remotelink 0.3.14 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,12 +1,3788 @@
1
1
  #!/usr/bin/env node
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
9
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
10
+ }) : x)(function(x) {
11
+ if (typeof require !== "undefined") return require.apply(this, arguments);
12
+ throw Error('Dynamic require of "' + x + '" is not supported');
13
+ });
14
+ var __commonJS = (cb, mod) => function __require2() {
15
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
16
+ };
17
+ var __copyProps = (to, from, except, desc) => {
18
+ if (from && typeof from === "object" || typeof from === "function") {
19
+ for (let key of __getOwnPropNames(from))
20
+ if (!__hasOwnProp.call(to, key) && key !== except)
21
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
22
+ }
23
+ return to;
24
+ };
25
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
26
+ // If the importer is in node compatibility mode or this is not an ESM
27
+ // file that has been converted to a CommonJS file using a Babel-
28
+ // compatible transform (i.e. "__esModule" has not been set), then set
29
+ // "default" to the CommonJS "module.exports" for node compatibility.
30
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
31
+ mod
32
+ ));
33
+
34
+ // ../../node_modules/.pnpm/ws@8.21.3/node_modules/ws/lib/constants.js
35
+ var require_constants = __commonJS({
36
+ "../../node_modules/.pnpm/ws@8.21.3/node_modules/ws/lib/constants.js"(exports, module) {
37
+ "use strict";
38
+ var BINARY_TYPES = ["nodebuffer", "arraybuffer", "fragments"];
39
+ var hasBlob = typeof Blob !== "undefined";
40
+ if (hasBlob) BINARY_TYPES.push("blob");
41
+ module.exports = {
42
+ BINARY_TYPES,
43
+ CLOSE_TIMEOUT: 3e4,
44
+ EMPTY_BUFFER: Buffer.alloc(0),
45
+ GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
46
+ hasBlob,
47
+ kForOnEventAttribute: /* @__PURE__ */ Symbol("kIsForOnEventAttribute"),
48
+ kListener: /* @__PURE__ */ Symbol("kListener"),
49
+ kStatusCode: /* @__PURE__ */ Symbol("status-code"),
50
+ kWebSocket: /* @__PURE__ */ Symbol("websocket"),
51
+ NOOP: () => {
52
+ }
53
+ };
54
+ }
55
+ });
56
+
57
+ // ../../node_modules/.pnpm/ws@8.21.3/node_modules/ws/lib/buffer-util.js
58
+ var require_buffer_util = __commonJS({
59
+ "../../node_modules/.pnpm/ws@8.21.3/node_modules/ws/lib/buffer-util.js"(exports, module) {
60
+ "use strict";
61
+ var { EMPTY_BUFFER } = require_constants();
62
+ var FastBuffer = Buffer[Symbol.species];
63
+ function concat(list, totalLength) {
64
+ if (list.length === 0) return EMPTY_BUFFER;
65
+ if (list.length === 1) return list[0];
66
+ const target = Buffer.allocUnsafe(totalLength);
67
+ let offset = 0;
68
+ for (let i = 0; i < list.length; i++) {
69
+ const buf = list[i];
70
+ target.set(buf, offset);
71
+ offset += buf.length;
72
+ }
73
+ if (offset < totalLength) {
74
+ return new FastBuffer(target.buffer, target.byteOffset, offset);
75
+ }
76
+ return target;
77
+ }
78
+ function _mask(source, mask, output, offset, length) {
79
+ for (let i = 0; i < length; i++) {
80
+ output[offset + i] = source[i] ^ mask[i & 3];
81
+ }
82
+ }
83
+ function _unmask(buffer, mask) {
84
+ for (let i = 0; i < buffer.length; i++) {
85
+ buffer[i] ^= mask[i & 3];
86
+ }
87
+ }
88
+ function toArrayBuffer(buf) {
89
+ if (buf.length === buf.buffer.byteLength) {
90
+ return buf.buffer;
91
+ }
92
+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);
93
+ }
94
+ function toBuffer(data) {
95
+ toBuffer.readOnly = true;
96
+ if (Buffer.isBuffer(data)) return data;
97
+ let buf;
98
+ if (data instanceof ArrayBuffer) {
99
+ buf = new FastBuffer(data);
100
+ } else if (ArrayBuffer.isView(data)) {
101
+ buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);
102
+ } else {
103
+ buf = Buffer.from(data);
104
+ toBuffer.readOnly = false;
105
+ }
106
+ return buf;
107
+ }
108
+ module.exports = {
109
+ concat,
110
+ mask: _mask,
111
+ toArrayBuffer,
112
+ toBuffer,
113
+ unmask: _unmask
114
+ };
115
+ if (!process.env.WS_NO_BUFFER_UTIL) {
116
+ try {
117
+ const bufferUtil = __require("bufferutil");
118
+ module.exports.mask = function(source, mask, output, offset, length) {
119
+ if (length < 48) _mask(source, mask, output, offset, length);
120
+ else bufferUtil.mask(source, mask, output, offset, length);
121
+ };
122
+ module.exports.unmask = function(buffer, mask) {
123
+ if (buffer.length < 32) _unmask(buffer, mask);
124
+ else bufferUtil.unmask(buffer, mask);
125
+ };
126
+ } catch (e) {
127
+ }
128
+ }
129
+ }
130
+ });
131
+
132
+ // ../../node_modules/.pnpm/ws@8.21.3/node_modules/ws/lib/limiter.js
133
+ var require_limiter = __commonJS({
134
+ "../../node_modules/.pnpm/ws@8.21.3/node_modules/ws/lib/limiter.js"(exports, module) {
135
+ "use strict";
136
+ var kDone = /* @__PURE__ */ Symbol("kDone");
137
+ var kRun = /* @__PURE__ */ Symbol("kRun");
138
+ var Limiter = class {
139
+ /**
140
+ * Creates a new `Limiter`.
141
+ *
142
+ * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed
143
+ * to run concurrently
144
+ */
145
+ constructor(concurrency) {
146
+ this[kDone] = () => {
147
+ this.pending--;
148
+ this[kRun]();
149
+ };
150
+ this.concurrency = concurrency || Infinity;
151
+ this.jobs = [];
152
+ this.pending = 0;
153
+ }
154
+ /**
155
+ * Adds a job to the queue.
156
+ *
157
+ * @param {Function} job The job to run
158
+ * @public
159
+ */
160
+ add(job) {
161
+ this.jobs.push(job);
162
+ this[kRun]();
163
+ }
164
+ /**
165
+ * Removes a job from the queue and runs it if possible.
166
+ *
167
+ * @private
168
+ */
169
+ [kRun]() {
170
+ if (this.pending === this.concurrency) return;
171
+ if (this.jobs.length) {
172
+ const job = this.jobs.shift();
173
+ this.pending++;
174
+ job(this[kDone]);
175
+ }
176
+ }
177
+ };
178
+ module.exports = Limiter;
179
+ }
180
+ });
181
+
182
+ // ../../node_modules/.pnpm/ws@8.21.3/node_modules/ws/lib/permessage-deflate.js
183
+ var require_permessage_deflate = __commonJS({
184
+ "../../node_modules/.pnpm/ws@8.21.3/node_modules/ws/lib/permessage-deflate.js"(exports, module) {
185
+ "use strict";
186
+ var zlib = __require("zlib");
187
+ var bufferUtil = require_buffer_util();
188
+ var Limiter = require_limiter();
189
+ var { kStatusCode } = require_constants();
190
+ var FastBuffer = Buffer[Symbol.species];
191
+ var TRAILER = Buffer.from([0, 0, 255, 255]);
192
+ var kPerMessageDeflate = /* @__PURE__ */ Symbol("permessage-deflate");
193
+ var kTotalLength = /* @__PURE__ */ Symbol("total-length");
194
+ var kCallback = /* @__PURE__ */ Symbol("callback");
195
+ var kBuffers = /* @__PURE__ */ Symbol("buffers");
196
+ var kError = /* @__PURE__ */ Symbol("error");
197
+ var zlibLimiter;
198
+ var PerMessageDeflate2 = class {
199
+ /**
200
+ * Creates a PerMessageDeflate instance.
201
+ *
202
+ * @param {Object} [options] Configuration options
203
+ * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support
204
+ * for, or request, a custom client window size
205
+ * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/
206
+ * acknowledge disabling of client context takeover
207
+ * @param {Number} [options.concurrencyLimit=10] The number of concurrent
208
+ * calls to zlib
209
+ * @param {Boolean} [options.isServer=false] Create the instance in either
210
+ * server or client mode
211
+ * @param {Number} [options.maxPayload=0] The maximum allowed message length
212
+ * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the
213
+ * use of a custom server window size
214
+ * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept
215
+ * disabling of server context takeover
216
+ * @param {Number} [options.threshold=1024] Size (in bytes) below which
217
+ * messages should not be compressed if context takeover is disabled
218
+ * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on
219
+ * deflate
220
+ * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on
221
+ * inflate
222
+ */
223
+ constructor(options) {
224
+ this._options = options || {};
225
+ this._threshold = this._options.threshold !== void 0 ? this._options.threshold : 1024;
226
+ this._maxPayload = this._options.maxPayload | 0;
227
+ this._isServer = !!this._options.isServer;
228
+ this._deflate = null;
229
+ this._inflate = null;
230
+ this.params = null;
231
+ if (!zlibLimiter) {
232
+ const concurrency = this._options.concurrencyLimit !== void 0 ? this._options.concurrencyLimit : 10;
233
+ zlibLimiter = new Limiter(concurrency);
234
+ }
235
+ }
236
+ /**
237
+ * @type {String}
238
+ */
239
+ static get extensionName() {
240
+ return "permessage-deflate";
241
+ }
242
+ /**
243
+ * Create an extension negotiation offer.
244
+ *
245
+ * @return {Object} Extension parameters
246
+ * @public
247
+ */
248
+ offer() {
249
+ const params = {};
250
+ if (this._options.serverNoContextTakeover) {
251
+ params.server_no_context_takeover = true;
252
+ }
253
+ if (this._options.clientNoContextTakeover) {
254
+ params.client_no_context_takeover = true;
255
+ }
256
+ if (this._options.serverMaxWindowBits) {
257
+ params.server_max_window_bits = this._options.serverMaxWindowBits;
258
+ }
259
+ if (this._options.clientMaxWindowBits) {
260
+ params.client_max_window_bits = this._options.clientMaxWindowBits;
261
+ } else if (this._options.clientMaxWindowBits == null) {
262
+ params.client_max_window_bits = true;
263
+ }
264
+ return params;
265
+ }
266
+ /**
267
+ * Accept an extension negotiation offer/response.
268
+ *
269
+ * @param {Array} configurations The extension negotiation offers/reponse
270
+ * @return {Object} Accepted configuration
271
+ * @public
272
+ */
273
+ accept(configurations) {
274
+ configurations = this.normalizeParams(configurations);
275
+ this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations);
276
+ return this.params;
277
+ }
278
+ /**
279
+ * Releases all resources used by the extension.
280
+ *
281
+ * @public
282
+ */
283
+ cleanup() {
284
+ if (this._inflate) {
285
+ this._inflate.close();
286
+ this._inflate = null;
287
+ }
288
+ if (this._deflate) {
289
+ const callback = this._deflate[kCallback];
290
+ this._deflate.close();
291
+ this._deflate = null;
292
+ if (callback) {
293
+ callback(
294
+ new Error(
295
+ "The deflate stream was closed while data was being processed"
296
+ )
297
+ );
298
+ }
299
+ }
300
+ }
301
+ /**
302
+ * Accept an extension negotiation offer.
303
+ *
304
+ * @param {Array} offers The extension negotiation offers
305
+ * @return {Object} Accepted configuration
306
+ * @private
307
+ */
308
+ acceptAsServer(offers) {
309
+ const opts = this._options;
310
+ const accepted = offers.find((params) => {
311
+ 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)) {
312
+ return false;
313
+ }
314
+ return true;
315
+ });
316
+ if (!accepted) {
317
+ throw new Error("None of the extension offers can be accepted");
318
+ }
319
+ if (opts.serverNoContextTakeover) {
320
+ accepted.server_no_context_takeover = true;
321
+ }
322
+ if (opts.clientNoContextTakeover) {
323
+ accepted.client_no_context_takeover = true;
324
+ }
325
+ if (typeof opts.serverMaxWindowBits === "number") {
326
+ accepted.server_max_window_bits = opts.serverMaxWindowBits;
327
+ }
328
+ if (typeof opts.clientMaxWindowBits === "number") {
329
+ accepted.client_max_window_bits = opts.clientMaxWindowBits;
330
+ } else if (accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false) {
331
+ delete accepted.client_max_window_bits;
332
+ }
333
+ return accepted;
334
+ }
335
+ /**
336
+ * Accept the extension negotiation response.
337
+ *
338
+ * @param {Array} response The extension negotiation response
339
+ * @return {Object} Accepted configuration
340
+ * @private
341
+ */
342
+ acceptAsClient(response) {
343
+ const params = response[0];
344
+ if (this._options.clientNoContextTakeover === false && params.client_no_context_takeover) {
345
+ throw new Error('Unexpected parameter "client_no_context_takeover"');
346
+ }
347
+ if (!params.client_max_window_bits) {
348
+ if (typeof this._options.clientMaxWindowBits === "number") {
349
+ params.client_max_window_bits = this._options.clientMaxWindowBits;
350
+ }
351
+ } else if (this._options.clientMaxWindowBits === false || typeof this._options.clientMaxWindowBits === "number" && params.client_max_window_bits > this._options.clientMaxWindowBits) {
352
+ throw new Error(
353
+ 'Unexpected or invalid parameter "client_max_window_bits"'
354
+ );
355
+ }
356
+ return params;
357
+ }
358
+ /**
359
+ * Normalize parameters.
360
+ *
361
+ * @param {Array} configurations The extension negotiation offers/reponse
362
+ * @return {Array} The offers/response with normalized parameters
363
+ * @private
364
+ */
365
+ normalizeParams(configurations) {
366
+ configurations.forEach((params) => {
367
+ Object.keys(params).forEach((key) => {
368
+ let value = params[key];
369
+ if (value.length > 1) {
370
+ throw new Error(`Parameter "${key}" must have only a single value`);
371
+ }
372
+ value = value[0];
373
+ if (key === "client_max_window_bits") {
374
+ if (value !== true) {
375
+ const num = +value;
376
+ if (!Number.isInteger(num) || num < 8 || num > 15) {
377
+ throw new TypeError(
378
+ `Invalid value for parameter "${key}": ${value}`
379
+ );
380
+ }
381
+ value = num;
382
+ } else if (!this._isServer) {
383
+ throw new TypeError(
384
+ `Invalid value for parameter "${key}": ${value}`
385
+ );
386
+ }
387
+ } else if (key === "server_max_window_bits") {
388
+ const num = +value;
389
+ if (!Number.isInteger(num) || num < 8 || num > 15) {
390
+ throw new TypeError(
391
+ `Invalid value for parameter "${key}": ${value}`
392
+ );
393
+ }
394
+ value = num;
395
+ } else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") {
396
+ if (value !== true) {
397
+ throw new TypeError(
398
+ `Invalid value for parameter "${key}": ${value}`
399
+ );
400
+ }
401
+ } else {
402
+ throw new Error(`Unknown parameter "${key}"`);
403
+ }
404
+ params[key] = value;
405
+ });
406
+ });
407
+ return configurations;
408
+ }
409
+ /**
410
+ * Decompress data. Concurrency limited.
411
+ *
412
+ * @param {Buffer} data Compressed data
413
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
414
+ * @param {Function} callback Callback
415
+ * @public
416
+ */
417
+ decompress(data, fin, callback) {
418
+ zlibLimiter.add((done) => {
419
+ this._decompress(data, fin, (err, result) => {
420
+ done();
421
+ callback(err, result);
422
+ });
423
+ });
424
+ }
425
+ /**
426
+ * Compress data. Concurrency limited.
427
+ *
428
+ * @param {(Buffer|String)} data Data to compress
429
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
430
+ * @param {Function} callback Callback
431
+ * @public
432
+ */
433
+ compress(data, fin, callback) {
434
+ zlibLimiter.add((done) => {
435
+ this._compress(data, fin, (err, result) => {
436
+ done();
437
+ callback(err, result);
438
+ });
439
+ });
440
+ }
441
+ /**
442
+ * Decompress data.
443
+ *
444
+ * @param {Buffer} data Compressed data
445
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
446
+ * @param {Function} callback Callback
447
+ * @private
448
+ */
449
+ _decompress(data, fin, callback) {
450
+ const endpoint = this._isServer ? "client" : "server";
451
+ if (!this._inflate) {
452
+ const key = `${endpoint}_max_window_bits`;
453
+ const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
454
+ this._inflate = zlib.createInflateRaw({
455
+ ...this._options.zlibInflateOptions,
456
+ windowBits
457
+ });
458
+ this._inflate[kPerMessageDeflate] = this;
459
+ this._inflate[kTotalLength] = 0;
460
+ this._inflate[kBuffers] = [];
461
+ this._inflate.on("error", inflateOnError);
462
+ this._inflate.on("data", inflateOnData);
463
+ }
464
+ this._inflate[kCallback] = callback;
465
+ this._inflate.write(data);
466
+ if (fin) this._inflate.write(TRAILER);
467
+ this._inflate.flush(() => {
468
+ const err = this._inflate[kError];
469
+ if (err) {
470
+ this._inflate.close();
471
+ this._inflate = null;
472
+ callback(err);
473
+ return;
474
+ }
475
+ const data2 = bufferUtil.concat(
476
+ this._inflate[kBuffers],
477
+ this._inflate[kTotalLength]
478
+ );
479
+ if (this._inflate._readableState.endEmitted) {
480
+ this._inflate.close();
481
+ this._inflate = null;
482
+ } else {
483
+ this._inflate[kTotalLength] = 0;
484
+ this._inflate[kBuffers] = [];
485
+ if (fin && this.params[`${endpoint}_no_context_takeover`]) {
486
+ this._inflate.reset();
487
+ }
488
+ }
489
+ callback(null, data2);
490
+ });
491
+ }
492
+ /**
493
+ * Compress data.
494
+ *
495
+ * @param {(Buffer|String)} data Data to compress
496
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
497
+ * @param {Function} callback Callback
498
+ * @private
499
+ */
500
+ _compress(data, fin, callback) {
501
+ const endpoint = this._isServer ? "server" : "client";
502
+ if (!this._deflate) {
503
+ const key = `${endpoint}_max_window_bits`;
504
+ const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
505
+ this._deflate = zlib.createDeflateRaw({
506
+ ...this._options.zlibDeflateOptions,
507
+ windowBits
508
+ });
509
+ this._deflate[kTotalLength] = 0;
510
+ this._deflate[kBuffers] = [];
511
+ this._deflate.on("data", deflateOnData);
512
+ }
513
+ this._deflate[kCallback] = callback;
514
+ this._deflate.write(data);
515
+ this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {
516
+ if (!this._deflate) {
517
+ return;
518
+ }
519
+ let data2 = bufferUtil.concat(
520
+ this._deflate[kBuffers],
521
+ this._deflate[kTotalLength]
522
+ );
523
+ if (fin) {
524
+ data2 = new FastBuffer(data2.buffer, data2.byteOffset, data2.length - 4);
525
+ }
526
+ this._deflate[kCallback] = null;
527
+ this._deflate[kTotalLength] = 0;
528
+ this._deflate[kBuffers] = [];
529
+ if (fin && this.params[`${endpoint}_no_context_takeover`]) {
530
+ this._deflate.reset();
531
+ }
532
+ callback(null, data2);
533
+ });
534
+ }
535
+ };
536
+ module.exports = PerMessageDeflate2;
537
+ function deflateOnData(chunk) {
538
+ this[kBuffers].push(chunk);
539
+ this[kTotalLength] += chunk.length;
540
+ }
541
+ function inflateOnData(chunk) {
542
+ this[kTotalLength] += chunk.length;
543
+ if (this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) {
544
+ this[kBuffers].push(chunk);
545
+ return;
546
+ }
547
+ this[kError] = new RangeError("Max payload size exceeded");
548
+ this[kError].code = "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH";
549
+ this[kError][kStatusCode] = 1009;
550
+ this.removeListener("data", inflateOnData);
551
+ this.reset();
552
+ }
553
+ function inflateOnError(err) {
554
+ this[kPerMessageDeflate]._inflate = null;
555
+ if (this[kError]) {
556
+ this[kCallback](this[kError]);
557
+ return;
558
+ }
559
+ err[kStatusCode] = 1007;
560
+ this[kCallback](err);
561
+ }
562
+ }
563
+ });
564
+
565
+ // ../../node_modules/.pnpm/ws@8.21.3/node_modules/ws/lib/validation.js
566
+ var require_validation = __commonJS({
567
+ "../../node_modules/.pnpm/ws@8.21.3/node_modules/ws/lib/validation.js"(exports, module) {
568
+ "use strict";
569
+ var { isUtf8 } = __require("buffer");
570
+ var { hasBlob } = require_constants();
571
+ var tokenChars = [
572
+ 0,
573
+ 0,
574
+ 0,
575
+ 0,
576
+ 0,
577
+ 0,
578
+ 0,
579
+ 0,
580
+ 0,
581
+ 0,
582
+ 0,
583
+ 0,
584
+ 0,
585
+ 0,
586
+ 0,
587
+ 0,
588
+ // 0 - 15
589
+ 0,
590
+ 0,
591
+ 0,
592
+ 0,
593
+ 0,
594
+ 0,
595
+ 0,
596
+ 0,
597
+ 0,
598
+ 0,
599
+ 0,
600
+ 0,
601
+ 0,
602
+ 0,
603
+ 0,
604
+ 0,
605
+ // 16 - 31
606
+ 0,
607
+ 1,
608
+ 0,
609
+ 1,
610
+ 1,
611
+ 1,
612
+ 1,
613
+ 1,
614
+ 0,
615
+ 0,
616
+ 1,
617
+ 1,
618
+ 0,
619
+ 1,
620
+ 1,
621
+ 0,
622
+ // 32 - 47
623
+ 1,
624
+ 1,
625
+ 1,
626
+ 1,
627
+ 1,
628
+ 1,
629
+ 1,
630
+ 1,
631
+ 1,
632
+ 1,
633
+ 0,
634
+ 0,
635
+ 0,
636
+ 0,
637
+ 0,
638
+ 0,
639
+ // 48 - 63
640
+ 0,
641
+ 1,
642
+ 1,
643
+ 1,
644
+ 1,
645
+ 1,
646
+ 1,
647
+ 1,
648
+ 1,
649
+ 1,
650
+ 1,
651
+ 1,
652
+ 1,
653
+ 1,
654
+ 1,
655
+ 1,
656
+ // 64 - 79
657
+ 1,
658
+ 1,
659
+ 1,
660
+ 1,
661
+ 1,
662
+ 1,
663
+ 1,
664
+ 1,
665
+ 1,
666
+ 1,
667
+ 1,
668
+ 0,
669
+ 0,
670
+ 0,
671
+ 1,
672
+ 1,
673
+ // 80 - 95
674
+ 1,
675
+ 1,
676
+ 1,
677
+ 1,
678
+ 1,
679
+ 1,
680
+ 1,
681
+ 1,
682
+ 1,
683
+ 1,
684
+ 1,
685
+ 1,
686
+ 1,
687
+ 1,
688
+ 1,
689
+ 1,
690
+ // 96 - 111
691
+ 1,
692
+ 1,
693
+ 1,
694
+ 1,
695
+ 1,
696
+ 1,
697
+ 1,
698
+ 1,
699
+ 1,
700
+ 1,
701
+ 1,
702
+ 0,
703
+ 1,
704
+ 0,
705
+ 1,
706
+ 0
707
+ // 112 - 127
708
+ ];
709
+ function isValidStatusCode(code) {
710
+ return code >= 1e3 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006 || code >= 3e3 && code <= 4999;
711
+ }
712
+ function _isValidUTF8(buf) {
713
+ const len = buf.length;
714
+ let i = 0;
715
+ while (i < len) {
716
+ if ((buf[i] & 128) === 0) {
717
+ i++;
718
+ } else if ((buf[i] & 224) === 192) {
719
+ if (i + 1 === len || (buf[i + 1] & 192) !== 128 || (buf[i] & 254) === 192) {
720
+ return false;
721
+ }
722
+ i += 2;
723
+ } else if ((buf[i] & 240) === 224) {
724
+ if (i + 2 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || buf[i] === 224 && (buf[i + 1] & 224) === 128 || // Overlong
725
+ buf[i] === 237 && (buf[i + 1] & 224) === 160) {
726
+ return false;
727
+ }
728
+ i += 3;
729
+ } else if ((buf[i] & 248) === 240) {
730
+ if (i + 3 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || (buf[i + 3] & 192) !== 128 || buf[i] === 240 && (buf[i + 1] & 240) === 128 || // Overlong
731
+ buf[i] === 244 && buf[i + 1] > 143 || buf[i] > 244) {
732
+ return false;
733
+ }
734
+ i += 4;
735
+ } else {
736
+ return false;
737
+ }
738
+ }
739
+ return true;
740
+ }
741
+ function isBlob(value) {
742
+ 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");
743
+ }
744
+ module.exports = {
745
+ isBlob,
746
+ isValidStatusCode,
747
+ isValidUTF8: _isValidUTF8,
748
+ tokenChars
749
+ };
750
+ if (isUtf8) {
751
+ module.exports.isValidUTF8 = function(buf) {
752
+ return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);
753
+ };
754
+ } else if (!process.env.WS_NO_UTF_8_VALIDATE) {
755
+ try {
756
+ const isValidUTF8 = __require("utf-8-validate");
757
+ module.exports.isValidUTF8 = function(buf) {
758
+ return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);
759
+ };
760
+ } catch (e) {
761
+ }
762
+ }
763
+ }
764
+ });
765
+
766
+ // ../../node_modules/.pnpm/ws@8.21.3/node_modules/ws/lib/receiver.js
767
+ var require_receiver = __commonJS({
768
+ "../../node_modules/.pnpm/ws@8.21.3/node_modules/ws/lib/receiver.js"(exports, module) {
769
+ "use strict";
770
+ var { Writable } = __require("stream");
771
+ var PerMessageDeflate2 = require_permessage_deflate();
772
+ var {
773
+ BINARY_TYPES,
774
+ EMPTY_BUFFER,
775
+ kStatusCode,
776
+ kWebSocket
777
+ } = require_constants();
778
+ var { concat, toArrayBuffer, unmask } = require_buffer_util();
779
+ var { isValidStatusCode, isValidUTF8 } = require_validation();
780
+ var FastBuffer = Buffer[Symbol.species];
781
+ var GET_INFO = 0;
782
+ var GET_PAYLOAD_LENGTH_16 = 1;
783
+ var GET_PAYLOAD_LENGTH_64 = 2;
784
+ var GET_MASK = 3;
785
+ var GET_DATA = 4;
786
+ var INFLATING = 5;
787
+ var DEFER_EVENT = 6;
788
+ var Receiver2 = class extends Writable {
789
+ /**
790
+ * Creates a Receiver instance.
791
+ *
792
+ * @param {Object} [options] Options object
793
+ * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
794
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
795
+ * multiple times in the same tick
796
+ * @param {String} [options.binaryType=nodebuffer] The type for binary data
797
+ * @param {Object} [options.extensions] An object containing the negotiated
798
+ * extensions
799
+ * @param {Boolean} [options.isServer=false] Specifies whether to operate in
800
+ * client or server mode
801
+ * @param {Number} [options.maxBufferedChunks=0] The maximum number of
802
+ * buffered data chunks
803
+ * @param {Number} [options.maxFragments=0] The maximum number of message
804
+ * fragments
805
+ * @param {Number} [options.maxPayload=0] The maximum allowed message length
806
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
807
+ * not to skip UTF-8 validation for text and close messages
808
+ */
809
+ constructor(options = {}) {
810
+ super();
811
+ this._allowSynchronousEvents = options.allowSynchronousEvents !== void 0 ? options.allowSynchronousEvents : true;
812
+ this._binaryType = options.binaryType || BINARY_TYPES[0];
813
+ this._extensions = options.extensions || {};
814
+ this._isServer = !!options.isServer;
815
+ this._maxBufferedChunks = options.maxBufferedChunks | 0;
816
+ this._maxFragments = options.maxFragments | 0;
817
+ this._maxPayload = options.maxPayload | 0;
818
+ this._skipUTF8Validation = !!options.skipUTF8Validation;
819
+ this[kWebSocket] = void 0;
820
+ this._bufferedBytes = 0;
821
+ this._buffers = [];
822
+ this._compressed = false;
823
+ this._payloadLength = 0;
824
+ this._mask = void 0;
825
+ this._fragmented = 0;
826
+ this._masked = false;
827
+ this._fin = false;
828
+ this._opcode = 0;
829
+ this._totalPayloadLength = 0;
830
+ this._messageLength = 0;
831
+ this._numFragments = 0;
832
+ this._fragments = [];
833
+ this._errored = false;
834
+ this._loop = false;
835
+ this._state = GET_INFO;
836
+ }
837
+ /**
838
+ * Implements `Writable.prototype._write()`.
839
+ *
840
+ * @param {Buffer} chunk The chunk of data to write
841
+ * @param {String} encoding The character encoding of `chunk`
842
+ * @param {Function} cb Callback
843
+ * @private
844
+ */
845
+ _write(chunk, encoding, cb) {
846
+ if (this._opcode === 8 && this._state == GET_INFO) return cb();
847
+ if (this._maxBufferedChunks > 0 && this._buffers.length >= this._maxBufferedChunks) {
848
+ cb(
849
+ this.createError(
850
+ RangeError,
851
+ "Too many buffered chunks",
852
+ false,
853
+ 1008,
854
+ "WS_ERR_TOO_MANY_BUFFERED_PARTS"
855
+ )
856
+ );
857
+ return;
858
+ }
859
+ this._bufferedBytes += chunk.length;
860
+ this._buffers.push(chunk);
861
+ this.startLoop(cb);
862
+ }
863
+ /**
864
+ * Consumes `n` bytes from the buffered data.
865
+ *
866
+ * @param {Number} n The number of bytes to consume
867
+ * @return {Buffer} The consumed bytes
868
+ * @private
869
+ */
870
+ consume(n) {
871
+ this._bufferedBytes -= n;
872
+ if (n === this._buffers[0].length) return this._buffers.shift();
873
+ if (n < this._buffers[0].length) {
874
+ const buf = this._buffers[0];
875
+ this._buffers[0] = new FastBuffer(
876
+ buf.buffer,
877
+ buf.byteOffset + n,
878
+ buf.length - n
879
+ );
880
+ return new FastBuffer(buf.buffer, buf.byteOffset, n);
881
+ }
882
+ const dst = Buffer.allocUnsafe(n);
883
+ do {
884
+ const buf = this._buffers[0];
885
+ const offset = dst.length - n;
886
+ if (n >= buf.length) {
887
+ dst.set(this._buffers.shift(), offset);
888
+ } else {
889
+ dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);
890
+ this._buffers[0] = new FastBuffer(
891
+ buf.buffer,
892
+ buf.byteOffset + n,
893
+ buf.length - n
894
+ );
895
+ }
896
+ n -= buf.length;
897
+ } while (n > 0);
898
+ return dst;
899
+ }
900
+ /**
901
+ * Starts the parsing loop.
902
+ *
903
+ * @param {Function} cb Callback
904
+ * @private
905
+ */
906
+ startLoop(cb) {
907
+ this._loop = true;
908
+ do {
909
+ switch (this._state) {
910
+ case GET_INFO:
911
+ this.getInfo(cb);
912
+ break;
913
+ case GET_PAYLOAD_LENGTH_16:
914
+ this.getPayloadLength16(cb);
915
+ break;
916
+ case GET_PAYLOAD_LENGTH_64:
917
+ this.getPayloadLength64(cb);
918
+ break;
919
+ case GET_MASK:
920
+ this.getMask();
921
+ break;
922
+ case GET_DATA:
923
+ this.getData(cb);
924
+ break;
925
+ case INFLATING:
926
+ case DEFER_EVENT:
927
+ this._loop = false;
928
+ return;
929
+ }
930
+ } while (this._loop);
931
+ if (!this._errored) cb();
932
+ }
933
+ /**
934
+ * Reads the first two bytes of a frame.
935
+ *
936
+ * @param {Function} cb Callback
937
+ * @private
938
+ */
939
+ getInfo(cb) {
940
+ if (this._bufferedBytes < 2) {
941
+ this._loop = false;
942
+ return;
943
+ }
944
+ const buf = this.consume(2);
945
+ if ((buf[0] & 48) !== 0) {
946
+ const error = this.createError(
947
+ RangeError,
948
+ "RSV2 and RSV3 must be clear",
949
+ true,
950
+ 1002,
951
+ "WS_ERR_UNEXPECTED_RSV_2_3"
952
+ );
953
+ cb(error);
954
+ return;
955
+ }
956
+ const compressed = (buf[0] & 64) === 64;
957
+ if (compressed && !this._extensions[PerMessageDeflate2.extensionName]) {
958
+ const error = this.createError(
959
+ RangeError,
960
+ "RSV1 must be clear",
961
+ true,
962
+ 1002,
963
+ "WS_ERR_UNEXPECTED_RSV_1"
964
+ );
965
+ cb(error);
966
+ return;
967
+ }
968
+ this._fin = (buf[0] & 128) === 128;
969
+ this._opcode = buf[0] & 15;
970
+ this._payloadLength = buf[1] & 127;
971
+ if (this._opcode === 0) {
972
+ if (compressed) {
973
+ const error = this.createError(
974
+ RangeError,
975
+ "RSV1 must be clear",
976
+ true,
977
+ 1002,
978
+ "WS_ERR_UNEXPECTED_RSV_1"
979
+ );
980
+ cb(error);
981
+ return;
982
+ }
983
+ if (!this._fragmented) {
984
+ const error = this.createError(
985
+ RangeError,
986
+ "invalid opcode 0",
987
+ true,
988
+ 1002,
989
+ "WS_ERR_INVALID_OPCODE"
990
+ );
991
+ cb(error);
992
+ return;
993
+ }
994
+ this._opcode = this._fragmented;
995
+ } else if (this._opcode === 1 || this._opcode === 2) {
996
+ if (this._fragmented) {
997
+ const error = this.createError(
998
+ RangeError,
999
+ `invalid opcode ${this._opcode}`,
1000
+ true,
1001
+ 1002,
1002
+ "WS_ERR_INVALID_OPCODE"
1003
+ );
1004
+ cb(error);
1005
+ return;
1006
+ }
1007
+ this._compressed = compressed;
1008
+ } else if (this._opcode > 7 && this._opcode < 11) {
1009
+ if (!this._fin) {
1010
+ const error = this.createError(
1011
+ RangeError,
1012
+ "FIN must be set",
1013
+ true,
1014
+ 1002,
1015
+ "WS_ERR_EXPECTED_FIN"
1016
+ );
1017
+ cb(error);
1018
+ return;
1019
+ }
1020
+ if (compressed) {
1021
+ const error = this.createError(
1022
+ RangeError,
1023
+ "RSV1 must be clear",
1024
+ true,
1025
+ 1002,
1026
+ "WS_ERR_UNEXPECTED_RSV_1"
1027
+ );
1028
+ cb(error);
1029
+ return;
1030
+ }
1031
+ if (this._payloadLength > 125 || this._opcode === 8 && this._payloadLength === 1) {
1032
+ const error = this.createError(
1033
+ RangeError,
1034
+ `invalid payload length ${this._payloadLength}`,
1035
+ true,
1036
+ 1002,
1037
+ "WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"
1038
+ );
1039
+ cb(error);
1040
+ return;
1041
+ }
1042
+ } else {
1043
+ const error = this.createError(
1044
+ RangeError,
1045
+ `invalid opcode ${this._opcode}`,
1046
+ true,
1047
+ 1002,
1048
+ "WS_ERR_INVALID_OPCODE"
1049
+ );
1050
+ cb(error);
1051
+ return;
1052
+ }
1053
+ if (!this._fin && !this._fragmented) this._fragmented = this._opcode;
1054
+ this._masked = (buf[1] & 128) === 128;
1055
+ if (this._isServer) {
1056
+ if (!this._masked) {
1057
+ const error = this.createError(
1058
+ RangeError,
1059
+ "MASK must be set",
1060
+ true,
1061
+ 1002,
1062
+ "WS_ERR_EXPECTED_MASK"
1063
+ );
1064
+ cb(error);
1065
+ return;
1066
+ }
1067
+ } else if (this._masked) {
1068
+ const error = this.createError(
1069
+ RangeError,
1070
+ "MASK must be clear",
1071
+ true,
1072
+ 1002,
1073
+ "WS_ERR_UNEXPECTED_MASK"
1074
+ );
1075
+ cb(error);
1076
+ return;
1077
+ }
1078
+ if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;
1079
+ else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;
1080
+ else this.haveLength(cb);
1081
+ }
1082
+ /**
1083
+ * Gets extended payload length (7+16).
1084
+ *
1085
+ * @param {Function} cb Callback
1086
+ * @private
1087
+ */
1088
+ getPayloadLength16(cb) {
1089
+ if (this._bufferedBytes < 2) {
1090
+ this._loop = false;
1091
+ return;
1092
+ }
1093
+ this._payloadLength = this.consume(2).readUInt16BE(0);
1094
+ this.haveLength(cb);
1095
+ }
1096
+ /**
1097
+ * Gets extended payload length (7+64).
1098
+ *
1099
+ * @param {Function} cb Callback
1100
+ * @private
1101
+ */
1102
+ getPayloadLength64(cb) {
1103
+ if (this._bufferedBytes < 8) {
1104
+ this._loop = false;
1105
+ return;
1106
+ }
1107
+ const buf = this.consume(8);
1108
+ const num = buf.readUInt32BE(0);
1109
+ if (num > Math.pow(2, 53 - 32) - 1) {
1110
+ const error = this.createError(
1111
+ RangeError,
1112
+ "Unsupported WebSocket frame: payload length > 2^53 - 1",
1113
+ false,
1114
+ 1009,
1115
+ "WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH"
1116
+ );
1117
+ cb(error);
1118
+ return;
1119
+ }
1120
+ this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
1121
+ this.haveLength(cb);
1122
+ }
1123
+ /**
1124
+ * Payload length has been read.
1125
+ *
1126
+ * @param {Function} cb Callback
1127
+ * @private
1128
+ */
1129
+ haveLength(cb) {
1130
+ if (this._payloadLength && this._opcode < 8) {
1131
+ this._totalPayloadLength += this._payloadLength;
1132
+ if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
1133
+ const error = this.createError(
1134
+ RangeError,
1135
+ "Max payload size exceeded",
1136
+ false,
1137
+ 1009,
1138
+ "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
1139
+ );
1140
+ cb(error);
1141
+ return;
1142
+ }
1143
+ }
1144
+ if (this._masked) this._state = GET_MASK;
1145
+ else this._state = GET_DATA;
1146
+ }
1147
+ /**
1148
+ * Reads mask bytes.
1149
+ *
1150
+ * @private
1151
+ */
1152
+ getMask() {
1153
+ if (this._bufferedBytes < 4) {
1154
+ this._loop = false;
1155
+ return;
1156
+ }
1157
+ this._mask = this.consume(4);
1158
+ this._state = GET_DATA;
1159
+ }
1160
+ /**
1161
+ * Reads data bytes.
1162
+ *
1163
+ * @param {Function} cb Callback
1164
+ * @private
1165
+ */
1166
+ getData(cb) {
1167
+ let data = EMPTY_BUFFER;
1168
+ if (this._payloadLength) {
1169
+ if (this._bufferedBytes < this._payloadLength) {
1170
+ this._loop = false;
1171
+ return;
1172
+ }
1173
+ data = this.consume(this._payloadLength);
1174
+ if (this._masked && (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0) {
1175
+ unmask(data, this._mask);
1176
+ }
1177
+ }
1178
+ if (this._opcode > 7) {
1179
+ this.controlMessage(data, cb);
1180
+ return;
1181
+ }
1182
+ if (this._maxFragments > 0 && ++this._numFragments > this._maxFragments) {
1183
+ const error = this.createError(
1184
+ RangeError,
1185
+ "Too many message fragments",
1186
+ false,
1187
+ 1008,
1188
+ "WS_ERR_TOO_MANY_BUFFERED_PARTS"
1189
+ );
1190
+ cb(error);
1191
+ return;
1192
+ }
1193
+ if (this._compressed) {
1194
+ this._state = INFLATING;
1195
+ this.decompress(data, cb);
1196
+ return;
1197
+ }
1198
+ if (data.length) {
1199
+ this._messageLength = this._totalPayloadLength;
1200
+ this._fragments.push(data);
1201
+ }
1202
+ this.dataMessage(cb);
1203
+ }
1204
+ /**
1205
+ * Decompresses data.
1206
+ *
1207
+ * @param {Buffer} data Compressed data
1208
+ * @param {Function} cb Callback
1209
+ * @private
1210
+ */
1211
+ decompress(data, cb) {
1212
+ const perMessageDeflate = this._extensions[PerMessageDeflate2.extensionName];
1213
+ perMessageDeflate.decompress(data, this._fin, (err, buf) => {
1214
+ if (err) return cb(err);
1215
+ if (buf.length) {
1216
+ this._messageLength += buf.length;
1217
+ if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
1218
+ const error = this.createError(
1219
+ RangeError,
1220
+ "Max payload size exceeded",
1221
+ false,
1222
+ 1009,
1223
+ "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
1224
+ );
1225
+ cb(error);
1226
+ return;
1227
+ }
1228
+ this._fragments.push(buf);
1229
+ }
1230
+ this.dataMessage(cb);
1231
+ if (this._state === GET_INFO) this.startLoop(cb);
1232
+ });
1233
+ }
1234
+ /**
1235
+ * Handles a data message.
1236
+ *
1237
+ * @param {Function} cb Callback
1238
+ * @private
1239
+ */
1240
+ dataMessage(cb) {
1241
+ if (!this._fin) {
1242
+ this._state = GET_INFO;
1243
+ return;
1244
+ }
1245
+ const messageLength = this._messageLength;
1246
+ const fragments = this._fragments;
1247
+ this._totalPayloadLength = 0;
1248
+ this._messageLength = 0;
1249
+ this._fragmented = 0;
1250
+ this._numFragments = 0;
1251
+ this._fragments = [];
1252
+ if (this._opcode === 2) {
1253
+ let data;
1254
+ if (this._binaryType === "nodebuffer") {
1255
+ data = concat(fragments, messageLength);
1256
+ } else if (this._binaryType === "arraybuffer") {
1257
+ data = toArrayBuffer(concat(fragments, messageLength));
1258
+ } else if (this._binaryType === "blob") {
1259
+ data = new Blob(fragments);
1260
+ } else {
1261
+ data = fragments;
1262
+ }
1263
+ if (this._allowSynchronousEvents) {
1264
+ this.emit("message", data, true);
1265
+ this._state = GET_INFO;
1266
+ } else {
1267
+ this._state = DEFER_EVENT;
1268
+ setImmediate(() => {
1269
+ this.emit("message", data, true);
1270
+ this._state = GET_INFO;
1271
+ this.startLoop(cb);
1272
+ });
1273
+ }
1274
+ } else {
1275
+ const buf = concat(fragments, messageLength);
1276
+ if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
1277
+ const error = this.createError(
1278
+ Error,
1279
+ "invalid UTF-8 sequence",
1280
+ true,
1281
+ 1007,
1282
+ "WS_ERR_INVALID_UTF8"
1283
+ );
1284
+ cb(error);
1285
+ return;
1286
+ }
1287
+ if (this._state === INFLATING || this._allowSynchronousEvents) {
1288
+ this.emit("message", buf, false);
1289
+ this._state = GET_INFO;
1290
+ } else {
1291
+ this._state = DEFER_EVENT;
1292
+ setImmediate(() => {
1293
+ this.emit("message", buf, false);
1294
+ this._state = GET_INFO;
1295
+ this.startLoop(cb);
1296
+ });
1297
+ }
1298
+ }
1299
+ }
1300
+ /**
1301
+ * Handles a control message.
1302
+ *
1303
+ * @param {Buffer} data Data to handle
1304
+ * @return {(Error|RangeError|undefined)} A possible error
1305
+ * @private
1306
+ */
1307
+ controlMessage(data, cb) {
1308
+ if (this._opcode === 8) {
1309
+ if (data.length === 0) {
1310
+ this._loop = false;
1311
+ this.emit("conclude", 1005, EMPTY_BUFFER);
1312
+ this.end();
1313
+ } else {
1314
+ const code = data.readUInt16BE(0);
1315
+ if (!isValidStatusCode(code)) {
1316
+ const error = this.createError(
1317
+ RangeError,
1318
+ `invalid status code ${code}`,
1319
+ true,
1320
+ 1002,
1321
+ "WS_ERR_INVALID_CLOSE_CODE"
1322
+ );
1323
+ cb(error);
1324
+ return;
1325
+ }
1326
+ const buf = new FastBuffer(
1327
+ data.buffer,
1328
+ data.byteOffset + 2,
1329
+ data.length - 2
1330
+ );
1331
+ if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
1332
+ const error = this.createError(
1333
+ Error,
1334
+ "invalid UTF-8 sequence",
1335
+ true,
1336
+ 1007,
1337
+ "WS_ERR_INVALID_UTF8"
1338
+ );
1339
+ cb(error);
1340
+ return;
1341
+ }
1342
+ this._loop = false;
1343
+ this.emit("conclude", code, buf);
1344
+ this.end();
1345
+ }
1346
+ this._state = GET_INFO;
1347
+ return;
1348
+ }
1349
+ if (this._allowSynchronousEvents) {
1350
+ this.emit(this._opcode === 9 ? "ping" : "pong", data);
1351
+ this._state = GET_INFO;
1352
+ } else {
1353
+ this._state = DEFER_EVENT;
1354
+ setImmediate(() => {
1355
+ this.emit(this._opcode === 9 ? "ping" : "pong", data);
1356
+ this._state = GET_INFO;
1357
+ this.startLoop(cb);
1358
+ });
1359
+ }
1360
+ }
1361
+ /**
1362
+ * Builds an error object.
1363
+ *
1364
+ * @param {function(new:Error|RangeError)} ErrorCtor The error constructor
1365
+ * @param {String} message The error message
1366
+ * @param {Boolean} prefix Specifies whether or not to add a default prefix to
1367
+ * `message`
1368
+ * @param {Number} statusCode The status code
1369
+ * @param {String} errorCode The exposed error code
1370
+ * @return {(Error|RangeError)} The error
1371
+ * @private
1372
+ */
1373
+ createError(ErrorCtor, message, prefix, statusCode, errorCode) {
1374
+ this._loop = false;
1375
+ this._errored = true;
1376
+ const err = new ErrorCtor(
1377
+ prefix ? `Invalid WebSocket frame: ${message}` : message
1378
+ );
1379
+ Error.captureStackTrace(err, this.createError);
1380
+ err.code = errorCode;
1381
+ err[kStatusCode] = statusCode;
1382
+ return err;
1383
+ }
1384
+ };
1385
+ module.exports = Receiver2;
1386
+ }
1387
+ });
1388
+
1389
+ // ../../node_modules/.pnpm/ws@8.21.3/node_modules/ws/lib/sender.js
1390
+ var require_sender = __commonJS({
1391
+ "../../node_modules/.pnpm/ws@8.21.3/node_modules/ws/lib/sender.js"(exports, module) {
1392
+ "use strict";
1393
+ var { Duplex } = __require("stream");
1394
+ var { randomFillSync } = __require("crypto");
1395
+ var {
1396
+ types: { isUint8Array }
1397
+ } = __require("util");
1398
+ var PerMessageDeflate2 = require_permessage_deflate();
1399
+ var { EMPTY_BUFFER, kWebSocket, NOOP } = require_constants();
1400
+ var { isBlob, isValidStatusCode } = require_validation();
1401
+ var { mask: applyMask, toBuffer } = require_buffer_util();
1402
+ var kByteLength = /* @__PURE__ */ Symbol("kByteLength");
1403
+ var maskBuffer = Buffer.alloc(4);
1404
+ var RANDOM_POOL_SIZE = 8 * 1024;
1405
+ var randomPool;
1406
+ var randomPoolPointer = RANDOM_POOL_SIZE;
1407
+ var DEFAULT = 0;
1408
+ var DEFLATING = 1;
1409
+ var GET_BLOB_DATA = 2;
1410
+ var Sender2 = class _Sender {
1411
+ /**
1412
+ * Creates a Sender instance.
1413
+ *
1414
+ * @param {Duplex} socket The connection socket
1415
+ * @param {Object} [extensions] An object containing the negotiated extensions
1416
+ * @param {Function} [generateMask] The function used to generate the masking
1417
+ * key
1418
+ */
1419
+ constructor(socket, extensions, generateMask) {
1420
+ this._extensions = extensions || {};
1421
+ if (generateMask) {
1422
+ this._generateMask = generateMask;
1423
+ this._maskBuffer = Buffer.alloc(4);
1424
+ }
1425
+ this._socket = socket;
1426
+ this._firstFragment = true;
1427
+ this._compress = false;
1428
+ this._bufferedBytes = 0;
1429
+ this._queue = [];
1430
+ this._state = DEFAULT;
1431
+ this.onerror = NOOP;
1432
+ this[kWebSocket] = void 0;
1433
+ }
1434
+ /**
1435
+ * Frames a piece of data according to the HyBi WebSocket protocol.
1436
+ *
1437
+ * @param {(Buffer|String)} data The data to frame
1438
+ * @param {Object} options Options object
1439
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
1440
+ * FIN bit
1441
+ * @param {Function} [options.generateMask] The function used to generate the
1442
+ * masking key
1443
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1444
+ * `data`
1445
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
1446
+ * key
1447
+ * @param {Number} options.opcode The opcode
1448
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
1449
+ * modified
1450
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
1451
+ * RSV1 bit
1452
+ * @return {(Buffer|String)[]} The framed data
1453
+ * @public
1454
+ */
1455
+ static frame(data, options) {
1456
+ let mask;
1457
+ let merge = false;
1458
+ let offset = 2;
1459
+ let skipMasking = false;
1460
+ if (options.mask) {
1461
+ mask = options.maskBuffer || maskBuffer;
1462
+ if (options.generateMask) {
1463
+ options.generateMask(mask);
1464
+ } else {
1465
+ if (randomPoolPointer === RANDOM_POOL_SIZE) {
1466
+ if (randomPool === void 0) {
1467
+ randomPool = Buffer.alloc(RANDOM_POOL_SIZE);
1468
+ }
1469
+ randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);
1470
+ randomPoolPointer = 0;
1471
+ }
1472
+ mask[0] = randomPool[randomPoolPointer++];
1473
+ mask[1] = randomPool[randomPoolPointer++];
1474
+ mask[2] = randomPool[randomPoolPointer++];
1475
+ mask[3] = randomPool[randomPoolPointer++];
1476
+ }
1477
+ skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;
1478
+ offset = 6;
1479
+ }
1480
+ let dataLength;
1481
+ if (typeof data === "string") {
1482
+ if ((!options.mask || skipMasking) && options[kByteLength] !== void 0) {
1483
+ dataLength = options[kByteLength];
1484
+ } else {
1485
+ data = Buffer.from(data);
1486
+ dataLength = data.length;
1487
+ }
1488
+ } else {
1489
+ dataLength = data.length;
1490
+ merge = options.mask && options.readOnly && !skipMasking;
1491
+ }
1492
+ let payloadLength = dataLength;
1493
+ if (dataLength >= 65536) {
1494
+ offset += 8;
1495
+ payloadLength = 127;
1496
+ } else if (dataLength > 125) {
1497
+ offset += 2;
1498
+ payloadLength = 126;
1499
+ }
1500
+ const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);
1501
+ target[0] = options.fin ? options.opcode | 128 : options.opcode;
1502
+ if (options.rsv1) target[0] |= 64;
1503
+ target[1] = payloadLength;
1504
+ if (payloadLength === 126) {
1505
+ target.writeUInt16BE(dataLength, 2);
1506
+ } else if (payloadLength === 127) {
1507
+ target[2] = target[3] = 0;
1508
+ target.writeUIntBE(dataLength, 4, 6);
1509
+ }
1510
+ if (!options.mask) return [target, data];
1511
+ target[1] |= 128;
1512
+ target[offset - 4] = mask[0];
1513
+ target[offset - 3] = mask[1];
1514
+ target[offset - 2] = mask[2];
1515
+ target[offset - 1] = mask[3];
1516
+ if (skipMasking) return [target, data];
1517
+ if (merge) {
1518
+ applyMask(data, mask, target, offset, dataLength);
1519
+ return [target];
1520
+ }
1521
+ applyMask(data, mask, data, 0, dataLength);
1522
+ return [target, data];
1523
+ }
1524
+ /**
1525
+ * Sends a close message to the other peer.
1526
+ *
1527
+ * @param {Number} [code] The status code component of the body
1528
+ * @param {(String|Buffer)} [data] The message component of the body
1529
+ * @param {Boolean} [mask=false] Specifies whether or not to mask the message
1530
+ * @param {Function} [cb] Callback
1531
+ * @public
1532
+ */
1533
+ close(code, data, mask, cb) {
1534
+ let buf;
1535
+ if (code === void 0) {
1536
+ buf = EMPTY_BUFFER;
1537
+ } else if (typeof code !== "number" || !isValidStatusCode(code)) {
1538
+ throw new TypeError("First argument must be a valid error code number");
1539
+ } else if (data === void 0 || !data.length) {
1540
+ buf = Buffer.allocUnsafe(2);
1541
+ buf.writeUInt16BE(code, 0);
1542
+ } else {
1543
+ const length = Buffer.byteLength(data);
1544
+ if (length > 123) {
1545
+ throw new RangeError("The message must not be greater than 123 bytes");
1546
+ }
1547
+ buf = Buffer.allocUnsafe(2 + length);
1548
+ buf.writeUInt16BE(code, 0);
1549
+ if (typeof data === "string") {
1550
+ buf.write(data, 2);
1551
+ } else if (isUint8Array(data)) {
1552
+ buf.set(data, 2);
1553
+ } else {
1554
+ throw new TypeError("Second argument must be a string or a Uint8Array");
1555
+ }
1556
+ }
1557
+ const options = {
1558
+ [kByteLength]: buf.length,
1559
+ fin: true,
1560
+ generateMask: this._generateMask,
1561
+ mask,
1562
+ maskBuffer: this._maskBuffer,
1563
+ opcode: 8,
1564
+ readOnly: false,
1565
+ rsv1: false
1566
+ };
1567
+ if (this._state !== DEFAULT) {
1568
+ this.enqueue([this.dispatch, buf, false, options, cb]);
1569
+ } else {
1570
+ this.sendFrame(_Sender.frame(buf, options), cb);
1571
+ }
1572
+ }
1573
+ /**
1574
+ * Sends a ping message to the other peer.
1575
+ *
1576
+ * @param {*} data The message to send
1577
+ * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
1578
+ * @param {Function} [cb] Callback
1579
+ * @public
1580
+ */
1581
+ ping(data, mask, cb) {
1582
+ let byteLength;
1583
+ let readOnly;
1584
+ if (typeof data === "string") {
1585
+ byteLength = Buffer.byteLength(data);
1586
+ readOnly = false;
1587
+ } else if (isBlob(data)) {
1588
+ byteLength = data.size;
1589
+ readOnly = false;
1590
+ } else {
1591
+ data = toBuffer(data);
1592
+ byteLength = data.length;
1593
+ readOnly = toBuffer.readOnly;
1594
+ }
1595
+ if (byteLength > 125) {
1596
+ throw new RangeError("The data size must not be greater than 125 bytes");
1597
+ }
1598
+ const options = {
1599
+ [kByteLength]: byteLength,
1600
+ fin: true,
1601
+ generateMask: this._generateMask,
1602
+ mask,
1603
+ maskBuffer: this._maskBuffer,
1604
+ opcode: 9,
1605
+ readOnly,
1606
+ rsv1: false
1607
+ };
1608
+ if (isBlob(data)) {
1609
+ if (this._state !== DEFAULT) {
1610
+ this.enqueue([this.getBlobData, data, false, options, cb]);
1611
+ } else {
1612
+ this.getBlobData(data, false, options, cb);
1613
+ }
1614
+ } else if (this._state !== DEFAULT) {
1615
+ this.enqueue([this.dispatch, data, false, options, cb]);
1616
+ } else {
1617
+ this.sendFrame(_Sender.frame(data, options), cb);
1618
+ }
1619
+ }
1620
+ /**
1621
+ * Sends a pong message to the other peer.
1622
+ *
1623
+ * @param {*} data The message to send
1624
+ * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
1625
+ * @param {Function} [cb] Callback
1626
+ * @public
1627
+ */
1628
+ pong(data, mask, cb) {
1629
+ let byteLength;
1630
+ let readOnly;
1631
+ if (typeof data === "string") {
1632
+ byteLength = Buffer.byteLength(data);
1633
+ readOnly = false;
1634
+ } else if (isBlob(data)) {
1635
+ byteLength = data.size;
1636
+ readOnly = false;
1637
+ } else {
1638
+ data = toBuffer(data);
1639
+ byteLength = data.length;
1640
+ readOnly = toBuffer.readOnly;
1641
+ }
1642
+ if (byteLength > 125) {
1643
+ throw new RangeError("The data size must not be greater than 125 bytes");
1644
+ }
1645
+ const options = {
1646
+ [kByteLength]: byteLength,
1647
+ fin: true,
1648
+ generateMask: this._generateMask,
1649
+ mask,
1650
+ maskBuffer: this._maskBuffer,
1651
+ opcode: 10,
1652
+ readOnly,
1653
+ rsv1: false
1654
+ };
1655
+ if (isBlob(data)) {
1656
+ if (this._state !== DEFAULT) {
1657
+ this.enqueue([this.getBlobData, data, false, options, cb]);
1658
+ } else {
1659
+ this.getBlobData(data, false, options, cb);
1660
+ }
1661
+ } else if (this._state !== DEFAULT) {
1662
+ this.enqueue([this.dispatch, data, false, options, cb]);
1663
+ } else {
1664
+ this.sendFrame(_Sender.frame(data, options), cb);
1665
+ }
1666
+ }
1667
+ /**
1668
+ * Sends a data message to the other peer.
1669
+ *
1670
+ * @param {*} data The message to send
1671
+ * @param {Object} options Options object
1672
+ * @param {Boolean} [options.binary=false] Specifies whether `data` is binary
1673
+ * or text
1674
+ * @param {Boolean} [options.compress=false] Specifies whether or not to
1675
+ * compress `data`
1676
+ * @param {Boolean} [options.fin=false] Specifies whether the fragment is the
1677
+ * last one
1678
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1679
+ * `data`
1680
+ * @param {Function} [cb] Callback
1681
+ * @public
1682
+ */
1683
+ send(data, options, cb) {
1684
+ const perMessageDeflate = this._extensions[PerMessageDeflate2.extensionName];
1685
+ let opcode = options.binary ? 2 : 1;
1686
+ let rsv1 = options.compress;
1687
+ let byteLength;
1688
+ let readOnly;
1689
+ if (typeof data === "string") {
1690
+ byteLength = Buffer.byteLength(data);
1691
+ readOnly = false;
1692
+ } else if (isBlob(data)) {
1693
+ byteLength = data.size;
1694
+ readOnly = false;
1695
+ } else {
1696
+ data = toBuffer(data);
1697
+ byteLength = data.length;
1698
+ readOnly = toBuffer.readOnly;
1699
+ }
1700
+ if (this._firstFragment) {
1701
+ this._firstFragment = false;
1702
+ if (rsv1 && perMessageDeflate && perMessageDeflate.params[perMessageDeflate._isServer ? "server_no_context_takeover" : "client_no_context_takeover"]) {
1703
+ rsv1 = byteLength >= perMessageDeflate._threshold;
1704
+ }
1705
+ this._compress = rsv1;
1706
+ } else {
1707
+ rsv1 = false;
1708
+ opcode = 0;
1709
+ }
1710
+ if (options.fin) this._firstFragment = true;
1711
+ const opts = {
1712
+ [kByteLength]: byteLength,
1713
+ fin: options.fin,
1714
+ generateMask: this._generateMask,
1715
+ mask: options.mask,
1716
+ maskBuffer: this._maskBuffer,
1717
+ opcode,
1718
+ readOnly,
1719
+ rsv1
1720
+ };
1721
+ if (isBlob(data)) {
1722
+ if (this._state !== DEFAULT) {
1723
+ this.enqueue([this.getBlobData, data, this._compress, opts, cb]);
1724
+ } else {
1725
+ this.getBlobData(data, this._compress, opts, cb);
1726
+ }
1727
+ } else if (this._state !== DEFAULT) {
1728
+ this.enqueue([this.dispatch, data, this._compress, opts, cb]);
1729
+ } else {
1730
+ this.dispatch(data, this._compress, opts, cb);
1731
+ }
1732
+ }
1733
+ /**
1734
+ * Gets the contents of a blob as binary data.
1735
+ *
1736
+ * @param {Blob} blob The blob
1737
+ * @param {Boolean} [compress=false] Specifies whether or not to compress
1738
+ * the data
1739
+ * @param {Object} options Options object
1740
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
1741
+ * FIN bit
1742
+ * @param {Function} [options.generateMask] The function used to generate the
1743
+ * masking key
1744
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1745
+ * `data`
1746
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
1747
+ * key
1748
+ * @param {Number} options.opcode The opcode
1749
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
1750
+ * modified
1751
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
1752
+ * RSV1 bit
1753
+ * @param {Function} [cb] Callback
1754
+ * @private
1755
+ */
1756
+ getBlobData(blob, compress, options, cb) {
1757
+ this._bufferedBytes += options[kByteLength];
1758
+ this._state = GET_BLOB_DATA;
1759
+ blob.arrayBuffer().then((arrayBuffer) => {
1760
+ if (this._socket.destroyed) {
1761
+ const err = new Error(
1762
+ "The socket was closed while the blob was being read"
1763
+ );
1764
+ process.nextTick(callCallbacks, this, err, cb);
1765
+ return;
1766
+ }
1767
+ this._bufferedBytes -= options[kByteLength];
1768
+ const data = toBuffer(arrayBuffer);
1769
+ if (!compress) {
1770
+ this._state = DEFAULT;
1771
+ this.sendFrame(_Sender.frame(data, options), cb);
1772
+ this.dequeue();
1773
+ } else {
1774
+ this.dispatch(data, compress, options, cb);
1775
+ }
1776
+ }).catch((err) => {
1777
+ process.nextTick(onError, this, err, cb);
1778
+ });
1779
+ }
1780
+ /**
1781
+ * Dispatches a message.
1782
+ *
1783
+ * @param {(Buffer|String)} data The message to send
1784
+ * @param {Boolean} [compress=false] Specifies whether or not to compress
1785
+ * `data`
1786
+ * @param {Object} options Options object
1787
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
1788
+ * FIN bit
1789
+ * @param {Function} [options.generateMask] The function used to generate the
1790
+ * masking key
1791
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1792
+ * `data`
1793
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
1794
+ * key
1795
+ * @param {Number} options.opcode The opcode
1796
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
1797
+ * modified
1798
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
1799
+ * RSV1 bit
1800
+ * @param {Function} [cb] Callback
1801
+ * @private
1802
+ */
1803
+ dispatch(data, compress, options, cb) {
1804
+ if (!compress) {
1805
+ this.sendFrame(_Sender.frame(data, options), cb);
1806
+ return;
1807
+ }
1808
+ const perMessageDeflate = this._extensions[PerMessageDeflate2.extensionName];
1809
+ this._bufferedBytes += options[kByteLength];
1810
+ this._state = DEFLATING;
1811
+ perMessageDeflate.compress(data, options.fin, (_, buf) => {
1812
+ if (this._socket.destroyed) {
1813
+ const err = new Error(
1814
+ "The socket was closed while data was being compressed"
1815
+ );
1816
+ callCallbacks(this, err, cb);
1817
+ return;
1818
+ }
1819
+ this._bufferedBytes -= options[kByteLength];
1820
+ this._state = DEFAULT;
1821
+ options.readOnly = false;
1822
+ this.sendFrame(_Sender.frame(buf, options), cb);
1823
+ this.dequeue();
1824
+ });
1825
+ }
1826
+ /**
1827
+ * Executes queued send operations.
1828
+ *
1829
+ * @private
1830
+ */
1831
+ dequeue() {
1832
+ while (this._state === DEFAULT && this._queue.length) {
1833
+ const params = this._queue.shift();
1834
+ this._bufferedBytes -= params[3][kByteLength];
1835
+ Reflect.apply(params[0], this, params.slice(1));
1836
+ }
1837
+ }
1838
+ /**
1839
+ * Enqueues a send operation.
1840
+ *
1841
+ * @param {Array} params Send operation parameters.
1842
+ * @private
1843
+ */
1844
+ enqueue(params) {
1845
+ this._bufferedBytes += params[3][kByteLength];
1846
+ this._queue.push(params);
1847
+ }
1848
+ /**
1849
+ * Sends a frame.
1850
+ *
1851
+ * @param {(Buffer | String)[]} list The frame to send
1852
+ * @param {Function} [cb] Callback
1853
+ * @private
1854
+ */
1855
+ sendFrame(list, cb) {
1856
+ if (list.length === 2) {
1857
+ this._socket.cork();
1858
+ this._socket.write(list[0]);
1859
+ this._socket.write(list[1], cb);
1860
+ this._socket.uncork();
1861
+ } else {
1862
+ this._socket.write(list[0], cb);
1863
+ }
1864
+ }
1865
+ };
1866
+ module.exports = Sender2;
1867
+ function callCallbacks(sender, err, cb) {
1868
+ if (typeof cb === "function") cb(err);
1869
+ for (let i = 0; i < sender._queue.length; i++) {
1870
+ const params = sender._queue[i];
1871
+ const callback = params[params.length - 1];
1872
+ if (typeof callback === "function") callback(err);
1873
+ }
1874
+ }
1875
+ function onError(sender, err, cb) {
1876
+ callCallbacks(sender, err, cb);
1877
+ sender.onerror(err);
1878
+ }
1879
+ }
1880
+ });
1881
+
1882
+ // ../../node_modules/.pnpm/ws@8.21.3/node_modules/ws/lib/event-target.js
1883
+ var require_event_target = __commonJS({
1884
+ "../../node_modules/.pnpm/ws@8.21.3/node_modules/ws/lib/event-target.js"(exports, module) {
1885
+ "use strict";
1886
+ var { kForOnEventAttribute, kListener } = require_constants();
1887
+ var kCode = /* @__PURE__ */ Symbol("kCode");
1888
+ var kData = /* @__PURE__ */ Symbol("kData");
1889
+ var kError = /* @__PURE__ */ Symbol("kError");
1890
+ var kMessage = /* @__PURE__ */ Symbol("kMessage");
1891
+ var kReason = /* @__PURE__ */ Symbol("kReason");
1892
+ var kTarget = /* @__PURE__ */ Symbol("kTarget");
1893
+ var kType = /* @__PURE__ */ Symbol("kType");
1894
+ var kWasClean = /* @__PURE__ */ Symbol("kWasClean");
1895
+ var Event = class {
1896
+ /**
1897
+ * Create a new `Event`.
1898
+ *
1899
+ * @param {String} type The name of the event
1900
+ * @throws {TypeError} If the `type` argument is not specified
1901
+ */
1902
+ constructor(type) {
1903
+ this[kTarget] = null;
1904
+ this[kType] = type;
1905
+ }
1906
+ /**
1907
+ * @type {*}
1908
+ */
1909
+ get target() {
1910
+ return this[kTarget];
1911
+ }
1912
+ /**
1913
+ * @type {String}
1914
+ */
1915
+ get type() {
1916
+ return this[kType];
1917
+ }
1918
+ };
1919
+ Object.defineProperty(Event.prototype, "target", { enumerable: true });
1920
+ Object.defineProperty(Event.prototype, "type", { enumerable: true });
1921
+ var CloseEvent = class extends Event {
1922
+ /**
1923
+ * Create a new `CloseEvent`.
1924
+ *
1925
+ * @param {String} type The name of the event
1926
+ * @param {Object} [options] A dictionary object that allows for setting
1927
+ * attributes via object members of the same name
1928
+ * @param {Number} [options.code=0] The status code explaining why the
1929
+ * connection was closed
1930
+ * @param {String} [options.reason=''] A human-readable string explaining why
1931
+ * the connection was closed
1932
+ * @param {Boolean} [options.wasClean=false] Indicates whether or not the
1933
+ * connection was cleanly closed
1934
+ */
1935
+ constructor(type, options = {}) {
1936
+ super(type);
1937
+ this[kCode] = options.code === void 0 ? 0 : options.code;
1938
+ this[kReason] = options.reason === void 0 ? "" : options.reason;
1939
+ this[kWasClean] = options.wasClean === void 0 ? false : options.wasClean;
1940
+ }
1941
+ /**
1942
+ * @type {Number}
1943
+ */
1944
+ get code() {
1945
+ return this[kCode];
1946
+ }
1947
+ /**
1948
+ * @type {String}
1949
+ */
1950
+ get reason() {
1951
+ return this[kReason];
1952
+ }
1953
+ /**
1954
+ * @type {Boolean}
1955
+ */
1956
+ get wasClean() {
1957
+ return this[kWasClean];
1958
+ }
1959
+ };
1960
+ Object.defineProperty(CloseEvent.prototype, "code", { enumerable: true });
1961
+ Object.defineProperty(CloseEvent.prototype, "reason", { enumerable: true });
1962
+ Object.defineProperty(CloseEvent.prototype, "wasClean", { enumerable: true });
1963
+ var ErrorEvent = class extends Event {
1964
+ /**
1965
+ * Create a new `ErrorEvent`.
1966
+ *
1967
+ * @param {String} type The name of the event
1968
+ * @param {Object} [options] A dictionary object that allows for setting
1969
+ * attributes via object members of the same name
1970
+ * @param {*} [options.error=null] The error that generated this event
1971
+ * @param {String} [options.message=''] The error message
1972
+ */
1973
+ constructor(type, options = {}) {
1974
+ super(type);
1975
+ this[kError] = options.error === void 0 ? null : options.error;
1976
+ this[kMessage] = options.message === void 0 ? "" : options.message;
1977
+ }
1978
+ /**
1979
+ * @type {*}
1980
+ */
1981
+ get error() {
1982
+ return this[kError];
1983
+ }
1984
+ /**
1985
+ * @type {String}
1986
+ */
1987
+ get message() {
1988
+ return this[kMessage];
1989
+ }
1990
+ };
1991
+ Object.defineProperty(ErrorEvent.prototype, "error", { enumerable: true });
1992
+ Object.defineProperty(ErrorEvent.prototype, "message", { enumerable: true });
1993
+ var MessageEvent = class extends Event {
1994
+ /**
1995
+ * Create a new `MessageEvent`.
1996
+ *
1997
+ * @param {String} type The name of the event
1998
+ * @param {Object} [options] A dictionary object that allows for setting
1999
+ * attributes via object members of the same name
2000
+ * @param {*} [options.data=null] The message content
2001
+ */
2002
+ constructor(type, options = {}) {
2003
+ super(type);
2004
+ this[kData] = options.data === void 0 ? null : options.data;
2005
+ }
2006
+ /**
2007
+ * @type {*}
2008
+ */
2009
+ get data() {
2010
+ return this[kData];
2011
+ }
2012
+ };
2013
+ Object.defineProperty(MessageEvent.prototype, "data", { enumerable: true });
2014
+ var EventTarget = {
2015
+ /**
2016
+ * Register an event listener.
2017
+ *
2018
+ * @param {String} type A string representing the event type to listen for
2019
+ * @param {(Function|Object)} handler The listener to add
2020
+ * @param {Object} [options] An options object specifies characteristics about
2021
+ * the event listener
2022
+ * @param {Boolean} [options.once=false] A `Boolean` indicating that the
2023
+ * listener should be invoked at most once after being added. If `true`,
2024
+ * the listener would be automatically removed when invoked.
2025
+ * @public
2026
+ */
2027
+ addEventListener(type, handler, options = {}) {
2028
+ for (const listener of this.listeners(type)) {
2029
+ if (!options[kForOnEventAttribute] && listener[kListener] === handler && !listener[kForOnEventAttribute]) {
2030
+ return;
2031
+ }
2032
+ }
2033
+ let wrapper;
2034
+ if (type === "message") {
2035
+ wrapper = function onMessage(data, isBinary) {
2036
+ const event = new MessageEvent("message", {
2037
+ data: isBinary ? data : data.toString()
2038
+ });
2039
+ event[kTarget] = this;
2040
+ callListener(handler, this, event);
2041
+ };
2042
+ } else if (type === "close") {
2043
+ wrapper = function onClose(code, message) {
2044
+ const event = new CloseEvent("close", {
2045
+ code,
2046
+ reason: message.toString(),
2047
+ wasClean: this._closeFrameReceived && this._closeFrameSent
2048
+ });
2049
+ event[kTarget] = this;
2050
+ callListener(handler, this, event);
2051
+ };
2052
+ } else if (type === "error") {
2053
+ wrapper = function onError(error) {
2054
+ const event = new ErrorEvent("error", {
2055
+ error,
2056
+ message: error.message
2057
+ });
2058
+ event[kTarget] = this;
2059
+ callListener(handler, this, event);
2060
+ };
2061
+ } else if (type === "open") {
2062
+ wrapper = function onOpen() {
2063
+ const event = new Event("open");
2064
+ event[kTarget] = this;
2065
+ callListener(handler, this, event);
2066
+ };
2067
+ } else {
2068
+ return;
2069
+ }
2070
+ wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];
2071
+ wrapper[kListener] = handler;
2072
+ if (options.once) {
2073
+ this.once(type, wrapper);
2074
+ } else {
2075
+ this.on(type, wrapper);
2076
+ }
2077
+ },
2078
+ /**
2079
+ * Remove an event listener.
2080
+ *
2081
+ * @param {String} type A string representing the event type to remove
2082
+ * @param {(Function|Object)} handler The listener to remove
2083
+ * @public
2084
+ */
2085
+ removeEventListener(type, handler) {
2086
+ for (const listener of this.listeners(type)) {
2087
+ if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {
2088
+ this.removeListener(type, listener);
2089
+ break;
2090
+ }
2091
+ }
2092
+ }
2093
+ };
2094
+ module.exports = {
2095
+ CloseEvent,
2096
+ ErrorEvent,
2097
+ Event,
2098
+ EventTarget,
2099
+ MessageEvent
2100
+ };
2101
+ function callListener(listener, thisArg, event) {
2102
+ if (typeof listener === "object" && listener.handleEvent) {
2103
+ listener.handleEvent.call(listener, event);
2104
+ } else {
2105
+ listener.call(thisArg, event);
2106
+ }
2107
+ }
2108
+ }
2109
+ });
2110
+
2111
+ // ../../node_modules/.pnpm/ws@8.21.3/node_modules/ws/lib/extension.js
2112
+ var require_extension = __commonJS({
2113
+ "../../node_modules/.pnpm/ws@8.21.3/node_modules/ws/lib/extension.js"(exports, module) {
2114
+ "use strict";
2115
+ var { tokenChars } = require_validation();
2116
+ function push(dest, name, elem) {
2117
+ if (dest[name] === void 0) dest[name] = [elem];
2118
+ else dest[name].push(elem);
2119
+ }
2120
+ function parse(header) {
2121
+ const offers = /* @__PURE__ */ Object.create(null);
2122
+ let params = /* @__PURE__ */ Object.create(null);
2123
+ let mustUnescape = false;
2124
+ let isEscaping = false;
2125
+ let inQuotes = false;
2126
+ let extensionName;
2127
+ let paramName;
2128
+ let start = -1;
2129
+ let code = -1;
2130
+ let end = -1;
2131
+ let i = 0;
2132
+ for (; i < header.length; i++) {
2133
+ code = header.charCodeAt(i);
2134
+ if (extensionName === void 0) {
2135
+ if (end === -1 && tokenChars[code] === 1) {
2136
+ if (start === -1) start = i;
2137
+ } else if (i !== 0 && (code === 32 || code === 9)) {
2138
+ if (end === -1 && start !== -1) end = i;
2139
+ } else if (code === 59 || code === 44) {
2140
+ if (start === -1) {
2141
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2142
+ }
2143
+ if (end === -1) end = i;
2144
+ const name = header.slice(start, end);
2145
+ if (code === 44) {
2146
+ push(offers, name, params);
2147
+ params = /* @__PURE__ */ Object.create(null);
2148
+ } else {
2149
+ extensionName = name;
2150
+ }
2151
+ start = end = -1;
2152
+ } else {
2153
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2154
+ }
2155
+ } else if (paramName === void 0) {
2156
+ if (end === -1 && tokenChars[code] === 1) {
2157
+ if (start === -1) start = i;
2158
+ } else if (code === 32 || code === 9) {
2159
+ if (end === -1 && start !== -1) end = i;
2160
+ } else if (code === 59 || code === 44) {
2161
+ if (start === -1) {
2162
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2163
+ }
2164
+ if (end === -1) end = i;
2165
+ push(params, header.slice(start, end), true);
2166
+ if (code === 44) {
2167
+ push(offers, extensionName, params);
2168
+ params = /* @__PURE__ */ Object.create(null);
2169
+ extensionName = void 0;
2170
+ }
2171
+ start = end = -1;
2172
+ } else if (code === 61 && start !== -1 && end === -1) {
2173
+ paramName = header.slice(start, i);
2174
+ start = end = -1;
2175
+ } else {
2176
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2177
+ }
2178
+ } else {
2179
+ if (isEscaping) {
2180
+ if (tokenChars[code] !== 1) {
2181
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2182
+ }
2183
+ if (start === -1) start = i;
2184
+ else if (!mustUnescape) mustUnescape = true;
2185
+ isEscaping = false;
2186
+ } else if (inQuotes) {
2187
+ if (tokenChars[code] === 1) {
2188
+ if (start === -1) start = i;
2189
+ } else if (code === 34 && start !== -1) {
2190
+ inQuotes = false;
2191
+ end = i;
2192
+ } else if (code === 92) {
2193
+ isEscaping = true;
2194
+ } else {
2195
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2196
+ }
2197
+ } else if (code === 34 && header.charCodeAt(i - 1) === 61) {
2198
+ inQuotes = true;
2199
+ } else if (end === -1 && tokenChars[code] === 1) {
2200
+ if (start === -1) start = i;
2201
+ } else if (start !== -1 && (code === 32 || code === 9)) {
2202
+ if (end === -1) end = i;
2203
+ } else if (code === 59 || code === 44) {
2204
+ if (start === -1) {
2205
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2206
+ }
2207
+ if (end === -1) end = i;
2208
+ let value = header.slice(start, end);
2209
+ if (mustUnescape) {
2210
+ value = value.replace(/\\/g, "");
2211
+ mustUnescape = false;
2212
+ }
2213
+ push(params, paramName, value);
2214
+ if (code === 44) {
2215
+ push(offers, extensionName, params);
2216
+ params = /* @__PURE__ */ Object.create(null);
2217
+ extensionName = void 0;
2218
+ }
2219
+ paramName = void 0;
2220
+ start = end = -1;
2221
+ } else {
2222
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2223
+ }
2224
+ }
2225
+ }
2226
+ if (start === -1 || inQuotes || code === 32 || code === 9) {
2227
+ throw new SyntaxError("Unexpected end of input");
2228
+ }
2229
+ if (end === -1) end = i;
2230
+ const token = header.slice(start, end);
2231
+ if (extensionName === void 0) {
2232
+ push(offers, token, params);
2233
+ } else {
2234
+ if (paramName === void 0) {
2235
+ push(params, token, true);
2236
+ } else if (mustUnescape) {
2237
+ push(params, paramName, token.replace(/\\/g, ""));
2238
+ } else {
2239
+ push(params, paramName, token);
2240
+ }
2241
+ push(offers, extensionName, params);
2242
+ }
2243
+ return offers;
2244
+ }
2245
+ function format(extensions) {
2246
+ return Object.keys(extensions).map((extension2) => {
2247
+ let configurations = extensions[extension2];
2248
+ if (!Array.isArray(configurations)) configurations = [configurations];
2249
+ return configurations.map((params) => {
2250
+ return [extension2].concat(
2251
+ Object.keys(params).map((k) => {
2252
+ let values = params[k];
2253
+ if (!Array.isArray(values)) values = [values];
2254
+ return values.map((v) => v === true ? k : `${k}=${v}`).join("; ");
2255
+ })
2256
+ ).join("; ");
2257
+ }).join(", ");
2258
+ }).join(", ");
2259
+ }
2260
+ module.exports = { format, parse };
2261
+ }
2262
+ });
2263
+
2264
+ // ../../node_modules/.pnpm/ws@8.21.3/node_modules/ws/lib/websocket.js
2265
+ var require_websocket = __commonJS({
2266
+ "../../node_modules/.pnpm/ws@8.21.3/node_modules/ws/lib/websocket.js"(exports, module) {
2267
+ "use strict";
2268
+ var EventEmitter = __require("events");
2269
+ var https = __require("https");
2270
+ var http = __require("http");
2271
+ var net = __require("net");
2272
+ var tls = __require("tls");
2273
+ var { randomBytes, createHash } = __require("crypto");
2274
+ var { Duplex, Readable } = __require("stream");
2275
+ var { URL: URL2 } = __require("url");
2276
+ var PerMessageDeflate2 = require_permessage_deflate();
2277
+ var Receiver2 = require_receiver();
2278
+ var Sender2 = require_sender();
2279
+ var { isBlob } = require_validation();
2280
+ var {
2281
+ BINARY_TYPES,
2282
+ CLOSE_TIMEOUT,
2283
+ EMPTY_BUFFER,
2284
+ GUID,
2285
+ kForOnEventAttribute,
2286
+ kListener,
2287
+ kStatusCode,
2288
+ kWebSocket,
2289
+ NOOP
2290
+ } = require_constants();
2291
+ var {
2292
+ EventTarget: { addEventListener, removeEventListener }
2293
+ } = require_event_target();
2294
+ var { format, parse } = require_extension();
2295
+ var { toBuffer } = require_buffer_util();
2296
+ var kAborted = /* @__PURE__ */ Symbol("kAborted");
2297
+ var protocolVersions = [8, 13];
2298
+ var readyStates = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"];
2299
+ var subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
2300
+ var WebSocket2 = class _WebSocket extends EventEmitter {
2301
+ /**
2302
+ * Create a new `WebSocket`.
2303
+ *
2304
+ * @param {(String|URL)} address The URL to which to connect
2305
+ * @param {(String|String[])} [protocols] The subprotocols
2306
+ * @param {Object} [options] Connection options
2307
+ */
2308
+ constructor(address, protocols, options) {
2309
+ super();
2310
+ this._binaryType = BINARY_TYPES[0];
2311
+ this._closeCode = 1006;
2312
+ this._closeFrameReceived = false;
2313
+ this._closeFrameSent = false;
2314
+ this._closeMessage = EMPTY_BUFFER;
2315
+ this._closeTimer = null;
2316
+ this._errorEmitted = false;
2317
+ this._extensions = {};
2318
+ this._paused = false;
2319
+ this._protocol = "";
2320
+ this._readyState = _WebSocket.CONNECTING;
2321
+ this._receiver = null;
2322
+ this._sender = null;
2323
+ this._socket = null;
2324
+ if (address !== null) {
2325
+ this._bufferedAmount = 0;
2326
+ this._isServer = false;
2327
+ this._redirects = 0;
2328
+ if (protocols === void 0) {
2329
+ protocols = [];
2330
+ } else if (!Array.isArray(protocols)) {
2331
+ if (typeof protocols === "object" && protocols !== null) {
2332
+ options = protocols;
2333
+ protocols = [];
2334
+ } else {
2335
+ protocols = [protocols];
2336
+ }
2337
+ }
2338
+ initAsClient(this, address, protocols, options);
2339
+ } else {
2340
+ this._autoPong = options.autoPong;
2341
+ this._closeTimeout = options.closeTimeout;
2342
+ this._isServer = true;
2343
+ }
2344
+ }
2345
+ /**
2346
+ * For historical reasons, the custom "nodebuffer" type is used by the default
2347
+ * instead of "blob".
2348
+ *
2349
+ * @type {String}
2350
+ */
2351
+ get binaryType() {
2352
+ return this._binaryType;
2353
+ }
2354
+ set binaryType(type) {
2355
+ if (!BINARY_TYPES.includes(type)) return;
2356
+ this._binaryType = type;
2357
+ if (this._receiver) this._receiver._binaryType = type;
2358
+ }
2359
+ /**
2360
+ * @type {Number}
2361
+ */
2362
+ get bufferedAmount() {
2363
+ if (!this._socket) return this._bufferedAmount;
2364
+ return this._socket._writableState.length + this._sender._bufferedBytes;
2365
+ }
2366
+ /**
2367
+ * @type {String}
2368
+ */
2369
+ get extensions() {
2370
+ return Object.keys(this._extensions).join();
2371
+ }
2372
+ /**
2373
+ * @type {Boolean}
2374
+ */
2375
+ get isPaused() {
2376
+ return this._paused;
2377
+ }
2378
+ /**
2379
+ * @type {Function}
2380
+ */
2381
+ /* istanbul ignore next */
2382
+ get onclose() {
2383
+ return null;
2384
+ }
2385
+ /**
2386
+ * @type {Function}
2387
+ */
2388
+ /* istanbul ignore next */
2389
+ get onerror() {
2390
+ return null;
2391
+ }
2392
+ /**
2393
+ * @type {Function}
2394
+ */
2395
+ /* istanbul ignore next */
2396
+ get onopen() {
2397
+ return null;
2398
+ }
2399
+ /**
2400
+ * @type {Function}
2401
+ */
2402
+ /* istanbul ignore next */
2403
+ get onmessage() {
2404
+ return null;
2405
+ }
2406
+ /**
2407
+ * @type {String}
2408
+ */
2409
+ get protocol() {
2410
+ return this._protocol;
2411
+ }
2412
+ /**
2413
+ * @type {Number}
2414
+ */
2415
+ get readyState() {
2416
+ return this._readyState;
2417
+ }
2418
+ /**
2419
+ * @type {String}
2420
+ */
2421
+ get url() {
2422
+ return this._url;
2423
+ }
2424
+ /**
2425
+ * Set up the socket and the internal resources.
2426
+ *
2427
+ * @param {Duplex} socket The network socket between the server and client
2428
+ * @param {Buffer} head The first packet of the upgraded stream
2429
+ * @param {Object} options Options object
2430
+ * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether
2431
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
2432
+ * multiple times in the same tick
2433
+ * @param {Function} [options.generateMask] The function used to generate the
2434
+ * masking key
2435
+ * @param {Number} [options.maxBufferedChunks=0] The maximum number of
2436
+ * buffered data chunks
2437
+ * @param {Number} [options.maxFragments=0] The maximum number of message
2438
+ * fragments
2439
+ * @param {Number} [options.maxPayload=0] The maximum allowed message size
2440
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
2441
+ * not to skip UTF-8 validation for text and close messages
2442
+ * @private
2443
+ */
2444
+ setSocket(socket, head, options) {
2445
+ const receiver = new Receiver2({
2446
+ allowSynchronousEvents: options.allowSynchronousEvents,
2447
+ binaryType: this.binaryType,
2448
+ extensions: this._extensions,
2449
+ isServer: this._isServer,
2450
+ maxBufferedChunks: options.maxBufferedChunks,
2451
+ maxFragments: options.maxFragments,
2452
+ maxPayload: options.maxPayload,
2453
+ skipUTF8Validation: options.skipUTF8Validation
2454
+ });
2455
+ const sender = new Sender2(socket, this._extensions, options.generateMask);
2456
+ this._receiver = receiver;
2457
+ this._sender = sender;
2458
+ this._socket = socket;
2459
+ receiver[kWebSocket] = this;
2460
+ sender[kWebSocket] = this;
2461
+ socket[kWebSocket] = this;
2462
+ receiver.on("conclude", receiverOnConclude);
2463
+ receiver.on("drain", receiverOnDrain);
2464
+ receiver.on("error", receiverOnError);
2465
+ receiver.on("message", receiverOnMessage);
2466
+ receiver.on("ping", receiverOnPing);
2467
+ receiver.on("pong", receiverOnPong);
2468
+ sender.onerror = senderOnError;
2469
+ if (socket.setTimeout) socket.setTimeout(0);
2470
+ if (socket.setNoDelay) socket.setNoDelay();
2471
+ if (head.length > 0) socket.unshift(head);
2472
+ socket.on("close", socketOnClose);
2473
+ socket.on("data", socketOnData);
2474
+ socket.on("end", socketOnEnd);
2475
+ socket.on("error", socketOnError);
2476
+ this._readyState = _WebSocket.OPEN;
2477
+ this.emit("open");
2478
+ }
2479
+ /**
2480
+ * Emit the `'close'` event.
2481
+ *
2482
+ * @private
2483
+ */
2484
+ emitClose() {
2485
+ if (!this._socket) {
2486
+ this._readyState = _WebSocket.CLOSED;
2487
+ this.emit("close", this._closeCode, this._closeMessage);
2488
+ return;
2489
+ }
2490
+ if (this._extensions[PerMessageDeflate2.extensionName]) {
2491
+ this._extensions[PerMessageDeflate2.extensionName].cleanup();
2492
+ }
2493
+ this._receiver.removeAllListeners();
2494
+ this._readyState = _WebSocket.CLOSED;
2495
+ this.emit("close", this._closeCode, this._closeMessage);
2496
+ }
2497
+ /**
2498
+ * Start a closing handshake.
2499
+ *
2500
+ * +----------+ +-----------+ +----------+
2501
+ * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -
2502
+ * | +----------+ +-----------+ +----------+ |
2503
+ * +----------+ +-----------+ |
2504
+ * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING
2505
+ * +----------+ +-----------+ |
2506
+ * | | | +---+ |
2507
+ * +------------------------+-->|fin| - - - -
2508
+ * | +---+ | +---+
2509
+ * - - - - -|fin|<---------------------+
2510
+ * +---+
2511
+ *
2512
+ * @param {Number} [code] Status code explaining why the connection is closing
2513
+ * @param {(String|Buffer)} [data] The reason why the connection is
2514
+ * closing
2515
+ * @public
2516
+ */
2517
+ close(code, data) {
2518
+ if (this.readyState === _WebSocket.CLOSED) return;
2519
+ if (this.readyState === _WebSocket.CONNECTING) {
2520
+ const msg = "WebSocket was closed before the connection was established";
2521
+ abortHandshake(this, this._req, msg);
2522
+ return;
2523
+ }
2524
+ if (this.readyState === _WebSocket.CLOSING) {
2525
+ if (this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted)) {
2526
+ this._socket.end();
2527
+ }
2528
+ return;
2529
+ }
2530
+ this._readyState = _WebSocket.CLOSING;
2531
+ this._sender.close(code, data, !this._isServer, (err) => {
2532
+ if (err) return;
2533
+ this._closeFrameSent = true;
2534
+ if (this._closeFrameReceived || this._receiver._writableState.errorEmitted) {
2535
+ this._socket.end();
2536
+ }
2537
+ });
2538
+ setCloseTimer(this);
2539
+ }
2540
+ /**
2541
+ * Pause the socket.
2542
+ *
2543
+ * @public
2544
+ */
2545
+ pause() {
2546
+ if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) {
2547
+ return;
2548
+ }
2549
+ this._paused = true;
2550
+ this._socket.pause();
2551
+ }
2552
+ /**
2553
+ * Send a ping.
2554
+ *
2555
+ * @param {*} [data] The data to send
2556
+ * @param {Boolean} [mask] Indicates whether or not to mask `data`
2557
+ * @param {Function} [cb] Callback which is executed when the ping is sent
2558
+ * @public
2559
+ */
2560
+ ping(data, mask, cb) {
2561
+ if (this.readyState === _WebSocket.CONNECTING) {
2562
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
2563
+ }
2564
+ if (typeof data === "function") {
2565
+ cb = data;
2566
+ data = mask = void 0;
2567
+ } else if (typeof mask === "function") {
2568
+ cb = mask;
2569
+ mask = void 0;
2570
+ }
2571
+ if (typeof data === "number") data = data.toString();
2572
+ if (this.readyState !== _WebSocket.OPEN) {
2573
+ sendAfterClose(this, data, cb);
2574
+ return;
2575
+ }
2576
+ if (mask === void 0) mask = !this._isServer;
2577
+ this._sender.ping(data || EMPTY_BUFFER, mask, cb);
2578
+ }
2579
+ /**
2580
+ * Send a pong.
2581
+ *
2582
+ * @param {*} [data] The data to send
2583
+ * @param {Boolean} [mask] Indicates whether or not to mask `data`
2584
+ * @param {Function} [cb] Callback which is executed when the pong is sent
2585
+ * @public
2586
+ */
2587
+ pong(data, mask, cb) {
2588
+ if (this.readyState === _WebSocket.CONNECTING) {
2589
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
2590
+ }
2591
+ if (typeof data === "function") {
2592
+ cb = data;
2593
+ data = mask = void 0;
2594
+ } else if (typeof mask === "function") {
2595
+ cb = mask;
2596
+ mask = void 0;
2597
+ }
2598
+ if (typeof data === "number") data = data.toString();
2599
+ if (this.readyState !== _WebSocket.OPEN) {
2600
+ sendAfterClose(this, data, cb);
2601
+ return;
2602
+ }
2603
+ if (mask === void 0) mask = !this._isServer;
2604
+ this._sender.pong(data || EMPTY_BUFFER, mask, cb);
2605
+ }
2606
+ /**
2607
+ * Resume the socket.
2608
+ *
2609
+ * @public
2610
+ */
2611
+ resume() {
2612
+ if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) {
2613
+ return;
2614
+ }
2615
+ this._paused = false;
2616
+ if (!this._receiver._writableState.needDrain) this._socket.resume();
2617
+ }
2618
+ /**
2619
+ * Send a data message.
2620
+ *
2621
+ * @param {*} data The message to send
2622
+ * @param {Object} [options] Options object
2623
+ * @param {Boolean} [options.binary] Specifies whether `data` is binary or
2624
+ * text
2625
+ * @param {Boolean} [options.compress] Specifies whether or not to compress
2626
+ * `data`
2627
+ * @param {Boolean} [options.fin=true] Specifies whether the fragment is the
2628
+ * last one
2629
+ * @param {Boolean} [options.mask] Specifies whether or not to mask `data`
2630
+ * @param {Function} [cb] Callback which is executed when data is written out
2631
+ * @public
2632
+ */
2633
+ send(data, options, cb) {
2634
+ if (this.readyState === _WebSocket.CONNECTING) {
2635
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
2636
+ }
2637
+ if (typeof options === "function") {
2638
+ cb = options;
2639
+ options = {};
2640
+ }
2641
+ if (typeof data === "number") data = data.toString();
2642
+ if (this.readyState !== _WebSocket.OPEN) {
2643
+ sendAfterClose(this, data, cb);
2644
+ return;
2645
+ }
2646
+ const opts = {
2647
+ binary: typeof data !== "string",
2648
+ mask: !this._isServer,
2649
+ compress: true,
2650
+ fin: true,
2651
+ ...options
2652
+ };
2653
+ if (!this._extensions[PerMessageDeflate2.extensionName]) {
2654
+ opts.compress = false;
2655
+ }
2656
+ this._sender.send(data || EMPTY_BUFFER, opts, cb);
2657
+ }
2658
+ /**
2659
+ * Forcibly close the connection.
2660
+ *
2661
+ * @public
2662
+ */
2663
+ terminate() {
2664
+ if (this.readyState === _WebSocket.CLOSED) return;
2665
+ if (this.readyState === _WebSocket.CONNECTING) {
2666
+ const msg = "WebSocket was closed before the connection was established";
2667
+ abortHandshake(this, this._req, msg);
2668
+ return;
2669
+ }
2670
+ if (this._socket) {
2671
+ this._readyState = _WebSocket.CLOSING;
2672
+ this._socket.destroy();
2673
+ }
2674
+ }
2675
+ };
2676
+ Object.defineProperty(WebSocket2, "CONNECTING", {
2677
+ enumerable: true,
2678
+ value: readyStates.indexOf("CONNECTING")
2679
+ });
2680
+ Object.defineProperty(WebSocket2.prototype, "CONNECTING", {
2681
+ enumerable: true,
2682
+ value: readyStates.indexOf("CONNECTING")
2683
+ });
2684
+ Object.defineProperty(WebSocket2, "OPEN", {
2685
+ enumerable: true,
2686
+ value: readyStates.indexOf("OPEN")
2687
+ });
2688
+ Object.defineProperty(WebSocket2.prototype, "OPEN", {
2689
+ enumerable: true,
2690
+ value: readyStates.indexOf("OPEN")
2691
+ });
2692
+ Object.defineProperty(WebSocket2, "CLOSING", {
2693
+ enumerable: true,
2694
+ value: readyStates.indexOf("CLOSING")
2695
+ });
2696
+ Object.defineProperty(WebSocket2.prototype, "CLOSING", {
2697
+ enumerable: true,
2698
+ value: readyStates.indexOf("CLOSING")
2699
+ });
2700
+ Object.defineProperty(WebSocket2, "CLOSED", {
2701
+ enumerable: true,
2702
+ value: readyStates.indexOf("CLOSED")
2703
+ });
2704
+ Object.defineProperty(WebSocket2.prototype, "CLOSED", {
2705
+ enumerable: true,
2706
+ value: readyStates.indexOf("CLOSED")
2707
+ });
2708
+ [
2709
+ "binaryType",
2710
+ "bufferedAmount",
2711
+ "extensions",
2712
+ "isPaused",
2713
+ "protocol",
2714
+ "readyState",
2715
+ "url"
2716
+ ].forEach((property) => {
2717
+ Object.defineProperty(WebSocket2.prototype, property, { enumerable: true });
2718
+ });
2719
+ ["open", "error", "close", "message"].forEach((method) => {
2720
+ Object.defineProperty(WebSocket2.prototype, `on${method}`, {
2721
+ enumerable: true,
2722
+ get() {
2723
+ for (const listener of this.listeners(method)) {
2724
+ if (listener[kForOnEventAttribute]) return listener[kListener];
2725
+ }
2726
+ return null;
2727
+ },
2728
+ set(handler) {
2729
+ for (const listener of this.listeners(method)) {
2730
+ if (listener[kForOnEventAttribute]) {
2731
+ this.removeListener(method, listener);
2732
+ break;
2733
+ }
2734
+ }
2735
+ if (typeof handler !== "function") return;
2736
+ this.addEventListener(method, handler, {
2737
+ [kForOnEventAttribute]: true
2738
+ });
2739
+ }
2740
+ });
2741
+ });
2742
+ WebSocket2.prototype.addEventListener = addEventListener;
2743
+ WebSocket2.prototype.removeEventListener = removeEventListener;
2744
+ module.exports = WebSocket2;
2745
+ function initAsClient(websocket, address, protocols, options) {
2746
+ const opts = {
2747
+ allowSynchronousEvents: true,
2748
+ autoPong: true,
2749
+ closeTimeout: CLOSE_TIMEOUT,
2750
+ protocolVersion: protocolVersions[1],
2751
+ maxBufferedChunks: 256 * 1024,
2752
+ maxFragments: 16 * 1024,
2753
+ maxPayload: 100 * 1024 * 1024,
2754
+ skipUTF8Validation: false,
2755
+ perMessageDeflate: true,
2756
+ followRedirects: false,
2757
+ maxRedirects: 10,
2758
+ ...options,
2759
+ socketPath: void 0,
2760
+ hostname: void 0,
2761
+ protocol: void 0,
2762
+ timeout: void 0,
2763
+ method: "GET",
2764
+ host: void 0,
2765
+ path: void 0,
2766
+ port: void 0
2767
+ };
2768
+ websocket._autoPong = opts.autoPong;
2769
+ websocket._closeTimeout = opts.closeTimeout;
2770
+ if (!protocolVersions.includes(opts.protocolVersion)) {
2771
+ throw new RangeError(
2772
+ `Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`
2773
+ );
2774
+ }
2775
+ let parsedUrl;
2776
+ if (address instanceof URL2) {
2777
+ parsedUrl = address;
2778
+ } else {
2779
+ try {
2780
+ parsedUrl = new URL2(address);
2781
+ } catch {
2782
+ throw new SyntaxError(`Invalid URL: ${address}`);
2783
+ }
2784
+ }
2785
+ if (parsedUrl.protocol === "http:") {
2786
+ parsedUrl.protocol = "ws:";
2787
+ } else if (parsedUrl.protocol === "https:") {
2788
+ parsedUrl.protocol = "wss:";
2789
+ }
2790
+ websocket._url = parsedUrl.href;
2791
+ const isSecure = parsedUrl.protocol === "wss:";
2792
+ const isIpcUrl = parsedUrl.protocol === "ws+unix:";
2793
+ let invalidUrlMessage;
2794
+ if (parsedUrl.protocol !== "ws:" && !isSecure && !isIpcUrl) {
2795
+ invalidUrlMessage = `The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`;
2796
+ } else if (isIpcUrl && !parsedUrl.pathname) {
2797
+ invalidUrlMessage = "The URL's pathname is empty";
2798
+ } else if (parsedUrl.hash) {
2799
+ invalidUrlMessage = "The URL contains a fragment identifier";
2800
+ }
2801
+ if (invalidUrlMessage) {
2802
+ const err = new SyntaxError(invalidUrlMessage);
2803
+ if (websocket._redirects === 0) {
2804
+ throw err;
2805
+ } else {
2806
+ emitErrorAndClose(websocket, err);
2807
+ return;
2808
+ }
2809
+ }
2810
+ const defaultPort = isSecure ? 443 : 80;
2811
+ const key = randomBytes(16).toString("base64");
2812
+ const request = isSecure ? https.request : http.request;
2813
+ const protocolSet = /* @__PURE__ */ new Set();
2814
+ let perMessageDeflate;
2815
+ opts.createConnection = opts.createConnection || (isSecure ? tlsConnect : netConnect);
2816
+ opts.defaultPort = opts.defaultPort || defaultPort;
2817
+ opts.port = parsedUrl.port || defaultPort;
2818
+ opts.host = parsedUrl.hostname.startsWith("[") ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname;
2819
+ opts.headers = {
2820
+ ...opts.headers,
2821
+ "Sec-WebSocket-Version": opts.protocolVersion,
2822
+ "Sec-WebSocket-Key": key,
2823
+ Connection: "Upgrade",
2824
+ Upgrade: "websocket"
2825
+ };
2826
+ opts.path = parsedUrl.pathname + parsedUrl.search;
2827
+ opts.timeout = opts.handshakeTimeout;
2828
+ if (opts.perMessageDeflate) {
2829
+ perMessageDeflate = new PerMessageDeflate2({
2830
+ ...opts.perMessageDeflate,
2831
+ isServer: false,
2832
+ maxPayload: opts.maxPayload
2833
+ });
2834
+ opts.headers["Sec-WebSocket-Extensions"] = format({
2835
+ [PerMessageDeflate2.extensionName]: perMessageDeflate.offer()
2836
+ });
2837
+ }
2838
+ if (protocols.length) {
2839
+ for (const protocol of protocols) {
2840
+ if (typeof protocol !== "string" || !subprotocolRegex.test(protocol) || protocolSet.has(protocol)) {
2841
+ throw new SyntaxError(
2842
+ "An invalid or duplicated subprotocol was specified"
2843
+ );
2844
+ }
2845
+ protocolSet.add(protocol);
2846
+ }
2847
+ opts.headers["Sec-WebSocket-Protocol"] = protocols.join(",");
2848
+ }
2849
+ if (opts.origin) {
2850
+ if (opts.protocolVersion < 13) {
2851
+ opts.headers["Sec-WebSocket-Origin"] = opts.origin;
2852
+ } else {
2853
+ opts.headers.Origin = opts.origin;
2854
+ }
2855
+ }
2856
+ if (parsedUrl.username || parsedUrl.password) {
2857
+ opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
2858
+ }
2859
+ if (isIpcUrl) {
2860
+ const parts = opts.path.split(":");
2861
+ opts.socketPath = parts[0];
2862
+ opts.path = parts[1];
2863
+ }
2864
+ let req;
2865
+ if (opts.followRedirects) {
2866
+ if (websocket._redirects === 0) {
2867
+ websocket._originalIpc = isIpcUrl;
2868
+ websocket._originalSecure = isSecure;
2869
+ websocket._originalHostOrSocketPath = isIpcUrl ? opts.socketPath : parsedUrl.host;
2870
+ const headers = options && options.headers;
2871
+ options = { ...options, headers: {} };
2872
+ if (headers) {
2873
+ for (const [key2, value] of Object.entries(headers)) {
2874
+ options.headers[key2.toLowerCase()] = value;
2875
+ }
2876
+ }
2877
+ } else if (websocket.listenerCount("redirect") === 0) {
2878
+ const isSameHost = isIpcUrl ? websocket._originalIpc ? opts.socketPath === websocket._originalHostOrSocketPath : false : websocket._originalIpc ? false : parsedUrl.host === websocket._originalHostOrSocketPath;
2879
+ if (!isSameHost || websocket._originalSecure && !isSecure) {
2880
+ delete opts.headers.authorization;
2881
+ delete opts.headers.cookie;
2882
+ if (!isSameHost) delete opts.headers.host;
2883
+ opts.auth = void 0;
2884
+ }
2885
+ }
2886
+ if (opts.auth && !options.headers.authorization) {
2887
+ options.headers.authorization = "Basic " + Buffer.from(opts.auth).toString("base64");
2888
+ }
2889
+ req = websocket._req = request(opts);
2890
+ if (websocket._redirects) {
2891
+ websocket.emit("redirect", websocket.url, req);
2892
+ }
2893
+ } else {
2894
+ req = websocket._req = request(opts);
2895
+ }
2896
+ if (opts.timeout) {
2897
+ req.on("timeout", () => {
2898
+ abortHandshake(websocket, req, "Opening handshake has timed out");
2899
+ });
2900
+ }
2901
+ req.on("error", (err) => {
2902
+ if (req === null || req[kAborted]) return;
2903
+ req = websocket._req = null;
2904
+ emitErrorAndClose(websocket, err);
2905
+ });
2906
+ req.on("response", (res) => {
2907
+ const location = res.headers.location;
2908
+ const statusCode = res.statusCode;
2909
+ if (location && opts.followRedirects && statusCode >= 300 && statusCode < 400) {
2910
+ if (++websocket._redirects > opts.maxRedirects) {
2911
+ abortHandshake(websocket, req, "Maximum redirects exceeded");
2912
+ return;
2913
+ }
2914
+ req.abort();
2915
+ let addr;
2916
+ try {
2917
+ addr = new URL2(location, address);
2918
+ } catch (e) {
2919
+ const err = new SyntaxError(`Invalid URL: ${location}`);
2920
+ emitErrorAndClose(websocket, err);
2921
+ return;
2922
+ }
2923
+ initAsClient(websocket, addr, protocols, options);
2924
+ } else if (!websocket.emit("unexpected-response", req, res)) {
2925
+ abortHandshake(
2926
+ websocket,
2927
+ req,
2928
+ `Unexpected server response: ${res.statusCode}`
2929
+ );
2930
+ }
2931
+ });
2932
+ req.on("upgrade", (res, socket, head) => {
2933
+ websocket.emit("upgrade", res);
2934
+ if (websocket.readyState !== WebSocket2.CONNECTING) return;
2935
+ req = websocket._req = null;
2936
+ const upgrade = res.headers.upgrade;
2937
+ if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
2938
+ abortHandshake(websocket, socket, "Invalid Upgrade header");
2939
+ return;
2940
+ }
2941
+ const digest = createHash("sha1").update(key + GUID).digest("base64");
2942
+ if (res.headers["sec-websocket-accept"] !== digest) {
2943
+ abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
2944
+ return;
2945
+ }
2946
+ const serverProt = res.headers["sec-websocket-protocol"];
2947
+ let protError;
2948
+ if (serverProt !== void 0) {
2949
+ if (!protocolSet.size) {
2950
+ protError = "Server sent a subprotocol but none was requested";
2951
+ } else if (!protocolSet.has(serverProt)) {
2952
+ protError = "Server sent an invalid subprotocol";
2953
+ }
2954
+ } else if (protocolSet.size) {
2955
+ protError = "Server sent no subprotocol";
2956
+ }
2957
+ if (protError) {
2958
+ abortHandshake(websocket, socket, protError);
2959
+ return;
2960
+ }
2961
+ if (serverProt) websocket._protocol = serverProt;
2962
+ const secWebSocketExtensions = res.headers["sec-websocket-extensions"];
2963
+ if (secWebSocketExtensions !== void 0) {
2964
+ if (!perMessageDeflate) {
2965
+ const message = "Server sent a Sec-WebSocket-Extensions header but no extension was requested";
2966
+ abortHandshake(websocket, socket, message);
2967
+ return;
2968
+ }
2969
+ let extensions;
2970
+ try {
2971
+ extensions = parse(secWebSocketExtensions);
2972
+ } catch (err) {
2973
+ const message = "Invalid Sec-WebSocket-Extensions header";
2974
+ abortHandshake(websocket, socket, message);
2975
+ return;
2976
+ }
2977
+ const extensionNames = Object.keys(extensions);
2978
+ if (extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate2.extensionName) {
2979
+ const message = "Server indicated an extension that was not requested";
2980
+ abortHandshake(websocket, socket, message);
2981
+ return;
2982
+ }
2983
+ try {
2984
+ perMessageDeflate.accept(extensions[PerMessageDeflate2.extensionName]);
2985
+ } catch (err) {
2986
+ const message = "Invalid Sec-WebSocket-Extensions header";
2987
+ abortHandshake(websocket, socket, message);
2988
+ return;
2989
+ }
2990
+ websocket._extensions[PerMessageDeflate2.extensionName] = perMessageDeflate;
2991
+ }
2992
+ websocket.setSocket(socket, head, {
2993
+ allowSynchronousEvents: opts.allowSynchronousEvents,
2994
+ generateMask: opts.generateMask,
2995
+ maxBufferedChunks: opts.maxBufferedChunks,
2996
+ maxFragments: opts.maxFragments,
2997
+ maxPayload: opts.maxPayload,
2998
+ skipUTF8Validation: opts.skipUTF8Validation
2999
+ });
3000
+ });
3001
+ if (opts.finishRequest) {
3002
+ opts.finishRequest(req, websocket);
3003
+ } else {
3004
+ req.end();
3005
+ }
3006
+ }
3007
+ function emitErrorAndClose(websocket, err) {
3008
+ websocket._readyState = WebSocket2.CLOSING;
3009
+ websocket._errorEmitted = true;
3010
+ websocket.emit("error", err);
3011
+ websocket.emitClose();
3012
+ }
3013
+ function netConnect(options) {
3014
+ options.path = options.socketPath;
3015
+ return net.connect(options);
3016
+ }
3017
+ function tlsConnect(options) {
3018
+ options.path = void 0;
3019
+ if (!options.servername && options.servername !== "") {
3020
+ options.servername = net.isIP(options.host) ? "" : options.host;
3021
+ }
3022
+ return tls.connect(options);
3023
+ }
3024
+ function abortHandshake(websocket, stream, message) {
3025
+ websocket._readyState = WebSocket2.CLOSING;
3026
+ const err = new Error(message);
3027
+ Error.captureStackTrace(err, abortHandshake);
3028
+ if (stream.setHeader) {
3029
+ stream[kAborted] = true;
3030
+ stream.abort();
3031
+ if (stream.socket && !stream.socket.destroyed) {
3032
+ stream.socket.destroy();
3033
+ }
3034
+ process.nextTick(emitErrorAndClose, websocket, err);
3035
+ } else {
3036
+ stream.destroy(err);
3037
+ stream.once("error", websocket.emit.bind(websocket, "error"));
3038
+ stream.once("close", websocket.emitClose.bind(websocket));
3039
+ }
3040
+ }
3041
+ function sendAfterClose(websocket, data, cb) {
3042
+ if (data) {
3043
+ const length = isBlob(data) ? data.size : toBuffer(data).length;
3044
+ if (websocket._socket) websocket._sender._bufferedBytes += length;
3045
+ else websocket._bufferedAmount += length;
3046
+ }
3047
+ if (cb) {
3048
+ const err = new Error(
3049
+ `WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})`
3050
+ );
3051
+ process.nextTick(cb, err);
3052
+ }
3053
+ }
3054
+ function receiverOnConclude(code, reason) {
3055
+ const websocket = this[kWebSocket];
3056
+ websocket._closeFrameReceived = true;
3057
+ websocket._closeMessage = reason;
3058
+ websocket._closeCode = code;
3059
+ if (websocket._socket[kWebSocket] === void 0) return;
3060
+ websocket._socket.removeListener("data", socketOnData);
3061
+ process.nextTick(resume, websocket._socket);
3062
+ if (code === 1005) websocket.close();
3063
+ else websocket.close(code, reason);
3064
+ }
3065
+ function receiverOnDrain() {
3066
+ const websocket = this[kWebSocket];
3067
+ if (!websocket.isPaused) websocket._socket.resume();
3068
+ }
3069
+ function receiverOnError(err) {
3070
+ const websocket = this[kWebSocket];
3071
+ if (websocket._socket[kWebSocket] !== void 0) {
3072
+ websocket._socket.removeListener("data", socketOnData);
3073
+ process.nextTick(resume, websocket._socket);
3074
+ websocket.close(err[kStatusCode]);
3075
+ }
3076
+ if (!websocket._errorEmitted) {
3077
+ websocket._errorEmitted = true;
3078
+ websocket.emit("error", err);
3079
+ }
3080
+ }
3081
+ function receiverOnFinish() {
3082
+ this[kWebSocket].emitClose();
3083
+ }
3084
+ function receiverOnMessage(data, isBinary) {
3085
+ this[kWebSocket].emit("message", data, isBinary);
3086
+ }
3087
+ function receiverOnPing(data) {
3088
+ const websocket = this[kWebSocket];
3089
+ if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP);
3090
+ websocket.emit("ping", data);
3091
+ }
3092
+ function receiverOnPong(data) {
3093
+ this[kWebSocket].emit("pong", data);
3094
+ }
3095
+ function resume(stream) {
3096
+ stream.resume();
3097
+ }
3098
+ function senderOnError(err) {
3099
+ const websocket = this[kWebSocket];
3100
+ if (websocket.readyState === WebSocket2.CLOSED) return;
3101
+ if (websocket.readyState === WebSocket2.OPEN) {
3102
+ websocket._readyState = WebSocket2.CLOSING;
3103
+ setCloseTimer(websocket);
3104
+ }
3105
+ this._socket.end();
3106
+ if (!websocket._errorEmitted) {
3107
+ websocket._errorEmitted = true;
3108
+ websocket.emit("error", err);
3109
+ }
3110
+ }
3111
+ function setCloseTimer(websocket) {
3112
+ websocket._closeTimer = setTimeout(
3113
+ websocket._socket.destroy.bind(websocket._socket),
3114
+ websocket._closeTimeout
3115
+ );
3116
+ }
3117
+ function socketOnClose() {
3118
+ const websocket = this[kWebSocket];
3119
+ this.removeListener("close", socketOnClose);
3120
+ this.removeListener("data", socketOnData);
3121
+ this.removeListener("end", socketOnEnd);
3122
+ websocket._readyState = WebSocket2.CLOSING;
3123
+ if (!this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && this._readableState.length !== 0) {
3124
+ const chunk = this.read(this._readableState.length);
3125
+ websocket._receiver.write(chunk);
3126
+ }
3127
+ websocket._receiver.end();
3128
+ this[kWebSocket] = void 0;
3129
+ clearTimeout(websocket._closeTimer);
3130
+ if (websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted) {
3131
+ websocket.emitClose();
3132
+ } else {
3133
+ websocket._receiver.on("error", receiverOnFinish);
3134
+ websocket._receiver.on("finish", receiverOnFinish);
3135
+ }
3136
+ }
3137
+ function socketOnData(chunk) {
3138
+ if (!this[kWebSocket]._receiver.write(chunk)) {
3139
+ this.pause();
3140
+ }
3141
+ }
3142
+ function socketOnEnd() {
3143
+ const websocket = this[kWebSocket];
3144
+ websocket._readyState = WebSocket2.CLOSING;
3145
+ websocket._receiver.end();
3146
+ this.end();
3147
+ }
3148
+ function socketOnError() {
3149
+ const websocket = this[kWebSocket];
3150
+ this.removeListener("error", socketOnError);
3151
+ this.on("error", NOOP);
3152
+ if (websocket) {
3153
+ websocket._readyState = WebSocket2.CLOSING;
3154
+ this.destroy();
3155
+ }
3156
+ }
3157
+ }
3158
+ });
3159
+
3160
+ // ../../node_modules/.pnpm/ws@8.21.3/node_modules/ws/lib/stream.js
3161
+ var require_stream = __commonJS({
3162
+ "../../node_modules/.pnpm/ws@8.21.3/node_modules/ws/lib/stream.js"(exports, module) {
3163
+ "use strict";
3164
+ var WebSocket2 = require_websocket();
3165
+ var { Duplex } = __require("stream");
3166
+ function emitClose(stream) {
3167
+ stream.emit("close");
3168
+ }
3169
+ function duplexOnEnd() {
3170
+ if (!this.destroyed && this._writableState.finished) {
3171
+ this.destroy();
3172
+ }
3173
+ }
3174
+ function duplexOnError(err) {
3175
+ this.removeListener("error", duplexOnError);
3176
+ this.destroy();
3177
+ if (this.listenerCount("error") === 0) {
3178
+ this.emit("error", err);
3179
+ }
3180
+ }
3181
+ function createWebSocketStream2(ws, options) {
3182
+ let terminateOnDestroy = true;
3183
+ const duplex = new Duplex({
3184
+ ...options,
3185
+ autoDestroy: false,
3186
+ emitClose: false,
3187
+ objectMode: false,
3188
+ writableObjectMode: false
3189
+ });
3190
+ ws.on("message", function message(msg, isBinary) {
3191
+ const data = !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;
3192
+ if (!duplex.push(data)) ws.pause();
3193
+ });
3194
+ ws.once("error", function error(err) {
3195
+ if (duplex.destroyed) return;
3196
+ terminateOnDestroy = false;
3197
+ duplex.destroy(err);
3198
+ });
3199
+ ws.once("close", function close() {
3200
+ if (duplex.destroyed) return;
3201
+ duplex.push(null);
3202
+ });
3203
+ duplex._destroy = function(err, callback) {
3204
+ if (ws.readyState === ws.CLOSED) {
3205
+ callback(err);
3206
+ process.nextTick(emitClose, duplex);
3207
+ return;
3208
+ }
3209
+ let called = false;
3210
+ ws.once("error", function error(err2) {
3211
+ called = true;
3212
+ callback(err2);
3213
+ });
3214
+ ws.once("close", function close() {
3215
+ if (!called) callback(err);
3216
+ process.nextTick(emitClose, duplex);
3217
+ });
3218
+ if (terminateOnDestroy) ws.terminate();
3219
+ };
3220
+ duplex._final = function(callback) {
3221
+ if (ws.readyState === ws.CONNECTING) {
3222
+ ws.once("open", function open() {
3223
+ duplex._final(callback);
3224
+ });
3225
+ return;
3226
+ }
3227
+ if (ws._socket === null) return;
3228
+ if (ws._socket._writableState.finished) {
3229
+ callback();
3230
+ if (duplex._readableState.endEmitted) duplex.destroy();
3231
+ } else {
3232
+ ws._socket.once("finish", function finish() {
3233
+ callback();
3234
+ });
3235
+ ws.close();
3236
+ }
3237
+ };
3238
+ duplex._read = function() {
3239
+ if (ws.isPaused) ws.resume();
3240
+ };
3241
+ duplex._write = function(chunk, encoding, callback) {
3242
+ if (ws.readyState === ws.CONNECTING) {
3243
+ ws.once("open", function open() {
3244
+ duplex._write(chunk, encoding, callback);
3245
+ });
3246
+ return;
3247
+ }
3248
+ ws.send(chunk, callback);
3249
+ };
3250
+ duplex.on("end", duplexOnEnd);
3251
+ duplex.on("error", duplexOnError);
3252
+ return duplex;
3253
+ }
3254
+ module.exports = createWebSocketStream2;
3255
+ }
3256
+ });
3257
+
3258
+ // ../../node_modules/.pnpm/ws@8.21.3/node_modules/ws/lib/subprotocol.js
3259
+ var require_subprotocol = __commonJS({
3260
+ "../../node_modules/.pnpm/ws@8.21.3/node_modules/ws/lib/subprotocol.js"(exports, module) {
3261
+ "use strict";
3262
+ var { tokenChars } = require_validation();
3263
+ function parse(header) {
3264
+ const protocols = /* @__PURE__ */ new Set();
3265
+ let start = -1;
3266
+ let end = -1;
3267
+ let i = 0;
3268
+ for (i; i < header.length; i++) {
3269
+ const code = header.charCodeAt(i);
3270
+ if (end === -1 && tokenChars[code] === 1) {
3271
+ if (start === -1) start = i;
3272
+ } else if (i !== 0 && (code === 32 || code === 9)) {
3273
+ if (end === -1 && start !== -1) end = i;
3274
+ } else if (code === 44) {
3275
+ if (start === -1) {
3276
+ throw new SyntaxError(`Unexpected character at index ${i}`);
3277
+ }
3278
+ if (end === -1) end = i;
3279
+ const protocol2 = header.slice(start, end);
3280
+ if (protocols.has(protocol2)) {
3281
+ throw new SyntaxError(`The "${protocol2}" subprotocol is duplicated`);
3282
+ }
3283
+ protocols.add(protocol2);
3284
+ start = end = -1;
3285
+ } else {
3286
+ throw new SyntaxError(`Unexpected character at index ${i}`);
3287
+ }
3288
+ }
3289
+ if (start === -1 || end !== -1) {
3290
+ throw new SyntaxError("Unexpected end of input");
3291
+ }
3292
+ const protocol = header.slice(start, i);
3293
+ if (protocols.has(protocol)) {
3294
+ throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
3295
+ }
3296
+ protocols.add(protocol);
3297
+ return protocols;
3298
+ }
3299
+ module.exports = { parse };
3300
+ }
3301
+ });
3302
+
3303
+ // ../../node_modules/.pnpm/ws@8.21.3/node_modules/ws/lib/websocket-server.js
3304
+ var require_websocket_server = __commonJS({
3305
+ "../../node_modules/.pnpm/ws@8.21.3/node_modules/ws/lib/websocket-server.js"(exports, module) {
3306
+ "use strict";
3307
+ var EventEmitter = __require("events");
3308
+ var http = __require("http");
3309
+ var { Duplex } = __require("stream");
3310
+ var { createHash } = __require("crypto");
3311
+ var extension2 = require_extension();
3312
+ var PerMessageDeflate2 = require_permessage_deflate();
3313
+ var subprotocol2 = require_subprotocol();
3314
+ var WebSocket2 = require_websocket();
3315
+ var { CLOSE_TIMEOUT, GUID, kWebSocket } = require_constants();
3316
+ var keyRegex = /^[+/0-9A-Za-z]{22}==$/;
3317
+ var RUNNING = 0;
3318
+ var CLOSING = 1;
3319
+ var CLOSED = 2;
3320
+ var WebSocketServer2 = class extends EventEmitter {
3321
+ /**
3322
+ * Create a `WebSocketServer` instance.
3323
+ *
3324
+ * @param {Object} options Configuration options
3325
+ * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
3326
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
3327
+ * multiple times in the same tick
3328
+ * @param {Boolean} [options.autoPong=true] Specifies whether or not to
3329
+ * automatically send a pong in response to a ping
3330
+ * @param {Number} [options.backlog=511] The maximum length of the queue of
3331
+ * pending connections
3332
+ * @param {Boolean} [options.clientTracking=true] Specifies whether or not to
3333
+ * track clients
3334
+ * @param {Number} [options.closeTimeout=30000] Duration in milliseconds to
3335
+ * wait for the closing handshake to finish after `websocket.close()` is
3336
+ * called
3337
+ * @param {Function} [options.handleProtocols] A hook to handle protocols
3338
+ * @param {String} [options.host] The hostname where to bind the server
3339
+ * @param {Number} [options.maxBufferedChunks=262144] The maximum number of
3340
+ * buffered data chunks
3341
+ * @param {Number} [options.maxFragments=16384] The maximum number of message
3342
+ * fragments
3343
+ * @param {Number} [options.maxPayload=104857600] The maximum allowed message
3344
+ * size
3345
+ * @param {Boolean} [options.noServer=false] Enable no server mode
3346
+ * @param {String} [options.path] Accept only connections matching this path
3347
+ * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable
3348
+ * permessage-deflate
3349
+ * @param {Number} [options.port] The port where to bind the server
3350
+ * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S
3351
+ * server to use
3352
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
3353
+ * not to skip UTF-8 validation for text and close messages
3354
+ * @param {Function} [options.verifyClient] A hook to reject connections
3355
+ * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`
3356
+ * class to use. It must be the `WebSocket` class or class that extends it
3357
+ * @param {Function} [callback] A listener for the `listening` event
3358
+ */
3359
+ constructor(options, callback) {
3360
+ super();
3361
+ options = {
3362
+ allowSynchronousEvents: true,
3363
+ autoPong: true,
3364
+ maxBufferedChunks: 256 * 1024,
3365
+ maxFragments: 16 * 1024,
3366
+ maxPayload: 100 * 1024 * 1024,
3367
+ skipUTF8Validation: false,
3368
+ perMessageDeflate: false,
3369
+ handleProtocols: null,
3370
+ clientTracking: true,
3371
+ closeTimeout: CLOSE_TIMEOUT,
3372
+ verifyClient: null,
3373
+ noServer: false,
3374
+ backlog: null,
3375
+ // use default (511 as implemented in net.js)
3376
+ server: null,
3377
+ host: null,
3378
+ path: null,
3379
+ port: null,
3380
+ WebSocket: WebSocket2,
3381
+ ...options
3382
+ };
3383
+ if (options.port == null && !options.server && !options.noServer || options.port != null && (options.server || options.noServer) || options.server && options.noServer) {
3384
+ throw new TypeError(
3385
+ 'One and only one of the "port", "server", or "noServer" options must be specified'
3386
+ );
3387
+ }
3388
+ if (options.port != null) {
3389
+ this._server = http.createServer((req, res) => {
3390
+ const body = http.STATUS_CODES[426];
3391
+ res.writeHead(426, {
3392
+ "Content-Length": body.length,
3393
+ "Content-Type": "text/plain"
3394
+ });
3395
+ res.end(body);
3396
+ });
3397
+ this._server.listen(
3398
+ options.port,
3399
+ options.host,
3400
+ options.backlog,
3401
+ callback
3402
+ );
3403
+ } else if (options.server) {
3404
+ this._server = options.server;
3405
+ }
3406
+ if (this._server) {
3407
+ const emitConnection = this.emit.bind(this, "connection");
3408
+ this._removeListeners = addListeners(this._server, {
3409
+ listening: this.emit.bind(this, "listening"),
3410
+ error: this.emit.bind(this, "error"),
3411
+ upgrade: (req, socket, head) => {
3412
+ this.handleUpgrade(req, socket, head, emitConnection);
3413
+ }
3414
+ });
3415
+ }
3416
+ if (options.perMessageDeflate === true) options.perMessageDeflate = {};
3417
+ if (options.clientTracking) {
3418
+ this.clients = /* @__PURE__ */ new Set();
3419
+ this._shouldEmitClose = false;
3420
+ }
3421
+ this.options = options;
3422
+ this._state = RUNNING;
3423
+ }
3424
+ /**
3425
+ * Returns the bound address, the address family name, and port of the server
3426
+ * as reported by the operating system if listening on an IP socket.
3427
+ * If the server is listening on a pipe or UNIX domain socket, the name is
3428
+ * returned as a string.
3429
+ *
3430
+ * @return {(Object|String|null)} The address of the server
3431
+ * @public
3432
+ */
3433
+ address() {
3434
+ if (this.options.noServer) {
3435
+ throw new Error('The server is operating in "noServer" mode');
3436
+ }
3437
+ if (!this._server) return null;
3438
+ return this._server.address();
3439
+ }
3440
+ /**
3441
+ * Stop the server from accepting new connections and emit the `'close'` event
3442
+ * when all existing connections are closed.
3443
+ *
3444
+ * @param {Function} [cb] A one-time listener for the `'close'` event
3445
+ * @public
3446
+ */
3447
+ close(cb) {
3448
+ if (this._state === CLOSED) {
3449
+ if (cb) {
3450
+ this.once("close", () => {
3451
+ cb(new Error("The server is not running"));
3452
+ });
3453
+ }
3454
+ process.nextTick(emitClose, this);
3455
+ return;
3456
+ }
3457
+ if (cb) this.once("close", cb);
3458
+ if (this._state === CLOSING) return;
3459
+ this._state = CLOSING;
3460
+ if (this.options.noServer || this.options.server) {
3461
+ if (this._server) {
3462
+ this._removeListeners();
3463
+ this._removeListeners = this._server = null;
3464
+ }
3465
+ if (this.clients) {
3466
+ if (!this.clients.size) {
3467
+ process.nextTick(emitClose, this);
3468
+ } else {
3469
+ this._shouldEmitClose = true;
3470
+ }
3471
+ } else {
3472
+ process.nextTick(emitClose, this);
3473
+ }
3474
+ } else {
3475
+ const server = this._server;
3476
+ this._removeListeners();
3477
+ this._removeListeners = this._server = null;
3478
+ server.close(() => {
3479
+ emitClose(this);
3480
+ });
3481
+ }
3482
+ }
3483
+ /**
3484
+ * See if a given request should be handled by this server instance.
3485
+ *
3486
+ * @param {http.IncomingMessage} req Request object to inspect
3487
+ * @return {Boolean} `true` if the request is valid, else `false`
3488
+ * @public
3489
+ */
3490
+ shouldHandle(req) {
3491
+ if (this.options.path) {
3492
+ const index = req.url.indexOf("?");
3493
+ const pathname = index !== -1 ? req.url.slice(0, index) : req.url;
3494
+ if (pathname !== this.options.path) return false;
3495
+ }
3496
+ return true;
3497
+ }
3498
+ /**
3499
+ * Handle a HTTP Upgrade request.
3500
+ *
3501
+ * @param {http.IncomingMessage} req The request object
3502
+ * @param {Duplex} socket The network socket between the server and client
3503
+ * @param {Buffer} head The first packet of the upgraded stream
3504
+ * @param {Function} cb Callback
3505
+ * @public
3506
+ */
3507
+ handleUpgrade(req, socket, head, cb) {
3508
+ socket.on("error", socketOnError);
3509
+ const key = req.headers["sec-websocket-key"];
3510
+ const upgrade = req.headers.upgrade;
3511
+ const version = +req.headers["sec-websocket-version"];
3512
+ if (req.method !== "GET") {
3513
+ const message = "Invalid HTTP method";
3514
+ abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);
3515
+ return;
3516
+ }
3517
+ if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
3518
+ const message = "Invalid Upgrade header";
3519
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3520
+ return;
3521
+ }
3522
+ if (key === void 0 || !keyRegex.test(key)) {
3523
+ const message = "Missing or invalid Sec-WebSocket-Key header";
3524
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3525
+ return;
3526
+ }
3527
+ if (version !== 13 && version !== 8) {
3528
+ const message = "Missing or invalid Sec-WebSocket-Version header";
3529
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message, {
3530
+ "Sec-WebSocket-Version": "13, 8"
3531
+ });
3532
+ return;
3533
+ }
3534
+ if (!this.shouldHandle(req)) {
3535
+ abortHandshake(socket, 400);
3536
+ return;
3537
+ }
3538
+ const secWebSocketProtocol = req.headers["sec-websocket-protocol"];
3539
+ let protocols = /* @__PURE__ */ new Set();
3540
+ if (secWebSocketProtocol !== void 0) {
3541
+ try {
3542
+ protocols = subprotocol2.parse(secWebSocketProtocol);
3543
+ } catch (err) {
3544
+ const message = "Invalid Sec-WebSocket-Protocol header";
3545
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3546
+ return;
3547
+ }
3548
+ }
3549
+ const secWebSocketExtensions = req.headers["sec-websocket-extensions"];
3550
+ const extensions = {};
3551
+ if (this.options.perMessageDeflate && secWebSocketExtensions !== void 0) {
3552
+ const perMessageDeflate = new PerMessageDeflate2({
3553
+ ...this.options.perMessageDeflate,
3554
+ isServer: true,
3555
+ maxPayload: this.options.maxPayload
3556
+ });
3557
+ try {
3558
+ const offers = extension2.parse(secWebSocketExtensions);
3559
+ if (offers[PerMessageDeflate2.extensionName]) {
3560
+ perMessageDeflate.accept(offers[PerMessageDeflate2.extensionName]);
3561
+ extensions[PerMessageDeflate2.extensionName] = perMessageDeflate;
3562
+ }
3563
+ } catch (err) {
3564
+ const message = "Invalid or unacceptable Sec-WebSocket-Extensions header";
3565
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3566
+ return;
3567
+ }
3568
+ }
3569
+ if (this.options.verifyClient) {
3570
+ const info = {
3571
+ origin: req.headers[`${version === 8 ? "sec-websocket-origin" : "origin"}`],
3572
+ secure: !!(req.socket.authorized || req.socket.encrypted),
3573
+ req
3574
+ };
3575
+ if (this.options.verifyClient.length === 2) {
3576
+ this.options.verifyClient(info, (verified, code, message, headers) => {
3577
+ if (!verified) {
3578
+ return abortHandshake(socket, code || 401, message, headers);
3579
+ }
3580
+ this.completeUpgrade(
3581
+ extensions,
3582
+ key,
3583
+ protocols,
3584
+ req,
3585
+ socket,
3586
+ head,
3587
+ cb
3588
+ );
3589
+ });
3590
+ return;
3591
+ }
3592
+ if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);
3593
+ }
3594
+ this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
3595
+ }
3596
+ /**
3597
+ * Upgrade the connection to WebSocket.
3598
+ *
3599
+ * @param {Object} extensions The accepted extensions
3600
+ * @param {String} key The value of the `Sec-WebSocket-Key` header
3601
+ * @param {Set} protocols The subprotocols
3602
+ * @param {http.IncomingMessage} req The request object
3603
+ * @param {Duplex} socket The network socket between the server and client
3604
+ * @param {Buffer} head The first packet of the upgraded stream
3605
+ * @param {Function} cb Callback
3606
+ * @throws {Error} If called more than once with the same socket
3607
+ * @private
3608
+ */
3609
+ completeUpgrade(extensions, key, protocols, req, socket, head, cb) {
3610
+ if (!socket.readable || !socket.writable) return socket.destroy();
3611
+ if (socket[kWebSocket]) {
3612
+ throw new Error(
3613
+ "server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration"
3614
+ );
3615
+ }
3616
+ if (this._state > RUNNING) return abortHandshake(socket, 503);
3617
+ const digest = createHash("sha1").update(key + GUID).digest("base64");
3618
+ const headers = [
3619
+ "HTTP/1.1 101 Switching Protocols",
3620
+ "Upgrade: websocket",
3621
+ "Connection: Upgrade",
3622
+ `Sec-WebSocket-Accept: ${digest}`
3623
+ ];
3624
+ const ws = new this.options.WebSocket(null, void 0, this.options);
3625
+ if (protocols.size) {
3626
+ const protocol = this.options.handleProtocols ? this.options.handleProtocols(protocols, req) : protocols.values().next().value;
3627
+ if (protocol) {
3628
+ headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
3629
+ ws._protocol = protocol;
3630
+ }
3631
+ }
3632
+ if (extensions[PerMessageDeflate2.extensionName]) {
3633
+ const params = extensions[PerMessageDeflate2.extensionName].params;
3634
+ const value = extension2.format({
3635
+ [PerMessageDeflate2.extensionName]: [params]
3636
+ });
3637
+ headers.push(`Sec-WebSocket-Extensions: ${value}`);
3638
+ ws._extensions = extensions;
3639
+ }
3640
+ this.emit("headers", headers, req);
3641
+ socket.write(headers.concat("\r\n").join("\r\n"));
3642
+ socket.removeListener("error", socketOnError);
3643
+ ws.setSocket(socket, head, {
3644
+ allowSynchronousEvents: this.options.allowSynchronousEvents,
3645
+ maxBufferedChunks: this.options.maxBufferedChunks,
3646
+ maxFragments: this.options.maxFragments,
3647
+ maxPayload: this.options.maxPayload,
3648
+ skipUTF8Validation: this.options.skipUTF8Validation
3649
+ });
3650
+ if (this.clients) {
3651
+ this.clients.add(ws);
3652
+ ws.on("close", () => {
3653
+ this.clients.delete(ws);
3654
+ if (this._shouldEmitClose && !this.clients.size) {
3655
+ process.nextTick(emitClose, this);
3656
+ }
3657
+ });
3658
+ }
3659
+ cb(ws, req);
3660
+ }
3661
+ };
3662
+ module.exports = WebSocketServer2;
3663
+ function addListeners(server, map) {
3664
+ for (const event of Object.keys(map)) server.on(event, map[event]);
3665
+ return function removeListeners() {
3666
+ for (const event of Object.keys(map)) {
3667
+ server.removeListener(event, map[event]);
3668
+ }
3669
+ };
3670
+ }
3671
+ function emitClose(server) {
3672
+ server._state = CLOSED;
3673
+ server.emit("close");
3674
+ }
3675
+ function socketOnError() {
3676
+ this.destroy();
3677
+ }
3678
+ function abortHandshake(socket, code, message, headers) {
3679
+ message = message || http.STATUS_CODES[code];
3680
+ headers = {
3681
+ Connection: "close",
3682
+ "Content-Type": "text/html",
3683
+ "Content-Length": Buffer.byteLength(message),
3684
+ ...headers
3685
+ };
3686
+ socket.once("finish", socket.destroy);
3687
+ socket.end(
3688
+ `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r
3689
+ ` + Object.keys(headers).map((h) => `${h}: ${headers[h]}`).join("\r\n") + "\r\n\r\n" + message
3690
+ );
3691
+ }
3692
+ function abortHandshakeOrEmitwsClientError(server, req, socket, code, message, headers) {
3693
+ if (server.listenerCount("wsClientError")) {
3694
+ const err = new Error(message);
3695
+ Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);
3696
+ server.emit("wsClientError", err, socket, req);
3697
+ } else {
3698
+ abortHandshake(socket, code, message, headers);
3699
+ }
3700
+ }
3701
+ }
3702
+ });
2
3703
 
3
- // src/index.ts
4
- import os3 from "os";
5
- import path4 from "path";
3704
+ // src/keep-awake.ts
3705
+ import { spawn } from "child_process";
3706
+ var HELPER_SECONDS = 210;
3707
+ var windowsScript = `
3708
+ Add-Type -TypeDefinition 'using System; using System.Runtime.InteropServices; public static class RemoteArcPower { [DllImport("kernel32.dll")] public static extern uint SetThreadExecutionState(uint flags); }'
3709
+ if ([RemoteArcPower]::SetThreadExecutionState([uint32]2147483649) -eq 0) { exit 1 }
3710
+ try { Start-Sleep -Seconds ${HELPER_SECONDS} } finally { [RemoteArcPower]::SetThreadExecutionState([uint32]2147483648) | Out-Null }
3711
+ `;
3712
+ function createTaskKeepAwakeManager(options = {}) {
3713
+ const platform = options.platform || process.platform;
3714
+ const clock = options.now || Date.now;
3715
+ const launch = options.spawn || spawn;
3716
+ const leases = /* @__PURE__ */ new Map();
3717
+ let helper = null;
3718
+ let helperUntil = 0;
3719
+ let closed = false;
3720
+ let failure = null;
3721
+ const supported = ["darwin", "win32", "linux"].includes(platform);
3722
+ const stop = () => {
3723
+ helper?.kill();
3724
+ helper = null;
3725
+ helperUntil = 0;
3726
+ };
3727
+ const sweep = () => {
3728
+ for (const [id, expires] of leases) if (expires <= clock()) leases.delete(id);
3729
+ if (!leases.size) stop();
3730
+ };
3731
+ const timer = setInterval(sweep, 15e3);
3732
+ timer.unref();
3733
+ async function start() {
3734
+ if (helper && helperUntil > clock() + 9e4) return;
3735
+ stop();
3736
+ const [command, args] = platform === "darwin" ? ["caffeinate", ["-i", "-t", String(HELPER_SECONDS)]] : platform === "win32" ? ["powershell.exe", ["-NoProfile", "-NonInteractive", "-WindowStyle", "Hidden", "-Command", windowsScript]] : ["systemd-inhibit", ["--what=sleep", "--mode=block", "--who=Remote Arc", "--why=An authorized task is active", "sleep", String(HELPER_SECONDS)]];
3737
+ const child = launch(command, args, { windowsHide: true, stdio: "ignore" });
3738
+ helper = child;
3739
+ helperUntil = clock() + HELPER_SECONDS * 1e3;
3740
+ failure = null;
3741
+ child.once("exit", (code) => {
3742
+ if (helper !== child) return;
3743
+ helper = null;
3744
+ helperUntil = 0;
3745
+ if (code !== 0 && code !== null) failure = "Power inhibitor exited with code " + code;
3746
+ });
3747
+ await new Promise((resolve, reject) => {
3748
+ child.once("spawn", resolve);
3749
+ child.once("error", (error) => {
3750
+ failure = error.message;
3751
+ helper = null;
3752
+ helperUntil = 0;
3753
+ reject(error);
3754
+ });
3755
+ });
3756
+ }
3757
+ return {
3758
+ async set(taskId, seconds) {
3759
+ if (closed) throw new Error("Keep-awake manager is closed.");
3760
+ if (!/^[A-Za-z0-9_-]{1,120}$/.test(taskId) || !Number.isInteger(seconds) || seconds < 0 || seconds > 180) throw new Error("Invalid keep-awake lease.");
3761
+ if (seconds === 0) leases.delete(taskId);
3762
+ else leases.set(taskId, clock() + seconds * 1e3);
3763
+ sweep();
3764
+ if (!supported) return { supported: false, active: false, detail: "OS power inhibition is unavailable." };
3765
+ if (leases.size) await start();
3766
+ return { supported, active: Boolean(helper), leased_tasks: leases.size, detail: failure };
3767
+ },
3768
+ status() {
3769
+ sweep();
3770
+ return { supported, active: Boolean(helper), leased_tasks: leases.size, detail: failure };
3771
+ },
3772
+ close() {
3773
+ closed = true;
3774
+ clearInterval(timer);
3775
+ leases.clear();
3776
+ stop();
3777
+ }
3778
+ };
3779
+ }
3780
+
3781
+ // src/goal-workspace.ts
6
3782
  import fs4 from "fs/promises";
7
- import { spawn as spawn2 } from "child_process";
8
- import process3 from "process";
9
- import WebSocket from "ws";
3783
+ import path4 from "path";
3784
+ import { execFile as execFile2 } from "child_process";
3785
+ import { promisify } from "util";
10
3786
 
11
3787
  // ../execution-core/src/filesystem.ts
12
3788
  import crypto from "crypto";
@@ -86,6 +3862,121 @@ async function readTextFile(targetPath, offset, length) {
86
3862
 
87
3863
  ${chunk}`;
88
3864
  }
3865
+ var BINARY_DEFAULT_BYTES = 64 * 1024;
3866
+ var BINARY_MAX_BYTES = 256 * 1024;
3867
+ function binaryFileRevision(stat) {
3868
+ return crypto.createHash("sha256").update(String(stat.size) + ":" + String(stat.mtimeMs)).digest("hex");
3869
+ }
3870
+ function assertBinaryRevision(expected, actual) {
3871
+ if (expected && expected !== actual) {
3872
+ throw new Error(
3873
+ "FILE_CHANGED_DURING_READ: Binary file changed since the previous chunk. Restart from offset 0 with the new file_revision."
3874
+ );
3875
+ }
3876
+ }
3877
+ function binaryMimeType(targetPath, header) {
3878
+ const extension2 = path.extname(targetPath).toLowerCase();
3879
+ const office = {
3880
+ ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
3881
+ ".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
3882
+ ".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation"
3883
+ };
3884
+ if (office[extension2]) return office[extension2];
3885
+ const bytes = header || Buffer.alloc(0);
3886
+ const ascii = bytes.toString("ascii");
3887
+ if (bytes.length >= 8 && bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))) {
3888
+ return "image/png";
3889
+ }
3890
+ if (bytes.length >= 3 && bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255) {
3891
+ return "image/jpeg";
3892
+ }
3893
+ if (ascii.startsWith("GIF87a") || ascii.startsWith("GIF89a")) return "image/gif";
3894
+ if (ascii.startsWith("%PDF-")) return "application/pdf";
3895
+ if (bytes.length >= 2 && bytes[0] === 31 && bytes[1] === 139) return "application/gzip";
3896
+ if (bytes.length >= 4 && bytes.subarray(0, 4).equals(Buffer.from([0, 97, 115, 109]))) {
3897
+ return "application/wasm";
3898
+ }
3899
+ if (bytes.length >= 12 && ascii.startsWith("RIFF") && ascii.slice(8, 12) === "WEBP") {
3900
+ return "image/webp";
3901
+ }
3902
+ if (bytes.length >= 4 && bytes[0] === 80 && bytes[1] === 75 && (bytes[2] === 3 && bytes[3] === 4 || bytes[2] === 5 && bytes[3] === 6 || bytes[2] === 7 && bytes[3] === 8)) {
3903
+ return "application/zip";
3904
+ }
3905
+ const known = {
3906
+ ".png": "image/png",
3907
+ ".jpg": "image/jpeg",
3908
+ ".jpeg": "image/jpeg",
3909
+ ".gif": "image/gif",
3910
+ ".webp": "image/webp",
3911
+ ".pdf": "application/pdf",
3912
+ ".zip": "application/zip",
3913
+ ".gz": "application/gzip",
3914
+ ".wasm": "application/wasm"
3915
+ };
3916
+ return known[extension2] || "application/octet-stream";
3917
+ }
3918
+ async function readBinaryFile(targetPath, offset = 0, length = BINARY_DEFAULT_BYTES, expectedRevision) {
3919
+ const stat = await fs.stat(targetPath);
3920
+ if (!stat.isFile()) throw new Error("Path is not a file: " + targetPath);
3921
+ const fileRevision = binaryFileRevision(stat);
3922
+ assertBinaryRevision(expectedRevision, fileRevision);
3923
+ const byteOffset = Number.isFinite(offset) ? Math.max(0, Math.trunc(offset)) : 0;
3924
+ const requested = Number.isFinite(length) ? Math.trunc(length) : BINARY_DEFAULT_BYTES;
3925
+ if (requested <= 0) throw new Error("length must be a positive byte count.");
3926
+ if (requested > BINARY_MAX_BYTES) {
3927
+ throw new Error("read_binary_file length cannot exceed " + BINARY_MAX_BYTES + " bytes.");
3928
+ }
3929
+ if (byteOffset >= stat.size) {
3930
+ return {
3931
+ path: targetPath,
3932
+ mime_type: binaryMimeType(targetPath),
3933
+ encoding: "base64",
3934
+ size: stat.size,
3935
+ file_revision: fileRevision,
3936
+ offset: byteOffset,
3937
+ bytes_read: 0,
3938
+ eof: true,
3939
+ chunk_sha256: crypto.createHash("sha256").update(Buffer.alloc(0)).digest("hex"),
3940
+ data: ""
3941
+ };
3942
+ }
3943
+ const toRead = Math.min(requested, stat.size - byteOffset);
3944
+ const handle = await fs.open(targetPath, "r");
3945
+ try {
3946
+ const headerBuffer = Buffer.allocUnsafe(Math.min(16, stat.size));
3947
+ const headerResult = await handle.read(
3948
+ headerBuffer,
3949
+ 0,
3950
+ headerBuffer.length,
3951
+ 0
3952
+ );
3953
+ const header = headerBuffer.subarray(0, headerResult.bytesRead);
3954
+ const buffer = Buffer.allocUnsafe(toRead);
3955
+ const result = await handle.read(buffer, 0, toRead, byteOffset);
3956
+ const chunk = buffer.subarray(0, result.bytesRead);
3957
+ const afterStat = await fs.stat(targetPath);
3958
+ const afterRevision = binaryFileRevision(afterStat);
3959
+ if (afterRevision !== fileRevision) {
3960
+ throw new Error(
3961
+ "FILE_CHANGED_DURING_READ: Binary file changed while this chunk was being read. Restart from offset 0."
3962
+ );
3963
+ }
3964
+ return {
3965
+ path: targetPath,
3966
+ mime_type: binaryMimeType(targetPath, header),
3967
+ encoding: "base64",
3968
+ size: stat.size,
3969
+ file_revision: fileRevision,
3970
+ offset: byteOffset,
3971
+ bytes_read: result.bytesRead,
3972
+ eof: byteOffset + result.bytesRead >= stat.size,
3973
+ chunk_sha256: crypto.createHash("sha256").update(chunk).digest("hex"),
3974
+ data: chunk.toString("base64")
3975
+ };
3976
+ } finally {
3977
+ await handle.close();
3978
+ }
3979
+ }
89
3980
  async function getFileInfo(targetPath) {
90
3981
  const stat = await fs.lstat(targetPath);
91
3982
  return {
@@ -180,7 +4071,7 @@ async function browseDirectories(targetPath, canReveal) {
180
4071
  }
181
4072
 
182
4073
  // ../execution-core/src/process.ts
183
- import { execFile, spawn } from "child_process";
4074
+ import { execFile, spawn as spawn2 } from "child_process";
184
4075
  import crypto2 from "crypto";
185
4076
  import process2 from "process";
186
4077
  var MAX_CAPTURE_BYTES = 2 * 1024 * 1024;
@@ -210,7 +4101,7 @@ async function terminateTree(child) {
210
4101
  if (!child.pid) return;
211
4102
  if (process2.platform === "win32") {
212
4103
  await new Promise((resolve) => {
213
- const killer = spawn(
4104
+ const killer = spawn2(
214
4105
  "taskkill.exe",
215
4106
  ["/PID", String(child.pid), "/T", "/F"],
216
4107
  { windowsHide: true, stdio: "ignore" }
@@ -236,7 +4127,7 @@ async function runShellCommand(command, timeoutMs = 5e3, cwd) {
236
4127
  const timeout = Math.max(100, Math.min(12e4, Math.trunc(timeoutMs || 5e3)));
237
4128
  const startedAt = Date.now();
238
4129
  return await new Promise((resolve, reject) => {
239
- const child = spawn(command, {
4130
+ const child = spawn2(command, {
240
4131
  shell: true,
241
4132
  cwd,
242
4133
  windowsHide: true,
@@ -297,14 +4188,15 @@ function cleanupManagedProcesses() {
297
4188
  managedProcesses.delete(item.id);
298
4189
  }
299
4190
  }
300
- async function startBackgroundProcess(command, cwd) {
4191
+ async function startBackgroundProcess(command, cwd, maxDurationSeconds) {
4192
+ if (maxDurationSeconds !== void 0 && (!Number.isInteger(maxDurationSeconds) || maxDurationSeconds < 1 || maxDurationSeconds > 7 * 86400)) throw new Error("Invalid managed process duration.");
301
4193
  cleanupManagedProcesses();
302
4194
  if (managedProcesses.size >= MAX_MANAGED_PROCESSES) {
303
4195
  throw new Error(
304
4196
  "Remote Arc already has the maximum number of managed background processes on this device."
305
4197
  );
306
4198
  }
307
- const child = spawn(command, {
4199
+ const child = spawn2(command, {
308
4200
  shell: true,
309
4201
  cwd,
310
4202
  windowsHide: true,
@@ -325,6 +4217,11 @@ async function startBackgroundProcess(command, cwd) {
325
4217
  stderr: ""
326
4218
  };
327
4219
  managedProcesses.set(id, item);
4220
+ const deadlineTimer = maxDurationSeconds === void 0 ? void 0 : setTimeout(() => {
4221
+ item.stderr = appendCapped(item.stderr, "\nRemote Arc: authorized process time budget exhausted.");
4222
+ void terminateTree(child);
4223
+ }, maxDurationSeconds * 1e3);
4224
+ deadlineTimer?.unref();
328
4225
  child.stdout?.on("data", (chunk) => {
329
4226
  item.stdout = appendCapped(item.stdout, chunk);
330
4227
  });
@@ -332,10 +4229,12 @@ async function startBackgroundProcess(command, cwd) {
332
4229
  item.stderr = appendCapped(item.stderr, chunk);
333
4230
  });
334
4231
  child.once("error", (error) => {
4232
+ clearTimeout(deadlineTimer);
335
4233
  item.stderr = appendCapped(item.stderr, "\n" + error.message);
336
4234
  item.endedAt = Date.now();
337
4235
  });
338
4236
  child.once("close", (code, signal) => {
4237
+ clearTimeout(deadlineTimer);
339
4238
  item.exitCode = code;
340
4239
  item.signal = signal;
341
4240
  item.endedAt = Date.now();
@@ -646,7 +4545,7 @@ var DESTRUCTIVE_COMMAND_RULES = [
646
4545
  reason: "recursive deletion of a root or home path"
647
4546
  },
648
4547
  {
649
- pattern: /\b(?:mkfs(?:\.\w+)?|wipefs|fdisk|parted)\b/i,
4548
+ pattern: /(?:^|(?:&&|\|\||[;&|])\s*|(?:-Command|-c)\s+["']?\s*)(?:sudo\s+)?(?:mkfs(?:\.\w+)?|wipefs|fdisk|parted)\b/i,
650
4549
  reason: "disk or filesystem destructive operation"
651
4550
  },
652
4551
  {
@@ -658,19 +4557,19 @@ var DESTRUCTIVE_COMMAND_RULES = [
658
4557
  reason: "disk erase"
659
4558
  },
660
4559
  {
661
- pattern: /\b(?:format(?:\.com)?\s+[a-z]:|diskpart\b|clear-disk\b|initialize-disk\b)/i,
4560
+ pattern: /(?:^|(?:&&|\|\||[;&|])\s*|(?:-Command|-c)\s+["']?\s*)(?:format(?:\.com)?\s+[a-z]:|diskpart\b|clear-disk\b|initialize-disk\b)/i,
662
4561
  reason: "Windows disk destructive operation"
663
4562
  },
664
4563
  {
665
- pattern: /\b(?:shutdown|reboot|halt|poweroff)\b/i,
4564
+ pattern: /(?:^|(?:&&|\|\||[;&|])\s*|(?:-Command|-c)\s+["']?\s*)(?:sudo\s+)?(?:shutdown(?:\.exe)?|reboot|halt|poweroff)\b/i,
666
4565
  reason: "system shutdown or reboot"
667
4566
  },
668
4567
  {
669
- pattern: /\bremove-item\b[^\n]*(?:-recurse[^\n]*-force|-force[^\n]*-recurse)[^\n]*(?:[a-z]:\\(?:\*|\s|$)|\$env:systemdrive)/i,
4568
+ pattern: /(?:^|(?:&&|\|\||[;&|])\s*|(?:-Command|-c)\s+["']?\s*)remove-item\b[^\n]*(?:-recurse[^\n]*-force|-force[^\n]*-recurse)[^\n]*(?:[a-z]:\\(?:\*|\s|$)|\$env:systemdrive)/i,
670
4569
  reason: "recursive forced deletion of a drive root"
671
4570
  },
672
4571
  {
673
- pattern: /\b(?:del|erase|rd|rmdir)\b[^\n]*\/s[^\n]*\/q[^\n]*[a-z]:\\/i,
4572
+ pattern: /(?:^|(?:&&|\|\||[;&|])\s*|(?:-Command|-c)\s+["']?\s*)(?:del|erase|rd|rmdir)\b[^\n]*\/s[^\n]*\/q[^\n]*[a-z]:\\/i,
674
4573
  reason: "recursive Windows drive deletion"
675
4574
  },
676
4575
  {
@@ -780,17 +4679,20 @@ function looksLikeSensitiveFile(target) {
780
4679
  if (normalized.endsWith("/.kube/config")) return true;
781
4680
  return false;
782
4681
  }
783
- async function enforcePathPolicy(targetPath, policy = {}) {
4682
+ async function enforcePathPolicy(targetPath, policy = {}, options = {}) {
784
4683
  const target = await canonicalTarget(targetPath);
785
4684
  const workspaceInputs = (policy.workspaceRoots || []).filter(
786
4685
  (item) => typeof item === "string" && item.trim()
787
4686
  );
788
4687
  const roots = await Promise.all(workspaceInputs.map(canonicalTarget));
789
- if (roots.length && !roots.some((root) => isInside(target, root))) {
4688
+ if (options.enforceWorkspace !== false && roots.length && !roots.some((root) => isInside(target, root))) {
790
4689
  throw new Error(
791
- "Blocked by Remote Arc Workspace Scope: path is outside the allowed workspace roots."
4690
+ "Blocked by Remote Arc Trusted Write Locations: path is outside the allowed write roots."
792
4691
  );
793
4692
  }
4693
+ if (policy.taskWorkspaceRoot && !isInside(target, await canonicalTarget(policy.taskWorkspaceRoot))) {
4694
+ throw new Error("Blocked by Remote Arc Task Workspace: path escapes the owned candidate.");
4695
+ }
794
4696
  if (policy.protectSensitivePaths !== false) {
795
4697
  const sensitiveInputs = [
796
4698
  ...defaultSensitiveRoots(),
@@ -825,7 +4727,8 @@ function normalizePolicy(policy) {
825
4727
  sensitiveAllowPaths: Array.from(
826
4728
  new Set((policy?.sensitiveAllowPaths || []).filter((item) => typeof item === "string" && item.trim()))
827
4729
  ).slice(0, 32),
828
- undoEnabled: policy?.undoEnabled !== false
4730
+ undoEnabled: policy?.undoEnabled !== false,
4731
+ ...typeof policy?.taskWorkspaceRoot === "string" && policy.taskWorkspaceRoot.trim() ? { taskWorkspaceRoot: policy.taskWorkspaceRoot } : {}
829
4732
  };
830
4733
  }
831
4734
 
@@ -834,6 +4737,7 @@ var SAFE_TOOLS = /* @__PURE__ */ new Set([
834
4737
  "list_directory",
835
4738
  "browse_directories",
836
4739
  "read_file",
4740
+ "read_binary_file",
837
4741
  "get_file_info",
838
4742
  "list_processes",
839
4743
  "list_undo_actions"
@@ -893,6 +4797,21 @@ var DEFINITIONS = [
893
4797
  additionalProperties: false
894
4798
  }
895
4799
  },
4800
+ {
4801
+ name: "read_binary_file",
4802
+ description: "Read a bounded binary file chunk as base64. Offset and length are byte counts; pass expected_revision on later chunks to detect file changes.",
4803
+ inputSchema: {
4804
+ type: "object",
4805
+ properties: {
4806
+ path: { type: "string" },
4807
+ offset: { type: "integer", minimum: 0, default: 0 },
4808
+ length: { type: "integer", minimum: 1, maximum: 262144, default: 65536 },
4809
+ expected_revision: { type: "string", minLength: 1, maxLength: 128 }
4810
+ },
4811
+ required: ["path"],
4812
+ additionalProperties: false
4813
+ }
4814
+ },
896
4815
  {
897
4816
  name: "get_file_info",
898
4817
  description: "Get local file or directory metadata.",
@@ -1063,14 +4982,18 @@ var RemoteArcExecutionCore = class {
1063
4982
  const policy = normalizePolicy(policyInput);
1064
4983
  switch (toolName) {
1065
4984
  case "list_directory": {
1066
- const target = await enforcePathPolicy(requiredString(args, "path"), policy);
4985
+ const target = await enforcePathPolicy(requiredString(args, "path"), policy, {
4986
+ enforceWorkspace: false
4987
+ });
1067
4988
  return textResult(
1068
4989
  await listDirectory(
1069
4990
  target,
1070
4991
  optionalNumber(args, "depth") ?? 2,
1071
4992
  async (candidate) => {
1072
4993
  try {
1073
- await enforcePathPolicy(candidate, policy);
4994
+ await enforcePathPolicy(candidate, policy, {
4995
+ enforceWorkspace: false
4996
+ });
1074
4997
  return true;
1075
4998
  } catch {
1076
4999
  return false;
@@ -1080,7 +5003,9 @@ var RemoteArcExecutionCore = class {
1080
5003
  );
1081
5004
  }
1082
5005
  case "browse_directories": {
1083
- const target = await enforcePathPolicy(requiredString(args, "path"), policy);
5006
+ const target = await enforcePathPolicy(requiredString(args, "path"), policy, {
5007
+ enforceWorkspace: false
5008
+ });
1084
5009
  return textResult(
1085
5010
  await browseDirectories(
1086
5011
  target,
@@ -1096,7 +5021,9 @@ var RemoteArcExecutionCore = class {
1096
5021
  );
1097
5022
  }
1098
5023
  case "read_file": {
1099
- const target = await enforcePathPolicy(requiredString(args, "path"), policy);
5024
+ const target = await enforcePathPolicy(requiredString(args, "path"), policy, {
5025
+ enforceWorkspace: false
5026
+ });
1100
5027
  return textResult(
1101
5028
  await readTextFile(
1102
5029
  target,
@@ -1105,8 +5032,23 @@ var RemoteArcExecutionCore = class {
1105
5032
  )
1106
5033
  );
1107
5034
  }
5035
+ case "read_binary_file": {
5036
+ const target = await enforcePathPolicy(requiredString(args, "path"), policy, {
5037
+ enforceWorkspace: false
5038
+ });
5039
+ return textResult(
5040
+ await readBinaryFile(
5041
+ target,
5042
+ optionalNumber(args, "offset"),
5043
+ optionalNumber(args, "length"),
5044
+ optionalString(args, "expected_revision")
5045
+ )
5046
+ );
5047
+ }
1108
5048
  case "get_file_info": {
1109
- const target = await enforcePathPolicy(requiredString(args, "path"), policy);
5049
+ const target = await enforcePathPolicy(requiredString(args, "path"), policy, {
5050
+ enforceWorkspace: false
5051
+ });
1110
5052
  return textResult(await getFileInfo(target));
1111
5053
  }
1112
5054
  case "list_processes":
@@ -1155,12 +5097,12 @@ var RemoteArcExecutionCore = class {
1155
5097
  const cwdInput = optionalString(args, "cwd");
1156
5098
  if ((policy.workspaceRoots || []).length && !cwdInput) {
1157
5099
  throw new Error(
1158
- "Workspace Scope is enabled. start_process requires an in-scope cwd. Terminal commands are not an OS sandbox and may still access paths outside that directory."
5100
+ "Trusted Write Locations are enabled. start_process requires an in-scope cwd. Terminal commands are not an OS sandbox and may still access paths outside that directory."
1159
5101
  );
1160
5102
  }
1161
5103
  const cwd = cwdInput ? await enforcePathPolicy(cwdInput, policy) : void 0;
1162
5104
  if (args.background === true) {
1163
- return textResult(await startBackgroundProcess(command, cwd));
5105
+ return textResult(await startBackgroundProcess(command, cwd, optionalNumber(args, "max_duration_seconds")));
1164
5106
  }
1165
5107
  return textResult(
1166
5108
  await runShellCommand(
@@ -1221,12 +5163,396 @@ var RemoteArcExecutionCore = class {
1221
5163
  }
1222
5164
  };
1223
5165
 
5166
+ // src/goal-workspace.ts
5167
+ var run = promisify(execFile2);
5168
+ var pending = /* @__PURE__ */ new Map();
5169
+ var samePath = (a, b) => process.platform === "win32" ? path4.resolve(a).toLowerCase() === path4.resolve(b).toLowerCase() : path4.resolve(a) === path4.resolve(b);
5170
+ var git = async (cwd, args) => (await run("git", ["-c", "core.hooksPath=", "-c", "commit.gpgSign=false", "-C", cwd, ...args], { windowsHide: true, timeout: 2e4, maxBuffer: 1e6, env: { ...process.env, GIT_TERMINAL_PROMPT: "0", GIT_AUTHOR_NAME: "Remote Arc", GIT_AUTHOR_EMAIL: "task@remotearc.local", GIT_COMMITTER_NAME: "Remote Arc", GIT_COMMITTER_EMAIL: "task@remotearc.local" } })).stdout.trim();
5171
+ async function goalWorkspace(args, policy = {}) {
5172
+ const id = String(args.task_id || ""), operation = String(args.operation_id || ""), action = String(args.action || "");
5173
+ if (!/^[A-Za-z0-9_-]{1,100}$/.test(id) || !/^[A-Za-z0-9_.:-]{1,120}$/.test(operation) || !["create", "capture", "reject", "status", "fingerprint"].includes(action)) throw new Error("Invalid goal workspace operation.");
5174
+ const prior = pending.get(id) || Promise.resolve();
5175
+ const next = prior.catch(() => void 0).then(async () => {
5176
+ const root = await enforcePathPolicy(String(args.workspace || ""), policy);
5177
+ const canonical = await fs4.realpath(root);
5178
+ const directory = await enforcePathPolicy(path4.join(canonical, ".remotearc-goals", id), policy);
5179
+ const file = path4.join(directory, "state.json");
5180
+ let state;
5181
+ try {
5182
+ state = JSON.parse(await fs4.readFile(file, "utf8"));
5183
+ } catch (e) {
5184
+ if (e.code !== "ENOENT") throw e;
5185
+ }
5186
+ if (state && (state.version !== 1 || state.task_id !== id || state.root !== canonical)) throw new Error("Workspace ownership cannot be proven.");
5187
+ const result = (s) => ({ root: s.root, path: s.path, frontier: s.frontier, generation: s.generation });
5188
+ const save = async (s) => {
5189
+ const temp = file + ".next";
5190
+ await fs4.writeFile(temp, JSON.stringify(s), { encoding: "utf8", mode: 384 });
5191
+ await fs4.rename(temp, file);
5192
+ };
5193
+ if (state?.operations[operation] && !["status", "fingerprint"].includes(action)) return state.operations[operation];
5194
+ if (!state) {
5195
+ if (action !== "create") throw new Error("No owned goal workspace. Update the device CLI if this tool is unavailable.");
5196
+ const top = await fs4.realpath(await git(canonical, ["rev-parse", "--show-toplevel"]));
5197
+ if (!samePath(top, canonical)) throw new Error("Quality isolation requires the repository root.");
5198
+ if (await git(canonical, ["status", "--porcelain", "--", ".", ":!.remotearc-goals"])) throw new Error("Quality baseline requires a clean checkout; preserve user edits before starting.");
5199
+ const frontier = await git(canonical, ["rev-parse", "HEAD"]);
5200
+ await fs4.mkdir(directory, { recursive: true });
5201
+ const candidate = await enforcePathPolicy(path4.join(directory, "candidate-0"), policy);
5202
+ await git(canonical, ["worktree", "add", "--detach", candidate, frontier]);
5203
+ state = { version: 1, task_id: id, root: canonical, path: candidate, frontier, generation: 0, operations: {} };
5204
+ } else {
5205
+ const expected = path4.join(directory, "candidate-" + state.generation);
5206
+ if (!samePath(state.path, expected) || !samePath(await fs4.realpath(state.path), expected)) throw new Error("Candidate ownership path changed.");
5207
+ await enforcePathPolicy(state.path, policy);
5208
+ const marker = await fs4.lstat(path4.join(state.path, ".git"));
5209
+ if (!marker.isFile() || marker.isSymbolicLink()) throw new Error("Candidate Git identity changed.");
5210
+ const common = await fs4.realpath(await git(state.path, ["rev-parse", "--path-format=absolute", "--git-common-dir"]));
5211
+ const original = await fs4.realpath(await git(canonical, ["rev-parse", "--path-format=absolute", "--git-common-dir"]));
5212
+ if (!samePath(common, original)) throw new Error("Candidate belongs to another repository.");
5213
+ if (action === "capture") {
5214
+ if (args.expected_frontier !== state.frontier) throw new Error("Accepted checkpoint changed. Read context again.");
5215
+ await git(state.path, ["add", "-A", "--", "."]);
5216
+ const tree = await git(state.path, ["write-tree"]);
5217
+ if (args.expected_tree !== tree) throw new Error("Candidate changed during validation; rerun checks before promoting.");
5218
+ const head = await git(state.path, ["rev-parse", "HEAD"]);
5219
+ const commit = await git(state.path, ["commit-tree", tree, "-p", head, "-m", "Remote Arc accepted task checkpoint " + id]);
5220
+ await git(state.path, ["update-ref", "HEAD", commit, head]);
5221
+ state.frontier = commit;
5222
+ }
5223
+ if (action === "reject") {
5224
+ if (args.expected_frontier !== state.frontier) throw new Error("Accepted checkpoint changed. Read context again.");
5225
+ const candidate = await enforcePathPolicy(path4.join(directory, "candidate-" + (state.generation + 1)), policy);
5226
+ await git(canonical, ["worktree", "add", "--detach", candidate, state.frontier]);
5227
+ state.generation++;
5228
+ state.path = candidate;
5229
+ }
5230
+ }
5231
+ if (action === "fingerprint") {
5232
+ await git(state.path, ["add", "-A", "--", "."]);
5233
+ return { ...result(state), tree: await git(state.path, ["write-tree"]) };
5234
+ }
5235
+ state.operations[operation] = result(state);
5236
+ const keys = Object.keys(state.operations);
5237
+ for (const key of keys.slice(0, -256)) delete state.operations[key];
5238
+ await save(state);
5239
+ return { ...result(state), ...action === "status" ? { git_status: (await git(state.path, ["status", "--porcelain"])).slice(0, 6e3) } : {} };
5240
+ });
5241
+ pending.set(id, next);
5242
+ try {
5243
+ return await next;
5244
+ } finally {
5245
+ if (pending.get(id) === next) pending.delete(id);
5246
+ }
5247
+ }
5248
+
5249
+ // src/index.ts
5250
+ import os4 from "os";
5251
+ import path6 from "path";
5252
+ import fs6 from "fs/promises";
5253
+ import { spawn as spawn4 } from "child_process";
5254
+ import process3 from "process";
5255
+ import { createInterface } from "readline/promises";
5256
+ import { fileURLToPath } from "url";
5257
+
5258
+ // ../../node_modules/.pnpm/ws@8.21.3/node_modules/ws/wrapper.mjs
5259
+ var import_stream = __toESM(require_stream(), 1);
5260
+ var import_extension = __toESM(require_extension(), 1);
5261
+ var import_permessage_deflate = __toESM(require_permessage_deflate(), 1);
5262
+ var import_receiver = __toESM(require_receiver(), 1);
5263
+ var import_sender = __toESM(require_sender(), 1);
5264
+ var import_subprotocol = __toESM(require_subprotocol(), 1);
5265
+ var import_websocket = __toESM(require_websocket(), 1);
5266
+ var import_websocket_server = __toESM(require_websocket_server(), 1);
5267
+ var wrapper_default = import_websocket.default;
5268
+
5269
+ // src/background.ts
5270
+ import os3 from "os";
5271
+ import path5 from "path";
5272
+ import fs5 from "fs/promises";
5273
+ import { spawn as spawn3 } from "child_process";
5274
+ var CONFIG_DIR = path5.join(os3.homedir(), ".remotearc");
5275
+ var AGENT_DIR = path5.join(CONFIG_DIR, "agent");
5276
+ var LOG_DIR = path5.join(CONFIG_DIR, "logs");
5277
+ var AGENT_BUNDLE = path5.join(AGENT_DIR, "remotelink.mjs");
5278
+ var MAC_LABEL = "app.remotearc.agent";
5279
+ var WINDOWS_TASK = "Remote Arc Agent";
5280
+ var LINUX_UNIT = "remotearc-agent.service";
5281
+ async function run2(command, args, options = {}) {
5282
+ return new Promise((resolve, reject) => {
5283
+ const child = spawn3(command, args, {
5284
+ stdio: ["ignore", "pipe", "pipe"],
5285
+ windowsHide: true
5286
+ });
5287
+ let stdout = "";
5288
+ let stderr = "";
5289
+ child.stdout?.on("data", (chunk) => {
5290
+ stdout += chunk.toString();
5291
+ });
5292
+ child.stderr?.on("data", (chunk) => {
5293
+ stderr += chunk.toString();
5294
+ });
5295
+ child.once("error", (error) => {
5296
+ if (options.ignoreFailure) {
5297
+ resolve({ code: 1, stdout, stderr: stderr || error.message });
5298
+ return;
5299
+ }
5300
+ reject(error);
5301
+ });
5302
+ child.once("close", (code) => {
5303
+ const result = { code: code ?? 1, stdout, stderr };
5304
+ if ((code ?? 1) !== 0 && !options.ignoreFailure) {
5305
+ reject(
5306
+ new Error(
5307
+ `${command} exited with ${String(code)}: ${stderr.trim() || stdout.trim() || "unknown error"}`
5308
+ )
5309
+ );
5310
+ return;
5311
+ }
5312
+ resolve(result);
5313
+ });
5314
+ });
5315
+ }
5316
+ function xmlEscape(value) {
5317
+ return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
5318
+ }
5319
+ function psQuote(value) {
5320
+ return "'" + value.replaceAll("'", "''") + "'";
5321
+ }
5322
+ async function ensureBundle(sourcePath) {
5323
+ await fs5.mkdir(AGENT_DIR, { recursive: true });
5324
+ await fs5.mkdir(LOG_DIR, { recursive: true });
5325
+ if (path5.resolve(sourcePath) !== path5.resolve(AGENT_BUNDLE)) {
5326
+ await fs5.copyFile(sourcePath, AGENT_BUNDLE);
5327
+ if (process.platform !== "win32") {
5328
+ await fs5.chmod(AGENT_BUNDLE, 448).catch(() => void 0);
5329
+ }
5330
+ }
5331
+ }
5332
+ function macPlistPath() {
5333
+ return path5.join(os3.homedir(), "Library", "LaunchAgents", MAC_LABEL + ".plist");
5334
+ }
5335
+ function linuxUnitPath() {
5336
+ return path5.join(os3.homedir(), ".config", "systemd", "user", LINUX_UNIT);
5337
+ }
5338
+ async function enableMac(sourcePath, preserveCurrent) {
5339
+ await ensureBundle(sourcePath);
5340
+ const plistPath = macPlistPath();
5341
+ await fs5.mkdir(path5.dirname(plistPath), { recursive: true });
5342
+ const stdoutPath = path5.join(LOG_DIR, "agent.log");
5343
+ const stderrPath = path5.join(LOG_DIR, "agent-error.log");
5344
+ const plist = `<?xml version="1.0" encoding="UTF-8"?>
5345
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
5346
+ <plist version="1.0">
5347
+ <dict>
5348
+ <key>Label</key><string>${MAC_LABEL}</string>
5349
+ <key>ProgramArguments</key>
5350
+ <array>
5351
+ <string>${xmlEscape(process.execPath)}</string>
5352
+ <string>${xmlEscape(AGENT_BUNDLE)}</string>
5353
+ <string>--agent</string>
5354
+ </array>
5355
+ <key>RunAtLoad</key><true/>
5356
+ <key>KeepAlive</key>
5357
+ <dict>
5358
+ <key>SuccessfulExit</key><false/>
5359
+ </dict>
5360
+ <key>ProcessType</key><string>Background</string>
5361
+ <key>ThrottleInterval</key><integer>5</integer>
5362
+ <key>StandardOutPath</key><string>${xmlEscape(stdoutPath)}</string>
5363
+ <key>StandardErrorPath</key><string>${xmlEscape(stderrPath)}</string>
5364
+ </dict>
5365
+ </plist>
5366
+ `;
5367
+ await fs5.writeFile(plistPath, plist, { mode: 384 });
5368
+ const domain = `gui/${process.getuid?.() ?? os3.userInfo().uid}`;
5369
+ const loaded = await run2(
5370
+ "launchctl",
5371
+ ["print", domain + "/" + MAC_LABEL],
5372
+ { ignoreFailure: true }
5373
+ );
5374
+ await run2("launchctl", ["enable", domain + "/" + MAC_LABEL], {
5375
+ ignoreFailure: true
5376
+ });
5377
+ if (!(preserveCurrent && loaded.code === 0)) {
5378
+ await run2("launchctl", ["bootout", domain + "/" + MAC_LABEL], {
5379
+ ignoreFailure: true
5380
+ });
5381
+ await run2("launchctl", ["bootstrap", domain, plistPath]);
5382
+ await run2("launchctl", ["kickstart", "-k", domain + "/" + MAC_LABEL], {
5383
+ ignoreFailure: true
5384
+ });
5385
+ }
5386
+ return backgroundAgentStatus();
5387
+ }
5388
+ async function disableMac(stopCurrent) {
5389
+ const plistPath = macPlistPath();
5390
+ const domain = `gui/${process.getuid?.() ?? os3.userInfo().uid}`;
5391
+ await run2("launchctl", ["disable", domain + "/" + MAC_LABEL], {
5392
+ ignoreFailure: true
5393
+ });
5394
+ await fs5.rm(plistPath, { force: true });
5395
+ if (stopCurrent) {
5396
+ await run2("launchctl", ["bootout", domain + "/" + MAC_LABEL], {
5397
+ ignoreFailure: true
5398
+ });
5399
+ }
5400
+ return backgroundAgentStatus();
5401
+ }
5402
+ async function statusMac() {
5403
+ const plistPath = macPlistPath();
5404
+ const enabled = await fs5.access(plistPath).then(() => true).catch(() => false);
5405
+ const domain = `gui/${process.getuid?.() ?? os3.userInfo().uid}`;
5406
+ const result = await run2(
5407
+ "launchctl",
5408
+ ["print", domain + "/" + MAC_LABEL],
5409
+ { ignoreFailure: true }
5410
+ );
5411
+ return {
5412
+ supported: true,
5413
+ enabled,
5414
+ active: result.code === 0,
5415
+ service: "launchd"
5416
+ };
5417
+ }
5418
+ async function enableLinux(sourcePath, preserveCurrent) {
5419
+ await ensureBundle(sourcePath);
5420
+ const unitPath = linuxUnitPath();
5421
+ await fs5.mkdir(path5.dirname(unitPath), { recursive: true });
5422
+ const unit = `[Unit]
5423
+ Description=Remote Arc background agent
5424
+ After=network-online.target
5425
+ Wants=network-online.target
5426
+
5427
+ [Service]
5428
+ Type=simple
5429
+ ExecStart=${process.execPath} ${AGENT_BUNDLE} --agent
5430
+ Restart=on-failure
5431
+ RestartSec=3
5432
+ Environment=NODE_ENV=production
5433
+
5434
+ [Install]
5435
+ WantedBy=default.target
5436
+ `;
5437
+ await fs5.writeFile(unitPath, unit, { mode: 384 });
5438
+ await run2("systemctl", ["--user", "daemon-reload"]);
5439
+ await run2(
5440
+ "systemctl",
5441
+ preserveCurrent ? ["--user", "enable", LINUX_UNIT] : ["--user", "enable", "--now", LINUX_UNIT]
5442
+ );
5443
+ return backgroundAgentStatus();
5444
+ }
5445
+ async function disableLinux(stopCurrent) {
5446
+ await run2(
5447
+ "systemctl",
5448
+ stopCurrent ? ["--user", "disable", "--now", LINUX_UNIT] : ["--user", "disable", LINUX_UNIT],
5449
+ { ignoreFailure: true }
5450
+ );
5451
+ await fs5.rm(linuxUnitPath(), { force: true });
5452
+ if (stopCurrent) {
5453
+ await run2("systemctl", ["--user", "daemon-reload"], {
5454
+ ignoreFailure: true
5455
+ });
5456
+ }
5457
+ return backgroundAgentStatus();
5458
+ }
5459
+ async function statusLinux() {
5460
+ const enabledResult = await run2(
5461
+ "systemctl",
5462
+ ["--user", "is-enabled", LINUX_UNIT],
5463
+ { ignoreFailure: true }
5464
+ );
5465
+ const activeResult = await run2(
5466
+ "systemctl",
5467
+ ["--user", "is-active", LINUX_UNIT],
5468
+ { ignoreFailure: true }
5469
+ );
5470
+ const supported = enabledResult.stderr.toLowerCase().includes("failed to connect to bus") ? false : true;
5471
+ return {
5472
+ supported,
5473
+ enabled: enabledResult.code === 0,
5474
+ active: activeResult.code === 0,
5475
+ service: supported ? "systemd-user" : "unsupported",
5476
+ detail: supported ? void 0 : "systemd user services are unavailable"
5477
+ };
5478
+ }
5479
+ async function powershell(script, ignoreFailure = false) {
5480
+ return run2(
5481
+ "powershell.exe",
5482
+ ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", script],
5483
+ { ignoreFailure }
5484
+ );
5485
+ }
5486
+ async function enableWindows(sourcePath, preserveCurrent) {
5487
+ await ensureBundle(sourcePath);
5488
+ const args = `"${AGENT_BUNDLE}" --agent`;
5489
+ const script = [
5490
+ `$action = New-ScheduledTaskAction -Execute ${psQuote(process.execPath)} -Argument ${psQuote(args)}`,
5491
+ "$trigger = New-ScheduledTaskTrigger -AtLogOn",
5492
+ "$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable -RestartCount 999 -RestartInterval (New-TimeSpan -Minutes 1)",
5493
+ `Register-ScheduledTask -TaskName ${psQuote(WINDOWS_TASK)} -Action $action -Trigger $trigger -Settings $settings -Description 'Remote Arc background connection' -Force | Out-Null`,
5494
+ ...preserveCurrent ? [] : [`Start-ScheduledTask -TaskName ${psQuote(WINDOWS_TASK)}`]
5495
+ ].join("; ");
5496
+ await powershell(script);
5497
+ return backgroundAgentStatus();
5498
+ }
5499
+ async function disableWindows(stopCurrent) {
5500
+ const commands = [];
5501
+ if (stopCurrent) {
5502
+ commands.push(
5503
+ `Stop-ScheduledTask -TaskName ${psQuote(WINDOWS_TASK)} -ErrorAction SilentlyContinue`
5504
+ );
5505
+ }
5506
+ commands.push(
5507
+ `Unregister-ScheduledTask -TaskName ${psQuote(WINDOWS_TASK)} -Confirm:$false -ErrorAction SilentlyContinue`
5508
+ );
5509
+ await powershell(commands.join("; "), true);
5510
+ return backgroundAgentStatus();
5511
+ }
5512
+ async function statusWindows() {
5513
+ const script = `$task = Get-ScheduledTask -TaskName ${psQuote(WINDOWS_TASK)} -ErrorAction SilentlyContinue; if ($null -eq $task) { exit 3 }; Write-Output $task.State`;
5514
+ const result = await powershell(script, true);
5515
+ return {
5516
+ supported: true,
5517
+ enabled: result.code === 0,
5518
+ active: result.code === 0 && /running/i.test(result.stdout),
5519
+ service: "task-scheduler"
5520
+ };
5521
+ }
5522
+ async function backgroundAgentStatus() {
5523
+ if (process.platform === "darwin") return statusMac();
5524
+ if (process.platform === "win32") return statusWindows();
5525
+ if (process.platform === "linux") return statusLinux();
5526
+ return {
5527
+ supported: false,
5528
+ enabled: false,
5529
+ active: false,
5530
+ service: "unsupported",
5531
+ detail: "unsupported operating system"
5532
+ };
5533
+ }
5534
+ async function enableBackgroundAgent(sourcePath, options = {}) {
5535
+ const preserveCurrent = options.preserveCurrent ?? false;
5536
+ if (process.platform === "darwin") return enableMac(sourcePath, preserveCurrent);
5537
+ if (process.platform === "win32") return enableWindows(sourcePath, preserveCurrent);
5538
+ if (process.platform === "linux") return enableLinux(sourcePath, preserveCurrent);
5539
+ return backgroundAgentStatus();
5540
+ }
5541
+ async function disableBackgroundAgent(options = {}) {
5542
+ const stopCurrent = options.stopCurrent ?? true;
5543
+ if (process.platform === "darwin") return disableMac(stopCurrent);
5544
+ if (process.platform === "win32") return disableWindows(stopCurrent);
5545
+ if (process.platform === "linux") return disableLinux(stopCurrent);
5546
+ return backgroundAgentStatus();
5547
+ }
5548
+
1224
5549
  // src/index.ts
1225
- var VERSION = "0.3.14";
5550
+ var VERSION = "0.4.1";
1226
5551
  var DEFAULT_ORIGIN = "https://mcp.remotearc.app";
1227
- var CONFIG_DIR = path4.join(os3.homedir(), ".remotearc");
1228
- var CONFIG_PATH = path4.join(CONFIG_DIR, "config.json");
1229
- var LEGACY_CONFIG_PATH = path4.join(os3.homedir(), ".remote-link", "config.json");
5552
+ var CONFIG_DIR2 = path6.join(os4.homedir(), ".remotearc");
5553
+ var CONFIG_PATH = path6.join(CONFIG_DIR2, "config.json");
5554
+ var LEGACY_CONFIG_PATH = path6.join(os4.homedir(), ".remote-link", "config.json");
5555
+ var SELF_PATH = fileURLToPath(import.meta.url);
1230
5556
  var RevokedDeviceCredentialError = class extends Error {
1231
5557
  constructor() {
1232
5558
  super("Saved device credential has been revoked.");
@@ -1249,6 +5575,77 @@ async function validateSavedPairing(config) {
1249
5575
  }
1250
5576
  }
1251
5577
  var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
5578
+ var approvalPromptActive = false;
5579
+ async function promptPendingApproval(config) {
5580
+ if (approvalPromptActive || argFlag("--agent") || !process3.stdin.isTTY || !process3.stdout.isTTY) {
5581
+ return;
5582
+ }
5583
+ approvalPromptActive = true;
5584
+ try {
5585
+ const response = await fetch(
5586
+ new URL("/api/device/approvals/pending", config.origin),
5587
+ { headers: { Authorization: "Bearer " + config.deviceToken } }
5588
+ );
5589
+ if (!response.ok) return;
5590
+ const approvals = await response.json();
5591
+ const approval = approvals[0];
5592
+ if (!approval) return;
5593
+ process3.stdout.write("\n");
5594
+ logLine(
5595
+ "warn",
5596
+ `Approval required \xB7 ${bold(approval.tool_name)} \xB7 ${dim(approval.request_id.slice(0, 8))}`
5597
+ );
5598
+ process3.stdout.write(" " + bold(approval.target_path) + "\n");
5599
+ process3.stdout.write(
5600
+ " " + dim(
5601
+ (approval.client_name || approval.client_id?.slice(0, 12) || "AI client") + " \xB7 expires " + new Date(approval.expires_at).toLocaleTimeString()
5602
+ ) + "\n"
5603
+ );
5604
+ const rl = createInterface({ input: process3.stdin, output: process3.stdout });
5605
+ let answer = "";
5606
+ try {
5607
+ answer = (await rl.question(
5608
+ " [1] Allow once [2] Allow 10 min [3] Trust folder [d] Deny [Enter] Later\n > "
5609
+ )).trim().toLowerCase();
5610
+ } finally {
5611
+ rl.close();
5612
+ }
5613
+ const decision = answer === "1" ? "allow_once" : answer === "2" ? "allow_10m" : answer === "3" ? "always_folder" : answer === "d" || answer === "deny" ? "deny" : null;
5614
+ if (!decision) {
5615
+ logLine("info", "Approval left pending \xB7 use Dashboard \u2192 Security anytime.");
5616
+ return;
5617
+ }
5618
+ const decisionResponse = await fetch(
5619
+ new URL(
5620
+ "/api/device/approvals/" + encodeURIComponent(approval.id) + "/decision",
5621
+ config.origin
5622
+ ),
5623
+ {
5624
+ method: "POST",
5625
+ headers: {
5626
+ Authorization: "Bearer " + config.deviceToken,
5627
+ "content-type": "application/json"
5628
+ },
5629
+ body: JSON.stringify({ decision })
5630
+ }
5631
+ );
5632
+ if (!decisionResponse.ok) {
5633
+ const payload = await decisionResponse.json().catch(() => ({}));
5634
+ logLine(
5635
+ "error",
5636
+ "Approval failed \xB7 " + (payload.error || String(decisionResponse.status))
5637
+ );
5638
+ return;
5639
+ }
5640
+ logLine(
5641
+ decision === "deny" ? "warn" : "success",
5642
+ decision === "deny" ? "Approval denied." : decision === "always_folder" ? "Folder added to Trusted Write Locations." : "Temporary write approval granted."
5643
+ );
5644
+ } catch {
5645
+ } finally {
5646
+ approvalPromptActive = false;
5647
+ }
5648
+ }
1252
5649
  var supportsColor = process3.stdout.isTTY && !process3.env.NO_COLOR;
1253
5650
  var paint = (code, value) => supportsColor ? `\x1B[${code}m${value}\x1B[0m` : value;
1254
5651
  var dim = (value) => paint("2", value);
@@ -1290,11 +5687,11 @@ function modeLabel(mode) {
1290
5687
  }
1291
5688
  async function readConfig() {
1292
5689
  try {
1293
- return JSON.parse(await fs4.readFile(CONFIG_PATH, "utf8"));
5690
+ return JSON.parse(await fs6.readFile(CONFIG_PATH, "utf8"));
1294
5691
  } catch {
1295
5692
  try {
1296
5693
  const legacy = JSON.parse(
1297
- await fs4.readFile(LEGACY_CONFIG_PATH, "utf8")
5694
+ await fs6.readFile(LEGACY_CONFIG_PATH, "utf8")
1298
5695
  );
1299
5696
  await writeConfig(legacy);
1300
5697
  logLine("success", "Migrated existing Remote Link pairing to Remote Arc.");
@@ -1305,29 +5702,29 @@ async function readConfig() {
1305
5702
  }
1306
5703
  }
1307
5704
  async function writeConfig(config) {
1308
- await fs4.mkdir(CONFIG_DIR, { recursive: true });
1309
- await fs4.writeFile(CONFIG_PATH, JSON.stringify(config, null, 2) + "\n", {
5705
+ await fs6.mkdir(CONFIG_DIR2, { recursive: true });
5706
+ await fs6.writeFile(CONFIG_PATH, JSON.stringify(config, null, 2) + "\n", {
1310
5707
  mode: 384
1311
5708
  });
1312
5709
  }
1313
5710
  async function resetConfig() {
1314
5711
  await Promise.all([
1315
- fs4.rm(CONFIG_PATH, { force: true }),
1316
- fs4.rm(LEGACY_CONFIG_PATH, { force: true })
5712
+ fs6.rm(CONFIG_PATH, { force: true }),
5713
+ fs6.rm(LEGACY_CONFIG_PATH, { force: true })
1317
5714
  ]);
1318
5715
  logLine("success", "Removed saved device credentials.");
1319
5716
  }
1320
5717
  function openBrowser(url) {
1321
5718
  const command = process3.platform === "win32" ? "cmd" : process3.platform === "darwin" ? "open" : "xdg-open";
1322
5719
  const args = process3.platform === "win32" ? ["/c", "start", "", url] : [url];
1323
- const child = spawn2(command, args, {
5720
+ const child = spawn4(command, args, {
1324
5721
  detached: true,
1325
5722
  stdio: "ignore"
1326
5723
  });
1327
5724
  child.unref();
1328
5725
  }
1329
5726
  async function pair(origin, mode) {
1330
- const deviceName = os3.hostname();
5727
+ const deviceName = os4.hostname();
1331
5728
  const response = await fetch(origin + "/api/device/start", {
1332
5729
  method: "POST",
1333
5730
  headers: { "content-type": "application/json" },
@@ -1335,7 +5732,7 @@ async function pair(origin, mode) {
1335
5732
  device_name: deviceName,
1336
5733
  platform: process3.platform,
1337
5734
  arch: process3.arch,
1338
- hostname: os3.hostname()
5735
+ hostname: os4.hostname()
1339
5736
  })
1340
5737
  });
1341
5738
  if (!response.ok) {
@@ -1409,6 +5806,8 @@ async function connectAgent(config) {
1409
5806
  `Permission profile: ${isLocalSafeMode(config.mode) ? green("safe local cap") : cyan("dashboard-managed")}`
1410
5807
  );
1411
5808
  const tools = await core.tools();
5809
+ const internalTools = ["background_agent_status", "set_background_agent", "set_task_keep_awake", "goal_workspace"];
5810
+ let keepAwake = createTaskKeepAwakeManager();
1412
5811
  logLine("success", `Local tools ready: ${tools.length} exposed`);
1413
5812
  process3.stdout.write(" " + dim(tools.map((tool) => tool.name).join(" \xB7 ")) + "\n");
1414
5813
  try {
@@ -1428,13 +5827,14 @@ async function connectAgent(config) {
1428
5827
  let backoff = 1e3;
1429
5828
  const shutdown = async () => {
1430
5829
  stopped = true;
5830
+ keepAwake.close();
1431
5831
  await core.close().catch(() => void 0);
1432
5832
  };
1433
5833
  process3.on("SIGINT", shutdown);
1434
5834
  process3.on("SIGTERM", shutdown);
1435
5835
  while (!stopped) {
1436
5836
  logLine("event", `Connecting relay ${dim(wsUrl.host)}\u2026`);
1437
- const ws = new WebSocket(wsUrl, {
5837
+ const ws = new wrapper_default(wsUrl, {
1438
5838
  headers: {
1439
5839
  Authorization: "Bearer " + config.deviceToken
1440
5840
  }
@@ -1482,11 +5882,16 @@ async function connectAgent(config) {
1482
5882
  name: config.deviceName,
1483
5883
  platform: process3.platform,
1484
5884
  arch: process3.arch,
1485
- hostname: os3.hostname(),
5885
+ hostname: os4.hostname(),
1486
5886
  agentVersion: VERSION
1487
5887
  },
1488
- tools: tools.map((tool) => tool.name),
1489
- capabilities: ["native_core_v1", "device_policy_v1", "undo_history_v1"]
5888
+ tools: [...tools.map((tool) => tool.name), ...internalTools],
5889
+ capabilities: [
5890
+ "native_core_v1",
5891
+ "device_policy_v1",
5892
+ "undo_history_v1",
5893
+ "background_agent_v1"
5894
+ ]
1490
5895
  })
1491
5896
  );
1492
5897
  logLine("success", `Relay connected \xB7 ${bold(config.deviceName)} \xB7 ${config.mode} mode`);
@@ -1495,9 +5900,18 @@ async function connectAgent(config) {
1495
5900
  process3.stdout.write(" " + dim("Ctrl+C to disconnect") + "\n\n");
1496
5901
  const sendHeartbeat = async () => {
1497
5902
  try {
5903
+ const background = config.backgroundEnabled === void 0 ? null : await backgroundAgentStatus().catch(() => null);
1498
5904
  await fetch(new URL("/api/device/heartbeat", config.origin), {
1499
5905
  method: "POST",
1500
- headers: { Authorization: "Bearer " + config.deviceToken }
5906
+ headers: {
5907
+ Authorization: "Bearer " + config.deviceToken,
5908
+ "content-type": "application/json"
5909
+ },
5910
+ body: JSON.stringify({
5911
+ background_enabled: background?.enabled,
5912
+ background_process: argFlag("--agent"),
5913
+ background_service: background?.service
5914
+ })
1501
5915
  });
1502
5916
  } catch {
1503
5917
  }
@@ -1507,8 +5921,31 @@ async function connectAgent(config) {
1507
5921
  () => void sendHeartbeat(),
1508
5922
  15 * 6e4
1509
5923
  );
5924
+ void promptPendingApproval(config);
5925
+ const approvalTimer = setInterval(
5926
+ () => void promptPendingApproval(config),
5927
+ 4e3
5928
+ );
5929
+ let lastSocketActivity = Date.now();
5930
+ ws.on("pong", () => {
5931
+ lastSocketActivity = Date.now();
5932
+ });
5933
+ const livenessTimer = setInterval(() => {
5934
+ if (ws.readyState !== wrapper_default.OPEN) return;
5935
+ if (Date.now() - lastSocketActivity > 75e3) {
5936
+ logLine("warn", "Relay connection became stale \xB7 reconnecting\u2026");
5937
+ ws.terminate();
5938
+ return;
5939
+ }
5940
+ try {
5941
+ ws.ping();
5942
+ } catch {
5943
+ ws.terminate();
5944
+ }
5945
+ }, 3e4);
1510
5946
  await new Promise((resolve) => {
1511
5947
  ws.on("message", async (raw) => {
5948
+ lastSocketActivity = Date.now();
1512
5949
  let message;
1513
5950
  try {
1514
5951
  message = JSON.parse(raw.toString());
@@ -1521,11 +5958,50 @@ async function connectAgent(config) {
1521
5958
  const callStarted = Date.now();
1522
5959
  logLine("event", `tool.call ${bold(message.tool)} \xB7 ${dim(message.id.slice(0, 8))}`);
1523
5960
  try {
1524
- const result = await core.call(
1525
- message.tool,
1526
- message.arguments || {},
1527
- message.policy
1528
- );
5961
+ let result;
5962
+ let exitAfterResponse = false;
5963
+ if (message.tool === "goal_workspace") {
5964
+ if (!(await core.tools()).some((tool) => tool.name === "start_process")) throw new Error("Goal checkpoints require terminal mode.");
5965
+ result = await goalWorkspace(message.arguments || {}, message.policy);
5966
+ } else if (message.tool === "set_task_keep_awake") {
5967
+ result = await keepAwake.set(String(message.arguments?.task_id || ""), Number(message.arguments?.seconds || 0));
5968
+ } else if (message.tool === "background_agent_status") {
5969
+ const status = await backgroundAgentStatus();
5970
+ result = {
5971
+ ...status,
5972
+ enabled: status.enabled,
5973
+ desired_enabled: config.backgroundEnabled ?? null
5974
+ };
5975
+ } else if (message.tool === "set_background_agent") {
5976
+ const enabled = message.arguments?.enabled;
5977
+ if (typeof enabled !== "boolean") {
5978
+ throw new Error("enabled must be a boolean");
5979
+ }
5980
+ config.backgroundEnabled = enabled;
5981
+ await writeConfig(config);
5982
+ if (enabled) {
5983
+ const current = await backgroundAgentStatus();
5984
+ result = current.enabled ? { ...current, desired_enabled: true } : {
5985
+ ...await enableBackgroundAgent(SELF_PATH, {
5986
+ preserveCurrent: argFlag("--agent")
5987
+ }),
5988
+ desired_enabled: true
5989
+ };
5990
+ exitAfterResponse = !argFlag("--agent");
5991
+ } else {
5992
+ result = {
5993
+ ...await disableBackgroundAgent({ stopCurrent: false }),
5994
+ desired_enabled: false
5995
+ };
5996
+ exitAfterResponse = false;
5997
+ }
5998
+ } else {
5999
+ result = await core.call(
6000
+ message.tool,
6001
+ message.arguments || {},
6002
+ message.policy
6003
+ );
6004
+ }
1529
6005
  logLine("success", `tool.done ${message.tool} \xB7 ${Date.now() - callStarted}ms`);
1530
6006
  ws.send(
1531
6007
  JSON.stringify({
@@ -1534,6 +6010,9 @@ async function connectAgent(config) {
1534
6010
  result
1535
6011
  })
1536
6012
  );
6013
+ if (exitAfterResponse) {
6014
+ setTimeout(() => process3.exit(0), 500);
6015
+ }
1537
6016
  } catch (error) {
1538
6017
  logLine("error", `tool.fail ${message.tool} \xB7 ${error instanceof Error ? error.message : String(error)}`);
1539
6018
  ws.send(
@@ -1549,6 +6028,8 @@ async function connectAgent(config) {
1549
6028
  ws.once("error", resolve);
1550
6029
  });
1551
6030
  clearInterval(heartbeatTimer);
6031
+ clearInterval(approvalTimer);
6032
+ clearInterval(livenessTimer);
1552
6033
  } catch (error) {
1553
6034
  if (error instanceof RevokedDeviceCredentialError) {
1554
6035
  logLine("warn", error.message);
@@ -1562,15 +6043,17 @@ async function connectAgent(config) {
1562
6043
  "Relay connection failed: " + (error instanceof Error ? error.message : String(error))
1563
6044
  );
1564
6045
  } finally {
6046
+ keepAwake.close();
6047
+ if (!stopped) keepAwake = createTaskKeepAwakeManager();
1565
6048
  ws.removeAllListeners("message");
1566
6049
  ws.removeAllListeners("open");
1567
6050
  ws.removeAllListeners("unexpected-response");
1568
6051
  ws.removeAllListeners("close");
1569
6052
  ws.removeAllListeners("error");
1570
6053
  ws.on("error", absorbSocketError);
1571
- if (ws.readyState === WebSocket.OPEN) {
6054
+ if (ws.readyState === wrapper_default.OPEN) {
1572
6055
  ws.close();
1573
- } else if (ws.readyState === WebSocket.CONNECTING) {
6056
+ } else if (ws.readyState === wrapper_default.CONNECTING) {
1574
6057
  ws.terminate();
1575
6058
  }
1576
6059
  }
@@ -1599,10 +6082,13 @@ async function main() {
1599
6082
  " npx remotelink",
1600
6083
  "",
1601
6084
  "Options:",
1602
- " --safe Hard local read-only cap; dashboard cannot enable write tools",
1603
- " --developer Legacy alias for dashboard-managed capabilities",
1604
- " --reset Remove this computer's saved pairing",
1605
- " --version Print CLI version",
6085
+ " --safe Hard local read-only cap; dashboard cannot enable write tools",
6086
+ " --developer Legacy alias for dashboard-managed capabilities",
6087
+ " --foreground Keep this session attached to the terminal instead of background mode",
6088
+ " --background Enable the login background agent",
6089
+ " --no-background Disable login background mode and run this session in the foreground",
6090
+ " --reset Remove local pairing and background-agent registration",
6091
+ " --version Print CLI version",
1606
6092
  " --help Show this help",
1607
6093
  ""
1608
6094
  ].join("\n")
@@ -1614,10 +6100,15 @@ async function main() {
1614
6100
  return;
1615
6101
  }
1616
6102
  if (argFlag("--reset")) {
6103
+ await disableBackgroundAgent({ stopCurrent: true }).catch(() => void 0);
1617
6104
  await resetConfig();
1618
6105
  return;
1619
6106
  }
1620
6107
  const origin = process3.env.REMOTEARC_ORIGIN || process3.env.REMOTE_LINK_ORIGIN || process3.argv.find((value) => value.startsWith("--origin="))?.slice(9) || DEFAULT_ORIGIN;
6108
+ const agentMode = argFlag("--agent");
6109
+ const foregroundMode = argFlag("--foreground");
6110
+ const disableBackground = argFlag("--no-background");
6111
+ const enableBackground = argFlag("--background");
1621
6112
  let config = await readConfig();
1622
6113
  while (true) {
1623
6114
  if (config && ["https://remote.samyao.me", "https://remotearc.app"].includes(config.origin)) {
@@ -1626,12 +6117,57 @@ async function main() {
1626
6117
  logLine("info", "Migrated relay origin to " + DEFAULT_ORIGIN);
1627
6118
  }
1628
6119
  if (!config) {
6120
+ if (agentMode) return;
1629
6121
  config = await pair(origin, selectedMode());
1630
6122
  } else if (argFlag("--safe") || argFlag("--developer")) {
1631
6123
  config.mode = argFlag("--safe") ? "safe" : "managed";
1632
6124
  await writeConfig(config);
1633
6125
  }
6126
+ if (disableBackground) {
6127
+ config.backgroundEnabled = false;
6128
+ await writeConfig(config);
6129
+ await disableBackgroundAgent({ stopCurrent: true }).catch(() => void 0);
6130
+ } else if (enableBackground) {
6131
+ config.backgroundEnabled = true;
6132
+ await writeConfig(config);
6133
+ }
1634
6134
  logLine("info", `Using paired device identity ${dim(config.deviceId.slice(0, 8))}\u2026`);
6135
+ if (agentMode) {
6136
+ if (config.backgroundEnabled !== true) return;
6137
+ const result2 = await connectAgent(config);
6138
+ if (result2 !== "rePair") return;
6139
+ return;
6140
+ }
6141
+ if (!foregroundMode && config.backgroundEnabled === true) {
6142
+ try {
6143
+ const status = await enableBackgroundAgent(SELF_PATH);
6144
+ if (status.supported && status.enabled) {
6145
+ banner();
6146
+ logLine("success", "Background connection enabled.");
6147
+ logLine(
6148
+ "info",
6149
+ `Service: ${status.service} \xB7 starts automatically at login`
6150
+ );
6151
+ logLine(
6152
+ "info",
6153
+ "Use the Remote Arc dashboard or --no-background to disable it."
6154
+ );
6155
+ return;
6156
+ }
6157
+ logLine("warn", status.detail || "Background services are unavailable on this system.");
6158
+ } catch (error) {
6159
+ logLine(
6160
+ "warn",
6161
+ "Could not enable background mode; keeping this terminal session connected: " + (error instanceof Error ? error.message : String(error))
6162
+ );
6163
+ }
6164
+ }
6165
+ if (config.backgroundEnabled === void 0) {
6166
+ logLine(
6167
+ "info",
6168
+ "Background connection is not configured yet \xB7 finish setup in the browser or Devices."
6169
+ );
6170
+ }
1635
6171
  const result = await connectAgent(config);
1636
6172
  if (result !== "rePair") return;
1637
6173
  config = null;