pi-cursor-sdk 0.1.49 → 0.1.51

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 (278) hide show
  1. package/CHANGELOG.md +36 -1
  2. package/README.md +2 -2
  3. package/docs/cursor-live-smoke-checklist.md +4 -4
  4. package/docs/cursor-model-ux-spec.md +5 -5
  5. package/docs/cursor-native-tool-replay.md +2 -2
  6. package/docs/cursor-native-tool-visual-audit.md +1 -1
  7. package/docs/cursor-testing-lessons.md +1 -1
  8. package/package.json +6 -15
  9. package/src/cursor-fallback-models.generated.ts +536 -302
  10. package/src/cursor-provider-errors.ts +29 -0
  11. package/src/cursor-provider-overflow.ts +96 -0
  12. package/src/cursor-tool-manifest.ts +1 -1
  13. package/src/index.ts +4 -1
  14. package/node_modules/@connectrpc/connect-node/README.md +0 -141
  15. package/node_modules/@connectrpc/connect-node/dist/cjs/compression.d.ts +0 -15
  16. package/node_modules/@connectrpc/connect-node/dist/cjs/compression.js +0 -89
  17. package/node_modules/@connectrpc/connect-node/dist/cjs/connect-node-adapter.d.ts +0 -42
  18. package/node_modules/@connectrpc/connect-node/dist/cjs/connect-node-adapter.js +0 -61
  19. package/node_modules/@connectrpc/connect-node/dist/cjs/connect-transport.d.ts +0 -100
  20. package/node_modules/@connectrpc/connect-node/dist/cjs/connect-transport.js +0 -25
  21. package/node_modules/@connectrpc/connect-node/dist/cjs/grpc-transport.d.ts +0 -96
  22. package/node_modules/@connectrpc/connect-node/dist/cjs/grpc-transport.js +0 -25
  23. package/node_modules/@connectrpc/connect-node/dist/cjs/grpc-web-transport.d.ts +0 -96
  24. package/node_modules/@connectrpc/connect-node/dist/cjs/grpc-web-transport.js +0 -25
  25. package/node_modules/@connectrpc/connect-node/dist/cjs/http2-session-manager.d.ts +0 -146
  26. package/node_modules/@connectrpc/connect-node/dist/cjs/http2-session-manager.js +0 -536
  27. package/node_modules/@connectrpc/connect-node/dist/cjs/index.d.ts +0 -15
  28. package/node_modules/@connectrpc/connect-node/dist/cjs/index.js +0 -36
  29. package/node_modules/@connectrpc/connect-node/dist/cjs/node-error.d.ts +0 -45
  30. package/node_modules/@connectrpc/connect-node/dist/cjs/node-error.js +0 -154
  31. package/node_modules/@connectrpc/connect-node/dist/cjs/node-headers-polyfill.d.ts +0 -1
  32. package/node_modules/@connectrpc/connect-node/dist/cjs/node-headers-polyfill.js +0 -29
  33. package/node_modules/@connectrpc/connect-node/dist/cjs/node-transport-options.d.ts +0 -89
  34. package/node_modules/@connectrpc/connect-node/dist/cjs/node-transport-options.js +0 -58
  35. package/node_modules/@connectrpc/connect-node/dist/cjs/node-universal-client.d.ts +0 -54
  36. package/node_modules/@connectrpc/connect-node/dist/cjs/node-universal-client.js +0 -326
  37. package/node_modules/@connectrpc/connect-node/dist/cjs/node-universal-handler.d.ts +0 -41
  38. package/node_modules/@connectrpc/connect-node/dist/cjs/node-universal-handler.js +0 -234
  39. package/node_modules/@connectrpc/connect-node/dist/cjs/node-universal-header.d.ts +0 -19
  40. package/node_modules/@connectrpc/connect-node/dist/cjs/node-universal-header.js +0 -97
  41. package/node_modules/@connectrpc/connect-node/dist/cjs/package.json +0 -1
  42. package/node_modules/@connectrpc/connect-node/dist/esm/compression.d.ts +0 -15
  43. package/node_modules/@connectrpc/connect-node/dist/esm/compression.js +0 -86
  44. package/node_modules/@connectrpc/connect-node/dist/esm/connect-node-adapter.d.ts +0 -42
  45. package/node_modules/@connectrpc/connect-node/dist/esm/connect-node-adapter.js +0 -58
  46. package/node_modules/@connectrpc/connect-node/dist/esm/connect-transport.d.ts +0 -100
  47. package/node_modules/@connectrpc/connect-node/dist/esm/connect-transport.js +0 -22
  48. package/node_modules/@connectrpc/connect-node/dist/esm/grpc-transport.d.ts +0 -96
  49. package/node_modules/@connectrpc/connect-node/dist/esm/grpc-transport.js +0 -22
  50. package/node_modules/@connectrpc/connect-node/dist/esm/grpc-web-transport.d.ts +0 -96
  51. package/node_modules/@connectrpc/connect-node/dist/esm/grpc-web-transport.js +0 -22
  52. package/node_modules/@connectrpc/connect-node/dist/esm/http2-session-manager.d.ts +0 -146
  53. package/node_modules/@connectrpc/connect-node/dist/esm/http2-session-manager.js +0 -532
  54. package/node_modules/@connectrpc/connect-node/dist/esm/index.d.ts +0 -15
  55. package/node_modules/@connectrpc/connect-node/dist/esm/index.js +0 -23
  56. package/node_modules/@connectrpc/connect-node/dist/esm/node-error.d.ts +0 -45
  57. package/node_modules/@connectrpc/connect-node/dist/esm/node-error.js +0 -147
  58. package/node_modules/@connectrpc/connect-node/dist/esm/node-headers-polyfill.d.ts +0 -1
  59. package/node_modules/@connectrpc/connect-node/dist/esm/node-headers-polyfill.js +0 -27
  60. package/node_modules/@connectrpc/connect-node/dist/esm/node-transport-options.d.ts +0 -89
  61. package/node_modules/@connectrpc/connect-node/dist/esm/node-transport-options.js +0 -58
  62. package/node_modules/@connectrpc/connect-node/dist/esm/node-universal-client.d.ts +0 -54
  63. package/node_modules/@connectrpc/connect-node/dist/esm/node-universal-client.js +0 -324
  64. package/node_modules/@connectrpc/connect-node/dist/esm/node-universal-handler.d.ts +0 -41
  65. package/node_modules/@connectrpc/connect-node/dist/esm/node-universal-handler.js +0 -230
  66. package/node_modules/@connectrpc/connect-node/dist/esm/node-universal-header.d.ts +0 -19
  67. package/node_modules/@connectrpc/connect-node/dist/esm/node-universal-header.js +0 -93
  68. package/node_modules/@connectrpc/connect-node/package.json +0 -46
  69. package/node_modules/undici/LICENSE +0 -21
  70. package/node_modules/undici/README.md +0 -741
  71. package/node_modules/undici/docs/docs/api/Agent.md +0 -84
  72. package/node_modules/undici/docs/docs/api/BalancedPool.md +0 -99
  73. package/node_modules/undici/docs/docs/api/CacheStorage.md +0 -30
  74. package/node_modules/undici/docs/docs/api/CacheStore.md +0 -164
  75. package/node_modules/undici/docs/docs/api/Client.md +0 -288
  76. package/node_modules/undici/docs/docs/api/ClientStats.md +0 -27
  77. package/node_modules/undici/docs/docs/api/Connector.md +0 -115
  78. package/node_modules/undici/docs/docs/api/ContentType.md +0 -57
  79. package/node_modules/undici/docs/docs/api/Cookies.md +0 -128
  80. package/node_modules/undici/docs/docs/api/Debug.md +0 -62
  81. package/node_modules/undici/docs/docs/api/DiagnosticsChannel.md +0 -315
  82. package/node_modules/undici/docs/docs/api/Dispatcher.md +0 -1392
  83. package/node_modules/undici/docs/docs/api/EnvHttpProxyAgent.md +0 -159
  84. package/node_modules/undici/docs/docs/api/Errors.md +0 -49
  85. package/node_modules/undici/docs/docs/api/EventSource.md +0 -45
  86. package/node_modules/undici/docs/docs/api/Fetch.md +0 -60
  87. package/node_modules/undici/docs/docs/api/GlobalInstallation.md +0 -139
  88. package/node_modules/undici/docs/docs/api/H2CClient.md +0 -263
  89. package/node_modules/undici/docs/docs/api/MockAgent.md +0 -603
  90. package/node_modules/undici/docs/docs/api/MockCallHistory.md +0 -197
  91. package/node_modules/undici/docs/docs/api/MockCallHistoryLog.md +0 -43
  92. package/node_modules/undici/docs/docs/api/MockClient.md +0 -81
  93. package/node_modules/undici/docs/docs/api/MockErrors.md +0 -12
  94. package/node_modules/undici/docs/docs/api/MockPool.md +0 -555
  95. package/node_modules/undici/docs/docs/api/Pool.md +0 -84
  96. package/node_modules/undici/docs/docs/api/PoolStats.md +0 -35
  97. package/node_modules/undici/docs/docs/api/ProxyAgent.md +0 -229
  98. package/node_modules/undici/docs/docs/api/RedirectHandler.md +0 -93
  99. package/node_modules/undici/docs/docs/api/RetryAgent.md +0 -50
  100. package/node_modules/undici/docs/docs/api/RetryHandler.md +0 -118
  101. package/node_modules/undici/docs/docs/api/RoundRobinPool.md +0 -145
  102. package/node_modules/undici/docs/docs/api/SnapshotAgent.md +0 -616
  103. package/node_modules/undici/docs/docs/api/Socks5ProxyAgent.md +0 -275
  104. package/node_modules/undici/docs/docs/api/Util.md +0 -25
  105. package/node_modules/undici/docs/docs/api/WebSocket.md +0 -141
  106. package/node_modules/undici/docs/docs/api/api-lifecycle.md +0 -91
  107. package/node_modules/undici/docs/docs/best-practices/client-certificate.md +0 -64
  108. package/node_modules/undici/docs/docs/best-practices/crawling.md +0 -58
  109. package/node_modules/undici/docs/docs/best-practices/mocking-request.md +0 -190
  110. package/node_modules/undici/docs/docs/best-practices/proxy.md +0 -127
  111. package/node_modules/undici/docs/docs/best-practices/undici-vs-builtin-fetch.md +0 -224
  112. package/node_modules/undici/docs/docs/best-practices/writing-tests.md +0 -63
  113. package/node_modules/undici/index-fetch.js +0 -65
  114. package/node_modules/undici/index.d.ts +0 -3
  115. package/node_modules/undici/index.js +0 -234
  116. package/node_modules/undici/lib/api/abort-signal.js +0 -59
  117. package/node_modules/undici/lib/api/api-connect.js +0 -110
  118. package/node_modules/undici/lib/api/api-pipeline.js +0 -252
  119. package/node_modules/undici/lib/api/api-request.js +0 -214
  120. package/node_modules/undici/lib/api/api-stream.js +0 -209
  121. package/node_modules/undici/lib/api/api-upgrade.js +0 -111
  122. package/node_modules/undici/lib/api/index.js +0 -7
  123. package/node_modules/undici/lib/api/readable.js +0 -580
  124. package/node_modules/undici/lib/cache/memory-cache-store.js +0 -234
  125. package/node_modules/undici/lib/cache/sqlite-cache-store.js +0 -461
  126. package/node_modules/undici/lib/core/connect.js +0 -153
  127. package/node_modules/undici/lib/core/constants.js +0 -143
  128. package/node_modules/undici/lib/core/diagnostics.js +0 -227
  129. package/node_modules/undici/lib/core/errors.js +0 -477
  130. package/node_modules/undici/lib/core/request.js +0 -453
  131. package/node_modules/undici/lib/core/socks5-client.js +0 -422
  132. package/node_modules/undici/lib/core/socks5-utils.js +0 -212
  133. package/node_modules/undici/lib/core/symbols.js +0 -75
  134. package/node_modules/undici/lib/core/tree.js +0 -160
  135. package/node_modules/undici/lib/core/util.js +0 -992
  136. package/node_modules/undici/lib/dispatcher/agent.js +0 -158
  137. package/node_modules/undici/lib/dispatcher/balanced-pool.js +0 -219
  138. package/node_modules/undici/lib/dispatcher/client-h1.js +0 -1722
  139. package/node_modules/undici/lib/dispatcher/client-h2.js +0 -995
  140. package/node_modules/undici/lib/dispatcher/client.js +0 -664
  141. package/node_modules/undici/lib/dispatcher/dispatcher-base.js +0 -184
  142. package/node_modules/undici/lib/dispatcher/dispatcher.js +0 -48
  143. package/node_modules/undici/lib/dispatcher/env-http-proxy-agent.js +0 -146
  144. package/node_modules/undici/lib/dispatcher/fixed-queue.js +0 -135
  145. package/node_modules/undici/lib/dispatcher/h2c-client.js +0 -51
  146. package/node_modules/undici/lib/dispatcher/pool-base.js +0 -214
  147. package/node_modules/undici/lib/dispatcher/pool.js +0 -118
  148. package/node_modules/undici/lib/dispatcher/proxy-agent.js +0 -319
  149. package/node_modules/undici/lib/dispatcher/retry-agent.js +0 -35
  150. package/node_modules/undici/lib/dispatcher/round-robin-pool.js +0 -137
  151. package/node_modules/undici/lib/dispatcher/socks5-proxy-agent.js +0 -260
  152. package/node_modules/undici/lib/encoding/index.js +0 -33
  153. package/node_modules/undici/lib/global.js +0 -59
  154. package/node_modules/undici/lib/handler/cache-handler.js +0 -578
  155. package/node_modules/undici/lib/handler/cache-revalidation-handler.js +0 -124
  156. package/node_modules/undici/lib/handler/decorator-handler.js +0 -67
  157. package/node_modules/undici/lib/handler/deduplication-handler.js +0 -460
  158. package/node_modules/undici/lib/handler/redirect-handler.js +0 -238
  159. package/node_modules/undici/lib/handler/retry-handler.js +0 -394
  160. package/node_modules/undici/lib/handler/unwrap-handler.js +0 -106
  161. package/node_modules/undici/lib/handler/wrap-handler.js +0 -105
  162. package/node_modules/undici/lib/interceptor/cache.js +0 -495
  163. package/node_modules/undici/lib/interceptor/decompress.js +0 -259
  164. package/node_modules/undici/lib/interceptor/deduplicate.js +0 -117
  165. package/node_modules/undici/lib/interceptor/dns.js +0 -571
  166. package/node_modules/undici/lib/interceptor/dump.js +0 -112
  167. package/node_modules/undici/lib/interceptor/redirect.js +0 -21
  168. package/node_modules/undici/lib/interceptor/response-error.js +0 -95
  169. package/node_modules/undici/lib/interceptor/retry.js +0 -19
  170. package/node_modules/undici/lib/llhttp/.gitkeep +0 -0
  171. package/node_modules/undici/lib/llhttp/constants.d.ts +0 -195
  172. package/node_modules/undici/lib/llhttp/constants.js +0 -531
  173. package/node_modules/undici/lib/llhttp/llhttp-wasm.js +0 -15
  174. package/node_modules/undici/lib/llhttp/llhttp_simd-wasm.js +0 -15
  175. package/node_modules/undici/lib/llhttp/utils.d.ts +0 -2
  176. package/node_modules/undici/lib/llhttp/utils.js +0 -12
  177. package/node_modules/undici/lib/mock/mock-agent.js +0 -232
  178. package/node_modules/undici/lib/mock/mock-call-history.js +0 -248
  179. package/node_modules/undici/lib/mock/mock-client.js +0 -68
  180. package/node_modules/undici/lib/mock/mock-errors.js +0 -29
  181. package/node_modules/undici/lib/mock/mock-interceptor.js +0 -209
  182. package/node_modules/undici/lib/mock/mock-pool.js +0 -68
  183. package/node_modules/undici/lib/mock/mock-symbols.js +0 -32
  184. package/node_modules/undici/lib/mock/mock-utils.js +0 -486
  185. package/node_modules/undici/lib/mock/pending-interceptors-formatter.js +0 -43
  186. package/node_modules/undici/lib/mock/snapshot-agent.js +0 -353
  187. package/node_modules/undici/lib/mock/snapshot-recorder.js +0 -588
  188. package/node_modules/undici/lib/mock/snapshot-utils.js +0 -158
  189. package/node_modules/undici/lib/util/cache.js +0 -414
  190. package/node_modules/undici/lib/util/date.js +0 -653
  191. package/node_modules/undici/lib/util/promise.js +0 -28
  192. package/node_modules/undici/lib/util/runtime-features.js +0 -124
  193. package/node_modules/undici/lib/util/stats.js +0 -32
  194. package/node_modules/undici/lib/util/timers.js +0 -425
  195. package/node_modules/undici/lib/web/cache/cache.js +0 -864
  196. package/node_modules/undici/lib/web/cache/cachestorage.js +0 -152
  197. package/node_modules/undici/lib/web/cache/util.js +0 -45
  198. package/node_modules/undici/lib/web/cookies/constants.js +0 -12
  199. package/node_modules/undici/lib/web/cookies/index.js +0 -199
  200. package/node_modules/undici/lib/web/cookies/parse.js +0 -314
  201. package/node_modules/undici/lib/web/cookies/util.js +0 -282
  202. package/node_modules/undici/lib/web/eventsource/eventsource-stream.js +0 -399
  203. package/node_modules/undici/lib/web/eventsource/eventsource.js +0 -501
  204. package/node_modules/undici/lib/web/eventsource/util.js +0 -29
  205. package/node_modules/undici/lib/web/fetch/LICENSE +0 -21
  206. package/node_modules/undici/lib/web/fetch/body.js +0 -509
  207. package/node_modules/undici/lib/web/fetch/constants.js +0 -131
  208. package/node_modules/undici/lib/web/fetch/data-url.js +0 -596
  209. package/node_modules/undici/lib/web/fetch/formdata-parser.js +0 -586
  210. package/node_modules/undici/lib/web/fetch/formdata.js +0 -259
  211. package/node_modules/undici/lib/web/fetch/global.js +0 -40
  212. package/node_modules/undici/lib/web/fetch/headers.js +0 -719
  213. package/node_modules/undici/lib/web/fetch/index.js +0 -2413
  214. package/node_modules/undici/lib/web/fetch/request.js +0 -1115
  215. package/node_modules/undici/lib/web/fetch/response.js +0 -641
  216. package/node_modules/undici/lib/web/fetch/util.js +0 -1522
  217. package/node_modules/undici/lib/web/infra/index.js +0 -229
  218. package/node_modules/undici/lib/web/subresource-integrity/Readme.md +0 -9
  219. package/node_modules/undici/lib/web/subresource-integrity/subresource-integrity.js +0 -307
  220. package/node_modules/undici/lib/web/webidl/index.js +0 -1006
  221. package/node_modules/undici/lib/web/websocket/connection.js +0 -329
  222. package/node_modules/undici/lib/web/websocket/constants.js +0 -126
  223. package/node_modules/undici/lib/web/websocket/events.js +0 -331
  224. package/node_modules/undici/lib/web/websocket/frame.js +0 -133
  225. package/node_modules/undici/lib/web/websocket/permessage-deflate.js +0 -100
  226. package/node_modules/undici/lib/web/websocket/receiver.js +0 -507
  227. package/node_modules/undici/lib/web/websocket/sender.js +0 -109
  228. package/node_modules/undici/lib/web/websocket/stream/websocketerror.js +0 -104
  229. package/node_modules/undici/lib/web/websocket/stream/websocketstream.js +0 -498
  230. package/node_modules/undici/lib/web/websocket/util.js +0 -347
  231. package/node_modules/undici/lib/web/websocket/websocket.js +0 -758
  232. package/node_modules/undici/package.json +0 -152
  233. package/node_modules/undici/scripts/strip-comments.js +0 -10
  234. package/node_modules/undici/types/README.md +0 -6
  235. package/node_modules/undici/types/agent.d.ts +0 -32
  236. package/node_modules/undici/types/api.d.ts +0 -43
  237. package/node_modules/undici/types/balanced-pool.d.ts +0 -30
  238. package/node_modules/undici/types/cache-interceptor.d.ts +0 -179
  239. package/node_modules/undici/types/cache.d.ts +0 -36
  240. package/node_modules/undici/types/client-stats.d.ts +0 -15
  241. package/node_modules/undici/types/client.d.ts +0 -139
  242. package/node_modules/undici/types/connector.d.ts +0 -36
  243. package/node_modules/undici/types/content-type.d.ts +0 -21
  244. package/node_modules/undici/types/cookies.d.ts +0 -30
  245. package/node_modules/undici/types/diagnostics-channel.d.ts +0 -74
  246. package/node_modules/undici/types/dispatcher.d.ts +0 -275
  247. package/node_modules/undici/types/env-http-proxy-agent.d.ts +0 -22
  248. package/node_modules/undici/types/errors.d.ts +0 -177
  249. package/node_modules/undici/types/eventsource.d.ts +0 -66
  250. package/node_modules/undici/types/fetch.d.ts +0 -231
  251. package/node_modules/undici/types/formdata.d.ts +0 -114
  252. package/node_modules/undici/types/global-dispatcher.d.ts +0 -9
  253. package/node_modules/undici/types/global-origin.d.ts +0 -7
  254. package/node_modules/undici/types/h2c-client.d.ts +0 -73
  255. package/node_modules/undici/types/handlers.d.ts +0 -14
  256. package/node_modules/undici/types/header.d.ts +0 -160
  257. package/node_modules/undici/types/index.d.ts +0 -91
  258. package/node_modules/undici/types/interceptors.d.ts +0 -80
  259. package/node_modules/undici/types/mock-agent.d.ts +0 -68
  260. package/node_modules/undici/types/mock-call-history.d.ts +0 -111
  261. package/node_modules/undici/types/mock-client.d.ts +0 -27
  262. package/node_modules/undici/types/mock-errors.d.ts +0 -12
  263. package/node_modules/undici/types/mock-interceptor.d.ts +0 -94
  264. package/node_modules/undici/types/mock-pool.d.ts +0 -27
  265. package/node_modules/undici/types/patch.d.ts +0 -29
  266. package/node_modules/undici/types/pool-stats.d.ts +0 -19
  267. package/node_modules/undici/types/pool.d.ts +0 -41
  268. package/node_modules/undici/types/proxy-agent.d.ts +0 -29
  269. package/node_modules/undici/types/readable.d.ts +0 -68
  270. package/node_modules/undici/types/retry-agent.d.ts +0 -8
  271. package/node_modules/undici/types/retry-handler.d.ts +0 -125
  272. package/node_modules/undici/types/round-robin-pool.d.ts +0 -41
  273. package/node_modules/undici/types/snapshot-agent.d.ts +0 -109
  274. package/node_modules/undici/types/socks5-proxy-agent.d.ts +0 -25
  275. package/node_modules/undici/types/util.d.ts +0 -18
  276. package/node_modules/undici/types/utility.d.ts +0 -7
  277. package/node_modules/undici/types/webidl.d.ts +0 -347
  278. package/node_modules/undici/types/websocket.d.ts +0 -188
@@ -1,1722 +0,0 @@
1
- 'use strict'
2
-
3
- /* global WebAssembly */
4
-
5
- const assert = require('node:assert')
6
- const util = require('../core/util.js')
7
- const { channels } = require('../core/diagnostics.js')
8
- const timers = require('../util/timers.js')
9
- const {
10
- RequestContentLengthMismatchError,
11
- ResponseContentLengthMismatchError,
12
- RequestAbortedError,
13
- HeadersTimeoutError,
14
- HeadersOverflowError,
15
- SocketError,
16
- InformationalError,
17
- BodyTimeoutError,
18
- HTTPParserError,
19
- ResponseExceededMaxSizeError
20
- } = require('../core/errors.js')
21
- const {
22
- kUrl,
23
- kReset,
24
- kClient,
25
- kParser,
26
- kBlocking,
27
- kRunning,
28
- kPending,
29
- kSize,
30
- kWriting,
31
- kQueue,
32
- kNoRef,
33
- kKeepAliveDefaultTimeout,
34
- kHostHeader,
35
- kPendingIdx,
36
- kRunningIdx,
37
- kError,
38
- kPipelining,
39
- kSocket,
40
- kKeepAliveTimeoutValue,
41
- kMaxHeadersSize,
42
- kKeepAliveMaxTimeout,
43
- kKeepAliveTimeoutThreshold,
44
- kHeadersTimeout,
45
- kBodyTimeout,
46
- kStrictContentLength,
47
- kMaxRequests,
48
- kCounter,
49
- kMaxResponseSize,
50
- kOnError,
51
- kResume,
52
- kHTTPContext,
53
- kClosed
54
- } = require('../core/symbols.js')
55
-
56
- const constants = require('../llhttp/constants.js')
57
- const EMPTY_BUF = Buffer.alloc(0)
58
- const FastBuffer = Buffer[Symbol.species]
59
- const removeAllListeners = util.removeAllListeners
60
- const kIdleSocketValidation = Symbol('kIdleSocketValidation')
61
- const kIdleSocketValidationTimeout = Symbol('kIdleSocketValidationTimeout')
62
- const kSocketUsed = Symbol('kSocketUsed')
63
-
64
- let extractBody
65
-
66
- function lazyllhttp () {
67
- const llhttpWasmData = process.env.JEST_WORKER_ID ? require('../llhttp/llhttp-wasm.js') : undefined
68
-
69
- let mod
70
-
71
- // We disable wasm SIMD on ppc64 as it seems to be broken on Power 9 architectures.
72
- let useWasmSIMD = process.arch !== 'ppc64'
73
- // The Env Variable UNDICI_NO_WASM_SIMD allows explicitly overriding the default behavior
74
- if (process.env.UNDICI_NO_WASM_SIMD === '1') {
75
- useWasmSIMD = false
76
- } else if (process.env.UNDICI_NO_WASM_SIMD === '0') {
77
- useWasmSIMD = true
78
- }
79
-
80
- if (useWasmSIMD) {
81
- try {
82
- mod = new WebAssembly.Module(require('../llhttp/llhttp_simd-wasm.js'))
83
- } catch {
84
- }
85
- }
86
-
87
- if (!mod) {
88
- // We could check if the error was caused by the simd option not
89
- // being enabled, but the occurring of this other error
90
- // * https://github.com/emscripten-core/emscripten/issues/11495
91
- // got me to remove that check to avoid breaking Node 12.
92
- mod = new WebAssembly.Module(llhttpWasmData || require('../llhttp/llhttp-wasm.js'))
93
- }
94
-
95
- return new WebAssembly.Instance(mod, {
96
- env: {
97
- /**
98
- * @param {number} p
99
- * @param {number} at
100
- * @param {number} len
101
- * @returns {number}
102
- */
103
- wasm_on_url: (p, at, len) => {
104
- return 0
105
- },
106
- /**
107
- * @param {number} p
108
- * @param {number} at
109
- * @param {number} len
110
- * @returns {number}
111
- */
112
- wasm_on_status: (p, at, len) => {
113
- assert(currentParser.ptr === p)
114
- const start = at - currentBufferPtr + currentBufferRef.byteOffset
115
- return currentParser.onStatus(new FastBuffer(currentBufferRef.buffer, start, len))
116
- },
117
- /**
118
- * @param {number} p
119
- * @returns {number}
120
- */
121
- wasm_on_message_begin: (p) => {
122
- assert(currentParser.ptr === p)
123
- return currentParser.onMessageBegin()
124
- },
125
- /**
126
- * @param {number} p
127
- * @param {number} at
128
- * @param {number} len
129
- * @returns {number}
130
- */
131
- wasm_on_header_field: (p, at, len) => {
132
- assert(currentParser.ptr === p)
133
- const start = at - currentBufferPtr + currentBufferRef.byteOffset
134
- return currentParser.onHeaderField(new FastBuffer(currentBufferRef.buffer, start, len))
135
- },
136
- /**
137
- * @param {number} p
138
- * @param {number} at
139
- * @param {number} len
140
- * @returns {number}
141
- */
142
- wasm_on_header_value: (p, at, len) => {
143
- assert(currentParser.ptr === p)
144
- const start = at - currentBufferPtr + currentBufferRef.byteOffset
145
- return currentParser.onHeaderValue(new FastBuffer(currentBufferRef.buffer, start, len))
146
- },
147
- /**
148
- * @param {number} p
149
- * @param {number} statusCode
150
- * @param {0|1} upgrade
151
- * @param {0|1} shouldKeepAlive
152
- * @returns {number}
153
- */
154
- wasm_on_headers_complete: (p, statusCode, upgrade, shouldKeepAlive) => {
155
- assert(currentParser.ptr === p)
156
- return currentParser.onHeadersComplete(statusCode, upgrade === 1, shouldKeepAlive === 1)
157
- },
158
- /**
159
- * @param {number} p
160
- * @param {number} at
161
- * @param {number} len
162
- * @returns {number}
163
- */
164
- wasm_on_body: (p, at, len) => {
165
- assert(currentParser.ptr === p)
166
- const start = at - currentBufferPtr + currentBufferRef.byteOffset
167
- return currentParser.onBody(new FastBuffer(currentBufferRef.buffer, start, len))
168
- },
169
- /**
170
- * @param {number} p
171
- * @returns {number}
172
- */
173
- wasm_on_message_complete: (p) => {
174
- assert(currentParser.ptr === p)
175
- return currentParser.onMessageComplete()
176
- }
177
-
178
- }
179
- })
180
- }
181
-
182
- let llhttpInstance = null
183
-
184
- /**
185
- * @type {Parser|null}
186
- */
187
- let currentParser = null
188
- let currentBufferRef = null
189
- /**
190
- * @type {number}
191
- */
192
- let currentBufferSize = 0
193
- let currentBufferPtr = null
194
-
195
- const USE_NATIVE_TIMER = 0
196
- const USE_FAST_TIMER = 1
197
-
198
- // Use fast timers for headers and body to take eventual event loop
199
- // latency into account.
200
- const TIMEOUT_HEADERS = 2 | USE_FAST_TIMER
201
- const TIMEOUT_BODY = 4 | USE_FAST_TIMER
202
-
203
- // Use native timers to ignore event loop latency for keep-alive
204
- // handling.
205
- const TIMEOUT_KEEP_ALIVE = 8 | USE_NATIVE_TIMER
206
-
207
- class Parser {
208
- /**
209
- * @param {import('./client.js')} client
210
- * @param {import('net').Socket} socket
211
- * @param {*} llhttp
212
- */
213
- constructor (client, socket, { exports }) {
214
- this.llhttp = exports
215
- this.ptr = this.llhttp.llhttp_alloc(constants.TYPE.RESPONSE)
216
- this.client = client
217
- /**
218
- * @type {import('net').Socket}
219
- */
220
- this.socket = socket
221
- this.timeout = null
222
- this.timeoutWeakRef = new WeakRef(this)
223
- this.timeoutValue = null
224
- this.timeoutType = null
225
- this.statusCode = 0
226
- this.statusText = ''
227
- this.upgrade = false
228
- this.headers = []
229
- this.headersSize = 0
230
- this.headersMaxSize = client[kMaxHeadersSize]
231
- this.shouldKeepAlive = false
232
- this.paused = false
233
- this.resume = this.resume.bind(this)
234
-
235
- this.bytesRead = 0
236
-
237
- this.keepAlive = ''
238
- this.contentLength = ''
239
- this.connection = ''
240
- this.maxResponseSize = client[kMaxResponseSize]
241
- }
242
-
243
- setTimeout (delay, type) {
244
- // If the existing timer and the new timer are of different timer type
245
- // (fast or native) or have different delay, we need to clear the existing
246
- // timer and set a new one.
247
- if (
248
- delay !== this.timeoutValue ||
249
- (type & USE_FAST_TIMER) ^ (this.timeoutType & USE_FAST_TIMER)
250
- ) {
251
- // If a timeout is already set, clear it with clearTimeout of the fast
252
- // timer implementation, as it can clear fast and native timers.
253
- if (this.timeout) {
254
- timers.clearTimeout(this.timeout)
255
- this.timeout = null
256
- }
257
-
258
- if (delay) {
259
- if (type & USE_FAST_TIMER) {
260
- this.timeout = timers.setFastTimeout(onParserTimeout, delay, this.timeoutWeakRef)
261
- } else {
262
- this.timeout = setTimeout(onParserTimeout, delay, this.timeoutWeakRef)
263
- this.timeout?.unref()
264
- }
265
- }
266
-
267
- this.timeoutValue = delay
268
- } else if (this.timeout) {
269
- if (this.timeout.refresh) {
270
- this.timeout.refresh()
271
- }
272
- }
273
-
274
- this.timeoutType = type
275
- }
276
-
277
- resume () {
278
- if (this.socket.destroyed || !this.paused) {
279
- return
280
- }
281
-
282
- assert(this.ptr != null)
283
- assert(currentParser === null)
284
-
285
- this.llhttp.llhttp_resume(this.ptr)
286
-
287
- assert(this.timeoutType === TIMEOUT_BODY)
288
- if (this.timeout) {
289
- if (this.timeout.refresh) {
290
- this.timeout.refresh()
291
- }
292
- }
293
-
294
- this.paused = false
295
- this.execute(this.socket.read() || EMPTY_BUF) // Flush parser.
296
- this.readMore()
297
- }
298
-
299
- readMore () {
300
- while (!this.paused && this.ptr) {
301
- const chunk = this.socket.read()
302
- if (chunk === null) {
303
- break
304
- }
305
- this.execute(chunk)
306
- }
307
- }
308
-
309
- /**
310
- * @param {Buffer} chunk
311
- */
312
- execute (chunk) {
313
- assert(currentParser === null)
314
- assert(this.ptr != null)
315
- assert(!this.paused)
316
-
317
- const { socket, llhttp } = this
318
-
319
- // Allocate a new buffer if the current buffer is too small.
320
- if (chunk.length > currentBufferSize) {
321
- if (currentBufferPtr) {
322
- llhttp.free(currentBufferPtr)
323
- }
324
- // Allocate a buffer that is a multiple of 4096 bytes.
325
- currentBufferSize = Math.ceil(chunk.length / 4096) * 4096
326
- currentBufferPtr = llhttp.malloc(currentBufferSize)
327
- }
328
-
329
- new Uint8Array(llhttp.memory.buffer, currentBufferPtr, currentBufferSize).set(chunk)
330
-
331
- // Call `execute` on the wasm parser.
332
- // We pass the `llhttp_parser` pointer address, the pointer address of buffer view data,
333
- // and finally the length of bytes to parse.
334
- // The return value is an error code or `constants.ERROR.OK`.
335
- try {
336
- let ret
337
-
338
- try {
339
- currentBufferRef = chunk
340
- currentParser = this
341
- ret = llhttp.llhttp_execute(this.ptr, currentBufferPtr, chunk.length)
342
- } finally {
343
- currentParser = null
344
- currentBufferRef = null
345
- }
346
-
347
- if (ret !== constants.ERROR.OK) {
348
- const data = chunk.subarray(llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr)
349
-
350
- if (ret === constants.ERROR.PAUSED_UPGRADE) {
351
- this.onUpgrade(data)
352
- } else if (ret === constants.ERROR.PAUSED) {
353
- this.paused = true
354
- socket.unshift(data)
355
- } else {
356
- throw this.createError(ret, data)
357
- }
358
- }
359
- } catch (err) {
360
- util.destroy(socket, err)
361
- }
362
- }
363
-
364
- finish () {
365
- assert(currentParser === null)
366
- assert(this.ptr != null)
367
- assert(!this.paused)
368
-
369
- const { llhttp } = this
370
-
371
- let ret
372
-
373
- try {
374
- currentParser = this
375
- ret = llhttp.llhttp_finish(this.ptr)
376
- } finally {
377
- currentParser = null
378
- }
379
-
380
- if (ret === constants.ERROR.OK) {
381
- return null
382
- }
383
-
384
- if (ret === constants.ERROR.PAUSED || ret === constants.ERROR.PAUSED_UPGRADE) {
385
- this.paused = true
386
- return null
387
- }
388
-
389
- return this.createError(ret, EMPTY_BUF)
390
- }
391
-
392
- createError (ret, data) {
393
- const { llhttp, contentLength, bytesRead } = this
394
-
395
- if (contentLength && bytesRead !== parseInt(contentLength, 10)) {
396
- return new ResponseContentLengthMismatchError()
397
- }
398
-
399
- const ptr = llhttp.llhttp_get_error_reason(this.ptr)
400
- let message = ''
401
- if (ptr) {
402
- const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0)
403
- message =
404
- 'Response does not match the HTTP/1.1 protocol (' +
405
- Buffer.from(llhttp.memory.buffer, ptr, len).toString() +
406
- ')'
407
- }
408
-
409
- return new HTTPParserError(message, constants.ERROR[ret], data)
410
- }
411
-
412
- destroy () {
413
- assert(currentParser === null)
414
- assert(this.ptr != null)
415
-
416
- this.llhttp.llhttp_free(this.ptr)
417
- this.ptr = null
418
-
419
- this.timeout && timers.clearTimeout(this.timeout)
420
- this.timeout = null
421
- this.timeoutValue = null
422
- this.timeoutType = null
423
-
424
- this.paused = false
425
- }
426
-
427
- /**
428
- * @param {Buffer} buf
429
- * @returns {0}
430
- */
431
- onStatus (buf) {
432
- this.statusText = buf.toString()
433
- return 0
434
- }
435
-
436
- /**
437
- * @returns {0|-1}
438
- */
439
- onMessageBegin () {
440
- const { socket, client } = this
441
-
442
- if (socket.destroyed) {
443
- return -1
444
- }
445
-
446
- if (client[kRunning] === 0) {
447
- util.destroy(socket, new SocketError('bad response', util.getSocketInfo(socket)))
448
- return -1
449
- }
450
-
451
- const request = client[kQueue][client[kRunningIdx]]
452
- if (!request) {
453
- return -1
454
- }
455
- request.onResponseStarted()
456
-
457
- return 0
458
- }
459
-
460
- /**
461
- * @param {Buffer} buf
462
- * @returns {number}
463
- */
464
- onHeaderField (buf) {
465
- const len = this.headers.length
466
-
467
- if ((len & 1) === 0) {
468
- this.headers.push(buf)
469
- } else {
470
- this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf])
471
- }
472
-
473
- this.trackHeader(buf.length)
474
-
475
- return 0
476
- }
477
-
478
- /**
479
- * @param {Buffer} buf
480
- * @returns {number}
481
- */
482
- onHeaderValue (buf) {
483
- let len = this.headers.length
484
-
485
- if ((len & 1) === 1) {
486
- this.headers.push(buf)
487
- len += 1
488
- } else {
489
- this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf])
490
- }
491
-
492
- const key = this.headers[len - 2]
493
- if (key.length === 10) {
494
- const headerName = util.bufferToLowerCasedHeaderName(key)
495
- if (headerName === 'keep-alive') {
496
- this.keepAlive += buf.toString()
497
- } else if (headerName === 'connection') {
498
- this.connection += buf.toString()
499
- }
500
- } else if (key.length === 14 && util.bufferToLowerCasedHeaderName(key) === 'content-length') {
501
- this.contentLength += buf.toString()
502
- }
503
-
504
- this.trackHeader(buf.length)
505
-
506
- return 0
507
- }
508
-
509
- /**
510
- * @param {number} len
511
- */
512
- trackHeader (len) {
513
- this.headersSize += len
514
- if (this.headersSize >= this.headersMaxSize) {
515
- util.destroy(this.socket, new HeadersOverflowError())
516
- }
517
- }
518
-
519
- /**
520
- * @param {Buffer} head
521
- */
522
- onUpgrade (head) {
523
- const { upgrade, client, socket, headers, statusCode } = this
524
-
525
- assert(upgrade)
526
- assert(client[kSocket] === socket)
527
- assert(!socket.destroyed)
528
- assert(!this.paused)
529
- assert((headers.length & 1) === 0)
530
-
531
- const request = client[kQueue][client[kRunningIdx]]
532
- assert(request)
533
- assert(request.upgrade || request.method === 'CONNECT')
534
-
535
- this.statusCode = 0
536
- this.statusText = ''
537
- this.shouldKeepAlive = false
538
-
539
- this.headers = []
540
- this.headersSize = 0
541
-
542
- socket.unshift(head)
543
-
544
- socket[kParser].destroy()
545
- socket[kParser] = null
546
-
547
- socket[kClient] = null
548
- socket[kError] = null
549
-
550
- removeAllListeners(socket)
551
-
552
- client[kSocket] = null
553
- client[kHTTPContext] = null // TODO (fix): This is hacky...
554
- client[kQueue][client[kRunningIdx]++] = null
555
- client.emit('disconnect', client[kUrl], [client], new InformationalError('upgrade'))
556
-
557
- try {
558
- request.onUpgrade(statusCode, headers, socket)
559
- } catch (err) {
560
- util.destroy(socket, err)
561
- }
562
-
563
- client[kResume]()
564
- }
565
-
566
- /**
567
- * @param {number} statusCode
568
- * @param {boolean} upgrade
569
- * @param {boolean} shouldKeepAlive
570
- * @returns {number}
571
- */
572
- onHeadersComplete (statusCode, upgrade, shouldKeepAlive) {
573
- const { client, socket, headers, statusText } = this
574
-
575
- if (socket.destroyed) {
576
- return -1
577
- }
578
-
579
- if (client[kRunning] === 0) {
580
- util.destroy(socket, new SocketError('bad response', util.getSocketInfo(socket)))
581
- return -1
582
- }
583
-
584
- const request = client[kQueue][client[kRunningIdx]]
585
-
586
- if (!request) {
587
- return -1
588
- }
589
-
590
- assert(!this.upgrade)
591
- assert(this.statusCode < 200)
592
-
593
- if (statusCode === 100) {
594
- util.destroy(socket, new SocketError('bad response', util.getSocketInfo(socket)))
595
- return -1
596
- }
597
-
598
- /* this can only happen if server is misbehaving */
599
- if (upgrade && !request.upgrade) {
600
- util.destroy(socket, new SocketError('bad upgrade', util.getSocketInfo(socket)))
601
- return -1
602
- }
603
-
604
- assert(this.timeoutType === TIMEOUT_HEADERS)
605
-
606
- this.statusCode = statusCode
607
- this.shouldKeepAlive = (
608
- shouldKeepAlive ||
609
- // Override llhttp value which does not allow keepAlive for HEAD.
610
- (request.method === 'HEAD' && !socket[kReset] && this.connection.toLowerCase() === 'keep-alive')
611
- )
612
-
613
- if (this.statusCode >= 200) {
614
- const bodyTimeout = request.bodyTimeout != null
615
- ? request.bodyTimeout
616
- : client[kBodyTimeout]
617
- this.setTimeout(bodyTimeout, TIMEOUT_BODY)
618
- } else if (this.timeout) {
619
- if (this.timeout.refresh) {
620
- this.timeout.refresh()
621
- }
622
- }
623
-
624
- if (request.method === 'CONNECT') {
625
- assert(client[kRunning] === 1)
626
- this.upgrade = true
627
- return 2
628
- }
629
-
630
- if (upgrade) {
631
- assert(client[kRunning] === 1)
632
- this.upgrade = true
633
- return 2
634
- }
635
-
636
- assert((this.headers.length & 1) === 0)
637
- this.headers = []
638
- this.headersSize = 0
639
-
640
- if (this.shouldKeepAlive && client[kPipelining]) {
641
- const keepAliveTimeout = this.keepAlive ? util.parseKeepAliveTimeout(this.keepAlive) : null
642
-
643
- if (keepAliveTimeout != null) {
644
- const timeout = Math.min(
645
- keepAliveTimeout - client[kKeepAliveTimeoutThreshold],
646
- client[kKeepAliveMaxTimeout]
647
- )
648
- if (timeout <= 0) {
649
- socket[kReset] = true
650
- } else {
651
- client[kKeepAliveTimeoutValue] = timeout
652
- }
653
- } else {
654
- client[kKeepAliveTimeoutValue] = client[kKeepAliveDefaultTimeout]
655
- }
656
- } else {
657
- // Stop more requests from being dispatched.
658
- socket[kReset] = true
659
- }
660
-
661
- const pause = request.onHeaders(statusCode, headers, this.resume, statusText) === false
662
-
663
- if (request.aborted) {
664
- return -1
665
- }
666
-
667
- if (request.method === 'HEAD') {
668
- return 1
669
- }
670
-
671
- if (statusCode < 200) {
672
- return 1
673
- }
674
-
675
- if (socket[kBlocking]) {
676
- socket[kBlocking] = false
677
- client[kResume]()
678
- }
679
-
680
- return pause ? constants.ERROR.PAUSED : 0
681
- }
682
-
683
- /**
684
- * @param {Buffer} buf
685
- * @returns {number}
686
- */
687
- onBody (buf) {
688
- const { client, socket, statusCode, maxResponseSize } = this
689
-
690
- if (socket.destroyed) {
691
- return -1
692
- }
693
-
694
- const request = client[kQueue][client[kRunningIdx]]
695
- assert(request)
696
-
697
- assert(this.timeoutType === TIMEOUT_BODY)
698
- if (this.timeout) {
699
- if (this.timeout.refresh) {
700
- this.timeout.refresh()
701
- }
702
- }
703
-
704
- assert(statusCode >= 200)
705
-
706
- if (maxResponseSize > -1 && this.bytesRead + buf.length > maxResponseSize) {
707
- util.destroy(socket, new ResponseExceededMaxSizeError())
708
- return -1
709
- }
710
-
711
- this.bytesRead += buf.length
712
-
713
- if (request.onData(buf) === false) {
714
- return constants.ERROR.PAUSED
715
- }
716
-
717
- return 0
718
- }
719
-
720
- /**
721
- * @returns {number}
722
- */
723
- onMessageComplete () {
724
- const { client, socket, statusCode, upgrade, headers, contentLength, bytesRead, shouldKeepAlive } = this
725
-
726
- if (socket.destroyed && (!statusCode || shouldKeepAlive)) {
727
- return -1
728
- }
729
-
730
- if (upgrade) {
731
- return 0
732
- }
733
-
734
- assert(statusCode >= 100)
735
- assert((this.headers.length & 1) === 0)
736
-
737
- const request = client[kQueue][client[kRunningIdx]]
738
- assert(request)
739
-
740
- this.statusCode = 0
741
- this.statusText = ''
742
- this.bytesRead = 0
743
- this.contentLength = ''
744
- this.keepAlive = ''
745
- this.connection = ''
746
-
747
- this.headers = []
748
- this.headersSize = 0
749
-
750
- if (statusCode < 200) {
751
- return 0
752
- }
753
-
754
- if (request.method !== 'HEAD' && contentLength && bytesRead !== parseInt(contentLength, 10)) {
755
- util.destroy(socket, new ResponseContentLengthMismatchError())
756
- return -1
757
- }
758
-
759
- request.onComplete(headers)
760
-
761
- client[kQueue][client[kRunningIdx]++] = null
762
- socket[kSocketUsed] = client[kPending] === 0
763
-
764
- if (socket[kWriting]) {
765
- assert(client[kRunning] === 0)
766
- // Response completed before request.
767
- util.destroy(socket, new InformationalError('reset'))
768
- return constants.ERROR.PAUSED
769
- } else if (!shouldKeepAlive) {
770
- util.destroy(socket, new InformationalError('reset'))
771
- return constants.ERROR.PAUSED
772
- } else if (socket[kReset] && client[kRunning] === 0) {
773
- // Destroy socket once all requests have completed.
774
- // The request at the tail of the pipeline is the one
775
- // that requested reset and no further requests should
776
- // have been queued since then.
777
- util.destroy(socket, new InformationalError('reset'))
778
- return constants.ERROR.PAUSED
779
- } else if (client[kPipelining] == null || client[kPipelining] === 1) {
780
- // We must wait a full event loop cycle to reuse this socket to make sure
781
- // that non-spec compliant servers are not closing the connection even if they
782
- // said they won't.
783
- setImmediate(client[kResume])
784
- } else {
785
- client[kResume]()
786
- }
787
-
788
- return 0
789
- }
790
- }
791
-
792
- function onParserTimeout (parserWeakRef) {
793
- const parser = parserWeakRef.deref()
794
- if (!parser) {
795
- return
796
- }
797
-
798
- const { socket, timeoutType, client, paused } = parser
799
-
800
- if (timeoutType === TIMEOUT_HEADERS) {
801
- if (!socket[kWriting] || socket.writableNeedDrain || client[kRunning] > 1) {
802
- assert(!paused, 'cannot be paused while waiting for headers')
803
- util.destroy(socket, new HeadersTimeoutError())
804
- }
805
- } else if (timeoutType === TIMEOUT_BODY) {
806
- if (!paused) {
807
- util.destroy(socket, new BodyTimeoutError())
808
- }
809
- } else if (timeoutType === TIMEOUT_KEEP_ALIVE) {
810
- assert(client[kRunning] === 0 && client[kKeepAliveTimeoutValue])
811
- util.destroy(socket, new InformationalError('socket idle timeout'))
812
- }
813
- }
814
-
815
- /**
816
- * @param {import ('./client.js')} client
817
- * @param {import('net').Socket} socket
818
- * @returns
819
- */
820
- function connectH1 (client, socket) {
821
- client[kSocket] = socket
822
-
823
- if (!llhttpInstance) {
824
- llhttpInstance = lazyllhttp()
825
- }
826
-
827
- if (socket.errored) {
828
- throw socket.errored
829
- }
830
-
831
- if (socket.destroyed) {
832
- throw new SocketError('destroyed')
833
- }
834
-
835
- socket[kNoRef] = false
836
- socket[kWriting] = false
837
- socket[kReset] = false
838
- socket[kBlocking] = false
839
- socket[kIdleSocketValidation] = 0
840
- socket[kIdleSocketValidationTimeout] = null
841
- socket[kSocketUsed] = false
842
- socket[kParser] = new Parser(client, socket, llhttpInstance)
843
-
844
- util.addListener(socket, 'error', onHttpSocketError)
845
- util.addListener(socket, 'readable', onHttpSocketReadable)
846
- util.addListener(socket, 'end', onHttpSocketEnd)
847
- util.addListener(socket, 'close', onHttpSocketClose)
848
-
849
- socket[kClosed] = false
850
- socket.on('close', onSocketClose)
851
-
852
- return {
853
- version: 'h1',
854
- defaultPipelining: 1,
855
- write (request) {
856
- return writeH1(client, request)
857
- },
858
- resume () {
859
- resumeH1(client)
860
- },
861
- /**
862
- * @param {Error|undefined} err
863
- * @param {() => void} callback
864
- */
865
- destroy (err, callback) {
866
- if (socket[kClosed]) {
867
- queueMicrotask(callback)
868
- } else {
869
- socket.on('close', callback)
870
- socket.destroy(err)
871
- }
872
- },
873
- /**
874
- * @returns {boolean}
875
- */
876
- get destroyed () {
877
- return socket.destroyed
878
- },
879
- /**
880
- * @param {import('../core/request.js')} request
881
- * @returns {boolean}
882
- */
883
- busy (request) {
884
- if (socket[kWriting] || socket[kReset] || socket[kBlocking] || socket[kIdleSocketValidation] === 1) {
885
- return true
886
- }
887
-
888
- if (request) {
889
- if (client[kRunning] > 0 && !request.idempotent) {
890
- // Non-idempotent request cannot be retried.
891
- // Ensure that no other requests are inflight and
892
- // could cause failure.
893
- return true
894
- }
895
-
896
- if (client[kRunning] > 0 && (request.upgrade || request.method === 'CONNECT')) {
897
- // Don't dispatch an upgrade until all preceding requests have completed.
898
- // A misbehaving server might upgrade the connection before all pipelined
899
- // request has completed.
900
- return true
901
- }
902
-
903
- if (client[kRunning] > 0 && util.bodyLength(request.body) !== 0 &&
904
- (util.isStream(request.body) || util.isAsyncIterable(request.body) || util.isFormDataLike(request.body))) {
905
- // Request with stream or iterator body can error while other requests
906
- // are inflight and indirectly error those as well.
907
- // Ensure this doesn't happen by waiting for inflight
908
- // to complete before dispatching.
909
-
910
- // Request with stream or iterator body cannot be retried.
911
- // Ensure that no other requests are inflight and
912
- // could cause failure.
913
- return true
914
- }
915
- }
916
-
917
- return false
918
- }
919
- }
920
- }
921
-
922
- function onHttpSocketError (err) {
923
- assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID')
924
-
925
- const parser = this[kParser]
926
-
927
- // On Mac OS, we get an ECONNRESET even if there is a full body to be forwarded
928
- // to the user.
929
- if (err.code === 'ECONNRESET' && parser.statusCode && !parser.shouldKeepAlive) {
930
- const parserErr = parser.finish()
931
- if (parserErr) {
932
- this[kError] = parserErr
933
- this[kClient][kOnError](parserErr)
934
- }
935
- return
936
- }
937
-
938
- this[kError] = err
939
-
940
- this[kClient][kOnError](err)
941
- }
942
-
943
- function onHttpSocketReadable () {
944
- this[kParser]?.readMore()
945
- }
946
-
947
- function onHttpSocketEnd () {
948
- const parser = this[kParser]
949
-
950
- if (parser.statusCode && !parser.shouldKeepAlive) {
951
- const parserErr = parser.finish()
952
- if (parserErr) {
953
- util.destroy(this, parserErr)
954
- }
955
- return
956
- }
957
-
958
- util.destroy(this, new SocketError('other side closed', util.getSocketInfo(this)))
959
- }
960
-
961
- function onHttpSocketClose () {
962
- const parser = this[kParser]
963
-
964
- clearIdleSocketValidation(this)
965
-
966
- if (parser) {
967
- if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) {
968
- this[kError] = parser.finish() || this[kError]
969
- }
970
-
971
- this[kParser].destroy()
972
- this[kParser] = null
973
- }
974
-
975
- const err = this[kError] || new SocketError('closed', util.getSocketInfo(this))
976
-
977
- const client = this[kClient]
978
-
979
- client[kSocket] = null
980
- client[kHTTPContext] = null // TODO (fix): This is hacky...
981
-
982
- if (client.destroyed) {
983
- assert(client[kPending] === 0)
984
-
985
- // Fail entire queue.
986
- const requests = client[kQueue].splice(client[kRunningIdx])
987
- for (let i = 0; i < requests.length; i++) {
988
- const request = requests[i]
989
- util.errorRequest(client, request, err)
990
- }
991
- } else if (client[kRunning] > 0 && err.code !== 'UND_ERR_INFO') {
992
- // Fail head of pipeline.
993
- const request = client[kQueue][client[kRunningIdx]]
994
- client[kQueue][client[kRunningIdx]++] = null
995
-
996
- util.errorRequest(client, request, err)
997
- }
998
-
999
- client[kPendingIdx] = client[kRunningIdx]
1000
-
1001
- assert(client[kRunning] === 0)
1002
-
1003
- client.emit('disconnect', client[kUrl], [client], err)
1004
-
1005
- client[kResume]()
1006
- }
1007
-
1008
- function onSocketClose () {
1009
- this[kClosed] = true
1010
- }
1011
-
1012
- function clearIdleSocketValidation (socket) {
1013
- if (socket[kIdleSocketValidationTimeout]) {
1014
- clearTimeout(socket[kIdleSocketValidationTimeout])
1015
- socket[kIdleSocketValidationTimeout] = null
1016
- }
1017
-
1018
- socket[kIdleSocketValidation] = 0
1019
- }
1020
-
1021
- function scheduleIdleSocketValidation (client, socket) {
1022
- socket[kIdleSocketValidation] = 1
1023
- socket[kIdleSocketValidationTimeout] = setTimeout(() => {
1024
- socket[kIdleSocketValidationTimeout] = null
1025
- socket[kIdleSocketValidation] = 2
1026
-
1027
- if (client[kSocket] === socket && !socket.destroyed) {
1028
- client[kResume]()
1029
- }
1030
- }, 0)
1031
- socket[kIdleSocketValidationTimeout].unref?.()
1032
- }
1033
-
1034
- /**
1035
- * @param {import('./client.js')} client
1036
- */
1037
- function resumeH1 (client) {
1038
- const socket = client[kSocket]
1039
-
1040
- if (socket && !socket.destroyed) {
1041
- if (client[kSize] === 0) {
1042
- if (!socket[kNoRef] && socket.unref) {
1043
- socket.unref()
1044
- socket[kNoRef] = true
1045
- }
1046
- } else if (socket[kNoRef] && socket.ref) {
1047
- socket.ref()
1048
- socket[kNoRef] = false
1049
- }
1050
-
1051
- if (client[kRunning] === 0 && client[kPending] > 0 && socket[kSocketUsed]) {
1052
- if (socket[kIdleSocketValidation] === 0) {
1053
- scheduleIdleSocketValidation(client, socket)
1054
- socket[kParser].readMore()
1055
- if (socket.destroyed) {
1056
- return
1057
- }
1058
- return
1059
- }
1060
-
1061
- if (socket[kIdleSocketValidation] === 1) {
1062
- socket[kParser].readMore()
1063
- if (socket.destroyed) {
1064
- return
1065
- }
1066
- return
1067
- }
1068
- }
1069
-
1070
- if (client[kRunning] === 0) {
1071
- socket[kParser].readMore()
1072
- if (socket.destroyed) {
1073
- return
1074
- }
1075
- }
1076
-
1077
- if (client[kSize] === 0) {
1078
- if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) {
1079
- socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE)
1080
- }
1081
- } else if (client[kRunning] > 0 && socket[kParser].statusCode < 200) {
1082
- if (socket[kParser].timeoutType !== TIMEOUT_HEADERS) {
1083
- const request = client[kQueue][client[kRunningIdx]]
1084
- const headersTimeout = request.headersTimeout != null
1085
- ? request.headersTimeout
1086
- : client[kHeadersTimeout]
1087
- socket[kParser].setTimeout(headersTimeout, TIMEOUT_HEADERS)
1088
- }
1089
- }
1090
- }
1091
- }
1092
-
1093
- // https://www.rfc-editor.org/rfc/rfc7230#section-3.3.2
1094
- function shouldSendContentLength (method) {
1095
- return method !== 'GET' && method !== 'HEAD' && method !== 'OPTIONS' && method !== 'TRACE' && method !== 'CONNECT'
1096
- }
1097
-
1098
- /**
1099
- * @param {import('./client.js')} client
1100
- * @param {import('../core/request.js')} request
1101
- * @returns
1102
- */
1103
- function writeH1 (client, request) {
1104
- const { method, path, host, upgrade, blocking, reset } = request
1105
-
1106
- let { body, headers, contentLength } = request
1107
-
1108
- // https://tools.ietf.org/html/rfc7231#section-4.3.1
1109
- // https://tools.ietf.org/html/rfc7231#section-4.3.2
1110
- // https://tools.ietf.org/html/rfc7231#section-4.3.5
1111
-
1112
- // Sending a payload body on a request that does not
1113
- // expect it can cause undefined behavior on some
1114
- // servers and corrupt connection state. Do not
1115
- // re-use the connection for further requests.
1116
-
1117
- const expectsPayload = (
1118
- method === 'PUT' ||
1119
- method === 'POST' ||
1120
- method === 'PATCH' ||
1121
- method === 'QUERY' ||
1122
- method === 'PROPFIND' ||
1123
- method === 'PROPPATCH'
1124
- )
1125
-
1126
- if (util.isFormDataLike(body)) {
1127
- if (!extractBody) {
1128
- extractBody = require('../web/fetch/body.js').extractBody
1129
- }
1130
-
1131
- const [bodyStream, contentType] = extractBody(body)
1132
- if (request.contentType == null) {
1133
- headers.push('content-type', contentType)
1134
- }
1135
- body = bodyStream.stream
1136
- contentLength = bodyStream.length
1137
- } else if (util.isBlobLike(body) && request.contentType == null && body.type) {
1138
- headers.push('content-type', body.type)
1139
- }
1140
-
1141
- if (body && typeof body.read === 'function') {
1142
- // Try to read EOF in order to get length.
1143
- body.read(0)
1144
- }
1145
-
1146
- const bodyLength = util.bodyLength(body)
1147
-
1148
- contentLength = bodyLength ?? contentLength
1149
-
1150
- if (contentLength === null) {
1151
- contentLength = request.contentLength
1152
- }
1153
-
1154
- if (contentLength === 0 && !expectsPayload) {
1155
- // https://tools.ietf.org/html/rfc7230#section-3.3.2
1156
- // A user agent SHOULD NOT send a Content-Length header field when
1157
- // the request message does not contain a payload body and the method
1158
- // semantics do not anticipate such a body.
1159
-
1160
- contentLength = null
1161
- }
1162
-
1163
- // https://github.com/nodejs/undici/issues/2046
1164
- // A user agent may send a Content-Length header with 0 value, this should be allowed.
1165
- if (shouldSendContentLength(method) && contentLength > 0 && request.contentLength !== null && request.contentLength !== contentLength) {
1166
- if (client[kStrictContentLength]) {
1167
- util.errorRequest(client, request, new RequestContentLengthMismatchError())
1168
- return false
1169
- }
1170
-
1171
- process.emitWarning(new RequestContentLengthMismatchError())
1172
- }
1173
-
1174
- const socket = client[kSocket]
1175
- clearIdleSocketValidation(socket)
1176
-
1177
- /**
1178
- * @param {Error} [err]
1179
- * @returns {void}
1180
- */
1181
- const abort = (err) => {
1182
- if (request.aborted || request.completed) {
1183
- return
1184
- }
1185
-
1186
- util.errorRequest(client, request, err || new RequestAbortedError())
1187
-
1188
- util.destroy(body)
1189
- util.destroy(socket, new InformationalError('aborted'))
1190
- }
1191
-
1192
- try {
1193
- request.onConnect(abort)
1194
- } catch (err) {
1195
- util.errorRequest(client, request, err)
1196
- }
1197
-
1198
- if (request.aborted) {
1199
- return false
1200
- }
1201
-
1202
- if (method === 'HEAD') {
1203
- // https://github.com/mcollina/undici/issues/258
1204
- // Close after a HEAD request to interop with misbehaving servers
1205
- // that may send a body in the response.
1206
-
1207
- socket[kReset] = true
1208
- }
1209
-
1210
- if (upgrade || method === 'CONNECT') {
1211
- // On CONNECT or upgrade, block pipeline from dispatching further
1212
- // requests on this connection.
1213
-
1214
- socket[kReset] = true
1215
- }
1216
-
1217
- if (reset != null) {
1218
- socket[kReset] = reset
1219
- }
1220
-
1221
- if (client[kMaxRequests] && socket[kCounter]++ >= client[kMaxRequests]) {
1222
- socket[kReset] = true
1223
- }
1224
-
1225
- if (blocking) {
1226
- socket[kBlocking] = true
1227
- }
1228
-
1229
- if (socket.setTypeOfService) {
1230
- socket.setTypeOfService(request.typeOfService)
1231
- }
1232
-
1233
- let header = `${method} ${path} HTTP/1.1\r\n`
1234
-
1235
- if (typeof host === 'string') {
1236
- header += `host: ${host}\r\n`
1237
- } else {
1238
- header += client[kHostHeader]
1239
- }
1240
-
1241
- if (upgrade) {
1242
- header += `connection: upgrade\r\nupgrade: ${upgrade}\r\n`
1243
- } else if (client[kPipelining] && !socket[kReset]) {
1244
- header += 'connection: keep-alive\r\n'
1245
- } else {
1246
- header += 'connection: close\r\n'
1247
- }
1248
-
1249
- if (Array.isArray(headers)) {
1250
- for (let n = 0; n < headers.length; n += 2) {
1251
- const key = headers[n + 0]
1252
- const val = headers[n + 1]
1253
-
1254
- if (Array.isArray(val)) {
1255
- for (let i = 0; i < val.length; i++) {
1256
- header += `${key}: ${val[i]}\r\n`
1257
- }
1258
- } else {
1259
- header += `${key}: ${val}\r\n`
1260
- }
1261
- }
1262
- }
1263
-
1264
- if (channels.sendHeaders.hasSubscribers) {
1265
- channels.sendHeaders.publish({ request, headers: header, socket })
1266
- }
1267
-
1268
- if (!body || bodyLength === 0) {
1269
- writeBuffer(abort, null, client, request, socket, contentLength, header, expectsPayload)
1270
- } else if (util.isBuffer(body)) {
1271
- writeBuffer(abort, body, client, request, socket, contentLength, header, expectsPayload)
1272
- } else if (util.isBlobLike(body)) {
1273
- if (typeof body.stream === 'function') {
1274
- writeIterable(abort, body.stream(), client, request, socket, contentLength, header, expectsPayload)
1275
- } else {
1276
- writeBlob(abort, body, client, request, socket, contentLength, header, expectsPayload)
1277
- }
1278
- } else if (util.isStream(body)) {
1279
- writeStream(abort, body, client, request, socket, contentLength, header, expectsPayload)
1280
- } else if (util.isIterable(body)) {
1281
- writeIterable(abort, body, client, request, socket, contentLength, header, expectsPayload)
1282
- } else {
1283
- assert(false)
1284
- }
1285
-
1286
- return true
1287
- }
1288
-
1289
- /**
1290
- * @param {AbortCallback} abort
1291
- * @param {import('stream').Stream} body
1292
- * @param {import('./client.js')} client
1293
- * @param {import('../core/request.js')} request
1294
- * @param {import('net').Socket} socket
1295
- * @param {number} contentLength
1296
- * @param {string} header
1297
- * @param {boolean} expectsPayload
1298
- */
1299
- function writeStream (abort, body, client, request, socket, contentLength, header, expectsPayload) {
1300
- assert(contentLength !== 0 || client[kRunning] === 0, 'stream body cannot be pipelined')
1301
-
1302
- let finished = false
1303
-
1304
- const writer = new AsyncWriter({ abort, socket, request, contentLength, client, expectsPayload, header })
1305
-
1306
- /**
1307
- * @param {Buffer} chunk
1308
- * @returns {void}
1309
- */
1310
- const onData = function (chunk) {
1311
- if (finished) {
1312
- return
1313
- }
1314
-
1315
- try {
1316
- if (!writer.write(chunk) && this.pause) {
1317
- this.pause()
1318
- }
1319
- } catch (err) {
1320
- util.destroy(this, err)
1321
- }
1322
- }
1323
-
1324
- /**
1325
- * @returns {void}
1326
- */
1327
- const onDrain = function () {
1328
- if (finished) {
1329
- return
1330
- }
1331
-
1332
- if (body.resume) {
1333
- body.resume()
1334
- }
1335
- }
1336
-
1337
- /**
1338
- * @returns {void}
1339
- */
1340
- const onClose = function () {
1341
- // 'close' might be emitted *before* 'error' for
1342
- // broken streams. Wait a tick to avoid this case.
1343
- queueMicrotask(() => {
1344
- // It's only safe to remove 'error' listener after
1345
- // 'close'.
1346
- body.removeListener('error', onFinished)
1347
- })
1348
-
1349
- if (!finished) {
1350
- const err = new RequestAbortedError()
1351
- queueMicrotask(() => onFinished(err))
1352
- }
1353
- }
1354
-
1355
- /**
1356
- * @param {Error} [err]
1357
- * @returns
1358
- */
1359
- const onFinished = function (err) {
1360
- if (finished) {
1361
- return
1362
- }
1363
-
1364
- finished = true
1365
-
1366
- assert(socket.destroyed || (socket[kWriting] && client[kRunning] <= 1))
1367
-
1368
- socket
1369
- .off('drain', onDrain)
1370
- .off('error', onFinished)
1371
-
1372
- body
1373
- .removeListener('data', onData)
1374
- .removeListener('end', onFinished)
1375
- .removeListener('close', onClose)
1376
-
1377
- if (!err) {
1378
- try {
1379
- writer.end()
1380
- } catch (er) {
1381
- err = er
1382
- }
1383
- }
1384
-
1385
- writer.destroy(err)
1386
-
1387
- if (err && (err.code !== 'UND_ERR_INFO' || err.message !== 'reset')) {
1388
- util.destroy(body, err)
1389
- } else {
1390
- util.destroy(body)
1391
- }
1392
- }
1393
-
1394
- body
1395
- .on('data', onData)
1396
- .on('end', onFinished)
1397
- .on('error', onFinished)
1398
- .on('close', onClose)
1399
-
1400
- if (body.resume) {
1401
- body.resume()
1402
- }
1403
-
1404
- socket
1405
- .on('drain', onDrain)
1406
- .on('error', onFinished)
1407
-
1408
- if (body.errorEmitted ?? body.errored) {
1409
- setImmediate(onFinished, body.errored)
1410
- } else if (body.endEmitted ?? body.readableEnded) {
1411
- setImmediate(onFinished, null)
1412
- }
1413
-
1414
- if (body.closeEmitted ?? body.closed) {
1415
- setImmediate(onClose)
1416
- }
1417
- }
1418
-
1419
- /**
1420
- * @typedef AbortCallback
1421
- * @type {Function}
1422
- * @param {Error} [err]
1423
- * @returns {void}
1424
- */
1425
-
1426
- /**
1427
- * @param {AbortCallback} abort
1428
- * @param {Uint8Array|null} body
1429
- * @param {import('./client.js')} client
1430
- * @param {import('../core/request.js')} request
1431
- * @param {import('net').Socket} socket
1432
- * @param {number} contentLength
1433
- * @param {string} header
1434
- * @param {boolean} expectsPayload
1435
- * @returns {void}
1436
- */
1437
- function writeBuffer (abort, body, client, request, socket, contentLength, header, expectsPayload) {
1438
- try {
1439
- if (!body) {
1440
- if (contentLength === 0) {
1441
- socket.write(`${header}content-length: 0\r\n\r\n`, 'latin1')
1442
- } else {
1443
- assert(contentLength === null, 'no body must not have content length')
1444
- socket.write(`${header}\r\n`, 'latin1')
1445
- }
1446
- } else if (util.isBuffer(body)) {
1447
- assert(contentLength === body.byteLength, 'buffer body must have content length')
1448
-
1449
- socket.cork()
1450
- socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1')
1451
- socket.write(body)
1452
- socket.uncork()
1453
- request.onBodySent(body)
1454
-
1455
- if (!expectsPayload && request.reset !== false) {
1456
- socket[kReset] = true
1457
- }
1458
- }
1459
- request.onRequestSent()
1460
-
1461
- client[kResume]()
1462
- } catch (err) {
1463
- abort(err)
1464
- }
1465
- }
1466
-
1467
- /**
1468
- * @param {AbortCallback} abort
1469
- * @param {Blob} body
1470
- * @param {import('./client.js')} client
1471
- * @param {import('../core/request.js')} request
1472
- * @param {import('net').Socket} socket
1473
- * @param {number} contentLength
1474
- * @param {string} header
1475
- * @param {boolean} expectsPayload
1476
- * @returns {Promise<void>}
1477
- */
1478
- async function writeBlob (abort, body, client, request, socket, contentLength, header, expectsPayload) {
1479
- assert(contentLength === body.size, 'blob body must have content length')
1480
-
1481
- try {
1482
- if (contentLength != null && contentLength !== body.size) {
1483
- throw new RequestContentLengthMismatchError()
1484
- }
1485
-
1486
- const buffer = Buffer.from(await body.arrayBuffer())
1487
-
1488
- socket.cork()
1489
- socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1')
1490
- socket.write(buffer)
1491
- socket.uncork()
1492
-
1493
- request.onBodySent(buffer)
1494
- request.onRequestSent()
1495
-
1496
- if (!expectsPayload && request.reset !== false) {
1497
- socket[kReset] = true
1498
- }
1499
-
1500
- client[kResume]()
1501
- } catch (err) {
1502
- abort(err)
1503
- }
1504
- }
1505
-
1506
- /**
1507
- * @param {AbortCallback} abort
1508
- * @param {Iterable} body
1509
- * @param {import('./client.js')} client
1510
- * @param {import('../core/request.js')} request
1511
- * @param {import('net').Socket} socket
1512
- * @param {number} contentLength
1513
- * @param {string} header
1514
- * @param {boolean} expectsPayload
1515
- * @returns {Promise<void>}
1516
- */
1517
- async function writeIterable (abort, body, client, request, socket, contentLength, header, expectsPayload) {
1518
- assert(contentLength !== 0 || client[kRunning] === 0, 'iterator body cannot be pipelined')
1519
-
1520
- let callback = null
1521
- function onDrain () {
1522
- if (callback) {
1523
- const cb = callback
1524
- callback = null
1525
- cb()
1526
- }
1527
- }
1528
-
1529
- const waitForDrain = () => new Promise((resolve, reject) => {
1530
- assert(callback === null)
1531
-
1532
- if (socket[kError]) {
1533
- reject(socket[kError])
1534
- } else {
1535
- callback = resolve
1536
- }
1537
- })
1538
-
1539
- socket
1540
- .on('close', onDrain)
1541
- .on('drain', onDrain)
1542
-
1543
- const writer = new AsyncWriter({ abort, socket, request, contentLength, client, expectsPayload, header })
1544
- try {
1545
- // It's up to the user to somehow abort the async iterable.
1546
- for await (const chunk of body) {
1547
- if (socket[kError]) {
1548
- throw socket[kError]
1549
- }
1550
-
1551
- if (!writer.write(chunk)) {
1552
- await waitForDrain()
1553
- }
1554
- }
1555
-
1556
- writer.end()
1557
- } catch (err) {
1558
- writer.destroy(err)
1559
- } finally {
1560
- socket
1561
- .off('close', onDrain)
1562
- .off('drain', onDrain)
1563
- }
1564
- }
1565
-
1566
- class AsyncWriter {
1567
- /**
1568
- *
1569
- * @param {object} arg
1570
- * @param {AbortCallback} arg.abort
1571
- * @param {import('net').Socket} arg.socket
1572
- * @param {import('../core/request.js')} arg.request
1573
- * @param {number} arg.contentLength
1574
- * @param {import('./client.js')} arg.client
1575
- * @param {boolean} arg.expectsPayload
1576
- * @param {string} arg.header
1577
- */
1578
- constructor ({ abort, socket, request, contentLength, client, expectsPayload, header }) {
1579
- this.socket = socket
1580
- this.request = request
1581
- this.contentLength = contentLength
1582
- this.client = client
1583
- this.bytesWritten = 0
1584
- this.expectsPayload = expectsPayload
1585
- this.header = header
1586
- this.abort = abort
1587
-
1588
- socket[kWriting] = true
1589
- }
1590
-
1591
- /**
1592
- * @param {Buffer} chunk
1593
- * @returns
1594
- */
1595
- write (chunk) {
1596
- const { socket, request, contentLength, client, bytesWritten, expectsPayload, header } = this
1597
-
1598
- if (socket[kError]) {
1599
- throw socket[kError]
1600
- }
1601
-
1602
- if (socket.destroyed) {
1603
- return false
1604
- }
1605
-
1606
- const len = Buffer.byteLength(chunk)
1607
- if (!len) {
1608
- return true
1609
- }
1610
-
1611
- // We should defer writing chunks.
1612
- if (contentLength !== null && bytesWritten + len > contentLength) {
1613
- if (client[kStrictContentLength]) {
1614
- throw new RequestContentLengthMismatchError()
1615
- }
1616
-
1617
- process.emitWarning(new RequestContentLengthMismatchError())
1618
- }
1619
-
1620
- socket.cork()
1621
-
1622
- if (bytesWritten === 0) {
1623
- if (!expectsPayload && request.reset !== false) {
1624
- socket[kReset] = true
1625
- }
1626
-
1627
- if (contentLength === null) {
1628
- socket.write(`${header}transfer-encoding: chunked\r\n`, 'latin1')
1629
- } else {
1630
- socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1')
1631
- }
1632
- }
1633
-
1634
- if (contentLength === null) {
1635
- socket.write(`\r\n${len.toString(16)}\r\n`, 'latin1')
1636
- }
1637
-
1638
- this.bytesWritten += len
1639
-
1640
- const ret = socket.write(chunk)
1641
-
1642
- socket.uncork()
1643
-
1644
- request.onBodySent(chunk)
1645
-
1646
- if (!ret) {
1647
- if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) {
1648
- if (socket[kParser].timeout.refresh) {
1649
- socket[kParser].timeout.refresh()
1650
- }
1651
- }
1652
- }
1653
-
1654
- return ret
1655
- }
1656
-
1657
- /**
1658
- * @returns {void}
1659
- */
1660
- end () {
1661
- const { socket, contentLength, client, bytesWritten, expectsPayload, header, request } = this
1662
- request.onRequestSent()
1663
-
1664
- socket[kWriting] = false
1665
-
1666
- if (socket[kError]) {
1667
- throw socket[kError]
1668
- }
1669
-
1670
- if (socket.destroyed) {
1671
- return
1672
- }
1673
-
1674
- if (bytesWritten === 0) {
1675
- if (expectsPayload) {
1676
- // https://tools.ietf.org/html/rfc7230#section-3.3.2
1677
- // A user agent SHOULD send a Content-Length in a request message when
1678
- // no Transfer-Encoding is sent and the request method defines a meaning
1679
- // for an enclosed payload body.
1680
-
1681
- socket.write(`${header}content-length: 0\r\n\r\n`, 'latin1')
1682
- } else {
1683
- socket.write(`${header}\r\n`, 'latin1')
1684
- }
1685
- } else if (contentLength === null) {
1686
- socket.write('\r\n0\r\n\r\n', 'latin1')
1687
- }
1688
-
1689
- if (contentLength !== null && bytesWritten !== contentLength) {
1690
- if (client[kStrictContentLength]) {
1691
- throw new RequestContentLengthMismatchError()
1692
- } else {
1693
- process.emitWarning(new RequestContentLengthMismatchError())
1694
- }
1695
- }
1696
-
1697
- if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) {
1698
- if (socket[kParser].timeout.refresh) {
1699
- socket[kParser].timeout.refresh()
1700
- }
1701
- }
1702
-
1703
- client[kResume]()
1704
- }
1705
-
1706
- /**
1707
- * @param {Error} [err]
1708
- * @returns {void}
1709
- */
1710
- destroy (err) {
1711
- const { socket, client, abort } = this
1712
-
1713
- socket[kWriting] = false
1714
-
1715
- if (err) {
1716
- assert(client[kRunning] <= 1, 'pipeline should only contain this request')
1717
- abort(err)
1718
- }
1719
- }
1720
- }
1721
-
1722
- module.exports = connectH1