@amplitude/analytics-core 2.40.0 → 2.40.1

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.
@@ -2,7 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.networkObserver = exports.NetworkObserver = exports.NetworkEventCallback = void 0;
4
4
  var tslib_1 = require("tslib");
5
- var __1 = require("..");
5
+ var global_scope_1 = require("../global-scope");
6
6
  var uuid_1 = require("../utils/uuid");
7
7
  var network_request_event_1 = require("../network-request-event");
8
8
  /**
@@ -33,7 +33,7 @@ var NetworkObserver = /** @class */ (function () {
33
33
  this.eventCallbacks = new Map();
34
34
  this.isObserving = false;
35
35
  this.logger = logger;
36
- var globalScope = (0, __1.getGlobalScope)();
36
+ var globalScope = (0, global_scope_1.getGlobalScope)();
37
37
  if (!NetworkObserver.isSupported()) {
38
38
  /* istanbul ignore next */
39
39
  return;
@@ -41,7 +41,7 @@ var NetworkObserver = /** @class */ (function () {
41
41
  this.globalScope = globalScope;
42
42
  }
43
43
  NetworkObserver.isSupported = function () {
44
- var globalScope = (0, __1.getGlobalScope)();
44
+ var globalScope = (0, global_scope_1.getGlobalScope)();
45
45
  return !!globalScope && !!globalScope.fetch;
46
46
  };
47
47
  NetworkObserver.prototype.subscribe = function (eventCallback, logger) {
@@ -1 +1 @@
1
- {"version":3,"file":"network.js","sourceRoot":"","sources":["../../../src/observers/network.ts"],"names":[],"mappings":";;;;AAAA,wBAAoC;AACpC,sCAAqC;AAErC,kEAUkC;AAalC;;GAEG;AACH,SAAS,SAAS,CAAC,WAAgB;IACjC,OAAO,OAAO,WAAW,KAAK,QAAQ,IAAI,WAAW,KAAK,IAAI,IAAI,KAAK,IAAI,WAAW,IAAI,QAAQ,IAAI,WAAW,CAAC;AACpH,CAAC;AAID;IACE,8BAA4B,QAA8C,EAAkB,EAAmB;QAAnB,mBAAA,EAAA,SAAa,WAAI,GAAE;QAAnF,aAAQ,GAAR,QAAQ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C,AAhYD,IAgYC;AAhYY,0CAAe;AAkY5B,wCAAwC;AAC3B,QAAA,eAAe,GAAG,IAAI,eAAe,EAAE,CAAC","sourcesContent":["import { getGlobalScope } from '..';\nimport { UUID } from '../utils/uuid';\nimport { ILogger } from '../logger';\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 headers: Record<string, string>;\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 responseText: string;\n responseType: XMLHttpRequestResponseType;\n getAllResponseHeaders: typeof XMLHttpRequest.prototype.getAllResponseHeaders;\n getResponseHeader: typeof XMLHttpRequest.prototype.getResponseHeader;\n addEventListener: (type: 'loadend', listener: () => void) => void;\n};\n\nfunction safeInvoke(fn: () => void) {\n try {\n fn();\n } catch (err) {\n // swallow the error\n }\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 /* istanbul ignore next */\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const originalXhrSetRequestHeader = this.globalScope?.XMLHttpRequest?.prototype?.setRequestHeader;\n if (originalXhrOpen && originalXhrSend && originalXhrSetRequestHeader) {\n this.observeXhr(originalXhrOpen, originalXhrSend, originalXhrSetRequestHeader);\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 safeInvoke(() => {\n /* istanbul ignore next */\n this.logger?.debug('an unexpected error occurred while triggering event callbacks', err);\n });\n }\n });\n }\n\n 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\n // strip basic auth from the URL\n if (url) {\n try {\n const parsedUrl = new URL(url);\n // reconstruct the URL without the basic auth\n url = `${parsedUrl.protocol}//${parsedUrl.host}${parsedUrl.pathname}${parsedUrl.search}${parsedUrl.hash}`;\n // eslint-disable-next-line no-empty\n } catch (err) {}\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 safeInvoke(() => 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 safeInvoke(() => 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 /**\n * Creates a function that parses the response of an XMLHttpRequest as JSON.\n *\n * Returns function instead of JSON object to avoid unnecessary parsing if the\n * body is not being captured.\n *\n * @param xhrSafe - The XMLHttpRequest object.\n * @param context - The NetworkObserver instance.\n * @returns A function that parses the response of an XMLHttpRequest as JSON.\n */\n static createXhrJsonParser(xhrUnsafe: XMLHttpRequest, context: NetworkObserver) {\n return () => {\n try {\n if (xhrUnsafe.responseType === 'json') {\n // if response is a JS object, clone it so that subscribers can't mutate it\n if (context.globalScope?.structuredClone) {\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-return */\n return context.globalScope.structuredClone(xhrUnsafe.response);\n }\n } else if (['text', ''].includes(xhrUnsafe.responseType)) {\n // if response is a string, parse it as JSON\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-return */\n return JSON.parse(xhrUnsafe.responseText);\n }\n } catch (err) {\n /* istanbul ignore if */\n if (err instanceof Error && err.name === 'InvalidStateError') {\n // https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseText#exceptions\n // if we reach here, it means we don't handle responseType correctly\n safeInvoke(() =>\n context.logger?.debug(\n `unexpected error when retrieving responseText. responseType='${xhrUnsafe.responseType}'`,\n ),\n );\n }\n // the other possible error is Json Parse error which we fail silently\n return null;\n }\n return null;\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 originalXhrSetRequestHeader: (headerName: string, headerValue: string) => void,\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 headers: {},\n ...networkObserverContext.getTimestamps(),\n } as AmplitudeAnalyticsEvent;\n } catch (err) {\n /* istanbul ignore next */\n safeInvoke(() =>\n networkObserverContext.logger?.debug('an unexpected error occurred while calling xhr open', err),\n );\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 xhrUnsafe = this;\n const xhrSafe = xhrUnsafe as unknown as AmplitudeXMLHttpRequestSafe;\n const getJson = NetworkObserver.createXhrJsonParser(xhrUnsafe, networkObserverContext);\n const body = args[0] as XMLHttpRequestBodyInitSafe;\n const requestEvent = xhrSafe.$$AmplitudeAnalyticsEvent;\n\n // if xhrSafe.$$AmplitudeAnalyticsEvent is not set, it means that\n // the xhr.open method was called before we monkey-patched XHR and\n // the event is missed\n if (xhrSafe.$$AmplitudeAnalyticsEvent) {\n xhrSafe.addEventListener('loadend', function () {\n try {\n const responseHeaders = xhrSafe.getAllResponseHeaders();\n const responseBodySize = xhrSafe.getResponseHeader('content-length');\n\n const responseWrapper = new ResponseWrapperXhr(\n xhrSafe.status,\n responseHeaders,\n /* istanbul ignore next */\n responseBodySize ? parseInt(responseBodySize, 10) : undefined,\n getJson,\n );\n const requestHeaders = xhrSafe.$$AmplitudeAnalyticsEvent.headers;\n const requestWrapper = new RequestWrapperXhr(body, requestHeaders);\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 safeInvoke(() =>\n networkObserverContext.logger?.debug('an unexpected error occurred while handling xhr send', err),\n );\n }\n });\n }\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-argument */\n return originalXhrSend.apply(xhrSafe, args as any);\n };\n\n /**\n * IMPORTANT: This overrides window.XMLHttpRequest.prototype.setRequestHeader\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.setRequestHeader\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.setRequestHeader = function (headerName: any, headerValue: any) {\n const xhrSafe = this as unknown as AmplitudeXMLHttpRequestSafe;\n try {\n const analyticsEvent = xhrSafe.$$AmplitudeAnalyticsEvent;\n if (analyticsEvent) {\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-assignment */\n analyticsEvent.headers[headerName as string] = headerValue as string;\n }\n } catch (err) {\n /* istanbul ignore next */\n safeInvoke(() =>\n networkObserverContext.logger?.debug('an unexpected error occurred while calling xhr setRequestHeader', err),\n );\n }\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-argument */\n originalXhrSetRequestHeader.apply(xhrSafe, [headerName, headerValue]);\n };\n }\n}\n\n// singleton instance of NetworkObserver\nexport const networkObserver = new NetworkObserver();\n"]}
1
+ {"version":3,"file":"network.js","sourceRoot":"","sources":["../../../src/observers/network.ts"],"names":[],"mappings":";;;;AAAA,gDAAiD;AACjD,sCAAqC;AAErC,kEAUkC;AAalC;;GAEG;AACH,SAAS,SAAS,CAAC,WAAgB;IACjC,OAAO,OAAO,WAAW,KAAK,QAAQ,IAAI,WAAW,KAAK,IAAI,IAAI,KAAK,IAAI,WAAW,IAAI,QAAQ,IAAI,WAAW,CAAC;AACpH,CAAC;AAID;IACE,8BAA4B,QAA8C,EAAkB,EAAmB;QAAnB,mBAAA,EAAA,SAAa,WAAI,GAAE;QAAnF,aAAQ,GAAR,QAAQ,CAAsC;QAAkB,OAAE,GAAF,EAAE,CAAiB;IAAG,CAAC;IACrH,2BAAC;AAAD,CAAC,AAFD,IAEC;AAFY,oDAAoB;AAuBjC,SAAS,UAAU,CAAC,EAAc;IAChC,IAAI;QACF,EAAE,EAAE,CAAC;KACN;IAAC,OAAO,GAAG,EAAE;QACZ,oBA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AS,EACT,YAAY,CAAC,SAAS,EACtB,YAAY,CAAC,aAAa,CAC3B,CAAC;qBACH;oBAAC,OAAO,GAAG,EAAE;wBACZ,0BAA0B;wBAC1B,UAAU,CAAC,sBACT,OAAA,MAAA,sBAAsB,CAAC,MAAM,0CAAE,KAAK,CAAC,sDAAsD,EAAE,GAAG,CAAC,CAAA,EAAA,CAClG,CAAC;qBACH;gBACH,CAAC,CAAC,CAAC;aACJ;YACD,oEAAoE;YACpE,OAAO,eAAe,CAAC,KAAK,CAAC,OAAO,EAAE,IAAW,CAAC,CAAC;QACrD,CAAC,CAAC;QAEF;;;;;WAKG;QACH,oEAAoE;QACpE,oEAAoE;QACpE,QAAQ,CAAC,gBAAgB,GAAG,UAAU,UAAe,EAAE,WAAgB;YACrE,IAAM,OAAO,GAAG,IAA8C,CAAC;YAC/D,IAAI;gBACF,IAAM,cAAc,GAAG,OAAO,CAAC,yBAAyB,CAAC;gBACzD,IAAI,cAAc,EAAE;oBAClB,sEAAsE;oBACtE,cAAc,CAAC,OAAO,CAAC,UAAoB,CAAC,GAAG,WAAqB,CAAC;iBACtE;aACF;YAAC,OAAO,GAAG,EAAE;gBACZ,0BAA0B;gBAC1B,UAAU,CAAC,sBACT,OAAA,MAAA,sBAAsB,CAAC,MAAM,0CAAE,KAAK,CAAC,iEAAiE,EAAE,GAAG,CAAC,CAAA,EAAA,CAC7G,CAAC;aACH;YACD,oEAAoE;YACpE,2BAA2B,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC,UAAU,EAAE,WAAW,CAAC,CAAC,CAAC;QACxE,CAAC,CAAC;IACJ,CAAC;IACH,sBAAC;AAAD,CAAC,AAhYD,IAgYC;AAhYY,0CAAe;AAkY5B,wCAAwC;AAC3B,QAAA,eAAe,GAAG,IAAI,eAAe,EAAE,CAAC","sourcesContent":["import { getGlobalScope } from '../global-scope';\nimport { UUID } from '../utils/uuid';\nimport { ILogger } from '../logger';\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 headers: Record<string, string>;\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 responseText: string;\n responseType: XMLHttpRequestResponseType;\n getAllResponseHeaders: typeof XMLHttpRequest.prototype.getAllResponseHeaders;\n getResponseHeader: typeof XMLHttpRequest.prototype.getResponseHeader;\n addEventListener: (type: 'loadend', listener: () => void) => void;\n};\n\nfunction safeInvoke(fn: () => void) {\n try {\n fn();\n } catch (err) {\n // swallow the error\n }\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 /* istanbul ignore next */\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const originalXhrSetRequestHeader = this.globalScope?.XMLHttpRequest?.prototype?.setRequestHeader;\n if (originalXhrOpen && originalXhrSend && originalXhrSetRequestHeader) {\n this.observeXhr(originalXhrOpen, originalXhrSend, originalXhrSetRequestHeader);\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 safeInvoke(() => {\n /* istanbul ignore next */\n this.logger?.debug('an unexpected error occurred while triggering event callbacks', err);\n });\n }\n });\n }\n\n 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\n // strip basic auth from the URL\n if (url) {\n try {\n const parsedUrl = new URL(url);\n // reconstruct the URL without the basic auth\n url = `${parsedUrl.protocol}//${parsedUrl.host}${parsedUrl.pathname}${parsedUrl.search}${parsedUrl.hash}`;\n // eslint-disable-next-line no-empty\n } catch (err) {}\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 safeInvoke(() => 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 safeInvoke(() => 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 /**\n * Creates a function that parses the response of an XMLHttpRequest as JSON.\n *\n * Returns function instead of JSON object to avoid unnecessary parsing if the\n * body is not being captured.\n *\n * @param xhrSafe - The XMLHttpRequest object.\n * @param context - The NetworkObserver instance.\n * @returns A function that parses the response of an XMLHttpRequest as JSON.\n */\n static createXhrJsonParser(xhrUnsafe: XMLHttpRequest, context: NetworkObserver) {\n return () => {\n try {\n if (xhrUnsafe.responseType === 'json') {\n // if response is a JS object, clone it so that subscribers can't mutate it\n if (context.globalScope?.structuredClone) {\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-return */\n return context.globalScope.structuredClone(xhrUnsafe.response);\n }\n } else if (['text', ''].includes(xhrUnsafe.responseType)) {\n // if response is a string, parse it as JSON\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-return */\n return JSON.parse(xhrUnsafe.responseText);\n }\n } catch (err) {\n /* istanbul ignore if */\n if (err instanceof Error && err.name === 'InvalidStateError') {\n // https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseText#exceptions\n // if we reach here, it means we don't handle responseType correctly\n safeInvoke(() =>\n context.logger?.debug(\n `unexpected error when retrieving responseText. responseType='${xhrUnsafe.responseType}'`,\n ),\n );\n }\n // the other possible error is Json Parse error which we fail silently\n return null;\n }\n return null;\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 originalXhrSetRequestHeader: (headerName: string, headerValue: string) => void,\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 headers: {},\n ...networkObserverContext.getTimestamps(),\n } as AmplitudeAnalyticsEvent;\n } catch (err) {\n /* istanbul ignore next */\n safeInvoke(() =>\n networkObserverContext.logger?.debug('an unexpected error occurred while calling xhr open', err),\n );\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 xhrUnsafe = this;\n const xhrSafe = xhrUnsafe as unknown as AmplitudeXMLHttpRequestSafe;\n const getJson = NetworkObserver.createXhrJsonParser(xhrUnsafe, networkObserverContext);\n const body = args[0] as XMLHttpRequestBodyInitSafe;\n const requestEvent = xhrSafe.$$AmplitudeAnalyticsEvent;\n\n // if xhrSafe.$$AmplitudeAnalyticsEvent is not set, it means that\n // the xhr.open method was called before we monkey-patched XHR and\n // the event is missed\n if (xhrSafe.$$AmplitudeAnalyticsEvent) {\n xhrSafe.addEventListener('loadend', function () {\n try {\n const responseHeaders = xhrSafe.getAllResponseHeaders();\n const responseBodySize = xhrSafe.getResponseHeader('content-length');\n\n const responseWrapper = new ResponseWrapperXhr(\n xhrSafe.status,\n responseHeaders,\n /* istanbul ignore next */\n responseBodySize ? parseInt(responseBodySize, 10) : undefined,\n getJson,\n );\n const requestHeaders = xhrSafe.$$AmplitudeAnalyticsEvent.headers;\n const requestWrapper = new RequestWrapperXhr(body, requestHeaders);\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 safeInvoke(() =>\n networkObserverContext.logger?.debug('an unexpected error occurred while handling xhr send', err),\n );\n }\n });\n }\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-argument */\n return originalXhrSend.apply(xhrSafe, args as any);\n };\n\n /**\n * IMPORTANT: This overrides window.XMLHttpRequest.prototype.setRequestHeader\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.setRequestHeader\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.setRequestHeader = function (headerName: any, headerValue: any) {\n const xhrSafe = this as unknown as AmplitudeXMLHttpRequestSafe;\n try {\n const analyticsEvent = xhrSafe.$$AmplitudeAnalyticsEvent;\n if (analyticsEvent) {\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-assignment */\n analyticsEvent.headers[headerName as string] = headerValue as string;\n }\n } catch (err) {\n /* istanbul ignore next */\n safeInvoke(() =>\n networkObserverContext.logger?.debug('an unexpected error occurred while calling xhr setRequestHeader', err),\n );\n }\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-argument */\n originalXhrSetRequestHeader.apply(xhrSafe, [headerName, headerValue]);\n };\n }\n}\n\n// singleton instance of NetworkObserver\nexport const networkObserver = new NetworkObserver();\n"]}
@@ -1,5 +1,5 @@
1
1
  import { __assign, __awaiter, __generator, __read } from "tslib";
2
- import { getGlobalScope } from '..';
2
+ import { getGlobalScope } from '../global-scope';
3
3
  import { UUID } from '../utils/uuid';
4
4
  import { NetworkRequestEvent, RequestWrapperFetch, ResponseWrapperFetch, RequestWrapperXhr, ResponseWrapperXhr, } from '../network-request-event';
5
5
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"network.js","sourceRoot":"","sources":["../../../src/observers/network.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,IAAI,CAAC;AACpC,OAAO,EAAE,IAAI,EAAE,MAAM,eAAe,CAAC;AAErC,OAAO,EAEL,mBAAmB,EACnB,mBAAmB,EACnB,oBAAoB,EACpB,iBAAiB,EACjB,kBAAkB,GAInB,MAAM,0BAA0B,CAAC;AAalC;;GAEG;AACH,SAAS,SAAS,CAAC,WAAgB;IACjC,OAAO,OAAO,WAAW,KAAK,QAAQ,IAAI,WAAW,KAAK,IAAI,IAAI,KAAK,IAAI,WAAW,IAAI,QAAQ,IAAI,WAAW,CAAC;AACpH,CAAC;AAID;IACE,8BAA4B,QAA8C,EAAkB,EAAmB;QAAnB,mBAAA,EAAA,KAAa,IAAI,EAAE;QAAnF,aAAQ,GAAR,QAAQ,CAAsC;QAA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CAAC,IAAM,eAAe,GAAG,IAAI,eAAe,EAAE,CAAC","sourcesContent":["import { getGlobalScope } from '..';\nimport { UUID } from '../utils/uuid';\nimport { ILogger } from '../logger';\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 headers: Record<string, string>;\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 responseText: string;\n responseType: XMLHttpRequestResponseType;\n getAllResponseHeaders: typeof XMLHttpRequest.prototype.getAllResponseHeaders;\n getResponseHeader: typeof XMLHttpRequest.prototype.getResponseHeader;\n addEventListener: (type: 'loadend', listener: () => void) => void;\n};\n\nfunction safeInvoke(fn: () => void) {\n try {\n fn();\n } catch (err) {\n // swallow the error\n }\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 /* istanbul ignore next */\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const originalXhrSetRequestHeader = this.globalScope?.XMLHttpRequest?.prototype?.setRequestHeader;\n if (originalXhrOpen && originalXhrSend && originalXhrSetRequestHeader) {\n this.observeXhr(originalXhrOpen, originalXhrSend, originalXhrSetRequestHeader);\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 safeInvoke(() => {\n /* istanbul ignore next */\n this.logger?.debug('an unexpected error occurred while triggering event callbacks', err);\n });\n }\n });\n }\n\n 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\n // strip basic auth from the URL\n if (url) {\n try {\n const parsedUrl = new URL(url);\n // reconstruct the URL without the basic auth\n url = `${parsedUrl.protocol}//${parsedUrl.host}${parsedUrl.pathname}${parsedUrl.search}${parsedUrl.hash}`;\n // eslint-disable-next-line no-empty\n } catch (err) {}\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 safeInvoke(() => 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 safeInvoke(() => 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 /**\n * Creates a function that parses the response of an XMLHttpRequest as JSON.\n *\n * Returns function instead of JSON object to avoid unnecessary parsing if the\n * body is not being captured.\n *\n * @param xhrSafe - The XMLHttpRequest object.\n * @param context - The NetworkObserver instance.\n * @returns A function that parses the response of an XMLHttpRequest as JSON.\n */\n static createXhrJsonParser(xhrUnsafe: XMLHttpRequest, context: NetworkObserver) {\n return () => {\n try {\n if (xhrUnsafe.responseType === 'json') {\n // if response is a JS object, clone it so that subscribers can't mutate it\n if (context.globalScope?.structuredClone) {\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-return */\n return context.globalScope.structuredClone(xhrUnsafe.response);\n }\n } else if (['text', ''].includes(xhrUnsafe.responseType)) {\n // if response is a string, parse it as JSON\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-return */\n return JSON.parse(xhrUnsafe.responseText);\n }\n } catch (err) {\n /* istanbul ignore if */\n if (err instanceof Error && err.name === 'InvalidStateError') {\n // https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseText#exceptions\n // if we reach here, it means we don't handle responseType correctly\n safeInvoke(() =>\n context.logger?.debug(\n `unexpected error when retrieving responseText. responseType='${xhrUnsafe.responseType}'`,\n ),\n );\n }\n // the other possible error is Json Parse error which we fail silently\n return null;\n }\n return null;\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 originalXhrSetRequestHeader: (headerName: string, headerValue: string) => void,\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 headers: {},\n ...networkObserverContext.getTimestamps(),\n } as AmplitudeAnalyticsEvent;\n } catch (err) {\n /* istanbul ignore next */\n safeInvoke(() =>\n networkObserverContext.logger?.debug('an unexpected error occurred while calling xhr open', err),\n );\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 xhrUnsafe = this;\n const xhrSafe = xhrUnsafe as unknown as AmplitudeXMLHttpRequestSafe;\n const getJson = NetworkObserver.createXhrJsonParser(xhrUnsafe, networkObserverContext);\n const body = args[0] as XMLHttpRequestBodyInitSafe;\n const requestEvent = xhrSafe.$$AmplitudeAnalyticsEvent;\n\n // if xhrSafe.$$AmplitudeAnalyticsEvent is not set, it means that\n // the xhr.open method was called before we monkey-patched XHR and\n // the event is missed\n if (xhrSafe.$$AmplitudeAnalyticsEvent) {\n xhrSafe.addEventListener('loadend', function () {\n try {\n const responseHeaders = xhrSafe.getAllResponseHeaders();\n const responseBodySize = xhrSafe.getResponseHeader('content-length');\n\n const responseWrapper = new ResponseWrapperXhr(\n xhrSafe.status,\n responseHeaders,\n /* istanbul ignore next */\n responseBodySize ? parseInt(responseBodySize, 10) : undefined,\n getJson,\n );\n const requestHeaders = xhrSafe.$$AmplitudeAnalyticsEvent.headers;\n const requestWrapper = new RequestWrapperXhr(body, requestHeaders);\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 safeInvoke(() =>\n networkObserverContext.logger?.debug('an unexpected error occurred while handling xhr send', err),\n );\n }\n });\n }\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-argument */\n return originalXhrSend.apply(xhrSafe, args as any);\n };\n\n /**\n * IMPORTANT: This overrides window.XMLHttpRequest.prototype.setRequestHeader\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.setRequestHeader\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.setRequestHeader = function (headerName: any, headerValue: any) {\n const xhrSafe = this as unknown as AmplitudeXMLHttpRequestSafe;\n try {\n const analyticsEvent = xhrSafe.$$AmplitudeAnalyticsEvent;\n if (analyticsEvent) {\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-assignment */\n analyticsEvent.headers[headerName as string] = headerValue as string;\n }\n } catch (err) {\n /* istanbul ignore next */\n safeInvoke(() =>\n networkObserverContext.logger?.debug('an unexpected error occurred while calling xhr setRequestHeader', err),\n );\n }\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-argument */\n originalXhrSetRequestHeader.apply(xhrSafe, [headerName, headerValue]);\n };\n }\n}\n\n// singleton instance of NetworkObserver\nexport const networkObserver = new NetworkObserver();\n"]}
1
+ {"version":3,"file":"network.js","sourceRoot":"","sources":["../../../src/observers/network.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACjD,OAAO,EAAE,IAAI,EAAE,MAAM,eAAe,CAAC;AAErC,OAAO,EAEL,mBAAmB,EACnB,mBAAmB,EACnB,oBAAoB,EACpB,iBAAiB,EACjB,kBAAkB,GAInB,MAAM,0BAA0B,CAAC;AAalC;;GAEG;AACH,SAAS,SAAS,CAAC,WAAgB;IACjC,OAAO,OAAO,WAAW,KAAK,QAAQ,IAAI,WAAW,KAAK,IAAI,IAAI,KAAK,IAAI,WAAW,IAAI,QAAQ,IAAI,WAAW,CAAC;AACpH,CAAC;AAID;IACE,8BAA4B,QAA8C,EAAkB,EAAmB;QAAnB,mBAAA,EAAA,KAAa,IAAI,EAAE;QAAnF,aAAQ,GAAR,QAAQ,CAAsC;QAAkB,OAAE,GAAF,EAAE,CAAiB;IAAG,CAAC;IACrH,2BAAC;AAAD,CAAC,AAFD,IAEC;;AAqBD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UUID } from '../utils/uuid';\nimport { ILogger } from '../logger';\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 headers: Record<string, string>;\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 responseText: string;\n responseType: XMLHttpRequestResponseType;\n getAllResponseHeaders: typeof XMLHttpRequest.prototype.getAllResponseHeaders;\n getResponseHeader: typeof XMLHttpRequest.prototype.getResponseHeader;\n addEventListener: (type: 'loadend', listener: () => void) => void;\n};\n\nfunction safeInvoke(fn: () => void) {\n try {\n fn();\n } catch (err) {\n // swallow the error\n }\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 /* istanbul ignore next */\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const originalXhrSetRequestHeader = this.globalScope?.XMLHttpRequest?.prototype?.setRequestHeader;\n if (originalXhrOpen && originalXhrSend && originalXhrSetRequestHeader) {\n this.observeXhr(originalXhrOpen, originalXhrSend, originalXhrSetRequestHeader);\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 safeInvoke(() => {\n /* istanbul ignore next */\n this.logger?.debug('an unexpected error occurred while triggering event callbacks', err);\n });\n }\n });\n }\n\n 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\n // strip basic auth from the URL\n if (url) {\n try {\n const parsedUrl = new URL(url);\n // reconstruct the URL without the basic auth\n url = `${parsedUrl.protocol}//${parsedUrl.host}${parsedUrl.pathname}${parsedUrl.search}${parsedUrl.hash}`;\n // eslint-disable-next-line no-empty\n } catch (err) {}\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 safeInvoke(() => 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 safeInvoke(() => 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 /**\n * Creates a function that parses the response of an XMLHttpRequest as JSON.\n *\n * Returns function instead of JSON object to avoid unnecessary parsing if the\n * body is not being captured.\n *\n * @param xhrSafe - The XMLHttpRequest object.\n * @param context - The NetworkObserver instance.\n * @returns A function that parses the response of an XMLHttpRequest as JSON.\n */\n static createXhrJsonParser(xhrUnsafe: XMLHttpRequest, context: NetworkObserver) {\n return () => {\n try {\n if (xhrUnsafe.responseType === 'json') {\n // if response is a JS object, clone it so that subscribers can't mutate it\n if (context.globalScope?.structuredClone) {\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-return */\n return context.globalScope.structuredClone(xhrUnsafe.response);\n }\n } else if (['text', ''].includes(xhrUnsafe.responseType)) {\n // if response is a string, parse it as JSON\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-return */\n return JSON.parse(xhrUnsafe.responseText);\n }\n } catch (err) {\n /* istanbul ignore if */\n if (err instanceof Error && err.name === 'InvalidStateError') {\n // https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseText#exceptions\n // if we reach here, it means we don't handle responseType correctly\n safeInvoke(() =>\n context.logger?.debug(\n `unexpected error when retrieving responseText. responseType='${xhrUnsafe.responseType}'`,\n ),\n );\n }\n // the other possible error is Json Parse error which we fail silently\n return null;\n }\n return null;\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 originalXhrSetRequestHeader: (headerName: string, headerValue: string) => void,\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 headers: {},\n ...networkObserverContext.getTimestamps(),\n } as AmplitudeAnalyticsEvent;\n } catch (err) {\n /* istanbul ignore next */\n safeInvoke(() =>\n networkObserverContext.logger?.debug('an unexpected error occurred while calling xhr open', err),\n );\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 xhrUnsafe = this;\n const xhrSafe = xhrUnsafe as unknown as AmplitudeXMLHttpRequestSafe;\n const getJson = NetworkObserver.createXhrJsonParser(xhrUnsafe, networkObserverContext);\n const body = args[0] as XMLHttpRequestBodyInitSafe;\n const requestEvent = xhrSafe.$$AmplitudeAnalyticsEvent;\n\n // if xhrSafe.$$AmplitudeAnalyticsEvent is not set, it means that\n // the xhr.open method was called before we monkey-patched XHR and\n // the event is missed\n if (xhrSafe.$$AmplitudeAnalyticsEvent) {\n xhrSafe.addEventListener('loadend', function () {\n try {\n const responseHeaders = xhrSafe.getAllResponseHeaders();\n const responseBodySize = xhrSafe.getResponseHeader('content-length');\n\n const responseWrapper = new ResponseWrapperXhr(\n xhrSafe.status,\n responseHeaders,\n /* istanbul ignore next */\n responseBodySize ? parseInt(responseBodySize, 10) : undefined,\n getJson,\n );\n const requestHeaders = xhrSafe.$$AmplitudeAnalyticsEvent.headers;\n const requestWrapper = new RequestWrapperXhr(body, requestHeaders);\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 safeInvoke(() =>\n networkObserverContext.logger?.debug('an unexpected error occurred while handling xhr send', err),\n );\n }\n });\n }\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-argument */\n return originalXhrSend.apply(xhrSafe, args as any);\n };\n\n /**\n * IMPORTANT: This overrides window.XMLHttpRequest.prototype.setRequestHeader\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.setRequestHeader\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.setRequestHeader = function (headerName: any, headerValue: any) {\n const xhrSafe = this as unknown as AmplitudeXMLHttpRequestSafe;\n try {\n const analyticsEvent = xhrSafe.$$AmplitudeAnalyticsEvent;\n if (analyticsEvent) {\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-assignment */\n analyticsEvent.headers[headerName as string] = headerValue as string;\n }\n } catch (err) {\n /* istanbul ignore next */\n safeInvoke(() =>\n networkObserverContext.logger?.debug('an unexpected error occurred while calling xhr setRequestHeader', err),\n );\n }\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-argument */\n originalXhrSetRequestHeader.apply(xhrSafe, [headerName, headerValue]);\n };\n }\n}\n\n// singleton instance of NetworkObserver\nexport const networkObserver = new NetworkObserver();\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@amplitude/analytics-core",
3
- "version": "2.40.0",
3
+ "version": "2.40.1",
4
4
  "description": "",
5
5
  "author": "Amplitude Inc",
6
6
  "homepage": "https://github.com/amplitude/Amplitude-TypeScript",