@microsoft/applicationinsights-analytics-js 2.8.0-nightly.2202-06 → 2.8.0-nightly.2204-04

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/browser/applicationinsights-analytics-js.integrity.json +9 -9
  2. package/browser/applicationinsights-analytics-js.js +1774 -924
  3. package/browser/applicationinsights-analytics-js.js.map +1 -1
  4. package/browser/applicationinsights-analytics-js.min.js +2 -2
  5. package/browser/applicationinsights-analytics-js.min.js.map +1 -1
  6. package/dist/applicationinsights-analytics-js.api.json +138 -229
  7. package/dist/applicationinsights-analytics-js.api.md +8 -18
  8. package/dist/applicationinsights-analytics-js.d.ts +9 -104
  9. package/dist/applicationinsights-analytics-js.js +1774 -924
  10. package/dist/applicationinsights-analytics-js.js.map +1 -1
  11. package/dist/applicationinsights-analytics-js.min.js +2 -2
  12. package/dist/applicationinsights-analytics-js.min.js.map +1 -1
  13. package/dist/applicationinsights-analytics-js.rollup.d.ts +9 -104
  14. package/dist-esm/JavaScriptSDK/AnalyticsPlugin.js +674 -0
  15. package/dist-esm/JavaScriptSDK/AnalyticsPlugin.js.map +1 -0
  16. package/dist-esm/JavaScriptSDK/Telemetry/PageViewManager.js +21 -8
  17. package/dist-esm/JavaScriptSDK/Telemetry/PageViewManager.js.map +1 -1
  18. package/dist-esm/JavaScriptSDK/Telemetry/PageViewPerformanceManager.js +10 -10
  19. package/dist-esm/JavaScriptSDK/Telemetry/PageViewPerformanceManager.js.map +1 -1
  20. package/dist-esm/JavaScriptSDK/Telemetry/PageVisitTimeManager.js +5 -5
  21. package/dist-esm/JavaScriptSDK/Telemetry/PageVisitTimeManager.js.map +1 -1
  22. package/dist-esm/JavaScriptSDK/Timing.js +39 -0
  23. package/dist-esm/JavaScriptSDK/Timing.js.map +1 -0
  24. package/dist-esm/JavaScriptSDK.Interfaces/ITelemetryConfig.js +1 -1
  25. package/dist-esm/applicationinsights-analytics-js.js +2 -2
  26. package/dist-esm/applicationinsights-analytics-js.js.map +1 -1
  27. package/package.json +6 -6
  28. package/src/JavaScriptSDK/{ApplicationInsights.ts → AnalyticsPlugin.ts} +403 -325
  29. package/src/JavaScriptSDK/Telemetry/PageViewManager.ts +32 -13
  30. package/src/JavaScriptSDK/Telemetry/PageViewPerformanceManager.ts +6 -6
  31. package/src/JavaScriptSDK/Telemetry/PageVisitTimeManager.ts +1 -1
  32. package/src/JavaScriptSDK/Timing.ts +46 -0
  33. package/src/applicationinsights-analytics-js.ts +1 -1
  34. package/types/JavaScriptSDK/{ApplicationInsights.d.ts → AnalyticsPlugin.d.ts} +12 -16
  35. package/types/JavaScriptSDK/Telemetry/PageViewManager.d.ts +2 -1
  36. package/types/JavaScriptSDK/Telemetry/PageViewPerformanceManager.d.ts +9 -9
  37. package/types/JavaScriptSDK/Telemetry/PageVisitTimeManager.d.ts +4 -4
  38. package/types/JavaScriptSDK/Timing.d.ts +18 -0
  39. package/types/applicationinsights-analytics-js.d.ts +1 -1
  40. package/types/tsdoc-metadata.json +1 -1
  41. package/dist-esm/JavaScriptSDK/ApplicationInsights.js +0 -606
  42. package/dist-esm/JavaScriptSDK/ApplicationInsights.js.map +0 -1
@@ -8,25 +8,28 @@ import {
8
8
  TelemetryItemCreator, Metric, Exception, SeverityLevel, Trace, IDependencyTelemetry,
9
9
  IExceptionTelemetry, ITraceTelemetry, IMetricTelemetry, IAutoExceptionTelemetry,
10
10
  IPageViewTelemetryInternal, IPageViewTelemetry, IPageViewPerformanceTelemetry, IPageViewPerformanceTelemetryInternal,
11
- dateTimeUtilsDuration, IExceptionInternal, PropertiesPluginIdentifier, AnalyticsPluginIdentifier, stringToBoolOrDefault, createDomEvent,
12
- strNotSpecified, isCrossOriginError, utlDisableStorage, dataSanitizeString
11
+ IExceptionInternal, PropertiesPluginIdentifier, AnalyticsPluginIdentifier, stringToBoolOrDefault, createDomEvent,
12
+ strNotSpecified, isCrossOriginError, utlDisableStorage, utlEnableStorage, dataSanitizeString
13
13
  } from "@microsoft/applicationinsights-common";
14
14
 
15
15
  import {
16
16
  IPlugin, IConfiguration, IAppInsightsCore,
17
17
  BaseTelemetryPlugin, ITelemetryItem, IProcessTelemetryContext, ITelemetryPluginChain,
18
- IDiagnosticLogger, LoggingSeverity, _InternalMessageId, ICustomProperties,
19
- getWindow, getDocument, getHistory, getLocation, doPerf, objForEachKey,
20
- isString, isFunction, isNullOrUndefined, arrForEach, generateW3CId, dumpObj, getExceptionName, ICookieMgr, safeGetCookieMgr
18
+ LoggingSeverity, _InternalMessageId, ICustomProperties,
19
+ getWindow, getDocument, getHistory, getLocation, objForEachKey,
20
+ isString, isFunction, isNullOrUndefined, arrForEach, generateW3CId, dumpObj, getExceptionName, ICookieMgr, safeGetCookieMgr,
21
+ TelemetryInitializerFunction, hasHistory, strUndefined, objDefineAccessors, InstrumentFunc, IInstrumentCallDetails, eventOn, eventOff,
22
+ mergeEvtNamespace, createUniqueNamespace, ITelemetryInitializerHandler, throwError, isUndefined, hasWindow, createProcessTelemetryContext,
23
+ ITelemetryUnloadState, IProcessTelemetryUnloadContext
21
24
  } from "@microsoft/applicationinsights-core-js";
22
25
  import { PageViewManager, IAppInsightsInternal } from "./Telemetry/PageViewManager";
23
26
  import { PageVisitTimeManager } from "./Telemetry/PageVisitTimeManager";
24
27
  import { PageViewPerformanceManager } from "./Telemetry/PageViewPerformanceManager";
25
- import { ITelemetryConfig } from "../JavaScriptSDK.Interfaces/ITelemetryConfig";
26
28
  import dynamicProto from "@microsoft/dynamicproto-js";
27
29
 
28
30
  // For types only
29
31
  import { PropertiesPlugin } from "@microsoft/applicationinsights-properties-js";
32
+ import { Timing } from "./Timing";
30
33
 
31
34
  "use strict";
32
35
 
@@ -53,55 +56,86 @@ function _getReason(error: any) {
53
56
  return error || "";
54
57
  }
55
58
 
56
- export class ApplicationInsights extends BaseTelemetryPlugin implements IAppInsights, IAppInsightsInternal {
57
- public static Version = "2.8.0-nightly.2202-06"; // Not currently used anywhere
59
+ const MinMilliSeconds = 60000;
58
60
 
59
- public static getDefaultConfig(config?: IConfig): IConfig {
60
- if (!config) {
61
- config = {};
62
- }
61
+ function _configMilliseconds(value: number, defValue: number) {
62
+ value = value || defValue;
63
+ if (value < MinMilliSeconds) {
64
+ value = MinMilliSeconds;
65
+ }
63
66
 
64
- // set default values
65
- config.sessionRenewalMs = 30 * 60 * 1000;
66
- config.sessionExpirationMs = 24 * 60 * 60 * 1000;
67
- config.disableExceptionTracking = stringToBoolOrDefault(config.disableExceptionTracking);
68
- config.autoTrackPageVisitTime = stringToBoolOrDefault(config.autoTrackPageVisitTime);
69
- config.overridePageViewDuration = stringToBoolOrDefault(config.overridePageViewDuration);
70
- config.enableUnhandledPromiseRejectionTracking = stringToBoolOrDefault(config.enableUnhandledPromiseRejectionTracking);
71
-
72
- if (isNaN(config.samplingPercentage) || config.samplingPercentage <= 0 || config.samplingPercentage >= 100) {
73
- config.samplingPercentage = 100;
74
- }
67
+ return value;
68
+ }
75
69
 
76
- config.isStorageUseDisabled = stringToBoolOrDefault(config.isStorageUseDisabled);
77
- config.isBrowserLinkTrackingEnabled = stringToBoolOrDefault(config.isBrowserLinkTrackingEnabled);
78
- config.enableAutoRouteTracking = stringToBoolOrDefault(config.enableAutoRouteTracking);
79
- config.namePrefix = config.namePrefix || "";
70
+ function _getDefaultConfig(config?: IConfig): IConfig {
71
+ if (!config) {
72
+ config = {};
73
+ }
80
74
 
81
- config.enableDebug = stringToBoolOrDefault(config.enableDebug);
82
- config.disableFlushOnBeforeUnload = stringToBoolOrDefault(config.disableFlushOnBeforeUnload);
83
- config.disableFlushOnUnload = stringToBoolOrDefault(config.disableFlushOnUnload, config.disableFlushOnBeforeUnload);
75
+ // set default values
76
+ config.sessionRenewalMs = _configMilliseconds(config.sessionRenewalMs, 30 * 60 * 1000);
77
+ config.sessionExpirationMs = _configMilliseconds(config.sessionExpirationMs, 24 * 60 * 60 * 1000);
78
+ config.disableExceptionTracking = stringToBoolOrDefault(config.disableExceptionTracking);
79
+ config.autoTrackPageVisitTime = stringToBoolOrDefault(config.autoTrackPageVisitTime);
80
+ config.overridePageViewDuration = stringToBoolOrDefault(config.overridePageViewDuration);
81
+ config.enableUnhandledPromiseRejectionTracking = stringToBoolOrDefault(config.enableUnhandledPromiseRejectionTracking);
84
82
 
85
- return config;
83
+ if (isNaN(config.samplingPercentage) || config.samplingPercentage <= 0 || config.samplingPercentage >= 100) {
84
+ config.samplingPercentage = 100;
86
85
  }
87
86
 
87
+ config.isStorageUseDisabled = stringToBoolOrDefault(config.isStorageUseDisabled);
88
+ config.isBrowserLinkTrackingEnabled = stringToBoolOrDefault(config.isBrowserLinkTrackingEnabled);
89
+ config.enableAutoRouteTracking = stringToBoolOrDefault(config.enableAutoRouteTracking);
90
+ config.namePrefix = config.namePrefix || "";
91
+
92
+ config.enableDebug = stringToBoolOrDefault(config.enableDebug);
93
+ config.disableFlushOnBeforeUnload = stringToBoolOrDefault(config.disableFlushOnBeforeUnload);
94
+ config.disableFlushOnUnload = stringToBoolOrDefault(config.disableFlushOnUnload, config.disableFlushOnBeforeUnload);
95
+
96
+ return config;
97
+ }
98
+
99
+ function _updateStorageUsage(extConfig: IConfig) {
100
+ // Not resetting the storage usage as someone may have manually called utlDisableStorage, so this will only
101
+ // reset based if the configuration option is provided
102
+ if (!isUndefined(extConfig.isStorageUseDisabled)) {
103
+ if (extConfig.isStorageUseDisabled) {
104
+ utlDisableStorage();
105
+ } else {
106
+ utlEnableStorage();
107
+ }
108
+ }
109
+ }
110
+
111
+ export class AnalyticsPlugin extends BaseTelemetryPlugin implements IAppInsights, IAppInsightsInternal {
112
+ public static Version = "2.8.0-nightly.2204-04"; // Not currently used anywhere
113
+
114
+ public static getDefaultConfig = _getDefaultConfig;
115
+
88
116
  public identifier: string = AnalyticsPluginIdentifier; // do not change name or priority
89
117
  public priority: number = 180; // take from reserved priority range 100- 200
90
118
  public config: IConfig;
91
119
  public queue: Array<() => void>;
92
120
  public autoRoutePVDelay = 500; // ms; Time to wait after a route change before triggering a pageview to allow DOM changes to take place
93
121
 
94
- protected _telemetryInitializers: Array<(envelope: ITelemetryItem) => boolean | void>; // Internal telemetry initializers.
95
- protected _pageViewManager: PageViewManager;
96
- protected _pageViewPerformanceManager: PageViewPerformanceManager;
97
- protected _pageVisitTimeManager: PageVisitTimeManager;
98
-
99
122
  constructor() {
100
123
  super();
101
124
  let _eventTracking: Timing;
102
125
  let _pageTracking: Timing;
103
- let _properties: PropertiesPlugin;
104
-
126
+ let _pageViewManager: PageViewManager;
127
+ let _pageViewPerformanceManager: PageViewPerformanceManager;
128
+ let _pageVisitTimeManager: PageVisitTimeManager;
129
+ let _preInitTelemetryInitializers: TelemetryInitializerFunction[];
130
+ let _isBrowserLinkTrackingEnabled: boolean;
131
+ let _browserLinkInitializerAdded: boolean;
132
+ let _enableAutoRouteTracking: boolean;
133
+ let _historyListenerAdded: boolean;
134
+ let _disableExceptionTracking: boolean;
135
+ let _autoExceptionInstrumented: boolean;
136
+ let _enableUnhandledPromiseRejectionTracking: boolean;
137
+ let _autoUnhandledPromiseInstrumented: boolean;
138
+
105
139
  // Counts number of trackAjax invocations.
106
140
  // By default we only monitor X ajax call per view to avoid too much load.
107
141
  // Default value is set in config.
@@ -111,48 +145,24 @@ export class ApplicationInsights extends BaseTelemetryPlugin implements IAppInsi
111
145
  // array with max length of 2 that store current url and previous url for SPA page route change trackPageview use.
112
146
  let _prevUri: string; // Assigned in the constructor
113
147
  let _currUri: string;
114
-
148
+ let _evtNamespace: string | string[];
149
+
150
+ dynamicProto(AnalyticsPlugin, this, (_self, _base) => {
151
+ let _addHook = _base._addHook;
115
152
 
116
- dynamicProto(ApplicationInsights, this, (_self, _base) => {
117
- let location = getLocation(true);
118
- _prevUri = location && location.href || "";
153
+ _initDefaults();
119
154
 
120
155
  _self.getCookieMgr = () => {
121
156
  return safeGetCookieMgr(_self.core);
122
157
  };
123
158
 
124
159
  _self.processTelemetry = (env: ITelemetryItem, itemCtx?: IProcessTelemetryContext) => {
125
- doPerf(_self.core, () => _self.identifier + ":processTelemetry", () => {
126
- let doNotSendItem = false;
127
- const telemetryInitializersCount = _self._telemetryInitializers.length;
128
- itemCtx = _self._getTelCtx(itemCtx);
129
- for (let i = 0; i < telemetryInitializersCount; ++i) {
130
- const telemetryInitializer = _self._telemetryInitializers[i];
131
- if (telemetryInitializer) {
132
- try {
133
- if (telemetryInitializer.apply(null, [env]) === false) {
134
- doNotSendItem = true;
135
- break;
136
- }
137
- } catch (e) {
138
- // log error but dont stop executing rest of the telemetry initializers
139
- // doNotSendItem = true;
140
- itemCtx.diagLog().throwInternal(
141
- LoggingSeverity.CRITICAL, _InternalMessageId.TelemetryInitializerFailed, "One of telemetry initializers failed, telemetry item will not be sent: " + getExceptionName(e),
142
- { exception: dumpObj(e) }, true);
143
- }
144
- }
145
- }
146
-
147
- if (!doNotSendItem) {
148
- _self.processNext(env, itemCtx);
149
- }
150
- }, () => ({ item: env }), !((env as any).sync));
160
+ _self.processNext(env, itemCtx);
151
161
  };
152
162
 
153
163
  _self.trackEvent = (event: IEventTelemetry, customProperties?: ICustomProperties): void => {
154
164
  try {
155
- const telemetryItem = TelemetryItemCreator.create<IEventTelemetry>(
165
+ let telemetryItem = TelemetryItemCreator.create<IEventTelemetry>(
156
166
  event,
157
167
  EventTelemetry.dataType,
158
168
  EventTelemetry.envelopeType,
@@ -162,7 +172,7 @@ export class ApplicationInsights extends BaseTelemetryPlugin implements IAppInsi
162
172
 
163
173
  _self.core.track(telemetryItem);
164
174
  } catch (e) {
165
- _self.diagLog().throwInternal(LoggingSeverity.WARNING,
175
+ _throwInternal(LoggingSeverity.WARNING,
166
176
  _InternalMessageId.TrackTraceFailed,
167
177
  "trackTrace failed, trace will not be collected: " + getExceptionName(e),
168
178
  { exception: dumpObj(e) });
@@ -177,7 +187,7 @@ export class ApplicationInsights extends BaseTelemetryPlugin implements IAppInsi
177
187
  try {
178
188
  _eventTracking.start(name);
179
189
  } catch (e) {
180
- _self.diagLog().throwInternal(LoggingSeverity.CRITICAL,
190
+ _throwInternal(LoggingSeverity.CRITICAL,
181
191
  _InternalMessageId.StartTrackEventFailed,
182
192
  "startTrackEvent failed, event will not be collected: " + getExceptionName(e),
183
193
  { exception: dumpObj(e) });
@@ -194,7 +204,7 @@ export class ApplicationInsights extends BaseTelemetryPlugin implements IAppInsi
194
204
  try {
195
205
  _eventTracking.stop(name, undefined, properties); // Todo: Fix to pass measurements once type is updated
196
206
  } catch (e) {
197
- _self.diagLog().throwInternal(LoggingSeverity.CRITICAL,
207
+ _throwInternal(LoggingSeverity.CRITICAL,
198
208
  _InternalMessageId.StopTrackEventFailed,
199
209
  "stopTrackEvent failed, event will not be collected: " + getExceptionName(e),
200
210
  { exception: dumpObj(e) });
@@ -209,7 +219,7 @@ export class ApplicationInsights extends BaseTelemetryPlugin implements IAppInsi
209
219
  */
210
220
  _self.trackTrace = (trace: ITraceTelemetry, customProperties?: ICustomProperties): void => {
211
221
  try {
212
- const telemetryItem = TelemetryItemCreator.create<ITraceTelemetry>(
222
+ let telemetryItem = TelemetryItemCreator.create<ITraceTelemetry>(
213
223
  trace,
214
224
  Trace.dataType,
215
225
  Trace.envelopeType,
@@ -218,7 +228,7 @@ export class ApplicationInsights extends BaseTelemetryPlugin implements IAppInsi
218
228
 
219
229
  _self.core.track(telemetryItem);
220
230
  } catch (e) {
221
- _self.diagLog().throwInternal(LoggingSeverity.WARNING,
231
+ _throwInternal(LoggingSeverity.WARNING,
222
232
  _InternalMessageId.TrackTraceFailed,
223
233
  "trackTrace failed, trace will not be collected: " + getExceptionName(e),
224
234
  { exception: dumpObj(e) });
@@ -238,7 +248,7 @@ export class ApplicationInsights extends BaseTelemetryPlugin implements IAppInsi
238
248
  */
239
249
  _self.trackMetric = (metric: IMetricTelemetry, customProperties?: ICustomProperties): void => {
240
250
  try {
241
- const telemetryItem = TelemetryItemCreator.create<IMetricTelemetry>(
251
+ let telemetryItem = TelemetryItemCreator.create<IMetricTelemetry>(
242
252
  metric,
243
253
  Metric.dataType,
244
254
  Metric.envelopeType,
@@ -248,7 +258,7 @@ export class ApplicationInsights extends BaseTelemetryPlugin implements IAppInsi
248
258
 
249
259
  _self.core.track(telemetryItem);
250
260
  } catch (e) {
251
- _self.diagLog().throwInternal(LoggingSeverity.CRITICAL,
261
+ _throwInternal(LoggingSeverity.CRITICAL,
252
262
  _InternalMessageId.TrackMetricFailed,
253
263
  "trackMetric failed, metric will not be collected: " + getExceptionName(e),
254
264
  { exception: dumpObj(e) });
@@ -263,14 +273,14 @@ export class ApplicationInsights extends BaseTelemetryPlugin implements IAppInsi
263
273
  */
264
274
  _self.trackPageView = (pageView?: IPageViewTelemetry, customProperties?: ICustomProperties) => {
265
275
  try {
266
- const inPv = pageView || {};
267
- _self._pageViewManager.trackPageView(inPv, {...inPv.properties, ...inPv.measurements, ...customProperties});
276
+ let inPv = pageView || {};
277
+ _pageViewManager.trackPageView(inPv, {...inPv.properties, ...inPv.measurements, ...customProperties});
268
278
 
269
279
  if (_self.config.autoTrackPageVisitTime) {
270
- _self._pageVisitTimeManager.trackPreviousPageVisit(inPv.name, inPv.uri);
280
+ _pageVisitTimeManager.trackPreviousPageVisit(inPv.name, inPv.uri);
271
281
  }
272
282
  } catch (e) {
273
- _self.diagLog().throwInternal(
283
+ _throwInternal(
274
284
  LoggingSeverity.CRITICAL,
275
285
  _InternalMessageId.TrackPVFailed,
276
286
  "trackPageView failed, page view will not be collected: " + getExceptionName(e),
@@ -290,7 +300,7 @@ export class ApplicationInsights extends BaseTelemetryPlugin implements IAppInsi
290
300
  pageView.refUri = pageView.refUri === undefined ? doc.referrer : pageView.refUri;
291
301
  }
292
302
 
293
- const telemetryItem = TelemetryItemCreator.create<IPageViewTelemetryInternal>(
303
+ let telemetryItem = TelemetryItemCreator.create<IPageViewTelemetryInternal>(
294
304
  pageView,
295
305
  PageView.dataType,
296
306
  PageView.envelopeType,
@@ -310,7 +320,7 @@ export class ApplicationInsights extends BaseTelemetryPlugin implements IAppInsi
310
320
  * @param properties
311
321
  */
312
322
  _self.sendPageViewPerformanceInternal = (pageViewPerformance: IPageViewPerformanceTelemetryInternal, properties?: { [key: string]: any }, systemProperties?: { [key: string]: any }) => {
313
- const telemetryItem = TelemetryItemCreator.create<IPageViewPerformanceTelemetryInternal>(
323
+ let telemetryItem = TelemetryItemCreator.create<IPageViewPerformanceTelemetryInternal>(
314
324
  pageViewPerformance,
315
325
  PageViewPerformance.dataType,
316
326
  PageViewPerformance.envelopeType,
@@ -327,11 +337,12 @@ export class ApplicationInsights extends BaseTelemetryPlugin implements IAppInsi
327
337
  * @param customProperties
328
338
  */
329
339
  _self.trackPageViewPerformance = (pageViewPerformance: IPageViewPerformanceTelemetry, customProperties?: ICustomProperties): void => {
340
+ let inPvp = pageViewPerformance || {};
330
341
  try {
331
- _self._pageViewPerformanceManager.populatePageViewPerformanceEvent(pageViewPerformance);
332
- _self.sendPageViewPerformanceInternal(pageViewPerformance, customProperties);
342
+ _pageViewPerformanceManager.populatePageViewPerformanceEvent(inPvp);
343
+ _self.sendPageViewPerformanceInternal(inPvp, customProperties);
333
344
  } catch (e) {
334
- _self.diagLog().throwInternal(
345
+ _throwInternal(
335
346
  LoggingSeverity.CRITICAL,
336
347
  _InternalMessageId.TrackPVFailed,
337
348
  "trackPageViewPerformance failed, page view will not be collected: " + getExceptionName(e),
@@ -354,7 +365,7 @@ export class ApplicationInsights extends BaseTelemetryPlugin implements IAppInsi
354
365
 
355
366
  _pageTracking.start(name);
356
367
  } catch (e) {
357
- _self.diagLog().throwInternal(
368
+ _throwInternal(
358
369
  LoggingSeverity.CRITICAL,
359
370
  _InternalMessageId.StartTrackFailed,
360
371
  "startTrackPage failed, page view may not be collected: " + getExceptionName(e),
@@ -385,10 +396,10 @@ export class ApplicationInsights extends BaseTelemetryPlugin implements IAppInsi
385
396
  _pageTracking.stop(name, url, properties, measurement);
386
397
 
387
398
  if (_self.config.autoTrackPageVisitTime) {
388
- _self._pageVisitTimeManager.trackPreviousPageVisit(name, url);
399
+ _pageVisitTimeManager.trackPreviousPageVisit(name, url);
389
400
  }
390
401
  } catch (e) {
391
- _self.diagLog().throwInternal(
402
+ _throwInternal(
392
403
  LoggingSeverity.CRITICAL,
393
404
  _InternalMessageId.StopTrackFailed,
394
405
  "stopTrackPage failed, page view will not be collected: " + getExceptionName(e),
@@ -396,7 +407,7 @@ export class ApplicationInsights extends BaseTelemetryPlugin implements IAppInsi
396
407
  }
397
408
  };
398
409
 
399
- /**
410
+ /**
400
411
  * @ignore INTERNAL ONLY
401
412
  * @param exception
402
413
  * @param properties
@@ -404,7 +415,7 @@ export class ApplicationInsights extends BaseTelemetryPlugin implements IAppInsi
404
415
  */
405
416
  _self.sendExceptionInternal = (exception: IExceptionTelemetry, customProperties?: { [key: string]: any }, systemProperties?: { [key: string]: any }) => {
406
417
  const theError = exception.exception || exception.error || new Error(strNotSpecified);
407
- const exceptionPartB = new Exception(
418
+ let exceptionPartB = new Exception(
408
419
  _self.diagLog(),
409
420
  theError,
410
421
  exception.properties || customProperties,
@@ -413,7 +424,7 @@ export class ApplicationInsights extends BaseTelemetryPlugin implements IAppInsi
413
424
  exception.id
414
425
  ).toInterface();
415
426
 
416
- const telemetryItem: ITelemetryItem = TelemetryItemCreator.create<IExceptionInternal>(
427
+ let telemetryItem: ITelemetryItem = TelemetryItemCreator.create<IExceptionInternal>(
417
428
  exceptionPartB,
418
429
  Exception.dataType,
419
430
  Exception.envelopeType,
@@ -434,10 +445,14 @@ export class ApplicationInsights extends BaseTelemetryPlugin implements IAppInsi
434
445
  * @memberof ApplicationInsights
435
446
  */
436
447
  _self.trackException = (exception: IExceptionTelemetry, customProperties?: ICustomProperties): void => {
448
+ if (exception && !exception.exception && (exception as any).error) {
449
+ exception.exception = (exception as any).error;
450
+ }
451
+
437
452
  try {
438
453
  _self.sendExceptionInternal(exception, customProperties);
439
454
  } catch (e) {
440
- _self.diagLog().throwInternal(
455
+ _throwInternal(
441
456
  LoggingSeverity.CRITICAL,
442
457
  _InternalMessageId.TrackExceptionFailed,
443
458
  "trackException failed, exception will not be collected: " + getExceptionName(e),
@@ -464,7 +479,7 @@ export class ApplicationInsights extends BaseTelemetryPlugin implements IAppInsi
464
479
  const url = (exception && exception.url) || (getDocument() || {} as any).URL;
465
480
  // If no error source is provided assume the default window.onerror handler
466
481
  const errorSrc = exception.errorSrc || "window.onerror@" + url + ":" + (exception.lineNumber || 0) + ":" + (exception.columnNumber || 0);
467
- const properties = {
482
+ let properties = {
468
483
  errorSrc,
469
484
  url,
470
485
  lineNumber: exception.lineNumber || 0,
@@ -492,7 +507,7 @@ export class ApplicationInsights extends BaseTelemetryPlugin implements IAppInsi
492
507
  } catch (e) {
493
508
  const errorString = error ? (error.name + ", " + error.message) : "null";
494
509
 
495
- _self.diagLog().throwInternal(
510
+ _throwInternal(
496
511
  LoggingSeverity.CRITICAL,
497
512
  _InternalMessageId.ExceptionWhileLoggingError,
498
513
  "_onError threw exception while logging error, error will not be collected: "
@@ -502,8 +517,18 @@ export class ApplicationInsights extends BaseTelemetryPlugin implements IAppInsi
502
517
  }
503
518
  };
504
519
 
505
- _self.addTelemetryInitializer = (telemetryInitializer: (item: ITelemetryItem) => boolean | void) => {
506
- _self._telemetryInitializers.push(telemetryInitializer);
520
+ _self.addTelemetryInitializer = (telemetryInitializer: TelemetryInitializerFunction): ITelemetryInitializerHandler | void => {
521
+ if (_self.core) {
522
+ // Just add to the core
523
+ return _self.core.addTelemetryInitializer(telemetryInitializer);
524
+ }
525
+
526
+ // Handle "pre-initialization" telemetry initializers (for backward compatibility)
527
+ if (!_preInitTelemetryInitializers) {
528
+ _preInitTelemetryInitializers = [];
529
+ }
530
+
531
+ _preInitTelemetryInitializers.push(telemetryInitializer);
507
532
  };
508
533
 
509
534
  _self.initialize = (config: IConfiguration & IConfig, core: IAppInsightsCore, extensions: IPlugin[], pluginChain?:ITelemetryPluginChain) => {
@@ -512,197 +537,105 @@ export class ApplicationInsights extends BaseTelemetryPlugin implements IAppInsi
512
537
  }
513
538
 
514
539
  if (isNullOrUndefined(core)) {
515
- throw Error("Error initializing");
540
+ throwError("Error initializing");
516
541
  }
517
542
 
518
543
  _base.initialize(config, core, extensions, pluginChain);
519
- _self.setInitialized(false); // resetting the initialized state, just in case the following fails
520
- let ctx = _self._getTelCtx();
521
- let identifier = _self.identifier;
522
-
523
- _self.config = ctx.getExtCfg<IConfig>(identifier);
524
-
525
- // load default values if specified
526
- const defaults: IConfig = ApplicationInsights.getDefaultConfig(config);
527
- if (defaults !== undefined) {
528
- objForEachKey(defaults, (field, value) => {
529
- // for each unspecified field, set the default value
530
- _self.config[field] = ctx.getConfig(identifier, field, value);
531
- if (_self.config[field] === undefined) {
532
- _self.config[field] = value;
544
+ try {
545
+ _evtNamespace = mergeEvtNamespace(createUniqueNamespace(_self.identifier), core.evtNamespace && core.evtNamespace());
546
+ if (_preInitTelemetryInitializers) {
547
+ arrForEach(_preInitTelemetryInitializers, (initializer) => {
548
+ core.addTelemetryInitializer(initializer);
549
+ });
550
+
551
+ _preInitTelemetryInitializers = null;
552
+ }
553
+
554
+ let extConfig = _populateDefaults(config);
555
+ _updateStorageUsage(extConfig);
556
+
557
+ _pageViewPerformanceManager = new PageViewPerformanceManager(_self.core);
558
+ _pageViewManager = new PageViewManager(this, extConfig.overridePageViewDuration, _self.core, _pageViewPerformanceManager);
559
+ _pageVisitTimeManager = new PageVisitTimeManager(_self.diagLog(), (pageName, pageUrl, pageVisitTime) => trackPageVisitTime(pageName, pageUrl, pageVisitTime))
560
+
561
+ _updateBrowserLinkTracking(extConfig, config);
562
+
563
+ _eventTracking = new Timing(_self.diagLog(), "trackEvent");
564
+ _eventTracking.action =
565
+ (name?: string, url?: string, duration?: number, properties?: { [key: string]: string }) => {
566
+ if (!properties) {
567
+ properties = {};
568
+ }
569
+
570
+ properties[durationProperty] = duration.toString();
571
+ _self.trackEvent({ name, properties } as IEventTelemetry);
533
572
  }
534
- });
535
- }
536
-
537
- // Todo: move this out of static state
538
- if (_self.config.isStorageUseDisabled) {
539
- utlDisableStorage();
540
- }
541
-
542
- const configGetters: ITelemetryConfig = {
543
- instrumentationKey: () => config.instrumentationKey,
544
- accountId: () => _self.config.accountId || config.accountId,
545
- sessionRenewalMs: () => _self.config.sessionRenewalMs || config.sessionRenewalMs,
546
- sessionExpirationMs: () => _self.config.sessionExpirationMs || config.sessionExpirationMs,
547
- sampleRate: () => _self.config.samplingPercentage || config.samplingPercentage,
548
- sdkExtension: () => _self.config.sdkExtension || config.sdkExtension,
549
- isBrowserLinkTrackingEnabled: () => _self.config.isBrowserLinkTrackingEnabled || config.isBrowserLinkTrackingEnabled,
550
- appId: () => _self.config.appId || config.appId
551
- }
552
-
553
- _self._pageViewPerformanceManager = new PageViewPerformanceManager(_self.core);
554
- _self._pageViewManager = new PageViewManager(this, _self.config.overridePageViewDuration, _self.core, _self._pageViewPerformanceManager);
555
- _self._pageVisitTimeManager = new PageVisitTimeManager(_self.diagLog(), (pageName, pageUrl, pageVisitTime) => trackPageVisitTime(pageName, pageUrl, pageVisitTime))
556
-
557
- _self._telemetryInitializers = _self._telemetryInitializers || [];
558
- _addDefaultTelemetryInitializers(configGetters);
559
-
560
- _eventTracking = new Timing(_self.diagLog(), "trackEvent");
561
- _eventTracking.action =
562
- (name?: string, url?: string, duration?: number, properties?: { [key: string]: string }) => {
563
- if (!properties) {
573
+
574
+ // initialize page view timing
575
+ _pageTracking = new Timing(_self.diagLog(), "trackPageView");
576
+ _pageTracking.action = (name, url, duration, properties, measurements) => {
577
+
578
+ // duration must be a custom property in order for the collector to extract it
579
+ if (isNullOrUndefined(properties)) {
564
580
  properties = {};
565
581
  }
566
-
567
582
  properties[durationProperty] = duration.toString();
568
- _self.trackEvent({ name, properties } as IEventTelemetry);
569
- }
570
-
571
- // initialize page view timing
572
- _pageTracking = new Timing(_self.diagLog(), "trackPageView");
573
- _pageTracking.action = (name, url, duration, properties, measurements) => {
574
-
575
- // duration must be a custom property in order for the collector to extract it
576
- if (isNullOrUndefined(properties)) {
577
- properties = {};
583
+
584
+ let pageViewItem: IPageViewTelemetry = {
585
+ name,
586
+ uri: url,
587
+ properties,
588
+ measurements
589
+ };
590
+
591
+ _self.sendPageViewInternal(pageViewItem, properties);
578
592
  }
579
- properties[durationProperty] = duration.toString();
580
-
581
- const pageViewItem: IPageViewTelemetry = {
582
- name,
583
- uri: url,
584
- properties,
585
- measurements
586
- };
587
-
588
- _self.sendPageViewInternal(pageViewItem, properties);
589
- }
590
-
591
- let _window = getWindow();
592
- let _history = getHistory();
593
- let _location = getLocation(true);
594
-
595
- const instance: IAppInsights = this;
596
- if (_self.config.disableExceptionTracking === false &&
597
- !_self.config.autoExceptionInstrumented && _window) {
598
- // We want to enable exception auto collection and it has not been done so yet
599
- const onerror = "onerror";
600
- const originalOnError = _window[onerror];
601
- _window.onerror = (message, url, lineNumber, columnNumber, error) => {
602
- const evt = _window[strEvent];
603
- const handled = originalOnError && (originalOnError(message, url, lineNumber, columnNumber, error) as any);
604
- if (handled !== true) { // handled could be typeof function
605
- instance._onerror(Exception.CreateAutoException(
606
- message,
607
- url,
608
- lineNumber,
609
- columnNumber,
610
- error,
611
- evt
612
- ));
613
- }
614
-
615
- return handled;
593
+
594
+ if (hasWindow()) {
595
+ _updateExceptionTracking(extConfig);
596
+ _updateLocationChange(extConfig);
616
597
  }
617
- _self.config.autoExceptionInstrumented = true;
598
+
599
+ } catch (e) {
600
+ // resetting the initialized state because of failure
601
+ _self.setInitialized(false);
602
+ throw e;
618
603
  }
604
+ };
619
605
 
620
- if (_self.config.disableExceptionTracking === false &&
621
- _self.config.enableUnhandledPromiseRejectionTracking === true &&
622
- !_self.config.autoUnhandledPromiseInstrumented && _window) {
623
- // We want to enable exception auto collection and it has not been done so yet
624
- const onunhandledrejection = "onunhandledrejection";
625
- const originalOnUnhandledRejection = _window[onunhandledrejection];
626
- _window[onunhandledrejection] = (error: PromiseRejectionEvent) => {
627
- const evt = _window[strEvent];
628
- const handled = originalOnUnhandledRejection && (originalOnUnhandledRejection.call(_window, error) as any);
629
- if (handled !== true) { // handled could be typeof function
630
- instance._onerror(Exception.CreateAutoException(
631
- _getReason(error),
632
- _location ? _location.href : "",
633
- 0,
634
- 0,
635
- error,
636
- evt
637
- ));
638
- }
606
+ _self._doTeardown = (unloadCtx?: IProcessTelemetryUnloadContext, unloadState?: ITelemetryUnloadState) => {
607
+ _pageViewManager && _pageViewManager.teardown(unloadCtx, unloadState)
608
+
609
+ // Just register to remove all events associated with this namespace
610
+ eventOff(window, null, null, _evtNamespace);
611
+ _initDefaults();
612
+ };
613
+
614
+ function _populateDefaults(config: IConfiguration) {
615
+ let ctx = createProcessTelemetryContext(null, config, _self.core);
616
+ let identifier = _self.identifier;
639
617
 
640
- return handled;
641
- }
642
- _self.config.autoUnhandledPromiseInstrumented = true;
643
- }
618
+ // load default values if specified
619
+ const defaults: IConfig = _getDefaultConfig(config);
620
+ let extConfig = _self.config = ctx.getExtCfg<IConfig>(identifier);
644
621
 
645
- /**
646
- * Create a custom "locationchange" event which is triggered each time the history object is changed
647
- */
648
- if (_self.config.enableAutoRouteTracking === true
649
- && _history && isFunction(_history.pushState) && isFunction(_history.replaceState)
650
- && _window
651
- && typeof Event !== "undefined") {
652
- const _self = this;
653
- // Find the properties plugin
654
- arrForEach(extensions, extension => {
655
- if (extension.identifier === PropertiesPluginIdentifier) {
656
- _properties = extension as PropertiesPlugin;
622
+ if (defaults !== undefined) {
623
+ objForEachKey(defaults, (field, value) => {
624
+ // for each unspecified field, set the default value
625
+ extConfig[field] = ctx.getConfig(identifier, field, value);
626
+ if (extConfig[field] === undefined) {
627
+ extConfig = value;
657
628
  }
658
629
  });
659
-
660
- _history.pushState = ( f => function pushState() {
661
- const ret = f.apply(this, arguments);
662
- _dispatchEvent(_window, createDomEvent(_self.config.namePrefix + "pushState"));
663
- _dispatchEvent(_window, createDomEvent(_self.config.namePrefix + "locationchange"));
664
- return ret;
665
- })(_history.pushState);
666
-
667
- _history.replaceState = ( f => function replaceState(){
668
- const ret = f.apply(this, arguments);
669
- _dispatchEvent(_window, createDomEvent(_self.config.namePrefix + "replaceState"));
670
- _dispatchEvent(_window, createDomEvent(_self.config.namePrefix + "locationchange"));
671
- return ret;
672
- })(_history.replaceState);
673
-
674
- if (_window.addEventListener) {
675
- _window.addEventListener(_self.config.namePrefix + "popstate",()=>{
676
- _dispatchEvent(_window, createDomEvent(_self.config.namePrefix + "locationchange"));
677
- });
678
-
679
- _window.addEventListener(_self.config.namePrefix + "locationchange", () => {
680
- if (_properties && _properties.context && _properties.context.telemetryTrace) {
681
- _properties.context.telemetryTrace.traceID = generateW3CId();
682
- let traceLocationName = "_unknown_";
683
- if (_location && _location.pathname) {
684
- traceLocationName = _location.pathname + (_location.hash || "");
685
- }
686
-
687
- // This populates the ai.operation.name which has a maximum size of 1024 so we need to sanitize it
688
- _properties.context.telemetryTrace.name = dataSanitizeString(_self.diagLog(), traceLocationName);
689
- }
690
- if (_currUri) {
691
- _prevUri = _currUri;
692
- _currUri = _location && _location.href || "";
693
- } else {
694
- _currUri = _location && _location.href || "";
695
- }
696
- setTimeout(((uri: string) => {
697
- // todo: override start time so that it is not affected by autoRoutePVDelay
698
- _self.trackPageView({ refUri: uri, properties: { duration: 0 } }); // SPA route change loading durations are undefined, so send 0
699
- }).bind(this, _prevUri), _self.autoRoutePVDelay);
700
- });
701
- }
702
630
  }
703
631
 
704
- _self.setInitialized(true);
705
- };
632
+ return extConfig;
633
+ }
634
+
635
+ function _updateBrowserLinkTracking(extConfig: IConfig, config: IConfig) {
636
+ _isBrowserLinkTrackingEnabled = extConfig.isBrowserLinkTrackingEnabled || config.isBrowserLinkTrackingEnabled;
637
+ _addDefaultTelemetryInitializers();
638
+ }
706
639
 
707
640
  /**
708
641
  * Log a page visit time
@@ -710,7 +643,7 @@ export class ApplicationInsights extends BaseTelemetryPlugin implements IAppInsi
710
643
  * @param pageVisitDuration Duration of visit to the page in milleseconds
711
644
  */
712
645
  function trackPageVisitTime(pageName: string, pageUrl: string, pageVisitTime: number) {
713
- const properties = { PageName: pageName, PageUrl: pageUrl };
646
+ let properties = { PageName: pageName, PageUrl: pageUrl };
714
647
  _self.trackMetric({
715
648
  name: "PageVisitTime",
716
649
  average: pageVisitTime,
@@ -720,12 +653,12 @@ export class ApplicationInsights extends BaseTelemetryPlugin implements IAppInsi
720
653
  }, properties);
721
654
  }
722
655
 
723
- function _addDefaultTelemetryInitializers(configGetters: ITelemetryConfig) {
724
- if (!configGetters.isBrowserLinkTrackingEnabled()) {
656
+ function _addDefaultTelemetryInitializers() {
657
+ if (!_browserLinkInitializerAdded && _isBrowserLinkTrackingEnabled) {
725
658
  const browserLinkPaths = ["/browserLinkSignalR/", "/__browserLink/"];
726
659
  const dropBrowserLinkRequests = (envelope: ITelemetryItem) => {
727
- if (envelope.baseType === RemoteDependencyData.dataType) {
728
- const remoteData = envelope.baseData as IDependencyTelemetry;
660
+ if (_isBrowserLinkTrackingEnabled && envelope.baseType === RemoteDependencyData.dataType) {
661
+ let remoteData = envelope.baseData as IDependencyTelemetry;
729
662
  if (remoteData) {
730
663
  for (let i = 0; i < browserLinkPaths.length; i++) {
731
664
  if (remoteData.target && remoteData.target.indexOf(browserLinkPaths[i]) >= 0) {
@@ -738,16 +671,13 @@ export class ApplicationInsights extends BaseTelemetryPlugin implements IAppInsi
738
671
  return true;
739
672
  }
740
673
 
741
- _addTelemetryInitializer(dropBrowserLinkRequests)
674
+ _self.addTelemetryInitializer(dropBrowserLinkRequests);
675
+ _browserLinkInitializerAdded = true;
742
676
  }
743
677
  }
744
678
 
745
- function _addTelemetryInitializer(telemetryInitializer: (envelope: ITelemetryItem) => boolean | void) {
746
- _self._telemetryInitializers.push(telemetryInitializer);
747
- }
748
-
749
679
  function _sendCORSException(exception: IAutoExceptionTelemetry, properties?: ICustomProperties) {
750
- const telemetryItem: ITelemetryItem = TelemetryItemCreator.create<IAutoExceptionTelemetry>(
680
+ let telemetryItem: ITelemetryItem = TelemetryItemCreator.create<IAutoExceptionTelemetry>(
751
681
  exception,
752
682
  Exception.dataType,
753
683
  Exception.envelopeType,
@@ -757,6 +687,196 @@ export class ApplicationInsights extends BaseTelemetryPlugin implements IAppInsi
757
687
 
758
688
  _self.core.track(telemetryItem);
759
689
  }
690
+
691
+ function _updateExceptionTracking(extConfig: IConfig) {
692
+ let _window = getWindow();
693
+ let locn = getLocation(true);
694
+
695
+ _disableExceptionTracking = extConfig.disableExceptionTracking;
696
+
697
+ if (!_disableExceptionTracking && !_autoExceptionInstrumented && !extConfig.autoExceptionInstrumented) {
698
+ // We want to enable exception auto collection and it has not been done so yet
699
+ _addHook(InstrumentFunc(_window, "onerror", {
700
+ ns: _evtNamespace,
701
+ rsp: (callDetails: IInstrumentCallDetails, message, url, lineNumber, columnNumber, error) => {
702
+ if (!_disableExceptionTracking && callDetails.rslt !== true) {
703
+ _self._onerror(Exception.CreateAutoException(
704
+ message,
705
+ url,
706
+ lineNumber,
707
+ columnNumber,
708
+ error,
709
+ callDetails.evt
710
+ ));
711
+ }
712
+ }
713
+ }));
714
+
715
+ _autoExceptionInstrumented = true;
716
+ }
717
+
718
+ _addUnhandledPromiseRejectionTracking(extConfig, _window, locn);
719
+ }
720
+
721
+ function _updateLocationChange(extConfig: IConfig) {
722
+ let win = getWindow();
723
+ let locn = getLocation(true);
724
+
725
+ _enableAutoRouteTracking = extConfig.enableAutoRouteTracking === true;
726
+
727
+ /**
728
+ * Create a custom "locationchange" event which is triggered each time the history object is changed
729
+ */
730
+ if (win && _enableAutoRouteTracking && hasHistory()) {
731
+ let _history = getHistory();
732
+
733
+ if (isFunction(_history.pushState) && isFunction(_history.replaceState) && typeof Event !== strUndefined) {
734
+ _addHistoryListener(extConfig, win, _history, locn);
735
+ }
736
+ }
737
+ }
738
+
739
+ /**
740
+ * Create a custom "locationchange" event which is triggered each time the history object is changed
741
+ */
742
+ function _addHistoryListener(extConfig: IConfig, win: Window, history: History, locn: Location) {
743
+
744
+ function _popstateHandler() {
745
+ if (_enableAutoRouteTracking) {
746
+ _dispatchEvent(win, createDomEvent(extConfig.namePrefix + "locationchange"));
747
+ }
748
+ }
749
+
750
+ function _locationChangeHandler() {
751
+ // We always track the changes (if the handler is installed) to handle the feature being disabled between location changes
752
+ if (_currUri) {
753
+ _prevUri = _currUri;
754
+ _currUri = locn && locn.href || "";
755
+ } else {
756
+ _currUri = locn && locn.href || "";
757
+ }
758
+
759
+ if (_enableAutoRouteTracking) {
760
+ let properties = _self.core.getPlugin<PropertiesPlugin>(PropertiesPluginIdentifier);
761
+
762
+ if (properties) {
763
+ let context = properties.plugin.context;
764
+ if (context && context.telemetryTrace) {
765
+ context.telemetryTrace.traceID = generateW3CId();
766
+ let traceLocationName = "_unknown_";
767
+ if (locn && locn.pathname) {
768
+ traceLocationName = locn.pathname + (locn.hash || "");
769
+ }
770
+
771
+ // This populates the ai.operation.name which has a maximum size of 1024 so we need to sanitize it
772
+ context.telemetryTrace.name = dataSanitizeString(_self.diagLog(), traceLocationName);
773
+ }
774
+ }
775
+
776
+ setTimeout(((uri: string) => {
777
+ // todo: override start time so that it is not affected by autoRoutePVDelay
778
+ _self.trackPageView({ refUri: uri, properties: { duration: 0 } }); // SPA route change loading durations are undefined, so send 0
779
+ }).bind(this, _prevUri), _self.autoRoutePVDelay);
780
+ }
781
+ }
782
+
783
+ if (!_historyListenerAdded) {
784
+ _addHook(InstrumentFunc(history, "pushState", {
785
+ ns: _evtNamespace,
786
+ rsp: () => {
787
+ if (_enableAutoRouteTracking) {
788
+ _dispatchEvent(win, createDomEvent(extConfig.namePrefix + "pushState"));
789
+ _dispatchEvent(win, createDomEvent(extConfig.namePrefix + "locationchange"));
790
+ }
791
+ }
792
+ }));
793
+
794
+ _addHook(InstrumentFunc(history, "replaceState", {
795
+ ns: _evtNamespace,
796
+ rsp: () => {
797
+ if (_enableAutoRouteTracking) {
798
+ _dispatchEvent(win, createDomEvent(extConfig.namePrefix + "replaceState"));
799
+ _dispatchEvent(win, createDomEvent(extConfig.namePrefix + "locationchange"));
800
+ }
801
+ }
802
+ }));
803
+
804
+ eventOn(win, extConfig.namePrefix + "popstate", _popstateHandler, _evtNamespace);
805
+ eventOn(win, extConfig.namePrefix + "locationchange", _locationChangeHandler, _evtNamespace);
806
+
807
+ _historyListenerAdded = true;
808
+ }
809
+ }
810
+
811
+ function _addUnhandledPromiseRejectionTracking(extConfig: IConfig, _window: Window, _location: Location) {
812
+ _enableUnhandledPromiseRejectionTracking = extConfig.enableUnhandledPromiseRejectionTracking === true;
813
+
814
+ if (_enableUnhandledPromiseRejectionTracking && !_autoUnhandledPromiseInstrumented) {
815
+ // We want to enable exception auto collection and it has not been done so yet
816
+ _addHook(InstrumentFunc(_window, "onunhandledrejection", {
817
+ ns: _evtNamespace,
818
+ rsp: (callDetails: IInstrumentCallDetails, error: PromiseRejectionEvent) => {
819
+ if (_enableUnhandledPromiseRejectionTracking && callDetails.rslt !== true) { // handled could be typeof function
820
+ _self._onerror(Exception.CreateAutoException(
821
+ _getReason(error),
822
+ _location ? _location.href : "",
823
+ 0,
824
+ 0,
825
+ error,
826
+ callDetails.evt
827
+ ));
828
+ }
829
+ }
830
+ }));
831
+
832
+ _autoUnhandledPromiseInstrumented = true;
833
+ extConfig.autoUnhandledPromiseInstrumented = _autoUnhandledPromiseInstrumented;
834
+ }
835
+ }
836
+
837
+ /**
838
+ * This method will throw exceptions in debug mode or attempt to log the error as a console warning.
839
+ * @param severity {LoggingSeverity} - The severity of the log message
840
+ * @param message {_InternalLogMessage} - The log message.
841
+ */
842
+ function _throwInternal(severity: LoggingSeverity, msgId: _InternalMessageId, msg: string, properties?: Object, isUserAct?: boolean): void {
843
+ _self.diagLog().throwInternal(severity, msgId, msg, properties, isUserAct);
844
+ }
845
+
846
+ function _initDefaults() {
847
+ _eventTracking = null;
848
+ _pageTracking = null;
849
+ _pageViewManager = null;
850
+ _pageViewPerformanceManager = null;
851
+ _pageVisitTimeManager = null;
852
+ _preInitTelemetryInitializers = null;
853
+ _isBrowserLinkTrackingEnabled = false;
854
+ _browserLinkInitializerAdded = false;
855
+ _enableAutoRouteTracking = false;
856
+ _historyListenerAdded = false;
857
+ _disableExceptionTracking = false;
858
+ _autoExceptionInstrumented = false;
859
+ _enableUnhandledPromiseRejectionTracking = false;
860
+ _autoUnhandledPromiseInstrumented = false;
861
+
862
+ // Counts number of trackAjax invocations.
863
+ // By default we only monitor X ajax call per view to avoid too much load.
864
+ // Default value is set in config.
865
+ // This counter keeps increasing even after the limit is reached.
866
+ _trackAjaxAttempts = 0;
867
+
868
+ // array with max length of 2 that store current url and previous url for SPA page route change trackPageview use.
869
+ let location = getLocation(true);
870
+ _prevUri = location && location.href || "";
871
+ _currUri = null;
872
+ _evtNamespace = null;
873
+ }
874
+
875
+ // For backward compatibility
876
+ objDefineAccessors(_self, "_pageViewManager", () => _pageViewManager);
877
+ objDefineAccessors(_self, "_pageViewPerformanceManager", () => _pageViewPerformanceManager);
878
+ objDefineAccessors(_self, "_pageVisitTimeManager", () => _pageVisitTimeManager);
879
+ objDefineAccessors(_self, "_evtNamespace", () => "." + _evtNamespace);
760
880
  });
761
881
  }
762
882
 
@@ -867,7 +987,6 @@ export class ApplicationInsights extends BaseTelemetryPlugin implements IAppInsi
867
987
  // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
868
988
  }
869
989
 
870
-
871
990
  /**
872
991
  * Stops the timer that was started by calling `startTrackPage` and sends the pageview load time telemetry with the specified properties and measurements.
873
992
  * The duration of the page view will be the time between calling `startTrackPage` and `stopTrackPage`.
@@ -880,7 +999,7 @@ export class ApplicationInsights extends BaseTelemetryPlugin implements IAppInsi
880
999
  // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
881
1000
  }
882
1001
 
883
- /**
1002
+ /**
884
1003
  * @ignore INTERNAL ONLY
885
1004
  * @param exception
886
1005
  * @param properties
@@ -912,52 +1031,11 @@ export class ApplicationInsights extends BaseTelemetryPlugin implements IAppInsi
912
1031
  // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
913
1032
  }
914
1033
 
915
- public addTelemetryInitializer(telemetryInitializer: (item: ITelemetryItem) => boolean | void) {
1034
+ public addTelemetryInitializer(telemetryInitializer: (item: ITelemetryItem) => boolean | void): ITelemetryInitializerHandler | void {
916
1035
  // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
917
1036
  }
918
1037
 
919
1038
  public initialize(config: IConfiguration & IConfig, core: IAppInsightsCore, extensions: IPlugin[], pluginChain?:ITelemetryPluginChain) {
920
1039
  // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging
921
1040
  }
922
- }
923
-
924
- /**
925
- * Used to record timed events and page views.
926
- */
927
- class Timing {
928
-
929
- public action: (name?: string, url?: string, duration?: number, properties?: { [key: string]: string }, measurements?: { [key: string]: number }) => void;
930
- public start: (name: string) => void;
931
- public stop: (name: string, url: string, properties?: { [key: string]: string }, measurements?: { [key: string]: number }) => void;
932
-
933
- constructor(logger: IDiagnosticLogger, name: string) {
934
- let _self = this;
935
- let _events: { [key: string]: number; } = {}
936
-
937
- _self.start = (name: string) => {
938
- if (typeof _events[name] !== "undefined") {
939
- logger.throwInternal(
940
- LoggingSeverity.WARNING, _InternalMessageId.StartCalledMoreThanOnce, "start was called more than once for this event without calling stop.",
941
- { name, key: name }, true);
942
- }
943
-
944
- _events[name] = +new Date;
945
- }
946
-
947
- _self.stop = (name: string, url: string, properties?: { [key: string]: string }, measurements?: { [key: string]: number }) => {
948
- const start = _events[name];
949
- if (isNaN(start)) {
950
- logger.throwInternal(
951
- LoggingSeverity.WARNING, _InternalMessageId.StopCalledWithoutStart, "stop was called without a corresponding start.",
952
- { name, key: name }, true);
953
- } else {
954
- const end = +new Date;
955
- const duration = dateTimeUtilsDuration(start, end);
956
- _self.action(name, url, duration, properties, measurements);
957
- }
958
-
959
- delete _events[name];
960
- _events[name] = undefined;
961
- }
962
- }
963
1041
  }