@principal-ai/control-tower-core 0.1.3 → 0.1.5

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