@mswjs/interceptors 0.41.9 → 0.42.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (335) hide show
  1. package/README.md +274 -228
  2. package/lib/browser/{bufferUtils-BiiO6HZv.mjs → buffer-utils-DJj7YzLG.js} +3 -3
  3. package/lib/browser/buffer-utils-DJj7YzLG.js.map +1 -0
  4. package/lib/browser/create-request-id-Bk5YX1AM.js +720 -0
  5. package/lib/browser/create-request-id-Bk5YX1AM.js.map +1 -0
  6. package/lib/browser/{getRawRequest-B1BqgWG6.mjs → fetch-utils-CUOrwEQf.js} +123 -52
  7. package/lib/browser/fetch-utils-CUOrwEQf.js.map +1 -0
  8. package/lib/browser/handle-request-CqVvBhcw.js +167 -0
  9. package/lib/browser/handle-request-CqVvBhcw.js.map +1 -0
  10. package/lib/{node/hasConfigurableGlobal-BiTmog1u.mjs → browser/has-configurable-global-Cew-dYqk.js} +5 -7
  11. package/lib/browser/has-configurable-global-Cew-dYqk.js.map +1 -0
  12. package/lib/browser/http-CB9rQ7i_.d.ts +105 -0
  13. package/lib/browser/{index.d.cts → index.d.ts} +33 -38
  14. package/lib/browser/index.js +130 -0
  15. package/lib/browser/index.js.map +1 -0
  16. package/lib/browser/interceptor-dtJZ_9QT.d.ts +50 -0
  17. package/lib/browser/interceptors/WebSocket/index.d.ts +2 -0
  18. package/lib/browser/interceptors/WebSocket/{index.mjs → index.js} +39 -30
  19. package/lib/browser/interceptors/WebSocket/index.js.map +1 -0
  20. package/lib/browser/interceptors/XMLHttpRequest/web.d.ts +11 -0
  21. package/lib/browser/interceptors/XMLHttpRequest/web.js +2 -0
  22. package/lib/browser/interceptors/fetch/web.d.ts +14 -0
  23. package/lib/browser/interceptors/fetch/web.js +2 -0
  24. package/lib/browser/presets/browser.d.ts +11 -0
  25. package/lib/browser/presets/browser.js +12 -0
  26. package/lib/browser/presets/browser.js.map +1 -0
  27. package/lib/browser/{resolveWebSocketUrl-C83-x9iE.mjs → resolve-web-socket-url-CSvNPLGi.js} +3 -3
  28. package/lib/browser/resolve-web-socket-url-CSvNPLGi.js.map +1 -0
  29. package/lib/browser/{XMLHttpRequest-DrZAf3w6.mjs → web-BcKSQghf.js} +327 -255
  30. package/lib/browser/web-BcKSQghf.js.map +1 -0
  31. package/lib/browser/web-CdcYFjgm.js +248 -0
  32. package/lib/browser/web-CdcYFjgm.js.map +1 -0
  33. package/lib/browser/{interceptors/WebSocket/index.d.cts → websocket-CC0nB0md.d.ts} +41 -33
  34. package/lib/node/batch-interceptor-ByEZVih3.js +119 -0
  35. package/lib/node/batch-interceptor-ByEZVih3.js.map +1 -0
  36. package/lib/node/batch-interceptor-CPjFK2td.d.ts +28 -0
  37. package/lib/node/buffer-utils-BvPY1Tc-.js +187 -0
  38. package/lib/node/buffer-utils-BvPY1Tc-.js.map +1 -0
  39. package/lib/node/fetch-utils-Dw1PsmtX.js +568 -0
  40. package/lib/node/fetch-utils-Dw1PsmtX.js.map +1 -0
  41. package/lib/node/has-configurable-global-CJCh_g1I.js +22 -0
  42. package/lib/node/has-configurable-global-CJCh_g1I.js.map +1 -0
  43. package/lib/node/http-CB9rQ7i_.d.ts +105 -0
  44. package/lib/{browser/interceptors/WebSocket/index.d.mts → node/index.d.ts} +120 -60
  45. package/lib/node/{index.mjs → index.js} +8 -11
  46. package/lib/node/index.js.map +1 -0
  47. package/lib/node/interceptor-dtJZ_9QT.d.ts +50 -0
  48. package/lib/node/interceptors/ClientRequest/index.d.ts +14 -0
  49. package/lib/node/interceptors/ClientRequest/index.js +67 -0
  50. package/lib/node/interceptors/ClientRequest/index.js.map +1 -0
  51. package/lib/node/interceptors/XMLHttpRequest/node.d.ts +12 -0
  52. package/lib/node/interceptors/XMLHttpRequest/node.js +74 -0
  53. package/lib/node/interceptors/XMLHttpRequest/node.js.map +1 -0
  54. package/lib/node/interceptors/fetch/node.d.ts +18 -0
  55. package/lib/node/interceptors/fetch/node.js +83 -0
  56. package/lib/node/interceptors/fetch/node.js.map +1 -0
  57. package/lib/node/interceptors/http/index.d.ts +14 -0
  58. package/lib/node/interceptors/http/index.js +32 -0
  59. package/lib/node/interceptors/http/index.js.map +1 -0
  60. package/lib/node/interceptors/net/index.d.ts +203 -0
  61. package/lib/node/interceptors/net/index.js +2 -0
  62. package/lib/node/llhttp/constants.cjs +485 -0
  63. package/lib/node/llhttp/constants.d.cts +957 -0
  64. package/lib/node/llhttp/llhttp.wasm +0 -0
  65. package/lib/node/net-DtMnyEeg.js +1388 -0
  66. package/lib/node/net-DtMnyEeg.js.map +1 -0
  67. package/lib/node/presets/node.d.ts +12 -0
  68. package/lib/node/presets/node.js +17 -0
  69. package/lib/node/presets/node.js.map +1 -0
  70. package/lib/node/{RemoteHttpInterceptor.d.cts → remote-http-interceptor.d.ts} +12 -11
  71. package/lib/node/{RemoteHttpInterceptor.mjs → remote-http-interceptor.js} +38 -33
  72. package/lib/node/remote-http-interceptor.js.map +1 -0
  73. package/lib/node/source-lP0yyEtA.js +1990 -0
  74. package/lib/node/source-lP0yyEtA.js.map +1 -0
  75. package/package.json +79 -118
  76. package/src/batch-interceptor.test.ts +475 -0
  77. package/src/batch-interceptor.ts +244 -0
  78. package/src/{createRequestId.test.ts → create-request-id.test.ts} +1 -2
  79. package/src/disposable.ts +13 -0
  80. package/src/events/http.ts +92 -0
  81. package/src/events/websocket.ts +47 -0
  82. package/src/glossary.ts +1 -27
  83. package/src/index.ts +18 -10
  84. package/src/interceptor.test.ts +279 -0
  85. package/src/interceptor.ts +139 -0
  86. package/src/interceptors/ClientRequest/index.test.ts +21 -39
  87. package/src/interceptors/ClientRequest/index.ts +64 -179
  88. package/src/interceptors/ClientRequest/utils/{recordRawHeaders.test.ts → record-raw-headers.test.ts} +1 -2
  89. package/src/interceptors/ClientRequest/utils/{recordRawHeaders.ts → record-raw-headers.ts} +29 -2
  90. package/src/interceptors/WebSocket/index.ts +33 -50
  91. package/src/interceptors/WebSocket/utils/{bindEvent.test.ts → bind-event.test.ts} +1 -2
  92. package/src/interceptors/WebSocket/utils/events.test.ts +0 -1
  93. package/src/interceptors/WebSocket/{WebSocketClassTransport.ts → web-socket-class-transport.ts} +3 -3
  94. package/src/interceptors/WebSocket/{WebSocketClientConnection.ts → web-socket-client-connection.ts} +4 -4
  95. package/src/interceptors/WebSocket/{WebSocketOverride.ts → web-socket-override.ts} +6 -7
  96. package/src/interceptors/WebSocket/{WebSocketServerConnection.ts → web-socket-server-connection.ts} +4 -4
  97. package/src/interceptors/WebSocket/{WebSocketTransport.ts → web-socket-transport.ts} +1 -1
  98. package/src/interceptors/XMLHttpRequest/node.ts +104 -0
  99. package/src/interceptors/XMLHttpRequest/polyfills/{ProgressEventPolyfill.ts → progress-event-polyfill.ts} +1 -1
  100. package/src/interceptors/XMLHttpRequest/utils/{concateArrayBuffer.test.ts → concat-array-buffer.test.ts} +1 -2
  101. package/src/interceptors/XMLHttpRequest/utils/{concatArrayBuffer.ts → concat-array-buffer.ts} +1 -1
  102. package/src/interceptors/XMLHttpRequest/utils/{createEvent.test.ts → create-event.test.ts} +3 -4
  103. package/src/interceptors/XMLHttpRequest/utils/{createEvent.ts → create-event.ts} +2 -2
  104. package/src/interceptors/XMLHttpRequest/utils/{createResponse.ts → create-response.ts} +1 -1
  105. package/src/interceptors/XMLHttpRequest/utils/{getBodyByteLength.test.ts → get-body-byte-length.test.ts} +1 -2
  106. package/src/interceptors/XMLHttpRequest/web.ts +34 -0
  107. package/src/interceptors/XMLHttpRequest/{XMLHttpRequestController.ts → xml-http-request-controller.ts} +363 -204
  108. package/src/interceptors/XMLHttpRequest/{XMLHttpRequestProxy.ts → xml-http-request-proxy.ts} +28 -25
  109. package/src/interceptors/fetch/node.ts +103 -0
  110. package/src/interceptors/fetch/utils/{followRedirect.ts → follow-redirect.ts} +1 -1
  111. package/src/interceptors/fetch/web.ts +217 -0
  112. package/src/interceptors/http/forward-events.test.ts +86 -0
  113. package/src/interceptors/http/forward-events.ts +139 -0
  114. package/src/interceptors/http/http-parser/index.ts +310 -0
  115. package/src/interceptors/http/http-parser/llhttp/constants.cjs +485 -0
  116. package/src/interceptors/http/http-parser/llhttp/constants.d.cts +957 -0
  117. package/src/interceptors/http/http-parser/llhttp/llhttp.wasm +0 -0
  118. package/src/interceptors/http/http-parser.ts +138 -0
  119. package/src/interceptors/http/index.ts +34 -0
  120. package/src/interceptors/http/source.ts +688 -0
  121. package/src/interceptors/net/index.ts +368 -0
  122. package/src/interceptors/net/socket-controller.ts +1476 -0
  123. package/src/interceptors/net/utils/address-info.ts +54 -0
  124. package/src/interceptors/net/utils/connection-options-to-url.ts +56 -0
  125. package/src/interceptors/net/utils/flush-writes.ts +57 -0
  126. package/src/interceptors/net/utils/get-tls-connect-options.ts +23 -0
  127. package/src/interceptors/net/utils/normalize-net-connect-args.test.ts +233 -0
  128. package/src/interceptors/net/utils/normalize-net-connect-args.ts +121 -0
  129. package/src/interceptors/net/utils/normalize-tls-connect-args.ts +50 -0
  130. package/src/presets/browser.ts +4 -4
  131. package/src/presets/node.ts +4 -4
  132. package/src/{RemoteHttpInterceptor.ts → remote-http-interceptor.ts} +55 -42
  133. package/src/request-context.ts +40 -0
  134. package/src/{RequestController.test.ts → request-controller.test.ts} +37 -3
  135. package/src/{RequestController.ts → request-controller.ts} +33 -11
  136. package/src/utils/{bufferUtils.test.ts → buffer-utils.test.ts} +1 -2
  137. package/src/utils/buffer-utils.ts +37 -0
  138. package/src/utils/{cloneObject.test.ts → clone-object.test.ts} +1 -2
  139. package/src/utils/{cloneObject.ts → clone-object.ts} +8 -8
  140. package/src/utils/{createProxy.test.ts → create-proxy.test.ts} +6 -4
  141. package/src/utils/{createProxy.ts → create-proxy.ts} +1 -1
  142. package/src/utils/{fetchUtils.test.ts → fetch-utils.test.ts} +1 -1
  143. package/src/utils/{fetchUtils.ts → fetch-utils.ts} +28 -3
  144. package/src/utils/{findPropertySource.test.ts → find-property-source.test.ts} +1 -2
  145. package/src/utils/{getCleanUrl.test.ts → get-clean-url.test.ts} +1 -2
  146. package/src/utils/{getUrlByRequestOptions.test.ts → get-url-by-request-options.test.ts} +4 -8
  147. package/src/utils/{getUrlByRequestOptions.ts → get-url-by-request-options.ts} +16 -16
  148. package/src/utils/{getValueBySymbol.test.ts → get-value-by-symbol.test.ts} +1 -2
  149. package/src/utils/{handleRequest.ts → handle-request.ts} +61 -41
  150. package/src/utils/{hasConfigurableGlobal.test.ts → has-configurable-global.test.ts} +1 -2
  151. package/src/utils/{hasConfigurableGlobal.ts → has-configurable-global.ts} +2 -4
  152. package/src/utils/{isObject.test.ts → is-object.test.ts} +1 -2
  153. package/src/utils/logger.test.ts +154 -0
  154. package/src/utils/logger.ts +154 -0
  155. package/src/utils/{parseJson.test.ts → parse-json.test.ts} +1 -2
  156. package/src/utils/{patchesRegistry.test.ts → patches-registry.test.ts} +1 -1
  157. package/src/utils/{patchesRegistry.ts → patches-registry.ts} +1 -1
  158. package/src/utils/{responseUtils.ts → response-utils.ts} +25 -2
  159. package/ClientRequest/package.json +0 -11
  160. package/RemoteHttpInterceptor/package.json +0 -11
  161. package/WebSocket/package.json +0 -12
  162. package/XMLHttpRequest/package.json +0 -12
  163. package/fetch/package.json +0 -12
  164. package/lib/browser/Interceptor-Deczogc8.d.cts +0 -65
  165. package/lib/browser/Interceptor-gqKgs-aF.d.mts +0 -65
  166. package/lib/browser/XMLHttpRequest-DrZAf3w6.mjs.map +0 -1
  167. package/lib/browser/XMLHttpRequest-gXuzzX1g.cjs +0 -751
  168. package/lib/browser/XMLHttpRequest-gXuzzX1g.cjs.map +0 -1
  169. package/lib/browser/bufferUtils-BiiO6HZv.mjs.map +0 -1
  170. package/lib/browser/bufferUtils-Uc0eRItL.cjs +0 -38
  171. package/lib/browser/bufferUtils-Uc0eRItL.cjs.map +0 -1
  172. package/lib/browser/createRequestId-DOf8Ktjs.cjs +0 -205
  173. package/lib/browser/createRequestId-DOf8Ktjs.cjs.map +0 -1
  174. package/lib/browser/createRequestId-DYCsFHOi.mjs +0 -170
  175. package/lib/browser/createRequestId-DYCsFHOi.mjs.map +0 -1
  176. package/lib/browser/fetch-5IMPqr9e.mjs +0 -236
  177. package/lib/browser/fetch-5IMPqr9e.mjs.map +0 -1
  178. package/lib/browser/fetch-Bt9rMY9c.cjs +0 -241
  179. package/lib/browser/fetch-Bt9rMY9c.cjs.map +0 -1
  180. package/lib/browser/getRawRequest-B1BqgWG6.mjs.map +0 -1
  181. package/lib/browser/getRawRequest-DdfaiPVH.cjs +0 -376
  182. package/lib/browser/getRawRequest-DdfaiPVH.cjs.map +0 -1
  183. package/lib/browser/glossary-1lhZx6Aw.d.cts +0 -69
  184. package/lib/browser/glossary-nkHWcwvY.d.mts +0 -69
  185. package/lib/browser/handleRequest-CJim54xG.cjs +0 -191
  186. package/lib/browser/handleRequest-CJim54xG.cjs.map +0 -1
  187. package/lib/browser/handleRequest-CPPgsG7s.mjs +0 -180
  188. package/lib/browser/handleRequest-CPPgsG7s.mjs.map +0 -1
  189. package/lib/browser/hasConfigurableGlobal-C8zq1MCg.mjs +0 -109
  190. package/lib/browser/hasConfigurableGlobal-C8zq1MCg.mjs.map +0 -1
  191. package/lib/browser/hasConfigurableGlobal-CS7adEvV.cjs +0 -126
  192. package/lib/browser/hasConfigurableGlobal-CS7adEvV.cjs.map +0 -1
  193. package/lib/browser/index.cjs +0 -70
  194. package/lib/browser/index.cjs.map +0 -1
  195. package/lib/browser/index.d.mts +0 -125
  196. package/lib/browser/index.mjs +0 -56
  197. package/lib/browser/index.mjs.map +0 -1
  198. package/lib/browser/interceptors/WebSocket/index.cjs +0 -618
  199. package/lib/browser/interceptors/WebSocket/index.cjs.map +0 -1
  200. package/lib/browser/interceptors/WebSocket/index.mjs.map +0 -1
  201. package/lib/browser/interceptors/XMLHttpRequest/index.cjs +0 -8
  202. package/lib/browser/interceptors/XMLHttpRequest/index.d.cts +0 -15
  203. package/lib/browser/interceptors/XMLHttpRequest/index.d.mts +0 -15
  204. package/lib/browser/interceptors/XMLHttpRequest/index.mjs +0 -8
  205. package/lib/browser/interceptors/fetch/index.cjs +0 -7
  206. package/lib/browser/interceptors/fetch/index.d.cts +0 -13
  207. package/lib/browser/interceptors/fetch/index.d.mts +0 -13
  208. package/lib/browser/interceptors/fetch/index.mjs +0 -7
  209. package/lib/browser/presets/browser.cjs +0 -18
  210. package/lib/browser/presets/browser.cjs.map +0 -1
  211. package/lib/browser/presets/browser.d.cts +0 -12
  212. package/lib/browser/presets/browser.d.mts +0 -14
  213. package/lib/browser/presets/browser.mjs +0 -18
  214. package/lib/browser/presets/browser.mjs.map +0 -1
  215. package/lib/browser/resolveWebSocketUrl-6K6EgqsA.cjs +0 -31
  216. package/lib/browser/resolveWebSocketUrl-6K6EgqsA.cjs.map +0 -1
  217. package/lib/browser/resolveWebSocketUrl-C83-x9iE.mjs.map +0 -1
  218. package/lib/node/BatchInterceptor-BGhH8z1z.cjs +0 -49
  219. package/lib/node/BatchInterceptor-BGhH8z1z.cjs.map +0 -1
  220. package/lib/node/BatchInterceptor-C4-RX5rg.mjs +0 -44
  221. package/lib/node/BatchInterceptor-C4-RX5rg.mjs.map +0 -1
  222. package/lib/node/BatchInterceptor-KKF8Q47I.d.cts +0 -26
  223. package/lib/node/BatchInterceptor-rSr-NH_H.d.mts +0 -26
  224. package/lib/node/ClientRequest-2loAH7xM.cjs +0 -1058
  225. package/lib/node/ClientRequest-2loAH7xM.cjs.map +0 -1
  226. package/lib/node/ClientRequest-DGhBX21V.mjs +0 -1049
  227. package/lib/node/ClientRequest-DGhBX21V.mjs.map +0 -1
  228. package/lib/node/Interceptor-BsZ21ue0.d.cts +0 -132
  229. package/lib/node/Interceptor-soD-WpQO.d.mts +0 -132
  230. package/lib/node/RemoteHttpInterceptor.cjs +0 -155
  231. package/lib/node/RemoteHttpInterceptor.cjs.map +0 -1
  232. package/lib/node/RemoteHttpInterceptor.d.mts +0 -39
  233. package/lib/node/RemoteHttpInterceptor.mjs.map +0 -1
  234. package/lib/node/XMLHttpRequest-BtDNZipW.cjs +0 -752
  235. package/lib/node/XMLHttpRequest-BtDNZipW.cjs.map +0 -1
  236. package/lib/node/XMLHttpRequest-Dw6Wm-UU.mjs +0 -746
  237. package/lib/node/XMLHttpRequest-Dw6Wm-UU.mjs.map +0 -1
  238. package/lib/node/bufferUtils-DxPxwff_.mjs +0 -20
  239. package/lib/node/bufferUtils-DxPxwff_.mjs.map +0 -1
  240. package/lib/node/bufferUtils-S5_-2eN4.cjs +0 -38
  241. package/lib/node/bufferUtils-S5_-2eN4.cjs.map +0 -1
  242. package/lib/node/chunk-CbDLau6x.cjs +0 -34
  243. package/lib/node/fetch-CaC3rGEu.mjs +0 -252
  244. package/lib/node/fetch-CaC3rGEu.mjs.map +0 -1
  245. package/lib/node/fetch-D2ClLNN-.cjs +0 -259
  246. package/lib/node/fetch-D2ClLNN-.cjs.map +0 -1
  247. package/lib/node/fetchUtils-BKJ1XmiO.mjs +0 -480
  248. package/lib/node/fetchUtils-BKJ1XmiO.mjs.map +0 -1
  249. package/lib/node/fetchUtils-umV5xXBy.cjs +0 -546
  250. package/lib/node/fetchUtils-umV5xXBy.cjs.map +0 -1
  251. package/lib/node/getRawRequest-B6znU6il.cjs +0 -36
  252. package/lib/node/getRawRequest-B6znU6il.cjs.map +0 -1
  253. package/lib/node/getRawRequest-C2-1urzA.mjs +0 -24
  254. package/lib/node/getRawRequest-C2-1urzA.mjs.map +0 -1
  255. package/lib/node/handleRequest-C-cKYjIh.cjs +0 -222
  256. package/lib/node/handleRequest-C-cKYjIh.cjs.map +0 -1
  257. package/lib/node/handleRequest-FIQv5pwH.mjs +0 -192
  258. package/lib/node/handleRequest-FIQv5pwH.mjs.map +0 -1
  259. package/lib/node/hasConfigurableGlobal-BiTmog1u.mjs.map +0 -1
  260. package/lib/node/hasConfigurableGlobal-MjY06_Ok.cjs +0 -108
  261. package/lib/node/hasConfigurableGlobal-MjY06_Ok.cjs.map +0 -1
  262. package/lib/node/index-BJ5E5aW-.d.cts +0 -113
  263. package/lib/node/index-DfoF45ih.d.mts +0 -113
  264. package/lib/node/index.cjs +0 -53
  265. package/lib/node/index.cjs.map +0 -1
  266. package/lib/node/index.d.cts +0 -104
  267. package/lib/node/index.d.mts +0 -104
  268. package/lib/node/index.mjs.map +0 -1
  269. package/lib/node/interceptors/ClientRequest/index.cjs +0 -6
  270. package/lib/node/interceptors/ClientRequest/index.d.cts +0 -2
  271. package/lib/node/interceptors/ClientRequest/index.d.mts +0 -3
  272. package/lib/node/interceptors/ClientRequest/index.mjs +0 -6
  273. package/lib/node/interceptors/XMLHttpRequest/index.cjs +0 -7
  274. package/lib/node/interceptors/XMLHttpRequest/index.d.cts +0 -14
  275. package/lib/node/interceptors/XMLHttpRequest/index.d.mts +0 -14
  276. package/lib/node/interceptors/XMLHttpRequest/index.mjs +0 -7
  277. package/lib/node/interceptors/fetch/index.cjs +0 -6
  278. package/lib/node/interceptors/fetch/index.d.cts +0 -12
  279. package/lib/node/interceptors/fetch/index.d.mts +0 -12
  280. package/lib/node/interceptors/fetch/index.mjs +0 -6
  281. package/lib/node/node-DIKcnzhK.cjs +0 -39
  282. package/lib/node/node-DIKcnzhK.cjs.map +0 -1
  283. package/lib/node/node-lsdNwZEW.mjs +0 -27
  284. package/lib/node/node-lsdNwZEW.mjs.map +0 -1
  285. package/lib/node/presets/node.cjs +0 -23
  286. package/lib/node/presets/node.cjs.map +0 -1
  287. package/lib/node/presets/node.d.cts +0 -13
  288. package/lib/node/presets/node.d.mts +0 -15
  289. package/lib/node/presets/node.mjs +0 -23
  290. package/lib/node/presets/node.mjs.map +0 -1
  291. package/lib/node/utils/node/index.cjs +0 -4
  292. package/lib/node/utils/node/index.d.cts +0 -16
  293. package/lib/node/utils/node/index.d.mts +0 -16
  294. package/lib/node/utils/node/index.mjs +0 -3
  295. package/presets/browser/package.json +0 -5
  296. package/presets/node/package.json +0 -11
  297. package/src/BatchInterceptor.test.ts +0 -255
  298. package/src/BatchInterceptor.ts +0 -96
  299. package/src/Interceptor.test.ts +0 -205
  300. package/src/Interceptor.ts +0 -249
  301. package/src/getRawRequest.ts +0 -21
  302. package/src/interceptors/ClientRequest/MockHttpSocket.ts +0 -724
  303. package/src/interceptors/ClientRequest/agents.ts +0 -110
  304. package/src/interceptors/ClientRequest/utils/getIncomingMessageBody.test.ts +0 -54
  305. package/src/interceptors/ClientRequest/utils/getIncomingMessageBody.ts +0 -45
  306. package/src/interceptors/ClientRequest/utils/normalizeClientRequestArgs.test.ts +0 -427
  307. package/src/interceptors/ClientRequest/utils/normalizeClientRequestArgs.ts +0 -268
  308. package/src/interceptors/ClientRequest/utils/parserUtils.ts +0 -48
  309. package/src/interceptors/Socket/MockSocket.test.ts +0 -264
  310. package/src/interceptors/Socket/MockSocket.ts +0 -58
  311. package/src/interceptors/Socket/utils/baseUrlFromConnectionOptions.ts +0 -26
  312. package/src/interceptors/Socket/utils/normalizeSocketWriteArgs.test.ts +0 -52
  313. package/src/interceptors/Socket/utils/normalizeSocketWriteArgs.ts +0 -33
  314. package/src/interceptors/XMLHttpRequest/index.ts +0 -40
  315. package/src/interceptors/fetch/index.ts +0 -203
  316. package/src/utils/bufferUtils.ts +0 -22
  317. package/src/utils/canParseUrl.ts +0 -13
  318. package/src/utils/emitAsync.ts +0 -25
  319. package/src/utils/nextTick.ts +0 -11
  320. package/src/utils/node/index.ts +0 -39
  321. /package/src/{createRequestId.ts → create-request-id.ts} +0 -0
  322. /package/src/{InterceptorError.ts → interceptor-error.ts} +0 -0
  323. /package/src/interceptors/WebSocket/utils/{bindEvent.ts → bind-event.ts} +0 -0
  324. /package/src/interceptors/XMLHttpRequest/polyfills/{EventPolyfill.ts → event-polyfill.ts} +0 -0
  325. /package/src/interceptors/XMLHttpRequest/utils/{getBodyByteLength.ts → get-body-byte-length.ts} +0 -0
  326. /package/src/interceptors/XMLHttpRequest/utils/{isDomParserSupportedType.ts → is-dom-parser-supported-type.ts} +0 -0
  327. /package/src/interceptors/fetch/utils/{createNetworkError.ts → create-network-error.ts} +0 -0
  328. /package/src/utils/{findPropertySource.ts → find-property-source.ts} +0 -0
  329. /package/src/utils/{getCleanUrl.ts → get-clean-url.ts} +0 -0
  330. /package/src/utils/{getValueBySymbol.ts → get-value-by-symbol.ts} +0 -0
  331. /package/src/utils/{isNodeLikeError.ts → is-node-like-error.ts} +0 -0
  332. /package/src/utils/{isObject.ts → is-object.ts} +0 -0
  333. /package/src/utils/{isPropertyAccessible.ts → is-property-accessible.ts} +0 -0
  334. /package/src/utils/{parseJson.ts → parse-json.ts} +0 -0
  335. /package/src/utils/{resolveWebSocketUrl.ts → resolve-web-socket-url.ts} +0 -0
@@ -1,1058 +0,0 @@
1
- const require_chunk = require('./chunk-CbDLau6x.cjs');
2
- const require_fetchUtils = require('./fetchUtils-umV5xXBy.cjs');
3
- const require_getRawRequest = require('./getRawRequest-B6znU6il.cjs');
4
- const require_handleRequest = require('./handleRequest-C-cKYjIh.cjs');
5
- const require_node = require('./node-DIKcnzhK.cjs');
6
- let _open_draft_logger = require("@open-draft/logger");
7
- let outvariant = require("outvariant");
8
- let node_http = require("node:http");
9
- node_http = require_chunk.__toESM(node_http);
10
- let node_https = require("node:https");
11
- node_https = require_chunk.__toESM(node_https);
12
- let node_net = require("node:net");
13
- node_net = require_chunk.__toESM(node_net);
14
- let _http_common = require("_http_common");
15
- let node_stream = require("node:stream");
16
- let node_url = require("node:url");
17
- let http = require("http");
18
-
19
- //#region src/interceptors/Socket/utils/normalizeSocketWriteArgs.ts
20
- /**
21
- * Normalizes the arguments provided to the `Writable.prototype.write()`
22
- * and `Writable.prototype.end()`.
23
- */
24
- function normalizeSocketWriteArgs(args) {
25
- const normalized = [
26
- args[0],
27
- void 0,
28
- void 0
29
- ];
30
- if (typeof args[1] === "string") normalized[1] = args[1];
31
- else if (typeof args[1] === "function") normalized[2] = args[1];
32
- if (typeof args[2] === "function") normalized[2] = args[2];
33
- return normalized;
34
- }
35
-
36
- //#endregion
37
- //#region src/interceptors/Socket/MockSocket.ts
38
- var MockSocket = class extends node_net.default.Socket {
39
- constructor(options) {
40
- super();
41
- this.options = options;
42
- this.connecting = false;
43
- this.connect();
44
- this._final = (callback) => {
45
- callback(null);
46
- };
47
- }
48
- connect() {
49
- this.connecting = true;
50
- return this;
51
- }
52
- write(...args) {
53
- const [chunk, encoding, callback] = normalizeSocketWriteArgs(args);
54
- this.options.write(chunk, encoding, callback);
55
- return true;
56
- }
57
- end(...args) {
58
- const [chunk, encoding, callback] = normalizeSocketWriteArgs(args);
59
- this.options.write(chunk, encoding, callback);
60
- return super.end.apply(this, args);
61
- }
62
- push(chunk, encoding) {
63
- this.options.read(chunk, encoding);
64
- return super.push(chunk, encoding);
65
- }
66
- };
67
-
68
- //#endregion
69
- //#region src/interceptors/Socket/utils/baseUrlFromConnectionOptions.ts
70
- function baseUrlFromConnectionOptions(options) {
71
- if ("href" in options) return new URL(options.href);
72
- const protocol = options.port === 443 ? "https:" : "http:";
73
- const host = options.host;
74
- const url = new URL(`${protocol}//${host}`);
75
- if (options.port) url.port = options.port.toString();
76
- if (options.path) url.pathname = options.path;
77
- if (options.auth) {
78
- const [username, password] = options.auth.split(":");
79
- url.username = username;
80
- url.password = password;
81
- }
82
- return url;
83
- }
84
-
85
- //#endregion
86
- //#region src/interceptors/ClientRequest/utils/recordRawHeaders.ts
87
- const kRawHeaders = Symbol("kRawHeaders");
88
- const kRestorePatches = Symbol("kRestorePatches");
89
- function recordRawHeader(headers, args, behavior) {
90
- ensureRawHeadersSymbol(headers, []);
91
- const rawHeaders = Reflect.get(headers, kRawHeaders);
92
- if (behavior === "set") {
93
- for (let index = rawHeaders.length - 1; index >= 0; index--) if (rawHeaders[index][0].toLowerCase() === args[0].toLowerCase()) rawHeaders.splice(index, 1);
94
- }
95
- rawHeaders.push(args);
96
- }
97
- /**
98
- * Define the raw headers symbol on the given `Headers` instance.
99
- * If the symbol already exists, this function does nothing.
100
- */
101
- function ensureRawHeadersSymbol(headers, rawHeaders) {
102
- if (Reflect.has(headers, kRawHeaders)) return;
103
- defineRawHeadersSymbol(headers, rawHeaders);
104
- }
105
- /**
106
- * Define the raw headers symbol on the given `Headers` instance.
107
- * If the symbol already exists, it gets overridden.
108
- */
109
- function defineRawHeadersSymbol(headers, rawHeaders) {
110
- Object.defineProperty(headers, kRawHeaders, {
111
- value: rawHeaders,
112
- enumerable: false,
113
- configurable: true
114
- });
115
- }
116
- /**
117
- * Patch the global `Headers` class to store raw headers.
118
- * This is for compatibility with `IncomingMessage.prototype.rawHeaders`.
119
- *
120
- * @note Node.js has their own raw headers symbol but it
121
- * only records the first header name in case of multi-value headers.
122
- * Any other headers are normalized before comparing. This makes it
123
- * incompatible with the `rawHeaders` format.
124
- *
125
- * let h = new Headers()
126
- * h.append('X-Custom', 'one')
127
- * h.append('x-custom', 'two')
128
- * h[Symbol('headers map')] // Map { 'X-Custom' => 'one, two' }
129
- */
130
- function recordRawFetchHeaders() {
131
- if (Reflect.get(Headers, kRestorePatches)) return Reflect.get(Headers, kRestorePatches);
132
- const { Headers: OriginalHeaders, Request: OriginalRequest, Response: OriginalResponse } = globalThis;
133
- const { set, append, delete: headersDeleteMethod } = Headers.prototype;
134
- Object.defineProperty(Headers, kRestorePatches, {
135
- value: () => {
136
- Headers.prototype.set = set;
137
- Headers.prototype.append = append;
138
- Headers.prototype.delete = headersDeleteMethod;
139
- globalThis.Headers = OriginalHeaders;
140
- globalThis.Request = OriginalRequest;
141
- globalThis.Response = OriginalResponse;
142
- Object.setPrototypeOf(require_fetchUtils.FetchRequest, OriginalRequest);
143
- Object.setPrototypeOf(require_fetchUtils.FetchRequest.prototype, OriginalRequest.prototype);
144
- Object.setPrototypeOf(require_fetchUtils.FetchResponse, OriginalResponse);
145
- Object.setPrototypeOf(require_fetchUtils.FetchResponse.prototype, OriginalResponse.prototype);
146
- Reflect.deleteProperty(Headers, kRestorePatches);
147
- },
148
- enumerable: false,
149
- configurable: true
150
- });
151
- Object.defineProperty(globalThis, "Headers", {
152
- enumerable: true,
153
- writable: true,
154
- value: new Proxy(Headers, { construct(target, args, newTarget) {
155
- const headersInit = args[0] || [];
156
- if (headersInit instanceof Headers && Reflect.has(headersInit, kRawHeaders)) {
157
- const sanitizedHeaders = Reflect.get(headersInit, kRawHeaders).map((tuple) => [tuple[0], tuple[1]]);
158
- const headers$1 = Reflect.construct(target, [sanitizedHeaders], newTarget);
159
- ensureRawHeadersSymbol(headers$1, [...sanitizedHeaders]);
160
- return headers$1;
161
- }
162
- const headers = Reflect.construct(target, args, newTarget);
163
- if (!Reflect.has(headers, kRawHeaders)) ensureRawHeadersSymbol(headers, Array.isArray(headersInit) ? headersInit : Object.entries(headersInit));
164
- return headers;
165
- } })
166
- });
167
- Headers.prototype.set = new Proxy(Headers.prototype.set, { apply(target, thisArg, args) {
168
- recordRawHeader(thisArg, [args[0], args[1]], "set");
169
- return Reflect.apply(target, thisArg, args);
170
- } });
171
- Headers.prototype.append = new Proxy(Headers.prototype.append, { apply(target, thisArg, args) {
172
- recordRawHeader(thisArg, [args[0], args[1]], "append");
173
- return Reflect.apply(target, thisArg, args);
174
- } });
175
- Headers.prototype.delete = new Proxy(Headers.prototype.delete, { apply(target, thisArg, args) {
176
- const rawHeaders = Reflect.get(thisArg, kRawHeaders);
177
- if (rawHeaders) {
178
- for (let index = rawHeaders.length - 1; index >= 0; index--) if (rawHeaders[index][0].toLowerCase() === args[0].toLowerCase()) rawHeaders.splice(index, 1);
179
- }
180
- return Reflect.apply(target, thisArg, args);
181
- } });
182
- Object.defineProperty(globalThis, "Request", {
183
- enumerable: true,
184
- writable: true,
185
- value: new Proxy(Request, { construct(target, args, newTarget) {
186
- const request = Reflect.construct(target, args, newTarget);
187
- const inferredRawHeaders = [];
188
- if (typeof args[0] === "object" && args[0].headers != null) inferredRawHeaders.push(...inferRawHeaders(args[0].headers));
189
- if (typeof args[1] === "object" && args[1].headers != null) inferredRawHeaders.push(...inferRawHeaders(args[1].headers));
190
- if (inferredRawHeaders.length > 0) ensureRawHeadersSymbol(request.headers, inferredRawHeaders);
191
- return request;
192
- } })
193
- });
194
- Object.defineProperty(globalThis, "Response", {
195
- enumerable: true,
196
- writable: true,
197
- value: new Proxy(Response, { construct(target, args, newTarget) {
198
- const response = Reflect.construct(target, args, newTarget);
199
- if (typeof args[1] === "object" && args[1].headers != null) ensureRawHeadersSymbol(response.headers, inferRawHeaders(args[1].headers));
200
- return response;
201
- } })
202
- });
203
- /**
204
- * Re-parent FetchRequest/FetchResponse so their `super()` calls go
205
- * through the proxied globalThis.Request/Response above. Without this,
206
- * FetchRequest extends the statically-captured (original) Request,
207
- * bypassing the construct proxy that records raw headers.
208
- */
209
- Object.setPrototypeOf(require_fetchUtils.FetchRequest, globalThis.Request);
210
- Object.setPrototypeOf(require_fetchUtils.FetchRequest.prototype, globalThis.Request.prototype);
211
- Object.setPrototypeOf(require_fetchUtils.FetchResponse, globalThis.Response);
212
- Object.setPrototypeOf(require_fetchUtils.FetchResponse.prototype, globalThis.Response.prototype);
213
- }
214
- function restoreHeadersPrototype() {
215
- if (!Reflect.get(Headers, kRestorePatches)) return;
216
- Reflect.get(Headers, kRestorePatches)();
217
- }
218
- function getRawFetchHeaders(headers) {
219
- if (!Reflect.has(headers, kRawHeaders)) return Array.from(headers.entries());
220
- const rawHeaders = Reflect.get(headers, kRawHeaders);
221
- return rawHeaders.length > 0 ? rawHeaders : Array.from(headers.entries());
222
- }
223
- /**
224
- * Infers the raw headers from the given `HeadersInit` provided
225
- * to the Request/Response constructor.
226
- *
227
- * If the `init.headers` is a Headers instance, use it directly.
228
- * That means the headers were created standalone and already have
229
- * the raw headers stored.
230
- * If the `init.headers` is a HeadersInit, create a new Headers
231
- * instance out of it.
232
- */
233
- function inferRawHeaders(headers) {
234
- if (headers instanceof Headers) return Reflect.get(headers, kRawHeaders) || [];
235
- return Reflect.get(new Headers(headers), kRawHeaders);
236
- }
237
-
238
- //#endregion
239
- //#region src/interceptors/ClientRequest/utils/parserUtils.ts
240
- /**
241
- * @see https://github.com/nodejs/node/blob/f3adc11e37b8bfaaa026ea85c1cf22e3a0e29ae9/lib/_http_common.js#L180
242
- */
243
- function freeParser(parser, socket) {
244
- if (parser._consumed) parser.unconsume();
245
- parser._headers = [];
246
- parser._url = "";
247
- parser.socket = null;
248
- parser.incoming = null;
249
- parser.outgoing = null;
250
- parser.maxHeaderPairs = 2e3;
251
- parser._consumed = false;
252
- parser.onIncoming = null;
253
- parser[_http_common.HTTPParser.kOnHeaders] = null;
254
- parser[_http_common.HTTPParser.kOnHeadersComplete] = null;
255
- parser[_http_common.HTTPParser.kOnMessageBegin] = null;
256
- parser[_http_common.HTTPParser.kOnMessageComplete] = null;
257
- parser[_http_common.HTTPParser.kOnBody] = null;
258
- parser[_http_common.HTTPParser.kOnExecute] = null;
259
- parser[_http_common.HTTPParser.kOnTimeout] = null;
260
- parser.remove();
261
- parser.free();
262
- if (socket)
263
- /**
264
- * @note Unassigning the socket's parser will fail this assertion
265
- * if there's still some data being processed on the socket:
266
- * @see https://github.com/nodejs/node/blob/4e1f39b678b37017ac9baa0971e3aeecd3b67b51/lib/_http_client.js#L613
267
- */
268
- if (socket.destroyed) socket.parser = null;
269
- else socket.once("end", () => {
270
- socket.parser = null;
271
- });
272
- }
273
-
274
- //#endregion
275
- //#region src/interceptors/ClientRequest/MockHttpSocket.ts
276
- const kRequestId = Symbol("kRequestId");
277
- var MockHttpSocket = class extends MockSocket {
278
- constructor(options) {
279
- super({
280
- write: (chunk, encoding, callback) => {
281
- if (this.socketState !== "passthrough") this.writeBuffer.push([
282
- chunk,
283
- encoding,
284
- callback
285
- ]);
286
- if (chunk) {
287
- /**
288
- * Forward any writes to the mock socket to the underlying original socket.
289
- * This ensures functional duplex connections, like WebSocket.
290
- * @see https://github.com/mswjs/interceptors/issues/682
291
- */
292
- if (this.socketState === "passthrough") this.originalSocket?.write(chunk, encoding, callback);
293
- this.requestParser.execute(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding));
294
- }
295
- },
296
- read: (chunk) => {
297
- if (chunk !== null)
298
- /**
299
- * @todo We need to free the parser if the connection has been
300
- * upgraded to a non-HTTP protocol. It won't be able to parse data
301
- * from that point onward anyway. No need to keep it in memory.
302
- */
303
- this.responseParser.execute(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
304
- }
305
- });
306
- this.requestRawHeadersBuffer = [];
307
- this.responseRawHeadersBuffer = [];
308
- this.writeBuffer = [];
309
- this.socketState = "unknown";
310
- this.onRequestHeaders = (rawHeaders) => {
311
- this.requestRawHeadersBuffer.push(...rawHeaders);
312
- };
313
- this.onRequestStart = (versionMajor, versionMinor, rawHeaders, _, path, __, ___, ____, shouldKeepAlive) => {
314
- this.shouldKeepAlive = shouldKeepAlive;
315
- const url = new URL(path || "", this.baseUrl);
316
- const method = this.connectionOptions.method?.toUpperCase() || "GET";
317
- const headers = require_fetchUtils.FetchResponse.parseRawHeaders([...this.requestRawHeadersBuffer, ...rawHeaders || []]);
318
- this.requestRawHeadersBuffer.length = 0;
319
- const canHaveBody = method !== "GET" && method !== "HEAD";
320
- if (url.username || url.password) {
321
- if (!headers.has("authorization")) headers.set("authorization", `Basic ${url.username}:${url.password}`);
322
- url.username = "";
323
- url.password = "";
324
- }
325
- this.requestStream = new node_stream.Readable({ read: () => {
326
- this.flushWriteBuffer();
327
- } });
328
- const requestId = require_fetchUtils.createRequestId();
329
- this.request = new require_fetchUtils.FetchRequest(url, {
330
- method,
331
- headers,
332
- credentials: "same-origin",
333
- duplex: canHaveBody ? "half" : void 0,
334
- body: canHaveBody ? node_stream.Readable.toWeb(this.requestStream) : null
335
- });
336
- Reflect.set(this.request, kRequestId, requestId);
337
- require_getRawRequest.setRawRequest(this.request, Reflect.get(this, "_httpMessage"));
338
- require_node.setRawRequestBodyStream(this.request, this.requestStream);
339
- /**
340
- * @fixme Stop relying on the "X-Request-Id" request header
341
- * to figure out if one interceptor has been invoked within another.
342
- * @see https://github.com/mswjs/interceptors/issues/378
343
- */
344
- if (this.request.headers.has(require_fetchUtils.INTERNAL_REQUEST_ID_HEADER_NAME)) {
345
- this.passthrough();
346
- return;
347
- }
348
- this.onRequest({
349
- requestId,
350
- request: this.request,
351
- socket: this
352
- });
353
- };
354
- this.onResponseHeaders = (rawHeaders) => {
355
- this.responseRawHeadersBuffer.push(...rawHeaders);
356
- };
357
- this.onResponseStart = (versionMajor, versionMinor, rawHeaders, method, url, status, statusText) => {
358
- const headers = require_fetchUtils.FetchResponse.parseRawHeaders([...this.responseRawHeadersBuffer, ...rawHeaders || []]);
359
- this.responseRawHeadersBuffer.length = 0;
360
- const response = new require_fetchUtils.FetchResponse(
361
- /**
362
- * @note The Fetch API response instance exposed to the consumer
363
- * is created over the response stream of the HTTP parser. It is NOT
364
- * related to the Socket instance. This way, you can read response body
365
- * in response listener while the Socket instance delays the emission
366
- * of "end" and other events until those response listeners are finished.
367
- */
368
- require_fetchUtils.FetchResponse.isResponseWithBody(status) ? node_stream.Readable.toWeb(this.responseStream = new node_stream.Readable({ read() {} })) : null,
369
- {
370
- url,
371
- status,
372
- statusText,
373
- headers
374
- }
375
- );
376
- (0, outvariant.invariant)(this.request, "Failed to handle a response: request does not exist");
377
- require_fetchUtils.FetchResponse.setUrl(this.request.url, response);
378
- /**
379
- * @fixme Stop relying on the "X-Request-Id" request header
380
- * to figure out if one interceptor has been invoked within another.
381
- * @see https://github.com/mswjs/interceptors/issues/378
382
- */
383
- if (this.request.headers.has(require_fetchUtils.INTERNAL_REQUEST_ID_HEADER_NAME)) return;
384
- this.responseListenersPromise = this.onResponse({
385
- response,
386
- isMockedResponse: this.socketState === "mock",
387
- requestId: Reflect.get(this.request, kRequestId),
388
- request: this.request,
389
- socket: this
390
- });
391
- };
392
- this.connectionOptions = options.connectionOptions;
393
- this.createConnection = options.createConnection;
394
- this.onRequest = options.onRequest;
395
- this.onResponse = options.onResponse;
396
- this.baseUrl = baseUrlFromConnectionOptions(this.connectionOptions);
397
- this.requestParser = new _http_common.HTTPParser();
398
- this.requestParser.initialize(_http_common.HTTPParser.REQUEST, {});
399
- this.requestParser[_http_common.HTTPParser.kOnHeaders] = this.onRequestHeaders.bind(this);
400
- this.requestParser[_http_common.HTTPParser.kOnHeadersComplete] = this.onRequestStart.bind(this);
401
- this.requestParser[_http_common.HTTPParser.kOnBody] = this.onRequestBody.bind(this);
402
- this.requestParser[_http_common.HTTPParser.kOnMessageComplete] = this.onRequestEnd.bind(this);
403
- this.responseParser = new _http_common.HTTPParser();
404
- this.responseParser.initialize(_http_common.HTTPParser.RESPONSE, {});
405
- this.responseParser[_http_common.HTTPParser.kOnHeaders] = this.onResponseHeaders.bind(this);
406
- this.responseParser[_http_common.HTTPParser.kOnHeadersComplete] = this.onResponseStart.bind(this);
407
- this.responseParser[_http_common.HTTPParser.kOnBody] = this.onResponseBody.bind(this);
408
- this.responseParser[_http_common.HTTPParser.kOnMessageComplete] = this.onResponseEnd.bind(this);
409
- this.once("finish", () => freeParser(this.requestParser, this));
410
- if (this.baseUrl.protocol === "https:") {
411
- Reflect.set(this, "encrypted", true);
412
- Reflect.set(this, "authorized", false);
413
- Reflect.set(this, "getProtocol", () => "TLSv1.3");
414
- Reflect.set(this, "getSession", () => void 0);
415
- Reflect.set(this, "isSessionReused", () => false);
416
- Reflect.set(this, "getCipher", () => ({
417
- name: "AES256-SHA",
418
- standardName: "TLS_RSA_WITH_AES_256_CBC_SHA",
419
- version: "TLSv1.3"
420
- }));
421
- }
422
- }
423
- emit(event, ...args) {
424
- const emitEvent = super.emit.bind(this, event, ...args);
425
- if (this.responseListenersPromise) {
426
- this.responseListenersPromise.finally(emitEvent);
427
- return this.listenerCount(event) > 0;
428
- }
429
- return emitEvent();
430
- }
431
- destroy(error) {
432
- freeParser(this.responseParser, this);
433
- if (error) this.emit("error", error);
434
- return super.destroy(error);
435
- }
436
- /**
437
- * Establish this Socket connection as-is and pipe
438
- * its data/events through this Socket.
439
- */
440
- passthrough() {
441
- this.socketState = "passthrough";
442
- if (this.destroyed) return;
443
- const socket = this.createConnection();
444
- this.originalSocket = socket;
445
- /**
446
- * @note Inherit the original socket's connection handle.
447
- * Without this, each push to the mock socket results in a
448
- * new "connection" listener being added (i.e. buffering pushes).
449
- * @see https://github.com/nodejs/node/blob/b18153598b25485ce4f54d0c5cb830a9457691ee/lib/net.js#L734
450
- */
451
- if ("_handle" in socket) Object.defineProperty(this, "_handle", {
452
- value: socket._handle,
453
- enumerable: true,
454
- writable: true
455
- });
456
- this.once("close", () => {
457
- socket.removeAllListeners();
458
- if (!socket.destroyed) socket.destroy();
459
- this.originalSocket = void 0;
460
- });
461
- this.address = socket.address.bind(socket);
462
- let writeArgs;
463
- let headersWritten = false;
464
- while (writeArgs = this.writeBuffer.shift()) if (writeArgs !== void 0) {
465
- if (!headersWritten) {
466
- const [chunk, encoding, callback] = writeArgs;
467
- const chunkString = chunk.toString();
468
- const chunkBeforeRequestHeaders = chunkString.slice(0, chunkString.indexOf("\r\n") + 2);
469
- const chunkAfterRequestHeaders = chunkString.slice(chunk.indexOf("\r\n\r\n"));
470
- const headersChunk = `${chunkBeforeRequestHeaders}${getRawFetchHeaders(this.request.headers).filter(([name]) => {
471
- return name.toLowerCase() !== require_fetchUtils.INTERNAL_REQUEST_ID_HEADER_NAME;
472
- }).map(([name, value]) => `${name}: ${value}`).join("\r\n")}${chunkAfterRequestHeaders}`;
473
- socket.write(headersChunk, encoding, callback);
474
- headersWritten = true;
475
- continue;
476
- }
477
- socket.write(...writeArgs);
478
- }
479
- if (Reflect.get(socket, "encrypted")) [
480
- "encrypted",
481
- "authorized",
482
- "getProtocol",
483
- "getSession",
484
- "isSessionReused",
485
- "getCipher"
486
- ].forEach((propertyName) => {
487
- Object.defineProperty(this, propertyName, {
488
- enumerable: true,
489
- get: () => {
490
- const value = Reflect.get(socket, propertyName);
491
- return typeof value === "function" ? value.bind(socket) : value;
492
- }
493
- });
494
- });
495
- socket.on("lookup", (...args) => this.emit("lookup", ...args)).on("connect", () => {
496
- this.connecting = socket.connecting;
497
- this.emit("connect");
498
- }).on("secureConnect", () => this.emit("secureConnect")).on("secure", () => this.emit("secure")).on("session", (session) => this.emit("session", session)).on("ready", () => this.emit("ready")).on("drain", () => this.emit("drain")).on("data", (chunk) => {
499
- this.push(chunk);
500
- }).on("error", (error) => {
501
- Reflect.set(this, "_hadError", Reflect.get(socket, "_hadError"));
502
- this.emit("error", error);
503
- }).on("resume", () => this.emit("resume")).on("timeout", () => this.emit("timeout")).on("prefinish", () => this.emit("prefinish")).on("finish", () => this.emit("finish")).on("close", (hadError) => this.emit("close", hadError)).on("end", () => this.emit("end"));
504
- }
505
- /**
506
- * Convert the given Fetch API `Response` instance to an
507
- * HTTP message and push it to the socket.
508
- */
509
- async respondWith(response) {
510
- if (this.destroyed) return;
511
- (0, outvariant.invariant)(this.socketState !== "mock", "[MockHttpSocket] Failed to respond to the \"%s %s\" request with \"%s %s\": the request has already been handled", this.request?.method, this.request?.url, response.status, response.statusText);
512
- if (require_handleRequest.isPropertyAccessible(response, "type") && response.type === "error") {
513
- this.errorWith(/* @__PURE__ */ new TypeError("Network error"));
514
- return;
515
- }
516
- this.mockConnect();
517
- this.socketState = "mock";
518
- this.flushWriteBuffer();
519
- const serverResponse = new node_http.ServerResponse(new node_http.IncomingMessage(this));
520
- /**
521
- * Assign a mock socket instance to the server response to
522
- * spy on the response chunk writes. Push the transformed response chunks
523
- * to this `MockHttpSocket` instance to trigger the "data" event.
524
- * @note Providing the same `MockSocket` instance when creating `ServerResponse`
525
- * does not have the same effect.
526
- * @see https://github.com/nodejs/node/blob/10099bb3f7fd97bb9dd9667188426866b3098e07/test/parallel/test-http-server-response-standalone.js#L32
527
- */
528
- serverResponse.assignSocket(new MockSocket({
529
- write: (chunk, encoding, callback) => {
530
- this.push(chunk, encoding);
531
- callback?.();
532
- },
533
- read() {}
534
- }));
535
- /**
536
- * @note Remove the `Connection` and `Date` response headers
537
- * injected by `ServerResponse` by default. Those are required
538
- * from the server but the interceptor is NOT technically a server.
539
- * It's confusing to add response headers that the developer didn't
540
- * specify themselves. They can always add these if they wish.
541
- * @see https://www.rfc-editor.org/rfc/rfc9110#field.date
542
- * @see https://www.rfc-editor.org/rfc/rfc9110#field.connection
543
- */
544
- serverResponse.removeHeader("connection");
545
- serverResponse.removeHeader("date");
546
- const rawResponseHeaders = getRawFetchHeaders(response.headers);
547
- /**
548
- * @note Call `.writeHead` in order to set the raw response headers
549
- * in the same case as they were provided by the developer. Using
550
- * `.setHeader()`/`.appendHeader()` normalizes header names.
551
- */
552
- serverResponse.writeHead(response.status, response.statusText || node_http.STATUS_CODES[response.status], rawResponseHeaders);
553
- this.once("error", () => {
554
- serverResponse.destroy();
555
- });
556
- if (response.body) try {
557
- const reader = response.body.getReader();
558
- while (true) {
559
- const { done, value } = await reader.read();
560
- if (done) {
561
- serverResponse.end();
562
- break;
563
- }
564
- serverResponse.write(value);
565
- }
566
- } catch (error) {
567
- if (error instanceof Error) {
568
- serverResponse.destroy();
569
- /**
570
- * @note Destroy the request socket gracefully.
571
- * Response stream errors do NOT produce request errors.
572
- */
573
- this.destroy();
574
- return;
575
- }
576
- serverResponse.destroy();
577
- throw error;
578
- }
579
- else serverResponse.end();
580
- if (!this.shouldKeepAlive) {
581
- this.emit("readable");
582
- /**
583
- * @todo @fixme This is likely a hack.
584
- * Since we push null to the socket, it never propagates to the
585
- * parser, and the parser never calls "onResponseEnd" to close
586
- * the response stream. We are closing the stream here manually
587
- * but that shouldn't be the case.
588
- */
589
- this.responseStream?.push(null);
590
- this.push(null);
591
- }
592
- }
593
- /**
594
- * Close this socket connection with the given error.
595
- */
596
- errorWith(error) {
597
- this.destroy(error);
598
- }
599
- mockConnect() {
600
- this.connecting = false;
601
- const isIPv6 = node_net.default.isIPv6(this.connectionOptions.hostname) || this.connectionOptions.family === 6;
602
- const addressInfo = {
603
- address: isIPv6 ? "::1" : "127.0.0.1",
604
- family: isIPv6 ? "IPv6" : "IPv4",
605
- port: this.connectionOptions.port
606
- };
607
- this.address = () => addressInfo;
608
- this.emit("lookup", null, addressInfo.address, addressInfo.family === "IPv6" ? 6 : 4, this.connectionOptions.host);
609
- this.emit("connect");
610
- this.emit("ready");
611
- if (this.baseUrl.protocol === "https:") {
612
- this.emit("secure");
613
- this.emit("secureConnect");
614
- this.emit("session", this.connectionOptions.session || Buffer.from("mock-session-renegotiate"));
615
- this.emit("session", Buffer.from("mock-session-resume"));
616
- }
617
- }
618
- flushWriteBuffer() {
619
- for (const writeCall of this.writeBuffer) if (typeof writeCall[2] === "function") {
620
- writeCall[2]();
621
- /**
622
- * @note Remove the callback from the write call
623
- * so it doesn't get called twice on passthrough
624
- * if `request.end()` was called within `request.write()`.
625
- * @see https://github.com/mswjs/interceptors/issues/684
626
- */
627
- writeCall[2] = void 0;
628
- }
629
- }
630
- onRequestBody(chunk) {
631
- (0, outvariant.invariant)(this.requestStream, "Failed to write to a request stream: stream does not exist");
632
- this.requestStream.push(chunk);
633
- }
634
- onRequestEnd() {
635
- if (this.requestStream) this.requestStream.push(null);
636
- }
637
- onResponseBody(chunk) {
638
- (0, outvariant.invariant)(this.responseStream, "Failed to write to a response stream: stream does not exist");
639
- this.responseStream.push(chunk);
640
- }
641
- onResponseEnd() {
642
- if (this.responseStream) this.responseStream.push(null);
643
- }
644
- };
645
-
646
- //#endregion
647
- //#region src/interceptors/ClientRequest/agents.ts
648
- var MockAgent = class extends node_http.default.Agent {
649
- constructor(options) {
650
- super();
651
- this.customAgent = options.customAgent;
652
- this.onRequest = options.onRequest;
653
- this.onResponse = options.onResponse;
654
- }
655
- createConnection(options, callback) {
656
- const createConnection = this.customAgent instanceof node_http.default.Agent ? this.customAgent.createConnection : super.createConnection;
657
- const createConnectionOptions = this.customAgent instanceof node_http.default.Agent ? {
658
- ...options,
659
- ...this.customAgent.options
660
- } : options;
661
- return new MockHttpSocket({
662
- connectionOptions: options,
663
- createConnection: createConnection.bind(this.customAgent || this, createConnectionOptions, callback),
664
- onRequest: this.onRequest.bind(this),
665
- onResponse: this.onResponse.bind(this)
666
- });
667
- }
668
- };
669
- var MockHttpsAgent = class extends node_https.default.Agent {
670
- constructor(options) {
671
- super();
672
- this.customAgent = options.customAgent;
673
- this.onRequest = options.onRequest;
674
- this.onResponse = options.onResponse;
675
- }
676
- createConnection(options, callback) {
677
- const createConnection = this.customAgent instanceof node_http.default.Agent ? this.customAgent.createConnection : super.createConnection;
678
- const createConnectionOptions = this.customAgent instanceof node_http.default.Agent ? {
679
- ...options,
680
- ...this.customAgent.options
681
- } : options;
682
- return new MockHttpSocket({
683
- connectionOptions: options,
684
- createConnection: createConnection.bind(this.customAgent || this, createConnectionOptions, callback),
685
- onRequest: this.onRequest.bind(this),
686
- onResponse: this.onResponse.bind(this)
687
- });
688
- }
689
- };
690
-
691
- //#endregion
692
- //#region src/utils/getUrlByRequestOptions.ts
693
- const logger$2 = new _open_draft_logger.Logger("utils getUrlByRequestOptions");
694
- const DEFAULT_PATH = "/";
695
- const DEFAULT_PROTOCOL = "http:";
696
- const DEFAULT_HOSTNAME = "localhost";
697
- const SSL_PORT = 443;
698
- function getAgent(options) {
699
- return options.agent instanceof http.Agent ? options.agent : void 0;
700
- }
701
- function getProtocolByRequestOptions(options) {
702
- if (options.protocol) return options.protocol;
703
- const agentProtocol = getAgent(options)?.protocol;
704
- if (agentProtocol) return agentProtocol;
705
- const port = getPortByRequestOptions(options);
706
- return options.cert || port === SSL_PORT ? "https:" : options.uri?.protocol || DEFAULT_PROTOCOL;
707
- }
708
- function getPortByRequestOptions(options) {
709
- if (options.port) return Number(options.port);
710
- const agent = getAgent(options);
711
- if (agent?.options.port) return Number(agent.options.port);
712
- if (agent?.defaultPort) return Number(agent.defaultPort);
713
- }
714
- function getAuthByRequestOptions(options) {
715
- if (options.auth) {
716
- const [username, password] = options.auth.split(":");
717
- return {
718
- username,
719
- password
720
- };
721
- }
722
- }
723
- /**
724
- * Returns true if host looks like an IPv6 address without surrounding brackets
725
- * It assumes any host containing `:` is definitely not IPv4 and probably IPv6,
726
- * but note that this could include invalid IPv6 addresses as well.
727
- */
728
- function isRawIPv6Address(host) {
729
- return host.includes(":") && !host.startsWith("[") && !host.endsWith("]");
730
- }
731
- function getHostname(options) {
732
- let host = options.hostname || options.host;
733
- if (host) {
734
- if (isRawIPv6Address(host)) host = `[${host}]`;
735
- return new URL(`http://${host}`).hostname;
736
- }
737
- return DEFAULT_HOSTNAME;
738
- }
739
- /**
740
- * Creates a `URL` instance from a given `RequestOptions` object.
741
- */
742
- function getUrlByRequestOptions(options) {
743
- logger$2.info("request options", options);
744
- if (options.uri) {
745
- logger$2.info("constructing url from explicitly provided \"options.uri\": %s", options.uri);
746
- return new URL(options.uri.href);
747
- }
748
- logger$2.info("figuring out url from request options...");
749
- const protocol = getProtocolByRequestOptions(options);
750
- logger$2.info("protocol", protocol);
751
- const port = getPortByRequestOptions(options);
752
- logger$2.info("port", port);
753
- const hostname = getHostname(options);
754
- logger$2.info("hostname", hostname);
755
- const path = options.path || DEFAULT_PATH;
756
- logger$2.info("path", path);
757
- const credentials = getAuthByRequestOptions(options);
758
- logger$2.info("credentials", credentials);
759
- const authString = credentials ? `${credentials.username}:${credentials.password}@` : "";
760
- logger$2.info("auth string:", authString);
761
- const portString = typeof port !== "undefined" ? `:${port}` : "";
762
- const url = new URL(`${protocol}//${hostname}${portString}${path}`);
763
- url.username = credentials?.username || "";
764
- url.password = credentials?.password || "";
765
- logger$2.info("created url:", url);
766
- return url;
767
- }
768
-
769
- //#endregion
770
- //#region src/utils/cloneObject.ts
771
- const logger$1 = new _open_draft_logger.Logger("cloneObject");
772
- function isPlainObject(obj) {
773
- logger$1.info("is plain object?", obj);
774
- if (obj == null || !obj.constructor?.name) {
775
- logger$1.info("given object is undefined, not a plain object...");
776
- return false;
777
- }
778
- logger$1.info("checking the object constructor:", obj.constructor.name);
779
- return obj.constructor.name === "Object";
780
- }
781
- function cloneObject(obj) {
782
- logger$1.info("cloning object:", obj);
783
- const enumerableProperties = Object.entries(obj).reduce((acc, [key, value]) => {
784
- logger$1.info("analyzing key-value pair:", key, value);
785
- acc[key] = isPlainObject(value) ? cloneObject(value) : value;
786
- return acc;
787
- }, {});
788
- return isPlainObject(obj) ? enumerableProperties : Object.assign(Object.getPrototypeOf(obj), enumerableProperties);
789
- }
790
-
791
- //#endregion
792
- //#region src/interceptors/ClientRequest/utils/normalizeClientRequestArgs.ts
793
- const logger = new _open_draft_logger.Logger("http normalizeClientRequestArgs");
794
- function resolveRequestOptions(args, url) {
795
- if (typeof args[1] === "undefined" || typeof args[1] === "function") {
796
- logger.info("request options not provided, deriving from the url", url);
797
- return (0, node_url.urlToHttpOptions)(url);
798
- }
799
- if (args[1]) {
800
- logger.info("has custom RequestOptions!", args[1]);
801
- const requestOptionsFromUrl = (0, node_url.urlToHttpOptions)(url);
802
- logger.info("derived RequestOptions from the URL:", requestOptionsFromUrl);
803
- /**
804
- * Clone the request options to lock their state
805
- * at the moment they are provided to `ClientRequest`.
806
- * @see https://github.com/mswjs/interceptors/issues/86
807
- */
808
- logger.info("cloning RequestOptions...");
809
- const clonedRequestOptions = cloneObject(args[1]);
810
- logger.info("successfully cloned RequestOptions!", clonedRequestOptions);
811
- return {
812
- ...requestOptionsFromUrl,
813
- ...clonedRequestOptions
814
- };
815
- }
816
- logger.info("using an empty object as request options");
817
- return {};
818
- }
819
- /**
820
- * Overrides the given `URL` instance with the explicit properties provided
821
- * on the `RequestOptions` object. The options object takes precedence,
822
- * and will replace URL properties like "host", "path", and "port", if specified.
823
- */
824
- function overrideUrlByRequestOptions(url, options) {
825
- url.host = options.host || url.host;
826
- url.hostname = options.hostname || url.hostname;
827
- url.port = options.port ? options.port.toString() : url.port;
828
- if (options.path) {
829
- const parsedOptionsPath = (0, node_url.parse)(options.path, false);
830
- url.pathname = parsedOptionsPath.pathname || "";
831
- url.search = parsedOptionsPath.search || "";
832
- }
833
- return url;
834
- }
835
- function resolveCallback(args) {
836
- return typeof args[1] === "function" ? args[1] : args[2];
837
- }
838
- /**
839
- * Normalizes parameters given to a `http.request` call
840
- * so it always has a `URL` and `RequestOptions`.
841
- */
842
- function normalizeClientRequestArgs(defaultProtocol, args) {
843
- let url;
844
- let options;
845
- let callback;
846
- logger.info("arguments", args);
847
- logger.info("using default protocol:", defaultProtocol);
848
- if (args.length === 0) {
849
- const url$1 = new node_url.URL("http://localhost");
850
- return [url$1, resolveRequestOptions(args, url$1)];
851
- }
852
- if (typeof args[0] === "string") {
853
- logger.info("first argument is a location string:", args[0]);
854
- url = new node_url.URL(args[0]);
855
- logger.info("created a url:", url);
856
- const requestOptionsFromUrl = (0, node_url.urlToHttpOptions)(url);
857
- logger.info("request options from url:", requestOptionsFromUrl);
858
- options = resolveRequestOptions(args, url);
859
- logger.info("resolved request options:", options);
860
- callback = resolveCallback(args);
861
- } else if (args[0] instanceof node_url.URL) {
862
- url = args[0];
863
- logger.info("first argument is a URL:", url);
864
- if (typeof args[1] !== "undefined" && require_handleRequest.isObject(args[1])) url = overrideUrlByRequestOptions(url, args[1]);
865
- options = resolveRequestOptions(args, url);
866
- logger.info("derived request options:", options);
867
- callback = resolveCallback(args);
868
- } else if ("hash" in args[0] && !("method" in args[0])) {
869
- const [legacyUrl] = args;
870
- logger.info("first argument is a legacy URL:", legacyUrl);
871
- if (legacyUrl.hostname === null) {
872
- /**
873
- * We are dealing with a relative url, so use the path as an "option" and
874
- * merge in any existing options, giving priority to existing options -- i.e. a path in any
875
- * existing options will take precedence over the one contained in the url. This is consistent
876
- * with the behaviour in ClientRequest.
877
- * @see https://github.com/nodejs/node/blob/d84f1312915fe45fe0febe888db692c74894c382/lib/_http_client.js#L122
878
- */
879
- logger.info("given legacy URL is relative (no hostname)");
880
- return require_handleRequest.isObject(args[1]) ? normalizeClientRequestArgs(defaultProtocol, [{
881
- path: legacyUrl.path,
882
- ...args[1]
883
- }, args[2]]) : normalizeClientRequestArgs(defaultProtocol, [{ path: legacyUrl.path }, args[1]]);
884
- }
885
- logger.info("given legacy url is absolute");
886
- const resolvedUrl = new node_url.URL(legacyUrl.href);
887
- return args[1] === void 0 ? normalizeClientRequestArgs(defaultProtocol, [resolvedUrl]) : typeof args[1] === "function" ? normalizeClientRequestArgs(defaultProtocol, [resolvedUrl, args[1]]) : normalizeClientRequestArgs(defaultProtocol, [
888
- resolvedUrl,
889
- args[1],
890
- args[2]
891
- ]);
892
- } else if (require_handleRequest.isObject(args[0])) {
893
- options = { ...args[0] };
894
- logger.info("first argument is RequestOptions:", options);
895
- options.protocol = options.protocol || defaultProtocol;
896
- logger.info("normalized request options:", options);
897
- url = getUrlByRequestOptions(options);
898
- logger.info("created a URL from RequestOptions:", url.href);
899
- callback = resolveCallback(args);
900
- } else throw new Error(`Failed to construct ClientRequest with these parameters: ${args}`);
901
- options.protocol = options.protocol || url.protocol;
902
- options.method = options.method || "GET";
903
- /**
904
- * Ensure that the default Agent is always set.
905
- * This prevents the protocol mismatch for requests with { agent: false },
906
- * where the global Agent is inferred.
907
- * @see https://github.com/mswjs/msw/issues/1150
908
- * @see https://github.com/nodejs/node/blob/418ff70b810f0e7112d48baaa72932a56cfa213b/lib/_http_client.js#L130
909
- * @see https://github.com/nodejs/node/blob/418ff70b810f0e7112d48baaa72932a56cfa213b/lib/_http_client.js#L157-L159
910
- */
911
- if (!options._defaultAgent) {
912
- logger.info("has no default agent, setting the default agent for \"%s\"", options.protocol);
913
- options._defaultAgent = options.protocol === "https:" ? node_https.globalAgent : node_http.globalAgent;
914
- }
915
- logger.info("successfully resolved url:", url.href);
916
- logger.info("successfully resolved options:", options);
917
- logger.info("successfully resolved callback:", callback);
918
- /**
919
- * @note If the user-provided URL is not a valid URL in Node.js,
920
- * (e.g. the one provided by the JSDOM polyfills), case it to
921
- * string. Otherwise, this throws on Node.js incompatibility
922
- * (`ERR_INVALID_ARG_TYPE` on the connection listener)
923
- * @see https://github.com/node-fetch/node-fetch/issues/1376#issuecomment-966435555
924
- */
925
- if (!(url instanceof node_url.URL)) url = url.toString();
926
- return [
927
- url,
928
- options,
929
- callback
930
- ];
931
- }
932
-
933
- //#endregion
934
- //#region src/interceptors/ClientRequest/index.ts
935
- var ClientRequestInterceptor = class ClientRequestInterceptor extends require_fetchUtils.Interceptor {
936
- static {
937
- this.symbol = Symbol.for("client-request-interceptor");
938
- }
939
- constructor() {
940
- super(ClientRequestInterceptor.symbol);
941
- this.onRequest = async ({ request, socket }) => {
942
- const controller = new require_fetchUtils.RequestController(request, {
943
- passthrough() {
944
- socket.passthrough();
945
- },
946
- async respondWith(response) {
947
- await socket.respondWith(response);
948
- },
949
- errorWith(reason) {
950
- if (reason instanceof Error) socket.errorWith(reason);
951
- }
952
- });
953
- await require_handleRequest.handleRequest({
954
- request,
955
- requestId: Reflect.get(request, kRequestId),
956
- controller,
957
- emitter: this.emitter
958
- });
959
- };
960
- this.onResponse = async ({ requestId, request, response, isMockedResponse }) => {
961
- return require_handleRequest.emitAsync(this.emitter, "response", {
962
- requestId,
963
- request,
964
- response,
965
- isMockedResponse
966
- });
967
- };
968
- }
969
- setup() {
970
- const { ClientRequest: OriginalClientRequest, get: originalGet, request: originalRequest } = node_http.default;
971
- const { get: originalHttpsGet, request: originalHttpsRequest } = node_https.default;
972
- const onRequest = this.onRequest.bind(this);
973
- const onResponse = this.onResponse.bind(this);
974
- node_http.default.ClientRequest = new Proxy(node_http.default.ClientRequest, { construct: (target, args) => {
975
- const [url, options, callback] = normalizeClientRequestArgs("http:", args);
976
- options.agent = new (options.protocol === "https:" ? MockHttpsAgent : MockAgent)({
977
- customAgent: options.agent,
978
- onRequest,
979
- onResponse
980
- });
981
- return Reflect.construct(target, [
982
- url,
983
- options,
984
- callback
985
- ]);
986
- } });
987
- node_http.default.request = new Proxy(node_http.default.request, { apply: (target, thisArg, args) => {
988
- const [url, options, callback] = normalizeClientRequestArgs("http:", args);
989
- options.agent = new MockAgent({
990
- customAgent: options.agent,
991
- onRequest,
992
- onResponse
993
- });
994
- return Reflect.apply(target, thisArg, [
995
- url,
996
- options,
997
- callback
998
- ]);
999
- } });
1000
- node_http.default.get = new Proxy(node_http.default.get, { apply: (target, thisArg, args) => {
1001
- const [url, options, callback] = normalizeClientRequestArgs("http:", args);
1002
- options.agent = new MockAgent({
1003
- customAgent: options.agent,
1004
- onRequest,
1005
- onResponse
1006
- });
1007
- return Reflect.apply(target, thisArg, [
1008
- url,
1009
- options,
1010
- callback
1011
- ]);
1012
- } });
1013
- node_https.default.request = new Proxy(node_https.default.request, { apply: (target, thisArg, args) => {
1014
- const [url, options, callback] = normalizeClientRequestArgs("https:", args);
1015
- options.agent = new MockHttpsAgent({
1016
- customAgent: options.agent,
1017
- onRequest,
1018
- onResponse
1019
- });
1020
- return Reflect.apply(target, thisArg, [
1021
- url,
1022
- options,
1023
- callback
1024
- ]);
1025
- } });
1026
- node_https.default.get = new Proxy(node_https.default.get, { apply: (target, thisArg, args) => {
1027
- const [url, options, callback] = normalizeClientRequestArgs("https:", args);
1028
- options.agent = new MockHttpsAgent({
1029
- customAgent: options.agent,
1030
- onRequest,
1031
- onResponse
1032
- });
1033
- return Reflect.apply(target, thisArg, [
1034
- url,
1035
- options,
1036
- callback
1037
- ]);
1038
- } });
1039
- recordRawFetchHeaders();
1040
- this.subscriptions.push(() => {
1041
- node_http.default.ClientRequest = OriginalClientRequest;
1042
- node_http.default.get = originalGet;
1043
- node_http.default.request = originalRequest;
1044
- node_https.default.get = originalHttpsGet;
1045
- node_https.default.request = originalHttpsRequest;
1046
- restoreHeadersPrototype();
1047
- });
1048
- }
1049
- };
1050
-
1051
- //#endregion
1052
- Object.defineProperty(exports, 'ClientRequestInterceptor', {
1053
- enumerable: true,
1054
- get: function () {
1055
- return ClientRequestInterceptor;
1056
- }
1057
- });
1058
- //# sourceMappingURL=ClientRequest-2loAH7xM.cjs.map