usebeeline 0.0.57 → 0.0.61

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 (2) hide show
  1. package/dist/usebeeline.mjs +4149 -169
  2. package/package.json +1 -1
@@ -6,6 +6,12 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
6
  var __getOwnPropNames = Object.getOwnPropertyNames;
7
7
  var __getProtoOf = Object.getPrototypeOf;
8
8
  var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
10
+ get: (a2, b) => (typeof require !== "undefined" ? require : a2)[b]
11
+ }) : x)(function(x) {
12
+ if (typeof require !== "undefined") return require.apply(this, arguments);
13
+ throw Error('Dynamic require of "' + x + '" is not supported');
14
+ });
9
15
  var __esm = (fn, res, err) => function __init() {
10
16
  if (err) throw err[0];
11
17
  try {
@@ -14,7 +20,7 @@ var __esm = (fn, res, err) => function __init() {
14
20
  throw err = [e], e;
15
21
  }
16
22
  };
17
- var __commonJS = (cb, mod3) => function __require() {
23
+ var __commonJS = (cb, mod3) => function __require2() {
18
24
  try {
19
25
  return mod3 || (0, cb[__getOwnPropNames(cb)[0]])((mod3 = { exports: {} }).exports, mod3), mod3.exports;
20
26
  } catch (e) {
@@ -93,80 +99,3750 @@ var require_src = __commonJS({
93
99
  clear += cursor3.left;
94
100
  return clear;
95
101
  }
96
- };
97
- module.exports = { cursor: cursor3, scroll, erase: erase3, beep };
102
+ };
103
+ module.exports = { cursor: cursor3, scroll, erase: erase3, beep };
104
+ }
105
+ });
106
+
107
+ // node_modules/picocolors/picocolors.js
108
+ var require_picocolors = __commonJS({
109
+ "node_modules/picocolors/picocolors.js"(exports, module) {
110
+ var p = process || {};
111
+ var argv = p.argv || [];
112
+ var env = p.env || {};
113
+ var isColorSupported = !(!!env.NO_COLOR || argv.includes("--no-color")) && (!!env.FORCE_COLOR || argv.includes("--color") || p.platform === "win32" || (p.stdout || {}).isTTY && env.TERM !== "dumb" || !!env.CI);
114
+ var formatter = (open2, close, replace = open2) => (input) => {
115
+ let string = "" + input, index = string.indexOf(close, open2.length);
116
+ return ~index ? open2 + replaceClose(string, close, replace, index) + close : open2 + string + close;
117
+ };
118
+ var replaceClose = (string, close, replace, index) => {
119
+ let result = "", cursor3 = 0;
120
+ do {
121
+ result += string.substring(cursor3, index) + replace;
122
+ cursor3 = index + close.length;
123
+ index = string.indexOf(close, cursor3);
124
+ } while (~index);
125
+ return result + string.substring(cursor3);
126
+ };
127
+ var createColors = (enabled = isColorSupported) => {
128
+ let f = enabled ? formatter : () => String;
129
+ return {
130
+ isColorSupported: enabled,
131
+ reset: f("\x1B[0m", "\x1B[0m"),
132
+ bold: f("\x1B[1m", "\x1B[22m", "\x1B[22m\x1B[1m"),
133
+ dim: f("\x1B[2m", "\x1B[22m", "\x1B[22m\x1B[2m"),
134
+ italic: f("\x1B[3m", "\x1B[23m"),
135
+ underline: f("\x1B[4m", "\x1B[24m"),
136
+ inverse: f("\x1B[7m", "\x1B[27m"),
137
+ hidden: f("\x1B[8m", "\x1B[28m"),
138
+ strikethrough: f("\x1B[9m", "\x1B[29m"),
139
+ black: f("\x1B[30m", "\x1B[39m"),
140
+ red: f("\x1B[31m", "\x1B[39m"),
141
+ green: f("\x1B[32m", "\x1B[39m"),
142
+ yellow: f("\x1B[33m", "\x1B[39m"),
143
+ blue: f("\x1B[34m", "\x1B[39m"),
144
+ magenta: f("\x1B[35m", "\x1B[39m"),
145
+ cyan: f("\x1B[36m", "\x1B[39m"),
146
+ white: f("\x1B[37m", "\x1B[39m"),
147
+ gray: f("\x1B[90m", "\x1B[39m"),
148
+ bgBlack: f("\x1B[40m", "\x1B[49m"),
149
+ bgRed: f("\x1B[41m", "\x1B[49m"),
150
+ bgGreen: f("\x1B[42m", "\x1B[49m"),
151
+ bgYellow: f("\x1B[43m", "\x1B[49m"),
152
+ bgBlue: f("\x1B[44m", "\x1B[49m"),
153
+ bgMagenta: f("\x1B[45m", "\x1B[49m"),
154
+ bgCyan: f("\x1B[46m", "\x1B[49m"),
155
+ bgWhite: f("\x1B[47m", "\x1B[49m"),
156
+ blackBright: f("\x1B[90m", "\x1B[39m"),
157
+ redBright: f("\x1B[91m", "\x1B[39m"),
158
+ greenBright: f("\x1B[92m", "\x1B[39m"),
159
+ yellowBright: f("\x1B[93m", "\x1B[39m"),
160
+ blueBright: f("\x1B[94m", "\x1B[39m"),
161
+ magentaBright: f("\x1B[95m", "\x1B[39m"),
162
+ cyanBright: f("\x1B[96m", "\x1B[39m"),
163
+ whiteBright: f("\x1B[97m", "\x1B[39m"),
164
+ bgBlackBright: f("\x1B[100m", "\x1B[49m"),
165
+ bgRedBright: f("\x1B[101m", "\x1B[49m"),
166
+ bgGreenBright: f("\x1B[102m", "\x1B[49m"),
167
+ bgYellowBright: f("\x1B[103m", "\x1B[49m"),
168
+ bgBlueBright: f("\x1B[104m", "\x1B[49m"),
169
+ bgMagentaBright: f("\x1B[105m", "\x1B[49m"),
170
+ bgCyanBright: f("\x1B[106m", "\x1B[49m"),
171
+ bgWhiteBright: f("\x1B[107m", "\x1B[49m")
172
+ };
173
+ };
174
+ module.exports = createColors();
175
+ module.exports.createColors = createColors;
176
+ }
177
+ });
178
+
179
+ // node_modules/ws/lib/constants.js
180
+ var require_constants = __commonJS({
181
+ "node_modules/ws/lib/constants.js"(exports, module) {
182
+ "use strict";
183
+ var BINARY_TYPES = ["nodebuffer", "arraybuffer", "fragments"];
184
+ var hasBlob = typeof Blob !== "undefined";
185
+ if (hasBlob) BINARY_TYPES.push("blob");
186
+ module.exports = {
187
+ BINARY_TYPES,
188
+ CLOSE_TIMEOUT: 3e4,
189
+ EMPTY_BUFFER: Buffer.alloc(0),
190
+ GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
191
+ hasBlob,
192
+ kForOnEventAttribute: /* @__PURE__ */ Symbol("kIsForOnEventAttribute"),
193
+ kListener: /* @__PURE__ */ Symbol("kListener"),
194
+ kStatusCode: /* @__PURE__ */ Symbol("status-code"),
195
+ kWebSocket: /* @__PURE__ */ Symbol("websocket"),
196
+ NOOP: () => {
197
+ }
198
+ };
199
+ }
200
+ });
201
+
202
+ // node_modules/ws/lib/buffer-util.js
203
+ var require_buffer_util = __commonJS({
204
+ "node_modules/ws/lib/buffer-util.js"(exports, module) {
205
+ "use strict";
206
+ var { EMPTY_BUFFER: EMPTY_BUFFER2 } = require_constants();
207
+ var FastBuffer = Buffer[Symbol.species];
208
+ function concat(list, totalLength) {
209
+ if (list.length === 0) return EMPTY_BUFFER2;
210
+ if (list.length === 1) return list[0];
211
+ const target = Buffer.allocUnsafe(totalLength);
212
+ let offset = 0;
213
+ for (let i3 = 0; i3 < list.length; i3++) {
214
+ const buf = list[i3];
215
+ target.set(buf, offset);
216
+ offset += buf.length;
217
+ }
218
+ if (offset < totalLength) {
219
+ return new FastBuffer(target.buffer, target.byteOffset, offset);
220
+ }
221
+ return target;
222
+ }
223
+ function _mask(source, mask, output, offset, length) {
224
+ for (let i3 = 0; i3 < length; i3++) {
225
+ output[offset + i3] = source[i3] ^ mask[i3 & 3];
226
+ }
227
+ }
228
+ function _unmask(buffer, mask) {
229
+ for (let i3 = 0; i3 < buffer.length; i3++) {
230
+ buffer[i3] ^= mask[i3 & 3];
231
+ }
232
+ }
233
+ function toArrayBuffer(buf) {
234
+ if (buf.length === buf.buffer.byteLength) {
235
+ return buf.buffer;
236
+ }
237
+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);
238
+ }
239
+ function toBuffer(data) {
240
+ toBuffer.readOnly = true;
241
+ if (Buffer.isBuffer(data)) return data;
242
+ let buf;
243
+ if (data instanceof ArrayBuffer) {
244
+ buf = new FastBuffer(data);
245
+ } else if (ArrayBuffer.isView(data)) {
246
+ buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);
247
+ } else {
248
+ buf = Buffer.from(data);
249
+ toBuffer.readOnly = false;
250
+ }
251
+ return buf;
252
+ }
253
+ module.exports = {
254
+ concat,
255
+ mask: _mask,
256
+ toArrayBuffer,
257
+ toBuffer,
258
+ unmask: _unmask
259
+ };
260
+ if (!process.env.WS_NO_BUFFER_UTIL) {
261
+ try {
262
+ const bufferUtil = __require("bufferutil");
263
+ module.exports.mask = function(source, mask, output, offset, length) {
264
+ if (length < 48) _mask(source, mask, output, offset, length);
265
+ else bufferUtil.mask(source, mask, output, offset, length);
266
+ };
267
+ module.exports.unmask = function(buffer, mask) {
268
+ if (buffer.length < 32) _unmask(buffer, mask);
269
+ else bufferUtil.unmask(buffer, mask);
270
+ };
271
+ } catch (e) {
272
+ }
273
+ }
274
+ }
275
+ });
276
+
277
+ // node_modules/ws/lib/limiter.js
278
+ var require_limiter = __commonJS({
279
+ "node_modules/ws/lib/limiter.js"(exports, module) {
280
+ "use strict";
281
+ var kDone = /* @__PURE__ */ Symbol("kDone");
282
+ var kRun = /* @__PURE__ */ Symbol("kRun");
283
+ var Limiter = class {
284
+ /**
285
+ * Creates a new `Limiter`.
286
+ *
287
+ * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed
288
+ * to run concurrently
289
+ */
290
+ constructor(concurrency) {
291
+ this[kDone] = () => {
292
+ this.pending--;
293
+ this[kRun]();
294
+ };
295
+ this.concurrency = concurrency || Infinity;
296
+ this.jobs = [];
297
+ this.pending = 0;
298
+ }
299
+ /**
300
+ * Adds a job to the queue.
301
+ *
302
+ * @param {Function} job The job to run
303
+ * @public
304
+ */
305
+ add(job) {
306
+ this.jobs.push(job);
307
+ this[kRun]();
308
+ }
309
+ /**
310
+ * Removes a job from the queue and runs it if possible.
311
+ *
312
+ * @private
313
+ */
314
+ [kRun]() {
315
+ if (this.pending === this.concurrency) return;
316
+ if (this.jobs.length) {
317
+ const job = this.jobs.shift();
318
+ this.pending++;
319
+ job(this[kDone]);
320
+ }
321
+ }
322
+ };
323
+ module.exports = Limiter;
324
+ }
325
+ });
326
+
327
+ // node_modules/ws/lib/permessage-deflate.js
328
+ var require_permessage_deflate = __commonJS({
329
+ "node_modules/ws/lib/permessage-deflate.js"(exports, module) {
330
+ "use strict";
331
+ var zlib = __require("zlib");
332
+ var bufferUtil = require_buffer_util();
333
+ var Limiter = require_limiter();
334
+ var { kStatusCode } = require_constants();
335
+ var FastBuffer = Buffer[Symbol.species];
336
+ var TRAILER = Buffer.from([0, 0, 255, 255]);
337
+ var kPerMessageDeflate = /* @__PURE__ */ Symbol("permessage-deflate");
338
+ var kTotalLength = /* @__PURE__ */ Symbol("total-length");
339
+ var kCallback = /* @__PURE__ */ Symbol("callback");
340
+ var kBuffers = /* @__PURE__ */ Symbol("buffers");
341
+ var kError = /* @__PURE__ */ Symbol("error");
342
+ var zlibLimiter;
343
+ var PerMessageDeflate2 = class {
344
+ /**
345
+ * Creates a PerMessageDeflate instance.
346
+ *
347
+ * @param {Object} [options] Configuration options
348
+ * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support
349
+ * for, or request, a custom client window size
350
+ * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/
351
+ * acknowledge disabling of client context takeover
352
+ * @param {Number} [options.concurrencyLimit=10] The number of concurrent
353
+ * calls to zlib
354
+ * @param {Boolean} [options.isServer=false] Create the instance in either
355
+ * server or client mode
356
+ * @param {Number} [options.maxPayload=0] The maximum allowed message length
357
+ * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the
358
+ * use of a custom server window size
359
+ * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept
360
+ * disabling of server context takeover
361
+ * @param {Number} [options.threshold=1024] Size (in bytes) below which
362
+ * messages should not be compressed if context takeover is disabled
363
+ * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on
364
+ * deflate
365
+ * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on
366
+ * inflate
367
+ */
368
+ constructor(options) {
369
+ this._options = options || {};
370
+ this._threshold = this._options.threshold !== void 0 ? this._options.threshold : 1024;
371
+ this._maxPayload = this._options.maxPayload | 0;
372
+ this._isServer = !!this._options.isServer;
373
+ this._deflate = null;
374
+ this._inflate = null;
375
+ this.params = null;
376
+ if (!zlibLimiter) {
377
+ const concurrency = this._options.concurrencyLimit !== void 0 ? this._options.concurrencyLimit : 10;
378
+ zlibLimiter = new Limiter(concurrency);
379
+ }
380
+ }
381
+ /**
382
+ * @type {String}
383
+ */
384
+ static get extensionName() {
385
+ return "permessage-deflate";
386
+ }
387
+ /**
388
+ * Create an extension negotiation offer.
389
+ *
390
+ * @return {Object} Extension parameters
391
+ * @public
392
+ */
393
+ offer() {
394
+ const params = {};
395
+ if (this._options.serverNoContextTakeover) {
396
+ params.server_no_context_takeover = true;
397
+ }
398
+ if (this._options.clientNoContextTakeover) {
399
+ params.client_no_context_takeover = true;
400
+ }
401
+ if (this._options.serverMaxWindowBits) {
402
+ params.server_max_window_bits = this._options.serverMaxWindowBits;
403
+ }
404
+ if (this._options.clientMaxWindowBits) {
405
+ params.client_max_window_bits = this._options.clientMaxWindowBits;
406
+ } else if (this._options.clientMaxWindowBits == null) {
407
+ params.client_max_window_bits = true;
408
+ }
409
+ return params;
410
+ }
411
+ /**
412
+ * Accept an extension negotiation offer/response.
413
+ *
414
+ * @param {Array} configurations The extension negotiation offers/reponse
415
+ * @return {Object} Accepted configuration
416
+ * @public
417
+ */
418
+ accept(configurations) {
419
+ configurations = this.normalizeParams(configurations);
420
+ this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations);
421
+ return this.params;
422
+ }
423
+ /**
424
+ * Releases all resources used by the extension.
425
+ *
426
+ * @public
427
+ */
428
+ cleanup() {
429
+ if (this._inflate) {
430
+ this._inflate.close();
431
+ this._inflate = null;
432
+ }
433
+ if (this._deflate) {
434
+ const callback = this._deflate[kCallback];
435
+ this._deflate.close();
436
+ this._deflate = null;
437
+ if (callback) {
438
+ callback(
439
+ new Error(
440
+ "The deflate stream was closed while data was being processed"
441
+ )
442
+ );
443
+ }
444
+ }
445
+ }
446
+ /**
447
+ * Accept an extension negotiation offer.
448
+ *
449
+ * @param {Array} offers The extension negotiation offers
450
+ * @return {Object} Accepted configuration
451
+ * @private
452
+ */
453
+ acceptAsServer(offers) {
454
+ const opts = this._options;
455
+ const accepted = offers.find((params) => {
456
+ if (opts.serverNoContextTakeover === false && params.server_no_context_takeover || params.server_max_window_bits && (opts.serverMaxWindowBits === false || typeof opts.serverMaxWindowBits === "number" && opts.serverMaxWindowBits > params.server_max_window_bits) || typeof opts.clientMaxWindowBits === "number" && (typeof params.client_max_window_bits === "number" ? opts.clientMaxWindowBits > params.client_max_window_bits : !params.client_max_window_bits)) {
457
+ return false;
458
+ }
459
+ return true;
460
+ });
461
+ if (!accepted) {
462
+ throw new Error("None of the extension offers can be accepted");
463
+ }
464
+ if (opts.serverNoContextTakeover) {
465
+ accepted.server_no_context_takeover = true;
466
+ }
467
+ if (opts.clientNoContextTakeover) {
468
+ accepted.client_no_context_takeover = true;
469
+ }
470
+ if (typeof opts.serverMaxWindowBits === "number") {
471
+ accepted.server_max_window_bits = opts.serverMaxWindowBits;
472
+ }
473
+ if (typeof opts.clientMaxWindowBits === "number") {
474
+ accepted.client_max_window_bits = opts.clientMaxWindowBits;
475
+ } else if (accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false) {
476
+ delete accepted.client_max_window_bits;
477
+ }
478
+ return accepted;
479
+ }
480
+ /**
481
+ * Accept the extension negotiation response.
482
+ *
483
+ * @param {Array} response The extension negotiation response
484
+ * @return {Object} Accepted configuration
485
+ * @private
486
+ */
487
+ acceptAsClient(response) {
488
+ const params = response[0];
489
+ if (this._options.clientNoContextTakeover === false && params.client_no_context_takeover) {
490
+ throw new Error('Unexpected parameter "client_no_context_takeover"');
491
+ }
492
+ if (!params.client_max_window_bits) {
493
+ if (typeof this._options.clientMaxWindowBits === "number") {
494
+ params.client_max_window_bits = this._options.clientMaxWindowBits;
495
+ }
496
+ } else if (this._options.clientMaxWindowBits === false || typeof this._options.clientMaxWindowBits === "number" && params.client_max_window_bits > this._options.clientMaxWindowBits) {
497
+ throw new Error(
498
+ 'Unexpected or invalid parameter "client_max_window_bits"'
499
+ );
500
+ }
501
+ return params;
502
+ }
503
+ /**
504
+ * Normalize parameters.
505
+ *
506
+ * @param {Array} configurations The extension negotiation offers/reponse
507
+ * @return {Array} The offers/response with normalized parameters
508
+ * @private
509
+ */
510
+ normalizeParams(configurations) {
511
+ configurations.forEach((params) => {
512
+ Object.keys(params).forEach((key) => {
513
+ let value = params[key];
514
+ if (value.length > 1) {
515
+ throw new Error(`Parameter "${key}" must have only a single value`);
516
+ }
517
+ value = value[0];
518
+ if (key === "client_max_window_bits") {
519
+ if (value !== true) {
520
+ const num3 = +value;
521
+ if (!Number.isInteger(num3) || num3 < 8 || num3 > 15) {
522
+ throw new TypeError(
523
+ `Invalid value for parameter "${key}": ${value}`
524
+ );
525
+ }
526
+ value = num3;
527
+ } else if (!this._isServer) {
528
+ throw new TypeError(
529
+ `Invalid value for parameter "${key}": ${value}`
530
+ );
531
+ }
532
+ } else if (key === "server_max_window_bits") {
533
+ const num3 = +value;
534
+ if (!Number.isInteger(num3) || num3 < 8 || num3 > 15) {
535
+ throw new TypeError(
536
+ `Invalid value for parameter "${key}": ${value}`
537
+ );
538
+ }
539
+ value = num3;
540
+ } else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") {
541
+ if (value !== true) {
542
+ throw new TypeError(
543
+ `Invalid value for parameter "${key}": ${value}`
544
+ );
545
+ }
546
+ } else {
547
+ throw new Error(`Unknown parameter "${key}"`);
548
+ }
549
+ params[key] = value;
550
+ });
551
+ });
552
+ return configurations;
553
+ }
554
+ /**
555
+ * Decompress data. Concurrency limited.
556
+ *
557
+ * @param {Buffer} data Compressed data
558
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
559
+ * @param {Function} callback Callback
560
+ * @public
561
+ */
562
+ decompress(data, fin, callback) {
563
+ zlibLimiter.add((done) => {
564
+ this._decompress(data, fin, (err, result) => {
565
+ done();
566
+ callback(err, result);
567
+ });
568
+ });
569
+ }
570
+ /**
571
+ * Compress data. Concurrency limited.
572
+ *
573
+ * @param {(Buffer|String)} data Data to compress
574
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
575
+ * @param {Function} callback Callback
576
+ * @public
577
+ */
578
+ compress(data, fin, callback) {
579
+ zlibLimiter.add((done) => {
580
+ this._compress(data, fin, (err, result) => {
581
+ done();
582
+ callback(err, result);
583
+ });
584
+ });
585
+ }
586
+ /**
587
+ * Decompress data.
588
+ *
589
+ * @param {Buffer} data Compressed data
590
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
591
+ * @param {Function} callback Callback
592
+ * @private
593
+ */
594
+ _decompress(data, fin, callback) {
595
+ const endpoint2 = this._isServer ? "client" : "server";
596
+ if (!this._inflate) {
597
+ const key = `${endpoint2}_max_window_bits`;
598
+ const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
599
+ this._inflate = zlib.createInflateRaw({
600
+ ...this._options.zlibInflateOptions,
601
+ windowBits
602
+ });
603
+ this._inflate[kPerMessageDeflate] = this;
604
+ this._inflate[kTotalLength] = 0;
605
+ this._inflate[kBuffers] = [];
606
+ this._inflate.on("error", inflateOnError);
607
+ this._inflate.on("data", inflateOnData);
608
+ }
609
+ this._inflate[kCallback] = callback;
610
+ this._inflate.write(data);
611
+ if (fin) this._inflate.write(TRAILER);
612
+ this._inflate.flush(() => {
613
+ const err = this._inflate[kError];
614
+ if (err) {
615
+ this._inflate.close();
616
+ this._inflate = null;
617
+ callback(err);
618
+ return;
619
+ }
620
+ const data2 = bufferUtil.concat(
621
+ this._inflate[kBuffers],
622
+ this._inflate[kTotalLength]
623
+ );
624
+ if (this._inflate._readableState.endEmitted) {
625
+ this._inflate.close();
626
+ this._inflate = null;
627
+ } else {
628
+ this._inflate[kTotalLength] = 0;
629
+ this._inflate[kBuffers] = [];
630
+ if (fin && this.params[`${endpoint2}_no_context_takeover`]) {
631
+ this._inflate.reset();
632
+ }
633
+ }
634
+ callback(null, data2);
635
+ });
636
+ }
637
+ /**
638
+ * Compress data.
639
+ *
640
+ * @param {(Buffer|String)} data Data to compress
641
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
642
+ * @param {Function} callback Callback
643
+ * @private
644
+ */
645
+ _compress(data, fin, callback) {
646
+ const endpoint2 = this._isServer ? "server" : "client";
647
+ if (!this._deflate) {
648
+ const key = `${endpoint2}_max_window_bits`;
649
+ const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
650
+ this._deflate = zlib.createDeflateRaw({
651
+ ...this._options.zlibDeflateOptions,
652
+ windowBits
653
+ });
654
+ this._deflate[kTotalLength] = 0;
655
+ this._deflate[kBuffers] = [];
656
+ this._deflate.on("data", deflateOnData);
657
+ }
658
+ this._deflate[kCallback] = callback;
659
+ this._deflate.write(data);
660
+ this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {
661
+ if (!this._deflate) {
662
+ return;
663
+ }
664
+ let data2 = bufferUtil.concat(
665
+ this._deflate[kBuffers],
666
+ this._deflate[kTotalLength]
667
+ );
668
+ if (fin) {
669
+ data2 = new FastBuffer(data2.buffer, data2.byteOffset, data2.length - 4);
670
+ }
671
+ this._deflate[kCallback] = null;
672
+ this._deflate[kTotalLength] = 0;
673
+ this._deflate[kBuffers] = [];
674
+ if (fin && this.params[`${endpoint2}_no_context_takeover`]) {
675
+ this._deflate.reset();
676
+ }
677
+ callback(null, data2);
678
+ });
679
+ }
680
+ };
681
+ module.exports = PerMessageDeflate2;
682
+ function deflateOnData(chunk) {
683
+ this[kBuffers].push(chunk);
684
+ this[kTotalLength] += chunk.length;
685
+ }
686
+ function inflateOnData(chunk) {
687
+ this[kTotalLength] += chunk.length;
688
+ if (this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) {
689
+ this[kBuffers].push(chunk);
690
+ return;
691
+ }
692
+ this[kError] = new RangeError("Max payload size exceeded");
693
+ this[kError].code = "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH";
694
+ this[kError][kStatusCode] = 1009;
695
+ this.removeListener("data", inflateOnData);
696
+ this.reset();
697
+ }
698
+ function inflateOnError(err) {
699
+ this[kPerMessageDeflate]._inflate = null;
700
+ if (this[kError]) {
701
+ this[kCallback](this[kError]);
702
+ return;
703
+ }
704
+ err[kStatusCode] = 1007;
705
+ this[kCallback](err);
706
+ }
707
+ }
708
+ });
709
+
710
+ // node_modules/ws/lib/validation.js
711
+ var require_validation = __commonJS({
712
+ "node_modules/ws/lib/validation.js"(exports, module) {
713
+ "use strict";
714
+ var { isUtf8 } = __require("buffer");
715
+ var { hasBlob } = require_constants();
716
+ var tokenChars = [
717
+ 0,
718
+ 0,
719
+ 0,
720
+ 0,
721
+ 0,
722
+ 0,
723
+ 0,
724
+ 0,
725
+ 0,
726
+ 0,
727
+ 0,
728
+ 0,
729
+ 0,
730
+ 0,
731
+ 0,
732
+ 0,
733
+ // 0 - 15
734
+ 0,
735
+ 0,
736
+ 0,
737
+ 0,
738
+ 0,
739
+ 0,
740
+ 0,
741
+ 0,
742
+ 0,
743
+ 0,
744
+ 0,
745
+ 0,
746
+ 0,
747
+ 0,
748
+ 0,
749
+ 0,
750
+ // 16 - 31
751
+ 0,
752
+ 1,
753
+ 0,
754
+ 1,
755
+ 1,
756
+ 1,
757
+ 1,
758
+ 1,
759
+ 0,
760
+ 0,
761
+ 1,
762
+ 1,
763
+ 0,
764
+ 1,
765
+ 1,
766
+ 0,
767
+ // 32 - 47
768
+ 1,
769
+ 1,
770
+ 1,
771
+ 1,
772
+ 1,
773
+ 1,
774
+ 1,
775
+ 1,
776
+ 1,
777
+ 1,
778
+ 0,
779
+ 0,
780
+ 0,
781
+ 0,
782
+ 0,
783
+ 0,
784
+ // 48 - 63
785
+ 0,
786
+ 1,
787
+ 1,
788
+ 1,
789
+ 1,
790
+ 1,
791
+ 1,
792
+ 1,
793
+ 1,
794
+ 1,
795
+ 1,
796
+ 1,
797
+ 1,
798
+ 1,
799
+ 1,
800
+ 1,
801
+ // 64 - 79
802
+ 1,
803
+ 1,
804
+ 1,
805
+ 1,
806
+ 1,
807
+ 1,
808
+ 1,
809
+ 1,
810
+ 1,
811
+ 1,
812
+ 1,
813
+ 0,
814
+ 0,
815
+ 0,
816
+ 1,
817
+ 1,
818
+ // 80 - 95
819
+ 1,
820
+ 1,
821
+ 1,
822
+ 1,
823
+ 1,
824
+ 1,
825
+ 1,
826
+ 1,
827
+ 1,
828
+ 1,
829
+ 1,
830
+ 1,
831
+ 1,
832
+ 1,
833
+ 1,
834
+ 1,
835
+ // 96 - 111
836
+ 1,
837
+ 1,
838
+ 1,
839
+ 1,
840
+ 1,
841
+ 1,
842
+ 1,
843
+ 1,
844
+ 1,
845
+ 1,
846
+ 1,
847
+ 0,
848
+ 1,
849
+ 0,
850
+ 1,
851
+ 0
852
+ // 112 - 127
853
+ ];
854
+ function isValidStatusCode(code) {
855
+ return code >= 1e3 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006 || code >= 3e3 && code <= 4999;
856
+ }
857
+ function _isValidUTF8(buf) {
858
+ const len = buf.length;
859
+ let i3 = 0;
860
+ while (i3 < len) {
861
+ if ((buf[i3] & 128) === 0) {
862
+ i3++;
863
+ } else if ((buf[i3] & 224) === 192) {
864
+ if (i3 + 1 === len || (buf[i3 + 1] & 192) !== 128 || (buf[i3] & 254) === 192) {
865
+ return false;
866
+ }
867
+ i3 += 2;
868
+ } else if ((buf[i3] & 240) === 224) {
869
+ if (i3 + 2 >= len || (buf[i3 + 1] & 192) !== 128 || (buf[i3 + 2] & 192) !== 128 || buf[i3] === 224 && (buf[i3 + 1] & 224) === 128 || // Overlong
870
+ buf[i3] === 237 && (buf[i3 + 1] & 224) === 160) {
871
+ return false;
872
+ }
873
+ i3 += 3;
874
+ } else if ((buf[i3] & 248) === 240) {
875
+ if (i3 + 3 >= len || (buf[i3 + 1] & 192) !== 128 || (buf[i3 + 2] & 192) !== 128 || (buf[i3 + 3] & 192) !== 128 || buf[i3] === 240 && (buf[i3 + 1] & 240) === 128 || // Overlong
876
+ buf[i3] === 244 && buf[i3 + 1] > 143 || buf[i3] > 244) {
877
+ return false;
878
+ }
879
+ i3 += 4;
880
+ } else {
881
+ return false;
882
+ }
883
+ }
884
+ return true;
885
+ }
886
+ function isBlob(value) {
887
+ 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");
888
+ }
889
+ module.exports = {
890
+ isBlob,
891
+ isValidStatusCode,
892
+ isValidUTF8: _isValidUTF8,
893
+ tokenChars
894
+ };
895
+ if (isUtf8) {
896
+ module.exports.isValidUTF8 = function(buf) {
897
+ return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);
898
+ };
899
+ } else if (!process.env.WS_NO_UTF_8_VALIDATE) {
900
+ try {
901
+ const isValidUTF8 = __require("utf-8-validate");
902
+ module.exports.isValidUTF8 = function(buf) {
903
+ return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);
904
+ };
905
+ } catch (e) {
906
+ }
907
+ }
908
+ }
909
+ });
910
+
911
+ // node_modules/ws/lib/receiver.js
912
+ var require_receiver = __commonJS({
913
+ "node_modules/ws/lib/receiver.js"(exports, module) {
914
+ "use strict";
915
+ var { Writable } = __require("stream");
916
+ var PerMessageDeflate2 = require_permessage_deflate();
917
+ var {
918
+ BINARY_TYPES,
919
+ EMPTY_BUFFER: EMPTY_BUFFER2,
920
+ kStatusCode,
921
+ kWebSocket
922
+ } = require_constants();
923
+ var { concat, toArrayBuffer, unmask } = require_buffer_util();
924
+ var { isValidStatusCode, isValidUTF8 } = require_validation();
925
+ var FastBuffer = Buffer[Symbol.species];
926
+ var GET_INFO = 0;
927
+ var GET_PAYLOAD_LENGTH_16 = 1;
928
+ var GET_PAYLOAD_LENGTH_64 = 2;
929
+ var GET_MASK = 3;
930
+ var GET_DATA = 4;
931
+ var INFLATING = 5;
932
+ var DEFER_EVENT = 6;
933
+ var Receiver2 = class extends Writable {
934
+ /**
935
+ * Creates a Receiver instance.
936
+ *
937
+ * @param {Object} [options] Options object
938
+ * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
939
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
940
+ * multiple times in the same tick
941
+ * @param {String} [options.binaryType=nodebuffer] The type for binary data
942
+ * @param {Object} [options.extensions] An object containing the negotiated
943
+ * extensions
944
+ * @param {Boolean} [options.isServer=false] Specifies whether to operate in
945
+ * client or server mode
946
+ * @param {Number} [options.maxBufferedChunks=0] The maximum number of
947
+ * buffered data chunks
948
+ * @param {Number} [options.maxFragments=0] The maximum number of message
949
+ * fragments
950
+ * @param {Number} [options.maxPayload=0] The maximum allowed message length
951
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
952
+ * not to skip UTF-8 validation for text and close messages
953
+ */
954
+ constructor(options = {}) {
955
+ super();
956
+ this._allowSynchronousEvents = options.allowSynchronousEvents !== void 0 ? options.allowSynchronousEvents : true;
957
+ this._binaryType = options.binaryType || BINARY_TYPES[0];
958
+ this._extensions = options.extensions || {};
959
+ this._isServer = !!options.isServer;
960
+ this._maxBufferedChunks = options.maxBufferedChunks | 0;
961
+ this._maxFragments = options.maxFragments | 0;
962
+ this._maxPayload = options.maxPayload | 0;
963
+ this._skipUTF8Validation = !!options.skipUTF8Validation;
964
+ this[kWebSocket] = void 0;
965
+ this._bufferedBytes = 0;
966
+ this._buffers = [];
967
+ this._compressed = false;
968
+ this._payloadLength = 0;
969
+ this._mask = void 0;
970
+ this._fragmented = 0;
971
+ this._masked = false;
972
+ this._fin = false;
973
+ this._opcode = 0;
974
+ this._totalPayloadLength = 0;
975
+ this._messageLength = 0;
976
+ this._numFragments = 0;
977
+ this._fragments = [];
978
+ this._errored = false;
979
+ this._loop = false;
980
+ this._state = GET_INFO;
981
+ }
982
+ /**
983
+ * Implements `Writable.prototype._write()`.
984
+ *
985
+ * @param {Buffer} chunk The chunk of data to write
986
+ * @param {String} encoding The character encoding of `chunk`
987
+ * @param {Function} cb Callback
988
+ * @private
989
+ */
990
+ _write(chunk, encoding, cb) {
991
+ if (this._opcode === 8 && this._state == GET_INFO) return cb();
992
+ if (this._maxBufferedChunks > 0 && this._buffers.length >= this._maxBufferedChunks) {
993
+ cb(
994
+ this.createError(
995
+ RangeError,
996
+ "Too many buffered chunks",
997
+ false,
998
+ 1008,
999
+ "WS_ERR_TOO_MANY_BUFFERED_PARTS"
1000
+ )
1001
+ );
1002
+ return;
1003
+ }
1004
+ this._bufferedBytes += chunk.length;
1005
+ this._buffers.push(chunk);
1006
+ this.startLoop(cb);
1007
+ }
1008
+ /**
1009
+ * Consumes `n` bytes from the buffered data.
1010
+ *
1011
+ * @param {Number} n The number of bytes to consume
1012
+ * @return {Buffer} The consumed bytes
1013
+ * @private
1014
+ */
1015
+ consume(n3) {
1016
+ this._bufferedBytes -= n3;
1017
+ if (n3 === this._buffers[0].length) return this._buffers.shift();
1018
+ if (n3 < this._buffers[0].length) {
1019
+ const buf = this._buffers[0];
1020
+ this._buffers[0] = new FastBuffer(
1021
+ buf.buffer,
1022
+ buf.byteOffset + n3,
1023
+ buf.length - n3
1024
+ );
1025
+ return new FastBuffer(buf.buffer, buf.byteOffset, n3);
1026
+ }
1027
+ const dst = Buffer.allocUnsafe(n3);
1028
+ do {
1029
+ const buf = this._buffers[0];
1030
+ const offset = dst.length - n3;
1031
+ if (n3 >= buf.length) {
1032
+ dst.set(this._buffers.shift(), offset);
1033
+ } else {
1034
+ dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n3), offset);
1035
+ this._buffers[0] = new FastBuffer(
1036
+ buf.buffer,
1037
+ buf.byteOffset + n3,
1038
+ buf.length - n3
1039
+ );
1040
+ }
1041
+ n3 -= buf.length;
1042
+ } while (n3 > 0);
1043
+ return dst;
1044
+ }
1045
+ /**
1046
+ * Starts the parsing loop.
1047
+ *
1048
+ * @param {Function} cb Callback
1049
+ * @private
1050
+ */
1051
+ startLoop(cb) {
1052
+ this._loop = true;
1053
+ do {
1054
+ switch (this._state) {
1055
+ case GET_INFO:
1056
+ this.getInfo(cb);
1057
+ break;
1058
+ case GET_PAYLOAD_LENGTH_16:
1059
+ this.getPayloadLength16(cb);
1060
+ break;
1061
+ case GET_PAYLOAD_LENGTH_64:
1062
+ this.getPayloadLength64(cb);
1063
+ break;
1064
+ case GET_MASK:
1065
+ this.getMask();
1066
+ break;
1067
+ case GET_DATA:
1068
+ this.getData(cb);
1069
+ break;
1070
+ case INFLATING:
1071
+ case DEFER_EVENT:
1072
+ this._loop = false;
1073
+ return;
1074
+ }
1075
+ } while (this._loop);
1076
+ if (!this._errored) cb();
1077
+ }
1078
+ /**
1079
+ * Reads the first two bytes of a frame.
1080
+ *
1081
+ * @param {Function} cb Callback
1082
+ * @private
1083
+ */
1084
+ getInfo(cb) {
1085
+ if (this._bufferedBytes < 2) {
1086
+ this._loop = false;
1087
+ return;
1088
+ }
1089
+ const buf = this.consume(2);
1090
+ if ((buf[0] & 48) !== 0) {
1091
+ const error = this.createError(
1092
+ RangeError,
1093
+ "RSV2 and RSV3 must be clear",
1094
+ true,
1095
+ 1002,
1096
+ "WS_ERR_UNEXPECTED_RSV_2_3"
1097
+ );
1098
+ cb(error);
1099
+ return;
1100
+ }
1101
+ const compressed = (buf[0] & 64) === 64;
1102
+ if (compressed && !this._extensions[PerMessageDeflate2.extensionName]) {
1103
+ const error = this.createError(
1104
+ RangeError,
1105
+ "RSV1 must be clear",
1106
+ true,
1107
+ 1002,
1108
+ "WS_ERR_UNEXPECTED_RSV_1"
1109
+ );
1110
+ cb(error);
1111
+ return;
1112
+ }
1113
+ this._fin = (buf[0] & 128) === 128;
1114
+ this._opcode = buf[0] & 15;
1115
+ this._payloadLength = buf[1] & 127;
1116
+ if (this._opcode === 0) {
1117
+ if (compressed) {
1118
+ const error = this.createError(
1119
+ RangeError,
1120
+ "RSV1 must be clear",
1121
+ true,
1122
+ 1002,
1123
+ "WS_ERR_UNEXPECTED_RSV_1"
1124
+ );
1125
+ cb(error);
1126
+ return;
1127
+ }
1128
+ if (!this._fragmented) {
1129
+ const error = this.createError(
1130
+ RangeError,
1131
+ "invalid opcode 0",
1132
+ true,
1133
+ 1002,
1134
+ "WS_ERR_INVALID_OPCODE"
1135
+ );
1136
+ cb(error);
1137
+ return;
1138
+ }
1139
+ this._opcode = this._fragmented;
1140
+ } else if (this._opcode === 1 || this._opcode === 2) {
1141
+ if (this._fragmented) {
1142
+ const error = this.createError(
1143
+ RangeError,
1144
+ `invalid opcode ${this._opcode}`,
1145
+ true,
1146
+ 1002,
1147
+ "WS_ERR_INVALID_OPCODE"
1148
+ );
1149
+ cb(error);
1150
+ return;
1151
+ }
1152
+ this._compressed = compressed;
1153
+ } else if (this._opcode > 7 && this._opcode < 11) {
1154
+ if (!this._fin) {
1155
+ const error = this.createError(
1156
+ RangeError,
1157
+ "FIN must be set",
1158
+ true,
1159
+ 1002,
1160
+ "WS_ERR_EXPECTED_FIN"
1161
+ );
1162
+ cb(error);
1163
+ return;
1164
+ }
1165
+ if (compressed) {
1166
+ const error = this.createError(
1167
+ RangeError,
1168
+ "RSV1 must be clear",
1169
+ true,
1170
+ 1002,
1171
+ "WS_ERR_UNEXPECTED_RSV_1"
1172
+ );
1173
+ cb(error);
1174
+ return;
1175
+ }
1176
+ if (this._payloadLength > 125 || this._opcode === 8 && this._payloadLength === 1) {
1177
+ const error = this.createError(
1178
+ RangeError,
1179
+ `invalid payload length ${this._payloadLength}`,
1180
+ true,
1181
+ 1002,
1182
+ "WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"
1183
+ );
1184
+ cb(error);
1185
+ return;
1186
+ }
1187
+ } else {
1188
+ const error = this.createError(
1189
+ RangeError,
1190
+ `invalid opcode ${this._opcode}`,
1191
+ true,
1192
+ 1002,
1193
+ "WS_ERR_INVALID_OPCODE"
1194
+ );
1195
+ cb(error);
1196
+ return;
1197
+ }
1198
+ if (!this._fin && !this._fragmented) this._fragmented = this._opcode;
1199
+ this._masked = (buf[1] & 128) === 128;
1200
+ if (this._isServer) {
1201
+ if (!this._masked) {
1202
+ const error = this.createError(
1203
+ RangeError,
1204
+ "MASK must be set",
1205
+ true,
1206
+ 1002,
1207
+ "WS_ERR_EXPECTED_MASK"
1208
+ );
1209
+ cb(error);
1210
+ return;
1211
+ }
1212
+ } else if (this._masked) {
1213
+ const error = this.createError(
1214
+ RangeError,
1215
+ "MASK must be clear",
1216
+ true,
1217
+ 1002,
1218
+ "WS_ERR_UNEXPECTED_MASK"
1219
+ );
1220
+ cb(error);
1221
+ return;
1222
+ }
1223
+ if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;
1224
+ else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;
1225
+ else this.haveLength(cb);
1226
+ }
1227
+ /**
1228
+ * Gets extended payload length (7+16).
1229
+ *
1230
+ * @param {Function} cb Callback
1231
+ * @private
1232
+ */
1233
+ getPayloadLength16(cb) {
1234
+ if (this._bufferedBytes < 2) {
1235
+ this._loop = false;
1236
+ return;
1237
+ }
1238
+ this._payloadLength = this.consume(2).readUInt16BE(0);
1239
+ this.haveLength(cb);
1240
+ }
1241
+ /**
1242
+ * Gets extended payload length (7+64).
1243
+ *
1244
+ * @param {Function} cb Callback
1245
+ * @private
1246
+ */
1247
+ getPayloadLength64(cb) {
1248
+ if (this._bufferedBytes < 8) {
1249
+ this._loop = false;
1250
+ return;
1251
+ }
1252
+ const buf = this.consume(8);
1253
+ const num3 = buf.readUInt32BE(0);
1254
+ if (num3 > Math.pow(2, 53 - 32) - 1) {
1255
+ const error = this.createError(
1256
+ RangeError,
1257
+ "Unsupported WebSocket frame: payload length > 2^53 - 1",
1258
+ false,
1259
+ 1009,
1260
+ "WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH"
1261
+ );
1262
+ cb(error);
1263
+ return;
1264
+ }
1265
+ this._payloadLength = num3 * Math.pow(2, 32) + buf.readUInt32BE(4);
1266
+ this.haveLength(cb);
1267
+ }
1268
+ /**
1269
+ * Payload length has been read.
1270
+ *
1271
+ * @param {Function} cb Callback
1272
+ * @private
1273
+ */
1274
+ haveLength(cb) {
1275
+ if (this._payloadLength && this._opcode < 8) {
1276
+ this._totalPayloadLength += this._payloadLength;
1277
+ if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
1278
+ const error = this.createError(
1279
+ RangeError,
1280
+ "Max payload size exceeded",
1281
+ false,
1282
+ 1009,
1283
+ "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
1284
+ );
1285
+ cb(error);
1286
+ return;
1287
+ }
1288
+ }
1289
+ if (this._masked) this._state = GET_MASK;
1290
+ else this._state = GET_DATA;
1291
+ }
1292
+ /**
1293
+ * Reads mask bytes.
1294
+ *
1295
+ * @private
1296
+ */
1297
+ getMask() {
1298
+ if (this._bufferedBytes < 4) {
1299
+ this._loop = false;
1300
+ return;
1301
+ }
1302
+ this._mask = this.consume(4);
1303
+ this._state = GET_DATA;
1304
+ }
1305
+ /**
1306
+ * Reads data bytes.
1307
+ *
1308
+ * @param {Function} cb Callback
1309
+ * @private
1310
+ */
1311
+ getData(cb) {
1312
+ let data = EMPTY_BUFFER2;
1313
+ if (this._payloadLength) {
1314
+ if (this._bufferedBytes < this._payloadLength) {
1315
+ this._loop = false;
1316
+ return;
1317
+ }
1318
+ data = this.consume(this._payloadLength);
1319
+ if (this._masked && (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0) {
1320
+ unmask(data, this._mask);
1321
+ }
1322
+ }
1323
+ if (this._opcode > 7) {
1324
+ this.controlMessage(data, cb);
1325
+ return;
1326
+ }
1327
+ if (this._maxFragments > 0 && ++this._numFragments > this._maxFragments) {
1328
+ const error = this.createError(
1329
+ RangeError,
1330
+ "Too many message fragments",
1331
+ false,
1332
+ 1008,
1333
+ "WS_ERR_TOO_MANY_BUFFERED_PARTS"
1334
+ );
1335
+ cb(error);
1336
+ return;
1337
+ }
1338
+ if (this._compressed) {
1339
+ this._state = INFLATING;
1340
+ this.decompress(data, cb);
1341
+ return;
1342
+ }
1343
+ if (data.length) {
1344
+ this._messageLength = this._totalPayloadLength;
1345
+ this._fragments.push(data);
1346
+ }
1347
+ this.dataMessage(cb);
1348
+ }
1349
+ /**
1350
+ * Decompresses data.
1351
+ *
1352
+ * @param {Buffer} data Compressed data
1353
+ * @param {Function} cb Callback
1354
+ * @private
1355
+ */
1356
+ decompress(data, cb) {
1357
+ const perMessageDeflate = this._extensions[PerMessageDeflate2.extensionName];
1358
+ perMessageDeflate.decompress(data, this._fin, (err, buf) => {
1359
+ if (err) return cb(err);
1360
+ if (buf.length) {
1361
+ this._messageLength += buf.length;
1362
+ if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
1363
+ const error = this.createError(
1364
+ RangeError,
1365
+ "Max payload size exceeded",
1366
+ false,
1367
+ 1009,
1368
+ "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
1369
+ );
1370
+ cb(error);
1371
+ return;
1372
+ }
1373
+ this._fragments.push(buf);
1374
+ }
1375
+ this.dataMessage(cb);
1376
+ if (this._state === GET_INFO) this.startLoop(cb);
1377
+ });
1378
+ }
1379
+ /**
1380
+ * Handles a data message.
1381
+ *
1382
+ * @param {Function} cb Callback
1383
+ * @private
1384
+ */
1385
+ dataMessage(cb) {
1386
+ if (!this._fin) {
1387
+ this._state = GET_INFO;
1388
+ return;
1389
+ }
1390
+ const messageLength = this._messageLength;
1391
+ const fragments = this._fragments;
1392
+ this._totalPayloadLength = 0;
1393
+ this._messageLength = 0;
1394
+ this._fragmented = 0;
1395
+ this._numFragments = 0;
1396
+ this._fragments = [];
1397
+ if (this._opcode === 2) {
1398
+ let data;
1399
+ if (this._binaryType === "nodebuffer") {
1400
+ data = concat(fragments, messageLength);
1401
+ } else if (this._binaryType === "arraybuffer") {
1402
+ data = toArrayBuffer(concat(fragments, messageLength));
1403
+ } else if (this._binaryType === "blob") {
1404
+ data = new Blob(fragments);
1405
+ } else {
1406
+ data = fragments;
1407
+ }
1408
+ if (this._allowSynchronousEvents) {
1409
+ this.emit("message", data, true);
1410
+ this._state = GET_INFO;
1411
+ } else {
1412
+ this._state = DEFER_EVENT;
1413
+ setImmediate(() => {
1414
+ this.emit("message", data, true);
1415
+ this._state = GET_INFO;
1416
+ this.startLoop(cb);
1417
+ });
1418
+ }
1419
+ } else {
1420
+ const buf = concat(fragments, messageLength);
1421
+ if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
1422
+ const error = this.createError(
1423
+ Error,
1424
+ "invalid UTF-8 sequence",
1425
+ true,
1426
+ 1007,
1427
+ "WS_ERR_INVALID_UTF8"
1428
+ );
1429
+ cb(error);
1430
+ return;
1431
+ }
1432
+ if (this._state === INFLATING || this._allowSynchronousEvents) {
1433
+ this.emit("message", buf, false);
1434
+ this._state = GET_INFO;
1435
+ } else {
1436
+ this._state = DEFER_EVENT;
1437
+ setImmediate(() => {
1438
+ this.emit("message", buf, false);
1439
+ this._state = GET_INFO;
1440
+ this.startLoop(cb);
1441
+ });
1442
+ }
1443
+ }
1444
+ }
1445
+ /**
1446
+ * Handles a control message.
1447
+ *
1448
+ * @param {Buffer} data Data to handle
1449
+ * @return {(Error|RangeError|undefined)} A possible error
1450
+ * @private
1451
+ */
1452
+ controlMessage(data, cb) {
1453
+ if (this._opcode === 8) {
1454
+ if (data.length === 0) {
1455
+ this._loop = false;
1456
+ this.emit("conclude", 1005, EMPTY_BUFFER2);
1457
+ this.end();
1458
+ } else {
1459
+ const code = data.readUInt16BE(0);
1460
+ if (!isValidStatusCode(code)) {
1461
+ const error = this.createError(
1462
+ RangeError,
1463
+ `invalid status code ${code}`,
1464
+ true,
1465
+ 1002,
1466
+ "WS_ERR_INVALID_CLOSE_CODE"
1467
+ );
1468
+ cb(error);
1469
+ return;
1470
+ }
1471
+ const buf = new FastBuffer(
1472
+ data.buffer,
1473
+ data.byteOffset + 2,
1474
+ data.length - 2
1475
+ );
1476
+ if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
1477
+ const error = this.createError(
1478
+ Error,
1479
+ "invalid UTF-8 sequence",
1480
+ true,
1481
+ 1007,
1482
+ "WS_ERR_INVALID_UTF8"
1483
+ );
1484
+ cb(error);
1485
+ return;
1486
+ }
1487
+ this._loop = false;
1488
+ this.emit("conclude", code, buf);
1489
+ this.end();
1490
+ }
1491
+ this._state = GET_INFO;
1492
+ return;
1493
+ }
1494
+ if (this._allowSynchronousEvents) {
1495
+ this.emit(this._opcode === 9 ? "ping" : "pong", data);
1496
+ this._state = GET_INFO;
1497
+ } else {
1498
+ this._state = DEFER_EVENT;
1499
+ setImmediate(() => {
1500
+ this.emit(this._opcode === 9 ? "ping" : "pong", data);
1501
+ this._state = GET_INFO;
1502
+ this.startLoop(cb);
1503
+ });
1504
+ }
1505
+ }
1506
+ /**
1507
+ * Builds an error object.
1508
+ *
1509
+ * @param {function(new:Error|RangeError)} ErrorCtor The error constructor
1510
+ * @param {String} message The error message
1511
+ * @param {Boolean} prefix Specifies whether or not to add a default prefix to
1512
+ * `message`
1513
+ * @param {Number} statusCode The status code
1514
+ * @param {String} errorCode The exposed error code
1515
+ * @return {(Error|RangeError)} The error
1516
+ * @private
1517
+ */
1518
+ createError(ErrorCtor, message, prefix, statusCode, errorCode) {
1519
+ this._loop = false;
1520
+ this._errored = true;
1521
+ const err = new ErrorCtor(
1522
+ prefix ? `Invalid WebSocket frame: ${message}` : message
1523
+ );
1524
+ Error.captureStackTrace(err, this.createError);
1525
+ err.code = errorCode;
1526
+ err[kStatusCode] = statusCode;
1527
+ return err;
1528
+ }
1529
+ };
1530
+ module.exports = Receiver2;
1531
+ }
1532
+ });
1533
+
1534
+ // node_modules/ws/lib/sender.js
1535
+ var require_sender = __commonJS({
1536
+ "node_modules/ws/lib/sender.js"(exports, module) {
1537
+ "use strict";
1538
+ var { Duplex } = __require("stream");
1539
+ var { randomFillSync } = __require("crypto");
1540
+ var {
1541
+ types: { isUint8Array }
1542
+ } = __require("util");
1543
+ var PerMessageDeflate2 = require_permessage_deflate();
1544
+ var { EMPTY_BUFFER: EMPTY_BUFFER2, kWebSocket, NOOP } = require_constants();
1545
+ var { isBlob, isValidStatusCode } = require_validation();
1546
+ var { mask: applyMask, toBuffer } = require_buffer_util();
1547
+ var kByteLength = /* @__PURE__ */ Symbol("kByteLength");
1548
+ var maskBuffer = Buffer.alloc(4);
1549
+ var RANDOM_POOL_SIZE = 8 * 1024;
1550
+ var randomPool;
1551
+ var randomPoolPointer = RANDOM_POOL_SIZE;
1552
+ var DEFAULT = 0;
1553
+ var DEFLATING = 1;
1554
+ var GET_BLOB_DATA = 2;
1555
+ var Sender2 = class _Sender {
1556
+ /**
1557
+ * Creates a Sender instance.
1558
+ *
1559
+ * @param {Duplex} socket The connection socket
1560
+ * @param {Object} [extensions] An object containing the negotiated extensions
1561
+ * @param {Function} [generateMask] The function used to generate the masking
1562
+ * key
1563
+ */
1564
+ constructor(socket, extensions, generateMask) {
1565
+ this._extensions = extensions || {};
1566
+ if (generateMask) {
1567
+ this._generateMask = generateMask;
1568
+ this._maskBuffer = Buffer.alloc(4);
1569
+ }
1570
+ this._socket = socket;
1571
+ this._firstFragment = true;
1572
+ this._compress = false;
1573
+ this._bufferedBytes = 0;
1574
+ this._queue = [];
1575
+ this._state = DEFAULT;
1576
+ this.onerror = NOOP;
1577
+ this[kWebSocket] = void 0;
1578
+ }
1579
+ /**
1580
+ * Frames a piece of data according to the HyBi WebSocket protocol.
1581
+ *
1582
+ * @param {(Buffer|String)} data The data to frame
1583
+ * @param {Object} options Options object
1584
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
1585
+ * FIN bit
1586
+ * @param {Function} [options.generateMask] The function used to generate the
1587
+ * masking key
1588
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1589
+ * `data`
1590
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
1591
+ * key
1592
+ * @param {Number} options.opcode The opcode
1593
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
1594
+ * modified
1595
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
1596
+ * RSV1 bit
1597
+ * @return {(Buffer|String)[]} The framed data
1598
+ * @public
1599
+ */
1600
+ static frame(data, options) {
1601
+ let mask;
1602
+ let merge = false;
1603
+ let offset = 2;
1604
+ let skipMasking = false;
1605
+ if (options.mask) {
1606
+ mask = options.maskBuffer || maskBuffer;
1607
+ if (options.generateMask) {
1608
+ options.generateMask(mask);
1609
+ } else {
1610
+ if (randomPoolPointer === RANDOM_POOL_SIZE) {
1611
+ if (randomPool === void 0) {
1612
+ randomPool = Buffer.alloc(RANDOM_POOL_SIZE);
1613
+ }
1614
+ randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);
1615
+ randomPoolPointer = 0;
1616
+ }
1617
+ mask[0] = randomPool[randomPoolPointer++];
1618
+ mask[1] = randomPool[randomPoolPointer++];
1619
+ mask[2] = randomPool[randomPoolPointer++];
1620
+ mask[3] = randomPool[randomPoolPointer++];
1621
+ }
1622
+ skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;
1623
+ offset = 6;
1624
+ }
1625
+ let dataLength;
1626
+ if (typeof data === "string") {
1627
+ if ((!options.mask || skipMasking) && options[kByteLength] !== void 0) {
1628
+ dataLength = options[kByteLength];
1629
+ } else {
1630
+ data = Buffer.from(data);
1631
+ dataLength = data.length;
1632
+ }
1633
+ } else {
1634
+ dataLength = data.length;
1635
+ merge = options.mask && options.readOnly && !skipMasking;
1636
+ }
1637
+ let payloadLength = dataLength;
1638
+ if (dataLength >= 65536) {
1639
+ offset += 8;
1640
+ payloadLength = 127;
1641
+ } else if (dataLength > 125) {
1642
+ offset += 2;
1643
+ payloadLength = 126;
1644
+ }
1645
+ const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);
1646
+ target[0] = options.fin ? options.opcode | 128 : options.opcode;
1647
+ if (options.rsv1) target[0] |= 64;
1648
+ target[1] = payloadLength;
1649
+ if (payloadLength === 126) {
1650
+ target.writeUInt16BE(dataLength, 2);
1651
+ } else if (payloadLength === 127) {
1652
+ target[2] = target[3] = 0;
1653
+ target.writeUIntBE(dataLength, 4, 6);
1654
+ }
1655
+ if (!options.mask) return [target, data];
1656
+ target[1] |= 128;
1657
+ target[offset - 4] = mask[0];
1658
+ target[offset - 3] = mask[1];
1659
+ target[offset - 2] = mask[2];
1660
+ target[offset - 1] = mask[3];
1661
+ if (skipMasking) return [target, data];
1662
+ if (merge) {
1663
+ applyMask(data, mask, target, offset, dataLength);
1664
+ return [target];
1665
+ }
1666
+ applyMask(data, mask, data, 0, dataLength);
1667
+ return [target, data];
1668
+ }
1669
+ /**
1670
+ * Sends a close message to the other peer.
1671
+ *
1672
+ * @param {Number} [code] The status code component of the body
1673
+ * @param {(String|Buffer)} [data] The message component of the body
1674
+ * @param {Boolean} [mask=false] Specifies whether or not to mask the message
1675
+ * @param {Function} [cb] Callback
1676
+ * @public
1677
+ */
1678
+ close(code, data, mask, cb) {
1679
+ let buf;
1680
+ if (code === void 0) {
1681
+ buf = EMPTY_BUFFER2;
1682
+ } else if (typeof code !== "number" || !isValidStatusCode(code)) {
1683
+ throw new TypeError("First argument must be a valid error code number");
1684
+ } else if (data === void 0 || !data.length) {
1685
+ buf = Buffer.allocUnsafe(2);
1686
+ buf.writeUInt16BE(code, 0);
1687
+ } else {
1688
+ const length = Buffer.byteLength(data);
1689
+ if (length > 123) {
1690
+ throw new RangeError("The message must not be greater than 123 bytes");
1691
+ }
1692
+ buf = Buffer.allocUnsafe(2 + length);
1693
+ buf.writeUInt16BE(code, 0);
1694
+ if (typeof data === "string") {
1695
+ buf.write(data, 2);
1696
+ } else if (isUint8Array(data)) {
1697
+ buf.set(data, 2);
1698
+ } else {
1699
+ throw new TypeError("Second argument must be a string or a Uint8Array");
1700
+ }
1701
+ }
1702
+ const options = {
1703
+ [kByteLength]: buf.length,
1704
+ fin: true,
1705
+ generateMask: this._generateMask,
1706
+ mask,
1707
+ maskBuffer: this._maskBuffer,
1708
+ opcode: 8,
1709
+ readOnly: false,
1710
+ rsv1: false
1711
+ };
1712
+ if (this._state !== DEFAULT) {
1713
+ this.enqueue([this.dispatch, buf, false, options, cb]);
1714
+ } else {
1715
+ this.sendFrame(_Sender.frame(buf, options), cb);
1716
+ }
1717
+ }
1718
+ /**
1719
+ * Sends a ping message to the other peer.
1720
+ *
1721
+ * @param {*} data The message to send
1722
+ * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
1723
+ * @param {Function} [cb] Callback
1724
+ * @public
1725
+ */
1726
+ ping(data, mask, cb) {
1727
+ let byteLength;
1728
+ let readOnly;
1729
+ if (typeof data === "string") {
1730
+ byteLength = Buffer.byteLength(data);
1731
+ readOnly = false;
1732
+ } else if (isBlob(data)) {
1733
+ byteLength = data.size;
1734
+ readOnly = false;
1735
+ } else {
1736
+ data = toBuffer(data);
1737
+ byteLength = data.length;
1738
+ readOnly = toBuffer.readOnly;
1739
+ }
1740
+ if (byteLength > 125) {
1741
+ throw new RangeError("The data size must not be greater than 125 bytes");
1742
+ }
1743
+ const options = {
1744
+ [kByteLength]: byteLength,
1745
+ fin: true,
1746
+ generateMask: this._generateMask,
1747
+ mask,
1748
+ maskBuffer: this._maskBuffer,
1749
+ opcode: 9,
1750
+ readOnly,
1751
+ rsv1: false
1752
+ };
1753
+ if (isBlob(data)) {
1754
+ if (this._state !== DEFAULT) {
1755
+ this.enqueue([this.getBlobData, data, false, options, cb]);
1756
+ } else {
1757
+ this.getBlobData(data, false, options, cb);
1758
+ }
1759
+ } else if (this._state !== DEFAULT) {
1760
+ this.enqueue([this.dispatch, data, false, options, cb]);
1761
+ } else {
1762
+ this.sendFrame(_Sender.frame(data, options), cb);
1763
+ }
1764
+ }
1765
+ /**
1766
+ * Sends a pong message to the other peer.
1767
+ *
1768
+ * @param {*} data The message to send
1769
+ * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
1770
+ * @param {Function} [cb] Callback
1771
+ * @public
1772
+ */
1773
+ pong(data, mask, cb) {
1774
+ let byteLength;
1775
+ let readOnly;
1776
+ if (typeof data === "string") {
1777
+ byteLength = Buffer.byteLength(data);
1778
+ readOnly = false;
1779
+ } else if (isBlob(data)) {
1780
+ byteLength = data.size;
1781
+ readOnly = false;
1782
+ } else {
1783
+ data = toBuffer(data);
1784
+ byteLength = data.length;
1785
+ readOnly = toBuffer.readOnly;
1786
+ }
1787
+ if (byteLength > 125) {
1788
+ throw new RangeError("The data size must not be greater than 125 bytes");
1789
+ }
1790
+ const options = {
1791
+ [kByteLength]: byteLength,
1792
+ fin: true,
1793
+ generateMask: this._generateMask,
1794
+ mask,
1795
+ maskBuffer: this._maskBuffer,
1796
+ opcode: 10,
1797
+ readOnly,
1798
+ rsv1: false
1799
+ };
1800
+ if (isBlob(data)) {
1801
+ if (this._state !== DEFAULT) {
1802
+ this.enqueue([this.getBlobData, data, false, options, cb]);
1803
+ } else {
1804
+ this.getBlobData(data, false, options, cb);
1805
+ }
1806
+ } else if (this._state !== DEFAULT) {
1807
+ this.enqueue([this.dispatch, data, false, options, cb]);
1808
+ } else {
1809
+ this.sendFrame(_Sender.frame(data, options), cb);
1810
+ }
1811
+ }
1812
+ /**
1813
+ * Sends a data message to the other peer.
1814
+ *
1815
+ * @param {*} data The message to send
1816
+ * @param {Object} options Options object
1817
+ * @param {Boolean} [options.binary=false] Specifies whether `data` is binary
1818
+ * or text
1819
+ * @param {Boolean} [options.compress=false] Specifies whether or not to
1820
+ * compress `data`
1821
+ * @param {Boolean} [options.fin=false] Specifies whether the fragment is the
1822
+ * last one
1823
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1824
+ * `data`
1825
+ * @param {Function} [cb] Callback
1826
+ * @public
1827
+ */
1828
+ send(data, options, cb) {
1829
+ const perMessageDeflate = this._extensions[PerMessageDeflate2.extensionName];
1830
+ let opcode = options.binary ? 2 : 1;
1831
+ let rsv1 = options.compress;
1832
+ let byteLength;
1833
+ let readOnly;
1834
+ if (typeof data === "string") {
1835
+ byteLength = Buffer.byteLength(data);
1836
+ readOnly = false;
1837
+ } else if (isBlob(data)) {
1838
+ byteLength = data.size;
1839
+ readOnly = false;
1840
+ } else {
1841
+ data = toBuffer(data);
1842
+ byteLength = data.length;
1843
+ readOnly = toBuffer.readOnly;
1844
+ }
1845
+ if (this._firstFragment) {
1846
+ this._firstFragment = false;
1847
+ if (rsv1 && perMessageDeflate && perMessageDeflate.params[perMessageDeflate._isServer ? "server_no_context_takeover" : "client_no_context_takeover"]) {
1848
+ rsv1 = byteLength >= perMessageDeflate._threshold;
1849
+ }
1850
+ this._compress = rsv1;
1851
+ } else {
1852
+ rsv1 = false;
1853
+ opcode = 0;
1854
+ }
1855
+ if (options.fin) this._firstFragment = true;
1856
+ const opts = {
1857
+ [kByteLength]: byteLength,
1858
+ fin: options.fin,
1859
+ generateMask: this._generateMask,
1860
+ mask: options.mask,
1861
+ maskBuffer: this._maskBuffer,
1862
+ opcode,
1863
+ readOnly,
1864
+ rsv1
1865
+ };
1866
+ if (isBlob(data)) {
1867
+ if (this._state !== DEFAULT) {
1868
+ this.enqueue([this.getBlobData, data, this._compress, opts, cb]);
1869
+ } else {
1870
+ this.getBlobData(data, this._compress, opts, cb);
1871
+ }
1872
+ } else if (this._state !== DEFAULT) {
1873
+ this.enqueue([this.dispatch, data, this._compress, opts, cb]);
1874
+ } else {
1875
+ this.dispatch(data, this._compress, opts, cb);
1876
+ }
1877
+ }
1878
+ /**
1879
+ * Gets the contents of a blob as binary data.
1880
+ *
1881
+ * @param {Blob} blob The blob
1882
+ * @param {Boolean} [compress=false] Specifies whether or not to compress
1883
+ * the data
1884
+ * @param {Object} options Options object
1885
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
1886
+ * FIN bit
1887
+ * @param {Function} [options.generateMask] The function used to generate the
1888
+ * masking key
1889
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1890
+ * `data`
1891
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
1892
+ * key
1893
+ * @param {Number} options.opcode The opcode
1894
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
1895
+ * modified
1896
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
1897
+ * RSV1 bit
1898
+ * @param {Function} [cb] Callback
1899
+ * @private
1900
+ */
1901
+ getBlobData(blob, compress, options, cb) {
1902
+ this._bufferedBytes += options[kByteLength];
1903
+ this._state = GET_BLOB_DATA;
1904
+ blob.arrayBuffer().then((arrayBuffer) => {
1905
+ if (this._socket.destroyed) {
1906
+ const err = new Error(
1907
+ "The socket was closed while the blob was being read"
1908
+ );
1909
+ process.nextTick(callCallbacks, this, err, cb);
1910
+ return;
1911
+ }
1912
+ this._bufferedBytes -= options[kByteLength];
1913
+ const data = toBuffer(arrayBuffer);
1914
+ if (!compress) {
1915
+ this._state = DEFAULT;
1916
+ this.sendFrame(_Sender.frame(data, options), cb);
1917
+ this.dequeue();
1918
+ } else {
1919
+ this.dispatch(data, compress, options, cb);
1920
+ }
1921
+ }).catch((err) => {
1922
+ process.nextTick(onError, this, err, cb);
1923
+ });
1924
+ }
1925
+ /**
1926
+ * Dispatches a message.
1927
+ *
1928
+ * @param {(Buffer|String)} data The message to send
1929
+ * @param {Boolean} [compress=false] Specifies whether or not to compress
1930
+ * `data`
1931
+ * @param {Object} options Options object
1932
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
1933
+ * FIN bit
1934
+ * @param {Function} [options.generateMask] The function used to generate the
1935
+ * masking key
1936
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1937
+ * `data`
1938
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
1939
+ * key
1940
+ * @param {Number} options.opcode The opcode
1941
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
1942
+ * modified
1943
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
1944
+ * RSV1 bit
1945
+ * @param {Function} [cb] Callback
1946
+ * @private
1947
+ */
1948
+ dispatch(data, compress, options, cb) {
1949
+ if (!compress) {
1950
+ this.sendFrame(_Sender.frame(data, options), cb);
1951
+ return;
1952
+ }
1953
+ const perMessageDeflate = this._extensions[PerMessageDeflate2.extensionName];
1954
+ this._bufferedBytes += options[kByteLength];
1955
+ this._state = DEFLATING;
1956
+ perMessageDeflate.compress(data, options.fin, (_, buf) => {
1957
+ if (this._socket.destroyed) {
1958
+ const err = new Error(
1959
+ "The socket was closed while data was being compressed"
1960
+ );
1961
+ callCallbacks(this, err, cb);
1962
+ return;
1963
+ }
1964
+ this._bufferedBytes -= options[kByteLength];
1965
+ this._state = DEFAULT;
1966
+ options.readOnly = false;
1967
+ this.sendFrame(_Sender.frame(buf, options), cb);
1968
+ this.dequeue();
1969
+ });
1970
+ }
1971
+ /**
1972
+ * Executes queued send operations.
1973
+ *
1974
+ * @private
1975
+ */
1976
+ dequeue() {
1977
+ while (this._state === DEFAULT && this._queue.length) {
1978
+ const params = this._queue.shift();
1979
+ this._bufferedBytes -= params[3][kByteLength];
1980
+ Reflect.apply(params[0], this, params.slice(1));
1981
+ }
1982
+ }
1983
+ /**
1984
+ * Enqueues a send operation.
1985
+ *
1986
+ * @param {Array} params Send operation parameters.
1987
+ * @private
1988
+ */
1989
+ enqueue(params) {
1990
+ this._bufferedBytes += params[3][kByteLength];
1991
+ this._queue.push(params);
1992
+ }
1993
+ /**
1994
+ * Sends a frame.
1995
+ *
1996
+ * @param {(Buffer | String)[]} list The frame to send
1997
+ * @param {Function} [cb] Callback
1998
+ * @private
1999
+ */
2000
+ sendFrame(list, cb) {
2001
+ if (list.length === 2) {
2002
+ this._socket.cork();
2003
+ this._socket.write(list[0]);
2004
+ this._socket.write(list[1], cb);
2005
+ this._socket.uncork();
2006
+ } else {
2007
+ this._socket.write(list[0], cb);
2008
+ }
2009
+ }
2010
+ };
2011
+ module.exports = Sender2;
2012
+ function callCallbacks(sender, err, cb) {
2013
+ if (typeof cb === "function") cb(err);
2014
+ for (let i3 = 0; i3 < sender._queue.length; i3++) {
2015
+ const params = sender._queue[i3];
2016
+ const callback = params[params.length - 1];
2017
+ if (typeof callback === "function") callback(err);
2018
+ }
2019
+ }
2020
+ function onError(sender, err, cb) {
2021
+ callCallbacks(sender, err, cb);
2022
+ sender.onerror(err);
2023
+ }
2024
+ }
2025
+ });
2026
+
2027
+ // node_modules/ws/lib/event-target.js
2028
+ var require_event_target = __commonJS({
2029
+ "node_modules/ws/lib/event-target.js"(exports, module) {
2030
+ "use strict";
2031
+ var { kForOnEventAttribute, kListener } = require_constants();
2032
+ var kCode = /* @__PURE__ */ Symbol("kCode");
2033
+ var kData = /* @__PURE__ */ Symbol("kData");
2034
+ var kError = /* @__PURE__ */ Symbol("kError");
2035
+ var kMessage = /* @__PURE__ */ Symbol("kMessage");
2036
+ var kReason = /* @__PURE__ */ Symbol("kReason");
2037
+ var kTarget = /* @__PURE__ */ Symbol("kTarget");
2038
+ var kType = /* @__PURE__ */ Symbol("kType");
2039
+ var kWasClean = /* @__PURE__ */ Symbol("kWasClean");
2040
+ var Event = class {
2041
+ /**
2042
+ * Create a new `Event`.
2043
+ *
2044
+ * @param {String} type The name of the event
2045
+ * @throws {TypeError} If the `type` argument is not specified
2046
+ */
2047
+ constructor(type) {
2048
+ this[kTarget] = null;
2049
+ this[kType] = type;
2050
+ }
2051
+ /**
2052
+ * @type {*}
2053
+ */
2054
+ get target() {
2055
+ return this[kTarget];
2056
+ }
2057
+ /**
2058
+ * @type {String}
2059
+ */
2060
+ get type() {
2061
+ return this[kType];
2062
+ }
2063
+ };
2064
+ Object.defineProperty(Event.prototype, "target", { enumerable: true });
2065
+ Object.defineProperty(Event.prototype, "type", { enumerable: true });
2066
+ var CloseEvent = class extends Event {
2067
+ /**
2068
+ * Create a new `CloseEvent`.
2069
+ *
2070
+ * @param {String} type The name of the event
2071
+ * @param {Object} [options] A dictionary object that allows for setting
2072
+ * attributes via object members of the same name
2073
+ * @param {Number} [options.code=0] The status code explaining why the
2074
+ * connection was closed
2075
+ * @param {String} [options.reason=''] A human-readable string explaining why
2076
+ * the connection was closed
2077
+ * @param {Boolean} [options.wasClean=false] Indicates whether or not the
2078
+ * connection was cleanly closed
2079
+ */
2080
+ constructor(type, options = {}) {
2081
+ super(type);
2082
+ this[kCode] = options.code === void 0 ? 0 : options.code;
2083
+ this[kReason] = options.reason === void 0 ? "" : options.reason;
2084
+ this[kWasClean] = options.wasClean === void 0 ? false : options.wasClean;
2085
+ }
2086
+ /**
2087
+ * @type {Number}
2088
+ */
2089
+ get code() {
2090
+ return this[kCode];
2091
+ }
2092
+ /**
2093
+ * @type {String}
2094
+ */
2095
+ get reason() {
2096
+ return this[kReason];
2097
+ }
2098
+ /**
2099
+ * @type {Boolean}
2100
+ */
2101
+ get wasClean() {
2102
+ return this[kWasClean];
2103
+ }
2104
+ };
2105
+ Object.defineProperty(CloseEvent.prototype, "code", { enumerable: true });
2106
+ Object.defineProperty(CloseEvent.prototype, "reason", { enumerable: true });
2107
+ Object.defineProperty(CloseEvent.prototype, "wasClean", { enumerable: true });
2108
+ var ErrorEvent = class extends Event {
2109
+ /**
2110
+ * Create a new `ErrorEvent`.
2111
+ *
2112
+ * @param {String} type The name of the event
2113
+ * @param {Object} [options] A dictionary object that allows for setting
2114
+ * attributes via object members of the same name
2115
+ * @param {*} [options.error=null] The error that generated this event
2116
+ * @param {String} [options.message=''] The error message
2117
+ */
2118
+ constructor(type, options = {}) {
2119
+ super(type);
2120
+ this[kError] = options.error === void 0 ? null : options.error;
2121
+ this[kMessage] = options.message === void 0 ? "" : options.message;
2122
+ }
2123
+ /**
2124
+ * @type {*}
2125
+ */
2126
+ get error() {
2127
+ return this[kError];
2128
+ }
2129
+ /**
2130
+ * @type {String}
2131
+ */
2132
+ get message() {
2133
+ return this[kMessage];
2134
+ }
2135
+ };
2136
+ Object.defineProperty(ErrorEvent.prototype, "error", { enumerable: true });
2137
+ Object.defineProperty(ErrorEvent.prototype, "message", { enumerable: true });
2138
+ var MessageEvent = class extends Event {
2139
+ /**
2140
+ * Create a new `MessageEvent`.
2141
+ *
2142
+ * @param {String} type The name of the event
2143
+ * @param {Object} [options] A dictionary object that allows for setting
2144
+ * attributes via object members of the same name
2145
+ * @param {*} [options.data=null] The message content
2146
+ */
2147
+ constructor(type, options = {}) {
2148
+ super(type);
2149
+ this[kData] = options.data === void 0 ? null : options.data;
2150
+ }
2151
+ /**
2152
+ * @type {*}
2153
+ */
2154
+ get data() {
2155
+ return this[kData];
2156
+ }
2157
+ };
2158
+ Object.defineProperty(MessageEvent.prototype, "data", { enumerable: true });
2159
+ var EventTarget = {
2160
+ /**
2161
+ * Register an event listener.
2162
+ *
2163
+ * @param {String} type A string representing the event type to listen for
2164
+ * @param {(Function|Object)} handler The listener to add
2165
+ * @param {Object} [options] An options object specifies characteristics about
2166
+ * the event listener
2167
+ * @param {Boolean} [options.once=false] A `Boolean` indicating that the
2168
+ * listener should be invoked at most once after being added. If `true`,
2169
+ * the listener would be automatically removed when invoked.
2170
+ * @public
2171
+ */
2172
+ addEventListener(type, handler, options = {}) {
2173
+ for (const listener of this.listeners(type)) {
2174
+ if (!options[kForOnEventAttribute] && listener[kListener] === handler && !listener[kForOnEventAttribute]) {
2175
+ return;
2176
+ }
2177
+ }
2178
+ let wrapper;
2179
+ if (type === "message") {
2180
+ wrapper = function onMessage(data, isBinary) {
2181
+ const event = new MessageEvent("message", {
2182
+ data: isBinary ? data : data.toString()
2183
+ });
2184
+ event[kTarget] = this;
2185
+ callListener(handler, this, event);
2186
+ };
2187
+ } else if (type === "close") {
2188
+ wrapper = function onClose(code, message) {
2189
+ const event = new CloseEvent("close", {
2190
+ code,
2191
+ reason: message.toString(),
2192
+ wasClean: this._closeFrameReceived && this._closeFrameSent
2193
+ });
2194
+ event[kTarget] = this;
2195
+ callListener(handler, this, event);
2196
+ };
2197
+ } else if (type === "error") {
2198
+ wrapper = function onError(error) {
2199
+ const event = new ErrorEvent("error", {
2200
+ error,
2201
+ message: error.message
2202
+ });
2203
+ event[kTarget] = this;
2204
+ callListener(handler, this, event);
2205
+ };
2206
+ } else if (type === "open") {
2207
+ wrapper = function onOpen() {
2208
+ const event = new Event("open");
2209
+ event[kTarget] = this;
2210
+ callListener(handler, this, event);
2211
+ };
2212
+ } else {
2213
+ return;
2214
+ }
2215
+ wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];
2216
+ wrapper[kListener] = handler;
2217
+ if (options.once) {
2218
+ this.once(type, wrapper);
2219
+ } else {
2220
+ this.on(type, wrapper);
2221
+ }
2222
+ },
2223
+ /**
2224
+ * Remove an event listener.
2225
+ *
2226
+ * @param {String} type A string representing the event type to remove
2227
+ * @param {(Function|Object)} handler The listener to remove
2228
+ * @public
2229
+ */
2230
+ removeEventListener(type, handler) {
2231
+ for (const listener of this.listeners(type)) {
2232
+ if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {
2233
+ this.removeListener(type, listener);
2234
+ break;
2235
+ }
2236
+ }
2237
+ }
2238
+ };
2239
+ module.exports = {
2240
+ CloseEvent,
2241
+ ErrorEvent,
2242
+ Event,
2243
+ EventTarget,
2244
+ MessageEvent
2245
+ };
2246
+ function callListener(listener, thisArg, event) {
2247
+ if (typeof listener === "object" && listener.handleEvent) {
2248
+ listener.handleEvent.call(listener, event);
2249
+ } else {
2250
+ listener.call(thisArg, event);
2251
+ }
2252
+ }
2253
+ }
2254
+ });
2255
+
2256
+ // node_modules/ws/lib/extension.js
2257
+ var require_extension = __commonJS({
2258
+ "node_modules/ws/lib/extension.js"(exports, module) {
2259
+ "use strict";
2260
+ var { tokenChars } = require_validation();
2261
+ function push(dest, name, elem) {
2262
+ if (dest[name] === void 0) dest[name] = [elem];
2263
+ else dest[name].push(elem);
2264
+ }
2265
+ function parse5(header) {
2266
+ const offers = /* @__PURE__ */ Object.create(null);
2267
+ let params = /* @__PURE__ */ Object.create(null);
2268
+ let mustUnescape = false;
2269
+ let isEscaping = false;
2270
+ let inQuotes = false;
2271
+ let extensionName;
2272
+ let paramName;
2273
+ let start = -1;
2274
+ let code = -1;
2275
+ let end = -1;
2276
+ let i3 = 0;
2277
+ for (; i3 < header.length; i3++) {
2278
+ code = header.charCodeAt(i3);
2279
+ if (extensionName === void 0) {
2280
+ if (end === -1 && tokenChars[code] === 1) {
2281
+ if (start === -1) start = i3;
2282
+ } else if (i3 !== 0 && (code === 32 || code === 9)) {
2283
+ if (end === -1 && start !== -1) end = i3;
2284
+ } else if (code === 59 || code === 44) {
2285
+ if (start === -1) {
2286
+ throw new SyntaxError(`Unexpected character at index ${i3}`);
2287
+ }
2288
+ if (end === -1) end = i3;
2289
+ const name = header.slice(start, end);
2290
+ if (code === 44) {
2291
+ push(offers, name, params);
2292
+ params = /* @__PURE__ */ Object.create(null);
2293
+ } else {
2294
+ extensionName = name;
2295
+ }
2296
+ start = end = -1;
2297
+ } else {
2298
+ throw new SyntaxError(`Unexpected character at index ${i3}`);
2299
+ }
2300
+ } else if (paramName === void 0) {
2301
+ if (end === -1 && tokenChars[code] === 1) {
2302
+ if (start === -1) start = i3;
2303
+ } else if (code === 32 || code === 9) {
2304
+ if (end === -1 && start !== -1) end = i3;
2305
+ } else if (code === 59 || code === 44) {
2306
+ if (start === -1) {
2307
+ throw new SyntaxError(`Unexpected character at index ${i3}`);
2308
+ }
2309
+ if (end === -1) end = i3;
2310
+ push(params, header.slice(start, end), true);
2311
+ if (code === 44) {
2312
+ push(offers, extensionName, params);
2313
+ params = /* @__PURE__ */ Object.create(null);
2314
+ extensionName = void 0;
2315
+ }
2316
+ start = end = -1;
2317
+ } else if (code === 61 && start !== -1 && end === -1) {
2318
+ paramName = header.slice(start, i3);
2319
+ start = end = -1;
2320
+ } else {
2321
+ throw new SyntaxError(`Unexpected character at index ${i3}`);
2322
+ }
2323
+ } else {
2324
+ if (isEscaping) {
2325
+ if (tokenChars[code] !== 1) {
2326
+ throw new SyntaxError(`Unexpected character at index ${i3}`);
2327
+ }
2328
+ if (start === -1) start = i3;
2329
+ else if (!mustUnescape) mustUnescape = true;
2330
+ isEscaping = false;
2331
+ } else if (inQuotes) {
2332
+ if (tokenChars[code] === 1) {
2333
+ if (start === -1) start = i3;
2334
+ } else if (code === 34 && start !== -1) {
2335
+ inQuotes = false;
2336
+ end = i3;
2337
+ } else if (code === 92) {
2338
+ isEscaping = true;
2339
+ } else {
2340
+ throw new SyntaxError(`Unexpected character at index ${i3}`);
2341
+ }
2342
+ } else if (code === 34 && header.charCodeAt(i3 - 1) === 61) {
2343
+ inQuotes = true;
2344
+ } else if (end === -1 && tokenChars[code] === 1) {
2345
+ if (start === -1) start = i3;
2346
+ } else if (start !== -1 && (code === 32 || code === 9)) {
2347
+ if (end === -1) end = i3;
2348
+ } else if (code === 59 || code === 44) {
2349
+ if (start === -1) {
2350
+ throw new SyntaxError(`Unexpected character at index ${i3}`);
2351
+ }
2352
+ if (end === -1) end = i3;
2353
+ let value = header.slice(start, end);
2354
+ if (mustUnescape) {
2355
+ value = value.replace(/\\/g, "");
2356
+ mustUnescape = false;
2357
+ }
2358
+ push(params, paramName, value);
2359
+ if (code === 44) {
2360
+ push(offers, extensionName, params);
2361
+ params = /* @__PURE__ */ Object.create(null);
2362
+ extensionName = void 0;
2363
+ }
2364
+ paramName = void 0;
2365
+ start = end = -1;
2366
+ } else {
2367
+ throw new SyntaxError(`Unexpected character at index ${i3}`);
2368
+ }
2369
+ }
2370
+ }
2371
+ if (start === -1 || inQuotes || code === 32 || code === 9) {
2372
+ throw new SyntaxError("Unexpected end of input");
2373
+ }
2374
+ if (end === -1) end = i3;
2375
+ const token = header.slice(start, end);
2376
+ if (extensionName === void 0) {
2377
+ push(offers, token, params);
2378
+ } else {
2379
+ if (paramName === void 0) {
2380
+ push(params, token, true);
2381
+ } else if (mustUnescape) {
2382
+ push(params, paramName, token.replace(/\\/g, ""));
2383
+ } else {
2384
+ push(params, paramName, token);
2385
+ }
2386
+ push(offers, extensionName, params);
2387
+ }
2388
+ return offers;
2389
+ }
2390
+ function format(extensions) {
2391
+ return Object.keys(extensions).map((extension2) => {
2392
+ let configurations = extensions[extension2];
2393
+ if (!Array.isArray(configurations)) configurations = [configurations];
2394
+ return configurations.map((params) => {
2395
+ return [extension2].concat(
2396
+ Object.keys(params).map((k) => {
2397
+ let values = params[k];
2398
+ if (!Array.isArray(values)) values = [values];
2399
+ return values.map((v) => v === true ? k : `${k}=${v}`).join("; ");
2400
+ })
2401
+ ).join("; ");
2402
+ }).join(", ");
2403
+ }).join(", ");
2404
+ }
2405
+ module.exports = { format, parse: parse5 };
2406
+ }
2407
+ });
2408
+
2409
+ // node_modules/ws/lib/websocket.js
2410
+ var require_websocket = __commonJS({
2411
+ "node_modules/ws/lib/websocket.js"(exports, module) {
2412
+ "use strict";
2413
+ var EventEmitter2 = __require("events");
2414
+ var https = __require("https");
2415
+ var http = __require("http");
2416
+ var net = __require("net");
2417
+ var tls = __require("tls");
2418
+ var { randomBytes: randomBytes7, createHash: createHash7 } = __require("crypto");
2419
+ var { Duplex, Readable } = __require("stream");
2420
+ var { URL: URL2 } = __require("url");
2421
+ var PerMessageDeflate2 = require_permessage_deflate();
2422
+ var Receiver2 = require_receiver();
2423
+ var Sender2 = require_sender();
2424
+ var { isBlob } = require_validation();
2425
+ var {
2426
+ BINARY_TYPES,
2427
+ CLOSE_TIMEOUT,
2428
+ EMPTY_BUFFER: EMPTY_BUFFER2,
2429
+ GUID,
2430
+ kForOnEventAttribute,
2431
+ kListener,
2432
+ kStatusCode,
2433
+ kWebSocket,
2434
+ NOOP
2435
+ } = require_constants();
2436
+ var {
2437
+ EventTarget: { addEventListener, removeEventListener }
2438
+ } = require_event_target();
2439
+ var { format, parse: parse5 } = require_extension();
2440
+ var { toBuffer } = require_buffer_util();
2441
+ var kAborted = /* @__PURE__ */ Symbol("kAborted");
2442
+ var protocolVersions = [8, 13];
2443
+ var readyStates = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"];
2444
+ var subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
2445
+ var WebSocket3 = class _WebSocket3 extends EventEmitter2 {
2446
+ /**
2447
+ * Create a new `WebSocket`.
2448
+ *
2449
+ * @param {(String|URL)} address The URL to which to connect
2450
+ * @param {(String|String[])} [protocols] The subprotocols
2451
+ * @param {Object} [options] Connection options
2452
+ */
2453
+ constructor(address, protocols, options) {
2454
+ super();
2455
+ this._binaryType = BINARY_TYPES[0];
2456
+ this._closeCode = 1006;
2457
+ this._closeFrameReceived = false;
2458
+ this._closeFrameSent = false;
2459
+ this._closeMessage = EMPTY_BUFFER2;
2460
+ this._closeTimer = null;
2461
+ this._errorEmitted = false;
2462
+ this._extensions = {};
2463
+ this._paused = false;
2464
+ this._protocol = "";
2465
+ this._readyState = _WebSocket3.CONNECTING;
2466
+ this._receiver = null;
2467
+ this._sender = null;
2468
+ this._socket = null;
2469
+ if (address !== null) {
2470
+ this._bufferedAmount = 0;
2471
+ this._isServer = false;
2472
+ this._redirects = 0;
2473
+ if (protocols === void 0) {
2474
+ protocols = [];
2475
+ } else if (!Array.isArray(protocols)) {
2476
+ if (typeof protocols === "object" && protocols !== null) {
2477
+ options = protocols;
2478
+ protocols = [];
2479
+ } else {
2480
+ protocols = [protocols];
2481
+ }
2482
+ }
2483
+ initAsClient(this, address, protocols, options);
2484
+ } else {
2485
+ this._autoPong = options.autoPong;
2486
+ this._closeTimeout = options.closeTimeout;
2487
+ this._isServer = true;
2488
+ }
2489
+ }
2490
+ /**
2491
+ * For historical reasons, the custom "nodebuffer" type is used by the default
2492
+ * instead of "blob".
2493
+ *
2494
+ * @type {String}
2495
+ */
2496
+ get binaryType() {
2497
+ return this._binaryType;
2498
+ }
2499
+ set binaryType(type) {
2500
+ if (!BINARY_TYPES.includes(type)) return;
2501
+ this._binaryType = type;
2502
+ if (this._receiver) this._receiver._binaryType = type;
2503
+ }
2504
+ /**
2505
+ * @type {Number}
2506
+ */
2507
+ get bufferedAmount() {
2508
+ if (!this._socket) return this._bufferedAmount;
2509
+ return this._socket._writableState.length + this._sender._bufferedBytes;
2510
+ }
2511
+ /**
2512
+ * @type {String}
2513
+ */
2514
+ get extensions() {
2515
+ return Object.keys(this._extensions).join();
2516
+ }
2517
+ /**
2518
+ * @type {Boolean}
2519
+ */
2520
+ get isPaused() {
2521
+ return this._paused;
2522
+ }
2523
+ /**
2524
+ * @type {Function}
2525
+ */
2526
+ /* istanbul ignore next */
2527
+ get onclose() {
2528
+ return null;
2529
+ }
2530
+ /**
2531
+ * @type {Function}
2532
+ */
2533
+ /* istanbul ignore next */
2534
+ get onerror() {
2535
+ return null;
2536
+ }
2537
+ /**
2538
+ * @type {Function}
2539
+ */
2540
+ /* istanbul ignore next */
2541
+ get onopen() {
2542
+ return null;
2543
+ }
2544
+ /**
2545
+ * @type {Function}
2546
+ */
2547
+ /* istanbul ignore next */
2548
+ get onmessage() {
2549
+ return null;
2550
+ }
2551
+ /**
2552
+ * @type {String}
2553
+ */
2554
+ get protocol() {
2555
+ return this._protocol;
2556
+ }
2557
+ /**
2558
+ * @type {Number}
2559
+ */
2560
+ get readyState() {
2561
+ return this._readyState;
2562
+ }
2563
+ /**
2564
+ * @type {String}
2565
+ */
2566
+ get url() {
2567
+ return this._url;
2568
+ }
2569
+ /**
2570
+ * Set up the socket and the internal resources.
2571
+ *
2572
+ * @param {Duplex} socket The network socket between the server and client
2573
+ * @param {Buffer} head The first packet of the upgraded stream
2574
+ * @param {Object} options Options object
2575
+ * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether
2576
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
2577
+ * multiple times in the same tick
2578
+ * @param {Function} [options.generateMask] The function used to generate the
2579
+ * masking key
2580
+ * @param {Number} [options.maxBufferedChunks=0] The maximum number of
2581
+ * buffered data chunks
2582
+ * @param {Number} [options.maxFragments=0] The maximum number of message
2583
+ * fragments
2584
+ * @param {Number} [options.maxPayload=0] The maximum allowed message size
2585
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
2586
+ * not to skip UTF-8 validation for text and close messages
2587
+ * @private
2588
+ */
2589
+ setSocket(socket, head, options) {
2590
+ const receiver = new Receiver2({
2591
+ allowSynchronousEvents: options.allowSynchronousEvents,
2592
+ binaryType: this.binaryType,
2593
+ extensions: this._extensions,
2594
+ isServer: this._isServer,
2595
+ maxBufferedChunks: options.maxBufferedChunks,
2596
+ maxFragments: options.maxFragments,
2597
+ maxPayload: options.maxPayload,
2598
+ skipUTF8Validation: options.skipUTF8Validation
2599
+ });
2600
+ const sender = new Sender2(socket, this._extensions, options.generateMask);
2601
+ this._receiver = receiver;
2602
+ this._sender = sender;
2603
+ this._socket = socket;
2604
+ receiver[kWebSocket] = this;
2605
+ sender[kWebSocket] = this;
2606
+ socket[kWebSocket] = this;
2607
+ receiver.on("conclude", receiverOnConclude);
2608
+ receiver.on("drain", receiverOnDrain);
2609
+ receiver.on("error", receiverOnError);
2610
+ receiver.on("message", receiverOnMessage);
2611
+ receiver.on("ping", receiverOnPing);
2612
+ receiver.on("pong", receiverOnPong);
2613
+ sender.onerror = senderOnError;
2614
+ if (socket.setTimeout) socket.setTimeout(0);
2615
+ if (socket.setNoDelay) socket.setNoDelay();
2616
+ if (head.length > 0) socket.unshift(head);
2617
+ socket.on("close", socketOnClose);
2618
+ socket.on("data", socketOnData);
2619
+ socket.on("end", socketOnEnd);
2620
+ socket.on("error", socketOnError);
2621
+ this._readyState = _WebSocket3.OPEN;
2622
+ this.emit("open");
2623
+ }
2624
+ /**
2625
+ * Emit the `'close'` event.
2626
+ *
2627
+ * @private
2628
+ */
2629
+ emitClose() {
2630
+ if (!this._socket) {
2631
+ this._readyState = _WebSocket3.CLOSED;
2632
+ this.emit("close", this._closeCode, this._closeMessage);
2633
+ return;
2634
+ }
2635
+ if (this._extensions[PerMessageDeflate2.extensionName]) {
2636
+ this._extensions[PerMessageDeflate2.extensionName].cleanup();
2637
+ }
2638
+ this._receiver.removeAllListeners();
2639
+ this._readyState = _WebSocket3.CLOSED;
2640
+ this.emit("close", this._closeCode, this._closeMessage);
2641
+ }
2642
+ /**
2643
+ * Start a closing handshake.
2644
+ *
2645
+ * +----------+ +-----------+ +----------+
2646
+ * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -
2647
+ * | +----------+ +-----------+ +----------+ |
2648
+ * +----------+ +-----------+ |
2649
+ * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING
2650
+ * +----------+ +-----------+ |
2651
+ * | | | +---+ |
2652
+ * +------------------------+-->|fin| - - - -
2653
+ * | +---+ | +---+
2654
+ * - - - - -|fin|<---------------------+
2655
+ * +---+
2656
+ *
2657
+ * @param {Number} [code] Status code explaining why the connection is closing
2658
+ * @param {(String|Buffer)} [data] The reason why the connection is
2659
+ * closing
2660
+ * @public
2661
+ */
2662
+ close(code, data) {
2663
+ if (this.readyState === _WebSocket3.CLOSED) return;
2664
+ if (this.readyState === _WebSocket3.CONNECTING) {
2665
+ const msg = "WebSocket was closed before the connection was established";
2666
+ abortHandshake(this, this._req, msg);
2667
+ return;
2668
+ }
2669
+ if (this.readyState === _WebSocket3.CLOSING) {
2670
+ if (this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted)) {
2671
+ this._socket.end();
2672
+ }
2673
+ return;
2674
+ }
2675
+ this._readyState = _WebSocket3.CLOSING;
2676
+ this._sender.close(code, data, !this._isServer, (err) => {
2677
+ if (err) return;
2678
+ this._closeFrameSent = true;
2679
+ if (this._closeFrameReceived || this._receiver._writableState.errorEmitted) {
2680
+ this._socket.end();
2681
+ }
2682
+ });
2683
+ setCloseTimer(this);
2684
+ }
2685
+ /**
2686
+ * Pause the socket.
2687
+ *
2688
+ * @public
2689
+ */
2690
+ pause() {
2691
+ if (this.readyState === _WebSocket3.CONNECTING || this.readyState === _WebSocket3.CLOSED) {
2692
+ return;
2693
+ }
2694
+ this._paused = true;
2695
+ this._socket.pause();
2696
+ }
2697
+ /**
2698
+ * Send a ping.
2699
+ *
2700
+ * @param {*} [data] The data to send
2701
+ * @param {Boolean} [mask] Indicates whether or not to mask `data`
2702
+ * @param {Function} [cb] Callback which is executed when the ping is sent
2703
+ * @public
2704
+ */
2705
+ ping(data, mask, cb) {
2706
+ if (this.readyState === _WebSocket3.CONNECTING) {
2707
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
2708
+ }
2709
+ if (typeof data === "function") {
2710
+ cb = data;
2711
+ data = mask = void 0;
2712
+ } else if (typeof mask === "function") {
2713
+ cb = mask;
2714
+ mask = void 0;
2715
+ }
2716
+ if (typeof data === "number") data = data.toString();
2717
+ if (this.readyState !== _WebSocket3.OPEN) {
2718
+ sendAfterClose(this, data, cb);
2719
+ return;
2720
+ }
2721
+ if (mask === void 0) mask = !this._isServer;
2722
+ this._sender.ping(data || EMPTY_BUFFER2, mask, cb);
2723
+ }
2724
+ /**
2725
+ * Send a pong.
2726
+ *
2727
+ * @param {*} [data] The data to send
2728
+ * @param {Boolean} [mask] Indicates whether or not to mask `data`
2729
+ * @param {Function} [cb] Callback which is executed when the pong is sent
2730
+ * @public
2731
+ */
2732
+ pong(data, mask, cb) {
2733
+ if (this.readyState === _WebSocket3.CONNECTING) {
2734
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
2735
+ }
2736
+ if (typeof data === "function") {
2737
+ cb = data;
2738
+ data = mask = void 0;
2739
+ } else if (typeof mask === "function") {
2740
+ cb = mask;
2741
+ mask = void 0;
2742
+ }
2743
+ if (typeof data === "number") data = data.toString();
2744
+ if (this.readyState !== _WebSocket3.OPEN) {
2745
+ sendAfterClose(this, data, cb);
2746
+ return;
2747
+ }
2748
+ if (mask === void 0) mask = !this._isServer;
2749
+ this._sender.pong(data || EMPTY_BUFFER2, mask, cb);
2750
+ }
2751
+ /**
2752
+ * Resume the socket.
2753
+ *
2754
+ * @public
2755
+ */
2756
+ resume() {
2757
+ if (this.readyState === _WebSocket3.CONNECTING || this.readyState === _WebSocket3.CLOSED) {
2758
+ return;
2759
+ }
2760
+ this._paused = false;
2761
+ if (!this._receiver._writableState.needDrain) this._socket.resume();
2762
+ }
2763
+ /**
2764
+ * Send a data message.
2765
+ *
2766
+ * @param {*} data The message to send
2767
+ * @param {Object} [options] Options object
2768
+ * @param {Boolean} [options.binary] Specifies whether `data` is binary or
2769
+ * text
2770
+ * @param {Boolean} [options.compress] Specifies whether or not to compress
2771
+ * `data`
2772
+ * @param {Boolean} [options.fin=true] Specifies whether the fragment is the
2773
+ * last one
2774
+ * @param {Boolean} [options.mask] Specifies whether or not to mask `data`
2775
+ * @param {Function} [cb] Callback which is executed when data is written out
2776
+ * @public
2777
+ */
2778
+ send(data, options, cb) {
2779
+ if (this.readyState === _WebSocket3.CONNECTING) {
2780
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
2781
+ }
2782
+ if (typeof options === "function") {
2783
+ cb = options;
2784
+ options = {};
2785
+ }
2786
+ if (typeof data === "number") data = data.toString();
2787
+ if (this.readyState !== _WebSocket3.OPEN) {
2788
+ sendAfterClose(this, data, cb);
2789
+ return;
2790
+ }
2791
+ const opts = {
2792
+ binary: typeof data !== "string",
2793
+ mask: !this._isServer,
2794
+ compress: true,
2795
+ fin: true,
2796
+ ...options
2797
+ };
2798
+ if (!this._extensions[PerMessageDeflate2.extensionName]) {
2799
+ opts.compress = false;
2800
+ }
2801
+ this._sender.send(data || EMPTY_BUFFER2, opts, cb);
2802
+ }
2803
+ /**
2804
+ * Forcibly close the connection.
2805
+ *
2806
+ * @public
2807
+ */
2808
+ terminate() {
2809
+ if (this.readyState === _WebSocket3.CLOSED) return;
2810
+ if (this.readyState === _WebSocket3.CONNECTING) {
2811
+ const msg = "WebSocket was closed before the connection was established";
2812
+ abortHandshake(this, this._req, msg);
2813
+ return;
2814
+ }
2815
+ if (this._socket) {
2816
+ this._readyState = _WebSocket3.CLOSING;
2817
+ this._socket.destroy();
2818
+ }
2819
+ }
2820
+ };
2821
+ Object.defineProperty(WebSocket3, "CONNECTING", {
2822
+ enumerable: true,
2823
+ value: readyStates.indexOf("CONNECTING")
2824
+ });
2825
+ Object.defineProperty(WebSocket3.prototype, "CONNECTING", {
2826
+ enumerable: true,
2827
+ value: readyStates.indexOf("CONNECTING")
2828
+ });
2829
+ Object.defineProperty(WebSocket3, "OPEN", {
2830
+ enumerable: true,
2831
+ value: readyStates.indexOf("OPEN")
2832
+ });
2833
+ Object.defineProperty(WebSocket3.prototype, "OPEN", {
2834
+ enumerable: true,
2835
+ value: readyStates.indexOf("OPEN")
2836
+ });
2837
+ Object.defineProperty(WebSocket3, "CLOSING", {
2838
+ enumerable: true,
2839
+ value: readyStates.indexOf("CLOSING")
2840
+ });
2841
+ Object.defineProperty(WebSocket3.prototype, "CLOSING", {
2842
+ enumerable: true,
2843
+ value: readyStates.indexOf("CLOSING")
2844
+ });
2845
+ Object.defineProperty(WebSocket3, "CLOSED", {
2846
+ enumerable: true,
2847
+ value: readyStates.indexOf("CLOSED")
2848
+ });
2849
+ Object.defineProperty(WebSocket3.prototype, "CLOSED", {
2850
+ enumerable: true,
2851
+ value: readyStates.indexOf("CLOSED")
2852
+ });
2853
+ [
2854
+ "binaryType",
2855
+ "bufferedAmount",
2856
+ "extensions",
2857
+ "isPaused",
2858
+ "protocol",
2859
+ "readyState",
2860
+ "url"
2861
+ ].forEach((property) => {
2862
+ Object.defineProperty(WebSocket3.prototype, property, { enumerable: true });
2863
+ });
2864
+ ["open", "error", "close", "message"].forEach((method) => {
2865
+ Object.defineProperty(WebSocket3.prototype, `on${method}`, {
2866
+ enumerable: true,
2867
+ get() {
2868
+ for (const listener of this.listeners(method)) {
2869
+ if (listener[kForOnEventAttribute]) return listener[kListener];
2870
+ }
2871
+ return null;
2872
+ },
2873
+ set(handler) {
2874
+ for (const listener of this.listeners(method)) {
2875
+ if (listener[kForOnEventAttribute]) {
2876
+ this.removeListener(method, listener);
2877
+ break;
2878
+ }
2879
+ }
2880
+ if (typeof handler !== "function") return;
2881
+ this.addEventListener(method, handler, {
2882
+ [kForOnEventAttribute]: true
2883
+ });
2884
+ }
2885
+ });
2886
+ });
2887
+ WebSocket3.prototype.addEventListener = addEventListener;
2888
+ WebSocket3.prototype.removeEventListener = removeEventListener;
2889
+ module.exports = WebSocket3;
2890
+ function initAsClient(websocket, address, protocols, options) {
2891
+ const opts = {
2892
+ allowSynchronousEvents: true,
2893
+ autoPong: true,
2894
+ closeTimeout: CLOSE_TIMEOUT,
2895
+ protocolVersion: protocolVersions[1],
2896
+ maxBufferedChunks: 256 * 1024,
2897
+ maxFragments: 16 * 1024,
2898
+ maxPayload: 100 * 1024 * 1024,
2899
+ skipUTF8Validation: false,
2900
+ perMessageDeflate: true,
2901
+ followRedirects: false,
2902
+ maxRedirects: 10,
2903
+ ...options,
2904
+ socketPath: void 0,
2905
+ hostname: void 0,
2906
+ protocol: void 0,
2907
+ timeout: void 0,
2908
+ method: "GET",
2909
+ host: void 0,
2910
+ path: void 0,
2911
+ port: void 0
2912
+ };
2913
+ websocket._autoPong = opts.autoPong;
2914
+ websocket._closeTimeout = opts.closeTimeout;
2915
+ if (!protocolVersions.includes(opts.protocolVersion)) {
2916
+ throw new RangeError(
2917
+ `Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`
2918
+ );
2919
+ }
2920
+ let parsedUrl;
2921
+ if (address instanceof URL2) {
2922
+ parsedUrl = address;
2923
+ } else {
2924
+ try {
2925
+ parsedUrl = new URL2(address);
2926
+ } catch {
2927
+ throw new SyntaxError(`Invalid URL: ${address}`);
2928
+ }
2929
+ }
2930
+ if (parsedUrl.protocol === "http:") {
2931
+ parsedUrl.protocol = "ws:";
2932
+ } else if (parsedUrl.protocol === "https:") {
2933
+ parsedUrl.protocol = "wss:";
2934
+ }
2935
+ websocket._url = parsedUrl.href;
2936
+ const isSecure = parsedUrl.protocol === "wss:";
2937
+ const isIpcUrl = parsedUrl.protocol === "ws+unix:";
2938
+ let invalidUrlMessage;
2939
+ if (parsedUrl.protocol !== "ws:" && !isSecure && !isIpcUrl) {
2940
+ invalidUrlMessage = `The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`;
2941
+ } else if (isIpcUrl && !parsedUrl.pathname) {
2942
+ invalidUrlMessage = "The URL's pathname is empty";
2943
+ } else if (parsedUrl.hash) {
2944
+ invalidUrlMessage = "The URL contains a fragment identifier";
2945
+ }
2946
+ if (invalidUrlMessage) {
2947
+ const err = new SyntaxError(invalidUrlMessage);
2948
+ if (websocket._redirects === 0) {
2949
+ throw err;
2950
+ } else {
2951
+ emitErrorAndClose(websocket, err);
2952
+ return;
2953
+ }
2954
+ }
2955
+ const defaultPort = isSecure ? 443 : 80;
2956
+ const key = randomBytes7(16).toString("base64");
2957
+ const request = isSecure ? https.request : http.request;
2958
+ const protocolSet = /* @__PURE__ */ new Set();
2959
+ let perMessageDeflate;
2960
+ opts.createConnection = opts.createConnection || (isSecure ? tlsConnect : netConnect);
2961
+ opts.defaultPort = opts.defaultPort || defaultPort;
2962
+ opts.port = parsedUrl.port || defaultPort;
2963
+ opts.host = parsedUrl.hostname.startsWith("[") ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname;
2964
+ opts.headers = {
2965
+ ...opts.headers,
2966
+ "Sec-WebSocket-Version": opts.protocolVersion,
2967
+ "Sec-WebSocket-Key": key,
2968
+ Connection: "Upgrade",
2969
+ Upgrade: "websocket"
2970
+ };
2971
+ opts.path = parsedUrl.pathname + parsedUrl.search;
2972
+ opts.timeout = opts.handshakeTimeout;
2973
+ if (opts.perMessageDeflate) {
2974
+ perMessageDeflate = new PerMessageDeflate2({
2975
+ ...opts.perMessageDeflate,
2976
+ isServer: false,
2977
+ maxPayload: opts.maxPayload
2978
+ });
2979
+ opts.headers["Sec-WebSocket-Extensions"] = format({
2980
+ [PerMessageDeflate2.extensionName]: perMessageDeflate.offer()
2981
+ });
2982
+ }
2983
+ if (protocols.length) {
2984
+ for (const protocol of protocols) {
2985
+ if (typeof protocol !== "string" || !subprotocolRegex.test(protocol) || protocolSet.has(protocol)) {
2986
+ throw new SyntaxError(
2987
+ "An invalid or duplicated subprotocol was specified"
2988
+ );
2989
+ }
2990
+ protocolSet.add(protocol);
2991
+ }
2992
+ opts.headers["Sec-WebSocket-Protocol"] = protocols.join(",");
2993
+ }
2994
+ if (opts.origin) {
2995
+ if (opts.protocolVersion < 13) {
2996
+ opts.headers["Sec-WebSocket-Origin"] = opts.origin;
2997
+ } else {
2998
+ opts.headers.Origin = opts.origin;
2999
+ }
3000
+ }
3001
+ if (parsedUrl.username || parsedUrl.password) {
3002
+ opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
3003
+ }
3004
+ if (isIpcUrl) {
3005
+ const parts = opts.path.split(":");
3006
+ opts.socketPath = parts[0];
3007
+ opts.path = parts[1];
3008
+ }
3009
+ let req;
3010
+ if (opts.followRedirects) {
3011
+ if (websocket._redirects === 0) {
3012
+ websocket._originalIpc = isIpcUrl;
3013
+ websocket._originalSecure = isSecure;
3014
+ websocket._originalHostOrSocketPath = isIpcUrl ? opts.socketPath : parsedUrl.host;
3015
+ const headers = options && options.headers;
3016
+ options = { ...options, headers: {} };
3017
+ if (headers) {
3018
+ for (const [key2, value] of Object.entries(headers)) {
3019
+ options.headers[key2.toLowerCase()] = value;
3020
+ }
3021
+ }
3022
+ } else if (websocket.listenerCount("redirect") === 0) {
3023
+ const isSameHost = isIpcUrl ? websocket._originalIpc ? opts.socketPath === websocket._originalHostOrSocketPath : false : websocket._originalIpc ? false : parsedUrl.host === websocket._originalHostOrSocketPath;
3024
+ if (!isSameHost || websocket._originalSecure && !isSecure) {
3025
+ delete opts.headers.authorization;
3026
+ delete opts.headers.cookie;
3027
+ if (!isSameHost) delete opts.headers.host;
3028
+ opts.auth = void 0;
3029
+ }
3030
+ }
3031
+ if (opts.auth && !options.headers.authorization) {
3032
+ options.headers.authorization = "Basic " + Buffer.from(opts.auth).toString("base64");
3033
+ }
3034
+ req = websocket._req = request(opts);
3035
+ if (websocket._redirects) {
3036
+ websocket.emit("redirect", websocket.url, req);
3037
+ }
3038
+ } else {
3039
+ req = websocket._req = request(opts);
3040
+ }
3041
+ if (opts.timeout) {
3042
+ req.on("timeout", () => {
3043
+ abortHandshake(websocket, req, "Opening handshake has timed out");
3044
+ });
3045
+ }
3046
+ req.on("error", (err) => {
3047
+ if (req === null || req[kAborted]) return;
3048
+ req = websocket._req = null;
3049
+ emitErrorAndClose(websocket, err);
3050
+ });
3051
+ req.on("response", (res) => {
3052
+ const location = res.headers.location;
3053
+ const statusCode = res.statusCode;
3054
+ if (location && opts.followRedirects && statusCode >= 300 && statusCode < 400) {
3055
+ if (++websocket._redirects > opts.maxRedirects) {
3056
+ abortHandshake(websocket, req, "Maximum redirects exceeded");
3057
+ return;
3058
+ }
3059
+ req.abort();
3060
+ let addr;
3061
+ try {
3062
+ addr = new URL2(location, address);
3063
+ } catch (e) {
3064
+ const err = new SyntaxError(`Invalid URL: ${location}`);
3065
+ emitErrorAndClose(websocket, err);
3066
+ return;
3067
+ }
3068
+ initAsClient(websocket, addr, protocols, options);
3069
+ } else if (!websocket.emit("unexpected-response", req, res)) {
3070
+ abortHandshake(
3071
+ websocket,
3072
+ req,
3073
+ `Unexpected server response: ${res.statusCode}`
3074
+ );
3075
+ }
3076
+ });
3077
+ req.on("upgrade", (res, socket, head) => {
3078
+ websocket.emit("upgrade", res);
3079
+ if (websocket.readyState !== WebSocket3.CONNECTING) return;
3080
+ req = websocket._req = null;
3081
+ const upgrade = res.headers.upgrade;
3082
+ if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
3083
+ abortHandshake(websocket, socket, "Invalid Upgrade header");
3084
+ return;
3085
+ }
3086
+ const digest = createHash7("sha1").update(key + GUID).digest("base64");
3087
+ if (res.headers["sec-websocket-accept"] !== digest) {
3088
+ abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
3089
+ return;
3090
+ }
3091
+ const serverProt = res.headers["sec-websocket-protocol"];
3092
+ let protError;
3093
+ if (serverProt !== void 0) {
3094
+ if (!protocolSet.size) {
3095
+ protError = "Server sent a subprotocol but none was requested";
3096
+ } else if (!protocolSet.has(serverProt)) {
3097
+ protError = "Server sent an invalid subprotocol";
3098
+ }
3099
+ } else if (protocolSet.size) {
3100
+ protError = "Server sent no subprotocol";
3101
+ }
3102
+ if (protError) {
3103
+ abortHandshake(websocket, socket, protError);
3104
+ return;
3105
+ }
3106
+ if (serverProt) websocket._protocol = serverProt;
3107
+ const secWebSocketExtensions = res.headers["sec-websocket-extensions"];
3108
+ if (secWebSocketExtensions !== void 0) {
3109
+ if (!perMessageDeflate) {
3110
+ const message = "Server sent a Sec-WebSocket-Extensions header but no extension was requested";
3111
+ abortHandshake(websocket, socket, message);
3112
+ return;
3113
+ }
3114
+ let extensions;
3115
+ try {
3116
+ extensions = parse5(secWebSocketExtensions);
3117
+ } catch (err) {
3118
+ const message = "Invalid Sec-WebSocket-Extensions header";
3119
+ abortHandshake(websocket, socket, message);
3120
+ return;
3121
+ }
3122
+ const extensionNames = Object.keys(extensions);
3123
+ if (extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate2.extensionName) {
3124
+ const message = "Server indicated an extension that was not requested";
3125
+ abortHandshake(websocket, socket, message);
3126
+ return;
3127
+ }
3128
+ try {
3129
+ perMessageDeflate.accept(extensions[PerMessageDeflate2.extensionName]);
3130
+ } catch (err) {
3131
+ const message = "Invalid Sec-WebSocket-Extensions header";
3132
+ abortHandshake(websocket, socket, message);
3133
+ return;
3134
+ }
3135
+ websocket._extensions[PerMessageDeflate2.extensionName] = perMessageDeflate;
3136
+ }
3137
+ websocket.setSocket(socket, head, {
3138
+ allowSynchronousEvents: opts.allowSynchronousEvents,
3139
+ generateMask: opts.generateMask,
3140
+ maxBufferedChunks: opts.maxBufferedChunks,
3141
+ maxFragments: opts.maxFragments,
3142
+ maxPayload: opts.maxPayload,
3143
+ skipUTF8Validation: opts.skipUTF8Validation
3144
+ });
3145
+ });
3146
+ if (opts.finishRequest) {
3147
+ opts.finishRequest(req, websocket);
3148
+ } else {
3149
+ req.end();
3150
+ }
3151
+ }
3152
+ function emitErrorAndClose(websocket, err) {
3153
+ websocket._readyState = WebSocket3.CLOSING;
3154
+ websocket._errorEmitted = true;
3155
+ websocket.emit("error", err);
3156
+ websocket.emitClose();
3157
+ }
3158
+ function netConnect(options) {
3159
+ options.path = options.socketPath;
3160
+ return net.connect(options);
3161
+ }
3162
+ function tlsConnect(options) {
3163
+ options.path = void 0;
3164
+ if (!options.servername && options.servername !== "") {
3165
+ options.servername = net.isIP(options.host) ? "" : options.host;
3166
+ }
3167
+ return tls.connect(options);
3168
+ }
3169
+ function abortHandshake(websocket, stream, message) {
3170
+ websocket._readyState = WebSocket3.CLOSING;
3171
+ const err = new Error(message);
3172
+ Error.captureStackTrace(err, abortHandshake);
3173
+ if (stream.setHeader) {
3174
+ stream[kAborted] = true;
3175
+ stream.abort();
3176
+ if (stream.socket && !stream.socket.destroyed) {
3177
+ stream.socket.destroy();
3178
+ }
3179
+ process.nextTick(emitErrorAndClose, websocket, err);
3180
+ } else {
3181
+ stream.destroy(err);
3182
+ stream.once("error", websocket.emit.bind(websocket, "error"));
3183
+ stream.once("close", websocket.emitClose.bind(websocket));
3184
+ }
3185
+ }
3186
+ function sendAfterClose(websocket, data, cb) {
3187
+ if (data) {
3188
+ const length = isBlob(data) ? data.size : toBuffer(data).length;
3189
+ if (websocket._socket) websocket._sender._bufferedBytes += length;
3190
+ else websocket._bufferedAmount += length;
3191
+ }
3192
+ if (cb) {
3193
+ const err = new Error(
3194
+ `WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})`
3195
+ );
3196
+ process.nextTick(cb, err);
3197
+ }
3198
+ }
3199
+ function receiverOnConclude(code, reason) {
3200
+ const websocket = this[kWebSocket];
3201
+ websocket._closeFrameReceived = true;
3202
+ websocket._closeMessage = reason;
3203
+ websocket._closeCode = code;
3204
+ if (websocket._socket[kWebSocket] === void 0) return;
3205
+ websocket._socket.removeListener("data", socketOnData);
3206
+ process.nextTick(resume, websocket._socket);
3207
+ if (code === 1005) websocket.close();
3208
+ else websocket.close(code, reason);
3209
+ }
3210
+ function receiverOnDrain() {
3211
+ const websocket = this[kWebSocket];
3212
+ if (!websocket.isPaused) websocket._socket.resume();
3213
+ }
3214
+ function receiverOnError(err) {
3215
+ const websocket = this[kWebSocket];
3216
+ if (websocket._socket[kWebSocket] !== void 0) {
3217
+ websocket._socket.removeListener("data", socketOnData);
3218
+ process.nextTick(resume, websocket._socket);
3219
+ websocket.close(err[kStatusCode]);
3220
+ }
3221
+ if (!websocket._errorEmitted) {
3222
+ websocket._errorEmitted = true;
3223
+ websocket.emit("error", err);
3224
+ }
3225
+ }
3226
+ function receiverOnFinish() {
3227
+ this[kWebSocket].emitClose();
3228
+ }
3229
+ function receiverOnMessage(data, isBinary) {
3230
+ this[kWebSocket].emit("message", data, isBinary);
3231
+ }
3232
+ function receiverOnPing(data) {
3233
+ const websocket = this[kWebSocket];
3234
+ if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP);
3235
+ websocket.emit("ping", data);
3236
+ }
3237
+ function receiverOnPong(data) {
3238
+ this[kWebSocket].emit("pong", data);
3239
+ }
3240
+ function resume(stream) {
3241
+ stream.resume();
3242
+ }
3243
+ function senderOnError(err) {
3244
+ const websocket = this[kWebSocket];
3245
+ if (websocket.readyState === WebSocket3.CLOSED) return;
3246
+ if (websocket.readyState === WebSocket3.OPEN) {
3247
+ websocket._readyState = WebSocket3.CLOSING;
3248
+ setCloseTimer(websocket);
3249
+ }
3250
+ this._socket.end();
3251
+ if (!websocket._errorEmitted) {
3252
+ websocket._errorEmitted = true;
3253
+ websocket.emit("error", err);
3254
+ }
3255
+ }
3256
+ function setCloseTimer(websocket) {
3257
+ websocket._closeTimer = setTimeout(
3258
+ websocket._socket.destroy.bind(websocket._socket),
3259
+ websocket._closeTimeout
3260
+ );
3261
+ }
3262
+ function socketOnClose() {
3263
+ const websocket = this[kWebSocket];
3264
+ this.removeListener("close", socketOnClose);
3265
+ this.removeListener("data", socketOnData);
3266
+ this.removeListener("end", socketOnEnd);
3267
+ websocket._readyState = WebSocket3.CLOSING;
3268
+ if (!this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && this._readableState.length !== 0) {
3269
+ const chunk = this.read(this._readableState.length);
3270
+ websocket._receiver.write(chunk);
3271
+ }
3272
+ websocket._receiver.end();
3273
+ this[kWebSocket] = void 0;
3274
+ clearTimeout(websocket._closeTimer);
3275
+ if (websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted) {
3276
+ websocket.emitClose();
3277
+ } else {
3278
+ websocket._receiver.on("error", receiverOnFinish);
3279
+ websocket._receiver.on("finish", receiverOnFinish);
3280
+ }
3281
+ }
3282
+ function socketOnData(chunk) {
3283
+ if (!this[kWebSocket]._receiver.write(chunk)) {
3284
+ this.pause();
3285
+ }
3286
+ }
3287
+ function socketOnEnd() {
3288
+ const websocket = this[kWebSocket];
3289
+ websocket._readyState = WebSocket3.CLOSING;
3290
+ websocket._receiver.end();
3291
+ this.end();
3292
+ }
3293
+ function socketOnError() {
3294
+ const websocket = this[kWebSocket];
3295
+ this.removeListener("error", socketOnError);
3296
+ this.on("error", NOOP);
3297
+ if (websocket) {
3298
+ websocket._readyState = WebSocket3.CLOSING;
3299
+ this.destroy();
3300
+ }
3301
+ }
3302
+ }
3303
+ });
3304
+
3305
+ // node_modules/ws/lib/stream.js
3306
+ var require_stream = __commonJS({
3307
+ "node_modules/ws/lib/stream.js"(exports, module) {
3308
+ "use strict";
3309
+ var WebSocket3 = require_websocket();
3310
+ var { Duplex } = __require("stream");
3311
+ function emitClose(stream) {
3312
+ stream.emit("close");
3313
+ }
3314
+ function duplexOnEnd() {
3315
+ if (!this.destroyed && this._writableState.finished) {
3316
+ this.destroy();
3317
+ }
3318
+ }
3319
+ function duplexOnError(err) {
3320
+ this.removeListener("error", duplexOnError);
3321
+ this.destroy();
3322
+ if (this.listenerCount("error") === 0) {
3323
+ this.emit("error", err);
3324
+ }
3325
+ }
3326
+ function createWebSocketStream2(ws, options) {
3327
+ let terminateOnDestroy = true;
3328
+ const duplex = new Duplex({
3329
+ ...options,
3330
+ autoDestroy: false,
3331
+ emitClose: false,
3332
+ objectMode: false,
3333
+ writableObjectMode: false
3334
+ });
3335
+ ws.on("message", function message(msg, isBinary) {
3336
+ const data = !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;
3337
+ if (!duplex.push(data)) ws.pause();
3338
+ });
3339
+ ws.once("error", function error(err) {
3340
+ if (duplex.destroyed) return;
3341
+ terminateOnDestroy = false;
3342
+ duplex.destroy(err);
3343
+ });
3344
+ ws.once("close", function close() {
3345
+ if (duplex.destroyed) return;
3346
+ duplex.push(null);
3347
+ });
3348
+ duplex._destroy = function(err, callback) {
3349
+ if (ws.readyState === ws.CLOSED) {
3350
+ callback(err);
3351
+ process.nextTick(emitClose, duplex);
3352
+ return;
3353
+ }
3354
+ let called = false;
3355
+ ws.once("error", function error(err2) {
3356
+ called = true;
3357
+ callback(err2);
3358
+ });
3359
+ ws.once("close", function close() {
3360
+ if (!called) callback(err);
3361
+ process.nextTick(emitClose, duplex);
3362
+ });
3363
+ if (terminateOnDestroy) ws.terminate();
3364
+ };
3365
+ duplex._final = function(callback) {
3366
+ if (ws.readyState === ws.CONNECTING) {
3367
+ ws.once("open", function open2() {
3368
+ duplex._final(callback);
3369
+ });
3370
+ return;
3371
+ }
3372
+ if (ws._socket === null) return;
3373
+ if (ws._socket._writableState.finished) {
3374
+ callback();
3375
+ if (duplex._readableState.endEmitted) duplex.destroy();
3376
+ } else {
3377
+ ws._socket.once("finish", function finish() {
3378
+ callback();
3379
+ });
3380
+ ws.close();
3381
+ }
3382
+ };
3383
+ duplex._read = function() {
3384
+ if (ws.isPaused) ws.resume();
3385
+ };
3386
+ duplex._write = function(chunk, encoding, callback) {
3387
+ if (ws.readyState === ws.CONNECTING) {
3388
+ ws.once("open", function open2() {
3389
+ duplex._write(chunk, encoding, callback);
3390
+ });
3391
+ return;
3392
+ }
3393
+ ws.send(chunk, callback);
3394
+ };
3395
+ duplex.on("end", duplexOnEnd);
3396
+ duplex.on("error", duplexOnError);
3397
+ return duplex;
3398
+ }
3399
+ module.exports = createWebSocketStream2;
3400
+ }
3401
+ });
3402
+
3403
+ // node_modules/ws/lib/subprotocol.js
3404
+ var require_subprotocol = __commonJS({
3405
+ "node_modules/ws/lib/subprotocol.js"(exports, module) {
3406
+ "use strict";
3407
+ var { tokenChars } = require_validation();
3408
+ function parse5(header) {
3409
+ const protocols = /* @__PURE__ */ new Set();
3410
+ let start = -1;
3411
+ let end = -1;
3412
+ let i3 = 0;
3413
+ for (i3; i3 < header.length; i3++) {
3414
+ const code = header.charCodeAt(i3);
3415
+ if (end === -1 && tokenChars[code] === 1) {
3416
+ if (start === -1) start = i3;
3417
+ } else if (i3 !== 0 && (code === 32 || code === 9)) {
3418
+ if (end === -1 && start !== -1) end = i3;
3419
+ } else if (code === 44) {
3420
+ if (start === -1) {
3421
+ throw new SyntaxError(`Unexpected character at index ${i3}`);
3422
+ }
3423
+ if (end === -1) end = i3;
3424
+ const protocol2 = header.slice(start, end);
3425
+ if (protocols.has(protocol2)) {
3426
+ throw new SyntaxError(`The "${protocol2}" subprotocol is duplicated`);
3427
+ }
3428
+ protocols.add(protocol2);
3429
+ start = end = -1;
3430
+ } else {
3431
+ throw new SyntaxError(`Unexpected character at index ${i3}`);
3432
+ }
3433
+ }
3434
+ if (start === -1 || end !== -1) {
3435
+ throw new SyntaxError("Unexpected end of input");
3436
+ }
3437
+ const protocol = header.slice(start, i3);
3438
+ if (protocols.has(protocol)) {
3439
+ throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
3440
+ }
3441
+ protocols.add(protocol);
3442
+ return protocols;
3443
+ }
3444
+ module.exports = { parse: parse5 };
98
3445
  }
99
3446
  });
100
3447
 
101
- // node_modules/picocolors/picocolors.js
102
- var require_picocolors = __commonJS({
103
- "node_modules/picocolors/picocolors.js"(exports, module) {
104
- var p = process || {};
105
- var argv = p.argv || [];
106
- var env = p.env || {};
107
- var isColorSupported = !(!!env.NO_COLOR || argv.includes("--no-color")) && (!!env.FORCE_COLOR || argv.includes("--color") || p.platform === "win32" || (p.stdout || {}).isTTY && env.TERM !== "dumb" || !!env.CI);
108
- var formatter = (open2, close, replace = open2) => (input) => {
109
- let string = "" + input, index = string.indexOf(close, open2.length);
110
- return ~index ? open2 + replaceClose(string, close, replace, index) + close : open2 + string + close;
111
- };
112
- var replaceClose = (string, close, replace, index) => {
113
- let result = "", cursor3 = 0;
114
- do {
115
- result += string.substring(cursor3, index) + replace;
116
- cursor3 = index + close.length;
117
- index = string.indexOf(close, cursor3);
118
- } while (~index);
119
- return result + string.substring(cursor3);
3448
+ // node_modules/ws/lib/websocket-server.js
3449
+ var require_websocket_server = __commonJS({
3450
+ "node_modules/ws/lib/websocket-server.js"(exports, module) {
3451
+ "use strict";
3452
+ var EventEmitter2 = __require("events");
3453
+ var http = __require("http");
3454
+ var { Duplex } = __require("stream");
3455
+ var { createHash: createHash7 } = __require("crypto");
3456
+ var extension2 = require_extension();
3457
+ var PerMessageDeflate2 = require_permessage_deflate();
3458
+ var subprotocol2 = require_subprotocol();
3459
+ var WebSocket3 = require_websocket();
3460
+ var { CLOSE_TIMEOUT, GUID, kWebSocket } = require_constants();
3461
+ var keyRegex = /^[+/0-9A-Za-z]{22}==$/;
3462
+ var RUNNING = 0;
3463
+ var CLOSING = 1;
3464
+ var CLOSED = 2;
3465
+ var WebSocketServer2 = class extends EventEmitter2 {
3466
+ /**
3467
+ * Create a `WebSocketServer` instance.
3468
+ *
3469
+ * @param {Object} options Configuration options
3470
+ * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
3471
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
3472
+ * multiple times in the same tick
3473
+ * @param {Boolean} [options.autoPong=true] Specifies whether or not to
3474
+ * automatically send a pong in response to a ping
3475
+ * @param {Number} [options.backlog=511] The maximum length of the queue of
3476
+ * pending connections
3477
+ * @param {Boolean} [options.clientTracking=true] Specifies whether or not to
3478
+ * track clients
3479
+ * @param {Number} [options.closeTimeout=30000] Duration in milliseconds to
3480
+ * wait for the closing handshake to finish after `websocket.close()` is
3481
+ * called
3482
+ * @param {Function} [options.handleProtocols] A hook to handle protocols
3483
+ * @param {String} [options.host] The hostname where to bind the server
3484
+ * @param {Number} [options.maxBufferedChunks=262144] The maximum number of
3485
+ * buffered data chunks
3486
+ * @param {Number} [options.maxFragments=16384] The maximum number of message
3487
+ * fragments
3488
+ * @param {Number} [options.maxPayload=104857600] The maximum allowed message
3489
+ * size
3490
+ * @param {Boolean} [options.noServer=false] Enable no server mode
3491
+ * @param {String} [options.path] Accept only connections matching this path
3492
+ * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable
3493
+ * permessage-deflate
3494
+ * @param {Number} [options.port] The port where to bind the server
3495
+ * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S
3496
+ * server to use
3497
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
3498
+ * not to skip UTF-8 validation for text and close messages
3499
+ * @param {Function} [options.verifyClient] A hook to reject connections
3500
+ * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`
3501
+ * class to use. It must be the `WebSocket` class or class that extends it
3502
+ * @param {Function} [callback] A listener for the `listening` event
3503
+ */
3504
+ constructor(options, callback) {
3505
+ super();
3506
+ options = {
3507
+ allowSynchronousEvents: true,
3508
+ autoPong: true,
3509
+ maxBufferedChunks: 256 * 1024,
3510
+ maxFragments: 16 * 1024,
3511
+ maxPayload: 100 * 1024 * 1024,
3512
+ skipUTF8Validation: false,
3513
+ perMessageDeflate: false,
3514
+ handleProtocols: null,
3515
+ clientTracking: true,
3516
+ closeTimeout: CLOSE_TIMEOUT,
3517
+ verifyClient: null,
3518
+ noServer: false,
3519
+ backlog: null,
3520
+ // use default (511 as implemented in net.js)
3521
+ server: null,
3522
+ host: null,
3523
+ path: null,
3524
+ port: null,
3525
+ WebSocket: WebSocket3,
3526
+ ...options
3527
+ };
3528
+ if (options.port == null && !options.server && !options.noServer || options.port != null && (options.server || options.noServer) || options.server && options.noServer) {
3529
+ throw new TypeError(
3530
+ 'One and only one of the "port", "server", or "noServer" options must be specified'
3531
+ );
3532
+ }
3533
+ if (options.port != null) {
3534
+ this._server = http.createServer((req, res) => {
3535
+ const body = http.STATUS_CODES[426];
3536
+ res.writeHead(426, {
3537
+ "Content-Length": body.length,
3538
+ "Content-Type": "text/plain"
3539
+ });
3540
+ res.end(body);
3541
+ });
3542
+ this._server.listen(
3543
+ options.port,
3544
+ options.host,
3545
+ options.backlog,
3546
+ callback
3547
+ );
3548
+ } else if (options.server) {
3549
+ this._server = options.server;
3550
+ }
3551
+ if (this._server) {
3552
+ const emitConnection = this.emit.bind(this, "connection");
3553
+ this._removeListeners = addListeners(this._server, {
3554
+ listening: this.emit.bind(this, "listening"),
3555
+ error: this.emit.bind(this, "error"),
3556
+ upgrade: (req, socket, head) => {
3557
+ this.handleUpgrade(req, socket, head, emitConnection);
3558
+ }
3559
+ });
3560
+ }
3561
+ if (options.perMessageDeflate === true) options.perMessageDeflate = {};
3562
+ if (options.clientTracking) {
3563
+ this.clients = /* @__PURE__ */ new Set();
3564
+ this._shouldEmitClose = false;
3565
+ }
3566
+ this.options = options;
3567
+ this._state = RUNNING;
3568
+ }
3569
+ /**
3570
+ * Returns the bound address, the address family name, and port of the server
3571
+ * as reported by the operating system if listening on an IP socket.
3572
+ * If the server is listening on a pipe or UNIX domain socket, the name is
3573
+ * returned as a string.
3574
+ *
3575
+ * @return {(Object|String|null)} The address of the server
3576
+ * @public
3577
+ */
3578
+ address() {
3579
+ if (this.options.noServer) {
3580
+ throw new Error('The server is operating in "noServer" mode');
3581
+ }
3582
+ if (!this._server) return null;
3583
+ return this._server.address();
3584
+ }
3585
+ /**
3586
+ * Stop the server from accepting new connections and emit the `'close'` event
3587
+ * when all existing connections are closed.
3588
+ *
3589
+ * @param {Function} [cb] A one-time listener for the `'close'` event
3590
+ * @public
3591
+ */
3592
+ close(cb) {
3593
+ if (this._state === CLOSED) {
3594
+ if (cb) {
3595
+ this.once("close", () => {
3596
+ cb(new Error("The server is not running"));
3597
+ });
3598
+ }
3599
+ process.nextTick(emitClose, this);
3600
+ return;
3601
+ }
3602
+ if (cb) this.once("close", cb);
3603
+ if (this._state === CLOSING) return;
3604
+ this._state = CLOSING;
3605
+ if (this.options.noServer || this.options.server) {
3606
+ if (this._server) {
3607
+ this._removeListeners();
3608
+ this._removeListeners = this._server = null;
3609
+ }
3610
+ if (this.clients) {
3611
+ if (!this.clients.size) {
3612
+ process.nextTick(emitClose, this);
3613
+ } else {
3614
+ this._shouldEmitClose = true;
3615
+ }
3616
+ } else {
3617
+ process.nextTick(emitClose, this);
3618
+ }
3619
+ } else {
3620
+ const server = this._server;
3621
+ this._removeListeners();
3622
+ this._removeListeners = this._server = null;
3623
+ server.close(() => {
3624
+ emitClose(this);
3625
+ });
3626
+ }
3627
+ }
3628
+ /**
3629
+ * See if a given request should be handled by this server instance.
3630
+ *
3631
+ * @param {http.IncomingMessage} req Request object to inspect
3632
+ * @return {Boolean} `true` if the request is valid, else `false`
3633
+ * @public
3634
+ */
3635
+ shouldHandle(req) {
3636
+ if (this.options.path) {
3637
+ const index = req.url.indexOf("?");
3638
+ const pathname = index !== -1 ? req.url.slice(0, index) : req.url;
3639
+ if (pathname !== this.options.path) return false;
3640
+ }
3641
+ return true;
3642
+ }
3643
+ /**
3644
+ * Handle a HTTP Upgrade request.
3645
+ *
3646
+ * @param {http.IncomingMessage} req The request object
3647
+ * @param {Duplex} socket The network socket between the server and client
3648
+ * @param {Buffer} head The first packet of the upgraded stream
3649
+ * @param {Function} cb Callback
3650
+ * @public
3651
+ */
3652
+ handleUpgrade(req, socket, head, cb) {
3653
+ socket.on("error", socketOnError);
3654
+ const key = req.headers["sec-websocket-key"];
3655
+ const upgrade = req.headers.upgrade;
3656
+ const version = +req.headers["sec-websocket-version"];
3657
+ if (req.method !== "GET") {
3658
+ const message = "Invalid HTTP method";
3659
+ abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);
3660
+ return;
3661
+ }
3662
+ if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
3663
+ const message = "Invalid Upgrade header";
3664
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3665
+ return;
3666
+ }
3667
+ if (key === void 0 || !keyRegex.test(key)) {
3668
+ const message = "Missing or invalid Sec-WebSocket-Key header";
3669
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3670
+ return;
3671
+ }
3672
+ if (version !== 13 && version !== 8) {
3673
+ const message = "Missing or invalid Sec-WebSocket-Version header";
3674
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message, {
3675
+ "Sec-WebSocket-Version": "13, 8"
3676
+ });
3677
+ return;
3678
+ }
3679
+ if (!this.shouldHandle(req)) {
3680
+ abortHandshake(socket, 400);
3681
+ return;
3682
+ }
3683
+ const secWebSocketProtocol = req.headers["sec-websocket-protocol"];
3684
+ let protocols = /* @__PURE__ */ new Set();
3685
+ if (secWebSocketProtocol !== void 0) {
3686
+ try {
3687
+ protocols = subprotocol2.parse(secWebSocketProtocol);
3688
+ } catch (err) {
3689
+ const message = "Invalid Sec-WebSocket-Protocol header";
3690
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3691
+ return;
3692
+ }
3693
+ }
3694
+ const secWebSocketExtensions = req.headers["sec-websocket-extensions"];
3695
+ const extensions = {};
3696
+ if (this.options.perMessageDeflate && secWebSocketExtensions !== void 0) {
3697
+ const perMessageDeflate = new PerMessageDeflate2({
3698
+ ...this.options.perMessageDeflate,
3699
+ isServer: true,
3700
+ maxPayload: this.options.maxPayload
3701
+ });
3702
+ try {
3703
+ const offers = extension2.parse(secWebSocketExtensions);
3704
+ if (offers[PerMessageDeflate2.extensionName]) {
3705
+ perMessageDeflate.accept(offers[PerMessageDeflate2.extensionName]);
3706
+ extensions[PerMessageDeflate2.extensionName] = perMessageDeflate;
3707
+ }
3708
+ } catch (err) {
3709
+ const message = "Invalid or unacceptable Sec-WebSocket-Extensions header";
3710
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3711
+ return;
3712
+ }
3713
+ }
3714
+ if (this.options.verifyClient) {
3715
+ const info = {
3716
+ origin: req.headers[`${version === 8 ? "sec-websocket-origin" : "origin"}`],
3717
+ secure: !!(req.socket.authorized || req.socket.encrypted),
3718
+ req
3719
+ };
3720
+ if (this.options.verifyClient.length === 2) {
3721
+ this.options.verifyClient(info, (verified, code, message, headers) => {
3722
+ if (!verified) {
3723
+ return abortHandshake(socket, code || 401, message, headers);
3724
+ }
3725
+ this.completeUpgrade(
3726
+ extensions,
3727
+ key,
3728
+ protocols,
3729
+ req,
3730
+ socket,
3731
+ head,
3732
+ cb
3733
+ );
3734
+ });
3735
+ return;
3736
+ }
3737
+ if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);
3738
+ }
3739
+ this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
3740
+ }
3741
+ /**
3742
+ * Upgrade the connection to WebSocket.
3743
+ *
3744
+ * @param {Object} extensions The accepted extensions
3745
+ * @param {String} key The value of the `Sec-WebSocket-Key` header
3746
+ * @param {Set} protocols The subprotocols
3747
+ * @param {http.IncomingMessage} req The request object
3748
+ * @param {Duplex} socket The network socket between the server and client
3749
+ * @param {Buffer} head The first packet of the upgraded stream
3750
+ * @param {Function} cb Callback
3751
+ * @throws {Error} If called more than once with the same socket
3752
+ * @private
3753
+ */
3754
+ completeUpgrade(extensions, key, protocols, req, socket, head, cb) {
3755
+ if (!socket.readable || !socket.writable) return socket.destroy();
3756
+ if (socket[kWebSocket]) {
3757
+ throw new Error(
3758
+ "server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration"
3759
+ );
3760
+ }
3761
+ if (this._state > RUNNING) return abortHandshake(socket, 503);
3762
+ const digest = createHash7("sha1").update(key + GUID).digest("base64");
3763
+ const headers = [
3764
+ "HTTP/1.1 101 Switching Protocols",
3765
+ "Upgrade: websocket",
3766
+ "Connection: Upgrade",
3767
+ `Sec-WebSocket-Accept: ${digest}`
3768
+ ];
3769
+ const ws = new this.options.WebSocket(null, void 0, this.options);
3770
+ if (protocols.size) {
3771
+ const protocol = this.options.handleProtocols ? this.options.handleProtocols(protocols, req) : protocols.values().next().value;
3772
+ if (protocol) {
3773
+ headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
3774
+ ws._protocol = protocol;
3775
+ }
3776
+ }
3777
+ if (extensions[PerMessageDeflate2.extensionName]) {
3778
+ const params = extensions[PerMessageDeflate2.extensionName].params;
3779
+ const value = extension2.format({
3780
+ [PerMessageDeflate2.extensionName]: [params]
3781
+ });
3782
+ headers.push(`Sec-WebSocket-Extensions: ${value}`);
3783
+ ws._extensions = extensions;
3784
+ }
3785
+ this.emit("headers", headers, req);
3786
+ socket.write(headers.concat("\r\n").join("\r\n"));
3787
+ socket.removeListener("error", socketOnError);
3788
+ ws.setSocket(socket, head, {
3789
+ allowSynchronousEvents: this.options.allowSynchronousEvents,
3790
+ maxBufferedChunks: this.options.maxBufferedChunks,
3791
+ maxFragments: this.options.maxFragments,
3792
+ maxPayload: this.options.maxPayload,
3793
+ skipUTF8Validation: this.options.skipUTF8Validation
3794
+ });
3795
+ if (this.clients) {
3796
+ this.clients.add(ws);
3797
+ ws.on("close", () => {
3798
+ this.clients.delete(ws);
3799
+ if (this._shouldEmitClose && !this.clients.size) {
3800
+ process.nextTick(emitClose, this);
3801
+ }
3802
+ });
3803
+ }
3804
+ cb(ws, req);
3805
+ }
120
3806
  };
121
- var createColors = (enabled = isColorSupported) => {
122
- let f = enabled ? formatter : () => String;
123
- return {
124
- isColorSupported: enabled,
125
- reset: f("\x1B[0m", "\x1B[0m"),
126
- bold: f("\x1B[1m", "\x1B[22m", "\x1B[22m\x1B[1m"),
127
- dim: f("\x1B[2m", "\x1B[22m", "\x1B[22m\x1B[2m"),
128
- italic: f("\x1B[3m", "\x1B[23m"),
129
- underline: f("\x1B[4m", "\x1B[24m"),
130
- inverse: f("\x1B[7m", "\x1B[27m"),
131
- hidden: f("\x1B[8m", "\x1B[28m"),
132
- strikethrough: f("\x1B[9m", "\x1B[29m"),
133
- black: f("\x1B[30m", "\x1B[39m"),
134
- red: f("\x1B[31m", "\x1B[39m"),
135
- green: f("\x1B[32m", "\x1B[39m"),
136
- yellow: f("\x1B[33m", "\x1B[39m"),
137
- blue: f("\x1B[34m", "\x1B[39m"),
138
- magenta: f("\x1B[35m", "\x1B[39m"),
139
- cyan: f("\x1B[36m", "\x1B[39m"),
140
- white: f("\x1B[37m", "\x1B[39m"),
141
- gray: f("\x1B[90m", "\x1B[39m"),
142
- bgBlack: f("\x1B[40m", "\x1B[49m"),
143
- bgRed: f("\x1B[41m", "\x1B[49m"),
144
- bgGreen: f("\x1B[42m", "\x1B[49m"),
145
- bgYellow: f("\x1B[43m", "\x1B[49m"),
146
- bgBlue: f("\x1B[44m", "\x1B[49m"),
147
- bgMagenta: f("\x1B[45m", "\x1B[49m"),
148
- bgCyan: f("\x1B[46m", "\x1B[49m"),
149
- bgWhite: f("\x1B[47m", "\x1B[49m"),
150
- blackBright: f("\x1B[90m", "\x1B[39m"),
151
- redBright: f("\x1B[91m", "\x1B[39m"),
152
- greenBright: f("\x1B[92m", "\x1B[39m"),
153
- yellowBright: f("\x1B[93m", "\x1B[39m"),
154
- blueBright: f("\x1B[94m", "\x1B[39m"),
155
- magentaBright: f("\x1B[95m", "\x1B[39m"),
156
- cyanBright: f("\x1B[96m", "\x1B[39m"),
157
- whiteBright: f("\x1B[97m", "\x1B[39m"),
158
- bgBlackBright: f("\x1B[100m", "\x1B[49m"),
159
- bgRedBright: f("\x1B[101m", "\x1B[49m"),
160
- bgGreenBright: f("\x1B[102m", "\x1B[49m"),
161
- bgYellowBright: f("\x1B[103m", "\x1B[49m"),
162
- bgBlueBright: f("\x1B[104m", "\x1B[49m"),
163
- bgMagentaBright: f("\x1B[105m", "\x1B[49m"),
164
- bgCyanBright: f("\x1B[106m", "\x1B[49m"),
165
- bgWhiteBright: f("\x1B[107m", "\x1B[49m")
3807
+ module.exports = WebSocketServer2;
3808
+ function addListeners(server, map) {
3809
+ for (const event of Object.keys(map)) server.on(event, map[event]);
3810
+ return function removeListeners() {
3811
+ for (const event of Object.keys(map)) {
3812
+ server.removeListener(event, map[event]);
3813
+ }
166
3814
  };
167
- };
168
- module.exports = createColors();
169
- module.exports.createColors = createColors;
3815
+ }
3816
+ function emitClose(server) {
3817
+ server._state = CLOSED;
3818
+ server.emit("close");
3819
+ }
3820
+ function socketOnError() {
3821
+ this.destroy();
3822
+ }
3823
+ function abortHandshake(socket, code, message, headers) {
3824
+ message = message || http.STATUS_CODES[code];
3825
+ headers = {
3826
+ Connection: "close",
3827
+ "Content-Type": "text/html",
3828
+ "Content-Length": Buffer.byteLength(message),
3829
+ ...headers
3830
+ };
3831
+ socket.once("finish", socket.destroy);
3832
+ socket.end(
3833
+ `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r
3834
+ ` + Object.keys(headers).map((h2) => `${h2}: ${headers[h2]}`).join("\r\n") + "\r\n\r\n" + message
3835
+ );
3836
+ }
3837
+ function abortHandshakeOrEmitwsClientError(server, req, socket, code, message, headers) {
3838
+ if (server.listenerCount("wsClientError")) {
3839
+ const err = new Error(message);
3840
+ Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);
3841
+ server.emit("wsClientError", err, socket, req);
3842
+ } else {
3843
+ abortHandshake(socket, code, message, headers);
3844
+ }
3845
+ }
170
3846
  }
171
3847
  });
172
3848
 
@@ -4451,6 +8127,17 @@ async function syncAgentModelCatalog(input) {
4451
8127
  // apps/body/dist/daemon-api-client.js
4452
8128
  import { resolve as resolve7 } from "node:path";
4453
8129
 
8130
+ // node_modules/ws/wrapper.mjs
8131
+ var import_stream = __toESM(require_stream(), 1);
8132
+ var import_extension = __toESM(require_extension(), 1);
8133
+ var import_permessage_deflate = __toESM(require_permessage_deflate(), 1);
8134
+ var import_receiver = __toESM(require_receiver(), 1);
8135
+ var import_sender = __toESM(require_sender(), 1);
8136
+ var import_subprotocol = __toESM(require_subprotocol(), 1);
8137
+ var import_websocket = __toESM(require_websocket(), 1);
8138
+ var import_websocket_server = __toESM(require_websocket_server(), 1);
8139
+ var wrapper_default = import_websocket.default;
8140
+
4454
8141
  // apps/body/dist/runtime.js
4455
8142
  import { randomBytes as randomBytes5 } from "node:crypto";
4456
8143
  import { execFile } from "node:child_process";
@@ -13217,6 +16904,20 @@ var DaemonApiError = class extends Error {
13217
16904
  }
13218
16905
  };
13219
16906
  var AGENT_REMOVED_CODE = "agent_removed";
16907
+ function laterInboxCursor(left, right) {
16908
+ if (!left)
16909
+ return right;
16910
+ if (!right)
16911
+ return left;
16912
+ const leftMatch = left.match(/^(\d+),([0-9a-f]{64})$/);
16913
+ const rightMatch = right.match(/^(\d+),([0-9a-f]{64})$/);
16914
+ if (!leftMatch || !rightMatch)
16915
+ return right;
16916
+ const timeOrder = BigInt(leftMatch[1]) - BigInt(rightMatch[1]);
16917
+ if (timeOrder !== 0n)
16918
+ return timeOrder > 0n ? left : right;
16919
+ return leftMatch[2] >= rightMatch[2] ? left : right;
16920
+ }
13220
16921
  function isAgentRemovedError(error) {
13221
16922
  return error instanceof DaemonApiError && error.status === 403 && error.code === AGENT_REMOVED_CODE;
13222
16923
  }
@@ -13238,16 +16939,59 @@ var DaemonApiClient = class {
13238
16939
  daemonToken;
13239
16940
  agentId;
13240
16941
  fetchImpl;
13241
- constructor(baseUrl, daemonToken, agentId, fetchImpl = fetch) {
16942
+ webSocketFactory;
16943
+ liveSocket;
16944
+ liveReconnect;
16945
+ liveReconnectDelayMs = 1e3;
16946
+ liveRooms = /* @__PURE__ */ new Map();
16947
+ constructor(baseUrl, daemonToken, agentId, fetchImpl = fetch, webSocketFactory = (url, protocols) => new wrapper_default(url, protocols)) {
13242
16948
  this.baseUrl = baseUrl;
13243
16949
  this.daemonToken = daemonToken;
13244
16950
  this.agentId = agentId;
13245
16951
  this.fetchImpl = fetchImpl;
16952
+ this.webSocketFactory = webSocketFactory;
13246
16953
  }
13247
16954
  /** Connection material for the daemon-owned MCP proxy and corner credentials. */
13248
16955
  connection() {
13249
16956
  return { baseUrl: this.baseUrl, daemonToken: this.daemonToken, agentId: this.agentId };
13250
16957
  }
16958
+ /** Add one Room to this agent's shared live socket. */
16959
+ liveSubscribe(roomId, cursor3, onItems, onState, presence) {
16960
+ const existing = this.liveRooms.get(roomId);
16961
+ if (existing) {
16962
+ existing.cursor = cursor3 ?? existing.cursor;
16963
+ existing.onItems = onItems ?? existing.onItems;
16964
+ existing.onState = onState ?? existing.onState;
16965
+ existing.presence = presence ?? existing.presence;
16966
+ } else {
16967
+ this.liveRooms.set(roomId, {
16968
+ ...cursor3 ? { cursor: cursor3 } : {},
16969
+ pushedIds: /* @__PURE__ */ new Set(),
16970
+ ...onItems ? { onItems } : {},
16971
+ ...onState ? { onState } : {},
16972
+ ...presence ? { presence } : {}
16973
+ });
16974
+ }
16975
+ this.ensureLiveSocket();
16976
+ if (this.liveSocket?.readyState === wrapper_default.OPEN)
16977
+ this.sendLiveSubscription(roomId);
16978
+ return () => {
16979
+ this.liveRooms.delete(roomId);
16980
+ if (this.liveSocket?.readyState === wrapper_default.OPEN) {
16981
+ this.liveSocket.send(JSON.stringify({ type: "unsubscribe", roomId }));
16982
+ }
16983
+ if (!this.liveRooms.size) {
16984
+ clearTimeout(this.liveReconnect);
16985
+ this.liveSocket?.close();
16986
+ this.liveSocket = void 0;
16987
+ }
16988
+ };
16989
+ }
16990
+ updateLiveCursor(roomId, cursor3) {
16991
+ const room = this.liveRooms.get(roomId);
16992
+ if (room && cursor3)
16993
+ room.cursor = cursor3;
16994
+ }
13251
16995
  async execute(name, input) {
13252
16996
  const candidate = input;
13253
16997
  if (typeof candidate.agentId === "string" && candidate.agentId !== this.agentId) {
@@ -13265,6 +17009,82 @@ var DaemonApiClient = class {
13265
17009
  throw await responseError(response);
13266
17010
  return await response.json();
13267
17011
  }
17012
+ ensureLiveSocket() {
17013
+ if (this.liveSocket || !this.liveRooms.size)
17014
+ return;
17015
+ const socket = this.webSocketFactory(this.baseUrl.replace(/^http/, "ws") + "/v1/phone/live", [`bearer.${this.daemonToken}`]);
17016
+ this.liveSocket = socket;
17017
+ socket.onopen = () => {
17018
+ this.liveReconnectDelayMs = 1e3;
17019
+ for (const roomId of this.liveRooms.keys())
17020
+ this.sendLiveSubscription(roomId);
17021
+ };
17022
+ socket.onmessage = (message) => {
17023
+ let value;
17024
+ try {
17025
+ value = JSON.parse(String(message.data));
17026
+ } catch {
17027
+ return;
17028
+ }
17029
+ if (!value || typeof value !== "object")
17030
+ return;
17031
+ const event = value;
17032
+ if (event.type === "subscribed" && typeof event.roomId === "string") {
17033
+ const capabilities = event.capabilities;
17034
+ this.liveRooms.get(event.roomId)?.onState?.(true, {
17035
+ pushIntake: capabilities?.pushIntake === true,
17036
+ connectionPresence: capabilities?.connectionPresence === true
17037
+ });
17038
+ return;
17039
+ }
17040
+ if (event.type !== "inbox" || typeof event.roomId !== "string" || !Array.isArray(event.items))
17041
+ return;
17042
+ const room = this.liveRooms.get(event.roomId);
17043
+ if (!room)
17044
+ return;
17045
+ const items = [];
17046
+ for (const candidate of event.items) {
17047
+ if (!candidate || typeof candidate !== "object")
17048
+ continue;
17049
+ const id = candidate.id;
17050
+ if (typeof id === "string") {
17051
+ if (!room.pushedIds.has(id))
17052
+ items.push(candidate);
17053
+ room.pushedIds.add(id);
17054
+ }
17055
+ }
17056
+ while (room.pushedIds.size > 1e4)
17057
+ room.pushedIds.delete(room.pushedIds.values().next().value);
17058
+ if (items.length)
17059
+ room.onItems?.(items, typeof event.cursor === "string" ? event.cursor : void 0);
17060
+ };
17061
+ const reconnect = () => {
17062
+ if (this.liveSocket !== socket)
17063
+ return;
17064
+ this.liveSocket = void 0;
17065
+ for (const room of this.liveRooms.values())
17066
+ room.onState?.(false);
17067
+ if (!this.liveRooms.size)
17068
+ return;
17069
+ const delay = this.liveReconnectDelayMs;
17070
+ this.liveReconnectDelayMs = Math.min(delay * 2, 3e4);
17071
+ this.liveReconnect = setTimeout(() => this.ensureLiveSocket(), delay);
17072
+ this.liveReconnect.unref?.();
17073
+ };
17074
+ socket.onerror = () => void 0;
17075
+ socket.onclose = reconnect;
17076
+ }
17077
+ sendLiveSubscription(roomId) {
17078
+ const room = this.liveRooms.get(roomId);
17079
+ if (!room || this.liveSocket?.readyState !== wrapper_default.OPEN)
17080
+ return;
17081
+ this.liveSocket.send(JSON.stringify({
17082
+ type: "subscribe",
17083
+ roomId,
17084
+ ...room.cursor ? { cursor: room.cursor } : {},
17085
+ ...room.presence
17086
+ }));
17087
+ }
13268
17088
  };
13269
17089
  async function activateDaemonTransport(path, fetchImpl = fetch) {
13270
17090
  const runtime = await readRuntimeRecord(path);
@@ -16950,6 +20770,14 @@ function cornerClosePollMs(random = Math.random) {
16950
20770
  var MonolithCornerTurnLoop = class {
16951
20771
  options;
16952
20772
  agent;
20773
+ reconciliationRequested = true;
20774
+ wakeIntake;
20775
+ /** Called by the daemon's one slow workspace reconciliation sweep. */
20776
+ requestReconciliation() {
20777
+ this.reconciliationRequested = true;
20778
+ this.wakeIntake?.();
20779
+ this.wakeIntake = void 0;
20780
+ }
16953
20781
  client;
16954
20782
  sessionId;
16955
20783
  /** The configuration the live session baked in; a change invalidates it. */
@@ -17094,11 +20922,9 @@ var MonolithCornerTurnLoop = class {
17094
20922
  })
17095
20923
  }) : {};
17096
20924
  const command = this.options.config.agentCommand ?? this.options.config.agentBinary;
17097
- let githubEnv = {
17098
- GH_TOKEN: this.options.githubToken,
17099
- GITHUB_TOKEN: this.options.githubToken
17100
- };
17101
- if (this.options.config.runtimeConfigPath && this.options.config.agentHomeRoot) {
20925
+ const repository = this.options.repository;
20926
+ let githubEnv = repository ? { GH_TOKEN: repository.githubToken, GITHUB_TOKEN: repository.githubToken } : {};
20927
+ if (repository && this.options.config.runtimeConfigPath && this.options.config.agentHomeRoot) {
17102
20928
  const gitBinary = (await execFileAsync3("which", ["git"])).stdout.trim();
17103
20929
  const ghBinary = await execFileAsync3("which", ["gh"]).then((result) => result.stdout.trim()).catch(() => void 0);
17104
20930
  githubEnv = await installCornerGitHubWrappers({
@@ -17137,7 +20963,7 @@ var MonolithCornerTurnLoop = class {
17137
20963
  mode: "edit",
17138
20964
  cwd: this.options.worktreePath,
17139
20965
  worktreePath: this.options.worktreePath,
17140
- gitCommonDir: this.options.gitCommonDir,
20966
+ ...repository ? { gitCommonDir: repository.gitCommonDir } : {},
17141
20967
  protectedPaths: [this.options.runtime.supervisorRoot],
17142
20968
  harnessStateDirs: stateDirs,
17143
20969
  harnessHomeStateDirs: homeStateDirs,
@@ -17160,19 +20986,21 @@ var MonolithCornerTurnLoop = class {
17160
20986
  this.client = (this.options.createAcpClient ?? ((value) => new AcpClient(value)))(clientOptions);
17161
20987
  await this.client.start();
17162
20988
  const servers = [
17163
- {
17164
- name: "buzz-dev-mcp",
17165
- command: this.options.config.mcpBinary,
17166
- args: [],
17167
- // ACP hosts launch stdio MCP servers with an explicit, sanitized env.
17168
- // This token is minted for this exact corner and is also the credential
17169
- // helper's password source, so its shell commands need the same scope as
17170
- // the corner harness without inheriting any host credentials.
17171
- env: [
17172
- { name: "GH_TOKEN", value: this.options.githubToken },
17173
- { name: "GITHUB_TOKEN", value: this.options.githubToken }
17174
- ]
17175
- },
20989
+ ...repository ? [
20990
+ {
20991
+ name: "buzz-dev-mcp",
20992
+ command: this.options.config.mcpBinary,
20993
+ args: [],
20994
+ // ACP hosts launch stdio MCP servers with an explicit, sanitized env.
20995
+ // This token is minted for this exact corner and is also the credential
20996
+ // helper's password source, so its shell commands need the same scope as
20997
+ // the corner harness without inheriting any host credentials.
20998
+ env: [
20999
+ { name: "GH_TOKEN", value: repository.githubToken },
21000
+ { name: "GITHUB_TOKEN", value: repository.githubToken }
21001
+ ]
21002
+ }
21003
+ ] : [],
17176
21004
  beelineAgentMcpServer(this.options.config, this.options.api, {
17177
21005
  roomId: this.options.parentRoomId,
17178
21006
  workspaceId: this.options.workspaceId,
@@ -17203,17 +21031,23 @@ var MonolithCornerTurnLoop = class {
17203
21031
  systemPrompt: [
17204
21032
  identityInstructions,
17205
21033
  personaInstructions,
17206
- `You are in an isolated git worktree on ${this.options.featureBranch}, targeting ${this.options.targetBranch}.`,
17207
- "Work normally with the full coding tools. Commit and push only this feature branch. Use gh to open its pull request.",
17208
- `This corner is shared: any of its member agents may be addressed in it and work on ${this.options.featureBranch}. Run git pull --rebase origin ${this.options.featureBranch} before you push, and never force-push it.`,
17209
- "PR-opening turn rule: as soon as a pull request exists, print its full GitHub URL as your final response and end the turn immediately. Do not call pr_checks_status in that same turn and do not wait for checks inside it. Then stay idle until a later corner fact or human message starts another turn.",
17210
- 'Never merge because local tests pass or because gh reports passing checks. On a later turn triggered by a server-posted checks-passed note, call beeline-agent pr_checks_status. Merge only when it returns checks="passed", held=false, and approvalPending=false.',
17211
- "Merge the PR yourself only after the checks-passed event shows every check green; if any check failed or is still running, say exactly which and stop - never merge red.",
17212
- "If any human in this corner says hold or do not merge, do not merge until a later human explicitly resumes it.",
17213
- "Do not tag the user when a corner turn finishes: the server posts the merge summary card and its push already cover completion. Tag a human only mid-turn, and only when you need a decision or input.",
17214
- 'GitHub check and merge notes are server lines already in the corner: never restate them (no "checks passed", "CI is green", "PR ready for review"). On a checks turn, say nothing unless you act - a merge or a pushed fix - and then one short line about that.',
17215
- "A human approval in the app asks the server to merge. When approval is pending, wait for the server close request instead of racing it with gh. If checks passed, no hold exists, and no approval is pending, merge the pull request yourself with gh.",
17216
- "Never push directly to the target branch. Never merge a different pull request."
21034
+ ...repository ? [
21035
+ `You are in an isolated git worktree on ${repository.featureBranch}, targeting ${repository.targetBranch}.`,
21036
+ "Work normally with the full coding tools. Commit and push only this feature branch. Use gh to open its pull request.",
21037
+ `This corner is shared: any of its member agents may be addressed in it and work on ${repository.featureBranch}. Run git pull --rebase origin ${repository.featureBranch} before you push, and never force-push it.`,
21038
+ "PR-opening turn rule: as soon as a pull request exists, print its full GitHub URL as your final response and end the turn immediately. Do not call pr_checks_status in that same turn and do not wait for checks inside it. Then stay idle until a later corner fact or human message starts another turn.",
21039
+ 'Never merge because local tests pass or because gh reports passing checks. On a later turn triggered by a server-posted checks-passed note, call beeline-agent pr_checks_status. Merge only when it returns checks="passed", held=false, and approvalPending=false.',
21040
+ "Merge the PR yourself only after the checks-passed event shows every check green; if any check failed or is still running, say exactly which and stop - never merge red.",
21041
+ "If any human in this corner says hold or do not merge, do not merge until a later human explicitly resumes it.",
21042
+ "Do not tag the user when a corner turn finishes: the server posts the merge summary card and its push already cover completion. Tag a human only mid-turn, and only when you need a decision or input.",
21043
+ 'GitHub check and merge notes are server lines already in the corner: never restate them (no "checks passed", "CI is green", "PR ready for review"). On a checks turn, say nothing unless you act - a merge or a pushed fix - and then one short line about that.',
21044
+ "A human approval in the app asks the server to merge. When approval is pending, wait for the server close request instead of racing it with gh. If checks passed, no hold exists, and no approval is pending, merge the pull request yourself with gh.",
21045
+ "Never push directly to the target branch. Never merge a different pull request."
21046
+ ] : [
21047
+ "This is a chat-only corner with no repository or GitHub workflow.",
21048
+ "Work in this corner's writable workspace. Use write_scratch_file or ordinary tools to create files, then attach_file to send them back to the corner.",
21049
+ "Do not initialize a repository, create a branch, push, open a pull request, or wait for GitHub checks."
21050
+ ]
17217
21051
  ].filter(Boolean).join("\n\n")
17218
21052
  });
17219
21053
  this.sessionId = opened.sessionId;
@@ -17346,7 +21180,7 @@ ${this.options.objective}`,
17346
21180
  ${trigger}`,
17347
21181
  ...attachmentPromptLines(attachments, delivered, this.acceptsImages())
17348
21182
  ].join("\n"),
17349
- "Continue the objective. Obey the PR checks and human hold rules in your session instructions.",
21183
+ this.options.repository ? "Continue the objective. Obey the PR checks and human hold rules in your session instructions." : "Continue the objective. Attach completed files before calling close_corner.",
17350
21184
  MAINTAIN_ASSIGNED_IDENTITY_DIRECTIVE
17351
21185
  ].filter(Boolean).join("\n\n");
17352
21186
  const stream = new AgentTurnStream({
@@ -17496,10 +21330,13 @@ ${trigger}`,
17496
21330
  * fails with that sentence and the server inscribes it in the corner.
17497
21331
  */
17498
21332
  async syncBranch() {
17499
- const token = await this.options.api.execute("getRoomGitHubToken", { roomId: this.options.parentRoomId }).then((granted) => granted.token).catch(() => this.options.githubToken);
21333
+ const repository = this.options.repository;
21334
+ if (!repository)
21335
+ return;
21336
+ const token = await this.options.api.execute("getRoomGitHubToken", { roomId: this.options.parentRoomId }).then((granted) => granted.token).catch(() => repository.githubToken);
17500
21337
  await syncCornerBranch({
17501
21338
  worktreePath: this.options.worktreePath,
17502
- featureBranch: this.options.featureBranch,
21339
+ featureBranch: repository.featureBranch,
17503
21340
  env: { ...process.env, GH_TOKEN: token, GITHUB_TOKEN: token, GIT_TERMINAL_PROMPT: "0" }
17504
21341
  });
17505
21342
  }
@@ -17519,7 +21356,32 @@ ${trigger}`,
17519
21356
  }
17520
21357
  async run() {
17521
21358
  const { api, cornerId, signal } = this.options;
17522
- let cursor3 = (await api.execute("getRoomInbox", { roomId: cornerId, startAtLatest: true })).cursor;
21359
+ const activation = await api.execute("getRoomInbox", {
21360
+ roomId: cornerId,
21361
+ startAtLatest: true
21362
+ });
21363
+ let cursor3 = activation.cursor;
21364
+ const processedInboxIds = /* @__PURE__ */ new Set();
21365
+ const pushedInbox = [];
21366
+ let pendingPushedCursor;
21367
+ let liveConnected = false;
21368
+ const rewindSupported = Array.isArray(activation.rewindIds);
21369
+ for (const id of activation.rewindIds ?? [])
21370
+ processedInboxIds.add(id);
21371
+ const stopLive = api.liveSubscribe?.(cornerId, cursor3, (items, pushedCursor) => {
21372
+ pushedInbox.push(...items);
21373
+ pendingPushedCursor = laterInboxCursor(pendingPushedCursor, pushedCursor);
21374
+ this.wakeIntake?.();
21375
+ this.wakeIntake = void 0;
21376
+ }, (connected, capabilities) => {
21377
+ liveConnected = connected && capabilities?.pushIntake === true;
21378
+ this.wakeIntake?.();
21379
+ this.wakeIntake = void 0;
21380
+ }, {
21381
+ ...this.options.config.daemonReleaseVersion ? { releaseVersion: this.options.config.daemonReleaseVersion } : {},
21382
+ ...this.options.config.daemonSourceSha ? { sourceSha: this.options.config.daemonSourceSha } : {},
21383
+ available: !this.options.config.modelUnavailable
21384
+ });
17523
21385
  const history = await api.execute("getRoomConversation", { roomId: cornerId, limit: 200 });
17524
21386
  await this.roster().catch(() => void 0);
17525
21387
  for (const item of history.items)
@@ -17533,16 +21395,27 @@ ${trigger}`,
17533
21395
  let pollWithoutWait = false;
17534
21396
  while (!signal?.aborted) {
17535
21397
  try {
17536
- const inbox = await api.execute("getCornerCloseRequests", {
21398
+ const pollNow = pushedInbox.length > 0 || !liveConnected || this.reconciliationRequested;
21399
+ const inbox = !pollNow ? { items: [], cursor: void 0, closeRequested: false } : await api.execute("getCornerCloseRequests", {
17537
21400
  cornerId,
17538
- ...cursor3 ? { after: cursor3 } : {}
21401
+ ...cursor3 ? { after: cursor3 } : {},
21402
+ ...rewindSupported ? { rewind: true } : {}
17539
21403
  });
21404
+ if (pollNow) {
21405
+ this.reconciliationRequested = false;
21406
+ }
17540
21407
  if (inbox.closeRequested) {
17541
21408
  await this.options.onCloseRequested();
17542
21409
  return;
17543
21410
  }
17544
21411
  const checkNotes = [];
17545
- for (const item of inbox.items) {
21412
+ const delivered = [...pushedInbox.splice(0), ...inbox.items];
21413
+ for (const item of delivered) {
21414
+ if (processedInboxIds.has(item.id))
21415
+ continue;
21416
+ processedInboxIds.add(item.id);
21417
+ while (processedInboxIds.size > 1e4)
21418
+ processedInboxIds.delete(processedInboxIds.values().next().value);
17546
21419
  if (item.type === "message") {
17547
21420
  this.noteCarrier(item.authorId);
17548
21421
  if (item.authorId === this.agent.publicKey)
@@ -17582,11 +21455,16 @@ This answers your grant request; resume the paused work. If approved and it is a
17582
21455
  pollWithoutWait = true;
17583
21456
  }
17584
21457
  }
17585
- cursor3 = inbox.cursor ?? cursor3;
17586
- this.options.onPoll();
21458
+ cursor3 = laterInboxCursor(cursor3, laterInboxCursor(inbox.cursor, pendingPushedCursor));
21459
+ pendingPushedCursor = void 0;
21460
+ api.updateLiveCursor?.(cornerId, cursor3);
21461
+ if (pollNow)
21462
+ this.options.onPoll();
17587
21463
  await Promise.race([
17588
- wait(pollWithoutWait ? 0 : this.options.pollMs ?? cornerClosePollMs(), signal),
17589
- waitForWake(api, cornerId, signal)
21464
+ wait(pollWithoutWait ? 0 : liveConnected ? 2147483647 : this.options.pollMs ?? cornerClosePollMs(), signal),
21465
+ pushedInbox.length ? Promise.resolve() : new Promise((resolve30) => {
21466
+ this.wakeIntake = resolve30;
21467
+ })
17590
21468
  ]);
17591
21469
  pollWithoutWait = false;
17592
21470
  } catch (error) {
@@ -17598,27 +21476,13 @@ This answers your grant request; resume the paused work. If approved and it is a
17598
21476
  }
17599
21477
  }
17600
21478
  } finally {
21479
+ stopLive?.();
21480
+ this.wakeIntake = void 0;
17601
21481
  this.options.grantRunner?.unregister(cornerId);
17602
21482
  await this.options.scheduler.suspend(cornerId);
17603
21483
  }
17604
21484
  }
17605
21485
  };
17606
- async function waitForWake(api, cornerId, signal) {
17607
- if (signal?.aborted)
17608
- return;
17609
- try {
17610
- await api.execute("waitForCornerWake", { cornerId });
17611
- } catch {
17612
- await never(signal);
17613
- }
17614
- }
17615
- async function never(signal) {
17616
- if (signal?.aborted)
17617
- return;
17618
- await new Promise((resolveNever) => {
17619
- signal?.addEventListener("abort", () => resolveNever(), { once: true });
17620
- });
17621
- }
17622
21486
  async function wait(ms, signal) {
17623
21487
  if (signal?.aborted)
17624
21488
  return;
@@ -17766,6 +21630,14 @@ function agentReplyMentionIds(text2, roster, authorId) {
17766
21630
  var MonolithRoomTurnLoop = class {
17767
21631
  options;
17768
21632
  agent;
21633
+ reconciliationRequested = true;
21634
+ wakeIntake;
21635
+ /** Called by the daemon's one slow workspace reconciliation sweep. */
21636
+ requestReconciliation() {
21637
+ this.reconciliationRequested = true;
21638
+ this.wakeIntake?.();
21639
+ this.wakeIntake = void 0;
21640
+ }
17769
21641
  client;
17770
21642
  sessionId;
17771
21643
  /** The configuration the live session baked in; a change invalidates it. */
@@ -18360,7 +22232,10 @@ var MonolithRoomTurnLoop = class {
18360
22232
  async run() {
18361
22233
  const { api, roomId, signal } = this.options;
18362
22234
  const status = this.options.config.modelUnavailable ? "offline" : "online";
18363
- const postPresence = async (presence) => {
22235
+ let legacyPresence = false;
22236
+ let legacyPresenceHeartbeat;
22237
+ let legacyPresenceFallback;
22238
+ const postLegacyPresence = async (presence) => {
18364
22239
  await api.execute("postAgentPresence", {
18365
22240
  agentId: this.agent.publicKey,
18366
22241
  roomId,
@@ -18368,25 +22243,77 @@ var MonolithRoomTurnLoop = class {
18368
22243
  ...this.options.config.daemonReleaseVersion ? { releaseVersion: this.options.config.daemonReleaseVersion } : {},
18369
22244
  ...this.options.config.daemonSourceSha ? { sourceSha: this.options.config.daemonSourceSha } : {}
18370
22245
  });
18371
- this.options.health.presence(presence);
18372
22246
  };
18373
- await postPresence(status);
18374
- const heartbeat = setInterval(() => void postPresence(status).catch((error) => console.error(`[thin-core] monolith Room ${roomId} presence heartbeat failed:`, error)), 3e4);
18375
- heartbeat.unref?.();
22247
+ const useLegacyPresence = () => {
22248
+ if (legacyPresence)
22249
+ return;
22250
+ legacyPresence = true;
22251
+ void postLegacyPresence(status).catch((error) => console.error(`[thin-core] monolith Room ${roomId} presence fallback failed:`, error));
22252
+ legacyPresenceHeartbeat = setInterval(() => void postLegacyPresence(status).catch((error) => console.error(`[thin-core] monolith Room ${roomId} presence fallback failed:`, error)), 3e4);
22253
+ legacyPresenceHeartbeat.unref?.();
22254
+ };
22255
+ const stopLegacyPresence = () => {
22256
+ legacyPresence = false;
22257
+ clearTimeout(legacyPresenceFallback);
22258
+ legacyPresenceFallback = void 0;
22259
+ clearInterval(legacyPresenceHeartbeat);
22260
+ legacyPresenceHeartbeat = void 0;
22261
+ };
18376
22262
  let cursor3;
22263
+ const processedInboxIds = /* @__PURE__ */ new Set();
22264
+ const pushedInbox = [];
22265
+ let pendingPushedCursor;
22266
+ let liveConnected = false;
22267
+ let stopLive;
22268
+ legacyPresenceFallback = setTimeout(useLegacyPresence, 1e3);
22269
+ legacyPresenceFallback.unref?.();
18377
22270
  try {
18378
- cursor3 = (await api.execute("getRoomInbox", { roomId, startAtLatest: true })).cursor;
22271
+ const activation = await api.execute("getRoomInbox", { roomId, startAtLatest: true });
22272
+ cursor3 = activation.cursor;
22273
+ const rewindSupported = Array.isArray(activation.rewindIds);
22274
+ for (const id of activation.rewindIds ?? [])
22275
+ processedInboxIds.add(id);
22276
+ stopLive = api.liveSubscribe?.(roomId, cursor3, (items, pushedCursor) => {
22277
+ pushedInbox.push(...items);
22278
+ pendingPushedCursor = laterInboxCursor(pendingPushedCursor, pushedCursor);
22279
+ this.wakeIntake?.();
22280
+ this.wakeIntake = void 0;
22281
+ }, (connected, capabilities) => {
22282
+ liveConnected = connected && capabilities?.pushIntake === true;
22283
+ if (connected && capabilities?.connectionPresence !== true)
22284
+ useLegacyPresence();
22285
+ else if (connected)
22286
+ stopLegacyPresence();
22287
+ this.options.health.presence(connected && !this.options.config.modelUnavailable ? "online" : "offline");
22288
+ this.wakeIntake?.();
22289
+ this.wakeIntake = void 0;
22290
+ }, {
22291
+ ...this.options.config.daemonReleaseVersion ? { releaseVersion: this.options.config.daemonReleaseVersion } : {},
22292
+ ...this.options.config.daemonSourceSha ? { sourceSha: this.options.config.daemonSourceSha } : {},
22293
+ available: !this.options.config.modelUnavailable
22294
+ });
18379
22295
  while (!signal?.aborted) {
18380
22296
  try {
18381
22297
  if (!this.activeTurn && this.queuedTurns.length) {
18382
22298
  this.startPrompt(this.queuedTurns.shift());
18383
22299
  }
18384
- const inbox = await api.execute("getRoomInbox", {
22300
+ const pollNow = pushedInbox.length === 0 && (!liveConnected || this.reconciliationRequested);
22301
+ const inbox = !pollNow ? { items: [], cursor: void 0 } : await api.execute("getRoomInbox", {
18385
22302
  roomId,
18386
22303
  ...cursor3 ? { after: cursor3 } : {},
22304
+ ...rewindSupported ? { rewind: true } : {},
18387
22305
  limit: 200
18388
22306
  });
18389
- for (const item of inbox.items) {
22307
+ if (pollNow) {
22308
+ this.reconciliationRequested = false;
22309
+ }
22310
+ const delivered = [...pushedInbox.splice(0), ...inbox.items];
22311
+ for (const item of delivered) {
22312
+ if (processedInboxIds.has(item.id))
22313
+ continue;
22314
+ processedInboxIds.add(item.id);
22315
+ while (processedInboxIds.size > 1e4)
22316
+ processedInboxIds.delete(processedInboxIds.values().next().value);
18390
22317
  if (!inboxItemTriggersTurn(item, this.agent.publicKey))
18391
22318
  continue;
18392
22319
  if (!inboxItemSkipsSenderPolicy(item, this.agent.publicKey)) {
@@ -18406,9 +22333,19 @@ var MonolithRoomTurnLoop = class {
18406
22333
  else
18407
22334
  this.queuedTurns.push(item);
18408
22335
  }
18409
- cursor3 = inbox.cursor ?? cursor3;
18410
- this.options.health.poll();
18411
- await wait2(this.options.pollMs ?? 1e3, signal);
22336
+ cursor3 = laterInboxCursor(cursor3, laterInboxCursor(inbox.cursor, pendingPushedCursor));
22337
+ pendingPushedCursor = void 0;
22338
+ api.updateLiveCursor?.(roomId, cursor3);
22339
+ if (pollNow)
22340
+ this.options.health.poll();
22341
+ if (!pushedInbox.length) {
22342
+ await Promise.race([
22343
+ wait2(liveConnected ? 2147483647 : this.options.pollMs ?? 1e3, signal),
22344
+ new Promise((resolve30) => {
22345
+ this.wakeIntake = resolve30;
22346
+ })
22347
+ ]);
22348
+ }
18412
22349
  } catch (error) {
18413
22350
  if (signal?.aborted)
18414
22351
  break;
@@ -18418,13 +22355,18 @@ var MonolithRoomTurnLoop = class {
18418
22355
  }
18419
22356
  }
18420
22357
  } finally {
18421
- clearInterval(heartbeat);
22358
+ stopLive?.();
22359
+ this.wakeIntake = void 0;
18422
22360
  this.options.grantRunner?.unregister(roomId);
18423
22361
  if (this.activeTurn?.phase === "prompting" && this.client && this.sessionId) {
18424
22362
  this.client.sessionCancel(this.sessionId);
18425
22363
  }
18426
22364
  await this.activeTurn?.promise;
18427
- await postPresence("offline").catch((error) => console.error(`[thin-core] monolith Room ${roomId} offline presence failed:`, error));
22365
+ clearTimeout(legacyPresenceFallback);
22366
+ clearInterval(legacyPresenceHeartbeat);
22367
+ if (legacyPresence) {
22368
+ await postLegacyPresence("offline").catch((error) => console.error(`[thin-core] monolith Room ${roomId} offline presence failed:`, error));
22369
+ }
18428
22370
  await this.options.scheduler.suspend(roomId);
18429
22371
  }
18430
22372
  }
@@ -18915,7 +22857,14 @@ async function materializeCornerWorktree(input) {
18915
22857
  "credential.https://github.com.helper",
18916
22858
  "!f() { echo username=x-access-token; echo password=$GH_TOKEN; }; f"
18917
22859
  ]);
18918
- await execFileAsync4("git", ["-C", path, "config", "--worktree", "user.name", input.committer.name]);
22860
+ await execFileAsync4("git", [
22861
+ "-C",
22862
+ path,
22863
+ "config",
22864
+ "--worktree",
22865
+ "user.name",
22866
+ input.committer.name
22867
+ ]);
18919
22868
  await execFileAsync4("git", [
18920
22869
  "-C",
18921
22870
  path,
@@ -18944,6 +22893,13 @@ async function mapWithConcurrency(values, limit, visit) {
18944
22893
  }));
18945
22894
  }
18946
22895
  var execFileAsync4 = promisify4(execFile5);
22896
+ async function removeCornerScratchWorkspace(input) {
22897
+ const expected = resolve19(input.roomRoot, "scratch");
22898
+ if (resolve19(input.scratchPath) !== expected) {
22899
+ throw new Error(`refusing to remove scratch outside corner ${input.cornerId}`);
22900
+ }
22901
+ await rm4(expected, { recursive: true, force: true });
22902
+ }
18947
22903
  var RoomRuntimeCoordinator = class {
18948
22904
  configPath;
18949
22905
  baseConfig;
@@ -19108,6 +23064,8 @@ var RoomRuntimeCoordinator = class {
19108
23064
  await running.promise.catch(() => void 0);
19109
23065
  if (running.worktree)
19110
23066
  await this.reapCornerWorktree(running.worktree);
23067
+ else if (running.scratch)
23068
+ await this.reapCornerScratch(running.scratch);
19111
23069
  }
19112
23070
  await mapWithConcurrency(desiredTopRooms, ROOM_JOIN_CONCURRENCY, async (roomId) => {
19113
23071
  if (!this.running.has(roomId))
@@ -19117,6 +23075,8 @@ var RoomRuntimeCoordinator = class {
19117
23075
  if (!this.running.has(corner.cornerId))
19118
23076
  await this.startCorner(corner);
19119
23077
  });
23078
+ for (const running of this.running.values())
23079
+ running.body.requestReconciliation();
19120
23080
  return "member";
19121
23081
  }
19122
23082
  roomRecord(roomId) {
@@ -19140,8 +23100,7 @@ var RoomRuntimeCoordinator = class {
19140
23100
  return void 0;
19141
23101
  }
19142
23102
  }
19143
- roomConfig(roomId) {
19144
- const workspaceRoot = this.roomRoot(roomId);
23103
+ roomConfig(roomId, workspaceRoot = this.roomRoot(roomId)) {
19145
23104
  const agentHomeRoot = this.roomAgentHomeRoot(workspaceRoot, true);
19146
23105
  return {
19147
23106
  ...this.baseConfig,
@@ -19245,7 +23204,7 @@ var RoomRuntimeCoordinator = class {
19245
23204
  return;
19246
23205
  this.startingCorners.add(corner.cornerId);
19247
23206
  try {
19248
- const [restore, repository, conversation, granted] = await Promise.all([
23207
+ const [restore, repository, conversation] = await Promise.all([
19249
23208
  this.options.daemonApi.execute("getCornerRestoreState", { cornerId: corner.cornerId }),
19250
23209
  this.options.daemonApi.execute("getRoomRepositoryState", {
19251
23210
  roomId: corner.parentRoomId
@@ -19257,28 +23216,35 @@ var RoomRuntimeCoordinator = class {
19257
23216
  roomId: corner.cornerId,
19258
23217
  limit: 200,
19259
23218
  window: "earliest"
19260
- }),
19261
- this.options.daemonApi.execute("getRoomGitHubToken", {
19262
- roomId: corner.parentRoomId
19263
23219
  })
19264
23220
  ]);
19265
- if (repository.resolution !== "repository" || !repository.remote || !repository.key) {
19266
- throw new Error("corner parent Room has no verified repository binding");
23221
+ if (repository.resolution === "unverified") {
23222
+ throw new Error("corner parent Room repository state is not verified yet");
23223
+ }
23224
+ if (repository.resolution === "repository" && (!repository.remote || !repository.key)) {
23225
+ throw new Error("corner parent Room has an incomplete repository binding");
19267
23226
  }
19268
23227
  const objective = conversation.items.find((item) => item.type === "message")?.body.trim();
19269
23228
  if (!objective)
19270
23229
  throw new Error("corner has no durable objective post");
19271
- const targetBranch = repository.targetBranch || "main";
19272
- const featureBranch = restore.featureBranch ?? `feature/corner-${corner.cornerId.replaceAll("-", "").slice(0, 12)}`;
19273
- const worktree = await this.materializeCornerWorktree({
23230
+ const repositoryBacked = repository.resolution === "repository";
23231
+ const targetBranch = repositoryBacked ? repository.targetBranch || "main" : void 0;
23232
+ const featureBranch = repositoryBacked ? restore.featureBranch ?? `feature/corner-${corner.cornerId.replaceAll("-", "").slice(0, 12)}` : void 0;
23233
+ const granted = repositoryBacked ? await this.options.daemonApi.execute("getRoomGitHubToken", {
23234
+ roomId: corner.parentRoomId
23235
+ }) : void 0;
23236
+ const worktree = repositoryBacked ? await this.materializeCornerWorktree({
19274
23237
  cornerId: corner.cornerId,
19275
23238
  remote: repository.remote,
19276
23239
  targetBranch,
19277
23240
  featureBranch,
19278
23241
  token: granted.token
19279
- });
23242
+ }) : void 0;
23243
+ const workspacePath = worktree?.path ?? resolve19(this.roomRoot(corner.cornerId), "scratch");
23244
+ if (!worktree)
23245
+ await mkdir11(workspacePath, { recursive: true, mode: 448 });
19280
23246
  const isOpener = !corner.openedBy || corner.openedBy === this.agent.publicKey;
19281
- if (shouldPostInitialCornerWorkingState(restore, isOpener)) {
23247
+ if (worktree && shouldPostInitialCornerWorkingState(restore, isOpener)) {
19282
23248
  await this.options.daemonApi.execute("postCornerRemoteState", {
19283
23249
  cornerId: corner.cornerId,
19284
23250
  branch: featureBranch,
@@ -19297,23 +23263,27 @@ var RoomRuntimeCoordinator = class {
19297
23263
  workspaceId: this.runtime.communityId,
19298
23264
  ...corner.openedBy ? { openedBy: corner.openedBy } : {},
19299
23265
  objective,
19300
- featureBranch,
19301
- targetBranch,
19302
- worktreePath: worktree.path,
19303
- gitCommonDir: worktree.gitCommonDir,
19304
- githubToken: granted.token,
23266
+ worktreePath: workspacePath,
23267
+ ...worktree ? {
23268
+ repository: {
23269
+ featureBranch,
23270
+ targetBranch,
23271
+ gitCommonDir: worktree.gitCommonDir,
23272
+ githubToken: granted.token
23273
+ }
23274
+ } : {},
19305
23275
  runtime: this.runtime,
19306
- config: this.roomConfig(corner.cornerId),
23276
+ config: this.roomConfig(corner.cornerId, worktree ? void 0 : workspacePath),
19307
23277
  api: this.options.daemonApi,
19308
23278
  scheduler: this.scheduler,
19309
23279
  signal: controller.signal,
19310
23280
  onPoll: () => this.notePoll(corner.cornerId),
19311
23281
  onFailure: (retryInMs) => this.noteFailure(corner.cornerId, retryInMs),
19312
- onCloseRequested: () => this.reapCornerWorktree({
23282
+ onCloseRequested: () => worktree ? this.reapCornerWorktree({
19313
23283
  ...worktree,
19314
23284
  cornerId: corner.cornerId,
19315
23285
  branch: featureBranch
19316
- })
23286
+ }) : this.reapCornerScratch({ path: workspacePath, cornerId: corner.cornerId })
19317
23287
  });
19318
23288
  const promise = loop.run().catch((error) => {
19319
23289
  if (!controller.signal.aborted) {
@@ -19331,14 +23301,17 @@ var RoomRuntimeCoordinator = class {
19331
23301
  lastPollAt: startedAt,
19332
23302
  backoffUntil: 0,
19333
23303
  recovering: false,
19334
- worktree: {
19335
- ...worktree,
19336
- cornerId: corner.cornerId,
19337
- branch: featureBranch
19338
- }
23304
+ ...worktree ? {
23305
+ worktree: {
23306
+ ...worktree,
23307
+ cornerId: corner.cornerId,
23308
+ branch: featureBranch
23309
+ }
23310
+ } : {},
23311
+ ...!worktree ? { scratch: { path: workspacePath, cornerId: corner.cornerId } } : {}
19339
23312
  });
19340
23313
  this.reportedCornerStartFailures.delete(corner.cornerId);
19341
- console.log(`[thin-core] serving corner ${corner.cornerId} on ${featureBranch} at ${worktree.path}`);
23314
+ console.log(worktree ? `[thin-core] serving corner ${corner.cornerId} on ${featureBranch} at ${workspacePath}` : `[thin-core] serving chat-only corner ${corner.cornerId} at ${workspacePath}`);
19342
23315
  } catch (error) {
19343
23316
  console.error(`[thin-core] failed to start corner ${corner.cornerId}:`, error);
19344
23317
  await this.reportCornerStartFailure(corner.cornerId, error);
@@ -19405,6 +23378,13 @@ var RoomRuntimeCoordinator = class {
19405
23378
  checks: "unknown"
19406
23379
  });
19407
23380
  }
23381
+ async reapCornerScratch(scratch) {
23382
+ await removeCornerScratchWorkspace({
23383
+ cornerId: scratch.cornerId,
23384
+ roomRoot: this.roomRoot(scratch.cornerId),
23385
+ scratchPath: scratch.path
23386
+ });
23387
+ }
19408
23388
  notePoll(roomId) {
19409
23389
  const room = this.running.get(roomId);
19410
23390
  if (!room)