ns-auth-sdk 1.14.0 → 1.14.2

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 (153) hide show
  1. package/dist/{cjs-CSUAVztq.cjs → browser-index.cjs} +5476 -296
  2. package/dist/browser-index.cjs.map +1 -0
  3. package/dist/browser-index.d.cts +1998 -0
  4. package/dist/browser-index.d.cts.map +1 -0
  5. package/dist/browser-index.d.mts +1998 -0
  6. package/dist/browser-index.d.mts.map +1 -0
  7. package/dist/{cjs-sm5h7qxv.mjs → browser-index.mjs} +5169 -69
  8. package/dist/browser-index.mjs.map +1 -0
  9. package/dist/{group-coordination-BlFpBVpn.mjs → group-coordination-BV6PKlKp.mjs} +1 -1
  10. package/dist/{group-coordination-BlFpBVpn.mjs.map → group-coordination-BV6PKlKp.mjs.map} +1 -1
  11. package/dist/{group-coordination-ImuoJEoy.mjs → group-coordination-BytkmY9j.mjs} +1 -1
  12. package/dist/{group-coordination-LGIyipaX.cjs → group-coordination-DL39hJ3R.cjs} +1 -1
  13. package/dist/{group-coordination-LGIyipaX.cjs.map → group-coordination-DL39hJ3R.cjs.map} +1 -1
  14. package/dist/{group-coordination-Cf18OjZt.cjs → group-coordination-DLban6a7.cjs} +1 -1
  15. package/dist/index.cjs +8899 -41
  16. package/dist/index.cjs.map +1 -1
  17. package/dist/index.d.cts.map +1 -1
  18. package/dist/index.mjs +9072 -213
  19. package/dist/index.mjs.map +1 -1
  20. package/dist/{prf-handler-D3EqUNWe.cjs → prf-handler-BNd7gmXJ.cjs} +1 -1
  21. package/dist/{prf-handler-D3EqUNWe.cjs.map → prf-handler-BNd7gmXJ.cjs.map} +1 -1
  22. package/dist/prf-handler-CRMgzJG2.cjs +3 -0
  23. package/dist/{prf-handler-Dly_WZGn.mjs → prf-handler-DG99ZkS2.mjs} +1 -1
  24. package/dist/{prf-handler-Db8CsoIP.mjs → prf-handler-Dj2WTO9i.mjs} +1 -1
  25. package/dist/{prf-handler-Db8CsoIP.mjs.map → prf-handler-Dj2WTO9i.mjs.map} +1 -1
  26. package/dist/zkm.service-Bv88tVS5.mjs +3 -0
  27. package/dist/zkm.service-D2BZ_aqA.cjs +3 -0
  28. package/dist/{zkm.service-DfSPbuOl.cjs → zkm.service-DX06sSfB.cjs} +1 -1
  29. package/dist/{zkm.service-DfSPbuOl.cjs.map → zkm.service-DX06sSfB.cjs.map} +1 -1
  30. package/dist/{zkm.service-B24N_0FB.mjs → zkm.service-j0HlN7Oq.mjs} +1 -1
  31. package/dist/{zkm.service-B24N_0FB.mjs.map → zkm.service-j0HlN7Oq.mjs.map} +1 -1
  32. package/package.json +19 -6
  33. package/dist/_esm-C7FRLTj2.cjs +0 -9030
  34. package/dist/_esm-C7FRLTj2.cjs.map +0 -1
  35. package/dist/_esm-D_oMW5T5.mjs +0 -9028
  36. package/dist/_esm-D_oMW5T5.mjs.map +0 -1
  37. package/dist/base64-js-B8y7dH5k.mjs +0 -93
  38. package/dist/base64-js-B8y7dH5k.mjs.map +0 -1
  39. package/dist/base64-js-Tm-kCeud.cjs +0 -98
  40. package/dist/base64-js-Tm-kCeud.cjs.map +0 -1
  41. package/dist/ccip-157tdxqP.cjs +0 -7947
  42. package/dist/ccip-157tdxqP.cjs.map +0 -1
  43. package/dist/ccip-BEMMdVyd.cjs +0 -4
  44. package/dist/ccip-BSmCdJ3K.mjs +0 -3
  45. package/dist/ccip-okqXkslP.mjs +0 -6567
  46. package/dist/ccip-okqXkslP.mjs.map +0 -1
  47. package/dist/chains-CTeD2UcS.mjs +0 -33
  48. package/dist/chains-CTeD2UcS.mjs.map +0 -1
  49. package/dist/chains-Du-lv_5i.cjs +0 -33
  50. package/dist/chains-Du-lv_5i.cjs.map +0 -1
  51. package/dist/chunk-Bnu9O96Y.cjs +0 -60
  52. package/dist/chunk-CVYhg9ik.mjs +0 -45
  53. package/dist/cjs-CSUAVztq.cjs.map +0 -1
  54. package/dist/cjs-sm5h7qxv.mjs.map +0 -1
  55. package/dist/defineChain-7QG67hYU.cjs +0 -30
  56. package/dist/defineChain-7QG67hYU.cjs.map +0 -1
  57. package/dist/defineChain-DBem8ZQY.mjs +0 -24
  58. package/dist/defineChain-DBem8ZQY.mjs.map +0 -1
  59. package/dist/dist-BPmSxkxc.cjs +0 -10676
  60. package/dist/dist-BPmSxkxc.cjs.map +0 -1
  61. package/dist/dist-BSjH4t6s.cjs +0 -12932
  62. package/dist/dist-BSjH4t6s.cjs.map +0 -1
  63. package/dist/dist-C-KjTK4Q.cjs +0 -447
  64. package/dist/dist-C-KjTK4Q.cjs.map +0 -1
  65. package/dist/dist-C2h97xM-.mjs +0 -355
  66. package/dist/dist-C2h97xM-.mjs.map +0 -1
  67. package/dist/dist-CT7grDWb.mjs +0 -12920
  68. package/dist/dist-CT7grDWb.mjs.map +0 -1
  69. package/dist/dist-D7fRmK6G.mjs +0 -10632
  70. package/dist/dist-D7fRmK6G.mjs.map +0 -1
  71. package/dist/dist-DlmcyFmM.mjs +0 -16951
  72. package/dist/dist-DlmcyFmM.mjs.map +0 -1
  73. package/dist/dist-O0uZr5OF.cjs +0 -17122
  74. package/dist/dist-O0uZr5OF.cjs.map +0 -1
  75. package/dist/echo-BB-JgAYZ.cjs +0 -339
  76. package/dist/echo-BB-JgAYZ.cjs.map +0 -1
  77. package/dist/echo-Bwy4_Cvh.mjs +0 -316
  78. package/dist/echo-Bwy4_Cvh.mjs.map +0 -1
  79. package/dist/echo-D6X2IuNW.cjs +0 -9
  80. package/dist/echo-DvfG_heb.mjs +0 -8
  81. package/dist/esm-BcHKCX5i.mjs +0 -569
  82. package/dist/esm-BcHKCX5i.mjs.map +0 -1
  83. package/dist/esm-Bh_YwFIz.cjs +0 -599
  84. package/dist/esm-Bh_YwFIz.cjs.map +0 -1
  85. package/dist/esm-C0XO9TQm.cjs +0 -30449
  86. package/dist/esm-C0XO9TQm.cjs.map +0 -1
  87. package/dist/esm-vMUVj9k4.mjs +0 -30440
  88. package/dist/esm-vMUVj9k4.mjs.map +0 -1
  89. package/dist/keyset-CKMQXvsb.mjs +0 -172
  90. package/dist/keyset-CKMQXvsb.mjs.map +0 -1
  91. package/dist/keyset-Cxdgu110.cjs +0 -237
  92. package/dist/keyset-Cxdgu110.cjs.map +0 -1
  93. package/dist/keyset-DLxpGhdu.cjs +0 -6
  94. package/dist/keyset-IKjlhvqF.mjs +0 -4
  95. package/dist/node-3EUJ4ga9.cjs +0 -9
  96. package/dist/node-C2UpE11T.cjs +0 -444
  97. package/dist/node-C2UpE11T.cjs.map +0 -1
  98. package/dist/node-CHdpTQdN.mjs +0 -8679
  99. package/dist/node-CHdpTQdN.mjs.map +0 -1
  100. package/dist/node-DQt1CVGl.mjs +0 -6
  101. package/dist/node-Dy8ww1LG.cjs +0 -8680
  102. package/dist/node-Dy8ww1LG.cjs.map +0 -1
  103. package/dist/node-IX55IH6z.mjs +0 -397
  104. package/dist/node-IX55IH6z.mjs.map +0 -1
  105. package/dist/nostr-BTOpBN_5.cjs +0 -11
  106. package/dist/nostr-D4E52XRU.mjs +0 -224
  107. package/dist/nostr-D4E52XRU.mjs.map +0 -1
  108. package/dist/nostr-Hv2tsnuI.cjs +0 -272
  109. package/dist/nostr-Hv2tsnuI.cjs.map +0 -1
  110. package/dist/nostr-ZwJe_DlZ.mjs +0 -4
  111. package/dist/pako.esm-DTVnlCJh.cjs +0 -3856
  112. package/dist/pako.esm-DTVnlCJh.cjs.map +0 -1
  113. package/dist/pako.esm-ORhkEHM2.mjs +0 -3838
  114. package/dist/pako.esm-ORhkEHM2.mjs.map +0 -1
  115. package/dist/peer-B9g3OQ5D.cjs +0 -18
  116. package/dist/peer-CptDj7zu.mjs +0 -745
  117. package/dist/peer-CptDj7zu.mjs.map +0 -1
  118. package/dist/peer-CtqL0yiE.mjs +0 -9
  119. package/dist/peer-XrPL0O6z.cjs +0 -822
  120. package/dist/peer-XrPL0O6z.cjs.map +0 -1
  121. package/dist/ping-BXKREIdI.mjs +0 -7
  122. package/dist/ping-BtVhKocl.cjs +0 -379
  123. package/dist/ping-BtVhKocl.cjs.map +0 -1
  124. package/dist/ping-D5fpMhGC.cjs +0 -11
  125. package/dist/ping-DOD50kW_.mjs +0 -332
  126. package/dist/ping-DOD50kW_.mjs.map +0 -1
  127. package/dist/policy-8HcjulLD.cjs +0 -293
  128. package/dist/policy-8HcjulLD.cjs.map +0 -1
  129. package/dist/policy-BA6MEOBY.mjs +0 -5
  130. package/dist/policy-BFNdXvmM.cjs +0 -11
  131. package/dist/policy-D_nFHHjo.mjs +0 -228
  132. package/dist/policy-D_nFHHjo.mjs.map +0 -1
  133. package/dist/prf-handler-BNiyCQMt.cjs +0 -3
  134. package/dist/src-CVfTUJQl.mjs +0 -822
  135. package/dist/src-CVfTUJQl.mjs.map +0 -1
  136. package/dist/src-D5S86Xpf.cjs +0 -827
  137. package/dist/src-D5S86Xpf.cjs.map +0 -1
  138. package/dist/types-B-TLIS13.cjs +0 -212
  139. package/dist/types-B-TLIS13.cjs.map +0 -1
  140. package/dist/types-CTm_FHYD.mjs +0 -111
  141. package/dist/types-CTm_FHYD.mjs.map +0 -1
  142. package/dist/validation-1xwWVXqE.mjs +0 -3
  143. package/dist/validation-DnpurN79.cjs +0 -405
  144. package/dist/validation-DnpurN79.cjs.map +0 -1
  145. package/dist/validation-IsAUvsvy.mjs +0 -334
  146. package/dist/validation-IsAUvsvy.mjs.map +0 -1
  147. package/dist/validation-yCvZCqIs.cjs +0 -6
  148. package/dist/wrapper-C5NpyacC.cjs +0 -3552
  149. package/dist/wrapper-C5NpyacC.cjs.map +0 -1
  150. package/dist/wrapper-CHq_CV4J.mjs +0 -3552
  151. package/dist/wrapper-CHq_CV4J.mjs.map +0 -1
  152. package/dist/zkm.service-BrXyI4BS.mjs +0 -3
  153. package/dist/zkm.service-BvQ01wSH.cjs +0 -3
@@ -1,3552 +0,0 @@
1
- import { i as __toESM, r as __require, t as __commonJSMin } from "./chunk-CVYhg9ik.mjs";
2
-
3
- //#region node_modules/ws/lib/constants.js
4
- var require_constants = /* @__PURE__ */ __commonJSMin(((exports, module) => {
5
- const BINARY_TYPES = [
6
- "nodebuffer",
7
- "arraybuffer",
8
- "fragments"
9
- ];
10
- const hasBlob = typeof Blob !== "undefined";
11
- if (hasBlob) BINARY_TYPES.push("blob");
12
- module.exports = {
13
- BINARY_TYPES,
14
- CLOSE_TIMEOUT: 3e4,
15
- EMPTY_BUFFER: Buffer.alloc(0),
16
- GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
17
- hasBlob,
18
- kForOnEventAttribute: Symbol("kIsForOnEventAttribute"),
19
- kListener: Symbol("kListener"),
20
- kStatusCode: Symbol("status-code"),
21
- kWebSocket: Symbol("websocket"),
22
- NOOP: () => {}
23
- };
24
- }));
25
-
26
- //#endregion
27
- //#region node_modules/ws/lib/buffer-util.js
28
- var require_buffer_util = /* @__PURE__ */ __commonJSMin(((exports, module) => {
29
- const { EMPTY_BUFFER } = require_constants();
30
- const FastBuffer = Buffer[Symbol.species];
31
- /**
32
- * Merges an array of buffers into a new buffer.
33
- *
34
- * @param {Buffer[]} list The array of buffers to concat
35
- * @param {Number} totalLength The total length of buffers in the list
36
- * @return {Buffer} The resulting buffer
37
- * @public
38
- */
39
- function concat(list, totalLength) {
40
- if (list.length === 0) return EMPTY_BUFFER;
41
- if (list.length === 1) return list[0];
42
- const target = Buffer.allocUnsafe(totalLength);
43
- let offset = 0;
44
- for (let i = 0; i < list.length; i++) {
45
- const buf = list[i];
46
- target.set(buf, offset);
47
- offset += buf.length;
48
- }
49
- if (offset < totalLength) return new FastBuffer(target.buffer, target.byteOffset, offset);
50
- return target;
51
- }
52
- /**
53
- * Masks a buffer using the given mask.
54
- *
55
- * @param {Buffer} source The buffer to mask
56
- * @param {Buffer} mask The mask to use
57
- * @param {Buffer} output The buffer where to store the result
58
- * @param {Number} offset The offset at which to start writing
59
- * @param {Number} length The number of bytes to mask.
60
- * @public
61
- */
62
- function _mask(source, mask, output, offset, length) {
63
- for (let i = 0; i < length; i++) output[offset + i] = source[i] ^ mask[i & 3];
64
- }
65
- /**
66
- * Unmasks a buffer using the given mask.
67
- *
68
- * @param {Buffer} buffer The buffer to unmask
69
- * @param {Buffer} mask The mask to use
70
- * @public
71
- */
72
- function _unmask(buffer, mask) {
73
- for (let i = 0; i < buffer.length; i++) buffer[i] ^= mask[i & 3];
74
- }
75
- /**
76
- * Converts a buffer to an `ArrayBuffer`.
77
- *
78
- * @param {Buffer} buf The buffer to convert
79
- * @return {ArrayBuffer} Converted buffer
80
- * @public
81
- */
82
- function toArrayBuffer(buf) {
83
- if (buf.length === buf.buffer.byteLength) return buf.buffer;
84
- return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);
85
- }
86
- /**
87
- * Converts `data` to a `Buffer`.
88
- *
89
- * @param {*} data The data to convert
90
- * @return {Buffer} The buffer
91
- * @throws {TypeError}
92
- * @public
93
- */
94
- function toBuffer(data) {
95
- toBuffer.readOnly = true;
96
- if (Buffer.isBuffer(data)) return data;
97
- let buf;
98
- if (data instanceof ArrayBuffer) buf = new FastBuffer(data);
99
- else if (ArrayBuffer.isView(data)) buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);
100
- else {
101
- buf = Buffer.from(data);
102
- toBuffer.readOnly = false;
103
- }
104
- return buf;
105
- }
106
- module.exports = {
107
- concat,
108
- mask: _mask,
109
- toArrayBuffer,
110
- toBuffer,
111
- unmask: _unmask
112
- };
113
- /* istanbul ignore else */
114
- if (!process.env.WS_NO_BUFFER_UTIL) try {
115
- const bufferUtil = __require("bufferutil");
116
- module.exports.mask = function(source, mask, output, offset, length) {
117
- if (length < 48) _mask(source, mask, output, offset, length);
118
- else bufferUtil.mask(source, mask, output, offset, length);
119
- };
120
- module.exports.unmask = function(buffer, mask) {
121
- if (buffer.length < 32) _unmask(buffer, mask);
122
- else bufferUtil.unmask(buffer, mask);
123
- };
124
- } catch (e) {}
125
- }));
126
-
127
- //#endregion
128
- //#region node_modules/ws/lib/limiter.js
129
- var require_limiter = /* @__PURE__ */ __commonJSMin(((exports, module) => {
130
- const kDone = Symbol("kDone");
131
- const kRun = Symbol("kRun");
132
- /**
133
- * A very simple job queue with adjustable concurrency. Adapted from
134
- * https://github.com/STRML/async-limiter
135
- */
136
- var Limiter = class {
137
- /**
138
- * Creates a new `Limiter`.
139
- *
140
- * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed
141
- * to run concurrently
142
- */
143
- constructor(concurrency) {
144
- this[kDone] = () => {
145
- this.pending--;
146
- this[kRun]();
147
- };
148
- this.concurrency = concurrency || Infinity;
149
- this.jobs = [];
150
- this.pending = 0;
151
- }
152
- /**
153
- * Adds a job to the queue.
154
- *
155
- * @param {Function} job The job to run
156
- * @public
157
- */
158
- add(job) {
159
- this.jobs.push(job);
160
- this[kRun]();
161
- }
162
- /**
163
- * Removes a job from the queue and runs it if possible.
164
- *
165
- * @private
166
- */
167
- [kRun]() {
168
- if (this.pending === this.concurrency) return;
169
- if (this.jobs.length) {
170
- const job = this.jobs.shift();
171
- this.pending++;
172
- job(this[kDone]);
173
- }
174
- }
175
- };
176
- module.exports = Limiter;
177
- }));
178
-
179
- //#endregion
180
- //#region node_modules/ws/lib/permessage-deflate.js
181
- var require_permessage_deflate = /* @__PURE__ */ __commonJSMin(((exports, module) => {
182
- const zlib = __require("zlib");
183
- const bufferUtil = require_buffer_util();
184
- const Limiter = require_limiter();
185
- const { kStatusCode } = require_constants();
186
- const FastBuffer = Buffer[Symbol.species];
187
- const TRAILER = Buffer.from([
188
- 0,
189
- 0,
190
- 255,
191
- 255
192
- ]);
193
- const kPerMessageDeflate = Symbol("permessage-deflate");
194
- const kTotalLength = Symbol("total-length");
195
- const kCallback = Symbol("callback");
196
- const kBuffers = Symbol("buffers");
197
- const kError = Symbol("error");
198
- let zlibLimiter;
199
- /**
200
- * permessage-deflate implementation.
201
- */
202
- var PerMessageDeflate = class {
203
- /**
204
- * Creates a PerMessageDeflate instance.
205
- *
206
- * @param {Object} [options] Configuration options
207
- * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support
208
- * for, or request, a custom client window size
209
- * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/
210
- * acknowledge disabling of client context takeover
211
- * @param {Number} [options.concurrencyLimit=10] The number of concurrent
212
- * calls to zlib
213
- * @param {Boolean} [options.isServer=false] Create the instance in either
214
- * server or client mode
215
- * @param {Number} [options.maxPayload=0] The maximum allowed message length
216
- * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the
217
- * use of a custom server window size
218
- * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept
219
- * disabling of server context takeover
220
- * @param {Number} [options.threshold=1024] Size (in bytes) below which
221
- * messages should not be compressed if context takeover is disabled
222
- * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on
223
- * deflate
224
- * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on
225
- * inflate
226
- */
227
- constructor(options) {
228
- this._options = options || {};
229
- this._threshold = this._options.threshold !== void 0 ? this._options.threshold : 1024;
230
- this._maxPayload = this._options.maxPayload | 0;
231
- this._isServer = !!this._options.isServer;
232
- this._deflate = null;
233
- this._inflate = null;
234
- this.params = null;
235
- if (!zlibLimiter) zlibLimiter = new Limiter(this._options.concurrencyLimit !== void 0 ? this._options.concurrencyLimit : 10);
236
- }
237
- /**
238
- * @type {String}
239
- */
240
- static get extensionName() {
241
- return "permessage-deflate";
242
- }
243
- /**
244
- * Create an extension negotiation offer.
245
- *
246
- * @return {Object} Extension parameters
247
- * @public
248
- */
249
- offer() {
250
- const params = {};
251
- if (this._options.serverNoContextTakeover) params.server_no_context_takeover = true;
252
- if (this._options.clientNoContextTakeover) params.client_no_context_takeover = true;
253
- if (this._options.serverMaxWindowBits) params.server_max_window_bits = this._options.serverMaxWindowBits;
254
- if (this._options.clientMaxWindowBits) params.client_max_window_bits = this._options.clientMaxWindowBits;
255
- else if (this._options.clientMaxWindowBits == null) params.client_max_window_bits = true;
256
- return params;
257
- }
258
- /**
259
- * Accept an extension negotiation offer/response.
260
- *
261
- * @param {Array} configurations The extension negotiation offers/reponse
262
- * @return {Object} Accepted configuration
263
- * @public
264
- */
265
- accept(configurations) {
266
- configurations = this.normalizeParams(configurations);
267
- this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations);
268
- return this.params;
269
- }
270
- /**
271
- * Releases all resources used by the extension.
272
- *
273
- * @public
274
- */
275
- cleanup() {
276
- if (this._inflate) {
277
- this._inflate.close();
278
- this._inflate = null;
279
- }
280
- if (this._deflate) {
281
- const callback = this._deflate[kCallback];
282
- this._deflate.close();
283
- this._deflate = null;
284
- if (callback) callback(/* @__PURE__ */ new Error("The deflate stream was closed while data was being processed"));
285
- }
286
- }
287
- /**
288
- * Accept an extension negotiation offer.
289
- *
290
- * @param {Array} offers The extension negotiation offers
291
- * @return {Object} Accepted configuration
292
- * @private
293
- */
294
- acceptAsServer(offers) {
295
- const opts = this._options;
296
- const accepted = offers.find((params) => {
297
- if (opts.serverNoContextTakeover === false && params.server_no_context_takeover || params.server_max_window_bits && (opts.serverMaxWindowBits === false || typeof opts.serverMaxWindowBits === "number" && opts.serverMaxWindowBits > params.server_max_window_bits) || typeof opts.clientMaxWindowBits === "number" && !params.client_max_window_bits) return false;
298
- return true;
299
- });
300
- if (!accepted) throw new Error("None of the extension offers can be accepted");
301
- if (opts.serverNoContextTakeover) accepted.server_no_context_takeover = true;
302
- if (opts.clientNoContextTakeover) accepted.client_no_context_takeover = true;
303
- if (typeof opts.serverMaxWindowBits === "number") accepted.server_max_window_bits = opts.serverMaxWindowBits;
304
- if (typeof opts.clientMaxWindowBits === "number") accepted.client_max_window_bits = opts.clientMaxWindowBits;
305
- else if (accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false) delete accepted.client_max_window_bits;
306
- return accepted;
307
- }
308
- /**
309
- * Accept the extension negotiation response.
310
- *
311
- * @param {Array} response The extension negotiation response
312
- * @return {Object} Accepted configuration
313
- * @private
314
- */
315
- acceptAsClient(response) {
316
- const params = response[0];
317
- if (this._options.clientNoContextTakeover === false && params.client_no_context_takeover) throw new Error("Unexpected parameter \"client_no_context_takeover\"");
318
- if (!params.client_max_window_bits) {
319
- if (typeof this._options.clientMaxWindowBits === "number") params.client_max_window_bits = this._options.clientMaxWindowBits;
320
- } else if (this._options.clientMaxWindowBits === false || typeof this._options.clientMaxWindowBits === "number" && params.client_max_window_bits > this._options.clientMaxWindowBits) throw new Error("Unexpected or invalid parameter \"client_max_window_bits\"");
321
- return params;
322
- }
323
- /**
324
- * Normalize parameters.
325
- *
326
- * @param {Array} configurations The extension negotiation offers/reponse
327
- * @return {Array} The offers/response with normalized parameters
328
- * @private
329
- */
330
- normalizeParams(configurations) {
331
- configurations.forEach((params) => {
332
- Object.keys(params).forEach((key) => {
333
- let value = params[key];
334
- if (value.length > 1) throw new Error(`Parameter "${key}" must have only a single value`);
335
- value = value[0];
336
- if (key === "client_max_window_bits") {
337
- if (value !== true) {
338
- const num = +value;
339
- if (!Number.isInteger(num) || num < 8 || num > 15) throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
340
- value = num;
341
- } else if (!this._isServer) throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
342
- } else if (key === "server_max_window_bits") {
343
- const num = +value;
344
- if (!Number.isInteger(num) || num < 8 || num > 15) throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
345
- value = num;
346
- } else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") {
347
- if (value !== true) throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
348
- } else throw new Error(`Unknown parameter "${key}"`);
349
- params[key] = value;
350
- });
351
- });
352
- return configurations;
353
- }
354
- /**
355
- * Decompress data. Concurrency limited.
356
- *
357
- * @param {Buffer} data Compressed data
358
- * @param {Boolean} fin Specifies whether or not this is the last fragment
359
- * @param {Function} callback Callback
360
- * @public
361
- */
362
- decompress(data, fin, callback) {
363
- zlibLimiter.add((done) => {
364
- this._decompress(data, fin, (err, result) => {
365
- done();
366
- callback(err, result);
367
- });
368
- });
369
- }
370
- /**
371
- * Compress data. Concurrency limited.
372
- *
373
- * @param {(Buffer|String)} data Data to compress
374
- * @param {Boolean} fin Specifies whether or not this is the last fragment
375
- * @param {Function} callback Callback
376
- * @public
377
- */
378
- compress(data, fin, callback) {
379
- zlibLimiter.add((done) => {
380
- this._compress(data, fin, (err, result) => {
381
- done();
382
- callback(err, result);
383
- });
384
- });
385
- }
386
- /**
387
- * Decompress data.
388
- *
389
- * @param {Buffer} data Compressed data
390
- * @param {Boolean} fin Specifies whether or not this is the last fragment
391
- * @param {Function} callback Callback
392
- * @private
393
- */
394
- _decompress(data, fin, callback) {
395
- const endpoint = this._isServer ? "client" : "server";
396
- if (!this._inflate) {
397
- const key = `${endpoint}_max_window_bits`;
398
- const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
399
- this._inflate = zlib.createInflateRaw({
400
- ...this._options.zlibInflateOptions,
401
- windowBits
402
- });
403
- this._inflate[kPerMessageDeflate] = this;
404
- this._inflate[kTotalLength] = 0;
405
- this._inflate[kBuffers] = [];
406
- this._inflate.on("error", inflateOnError);
407
- this._inflate.on("data", inflateOnData);
408
- }
409
- this._inflate[kCallback] = callback;
410
- this._inflate.write(data);
411
- if (fin) this._inflate.write(TRAILER);
412
- this._inflate.flush(() => {
413
- const err = this._inflate[kError];
414
- if (err) {
415
- this._inflate.close();
416
- this._inflate = null;
417
- callback(err);
418
- return;
419
- }
420
- const data$1 = bufferUtil.concat(this._inflate[kBuffers], this._inflate[kTotalLength]);
421
- if (this._inflate._readableState.endEmitted) {
422
- this._inflate.close();
423
- this._inflate = null;
424
- } else {
425
- this._inflate[kTotalLength] = 0;
426
- this._inflate[kBuffers] = [];
427
- if (fin && this.params[`${endpoint}_no_context_takeover`]) this._inflate.reset();
428
- }
429
- callback(null, data$1);
430
- });
431
- }
432
- /**
433
- * Compress data.
434
- *
435
- * @param {(Buffer|String)} data Data to compress
436
- * @param {Boolean} fin Specifies whether or not this is the last fragment
437
- * @param {Function} callback Callback
438
- * @private
439
- */
440
- _compress(data, fin, callback) {
441
- const endpoint = this._isServer ? "server" : "client";
442
- if (!this._deflate) {
443
- const key = `${endpoint}_max_window_bits`;
444
- const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
445
- this._deflate = zlib.createDeflateRaw({
446
- ...this._options.zlibDeflateOptions,
447
- windowBits
448
- });
449
- this._deflate[kTotalLength] = 0;
450
- this._deflate[kBuffers] = [];
451
- this._deflate.on("data", deflateOnData);
452
- }
453
- this._deflate[kCallback] = callback;
454
- this._deflate.write(data);
455
- this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {
456
- if (!this._deflate) return;
457
- let data$1 = bufferUtil.concat(this._deflate[kBuffers], this._deflate[kTotalLength]);
458
- if (fin) data$1 = new FastBuffer(data$1.buffer, data$1.byteOffset, data$1.length - 4);
459
- this._deflate[kCallback] = null;
460
- this._deflate[kTotalLength] = 0;
461
- this._deflate[kBuffers] = [];
462
- if (fin && this.params[`${endpoint}_no_context_takeover`]) this._deflate.reset();
463
- callback(null, data$1);
464
- });
465
- }
466
- };
467
- module.exports = PerMessageDeflate;
468
- /**
469
- * The listener of the `zlib.DeflateRaw` stream `'data'` event.
470
- *
471
- * @param {Buffer} chunk A chunk of data
472
- * @private
473
- */
474
- function deflateOnData(chunk) {
475
- this[kBuffers].push(chunk);
476
- this[kTotalLength] += chunk.length;
477
- }
478
- /**
479
- * The listener of the `zlib.InflateRaw` stream `'data'` event.
480
- *
481
- * @param {Buffer} chunk A chunk of data
482
- * @private
483
- */
484
- function inflateOnData(chunk) {
485
- this[kTotalLength] += chunk.length;
486
- if (this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) {
487
- this[kBuffers].push(chunk);
488
- return;
489
- }
490
- this[kError] = /* @__PURE__ */ new RangeError("Max payload size exceeded");
491
- this[kError].code = "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH";
492
- this[kError][kStatusCode] = 1009;
493
- this.removeListener("data", inflateOnData);
494
- this.reset();
495
- }
496
- /**
497
- * The listener of the `zlib.InflateRaw` stream `'error'` event.
498
- *
499
- * @param {Error} err The emitted error
500
- * @private
501
- */
502
- function inflateOnError(err) {
503
- this[kPerMessageDeflate]._inflate = null;
504
- if (this[kError]) {
505
- this[kCallback](this[kError]);
506
- return;
507
- }
508
- err[kStatusCode] = 1007;
509
- this[kCallback](err);
510
- }
511
- }));
512
-
513
- //#endregion
514
- //#region node_modules/ws/lib/validation.js
515
- var require_validation = /* @__PURE__ */ __commonJSMin(((exports, module) => {
516
- const { isUtf8 } = __require("buffer");
517
- const { hasBlob } = require_constants();
518
- const tokenChars = [
519
- 0,
520
- 0,
521
- 0,
522
- 0,
523
- 0,
524
- 0,
525
- 0,
526
- 0,
527
- 0,
528
- 0,
529
- 0,
530
- 0,
531
- 0,
532
- 0,
533
- 0,
534
- 0,
535
- 0,
536
- 0,
537
- 0,
538
- 0,
539
- 0,
540
- 0,
541
- 0,
542
- 0,
543
- 0,
544
- 0,
545
- 0,
546
- 0,
547
- 0,
548
- 0,
549
- 0,
550
- 0,
551
- 0,
552
- 1,
553
- 0,
554
- 1,
555
- 1,
556
- 1,
557
- 1,
558
- 1,
559
- 0,
560
- 0,
561
- 1,
562
- 1,
563
- 0,
564
- 1,
565
- 1,
566
- 0,
567
- 1,
568
- 1,
569
- 1,
570
- 1,
571
- 1,
572
- 1,
573
- 1,
574
- 1,
575
- 1,
576
- 1,
577
- 0,
578
- 0,
579
- 0,
580
- 0,
581
- 0,
582
- 0,
583
- 0,
584
- 1,
585
- 1,
586
- 1,
587
- 1,
588
- 1,
589
- 1,
590
- 1,
591
- 1,
592
- 1,
593
- 1,
594
- 1,
595
- 1,
596
- 1,
597
- 1,
598
- 1,
599
- 1,
600
- 1,
601
- 1,
602
- 1,
603
- 1,
604
- 1,
605
- 1,
606
- 1,
607
- 1,
608
- 1,
609
- 1,
610
- 0,
611
- 0,
612
- 0,
613
- 1,
614
- 1,
615
- 1,
616
- 1,
617
- 1,
618
- 1,
619
- 1,
620
- 1,
621
- 1,
622
- 1,
623
- 1,
624
- 1,
625
- 1,
626
- 1,
627
- 1,
628
- 1,
629
- 1,
630
- 1,
631
- 1,
632
- 1,
633
- 1,
634
- 1,
635
- 1,
636
- 1,
637
- 1,
638
- 1,
639
- 1,
640
- 1,
641
- 1,
642
- 0,
643
- 1,
644
- 0,
645
- 1,
646
- 0
647
- ];
648
- /**
649
- * Checks if a status code is allowed in a close frame.
650
- *
651
- * @param {Number} code The status code
652
- * @return {Boolean} `true` if the status code is valid, else `false`
653
- * @public
654
- */
655
- function isValidStatusCode(code) {
656
- return code >= 1e3 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006 || code >= 3e3 && code <= 4999;
657
- }
658
- /**
659
- * Checks if a given buffer contains only correct UTF-8.
660
- * Ported from https://www.cl.cam.ac.uk/%7Emgk25/ucs/utf8_check.c by
661
- * Markus Kuhn.
662
- *
663
- * @param {Buffer} buf The buffer to check
664
- * @return {Boolean} `true` if `buf` contains only correct UTF-8, else `false`
665
- * @public
666
- */
667
- function _isValidUTF8(buf) {
668
- const len = buf.length;
669
- let i = 0;
670
- while (i < len) if ((buf[i] & 128) === 0) i++;
671
- else if ((buf[i] & 224) === 192) {
672
- if (i + 1 === len || (buf[i + 1] & 192) !== 128 || (buf[i] & 254) === 192) return false;
673
- i += 2;
674
- } else if ((buf[i] & 240) === 224) {
675
- if (i + 2 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || buf[i] === 224 && (buf[i + 1] & 224) === 128 || buf[i] === 237 && (buf[i + 1] & 224) === 160) return false;
676
- i += 3;
677
- } else if ((buf[i] & 248) === 240) {
678
- if (i + 3 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || (buf[i + 3] & 192) !== 128 || buf[i] === 240 && (buf[i + 1] & 240) === 128 || buf[i] === 244 && buf[i + 1] > 143 || buf[i] > 244) return false;
679
- i += 4;
680
- } else return false;
681
- return true;
682
- }
683
- /**
684
- * Determines whether a value is a `Blob`.
685
- *
686
- * @param {*} value The value to be tested
687
- * @return {Boolean} `true` if `value` is a `Blob`, else `false`
688
- * @private
689
- */
690
- function isBlob(value) {
691
- return hasBlob && typeof value === "object" && typeof value.arrayBuffer === "function" && typeof value.type === "string" && typeof value.stream === "function" && (value[Symbol.toStringTag] === "Blob" || value[Symbol.toStringTag] === "File");
692
- }
693
- module.exports = {
694
- isBlob,
695
- isValidStatusCode,
696
- isValidUTF8: _isValidUTF8,
697
- tokenChars
698
- };
699
- if (isUtf8) module.exports.isValidUTF8 = function(buf) {
700
- return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);
701
- };
702
- else if (!process.env.WS_NO_UTF_8_VALIDATE) try {
703
- const isValidUTF8 = __require("utf-8-validate");
704
- module.exports.isValidUTF8 = function(buf) {
705
- return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);
706
- };
707
- } catch (e) {}
708
- }));
709
-
710
- //#endregion
711
- //#region node_modules/ws/lib/receiver.js
712
- var require_receiver = /* @__PURE__ */ __commonJSMin(((exports, module) => {
713
- const { Writable } = __require("stream");
714
- const PerMessageDeflate = require_permessage_deflate();
715
- const { BINARY_TYPES, EMPTY_BUFFER, kStatusCode, kWebSocket } = require_constants();
716
- const { concat, toArrayBuffer, unmask } = require_buffer_util();
717
- const { isValidStatusCode, isValidUTF8 } = require_validation();
718
- const FastBuffer = Buffer[Symbol.species];
719
- const GET_INFO = 0;
720
- const GET_PAYLOAD_LENGTH_16 = 1;
721
- const GET_PAYLOAD_LENGTH_64 = 2;
722
- const GET_MASK = 3;
723
- const GET_DATA = 4;
724
- const INFLATING = 5;
725
- const DEFER_EVENT = 6;
726
- /**
727
- * HyBi Receiver implementation.
728
- *
729
- * @extends Writable
730
- */
731
- var Receiver = class extends Writable {
732
- /**
733
- * Creates a Receiver instance.
734
- *
735
- * @param {Object} [options] Options object
736
- * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
737
- * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
738
- * multiple times in the same tick
739
- * @param {String} [options.binaryType=nodebuffer] The type for binary data
740
- * @param {Object} [options.extensions] An object containing the negotiated
741
- * extensions
742
- * @param {Boolean} [options.isServer=false] Specifies whether to operate in
743
- * client or server mode
744
- * @param {Number} [options.maxPayload=0] The maximum allowed message length
745
- * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
746
- * not to skip UTF-8 validation for text and close messages
747
- */
748
- constructor(options = {}) {
749
- super();
750
- this._allowSynchronousEvents = options.allowSynchronousEvents !== void 0 ? options.allowSynchronousEvents : true;
751
- this._binaryType = options.binaryType || BINARY_TYPES[0];
752
- this._extensions = options.extensions || {};
753
- this._isServer = !!options.isServer;
754
- this._maxPayload = options.maxPayload | 0;
755
- this._skipUTF8Validation = !!options.skipUTF8Validation;
756
- this[kWebSocket] = void 0;
757
- this._bufferedBytes = 0;
758
- this._buffers = [];
759
- this._compressed = false;
760
- this._payloadLength = 0;
761
- this._mask = void 0;
762
- this._fragmented = 0;
763
- this._masked = false;
764
- this._fin = false;
765
- this._opcode = 0;
766
- this._totalPayloadLength = 0;
767
- this._messageLength = 0;
768
- this._fragments = [];
769
- this._errored = false;
770
- this._loop = false;
771
- this._state = GET_INFO;
772
- }
773
- /**
774
- * Implements `Writable.prototype._write()`.
775
- *
776
- * @param {Buffer} chunk The chunk of data to write
777
- * @param {String} encoding The character encoding of `chunk`
778
- * @param {Function} cb Callback
779
- * @private
780
- */
781
- _write(chunk, encoding, cb) {
782
- if (this._opcode === 8 && this._state == GET_INFO) return cb();
783
- this._bufferedBytes += chunk.length;
784
- this._buffers.push(chunk);
785
- this.startLoop(cb);
786
- }
787
- /**
788
- * Consumes `n` bytes from the buffered data.
789
- *
790
- * @param {Number} n The number of bytes to consume
791
- * @return {Buffer} The consumed bytes
792
- * @private
793
- */
794
- consume(n) {
795
- this._bufferedBytes -= n;
796
- if (n === this._buffers[0].length) return this._buffers.shift();
797
- if (n < this._buffers[0].length) {
798
- const buf = this._buffers[0];
799
- this._buffers[0] = new FastBuffer(buf.buffer, buf.byteOffset + n, buf.length - n);
800
- return new FastBuffer(buf.buffer, buf.byteOffset, n);
801
- }
802
- const dst = Buffer.allocUnsafe(n);
803
- do {
804
- const buf = this._buffers[0];
805
- const offset = dst.length - n;
806
- if (n >= buf.length) dst.set(this._buffers.shift(), offset);
807
- else {
808
- dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);
809
- this._buffers[0] = new FastBuffer(buf.buffer, buf.byteOffset + n, buf.length - n);
810
- }
811
- n -= buf.length;
812
- } while (n > 0);
813
- return dst;
814
- }
815
- /**
816
- * Starts the parsing loop.
817
- *
818
- * @param {Function} cb Callback
819
- * @private
820
- */
821
- startLoop(cb) {
822
- this._loop = true;
823
- do
824
- switch (this._state) {
825
- case GET_INFO:
826
- this.getInfo(cb);
827
- break;
828
- case GET_PAYLOAD_LENGTH_16:
829
- this.getPayloadLength16(cb);
830
- break;
831
- case GET_PAYLOAD_LENGTH_64:
832
- this.getPayloadLength64(cb);
833
- break;
834
- case GET_MASK:
835
- this.getMask();
836
- break;
837
- case GET_DATA:
838
- this.getData(cb);
839
- break;
840
- case INFLATING:
841
- case DEFER_EVENT:
842
- this._loop = false;
843
- return;
844
- }
845
- while (this._loop);
846
- if (!this._errored) cb();
847
- }
848
- /**
849
- * Reads the first two bytes of a frame.
850
- *
851
- * @param {Function} cb Callback
852
- * @private
853
- */
854
- getInfo(cb) {
855
- if (this._bufferedBytes < 2) {
856
- this._loop = false;
857
- return;
858
- }
859
- const buf = this.consume(2);
860
- if ((buf[0] & 48) !== 0) {
861
- cb(this.createError(RangeError, "RSV2 and RSV3 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_2_3"));
862
- return;
863
- }
864
- const compressed = (buf[0] & 64) === 64;
865
- if (compressed && !this._extensions[PerMessageDeflate.extensionName]) {
866
- cb(this.createError(RangeError, "RSV1 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_1"));
867
- return;
868
- }
869
- this._fin = (buf[0] & 128) === 128;
870
- this._opcode = buf[0] & 15;
871
- this._payloadLength = buf[1] & 127;
872
- if (this._opcode === 0) {
873
- if (compressed) {
874
- cb(this.createError(RangeError, "RSV1 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_1"));
875
- return;
876
- }
877
- if (!this._fragmented) {
878
- cb(this.createError(RangeError, "invalid opcode 0", true, 1002, "WS_ERR_INVALID_OPCODE"));
879
- return;
880
- }
881
- this._opcode = this._fragmented;
882
- } else if (this._opcode === 1 || this._opcode === 2) {
883
- if (this._fragmented) {
884
- cb(this.createError(RangeError, `invalid opcode ${this._opcode}`, true, 1002, "WS_ERR_INVALID_OPCODE"));
885
- return;
886
- }
887
- this._compressed = compressed;
888
- } else if (this._opcode > 7 && this._opcode < 11) {
889
- if (!this._fin) {
890
- cb(this.createError(RangeError, "FIN must be set", true, 1002, "WS_ERR_EXPECTED_FIN"));
891
- return;
892
- }
893
- if (compressed) {
894
- cb(this.createError(RangeError, "RSV1 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_1"));
895
- return;
896
- }
897
- if (this._payloadLength > 125 || this._opcode === 8 && this._payloadLength === 1) {
898
- cb(this.createError(RangeError, `invalid payload length ${this._payloadLength}`, true, 1002, "WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"));
899
- return;
900
- }
901
- } else {
902
- cb(this.createError(RangeError, `invalid opcode ${this._opcode}`, true, 1002, "WS_ERR_INVALID_OPCODE"));
903
- return;
904
- }
905
- if (!this._fin && !this._fragmented) this._fragmented = this._opcode;
906
- this._masked = (buf[1] & 128) === 128;
907
- if (this._isServer) {
908
- if (!this._masked) {
909
- cb(this.createError(RangeError, "MASK must be set", true, 1002, "WS_ERR_EXPECTED_MASK"));
910
- return;
911
- }
912
- } else if (this._masked) {
913
- cb(this.createError(RangeError, "MASK must be clear", true, 1002, "WS_ERR_UNEXPECTED_MASK"));
914
- return;
915
- }
916
- if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;
917
- else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;
918
- else this.haveLength(cb);
919
- }
920
- /**
921
- * Gets extended payload length (7+16).
922
- *
923
- * @param {Function} cb Callback
924
- * @private
925
- */
926
- getPayloadLength16(cb) {
927
- if (this._bufferedBytes < 2) {
928
- this._loop = false;
929
- return;
930
- }
931
- this._payloadLength = this.consume(2).readUInt16BE(0);
932
- this.haveLength(cb);
933
- }
934
- /**
935
- * Gets extended payload length (7+64).
936
- *
937
- * @param {Function} cb Callback
938
- * @private
939
- */
940
- getPayloadLength64(cb) {
941
- if (this._bufferedBytes < 8) {
942
- this._loop = false;
943
- return;
944
- }
945
- const buf = this.consume(8);
946
- const num = buf.readUInt32BE(0);
947
- if (num > Math.pow(2, 21) - 1) {
948
- cb(this.createError(RangeError, "Unsupported WebSocket frame: payload length > 2^53 - 1", false, 1009, "WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH"));
949
- return;
950
- }
951
- this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
952
- this.haveLength(cb);
953
- }
954
- /**
955
- * Payload length has been read.
956
- *
957
- * @param {Function} cb Callback
958
- * @private
959
- */
960
- haveLength(cb) {
961
- if (this._payloadLength && this._opcode < 8) {
962
- this._totalPayloadLength += this._payloadLength;
963
- if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
964
- cb(this.createError(RangeError, "Max payload size exceeded", false, 1009, "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"));
965
- return;
966
- }
967
- }
968
- if (this._masked) this._state = GET_MASK;
969
- else this._state = GET_DATA;
970
- }
971
- /**
972
- * Reads mask bytes.
973
- *
974
- * @private
975
- */
976
- getMask() {
977
- if (this._bufferedBytes < 4) {
978
- this._loop = false;
979
- return;
980
- }
981
- this._mask = this.consume(4);
982
- this._state = GET_DATA;
983
- }
984
- /**
985
- * Reads data bytes.
986
- *
987
- * @param {Function} cb Callback
988
- * @private
989
- */
990
- getData(cb) {
991
- let data = EMPTY_BUFFER;
992
- if (this._payloadLength) {
993
- if (this._bufferedBytes < this._payloadLength) {
994
- this._loop = false;
995
- return;
996
- }
997
- data = this.consume(this._payloadLength);
998
- if (this._masked && (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0) unmask(data, this._mask);
999
- }
1000
- if (this._opcode > 7) {
1001
- this.controlMessage(data, cb);
1002
- return;
1003
- }
1004
- if (this._compressed) {
1005
- this._state = INFLATING;
1006
- this.decompress(data, cb);
1007
- return;
1008
- }
1009
- if (data.length) {
1010
- this._messageLength = this._totalPayloadLength;
1011
- this._fragments.push(data);
1012
- }
1013
- this.dataMessage(cb);
1014
- }
1015
- /**
1016
- * Decompresses data.
1017
- *
1018
- * @param {Buffer} data Compressed data
1019
- * @param {Function} cb Callback
1020
- * @private
1021
- */
1022
- decompress(data, cb) {
1023
- this._extensions[PerMessageDeflate.extensionName].decompress(data, this._fin, (err, buf) => {
1024
- if (err) return cb(err);
1025
- if (buf.length) {
1026
- this._messageLength += buf.length;
1027
- if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
1028
- cb(this.createError(RangeError, "Max payload size exceeded", false, 1009, "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"));
1029
- return;
1030
- }
1031
- this._fragments.push(buf);
1032
- }
1033
- this.dataMessage(cb);
1034
- if (this._state === GET_INFO) this.startLoop(cb);
1035
- });
1036
- }
1037
- /**
1038
- * Handles a data message.
1039
- *
1040
- * @param {Function} cb Callback
1041
- * @private
1042
- */
1043
- dataMessage(cb) {
1044
- if (!this._fin) {
1045
- this._state = GET_INFO;
1046
- return;
1047
- }
1048
- const messageLength = this._messageLength;
1049
- const fragments = this._fragments;
1050
- this._totalPayloadLength = 0;
1051
- this._messageLength = 0;
1052
- this._fragmented = 0;
1053
- this._fragments = [];
1054
- if (this._opcode === 2) {
1055
- let data;
1056
- if (this._binaryType === "nodebuffer") data = concat(fragments, messageLength);
1057
- else if (this._binaryType === "arraybuffer") data = toArrayBuffer(concat(fragments, messageLength));
1058
- else if (this._binaryType === "blob") data = new Blob(fragments);
1059
- else data = fragments;
1060
- if (this._allowSynchronousEvents) {
1061
- this.emit("message", data, true);
1062
- this._state = GET_INFO;
1063
- } else {
1064
- this._state = DEFER_EVENT;
1065
- setImmediate(() => {
1066
- this.emit("message", data, true);
1067
- this._state = GET_INFO;
1068
- this.startLoop(cb);
1069
- });
1070
- }
1071
- } else {
1072
- const buf = concat(fragments, messageLength);
1073
- if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
1074
- cb(this.createError(Error, "invalid UTF-8 sequence", true, 1007, "WS_ERR_INVALID_UTF8"));
1075
- return;
1076
- }
1077
- if (this._state === INFLATING || this._allowSynchronousEvents) {
1078
- this.emit("message", buf, false);
1079
- this._state = GET_INFO;
1080
- } else {
1081
- this._state = DEFER_EVENT;
1082
- setImmediate(() => {
1083
- this.emit("message", buf, false);
1084
- this._state = GET_INFO;
1085
- this.startLoop(cb);
1086
- });
1087
- }
1088
- }
1089
- }
1090
- /**
1091
- * Handles a control message.
1092
- *
1093
- * @param {Buffer} data Data to handle
1094
- * @return {(Error|RangeError|undefined)} A possible error
1095
- * @private
1096
- */
1097
- controlMessage(data, cb) {
1098
- if (this._opcode === 8) {
1099
- if (data.length === 0) {
1100
- this._loop = false;
1101
- this.emit("conclude", 1005, EMPTY_BUFFER);
1102
- this.end();
1103
- } else {
1104
- const code = data.readUInt16BE(0);
1105
- if (!isValidStatusCode(code)) {
1106
- cb(this.createError(RangeError, `invalid status code ${code}`, true, 1002, "WS_ERR_INVALID_CLOSE_CODE"));
1107
- return;
1108
- }
1109
- const buf = new FastBuffer(data.buffer, data.byteOffset + 2, data.length - 2);
1110
- if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
1111
- cb(this.createError(Error, "invalid UTF-8 sequence", true, 1007, "WS_ERR_INVALID_UTF8"));
1112
- return;
1113
- }
1114
- this._loop = false;
1115
- this.emit("conclude", code, buf);
1116
- this.end();
1117
- }
1118
- this._state = GET_INFO;
1119
- return;
1120
- }
1121
- if (this._allowSynchronousEvents) {
1122
- this.emit(this._opcode === 9 ? "ping" : "pong", data);
1123
- this._state = GET_INFO;
1124
- } else {
1125
- this._state = DEFER_EVENT;
1126
- setImmediate(() => {
1127
- this.emit(this._opcode === 9 ? "ping" : "pong", data);
1128
- this._state = GET_INFO;
1129
- this.startLoop(cb);
1130
- });
1131
- }
1132
- }
1133
- /**
1134
- * Builds an error object.
1135
- *
1136
- * @param {function(new:Error|RangeError)} ErrorCtor The error constructor
1137
- * @param {String} message The error message
1138
- * @param {Boolean} prefix Specifies whether or not to add a default prefix to
1139
- * `message`
1140
- * @param {Number} statusCode The status code
1141
- * @param {String} errorCode The exposed error code
1142
- * @return {(Error|RangeError)} The error
1143
- * @private
1144
- */
1145
- createError(ErrorCtor, message, prefix, statusCode, errorCode) {
1146
- this._loop = false;
1147
- this._errored = true;
1148
- const err = new ErrorCtor(prefix ? `Invalid WebSocket frame: ${message}` : message);
1149
- Error.captureStackTrace(err, this.createError);
1150
- err.code = errorCode;
1151
- err[kStatusCode] = statusCode;
1152
- return err;
1153
- }
1154
- };
1155
- module.exports = Receiver;
1156
- }));
1157
-
1158
- //#endregion
1159
- //#region node_modules/ws/lib/sender.js
1160
- var require_sender = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1161
- const { Duplex: Duplex$3 } = __require("stream");
1162
- const { randomFillSync } = __require("crypto");
1163
- const PerMessageDeflate = require_permessage_deflate();
1164
- const { EMPTY_BUFFER, kWebSocket, NOOP } = require_constants();
1165
- const { isBlob, isValidStatusCode } = require_validation();
1166
- const { mask: applyMask, toBuffer } = require_buffer_util();
1167
- const kByteLength = Symbol("kByteLength");
1168
- const maskBuffer = Buffer.alloc(4);
1169
- const RANDOM_POOL_SIZE = 8 * 1024;
1170
- let randomPool;
1171
- let randomPoolPointer = RANDOM_POOL_SIZE;
1172
- const DEFAULT = 0;
1173
- const DEFLATING = 1;
1174
- const GET_BLOB_DATA = 2;
1175
- /**
1176
- * HyBi Sender implementation.
1177
- */
1178
- var Sender = class Sender {
1179
- /**
1180
- * Creates a Sender instance.
1181
- *
1182
- * @param {Duplex} socket The connection socket
1183
- * @param {Object} [extensions] An object containing the negotiated extensions
1184
- * @param {Function} [generateMask] The function used to generate the masking
1185
- * key
1186
- */
1187
- constructor(socket, extensions, generateMask) {
1188
- this._extensions = extensions || {};
1189
- if (generateMask) {
1190
- this._generateMask = generateMask;
1191
- this._maskBuffer = Buffer.alloc(4);
1192
- }
1193
- this._socket = socket;
1194
- this._firstFragment = true;
1195
- this._compress = false;
1196
- this._bufferedBytes = 0;
1197
- this._queue = [];
1198
- this._state = DEFAULT;
1199
- this.onerror = NOOP;
1200
- this[kWebSocket] = void 0;
1201
- }
1202
- /**
1203
- * Frames a piece of data according to the HyBi WebSocket protocol.
1204
- *
1205
- * @param {(Buffer|String)} data The data to frame
1206
- * @param {Object} options Options object
1207
- * @param {Boolean} [options.fin=false] Specifies whether or not to set the
1208
- * FIN bit
1209
- * @param {Function} [options.generateMask] The function used to generate the
1210
- * masking key
1211
- * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1212
- * `data`
1213
- * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
1214
- * key
1215
- * @param {Number} options.opcode The opcode
1216
- * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
1217
- * modified
1218
- * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
1219
- * RSV1 bit
1220
- * @return {(Buffer|String)[]} The framed data
1221
- * @public
1222
- */
1223
- static frame(data, options) {
1224
- let mask;
1225
- let merge = false;
1226
- let offset = 2;
1227
- let skipMasking = false;
1228
- if (options.mask) {
1229
- mask = options.maskBuffer || maskBuffer;
1230
- if (options.generateMask) options.generateMask(mask);
1231
- else {
1232
- if (randomPoolPointer === RANDOM_POOL_SIZE) {
1233
- /* istanbul ignore else */
1234
- if (randomPool === void 0) randomPool = Buffer.alloc(RANDOM_POOL_SIZE);
1235
- randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);
1236
- randomPoolPointer = 0;
1237
- }
1238
- mask[0] = randomPool[randomPoolPointer++];
1239
- mask[1] = randomPool[randomPoolPointer++];
1240
- mask[2] = randomPool[randomPoolPointer++];
1241
- mask[3] = randomPool[randomPoolPointer++];
1242
- }
1243
- skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;
1244
- offset = 6;
1245
- }
1246
- let dataLength;
1247
- if (typeof data === "string") if ((!options.mask || skipMasking) && options[kByteLength] !== void 0) dataLength = options[kByteLength];
1248
- else {
1249
- data = Buffer.from(data);
1250
- dataLength = data.length;
1251
- }
1252
- else {
1253
- dataLength = data.length;
1254
- merge = options.mask && options.readOnly && !skipMasking;
1255
- }
1256
- let payloadLength = dataLength;
1257
- if (dataLength >= 65536) {
1258
- offset += 8;
1259
- payloadLength = 127;
1260
- } else if (dataLength > 125) {
1261
- offset += 2;
1262
- payloadLength = 126;
1263
- }
1264
- const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);
1265
- target[0] = options.fin ? options.opcode | 128 : options.opcode;
1266
- if (options.rsv1) target[0] |= 64;
1267
- target[1] = payloadLength;
1268
- if (payloadLength === 126) target.writeUInt16BE(dataLength, 2);
1269
- else if (payloadLength === 127) {
1270
- target[2] = target[3] = 0;
1271
- target.writeUIntBE(dataLength, 4, 6);
1272
- }
1273
- if (!options.mask) return [target, data];
1274
- target[1] |= 128;
1275
- target[offset - 4] = mask[0];
1276
- target[offset - 3] = mask[1];
1277
- target[offset - 2] = mask[2];
1278
- target[offset - 1] = mask[3];
1279
- if (skipMasking) return [target, data];
1280
- if (merge) {
1281
- applyMask(data, mask, target, offset, dataLength);
1282
- return [target];
1283
- }
1284
- applyMask(data, mask, data, 0, dataLength);
1285
- return [target, data];
1286
- }
1287
- /**
1288
- * Sends a close message to the other peer.
1289
- *
1290
- * @param {Number} [code] The status code component of the body
1291
- * @param {(String|Buffer)} [data] The message component of the body
1292
- * @param {Boolean} [mask=false] Specifies whether or not to mask the message
1293
- * @param {Function} [cb] Callback
1294
- * @public
1295
- */
1296
- close(code, data, mask, cb) {
1297
- let buf;
1298
- if (code === void 0) buf = EMPTY_BUFFER;
1299
- else if (typeof code !== "number" || !isValidStatusCode(code)) throw new TypeError("First argument must be a valid error code number");
1300
- else if (data === void 0 || !data.length) {
1301
- buf = Buffer.allocUnsafe(2);
1302
- buf.writeUInt16BE(code, 0);
1303
- } else {
1304
- const length = Buffer.byteLength(data);
1305
- if (length > 123) throw new RangeError("The message must not be greater than 123 bytes");
1306
- buf = Buffer.allocUnsafe(2 + length);
1307
- buf.writeUInt16BE(code, 0);
1308
- if (typeof data === "string") buf.write(data, 2);
1309
- else buf.set(data, 2);
1310
- }
1311
- const options = {
1312
- [kByteLength]: buf.length,
1313
- fin: true,
1314
- generateMask: this._generateMask,
1315
- mask,
1316
- maskBuffer: this._maskBuffer,
1317
- opcode: 8,
1318
- readOnly: false,
1319
- rsv1: false
1320
- };
1321
- if (this._state !== DEFAULT) this.enqueue([
1322
- this.dispatch,
1323
- buf,
1324
- false,
1325
- options,
1326
- cb
1327
- ]);
1328
- else this.sendFrame(Sender.frame(buf, options), cb);
1329
- }
1330
- /**
1331
- * Sends a ping message to the other peer.
1332
- *
1333
- * @param {*} data The message to send
1334
- * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
1335
- * @param {Function} [cb] Callback
1336
- * @public
1337
- */
1338
- ping(data, mask, cb) {
1339
- let byteLength;
1340
- let readOnly;
1341
- if (typeof data === "string") {
1342
- byteLength = Buffer.byteLength(data);
1343
- readOnly = false;
1344
- } else if (isBlob(data)) {
1345
- byteLength = data.size;
1346
- readOnly = false;
1347
- } else {
1348
- data = toBuffer(data);
1349
- byteLength = data.length;
1350
- readOnly = toBuffer.readOnly;
1351
- }
1352
- if (byteLength > 125) throw new RangeError("The data size must not be greater than 125 bytes");
1353
- const options = {
1354
- [kByteLength]: byteLength,
1355
- fin: true,
1356
- generateMask: this._generateMask,
1357
- mask,
1358
- maskBuffer: this._maskBuffer,
1359
- opcode: 9,
1360
- readOnly,
1361
- rsv1: false
1362
- };
1363
- if (isBlob(data)) if (this._state !== DEFAULT) this.enqueue([
1364
- this.getBlobData,
1365
- data,
1366
- false,
1367
- options,
1368
- cb
1369
- ]);
1370
- else this.getBlobData(data, false, options, cb);
1371
- else if (this._state !== DEFAULT) this.enqueue([
1372
- this.dispatch,
1373
- data,
1374
- false,
1375
- options,
1376
- cb
1377
- ]);
1378
- else this.sendFrame(Sender.frame(data, options), cb);
1379
- }
1380
- /**
1381
- * Sends a pong message to the other peer.
1382
- *
1383
- * @param {*} data The message to send
1384
- * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
1385
- * @param {Function} [cb] Callback
1386
- * @public
1387
- */
1388
- pong(data, mask, cb) {
1389
- let byteLength;
1390
- let readOnly;
1391
- if (typeof data === "string") {
1392
- byteLength = Buffer.byteLength(data);
1393
- readOnly = false;
1394
- } else if (isBlob(data)) {
1395
- byteLength = data.size;
1396
- readOnly = false;
1397
- } else {
1398
- data = toBuffer(data);
1399
- byteLength = data.length;
1400
- readOnly = toBuffer.readOnly;
1401
- }
1402
- if (byteLength > 125) throw new RangeError("The data size must not be greater than 125 bytes");
1403
- const options = {
1404
- [kByteLength]: byteLength,
1405
- fin: true,
1406
- generateMask: this._generateMask,
1407
- mask,
1408
- maskBuffer: this._maskBuffer,
1409
- opcode: 10,
1410
- readOnly,
1411
- rsv1: false
1412
- };
1413
- if (isBlob(data)) if (this._state !== DEFAULT) this.enqueue([
1414
- this.getBlobData,
1415
- data,
1416
- false,
1417
- options,
1418
- cb
1419
- ]);
1420
- else this.getBlobData(data, false, options, cb);
1421
- else if (this._state !== DEFAULT) this.enqueue([
1422
- this.dispatch,
1423
- data,
1424
- false,
1425
- options,
1426
- cb
1427
- ]);
1428
- else this.sendFrame(Sender.frame(data, options), cb);
1429
- }
1430
- /**
1431
- * Sends a data message to the other peer.
1432
- *
1433
- * @param {*} data The message to send
1434
- * @param {Object} options Options object
1435
- * @param {Boolean} [options.binary=false] Specifies whether `data` is binary
1436
- * or text
1437
- * @param {Boolean} [options.compress=false] Specifies whether or not to
1438
- * compress `data`
1439
- * @param {Boolean} [options.fin=false] Specifies whether the fragment is the
1440
- * last one
1441
- * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1442
- * `data`
1443
- * @param {Function} [cb] Callback
1444
- * @public
1445
- */
1446
- send(data, options, cb) {
1447
- const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
1448
- let opcode = options.binary ? 2 : 1;
1449
- let rsv1 = options.compress;
1450
- let byteLength;
1451
- let readOnly;
1452
- if (typeof data === "string") {
1453
- byteLength = Buffer.byteLength(data);
1454
- readOnly = false;
1455
- } else if (isBlob(data)) {
1456
- byteLength = data.size;
1457
- readOnly = false;
1458
- } else {
1459
- data = toBuffer(data);
1460
- byteLength = data.length;
1461
- readOnly = toBuffer.readOnly;
1462
- }
1463
- if (this._firstFragment) {
1464
- this._firstFragment = false;
1465
- if (rsv1 && perMessageDeflate && perMessageDeflate.params[perMessageDeflate._isServer ? "server_no_context_takeover" : "client_no_context_takeover"]) rsv1 = byteLength >= perMessageDeflate._threshold;
1466
- this._compress = rsv1;
1467
- } else {
1468
- rsv1 = false;
1469
- opcode = 0;
1470
- }
1471
- if (options.fin) this._firstFragment = true;
1472
- const opts = {
1473
- [kByteLength]: byteLength,
1474
- fin: options.fin,
1475
- generateMask: this._generateMask,
1476
- mask: options.mask,
1477
- maskBuffer: this._maskBuffer,
1478
- opcode,
1479
- readOnly,
1480
- rsv1
1481
- };
1482
- if (isBlob(data)) if (this._state !== DEFAULT) this.enqueue([
1483
- this.getBlobData,
1484
- data,
1485
- this._compress,
1486
- opts,
1487
- cb
1488
- ]);
1489
- else this.getBlobData(data, this._compress, opts, cb);
1490
- else if (this._state !== DEFAULT) this.enqueue([
1491
- this.dispatch,
1492
- data,
1493
- this._compress,
1494
- opts,
1495
- cb
1496
- ]);
1497
- else this.dispatch(data, this._compress, opts, cb);
1498
- }
1499
- /**
1500
- * Gets the contents of a blob as binary data.
1501
- *
1502
- * @param {Blob} blob The blob
1503
- * @param {Boolean} [compress=false] Specifies whether or not to compress
1504
- * the data
1505
- * @param {Object} options Options object
1506
- * @param {Boolean} [options.fin=false] Specifies whether or not to set the
1507
- * FIN bit
1508
- * @param {Function} [options.generateMask] The function used to generate the
1509
- * masking key
1510
- * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1511
- * `data`
1512
- * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
1513
- * key
1514
- * @param {Number} options.opcode The opcode
1515
- * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
1516
- * modified
1517
- * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
1518
- * RSV1 bit
1519
- * @param {Function} [cb] Callback
1520
- * @private
1521
- */
1522
- getBlobData(blob, compress, options, cb) {
1523
- this._bufferedBytes += options[kByteLength];
1524
- this._state = GET_BLOB_DATA;
1525
- blob.arrayBuffer().then((arrayBuffer) => {
1526
- if (this._socket.destroyed) {
1527
- const err = /* @__PURE__ */ new Error("The socket was closed while the blob was being read");
1528
- process.nextTick(callCallbacks, this, err, cb);
1529
- return;
1530
- }
1531
- this._bufferedBytes -= options[kByteLength];
1532
- const data = toBuffer(arrayBuffer);
1533
- if (!compress) {
1534
- this._state = DEFAULT;
1535
- this.sendFrame(Sender.frame(data, options), cb);
1536
- this.dequeue();
1537
- } else this.dispatch(data, compress, options, cb);
1538
- }).catch((err) => {
1539
- process.nextTick(onError, this, err, cb);
1540
- });
1541
- }
1542
- /**
1543
- * Dispatches a message.
1544
- *
1545
- * @param {(Buffer|String)} data The message to send
1546
- * @param {Boolean} [compress=false] Specifies whether or not to compress
1547
- * `data`
1548
- * @param {Object} options Options object
1549
- * @param {Boolean} [options.fin=false] Specifies whether or not to set the
1550
- * FIN bit
1551
- * @param {Function} [options.generateMask] The function used to generate the
1552
- * masking key
1553
- * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1554
- * `data`
1555
- * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
1556
- * key
1557
- * @param {Number} options.opcode The opcode
1558
- * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
1559
- * modified
1560
- * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
1561
- * RSV1 bit
1562
- * @param {Function} [cb] Callback
1563
- * @private
1564
- */
1565
- dispatch(data, compress, options, cb) {
1566
- if (!compress) {
1567
- this.sendFrame(Sender.frame(data, options), cb);
1568
- return;
1569
- }
1570
- const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
1571
- this._bufferedBytes += options[kByteLength];
1572
- this._state = DEFLATING;
1573
- perMessageDeflate.compress(data, options.fin, (_, buf) => {
1574
- if (this._socket.destroyed) {
1575
- callCallbacks(this, /* @__PURE__ */ new Error("The socket was closed while data was being compressed"), cb);
1576
- return;
1577
- }
1578
- this._bufferedBytes -= options[kByteLength];
1579
- this._state = DEFAULT;
1580
- options.readOnly = false;
1581
- this.sendFrame(Sender.frame(buf, options), cb);
1582
- this.dequeue();
1583
- });
1584
- }
1585
- /**
1586
- * Executes queued send operations.
1587
- *
1588
- * @private
1589
- */
1590
- dequeue() {
1591
- while (this._state === DEFAULT && this._queue.length) {
1592
- const params = this._queue.shift();
1593
- this._bufferedBytes -= params[3][kByteLength];
1594
- Reflect.apply(params[0], this, params.slice(1));
1595
- }
1596
- }
1597
- /**
1598
- * Enqueues a send operation.
1599
- *
1600
- * @param {Array} params Send operation parameters.
1601
- * @private
1602
- */
1603
- enqueue(params) {
1604
- this._bufferedBytes += params[3][kByteLength];
1605
- this._queue.push(params);
1606
- }
1607
- /**
1608
- * Sends a frame.
1609
- *
1610
- * @param {(Buffer | String)[]} list The frame to send
1611
- * @param {Function} [cb] Callback
1612
- * @private
1613
- */
1614
- sendFrame(list, cb) {
1615
- if (list.length === 2) {
1616
- this._socket.cork();
1617
- this._socket.write(list[0]);
1618
- this._socket.write(list[1], cb);
1619
- this._socket.uncork();
1620
- } else this._socket.write(list[0], cb);
1621
- }
1622
- };
1623
- module.exports = Sender;
1624
- /**
1625
- * Calls queued callbacks with an error.
1626
- *
1627
- * @param {Sender} sender The `Sender` instance
1628
- * @param {Error} err The error to call the callbacks with
1629
- * @param {Function} [cb] The first callback
1630
- * @private
1631
- */
1632
- function callCallbacks(sender, err, cb) {
1633
- if (typeof cb === "function") cb(err);
1634
- for (let i = 0; i < sender._queue.length; i++) {
1635
- const params = sender._queue[i];
1636
- const callback = params[params.length - 1];
1637
- if (typeof callback === "function") callback(err);
1638
- }
1639
- }
1640
- /**
1641
- * Handles a `Sender` error.
1642
- *
1643
- * @param {Sender} sender The `Sender` instance
1644
- * @param {Error} err The error
1645
- * @param {Function} [cb] The first pending callback
1646
- * @private
1647
- */
1648
- function onError(sender, err, cb) {
1649
- callCallbacks(sender, err, cb);
1650
- sender.onerror(err);
1651
- }
1652
- }));
1653
-
1654
- //#endregion
1655
- //#region node_modules/ws/lib/event-target.js
1656
- var require_event_target = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1657
- const { kForOnEventAttribute, kListener } = require_constants();
1658
- const kCode = Symbol("kCode");
1659
- const kData = Symbol("kData");
1660
- const kError = Symbol("kError");
1661
- const kMessage = Symbol("kMessage");
1662
- const kReason = Symbol("kReason");
1663
- const kTarget = Symbol("kTarget");
1664
- const kType = Symbol("kType");
1665
- const kWasClean = Symbol("kWasClean");
1666
- /**
1667
- * Class representing an event.
1668
- */
1669
- var Event = class {
1670
- /**
1671
- * Create a new `Event`.
1672
- *
1673
- * @param {String} type The name of the event
1674
- * @throws {TypeError} If the `type` argument is not specified
1675
- */
1676
- constructor(type) {
1677
- this[kTarget] = null;
1678
- this[kType] = type;
1679
- }
1680
- /**
1681
- * @type {*}
1682
- */
1683
- get target() {
1684
- return this[kTarget];
1685
- }
1686
- /**
1687
- * @type {String}
1688
- */
1689
- get type() {
1690
- return this[kType];
1691
- }
1692
- };
1693
- Object.defineProperty(Event.prototype, "target", { enumerable: true });
1694
- Object.defineProperty(Event.prototype, "type", { enumerable: true });
1695
- /**
1696
- * Class representing a close event.
1697
- *
1698
- * @extends Event
1699
- */
1700
- var CloseEvent = class extends Event {
1701
- /**
1702
- * Create a new `CloseEvent`.
1703
- *
1704
- * @param {String} type The name of the event
1705
- * @param {Object} [options] A dictionary object that allows for setting
1706
- * attributes via object members of the same name
1707
- * @param {Number} [options.code=0] The status code explaining why the
1708
- * connection was closed
1709
- * @param {String} [options.reason=''] A human-readable string explaining why
1710
- * the connection was closed
1711
- * @param {Boolean} [options.wasClean=false] Indicates whether or not the
1712
- * connection was cleanly closed
1713
- */
1714
- constructor(type, options = {}) {
1715
- super(type);
1716
- this[kCode] = options.code === void 0 ? 0 : options.code;
1717
- this[kReason] = options.reason === void 0 ? "" : options.reason;
1718
- this[kWasClean] = options.wasClean === void 0 ? false : options.wasClean;
1719
- }
1720
- /**
1721
- * @type {Number}
1722
- */
1723
- get code() {
1724
- return this[kCode];
1725
- }
1726
- /**
1727
- * @type {String}
1728
- */
1729
- get reason() {
1730
- return this[kReason];
1731
- }
1732
- /**
1733
- * @type {Boolean}
1734
- */
1735
- get wasClean() {
1736
- return this[kWasClean];
1737
- }
1738
- };
1739
- Object.defineProperty(CloseEvent.prototype, "code", { enumerable: true });
1740
- Object.defineProperty(CloseEvent.prototype, "reason", { enumerable: true });
1741
- Object.defineProperty(CloseEvent.prototype, "wasClean", { enumerable: true });
1742
- /**
1743
- * Class representing an error event.
1744
- *
1745
- * @extends Event
1746
- */
1747
- var ErrorEvent = class extends Event {
1748
- /**
1749
- * Create a new `ErrorEvent`.
1750
- *
1751
- * @param {String} type The name of the event
1752
- * @param {Object} [options] A dictionary object that allows for setting
1753
- * attributes via object members of the same name
1754
- * @param {*} [options.error=null] The error that generated this event
1755
- * @param {String} [options.message=''] The error message
1756
- */
1757
- constructor(type, options = {}) {
1758
- super(type);
1759
- this[kError] = options.error === void 0 ? null : options.error;
1760
- this[kMessage] = options.message === void 0 ? "" : options.message;
1761
- }
1762
- /**
1763
- * @type {*}
1764
- */
1765
- get error() {
1766
- return this[kError];
1767
- }
1768
- /**
1769
- * @type {String}
1770
- */
1771
- get message() {
1772
- return this[kMessage];
1773
- }
1774
- };
1775
- Object.defineProperty(ErrorEvent.prototype, "error", { enumerable: true });
1776
- Object.defineProperty(ErrorEvent.prototype, "message", { enumerable: true });
1777
- /**
1778
- * Class representing a message event.
1779
- *
1780
- * @extends Event
1781
- */
1782
- var MessageEvent = class extends Event {
1783
- /**
1784
- * Create a new `MessageEvent`.
1785
- *
1786
- * @param {String} type The name of the event
1787
- * @param {Object} [options] A dictionary object that allows for setting
1788
- * attributes via object members of the same name
1789
- * @param {*} [options.data=null] The message content
1790
- */
1791
- constructor(type, options = {}) {
1792
- super(type);
1793
- this[kData] = options.data === void 0 ? null : options.data;
1794
- }
1795
- /**
1796
- * @type {*}
1797
- */
1798
- get data() {
1799
- return this[kData];
1800
- }
1801
- };
1802
- Object.defineProperty(MessageEvent.prototype, "data", { enumerable: true });
1803
- /**
1804
- * This provides methods for emulating the `EventTarget` interface. It's not
1805
- * meant to be used directly.
1806
- *
1807
- * @mixin
1808
- */
1809
- const EventTarget = {
1810
- addEventListener(type, handler, options = {}) {
1811
- for (const listener of this.listeners(type)) if (!options[kForOnEventAttribute] && listener[kListener] === handler && !listener[kForOnEventAttribute]) return;
1812
- let wrapper;
1813
- if (type === "message") wrapper = function onMessage(data, isBinary) {
1814
- const event = new MessageEvent("message", { data: isBinary ? data : data.toString() });
1815
- event[kTarget] = this;
1816
- callListener(handler, this, event);
1817
- };
1818
- else if (type === "close") wrapper = function onClose(code, message) {
1819
- const event = new CloseEvent("close", {
1820
- code,
1821
- reason: message.toString(),
1822
- wasClean: this._closeFrameReceived && this._closeFrameSent
1823
- });
1824
- event[kTarget] = this;
1825
- callListener(handler, this, event);
1826
- };
1827
- else if (type === "error") wrapper = function onError(error) {
1828
- const event = new ErrorEvent("error", {
1829
- error,
1830
- message: error.message
1831
- });
1832
- event[kTarget] = this;
1833
- callListener(handler, this, event);
1834
- };
1835
- else if (type === "open") wrapper = function onOpen() {
1836
- const event = new Event("open");
1837
- event[kTarget] = this;
1838
- callListener(handler, this, event);
1839
- };
1840
- else return;
1841
- wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];
1842
- wrapper[kListener] = handler;
1843
- if (options.once) this.once(type, wrapper);
1844
- else this.on(type, wrapper);
1845
- },
1846
- removeEventListener(type, handler) {
1847
- for (const listener of this.listeners(type)) if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {
1848
- this.removeListener(type, listener);
1849
- break;
1850
- }
1851
- }
1852
- };
1853
- module.exports = {
1854
- CloseEvent,
1855
- ErrorEvent,
1856
- Event,
1857
- EventTarget,
1858
- MessageEvent
1859
- };
1860
- /**
1861
- * Call an event listener
1862
- *
1863
- * @param {(Function|Object)} listener The listener to call
1864
- * @param {*} thisArg The value to use as `this`` when calling the listener
1865
- * @param {Event} event The event to pass to the listener
1866
- * @private
1867
- */
1868
- function callListener(listener, thisArg, event) {
1869
- if (typeof listener === "object" && listener.handleEvent) listener.handleEvent.call(listener, event);
1870
- else listener.call(thisArg, event);
1871
- }
1872
- }));
1873
-
1874
- //#endregion
1875
- //#region node_modules/ws/lib/extension.js
1876
- var require_extension = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1877
- const { tokenChars } = require_validation();
1878
- /**
1879
- * Adds an offer to the map of extension offers or a parameter to the map of
1880
- * parameters.
1881
- *
1882
- * @param {Object} dest The map of extension offers or parameters
1883
- * @param {String} name The extension or parameter name
1884
- * @param {(Object|Boolean|String)} elem The extension parameters or the
1885
- * parameter value
1886
- * @private
1887
- */
1888
- function push(dest, name, elem) {
1889
- if (dest[name] === void 0) dest[name] = [elem];
1890
- else dest[name].push(elem);
1891
- }
1892
- /**
1893
- * Parses the `Sec-WebSocket-Extensions` header into an object.
1894
- *
1895
- * @param {String} header The field value of the header
1896
- * @return {Object} The parsed object
1897
- * @public
1898
- */
1899
- function parse(header) {
1900
- const offers = Object.create(null);
1901
- let params = Object.create(null);
1902
- let mustUnescape = false;
1903
- let isEscaping = false;
1904
- let inQuotes = false;
1905
- let extensionName;
1906
- let paramName;
1907
- let start = -1;
1908
- let code = -1;
1909
- let end = -1;
1910
- let i = 0;
1911
- for (; i < header.length; i++) {
1912
- code = header.charCodeAt(i);
1913
- if (extensionName === void 0) if (end === -1 && tokenChars[code] === 1) {
1914
- if (start === -1) start = i;
1915
- } else if (i !== 0 && (code === 32 || code === 9)) {
1916
- if (end === -1 && start !== -1) end = i;
1917
- } else if (code === 59 || code === 44) {
1918
- if (start === -1) throw new SyntaxError(`Unexpected character at index ${i}`);
1919
- if (end === -1) end = i;
1920
- const name = header.slice(start, end);
1921
- if (code === 44) {
1922
- push(offers, name, params);
1923
- params = Object.create(null);
1924
- } else extensionName = name;
1925
- start = end = -1;
1926
- } else throw new SyntaxError(`Unexpected character at index ${i}`);
1927
- else if (paramName === void 0) if (end === -1 && tokenChars[code] === 1) {
1928
- if (start === -1) start = i;
1929
- } else if (code === 32 || code === 9) {
1930
- if (end === -1 && start !== -1) end = i;
1931
- } else if (code === 59 || code === 44) {
1932
- if (start === -1) throw new SyntaxError(`Unexpected character at index ${i}`);
1933
- if (end === -1) end = i;
1934
- push(params, header.slice(start, end), true);
1935
- if (code === 44) {
1936
- push(offers, extensionName, params);
1937
- params = Object.create(null);
1938
- extensionName = void 0;
1939
- }
1940
- start = end = -1;
1941
- } else if (code === 61 && start !== -1 && end === -1) {
1942
- paramName = header.slice(start, i);
1943
- start = end = -1;
1944
- } else throw new SyntaxError(`Unexpected character at index ${i}`);
1945
- else if (isEscaping) {
1946
- if (tokenChars[code] !== 1) throw new SyntaxError(`Unexpected character at index ${i}`);
1947
- if (start === -1) start = i;
1948
- else if (!mustUnescape) mustUnescape = true;
1949
- isEscaping = false;
1950
- } else if (inQuotes) if (tokenChars[code] === 1) {
1951
- if (start === -1) start = i;
1952
- } else if (code === 34 && start !== -1) {
1953
- inQuotes = false;
1954
- end = i;
1955
- } else if (code === 92) isEscaping = true;
1956
- else throw new SyntaxError(`Unexpected character at index ${i}`);
1957
- else if (code === 34 && header.charCodeAt(i - 1) === 61) inQuotes = true;
1958
- else if (end === -1 && tokenChars[code] === 1) {
1959
- if (start === -1) start = i;
1960
- } else if (start !== -1 && (code === 32 || code === 9)) {
1961
- if (end === -1) end = i;
1962
- } else if (code === 59 || code === 44) {
1963
- if (start === -1) throw new SyntaxError(`Unexpected character at index ${i}`);
1964
- if (end === -1) end = i;
1965
- let value = header.slice(start, end);
1966
- if (mustUnescape) {
1967
- value = value.replace(/\\/g, "");
1968
- mustUnescape = false;
1969
- }
1970
- push(params, paramName, value);
1971
- if (code === 44) {
1972
- push(offers, extensionName, params);
1973
- params = Object.create(null);
1974
- extensionName = void 0;
1975
- }
1976
- paramName = void 0;
1977
- start = end = -1;
1978
- } else throw new SyntaxError(`Unexpected character at index ${i}`);
1979
- }
1980
- if (start === -1 || inQuotes || code === 32 || code === 9) throw new SyntaxError("Unexpected end of input");
1981
- if (end === -1) end = i;
1982
- const token = header.slice(start, end);
1983
- if (extensionName === void 0) push(offers, token, params);
1984
- else {
1985
- if (paramName === void 0) push(params, token, true);
1986
- else if (mustUnescape) push(params, paramName, token.replace(/\\/g, ""));
1987
- else push(params, paramName, token);
1988
- push(offers, extensionName, params);
1989
- }
1990
- return offers;
1991
- }
1992
- /**
1993
- * Builds the `Sec-WebSocket-Extensions` header field value.
1994
- *
1995
- * @param {Object} extensions The map of extensions and parameters to format
1996
- * @return {String} A string representing the given object
1997
- * @public
1998
- */
1999
- function format(extensions) {
2000
- return Object.keys(extensions).map((extension$1) => {
2001
- let configurations = extensions[extension$1];
2002
- if (!Array.isArray(configurations)) configurations = [configurations];
2003
- return configurations.map((params) => {
2004
- return [extension$1].concat(Object.keys(params).map((k) => {
2005
- let values = params[k];
2006
- if (!Array.isArray(values)) values = [values];
2007
- return values.map((v) => v === true ? k : `${k}=${v}`).join("; ");
2008
- })).join("; ");
2009
- }).join(", ");
2010
- }).join(", ");
2011
- }
2012
- module.exports = {
2013
- format,
2014
- parse
2015
- };
2016
- }));
2017
-
2018
- //#endregion
2019
- //#region node_modules/ws/lib/websocket.js
2020
- var require_websocket = /* @__PURE__ */ __commonJSMin(((exports, module) => {
2021
- const EventEmitter$1 = __require("events");
2022
- const https = __require("https");
2023
- const http$1 = __require("http");
2024
- const net = __require("net");
2025
- const tls = __require("tls");
2026
- const { randomBytes, createHash: createHash$1 } = __require("crypto");
2027
- const { Duplex: Duplex$2, Readable } = __require("stream");
2028
- const { URL } = __require("url");
2029
- const PerMessageDeflate = require_permessage_deflate();
2030
- const Receiver = require_receiver();
2031
- const Sender = require_sender();
2032
- const { isBlob } = require_validation();
2033
- const { BINARY_TYPES, CLOSE_TIMEOUT, EMPTY_BUFFER, GUID, kForOnEventAttribute, kListener, kStatusCode, kWebSocket, NOOP } = require_constants();
2034
- const { EventTarget: { addEventListener, removeEventListener } } = require_event_target();
2035
- const { format, parse } = require_extension();
2036
- const { toBuffer } = require_buffer_util();
2037
- const kAborted = Symbol("kAborted");
2038
- const protocolVersions = [8, 13];
2039
- const readyStates = [
2040
- "CONNECTING",
2041
- "OPEN",
2042
- "CLOSING",
2043
- "CLOSED"
2044
- ];
2045
- const subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
2046
- /**
2047
- * Class representing a WebSocket.
2048
- *
2049
- * @extends EventEmitter
2050
- */
2051
- var WebSocket = class WebSocket extends EventEmitter$1 {
2052
- /**
2053
- * Create a new `WebSocket`.
2054
- *
2055
- * @param {(String|URL)} address The URL to which to connect
2056
- * @param {(String|String[])} [protocols] The subprotocols
2057
- * @param {Object} [options] Connection options
2058
- */
2059
- constructor(address, protocols, options) {
2060
- super();
2061
- this._binaryType = BINARY_TYPES[0];
2062
- this._closeCode = 1006;
2063
- this._closeFrameReceived = false;
2064
- this._closeFrameSent = false;
2065
- this._closeMessage = EMPTY_BUFFER;
2066
- this._closeTimer = null;
2067
- this._errorEmitted = false;
2068
- this._extensions = {};
2069
- this._paused = false;
2070
- this._protocol = "";
2071
- this._readyState = WebSocket.CONNECTING;
2072
- this._receiver = null;
2073
- this._sender = null;
2074
- this._socket = null;
2075
- if (address !== null) {
2076
- this._bufferedAmount = 0;
2077
- this._isServer = false;
2078
- this._redirects = 0;
2079
- if (protocols === void 0) protocols = [];
2080
- else if (!Array.isArray(protocols)) if (typeof protocols === "object" && protocols !== null) {
2081
- options = protocols;
2082
- protocols = [];
2083
- } else protocols = [protocols];
2084
- initAsClient(this, address, protocols, options);
2085
- } else {
2086
- this._autoPong = options.autoPong;
2087
- this._closeTimeout = options.closeTimeout;
2088
- this._isServer = true;
2089
- }
2090
- }
2091
- /**
2092
- * For historical reasons, the custom "nodebuffer" type is used by the default
2093
- * instead of "blob".
2094
- *
2095
- * @type {String}
2096
- */
2097
- get binaryType() {
2098
- return this._binaryType;
2099
- }
2100
- set binaryType(type) {
2101
- if (!BINARY_TYPES.includes(type)) return;
2102
- this._binaryType = type;
2103
- if (this._receiver) this._receiver._binaryType = type;
2104
- }
2105
- /**
2106
- * @type {Number}
2107
- */
2108
- get bufferedAmount() {
2109
- if (!this._socket) return this._bufferedAmount;
2110
- return this._socket._writableState.length + this._sender._bufferedBytes;
2111
- }
2112
- /**
2113
- * @type {String}
2114
- */
2115
- get extensions() {
2116
- return Object.keys(this._extensions).join();
2117
- }
2118
- /**
2119
- * @type {Boolean}
2120
- */
2121
- get isPaused() {
2122
- return this._paused;
2123
- }
2124
- /**
2125
- * @type {Function}
2126
- */
2127
- /* istanbul ignore next */
2128
- get onclose() {
2129
- return null;
2130
- }
2131
- /**
2132
- * @type {Function}
2133
- */
2134
- /* istanbul ignore next */
2135
- get onerror() {
2136
- return null;
2137
- }
2138
- /**
2139
- * @type {Function}
2140
- */
2141
- /* istanbul ignore next */
2142
- get onopen() {
2143
- return null;
2144
- }
2145
- /**
2146
- * @type {Function}
2147
- */
2148
- /* istanbul ignore next */
2149
- get onmessage() {
2150
- return null;
2151
- }
2152
- /**
2153
- * @type {String}
2154
- */
2155
- get protocol() {
2156
- return this._protocol;
2157
- }
2158
- /**
2159
- * @type {Number}
2160
- */
2161
- get readyState() {
2162
- return this._readyState;
2163
- }
2164
- /**
2165
- * @type {String}
2166
- */
2167
- get url() {
2168
- return this._url;
2169
- }
2170
- /**
2171
- * Set up the socket and the internal resources.
2172
- *
2173
- * @param {Duplex} socket The network socket between the server and client
2174
- * @param {Buffer} head The first packet of the upgraded stream
2175
- * @param {Object} options Options object
2176
- * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether
2177
- * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
2178
- * multiple times in the same tick
2179
- * @param {Function} [options.generateMask] The function used to generate the
2180
- * masking key
2181
- * @param {Number} [options.maxPayload=0] The maximum allowed message size
2182
- * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
2183
- * not to skip UTF-8 validation for text and close messages
2184
- * @private
2185
- */
2186
- setSocket(socket, head, options) {
2187
- const receiver = new Receiver({
2188
- allowSynchronousEvents: options.allowSynchronousEvents,
2189
- binaryType: this.binaryType,
2190
- extensions: this._extensions,
2191
- isServer: this._isServer,
2192
- maxPayload: options.maxPayload,
2193
- skipUTF8Validation: options.skipUTF8Validation
2194
- });
2195
- const sender = new Sender(socket, this._extensions, options.generateMask);
2196
- this._receiver = receiver;
2197
- this._sender = sender;
2198
- this._socket = socket;
2199
- receiver[kWebSocket] = this;
2200
- sender[kWebSocket] = this;
2201
- socket[kWebSocket] = this;
2202
- receiver.on("conclude", receiverOnConclude);
2203
- receiver.on("drain", receiverOnDrain);
2204
- receiver.on("error", receiverOnError);
2205
- receiver.on("message", receiverOnMessage);
2206
- receiver.on("ping", receiverOnPing);
2207
- receiver.on("pong", receiverOnPong);
2208
- sender.onerror = senderOnError;
2209
- if (socket.setTimeout) socket.setTimeout(0);
2210
- if (socket.setNoDelay) socket.setNoDelay();
2211
- if (head.length > 0) socket.unshift(head);
2212
- socket.on("close", socketOnClose);
2213
- socket.on("data", socketOnData);
2214
- socket.on("end", socketOnEnd);
2215
- socket.on("error", socketOnError);
2216
- this._readyState = WebSocket.OPEN;
2217
- this.emit("open");
2218
- }
2219
- /**
2220
- * Emit the `'close'` event.
2221
- *
2222
- * @private
2223
- */
2224
- emitClose() {
2225
- if (!this._socket) {
2226
- this._readyState = WebSocket.CLOSED;
2227
- this.emit("close", this._closeCode, this._closeMessage);
2228
- return;
2229
- }
2230
- if (this._extensions[PerMessageDeflate.extensionName]) this._extensions[PerMessageDeflate.extensionName].cleanup();
2231
- this._receiver.removeAllListeners();
2232
- this._readyState = WebSocket.CLOSED;
2233
- this.emit("close", this._closeCode, this._closeMessage);
2234
- }
2235
- /**
2236
- * Start a closing handshake.
2237
- *
2238
- * +----------+ +-----------+ +----------+
2239
- * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -
2240
- * | +----------+ +-----------+ +----------+ |
2241
- * +----------+ +-----------+ |
2242
- * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING
2243
- * +----------+ +-----------+ |
2244
- * | | | +---+ |
2245
- * +------------------------+-->|fin| - - - -
2246
- * | +---+ | +---+
2247
- * - - - - -|fin|<---------------------+
2248
- * +---+
2249
- *
2250
- * @param {Number} [code] Status code explaining why the connection is closing
2251
- * @param {(String|Buffer)} [data] The reason why the connection is
2252
- * closing
2253
- * @public
2254
- */
2255
- close(code, data) {
2256
- if (this.readyState === WebSocket.CLOSED) return;
2257
- if (this.readyState === WebSocket.CONNECTING) {
2258
- abortHandshake(this, this._req, "WebSocket was closed before the connection was established");
2259
- return;
2260
- }
2261
- if (this.readyState === WebSocket.CLOSING) {
2262
- if (this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted)) this._socket.end();
2263
- return;
2264
- }
2265
- this._readyState = WebSocket.CLOSING;
2266
- this._sender.close(code, data, !this._isServer, (err) => {
2267
- if (err) return;
2268
- this._closeFrameSent = true;
2269
- if (this._closeFrameReceived || this._receiver._writableState.errorEmitted) this._socket.end();
2270
- });
2271
- setCloseTimer(this);
2272
- }
2273
- /**
2274
- * Pause the socket.
2275
- *
2276
- * @public
2277
- */
2278
- pause() {
2279
- if (this.readyState === WebSocket.CONNECTING || this.readyState === WebSocket.CLOSED) return;
2280
- this._paused = true;
2281
- this._socket.pause();
2282
- }
2283
- /**
2284
- * Send a ping.
2285
- *
2286
- * @param {*} [data] The data to send
2287
- * @param {Boolean} [mask] Indicates whether or not to mask `data`
2288
- * @param {Function} [cb] Callback which is executed when the ping is sent
2289
- * @public
2290
- */
2291
- ping(data, mask, cb) {
2292
- if (this.readyState === WebSocket.CONNECTING) throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
2293
- if (typeof data === "function") {
2294
- cb = data;
2295
- data = mask = void 0;
2296
- } else if (typeof mask === "function") {
2297
- cb = mask;
2298
- mask = void 0;
2299
- }
2300
- if (typeof data === "number") data = data.toString();
2301
- if (this.readyState !== WebSocket.OPEN) {
2302
- sendAfterClose(this, data, cb);
2303
- return;
2304
- }
2305
- if (mask === void 0) mask = !this._isServer;
2306
- this._sender.ping(data || EMPTY_BUFFER, mask, cb);
2307
- }
2308
- /**
2309
- * Send a pong.
2310
- *
2311
- * @param {*} [data] The data to send
2312
- * @param {Boolean} [mask] Indicates whether or not to mask `data`
2313
- * @param {Function} [cb] Callback which is executed when the pong is sent
2314
- * @public
2315
- */
2316
- pong(data, mask, cb) {
2317
- if (this.readyState === WebSocket.CONNECTING) throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
2318
- if (typeof data === "function") {
2319
- cb = data;
2320
- data = mask = void 0;
2321
- } else if (typeof mask === "function") {
2322
- cb = mask;
2323
- mask = void 0;
2324
- }
2325
- if (typeof data === "number") data = data.toString();
2326
- if (this.readyState !== WebSocket.OPEN) {
2327
- sendAfterClose(this, data, cb);
2328
- return;
2329
- }
2330
- if (mask === void 0) mask = !this._isServer;
2331
- this._sender.pong(data || EMPTY_BUFFER, mask, cb);
2332
- }
2333
- /**
2334
- * Resume the socket.
2335
- *
2336
- * @public
2337
- */
2338
- resume() {
2339
- if (this.readyState === WebSocket.CONNECTING || this.readyState === WebSocket.CLOSED) return;
2340
- this._paused = false;
2341
- if (!this._receiver._writableState.needDrain) this._socket.resume();
2342
- }
2343
- /**
2344
- * Send a data message.
2345
- *
2346
- * @param {*} data The message to send
2347
- * @param {Object} [options] Options object
2348
- * @param {Boolean} [options.binary] Specifies whether `data` is binary or
2349
- * text
2350
- * @param {Boolean} [options.compress] Specifies whether or not to compress
2351
- * `data`
2352
- * @param {Boolean} [options.fin=true] Specifies whether the fragment is the
2353
- * last one
2354
- * @param {Boolean} [options.mask] Specifies whether or not to mask `data`
2355
- * @param {Function} [cb] Callback which is executed when data is written out
2356
- * @public
2357
- */
2358
- send(data, options, cb) {
2359
- if (this.readyState === WebSocket.CONNECTING) throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
2360
- if (typeof options === "function") {
2361
- cb = options;
2362
- options = {};
2363
- }
2364
- if (typeof data === "number") data = data.toString();
2365
- if (this.readyState !== WebSocket.OPEN) {
2366
- sendAfterClose(this, data, cb);
2367
- return;
2368
- }
2369
- const opts = {
2370
- binary: typeof data !== "string",
2371
- mask: !this._isServer,
2372
- compress: true,
2373
- fin: true,
2374
- ...options
2375
- };
2376
- if (!this._extensions[PerMessageDeflate.extensionName]) opts.compress = false;
2377
- this._sender.send(data || EMPTY_BUFFER, opts, cb);
2378
- }
2379
- /**
2380
- * Forcibly close the connection.
2381
- *
2382
- * @public
2383
- */
2384
- terminate() {
2385
- if (this.readyState === WebSocket.CLOSED) return;
2386
- if (this.readyState === WebSocket.CONNECTING) {
2387
- abortHandshake(this, this._req, "WebSocket was closed before the connection was established");
2388
- return;
2389
- }
2390
- if (this._socket) {
2391
- this._readyState = WebSocket.CLOSING;
2392
- this._socket.destroy();
2393
- }
2394
- }
2395
- };
2396
- /**
2397
- * @constant {Number} CONNECTING
2398
- * @memberof WebSocket
2399
- */
2400
- Object.defineProperty(WebSocket, "CONNECTING", {
2401
- enumerable: true,
2402
- value: readyStates.indexOf("CONNECTING")
2403
- });
2404
- /**
2405
- * @constant {Number} CONNECTING
2406
- * @memberof WebSocket.prototype
2407
- */
2408
- Object.defineProperty(WebSocket.prototype, "CONNECTING", {
2409
- enumerable: true,
2410
- value: readyStates.indexOf("CONNECTING")
2411
- });
2412
- /**
2413
- * @constant {Number} OPEN
2414
- * @memberof WebSocket
2415
- */
2416
- Object.defineProperty(WebSocket, "OPEN", {
2417
- enumerable: true,
2418
- value: readyStates.indexOf("OPEN")
2419
- });
2420
- /**
2421
- * @constant {Number} OPEN
2422
- * @memberof WebSocket.prototype
2423
- */
2424
- Object.defineProperty(WebSocket.prototype, "OPEN", {
2425
- enumerable: true,
2426
- value: readyStates.indexOf("OPEN")
2427
- });
2428
- /**
2429
- * @constant {Number} CLOSING
2430
- * @memberof WebSocket
2431
- */
2432
- Object.defineProperty(WebSocket, "CLOSING", {
2433
- enumerable: true,
2434
- value: readyStates.indexOf("CLOSING")
2435
- });
2436
- /**
2437
- * @constant {Number} CLOSING
2438
- * @memberof WebSocket.prototype
2439
- */
2440
- Object.defineProperty(WebSocket.prototype, "CLOSING", {
2441
- enumerable: true,
2442
- value: readyStates.indexOf("CLOSING")
2443
- });
2444
- /**
2445
- * @constant {Number} CLOSED
2446
- * @memberof WebSocket
2447
- */
2448
- Object.defineProperty(WebSocket, "CLOSED", {
2449
- enumerable: true,
2450
- value: readyStates.indexOf("CLOSED")
2451
- });
2452
- /**
2453
- * @constant {Number} CLOSED
2454
- * @memberof WebSocket.prototype
2455
- */
2456
- Object.defineProperty(WebSocket.prototype, "CLOSED", {
2457
- enumerable: true,
2458
- value: readyStates.indexOf("CLOSED")
2459
- });
2460
- [
2461
- "binaryType",
2462
- "bufferedAmount",
2463
- "extensions",
2464
- "isPaused",
2465
- "protocol",
2466
- "readyState",
2467
- "url"
2468
- ].forEach((property) => {
2469
- Object.defineProperty(WebSocket.prototype, property, { enumerable: true });
2470
- });
2471
- [
2472
- "open",
2473
- "error",
2474
- "close",
2475
- "message"
2476
- ].forEach((method) => {
2477
- Object.defineProperty(WebSocket.prototype, `on${method}`, {
2478
- enumerable: true,
2479
- get() {
2480
- for (const listener of this.listeners(method)) if (listener[kForOnEventAttribute]) return listener[kListener];
2481
- return null;
2482
- },
2483
- set(handler) {
2484
- for (const listener of this.listeners(method)) if (listener[kForOnEventAttribute]) {
2485
- this.removeListener(method, listener);
2486
- break;
2487
- }
2488
- if (typeof handler !== "function") return;
2489
- this.addEventListener(method, handler, { [kForOnEventAttribute]: true });
2490
- }
2491
- });
2492
- });
2493
- WebSocket.prototype.addEventListener = addEventListener;
2494
- WebSocket.prototype.removeEventListener = removeEventListener;
2495
- module.exports = WebSocket;
2496
- /**
2497
- * Initialize a WebSocket client.
2498
- *
2499
- * @param {WebSocket} websocket The client to initialize
2500
- * @param {(String|URL)} address The URL to which to connect
2501
- * @param {Array} protocols The subprotocols
2502
- * @param {Object} [options] Connection options
2503
- * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether any
2504
- * of the `'message'`, `'ping'`, and `'pong'` events can be emitted multiple
2505
- * times in the same tick
2506
- * @param {Boolean} [options.autoPong=true] Specifies whether or not to
2507
- * automatically send a pong in response to a ping
2508
- * @param {Number} [options.closeTimeout=30000] Duration in milliseconds to wait
2509
- * for the closing handshake to finish after `websocket.close()` is called
2510
- * @param {Function} [options.finishRequest] A function which can be used to
2511
- * customize the headers of each http request before it is sent
2512
- * @param {Boolean} [options.followRedirects=false] Whether or not to follow
2513
- * redirects
2514
- * @param {Function} [options.generateMask] The function used to generate the
2515
- * masking key
2516
- * @param {Number} [options.handshakeTimeout] Timeout in milliseconds for the
2517
- * handshake request
2518
- * @param {Number} [options.maxPayload=104857600] The maximum allowed message
2519
- * size
2520
- * @param {Number} [options.maxRedirects=10] The maximum number of redirects
2521
- * allowed
2522
- * @param {String} [options.origin] Value of the `Origin` or
2523
- * `Sec-WebSocket-Origin` header
2524
- * @param {(Boolean|Object)} [options.perMessageDeflate=true] Enable/disable
2525
- * permessage-deflate
2526
- * @param {Number} [options.protocolVersion=13] Value of the
2527
- * `Sec-WebSocket-Version` header
2528
- * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
2529
- * not to skip UTF-8 validation for text and close messages
2530
- * @private
2531
- */
2532
- function initAsClient(websocket, address, protocols, options) {
2533
- const opts = {
2534
- allowSynchronousEvents: true,
2535
- autoPong: true,
2536
- closeTimeout: CLOSE_TIMEOUT,
2537
- protocolVersion: protocolVersions[1],
2538
- maxPayload: 100 * 1024 * 1024,
2539
- skipUTF8Validation: false,
2540
- perMessageDeflate: true,
2541
- followRedirects: false,
2542
- maxRedirects: 10,
2543
- ...options,
2544
- socketPath: void 0,
2545
- hostname: void 0,
2546
- protocol: void 0,
2547
- timeout: void 0,
2548
- method: "GET",
2549
- host: void 0,
2550
- path: void 0,
2551
- port: void 0
2552
- };
2553
- websocket._autoPong = opts.autoPong;
2554
- websocket._closeTimeout = opts.closeTimeout;
2555
- if (!protocolVersions.includes(opts.protocolVersion)) throw new RangeError(`Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`);
2556
- let parsedUrl;
2557
- if (address instanceof URL) parsedUrl = address;
2558
- else try {
2559
- parsedUrl = new URL(address);
2560
- } catch {
2561
- throw new SyntaxError(`Invalid URL: ${address}`);
2562
- }
2563
- if (parsedUrl.protocol === "http:") parsedUrl.protocol = "ws:";
2564
- else if (parsedUrl.protocol === "https:") parsedUrl.protocol = "wss:";
2565
- websocket._url = parsedUrl.href;
2566
- const isSecure = parsedUrl.protocol === "wss:";
2567
- const isIpcUrl = parsedUrl.protocol === "ws+unix:";
2568
- let invalidUrlMessage;
2569
- if (parsedUrl.protocol !== "ws:" && !isSecure && !isIpcUrl) invalidUrlMessage = "The URL's protocol must be one of \"ws:\", \"wss:\", \"http:\", \"https:\", or \"ws+unix:\"";
2570
- else if (isIpcUrl && !parsedUrl.pathname) invalidUrlMessage = "The URL's pathname is empty";
2571
- else if (parsedUrl.hash) invalidUrlMessage = "The URL contains a fragment identifier";
2572
- if (invalidUrlMessage) {
2573
- const err = new SyntaxError(invalidUrlMessage);
2574
- if (websocket._redirects === 0) throw err;
2575
- else {
2576
- emitErrorAndClose(websocket, err);
2577
- return;
2578
- }
2579
- }
2580
- const defaultPort = isSecure ? 443 : 80;
2581
- const key = randomBytes(16).toString("base64");
2582
- const request = isSecure ? https.request : http$1.request;
2583
- const protocolSet = /* @__PURE__ */ new Set();
2584
- let perMessageDeflate;
2585
- opts.createConnection = opts.createConnection || (isSecure ? tlsConnect : netConnect);
2586
- opts.defaultPort = opts.defaultPort || defaultPort;
2587
- opts.port = parsedUrl.port || defaultPort;
2588
- opts.host = parsedUrl.hostname.startsWith("[") ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname;
2589
- opts.headers = {
2590
- ...opts.headers,
2591
- "Sec-WebSocket-Version": opts.protocolVersion,
2592
- "Sec-WebSocket-Key": key,
2593
- Connection: "Upgrade",
2594
- Upgrade: "websocket"
2595
- };
2596
- opts.path = parsedUrl.pathname + parsedUrl.search;
2597
- opts.timeout = opts.handshakeTimeout;
2598
- if (opts.perMessageDeflate) {
2599
- perMessageDeflate = new PerMessageDeflate({
2600
- ...opts.perMessageDeflate,
2601
- isServer: false,
2602
- maxPayload: opts.maxPayload
2603
- });
2604
- opts.headers["Sec-WebSocket-Extensions"] = format({ [PerMessageDeflate.extensionName]: perMessageDeflate.offer() });
2605
- }
2606
- if (protocols.length) {
2607
- for (const protocol of protocols) {
2608
- if (typeof protocol !== "string" || !subprotocolRegex.test(protocol) || protocolSet.has(protocol)) throw new SyntaxError("An invalid or duplicated subprotocol was specified");
2609
- protocolSet.add(protocol);
2610
- }
2611
- opts.headers["Sec-WebSocket-Protocol"] = protocols.join(",");
2612
- }
2613
- if (opts.origin) if (opts.protocolVersion < 13) opts.headers["Sec-WebSocket-Origin"] = opts.origin;
2614
- else opts.headers.Origin = opts.origin;
2615
- if (parsedUrl.username || parsedUrl.password) opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
2616
- if (isIpcUrl) {
2617
- const parts = opts.path.split(":");
2618
- opts.socketPath = parts[0];
2619
- opts.path = parts[1];
2620
- }
2621
- let req;
2622
- if (opts.followRedirects) {
2623
- if (websocket._redirects === 0) {
2624
- websocket._originalIpc = isIpcUrl;
2625
- websocket._originalSecure = isSecure;
2626
- websocket._originalHostOrSocketPath = isIpcUrl ? opts.socketPath : parsedUrl.host;
2627
- const headers = options && options.headers;
2628
- options = {
2629
- ...options,
2630
- headers: {}
2631
- };
2632
- if (headers) for (const [key$1, value] of Object.entries(headers)) options.headers[key$1.toLowerCase()] = value;
2633
- } else if (websocket.listenerCount("redirect") === 0) {
2634
- const isSameHost = isIpcUrl ? websocket._originalIpc ? opts.socketPath === websocket._originalHostOrSocketPath : false : websocket._originalIpc ? false : parsedUrl.host === websocket._originalHostOrSocketPath;
2635
- if (!isSameHost || websocket._originalSecure && !isSecure) {
2636
- delete opts.headers.authorization;
2637
- delete opts.headers.cookie;
2638
- if (!isSameHost) delete opts.headers.host;
2639
- opts.auth = void 0;
2640
- }
2641
- }
2642
- if (opts.auth && !options.headers.authorization) options.headers.authorization = "Basic " + Buffer.from(opts.auth).toString("base64");
2643
- req = websocket._req = request(opts);
2644
- if (websocket._redirects) websocket.emit("redirect", websocket.url, req);
2645
- } else req = websocket._req = request(opts);
2646
- if (opts.timeout) req.on("timeout", () => {
2647
- abortHandshake(websocket, req, "Opening handshake has timed out");
2648
- });
2649
- req.on("error", (err) => {
2650
- if (req === null || req[kAborted]) return;
2651
- req = websocket._req = null;
2652
- emitErrorAndClose(websocket, err);
2653
- });
2654
- req.on("response", (res) => {
2655
- const location = res.headers.location;
2656
- const statusCode = res.statusCode;
2657
- if (location && opts.followRedirects && statusCode >= 300 && statusCode < 400) {
2658
- if (++websocket._redirects > opts.maxRedirects) {
2659
- abortHandshake(websocket, req, "Maximum redirects exceeded");
2660
- return;
2661
- }
2662
- req.abort();
2663
- let addr;
2664
- try {
2665
- addr = new URL(location, address);
2666
- } catch (e) {
2667
- emitErrorAndClose(websocket, /* @__PURE__ */ new SyntaxError(`Invalid URL: ${location}`));
2668
- return;
2669
- }
2670
- initAsClient(websocket, addr, protocols, options);
2671
- } else if (!websocket.emit("unexpected-response", req, res)) abortHandshake(websocket, req, `Unexpected server response: ${res.statusCode}`);
2672
- });
2673
- req.on("upgrade", (res, socket, head) => {
2674
- websocket.emit("upgrade", res);
2675
- if (websocket.readyState !== WebSocket.CONNECTING) return;
2676
- req = websocket._req = null;
2677
- const upgrade = res.headers.upgrade;
2678
- if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
2679
- abortHandshake(websocket, socket, "Invalid Upgrade header");
2680
- return;
2681
- }
2682
- const digest = createHash$1("sha1").update(key + GUID).digest("base64");
2683
- if (res.headers["sec-websocket-accept"] !== digest) {
2684
- abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
2685
- return;
2686
- }
2687
- const serverProt = res.headers["sec-websocket-protocol"];
2688
- let protError;
2689
- if (serverProt !== void 0) {
2690
- if (!protocolSet.size) protError = "Server sent a subprotocol but none was requested";
2691
- else if (!protocolSet.has(serverProt)) protError = "Server sent an invalid subprotocol";
2692
- } else if (protocolSet.size) protError = "Server sent no subprotocol";
2693
- if (protError) {
2694
- abortHandshake(websocket, socket, protError);
2695
- return;
2696
- }
2697
- if (serverProt) websocket._protocol = serverProt;
2698
- const secWebSocketExtensions = res.headers["sec-websocket-extensions"];
2699
- if (secWebSocketExtensions !== void 0) {
2700
- if (!perMessageDeflate) {
2701
- abortHandshake(websocket, socket, "Server sent a Sec-WebSocket-Extensions header but no extension was requested");
2702
- return;
2703
- }
2704
- let extensions;
2705
- try {
2706
- extensions = parse(secWebSocketExtensions);
2707
- } catch (err) {
2708
- abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Extensions header");
2709
- return;
2710
- }
2711
- const extensionNames = Object.keys(extensions);
2712
- if (extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate.extensionName) {
2713
- abortHandshake(websocket, socket, "Server indicated an extension that was not requested");
2714
- return;
2715
- }
2716
- try {
2717
- perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]);
2718
- } catch (err) {
2719
- abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Extensions header");
2720
- return;
2721
- }
2722
- websocket._extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
2723
- }
2724
- websocket.setSocket(socket, head, {
2725
- allowSynchronousEvents: opts.allowSynchronousEvents,
2726
- generateMask: opts.generateMask,
2727
- maxPayload: opts.maxPayload,
2728
- skipUTF8Validation: opts.skipUTF8Validation
2729
- });
2730
- });
2731
- if (opts.finishRequest) opts.finishRequest(req, websocket);
2732
- else req.end();
2733
- }
2734
- /**
2735
- * Emit the `'error'` and `'close'` events.
2736
- *
2737
- * @param {WebSocket} websocket The WebSocket instance
2738
- * @param {Error} The error to emit
2739
- * @private
2740
- */
2741
- function emitErrorAndClose(websocket, err) {
2742
- websocket._readyState = WebSocket.CLOSING;
2743
- websocket._errorEmitted = true;
2744
- websocket.emit("error", err);
2745
- websocket.emitClose();
2746
- }
2747
- /**
2748
- * Create a `net.Socket` and initiate a connection.
2749
- *
2750
- * @param {Object} options Connection options
2751
- * @return {net.Socket} The newly created socket used to start the connection
2752
- * @private
2753
- */
2754
- function netConnect(options) {
2755
- options.path = options.socketPath;
2756
- return net.connect(options);
2757
- }
2758
- /**
2759
- * Create a `tls.TLSSocket` and initiate a connection.
2760
- *
2761
- * @param {Object} options Connection options
2762
- * @return {tls.TLSSocket} The newly created socket used to start the connection
2763
- * @private
2764
- */
2765
- function tlsConnect(options) {
2766
- options.path = void 0;
2767
- if (!options.servername && options.servername !== "") options.servername = net.isIP(options.host) ? "" : options.host;
2768
- return tls.connect(options);
2769
- }
2770
- /**
2771
- * Abort the handshake and emit an error.
2772
- *
2773
- * @param {WebSocket} websocket The WebSocket instance
2774
- * @param {(http.ClientRequest|net.Socket|tls.Socket)} stream The request to
2775
- * abort or the socket to destroy
2776
- * @param {String} message The error message
2777
- * @private
2778
- */
2779
- function abortHandshake(websocket, stream, message) {
2780
- websocket._readyState = WebSocket.CLOSING;
2781
- const err = new Error(message);
2782
- Error.captureStackTrace(err, abortHandshake);
2783
- if (stream.setHeader) {
2784
- stream[kAborted] = true;
2785
- stream.abort();
2786
- if (stream.socket && !stream.socket.destroyed) stream.socket.destroy();
2787
- process.nextTick(emitErrorAndClose, websocket, err);
2788
- } else {
2789
- stream.destroy(err);
2790
- stream.once("error", websocket.emit.bind(websocket, "error"));
2791
- stream.once("close", websocket.emitClose.bind(websocket));
2792
- }
2793
- }
2794
- /**
2795
- * Handle cases where the `ping()`, `pong()`, or `send()` methods are called
2796
- * when the `readyState` attribute is `CLOSING` or `CLOSED`.
2797
- *
2798
- * @param {WebSocket} websocket The WebSocket instance
2799
- * @param {*} [data] The data to send
2800
- * @param {Function} [cb] Callback
2801
- * @private
2802
- */
2803
- function sendAfterClose(websocket, data, cb) {
2804
- if (data) {
2805
- const length = isBlob(data) ? data.size : toBuffer(data).length;
2806
- if (websocket._socket) websocket._sender._bufferedBytes += length;
2807
- else websocket._bufferedAmount += length;
2808
- }
2809
- if (cb) {
2810
- const err = /* @__PURE__ */ new Error(`WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})`);
2811
- process.nextTick(cb, err);
2812
- }
2813
- }
2814
- /**
2815
- * The listener of the `Receiver` `'conclude'` event.
2816
- *
2817
- * @param {Number} code The status code
2818
- * @param {Buffer} reason The reason for closing
2819
- * @private
2820
- */
2821
- function receiverOnConclude(code, reason) {
2822
- const websocket = this[kWebSocket];
2823
- websocket._closeFrameReceived = true;
2824
- websocket._closeMessage = reason;
2825
- websocket._closeCode = code;
2826
- if (websocket._socket[kWebSocket] === void 0) return;
2827
- websocket._socket.removeListener("data", socketOnData);
2828
- process.nextTick(resume, websocket._socket);
2829
- if (code === 1005) websocket.close();
2830
- else websocket.close(code, reason);
2831
- }
2832
- /**
2833
- * The listener of the `Receiver` `'drain'` event.
2834
- *
2835
- * @private
2836
- */
2837
- function receiverOnDrain() {
2838
- const websocket = this[kWebSocket];
2839
- if (!websocket.isPaused) websocket._socket.resume();
2840
- }
2841
- /**
2842
- * The listener of the `Receiver` `'error'` event.
2843
- *
2844
- * @param {(RangeError|Error)} err The emitted error
2845
- * @private
2846
- */
2847
- function receiverOnError(err) {
2848
- const websocket = this[kWebSocket];
2849
- if (websocket._socket[kWebSocket] !== void 0) {
2850
- websocket._socket.removeListener("data", socketOnData);
2851
- process.nextTick(resume, websocket._socket);
2852
- websocket.close(err[kStatusCode]);
2853
- }
2854
- if (!websocket._errorEmitted) {
2855
- websocket._errorEmitted = true;
2856
- websocket.emit("error", err);
2857
- }
2858
- }
2859
- /**
2860
- * The listener of the `Receiver` `'finish'` event.
2861
- *
2862
- * @private
2863
- */
2864
- function receiverOnFinish() {
2865
- this[kWebSocket].emitClose();
2866
- }
2867
- /**
2868
- * The listener of the `Receiver` `'message'` event.
2869
- *
2870
- * @param {Buffer|ArrayBuffer|Buffer[])} data The message
2871
- * @param {Boolean} isBinary Specifies whether the message is binary or not
2872
- * @private
2873
- */
2874
- function receiverOnMessage(data, isBinary) {
2875
- this[kWebSocket].emit("message", data, isBinary);
2876
- }
2877
- /**
2878
- * The listener of the `Receiver` `'ping'` event.
2879
- *
2880
- * @param {Buffer} data The data included in the ping frame
2881
- * @private
2882
- */
2883
- function receiverOnPing(data) {
2884
- const websocket = this[kWebSocket];
2885
- if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP);
2886
- websocket.emit("ping", data);
2887
- }
2888
- /**
2889
- * The listener of the `Receiver` `'pong'` event.
2890
- *
2891
- * @param {Buffer} data The data included in the pong frame
2892
- * @private
2893
- */
2894
- function receiverOnPong(data) {
2895
- this[kWebSocket].emit("pong", data);
2896
- }
2897
- /**
2898
- * Resume a readable stream
2899
- *
2900
- * @param {Readable} stream The readable stream
2901
- * @private
2902
- */
2903
- function resume(stream) {
2904
- stream.resume();
2905
- }
2906
- /**
2907
- * The `Sender` error event handler.
2908
- *
2909
- * @param {Error} The error
2910
- * @private
2911
- */
2912
- function senderOnError(err) {
2913
- const websocket = this[kWebSocket];
2914
- if (websocket.readyState === WebSocket.CLOSED) return;
2915
- if (websocket.readyState === WebSocket.OPEN) {
2916
- websocket._readyState = WebSocket.CLOSING;
2917
- setCloseTimer(websocket);
2918
- }
2919
- this._socket.end();
2920
- if (!websocket._errorEmitted) {
2921
- websocket._errorEmitted = true;
2922
- websocket.emit("error", err);
2923
- }
2924
- }
2925
- /**
2926
- * Set a timer to destroy the underlying raw socket of a WebSocket.
2927
- *
2928
- * @param {WebSocket} websocket The WebSocket instance
2929
- * @private
2930
- */
2931
- function setCloseTimer(websocket) {
2932
- websocket._closeTimer = setTimeout(websocket._socket.destroy.bind(websocket._socket), websocket._closeTimeout);
2933
- }
2934
- /**
2935
- * The listener of the socket `'close'` event.
2936
- *
2937
- * @private
2938
- */
2939
- function socketOnClose() {
2940
- const websocket = this[kWebSocket];
2941
- this.removeListener("close", socketOnClose);
2942
- this.removeListener("data", socketOnData);
2943
- this.removeListener("end", socketOnEnd);
2944
- websocket._readyState = WebSocket.CLOSING;
2945
- if (!this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && this._readableState.length !== 0) {
2946
- const chunk = this.read(this._readableState.length);
2947
- websocket._receiver.write(chunk);
2948
- }
2949
- websocket._receiver.end();
2950
- this[kWebSocket] = void 0;
2951
- clearTimeout(websocket._closeTimer);
2952
- if (websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted) websocket.emitClose();
2953
- else {
2954
- websocket._receiver.on("error", receiverOnFinish);
2955
- websocket._receiver.on("finish", receiverOnFinish);
2956
- }
2957
- }
2958
- /**
2959
- * The listener of the socket `'data'` event.
2960
- *
2961
- * @param {Buffer} chunk A chunk of data
2962
- * @private
2963
- */
2964
- function socketOnData(chunk) {
2965
- if (!this[kWebSocket]._receiver.write(chunk)) this.pause();
2966
- }
2967
- /**
2968
- * The listener of the socket `'end'` event.
2969
- *
2970
- * @private
2971
- */
2972
- function socketOnEnd() {
2973
- const websocket = this[kWebSocket];
2974
- websocket._readyState = WebSocket.CLOSING;
2975
- websocket._receiver.end();
2976
- this.end();
2977
- }
2978
- /**
2979
- * The listener of the socket `'error'` event.
2980
- *
2981
- * @private
2982
- */
2983
- function socketOnError() {
2984
- const websocket = this[kWebSocket];
2985
- this.removeListener("error", socketOnError);
2986
- this.on("error", NOOP);
2987
- if (websocket) {
2988
- websocket._readyState = WebSocket.CLOSING;
2989
- this.destroy();
2990
- }
2991
- }
2992
- }));
2993
-
2994
- //#endregion
2995
- //#region node_modules/ws/lib/stream.js
2996
- var require_stream = /* @__PURE__ */ __commonJSMin(((exports, module) => {
2997
- require_websocket();
2998
- const { Duplex: Duplex$1 } = __require("stream");
2999
- /**
3000
- * Emits the `'close'` event on a stream.
3001
- *
3002
- * @param {Duplex} stream The stream.
3003
- * @private
3004
- */
3005
- function emitClose(stream) {
3006
- stream.emit("close");
3007
- }
3008
- /**
3009
- * The listener of the `'end'` event.
3010
- *
3011
- * @private
3012
- */
3013
- function duplexOnEnd() {
3014
- if (!this.destroyed && this._writableState.finished) this.destroy();
3015
- }
3016
- /**
3017
- * The listener of the `'error'` event.
3018
- *
3019
- * @param {Error} err The error
3020
- * @private
3021
- */
3022
- function duplexOnError(err) {
3023
- this.removeListener("error", duplexOnError);
3024
- this.destroy();
3025
- if (this.listenerCount("error") === 0) this.emit("error", err);
3026
- }
3027
- /**
3028
- * Wraps a `WebSocket` in a duplex stream.
3029
- *
3030
- * @param {WebSocket} ws The `WebSocket` to wrap
3031
- * @param {Object} [options] The options for the `Duplex` constructor
3032
- * @return {Duplex} The duplex stream
3033
- * @public
3034
- */
3035
- function createWebSocketStream(ws, options) {
3036
- let terminateOnDestroy = true;
3037
- const duplex = new Duplex$1({
3038
- ...options,
3039
- autoDestroy: false,
3040
- emitClose: false,
3041
- objectMode: false,
3042
- writableObjectMode: false
3043
- });
3044
- ws.on("message", function message(msg, isBinary) {
3045
- const data = !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;
3046
- if (!duplex.push(data)) ws.pause();
3047
- });
3048
- ws.once("error", function error(err) {
3049
- if (duplex.destroyed) return;
3050
- terminateOnDestroy = false;
3051
- duplex.destroy(err);
3052
- });
3053
- ws.once("close", function close() {
3054
- if (duplex.destroyed) return;
3055
- duplex.push(null);
3056
- });
3057
- duplex._destroy = function(err, callback) {
3058
- if (ws.readyState === ws.CLOSED) {
3059
- callback(err);
3060
- process.nextTick(emitClose, duplex);
3061
- return;
3062
- }
3063
- let called = false;
3064
- ws.once("error", function error(err$1) {
3065
- called = true;
3066
- callback(err$1);
3067
- });
3068
- ws.once("close", function close() {
3069
- if (!called) callback(err);
3070
- process.nextTick(emitClose, duplex);
3071
- });
3072
- if (terminateOnDestroy) ws.terminate();
3073
- };
3074
- duplex._final = function(callback) {
3075
- if (ws.readyState === ws.CONNECTING) {
3076
- ws.once("open", function open() {
3077
- duplex._final(callback);
3078
- });
3079
- return;
3080
- }
3081
- if (ws._socket === null) return;
3082
- if (ws._socket._writableState.finished) {
3083
- callback();
3084
- if (duplex._readableState.endEmitted) duplex.destroy();
3085
- } else {
3086
- ws._socket.once("finish", function finish() {
3087
- callback();
3088
- });
3089
- ws.close();
3090
- }
3091
- };
3092
- duplex._read = function() {
3093
- if (ws.isPaused) ws.resume();
3094
- };
3095
- duplex._write = function(chunk, encoding, callback) {
3096
- if (ws.readyState === ws.CONNECTING) {
3097
- ws.once("open", function open() {
3098
- duplex._write(chunk, encoding, callback);
3099
- });
3100
- return;
3101
- }
3102
- ws.send(chunk, callback);
3103
- };
3104
- duplex.on("end", duplexOnEnd);
3105
- duplex.on("error", duplexOnError);
3106
- return duplex;
3107
- }
3108
- module.exports = createWebSocketStream;
3109
- }));
3110
-
3111
- //#endregion
3112
- //#region node_modules/ws/lib/subprotocol.js
3113
- var require_subprotocol = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3114
- const { tokenChars } = require_validation();
3115
- /**
3116
- * Parses the `Sec-WebSocket-Protocol` header into a set of subprotocol names.
3117
- *
3118
- * @param {String} header The field value of the header
3119
- * @return {Set} The subprotocol names
3120
- * @public
3121
- */
3122
- function parse(header) {
3123
- const protocols = /* @__PURE__ */ new Set();
3124
- let start = -1;
3125
- let end = -1;
3126
- let i = 0;
3127
- for (; i < header.length; i++) {
3128
- const code = header.charCodeAt(i);
3129
- if (end === -1 && tokenChars[code] === 1) {
3130
- if (start === -1) start = i;
3131
- } else if (i !== 0 && (code === 32 || code === 9)) {
3132
- if (end === -1 && start !== -1) end = i;
3133
- } else if (code === 44) {
3134
- if (start === -1) throw new SyntaxError(`Unexpected character at index ${i}`);
3135
- if (end === -1) end = i;
3136
- const protocol$1 = header.slice(start, end);
3137
- if (protocols.has(protocol$1)) throw new SyntaxError(`The "${protocol$1}" subprotocol is duplicated`);
3138
- protocols.add(protocol$1);
3139
- start = end = -1;
3140
- } else throw new SyntaxError(`Unexpected character at index ${i}`);
3141
- }
3142
- if (start === -1 || end !== -1) throw new SyntaxError("Unexpected end of input");
3143
- const protocol = header.slice(start, i);
3144
- if (protocols.has(protocol)) throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
3145
- protocols.add(protocol);
3146
- return protocols;
3147
- }
3148
- module.exports = { parse };
3149
- }));
3150
-
3151
- //#endregion
3152
- //#region node_modules/ws/lib/websocket-server.js
3153
- var require_websocket_server = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3154
- const EventEmitter = __require("events");
3155
- const http = __require("http");
3156
- const { Duplex } = __require("stream");
3157
- const { createHash } = __require("crypto");
3158
- const extension = require_extension();
3159
- const PerMessageDeflate = require_permessage_deflate();
3160
- const subprotocol = require_subprotocol();
3161
- const WebSocket = require_websocket();
3162
- const { CLOSE_TIMEOUT, GUID, kWebSocket } = require_constants();
3163
- const keyRegex = /^[+/0-9A-Za-z]{22}==$/;
3164
- const RUNNING = 0;
3165
- const CLOSING = 1;
3166
- const CLOSED = 2;
3167
- /**
3168
- * Class representing a WebSocket server.
3169
- *
3170
- * @extends EventEmitter
3171
- */
3172
- var WebSocketServer = class extends EventEmitter {
3173
- /**
3174
- * Create a `WebSocketServer` instance.
3175
- *
3176
- * @param {Object} options Configuration options
3177
- * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
3178
- * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
3179
- * multiple times in the same tick
3180
- * @param {Boolean} [options.autoPong=true] Specifies whether or not to
3181
- * automatically send a pong in response to a ping
3182
- * @param {Number} [options.backlog=511] The maximum length of the queue of
3183
- * pending connections
3184
- * @param {Boolean} [options.clientTracking=true] Specifies whether or not to
3185
- * track clients
3186
- * @param {Number} [options.closeTimeout=30000] Duration in milliseconds to
3187
- * wait for the closing handshake to finish after `websocket.close()` is
3188
- * called
3189
- * @param {Function} [options.handleProtocols] A hook to handle protocols
3190
- * @param {String} [options.host] The hostname where to bind the server
3191
- * @param {Number} [options.maxPayload=104857600] The maximum allowed message
3192
- * size
3193
- * @param {Boolean} [options.noServer=false] Enable no server mode
3194
- * @param {String} [options.path] Accept only connections matching this path
3195
- * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable
3196
- * permessage-deflate
3197
- * @param {Number} [options.port] The port where to bind the server
3198
- * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S
3199
- * server to use
3200
- * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
3201
- * not to skip UTF-8 validation for text and close messages
3202
- * @param {Function} [options.verifyClient] A hook to reject connections
3203
- * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`
3204
- * class to use. It must be the `WebSocket` class or class that extends it
3205
- * @param {Function} [callback] A listener for the `listening` event
3206
- */
3207
- constructor(options, callback) {
3208
- super();
3209
- options = {
3210
- allowSynchronousEvents: true,
3211
- autoPong: true,
3212
- maxPayload: 100 * 1024 * 1024,
3213
- skipUTF8Validation: false,
3214
- perMessageDeflate: false,
3215
- handleProtocols: null,
3216
- clientTracking: true,
3217
- closeTimeout: CLOSE_TIMEOUT,
3218
- verifyClient: null,
3219
- noServer: false,
3220
- backlog: null,
3221
- server: null,
3222
- host: null,
3223
- path: null,
3224
- port: null,
3225
- WebSocket,
3226
- ...options
3227
- };
3228
- if (options.port == null && !options.server && !options.noServer || options.port != null && (options.server || options.noServer) || options.server && options.noServer) throw new TypeError("One and only one of the \"port\", \"server\", or \"noServer\" options must be specified");
3229
- if (options.port != null) {
3230
- this._server = http.createServer((req, res) => {
3231
- const body = http.STATUS_CODES[426];
3232
- res.writeHead(426, {
3233
- "Content-Length": body.length,
3234
- "Content-Type": "text/plain"
3235
- });
3236
- res.end(body);
3237
- });
3238
- this._server.listen(options.port, options.host, options.backlog, callback);
3239
- } else if (options.server) this._server = options.server;
3240
- if (this._server) {
3241
- const emitConnection = this.emit.bind(this, "connection");
3242
- this._removeListeners = addListeners(this._server, {
3243
- listening: this.emit.bind(this, "listening"),
3244
- error: this.emit.bind(this, "error"),
3245
- upgrade: (req, socket, head) => {
3246
- this.handleUpgrade(req, socket, head, emitConnection);
3247
- }
3248
- });
3249
- }
3250
- if (options.perMessageDeflate === true) options.perMessageDeflate = {};
3251
- if (options.clientTracking) {
3252
- this.clients = /* @__PURE__ */ new Set();
3253
- this._shouldEmitClose = false;
3254
- }
3255
- this.options = options;
3256
- this._state = RUNNING;
3257
- }
3258
- /**
3259
- * Returns the bound address, the address family name, and port of the server
3260
- * as reported by the operating system if listening on an IP socket.
3261
- * If the server is listening on a pipe or UNIX domain socket, the name is
3262
- * returned as a string.
3263
- *
3264
- * @return {(Object|String|null)} The address of the server
3265
- * @public
3266
- */
3267
- address() {
3268
- if (this.options.noServer) throw new Error("The server is operating in \"noServer\" mode");
3269
- if (!this._server) return null;
3270
- return this._server.address();
3271
- }
3272
- /**
3273
- * Stop the server from accepting new connections and emit the `'close'` event
3274
- * when all existing connections are closed.
3275
- *
3276
- * @param {Function} [cb] A one-time listener for the `'close'` event
3277
- * @public
3278
- */
3279
- close(cb) {
3280
- if (this._state === CLOSED) {
3281
- if (cb) this.once("close", () => {
3282
- cb(/* @__PURE__ */ new Error("The server is not running"));
3283
- });
3284
- process.nextTick(emitClose, this);
3285
- return;
3286
- }
3287
- if (cb) this.once("close", cb);
3288
- if (this._state === CLOSING) return;
3289
- this._state = CLOSING;
3290
- if (this.options.noServer || this.options.server) {
3291
- if (this._server) {
3292
- this._removeListeners();
3293
- this._removeListeners = this._server = null;
3294
- }
3295
- if (this.clients) if (!this.clients.size) process.nextTick(emitClose, this);
3296
- else this._shouldEmitClose = true;
3297
- else process.nextTick(emitClose, this);
3298
- } else {
3299
- const server = this._server;
3300
- this._removeListeners();
3301
- this._removeListeners = this._server = null;
3302
- server.close(() => {
3303
- emitClose(this);
3304
- });
3305
- }
3306
- }
3307
- /**
3308
- * See if a given request should be handled by this server instance.
3309
- *
3310
- * @param {http.IncomingMessage} req Request object to inspect
3311
- * @return {Boolean} `true` if the request is valid, else `false`
3312
- * @public
3313
- */
3314
- shouldHandle(req) {
3315
- if (this.options.path) {
3316
- const index = req.url.indexOf("?");
3317
- if ((index !== -1 ? req.url.slice(0, index) : req.url) !== this.options.path) return false;
3318
- }
3319
- return true;
3320
- }
3321
- /**
3322
- * Handle a HTTP Upgrade request.
3323
- *
3324
- * @param {http.IncomingMessage} req The request object
3325
- * @param {Duplex} socket The network socket between the server and client
3326
- * @param {Buffer} head The first packet of the upgraded stream
3327
- * @param {Function} cb Callback
3328
- * @public
3329
- */
3330
- handleUpgrade(req, socket, head, cb) {
3331
- socket.on("error", socketOnError);
3332
- const key = req.headers["sec-websocket-key"];
3333
- const upgrade = req.headers.upgrade;
3334
- const version = +req.headers["sec-websocket-version"];
3335
- if (req.method !== "GET") {
3336
- abortHandshakeOrEmitwsClientError(this, req, socket, 405, "Invalid HTTP method");
3337
- return;
3338
- }
3339
- if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
3340
- abortHandshakeOrEmitwsClientError(this, req, socket, 400, "Invalid Upgrade header");
3341
- return;
3342
- }
3343
- if (key === void 0 || !keyRegex.test(key)) {
3344
- abortHandshakeOrEmitwsClientError(this, req, socket, 400, "Missing or invalid Sec-WebSocket-Key header");
3345
- return;
3346
- }
3347
- if (version !== 13 && version !== 8) {
3348
- abortHandshakeOrEmitwsClientError(this, req, socket, 400, "Missing or invalid Sec-WebSocket-Version header", { "Sec-WebSocket-Version": "13, 8" });
3349
- return;
3350
- }
3351
- if (!this.shouldHandle(req)) {
3352
- abortHandshake(socket, 400);
3353
- return;
3354
- }
3355
- const secWebSocketProtocol = req.headers["sec-websocket-protocol"];
3356
- let protocols = /* @__PURE__ */ new Set();
3357
- if (secWebSocketProtocol !== void 0) try {
3358
- protocols = subprotocol.parse(secWebSocketProtocol);
3359
- } catch (err) {
3360
- abortHandshakeOrEmitwsClientError(this, req, socket, 400, "Invalid Sec-WebSocket-Protocol header");
3361
- return;
3362
- }
3363
- const secWebSocketExtensions = req.headers["sec-websocket-extensions"];
3364
- const extensions = {};
3365
- if (this.options.perMessageDeflate && secWebSocketExtensions !== void 0) {
3366
- const perMessageDeflate = new PerMessageDeflate({
3367
- ...this.options.perMessageDeflate,
3368
- isServer: true,
3369
- maxPayload: this.options.maxPayload
3370
- });
3371
- try {
3372
- const offers = extension.parse(secWebSocketExtensions);
3373
- if (offers[PerMessageDeflate.extensionName]) {
3374
- perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);
3375
- extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
3376
- }
3377
- } catch (err) {
3378
- abortHandshakeOrEmitwsClientError(this, req, socket, 400, "Invalid or unacceptable Sec-WebSocket-Extensions header");
3379
- return;
3380
- }
3381
- }
3382
- if (this.options.verifyClient) {
3383
- const info = {
3384
- origin: req.headers[`${version === 8 ? "sec-websocket-origin" : "origin"}`],
3385
- secure: !!(req.socket.authorized || req.socket.encrypted),
3386
- req
3387
- };
3388
- if (this.options.verifyClient.length === 2) {
3389
- this.options.verifyClient(info, (verified, code, message, headers) => {
3390
- if (!verified) return abortHandshake(socket, code || 401, message, headers);
3391
- this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
3392
- });
3393
- return;
3394
- }
3395
- if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);
3396
- }
3397
- this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
3398
- }
3399
- /**
3400
- * Upgrade the connection to WebSocket.
3401
- *
3402
- * @param {Object} extensions The accepted extensions
3403
- * @param {String} key The value of the `Sec-WebSocket-Key` header
3404
- * @param {Set} protocols The subprotocols
3405
- * @param {http.IncomingMessage} req The request object
3406
- * @param {Duplex} socket The network socket between the server and client
3407
- * @param {Buffer} head The first packet of the upgraded stream
3408
- * @param {Function} cb Callback
3409
- * @throws {Error} If called more than once with the same socket
3410
- * @private
3411
- */
3412
- completeUpgrade(extensions, key, protocols, req, socket, head, cb) {
3413
- if (!socket.readable || !socket.writable) return socket.destroy();
3414
- if (socket[kWebSocket]) throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");
3415
- if (this._state > RUNNING) return abortHandshake(socket, 503);
3416
- const headers = [
3417
- "HTTP/1.1 101 Switching Protocols",
3418
- "Upgrade: websocket",
3419
- "Connection: Upgrade",
3420
- `Sec-WebSocket-Accept: ${createHash("sha1").update(key + GUID).digest("base64")}`
3421
- ];
3422
- const ws = new this.options.WebSocket(null, void 0, this.options);
3423
- if (protocols.size) {
3424
- const protocol = this.options.handleProtocols ? this.options.handleProtocols(protocols, req) : protocols.values().next().value;
3425
- if (protocol) {
3426
- headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
3427
- ws._protocol = protocol;
3428
- }
3429
- }
3430
- if (extensions[PerMessageDeflate.extensionName]) {
3431
- const params = extensions[PerMessageDeflate.extensionName].params;
3432
- const value = extension.format({ [PerMessageDeflate.extensionName]: [params] });
3433
- headers.push(`Sec-WebSocket-Extensions: ${value}`);
3434
- ws._extensions = extensions;
3435
- }
3436
- this.emit("headers", headers, req);
3437
- socket.write(headers.concat("\r\n").join("\r\n"));
3438
- socket.removeListener("error", socketOnError);
3439
- ws.setSocket(socket, head, {
3440
- allowSynchronousEvents: this.options.allowSynchronousEvents,
3441
- maxPayload: this.options.maxPayload,
3442
- skipUTF8Validation: this.options.skipUTF8Validation
3443
- });
3444
- if (this.clients) {
3445
- this.clients.add(ws);
3446
- ws.on("close", () => {
3447
- this.clients.delete(ws);
3448
- if (this._shouldEmitClose && !this.clients.size) process.nextTick(emitClose, this);
3449
- });
3450
- }
3451
- cb(ws, req);
3452
- }
3453
- };
3454
- module.exports = WebSocketServer;
3455
- /**
3456
- * Add event listeners on an `EventEmitter` using a map of <event, listener>
3457
- * pairs.
3458
- *
3459
- * @param {EventEmitter} server The event emitter
3460
- * @param {Object.<String, Function>} map The listeners to add
3461
- * @return {Function} A function that will remove the added listeners when
3462
- * called
3463
- * @private
3464
- */
3465
- function addListeners(server, map) {
3466
- for (const event of Object.keys(map)) server.on(event, map[event]);
3467
- return function removeListeners() {
3468
- for (const event of Object.keys(map)) server.removeListener(event, map[event]);
3469
- };
3470
- }
3471
- /**
3472
- * Emit a `'close'` event on an `EventEmitter`.
3473
- *
3474
- * @param {EventEmitter} server The event emitter
3475
- * @private
3476
- */
3477
- function emitClose(server) {
3478
- server._state = CLOSED;
3479
- server.emit("close");
3480
- }
3481
- /**
3482
- * Handle socket errors.
3483
- *
3484
- * @private
3485
- */
3486
- function socketOnError() {
3487
- this.destroy();
3488
- }
3489
- /**
3490
- * Close the connection when preconditions are not fulfilled.
3491
- *
3492
- * @param {Duplex} socket The socket of the upgrade request
3493
- * @param {Number} code The HTTP response status code
3494
- * @param {String} [message] The HTTP response body
3495
- * @param {Object} [headers] Additional HTTP response headers
3496
- * @private
3497
- */
3498
- function abortHandshake(socket, code, message, headers) {
3499
- message = message || http.STATUS_CODES[code];
3500
- headers = {
3501
- Connection: "close",
3502
- "Content-Type": "text/html",
3503
- "Content-Length": Buffer.byteLength(message),
3504
- ...headers
3505
- };
3506
- socket.once("finish", socket.destroy);
3507
- socket.end(`HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r\n` + Object.keys(headers).map((h) => `${h}: ${headers[h]}`).join("\r\n") + "\r\n\r\n" + message);
3508
- }
3509
- /**
3510
- * Emit a `'wsClientError'` event on a `WebSocketServer` if there is at least
3511
- * one listener for it, otherwise call `abortHandshake()`.
3512
- *
3513
- * @param {WebSocketServer} server The WebSocket server
3514
- * @param {http.IncomingMessage} req The request object
3515
- * @param {Duplex} socket The socket of the upgrade request
3516
- * @param {Number} code The HTTP response status code
3517
- * @param {String} message The HTTP response body
3518
- * @param {Object} [headers] The HTTP response headers
3519
- * @private
3520
- */
3521
- function abortHandshakeOrEmitwsClientError(server, req, socket, code, message, headers) {
3522
- if (server.listenerCount("wsClientError")) {
3523
- const err = new Error(message);
3524
- Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);
3525
- server.emit("wsClientError", err, socket, req);
3526
- } else abortHandshake(socket, code, message, headers);
3527
- }
3528
- }));
3529
-
3530
- //#endregion
3531
- //#region node_modules/ws/wrapper.mjs
3532
- var import_stream = /* @__PURE__ */ __toESM(require_stream(), 1);
3533
- var import_extension = /* @__PURE__ */ __toESM(require_extension(), 1);
3534
- var import_permessage_deflate = /* @__PURE__ */ __toESM(require_permessage_deflate(), 1);
3535
- var import_receiver = /* @__PURE__ */ __toESM(require_receiver(), 1);
3536
- var import_sender = /* @__PURE__ */ __toESM(require_sender(), 1);
3537
- var import_subprotocol = /* @__PURE__ */ __toESM(require_subprotocol(), 1);
3538
- var import_websocket = /* @__PURE__ */ __toESM(require_websocket(), 1);
3539
- var import_websocket_server = /* @__PURE__ */ __toESM(require_websocket_server(), 1);
3540
- var wrapper_default = import_websocket.default;
3541
-
3542
- //#endregion
3543
- var PerMessageDeflate = import_permessage_deflate.default;
3544
- var Receiver = import_receiver.default;
3545
- var Sender = import_sender.default;
3546
- var WebSocket = import_websocket.default;
3547
- var WebSocketServer = import_websocket_server.default;
3548
- var createWebSocketStream = import_stream.default;
3549
- var extension = import_extension.default;
3550
- var subprotocol = import_subprotocol.default;
3551
- export { PerMessageDeflate, Receiver, Sender, WebSocket, WebSocketServer, createWebSocketStream, wrapper_default as default, extension, subprotocol };
3552
- //# sourceMappingURL=wrapper-CHq_CV4J.mjs.map