@depup/undici 7.24.3-depup.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (211) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +25 -0
  3. package/changes.json +5 -0
  4. package/docs/docs/api/Agent.md +84 -0
  5. package/docs/docs/api/BalancedPool.md +99 -0
  6. package/docs/docs/api/CacheStorage.md +30 -0
  7. package/docs/docs/api/CacheStore.md +164 -0
  8. package/docs/docs/api/Client.md +285 -0
  9. package/docs/docs/api/ClientStats.md +27 -0
  10. package/docs/docs/api/Connector.md +115 -0
  11. package/docs/docs/api/ContentType.md +57 -0
  12. package/docs/docs/api/Cookies.md +101 -0
  13. package/docs/docs/api/Debug.md +62 -0
  14. package/docs/docs/api/DiagnosticsChannel.md +313 -0
  15. package/docs/docs/api/Dispatcher.md +1392 -0
  16. package/docs/docs/api/EnvHttpProxyAgent.md +159 -0
  17. package/docs/docs/api/Errors.md +49 -0
  18. package/docs/docs/api/EventSource.md +45 -0
  19. package/docs/docs/api/Fetch.md +52 -0
  20. package/docs/docs/api/GlobalInstallation.md +91 -0
  21. package/docs/docs/api/H2CClient.md +263 -0
  22. package/docs/docs/api/MockAgent.md +603 -0
  23. package/docs/docs/api/MockCallHistory.md +197 -0
  24. package/docs/docs/api/MockCallHistoryLog.md +43 -0
  25. package/docs/docs/api/MockClient.md +81 -0
  26. package/docs/docs/api/MockErrors.md +12 -0
  27. package/docs/docs/api/MockPool.md +555 -0
  28. package/docs/docs/api/Pool.md +84 -0
  29. package/docs/docs/api/PoolStats.md +35 -0
  30. package/docs/docs/api/ProxyAgent.md +229 -0
  31. package/docs/docs/api/RedirectHandler.md +96 -0
  32. package/docs/docs/api/RetryAgent.md +50 -0
  33. package/docs/docs/api/RetryHandler.md +118 -0
  34. package/docs/docs/api/RoundRobinPool.md +145 -0
  35. package/docs/docs/api/SnapshotAgent.md +616 -0
  36. package/docs/docs/api/Socks5ProxyAgent.md +274 -0
  37. package/docs/docs/api/Util.md +25 -0
  38. package/docs/docs/api/WebSocket.md +141 -0
  39. package/docs/docs/api/api-lifecycle.md +91 -0
  40. package/docs/docs/best-practices/client-certificate.md +64 -0
  41. package/docs/docs/best-practices/crawling.md +58 -0
  42. package/docs/docs/best-practices/mocking-request.md +190 -0
  43. package/docs/docs/best-practices/proxy.md +127 -0
  44. package/docs/docs/best-practices/undici-vs-builtin-fetch.md +137 -0
  45. package/docs/docs/best-practices/writing-tests.md +20 -0
  46. package/index-fetch.js +65 -0
  47. package/index.d.ts +3 -0
  48. package/index.js +234 -0
  49. package/lib/api/abort-signal.js +59 -0
  50. package/lib/api/api-connect.js +110 -0
  51. package/lib/api/api-pipeline.js +252 -0
  52. package/lib/api/api-request.js +214 -0
  53. package/lib/api/api-stream.js +209 -0
  54. package/lib/api/api-upgrade.js +111 -0
  55. package/lib/api/index.js +7 -0
  56. package/lib/api/readable.js +580 -0
  57. package/lib/cache/memory-cache-store.js +234 -0
  58. package/lib/cache/sqlite-cache-store.js +461 -0
  59. package/lib/core/connect.js +137 -0
  60. package/lib/core/constants.js +143 -0
  61. package/lib/core/diagnostics.js +225 -0
  62. package/lib/core/errors.js +477 -0
  63. package/lib/core/request.js +430 -0
  64. package/lib/core/socks5-client.js +407 -0
  65. package/lib/core/socks5-utils.js +203 -0
  66. package/lib/core/symbols.js +75 -0
  67. package/lib/core/tree.js +160 -0
  68. package/lib/core/util.js +972 -0
  69. package/lib/dispatcher/agent.js +158 -0
  70. package/lib/dispatcher/balanced-pool.js +219 -0
  71. package/lib/dispatcher/client-h1.js +1610 -0
  72. package/lib/dispatcher/client-h2.js +995 -0
  73. package/lib/dispatcher/client.js +654 -0
  74. package/lib/dispatcher/dispatcher-base.js +165 -0
  75. package/lib/dispatcher/dispatcher.js +48 -0
  76. package/lib/dispatcher/env-http-proxy-agent.js +146 -0
  77. package/lib/dispatcher/fixed-queue.js +135 -0
  78. package/lib/dispatcher/h2c-client.js +51 -0
  79. package/lib/dispatcher/pool-base.js +214 -0
  80. package/lib/dispatcher/pool.js +118 -0
  81. package/lib/dispatcher/proxy-agent.js +318 -0
  82. package/lib/dispatcher/retry-agent.js +35 -0
  83. package/lib/dispatcher/round-robin-pool.js +137 -0
  84. package/lib/dispatcher/socks5-proxy-agent.js +249 -0
  85. package/lib/encoding/index.js +33 -0
  86. package/lib/global.js +50 -0
  87. package/lib/handler/cache-handler.js +561 -0
  88. package/lib/handler/cache-revalidation-handler.js +124 -0
  89. package/lib/handler/decorator-handler.js +67 -0
  90. package/lib/handler/deduplication-handler.js +460 -0
  91. package/lib/handler/redirect-handler.js +238 -0
  92. package/lib/handler/retry-handler.js +394 -0
  93. package/lib/handler/unwrap-handler.js +100 -0
  94. package/lib/handler/wrap-handler.js +105 -0
  95. package/lib/interceptor/cache.js +495 -0
  96. package/lib/interceptor/decompress.js +259 -0
  97. package/lib/interceptor/deduplicate.js +117 -0
  98. package/lib/interceptor/dns.js +571 -0
  99. package/lib/interceptor/dump.js +112 -0
  100. package/lib/interceptor/redirect.js +21 -0
  101. package/lib/interceptor/response-error.js +95 -0
  102. package/lib/interceptor/retry.js +19 -0
  103. package/lib/llhttp/.gitkeep +0 -0
  104. package/lib/llhttp/constants.d.ts +195 -0
  105. package/lib/llhttp/constants.js +531 -0
  106. package/lib/llhttp/llhttp-wasm.js +15 -0
  107. package/lib/llhttp/llhttp_simd-wasm.js +15 -0
  108. package/lib/llhttp/utils.d.ts +2 -0
  109. package/lib/llhttp/utils.js +12 -0
  110. package/lib/mock/mock-agent.js +232 -0
  111. package/lib/mock/mock-call-history.js +248 -0
  112. package/lib/mock/mock-client.js +68 -0
  113. package/lib/mock/mock-errors.js +29 -0
  114. package/lib/mock/mock-interceptor.js +209 -0
  115. package/lib/mock/mock-pool.js +68 -0
  116. package/lib/mock/mock-symbols.js +31 -0
  117. package/lib/mock/mock-utils.js +480 -0
  118. package/lib/mock/pending-interceptors-formatter.js +43 -0
  119. package/lib/mock/snapshot-agent.js +353 -0
  120. package/lib/mock/snapshot-recorder.js +588 -0
  121. package/lib/mock/snapshot-utils.js +158 -0
  122. package/lib/util/cache.js +407 -0
  123. package/lib/util/date.js +653 -0
  124. package/lib/util/promise.js +28 -0
  125. package/lib/util/runtime-features.js +124 -0
  126. package/lib/util/stats.js +32 -0
  127. package/lib/util/timers.js +425 -0
  128. package/lib/web/cache/cache.js +864 -0
  129. package/lib/web/cache/cachestorage.js +152 -0
  130. package/lib/web/cache/util.js +45 -0
  131. package/lib/web/cookies/constants.js +12 -0
  132. package/lib/web/cookies/index.js +199 -0
  133. package/lib/web/cookies/parse.js +322 -0
  134. package/lib/web/cookies/util.js +282 -0
  135. package/lib/web/eventsource/eventsource-stream.js +399 -0
  136. package/lib/web/eventsource/eventsource.js +501 -0
  137. package/lib/web/eventsource/util.js +29 -0
  138. package/lib/web/fetch/LICENSE +21 -0
  139. package/lib/web/fetch/body.js +509 -0
  140. package/lib/web/fetch/constants.js +131 -0
  141. package/lib/web/fetch/data-url.js +596 -0
  142. package/lib/web/fetch/formdata-parser.js +575 -0
  143. package/lib/web/fetch/formdata.js +259 -0
  144. package/lib/web/fetch/global.js +40 -0
  145. package/lib/web/fetch/headers.js +719 -0
  146. package/lib/web/fetch/index.js +2378 -0
  147. package/lib/web/fetch/request.js +1115 -0
  148. package/lib/web/fetch/response.js +641 -0
  149. package/lib/web/fetch/util.js +1520 -0
  150. package/lib/web/infra/index.js +229 -0
  151. package/lib/web/subresource-integrity/Readme.md +9 -0
  152. package/lib/web/subresource-integrity/subresource-integrity.js +307 -0
  153. package/lib/web/webidl/index.js +1006 -0
  154. package/lib/web/websocket/connection.js +329 -0
  155. package/lib/web/websocket/constants.js +126 -0
  156. package/lib/web/websocket/events.js +331 -0
  157. package/lib/web/websocket/frame.js +133 -0
  158. package/lib/web/websocket/permessage-deflate.js +118 -0
  159. package/lib/web/websocket/receiver.js +450 -0
  160. package/lib/web/websocket/sender.js +109 -0
  161. package/lib/web/websocket/stream/websocketerror.js +104 -0
  162. package/lib/web/websocket/stream/websocketstream.js +497 -0
  163. package/lib/web/websocket/util.js +347 -0
  164. package/lib/web/websocket/websocket.js +739 -0
  165. package/package.json +163 -0
  166. package/scripts/strip-comments.js +10 -0
  167. package/types/README.md +6 -0
  168. package/types/agent.d.ts +32 -0
  169. package/types/api.d.ts +43 -0
  170. package/types/balanced-pool.d.ts +30 -0
  171. package/types/cache-interceptor.d.ts +179 -0
  172. package/types/cache.d.ts +36 -0
  173. package/types/client-stats.d.ts +15 -0
  174. package/types/client.d.ts +123 -0
  175. package/types/connector.d.ts +36 -0
  176. package/types/content-type.d.ts +21 -0
  177. package/types/cookies.d.ts +30 -0
  178. package/types/diagnostics-channel.d.ts +74 -0
  179. package/types/dispatcher.d.ts +279 -0
  180. package/types/env-http-proxy-agent.d.ts +22 -0
  181. package/types/errors.d.ts +177 -0
  182. package/types/eventsource.d.ts +66 -0
  183. package/types/fetch.d.ts +211 -0
  184. package/types/formdata.d.ts +108 -0
  185. package/types/global-dispatcher.d.ts +9 -0
  186. package/types/global-origin.d.ts +7 -0
  187. package/types/h2c-client.d.ts +73 -0
  188. package/types/handlers.d.ts +15 -0
  189. package/types/header.d.ts +160 -0
  190. package/types/index.d.ts +91 -0
  191. package/types/interceptors.d.ts +80 -0
  192. package/types/mock-agent.d.ts +68 -0
  193. package/types/mock-call-history.d.ts +111 -0
  194. package/types/mock-client.d.ts +27 -0
  195. package/types/mock-errors.d.ts +12 -0
  196. package/types/mock-interceptor.d.ts +94 -0
  197. package/types/mock-pool.d.ts +27 -0
  198. package/types/patch.d.ts +29 -0
  199. package/types/pool-stats.d.ts +19 -0
  200. package/types/pool.d.ts +41 -0
  201. package/types/proxy-agent.d.ts +29 -0
  202. package/types/readable.d.ts +68 -0
  203. package/types/retry-agent.d.ts +8 -0
  204. package/types/retry-handler.d.ts +125 -0
  205. package/types/round-robin-pool.d.ts +41 -0
  206. package/types/snapshot-agent.d.ts +109 -0
  207. package/types/socks5-proxy-agent.d.ts +25 -0
  208. package/types/util.d.ts +18 -0
  209. package/types/utility.d.ts +7 -0
  210. package/types/webidl.d.ts +347 -0
  211. package/types/websocket.d.ts +188 -0
@@ -0,0 +1,159 @@
1
+ # Class: EnvHttpProxyAgent
2
+
3
+ Extends: `undici.Dispatcher`
4
+
5
+ EnvHttpProxyAgent automatically reads the proxy configuration from the environment variables `http_proxy`, `https_proxy`, and `no_proxy` and sets up the proxy agents accordingly. When `http_proxy` and `https_proxy` are set, `http_proxy` is used for HTTP requests and `https_proxy` is used for HTTPS requests. If only `http_proxy` is set, `http_proxy` is used for both HTTP and HTTPS requests. If only `https_proxy` is set, it is only used for HTTPS requests.
6
+
7
+ `no_proxy` is a comma or space-separated list of hostnames that should not be proxied. The list may contain leading wildcard characters (`*`). If `no_proxy` is set, the EnvHttpProxyAgent will bypass the proxy for requests to hosts that match the list. If `no_proxy` is set to `"*"`, the EnvHttpProxyAgent will bypass the proxy for all requests.
8
+
9
+ Uppercase environment variables are also supported: `HTTP_PROXY`, `HTTPS_PROXY`, and `NO_PROXY`. However, if both the lowercase and uppercase environment variables are set, the uppercase environment variables will be ignored.
10
+
11
+ ## `new EnvHttpProxyAgent([options])`
12
+
13
+ Arguments:
14
+
15
+ * **options** `EnvHttpProxyAgentOptions` (optional) - extends the `Agent` options.
16
+
17
+ Returns: `EnvHttpProxyAgent`
18
+
19
+ ### Parameter: `EnvHttpProxyAgentOptions`
20
+
21
+ Extends: [`AgentOptions`](/docs/docs/api/Agent.md#parameter-agentoptions)
22
+
23
+ * **httpProxy** `string` (optional) - When set, it will override the `HTTP_PROXY` environment variable.
24
+ * **httpsProxy** `string` (optional) - When set, it will override the `HTTPS_PROXY` environment variable.
25
+ * **noProxy** `string` (optional) - When set, it will override the `NO_PROXY` environment variable.
26
+
27
+ Examples:
28
+
29
+ ```js
30
+ import { EnvHttpProxyAgent } from 'undici'
31
+
32
+ const envHttpProxyAgent = new EnvHttpProxyAgent()
33
+ // or
34
+ const envHttpProxyAgent = new EnvHttpProxyAgent({ httpProxy: 'my.proxy.server:8080', httpsProxy: 'my.proxy.server:8443', noProxy: 'localhost' })
35
+ ```
36
+
37
+ #### Example - EnvHttpProxyAgent instantiation
38
+
39
+ This will instantiate the EnvHttpProxyAgent. It will not do anything until registered as the agent to use with requests.
40
+
41
+ ```js
42
+ import { EnvHttpProxyAgent } from 'undici'
43
+
44
+ const envHttpProxyAgent = new EnvHttpProxyAgent()
45
+ ```
46
+
47
+ #### Example - Basic Proxy Fetch with global agent dispatcher
48
+
49
+ ```js
50
+ import { setGlobalDispatcher, fetch, EnvHttpProxyAgent } from 'undici'
51
+
52
+ const envHttpProxyAgent = new EnvHttpProxyAgent()
53
+ setGlobalDispatcher(envHttpProxyAgent)
54
+
55
+ const { status, json } = await fetch('http://localhost:3000/foo')
56
+
57
+ console.log('response received', status) // response received 200
58
+
59
+ const data = await json() // data { foo: "bar" }
60
+ ```
61
+
62
+ #### Example - Basic Proxy Request with global agent dispatcher
63
+
64
+ ```js
65
+ import { setGlobalDispatcher, request, EnvHttpProxyAgent } from 'undici'
66
+
67
+ const envHttpProxyAgent = new EnvHttpProxyAgent()
68
+ setGlobalDispatcher(envHttpProxyAgent)
69
+
70
+ const { statusCode, body } = await request('http://localhost:3000/foo')
71
+
72
+ console.log('response received', statusCode) // response received 200
73
+
74
+ for await (const data of body) {
75
+ console.log('data', data.toString('utf8')) // data foo
76
+ }
77
+ ```
78
+
79
+ #### Example - Basic Proxy Request with local agent dispatcher
80
+
81
+ ```js
82
+ import { EnvHttpProxyAgent, request } from 'undici'
83
+
84
+ const envHttpProxyAgent = new EnvHttpProxyAgent()
85
+
86
+ const {
87
+ statusCode,
88
+ body
89
+ } = await request('http://localhost:3000/foo', { dispatcher: envHttpProxyAgent })
90
+
91
+ console.log('response received', statusCode) // response received 200
92
+
93
+ for await (const data of body) {
94
+ console.log('data', data.toString('utf8')) // data foo
95
+ }
96
+ ```
97
+
98
+ #### Example - Basic Proxy Fetch with local agent dispatcher
99
+
100
+ ```js
101
+ import { EnvHttpProxyAgent, fetch } from 'undici'
102
+
103
+ const envHttpProxyAgent = new EnvHttpProxyAgent()
104
+
105
+ const {
106
+ status,
107
+ json
108
+ } = await fetch('http://localhost:3000/foo', { dispatcher: envHttpProxyAgent })
109
+
110
+ console.log('response received', status) // response received 200
111
+
112
+ const data = await json() // data { foo: "bar" }
113
+ ```
114
+
115
+ ## Instance Methods
116
+
117
+ ### `EnvHttpProxyAgent.close([callback])`
118
+
119
+ Implements [`Dispatcher.close([callback])`](/docs/docs/api/Dispatcher.md#dispatcherclosecallback-promise).
120
+
121
+ ### `EnvHttpProxyAgent.destroy([error, callback])`
122
+
123
+ Implements [`Dispatcher.destroy([error, callback])`](/docs/docs/api/Dispatcher.md#dispatcherdestroyerror-callback-promise).
124
+
125
+ ### `EnvHttpProxyAgent.dispatch(options, handler: AgentDispatchOptions)`
126
+
127
+ Implements [`Dispatcher.dispatch(options, handler)`](/docs/docs/api/Dispatcher.md#dispatcherdispatchoptions-handler).
128
+
129
+ #### Parameter: `AgentDispatchOptions`
130
+
131
+ Extends: [`DispatchOptions`](/docs/docs/api/Dispatcher.md#parameter-dispatchoptions)
132
+
133
+ * **origin** `string | URL`
134
+
135
+ Implements [`Dispatcher.destroy([error, callback])`](/docs/docs/api/Dispatcher.md#dispatcherdestroyerror-callback-promise).
136
+
137
+ ### `EnvHttpProxyAgent.connect(options[, callback])`
138
+
139
+ See [`Dispatcher.connect(options[, callback])`](/docs/docs/api/Dispatcher.md#dispatcherconnectoptions-callback).
140
+
141
+ ### `EnvHttpProxyAgent.dispatch(options, handler)`
142
+
143
+ Implements [`Dispatcher.dispatch(options, handler)`](/docs/docs/api/Dispatcher.md#dispatcherdispatchoptions-handler).
144
+
145
+ ### `EnvHttpProxyAgent.pipeline(options, handler)`
146
+
147
+ See [`Dispatcher.pipeline(options, handler)`](/docs/docs/api/Dispatcher.md#dispatcherpipelineoptions-handler).
148
+
149
+ ### `EnvHttpProxyAgent.request(options[, callback])`
150
+
151
+ See [`Dispatcher.request(options [, callback])`](/docs/docs/api/Dispatcher.md#dispatcherrequestoptions-callback).
152
+
153
+ ### `EnvHttpProxyAgent.stream(options, factory[, callback])`
154
+
155
+ See [`Dispatcher.stream(options, factory[, callback])`](/docs/docs/api/Dispatcher.md#dispatcherstreamoptions-factory-callback).
156
+
157
+ ### `EnvHttpProxyAgent.upgrade(options[, callback])`
158
+
159
+ See [`Dispatcher.upgrade(options[, callback])`](/docs/docs/api/Dispatcher.md#dispatcherupgradeoptions-callback).
@@ -0,0 +1,49 @@
1
+ # Errors
2
+
3
+ Undici exposes a variety of error objects that you can use to enhance your error handling.
4
+ You can find all the error objects inside the `errors` key.
5
+
6
+ ```js
7
+ import { errors } from 'undici'
8
+ ```
9
+
10
+ | Error | Error Codes | Description |
11
+ | ------------------------------------ | ------------------------------------- | ------------------------------------------------------------------------- |
12
+ | `UndiciError` | `UND_ERR` | all errors below are extended from `UndiciError`. |
13
+ | `ConnectTimeoutError` | `UND_ERR_CONNECT_TIMEOUT` | socket is destroyed due to connect timeout. |
14
+ | `HeadersTimeoutError` | `UND_ERR_HEADERS_TIMEOUT` | socket is destroyed due to headers timeout. |
15
+ | `HeadersOverflowError` | `UND_ERR_HEADERS_OVERFLOW` | socket is destroyed due to headers' max size being exceeded. |
16
+ | `BodyTimeoutError` | `UND_ERR_BODY_TIMEOUT` | socket is destroyed due to body timeout. |
17
+ | `InvalidArgumentError` | `UND_ERR_INVALID_ARG` | passed an invalid argument. |
18
+ | `InvalidReturnValueError` | `UND_ERR_INVALID_RETURN_VALUE` | returned an invalid value. |
19
+ | `RequestAbortedError` | `UND_ERR_ABORTED` | the request has been aborted by the user |
20
+ | `ClientDestroyedError` | `UND_ERR_DESTROYED` | trying to use a destroyed client. |
21
+ | `ClientClosedError` | `UND_ERR_CLOSED` | trying to use a closed client. |
22
+ | `SocketError` | `UND_ERR_SOCKET` | there is an error with the socket. |
23
+ | `NotSupportedError` | `UND_ERR_NOT_SUPPORTED` | encountered unsupported functionality. |
24
+ | `RequestContentLengthMismatchError` | `UND_ERR_REQ_CONTENT_LENGTH_MISMATCH` | request body does not match content-length header |
25
+ | `ResponseContentLengthMismatchError` | `UND_ERR_RES_CONTENT_LENGTH_MISMATCH` | response body does not match content-length header |
26
+ | `InformationalError` | `UND_ERR_INFO` | expected error with reason |
27
+ | `ResponseExceededMaxSizeError` | `UND_ERR_RES_EXCEEDED_MAX_SIZE` | response body exceed the max size allowed |
28
+ | `SecureProxyConnectionError` | `UND_ERR_PRX_TLS` | tls connection to a proxy failed |
29
+ | `MessageSizeExceededError` | `UND_ERR_WS_MESSAGE_SIZE_EXCEEDED` | WebSocket decompressed message exceeded the maximum allowed size |
30
+
31
+ Be aware of the possible difference between the global dispatcher version and the actual undici version you might be using. We recommend to avoid the check `instanceof errors.UndiciError` and seek for the `error.code === '<error_code>'` instead to avoid inconsistencies.
32
+ ### `SocketError`
33
+
34
+ The `SocketError` has a `.socket` property which holds socket metadata:
35
+
36
+ ```ts
37
+ interface SocketInfo {
38
+ localAddress?: string
39
+ localPort?: number
40
+ remoteAddress?: string
41
+ remotePort?: number
42
+ remoteFamily?: string
43
+ timeout?: number
44
+ bytesWritten?: number
45
+ bytesRead?: number
46
+ }
47
+ ```
48
+
49
+ Be aware that in some cases the `.socket` property can be `null`.
@@ -0,0 +1,45 @@
1
+ # EventSource
2
+
3
+ > ⚠️ Warning: the EventSource API is experimental.
4
+
5
+ Undici exposes a WHATWG spec-compliant implementation of [EventSource](https://developer.mozilla.org/en-US/docs/Web/API/EventSource)
6
+ for [Server-Sent Events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events).
7
+
8
+ ## Instantiating EventSource
9
+
10
+ Undici exports a EventSource class. You can instantiate the EventSource as
11
+ follows:
12
+
13
+ ```mjs
14
+ import { EventSource } from 'undici'
15
+
16
+ const eventSource = new EventSource('http://localhost:3000')
17
+ eventSource.onmessage = (event) => {
18
+ console.log(event.data)
19
+ }
20
+ ```
21
+
22
+ ## Using a custom Dispatcher
23
+
24
+ undici allows you to set your own Dispatcher in the EventSource constructor.
25
+
26
+ An example which allows you to modify the request headers is:
27
+
28
+ ```mjs
29
+ import { EventSource, Agent } from 'undici'
30
+
31
+ class CustomHeaderAgent extends Agent {
32
+ dispatch (opts) {
33
+ opts.headers['x-custom-header'] = 'hello world'
34
+ return super.dispatch(...arguments)
35
+ }
36
+ }
37
+
38
+ const eventSource = new EventSource('http://localhost:3000', {
39
+ dispatcher: new CustomHeaderAgent()
40
+ })
41
+
42
+ ```
43
+
44
+ More information about the EventSource API can be found on
45
+ [MDN](https://developer.mozilla.org/en-US/docs/Web/API/EventSource).
@@ -0,0 +1,52 @@
1
+ # Fetch
2
+
3
+ Undici exposes a fetch() method starts the process of fetching a resource from the network.
4
+
5
+ Documentation and examples can be found on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/fetch).
6
+
7
+ ## FormData
8
+
9
+ This API is implemented as per the standard, you can find documentation on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/FormData).
10
+
11
+ If any parameters are passed to the FormData constructor other than `undefined`, an error will be thrown. Other parameters are ignored.
12
+
13
+ ## Response
14
+
15
+ This API is implemented as per the standard, you can find documentation on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Response)
16
+
17
+ ## Request
18
+
19
+ This API is implemented as per the standard, you can find documentation on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Request)
20
+
21
+ ## Header
22
+
23
+ This API is implemented as per the standard, you can find documentation on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Headers)
24
+
25
+ # Body Mixins
26
+
27
+ `Response` and `Request` body inherit body mixin methods. These methods include:
28
+
29
+ - [`.arrayBuffer()`](https://fetch.spec.whatwg.org/#dom-body-arraybuffer)
30
+ - [`.blob()`](https://fetch.spec.whatwg.org/#dom-body-blob)
31
+ - [`.bytes()`](https://fetch.spec.whatwg.org/#dom-body-bytes)
32
+ - [`.formData()`](https://fetch.spec.whatwg.org/#dom-body-formdata)
33
+ - [`.json()`](https://fetch.spec.whatwg.org/#dom-body-json)
34
+ - [`.text()`](https://fetch.spec.whatwg.org/#dom-body-text)
35
+
36
+ There is an ongoing discussion regarding `.formData()` and its usefulness and performance in server environments. It is recommended to use a dedicated library for parsing `multipart/form-data` bodies, such as [Busboy](https://www.npmjs.com/package/busboy) or [@fastify/busboy](https://www.npmjs.com/package/@fastify/busboy).
37
+
38
+ These libraries can be interfaced with fetch with the following example code:
39
+
40
+ ```mjs
41
+ import { Busboy } from '@fastify/busboy'
42
+ import { Readable } from 'node:stream'
43
+
44
+ const response = await fetch('...')
45
+ const busboy = new Busboy({
46
+ headers: {
47
+ 'content-type': response.headers.get('content-type')
48
+ }
49
+ })
50
+
51
+ Readable.fromWeb(response.body).pipe(busboy)
52
+ ```
@@ -0,0 +1,91 @@
1
+ # Global Installation
2
+
3
+ Undici provides an `install()` function to add all WHATWG fetch classes to `globalThis`, making them available globally without requiring imports.
4
+
5
+ ## `install()`
6
+
7
+ Install all WHATWG fetch classes globally on `globalThis`.
8
+
9
+ **Example:**
10
+
11
+ ```js
12
+ import { install } from 'undici'
13
+
14
+ // Install all WHATWG fetch classes globally
15
+ install()
16
+
17
+ // Now you can use fetch classes globally without importing
18
+ const response = await fetch('https://api.example.com/data')
19
+ const data = await response.json()
20
+
21
+ // All classes are available globally:
22
+ const headers = new Headers([['content-type', 'application/json']])
23
+ const request = new Request('https://example.com')
24
+ const formData = new FormData()
25
+ const ws = new WebSocket('wss://example.com')
26
+ const eventSource = new EventSource('https://example.com/events')
27
+ ```
28
+
29
+ ## Installed Classes
30
+
31
+ The `install()` function adds the following classes to `globalThis`:
32
+
33
+ | Class | Description |
34
+ |-------|-------------|
35
+ | `fetch` | The fetch function for making HTTP requests |
36
+ | `Headers` | HTTP headers management |
37
+ | `Response` | HTTP response representation |
38
+ | `Request` | HTTP request representation |
39
+ | `FormData` | Form data handling |
40
+ | `WebSocket` | WebSocket client |
41
+ | `CloseEvent` | WebSocket close event |
42
+ | `ErrorEvent` | WebSocket error event |
43
+ | `MessageEvent` | WebSocket message event |
44
+ | `EventSource` | Server-sent events client |
45
+
46
+ ## Use Cases
47
+
48
+ Global installation is useful for:
49
+
50
+ - **Polyfilling environments** that don't have native fetch support
51
+ - **Ensuring consistent behavior** across different Node.js versions
52
+ - **Library compatibility** when third-party libraries expect global fetch
53
+ - **Migration scenarios** where you want to replace built-in implementations
54
+ - **Testing environments** where you need predictable fetch behavior
55
+
56
+ ## Example: Polyfilling an Environment
57
+
58
+ ```js
59
+ import { install } from 'undici'
60
+
61
+ // Check if fetch is available and install if needed
62
+ if (typeof globalThis.fetch === 'undefined') {
63
+ install()
64
+ console.log('Undici fetch installed globally')
65
+ }
66
+
67
+ // Now fetch is guaranteed to be available
68
+ const response = await fetch('https://api.example.com')
69
+ ```
70
+
71
+ ## Example: Testing Environment
72
+
73
+ ```js
74
+ import { install } from 'undici'
75
+
76
+ // In test setup, ensure consistent fetch behavior
77
+ install()
78
+
79
+ // Now all tests use undici's implementations
80
+ test('fetch API test', async () => {
81
+ const response = await fetch('https://example.com')
82
+ expect(response).toBeInstanceOf(Response)
83
+ })
84
+ ```
85
+
86
+ ## Notes
87
+
88
+ - The `install()` function overwrites any existing global implementations
89
+ - Classes installed are undici's implementations, not Node.js built-ins
90
+ - This provides access to undici's latest features and performance improvements
91
+ - The global installation persists for the lifetime of the process
@@ -0,0 +1,263 @@
1
+ # Class: H2CClient
2
+
3
+ Extends: `undici.Dispatcher`
4
+
5
+ A basic H2C client.
6
+
7
+ **Example**
8
+
9
+ ```js
10
+ const { createServer } = require('node:http2')
11
+ const { once } = require('node:events')
12
+ const { H2CClient } = require('undici')
13
+
14
+ const server = createServer((req, res) => {
15
+ res.writeHead(200)
16
+ res.end('Hello, world!')
17
+ })
18
+
19
+ server.listen()
20
+ once(server, 'listening').then(() => {
21
+ const client = new H2CClient(`http://localhost:${server.address().port}/`)
22
+
23
+ const response = await client.request({ path: '/', method: 'GET' })
24
+ console.log(response.statusCode) // 200
25
+ response.body.text.then((text) => {
26
+ console.log(text) // Hello, world!
27
+ })
28
+ })
29
+ ```
30
+
31
+ ## `new H2CClient(url[, options])`
32
+
33
+ Arguments:
34
+
35
+ - **url** `URL | string` - Should only include the **protocol, hostname, and port**. It only supports `http` protocol.
36
+ - **options** `H2CClientOptions` (optional)
37
+
38
+ Returns: `H2CClient`
39
+
40
+ ### Parameter: `H2CClientOptions`
41
+
42
+ - **bodyTimeout** `number | null` (optional) - Default: `300e3` - The timeout after which a request will time out, in milliseconds. Monitors time between receiving body data. Use `0` to disable it entirely. Defaults to 300 seconds. Please note the `timeout` will be reset if you keep writing data to the socket everytime.
43
+ - **headersTimeout** `number | null` (optional) - Default: `300e3` - The amount of time, in milliseconds, the parser will wait to receive the complete HTTP headers while not sending the request. Defaults to 300 seconds.
44
+ - **keepAliveMaxTimeout** `number | null` (optional) - Default: `600e3` - The maximum allowed `keepAliveTimeout`, in milliseconds, when overridden by _keep-alive_ hints from the server. Defaults to 10 minutes.
45
+ - **keepAliveTimeout** `number | null` (optional) - Default: `4e3` - The timeout, in milliseconds, after which a socket without active requests will time out. Monitors time between activity on a connected socket. This value may be overridden by _keep-alive_ hints from the server. See [MDN: HTTP - Headers - Keep-Alive directives](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Keep-Alive#directives) for more details. Defaults to 4 seconds.
46
+ - **keepAliveTimeoutThreshold** `number | null` (optional) - Default: `2e3` - A number of milliseconds subtracted from server _keep-alive_ hints when overriding `keepAliveTimeout` to account for timing inaccuracies caused by e.g. transport latency. Defaults to 2 seconds.
47
+ - **maxHeaderSize** `number | null` (optional) - Default: `--max-http-header-size` or `16384` - The maximum length of request headers in bytes. Defaults to Node.js' --max-http-header-size or 16KiB.
48
+ - **maxResponseSize** `number | null` (optional) - Default: `-1` - The maximum length of response body in bytes. Set to `-1` to disable.
49
+ - **maxConcurrentStreams**: `number` - Default: `100`. Dictates the maximum number of concurrent streams for a single H2 session. It can be overridden by a SETTINGS remote frame.
50
+ - **pipelining** `number | null` (optional) - Default to `maxConcurrentStreams` - The amount of concurrent requests sent over a single HTTP/2 session in accordance with [RFC-7540](https://httpwg.org/specs/rfc7540.html#StreamsLayer) Stream specification. Streams can be closed up by remote server at any time.
51
+ - **pingInterval**: `number` - Default: `60e3`. The time interval in milliseconds between PING frames sent to the server. Set to `0` to disable PING frames. This is only applicable for HTTP/2 connections.
52
+ - **connect** `ConnectOptions | null` (optional) - Default: `null`.
53
+ - **strictContentLength** `Boolean` (optional) - Default: `true` - Whether to treat request content length mismatches as errors. If true, an error is thrown when the request content-length header doesn't match the length of the request body. **Security Warning:** Disabling this option can expose your application to HTTP Request Smuggling attacks, where mismatched content-length headers cause servers and proxies to interpret request boundaries differently. This can lead to cache poisoning, credential hijacking, and bypassing security controls. Only disable this in controlled environments where you fully trust the request source.
54
+ - **autoSelectFamily**: `boolean` (optional) - Default: depends on local Node version, on Node 18.13.0 and above is `false`. Enables a family autodetection algorithm that loosely implements section 5 of [RFC 8305](https://tools.ietf.org/html/rfc8305#section-5). See [here](https://nodejs.org/api/net.html#socketconnectoptions-connectlistener) for more details. This option is ignored if not supported by the current Node version.
55
+ - **autoSelectFamilyAttemptTimeout**: `number` - Default: depends on local Node version, on Node 18.13.0 and above is `250`. The amount of time in milliseconds to wait for a connection attempt to finish before trying the next address when using the `autoSelectFamily` option. See [here](https://nodejs.org/api/net.html#socketconnectoptions-connectlistener) for more details.
56
+
57
+ #### Parameter: `H2CConnectOptions`
58
+
59
+ - **socketPath** `string | null` (optional) - Default: `null` - An IPC endpoint, either Unix domain socket or Windows named pipe.
60
+ - **timeout** `number | null` (optional) - In milliseconds, Default `10e3`.
61
+ - **servername** `string | null` (optional)
62
+ - **keepAlive** `boolean | null` (optional) - Default: `true` - TCP keep-alive enabled
63
+ - **keepAliveInitialDelay** `number | null` (optional) - Default: `60000` - TCP keep-alive interval for the socket in milliseconds
64
+
65
+ ### Example - Basic Client instantiation
66
+
67
+ This will instantiate the undici H2CClient, but it will not connect to the origin until something is queued. Consider using `client.connect` to prematurely connect to the origin, or just call `client.request`.
68
+
69
+ ```js
70
+ "use strict";
71
+ import { H2CClient } from "undici";
72
+
73
+ const client = new H2CClient("http://localhost:3000");
74
+ ```
75
+
76
+ ## Instance Methods
77
+
78
+ ### `H2CClient.close([callback])`
79
+
80
+ Implements [`Dispatcher.close([callback])`](/docs/docs/api/Dispatcher.md#dispatcherclosecallback-promise).
81
+
82
+ ### `H2CClient.destroy([error, callback])`
83
+
84
+ Implements [`Dispatcher.destroy([error, callback])`](/docs/docs/api/Dispatcher.md#dispatcherdestroyerror-callback-promise).
85
+
86
+ Waits until socket is closed before invoking the callback (or returning a promise if no callback is provided).
87
+
88
+ ### `H2CClient.connect(options[, callback])`
89
+
90
+ See [`Dispatcher.connect(options[, callback])`](/docs/docs/api/Dispatcher.md#dispatcherconnectoptions-callback).
91
+
92
+ ### `H2CClient.dispatch(options, handlers)`
93
+
94
+ Implements [`Dispatcher.dispatch(options, handlers)`](/docs/docs/api/Dispatcher.md#dispatcherdispatchoptions-handler).
95
+
96
+ ### `H2CClient.pipeline(options, handler)`
97
+
98
+ See [`Dispatcher.pipeline(options, handler)`](/docs/docs/api/Dispatcher.md#dispatcherpipelineoptions-handler).
99
+
100
+ ### `H2CClient.request(options[, callback])`
101
+
102
+ See [`Dispatcher.request(options [, callback])`](/docs/docs/api/Dispatcher.md#dispatcherrequestoptions-callback).
103
+
104
+ ### `H2CClient.stream(options, factory[, callback])`
105
+
106
+ See [`Dispatcher.stream(options, factory[, callback])`](/docs/docs/api/Dispatcher.md#dispatcherstreamoptions-factory-callback).
107
+
108
+ ### `H2CClient.upgrade(options[, callback])`
109
+
110
+ See [`Dispatcher.upgrade(options[, callback])`](/docs/docs/api/Dispatcher.md#dispatcherupgradeoptions-callback).
111
+
112
+ ## Instance Properties
113
+
114
+ ### `H2CClient.closed`
115
+
116
+ - `boolean`
117
+
118
+ `true` after `H2CClient.close()` has been called.
119
+
120
+ ### `H2CClient.destroyed`
121
+
122
+ - `boolean`
123
+
124
+ `true` after `client.destroyed()` has been called or `client.close()` has been called and the client shutdown has completed.
125
+
126
+ ### `H2CClient.pipelining`
127
+
128
+ - `number`
129
+
130
+ Property to get and set the pipelining factor.
131
+
132
+ ## Instance Events
133
+
134
+ ### Event: `'connect'`
135
+
136
+ See [Dispatcher Event: `'connect'`](/docs/docs/api/Dispatcher.md#event-connect).
137
+
138
+ Parameters:
139
+
140
+ - **origin** `URL`
141
+ - **targets** `Array<Dispatcher>`
142
+
143
+ Emitted when a socket has been created and connected. The client will connect once `client.size > 0`.
144
+
145
+ #### Example - Client connect event
146
+
147
+ ```js
148
+ import { createServer } from "node:http2";
149
+ import { H2CClient } from "undici";
150
+ import { once } from "events";
151
+
152
+ const server = createServer((request, response) => {
153
+ response.end("Hello, World!");
154
+ }).listen();
155
+
156
+ await once(server, "listening");
157
+
158
+ const client = new H2CClient(`http://localhost:${server.address().port}`);
159
+
160
+ client.on("connect", (origin) => {
161
+ console.log(`Connected to ${origin}`); // should print before the request body statement
162
+ });
163
+
164
+ try {
165
+ const { body } = await client.request({
166
+ path: "/",
167
+ method: "GET",
168
+ });
169
+ body.setEncoding("utf-8");
170
+ body.on("data", console.log);
171
+ client.close();
172
+ server.close();
173
+ } catch (error) {
174
+ console.error(error);
175
+ client.close();
176
+ server.close();
177
+ }
178
+ ```
179
+
180
+ ### Event: `'disconnect'`
181
+
182
+ See [Dispatcher Event: `'disconnect'`](/docs/docs/api/Dispatcher.md#event-disconnect).
183
+
184
+ Parameters:
185
+
186
+ - **origin** `URL`
187
+ - **targets** `Array<Dispatcher>`
188
+ - **error** `Error`
189
+
190
+ Emitted when socket has disconnected. The error argument of the event is the error which caused the socket to disconnect. The client will reconnect if or once `client.size > 0`.
191
+
192
+ #### Example - Client disconnect event
193
+
194
+ ```js
195
+ import { createServer } from "node:http2";
196
+ import { H2CClient } from "undici";
197
+ import { once } from "events";
198
+
199
+ const server = createServer((request, response) => {
200
+ response.destroy();
201
+ }).listen();
202
+
203
+ await once(server, "listening");
204
+
205
+ const client = new H2CClient(`http://localhost:${server.address().port}`);
206
+
207
+ client.on("disconnect", (origin) => {
208
+ console.log(`Disconnected from ${origin}`);
209
+ });
210
+
211
+ try {
212
+ await client.request({
213
+ path: "/",
214
+ method: "GET",
215
+ });
216
+ } catch (error) {
217
+ console.error(error.message);
218
+ client.close();
219
+ server.close();
220
+ }
221
+ ```
222
+
223
+ ### Event: `'drain'`
224
+
225
+ Emitted when pipeline is no longer busy.
226
+
227
+ See [Dispatcher Event: `'drain'`](/docs/docs/api/Dispatcher.md#event-drain).
228
+
229
+ #### Example - Client drain event
230
+
231
+ ```js
232
+ import { createServer } from "node:http2";
233
+ import { H2CClient } from "undici";
234
+ import { once } from "events";
235
+
236
+ const server = createServer((request, response) => {
237
+ response.end("Hello, World!");
238
+ }).listen();
239
+
240
+ await once(server, "listening");
241
+
242
+ const client = new H2CClient(`http://localhost:${server.address().port}`);
243
+
244
+ client.on("drain", () => {
245
+ console.log("drain event");
246
+ client.close();
247
+ server.close();
248
+ });
249
+
250
+ const requests = [
251
+ client.request({ path: "/", method: "GET" }),
252
+ client.request({ path: "/", method: "GET" }),
253
+ client.request({ path: "/", method: "GET" }),
254
+ ];
255
+
256
+ await Promise.all(requests);
257
+
258
+ console.log("requests completed");
259
+ ```
260
+
261
+ ### Event: `'error'`
262
+
263
+ Invoked for users errors such as throwing in the `onError` handler.