@kookapp/clawdbot-plugin 1.0.0 → 1.0.2

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