@amplitude/analytics-core 2.22.0 → 2.22.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.
- package/lib/cjs/network-observer.d.ts +11 -0
- package/lib/cjs/network-observer.d.ts.map +1 -1
- package/lib/cjs/network-observer.js +47 -5
- package/lib/cjs/network-observer.js.map +1 -1
- package/lib/cjs/network-request-event.d.ts +2 -4
- package/lib/cjs/network-request-event.d.ts.map +1 -1
- package/lib/cjs/network-request-event.js +11 -20
- package/lib/cjs/network-request-event.js.map +1 -1
- package/lib/esm/network-observer.d.ts +11 -0
- package/lib/esm/network-observer.d.ts.map +1 -1
- package/lib/esm/network-observer.js +47 -5
- package/lib/esm/network-observer.js.map +1 -1
- package/lib/esm/network-request-event.d.ts +2 -4
- package/lib/esm/network-request-event.d.ts.map +1 -1
- package/lib/esm/network-request-event.js +11 -20
- package/lib/esm/network-request-event.js.map +1 -1
- package/package.json +2 -2
|
@@ -19,6 +19,17 @@ export declare class NetworkObserver {
|
|
|
19
19
|
private handleNetworkRequestEvent;
|
|
20
20
|
private getTimestamps;
|
|
21
21
|
private observeFetch;
|
|
22
|
+
/**
|
|
23
|
+
* Creates a function that parses the response of an XMLHttpRequest as JSON.
|
|
24
|
+
*
|
|
25
|
+
* Returns function instead of JSON object to avoid unnecessary parsing if the
|
|
26
|
+
* body is not being captured.
|
|
27
|
+
*
|
|
28
|
+
* @param xhrSafe - The XMLHttpRequest object.
|
|
29
|
+
* @param context - The NetworkObserver instance.
|
|
30
|
+
* @returns A function that parses the response of an XMLHttpRequest as JSON.
|
|
31
|
+
*/
|
|
32
|
+
static createXhrJsonParser(xhrUnsafe: XMLHttpRequest, context: NetworkObserver): () => any;
|
|
22
33
|
private observeXhr;
|
|
23
34
|
}
|
|
24
35
|
export declare const networkObserver: NetworkObserver;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"network-observer.d.ts","sourceRoot":"","sources":["../../src/network-observer.ts"],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,mBAAmB;IAa1D,OAAO,CAAC,yBAAyB;IA4DjC,OAAO,CAAC,aAAa;IAQrB,OAAO,CAAC,YAAY;IA8DpB;;;;;;;;;OASG;IACH,MAAM,CAAC,mBAAmB,CAAC,SAAS,EAAE,cAAc,EAAE,OAAO,EAAE,eAAe;IA8B9E,OAAO,CAAC,UAAU;CAqHnB;AAGD,eAAO,MAAM,eAAe,iBAAwB,CAAC"}
|
|
@@ -192,6 +192,46 @@ var NetworkObserver = /** @class */ (function () {
|
|
|
192
192
|
});
|
|
193
193
|
}); };
|
|
194
194
|
};
|
|
195
|
+
/**
|
|
196
|
+
* Creates a function that parses the response of an XMLHttpRequest as JSON.
|
|
197
|
+
*
|
|
198
|
+
* Returns function instead of JSON object to avoid unnecessary parsing if the
|
|
199
|
+
* body is not being captured.
|
|
200
|
+
*
|
|
201
|
+
* @param xhrSafe - The XMLHttpRequest object.
|
|
202
|
+
* @param context - The NetworkObserver instance.
|
|
203
|
+
* @returns A function that parses the response of an XMLHttpRequest as JSON.
|
|
204
|
+
*/
|
|
205
|
+
NetworkObserver.createXhrJsonParser = function (xhrUnsafe, context) {
|
|
206
|
+
return function () {
|
|
207
|
+
var _a, _b;
|
|
208
|
+
try {
|
|
209
|
+
if (xhrUnsafe.responseType === 'json') {
|
|
210
|
+
// if response is a JS object, clone it so that subscribers can't mutate it
|
|
211
|
+
if ((_a = context.globalScope) === null || _a === void 0 ? void 0 : _a.structuredClone) {
|
|
212
|
+
/* eslint-disable-next-line @typescript-eslint/no-unsafe-return */
|
|
213
|
+
return context.globalScope.structuredClone(xhrUnsafe.response);
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
else if (['text', ''].includes(xhrUnsafe.responseType)) {
|
|
217
|
+
// if response is a string, parse it as JSON
|
|
218
|
+
/* eslint-disable-next-line @typescript-eslint/no-unsafe-return */
|
|
219
|
+
return JSON.parse(xhrUnsafe.responseText);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
catch (err) {
|
|
223
|
+
/* istanbul ignore if */
|
|
224
|
+
if (err instanceof Error && err.name === 'InvalidStateError') {
|
|
225
|
+
// https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseText#exceptions
|
|
226
|
+
// if we reach here, it means we don't handle responseType correctly
|
|
227
|
+
(_b = context.logger) === null || _b === void 0 ? void 0 : _b.error("unexpected error when retrieving responseText. responseType='".concat(xhrUnsafe.responseType, "'"));
|
|
228
|
+
}
|
|
229
|
+
// the other possible error is Json Parse error which we fail silently
|
|
230
|
+
return null;
|
|
231
|
+
}
|
|
232
|
+
return null;
|
|
233
|
+
};
|
|
234
|
+
};
|
|
195
235
|
NetworkObserver.prototype.observeXhr = function (originalXhrOpen, originalXhrSend, originalXhrSetRequestHeader) {
|
|
196
236
|
/* istanbul ignore next */
|
|
197
237
|
if (!this.globalScope || !originalXhrOpen || !originalXhrSend) {
|
|
@@ -219,7 +259,7 @@ var NetworkObserver = /** @class */ (function () {
|
|
|
219
259
|
}
|
|
220
260
|
catch (err) {
|
|
221
261
|
/* istanbul ignore next */
|
|
222
|
-
(_b = networkObserverContext.logger) === null || _b === void 0 ? void 0 : _b.
|
|
262
|
+
(_b = networkObserverContext.logger) === null || _b === void 0 ? void 0 : _b.error('an unexpected error occurred while calling xhr open', err);
|
|
223
263
|
}
|
|
224
264
|
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
|
|
225
265
|
return originalXhrOpen.apply(xhrSafe, args);
|
|
@@ -238,7 +278,9 @@ var NetworkObserver = /** @class */ (function () {
|
|
|
238
278
|
args[_i] = arguments[_i];
|
|
239
279
|
}
|
|
240
280
|
// eslint-disable-next-line @typescript-eslint/no-this-alias
|
|
241
|
-
var
|
|
281
|
+
var xhrUnsafe = this;
|
|
282
|
+
var xhrSafe = xhrUnsafe;
|
|
283
|
+
var getJson = NetworkObserver.createXhrJsonParser(xhrUnsafe, networkObserverContext);
|
|
242
284
|
var body = args[0];
|
|
243
285
|
var requestEvent = xhrSafe.$$AmplitudeAnalyticsEvent;
|
|
244
286
|
xhrSafe.addEventListener('loadend', function () {
|
|
@@ -248,7 +290,7 @@ var NetworkObserver = /** @class */ (function () {
|
|
|
248
290
|
var responseBodySize = xhrSafe.getResponseHeader('content-length');
|
|
249
291
|
var responseWrapper = new network_request_event_1.ResponseWrapperXhr(xhrSafe.status, responseHeaders,
|
|
250
292
|
/* istanbul ignore next */
|
|
251
|
-
responseBodySize ? parseInt(responseBodySize, 10) : undefined,
|
|
293
|
+
responseBodySize ? parseInt(responseBodySize, 10) : undefined, getJson);
|
|
252
294
|
var requestHeaders = xhrSafe.$$AmplitudeAnalyticsEvent.headers;
|
|
253
295
|
var requestWrapper = new network_request_event_1.RequestWrapperXhr(body, requestHeaders);
|
|
254
296
|
requestEvent.status = xhrSafe.status;
|
|
@@ -256,7 +298,7 @@ var NetworkObserver = /** @class */ (function () {
|
|
|
256
298
|
}
|
|
257
299
|
catch (err) {
|
|
258
300
|
/* istanbul ignore next */
|
|
259
|
-
(_a = networkObserverContext.logger) === null || _a === void 0 ? void 0 : _a.
|
|
301
|
+
(_a = networkObserverContext.logger) === null || _a === void 0 ? void 0 : _a.error('an unexpected error occurred while handling xhr send', err);
|
|
260
302
|
}
|
|
261
303
|
});
|
|
262
304
|
/* eslint-disable-next-line @typescript-eslint/no-unsafe-argument */
|
|
@@ -279,7 +321,7 @@ var NetworkObserver = /** @class */ (function () {
|
|
|
279
321
|
}
|
|
280
322
|
catch (err) {
|
|
281
323
|
/* istanbul ignore next */
|
|
282
|
-
(_a = networkObserverContext.logger) === null || _a === void 0 ? void 0 : _a.
|
|
324
|
+
(_a = networkObserverContext.logger) === null || _a === void 0 ? void 0 : _a.error('an unexpected error occurred while calling xhr setRequestHeader', err);
|
|
283
325
|
}
|
|
284
326
|
/* eslint-disable-next-line @typescript-eslint/no-unsafe-argument */
|
|
285
327
|
originalXhrSetRequestHeader.apply(xhrSafe, [headerName, headerValue]);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,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Y,CAAC,GAAG,EAAE,MAAM,EAAE,YAAY,CAAC,MAAM,EAAE,EACtD,cAAc,EACd,eAAe,EACf,SAAS,EACT,YAAY,CAAC,SAAS,EACtB,YAAY,CAAC,aAAa,CAC3B,CAAC;iBACH;gBAAC,OAAO,GAAG,EAAE;oBACZ,0BAA0B;oBAC1B,MAAA,sBAAsB,CAAC,MAAM,0CAAE,KAAK,CAAC,sDAAsD,EAAE,GAAG,CAAC,CAAC;iBACnG;YACH,CAAC,CAAC,CAAC;YACH,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,sEAAsE;gBACtE,OAAO,CAAC,yBAAyB,CAAC,OAAO,CAAC,UAAoB,CAAC,GAAG,WAAqB,CAAC;aACzF;YAAC,OAAO,GAAG,EAAE;gBACZ,0BAA0B;gBAC1B,MAAA,sBAAsB,CAAC,MAAM,0CAAE,KAAK,CAAC,iEAAiE,EAAE,GAAG,CAAC,CAAC;aAC9G;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,AAzTD,IAyTC;AAzTY,0CAAe;AA2T5B,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 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 /* 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 /* 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 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 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 xhrSafe.responseText,\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 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 * 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 /* eslint-disable-next-line @typescript-eslint/no-unsafe-assignment */\n xhrSafe.$$AmplitudeAnalyticsEvent.headers[headerName as string] = headerValue as string;\n } catch (err) {\n /* istanbul ignore next */\n networkObserverContext.logger?.debug('an unexpected error occurred while calling xhr setRequestHeader', err);\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-observer.js","sourceRoot":"","sources":["../../src/network-observer.ts"],"names":[],"mappings":";;;;AAAA,uBAAoC;AACpC,qCAAoC;AAEpC,iEAUiC;AAajC;;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;IAME,yBAAY,MAAgB;QALpB,mBAAc,GAAsC,IAAI,GAAG,EAAE,CAAC;QAI9D,gBAAW,GAAG,KAAK,CAAC;QAE1B,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAM,WAAW,GAAG,IAAA,iBAAc,GAAE,CAAC;QACrC,IAAI,CAAC,eAAe,CAAC,WAAW,EAAE,EAAE;YAClC,0BAA0B;YAC1B,OAAO;SACR;QACD,IAAI,CAAC,WAAW,GAAG,WAAW,CAAC;IACjC,CAAC;IAEM,2BAAW,GAAlB;QACE,IAAM,WAAW,GAAG,IAAA,iBAAc,GAAE,CAAC;QACrC,OAAO,CAAC,CAAC,WAAW,IAAI,CAAC,CAAC,WAAW,CAAC,KAAK,CAAC;IAC9C,CAAC;IAED,mCAAS,GAAT,UAAU,aAAmC,EAAE,MAAgB;;QAC7D,IAAI,CAA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AE,EACtD,cAAc,EACd,eAAe,EACf,SAAS,EACT,YAAY,CAAC,SAAS,EACtB,YAAY,CAAC,aAAa,CAC3B,CAAC;iBACH;gBAAC,OAAO,GAAG,EAAE;oBACZ,0BAA0B;oBAC1B,MAAA,sBAAsB,CAAC,MAAM,0CAAE,KAAK,CAAC,sDAAsD,EAAE,GAAG,CAAC,CAAC;iBACnG;YACH,CAAC,CAAC,CAAC;YACH,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,sEAAsE;gBACtE,OAAO,CAAC,yBAAyB,CAAC,OAAO,CAAC,UAAoB,CAAC,GAAG,WAAqB,CAAC;aACzF;YAAC,OAAO,GAAG,EAAE;gBACZ,0BAA0B;gBAC1B,MAAA,sBAAsB,CAAC,MAAM,0CAAE,KAAK,CAAC,iEAAiE,EAAE,GAAG,CAAC,CAAC;aAC9G;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,AApWD,IAoWC;AApWY,0CAAe;AAsW5B,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\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 /* 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 /**\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 context.logger?.error(\n `unexpected error when retrieving responseText. responseType='${xhrUnsafe.responseType}'`,\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 networkObserverContext.logger?.error('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 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 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 networkObserverContext.logger?.error('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 * 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 /* eslint-disable-next-line @typescript-eslint/no-unsafe-assignment */\n xhrSafe.$$AmplitudeAnalyticsEvent.headers[headerName as string] = headerValue as string;\n } catch (err) {\n /* istanbul ignore next */\n networkObserverContext.logger?.error('an unexpected error occurred while calling xhr setRequestHeader', err);\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"]}
|
|
@@ -104,7 +104,6 @@ export interface IResponseWrapper {
|
|
|
104
104
|
bodySize?: number;
|
|
105
105
|
status?: number;
|
|
106
106
|
body?: string | Blob | ReadableStream | ArrayBuffer | FormDataSafe | URLSearchParams | ArrayBufferView | null;
|
|
107
|
-
text: () => Promise<string | null>;
|
|
108
107
|
json: (allow?: string[], exclude?: string[]) => Promise<JsonObject | null>;
|
|
109
108
|
}
|
|
110
109
|
/**
|
|
@@ -141,11 +140,10 @@ export declare class ResponseWrapperXhr implements IResponseWrapper {
|
|
|
141
140
|
readonly statusCode: number;
|
|
142
141
|
readonly headersString: string;
|
|
143
142
|
readonly size: number | undefined;
|
|
144
|
-
readonly
|
|
145
|
-
constructor(statusCode: number, headersString: string, size: number | undefined,
|
|
143
|
+
readonly getJson: () => any | null;
|
|
144
|
+
constructor(statusCode: number, headersString: string, size: number | undefined, getJson: () => any | null);
|
|
146
145
|
get bodySize(): number | undefined;
|
|
147
146
|
get status(): number;
|
|
148
|
-
text(): Promise<string | null>;
|
|
149
147
|
headers(allow?: string[]): Record<string, string> | undefined;
|
|
150
148
|
json(allow?: string[], exclude?: string[]): Promise<JsonObject | null>;
|
|
151
149
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"network-request-event.d.ts","sourceRoot":"","sources":["../../src/network-request-event.ts"],"names":[],"mappings":"AAQA,KAAK,QAAQ,GAAG;IACd,IAAI,EAAE,MAAM,CAAC;CACd,CAAC;AAEF,KAAK,eAAe,GAAG;IACrB,UAAU,EAAE,MAAM,CAAC;CACpB,CAAC;AAEF,KAAK,mBAAmB,GAAG;IACzB,UAAU,EAAE,MAAM,CAAC;CACpB,CAAC;AAEF,KAAK,mBAAmB,GAAG;IACzB,QAAQ,IAAI,MAAM,CAAC;CACpB,CAAC;AAKF,KAAK,sBAAsB,GAAG,MAAM,GAAG,QAAQ,GAAG,IAAI,CAAC;AAEvD,KAAK,YAAY,GACb,MAAM,GACN,IAAI,GACJ,eAAe,GACf,YAAY,GACZ,mBAAmB,GACnB,mBAAmB,GACnB,IAAI,GACJ,SAAS,CAAC;AAEd,KAAK,kBAAkB,GAAG;IACxB,OAAO,IAAI,gBAAgB,CAAC,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;IAC9C,OAAO,CAAC,UAAU,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,EAAE,M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,eAAO,MAAM,YAAY,YACd,OAAO,MAAM,EAAE,MAAM,CAAC;;;MAK9B,OAAO,MAAM,EAAE,MAAM,CAqBvB,CAAC;AACF,qBAAa,mBAAmB;aAMZ,IAAI,EAAE,KAAK,GAAG,OAAO;aACrB,MAAM,EAAE,MAAM;aACd,SAAS,EAAE,MAAM;aACjB,SAAS,EAAE,MAAM;aACjB,GAAG,CAAC;aACJ,cAAc,CAAC;aACf,MAAM,EAAE,MAAM;aACd,QAAQ,CAAC;aACT,eAAe,CAAC;aAChB,KAAK,CAAC;cACd,MAAM;iBACH,MAAM;;aAED,OAAO,CAAC;IAlBnB,cAAc,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACxC,eAAe,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACzC,eAAe,CAAC,EAAE,OAAO,CAAC,UAAU,GAAG,IAAI,CAAC,CAAC;IAC7C,gBAAgB,CAAC,EAAE,OAAO,CAAC,UAAU,GAAG,IAAI,CAAC,CAAC;gBAEnC,IAAI,EAAE,KAAK,GAAG,OAAO,EACrB,MAAM,EAAE,MAAM,EACd,SAAS,EAAE,MAAM,EACjB,SAAS,EAAE,MAAM,EACjB,GAAG,CAAC,oBAAQ,EACZ,cAAc,CAAC,6BAAiB,EAChC,MAAM,GAAE,MAAU,EAClB,QAAQ,CAAC,oBAAQ,EACjB,eAAe,CAAC,8BAAkB,EAClC,KAAK,CAAC;cACd,MAAM;iBACH,MAAM;iBAChB,EACe,OAAO,CAAC,oBAAQ;IAGlC,cAAc,IAAI,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC;CAmBtC"}
|
|
@@ -346,11 +346,11 @@ var ResponseWrapperFetch = /** @class */ (function () {
|
|
|
346
346
|
}());
|
|
347
347
|
exports.ResponseWrapperFetch = ResponseWrapperFetch;
|
|
348
348
|
var ResponseWrapperXhr = /** @class */ (function () {
|
|
349
|
-
function ResponseWrapperXhr(statusCode, headersString, size,
|
|
349
|
+
function ResponseWrapperXhr(statusCode, headersString, size, getJson) {
|
|
350
350
|
this.statusCode = statusCode;
|
|
351
351
|
this.headersString = headersString;
|
|
352
352
|
this.size = size;
|
|
353
|
-
this.
|
|
353
|
+
this.getJson = getJson;
|
|
354
354
|
}
|
|
355
355
|
Object.defineProperty(ResponseWrapperXhr.prototype, "bodySize", {
|
|
356
356
|
get: function () {
|
|
@@ -366,14 +366,6 @@ var ResponseWrapperXhr = /** @class */ (function () {
|
|
|
366
366
|
enumerable: false,
|
|
367
367
|
configurable: true
|
|
368
368
|
});
|
|
369
|
-
ResponseWrapperXhr.prototype.text = function () {
|
|
370
|
-
return tslib_1.__awaiter(this, void 0, void 0, function () {
|
|
371
|
-
return tslib_1.__generator(this, function (_a) {
|
|
372
|
-
// reject if body has already been consumed
|
|
373
|
-
return [2 /*return*/, this.responseText];
|
|
374
|
-
});
|
|
375
|
-
});
|
|
376
|
-
};
|
|
377
369
|
ResponseWrapperXhr.prototype.headers = function (allow) {
|
|
378
370
|
var e_3, _a;
|
|
379
371
|
if (allow === void 0) { allow = []; }
|
|
@@ -404,18 +396,17 @@ var ResponseWrapperXhr = /** @class */ (function () {
|
|
|
404
396
|
if (allow === void 0) { allow = []; }
|
|
405
397
|
if (exclude === void 0) { exclude = []; }
|
|
406
398
|
return tslib_1.__awaiter(this, void 0, void 0, function () {
|
|
407
|
-
var
|
|
399
|
+
var jsonBody;
|
|
408
400
|
return tslib_1.__generator(this, function (_a) {
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
text = _a.sent();
|
|
417
|
-
return [2 /*return*/, safeParseAndPruneBody(text, allow, exclude)];
|
|
401
|
+
if (allow.length === 0) {
|
|
402
|
+
return [2 /*return*/, null];
|
|
403
|
+
}
|
|
404
|
+
jsonBody = this.getJson();
|
|
405
|
+
if (jsonBody) {
|
|
406
|
+
(0, json_query_1.pruneJson)(jsonBody, allow, exclude);
|
|
407
|
+
return [2 /*return*/, jsonBody];
|
|
418
408
|
}
|
|
409
|
+
return [2 /*return*/, null];
|
|
419
410
|
});
|
|
420
411
|
});
|
|
421
412
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"network-request-event.js","sourceRoot":"","sources":["../../src/network-request-event.ts"],"names":[],"mappings":";;;;AAAA,+CAAgD;AAChD,iDAA+C;AAC/C,uBAAqD;AA2DrD,IAAM,iBAAiB,GAAG,GAAG,CAAC;AAmCjB,QAAA,eAAe,GAAG,GAAG,CAAC;AAEnC;;;;;;;;;;;;;;;;;GAiBG;AACH;IAEE,6BAAoB,OAAwB;QAAxB,YAAO,GAAP,OAAO,CAAiB;IAAG,CAAC;IAEhD,qCAAO,GAAP,UAAQ,KAAoB;;QAApB,sBAAA,EAAA,UAAoB;QAC1B,IAAM,aAAa,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC;QAE3C,qCAAqC;QACrC,IAAM,eAAe,GAA2B,EAAE,CAAC;QACnD,IAAI,KAAK,CAAC,OAAO,CAAC,aAAa,CAAC,EAAE;YAChC,aAAa,CAAC,OAAO,CAAC,UAAC,EAAyB;oBAAzB,KAAA,qBAAyB,EAAxB,UAAU,QAAA,EAAE,WAAW,QAAA;gBAC7C,eAAe,CAAC,UAAU,CAAC,GAAG,WAAW,CAAC;YAC5C,CAAC,CAAC,CAAC;SACJ;aAAM,IAAI,aAAa,YAAY,OAAO,EAAE;YAC3C,aAAa,CAAC,OAAO,CAAC,UAAC,KAAa,EAAE,GAAW;gBAC/C,eAAe,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;YAC/B,CAAC,CAAC,CAAC;SACJ;aAAM,IAAI,OAAO,aAAa,KAAK,QAAQ,IAAI,aAAa,KAAK,IAAI,EAAE;;gBACtE,KAA2B,IAAA,KAAA,iBAAA,MAAM,CAAC,OAAO,CAAC,aAAuC,CAAC,CAAA,gBAAA,4BAAE;oBAAzE,IAAA,K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EN_HEADERS } from './';\n\n/* SAFE TYPE DEFINITIONS\n These type definitions expose limited properties of the original types\n to prevent the consumer from mutating them or consuming them.\n*/\ntype BlobSafe = {\n size: number;\n};\n\ntype ArrayBufferSafe = {\n byteLength: number;\n};\n\ntype ArrayBufferViewSafe = {\n byteLength: number;\n};\n\ntype URLSearchParamsSafe = {\n toString(): string;\n};\n\n// no method on readablestream is safe to call\ntype ReadableStreamSafe = Record<string, never>;\n\ntype FormDataEntryValueSafe = string | BlobSafe | null;\n\ntype BodyInitSafe =\n | string\n | Blob\n | ArrayBufferSafe\n | FormDataSafe\n | URLSearchParamsSafe\n | ArrayBufferViewSafe\n | null\n | undefined;\n\ntype HeadersRequestSafe = {\n entries(): IterableIterator<[string, string]>;\n forEach(callbackfn: (value: string, key: string) => void): void;\n};\n\ntype HeadersResponseSafe = {\n get(name: string): string | null;\n forEach(callbackfn: (value: string, key: string) => void): void;\n};\n\ntype HeadersInitSafe = HeadersRequestSafe | Record<string, string> | string[][];\n\ntype ResponseSafe = {\n status: number;\n headers: HeadersResponseSafe | undefined;\n clone(): ResponseCloneSafe;\n};\n\ntype ResponseCloneSafe = {\n text(): Promise<string>;\n};\n\nconst TEXT_READ_TIMEOUT = 500;\n\nexport type RequestInitSafe = {\n method?: string;\n headers?: HeadersInitSafe;\n body?: BodyInitSafe;\n};\nexport interface FormDataSafe {\n entries(): IterableIterator<[string, FormDataEntryValueSafe]>;\n}\nexport type XMLHttpRequestBodyInitSafe = BlobSafe | FormDataSafe | URLSearchParamsSafe | string;\n\nexport type FetchRequestBody =\n | string\n | BlobSafe\n | ArrayBufferSafe\n | FormDataSafe\n | URLSearchParamsSafe\n | ArrayBufferViewSafe\n | null\n | undefined;\n\nexport interface IRequestWrapper {\n /**\n * Get the headers of the request.\n * @param allow - The headers to allow.\n * @returns The pruned headers\n */\n headers(allow?: string[]): Record<string, string> | undefined;\n bodySize?: number;\n method?: string;\n body?: FetchRequestBody | XMLHttpRequestBodyInitSafe | null;\n json: (allow?: string[], exclude?: string[]) => Promise<JsonObject | null>;\n}\n\nexport const MAXIMUM_ENTRIES = 100;\n\n/**\n * This class encapsulates the RequestInit (https://developer.mozilla.org/en-US/docs/Web/API/RequestInit)\n * object so that the consumer can only get access to the headers, method and body size.\n *\n * This is to prevent consumers from directly accessing the Request object\n * and mutating it or running costly operations on it.\n *\n * IMPORTANT:\n * * Do not make changes to this class without careful consideration\n * of performance implications, memory usage and potential to mutate the customer's\n * request.\n * * NEVER .clone() the RequestInit object. This will 2x's the memory overhead of the request\n * * NEVER: call .arrayBuffer(), text(), json() or any other method on the body that\n * consumes the body's stream. This will cause the response to be consumed\n * meaning the body will be empty when the customer tries to access it.\n * (ie: if the body is an instanceof https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream\n * never call any of the methods on it)\n */\nexport class RequestWrapperFetch implements IRequestWrapper {\n private _bodySize: number | undefined;\n constructor(private request: RequestInitSafe) {}\n\n headers(allow: string[] = []): Record<string, string> | undefined {\n const headersUnsafe = this.request.headers;\n\n // copy the headers into a new object\n const headersSafeCopy: Record<string, string> = {};\n if (Array.isArray(headersUnsafe)) {\n headersUnsafe.forEach(([headerName, headerValue]) => {\n headersSafeCopy[headerName] = headerValue;\n });\n } else if (headersUnsafe instanceof Headers) {\n headersUnsafe.forEach((value: string, key: string) => {\n headersSafeCopy[key] = value;\n });\n } else if (typeof headersUnsafe === 'object' && headersUnsafe !== null) {\n for (const [key, value] of Object.entries(headersUnsafe as Record<string, string>)) {\n headersSafeCopy[key] = value;\n }\n }\n\n return pruneHeaders(headersSafeCopy, { allow });\n }\n\n get bodySize(): number | undefined {\n if (typeof this._bodySize === 'number') return this._bodySize;\n const global = getGlobalScope();\n\n /* istanbul ignore if */\n if (!global?.TextEncoder) {\n return;\n }\n const body = this.request.body as FetchRequestBody;\n this._bodySize = getBodySize(body, MAXIMUM_ENTRIES);\n return this._bodySize;\n }\n\n get method(): string | undefined {\n return this.request.method;\n }\n\n get body(): string | null {\n if (typeof this.request.body === 'string') {\n return this.request.body;\n }\n return null;\n }\n\n async json(allow: string[] = [], exclude: string[] = []): Promise<JsonObject | null> {\n if (allow.length === 0) {\n return null;\n }\n const text = this.body;\n return safeParseAndPruneBody(text, allow, exclude);\n }\n}\n\nexport class RequestWrapperXhr implements IRequestWrapper {\n constructor(readonly bodyRaw: XMLHttpRequestBodyInitSafe | null, readonly requestHeaders: Record<string, string>) {}\n\n headers(allow: string[] = []): Record<string, string> | undefined {\n return pruneHeaders(this.requestHeaders, { allow });\n }\n\n get bodySize(): number | undefined {\n return getBodySize(this.bodyRaw as FetchRequestBody, MAXIMUM_ENTRIES);\n }\n\n get body(): string | null {\n if (typeof this.bodyRaw === 'string') {\n return this.bodyRaw;\n }\n return null;\n }\n\n async json(allow: string[] = [], exclude: string[] = []): Promise<JsonObject | null> {\n if (allow.length === 0) {\n return null;\n }\n const text = this.body;\n return safeParseAndPruneBody(text, allow, exclude);\n }\n}\n\nfunction getBodySize(bodyUnsafe: FetchRequestBody, maxEntries: number): number | undefined {\n let bodySize: number | undefined;\n const global = getGlobalScope();\n /* istanbul ignore next */\n const TextEncoder = global?.TextEncoder;\n /* istanbul ignore next */\n if (!TextEncoder) {\n return;\n }\n let bodySafe;\n if (typeof bodyUnsafe === 'string') {\n bodySafe = bodyUnsafe;\n bodySize = new TextEncoder().encode(bodySafe).length;\n } else if (bodyUnsafe instanceof Blob) {\n bodySafe = bodyUnsafe as BlobSafe;\n bodySize = bodySafe.size;\n } else if (bodyUnsafe instanceof URLSearchParams) {\n bodySafe = bodyUnsafe as URLSearchParamsSafe;\n bodySize = new TextEncoder().encode(bodySafe.toString()).length;\n } else if (ArrayBuffer.isView(bodyUnsafe)) {\n bodySafe = bodyUnsafe as ArrayBufferViewSafe;\n bodySize = bodySafe.byteLength;\n } else if (bodyUnsafe instanceof ArrayBuffer) {\n bodySafe = bodyUnsafe as ArrayBufferSafe;\n bodySize = bodySafe.byteLength;\n } else if (bodyUnsafe instanceof FormData) {\n // Estimating only for text parts; not accurate for files\n const formData = bodyUnsafe as unknown as FormDataSafe;\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 instanceof Blob) {\n total += value.size;\n } else {\n // encountered an unknown type\n // we can't estimate the size of this entry\n return;\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 >= maxEntries) {\n return;\n }\n }\n bodySize = total;\n } else if (bodyUnsafe instanceof ReadableStream) {\n // If bodyUnsafe is an instanceof ReadableStream, we can't determine the size,\n // without consuming it, so we return undefined.\n // Never ever consume ReadableStream! DO NOT DO IT!!!\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n bodySafe = bodyUnsafe as unknown as ReadableStreamSafe;\n return;\n }\n return bodySize;\n}\n\nexport type JsonObject = {\n [key: string]: JsonValue;\n};\n\nexport type JsonValue = string | number | boolean | null | JsonObject | JsonArray;\n\nexport type JsonArray = Array<JsonValue>;\n\nexport interface IResponseWrapper {\n /**\n * Get the headers of the response.\n * @param allow - The headers to allow.\n * @returns The pruned headers\n */\n headers(allow?: string[]): Record<string, string> | undefined;\n bodySize?: number;\n status?: number;\n body?: string | Blob | ReadableStream | ArrayBuffer | FormDataSafe | URLSearchParams | ArrayBufferView | null;\n text: () => Promise<string | null>;\n json: (allow?: string[], exclude?: string[]) => Promise<JsonObject | null>;\n}\n\n/**\n * This class encapsulates the Fetch API Response object\n * (https://developer.mozilla.org/en-US/docs/Web/API/Response) so that the consumer can\n * only get access to the headers and body size.\n *\n * This is to prevent consumers from directly accessing the Response object\n * and mutating it or running costly operations on it.\n *\n * IMPORTANT:\n * * Do not make changes to this class without careful consideration\n * of performance implications, memory usage and potential to mutate the customer's\n * response.\n * * Do not .clone() the Response object unless you need to access the body.\n * Cloning will 2x the memory overhead of the response.\n * * NEVER consume the body's stream. This will cause the response to be consumed\n * meaning the body will be empty when the customer tries to access it.\n * (ie: if the body is an instanceof https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream\n * never call any of the methods on it)\n */\nexport class ResponseWrapperFetch implements IResponseWrapper {\n private _bodySize: number | undefined;\n private clonedResponse?: ResponseCloneSafe;\n constructor(private response: ResponseSafe) {}\n\n headers(allow: string[] = []): Record<string, string> | undefined {\n if (this.response.headers instanceof Headers) {\n const headersSafe = this.response.headers as HeadersResponseSafe;\n const headersOut: Record<string, string> = {};\n /* istanbul ignore next */\n headersSafe?.forEach?.((value, key) => {\n headersOut[key] = value;\n });\n return pruneHeaders(headersOut, { allow });\n }\n\n return;\n }\n\n get bodySize(): number | undefined {\n if (this._bodySize !== undefined) return this._bodySize;\n /* istanbul ignore next */\n const contentLength = this.response.headers?.get?.('content-length');\n const bodySize = contentLength ? parseInt(contentLength, 10) : undefined;\n this._bodySize = bodySize;\n return bodySize;\n }\n\n get status(): number {\n return this.response.status;\n }\n\n async text(): Promise<string | null> {\n // !!!IMPORTANT: we clone the response to avoid mutating the original response\n // never call .text(), .json(), etc.. on the original response always clone it first\n if (!this.clonedResponse) {\n this.clonedResponse = this.response.clone();\n }\n try {\n const textPromise = this.clonedResponse.text();\n const timer = new Promise<null>((resolve) =>\n setTimeout(\n /* istanbul ignore next */\n () => resolve(null),\n TEXT_READ_TIMEOUT,\n ),\n );\n const text = await Promise.race<string | null>([textPromise, timer]);\n return text;\n } catch (error) {\n return null;\n }\n }\n\n async json(allow: string[] = [], exclude: string[] = []): Promise<JsonObject | null> {\n if (allow.length === 0) {\n return null;\n }\n const text = await this.text();\n return safeParseAndPruneBody(text, allow, exclude);\n }\n}\n\nexport class ResponseWrapperXhr implements IResponseWrapper {\n constructor(\n readonly statusCode: number,\n readonly headersString: string,\n readonly size: number | undefined,\n readonly responseText: string,\n ) {}\n\n get bodySize(): number | undefined {\n return this.size;\n }\n\n get status(): number {\n return this.statusCode;\n }\n\n async text(): Promise<string | null> {\n // reject if body has already been consumed\n return this.responseText;\n }\n\n headers(allow: string[] = []): Record<string, string> | undefined {\n if (!this.headersString) {\n return {};\n }\n const headers: Record<string, string> = {};\n const headerLines = this.headersString.split('\\r\\n');\n for (const line of headerLines) {\n const [key, value] = line.split(': ');\n if (key && value) {\n headers[key] = value;\n }\n }\n return pruneHeaders(headers, { allow });\n }\n\n async json(allow: string[] = [], exclude: string[] = []): Promise<JsonObject | null> {\n if (allow.length === 0) {\n return null;\n }\n const text = await this.text();\n return safeParseAndPruneBody(text, allow, exclude);\n }\n}\n\nfunction safeParseAndPruneBody(text: string | null, allow: string[], exclude: string[]): JsonObject | null {\n if (!text) return null;\n try {\n const json = JSON.parse(text) as JsonObject;\n pruneJson(json, allow, exclude);\n return json;\n } catch (error) {\n return null;\n }\n}\n\nexport enum PRUNE_STRATEGY {\n REDACT = 'redact',\n REMOVE = 'remove',\n}\n\nconst REDACTED_VALUE = '[REDACTED]';\n\n/**\n * Prune headers from a headers record object.\n * @param headers - The headers to prune.\n * @param options - The options to prune the headers.\n * @param options.exclude - List of headers to delete from headers\n * @param options.include - List of headers to keep in headers, if not provided, all headers are kept by default\n * @returns The pruned headers.\n */\nexport const pruneHeaders = (\n headers: Record<string, string>,\n options: {\n allow?: string[];\n strategy?: PRUNE_STRATEGY;\n },\n): Record<string, string> => {\n const { allow = [], strategy = PRUNE_STRATEGY.REMOVE } = options;\n const exclude = [...FORBIDDEN_HEADERS];\n const headersPruned: Record<string, string> = {};\n\n for (const key of Object.keys(headers)) {\n const lowerKey = key.toLowerCase();\n\n if (exclude.find((e) => e.toLowerCase() === lowerKey)) {\n if (strategy === PRUNE_STRATEGY.REDACT) {\n headersPruned[key] = REDACTED_VALUE;\n }\n } else if (!allow.find((i) => i.toLowerCase() === lowerKey)) {\n if (strategy === PRUNE_STRATEGY.REDACT) {\n headersPruned[key] = REDACTED_VALUE;\n }\n } else {\n headersPruned[key] = headers[key];\n }\n }\n return headersPruned;\n};\nexport class NetworkRequestEvent {\n public requestHeaders?: Record<string, string>;\n public responseHeaders?: Record<string, string>;\n public requestBodyJson?: Promise<JsonObject | null>;\n public responseBodyJson?: Promise<JsonObject | null>;\n constructor(\n public readonly type: 'xhr' | 'fetch',\n public readonly method: string,\n public readonly timestamp: number,\n public readonly startTime: number,\n public readonly url?: string,\n public readonly requestWrapper?: IRequestWrapper,\n public readonly status: number = 0,\n public readonly duration?: number,\n public readonly responseWrapper?: IResponseWrapper,\n public readonly error?: {\n name: string;\n message: string;\n },\n public readonly endTime?: number,\n ) {}\n\n toSerializable(): Record<string, any> {\n const serialized: Record<string, any> = {\n type: this.type,\n method: this.method,\n url: this.url,\n timestamp: this.timestamp,\n status: this.status,\n duration: this.duration,\n error: this.error,\n startTime: this.startTime,\n endTime: this.endTime,\n requestHeaders: this.requestWrapper?.headers([...SAFE_HEADERS]),\n requestBodySize: this.requestWrapper?.bodySize,\n responseHeaders: this.responseWrapper?.headers([...SAFE_HEADERS]),\n responseBodySize: this.responseWrapper?.bodySize,\n };\n\n return Object.fromEntries(Object.entries(serialized).filter(([_, v]) => v !== undefined));\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"network-request-event.js","sourceRoot":"","sources":["../../src/network-request-event.ts"],"names":[],"mappings":";;;;AAAA,+CAAgD;AAChD,iDAA+C;AAC/C,uBAAqD;AA2DrD,IAAM,iBAAiB,GAAG,GAAG,CAAC;AAmCjB,QAAA,eAAe,GAAG,GAAG,CAAC;AAEnC;;;;;;;;;;;;;;;;;GAiBG;AACH;IAEE,6BAAoB,OAAwB;QAAxB,YAAO,GAAP,OAAO,CAAiB;IAAG,CAAC;IAEhD,qCAAO,GAAP,UAAQ,KAAoB;;QAApB,sBAAA,EAAA,UAAoB;QAC1B,IAAM,aAAa,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC;QAE3C,qCAAqC;QACrC,IAAM,eAAe,GAA2B,EAAE,CAAC;QACnD,IAAI,KAAK,CAAC,OAAO,CAAC,aAAa,CAAC,EAAE;YAChC,aAAa,CAAC,OAAO,CAAC,UAAC,EAAyB;oBAAzB,KAAA,qBAAyB,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ACjE,gBAAgB,EAAE,MAAA,IAAI,CAAC,eAAe,0CAAE,QAAQ;SACjD,CAAC;QAEF,OAAO,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC,MAAM,CAAC,UAAC,EAAM;gBAAN,KAAA,qBAAM,EAAL,CAAC,QAAA,EAAE,CAAC,QAAA;YAAM,OAAA,CAAC,KAAK,SAAS;QAAf,CAAe,CAAC,CAAC,CAAC;IAC5F,CAAC;IACH,0BAAC;AAAD,CAAC,AAzCD,IAyCC;AAzCY,kDAAmB","sourcesContent":["import { getGlobalScope } from './global-scope';\nimport { pruneJson } from './utils/json-query';\nimport { SAFE_HEADERS, FORBIDDEN_HEADERS } from './';\n\n/* SAFE TYPE DEFINITIONS\n These type definitions expose limited properties of the original types\n to prevent the consumer from mutating them or consuming them.\n*/\ntype BlobSafe = {\n size: number;\n};\n\ntype ArrayBufferSafe = {\n byteLength: number;\n};\n\ntype ArrayBufferViewSafe = {\n byteLength: number;\n};\n\ntype URLSearchParamsSafe = {\n toString(): string;\n};\n\n// no method on readablestream is safe to call\ntype ReadableStreamSafe = Record<string, never>;\n\ntype FormDataEntryValueSafe = string | BlobSafe | null;\n\ntype BodyInitSafe =\n | string\n | Blob\n | ArrayBufferSafe\n | FormDataSafe\n | URLSearchParamsSafe\n | ArrayBufferViewSafe\n | null\n | undefined;\n\ntype HeadersRequestSafe = {\n entries(): IterableIterator<[string, string]>;\n forEach(callbackfn: (value: string, key: string) => void): void;\n};\n\ntype HeadersResponseSafe = {\n get(name: string): string | null;\n forEach(callbackfn: (value: string, key: string) => void): void;\n};\n\ntype HeadersInitSafe = HeadersRequestSafe | Record<string, string> | string[][];\n\ntype ResponseSafe = {\n status: number;\n headers: HeadersResponseSafe | undefined;\n clone(): ResponseCloneSafe;\n};\n\ntype ResponseCloneSafe = {\n text(): Promise<string>;\n};\n\nconst TEXT_READ_TIMEOUT = 500;\n\nexport type RequestInitSafe = {\n method?: string;\n headers?: HeadersInitSafe;\n body?: BodyInitSafe;\n};\nexport interface FormDataSafe {\n entries(): IterableIterator<[string, FormDataEntryValueSafe]>;\n}\nexport type XMLHttpRequestBodyInitSafe = BlobSafe | FormDataSafe | URLSearchParamsSafe | string;\n\nexport type FetchRequestBody =\n | string\n | BlobSafe\n | ArrayBufferSafe\n | FormDataSafe\n | URLSearchParamsSafe\n | ArrayBufferViewSafe\n | null\n | undefined;\n\nexport interface IRequestWrapper {\n /**\n * Get the headers of the request.\n * @param allow - The headers to allow.\n * @returns The pruned headers\n */\n headers(allow?: string[]): Record<string, string> | undefined;\n bodySize?: number;\n method?: string;\n body?: FetchRequestBody | XMLHttpRequestBodyInitSafe | null;\n json: (allow?: string[], exclude?: string[]) => Promise<JsonObject | null>;\n}\n\nexport const MAXIMUM_ENTRIES = 100;\n\n/**\n * This class encapsulates the RequestInit (https://developer.mozilla.org/en-US/docs/Web/API/RequestInit)\n * object so that the consumer can only get access to the headers, method and body size.\n *\n * This is to prevent consumers from directly accessing the Request object\n * and mutating it or running costly operations on it.\n *\n * IMPORTANT:\n * * Do not make changes to this class without careful consideration\n * of performance implications, memory usage and potential to mutate the customer's\n * request.\n * * NEVER .clone() the RequestInit object. This will 2x's the memory overhead of the request\n * * NEVER: call .arrayBuffer(), text(), json() or any other method on the body that\n * consumes the body's stream. This will cause the response to be consumed\n * meaning the body will be empty when the customer tries to access it.\n * (ie: if the body is an instanceof https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream\n * never call any of the methods on it)\n */\nexport class RequestWrapperFetch implements IRequestWrapper {\n private _bodySize: number | undefined;\n constructor(private request: RequestInitSafe) {}\n\n headers(allow: string[] = []): Record<string, string> | undefined {\n const headersUnsafe = this.request.headers;\n\n // copy the headers into a new object\n const headersSafeCopy: Record<string, string> = {};\n if (Array.isArray(headersUnsafe)) {\n headersUnsafe.forEach(([headerName, headerValue]) => {\n headersSafeCopy[headerName] = headerValue;\n });\n } else if (headersUnsafe instanceof Headers) {\n headersUnsafe.forEach((value: string, key: string) => {\n headersSafeCopy[key] = value;\n });\n } else if (typeof headersUnsafe === 'object' && headersUnsafe !== null) {\n for (const [key, value] of Object.entries(headersUnsafe as Record<string, string>)) {\n headersSafeCopy[key] = value;\n }\n }\n\n return pruneHeaders(headersSafeCopy, { allow });\n }\n\n get bodySize(): number | undefined {\n if (typeof this._bodySize === 'number') return this._bodySize;\n const global = getGlobalScope();\n\n /* istanbul ignore if */\n if (!global?.TextEncoder) {\n return;\n }\n const body = this.request.body as FetchRequestBody;\n this._bodySize = getBodySize(body, MAXIMUM_ENTRIES);\n return this._bodySize;\n }\n\n get method(): string | undefined {\n return this.request.method;\n }\n\n get body(): string | null {\n if (typeof this.request.body === 'string') {\n return this.request.body;\n }\n return null;\n }\n\n async json(allow: string[] = [], exclude: string[] = []): Promise<JsonObject | null> {\n if (allow.length === 0) {\n return null;\n }\n const text = this.body;\n return safeParseAndPruneBody(text, allow, exclude);\n }\n}\n\nexport class RequestWrapperXhr implements IRequestWrapper {\n constructor(readonly bodyRaw: XMLHttpRequestBodyInitSafe | null, readonly requestHeaders: Record<string, string>) {}\n\n headers(allow: string[] = []): Record<string, string> | undefined {\n return pruneHeaders(this.requestHeaders, { allow });\n }\n\n get bodySize(): number | undefined {\n return getBodySize(this.bodyRaw as FetchRequestBody, MAXIMUM_ENTRIES);\n }\n\n get body(): string | null {\n if (typeof this.bodyRaw === 'string') {\n return this.bodyRaw;\n }\n return null;\n }\n\n async json(allow: string[] = [], exclude: string[] = []): Promise<JsonObject | null> {\n if (allow.length === 0) {\n return null;\n }\n const text = this.body;\n return safeParseAndPruneBody(text, allow, exclude);\n }\n}\n\nfunction getBodySize(bodyUnsafe: FetchRequestBody, maxEntries: number): number | undefined {\n let bodySize: number | undefined;\n const global = getGlobalScope();\n /* istanbul ignore next */\n const TextEncoder = global?.TextEncoder;\n /* istanbul ignore next */\n if (!TextEncoder) {\n return;\n }\n let bodySafe;\n if (typeof bodyUnsafe === 'string') {\n bodySafe = bodyUnsafe;\n bodySize = new TextEncoder().encode(bodySafe).length;\n } else if (bodyUnsafe instanceof Blob) {\n bodySafe = bodyUnsafe as BlobSafe;\n bodySize = bodySafe.size;\n } else if (bodyUnsafe instanceof URLSearchParams) {\n bodySafe = bodyUnsafe as URLSearchParamsSafe;\n bodySize = new TextEncoder().encode(bodySafe.toString()).length;\n } else if (ArrayBuffer.isView(bodyUnsafe)) {\n bodySafe = bodyUnsafe as ArrayBufferViewSafe;\n bodySize = bodySafe.byteLength;\n } else if (bodyUnsafe instanceof ArrayBuffer) {\n bodySafe = bodyUnsafe as ArrayBufferSafe;\n bodySize = bodySafe.byteLength;\n } else if (bodyUnsafe instanceof FormData) {\n // Estimating only for text parts; not accurate for files\n const formData = bodyUnsafe as unknown as FormDataSafe;\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 instanceof Blob) {\n total += value.size;\n } else {\n // encountered an unknown type\n // we can't estimate the size of this entry\n return;\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 >= maxEntries) {\n return;\n }\n }\n bodySize = total;\n } else if (bodyUnsafe instanceof ReadableStream) {\n // If bodyUnsafe is an instanceof ReadableStream, we can't determine the size,\n // without consuming it, so we return undefined.\n // Never ever consume ReadableStream! DO NOT DO IT!!!\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n bodySafe = bodyUnsafe as unknown as ReadableStreamSafe;\n return;\n }\n return bodySize;\n}\n\nexport type JsonObject = {\n [key: string]: JsonValue;\n};\n\nexport type JsonValue = string | number | boolean | null | JsonObject | JsonArray;\n\nexport type JsonArray = Array<JsonValue>;\n\nexport interface IResponseWrapper {\n /**\n * Get the headers of the response.\n * @param allow - The headers to allow.\n * @returns The pruned headers\n */\n headers(allow?: string[]): Record<string, string> | undefined;\n bodySize?: number;\n status?: number;\n body?: string | Blob | ReadableStream | ArrayBuffer | FormDataSafe | URLSearchParams | ArrayBufferView | null;\n json: (allow?: string[], exclude?: string[]) => Promise<JsonObject | null>;\n}\n\n/**\n * This class encapsulates the Fetch API Response object\n * (https://developer.mozilla.org/en-US/docs/Web/API/Response) so that the consumer can\n * only get access to the headers and body size.\n *\n * This is to prevent consumers from directly accessing the Response object\n * and mutating it or running costly operations on it.\n *\n * IMPORTANT:\n * * Do not make changes to this class without careful consideration\n * of performance implications, memory usage and potential to mutate the customer's\n * response.\n * * Do not .clone() the Response object unless you need to access the body.\n * Cloning will 2x the memory overhead of the response.\n * * NEVER consume the body's stream. This will cause the response to be consumed\n * meaning the body will be empty when the customer tries to access it.\n * (ie: if the body is an instanceof https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream\n * never call any of the methods on it)\n */\nexport class ResponseWrapperFetch implements IResponseWrapper {\n private _bodySize: number | undefined;\n private clonedResponse?: ResponseCloneSafe;\n constructor(private response: ResponseSafe) {}\n\n headers(allow: string[] = []): Record<string, string> | undefined {\n if (this.response.headers instanceof Headers) {\n const headersSafe = this.response.headers as HeadersResponseSafe;\n const headersOut: Record<string, string> = {};\n /* istanbul ignore next */\n headersSafe?.forEach?.((value, key) => {\n headersOut[key] = value;\n });\n return pruneHeaders(headersOut, { allow });\n }\n\n return;\n }\n\n get bodySize(): number | undefined {\n if (this._bodySize !== undefined) return this._bodySize;\n /* istanbul ignore next */\n const contentLength = this.response.headers?.get?.('content-length');\n const bodySize = contentLength ? parseInt(contentLength, 10) : undefined;\n this._bodySize = bodySize;\n return bodySize;\n }\n\n get status(): number {\n return this.response.status;\n }\n\n async text(): Promise<string | null> {\n // !!!IMPORTANT: we clone the response to avoid mutating the original response\n // never call .text(), .json(), etc.. on the original response always clone it first\n if (!this.clonedResponse) {\n this.clonedResponse = this.response.clone();\n }\n try {\n const textPromise = this.clonedResponse.text();\n const timer = new Promise<null>((resolve) =>\n setTimeout(\n /* istanbul ignore next */\n () => resolve(null),\n TEXT_READ_TIMEOUT,\n ),\n );\n const text = await Promise.race<string | null>([textPromise, timer]);\n return text;\n } catch (error) {\n return null;\n }\n }\n\n async json(allow: string[] = [], exclude: string[] = []): Promise<JsonObject | null> {\n if (allow.length === 0) {\n return null;\n }\n const text = await this.text();\n return safeParseAndPruneBody(text, allow, exclude);\n }\n}\n\nexport class ResponseWrapperXhr implements IResponseWrapper {\n constructor(\n readonly statusCode: number,\n readonly headersString: string,\n readonly size: number | undefined,\n readonly getJson: () => any | null,\n ) {}\n\n get bodySize(): number | undefined {\n return this.size;\n }\n\n get status(): number {\n return this.statusCode;\n }\n\n headers(allow: string[] = []): Record<string, string> | undefined {\n if (!this.headersString) {\n return {};\n }\n const headers: Record<string, string> = {};\n const headerLines = this.headersString.split('\\r\\n');\n for (const line of headerLines) {\n const [key, value] = line.split(': ');\n if (key && value) {\n headers[key] = value;\n }\n }\n return pruneHeaders(headers, { allow });\n }\n\n async json(allow: string[] = [], exclude: string[] = []): Promise<JsonObject | null> {\n if (allow.length === 0) {\n return null;\n }\n const jsonBody = this.getJson() as JsonObject | null;\n if (jsonBody) {\n pruneJson(jsonBody, allow, exclude);\n return jsonBody;\n }\n return null;\n }\n}\n\nfunction safeParseAndPruneBody(text: string | null, allow: string[], exclude: string[]): JsonObject | null {\n if (!text) return null;\n try {\n const json = JSON.parse(text) as JsonObject;\n pruneJson(json, allow, exclude);\n return json;\n } catch (error) {\n return null;\n }\n}\n\nexport enum PRUNE_STRATEGY {\n REDACT = 'redact',\n REMOVE = 'remove',\n}\n\nconst REDACTED_VALUE = '[REDACTED]';\n\n/**\n * Prune headers from a headers record object.\n * @param headers - The headers to prune.\n * @param options - The options to prune the headers.\n * @param options.exclude - List of headers to delete from headers\n * @param options.include - List of headers to keep in headers, if not provided, all headers are kept by default\n * @returns The pruned headers.\n */\nexport const pruneHeaders = (\n headers: Record<string, string>,\n options: {\n allow?: string[];\n strategy?: PRUNE_STRATEGY;\n },\n): Record<string, string> => {\n const { allow = [], strategy = PRUNE_STRATEGY.REMOVE } = options;\n const exclude = [...FORBIDDEN_HEADERS];\n const headersPruned: Record<string, string> = {};\n\n for (const key of Object.keys(headers)) {\n const lowerKey = key.toLowerCase();\n\n if (exclude.find((e) => e.toLowerCase() === lowerKey)) {\n if (strategy === PRUNE_STRATEGY.REDACT) {\n headersPruned[key] = REDACTED_VALUE;\n }\n } else if (!allow.find((i) => i.toLowerCase() === lowerKey)) {\n if (strategy === PRUNE_STRATEGY.REDACT) {\n headersPruned[key] = REDACTED_VALUE;\n }\n } else {\n headersPruned[key] = headers[key];\n }\n }\n return headersPruned;\n};\nexport class NetworkRequestEvent {\n public requestHeaders?: Record<string, string>;\n public responseHeaders?: Record<string, string>;\n public requestBodyJson?: Promise<JsonObject | null>;\n public responseBodyJson?: Promise<JsonObject | null>;\n constructor(\n public readonly type: 'xhr' | 'fetch',\n public readonly method: string,\n public readonly timestamp: number,\n public readonly startTime: number,\n public readonly url?: string,\n public readonly requestWrapper?: IRequestWrapper,\n public readonly status: number = 0,\n public readonly duration?: number,\n public readonly responseWrapper?: IResponseWrapper,\n public readonly error?: {\n name: string;\n message: string;\n },\n public readonly endTime?: number,\n ) {}\n\n toSerializable(): Record<string, any> {\n const serialized: Record<string, any> = {\n type: this.type,\n method: this.method,\n url: this.url,\n timestamp: this.timestamp,\n status: this.status,\n duration: this.duration,\n error: this.error,\n startTime: this.startTime,\n endTime: this.endTime,\n requestHeaders: this.requestWrapper?.headers([...SAFE_HEADERS]),\n requestBodySize: this.requestWrapper?.bodySize,\n responseHeaders: this.responseWrapper?.headers([...SAFE_HEADERS]),\n responseBodySize: this.responseWrapper?.bodySize,\n };\n\n return Object.fromEntries(Object.entries(serialized).filter(([_, v]) => v !== undefined));\n }\n}\n"]}
|
|
@@ -19,6 +19,17 @@ export declare class NetworkObserver {
|
|
|
19
19
|
private handleNetworkRequestEvent;
|
|
20
20
|
private getTimestamps;
|
|
21
21
|
private observeFetch;
|
|
22
|
+
/**
|
|
23
|
+
* Creates a function that parses the response of an XMLHttpRequest as JSON.
|
|
24
|
+
*
|
|
25
|
+
* Returns function instead of JSON object to avoid unnecessary parsing if the
|
|
26
|
+
* body is not being captured.
|
|
27
|
+
*
|
|
28
|
+
* @param xhrSafe - The XMLHttpRequest object.
|
|
29
|
+
* @param context - The NetworkObserver instance.
|
|
30
|
+
* @returns A function that parses the response of an XMLHttpRequest as JSON.
|
|
31
|
+
*/
|
|
32
|
+
static createXhrJsonParser(xhrUnsafe: XMLHttpRequest, context: NetworkObserver): () => any;
|
|
22
33
|
private observeXhr;
|
|
23
34
|
}
|
|
24
35
|
export declare const networkObserver: NetworkObserver;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"network-observer.d.ts","sourceRoot":"","sources":["../../src/network-observer.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,OAAO,EAAE,MAAM,UAAU,CAAC;AACnC,OAAO,EAEL,mBAAmB,EAQpB,MAAM,yBAAyB,CAAC;AAoBjC,MAAM,MAAM,sBAAsB,GAAG,CAAC,KAAK,EAAE,mBAAmB,KAAK,IAAI,CAAC;AAE1E,qBAAa,oBAAoB;aACH,QAAQ,EAAE,CAAC,KAAK,EAAE,mBAAmB,KAAK,IAAI;aAAkB,EAAE,EAAE,MAAM;gBAA1E,QAAQ,EAAE,CAAC,KAAK,EAAE,mBAAmB,KAAK,IAAI,EAAkB,EAAE,GAAE,MAAe;CAChH;
|
|
1
|
+
{"version":3,"file":"network-observer.d.ts","sourceRoot":"","sources":["../../src/network-observer.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,OAAO,EAAE,MAAM,UAAU,CAAC;AACnC,OAAO,EAEL,mBAAmB,EAQpB,MAAM,yBAAyB,CAAC;AAoBjC,MAAM,MAAM,sBAAsB,GAAG,CAAC,KAAK,EAAE,mBAAmB,KAAK,IAAI,CAAC;AAE1E,qBAAa,oBAAoB;aACH,QAAQ,EAAE,CAAC,KAAK,EAAE,mBAAmB,KAAK,IAAI;aAAkB,EAAE,EAAE,MAAM;gBAA1E,QAAQ,EAAE,CAAC,KAAK,EAAE,mBAAmB,KAAK,IAAI,EAAkB,EAAE,GAAE,MAAe;CAChH;AAqBD,qBAAa,eAAe;IAC1B,OAAO,CAAC,cAAc,CAAgD;IAEtE,OAAO,CAAC,WAAW,CAAC,CAAoB;IACxC,OAAO,CAAC,MAAM,CAAC,CAAU;IACzB,OAAO,CAAC,WAAW,CAAS;gBAChB,MAAM,CAAC,EAAE,OAAO;IAU5B,MAAM,CAAC,WAAW,IAAI,OAAO;IAK7B,SAAS,CAAC,aAAa,EAAE,oBAAoB,EAAE,MAAM,CAAC,EAAE,OAAO;IA+B/D,WAAW,CAAC,aAAa,EAAE,oBAAoB;IAI/C,SAAS,CAAC,qBAAqB,CAAC,KAAK,EAAE,mBAAmB;IAa1D,OAAO,CAAC,yBAAyB;IA4DjC,OAAO,CAAC,aAAa;IAQrB,OAAO,CAAC,YAAY;IA8DpB;;;;;;;;;OASG;IACH,MAAM,CAAC,mBAAmB,CAAC,SAAS,EAAE,cAAc,EAAE,OAAO,EAAE,eAAe;IA8B9E,OAAO,CAAC,UAAU;CAqHnB;AAGD,eAAO,MAAM,eAAe,iBAAwB,CAAC"}
|
|
@@ -189,6 +189,46 @@ var NetworkObserver = /** @class */ (function () {
|
|
|
189
189
|
});
|
|
190
190
|
}); };
|
|
191
191
|
};
|
|
192
|
+
/**
|
|
193
|
+
* Creates a function that parses the response of an XMLHttpRequest as JSON.
|
|
194
|
+
*
|
|
195
|
+
* Returns function instead of JSON object to avoid unnecessary parsing if the
|
|
196
|
+
* body is not being captured.
|
|
197
|
+
*
|
|
198
|
+
* @param xhrSafe - The XMLHttpRequest object.
|
|
199
|
+
* @param context - The NetworkObserver instance.
|
|
200
|
+
* @returns A function that parses the response of an XMLHttpRequest as JSON.
|
|
201
|
+
*/
|
|
202
|
+
NetworkObserver.createXhrJsonParser = function (xhrUnsafe, context) {
|
|
203
|
+
return function () {
|
|
204
|
+
var _a, _b;
|
|
205
|
+
try {
|
|
206
|
+
if (xhrUnsafe.responseType === 'json') {
|
|
207
|
+
// if response is a JS object, clone it so that subscribers can't mutate it
|
|
208
|
+
if ((_a = context.globalScope) === null || _a === void 0 ? void 0 : _a.structuredClone) {
|
|
209
|
+
/* eslint-disable-next-line @typescript-eslint/no-unsafe-return */
|
|
210
|
+
return context.globalScope.structuredClone(xhrUnsafe.response);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
else if (['text', ''].includes(xhrUnsafe.responseType)) {
|
|
214
|
+
// if response is a string, parse it as JSON
|
|
215
|
+
/* eslint-disable-next-line @typescript-eslint/no-unsafe-return */
|
|
216
|
+
return JSON.parse(xhrUnsafe.responseText);
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
catch (err) {
|
|
220
|
+
/* istanbul ignore if */
|
|
221
|
+
if (err instanceof Error && err.name === 'InvalidStateError') {
|
|
222
|
+
// https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseText#exceptions
|
|
223
|
+
// if we reach here, it means we don't handle responseType correctly
|
|
224
|
+
(_b = context.logger) === null || _b === void 0 ? void 0 : _b.error("unexpected error when retrieving responseText. responseType='".concat(xhrUnsafe.responseType, "'"));
|
|
225
|
+
}
|
|
226
|
+
// the other possible error is Json Parse error which we fail silently
|
|
227
|
+
return null;
|
|
228
|
+
}
|
|
229
|
+
return null;
|
|
230
|
+
};
|
|
231
|
+
};
|
|
192
232
|
NetworkObserver.prototype.observeXhr = function (originalXhrOpen, originalXhrSend, originalXhrSetRequestHeader) {
|
|
193
233
|
/* istanbul ignore next */
|
|
194
234
|
if (!this.globalScope || !originalXhrOpen || !originalXhrSend) {
|
|
@@ -216,7 +256,7 @@ var NetworkObserver = /** @class */ (function () {
|
|
|
216
256
|
}
|
|
217
257
|
catch (err) {
|
|
218
258
|
/* istanbul ignore next */
|
|
219
|
-
(_b = networkObserverContext.logger) === null || _b === void 0 ? void 0 : _b.
|
|
259
|
+
(_b = networkObserverContext.logger) === null || _b === void 0 ? void 0 : _b.error('an unexpected error occurred while calling xhr open', err);
|
|
220
260
|
}
|
|
221
261
|
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
|
|
222
262
|
return originalXhrOpen.apply(xhrSafe, args);
|
|
@@ -235,7 +275,9 @@ var NetworkObserver = /** @class */ (function () {
|
|
|
235
275
|
args[_i] = arguments[_i];
|
|
236
276
|
}
|
|
237
277
|
// eslint-disable-next-line @typescript-eslint/no-this-alias
|
|
238
|
-
var
|
|
278
|
+
var xhrUnsafe = this;
|
|
279
|
+
var xhrSafe = xhrUnsafe;
|
|
280
|
+
var getJson = NetworkObserver.createXhrJsonParser(xhrUnsafe, networkObserverContext);
|
|
239
281
|
var body = args[0];
|
|
240
282
|
var requestEvent = xhrSafe.$$AmplitudeAnalyticsEvent;
|
|
241
283
|
xhrSafe.addEventListener('loadend', function () {
|
|
@@ -245,7 +287,7 @@ var NetworkObserver = /** @class */ (function () {
|
|
|
245
287
|
var responseBodySize = xhrSafe.getResponseHeader('content-length');
|
|
246
288
|
var responseWrapper = new ResponseWrapperXhr(xhrSafe.status, responseHeaders,
|
|
247
289
|
/* istanbul ignore next */
|
|
248
|
-
responseBodySize ? parseInt(responseBodySize, 10) : undefined,
|
|
290
|
+
responseBodySize ? parseInt(responseBodySize, 10) : undefined, getJson);
|
|
249
291
|
var requestHeaders = xhrSafe.$$AmplitudeAnalyticsEvent.headers;
|
|
250
292
|
var requestWrapper = new RequestWrapperXhr(body, requestHeaders);
|
|
251
293
|
requestEvent.status = xhrSafe.status;
|
|
@@ -253,7 +295,7 @@ var NetworkObserver = /** @class */ (function () {
|
|
|
253
295
|
}
|
|
254
296
|
catch (err) {
|
|
255
297
|
/* istanbul ignore next */
|
|
256
|
-
(_a = networkObserverContext.logger) === null || _a === void 0 ? void 0 : _a.
|
|
298
|
+
(_a = networkObserverContext.logger) === null || _a === void 0 ? void 0 : _a.error('an unexpected error occurred while handling xhr send', err);
|
|
257
299
|
}
|
|
258
300
|
});
|
|
259
301
|
/* eslint-disable-next-line @typescript-eslint/no-unsafe-argument */
|
|
@@ -276,7 +318,7 @@ var NetworkObserver = /** @class */ (function () {
|
|
|
276
318
|
}
|
|
277
319
|
catch (err) {
|
|
278
320
|
/* istanbul ignore next */
|
|
279
|
-
(_a = networkObserverContext.logger) === null || _a === void 0 ? void 0 : _a.
|
|
321
|
+
(_a = networkObserverContext.logger) === null || _a === void 0 ? void 0 : _a.error('an unexpected error occurred while calling xhr setRequestHeader', err);
|
|
280
322
|
}
|
|
281
323
|
/* eslint-disable-next-line @typescript-eslint/no-unsafe-argument */
|
|
282
324
|
originalXhrSetRequestHeader.apply(xhrSafe, [headerName, headerValue]);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"network-observer.js","sourceRoot":"","sources":["../../src/network-observer.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,IAAI,CAAC;AACpC,OAAO,EAAE,IAAI,EAAE,MAAM,cAAc,CAAC;AAEpC,OAAO,EAEL,mBAAmB,EACnB,mBAAmB,EACnB,oBAAoB,EACpB,iBAAiB,EACjB,kBAAkB,GAInB,MAAM,yBAAyB,CAAC;AAajC;;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;;AAoBD;IAME,yBAAY,MAAgB;QALpB,mBAAc,GAAsC,IAAI,GAAG,EAAE,CAAC;QAI9D,gBAAW,GAAG,KAAK,CAAC;QAE1B,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAM,WAAW,GAAG,c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,GAAG,EAAE;gBACZ,0BAA0B;gBAC1B,MAAA,sBAAsB,CAAC,MAAM,0CAAE,KAAK,CAAC,iEAAiE,EAAE,GAAG,CAAC,CAAC;aAC9G;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,AAzTD,IAyTC;;AAED,wCAAwC;AACxC,MAAM,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 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 /* 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 /* 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 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 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 xhrSafe.responseText,\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 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 * 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 /* eslint-disable-next-line @typescript-eslint/no-unsafe-assignment */\n xhrSafe.$$AmplitudeAnalyticsEvent.headers[headerName as string] = headerValue as string;\n } catch (err) {\n /* istanbul ignore next */\n networkObserverContext.logger?.debug('an unexpected error occurred while calling xhr setRequestHeader', err);\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-observer.js","sourceRoot":"","sources":["../../src/network-observer.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,IAAI,CAAC;AACpC,OAAO,EAAE,IAAI,EAAE,MAAM,cAAc,CAAC;AAEpC,OAAO,EAEL,mBAAmB,EACnB,mBAAmB,EACnB,oBAAoB,EACpB,iBAAiB,EACjB,kBAAkB,GAInB,MAAM,yBAAyB,CAAC;AAajC;;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,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yB,CAAC,OAAO,CAAC,UAAoB,CAAC,GAAG,WAAqB,CAAC;aACzF;YAAC,OAAO,GAAG,EAAE;gBACZ,0BAA0B;gBAC1B,MAAA,sBAAsB,CAAC,MAAM,0CAAE,KAAK,CAAC,iEAAiE,EAAE,GAAG,CAAC,CAAC;aAC9G;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,AApWD,IAoWC;;AAED,wCAAwC;AACxC,MAAM,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\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 /* 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 /**\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 context.logger?.error(\n `unexpected error when retrieving responseText. responseType='${xhrUnsafe.responseType}'`,\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 networkObserverContext.logger?.error('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 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 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 networkObserverContext.logger?.error('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 * 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 /* eslint-disable-next-line @typescript-eslint/no-unsafe-assignment */\n xhrSafe.$$AmplitudeAnalyticsEvent.headers[headerName as string] = headerValue as string;\n } catch (err) {\n /* istanbul ignore next */\n networkObserverContext.logger?.error('an unexpected error occurred while calling xhr setRequestHeader', err);\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"]}
|
|
@@ -104,7 +104,6 @@ export interface IResponseWrapper {
|
|
|
104
104
|
bodySize?: number;
|
|
105
105
|
status?: number;
|
|
106
106
|
body?: string | Blob | ReadableStream | ArrayBuffer | FormDataSafe | URLSearchParams | ArrayBufferView | null;
|
|
107
|
-
text: () => Promise<string | null>;
|
|
108
107
|
json: (allow?: string[], exclude?: string[]) => Promise<JsonObject | null>;
|
|
109
108
|
}
|
|
110
109
|
/**
|
|
@@ -141,11 +140,10 @@ export declare class ResponseWrapperXhr implements IResponseWrapper {
|
|
|
141
140
|
readonly statusCode: number;
|
|
142
141
|
readonly headersString: string;
|
|
143
142
|
readonly size: number | undefined;
|
|
144
|
-
readonly
|
|
145
|
-
constructor(statusCode: number, headersString: string, size: number | undefined,
|
|
143
|
+
readonly getJson: () => any | null;
|
|
144
|
+
constructor(statusCode: number, headersString: string, size: number | undefined, getJson: () => any | null);
|
|
146
145
|
get bodySize(): number | undefined;
|
|
147
146
|
get status(): number;
|
|
148
|
-
text(): Promise<string | null>;
|
|
149
147
|
headers(allow?: string[]): Record<string, string> | undefined;
|
|
150
148
|
json(allow?: string[], exclude?: string[]): Promise<JsonObject | null>;
|
|
151
149
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"network-request-event.d.ts","sour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AU,GAAG,IAAI,CAAC,CAAC;IAC7C,gBAAgB,CAAC,EAAE,OAAO,CAAC,UAAU,GAAG,IAAI,CAAC,CAAC;gBAEnC,IAAI,EAAE,KAAK,GAAG,OAAO,EACrB,MAAM,EAAE,MAAM,EACd,SAAS,EAAE,MAAM,EACjB,SAAS,EAAE,MAAM,EACjB,GAAG,CAAC,oBAAQ,EACZ,cAAc,CAAC,6BAAiB,EAChC,MAAM,GAAE,MAAU,EAClB,QAAQ,CAAC,oBAAQ,EACjB,eAAe,CAAC,8BAAkB,EAClC,KAAK,CAAC;cACd,MAAM;iBACH,MAAM;iBAChB,EACe,OAAO,CAAC,oBAAQ;IAGlC,cAAc,IAAI,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC;CAmBtC"}
|
|
@@ -343,11 +343,11 @@ var ResponseWrapperFetch = /** @class */ (function () {
|
|
|
343
343
|
}());
|
|
344
344
|
export { ResponseWrapperFetch };
|
|
345
345
|
var ResponseWrapperXhr = /** @class */ (function () {
|
|
346
|
-
function ResponseWrapperXhr(statusCode, headersString, size,
|
|
346
|
+
function ResponseWrapperXhr(statusCode, headersString, size, getJson) {
|
|
347
347
|
this.statusCode = statusCode;
|
|
348
348
|
this.headersString = headersString;
|
|
349
349
|
this.size = size;
|
|
350
|
-
this.
|
|
350
|
+
this.getJson = getJson;
|
|
351
351
|
}
|
|
352
352
|
Object.defineProperty(ResponseWrapperXhr.prototype, "bodySize", {
|
|
353
353
|
get: function () {
|
|
@@ -363,14 +363,6 @@ var ResponseWrapperXhr = /** @class */ (function () {
|
|
|
363
363
|
enumerable: false,
|
|
364
364
|
configurable: true
|
|
365
365
|
});
|
|
366
|
-
ResponseWrapperXhr.prototype.text = function () {
|
|
367
|
-
return __awaiter(this, void 0, void 0, function () {
|
|
368
|
-
return __generator(this, function (_a) {
|
|
369
|
-
// reject if body has already been consumed
|
|
370
|
-
return [2 /*return*/, this.responseText];
|
|
371
|
-
});
|
|
372
|
-
});
|
|
373
|
-
};
|
|
374
366
|
ResponseWrapperXhr.prototype.headers = function (allow) {
|
|
375
367
|
var e_3, _a;
|
|
376
368
|
if (allow === void 0) { allow = []; }
|
|
@@ -401,18 +393,17 @@ var ResponseWrapperXhr = /** @class */ (function () {
|
|
|
401
393
|
if (allow === void 0) { allow = []; }
|
|
402
394
|
if (exclude === void 0) { exclude = []; }
|
|
403
395
|
return __awaiter(this, void 0, void 0, function () {
|
|
404
|
-
var
|
|
396
|
+
var jsonBody;
|
|
405
397
|
return __generator(this, function (_a) {
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
text = _a.sent();
|
|
414
|
-
return [2 /*return*/, safeParseAndPruneBody(text, allow, exclude)];
|
|
398
|
+
if (allow.length === 0) {
|
|
399
|
+
return [2 /*return*/, null];
|
|
400
|
+
}
|
|
401
|
+
jsonBody = this.getJson();
|
|
402
|
+
if (jsonBody) {
|
|
403
|
+
pruneJson(jsonBody, allow, exclude);
|
|
404
|
+
return [2 /*return*/, jsonBody];
|
|
415
405
|
}
|
|
406
|
+
return [2 /*return*/, null];
|
|
416
407
|
});
|
|
417
408
|
});
|
|
418
409
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"network-request-event.js","sourceRoot":"","sources":["../../src/network-request-event.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAChD,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAC/C,OAAO,EAAE,YAAY,EAAE,iBAAiB,EAAE,MAAM,IAAI,CAAC;AA2DrD,IAAM,iBAAiB,GAAG,GAAG,CAAC;AAmC9B,MAAM,CAAC,IAAM,eAAe,GAAG,GAAG,CAAC;AAEnC;;;;;;;;;;;;;;;;;GAiBG;AACH;IAEE,6BAAoB,OAAwB;QAAxB,YAAO,GAAP,OAAO,CAAiB;IAAG,CAAC;IAEhD,qCAAO,GAA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OAAO,0BAAK,YAAY,UAAE;YAC/D,eAAe,EAAE,MAAA,IAAI,CAAC,cAAc,0CAAE,QAAQ;YAC9C,eAAe,EAAE,MAAA,IAAI,CAAC,eAAe,0CAAE,OAAO,0BAAK,YAAY,UAAE;YACjE,gBAAgB,EAAE,MAAA,IAAI,CAAC,eAAe,0CAAE,QAAQ;SACjD,CAAC;QAEF,OAAO,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC,MAAM,CAAC,UAAC,EAAM;gBAAN,KAAA,aAAM,EAAL,CAAC,QAAA,EAAE,CAAC,QAAA;YAAM,OAAA,CAAC,KAAK,SAAS;QAAf,CAAe,CAAC,CAAC,CAAC;IAC5F,CAAC;IACH,0BAAC;AAAD,CAAC,AAzCD,IAyCC","sourcesContent":["import { getGlobalScope } from './global-scope';\nimport { pruneJson } from './utils/json-query';\nimport { SAFE_HEADERS, FORBIDDEN_HEADERS } from './';\n\n/* SAFE TYPE DEFINITIONS\n These type definitions expose limited properties of the original types\n to prevent the consumer from mutating them or consuming them.\n*/\ntype BlobSafe = {\n size: number;\n};\n\ntype ArrayBufferSafe = {\n byteLength: number;\n};\n\ntype ArrayBufferViewSafe = {\n byteLength: number;\n};\n\ntype URLSearchParamsSafe = {\n toString(): string;\n};\n\n// no method on readablestream is safe to call\ntype ReadableStreamSafe = Record<string, never>;\n\ntype FormDataEntryValueSafe = string | BlobSafe | null;\n\ntype BodyInitSafe =\n | string\n | Blob\n | ArrayBufferSafe\n | FormDataSafe\n | URLSearchParamsSafe\n | ArrayBufferViewSafe\n | null\n | undefined;\n\ntype HeadersRequestSafe = {\n entries(): IterableIterator<[string, string]>;\n forEach(callbackfn: (value: string, key: string) => void): void;\n};\n\ntype HeadersResponseSafe = {\n get(name: string): string | null;\n forEach(callbackfn: (value: string, key: string) => void): void;\n};\n\ntype HeadersInitSafe = HeadersRequestSafe | Record<string, string> | string[][];\n\ntype ResponseSafe = {\n status: number;\n headers: HeadersResponseSafe | undefined;\n clone(): ResponseCloneSafe;\n};\n\ntype ResponseCloneSafe = {\n text(): Promise<string>;\n};\n\nconst TEXT_READ_TIMEOUT = 500;\n\nexport type RequestInitSafe = {\n method?: string;\n headers?: HeadersInitSafe;\n body?: BodyInitSafe;\n};\nexport interface FormDataSafe {\n entries(): IterableIterator<[string, FormDataEntryValueSafe]>;\n}\nexport type XMLHttpRequestBodyInitSafe = BlobSafe | FormDataSafe | URLSearchParamsSafe | string;\n\nexport type FetchRequestBody =\n | string\n | BlobSafe\n | ArrayBufferSafe\n | FormDataSafe\n | URLSearchParamsSafe\n | ArrayBufferViewSafe\n | null\n | undefined;\n\nexport interface IRequestWrapper {\n /**\n * Get the headers of the request.\n * @param allow - The headers to allow.\n * @returns The pruned headers\n */\n headers(allow?: string[]): Record<string, string> | undefined;\n bodySize?: number;\n method?: string;\n body?: FetchRequestBody | XMLHttpRequestBodyInitSafe | null;\n json: (allow?: string[], exclude?: string[]) => Promise<JsonObject | null>;\n}\n\nexport const MAXIMUM_ENTRIES = 100;\n\n/**\n * This class encapsulates the RequestInit (https://developer.mozilla.org/en-US/docs/Web/API/RequestInit)\n * object so that the consumer can only get access to the headers, method and body size.\n *\n * This is to prevent consumers from directly accessing the Request object\n * and mutating it or running costly operations on it.\n *\n * IMPORTANT:\n * * Do not make changes to this class without careful consideration\n * of performance implications, memory usage and potential to mutate the customer's\n * request.\n * * NEVER .clone() the RequestInit object. This will 2x's the memory overhead of the request\n * * NEVER: call .arrayBuffer(), text(), json() or any other method on the body that\n * consumes the body's stream. This will cause the response to be consumed\n * meaning the body will be empty when the customer tries to access it.\n * (ie: if the body is an instanceof https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream\n * never call any of the methods on it)\n */\nexport class RequestWrapperFetch implements IRequestWrapper {\n private _bodySize: number | undefined;\n constructor(private request: RequestInitSafe) {}\n\n headers(allow: string[] = []): Record<string, string> | undefined {\n const headersUnsafe = this.request.headers;\n\n // copy the headers into a new object\n const headersSafeCopy: Record<string, string> = {};\n if (Array.isArray(headersUnsafe)) {\n headersUnsafe.forEach(([headerName, headerValue]) => {\n headersSafeCopy[headerName] = headerValue;\n });\n } else if (headersUnsafe instanceof Headers) {\n headersUnsafe.forEach((value: string, key: string) => {\n headersSafeCopy[key] = value;\n });\n } else if (typeof headersUnsafe === 'object' && headersUnsafe !== null) {\n for (const [key, value] of Object.entries(headersUnsafe as Record<string, string>)) {\n headersSafeCopy[key] = value;\n }\n }\n\n return pruneHeaders(headersSafeCopy, { allow });\n }\n\n get bodySize(): number | undefined {\n if (typeof this._bodySize === 'number') return this._bodySize;\n const global = getGlobalScope();\n\n /* istanbul ignore if */\n if (!global?.TextEncoder) {\n return;\n }\n const body = this.request.body as FetchRequestBody;\n this._bodySize = getBodySize(body, MAXIMUM_ENTRIES);\n return this._bodySize;\n }\n\n get method(): string | undefined {\n return this.request.method;\n }\n\n get body(): string | null {\n if (typeof this.request.body === 'string') {\n return this.request.body;\n }\n return null;\n }\n\n async json(allow: string[] = [], exclude: string[] = []): Promise<JsonObject | null> {\n if (allow.length === 0) {\n return null;\n }\n const text = this.body;\n return safeParseAndPruneBody(text, allow, exclude);\n }\n}\n\nexport class RequestWrapperXhr implements IRequestWrapper {\n constructor(readonly bodyRaw: XMLHttpRequestBodyInitSafe | null, readonly requestHeaders: Record<string, string>) {}\n\n headers(allow: string[] = []): Record<string, string> | undefined {\n return pruneHeaders(this.requestHeaders, { allow });\n }\n\n get bodySize(): number | undefined {\n return getBodySize(this.bodyRaw as FetchRequestBody, MAXIMUM_ENTRIES);\n }\n\n get body(): string | null {\n if (typeof this.bodyRaw === 'string') {\n return this.bodyRaw;\n }\n return null;\n }\n\n async json(allow: string[] = [], exclude: string[] = []): Promise<JsonObject | null> {\n if (allow.length === 0) {\n return null;\n }\n const text = this.body;\n return safeParseAndPruneBody(text, allow, exclude);\n }\n}\n\nfunction getBodySize(bodyUnsafe: FetchRequestBody, maxEntries: number): number | undefined {\n let bodySize: number | undefined;\n const global = getGlobalScope();\n /* istanbul ignore next */\n const TextEncoder = global?.TextEncoder;\n /* istanbul ignore next */\n if (!TextEncoder) {\n return;\n }\n let bodySafe;\n if (typeof bodyUnsafe === 'string') {\n bodySafe = bodyUnsafe;\n bodySize = new TextEncoder().encode(bodySafe).length;\n } else if (bodyUnsafe instanceof Blob) {\n bodySafe = bodyUnsafe as BlobSafe;\n bodySize = bodySafe.size;\n } else if (bodyUnsafe instanceof URLSearchParams) {\n bodySafe = bodyUnsafe as URLSearchParamsSafe;\n bodySize = new TextEncoder().encode(bodySafe.toString()).length;\n } else if (ArrayBuffer.isView(bodyUnsafe)) {\n bodySafe = bodyUnsafe as ArrayBufferViewSafe;\n bodySize = bodySafe.byteLength;\n } else if (bodyUnsafe instanceof ArrayBuffer) {\n bodySafe = bodyUnsafe as ArrayBufferSafe;\n bodySize = bodySafe.byteLength;\n } else if (bodyUnsafe instanceof FormData) {\n // Estimating only for text parts; not accurate for files\n const formData = bodyUnsafe as unknown as FormDataSafe;\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 instanceof Blob) {\n total += value.size;\n } else {\n // encountered an unknown type\n // we can't estimate the size of this entry\n return;\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 >= maxEntries) {\n return;\n }\n }\n bodySize = total;\n } else if (bodyUnsafe instanceof ReadableStream) {\n // If bodyUnsafe is an instanceof ReadableStream, we can't determine the size,\n // without consuming it, so we return undefined.\n // Never ever consume ReadableStream! DO NOT DO IT!!!\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n bodySafe = bodyUnsafe as unknown as ReadableStreamSafe;\n return;\n }\n return bodySize;\n}\n\nexport type JsonObject = {\n [key: string]: JsonValue;\n};\n\nexport type JsonValue = string | number | boolean | null | JsonObject | JsonArray;\n\nexport type JsonArray = Array<JsonValue>;\n\nexport interface IResponseWrapper {\n /**\n * Get the headers of the response.\n * @param allow - The headers to allow.\n * @returns The pruned headers\n */\n headers(allow?: string[]): Record<string, string> | undefined;\n bodySize?: number;\n status?: number;\n body?: string | Blob | ReadableStream | ArrayBuffer | FormDataSafe | URLSearchParams | ArrayBufferView | null;\n text: () => Promise<string | null>;\n json: (allow?: string[], exclude?: string[]) => Promise<JsonObject | null>;\n}\n\n/**\n * This class encapsulates the Fetch API Response object\n * (https://developer.mozilla.org/en-US/docs/Web/API/Response) so that the consumer can\n * only get access to the headers and body size.\n *\n * This is to prevent consumers from directly accessing the Response object\n * and mutating it or running costly operations on it.\n *\n * IMPORTANT:\n * * Do not make changes to this class without careful consideration\n * of performance implications, memory usage and potential to mutate the customer's\n * response.\n * * Do not .clone() the Response object unless you need to access the body.\n * Cloning will 2x the memory overhead of the response.\n * * NEVER consume the body's stream. This will cause the response to be consumed\n * meaning the body will be empty when the customer tries to access it.\n * (ie: if the body is an instanceof https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream\n * never call any of the methods on it)\n */\nexport class ResponseWrapperFetch implements IResponseWrapper {\n private _bodySize: number | undefined;\n private clonedResponse?: ResponseCloneSafe;\n constructor(private response: ResponseSafe) {}\n\n headers(allow: string[] = []): Record<string, string> | undefined {\n if (this.response.headers instanceof Headers) {\n const headersSafe = this.response.headers as HeadersResponseSafe;\n const headersOut: Record<string, string> = {};\n /* istanbul ignore next */\n headersSafe?.forEach?.((value, key) => {\n headersOut[key] = value;\n });\n return pruneHeaders(headersOut, { allow });\n }\n\n return;\n }\n\n get bodySize(): number | undefined {\n if (this._bodySize !== undefined) return this._bodySize;\n /* istanbul ignore next */\n const contentLength = this.response.headers?.get?.('content-length');\n const bodySize = contentLength ? parseInt(contentLength, 10) : undefined;\n this._bodySize = bodySize;\n return bodySize;\n }\n\n get status(): number {\n return this.response.status;\n }\n\n async text(): Promise<string | null> {\n // !!!IMPORTANT: we clone the response to avoid mutating the original response\n // never call .text(), .json(), etc.. on the original response always clone it first\n if (!this.clonedResponse) {\n this.clonedResponse = this.response.clone();\n }\n try {\n const textPromise = this.clonedResponse.text();\n const timer = new Promise<null>((resolve) =>\n setTimeout(\n /* istanbul ignore next */\n () => resolve(null),\n TEXT_READ_TIMEOUT,\n ),\n );\n const text = await Promise.race<string | null>([textPromise, timer]);\n return text;\n } catch (error) {\n return null;\n }\n }\n\n async json(allow: string[] = [], exclude: string[] = []): Promise<JsonObject | null> {\n if (allow.length === 0) {\n return null;\n }\n const text = await this.text();\n return safeParseAndPruneBody(text, allow, exclude);\n }\n}\n\nexport class ResponseWrapperXhr implements IResponseWrapper {\n constructor(\n readonly statusCode: number,\n readonly headersString: string,\n readonly size: number | undefined,\n readonly responseText: string,\n ) {}\n\n get bodySize(): number | undefined {\n return this.size;\n }\n\n get status(): number {\n return this.statusCode;\n }\n\n async text(): Promise<string | null> {\n // reject if body has already been consumed\n return this.responseText;\n }\n\n headers(allow: string[] = []): Record<string, string> | undefined {\n if (!this.headersString) {\n return {};\n }\n const headers: Record<string, string> = {};\n const headerLines = this.headersString.split('\\r\\n');\n for (const line of headerLines) {\n const [key, value] = line.split(': ');\n if (key && value) {\n headers[key] = value;\n }\n }\n return pruneHeaders(headers, { allow });\n }\n\n async json(allow: string[] = [], exclude: string[] = []): Promise<JsonObject | null> {\n if (allow.length === 0) {\n return null;\n }\n const text = await this.text();\n return safeParseAndPruneBody(text, allow, exclude);\n }\n}\n\nfunction safeParseAndPruneBody(text: string | null, allow: string[], exclude: string[]): JsonObject | null {\n if (!text) return null;\n try {\n const json = JSON.parse(text) as JsonObject;\n pruneJson(json, allow, exclude);\n return json;\n } catch (error) {\n return null;\n }\n}\n\nexport enum PRUNE_STRATEGY {\n REDACT = 'redact',\n REMOVE = 'remove',\n}\n\nconst REDACTED_VALUE = '[REDACTED]';\n\n/**\n * Prune headers from a headers record object.\n * @param headers - The headers to prune.\n * @param options - The options to prune the headers.\n * @param options.exclude - List of headers to delete from headers\n * @param options.include - List of headers to keep in headers, if not provided, all headers are kept by default\n * @returns The pruned headers.\n */\nexport const pruneHeaders = (\n headers: Record<string, string>,\n options: {\n allow?: string[];\n strategy?: PRUNE_STRATEGY;\n },\n): Record<string, string> => {\n const { allow = [], strategy = PRUNE_STRATEGY.REMOVE } = options;\n const exclude = [...FORBIDDEN_HEADERS];\n const headersPruned: Record<string, string> = {};\n\n for (const key of Object.keys(headers)) {\n const lowerKey = key.toLowerCase();\n\n if (exclude.find((e) => e.toLowerCase() === lowerKey)) {\n if (strategy === PRUNE_STRATEGY.REDACT) {\n headersPruned[key] = REDACTED_VALUE;\n }\n } else if (!allow.find((i) => i.toLowerCase() === lowerKey)) {\n if (strategy === PRUNE_STRATEGY.REDACT) {\n headersPruned[key] = REDACTED_VALUE;\n }\n } else {\n headersPruned[key] = headers[key];\n }\n }\n return headersPruned;\n};\nexport class NetworkRequestEvent {\n public requestHeaders?: Record<string, string>;\n public responseHeaders?: Record<string, string>;\n public requestBodyJson?: Promise<JsonObject | null>;\n public responseBodyJson?: Promise<JsonObject | null>;\n constructor(\n public readonly type: 'xhr' | 'fetch',\n public readonly method: string,\n public readonly timestamp: number,\n public readonly startTime: number,\n public readonly url?: string,\n public readonly requestWrapper?: IRequestWrapper,\n public readonly status: number = 0,\n public readonly duration?: number,\n public readonly responseWrapper?: IResponseWrapper,\n public readonly error?: {\n name: string;\n message: string;\n },\n public readonly endTime?: number,\n ) {}\n\n toSerializable(): Record<string, any> {\n const serialized: Record<string, any> = {\n type: this.type,\n method: this.method,\n url: this.url,\n timestamp: this.timestamp,\n status: this.status,\n duration: this.duration,\n error: this.error,\n startTime: this.startTime,\n endTime: this.endTime,\n requestHeaders: this.requestWrapper?.headers([...SAFE_HEADERS]),\n requestBodySize: this.requestWrapper?.bodySize,\n responseHeaders: this.responseWrapper?.headers([...SAFE_HEADERS]),\n responseBodySize: this.responseWrapper?.bodySize,\n };\n\n return Object.fromEntries(Object.entries(serialized).filter(([_, v]) => v !== undefined));\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"network-request-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AM,UAAU,GAAwB;YACtC,IAAI,EAAE,IAAI,CAAC,IAAI;YACf,MAAM,EAAE,IAAI,CAAC,MAAM;YACnB,GAAG,EAAE,IAAI,CAAC,GAAG;YACb,SAAS,EAAE,IAAI,CAAC,SAAS;YACzB,MAAM,EAAE,IAAI,CAAC,MAAM;YACnB,QAAQ,EAAE,IAAI,CAAC,QAAQ;YACvB,KAAK,EAAE,IAAI,CAAC,KAAK;YACjB,SAAS,EAAE,IAAI,CAAC,SAAS;YACzB,OAAO,EAAE,IAAI,CAAC,OAAO;YACrB,cAAc,EAAE,MAAA,IAAI,CAAC,cAAc,0CAAE,OAAO,0BAAK,YAAY,UAAE;YAC/D,eAAe,EAAE,MAAA,IAAI,CAAC,cAAc,0CAAE,QAAQ;YAC9C,eAAe,EAAE,MAAA,IAAI,CAAC,eAAe,0CAAE,OAAO,0BAAK,YAAY,UAAE;YACjE,gBAAgB,EAAE,MAAA,IAAI,CAAC,eAAe,0CAAE,QAAQ;SACjD,CAAC;QAEF,OAAO,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC,MAAM,CAAC,UAAC,EAAM;gBAAN,KAAA,aAAM,EAAL,CAAC,QAAA,EAAE,CAAC,QAAA;YAAM,OAAA,CAAC,KAAK,SAAS;QAAf,CAAe,CAAC,CAAC,CAAC;IAC5F,CAAC;IACH,0BAAC;AAAD,CAAC,AAzCD,IAyCC","sourcesContent":["import { getGlobalScope } from './global-scope';\nimport { pruneJson } from './utils/json-query';\nimport { SAFE_HEADERS, FORBIDDEN_HEADERS } from './';\n\n/* SAFE TYPE DEFINITIONS\n These type definitions expose limited properties of the original types\n to prevent the consumer from mutating them or consuming them.\n*/\ntype BlobSafe = {\n size: number;\n};\n\ntype ArrayBufferSafe = {\n byteLength: number;\n};\n\ntype ArrayBufferViewSafe = {\n byteLength: number;\n};\n\ntype URLSearchParamsSafe = {\n toString(): string;\n};\n\n// no method on readablestream is safe to call\ntype ReadableStreamSafe = Record<string, never>;\n\ntype FormDataEntryValueSafe = string | BlobSafe | null;\n\ntype BodyInitSafe =\n | string\n | Blob\n | ArrayBufferSafe\n | FormDataSafe\n | URLSearchParamsSafe\n | ArrayBufferViewSafe\n | null\n | undefined;\n\ntype HeadersRequestSafe = {\n entries(): IterableIterator<[string, string]>;\n forEach(callbackfn: (value: string, key: string) => void): void;\n};\n\ntype HeadersResponseSafe = {\n get(name: string): string | null;\n forEach(callbackfn: (value: string, key: string) => void): void;\n};\n\ntype HeadersInitSafe = HeadersRequestSafe | Record<string, string> | string[][];\n\ntype ResponseSafe = {\n status: number;\n headers: HeadersResponseSafe | undefined;\n clone(): ResponseCloneSafe;\n};\n\ntype ResponseCloneSafe = {\n text(): Promise<string>;\n};\n\nconst TEXT_READ_TIMEOUT = 500;\n\nexport type RequestInitSafe = {\n method?: string;\n headers?: HeadersInitSafe;\n body?: BodyInitSafe;\n};\nexport interface FormDataSafe {\n entries(): IterableIterator<[string, FormDataEntryValueSafe]>;\n}\nexport type XMLHttpRequestBodyInitSafe = BlobSafe | FormDataSafe | URLSearchParamsSafe | string;\n\nexport type FetchRequestBody =\n | string\n | BlobSafe\n | ArrayBufferSafe\n | FormDataSafe\n | URLSearchParamsSafe\n | ArrayBufferViewSafe\n | null\n | undefined;\n\nexport interface IRequestWrapper {\n /**\n * Get the headers of the request.\n * @param allow - The headers to allow.\n * @returns The pruned headers\n */\n headers(allow?: string[]): Record<string, string> | undefined;\n bodySize?: number;\n method?: string;\n body?: FetchRequestBody | XMLHttpRequestBodyInitSafe | null;\n json: (allow?: string[], exclude?: string[]) => Promise<JsonObject | null>;\n}\n\nexport const MAXIMUM_ENTRIES = 100;\n\n/**\n * This class encapsulates the RequestInit (https://developer.mozilla.org/en-US/docs/Web/API/RequestInit)\n * object so that the consumer can only get access to the headers, method and body size.\n *\n * This is to prevent consumers from directly accessing the Request object\n * and mutating it or running costly operations on it.\n *\n * IMPORTANT:\n * * Do not make changes to this class without careful consideration\n * of performance implications, memory usage and potential to mutate the customer's\n * request.\n * * NEVER .clone() the RequestInit object. This will 2x's the memory overhead of the request\n * * NEVER: call .arrayBuffer(), text(), json() or any other method on the body that\n * consumes the body's stream. This will cause the response to be consumed\n * meaning the body will be empty when the customer tries to access it.\n * (ie: if the body is an instanceof https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream\n * never call any of the methods on it)\n */\nexport class RequestWrapperFetch implements IRequestWrapper {\n private _bodySize: number | undefined;\n constructor(private request: RequestInitSafe) {}\n\n headers(allow: string[] = []): Record<string, string> | undefined {\n const headersUnsafe = this.request.headers;\n\n // copy the headers into a new object\n const headersSafeCopy: Record<string, string> = {};\n if (Array.isArray(headersUnsafe)) {\n headersUnsafe.forEach(([headerName, headerValue]) => {\n headersSafeCopy[headerName] = headerValue;\n });\n } else if (headersUnsafe instanceof Headers) {\n headersUnsafe.forEach((value: string, key: string) => {\n headersSafeCopy[key] = value;\n });\n } else if (typeof headersUnsafe === 'object' && headersUnsafe !== null) {\n for (const [key, value] of Object.entries(headersUnsafe as Record<string, string>)) {\n headersSafeCopy[key] = value;\n }\n }\n\n return pruneHeaders(headersSafeCopy, { allow });\n }\n\n get bodySize(): number | undefined {\n if (typeof this._bodySize === 'number') return this._bodySize;\n const global = getGlobalScope();\n\n /* istanbul ignore if */\n if (!global?.TextEncoder) {\n return;\n }\n const body = this.request.body as FetchRequestBody;\n this._bodySize = getBodySize(body, MAXIMUM_ENTRIES);\n return this._bodySize;\n }\n\n get method(): string | undefined {\n return this.request.method;\n }\n\n get body(): string | null {\n if (typeof this.request.body === 'string') {\n return this.request.body;\n }\n return null;\n }\n\n async json(allow: string[] = [], exclude: string[] = []): Promise<JsonObject | null> {\n if (allow.length === 0) {\n return null;\n }\n const text = this.body;\n return safeParseAndPruneBody(text, allow, exclude);\n }\n}\n\nexport class RequestWrapperXhr implements IRequestWrapper {\n constructor(readonly bodyRaw: XMLHttpRequestBodyInitSafe | null, readonly requestHeaders: Record<string, string>) {}\n\n headers(allow: string[] = []): Record<string, string> | undefined {\n return pruneHeaders(this.requestHeaders, { allow });\n }\n\n get bodySize(): number | undefined {\n return getBodySize(this.bodyRaw as FetchRequestBody, MAXIMUM_ENTRIES);\n }\n\n get body(): string | null {\n if (typeof this.bodyRaw === 'string') {\n return this.bodyRaw;\n }\n return null;\n }\n\n async json(allow: string[] = [], exclude: string[] = []): Promise<JsonObject | null> {\n if (allow.length === 0) {\n return null;\n }\n const text = this.body;\n return safeParseAndPruneBody(text, allow, exclude);\n }\n}\n\nfunction getBodySize(bodyUnsafe: FetchRequestBody, maxEntries: number): number | undefined {\n let bodySize: number | undefined;\n const global = getGlobalScope();\n /* istanbul ignore next */\n const TextEncoder = global?.TextEncoder;\n /* istanbul ignore next */\n if (!TextEncoder) {\n return;\n }\n let bodySafe;\n if (typeof bodyUnsafe === 'string') {\n bodySafe = bodyUnsafe;\n bodySize = new TextEncoder().encode(bodySafe).length;\n } else if (bodyUnsafe instanceof Blob) {\n bodySafe = bodyUnsafe as BlobSafe;\n bodySize = bodySafe.size;\n } else if (bodyUnsafe instanceof URLSearchParams) {\n bodySafe = bodyUnsafe as URLSearchParamsSafe;\n bodySize = new TextEncoder().encode(bodySafe.toString()).length;\n } else if (ArrayBuffer.isView(bodyUnsafe)) {\n bodySafe = bodyUnsafe as ArrayBufferViewSafe;\n bodySize = bodySafe.byteLength;\n } else if (bodyUnsafe instanceof ArrayBuffer) {\n bodySafe = bodyUnsafe as ArrayBufferSafe;\n bodySize = bodySafe.byteLength;\n } else if (bodyUnsafe instanceof FormData) {\n // Estimating only for text parts; not accurate for files\n const formData = bodyUnsafe as unknown as FormDataSafe;\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 instanceof Blob) {\n total += value.size;\n } else {\n // encountered an unknown type\n // we can't estimate the size of this entry\n return;\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 >= maxEntries) {\n return;\n }\n }\n bodySize = total;\n } else if (bodyUnsafe instanceof ReadableStream) {\n // If bodyUnsafe is an instanceof ReadableStream, we can't determine the size,\n // without consuming it, so we return undefined.\n // Never ever consume ReadableStream! DO NOT DO IT!!!\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n bodySafe = bodyUnsafe as unknown as ReadableStreamSafe;\n return;\n }\n return bodySize;\n}\n\nexport type JsonObject = {\n [key: string]: JsonValue;\n};\n\nexport type JsonValue = string | number | boolean | null | JsonObject | JsonArray;\n\nexport type JsonArray = Array<JsonValue>;\n\nexport interface IResponseWrapper {\n /**\n * Get the headers of the response.\n * @param allow - The headers to allow.\n * @returns The pruned headers\n */\n headers(allow?: string[]): Record<string, string> | undefined;\n bodySize?: number;\n status?: number;\n body?: string | Blob | ReadableStream | ArrayBuffer | FormDataSafe | URLSearchParams | ArrayBufferView | null;\n json: (allow?: string[], exclude?: string[]) => Promise<JsonObject | null>;\n}\n\n/**\n * This class encapsulates the Fetch API Response object\n * (https://developer.mozilla.org/en-US/docs/Web/API/Response) so that the consumer can\n * only get access to the headers and body size.\n *\n * This is to prevent consumers from directly accessing the Response object\n * and mutating it or running costly operations on it.\n *\n * IMPORTANT:\n * * Do not make changes to this class without careful consideration\n * of performance implications, memory usage and potential to mutate the customer's\n * response.\n * * Do not .clone() the Response object unless you need to access the body.\n * Cloning will 2x the memory overhead of the response.\n * * NEVER consume the body's stream. This will cause the response to be consumed\n * meaning the body will be empty when the customer tries to access it.\n * (ie: if the body is an instanceof https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream\n * never call any of the methods on it)\n */\nexport class ResponseWrapperFetch implements IResponseWrapper {\n private _bodySize: number | undefined;\n private clonedResponse?: ResponseCloneSafe;\n constructor(private response: ResponseSafe) {}\n\n headers(allow: string[] = []): Record<string, string> | undefined {\n if (this.response.headers instanceof Headers) {\n const headersSafe = this.response.headers as HeadersResponseSafe;\n const headersOut: Record<string, string> = {};\n /* istanbul ignore next */\n headersSafe?.forEach?.((value, key) => {\n headersOut[key] = value;\n });\n return pruneHeaders(headersOut, { allow });\n }\n\n return;\n }\n\n get bodySize(): number | undefined {\n if (this._bodySize !== undefined) return this._bodySize;\n /* istanbul ignore next */\n const contentLength = this.response.headers?.get?.('content-length');\n const bodySize = contentLength ? parseInt(contentLength, 10) : undefined;\n this._bodySize = bodySize;\n return bodySize;\n }\n\n get status(): number {\n return this.response.status;\n }\n\n async text(): Promise<string | null> {\n // !!!IMPORTANT: we clone the response to avoid mutating the original response\n // never call .text(), .json(), etc.. on the original response always clone it first\n if (!this.clonedResponse) {\n this.clonedResponse = this.response.clone();\n }\n try {\n const textPromise = this.clonedResponse.text();\n const timer = new Promise<null>((resolve) =>\n setTimeout(\n /* istanbul ignore next */\n () => resolve(null),\n TEXT_READ_TIMEOUT,\n ),\n );\n const text = await Promise.race<string | null>([textPromise, timer]);\n return text;\n } catch (error) {\n return null;\n }\n }\n\n async json(allow: string[] = [], exclude: string[] = []): Promise<JsonObject | null> {\n if (allow.length === 0) {\n return null;\n }\n const text = await this.text();\n return safeParseAndPruneBody(text, allow, exclude);\n }\n}\n\nexport class ResponseWrapperXhr implements IResponseWrapper {\n constructor(\n readonly statusCode: number,\n readonly headersString: string,\n readonly size: number | undefined,\n readonly getJson: () => any | null,\n ) {}\n\n get bodySize(): number | undefined {\n return this.size;\n }\n\n get status(): number {\n return this.statusCode;\n }\n\n headers(allow: string[] = []): Record<string, string> | undefined {\n if (!this.headersString) {\n return {};\n }\n const headers: Record<string, string> = {};\n const headerLines = this.headersString.split('\\r\\n');\n for (const line of headerLines) {\n const [key, value] = line.split(': ');\n if (key && value) {\n headers[key] = value;\n }\n }\n return pruneHeaders(headers, { allow });\n }\n\n async json(allow: string[] = [], exclude: string[] = []): Promise<JsonObject | null> {\n if (allow.length === 0) {\n return null;\n }\n const jsonBody = this.getJson() as JsonObject | null;\n if (jsonBody) {\n pruneJson(jsonBody, allow, exclude);\n return jsonBody;\n }\n return null;\n }\n}\n\nfunction safeParseAndPruneBody(text: string | null, allow: string[], exclude: string[]): JsonObject | null {\n if (!text) return null;\n try {\n const json = JSON.parse(text) as JsonObject;\n pruneJson(json, allow, exclude);\n return json;\n } catch (error) {\n return null;\n }\n}\n\nexport enum PRUNE_STRATEGY {\n REDACT = 'redact',\n REMOVE = 'remove',\n}\n\nconst REDACTED_VALUE = '[REDACTED]';\n\n/**\n * Prune headers from a headers record object.\n * @param headers - The headers to prune.\n * @param options - The options to prune the headers.\n * @param options.exclude - List of headers to delete from headers\n * @param options.include - List of headers to keep in headers, if not provided, all headers are kept by default\n * @returns The pruned headers.\n */\nexport const pruneHeaders = (\n headers: Record<string, string>,\n options: {\n allow?: string[];\n strategy?: PRUNE_STRATEGY;\n },\n): Record<string, string> => {\n const { allow = [], strategy = PRUNE_STRATEGY.REMOVE } = options;\n const exclude = [...FORBIDDEN_HEADERS];\n const headersPruned: Record<string, string> = {};\n\n for (const key of Object.keys(headers)) {\n const lowerKey = key.toLowerCase();\n\n if (exclude.find((e) => e.toLowerCase() === lowerKey)) {\n if (strategy === PRUNE_STRATEGY.REDACT) {\n headersPruned[key] = REDACTED_VALUE;\n }\n } else if (!allow.find((i) => i.toLowerCase() === lowerKey)) {\n if (strategy === PRUNE_STRATEGY.REDACT) {\n headersPruned[key] = REDACTED_VALUE;\n }\n } else {\n headersPruned[key] = headers[key];\n }\n }\n return headersPruned;\n};\nexport class NetworkRequestEvent {\n public requestHeaders?: Record<string, string>;\n public responseHeaders?: Record<string, string>;\n public requestBodyJson?: Promise<JsonObject | null>;\n public responseBodyJson?: Promise<JsonObject | null>;\n constructor(\n public readonly type: 'xhr' | 'fetch',\n public readonly method: string,\n public readonly timestamp: number,\n public readonly startTime: number,\n public readonly url?: string,\n public readonly requestWrapper?: IRequestWrapper,\n public readonly status: number = 0,\n public readonly duration?: number,\n public readonly responseWrapper?: IResponseWrapper,\n public readonly error?: {\n name: string;\n message: string;\n },\n public readonly endTime?: number,\n ) {}\n\n toSerializable(): Record<string, any> {\n const serialized: Record<string, any> = {\n type: this.type,\n method: this.method,\n url: this.url,\n timestamp: this.timestamp,\n status: this.status,\n duration: this.duration,\n error: this.error,\n startTime: this.startTime,\n endTime: this.endTime,\n requestHeaders: this.requestWrapper?.headers([...SAFE_HEADERS]),\n requestBodySize: this.requestWrapper?.bodySize,\n responseHeaders: this.responseWrapper?.headers([...SAFE_HEADERS]),\n responseBodySize: this.responseWrapper?.bodySize,\n };\n\n return Object.fromEntries(Object.entries(serialized).filter(([_, v]) => v !== undefined));\n }\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@amplitude/analytics-core",
|
|
3
|
-
"version": "2.22.
|
|
3
|
+
"version": "2.22.1",
|
|
4
4
|
"description": "",
|
|
5
5
|
"author": "Amplitude Inc",
|
|
6
6
|
"homepage": "https://github.com/amplitude/Amplitude-TypeScript",
|
|
@@ -42,5 +42,5 @@
|
|
|
42
42
|
"files": [
|
|
43
43
|
"lib"
|
|
44
44
|
],
|
|
45
|
-
"gitHead": "
|
|
45
|
+
"gitHead": "ab511cd5652935c1582014e79601861c29c7163a"
|
|
46
46
|
}
|