@mswjs/interceptors 0.40.0 → 0.41.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (272) hide show
  1. package/ClientRequest/package.json +7 -2
  2. package/RemoteHttpInterceptor/package.json +7 -2
  3. package/WebSocket/package.json +9 -2
  4. package/XMLHttpRequest/package.json +9 -3
  5. package/fetch/package.json +9 -3
  6. package/lib/browser/Interceptor-2mUoKZL1.d.mts +65 -0
  7. package/lib/browser/Interceptor-Deczogc8.d.cts +65 -0
  8. package/lib/browser/XMLHttpRequest-BUfglQD1.cjs +761 -0
  9. package/lib/browser/XMLHttpRequest-BUfglQD1.cjs.map +1 -0
  10. package/lib/browser/XMLHttpRequest-DS5fc8Qs.mjs +756 -0
  11. package/lib/browser/XMLHttpRequest-DS5fc8Qs.mjs.map +1 -0
  12. package/lib/browser/bufferUtils-BiiO6HZv.mjs +20 -0
  13. package/lib/browser/bufferUtils-BiiO6HZv.mjs.map +1 -0
  14. package/lib/browser/bufferUtils-Uc0eRItL.cjs +38 -0
  15. package/lib/browser/bufferUtils-Uc0eRItL.cjs.map +1 -0
  16. package/lib/browser/createRequestId-Cs4oXfa1.cjs +205 -0
  17. package/lib/browser/createRequestId-Cs4oXfa1.cjs.map +1 -0
  18. package/lib/browser/createRequestId-DQcIlohW.mjs +170 -0
  19. package/lib/browser/createRequestId-DQcIlohW.mjs.map +1 -0
  20. package/lib/browser/fetch-BHcqM3z7.cjs +253 -0
  21. package/lib/browser/fetch-BHcqM3z7.cjs.map +1 -0
  22. package/lib/browser/fetch-DSJoynSF.mjs +248 -0
  23. package/lib/browser/fetch-DSJoynSF.mjs.map +1 -0
  24. package/lib/browser/getRawRequest-BTaNLFr0.mjs +218 -0
  25. package/lib/browser/getRawRequest-BTaNLFr0.mjs.map +1 -0
  26. package/lib/browser/getRawRequest-zx8rUJL2.cjs +259 -0
  27. package/lib/browser/getRawRequest-zx8rUJL2.cjs.map +1 -0
  28. package/lib/browser/glossary-BdLS4k1H.d.cts +70 -0
  29. package/lib/browser/glossary-gEEJhK4S.d.mts +70 -0
  30. package/lib/browser/handleRequest-DI6a7Dty.cjs +189 -0
  31. package/lib/browser/handleRequest-DI6a7Dty.cjs.map +1 -0
  32. package/lib/browser/handleRequest-DxGbCTbb.mjs +178 -0
  33. package/lib/browser/handleRequest-DxGbCTbb.mjs.map +1 -0
  34. package/lib/browser/hasConfigurableGlobal-C8kXFDic.mjs +33 -0
  35. package/lib/browser/hasConfigurableGlobal-C8kXFDic.mjs.map +1 -0
  36. package/lib/browser/hasConfigurableGlobal-D7S3l5h6.cjs +45 -0
  37. package/lib/browser/hasConfigurableGlobal-D7S3l5h6.cjs.map +1 -0
  38. package/lib/browser/index.cjs +68 -0
  39. package/lib/browser/index.cjs.map +1 -0
  40. package/lib/browser/index.d.cts +87 -0
  41. package/lib/browser/index.d.mts +87 -0
  42. package/lib/browser/index.mjs +49 -77
  43. package/lib/browser/index.mjs.map +1 -1
  44. package/lib/browser/interceptors/WebSocket/index.cjs +621 -0
  45. package/lib/browser/interceptors/WebSocket/index.cjs.map +1 -0
  46. package/lib/browser/interceptors/WebSocket/index.d.cts +277 -0
  47. package/lib/browser/interceptors/WebSocket/index.d.mts +277 -0
  48. package/lib/browser/interceptors/WebSocket/index.mjs +587 -694
  49. package/lib/browser/interceptors/WebSocket/index.mjs.map +1 -1
  50. package/lib/browser/interceptors/XMLHttpRequest/index.cjs +7 -0
  51. package/lib/browser/interceptors/XMLHttpRequest/index.d.cts +15 -0
  52. package/lib/browser/interceptors/XMLHttpRequest/index.d.mts +15 -0
  53. package/lib/browser/interceptors/XMLHttpRequest/index.mjs +7 -12
  54. package/lib/browser/interceptors/fetch/index.cjs +6 -0
  55. package/lib/browser/interceptors/fetch/index.d.cts +13 -0
  56. package/lib/browser/interceptors/fetch/index.d.mts +13 -0
  57. package/lib/browser/interceptors/fetch/index.mjs +6 -11
  58. package/lib/browser/presets/browser.cjs +17 -0
  59. package/lib/browser/presets/browser.cjs.map +1 -0
  60. package/lib/browser/presets/browser.d.cts +12 -0
  61. package/lib/browser/presets/browser.d.mts +14 -0
  62. package/lib/browser/presets/browser.mjs +15 -19
  63. package/lib/browser/presets/browser.mjs.map +1 -1
  64. package/lib/node/BatchInterceptor-3LnAnLTx.cjs +49 -0
  65. package/lib/node/BatchInterceptor-3LnAnLTx.cjs.map +1 -0
  66. package/lib/node/BatchInterceptor-D7mXzHcQ.d.mts +26 -0
  67. package/lib/node/BatchInterceptor-DFaBPilf.mjs +44 -0
  68. package/lib/node/BatchInterceptor-DFaBPilf.mjs.map +1 -0
  69. package/lib/node/BatchInterceptor-D_YqR8qU.d.cts +26 -0
  70. package/lib/node/ClientRequest-2rDe54Ui.cjs +1043 -0
  71. package/lib/node/ClientRequest-2rDe54Ui.cjs.map +1 -0
  72. package/lib/node/ClientRequest-Ca8Qykuv.mjs +1034 -0
  73. package/lib/node/ClientRequest-Ca8Qykuv.mjs.map +1 -0
  74. package/lib/node/Interceptor-DEazpLJd.d.mts +133 -0
  75. package/lib/node/Interceptor-DJ2akVWI.d.cts +133 -0
  76. package/lib/node/RemoteHttpInterceptor.cjs +154 -0
  77. package/lib/node/RemoteHttpInterceptor.cjs.map +1 -0
  78. package/lib/node/RemoteHttpInterceptor.d.cts +39 -0
  79. package/lib/node/RemoteHttpInterceptor.d.mts +39 -0
  80. package/lib/node/RemoteHttpInterceptor.mjs +145 -190
  81. package/lib/node/RemoteHttpInterceptor.mjs.map +1 -1
  82. package/lib/node/XMLHttpRequest-B7kJdYYI.cjs +763 -0
  83. package/lib/node/XMLHttpRequest-B7kJdYYI.cjs.map +1 -0
  84. package/lib/node/XMLHttpRequest-C8dIZpds.mjs +757 -0
  85. package/lib/node/XMLHttpRequest-C8dIZpds.mjs.map +1 -0
  86. package/lib/node/bufferUtils-DiCTqG-7.cjs +38 -0
  87. package/lib/node/bufferUtils-DiCTqG-7.cjs.map +1 -0
  88. package/lib/node/bufferUtils-_8XfKIfX.mjs +20 -0
  89. package/lib/node/bufferUtils-_8XfKIfX.mjs.map +1 -0
  90. package/lib/node/chunk-CbDLau6x.cjs +34 -0
  91. package/lib/node/fetch-BmXpK10r.cjs +272 -0
  92. package/lib/node/fetch-BmXpK10r.cjs.map +1 -0
  93. package/lib/node/fetch-G1DVwDKG.mjs +265 -0
  94. package/lib/node/fetch-G1DVwDKG.mjs.map +1 -0
  95. package/lib/node/fetchUtils-BaY5iWXw.cjs +419 -0
  96. package/lib/node/fetchUtils-BaY5iWXw.cjs.map +1 -0
  97. package/lib/node/fetchUtils-CoU35g3M.mjs +359 -0
  98. package/lib/node/fetchUtils-CoU35g3M.mjs.map +1 -0
  99. package/lib/node/getRawRequest-BavnMWh_.cjs +36 -0
  100. package/lib/node/getRawRequest-BavnMWh_.cjs.map +1 -0
  101. package/lib/node/getRawRequest-DnwmXyOW.mjs +24 -0
  102. package/lib/node/getRawRequest-DnwmXyOW.mjs.map +1 -0
  103. package/lib/node/glossary-BLKRyLBd.cjs +12 -0
  104. package/lib/node/glossary-BLKRyLBd.cjs.map +1 -0
  105. package/lib/node/glossary-glQBRnVD.mjs +6 -0
  106. package/lib/node/glossary-glQBRnVD.mjs.map +1 -0
  107. package/lib/node/handleRequest-Bb7Y-XLw.cjs +220 -0
  108. package/lib/node/handleRequest-Bb7Y-XLw.cjs.map +1 -0
  109. package/lib/node/handleRequest-Y97UwBbF.mjs +190 -0
  110. package/lib/node/handleRequest-Y97UwBbF.mjs.map +1 -0
  111. package/lib/node/hasConfigurableGlobal-C97fWuaA.cjs +26 -0
  112. package/lib/node/hasConfigurableGlobal-C97fWuaA.cjs.map +1 -0
  113. package/lib/node/hasConfigurableGlobal-DBJA0vjm.mjs +20 -0
  114. package/lib/node/hasConfigurableGlobal-DBJA0vjm.mjs.map +1 -0
  115. package/lib/node/index-BMbJ8FXL.d.cts +113 -0
  116. package/lib/node/index-C0YAQ36w.d.mts +113 -0
  117. package/lib/node/index.cjs +30 -0
  118. package/lib/node/index.cjs.map +1 -0
  119. package/lib/node/index.d.cts +66 -0
  120. package/lib/node/index.d.mts +66 -0
  121. package/lib/node/index.mjs +13 -41
  122. package/lib/node/index.mjs.map +1 -1
  123. package/lib/node/interceptors/ClientRequest/index.cjs +6 -0
  124. package/lib/node/interceptors/ClientRequest/index.d.cts +2 -0
  125. package/lib/node/interceptors/ClientRequest/index.d.mts +3 -0
  126. package/lib/node/interceptors/ClientRequest/index.mjs +6 -11
  127. package/lib/node/interceptors/XMLHttpRequest/index.cjs +6 -0
  128. package/lib/node/interceptors/XMLHttpRequest/index.d.cts +14 -0
  129. package/lib/node/interceptors/XMLHttpRequest/index.d.mts +14 -0
  130. package/lib/node/interceptors/XMLHttpRequest/index.mjs +6 -13
  131. package/lib/node/interceptors/fetch/index.cjs +5 -0
  132. package/lib/node/interceptors/fetch/index.d.cts +12 -0
  133. package/lib/node/interceptors/fetch/index.d.mts +12 -0
  134. package/lib/node/interceptors/fetch/index.mjs +5 -12
  135. package/lib/node/node-DwCc6iuP.mjs +27 -0
  136. package/lib/node/node-DwCc6iuP.mjs.map +1 -0
  137. package/lib/node/node-dKdAf3tC.cjs +39 -0
  138. package/lib/node/node-dKdAf3tC.cjs.map +1 -0
  139. package/lib/node/presets/node.cjs +22 -0
  140. package/lib/node/presets/node.cjs.map +1 -0
  141. package/lib/node/presets/node.d.cts +13 -0
  142. package/lib/node/presets/node.d.mts +15 -0
  143. package/lib/node/presets/node.mjs +18 -23
  144. package/lib/node/presets/node.mjs.map +1 -1
  145. package/lib/node/utils/node/index.cjs +4 -0
  146. package/lib/node/utils/node/{index.d.ts → index.d.cts} +5 -2
  147. package/lib/node/utils/node/index.d.mts +16 -0
  148. package/lib/node/utils/node/index.mjs +3 -10
  149. package/package.json +33 -59
  150. package/presets/browser/package.json +2 -3
  151. package/presets/node/package.json +7 -2
  152. package/src/interceptors/ClientRequest/MockHttpSocket.ts +21 -8
  153. package/src/interceptors/ClientRequest/utils/parserUtils.ts +48 -0
  154. package/src/interceptors/WebSocket/index.ts +4 -1
  155. package/src/interceptors/XMLHttpRequest/utils/getBodyByteLength.test.ts +2 -2
  156. package/lib/browser/Interceptor-af98b768.d.ts +0 -63
  157. package/lib/browser/chunk-2HUMWGRD.js +0 -37
  158. package/lib/browser/chunk-2HUMWGRD.js.map +0 -1
  159. package/lib/browser/chunk-2MCNQOY3.js +0 -851
  160. package/lib/browser/chunk-2MCNQOY3.js.map +0 -1
  161. package/lib/browser/chunk-57RIRQUY.js +0 -218
  162. package/lib/browser/chunk-57RIRQUY.js.map +0 -1
  163. package/lib/browser/chunk-6HYIRFX2.mjs +0 -22
  164. package/lib/browser/chunk-6HYIRFX2.mjs.map +0 -1
  165. package/lib/browser/chunk-FW45TRCB.js +0 -178
  166. package/lib/browser/chunk-FW45TRCB.js.map +0 -1
  167. package/lib/browser/chunk-JQ2S7G56.js +0 -185
  168. package/lib/browser/chunk-JQ2S7G56.js.map +0 -1
  169. package/lib/browser/chunk-LIKZF2VU.mjs +0 -218
  170. package/lib/browser/chunk-LIKZF2VU.mjs.map +0 -1
  171. package/lib/browser/chunk-LK6DILFK.js +0 -22
  172. package/lib/browser/chunk-LK6DILFK.js.map +0 -1
  173. package/lib/browser/chunk-MNT2FUCH.js +0 -301
  174. package/lib/browser/chunk-MNT2FUCH.js.map +0 -1
  175. package/lib/browser/chunk-VOUOVDAW.mjs +0 -178
  176. package/lib/browser/chunk-VOUOVDAW.mjs.map +0 -1
  177. package/lib/browser/chunk-VYSDLBSS.mjs +0 -37
  178. package/lib/browser/chunk-VYSDLBSS.mjs.map +0 -1
  179. package/lib/browser/chunk-WADP6VHN.mjs +0 -851
  180. package/lib/browser/chunk-WADP6VHN.mjs.map +0 -1
  181. package/lib/browser/chunk-WOWPV4GR.mjs +0 -301
  182. package/lib/browser/chunk-WOWPV4GR.mjs.map +0 -1
  183. package/lib/browser/chunk-Z5TSB3T6.mjs +0 -185
  184. package/lib/browser/chunk-Z5TSB3T6.mjs.map +0 -1
  185. package/lib/browser/glossary-f7ee1c9d.d.ts +0 -74
  186. package/lib/browser/index.d.ts +0 -82
  187. package/lib/browser/index.js +0 -83
  188. package/lib/browser/index.js.map +0 -1
  189. package/lib/browser/interceptors/WebSocket/index.d.ts +0 -271
  190. package/lib/browser/interceptors/WebSocket/index.js +0 -721
  191. package/lib/browser/interceptors/WebSocket/index.js.map +0 -1
  192. package/lib/browser/interceptors/XMLHttpRequest/index.d.ts +0 -14
  193. package/lib/browser/interceptors/XMLHttpRequest/index.js +0 -12
  194. package/lib/browser/interceptors/XMLHttpRequest/index.js.map +0 -1
  195. package/lib/browser/interceptors/XMLHttpRequest/index.mjs.map +0 -1
  196. package/lib/browser/interceptors/fetch/index.d.ts +0 -13
  197. package/lib/browser/interceptors/fetch/index.js +0 -11
  198. package/lib/browser/interceptors/fetch/index.js.map +0 -1
  199. package/lib/browser/interceptors/fetch/index.mjs.map +0 -1
  200. package/lib/browser/presets/browser.d.ts +0 -14
  201. package/lib/browser/presets/browser.js +0 -21
  202. package/lib/browser/presets/browser.js.map +0 -1
  203. package/lib/node/BatchInterceptor-cb9a2eee.d.ts +0 -24
  204. package/lib/node/Interceptor-dc0a39b5.d.ts +0 -136
  205. package/lib/node/RemoteHttpInterceptor.d.ts +0 -44
  206. package/lib/node/RemoteHttpInterceptor.js +0 -197
  207. package/lib/node/RemoteHttpInterceptor.js.map +0 -1
  208. package/lib/node/chunk-5UGIB6OX.mjs +0 -1126
  209. package/lib/node/chunk-5UGIB6OX.mjs.map +0 -1
  210. package/lib/node/chunk-5V3SIIW2.mjs +0 -853
  211. package/lib/node/chunk-5V3SIIW2.mjs.map +0 -1
  212. package/lib/node/chunk-6B3ZQOO2.js +0 -853
  213. package/lib/node/chunk-6B3ZQOO2.js.map +0 -1
  214. package/lib/node/chunk-6HYIRFX2.mjs +0 -22
  215. package/lib/node/chunk-6HYIRFX2.mjs.map +0 -1
  216. package/lib/node/chunk-6YM4PLBI.mjs +0 -7
  217. package/lib/node/chunk-6YM4PLBI.mjs.map +0 -1
  218. package/lib/node/chunk-73NOP3T5.js +0 -7
  219. package/lib/node/chunk-73NOP3T5.js.map +0 -1
  220. package/lib/node/chunk-7Q53NNPV.js +0 -189
  221. package/lib/node/chunk-7Q53NNPV.js.map +0 -1
  222. package/lib/node/chunk-DOWWQYXZ.js +0 -369
  223. package/lib/node/chunk-DOWWQYXZ.js.map +0 -1
  224. package/lib/node/chunk-FRZQJNBO.js +0 -318
  225. package/lib/node/chunk-FRZQJNBO.js.map +0 -1
  226. package/lib/node/chunk-GKN5RBVR.mjs +0 -32
  227. package/lib/node/chunk-GKN5RBVR.mjs.map +0 -1
  228. package/lib/node/chunk-J5MULIHT.js +0 -51
  229. package/lib/node/chunk-J5MULIHT.js.map +0 -1
  230. package/lib/node/chunk-JXGB54LE.mjs +0 -369
  231. package/lib/node/chunk-JXGB54LE.mjs.map +0 -1
  232. package/lib/node/chunk-LK6DILFK.js +0 -22
  233. package/lib/node/chunk-LK6DILFK.js.map +0 -1
  234. package/lib/node/chunk-OFW5L5ET.mjs +0 -318
  235. package/lib/node/chunk-OFW5L5ET.mjs.map +0 -1
  236. package/lib/node/chunk-PFGO5BSM.js +0 -25
  237. package/lib/node/chunk-PFGO5BSM.js.map +0 -1
  238. package/lib/node/chunk-R6T7CL5E.mjs +0 -189
  239. package/lib/node/chunk-R6T7CL5E.mjs.map +0 -1
  240. package/lib/node/chunk-SQ6RHTJR.mjs +0 -51
  241. package/lib/node/chunk-SQ6RHTJR.mjs.map +0 -1
  242. package/lib/node/chunk-SRMAQGPM.js +0 -30
  243. package/lib/node/chunk-SRMAQGPM.js.map +0 -1
  244. package/lib/node/chunk-T3TW4P64.js +0 -32
  245. package/lib/node/chunk-T3TW4P64.js.map +0 -1
  246. package/lib/node/chunk-TX5GBTFY.mjs +0 -25
  247. package/lib/node/chunk-TX5GBTFY.mjs.map +0 -1
  248. package/lib/node/chunk-VYO5XDY2.js +0 -1126
  249. package/lib/node/chunk-VYO5XDY2.js.map +0 -1
  250. package/lib/node/chunk-YWNGXXUQ.mjs +0 -30
  251. package/lib/node/chunk-YWNGXXUQ.mjs.map +0 -1
  252. package/lib/node/index.d.ts +0 -61
  253. package/lib/node/index.js +0 -45
  254. package/lib/node/index.js.map +0 -1
  255. package/lib/node/interceptors/ClientRequest/index.d.ts +0 -110
  256. package/lib/node/interceptors/ClientRequest/index.js +0 -11
  257. package/lib/node/interceptors/ClientRequest/index.js.map +0 -1
  258. package/lib/node/interceptors/ClientRequest/index.mjs.map +0 -1
  259. package/lib/node/interceptors/XMLHttpRequest/index.d.ts +0 -13
  260. package/lib/node/interceptors/XMLHttpRequest/index.js +0 -13
  261. package/lib/node/interceptors/XMLHttpRequest/index.js.map +0 -1
  262. package/lib/node/interceptors/XMLHttpRequest/index.mjs.map +0 -1
  263. package/lib/node/interceptors/fetch/index.d.ts +0 -12
  264. package/lib/node/interceptors/fetch/index.js +0 -12
  265. package/lib/node/interceptors/fetch/index.js.map +0 -1
  266. package/lib/node/interceptors/fetch/index.mjs.map +0 -1
  267. package/lib/node/presets/node.d.ts +0 -15
  268. package/lib/node/presets/node.js +0 -27
  269. package/lib/node/presets/node.js.map +0 -1
  270. package/lib/node/utils/node/index.js +0 -10
  271. package/lib/node/utils/node/index.js.map +0 -1
  272. package/lib/node/utils/node/index.mjs.map +0 -1
@@ -1,1126 +0,0 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
2
-
3
- var _chunkT3TW4P64js = require('./chunk-T3TW4P64.js');
4
-
5
-
6
-
7
-
8
-
9
- var _chunk7Q53NNPVjs = require('./chunk-7Q53NNPV.js');
10
-
11
-
12
-
13
-
14
-
15
-
16
- var _chunkDOWWQYXZjs = require('./chunk-DOWWQYXZ.js');
17
-
18
-
19
- var _chunkSRMAQGPMjs = require('./chunk-SRMAQGPM.js');
20
-
21
- // src/interceptors/ClientRequest/index.ts
22
- var _http = require('http'); var _http2 = _interopRequireDefault(_http);
23
- var _https = require('https'); var _https2 = _interopRequireDefault(_https);
24
-
25
- // src/interceptors/ClientRequest/MockHttpSocket.ts
26
- var _net = require('net'); var _net2 = _interopRequireDefault(_net);
27
-
28
-
29
- var __http_common = require('_http_common');
30
-
31
- var _stream = require('stream');
32
- var _outvariant = require('outvariant');
33
-
34
- // src/interceptors/Socket/MockSocket.ts
35
-
36
-
37
- // src/interceptors/Socket/utils/normalizeSocketWriteArgs.ts
38
- function normalizeSocketWriteArgs(args) {
39
- const normalized = [args[0], void 0, void 0];
40
- if (typeof args[1] === "string") {
41
- normalized[1] = args[1];
42
- } else if (typeof args[1] === "function") {
43
- normalized[2] = args[1];
44
- }
45
- if (typeof args[2] === "function") {
46
- normalized[2] = args[2];
47
- }
48
- return normalized;
49
- }
50
-
51
- // src/interceptors/Socket/MockSocket.ts
52
- var MockSocket = class extends _net2.default.Socket {
53
- constructor(options) {
54
- super();
55
- this.options = options;
56
- this.connecting = false;
57
- this.connect();
58
- this._final = (callback) => {
59
- callback(null);
60
- };
61
- }
62
- connect() {
63
- this.connecting = true;
64
- return this;
65
- }
66
- write(...args) {
67
- const [chunk, encoding, callback] = normalizeSocketWriteArgs(
68
- args
69
- );
70
- this.options.write(chunk, encoding, callback);
71
- return true;
72
- }
73
- end(...args) {
74
- const [chunk, encoding, callback] = normalizeSocketWriteArgs(
75
- args
76
- );
77
- this.options.write(chunk, encoding, callback);
78
- return super.end.apply(this, args);
79
- }
80
- push(chunk, encoding) {
81
- this.options.read(chunk, encoding);
82
- return super.push(chunk, encoding);
83
- }
84
- };
85
-
86
- // src/interceptors/Socket/utils/baseUrlFromConnectionOptions.ts
87
- function baseUrlFromConnectionOptions(options) {
88
- if ("href" in options) {
89
- return new URL(options.href);
90
- }
91
- const protocol = options.port === 443 ? "https:" : "http:";
92
- const host = options.host;
93
- const url = new URL(`${protocol}//${host}`);
94
- if (options.port) {
95
- url.port = options.port.toString();
96
- }
97
- if (options.path) {
98
- url.pathname = options.path;
99
- }
100
- if (options.auth) {
101
- const [username, password] = options.auth.split(":");
102
- url.username = username;
103
- url.password = password;
104
- }
105
- return url;
106
- }
107
-
108
- // src/interceptors/ClientRequest/utils/recordRawHeaders.ts
109
- var kRawHeaders = Symbol("kRawHeaders");
110
- var kRestorePatches = Symbol("kRestorePatches");
111
- function recordRawHeader(headers, args, behavior) {
112
- ensureRawHeadersSymbol(headers, []);
113
- const rawHeaders = Reflect.get(headers, kRawHeaders);
114
- if (behavior === "set") {
115
- for (let index = rawHeaders.length - 1; index >= 0; index--) {
116
- if (rawHeaders[index][0].toLowerCase() === args[0].toLowerCase()) {
117
- rawHeaders.splice(index, 1);
118
- }
119
- }
120
- }
121
- rawHeaders.push(args);
122
- }
123
- function ensureRawHeadersSymbol(headers, rawHeaders) {
124
- if (Reflect.has(headers, kRawHeaders)) {
125
- return;
126
- }
127
- defineRawHeadersSymbol(headers, rawHeaders);
128
- }
129
- function defineRawHeadersSymbol(headers, rawHeaders) {
130
- Object.defineProperty(headers, kRawHeaders, {
131
- value: rawHeaders,
132
- enumerable: false,
133
- // Mark the symbol as configurable so its value can be overridden.
134
- // Overrides happen when merging raw headers from multiple sources.
135
- // E.g. new Request(new Request(url, { headers }), { headers })
136
- configurable: true
137
- });
138
- }
139
- function recordRawFetchHeaders() {
140
- if (Reflect.get(Headers, kRestorePatches)) {
141
- return Reflect.get(Headers, kRestorePatches);
142
- }
143
- const {
144
- Headers: OriginalHeaders,
145
- Request: OriginalRequest,
146
- Response: OriginalResponse
147
- } = globalThis;
148
- const { set, append, delete: headersDeleteMethod } = Headers.prototype;
149
- Object.defineProperty(Headers, kRestorePatches, {
150
- value: () => {
151
- Headers.prototype.set = set;
152
- Headers.prototype.append = append;
153
- Headers.prototype.delete = headersDeleteMethod;
154
- globalThis.Headers = OriginalHeaders;
155
- globalThis.Request = OriginalRequest;
156
- globalThis.Response = OriginalResponse;
157
- Reflect.deleteProperty(Headers, kRestorePatches);
158
- },
159
- enumerable: false,
160
- /**
161
- * @note Mark this property as configurable
162
- * so we can delete it using `Reflect.delete` during cleanup.
163
- */
164
- configurable: true
165
- });
166
- Object.defineProperty(globalThis, "Headers", {
167
- enumerable: true,
168
- writable: true,
169
- value: new Proxy(Headers, {
170
- construct(target, args, newTarget) {
171
- const headersInit = args[0] || [];
172
- if (headersInit instanceof Headers && Reflect.has(headersInit, kRawHeaders)) {
173
- const headers2 = Reflect.construct(
174
- target,
175
- [Reflect.get(headersInit, kRawHeaders)],
176
- newTarget
177
- );
178
- ensureRawHeadersSymbol(headers2, [
179
- /**
180
- * @note Spread the retrieved headers to clone them.
181
- * This prevents multiple Headers instances from pointing
182
- * at the same internal "rawHeaders" array.
183
- */
184
- ...Reflect.get(headersInit, kRawHeaders)
185
- ]);
186
- return headers2;
187
- }
188
- const headers = Reflect.construct(target, args, newTarget);
189
- if (!Reflect.has(headers, kRawHeaders)) {
190
- const rawHeadersInit = Array.isArray(headersInit) ? headersInit : Object.entries(headersInit);
191
- ensureRawHeadersSymbol(headers, rawHeadersInit);
192
- }
193
- return headers;
194
- }
195
- })
196
- });
197
- Headers.prototype.set = new Proxy(Headers.prototype.set, {
198
- apply(target, thisArg, args) {
199
- recordRawHeader(thisArg, args, "set");
200
- return Reflect.apply(target, thisArg, args);
201
- }
202
- });
203
- Headers.prototype.append = new Proxy(Headers.prototype.append, {
204
- apply(target, thisArg, args) {
205
- recordRawHeader(thisArg, args, "append");
206
- return Reflect.apply(target, thisArg, args);
207
- }
208
- });
209
- Headers.prototype.delete = new Proxy(Headers.prototype.delete, {
210
- apply(target, thisArg, args) {
211
- const rawHeaders = Reflect.get(thisArg, kRawHeaders);
212
- if (rawHeaders) {
213
- for (let index = rawHeaders.length - 1; index >= 0; index--) {
214
- if (rawHeaders[index][0].toLowerCase() === args[0].toLowerCase()) {
215
- rawHeaders.splice(index, 1);
216
- }
217
- }
218
- }
219
- return Reflect.apply(target, thisArg, args);
220
- }
221
- });
222
- Object.defineProperty(globalThis, "Request", {
223
- enumerable: true,
224
- writable: true,
225
- value: new Proxy(Request, {
226
- construct(target, args, newTarget) {
227
- const request = Reflect.construct(target, args, newTarget);
228
- const inferredRawHeaders = [];
229
- if (typeof args[0] === "object" && args[0].headers != null) {
230
- inferredRawHeaders.push(...inferRawHeaders(args[0].headers));
231
- }
232
- if (typeof args[1] === "object" && args[1].headers != null) {
233
- inferredRawHeaders.push(...inferRawHeaders(args[1].headers));
234
- }
235
- if (inferredRawHeaders.length > 0) {
236
- ensureRawHeadersSymbol(request.headers, inferredRawHeaders);
237
- }
238
- return request;
239
- }
240
- })
241
- });
242
- Object.defineProperty(globalThis, "Response", {
243
- enumerable: true,
244
- writable: true,
245
- value: new Proxy(Response, {
246
- construct(target, args, newTarget) {
247
- const response = Reflect.construct(target, args, newTarget);
248
- if (typeof args[1] === "object" && args[1].headers != null) {
249
- ensureRawHeadersSymbol(
250
- response.headers,
251
- inferRawHeaders(args[1].headers)
252
- );
253
- }
254
- return response;
255
- }
256
- })
257
- });
258
- }
259
- function restoreHeadersPrototype() {
260
- if (!Reflect.get(Headers, kRestorePatches)) {
261
- return;
262
- }
263
- Reflect.get(Headers, kRestorePatches)();
264
- }
265
- function getRawFetchHeaders(headers) {
266
- if (!Reflect.has(headers, kRawHeaders)) {
267
- return Array.from(headers.entries());
268
- }
269
- const rawHeaders = Reflect.get(headers, kRawHeaders);
270
- return rawHeaders.length > 0 ? rawHeaders : Array.from(headers.entries());
271
- }
272
- function inferRawHeaders(headers) {
273
- if (headers instanceof Headers) {
274
- return Reflect.get(headers, kRawHeaders) || [];
275
- }
276
- return Reflect.get(new Headers(headers), kRawHeaders);
277
- }
278
-
279
- // src/interceptors/ClientRequest/MockHttpSocket.ts
280
- var kRequestId = Symbol("kRequestId");
281
- var MockHttpSocket = class extends MockSocket {
282
- constructor(options) {
283
- super({
284
- write: (chunk, encoding, callback) => {
285
- var _a;
286
- if (this.socketState !== "passthrough") {
287
- this.writeBuffer.push([chunk, encoding, callback]);
288
- }
289
- if (chunk) {
290
- if (this.socketState === "passthrough") {
291
- (_a = this.originalSocket) == null ? void 0 : _a.write(chunk, encoding, callback);
292
- }
293
- this.requestParser.execute(
294
- Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding)
295
- );
296
- }
297
- },
298
- read: (chunk) => {
299
- if (chunk !== null) {
300
- this.responseParser.execute(
301
- Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)
302
- );
303
- }
304
- }
305
- });
306
- this.requestRawHeadersBuffer = [];
307
- this.responseRawHeadersBuffer = [];
308
- this.writeBuffer = [];
309
- this.socketState = "unknown";
310
- /**
311
- * This callback might be called when the request is "slow":
312
- * - Request headers were fragmented across multiple TCP packages;
313
- * - Request headers were too large to be processed in a single run
314
- * (e.g. more than 30 request headers).
315
- * @note This is called before request start.
316
- */
317
- this.onRequestHeaders = (rawHeaders) => {
318
- this.requestRawHeadersBuffer.push(...rawHeaders);
319
- };
320
- this.onRequestStart = (versionMajor, versionMinor, rawHeaders, _, path, __, ___, ____, shouldKeepAlive) => {
321
- var _a;
322
- this.shouldKeepAlive = shouldKeepAlive;
323
- const url = new URL(path || "", this.baseUrl);
324
- const method = ((_a = this.connectionOptions.method) == null ? void 0 : _a.toUpperCase()) || "GET";
325
- const headers = _chunkDOWWQYXZjs.FetchResponse.parseRawHeaders([
326
- ...this.requestRawHeadersBuffer,
327
- ...rawHeaders || []
328
- ]);
329
- this.requestRawHeadersBuffer.length = 0;
330
- const canHaveBody = method !== "GET" && method !== "HEAD";
331
- if (url.username || url.password) {
332
- if (!headers.has("authorization")) {
333
- headers.set("authorization", `Basic ${url.username}:${url.password}`);
334
- }
335
- url.username = "";
336
- url.password = "";
337
- }
338
- this.requestStream = new (0, _stream.Readable)({
339
- /**
340
- * @note Provide the `read()` method so a `Readable` could be
341
- * used as the actual request body (the stream calls "read()").
342
- * We control the queue in the onRequestBody/End functions.
343
- */
344
- read: () => {
345
- this.flushWriteBuffer();
346
- }
347
- });
348
- const requestId = _chunkDOWWQYXZjs.createRequestId.call(void 0, );
349
- this.request = new Request(url, {
350
- method,
351
- headers,
352
- credentials: "same-origin",
353
- // @ts-expect-error Undocumented Fetch property.
354
- duplex: canHaveBody ? "half" : void 0,
355
- body: canHaveBody ? _stream.Readable.toWeb(this.requestStream) : null
356
- });
357
- Reflect.set(this.request, kRequestId, requestId);
358
- _chunkSRMAQGPMjs.setRawRequest.call(void 0, this.request, Reflect.get(this, "_httpMessage"));
359
- _chunkT3TW4P64js.setRawRequestBodyStream.call(void 0, this.request, this.requestStream);
360
- if (this.request.headers.has(_chunkDOWWQYXZjs.INTERNAL_REQUEST_ID_HEADER_NAME)) {
361
- this.passthrough();
362
- return;
363
- }
364
- this.onRequest({
365
- requestId,
366
- request: this.request,
367
- socket: this
368
- });
369
- };
370
- /**
371
- * This callback might be called when the response is "slow":
372
- * - Response headers were fragmented across multiple TCP packages;
373
- * - Response headers were too large to be processed in a single run
374
- * (e.g. more than 30 response headers).
375
- * @note This is called before response start.
376
- */
377
- this.onResponseHeaders = (rawHeaders) => {
378
- this.responseRawHeadersBuffer.push(...rawHeaders);
379
- };
380
- this.onResponseStart = (versionMajor, versionMinor, rawHeaders, method, url, status, statusText) => {
381
- const headers = _chunkDOWWQYXZjs.FetchResponse.parseRawHeaders([
382
- ...this.responseRawHeadersBuffer,
383
- ...rawHeaders || []
384
- ]);
385
- this.responseRawHeadersBuffer.length = 0;
386
- const response = new (0, _chunkDOWWQYXZjs.FetchResponse)(
387
- /**
388
- * @note The Fetch API response instance exposed to the consumer
389
- * is created over the response stream of the HTTP parser. It is NOT
390
- * related to the Socket instance. This way, you can read response body
391
- * in response listener while the Socket instance delays the emission
392
- * of "end" and other events until those response listeners are finished.
393
- */
394
- _chunkDOWWQYXZjs.FetchResponse.isResponseWithBody(status) ? _stream.Readable.toWeb(
395
- this.responseStream = new (0, _stream.Readable)({ read() {
396
- } })
397
- ) : null,
398
- {
399
- url,
400
- status,
401
- statusText,
402
- headers
403
- }
404
- );
405
- _outvariant.invariant.call(void 0,
406
- this.request,
407
- "Failed to handle a response: request does not exist"
408
- );
409
- _chunkDOWWQYXZjs.FetchResponse.setUrl(this.request.url, response);
410
- if (this.request.headers.has(_chunkDOWWQYXZjs.INTERNAL_REQUEST_ID_HEADER_NAME)) {
411
- return;
412
- }
413
- this.responseListenersPromise = this.onResponse({
414
- response,
415
- isMockedResponse: this.socketState === "mock",
416
- requestId: Reflect.get(this.request, kRequestId),
417
- request: this.request,
418
- socket: this
419
- });
420
- };
421
- this.connectionOptions = options.connectionOptions;
422
- this.createConnection = options.createConnection;
423
- this.onRequest = options.onRequest;
424
- this.onResponse = options.onResponse;
425
- this.baseUrl = baseUrlFromConnectionOptions(this.connectionOptions);
426
- this.requestParser = new (0, __http_common.HTTPParser)();
427
- this.requestParser.initialize(__http_common.HTTPParser.REQUEST, {});
428
- this.requestParser[__http_common.HTTPParser.kOnHeaders] = this.onRequestHeaders.bind(this);
429
- this.requestParser[__http_common.HTTPParser.kOnHeadersComplete] = this.onRequestStart.bind(this);
430
- this.requestParser[__http_common.HTTPParser.kOnBody] = this.onRequestBody.bind(this);
431
- this.requestParser[__http_common.HTTPParser.kOnMessageComplete] = this.onRequestEnd.bind(this);
432
- this.responseParser = new (0, __http_common.HTTPParser)();
433
- this.responseParser.initialize(__http_common.HTTPParser.RESPONSE, {});
434
- this.responseParser[__http_common.HTTPParser.kOnHeaders] = this.onResponseHeaders.bind(this);
435
- this.responseParser[__http_common.HTTPParser.kOnHeadersComplete] = this.onResponseStart.bind(this);
436
- this.responseParser[__http_common.HTTPParser.kOnBody] = this.onResponseBody.bind(this);
437
- this.responseParser[__http_common.HTTPParser.kOnMessageComplete] = this.onResponseEnd.bind(this);
438
- this.once("finish", () => this.requestParser.free());
439
- if (this.baseUrl.protocol === "https:") {
440
- Reflect.set(this, "encrypted", true);
441
- Reflect.set(this, "authorized", false);
442
- Reflect.set(this, "getProtocol", () => "TLSv1.3");
443
- Reflect.set(this, "getSession", () => void 0);
444
- Reflect.set(this, "isSessionReused", () => false);
445
- Reflect.set(this, "getCipher", () => ({ name: "AES256-SHA", standardName: "TLS_RSA_WITH_AES_256_CBC_SHA", version: "TLSv1.3" }));
446
- }
447
- }
448
- emit(event, ...args) {
449
- const emitEvent = super.emit.bind(this, event, ...args);
450
- if (this.responseListenersPromise) {
451
- this.responseListenersPromise.finally(emitEvent);
452
- return this.listenerCount(event) > 0;
453
- }
454
- return emitEvent();
455
- }
456
- destroy(error) {
457
- this.responseParser.free();
458
- if (error) {
459
- this.emit("error", error);
460
- }
461
- return super.destroy(error);
462
- }
463
- /**
464
- * Establish this Socket connection as-is and pipe
465
- * its data/events through this Socket.
466
- */
467
- passthrough() {
468
- this.socketState = "passthrough";
469
- if (this.destroyed) {
470
- return;
471
- }
472
- const socket = this.createConnection();
473
- this.originalSocket = socket;
474
- if ("_handle" in socket) {
475
- Object.defineProperty(this, "_handle", {
476
- value: socket._handle,
477
- enumerable: true,
478
- writable: true
479
- });
480
- }
481
- this.once("error", (error) => {
482
- socket.destroy(error);
483
- });
484
- this.address = socket.address.bind(socket);
485
- let writeArgs;
486
- let headersWritten = false;
487
- while (writeArgs = this.writeBuffer.shift()) {
488
- if (writeArgs !== void 0) {
489
- if (!headersWritten) {
490
- const [chunk, encoding, callback] = writeArgs;
491
- const chunkString = chunk.toString();
492
- const chunkBeforeRequestHeaders = chunkString.slice(
493
- 0,
494
- chunkString.indexOf("\r\n") + 2
495
- );
496
- const chunkAfterRequestHeaders = chunkString.slice(
497
- chunk.indexOf("\r\n\r\n")
498
- );
499
- const rawRequestHeaders = getRawFetchHeaders(this.request.headers);
500
- const requestHeadersString = rawRequestHeaders.filter(([name]) => {
501
- return name.toLowerCase() !== _chunkDOWWQYXZjs.INTERNAL_REQUEST_ID_HEADER_NAME;
502
- }).map(([name, value]) => `${name}: ${value}`).join("\r\n");
503
- const headersChunk = `${chunkBeforeRequestHeaders}${requestHeadersString}${chunkAfterRequestHeaders}`;
504
- socket.write(headersChunk, encoding, callback);
505
- headersWritten = true;
506
- continue;
507
- }
508
- socket.write(...writeArgs);
509
- }
510
- }
511
- if (Reflect.get(socket, "encrypted")) {
512
- const tlsProperties = [
513
- "encrypted",
514
- "authorized",
515
- "getProtocol",
516
- "getSession",
517
- "isSessionReused",
518
- "getCipher"
519
- ];
520
- tlsProperties.forEach((propertyName) => {
521
- Object.defineProperty(this, propertyName, {
522
- enumerable: true,
523
- get: () => {
524
- const value = Reflect.get(socket, propertyName);
525
- return typeof value === "function" ? value.bind(socket) : value;
526
- }
527
- });
528
- });
529
- }
530
- socket.on("lookup", (...args) => this.emit("lookup", ...args)).on("connect", () => {
531
- this.connecting = socket.connecting;
532
- this.emit("connect");
533
- }).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) => {
534
- this.push(chunk);
535
- }).on("error", (error) => {
536
- Reflect.set(this, "_hadError", Reflect.get(socket, "_hadError"));
537
- this.emit("error", error);
538
- }).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"));
539
- }
540
- /**
541
- * Convert the given Fetch API `Response` instance to an
542
- * HTTP message and push it to the socket.
543
- */
544
- async respondWith(response) {
545
- var _a, _b, _c;
546
- if (this.destroyed) {
547
- return;
548
- }
549
- _outvariant.invariant.call(void 0,
550
- this.socketState !== "mock",
551
- '[MockHttpSocket] Failed to respond to the "%s %s" request with "%s %s": the request has already been handled',
552
- (_a = this.request) == null ? void 0 : _a.method,
553
- (_b = this.request) == null ? void 0 : _b.url,
554
- response.status,
555
- response.statusText
556
- );
557
- if (_chunk7Q53NNPVjs.isPropertyAccessible.call(void 0, response, "type") && response.type === "error") {
558
- this.errorWith(new TypeError("Network error"));
559
- return;
560
- }
561
- this.mockConnect();
562
- this.socketState = "mock";
563
- this.flushWriteBuffer();
564
- const serverResponse = new (0, _http.ServerResponse)(new (0, _http.IncomingMessage)(this));
565
- serverResponse.assignSocket(
566
- new MockSocket({
567
- write: (chunk, encoding, callback) => {
568
- this.push(chunk, encoding);
569
- callback == null ? void 0 : callback();
570
- },
571
- read() {
572
- }
573
- })
574
- );
575
- serverResponse.removeHeader("connection");
576
- serverResponse.removeHeader("date");
577
- const rawResponseHeaders = getRawFetchHeaders(response.headers);
578
- serverResponse.writeHead(
579
- response.status,
580
- response.statusText || _http.STATUS_CODES[response.status],
581
- rawResponseHeaders
582
- );
583
- this.once("error", () => {
584
- serverResponse.destroy();
585
- });
586
- if (response.body) {
587
- try {
588
- const reader = response.body.getReader();
589
- while (true) {
590
- const { done, value } = await reader.read();
591
- if (done) {
592
- serverResponse.end();
593
- break;
594
- }
595
- serverResponse.write(value);
596
- }
597
- } catch (error) {
598
- if (error instanceof Error) {
599
- serverResponse.destroy();
600
- this.destroy();
601
- return;
602
- }
603
- serverResponse.destroy();
604
- throw error;
605
- }
606
- } else {
607
- serverResponse.end();
608
- }
609
- if (!this.shouldKeepAlive) {
610
- this.emit("readable");
611
- (_c = this.responseStream) == null ? void 0 : _c.push(null);
612
- this.push(null);
613
- }
614
- }
615
- /**
616
- * Close this socket connection with the given error.
617
- */
618
- errorWith(error) {
619
- this.destroy(error);
620
- }
621
- mockConnect() {
622
- this.connecting = false;
623
- const isIPv6 = _net2.default.isIPv6(this.connectionOptions.hostname) || this.connectionOptions.family === 6;
624
- const addressInfo = {
625
- address: isIPv6 ? "::1" : "127.0.0.1",
626
- family: isIPv6 ? "IPv6" : "IPv4",
627
- port: this.connectionOptions.port
628
- };
629
- this.address = () => addressInfo;
630
- this.emit(
631
- "lookup",
632
- null,
633
- addressInfo.address,
634
- addressInfo.family === "IPv6" ? 6 : 4,
635
- this.connectionOptions.host
636
- );
637
- this.emit("connect");
638
- this.emit("ready");
639
- if (this.baseUrl.protocol === "https:") {
640
- this.emit("secure");
641
- this.emit("secureConnect");
642
- this.emit(
643
- "session",
644
- this.connectionOptions.session || Buffer.from("mock-session-renegotiate")
645
- );
646
- this.emit("session", Buffer.from("mock-session-resume"));
647
- }
648
- }
649
- flushWriteBuffer() {
650
- for (const writeCall of this.writeBuffer) {
651
- if (typeof writeCall[2] === "function") {
652
- writeCall[2]();
653
- writeCall[2] = void 0;
654
- }
655
- }
656
- }
657
- onRequestBody(chunk) {
658
- _outvariant.invariant.call(void 0,
659
- this.requestStream,
660
- "Failed to write to a request stream: stream does not exist"
661
- );
662
- this.requestStream.push(chunk);
663
- }
664
- onRequestEnd() {
665
- if (this.requestStream) {
666
- this.requestStream.push(null);
667
- }
668
- }
669
- onResponseBody(chunk) {
670
- _outvariant.invariant.call(void 0,
671
- this.responseStream,
672
- "Failed to write to a response stream: stream does not exist"
673
- );
674
- this.responseStream.push(chunk);
675
- }
676
- onResponseEnd() {
677
- if (this.responseStream) {
678
- this.responseStream.push(null);
679
- }
680
- }
681
- };
682
-
683
- // src/interceptors/ClientRequest/agents.ts
684
-
685
-
686
- var MockAgent = class extends _http2.default.Agent {
687
- constructor(options) {
688
- super();
689
- this.customAgent = options.customAgent;
690
- this.onRequest = options.onRequest;
691
- this.onResponse = options.onResponse;
692
- }
693
- createConnection(options, callback) {
694
- const createConnection = this.customAgent instanceof _http2.default.Agent ? this.customAgent.createConnection : super.createConnection;
695
- const createConnectionOptions = this.customAgent instanceof _http2.default.Agent ? {
696
- ...options,
697
- ...this.customAgent.options
698
- } : options;
699
- const socket = new MockHttpSocket({
700
- connectionOptions: options,
701
- createConnection: createConnection.bind(
702
- this.customAgent || this,
703
- createConnectionOptions,
704
- callback
705
- ),
706
- onRequest: this.onRequest.bind(this),
707
- onResponse: this.onResponse.bind(this)
708
- });
709
- return socket;
710
- }
711
- };
712
- var MockHttpsAgent = class extends _https2.default.Agent {
713
- constructor(options) {
714
- super();
715
- this.customAgent = options.customAgent;
716
- this.onRequest = options.onRequest;
717
- this.onResponse = options.onResponse;
718
- }
719
- createConnection(options, callback) {
720
- const createConnection = this.customAgent instanceof _http2.default.Agent ? this.customAgent.createConnection : super.createConnection;
721
- const createConnectionOptions = this.customAgent instanceof _http2.default.Agent ? {
722
- ...options,
723
- ...this.customAgent.options
724
- } : options;
725
- const socket = new MockHttpSocket({
726
- connectionOptions: options,
727
- createConnection: createConnection.bind(
728
- this.customAgent || this,
729
- createConnectionOptions,
730
- callback
731
- ),
732
- onRequest: this.onRequest.bind(this),
733
- onResponse: this.onResponse.bind(this)
734
- });
735
- return socket;
736
- }
737
- };
738
-
739
- // src/interceptors/ClientRequest/utils/normalizeClientRequestArgs.ts
740
- var _url = require('url');
741
-
742
-
743
-
744
-
745
-
746
-
747
-
748
-
749
-
750
-
751
- var _logger = require('@open-draft/logger');
752
-
753
- // src/utils/getUrlByRequestOptions.ts
754
-
755
-
756
- var logger = new (0, _logger.Logger)("utils getUrlByRequestOptions");
757
- var DEFAULT_PATH = "/";
758
- var DEFAULT_PROTOCOL = "http:";
759
- var DEFAULT_HOSTNAME = "localhost";
760
- var SSL_PORT = 443;
761
- function getAgent(options) {
762
- return options.agent instanceof _http.Agent ? options.agent : void 0;
763
- }
764
- function getProtocolByRequestOptions(options) {
765
- var _a;
766
- if (options.protocol) {
767
- return options.protocol;
768
- }
769
- const agent = getAgent(options);
770
- const agentProtocol = agent == null ? void 0 : agent.protocol;
771
- if (agentProtocol) {
772
- return agentProtocol;
773
- }
774
- const port = getPortByRequestOptions(options);
775
- const isSecureRequest = options.cert || port === SSL_PORT;
776
- return isSecureRequest ? "https:" : ((_a = options.uri) == null ? void 0 : _a.protocol) || DEFAULT_PROTOCOL;
777
- }
778
- function getPortByRequestOptions(options) {
779
- if (options.port) {
780
- return Number(options.port);
781
- }
782
- const agent = getAgent(options);
783
- if (agent == null ? void 0 : agent.options.port) {
784
- return Number(agent.options.port);
785
- }
786
- if (agent == null ? void 0 : agent.defaultPort) {
787
- return Number(agent.defaultPort);
788
- }
789
- return void 0;
790
- }
791
- function getAuthByRequestOptions(options) {
792
- if (options.auth) {
793
- const [username, password] = options.auth.split(":");
794
- return { username, password };
795
- }
796
- }
797
- function isRawIPv6Address(host) {
798
- return host.includes(":") && !host.startsWith("[") && !host.endsWith("]");
799
- }
800
- function getHostname(options) {
801
- let host = options.hostname || options.host;
802
- if (host) {
803
- if (isRawIPv6Address(host)) {
804
- host = `[${host}]`;
805
- }
806
- return new URL(`http://${host}`).hostname;
807
- }
808
- return DEFAULT_HOSTNAME;
809
- }
810
- function getUrlByRequestOptions(options) {
811
- logger.info("request options", options);
812
- if (options.uri) {
813
- logger.info(
814
- 'constructing url from explicitly provided "options.uri": %s',
815
- options.uri
816
- );
817
- return new URL(options.uri.href);
818
- }
819
- logger.info("figuring out url from request options...");
820
- const protocol = getProtocolByRequestOptions(options);
821
- logger.info("protocol", protocol);
822
- const port = getPortByRequestOptions(options);
823
- logger.info("port", port);
824
- const hostname = getHostname(options);
825
- logger.info("hostname", hostname);
826
- const path = options.path || DEFAULT_PATH;
827
- logger.info("path", path);
828
- const credentials = getAuthByRequestOptions(options);
829
- logger.info("credentials", credentials);
830
- const authString = credentials ? `${credentials.username}:${credentials.password}@` : "";
831
- logger.info("auth string:", authString);
832
- const portString = typeof port !== "undefined" ? `:${port}` : "";
833
- const url = new URL(`${protocol}//${hostname}${portString}${path}`);
834
- url.username = (credentials == null ? void 0 : credentials.username) || "";
835
- url.password = (credentials == null ? void 0 : credentials.password) || "";
836
- logger.info("created url:", url);
837
- return url;
838
- }
839
-
840
- // src/utils/cloneObject.ts
841
-
842
- var logger2 = new (0, _logger.Logger)("cloneObject");
843
- function isPlainObject(obj) {
844
- var _a;
845
- logger2.info("is plain object?", obj);
846
- if (obj == null || !((_a = obj.constructor) == null ? void 0 : _a.name)) {
847
- logger2.info("given object is undefined, not a plain object...");
848
- return false;
849
- }
850
- logger2.info("checking the object constructor:", obj.constructor.name);
851
- return obj.constructor.name === "Object";
852
- }
853
- function cloneObject(obj) {
854
- logger2.info("cloning object:", obj);
855
- const enumerableProperties = Object.entries(obj).reduce(
856
- (acc, [key, value]) => {
857
- logger2.info("analyzing key-value pair:", key, value);
858
- acc[key] = isPlainObject(value) ? cloneObject(value) : value;
859
- return acc;
860
- },
861
- {}
862
- );
863
- return isPlainObject(obj) ? enumerableProperties : Object.assign(Object.getPrototypeOf(obj), enumerableProperties);
864
- }
865
-
866
- // src/interceptors/ClientRequest/utils/normalizeClientRequestArgs.ts
867
- var logger3 = new (0, _logger.Logger)("http normalizeClientRequestArgs");
868
- function resolveRequestOptions(args, url) {
869
- if (typeof args[1] === "undefined" || typeof args[1] === "function") {
870
- logger3.info("request options not provided, deriving from the url", url);
871
- return _url.urlToHttpOptions.call(void 0, url);
872
- }
873
- if (args[1]) {
874
- logger3.info("has custom RequestOptions!", args[1]);
875
- const requestOptionsFromUrl = _url.urlToHttpOptions.call(void 0, url);
876
- logger3.info("derived RequestOptions from the URL:", requestOptionsFromUrl);
877
- logger3.info("cloning RequestOptions...");
878
- const clonedRequestOptions = cloneObject(args[1]);
879
- logger3.info("successfully cloned RequestOptions!", clonedRequestOptions);
880
- return {
881
- ...requestOptionsFromUrl,
882
- ...clonedRequestOptions
883
- };
884
- }
885
- logger3.info("using an empty object as request options");
886
- return {};
887
- }
888
- function overrideUrlByRequestOptions(url, options) {
889
- url.host = options.host || url.host;
890
- url.hostname = options.hostname || url.hostname;
891
- url.port = options.port ? options.port.toString() : url.port;
892
- if (options.path) {
893
- const parsedOptionsPath = _url.parse.call(void 0, options.path, false);
894
- url.pathname = parsedOptionsPath.pathname || "";
895
- url.search = parsedOptionsPath.search || "";
896
- }
897
- return url;
898
- }
899
- function resolveCallback(args) {
900
- return typeof args[1] === "function" ? args[1] : args[2];
901
- }
902
- function normalizeClientRequestArgs(defaultProtocol, args) {
903
- let url;
904
- let options;
905
- let callback;
906
- logger3.info("arguments", args);
907
- logger3.info("using default protocol:", defaultProtocol);
908
- if (args.length === 0) {
909
- const url2 = new (0, _url.URL)("http://localhost");
910
- const options2 = resolveRequestOptions(args, url2);
911
- return [url2, options2];
912
- }
913
- if (typeof args[0] === "string") {
914
- logger3.info("first argument is a location string:", args[0]);
915
- url = new (0, _url.URL)(args[0]);
916
- logger3.info("created a url:", url);
917
- const requestOptionsFromUrl = _url.urlToHttpOptions.call(void 0, url);
918
- logger3.info("request options from url:", requestOptionsFromUrl);
919
- options = resolveRequestOptions(args, url);
920
- logger3.info("resolved request options:", options);
921
- callback = resolveCallback(args);
922
- } else if (args[0] instanceof _url.URL) {
923
- url = args[0];
924
- logger3.info("first argument is a URL:", url);
925
- if (typeof args[1] !== "undefined" && _chunk7Q53NNPVjs.isObject.call(void 0, args[1])) {
926
- url = overrideUrlByRequestOptions(url, args[1]);
927
- }
928
- options = resolveRequestOptions(args, url);
929
- logger3.info("derived request options:", options);
930
- callback = resolveCallback(args);
931
- } else if ("hash" in args[0] && !("method" in args[0])) {
932
- const [legacyUrl] = args;
933
- logger3.info("first argument is a legacy URL:", legacyUrl);
934
- if (legacyUrl.hostname === null) {
935
- logger3.info("given legacy URL is relative (no hostname)");
936
- return _chunk7Q53NNPVjs.isObject.call(void 0, args[1]) ? normalizeClientRequestArgs(defaultProtocol, [
937
- { path: legacyUrl.path, ...args[1] },
938
- args[2]
939
- ]) : normalizeClientRequestArgs(defaultProtocol, [
940
- { path: legacyUrl.path },
941
- args[1]
942
- ]);
943
- }
944
- logger3.info("given legacy url is absolute");
945
- const resolvedUrl = new (0, _url.URL)(legacyUrl.href);
946
- return args[1] === void 0 ? normalizeClientRequestArgs(defaultProtocol, [resolvedUrl]) : typeof args[1] === "function" ? normalizeClientRequestArgs(defaultProtocol, [resolvedUrl, args[1]]) : normalizeClientRequestArgs(defaultProtocol, [
947
- resolvedUrl,
948
- args[1],
949
- args[2]
950
- ]);
951
- } else if (_chunk7Q53NNPVjs.isObject.call(void 0, args[0])) {
952
- options = { ...args[0] };
953
- logger3.info("first argument is RequestOptions:", options);
954
- options.protocol = options.protocol || defaultProtocol;
955
- logger3.info("normalized request options:", options);
956
- url = getUrlByRequestOptions(options);
957
- logger3.info("created a URL from RequestOptions:", url.href);
958
- callback = resolveCallback(args);
959
- } else {
960
- throw new Error(
961
- `Failed to construct ClientRequest with these parameters: ${args}`
962
- );
963
- }
964
- options.protocol = options.protocol || url.protocol;
965
- options.method = options.method || "GET";
966
- if (!options._defaultAgent) {
967
- logger3.info(
968
- 'has no default agent, setting the default agent for "%s"',
969
- options.protocol
970
- );
971
- options._defaultAgent = options.protocol === "https:" ? _https.globalAgent : _http.globalAgent;
972
- }
973
- logger3.info("successfully resolved url:", url.href);
974
- logger3.info("successfully resolved options:", options);
975
- logger3.info("successfully resolved callback:", callback);
976
- if (!(url instanceof _url.URL)) {
977
- url = url.toString();
978
- }
979
- return [url, options, callback];
980
- }
981
-
982
- // src/interceptors/ClientRequest/index.ts
983
- var _ClientRequestInterceptor = class extends _chunkDOWWQYXZjs.Interceptor {
984
- constructor() {
985
- super(_ClientRequestInterceptor.symbol);
986
- this.onRequest = async ({
987
- request,
988
- socket
989
- }) => {
990
- const controller = new (0, _chunkDOWWQYXZjs.RequestController)(request, {
991
- passthrough() {
992
- socket.passthrough();
993
- },
994
- async respondWith(response) {
995
- await socket.respondWith(response);
996
- },
997
- errorWith(reason) {
998
- if (reason instanceof Error) {
999
- socket.errorWith(reason);
1000
- }
1001
- }
1002
- });
1003
- await _chunk7Q53NNPVjs.handleRequest.call(void 0, {
1004
- request,
1005
- requestId: Reflect.get(request, kRequestId),
1006
- controller,
1007
- emitter: this.emitter
1008
- });
1009
- };
1010
- this.onResponse = async ({
1011
- requestId,
1012
- request,
1013
- response,
1014
- isMockedResponse
1015
- }) => {
1016
- return _chunk7Q53NNPVjs.emitAsync.call(void 0, this.emitter, "response", {
1017
- requestId,
1018
- request,
1019
- response,
1020
- isMockedResponse
1021
- });
1022
- };
1023
- }
1024
- setup() {
1025
- const {
1026
- ClientRequest: OriginalClientRequest,
1027
- get: originalGet,
1028
- request: originalRequest
1029
- } = _http2.default;
1030
- const { get: originalHttpsGet, request: originalHttpsRequest } = _https2.default;
1031
- const onRequest = this.onRequest.bind(this);
1032
- const onResponse = this.onResponse.bind(this);
1033
- _http2.default.ClientRequest = new Proxy(_http2.default.ClientRequest, {
1034
- construct: (target, args) => {
1035
- const [url, options, callback] = normalizeClientRequestArgs(
1036
- "http:",
1037
- args
1038
- );
1039
- const Agent2 = options.protocol === "https:" ? MockHttpsAgent : MockAgent;
1040
- const mockAgent = new Agent2({
1041
- customAgent: options.agent,
1042
- onRequest,
1043
- onResponse
1044
- });
1045
- options.agent = mockAgent;
1046
- return Reflect.construct(target, [url, options, callback]);
1047
- }
1048
- });
1049
- _http2.default.request = new Proxy(_http2.default.request, {
1050
- apply: (target, thisArg, args) => {
1051
- const [url, options, callback] = normalizeClientRequestArgs(
1052
- "http:",
1053
- args
1054
- );
1055
- const mockAgent = new MockAgent({
1056
- customAgent: options.agent,
1057
- onRequest,
1058
- onResponse
1059
- });
1060
- options.agent = mockAgent;
1061
- return Reflect.apply(target, thisArg, [url, options, callback]);
1062
- }
1063
- });
1064
- _http2.default.get = new Proxy(_http2.default.get, {
1065
- apply: (target, thisArg, args) => {
1066
- const [url, options, callback] = normalizeClientRequestArgs(
1067
- "http:",
1068
- args
1069
- );
1070
- const mockAgent = new MockAgent({
1071
- customAgent: options.agent,
1072
- onRequest,
1073
- onResponse
1074
- });
1075
- options.agent = mockAgent;
1076
- return Reflect.apply(target, thisArg, [url, options, callback]);
1077
- }
1078
- });
1079
- _https2.default.request = new Proxy(_https2.default.request, {
1080
- apply: (target, thisArg, args) => {
1081
- const [url, options, callback] = normalizeClientRequestArgs(
1082
- "https:",
1083
- args
1084
- );
1085
- const mockAgent = new MockHttpsAgent({
1086
- customAgent: options.agent,
1087
- onRequest,
1088
- onResponse
1089
- });
1090
- options.agent = mockAgent;
1091
- return Reflect.apply(target, thisArg, [url, options, callback]);
1092
- }
1093
- });
1094
- _https2.default.get = new Proxy(_https2.default.get, {
1095
- apply: (target, thisArg, args) => {
1096
- const [url, options, callback] = normalizeClientRequestArgs(
1097
- "https:",
1098
- args
1099
- );
1100
- const mockAgent = new MockHttpsAgent({
1101
- customAgent: options.agent,
1102
- onRequest,
1103
- onResponse
1104
- });
1105
- options.agent = mockAgent;
1106
- return Reflect.apply(target, thisArg, [url, options, callback]);
1107
- }
1108
- });
1109
- recordRawFetchHeaders();
1110
- this.subscriptions.push(() => {
1111
- _http2.default.ClientRequest = OriginalClientRequest;
1112
- _http2.default.get = originalGet;
1113
- _http2.default.request = originalRequest;
1114
- _https2.default.get = originalHttpsGet;
1115
- _https2.default.request = originalHttpsRequest;
1116
- restoreHeadersPrototype();
1117
- });
1118
- }
1119
- };
1120
- var ClientRequestInterceptor = _ClientRequestInterceptor;
1121
- ClientRequestInterceptor.symbol = Symbol("client-request-interceptor");
1122
-
1123
-
1124
-
1125
- exports.ClientRequestInterceptor = ClientRequestInterceptor;
1126
- //# sourceMappingURL=chunk-VYO5XDY2.js.map