@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,739 @@
1
+ 'use strict'
2
+
3
+ const { isArrayBuffer } = require('node:util/types')
4
+ const { webidl } = require('../webidl')
5
+ const { URLSerializer } = require('../fetch/data-url')
6
+ const { environmentSettingsObject } = require('../fetch/util')
7
+ const { staticPropertyDescriptors, states, sentCloseFrameState, sendHints, opcodes } = require('./constants')
8
+ const {
9
+ isConnecting,
10
+ isEstablished,
11
+ isClosing,
12
+ isClosed,
13
+ isValidSubprotocol,
14
+ fireEvent,
15
+ utf8Decode,
16
+ toArrayBuffer,
17
+ getURLRecord
18
+ } = require('./util')
19
+ const { establishWebSocketConnection, closeWebSocketConnection, failWebsocketConnection } = require('./connection')
20
+ const { ByteParser } = require('./receiver')
21
+ const { kEnumerableProperty } = require('../../core/util')
22
+ const { getGlobalDispatcher } = require('../../global')
23
+ const { ErrorEvent, CloseEvent, createFastMessageEvent } = require('./events')
24
+ const { SendQueue } = require('./sender')
25
+ const { WebsocketFrameSend } = require('./frame')
26
+ const { channels } = require('../../core/diagnostics')
27
+
28
+ /**
29
+ * @typedef {object} Handler
30
+ * @property {(response: any, extensions?: string[]) => void} onConnectionEstablished
31
+ * @property {(opcode: number, data: Buffer) => void} onMessage
32
+ * @property {(error: Error) => void} onParserError
33
+ * @property {() => void} onParserDrain
34
+ * @property {(chunk: Buffer) => void} onSocketData
35
+ * @property {(err: Error) => void} onSocketError
36
+ * @property {() => void} onSocketClose
37
+ * @property {(body: Buffer) => void} onPing
38
+ * @property {(body: Buffer) => void} onPong
39
+ *
40
+ * @property {number} readyState
41
+ * @property {import('stream').Duplex} socket
42
+ * @property {Set<number>} closeState
43
+ * @property {import('../fetch/index').Fetch} controller
44
+ * @property {boolean} [wasEverConnected=false]
45
+ */
46
+
47
+ // https://websockets.spec.whatwg.org/#interface-definition
48
+ class WebSocket extends EventTarget {
49
+ #events = {
50
+ open: null,
51
+ error: null,
52
+ close: null,
53
+ message: null
54
+ }
55
+
56
+ #bufferedAmount = 0
57
+ #protocol = ''
58
+ #extensions = ''
59
+
60
+ /** @type {SendQueue} */
61
+ #sendQueue
62
+
63
+ /** @type {Handler} */
64
+ #handler = {
65
+ onConnectionEstablished: (response, extensions) => this.#onConnectionEstablished(response, extensions),
66
+ onMessage: (opcode, data) => this.#onMessage(opcode, data),
67
+ onParserError: (err) => failWebsocketConnection(this.#handler, null, err.message),
68
+ onParserDrain: () => this.#onParserDrain(),
69
+ onSocketData: (chunk) => {
70
+ if (!this.#parser.write(chunk)) {
71
+ this.#handler.socket.pause()
72
+ }
73
+ },
74
+ onSocketError: (err) => {
75
+ this.#handler.readyState = states.CLOSING
76
+
77
+ if (channels.socketError.hasSubscribers) {
78
+ channels.socketError.publish(err)
79
+ }
80
+
81
+ this.#handler.socket.destroy()
82
+ },
83
+ onSocketClose: () => this.#onSocketClose(),
84
+ onPing: (body) => {
85
+ if (channels.ping.hasSubscribers) {
86
+ channels.ping.publish({
87
+ payload: body,
88
+ websocket: this
89
+ })
90
+ }
91
+ },
92
+ onPong: (body) => {
93
+ if (channels.pong.hasSubscribers) {
94
+ channels.pong.publish({
95
+ payload: body,
96
+ websocket: this
97
+ })
98
+ }
99
+ },
100
+
101
+ readyState: states.CONNECTING,
102
+ socket: null,
103
+ closeState: new Set(),
104
+ controller: null,
105
+ wasEverConnected: false
106
+ }
107
+
108
+ #url
109
+ #binaryType
110
+ /** @type {import('./receiver').ByteParser} */
111
+ #parser
112
+
113
+ /**
114
+ * @param {string} url
115
+ * @param {string|string[]} protocols
116
+ */
117
+ constructor (url, protocols = []) {
118
+ super()
119
+
120
+ webidl.util.markAsUncloneable(this)
121
+
122
+ const prefix = 'WebSocket constructor'
123
+ webidl.argumentLengthCheck(arguments, 1, prefix)
124
+
125
+ const options = webidl.converters['DOMString or sequence<DOMString> or WebSocketInit'](protocols, prefix, 'options')
126
+
127
+ url = webidl.converters.USVString(url)
128
+ protocols = options.protocols
129
+
130
+ // 1. Let baseURL be this's relevant settings object's API base URL.
131
+ const baseURL = environmentSettingsObject.settingsObject.baseUrl
132
+
133
+ // 2. Let urlRecord be the result of getting a URL record given url and baseURL.
134
+ const urlRecord = getURLRecord(url, baseURL)
135
+
136
+ // 3. If protocols is a string, set protocols to a sequence consisting
137
+ // of just that string.
138
+ if (typeof protocols === 'string') {
139
+ protocols = [protocols]
140
+ }
141
+
142
+ // 4. If any of the values in protocols occur more than once or otherwise
143
+ // fail to match the requirements for elements that comprise the value
144
+ // of `Sec-WebSocket-Protocol` fields as defined by The WebSocket
145
+ // protocol, then throw a "SyntaxError" DOMException.
146
+ if (protocols.length !== new Set(protocols.map(p => p.toLowerCase())).size) {
147
+ throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError')
148
+ }
149
+
150
+ if (protocols.length > 0 && !protocols.every(p => isValidSubprotocol(p))) {
151
+ throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError')
152
+ }
153
+
154
+ // 5. Set this's url to urlRecord.
155
+ this.#url = new URL(urlRecord.href)
156
+
157
+ // 6. Let client be this's relevant settings object.
158
+ const client = environmentSettingsObject.settingsObject
159
+
160
+ // 7. Run this step in parallel:
161
+ // 7.1. Establish a WebSocket connection given urlRecord, protocols,
162
+ // and client.
163
+ this.#handler.controller = establishWebSocketConnection(
164
+ urlRecord,
165
+ protocols,
166
+ client,
167
+ this.#handler,
168
+ options
169
+ )
170
+
171
+ // Each WebSocket object has an associated ready state, which is a
172
+ // number representing the state of the connection. Initially it must
173
+ // be CONNECTING (0).
174
+ this.#handler.readyState = WebSocket.CONNECTING
175
+
176
+ // The extensions attribute must initially return the empty string.
177
+
178
+ // The protocol attribute must initially return the empty string.
179
+
180
+ // Each WebSocket object has an associated binary type, which is a
181
+ // BinaryType. Initially it must be "blob".
182
+ this.#binaryType = 'blob'
183
+ }
184
+
185
+ /**
186
+ * @see https://websockets.spec.whatwg.org/#dom-websocket-close
187
+ * @param {number|undefined} code
188
+ * @param {string|undefined} reason
189
+ */
190
+ close (code = undefined, reason = undefined) {
191
+ webidl.brandCheck(this, WebSocket)
192
+
193
+ const prefix = 'WebSocket.close'
194
+
195
+ if (code !== undefined) {
196
+ code = webidl.converters['unsigned short'](code, prefix, 'code', webidl.attributes.Clamp)
197
+ }
198
+
199
+ if (reason !== undefined) {
200
+ reason = webidl.converters.USVString(reason)
201
+ }
202
+
203
+ // 1. If code is the special value "missing", then set code to null.
204
+ code ??= null
205
+
206
+ // 2. If reason is the special value "missing", then set reason to the empty string.
207
+ reason ??= ''
208
+
209
+ // 3. Close the WebSocket with this, code, and reason.
210
+ closeWebSocketConnection(this.#handler, code, reason, true)
211
+ }
212
+
213
+ /**
214
+ * @see https://websockets.spec.whatwg.org/#dom-websocket-send
215
+ * @param {NodeJS.TypedArray|ArrayBuffer|Blob|string} data
216
+ */
217
+ send (data) {
218
+ webidl.brandCheck(this, WebSocket)
219
+
220
+ const prefix = 'WebSocket.send'
221
+ webidl.argumentLengthCheck(arguments, 1, prefix)
222
+
223
+ data = webidl.converters.WebSocketSendData(data, prefix, 'data')
224
+
225
+ // 1. If this's ready state is CONNECTING, then throw an
226
+ // "InvalidStateError" DOMException.
227
+ if (isConnecting(this.#handler.readyState)) {
228
+ throw new DOMException('Sent before connected.', 'InvalidStateError')
229
+ }
230
+
231
+ // 2. Run the appropriate set of steps from the following list:
232
+ // https://datatracker.ietf.org/doc/html/rfc6455#section-6.1
233
+ // https://datatracker.ietf.org/doc/html/rfc6455#section-5.2
234
+
235
+ if (!isEstablished(this.#handler.readyState) || isClosing(this.#handler.readyState)) {
236
+ return
237
+ }
238
+
239
+ // If data is a string
240
+ if (typeof data === 'string') {
241
+ // If the WebSocket connection is established and the WebSocket
242
+ // closing handshake has not yet started, then the user agent
243
+ // must send a WebSocket Message comprised of the data argument
244
+ // using a text frame opcode; if the data cannot be sent, e.g.
245
+ // because it would need to be buffered but the buffer is full,
246
+ // the user agent must flag the WebSocket as full and then close
247
+ // the WebSocket connection. Any invocation of this method with a
248
+ // string argument that does not throw an exception must increase
249
+ // the bufferedAmount attribute by the number of bytes needed to
250
+ // express the argument as UTF-8.
251
+
252
+ const buffer = Buffer.from(data)
253
+
254
+ this.#bufferedAmount += buffer.byteLength
255
+ this.#sendQueue.add(buffer, () => {
256
+ this.#bufferedAmount -= buffer.byteLength
257
+ }, sendHints.text)
258
+ } else if (isArrayBuffer(data)) {
259
+ // If the WebSocket connection is established, and the WebSocket
260
+ // closing handshake has not yet started, then the user agent must
261
+ // send a WebSocket Message comprised of data using a binary frame
262
+ // opcode; if the data cannot be sent, e.g. because it would need
263
+ // to be buffered but the buffer is full, the user agent must flag
264
+ // the WebSocket as full and then close the WebSocket connection.
265
+ // The data to be sent is the data stored in the buffer described
266
+ // by the ArrayBuffer object. Any invocation of this method with an
267
+ // ArrayBuffer argument that does not throw an exception must
268
+ // increase the bufferedAmount attribute by the length of the
269
+ // ArrayBuffer in bytes.
270
+
271
+ this.#bufferedAmount += data.byteLength
272
+ this.#sendQueue.add(data, () => {
273
+ this.#bufferedAmount -= data.byteLength
274
+ }, sendHints.arrayBuffer)
275
+ } else if (ArrayBuffer.isView(data)) {
276
+ // If the WebSocket connection is established, and the WebSocket
277
+ // closing handshake has not yet started, then the user agent must
278
+ // send a WebSocket Message comprised of data using a binary frame
279
+ // opcode; if the data cannot be sent, e.g. because it would need to
280
+ // be buffered but the buffer is full, the user agent must flag the
281
+ // WebSocket as full and then close the WebSocket connection. The
282
+ // data to be sent is the data stored in the section of the buffer
283
+ // described by the ArrayBuffer object that data references. Any
284
+ // invocation of this method with this kind of argument that does
285
+ // not throw an exception must increase the bufferedAmount attribute
286
+ // by the length of data’s buffer in bytes.
287
+
288
+ this.#bufferedAmount += data.byteLength
289
+ this.#sendQueue.add(data, () => {
290
+ this.#bufferedAmount -= data.byteLength
291
+ }, sendHints.typedArray)
292
+ } else if (webidl.is.Blob(data)) {
293
+ // If the WebSocket connection is established, and the WebSocket
294
+ // closing handshake has not yet started, then the user agent must
295
+ // send a WebSocket Message comprised of data using a binary frame
296
+ // opcode; if the data cannot be sent, e.g. because it would need to
297
+ // be buffered but the buffer is full, the user agent must flag the
298
+ // WebSocket as full and then close the WebSocket connection. The data
299
+ // to be sent is the raw data represented by the Blob object. Any
300
+ // invocation of this method with a Blob argument that does not throw
301
+ // an exception must increase the bufferedAmount attribute by the size
302
+ // of the Blob object’s raw data, in bytes.
303
+
304
+ this.#bufferedAmount += data.size
305
+ this.#sendQueue.add(data, () => {
306
+ this.#bufferedAmount -= data.size
307
+ }, sendHints.blob)
308
+ }
309
+ }
310
+
311
+ get readyState () {
312
+ webidl.brandCheck(this, WebSocket)
313
+
314
+ // The readyState getter steps are to return this's ready state.
315
+ return this.#handler.readyState
316
+ }
317
+
318
+ get bufferedAmount () {
319
+ webidl.brandCheck(this, WebSocket)
320
+
321
+ return this.#bufferedAmount
322
+ }
323
+
324
+ get url () {
325
+ webidl.brandCheck(this, WebSocket)
326
+
327
+ // The url getter steps are to return this's url, serialized.
328
+ return URLSerializer(this.#url)
329
+ }
330
+
331
+ get extensions () {
332
+ webidl.brandCheck(this, WebSocket)
333
+
334
+ return this.#extensions
335
+ }
336
+
337
+ get protocol () {
338
+ webidl.brandCheck(this, WebSocket)
339
+
340
+ return this.#protocol
341
+ }
342
+
343
+ get onopen () {
344
+ webidl.brandCheck(this, WebSocket)
345
+
346
+ return this.#events.open
347
+ }
348
+
349
+ set onopen (fn) {
350
+ webidl.brandCheck(this, WebSocket)
351
+
352
+ if (this.#events.open) {
353
+ this.removeEventListener('open', this.#events.open)
354
+ }
355
+
356
+ const listener = webidl.converters.EventHandlerNonNull(fn)
357
+
358
+ if (listener !== null) {
359
+ this.addEventListener('open', listener)
360
+ this.#events.open = fn
361
+ } else {
362
+ this.#events.open = null
363
+ }
364
+ }
365
+
366
+ get onerror () {
367
+ webidl.brandCheck(this, WebSocket)
368
+
369
+ return this.#events.error
370
+ }
371
+
372
+ set onerror (fn) {
373
+ webidl.brandCheck(this, WebSocket)
374
+
375
+ if (this.#events.error) {
376
+ this.removeEventListener('error', this.#events.error)
377
+ }
378
+
379
+ const listener = webidl.converters.EventHandlerNonNull(fn)
380
+
381
+ if (listener !== null) {
382
+ this.addEventListener('error', listener)
383
+ this.#events.error = fn
384
+ } else {
385
+ this.#events.error = null
386
+ }
387
+ }
388
+
389
+ get onclose () {
390
+ webidl.brandCheck(this, WebSocket)
391
+
392
+ return this.#events.close
393
+ }
394
+
395
+ set onclose (fn) {
396
+ webidl.brandCheck(this, WebSocket)
397
+
398
+ if (this.#events.close) {
399
+ this.removeEventListener('close', this.#events.close)
400
+ }
401
+
402
+ const listener = webidl.converters.EventHandlerNonNull(fn)
403
+
404
+ if (listener !== null) {
405
+ this.addEventListener('close', listener)
406
+ this.#events.close = fn
407
+ } else {
408
+ this.#events.close = null
409
+ }
410
+ }
411
+
412
+ get onmessage () {
413
+ webidl.brandCheck(this, WebSocket)
414
+
415
+ return this.#events.message
416
+ }
417
+
418
+ set onmessage (fn) {
419
+ webidl.brandCheck(this, WebSocket)
420
+
421
+ if (this.#events.message) {
422
+ this.removeEventListener('message', this.#events.message)
423
+ }
424
+
425
+ const listener = webidl.converters.EventHandlerNonNull(fn)
426
+
427
+ if (listener !== null) {
428
+ this.addEventListener('message', listener)
429
+ this.#events.message = fn
430
+ } else {
431
+ this.#events.message = null
432
+ }
433
+ }
434
+
435
+ get binaryType () {
436
+ webidl.brandCheck(this, WebSocket)
437
+
438
+ return this.#binaryType
439
+ }
440
+
441
+ set binaryType (type) {
442
+ webidl.brandCheck(this, WebSocket)
443
+
444
+ if (type !== 'blob' && type !== 'arraybuffer') {
445
+ this.#binaryType = 'blob'
446
+ } else {
447
+ this.#binaryType = type
448
+ }
449
+ }
450
+
451
+ /**
452
+ * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol
453
+ */
454
+ #onConnectionEstablished (response, parsedExtensions) {
455
+ // processResponse is called when the "response's header list has been received and initialized."
456
+ // once this happens, the connection is open
457
+ this.#handler.socket = response.socket
458
+
459
+ const parser = new ByteParser(this.#handler, parsedExtensions)
460
+ parser.on('drain', () => this.#handler.onParserDrain())
461
+ parser.on('error', (err) => this.#handler.onParserError(err))
462
+
463
+ this.#parser = parser
464
+ this.#sendQueue = new SendQueue(response.socket)
465
+
466
+ // 1. Change the ready state to OPEN (1).
467
+ this.#handler.readyState = states.OPEN
468
+
469
+ // 2. Change the extensions attribute’s value to the extensions in use, if
470
+ // it is not the null value.
471
+ // https://datatracker.ietf.org/doc/html/rfc6455#section-9.1
472
+ const extensions = response.headersList.get('sec-websocket-extensions')
473
+
474
+ if (extensions !== null) {
475
+ this.#extensions = extensions
476
+ }
477
+
478
+ // 3. Change the protocol attribute’s value to the subprotocol in use, if
479
+ // it is not the null value.
480
+ // https://datatracker.ietf.org/doc/html/rfc6455#section-1.9
481
+ const protocol = response.headersList.get('sec-websocket-protocol')
482
+
483
+ if (protocol !== null) {
484
+ this.#protocol = protocol
485
+ }
486
+
487
+ // 4. Fire an event named open at the WebSocket object.
488
+ fireEvent('open', this)
489
+
490
+ if (channels.open.hasSubscribers) {
491
+ // Convert headers to a plain object for the event
492
+ const headers = response.headersList.entries
493
+ channels.open.publish({
494
+ address: response.socket.address(),
495
+ protocol: this.#protocol,
496
+ extensions: this.#extensions,
497
+ websocket: this,
498
+ handshakeResponse: {
499
+ status: response.status,
500
+ statusText: response.statusText,
501
+ headers
502
+ }
503
+ })
504
+ }
505
+ }
506
+
507
+ #onMessage (type, data) {
508
+ // 1. If ready state is not OPEN (1), then return.
509
+ if (this.#handler.readyState !== states.OPEN) {
510
+ return
511
+ }
512
+
513
+ // 2. Let dataForEvent be determined by switching on type and binary type:
514
+ let dataForEvent
515
+
516
+ if (type === opcodes.TEXT) {
517
+ // -> type indicates that the data is Text
518
+ // a new DOMString containing data
519
+ try {
520
+ dataForEvent = utf8Decode(data)
521
+ } catch {
522
+ failWebsocketConnection(this.#handler, 1007, 'Received invalid UTF-8 in text frame.')
523
+ return
524
+ }
525
+ } else if (type === opcodes.BINARY) {
526
+ if (this.#binaryType === 'blob') {
527
+ // -> type indicates that the data is Binary and binary type is "blob"
528
+ // a new Blob object, created in the relevant Realm of the WebSocket
529
+ // object, that represents data as its raw data
530
+ dataForEvent = new Blob([data])
531
+ } else {
532
+ // -> type indicates that the data is Binary and binary type is "arraybuffer"
533
+ // a new ArrayBuffer object, created in the relevant Realm of the
534
+ // WebSocket object, whose contents are data
535
+ dataForEvent = toArrayBuffer(data)
536
+ }
537
+ }
538
+
539
+ // 3. Fire an event named message at the WebSocket object, using MessageEvent,
540
+ // with the origin attribute initialized to the serialization of the WebSocket
541
+ // object’s url's origin, and the data attribute initialized to dataForEvent.
542
+ fireEvent('message', this, createFastMessageEvent, {
543
+ origin: this.#url.origin,
544
+ data: dataForEvent
545
+ })
546
+ }
547
+
548
+ #onParserDrain () {
549
+ this.#handler.socket.resume()
550
+ }
551
+
552
+ /**
553
+ * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol
554
+ * @see https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.4
555
+ */
556
+ #onSocketClose () {
557
+ // If the TCP connection was closed after the
558
+ // WebSocket closing handshake was completed, the WebSocket connection
559
+ // is said to have been closed _cleanly_.
560
+ const wasClean =
561
+ this.#handler.closeState.has(sentCloseFrameState.SENT) &&
562
+ this.#handler.closeState.has(sentCloseFrameState.RECEIVED)
563
+
564
+ let code = 1005
565
+ let reason = ''
566
+
567
+ const result = this.#parser?.closingInfo
568
+
569
+ if (result && !result.error) {
570
+ code = result.code ?? 1005
571
+ reason = result.reason
572
+ }
573
+
574
+ // 1. Change the ready state to CLOSED (3).
575
+ this.#handler.readyState = states.CLOSED
576
+
577
+ // 2. If the user agent was required to fail the WebSocket
578
+ // connection, or if the WebSocket connection was closed
579
+ // after being flagged as full, fire an event named error
580
+ // at the WebSocket object.
581
+ if (!this.#handler.closeState.has(sentCloseFrameState.RECEIVED)) {
582
+ // If _The WebSocket
583
+ // Connection is Closed_ and no Close control frame was received by the
584
+ // endpoint (such as could occur if the underlying transport connection
585
+ // is lost), _The WebSocket Connection Close Code_ is considered to be
586
+ // 1006.
587
+ code = 1006
588
+
589
+ fireEvent('error', this, (type, init) => new ErrorEvent(type, init), {
590
+ error: new TypeError(reason)
591
+ })
592
+ }
593
+
594
+ // 3. Fire an event named close at the WebSocket object,
595
+ // using CloseEvent, with the wasClean attribute
596
+ // initialized to true if the connection closed cleanly
597
+ // and false otherwise, the code attribute initialized to
598
+ // the WebSocket connection close code, and the reason
599
+ // attribute initialized to the result of applying UTF-8
600
+ // decode without BOM to the WebSocket connection close
601
+ // reason.
602
+ // TODO: process.nextTick
603
+ fireEvent('close', this, (type, init) => new CloseEvent(type, init), {
604
+ wasClean, code, reason
605
+ })
606
+
607
+ if (channels.close.hasSubscribers) {
608
+ channels.close.publish({
609
+ websocket: this,
610
+ code,
611
+ reason
612
+ })
613
+ }
614
+ }
615
+
616
+ /**
617
+ * @param {WebSocket} ws
618
+ * @param {Buffer|undefined} buffer
619
+ */
620
+ static ping (ws, buffer) {
621
+ if (Buffer.isBuffer(buffer)) {
622
+ if (buffer.length > 125) {
623
+ throw new TypeError('A PING frame cannot have a body larger than 125 bytes.')
624
+ }
625
+ } else if (buffer !== undefined) {
626
+ throw new TypeError('Expected buffer payload')
627
+ }
628
+
629
+ // An endpoint MAY send a Ping frame any time after the connection is
630
+ // established and before the connection is closed.
631
+ const readyState = ws.#handler.readyState
632
+
633
+ if (isEstablished(readyState) && !isClosing(readyState) && !isClosed(readyState)) {
634
+ const frame = new WebsocketFrameSend(buffer)
635
+ ws.#handler.socket.write(frame.createFrame(opcodes.PING))
636
+ }
637
+ }
638
+ }
639
+
640
+ const { ping } = WebSocket
641
+ Reflect.deleteProperty(WebSocket, 'ping')
642
+
643
+ // https://websockets.spec.whatwg.org/#dom-websocket-connecting
644
+ WebSocket.CONNECTING = WebSocket.prototype.CONNECTING = states.CONNECTING
645
+ // https://websockets.spec.whatwg.org/#dom-websocket-open
646
+ WebSocket.OPEN = WebSocket.prototype.OPEN = states.OPEN
647
+ // https://websockets.spec.whatwg.org/#dom-websocket-closing
648
+ WebSocket.CLOSING = WebSocket.prototype.CLOSING = states.CLOSING
649
+ // https://websockets.spec.whatwg.org/#dom-websocket-closed
650
+ WebSocket.CLOSED = WebSocket.prototype.CLOSED = states.CLOSED
651
+
652
+ Object.defineProperties(WebSocket.prototype, {
653
+ CONNECTING: staticPropertyDescriptors,
654
+ OPEN: staticPropertyDescriptors,
655
+ CLOSING: staticPropertyDescriptors,
656
+ CLOSED: staticPropertyDescriptors,
657
+ url: kEnumerableProperty,
658
+ readyState: kEnumerableProperty,
659
+ bufferedAmount: kEnumerableProperty,
660
+ onopen: kEnumerableProperty,
661
+ onerror: kEnumerableProperty,
662
+ onclose: kEnumerableProperty,
663
+ close: kEnumerableProperty,
664
+ onmessage: kEnumerableProperty,
665
+ binaryType: kEnumerableProperty,
666
+ send: kEnumerableProperty,
667
+ extensions: kEnumerableProperty,
668
+ protocol: kEnumerableProperty,
669
+ [Symbol.toStringTag]: {
670
+ value: 'WebSocket',
671
+ writable: false,
672
+ enumerable: false,
673
+ configurable: true
674
+ }
675
+ })
676
+
677
+ Object.defineProperties(WebSocket, {
678
+ CONNECTING: staticPropertyDescriptors,
679
+ OPEN: staticPropertyDescriptors,
680
+ CLOSING: staticPropertyDescriptors,
681
+ CLOSED: staticPropertyDescriptors
682
+ })
683
+
684
+ webidl.converters['sequence<DOMString>'] = webidl.sequenceConverter(
685
+ webidl.converters.DOMString
686
+ )
687
+
688
+ webidl.converters['DOMString or sequence<DOMString>'] = function (V, prefix, argument) {
689
+ if (webidl.util.Type(V) === webidl.util.Types.OBJECT && Symbol.iterator in V) {
690
+ return webidl.converters['sequence<DOMString>'](V)
691
+ }
692
+
693
+ return webidl.converters.DOMString(V, prefix, argument)
694
+ }
695
+
696
+ // This implements the proposal made in https://github.com/whatwg/websockets/issues/42
697
+ webidl.converters.WebSocketInit = webidl.dictionaryConverter([
698
+ {
699
+ key: 'protocols',
700
+ converter: webidl.converters['DOMString or sequence<DOMString>'],
701
+ defaultValue: () => []
702
+ },
703
+ {
704
+ key: 'dispatcher',
705
+ converter: webidl.converters.any,
706
+ defaultValue: () => getGlobalDispatcher()
707
+ },
708
+ {
709
+ key: 'headers',
710
+ converter: webidl.nullableConverter(webidl.converters.HeadersInit)
711
+ }
712
+ ])
713
+
714
+ webidl.converters['DOMString or sequence<DOMString> or WebSocketInit'] = function (V) {
715
+ if (webidl.util.Type(V) === webidl.util.Types.OBJECT && !(Symbol.iterator in V)) {
716
+ return webidl.converters.WebSocketInit(V)
717
+ }
718
+
719
+ return { protocols: webidl.converters['DOMString or sequence<DOMString>'](V) }
720
+ }
721
+
722
+ webidl.converters.WebSocketSendData = function (V) {
723
+ if (webidl.util.Type(V) === webidl.util.Types.OBJECT) {
724
+ if (webidl.is.Blob(V)) {
725
+ return V
726
+ }
727
+
728
+ if (webidl.is.BufferSource(V)) {
729
+ return V
730
+ }
731
+ }
732
+
733
+ return webidl.converters.USVString(V)
734
+ }
735
+
736
+ module.exports = {
737
+ WebSocket,
738
+ ping
739
+ }