@amplitude/analytics-core 2.12.0 → 2.13.0-networkcaptureprerelease.0

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.
@@ -40,6 +40,7 @@ export { PageTrackingOptions, PageTrackingTrackOn, PageTrackingHistoryChanges }
40
40
  export { Status } from './types/status';
41
41
  export { BrowserConfig, BrowserOptions, DefaultTrackingOptions, TrackingOptions, AutocaptureOptions, CookieOptions, AttributionOptions, } from './types/browser-config';
42
42
  export { BrowserClient } from './types/browser-client';
43
- export { NetworkRequestEvent, NetworkEventCallback, networkObserver } from './network-observer';
43
+ export { NetworkEventCallback, networkObserver } from './network-observer';
44
+ export { NetworkRequestEvent } from './network-request-event';
44
45
  export { NetworkTrackingOptions, NetworkCaptureRule } from './types/network-tracking';
45
46
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAC1D,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AACjD,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,eAAe,EAAE,MAAM,WAAW,CAAC;AAC/D,OAAO,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AACpD,OAAO,EAAE,mBAAmB,EAAE,MAAM,oBAAoB,CAAC;AACzD,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,eAAe,EAAE,MAAM,UAAU,CAAC;AAC5D,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,SAAS,EAAE,MAAM,UAAU,CAAC;AACtD,OAAO,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAChD,OAAO,EAAE,qBAAqB,EAAE,oBAAoB,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AACxG,OAAO,EAAE,YAAY,EAAE,MAAM,WA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BAAoB,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AAC3E,OAAO,EAAE,mBAAmB,EAAE,MAAM,yBAAyB,CAAC;AAC9D,OAAO,EAAE,sBAAsB,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC"}
package/lib/cjs/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.networkObserver = exports.NetworkEventCallback = exports.Status = exports.DEFAULT_ACTION_CLICK_ALLOWLIST = exports.DEFAULT_DATA_ATTRIBUTE_PREFIX = exports.DEFAULT_CSS_SELECTOR_ALLOWLIST = exports.OfflineDisabled = exports.ServerZone = exports.SpecialEventType = exports.IdentifyOperation = exports.STORAGE_PREFIX = exports.AMPLITUDE_PREFIX = exports.LogLevel = exports.FetchTransport = exports.BaseTransport = exports.getStorageKey = exports.CookieStorage = exports.MemoryStorage = exports.createIdentifyEvent = exports.UUID = exports.getClientStates = exports.getClientLogConfig = exports.debugWrapper = exports.returnWrapper = exports.getQueryParams = exports.getLanguage = exports.getOldCookieName = exports.getCookieName = exports.isNewSession = exports.setConnectorUserId = exports.setConnectorDeviceId = exports.getAnalyticsConnector = exports.getGlobalScope = exports.Logger = exports.RequestMetadata = exports.Config = exports.IdentityEventSender = exports.Destination = exports.RevenueProperty = exports.Revenue = exports.Identify = exports.AmplitudeCore = void 0;
3
+ exports.NetworkRequestEvent = exports.networkObserver = exports.NetworkEventCallback = exports.Status = exports.DEFAULT_ACTION_CLICK_ALLOWLIST = exports.DEFAULT_DATA_ATTRIBUTE_PREFIX = exports.DEFAULT_CSS_SELECTOR_ALLOWLIST = exports.OfflineDisabled = exports.ServerZone = exports.SpecialEventType = exports.IdentifyOperation = exports.STORAGE_PREFIX = exports.AMPLITUDE_PREFIX = exports.LogLevel = exports.FetchTransport = exports.BaseTransport = exports.getStorageKey = exports.CookieStorage = exports.MemoryStorage = exports.createIdentifyEvent = exports.UUID = exports.getClientStates = exports.getClientLogConfig = exports.debugWrapper = exports.returnWrapper = exports.getQueryParams = exports.getLanguage = exports.getOldCookieName = exports.getCookieName = exports.isNewSession = exports.setConnectorUserId = exports.setConnectorDeviceId = exports.getAnalyticsConnector = exports.getGlobalScope = exports.Logger = exports.RequestMetadata = exports.Config = exports.IdentityEventSender = exports.Destination = exports.RevenueProperty = exports.Revenue = exports.Identify = exports.AmplitudeCore = void 0;
4
4
  var core_client_1 = require("./core-client");
5
5
  Object.defineProperty(exports, "AmplitudeCore", { enumerable: true, get: function () { return core_client_1.AmplitudeCore; } });
6
6
  var identify_1 = require("./identify");
@@ -73,4 +73,6 @@ Object.defineProperty(exports, "Status", { enumerable: true, get: function () {
73
73
  var network_observer_1 = require("./network-observer");
74
74
  Object.defineProperty(exports, "NetworkEventCallback", { enumerable: true, get: function () { return network_observer_1.NetworkEventCallback; } });
75
75
  Object.defineProperty(exports, "networkObserver", { enumerable: true, get: function () { return network_observer_1.networkObserver; } });
76
+ var network_request_event_1 = require("./network-request-event");
77
+ Object.defineProperty(exports, "NetworkRequestEvent", { enumerable: true, get: function () { return network_request_event_1.NetworkRequestEvent; } });
76
78
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;AAAA,6CAA0D;AAAjD,4GAAA,aAAa,OAAA;AACtB,uCAAiD;AAAxC,oGAAA,QAAQ,OAAA;AACjB,qCAA+D;AAAtD,kGAAA,OAAO,OAAA;AAAY,0GAAA,eAAe,OAAA;AAC3C,qDAAoD;AAA3C,0GAAA,WAAW,OAAA;AACpB,+CAAyD;AAAhD,+GAAA,mBAAmB,OAAA;AAC5B,mCAA4D;AAA1C,gGAAA,MAAM,OAAA;AAAE,yGAAA,eAAe,OAAA;AACzC,mCAAsD;AAA7C,gGAAA,MAAM,OAAA;AACf,+CAAgD;AAAvC,8GAAA,cAAc,OAAA;AACvB,6DAAwG;AAA/F,4HAAA,qBAAqB,OAA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enue, RevenueProperty } from './revenue';\nexport { Destination } from './plugins/destination';\nexport { IdentityEventSender } from './plugins/identity';\nexport { IConfig, Config, RequestMetadata } from './config';\nexport { Logger, ILogger, LogConfig } from './logger';\nexport { getGlobalScope } from './global-scope';\nexport { getAnalyticsConnector, setConnectorDeviceId, setConnectorUserId } from './analytics-connector';\nexport { isNewSession } from './session';\nexport { getCookieName, getOldCookieName } from './cookie-name';\nexport { getLanguage } from './language';\nexport { getQueryParams } from './query-params';\n\nexport { returnWrapper, AmplitudeReturn } from './utils/return-wrapper';\nexport { debugWrapper, getClientLogConfig, getClientStates } from './utils/debug';\nexport { UUID } from './utils/uuid';\nexport { createIdentifyEvent } from './utils/event-builder';\n\nexport { MemoryStorage } from './storage/memory';\nexport { CookieStorage } from './storage/cookie';\nexport { getStorageKey } from './storage/helpers';\n\nexport { BaseTransport } from './transports/base';\nexport { FetchTransport } from './transports/fetch';\n\nexport { LogLevel } from './types/loglevel';\nexport { AMPLITUDE_PREFIX, STORAGE_PREFIX } from './types/constants';\nexport { Storage, IdentityStorageType } from './types/storage';\nexport { Event, IdentifyOperation, SpecialEventType, IdentifyEvent, GroupIdentifyEvent } from './types/event/event';\nexport { EventOptions, BaseEvent } from './types/event/base-event';\nexport { IngestionMetadata } from './types/event/ingestion-metadata';\nexport { ServerZoneType, ServerZone } from './types/server-zone';\nexport { OfflineDisabled } from './types/offline';\nexport { Plan } from './types/event/plan';\nexport { TransportType, Transport } from './types/transport';\nexport { Payload } from './types/payload';\nexport { Response } from './types/response';\nexport { UserSession } from './types/user-session';\nexport { Plugin, BeforePlugin, DestinationPlugin, EnrichmentPlugin, PluginType } from './types/plugin';\nexport { Result } from './types/result';\nexport {\n ElementInteractionsOptions,\n Messenger,\n ActionType,\n DEFAULT_CSS_SELECTOR_ALLOWLIST,\n DEFAULT_DATA_ATTRIBUTE_PREFIX,\n DEFAULT_ACTION_CLICK_ALLOWLIST,\n} from './types/element-interactions';\nexport { PageTrackingOptions, PageTrackingTrackOn, PageTrackingHistoryChanges } from './types/page-view-tracking';\nexport { Status } from './types/status';\nexport {\n BrowserConfig,\n BrowserOptions,\n DefaultTrackingOptions,\n TrackingOptions,\n AutocaptureOptions,\n CookieOptions,\n AttributionOptions,\n} from './types/browser-config';\nexport { BrowserClient } from './types/browser-client';\n\nexport { NetworkRequestEvent, NetworkEventCallback, networkObserver } from './network-observer';\nexport { NetworkTrackingOptions, NetworkCaptureRule } from './types/network-tracking';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;AAAA,6CAA0D;AAAjD,4GAAA,aAAa,OAAA;AACtB,uCAAiD;AAAxC,oGAAA,QAAQ,OAAA;AACjB,qCAA+D;AAAtD,kGAAA,OAAO,OAAA;AAAY,0GAAA,eAAe,OAAA;AAC3C,qDAAoD;AAA3C,0GAAA,WAAW,OAAA;AACpB,+CAAyD;AAAhD,+GAAA,mBAAmB,OAAA;AAC5B,mCAA4D;AAA1C,gGAAA,MAAM,OAAA;AAAE,yGAAA,eAAe,OAAA;AACzC,mCAAsD;AAA7C,gGAAA,MAAM,OAAA;AACf,+CAAgD;AAAvC,8GAAA,cAAc,OAAA;AACvB,6DAAwG;AAA/F,4HAAA,qBAAqB,OAAA;AAAE,2HAAA,oBAAoB,OAAA;AAAE,yHAAA,kBAAkB,OAAA;AACxE,qCAAyC;AAAhC,uGAAA,YAAY,OAAA;AACrB,6CAAgE;AAAvD,4GAAA,aAAa,OAAA;AAAE,+GAAA,gBAAgB,OAAA;AACxC,uCAAyC;AAAhC,uGAAA,WAAW,OAAA;AACpB,+CAAgD;AAAvC,8GAAA,cAAc,OAAA;AAEvB,yDAAwE;AAA/D,+GAAA,aAAa,OAAA;AACtB,uCAAkF;AAAzE,qGAAA,YAAY,OAAA;AAAE,2GAAA,kBAAkB,OAAA;AAAE,wGAAA,eAAe,OAAA;AAC1D,qCAAoC;AAA3B,4FAAA,IAAI,OAAA;AACb,uDAA4D;AAAnD,oHAAA,mBAAmB,OAAA;AAE5B,2CAAiD;AAAxC,uGAAA,aAAa,OAAA;AACtB,2CAAiD;AAAxC,uGAAA,aAAa,OAAA;AACtB,6CAAkD;AAAzC,wGAAA,aAAa,OAAA;AAEtB,0CAAkD;AAAzC,qGAAA,aAAa,OAAA;AACtB,4CAAoD;AAA3C,uGAAA,cAAc,OAAA;AAEvB,6CAA4C;AAAnC,oGAAA,QAAQ,OAAA;AACjB,+CAAqE;AAA5D,6GAAA,gBAAgB,OAAA;AAAE,2GAAA,cAAc,OAAA;AAEzC,6CAAoH;AAApG,0GAAA,iBAAiB,OAAA;AAAE,yGAAA,gBAAgB,OAAA;AAGnD,mDAAiE;AAAxC,yGAAA,UAAU,OAAA;AACnC,2CAAkD;AAAzC,0GAAA,eAAe,OAAA;AAQxB,qEAOsC;AAHpC,sIAAA,8BAA8B,OAAA;AAC9B,qIAAA,6BAA6B,OAAA;AAC7B,sIAAA,8BAA8B,OAAA;AAGhC,yCAAwC;AAA/B,gGAAA,MAAM,OAAA;AAYf,uDAA2E;AAAlE,wHAAA,oBAAoB,OAAA;AAAE,mHAAA,eAAe,OAAA;AAC9C,iEAA8D;AAArD,4HAAA,mBAAmB,OAAA","sourcesContent":["export { AmplitudeCore, CoreClient } from './core-client';\nexport { Identify, IIdentify } from './identify';\nexport { Revenue, IRevenue, RevenueProperty } from './revenue';\nexport { Destination } from './plugins/destination';\nexport { IdentityEventSender } from './plugins/identity';\nexport { IConfig, Config, RequestMetadata } from './config';\nexport { Logger, ILogger, LogConfig } from './logger';\nexport { getGlobalScope } from './global-scope';\nexport { getAnalyticsConnector, setConnectorDeviceId, setConnectorUserId } from './analytics-connector';\nexport { isNewSession } from './session';\nexport { getCookieName, getOldCookieName } from './cookie-name';\nexport { getLanguage } from './language';\nexport { getQueryParams } from './query-params';\n\nexport { returnWrapper, AmplitudeReturn } from './utils/return-wrapper';\nexport { debugWrapper, getClientLogConfig, getClientStates } from './utils/debug';\nexport { UUID } from './utils/uuid';\nexport { createIdentifyEvent } from './utils/event-builder';\n\nexport { MemoryStorage } from './storage/memory';\nexport { CookieStorage } from './storage/cookie';\nexport { getStorageKey } from './storage/helpers';\n\nexport { BaseTransport } from './transports/base';\nexport { FetchTransport } from './transports/fetch';\n\nexport { LogLevel } from './types/loglevel';\nexport { AMPLITUDE_PREFIX, STORAGE_PREFIX } from './types/constants';\nexport { Storage, IdentityStorageType } from './types/storage';\nexport { Event, IdentifyOperation, SpecialEventType, IdentifyEvent, GroupIdentifyEvent } from './types/event/event';\nexport { EventOptions, BaseEvent } from './types/event/base-event';\nexport { IngestionMetadata } from './types/event/ingestion-metadata';\nexport { ServerZoneType, ServerZone } from './types/server-zone';\nexport { OfflineDisabled } from './types/offline';\nexport { Plan } from './types/event/plan';\nexport { TransportType, Transport } from './types/transport';\nexport { Payload } from './types/payload';\nexport { Response } from './types/response';\nexport { UserSession } from './types/user-session';\nexport { Plugin, BeforePlugin, DestinationPlugin, EnrichmentPlugin, PluginType } from './types/plugin';\nexport { Result } from './types/result';\nexport {\n ElementInteractionsOptions,\n Messenger,\n ActionType,\n DEFAULT_CSS_SELECTOR_ALLOWLIST,\n DEFAULT_DATA_ATTRIBUTE_PREFIX,\n DEFAULT_ACTION_CLICK_ALLOWLIST,\n} from './types/element-interactions';\nexport { PageTrackingOptions, PageTrackingTrackOn, PageTrackingHistoryChanges } from './types/page-view-tracking';\nexport { Status } from './types/status';\nexport {\n BrowserConfig,\n BrowserOptions,\n DefaultTrackingOptions,\n TrackingOptions,\n AutocaptureOptions,\n CookieOptions,\n AttributionOptions,\n} from './types/browser-config';\nexport { BrowserClient } from './types/browser-client';\n\nexport { NetworkEventCallback, networkObserver } from './network-observer';\nexport { NetworkRequestEvent } from './network-request-event';\nexport { NetworkTrackingOptions, NetworkCaptureRule } from './types/network-tracking';\n"]}
@@ -1,28 +1,5 @@
1
1
  import { ILogger } from '.';
2
- export interface NetworkRequestEvent {
3
- type: string;
4
- method: string;
5
- url: string;
6
- timestamp: number;
7
- status?: number;
8
- duration?: number;
9
- requestBodySize?: number;
10
- requestHeaders?: Record<string, string>;
11
- responseBodySize?: number;
12
- responseHeaders?: Record<string, string>;
13
- error?: {
14
- name: string;
15
- message: string;
16
- };
17
- startTime?: number;
18
- endTime?: number;
19
- }
20
- type FormDataEntryValueBrowser = string | Blob | null;
21
- export interface FormDataBrowser {
22
- entries(): IterableIterator<[string, FormDataEntryValueBrowser]>;
23
- }
24
- export type FetchRequestBody = string | Blob | ArrayBuffer | FormDataBrowser | URLSearchParams | null | undefined;
25
- export declare function getRequestBodyLength(body: FetchRequestBody | null | undefined): number | undefined;
2
+ import { NetworkRequestEvent } from './network-request-event';
26
3
  export type NetworkEventCallbackFn = (event: NetworkRequestEvent) => void;
27
4
  export declare class NetworkEventCallback {
28
5
  readonly callback: (event: NetworkRequestEvent) => void;
@@ -30,18 +7,19 @@ export declare class NetworkEventCallback {
30
7
  constructor(callback: (event: NetworkRequestEvent) => void, id?: string);
31
8
  }
32
9
  export declare class NetworkObserver {
33
- private originalFetch?;
34
10
  private eventCallbacks;
35
- private isObserving;
36
11
  private globalScope?;
37
12
  private logger?;
13
+ private isObserving;
38
14
  constructor(logger?: ILogger);
39
15
  static isSupported(): boolean;
40
16
  subscribe(eventCallback: NetworkEventCallback, logger?: ILogger): void;
41
17
  unsubscribe(eventCallback: NetworkEventCallback): void;
42
18
  protected triggerEventCallbacks(event: NetworkRequestEvent): void;
19
+ private handleNetworkRequestEvent;
20
+ private getTimestamps;
43
21
  private observeFetch;
22
+ private observeXhr;
44
23
  }
45
24
  export declare const networkObserver: NetworkObserver;
46
- export {};
47
25
  //# sourceMappingURL=network-observer.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"network-observer.d.ts","sourceRoot":"","sources":["../../src/network-observer.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,OAAO,EAAE,MAAM,GAAG,CAAC;AAG5B,MAAM,WAAW,mBAAmB;IAClC,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,E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AAE,oBAAoB;IAI/C,SAAS,CAAC,qBAAqB,CAAC,KAAK,EAAE,mBAAmB;IAa1D,OAAO,CAAC,yBAAyB;IA4DjC,OAAO,CAAC,aAAa;IAQrB,OAAO,CAAC,YAAY;IA8DpB,OAAO,CAAC,UAAU;CAyFnB;AAGD,eAAO,MAAM,eAAe,iBAAwB,CAAC"}
@@ -1,68 +1,16 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.networkObserver = exports.NetworkObserver = exports.NetworkEventCallback = exports.getRequestBodyLength = void 0;
3
+ exports.networkObserver = exports.NetworkObserver = exports.NetworkEventCallback = void 0;
4
4
  var tslib_1 = require("tslib");
5
- var global_scope_1 = require("./global-scope");
5
+ var _1 = require("./");
6
6
  var uuid_1 = require("./utils/uuid");
7
- var MAXIMUM_ENTRIES = 100;
8
- function getRequestBodyLength(body) {
9
- var e_1, _a;
10
- var global = (0, global_scope_1.getGlobalScope)();
11
- if (!(global === null || global === void 0 ? void 0 : global.TextEncoder)) {
12
- return;
13
- }
14
- var TextEncoder = global.TextEncoder;
15
- if (typeof body === 'string') {
16
- return new TextEncoder().encode(body).length;
17
- }
18
- else if (body instanceof Blob) {
19
- return body.size;
20
- }
21
- else if (body instanceof URLSearchParams) {
22
- return new TextEncoder().encode(body.toString()).length;
23
- }
24
- else if (body instanceof ArrayBuffer) {
25
- return body.byteLength;
26
- }
27
- else if (ArrayBuffer.isView(body)) {
28
- return body.byteLength;
29
- }
30
- else if (body instanceof FormData) {
31
- // Estimating only for text parts; not accurate for files
32
- var formData = body;
33
- var total = 0;
34
- var count = 0;
35
- try {
36
- for (var _b = tslib_1.__values(formData.entries()), _c = _b.next(); !_c.done; _c = _b.next()) {
37
- var _d = tslib_1.__read(_c.value, 2), key = _d[0], value = _d[1];
38
- total += key.length;
39
- if (typeof value === 'string') {
40
- total += new TextEncoder().encode(value).length;
41
- }
42
- else if (value.size) {
43
- // if we encounter a "File" type, we should not count it and just return undefined
44
- total += value.size;
45
- }
46
- // terminate if we reach the maximum number of entries
47
- // to avoid performance issues in case of very large FormDataß
48
- if (++count >= MAXIMUM_ENTRIES) {
49
- return;
50
- }
51
- }
52
- }
53
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
54
- finally {
55
- try {
56
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
57
- }
58
- finally { if (e_1) throw e_1.error; }
59
- }
60
- return total;
61
- }
62
- // Stream or unknown
63
- return;
7
+ var network_request_event_1 = require("./network-request-event");
8
+ /**
9
+ * Typeguard function checks if an input is a Request object.
10
+ */
11
+ function isRequest(requestInfo) {
12
+ return typeof requestInfo === 'object' && requestInfo !== null && 'url' in requestInfo && 'method' in requestInfo;
64
13
  }
65
- exports.getRequestBodyLength = getRequestBodyLength;
66
14
  var NetworkEventCallback = /** @class */ (function () {
67
15
  function NetworkEventCallback(callback, id) {
68
16
  if (id === void 0) { id = (0, uuid_1.UUID)(); }
@@ -74,39 +22,48 @@ var NetworkEventCallback = /** @class */ (function () {
74
22
  exports.NetworkEventCallback = NetworkEventCallback;
75
23
  var NetworkObserver = /** @class */ (function () {
76
24
  function NetworkObserver(logger) {
77
- var _a;
78
25
  this.eventCallbacks = new Map();
79
26
  this.isObserving = false;
80
27
  this.logger = logger;
81
- var globalScope = (0, global_scope_1.getGlobalScope)();
28
+ var globalScope = (0, _1.getGlobalScope)();
82
29
  if (!NetworkObserver.isSupported()) {
83
30
  /* istanbul ignore next */
84
31
  return;
85
32
  }
86
33
  this.globalScope = globalScope;
87
- /* istanbul ignore next */
88
- this.originalFetch = (_a = this.globalScope) === null || _a === void 0 ? void 0 : _a.fetch;
89
34
  }
90
35
  NetworkObserver.isSupported = function () {
91
- var globalScope = (0, global_scope_1.getGlobalScope)();
36
+ var globalScope = (0, _1.getGlobalScope)();
92
37
  return !!globalScope && !!globalScope.fetch;
93
38
  };
94
39
  NetworkObserver.prototype.subscribe = function (eventCallback, logger) {
40
+ var _a, _b, _c, _d, _e, _f, _g;
95
41
  if (!this.logger) {
96
42
  this.logger = logger;
97
43
  }
98
44
  this.eventCallbacks.set(eventCallback.id, eventCallback);
99
45
  if (!this.isObserving) {
100
- this.observeFetch();
46
+ /* istanbul ignore next */
47
+ // eslint-disable-next-line @typescript-eslint/unbound-method
48
+ var originalXhrOpen = (_c = (_b = (_a = this.globalScope) === null || _a === void 0 ? void 0 : _a.XMLHttpRequest) === null || _b === void 0 ? void 0 : _b.prototype) === null || _c === void 0 ? void 0 : _c.open;
49
+ /* istanbul ignore next */
50
+ // eslint-disable-next-line @typescript-eslint/unbound-method
51
+ var originalXhrSend = (_f = (_e = (_d = this.globalScope) === null || _d === void 0 ? void 0 : _d.XMLHttpRequest) === null || _e === void 0 ? void 0 : _e.prototype) === null || _f === void 0 ? void 0 : _f.send;
52
+ if (originalXhrOpen && originalXhrSend) {
53
+ this.observeXhr(originalXhrOpen, originalXhrSend);
54
+ }
55
+ /* istanbul ignore next */
56
+ var originalFetch = (_g = this.globalScope) === null || _g === void 0 ? void 0 : _g.fetch;
57
+ /* istanbul ignore next */
58
+ if (originalFetch) {
59
+ this.observeFetch(originalFetch);
60
+ }
61
+ /* istanbul ignore next */
101
62
  this.isObserving = true;
102
63
  }
103
64
  };
104
65
  NetworkObserver.prototype.unsubscribe = function (eventCallback) {
105
66
  this.eventCallbacks.delete(eventCallback.id);
106
- if (this.originalFetch && this.globalScope && this.eventCallbacks.size === 0 && this.isObserving) {
107
- this.globalScope.fetch = this.originalFetch;
108
- this.isObserving = false;
109
- }
110
67
  };
111
68
  NetworkObserver.prototype.triggerEventCallbacks = function (event) {
112
69
  var _this = this;
@@ -116,76 +73,192 @@ var NetworkObserver = /** @class */ (function () {
116
73
  callback.callback(event);
117
74
  }
118
75
  catch (err) {
76
+ // if the callback throws an error, we should catch it
77
+ // to avoid breaking the fetch promise chain
119
78
  /* istanbul ignore next */
120
79
  (_a = _this.logger) === null || _a === void 0 ? void 0 : _a.debug('an unexpected error occurred while triggering event callbacks', err);
121
80
  }
122
81
  });
123
82
  };
124
- NetworkObserver.prototype.observeFetch = function () {
83
+ NetworkObserver.prototype.handleNetworkRequestEvent = function (requestType, requestInfo, requestWrapper, responseWrapper, typedError, startTime, durationStart) {
84
+ var _a;
85
+ /* istanbul ignore next */
86
+ if (startTime === undefined || durationStart === undefined) {
87
+ // if we reach this point, it means that the performance API is not supported
88
+ // so we can't construct a NetworkRequestEvent
89
+ return;
90
+ }
91
+ // parse the URL and Method
92
+ var url;
93
+ var method = 'GET';
94
+ if (isRequest(requestInfo)) {
95
+ url = requestInfo['url'];
96
+ method = requestInfo['method'];
97
+ }
98
+ else {
99
+ url = (_a = requestInfo === null || requestInfo === void 0 ? void 0 : requestInfo.toString) === null || _a === void 0 ? void 0 : _a.call(requestInfo);
100
+ }
101
+ method = (requestWrapper === null || requestWrapper === void 0 ? void 0 : requestWrapper.method) || method;
102
+ var status, error;
103
+ if (responseWrapper) {
104
+ status = responseWrapper.status;
105
+ }
106
+ if (typedError) {
107
+ error = {
108
+ name: typedError.name || 'UnknownError',
109
+ message: typedError.message || 'An unknown error occurred',
110
+ };
111
+ status = 0;
112
+ }
113
+ var duration = Math.floor(performance.now() - durationStart);
114
+ var endTime = Math.floor(startTime + duration);
115
+ var requestEvent = new network_request_event_1.NetworkRequestEvent(requestType, method, startTime, // timestamp and startTime are aliases
116
+ startTime, url, requestWrapper, status, duration, responseWrapper, error, endTime);
117
+ this.triggerEventCallbacks(requestEvent);
118
+ };
119
+ NetworkObserver.prototype.getTimestamps = function () {
120
+ var _a, _b;
121
+ /* istanbul ignore next */
122
+ return {
123
+ startTime: (_a = Date.now) === null || _a === void 0 ? void 0 : _a.call(Date),
124
+ durationStart: (_b = performance === null || performance === void 0 ? void 0 : performance.now) === null || _b === void 0 ? void 0 : _b.call(performance),
125
+ };
126
+ };
127
+ NetworkObserver.prototype.observeFetch = function (originalFetch) {
125
128
  var _this = this;
126
129
  /* istanbul ignore next */
127
- if (!this.globalScope || !this.originalFetch) {
130
+ if (!this.globalScope || !originalFetch) {
128
131
  return;
129
132
  }
130
- var originalFetch = this.globalScope.fetch;
131
- this.globalScope.fetch = function (input, init) { return tslib_1.__awaiter(_this, void 0, void 0, function () {
132
- var startTime, durationStart, requestEvent, response, headers_1, contentLength_1, error_1, endTime, typedError;
133
- return tslib_1.__generator(this, function (_a) {
134
- switch (_a.label) {
133
+ /**
134
+ * IMPORTANT: This overrides window.fetch in browsers.
135
+ * You probably never need to make changes to this function.
136
+ * If you do, please be careful to preserve the original functionality of fetch
137
+ * and make sure another developer who is an expert reviews this change throughly
138
+ */
139
+ this.globalScope.fetch = function (requestInfo, requestInit) { return tslib_1.__awaiter(_this, void 0, void 0, function () {
140
+ var timestamps, originalResponse, originalError, err_1;
141
+ var _a, _b;
142
+ return tslib_1.__generator(this, function (_c) {
143
+ switch (_c.label) {
135
144
  case 0:
136
- startTime = Date.now();
137
- durationStart = performance.now();
138
- requestEvent = {
139
- timestamp: startTime,
140
- startTime: startTime,
141
- type: 'fetch',
142
- method: (init === null || init === void 0 ? void 0 : init.method) || 'GET',
143
- url: input.toString(),
144
- requestHeaders: init === null || init === void 0 ? void 0 : init.headers,
145
- requestBodySize: getRequestBodyLength(init === null || init === void 0 ? void 0 : init.body),
146
- };
147
- _a.label = 1;
145
+ try {
146
+ timestamps = this.getTimestamps();
147
+ }
148
+ catch (error) {
149
+ /* istanbul ignore next */
150
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.debug('an unexpected error occurred while retrieving timestamps', error);
151
+ }
152
+ _c.label = 1;
148
153
  case 1:
149
- _a.trys.push([1, 3, , 4]);
150
- return [4 /*yield*/, originalFetch(input, init)];
154
+ _c.trys.push([1, 3, , 4]);
155
+ return [4 /*yield*/, originalFetch(requestInfo, requestInit)];
151
156
  case 2:
152
- response = _a.sent();
153
- requestEvent.status = response.status;
154
- requestEvent.duration = Math.floor(performance.now() - durationStart);
155
- requestEvent.startTime = startTime;
156
- requestEvent.endTime = Math.floor(startTime + requestEvent.duration);
157
- headers_1 = {};
158
- contentLength_1 = undefined;
159
- response.headers.forEach(function (value, key) {
160
- headers_1[key] = value;
161
- if (key === 'content-length') {
162
- contentLength_1 = parseInt(value, 10) || undefined;
163
- }
164
- });
165
- requestEvent.responseHeaders = headers_1;
166
- requestEvent.responseBodySize = contentLength_1;
167
- this.triggerEventCallbacks(requestEvent);
168
- return [2 /*return*/, response];
157
+ originalResponse = _c.sent();
158
+ return [3 /*break*/, 4];
169
159
  case 3:
170
- error_1 = _a.sent();
171
- endTime = Date.now();
172
- requestEvent.duration = endTime - startTime;
173
- typedError = error_1;
174
- requestEvent.error = {
175
- name: typedError.name || 'UnknownError',
176
- message: typedError.message || 'An unknown error occurred',
177
- };
178
- if (typedError.name === 'AbortError') {
179
- requestEvent.error.name = 'AbortError';
180
- requestEvent.status = 0;
160
+ err_1 = _c.sent();
161
+ // Capture error information
162
+ originalError = err_1;
163
+ return [3 /*break*/, 4];
164
+ case 4:
165
+ // 3. call the handler after the fetch call is done
166
+ try {
167
+ this.handleNetworkRequestEvent('fetch', requestInfo, requestInit ? new network_request_event_1.RequestWrapperFetch(requestInit) : undefined, originalResponse ? new network_request_event_1.ResponseWrapperFetch(originalResponse) : undefined, originalError,
168
+ /* istanbul ignore next */
169
+ timestamps === null || timestamps === void 0 ? void 0 : timestamps.startTime,
170
+ /* istanbul ignore next */
171
+ timestamps === null || timestamps === void 0 ? void 0 : timestamps.durationStart);
172
+ }
173
+ catch (err) {
174
+ // this catch shouldn't be reachable, but keep it here for safety
175
+ // because we're overriding the fetch function and better to be safe than sorry
176
+ /* istanbul ignore next */
177
+ (_b = this.logger) === null || _b === void 0 ? void 0 : _b.debug('an unexpected error occurred while handling fetch', err);
181
178
  }
182
- this.triggerEventCallbacks(requestEvent);
183
- throw error_1;
184
- case 4: return [2 /*return*/];
179
+ // 4. return the original response or throw the original error
180
+ if (originalResponse) {
181
+ // if the response is not undefined, return it
182
+ return [2 /*return*/, originalResponse];
183
+ }
184
+ else {
185
+ throw originalError;
186
+ }
187
+ return [2 /*return*/];
185
188
  }
186
189
  });
187
190
  }); };
188
191
  };
192
+ NetworkObserver.prototype.observeXhr = function (originalXhrOpen, originalXhrSend) {
193
+ /* istanbul ignore next */
194
+ if (!this.globalScope || !originalXhrOpen || !originalXhrSend) {
195
+ return;
196
+ }
197
+ var xhrProto = this.globalScope.XMLHttpRequest.prototype;
198
+ var networkObserverContext = this;
199
+ /**
200
+ * IMPORTANT: This overrides window.XMLHttpRequest.prototype.open
201
+ * You probably never need to make changes to this function.
202
+ * If you do, please be careful to preserve the original functionality of xhr.open
203
+ * and make sure another developer who is an expert reviews this change throughly
204
+ */
205
+ xhrProto.open = function () {
206
+ var _a, _b;
207
+ var args = [];
208
+ for (var _i = 0; _i < arguments.length; _i++) {
209
+ args[_i] = arguments[_i];
210
+ }
211
+ var xhrSafe = this;
212
+ var _c = tslib_1.__read(args, 2), method = _c[0], url = _c[1];
213
+ try {
214
+ /* istanbul ignore next */
215
+ xhrSafe.$$AmplitudeAnalyticsEvent = tslib_1.__assign({ method: method, url: (_a = url === null || url === void 0 ? void 0 : url.toString) === null || _a === void 0 ? void 0 : _a.call(url) }, networkObserverContext.getTimestamps());
216
+ }
217
+ catch (err) {
218
+ /* istanbul ignore next */
219
+ (_b = networkObserverContext.logger) === null || _b === void 0 ? void 0 : _b.debug('an unexpected error occurred while calling xhr open', err);
220
+ }
221
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
222
+ return originalXhrOpen.apply(xhrSafe, args);
223
+ };
224
+ /**
225
+ * IMPORTANT: This overrides window.XMLHttpRequest.prototype.send
226
+ * You probably never need to make changes to this function.
227
+ * If you do, please be careful to preserve the original functionality of xhr.send
228
+ * and make sure another developer who is an expert reviews this change throughly
229
+ */
230
+ // allow "any" type for args to reflect how it's used in the browser
231
+ /* eslint-disable-next-line @typescript-eslint/no-unsafe-argument */
232
+ xhrProto.send = function () {
233
+ var args = [];
234
+ for (var _i = 0; _i < arguments.length; _i++) {
235
+ args[_i] = arguments[_i];
236
+ }
237
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
238
+ var xhrSafe = this;
239
+ var body = args[0];
240
+ var requestEvent = xhrSafe.$$AmplitudeAnalyticsEvent;
241
+ xhrSafe.addEventListener('loadend', function () {
242
+ var _a;
243
+ try {
244
+ var responseHeaders = xhrSafe.getAllResponseHeaders();
245
+ var responseBodySize = xhrSafe.getResponseHeader('content-length');
246
+ var responseWrapper = new network_request_event_1.ResponseWrapperXhr(xhrSafe.status, responseHeaders,
247
+ /* istanbul ignore next */
248
+ responseBodySize ? parseInt(responseBodySize, 10) : undefined);
249
+ var requestWrapper = new network_request_event_1.RequestWrapperXhr(body);
250
+ requestEvent.status = xhrSafe.status;
251
+ networkObserverContext.handleNetworkRequestEvent('xhr', { url: requestEvent.url, method: requestEvent.method }, requestWrapper, responseWrapper, undefined, requestEvent.startTime, requestEvent.durationStart);
252
+ }
253
+ catch (err) {
254
+ /* istanbul ignore next */
255
+ (_a = networkObserverContext.logger) === null || _a === void 0 ? void 0 : _a.debug('an unexpected error occurred while handling xhr send', err);
256
+ }
257
+ });
258
+ /* eslint-disable-next-line @typescript-eslint/no-unsafe-argument */
259
+ return originalXhrSend.apply(xhrSafe, args);
260
+ };
261
+ };
189
262
  return NetworkObserver;
190
263
  }());
191
264
  exports.NetworkObserver = NetworkObserver;
@@ -1 +1 @@
1
- {"version":3,"file":"network-observer.js","sourceRoot":"","sources":["../../src/network-observer.ts"],"names":[],"mappings":";;;;AAAA,+CAAgD;AAChD,qCAAoC;AAGpC,IAAM,eAAe,GAAG,GAAG,CAAC;AA4B5B,SAAgB,oBAAoB,CAAC,IAAyC;;IAC5E,IAAM,MAAM,GAAG,IAAA,6BAAc,GAAE,CAAC;IAChC,IAAI,CAAC,CAAA,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,WAAW,CAAA,EAAE;QACxB,OAAO;KACR;IACO,IAAA,WAAW,GAAK,MAAM,YAAX,CAAY;IAE/B,IAAI,OAAO,IAAI,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KAAK,GAAG;4BACnB,IAAI,EAAE,UAAU,CAAC,IAAI,IAAI,cAAc;4BACvC,OAAO,EAAE,UAAU,CAAC,OAAO,IAAI,2BAA2B;yBAC3D,CAAC;wBAEF,IAAI,UAAU,CAAC,IAAI,KAAK,YAAY,EAAE;4BACpC,YAAY,CAAC,KAAK,CAAC,IAAI,GAAG,YAAY,CAAC;4BACvC,YAAY,CAAC,MAAM,GAAG,CAAC,CAAC;yBACzB;wBAED,IAAI,CAAC,qBAAqB,CAAC,YAAY,CAAC,CAAC;wBACzC,MAAM,OAAK,CAAC;;;;aAEf,CAAC;IACJ,CAAC;IACH,sBAAC;AAAD,CAAC,AAtHD,IAsHC;AAtHY,0CAAe;AAwH5B,wCAAwC;AAC3B,QAAA,eAAe,GAAG,IAAI,eAAe,EAAE,CAAC","sourcesContent":["import { getGlobalScope } from './global-scope';\nimport { UUID } from './utils/uuid';\nimport { ILogger } from '.';\n\nconst MAXIMUM_ENTRIES = 100;\nexport interface NetworkRequestEvent {\n type: string;\n method: string;\n url: string;\n timestamp: number;\n status?: number;\n duration?: number;\n requestBodySize?: number;\n requestHeaders?: Record<string, string>;\n responseBodySize?: number;\n responseHeaders?: Record<string, string>;\n error?: {\n name: string;\n message: string;\n };\n startTime?: number;\n endTime?: number;\n}\n\n// using this type instead of the DOM's ttp so that it's Node compatible\ntype FormDataEntryValueBrowser = string | Blob | null;\nexport interface FormDataBrowser {\n entries(): IterableIterator<[string, FormDataEntryValueBrowser]>;\n}\n\nexport type FetchRequestBody = string | Blob | ArrayBuffer | FormDataBrowser | URLSearchParams | null | undefined;\n\nexport function getRequestBodyLength(body: FetchRequestBody | null | undefined): number | undefined {\n const global = getGlobalScope();\n if (!global?.TextEncoder) {\n return;\n }\n const { TextEncoder } = global;\n\n if (typeof body === 'string') {\n return new TextEncoder().encode(body).length;\n } else if (body instanceof Blob) {\n return body.size;\n } else if (body instanceof URLSearchParams) {\n return new TextEncoder().encode(body.toString()).length;\n } else if (body instanceof ArrayBuffer) {\n return body.byteLength;\n } else if (ArrayBuffer.isView(body)) {\n return body.byteLength;\n } else if (body instanceof FormData) {\n // Estimating only for text parts; not accurate for files\n const formData = body as FormDataBrowser;\n\n let total = 0;\n let count = 0;\n for (const [key, value] of formData.entries()) {\n total += key.length;\n if (typeof value === 'string') {\n total += new TextEncoder().encode(value).length;\n } else if ((value as Blob).size) {\n // if we encounter a \"File\" type, we should not count it and just return undefined\n total += (value as Blob).size;\n }\n // terminate if we reach the maximum number of entries\n // to avoid performance issues in case of very large FormDataß\n if (++count >= MAXIMUM_ENTRIES) {\n return;\n }\n }\n return total;\n }\n // Stream or unknown\n return;\n}\n\nexport type NetworkEventCallbackFn = (event: NetworkRequestEvent) => void;\n\nexport class NetworkEventCallback {\n constructor(public readonly callback: (event: NetworkRequestEvent) => void, public readonly id: string = UUID()) {}\n}\n\nexport class NetworkObserver {\n private originalFetch?: typeof fetch;\n private eventCallbacks: Map<string, NetworkEventCallback> = new Map();\n private isObserving = false;\n // eslint-disable-next-line no-restricted-globals\n private globalScope?: typeof globalThis;\n private logger?: ILogger;\n constructor(logger?: ILogger) {\n this.logger = logger;\n const globalScope = getGlobalScope();\n if (!NetworkObserver.isSupported()) {\n /* istanbul ignore next */\n return;\n }\n this.globalScope = globalScope;\n /* istanbul ignore next */\n this.originalFetch = this.globalScope?.fetch;\n }\n\n static isSupported(): boolean {\n const globalScope = getGlobalScope();\n return !!globalScope && !!globalScope.fetch;\n }\n\n subscribe(eventCallback: NetworkEventCallback, logger?: ILogger) {\n if (!this.logger) {\n this.logger = logger;\n }\n this.eventCallbacks.set(eventCallback.id, eventCallback);\n if (!this.isObserving) {\n this.observeFetch();\n this.isObserving = true;\n }\n }\n\n unsubscribe(eventCallback: NetworkEventCallback) {\n this.eventCallbacks.delete(eventCallback.id);\n if (this.originalFetch && this.globalScope && this.eventCallbacks.size === 0 && this.isObserving) {\n this.globalScope.fetch = this.originalFetch;\n this.isObserving = false;\n }\n }\n\n protected triggerEventCallbacks(event: NetworkRequestEvent) {\n this.eventCallbacks.forEach((callback) => {\n try {\n callback.callback(event);\n } catch (err) {\n /* istanbul ignore next */\n this.logger?.debug('an unexpected error occurred while triggering event callbacks', err);\n }\n });\n }\n\n private observeFetch() {\n /* istanbul ignore next */\n if (!this.globalScope || !this.originalFetch) {\n return;\n }\n const originalFetch = this.globalScope.fetch;\n\n this.globalScope.fetch = async (input: RequestInfo | URL, init?: RequestInit) => {\n const startTime = Date.now();\n const durationStart = performance.now();\n const requestEvent: NetworkRequestEvent = {\n timestamp: startTime,\n startTime,\n type: 'fetch',\n method: init?.method || 'GET', // Fetch API defaulted to GET when no method is provided\n url: input.toString(),\n requestHeaders: init?.headers as Record<string, string>,\n requestBodySize: getRequestBodyLength(init?.body as FetchRequestBody),\n };\n\n try {\n const response = await originalFetch(input, init);\n\n requestEvent.status = response.status;\n requestEvent.duration = Math.floor(performance.now() - durationStart);\n requestEvent.startTime = startTime;\n requestEvent.endTime = Math.floor(startTime + requestEvent.duration);\n\n // Convert Headers\n const headers: Record<string, string> = {};\n let contentLength: number | undefined = undefined;\n response.headers.forEach((value: string, key: string) => {\n headers[key] = value;\n if (key === 'content-length') {\n contentLength = parseInt(value, 10) || undefined;\n }\n });\n requestEvent.responseHeaders = headers;\n requestEvent.responseBodySize = contentLength;\n\n this.triggerEventCallbacks(requestEvent);\n return response;\n } catch (error) {\n const endTime = Date.now();\n requestEvent.duration = endTime - startTime;\n\n // Capture error information\n const typedError = error as Error;\n\n requestEvent.error = {\n name: typedError.name || 'UnknownError',\n message: typedError.message || 'An unknown error occurred',\n };\n\n if (typedError.name === 'AbortError') {\n requestEvent.error.name = 'AbortError';\n requestEvent.status = 0;\n }\n\n this.triggerEventCallbacks(requestEvent);\n throw error;\n }\n };\n }\n}\n\n// singleton instance of NetworkObserver\nexport const networkObserver = new NetworkObserver();\n"]}
1
+ {"version":3,"file":"network-observer.js","sourceRoot":"","sources":["../../src/network-observer.ts"],"names":[],"mappings":";;;;AAAA,uBA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W,CAAC,CAAC;QACrD,CAAC,CAAC;IACJ,CAAC;IACH,sBAAC;AAAD,CAAC,AA7RD,IA6RC;AA7RY,0CAAe;AA+R5B,wCAAwC;AAC3B,QAAA,eAAe,GAAG,IAAI,eAAe,EAAE,CAAC","sourcesContent":["import { getGlobalScope } from './';\nimport { UUID } from './utils/uuid';\nimport { ILogger } from '.';\nimport {\n IRequestWrapper,\n NetworkRequestEvent,\n RequestWrapperFetch,\n ResponseWrapperFetch,\n RequestWrapperXhr,\n ResponseWrapperXhr,\n IResponseWrapper,\n RequestInitSafe,\n XMLHttpRequestBodyInitSafe,\n} from './network-request-event';\n\n// object that is added to each XHR instance so\n// that info can be set in xhr.open and retrieved in xhr.send\ntype AmplitudeAnalyticsEvent = {\n method: string;\n url: string | URL;\n startTime: number;\n durationStart: number;\n status?: number;\n};\n\n/**\n * Typeguard function checks if an input is a Request object.\n */\nfunction isRequest(requestInfo: any): requestInfo is Request {\n return typeof requestInfo === 'object' && requestInfo !== null && 'url' in requestInfo && 'method' in requestInfo;\n}\n\nexport type NetworkEventCallbackFn = (event: NetworkRequestEvent) => void;\n\nexport class NetworkEventCallback {\n constructor(public readonly callback: (event: NetworkRequestEvent) => void, public readonly id: string = UUID()) {}\n}\n\ntype RequestUrlAndMethod = {\n url: string | URL | undefined;\n method: string | undefined;\n};\n\n// A narrowed down [XMLHttpRequest](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) type\n// that only includes the properties we need to access and adds the $$AmplitudeAnalyticsEvent property\n// Use great care when modifying this type, make sure you only use read-only properties and only add\n// what you need to access, nothing more.\ntype AmplitudeXMLHttpRequestSafe = {\n $$AmplitudeAnalyticsEvent: AmplitudeAnalyticsEvent;\n status: number;\n getAllResponseHeaders: typeof XMLHttpRequest.prototype.getAllResponseHeaders;\n getResponseHeader: typeof XMLHttpRequest.prototype.getResponseHeader;\n addEventListener: (type: 'loadend', listener: () => void) => void;\n};\n\nexport class NetworkObserver {\n private eventCallbacks: Map<string, NetworkEventCallback> = new Map();\n // eslint-disable-next-line no-restricted-globals\n private globalScope?: typeof globalThis;\n private logger?: ILogger;\n private isObserving = false;\n constructor(logger?: ILogger) {\n this.logger = logger;\n const globalScope = getGlobalScope();\n if (!NetworkObserver.isSupported()) {\n /* istanbul ignore next */\n return;\n }\n this.globalScope = globalScope;\n }\n\n static isSupported(): boolean {\n const globalScope = getGlobalScope();\n return !!globalScope && !!globalScope.fetch;\n }\n\n subscribe(eventCallback: NetworkEventCallback, logger?: ILogger) {\n if (!this.logger) {\n this.logger = logger;\n }\n this.eventCallbacks.set(eventCallback.id, eventCallback);\n if (!this.isObserving) {\n /* istanbul ignore next */\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const originalXhrOpen = this.globalScope?.XMLHttpRequest?.prototype?.open;\n /* istanbul ignore next */\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const originalXhrSend = this.globalScope?.XMLHttpRequest?.prototype?.send;\n if (originalXhrOpen && originalXhrSend) {\n this.observeXhr(originalXhrOpen, originalXhrSend);\n }\n\n /* istanbul ignore next */\n const originalFetch = this.globalScope?.fetch;\n /* istanbul ignore next */\n if (originalFetch) {\n this.observeFetch(originalFetch);\n }\n\n /* istanbul ignore next */\n this.isObserving = true;\n }\n }\n\n unsubscribe(eventCallback: NetworkEventCallback) {\n this.eventCallbacks.delete(eventCallback.id);\n }\n\n protected triggerEventCallbacks(event: NetworkRequestEvent) {\n this.eventCallbacks.forEach((callback) => {\n try {\n callback.callback(event);\n } catch (err) {\n // if the callback throws an error, we should catch it\n // to avoid breaking the fetch promise chain\n /* istanbul ignore next */\n this.logger?.debug('an unexpected error occurred while triggering event callbacks', err);\n }\n });\n }\n\n private handleNetworkRequestEvent(\n requestType: 'fetch' | 'xhr',\n requestInfo: RequestInfo | URL | RequestUrlAndMethod | undefined,\n requestWrapper: IRequestWrapper | undefined,\n responseWrapper: IResponseWrapper | undefined,\n typedError: Error | undefined,\n startTime?: number,\n durationStart?: number,\n ) {\n /* istanbul ignore next */\n if (startTime === undefined || durationStart === undefined) {\n // if we reach this point, it means that the performance API is not supported\n // so we can't construct a NetworkRequestEvent\n return;\n }\n\n // parse the URL and Method\n let url: string | undefined;\n let method = 'GET';\n if (isRequest(requestInfo)) {\n url = requestInfo['url'];\n method = requestInfo['method'];\n } else {\n url = requestInfo?.toString?.();\n }\n method = requestWrapper?.method || method;\n\n let status, error;\n if (responseWrapper) {\n status = responseWrapper.status;\n }\n\n if (typedError) {\n error = {\n name: typedError.name || 'UnknownError',\n message: typedError.message || 'An unknown error occurred',\n };\n status = 0;\n }\n\n const duration = Math.floor(performance.now() - durationStart);\n const endTime = Math.floor(startTime + duration);\n\n const requestEvent = new NetworkRequestEvent(\n requestType,\n method,\n startTime, // timestamp and startTime are aliases\n startTime,\n url,\n requestWrapper,\n status,\n duration,\n responseWrapper,\n error,\n endTime,\n );\n\n this.triggerEventCallbacks(requestEvent);\n }\n\n private getTimestamps() {\n /* istanbul ignore next */\n return {\n startTime: Date.now?.(),\n durationStart: performance?.now?.(),\n };\n }\n\n private observeFetch(\n originalFetch: (requestInfo: RequestInfo | URL, requestInit?: RequestInit) => Promise<Response>,\n ) {\n /* istanbul ignore next */\n if (!this.globalScope || !originalFetch) {\n return;\n }\n /**\n * IMPORTANT: This overrides window.fetch in browsers.\n * You probably never need to make changes to this function.\n * If you do, please be careful to preserve the original functionality of fetch\n * and make sure another developer who is an expert reviews this change throughly\n */\n this.globalScope.fetch = async (requestInfo?: RequestInfo | URL, requestInit?: RequestInit) => {\n // 1: capture the start time and duration start time before the fetch call\n let timestamps;\n try {\n timestamps = this.getTimestamps();\n } catch (error) {\n /* istanbul ignore next */\n this.logger?.debug('an unexpected error occurred while retrieving timestamps', error);\n }\n\n // 2. make the call to the original fetch and preserve the response or error\n let originalResponse, originalError;\n try {\n originalResponse = await originalFetch(requestInfo as RequestInfo | URL, requestInit);\n } catch (err) {\n // Capture error information\n originalError = err;\n }\n\n // 3. call the handler after the fetch call is done\n try {\n this.handleNetworkRequestEvent(\n 'fetch',\n requestInfo,\n requestInit ? new RequestWrapperFetch(requestInit as RequestInitSafe) : undefined,\n originalResponse ? new ResponseWrapperFetch(originalResponse) : undefined,\n originalError as Error,\n /* istanbul ignore next */\n timestamps?.startTime,\n /* istanbul ignore next */\n timestamps?.durationStart,\n );\n } catch (err) {\n // this catch shouldn't be reachable, but keep it here for safety\n // because we're overriding the fetch function and better to be safe than sorry\n /* istanbul ignore next */\n this.logger?.debug('an unexpected error occurred while handling fetch', err);\n }\n\n // 4. return the original response or throw the original error\n if (originalResponse) {\n // if the response is not undefined, return it\n return originalResponse;\n } else {\n throw originalError;\n }\n };\n }\n\n private observeXhr(\n originalXhrOpen:\n | ((\n method: string,\n url: string | URL,\n async?: boolean,\n username?: string | null,\n password?: string | null,\n ) => void)\n | undefined,\n originalXhrSend: ((body?: Document | XMLHttpRequestBodyInit | null) => void) | undefined,\n ) {\n /* istanbul ignore next */\n if (!this.globalScope || !originalXhrOpen || !originalXhrSend) {\n return;\n }\n\n const xhrProto = this.globalScope.XMLHttpRequest.prototype;\n\n const networkObserverContext = this as NetworkObserver;\n\n /**\n * IMPORTANT: This overrides window.XMLHttpRequest.prototype.open\n * You probably never need to make changes to this function.\n * If you do, please be careful to preserve the original functionality of xhr.open\n * and make sure another developer who is an expert reviews this change throughly\n */\n xhrProto.open = function (...args: any[]) {\n const xhrSafe = this as unknown as AmplitudeXMLHttpRequestSafe;\n const [method, url] = args as [string, string | URL];\n try {\n /* istanbul ignore next */\n xhrSafe.$$AmplitudeAnalyticsEvent = {\n method,\n url: url?.toString?.(),\n ...networkObserverContext.getTimestamps(),\n } as AmplitudeAnalyticsEvent;\n } catch (err) {\n /* istanbul ignore next */\n networkObserverContext.logger?.debug('an unexpected error occurred while calling xhr open', err);\n }\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n return originalXhrOpen.apply(xhrSafe, args as any);\n };\n\n /**\n * IMPORTANT: This overrides window.XMLHttpRequest.prototype.send\n * You probably never need to make changes to this function.\n * If you do, please be careful to preserve the original functionality of xhr.send\n * and make sure another developer who is an expert reviews this change throughly\n */\n // allow \"any\" type for args to reflect how it's used in the browser\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-argument */\n xhrProto.send = function (...args: any[]) {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const xhrSafe = this as unknown as AmplitudeXMLHttpRequestSafe;\n const body = args[0] as XMLHttpRequestBodyInitSafe;\n const requestEvent = xhrSafe.$$AmplitudeAnalyticsEvent;\n\n xhrSafe.addEventListener('loadend', function () {\n try {\n const responseHeaders = xhrSafe.getAllResponseHeaders();\n const responseBodySize = xhrSafe.getResponseHeader('content-length');\n const responseWrapper = new ResponseWrapperXhr(\n xhrSafe.status,\n responseHeaders,\n /* istanbul ignore next */\n responseBodySize ? parseInt(responseBodySize, 10) : undefined,\n );\n const requestWrapper = new RequestWrapperXhr(body);\n requestEvent.status = xhrSafe.status;\n networkObserverContext.handleNetworkRequestEvent(\n 'xhr',\n { url: requestEvent.url, method: requestEvent.method },\n requestWrapper,\n responseWrapper,\n undefined,\n requestEvent.startTime,\n requestEvent.durationStart,\n );\n } catch (err) {\n /* istanbul ignore next */\n networkObserverContext.logger?.debug('an unexpected error occurred while handling xhr send', err);\n }\n });\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-argument */\n return originalXhrSend.apply(xhrSafe, args as any);\n };\n }\n}\n\n// singleton instance of NetworkObserver\nexport const networkObserver = new NetworkObserver();\n"]}