@mu-crew/mu 3.13.2 → 4.0.0

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