@api-client/core 0.18.11 → 0.18.13

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 (264) hide show
  1. package/build/src/browser.d.ts +0 -3
  2. package/build/src/browser.d.ts.map +1 -1
  3. package/build/src/browser.js +0 -3
  4. package/build/src/browser.js.map +1 -1
  5. package/build/src/index.d.ts +2 -5
  6. package/build/src/index.d.ts.map +1 -1
  7. package/build/src/index.js +2 -5
  8. package/build/src/index.js.map +1 -1
  9. package/build/src/lib/logging/DefaultLogger.d.ts +14 -0
  10. package/build/src/lib/logging/DefaultLogger.d.ts.map +1 -1
  11. package/build/src/lib/logging/DefaultLogger.js +27 -0
  12. package/build/src/lib/logging/DefaultLogger.js.map +1 -1
  13. package/build/src/lib/logging/index.d.ts +4 -0
  14. package/build/src/lib/logging/index.d.ts.map +1 -0
  15. package/build/src/lib/logging/index.js +10 -0
  16. package/build/src/lib/logging/index.js.map +1 -0
  17. package/build/src/modeling/DomainModel.d.ts.map +1 -1
  18. package/build/src/modeling/DomainModel.js +11 -4
  19. package/build/src/modeling/DomainModel.js.map +1 -1
  20. package/build/src/models/ClientCertificate.d.ts +1 -1
  21. package/build/src/models/ClientCertificate.js.map +1 -1
  22. package/build/src/models/RequestConfig.d.ts +1 -1
  23. package/build/src/models/RequestConfig.js.map +1 -1
  24. package/build/src/models/SerializableError.d.ts +1 -1
  25. package/build/src/models/SerializableError.d.ts.map +1 -1
  26. package/build/src/models/SerializableError.js.map +1 -1
  27. package/build/src/proxy/RequestProxy.d.ts.map +1 -1
  28. package/build/src/proxy/RequestProxy.js +2 -2
  29. package/build/src/proxy/RequestProxy.js.map +1 -1
  30. package/build/src/runtime/http-engine/CoreEngine.d.ts +218 -139
  31. package/build/src/runtime/http-engine/CoreEngine.d.ts.map +1 -1
  32. package/build/src/runtime/http-engine/CoreEngine.js +716 -870
  33. package/build/src/runtime/http-engine/CoreEngine.js.map +1 -1
  34. package/build/src/runtime/http-engine/PayloadSupport.d.ts.map +1 -1
  35. package/build/src/runtime/http-engine/PayloadSupport.js +2 -1
  36. package/build/src/runtime/http-engine/PayloadSupport.js.map +1 -1
  37. package/build/src/runtime/http-engine/auth/AuthManager.d.ts +73 -0
  38. package/build/src/runtime/http-engine/auth/AuthManager.d.ts.map +1 -0
  39. package/build/src/runtime/http-engine/auth/AuthManager.js +186 -0
  40. package/build/src/runtime/http-engine/auth/AuthManager.js.map +1 -0
  41. package/build/src/runtime/http-engine/auth/index.d.ts +2 -0
  42. package/build/src/runtime/http-engine/auth/index.d.ts.map +1 -0
  43. package/build/src/runtime/http-engine/auth/index.js +2 -0
  44. package/build/src/runtime/http-engine/auth/index.js.map +1 -0
  45. package/build/src/runtime/http-engine/certificates/CertificateManager.d.ts +11 -0
  46. package/build/src/runtime/http-engine/certificates/CertificateManager.d.ts.map +1 -0
  47. package/build/src/runtime/http-engine/certificates/CertificateManager.js +76 -0
  48. package/build/src/runtime/http-engine/certificates/CertificateManager.js.map +1 -0
  49. package/build/src/runtime/http-engine/certificates/index.d.ts +2 -0
  50. package/build/src/runtime/http-engine/certificates/index.d.ts.map +1 -0
  51. package/build/src/runtime/http-engine/certificates/index.js +2 -0
  52. package/build/src/runtime/http-engine/certificates/index.js.map +1 -0
  53. package/build/src/runtime/http-engine/compression/CompressionManager.d.ts +25 -0
  54. package/build/src/runtime/http-engine/compression/CompressionManager.d.ts.map +1 -0
  55. package/build/src/runtime/http-engine/compression/CompressionManager.js +89 -0
  56. package/build/src/runtime/http-engine/compression/CompressionManager.js.map +1 -0
  57. package/build/src/runtime/http-engine/compression/index.d.ts +2 -0
  58. package/build/src/runtime/http-engine/compression/index.d.ts.map +1 -0
  59. package/build/src/runtime/http-engine/compression/index.js +2 -0
  60. package/build/src/runtime/http-engine/compression/index.js.map +1 -0
  61. package/build/src/runtime/http-engine/connections/ConnectionManager.d.ts +57 -0
  62. package/build/src/runtime/http-engine/connections/ConnectionManager.d.ts.map +1 -0
  63. package/build/src/runtime/http-engine/connections/ConnectionManager.js +78 -0
  64. package/build/src/runtime/http-engine/connections/ConnectionManager.js.map +1 -0
  65. package/build/src/runtime/http-engine/connections/DigestAuthHandler.d.ts +70 -0
  66. package/build/src/runtime/http-engine/connections/DigestAuthHandler.d.ts.map +1 -0
  67. package/build/src/runtime/http-engine/connections/DigestAuthHandler.js +184 -0
  68. package/build/src/runtime/http-engine/connections/DigestAuthHandler.js.map +1 -0
  69. package/build/src/runtime/http-engine/connections/DirectConnection.d.ts +22 -0
  70. package/build/src/runtime/http-engine/connections/DirectConnection.d.ts.map +1 -0
  71. package/build/src/runtime/http-engine/connections/DirectConnection.js +105 -0
  72. package/build/src/runtime/http-engine/connections/DirectConnection.js.map +1 -0
  73. package/build/src/runtime/http-engine/connections/ProxyAuthHandler.d.ts +60 -0
  74. package/build/src/runtime/http-engine/connections/ProxyAuthHandler.d.ts.map +1 -0
  75. package/build/src/runtime/http-engine/connections/ProxyAuthHandler.js +138 -0
  76. package/build/src/runtime/http-engine/connections/ProxyAuthHandler.js.map +1 -0
  77. package/build/src/runtime/http-engine/connections/ProxyConnection.d.ts +14 -0
  78. package/build/src/runtime/http-engine/connections/ProxyConnection.d.ts.map +1 -0
  79. package/build/src/runtime/http-engine/connections/ProxyConnection.js +47 -0
  80. package/build/src/runtime/http-engine/connections/ProxyConnection.js.map +1 -0
  81. package/build/src/runtime/http-engine/connections/TunnelConnection.d.ts +13 -0
  82. package/build/src/runtime/http-engine/connections/TunnelConnection.d.ts.map +1 -0
  83. package/build/src/runtime/http-engine/connections/TunnelConnection.js +175 -0
  84. package/build/src/runtime/http-engine/connections/TunnelConnection.js.map +1 -0
  85. package/build/src/runtime/http-engine/connections/index.d.ts +7 -0
  86. package/build/src/runtime/http-engine/connections/index.d.ts.map +1 -0
  87. package/build/src/runtime/http-engine/connections/index.js +7 -0
  88. package/build/src/runtime/http-engine/connections/index.js.map +1 -0
  89. package/build/src/runtime/http-engine/constants.d.ts +69 -0
  90. package/build/src/runtime/http-engine/constants.d.ts.map +1 -0
  91. package/build/src/runtime/http-engine/constants.js +90 -0
  92. package/build/src/runtime/http-engine/constants.js.map +1 -0
  93. package/build/src/runtime/http-engine/cookies/CookieProcessor.d.ts +5 -0
  94. package/build/src/runtime/http-engine/cookies/CookieProcessor.d.ts.map +1 -0
  95. package/build/src/runtime/http-engine/cookies/CookieProcessor.js +20 -0
  96. package/build/src/runtime/http-engine/cookies/CookieProcessor.js.map +1 -0
  97. package/build/src/runtime/http-engine/cookies/index.d.ts +2 -0
  98. package/build/src/runtime/http-engine/cookies/index.d.ts.map +1 -0
  99. package/build/src/runtime/http-engine/cookies/index.js +2 -0
  100. package/build/src/runtime/http-engine/cookies/index.js.map +1 -0
  101. package/build/src/runtime/http-engine/errors/HttpEngineErrors.d.ts +156 -0
  102. package/build/src/runtime/http-engine/errors/HttpEngineErrors.d.ts.map +1 -0
  103. package/build/src/runtime/http-engine/errors/HttpEngineErrors.js +227 -0
  104. package/build/src/runtime/http-engine/errors/HttpEngineErrors.js.map +1 -0
  105. package/build/src/runtime/http-engine/errors/index.d.ts +2 -0
  106. package/build/src/runtime/http-engine/errors/index.d.ts.map +1 -0
  107. package/build/src/runtime/http-engine/errors/index.js +2 -0
  108. package/build/src/runtime/http-engine/errors/index.js.map +1 -0
  109. package/build/src/runtime/http-engine/message/MessageBuilder.d.ts +66 -0
  110. package/build/src/runtime/http-engine/message/MessageBuilder.d.ts.map +1 -0
  111. package/build/src/runtime/http-engine/message/MessageBuilder.js +161 -0
  112. package/build/src/runtime/http-engine/message/MessageBuilder.js.map +1 -0
  113. package/build/src/runtime/http-engine/message/MessageProcessor.d.ts +27 -0
  114. package/build/src/runtime/http-engine/message/MessageProcessor.d.ts.map +1 -0
  115. package/build/src/runtime/http-engine/message/MessageProcessor.js +51 -0
  116. package/build/src/runtime/http-engine/message/MessageProcessor.js.map +1 -0
  117. package/build/src/runtime/http-engine/message/index.d.ts +3 -0
  118. package/build/src/runtime/http-engine/message/index.d.ts.map +1 -0
  119. package/build/src/runtime/http-engine/message/index.js +3 -0
  120. package/build/src/runtime/http-engine/message/index.js.map +1 -0
  121. package/build/src/runtime/http-engine/ntlm/NtlmAuth.d.ts +2 -8
  122. package/build/src/runtime/http-engine/ntlm/NtlmAuth.d.ts.map +1 -1
  123. package/build/src/runtime/http-engine/ntlm/NtlmAuth.js +11 -5
  124. package/build/src/runtime/http-engine/ntlm/NtlmAuth.js.map +1 -1
  125. package/build/src/runtime/http-engine/ntlm/NtlmMessage.js +6 -6
  126. package/build/src/runtime/http-engine/ntlm/NtlmMessage.js.map +1 -1
  127. package/build/src/runtime/http-engine/parsers/BodyParser.d.ts +39 -0
  128. package/build/src/runtime/http-engine/parsers/BodyParser.d.ts.map +1 -0
  129. package/build/src/runtime/http-engine/parsers/BodyParser.js +145 -0
  130. package/build/src/runtime/http-engine/parsers/BodyParser.js.map +1 -0
  131. package/build/src/runtime/http-engine/parsers/HeadersParser.d.ts +29 -0
  132. package/build/src/runtime/http-engine/parsers/HeadersParser.d.ts.map +1 -0
  133. package/build/src/runtime/http-engine/parsers/HeadersParser.js +88 -0
  134. package/build/src/runtime/http-engine/parsers/HeadersParser.js.map +1 -0
  135. package/build/src/runtime/http-engine/parsers/HttpResponseParser.d.ts +91 -0
  136. package/build/src/runtime/http-engine/parsers/HttpResponseParser.d.ts.map +1 -0
  137. package/build/src/runtime/http-engine/parsers/HttpResponseParser.js +236 -0
  138. package/build/src/runtime/http-engine/parsers/HttpResponseParser.js.map +1 -0
  139. package/build/src/runtime/http-engine/parsers/StatusParser.d.ts +20 -0
  140. package/build/src/runtime/http-engine/parsers/StatusParser.d.ts.map +1 -0
  141. package/build/src/runtime/http-engine/parsers/StatusParser.js +51 -0
  142. package/build/src/runtime/http-engine/parsers/StatusParser.js.map +1 -0
  143. package/build/src/runtime/http-engine/parsers/index.d.ts +5 -0
  144. package/build/src/runtime/http-engine/parsers/index.d.ts.map +1 -0
  145. package/build/src/runtime/http-engine/parsers/index.js +5 -0
  146. package/build/src/runtime/http-engine/parsers/index.js.map +1 -0
  147. package/build/src/runtime/http-engine/response/ResponseProcessor.d.ts +22 -0
  148. package/build/src/runtime/http-engine/response/ResponseProcessor.d.ts.map +1 -0
  149. package/build/src/runtime/http-engine/response/ResponseProcessor.js +25 -0
  150. package/build/src/runtime/http-engine/response/ResponseProcessor.js.map +1 -0
  151. package/build/src/runtime/http-engine/response/index.d.ts +2 -0
  152. package/build/src/runtime/http-engine/response/index.d.ts.map +1 -0
  153. package/build/src/runtime/http-engine/response/index.js +2 -0
  154. package/build/src/runtime/http-engine/response/index.js.map +1 -0
  155. package/build/src/runtime/http-engine/statistics/StatisticsProcessor.d.ts +7 -0
  156. package/build/src/runtime/http-engine/statistics/StatisticsProcessor.d.ts.map +1 -0
  157. package/build/src/runtime/http-engine/statistics/StatisticsProcessor.js +40 -0
  158. package/build/src/runtime/http-engine/statistics/StatisticsProcessor.js.map +1 -0
  159. package/build/src/runtime/http-engine/statistics/index.d.ts +2 -0
  160. package/build/src/runtime/http-engine/statistics/index.d.ts.map +1 -0
  161. package/build/src/runtime/http-engine/statistics/index.js +2 -0
  162. package/build/src/runtime/http-engine/statistics/index.js.map +1 -0
  163. package/build/src/runtime/http-engine/url/UrlProcessor.d.ts +24 -0
  164. package/build/src/runtime/http-engine/url/UrlProcessor.d.ts.map +1 -0
  165. package/build/src/runtime/http-engine/url/UrlProcessor.js +50 -0
  166. package/build/src/runtime/http-engine/url/UrlProcessor.js.map +1 -0
  167. package/build/src/runtime/http-engine/url/index.d.ts +2 -0
  168. package/build/src/runtime/http-engine/url/index.d.ts.map +1 -0
  169. package/build/src/runtime/http-engine/url/index.js +2 -0
  170. package/build/src/runtime/http-engine/url/index.js.map +1 -0
  171. package/build/src/runtime/http-runner/HttpRequestRunner.d.ts +3 -3
  172. package/build/src/runtime/http-runner/HttpRequestRunner.d.ts.map +1 -1
  173. package/build/src/runtime/http-runner/HttpRequestRunner.js.map +1 -1
  174. package/build/src/runtime/node/InteropInterfaces.d.ts +3 -3
  175. package/build/src/runtime/node/InteropInterfaces.d.ts.map +1 -1
  176. package/build/src/runtime/node/InteropInterfaces.js.map +1 -1
  177. package/build/src/runtime/node/ProjectRequestRunner.d.ts +2 -2
  178. package/build/src/runtime/node/ProjectRequestRunner.d.ts.map +1 -1
  179. package/build/src/runtime/node/ProjectRequestRunner.js.map +1 -1
  180. package/build/src/runtime/node/ProjectRunner.d.ts.map +1 -1
  181. package/build/src/runtime/node/ProjectRunner.js +2 -2
  182. package/build/src/runtime/node/ProjectRunner.js.map +1 -1
  183. package/build/tsconfig.tsbuildinfo +1 -1
  184. package/data/models/example-generator-api.json +24 -24
  185. package/package.json +2 -2
  186. package/src/lib/logging/DefaultLogger.ts +32 -0
  187. package/src/modeling/DomainModel.ts +11 -4
  188. package/src/models/ClientCertificate.ts +1 -1
  189. package/src/models/RequestConfig.ts +1 -1
  190. package/src/models/SerializableError.ts +1 -1
  191. package/src/proxy/RequestProxy.ts +2 -2
  192. package/src/runtime/http-engine/CoreEngine.ts +858 -893
  193. package/src/runtime/http-engine/PayloadSupport.ts +2 -1
  194. package/src/runtime/http-engine/auth/AuthManager.ts +242 -0
  195. package/src/runtime/http-engine/certificates/CertificateManager.ts +74 -0
  196. package/src/runtime/http-engine/compression/CompressionManager.ts +99 -0
  197. package/src/runtime/http-engine/connections/ConnectionManager.ts +123 -0
  198. package/src/runtime/http-engine/connections/DigestAuthHandler.ts +238 -0
  199. package/src/runtime/http-engine/connections/DirectConnection.ts +134 -0
  200. package/src/runtime/http-engine/connections/ProxyAuthHandler.ts +179 -0
  201. package/src/runtime/http-engine/connections/ProxyConnection.ts +55 -0
  202. package/src/runtime/http-engine/connections/TunnelConnection.ts +192 -0
  203. package/src/runtime/http-engine/constants.ts +103 -0
  204. package/src/runtime/http-engine/cookies/CookieProcessor.ts +25 -0
  205. package/src/runtime/http-engine/errors/HttpEngineErrors.ts +319 -0
  206. package/src/runtime/http-engine/message/MessageBuilder.ts +201 -0
  207. package/src/runtime/http-engine/message/MessageProcessor.ts +73 -0
  208. package/src/runtime/http-engine/ntlm/NtlmAuth.ts +16 -13
  209. package/src/runtime/http-engine/ntlm/NtlmMessage.ts +6 -6
  210. package/src/runtime/http-engine/parsers/BodyParser.ts +171 -0
  211. package/src/runtime/http-engine/parsers/HeadersParser.ts +103 -0
  212. package/src/runtime/http-engine/parsers/HttpResponseParser.ts +280 -0
  213. package/src/runtime/http-engine/parsers/StatusParser.ts +69 -0
  214. package/src/runtime/http-engine/response/ResponseProcessor.ts +46 -0
  215. package/src/runtime/http-engine/statistics/StatisticsProcessor.ts +52 -0
  216. package/src/runtime/http-engine/url/UrlProcessor.ts +55 -0
  217. package/src/runtime/http-runner/HttpRequestRunner.ts +3 -3
  218. package/src/runtime/node/InteropInterfaces.ts +3 -3
  219. package/src/runtime/node/ProjectRequestRunner.ts +2 -2
  220. package/src/runtime/node/ProjectRunner.ts +2 -2
  221. package/tests/servers/ProxyServer.ts +32 -19
  222. package/tests/servers/express-routes/ApiEndpoint.ts +24 -0
  223. package/tests/servers/express-routes/BasicAuthRoute.ts +36 -0
  224. package/tests/servers/express-routes/BearerAuthRoute.ts +35 -0
  225. package/tests/servers/express-routes/NTLMRoute.ts +2 -3
  226. package/tests/servers/express-routes/PostApi.ts +15 -2
  227. package/tests/servers/express-routes/RedirectsApi.ts +12 -1
  228. package/tests/servers/express-routes/ResponsesApi.ts +1 -1
  229. package/tests/servers/express-routes/StreamApi.ts +19 -0
  230. package/tests/servers/oauth2mock/ServerMock.js +1 -1
  231. package/tests/unit/modeling/domain_model_entities.spec.ts +306 -1
  232. package/tests/unit/runtime/http-engine/HttpResponseParser.spec.ts +337 -0
  233. package/tests/unit/runtime/http-engine/abort.spec.ts +4 -5
  234. package/tests/unit/runtime/http-engine/auth.spec.ts +7 -58
  235. package/tests/unit/runtime/http-engine/certificates/CertificateManager.spec.ts +482 -0
  236. package/tests/unit/runtime/http-engine/certificates.spec.ts +2 -2
  237. package/tests/unit/runtime/http-engine/compression/CompressionManager.spec.ts +498 -0
  238. package/tests/unit/runtime/http-engine/compression.spec.ts +3 -72
  239. package/tests/unit/runtime/http-engine/connections/ConnectionManager.spec.ts +379 -0
  240. package/tests/unit/runtime/http-engine/connections/DigestAuthHandler.spec.ts +164 -0
  241. package/tests/unit/runtime/http-engine/core_engine.spec.ts +561 -0
  242. package/tests/unit/runtime/http-engine/engine_statuses.spec.ts +2 -2
  243. package/tests/unit/runtime/http-engine/events.spec.ts +2 -2
  244. package/tests/unit/runtime/http-engine/headers.spec.ts +2 -88
  245. package/tests/unit/runtime/http-engine/hosts.spec.ts +2 -2
  246. package/tests/unit/runtime/http-engine/http-get.spec.ts +2 -2
  247. package/tests/unit/runtime/http-engine/http-post.spec.ts +2 -2
  248. package/tests/unit/runtime/http-engine/logger.spec.ts +0 -8
  249. package/tests/unit/runtime/http-engine/message.spec.ts +2 -194
  250. package/tests/unit/runtime/http-engine/params.spec.ts +4 -4
  251. package/tests/unit/runtime/http-engine/proxy.spec.ts +15 -14
  252. package/tests/unit/runtime/http-engine/redirects.spec.ts +2 -2
  253. package/tests/unit/runtime/http-engine/responses.spec.ts +170 -277
  254. package/tests/unit/runtime/http-engine/timeout.spec.ts +3 -3
  255. package/tests/unit/runtime/http-engine/timings.spec.ts +2 -2
  256. package/tests/unit/runtime/proxy/HttpProjectProxy.spec.ts +25 -28
  257. package/tests/unit/runtime/runners/project_runner.spec.ts +2 -2
  258. package/tests/unit/runtime/runners/request_runner.spec.ts +2 -2
  259. package/build/src/runtime/http-engine/HttpEngine.d.ts +0 -311
  260. package/build/src/runtime/http-engine/HttpEngine.d.ts.map +0 -1
  261. package/build/src/runtime/http-engine/HttpEngine.js +0 -802
  262. package/build/src/runtime/http-engine/HttpEngine.js.map +0 -1
  263. package/src/runtime/http-engine/HttpEngine.ts +0 -952
  264. package/tests/unit/runtime/http-engine/connecting.spec.ts +0 -140
@@ -1,952 +0,0 @@
1
- /* eslint-disable @typescript-eslint/no-unsafe-declaration-merging */
2
- /* eslint-disable no-redeclare */
3
- import { URL } from 'url'
4
- import zlib from 'zlib'
5
- import tls from 'tls'
6
- import net from 'net'
7
- import http from 'http'
8
- import { EventEmitter } from 'events'
9
- import { IHttpRequest, HttpRequest } from '../../models/HttpRequest.js'
10
- import { IRequestBaseConfig } from '../../models/RequestConfig.js'
11
- import { IRequestAuthorization } from '../../models/RequestAuthorization.js'
12
- import { HostRule } from '../../models/HostRule.js'
13
- import { HttpCertificate, IPemCertificate } from '../../models/ClientCertificate.js'
14
- import { SentRequest } from '../../models/SentRequest.js'
15
- import { Response } from '../../models/Response.js'
16
- import { ErrorResponse } from '../../models/ErrorResponse.js'
17
- import { RequestsSize } from '../../models/RequestsSize.js'
18
- import { HttpResponse } from '../../models/HttpResponse.js'
19
- import { ResponseRedirect } from '../../models/ResponseRedirect.js'
20
- import { RequestLog, IRequestLog } from '../../models/RequestLog.js'
21
- import { RequestTime } from '../../models/RequestTime.js'
22
- import { SerializableError } from '../../models/SerializableError.js'
23
- import { ResponseAuthorization } from '../../models/ResponseAuthorization.js'
24
- import { DefaultLogger } from '../../lib/logging/DefaultLogger.js'
25
- import { ILogger, Logger } from '../../lib/logging/Logger.js'
26
- import { Headers } from '../../lib/headers/Headers.js'
27
- import * as RequestUtils from './RequestUtils.js'
28
- // import { Cookies } from '../../lib/cookies/Cookies.js';
29
- import { CookieParser } from '../../cookies/CookieParser.js'
30
- import { getCodeMessage } from './HttpErrorCodes.js'
31
-
32
- /**
33
- * A note on cookies and redirects.
34
- * The architecture here assumes running requests is a test environment.
35
- * This means cookies are not processed by this class. This includes processing cookies during a redirect.
36
- * The class does parse response cookies before a redirect and sets new cookies in the redirected request only
37
- * if they match the domain + path. However, this class doesn't know anything about other cookies
38
- * that the application may have for the domain after redirection.
39
- */
40
- export interface HttpEngineOptions extends IRequestBaseConfig {
41
- /**
42
- * The authorization configuration to apply to the request.
43
- */
44
- authorization?: IRequestAuthorization[]
45
- /**
46
- * Logger object.
47
- */
48
- logger?: ILogger
49
- /**
50
- * A certificate to use with the request.
51
- */
52
- certificates?: HttpCertificate[]
53
- }
54
-
55
- export interface RequestStats {
56
- firstReceiveTime?: number
57
- lastReceivedTime?: number
58
- messageStart?: number
59
- sentTime?: number
60
- connectionTime?: number
61
- lookupTime?: number
62
- connectedTime?: number
63
- secureStartTime?: number
64
- secureConnectedTime?: number
65
- startTime?: number
66
- responseTime?: number
67
- receivingTime?: number
68
- }
69
-
70
- export interface ResponseErrorInit {
71
- code?: number | string
72
- message?: string
73
- }
74
-
75
- export interface BeforeRedirectDetail {
76
- location: string
77
- returnValue: boolean
78
- }
79
- export interface HeadersReceivedDetail {
80
- value: string
81
- returnValue: boolean
82
- }
83
-
84
- export interface IRequestAuthState {
85
- method: 'ntlm'
86
- state: number
87
- headers?: string
88
- challengeHeader?: string
89
- }
90
-
91
- export declare interface HttpEngine {
92
- /**
93
- * Dispatched before a redirect occurs.
94
- * The detail object on the listener's only argument has the `location` property
95
- * with the new location for the request.
96
- * When the `returnValue` is set to `false` the request is cancelled.
97
- */
98
- on(event: 'beforeredirect', listener: (detail: BeforeRedirectDetail) => void): this
99
- on(event: 'loadstart' | 'firstbyte' | 'loadend', listener: () => void): this
100
- on(event: 'headersreceived', listener: (detail: HeadersReceivedDetail) => void): this
101
- /**
102
- * Dispatched before a redirect occurs.
103
- * The detail object on the listener's only argument has the `location` property
104
- * with the new location for the request.
105
- * When the `returnValue` is set to `false` the request is cancelled.
106
- */
107
- once(event: 'beforeredirect', listener: (detail: BeforeRedirectDetail) => void): this
108
- once(event: 'loadstart' | 'firstbyte' | 'loadend', listener: () => void): this
109
- once(event: 'headersreceived', listener: (detail: HeadersReceivedDetail) => void): this
110
- }
111
-
112
- export const mainPromiseSymbol = Symbol('mainPromise')
113
-
114
- /**
115
- * The base class to make HTTP requests in API Client.
116
- * This can be extended to support particular implementations.
117
- */
118
- export abstract class HttpEngine extends EventEmitter {
119
- request: HttpRequest
120
- opts: HttpEngineOptions
121
- logger: Logger
122
-
123
- /**
124
- * The current sent request
125
- */
126
- sentRequest: SentRequest
127
-
128
- redirects: ResponseRedirect[] = []
129
- /**
130
- * When true the request has been aborted.
131
- */
132
- aborted = false
133
- /**
134
- * Parsed value of the request URL.
135
- */
136
- uri: URL
137
-
138
- socket?: net.Socket
139
- /**
140
- * Host header can be different than registered URL because of
141
- * `hosts` rules.
142
- * If a rule changes host value of the URL the original URL host value
143
- * is used when generating the request and not overwritten one.
144
- * This way virtual hosts can be tested using hosts.
145
- */
146
- hostHeader: string | undefined
147
-
148
- protected hostTestReg = /^\s*host\s*:/im
149
- /**
150
- * Set when the request is redirected.
151
- */
152
- redirecting = false
153
-
154
- /**
155
- * The response headers.
156
- * The object may be empty when the response is not set.
157
- */
158
- currentHeaders = new Headers()
159
-
160
- /**
161
- * The response object build during the execution.
162
- */
163
- currentResponse?: Response
164
-
165
- /**
166
- * @return True if following redirects is allowed.
167
- */
168
- get followRedirects(): boolean {
169
- const { opts } = this
170
- if (typeof opts.followRedirects === 'boolean') {
171
- return opts.followRedirects
172
- }
173
- return true
174
- }
175
-
176
- /**
177
- * The request timeout.
178
- */
179
- get timeout(): number {
180
- const { opts } = this
181
- if (typeof opts.timeout === 'number') {
182
- return opts.timeout
183
- }
184
- return 0
185
- }
186
-
187
- /**
188
- * Keeps the raw body in a temporary buffer while processing the response.
189
- */
190
- _rawBody?: Buffer
191
-
192
- stats: RequestStats = {}
193
-
194
- auth?: IRequestAuthState
195
-
196
- protected mainResolver?: (log: IRequestLog) => void
197
- protected mainRejecter?: (err: SerializableError) => void;
198
- [mainPromiseSymbol]?: Promise<IRequestLog>
199
-
200
- protected _signal?: AbortSignal
201
-
202
- /**
203
- * The abort signal to set on this request.
204
- * Aborts the request when the signal fires.
205
- * @type {(AbortSignal | undefined)}
206
- */
207
- get signal(): AbortSignal | undefined {
208
- return this._signal
209
- }
210
-
211
- set signal(value: AbortSignal | undefined) {
212
- const old = this._signal
213
- if (old === value) {
214
- return
215
- }
216
- this._signal = value
217
- if (old) {
218
- old.removeEventListener('abort', this._abortHandler)
219
- }
220
- if (value) {
221
- value.addEventListener('abort', this._abortHandler)
222
- }
223
- }
224
-
225
- constructor(request: IHttpRequest, opts: HttpEngineOptions = {}) {
226
- super()
227
- this.request = new HttpRequest({ ...request })
228
- this.opts = opts
229
- this.logger = this.setupLogger(opts)
230
- this.sentRequest = new SentRequest({ ...request, startTime: Date.now() })
231
- this.uri = this.readUrl(request.url)
232
- this.hostHeader = RequestUtils.getHostHeader(request.url)
233
-
234
- this._abortHandler = this._abortHandler.bind(this)
235
- if (opts.signal) {
236
- this.signal = opts.signal
237
- }
238
- }
239
-
240
- /**
241
- * Creates a logger object to log debug output.
242
- */
243
- setupLogger(opts: HttpEngineOptions = {}): Logger {
244
- if (opts.logger) {
245
- return opts.logger
246
- }
247
- return new DefaultLogger()
248
- }
249
-
250
- /**
251
- * Updates the `uri` property from current request URL
252
- * @param value The request URL
253
- */
254
- readUrl(value: string): URL {
255
- const { hosts = [] } = this.opts
256
- const instances = hosts.map((i) => new HostRule(i))
257
- value = HostRule.applyHosts(value, instances)
258
- try {
259
- return new URL(value)
260
- } catch {
261
- throw new Error(`Unable to parse the URL: ${value}`)
262
- }
263
- }
264
-
265
- /**
266
- * Aborts current request.
267
- * It emits `error` event
268
- */
269
- abort(): void {
270
- this.aborted = true
271
- if (!this.socket) {
272
- return
273
- }
274
- this.socket.removeAllListeners()
275
- if (this.socket.destroyed) {
276
- this.socket = undefined
277
- return
278
- }
279
- this.socket.pause()
280
- this.socket.destroy()
281
- this.socket = undefined
282
- }
283
-
284
- /**
285
- * Handler for the `abort` event on the `AbortSignal`.
286
- */
287
- protected _abortHandler(): void {
288
- const e = new SerializableError('Request aborted', 3)
289
- this._errorRequest(e)
290
- this.abort()
291
- }
292
-
293
- /**
294
- * Sends the request.
295
- */
296
- abstract send(): Promise<IRequestLog>
297
-
298
- /**
299
- * Decompresses received body if `content-encoding` header is set.
300
- *
301
- * @param body A body buffer to decompress.
302
- * @return Promise resolved to parsed body
303
- */
304
- async decompress(body?: Buffer): Promise<Buffer | undefined> {
305
- const { aborted, currentHeaders } = this
306
- if (aborted || !currentHeaders || !body) {
307
- return
308
- }
309
- const ce = currentHeaders.get('content-encoding')
310
- if (!ce) {
311
- return body
312
- }
313
- if (ce.indexOf('deflate') !== -1) {
314
- return this.inflate(body)
315
- }
316
- if (ce.indexOf('gzip') !== -1) {
317
- return this.gunzip(body)
318
- }
319
- if (ce.indexOf('br') !== -1) {
320
- return this.brotli(body)
321
- }
322
- return body
323
- }
324
-
325
- /**
326
- * Decompress body with Inflate.
327
- * @param body Received response payload
328
- * @return Promise resolved to decompressed buffer.
329
- */
330
- inflate(body: Buffer): Promise<Buffer> {
331
- body = Buffer.from(body)
332
- return new Promise((resolve, reject) => {
333
- zlib.inflate(body, (err: Error | null, buffer: Buffer) => {
334
- if (err) {
335
- reject(new Error(err.message || String(err)))
336
- } else {
337
- resolve(buffer)
338
- }
339
- })
340
- })
341
- }
342
-
343
- /**
344
- * Decompress body with ZLib.
345
- * @param body Received response payload
346
- * @return Promise resolved to decompressed buffer.
347
- */
348
- gunzip(body: Buffer): Promise<Buffer> {
349
- body = Buffer.from(body)
350
- return new Promise((resolve, reject) => {
351
- zlib.gunzip(body, (err: Error | null, buffer: Buffer) => {
352
- if (err) {
353
- reject(new Error(err.message || String(err)))
354
- } else {
355
- resolve(buffer)
356
- }
357
- })
358
- })
359
- }
360
-
361
- /**
362
- * Decompress Brotli.
363
- * @param body Received response payload
364
- * @return Promise resolved to decompressed buffer.
365
- */
366
- brotli(body: Buffer): Promise<Buffer> {
367
- body = Buffer.from(body)
368
- return new Promise((resolve, reject) => {
369
- zlib.brotliDecompress(body, (err: Error | null, buffer: Buffer) => {
370
- if (err) {
371
- reject(err)
372
- } else {
373
- resolve(buffer)
374
- }
375
- })
376
- })
377
- }
378
-
379
- /**
380
- * Prepares headers list to be send to the remote machine.
381
- * If `defaultHeaders` option is set then it adds `user-agent` and `accept`
382
- * headers.
383
- * @param headers Parsed headers
384
- * @param withPayload Whether the request should send a body message
385
- */
386
- prepareHeaders(headers: Headers, withPayload = false): void {
387
- if (this.opts.defaultHeaders) {
388
- if (!headers.has('user-agent')) {
389
- if (this.opts.defaultUserAgent) {
390
- headers.set('user-agent', this.opts.defaultUserAgent)
391
- } else {
392
- headers.set('user-agent', 'api client')
393
- }
394
- }
395
- if (!headers.has('accept')) {
396
- if (this.opts.defaultAccept) {
397
- headers.set('accept', this.opts.defaultAccept)
398
- } else {
399
- headers.set('accept', '*/*')
400
- }
401
- }
402
- }
403
- if (withPayload) {
404
- if (!headers.has('content-type') && this.request.payloadOptions) {
405
- if (this.request.payloadOptions.mime) {
406
- headers.set('content-type', this.request.payloadOptions.mime)
407
- }
408
- }
409
- }
410
- }
411
-
412
- /**
413
- * Cleans the state after finished.
414
- */
415
- _cleanUp(): void {
416
- this.redirects = []
417
- this.currentHeaders = new Headers()
418
- this.currentResponse = undefined
419
- this._rawBody = undefined
420
- this.redirecting = false
421
- this.stats = {}
422
- this.mainRejecter = undefined
423
- this.mainResolver = undefined
424
- this._clearSocketEventListeners()
425
- }
426
-
427
- /**
428
- * Cleans up the state for redirect.
429
- */
430
- _cleanUpRedirect(): void {
431
- this.currentHeaders = new Headers()
432
- this.currentResponse = undefined
433
- this._rawBody = undefined
434
- this.stats = {}
435
- this._clearSocketEventListeners()
436
- }
437
-
438
- /**
439
- * Reports response when redirected.
440
- * @param status Received status code
441
- * @return True if the request has been redirected.
442
- */
443
- _reportRedirect(status: number): boolean {
444
- const { request, currentHeaders } = this
445
- if (!currentHeaders) {
446
- return false
447
- }
448
- const rerUrl = currentHeaders.get('location')
449
- // https://github.com/jarrodek/socket-fetch/issues/13
450
- const redirectOptions = RequestUtils.redirectOptions(status, request.method, rerUrl)
451
- if (!redirectOptions.redirect) {
452
- return false
453
- }
454
- this.redirecting = true
455
- setTimeout(() => this._redirectRequest(redirectOptions))
456
- return true
457
- }
458
-
459
- /**
460
- * Creates a response and adds it to the redirects list and redirects
461
- * the request to the new location.
462
- */
463
- async _redirectRequest(options: RequestUtils.RedirectOptions): Promise<void> {
464
- if (this.followRedirects === false) {
465
- this._publishResponse()
466
- return
467
- }
468
- const location = options.location && RequestUtils.getRedirectLocation(options.location, this.request.url)
469
- if (!location) {
470
- this._errorRequest({ code: 302 })
471
- return
472
- }
473
-
474
- // check if this is infinite loop
475
- if (RequestUtils.isRedirectLoop(location, this.redirects)) {
476
- this._errorRequest({ code: 310 })
477
- return
478
- }
479
-
480
- const detail: BeforeRedirectDetail = {
481
- location,
482
- returnValue: true,
483
- }
484
- this.emit('beforeredirect', detail)
485
- if (!detail.returnValue) {
486
- this._publishResponse()
487
- return
488
- }
489
- try {
490
- const responseCookies = this.currentHeaders.get('set-cookie')
491
- const response = await this._createRedirectResponse(location)
492
- this.redirects.push(response)
493
- this._cleanUpRedirect()
494
- if (responseCookies) {
495
- this._processRedirectCookies(responseCookies, location)
496
- }
497
- this.redirecting = false
498
-
499
- this.request.url = location
500
- this.sentRequest.url = location
501
- if (options.forceGet) {
502
- this.request.method = 'GET'
503
- }
504
- this.uri = this.readUrl(location)
505
- this.hostHeader = RequestUtils.getHostHeader(location)
506
- // No idea why but without setTimeout the program loses it's
507
- // scope after calling the function.
508
- setTimeout(() => this.send())
509
- } catch (e) {
510
- const error = e as Error
511
- this._errorRequest({
512
- message: (error && error.message) || 'Unknown error occurred',
513
- })
514
- }
515
- }
516
-
517
- /**
518
- * @param location The redirect location.
519
- * @return Redirect response object
520
- */
521
- async _createRedirectResponse(location: string): Promise<ResponseRedirect> {
522
- const { currentResponse = new Response() } = this
523
-
524
- const response = HttpResponse.fromValues(
525
- currentResponse.status,
526
- currentResponse.statusText,
527
- currentResponse.headers
528
- )
529
- if (currentResponse.payload) {
530
- response.payload = currentResponse.payload
531
- }
532
-
533
- const body = await this.decompress(this._rawBody)
534
- if (body) {
535
- await response.writePayload(body)
536
- currentResponse.payload = response.payload
537
- }
538
-
539
- const redirect = ResponseRedirect.fromValues(
540
- location,
541
- response.toJSON(),
542
- this.stats.startTime,
543
- this.stats.responseTime
544
- )
545
- redirect.timings = this._computeStats(this.stats)
546
-
547
- return redirect
548
- }
549
-
550
- /**
551
- * Creates a response object
552
- *
553
- * @return A response object.
554
- */
555
- async _createResponse(): Promise<Response | undefined> {
556
- if (this.aborted) {
557
- return
558
- }
559
- const { currentResponse } = this
560
- if (!currentResponse) {
561
- throw new Error(`Tried to create a response but no response data is set.`)
562
- }
563
- const { status } = currentResponse
564
- if (status === undefined) {
565
- throw new Error(`The response status is empty.
566
- It means that the successful connection wasn't made.
567
- Check your request parameters.`)
568
- }
569
- const body = await this.decompress(this._rawBody)
570
- const response = Response.fromValues(status, currentResponse.statusText, currentResponse.headers)
571
- response.timings = this._computeStats(this.stats)
572
- response.loadingTime = response.timings.total()
573
- if (body) {
574
- await response.writePayload(body)
575
- currentResponse.payload = response.payload
576
- }
577
- if (status === 401) {
578
- response.auth = this._getAuth()
579
- }
580
- return response
581
- }
582
-
583
- /**
584
- * Finishes the response with error message.
585
- */
586
- _errorRequest(opts: ResponseErrorInit): void {
587
- const { currentResponse } = this
588
- this.aborted = true
589
- let message
590
- if (opts.code && !opts.message) {
591
- message = getCodeMessage(opts.code)
592
- } else if (opts.message) {
593
- message = opts.message
594
- }
595
- message = message || 'Unknown error occurred'
596
- const error = new SerializableError(message, opts.code)
597
- const log = RequestLog.fromRequest(this.sentRequest.toJSON())
598
- const response = ErrorResponse.fromError(error)
599
- log.response = response
600
- if (currentResponse && currentResponse.status) {
601
- response.status = currentResponse.status
602
- response.statusText = currentResponse.statusText
603
- response.headers = currentResponse.headers
604
- response.payload = currentResponse.payload
605
- }
606
- this.finalizeRequest(log)
607
- this._cleanUp()
608
- }
609
-
610
- /**
611
- * Generates authorization info object from response.
612
- */
613
- _getAuth(): ResponseAuthorization {
614
- let auth = this.currentHeaders.get('www-authenticate')
615
- const result = new ResponseAuthorization()
616
- if (auth) {
617
- auth = auth.toLowerCase()
618
- if (auth.indexOf('ntlm') !== -1) {
619
- result.method = 'ntlm'
620
- } else if (auth.indexOf('basic') !== -1) {
621
- result.method = 'basic'
622
- } else if (auth.indexOf('digest') !== -1) {
623
- result.method = 'digest'
624
- }
625
- }
626
- return result
627
- }
628
-
629
- /**
630
- * Generate response object and publish it to the listeners.
631
- */
632
- async _publishResponse(): Promise<void> {
633
- if (this.aborted) {
634
- return
635
- }
636
- try {
637
- const response = await this._createResponse()
638
- if (!response) {
639
- return
640
- }
641
- const result = RequestLog.fromRequestResponse(this.sentRequest.toJSON(), response.toJSON())
642
- if (this.redirects.length) {
643
- result.redirects = this.redirects
644
- }
645
- result.size = new RequestsSize()
646
- if (this.sentRequest.httpMessage) {
647
- result.size.request = Buffer.from(this.sentRequest.httpMessage).length
648
- }
649
- if (response.payload) {
650
- if (typeof response.payload === 'string') {
651
- result.size.response = response.payload.length
652
- } else {
653
- result.size.response = response.payload.data.length
654
- }
655
- }
656
- this.finalizeRequest(result)
657
- } catch (e) {
658
- const error = e as Error
659
- // eslint-disable-next-line no-console
660
- console.error(error)
661
- this._errorRequest({
662
- message: (error && error.message) || 'Unknown error occurred',
663
- })
664
- }
665
- this.abort()
666
- this._cleanUp()
667
- }
668
-
669
- /**
670
- * Creates HAR 1.2 timings object from stats.
671
- * @param stats Timings object
672
- */
673
- _computeStats(stats: RequestStats): RequestTime {
674
- const {
675
- sentTime,
676
- messageStart,
677
- connectionTime = 0,
678
- lookupTime = 0,
679
- connectedTime,
680
- secureStartTime,
681
- secureConnectedTime,
682
- lastReceivedTime,
683
- firstReceiveTime,
684
- receivingTime,
685
- } = stats
686
- // in case the `send` event was not handled we use the `messageStart` as this is set when the request is created.
687
- const adjustedSentTime = sentTime || messageStart
688
- // when there was no body we check when the end time.
689
- const adjustedLastReceivedTime = lastReceivedTime || receivingTime
690
- const adjustedLookupTime = lookupTime || messageStart
691
- let send = adjustedSentTime && messageStart ? adjustedSentTime - messageStart : -1
692
- if (send < 0) {
693
- send = 0
694
- }
695
- const dns = lookupTime ? lookupTime - connectionTime : -1
696
- const connect = connectedTime && adjustedLookupTime ? connectedTime - adjustedLookupTime : -1
697
- let receive = adjustedLastReceivedTime && firstReceiveTime ? adjustedLastReceivedTime - firstReceiveTime : -1
698
- if (receive < 0) {
699
- receive = 0
700
- }
701
- let wait = firstReceiveTime && adjustedSentTime ? firstReceiveTime - adjustedSentTime : -1
702
- if (wait < 0) {
703
- wait = 0
704
- }
705
- let ssl = -1
706
- if (typeof secureStartTime === 'number' && typeof secureConnectedTime === 'number') {
707
- ssl = secureConnectedTime - secureStartTime
708
- }
709
- const result = new RequestTime()
710
- result.blocked = 0
711
- result.connect = connect
712
- result.receive = receive
713
- result.send = send
714
- result.wait = wait
715
- result.dns = dns
716
- result.ssl = ssl
717
- return result
718
- }
719
-
720
- /**
721
- * Handles cookie exchange when redirecting the request.
722
- * @param responseCookies Cookies received in the response
723
- * @param location Redirect destination
724
- */
725
- _processRedirectCookies(responseCookies: string, location: string): void {
726
- const received = CookieParser.parse(this.request.url, responseCookies)
727
- const forwardCookies = CookieParser.filterCookies(received, location)
728
- const headers = new Headers(this.request.toHeadersString())
729
- headers.delete('cookie')
730
- if (forwardCookies.length) {
731
- const parts: string[] = []
732
- forwardCookies.forEach((cookie) => {
733
- parts.push(cookie.toString())
734
- })
735
- headers.set('cookie', parts.join('; '))
736
- }
737
- this.request.headers = headers.toString()
738
-
739
- // let newParser = new Cookies(responseCookies, location);
740
- // newParser.filter();
741
- // const expired = newParser.clearExpired();
742
- // const hasCookie = headers.has('cookie');
743
- // if (hasCookie) {
744
- // const oldCookies = headers.get('cookie');
745
- // const oldParser = new Cookies(oldCookies, location);
746
- // oldParser.filter();
747
- // oldParser.clearExpired();
748
- // oldParser.merge(newParser);
749
- // newParser = oldParser;
750
- // // remove expired from the new response.
751
- // newParser.cookies = newParser.cookies.filter((c) => {
752
- // for (let i = 0, len = expired.length; i < len; i++) {
753
- // if (expired[i].name === c.name) {
754
- // return false;
755
- // }
756
- // }
757
- // return true;
758
- // });
759
- // }
760
- // const str = newParser.toString(true);
761
- // if (str) {
762
- // headers.set('cookie', str);
763
- // } else if (hasCookie) {
764
- // headers.delete('cookie');
765
- // }
766
- // this.request.headers = headers.toString();
767
- }
768
-
769
- /**
770
- * Checks certificate identity using TLS api.
771
- *
772
- * @param host Request host name
773
- * @param cert TLS certificate info object
774
- */
775
- _checkServerIdentity(host: string, cert: tls.PeerCertificate): Error | undefined {
776
- const err = tls.checkServerIdentity(host, cert)
777
- if (err) {
778
- return err
779
- }
780
- }
781
-
782
- /**
783
- * Clears event listeners of the socket object,
784
- */
785
- _clearSocketEventListeners(): void {
786
- if (!this.socket) {
787
- return
788
- }
789
- this.socket.removeAllListeners('error')
790
- this.socket.removeAllListeners('timeout')
791
- this.socket.removeAllListeners('end')
792
- }
793
-
794
- /**
795
- * Adds client certificate to the request configuration options.
796
- *
797
- * @param certificate List of certificate configurations.
798
- * @param options Request options. Cert agent options are added to this object.
799
- */
800
- _addClientCertificate(certificate: HttpCertificate, options: tls.ConnectionOptions): void {
801
- if (!certificate) {
802
- return
803
- }
804
- const cert = { ...certificate }
805
- if (cert.type === 'p12') {
806
- if (!options.pfx) {
807
- options.pfx = []
808
- }
809
- const struct: tls.PxfObject = {
810
- buf: Buffer.from(cert.cert.data as Buffer),
811
- }
812
- if (cert.cert.passphrase) {
813
- struct.passphrase = cert.cert.passphrase
814
- }
815
- if (!Array.isArray(options.pfx)) {
816
- if (options.pfx) {
817
- options.pfx = [options.pfx]
818
- } else {
819
- options.pfx = []
820
- }
821
- }
822
- options.pfx.push(struct)
823
- } else if (cert.type === 'pem') {
824
- const typed = cert as IPemCertificate
825
- if (!options.cert) {
826
- options.cert = []
827
- }
828
- if (!Array.isArray(options.cert)) {
829
- if (options.cert) {
830
- options.cert = [options.cert]
831
- } else {
832
- options.cert = []
833
- }
834
- }
835
- const added = Buffer.from(typed.cert.data as Buffer | Uint8Array)
836
- options.cert.push(added)
837
- if (typed.certKey) {
838
- if (!Array.isArray(options.key)) {
839
- if (options.key) {
840
- options.key = [options.key]
841
- } else {
842
- options.key = []
843
- }
844
- }
845
- const struct: tls.KeyObject = {
846
- pem: Buffer.from(typed.certKey.data as Buffer | Uint8Array),
847
- }
848
- if (typed.certKey.passphrase) {
849
- struct.passphrase = typed.certKey.passphrase
850
- }
851
- options.key.push(struct)
852
- }
853
- }
854
- }
855
-
856
- /**
857
- * @return Proxy authorization header value, when defined.
858
- */
859
- _proxyAuthHeader(): string | undefined {
860
- const { proxyUsername, proxyPassword = '', proxyAuthorization } = this.opts
861
- if (!proxyUsername || !proxyPassword) {
862
- if (!proxyAuthorization) {
863
- return undefined
864
- }
865
- return proxyAuthorization
866
- }
867
-
868
- if (!proxyAuthorization || proxyAuthorization === 'Basic') {
869
- // Basic authentication
870
- const token = Buffer.from(`${proxyUsername}:${proxyPassword}`).toString('base64')
871
- return `Basic ${token}`
872
- }
873
-
874
- // if (proxyAuthorization === 'Digest') {
875
- // // Digest authentication - this needs to be implemented.
876
- // // You'll need to keep track of the nonce, realm, etc. across requests.
877
- // // This is more complex and requires parsing the WWW-Authenticate header.
878
- // // Example (incomplete - needs proper nonce handling, etc.):
879
- // const ha1 = crypto.createHash('md5').update(`${proxyUsername}:${realm}:${proxyPassword}`).digest('hex');
880
- // const ha2 = crypto.createHash('md5').update(`${this.request.method}:${this.request.url}`).digest('hex');
881
- // const response = crypto.createHash('md5').update(`${ha1}:${nonce}:${ha2}`).digest('hex');
882
- // eslint-disable-next-line max-len
883
- // return `Digest username="${proxyUsername}", realm="${realm}", nonce="${nonce}", uri="${this.request.url}", response="${response}"`;
884
- // }
885
-
886
- throw new SerializableError(`Unsupported proxy authorization type: ${proxyAuthorization}`)
887
-
888
- // if (!proxyUsername) {
889
- // return undefined;
890
- // }
891
- // const auth = `${proxyUsername}:${proxyPassword}`;
892
- // const hash = Buffer.from(auth).toString('base64');
893
- // return `Basic ${hash}`;
894
- }
895
-
896
- /**
897
- * Reads the raw headers from the node response and transforms them into the internal headers.
898
- */
899
- computeResponseHeaders(res: http.IncomingMessage): Headers {
900
- const headers: Record<string, string> = {}
901
- for (let i = 0, len = res.rawHeaders.length; i < len; i += 2) {
902
- const name = res.rawHeaders[i]
903
- const value = res.rawHeaders[i + 1]
904
- if (headers[name]) {
905
- headers[name] += `; ${value}`
906
- } else {
907
- headers[name] = value
908
- }
909
- }
910
- return new Headers(headers)
911
- }
912
-
913
- /**
914
- * Called with the `send()` function to initialize the main promise returned by the send function.
915
- * The send function returns a promise that is resolved when the request finish.
916
- */
917
- protected wrapExecution(): Promise<IRequestLog> {
918
- let promise: Promise<IRequestLog>
919
- if (this[mainPromiseSymbol]) {
920
- promise = this[mainPromiseSymbol] as Promise<IRequestLog>
921
- } else {
922
- promise = new Promise((resolve, reject) => {
923
- this.mainResolver = resolve
924
- this.mainRejecter = reject
925
- })
926
- this[mainPromiseSymbol] = promise
927
- }
928
- return promise
929
- }
930
-
931
- /**
932
- * Called by the request finalizer or error finalized to report the response.
933
- *
934
- * @param log Either the request execution log or an error.
935
- */
936
- protected finalizeRequest(log: RequestLog | SerializableError): void {
937
- const { mainRejecter, mainResolver } = this
938
- if (!mainRejecter || !mainResolver) {
939
- // console.error(`Trying to finalize the request but the main resolver is not set.`);
940
- return
941
- }
942
-
943
- if (log instanceof SerializableError) {
944
- mainRejecter(log)
945
- } else {
946
- mainResolver(log.toJSON())
947
- }
948
- this.mainRejecter = undefined
949
- this.mainResolver = undefined
950
- this[mainPromiseSymbol] = undefined
951
- }
952
- }