nexus-channel 1.7.7 → 1.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,13 +1,4845 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.nexusPlugin = void 0;
4
- const core_1 = require("openclaw/plugin-sdk/core");
5
- const channel_1 = require("./src/channel");
6
- var channel_2 = require("./src/channel");
7
- Object.defineProperty(exports, "nexusPlugin", { enumerable: true, get: function () { return channel_2.nexusPlugin; } });
8
- exports.default = (0, core_1.defineChannelPluginEntry)({
9
- id: 'nexus',
10
- name: 'Nexus',
11
- description: 'Nexus Hub 2.0 channel plugin for OpenClaw',
12
- plugin: channel_1.nexusPlugin,
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __commonJS = (cb, mod) => function __require() {
8
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
9
+ };
10
+ var __export = (target, all) => {
11
+ for (var name in all)
12
+ __defProp(target, name, { get: all[name], enumerable: true });
13
+ };
14
+ var __copyProps = (to, from, except, desc) => {
15
+ if (from && typeof from === "object" || typeof from === "function") {
16
+ for (let key of __getOwnPropNames(from))
17
+ if (!__hasOwnProp.call(to, key) && key !== except)
18
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
19
+ }
20
+ return to;
21
+ };
22
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
23
+ // If the importer is in node compatibility mode or this is not an ESM
24
+ // file that has been converted to a CommonJS file using a Babel-
25
+ // compatible transform (i.e. "__esModule" has not been set), then set
26
+ // "default" to the CommonJS "module.exports" for node compatibility.
27
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
28
+ mod
29
+ ));
30
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
31
+
32
+ // node_modules/ws/lib/constants.js
33
+ var require_constants = __commonJS({
34
+ "node_modules/ws/lib/constants.js"(exports2, module2) {
35
+ "use strict";
36
+ var BINARY_TYPES = ["nodebuffer", "arraybuffer", "fragments"];
37
+ var hasBlob = typeof Blob !== "undefined";
38
+ if (hasBlob) BINARY_TYPES.push("blob");
39
+ module2.exports = {
40
+ BINARY_TYPES,
41
+ CLOSE_TIMEOUT: 3e4,
42
+ EMPTY_BUFFER: Buffer.alloc(0),
43
+ GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
44
+ hasBlob,
45
+ kForOnEventAttribute: /* @__PURE__ */ Symbol("kIsForOnEventAttribute"),
46
+ kListener: /* @__PURE__ */ Symbol("kListener"),
47
+ kStatusCode: /* @__PURE__ */ Symbol("status-code"),
48
+ kWebSocket: /* @__PURE__ */ Symbol("websocket"),
49
+ NOOP: () => {
50
+ }
51
+ };
52
+ }
53
+ });
54
+
55
+ // node_modules/ws/lib/buffer-util.js
56
+ var require_buffer_util = __commonJS({
57
+ "node_modules/ws/lib/buffer-util.js"(exports2, module2) {
58
+ "use strict";
59
+ var { EMPTY_BUFFER } = require_constants();
60
+ var FastBuffer = Buffer[Symbol.species];
61
+ function concat(list, totalLength) {
62
+ if (list.length === 0) return EMPTY_BUFFER;
63
+ if (list.length === 1) return list[0];
64
+ const target = Buffer.allocUnsafe(totalLength);
65
+ let offset = 0;
66
+ for (let i = 0; i < list.length; i++) {
67
+ const buf = list[i];
68
+ target.set(buf, offset);
69
+ offset += buf.length;
70
+ }
71
+ if (offset < totalLength) {
72
+ return new FastBuffer(target.buffer, target.byteOffset, offset);
73
+ }
74
+ return target;
75
+ }
76
+ function _mask(source, mask, output, offset, length) {
77
+ for (let i = 0; i < length; i++) {
78
+ output[offset + i] = source[i] ^ mask[i & 3];
79
+ }
80
+ }
81
+ function _unmask(buffer, mask) {
82
+ for (let i = 0; i < buffer.length; i++) {
83
+ buffer[i] ^= mask[i & 3];
84
+ }
85
+ }
86
+ function toArrayBuffer(buf) {
87
+ if (buf.length === buf.buffer.byteLength) {
88
+ return buf.buffer;
89
+ }
90
+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);
91
+ }
92
+ function toBuffer(data) {
93
+ toBuffer.readOnly = true;
94
+ if (Buffer.isBuffer(data)) return data;
95
+ let buf;
96
+ if (data instanceof ArrayBuffer) {
97
+ buf = new FastBuffer(data);
98
+ } else if (ArrayBuffer.isView(data)) {
99
+ buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);
100
+ } else {
101
+ buf = Buffer.from(data);
102
+ toBuffer.readOnly = false;
103
+ }
104
+ return buf;
105
+ }
106
+ module2.exports = {
107
+ concat,
108
+ mask: _mask,
109
+ toArrayBuffer,
110
+ toBuffer,
111
+ unmask: _unmask
112
+ };
113
+ if (true) {
114
+ try {
115
+ const bufferUtil = require("bufferutil");
116
+ module2.exports.mask = function(source, mask, output, offset, length) {
117
+ if (length < 48) _mask(source, mask, output, offset, length);
118
+ else bufferUtil.mask(source, mask, output, offset, length);
119
+ };
120
+ module2.exports.unmask = function(buffer, mask) {
121
+ if (buffer.length < 32) _unmask(buffer, mask);
122
+ else bufferUtil.unmask(buffer, mask);
123
+ };
124
+ } catch (e) {
125
+ }
126
+ }
127
+ }
128
+ });
129
+
130
+ // node_modules/ws/lib/limiter.js
131
+ var require_limiter = __commonJS({
132
+ "node_modules/ws/lib/limiter.js"(exports2, module2) {
133
+ "use strict";
134
+ var kDone = /* @__PURE__ */ Symbol("kDone");
135
+ var kRun = /* @__PURE__ */ Symbol("kRun");
136
+ var Limiter = class {
137
+ /**
138
+ * Creates a new `Limiter`.
139
+ *
140
+ * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed
141
+ * to run concurrently
142
+ */
143
+ constructor(concurrency) {
144
+ this[kDone] = () => {
145
+ this.pending--;
146
+ this[kRun]();
147
+ };
148
+ this.concurrency = concurrency || Infinity;
149
+ this.jobs = [];
150
+ this.pending = 0;
151
+ }
152
+ /**
153
+ * Adds a job to the queue.
154
+ *
155
+ * @param {Function} job The job to run
156
+ * @public
157
+ */
158
+ add(job) {
159
+ this.jobs.push(job);
160
+ this[kRun]();
161
+ }
162
+ /**
163
+ * Removes a job from the queue and runs it if possible.
164
+ *
165
+ * @private
166
+ */
167
+ [kRun]() {
168
+ if (this.pending === this.concurrency) return;
169
+ if (this.jobs.length) {
170
+ const job = this.jobs.shift();
171
+ this.pending++;
172
+ job(this[kDone]);
173
+ }
174
+ }
175
+ };
176
+ module2.exports = Limiter;
177
+ }
178
+ });
179
+
180
+ // node_modules/ws/lib/permessage-deflate.js
181
+ var require_permessage_deflate = __commonJS({
182
+ "node_modules/ws/lib/permessage-deflate.js"(exports2, module2) {
183
+ "use strict";
184
+ var zlib = require("zlib");
185
+ var bufferUtil = require_buffer_util();
186
+ var Limiter = require_limiter();
187
+ var { kStatusCode } = require_constants();
188
+ var FastBuffer = Buffer[Symbol.species];
189
+ var TRAILER = Buffer.from([0, 0, 255, 255]);
190
+ var kPerMessageDeflate = /* @__PURE__ */ Symbol("permessage-deflate");
191
+ var kTotalLength = /* @__PURE__ */ Symbol("total-length");
192
+ var kCallback = /* @__PURE__ */ Symbol("callback");
193
+ var kBuffers = /* @__PURE__ */ Symbol("buffers");
194
+ var kError = /* @__PURE__ */ Symbol("error");
195
+ var zlibLimiter;
196
+ var PerMessageDeflate2 = class {
197
+ /**
198
+ * Creates a PerMessageDeflate instance.
199
+ *
200
+ * @param {Object} [options] Configuration options
201
+ * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support
202
+ * for, or request, a custom client window size
203
+ * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/
204
+ * acknowledge disabling of client context takeover
205
+ * @param {Number} [options.concurrencyLimit=10] The number of concurrent
206
+ * calls to zlib
207
+ * @param {Boolean} [options.isServer=false] Create the instance in either
208
+ * server or client mode
209
+ * @param {Number} [options.maxPayload=0] The maximum allowed message length
210
+ * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the
211
+ * use of a custom server window size
212
+ * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept
213
+ * disabling of server context takeover
214
+ * @param {Number} [options.threshold=1024] Size (in bytes) below which
215
+ * messages should not be compressed if context takeover is disabled
216
+ * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on
217
+ * deflate
218
+ * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on
219
+ * inflate
220
+ */
221
+ constructor(options) {
222
+ this._options = options || {};
223
+ this._threshold = this._options.threshold !== void 0 ? this._options.threshold : 1024;
224
+ this._maxPayload = this._options.maxPayload | 0;
225
+ this._isServer = !!this._options.isServer;
226
+ this._deflate = null;
227
+ this._inflate = null;
228
+ this.params = null;
229
+ if (!zlibLimiter) {
230
+ const concurrency = this._options.concurrencyLimit !== void 0 ? this._options.concurrencyLimit : 10;
231
+ zlibLimiter = new Limiter(concurrency);
232
+ }
233
+ }
234
+ /**
235
+ * @type {String}
236
+ */
237
+ static get extensionName() {
238
+ return "permessage-deflate";
239
+ }
240
+ /**
241
+ * Create an extension negotiation offer.
242
+ *
243
+ * @return {Object} Extension parameters
244
+ * @public
245
+ */
246
+ offer() {
247
+ const params = {};
248
+ if (this._options.serverNoContextTakeover) {
249
+ params.server_no_context_takeover = true;
250
+ }
251
+ if (this._options.clientNoContextTakeover) {
252
+ params.client_no_context_takeover = true;
253
+ }
254
+ if (this._options.serverMaxWindowBits) {
255
+ params.server_max_window_bits = this._options.serverMaxWindowBits;
256
+ }
257
+ if (this._options.clientMaxWindowBits) {
258
+ params.client_max_window_bits = this._options.clientMaxWindowBits;
259
+ } else if (this._options.clientMaxWindowBits == null) {
260
+ params.client_max_window_bits = true;
261
+ }
262
+ return params;
263
+ }
264
+ /**
265
+ * Accept an extension negotiation offer/response.
266
+ *
267
+ * @param {Array} configurations The extension negotiation offers/reponse
268
+ * @return {Object} Accepted configuration
269
+ * @public
270
+ */
271
+ accept(configurations) {
272
+ configurations = this.normalizeParams(configurations);
273
+ this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations);
274
+ return this.params;
275
+ }
276
+ /**
277
+ * Releases all resources used by the extension.
278
+ *
279
+ * @public
280
+ */
281
+ cleanup() {
282
+ if (this._inflate) {
283
+ this._inflate.close();
284
+ this._inflate = null;
285
+ }
286
+ if (this._deflate) {
287
+ const callback = this._deflate[kCallback];
288
+ this._deflate.close();
289
+ this._deflate = null;
290
+ if (callback) {
291
+ callback(
292
+ new Error(
293
+ "The deflate stream was closed while data was being processed"
294
+ )
295
+ );
296
+ }
297
+ }
298
+ }
299
+ /**
300
+ * Accept an extension negotiation offer.
301
+ *
302
+ * @param {Array} offers The extension negotiation offers
303
+ * @return {Object} Accepted configuration
304
+ * @private
305
+ */
306
+ acceptAsServer(offers) {
307
+ const opts = this._options;
308
+ const accepted = offers.find((params) => {
309
+ if (opts.serverNoContextTakeover === false && params.server_no_context_takeover || params.server_max_window_bits && (opts.serverMaxWindowBits === false || typeof opts.serverMaxWindowBits === "number" && opts.serverMaxWindowBits > params.server_max_window_bits) || typeof opts.clientMaxWindowBits === "number" && !params.client_max_window_bits) {
310
+ return false;
311
+ }
312
+ return true;
313
+ });
314
+ if (!accepted) {
315
+ throw new Error("None of the extension offers can be accepted");
316
+ }
317
+ if (opts.serverNoContextTakeover) {
318
+ accepted.server_no_context_takeover = true;
319
+ }
320
+ if (opts.clientNoContextTakeover) {
321
+ accepted.client_no_context_takeover = true;
322
+ }
323
+ if (typeof opts.serverMaxWindowBits === "number") {
324
+ accepted.server_max_window_bits = opts.serverMaxWindowBits;
325
+ }
326
+ if (typeof opts.clientMaxWindowBits === "number") {
327
+ accepted.client_max_window_bits = opts.clientMaxWindowBits;
328
+ } else if (accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false) {
329
+ delete accepted.client_max_window_bits;
330
+ }
331
+ return accepted;
332
+ }
333
+ /**
334
+ * Accept the extension negotiation response.
335
+ *
336
+ * @param {Array} response The extension negotiation response
337
+ * @return {Object} Accepted configuration
338
+ * @private
339
+ */
340
+ acceptAsClient(response) {
341
+ const params = response[0];
342
+ if (this._options.clientNoContextTakeover === false && params.client_no_context_takeover) {
343
+ throw new Error('Unexpected parameter "client_no_context_takeover"');
344
+ }
345
+ if (!params.client_max_window_bits) {
346
+ if (typeof this._options.clientMaxWindowBits === "number") {
347
+ params.client_max_window_bits = this._options.clientMaxWindowBits;
348
+ }
349
+ } else if (this._options.clientMaxWindowBits === false || typeof this._options.clientMaxWindowBits === "number" && params.client_max_window_bits > this._options.clientMaxWindowBits) {
350
+ throw new Error(
351
+ 'Unexpected or invalid parameter "client_max_window_bits"'
352
+ );
353
+ }
354
+ return params;
355
+ }
356
+ /**
357
+ * Normalize parameters.
358
+ *
359
+ * @param {Array} configurations The extension negotiation offers/reponse
360
+ * @return {Array} The offers/response with normalized parameters
361
+ * @private
362
+ */
363
+ normalizeParams(configurations) {
364
+ configurations.forEach((params) => {
365
+ Object.keys(params).forEach((key) => {
366
+ let value = params[key];
367
+ if (value.length > 1) {
368
+ throw new Error(`Parameter "${key}" must have only a single value`);
369
+ }
370
+ value = value[0];
371
+ if (key === "client_max_window_bits") {
372
+ if (value !== true) {
373
+ const num = +value;
374
+ if (!Number.isInteger(num) || num < 8 || num > 15) {
375
+ throw new TypeError(
376
+ `Invalid value for parameter "${key}": ${value}`
377
+ );
378
+ }
379
+ value = num;
380
+ } else if (!this._isServer) {
381
+ throw new TypeError(
382
+ `Invalid value for parameter "${key}": ${value}`
383
+ );
384
+ }
385
+ } else if (key === "server_max_window_bits") {
386
+ const num = +value;
387
+ if (!Number.isInteger(num) || num < 8 || num > 15) {
388
+ throw new TypeError(
389
+ `Invalid value for parameter "${key}": ${value}`
390
+ );
391
+ }
392
+ value = num;
393
+ } else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") {
394
+ if (value !== true) {
395
+ throw new TypeError(
396
+ `Invalid value for parameter "${key}": ${value}`
397
+ );
398
+ }
399
+ } else {
400
+ throw new Error(`Unknown parameter "${key}"`);
401
+ }
402
+ params[key] = value;
403
+ });
404
+ });
405
+ return configurations;
406
+ }
407
+ /**
408
+ * Decompress data. Concurrency limited.
409
+ *
410
+ * @param {Buffer} data Compressed data
411
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
412
+ * @param {Function} callback Callback
413
+ * @public
414
+ */
415
+ decompress(data, fin, callback) {
416
+ zlibLimiter.add((done) => {
417
+ this._decompress(data, fin, (err, result) => {
418
+ done();
419
+ callback(err, result);
420
+ });
421
+ });
422
+ }
423
+ /**
424
+ * Compress data. Concurrency limited.
425
+ *
426
+ * @param {(Buffer|String)} data Data to compress
427
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
428
+ * @param {Function} callback Callback
429
+ * @public
430
+ */
431
+ compress(data, fin, callback) {
432
+ zlibLimiter.add((done) => {
433
+ this._compress(data, fin, (err, result) => {
434
+ done();
435
+ callback(err, result);
436
+ });
437
+ });
438
+ }
439
+ /**
440
+ * Decompress data.
441
+ *
442
+ * @param {Buffer} data Compressed data
443
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
444
+ * @param {Function} callback Callback
445
+ * @private
446
+ */
447
+ _decompress(data, fin, callback) {
448
+ const endpoint = this._isServer ? "client" : "server";
449
+ if (!this._inflate) {
450
+ const key = `${endpoint}_max_window_bits`;
451
+ const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
452
+ this._inflate = zlib.createInflateRaw({
453
+ ...this._options.zlibInflateOptions,
454
+ windowBits
455
+ });
456
+ this._inflate[kPerMessageDeflate] = this;
457
+ this._inflate[kTotalLength] = 0;
458
+ this._inflate[kBuffers] = [];
459
+ this._inflate.on("error", inflateOnError);
460
+ this._inflate.on("data", inflateOnData);
461
+ }
462
+ this._inflate[kCallback] = callback;
463
+ this._inflate.write(data);
464
+ if (fin) this._inflate.write(TRAILER);
465
+ this._inflate.flush(() => {
466
+ const err = this._inflate[kError];
467
+ if (err) {
468
+ this._inflate.close();
469
+ this._inflate = null;
470
+ callback(err);
471
+ return;
472
+ }
473
+ const data2 = bufferUtil.concat(
474
+ this._inflate[kBuffers],
475
+ this._inflate[kTotalLength]
476
+ );
477
+ if (this._inflate._readableState.endEmitted) {
478
+ this._inflate.close();
479
+ this._inflate = null;
480
+ } else {
481
+ this._inflate[kTotalLength] = 0;
482
+ this._inflate[kBuffers] = [];
483
+ if (fin && this.params[`${endpoint}_no_context_takeover`]) {
484
+ this._inflate.reset();
485
+ }
486
+ }
487
+ callback(null, data2);
488
+ });
489
+ }
490
+ /**
491
+ * Compress data.
492
+ *
493
+ * @param {(Buffer|String)} data Data to compress
494
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
495
+ * @param {Function} callback Callback
496
+ * @private
497
+ */
498
+ _compress(data, fin, callback) {
499
+ const endpoint = this._isServer ? "server" : "client";
500
+ if (!this._deflate) {
501
+ const key = `${endpoint}_max_window_bits`;
502
+ const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
503
+ this._deflate = zlib.createDeflateRaw({
504
+ ...this._options.zlibDeflateOptions,
505
+ windowBits
506
+ });
507
+ this._deflate[kTotalLength] = 0;
508
+ this._deflate[kBuffers] = [];
509
+ this._deflate.on("data", deflateOnData);
510
+ }
511
+ this._deflate[kCallback] = callback;
512
+ this._deflate.write(data);
513
+ this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {
514
+ if (!this._deflate) {
515
+ return;
516
+ }
517
+ let data2 = bufferUtil.concat(
518
+ this._deflate[kBuffers],
519
+ this._deflate[kTotalLength]
520
+ );
521
+ if (fin) {
522
+ data2 = new FastBuffer(data2.buffer, data2.byteOffset, data2.length - 4);
523
+ }
524
+ this._deflate[kCallback] = null;
525
+ this._deflate[kTotalLength] = 0;
526
+ this._deflate[kBuffers] = [];
527
+ if (fin && this.params[`${endpoint}_no_context_takeover`]) {
528
+ this._deflate.reset();
529
+ }
530
+ callback(null, data2);
531
+ });
532
+ }
533
+ };
534
+ module2.exports = PerMessageDeflate2;
535
+ function deflateOnData(chunk) {
536
+ this[kBuffers].push(chunk);
537
+ this[kTotalLength] += chunk.length;
538
+ }
539
+ function inflateOnData(chunk) {
540
+ this[kTotalLength] += chunk.length;
541
+ if (this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) {
542
+ this[kBuffers].push(chunk);
543
+ return;
544
+ }
545
+ this[kError] = new RangeError("Max payload size exceeded");
546
+ this[kError].code = "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH";
547
+ this[kError][kStatusCode] = 1009;
548
+ this.removeListener("data", inflateOnData);
549
+ this.reset();
550
+ }
551
+ function inflateOnError(err) {
552
+ this[kPerMessageDeflate]._inflate = null;
553
+ if (this[kError]) {
554
+ this[kCallback](this[kError]);
555
+ return;
556
+ }
557
+ err[kStatusCode] = 1007;
558
+ this[kCallback](err);
559
+ }
560
+ }
561
+ });
562
+
563
+ // node_modules/ws/lib/validation.js
564
+ var require_validation = __commonJS({
565
+ "node_modules/ws/lib/validation.js"(exports2, module2) {
566
+ "use strict";
567
+ var { isUtf8 } = require("buffer");
568
+ var { hasBlob } = require_constants();
569
+ var tokenChars = [
570
+ 0,
571
+ 0,
572
+ 0,
573
+ 0,
574
+ 0,
575
+ 0,
576
+ 0,
577
+ 0,
578
+ 0,
579
+ 0,
580
+ 0,
581
+ 0,
582
+ 0,
583
+ 0,
584
+ 0,
585
+ 0,
586
+ // 0 - 15
587
+ 0,
588
+ 0,
589
+ 0,
590
+ 0,
591
+ 0,
592
+ 0,
593
+ 0,
594
+ 0,
595
+ 0,
596
+ 0,
597
+ 0,
598
+ 0,
599
+ 0,
600
+ 0,
601
+ 0,
602
+ 0,
603
+ // 16 - 31
604
+ 0,
605
+ 1,
606
+ 0,
607
+ 1,
608
+ 1,
609
+ 1,
610
+ 1,
611
+ 1,
612
+ 0,
613
+ 0,
614
+ 1,
615
+ 1,
616
+ 0,
617
+ 1,
618
+ 1,
619
+ 0,
620
+ // 32 - 47
621
+ 1,
622
+ 1,
623
+ 1,
624
+ 1,
625
+ 1,
626
+ 1,
627
+ 1,
628
+ 1,
629
+ 1,
630
+ 1,
631
+ 0,
632
+ 0,
633
+ 0,
634
+ 0,
635
+ 0,
636
+ 0,
637
+ // 48 - 63
638
+ 0,
639
+ 1,
640
+ 1,
641
+ 1,
642
+ 1,
643
+ 1,
644
+ 1,
645
+ 1,
646
+ 1,
647
+ 1,
648
+ 1,
649
+ 1,
650
+ 1,
651
+ 1,
652
+ 1,
653
+ 1,
654
+ // 64 - 79
655
+ 1,
656
+ 1,
657
+ 1,
658
+ 1,
659
+ 1,
660
+ 1,
661
+ 1,
662
+ 1,
663
+ 1,
664
+ 1,
665
+ 1,
666
+ 0,
667
+ 0,
668
+ 0,
669
+ 1,
670
+ 1,
671
+ // 80 - 95
672
+ 1,
673
+ 1,
674
+ 1,
675
+ 1,
676
+ 1,
677
+ 1,
678
+ 1,
679
+ 1,
680
+ 1,
681
+ 1,
682
+ 1,
683
+ 1,
684
+ 1,
685
+ 1,
686
+ 1,
687
+ 1,
688
+ // 96 - 111
689
+ 1,
690
+ 1,
691
+ 1,
692
+ 1,
693
+ 1,
694
+ 1,
695
+ 1,
696
+ 1,
697
+ 1,
698
+ 1,
699
+ 1,
700
+ 0,
701
+ 1,
702
+ 0,
703
+ 1,
704
+ 0
705
+ // 112 - 127
706
+ ];
707
+ function isValidStatusCode(code) {
708
+ return code >= 1e3 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006 || code >= 3e3 && code <= 4999;
709
+ }
710
+ function _isValidUTF8(buf) {
711
+ const len = buf.length;
712
+ let i = 0;
713
+ while (i < len) {
714
+ if ((buf[i] & 128) === 0) {
715
+ i++;
716
+ } else if ((buf[i] & 224) === 192) {
717
+ if (i + 1 === len || (buf[i + 1] & 192) !== 128 || (buf[i] & 254) === 192) {
718
+ return false;
719
+ }
720
+ i += 2;
721
+ } else if ((buf[i] & 240) === 224) {
722
+ if (i + 2 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || buf[i] === 224 && (buf[i + 1] & 224) === 128 || // Overlong
723
+ buf[i] === 237 && (buf[i + 1] & 224) === 160) {
724
+ return false;
725
+ }
726
+ i += 3;
727
+ } else if ((buf[i] & 248) === 240) {
728
+ 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
729
+ buf[i] === 244 && buf[i + 1] > 143 || buf[i] > 244) {
730
+ return false;
731
+ }
732
+ i += 4;
733
+ } else {
734
+ return false;
735
+ }
736
+ }
737
+ return true;
738
+ }
739
+ function isBlob(value) {
740
+ 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");
741
+ }
742
+ module2.exports = {
743
+ isBlob,
744
+ isValidStatusCode,
745
+ isValidUTF8: _isValidUTF8,
746
+ tokenChars
747
+ };
748
+ if (isUtf8) {
749
+ module2.exports.isValidUTF8 = function(buf) {
750
+ return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);
751
+ };
752
+ } else if (true) {
753
+ try {
754
+ const isValidUTF8 = require("utf-8-validate");
755
+ module2.exports.isValidUTF8 = function(buf) {
756
+ return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);
757
+ };
758
+ } catch (e) {
759
+ }
760
+ }
761
+ }
762
+ });
763
+
764
+ // node_modules/ws/lib/receiver.js
765
+ var require_receiver = __commonJS({
766
+ "node_modules/ws/lib/receiver.js"(exports2, module2) {
767
+ "use strict";
768
+ var { Writable } = require("stream");
769
+ var PerMessageDeflate2 = require_permessage_deflate();
770
+ var {
771
+ BINARY_TYPES,
772
+ EMPTY_BUFFER,
773
+ kStatusCode,
774
+ kWebSocket
775
+ } = require_constants();
776
+ var { concat, toArrayBuffer, unmask } = require_buffer_util();
777
+ var { isValidStatusCode, isValidUTF8 } = require_validation();
778
+ var FastBuffer = Buffer[Symbol.species];
779
+ var GET_INFO = 0;
780
+ var GET_PAYLOAD_LENGTH_16 = 1;
781
+ var GET_PAYLOAD_LENGTH_64 = 2;
782
+ var GET_MASK = 3;
783
+ var GET_DATA = 4;
784
+ var INFLATING = 5;
785
+ var DEFER_EVENT = 6;
786
+ var Receiver2 = class extends Writable {
787
+ /**
788
+ * Creates a Receiver instance.
789
+ *
790
+ * @param {Object} [options] Options object
791
+ * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
792
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
793
+ * multiple times in the same tick
794
+ * @param {String} [options.binaryType=nodebuffer] The type for binary data
795
+ * @param {Object} [options.extensions] An object containing the negotiated
796
+ * extensions
797
+ * @param {Boolean} [options.isServer=false] Specifies whether to operate in
798
+ * client or server mode
799
+ * @param {Number} [options.maxPayload=0] The maximum allowed message length
800
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
801
+ * not to skip UTF-8 validation for text and close messages
802
+ */
803
+ constructor(options = {}) {
804
+ super();
805
+ this._allowSynchronousEvents = options.allowSynchronousEvents !== void 0 ? options.allowSynchronousEvents : true;
806
+ this._binaryType = options.binaryType || BINARY_TYPES[0];
807
+ this._extensions = options.extensions || {};
808
+ this._isServer = !!options.isServer;
809
+ this._maxPayload = options.maxPayload | 0;
810
+ this._skipUTF8Validation = !!options.skipUTF8Validation;
811
+ this[kWebSocket] = void 0;
812
+ this._bufferedBytes = 0;
813
+ this._buffers = [];
814
+ this._compressed = false;
815
+ this._payloadLength = 0;
816
+ this._mask = void 0;
817
+ this._fragmented = 0;
818
+ this._masked = false;
819
+ this._fin = false;
820
+ this._opcode = 0;
821
+ this._totalPayloadLength = 0;
822
+ this._messageLength = 0;
823
+ this._fragments = [];
824
+ this._errored = false;
825
+ this._loop = false;
826
+ this._state = GET_INFO;
827
+ }
828
+ /**
829
+ * Implements `Writable.prototype._write()`.
830
+ *
831
+ * @param {Buffer} chunk The chunk of data to write
832
+ * @param {String} encoding The character encoding of `chunk`
833
+ * @param {Function} cb Callback
834
+ * @private
835
+ */
836
+ _write(chunk, encoding, cb) {
837
+ if (this._opcode === 8 && this._state == GET_INFO) return cb();
838
+ this._bufferedBytes += chunk.length;
839
+ this._buffers.push(chunk);
840
+ this.startLoop(cb);
841
+ }
842
+ /**
843
+ * Consumes `n` bytes from the buffered data.
844
+ *
845
+ * @param {Number} n The number of bytes to consume
846
+ * @return {Buffer} The consumed bytes
847
+ * @private
848
+ */
849
+ consume(n) {
850
+ this._bufferedBytes -= n;
851
+ if (n === this._buffers[0].length) return this._buffers.shift();
852
+ if (n < this._buffers[0].length) {
853
+ const buf = this._buffers[0];
854
+ this._buffers[0] = new FastBuffer(
855
+ buf.buffer,
856
+ buf.byteOffset + n,
857
+ buf.length - n
858
+ );
859
+ return new FastBuffer(buf.buffer, buf.byteOffset, n);
860
+ }
861
+ const dst = Buffer.allocUnsafe(n);
862
+ do {
863
+ const buf = this._buffers[0];
864
+ const offset = dst.length - n;
865
+ if (n >= buf.length) {
866
+ dst.set(this._buffers.shift(), offset);
867
+ } else {
868
+ dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);
869
+ this._buffers[0] = new FastBuffer(
870
+ buf.buffer,
871
+ buf.byteOffset + n,
872
+ buf.length - n
873
+ );
874
+ }
875
+ n -= buf.length;
876
+ } while (n > 0);
877
+ return dst;
878
+ }
879
+ /**
880
+ * Starts the parsing loop.
881
+ *
882
+ * @param {Function} cb Callback
883
+ * @private
884
+ */
885
+ startLoop(cb) {
886
+ this._loop = true;
887
+ do {
888
+ switch (this._state) {
889
+ case GET_INFO:
890
+ this.getInfo(cb);
891
+ break;
892
+ case GET_PAYLOAD_LENGTH_16:
893
+ this.getPayloadLength16(cb);
894
+ break;
895
+ case GET_PAYLOAD_LENGTH_64:
896
+ this.getPayloadLength64(cb);
897
+ break;
898
+ case GET_MASK:
899
+ this.getMask();
900
+ break;
901
+ case GET_DATA:
902
+ this.getData(cb);
903
+ break;
904
+ case INFLATING:
905
+ case DEFER_EVENT:
906
+ this._loop = false;
907
+ return;
908
+ }
909
+ } while (this._loop);
910
+ if (!this._errored) cb();
911
+ }
912
+ /**
913
+ * Reads the first two bytes of a frame.
914
+ *
915
+ * @param {Function} cb Callback
916
+ * @private
917
+ */
918
+ getInfo(cb) {
919
+ if (this._bufferedBytes < 2) {
920
+ this._loop = false;
921
+ return;
922
+ }
923
+ const buf = this.consume(2);
924
+ if ((buf[0] & 48) !== 0) {
925
+ const error = this.createError(
926
+ RangeError,
927
+ "RSV2 and RSV3 must be clear",
928
+ true,
929
+ 1002,
930
+ "WS_ERR_UNEXPECTED_RSV_2_3"
931
+ );
932
+ cb(error);
933
+ return;
934
+ }
935
+ const compressed = (buf[0] & 64) === 64;
936
+ if (compressed && !this._extensions[PerMessageDeflate2.extensionName]) {
937
+ const error = this.createError(
938
+ RangeError,
939
+ "RSV1 must be clear",
940
+ true,
941
+ 1002,
942
+ "WS_ERR_UNEXPECTED_RSV_1"
943
+ );
944
+ cb(error);
945
+ return;
946
+ }
947
+ this._fin = (buf[0] & 128) === 128;
948
+ this._opcode = buf[0] & 15;
949
+ this._payloadLength = buf[1] & 127;
950
+ if (this._opcode === 0) {
951
+ if (compressed) {
952
+ const error = this.createError(
953
+ RangeError,
954
+ "RSV1 must be clear",
955
+ true,
956
+ 1002,
957
+ "WS_ERR_UNEXPECTED_RSV_1"
958
+ );
959
+ cb(error);
960
+ return;
961
+ }
962
+ if (!this._fragmented) {
963
+ const error = this.createError(
964
+ RangeError,
965
+ "invalid opcode 0",
966
+ true,
967
+ 1002,
968
+ "WS_ERR_INVALID_OPCODE"
969
+ );
970
+ cb(error);
971
+ return;
972
+ }
973
+ this._opcode = this._fragmented;
974
+ } else if (this._opcode === 1 || this._opcode === 2) {
975
+ if (this._fragmented) {
976
+ const error = this.createError(
977
+ RangeError,
978
+ `invalid opcode ${this._opcode}`,
979
+ true,
980
+ 1002,
981
+ "WS_ERR_INVALID_OPCODE"
982
+ );
983
+ cb(error);
984
+ return;
985
+ }
986
+ this._compressed = compressed;
987
+ } else if (this._opcode > 7 && this._opcode < 11) {
988
+ if (!this._fin) {
989
+ const error = this.createError(
990
+ RangeError,
991
+ "FIN must be set",
992
+ true,
993
+ 1002,
994
+ "WS_ERR_EXPECTED_FIN"
995
+ );
996
+ cb(error);
997
+ return;
998
+ }
999
+ if (compressed) {
1000
+ const error = this.createError(
1001
+ RangeError,
1002
+ "RSV1 must be clear",
1003
+ true,
1004
+ 1002,
1005
+ "WS_ERR_UNEXPECTED_RSV_1"
1006
+ );
1007
+ cb(error);
1008
+ return;
1009
+ }
1010
+ if (this._payloadLength > 125 || this._opcode === 8 && this._payloadLength === 1) {
1011
+ const error = this.createError(
1012
+ RangeError,
1013
+ `invalid payload length ${this._payloadLength}`,
1014
+ true,
1015
+ 1002,
1016
+ "WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"
1017
+ );
1018
+ cb(error);
1019
+ return;
1020
+ }
1021
+ } else {
1022
+ const error = this.createError(
1023
+ RangeError,
1024
+ `invalid opcode ${this._opcode}`,
1025
+ true,
1026
+ 1002,
1027
+ "WS_ERR_INVALID_OPCODE"
1028
+ );
1029
+ cb(error);
1030
+ return;
1031
+ }
1032
+ if (!this._fin && !this._fragmented) this._fragmented = this._opcode;
1033
+ this._masked = (buf[1] & 128) === 128;
1034
+ if (this._isServer) {
1035
+ if (!this._masked) {
1036
+ const error = this.createError(
1037
+ RangeError,
1038
+ "MASK must be set",
1039
+ true,
1040
+ 1002,
1041
+ "WS_ERR_EXPECTED_MASK"
1042
+ );
1043
+ cb(error);
1044
+ return;
1045
+ }
1046
+ } else if (this._masked) {
1047
+ const error = this.createError(
1048
+ RangeError,
1049
+ "MASK must be clear",
1050
+ true,
1051
+ 1002,
1052
+ "WS_ERR_UNEXPECTED_MASK"
1053
+ );
1054
+ cb(error);
1055
+ return;
1056
+ }
1057
+ if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;
1058
+ else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;
1059
+ else this.haveLength(cb);
1060
+ }
1061
+ /**
1062
+ * Gets extended payload length (7+16).
1063
+ *
1064
+ * @param {Function} cb Callback
1065
+ * @private
1066
+ */
1067
+ getPayloadLength16(cb) {
1068
+ if (this._bufferedBytes < 2) {
1069
+ this._loop = false;
1070
+ return;
1071
+ }
1072
+ this._payloadLength = this.consume(2).readUInt16BE(0);
1073
+ this.haveLength(cb);
1074
+ }
1075
+ /**
1076
+ * Gets extended payload length (7+64).
1077
+ *
1078
+ * @param {Function} cb Callback
1079
+ * @private
1080
+ */
1081
+ getPayloadLength64(cb) {
1082
+ if (this._bufferedBytes < 8) {
1083
+ this._loop = false;
1084
+ return;
1085
+ }
1086
+ const buf = this.consume(8);
1087
+ const num = buf.readUInt32BE(0);
1088
+ if (num > Math.pow(2, 53 - 32) - 1) {
1089
+ const error = this.createError(
1090
+ RangeError,
1091
+ "Unsupported WebSocket frame: payload length > 2^53 - 1",
1092
+ false,
1093
+ 1009,
1094
+ "WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH"
1095
+ );
1096
+ cb(error);
1097
+ return;
1098
+ }
1099
+ this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
1100
+ this.haveLength(cb);
1101
+ }
1102
+ /**
1103
+ * Payload length has been read.
1104
+ *
1105
+ * @param {Function} cb Callback
1106
+ * @private
1107
+ */
1108
+ haveLength(cb) {
1109
+ if (this._payloadLength && this._opcode < 8) {
1110
+ this._totalPayloadLength += this._payloadLength;
1111
+ if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
1112
+ const error = this.createError(
1113
+ RangeError,
1114
+ "Max payload size exceeded",
1115
+ false,
1116
+ 1009,
1117
+ "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
1118
+ );
1119
+ cb(error);
1120
+ return;
1121
+ }
1122
+ }
1123
+ if (this._masked) this._state = GET_MASK;
1124
+ else this._state = GET_DATA;
1125
+ }
1126
+ /**
1127
+ * Reads mask bytes.
1128
+ *
1129
+ * @private
1130
+ */
1131
+ getMask() {
1132
+ if (this._bufferedBytes < 4) {
1133
+ this._loop = false;
1134
+ return;
1135
+ }
1136
+ this._mask = this.consume(4);
1137
+ this._state = GET_DATA;
1138
+ }
1139
+ /**
1140
+ * Reads data bytes.
1141
+ *
1142
+ * @param {Function} cb Callback
1143
+ * @private
1144
+ */
1145
+ getData(cb) {
1146
+ let data = EMPTY_BUFFER;
1147
+ if (this._payloadLength) {
1148
+ if (this._bufferedBytes < this._payloadLength) {
1149
+ this._loop = false;
1150
+ return;
1151
+ }
1152
+ data = this.consume(this._payloadLength);
1153
+ if (this._masked && (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0) {
1154
+ unmask(data, this._mask);
1155
+ }
1156
+ }
1157
+ if (this._opcode > 7) {
1158
+ this.controlMessage(data, cb);
1159
+ return;
1160
+ }
1161
+ if (this._compressed) {
1162
+ this._state = INFLATING;
1163
+ this.decompress(data, cb);
1164
+ return;
1165
+ }
1166
+ if (data.length) {
1167
+ this._messageLength = this._totalPayloadLength;
1168
+ this._fragments.push(data);
1169
+ }
1170
+ this.dataMessage(cb);
1171
+ }
1172
+ /**
1173
+ * Decompresses data.
1174
+ *
1175
+ * @param {Buffer} data Compressed data
1176
+ * @param {Function} cb Callback
1177
+ * @private
1178
+ */
1179
+ decompress(data, cb) {
1180
+ const perMessageDeflate = this._extensions[PerMessageDeflate2.extensionName];
1181
+ perMessageDeflate.decompress(data, this._fin, (err, buf) => {
1182
+ if (err) return cb(err);
1183
+ if (buf.length) {
1184
+ this._messageLength += buf.length;
1185
+ if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
1186
+ const error = this.createError(
1187
+ RangeError,
1188
+ "Max payload size exceeded",
1189
+ false,
1190
+ 1009,
1191
+ "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
1192
+ );
1193
+ cb(error);
1194
+ return;
1195
+ }
1196
+ this._fragments.push(buf);
1197
+ }
1198
+ this.dataMessage(cb);
1199
+ if (this._state === GET_INFO) this.startLoop(cb);
1200
+ });
1201
+ }
1202
+ /**
1203
+ * Handles a data message.
1204
+ *
1205
+ * @param {Function} cb Callback
1206
+ * @private
1207
+ */
1208
+ dataMessage(cb) {
1209
+ if (!this._fin) {
1210
+ this._state = GET_INFO;
1211
+ return;
1212
+ }
1213
+ const messageLength = this._messageLength;
1214
+ const fragments = this._fragments;
1215
+ this._totalPayloadLength = 0;
1216
+ this._messageLength = 0;
1217
+ this._fragmented = 0;
1218
+ this._fragments = [];
1219
+ if (this._opcode === 2) {
1220
+ let data;
1221
+ if (this._binaryType === "nodebuffer") {
1222
+ data = concat(fragments, messageLength);
1223
+ } else if (this._binaryType === "arraybuffer") {
1224
+ data = toArrayBuffer(concat(fragments, messageLength));
1225
+ } else if (this._binaryType === "blob") {
1226
+ data = new Blob(fragments);
1227
+ } else {
1228
+ data = fragments;
1229
+ }
1230
+ if (this._allowSynchronousEvents) {
1231
+ this.emit("message", data, true);
1232
+ this._state = GET_INFO;
1233
+ } else {
1234
+ this._state = DEFER_EVENT;
1235
+ setImmediate(() => {
1236
+ this.emit("message", data, true);
1237
+ this._state = GET_INFO;
1238
+ this.startLoop(cb);
1239
+ });
1240
+ }
1241
+ } else {
1242
+ const buf = concat(fragments, messageLength);
1243
+ if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
1244
+ const error = this.createError(
1245
+ Error,
1246
+ "invalid UTF-8 sequence",
1247
+ true,
1248
+ 1007,
1249
+ "WS_ERR_INVALID_UTF8"
1250
+ );
1251
+ cb(error);
1252
+ return;
1253
+ }
1254
+ if (this._state === INFLATING || this._allowSynchronousEvents) {
1255
+ this.emit("message", buf, false);
1256
+ this._state = GET_INFO;
1257
+ } else {
1258
+ this._state = DEFER_EVENT;
1259
+ setImmediate(() => {
1260
+ this.emit("message", buf, false);
1261
+ this._state = GET_INFO;
1262
+ this.startLoop(cb);
1263
+ });
1264
+ }
1265
+ }
1266
+ }
1267
+ /**
1268
+ * Handles a control message.
1269
+ *
1270
+ * @param {Buffer} data Data to handle
1271
+ * @return {(Error|RangeError|undefined)} A possible error
1272
+ * @private
1273
+ */
1274
+ controlMessage(data, cb) {
1275
+ if (this._opcode === 8) {
1276
+ if (data.length === 0) {
1277
+ this._loop = false;
1278
+ this.emit("conclude", 1005, EMPTY_BUFFER);
1279
+ this.end();
1280
+ } else {
1281
+ const code = data.readUInt16BE(0);
1282
+ if (!isValidStatusCode(code)) {
1283
+ const error = this.createError(
1284
+ RangeError,
1285
+ `invalid status code ${code}`,
1286
+ true,
1287
+ 1002,
1288
+ "WS_ERR_INVALID_CLOSE_CODE"
1289
+ );
1290
+ cb(error);
1291
+ return;
1292
+ }
1293
+ const buf = new FastBuffer(
1294
+ data.buffer,
1295
+ data.byteOffset + 2,
1296
+ data.length - 2
1297
+ );
1298
+ if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
1299
+ const error = this.createError(
1300
+ Error,
1301
+ "invalid UTF-8 sequence",
1302
+ true,
1303
+ 1007,
1304
+ "WS_ERR_INVALID_UTF8"
1305
+ );
1306
+ cb(error);
1307
+ return;
1308
+ }
1309
+ this._loop = false;
1310
+ this.emit("conclude", code, buf);
1311
+ this.end();
1312
+ }
1313
+ this._state = GET_INFO;
1314
+ return;
1315
+ }
1316
+ if (this._allowSynchronousEvents) {
1317
+ this.emit(this._opcode === 9 ? "ping" : "pong", data);
1318
+ this._state = GET_INFO;
1319
+ } else {
1320
+ this._state = DEFER_EVENT;
1321
+ setImmediate(() => {
1322
+ this.emit(this._opcode === 9 ? "ping" : "pong", data);
1323
+ this._state = GET_INFO;
1324
+ this.startLoop(cb);
1325
+ });
1326
+ }
1327
+ }
1328
+ /**
1329
+ * Builds an error object.
1330
+ *
1331
+ * @param {function(new:Error|RangeError)} ErrorCtor The error constructor
1332
+ * @param {String} message The error message
1333
+ * @param {Boolean} prefix Specifies whether or not to add a default prefix to
1334
+ * `message`
1335
+ * @param {Number} statusCode The status code
1336
+ * @param {String} errorCode The exposed error code
1337
+ * @return {(Error|RangeError)} The error
1338
+ * @private
1339
+ */
1340
+ createError(ErrorCtor, message, prefix, statusCode, errorCode) {
1341
+ this._loop = false;
1342
+ this._errored = true;
1343
+ const err = new ErrorCtor(
1344
+ prefix ? `Invalid WebSocket frame: ${message}` : message
1345
+ );
1346
+ Error.captureStackTrace(err, this.createError);
1347
+ err.code = errorCode;
1348
+ err[kStatusCode] = statusCode;
1349
+ return err;
1350
+ }
1351
+ };
1352
+ module2.exports = Receiver2;
1353
+ }
1354
+ });
1355
+
1356
+ // node_modules/ws/lib/sender.js
1357
+ var require_sender = __commonJS({
1358
+ "node_modules/ws/lib/sender.js"(exports2, module2) {
1359
+ "use strict";
1360
+ var { Duplex } = require("stream");
1361
+ var { randomFillSync } = require("crypto");
1362
+ var PerMessageDeflate2 = require_permessage_deflate();
1363
+ var { EMPTY_BUFFER, kWebSocket, NOOP } = require_constants();
1364
+ var { isBlob, isValidStatusCode } = require_validation();
1365
+ var { mask: applyMask, toBuffer } = require_buffer_util();
1366
+ var kByteLength = /* @__PURE__ */ Symbol("kByteLength");
1367
+ var maskBuffer = Buffer.alloc(4);
1368
+ var RANDOM_POOL_SIZE = 8 * 1024;
1369
+ var randomPool;
1370
+ var randomPoolPointer = RANDOM_POOL_SIZE;
1371
+ var DEFAULT = 0;
1372
+ var DEFLATING = 1;
1373
+ var GET_BLOB_DATA = 2;
1374
+ var Sender2 = class _Sender {
1375
+ /**
1376
+ * Creates a Sender instance.
1377
+ *
1378
+ * @param {Duplex} socket The connection socket
1379
+ * @param {Object} [extensions] An object containing the negotiated extensions
1380
+ * @param {Function} [generateMask] The function used to generate the masking
1381
+ * key
1382
+ */
1383
+ constructor(socket, extensions, generateMask) {
1384
+ this._extensions = extensions || {};
1385
+ if (generateMask) {
1386
+ this._generateMask = generateMask;
1387
+ this._maskBuffer = Buffer.alloc(4);
1388
+ }
1389
+ this._socket = socket;
1390
+ this._firstFragment = true;
1391
+ this._compress = false;
1392
+ this._bufferedBytes = 0;
1393
+ this._queue = [];
1394
+ this._state = DEFAULT;
1395
+ this.onerror = NOOP;
1396
+ this[kWebSocket] = void 0;
1397
+ }
1398
+ /**
1399
+ * Frames a piece of data according to the HyBi WebSocket protocol.
1400
+ *
1401
+ * @param {(Buffer|String)} data The data to frame
1402
+ * @param {Object} options Options object
1403
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
1404
+ * FIN bit
1405
+ * @param {Function} [options.generateMask] The function used to generate the
1406
+ * masking key
1407
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1408
+ * `data`
1409
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
1410
+ * key
1411
+ * @param {Number} options.opcode The opcode
1412
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
1413
+ * modified
1414
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
1415
+ * RSV1 bit
1416
+ * @return {(Buffer|String)[]} The framed data
1417
+ * @public
1418
+ */
1419
+ static frame(data, options) {
1420
+ let mask;
1421
+ let merge = false;
1422
+ let offset = 2;
1423
+ let skipMasking = false;
1424
+ if (options.mask) {
1425
+ mask = options.maskBuffer || maskBuffer;
1426
+ if (options.generateMask) {
1427
+ options.generateMask(mask);
1428
+ } else {
1429
+ if (randomPoolPointer === RANDOM_POOL_SIZE) {
1430
+ if (randomPool === void 0) {
1431
+ randomPool = Buffer.alloc(RANDOM_POOL_SIZE);
1432
+ }
1433
+ randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);
1434
+ randomPoolPointer = 0;
1435
+ }
1436
+ mask[0] = randomPool[randomPoolPointer++];
1437
+ mask[1] = randomPool[randomPoolPointer++];
1438
+ mask[2] = randomPool[randomPoolPointer++];
1439
+ mask[3] = randomPool[randomPoolPointer++];
1440
+ }
1441
+ skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;
1442
+ offset = 6;
1443
+ }
1444
+ let dataLength;
1445
+ if (typeof data === "string") {
1446
+ if ((!options.mask || skipMasking) && options[kByteLength] !== void 0) {
1447
+ dataLength = options[kByteLength];
1448
+ } else {
1449
+ data = Buffer.from(data);
1450
+ dataLength = data.length;
1451
+ }
1452
+ } else {
1453
+ dataLength = data.length;
1454
+ merge = options.mask && options.readOnly && !skipMasking;
1455
+ }
1456
+ let payloadLength = dataLength;
1457
+ if (dataLength >= 65536) {
1458
+ offset += 8;
1459
+ payloadLength = 127;
1460
+ } else if (dataLength > 125) {
1461
+ offset += 2;
1462
+ payloadLength = 126;
1463
+ }
1464
+ const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);
1465
+ target[0] = options.fin ? options.opcode | 128 : options.opcode;
1466
+ if (options.rsv1) target[0] |= 64;
1467
+ target[1] = payloadLength;
1468
+ if (payloadLength === 126) {
1469
+ target.writeUInt16BE(dataLength, 2);
1470
+ } else if (payloadLength === 127) {
1471
+ target[2] = target[3] = 0;
1472
+ target.writeUIntBE(dataLength, 4, 6);
1473
+ }
1474
+ if (!options.mask) return [target, data];
1475
+ target[1] |= 128;
1476
+ target[offset - 4] = mask[0];
1477
+ target[offset - 3] = mask[1];
1478
+ target[offset - 2] = mask[2];
1479
+ target[offset - 1] = mask[3];
1480
+ if (skipMasking) return [target, data];
1481
+ if (merge) {
1482
+ applyMask(data, mask, target, offset, dataLength);
1483
+ return [target];
1484
+ }
1485
+ applyMask(data, mask, data, 0, dataLength);
1486
+ return [target, data];
1487
+ }
1488
+ /**
1489
+ * Sends a close message to the other peer.
1490
+ *
1491
+ * @param {Number} [code] The status code component of the body
1492
+ * @param {(String|Buffer)} [data] The message component of the body
1493
+ * @param {Boolean} [mask=false] Specifies whether or not to mask the message
1494
+ * @param {Function} [cb] Callback
1495
+ * @public
1496
+ */
1497
+ close(code, data, mask, cb) {
1498
+ let buf;
1499
+ if (code === void 0) {
1500
+ buf = EMPTY_BUFFER;
1501
+ } else if (typeof code !== "number" || !isValidStatusCode(code)) {
1502
+ throw new TypeError("First argument must be a valid error code number");
1503
+ } else if (data === void 0 || !data.length) {
1504
+ buf = Buffer.allocUnsafe(2);
1505
+ buf.writeUInt16BE(code, 0);
1506
+ } else {
1507
+ const length = Buffer.byteLength(data);
1508
+ if (length > 123) {
1509
+ throw new RangeError("The message must not be greater than 123 bytes");
1510
+ }
1511
+ buf = Buffer.allocUnsafe(2 + length);
1512
+ buf.writeUInt16BE(code, 0);
1513
+ if (typeof data === "string") {
1514
+ buf.write(data, 2);
1515
+ } else {
1516
+ buf.set(data, 2);
1517
+ }
1518
+ }
1519
+ const options = {
1520
+ [kByteLength]: buf.length,
1521
+ fin: true,
1522
+ generateMask: this._generateMask,
1523
+ mask,
1524
+ maskBuffer: this._maskBuffer,
1525
+ opcode: 8,
1526
+ readOnly: false,
1527
+ rsv1: false
1528
+ };
1529
+ if (this._state !== DEFAULT) {
1530
+ this.enqueue([this.dispatch, buf, false, options, cb]);
1531
+ } else {
1532
+ this.sendFrame(_Sender.frame(buf, options), cb);
1533
+ }
1534
+ }
1535
+ /**
1536
+ * Sends a ping message to the other peer.
1537
+ *
1538
+ * @param {*} data The message to send
1539
+ * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
1540
+ * @param {Function} [cb] Callback
1541
+ * @public
1542
+ */
1543
+ ping(data, mask, cb) {
1544
+ let byteLength;
1545
+ let readOnly;
1546
+ if (typeof data === "string") {
1547
+ byteLength = Buffer.byteLength(data);
1548
+ readOnly = false;
1549
+ } else if (isBlob(data)) {
1550
+ byteLength = data.size;
1551
+ readOnly = false;
1552
+ } else {
1553
+ data = toBuffer(data);
1554
+ byteLength = data.length;
1555
+ readOnly = toBuffer.readOnly;
1556
+ }
1557
+ if (byteLength > 125) {
1558
+ throw new RangeError("The data size must not be greater than 125 bytes");
1559
+ }
1560
+ const options = {
1561
+ [kByteLength]: byteLength,
1562
+ fin: true,
1563
+ generateMask: this._generateMask,
1564
+ mask,
1565
+ maskBuffer: this._maskBuffer,
1566
+ opcode: 9,
1567
+ readOnly,
1568
+ rsv1: false
1569
+ };
1570
+ if (isBlob(data)) {
1571
+ if (this._state !== DEFAULT) {
1572
+ this.enqueue([this.getBlobData, data, false, options, cb]);
1573
+ } else {
1574
+ this.getBlobData(data, false, options, cb);
1575
+ }
1576
+ } else if (this._state !== DEFAULT) {
1577
+ this.enqueue([this.dispatch, data, false, options, cb]);
1578
+ } else {
1579
+ this.sendFrame(_Sender.frame(data, options), cb);
1580
+ }
1581
+ }
1582
+ /**
1583
+ * Sends a pong message to the other peer.
1584
+ *
1585
+ * @param {*} data The message to send
1586
+ * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
1587
+ * @param {Function} [cb] Callback
1588
+ * @public
1589
+ */
1590
+ pong(data, mask, cb) {
1591
+ let byteLength;
1592
+ let readOnly;
1593
+ if (typeof data === "string") {
1594
+ byteLength = Buffer.byteLength(data);
1595
+ readOnly = false;
1596
+ } else if (isBlob(data)) {
1597
+ byteLength = data.size;
1598
+ readOnly = false;
1599
+ } else {
1600
+ data = toBuffer(data);
1601
+ byteLength = data.length;
1602
+ readOnly = toBuffer.readOnly;
1603
+ }
1604
+ if (byteLength > 125) {
1605
+ throw new RangeError("The data size must not be greater than 125 bytes");
1606
+ }
1607
+ const options = {
1608
+ [kByteLength]: byteLength,
1609
+ fin: true,
1610
+ generateMask: this._generateMask,
1611
+ mask,
1612
+ maskBuffer: this._maskBuffer,
1613
+ opcode: 10,
1614
+ readOnly,
1615
+ rsv1: false
1616
+ };
1617
+ if (isBlob(data)) {
1618
+ if (this._state !== DEFAULT) {
1619
+ this.enqueue([this.getBlobData, data, false, options, cb]);
1620
+ } else {
1621
+ this.getBlobData(data, false, options, cb);
1622
+ }
1623
+ } else if (this._state !== DEFAULT) {
1624
+ this.enqueue([this.dispatch, data, false, options, cb]);
1625
+ } else {
1626
+ this.sendFrame(_Sender.frame(data, options), cb);
1627
+ }
1628
+ }
1629
+ /**
1630
+ * Sends a data message to the other peer.
1631
+ *
1632
+ * @param {*} data The message to send
1633
+ * @param {Object} options Options object
1634
+ * @param {Boolean} [options.binary=false] Specifies whether `data` is binary
1635
+ * or text
1636
+ * @param {Boolean} [options.compress=false] Specifies whether or not to
1637
+ * compress `data`
1638
+ * @param {Boolean} [options.fin=false] Specifies whether the fragment is the
1639
+ * last one
1640
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1641
+ * `data`
1642
+ * @param {Function} [cb] Callback
1643
+ * @public
1644
+ */
1645
+ send(data, options, cb) {
1646
+ const perMessageDeflate = this._extensions[PerMessageDeflate2.extensionName];
1647
+ let opcode = options.binary ? 2 : 1;
1648
+ let rsv1 = options.compress;
1649
+ let byteLength;
1650
+ let readOnly;
1651
+ if (typeof data === "string") {
1652
+ byteLength = Buffer.byteLength(data);
1653
+ readOnly = false;
1654
+ } else if (isBlob(data)) {
1655
+ byteLength = data.size;
1656
+ readOnly = false;
1657
+ } else {
1658
+ data = toBuffer(data);
1659
+ byteLength = data.length;
1660
+ readOnly = toBuffer.readOnly;
1661
+ }
1662
+ if (this._firstFragment) {
1663
+ this._firstFragment = false;
1664
+ if (rsv1 && perMessageDeflate && perMessageDeflate.params[perMessageDeflate._isServer ? "server_no_context_takeover" : "client_no_context_takeover"]) {
1665
+ rsv1 = byteLength >= perMessageDeflate._threshold;
1666
+ }
1667
+ this._compress = rsv1;
1668
+ } else {
1669
+ rsv1 = false;
1670
+ opcode = 0;
1671
+ }
1672
+ if (options.fin) this._firstFragment = true;
1673
+ const opts = {
1674
+ [kByteLength]: byteLength,
1675
+ fin: options.fin,
1676
+ generateMask: this._generateMask,
1677
+ mask: options.mask,
1678
+ maskBuffer: this._maskBuffer,
1679
+ opcode,
1680
+ readOnly,
1681
+ rsv1
1682
+ };
1683
+ if (isBlob(data)) {
1684
+ if (this._state !== DEFAULT) {
1685
+ this.enqueue([this.getBlobData, data, this._compress, opts, cb]);
1686
+ } else {
1687
+ this.getBlobData(data, this._compress, opts, cb);
1688
+ }
1689
+ } else if (this._state !== DEFAULT) {
1690
+ this.enqueue([this.dispatch, data, this._compress, opts, cb]);
1691
+ } else {
1692
+ this.dispatch(data, this._compress, opts, cb);
1693
+ }
1694
+ }
1695
+ /**
1696
+ * Gets the contents of a blob as binary data.
1697
+ *
1698
+ * @param {Blob} blob The blob
1699
+ * @param {Boolean} [compress=false] Specifies whether or not to compress
1700
+ * the data
1701
+ * @param {Object} options Options object
1702
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
1703
+ * FIN bit
1704
+ * @param {Function} [options.generateMask] The function used to generate the
1705
+ * masking key
1706
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1707
+ * `data`
1708
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
1709
+ * key
1710
+ * @param {Number} options.opcode The opcode
1711
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
1712
+ * modified
1713
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
1714
+ * RSV1 bit
1715
+ * @param {Function} [cb] Callback
1716
+ * @private
1717
+ */
1718
+ getBlobData(blob, compress, options, cb) {
1719
+ this._bufferedBytes += options[kByteLength];
1720
+ this._state = GET_BLOB_DATA;
1721
+ blob.arrayBuffer().then((arrayBuffer) => {
1722
+ if (this._socket.destroyed) {
1723
+ const err = new Error(
1724
+ "The socket was closed while the blob was being read"
1725
+ );
1726
+ process.nextTick(callCallbacks, this, err, cb);
1727
+ return;
1728
+ }
1729
+ this._bufferedBytes -= options[kByteLength];
1730
+ const data = toBuffer(arrayBuffer);
1731
+ if (!compress) {
1732
+ this._state = DEFAULT;
1733
+ this.sendFrame(_Sender.frame(data, options), cb);
1734
+ this.dequeue();
1735
+ } else {
1736
+ this.dispatch(data, compress, options, cb);
1737
+ }
1738
+ }).catch((err) => {
1739
+ process.nextTick(onError, this, err, cb);
1740
+ });
1741
+ }
1742
+ /**
1743
+ * Dispatches a message.
1744
+ *
1745
+ * @param {(Buffer|String)} data The message to send
1746
+ * @param {Boolean} [compress=false] Specifies whether or not to compress
1747
+ * `data`
1748
+ * @param {Object} options Options object
1749
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
1750
+ * FIN bit
1751
+ * @param {Function} [options.generateMask] The function used to generate the
1752
+ * masking key
1753
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1754
+ * `data`
1755
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
1756
+ * key
1757
+ * @param {Number} options.opcode The opcode
1758
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
1759
+ * modified
1760
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
1761
+ * RSV1 bit
1762
+ * @param {Function} [cb] Callback
1763
+ * @private
1764
+ */
1765
+ dispatch(data, compress, options, cb) {
1766
+ if (!compress) {
1767
+ this.sendFrame(_Sender.frame(data, options), cb);
1768
+ return;
1769
+ }
1770
+ const perMessageDeflate = this._extensions[PerMessageDeflate2.extensionName];
1771
+ this._bufferedBytes += options[kByteLength];
1772
+ this._state = DEFLATING;
1773
+ perMessageDeflate.compress(data, options.fin, (_, buf) => {
1774
+ if (this._socket.destroyed) {
1775
+ const err = new Error(
1776
+ "The socket was closed while data was being compressed"
1777
+ );
1778
+ callCallbacks(this, err, cb);
1779
+ return;
1780
+ }
1781
+ this._bufferedBytes -= options[kByteLength];
1782
+ this._state = DEFAULT;
1783
+ options.readOnly = false;
1784
+ this.sendFrame(_Sender.frame(buf, options), cb);
1785
+ this.dequeue();
1786
+ });
1787
+ }
1788
+ /**
1789
+ * Executes queued send operations.
1790
+ *
1791
+ * @private
1792
+ */
1793
+ dequeue() {
1794
+ while (this._state === DEFAULT && this._queue.length) {
1795
+ const params = this._queue.shift();
1796
+ this._bufferedBytes -= params[3][kByteLength];
1797
+ Reflect.apply(params[0], this, params.slice(1));
1798
+ }
1799
+ }
1800
+ /**
1801
+ * Enqueues a send operation.
1802
+ *
1803
+ * @param {Array} params Send operation parameters.
1804
+ * @private
1805
+ */
1806
+ enqueue(params) {
1807
+ this._bufferedBytes += params[3][kByteLength];
1808
+ this._queue.push(params);
1809
+ }
1810
+ /**
1811
+ * Sends a frame.
1812
+ *
1813
+ * @param {(Buffer | String)[]} list The frame to send
1814
+ * @param {Function} [cb] Callback
1815
+ * @private
1816
+ */
1817
+ sendFrame(list, cb) {
1818
+ if (list.length === 2) {
1819
+ this._socket.cork();
1820
+ this._socket.write(list[0]);
1821
+ this._socket.write(list[1], cb);
1822
+ this._socket.uncork();
1823
+ } else {
1824
+ this._socket.write(list[0], cb);
1825
+ }
1826
+ }
1827
+ };
1828
+ module2.exports = Sender2;
1829
+ function callCallbacks(sender, err, cb) {
1830
+ if (typeof cb === "function") cb(err);
1831
+ for (let i = 0; i < sender._queue.length; i++) {
1832
+ const params = sender._queue[i];
1833
+ const callback = params[params.length - 1];
1834
+ if (typeof callback === "function") callback(err);
1835
+ }
1836
+ }
1837
+ function onError(sender, err, cb) {
1838
+ callCallbacks(sender, err, cb);
1839
+ sender.onerror(err);
1840
+ }
1841
+ }
1842
+ });
1843
+
1844
+ // node_modules/ws/lib/event-target.js
1845
+ var require_event_target = __commonJS({
1846
+ "node_modules/ws/lib/event-target.js"(exports2, module2) {
1847
+ "use strict";
1848
+ var { kForOnEventAttribute, kListener } = require_constants();
1849
+ var kCode = /* @__PURE__ */ Symbol("kCode");
1850
+ var kData = /* @__PURE__ */ Symbol("kData");
1851
+ var kError = /* @__PURE__ */ Symbol("kError");
1852
+ var kMessage = /* @__PURE__ */ Symbol("kMessage");
1853
+ var kReason = /* @__PURE__ */ Symbol("kReason");
1854
+ var kTarget = /* @__PURE__ */ Symbol("kTarget");
1855
+ var kType = /* @__PURE__ */ Symbol("kType");
1856
+ var kWasClean = /* @__PURE__ */ Symbol("kWasClean");
1857
+ var Event = class {
1858
+ /**
1859
+ * Create a new `Event`.
1860
+ *
1861
+ * @param {String} type The name of the event
1862
+ * @throws {TypeError} If the `type` argument is not specified
1863
+ */
1864
+ constructor(type) {
1865
+ this[kTarget] = null;
1866
+ this[kType] = type;
1867
+ }
1868
+ /**
1869
+ * @type {*}
1870
+ */
1871
+ get target() {
1872
+ return this[kTarget];
1873
+ }
1874
+ /**
1875
+ * @type {String}
1876
+ */
1877
+ get type() {
1878
+ return this[kType];
1879
+ }
1880
+ };
1881
+ Object.defineProperty(Event.prototype, "target", { enumerable: true });
1882
+ Object.defineProperty(Event.prototype, "type", { enumerable: true });
1883
+ var CloseEvent = class extends Event {
1884
+ /**
1885
+ * Create a new `CloseEvent`.
1886
+ *
1887
+ * @param {String} type The name of the event
1888
+ * @param {Object} [options] A dictionary object that allows for setting
1889
+ * attributes via object members of the same name
1890
+ * @param {Number} [options.code=0] The status code explaining why the
1891
+ * connection was closed
1892
+ * @param {String} [options.reason=''] A human-readable string explaining why
1893
+ * the connection was closed
1894
+ * @param {Boolean} [options.wasClean=false] Indicates whether or not the
1895
+ * connection was cleanly closed
1896
+ */
1897
+ constructor(type, options = {}) {
1898
+ super(type);
1899
+ this[kCode] = options.code === void 0 ? 0 : options.code;
1900
+ this[kReason] = options.reason === void 0 ? "" : options.reason;
1901
+ this[kWasClean] = options.wasClean === void 0 ? false : options.wasClean;
1902
+ }
1903
+ /**
1904
+ * @type {Number}
1905
+ */
1906
+ get code() {
1907
+ return this[kCode];
1908
+ }
1909
+ /**
1910
+ * @type {String}
1911
+ */
1912
+ get reason() {
1913
+ return this[kReason];
1914
+ }
1915
+ /**
1916
+ * @type {Boolean}
1917
+ */
1918
+ get wasClean() {
1919
+ return this[kWasClean];
1920
+ }
1921
+ };
1922
+ Object.defineProperty(CloseEvent.prototype, "code", { enumerable: true });
1923
+ Object.defineProperty(CloseEvent.prototype, "reason", { enumerable: true });
1924
+ Object.defineProperty(CloseEvent.prototype, "wasClean", { enumerable: true });
1925
+ var ErrorEvent = class extends Event {
1926
+ /**
1927
+ * Create a new `ErrorEvent`.
1928
+ *
1929
+ * @param {String} type The name of the event
1930
+ * @param {Object} [options] A dictionary object that allows for setting
1931
+ * attributes via object members of the same name
1932
+ * @param {*} [options.error=null] The error that generated this event
1933
+ * @param {String} [options.message=''] The error message
1934
+ */
1935
+ constructor(type, options = {}) {
1936
+ super(type);
1937
+ this[kError] = options.error === void 0 ? null : options.error;
1938
+ this[kMessage] = options.message === void 0 ? "" : options.message;
1939
+ }
1940
+ /**
1941
+ * @type {*}
1942
+ */
1943
+ get error() {
1944
+ return this[kError];
1945
+ }
1946
+ /**
1947
+ * @type {String}
1948
+ */
1949
+ get message() {
1950
+ return this[kMessage];
1951
+ }
1952
+ };
1953
+ Object.defineProperty(ErrorEvent.prototype, "error", { enumerable: true });
1954
+ Object.defineProperty(ErrorEvent.prototype, "message", { enumerable: true });
1955
+ var MessageEvent = class extends Event {
1956
+ /**
1957
+ * Create a new `MessageEvent`.
1958
+ *
1959
+ * @param {String} type The name of the event
1960
+ * @param {Object} [options] A dictionary object that allows for setting
1961
+ * attributes via object members of the same name
1962
+ * @param {*} [options.data=null] The message content
1963
+ */
1964
+ constructor(type, options = {}) {
1965
+ super(type);
1966
+ this[kData] = options.data === void 0 ? null : options.data;
1967
+ }
1968
+ /**
1969
+ * @type {*}
1970
+ */
1971
+ get data() {
1972
+ return this[kData];
1973
+ }
1974
+ };
1975
+ Object.defineProperty(MessageEvent.prototype, "data", { enumerable: true });
1976
+ var EventTarget = {
1977
+ /**
1978
+ * Register an event listener.
1979
+ *
1980
+ * @param {String} type A string representing the event type to listen for
1981
+ * @param {(Function|Object)} handler The listener to add
1982
+ * @param {Object} [options] An options object specifies characteristics about
1983
+ * the event listener
1984
+ * @param {Boolean} [options.once=false] A `Boolean` indicating that the
1985
+ * listener should be invoked at most once after being added. If `true`,
1986
+ * the listener would be automatically removed when invoked.
1987
+ * @public
1988
+ */
1989
+ addEventListener(type, handler, options = {}) {
1990
+ for (const listener of this.listeners(type)) {
1991
+ if (!options[kForOnEventAttribute] && listener[kListener] === handler && !listener[kForOnEventAttribute]) {
1992
+ return;
1993
+ }
1994
+ }
1995
+ let wrapper;
1996
+ if (type === "message") {
1997
+ wrapper = function onMessage(data, isBinary) {
1998
+ const event = new MessageEvent("message", {
1999
+ data: isBinary ? data : data.toString()
2000
+ });
2001
+ event[kTarget] = this;
2002
+ callListener(handler, this, event);
2003
+ };
2004
+ } else if (type === "close") {
2005
+ wrapper = function onClose(code, message) {
2006
+ const event = new CloseEvent("close", {
2007
+ code,
2008
+ reason: message.toString(),
2009
+ wasClean: this._closeFrameReceived && this._closeFrameSent
2010
+ });
2011
+ event[kTarget] = this;
2012
+ callListener(handler, this, event);
2013
+ };
2014
+ } else if (type === "error") {
2015
+ wrapper = function onError(error) {
2016
+ const event = new ErrorEvent("error", {
2017
+ error,
2018
+ message: error.message
2019
+ });
2020
+ event[kTarget] = this;
2021
+ callListener(handler, this, event);
2022
+ };
2023
+ } else if (type === "open") {
2024
+ wrapper = function onOpen() {
2025
+ const event = new Event("open");
2026
+ event[kTarget] = this;
2027
+ callListener(handler, this, event);
2028
+ };
2029
+ } else {
2030
+ return;
2031
+ }
2032
+ wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];
2033
+ wrapper[kListener] = handler;
2034
+ if (options.once) {
2035
+ this.once(type, wrapper);
2036
+ } else {
2037
+ this.on(type, wrapper);
2038
+ }
2039
+ },
2040
+ /**
2041
+ * Remove an event listener.
2042
+ *
2043
+ * @param {String} type A string representing the event type to remove
2044
+ * @param {(Function|Object)} handler The listener to remove
2045
+ * @public
2046
+ */
2047
+ removeEventListener(type, handler) {
2048
+ for (const listener of this.listeners(type)) {
2049
+ if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {
2050
+ this.removeListener(type, listener);
2051
+ break;
2052
+ }
2053
+ }
2054
+ }
2055
+ };
2056
+ module2.exports = {
2057
+ CloseEvent,
2058
+ ErrorEvent,
2059
+ Event,
2060
+ EventTarget,
2061
+ MessageEvent
2062
+ };
2063
+ function callListener(listener, thisArg, event) {
2064
+ if (typeof listener === "object" && listener.handleEvent) {
2065
+ listener.handleEvent.call(listener, event);
2066
+ } else {
2067
+ listener.call(thisArg, event);
2068
+ }
2069
+ }
2070
+ }
2071
+ });
2072
+
2073
+ // node_modules/ws/lib/extension.js
2074
+ var require_extension = __commonJS({
2075
+ "node_modules/ws/lib/extension.js"(exports2, module2) {
2076
+ "use strict";
2077
+ var { tokenChars } = require_validation();
2078
+ function push(dest, name, elem) {
2079
+ if (dest[name] === void 0) dest[name] = [elem];
2080
+ else dest[name].push(elem);
2081
+ }
2082
+ function parse(header) {
2083
+ const offers = /* @__PURE__ */ Object.create(null);
2084
+ let params = /* @__PURE__ */ Object.create(null);
2085
+ let mustUnescape = false;
2086
+ let isEscaping = false;
2087
+ let inQuotes = false;
2088
+ let extensionName;
2089
+ let paramName;
2090
+ let start = -1;
2091
+ let code = -1;
2092
+ let end = -1;
2093
+ let i = 0;
2094
+ for (; i < header.length; i++) {
2095
+ code = header.charCodeAt(i);
2096
+ if (extensionName === void 0) {
2097
+ if (end === -1 && tokenChars[code] === 1) {
2098
+ if (start === -1) start = i;
2099
+ } else if (i !== 0 && (code === 32 || code === 9)) {
2100
+ if (end === -1 && start !== -1) end = i;
2101
+ } else if (code === 59 || code === 44) {
2102
+ if (start === -1) {
2103
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2104
+ }
2105
+ if (end === -1) end = i;
2106
+ const name = header.slice(start, end);
2107
+ if (code === 44) {
2108
+ push(offers, name, params);
2109
+ params = /* @__PURE__ */ Object.create(null);
2110
+ } else {
2111
+ extensionName = name;
2112
+ }
2113
+ start = end = -1;
2114
+ } else {
2115
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2116
+ }
2117
+ } else if (paramName === void 0) {
2118
+ if (end === -1 && tokenChars[code] === 1) {
2119
+ if (start === -1) start = i;
2120
+ } else if (code === 32 || code === 9) {
2121
+ if (end === -1 && start !== -1) end = i;
2122
+ } else if (code === 59 || code === 44) {
2123
+ if (start === -1) {
2124
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2125
+ }
2126
+ if (end === -1) end = i;
2127
+ push(params, header.slice(start, end), true);
2128
+ if (code === 44) {
2129
+ push(offers, extensionName, params);
2130
+ params = /* @__PURE__ */ Object.create(null);
2131
+ extensionName = void 0;
2132
+ }
2133
+ start = end = -1;
2134
+ } else if (code === 61 && start !== -1 && end === -1) {
2135
+ paramName = header.slice(start, i);
2136
+ start = end = -1;
2137
+ } else {
2138
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2139
+ }
2140
+ } else {
2141
+ if (isEscaping) {
2142
+ if (tokenChars[code] !== 1) {
2143
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2144
+ }
2145
+ if (start === -1) start = i;
2146
+ else if (!mustUnescape) mustUnescape = true;
2147
+ isEscaping = false;
2148
+ } else if (inQuotes) {
2149
+ if (tokenChars[code] === 1) {
2150
+ if (start === -1) start = i;
2151
+ } else if (code === 34 && start !== -1) {
2152
+ inQuotes = false;
2153
+ end = i;
2154
+ } else if (code === 92) {
2155
+ isEscaping = true;
2156
+ } else {
2157
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2158
+ }
2159
+ } else if (code === 34 && header.charCodeAt(i - 1) === 61) {
2160
+ inQuotes = true;
2161
+ } else if (end === -1 && tokenChars[code] === 1) {
2162
+ if (start === -1) start = i;
2163
+ } else if (start !== -1 && (code === 32 || code === 9)) {
2164
+ if (end === -1) end = i;
2165
+ } else if (code === 59 || code === 44) {
2166
+ if (start === -1) {
2167
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2168
+ }
2169
+ if (end === -1) end = i;
2170
+ let value = header.slice(start, end);
2171
+ if (mustUnescape) {
2172
+ value = value.replace(/\\/g, "");
2173
+ mustUnescape = false;
2174
+ }
2175
+ push(params, paramName, value);
2176
+ if (code === 44) {
2177
+ push(offers, extensionName, params);
2178
+ params = /* @__PURE__ */ Object.create(null);
2179
+ extensionName = void 0;
2180
+ }
2181
+ paramName = void 0;
2182
+ start = end = -1;
2183
+ } else {
2184
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2185
+ }
2186
+ }
2187
+ }
2188
+ if (start === -1 || inQuotes || code === 32 || code === 9) {
2189
+ throw new SyntaxError("Unexpected end of input");
2190
+ }
2191
+ if (end === -1) end = i;
2192
+ const token = header.slice(start, end);
2193
+ if (extensionName === void 0) {
2194
+ push(offers, token, params);
2195
+ } else {
2196
+ if (paramName === void 0) {
2197
+ push(params, token, true);
2198
+ } else if (mustUnescape) {
2199
+ push(params, paramName, token.replace(/\\/g, ""));
2200
+ } else {
2201
+ push(params, paramName, token);
2202
+ }
2203
+ push(offers, extensionName, params);
2204
+ }
2205
+ return offers;
2206
+ }
2207
+ function format(extensions) {
2208
+ return Object.keys(extensions).map((extension2) => {
2209
+ let configurations = extensions[extension2];
2210
+ if (!Array.isArray(configurations)) configurations = [configurations];
2211
+ return configurations.map((params) => {
2212
+ return [extension2].concat(
2213
+ Object.keys(params).map((k) => {
2214
+ let values = params[k];
2215
+ if (!Array.isArray(values)) values = [values];
2216
+ return values.map((v) => v === true ? k : `${k}=${v}`).join("; ");
2217
+ })
2218
+ ).join("; ");
2219
+ }).join(", ");
2220
+ }).join(", ");
2221
+ }
2222
+ module2.exports = { format, parse };
2223
+ }
2224
+ });
2225
+
2226
+ // node_modules/ws/lib/websocket.js
2227
+ var require_websocket = __commonJS({
2228
+ "node_modules/ws/lib/websocket.js"(exports2, module2) {
2229
+ "use strict";
2230
+ var EventEmitter = require("events");
2231
+ var https = require("https");
2232
+ var http = require("http");
2233
+ var net = require("net");
2234
+ var tls = require("tls");
2235
+ var { randomBytes, createHash } = require("crypto");
2236
+ var { Duplex, Readable } = require("stream");
2237
+ var { URL: URL2 } = require("url");
2238
+ var PerMessageDeflate2 = require_permessage_deflate();
2239
+ var Receiver2 = require_receiver();
2240
+ var Sender2 = require_sender();
2241
+ var { isBlob } = require_validation();
2242
+ var {
2243
+ BINARY_TYPES,
2244
+ CLOSE_TIMEOUT,
2245
+ EMPTY_BUFFER,
2246
+ GUID,
2247
+ kForOnEventAttribute,
2248
+ kListener,
2249
+ kStatusCode,
2250
+ kWebSocket,
2251
+ NOOP
2252
+ } = require_constants();
2253
+ var {
2254
+ EventTarget: { addEventListener, removeEventListener }
2255
+ } = require_event_target();
2256
+ var { format, parse } = require_extension();
2257
+ var { toBuffer } = require_buffer_util();
2258
+ var kAborted = /* @__PURE__ */ Symbol("kAborted");
2259
+ var protocolVersions = [8, 13];
2260
+ var readyStates = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"];
2261
+ var subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
2262
+ var WebSocket2 = class _WebSocket extends EventEmitter {
2263
+ /**
2264
+ * Create a new `WebSocket`.
2265
+ *
2266
+ * @param {(String|URL)} address The URL to which to connect
2267
+ * @param {(String|String[])} [protocols] The subprotocols
2268
+ * @param {Object} [options] Connection options
2269
+ */
2270
+ constructor(address, protocols, options) {
2271
+ super();
2272
+ this._binaryType = BINARY_TYPES[0];
2273
+ this._closeCode = 1006;
2274
+ this._closeFrameReceived = false;
2275
+ this._closeFrameSent = false;
2276
+ this._closeMessage = EMPTY_BUFFER;
2277
+ this._closeTimer = null;
2278
+ this._errorEmitted = false;
2279
+ this._extensions = {};
2280
+ this._paused = false;
2281
+ this._protocol = "";
2282
+ this._readyState = _WebSocket.CONNECTING;
2283
+ this._receiver = null;
2284
+ this._sender = null;
2285
+ this._socket = null;
2286
+ if (address !== null) {
2287
+ this._bufferedAmount = 0;
2288
+ this._isServer = false;
2289
+ this._redirects = 0;
2290
+ if (protocols === void 0) {
2291
+ protocols = [];
2292
+ } else if (!Array.isArray(protocols)) {
2293
+ if (typeof protocols === "object" && protocols !== null) {
2294
+ options = protocols;
2295
+ protocols = [];
2296
+ } else {
2297
+ protocols = [protocols];
2298
+ }
2299
+ }
2300
+ initAsClient(this, address, protocols, options);
2301
+ } else {
2302
+ this._autoPong = options.autoPong;
2303
+ this._closeTimeout = options.closeTimeout;
2304
+ this._isServer = true;
2305
+ }
2306
+ }
2307
+ /**
2308
+ * For historical reasons, the custom "nodebuffer" type is used by the default
2309
+ * instead of "blob".
2310
+ *
2311
+ * @type {String}
2312
+ */
2313
+ get binaryType() {
2314
+ return this._binaryType;
2315
+ }
2316
+ set binaryType(type) {
2317
+ if (!BINARY_TYPES.includes(type)) return;
2318
+ this._binaryType = type;
2319
+ if (this._receiver) this._receiver._binaryType = type;
2320
+ }
2321
+ /**
2322
+ * @type {Number}
2323
+ */
2324
+ get bufferedAmount() {
2325
+ if (!this._socket) return this._bufferedAmount;
2326
+ return this._socket._writableState.length + this._sender._bufferedBytes;
2327
+ }
2328
+ /**
2329
+ * @type {String}
2330
+ */
2331
+ get extensions() {
2332
+ return Object.keys(this._extensions).join();
2333
+ }
2334
+ /**
2335
+ * @type {Boolean}
2336
+ */
2337
+ get isPaused() {
2338
+ return this._paused;
2339
+ }
2340
+ /**
2341
+ * @type {Function}
2342
+ */
2343
+ /* istanbul ignore next */
2344
+ get onclose() {
2345
+ return null;
2346
+ }
2347
+ /**
2348
+ * @type {Function}
2349
+ */
2350
+ /* istanbul ignore next */
2351
+ get onerror() {
2352
+ return null;
2353
+ }
2354
+ /**
2355
+ * @type {Function}
2356
+ */
2357
+ /* istanbul ignore next */
2358
+ get onopen() {
2359
+ return null;
2360
+ }
2361
+ /**
2362
+ * @type {Function}
2363
+ */
2364
+ /* istanbul ignore next */
2365
+ get onmessage() {
2366
+ return null;
2367
+ }
2368
+ /**
2369
+ * @type {String}
2370
+ */
2371
+ get protocol() {
2372
+ return this._protocol;
2373
+ }
2374
+ /**
2375
+ * @type {Number}
2376
+ */
2377
+ get readyState() {
2378
+ return this._readyState;
2379
+ }
2380
+ /**
2381
+ * @type {String}
2382
+ */
2383
+ get url() {
2384
+ return this._url;
2385
+ }
2386
+ /**
2387
+ * Set up the socket and the internal resources.
2388
+ *
2389
+ * @param {Duplex} socket The network socket between the server and client
2390
+ * @param {Buffer} head The first packet of the upgraded stream
2391
+ * @param {Object} options Options object
2392
+ * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether
2393
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
2394
+ * multiple times in the same tick
2395
+ * @param {Function} [options.generateMask] The function used to generate the
2396
+ * masking key
2397
+ * @param {Number} [options.maxPayload=0] The maximum allowed message size
2398
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
2399
+ * not to skip UTF-8 validation for text and close messages
2400
+ * @private
2401
+ */
2402
+ setSocket(socket, head, options) {
2403
+ const receiver = new Receiver2({
2404
+ allowSynchronousEvents: options.allowSynchronousEvents,
2405
+ binaryType: this.binaryType,
2406
+ extensions: this._extensions,
2407
+ isServer: this._isServer,
2408
+ maxPayload: options.maxPayload,
2409
+ skipUTF8Validation: options.skipUTF8Validation
2410
+ });
2411
+ const sender = new Sender2(socket, this._extensions, options.generateMask);
2412
+ this._receiver = receiver;
2413
+ this._sender = sender;
2414
+ this._socket = socket;
2415
+ receiver[kWebSocket] = this;
2416
+ sender[kWebSocket] = this;
2417
+ socket[kWebSocket] = this;
2418
+ receiver.on("conclude", receiverOnConclude);
2419
+ receiver.on("drain", receiverOnDrain);
2420
+ receiver.on("error", receiverOnError);
2421
+ receiver.on("message", receiverOnMessage);
2422
+ receiver.on("ping", receiverOnPing);
2423
+ receiver.on("pong", receiverOnPong);
2424
+ sender.onerror = senderOnError;
2425
+ if (socket.setTimeout) socket.setTimeout(0);
2426
+ if (socket.setNoDelay) socket.setNoDelay();
2427
+ if (head.length > 0) socket.unshift(head);
2428
+ socket.on("close", socketOnClose);
2429
+ socket.on("data", socketOnData);
2430
+ socket.on("end", socketOnEnd);
2431
+ socket.on("error", socketOnError);
2432
+ this._readyState = _WebSocket.OPEN;
2433
+ this.emit("open");
2434
+ }
2435
+ /**
2436
+ * Emit the `'close'` event.
2437
+ *
2438
+ * @private
2439
+ */
2440
+ emitClose() {
2441
+ if (!this._socket) {
2442
+ this._readyState = _WebSocket.CLOSED;
2443
+ this.emit("close", this._closeCode, this._closeMessage);
2444
+ return;
2445
+ }
2446
+ if (this._extensions[PerMessageDeflate2.extensionName]) {
2447
+ this._extensions[PerMessageDeflate2.extensionName].cleanup();
2448
+ }
2449
+ this._receiver.removeAllListeners();
2450
+ this._readyState = _WebSocket.CLOSED;
2451
+ this.emit("close", this._closeCode, this._closeMessage);
2452
+ }
2453
+ /**
2454
+ * Start a closing handshake.
2455
+ *
2456
+ * +----------+ +-----------+ +----------+
2457
+ * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -
2458
+ * | +----------+ +-----------+ +----------+ |
2459
+ * +----------+ +-----------+ |
2460
+ * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING
2461
+ * +----------+ +-----------+ |
2462
+ * | | | +---+ |
2463
+ * +------------------------+-->|fin| - - - -
2464
+ * | +---+ | +---+
2465
+ * - - - - -|fin|<---------------------+
2466
+ * +---+
2467
+ *
2468
+ * @param {Number} [code] Status code explaining why the connection is closing
2469
+ * @param {(String|Buffer)} [data] The reason why the connection is
2470
+ * closing
2471
+ * @public
2472
+ */
2473
+ close(code, data) {
2474
+ if (this.readyState === _WebSocket.CLOSED) return;
2475
+ if (this.readyState === _WebSocket.CONNECTING) {
2476
+ const msg = "WebSocket was closed before the connection was established";
2477
+ abortHandshake(this, this._req, msg);
2478
+ return;
2479
+ }
2480
+ if (this.readyState === _WebSocket.CLOSING) {
2481
+ if (this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted)) {
2482
+ this._socket.end();
2483
+ }
2484
+ return;
2485
+ }
2486
+ this._readyState = _WebSocket.CLOSING;
2487
+ this._sender.close(code, data, !this._isServer, (err) => {
2488
+ if (err) return;
2489
+ this._closeFrameSent = true;
2490
+ if (this._closeFrameReceived || this._receiver._writableState.errorEmitted) {
2491
+ this._socket.end();
2492
+ }
2493
+ });
2494
+ setCloseTimer(this);
2495
+ }
2496
+ /**
2497
+ * Pause the socket.
2498
+ *
2499
+ * @public
2500
+ */
2501
+ pause() {
2502
+ if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) {
2503
+ return;
2504
+ }
2505
+ this._paused = true;
2506
+ this._socket.pause();
2507
+ }
2508
+ /**
2509
+ * Send a ping.
2510
+ *
2511
+ * @param {*} [data] The data to send
2512
+ * @param {Boolean} [mask] Indicates whether or not to mask `data`
2513
+ * @param {Function} [cb] Callback which is executed when the ping is sent
2514
+ * @public
2515
+ */
2516
+ ping(data, mask, cb) {
2517
+ if (this.readyState === _WebSocket.CONNECTING) {
2518
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
2519
+ }
2520
+ if (typeof data === "function") {
2521
+ cb = data;
2522
+ data = mask = void 0;
2523
+ } else if (typeof mask === "function") {
2524
+ cb = mask;
2525
+ mask = void 0;
2526
+ }
2527
+ if (typeof data === "number") data = data.toString();
2528
+ if (this.readyState !== _WebSocket.OPEN) {
2529
+ sendAfterClose(this, data, cb);
2530
+ return;
2531
+ }
2532
+ if (mask === void 0) mask = !this._isServer;
2533
+ this._sender.ping(data || EMPTY_BUFFER, mask, cb);
2534
+ }
2535
+ /**
2536
+ * Send a pong.
2537
+ *
2538
+ * @param {*} [data] The data to send
2539
+ * @param {Boolean} [mask] Indicates whether or not to mask `data`
2540
+ * @param {Function} [cb] Callback which is executed when the pong is sent
2541
+ * @public
2542
+ */
2543
+ pong(data, mask, cb) {
2544
+ if (this.readyState === _WebSocket.CONNECTING) {
2545
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
2546
+ }
2547
+ if (typeof data === "function") {
2548
+ cb = data;
2549
+ data = mask = void 0;
2550
+ } else if (typeof mask === "function") {
2551
+ cb = mask;
2552
+ mask = void 0;
2553
+ }
2554
+ if (typeof data === "number") data = data.toString();
2555
+ if (this.readyState !== _WebSocket.OPEN) {
2556
+ sendAfterClose(this, data, cb);
2557
+ return;
2558
+ }
2559
+ if (mask === void 0) mask = !this._isServer;
2560
+ this._sender.pong(data || EMPTY_BUFFER, mask, cb);
2561
+ }
2562
+ /**
2563
+ * Resume the socket.
2564
+ *
2565
+ * @public
2566
+ */
2567
+ resume() {
2568
+ if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) {
2569
+ return;
2570
+ }
2571
+ this._paused = false;
2572
+ if (!this._receiver._writableState.needDrain) this._socket.resume();
2573
+ }
2574
+ /**
2575
+ * Send a data message.
2576
+ *
2577
+ * @param {*} data The message to send
2578
+ * @param {Object} [options] Options object
2579
+ * @param {Boolean} [options.binary] Specifies whether `data` is binary or
2580
+ * text
2581
+ * @param {Boolean} [options.compress] Specifies whether or not to compress
2582
+ * `data`
2583
+ * @param {Boolean} [options.fin=true] Specifies whether the fragment is the
2584
+ * last one
2585
+ * @param {Boolean} [options.mask] Specifies whether or not to mask `data`
2586
+ * @param {Function} [cb] Callback which is executed when data is written out
2587
+ * @public
2588
+ */
2589
+ send(data, options, cb) {
2590
+ if (this.readyState === _WebSocket.CONNECTING) {
2591
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
2592
+ }
2593
+ if (typeof options === "function") {
2594
+ cb = options;
2595
+ options = {};
2596
+ }
2597
+ if (typeof data === "number") data = data.toString();
2598
+ if (this.readyState !== _WebSocket.OPEN) {
2599
+ sendAfterClose(this, data, cb);
2600
+ return;
2601
+ }
2602
+ const opts = {
2603
+ binary: typeof data !== "string",
2604
+ mask: !this._isServer,
2605
+ compress: true,
2606
+ fin: true,
2607
+ ...options
2608
+ };
2609
+ if (!this._extensions[PerMessageDeflate2.extensionName]) {
2610
+ opts.compress = false;
2611
+ }
2612
+ this._sender.send(data || EMPTY_BUFFER, opts, cb);
2613
+ }
2614
+ /**
2615
+ * Forcibly close the connection.
2616
+ *
2617
+ * @public
2618
+ */
2619
+ terminate() {
2620
+ if (this.readyState === _WebSocket.CLOSED) return;
2621
+ if (this.readyState === _WebSocket.CONNECTING) {
2622
+ const msg = "WebSocket was closed before the connection was established";
2623
+ abortHandshake(this, this._req, msg);
2624
+ return;
2625
+ }
2626
+ if (this._socket) {
2627
+ this._readyState = _WebSocket.CLOSING;
2628
+ this._socket.destroy();
2629
+ }
2630
+ }
2631
+ };
2632
+ Object.defineProperty(WebSocket2, "CONNECTING", {
2633
+ enumerable: true,
2634
+ value: readyStates.indexOf("CONNECTING")
2635
+ });
2636
+ Object.defineProperty(WebSocket2.prototype, "CONNECTING", {
2637
+ enumerable: true,
2638
+ value: readyStates.indexOf("CONNECTING")
2639
+ });
2640
+ Object.defineProperty(WebSocket2, "OPEN", {
2641
+ enumerable: true,
2642
+ value: readyStates.indexOf("OPEN")
2643
+ });
2644
+ Object.defineProperty(WebSocket2.prototype, "OPEN", {
2645
+ enumerable: true,
2646
+ value: readyStates.indexOf("OPEN")
2647
+ });
2648
+ Object.defineProperty(WebSocket2, "CLOSING", {
2649
+ enumerable: true,
2650
+ value: readyStates.indexOf("CLOSING")
2651
+ });
2652
+ Object.defineProperty(WebSocket2.prototype, "CLOSING", {
2653
+ enumerable: true,
2654
+ value: readyStates.indexOf("CLOSING")
2655
+ });
2656
+ Object.defineProperty(WebSocket2, "CLOSED", {
2657
+ enumerable: true,
2658
+ value: readyStates.indexOf("CLOSED")
2659
+ });
2660
+ Object.defineProperty(WebSocket2.prototype, "CLOSED", {
2661
+ enumerable: true,
2662
+ value: readyStates.indexOf("CLOSED")
2663
+ });
2664
+ [
2665
+ "binaryType",
2666
+ "bufferedAmount",
2667
+ "extensions",
2668
+ "isPaused",
2669
+ "protocol",
2670
+ "readyState",
2671
+ "url"
2672
+ ].forEach((property) => {
2673
+ Object.defineProperty(WebSocket2.prototype, property, { enumerable: true });
2674
+ });
2675
+ ["open", "error", "close", "message"].forEach((method) => {
2676
+ Object.defineProperty(WebSocket2.prototype, `on${method}`, {
2677
+ enumerable: true,
2678
+ get() {
2679
+ for (const listener of this.listeners(method)) {
2680
+ if (listener[kForOnEventAttribute]) return listener[kListener];
2681
+ }
2682
+ return null;
2683
+ },
2684
+ set(handler) {
2685
+ for (const listener of this.listeners(method)) {
2686
+ if (listener[kForOnEventAttribute]) {
2687
+ this.removeListener(method, listener);
2688
+ break;
2689
+ }
2690
+ }
2691
+ if (typeof handler !== "function") return;
2692
+ this.addEventListener(method, handler, {
2693
+ [kForOnEventAttribute]: true
2694
+ });
2695
+ }
2696
+ });
2697
+ });
2698
+ WebSocket2.prototype.addEventListener = addEventListener;
2699
+ WebSocket2.prototype.removeEventListener = removeEventListener;
2700
+ module2.exports = WebSocket2;
2701
+ function initAsClient(websocket, address, protocols, options) {
2702
+ const opts = {
2703
+ allowSynchronousEvents: true,
2704
+ autoPong: true,
2705
+ closeTimeout: CLOSE_TIMEOUT,
2706
+ protocolVersion: protocolVersions[1],
2707
+ maxPayload: 100 * 1024 * 1024,
2708
+ skipUTF8Validation: false,
2709
+ perMessageDeflate: true,
2710
+ followRedirects: false,
2711
+ maxRedirects: 10,
2712
+ ...options,
2713
+ socketPath: void 0,
2714
+ hostname: void 0,
2715
+ protocol: void 0,
2716
+ timeout: void 0,
2717
+ method: "GET",
2718
+ host: void 0,
2719
+ path: void 0,
2720
+ port: void 0
2721
+ };
2722
+ websocket._autoPong = opts.autoPong;
2723
+ websocket._closeTimeout = opts.closeTimeout;
2724
+ if (!protocolVersions.includes(opts.protocolVersion)) {
2725
+ throw new RangeError(
2726
+ `Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`
2727
+ );
2728
+ }
2729
+ let parsedUrl;
2730
+ if (address instanceof URL2) {
2731
+ parsedUrl = address;
2732
+ } else {
2733
+ try {
2734
+ parsedUrl = new URL2(address);
2735
+ } catch {
2736
+ throw new SyntaxError(`Invalid URL: ${address}`);
2737
+ }
2738
+ }
2739
+ if (parsedUrl.protocol === "http:") {
2740
+ parsedUrl.protocol = "ws:";
2741
+ } else if (parsedUrl.protocol === "https:") {
2742
+ parsedUrl.protocol = "wss:";
2743
+ }
2744
+ websocket._url = parsedUrl.href;
2745
+ const isSecure = parsedUrl.protocol === "wss:";
2746
+ const isIpcUrl = parsedUrl.protocol === "ws+unix:";
2747
+ let invalidUrlMessage;
2748
+ if (parsedUrl.protocol !== "ws:" && !isSecure && !isIpcUrl) {
2749
+ invalidUrlMessage = `The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`;
2750
+ } else if (isIpcUrl && !parsedUrl.pathname) {
2751
+ invalidUrlMessage = "The URL's pathname is empty";
2752
+ } else if (parsedUrl.hash) {
2753
+ invalidUrlMessage = "The URL contains a fragment identifier";
2754
+ }
2755
+ if (invalidUrlMessage) {
2756
+ const err = new SyntaxError(invalidUrlMessage);
2757
+ if (websocket._redirects === 0) {
2758
+ throw err;
2759
+ } else {
2760
+ emitErrorAndClose(websocket, err);
2761
+ return;
2762
+ }
2763
+ }
2764
+ const defaultPort = isSecure ? 443 : 80;
2765
+ const key = randomBytes(16).toString("base64");
2766
+ const request = isSecure ? https.request : http.request;
2767
+ const protocolSet = /* @__PURE__ */ new Set();
2768
+ let perMessageDeflate;
2769
+ opts.createConnection = opts.createConnection || (isSecure ? tlsConnect : netConnect);
2770
+ opts.defaultPort = opts.defaultPort || defaultPort;
2771
+ opts.port = parsedUrl.port || defaultPort;
2772
+ opts.host = parsedUrl.hostname.startsWith("[") ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname;
2773
+ opts.headers = {
2774
+ ...opts.headers,
2775
+ "Sec-WebSocket-Version": opts.protocolVersion,
2776
+ "Sec-WebSocket-Key": key,
2777
+ Connection: "Upgrade",
2778
+ Upgrade: "websocket"
2779
+ };
2780
+ opts.path = parsedUrl.pathname + parsedUrl.search;
2781
+ opts.timeout = opts.handshakeTimeout;
2782
+ if (opts.perMessageDeflate) {
2783
+ perMessageDeflate = new PerMessageDeflate2({
2784
+ ...opts.perMessageDeflate,
2785
+ isServer: false,
2786
+ maxPayload: opts.maxPayload
2787
+ });
2788
+ opts.headers["Sec-WebSocket-Extensions"] = format({
2789
+ [PerMessageDeflate2.extensionName]: perMessageDeflate.offer()
2790
+ });
2791
+ }
2792
+ if (protocols.length) {
2793
+ for (const protocol of protocols) {
2794
+ if (typeof protocol !== "string" || !subprotocolRegex.test(protocol) || protocolSet.has(protocol)) {
2795
+ throw new SyntaxError(
2796
+ "An invalid or duplicated subprotocol was specified"
2797
+ );
2798
+ }
2799
+ protocolSet.add(protocol);
2800
+ }
2801
+ opts.headers["Sec-WebSocket-Protocol"] = protocols.join(",");
2802
+ }
2803
+ if (opts.origin) {
2804
+ if (opts.protocolVersion < 13) {
2805
+ opts.headers["Sec-WebSocket-Origin"] = opts.origin;
2806
+ } else {
2807
+ opts.headers.Origin = opts.origin;
2808
+ }
2809
+ }
2810
+ if (parsedUrl.username || parsedUrl.password) {
2811
+ opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
2812
+ }
2813
+ if (isIpcUrl) {
2814
+ const parts = opts.path.split(":");
2815
+ opts.socketPath = parts[0];
2816
+ opts.path = parts[1];
2817
+ }
2818
+ let req;
2819
+ if (opts.followRedirects) {
2820
+ if (websocket._redirects === 0) {
2821
+ websocket._originalIpc = isIpcUrl;
2822
+ websocket._originalSecure = isSecure;
2823
+ websocket._originalHostOrSocketPath = isIpcUrl ? opts.socketPath : parsedUrl.host;
2824
+ const headers = options && options.headers;
2825
+ options = { ...options, headers: {} };
2826
+ if (headers) {
2827
+ for (const [key2, value] of Object.entries(headers)) {
2828
+ options.headers[key2.toLowerCase()] = value;
2829
+ }
2830
+ }
2831
+ } else if (websocket.listenerCount("redirect") === 0) {
2832
+ const isSameHost = isIpcUrl ? websocket._originalIpc ? opts.socketPath === websocket._originalHostOrSocketPath : false : websocket._originalIpc ? false : parsedUrl.host === websocket._originalHostOrSocketPath;
2833
+ if (!isSameHost || websocket._originalSecure && !isSecure) {
2834
+ delete opts.headers.authorization;
2835
+ delete opts.headers.cookie;
2836
+ if (!isSameHost) delete opts.headers.host;
2837
+ opts.auth = void 0;
2838
+ }
2839
+ }
2840
+ if (opts.auth && !options.headers.authorization) {
2841
+ options.headers.authorization = "Basic " + Buffer.from(opts.auth).toString("base64");
2842
+ }
2843
+ req = websocket._req = request(opts);
2844
+ if (websocket._redirects) {
2845
+ websocket.emit("redirect", websocket.url, req);
2846
+ }
2847
+ } else {
2848
+ req = websocket._req = request(opts);
2849
+ }
2850
+ if (opts.timeout) {
2851
+ req.on("timeout", () => {
2852
+ abortHandshake(websocket, req, "Opening handshake has timed out");
2853
+ });
2854
+ }
2855
+ req.on("error", (err) => {
2856
+ if (req === null || req[kAborted]) return;
2857
+ req = websocket._req = null;
2858
+ emitErrorAndClose(websocket, err);
2859
+ });
2860
+ req.on("response", (res) => {
2861
+ const location = res.headers.location;
2862
+ const statusCode = res.statusCode;
2863
+ if (location && opts.followRedirects && statusCode >= 300 && statusCode < 400) {
2864
+ if (++websocket._redirects > opts.maxRedirects) {
2865
+ abortHandshake(websocket, req, "Maximum redirects exceeded");
2866
+ return;
2867
+ }
2868
+ req.abort();
2869
+ let addr;
2870
+ try {
2871
+ addr = new URL2(location, address);
2872
+ } catch (e) {
2873
+ const err = new SyntaxError(`Invalid URL: ${location}`);
2874
+ emitErrorAndClose(websocket, err);
2875
+ return;
2876
+ }
2877
+ initAsClient(websocket, addr, protocols, options);
2878
+ } else if (!websocket.emit("unexpected-response", req, res)) {
2879
+ abortHandshake(
2880
+ websocket,
2881
+ req,
2882
+ `Unexpected server response: ${res.statusCode}`
2883
+ );
2884
+ }
2885
+ });
2886
+ req.on("upgrade", (res, socket, head) => {
2887
+ websocket.emit("upgrade", res);
2888
+ if (websocket.readyState !== WebSocket2.CONNECTING) return;
2889
+ req = websocket._req = null;
2890
+ const upgrade = res.headers.upgrade;
2891
+ if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
2892
+ abortHandshake(websocket, socket, "Invalid Upgrade header");
2893
+ return;
2894
+ }
2895
+ const digest = createHash("sha1").update(key + GUID).digest("base64");
2896
+ if (res.headers["sec-websocket-accept"] !== digest) {
2897
+ abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
2898
+ return;
2899
+ }
2900
+ const serverProt = res.headers["sec-websocket-protocol"];
2901
+ let protError;
2902
+ if (serverProt !== void 0) {
2903
+ if (!protocolSet.size) {
2904
+ protError = "Server sent a subprotocol but none was requested";
2905
+ } else if (!protocolSet.has(serverProt)) {
2906
+ protError = "Server sent an invalid subprotocol";
2907
+ }
2908
+ } else if (protocolSet.size) {
2909
+ protError = "Server sent no subprotocol";
2910
+ }
2911
+ if (protError) {
2912
+ abortHandshake(websocket, socket, protError);
2913
+ return;
2914
+ }
2915
+ if (serverProt) websocket._protocol = serverProt;
2916
+ const secWebSocketExtensions = res.headers["sec-websocket-extensions"];
2917
+ if (secWebSocketExtensions !== void 0) {
2918
+ if (!perMessageDeflate) {
2919
+ const message = "Server sent a Sec-WebSocket-Extensions header but no extension was requested";
2920
+ abortHandshake(websocket, socket, message);
2921
+ return;
2922
+ }
2923
+ let extensions;
2924
+ try {
2925
+ extensions = parse(secWebSocketExtensions);
2926
+ } catch (err) {
2927
+ const message = "Invalid Sec-WebSocket-Extensions header";
2928
+ abortHandshake(websocket, socket, message);
2929
+ return;
2930
+ }
2931
+ const extensionNames = Object.keys(extensions);
2932
+ if (extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate2.extensionName) {
2933
+ const message = "Server indicated an extension that was not requested";
2934
+ abortHandshake(websocket, socket, message);
2935
+ return;
2936
+ }
2937
+ try {
2938
+ perMessageDeflate.accept(extensions[PerMessageDeflate2.extensionName]);
2939
+ } catch (err) {
2940
+ const message = "Invalid Sec-WebSocket-Extensions header";
2941
+ abortHandshake(websocket, socket, message);
2942
+ return;
2943
+ }
2944
+ websocket._extensions[PerMessageDeflate2.extensionName] = perMessageDeflate;
2945
+ }
2946
+ websocket.setSocket(socket, head, {
2947
+ allowSynchronousEvents: opts.allowSynchronousEvents,
2948
+ generateMask: opts.generateMask,
2949
+ maxPayload: opts.maxPayload,
2950
+ skipUTF8Validation: opts.skipUTF8Validation
2951
+ });
2952
+ });
2953
+ if (opts.finishRequest) {
2954
+ opts.finishRequest(req, websocket);
2955
+ } else {
2956
+ req.end();
2957
+ }
2958
+ }
2959
+ function emitErrorAndClose(websocket, err) {
2960
+ websocket._readyState = WebSocket2.CLOSING;
2961
+ websocket._errorEmitted = true;
2962
+ websocket.emit("error", err);
2963
+ websocket.emitClose();
2964
+ }
2965
+ function netConnect(options) {
2966
+ options.path = options.socketPath;
2967
+ return net.connect(options);
2968
+ }
2969
+ function tlsConnect(options) {
2970
+ options.path = void 0;
2971
+ if (!options.servername && options.servername !== "") {
2972
+ options.servername = net.isIP(options.host) ? "" : options.host;
2973
+ }
2974
+ return tls.connect(options);
2975
+ }
2976
+ function abortHandshake(websocket, stream, message) {
2977
+ websocket._readyState = WebSocket2.CLOSING;
2978
+ const err = new Error(message);
2979
+ Error.captureStackTrace(err, abortHandshake);
2980
+ if (stream.setHeader) {
2981
+ stream[kAborted] = true;
2982
+ stream.abort();
2983
+ if (stream.socket && !stream.socket.destroyed) {
2984
+ stream.socket.destroy();
2985
+ }
2986
+ process.nextTick(emitErrorAndClose, websocket, err);
2987
+ } else {
2988
+ stream.destroy(err);
2989
+ stream.once("error", websocket.emit.bind(websocket, "error"));
2990
+ stream.once("close", websocket.emitClose.bind(websocket));
2991
+ }
2992
+ }
2993
+ function sendAfterClose(websocket, data, cb) {
2994
+ if (data) {
2995
+ const length = isBlob(data) ? data.size : toBuffer(data).length;
2996
+ if (websocket._socket) websocket._sender._bufferedBytes += length;
2997
+ else websocket._bufferedAmount += length;
2998
+ }
2999
+ if (cb) {
3000
+ const err = new Error(
3001
+ `WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})`
3002
+ );
3003
+ process.nextTick(cb, err);
3004
+ }
3005
+ }
3006
+ function receiverOnConclude(code, reason) {
3007
+ const websocket = this[kWebSocket];
3008
+ websocket._closeFrameReceived = true;
3009
+ websocket._closeMessage = reason;
3010
+ websocket._closeCode = code;
3011
+ if (websocket._socket[kWebSocket] === void 0) return;
3012
+ websocket._socket.removeListener("data", socketOnData);
3013
+ process.nextTick(resume, websocket._socket);
3014
+ if (code === 1005) websocket.close();
3015
+ else websocket.close(code, reason);
3016
+ }
3017
+ function receiverOnDrain() {
3018
+ const websocket = this[kWebSocket];
3019
+ if (!websocket.isPaused) websocket._socket.resume();
3020
+ }
3021
+ function receiverOnError(err) {
3022
+ const websocket = this[kWebSocket];
3023
+ if (websocket._socket[kWebSocket] !== void 0) {
3024
+ websocket._socket.removeListener("data", socketOnData);
3025
+ process.nextTick(resume, websocket._socket);
3026
+ websocket.close(err[kStatusCode]);
3027
+ }
3028
+ if (!websocket._errorEmitted) {
3029
+ websocket._errorEmitted = true;
3030
+ websocket.emit("error", err);
3031
+ }
3032
+ }
3033
+ function receiverOnFinish() {
3034
+ this[kWebSocket].emitClose();
3035
+ }
3036
+ function receiverOnMessage(data, isBinary) {
3037
+ this[kWebSocket].emit("message", data, isBinary);
3038
+ }
3039
+ function receiverOnPing(data) {
3040
+ const websocket = this[kWebSocket];
3041
+ if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP);
3042
+ websocket.emit("ping", data);
3043
+ }
3044
+ function receiverOnPong(data) {
3045
+ this[kWebSocket].emit("pong", data);
3046
+ }
3047
+ function resume(stream) {
3048
+ stream.resume();
3049
+ }
3050
+ function senderOnError(err) {
3051
+ const websocket = this[kWebSocket];
3052
+ if (websocket.readyState === WebSocket2.CLOSED) return;
3053
+ if (websocket.readyState === WebSocket2.OPEN) {
3054
+ websocket._readyState = WebSocket2.CLOSING;
3055
+ setCloseTimer(websocket);
3056
+ }
3057
+ this._socket.end();
3058
+ if (!websocket._errorEmitted) {
3059
+ websocket._errorEmitted = true;
3060
+ websocket.emit("error", err);
3061
+ }
3062
+ }
3063
+ function setCloseTimer(websocket) {
3064
+ websocket._closeTimer = setTimeout(
3065
+ websocket._socket.destroy.bind(websocket._socket),
3066
+ websocket._closeTimeout
3067
+ );
3068
+ }
3069
+ function socketOnClose() {
3070
+ const websocket = this[kWebSocket];
3071
+ this.removeListener("close", socketOnClose);
3072
+ this.removeListener("data", socketOnData);
3073
+ this.removeListener("end", socketOnEnd);
3074
+ websocket._readyState = WebSocket2.CLOSING;
3075
+ if (!this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && this._readableState.length !== 0) {
3076
+ const chunk = this.read(this._readableState.length);
3077
+ websocket._receiver.write(chunk);
3078
+ }
3079
+ websocket._receiver.end();
3080
+ this[kWebSocket] = void 0;
3081
+ clearTimeout(websocket._closeTimer);
3082
+ if (websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted) {
3083
+ websocket.emitClose();
3084
+ } else {
3085
+ websocket._receiver.on("error", receiverOnFinish);
3086
+ websocket._receiver.on("finish", receiverOnFinish);
3087
+ }
3088
+ }
3089
+ function socketOnData(chunk) {
3090
+ if (!this[kWebSocket]._receiver.write(chunk)) {
3091
+ this.pause();
3092
+ }
3093
+ }
3094
+ function socketOnEnd() {
3095
+ const websocket = this[kWebSocket];
3096
+ websocket._readyState = WebSocket2.CLOSING;
3097
+ websocket._receiver.end();
3098
+ this.end();
3099
+ }
3100
+ function socketOnError() {
3101
+ const websocket = this[kWebSocket];
3102
+ this.removeListener("error", socketOnError);
3103
+ this.on("error", NOOP);
3104
+ if (websocket) {
3105
+ websocket._readyState = WebSocket2.CLOSING;
3106
+ this.destroy();
3107
+ }
3108
+ }
3109
+ }
3110
+ });
3111
+
3112
+ // node_modules/ws/lib/stream.js
3113
+ var require_stream = __commonJS({
3114
+ "node_modules/ws/lib/stream.js"(exports2, module2) {
3115
+ "use strict";
3116
+ var WebSocket2 = require_websocket();
3117
+ var { Duplex } = require("stream");
3118
+ function emitClose(stream) {
3119
+ stream.emit("close");
3120
+ }
3121
+ function duplexOnEnd() {
3122
+ if (!this.destroyed && this._writableState.finished) {
3123
+ this.destroy();
3124
+ }
3125
+ }
3126
+ function duplexOnError(err) {
3127
+ this.removeListener("error", duplexOnError);
3128
+ this.destroy();
3129
+ if (this.listenerCount("error") === 0) {
3130
+ this.emit("error", err);
3131
+ }
3132
+ }
3133
+ function createWebSocketStream2(ws, options) {
3134
+ let terminateOnDestroy = true;
3135
+ const duplex = new Duplex({
3136
+ ...options,
3137
+ autoDestroy: false,
3138
+ emitClose: false,
3139
+ objectMode: false,
3140
+ writableObjectMode: false
3141
+ });
3142
+ ws.on("message", function message(msg, isBinary) {
3143
+ const data = !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;
3144
+ if (!duplex.push(data)) ws.pause();
3145
+ });
3146
+ ws.once("error", function error(err) {
3147
+ if (duplex.destroyed) return;
3148
+ terminateOnDestroy = false;
3149
+ duplex.destroy(err);
3150
+ });
3151
+ ws.once("close", function close() {
3152
+ if (duplex.destroyed) return;
3153
+ duplex.push(null);
3154
+ });
3155
+ duplex._destroy = function(err, callback) {
3156
+ if (ws.readyState === ws.CLOSED) {
3157
+ callback(err);
3158
+ process.nextTick(emitClose, duplex);
3159
+ return;
3160
+ }
3161
+ let called = false;
3162
+ ws.once("error", function error(err2) {
3163
+ called = true;
3164
+ callback(err2);
3165
+ });
3166
+ ws.once("close", function close() {
3167
+ if (!called) callback(err);
3168
+ process.nextTick(emitClose, duplex);
3169
+ });
3170
+ if (terminateOnDestroy) ws.terminate();
3171
+ };
3172
+ duplex._final = function(callback) {
3173
+ if (ws.readyState === ws.CONNECTING) {
3174
+ ws.once("open", function open() {
3175
+ duplex._final(callback);
3176
+ });
3177
+ return;
3178
+ }
3179
+ if (ws._socket === null) return;
3180
+ if (ws._socket._writableState.finished) {
3181
+ callback();
3182
+ if (duplex._readableState.endEmitted) duplex.destroy();
3183
+ } else {
3184
+ ws._socket.once("finish", function finish() {
3185
+ callback();
3186
+ });
3187
+ ws.close();
3188
+ }
3189
+ };
3190
+ duplex._read = function() {
3191
+ if (ws.isPaused) ws.resume();
3192
+ };
3193
+ duplex._write = function(chunk, encoding, callback) {
3194
+ if (ws.readyState === ws.CONNECTING) {
3195
+ ws.once("open", function open() {
3196
+ duplex._write(chunk, encoding, callback);
3197
+ });
3198
+ return;
3199
+ }
3200
+ ws.send(chunk, callback);
3201
+ };
3202
+ duplex.on("end", duplexOnEnd);
3203
+ duplex.on("error", duplexOnError);
3204
+ return duplex;
3205
+ }
3206
+ module2.exports = createWebSocketStream2;
3207
+ }
3208
+ });
3209
+
3210
+ // node_modules/ws/lib/subprotocol.js
3211
+ var require_subprotocol = __commonJS({
3212
+ "node_modules/ws/lib/subprotocol.js"(exports2, module2) {
3213
+ "use strict";
3214
+ var { tokenChars } = require_validation();
3215
+ function parse(header) {
3216
+ const protocols = /* @__PURE__ */ new Set();
3217
+ let start = -1;
3218
+ let end = -1;
3219
+ let i = 0;
3220
+ for (i; i < header.length; i++) {
3221
+ const code = header.charCodeAt(i);
3222
+ if (end === -1 && tokenChars[code] === 1) {
3223
+ if (start === -1) start = i;
3224
+ } else if (i !== 0 && (code === 32 || code === 9)) {
3225
+ if (end === -1 && start !== -1) end = i;
3226
+ } else if (code === 44) {
3227
+ if (start === -1) {
3228
+ throw new SyntaxError(`Unexpected character at index ${i}`);
3229
+ }
3230
+ if (end === -1) end = i;
3231
+ const protocol2 = header.slice(start, end);
3232
+ if (protocols.has(protocol2)) {
3233
+ throw new SyntaxError(`The "${protocol2}" subprotocol is duplicated`);
3234
+ }
3235
+ protocols.add(protocol2);
3236
+ start = end = -1;
3237
+ } else {
3238
+ throw new SyntaxError(`Unexpected character at index ${i}`);
3239
+ }
3240
+ }
3241
+ if (start === -1 || end !== -1) {
3242
+ throw new SyntaxError("Unexpected end of input");
3243
+ }
3244
+ const protocol = header.slice(start, i);
3245
+ if (protocols.has(protocol)) {
3246
+ throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
3247
+ }
3248
+ protocols.add(protocol);
3249
+ return protocols;
3250
+ }
3251
+ module2.exports = { parse };
3252
+ }
3253
+ });
3254
+
3255
+ // node_modules/ws/lib/websocket-server.js
3256
+ var require_websocket_server = __commonJS({
3257
+ "node_modules/ws/lib/websocket-server.js"(exports2, module2) {
3258
+ "use strict";
3259
+ var EventEmitter = require("events");
3260
+ var http = require("http");
3261
+ var { Duplex } = require("stream");
3262
+ var { createHash } = require("crypto");
3263
+ var extension2 = require_extension();
3264
+ var PerMessageDeflate2 = require_permessage_deflate();
3265
+ var subprotocol2 = require_subprotocol();
3266
+ var WebSocket2 = require_websocket();
3267
+ var { CLOSE_TIMEOUT, GUID, kWebSocket } = require_constants();
3268
+ var keyRegex = /^[+/0-9A-Za-z]{22}==$/;
3269
+ var RUNNING = 0;
3270
+ var CLOSING = 1;
3271
+ var CLOSED = 2;
3272
+ var WebSocketServer2 = class extends EventEmitter {
3273
+ /**
3274
+ * Create a `WebSocketServer` instance.
3275
+ *
3276
+ * @param {Object} options Configuration options
3277
+ * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
3278
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
3279
+ * multiple times in the same tick
3280
+ * @param {Boolean} [options.autoPong=true] Specifies whether or not to
3281
+ * automatically send a pong in response to a ping
3282
+ * @param {Number} [options.backlog=511] The maximum length of the queue of
3283
+ * pending connections
3284
+ * @param {Boolean} [options.clientTracking=true] Specifies whether or not to
3285
+ * track clients
3286
+ * @param {Number} [options.closeTimeout=30000] Duration in milliseconds to
3287
+ * wait for the closing handshake to finish after `websocket.close()` is
3288
+ * called
3289
+ * @param {Function} [options.handleProtocols] A hook to handle protocols
3290
+ * @param {String} [options.host] The hostname where to bind the server
3291
+ * @param {Number} [options.maxPayload=104857600] The maximum allowed message
3292
+ * size
3293
+ * @param {Boolean} [options.noServer=false] Enable no server mode
3294
+ * @param {String} [options.path] Accept only connections matching this path
3295
+ * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable
3296
+ * permessage-deflate
3297
+ * @param {Number} [options.port] The port where to bind the server
3298
+ * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S
3299
+ * server to use
3300
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
3301
+ * not to skip UTF-8 validation for text and close messages
3302
+ * @param {Function} [options.verifyClient] A hook to reject connections
3303
+ * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`
3304
+ * class to use. It must be the `WebSocket` class or class that extends it
3305
+ * @param {Function} [callback] A listener for the `listening` event
3306
+ */
3307
+ constructor(options, callback) {
3308
+ super();
3309
+ options = {
3310
+ allowSynchronousEvents: true,
3311
+ autoPong: true,
3312
+ maxPayload: 100 * 1024 * 1024,
3313
+ skipUTF8Validation: false,
3314
+ perMessageDeflate: false,
3315
+ handleProtocols: null,
3316
+ clientTracking: true,
3317
+ closeTimeout: CLOSE_TIMEOUT,
3318
+ verifyClient: null,
3319
+ noServer: false,
3320
+ backlog: null,
3321
+ // use default (511 as implemented in net.js)
3322
+ server: null,
3323
+ host: null,
3324
+ path: null,
3325
+ port: null,
3326
+ WebSocket: WebSocket2,
3327
+ ...options
3328
+ };
3329
+ if (options.port == null && !options.server && !options.noServer || options.port != null && (options.server || options.noServer) || options.server && options.noServer) {
3330
+ throw new TypeError(
3331
+ 'One and only one of the "port", "server", or "noServer" options must be specified'
3332
+ );
3333
+ }
3334
+ if (options.port != null) {
3335
+ this._server = http.createServer((req, res) => {
3336
+ const body = http.STATUS_CODES[426];
3337
+ res.writeHead(426, {
3338
+ "Content-Length": body.length,
3339
+ "Content-Type": "text/plain"
3340
+ });
3341
+ res.end(body);
3342
+ });
3343
+ this._server.listen(
3344
+ options.port,
3345
+ options.host,
3346
+ options.backlog,
3347
+ callback
3348
+ );
3349
+ } else if (options.server) {
3350
+ this._server = options.server;
3351
+ }
3352
+ if (this._server) {
3353
+ const emitConnection = this.emit.bind(this, "connection");
3354
+ this._removeListeners = addListeners(this._server, {
3355
+ listening: this.emit.bind(this, "listening"),
3356
+ error: this.emit.bind(this, "error"),
3357
+ upgrade: (req, socket, head) => {
3358
+ this.handleUpgrade(req, socket, head, emitConnection);
3359
+ }
3360
+ });
3361
+ }
3362
+ if (options.perMessageDeflate === true) options.perMessageDeflate = {};
3363
+ if (options.clientTracking) {
3364
+ this.clients = /* @__PURE__ */ new Set();
3365
+ this._shouldEmitClose = false;
3366
+ }
3367
+ this.options = options;
3368
+ this._state = RUNNING;
3369
+ }
3370
+ /**
3371
+ * Returns the bound address, the address family name, and port of the server
3372
+ * as reported by the operating system if listening on an IP socket.
3373
+ * If the server is listening on a pipe or UNIX domain socket, the name is
3374
+ * returned as a string.
3375
+ *
3376
+ * @return {(Object|String|null)} The address of the server
3377
+ * @public
3378
+ */
3379
+ address() {
3380
+ if (this.options.noServer) {
3381
+ throw new Error('The server is operating in "noServer" mode');
3382
+ }
3383
+ if (!this._server) return null;
3384
+ return this._server.address();
3385
+ }
3386
+ /**
3387
+ * Stop the server from accepting new connections and emit the `'close'` event
3388
+ * when all existing connections are closed.
3389
+ *
3390
+ * @param {Function} [cb] A one-time listener for the `'close'` event
3391
+ * @public
3392
+ */
3393
+ close(cb) {
3394
+ if (this._state === CLOSED) {
3395
+ if (cb) {
3396
+ this.once("close", () => {
3397
+ cb(new Error("The server is not running"));
3398
+ });
3399
+ }
3400
+ process.nextTick(emitClose, this);
3401
+ return;
3402
+ }
3403
+ if (cb) this.once("close", cb);
3404
+ if (this._state === CLOSING) return;
3405
+ this._state = CLOSING;
3406
+ if (this.options.noServer || this.options.server) {
3407
+ if (this._server) {
3408
+ this._removeListeners();
3409
+ this._removeListeners = this._server = null;
3410
+ }
3411
+ if (this.clients) {
3412
+ if (!this.clients.size) {
3413
+ process.nextTick(emitClose, this);
3414
+ } else {
3415
+ this._shouldEmitClose = true;
3416
+ }
3417
+ } else {
3418
+ process.nextTick(emitClose, this);
3419
+ }
3420
+ } else {
3421
+ const server = this._server;
3422
+ this._removeListeners();
3423
+ this._removeListeners = this._server = null;
3424
+ server.close(() => {
3425
+ emitClose(this);
3426
+ });
3427
+ }
3428
+ }
3429
+ /**
3430
+ * See if a given request should be handled by this server instance.
3431
+ *
3432
+ * @param {http.IncomingMessage} req Request object to inspect
3433
+ * @return {Boolean} `true` if the request is valid, else `false`
3434
+ * @public
3435
+ */
3436
+ shouldHandle(req) {
3437
+ if (this.options.path) {
3438
+ const index = req.url.indexOf("?");
3439
+ const pathname = index !== -1 ? req.url.slice(0, index) : req.url;
3440
+ if (pathname !== this.options.path) return false;
3441
+ }
3442
+ return true;
3443
+ }
3444
+ /**
3445
+ * Handle a HTTP Upgrade request.
3446
+ *
3447
+ * @param {http.IncomingMessage} req The request object
3448
+ * @param {Duplex} socket The network socket between the server and client
3449
+ * @param {Buffer} head The first packet of the upgraded stream
3450
+ * @param {Function} cb Callback
3451
+ * @public
3452
+ */
3453
+ handleUpgrade(req, socket, head, cb) {
3454
+ socket.on("error", socketOnError);
3455
+ const key = req.headers["sec-websocket-key"];
3456
+ const upgrade = req.headers.upgrade;
3457
+ const version = +req.headers["sec-websocket-version"];
3458
+ if (req.method !== "GET") {
3459
+ const message = "Invalid HTTP method";
3460
+ abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);
3461
+ return;
3462
+ }
3463
+ if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
3464
+ const message = "Invalid Upgrade header";
3465
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3466
+ return;
3467
+ }
3468
+ if (key === void 0 || !keyRegex.test(key)) {
3469
+ const message = "Missing or invalid Sec-WebSocket-Key header";
3470
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3471
+ return;
3472
+ }
3473
+ if (version !== 13 && version !== 8) {
3474
+ const message = "Missing or invalid Sec-WebSocket-Version header";
3475
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message, {
3476
+ "Sec-WebSocket-Version": "13, 8"
3477
+ });
3478
+ return;
3479
+ }
3480
+ if (!this.shouldHandle(req)) {
3481
+ abortHandshake(socket, 400);
3482
+ return;
3483
+ }
3484
+ const secWebSocketProtocol = req.headers["sec-websocket-protocol"];
3485
+ let protocols = /* @__PURE__ */ new Set();
3486
+ if (secWebSocketProtocol !== void 0) {
3487
+ try {
3488
+ protocols = subprotocol2.parse(secWebSocketProtocol);
3489
+ } catch (err) {
3490
+ const message = "Invalid Sec-WebSocket-Protocol header";
3491
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3492
+ return;
3493
+ }
3494
+ }
3495
+ const secWebSocketExtensions = req.headers["sec-websocket-extensions"];
3496
+ const extensions = {};
3497
+ if (this.options.perMessageDeflate && secWebSocketExtensions !== void 0) {
3498
+ const perMessageDeflate = new PerMessageDeflate2({
3499
+ ...this.options.perMessageDeflate,
3500
+ isServer: true,
3501
+ maxPayload: this.options.maxPayload
3502
+ });
3503
+ try {
3504
+ const offers = extension2.parse(secWebSocketExtensions);
3505
+ if (offers[PerMessageDeflate2.extensionName]) {
3506
+ perMessageDeflate.accept(offers[PerMessageDeflate2.extensionName]);
3507
+ extensions[PerMessageDeflate2.extensionName] = perMessageDeflate;
3508
+ }
3509
+ } catch (err) {
3510
+ const message = "Invalid or unacceptable Sec-WebSocket-Extensions header";
3511
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3512
+ return;
3513
+ }
3514
+ }
3515
+ if (this.options.verifyClient) {
3516
+ const info = {
3517
+ origin: req.headers[`${version === 8 ? "sec-websocket-origin" : "origin"}`],
3518
+ secure: !!(req.socket.authorized || req.socket.encrypted),
3519
+ req
3520
+ };
3521
+ if (this.options.verifyClient.length === 2) {
3522
+ this.options.verifyClient(info, (verified, code, message, headers) => {
3523
+ if (!verified) {
3524
+ return abortHandshake(socket, code || 401, message, headers);
3525
+ }
3526
+ this.completeUpgrade(
3527
+ extensions,
3528
+ key,
3529
+ protocols,
3530
+ req,
3531
+ socket,
3532
+ head,
3533
+ cb
3534
+ );
3535
+ });
3536
+ return;
3537
+ }
3538
+ if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);
3539
+ }
3540
+ this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
3541
+ }
3542
+ /**
3543
+ * Upgrade the connection to WebSocket.
3544
+ *
3545
+ * @param {Object} extensions The accepted extensions
3546
+ * @param {String} key The value of the `Sec-WebSocket-Key` header
3547
+ * @param {Set} protocols The subprotocols
3548
+ * @param {http.IncomingMessage} req The request object
3549
+ * @param {Duplex} socket The network socket between the server and client
3550
+ * @param {Buffer} head The first packet of the upgraded stream
3551
+ * @param {Function} cb Callback
3552
+ * @throws {Error} If called more than once with the same socket
3553
+ * @private
3554
+ */
3555
+ completeUpgrade(extensions, key, protocols, req, socket, head, cb) {
3556
+ if (!socket.readable || !socket.writable) return socket.destroy();
3557
+ if (socket[kWebSocket]) {
3558
+ throw new Error(
3559
+ "server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration"
3560
+ );
3561
+ }
3562
+ if (this._state > RUNNING) return abortHandshake(socket, 503);
3563
+ const digest = createHash("sha1").update(key + GUID).digest("base64");
3564
+ const headers = [
3565
+ "HTTP/1.1 101 Switching Protocols",
3566
+ "Upgrade: websocket",
3567
+ "Connection: Upgrade",
3568
+ `Sec-WebSocket-Accept: ${digest}`
3569
+ ];
3570
+ const ws = new this.options.WebSocket(null, void 0, this.options);
3571
+ if (protocols.size) {
3572
+ const protocol = this.options.handleProtocols ? this.options.handleProtocols(protocols, req) : protocols.values().next().value;
3573
+ if (protocol) {
3574
+ headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
3575
+ ws._protocol = protocol;
3576
+ }
3577
+ }
3578
+ if (extensions[PerMessageDeflate2.extensionName]) {
3579
+ const params = extensions[PerMessageDeflate2.extensionName].params;
3580
+ const value = extension2.format({
3581
+ [PerMessageDeflate2.extensionName]: [params]
3582
+ });
3583
+ headers.push(`Sec-WebSocket-Extensions: ${value}`);
3584
+ ws._extensions = extensions;
3585
+ }
3586
+ this.emit("headers", headers, req);
3587
+ socket.write(headers.concat("\r\n").join("\r\n"));
3588
+ socket.removeListener("error", socketOnError);
3589
+ ws.setSocket(socket, head, {
3590
+ allowSynchronousEvents: this.options.allowSynchronousEvents,
3591
+ maxPayload: this.options.maxPayload,
3592
+ skipUTF8Validation: this.options.skipUTF8Validation
3593
+ });
3594
+ if (this.clients) {
3595
+ this.clients.add(ws);
3596
+ ws.on("close", () => {
3597
+ this.clients.delete(ws);
3598
+ if (this._shouldEmitClose && !this.clients.size) {
3599
+ process.nextTick(emitClose, this);
3600
+ }
3601
+ });
3602
+ }
3603
+ cb(ws, req);
3604
+ }
3605
+ };
3606
+ module2.exports = WebSocketServer2;
3607
+ function addListeners(server, map) {
3608
+ for (const event of Object.keys(map)) server.on(event, map[event]);
3609
+ return function removeListeners() {
3610
+ for (const event of Object.keys(map)) {
3611
+ server.removeListener(event, map[event]);
3612
+ }
3613
+ };
3614
+ }
3615
+ function emitClose(server) {
3616
+ server._state = CLOSED;
3617
+ server.emit("close");
3618
+ }
3619
+ function socketOnError() {
3620
+ this.destroy();
3621
+ }
3622
+ function abortHandshake(socket, code, message, headers) {
3623
+ message = message || http.STATUS_CODES[code];
3624
+ headers = {
3625
+ Connection: "close",
3626
+ "Content-Type": "text/html",
3627
+ "Content-Length": Buffer.byteLength(message),
3628
+ ...headers
3629
+ };
3630
+ socket.once("finish", socket.destroy);
3631
+ socket.end(
3632
+ `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r
3633
+ ` + Object.keys(headers).map((h) => `${h}: ${headers[h]}`).join("\r\n") + "\r\n\r\n" + message
3634
+ );
3635
+ }
3636
+ function abortHandshakeOrEmitwsClientError(server, req, socket, code, message, headers) {
3637
+ if (server.listenerCount("wsClientError")) {
3638
+ const err = new Error(message);
3639
+ Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);
3640
+ server.emit("wsClientError", err, socket, req);
3641
+ } else {
3642
+ abortHandshake(socket, code, message, headers);
3643
+ }
3644
+ }
3645
+ }
3646
+ });
3647
+
3648
+ // index.ts
3649
+ var index_exports = {};
3650
+ __export(index_exports, {
3651
+ default: () => index_default,
3652
+ nexusPlugin: () => nexusPlugin
3653
+ });
3654
+ module.exports = __toCommonJS(index_exports);
3655
+ var import_core2 = require("openclaw/plugin-sdk/core");
3656
+
3657
+ // src/channel.ts
3658
+ var import_core = require("openclaw/plugin-sdk/core");
3659
+
3660
+ // src/config/schema.ts
3661
+ var DEFAULT_HUB2D_URL = "ws://111.231.105.183:3001";
3662
+ var DEFAULT_ROOM_ID = "general,boss,alpha";
3663
+ var DEFAULT_AGENT_NAME = "";
3664
+ var DEFAULT_LONG_TEXT = 4e3;
3665
+ var DEFAULT_GATEWAY_TIMEOUT_MS = 6e5;
3666
+ var DEFAULT_API_PORT = 3004;
3667
+ var DEFAULT_GATEWAY_PORT = 18789;
3668
+
3669
+ // src/config/resolve-config.ts
3670
+ function isNonEmptyString(value) {
3671
+ return typeof value === "string" && value.trim().length > 0;
3672
+ }
3673
+ function normalizeContextInjection(value) {
3674
+ if (!isNonEmptyString(value)) return "P0";
3675
+ const upper = value.toUpperCase();
3676
+ if (upper === "OFF" || upper === "FALSE") return "OFF";
3677
+ if (upper === "L0" || upper === "L1" || upper === "L2") return upper;
3678
+ return "P0";
3679
+ }
3680
+ function readChannelsConfig(cfg) {
3681
+ const channelsCfg = cfg?.channels?.["nexus-channel"] || cfg?.channels?.["nexus"];
3682
+ return channelsCfg && typeof channelsCfg === "object" ? channelsCfg : {};
3683
+ }
3684
+ function getMissingRequiredFields(config) {
3685
+ const missing = [];
3686
+ if (!isNonEmptyString(config.agentName)) missing.push("agentName");
3687
+ return missing;
3688
+ }
3689
+ function resolveNexusConfig(cfg) {
3690
+ const channelsCfg = readChannelsConfig(cfg);
3691
+ const hasConfig = Object.keys(channelsCfg).length > 0;
3692
+ const autoGatewayToken = channelsCfg.gatewayToken || cfg?.gateway?.auth?.token || void 0;
3693
+ const resolved = {
3694
+ enabled: channelsCfg.enabled ?? true,
3695
+ hub2dUrl: channelsCfg.hub2dUrl ?? DEFAULT_HUB2D_URL,
3696
+ roomId: channelsCfg.roomId ?? DEFAULT_ROOM_ID,
3697
+ agentName: channelsCfg.agentName ?? DEFAULT_AGENT_NAME,
3698
+ token: channelsCfg.token,
3699
+ // agent auth token
3700
+ nexusApiKey: channelsCfg.nexusApiKey,
3701
+ apiPort: channelsCfg.apiPort ?? DEFAULT_API_PORT,
3702
+ gatewayPort: channelsCfg.gatewayPort ?? DEFAULT_GATEWAY_PORT,
3703
+ gatewayToken: autoGatewayToken,
3704
+ gatewayTimeoutMs: channelsCfg.gatewayTimeoutMs ?? DEFAULT_GATEWAY_TIMEOUT_MS,
3705
+ longTextThreshold: channelsCfg.longTextThreshold ?? DEFAULT_LONG_TEXT,
3706
+ contextInjection: normalizeContextInjection(channelsCfg.contextInjection)
3707
+ };
3708
+ const missingFields = getMissingRequiredFields(resolved);
3709
+ const configured = hasConfig && missingFields.length === 0;
3710
+ return {
3711
+ ...resolved,
3712
+ __nexusMeta: {
3713
+ configSource: hasConfig ? "channels.nexus-channel" : "none",
3714
+ fallbackUsed: false,
3715
+ fallbackFields: [],
3716
+ sourceByField: hasConfig ? Object.fromEntries(Object.keys(channelsCfg).map((key) => [key, "channels.nexus-channel"])) : {},
3717
+ missingFields,
3718
+ configured,
3719
+ warnings: hasConfig ? [] : ["Nexus config not found at channels.nexus-channel."]
3720
+ }
3721
+ };
3722
+ }
3723
+
3724
+ // src/transport/resume-store.ts
3725
+ var fs = __toESM(require("fs"));
3726
+ var path = __toESM(require("path"));
3727
+
3728
+ // src/utils/env.ts
3729
+ var _env = typeof process !== "undefined" && process ? process.env : {};
3730
+ function getEnv(key) {
3731
+ return _env[key];
3732
+ }
3733
+ function getEnvOr(key, fallback) {
3734
+ return _env[key] || fallback;
3735
+ }
3736
+
3737
+ // src/transport/resume-store.ts
3738
+ var RESUME_TOKEN_PATH = path.join(
3739
+ getEnvOr("HOME", "~"),
3740
+ ".openclaw",
3741
+ "state",
3742
+ "nexus-resume.json"
3743
+ );
3744
+ function loadResumeTokens() {
3745
+ try {
3746
+ if (fs.existsSync(RESUME_TOKEN_PATH)) {
3747
+ const data = JSON.parse(fs.readFileSync(RESUME_TOKEN_PATH, "utf-8"));
3748
+ return data || {};
3749
+ }
3750
+ } catch (e) {
3751
+ console.error(`[nexus] Failed to load resume_tokens: ${e.message}`);
3752
+ }
3753
+ return {};
3754
+ }
3755
+ function saveResumeTokens(tokens) {
3756
+ try {
3757
+ const dir = path.dirname(RESUME_TOKEN_PATH);
3758
+ if (!fs.existsSync(dir)) {
3759
+ fs.mkdirSync(dir, { recursive: true });
3760
+ }
3761
+ fs.writeFileSync(RESUME_TOKEN_PATH, JSON.stringify(tokens, null, 2));
3762
+ } catch (e) {
3763
+ console.error(`[nexus] Failed to save resume_tokens: ${e.message}`);
3764
+ }
3765
+ }
3766
+ var flushTimer = null;
3767
+ var tokensDirty = false;
3768
+ var currentTokens = {};
3769
+ function initResumeTokenStore(initialTokens) {
3770
+ currentTokens = initialTokens || loadResumeTokens();
3771
+ tokensDirty = false;
3772
+ }
3773
+ function updateResumeToken(room, eventId) {
3774
+ currentTokens[room] = eventId;
3775
+ tokensDirty = true;
3776
+ if (!flushTimer) {
3777
+ flushTimer = setTimeout(() => {
3778
+ flushTimer = null;
3779
+ if (tokensDirty) {
3780
+ saveResumeTokens(currentTokens);
3781
+ tokensDirty = false;
3782
+ }
3783
+ }, 2e3);
3784
+ }
3785
+ }
3786
+ function getResumeTokens() {
3787
+ return { ...currentTokens };
3788
+ }
3789
+ function flushResumeTokens() {
3790
+ if (flushTimer) {
3791
+ clearTimeout(flushTimer);
3792
+ flushTimer = null;
3793
+ }
3794
+ if (tokensDirty) {
3795
+ saveResumeTokens(currentTokens);
3796
+ tokensDirty = false;
3797
+ }
3798
+ }
3799
+ function resetResumeTokenStore() {
3800
+ if (flushTimer) {
3801
+ clearTimeout(flushTimer);
3802
+ flushTimer = null;
3803
+ }
3804
+ currentTokens = {};
3805
+ tokensDirty = false;
3806
+ }
3807
+
3808
+ // node_modules/ws/wrapper.mjs
3809
+ var import_stream = __toESM(require_stream(), 1);
3810
+ var import_extension = __toESM(require_extension(), 1);
3811
+ var import_permessage_deflate = __toESM(require_permessage_deflate(), 1);
3812
+ var import_receiver = __toESM(require_receiver(), 1);
3813
+ var import_sender = __toESM(require_sender(), 1);
3814
+ var import_subprotocol = __toESM(require_subprotocol(), 1);
3815
+ var import_websocket = __toESM(require_websocket(), 1);
3816
+ var import_websocket_server = __toESM(require_websocket_server(), 1);
3817
+ var wrapper_default = import_websocket.default;
3818
+
3819
+ // src/transport/ws-client.ts
3820
+ var fs2 = __toESM(require("fs"));
3821
+ var path2 = __toESM(require("path"));
3822
+
3823
+ // src/transport/frames.ts
3824
+ function buildConnectFrame(params) {
3825
+ const frame = {
3826
+ type: "connect",
3827
+ node: params.node,
3828
+ rooms: params.rooms,
3829
+ resume_token: params.resumeToken || {},
3830
+ clientInfo: {
3831
+ openclawVersion: params.openclawVersion || "unknown",
3832
+ pluginVersion: params.pluginVersion || "unknown"
3833
+ }
3834
+ };
3835
+ if (params.token) {
3836
+ frame.token = params.token;
3837
+ }
3838
+ return frame;
3839
+ }
3840
+ function buildAckFrame(roomId, eventId) {
3841
+ return {
3842
+ type: "ack",
3843
+ room_id: roomId,
3844
+ event_id: eventId
3845
+ };
3846
+ }
3847
+ function buildReplyFrame(params) {
3848
+ return {
3849
+ type: "reply",
3850
+ event_id: params.eventId,
3851
+ room_id: params.roomId,
3852
+ from: params.from,
3853
+ to: params.to,
3854
+ text: params.text,
3855
+ content: params.text,
3856
+ status: params.status,
3857
+ blocks: []
3858
+ };
3859
+ }
3860
+ function buildSendFrame(params) {
3861
+ return {
3862
+ type: "send",
3863
+ room_id: params.roomId,
3864
+ text: params.text,
3865
+ client_msg_id: params.clientMsgId,
3866
+ mentions: params.mentions
3867
+ };
3868
+ }
3869
+
3870
+ // src/transport/reconnect.ts
3871
+ var MAX_RECONNECT_DELAY = 3e4;
3872
+ var BASE_RECONNECT_DELAY = 1e3;
3873
+ function createReconnectState() {
3874
+ return {
3875
+ currentDelay: BASE_RECONNECT_DELAY,
3876
+ connId: 0
3877
+ };
3878
+ }
3879
+ function scheduleReconnect(state, callback) {
3880
+ const jitter = Math.floor(Math.random() * 250);
3881
+ const delay = state.currentDelay + jitter;
3882
+ const timer = setTimeout(() => {
3883
+ callback();
3884
+ }, delay);
3885
+ state.currentDelay = Math.min(state.currentDelay * 2, MAX_RECONNECT_DELAY);
3886
+ return { delay, timer };
3887
+ }
3888
+ function resetReconnectDelay(state) {
3889
+ state.currentDelay = BASE_RECONNECT_DELAY;
3890
+ }
3891
+ function incrementConnId(state) {
3892
+ return ++state.connId;
3893
+ }
3894
+ function isStaleConnection(state, connId) {
3895
+ return connId !== state.connId;
3896
+ }
3897
+
3898
+ // src/transport/ws-client.ts
3899
+ var MAX_OUTBOX_SIZE = 100;
3900
+ var IDLE_TIMEOUT_MS = 9e4;
3901
+ var IDLE_CHECK_INTERVAL_MS = 3e4;
3902
+ var WSClient = class {
3903
+ constructor(config) {
3904
+ this.ws = null;
3905
+ this.reconnectTimer = null;
3906
+ // Client-side liveness tracking
3907
+ this.lastFrameAt = 0;
3908
+ this.idleCheckTimer = null;
3909
+ // Outbound message queue
3910
+ this.outbox = [];
3911
+ this.config = config;
3912
+ this.reconnectState = createReconnectState();
3913
+ this.state = { connected: false };
3914
+ }
3915
+ connect() {
3916
+ const myConnId = incrementConnId(this.reconnectState);
3917
+ if (this.ws) {
3918
+ try {
3919
+ this.ws.close();
3920
+ } catch {
3921
+ }
3922
+ this.ws = null;
3923
+ }
3924
+ this.stopIdleCheck();
3925
+ console.log(`[nexus] WS connecting: ${this.config.hub2dUrl} rooms=${this.config.rooms.join(",")}`);
3926
+ this.ws = new wrapper_default(this.config.hub2dUrl);
3927
+ this.ws.on("open", () => {
3928
+ this.sendConnectFrame();
3929
+ });
3930
+ this.ws.on("message", (data) => {
3931
+ this.lastFrameAt = Date.now();
3932
+ this.handleMessage(data);
3933
+ });
3934
+ this.ws.on("close", (code, reason) => {
3935
+ this.handleClose(code, reason, myConnId);
3936
+ });
3937
+ this.ws.on("error", (error) => {
3938
+ console.error(`[nexus] WS error: ${error.message}`);
3939
+ });
3940
+ this.lastFrameAt = Date.now();
3941
+ this.startIdleCheck();
3942
+ }
3943
+ sendConnectFrame() {
3944
+ const frame = buildConnectFrame({
3945
+ node: this.config.agentName,
3946
+ rooms: this.config.rooms,
3947
+ resumeToken: getResumeTokens(),
3948
+ token: this.config.token,
3949
+ openclawVersion: getEnv("OPENCLAW_SERVICE_VERSION") || getEnv("OPENCLAW_VERSION") || "unknown",
3950
+ pluginVersion: this.readPluginVersion()
3951
+ });
3952
+ this.ws?.send(JSON.stringify(frame));
3953
+ console.log("[nexus] WS open, connect frame sent");
3954
+ }
3955
+ readPluginVersion() {
3956
+ try {
3957
+ let dir = path2.resolve(__dirname, "..");
3958
+ for (let i = 0; i < 5 && dir; i++) {
3959
+ const pkgPath = path2.join(dir, "package.json");
3960
+ if (fs2.existsSync(pkgPath)) {
3961
+ const pkg = JSON.parse(fs2.readFileSync(pkgPath, "utf-8"));
3962
+ if (pkg.name === "nexus-channel" || pkg.name?.includes("nexus")) {
3963
+ return pkg.version || "unknown";
3964
+ }
3965
+ }
3966
+ dir = path2.dirname(dir);
3967
+ }
3968
+ return "unknown";
3969
+ } catch {
3970
+ return "unknown";
3971
+ }
3972
+ }
3973
+ // ── Idle detection (client-side liveness) ──────────────────────────────
3974
+ startIdleCheck() {
3975
+ this.stopIdleCheck();
3976
+ this.idleCheckTimer = setInterval(() => {
3977
+ if (!this.state.connected || !this.ws) return;
3978
+ const idle = Date.now() - this.lastFrameAt;
3979
+ if (idle > IDLE_TIMEOUT_MS) {
3980
+ console.warn(`[nexus] No frames received for ${Math.round(idle / 1e3)}s, terminating stale connection`);
3981
+ try {
3982
+ this.ws.terminate();
3983
+ } catch {
3984
+ }
3985
+ }
3986
+ }, IDLE_CHECK_INTERVAL_MS);
3987
+ }
3988
+ stopIdleCheck() {
3989
+ if (this.idleCheckTimer) {
3990
+ clearInterval(this.idleCheckTimer);
3991
+ this.idleCheckTimer = null;
3992
+ }
3993
+ }
3994
+ // ── Outbox (send queue for offline buffering) ─────────────────────────
3995
+ enqueueOutbox(type, frame) {
3996
+ const item = {
3997
+ frame: JSON.stringify(frame),
3998
+ type,
3999
+ enqueuedAt: Date.now()
4000
+ };
4001
+ this.outbox.push(item);
4002
+ if (this.outbox.length > MAX_OUTBOX_SIZE) {
4003
+ const dropped = this.outbox.shift();
4004
+ console.warn(`[nexus] Outbox full, dropping oldest ${dropped?.type} (age ${Math.round((Date.now() - (dropped?.enqueuedAt || 0)) / 1e3)}s)`);
4005
+ }
4006
+ }
4007
+ flushOutbox() {
4008
+ if (this.outbox.length === 0) return;
4009
+ const items = this.outbox.splice(0);
4010
+ console.log(`[nexus] Flushing outbox: ${items.length} queued messages`);
4011
+ for (const item of items) {
4012
+ if (this.ws?.readyState === wrapper_default.OPEN) {
4013
+ this.ws.send(item.frame);
4014
+ } else {
4015
+ this.outbox.push(item);
4016
+ console.warn(`[nexus] WS closed during outbox flush, ${this.outbox.length} items re-queued`);
4017
+ return;
4018
+ }
4019
+ }
4020
+ }
4021
+ // ── Message handling ──────────────────────────────────────────────────
4022
+ handleMessage(data) {
4023
+ let frame;
4024
+ try {
4025
+ frame = JSON.parse(typeof data === "string" ? data : data.toString());
4026
+ } catch {
4027
+ console.error("[nexus] WS bad JSON, ignoring");
4028
+ return;
4029
+ }
4030
+ switch (frame.type) {
4031
+ case "connected": {
4032
+ const connectedFrame = frame;
4033
+ resetReconnectDelay(this.reconnectState);
4034
+ this.state.connected = true;
4035
+ this.state.pendingApproval = false;
4036
+ if (typeof connectedFrame.user_id === "number") {
4037
+ this.state.userId = connectedFrame.user_id;
4038
+ }
4039
+ console.log(
4040
+ `[nexus] WS connected: user_id=${this.state.userId} backlog_count=${JSON.stringify(connectedFrame.backlog_count || {})}`
4041
+ );
4042
+ this.flushOutbox();
4043
+ this.config.onConnected?.(connectedFrame);
4044
+ break;
4045
+ }
4046
+ case "event":
4047
+ this.config.onEvent?.(frame);
4048
+ break;
4049
+ case "ping":
4050
+ this.ws?.send(JSON.stringify({ type: "pong", ts: Date.now() }));
4051
+ break;
4052
+ case "error": {
4053
+ const errorFrame = frame;
4054
+ this.state.lastError = {
4055
+ code: errorFrame.code || "UNKNOWN",
4056
+ message: errorFrame.message || JSON.stringify(frame),
4057
+ ts: Date.now()
4058
+ };
4059
+ if (errorFrame.code === "PENDING_APPROVAL") {
4060
+ this.state.pendingApproval = true;
4061
+ console.warn(
4062
+ `[nexus] Agent pending approval: node=${this.config.agentName}. An admin must approve this agent in the Nexus UI before connecting. Will retry with reduced frequency.`
4063
+ );
4064
+ }
4065
+ console.error(`[nexus] Server error: code=${this.state.lastError.code} msg=${this.state.lastError.message}`);
4066
+ this.config.onError?.(errorFrame);
4067
+ break;
4068
+ }
4069
+ default:
4070
+ break;
4071
+ }
4072
+ }
4073
+ handleClose(code, reason, myConnId) {
4074
+ console.log(`[nexus] WS closed: code=${code} reason=${reason.toString() || "none"} connId=${myConnId}/${this.reconnectState.connId}`);
4075
+ this.state.connected = false;
4076
+ this.stopIdleCheck();
4077
+ flushResumeTokens();
4078
+ if (this.state.pendingApproval && code !== 4003) {
4079
+ this.state.pendingApproval = false;
4080
+ resetReconnectDelay(this.reconnectState);
4081
+ }
4082
+ if (!isStaleConnection(this.reconnectState, myConnId)) {
4083
+ this.scheduleReconnect();
4084
+ } else {
4085
+ console.log("[nexus] WS close from stale connection, skipping reconnect");
4086
+ }
4087
+ this.config.onClose?.();
4088
+ }
4089
+ scheduleReconnect() {
4090
+ if (this.reconnectTimer) {
4091
+ clearTimeout(this.reconnectTimer);
4092
+ }
4093
+ const PENDING_BASE_DELAY = 6e4;
4094
+ const PENDING_MAX_DELAY = 3e5;
4095
+ if (this.state.pendingApproval) {
4096
+ const jitter = Math.floor(Math.random() * 5e3);
4097
+ const delay = Math.min(
4098
+ Math.max(this.reconnectState.currentDelay, PENDING_BASE_DELAY) + jitter,
4099
+ PENDING_MAX_DELAY
4100
+ );
4101
+ this.reconnectTimer = setTimeout(() => {
4102
+ this.connect();
4103
+ }, delay);
4104
+ console.log(`[nexus] Reconnecting in ${Math.round(delay / 1e3)}s (pending approval)`);
4105
+ } else {
4106
+ const { delay, timer } = scheduleReconnect(this.reconnectState, () => {
4107
+ this.connect();
4108
+ });
4109
+ this.reconnectTimer = timer;
4110
+ console.log(`[nexus] Reconnecting in ${delay}ms`);
4111
+ }
4112
+ }
4113
+ sendAck(roomId, eventId) {
4114
+ const frame = buildAckFrame(roomId, eventId);
4115
+ if (this.ws?.readyState === wrapper_default.OPEN) {
4116
+ this.ws.send(JSON.stringify(frame));
4117
+ } else {
4118
+ this.enqueueOutbox("ack", frame);
4119
+ }
4120
+ }
4121
+ sendReply(eventId, roomId, to, text, status) {
4122
+ const frame = buildReplyFrame({
4123
+ eventId,
4124
+ roomId,
4125
+ from: this.config.agentName,
4126
+ to,
4127
+ text,
4128
+ status
4129
+ });
4130
+ if (this.ws?.readyState === wrapper_default.OPEN) {
4131
+ this.ws.send(JSON.stringify(frame));
4132
+ } else {
4133
+ this.enqueueOutbox("reply", frame);
4134
+ console.warn(`[nexus] WS not open, queued reply (event_id=${eventId})`);
4135
+ }
4136
+ }
4137
+ sendMessage(roomId, text, mentions, clientMsgId) {
4138
+ const frame = buildSendFrame({
4139
+ roomId,
4140
+ text,
4141
+ mentions,
4142
+ clientMsgId
4143
+ });
4144
+ if (this.ws?.readyState === wrapper_default.OPEN) {
4145
+ this.ws.send(JSON.stringify(frame));
4146
+ } else {
4147
+ this.enqueueOutbox("send", frame);
4148
+ console.warn("[nexus] WS not open, queued message");
4149
+ }
4150
+ }
4151
+ getState() {
4152
+ return { ...this.state };
4153
+ }
4154
+ isConnected() {
4155
+ return this.state.connected;
4156
+ }
4157
+ getUserId() {
4158
+ return this.state.userId;
4159
+ }
4160
+ getOutboxSize() {
4161
+ return this.outbox.length;
4162
+ }
4163
+ close() {
4164
+ if (this.reconnectTimer) {
4165
+ clearTimeout(this.reconnectTimer);
4166
+ this.reconnectTimer = null;
4167
+ }
4168
+ this.stopIdleCheck();
4169
+ if (this.ws) {
4170
+ try {
4171
+ this.ws.close();
4172
+ } catch {
4173
+ }
4174
+ this.ws = null;
4175
+ }
4176
+ flushResumeTokens();
4177
+ this.state.connected = false;
4178
+ }
4179
+ };
4180
+
4181
+ // src/gateway/chat-client.ts
4182
+ var RETRYABLE_STATUS_CODES = /* @__PURE__ */ new Set([429, 502, 503, 504]);
4183
+ var MAX_RETRIES = 3;
4184
+ var BASE_DELAY_MS = 3e3;
4185
+ var GatewayRequestError = class extends Error {
4186
+ constructor(message, code, status) {
4187
+ super(message);
4188
+ this.name = "GatewayRequestError";
4189
+ this.code = code;
4190
+ this.status = status;
4191
+ }
4192
+ };
4193
+ async function callGateway(messages, user, config) {
4194
+ const port = config.port ?? 18789;
4195
+ const token = config.token ?? "";
4196
+ const timeoutMs = config.timeoutMs ?? 6e5;
4197
+ const url = `http://127.0.0.1:${port}/v1/chat/completions`;
4198
+ const headers = { "Content-Type": "application/json" };
4199
+ if (token) headers.Authorization = `Bearer ${token}`;
4200
+ const controller = new AbortController();
4201
+ const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
4202
+ const startTime = Date.now();
4203
+ try {
4204
+ const resp = await fetch(url, {
4205
+ method: "POST",
4206
+ headers,
4207
+ body: JSON.stringify({
4208
+ model: "openclaw",
4209
+ messages,
4210
+ stream: false,
4211
+ user
4212
+ }),
4213
+ signal: controller.signal
4214
+ });
4215
+ const latencyMs = Date.now() - startTime;
4216
+ if (!resp.ok) {
4217
+ const errText = await resp.text().catch(() => "(no body)");
4218
+ throw new GatewayRequestError(
4219
+ `Gateway Error ${resp.status}: ${errText.slice(0, 100)}`,
4220
+ `HTTP_${resp.status}`,
4221
+ resp.status
4222
+ );
4223
+ }
4224
+ const data = await resp.json();
4225
+ const content = data?.choices?.[0]?.message?.content || "(no reply)";
4226
+ return { content, latencyMs };
4227
+ } catch (error) {
4228
+ if (error?.name === "AbortError") {
4229
+ throw new GatewayRequestError(`Gateway timeout after ${timeoutMs}ms`, "TIMEOUT");
4230
+ }
4231
+ if (error instanceof GatewayRequestError) {
4232
+ throw error;
4233
+ }
4234
+ throw new GatewayRequestError(error?.message || "Gateway request failed", "FETCH_ERROR");
4235
+ } finally {
4236
+ clearTimeout(timeoutId);
4237
+ }
4238
+ }
4239
+ function isRetryableGatewayError(error) {
4240
+ if (!(error instanceof GatewayRequestError)) return false;
4241
+ return typeof error.status === "number" && RETRYABLE_STATUS_CODES.has(error.status);
4242
+ }
4243
+ async function callGatewayWithRetry(messages, user, config, maxRetries = MAX_RETRIES) {
4244
+ let lastError;
4245
+ let totalWaitMs = 0;
4246
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
4247
+ try {
4248
+ return await callGateway(messages, user, config);
4249
+ } catch (error) {
4250
+ if (!(error instanceof GatewayRequestError)) {
4251
+ throw error;
4252
+ }
4253
+ lastError = error;
4254
+ if (attempt < maxRetries && isRetryableGatewayError(error)) {
4255
+ const delay = BASE_DELAY_MS * Math.pow(2, attempt) + Math.round(Math.random() * 1e3);
4256
+ totalWaitMs += delay;
4257
+ console.log(`[nexus] Gateway retry ${attempt + 1}/${maxRetries} after ${delay}ms (code=${error.code})`);
4258
+ await new Promise((resolve2) => setTimeout(resolve2, delay));
4259
+ continue;
4260
+ }
4261
+ error.retries = attempt;
4262
+ error.totalWaitMs = totalWaitMs;
4263
+ throw error;
4264
+ }
4265
+ }
4266
+ if (!lastError) {
4267
+ throw new GatewayRequestError("Gateway request failed", "FETCH_ERROR");
4268
+ }
4269
+ lastError.retries = maxRetries;
4270
+ lastError.totalWaitMs = totalWaitMs;
4271
+ throw lastError;
4272
+ }
4273
+
4274
+ // src/hub/api-client.ts
4275
+ function normalizeHub2dHttpBase(hub2dUrl, apiPort) {
4276
+ const wsUrl = hub2dUrl.startsWith("ws") ? hub2dUrl : hub2dUrl.replace(/^http/, "ws");
4277
+ const parsed = new URL(wsUrl);
4278
+ return `http://${parsed.hostname}:${apiPort}`;
4279
+ }
4280
+ function buildAuthHeaders(config) {
4281
+ const headers = {};
4282
+ const apiKey = config.nexusApiKey ?? getEnv("NEXUS_API_KEY") ?? "";
4283
+ if (apiKey) {
4284
+ headers["x-api-key"] = apiKey;
4285
+ }
4286
+ return headers;
4287
+ }
4288
+
4289
+ // src/hub/context.ts
4290
+ var CONTEXT_INJECTION_TTL_MS = 6e4;
4291
+ var CONTEXT_MAX_CHARS = 2e3;
4292
+ var contextCache = /* @__PURE__ */ new Map();
4293
+ async function fetchNexusContext(roomId, hub2dUrl, config) {
4294
+ const mode = config.contextInjection ?? "P0";
4295
+ if (mode === "OFF") return "";
4296
+ const agentName = config.agentName || "unknown";
4297
+ const cacheKey = `${roomId}:${agentName}`;
4298
+ const cached = contextCache.get(cacheKey);
4299
+ if (cached && Date.now() - cached.fetchedAt < CONTEXT_INJECTION_TTL_MS) {
4300
+ return cached.content;
4301
+ }
4302
+ try {
4303
+ const apiBase = normalizeHub2dHttpBase(hub2dUrl, config.apiPort ?? DEFAULT_API_PORT);
4304
+ const headers = buildAuthHeaders(config);
4305
+ const url = `${apiBase}/api/context/inject?room_id=${encodeURIComponent(roomId)}&level=P0&node=${encodeURIComponent(agentName)}`;
4306
+ const resp = await fetch(url, { headers, signal: AbortSignal.timeout(5e3) });
4307
+ if (!resp.ok) {
4308
+ console.error(`[nexus] context API error: ${resp.status}`);
4309
+ return "";
4310
+ }
4311
+ const data = await resp.json();
4312
+ if (!data?.enabled || !Array.isArray(data.items) || data.items.length === 0) {
4313
+ return "";
4314
+ }
4315
+ const lines = data.items.map((item) => {
4316
+ const sender = item.from || item.human_id || item.sender || "unknown";
4317
+ return `[${sender}] ${item.content}`;
4318
+ });
4319
+ let contentBody = lines.join("\n");
4320
+ if (contentBody.length > CONTEXT_MAX_CHARS) {
4321
+ contentBody = `${contentBody.slice(0, CONTEXT_MAX_CHARS)}
4322
+ [TRUNCATED context_too_long]`;
4323
+ }
4324
+ const content = `[Room Context: latest ${data.items.length} msgs]
4325
+ ${contentBody}
4326
+ [End Context]
4327
+
4328
+ `;
4329
+ contextCache.set(cacheKey, { content, fetchedAt: Date.now() });
4330
+ return content;
4331
+ } catch (error) {
4332
+ console.error(`[nexus] context fetch failed: ${error.message}`);
4333
+ return "";
4334
+ }
4335
+ }
4336
+
4337
+ // src/runtime/event-handler.ts
4338
+ var STALE_MESSAGE_TTL_MS = 20 * 60 * 1e3;
4339
+ function getEventTimestamp(eventId) {
4340
+ const ts = parseInt(eventId.split("-")[0], 10);
4341
+ return Number.isNaN(ts) ? 0 : ts;
4342
+ }
4343
+ function getEventDecision(params) {
4344
+ const { event, config, selfUserId, isRecent: isRecent2 } = params;
4345
+ const agentName = config.agentName || DEFAULT_AGENT_NAME;
4346
+ if (event.from === agentName) return "skip-own";
4347
+ const eventTs = getEventTimestamp(event.event_id);
4348
+ const ageMs = Date.now() - eventTs;
4349
+ if (eventTs > 0 && ageMs > STALE_MESSAGE_TTL_MS) return "skip-stale";
4350
+ const toActorIds = event.to_actor_ids || [];
4351
+ if (toActorIds.length > 0 && (selfUserId === void 0 || !toActorIds.includes(selfUserId))) {
4352
+ return "skip-actor-gate";
4353
+ }
4354
+ const mentions = event.mentions || [];
4355
+ if (toActorIds.length === 0 && mentions.length > 0 && !mentions.includes(agentName)) {
4356
+ return "skip-mention-gate";
4357
+ }
4358
+ if (isRecent2(event.event_id)) return "skip-duplicate";
4359
+ return "process";
4360
+ }
4361
+ function buildEventPrompt(event, config) {
4362
+ const threshold = config.longTextThreshold || DEFAULT_LONG_TEXT;
4363
+ const from = event.from || "unknown";
4364
+ let content = event.text || "";
4365
+ if (content.length > threshold) {
4366
+ content = `${content.slice(0, threshold)} [TRUNCATED orig_len=${event.text.length} kept=${threshold}]`;
4367
+ }
4368
+ if (Array.isArray(event.attachments) && event.attachments.length > 0) {
4369
+ const attLines = event.attachments.map((att) => {
4370
+ const parts = [`[\u9644\u4EF6:${att.type || "file"}] ${att.name || "unknown"}`];
4371
+ if (att.size) parts.push(`${Math.round(att.size / 1024)}KB`);
4372
+ if (att.width && att.height) parts.push(`${att.width}\xD7${att.height}`);
4373
+ return parts.join(" ");
4374
+ });
4375
+ content += `
4376
+ ${attLines.join("\n")}`;
4377
+ }
4378
+ return `[from: ${from}] ${content}`;
4379
+ }
4380
+ function parseSessionDirectives(rawText) {
4381
+ let text = rawText;
4382
+ let sessionKey = null;
4383
+ let sessionReset = false;
4384
+ const keyMatch = text.match(/\[SESSION_KEY:([^\]]+)\]/);
4385
+ if (keyMatch) {
4386
+ sessionKey = keyMatch[1];
4387
+ text = text.replace(/\[SESSION_KEY:[^\]]+\]\n?/, "");
4388
+ }
4389
+ if (text.includes("[SESSION_RESET]")) {
4390
+ sessionReset = true;
4391
+ text = text.replace(/\[SESSION_RESET\]\n?/, "");
4392
+ }
4393
+ return { text: text.trim(), sessionKey, sessionReset };
4394
+ }
4395
+ async function processEvent(params) {
4396
+ const { event, config, selfUserId, isRecent: isRecent2, markRecent: markRecent2, gatewayConfig, sendReply, sendAck, updateResumeToken: updateResumeToken2 } = params;
4397
+ const decision = getEventDecision({ event, config, selfUserId, isRecent: isRecent2 });
4398
+ const roomId = event.room_id || DEFAULT_ROOM_ID;
4399
+ if (decision !== "process") {
4400
+ if (decision !== "skip-own" && decision !== "skip-duplicate") {
4401
+ sendAck(roomId, event.event_id);
4402
+ updateResumeToken2(roomId, event.event_id);
4403
+ }
4404
+ return decision;
4405
+ }
4406
+ markRecent2(event.event_id);
4407
+ try {
4408
+ const { text: cleanedText, sessionKey: overrideKey, sessionReset } = parseSessionDirectives(event.text || "");
4409
+ const cleanedEvent = { ...event, text: cleanedText };
4410
+ let prompt = buildEventPrompt(cleanedEvent, config);
4411
+ const hub2dUrl = config.hub2dUrl || "ws://127.0.0.1:3001";
4412
+ const context = await fetchNexusContext(roomId, hub2dUrl, config);
4413
+ if (context) {
4414
+ prompt = `${context}${prompt}`;
4415
+ }
4416
+ const sessionKey = overrideKey || `nexus:${roomId}`;
4417
+ if (sessionReset) {
4418
+ try {
4419
+ await callGatewayWithRetry(
4420
+ [{ role: "user", content: "/new" }],
4421
+ sessionKey,
4422
+ gatewayConfig
4423
+ );
4424
+ console.log(`[nexus] Session reset: key=${sessionKey}`);
4425
+ } catch (resetErr) {
4426
+ console.warn(`[nexus] Session reset failed for ${sessionKey}:`, resetErr);
4427
+ }
4428
+ sendAck(roomId, event.event_id);
4429
+ updateResumeToken2(roomId, event.event_id);
4430
+ return "skip-reset";
4431
+ }
4432
+ const response = await callGatewayWithRetry([{ role: "user", content: prompt }], sessionKey, gatewayConfig);
4433
+ sendReply(event.event_id, roomId, event.from || "unknown", response.content, "done");
4434
+ sendAck(roomId, event.event_id);
4435
+ updateResumeToken2(roomId, event.event_id);
4436
+ return "process";
4437
+ } catch (error) {
4438
+ sendReply(
4439
+ event.event_id,
4440
+ roomId,
4441
+ event.from || "unknown",
4442
+ `[ERROR] ${error.code || "unknown_error"}: ${String(error.message || "").slice(0, 200)}`,
4443
+ "error"
4444
+ );
4445
+ sendAck(roomId, event.event_id);
4446
+ updateResumeToken2(roomId, event.event_id);
4447
+ return "process";
4448
+ }
4449
+ }
4450
+
4451
+ // src/runtime/outbound.ts
4452
+ var KNOWN_ROOMS = [
4453
+ { kind: "group", id: "general", name: "General" },
4454
+ { kind: "group", id: "boss", name: "Boss" },
4455
+ { kind: "group", id: "alpha", name: "Alpha" }
4456
+ ];
4457
+ var KNOWN_AGENTS = [
4458
+ { kind: "user", id: "serina", name: "Serina \u{1F4A0}" },
4459
+ { kind: "user", id: "cortana", name: "Cortana \u{1F90D}" },
4460
+ { kind: "user", id: "roland", name: "Roland \u{1F7E0}" },
4461
+ { kind: "user", id: "oracle", name: "Oracle \u{1F52E}" }
4462
+ ];
4463
+ var SILENT_PATTERNS = ["NO_REPLY", "HEARTBEAT_OK", "(no reply)"];
4464
+ function resolveOutboundTarget(to) {
4465
+ const room = KNOWN_ROOMS.find((item) => item.id === to || item.name.toLowerCase() === to.toLowerCase());
4466
+ if (room) return { ok: true, to: room.id };
4467
+ const agent = KNOWN_AGENTS.find((item) => item.id === to || item.name.toLowerCase().startsWith(to.toLowerCase()));
4468
+ if (agent) return { ok: true, to: agent.id };
4469
+ if (!to || !to.trim()) {
4470
+ return { ok: false, error: new Error("target required") };
4471
+ }
4472
+ return { ok: true, to };
4473
+ }
4474
+ function isResolvedOutboundTargetError(value) {
4475
+ return value.ok === false;
4476
+ }
4477
+ function createOutboundClient(config, sendMessage) {
4478
+ const agentName = config.agentName || DEFAULT_AGENT_NAME;
4479
+ const defaultRoom = (config.roomId || DEFAULT_ROOM_ID).split(",")[0].trim();
4480
+ return {
4481
+ async sendText(params) {
4482
+ if (!params.text.trim() || SILENT_PATTERNS.some((pattern) => params.text.trim().startsWith(pattern))) {
4483
+ return { channel: "nexus", messageId: `suppressed-${Date.now()}` };
4484
+ }
4485
+ const resolved = resolveOutboundTarget(params.to);
4486
+ if (isResolvedOutboundTargetError(resolved)) {
4487
+ throw resolved.error;
4488
+ }
4489
+ const isAgent = KNOWN_AGENTS.some((agent) => agent.id === resolved.to);
4490
+ const targetRoom = KNOWN_ROOMS.some((room) => room.id === resolved.to) ? resolved.to : defaultRoom;
4491
+ const mentions = isAgent && resolved.to !== agentName ? [resolved.to] : void 0;
4492
+ sendMessage(targetRoom, params.text, mentions, `out-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`);
4493
+ return { channel: "nexus", messageId: `out-${Date.now()}` };
4494
+ },
4495
+ async sendMedia(params) {
4496
+ const resolved = resolveOutboundTarget(params.to);
4497
+ if (isResolvedOutboundTargetError(resolved)) {
4498
+ throw resolved.error;
4499
+ }
4500
+ const targetRoom = KNOWN_ROOMS.some((room) => room.id === resolved.to) ? resolved.to : defaultRoom;
4501
+ const fallbackText = params.text || `[Media: ${params.mediaUrl || "unsupported"}]`;
4502
+ sendMessage(targetRoom, fallbackText, void 0, `media-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`);
4503
+ return { channel: "nexus", messageId: `media-${Date.now()}` };
4504
+ }
4505
+ };
4506
+ }
4507
+
4508
+ // src/runtime/directory.ts
4509
+ var KNOWN_ROOMS2 = [
4510
+ { kind: "group", id: "general", name: "General" },
4511
+ { kind: "group", id: "boss", name: "Boss" },
4512
+ { kind: "group", id: "alpha", name: "Alpha" }
4513
+ ];
4514
+ var KNOWN_AGENTS2 = [
4515
+ { kind: "user", id: "serina", name: "Serina \u{1F4A0}" },
4516
+ { kind: "user", id: "cortana", name: "Cortana \u{1F90D}" },
4517
+ { kind: "user", id: "roland", name: "Roland \u{1F7E0}" },
4518
+ { kind: "user", id: "oracle", name: "Oracle \u{1F52E}" }
4519
+ ];
4520
+ var directoryAdapter = {
4521
+ listGroups: async () => {
4522
+ return [...KNOWN_ROOMS2, ...KNOWN_AGENTS2.map((agent) => ({ ...agent, kind: "group" }))];
4523
+ },
4524
+ listPeers: async () => {
4525
+ return KNOWN_AGENTS2;
4526
+ }
4527
+ };
4528
+ var messagingAdapter = {
4529
+ targetResolver: {
4530
+ hint: "Use room name (general, boss) or agent name (serina, cortana, roland, oracle). Prefix with @ for agents.",
4531
+ looksLikeId: (raw) => {
4532
+ const lower = raw.toLowerCase().trim();
4533
+ return KNOWN_ROOMS2.some((room) => room.id === lower) || KNOWN_AGENTS2.some((agent) => agent.id === lower);
4534
+ }
4535
+ }
4536
+ };
4537
+
4538
+ // src/runtime/status.ts
4539
+ var defaultStatusSnapshot = {
4540
+ accountId: "default",
4541
+ enabled: true,
4542
+ configured: false,
4543
+ running: false,
4544
+ connected: false,
4545
+ lastConnectedAt: null,
4546
+ lastInboundAt: null,
4547
+ lastEventAt: null,
4548
+ lastError: null
4549
+ };
4550
+ var statusAdapter = {
4551
+ defaultRuntime: { ...defaultStatusSnapshot },
4552
+ buildChannelSummary: ({ snapshot }) => ({
4553
+ configured: Boolean(snapshot?.configured),
4554
+ linked: Boolean(snapshot?.connected),
4555
+ connected: Boolean(snapshot?.connected),
4556
+ running: Boolean(snapshot?.running),
4557
+ lastError: snapshot?.lastError ?? null,
4558
+ authAgeMs: typeof snapshot?.lastConnectedAt === "number" ? Math.max(0, Date.now() - snapshot.lastConnectedAt) : null
4559
+ }),
4560
+ buildAccountSnapshot: ({ account, runtime }) => {
4561
+ const meta2 = account?.__nexusMeta || { configured: false };
4562
+ return {
4563
+ accountId: account?.accountId || "default",
4564
+ name: account?.agentName || account?.accountId || "Nexus",
4565
+ enabled: account?.enabled ?? true,
4566
+ configured: Boolean(meta2.configured),
4567
+ running: runtime?.running ?? false,
4568
+ connected: runtime?.connected ?? false,
4569
+ lastConnectedAt: runtime?.lastConnectedAt ?? null,
4570
+ lastInboundAt: runtime?.lastInboundAt ?? null,
4571
+ lastEventAt: runtime?.lastEventAt ?? null,
4572
+ lastError: runtime?.lastError ?? null,
4573
+ meta: meta2,
4574
+ extra: {
4575
+ hub2dUrl: account?.hub2dUrl ?? null,
4576
+ roomId: account?.roomId ?? null,
4577
+ agentName: account?.agentName ?? null
4578
+ }
4579
+ };
4580
+ }
4581
+ };
4582
+
4583
+ // src/runtime/tools.ts
4584
+ var DispatchMessageSchema = {
4585
+ type: "object",
4586
+ properties: {
4587
+ target: { type: "string", description: "Agent name or room id to send to." },
4588
+ room_id: { type: "string", description: "Room ID to dispatch from." },
4589
+ text: { type: "string", description: "Message content." }
4590
+ },
4591
+ required: ["text"]
4592
+ };
4593
+ var GetRoomSummarySchema = {
4594
+ type: "object",
4595
+ properties: {
4596
+ room_id: { type: "string", description: "Room ID to query." },
4597
+ max_chars: { type: "number", minimum: 100, maximum: 5e3 }
4598
+ }
4599
+ };
4600
+ function createAgentTools(deps) {
4601
+ return [
4602
+ {
4603
+ name: "nexus_dispatch_message",
4604
+ description: "Dispatch a message to another agent or room in Nexus Hub.",
4605
+ schema: DispatchMessageSchema,
4606
+ ownerOnly: false,
4607
+ handler: async (args) => {
4608
+ const text = String(args?.text || "").trim();
4609
+ if (!text) return { content: "[ERROR] nexus_dispatch_message: text is required." };
4610
+ const cfg = deps.getConfig();
4611
+ const roomId = args?.room_id || (cfg.roomId || DEFAULT_ROOM_ID).split(",")[0].trim();
4612
+ const target = args?.target ? String(args.target) : void 0;
4613
+ const result = await deps.dispatchMessage(roomId, text, target);
4614
+ return { content: `[OK] Message dispatched. event_id=${result.event_id}` };
4615
+ }
4616
+ },
4617
+ {
4618
+ name: "nexus_get_room_summary",
4619
+ description: "Fetch recent room summary from Nexus Hub context API.",
4620
+ schema: GetRoomSummarySchema,
4621
+ ownerOnly: false,
4622
+ handler: async (args) => {
4623
+ const cfg = deps.getConfig();
4624
+ const roomId = args?.room_id || (cfg.roomId || DEFAULT_ROOM_ID).split(",")[0].trim();
4625
+ const maxChars = Number(args?.max_chars || 2e3);
4626
+ const hub2dUrl = cfg.hub2dUrl || "ws://127.0.0.1:3001";
4627
+ const context = await fetchNexusContext(roomId, hub2dUrl, cfg);
4628
+ if (!context) {
4629
+ return { content: `[INFO] No recent context available for room '${roomId}'.` };
4630
+ }
4631
+ const truncated = context.length > maxChars ? `${context.slice(0, maxChars)}
4632
+ [...truncated ${context.length - maxChars} chars]` : context;
4633
+ return { content: `## Room Summary: ${roomId}
4634
+
4635
+ ${truncated}` };
4636
+ }
4637
+ }
4638
+ ];
4639
+ }
4640
+
4641
+ // src/channel.ts
4642
+ var meta = {
4643
+ id: "nexus",
4644
+ label: "Nexus Hub 2.0",
4645
+ selectionLabel: "Nexus Hub (WebSocket)",
4646
+ detailLabel: "Nexus Hub 2.0",
4647
+ docsPath: "/channels/nexus",
4648
+ blurb: "Multi-agent hub with WS + persistence."
4649
+ };
4650
+ var currentConfig = {};
4651
+ var wsClient = null;
4652
+ var recentSet = /* @__PURE__ */ new Map();
4653
+ function isRecent(eventId) {
4654
+ return recentSet.has(eventId);
4655
+ }
4656
+ function markRecent(eventId) {
4657
+ recentSet.set(eventId, Date.now());
4658
+ if (recentSet.size > 1e4) {
4659
+ const entries = Array.from(recentSet.entries());
4660
+ for (const [key] of entries.slice(0, recentSet.size - 8e3)) {
4661
+ recentSet.delete(key);
4662
+ }
4663
+ }
4664
+ }
4665
+ async function dispatchMessage(roomId, text, target) {
4666
+ if (!wsClient || !wsClient.isConnected()) {
4667
+ throw new Error("Cannot dispatch message: WS not connected to hub2d");
4668
+ }
4669
+ const mentions = target ? [target] : void 0;
4670
+ const eventId = `dispatch-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
4671
+ wsClient.sendMessage(roomId, text, mentions, eventId);
4672
+ return { event_id: eventId };
4673
+ }
4674
+ var agentTools = createAgentTools({
4675
+ getConfig: () => currentConfig,
4676
+ dispatchMessage
4677
+ });
4678
+ var nexusPlugin = (0, import_core.createChatChannelPlugin)({
4679
+ base: {
4680
+ id: "nexus",
4681
+ meta,
4682
+ capabilities: {
4683
+ chatTypes: ["group"],
4684
+ reactions: false,
4685
+ threads: true,
4686
+ media: false,
4687
+ nativeCommands: false
4688
+ },
4689
+ reload: { configPrefixes: ["channels.nexus"] },
4690
+ configSchema: {
4691
+ schema: {
4692
+ type: "object",
4693
+ additionalProperties: false,
4694
+ properties: {
4695
+ enabled: { type: "boolean" },
4696
+ hub2dUrl: { type: "string" },
4697
+ roomId: { type: "string" },
4698
+ agentName: { type: "string" },
4699
+ token: { type: "string" },
4700
+ // agent auth token
4701
+ nexusApiKey: { type: "string" },
4702
+ apiPort: { type: "integer" },
4703
+ gatewayPort: { type: "integer" },
4704
+ gatewayToken: { type: "string" },
4705
+ gatewayTimeoutMs: { type: "integer" },
4706
+ longTextThreshold: { type: "integer" },
4707
+ contextInjection: { type: "string", enum: ["P0", "L0", "L1", "L2", "OFF"] }
4708
+ }
4709
+ },
4710
+ uiHints: {
4711
+ hub2dUrl: { label: "Hub2d WS URL", placeholder: "wss://your-hub.example.com/ws" },
4712
+ roomId: { label: "Room IDs (comma-separated)", placeholder: "general" },
4713
+ agentName: { label: "Agent Name", placeholder: "serina" },
4714
+ token: { label: "Agent Token", placeholder: "nagt_...", sensitive: true },
4715
+ nexusApiKey: { label: "Nexus API Key", placeholder: "nxk-...", sensitive: true },
4716
+ apiPort: { label: "Identity API Port", placeholder: "3004" },
4717
+ gatewayPort: { label: "Gateway Port", placeholder: "18789" },
4718
+ gatewayToken: { label: "Gateway Token", placeholder: "", sensitive: true },
4719
+ gatewayTimeoutMs: { label: "Gateway Timeout (ms)", placeholder: "120000" },
4720
+ longTextThreshold: { label: "Long Text Threshold (chars)", placeholder: "4000" },
4721
+ contextInjection: { label: "Nexus Context Mode", placeholder: "P0" }
4722
+ }
4723
+ },
4724
+ config: {
4725
+ listAccountIds: () => [import_core.DEFAULT_ACCOUNT_ID],
4726
+ defaultAccountId: () => import_core.DEFAULT_ACCOUNT_ID,
4727
+ resolveAccount: ((cfg) => resolveNexusConfig(cfg)),
4728
+ isConfigured: ((account) => Boolean(account?.__nexusMeta?.configured)),
4729
+ describeAccount: ((account) => ({
4730
+ accountId: account.accountId || import_core.DEFAULT_ACCOUNT_ID,
4731
+ name: account.agentName || "Nexus",
4732
+ enabled: account.enabled ?? true,
4733
+ configured: Boolean(account?.__nexusMeta?.configured),
4734
+ tokenSource: account?.__nexusMeta?.configSource || "channels.nexus"
4735
+ }))
4736
+ },
4737
+ agentTools,
4738
+ directory: directoryAdapter,
4739
+ messaging: messagingAdapter,
4740
+ status: statusAdapter,
4741
+ gateway: {
4742
+ startAccount: async (ctx) => {
4743
+ currentConfig = ctx.account || {};
4744
+ const resolved = {
4745
+ ...currentConfig,
4746
+ hub2dUrl: currentConfig.hub2dUrl || DEFAULT_HUB2D_URL,
4747
+ roomId: currentConfig.roomId || DEFAULT_ROOM_ID,
4748
+ agentName: currentConfig.agentName || DEFAULT_AGENT_NAME,
4749
+ gatewayPort: currentConfig.gatewayPort || DEFAULT_GATEWAY_PORT,
4750
+ gatewayTimeoutMs: currentConfig.gatewayTimeoutMs || DEFAULT_GATEWAY_TIMEOUT_MS
4751
+ };
4752
+ currentConfig = resolved;
4753
+ if (resolved.__nexusMeta?.configured === false) {
4754
+ const missing = resolved.__nexusMeta.missingFields.join(", ");
4755
+ throw new Error(`Nexus is not configured for account "${resolved.accountId || import_core.DEFAULT_ACCOUNT_ID}" (missing ${missing} in channels.nexus).`);
4756
+ }
4757
+ resetResumeTokenStore();
4758
+ initResumeTokenStore();
4759
+ const rooms = (resolved.roomId || DEFAULT_ROOM_ID).split(",").map((item) => item.trim()).filter(Boolean);
4760
+ wsClient = new WSClient({
4761
+ hub2dUrl: resolved.hub2dUrl || DEFAULT_HUB2D_URL,
4762
+ agentName: resolved.agentName || DEFAULT_AGENT_NAME,
4763
+ rooms,
4764
+ token: resolved.token,
4765
+ // pass auth token
4766
+ onConnected: () => {
4767
+ const snap = ctx.getStatus?.() || {};
4768
+ ctx.setStatus?.({ ...snap, running: true, connected: true, lastConnectedAt: Date.now() });
4769
+ },
4770
+ onEvent: async (event) => {
4771
+ await processEvent({
4772
+ event,
4773
+ config: resolved,
4774
+ selfUserId: wsClient?.getUserId(),
4775
+ isRecent,
4776
+ markRecent,
4777
+ gatewayConfig: {
4778
+ port: resolved.gatewayPort,
4779
+ token: resolved.gatewayToken,
4780
+ timeoutMs: resolved.gatewayTimeoutMs
4781
+ },
4782
+ sendReply: (eventId, roomId, to, text, status) => wsClient?.sendReply(eventId, roomId, to, text, status),
4783
+ sendAck: (roomId, eventId) => wsClient?.sendAck(roomId, eventId),
4784
+ updateResumeToken
4785
+ });
4786
+ },
4787
+ onError: (frame) => {
4788
+ const snap = ctx.getStatus?.() || {};
4789
+ ctx.setStatus?.({ ...snap, lastError: `${frame.code}: ${frame.message}` });
4790
+ },
4791
+ onClose: () => {
4792
+ const snap = ctx.getStatus?.() || {};
4793
+ ctx.setStatus?.({ ...snap, connected: false });
4794
+ }
4795
+ });
4796
+ wsClient.connect();
4797
+ await new Promise((resolve2) => {
4798
+ ctx.abortSignal?.addEventListener("abort", resolve2, { once: true });
4799
+ });
4800
+ },
4801
+ stopAccount: async () => {
4802
+ wsClient?.close();
4803
+ wsClient = null;
4804
+ }
4805
+ }
4806
+ },
4807
+ outbound: {
4808
+ base: {
4809
+ deliveryMode: "direct"
4810
+ },
4811
+ attachedResults: {
4812
+ channel: "nexus",
4813
+ sendText: async ({ to, text }) => {
4814
+ const outbound = createOutboundClient(currentConfig, (roomId, body, mentions, clientMsgId) => {
4815
+ wsClient?.sendMessage(roomId, body, mentions, clientMsgId);
4816
+ });
4817
+ const result = await outbound.sendText({ to, text });
4818
+ return {
4819
+ messageId: result.messageId
4820
+ };
4821
+ },
4822
+ sendMedia: async ({ to, text, mediaUrl }) => {
4823
+ const outbound = createOutboundClient(currentConfig, (roomId, body, mentions, clientMsgId) => {
4824
+ wsClient?.sendMessage(roomId, body, mentions, clientMsgId);
4825
+ });
4826
+ const result = await outbound.sendMedia({ to, text, mediaUrl });
4827
+ return {
4828
+ messageId: result.messageId
4829
+ };
4830
+ }
4831
+ }
4832
+ }
4833
+ });
4834
+
4835
+ // index.ts
4836
+ var index_default = (0, import_core2.defineChannelPluginEntry)({
4837
+ id: "nexus",
4838
+ name: "Nexus",
4839
+ description: "Nexus Hub 2.0 channel plugin for OpenClaw",
4840
+ plugin: nexusPlugin
4841
+ });
4842
+ // Annotate the CommonJS export names for ESM import in node:
4843
+ 0 && (module.exports = {
4844
+ nexusPlugin
13
4845
  });