@mswjs/interceptors 0.19.5 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,44 @@
1
+ import type { Debugger } from 'debug';
2
+ import { Request } from '@remix-run/web-fetch';
3
+ /**
4
+ * An `XMLHttpRequest` instance controller that allows us
5
+ * to handle any given request instance (e.g. responding to it).
6
+ */
7
+ export declare class XMLHttpRequestController {
8
+ readonly initialRequest: XMLHttpRequest;
9
+ log: Debugger;
10
+ request: XMLHttpRequest;
11
+ requestId?: string;
12
+ onRequest?: (this: XMLHttpRequestController, request: Request, requestId: string) => Promise<void>;
13
+ onResponse?: (this: XMLHttpRequestController, response: Response, request: Request, requestId: string) => void;
14
+ private method;
15
+ private url;
16
+ private requestHeaders;
17
+ private requestBody?;
18
+ private responseBuffer;
19
+ private events;
20
+ constructor(initialRequest: XMLHttpRequest, log: Debugger);
21
+ private registerEvent;
22
+ /**
23
+ * Responds to the current request with the given
24
+ * Fetch API `Response` instance.
25
+ */
26
+ respondWith(response: Response): void;
27
+ private responseBufferToText;
28
+ get response(): unknown;
29
+ get responseText(): string;
30
+ get responseXML(): Document | null;
31
+ errorWith(error: Error): void;
32
+ /**
33
+ * Transitions this request's `readyState` to the given one.
34
+ */
35
+ private setReadyState;
36
+ /**
37
+ * Triggers given event on the `XMLHttpRequest` instance.
38
+ */
39
+ private trigger;
40
+ /**
41
+ * Converts this `XMLHttpRequest` instance into a Fetch API `Request` instance.
42
+ */
43
+ toFetchApiRequest(): Request;
44
+ }
@@ -0,0 +1,413 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.XMLHttpRequestController = void 0;
13
+ const web_fetch_1 = require("@remix-run/web-fetch");
14
+ const headers_polyfill_1 = require("headers-polyfill");
15
+ const concatArrayBuffer_1 = require("./utils/concatArrayBuffer");
16
+ const createEvent_1 = require("./utils/createEvent");
17
+ const bufferUtils_1 = require("../../utils/bufferUtils");
18
+ const createProxy_1 = require("../../utils/createProxy");
19
+ const isDomParserSupportedType_1 = require("./utils/isDomParserSupportedType");
20
+ const parseJson_1 = require("../../utils/parseJson");
21
+ const uuid_1 = require("../../utils/uuid");
22
+ const createResponse_1 = require("./utils/createResponse");
23
+ const outvariant_1 = require("outvariant");
24
+ /**
25
+ * An `XMLHttpRequest` instance controller that allows us
26
+ * to handle any given request instance (e.g. responding to it).
27
+ */
28
+ class XMLHttpRequestController {
29
+ constructor(initialRequest, log) {
30
+ this.initialRequest = initialRequest;
31
+ this.log = log;
32
+ this.method = 'GET';
33
+ this.url = null;
34
+ this.events = new Map();
35
+ this.requestHeaders = new web_fetch_1.Headers();
36
+ this.responseBuffer = new Uint8Array();
37
+ this.request = (0, createProxy_1.createProxy)(initialRequest, {
38
+ setProperty: ([propertyName, nextValue], invoke) => {
39
+ /**
40
+ * @note Setting the "withCredentials" property on the XHR proxy
41
+ * causes the "TypeError: Illegal invocation" error. Instead,
42
+ * define the property on the original XHR instance itself.
43
+ */
44
+ if (propertyName === 'withCredentials') {
45
+ define(this.request, 'withCredentials', nextValue);
46
+ return true;
47
+ }
48
+ return invoke();
49
+ },
50
+ methodCall: ([methodName, args], invoke) => {
51
+ var _a;
52
+ switch (methodName) {
53
+ case 'open': {
54
+ const [method, url] = args;
55
+ this.requestId = (0, uuid_1.uuidv4)();
56
+ if (typeof url === 'undefined') {
57
+ this.method = 'GET';
58
+ this.url = toAbsoluteUrl(method);
59
+ }
60
+ else {
61
+ this.method = method;
62
+ this.url = toAbsoluteUrl(url);
63
+ }
64
+ this.log = this.log.extend(`${this.method} ${this.url.href}`);
65
+ this.log('open', this.method, this.url.href);
66
+ return invoke();
67
+ }
68
+ case 'addEventListener': {
69
+ const [eventName, listener] = args;
70
+ this.registerEvent(eventName, listener);
71
+ this.log('addEventListener', eventName, listener.name);
72
+ return invoke();
73
+ }
74
+ case 'setRequestHeader': {
75
+ const [name, value] = args;
76
+ this.requestHeaders.set(name, value);
77
+ this.log('setRequestHeader', name, value);
78
+ return invoke();
79
+ }
80
+ case 'send': {
81
+ const [body] = args;
82
+ if (body != null) {
83
+ this.requestBody =
84
+ typeof body === 'string' ? (0, bufferUtils_1.encodeBuffer)(body) : body;
85
+ }
86
+ this.request.addEventListener('load', () => {
87
+ if (typeof this.onResponse !== 'undefined') {
88
+ // Create a Fetch API Response representation of whichever
89
+ // response this XMLHttpRequest received. Note those may
90
+ // be either a mocked and the original response.
91
+ const fetchResponse = (0, createResponse_1.createResponse)(this.request,
92
+ /**
93
+ * The `response` property is the right way to read
94
+ * the ambiguous response body, as the request's "responseTyoe"
95
+ * may differ.
96
+ * @see https://xhr.spec.whatwg.org/#the-response-attribute
97
+ */
98
+ this.request.response);
99
+ // Notify the consumer about the response.
100
+ this.onResponse.call(this, fetchResponse, fetchRequest, this.requestId);
101
+ }
102
+ });
103
+ // Delegate request handling to the consumer.
104
+ const fetchRequest = this.toFetchApiRequest();
105
+ const onceRequestSettled = ((_a = this.onRequest) === null || _a === void 0 ? void 0 : _a.call(this, fetchRequest, this.requestId)) ||
106
+ Promise.resolve();
107
+ onceRequestSettled.finally(() => {
108
+ // If the consumer didn't handle the request perform it as-is.
109
+ // Note that the request may not yet be DONE and may, in fact,
110
+ // be LOADING while the "respondWith" method does its magic.
111
+ if (this.request.readyState < this.request.LOADING) {
112
+ this.log('request callback settled but request has not been handled (readystate %d), performing as-is...', this.request.readyState);
113
+ /**
114
+ * @note Set the intercepted request ID on the original request
115
+ * so that if it triggers any other interceptors, they don't attempt
116
+ * to process it once again.
117
+ *
118
+ * For instance, XMLHttpRequest is often implemented via "http.ClientRequest"
119
+ * and we don't want for both XHR and ClientRequest interceptors to
120
+ * handle the same request at the same time (e.g. emit the "response" event twice).
121
+ */
122
+ this.request.setRequestHeader('X-Request-Id', this.requestId);
123
+ return invoke();
124
+ }
125
+ });
126
+ break;
127
+ }
128
+ case 'onabort':
129
+ case 'onerror':
130
+ case 'onload':
131
+ case 'onloadend':
132
+ case 'onloadstart':
133
+ case 'onprogress':
134
+ case 'ontimeout':
135
+ case 'onreadystatechange': {
136
+ const [listener] = args;
137
+ this.registerEvent(methodName, listener);
138
+ return invoke();
139
+ }
140
+ default: {
141
+ return invoke();
142
+ }
143
+ }
144
+ },
145
+ });
146
+ }
147
+ registerEvent(eventName, listener) {
148
+ const prevEvents = this.events.get(eventName) || [];
149
+ const nextEvents = prevEvents.concat(listener);
150
+ this.events.set(eventName, nextEvents);
151
+ this.log('registered event "%s"', eventName, listener.name);
152
+ }
153
+ /**
154
+ * Responds to the current request with the given
155
+ * Fetch API `Response` instance.
156
+ */
157
+ respondWith(response) {
158
+ this.log('responding with a mocked response: %d %s', response.status, response.statusText);
159
+ define(this.request, 'status', response.status);
160
+ define(this.request, 'statusText', response.statusText);
161
+ define(this.request, 'responseURL', this.url.href);
162
+ this.request.getResponseHeader = new Proxy(this.request.getResponseHeader, {
163
+ apply: (_, __, args) => {
164
+ this.log('getResponseHeader', args[0]);
165
+ if (this.request.readyState < this.request.HEADERS_RECEIVED) {
166
+ this.log('headers not received yet, returning null');
167
+ // Headers not received yet, nothing to return.
168
+ return null;
169
+ }
170
+ const headerValue = response.headers.get(args[0]);
171
+ this.log('resolved response header "%s" to', args[0], headerValue);
172
+ return headerValue;
173
+ },
174
+ });
175
+ this.request.getAllResponseHeaders = new Proxy(this.request.getAllResponseHeaders, {
176
+ apply: () => {
177
+ this.log('getAllResponseHeaders');
178
+ if (this.request.readyState < this.request.HEADERS_RECEIVED) {
179
+ this.log('headers not received yet, returning empty string');
180
+ // Headers not received yet, nothing to return.
181
+ return '';
182
+ }
183
+ const allHeaders = (0, headers_polyfill_1.headersToString)(response.headers);
184
+ this.log('resolved all response headers to', allHeaders);
185
+ return allHeaders;
186
+ },
187
+ });
188
+ // Update the response getters to resolve against the mocked response.
189
+ Object.defineProperties(this.request, {
190
+ response: {
191
+ enumerable: true,
192
+ get: () => this.response,
193
+ },
194
+ responseText: {
195
+ enumerable: true,
196
+ get: () => this.responseText,
197
+ },
198
+ responseXML: {
199
+ enumerable: true,
200
+ get: () => this.responseXML,
201
+ },
202
+ });
203
+ const totalResponseBodyLength = response.headers.has('Content-Length')
204
+ ? Number(response.headers.get('Content-Length'))
205
+ : /**
206
+ * @todo Infer the response body length from the response body.
207
+ */
208
+ undefined;
209
+ this.log('calculated response body length', totalResponseBodyLength);
210
+ this.trigger('loadstart', {
211
+ loaded: 0,
212
+ total: totalResponseBodyLength,
213
+ });
214
+ this.setReadyState(this.request.HEADERS_RECEIVED);
215
+ this.setReadyState(this.request.LOADING);
216
+ const finalizeResponse = () => {
217
+ this.log('finalizing the mocked response...');
218
+ this.setReadyState(this.request.DONE);
219
+ this.trigger('load', {
220
+ loaded: this.responseBuffer.byteLength,
221
+ total: totalResponseBodyLength,
222
+ });
223
+ this.trigger('loadend', {
224
+ loaded: this.responseBuffer.byteLength,
225
+ total: totalResponseBodyLength,
226
+ });
227
+ };
228
+ if (response.body) {
229
+ this.log('mocked response has body, streaming...');
230
+ const reader = response.body.getReader();
231
+ const readNextResponseBodyChunk = () => __awaiter(this, void 0, void 0, function* () {
232
+ const { value, done } = yield reader.read();
233
+ if (done) {
234
+ this.log('response body stream done!');
235
+ finalizeResponse();
236
+ return;
237
+ }
238
+ if (value) {
239
+ this.log('read response body chunk:', value);
240
+ this.responseBuffer = (0, concatArrayBuffer_1.concatArrayBuffer)(this.responseBuffer, value);
241
+ this.trigger('progress', {
242
+ loaded: this.responseBuffer.byteLength,
243
+ total: totalResponseBodyLength,
244
+ });
245
+ }
246
+ readNextResponseBodyChunk();
247
+ });
248
+ readNextResponseBodyChunk();
249
+ }
250
+ else {
251
+ finalizeResponse();
252
+ }
253
+ }
254
+ responseBufferToText() {
255
+ return (0, bufferUtils_1.decodeBuffer)(this.responseBuffer);
256
+ }
257
+ get response() {
258
+ this.log('getResponse (responseType: %s)', this.request.responseType);
259
+ if (this.request.readyState !== this.request.DONE) {
260
+ return null;
261
+ }
262
+ switch (this.request.responseType) {
263
+ case 'json': {
264
+ const responseJson = (0, parseJson_1.parseJson)(this.responseBufferToText());
265
+ this.log('resolved response JSON', responseJson);
266
+ return responseJson;
267
+ }
268
+ case 'arraybuffer': {
269
+ const arrayBuffer = (0, bufferUtils_1.toArrayBuffer)(this.responseBuffer);
270
+ this.log('resolved response ArrayBuffer', arrayBuffer);
271
+ return arrayBuffer;
272
+ }
273
+ case 'blob': {
274
+ const mimeType = this.request.getResponseHeader('Content-Type') || 'text/plain';
275
+ const responseBlob = new Blob([this.responseBufferToText()], {
276
+ type: mimeType,
277
+ });
278
+ this.log('resolved response Blob (mime type: %s)', responseBlob, mimeType);
279
+ return responseBlob;
280
+ }
281
+ default: {
282
+ const responseText = this.responseBufferToText();
283
+ this.log('resolving "%s" response type as text', this.request.responseType, responseText);
284
+ return responseText;
285
+ }
286
+ }
287
+ }
288
+ get responseText() {
289
+ /**
290
+ * Throw when trying to read the response body as text when the
291
+ * "responseType" doesn't expect text. This just respects the spec better.
292
+ * @see https://xhr.spec.whatwg.org/#the-responsetext-attribute
293
+ */
294
+ (0, outvariant_1.invariant)(this.request.responseType === '' || this.request.responseType === 'text', 'InvalidStateError: The object is in invalid state.');
295
+ if (this.request.readyState !== this.request.LOADING &&
296
+ this.request.readyState !== this.request.DONE) {
297
+ return '';
298
+ }
299
+ const responseText = this.responseBufferToText();
300
+ this.log('getResponseText: "%s"', responseText);
301
+ return responseText;
302
+ }
303
+ get responseXML() {
304
+ (0, outvariant_1.invariant)(this.request.responseType === '' ||
305
+ this.request.responseType === 'document', 'InvalidStateError: The object is in invalid state.');
306
+ if (this.request.readyState !== this.request.DONE) {
307
+ return null;
308
+ }
309
+ const contentType = this.request.getResponseHeader('Content-Type') || '';
310
+ if (typeof DOMParser === 'undefined') {
311
+ console.warn('Cannot retrieve XMLHttpRequest response body as XML: DOMParser is not defined. You are likely using an environment that is not browser or does not polyfill browser globals correctly.');
312
+ return null;
313
+ }
314
+ if ((0, isDomParserSupportedType_1.isDomParserSupportedType)(contentType)) {
315
+ return new DOMParser().parseFromString(this.responseBufferToText(), contentType);
316
+ }
317
+ return null;
318
+ }
319
+ errorWith(error) {
320
+ this.log('responding with an error');
321
+ this.setReadyState(this.request.DONE);
322
+ this.trigger('error');
323
+ this.trigger('loadend');
324
+ }
325
+ /**
326
+ * Transitions this request's `readyState` to the given one.
327
+ */
328
+ setReadyState(nextReadyState) {
329
+ this.log('setReadyState: %d -> %d', this.request.readyState, nextReadyState);
330
+ if (this.request.readyState === nextReadyState) {
331
+ this.log('ready state identical, skipping transition...');
332
+ return;
333
+ }
334
+ define(this.request, 'readyState', nextReadyState);
335
+ this.log('set readyState to: %d', nextReadyState);
336
+ if (nextReadyState !== this.request.UNSENT) {
337
+ this.log('triggerring "readystatechange" event...');
338
+ this.trigger('readystatechange');
339
+ }
340
+ }
341
+ /**
342
+ * Triggers given event on the `XMLHttpRequest` instance.
343
+ */
344
+ trigger(eventName, options) {
345
+ const callback = this.request[`on${eventName}`];
346
+ const event = (0, createEvent_1.createEvent)(this.request, eventName, options);
347
+ this.log('trigger "%s"', eventName, options || '');
348
+ // Invoke direct callbacks.
349
+ if (typeof callback === 'function') {
350
+ this.log('found a direct "%s" callback, calling...', eventName);
351
+ callback.call(this.request, event);
352
+ }
353
+ // Invoke event listeners.
354
+ for (const [registeredEventName, listeners] of this.events) {
355
+ if (registeredEventName === eventName) {
356
+ this.log('found %d listener(s) for "%s" event, calling...', listeners.length, eventName);
357
+ listeners.forEach((listener) => listener.call(this.request, event));
358
+ }
359
+ }
360
+ }
361
+ /**
362
+ * Converts this `XMLHttpRequest` instance into a Fetch API `Request` instance.
363
+ */
364
+ toFetchApiRequest() {
365
+ this.log('converting request to a Fetch API Request...');
366
+ const fetchRequest = new web_fetch_1.Request(this.url.href, {
367
+ method: this.method,
368
+ headers: this.requestHeaders,
369
+ /**
370
+ * @see https://xhr.spec.whatwg.org/#cross-origin-credentials
371
+ */
372
+ credentials: this.request.withCredentials ? 'include' : 'same-origin',
373
+ body: this.requestBody,
374
+ });
375
+ const proxyHeaders = (0, createProxy_1.createProxy)(fetchRequest.headers, {
376
+ methodCall: ([methodName, args], invoke) => {
377
+ // Forward the latest state of the internal request headers
378
+ // because the interceptor might have modified them
379
+ // without responding to the request.
380
+ switch (methodName) {
381
+ case 'append':
382
+ case 'set': {
383
+ const [headerName, headerValue] = args;
384
+ this.request.setRequestHeader(headerName, headerValue);
385
+ break;
386
+ }
387
+ case 'delete': {
388
+ const [headerName] = args;
389
+ console.warn(`XMLHttpRequest: Cannot remove a "${headerName}" header from the Fetch API representation of the "${fetchRequest.method} ${fetchRequest.url}" request. XMLHttpRequest headers cannot be removed.`);
390
+ break;
391
+ }
392
+ }
393
+ return invoke();
394
+ },
395
+ });
396
+ define(fetchRequest, 'headers', proxyHeaders);
397
+ this.log('converted request to a Fetch API Request!', fetchRequest);
398
+ return fetchRequest;
399
+ }
400
+ }
401
+ exports.XMLHttpRequestController = XMLHttpRequestController;
402
+ function toAbsoluteUrl(url) {
403
+ return new URL(url.toString(), location.href);
404
+ }
405
+ function define(target, property, value) {
406
+ Reflect.defineProperty(target, property, {
407
+ // Ensure writable properties to allow redefining readonly properties.
408
+ writable: true,
409
+ enumerable: true,
410
+ value,
411
+ });
412
+ }
413
+ //# sourceMappingURL=XMLHttpRequestController.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"XMLHttpRequestController.js","sourceRoot":"","sources":["../../../src/interceptors/XMLHttpR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;wBACtD,MAAK;qBACN;oBAED,KAAK,QAAQ,CAAC,CAAC;wBACb,MAAM,CAAC,UAAU,CAAC,GAAG,IAAgB,CAAA;wBACrC,OAAO,CAAC,IAAI,CACV,oCAAoC,UAAU,sDAAsD,YAAY,CAAC,MAAM,IAAI,YAAY,CAAC,GAAG,sDAAsD,CAClM,CAAA;wBACD,MAAK;qBACN;iBACF;gBAED,OAAO,MAAM,EAAE,CAAA;YACjB,CAAC;SACF,CAAC,CAAA;QACF,MAAM,CAAC,YAAY,EAAE,SAAS,EAAE,YAAY,CAAC,CAAA;QAE7C,IAAI,CAAC,GAAG,CAAC,2CAA2C,EAAE,YAAY,CAAC,CAAA;QAEnE,OAAO,YAAY,CAAA;IACrB,CAAC;CACF;AA/hBD,4DA+hBC;AAED,SAAS,aAAa,CAAC,GAAiB;IACtC,OAAO,IAAI,GAAG,CAAC,GAAG,CAAC,QAAQ,EAAE,EAAE,QAAQ,CAAC,IAAI,CAAC,CAAA;AAC/C,CAAC;AAED,SAAS,MAAM,CAAC,MAAc,EAAE,QAAgB,EAAE,KAAc;IAC9D,OAAO,CAAC,cAAc,CAAC,MAAM,EAAE,QAAQ,EAAE;QACvC,sEAAsE;QACtE,QAAQ,EAAE,IAAI;QACd,UAAU,EAAE,IAAI;QAChB,KAAK;KACN,CAAC,CAAA;AACJ,CAAC"}
@@ -0,0 +1,20 @@
1
+ import type { Debugger } from 'debug';
2
+ import { XMLHttpRequestEmitter } from '.';
3
+ export interface XMLHttpRequestProxyOptions {
4
+ emitter: XMLHttpRequestEmitter;
5
+ log: Debugger;
6
+ }
7
+ /**
8
+ * Create a proxied `XMLHttpRequest` class.
9
+ * The proxied class establishes spies on certain methods,
10
+ * allowing us to intercept requests and respond to them.
11
+ */
12
+ export declare function createXMLHttpRequestProxy({ emitter, log, }: XMLHttpRequestProxyOptions): {
13
+ new (): XMLHttpRequest;
14
+ prototype: XMLHttpRequest;
15
+ readonly DONE: number;
16
+ readonly HEADERS_RECEIVED: number;
17
+ readonly LOADING: number;
18
+ readonly OPENED: number;
19
+ readonly UNSENT: number;
20
+ };
@@ -0,0 +1,75 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.createXMLHttpRequestProxy = void 0;
13
+ const until_1 = require("@open-draft/until");
14
+ const toInteractiveRequest_1 = require("../../utils/toInteractiveRequest");
15
+ const XMLHttpRequestController_1 = require("./XMLHttpRequestController");
16
+ /**
17
+ * Create a proxied `XMLHttpRequest` class.
18
+ * The proxied class establishes spies on certain methods,
19
+ * allowing us to intercept requests and respond to them.
20
+ */
21
+ function createXMLHttpRequestProxy({ emitter, log, }) {
22
+ const XMLHttpRequestProxy = new Proxy(globalThis.XMLHttpRequest, {
23
+ construct(target, args) {
24
+ log('constructed new XMLHttpRequest');
25
+ const originalRequest = Reflect.construct(target, args);
26
+ const requestController = new XMLHttpRequestController_1.XMLHttpRequestController(originalRequest, log);
27
+ requestController.onRequest = function (request, requestId) {
28
+ return __awaiter(this, void 0, void 0, function* () {
29
+ // Notify the consumer about a new request.
30
+ const interactiveRequest = (0, toInteractiveRequest_1.toInteractiveRequest)(request);
31
+ this.log('emitting the "request" event for %s listener(s)...', emitter.listenerCount('request'));
32
+ emitter.emit('request', interactiveRequest, requestId);
33
+ this.log('awaiting mocked response...');
34
+ const [middlewareException, mockedResponse] = yield (0, until_1.until)(() => __awaiter(this, void 0, void 0, function* () {
35
+ yield emitter.untilIdle('request', ({ args: [, pendingRequestId] }) => {
36
+ return pendingRequestId === requestId;
37
+ });
38
+ this.log('all "request" listeners settled!');
39
+ const [mockedResponse] = yield interactiveRequest.respondWith.invoked();
40
+ this.log('event.respondWith called with:', mockedResponse);
41
+ return mockedResponse;
42
+ }));
43
+ if (middlewareException) {
44
+ this.log('request listener threw an exception, aborting request...', middlewareException);
45
+ /**
46
+ * @todo Consider forwarding this error to the stderr as well
47
+ * since not all consumers are expecting to handle errors.
48
+ * If they don't, this error will be swallowed.
49
+ */
50
+ requestController.errorWith(middlewareException);
51
+ return;
52
+ }
53
+ if (typeof mockedResponse !== 'undefined') {
54
+ this.log('received mocked response: %d %s', mockedResponse.status, mockedResponse.statusText);
55
+ return requestController.respondWith(mockedResponse);
56
+ }
57
+ this.log('no mocked response received, performing request as-is...');
58
+ });
59
+ };
60
+ requestController.onResponse = function (response, request, requestId) {
61
+ return __awaiter(this, void 0, void 0, function* () {
62
+ this.log('emitting the "response" event for %s listener(s)...', emitter.listenerCount('response'));
63
+ emitter.emit('response', response, request, requestId);
64
+ });
65
+ };
66
+ // Return the proxied request from the controller
67
+ // so that the controller can react to the consumer's interactions
68
+ // with this request (opening/sending/etc).
69
+ return requestController.request;
70
+ },
71
+ });
72
+ return XMLHttpRequestProxy;
73
+ }
74
+ exports.createXMLHttpRequestProxy = createXMLHttpRequestProxy;
75
+ //# sourceMappingURL=XMLHttpRequestProxy.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"XMLHttpRequestProxy.js","sourceRoot":"","sources":["../../../src/interceptors/XMLHttpRequest/XMLHttpRequestProxy.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,6CAAyC;AAEzC,2EAAuE;AACvE,yEAAqE;AAOrE;;;;GAIG;AACH,SAAgB,yBAAyB,CAAC,EACxC,OAAO,EACP,GAAG,GACwB;IAC3B,MAAM,mBAAmB,GAAG,IAAI,KAAK,CAAC,UAAU,CAAC,cAAc,EAAE;QAC/D,SAAS,CAAC,MAAM,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AAS,CAAC,mBAAmB,CAAC,CAAA;wBAChD,OAAM;qBACP;oBAED,IAAI,OAAO,cAAc,KAAK,WAAW,EAAE;wBACzC,IAAI,CAAC,GAAG,CACN,iCAAiC,EACjC,cAAc,CAAC,MAAM,EACrB,cAAc,CAAC,UAAU,CAC1B,CAAA;wBAED,OAAO,iBAAiB,CAAC,WAAW,CAAC,cAAc,CAAC,CAAA;qBACrD;oBAED,IAAI,CAAC,GAAG,CAAC,0DAA0D,CAAC,CAAA;gBACtE,CAAC;aAAA,CAAA;YAED,iBAAiB,CAAC,UAAU,GAAG,UAC7B,QAAQ,EACR,OAAO,EACP,SAAS;;oBAET,IAAI,CAAC,GAAG,CACN,qDAAqD,EACrD,OAAO,CAAC,aAAa,CAAC,UAAU,CAAC,CAClC,CAAA;oBAED,OAAO,CAAC,IAAI,CAAC,UAAU,EAAE,QAAQ,EAAE,OAAO,EAAE,SAAS,CAAC,CAAA;gBACxD,CAAC;aAAA,CAAA;YAED,iDAAiD;YACjD,kEAAkE;YAClE,2CAA2C;YAC3C,OAAO,iBAAiB,CAAC,OAAO,CAAA;QAClC,CAAC;KACF,CAAC,CAAA;IAEF,OAAO,mBAAmB,CAAA;AAC5B,CAAC;AA9FD,8DA8FC"}
@@ -4,37 +4,35 @@ exports.XMLHttpRequestInterceptor = void 0;
4
4
  const outvariant_1 = require("outvariant");
5
5
  const glossary_1 = require("../../glossary");
6
6
  const Interceptor_1 = require("../../Interceptor");
7
- const XMLHttpRequestOverride_1 = require("./XMLHttpRequestOverride");
7
+ const XMLHttpRequestProxy_1 = require("./XMLHttpRequestProxy");
8
8
  class XMLHttpRequestInterceptor extends Interceptor_1.Interceptor {
9
9
  constructor() {
10
10
  super(XMLHttpRequestInterceptor.symbol);
11
11
  }
12
12
  checkEnvironment() {
13
- return (typeof window !== 'undefined' &&
14
- typeof window.XMLHttpRequest !== 'undefined');
13
+ return typeof globalThis.XMLHttpRequest !== 'undefined';
15
14
  }
16
15
  setup() {
17
16
  const log = this.log.extend('setup');
18
17
  log('patching "XMLHttpRequest" module...');
19
- const PureXMLHttpRequest = window.XMLHttpRequest;
18
+ const PureXMLHttpRequest = globalThis.XMLHttpRequest;
20
19
  (0, outvariant_1.invariant)(!PureXMLHttpRequest[glossary_1.IS_PATCHED_MODULE], 'Failed to patch the "XMLHttpRequest" module: already patched.');
21
- window.XMLHttpRequest = (0, XMLHttpRequestOverride_1.createXMLHttpRequestOverride)({
22
- XMLHttpRequest: PureXMLHttpRequest,
20
+ globalThis.XMLHttpRequest = (0, XMLHttpRequestProxy_1.createXMLHttpRequestProxy)({
23
21
  emitter: this.emitter,
24
22
  log: this.log,
25
23
  });
26
- log('native "XMLHttpRequest" module patched!', window.XMLHttpRequest.name);
27
- Object.defineProperty(window.XMLHttpRequest, glossary_1.IS_PATCHED_MODULE, {
24
+ log('native "XMLHttpRequest" module patched!', globalThis.XMLHttpRequest.name);
25
+ Object.defineProperty(globalThis.XMLHttpRequest, glossary_1.IS_PATCHED_MODULE, {
28
26
  enumerable: true,
29
27
  configurable: true,
30
28
  value: true,
31
29
  });
32
30
  this.subscriptions.push(() => {
33
- Object.defineProperty(window.XMLHttpRequest, glossary_1.IS_PATCHED_MODULE, {
31
+ Object.defineProperty(globalThis.XMLHttpRequest, glossary_1.IS_PATCHED_MODULE, {
34
32
  value: undefined,
35
33
  });
36
- window.XMLHttpRequest = PureXMLHttpRequest;
37
- log('native "XMLHttpRequest" module restored!', window.XMLHttpRequest.name);
34
+ globalThis.XMLHttpRequest = PureXMLHttpRequest;
35
+ log('native "XMLHttpRequest" module restored!', globalThis.XMLHttpRequest.name);
38
36
  });
39
37
  }
40
38
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/interceptors/XMLHttpRequest/index.ts"],"names":[],"mappings":";;;AAAA,2CAAsC;AACtC,6CAAuE;AAEvE,mDAA+C;AAE/C,qEAAuE;AASvE,MAAa,yBAA0B,SAAQ,yBAAgC;IAG7E;QACE,KAA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Ac,CAAC,IAAI,CAC/B,CAAA;QACH,CAAC,CAAC,CAAA;IACJ,CAAC;;AAlDH,8DAmDC;AAlDQ,gCAAM,GAAG,MAAM,CAAC,KAAK,CAAC,CAAA"}
@@ -0,0 +1,8 @@
1
+ export interface ProxyOptions<Target extends Record<string, any>> {
2
+ constructorCall?(args: Array<unknown>, next: NextFunction<Target>): Target;
3
+ methodCall?<F extends keyof Target>(this: Target, data: [methodName: F, args: Array<unknown>], next: NextFunction<void>): void;
4
+ setProperty?(data: [propertyName: string | symbol, nextValue: unknown], next: NextFunction<void>): void;
5
+ getProperty?(data: [propertyName: string | symbol, receiver: Target], next: NextFunction<void>): void;
6
+ }
7
+ export declare type NextFunction<ReturnType> = () => ReturnType;
8
+ export declare function createProxy<Target extends object>(target: Target, options: ProxyOptions<Target>): Target;