@phenx-inc/ctlsurf 0.1.2 → 0.1.4

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