Refactor code to provide better tree shaking and minification of generated code #1076 (#1811)

- Add Automatic Name replacing / Crunching
This commit is contained in:
Nev 2022-06-30 13:02:13 -07:00 коммит произвёл GitHub
Родитель 30e4518760
Коммит 0c76d710a0
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: 4AEE18F83AFDEB23
131 изменённых файлов: 5266 добавлений и 3206 удалений

64
.aiAutoMinify.json Normal file
Просмотреть файл

@ -0,0 +1,64 @@
{
"pkgs": {
"@microsoft/applicationinsights-core-js": {
"constEnums": [
"CallbackType",
"eEventsDiscardedReason",
"eLoggingSeverity",
"_eInternalMessageId",
"SendRequestReason",
"TelemetryUnloadReason",
"TelemetryUpdateReason",
"GetExtCfgMergeType"
]
},
"@microsoft/applicationinsights-perfmarkmeasure-js": {
"constEnums": []
},
"@microsoft/applicationinsights-common": {
"constEnums": [
"eStorageType",
"FieldType",
"eDistributedTracingModes",
"eRequestHeaders",
"DataPointType",
"DependencyKind",
"DependencySourceType",
"eSeverityLevel",
"DataSanitizerValues"
]
},
"@microsoft/applicationinsights-properties-js": {
"constEnums": []
},
"@microsoft/applicationinsights-dependencies-js": {
"constEnums": []
},
"@microsoft/applicationinsights-debugplugin-js": {
"constEnums": []
},
"@microsoft/applicationinsights-channel-js": {
"constEnums": []
},
"@microsoft/applicationinsights-react-native": {
"constEnums": []
},
"@microsoft/applicationinsights-clickanalytics-js": {
"constEnums": [
"_eExtendedInternalMessageId"
]
},
"@microsoft/applicationinsights-web-basic": {
"constEnums": []
},
"@microsoft/applicationinsights-analytics-js": {
"constEnums": []
},
"@microsoft/applicationinsights-web": {
"constEnums": []
},
"@microsoft/applicationinsights-react-js": {
"constEnums": []
}
}
}

3
.gitignore поставляемый
Просмотреть файл

@ -263,3 +263,6 @@ aicore.tests.d.ts
ai.tests.d.ts
/.vs
/index.html
# Generated Constant File
**/__DynamicConstants.ts

Просмотреть файл

@ -4,7 +4,10 @@ import * as pako from "pako";
import { Snippet } from "../../../src/Initialization";
export class AISKUSizeCheck extends AITestClass {
private readonly MAX_DEFLATE_SIZE = 44;
private readonly MAX_RAW_SIZE = 118;
private readonly MAX_BUNDLE_SIZE = 118;
private readonly MAX_RAW_DEFLATE_SIZE = 46;
private readonly MAX_BUNDLE_DEFLATE_SIZE = 47;
private readonly rawFilePath = "../dist/applicationinsights-web.min.js";
private readonly prodFilePath = "../browser/ai.2.min.js";
@ -50,6 +53,8 @@ export class AISKUSizeCheck extends AITestClass {
private _checkFileSize(isProd: boolean): void {
let _filePath = isProd? this.prodFilePath : this.rawFilePath;
let _maxFullSize = isProd ? this.MAX_BUNDLE_SIZE : this.MAX_RAW_SIZE;
let _maxDeflateSize = isProd ? this.MAX_BUNDLE_DEFLATE_SIZE : this.MAX_RAW_DEFLATE_SIZE;
let postfix = isProd? "" : "-raw";
let fileName = _filePath.split("..")[2];
this.testCase({
@ -63,8 +68,10 @@ export class AISKUSizeCheck extends AITestClass {
return;
} else {
return response.text().then(text => {
let size = Math.ceil((pako.deflate(text).length/1024) * 100) / 100.0;
Assert.ok(size <= this.MAX_DEFLATE_SIZE ,`max ${this.MAX_DEFLATE_SIZE} KB, current deflate size is: ${size} KB`);
let size = Math.ceil((text.length/1024) * 100) / 100.0;
Assert.ok(size <= _maxFullSize, `max ${_maxFullSize} KB, current deflate size is: ${size} KB`);
let deflateSize = Math.ceil((pako.deflate(text).length/1024) * 100) / 100.0;
Assert.ok(deflateSize <= _maxDeflateSize ,`max ${_maxDeflateSize} KB, current deflate size is: ${deflateSize} KB`);
}).catch((error: Error) => {
Assert.ok(false, `AISKU${postfix} response error: ${error}`);
});

Просмотреть файл

@ -20,10 +20,13 @@
"build:snippet": "grunt snippetvnext",
"rebuild": "npm run build",
"test": "grunt aiskuunittests",
"mintest": "grunt aisku-mintests",
"perftest": "grunt aiskuperf",
"lint": "tslint -p tsconfig.json",
"dtsgen": "api-extractor run --local && node ../scripts/dtsgen.js 'Microsoft.ApplicationInsights'",
"sri": "node ../tools/subResourceIntegrity/generateIntegrityFile.js",
"ai-min": "grunt aisku-min",
"ai-restore": "grunt aisku-restore",
"nightwatch:chrome": "nightwatch -c Tests/nightwatch/nightwatch.json Tests/nightwatch/run_nightwatch.js --env chrome",
"nightwatch:firefox": "nightwatch -c Tests/nightwatch/nightwatch.json Tests/nightwatch/run_nightwatch.js --env firefox",
"nightwatch:edge": "nightwatch -c Tests/nightwatch/nightwatch.json Tests/nightwatch/run_nightwatch.js --env edge",

Просмотреть файл

@ -1,6 +1,6 @@
import { IAppInsightsDeprecated, AppInsightsDeprecated } from "./ApplicationInsightsDeprecated";
import { Initialization as ApplicationInsights, Snippet, IApplicationInsights } from "./Initialization";
import { _legacyCookieMgr } from "@microsoft/applicationinsights-core-js";
import { AppInsightsDeprecated, IAppInsightsDeprecated } from "./ApplicationInsightsDeprecated";
import { IApplicationInsights, Initialization as ApplicationInsights, Snippet } from "./Initialization";
export class ApplicationInsightsContainer {

Просмотреть файл

@ -1,79 +1,219 @@
import dynamicProto from "@microsoft/dynamicproto-js";
import {
IConfig, SeverityLevel, stringToBoolOrDefault,
IPageViewTelemetry, ITraceTelemetry, IMetricTelemetry,
IAutoExceptionTelemetry, IDependencyTelemetry, IExceptionTelemetry,
IEventTelemetry, IEnvelope, ProcessLegacy
DEFAULT_BREEZE_ENDPOINT, DEFAULT_BREEZE_PATH, IAutoExceptionTelemetry, IConfig, IDependencyTelemetry, IEnvelope, IEventTelemetry,
IExceptionTelemetry, IMetricTelemetry, IPageViewTelemetry, ITraceTelemetry, ProcessLegacy, SeverityLevel, stringToBoolOrDefault
} from "@microsoft/applicationinsights-common";
import { Snippet, Initialization as ApplicationInsights } from "./Initialization";
import { ITelemetryItem, IDiagnosticLogger, IConfiguration, proxyAssign, throwError, ICookieMgr, arrIndexOf } from "@microsoft/applicationinsights-core-js";
import {
IConfiguration, ICookieMgr, IDiagnosticLogger, ITelemetryItem, arrIndexOf, isFunction, proxyAssign, proxyFunctions, throwError
} from "@microsoft/applicationinsights-core-js";
import { DfltAjaxCorrelationHeaderExDomains } from "@microsoft/applicationinsights-dependencies-js";
import { Initialization as ApplicationInsights, Snippet } from "./Initialization";
import {
STR_FLUSH, STR_GET_COOKIE_MGR, STR_SNIPPET, STR_START_TRACK_EVENT, STR_START_TRACK_PAGE, STR_STOP_TRACK_EVENT, STR_STOP_TRACK_PAGE
} from "./InternalConstants";
// This is an exclude list of properties that should not be updated during initialization
// They include a combination of private and internal property names
const _ignoreUpdateSnippetProperties = [
"snippet", "getDefaultConfig", "_hasLegacyInitializers", "_queue", "_processLegacyInitializers"
STR_SNIPPET, "getDefaultConfig", "_hasLegacyInitializers", "_queue", "_processLegacyInitializers"
];
// ToDo: fix properties and measurements once updates are done to common
function getDefaultConfig(config?: any): any {
if (!config) {
config = ({} as any);
}
// set default values
config.endpointUrl = config.endpointUrl || DEFAULT_BREEZE_ENDPOINT + DEFAULT_BREEZE_PATH;
config.sessionRenewalMs = 30 * 60 * 1000;
config.sessionExpirationMs = 24 * 60 * 60 * 1000;
config.maxBatchSizeInBytes = config.maxBatchSizeInBytes > 0 ? config.maxBatchSizeInBytes : 102400; // 100kb
config.maxBatchInterval = !isNaN(config.maxBatchInterval) ? config.maxBatchInterval : 15000;
config.enableDebug = stringToBoolOrDefault(config.enableDebug);
config.disableExceptionTracking = stringToBoolOrDefault(config.disableExceptionTracking);
config.disableTelemetry = stringToBoolOrDefault(config.disableTelemetry);
config.verboseLogging = stringToBoolOrDefault(config.verboseLogging);
config.emitLineDelimitedJson = stringToBoolOrDefault(config.emitLineDelimitedJson);
config.diagnosticLogInterval = config.diagnosticLogInterval || 10000;
config.autoTrackPageVisitTime = stringToBoolOrDefault(config.autoTrackPageVisitTime);
if (isNaN(config.samplingPercentage) || config.samplingPercentage <= 0 || config.samplingPercentage >= 100) {
config.samplingPercentage = 100;
}
config.disableAjaxTracking = stringToBoolOrDefault(config.disableAjaxTracking);
config.maxAjaxCallsPerView = !isNaN(config.maxAjaxCallsPerView) ? config.maxAjaxCallsPerView : 500;
config.isBeaconApiDisabled = stringToBoolOrDefault(config.isBeaconApiDisabled, true);
config.disableCorrelationHeaders = stringToBoolOrDefault(config.disableCorrelationHeaders);
config.correlationHeaderExcludedDomains = config.correlationHeaderExcludedDomains || DfltAjaxCorrelationHeaderExDomains;
config.disableFlushOnBeforeUnload = stringToBoolOrDefault(config.disableFlushOnBeforeUnload);
config.disableFlushOnUnload = stringToBoolOrDefault(config.disableFlushOnUnload, config.disableFlushOnBeforeUnload);
config.enableSessionStorageBuffer = stringToBoolOrDefault(config.enableSessionStorageBuffer, true);
config.isRetryDisabled = stringToBoolOrDefault(config.isRetryDisabled);
config.isCookieUseDisabled = stringToBoolOrDefault(config.isCookieUseDisabled);
config.isStorageUseDisabled = stringToBoolOrDefault(config.isStorageUseDisabled);
config.isBrowserLinkTrackingEnabled = stringToBoolOrDefault(config.isBrowserLinkTrackingEnabled);
config.enableCorsCorrelation = stringToBoolOrDefault(config.enableCorsCorrelation);
return config;
}
export class AppInsightsDeprecated implements IAppInsightsDeprecated {
private static getDefaultConfig(config?: any): any {
if (!config) {
config = ({} as any);
}
// set default values
config.endpointUrl = config.endpointUrl || "https://dc.services.visualstudio.com/v2/track";
config.sessionRenewalMs = 30 * 60 * 1000;
config.sessionExpirationMs = 24 * 60 * 60 * 1000;
config.maxBatchSizeInBytes = config.maxBatchSizeInBytes > 0 ? config.maxBatchSizeInBytes : 102400; // 100kb
config.maxBatchInterval = !isNaN(config.maxBatchInterval) ? config.maxBatchInterval : 15000;
config.enableDebug = stringToBoolOrDefault(config.enableDebug);
config.disableExceptionTracking = stringToBoolOrDefault(config.disableExceptionTracking);
config.disableTelemetry = stringToBoolOrDefault(config.disableTelemetry);
config.verboseLogging = stringToBoolOrDefault(config.verboseLogging);
config.emitLineDelimitedJson = stringToBoolOrDefault(config.emitLineDelimitedJson);
config.diagnosticLogInterval = config.diagnosticLogInterval || 10000;
config.autoTrackPageVisitTime = stringToBoolOrDefault(config.autoTrackPageVisitTime);
if (isNaN(config.samplingPercentage) || config.samplingPercentage <= 0 || config.samplingPercentage >= 100) {
config.samplingPercentage = 100;
}
config.disableAjaxTracking = stringToBoolOrDefault(config.disableAjaxTracking);
config.maxAjaxCallsPerView = !isNaN(config.maxAjaxCallsPerView) ? config.maxAjaxCallsPerView : 500;
config.isBeaconApiDisabled = stringToBoolOrDefault(config.isBeaconApiDisabled, true);
config.disableCorrelationHeaders = stringToBoolOrDefault(config.disableCorrelationHeaders);
config.correlationHeaderExcludedDomains = config.correlationHeaderExcludedDomains || [
"*.blob.core.windows.net",
"*.blob.core.chinacloudapi.cn",
"*.blob.core.cloudapi.de",
"*.blob.core.usgovcloudapi.net"];
config.disableFlushOnBeforeUnload = stringToBoolOrDefault(config.disableFlushOnBeforeUnload);
config.disableFlushOnUnload = stringToBoolOrDefault(config.disableFlushOnUnload, config.disableFlushOnBeforeUnload);
config.enableSessionStorageBuffer = stringToBoolOrDefault(config.enableSessionStorageBuffer, true);
config.isRetryDisabled = stringToBoolOrDefault(config.isRetryDisabled);
config.isCookieUseDisabled = stringToBoolOrDefault(config.isCookieUseDisabled);
config.isStorageUseDisabled = stringToBoolOrDefault(config.isStorageUseDisabled);
config.isBrowserLinkTrackingEnabled = stringToBoolOrDefault(config.isBrowserLinkTrackingEnabled);
config.enableCorsCorrelation = stringToBoolOrDefault(config.enableCorsCorrelation);
return config;
}
public config: IConfig & IConfiguration;
public snippet: Snippet;
public context: ITelemetryContext;
public logger: IDiagnosticLogger;
queue: Array<() => void>;
private appInsightsNew: ApplicationInsights;
private _hasLegacyInitializers = false;
private _queue: Array<((env: IEnvelope) => boolean | void)> = [];
public queue: Array<() => void>;
public appInsightsNew: ApplicationInsights;
constructor(snippet: Snippet, appInsightsNew: ApplicationInsights) {
this.config = AppInsightsDeprecated.getDefaultConfig(snippet.config);
this.appInsightsNew = appInsightsNew;
this.context = { addTelemetryInitializer: this.addTelemetryInitializers.bind(this) }
let _hasLegacyInitializers = false;
let _queue: Array<((env: IEnvelope) => boolean | void)> = [];
let _config: IConfiguration;
dynamicProto(AppInsightsDeprecated, this, (_self) => {
_config = getDefaultConfig(snippet.config);
_self.config = _config;
_self.snippet = snippet;
_self.appInsightsNew = appInsightsNew;
_self.context = { addTelemetryInitializer: _addTelemetryInitializers.bind(_self) };
_self.addTelemetryInitializers = _addTelemetryInitializers;
function _addTelemetryInitializers(callBack: (env: IEnvelope) => boolean | void) {
// Add initializer to current processing only if there is any old telemetry initializer
if (!_hasLegacyInitializers) {
appInsightsNew.addTelemetryInitializer(item => {
_processLegacyInitializers(item); // setup call back for each legacy processor
})
_hasLegacyInitializers = true;
}
_queue.push(callBack);
}
proxyFunctions(_self, appInsightsNew, [
STR_GET_COOKIE_MGR,
STR_START_TRACK_PAGE,
STR_STOP_TRACK_PAGE,
STR_FLUSH,
STR_START_TRACK_EVENT,
STR_STOP_TRACK_EVENT
]);
_self.trackPageView = (name?: string, url?: string, properties?: {[key: string]: string }, measurements?: {[key: string]: number }, duration?: number) => {
const telemetry: IPageViewTelemetry = {
name,
uri: url,
properties,
measurements
};
// fix for props, measurements, duration
appInsightsNew.trackPageView(telemetry);
};
_self.trackEvent = (name: string, properties?: Object, measurements?: Object) => {
appInsightsNew.trackEvent({ name} as IEventTelemetry);
};
_self.trackDependency = (id: string, method: string, absoluteUrl: string, pathName: string, totalTime: number, success: boolean, resultCode: number) => {
appInsightsNew.trackDependencyData(
{
id,
target: absoluteUrl,
type: pathName,
duration: totalTime,
properties: { HttpMethod: method },
success,
responseCode: resultCode
} as IDependencyTelemetry);
};
_self.trackException = (exception: Error, handledAt?: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }, severityLevel?: any) => {
appInsightsNew.trackException({
exception
} as IExceptionTelemetry);
};
_self.trackMetric = (name: string, average: number, sampleCount?: number, min?: number, max?: number, properties?: { [name: string]: string; }) => {
appInsightsNew.trackMetric({name, average, sampleCount, min, max} as IMetricTelemetry);
};
_self.trackTrace = (message: string, properties?: { [name: string]: string; }, severityLevel?: any) => {
appInsightsNew.trackTrace({ message, severityLevel } as ITraceTelemetry);
};
_self.setAuthenticatedUserContext = (authenticatedUserId: string, accountId?: string, storeInCookie?: boolean) => {
appInsightsNew.context.user.setAuthenticatedUserContext(authenticatedUserId, accountId, storeInCookie);
};
_self.clearAuthenticatedUserContext = () => {
appInsightsNew.context.user.clearAuthenticatedUserContext();
};
_self._onerror = (message: string, url: string, lineNumber: number, columnNumber: number, error: Error) => {
appInsightsNew._onerror({ message, url, lineNumber, columnNumber, error } as IAutoExceptionTelemetry);
};
_self.downloadAndSetup = (config: IConfig): void => {
throwError("downloadAndSetup not implemented in web SKU");
};
_self.updateSnippetDefinitions = (snippet: Snippet) => {
// apply full appInsights to the global instance
// Note: This must be called before loadAppInsights is called
proxyAssign(snippet, this, (name: string) => {
// Not excluding names prefixed with "_" as we need to proxy some functions like _onError
return name && arrIndexOf(_ignoreUpdateSnippetProperties, name) === -1;
});
};
// note: these are split into methods to enable unit tests
_self.loadAppInsights = () => {
// initialize global instance of appInsights
// var appInsights = new Microsoft.ApplicationInsights.AppInsights(_self.config);
// implement legacy version of trackPageView for 0.10<
if (_self.config["iKey"]) {
const originalTrackPageView = _self.trackPageView;
_self.trackPageView = (pagePath?: string, properties?: Object, measurements?: Object) => {
originalTrackPageView.apply(_self, [null, pagePath, properties, measurements]);
}
}
// implement legacy pageView interface if it is present in the snippet
const legacyPageView = "logPageView";
if (isFunction(_self.snippet[legacyPageView])) {
this[legacyPageView] = (pagePath?: string, properties?: {[key: string]: string }, measurements?: {[key: string]: number }) => {
_self.trackPageView(null, pagePath, properties, measurements);
}
}
// implement legacy event interface if it is present in the snippet
const legacyEvent = "logEvent";
if (isFunction(_self.snippet[legacyEvent])) {
this[legacyEvent] = (name: string, props?: Object, measurements?: Object) => {
_self.trackEvent(name, props, measurements);
}
}
return this;
};
function _processLegacyInitializers(item: ITelemetryItem): ITelemetryItem {
// instead of mapping new to legacy and then back again and repeating in channel, attach callback for channel to call
item.tags[ProcessLegacy] = _queue;
return item;
}
});
}
/**
@ -81,154 +221,84 @@ export class AppInsightsDeprecated implements IAppInsightsDeprecated {
*/
public addTelemetryInitializers(callBack: (env: IEnvelope) => boolean | void) {
// Add initializer to current processing only if there is any old telemetry initializer
if (!this._hasLegacyInitializers) {
this.appInsightsNew.addTelemetryInitializer(item => {
this._processLegacyInitializers(item); // setup call back for each legacy processor
})
this._hasLegacyInitializers = true;
}
this._queue.push(callBack);
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
/**
* Get the current cookie manager for this instance
*/
public getCookieMgr(): ICookieMgr {
return this.appInsightsNew.getCookieMgr();
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
return null;
}
startTrackPage(name?: string) {
this.appInsightsNew.startTrackPage(name);
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
stopTrackPage(name?: string, url?: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }) {
this.appInsightsNew.stopTrackPage(name, url, properties); // update
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
trackPageView(name?: string, url?: string, properties?: {[key: string]: string }, measurements?: {[key: string]: number }, duration?: number) {
const telemetry: IPageViewTelemetry = {
name,
uri: url,
properties,
measurements
};
// fix for props, measurements, duration
this.appInsightsNew.trackPageView(telemetry);
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
trackEvent(name: string, properties?: Object, measurements?: Object) {
this.appInsightsNew.trackEvent({ name} as IEventTelemetry);
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
trackDependency(id: string, method: string, absoluteUrl: string, pathName: string, totalTime: number, success: boolean, resultCode: number) {
this.appInsightsNew.trackDependencyData(
{
id,
target: absoluteUrl,
type: pathName,
duration: totalTime,
properties: { HttpMethod: method },
success,
responseCode: resultCode
} as IDependencyTelemetry);
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
trackException(exception: Error, handledAt?: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }, severityLevel?: any) {
this.appInsightsNew.trackException({
exception
} as IExceptionTelemetry);
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
trackMetric(name: string, average: number, sampleCount?: number, min?: number, max?: number, properties?: { [name: string]: string; }) {
this.appInsightsNew.trackMetric({name, average, sampleCount, min, max} as IMetricTelemetry);
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
trackTrace(message: string, properties?: { [name: string]: string; }, severityLevel?: any) {
this.appInsightsNew.trackTrace({ message, severityLevel } as ITraceTelemetry);
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
flush(async?: boolean) {
this.appInsightsNew.flush(async);
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
setAuthenticatedUserContext(authenticatedUserId: string, accountId?: string, storeInCookie?: boolean) {
this.appInsightsNew.context.user.setAuthenticatedUserContext(authenticatedUserId, accountId, storeInCookie);
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
clearAuthenticatedUserContext() {
this.appInsightsNew.context.user.clearAuthenticatedUserContext();
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
_onerror(message: string, url: string, lineNumber: number, columnNumber: number, error: Error) {
this.appInsightsNew._onerror({ message, url, lineNumber, columnNumber, error } as IAutoExceptionTelemetry);
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
startTrackEvent(name: string) {
this.appInsightsNew.startTrackEvent(name);
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
stopTrackEvent(name: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }) {
this.appInsightsNew.stopTrackEvent(name, properties, measurements);
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
downloadAndSetup?(config: IConfig): void {
throwError("downloadAndSetup not implemented in web SKU");
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
public updateSnippetDefinitions(snippet: Snippet) {
// apply full appInsights to the global instance
// Note: This must be called before loadAppInsights is called
proxyAssign(snippet, this, (name: string) => {
// Not excluding names prefixed with "_" as we need to proxy some functions like _onError
return name && arrIndexOf(_ignoreUpdateSnippetProperties, name) === -1;
});
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
// note: these are split into methods to enable unit tests
public loadAppInsights() {
// initialize global instance of appInsights
// var appInsights = new Microsoft.ApplicationInsights.AppInsights(this.config);
// implement legacy version of trackPageView for 0.10<
if (this.config["iKey"]) {
const originalTrackPageView = this.trackPageView;
this.trackPageView = (pagePath?: string, properties?: Object, measurements?: Object) => {
originalTrackPageView.apply(this, [null, pagePath, properties, measurements]);
}
}
// implement legacy pageView interface if it is present in the snippet
const legacyPageView = "logPageView";
if (typeof this.snippet[legacyPageView] === "function") {
this[legacyPageView] = (pagePath?: string, properties?: {[key: string]: string }, measurements?: {[key: string]: number }) => {
this.trackPageView(null, pagePath, properties, measurements);
}
}
// implement legacy event interface if it is present in the snippet
const legacyEvent = "logEvent";
if (typeof this.snippet[legacyEvent] === "function") {
this[legacyEvent] = (name: string, props?: Object, measurements?: Object) => {
this.trackEvent(name, props, measurements);
}
}
return this;
}
private _processLegacyInitializers(item: ITelemetryItem): ITelemetryItem {
// instead of mapping new to legacy and then back again and repeating in channel, attach callback for channel to call
item.tags[ProcessLegacy] = this._queue;
return item;
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
}
@ -249,7 +319,7 @@ export interface IAppInsightsDeprecated {
/**
* Get the current cookie manager for this instance
*/
getCookieMgr(): ICookieMgr;
getCookieMgr(): ICookieMgr;
/**
* Starts timing how long the user views a page or other item. Call this when the page opens.

Просмотреть файл

@ -1,9 +1,9 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import { Snippet } from "./Initialization";
import { ApplicationInsightsContainer } from "./ApplicationInsightsContainer";
import { strUndefined } from "@microsoft/applicationinsights-core-js";
import { ApplicationInsightsContainer } from "./ApplicationInsightsContainer";
import { Snippet } from "./Initialization";
// ----------------------------------------------------------------------------------------------------
// Exports available from the Cdn bundles

Просмотреть файл

@ -1,40 +1,47 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
"use strict";
import dynamicProto from "@microsoft/dynamicproto-js";
import {
IConfiguration, AppInsightsCore, IAppInsightsCore, eLoggingSeverity, _eInternalMessageId, ITelemetryItem, ICustomProperties,
IChannelControls, hasWindow, hasDocument, isReactNative, doPerf, IDiagnosticLogger, INotificationManager, objForEachKey, proxyAssign, proxyFunctions,
arrForEach, isString, isFunction, isNullOrUndefined, isArray, throwError, ICookieMgr, addPageUnloadEventListener, addPageHideEventListener,
createUniqueNamespace, ITelemetryPlugin, IPlugin, ILoadedPlugin, UnloadHandler, removePageUnloadEventListener, removePageHideEventListener,
ITelemetryInitializerHandler, ITelemetryUnloadState, mergeEvtNamespace, _throwInternal, arrIndexOf, IDistributedTraceContext
} from "@microsoft/applicationinsights-core-js";
import { AnalyticsPlugin, ApplicationInsights } from "@microsoft/applicationinsights-analytics-js";
import { Sender } from "@microsoft/applicationinsights-channel-js";
import { PropertiesPlugin } from "@microsoft/applicationinsights-properties-js";
import {
AnalyticsPluginIdentifier, BreezeChannelIdentifier, ConfigurationManager, ConnectionStringParser, ContextTagKeys, CorrelationIdHelper,
CtxTagKeys, DEFAULT_BREEZE_ENDPOINT, DEFAULT_BREEZE_PATH, Data, DataSanitizer, DateTimeUtils, DisabledPropertyName,
DistributedTracingModes, Envelope, Event, Exception, Extensions, FieldType, HttpMethod, IAppInsights, IAutoExceptionTelemetry, IConfig,
ICorrelationIdHelper, IDataSanitizer, IDateTimeUtils, IDependencyTelemetry, IEventTelemetry, IExceptionTelemetry, IMetricTelemetry,
IPageViewPerformanceTelemetry, IPageViewTelemetry, IPropertiesPlugin, IRequestHeaders, ITelemetryContext as Common_ITelemetryContext,
ITraceTelemetry, IUrlHelper, IUtil, Metric, PageView, PageViewPerformance, ProcessLegacy, PropertiesPluginIdentifier,
RemoteDependencyData, RequestHeaders, SampleRate, SeverityLevel, TelemetryItemCreator, Trace, UrlHelper, Util, parseConnectionString
} from "@microsoft/applicationinsights-common";
import {
AppInsightsCore, IAppInsightsCore, IChannelControls, IConfiguration, ICookieMgr, ICustomProperties, IDiagnosticLogger,
IDistributedTraceContext, ILoadedPlugin, INotificationManager, IPlugin, ITelemetryInitializerHandler, ITelemetryItem, ITelemetryPlugin,
ITelemetryUnloadState, UnloadHandler, _eInternalMessageId, _throwInternal, addPageHideEventListener, addPageUnloadEventListener,
arrForEach, arrIndexOf, createUniqueNamespace, doPerf, eLoggingSeverity, hasDocument, hasWindow, isArray, isFunction, isNullOrUndefined,
isReactNative, isString, mergeEvtNamespace, objForEachKey, proxyAssign, proxyFunctions, removePageHideEventListener,
removePageUnloadEventListener, throwError
} from "@microsoft/applicationinsights-core-js";
import { AjaxPlugin as DependenciesPlugin, IDependenciesPlugin } from "@microsoft/applicationinsights-dependencies-js";
import {
IUtil, Util, ICorrelationIdHelper, CorrelationIdHelper, IUrlHelper, UrlHelper, IDateTimeUtils, DateTimeUtils, ConnectionStringParser, FieldType,
IRequestHeaders, RequestHeaders, DisabledPropertyName, ProcessLegacy, SampleRate, HttpMethod, DEFAULT_BREEZE_ENDPOINT,
Envelope, Event, Exception, Metric, PageView, RemoteDependencyData, IEventTelemetry,
ITraceTelemetry, IMetricTelemetry, IDependencyTelemetry, IExceptionTelemetry, IAutoExceptionTelemetry,
IPageViewTelemetry, IPageViewPerformanceTelemetry, Trace, PageViewPerformance, Data, SeverityLevel,
IConfig, ConfigurationManager, ContextTagKeys, IDataSanitizer, DataSanitizer, TelemetryItemCreator, IAppInsights, CtxTagKeys, Extensions,
IPropertiesPlugin, DistributedTracingModes, PropertiesPluginIdentifier, BreezeChannelIdentifier, AnalyticsPluginIdentifier,
ITelemetryContext as Common_ITelemetryContext, parseConnectionString
} from "@microsoft/applicationinsights-common"
import { DependencyListenerFunction, IDependencyListenerHandler } from "@microsoft/applicationinsights-dependencies-js/types/DependencyListener";
DependencyListenerFunction, IDependencyListenerHandler
} from "@microsoft/applicationinsights-dependencies-js/types/DependencyListener";
import { PropertiesPlugin } from "@microsoft/applicationinsights-properties-js";
import {
STR_ADD_TELEMETRY_INITIALIZER, STR_CLEAR_AUTHENTICATED_USER_CONTEXT, STR_EVT_NAMESPACE, STR_GET_COOKIE_MGR, STR_GET_PLUGIN,
STR_POLL_INTERNAL_LOGS, STR_SET_AUTHENTICATED_USER_CONTEXT, STR_SNIPPET, STR_START_TRACK_EVENT, STR_START_TRACK_PAGE,
STR_STOP_TRACK_EVENT, STR_STOP_TRACK_PAGE, STR_TRACK_DEPENDENCY_DATA, STR_TRACK_EVENT, STR_TRACK_EXCEPTION, STR_TRACK_METRIC,
STR_TRACK_PAGE_VIEW, STR_TRACK_TRACE
} from "./InternalConstants";
export { IUtil, ICorrelationIdHelper, IUrlHelper, IDateTimeUtils, IRequestHeaders };
"use strict";
let _internalSdkSrc: string;
// This is an exclude list of properties that should not be updated during initialization
// They include a combination of private and internal property names
const _ignoreUpdateSnippetProperties = [
"snippet", "dependencies", "properties", "_snippetVersion", "appInsightsNew", "getSKUDefaults"
STR_SNIPPET, "dependencies", "properties", "_snippetVersion", "appInsightsNew", "getSKUDefaults"
];
/**
@ -178,7 +185,7 @@ export class Initialization implements IApplicationInsights {
if (config.connectionString) {
const cs = parseConnectionString(config.connectionString);
const ingest = cs.ingestionendpoint;
config.endpointUrl = ingest ? `${ingest}/v2/track` : config.endpointUrl; // only add /v2/track when from connectionstring
config.endpointUrl = ingest ? (ingest + DEFAULT_BREEZE_PATH) : config.endpointUrl; // only add /v2/track when from connectionstring
config.instrumentationKey = cs.instrumentationkey || config.instrumentationKey;
}
@ -257,7 +264,7 @@ export class Initialization implements IApplicationInsights {
}
doPerf(_self.core, () => "AISKU.loadAppInsights", () => {
const extensions = [];
const extensions: any[] = [];
extensions.push(_sender);
extensions.push(properties);
@ -399,32 +406,32 @@ export class Initialization implements IApplicationInsights {
};
proxyFunctions(_self, _self.appInsights, [
"getCookieMgr",
"trackEvent",
"trackPageView",
STR_GET_COOKIE_MGR,
STR_TRACK_EVENT,
STR_TRACK_PAGE_VIEW,
"trackPageViewPerformance",
"trackException",
STR_TRACK_EXCEPTION,
"_onerror",
"trackTrace",
"trackMetric",
"startTrackPage",
"stopTrackPage",
"startTrackEvent",
"stopTrackEvent"
STR_TRACK_TRACE,
STR_TRACK_METRIC,
STR_START_TRACK_PAGE,
STR_STOP_TRACK_PAGE,
STR_START_TRACK_EVENT,
STR_STOP_TRACK_EVENT
]);
proxyFunctions(_self, _getCurrentDependencies, [
"trackDependencyData",
STR_TRACK_DEPENDENCY_DATA,
"addDependencyListener"
]);
proxyFunctions(_self, _core, [
"addTelemetryInitializer",
"pollInternalLogs",
STR_ADD_TELEMETRY_INITIALIZER,
STR_POLL_INTERNAL_LOGS,
"stopPollingInternalLogs",
"getPlugin",
STR_GET_PLUGIN,
"addPlugin",
"evtNamespace",
STR_EVT_NAMESPACE,
"addUnloadCb",
"getTraceCtx"
]);
@ -433,8 +440,8 @@ export class Initialization implements IApplicationInsights {
let context = properties.context;
return context ? context.user : null;
}, [
"setAuthenticatedUserContext",
"clearAuthenticatedUserContext"
STR_SET_AUTHENTICATED_USER_CONTEXT,
STR_CLEAR_AUTHENTICATED_USER_CONTEXT
]);

Просмотреть файл

@ -0,0 +1,33 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// Note: DON'T Export these const from the package as we are still targeting ES3 this will export a mutable variables that someone could change!!!
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// Generally you should only put values that are used more than 2 times and then only if not already exposed as a constant (such as SdkCoreNames)
// as when using "short" named values from here they will be will be minified smaller than the SdkCoreNames[eSdkCoreNames.xxxx] value.
const _AUTHENTICATED_USER_CONTEXT = "AuthenticatedUserContext";
const _TRACK = "track";
export const STR_EMPTY = "";
export const STR_SNIPPET = "snippet";
export const STR_GET_COOKIE_MGR = "getCookieMgr";
export const STR_START_TRACK_PAGE = "startTrackPage";
export const STR_STOP_TRACK_PAGE = "stopTrackPage";
export const STR_FLUSH = "flush";
export const STR_START_TRACK_EVENT = "startTrackEvent";
export const STR_STOP_TRACK_EVENT = "stopTrackEvent";
export const STR_ADD_TELEMETRY_INITIALIZER = "addTelemetryInitializer";
export const STR_ADD_TELEMETRY_INITIALIZERS = STR_ADD_TELEMETRY_INITIALIZER + "s" as "addTelemetryInitializers";
export const STR_POLL_INTERNAL_LOGS = "pollInternalLogs";
export const STR_GET_PLUGIN = "getPlugin";
export const STR_EVT_NAMESPACE = "evtNamespace";
export const STR_TRACK_EVENT = _TRACK + "Event" as "trackEvent";
export const STR_TRACK_TRACE = _TRACK + "Trace" as "trackTrace";
export const STR_TRACK_METRIC = _TRACK + "Metric" as "trackMetric";
export const STR_TRACK_PAGE_VIEW = _TRACK + "PageView" as "trackPageView";
export const STR_TRACK_EXCEPTION = _TRACK + "Exception" as "trackException";
export const STR_TRACK_DEPENDENCY_DATA = _TRACK + "DependencyData" as "trackDependencyData";
export const STR_SET_AUTHENTICATED_USER_CONTEXT = "set" + _AUTHENTICATED_USER_CONTEXT as "setAuthenticatedUserContext";
export const STR_CLEAR_AUTHENTICATED_USER_CONTEXT = "clear" + _AUTHENTICATED_USER_CONTEXT as "clearAuthenticatedUserContext";

Просмотреть файл

@ -2,7 +2,10 @@ import { AITestClass, Assert } from "@microsoft/ai-test-framework";
import * as pako from "pako";
export class AISKULightSizeCheck extends AITestClass {
private readonly MAX_DEFLATE_SIZE = 27;
private readonly MAX_RAW_SIZE = 70;
private readonly MAX_BUNDLE_SIZE = 70;
private readonly MAX_RAW_DEFLATE_SIZE = 28;
private readonly MAX_BUNDLE_DEFLATE_SIZE = 28;
private readonly rawFilePath = "../dist/applicationinsights-web-basic.min.js";
private readonly prodFilePath = "../browser/aib.2.min.js";
@ -31,6 +34,8 @@ export class AISKULightSizeCheck extends AITestClass {
private _checkFileSize(isProd: boolean): void {
let _filePath = isProd? this.prodFilePath : this.rawFilePath;
let _maxFullSize = isProd ? this.MAX_BUNDLE_SIZE : this.MAX_RAW_SIZE;
let _maxDeflateSize = isProd ? this.MAX_BUNDLE_DEFLATE_SIZE : this.MAX_RAW_DEFLATE_SIZE;
let postfix = isProd? "" : "-raw";
let fileName = _filePath.split("..")[2];
this.testCase({
@ -44,8 +49,10 @@ export class AISKULightSizeCheck extends AITestClass {
return;
} else {
return response.text().then(text => {
let size = Math.ceil((pako.deflate(text).length/1024) * 100) / 100.0;
Assert.ok(size <= this.MAX_DEFLATE_SIZE ,`max ${this.MAX_DEFLATE_SIZE} KB, current deflate size is: ${size} KB`);
let size = Math.ceil((text.length/1024) * 100) / 100.0;
Assert.ok(size <= _maxFullSize, `max ${_maxFullSize} KB, current deflate size is: ${size} KB`);
let deflateSize = Math.ceil((pako.deflate(text).length/1024) * 100) / 100.0;
Assert.ok(deflateSize <= _maxDeflateSize ,`max ${_maxDeflateSize} KB, current deflate size is: ${deflateSize} KB`);
}).catch((error: Error) => {
Assert.ok(false, `AISKULight${postfix} response error: ${error}`);
});

Просмотреть файл

@ -14,9 +14,12 @@
"build:browser": "rollup -c rollup.config.js",
"rebuild": "npm run build",
"test": "grunt aiskuliteunittests",
"mintest": "grunt aiskulite-mintests",
"lint": "tslint -p tsconfig.json",
"dtsgen": "api-extractor run --local && node ../scripts/dtsgen.js 'Microsoft.ApplicationInsights'",
"sri": "node ../tools/subResourceIntegrity/generateIntegrityFile.js"
"sri": "node ../tools/subResourceIntegrity/generateIntegrityFile.js",
"ai-min": "grunt aiskulite-min",
"ai-restore": "grunt aiskulite-restore"
},
"repository": {
"type": "git",

Просмотреть файл

@ -2,21 +2,12 @@
// Licensed under the MIT License.
import dynamicProto from "@microsoft/dynamicproto-js";
import {
IConfiguration,
AppInsightsCore,
_InternalMessageId,
isNullOrUndefined,
ITelemetryItem,
throwError,
proxyFunctions,
UnloadHandler,
IPlugin,
ITelemetryPlugin,
ILoadedPlugin
} from "@microsoft/applicationinsights-core-js";
import { IConfig } from "@microsoft/applicationinsights-common";
import { Sender } from "@microsoft/applicationinsights-channel-js";
import { IConfig } from "@microsoft/applicationinsights-common";
import {
AppInsightsCore, IConfiguration, ILoadedPlugin, IPlugin, ITelemetryItem, ITelemetryPlugin, UnloadHandler, _InternalMessageId,
_eInternalMessageId, isNullOrUndefined, proxyFunctions, throwError
} from "@microsoft/applicationinsights-core-js";
/**
* @export
@ -201,4 +192,4 @@ export {
IPageViewPerformanceTelemetry,
ITraceTelemetry
} from "@microsoft/applicationinsights-common";
export { Sender } from "@microsoft/applicationinsights-channel-js";
export { Sender } from "@microsoft/applicationinsights-channel-js";

Просмотреть файл

@ -1280,7 +1280,6 @@ export class SenderTests extends AITestClass {
let appInsightsCore = new AppInsightsCore();
appInsightsCore.logger = new DiagnosticLogger();
let messageId: _InternalMessageId = _InternalMessageId.InvalidInstrumentationKey;
let logInternalSpy = this.sandbox.spy(appInsightsCore.logger, 'logInternalMessage');
this._sender.initialize(
{
instrumentationKey: '1aa11111-bbbb-1ccc-8ddd-eeeeffff3333',
@ -1296,14 +1295,12 @@ export class SenderTests extends AITestClass {
}, appInsightsCore, []
);
QUnit.assert.equal(false,logInternalSpy.calledOnce, 'valid Ikey test-1');
QUnit.assert.equal(0, appInsightsCore.logger.queue.length, "POST: No messageId logged");
this._sender.teardown();
appInsightsCore = new AppInsightsCore();
appInsightsCore.logger = new DiagnosticLogger();
messageId = _InternalMessageId.InvalidInstrumentationKey;
logInternalSpy = this.sandbox.spy(appInsightsCore.logger, 'logInternalMessage');
this._sender.initialize(
{
instrumentationKey: '1aa11111bbbb1ccc8dddeeeeffff3333',
@ -1319,9 +1316,6 @@ export class SenderTests extends AITestClass {
}, appInsightsCore, []
);
QUnit.assert.ok(logInternalSpy.calledOnce, 'iKey Validation check -throwInternal called');
QUnit.assert.equal(messageId, logInternalSpy.args[0][1].messageId, "Correct message logged");
QUnit.assert.ok(logInternalSpy.args[0][1].message.indexOf('Invalid Instrumentation key') !== -1, "Correct message logged");
QUnit.assert.equal(1, appInsightsCore.logger.queue.length, "POST: Correct messageId logged");
QUnit.assert.ok(appInsightsCore.logger.queue[0].message.indexOf('Invalid Instrumentation key') !== -1, "Correct message logged");
QUnit.assert.equal(messageId, appInsightsCore.logger.queue[0].messageId, "Correct message logged");
@ -1330,7 +1324,6 @@ export class SenderTests extends AITestClass {
appInsightsCore = new AppInsightsCore();
appInsightsCore.logger = new DiagnosticLogger();
messageId = _InternalMessageId.InvalidInstrumentationKey;
logInternalSpy = this.sandbox.spy(appInsightsCore.logger, 'logInternalMessage');
this._sender.initialize(
{
instrumentationKey: 'abc',
@ -1346,9 +1339,6 @@ export class SenderTests extends AITestClass {
}, appInsightsCore, []
);
QUnit.assert.ok(logInternalSpy.calledOnce, 'iKey Validation check -throwInternal called');
QUnit.assert.equal(messageId, logInternalSpy.args[0][1].messageId, "Correct message logged");
QUnit.assert.ok(logInternalSpy.args[0][1].message.indexOf('Invalid Instrumentation key') !== -1, "Correct message logged");
QUnit.assert.equal(1, appInsightsCore.logger.queue.length, "POST: Correct messageId logged");
QUnit.assert.ok(appInsightsCore.logger.queue[0].message.indexOf('Invalid Instrumentation key') !== -1, "Correct message logged");
QUnit.assert.equal(messageId, appInsightsCore.logger.queue[0].messageId, "Correct message logged");
@ -1357,7 +1347,6 @@ export class SenderTests extends AITestClass {
appInsightsCore = new AppInsightsCore();
appInsightsCore.logger = new DiagnosticLogger();
messageId = _InternalMessageId.InvalidInstrumentationKey;
logInternalSpy = this.sandbox.spy(appInsightsCore.logger, 'logInternalMessage');
this._sender.initialize(
{
instrumentationKey: '',
@ -1373,9 +1362,6 @@ export class SenderTests extends AITestClass {
}, appInsightsCore, []
);
QUnit.assert.ok(logInternalSpy.calledOnce, 'iKey Validation check -throwInternal called');
QUnit.assert.equal(messageId, logInternalSpy.args[0][1].messageId, "Correct message logged");
QUnit.assert.ok(logInternalSpy.args[0][1].message.indexOf('Invalid Instrumentation key') !== -1, "Correct message logged");
QUnit.assert.equal(1, appInsightsCore.logger.queue.length, "POST: Correct messageId logged");
QUnit.assert.ok(appInsightsCore.logger.queue[0].message.indexOf('Invalid Instrumentation key') !== -1, "Correct message logged");
QUnit.assert.equal(messageId, appInsightsCore.logger.queue[0].messageId, "Correct message logged");
@ -1384,7 +1370,6 @@ export class SenderTests extends AITestClass {
appInsightsCore = new AppInsightsCore();
appInsightsCore.logger = new DiagnosticLogger();
messageId = _InternalMessageId.InvalidInstrumentationKey;
logInternalSpy = this.sandbox.spy(appInsightsCore.logger, 'logInternalMessage');
this._sender.initialize(
{
instrumentationKey: 'abc',
@ -1401,7 +1386,6 @@ export class SenderTests extends AITestClass {
}, appInsightsCore, []
);
QUnit.assert.equal(false,logInternalSpy.calledOnce, 'disableIKeyValidation flag set to yes');
QUnit.assert.equal(0, appInsightsCore.logger.queue.length, "POST: No messageId logged");
this._sender.teardown();
}

Просмотреть файл

@ -16,9 +16,12 @@
"build:browser": "rollup -c",
"rebuild": "npm run build",
"test": "grunt aichanneltest",
"mintest": "grunt aichannel-mintest",
"lint": "tslint -p tsconfig.json",
"dtsgen": "api-extractor run --local && node ../../scripts/dtsgen.js \"Microsoft Application Insights JavaScript SDK Channel\"",
"sri": "node ../../tools/subResourceIntegrity/generateIntegrityFile.js"
"sri": "node ../../tools/subResourceIntegrity/generateIntegrityFile.js",
"ai-min": "grunt aichannel-min",
"ai-restore": "grunt aichannel-restore"
},
"devDependencies": {
"@microsoft/ai-test-framework": "0.0.1",

Просмотреть файл

@ -1,17 +1,13 @@
import {
IEnvelope, Data, Envelope,
RemoteDependencyData, Event, Exception,
Metric, PageView, Trace, PageViewPerformance, IDependencyTelemetry,
IPageViewPerformanceTelemetry, CtxTagKeys,
HttpMethod, IPageViewTelemetryInternal, IWeb,
IExceptionInternal,
SampleRate,
dataSanitizeString
CtxTagKeys, Data, Envelope, Event, Exception, HttpMethod, IDependencyTelemetry, IEnvelope, IExceptionInternal,
IPageViewPerformanceTelemetry, IPageViewTelemetryInternal, IWeb, Metric, PageView, PageViewPerformance, RemoteDependencyData, SampleRate,
Trace, dataSanitizeString
} from "@microsoft/applicationinsights-common";
import {
ITelemetryItem, IDiagnosticLogger, eLoggingSeverity, _eInternalMessageId, hasJSON, getJSON, objForEachKey,
isNullOrUndefined, isNumber, isString, toISOString, setValue, isTruthy, optimizeObject, _throwInternal, _warnToConsole
IDiagnosticLogger, ITelemetryItem, _eInternalMessageId, _throwInternal, _warnToConsole, eLoggingSeverity, getJSON, hasJSON,
isNullOrUndefined, isNumber, isString, isTruthy, objForEachKey, optimizeObject, setValue, toISOString
} from "@microsoft/applicationinsights-core-js";
import { STR_DURATION } from "./InternalConstants";
// these two constants are used to filter out properties not needed when trying to extract custom properties and measurements from the incoming payload
const strBaseType = "baseType";
@ -175,7 +171,7 @@ function EnvelopeCreatorInit(logger: IDiagnosticLogger, telemetryItem: ITelemetr
}
export const EnvelopeCreator = {
Version: "2.8.4"
Version: "#version#"
};
export function DependencyEnvelopeCreator(logger: IDiagnosticLogger, telemetryItem: ITelemetryItem, customUndefinedValue?: any): IEnvelope {
@ -263,18 +259,17 @@ export function PageViewEnvelopeCreator(logger: IDiagnosticLogger, telemetryItem
EnvelopeCreatorInit(logger, telemetryItem);
// Since duration is not part of the domain properties in Common Schema, extract it from part C
let strDuration = "duration";
let duration;
let baseData = telemetryItem[strBaseData];
if (!isNullOrUndefined(baseData) &&
!isNullOrUndefined(baseData[strProperties]) &&
!isNullOrUndefined(baseData[strProperties][strDuration])) { // from part B properties
duration = baseData[strProperties][strDuration];
delete baseData[strProperties][strDuration];
!isNullOrUndefined(baseData[strProperties][STR_DURATION])) { // from part B properties
duration = baseData[strProperties][STR_DURATION];
delete baseData[strProperties][STR_DURATION];
} else if (!isNullOrUndefined(telemetryItem.data) &&
!isNullOrUndefined(telemetryItem.data[strDuration])) { // from custom properties
duration = telemetryItem.data[strDuration];
delete telemetryItem.data[strDuration];
!isNullOrUndefined(telemetryItem.data[STR_DURATION])) { // from custom properties
duration = telemetryItem.data[STR_DURATION];
delete telemetryItem.data[STR_DURATION];
}
const bd = telemetryItem[strBaseData] as IPageViewTelemetryInternal;
@ -353,4 +348,4 @@ export function TraceEnvelopeCreator(logger: IDiagnosticLogger, telemetryItem: I
const baseData = new Trace(logger, message, severityLevel, props, measurements);
const data = new Data<Trace>(Trace.dataType, baseData);
return _createEnvelope<Trace>(logger, Trace.envelopeType, telemetryItem, data);
}
}

Просмотреть файл

@ -0,0 +1,11 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// Note: DON'T Export these const from the package as we are still targeting ES3 this will export a mutable variables that someone could change!!!
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// Generally you should only put values that are used more than 2 times and then only if not already exposed as a constant (such as SdkCoreNames)
// as when using "short" named values from here they will be will be minified smaller than the SdkCoreNames[eSdkCoreNames.xxxx] value.
export const STR_DURATION = "duration";

Просмотреть файл

@ -1,4 +1,6 @@
import { getWindow, getDocument, getNavigator, isUndefined, isNullOrUndefined, createUniqueNamespace, mergeEvtNamespace, eventOn, eventOff } from "@microsoft/applicationinsights-core-js";
import {
createUniqueNamespace, eventOff, eventOn, getDocument, getNavigator, getWindow, isNullOrUndefined, isUndefined, mergeEvtNamespace
} from "@microsoft/applicationinsights-core-js";
export interface IOfflineListener {
isOnline: () => boolean;

Просмотреть файл

@ -1,7 +1,10 @@
import { utlGetSessionStorage, utlSetSessionStorage } from "@microsoft/applicationinsights-common";
import { IDiagnosticLogger, eLoggingSeverity, _eInternalMessageId, getJSON, arrForEach, isFunction, arrIndexOf, isString, dumpObj, isArray, getExceptionName, _throwInternal } from "@microsoft/applicationinsights-core-js";
import { ISenderConfig } from "./Interfaces";
import dynamicProto from "@microsoft/dynamicproto-js";
import { utlGetSessionStorage, utlSetSessionStorage } from "@microsoft/applicationinsights-common";
import {
IDiagnosticLogger, _eInternalMessageId, _throwInternal, arrForEach, arrIndexOf, dumpObj, eLoggingSeverity, getExceptionName, getJSON,
isArray, isFunction, isString
} from "@microsoft/applicationinsights-core-js";
import { ISenderConfig } from "./Interfaces";
export interface ISendBuffer {
/**
@ -341,4 +344,4 @@ export class SessionStorageSendBuffer extends BaseSendBuffer implements ISendBuf
public clearSent(payload: string[]) {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
}
}

Просмотреть файл

@ -1,29 +1,25 @@
import { ISenderConfig, XDomainRequest as IXDomainRequest, IBackendResponse } from "./Interfaces";
import { ISendBuffer, SessionStorageSendBuffer, ArraySendBuffer } from "./SendBuffer";
import dynamicProto from "@microsoft/dynamicproto-js";
import {
DependencyEnvelopeCreator, EventEnvelopeCreator,
ExceptionEnvelopeCreator, MetricEnvelopeCreator, PageViewEnvelopeCreator,
PageViewPerformanceEnvelopeCreator, TraceEnvelopeCreator
} from "./EnvelopeCreator";
import { Serializer } from "./Serializer"; // todo move to channel
import {
DisabledPropertyName, RequestHeaders, IEnvelope, PageView, Event,
Trace, Exception, Metric, PageViewPerformance, RemoteDependencyData,
IChannelControlsAI, IConfig, ProcessLegacy, BreezeChannelIdentifier,
SampleRate, isInternalApplicationInsightsEndpoint, utlCanUseSessionStorage,
ISample
BreezeChannelIdentifier, DEFAULT_BREEZE_ENDPOINT, DEFAULT_BREEZE_PATH, DisabledPropertyName, Event, Exception, IChannelControlsAI,
IConfig, IEnvelope, ISample, Metric, PageView, PageViewPerformance, ProcessLegacy, RemoteDependencyData, RequestHeaders, SampleRate,
Trace, eRequestHeaders, isInternalApplicationInsightsEndpoint, utlCanUseSessionStorage
} from "@microsoft/applicationinsights-common";
import {
ITelemetryItem, IProcessTelemetryContext, IConfiguration,
_eInternalMessageId, eLoggingSeverity, IDiagnosticLogger, IAppInsightsCore, IPlugin,
getWindow, getNavigator, getJSON, BaseTelemetryPlugin, ITelemetryPluginChain, INotificationManager,
SendRequestReason, objForEachKey, isNullOrUndefined, arrForEach, dateNow, dumpObj, getExceptionName, getIEVersion, objKeys,
isBeaconsSupported, isFetchSupported, useXDomainRequest, isXhrSupported, isArray, createUniqueNamespace, mergeEvtNamespace,
IProcessTelemetryUnloadContext, ITelemetryUnloadState, _throwInternal, _warnToConsole
BaseTelemetryPlugin, IAppInsightsCore, IConfiguration, IDiagnosticLogger, INotificationManager, IPlugin, IProcessTelemetryContext,
IProcessTelemetryUnloadContext, ITelemetryItem, ITelemetryPluginChain, ITelemetryUnloadState, SendRequestReason, _eInternalMessageId,
_throwInternal, _warnToConsole, arrForEach, createUniqueNamespace, dateNow, dumpObj, eLoggingSeverity, getExceptionName, getIEVersion,
getJSON, getNavigator, getWindow, isArray, isBeaconsSupported, isFetchSupported, isNullOrUndefined, isXhrSupported, mergeEvtNamespace,
objForEachKey, objKeys, useXDomainRequest
} from "@microsoft/applicationinsights-core-js";
import { createOfflineListener, IOfflineListener } from "./Offline";
import { Sample } from "./TelemetryProcessors/Sample"
import dynamicProto from "@microsoft/dynamicproto-js";
import {
DependencyEnvelopeCreator, EventEnvelopeCreator, ExceptionEnvelopeCreator, MetricEnvelopeCreator, PageViewEnvelopeCreator,
PageViewPerformanceEnvelopeCreator, TraceEnvelopeCreator
} from "./EnvelopeCreator";
import { IBackendResponse, ISenderConfig, XDomainRequest as IXDomainRequest } from "./Interfaces";
import { IOfflineListener, createOfflineListener } from "./Offline";
import { ArraySendBuffer, ISendBuffer, SessionStorageSendBuffer } from "./SendBuffer";
import { Serializer } from "./Serializer";
import { Sample } from "./TelemetryProcessors/Sample";
const FetchSyncRequestSizeLimitBytes = 65000; // approx 64kb (the current Edge, Firefox and Chrome max limit)
@ -45,9 +41,12 @@ function _getResponseText(xhr: XMLHttpRequest | IXDomainRequest) {
}
function _getDefaultAppInsightsChannelConfig(): ISenderConfig {
let defaultValue: string;
let defaultCustomHeaders: [{header: string, value: string}];
// set default values
return {
endpointUrl: () => "https://dc.services.visualstudio.com/v2/track",
endpointUrl: () => DEFAULT_BREEZE_ENDPOINT + DEFAULT_BREEZE_PATH,
emitLineDelimitedJson: () => false,
maxBatchInterval: () => 15000,
maxBatchSizeInBytes: () => 102400, // 100kb
@ -58,11 +57,11 @@ function _getDefaultAppInsightsChannelConfig(): ISenderConfig {
disableXhr: () => false,
onunloadDisableFetch: () => false,
onunloadDisableBeacon: () => false,
instrumentationKey: () => undefined, // Channel doesn't need iKey, it should be set already
namePrefix: () => undefined,
instrumentationKey: () => defaultValue, // Channel doesn't need iKey, it should be set already
namePrefix: () => defaultValue,
samplingPercentage: () => 100,
customHeaders: () => undefined,
convertUndefined: () => undefined,
customHeaders: () => defaultCustomHeaders,
convertUndefined: () => defaultValue,
eventsLimitInMem: () => 10000
}
}
@ -279,6 +278,7 @@ export class Sender extends BaseTelemetryPlugin implements IChannelControlsAI {
_self.processTelemetry = (telemetryItem: ITelemetryItem, itemCtx?: IProcessTelemetryContext) => {
itemCtx = _self._getTelCtx(itemCtx);
let diagLogger = itemCtx.diagLog();
try {
// if master off switch is set, don't send any data
@ -289,13 +289,13 @@ export class Sender extends BaseTelemetryPlugin implements IChannelControlsAI {
// validate input
if (!telemetryItem) {
_throwInternal(itemCtx.diagLog(), eLoggingSeverity.CRITICAL, _eInternalMessageId.CannotSendEmptyTelemetry, "Cannot send empty telemetry");
_throwInternal(diagLogger, eLoggingSeverity.CRITICAL, _eInternalMessageId.CannotSendEmptyTelemetry, "Cannot send empty telemetry");
return;
}
// validate event
if (telemetryItem.baseData && !telemetryItem.baseType) {
_throwInternal(itemCtx.diagLog(), eLoggingSeverity.CRITICAL, _eInternalMessageId.InvalidEvent, "Cannot send telemetry without baseData and baseType");
_throwInternal(diagLogger, eLoggingSeverity.CRITICAL, _eInternalMessageId.InvalidEvent, "Cannot send telemetry without baseData and baseType");
return;
}
@ -306,14 +306,14 @@ export class Sender extends BaseTelemetryPlugin implements IChannelControlsAI {
// ensure a sender was constructed
if (!_self._sender) {
_throwInternal(itemCtx.diagLog(), eLoggingSeverity.CRITICAL, _eInternalMessageId.SenderNotInitialized, "Sender was not initialized");
_throwInternal(diagLogger, eLoggingSeverity.CRITICAL, _eInternalMessageId.SenderNotInitialized, "Sender was not initialized");
return;
}
// check if this item should be sampled in, else add sampleRate tag
if (!_isSampledIn(telemetryItem)) {
// Item is sampled out, do not send it
_throwInternal(itemCtx.diagLog(), eLoggingSeverity.WARNING, _eInternalMessageId.TelemetrySampledAndNotSent,
_throwInternal(diagLogger, eLoggingSeverity.WARNING, _eInternalMessageId.TelemetrySampledAndNotSent,
"Telemetry item was sampled out and not sent", { SampleRate: _self._sample.sampleRate });
return;
} else {
@ -324,9 +324,9 @@ export class Sender extends BaseTelemetryPlugin implements IChannelControlsAI {
// construct an envelope that Application Insights endpoint can understand
// if ikey of telemetry is provided and not empty, envelope will use this iKey instead of senderConfig iKey
let defaultEnvelopeIkey = telemetryItem.iKey || _self._senderConfig.instrumentationKey();
let aiEnvelope = Sender.constructEnvelope(telemetryItem, defaultEnvelopeIkey, itemCtx.diagLog(), convertUndefined);
let aiEnvelope = Sender.constructEnvelope(telemetryItem, defaultEnvelopeIkey, diagLogger, convertUndefined);
if (!aiEnvelope) {
_throwInternal(itemCtx.diagLog(), eLoggingSeverity.CRITICAL, _eInternalMessageId.CreateEnvelopeError, "Unable to create an AppInsights envelope");
_throwInternal(diagLogger, eLoggingSeverity.CRITICAL, _eInternalMessageId.CreateEnvelopeError, "Unable to create an AppInsights envelope");
return;
}
@ -337,12 +337,12 @@ export class Sender extends BaseTelemetryPlugin implements IChannelControlsAI {
try {
if (callBack && callBack(aiEnvelope) === false) {
doNotSendItem = true;
_warnToConsole(itemCtx.diagLog(), "Telemetry processor check returns false");
_warnToConsole(diagLogger, "Telemetry processor check returns false");
}
} catch (e) {
// log error but dont stop executing rest of the telemetry initializers
// doNotSendItem = true;
_throwInternal(itemCtx.diagLog(),
_throwInternal(diagLogger,
eLoggingSeverity.CRITICAL, _eInternalMessageId.TelemetryInitializerFailed, "One of telemetry initializers failed, telemetry item will not be sent: " + getExceptionName(e),
{ exception: dumpObj(e) }, true);
}
@ -372,7 +372,7 @@ export class Sender extends BaseTelemetryPlugin implements IChannelControlsAI {
_setupTimer();
} catch (e) {
_throwInternal(itemCtx.diagLog(),
_throwInternal(diagLogger,
eLoggingSeverity.WARNING,
_eInternalMessageId.FailedAddingTelemetryToBuffer,
"Failed adding telemetry to the sender's buffer, some telemetry will be lost: " + getExceptionName(e),
@ -462,8 +462,8 @@ export class Sender extends BaseTelemetryPlugin implements IChannelControlsAI {
* partial success handler
*/
_self._onPartialSuccess = (payload: string[], results: IBackendResponse) => {
const failed = [];
const retry = [];
const failed: string[] = [];
const retry: string[] = [];
// Iterate through the reversed array of errors so that splicing doesn't have invalid indexes after the first item.
const errors = results.errors.reverse();
@ -686,7 +686,7 @@ export class Sender extends BaseTelemetryPlugin implements IChannelControlsAI {
// append Sdk-Context request header only in case of breeze endpoint
if (isInternalApplicationInsightsEndpoint(endPointUrl)) {
xhr.setRequestHeader(RequestHeaders.sdkContextHeader, RequestHeaders.sdkContextHeaderAppIdRequest);
xhr.setRequestHeader(RequestHeaders[eRequestHeaders.sdkContextHeader], RequestHeaders[eRequestHeaders.sdkContextHeaderAppIdRequest]);
}
arrForEach(objKeys(_headers), (headerName) => {
@ -748,7 +748,7 @@ export class Sender extends BaseTelemetryPlugin implements IChannelControlsAI {
// append Sdk-Context request header only in case of breeze endpoint
if (isInternalApplicationInsightsEndpoint(endPointUrl)) {
requestHeaders.append(RequestHeaders.sdkContextHeader, RequestHeaders.sdkContextHeaderAppIdRequest);
requestHeaders.append(RequestHeaders[eRequestHeaders.sdkContextHeader], RequestHeaders[eRequestHeaders.sdkContextHeaderAppIdRequest]);
}
arrForEach(objKeys(_headers), (headerName) => {

Просмотреть файл

@ -1,8 +1,8 @@
import { ISerializable, FieldType } from "@microsoft/applicationinsights-common";
import {
IDiagnosticLogger, eLoggingSeverity, _eInternalMessageId, getJSON, objForEachKey, isFunction, isObject, isArray, _throwInternal
} from "@microsoft/applicationinsights-core-js";
import dynamicProto from "@microsoft/dynamicproto-js"
import {
IDiagnosticLogger, _eInternalMessageId, _throwInternal, eLoggingSeverity, getJSON, isArray, isFunction, isObject, objForEachKey
} from "@microsoft/applicationinsights-core-js";
import { FieldType, ISerializable } from "@microsoft/applicationinsights-common";
export class Serializer {
@ -105,7 +105,7 @@ export class Serializer {
}
function _serializeArray(sources: ISerializable[], name: string): any[] {
let output;
let output: any[];
if (!!sources) {
if (!isArray(sources)) {
@ -174,4 +174,4 @@ export class Serializer {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
return null;
}
}
}

Просмотреть файл

@ -46,4 +46,4 @@ export class Sample implements ISample {
isSampledIn = this.samplingScoreGenerator.getSamplingScore(envelope) < samplingPercentage;
return isSampledIn;
}
}
}

Просмотреть файл

@ -34,4 +34,4 @@ export class HashCodeScoreGenerator {
return Math.abs(hash);
}
}
}

Просмотреть файл

@ -1,9 +1,9 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import { HashCodeScoreGenerator } from "./HashCodeScoreGenerator";
import { ITelemetryItem } from "@microsoft/applicationinsights-core-js";
import { ContextTagKeys } from "@microsoft/applicationinsights-common";
import { ITelemetryItem } from "@microsoft/applicationinsights-core-js";
import { HashCodeScoreGenerator } from "./HashCodeScoreGenerator";
export class SamplingScoreGenerator {
@ -32,4 +32,4 @@ export class SamplingScoreGenerator {
return score;
}
}
}
}

Просмотреть файл

@ -969,6 +969,8 @@ export class AITestClass {
if (!failed) {
QUnit.assert.ok(true, "Validated [" + targetName + "] has no registered hooks");
} else {
QUnit.assert.ok(false, "Hooks: " + JSON.stringify(aiHook.h));
}
}
}

Просмотреть файл

@ -1,4 +1,4 @@

/** Defines a test case */
export class TestCase {
/** Name to use for the test case */

Просмотреть файл

@ -11,6 +11,16 @@
"ignoreMissingScript": false,
"allowWarningsInSuccessfulBuild": true
},
{
"commandKind": "bulk",
"name": "mintest",
"summary": "Run all tests for all packages using the ai-minify for the source",
"description": "Runs tests for all projects using the ai-minify for the source",
"safeForSimultaneousRushProcesses": false,
"enableParallelism": false,
"ignoreMissingScript": true,
"allowWarningsInSuccessfulBuild": true
},
{
"commandKind": "bulk",
"name": "perftest",
@ -41,6 +51,26 @@
"summary": "Run all build for all packages",
"name": "rebuild",
"allowWarningsInSuccessfulBuild": true
}
},
{
"commandKind": "bulk",
"name": "ai-min",
"summary": "Run all ai-minify tasks for all packages",
"description": "Runs ai-minify tasks for all projects",
"safeForSimultaneousRushProcesses": false,
"enableParallelism": false,
"ignoreMissingScript": true,
"allowWarningsInSuccessfulBuild": true
},
{
"commandKind": "bulk",
"name": "ai-restore",
"summary": "Run all restore tasks for all packages to unminify the files",
"description": "Runs all restore tasks for all projects to unminify the files",
"safeForSimultaneousRushProcesses": false,
"enableParallelism": false,
"ignoreMissingScript": true,
"allowWarningsInSuccessfulBuild": true
}
]
}

2784
common/config/rush/npm-shrinkwrap.json сгенерированный

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Просмотреть файл

@ -18,9 +18,12 @@
"build:browser": "rollup -c",
"rebuild": "npm run build",
"test": "grunt aitests",
"mintest": "grunt ai-mintests",
"lint": "tslint -p tsconfig.json",
"dtsgen": "api-extractor run --local && node ../../scripts/dtsgen.js \"Microsoft Application Insights JavaScript SDK - Web Analytics\"",
"sri": "node ../../tools/subResourceIntegrity/generateIntegrityFile.js"
"sri": "node ../../tools/subResourceIntegrity/generateIntegrityFile.js",
"ai-min": "grunt ai-min",
"ai-restore": "grunt ai-restore"
},
"devDependencies": {
"@microsoft/ai-test-framework": "0.0.1",

Просмотреть файл

@ -1,39 +1,31 @@
/**
* ApplicationInsights.ts
* @copyright Microsoft 2018
*/
* ApplicationInsights.ts
* @copyright Microsoft 2018
*/
import {
IConfig, PageViewPerformance, IAppInsights, PageView, RemoteDependencyData, Event as EventTelemetry, IEventTelemetry,
createTelemetryItem, Metric, Exception, eSeverityLevel, Trace, IDependencyTelemetry,
IExceptionTelemetry, ITraceTelemetry, IMetricTelemetry, IAutoExceptionTelemetry,
IPageViewTelemetryInternal, IPageViewTelemetry, IPageViewPerformanceTelemetry, IPageViewPerformanceTelemetryInternal,
IExceptionInternal, PropertiesPluginIdentifier, AnalyticsPluginIdentifier, stringToBoolOrDefault, createDomEvent,
strNotSpecified, isCrossOriginError, utlDisableStorage, utlEnableStorage, dataSanitizeString, createDistributedTraceContextFromTrace
} from "@microsoft/applicationinsights-common";
import {
IPlugin, IConfiguration, IAppInsightsCore,
BaseTelemetryPlugin, ITelemetryItem, IProcessTelemetryContext, ITelemetryPluginChain,
eLoggingSeverity, _eInternalMessageId, ICustomProperties,
getWindow, getDocument, getHistory, getLocation, objForEachKey,
isString, isFunction, isNullOrUndefined, arrForEach, generateW3CId, dumpObj, getExceptionName, ICookieMgr, safeGetCookieMgr,
TelemetryInitializerFunction, hasHistory, strUndefined, objDefineAccessors, InstrumentEvent, IInstrumentCallDetails, eventOn, eventOff,
mergeEvtNamespace, createUniqueNamespace, ITelemetryInitializerHandler, throwError, isUndefined, hasWindow, createProcessTelemetryContext,
ITelemetryUnloadState, IProcessTelemetryUnloadContext, IDistributedTraceContext
} from "@microsoft/applicationinsights-core-js";
import { PageViewManager, IAppInsightsInternal } from "./Telemetry/PageViewManager";
import { PageVisitTimeManager } from "./Telemetry/PageVisitTimeManager";
import { PageViewPerformanceManager } from "./Telemetry/PageViewPerformanceManager";
import dynamicProto from "@microsoft/dynamicproto-js";
// For types only
import {
AnalyticsPluginIdentifier, Event as EventTelemetry, Exception, IAppInsights, IAutoExceptionTelemetry, IConfig, IDependencyTelemetry,
IEventTelemetry, IExceptionInternal, IExceptionTelemetry, IMetricTelemetry, IPageViewPerformanceTelemetry,
IPageViewPerformanceTelemetryInternal, IPageViewTelemetry, IPageViewTelemetryInternal, ITraceTelemetry, Metric, PageView,
PageViewPerformance, PropertiesPluginIdentifier, RemoteDependencyData, Trace, createDistributedTraceContextFromTrace, createDomEvent,
createTelemetryItem, dataSanitizeString, eSeverityLevel, isCrossOriginError, strNotSpecified, stringToBoolOrDefault, utlDisableStorage,
utlEnableStorage
} from "@microsoft/applicationinsights-common";
import {
BaseTelemetryPlugin, IAppInsightsCore, IConfiguration, ICookieMgr, ICustomProperties, IDistributedTraceContext, IInstrumentCallDetails,
IPlugin, IProcessTelemetryContext, IProcessTelemetryUnloadContext, ITelemetryInitializerHandler, ITelemetryItem, ITelemetryPluginChain,
ITelemetryUnloadState, InstrumentEvent, TelemetryInitializerFunction, _eInternalMessageId, arrForEach, createProcessTelemetryContext,
createUniqueNamespace, dumpObj, eLoggingSeverity, eventOff, eventOn, generateW3CId, getDocument, getExceptionName, getHistory,
getLocation, getWindow, hasHistory, hasWindow, isFunction, isNullOrUndefined, isString, isUndefined, mergeEvtNamespace,
objDefineAccessors, objForEachKey, safeGetCookieMgr, strUndefined, throwError
} from "@microsoft/applicationinsights-core-js";
import { PropertiesPlugin } from "@microsoft/applicationinsights-properties-js";
import { IAppInsightsInternal, PageViewManager } from "./Telemetry/PageViewManager";
import { PageViewPerformanceManager } from "./Telemetry/PageViewPerformanceManager";
import { PageVisitTimeManager } from "./Telemetry/PageVisitTimeManager";
import { Timing } from "./Timing";
"use strict";
const durationProperty: string = "duration";
const strEvent = "event";
function _dispatchEvent(target:EventTarget, evnt: Event) {
@ -109,7 +101,7 @@ function _updateStorageUsage(extConfig: IConfig) {
}
export class AnalyticsPlugin extends BaseTelemetryPlugin implements IAppInsights, IAppInsightsInternal {
public static Version = "2.8.4"; // Not currently used anywhere
public static Version = "#version#"; // Not currently used anywhere
public static getDefaultConfig = _getDefaultConfig;
@ -566,12 +558,12 @@ export class AnalyticsPlugin extends BaseTelemetryPlugin implements IAppInsights
if (!properties) {
properties = {};
}
if (!measurements) {
measurements = {};
}
properties[durationProperty] = duration.toString();
properties.duration = duration.toString();
_self.trackEvent({ name, properties, measurements } as IEventTelemetry);
}
@ -583,7 +575,7 @@ export class AnalyticsPlugin extends BaseTelemetryPlugin implements IAppInsights
if (isNullOrUndefined(properties)) {
properties = {};
}
properties[durationProperty] = duration.toString();
properties.duration = duration.toString();
let pageViewItem: IPageViewTelemetry = {
name,
@ -765,9 +757,11 @@ export class AnalyticsPlugin extends BaseTelemetryPlugin implements IAppInsights
*/
function _addHistoryListener(extConfig: IConfig, win: Window, history: History, locn: Location) {
let namePrefix = extConfig.namePrefix || "";
function _popstateHandler() {
if (_enableAutoRouteTracking) {
_dispatchEvent(win, createDomEvent(extConfig.namePrefix + "locationchange"));
_dispatchEvent(win, createDomEvent(namePrefix + "locationchange"));
}
}
@ -805,8 +799,8 @@ export class AnalyticsPlugin extends BaseTelemetryPlugin implements IAppInsights
ns: _evtNamespace,
rsp: () => {
if (_enableAutoRouteTracking) {
_dispatchEvent(win, createDomEvent(extConfig.namePrefix + "pushState"));
_dispatchEvent(win, createDomEvent(extConfig.namePrefix + "locationchange"));
_dispatchEvent(win, createDomEvent(namePrefix + "pushState"));
_dispatchEvent(win, createDomEvent(namePrefix + "locationchange"));
}
}
}, true));
@ -815,14 +809,14 @@ export class AnalyticsPlugin extends BaseTelemetryPlugin implements IAppInsights
ns: _evtNamespace,
rsp: () => {
if (_enableAutoRouteTracking) {
_dispatchEvent(win, createDomEvent(extConfig.namePrefix + "replaceState"));
_dispatchEvent(win, createDomEvent(extConfig.namePrefix + "locationchange"));
_dispatchEvent(win, createDomEvent(namePrefix + "replaceState"));
_dispatchEvent(win, createDomEvent(namePrefix + "locationchange"));
}
}
}, true));
eventOn(win, extConfig.namePrefix + "popstate", _popstateHandler, _evtNamespace);
eventOn(win, extConfig.namePrefix + "locationchange", _locationChangeHandler, _evtNamespace);
eventOn(win, namePrefix + "popstate", _popstateHandler, _evtNamespace);
eventOn(win, namePrefix + "locationchange", _locationChangeHandler, _evtNamespace);
_historyListenerAdded = true;
}
@ -856,7 +850,7 @@ export class AnalyticsPlugin extends BaseTelemetryPlugin implements IAppInsights
/**
* This method will throw exceptions in debug mode or attempt to log the error as a console warning.
* @param severity {LoggingSeverity} - The severity of the log message
* @param severity {eLoggingSeverity} - The severity of the log message
* @param message {_InternalLogMessage} - The log message.
*/
function _throwInternal(severity: eLoggingSeverity, msgId: _eInternalMessageId, msg: string, properties?: Object, isUserAct?: boolean): void {
@ -1058,4 +1052,4 @@ export class AnalyticsPlugin extends BaseTelemetryPlugin implements IAppInsights
public initialize(config: IConfiguration & IConfig, core: IAppInsightsCore, extensions: IPlugin[], pluginChain?:ITelemetryPluginChain) {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
}
}

Просмотреть файл

@ -1,15 +1,15 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import dynamicProto from "@microsoft/dynamicproto-js";
import {
dateTimeUtilsDuration, IPageViewTelemetry, IPageViewTelemetryInternal, IPageViewPerformanceTelemetryInternal
IPageViewPerformanceTelemetryInternal, IPageViewTelemetry, IPageViewTelemetryInternal, dateTimeUtilsDuration
} from "@microsoft/applicationinsights-common";
import {
IAppInsightsCore, IDiagnosticLogger, eLoggingSeverity,
_eInternalMessageId, getDocument, getLocation, arrForEach, isNullOrUndefined, getExceptionName, dumpObj, IProcessTelemetryUnloadContext, ITelemetryUnloadState, _throwInternal
IAppInsightsCore, IDiagnosticLogger, IProcessTelemetryUnloadContext, ITelemetryUnloadState, _eInternalMessageId, _throwInternal,
arrForEach, dumpObj, eLoggingSeverity, getDocument, getExceptionName, getLocation, isNullOrUndefined
} from "@microsoft/applicationinsights-core-js";
import { PageViewPerformanceManager } from "./PageViewPerformanceManager";
import dynamicProto from "@microsoft/dynamicproto-js";
/**
* Internal interface to pass appInsights object to subcomponents without coupling
@ -134,7 +134,7 @@ export class PageViewManager {
customProperties = {};
}
customProperties["duration"] = customDuration;
customProperties.duration = customDuration;
}
// case 2
appInsights.sendPageViewInternal(
@ -166,13 +166,13 @@ export class PageViewManager {
if (!pageViewPerformance.isValid && !pageViewSent) {
// If navigation timing gives invalid numbers, then go back to "override page view duration" mode.
// That's the best value we can get that makes sense.
customProperties["duration"] = customDuration;
customProperties.duration = customDuration;
appInsights.sendPageViewInternal(
pageView,
customProperties);
} else {
if (!pageViewSent) {
customProperties["duration"] = pageViewPerformance.durationMs;
customProperties.duration = pageViewPerformance.durationMs;
appInsights.sendPageViewInternal(
pageView,
customProperties);
@ -188,7 +188,7 @@ export class PageViewManager {
// with the maximum duration limit. Otherwise, keep waiting until performance timings are ready
processed = true;
if (!pageViewSent) {
customProperties["duration"] = maxDurationLimit;
customProperties.duration = maxDurationLimit;
appInsights.sendPageViewInternal(
pageView,
customProperties

Просмотреть файл

@ -1,146 +1,204 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import dynamicProto from "@microsoft/dynamicproto-js";
import { IPageViewPerformanceTelemetryInternal, dateTimeUtilsDuration, msToTimeSpan } from "@microsoft/applicationinsights-common";
import {
IPageViewPerformanceTelemetryInternal, dateTimeUtilsDuration, msToTimeSpan
} from "@microsoft/applicationinsights-common";
import {
IAppInsightsCore, IDiagnosticLogger, eLoggingSeverity,
_eInternalMessageId, getNavigator, getPerformance, _throwInternal
IAppInsightsCore, IDiagnosticLogger, _eInternalMessageId, _throwInternal, eLoggingSeverity, getNavigator, getPerformance, safeGetLogger
} from "@microsoft/applicationinsights-core-js";
const MAX_DURATION_ALLOWED = 3600000; // 1h
const botAgentNames = ["googlebot", "adsbot-google", "apis-google", "mediapartners-google"];
function _isPerformanceTimingSupported() {
let perf = getPerformance();
return perf && !!perf.timing;
}
function _isPerformanceNavigationTimingSupported() {
let perf = getPerformance();
return perf && perf.getEntriesByType && perf.getEntriesByType("navigation").length > 0;
}
function _isPerformanceTimingDataReady() {
let perf = getPerformance();
const timing = perf ? perf.timing : 0;
return timing
&& timing.domainLookupStart > 0
&& timing.navigationStart > 0
&& timing.responseStart > 0
&& timing.requestStart > 0
&& timing.loadEventEnd > 0
&& timing.responseEnd > 0
&& timing.connectEnd > 0
&& timing.domLoading > 0;
}
function _getPerformanceTiming(): PerformanceTiming | null {
if (_isPerformanceTimingSupported()) {
return getPerformance().timing;
}
return null;
}
function _getPerformanceNavigationTiming(): PerformanceNavigationTiming | null {
if (_isPerformanceNavigationTimingSupported()) {
return getPerformance().getEntriesByType("navigation")[0] as PerformanceNavigationTiming;
}
return null;
}
/**
* This method tells if given durations should be excluded from collection.
*/
function _shouldCollectDuration(...durations: number[]): boolean {
var _navigator = getNavigator() || {} as any;
// a full list of Google crawlers user agent strings - https://support.google.com/webmasters/answer/1061943?hl=en
const userAgent = _navigator.userAgent;
let isGoogleBot = false;
if (userAgent) {
for (let i = 0; i < botAgentNames.length; i++) {
isGoogleBot = isGoogleBot || userAgent.toLowerCase().indexOf(botAgentNames[i]) !== -1;
}
}
if (isGoogleBot) {
// Don't report durations for GoogleBot, it is returning invalid values in performance.timing API.
return false;
} else {
// for other page views, don't report if it's outside of a reasonable range
for (let i = 0; i < durations.length; i++) {
if (durations[i] < 0 || durations[i] >= MAX_DURATION_ALLOWED) {
return false;
}
}
}
return true;
}
/**
* Class encapsulates sending page view performance telemetry.
*/
export class PageViewPerformanceManager {
private _logger: IDiagnosticLogger;
private MAX_DURATION_ALLOWED = 3600000; // 1h
constructor(core: IAppInsightsCore) {
if (core) {
this._logger = core.logger;
}
let _logger: IDiagnosticLogger = safeGetLogger(core);
dynamicProto(PageViewPerformanceManager, this, (_self) => {
_self.populatePageViewPerformanceEvent = (pageViewPerformance: IPageViewPerformanceTelemetryInternal): void => {
pageViewPerformance.isValid = false;
/*
* http://www.w3.org/TR/navigation-timing/#processing-model
* |-navigationStart
* | |-connectEnd
* | ||-requestStart
* | || |-responseStart
* | || | |-responseEnd
* | || | |
* | || | | |-loadEventEnd
* |---network---||---request---|---response---|---dom---|
* |--------------------------total----------------------|
*
* total = The difference between the load event of the current document is completed and the first recorded timestamp of the performance entry : https://developer.mozilla.org/en-US/docs/Web/Performance/Navigation_and_resource_timings#duration
* network = Redirect time + App Cache + DNS lookup time + TCP connection time
* request = Request time : https://developer.mozilla.org/en-US/docs/Web/Performance/Navigation_and_resource_timings#request_time
* response = Response time
* dom = Document load time : https://html.spec.whatwg.org/multipage/dom.html#document-load-timing-info
* = Document processing time : https://developers.google.com/web/fundamentals/performance/navigation-and-resource-timing/#document_processing
* + Loading time : https://developers.google.com/web/fundamentals/performance/navigation-and-resource-timing/#loading
*/
const navigationTiming = _getPerformanceNavigationTiming();
const timing = _getPerformanceTiming();
let total = 0;
let network = 0;
let request = 0;
let response = 0;
let dom = 0;
if (navigationTiming || timing) {
if (navigationTiming) {
total = navigationTiming.duration;
/**
* support both cases:
* - startTime is always zero: https://developer.mozilla.org/en-US/docs/Web/API/PerformanceNavigationTiming
* - for older browsers where the startTime is not zero
*/
network = navigationTiming.startTime === 0 ? navigationTiming.connectEnd : dateTimeUtilsDuration(navigationTiming.startTime, navigationTiming.connectEnd);
request = dateTimeUtilsDuration(navigationTiming.requestStart, navigationTiming.responseStart);
response = dateTimeUtilsDuration(navigationTiming.responseStart, navigationTiming.responseEnd);
dom = dateTimeUtilsDuration(navigationTiming.responseEnd, navigationTiming.loadEventEnd);
} else {
total = dateTimeUtilsDuration(timing.navigationStart, timing.loadEventEnd);
network = dateTimeUtilsDuration(timing.navigationStart, timing.connectEnd);
request = dateTimeUtilsDuration(timing.requestStart, timing.responseStart);
response = dateTimeUtilsDuration(timing.responseStart, timing.responseEnd);
dom = dateTimeUtilsDuration(timing.responseEnd, timing.loadEventEnd);
}
if (total === 0) {
_throwInternal(_logger,
eLoggingSeverity.WARNING,
_eInternalMessageId.ErrorPVCalc,
"error calculating page view performance.",
{ total, network, request, response, dom });
} else if (!this.shouldCollectDuration(total, network, request, response, dom)) {
_throwInternal(_logger,
eLoggingSeverity.WARNING,
_eInternalMessageId.InvalidDurationValue,
"Invalid page load duration value. Browser perf data won't be sent.",
{ total, network, request, response, dom });
} else if (total < Math.floor(network) + Math.floor(request) + Math.floor(response) + Math.floor(dom)) {
// some browsers may report individual components incorrectly so that the sum of the parts will be bigger than total PLT
// in this case, don't report client performance from this page
_throwInternal(_logger,
eLoggingSeverity.WARNING,
_eInternalMessageId.ClientPerformanceMathError,
"client performance math error.",
{ total, network, request, response, dom });
} else {
pageViewPerformance.durationMs = total;
// // convert to timespans
pageViewPerformance.perfTotal = pageViewPerformance.duration = msToTimeSpan(total);
pageViewPerformance.networkConnect = msToTimeSpan(network);
pageViewPerformance.sentRequest = msToTimeSpan(request);
pageViewPerformance.receivedResponse = msToTimeSpan(response);
pageViewPerformance.domProcessing = msToTimeSpan(dom);
pageViewPerformance.isValid = true;
}
}
}
_self.getPerformanceTiming = _getPerformanceTiming;
_self.isPerformanceTimingSupported = _isPerformanceTimingSupported;
_self.isPerformanceTimingDataReady = _isPerformanceTimingDataReady;
_self.shouldCollectDuration = _shouldCollectDuration;
});
}
public populatePageViewPerformanceEvent(pageViewPerformance: IPageViewPerformanceTelemetryInternal): void {
pageViewPerformance.isValid = false;
/*
* http://www.w3.org/TR/navigation-timing/#processing-model
* |-navigationStart
* | |-connectEnd
* | ||-requestStart
* | || |-responseStart
* | || | |-responseEnd
* | || | |
* | || | | |-loadEventEnd
* |---network---||---request---|---response---|---dom---|
* |--------------------------total----------------------|
*
* total = The difference between the load event of the current document is completed and the first recorded timestamp of the performance entry : https://developer.mozilla.org/en-US/docs/Web/Performance/Navigation_and_resource_timings#duration
* network = Redirect time + App Cache + DNS lookup time + TCP connection time
* request = Request time : https://developer.mozilla.org/en-US/docs/Web/Performance/Navigation_and_resource_timings#request_time
* response = Response time
* dom = Document load time : https://html.spec.whatwg.org/multipage/dom.html#document-load-timing-info
* = Document processing time : https://developers.google.com/web/fundamentals/performance/navigation-and-resource-timing/#document_processing
* + Loading time : https://developers.google.com/web/fundamentals/performance/navigation-and-resource-timing/#loading
*/
const navigationTiming = this.getPerformanceNavigationTiming();
const timing = this.getPerformanceTiming();
let total = 0;
let network = 0;
let request = 0;
let response = 0;
let dom = 0;
if (navigationTiming || timing) {
if (navigationTiming) {
total = navigationTiming.duration;
/**
* support both cases:
* - startTime is always zero: https://developer.mozilla.org/en-US/docs/Web/API/PerformanceNavigationTiming
* - for older browsers where the startTime is not zero
*/
network = navigationTiming.startTime === 0 ? navigationTiming.connectEnd : dateTimeUtilsDuration(navigationTiming.startTime, navigationTiming.connectEnd);
request = dateTimeUtilsDuration(navigationTiming.requestStart, navigationTiming.responseStart);
response = dateTimeUtilsDuration(navigationTiming.responseStart, navigationTiming.responseEnd);
dom = dateTimeUtilsDuration(navigationTiming.responseEnd, navigationTiming.loadEventEnd);
} else {
total = dateTimeUtilsDuration(timing.navigationStart, timing.loadEventEnd);
network = dateTimeUtilsDuration(timing.navigationStart, timing.connectEnd);
request = dateTimeUtilsDuration(timing.requestStart, timing.responseStart);
response = dateTimeUtilsDuration(timing.responseStart, timing.responseEnd);
dom = dateTimeUtilsDuration(timing.responseEnd, timing.loadEventEnd);
}
let logger = this._logger;
if (total === 0) {
_throwInternal(logger,
eLoggingSeverity.WARNING,
_eInternalMessageId.ErrorPVCalc,
"error calculating page view performance.",
{ total, network, request, response, dom });
} else if (!this.shouldCollectDuration(total, network, request, response, dom)) {
_throwInternal(logger,
eLoggingSeverity.WARNING,
_eInternalMessageId.InvalidDurationValue,
"Invalid page load duration value. Browser perf data won't be sent.",
{ total, network, request, response, dom });
} else if (total < Math.floor(network) + Math.floor(request) + Math.floor(response) + Math.floor(dom)) {
// some browsers may report individual components incorrectly so that the sum of the parts will be bigger than total PLT
// in this case, don't report client performance from this page
_throwInternal(logger,
eLoggingSeverity.WARNING,
_eInternalMessageId.ClientPerformanceMathError,
"client performance math error.",
{ total, network, request, response, dom });
} else {
pageViewPerformance.durationMs = total;
// // convert to timespans
pageViewPerformance.perfTotal = pageViewPerformance.duration = msToTimeSpan(total);
pageViewPerformance.networkConnect = msToTimeSpan(network);
pageViewPerformance.sentRequest = msToTimeSpan(request);
pageViewPerformance.receivedResponse = msToTimeSpan(response);
pageViewPerformance.domProcessing = msToTimeSpan(dom);
pageViewPerformance.isValid = true;
}
}
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
public getPerformanceTiming(): PerformanceTiming | null {
if (this.isPerformanceTimingSupported()) {
return getPerformance().timing;
}
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
return null;
}
public getPerformanceNavigationTiming(): PerformanceNavigationTiming | null {
if (this.isPerformanceNavigationTimingSupported()) {
return getPerformance().getEntriesByType("navigation")[0] as PerformanceNavigationTiming;
}
return null;
}
/**
* Returns true is window PerformanceNavigationTiming API is supported, false otherwise.
*/
public isPerformanceNavigationTimingSupported() {
let perf = getPerformance();
return perf && perf.getEntriesByType && perf.getEntriesByType("navigation").length > 0;
}
/**
* Returns true is window performance timing API is supported, false otherwise.
*/
public isPerformanceTimingSupported() {
let perf = getPerformance();
return perf && perf.timing;
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
return true;
}
/**
@ -148,50 +206,15 @@ export class PageViewPerformanceManager {
* Returns true if ready, false otherwise.
*/
public isPerformanceTimingDataReady() {
let perf = getPerformance();
const timing = perf ? perf.timing : 0;
return timing
&& timing.domainLookupStart > 0
&& timing.navigationStart > 0
&& timing.responseStart > 0
&& timing.requestStart > 0
&& timing.loadEventEnd > 0
&& timing.responseEnd > 0
&& timing.connectEnd > 0
&& timing.domLoading > 0;
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
return true;
}
/**
* This method tells if given durations should be excluded from collection.
*/
public shouldCollectDuration(...durations: number[]): boolean {
var _navigator = getNavigator() || {} as any;
// a full list of Google crawlers user agent strings - https://support.google.com/webmasters/answer/1061943?hl=en
const botAgentNames = ["googlebot", "adsbot-google", "apis-google", "mediapartners-google"];
const userAgent = _navigator.userAgent;
let isGoogleBot = false;
if (userAgent) {
for (let i = 0; i < botAgentNames.length; i++) {
isGoogleBot = isGoogleBot || userAgent.toLowerCase().indexOf(botAgentNames[i]) !== -1;
}
}
if (isGoogleBot) {
// Don't report durations for GoogleBot, it is returning invalid values in performance.timing API.
return false;
} else {
// for other page views, don't report if it's outside of a reasonable range
for (let i = 0; i < durations.length; i++) {
if (durations[i] < 0 || durations[i] >= this.MAX_DURATION_ALLOWED) {
return false;
}
}
}
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
return true;
}
}

Просмотреть файл

@ -1,26 +1,120 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import { utlCanUseSessionStorage, utlGetSessionStorage, utlRemoveSessionStorage, utlSetSessionStorage } from "@microsoft/applicationinsights-common";
import { IDiagnosticLogger, hasJSON, getJSON, dateNow, dumpObj, throwError, _warnToConsole } from "@microsoft/applicationinsights-core-js";
import dynamicProto from "@microsoft/dynamicproto-js";
import {
utlCanUseSessionStorage, utlGetSessionStorage, utlRemoveSessionStorage, utlSetSessionStorage
} from "@microsoft/applicationinsights-common";
import {
IDiagnosticLogger, _warnToConsole, dateNow, dumpObj, getJSON, hasJSON, objDefineAccessors, throwError
} from "@microsoft/applicationinsights-core-js";
/**
* Used to track page visit durations
*/
export class PageVisitTimeManager {
private prevPageVisitDataKeyName: string = "prevPageVisitData";
private pageVisitTimeTrackingHandler: (pageName: string, pageUrl: string, pageVisitTime: number) => void;
private _logger: IDiagnosticLogger;
/**
* Creates a new instance of PageVisitTimeManager
* @param pageVisitTimeTrackingHandler Delegate that will be called to send telemetry data to AI (when trackPreviousPageVisit is called)
* @returns {}
*/
constructor(logger: IDiagnosticLogger, pageVisitTimeTrackingHandler: (pageName: string, pageUrl: string, pageVisitTime: number) => void) {
this.pageVisitTimeTrackingHandler = pageVisitTimeTrackingHandler;
this._logger = logger;
let prevPageVisitDataKeyName: string = "prevPageVisitData";
dynamicProto(PageVisitTimeManager, this, (_self) => {
_self.trackPreviousPageVisit = (currentPageName: string, currentPageUrl: string) => {
try {
// Restart timer for new page view
const prevPageVisitTimeData = restartPageVisitTimer(currentPageName, currentPageUrl);
// If there was a page already being timed, track the visit time for it now.
if (prevPageVisitTimeData) {
pageVisitTimeTrackingHandler(prevPageVisitTimeData.pageName, prevPageVisitTimeData.pageUrl, prevPageVisitTimeData.pageVisitTime);
}
} catch (e) {
_warnToConsole(logger, "Auto track page visit time failed, metric will not be collected: " + dumpObj(e));
}
};
/**
* Stops timing of current page (if exists) and starts timing for duration of visit to pageName
* @param pageName Name of page to begin timing visit duration
* @returns {PageVisitData} Page visit data (including duration) of pageName from last call to start or restart, if exists. Null if not.
*/
function restartPageVisitTimer(pageName: string, pageUrl: string) {
let prevPageVisitData: PageVisitData = null;
try {
prevPageVisitData = stopPageVisitTimer();
startPageVisitTimer(pageName, pageUrl);
} catch (e) {
_warnToConsole(logger, "Call to restart failed: " + dumpObj(e));
prevPageVisitData = null;
}
return prevPageVisitData;
}
/**
* Starts timing visit duration of pageName
* @param pageName
* @returns {}
*/
function startPageVisitTimer(pageName: string, pageUrl: string) {
try {
if (utlCanUseSessionStorage()) {
if (utlGetSessionStorage(logger, prevPageVisitDataKeyName) != null) {
throwError("Cannot call startPageVisit consecutively without first calling stopPageVisit");
}
const currPageVisitData = new PageVisitData(pageName, pageUrl);
const currPageVisitDataStr = getJSON().stringify(currPageVisitData);
utlSetSessionStorage(logger, prevPageVisitDataKeyName, currPageVisitDataStr);
}
} catch (e) {
// TODO: Remove this catch in next phase, since if start is called twice in a row the exception needs to be propagated out
_warnToConsole(logger, "Call to start failed: " + dumpObj(e));
}
}
/**
* Stops timing of current page, if exists.
* @returns {PageVisitData} Page visit data (including duration) of pageName from call to start, if exists. Null if not.
*/
function stopPageVisitTimer() {
let prevPageVisitData: PageVisitData = null;
try {
if (utlCanUseSessionStorage()) {
// Define end time of page's visit
const pageVisitEndTime = dateNow();
// Try to retrieve page name and start time from session storage
const pageVisitDataJsonStr = utlGetSessionStorage(logger, prevPageVisitDataKeyName);
if (pageVisitDataJsonStr && hasJSON()) {
// if previous page data exists, set end time of visit
prevPageVisitData = getJSON().parse(pageVisitDataJsonStr);
prevPageVisitData.pageVisitTime = pageVisitEndTime - prevPageVisitData.pageVisitStartTime;
// Remove data from storage since we already used it
utlRemoveSessionStorage(logger, prevPageVisitDataKeyName);
}
}
} catch (e) {
_warnToConsole(logger, "Stop page visit timer failed: " + dumpObj(e));
prevPageVisitData = null;
}
return prevPageVisitData;
}
// For backward compatibility
objDefineAccessors(_self, "_logger", () => logger);
objDefineAccessors(_self, "pageVisitTimeTrackingHandler", () => pageVisitTimeTrackingHandler);
});
}
/**
@ -28,94 +122,8 @@ export class PageVisitTimeManager {
* @param currentPageName Name of page to begin timing for visit duration
* @param currentPageUrl Url of page to begin timing for visit duration
*/
public trackPreviousPageVisit(currentPageName: string, currentPageUrl: string) {
try {
// Restart timer for new page view
const prevPageVisitTimeData = this.restartPageVisitTimer(currentPageName, currentPageUrl);
// If there was a page already being timed, track the visit time for it now.
if (prevPageVisitTimeData) {
this.pageVisitTimeTrackingHandler(prevPageVisitTimeData.pageName, prevPageVisitTimeData.pageUrl, prevPageVisitTimeData.pageVisitTime);
}
} catch (e) {
_warnToConsole(this._logger, "Auto track page visit time failed, metric will not be collected: " + dumpObj(e));
}
}
/**
* Stops timing of current page (if exists) and starts timing for duration of visit to pageName
* @param pageName Name of page to begin timing visit duration
* @returns {PageVisitData} Page visit data (including duration) of pageName from last call to start or restart, if exists. Null if not.
*/
public restartPageVisitTimer(pageName: string, pageUrl: string) {
try {
const prevPageVisitData = this.stopPageVisitTimer();
this.startPageVisitTimer(pageName, pageUrl);
return prevPageVisitData;
} catch (e) {
_warnToConsole(this._logger, "Call to restart failed: " + dumpObj(e));
return null;
}
}
/**
* Starts timing visit duration of pageName
* @param pageName
* @returns {}
*/
public startPageVisitTimer(pageName: string, pageUrl: string) {
try {
if (utlCanUseSessionStorage()) {
if (utlGetSessionStorage(this._logger, this.prevPageVisitDataKeyName) != null) {
throwError("Cannot call startPageVisit consecutively without first calling stopPageVisit");
}
const currPageVisitData = new PageVisitData(pageName, pageUrl);
const currPageVisitDataStr = getJSON().stringify(currPageVisitData);
utlSetSessionStorage(this._logger, this.prevPageVisitDataKeyName, currPageVisitDataStr);
}
} catch (e) {
// TODO: Remove this catch in next phase, since if start is called twice in a row the exception needs to be propagated out
_warnToConsole(this._logger, "Call to start failed: " + dumpObj(e));
}
}
/**
* Stops timing of current page, if exists.
* @returns {PageVisitData} Page visit data (including duration) of pageName from call to start, if exists. Null if not.
*/
public stopPageVisitTimer() {
try {
if (utlCanUseSessionStorage()) {
// Define end time of page's visit
const pageVisitEndTime = dateNow();
// Try to retrieve page name and start time from session storage
const pageVisitDataJsonStr = utlGetSessionStorage(this._logger, this.prevPageVisitDataKeyName);
if (pageVisitDataJsonStr && hasJSON()) {
// if previous page data exists, set end time of visit
const prevPageVisitData: PageVisitData = getJSON().parse(pageVisitDataJsonStr);
prevPageVisitData.pageVisitTime = pageVisitEndTime - prevPageVisitData.pageVisitStartTime;
// Remove data from storage since we already used it
utlRemoveSessionStorage(this._logger, this.prevPageVisitDataKeyName);
// Return page visit data
return prevPageVisitData;
} else {
return null;
}
}
return null;
} catch (e) {
_warnToConsole(this._logger, "Stop page visit timer failed: " + dumpObj(e));
return null;
}
public trackPreviousPageVisit(currentPageName: string, currentPageUrl: string): void {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
}
@ -131,4 +139,4 @@ export class PageVisitData {
this.pageName = pageName;
this.pageUrl = pageUrl;
}
}
}

Просмотреть файл

@ -14,9 +14,12 @@
"build:browser": "rollup -c",
"rebuild": "npm run build",
"test": "grunt clickanalyticstests",
"mintest": "grunt clickanalytics-mintests",
"lint": "tslint -p tsconfig.json",
"dtsgen": "api-extractor run --local && node ../../scripts/dtsgen.js 'Microsoft.ApplicationInsights'",
"sri": "node ../../tools/subResourceIntegrity/generateIntegrityFile.js"
"sri": "node ../../tools/subResourceIntegrity/generateIntegrityFile.js",
"ai-min": "grunt clickanalytics-min",
"ai-restore": "grunt clickanalytics-restore"
},
"devDependencies": {
"@microsoft/ai-test-framework": "0.0.1",

Просмотреть файл

@ -1,34 +1,27 @@
/**
* @copyright Microsoft 2020
*/
* @copyright Microsoft 2020
*/
import dynamicProto from "@microsoft/dynamicproto-js";
import {
IPlugin, IConfiguration, IAppInsightsCore,
BaseTelemetryPlugin, isNullOrUndefined, ITelemetryItem,
IProcessTelemetryContext, ITelemetryPluginChain,
_eInternalMessageId, ICustomProperties,
eLoggingSeverity, arrForEach, dumpObj, getExceptionName, throwError, _throwInternal, IProcessTelemetryUnloadContext, ITelemetryUnloadState, unloadComponents
} from "@microsoft/applicationinsights-core-js";
import { IConfig, IPropertiesPlugin, PropertiesPluginIdentifier } from "@microsoft/applicationinsights-common";
import {
IClickAnalyticsConfiguration, IContentHandler,
IAutoCaptureHandler, IPageActionTelemetry
} from "./Interfaces/Datamodel";
import {
mergeConfig, BehaviorMapValidator,
BehaviorValueValidator, BehaviorEnumValidator
} from "./common/Utils";
BaseTelemetryPlugin, IAppInsightsCore, IConfiguration, ICustomProperties, IPlugin, IProcessTelemetryContext,
IProcessTelemetryUnloadContext, ITelemetryItem, ITelemetryPluginChain, ITelemetryUnloadState, _eInternalMessageId, _throwInternal,
arrForEach, dumpObj, eLoggingSeverity, getExceptionName, isNullOrUndefined, throwError, unloadComponents
} from "@microsoft/applicationinsights-core-js";
import { PropertiesPlugin } from "@microsoft/applicationinsights-properties-js";
import { IAutoCaptureHandler, IClickAnalyticsConfiguration, IContentHandler, IPageActionTelemetry } from "./Interfaces/Datamodel";
import { BehaviorEnumValidator, BehaviorMapValidator, BehaviorValueValidator, mergeConfig } from "./common/Utils";
import { PageAction } from "./events/PageAction";
import { AutoCaptureHandler } from "./handlers/AutoCaptureHandler";
import { DomContentHandler } from "./handlers/DomContentHandler";
import { PropertiesPlugin } from "@microsoft/applicationinsights-properties-js";
export { BehaviorMapValidator, BehaviorValueValidator, BehaviorEnumValidator }
export class ClickAnalyticsPlugin extends BaseTelemetryPlugin {
public identifier: string = "ClickAnalyticsPlugin";
public priority: number = 181;
public static Version = "2.8.4";
public static Version = "#version#";
constructor() {
super();
@ -132,4 +125,4 @@ export class ClickAnalyticsPlugin extends BaseTelemetryPlugin {
public trackPageAction(pageAction?: IPageActionTelemetry, customProperties?: ICustomProperties) {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
}
}

Просмотреть файл

@ -1,13 +1,10 @@
/**
* @copyright Microsoft 2020
*/
* @copyright Microsoft 2020
*/
import {
getLocation, getDocument, getWindow, hasDocument, isFunction
} from "@microsoft/applicationinsights-core-js";
import { findClosestAnchor, isValueAssigned } from "./common/Utils";
import { getDocument, getLocation, getWindow, hasDocument, isFunction } from "@microsoft/applicationinsights-core-js";
import { IClickAnalyticsConfiguration, IOverrideValues } from "./Interfaces/Datamodel";
import { findClosestAnchor, isValueAssigned } from "./common/Utils";
var clickCaptureInputTypes = { BUTTON: true, CHECKBOX: true, RADIO: true, RESET: true, SUBMIT: true };
@ -149,4 +146,4 @@ export function getUri(config: IClickAnalyticsConfiguration, location: any): str
return config.coreData.requestUri;
}
return sanitizeUrl(config, location);
}
}

Просмотреть файл

@ -289,4 +289,4 @@ export interface IPageActionTelemetry extends IEventTelemetry {
* Content Id (Parent Id) of the parent in which the content was located;
*/
parentId?: string;
}
}

Просмотреть файл

@ -1,25 +1,34 @@
/**
* @copyright Microsoft 2020
* File containing utility functions.
*/
* @copyright Microsoft 2020
* File containing utility functions.
*/
import { isNullOrUndefined, _InternalMessageId, hasDocument, hasOwnProperty, arrForEach } from "@microsoft/applicationinsights-core-js";
import {
IClickAnalyticsConfiguration
} from "../Interfaces/Datamodel";
_InternalMessageId, _eInternalMessageId, arrForEach, createEnumStyle, hasDocument, hasOwnProperty, isNullOrUndefined, objExtend
} from "@microsoft/applicationinsights-core-js";
import { IClickAnalyticsConfiguration } from "../Interfaces/Datamodel";
const Prototype = "prototype";
const DEFAULT_DONOT_TRACK_TAG = "ai-dnt";
const DEFAULT_AI_BLOB_ATTRIBUTE_TAG = "ai-blob";
const DEFAULT_DATA_PREFIX = "data-";
export const enum _eExtendedInternalMessageId {
CannotParseAiBlobValue = 101,
InvalidContentBlob = 102,
TrackPageActionEventFailed = 103
}
export const _ExtendedInternalMessageId = {
..._InternalMessageId,
CannotParseAiBlobValue: 101,
InvalidContentBlob: 102,
TrackPageActionEventFailed: 103
};
...createEnumStyle<typeof _eExtendedInternalMessageId>({
CannotParseAiBlobValue: _eExtendedInternalMessageId.CannotParseAiBlobValue,
InvalidContentBlob: _eExtendedInternalMessageId.InvalidContentBlob,
TrackPageActionEventFailed: _eExtendedInternalMessageId.TrackPageActionEventFailed
})
}
export type _ExtendedInternalMessageId = number | _eExtendedInternalMessageId | _eInternalMessageId;
/**
* Finds attributes in overrideConfig which are invalid or should be objects
@ -30,7 +39,7 @@ export const _ExtendedInternalMessageId = {
export function removeNonObjectsAndInvalidElements(overrideConfig: IClickAnalyticsConfiguration, attributeNamesExpectedObjects: Array<string>): void {
removeInvalidElements(overrideConfig);
for (var i in attributeNamesExpectedObjects) {
if (attributeNamesExpectedObjects.hasOwnProperty(i)) {
if (hasOwnProperty(attributeNamesExpectedObjects, i)) {
var objectName = attributeNamesExpectedObjects[i];
if (typeof overrideConfig[objectName] === "object") {
removeInvalidElements(overrideConfig[objectName]);
@ -258,54 +267,6 @@ export function bracketIt(str: string): string {
return "[" + str + "]";
}
/**
* Pass in the objects to merge as arguments.
* @param obj1 - object to merge. Set this argument to 'true' for a deep extend.
* @param obj2 - object to merge.
* @param obj3 - object to merge.
* @param obj4 - object to merge.
* @param obj5 - object to merge.
* @returns The extended object.
*/
export function extend(obj?: any, obj2?: any, obj3?: any, obj4?: any, obj5?: any): any {
// Variables
var extended = {};
var deep = false;
var i = 0;
var length = arguments.length;
var objProto = Object[Prototype];
var theArgs = arguments;
// Check if a deep merge
if (objProto.toString.call(theArgs[0]) === "[object Boolean]") {
deep = theArgs[0];
i++;
}
// Merge the object into the extended object
var merge = (obj: Object) => {
for (var prop in obj) {
if (hasOwnProperty(obj, prop)) {
// If deep merge and property is an object, merge properties
if (deep && objProto.toString.call(obj[prop]) === "[object Object]") {
extended[prop] = extend(true, extended[prop], obj[prop]);
} else {
extended[prop] = obj[prop];
}
}
}
};
// Loop through each object and conduct a merge
for (; i < length; i++) {
var obj = theArgs[i];
merge(obj);
}
return extended;
}
export function validateContentNamePrefix ( config: IClickAnalyticsConfiguration, defaultDataPrefix: string) {
return isValueAssigned(config.dataTags.customDataPrefix) && (config.dataTags.customDataPrefix.indexOf(defaultDataPrefix) === 0);
}
@ -355,7 +316,7 @@ export function mergeConfig(overrideConfig: IClickAnalyticsConfiguration): IClic
if(isValueAssigned(overrideConfig.dataTags)) {
overrideConfig.dataTags.customDataPrefix = validateContentNamePrefix(overrideConfig, DEFAULT_DATA_PREFIX) ? overrideConfig.dataTags.customDataPrefix : DEFAULT_DATA_PREFIX;
}
return extend(true, defaultConfig, overrideConfig);
return objExtend(true, defaultConfig, overrideConfig);
}
}
@ -380,5 +341,3 @@ export function BehaviorValueValidator (behaviorArray: string[]) {
export function BehaviorEnumValidator (enumObj: any) {
return (key: string) => enumObj[key] || "";
}

Просмотреть файл

@ -1,15 +1,18 @@
/**
* @copyright Microsoft 2020
*/
* @copyright Microsoft 2020
*/
import dynamicProto from "@microsoft/dynamicproto-js";
import { WebEvent } from "./WebEvent";
import * as DataCollector from "../DataCollector";
import { ITelemetryItem, getPerformance, ICustomProperties, eLoggingSeverity, _eInternalMessageId, objForEachKey, IDiagnosticLogger, _throwInternal } from "@microsoft/applicationinsights-core-js"
import { IClickAnalyticsConfiguration, IContentHandler, IPageActionOverrideValues, IPageActionTelemetry } from "../Interfaces/Datamodel";
import { extractFieldFromObject, bracketIt, isValueAssigned, extend } from "../common/Utils";
import { strNotSpecified } from "@microsoft/applicationinsights-common";
import {
ICustomProperties, IDiagnosticLogger, ITelemetryItem, _eInternalMessageId, _throwInternal, eLoggingSeverity, getPerformance, objExtend,
objForEachKey
} from "@microsoft/applicationinsights-core-js";
import { ClickAnalyticsPlugin } from "../ClickAnalyticsPlugin";
import { getClickTarget } from "../DataCollector";
import { IClickAnalyticsConfiguration, IContentHandler, IPageActionOverrideValues, IPageActionTelemetry } from "../Interfaces/Datamodel";
import { bracketIt, extractFieldFromObject, isValueAssigned } from "../common/Utils";
import { WebEvent } from "./WebEvent";
export class PageAction extends WebEvent {
@ -84,7 +87,7 @@ export class PageAction extends WebEvent {
}
// Fill PartB
if (element) {
pageActionEvent.targetUri = DataCollector.getClickTarget(element);
pageActionEvent.targetUri = getClickTarget(element);
elementContent = _self._contentHandler.getElementContent(element); // collect id,cn tags
@ -116,7 +119,7 @@ export class PageAction extends WebEvent {
}
_sanitizePageActionEventContent(elementContent);
pageActionEvent.content = bracketIt(JSON.stringify(extend(
pageActionEvent.content = bracketIt(JSON.stringify(objExtend(
elementContent,
overrideValues && overrideValues.contentTags ? overrideValues.contentTags : {})));

Просмотреть файл

@ -1,15 +1,17 @@
/**
* @copyright Microsoft 2020
*/
* @copyright Microsoft 2020
*/
import dynamicProto from "@microsoft/dynamicproto-js";
import {
isValueAssigned, extend
} from "../common/Utils";
import * as DataCollector from "../DataCollector";
import { IDiagnosticLogger, getLocation, hasWindow, IUnloadableComponent, IProcessTelemetryUnloadContext, ITelemetryUnloadState } from "@microsoft/applicationinsights-core-js";
import { IClickAnalyticsConfiguration, IPageTags, IOverrideValues, IContentHandler, ICoreData, IPageActionTelemetry } from "../Interfaces/Datamodel";
IDiagnosticLogger, IProcessTelemetryUnloadContext, ITelemetryUnloadState, IUnloadableComponent, getLocation, hasWindow, objExtend
} from "@microsoft/applicationinsights-core-js";
import { ClickAnalyticsPlugin } from "../ClickAnalyticsPlugin";
import { getPageName, getUri } from "../DataCollector";
import {
IClickAnalyticsConfiguration, IContentHandler, ICoreData, IOverrideValues, IPageActionTelemetry, IPageTags
} from "../Interfaces/Datamodel";
import { isValueAssigned } from "../common/Utils";
export class WebEvent implements IUnloadableComponent {
@ -56,10 +58,10 @@ export class WebEvent implements IUnloadableComponent {
_self.setBasicProperties = (event: IPageActionTelemetry, overrideValues: IOverrideValues) => {
if (!isValueAssigned(event.name)) {
event.pageName = DataCollector.getPageName(_self._config, overrideValues);
event.pageName = getPageName(_self._config, overrideValues);
}
if (!isValueAssigned(event.uri) && hasWindow) {
event.uri = DataCollector.getUri(_self._config, getLocation());
event.uri = getUri(_self._config, getLocation());
}
};
@ -93,10 +95,10 @@ export class WebEvent implements IUnloadableComponent {
// Prepare the pageTags object that is mostly the same for all events. Event specific pageTags will be added inside event constructors.
if (_self._pageTagsCallback) {
_self._pageTags = extend(true, _self._pageTags, _self._pageTagsCallback());
_self._pageTags = objExtend(true, _self._pageTags, _self._pageTagsCallback());
}
if (isValueAssigned(overrideValues.pageTags)) {
_self._pageTags = extend(true, _self._pageTags, overrideValues.pageTags);
_self._pageTags = objExtend(true, _self._pageTags, overrideValues.pageTags);
}
// If metadata is present add it to pageTags property
if (_self._metaTags) {

Просмотреть файл

@ -1,16 +1,16 @@
/**
* @copyright Microsoft 2020
*/
* @copyright Microsoft 2020
*/
import dynamicProto from "@microsoft/dynamicproto-js";
import {
IDiagnosticLogger, getWindow, getDocument, isNullOrUndefined, IProcessTelemetryUnloadContext, ITelemetryUnloadState,
mergeEvtNamespace, createUniqueNamespace, eventOn, eventOff
IDiagnosticLogger, IProcessTelemetryUnloadContext, ITelemetryUnloadState, createUniqueNamespace, eventOff, eventOn, getDocument,
getWindow, isNullOrUndefined, mergeEvtNamespace
} from "@microsoft/applicationinsights-core-js";
import { IAutoCaptureHandler, IPageActionOverrideValues, IClickAnalyticsConfiguration } from "../Interfaces/Datamodel"
import { isRightClick, isLeftClick, isKeyboardEnter, isKeyboardSpace, isMiddleClick, isElementDnt } from "../common/Utils";
import { ActionType } from "../Enums";
import { ClickAnalyticsPlugin } from "../ClickAnalyticsPlugin";
import { ActionType } from "../Enums";
import { IAutoCaptureHandler, IClickAnalyticsConfiguration, IPageActionOverrideValues } from "../Interfaces/Datamodel";
import { isElementDnt, isKeyboardEnter, isKeyboardSpace, isLeftClick, isMiddleClick, isRightClick } from "../common/Utils";
import { PageAction } from "../events/PageAction";
const clickCaptureInputTypes = { BUTTON: true, CHECKBOX: true, RADIO: true, RESET: true, SUBMIT: true };
@ -118,4 +118,4 @@ export class AutoCaptureHandler implements IAutoCaptureHandler {
public _doUnload(unloadCtx?: IProcessTelemetryUnloadContext, unloadState?: ITelemetryUnloadState, asyncCallback?: () => void): void | boolean {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
}
}

Просмотреть файл

@ -1,15 +1,13 @@
/**
* @copyright Microsoft 2020
*/
* @copyright Microsoft 2020
*/
import dynamicProto from "@microsoft/dynamicproto-js";
import {
removeInvalidElements,
walkUpDomChainWithElementValidation,
extend, isValueAssigned
} from "../common/Utils";
import { IDiagnosticLogger, eLoggingSeverity, getDocument, isNullOrUndefined, hasDocument, _throwInternal, _eInternalMessageId } from "@microsoft/applicationinsights-core-js";
IDiagnosticLogger, _eInternalMessageId, _throwInternal, eLoggingSeverity, getDocument, hasDocument, isNullOrUndefined, objExtend
} from "@microsoft/applicationinsights-core-js";
import { IClickAnalyticsConfiguration, IContent, IContentHandler } from "../Interfaces/Datamodel";
import { isValueAssigned, removeInvalidElements, walkUpDomChainWithElementValidation } from "../common/Utils";
const MAX_CONTENTNAME_LENGTH = 200;
@ -64,16 +62,16 @@ export class DomContentHandler implements IContentHandler {
} else {
// traverse up the DOM to find the closest parent with data-* tag defined
//contentElement = walkUpDomChainWithElementValidation(element, _self._isTracked, dataTagPrefix);
elementContent = extend(elementContent, _populateElementContent(element, dataTagPrefix, parentDataTagPrefix, aiBlobAttributeTag));
elementContent = objExtend(elementContent, _populateElementContent(element, dataTagPrefix, parentDataTagPrefix, aiBlobAttributeTag));
}
} else {
elementContent = extend(elementContent, _populateElementContentwithDataTag(element, dataTagPrefix, parentDataTagPrefix, aiBlobAttributeTag));
elementContent = objExtend(elementContent, _populateElementContentwithDataTag(element, dataTagPrefix, parentDataTagPrefix, aiBlobAttributeTag));
}
removeInvalidElements(elementContent);
if (parentDataTagPrefix) {
elementContent = extend(elementContent, _getParentDetails(element, elementContent, dataTagPrefix, aiBlobAttributeTag ));
elementContent = objExtend(elementContent, _getParentDetails(element, elementContent, dataTagPrefix, aiBlobAttributeTag ));
}
return elementContent;

Просмотреть файл

@ -20,7 +20,9 @@
"test": "",
"lint": "tslint -p tsconfig.json",
"dtsgen": "api-extractor run --local && node ../../scripts/dtsgen.js 'Microsoft.ApplicationInsights'",
"sri": "node ../../tools/subResourceIntegrity/generateIntegrityFile.js"
"sri": "node ../../tools/subResourceIntegrity/generateIntegrityFile.js",
"ai-min": "grunt debugplugin-min",
"ai-restore": "grunt debugplugin-restore"
},
"devDependencies": {
"@microsoft/applicationinsights-rollup-plugin-uglify3-js": "1.0.0",

Просмотреть файл

@ -1,17 +1,16 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import dynamicProto from "@microsoft/dynamicproto-js";
import {
BaseTelemetryPlugin, IConfiguration, arrForEach,
IAppInsightsCore, IPlugin, ITelemetryItem, IProcessTelemetryContext, _InternalLogMessage,
ITelemetryPluginChain, InstrumentFunc, IInstrumentCallDetails, InstrumentorHooksCallback, IPerfEvent, IChannelControls,
objForEachKey, isFunction, dateNow, isArray, isUndefined, getDebugExt, arrIndexOf
BaseTelemetryPlugin, IAppInsightsCore, IChannelControls, IConfiguration, IInstrumentCallDetails, IPerfEvent, IPlugin,
IProcessTelemetryContext, ITelemetryItem, ITelemetryPluginChain, InstrumentFunc, InstrumentorHooksCallback, arrForEach, arrIndexOf,
dateNow, getDebugExt, isArray, isFunction, isUndefined, objForEachKey
} from "@microsoft/applicationinsights-core-js";
import { Dashboard } from "./components/Dashboard";
import { DebugBin, DebugBinParent } from "./components/debugBins";
import { getTargetName } from "./components/helpers";
import { permStyle } from "./components/styleNodeSrc";
import { DebugBin, DebugBinParent } from "./components/debugBins";
import dynamicProto from "@microsoft/dynamicproto-js";
import { IDebugPluginConfig } from "./interfaces/IDebugPluginConfig";
interface IDebugConfig {
@ -386,4 +385,4 @@ export default class DebugPlugin extends BaseTelemetryPlugin {
processTelemetry(event: ITelemetryItem, itemCtx?: IProcessTelemetryContext) {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
}
}

Просмотреть файл

@ -1,9 +1,9 @@
import { arrForEach, arrIndexOf } from "@microsoft/applicationinsights-core-js";
import dynamicProto from "@microsoft/dynamicproto-js";
import { tempStyle } from "./styleNodeSrc";
import { FilterList } from "./filterList";
import { arrForEach, arrIndexOf } from "@microsoft/applicationinsights-core-js";
import { LogEntry } from "./LogEntry";
import { FilterList } from "./filterList";
import { copySelectedTree } from "./helpers";
import { tempStyle } from "./styleNodeSrc";
export interface IDashboardConfig {
prefix: string;
@ -285,4 +285,4 @@ export class Dashboard {
public hide(): void {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
}
}

Просмотреть файл

@ -1,6 +1,6 @@
import { isBoolean, isNumber, isObject, isString, objToString } from "@microsoft/applicationinsights-core-js";
import { makeRegex, traverseAndReplace, toggleClassName, MAX_DEPTH, formatLogElements, getTargetName, getTargetKeys } from "./helpers";
import { Util } from "@microsoft/applicationinsights-common";
import { isBoolean, isNumber, isObject, isString, objToString } from "@microsoft/applicationinsights-core-js";
import { MAX_DEPTH, formatLogElements, getTargetKeys, getTargetName, makeRegex, toggleClassName, traverseAndReplace } from "./helpers";
export class LogEntry {
isKeep: () => boolean;
@ -101,4 +101,3 @@ export class LogEntry {
}
}
}

Просмотреть файл

@ -122,4 +122,4 @@ export class DebugBin {
_self.elValue.className = "el-value incremented";
setTimeout(() => _self.elValue.className = "el-value", 1);
}
}
}

Просмотреть файл

@ -125,4 +125,4 @@ export class FilterList {
getCurrentFilter = () => {
return this.filterList;
}
}
}

Просмотреть файл

@ -1,8 +1,10 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import { arrForEach, arrIndexOf, hasOwnProperty, isFunction, isObject, isString, isSymbol, objKeys } from "@microsoft/applicationinsights-core-js";
import { Util } from "@microsoft/applicationinsights-common";
import {
arrForEach, arrIndexOf, hasOwnProperty, isFunction, isObject, isString, isSymbol, objKeys
} from "@microsoft/applicationinsights-core-js";
import { strShimPrototype } from "@microsoft/applicationinsights-shims";
const strConstructor = "constructor";

Просмотреть файл

@ -1,5 +1,6 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// @skip-file-minify
import { Util } from "@microsoft/applicationinsights-common";

Просмотреть файл

@ -18,9 +18,12 @@
"build:browser": "rollup -c",
"rebuild": "npm run build",
"test": "grunt depstest",
"mintest": "grunt deps-mintest",
"lint": "tslint -p tsconfig.json",
"dtsgen": "api-extractor run --local && node ../../scripts/dtsgen.js \"Microsoft Application Insights XHR dependencies plugin\"",
"sri": "node ../../tools/subResourceIntegrity/generateIntegrityFile.js"
"sri": "node ../../tools/subResourceIntegrity/generateIntegrityFile.js",
"ai-min": "grunt deps-min",
"ai-restore": "grunt deps-restore"
},
"devDependencies": {
"@microsoft/ai-test-framework": "0.0.1",

Просмотреть файл

@ -0,0 +1,13 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// Note: DON'T Export these const from the package as we are still targeting ES3 this will export a mutable variables that someone could change!!!
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// Generally you should only put values that are used more than 2 times and then only if not already exposed as a constant (such as SdkCoreNames)
// as when using "short" named values from here they will be will be minified smaller than the SdkCoreNames[eSdkCoreNames.xxxx] value.
export const STR_DURATION = "duration";
export const STR_PROPERTIES = "properties";

Просмотреть файл

@ -1,22 +1,23 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import dynamicProto from "@microsoft/dynamicproto-js";
import {
RequestHeaders, CorrelationIdHelper, createTelemetryItem, ICorrelationConfig,
RemoteDependencyData, dateTimeUtilsNow, DisabledPropertyName, IDependencyTelemetry,
IConfig, ITelemetryContext, PropertiesPluginIdentifier, eDistributedTracingModes, IRequestContext, isInternalApplicationInsightsEndpoint,
eRequestHeaders, formatTraceParent, createTraceParent, createDistributedTraceContextFromTrace
CorrelationIdHelper, DisabledPropertyName, IConfig, ICorrelationConfig, IDependencyTelemetry, IRequestContext, ITelemetryContext,
PropertiesPluginIdentifier, RemoteDependencyData, RequestHeaders, createDistributedTraceContextFromTrace, createTelemetryItem,
createTraceParent, dateTimeUtilsNow, eDistributedTracingModes, eRequestHeaders, formatTraceParent, isInternalApplicationInsightsEndpoint
} from "@microsoft/applicationinsights-common";
import {
isNullOrUndefined, arrForEach, isString, strTrim, isFunction, eLoggingSeverity, _eInternalMessageId,
IAppInsightsCore, BaseTelemetryPlugin, ITelemetryPluginChain, IConfiguration, IPlugin, ITelemetryItem, IProcessTelemetryContext,
getLocation, getGlobal, strPrototype, IInstrumentCallDetails, InstrumentFunc, InstrumentProto, getPerformance,
IInstrumentHooksCallbacks, objForEachKey, generateW3CId, getIEVersion, dumpObj, ICustomProperties, isXhrSupported, eventOn,
mergeEvtNamespace, createUniqueNamespace, createProcessTelemetryContext, _throwInternal, IDistributedTraceContext, getExceptionName
BaseTelemetryPlugin, IAppInsightsCore, IConfiguration, ICustomProperties, IDistributedTraceContext, IInstrumentCallDetails,
IInstrumentHooksCallbacks, IPlugin, IProcessTelemetryContext, ITelemetryItem, ITelemetryPluginChain, InstrumentFunc, InstrumentProto,
_eInternalMessageId, _throwInternal, arrForEach, createProcessTelemetryContext, createUniqueNamespace, deepFreeze, dumpObj,
eLoggingSeverity, eventOn, generateW3CId, getExceptionName, getGlobal, getIEVersion, getLocation, getPerformance, isFunction,
isNullOrUndefined, isString, isXhrSupported, mergeEvtNamespace, objForEachKey, strPrototype, strTrim
} from "@microsoft/applicationinsights-core-js";
import { ajaxRecord, IAjaxRecordResponse } from "./ajaxRecord";
import dynamicProto from "@microsoft/dynamicproto-js";
import { DependencyListenerFunction, IDependencyListenerContainer, IDependencyListenerDetails, IDependencyListenerHandler } from "./DependencyListener";
import {
DependencyListenerFunction, IDependencyListenerContainer, IDependencyListenerDetails, IDependencyListenerHandler
} from "./DependencyListener";
import { IAjaxRecordResponse, ajaxRecord } from "./ajaxRecord";
const AJAX_MONITOR_PREFIX = "ai.ajxmn.";
const strDiagLog = "diagLog";
@ -178,6 +179,13 @@ export interface XMLHttpRequestInstrumented extends XMLHttpRequest {
ajaxData: ajaxRecord;
}
export const DfltAjaxCorrelationHeaderExDomains = deepFreeze([
"*.blob.core.windows.net",
"*.blob.core.chinacloudapi.cn",
"*.blob.core.cloudapi.de",
"*.blob.core.usgovcloudapi.net"
]);
export interface IDependenciesPlugin extends IDependencyListenerContainer {
/**
* Logs dependency call
@ -202,11 +210,7 @@ export class AjaxMonitor extends BaseTelemetryPlugin implements IDependenciesPlu
excludeRequestFromAutoTrackingPatterns: undefined,
disableCorrelationHeaders: false,
distributedTracingMode: eDistributedTracingModes.AI_AND_W3C,
correlationHeaderExcludedDomains: [
"*.blob.core.windows.net",
"*.blob.core.chinacloudapi.cn",
"*.blob.core.cloudapi.de",
"*.blob.core.usgovcloudapi.net"],
correlationHeaderExcludedDomains: DfltAjaxCorrelationHeaderExDomains,
correlationHeaderDomains: undefined,
correlationHeaderExcludePatterns: undefined,
appId: undefined,
@ -302,20 +306,21 @@ export class AjaxMonitor extends BaseTelemetryPlugin implements IDependenciesPlu
if (!init) {
init = {};
}
// init headers override original request headers
// so, if they exist use only them, otherwise use request's because they should have been applied in the first place
// not using original request headers will result in them being lost
init.headers = new Headers(init.headers || (input instanceof Request ? (input.headers || {}) : {}));
let headers = new Headers(init.headers || (input instanceof Request ? (input.headers || {}) : {}));
if (_isUsingAIHeaders) {
const id = "|" + ajaxData.traceID + "." + ajaxData.spanID;
init.headers.set(RequestHeaders[eRequestHeaders.requestIdHeader], id);
headers.set(RequestHeaders[eRequestHeaders.requestIdHeader], id);
if (_enableRequestHeaderTracking) {
ajaxData.requestHeaders[RequestHeaders[eRequestHeaders.requestIdHeader]] = id;
}
}
const appId: string = _config.appId ||(_context && _context.appId());
if (appId) {
init.headers.set(RequestHeaders[eRequestHeaders.requestContextHeader], RequestHeaders[eRequestHeaders.requestContextAppIdFormat] + appId);
headers.set(RequestHeaders[eRequestHeaders.requestContextHeader], RequestHeaders[eRequestHeaders.requestContextAppIdFormat] + appId);
if (_enableRequestHeaderTracking) {
ajaxData.requestHeaders[RequestHeaders[eRequestHeaders.requestContextHeader]] = RequestHeaders[eRequestHeaders.requestContextAppIdFormat] + appId;
}
@ -327,11 +332,13 @@ export class AjaxMonitor extends BaseTelemetryPlugin implements IDependenciesPlu
}
const traceParent = formatTraceParent(createTraceParent(ajaxData.traceID, ajaxData.spanID, traceFlags));
init.headers.set(RequestHeaders[eRequestHeaders.traceParentHeader], traceParent);
headers.set(RequestHeaders[eRequestHeaders.traceParentHeader], traceParent);
if (_enableRequestHeaderTracking) {
ajaxData.requestHeaders[RequestHeaders[eRequestHeaders.traceParentHeader]] = traceParent;
}
}
init.headers = headers;
}
return init;
@ -552,7 +559,7 @@ export class AjaxMonitor extends BaseTelemetryPlugin implements IDependenciesPlu
if (_enableResponseHeaderTracking) {
const responseHeaderMap = {};
response.headers.forEach((value: string, name: string) => {
response.headers.forEach((value: string, name: string) => { // @skip-minify
if (_canIncludeHeaders(name)) {
responseHeaderMap[name] = value;
}
@ -1046,7 +1053,7 @@ export class AjaxMonitor extends BaseTelemetryPlugin implements IDependenciesPlu
let requestHeaders = {};
if (_enableRequestHeaderTracking) {
let headers = new Headers((init ? init.headers : 0) || (input instanceof Request ? (input.headers || {}) : {}));
headers.forEach((value, key) => {
headers.forEach((value, key) => { // @skip-minify
if (_canIncludeHeaders(key)) {
requestHeaders[key] = value;
}

Просмотреть файл

@ -1,9 +1,14 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import { dataSanitizeUrl, dateTimeUtilsDuration, IDependencyTelemetry, urlGetAbsoluteUrl, urlGetCompleteUrl, msToTimeSpan } from "@microsoft/applicationinsights-common";
import { IDiagnosticLogger, objKeys, arrForEach, isNumber, isString, normalizeJsName, objForEachKey } from "@microsoft/applicationinsights-core-js";
import dynamicProto from "@microsoft/dynamicproto-js";
import {
IDependencyTelemetry, dataSanitizeUrl, dateTimeUtilsDuration, msToTimeSpan, urlGetAbsoluteUrl, urlGetCompleteUrl
} from "@microsoft/applicationinsights-common";
import {
IDiagnosticLogger, arrForEach, isNumber, isString, normalizeJsName, objForEachKey, objKeys
} from "@microsoft/applicationinsights-core-js";
import { STR_DURATION, STR_PROPERTIES } from "./InternalConstants";
export interface IAjaxRecordResponse {
statusText: string,
@ -14,8 +19,6 @@ export interface IAjaxRecordResponse {
response?: Object
}
let strProperties = "properties";
/** @ignore */
function _calcPerfDuration(resourceEntry:PerformanceResourceTiming, start:string, end:string) {
let result = 0;
@ -76,7 +79,7 @@ function _populatePerfData(ajaxData:ajaxRecord, dependency:IDependencyTelemetry)
*/
let resourceEntry = ajaxData.perfTiming;
let props = dependency[strProperties] || {};
let props = dependency.properties || {};
let propsSet = 0;
let strName = "name";
let strStart = "Start";
@ -86,7 +89,6 @@ function _populatePerfData(ajaxData:ajaxRecord, dependency:IDependencyTelemetry)
let strRedirect = "redirect";
let strRequest = "request";
let strResponse = "response";
let strDuration = "duration";
let strStartTime = "startTime";
let strDomainLookupStart = strDomainLookup + strStart;
let strDomainLookupEnd = strDomainLookup + strEnd;
@ -127,12 +129,12 @@ function _populatePerfData(ajaxData:ajaxRecord, dependency:IDependencyTelemetry)
propsSet |= _setPerfDuration(props, "sentRequest", resourceEntry, strRequestStart, strResponseEnd);
// PerfTotal / Duration
let duration = resourceEntry[strDuration];
let duration = resourceEntry.duration;
if (!duration) {
duration = _calcPerfDuration(resourceEntry, strStartTime, strResponseEnd) || 0;
}
propsSet |= _setPerfValue(props, strDuration, duration);
propsSet |= _setPerfValue(props, STR_DURATION, duration);
propsSet |= _setPerfValue(props, "perfTotal", duration);
var serverTiming = resourceEntry[strServerTiming];
@ -167,7 +169,7 @@ function _populatePerfData(ajaxData:ajaxRecord, dependency:IDependencyTelemetry)
}
if (propsSet) {
dependency[strProperties] = props;
dependency.properties = props;
}
}
@ -296,7 +298,7 @@ export class ajaxRecord {
success: (+(self.status)) >= 200 && (+(self.status)) < 400,
responseCode: (+(self.status)),
method: self.method,
[strProperties]: { HttpMethod: self.method }
[STR_PROPERTIES]: { HttpMethod: self.method }
} as IDependencyTelemetry;
if (self.requestSentTime) {
@ -310,8 +312,8 @@ export class ajaxRecord {
if (enableRequestHeaderTracking) {
if (objKeys(self.requestHeaders).length > 0) {
dependency[strProperties] = dependency[strProperties] || {};
dependency[strProperties].requestHeaders = self.requestHeaders;
let props = dependency.properties = dependency.properties || {};
props.requestHeaders = self.requestHeaders;
}
}
@ -327,19 +329,19 @@ export class ajaxRecord {
if (response.headerMap) {
if (objKeys(response.headerMap).length > 0) {
dependency[strProperties] = dependency[strProperties] || {};
dependency[strProperties].responseHeaders = response.headerMap;
let props = dependency.properties = dependency.properties || {};
props.responseHeaders = response.headerMap;
}
}
if (self.errorStatusText && self.status >= 400) {
const responseType = response.type;
dependency[strProperties] = dependency[strProperties] || {};
let props = dependency.properties = dependency.properties || {};
if (responseType === "" || responseType === "text") {
dependency[strProperties][strResponseText] = response[strResponseText] ? response.statusText + " - " + response[strResponseText] : response.statusText;
props.responseText = response.responseText ? response.statusText + " - " + response[strResponseText] : response.statusText;
}
if (responseType === "json") {
dependency[strProperties][strResponseText] = response.response ? response.statusText + " - " + JSON.stringify(response.response) : response.statusText;
props.responseText = response.response ? response.statusText + " - " + JSON.stringify(response.response) : response.statusText;
}
}
}
@ -365,4 +367,3 @@ export class ajaxRecord {
return null;
}
}

Просмотреть файл

@ -1,5 +1,5 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
export { AjaxMonitor as AjaxPlugin, IDependenciesPlugin, XMLHttpRequestInstrumented, IInstrumentationRequirements } from "./ajax";
export { AjaxMonitor as AjaxPlugin, IDependenciesPlugin, XMLHttpRequestInstrumented, IInstrumentationRequirements, DfltAjaxCorrelationHeaderExDomains } from "./ajax";
export { ajaxRecord } from "./ajaxRecord";

Просмотреть файл

@ -18,9 +18,12 @@
"build:browser": "rollup -c",
"rebuild": "npm run build",
"test": "grunt perfmarkmeasuretests",
"mintest": "grunt perfmarkmeasure-mintests",
"lint": "tslint -p tsconfig.json",
"dtsgen": "api-extractor run --local && node ../../scripts/dtsgen.js \"Microsoft Application Insights Performance Mark and Measure Manager plugin\"",
"sri": "node ../../tools/subResourceIntegrity/generateIntegrityFile.js"
"sri": "node ../../tools/subResourceIntegrity/generateIntegrityFile.js",
"ai-min": "grunt perfmarkmeasure-min",
"ai-restore": "grunt perfmarkmeasure-restore"
},
"devDependencies": {
"@microsoft/ai-test-framework": "0.0.1",

Просмотреть файл

@ -1,10 +1,10 @@
/**
* PerfMarkMeasureManager.ts
* @copyright Microsoft 2021
*/
* PerfMarkMeasureManager.ts
* @copyright Microsoft 2021
*/
import dynamicProto from "@microsoft/dynamicproto-js";
import { getPerformance, getSetValue, INotificationManager, IPerfEvent, PerfManager } from "@microsoft/applicationinsights-core-js"
import { INotificationManager, IPerfEvent, PerfManager, getPerformance, getSetValue } from "@microsoft/applicationinsights-core-js";
import { IPerfMarkMeasureConfiguration } from "./interfaces/IPerfMarkMeasureConfiguration";
// Names used in the perf Event context

Просмотреть файл

@ -18,9 +18,12 @@
"build:browser": "rollup -c",
"rebuild": "npm run build",
"test": "grunt propertiestests",
"mintest": "grunt properties-mintests",
"lint": "tslint -p tsconfig.json",
"dtsgen": "api-extractor run --local && node ../../scripts/dtsgen.js \"Microsoft Application Insights properties plugin\"",
"sri": "node ../../tools/subResourceIntegrity/generateIntegrityFile.js"
"sri": "node ../../tools/subResourceIntegrity/generateIntegrityFile.js",
"ai-min": "grunt properties-min",
"ai-restore": "grunt properties-restore"
},
"devDependencies": {
"@microsoft/ai-test-framework": "0.0.1",

Просмотреть файл

@ -4,7 +4,7 @@
import { IInternal } from "@microsoft/applicationinsights-common";
import { ITelemetryConfig } from "../Interfaces/ITelemetryConfig";
const Version = "2.8.4";
const Version = "#version#";
export class Internal implements IInternal {
@ -39,4 +39,4 @@ export class Internal implements IInternal {
constructor(config: ITelemetryConfig) {
this.sdkVersion = (config.sdkExtension && config.sdkExtension() ? config.sdkExtension() + "_" : "") + "javascript:" + Version;
}
}
}

Просмотреть файл

@ -4,8 +4,8 @@
import dynamicProto from "@microsoft/dynamicproto-js";
import { ISession, utlCanUseLocalStorage, utlGetLocalStorage, utlSetLocalStorage } from "@microsoft/applicationinsights-common";
import {
IDiagnosticLogger, _eInternalMessageId, eLoggingSeverity, IAppInsightsCore, ICookieMgr, safeGetCookieMgr, isFunction,
newId, dumpObj, getExceptionName, dateNow, safeGetLogger, _throwInternal
IAppInsightsCore, ICookieMgr, IDiagnosticLogger, _eInternalMessageId, _throwInternal, dateNow, dumpObj, eLoggingSeverity,
getExceptionName, isFunction, newId, safeGetCookieMgr, safeGetLogger
} from "@microsoft/applicationinsights-core-js";
const cookieNameConst = "ai_session";

Просмотреть файл

@ -1,8 +1,8 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import { ITelemetryTrace, ITraceState, dataSanitizeString } from "@microsoft/applicationinsights-common";
import { generateW3CId, getLocation, IDiagnosticLogger } from "@microsoft/applicationinsights-core-js";
import { ITelemetryTrace, ITraceState, dataSanitizeString } from "@microsoft/applicationinsights-common";
import { IDiagnosticLogger, generateW3CId, getLocation } from "@microsoft/applicationinsights-core-js";
export class TelemetryTrace implements ITelemetryTrace {
@ -23,4 +23,4 @@ export class TelemetryTrace implements ITelemetryTrace {
_self.name = dataSanitizeString(logger, name);
}
}
}

Просмотреть файл

@ -2,10 +2,11 @@
// Licensed under the MIT License.
import dynamicProto from "@microsoft/dynamicproto-js";
import { IUserContext, utlRemoveStorage } from "@microsoft/applicationinsights-common";
import {
IAppInsightsCore, ICookieMgr, _eInternalMessageId, _throwInternal, eLoggingSeverity, newId, safeGetCookieMgr, safeGetLogger, toISOString
} from "@microsoft/applicationinsights-core-js";
import { ITelemetryConfig } from "../Interfaces/ITelemetryConfig";
import { utlRemoveStorage, IUserContext } from "@microsoft/applicationinsights-common";
import { _eInternalMessageId, eLoggingSeverity, IAppInsightsCore, ICookieMgr, safeGetCookieMgr, safeGetLogger, newId, toISOString, _throwInternal } from "@microsoft/applicationinsights-core-js";
function _validateUserInput(id: string): boolean {
// Validate:

Просмотреть файл

@ -1,38 +1,43 @@
/**
* PropertiesPlugin.ts
* @copyright Microsoft 2018
*/
* PropertiesPlugin.ts
* @copyright Microsoft 2018
*/
import dynamicProto from "@microsoft/dynamicproto-js";
import {
BaseTelemetryPlugin, IConfiguration, isNullOrUndefined,
IAppInsightsCore, IPlugin, ITelemetryItem, IProcessTelemetryContext, _InternalLogMessage, eLoggingSeverity, _eInternalMessageId, getNavigator,
ITelemetryPluginChain, objForEachKey, getSetValue, _logInternalMessage, IProcessTelemetryUnloadContext, ITelemetryUnloadState, IDistributedTraceContext
BreezeChannelIdentifier, IConfig, IPropertiesPlugin, PageView, PropertiesPluginIdentifier, createDistributedTraceContextFromTrace
} from "@microsoft/applicationinsights-common";
import {
BaseTelemetryPlugin, IAppInsightsCore, IConfiguration, IDistributedTraceContext, IPlugin, IProcessTelemetryContext,
IProcessTelemetryUnloadContext, ITelemetryItem, ITelemetryPluginChain, ITelemetryUnloadState, _InternalLogMessage, _eInternalMessageId,
_logInternalMessage, createProcessTelemetryContext, eLoggingSeverity, getNavigator, getSetValue, isNullOrUndefined, objForEachKey
} from "@microsoft/applicationinsights-core-js";
import { TelemetryContext } from "./TelemetryContext";
import { PageView, IConfig, BreezeChannelIdentifier, PropertiesPluginIdentifier, IPropertiesPlugin, createDistributedTraceContextFromTrace } from "@microsoft/applicationinsights-common";
import { ITelemetryConfig } from "./Interfaces/ITelemetryConfig";
import { IPropTelemetryContext } from "./Interfaces/IPropTelemetryContext";
import { ITelemetryConfig } from "./Interfaces/ITelemetryConfig";
import { TelemetryContext } from "./TelemetryContext";
export default class PropertiesPlugin extends BaseTelemetryPlugin implements IPropertiesPlugin {
public static getDefaultConfig(): ITelemetryConfig {
let defaultValue: string;
let nullValue: any = null;
const defaultConfig: ITelemetryConfig = {
instrumentationKey: () => undefined,
accountId: () => null,
instrumentationKey: () => defaultValue,
accountId: () => nullValue,
sessionRenewalMs: () => 30 * 60 * 1000,
samplingPercentage: () => 100,
sessionExpirationMs: () => 24 * 60 * 60 * 1000,
cookieDomain: () => null,
sdkExtension: () => null,
cookieDomain: () => nullValue,
sdkExtension: () => nullValue,
isBrowserLinkTrackingEnabled: () => false,
appId: () => null,
getSessionId: () => null,
namePrefix: () => undefined,
sessionCookiePostfix: () => undefined,
userCookiePostfix: () => undefined,
appId: () => nullValue,
getSessionId: () => nullValue,
namePrefix: () => defaultValue,
sessionCookiePostfix: () => defaultValue,
userCookiePostfix: () => defaultValue,
idLength: () => 22,
getNewId: () => null
getNewId: () => nullValue
};
return defaultConfig;
@ -56,25 +61,7 @@ export default class PropertiesPlugin extends BaseTelemetryPlugin implements IPr
_self.initialize = (config: IConfiguration & IConfig, core: IAppInsightsCore, extensions: IPlugin[], pluginChain?:ITelemetryPluginChain) => {
_base.initialize(config, core, extensions, pluginChain);
let ctx = _self._getTelCtx();
let identifier = _self.identifier;
const defaultConfig: ITelemetryConfig = PropertiesPlugin.getDefaultConfig();
_extensionConfig = _extensionConfig || {} as ITelemetryConfig;
objForEachKey(defaultConfig, (field, value) => {
_extensionConfig[field] = () => ctx.getConfig(identifier, field, value() as any);
});
_previousTraceCtx = core.getTraceCtx(false);
_self.context = new TelemetryContext(core, _extensionConfig, _previousTraceCtx);
_distributedTraceCtx = createDistributedTraceContextFromTrace(_self.context.telemetryTrace, _previousTraceCtx);
core.setTraceCtx(_distributedTraceCtx);
_self.context.appId = () => {
let breezeChannel = core.getPlugin<IPlugin>(BreezeChannelIdentifier);
return breezeChannel ? breezeChannel.plugin["_appId"] : null;
};
// Test hook to allow accessing the internal values -- explicitly not defined as an available property on the class
_self["_extConfig"] = _extensionConfig;
_populateDefaults(config);
};
/**
@ -135,6 +122,30 @@ export default class PropertiesPlugin extends BaseTelemetryPlugin implements IPr
_previousTraceCtx = null;
}
function _populateDefaults(config: IConfiguration) {
let identifier = _self.identifier;
let core = _self.core;
let ctx = createProcessTelemetryContext(null, config, core);
const defaultConfig: ITelemetryConfig = PropertiesPlugin.getDefaultConfig();
_extensionConfig = _extensionConfig || {} as ITelemetryConfig;
objForEachKey(defaultConfig, (field, value) => {
_extensionConfig[field] = () => ctx.getConfig(identifier, field, value());
});
_previousTraceCtx = core.getTraceCtx(false);
_self.context = new TelemetryContext(core, _extensionConfig, _previousTraceCtx);
_distributedTraceCtx = createDistributedTraceContextFromTrace(_self.context.telemetryTrace, _previousTraceCtx);
core.setTraceCtx(_distributedTraceCtx);
_self.context.appId = () => {
let breezeChannel = core.getPlugin<IPlugin>(BreezeChannelIdentifier);
return breezeChannel ? breezeChannel.plugin["_appId"] : null;
};
// Test hook to allow accessing the internal values -- explicitly not defined as an available property on the class
_self["_extConfig"] = _extensionConfig;
}
function _processTelemetryInternal(evt: ITelemetryItem, itemCtx: IProcessTelemetryContext) {
// Set Part A fields
getSetValue(evt, "tags", []);

Просмотреть файл

@ -1,20 +1,26 @@
/**
* TelemetryContext.ts
* @copyright Microsoft 2018
*/
* TelemetryContext.ts
* @copyright Microsoft 2018
*/
import dynamicProto from "@microsoft/dynamicproto-js";
import { ITelemetryItem, IProcessTelemetryContext, IAppInsightsCore, isString, objKeys, hasWindow, _InternalLogMessage, setValue, getSetValue, IDistributedTraceContext } from "@microsoft/applicationinsights-core-js";
import { Session, _SessionManager } from "./Context/Session";
import { Extensions, IOperatingSystem, ITelemetryTrace, IWeb, CtxTagKeys, PageView, IApplication, IDevice, ILocation, IUserContext, IInternal, ISession } from "@microsoft/applicationinsights-common";
import {
CtxTagKeys, Extensions, IApplication, IDevice, IInternal, ILocation, IOperatingSystem, ISession, ITelemetryTrace, IUserContext, IWeb,
PageView
} from "@microsoft/applicationinsights-common";
import {
IAppInsightsCore, IDistributedTraceContext, IProcessTelemetryContext, ITelemetryItem, _InternalLogMessage, getSetValue, hasWindow,
isString, objKeys, setValue
} from "@microsoft/applicationinsights-core-js";
import { Application } from "./Context/Application";
import { Device } from "./Context/Device";
import { Internal } from "./Context/Internal";
import { User } from "./Context/User";
import { Location } from "./Context/Location";
import { ITelemetryConfig } from "./Interfaces/ITelemetryConfig";
import { Session, _SessionManager } from "./Context/Session";
import { TelemetryTrace } from "./Context/TelemetryTrace";
import { User } from "./Context/User";
import { IPropTelemetryContext } from "./Interfaces/IPropTelemetryContext";
import { ITelemetryConfig } from "./Interfaces/ITelemetryConfig";
const strExt = "ext";
const strTags = "tags";
@ -220,4 +226,4 @@ export class TelemetryContext implements IPropTelemetryContext {
public cleanUp(event:ITelemetryItem, itemCtx?: IProcessTelemetryContext): void {
// @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
}
}
}

Просмотреть файл

@ -19,7 +19,9 @@
"test": "jest --config test/jestconfig.json",
"test-watch": "jest --config test/jestconfig.json --watch",
"lint": "tslint -p tsconfig.json",
"dtsgen": "api-extractor run --local && node ../../scripts/dtsgen.js \"Microsoft Application Insights react plugin\""
"dtsgen": "api-extractor run --local && node ../../scripts/dtsgen.js \"Microsoft Application Insights react plugin\"",
"ai-min": "grunt react-min",
"ai-restore": "grunt react-restore"
},
"devDependencies": {
"@microsoft/ai-test-framework": "0.0.1",

Просмотреть файл

@ -1,20 +1,20 @@
/**
* ReactPlugin.ts
* @copyright Microsoft 2019
*/
* ReactPlugin.ts
* @copyright Microsoft 2019
*/
import dynamicProto from "@microsoft/dynamicproto-js";
import {
IConfig, IPageViewTelemetry, IMetricTelemetry, IAppInsights, IEventTelemetry, IExceptionTelemetry, ITraceTelemetry
IAppInsights, IConfig, IEventTelemetry, IExceptionTelemetry, IMetricTelemetry, IPageViewTelemetry, ITraceTelemetry
} from "@microsoft/applicationinsights-common";
import {
IPlugin, IConfiguration, IAppInsightsCore,
ITelemetryPlugin, BaseTelemetryPlugin, ITelemetryItem, IProcessTelemetryContext,
ITelemetryPluginChain, _eInternalMessageId, eLoggingSeverity, ICustomProperties, safeGetCookieMgr, ICookieMgr, arrForEach, proxyFunctions, IProcessTelemetryUnloadContext, ITelemetryUnloadState, isFunction, objDefineAccessors, _throwInternal
BaseTelemetryPlugin, IAppInsightsCore, IConfiguration, ICookieMgr, ICustomProperties, IPlugin, IProcessTelemetryContext,
IProcessTelemetryUnloadContext, ITelemetryItem, ITelemetryPlugin, ITelemetryPluginChain, ITelemetryUnloadState, _eInternalMessageId,
_throwInternal, arrForEach, eLoggingSeverity, isFunction, objDefineAccessors, proxyFunctions, safeGetCookieMgr
} from "@microsoft/applicationinsights-core-js";
import { IReactExtensionConfig } from './Interfaces/IReactExtensionConfig';
import { History, Location, Update } from "history";
import { IReactExtensionConfig } from './Interfaces/IReactExtensionConfig';
export default class ReactPlugin extends BaseTelemetryPlugin {
public priority = 185;
public identifier = 'ReactPlugin';

Просмотреть файл

@ -1,9 +1,9 @@
/**
* ReactPlugin.ts
* @copyright Microsoft 2019
*/
import { useState, useEffect, useRef, Dispatch, SetStateAction } from "react";
* ReactPlugin.ts
* @copyright Microsoft 2019
*/
import ReactPlugin from "./ReactPlugin";
import { Dispatch, SetStateAction, useEffect, useRef, useState } from "react";
export type AIReactCustomEvent<T> = Dispatch<SetStateAction<T>>;

Просмотреть файл

@ -1,6 +1,6 @@
import { useEffect, useRef } from "react";
import { dateNow, ICustomProperties } from "@microsoft/applicationinsights-core-js";
import ReactPlugin from "./ReactPlugin";
import { ICustomProperties, dateNow } from "@microsoft/applicationinsights-core-js";
import { useEffect, useRef } from "react";
interface ITrackedData {
hookTimestamp: number;

Просмотреть файл

@ -15,9 +15,12 @@
"build:package": "rollup -c",
"rebuild": "npm run build",
"test": "grunt reactnativetests",
"mintest": "grunt reactnative-mintests",
"testx": "npm run build:test && grunt reactnativetests",
"lint": "tslint -p tsconfig.json",
"dtsgen": "api-extractor run --local && node ../../scripts/dtsgen.js \"Microsoft Application Insights react native plugin\""
"dtsgen": "api-extractor run --local && node ../../scripts/dtsgen.js \"Microsoft Application Insights react native plugin\"",
"ai-min": "grunt reactnative-min",
"ai-restore": "grunt reactnative-restore"
},
"devDependencies": {
"@microsoft/ai-test-framework": "0.0.1",

Просмотреть файл

@ -1,33 +1,20 @@
/**
* ReactNativePlugin.ts
* @copyright Microsoft 2019
*/
* ReactNativePlugin.ts
* @copyright Microsoft 2019
*/
import {
ITelemetryPlugin,
ITelemetryItem,
IPlugin,
IAppInsightsCore,
eLoggingSeverity,
_eInternalMessageId,
BaseTelemetryPlugin,
IProcessTelemetryContext,//,
arrForEach,
dumpObj,
getExceptionName,
isObject,
hasOwnProperty,
isUndefined,
IProcessTelemetryUnloadContext,
ITelemetryUnloadState,
_throwInternal, _warnToConsole
} from "@microsoft/applicationinsights-core-js";
import { ConfigurationManager, IDevice, IExceptionTelemetry, IAppInsights, eSeverityLevel, AnalyticsPluginIdentifier } from "@microsoft/applicationinsights-common";
import DeviceInfo from "react-native-device-info";
import { INativeDevice, IReactNativePluginConfig } from "./Interfaces";
import dynamicProto from "@microsoft/dynamicproto-js";
import DeviceInfo from "react-native-device-info";
import {
AnalyticsPluginIdentifier, ConfigurationManager, IAppInsights, IDevice, IExceptionTelemetry, eSeverityLevel
} from "@microsoft/applicationinsights-common";
import {
BaseTelemetryPlugin, IAppInsightsCore, IPlugin, IProcessTelemetryContext, IProcessTelemetryUnloadContext, ITelemetryItem,
ITelemetryPlugin, ITelemetryUnloadState, _eInternalMessageId, _throwInternal, _warnToConsole, arrForEach, dumpObj, eLoggingSeverity,
getExceptionName, hasOwnProperty, isObject, isUndefined
} from "@microsoft/applicationinsights-core-js";
import { getGlobal, strShimUndefined } from "@microsoft/applicationinsights-shims";
import { INativeDevice, IReactNativePluginConfig } from "./Interfaces";
declare var global: Window;

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Просмотреть файл

@ -15,6 +15,7 @@
"rebuild": "npm run build",
"testx": "rush test --verbose",
"test": "node common/scripts/install-run-rush.js test --verbose",
"mintest": "node common/scripts/install-run-rush.js mintest --verbose",
"lint": "node common/scripts/install-run-rush.js lint --verbose",
"perftest": "node common/scripts/install-run-rush.js perftest --verbose",
"rollupes3": "grunt rollupes3",
@ -23,7 +24,9 @@
"setVersion": "node ./tools/release-tools/setVersion.js",
"purge": "node common/scripts/install-run-rush.js purge",
"fullClean": "git clean -xdf && npm install && rush update --recheck --full",
"fullCleanBuild": "npm run fullClean && npm run rebuild"
"fullCleanBuild": "npm run fullClean && npm run rebuild",
"ai-min": "node common/scripts/install-run-rush.js ai-min",
"ai-restore": "node common/scripts/install-run-rush.js ai-restore"
},
"repository": {
"type": "git",

Просмотреть файл

@ -18,9 +18,12 @@
"build:browser": "rollup -c",
"rebuild": "npm run build",
"test": "grunt commontest",
"mintest": "grunt common-mintest",
"lint": "tslint -p tsconfig.json",
"dtsgen": "api-extractor run --local && node ../../scripts/dtsgen.js \"Microsoft Application Insights Common JavaScript Library\"",
"sri": "node ../../tools/subResourceIntegrity/generateIntegrityFile.js"
"sri": "node ../../tools/subResourceIntegrity/generateIntegrityFile.js",
"ai-min": "grunt common-min",
"ai-restore": "grunt common-restore"
},
"devDependencies": {
"@microsoft/ai-test-framework": "0.0.1",

Просмотреть файл

@ -1,11 +1,9 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// @duplicate of https://github.com/microsoft/ApplicationInsights-node.js/blob/develop/Library/ConnectionStringParser.ts
import { ConnectionString, ConnectionStringKey } from "./Interfaces/ConnectionString";
import { DEFAULT_BREEZE_ENDPOINT } from "./Constants";
import { arrReduce, objKeys } from "@microsoft/applicationinsights-core-js";
import { DEFAULT_BREEZE_ENDPOINT } from "./Constants";
import { ConnectionString, ConnectionStringKey } from "./Interfaces/ConnectionString";
const _FIELDS_SEPARATOR = ";";
const _FIELD_KEY_VALUE_SEPARATOR = "=";

Просмотреть файл

@ -13,5 +13,6 @@ export const SampleRate = "sampleRate";
export const ProcessLegacy = "ProcessLegacy";
export const HttpMethod = "http.method";
export const DEFAULT_BREEZE_ENDPOINT = "https://dc.services.visualstudio.com";
export const DEFAULT_BREEZE_PATH = "/v2/track";
export const strNotSpecified = "not_specified";
export const strIkey = "iKey";

Просмотреть файл

@ -1,7 +1,7 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import { arrForEach, IPlugin, isString } from "@microsoft/applicationinsights-core-js";
import { IPlugin, arrForEach, isString } from "@microsoft/applicationinsights-core-js";
const strEmpty = "";

Просмотреть файл

@ -1,6 +1,6 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import { IConfiguration, isNullOrUndefined, ICustomProperties } from "@microsoft/applicationinsights-core-js";
import { IConfiguration, ICustomProperties, isNullOrUndefined } from "@microsoft/applicationinsights-core-js";
import { DistributedTracingModes } from "../Enums";
import { IRequestContext } from "./IRequestContext";

Просмотреть файл

@ -1,7 +1,10 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import { dumpObj, getExceptionName, getGlobal, getGlobalInst, IDiagnosticLogger, isNullOrUndefined, eLoggingSeverity, objForEachKey, _eInternalMessageId, _throwInternal } from "@microsoft/applicationinsights-core-js";
import {
IDiagnosticLogger, _eInternalMessageId, _throwInternal, dumpObj, eLoggingSeverity, getExceptionName, getGlobal, getGlobalInst,
isNullOrUndefined, objForEachKey
} from "@microsoft/applicationinsights-core-js";
import { StorageType } from "./Enums";
let _canUseLocalStorage: boolean = undefined;
@ -217,4 +220,4 @@ export function utlRemoveSessionStorage(logger: IDiagnosticLogger, name: string)
}
return false;
}
}

Просмотреть файл

@ -1,10 +1,10 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import { IDataPoint } from "../../Interfaces/Contracts/IDataPoint";
import { ISerializable } from "../../Interfaces/Telemetry/ISerializable";
import { FieldType } from "../../Enums";
import { DataPointType } from "../../Interfaces/Contracts/DataPointType";
import { IDataPoint } from "../../Interfaces/Contracts/IDataPoint";
import { ISerializable } from "../../Interfaces/Telemetry/ISerializable";
export class DataPoint implements IDataPoint, ISerializable {
@ -55,4 +55,4 @@ export class DataPoint implements IDataPoint, ISerializable {
* Standard deviation of the aggregated metric. Should not be set for a measurement.
*/
public stdDev: number;
}
}

Просмотреть файл

@ -1,7 +1,9 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import { IDiagnosticLogger, eLoggingSeverity, _eInternalMessageId, hasJSON, getJSON, objForEachKey, isObject, strTrim, _throwInternal } from "@microsoft/applicationinsights-core-js";
import {
IDiagnosticLogger, _eInternalMessageId, _throwInternal, eLoggingSeverity, getJSON, hasJSON, isObject, objForEachKey, strTrim
} from "@microsoft/applicationinsights-core-js";
export const enum DataSanitizerValues {
/**

Просмотреть файл

@ -1,12 +1,12 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import { IDiagnosticLogger, toISOString } from "@microsoft/applicationinsights-core-js";
import { strNotSpecified } from "../../Constants";
import { FieldType } from "../../Enums";
import { IBase } from "../../Interfaces/Contracts/IBase";
import { IEnvelope } from "../../Interfaces/Telemetry/IEnvelope";
import { dataSanitizeString } from "./DataSanitizer";
import { FieldType } from "../../Enums";
import { IDiagnosticLogger, toISOString } from "@microsoft/applicationinsights-core-js";
import { strNotSpecified } from "../../Constants";
export class Envelope implements IEnvelope {
@ -78,4 +78,4 @@ export class Envelope implements IEnvelope {
data: FieldType.Required
};
}
}
}

Просмотреть файл

@ -1,12 +1,12 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import { IDiagnosticLogger } from "@microsoft/applicationinsights-core-js";
import { strNotSpecified } from "../Constants";
import { FieldType } from "../Enums";
import { IEventData } from "../Interfaces/Contracts/IEventData";
import { ISerializable } from "../Interfaces/Telemetry/ISerializable";
import { dataSanitizeString, dataSanitizeProperties, dataSanitizeMeasurements } from "./Common/DataSanitizer";
import { FieldType } from "../Enums";
import { strNotSpecified } from "../Constants";
import { IDiagnosticLogger } from "@microsoft/applicationinsights-core-js";
import { dataSanitizeMeasurements, dataSanitizeProperties, dataSanitizeString } from "./Common/DataSanitizer";
export class Event implements IEventData, ISerializable {
public static envelopeType = "Microsoft.ApplicationInsights.{0}.Event";
@ -49,4 +49,4 @@ export class Event implements IEventData, ISerializable {
_self.properties = dataSanitizeProperties(logger, properties);
_self.measurements = dataSanitizeMeasurements(logger, measurements);
}
}
}

Просмотреть файл

@ -1,18 +1,22 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import { IStackFrame } from "../Interfaces/Contracts/IStackFrame";
import {
IDiagnosticLogger, arrForEach, arrMap, isArray, isError, isFunction, isNullOrUndefined, isObject, isString, strTrim
} from "@microsoft/applicationinsights-core-js";
import { strNotSpecified } from "../Constants";
import { FieldType } from "../Enums";
import { IExceptionData } from "../Interfaces/Contracts/IExceptionData";
import { IExceptionDetails } from "../Interfaces/Contracts/IExceptionDetails";
import { ISerializable } from "../Interfaces/Telemetry/ISerializable";
import { dataSanitizeException, dataSanitizeMeasurements, dataSanitizeMessage, dataSanitizeProperties, dataSanitizeString } from "./Common/DataSanitizer";
import { FieldType } from "../Enums";
import { IStackFrame } from "../Interfaces/Contracts/IStackFrame";
import { SeverityLevel } from "../Interfaces/Contracts/SeverityLevel";
import { IDiagnosticLogger, isNullOrUndefined, arrMap, isString, strTrim, isArray, isError, arrForEach, isObject, isFunction } from "@microsoft/applicationinsights-core-js";
import {
IExceptionInternal, IExceptionDetailsInternal, IExceptionStackFrameInternal, IAutoExceptionTelemetry, IStackDetails
IAutoExceptionTelemetry, IExceptionDetailsInternal, IExceptionInternal, IExceptionStackFrameInternal, IStackDetails
} from "../Interfaces/IExceptionTelemetry";
import { strNotSpecified } from "../Constants";
import { ISerializable } from "../Interfaces/Telemetry/ISerializable";
import {
dataSanitizeException, dataSanitizeMeasurements, dataSanitizeMessage, dataSanitizeProperties, dataSanitizeString
} from "./Common/DataSanitizer";
const NoMethod = "<no_method>";
const strError = "error";

Просмотреть файл

@ -1,13 +1,13 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import { IMetricData } from "../Interfaces/Contracts/IMetricData";
import { ISerializable } from "../Interfaces/Telemetry/ISerializable";
import { dataSanitizeMeasurements, dataSanitizeProperties, dataSanitizeString } from "./Common/DataSanitizer";
import { FieldType } from "../Enums";
import { DataPoint } from "./Common/DataPoint";
import { IDiagnosticLogger } from "@microsoft/applicationinsights-core-js";
import { strNotSpecified } from "../Constants";
import { FieldType } from "../Enums";
import { IMetricData } from "../Interfaces/Contracts/IMetricData";
import { ISerializable } from "../Interfaces/Telemetry/ISerializable";
import { DataPoint } from "./Common/DataPoint";
import { dataSanitizeMeasurements, dataSanitizeProperties, dataSanitizeString } from "./Common/DataSanitizer";
export class Metric implements IMetricData, ISerializable {

Просмотреть файл

@ -1,13 +1,15 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import { IPageViewData } from "../Interfaces/Contracts/IPageViewData";
import { dataSanitizeId, dataSanitizeMeasurements, dataSanitizeProperties, dataSanitizeString, dataSanitizeUrl } from "./Common/DataSanitizer";
import { ISerializable } from "../Interfaces/Telemetry/ISerializable";
import { FieldType } from "../Enums";
import { IDiagnosticLogger } from "@microsoft/applicationinsights-core-js";
import { msToTimeSpan } from "../HelperFuncs";
import { strNotSpecified } from "../Constants";
import { FieldType } from "../Enums";
import { msToTimeSpan } from "../HelperFuncs";
import { IPageViewData } from "../Interfaces/Contracts/IPageViewData";
import { ISerializable } from "../Interfaces/Telemetry/ISerializable";
import {
dataSanitizeId, dataSanitizeMeasurements, dataSanitizeProperties, dataSanitizeString, dataSanitizeUrl
} from "./Common/DataSanitizer";
export class PageView implements IPageViewData, ISerializable {

Просмотреть файл

@ -1,14 +1,13 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import { IPageViewPerfData } from "../Interfaces/Contracts/IPageViewPerfData";
import { IDiagnosticLogger } from "@microsoft/applicationinsights-core-js";
import { strNotSpecified } from "../Constants";
import { FieldType } from "../Enums";
import { IPageViewPerfData } from "../Interfaces/Contracts/IPageViewPerfData";
import { IPageViewPerformanceTelemetry } from "../Interfaces/IPageViewPerformanceTelemetry";
import { ISerializable } from "../Interfaces/Telemetry/ISerializable";
import { dataSanitizeMeasurements, dataSanitizeProperties, dataSanitizeString, dataSanitizeUrl } from "./Common/DataSanitizer";
import { IDiagnosticLogger } from "@microsoft/applicationinsights-core-js";
import { IPageViewPerformanceTelemetry } from "../Interfaces/IPageViewPerformanceTelemetry";
import { strNotSpecified } from "../Constants";
export class PageViewPerformance implements IPageViewPerfData, ISerializable {

Просмотреть файл

@ -1,13 +1,13 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import { dataSanitizeMeasurements, dataSanitizeProperties, dataSanitizeString, dataSanitizeUrl } from "./Common/DataSanitizer";
import { FieldType } from "../Enums";
import { ISerializable } from "../Interfaces/Telemetry/ISerializable";
import { AjaxHelperParseDependencyPath} from "../Util";
import { IRemoteDependencyData } from "../Interfaces/Contracts/IRemoteDependencyData";
import { IDiagnosticLogger } from "@microsoft/applicationinsights-core-js";
import { FieldType } from "../Enums";
import { msToTimeSpan } from "../HelperFuncs";
import { IRemoteDependencyData } from "../Interfaces/Contracts/IRemoteDependencyData";
import { ISerializable } from "../Interfaces/Telemetry/ISerializable";
import { AjaxHelperParseDependencyPath } from "../Util";
import { dataSanitizeMeasurements, dataSanitizeProperties, dataSanitizeString, dataSanitizeUrl } from "./Common/DataSanitizer";
export class RemoteDependencyData implements IRemoteDependencyData, ISerializable {

Просмотреть файл

@ -1,13 +1,13 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import { IMessageData } from "../Interfaces/Contracts/IMessageData";
import { ISerializable } from "../Interfaces/Telemetry/ISerializable";
import { dataSanitizeMessage, dataSanitizeProperties, dataSanitizeMeasurements } from "./Common/DataSanitizer";
import { FieldType } from "../Enums";
import { SeverityLevel } from "../Interfaces/Contracts/SeverityLevel";
import { IDiagnosticLogger } from "@microsoft/applicationinsights-core-js";
import { strNotSpecified } from "../Constants";
import { FieldType } from "../Enums";
import { IMessageData } from "../Interfaces/Contracts/IMessageData";
import { SeverityLevel } from "../Interfaces/Contracts/SeverityLevel";
import { ISerializable } from "../Interfaces/Telemetry/ISerializable";
import { dataSanitizeMeasurements, dataSanitizeMessage, dataSanitizeProperties } from "./Common/DataSanitizer";
export class Trace implements IMessageData, ISerializable {

Просмотреть файл

@ -1,10 +1,11 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import {
IDiagnosticLogger, ITelemetryItem, isNullOrUndefined, objForEachKey, throwError, toISOString
} from "@microsoft/applicationinsights-core-js";
import { strIkey, strNotSpecified } from "./Constants";
import { dataSanitizeString } from "./Telemetry/Common/DataSanitizer";
import { ITelemetryItem, IDiagnosticLogger, objForEachKey, isNullOrUndefined, toISOString, throwError } from "@microsoft/applicationinsights-core-js";
import { strNotSpecified, strIkey } from "./Constants";
/**
* Create a telemetry item that the 1DS channel understands

Просмотреть файл

@ -2,31 +2,29 @@
// Licensed under the MIT License.
import {
IDiagnosticLogger, IPlugin, getPerformance,
getExceptionName as coreGetExceptionName, dumpObj,
isNullOrUndefined, strTrim, random32, isArray, isError, isDate,
newId, generateW3CId, toISOString, arrForEach, getIEVersion, attachEvent,
dateNow, uaDisallowsSameSiteNone, disableCookies as coreDisableCookies,
canUseCookies as coreCanUseCookies, getCookie as coreGetCookie,
setCookie as coreSetCookie, deleteCookie as coreDeleteCookie,
isBeaconsSupported, arrIndexOf, IDistributedTraceContext,
isValidTraceId, isValidSpanId
IDiagnosticLogger, IDistributedTraceContext, IPlugin, arrForEach, arrIndexOf, attachEvent, canUseCookies as coreCanUseCookies, dateNow,
deleteCookie as coreDeleteCookie, disableCookies as coreDisableCookies, dumpObj, generateW3CId, getCookie as coreGetCookie,
getExceptionName as coreGetExceptionName, getIEVersion, getPerformance, isArray, isBeaconsSupported, isDate, isError, isNullOrUndefined,
isValidSpanId, isValidTraceId, newId, random32, setCookie as coreSetCookie, strTrim, toISOString, uaDisallowsSameSiteNone
} from "@microsoft/applicationinsights-core-js";
import { eRequestHeaders, RequestHeaders } from "./RequestResponseHeaders";
import { dataSanitizeString } from "./Telemetry/Common/DataSanitizer";
import { ICorrelationConfig } from "./Interfaces/ICorrelationConfig";
import { DEFAULT_BREEZE_ENDPOINT, DEFAULT_BREEZE_PATH, strNotSpecified } from "./Constants";
import { createDomEvent } from "./DomHelperFuncs";
import { stringToBoolOrDefault, msToTimeSpan, isCrossOriginError, getExtensionByName } from "./HelperFuncs";
import { strNotSpecified } from "./Constants";
import { utlCanUseLocalStorage, utlCanUseSessionStorage, utlDisableStorage, utlGetSessionStorage, utlGetSessionStorageKeys, utlGetLocalStorage, utlRemoveSessionStorage, utlRemoveStorage, utlSetSessionStorage, utlSetLocalStorage } from "./StorageHelperFuncs";
import { urlGetAbsoluteUrl, urlGetCompleteUrl, urlGetPathName, urlParseFullHost, urlParseHost, urlParseUrl } from "./UrlHelperFuncs";
import { getExtensionByName, isCrossOriginError, msToTimeSpan, stringToBoolOrDefault } from "./HelperFuncs";
import { ITelemetryTrace } from "./Interfaces/Context/ITelemetryTrace";
import { ICorrelationConfig } from "./Interfaces/ICorrelationConfig";
import { RequestHeaders, eRequestHeaders } from "./RequestResponseHeaders";
import {
utlCanUseLocalStorage, utlCanUseSessionStorage, utlDisableStorage, utlGetLocalStorage, utlGetSessionStorage, utlGetSessionStorageKeys,
utlRemoveSessionStorage, utlRemoveStorage, utlSetLocalStorage, utlSetSessionStorage
} from "./StorageHelperFuncs";
import { dataSanitizeString } from "./Telemetry/Common/DataSanitizer";
import { urlGetAbsoluteUrl, urlGetCompleteUrl, urlGetPathName, urlParseFullHost, urlParseHost, urlParseUrl } from "./UrlHelperFuncs";
// listing only non-geo specific locations
const _internalEndpoints: string[] = [
"https://dc.services.visualstudio.com/v2/track",
"https://breeze.aimon.applicationinsights.io/v2/track",
"https://dc-int.services.visualstudio.com/v2/track"
DEFAULT_BREEZE_ENDPOINT + DEFAULT_BREEZE_PATH,
"https://breeze.aimon.applicationinsights.io" + DEFAULT_BREEZE_PATH,
"https://dc-int.services.visualstudio.com" + DEFAULT_BREEZE_PATH
];
export function isInternalApplicationInsightsEndpoint(endpointUrl: string): boolean {
@ -535,4 +533,4 @@ export function createDistributedTraceContextFromTrace(telemetryTrace?: ITelemet
trace.traceFlags = newTraceFlags
}
};
}
}

Просмотреть файл

@ -9,7 +9,7 @@ export {
export { parseConnectionString, ConnectionStringParser } from "./ConnectionStringParser";
export { FieldType } from "./Enums";
export { IRequestHeaders, RequestHeaders, eRequestHeaders } from "./RequestResponseHeaders";
export { DisabledPropertyName, ProcessLegacy, SampleRate, HttpMethod, DEFAULT_BREEZE_ENDPOINT, strNotSpecified } from "./Constants";
export { DisabledPropertyName, ProcessLegacy, SampleRate, HttpMethod, DEFAULT_BREEZE_ENDPOINT, DEFAULT_BREEZE_PATH, strNotSpecified } from "./Constants";
export { IData as AIData } from "./Interfaces/Contracts/IData";
export { IBase as AIBase } from "./Interfaces/Contracts/IBase";
export { ISerializable } from "./Interfaces/Telemetry/ISerializable";

Просмотреть файл

@ -2,7 +2,10 @@ import { Assert, AITestClass } from "@microsoft/ai-test-framework";
import * as pako from "pako";
export class AppInsightsCoreSizeCheck extends AITestClass {
private readonly MAX_DEFLATE_SIZE = 19;
private readonly MAX_RAW_SIZE = 45;
private readonly MAX_BUNDLE_SIZE = 45;
private readonly MAX_RAW_DEFLATE_SIZE = 19;
private readonly MAX_BUNDLE_DEFLATE_SIZE = 19;
private readonly rawFilePath = "../dist/applicationinsights-core-js.min.js";
private readonly prodFilePath = "../browser/applicationinsights-core-js.min.js";
@ -30,7 +33,9 @@ export class AppInsightsCoreSizeCheck extends AITestClass {
}
private _fileSizeCheck(isProd: boolean): void {
let _filePath = isProd ? this.prodFilePath : this.rawFilePath;
let _filePath = isProd? this.prodFilePath : this.rawFilePath;
let _maxFullSize = isProd ? this.MAX_BUNDLE_SIZE : this.MAX_RAW_SIZE;
let _maxDeflateSize = isProd ? this.MAX_BUNDLE_DEFLATE_SIZE : this.MAX_RAW_DEFLATE_SIZE;
let postfix = isProd ? "" : "-raw";
let fileName = _filePath.split("..")[1];
this.testCase({
@ -44,8 +49,10 @@ export class AppInsightsCoreSizeCheck extends AITestClass {
return;
} else {
return response.text().then(text => {
let size = Math.ceil((pako.deflate(text).length/1024) * 100) / 100.0;
Assert.ok(size <= this.MAX_DEFLATE_SIZE ,`max ${this.MAX_DEFLATE_SIZE} KB, current deflate size is: ${size} KB`);
let size = Math.ceil((text.length/1024) * 100) / 100.0;
Assert.ok(size <= _maxFullSize, `max ${_maxFullSize} KB, current deflate size is: ${size} KB`);
let deflateSize = Math.ceil((pako.deflate(text).length/1024) * 100) / 100.0;
Assert.ok(deflateSize <= _maxDeflateSize ,`max ${_maxDeflateSize} KB, current deflate size is: ${deflateSize} KB`);
}).catch((error) => {
Assert.ok(false, `applicationinsights-core${postfix} response error: ${error}`);
});

Просмотреть файл

@ -234,19 +234,13 @@ export class ApplicationInsightsCoreTests extends AITestClass {
const messageId: _InternalMessageId = _InternalMessageId.CannotAccessCookie; // can be any id
const logInternalSpy = this.sandbox.spy(appInsightsCore.logger, 'logInternalMessage');
// Test precondition
Assert.ok(logInternalSpy.notCalled, 'PRE: No internal logging performed yet');
Assert.equal(0, appInsightsCore.logger.queue.length, 'PRE: No logging recorded');
// Act
appInsightsCore.logger.throwInternal(LoggingSeverity.CRITICAL, messageId, "Test Error");
// Test postcondition
Assert.ok(logInternalSpy.calledOnce, 'POST: Logging success');
Assert.equal(messageId, logInternalSpy.args[0][1].messageId, "Correct message logged");
Assert.ok(logInternalSpy.args[0][1].message.indexOf('Test Error') !== -1, "Correct message logged");
Assert.equal(1, appInsightsCore.logger.queue.length, "POST: Correct messageId logged");
Assert.ok(appInsightsCore.logger.queue[0].message.indexOf('Test Error') !== -1, "Correct message logged");
Assert.equal(messageId, appInsightsCore.logger.queue[0].messageId, "Correct message logged");
@ -262,18 +256,15 @@ export class ApplicationInsightsCoreTests extends AITestClass {
appInsightsCore.logger = new DiagnosticLogger();
const messageId: _InternalMessageId = _InternalMessageId.CannotAccessCookie; // can be any id
const logInternalSpy = this.sandbox.spy(appInsightsCore.logger, 'logInternalMessage');
// Verify precondition
Assert.ok(logInternalSpy.notCalled, 'PRE: No internal logging performed yet');
Assert.equal(0, appInsightsCore.logger.queue.length, 'PRE: No internal logging performed yet');
// Act
appInsightsCore.logger.throwInternal(LoggingSeverity.CRITICAL, messageId, "Some message");
// Test postcondition
Assert.ok(logInternalSpy.calledOnce, 'POST: Logging success');
Assert.equal(messageId, logInternalSpy.args[0][1].messageId, "Correct message logged");
Assert.equal(1, appInsightsCore.logger.queue.length, 'POST: Logging success');
Assert.equal(messageId, appInsightsCore.logger.queue[0].messageId, "POST: Correct messageId logged");
// Logging same error doesn't duplicate
@ -440,25 +431,18 @@ export class ApplicationInsightsCoreTests extends AITestClass {
}, [channelPlugin]
);
const aiSpy = this.sandbox.spy(appInsightsCore.logger, 'logInternalMessage');
const dummySpy = this.sandbox.spy(dummyCore.logger, 'logInternalMessage');
const messageId: _InternalMessageId = _InternalMessageId.CannotAccessCookie; // can be any id
// Test precondition
Assert.equal(0, appInsightsCore.logger.queue.length, 'PRE: No internal logging performed yet');
Assert.ok(aiSpy.notCalled, "PRE: messageId not yet logged");
Assert.equal(0, dummyCore.logger.queue.length, 'PRE: No dummy logging');
Assert.ok(dummySpy.notCalled, "PRE: No dummy messageId logged");
// Act
appInsightsCore.logger.throwInternal(LoggingSeverity.CRITICAL, messageId, "Test Error");
// Test postcondition
Assert.equal(1, appInsightsCore.logger.queue.length, 'POST: Logging success');
Assert.ok(aiSpy.called, "POST: Correct messageId logged");
Assert.equal(0, dummyCore.logger.queue.length, 'POST: No dummy logging');
Assert.ok(dummySpy.notCalled, "POST: No dummy messageId logged");
}
});
@ -1015,6 +999,6 @@ class TrackPlugin implements IPlugin {
}
public processTelemetry(evt: ITelemetryItem) {
this._nextPlugin.processTelemetry(evt);
this._nextPlugin?.processTelemetry(evt);
}
}

Просмотреть файл

@ -1183,7 +1183,7 @@ class TestSamplingPlugin implements ITelemetryPlugin {
data.sampled = true;
if (!this.isSampledOut) {
this.nextPlugin.processTelemetry(env);
this.nextPlugin?.processTelemetry(env);
}
}
@ -1254,7 +1254,7 @@ class TestChannelPlugin implements IChannelControls {
this.events.push(env);
// Just calling processTelemetry as this is the original design of the Plugins (as opposed to the newer processNext())
this._nextPlugin.processTelemetry(env);
this._nextPlugin?.processTelemetry(env);
}
}

Просмотреть файл

@ -1,6 +1,15 @@
import { Assert, AITestClass } from "@microsoft/ai-test-framework";
import { _InternalMessageId, LoggingSeverity, eLoggingSeverity } from "../../../src/JavaScriptSDK.Enums/LoggingEnums";
import { _InternalMessageId, LoggingSeverity, eLoggingSeverity, _eInternalMessageId } from "../../../src/JavaScriptSDK.Enums/LoggingEnums";
import { _InternalLogMessage } from "../../../src/JavaScriptSDK/DiagnosticLogger";
import { isString, objForEachKey, objKeys } from "../../../src/JavaScriptSDK/HelperFuncs";
type NoRepeats<T extends readonly any[]> = { [M in keyof T]: { [N in keyof T]:
N extends M ? never : T[M] extends T[N] ? unknown : never
}[number] extends never ? T[M] : never }
const verifyArray = <T>() => <U extends NoRepeats<U> & readonly T[]>(
u: (U | [never]) & ([T] extends [U[number]] ? unknown : never)
) => u;
export class LoggingEnumTests extends AITestClass {
@ -34,7 +43,159 @@ export class LoggingEnumTests extends AITestClass {
Assert.equal("CRITICAL", LoggingSeverity[LoggingSeverity.CRITICAL], "Checking string value of LoggingSeverity.CRITICAL");
Assert.equal("WARNING", LoggingSeverity[LoggingSeverity.WARNING], "Checking string value of LoggingSeverity.WARNING");
Assert.equal(1, LoggingSeverity["CRITICAL"], "Checking string value of LoggingSeverity['CRITICAL']");
Assert.equal(2, LoggingSeverity["WARNING"], "Checking string value of LoggingSeverity['WARNING']");
}
});
});
this.testCase({
name: "LoggingSeverity validate immutability",
test: () => {
// Attempt to "Update" the fields
objForEachKey(LoggingSeverity, (field, value) => {
try {
if (isString(value)) {
LoggingSeverity[field] = "Hacked-" + value + "!!!";
} else {
LoggingSeverity[field] = value + 1000;
}
} catch (e) {
// Ignore any errors thrown while trying to "update" the value
}
});
// Add new values
try {
(LoggingSeverity[666] as any) = "New Stuff";
LoggingSeverity["NewStuff"] = "String New Stuff";
} catch(e) {
// Ignore any errors thrown while trying to "update" the value
}
Assert.equal(undefined, LoggingSeverity[666], "Check LoggingSeverity[100]");
Assert.equal(undefined, LoggingSeverity["NewStuff"], "Check LoggingSeverity[NewStuff]");
// Check the values again as they should not have changed
Assert.equal(1, LoggingSeverity.CRITICAL, "Check LoggingSeverity.CRITICAL");
Assert.equal(2, LoggingSeverity.WARNING, "Check LoggingSeverity.WARNING");
Assert.equal(eLoggingSeverity.CRITICAL, LoggingSeverity.CRITICAL, "Check LoggingSeverity.CRITICAL");
Assert.equal(eLoggingSeverity.WARNING, LoggingSeverity.WARNING, "Check LoggingSeverity.WARNING");
Assert.ok(1 === LoggingSeverity.CRITICAL, "Check LoggingSeverity.CRITICAL === 1");
Assert.ok(2 === LoggingSeverity.WARNING, "Check LoggingSeverity.WARNING === 2");
Assert.ok(eLoggingSeverity.CRITICAL === LoggingSeverity.CRITICAL, "Check Critical === eLoggingSeverity.CRITICAL");
Assert.ok(eLoggingSeverity.WARNING === LoggingSeverity.WARNING, "Check Warning === eLoggingSeverity.WARNING");
Assert.equal("1", LoggingSeverity.CRITICAL.toString(), "Checking value of LoggingSeverity.CRITICAL");
Assert.equal("2", LoggingSeverity.WARNING.toString(), "Checking value of LoggingSeverity.WARNING");
Assert.equal("CRITICAL", LoggingSeverity[LoggingSeverity.CRITICAL], "Checking string value of LoggingSeverity.CRITICAL");
Assert.equal("WARNING", LoggingSeverity[LoggingSeverity.WARNING], "Checking string value of LoggingSeverity.WARNING");
Assert.equal(1, LoggingSeverity["CRITICAL"], "Checking string value of LoggingSeverity['CRITICAL']");
Assert.equal(2, LoggingSeverity["WARNING"], "Checking string value of LoggingSeverity['WARNING']");
}
});
this.testCase({
name: "_InternalMessageId validate names",
test: () => {
const verifyInternalMessageIds = verifyArray<keyof typeof _eInternalMessageId>();
const expectedKeys = verifyInternalMessageIds([
"BrowserDoesNotSupportLocalStorage",
"BrowserCannotReadLocalStorage",
"BrowserCannotReadSessionStorage",
"BrowserCannotWriteLocalStorage",
"BrowserCannotWriteSessionStorage",
"BrowserFailedRemovalFromLocalStorage",
"BrowserFailedRemovalFromSessionStorage",
"CannotSendEmptyTelemetry",
"ClientPerformanceMathError",
"ErrorParsingAISessionCookie",
"ErrorPVCalc",
"ExceptionWhileLoggingError",
"FailedAddingTelemetryToBuffer",
"FailedMonitorAjaxAbort",
"FailedMonitorAjaxDur",
"FailedMonitorAjaxOpen",
"FailedMonitorAjaxRSC",
"FailedMonitorAjaxSend",
"FailedMonitorAjaxGetCorrelationHeader",
"FailedToAddHandlerForOnBeforeUnload",
"FailedToSendQueuedTelemetry",
"FailedToReportDataLoss",
"FlushFailed",
"MessageLimitPerPVExceeded",
"MissingRequiredFieldSpecification",
"NavigationTimingNotSupported",
"OnError",
"SessionRenewalDateIsZero",
"SenderNotInitialized",
"StartTrackEventFailed",
"StopTrackEventFailed",
"StartTrackFailed",
"StopTrackFailed",
"TelemetrySampledAndNotSent",
"TrackEventFailed",
"TrackExceptionFailed",
"TrackMetricFailed",
"TrackPVFailed",
"TrackPVFailedCalc",
"TrackTraceFailed",
"TransmissionFailed",
"FailedToSetStorageBuffer",
"FailedToRestoreStorageBuffer",
"InvalidBackendResponse",
"FailedToFixDepricatedValues",
"InvalidDurationValue",
"TelemetryEnvelopeInvalid",
"CreateEnvelopeError",
// User actionable
"CannotSerializeObject",
"CannotSerializeObjectNonSerializable",
"CircularReferenceDetected",
"ClearAuthContextFailed",
"ExceptionTruncated",
"IllegalCharsInName",
"ItemNotInArray",
"MaxAjaxPerPVExceeded",
"MessageTruncated",
"NameTooLong",
"SampleRateOutOfRange",
"SetAuthContextFailed",
"SetAuthContextFailedAccountName",
"StringValueTooLong",
"StartCalledMoreThanOnce",
"StopCalledWithoutStart",
"TelemetryInitializerFailed",
"TrackArgumentsNotSpecified",
"UrlTooLong",
"SessionStorageBufferFull",
"CannotAccessCookie",
"IdTooLong",
"InvalidEvent",
"FailedMonitorAjaxSetRequestHeader",
"SendBrowserInfoOnUserInit",
"PluginException",
"NotificationException",
"SnippetScriptLoadFailure",
"InvalidInstrumentationKey",
"CannotParseAiBlobValue",
"InvalidContentBlob",
"TrackPageActionEventFailed",
"FailedAddingCustomDefinedRequestContext",
"InMemoryStorageBufferFull",
"InstrumentationKeyDeprecation"
]);
expectedKeys.forEach((key) => {
Assert.equal(key, _InternalMessageId[_InternalMessageId[key]], " Expecting the key to be" + key);
});
}
});
}
}

Просмотреть файл

@ -23,10 +23,13 @@
"build:browser": "rollup -c rollup.config.js",
"rebuild": "npm run build",
"test": "grunt coreunittest",
"mintest": "grunt core-mintest",
"perftest": "grunt coreperftest",
"lint": "tslint -p tsconfig.json",
"dtsgen": "api-extractor run --local && node ../../scripts/dtsgen.js \"Microsoft Application Insights Core Javascript SDK\"",
"sri": "node ../../tools/subResourceIntegrity/generateIntegrityFile.js"
"sri": "node ../../tools/subResourceIntegrity/generateIntegrityFile.js",
"ai-min": "grunt core-min",
"ai-restore": "grunt core-restore"
},
"repository": {
"type": "git",

Просмотреть файл

@ -68,4 +68,4 @@ export const EventsDiscardedReason = createEnumStyle<typeof eEventsDiscardedReas
QueueFull: eEventsDiscardedReason.QueueFull
});
export type EventsDiscardedReason = number | eEventsDiscardedReason;
export type EventsDiscardedReason = number | eEventsDiscardedReason;

Просмотреть файл

@ -1,8 +1,25 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// @skip-file-minify
import { createEnumStyle } from "../JavaScriptSDK.Enums/EnumHelperFuncs";
const FAILED = "Failed";
const FAILED_MONITOR_AJAX = FAILED + "MonitorAjax";
const TRACK = "Track";
const START = "Start";
const STOP = "Stop";
const EVENT = "Event";
const AUTH_CONTEXT = "AuthContext";
const EXCEPTION = "Exception";
const LOCAL = "Local";
const SESSION = "Session";
const STORAGE = "Storage";
const BROWSER = "Browser";
const CANNOT = "Cannot";
const BUFFER = "Buffer";
const INSTRUMENTATION_KEY = "InstrumentationKey";
export const enum eLoggingSeverity {
/**
* Error will be sent as internal telemetry
@ -114,91 +131,90 @@ export const enum _eInternalMessageId {
*/
export const _InternalMessageId = createEnumStyle<typeof _eInternalMessageId>({
// Non user actionable
BrowserDoesNotSupportLocalStorage: _eInternalMessageId.BrowserDoesNotSupportLocalStorage,
BrowserCannotReadLocalStorage: _eInternalMessageId.BrowserCannotReadLocalStorage,
BrowserCannotReadSessionStorage: _eInternalMessageId.BrowserCannotReadSessionStorage,
BrowserCannotWriteLocalStorage: _eInternalMessageId.BrowserCannotWriteLocalStorage,
BrowserCannotWriteSessionStorage: _eInternalMessageId.BrowserCannotWriteSessionStorage,
BrowserFailedRemovalFromLocalStorage: _eInternalMessageId.BrowserFailedRemovalFromLocalStorage,
BrowserFailedRemovalFromSessionStorage: _eInternalMessageId.BrowserFailedRemovalFromSessionStorage,
CannotSendEmptyTelemetry: _eInternalMessageId.CannotSendEmptyTelemetry,
[BROWSER + "DoesNotSupport" + LOCAL + STORAGE as "BrowserDoesNotSupportLocalStorage"]: _eInternalMessageId.BrowserDoesNotSupportLocalStorage,
[BROWSER + CANNOT + "Read" + LOCAL + STORAGE as "BrowserCannotReadLocalStorage"]: _eInternalMessageId.BrowserCannotReadLocalStorage,
[BROWSER + CANNOT + "Read" + SESSION + STORAGE as "BrowserCannotReadSessionStorage"]: _eInternalMessageId.BrowserCannotReadSessionStorage,
[BROWSER + CANNOT + "Write" + LOCAL + STORAGE as "BrowserCannotWriteLocalStorage"]: _eInternalMessageId.BrowserCannotWriteLocalStorage,
[BROWSER + CANNOT + "Write" + SESSION + STORAGE as "BrowserCannotWriteSessionStorage"]: _eInternalMessageId.BrowserCannotWriteSessionStorage,
[BROWSER + FAILED + "RemovalFrom" + LOCAL + STORAGE as "BrowserFailedRemovalFromLocalStorage"]: _eInternalMessageId.BrowserFailedRemovalFromLocalStorage,
[BROWSER + FAILED + "RemovalFrom" + SESSION + STORAGE as "BrowserFailedRemovalFromSessionStorage"]: _eInternalMessageId.BrowserFailedRemovalFromSessionStorage,
[CANNOT + "SendEmptyTelemetry" as "CannotSendEmptyTelemetry"]: _eInternalMessageId.CannotSendEmptyTelemetry,
ClientPerformanceMathError: _eInternalMessageId.ClientPerformanceMathError,
ErrorParsingAISessionCookie: _eInternalMessageId.ErrorParsingAISessionCookie,
["ErrorParsingAI" + SESSION + "Cookie" as "ErrorParsingAISessionCookie"]: _eInternalMessageId.ErrorParsingAISessionCookie,
ErrorPVCalc: _eInternalMessageId.ErrorPVCalc,
ExceptionWhileLoggingError: _eInternalMessageId.ExceptionWhileLoggingError,
FailedAddingTelemetryToBuffer: _eInternalMessageId.FailedAddingTelemetryToBuffer,
FailedMonitorAjaxAbort: _eInternalMessageId.FailedMonitorAjaxAbort,
FailedMonitorAjaxDur: _eInternalMessageId.FailedMonitorAjaxDur,
FailedMonitorAjaxOpen: _eInternalMessageId.FailedMonitorAjaxOpen,
FailedMonitorAjaxRSC: _eInternalMessageId.FailedMonitorAjaxRSC,
FailedMonitorAjaxSend: _eInternalMessageId.FailedMonitorAjaxSend,
FailedMonitorAjaxGetCorrelationHeader: _eInternalMessageId.FailedMonitorAjaxGetCorrelationHeader,
FailedToAddHandlerForOnBeforeUnload: _eInternalMessageId.FailedToAddHandlerForOnBeforeUnload,
FailedToSendQueuedTelemetry: _eInternalMessageId.FailedToSendQueuedTelemetry,
FailedToReportDataLoss: _eInternalMessageId.FailedToReportDataLoss,
FlushFailed: _eInternalMessageId.FlushFailed,
[EXCEPTION + "WhileLoggingError" as "ExceptionWhileLoggingError"]: _eInternalMessageId.ExceptionWhileLoggingError,
[FAILED + "AddingTelemetryTo" + BUFFER as "FailedAddingTelemetryToBuffer"]: _eInternalMessageId.FailedAddingTelemetryToBuffer,
[FAILED_MONITOR_AJAX + "Abort" as "FailedMonitorAjaxAbort"]: _eInternalMessageId.FailedMonitorAjaxAbort,
[FAILED_MONITOR_AJAX + "Dur" as "FailedMonitorAjaxDur"]: _eInternalMessageId.FailedMonitorAjaxDur,
[FAILED_MONITOR_AJAX + "Open" as "FailedMonitorAjaxOpen"]: _eInternalMessageId.FailedMonitorAjaxOpen,
[FAILED_MONITOR_AJAX + "RSC" as "FailedMonitorAjaxRSC"]: _eInternalMessageId.FailedMonitorAjaxRSC,
[FAILED_MONITOR_AJAX + "Send" as "FailedMonitorAjaxSend"]: _eInternalMessageId.FailedMonitorAjaxSend,
[FAILED_MONITOR_AJAX + "GetCorrelationHeader" as "FailedMonitorAjaxGetCorrelationHeader"]: _eInternalMessageId.FailedMonitorAjaxGetCorrelationHeader,
[FAILED + "ToAddHandlerForOnBeforeUnload" as "FailedToAddHandlerForOnBeforeUnload"]: _eInternalMessageId.FailedToAddHandlerForOnBeforeUnload,
[FAILED + "ToSendQueuedTelemetry" as "FailedToSendQueuedTelemetry"]: _eInternalMessageId.FailedToSendQueuedTelemetry,
[FAILED + "ToReportDataLoss" as "FailedToReportDataLoss"]: _eInternalMessageId.FailedToReportDataLoss,
["Flush" + FAILED as "FlushFailed"]: _eInternalMessageId.FlushFailed,
MessageLimitPerPVExceeded: _eInternalMessageId.MessageLimitPerPVExceeded,
MissingRequiredFieldSpecification: _eInternalMessageId.MissingRequiredFieldSpecification,
NavigationTimingNotSupported: _eInternalMessageId.NavigationTimingNotSupported,
OnError: _eInternalMessageId.OnError,
SessionRenewalDateIsZero: _eInternalMessageId.SessionRenewalDateIsZero,
[SESSION + "RenewalDateIsZero" as "SessionRenewalDateIsZero"]: _eInternalMessageId.SessionRenewalDateIsZero,
SenderNotInitialized: _eInternalMessageId.SenderNotInitialized,
StartTrackEventFailed: _eInternalMessageId.StartTrackEventFailed,
StopTrackEventFailed: _eInternalMessageId.StopTrackEventFailed,
StartTrackFailed: _eInternalMessageId.StartTrackFailed,
StopTrackFailed: _eInternalMessageId.StopTrackFailed,
[START + TRACK + EVENT + FAILED as "StartTrackEventFailed"]: _eInternalMessageId.StartTrackEventFailed,
[STOP + TRACK + EVENT + FAILED as "StopTrackEventFailed"]: _eInternalMessageId.StopTrackEventFailed,
[START + TRACK + FAILED as "StartTrackFailed"]: _eInternalMessageId.StartTrackFailed,
[STOP + TRACK + FAILED as "StopTrackFailed"]: _eInternalMessageId.StopTrackFailed,
TelemetrySampledAndNotSent: _eInternalMessageId.TelemetrySampledAndNotSent,
TrackEventFailed: _eInternalMessageId.TrackEventFailed,
TrackExceptionFailed: _eInternalMessageId.TrackExceptionFailed,
TrackMetricFailed: _eInternalMessageId.TrackMetricFailed,
TrackPVFailed: _eInternalMessageId.TrackPVFailed,
TrackPVFailedCalc: _eInternalMessageId.TrackPVFailedCalc,
TrackTraceFailed: _eInternalMessageId.TrackTraceFailed,
TransmissionFailed: _eInternalMessageId.TransmissionFailed,
FailedToSetStorageBuffer: _eInternalMessageId.FailedToSetStorageBuffer,
FailedToRestoreStorageBuffer: _eInternalMessageId.FailedToRestoreStorageBuffer,
[TRACK + EVENT + FAILED as "TrackEventFailed"]: _eInternalMessageId.TrackEventFailed,
[TRACK + EXCEPTION + FAILED as "TrackExceptionFailed"]: _eInternalMessageId.TrackExceptionFailed,
[TRACK + "Metric" + FAILED as "TrackMetricFailed"]: _eInternalMessageId.TrackMetricFailed,
[TRACK + "PV" + FAILED as "TrackPVFailed"]: _eInternalMessageId.TrackPVFailed,
[TRACK + "PV" + FAILED + "Calc" as "TrackPVFailedCalc"]: _eInternalMessageId.TrackPVFailedCalc,
[TRACK + "Trace" + FAILED as "TrackTraceFailed"]: _eInternalMessageId.TrackTraceFailed,
["Transmission" + FAILED as "TransmissionFailed"]: _eInternalMessageId.TransmissionFailed,
[FAILED + "ToSet" + STORAGE + BUFFER as "FailedToSetStorageBuffer"]: _eInternalMessageId.FailedToSetStorageBuffer,
[FAILED + "ToRestore" + STORAGE + BUFFER as "FailedToRestoreStorageBuffer"]: _eInternalMessageId.FailedToRestoreStorageBuffer,
InvalidBackendResponse: _eInternalMessageId.InvalidBackendResponse,
FailedToFixDepricatedValues: _eInternalMessageId.FailedToFixDepricatedValues,
[FAILED + "ToFixDepricatedValues" as "FailedToFixDepricatedValues"]: _eInternalMessageId.FailedToFixDepricatedValues,
InvalidDurationValue: _eInternalMessageId.InvalidDurationValue,
TelemetryEnvelopeInvalid: _eInternalMessageId.TelemetryEnvelopeInvalid,
CreateEnvelopeError: _eInternalMessageId.CreateEnvelopeError,
// User actionable
CannotSerializeObject: _eInternalMessageId.CannotSerializeObject,
CannotSerializeObjectNonSerializable: _eInternalMessageId.CannotSerializeObjectNonSerializable,
[CANNOT + "SerializeObject" as "CannotSerializeObject"]: _eInternalMessageId.CannotSerializeObject,
[CANNOT + "SerializeObjectNonSerializable" as "CannotSerializeObjectNonSerializable"]: _eInternalMessageId.CannotSerializeObjectNonSerializable,
CircularReferenceDetected: _eInternalMessageId.CircularReferenceDetected,
ClearAuthContextFailed: _eInternalMessageId.ClearAuthContextFailed,
ExceptionTruncated: _eInternalMessageId.ExceptionTruncated,
["Clear" + AUTH_CONTEXT + FAILED as "ClearAuthContextFailed"]: _eInternalMessageId.ClearAuthContextFailed,
[EXCEPTION + "Truncated" as "ExceptionTruncated"]: _eInternalMessageId.ExceptionTruncated,
IllegalCharsInName: _eInternalMessageId.IllegalCharsInName,
ItemNotInArray: _eInternalMessageId.ItemNotInArray,
MaxAjaxPerPVExceeded: _eInternalMessageId.MaxAjaxPerPVExceeded,
MessageTruncated: _eInternalMessageId.MessageTruncated,
NameTooLong: _eInternalMessageId.NameTooLong,
SampleRateOutOfRange: _eInternalMessageId.SampleRateOutOfRange,
SetAuthContextFailed: _eInternalMessageId.SetAuthContextFailed,
SetAuthContextFailedAccountName: _eInternalMessageId.SetAuthContextFailedAccountName,
["Set" + AUTH_CONTEXT + FAILED as "SetAuthContextFailed"]: _eInternalMessageId.SetAuthContextFailed,
["Set" + AUTH_CONTEXT + FAILED + "AccountName" as "SetAuthContextFailedAccountName"]: _eInternalMessageId.SetAuthContextFailedAccountName,
StringValueTooLong: _eInternalMessageId.StringValueTooLong,
StartCalledMoreThanOnce: _eInternalMessageId.StartCalledMoreThanOnce,
StopCalledWithoutStart: _eInternalMessageId.StopCalledWithoutStart,
TelemetryInitializerFailed: _eInternalMessageId.TelemetryInitializerFailed,
["TelemetryInitializer" + FAILED as "TelemetryInitializerFailed"]: _eInternalMessageId.TelemetryInitializerFailed,
TrackArgumentsNotSpecified: _eInternalMessageId.TrackArgumentsNotSpecified,
UrlTooLong: _eInternalMessageId.UrlTooLong,
SessionStorageBufferFull: _eInternalMessageId.SessionStorageBufferFull,
CannotAccessCookie: _eInternalMessageId.CannotAccessCookie,
[SESSION + STORAGE + BUFFER + "Full" as "SessionStorageBufferFull"]: _eInternalMessageId.SessionStorageBufferFull,
[CANNOT + "AccessCookie" as "CannotAccessCookie"]: _eInternalMessageId.CannotAccessCookie,
IdTooLong: _eInternalMessageId.IdTooLong,
InvalidEvent: _eInternalMessageId.InvalidEvent,
FailedMonitorAjaxSetRequestHeader: _eInternalMessageId.FailedMonitorAjaxSetRequestHeader,
SendBrowserInfoOnUserInit: _eInternalMessageId.SendBrowserInfoOnUserInit,
PluginException: _eInternalMessageId.PluginException,
NotificationException: _eInternalMessageId.NotificationException,
[FAILED_MONITOR_AJAX + "SetRequestHeader" as "FailedMonitorAjaxSetRequestHeader"]: _eInternalMessageId.FailedMonitorAjaxSetRequestHeader,
["Send" + BROWSER + "InfoOnUserInit" as "SendBrowserInfoOnUserInit"]: _eInternalMessageId.SendBrowserInfoOnUserInit,
["Plugin" + EXCEPTION as "PluginException"]: _eInternalMessageId.PluginException,
["Notification" + EXCEPTION as "NotificationException"]: _eInternalMessageId.NotificationException,
SnippetScriptLoadFailure: _eInternalMessageId.SnippetScriptLoadFailure,
InvalidInstrumentationKey: _eInternalMessageId.InvalidInstrumentationKey,
CannotParseAiBlobValue: _eInternalMessageId.CannotParseAiBlobValue,
["Invalid" + INSTRUMENTATION_KEY as "InvalidInstrumentationKey"]: _eInternalMessageId.InvalidInstrumentationKey,
[CANNOT + "ParseAiBlobValue" as "CannotParseAiBlobValue"]: _eInternalMessageId.CannotParseAiBlobValue,
InvalidContentBlob: _eInternalMessageId.InvalidContentBlob,
TrackPageActionEventFailed: _eInternalMessageId.TrackPageActionEventFailed,
FailedAddingCustomDefinedRequestContext: _eInternalMessageId.FailedAddingCustomDefinedRequestContext,
InMemoryStorageBufferFull: _eInternalMessageId.InMemoryStorageBufferFull,
InstrumentationKeyDeprecation: _eInternalMessageId.InstrumentationKeyDeprecation
[TRACK + "PageAction" + EVENT + FAILED as "TrackPageActionEventFailed"]: _eInternalMessageId.TrackPageActionEventFailed,
[FAILED + "AddingCustomDefinedRequestContext" as "FailedAddingCustomDefinedRequestContext"]: _eInternalMessageId.FailedAddingCustomDefinedRequestContext,
["InMemory" + STORAGE + BUFFER + "Full" as "InMemoryStorageBufferFull"]: _eInternalMessageId.InMemoryStorageBufferFull,
[INSTRUMENTATION_KEY + "Deprecation" as "InstrumentationKeyDeprecation"]: _eInternalMessageId.InstrumentationKeyDeprecation
});
export type _InternalMessageId = number | _eInternalMessageId;

Просмотреть файл

@ -43,4 +43,4 @@ export interface IChannelControls extends ITelemetryPlugin {
flush(async: boolean, callBack?: (flushComplete?: boolean) => void, sendReason?: SendRequestReason): boolean | void;
}
export const MinChannelPriorty: number = 100;
export const MinChannelPriorty: number = 100;

Просмотреть файл

@ -2,10 +2,10 @@
// Licensed under the MIT License.
"use strict";
import { ITelemetryItem } from "./ITelemetryItem";
import { IConfiguration } from "./IConfiguration";
import { IAppInsightsCore } from "./IAppInsightsCore";
import { IConfiguration } from "./IConfiguration";
import { IProcessTelemetryContext, IProcessTelemetryUnloadContext, IProcessTelemetryUpdateContext } from "./IProcessTelemetryContext";
import { ITelemetryItem } from "./ITelemetryItem";
import { ITelemetryPluginChain } from "./ITelemetryPluginChain";
import { ITelemetryUnloadState } from "./ITelemetryUnloadState";
import { ITelemetryUpdateState } from "./ITelemetryUpdateState";

Просмотреть файл

@ -1,18 +1,18 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import { IAppInsightsCore } from "../JavaScriptSDK.Interfaces/IAppInsightsCore"
import { BaseCore } from "./BaseCore";
import { IConfiguration } from "../JavaScriptSDK.Interfaces/IConfiguration";
import { IPlugin } from "../JavaScriptSDK.Interfaces/ITelemetryPlugin";
import { ITelemetryItem } from "../JavaScriptSDK.Interfaces/ITelemetryItem";
import dynamicProto from "@microsoft/dynamicproto-js";
import { eEventsDiscardedReason } from "../JavaScriptSDK.Enums/EventsDiscardedReason";
import { IAppInsightsCore } from "../JavaScriptSDK.Interfaces/IAppInsightsCore";
import { IConfiguration } from "../JavaScriptSDK.Interfaces/IConfiguration";
import { IDiagnosticLogger } from "../JavaScriptSDK.Interfaces/IDiagnosticLogger";
import { INotificationManager } from "../JavaScriptSDK.Interfaces/INotificationManager";
import { ITelemetryItem } from "../JavaScriptSDK.Interfaces/ITelemetryItem";
import { IPlugin } from "../JavaScriptSDK.Interfaces/ITelemetryPlugin";
import { BaseCore } from "./BaseCore";
import { DiagnosticLogger } from "./DiagnosticLogger";
import { isNullOrUndefined, throwError } from "./HelperFuncs";
import { NotificationManager } from "./NotificationManager";
import { doPerf } from "./PerfManager";
import { INotificationManager } from "../JavaScriptSDK.Interfaces/INotificationManager";
import { IDiagnosticLogger } from "../JavaScriptSDK.Interfaces/IDiagnosticLogger";
import { DiagnosticLogger } from "./DiagnosticLogger";
import dynamicProto from "@microsoft/dynamicproto-js";
import { isNullOrUndefined, throwError } from "./HelperFuncs";
export class AppInsightsCore extends BaseCore implements IAppInsightsCore {
constructor() {

Некоторые файлы не были показаны из-за слишком большого количества измененных файлов Показать больше