@capyclaw/rsp-suite 0.0.0-stage → 0.1.1

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 (146) hide show
  1. package/README.md +84 -2
  2. package/cordis.patch.yml +8 -0
  3. package/dsh-suite.json +91 -0
  4. package/node_modules/@capyclaw/foundation/README.md +51 -0
  5. package/node_modules/@capyclaw/foundation/abi/assets.mjs +26 -0
  6. package/node_modules/@capyclaw/foundation/abi/bridge.mjs +88 -0
  7. package/node_modules/@capyclaw/foundation/abi/errors.mjs +63 -0
  8. package/node_modules/@capyclaw/foundation/abi/index.mjs +50 -0
  9. package/node_modules/@capyclaw/foundation/abi/kinds.mjs +271 -0
  10. package/node_modules/@capyclaw/foundation/abi/loader.mjs +352 -0
  11. package/node_modules/@capyclaw/foundation/abi/schema.mjs +98 -0
  12. package/node_modules/@capyclaw/foundation/abi/spec.mjs +258 -0
  13. package/node_modules/@capyclaw/foundation/abi/validate.mjs +24 -0
  14. package/node_modules/@capyclaw/foundation/abi/version.mjs +140 -0
  15. package/node_modules/@capyclaw/foundation/abi/visibility.mjs +90 -0
  16. package/node_modules/@capyclaw/foundation/cordis.patch.yml +5 -0
  17. package/node_modules/@capyclaw/foundation/kit/index.mjs +6 -0
  18. package/node_modules/@capyclaw/foundation/lib/adapters/client-panel.mjs +98 -0
  19. package/node_modules/@capyclaw/foundation/lib/adapters/host-event.mjs +35 -0
  20. package/node_modules/@capyclaw/foundation/lib/adapters/http-router.mjs +69 -0
  21. package/node_modules/@capyclaw/foundation/lib/adapters/lifecycle-hook.mjs +72 -0
  22. package/node_modules/@capyclaw/foundation/lib/adapters/own-server.mjs +113 -0
  23. package/node_modules/@capyclaw/foundation/lib/adapters/raw.mjs +69 -0
  24. package/node_modules/@capyclaw/foundation/lib/adapters/runtime-driver.mjs +120 -0
  25. package/node_modules/@capyclaw/foundation/lib/adapters/service-provider.mjs +77 -0
  26. package/node_modules/@capyclaw/foundation/lib/adapters/skill-provider.mjs +56 -0
  27. package/node_modules/@capyclaw/foundation/lib/adapters/tool-provider.mjs +50 -0
  28. package/node_modules/@capyclaw/foundation/lib/adapters/ui-panel.mjs +64 -0
  29. package/node_modules/@capyclaw/foundation/lib/ctx-service.mjs +42 -0
  30. package/node_modules/@capyclaw/foundation/lib/host/caps.mjs +38 -0
  31. package/node_modules/@capyclaw/foundation/lib/host/contract.mjs +88 -0
  32. package/node_modules/@capyclaw/foundation/lib/host/dsh.mjs +54 -0
  33. package/node_modules/@capyclaw/foundation/lib/host/memory.mjs +187 -0
  34. package/node_modules/@capyclaw/foundation/lib/host.mjs +23 -0
  35. package/node_modules/@capyclaw/foundation/lib/kernel.mjs +195 -0
  36. package/node_modules/@capyclaw/foundation/lib/skill/scan.mjs +115 -0
  37. package/node_modules/@capyclaw/foundation/lib/subsystems/events.mjs +60 -0
  38. package/node_modules/@capyclaw/foundation/lib/subsystems/log.mjs +51 -0
  39. package/node_modules/@capyclaw/foundation/lib/subsystems/net.mjs +198 -0
  40. package/node_modules/@capyclaw/foundation/package.json +53 -0
  41. package/node_modules/@capyclaw/foundation/runtime/index.mjs +20 -0
  42. package/node_modules/@capyclaw/plugin-kit/INTEGRATION.md +100 -0
  43. package/node_modules/@capyclaw/plugin-kit/README.md +70 -0
  44. package/node_modules/@capyclaw/plugin-kit/bin/sync.mjs +103 -0
  45. package/node_modules/@capyclaw/plugin-kit/package.json +72 -0
  46. package/node_modules/@capyclaw/plugin-kit/src/cli.mjs +56 -0
  47. package/node_modules/@capyclaw/plugin-kit/src/config.mjs +142 -0
  48. package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat-worker.js +132 -0
  49. package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat.mjs +26 -0
  50. package/node_modules/@capyclaw/plugin-kit/src/editor/lease.mjs +60 -0
  51. package/node_modules/@capyclaw/plugin-kit/src/editor/shadow.mjs +219 -0
  52. package/node_modules/@capyclaw/plugin-kit/src/editor/transport.js +13 -0
  53. package/node_modules/@capyclaw/plugin-kit/src/index.mjs +13 -0
  54. package/node_modules/@capyclaw/plugin-kit/src/ledger.mjs +151 -0
  55. package/node_modules/@capyclaw/plugin-kit/src/pack.mjs +230 -0
  56. package/node_modules/@capyclaw/plugin-kit/src/runtime/context.mjs +128 -0
  57. package/node_modules/@capyclaw/plugin-kit/src/self-contained.mjs +307 -0
  58. package/node_modules/@capyclaw/plugin-kit/src/service/api.mjs +45 -0
  59. package/node_modules/@capyclaw/plugin-kit/src/service/http.mjs +113 -0
  60. package/node_modules/@capyclaw/plugin-kit/src/service/mcp-http.mjs +150 -0
  61. package/node_modules/@capyclaw/plugin-kit/src/service/server.mjs +131 -0
  62. package/node_modules/@capyclaw/plugin-kit/src/service/static.mjs +79 -0
  63. package/node_modules/@capyclaw/plugin-kit/src/skills/provider.mjs +82 -0
  64. package/node_modules/@capyclaw/plugin-kit/src/store/blob-store.mjs +109 -0
  65. package/node_modules/@capyclaw/plugin-kit/src/store/content-store.mjs +17 -0
  66. package/node_modules/@capyclaw/plugin-kit/src/store/journal-store.mjs +89 -0
  67. package/node_modules/@capyclaw/plugin-kit/src/tools/result.mjs +57 -0
  68. package/node_modules/@capyclaw/plugin-kit/src/tools/validate.mjs +150 -0
  69. package/node_modules/@capyclaw/plugin-kit/src/tuning.mjs +82 -0
  70. package/node_modules/@capyclaw/plugin-kit/src/util/fs-lock.mjs +132 -0
  71. package/node_modules/@capyclaw/plugin-kit/src/util/http.mjs +130 -0
  72. package/node_modules/@capyclaw/plugin-kit/src/workspace/manager.mjs +664 -0
  73. package/node_modules/@capyclaw/plugin-kit/src/zip.mjs +181 -0
  74. package/node_modules/@capyclaw/rsp-skill-remote-screen/README.md +7 -0
  75. package/node_modules/@capyclaw/rsp-skill-remote-screen/contract/rsp-contract.json +478 -0
  76. package/node_modules/@capyclaw/rsp-skill-remote-screen/cordis.patch.yml +4 -0
  77. package/node_modules/@capyclaw/rsp-skill-remote-screen/package.json +33 -0
  78. package/node_modules/@capyclaw/rsp-skill-remote-screen/plugin.mjs +15 -0
  79. package/node_modules/@capyclaw/rsp-skill-remote-screen/skills/remote-screen/SKILL.md +131 -0
  80. package/node_modules/@capyclaw/rsp-workbench/contract/capabilities.json +203 -0
  81. package/node_modules/@capyclaw/rsp-workbench/lib/client.mjs +681 -0
  82. package/node_modules/@capyclaw/rsp-workbench/lib/descriptors.mjs +28 -0
  83. package/node_modules/@capyclaw/rsp-workbench/lib/host.mjs +51 -0
  84. package/node_modules/@capyclaw/rsp-workbench/lib/manager.mjs +333 -0
  85. package/node_modules/@capyclaw/rsp-workbench/lib/session-mode.mjs +68 -0
  86. package/node_modules/@capyclaw/rsp-workbench/lib/tools.mjs +485 -0
  87. package/node_modules/@capyclaw/rsp-workbench/lib/workbench.mjs +184 -0
  88. package/node_modules/@capyclaw/rsp-workbench/package.json +47 -0
  89. package/node_modules/@capyclaw/rsp-workbench/plugin.mjs +17 -0
  90. package/node_modules/@capyclaw/rsp-workbench/ui/index.html +578 -0
  91. package/node_modules/@capyclaw/service-host/README.md +86 -0
  92. package/node_modules/@capyclaw/service-host/cordis.patch.yml +4 -0
  93. package/node_modules/@capyclaw/service-host/dsh-suite.json +29 -0
  94. package/node_modules/@capyclaw/service-host/lib/host.mjs +22 -0
  95. package/node_modules/@capyclaw/service-host/package.json +60 -0
  96. package/node_modules/@capyclaw/service-host/src/index.mjs +597 -0
  97. package/node_modules/@capyclaw/service-host/src/tuning.mjs +63 -0
  98. package/node_modules/@capyclaw/suite-kit/README.md +289 -0
  99. package/node_modules/@capyclaw/suite-kit/bin/dsh-domain.mjs +98 -0
  100. package/node_modules/@capyclaw/suite-kit/bin/dsh-suite.mjs +174 -0
  101. package/node_modules/@capyclaw/suite-kit/client/embed.js +35 -0
  102. package/node_modules/@capyclaw/suite-kit/domain.schema.json +129 -0
  103. package/node_modules/@capyclaw/suite-kit/package.json +58 -0
  104. package/node_modules/@capyclaw/suite-kit/src/activation-registry.mjs +184 -0
  105. package/node_modules/@capyclaw/suite-kit/src/artifacts.mjs +131 -0
  106. package/node_modules/@capyclaw/suite-kit/src/capability.mjs +181 -0
  107. package/node_modules/@capyclaw/suite-kit/src/compose.mjs +201 -0
  108. package/node_modules/@capyclaw/suite-kit/src/domain.mjs +138 -0
  109. package/node_modules/@capyclaw/suite-kit/src/embed.mjs +81 -0
  110. package/node_modules/@capyclaw/suite-kit/src/host.mjs +251 -0
  111. package/node_modules/@capyclaw/suite-kit/src/index.mjs +24 -0
  112. package/node_modules/@capyclaw/suite-kit/src/manifest.mjs +263 -0
  113. package/node_modules/@capyclaw/suite-kit/src/orchestration.mjs +100 -0
  114. package/node_modules/@capyclaw/suite-kit/src/profile.mjs +584 -0
  115. package/node_modules/@capyclaw/suite-kit/src/surface.mjs +28 -0
  116. package/node_modules/@capyclaw/suite-kit/suite.schema.json +128 -0
  117. package/node_modules/@capyclaw/tool-host/README.md +56 -0
  118. package/node_modules/@capyclaw/tool-host/cordis.patch.yml +4 -0
  119. package/node_modules/@capyclaw/tool-host/dsh-suite.json +30 -0
  120. package/node_modules/@capyclaw/tool-host/lib/host.mjs +46 -0
  121. package/node_modules/@capyclaw/tool-host/package.json +59 -0
  122. package/node_modules/@capyclaw/tool-host/src/admit-images.mjs +80 -0
  123. package/node_modules/@capyclaw/tool-host/src/caller-session.mjs +25 -0
  124. package/node_modules/@capyclaw/tool-host/src/descriptors.mjs +166 -0
  125. package/node_modules/@capyclaw/tool-host/src/index.mjs +461 -0
  126. package/node_modules/@capyclaw/tool-host/src/mode-gate.mjs +272 -0
  127. package/node_modules/ws/LICENSE +20 -0
  128. package/node_modules/ws/README.md +539 -0
  129. package/node_modules/ws/browser.js +8 -0
  130. package/node_modules/ws/index.js +22 -0
  131. package/node_modules/ws/lib/buffer-util.js +142 -0
  132. package/node_modules/ws/lib/constants.js +19 -0
  133. package/node_modules/ws/lib/event-target.js +292 -0
  134. package/node_modules/ws/lib/extension.js +203 -0
  135. package/node_modules/ws/lib/limiter.js +55 -0
  136. package/node_modules/ws/lib/permessage-deflate.js +530 -0
  137. package/node_modules/ws/lib/receiver.js +751 -0
  138. package/node_modules/ws/lib/sender.js +610 -0
  139. package/node_modules/ws/lib/stream.js +161 -0
  140. package/node_modules/ws/lib/subprotocol.js +62 -0
  141. package/node_modules/ws/lib/validation.js +152 -0
  142. package/node_modules/ws/lib/websocket-server.js +562 -0
  143. package/node_modules/ws/lib/websocket.js +1440 -0
  144. package/node_modules/ws/package.json +74 -0
  145. package/node_modules/ws/wrapper.mjs +21 -0
  146. package/package.json +53 -4
@@ -0,0 +1,1440 @@
1
+ /* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^Duplex|Readable$", "caughtErrors": "none" }] */
2
+
3
+ 'use strict';
4
+
5
+ const EventEmitter = require('events');
6
+ const https = require('https');
7
+ const http = require('http');
8
+ const net = require('net');
9
+ const querystring = require('querystring');
10
+ const tls = require('tls');
11
+ const { randomBytes, createHash } = require('crypto');
12
+ const { Duplex, Readable } = require('stream');
13
+ const { URL } = require('url');
14
+
15
+ const PerMessageDeflate = require('./permessage-deflate');
16
+ const Receiver = require('./receiver');
17
+ const Sender = require('./sender');
18
+ const { isBlob } = require('./validation');
19
+
20
+ const {
21
+ BINARY_TYPES,
22
+ CLOSE_TIMEOUT,
23
+ EMPTY_BUFFER,
24
+ GUID,
25
+ kForOnEventAttribute,
26
+ kListener,
27
+ kStatusCode,
28
+ kWebSocket,
29
+ NOOP
30
+ } = require('./constants');
31
+ const {
32
+ EventTarget: { addEventListener, removeEventListener }
33
+ } = require('./event-target');
34
+ const { format, parse } = require('./extension');
35
+ const { toBuffer } = require('./buffer-util');
36
+
37
+ const kAborted = Symbol('kAborted');
38
+ const protocolVersions = [8, 13];
39
+ const readyStates = ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED'];
40
+ const subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
41
+
42
+ /**
43
+ * Class representing a WebSocket.
44
+ *
45
+ * @extends EventEmitter
46
+ */
47
+ class WebSocket extends EventEmitter {
48
+ /**
49
+ * Create a new `WebSocket`.
50
+ *
51
+ * @param {(String|URL)} address The URL to which to connect
52
+ * @param {(String|String[])} [protocols] The subprotocols
53
+ * @param {Object} [options] Connection options
54
+ */
55
+ constructor(address, protocols, options) {
56
+ super();
57
+
58
+ this._binaryType = BINARY_TYPES[0];
59
+ this._closeCode = 1006;
60
+ this._closeFrameReceived = false;
61
+ this._closeFrameSent = false;
62
+ this._closeMessage = EMPTY_BUFFER;
63
+ this._closeTimer = null;
64
+ this._errorEmitted = false;
65
+ this._extensions = {};
66
+ this._paused = false;
67
+ this._protocol = '';
68
+ this._readyState = WebSocket.CONNECTING;
69
+ this._receiver = null;
70
+ this._sender = null;
71
+ this._socket = null;
72
+
73
+ if (address !== null) {
74
+ this._bufferedAmount = 0;
75
+ this._isServer = false;
76
+ this._redirects = 0;
77
+
78
+ if (protocols === undefined) {
79
+ if (!options || options.protocols === undefined) {
80
+ protocols = [];
81
+ } else if (Array.isArray(options.protocols)) {
82
+ protocols = options.protocols;
83
+ } else {
84
+ protocols = [options.protocols];
85
+ }
86
+ } else if (!Array.isArray(protocols)) {
87
+ if (typeof protocols === 'object' && protocols !== null) {
88
+ options = protocols;
89
+
90
+ if (options.protocols === undefined) {
91
+ protocols = [];
92
+ } else if (Array.isArray(options.protocols)) {
93
+ protocols = options.protocols;
94
+ } else {
95
+ protocols = [options.protocols];
96
+ }
97
+ } else {
98
+ protocols = [protocols];
99
+ }
100
+ }
101
+
102
+ initAsClient(this, address, protocols, options);
103
+ } else {
104
+ this._autoPong = options.autoPong;
105
+ this._closeTimeout = options.closeTimeout;
106
+ this._isServer = true;
107
+ }
108
+ }
109
+
110
+ /**
111
+ * For historical reasons, the custom "nodebuffer" type is used by the default
112
+ * instead of "blob".
113
+ *
114
+ * @type {String}
115
+ */
116
+ get binaryType() {
117
+ return this._binaryType;
118
+ }
119
+
120
+ set binaryType(type) {
121
+ if (!BINARY_TYPES.includes(type)) return;
122
+
123
+ this._binaryType = type;
124
+
125
+ //
126
+ // Allow to change `binaryType` on the fly.
127
+ //
128
+ if (this._receiver) this._receiver._binaryType = type;
129
+ }
130
+
131
+ /**
132
+ * @type {Number}
133
+ */
134
+ get bufferedAmount() {
135
+ if (!this._socket) return this._bufferedAmount;
136
+
137
+ return this._socket._writableState.length + this._sender._bufferedBytes;
138
+ }
139
+
140
+ /**
141
+ * @type {String}
142
+ */
143
+ get extensions() {
144
+ return Object.keys(this._extensions).join();
145
+ }
146
+
147
+ /**
148
+ * @type {Boolean}
149
+ */
150
+ get isPaused() {
151
+ return this._paused;
152
+ }
153
+
154
+ /**
155
+ * @type {Function}
156
+ */
157
+ /* istanbul ignore next */
158
+ get onclose() {
159
+ return null;
160
+ }
161
+
162
+ /**
163
+ * @type {Function}
164
+ */
165
+ /* istanbul ignore next */
166
+ get onerror() {
167
+ return null;
168
+ }
169
+
170
+ /**
171
+ * @type {Function}
172
+ */
173
+ /* istanbul ignore next */
174
+ get onopen() {
175
+ return null;
176
+ }
177
+
178
+ /**
179
+ * @type {Function}
180
+ */
181
+ /* istanbul ignore next */
182
+ get onmessage() {
183
+ return null;
184
+ }
185
+
186
+ /**
187
+ * @type {String}
188
+ */
189
+ get protocol() {
190
+ return this._protocol;
191
+ }
192
+
193
+ /**
194
+ * @type {Number}
195
+ */
196
+ get readyState() {
197
+ return this._readyState;
198
+ }
199
+
200
+ /**
201
+ * @type {String}
202
+ */
203
+ get url() {
204
+ return this._url;
205
+ }
206
+
207
+ /**
208
+ * Set up the socket and the internal resources.
209
+ *
210
+ * @param {Duplex} socket The network socket between the server and client
211
+ * @param {Buffer} head The first packet of the upgraded stream
212
+ * @param {Object} options Options object
213
+ * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether
214
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
215
+ * multiple times in the same tick
216
+ * @param {Function} [options.generateMask] The function used to generate the
217
+ * masking key
218
+ * @param {Number} [options.maxBufferedChunks=0] The maximum number of
219
+ * buffered data chunks
220
+ * @param {Number} [options.maxFragments=0] The maximum number of message
221
+ * fragments
222
+ * @param {Number} [options.maxPayload=0] The maximum allowed message size
223
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
224
+ * not to skip UTF-8 validation for text and close messages
225
+ * @private
226
+ */
227
+ setSocket(socket, head, options) {
228
+ const receiver = new Receiver({
229
+ allowSynchronousEvents: options.allowSynchronousEvents,
230
+ binaryType: this.binaryType,
231
+ extensions: this._extensions,
232
+ isServer: this._isServer,
233
+ maxBufferedChunks: options.maxBufferedChunks,
234
+ maxFragments: options.maxFragments,
235
+ maxPayload: options.maxPayload,
236
+ skipUTF8Validation: options.skipUTF8Validation
237
+ });
238
+
239
+ const sender = new Sender(socket, this._extensions, options.generateMask);
240
+
241
+ this._receiver = receiver;
242
+ this._sender = sender;
243
+ this._socket = socket;
244
+
245
+ receiver[kWebSocket] = this;
246
+ sender[kWebSocket] = this;
247
+ socket[kWebSocket] = this;
248
+
249
+ receiver.on('conclude', receiverOnConclude);
250
+ receiver.on('drain', receiverOnDrain);
251
+ receiver.on('error', receiverOnError);
252
+ receiver.on('message', receiverOnMessage);
253
+ receiver.on('ping', receiverOnPing);
254
+ receiver.on('pong', receiverOnPong);
255
+
256
+ sender.onerror = senderOnError;
257
+
258
+ //
259
+ // These methods may not be available if `socket` is just a `Duplex`.
260
+ //
261
+ if (socket.setTimeout) socket.setTimeout(0);
262
+ if (socket.setNoDelay) socket.setNoDelay();
263
+
264
+ if (head.length > 0) socket.unshift(head);
265
+
266
+ socket.on('close', socketOnClose);
267
+ socket.on('data', socketOnData);
268
+ socket.on('end', socketOnEnd);
269
+ socket.on('error', socketOnError);
270
+
271
+ this._readyState = WebSocket.OPEN;
272
+ this.emit('open');
273
+ }
274
+
275
+ /**
276
+ * Emit the `'close'` event.
277
+ *
278
+ * @private
279
+ */
280
+ emitClose() {
281
+ if (!this._socket) {
282
+ this._readyState = WebSocket.CLOSED;
283
+ this.emit('close', this._closeCode, this._closeMessage);
284
+ return;
285
+ }
286
+
287
+ if (this._extensions[PerMessageDeflate.extensionName]) {
288
+ this._extensions[PerMessageDeflate.extensionName].cleanup();
289
+ }
290
+
291
+ this._receiver.removeAllListeners();
292
+ this._readyState = WebSocket.CLOSED;
293
+ this.emit('close', this._closeCode, this._closeMessage);
294
+ }
295
+
296
+ /**
297
+ * Start a closing handshake.
298
+ *
299
+ * +----------+ +-----------+ +----------+
300
+ * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -
301
+ * | +----------+ +-----------+ +----------+ |
302
+ * +----------+ +-----------+ |
303
+ * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING
304
+ * +----------+ +-----------+ |
305
+ * | | | +---+ |
306
+ * +------------------------+-->|fin| - - - -
307
+ * | +---+ | +---+
308
+ * - - - - -|fin|<---------------------+
309
+ * +---+
310
+ *
311
+ * @param {Number} [code] Status code explaining why the connection is closing
312
+ * @param {(String|Buffer)} [data] The reason why the connection is
313
+ * closing
314
+ * @public
315
+ */
316
+ close(code, data) {
317
+ if (this.readyState === WebSocket.CLOSED) return;
318
+ if (this.readyState === WebSocket.CONNECTING) {
319
+ const msg = 'WebSocket was closed before the connection was established';
320
+ abortHandshake(this, this._req, msg);
321
+ return;
322
+ }
323
+
324
+ if (this.readyState === WebSocket.CLOSING) {
325
+ if (
326
+ this._closeFrameSent &&
327
+ (this._closeFrameReceived || this._receiver._writableState.errorEmitted)
328
+ ) {
329
+ this._socket.end();
330
+ }
331
+
332
+ return;
333
+ }
334
+
335
+ this._sender.close(code, data, !this._isServer, (err) => {
336
+ //
337
+ // This error is handled by the `'error'` listener on the socket. We only
338
+ // want to know if the close frame has been sent here.
339
+ //
340
+ if (err) return;
341
+
342
+ this._closeFrameSent = true;
343
+
344
+ if (
345
+ this._closeFrameReceived ||
346
+ this._receiver._writableState.errorEmitted
347
+ ) {
348
+ this._socket.end();
349
+ }
350
+ });
351
+
352
+ this._readyState = WebSocket.CLOSING;
353
+ setCloseTimer(this);
354
+ }
355
+
356
+ /**
357
+ * Pause the socket.
358
+ *
359
+ * @public
360
+ */
361
+ pause() {
362
+ if (
363
+ this.readyState === WebSocket.CONNECTING ||
364
+ this.readyState === WebSocket.CLOSED
365
+ ) {
366
+ return;
367
+ }
368
+
369
+ this._paused = true;
370
+ this._socket.pause();
371
+ }
372
+
373
+ /**
374
+ * Send a ping.
375
+ *
376
+ * @param {*} [data] The data to send
377
+ * @param {Boolean} [mask] Indicates whether or not to mask `data`
378
+ * @param {Function} [cb] Callback which is executed when the ping is sent
379
+ * @public
380
+ */
381
+ ping(data, mask, cb) {
382
+ if (this.readyState === WebSocket.CONNECTING) {
383
+ throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');
384
+ }
385
+
386
+ if (typeof data === 'function') {
387
+ cb = data;
388
+ data = mask = undefined;
389
+ } else if (typeof mask === 'function') {
390
+ cb = mask;
391
+ mask = undefined;
392
+ }
393
+
394
+ if (typeof data === 'number') data = data.toString();
395
+
396
+ if (this.readyState !== WebSocket.OPEN) {
397
+ sendAfterClose(this, data, cb);
398
+ return;
399
+ }
400
+
401
+ if (mask === undefined) mask = !this._isServer;
402
+ this._sender.ping(data || EMPTY_BUFFER, mask, cb);
403
+ }
404
+
405
+ /**
406
+ * Send a pong.
407
+ *
408
+ * @param {*} [data] The data to send
409
+ * @param {Boolean} [mask] Indicates whether or not to mask `data`
410
+ * @param {Function} [cb] Callback which is executed when the pong is sent
411
+ * @public
412
+ */
413
+ pong(data, mask, cb) {
414
+ if (this.readyState === WebSocket.CONNECTING) {
415
+ throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');
416
+ }
417
+
418
+ if (typeof data === 'function') {
419
+ cb = data;
420
+ data = mask = undefined;
421
+ } else if (typeof mask === 'function') {
422
+ cb = mask;
423
+ mask = undefined;
424
+ }
425
+
426
+ if (typeof data === 'number') data = data.toString();
427
+
428
+ if (this.readyState !== WebSocket.OPEN) {
429
+ sendAfterClose(this, data, cb);
430
+ return;
431
+ }
432
+
433
+ if (mask === undefined) mask = !this._isServer;
434
+ this._sender.pong(data || EMPTY_BUFFER, mask, cb);
435
+ }
436
+
437
+ /**
438
+ * Resume the socket.
439
+ *
440
+ * @public
441
+ */
442
+ resume() {
443
+ if (
444
+ this.readyState === WebSocket.CONNECTING ||
445
+ this.readyState === WebSocket.CLOSED
446
+ ) {
447
+ return;
448
+ }
449
+
450
+ this._paused = false;
451
+ if (!this._receiver._writableState.needDrain) this._socket.resume();
452
+ }
453
+
454
+ /**
455
+ * Send a data message.
456
+ *
457
+ * @param {*} data The message to send
458
+ * @param {Object} [options] Options object
459
+ * @param {Boolean} [options.binary] Specifies whether `data` is binary or
460
+ * text
461
+ * @param {Boolean} [options.compress] Specifies whether or not to compress
462
+ * `data`
463
+ * @param {Boolean} [options.fin=true] Specifies whether the fragment is the
464
+ * last one
465
+ * @param {Boolean} [options.mask] Specifies whether or not to mask `data`
466
+ * @param {Function} [cb] Callback which is executed when data is written out
467
+ * @public
468
+ */
469
+ send(data, options, cb) {
470
+ if (this.readyState === WebSocket.CONNECTING) {
471
+ throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');
472
+ }
473
+
474
+ if (typeof options === 'function') {
475
+ cb = options;
476
+ options = {};
477
+ }
478
+
479
+ if (typeof data === 'number') data = data.toString();
480
+
481
+ if (this.readyState !== WebSocket.OPEN) {
482
+ sendAfterClose(this, data, cb);
483
+ return;
484
+ }
485
+
486
+ const opts = {
487
+ binary: typeof data !== 'string',
488
+ mask: !this._isServer,
489
+ compress: true,
490
+ fin: true,
491
+ ...options
492
+ };
493
+
494
+ if (!this._extensions[PerMessageDeflate.extensionName]) {
495
+ opts.compress = false;
496
+ }
497
+
498
+ this._sender.send(data || EMPTY_BUFFER, opts, cb);
499
+ }
500
+
501
+ /**
502
+ * Forcibly close the connection.
503
+ *
504
+ * @public
505
+ */
506
+ terminate() {
507
+ if (this.readyState === WebSocket.CLOSED) return;
508
+ if (this.readyState === WebSocket.CONNECTING) {
509
+ const msg = 'WebSocket was closed before the connection was established';
510
+ abortHandshake(this, this._req, msg);
511
+ return;
512
+ }
513
+
514
+ if (this._socket) {
515
+ this._readyState = WebSocket.CLOSING;
516
+ this._socket.destroy();
517
+ }
518
+ }
519
+ }
520
+
521
+ /**
522
+ * @constant {Number} CONNECTING
523
+ * @memberof WebSocket
524
+ */
525
+ Object.defineProperty(WebSocket, 'CONNECTING', {
526
+ enumerable: true,
527
+ value: readyStates.indexOf('CONNECTING')
528
+ });
529
+
530
+ /**
531
+ * @constant {Number} CONNECTING
532
+ * @memberof WebSocket.prototype
533
+ */
534
+ Object.defineProperty(WebSocket.prototype, 'CONNECTING', {
535
+ enumerable: true,
536
+ value: readyStates.indexOf('CONNECTING')
537
+ });
538
+
539
+ /**
540
+ * @constant {Number} OPEN
541
+ * @memberof WebSocket
542
+ */
543
+ Object.defineProperty(WebSocket, 'OPEN', {
544
+ enumerable: true,
545
+ value: readyStates.indexOf('OPEN')
546
+ });
547
+
548
+ /**
549
+ * @constant {Number} OPEN
550
+ * @memberof WebSocket.prototype
551
+ */
552
+ Object.defineProperty(WebSocket.prototype, 'OPEN', {
553
+ enumerable: true,
554
+ value: readyStates.indexOf('OPEN')
555
+ });
556
+
557
+ /**
558
+ * @constant {Number} CLOSING
559
+ * @memberof WebSocket
560
+ */
561
+ Object.defineProperty(WebSocket, 'CLOSING', {
562
+ enumerable: true,
563
+ value: readyStates.indexOf('CLOSING')
564
+ });
565
+
566
+ /**
567
+ * @constant {Number} CLOSING
568
+ * @memberof WebSocket.prototype
569
+ */
570
+ Object.defineProperty(WebSocket.prototype, 'CLOSING', {
571
+ enumerable: true,
572
+ value: readyStates.indexOf('CLOSING')
573
+ });
574
+
575
+ /**
576
+ * @constant {Number} CLOSED
577
+ * @memberof WebSocket
578
+ */
579
+ Object.defineProperty(WebSocket, 'CLOSED', {
580
+ enumerable: true,
581
+ value: readyStates.indexOf('CLOSED')
582
+ });
583
+
584
+ /**
585
+ * @constant {Number} CLOSED
586
+ * @memberof WebSocket.prototype
587
+ */
588
+ Object.defineProperty(WebSocket.prototype, 'CLOSED', {
589
+ enumerable: true,
590
+ value: readyStates.indexOf('CLOSED')
591
+ });
592
+
593
+ [
594
+ 'binaryType',
595
+ 'bufferedAmount',
596
+ 'extensions',
597
+ 'isPaused',
598
+ 'protocol',
599
+ 'readyState',
600
+ 'url'
601
+ ].forEach((property) => {
602
+ Object.defineProperty(WebSocket.prototype, property, { enumerable: true });
603
+ });
604
+
605
+ //
606
+ // Add the `onopen`, `onerror`, `onclose`, and `onmessage` attributes.
607
+ // See https://html.spec.whatwg.org/multipage/comms.html#the-websocket-interface
608
+ //
609
+ ['open', 'error', 'close', 'message'].forEach((method) => {
610
+ Object.defineProperty(WebSocket.prototype, `on${method}`, {
611
+ enumerable: true,
612
+ get() {
613
+ for (const listener of this.listeners(method)) {
614
+ if (listener[kForOnEventAttribute]) return listener[kListener];
615
+ }
616
+
617
+ return null;
618
+ },
619
+ set(handler) {
620
+ for (const listener of this.listeners(method)) {
621
+ if (listener[kForOnEventAttribute]) {
622
+ this.removeListener(method, listener);
623
+ break;
624
+ }
625
+ }
626
+
627
+ if (typeof handler !== 'function') return;
628
+
629
+ this.addEventListener(method, handler, {
630
+ [kForOnEventAttribute]: true
631
+ });
632
+ }
633
+ });
634
+ });
635
+
636
+ WebSocket.prototype.addEventListener = addEventListener;
637
+ WebSocket.prototype.removeEventListener = removeEventListener;
638
+
639
+ module.exports = WebSocket;
640
+
641
+ /**
642
+ * Initialize a WebSocket client.
643
+ *
644
+ * @param {WebSocket} websocket The client to initialize
645
+ * @param {(String|URL)} address The URL to which to connect
646
+ * @param {Array} protocols The subprotocols
647
+ * @param {Object} [options] Connection options
648
+ * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether any
649
+ * of the `'message'`, `'ping'`, and `'pong'` events can be emitted multiple
650
+ * times in the same tick
651
+ * @param {Boolean} [options.autoPong=true] Specifies whether or not to
652
+ * automatically send a pong in response to a ping
653
+ * @param {Number} [options.closeTimeout=30000] Duration in milliseconds to wait
654
+ * for the closing handshake to finish after `websocket.close()` is called
655
+ * @param {Function} [options.finishRequest] A function which can be used to
656
+ * customize the headers of each http request before it is sent
657
+ * @param {Boolean} [options.followRedirects=false] Whether or not to follow
658
+ * redirects
659
+ * @param {Function} [options.generateMask] The function used to generate the
660
+ * masking key
661
+ * @param {Number} [options.handshakeTimeout] Timeout in milliseconds for the
662
+ * handshake request
663
+ * @param {Number} [options.maxBufferedChunks=262144] The maximum number of
664
+ * buffered data chunks
665
+ * @param {Number} [options.maxFragments=16384] The maximum number of message
666
+ * fragments
667
+ * @param {Number} [options.maxPayload=104857600] The maximum allowed message
668
+ * size
669
+ * @param {Number} [options.maxRedirects=10] The maximum number of redirects
670
+ * allowed
671
+ * @param {String} [options.origin] Value of the `Origin` or
672
+ * `Sec-WebSocket-Origin` header
673
+ * @param {(Boolean|Object)} [options.perMessageDeflate=true] Enable/disable
674
+ * permessage-deflate
675
+ * @param {Number} [options.protocolVersion=13] Value of the
676
+ * `Sec-WebSocket-Version` header
677
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
678
+ * not to skip UTF-8 validation for text and close messages
679
+ * @private
680
+ */
681
+ function initAsClient(websocket, address, protocols, options) {
682
+ const opts = {
683
+ allowSynchronousEvents: true,
684
+ autoPong: true,
685
+ closeTimeout: CLOSE_TIMEOUT,
686
+ protocolVersion: protocolVersions[1],
687
+ maxBufferedChunks: 256 * 1024,
688
+ maxFragments: 16 * 1024,
689
+ maxPayload: 100 * 1024 * 1024,
690
+ skipUTF8Validation: false,
691
+ perMessageDeflate: true,
692
+ followRedirects: false,
693
+ maxRedirects: 10,
694
+ ...options,
695
+ socketPath: undefined,
696
+ hostname: undefined,
697
+ protocol: undefined,
698
+ protocols: undefined,
699
+ timeout: undefined,
700
+ method: 'GET',
701
+ host: undefined,
702
+ path: undefined,
703
+ port: undefined
704
+ };
705
+
706
+ websocket._autoPong = opts.autoPong;
707
+ websocket._closeTimeout = opts.closeTimeout;
708
+
709
+ if (!protocolVersions.includes(opts.protocolVersion)) {
710
+ throw new RangeError(
711
+ `Unsupported protocol version: ${opts.protocolVersion} ` +
712
+ `(supported versions: ${protocolVersions.join(', ')})`
713
+ );
714
+ }
715
+
716
+ let parsedUrl;
717
+
718
+ if (address instanceof URL) {
719
+ parsedUrl = address;
720
+ } else {
721
+ try {
722
+ parsedUrl = new URL(address);
723
+ } catch {
724
+ throw new SyntaxError(`Invalid URL: ${address}`);
725
+ }
726
+ }
727
+
728
+ if (parsedUrl.protocol === 'http:' || parsedUrl.protocol === 'https:') {
729
+ parsedUrl = new URL(parsedUrl);
730
+ parsedUrl.protocol = parsedUrl.protocol === 'http:' ? 'ws:' : 'wss:';
731
+ }
732
+
733
+ websocket._url = parsedUrl.href;
734
+
735
+ const isSecure = parsedUrl.protocol === 'wss:';
736
+ const isIpcUrl = parsedUrl.protocol === 'ws+unix:';
737
+ let invalidUrlMessage;
738
+
739
+ if (parsedUrl.protocol !== 'ws:' && !isSecure && !isIpcUrl) {
740
+ invalidUrlMessage =
741
+ 'The URL\'s protocol must be one of "ws:", "wss:", ' +
742
+ '"http:", "https:", or "ws+unix:"';
743
+ } else if (isIpcUrl && !parsedUrl.pathname) {
744
+ invalidUrlMessage = "The URL's pathname is empty";
745
+ } else if (parsedUrl.hash) {
746
+ invalidUrlMessage = 'The URL contains a fragment identifier';
747
+ }
748
+
749
+ if (invalidUrlMessage) {
750
+ const err = new SyntaxError(invalidUrlMessage);
751
+
752
+ if (websocket._redirects === 0) {
753
+ throw err;
754
+ } else {
755
+ emitErrorAndClose(websocket, err);
756
+ return;
757
+ }
758
+ }
759
+
760
+ const defaultPort = isSecure ? 443 : 80;
761
+ const key = randomBytes(16).toString('base64');
762
+ const request = isSecure ? https.request : http.request;
763
+ const protocolSet = new Set();
764
+ let perMessageDeflate;
765
+
766
+ opts.createConnection =
767
+ opts.createConnection || (isSecure ? tlsConnect : netConnect);
768
+ opts.defaultPort = opts.defaultPort || defaultPort;
769
+ opts.port = parsedUrl.port || defaultPort;
770
+ opts.host = parsedUrl.hostname.startsWith('[')
771
+ ? parsedUrl.hostname.slice(1, -1)
772
+ : parsedUrl.hostname;
773
+ opts.headers = {
774
+ ...opts.headers,
775
+ 'Sec-WebSocket-Version': opts.protocolVersion,
776
+ 'Sec-WebSocket-Key': key,
777
+ Connection: 'Upgrade',
778
+ Upgrade: 'websocket'
779
+ };
780
+ opts.path = parsedUrl.pathname + parsedUrl.search;
781
+ opts.timeout = opts.handshakeTimeout;
782
+
783
+ if (opts.perMessageDeflate) {
784
+ perMessageDeflate = new PerMessageDeflate({
785
+ ...opts.perMessageDeflate,
786
+ isServer: false,
787
+ maxPayload: opts.maxPayload
788
+ });
789
+ opts.headers['Sec-WebSocket-Extensions'] = format({
790
+ [PerMessageDeflate.extensionName]: perMessageDeflate.offer()
791
+ });
792
+ }
793
+ if (protocols.length) {
794
+ for (const protocol of protocols) {
795
+ if (
796
+ typeof protocol !== 'string' ||
797
+ !subprotocolRegex.test(protocol) ||
798
+ protocolSet.has(protocol)
799
+ ) {
800
+ throw new SyntaxError(
801
+ 'An invalid or duplicated subprotocol was specified'
802
+ );
803
+ }
804
+
805
+ protocolSet.add(protocol);
806
+ }
807
+
808
+ opts.headers['Sec-WebSocket-Protocol'] = protocols.join(',');
809
+ }
810
+ if (opts.origin) {
811
+ if (opts.protocolVersion < 13) {
812
+ opts.headers['Sec-WebSocket-Origin'] = opts.origin;
813
+ } else {
814
+ opts.headers.Origin = opts.origin;
815
+ }
816
+ }
817
+ if (parsedUrl.username || parsedUrl.password) {
818
+ const username = querystring.unescape(parsedUrl.username);
819
+ const password = querystring.unescape(parsedUrl.password);
820
+
821
+ opts.auth = `${username}:${password}`;
822
+ }
823
+
824
+ if (isIpcUrl) {
825
+ const i = opts.path.indexOf(':');
826
+
827
+ if (i === -1) {
828
+ opts.socketPath = opts.path;
829
+ opts.path = '';
830
+ } else {
831
+ opts.socketPath = opts.path.slice(0, i);
832
+ opts.path = opts.path.slice(i + 1);
833
+ }
834
+ }
835
+
836
+ let req;
837
+
838
+ if (opts.followRedirects) {
839
+ if (websocket._redirects === 0) {
840
+ websocket._originalIpc = isIpcUrl;
841
+ websocket._originalSecure = isSecure;
842
+ websocket._originalHostOrSocketPath = isIpcUrl
843
+ ? opts.socketPath
844
+ : parsedUrl.host;
845
+
846
+ const headers = options && options.headers;
847
+
848
+ //
849
+ // Shallow copy the user provided options so that headers can be changed
850
+ // without mutating the original object.
851
+ //
852
+ options = { ...options, headers: {} };
853
+
854
+ if (headers) {
855
+ for (const [key, value] of Object.entries(headers)) {
856
+ options.headers[key.toLowerCase()] = value;
857
+ }
858
+ }
859
+ } else if (websocket.listenerCount('redirect') === 0) {
860
+ const isSameHost = isIpcUrl
861
+ ? websocket._originalIpc
862
+ ? opts.socketPath === websocket._originalHostOrSocketPath
863
+ : false
864
+ : websocket._originalIpc
865
+ ? false
866
+ : parsedUrl.host === websocket._originalHostOrSocketPath;
867
+
868
+ if (!isSameHost || (websocket._originalSecure && !isSecure)) {
869
+ //
870
+ // Match curl 7.77.0 behavior and drop the following headers. These
871
+ // headers are also dropped when following a redirect to a subdomain.
872
+ //
873
+ delete opts.headers.authorization;
874
+ delete opts.headers.cookie;
875
+
876
+ if (!isSameHost) delete opts.headers.host;
877
+
878
+ opts.auth = undefined;
879
+ }
880
+ }
881
+
882
+ //
883
+ // Match curl 7.77.0 behavior and make the first `Authorization` header win.
884
+ // If the `Authorization` header is set, then there is nothing to do as it
885
+ // will take precedence.
886
+ //
887
+ if (opts.auth && !options.headers.authorization) {
888
+ options.headers.authorization =
889
+ 'Basic ' + Buffer.from(opts.auth).toString('base64');
890
+ }
891
+
892
+ req = websocket._req = request(opts);
893
+
894
+ if (websocket._redirects) {
895
+ //
896
+ // Unlike what is done for the `'upgrade'` event, no early exit is
897
+ // triggered here if the user calls `websocket.close()` or
898
+ // `websocket.terminate()` from a listener of the `'redirect'` event. This
899
+ // is because the user can also call `request.destroy()` with an error
900
+ // before calling `websocket.close()` or `websocket.terminate()` and this
901
+ // would result in an error being emitted on the `request` object with no
902
+ // `'error'` event listeners attached.
903
+ //
904
+ websocket.emit('redirect', websocket.url, req);
905
+ }
906
+ } else {
907
+ req = websocket._req = request(opts);
908
+ }
909
+
910
+ if (opts.timeout) {
911
+ req.on('timeout', () => {
912
+ abortHandshake(websocket, req, 'Opening handshake has timed out');
913
+ });
914
+ }
915
+
916
+ req.on('error', (err) => {
917
+ if (req === null || req[kAborted]) return;
918
+
919
+ req = websocket._req = null;
920
+ emitErrorAndClose(websocket, err);
921
+ });
922
+
923
+ req.on('response', (res) => {
924
+ const location = res.headers.location;
925
+ const statusCode = res.statusCode;
926
+
927
+ if (
928
+ location &&
929
+ opts.followRedirects &&
930
+ statusCode >= 300 &&
931
+ statusCode < 400
932
+ ) {
933
+ if (++websocket._redirects > opts.maxRedirects) {
934
+ abortHandshake(websocket, req, 'Maximum redirects exceeded');
935
+ return;
936
+ }
937
+
938
+ req.abort();
939
+
940
+ let addr;
941
+
942
+ try {
943
+ addr = new URL(location, address);
944
+ } catch (e) {
945
+ const err = new SyntaxError(`Invalid URL: ${location}`);
946
+ emitErrorAndClose(websocket, err);
947
+ return;
948
+ }
949
+
950
+ initAsClient(websocket, addr, protocols, options);
951
+ } else if (!websocket.emit('unexpected-response', req, res)) {
952
+ abortHandshake(
953
+ websocket,
954
+ req,
955
+ `Unexpected server response: ${res.statusCode}`
956
+ );
957
+ }
958
+ });
959
+
960
+ req.on('upgrade', (res, socket, head) => {
961
+ websocket.emit('upgrade', res);
962
+
963
+ //
964
+ // The user may have closed the connection from a listener of the
965
+ // `'upgrade'` event.
966
+ //
967
+ if (websocket.readyState !== WebSocket.CONNECTING) return;
968
+
969
+ req = websocket._req = null;
970
+
971
+ const upgrade = res.headers.upgrade;
972
+
973
+ if (upgrade === undefined || upgrade.toLowerCase() !== 'websocket') {
974
+ abortHandshake(websocket, socket, 'Invalid Upgrade header');
975
+ return;
976
+ }
977
+
978
+ const digest = createHash('sha1')
979
+ .update(key + GUID)
980
+ .digest('base64');
981
+
982
+ if (res.headers['sec-websocket-accept'] !== digest) {
983
+ abortHandshake(websocket, socket, 'Invalid Sec-WebSocket-Accept header');
984
+ return;
985
+ }
986
+
987
+ const serverProt = res.headers['sec-websocket-protocol'];
988
+ let protError;
989
+
990
+ if (serverProt !== undefined) {
991
+ if (!protocolSet.size) {
992
+ protError = 'Server sent a subprotocol but none was requested';
993
+ } else if (!protocolSet.has(serverProt)) {
994
+ protError = 'Server sent an invalid subprotocol';
995
+ }
996
+ } else if (protocolSet.size) {
997
+ protError = 'Server sent no subprotocol';
998
+ }
999
+
1000
+ if (protError) {
1001
+ abortHandshake(websocket, socket, protError);
1002
+ return;
1003
+ }
1004
+
1005
+ if (serverProt) websocket._protocol = serverProt;
1006
+
1007
+ const secWebSocketExtensions = res.headers['sec-websocket-extensions'];
1008
+
1009
+ if (secWebSocketExtensions !== undefined) {
1010
+ if (!perMessageDeflate) {
1011
+ const message =
1012
+ 'Server sent a Sec-WebSocket-Extensions header but no extension ' +
1013
+ 'was requested';
1014
+ abortHandshake(websocket, socket, message);
1015
+ return;
1016
+ }
1017
+
1018
+ let extensions;
1019
+
1020
+ try {
1021
+ extensions = parse(secWebSocketExtensions);
1022
+ } catch (err) {
1023
+ const message = 'Invalid Sec-WebSocket-Extensions header';
1024
+ abortHandshake(websocket, socket, message);
1025
+ return;
1026
+ }
1027
+
1028
+ const extensionNames = Object.keys(extensions);
1029
+
1030
+ if (
1031
+ extensionNames.length !== 1 ||
1032
+ extensionNames[0] !== PerMessageDeflate.extensionName
1033
+ ) {
1034
+ const message = 'Server indicated an extension that was not requested';
1035
+ abortHandshake(websocket, socket, message);
1036
+ return;
1037
+ }
1038
+
1039
+ try {
1040
+ perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]);
1041
+ } catch (err) {
1042
+ const message = 'Invalid Sec-WebSocket-Extensions header';
1043
+ abortHandshake(websocket, socket, message);
1044
+ return;
1045
+ }
1046
+
1047
+ websocket._extensions[PerMessageDeflate.extensionName] =
1048
+ perMessageDeflate;
1049
+ }
1050
+
1051
+ websocket.setSocket(socket, head, {
1052
+ allowSynchronousEvents: opts.allowSynchronousEvents,
1053
+ generateMask: opts.generateMask,
1054
+ maxBufferedChunks: opts.maxBufferedChunks,
1055
+ maxFragments: opts.maxFragments,
1056
+ maxPayload: opts.maxPayload,
1057
+ skipUTF8Validation: opts.skipUTF8Validation
1058
+ });
1059
+ });
1060
+
1061
+ if (opts.finishRequest) {
1062
+ opts.finishRequest(req, websocket);
1063
+ } else {
1064
+ req.end();
1065
+ }
1066
+ }
1067
+
1068
+ /**
1069
+ * Emit the `'error'` and `'close'` events.
1070
+ *
1071
+ * @param {WebSocket} websocket The WebSocket instance
1072
+ * @param {Error} The error to emit
1073
+ * @private
1074
+ */
1075
+ function emitErrorAndClose(websocket, err) {
1076
+ websocket._readyState = WebSocket.CLOSING;
1077
+ //
1078
+ // The following assignment is practically useless and is done only for
1079
+ // consistency.
1080
+ //
1081
+ websocket._errorEmitted = true;
1082
+ websocket.emit('error', err);
1083
+ websocket.emitClose();
1084
+ }
1085
+
1086
+ /**
1087
+ * Create a `net.Socket` and initiate a connection.
1088
+ *
1089
+ * @param {Object} options Connection options
1090
+ * @return {net.Socket} The newly created socket used to start the connection
1091
+ * @private
1092
+ */
1093
+ function netConnect(options) {
1094
+ options.path = options.socketPath;
1095
+ return net.connect(options);
1096
+ }
1097
+
1098
+ /**
1099
+ * Create a `tls.TLSSocket` and initiate a connection.
1100
+ *
1101
+ * @param {Object} options Connection options
1102
+ * @return {tls.TLSSocket} The newly created socket used to start the connection
1103
+ * @private
1104
+ */
1105
+ function tlsConnect(options) {
1106
+ options.path = undefined;
1107
+
1108
+ if (!options.servername && options.servername !== '') {
1109
+ options.servername = net.isIP(options.host) ? '' : options.host;
1110
+ }
1111
+
1112
+ return tls.connect(options);
1113
+ }
1114
+
1115
+ /**
1116
+ * Abort the handshake and emit an error.
1117
+ *
1118
+ * @param {WebSocket} websocket The WebSocket instance
1119
+ * @param {(http.ClientRequest|net.Socket|tls.Socket)} stream The request to
1120
+ * abort or the socket to destroy
1121
+ * @param {String} message The error message
1122
+ * @private
1123
+ */
1124
+ function abortHandshake(websocket, stream, message) {
1125
+ websocket._readyState = WebSocket.CLOSING;
1126
+
1127
+ const err = new Error(message);
1128
+ Error.captureStackTrace(err, abortHandshake);
1129
+
1130
+ if (stream.setHeader) {
1131
+ stream[kAborted] = true;
1132
+ stream.abort();
1133
+
1134
+ if (stream.socket && !stream.socket.destroyed) {
1135
+ //
1136
+ // On Node.js >= 14.3.0 `request.abort()` does not destroy the socket if
1137
+ // called after the request completed. See
1138
+ // https://github.com/websockets/ws/issues/1869.
1139
+ //
1140
+ stream.socket.destroy();
1141
+ }
1142
+
1143
+ process.nextTick(emitErrorAndClose, websocket, err);
1144
+ } else {
1145
+ stream.destroy(err);
1146
+ stream.once('error', websocket.emit.bind(websocket, 'error'));
1147
+ stream.once('close', websocket.emitClose.bind(websocket));
1148
+ }
1149
+ }
1150
+
1151
+ /**
1152
+ * Handle cases where the `ping()`, `pong()`, or `send()` methods are called
1153
+ * when the `readyState` attribute is `CLOSING` or `CLOSED`.
1154
+ *
1155
+ * @param {WebSocket} websocket The WebSocket instance
1156
+ * @param {*} [data] The data to send
1157
+ * @param {Function} [cb] Callback
1158
+ * @private
1159
+ */
1160
+ function sendAfterClose(websocket, data, cb) {
1161
+ if (data) {
1162
+ const length = isBlob(data) ? data.size : toBuffer(data).length;
1163
+
1164
+ //
1165
+ // The `_bufferedAmount` property is used only when the peer is a client and
1166
+ // the opening handshake fails. Under these circumstances, in fact, the
1167
+ // `setSocket()` method is not called, so the `_socket` and `_sender`
1168
+ // properties are set to `null`.
1169
+ //
1170
+ if (websocket._socket) websocket._sender._bufferedBytes += length;
1171
+ else websocket._bufferedAmount += length;
1172
+ }
1173
+
1174
+ if (cb) {
1175
+ const err = new Error(
1176
+ `WebSocket is not open: readyState ${websocket.readyState} ` +
1177
+ `(${readyStates[websocket.readyState]})`
1178
+ );
1179
+ process.nextTick(cb, err);
1180
+ }
1181
+ }
1182
+
1183
+ /**
1184
+ * The listener of the `Receiver` `'conclude'` event.
1185
+ *
1186
+ * @param {Number} code The status code
1187
+ * @param {Buffer} reason The reason for closing
1188
+ * @private
1189
+ */
1190
+ function receiverOnConclude(code, reason) {
1191
+ const websocket = this[kWebSocket];
1192
+
1193
+ websocket._closeFrameReceived = true;
1194
+ websocket._closeCode = code;
1195
+
1196
+ //
1197
+ // The reason is a view into the buffer the socket delivered. Copy it so that
1198
+ // the `WebSocket` does not keep that buffer alive. The copy is not pooled
1199
+ // because a pooled one would keep the pool alive in the same way.
1200
+ //
1201
+ if (reason.length === 0) {
1202
+ websocket._closeMessage = EMPTY_BUFFER;
1203
+ } else {
1204
+ websocket._closeMessage = Buffer.allocUnsafeSlow(reason.length);
1205
+ websocket._closeMessage.set(reason);
1206
+ }
1207
+
1208
+ if (websocket._socket[kWebSocket] === undefined) return;
1209
+
1210
+ websocket._socket.removeListener('data', socketOnData);
1211
+ process.nextTick(resume, websocket._socket);
1212
+
1213
+ if (code === 1005) websocket.close();
1214
+ else websocket.close(code, reason);
1215
+ }
1216
+
1217
+ /**
1218
+ * The listener of the `Receiver` `'drain'` event.
1219
+ *
1220
+ * @private
1221
+ */
1222
+ function receiverOnDrain() {
1223
+ const websocket = this[kWebSocket];
1224
+
1225
+ if (!websocket.isPaused) websocket._socket.resume();
1226
+ }
1227
+
1228
+ /**
1229
+ * The listener of the `Receiver` `'error'` event.
1230
+ *
1231
+ * @param {(RangeError|Error)} err The emitted error
1232
+ * @private
1233
+ */
1234
+ function receiverOnError(err) {
1235
+ const websocket = this[kWebSocket];
1236
+
1237
+ if (websocket._socket[kWebSocket] !== undefined) {
1238
+ websocket._socket.removeListener('data', socketOnData);
1239
+
1240
+ //
1241
+ // On Node.js < 14.0.0 the `'error'` event is emitted synchronously. See
1242
+ // https://github.com/websockets/ws/issues/1940.
1243
+ //
1244
+ process.nextTick(resume, websocket._socket);
1245
+
1246
+ websocket.close(err[kStatusCode]);
1247
+ }
1248
+
1249
+ if (!websocket._errorEmitted) {
1250
+ websocket._errorEmitted = true;
1251
+ websocket.emit('error', err);
1252
+ }
1253
+ }
1254
+
1255
+ /**
1256
+ * The listener of the `Receiver` `'finish'` event.
1257
+ *
1258
+ * @private
1259
+ */
1260
+ function receiverOnFinish() {
1261
+ this[kWebSocket].emitClose();
1262
+ }
1263
+
1264
+ /**
1265
+ * The listener of the `Receiver` `'message'` event.
1266
+ *
1267
+ * @param {Buffer|ArrayBuffer|Buffer[])} data The message
1268
+ * @param {Boolean} isBinary Specifies whether the message is binary or not
1269
+ * @private
1270
+ */
1271
+ function receiverOnMessage(data, isBinary) {
1272
+ this[kWebSocket].emit('message', data, isBinary);
1273
+ }
1274
+
1275
+ /**
1276
+ * The listener of the `Receiver` `'ping'` event.
1277
+ *
1278
+ * @param {Buffer} data The data included in the ping frame
1279
+ * @private
1280
+ */
1281
+ function receiverOnPing(data) {
1282
+ const websocket = this[kWebSocket];
1283
+
1284
+ if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP);
1285
+ websocket.emit('ping', data);
1286
+ }
1287
+
1288
+ /**
1289
+ * The listener of the `Receiver` `'pong'` event.
1290
+ *
1291
+ * @param {Buffer} data The data included in the pong frame
1292
+ * @private
1293
+ */
1294
+ function receiverOnPong(data) {
1295
+ this[kWebSocket].emit('pong', data);
1296
+ }
1297
+
1298
+ /**
1299
+ * Resume a readable stream
1300
+ *
1301
+ * @param {Readable} stream The readable stream
1302
+ * @private
1303
+ */
1304
+ function resume(stream) {
1305
+ stream.resume();
1306
+ }
1307
+
1308
+ /**
1309
+ * The `Sender` error event handler.
1310
+ *
1311
+ * @param {Error} The error
1312
+ * @private
1313
+ */
1314
+ function senderOnError(err) {
1315
+ const websocket = this[kWebSocket];
1316
+
1317
+ if (websocket.readyState === WebSocket.CLOSED) return;
1318
+ if (websocket.readyState === WebSocket.OPEN) {
1319
+ websocket._readyState = WebSocket.CLOSING;
1320
+ setCloseTimer(websocket);
1321
+ }
1322
+
1323
+ //
1324
+ // `socket.end()` is used instead of `socket.destroy()` to allow the other
1325
+ // peer to finish sending queued data. There is no need to set a timer here
1326
+ // because `CLOSING` means that it is already set or not needed.
1327
+ //
1328
+ this._socket.end();
1329
+
1330
+ if (!websocket._errorEmitted) {
1331
+ websocket._errorEmitted = true;
1332
+ websocket.emit('error', err);
1333
+ }
1334
+ }
1335
+
1336
+ /**
1337
+ * Set a timer to destroy the underlying raw socket of a WebSocket.
1338
+ *
1339
+ * @param {WebSocket} websocket The WebSocket instance
1340
+ * @private
1341
+ */
1342
+ function setCloseTimer(websocket) {
1343
+ websocket._closeTimer = setTimeout(
1344
+ websocket._socket.destroy.bind(websocket._socket),
1345
+ websocket._closeTimeout
1346
+ );
1347
+ }
1348
+
1349
+ /**
1350
+ * The listener of the socket `'close'` event.
1351
+ *
1352
+ * @private
1353
+ */
1354
+ function socketOnClose() {
1355
+ const websocket = this[kWebSocket];
1356
+
1357
+ this.removeListener('close', socketOnClose);
1358
+ this.removeListener('data', socketOnData);
1359
+ this.removeListener('end', socketOnEnd);
1360
+
1361
+ websocket._readyState = WebSocket.CLOSING;
1362
+
1363
+ //
1364
+ // The close frame might not have been received or the `'end'` event emitted,
1365
+ // for example, if the socket was destroyed due to an error. Ensure that the
1366
+ // `receiver` stream is closed after writing any remaining buffered data to
1367
+ // it. If the readable side of the socket is in flowing mode then there is no
1368
+ // buffered data as everything has been already written. If instead, the
1369
+ // socket is paused, any possible buffered data will be read as a single
1370
+ // chunk.
1371
+ //
1372
+ if (
1373
+ !this._readableState.endEmitted &&
1374
+ !websocket._closeFrameReceived &&
1375
+ !websocket._receiver._writableState.errorEmitted &&
1376
+ this._readableState.length !== 0
1377
+ ) {
1378
+ const chunk = this.read(this._readableState.length);
1379
+
1380
+ websocket._receiver.write(chunk);
1381
+ }
1382
+
1383
+ websocket._receiver.end();
1384
+
1385
+ this[kWebSocket] = undefined;
1386
+
1387
+ clearTimeout(websocket._closeTimer);
1388
+
1389
+ if (
1390
+ websocket._receiver._writableState.finished ||
1391
+ websocket._receiver._writableState.errorEmitted
1392
+ ) {
1393
+ websocket.emitClose();
1394
+ } else {
1395
+ websocket._receiver.on('error', receiverOnFinish);
1396
+ websocket._receiver.on('finish', receiverOnFinish);
1397
+ }
1398
+ }
1399
+
1400
+ /**
1401
+ * The listener of the socket `'data'` event.
1402
+ *
1403
+ * @param {Buffer} chunk A chunk of data
1404
+ * @private
1405
+ */
1406
+ function socketOnData(chunk) {
1407
+ if (!this[kWebSocket]._receiver.write(chunk)) {
1408
+ this.pause();
1409
+ }
1410
+ }
1411
+
1412
+ /**
1413
+ * The listener of the socket `'end'` event.
1414
+ *
1415
+ * @private
1416
+ */
1417
+ function socketOnEnd() {
1418
+ const websocket = this[kWebSocket];
1419
+
1420
+ websocket._readyState = WebSocket.CLOSING;
1421
+ websocket._receiver.end();
1422
+ this.end();
1423
+ }
1424
+
1425
+ /**
1426
+ * The listener of the socket `'error'` event.
1427
+ *
1428
+ * @private
1429
+ */
1430
+ function socketOnError() {
1431
+ const websocket = this[kWebSocket];
1432
+
1433
+ this.removeListener('error', socketOnError);
1434
+ this.on('error', NOOP);
1435
+
1436
+ if (websocket) {
1437
+ websocket._readyState = WebSocket.CLOSING;
1438
+ this.destroy();
1439
+ }
1440
+ }