@mswjs/interceptors 0.38.3 → 0.38.5
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/README.md +15 -0
- package/lib/browser/{chunk-P6ZNAT4K.mjs → chunk-7RPAMWJ6.mjs} +5 -5
- package/lib/browser/chunk-7RPAMWJ6.mjs.map +1 -0
- package/lib/browser/{chunk-XDWMU6ZF.mjs → chunk-CNX33NZA.mjs} +6 -3
- package/lib/browser/{chunk-XDWMU6ZF.mjs.map → chunk-CNX33NZA.mjs.map} +1 -1
- package/lib/browser/{chunk-FGSEOIC4.js → chunk-GTJ35JP4.js} +30 -12
- package/lib/browser/chunk-GTJ35JP4.js.map +1 -0
- package/lib/{node/chunk-5KMS5CTP.mjs → browser/chunk-L37TY7LC.mjs} +30 -14
- package/lib/browser/chunk-L37TY7LC.mjs.map +1 -0
- package/lib/browser/{chunk-NZ7OXVVL.js → chunk-MSUVVHIG.js} +5 -2
- package/lib/browser/{chunk-NZ7OXVVL.js.map → chunk-MSUVVHIG.js.map} +1 -1
- package/lib/browser/{chunk-WVIAZNTB.js → chunk-O2RCNIMR.js} +11 -11
- package/lib/browser/chunk-O2RCNIMR.js.map +1 -0
- package/lib/browser/{chunk-XHFULOZS.mjs → chunk-SKG3GP7X.mjs} +5 -5
- package/lib/browser/chunk-SKG3GP7X.mjs.map +1 -0
- package/lib/browser/{chunk-AF44JPFO.js → chunk-UY4VLZVB.js} +15 -15
- package/lib/browser/chunk-UY4VLZVB.js.map +1 -0
- package/lib/browser/{glossary-6564c252.d.ts → glossary-7152281e.d.ts} +5 -3
- package/lib/browser/index.d.ts +1 -1
- package/lib/browser/index.js +2 -2
- package/lib/browser/index.mjs +1 -1
- package/lib/browser/interceptors/XMLHttpRequest/index.d.ts +1 -1
- package/lib/browser/interceptors/XMLHttpRequest/index.js +4 -4
- package/lib/browser/interceptors/XMLHttpRequest/index.mjs +3 -3
- package/lib/browser/interceptors/fetch/index.d.ts +1 -1
- package/lib/browser/interceptors/fetch/index.js +4 -4
- package/lib/browser/interceptors/fetch/index.mjs +3 -3
- package/lib/browser/presets/browser.d.ts +1 -1
- package/lib/browser/presets/browser.js +6 -6
- package/lib/browser/presets/browser.mjs +4 -4
- package/lib/node/{BatchInterceptor-67bf41ba.d.ts → BatchInterceptor-5b72232f.d.ts} +1 -1
- package/lib/node/{Interceptor-436630be.d.ts → Interceptor-bc5a9d8e.d.ts} +5 -3
- package/lib/node/RemoteHttpInterceptor.d.ts +2 -2
- package/lib/node/RemoteHttpInterceptor.js +16 -14
- package/lib/node/RemoteHttpInterceptor.js.map +1 -1
- package/lib/node/RemoteHttpInterceptor.mjs +8 -6
- package/lib/node/RemoteHttpInterceptor.mjs.map +1 -1
- package/lib/node/chunk-3GJB4JDF.mjs +14 -0
- package/lib/node/chunk-3GJB4JDF.mjs.map +1 -0
- package/lib/node/{chunk-VEYMW7A4.mjs → chunk-3HLZLASJ.mjs} +8 -6
- package/lib/node/chunk-3HLZLASJ.mjs.map +1 -0
- package/lib/node/{chunk-T3P6W5EK.mjs → chunk-3TXENUZY.mjs} +8 -6
- package/lib/node/chunk-3TXENUZY.mjs.map +1 -0
- package/lib/node/chunk-4YBV77DG.js +32 -0
- package/lib/node/chunk-4YBV77DG.js.map +1 -0
- package/lib/node/{chunk-6L3PFBGT.js → chunk-C2JSMMHY.js} +32 -13
- package/lib/node/chunk-C2JSMMHY.js.map +1 -0
- package/lib/node/{chunk-QFLITAVV.js → chunk-DLID3GDG.js} +2 -10
- package/lib/node/chunk-DLID3GDG.js.map +1 -0
- package/lib/node/{chunk-CV5EAVU6.mjs → chunk-FHLAZ57F.mjs} +13 -11
- package/lib/node/chunk-FHLAZ57F.mjs.map +1 -0
- package/lib/node/{chunk-CNH7N6AT.js → chunk-K4I5GNXU.js} +16 -14
- package/lib/node/chunk-K4I5GNXU.js.map +1 -0
- package/lib/{browser/chunk-H5O73WD2.mjs → node/chunk-LGXJ3UUF.mjs} +33 -12
- package/lib/node/chunk-LGXJ3UUF.mjs.map +1 -0
- package/lib/node/{chunk-HAXZ5BCL.js → chunk-MCB574K6.js} +3 -3
- package/lib/node/{chunk-BURFIIB6.js → chunk-R7MWIVYW.js} +13 -11
- package/lib/node/chunk-R7MWIVYW.js.map +1 -0
- package/lib/node/{chunk-OU5BNOD7.js → chunk-RA7KLLRD.js} +29 -27
- package/lib/node/chunk-RA7KLLRD.js.map +1 -0
- package/lib/node/chunk-SMXZPJEA.js +14 -0
- package/lib/node/chunk-SMXZPJEA.js.map +1 -0
- package/lib/node/{chunk-67C2L7UE.mjs → chunk-TBU3WLO3.mjs} +2 -2
- package/lib/node/chunk-TJDMZZXE.mjs +32 -0
- package/lib/node/chunk-TJDMZZXE.mjs.map +1 -0
- package/lib/node/{chunk-45R4C3G5.mjs → chunk-YM42IU6M.mjs} +2 -10
- package/lib/node/chunk-YM42IU6M.mjs.map +1 -0
- package/lib/node/index.d.ts +2 -2
- package/lib/node/index.js +5 -3
- package/lib/node/index.js.map +1 -1
- package/lib/node/index.mjs +5 -3
- package/lib/node/index.mjs.map +1 -1
- package/lib/node/interceptors/ClientRequest/index.d.ts +1 -1
- package/lib/node/interceptors/ClientRequest/index.js +6 -4
- package/lib/node/interceptors/ClientRequest/index.mjs +5 -3
- package/lib/node/interceptors/XMLHttpRequest/index.d.ts +1 -1
- package/lib/node/interceptors/XMLHttpRequest/index.js +5 -4
- package/lib/node/interceptors/XMLHttpRequest/index.mjs +4 -3
- package/lib/node/interceptors/fetch/index.d.ts +1 -1
- package/lib/node/interceptors/fetch/index.js +5 -4
- package/lib/node/interceptors/fetch/index.mjs +4 -3
- package/lib/node/presets/node.d.ts +1 -1
- package/lib/node/presets/node.js +10 -8
- package/lib/node/presets/node.js.map +1 -1
- package/lib/node/presets/node.mjs +7 -5
- package/lib/node/presets/node.mjs.map +1 -1
- package/lib/node/utils/node/index.d.ts +13 -0
- package/lib/node/utils/node/index.js +10 -0
- package/lib/node/utils/node/index.js.map +1 -0
- package/lib/node/utils/node/index.mjs +10 -0
- package/lib/node/utils/node/index.mjs.map +1 -0
- package/package.json +12 -1
- package/src/RequestController.test.ts +8 -0
- package/src/RequestController.ts +9 -5
- package/src/getRawRequest.ts +5 -1
- package/src/interceptors/ClientRequest/MockHttpSocket.ts +11 -2
- package/src/interceptors/XMLHttpRequest/XMLHttpRequestController.ts +2 -2
- package/src/interceptors/fetch/index.ts +2 -2
- package/src/utils/handleRequest.ts +27 -9
- package/src/utils/node/index.ts +39 -0
- package/src/utils/responseUtils.ts +22 -2
- package/lib/browser/chunk-AF44JPFO.js.map +0 -1
- package/lib/browser/chunk-FGSEOIC4.js.map +0 -1
- package/lib/browser/chunk-H5O73WD2.mjs.map +0 -1
- package/lib/browser/chunk-P6ZNAT4K.mjs.map +0 -1
- package/lib/browser/chunk-WVIAZNTB.js.map +0 -1
- package/lib/browser/chunk-XHFULOZS.mjs.map +0 -1
- package/lib/node/chunk-45R4C3G5.mjs.map +0 -1
- package/lib/node/chunk-5KMS5CTP.mjs.map +0 -1
- package/lib/node/chunk-6L3PFBGT.js.map +0 -1
- package/lib/node/chunk-BURFIIB6.js.map +0 -1
- package/lib/node/chunk-CNH7N6AT.js.map +0 -1
- package/lib/node/chunk-CV5EAVU6.mjs.map +0 -1
- package/lib/node/chunk-OU5BNOD7.js.map +0 -1
- package/lib/node/chunk-QFLITAVV.js.map +0 -1
- package/lib/node/chunk-T3P6W5EK.mjs.map +0 -1
- package/lib/node/chunk-VEYMW7A4.mjs.map +0 -1
- /package/lib/node/{chunk-HAXZ5BCL.js.map → chunk-MCB574K6.js.map} +0 -0
- /package/lib/node/{chunk-67C2L7UE.mjs.map → chunk-TBU3WLO3.mjs.map} +0 -0
|
@@ -1,17 +1,19 @@
|
|
|
1
1
|
import {
|
|
2
2
|
ClientRequestInterceptor
|
|
3
|
-
} from "../chunk-
|
|
3
|
+
} from "../chunk-FHLAZ57F.mjs";
|
|
4
|
+
import "../chunk-TJDMZZXE.mjs";
|
|
4
5
|
import {
|
|
5
6
|
XMLHttpRequestInterceptor
|
|
6
|
-
} from "../chunk-
|
|
7
|
+
} from "../chunk-3HLZLASJ.mjs";
|
|
7
8
|
import "../chunk-6HYIRFX2.mjs";
|
|
8
9
|
import {
|
|
9
10
|
FetchInterceptor
|
|
10
|
-
} from "../chunk-
|
|
11
|
+
} from "../chunk-3TXENUZY.mjs";
|
|
11
12
|
import "../chunk-TX5GBTFY.mjs";
|
|
12
13
|
import "../chunk-6YM4PLBI.mjs";
|
|
13
|
-
import "../chunk-
|
|
14
|
-
import "../chunk-
|
|
14
|
+
import "../chunk-LGXJ3UUF.mjs";
|
|
15
|
+
import "../chunk-YM42IU6M.mjs";
|
|
16
|
+
import "../chunk-3GJB4JDF.mjs";
|
|
15
17
|
|
|
16
18
|
// src/presets/node.ts
|
|
17
19
|
var node_default = [
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/presets/node.ts"],"sourcesContent":["import { ClientRequestInterceptor } from '../interceptors/ClientRequest'\nimport { XMLHttpRequestInterceptor } from '../interceptors/XMLHttpRequest'\nimport { FetchInterceptor } from '../interceptors/fetch'\n\n/**\n * The default preset provisions the interception of requests\n * regardless of their type (http/https/XMLHttpRequest).\n */\nexport default [\n new ClientRequestInterceptor(),\n new XMLHttpRequestInterceptor(),\n new FetchInterceptor(),\n] as const\n"],"mappings":"
|
|
1
|
+
{"version":3,"sources":["../../../src/presets/node.ts"],"sourcesContent":["import { ClientRequestInterceptor } from '../interceptors/ClientRequest'\nimport { XMLHttpRequestInterceptor } from '../interceptors/XMLHttpRequest'\nimport { FetchInterceptor } from '../interceptors/fetch'\n\n/**\n * The default preset provisions the interception of requests\n * regardless of their type (http/https/XMLHttpRequest).\n */\nexport default [\n new ClientRequestInterceptor(),\n new XMLHttpRequestInterceptor(),\n new FetchInterceptor(),\n] as const\n"],"mappings":";;;;;;;;;;;;;;;;;;AAQA,IAAO,eAAQ;AAAA,EACb,IAAI,yBAAyB;AAAA,EAC7B,IAAI,0BAA0B;AAAA,EAC9B,IAAI,iBAAiB;AACvB;","names":[]}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { Readable } from 'node:stream';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Returns the request body stream of the given request.
|
|
5
|
+
* @note This is only relevant in the context of `http.ClientRequest`.
|
|
6
|
+
* This function will throw if the given `request` wasn't created based on
|
|
7
|
+
* the `http.ClientRequest` instance.
|
|
8
|
+
* You must rely on the web stream consumers for other request clients.
|
|
9
|
+
*/
|
|
10
|
+
declare function getClientRequestBodyStream(request: Request): Readable;
|
|
11
|
+
declare function setRawRequestBodyStream(request: Request, stream: Readable): void;
|
|
12
|
+
|
|
13
|
+
export { getClientRequestBodyStream, setRawRequestBodyStream };
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
var _chunk4YBV77DGjs = require('../../chunk-4YBV77DG.js');
|
|
5
|
+
require('../../chunk-SMXZPJEA.js');
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
exports.getClientRequestBodyStream = _chunk4YBV77DGjs.getClientRequestBodyStream; exports.setRawRequestBodyStream = _chunk4YBV77DGjs.setRawRequestBodyStream;
|
|
10
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"names":[],"mappings":""}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mswjs/interceptors",
|
|
3
3
|
"description": "Low-level HTTP/HTTPS/XHR/fetch request interception library.",
|
|
4
|
-
"version": "0.38.
|
|
4
|
+
"version": "0.38.5",
|
|
5
5
|
"main": "./lib/node/index.js",
|
|
6
6
|
"module": "./lib/node/index.mjs",
|
|
7
7
|
"types": "./lib/node/index.d.ts",
|
|
@@ -88,6 +88,17 @@
|
|
|
88
88
|
"import": "./lib/browser/presets/browser.mjs",
|
|
89
89
|
"default": "./lib/browser/presets/browser.js"
|
|
90
90
|
}
|
|
91
|
+
},
|
|
92
|
+
"./utils/node": {
|
|
93
|
+
"types": "./lib/node/utils/node/index.d.ts",
|
|
94
|
+
"node": {
|
|
95
|
+
"require": "./lib/node/utils/node/index.js",
|
|
96
|
+
"import": "./lib/node/utils/node/index.mjs"
|
|
97
|
+
},
|
|
98
|
+
"browser": null,
|
|
99
|
+
"require": "./lib/node/utils/node/index.js",
|
|
100
|
+
"import": "./lib/node/utils/node/index.mjs",
|
|
101
|
+
"default": "./lib/node/utils/node/index.js"
|
|
91
102
|
}
|
|
92
103
|
},
|
|
93
104
|
"author": "Artem Zakharchenko",
|
|
@@ -26,6 +26,14 @@ it('resolves the response promise with the error provided to "errorWith"', async
|
|
|
26
26
|
await expect(controller[kResponsePromise]).resolves.toEqual(error)
|
|
27
27
|
})
|
|
28
28
|
|
|
29
|
+
it('resolves the response promise with an arbitrary object provided to "errorWith"', async () => {
|
|
30
|
+
const controller = new RequestController(new Request('http://localhost'))
|
|
31
|
+
const error = { message: 'Oops!' }
|
|
32
|
+
controller.errorWith(error)
|
|
33
|
+
|
|
34
|
+
await expect(controller[kResponsePromise]).resolves.toEqual(error)
|
|
35
|
+
})
|
|
36
|
+
|
|
29
37
|
it('throws when calling "respondWith" multiple times', () => {
|
|
30
38
|
const controller = new RequestController(new Request('http://localhost'))
|
|
31
39
|
controller.respondWith(new Response('hello world'))
|
package/src/RequestController.ts
CHANGED
|
@@ -13,7 +13,9 @@ export class RequestController {
|
|
|
13
13
|
* @note This promise cannot be rejected. It's either infinitely
|
|
14
14
|
* pending or resolved with whichever Response was passed to `respondWith()`.
|
|
15
15
|
*/
|
|
16
|
-
[kResponsePromise]: DeferredPromise<
|
|
16
|
+
[kResponsePromise]: DeferredPromise<
|
|
17
|
+
Response | Record<string, any> | undefined
|
|
18
|
+
>;
|
|
17
19
|
|
|
18
20
|
/**
|
|
19
21
|
* Internal flag indicating if this request has been handled.
|
|
@@ -46,7 +48,7 @@ export class RequestController {
|
|
|
46
48
|
this[kResponsePromise].resolve(response)
|
|
47
49
|
|
|
48
50
|
/**
|
|
49
|
-
* @note The request
|
|
51
|
+
* @note The request controller doesn't do anything
|
|
50
52
|
* apart from letting the interceptor await the response
|
|
51
53
|
* provided by the developer through the response promise.
|
|
52
54
|
* Each interceptor implements the actual respondWith/errorWith
|
|
@@ -55,12 +57,14 @@ export class RequestController {
|
|
|
55
57
|
}
|
|
56
58
|
|
|
57
59
|
/**
|
|
58
|
-
* Error this request with the given
|
|
60
|
+
* Error this request with the given reason.
|
|
61
|
+
*
|
|
59
62
|
* @example
|
|
60
63
|
* controller.errorWith()
|
|
61
64
|
* controller.errorWith(new Error('Oops!'))
|
|
65
|
+
* controller.errorWith({ message: 'Oops!'})
|
|
62
66
|
*/
|
|
63
|
-
public errorWith(
|
|
67
|
+
public errorWith(reason?: Error | Record<string, any>): void {
|
|
64
68
|
invariant.as(
|
|
65
69
|
InterceptorError,
|
|
66
70
|
!this[kRequestHandled],
|
|
@@ -76,6 +80,6 @@ export class RequestController {
|
|
|
76
80
|
* This helps us differentiate between unhandled exceptions
|
|
77
81
|
* and intended errors ("errorWith") while waiting for the response.
|
|
78
82
|
*/
|
|
79
|
-
this[kResponsePromise].resolve(
|
|
83
|
+
this[kResponsePromise].resolve(reason)
|
|
80
84
|
}
|
|
81
85
|
}
|
package/src/getRawRequest.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
const kRawRequest = Symbol('kRawRequest')
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* Returns a raw request instance associated with this request.
|
|
@@ -15,3 +15,7 @@ export const kRawRequest = Symbol('kRawRequest')
|
|
|
15
15
|
export function getRawRequest(request: Request): unknown | undefined {
|
|
16
16
|
return Reflect.get(request, kRawRequest)
|
|
17
17
|
}
|
|
18
|
+
|
|
19
|
+
export function setRawRequest(request: Request, rawRequest: unknown): void {
|
|
20
|
+
Reflect.set(request, kRawRequest, rawRequest)
|
|
21
|
+
}
|
|
@@ -16,7 +16,8 @@ import { createServerErrorResponse } from '../../utils/responseUtils'
|
|
|
16
16
|
import { createRequestId } from '../../createRequestId'
|
|
17
17
|
import { getRawFetchHeaders } from './utils/recordRawHeaders'
|
|
18
18
|
import { FetchResponse } from '../../utils/fetchUtils'
|
|
19
|
-
import {
|
|
19
|
+
import { setRawRequest } from '../../getRawRequest'
|
|
20
|
+
import { setRawRequestBodyStream } from '../../utils/node'
|
|
20
21
|
|
|
21
22
|
type HttpConnectionOptions = any
|
|
22
23
|
|
|
@@ -515,7 +516,15 @@ export class MockHttpSocket extends MockSocket {
|
|
|
515
516
|
})
|
|
516
517
|
|
|
517
518
|
Reflect.set(this.request, kRequestId, requestId)
|
|
518
|
-
|
|
519
|
+
|
|
520
|
+
// Set the raw `http.ClientRequest` instance on the request instance.
|
|
521
|
+
// This is useful for cases like getting the raw headers of the request.
|
|
522
|
+
setRawRequest(this.request, Reflect.get(this, '_httpMessage'))
|
|
523
|
+
|
|
524
|
+
// Create a copy of the request body stream and store it on the request.
|
|
525
|
+
// This is only needed for the consumers who wish to read the request body stream
|
|
526
|
+
// of requests that cannot have a body per Fetch API specification (i.e. GET, HEAD).
|
|
527
|
+
setRawRequestBodyStream(this.request, this.requestStream)
|
|
519
528
|
|
|
520
529
|
// Skip handling the request that's already being handled
|
|
521
530
|
// by another (parent) interceptor. For example, XMLHttpRequest
|
|
@@ -15,7 +15,7 @@ import { createResponse } from './utils/createResponse'
|
|
|
15
15
|
import { INTERNAL_REQUEST_ID_HEADER_NAME } from '../../Interceptor'
|
|
16
16
|
import { createRequestId } from '../../createRequestId'
|
|
17
17
|
import { getBodyByteLength } from './utils/getBodyByteLength'
|
|
18
|
-
import {
|
|
18
|
+
import { setRawRequest } from '../../getRawRequest'
|
|
19
19
|
|
|
20
20
|
const kIsRequestHandled = Symbol('kIsRequestHandled')
|
|
21
21
|
const IS_NODE = isNodeProcess()
|
|
@@ -699,7 +699,7 @@ export class XMLHttpRequestController {
|
|
|
699
699
|
},
|
|
700
700
|
})
|
|
701
701
|
define(fetchRequest, 'headers', proxyHeaders)
|
|
702
|
-
|
|
702
|
+
setRawRequest(fetchRequest, this.request)
|
|
703
703
|
|
|
704
704
|
this.logger.info('converted request to a Fetch API Request!', fetchRequest)
|
|
705
705
|
|
|
@@ -12,7 +12,7 @@ import { followFetchRedirect } from './utils/followRedirect'
|
|
|
12
12
|
import { decompressResponse } from './utils/decompression'
|
|
13
13
|
import { hasConfigurableGlobal } from '../../utils/hasConfigurableGlobal'
|
|
14
14
|
import { FetchResponse } from '../../utils/fetchUtils'
|
|
15
|
-
import {
|
|
15
|
+
import { setRawRequest } from '../../getRawRequest'
|
|
16
16
|
|
|
17
17
|
export class FetchInterceptor extends Interceptor<HttpRequestEventMap> {
|
|
18
18
|
static symbol = Symbol('fetch')
|
|
@@ -55,7 +55,7 @@ export class FetchInterceptor extends Interceptor<HttpRequestEventMap> {
|
|
|
55
55
|
* @note Set the raw request only if a Request instance was provided to fetch.
|
|
56
56
|
*/
|
|
57
57
|
if (input instanceof Request) {
|
|
58
|
-
|
|
58
|
+
setRawRequest(request, input)
|
|
59
59
|
}
|
|
60
60
|
|
|
61
61
|
const responsePromise = new DeferredPromise<Response>()
|
|
@@ -7,10 +7,12 @@ import { kResponsePromise, RequestController } from '../RequestController'
|
|
|
7
7
|
import {
|
|
8
8
|
createServerErrorResponse,
|
|
9
9
|
isResponseError,
|
|
10
|
+
isResponseLike,
|
|
10
11
|
ResponseError,
|
|
11
12
|
} from './responseUtils'
|
|
12
13
|
import { InterceptorError } from '../InterceptorError'
|
|
13
14
|
import { isNodeLikeError } from './isNodeLikeError'
|
|
15
|
+
import { isObject } from './isObject'
|
|
14
16
|
|
|
15
17
|
interface HandleRequestOptions {
|
|
16
18
|
requestId: string
|
|
@@ -43,19 +45,37 @@ interface HandleRequestOptions {
|
|
|
43
45
|
export async function handleRequest(
|
|
44
46
|
options: HandleRequestOptions
|
|
45
47
|
): Promise<boolean> {
|
|
46
|
-
const handleResponse = async (
|
|
48
|
+
const handleResponse = async (
|
|
49
|
+
response: Response | Error | Record<string, any>
|
|
50
|
+
) => {
|
|
47
51
|
if (response instanceof Error) {
|
|
48
52
|
options.onError(response)
|
|
53
|
+
return true
|
|
49
54
|
}
|
|
50
55
|
|
|
51
56
|
// Handle "Response.error()" instances.
|
|
52
|
-
|
|
57
|
+
if (isResponseError(response)) {
|
|
53
58
|
options.onRequestError(response)
|
|
54
|
-
|
|
59
|
+
return true
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Handle normal responses or response-like objects.
|
|
64
|
+
* @note This must come before the arbitrary object check
|
|
65
|
+
* since Response instances are, in fact, objects.
|
|
66
|
+
*/
|
|
67
|
+
if (isResponseLike(response)) {
|
|
55
68
|
await options.onResponse(response)
|
|
69
|
+
return true
|
|
56
70
|
}
|
|
57
71
|
|
|
58
|
-
|
|
72
|
+
// Handle arbitrary objects provided to `.errorWith(reason)`.
|
|
73
|
+
if (isObject(response)) {
|
|
74
|
+
options.onError(response)
|
|
75
|
+
return true
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
return false
|
|
59
79
|
}
|
|
60
80
|
|
|
61
81
|
const handleResponseError = async (error: unknown): Promise<boolean> => {
|
|
@@ -116,7 +136,7 @@ export async function handleRequest(
|
|
|
116
136
|
// for that event are finished (e.g. async listeners awaited).
|
|
117
137
|
// By the end of this promise, the developer cannot affect the
|
|
118
138
|
// request anymore.
|
|
119
|
-
const
|
|
139
|
+
const requestListenersPromise = emitAsync(options.emitter, 'request', {
|
|
120
140
|
requestId: options.requestId,
|
|
121
141
|
request: options.request,
|
|
122
142
|
controller: options.controller,
|
|
@@ -125,14 +145,13 @@ export async function handleRequest(
|
|
|
125
145
|
await Promise.race([
|
|
126
146
|
// Short-circuit the request handling promise if the request gets aborted.
|
|
127
147
|
requestAbortPromise,
|
|
128
|
-
|
|
148
|
+
requestListenersPromise,
|
|
129
149
|
options.controller[kResponsePromise],
|
|
130
150
|
])
|
|
131
151
|
|
|
132
152
|
// The response promise will settle immediately once
|
|
133
153
|
// the developer calls either "respondWith" or "errorWith".
|
|
134
|
-
|
|
135
|
-
return mockedResponse
|
|
154
|
+
return await options.controller[kResponsePromise]
|
|
136
155
|
})
|
|
137
156
|
|
|
138
157
|
// Handle the request being aborted while waiting for the request listeners.
|
|
@@ -212,6 +231,5 @@ export async function handleRequest(
|
|
|
212
231
|
}
|
|
213
232
|
|
|
214
233
|
// In all other cases, consider the request unhandled.
|
|
215
|
-
// The interceptor must perform it as-is.
|
|
216
234
|
return false
|
|
217
235
|
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { ClientRequest } from 'node:http'
|
|
2
|
+
import { Readable } from 'node:stream'
|
|
3
|
+
import { invariant } from 'outvariant'
|
|
4
|
+
import { getRawRequest } from '../../getRawRequest'
|
|
5
|
+
|
|
6
|
+
const kRawRequestBodyStream = Symbol('kRawRequestBodyStream')
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Returns the request body stream of the given request.
|
|
10
|
+
* @note This is only relevant in the context of `http.ClientRequest`.
|
|
11
|
+
* This function will throw if the given `request` wasn't created based on
|
|
12
|
+
* the `http.ClientRequest` instance.
|
|
13
|
+
* You must rely on the web stream consumers for other request clients.
|
|
14
|
+
*/
|
|
15
|
+
export function getClientRequestBodyStream(request: Request): Readable {
|
|
16
|
+
const rawRequest = getRawRequest(request)
|
|
17
|
+
|
|
18
|
+
invariant(
|
|
19
|
+
rawRequest instanceof ClientRequest,
|
|
20
|
+
`Failed to retrieve raw request body stream: request is not an instance of "http.ClientRequest". Note that you can only use the "getClientRequestBodyStream" function with the requests issued by "http.clientRequest".`
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
const requestBodyStream = Reflect.get(request, kRawRequestBodyStream)
|
|
24
|
+
|
|
25
|
+
invariant(
|
|
26
|
+
requestBodyStream instanceof Readable,
|
|
27
|
+
'Failed to retrieve raw request body stream: corrupted stream (%s)',
|
|
28
|
+
typeof requestBodyStream
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
return requestBodyStream
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function setRawRequestBodyStream(
|
|
35
|
+
request: Request,
|
|
36
|
+
stream: Readable
|
|
37
|
+
): void {
|
|
38
|
+
Reflect.set(request, kRawRequestBodyStream, stream)
|
|
39
|
+
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { isObject } from './isObject'
|
|
1
2
|
import { isPropertyAccessible } from './isPropertyAccessible'
|
|
2
3
|
|
|
3
4
|
/**
|
|
@@ -34,6 +35,25 @@ export type ResponseError = Response & { type: 'error' }
|
|
|
34
35
|
* Safely check if we can access "type" on "Response" before continuing.
|
|
35
36
|
* @see https://github.com/mswjs/msw/issues/1834
|
|
36
37
|
*/
|
|
37
|
-
export function isResponseError(response:
|
|
38
|
-
return
|
|
38
|
+
export function isResponseError(response: unknown): response is ResponseError {
|
|
39
|
+
return (
|
|
40
|
+
response != null &&
|
|
41
|
+
response instanceof Response &&
|
|
42
|
+
isPropertyAccessible(response, 'type') &&
|
|
43
|
+
response.type === 'error'
|
|
44
|
+
)
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Check if the given value is a `Response` or a Response-like object.
|
|
49
|
+
* This is different from `value instanceof Response` because it supports
|
|
50
|
+
* custom `Response` constructors, like the one when using Undici directly.
|
|
51
|
+
*/
|
|
52
|
+
export function isResponseLike(value: unknown): value is Response {
|
|
53
|
+
return (
|
|
54
|
+
isObject<Record<string, any>>(value, true) &&
|
|
55
|
+
isPropertyAccessible(value, 'status') &&
|
|
56
|
+
isPropertyAccessible(value, 'statusText') &&
|
|
57
|
+
isPropertyAccessible(value, 'bodyUsed')
|
|
58
|
+
)
|
|
39
59
|
}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/interceptors/fetch/index.ts","../../src/interceptors/fetch/utils/createNetworkError.ts","../../src/interceptors/fetch/utils/followRedirect.ts","../../src/interceptors/fetch/utils/brotli-decompress.browser.ts","../../src/interceptors/fetch/utils/decompression.ts"],"names":["readable","transformers","response"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA,SAAS,iBAAiB;AAC1B,SAAS,uBAAuB;;;ACDzB,SAAS,mBAAmB,OAAiB;AAClD,SAAO,OAAO,OAAO,IAAI,UAAU,iBAAiB,GAAG;AAAA,IACrD;AAAA,EACF,CAAC;AACH;;;ACFA,IAAM,uBAAuB;AAAA,EAC3B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEA,IAAM,iBAAiB,OAAO,gBAAgB;AAK9C,eAAsB,oBACpB,SACA,UACmB;AACnB,MAAI,SAAS,WAAW,OAAO,QAAQ,QAAQ,MAAM;AACnD,WAAO,QAAQ,OAAO,mBAAmB,CAAC;AAAA,EAC5C;AAEA,QAAM,aAAa,IAAI,IAAI,QAAQ,GAAG;AAEtC,MAAI;AACJ,MAAI;AAEF,kBAAc,IAAI,IAAI,SAAS,QAAQ,IAAI,UAAU,GAAI,QAAQ,GAAG;AAAA,EACtE,SAAS,OAAP;AACA,WAAO,QAAQ,OAAO,mBAAmB,KAAK,CAAC;AAAA,EACjD;AAEA,MACE,EAAE,YAAY,aAAa,WAAW,YAAY,aAAa,WAC/D;AACA,WAAO,QAAQ;AAAA,MACb,mBAAmB,qCAAqC;AAAA,IAC1D;AAAA,EACF;AAEA,MAAI,QAAQ,IAAI,SAAS,cAAc,IAAI,IAAI;AAC7C,WAAO,QAAQ,OAAO,mBAAmB,yBAAyB,CAAC;AAAA,EACrE;AAEA,SAAO,eAAe,SAAS,gBAAgB;AAAA,IAC7C,QAAQ,QAAQ,IAAI,SAAS,cAAc,KAAK,KAAK;A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;AAEnD,gBAAM,gBAAgB,SAAS,MAAM;AAErC,gBAAM,UAAU,KAAK,SAAS,YAAY;AAAA,YACxC,UAAU;AAAA,YACV,kBAAkB;AAAA,YAClB,SAAS;AAAA,YACT;AAAA,UACF,CAAC;AAAA,QACH;AAEA,eAAO;AAAA,MACT,CAAC;AAAA,IACH;AAEA,WAAO,eAAe,WAAW,OAAO,mBAAmB;AAAA,MACzD,YAAY;AAAA,MACZ,cAAc;AAAA,MACd,OAAO;AAAA,IACT,CAAC;AAED,SAAK,cAAc,KAAK,MAAM;AAC5B,aAAO,eAAe,WAAW,OAAO,mBAAmB;AAAA,QACzD,OAAO;AAAA,MACT,CAAC;AAED,iBAAW,QAAQ;AAEnB,WAAK,OAAO;AAAA,QACV;AAAA,QACA,WAAW,MAAM;AAAA,MACnB;AAAA,IACF,CAAC;AAAA,EACH;AACF;AA1LO,IAAM,mBAAN;AAAM,iBACJ,SAAS,OAAO,OAAO","sourcesContent":["import { invariant } from 'outvariant'\nimport { DeferredPromise } from '@open-draft/deferred-promise'\nimport { HttpRequestEventMap, IS_PATCHED_MODULE } from '../../glossary'\nimport { Interceptor } from '../../Interceptor'\nimport { RequestController } from '../../RequestController'\nimport { emitAsync } from '../../utils/emitAsync'\nimport { handleRequest } from '../../utils/handleRequest'\nimport { canParseUrl } from '../../utils/canParseUrl'\nimport { createRequestId } from '../../createRequestId'\nimport { createNetworkError } from './utils/createNetworkError'\nimport { followFetchRedirect } from './utils/followRedirect'\nimport { decompressResponse } from './utils/decompression'\nimport { hasConfigurableGlobal } from '../../utils/hasConfigurableGlobal'\nimport { FetchResponse } from '../../utils/fetchUtils'\nimport { kRawRequest } from '../../getRawRequest'\n\nexport class FetchInterceptor extends Interceptor<HttpRequestEventMap> {\n static symbol = Symbol('fetch')\n\n constructor() {\n super(FetchInterceptor.symbol)\n }\n\n protected checkEnvironment() {\n return hasConfigurableGlobal('fetch')\n }\n\n protected async setup() {\n const pureFetch = globalThis.fetch\n\n invariant(\n !(pureFetch as any)[IS_PATCHED_MODULE],\n 'Failed to patch the \"fetch\" module: already patched.'\n )\n\n globalThis.fetch = async (input, init) => {\n const requestId = createRequestId()\n\n /**\n * @note Resolve potentially relative request URL\n * against the present `location`. This is mainly\n * for native `fetch` in JSDOM.\n * @see https://github.com/mswjs/msw/issues/1625\n */\n const resolvedInput =\n typeof input === 'string' &&\n typeof location !== 'undefined' &&\n !canParseUrl(input)\n ? new URL(input, location.href)\n : input\n\n const request = new Request(resolvedInput, init)\n\n /**\n * @note Set the raw request only if a Request instance was provided to fetch.\n */\n if (input instanceof Request) {\n Reflect.set(request, kRawRequest, input)\n }\n\n const responsePromise = new DeferredPromise<Response>()\n const controller = new RequestController(request)\n\n this.logger.info('[%s] %s', request.method, request.url)\n this.logger.info('awaiting for the mocked response...')\n\n this.logger.info(\n 'emitting the \"request\" event for %s listener(s)...',\n this.emitter.listenerCount('request')\n )\n\n const isRequestHandled = await handleRequest({\n request,\n requestId,\n emitter: this.emitter,\n controller,\n onResponse: async (rawResponse) => {\n this.logger.info('received mocked response!', {\n rawResponse,\n })\n\n // Decompress the mocked response body, if applicable.\n const decompressedStream = decompressResponse(rawResponse)\n const response =\n decompressedStream === null\n ? rawResponse\n : new FetchResponse(decompressedStream, rawResponse)\n\n FetchResponse.setUrl(request.url, response)\n\n /**\n * Undici's handling of following redirect responses.\n * Treat the \"manual\" redirect mode as a regular mocked response.\n * This way, the client can manually follow the redirect it receives.\n * @see https://github.com/nodejs/undici/blob/a6dac3149c505b58d2e6d068b97f4dc993da55f0/lib/web/fetch/index.js#L1173\n */\n if (FetchResponse.isRedirectResponse(response.status)) {\n // Reject the request promise if its `redirect` is set to `error`\n // and it receives a mocked redirect response.\n if (request.redirect === 'error') {\n responsePromise.reject(createNetworkError('unexpected redirect'))\n return\n }\n\n if (request.redirect === 'follow') {\n followFetchRedirect(request, response).then(\n (response) => {\n responsePromise.resolve(response)\n },\n (reason) => {\n responsePromise.reject(reason)\n }\n )\n return\n }\n }\n\n if (this.emitter.listenerCount('response') > 0) {\n this.logger.info('emitting the \"response\" event...')\n\n // Await the response listeners to finish before resolving\n // the response promise. This ensures all your logic finishes\n // before the interceptor resolves the pending response.\n await emitAsync(this.emitter, 'response', {\n // Clone the mocked response for the \"response\" event listener.\n // This way, the listener can read the response and not lock its body\n // for the actual fetch consumer.\n response: response.clone(),\n isMockedResponse: true,\n request,\n requestId,\n })\n }\n\n responsePromise.resolve(response)\n },\n onRequestError: (response) => {\n this.logger.info('request has errored!', { response })\n responsePromise.reject(createNetworkError(response))\n },\n onError: (error) => {\n this.logger.info('request has been aborted!', { error })\n responsePromise.reject(error)\n },\n })\n\n if (isRequestHandled) {\n this.logger.info('request has been handled, returning mock promise...')\n return responsePromise\n }\n\n this.logger.info(\n 'no mocked response received, performing request as-is...'\n )\n\n /**\n * @note Clone the request instance right before performing it.\n * This preserves any modifications made to the intercepted request\n * in the \"request\" listener. This also allows the user to read the\n * request body in the \"response\" listener (otherwise \"unusable\").\n */\n const requestCloneForResponseEvent = request.clone()\n\n return pureFetch(request).then(async (response) => {\n this.logger.info('original fetch performed', response)\n\n if (this.emitter.listenerCount('response') > 0) {\n this.logger.info('emitting the \"response\" event...')\n\n const responseClone = response.clone()\n\n await emitAsync(this.emitter, 'response', {\n response: responseClone,\n isMockedResponse: false,\n request: requestCloneForResponseEvent,\n requestId,\n })\n }\n\n return response\n })\n }\n\n Object.defineProperty(globalThis.fetch, IS_PATCHED_MODULE, {\n enumerable: true,\n configurable: true,\n value: true,\n })\n\n this.subscriptions.push(() => {\n Object.defineProperty(globalThis.fetch, IS_PATCHED_MODULE, {\n value: undefined,\n })\n\n globalThis.fetch = pureFetch\n\n this.logger.info(\n 'restored native \"globalThis.fetch\"!',\n globalThis.fetch.name\n )\n })\n }\n}\n","export function createNetworkError(cause?: unknown) {\n return Object.assign(new TypeError('Failed to fetch'), {\n cause,\n })\n}\n","import { createNetworkError } from './createNetworkError'\n\nconst REQUEST_BODY_HEADERS = [\n 'content-encoding',\n 'content-language',\n 'content-location',\n 'content-type',\n 'content-length',\n]\n\nconst kRedirectCount = Symbol('kRedirectCount')\n\n/**\n * @see https://github.com/nodejs/undici/blob/a6dac3149c505b58d2e6d068b97f4dc993da55f0/lib/web/fetch/index.js#L1210\n */\nexport async function followFetchRedirect(\n request: Request,\n response: Response\n): Promise<Response> {\n if (response.status !== 303 && request.body != null) {\n return Promise.reject(createNetworkError())\n }\n\n const requestUrl = new URL(request.url)\n\n let locationUrl: URL\n try {\n // If the location is a relative URL, use the request URL as the base URL.\n locationUrl = new URL(response.headers.get('location')!, request.url) \n } catch (error) {\n return Promise.reject(createNetworkError(error))\n }\n\n if (\n !(locationUrl.protocol === 'http:' || locationUrl.protocol === 'https:')\n ) {\n return Promise.reject(\n createNetworkError('URL scheme must be a HTTP(S) scheme')\n )\n }\n\n if (Reflect.get(request, kRedirectCount) > 20) {\n return Promise.reject(createNetworkError('redirect count exceeded'))\n }\n\n Object.defineProperty(request, kRedirectCount, {\n value: (Reflect.get(request, kRedirectCount) || 0) + 1,\n })\n\n if (\n request.mode === 'cors' &&\n (locationUrl.username || locationUrl.password) &&\n !sameOrigin(requestUrl, locationUrl)\n ) {\n return Promise.reject(\n createNetworkError('cross origin not allowed for request mode \"cors\"')\n )\n }\n\n const requestInit: RequestInit = {}\n\n if (\n ([301, 302].includes(response.status) && request.method === 'POST') ||\n (response.status === 303 && !['HEAD', 'GET'].includes(request.method))\n ) {\n requestInit.method = 'GET'\n requestInit.body = null\n\n REQUEST_BODY_HEADERS.forEach((headerName) => {\n request.headers.delete(headerName)\n })\n }\n\n if (!sameOrigin(requestUrl, locationUrl)) {\n request.headers.delete('authorization')\n request.headers.delete('proxy-authorization')\n request.headers.delete('cookie')\n request.headers.delete('host')\n }\n\n /**\n * @note Undici \"safely\" extracts the request body.\n * I suspect we cannot dispatch this request again\n * since its body has been read and the stream is locked.\n */\n\n requestInit.headers = request.headers\n return fetch(new Request(locationUrl, requestInit))\n}\n\n/**\n * @see https://github.com/nodejs/undici/blob/a6dac3149c505b58d2e6d068b97f4dc993da55f0/lib/web/fetch/util.js#L761\n */\nfunction sameOrigin(left: URL, right: URL): boolean {\n if (left.origin === right.origin && left.origin === 'null') {\n return true\n }\n\n if (\n left.protocol === right.protocol &&\n left.hostname === right.hostname &&\n left.port === right.port\n ) {\n return true\n }\n\n return false\n}\n","export class BrotliDecompressionStream extends TransformStream {\n constructor() {\n console.warn(\n '[Interceptors]: Brotli decompression of response streams is not supported in the browser'\n )\n\n super({\n transform(chunk, controller) {\n // Keep the stream as passthrough, it does nothing.\n controller.enqueue(chunk)\n },\n })\n }\n}\n","// Import from an internal alias that resolves to different modules\n// depending on the environment. This way, we can keep the fetch interceptor\n// intact while using different strategies for Brotli decompression.\nimport { BrotliDecompressionStream } from 'internal:brotli-decompress'\n\nclass PipelineStream extends TransformStream {\n constructor(\n transformStreams: Array<TransformStream>,\n ...strategies: Array<QueuingStrategy>\n ) {\n super({}, ...strategies)\n\n const readable = [super.readable as any, ...transformStreams].reduce(\n (readable, transform) => readable.pipeThrough(transform)\n )\n\n Object.defineProperty(this, 'readable', {\n get() {\n return readable\n },\n })\n }\n}\n\nexport function parseContentEncoding(contentEncoding: string): Array<string> {\n return contentEncoding\n .toLowerCase()\n .split(',')\n .map((coding) => coding.trim())\n}\n\nfunction createDecompressionStream(\n contentEncoding: string\n): TransformStream | null {\n if (contentEncoding === '') {\n return null\n }\n\n const codings = parseContentEncoding(contentEncoding)\n\n if (codings.length === 0) {\n return null\n }\n\n const transformers = codings.reduceRight<Array<TransformStream>>(\n (transformers, coding) => {\n if (coding === 'gzip' || coding === 'x-gzip') {\n return transformers.concat(new DecompressionStream('gzip'))\n } else if (coding === 'deflate') {\n return transformers.concat(new DecompressionStream('deflate'))\n } else if (coding === 'br') {\n return transformers.concat(new BrotliDecompressionStream())\n } else {\n transformers.length = 0\n }\n\n return transformers\n },\n []\n )\n\n return new PipelineStream(transformers)\n}\n\nexport function decompressResponse(\n response: Response\n): ReadableStream<any> | null {\n if (response.body === null) {\n return null\n }\n\n const decompressionStream = createDecompressionStream(\n response.headers.get('content-encoding') || ''\n )\n\n if (!decompressionStream) {\n return null\n }\n\n // Use `pipeTo` and return the decompression stream's readable\n // instead of `pipeThrough` because that will lock the original\n // response stream, making it unusable as the input to Response.\n response.body.pipeTo(decompressionStream.writable)\n return decompressionStream.readable\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/RequestController.ts","../../src/InterceptorError.ts","../../src/utils/emitAsync.ts","../../src/utils/handleRequest.ts","../../src/utils/isPropertyAccessible.ts","../../src/utils/responseUtils.ts","../../src/utils/isNodeLikeError.ts"],"names":["DeferredPromise"],"mappings":";AAAA,SAAS,iBAAiB;AAC1B,SAAS,uBAAuB;;;ACDzB,IAAM,mBAAN,cAA+B,MAAM;AAAA,EAC1C,YAAY,SAAkB;AAC5B,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,WAAO,eAAe,MAAM,iBAAiB,SAAS;AAAA,EACxD;AACF;;;ADFA,IAAM,kBAAkB,OAAO,iBAAiB;AACzC,IAAM,mBAAmB,OAAO,kBAAkB;AAElD,IAAM,oBAAN,MAAwB;AAAA,EAgB7B,YAAoB,SAAkB;AAAlB;AAClB,SAAK,eAAe,IAAI;AACxB,SAAK,gBAAgB,IAAI,IAAI,gBAAgB;AAAA,EAC/C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASO,YAAY,UAA0B;AAC3C,cAAU;AAAA,MACR;AAAA,MACA,CAAC,KAAK,eAAe;AAAA,MACrB;AAAA,MACA,KAAK,QAAQ;AAAA,MACb,KAAK,QAAQ;AAAA,IACf;AAEA,SAAK,eAAe,IAAI;AACxB,SAAK,gBAAgB,EAAE,QAAQ,QAAQ;AAAA,EASzC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQO,UAAU,OAAqB;AACpC,cAAU;AAAA,MACR;AAAA,MACA,CAAC,KAAK,eAA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A;AAAA,MACA,QAAQ,WAAW,gBAAgB;AAAA,IACrC,CAAC;AAID,UAAM,iBAAiB,MAAM,QAAQ,WAAW,gBAAgB;AAChE,WAAO;AAAA,EACT,CAAC;AAGD,MAAI,oBAAoB,UAAU,YAAY;AAC5C,YAAQ,QAAQ,oBAAoB,eAAe;AACnD,WAAO;AAAA,EACT;AAEA,MAAI,OAAO,OAAO;AAGhB,QAAI,MAAM,oBAAoB,OAAO,KAAK,GAAG;AAC3C,aAAO;AAAA,IACT;AAKA,QAAI,QAAQ,QAAQ,cAAc,oBAAoB,IAAI,GAAG;AAI3D,YAAM,+BAA+B,IAAI;AAAA,QACvC,QAAQ;AAAA,MACV;AAEA,YAAM,UAAU,QAAQ,SAAS,sBAAsB;AAAA,QACrD,OAAO,OAAO;AAAA,QACd,SAAS,QAAQ;AAAA,QACjB,WAAW,QAAQ;AAAA,QACnB,YAAY;AAAA,MACd,CAAC,EAAE,KAAK,MAAM;AAKZ,YACE,6BAA6B,gBAAgB,EAAE,UAAU,WACzD;AACA,uCAA6B,gBAAgB,EAAE,QAAQ,MAAS;AAAA,QAClE;AAAA,MACF,CAAC;AAED,YAAM,aAAa,MAAM;AAAA,QACvB,MAAM,6BAA6B,gBAAgB;AAAA,MACrD;AASA,UAAI,WAAW,OAAO;AACpB,eAAO,oBAAoB,WAAW,KAAK;AAAA,MAC7C;AAEA,UAAI,WAAW,MAAM;AACnB,eAAO,eAAe,WAAW,IAAI;AAAA,MACvC;AAAA,IACF;AAGA,YAAQ,WAAW,0BAA0B,OAAO,KAAK,CAAC;AAC1D,WAAO;AAAA,EACT;AAQA,MAAI,OAAO,MAAM;AACf,WAAO,eAAe,OAAO,IAAI;AAAA,EACnC;AAIA,SAAO;AACT","sourcesContent":["import { invariant } from 'outvariant'\nimport { DeferredPromise } from '@open-draft/deferred-promise'\nimport { InterceptorError } from './InterceptorError'\n\nconst kRequestHandled = Symbol('kRequestHandled')\nexport const kResponsePromise = Symbol('kResponsePromise')\n\nexport class RequestController {\n /**\n * Internal response promise.\n * Available only for the library internals to grab the\n * response instance provided by the developer.\n * @note This promise cannot be rejected. It's either infinitely\n * pending or resolved with whichever Response was passed to `respondWith()`.\n */\n [kResponsePromise]: DeferredPromise<Response | Error | undefined>;\n\n /**\n * Internal flag indicating if this request has been handled.\n * @note The response promise becomes \"fulfilled\" on the next tick.\n */\n [kRequestHandled]: boolean\n\n constructor(private request: Request) {\n this[kRequestHandled] = false\n this[kResponsePromise] = new DeferredPromise()\n }\n\n /**\n * Respond to this request with the given `Response` instance.\n * @example\n * controller.respondWith(new Response())\n * controller.respondWith(Response.json({ id }))\n * controller.respondWith(Response.error())\n */\n public respondWith(response: Response): void {\n invariant.as(\n InterceptorError,\n !this[kRequestHandled],\n 'Failed to respond to the \"%s %s\" request: the \"request\" event has already been handled.',\n this.request.method,\n this.request.url\n )\n\n this[kRequestHandled] = true\n this[kResponsePromise].resolve(response)\n\n /**\n * @note The request conrtoller doesn't do anything\n * apart from letting the interceptor await the response\n * provided by the developer through the response promise.\n * Each interceptor implements the actual respondWith/errorWith\n * logic based on that interceptor's needs.\n */\n }\n\n /**\n * Error this request with the given error.\n * @example\n * controller.errorWith()\n * controller.errorWith(new Error('Oops!'))\n */\n public errorWith(error?: Error): void {\n invariant.as(\n InterceptorError,\n !this[kRequestHandled],\n 'Failed to error the \"%s %s\" request: the \"request\" event has already been handled.',\n this.request.method,\n this.request.url\n )\n\n this[kRequestHandled] = true\n\n /**\n * @note Resolve the response promise, not reject.\n * This helps us differentiate between unhandled exceptions\n * and intended errors (\"errorWith\") while waiting for the response.\n */\n this[kResponsePromise].resolve(error)\n }\n}\n","export class InterceptorError extends Error {\n constructor(message?: string) {\n super(message)\n this.name = 'InterceptorError'\n Object.setPrototypeOf(this, InterceptorError.prototype)\n }\n}\n","import { Emitter, EventMap } from 'strict-event-emitter'\n\n/**\n * Emits an event on the given emitter but executes\n * the listeners sequentially. This accounts for asynchronous\n * listeners (e.g. those having \"sleep\" and handling the request).\n */\nexport async function emitAsync<\n Events extends EventMap,\n EventName extends keyof Events\n>(\n emitter: Emitter<Events>,\n eventName: EventName,\n ...data: Events[EventName]\n): Promise<void> {\n const listners = emitter.listeners(eventName)\n\n if (listners.length === 0) {\n return\n }\n\n for (const listener of listners) {\n await listener.apply(emitter, data)\n }\n}\n","import type { Emitter } from 'strict-event-emitter'\nimport { DeferredPromise } from '@open-draft/deferred-promise'\nimport { until } from '@open-draft/until'\nimport type { HttpRequestEventMap } from '../glossary'\nimport { emitAsync } from './emitAsync'\nimport { kResponsePromise, RequestController } from '../RequestController'\nimport {\n createServerErrorResponse,\n isResponseError,\n ResponseError,\n} from './responseUtils'\nimport { InterceptorError } from '../InterceptorError'\nimport { isNodeLikeError } from './isNodeLikeError'\n\ninterface HandleRequestOptions {\n requestId: string\n request: Request\n emitter: Emitter<HttpRequestEventMap>\n controller: RequestController\n\n /**\n * Called when the request has been handled\n * with the given `Response` instance.\n */\n onResponse: (response: Response) => void | Promise<void>\n\n /**\n * Called when the request has been handled\n * with the given `Response.error()` instance.\n */\n onRequestError: (response: ResponseError) => void\n\n /**\n * Called when an unhandled error happens during the\n * request handling. This is never a thrown error/response.\n */\n onError: (error: unknown) => void\n}\n\n/**\n * @returns {Promise<boolean>} Indicates whether the request has been handled.\n */\nexport async function handleRequest(\n options: HandleRequestOptions\n): Promise<boolean> {\n const handleResponse = async (response: Response | Error) => {\n if (response instanceof Error) {\n options.onError(response)\n }\n\n // Handle \"Response.error()\" instances.\n else if (isResponseError(response)) {\n options.onRequestError(response)\n } else {\n await options.onResponse(response)\n }\n\n return true\n }\n\n const handleResponseError = async (error: unknown): Promise<boolean> => {\n // Forward the special interceptor error instances\n // to the developer. These must not be handled in any way.\n if (error instanceof InterceptorError) {\n throw result.error\n }\n\n // Support mocking Node.js-like errors.\n if (isNodeLikeError(error)) {\n options.onError(error)\n return true\n }\n\n // Handle thrown responses.\n if (error instanceof Response) {\n return await handleResponse(error)\n }\n\n return false\n }\n\n // Add the last \"request\" listener to check if the request\n // has been handled in any way. If it hasn't, resolve the\n // response promise with undefined.\n options.emitter.once('request', ({ requestId: pendingRequestId }) => {\n if (pendingRequestId !== options.requestId) {\n return\n }\n\n if (options.controller[kResponsePromise].state === 'pending') {\n options.controller[kResponsePromise].resolve(undefined)\n }\n })\n\n const requestAbortPromise = new DeferredPromise<void, unknown>()\n\n /**\n * @note `signal` is not always defined in React Native.\n */\n if (options.request.signal) {\n if (options.request.signal.aborted) {\n requestAbortPromise.reject(options.request.signal.reason)\n } else {\n options.request.signal.addEventListener(\n 'abort',\n () => {\n requestAbortPromise.reject(options.request.signal.reason)\n },\n { once: true }\n )\n }\n }\n\n const result = await until(async () => {\n // Emit the \"request\" event and wait until all the listeners\n // for that event are finished (e.g. async listeners awaited).\n // By the end of this promise, the developer cannot affect the\n // request anymore.\n const requestListtenersPromise = emitAsync(options.emitter, 'request', {\n requestId: options.requestId,\n request: options.request,\n controller: options.controller,\n })\n\n await Promise.race([\n // Short-circuit the request handling promise if the request gets aborted.\n requestAbortPromise,\n requestListtenersPromise,\n options.controller[kResponsePromise],\n ])\n\n // The response promise will settle immediately once\n // the developer calls either \"respondWith\" or \"errorWith\".\n const mockedResponse = await options.controller[kResponsePromise]\n return mockedResponse\n })\n\n // Handle the request being aborted while waiting for the request listeners.\n if (requestAbortPromise.state === 'rejected') {\n options.onError(requestAbortPromise.rejectionReason)\n return true\n }\n\n if (result.error) {\n // Handle the error during the request listener execution.\n // These can be thrown responses or request errors.\n if (await handleResponseError(result.error)) {\n return true\n }\n\n // If the developer has added \"unhandledException\" listeners,\n // allow them to handle the error. They can translate it to a\n // mocked response, network error, or forward it as-is.\n if (options.emitter.listenerCount('unhandledException') > 0) {\n // Create a new request controller just for the unhandled exception case.\n // This is needed because the original controller might have been already\n // interacted with (e.g. \"respondWith\" or \"errorWith\" called on it).\n const unhandledExceptionController = new RequestController(\n options.request\n )\n\n await emitAsync(options.emitter, 'unhandledException', {\n error: result.error,\n request: options.request,\n requestId: options.requestId,\n controller: unhandledExceptionController,\n }).then(() => {\n // If all the \"unhandledException\" listeners have finished\n // but have not handled the response in any way, preemptively\n // resolve the pending response promise from the new controller.\n // This prevents it from hanging forever.\n if (\n unhandledExceptionController[kResponsePromise].state === 'pending'\n ) {\n unhandledExceptionController[kResponsePromise].resolve(undefined)\n }\n })\n\n const nextResult = await until(\n () => unhandledExceptionController[kResponsePromise]\n )\n\n /**\n * @note Handle the result of the unhandled controller\n * in the same way as the original request controller.\n * The exception here is that thrown errors within the\n * \"unhandledException\" event do NOT result in another\n * emit of the same event. They are forwarded as-is.\n */\n if (nextResult.error) {\n return handleResponseError(nextResult.error)\n }\n\n if (nextResult.data) {\n return handleResponse(nextResult.data)\n }\n }\n\n // Otherwise, coerce unhandled exceptions to a 500 Internal Server Error response.\n options.onResponse(createServerErrorResponse(result.error))\n return true\n }\n\n /**\n * Handle a mocked Response instance.\n * @note That this can also be an Error in case\n * the developer called \"errorWith\". This differentiates\n * unhandled exceptions from intended errors.\n */\n if (result.data) {\n return handleResponse(result.data)\n }\n\n // In all other cases, consider the request unhandled.\n // The interceptor must perform it as-is.\n return false\n}\n","/**\n * A function that validates if property access is possible on an object\n * without throwing. It returns `true` if the property access is possible\n * and `false` otherwise.\n *\n * Environments like miniflare will throw on property access on certain objects\n * like Request and Response, for unimplemented properties.\n */\nexport function isPropertyAccessible<Obj extends Record<string, any>>(\n obj: Obj,\n key: keyof Obj\n) {\n try {\n obj[key]\n return true\n } catch {\n return false\n }\n}\n","import { isPropertyAccessible } from './isPropertyAccessible'\n\n/**\n * Creates a generic 500 Unhandled Exception response.\n */\nexport function createServerErrorResponse(body: unknown): Response {\n return new Response(\n JSON.stringify(\n body instanceof Error\n ? {\n name: body.name,\n message: body.message,\n stack: body.stack,\n }\n : body\n ),\n {\n status: 500,\n statusText: 'Unhandled Exception',\n headers: {\n 'Content-Type': 'application/json',\n },\n }\n )\n}\n\nexport type ResponseError = Response & { type: 'error' }\n\n/**\n * Check if the given response is a `Response.error()`.\n *\n * @note Some environments, like Miniflare (Cloudflare) do not\n * implement the \"Response.type\" property and throw on its access.\n * Safely check if we can access \"type\" on \"Response\" before continuing.\n * @see https://github.com/mswjs/msw/issues/1834\n */\nexport function isResponseError(response: Response): response is ResponseError {\n return isPropertyAccessible(response, 'type') && response.type === 'error'\n}\n","export function isNodeLikeError(\n error: unknown\n): error is NodeJS.ErrnoException {\n if (error == null) {\n return false\n }\n\n if (!(error instanceof Error)) {\n return false\n }\n\n return 'code' in error && 'errno' in error\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/RequestController.ts","../../src/InterceptorError.ts","../../src/utils/emitAsync.ts","../../src/utils/handleRequest.ts","../../src/utils/isPropertyAccessible.ts","../../src/utils/responseUtils.ts","../../src/utils/isNodeLikeError.ts"],"sourcesContent":["import { invariant } from 'outvariant'\nimport { DeferredPromise } from '@open-draft/deferred-promise'\nimport { InterceptorError } from './InterceptorError'\n\nconst kRequestHandled = Symbol('kRequestHandled')\nexport const kResponsePromise = Symbol('kResponsePromise')\n\nexport class RequestController {\n /**\n * Internal response promise.\n * Available only for the library internals to grab the\n * response instance provided by the developer.\n * @note This promise cannot be rejected. It's either infinitely\n * pending or resolved with whichever Response was passed to `respondWith()`.\n */\n [kResponsePromise]: DeferredPromise<Response | Error | undefined>;\n\n /**\n * Internal flag indicating if this request has been handled.\n * @note The response promise becomes \"fulfilled\" on the next tick.\n */\n [kRequestHandled]: boolean\n\n constructor(private request: Request) {\n this[kRequestHandled] = false\n this[kResponsePromise] = new DeferredPromise()\n }\n\n /**\n * Respond to this request with the given `Response` instance.\n * @example\n * controller.respondWith(new Response())\n * controller.respondWith(Response.json({ id }))\n * controller.respondWith(Response.error())\n */\n public respondWith(response: Response): void {\n invariant.as(\n InterceptorError,\n !this[kRequestHandled],\n 'Failed to respond to the \"%s %s\" request: the \"request\" event has already been handled.',\n this.request.method,\n this.request.url\n )\n\n this[kRequestHandled] = true\n this[kResponsePromise].resolve(response)\n\n /**\n * @note The request conrtoller doesn't do anything\n * apart from letting the interceptor await the response\n * provided by the developer through the response promise.\n * Each interceptor implements the actual respondWith/errorWith\n * logic based on that interceptor's needs.\n */\n }\n\n /**\n * Error this request with the given error.\n * @example\n * controller.errorWith()\n * controller.errorWith(new Error('Oops!'))\n */\n public errorWith(error?: Error): void {\n invariant.as(\n InterceptorError,\n !this[kRequestHandled],\n 'Failed to error the \"%s %s\" request: the \"request\" event has already been handled.',\n this.request.method,\n this.request.url\n )\n\n this[kRequestHandled] = true\n\n /**\n * @note Resolve the response promise, not reject.\n * This helps us differentiate between unhandled exceptions\n * and intended errors (\"errorWith\") while waiting for the response.\n */\n this[kResponsePromise].resolve(error)\n }\n}\n","export class InterceptorError extends Error {\n constructor(message?: string) {\n super(message)\n this.name = 'InterceptorError'\n Object.setPrototypeOf(this, InterceptorError.prototype)\n }\n}\n","import { Emitter, EventMap } from 'strict-event-emitter'\n\n/**\n * Emits an event on the given emitter but executes\n * the listeners sequentially. This accounts for asynchronous\n * listeners (e.g. those having \"sleep\" and handling the request).\n */\nexport async function emitAsync<\n Events extends EventMap,\n EventName extends keyof Events\n>(\n emitter: Emitter<Events>,\n eventName: EventName,\n ...data: Events[EventName]\n): Promise<void> {\n const listners = emitter.listeners(eventName)\n\n if (listners.length === 0) {\n return\n }\n\n for (const listener of listners) {\n await listener.apply(emitter, data)\n }\n}\n","import type { Emitter } from 'strict-event-emitter'\nimport { DeferredPromise } from '@open-draft/deferred-promise'\nimport { until } from '@open-draft/until'\nimport type { HttpRequestEventMap } from '../glossary'\nimport { emitAsync } from './emitAsync'\nimport { kResponsePromise, RequestController } from '../RequestController'\nimport {\n createServerErrorResponse,\n isResponseError,\n ResponseError,\n} from './responseUtils'\nimport { InterceptorError } from '../InterceptorError'\nimport { isNodeLikeError } from './isNodeLikeError'\n\ninterface HandleRequestOptions {\n requestId: string\n request: Request\n emitter: Emitter<HttpRequestEventMap>\n controller: RequestController\n\n /**\n * Called when the request has been handled\n * with the given `Response` instance.\n */\n onResponse: (response: Response) => void | Promise<void>\n\n /**\n * Called when the request has been handled\n * with the given `Response.error()` instance.\n */\n onRequestError: (response: ResponseError) => void\n\n /**\n * Called when an unhandled error happens during the\n * request handling. This is never a thrown error/response.\n */\n onError: (error: unknown) => void\n}\n\n/**\n * @returns {Promise<boolean>} Indicates whether the request has been handled.\n */\nexport async function handleRequest(\n options: HandleRequestOptions\n): Promise<boolean> {\n const handleResponse = async (response: Response | Error) => {\n if (response instanceof Error) {\n options.onError(response)\n }\n\n // Handle \"Response.error()\" instances.\n else if (isResponseError(response)) {\n options.onRequestError(response)\n } else {\n await options.onResponse(response)\n }\n\n return true\n }\n\n const handleResponseError = async (error: unknown): Promise<boolean> => {\n // Forward the special interceptor error instances\n // to the developer. These must not be handled in any way.\n if (error instanceof InterceptorError) {\n throw result.error\n }\n\n // Support mocking Node.js-like errors.\n if (isNodeLikeError(error)) {\n options.onError(error)\n return true\n }\n\n // Handle thrown responses.\n if (error instanceof Response) {\n return await handleResponse(error)\n }\n\n return false\n }\n\n // Add the last \"request\" listener to check if the request\n // has been handled in any way. If it hasn't, resolve the\n // response promise with undefined.\n options.emitter.once('request', ({ requestId: pendingRequestId }) => {\n if (pendingRequestId !== options.requestId) {\n return\n }\n\n if (options.controller[kResponsePromise].state === 'pending') {\n options.controller[kResponsePromise].resolve(undefined)\n }\n })\n\n const requestAbortPromise = new DeferredPromise<void, unknown>()\n\n /**\n * @note `signal` is not always defined in React Native.\n */\n if (options.request.signal) {\n if (options.request.signal.aborted) {\n requestAbortPromise.reject(options.request.signal.reason)\n } else {\n options.request.signal.addEventListener(\n 'abort',\n () => {\n requestAbortPromise.reject(options.request.signal.reason)\n },\n { once: true }\n )\n }\n }\n\n const result = await until(async () => {\n // Emit the \"request\" event and wait until all the listeners\n // for that event are finished (e.g. async listeners awaited).\n // By the end of this promise, the developer cannot affect the\n // request anymore.\n const requestListtenersPromise = emitAsync(options.emitter, 'request', {\n requestId: options.requestId,\n request: options.request,\n controller: options.controller,\n })\n\n await Promise.race([\n // Short-circuit the request handling promise if the request gets aborted.\n requestAbortPromise,\n requestListtenersPromise,\n options.controller[kResponsePromise],\n ])\n\n // The response promise will settle immediately once\n // the developer calls either \"respondWith\" or \"errorWith\".\n const mockedResponse = await options.controller[kResponsePromise]\n return mockedResponse\n })\n\n // Handle the request being aborted while waiting for the request listeners.\n if (requestAbortPromise.state === 'rejected') {\n options.onError(requestAbortPromise.rejectionReason)\n return true\n }\n\n if (result.error) {\n // Handle the error during the request listener execution.\n // These can be thrown responses or request errors.\n if (await handleResponseError(result.error)) {\n return true\n }\n\n // If the developer has added \"unhandledException\" listeners,\n // allow them to handle the error. They can translate it to a\n // mocked response, network error, or forward it as-is.\n if (options.emitter.listenerCount('unhandledException') > 0) {\n // Create a new request controller just for the unhandled exception case.\n // This is needed because the original controller might have been already\n // interacted with (e.g. \"respondWith\" or \"errorWith\" called on it).\n const unhandledExceptionController = new RequestController(\n options.request\n )\n\n await emitAsync(options.emitter, 'unhandledException', {\n error: result.error,\n request: options.request,\n requestId: options.requestId,\n controller: unhandledExceptionController,\n }).then(() => {\n // If all the \"unhandledException\" listeners have finished\n // but have not handled the response in any way, preemptively\n // resolve the pending response promise from the new controller.\n // This prevents it from hanging forever.\n if (\n unhandledExceptionController[kResponsePromise].state === 'pending'\n ) {\n unhandledExceptionController[kResponsePromise].resolve(undefined)\n }\n })\n\n const nextResult = await until(\n () => unhandledExceptionController[kResponsePromise]\n )\n\n /**\n * @note Handle the result of the unhandled controller\n * in the same way as the original request controller.\n * The exception here is that thrown errors within the\n * \"unhandledException\" event do NOT result in another\n * emit of the same event. They are forwarded as-is.\n */\n if (nextResult.error) {\n return handleResponseError(nextResult.error)\n }\n\n if (nextResult.data) {\n return handleResponse(nextResult.data)\n }\n }\n\n // Otherwise, coerce unhandled exceptions to a 500 Internal Server Error response.\n options.onResponse(createServerErrorResponse(result.error))\n return true\n }\n\n /**\n * Handle a mocked Response instance.\n * @note That this can also be an Error in case\n * the developer called \"errorWith\". This differentiates\n * unhandled exceptions from intended errors.\n */\n if (result.data) {\n return handleResponse(result.data)\n }\n\n // In all other cases, consider the request unhandled.\n // The interceptor must perform it as-is.\n return false\n}\n","/**\n * A function that validates if property access is possible on an object\n * without throwing. It returns `true` if the property access is possible\n * and `false` otherwise.\n *\n * Environments like miniflare will throw on property access on certain objects\n * like Request and Response, for unimplemented properties.\n */\nexport function isPropertyAccessible<Obj extends Record<string, any>>(\n obj: Obj,\n key: keyof Obj\n) {\n try {\n obj[key]\n return true\n } catch {\n return false\n }\n}\n","import { isPropertyAccessible } from './isPropertyAccessible'\n\n/**\n * Creates a generic 500 Unhandled Exception response.\n */\nexport function createServerErrorResponse(body: unknown): Response {\n return new Response(\n JSON.stringify(\n body instanceof Error\n ? {\n name: body.name,\n message: body.message,\n stack: body.stack,\n }\n : body\n ),\n {\n status: 500,\n statusText: 'Unhandled Exception',\n headers: {\n 'Content-Type': 'application/json',\n },\n }\n )\n}\n\nexport type ResponseError = Response & { type: 'error' }\n\n/**\n * Check if the given response is a `Response.error()`.\n *\n * @note Some environments, like Miniflare (Cloudflare) do not\n * implement the \"Response.type\" property and throw on its access.\n * Safely check if we can access \"type\" on \"Response\" before continuing.\n * @see https://github.com/mswjs/msw/issues/1834\n */\nexport function isResponseError(response: Response): response is ResponseError {\n return isPropertyAccessible(response, 'type') && response.type === 'error'\n}\n","export function isNodeLikeError(\n error: unknown\n): error is NodeJS.ErrnoException {\n if (error == null) {\n return false\n }\n\n if (!(error instanceof Error)) {\n return false\n }\n\n return 'code' in error && 'errno' in error\n}\n"],"mappings":";AAAA,SAAS,iBAAiB;AAC1B,SAAS,uBAAuB;;;ACDzB,IAAM,mBAAN,cAA+B,MAAM;AAAA,EAC1C,YAAY,SAAkB;AAC5B,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,WAAO,eAAe,MAAM,iBAAiB,SAAS;AAAA,EACxD;AACF;;;ADFA,IAAM,kBAAkB,OAAO,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