@hiroosy/baileys-lite 0.0.3 → 0.3.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 (116) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +660 -12
  3. package/WAProto/index.js +2 -2558
  4. package/engine-requirements.js +3 -4
  5. package/package.json +8 -3
  6. package/src/binary/wa-binary.js +3 -25
  7. package/src/constants.js +7 -15
  8. package/src/defaults.js +2 -5
  9. package/src/foundation/ai-rich.js +530 -0
  10. package/src/foundation/audio-duration.js +43 -103
  11. package/src/foundation/audio-samples.js +19 -37
  12. package/src/foundation/boom.js +0 -7
  13. package/src/foundation/cache.js +4 -26
  14. package/src/foundation/concurrency.js +1 -19
  15. package/src/foundation/curve25519.js +7 -39
  16. package/src/foundation/link-preview.js +15 -57
  17. package/src/foundation/logger.js +0 -11
  18. package/src/foundation/long.js +4 -14
  19. package/src/foundation/protobuf-minimal.js +21 -53
  20. package/src/foundation/qrcode-terminal.js +273 -0
  21. package/src/foundation/sql-database.js +702 -0
  22. package/src/foundation/wa-crypto.js +2 -31
  23. package/src/foundation/zip.js +25 -41
  24. package/src/index.js +8 -18
  25. package/src/signal/libsignal.js +23 -78
  26. package/src/signal/signal-group.js +0 -35
  27. package/src/signal/signal-repository.js +10 -29
  28. package/src/socket/business-communities.js +12 -31
  29. package/src/socket/chats.js +5 -8
  30. package/src/socket/groups-newsletter.js +18 -17
  31. package/src/socket/messages-recv.js +81 -127
  32. package/src/socket/messages-send.js +372 -139
  33. package/src/socket/socket-core.js +227 -157
  34. package/src/socket/usync.js +2 -6
  35. package/src/socket-client/native-websocket.js +344 -0
  36. package/src/socket-client/websocket-client.js +84 -38
  37. package/src/utils/auth-state-core.js +14 -56
  38. package/src/utils/auth-state-storage.js +7 -42
  39. package/src/utils/chat-sync.js +4 -26
  40. package/src/utils/media.js +15 -71
  41. package/src/utils/message-compose.js +208 -85
  42. package/src/utils/message-processing.js +10 -65
  43. package/src/utils/username.js +19 -0
  44. package/src/utils/wa-protocol-core.js +71 -127
  45. package/src/vendor/jpeg-js/decoder.js +75 -136
  46. package/src/vendor/jpeg-js/encoder.js +179 -264
  47. package/src/vendor/pngjs/bitmapper.js +5 -27
  48. package/src/vendor/pngjs/bitpacker.js +4 -12
  49. package/src/vendor/pngjs/constants.js +3 -11
  50. package/src/vendor/pngjs/crc.js +0 -6
  51. package/src/vendor/pngjs/filter-pack.js +1 -7
  52. package/src/vendor/pngjs/filter-parse-sync.js +0 -6
  53. package/src/vendor/pngjs/filter-parse.js +1 -11
  54. package/src/vendor/pngjs/format-normaliser.js +5 -11
  55. package/src/vendor/pngjs/interlace.js +7 -24
  56. package/src/vendor/pngjs/packer-sync.js +0 -11
  57. package/src/vendor/pngjs/packer.js +7 -15
  58. package/src/vendor/pngjs/paeth-predictor.js +0 -6
  59. package/src/vendor/pngjs/parser-sync.js +0 -8
  60. package/src/vendor/pngjs/parser.js +5 -29
  61. package/src/vendor/pngjs/png-sync.js +0 -7
  62. package/src/vendor/pngjs/sync-inflate.js +7 -16
  63. package/src/vendor/pngjs/sync-reader.js +4 -11
  64. package/src/voip/WaVoipCoordinator.js +158 -0
  65. package/src/voip/app-data/WaAppDataStream.js +193 -0
  66. package/src/voip/app-data/protocol.js +172 -0
  67. package/src/voip/bytes.js +63 -0
  68. package/src/voip/call/WaCallManager.js +442 -0
  69. package/src/voip/call/WaCallMediaSession.js +1705 -0
  70. package/src/voip/call/call-state.js +203 -0
  71. package/src/voip/crypto/encryption.js +13 -0
  72. package/src/voip/crypto/primitives.js +21 -0
  73. package/src/voip/crypto/rtcp.js +66 -0
  74. package/src/voip/crypto/srtp.js +180 -0
  75. package/src/voip/crypto/ssrc.js +15 -0
  76. package/src/voip/index.js +628 -0
  77. package/src/voip/media/WaAudioEngine.js +486 -0
  78. package/src/voip/media/WaVideoEngine.js +275 -0
  79. package/src/voip/media/audio-codec.js +0 -0
  80. package/src/voip/media/audio-reorder.js +107 -0
  81. package/src/voip/media/h264.js +246 -0
  82. package/src/voip/media/mlow-codec.js +465 -0
  83. package/src/voip/media/rtcp.js +68 -0
  84. package/src/voip/media/rtp.js +242 -0
  85. package/src/voip/protobuf.js +30 -0
  86. package/src/voip/relay/WaManualRelay.js +609 -0
  87. package/src/voip/relay/datachannel/pre-negotiated.js +25 -0
  88. package/src/voip/relay/dtls/aead.js +46 -0
  89. package/src/voip/relay/dtls/cert-builder.js +102 -0
  90. package/src/voip/relay/dtls/der.js +98 -0
  91. package/src/voip/relay/dtls/ecdhe.js +37 -0
  92. package/src/voip/relay/dtls/handshake-framing.js +100 -0
  93. package/src/voip/relay/dtls/handshake-messages.js +158 -0
  94. package/src/voip/relay/dtls/handshake.js +582 -0
  95. package/src/voip/relay/dtls/prf.js +39 -0
  96. package/src/voip/relay/dtls/record.js +56 -0
  97. package/src/voip/relay/relay-ack.js +141 -0
  98. package/src/voip/relay/sctp/association.js +434 -0
  99. package/src/voip/relay/sctp/crc32c.js +21 -0
  100. package/src/voip/relay/sctp/wire.js +226 -0
  101. package/src/voip/relay/stun.js +463 -0
  102. package/src/voip/shim/baileys-resolve.js +7 -0
  103. package/src/voip/shim/core.js +66 -0
  104. package/src/voip/shim/crypto.js +6 -0
  105. package/src/voip/shim/proto.js +10 -0
  106. package/src/voip/shim/protocol.js +130 -0
  107. package/src/voip/shim/transport.js +82 -0
  108. package/src/voip/shim/util.js +207 -0
  109. package/src/voip/signaling/bridge.js +102 -0
  110. package/src/voip/signaling/screen-share.js +60 -0
  111. package/src/voip/signaling/signaling.js +491 -0
  112. package/src/voip/types.js +69 -0
  113. package/src/voip/voip-deps.js +243 -0
  114. package/src/voip/voipClient.js +314 -0
  115. package/src/wam/wam-constants.js +0 -1
  116. package/src/wam/wam.js +2 -7
@@ -1,7 +1,3 @@
1
- /**
2
- * USync (user info sync) query builder + protocols.
3
- * Combines what used to be 11 files under WAUSync/.
4
- */
5
1
  import { assertNodeErrorFree, getBinaryNodeChild, getBinaryNodeChildren, getBinaryNodeChildString } from '../binary/wa-binary.js'
6
2
 
7
3
  export class USyncUser {
@@ -70,7 +66,7 @@ export class USyncDeviceProtocol {
70
66
  return { tag: 'devices', attrs: { version: '2' } }
71
67
  }
72
68
  getUserElement() {
73
- // TODO: device phashing, ts, expectedTs; currently returns null (matches upstream)
69
+
74
70
  return null
75
71
  }
76
72
  parser(node) {
@@ -235,7 +231,7 @@ export class USyncQuery {
235
231
  parseUSyncQueryResult(result) {
236
232
  if (result?.attrs.type !== 'result') return
237
233
  const protocolMap = Object.fromEntries(this.protocols.map(protocol => [protocol.name, protocol.parser]))
238
- const queryResult = { list: [], sideList: [] } // TODO: implement errors etc.
234
+ const queryResult = { list: [], sideList: [] }
239
235
  const usyncNode = getBinaryNodeChild(result, 'usync')
240
236
  const listNode = usyncNode ? getBinaryNodeChild(usyncNode, 'list') : undefined
241
237
  if (listNode?.content && Array.isArray(listNode.content)) {
@@ -0,0 +1,344 @@
1
+ import { createHash, randomBytes } from 'node:crypto'
2
+ import { isIP, connect as connectTcp } from 'node:net'
3
+ import { connect as connectTls } from 'node:tls'
4
+
5
+ const GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
6
+ const MAX_MESSAGE_BYTES = 64 * 1024 * 1024
7
+ const MAX_HANDSHAKE_BYTES = 16 * 1024
8
+ const CLOSE_TIMEOUT_MS = 5000
9
+ const TOKEN = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/
10
+ const FORBIDDEN_HEADERS = new Set([
11
+ 'host', 'upgrade', 'connection', 'content-length', 'transfer-encoding',
12
+ 'sec-websocket-key', 'sec-websocket-version', 'sec-websocket-accept', 'sec-websocket-extensions', 'sec-websocket-protocol'
13
+ ])
14
+ const OPCODE_CONTINUATION = 0x0
15
+ const OPCODE_TEXT = 0x1
16
+ const OPCODE_BINARY = 0x2
17
+ const OPCODE_CLOSE = 0x8
18
+ const OPCODE_PING = 0x9
19
+ const OPCODE_PONG = 0xa
20
+ const TEXT_DECODER = new TextDecoder('utf-8', { fatal: true })
21
+
22
+ const isValidCloseCode = code => (code >= 1000 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006) || (code >= 3000 && code <= 4999)
23
+
24
+ const toArrayBuffer = buf => buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength)
25
+
26
+ const encodeFrame = (opcode, payload) => {
27
+ const length = payload.length
28
+ let header
29
+ if (length < 126) {
30
+ header = Buffer.alloc(2)
31
+ header[1] = 0x80 | length
32
+ } else if (length <= 0xffff) {
33
+ header = Buffer.alloc(4)
34
+ header[1] = 0x80 | 126
35
+ header.writeUInt16BE(length, 2)
36
+ } else {
37
+ header = Buffer.alloc(10)
38
+ header[1] = 0x80 | 127
39
+ header.writeBigUInt64BE(BigInt(length), 2)
40
+ }
41
+ header[0] = 0x80 | opcode
42
+ const mask = randomBytes(4)
43
+ const masked = Buffer.allocUnsafe(length)
44
+ for (let i = 0; i < length; i++) masked[i] = payload[i] ^ mask[i & 3]
45
+ return Buffer.concat([header, mask, masked])
46
+ }
47
+
48
+ export class NativeWebSocket {
49
+ static CONNECTING = 0
50
+ static OPEN = 1
51
+ static CLOSING = 2
52
+ static CLOSED = 3
53
+
54
+ #readyState = NativeWebSocket.CONNECTING
55
+ #socket = null
56
+ #buffer = Buffer.alloc(0)
57
+ #handshakeDone = false
58
+ #expectedAccept = ''
59
+ #fragments = null
60
+ #fragmentBytes = 0
61
+ #fragmentOpcode = 0
62
+ #closeSent = false
63
+ #closeTimer = null
64
+ #remoteClose = null
65
+ #failCode = null
66
+
67
+ constructor(url, options = {}) {
68
+ const target = new URL(url)
69
+ if (target.protocol !== 'ws:' && target.protocol !== 'wss:') throw new SyntaxError(`Unsupported WebSocket protocol: ${target.protocol}`)
70
+ this.url = target.href
71
+ this.binaryType = 'arraybuffer'
72
+ this.onopen = null
73
+ this.onmessage = null
74
+ this.onerror = null
75
+ this.onclose = null
76
+ this.#connect(target, options.headers ?? {})
77
+ }
78
+
79
+ get readyState() {
80
+ return this.#readyState
81
+ }
82
+
83
+ send(data) {
84
+ if (this.#readyState === NativeWebSocket.CONNECTING) throw new Error('InvalidStateError: Still in CONNECTING state')
85
+ if (this.#readyState !== NativeWebSocket.OPEN) return
86
+ const isText = typeof data === 'string'
87
+ let payload
88
+ if (isText) payload = Buffer.from(data, 'utf8')
89
+ else if (ArrayBuffer.isView(data)) payload = Buffer.from(data.buffer, data.byteOffset, data.byteLength)
90
+ else payload = Buffer.from(data)
91
+ this.#socket.write(encodeFrame(isText ? OPCODE_TEXT : OPCODE_BINARY, payload))
92
+ }
93
+
94
+ close(code, reason = '') {
95
+ if (this.#readyState === NativeWebSocket.CLOSING || this.#readyState === NativeWebSocket.CLOSED) return
96
+ if (code !== undefined && code !== 1000 && !(code >= 3000 && code <= 4999)) throw new TypeError(`InvalidAccessError: invalid close code ${code}`)
97
+ if (Buffer.byteLength(reason) > 123) throw new SyntaxError('Reason must be less than 123 bytes')
98
+ if (this.#readyState === NativeWebSocket.CONNECTING) {
99
+ this.#fire('onerror', { type: 'error', error: new Error('WebSocket was closed before the connection was established'), message: 'WebSocket was closed before the connection was established' })
100
+ this.#readyState = NativeWebSocket.CLOSING
101
+ this.#socket.destroy()
102
+ return
103
+ }
104
+ this.#readyState = NativeWebSocket.CLOSING
105
+ this.#sendClose(code, reason)
106
+ this.#scheduleDestroy()
107
+ }
108
+
109
+ #connect(target, headers) {
110
+ const secure = target.protocol === 'wss:'
111
+ const host = target.hostname.replace(/^\[(.*)\]$/, '$1')
112
+ const port = Number(target.port) || (secure ? 443 : 80)
113
+ const key = randomBytes(16).toString('base64')
114
+ this.#expectedAccept = createHash('sha1').update(key + GUID).digest('base64')
115
+ const lines = [
116
+ `GET ${target.pathname || '/'}${target.search} HTTP/1.1`,
117
+ `Host: ${target.port ? `${target.hostname}:${target.port}` : target.hostname}`,
118
+ 'Upgrade: websocket',
119
+ 'Connection: Upgrade',
120
+ `Sec-WebSocket-Key: ${key}`,
121
+ 'Sec-WebSocket-Version: 13'
122
+ ]
123
+ for (const [name, value] of Object.entries(headers)) {
124
+ if (value === undefined || value === null) continue
125
+ if (!TOKEN.test(name)) throw new TypeError(`Invalid header name: ${name}`)
126
+ const text = String(value)
127
+ if (/[\r\n\0]/.test(text)) throw new TypeError(`Invalid header value for ${name}`)
128
+ if (FORBIDDEN_HEADERS.has(name.toLowerCase())) continue
129
+ lines.push(`${name}: ${text}`)
130
+ }
131
+ const socket = secure
132
+ ? connectTls({ host, port, servername: isIP(host) ? undefined : host, ALPNProtocols: ['http/1.1'] })
133
+ : connectTcp({ host, port })
134
+ socket.setNoDelay(true)
135
+ socket.on('data', chunk => this.#onData(chunk))
136
+ socket.on('error', error => this.#onSocketError(error))
137
+ socket.on('close', () => this.#onSocketClose())
138
+ this.#socket = socket
139
+ socket.write(`${lines.join('\r\n')}\r\n\r\n`)
140
+ }
141
+
142
+ #onData(chunk) {
143
+ this.#buffer = this.#buffer.length ? Buffer.concat([this.#buffer, chunk]) : chunk
144
+ if (!this.#handshakeDone) {
145
+ const end = this.#buffer.indexOf('\r\n\r\n')
146
+ if (end === -1) {
147
+ if (this.#buffer.length > MAX_HANDSHAKE_BYTES) this.#abortHandshake(new Error('Handshake response too large'))
148
+ return
149
+ }
150
+ const head = this.#buffer.subarray(0, end).toString('latin1')
151
+ this.#buffer = this.#buffer.subarray(end + 4)
152
+ if (!this.#completeHandshake(head)) return
153
+ }
154
+ this.#parseFrames()
155
+ }
156
+
157
+ #completeHandshake(head) {
158
+ const [statusLine, ...headerLines] = head.split('\r\n')
159
+ const status = /^HTTP\/1\.[01] (\d{3})/.exec(statusLine)?.[1]
160
+ const reject = message => {
161
+ this.#abortHandshake(new Error(message))
162
+ return false
163
+ }
164
+ if (status !== '101') return reject(`Unexpected server response: ${status ?? 'invalid'}`)
165
+ const headers = new Map()
166
+ for (const line of headerLines) {
167
+ const i = line.indexOf(':')
168
+ if (i > 0) headers.set(line.slice(0, i).trim().toLowerCase(), line.slice(i + 1).trim())
169
+ }
170
+ const connection = (headers.get('connection') ?? '').toLowerCase().split(',').map(token => token.trim())
171
+ if (headers.get('upgrade')?.toLowerCase() !== 'websocket') return reject('Server did not set Upgrade header to "websocket".')
172
+ if (!connection.includes('upgrade')) return reject('Server did not set Connection header to "upgrade".')
173
+ if (headers.get('sec-websocket-accept') !== this.#expectedAccept) return reject('Incorrect hash received in Sec-WebSocket-Accept header.')
174
+ if (headers.get('sec-websocket-extensions')) return reject('Server negotiated an extension that was not requested.')
175
+ if (headers.get('sec-websocket-protocol')) return reject('Server negotiated a subprotocol that was not requested.')
176
+ this.#handshakeDone = true
177
+ this.#readyState = NativeWebSocket.OPEN
178
+ this.#fire('onopen', { type: 'open' })
179
+ return true
180
+ }
181
+
182
+ #abortHandshake(error) {
183
+ this.#fire('onerror', { type: 'error', error, message: error.message })
184
+ this.#socket.destroy()
185
+ }
186
+
187
+ #parseFrames() {
188
+ while (this.#buffer.length >= 2 && this.#readyState !== NativeWebSocket.CLOSED) {
189
+ const first = this.#buffer[0]
190
+ const second = this.#buffer[1]
191
+ const fin = (first & 0x80) !== 0
192
+ const opcode = first & 0x0f
193
+ const masked = (second & 0x80) !== 0
194
+ let length = second & 0x7f
195
+ let offset = 2
196
+ if (length === 126) {
197
+ if (this.#buffer.length < 4) return
198
+ length = this.#buffer.readUInt16BE(2)
199
+ offset = 4
200
+ } else if (length === 127) {
201
+ if (this.#buffer.length < 10) return
202
+ const big = this.#buffer.readBigUInt64BE(2)
203
+ if (big > BigInt(MAX_MESSAGE_BYTES)) return this.#failConnection(1009, 'Payload size exceeds maximum allowed size')
204
+ length = Number(big)
205
+ offset = 10
206
+ }
207
+ if (first & 0x70) return this.#failConnection(1002, 'RSV1, RSV2, RSV3 must be clear')
208
+ if (masked) return this.#failConnection(1002, 'Server frames must not be masked')
209
+ if (opcode >= 0x8 && (!fin || length > 125)) return this.#failConnection(1002, 'Invalid control frame')
210
+ if (length > MAX_MESSAGE_BYTES) return this.#failConnection(1009, 'Payload size exceeds maximum allowed size')
211
+ if (this.#buffer.length < offset + length) return
212
+ const payload = Buffer.from(this.#buffer.subarray(offset, offset + length))
213
+ this.#buffer = this.#buffer.subarray(offset + length)
214
+ this.#handleFrame(fin, opcode, payload)
215
+ }
216
+ }
217
+
218
+ #handleFrame(fin, opcode, payload) {
219
+ if (opcode === OPCODE_CONTINUATION && !this.#fragments) return this.#failConnection(1002, 'Unexpected continuation frame')
220
+ if ((opcode === OPCODE_TEXT || opcode === OPCODE_BINARY) && this.#fragments) return this.#failConnection(1002, 'Expected continuation frame')
221
+ switch (opcode) {
222
+ case OPCODE_CONTINUATION:
223
+ case OPCODE_TEXT:
224
+ case OPCODE_BINARY:
225
+ return this.#appendData(opcode, fin, payload)
226
+ case OPCODE_CLOSE:
227
+ return this.#handleClose(payload)
228
+ case OPCODE_PING:
229
+ if (this.#readyState === NativeWebSocket.OPEN) this.#socket.write(encodeFrame(OPCODE_PONG, payload))
230
+ return
231
+ case OPCODE_PONG:
232
+ return
233
+ default:
234
+ return this.#failConnection(1002, 'Invalid opcode received')
235
+ }
236
+ }
237
+
238
+ #appendData(opcode, fin, payload) {
239
+ if (opcode !== OPCODE_CONTINUATION) {
240
+ this.#fragments = []
241
+ this.#fragmentBytes = 0
242
+ this.#fragmentOpcode = opcode
243
+ }
244
+ this.#fragments.push(payload)
245
+ this.#fragmentBytes += payload.length
246
+ if (this.#fragmentBytes > MAX_MESSAGE_BYTES) return this.#failConnection(1009, 'Payload size exceeds maximum allowed size')
247
+ if (!fin) return
248
+ const message = this.#fragments.length === 1 ? this.#fragments[0] : Buffer.concat(this.#fragments, this.#fragmentBytes)
249
+ const messageOpcode = this.#fragmentOpcode
250
+ this.#fragments = null
251
+ this.#fragmentBytes = 0
252
+ if (messageOpcode === OPCODE_TEXT) {
253
+ let text
254
+ try {
255
+ text = TEXT_DECODER.decode(message)
256
+ } catch {
257
+ return this.#failConnection(1007, 'Invalid UTF-8')
258
+ }
259
+ this.#fire('onmessage', { type: 'message', data: text })
260
+ return
261
+ }
262
+ this.#fire('onmessage', { type: 'message', data: toArrayBuffer(message) })
263
+ }
264
+
265
+ #handleClose(payload) {
266
+ if (payload.length === 1) return this.#failConnection(1002, 'Received close frame with a 1-byte body.')
267
+ let code = 1005
268
+ let reason = ''
269
+ if (payload.length >= 2) {
270
+ code = payload.readUInt16BE(0)
271
+ if (!isValidCloseCode(code)) return this.#failConnection(1002, 'Invalid status code')
272
+ try {
273
+ reason = TEXT_DECODER.decode(payload.subarray(2))
274
+ } catch {
275
+ return this.#failConnection(1007, 'Invalid UTF-8')
276
+ }
277
+ }
278
+ this.#remoteClose = { code, reason }
279
+ this.#buffer = Buffer.alloc(0)
280
+ if (this.#readyState === NativeWebSocket.OPEN) this.#readyState = NativeWebSocket.CLOSING
281
+ this.#sendClose(payload.length >= 2 ? code : undefined, reason)
282
+ this.#socket.end()
283
+ this.#scheduleDestroy()
284
+ }
285
+
286
+ #failConnection(code, reason) {
287
+ if (this.#readyState === NativeWebSocket.CLOSED || this.#failCode !== null) return
288
+ this.#fire('onerror', { type: 'error', error: new Error(reason), message: reason })
289
+ this.#failCode = code
290
+ this.#buffer = Buffer.alloc(0)
291
+ this.#readyState = NativeWebSocket.CLOSING
292
+ this.#sendClose(code, reason)
293
+ this.#socket.end()
294
+ this.#scheduleDestroy()
295
+ }
296
+
297
+ #sendClose(code, reason = '') {
298
+ if (this.#closeSent || !this.#socket) return
299
+ this.#closeSent = true
300
+ let payload = Buffer.alloc(0)
301
+ if (code !== undefined) {
302
+ const text = Buffer.from(reason, 'utf8')
303
+ payload = Buffer.alloc(2 + text.length)
304
+ payload.writeUInt16BE(code, 0)
305
+ text.copy(payload, 2)
306
+ }
307
+ this.#socket.write(encodeFrame(OPCODE_CLOSE, payload))
308
+ }
309
+
310
+ #scheduleDestroy() {
311
+ if (this.#closeTimer || !this.#socket) return
312
+ this.#closeTimer = setTimeout(() => this.#socket?.destroy(), CLOSE_TIMEOUT_MS)
313
+ this.#closeTimer.unref?.()
314
+ }
315
+
316
+ #onSocketError(error) {
317
+ if (this.#readyState === NativeWebSocket.CLOSED) return
318
+ this.#fire('onerror', { type: 'error', error, message: error.message })
319
+ }
320
+
321
+ #onSocketClose() {
322
+ clearTimeout(this.#closeTimer)
323
+ this.#closeTimer = null
324
+ const code = this.#failCode ?? this.#remoteClose?.code ?? 1006
325
+ const reason = this.#failCode !== null ? '' : this.#remoteClose?.reason ?? ''
326
+ const wasClean = this.#remoteClose !== null && this.#failCode === null && this.#closeSent
327
+ this.#readyState = NativeWebSocket.CLOSED
328
+ this.#socket = null
329
+ this.#buffer = Buffer.alloc(0)
330
+ this.#fire('onclose', { type: 'close', code, reason, wasClean })
331
+ }
332
+
333
+ #fire(name, event) {
334
+ const handler = this[name]
335
+ if (typeof handler !== 'function') return
336
+ try {
337
+ handler.call(this, event)
338
+ } catch (error) {
339
+ queueMicrotask(() => {
340
+ throw error
341
+ })
342
+ }
343
+ }
344
+ }
@@ -1,23 +1,30 @@
1
1
  import { EventEmitter } from 'node:events'
2
2
  import { DEFAULT_ORIGIN } from '../defaults.js'
3
+ import { NativeWebSocket } from './native-websocket.js'
4
+
5
+ const WebSocketImpl = globalThis.WebSocket ?? NativeWebSocket
6
+ const usingNativeWebSocket = WebSocketImpl === NativeWebSocket
7
+
8
+ let h1Dispatcher
9
+ let h1DispatcherTried = false
10
+ function getH1Dispatcher(logger) {
11
+ if (h1DispatcherTried) return h1Dispatcher
12
+ h1DispatcherTried = true
13
+ try {
14
+ void globalThis.WebSocket
15
+ const base =
16
+ globalThis[Symbol.for('undici.globalDispatcher.2')] ??
17
+ globalThis[Symbol.for('undici.globalDispatcher.1')]
18
+ const Agent = base?.constructor
19
+ if (typeof Agent === 'function' && Agent !== Object) {
20
+ h1Dispatcher = new Agent({ allowH2: false })
21
+ }
22
+ } catch (err) {
23
+ logger?.warn?.({ err }, 'failed to create HTTP/1.1 dispatcher, falling back to the undici default')
24
+ }
25
+ return h1Dispatcher
26
+ }
3
27
 
4
- /**
5
- * Replaces `ws`, using Node's built-in `WebSocket` (undici-based, Node 22+).
6
- *
7
- * Handshake parity with `ws` (verified against a local server that records request headers):
8
- * - `Origin` -> sent (DEFAULT_ORIGIN), like upstream `ws({ origin })`
9
- * - `headers` -> config.options.headers, like upstream
10
- * - `dispatcher` -> config.dispatcher (undici Agent/ProxyAgent) is the native equivalent of
11
- * `ws`'s `agent`, so proxies work; a `ws`-style `config.agent` is NOT supported.
12
- * - handshake/connect timeout -> emulated with a timer (native WebSocket has no handshakeTimeout)
13
- *
14
- * NOTE: `{ headers, dispatcher }` is an undici extension to the WebSocket constructor, not part of the
15
- * browser standard. That is fine on Node 22+/24, which is what this package requires.
16
- *
17
- * Everything downstream (socket-core.js) talks to this class as a plain Node EventEmitter:
18
- * `.on('message', buf => ...)`, `.on('open')`, `.on('error')`, `.on('close')`, plus its own namespaced
19
- * events (`TAG:...`, `CB:...`, `frame`) emitted on itself, not on the underlying transport.
20
- */
21
28
  export class AbstractSocketClient extends EventEmitter {
22
29
  constructor(url, config) {
23
30
  super()
@@ -33,20 +40,25 @@ export class WebSocketClient extends AbstractSocketClient {
33
40
  this.socket = null
34
41
  }
35
42
 
43
+ emitError(err) {
44
+ if (this.listenerCount('error') > 0) this.emit('error', err)
45
+ else this.config?.logger?.debug?.({ err }, 'ws error ignored (no listener)')
46
+ }
47
+
36
48
  get isOpen() {
37
- return this.socket?.readyState === WebSocket.OPEN
49
+ return this.socket?.readyState === WebSocketImpl.OPEN
38
50
  }
39
51
 
40
52
  get isClosed() {
41
- return this.socket === null || this.socket?.readyState === WebSocket.CLOSED
53
+ return this.socket === null || this.socket?.readyState === WebSocketImpl.CLOSED
42
54
  }
43
55
 
44
56
  get isClosing() {
45
- return this.socket === null || this.socket?.readyState === WebSocket.CLOSING
57
+ return this.socket === null || this.socket?.readyState === WebSocketImpl.CLOSING
46
58
  }
47
59
 
48
60
  get isConnecting() {
49
- return this.socket?.readyState === WebSocket.CONNECTING
61
+ return this.socket?.readyState === WebSocketImpl.CONNECTING
50
62
  }
51
63
 
52
64
  connect() {
@@ -54,22 +66,33 @@ export class WebSocketClient extends AbstractSocketClient {
54
66
 
55
67
  const { options, connectTimeoutMs, dispatcher } = this.config || {}
56
68
  const wsOptions = { headers: { Origin: DEFAULT_ORIGIN, ...(options?.headers || {}) } }
57
- if (dispatcher) wsOptions.dispatcher = dispatcher
69
+ if (usingNativeWebSocket) {
70
+ if (dispatcher) this.config?.logger?.warn?.('`dispatcher` is ignored by the built-in WebSocket fallback; proxies are not applied')
71
+ } else {
72
+ const h1 = dispatcher || getH1Dispatcher(this.config?.logger)
73
+ if (h1) wsOptions.dispatcher = h1
74
+ }
58
75
  if (this.config?.agent) {
59
- this.config.logger?.warn?.('`agent` is not supported by the native WebSocket; pass an undici `dispatcher` (e.g. ProxyAgent) instead')
76
+ this.config.logger?.warn?.('`agent` is not supported by the WebSocket client; pass an undici `dispatcher` (e.g. ProxyAgent) on Node.js 22+ instead')
60
77
  }
61
78
 
62
- const socket = new WebSocket(this.url, wsOptions)
79
+ const socket = new WebSocketImpl(this.url, wsOptions)
63
80
  this.socket = socket
64
81
  socket.binaryType = 'arraybuffer'
65
82
 
66
- // emulate ws's `handshakeTimeout`: abort a connection that never opens
67
83
  let handshakeTimer
68
84
  if (connectTimeoutMs > 0) {
69
85
  handshakeTimer = setTimeout(() => {
70
- if (socket.readyState === WebSocket.CONNECTING) {
71
- this.emit('error', new Error('Opening handshake has timed out'))
72
- try { socket.close() } catch {}
86
+ if (socket.readyState === WebSocketImpl.CONNECTING) {
87
+
88
+ socket.onopen = null
89
+ socket.onmessage = null
90
+ socket.onerror = () => {}
91
+ socket.onclose = () => {}
92
+ this.emitError(new Error('Opening handshake has timed out'))
93
+ queueMicrotask(() => {
94
+ try { socket.close() } catch {}
95
+ })
73
96
  }
74
97
  }, connectTimeoutMs)
75
98
  handshakeTimer.unref?.()
@@ -78,10 +101,18 @@ export class WebSocketClient extends AbstractSocketClient {
78
101
 
79
102
  socket.onopen = () => { clearHandshake(); this.emit('open') }
80
103
  socket.onclose = event => { clearHandshake(); this.emit('close', event.code, event.reason) }
81
- socket.onerror = event => { clearHandshake(); this.emit('error', event.error || new Error(event.message || 'WebSocket error')) }
104
+ socket.onerror = event => {
105
+ clearHandshake()
106
+
107
+ const raw = event.error || new Error(event.message || 'WebSocket error')
108
+ if (!raw.message) {
109
+ const detail = raw.cause?.message || raw.cause?.code || event.message || 'unknown'
110
+ raw.message = `WebSocket error: ${detail}`
111
+ }
112
+ this.emitError(raw)
113
+ }
82
114
  socket.onmessage = event => {
83
- // `ws` handed listeners a Buffer/string; the native WebSocket hands back an ArrayBuffer
84
- // (binaryType set above) or a string — normalize to match.
115
+
85
116
  const { data } = event
86
117
  this.emit('message', typeof data === 'string' ? data : Buffer.from(data))
87
118
  }
@@ -90,16 +121,31 @@ export class WebSocketClient extends AbstractSocketClient {
90
121
  async close() {
91
122
  const socket = this.socket
92
123
  if (!socket) return
93
- if (socket.readyState === WebSocket.CLOSED) {
124
+ if (socket.readyState === WebSocketImpl.CLOSED) {
125
+ this.socket = null
126
+ return
127
+ }
128
+
129
+ if (socket.readyState === WebSocketImpl.CONNECTING) {
130
+ socket.onopen = null
131
+ socket.onmessage = null
132
+ socket.onerror = () => {}
133
+ socket.onclose = () => {}
94
134
  this.socket = null
135
+
136
+ queueMicrotask(() => {
137
+ try { socket.close() } catch {}
138
+ })
95
139
  return
96
140
  }
97
- // connect()'s onclose handler emits 'close'; here we only wait for it (like `ws`'s once('close')).
98
- // Guarded with a timeout: if the underlying transport is stuck (e.g. a wedged TCP
99
- // socket), 'close' may never fire and this would otherwise hang teardown forever.
141
+
100
142
  let onClose
101
143
  const closePromise = new Promise(resolve => { onClose = resolve; this.once('close', onClose) })
102
- try { socket.close() } catch {}
144
+ try {
145
+ socket.close()
146
+ } catch {
147
+
148
+ }
103
149
  await Promise.race([closePromise, new Promise(resolve => setTimeout(resolve, 5000))])
104
150
  this.off('close', onClose)
105
151
  this.socket = null
@@ -107,13 +153,13 @@ export class WebSocketClient extends AbstractSocketClient {
107
153
 
108
154
  send(str, cb) {
109
155
  const socket = this.socket
110
- if (!socket || socket.readyState !== WebSocket.OPEN) {
156
+ if (!socket || socket.readyState !== WebSocketImpl.OPEN) {
111
157
  cb?.(new Error('WebSocket is not open'))
112
158
  return false
113
159
  }
114
160
  try {
115
161
  socket.send(str)
116
- // native send() is fire-and-forget; defer the callback to keep `ws`'s async-callback semantics
162
+
117
163
  if (cb) queueMicrotask(() => cb())
118
164
  } catch (err) {
119
165
  cb?.(err)