@fancyboi999/open-tag-daemon 0.1.0

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/cli.mjs ADDED
@@ -0,0 +1,4857 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire as __ctr } from 'node:module'; const require = __ctr(import.meta.url);
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
10
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
11
+ }) : x)(function(x) {
12
+ if (typeof require !== "undefined") return require.apply(this, arguments);
13
+ throw Error('Dynamic require of "' + x + '" is not supported');
14
+ });
15
+ var __commonJS = (cb, mod) => function __require2() {
16
+ try {
17
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
18
+ } catch (e) {
19
+ throw mod = 0, e;
20
+ }
21
+ };
22
+ var __copyProps = (to, from, except, desc) => {
23
+ if (from && typeof from === "object" || typeof from === "function") {
24
+ for (let key of __getOwnPropNames(from))
25
+ if (!__hasOwnProp.call(to, key) && key !== except)
26
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
27
+ }
28
+ return to;
29
+ };
30
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
31
+ // If the importer is in node compatibility mode or this is not an ESM
32
+ // file that has been converted to a CommonJS file using a Babel-
33
+ // compatible transform (i.e. "__esModule" has not been set), then set
34
+ // "default" to the CommonJS "module.exports" for node compatibility.
35
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
36
+ mod
37
+ ));
38
+
39
+ // node_modules/ws/lib/constants.js
40
+ var require_constants = __commonJS({
41
+ "node_modules/ws/lib/constants.js"(exports, module) {
42
+ "use strict";
43
+ var BINARY_TYPES = ["nodebuffer", "arraybuffer", "fragments"];
44
+ var hasBlob = typeof Blob !== "undefined";
45
+ if (hasBlob) BINARY_TYPES.push("blob");
46
+ module.exports = {
47
+ BINARY_TYPES,
48
+ CLOSE_TIMEOUT: 3e4,
49
+ EMPTY_BUFFER: Buffer.alloc(0),
50
+ GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
51
+ hasBlob,
52
+ kForOnEventAttribute: /* @__PURE__ */ Symbol("kIsForOnEventAttribute"),
53
+ kListener: /* @__PURE__ */ Symbol("kListener"),
54
+ kStatusCode: /* @__PURE__ */ Symbol("status-code"),
55
+ kWebSocket: /* @__PURE__ */ Symbol("websocket"),
56
+ NOOP: () => {
57
+ }
58
+ };
59
+ }
60
+ });
61
+
62
+ // node_modules/ws/lib/buffer-util.js
63
+ var require_buffer_util = __commonJS({
64
+ "node_modules/ws/lib/buffer-util.js"(exports, module) {
65
+ "use strict";
66
+ var { EMPTY_BUFFER } = require_constants();
67
+ var FastBuffer = Buffer[Symbol.species];
68
+ function concat(list, totalLength) {
69
+ if (list.length === 0) return EMPTY_BUFFER;
70
+ if (list.length === 1) return list[0];
71
+ const target = Buffer.allocUnsafe(totalLength);
72
+ let offset = 0;
73
+ for (let i = 0; i < list.length; i++) {
74
+ const buf = list[i];
75
+ target.set(buf, offset);
76
+ offset += buf.length;
77
+ }
78
+ if (offset < totalLength) {
79
+ return new FastBuffer(target.buffer, target.byteOffset, offset);
80
+ }
81
+ return target;
82
+ }
83
+ function _mask(source, mask, output, offset, length) {
84
+ for (let i = 0; i < length; i++) {
85
+ output[offset + i] = source[i] ^ mask[i & 3];
86
+ }
87
+ }
88
+ function _unmask(buffer, mask) {
89
+ for (let i = 0; i < buffer.length; i++) {
90
+ buffer[i] ^= mask[i & 3];
91
+ }
92
+ }
93
+ function toArrayBuffer(buf) {
94
+ if (buf.length === buf.buffer.byteLength) {
95
+ return buf.buffer;
96
+ }
97
+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);
98
+ }
99
+ function toBuffer(data) {
100
+ toBuffer.readOnly = true;
101
+ if (Buffer.isBuffer(data)) return data;
102
+ let buf;
103
+ if (data instanceof ArrayBuffer) {
104
+ buf = new FastBuffer(data);
105
+ } else if (ArrayBuffer.isView(data)) {
106
+ buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);
107
+ } else {
108
+ buf = Buffer.from(data);
109
+ toBuffer.readOnly = false;
110
+ }
111
+ return buf;
112
+ }
113
+ module.exports = {
114
+ concat,
115
+ mask: _mask,
116
+ toArrayBuffer,
117
+ toBuffer,
118
+ unmask: _unmask
119
+ };
120
+ if (!process.env.WS_NO_BUFFER_UTIL) {
121
+ try {
122
+ const bufferUtil = __require("bufferutil");
123
+ module.exports.mask = function(source, mask, output, offset, length) {
124
+ if (length < 48) _mask(source, mask, output, offset, length);
125
+ else bufferUtil.mask(source, mask, output, offset, length);
126
+ };
127
+ module.exports.unmask = function(buffer, mask) {
128
+ if (buffer.length < 32) _unmask(buffer, mask);
129
+ else bufferUtil.unmask(buffer, mask);
130
+ };
131
+ } catch (e) {
132
+ }
133
+ }
134
+ }
135
+ });
136
+
137
+ // node_modules/ws/lib/limiter.js
138
+ var require_limiter = __commonJS({
139
+ "node_modules/ws/lib/limiter.js"(exports, module) {
140
+ "use strict";
141
+ var kDone = /* @__PURE__ */ Symbol("kDone");
142
+ var kRun = /* @__PURE__ */ Symbol("kRun");
143
+ var Limiter = class {
144
+ /**
145
+ * Creates a new `Limiter`.
146
+ *
147
+ * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed
148
+ * to run concurrently
149
+ */
150
+ constructor(concurrency) {
151
+ this[kDone] = () => {
152
+ this.pending--;
153
+ this[kRun]();
154
+ };
155
+ this.concurrency = concurrency || Infinity;
156
+ this.jobs = [];
157
+ this.pending = 0;
158
+ }
159
+ /**
160
+ * Adds a job to the queue.
161
+ *
162
+ * @param {Function} job The job to run
163
+ * @public
164
+ */
165
+ add(job) {
166
+ this.jobs.push(job);
167
+ this[kRun]();
168
+ }
169
+ /**
170
+ * Removes a job from the queue and runs it if possible.
171
+ *
172
+ * @private
173
+ */
174
+ [kRun]() {
175
+ if (this.pending === this.concurrency) return;
176
+ if (this.jobs.length) {
177
+ const job = this.jobs.shift();
178
+ this.pending++;
179
+ job(this[kDone]);
180
+ }
181
+ }
182
+ };
183
+ module.exports = Limiter;
184
+ }
185
+ });
186
+
187
+ // node_modules/ws/lib/permessage-deflate.js
188
+ var require_permessage_deflate = __commonJS({
189
+ "node_modules/ws/lib/permessage-deflate.js"(exports, module) {
190
+ "use strict";
191
+ var zlib = __require("zlib");
192
+ var bufferUtil = require_buffer_util();
193
+ var Limiter = require_limiter();
194
+ var { kStatusCode } = require_constants();
195
+ var FastBuffer = Buffer[Symbol.species];
196
+ var TRAILER = Buffer.from([0, 0, 255, 255]);
197
+ var kPerMessageDeflate = /* @__PURE__ */ Symbol("permessage-deflate");
198
+ var kTotalLength = /* @__PURE__ */ Symbol("total-length");
199
+ var kCallback = /* @__PURE__ */ Symbol("callback");
200
+ var kBuffers = /* @__PURE__ */ Symbol("buffers");
201
+ var kError = /* @__PURE__ */ Symbol("error");
202
+ var zlibLimiter;
203
+ var PerMessageDeflate2 = class {
204
+ /**
205
+ * Creates a PerMessageDeflate instance.
206
+ *
207
+ * @param {Object} [options] Configuration options
208
+ * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support
209
+ * for, or request, a custom client window size
210
+ * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/
211
+ * acknowledge disabling of client context takeover
212
+ * @param {Number} [options.concurrencyLimit=10] The number of concurrent
213
+ * calls to zlib
214
+ * @param {Boolean} [options.isServer=false] Create the instance in either
215
+ * server or client mode
216
+ * @param {Number} [options.maxPayload=0] The maximum allowed message length
217
+ * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the
218
+ * use of a custom server window size
219
+ * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept
220
+ * disabling of server context takeover
221
+ * @param {Number} [options.threshold=1024] Size (in bytes) below which
222
+ * messages should not be compressed if context takeover is disabled
223
+ * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on
224
+ * deflate
225
+ * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on
226
+ * inflate
227
+ */
228
+ constructor(options) {
229
+ this._options = options || {};
230
+ this._threshold = this._options.threshold !== void 0 ? this._options.threshold : 1024;
231
+ this._maxPayload = this._options.maxPayload | 0;
232
+ this._isServer = !!this._options.isServer;
233
+ this._deflate = null;
234
+ this._inflate = null;
235
+ this.params = null;
236
+ if (!zlibLimiter) {
237
+ const concurrency = this._options.concurrencyLimit !== void 0 ? this._options.concurrencyLimit : 10;
238
+ zlibLimiter = new Limiter(concurrency);
239
+ }
240
+ }
241
+ /**
242
+ * @type {String}
243
+ */
244
+ static get extensionName() {
245
+ return "permessage-deflate";
246
+ }
247
+ /**
248
+ * Create an extension negotiation offer.
249
+ *
250
+ * @return {Object} Extension parameters
251
+ * @public
252
+ */
253
+ offer() {
254
+ const params = {};
255
+ if (this._options.serverNoContextTakeover) {
256
+ params.server_no_context_takeover = true;
257
+ }
258
+ if (this._options.clientNoContextTakeover) {
259
+ params.client_no_context_takeover = true;
260
+ }
261
+ if (this._options.serverMaxWindowBits) {
262
+ params.server_max_window_bits = this._options.serverMaxWindowBits;
263
+ }
264
+ if (this._options.clientMaxWindowBits) {
265
+ params.client_max_window_bits = this._options.clientMaxWindowBits;
266
+ } else if (this._options.clientMaxWindowBits == null) {
267
+ params.client_max_window_bits = true;
268
+ }
269
+ return params;
270
+ }
271
+ /**
272
+ * Accept an extension negotiation offer/response.
273
+ *
274
+ * @param {Array} configurations The extension negotiation offers/reponse
275
+ * @return {Object} Accepted configuration
276
+ * @public
277
+ */
278
+ accept(configurations) {
279
+ configurations = this.normalizeParams(configurations);
280
+ this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations);
281
+ return this.params;
282
+ }
283
+ /**
284
+ * Releases all resources used by the extension.
285
+ *
286
+ * @public
287
+ */
288
+ cleanup() {
289
+ if (this._inflate) {
290
+ this._inflate.close();
291
+ this._inflate = null;
292
+ }
293
+ if (this._deflate) {
294
+ const callback = this._deflate[kCallback];
295
+ this._deflate.close();
296
+ this._deflate = null;
297
+ if (callback) {
298
+ callback(
299
+ new Error(
300
+ "The deflate stream was closed while data was being processed"
301
+ )
302
+ );
303
+ }
304
+ }
305
+ }
306
+ /**
307
+ * Accept an extension negotiation offer.
308
+ *
309
+ * @param {Array} offers The extension negotiation offers
310
+ * @return {Object} Accepted configuration
311
+ * @private
312
+ */
313
+ acceptAsServer(offers) {
314
+ const opts = this._options;
315
+ const accepted = offers.find((params) => {
316
+ if (opts.serverNoContextTakeover === false && params.server_no_context_takeover || params.server_max_window_bits && (opts.serverMaxWindowBits === false || typeof opts.serverMaxWindowBits === "number" && opts.serverMaxWindowBits > params.server_max_window_bits) || typeof opts.clientMaxWindowBits === "number" && !params.client_max_window_bits) {
317
+ return false;
318
+ }
319
+ return true;
320
+ });
321
+ if (!accepted) {
322
+ throw new Error("None of the extension offers can be accepted");
323
+ }
324
+ if (opts.serverNoContextTakeover) {
325
+ accepted.server_no_context_takeover = true;
326
+ }
327
+ if (opts.clientNoContextTakeover) {
328
+ accepted.client_no_context_takeover = true;
329
+ }
330
+ if (typeof opts.serverMaxWindowBits === "number") {
331
+ accepted.server_max_window_bits = opts.serverMaxWindowBits;
332
+ }
333
+ if (typeof opts.clientMaxWindowBits === "number") {
334
+ accepted.client_max_window_bits = opts.clientMaxWindowBits;
335
+ } else if (accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false) {
336
+ delete accepted.client_max_window_bits;
337
+ }
338
+ return accepted;
339
+ }
340
+ /**
341
+ * Accept the extension negotiation response.
342
+ *
343
+ * @param {Array} response The extension negotiation response
344
+ * @return {Object} Accepted configuration
345
+ * @private
346
+ */
347
+ acceptAsClient(response) {
348
+ const params = response[0];
349
+ if (this._options.clientNoContextTakeover === false && params.client_no_context_takeover) {
350
+ throw new Error('Unexpected parameter "client_no_context_takeover"');
351
+ }
352
+ if (!params.client_max_window_bits) {
353
+ if (typeof this._options.clientMaxWindowBits === "number") {
354
+ params.client_max_window_bits = this._options.clientMaxWindowBits;
355
+ }
356
+ } else if (this._options.clientMaxWindowBits === false || typeof this._options.clientMaxWindowBits === "number" && params.client_max_window_bits > this._options.clientMaxWindowBits) {
357
+ throw new Error(
358
+ 'Unexpected or invalid parameter "client_max_window_bits"'
359
+ );
360
+ }
361
+ return params;
362
+ }
363
+ /**
364
+ * Normalize parameters.
365
+ *
366
+ * @param {Array} configurations The extension negotiation offers/reponse
367
+ * @return {Array} The offers/response with normalized parameters
368
+ * @private
369
+ */
370
+ normalizeParams(configurations) {
371
+ configurations.forEach((params) => {
372
+ Object.keys(params).forEach((key) => {
373
+ let value = params[key];
374
+ if (value.length > 1) {
375
+ throw new Error(`Parameter "${key}" must have only a single value`);
376
+ }
377
+ value = value[0];
378
+ if (key === "client_max_window_bits") {
379
+ if (value !== true) {
380
+ const num = +value;
381
+ if (!Number.isInteger(num) || num < 8 || num > 15) {
382
+ throw new TypeError(
383
+ `Invalid value for parameter "${key}": ${value}`
384
+ );
385
+ }
386
+ value = num;
387
+ } else if (!this._isServer) {
388
+ throw new TypeError(
389
+ `Invalid value for parameter "${key}": ${value}`
390
+ );
391
+ }
392
+ } else if (key === "server_max_window_bits") {
393
+ const num = +value;
394
+ if (!Number.isInteger(num) || num < 8 || num > 15) {
395
+ throw new TypeError(
396
+ `Invalid value for parameter "${key}": ${value}`
397
+ );
398
+ }
399
+ value = num;
400
+ } else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") {
401
+ if (value !== true) {
402
+ throw new TypeError(
403
+ `Invalid value for parameter "${key}": ${value}`
404
+ );
405
+ }
406
+ } else {
407
+ throw new Error(`Unknown parameter "${key}"`);
408
+ }
409
+ params[key] = value;
410
+ });
411
+ });
412
+ return configurations;
413
+ }
414
+ /**
415
+ * Decompress data. Concurrency limited.
416
+ *
417
+ * @param {Buffer} data Compressed data
418
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
419
+ * @param {Function} callback Callback
420
+ * @public
421
+ */
422
+ decompress(data, fin, callback) {
423
+ zlibLimiter.add((done) => {
424
+ this._decompress(data, fin, (err, result) => {
425
+ done();
426
+ callback(err, result);
427
+ });
428
+ });
429
+ }
430
+ /**
431
+ * Compress data. Concurrency limited.
432
+ *
433
+ * @param {(Buffer|String)} data Data to compress
434
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
435
+ * @param {Function} callback Callback
436
+ * @public
437
+ */
438
+ compress(data, fin, callback) {
439
+ zlibLimiter.add((done) => {
440
+ this._compress(data, fin, (err, result) => {
441
+ done();
442
+ callback(err, result);
443
+ });
444
+ });
445
+ }
446
+ /**
447
+ * Decompress data.
448
+ *
449
+ * @param {Buffer} data Compressed data
450
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
451
+ * @param {Function} callback Callback
452
+ * @private
453
+ */
454
+ _decompress(data, fin, callback) {
455
+ const endpoint = this._isServer ? "client" : "server";
456
+ if (!this._inflate) {
457
+ const key = `${endpoint}_max_window_bits`;
458
+ const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
459
+ this._inflate = zlib.createInflateRaw({
460
+ ...this._options.zlibInflateOptions,
461
+ windowBits
462
+ });
463
+ this._inflate[kPerMessageDeflate] = this;
464
+ this._inflate[kTotalLength] = 0;
465
+ this._inflate[kBuffers] = [];
466
+ this._inflate.on("error", inflateOnError);
467
+ this._inflate.on("data", inflateOnData);
468
+ }
469
+ this._inflate[kCallback] = callback;
470
+ this._inflate.write(data);
471
+ if (fin) this._inflate.write(TRAILER);
472
+ this._inflate.flush(() => {
473
+ const err = this._inflate[kError];
474
+ if (err) {
475
+ this._inflate.close();
476
+ this._inflate = null;
477
+ callback(err);
478
+ return;
479
+ }
480
+ const data2 = bufferUtil.concat(
481
+ this._inflate[kBuffers],
482
+ this._inflate[kTotalLength]
483
+ );
484
+ if (this._inflate._readableState.endEmitted) {
485
+ this._inflate.close();
486
+ this._inflate = null;
487
+ } else {
488
+ this._inflate[kTotalLength] = 0;
489
+ this._inflate[kBuffers] = [];
490
+ if (fin && this.params[`${endpoint}_no_context_takeover`]) {
491
+ this._inflate.reset();
492
+ }
493
+ }
494
+ callback(null, data2);
495
+ });
496
+ }
497
+ /**
498
+ * Compress data.
499
+ *
500
+ * @param {(Buffer|String)} data Data to compress
501
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
502
+ * @param {Function} callback Callback
503
+ * @private
504
+ */
505
+ _compress(data, fin, callback) {
506
+ const endpoint = this._isServer ? "server" : "client";
507
+ if (!this._deflate) {
508
+ const key = `${endpoint}_max_window_bits`;
509
+ const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
510
+ this._deflate = zlib.createDeflateRaw({
511
+ ...this._options.zlibDeflateOptions,
512
+ windowBits
513
+ });
514
+ this._deflate[kTotalLength] = 0;
515
+ this._deflate[kBuffers] = [];
516
+ this._deflate.on("data", deflateOnData);
517
+ }
518
+ this._deflate[kCallback] = callback;
519
+ this._deflate.write(data);
520
+ this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {
521
+ if (!this._deflate) {
522
+ return;
523
+ }
524
+ let data2 = bufferUtil.concat(
525
+ this._deflate[kBuffers],
526
+ this._deflate[kTotalLength]
527
+ );
528
+ if (fin) {
529
+ data2 = new FastBuffer(data2.buffer, data2.byteOffset, data2.length - 4);
530
+ }
531
+ this._deflate[kCallback] = null;
532
+ this._deflate[kTotalLength] = 0;
533
+ this._deflate[kBuffers] = [];
534
+ if (fin && this.params[`${endpoint}_no_context_takeover`]) {
535
+ this._deflate.reset();
536
+ }
537
+ callback(null, data2);
538
+ });
539
+ }
540
+ };
541
+ module.exports = PerMessageDeflate2;
542
+ function deflateOnData(chunk) {
543
+ this[kBuffers].push(chunk);
544
+ this[kTotalLength] += chunk.length;
545
+ }
546
+ function inflateOnData(chunk) {
547
+ this[kTotalLength] += chunk.length;
548
+ if (this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) {
549
+ this[kBuffers].push(chunk);
550
+ return;
551
+ }
552
+ this[kError] = new RangeError("Max payload size exceeded");
553
+ this[kError].code = "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH";
554
+ this[kError][kStatusCode] = 1009;
555
+ this.removeListener("data", inflateOnData);
556
+ this.reset();
557
+ }
558
+ function inflateOnError(err) {
559
+ this[kPerMessageDeflate]._inflate = null;
560
+ if (this[kError]) {
561
+ this[kCallback](this[kError]);
562
+ return;
563
+ }
564
+ err[kStatusCode] = 1007;
565
+ this[kCallback](err);
566
+ }
567
+ }
568
+ });
569
+
570
+ // node_modules/ws/lib/validation.js
571
+ var require_validation = __commonJS({
572
+ "node_modules/ws/lib/validation.js"(exports, module) {
573
+ "use strict";
574
+ var { isUtf8 } = __require("buffer");
575
+ var { hasBlob } = require_constants();
576
+ var tokenChars = [
577
+ 0,
578
+ 0,
579
+ 0,
580
+ 0,
581
+ 0,
582
+ 0,
583
+ 0,
584
+ 0,
585
+ 0,
586
+ 0,
587
+ 0,
588
+ 0,
589
+ 0,
590
+ 0,
591
+ 0,
592
+ 0,
593
+ // 0 - 15
594
+ 0,
595
+ 0,
596
+ 0,
597
+ 0,
598
+ 0,
599
+ 0,
600
+ 0,
601
+ 0,
602
+ 0,
603
+ 0,
604
+ 0,
605
+ 0,
606
+ 0,
607
+ 0,
608
+ 0,
609
+ 0,
610
+ // 16 - 31
611
+ 0,
612
+ 1,
613
+ 0,
614
+ 1,
615
+ 1,
616
+ 1,
617
+ 1,
618
+ 1,
619
+ 0,
620
+ 0,
621
+ 1,
622
+ 1,
623
+ 0,
624
+ 1,
625
+ 1,
626
+ 0,
627
+ // 32 - 47
628
+ 1,
629
+ 1,
630
+ 1,
631
+ 1,
632
+ 1,
633
+ 1,
634
+ 1,
635
+ 1,
636
+ 1,
637
+ 1,
638
+ 0,
639
+ 0,
640
+ 0,
641
+ 0,
642
+ 0,
643
+ 0,
644
+ // 48 - 63
645
+ 0,
646
+ 1,
647
+ 1,
648
+ 1,
649
+ 1,
650
+ 1,
651
+ 1,
652
+ 1,
653
+ 1,
654
+ 1,
655
+ 1,
656
+ 1,
657
+ 1,
658
+ 1,
659
+ 1,
660
+ 1,
661
+ // 64 - 79
662
+ 1,
663
+ 1,
664
+ 1,
665
+ 1,
666
+ 1,
667
+ 1,
668
+ 1,
669
+ 1,
670
+ 1,
671
+ 1,
672
+ 1,
673
+ 0,
674
+ 0,
675
+ 0,
676
+ 1,
677
+ 1,
678
+ // 80 - 95
679
+ 1,
680
+ 1,
681
+ 1,
682
+ 1,
683
+ 1,
684
+ 1,
685
+ 1,
686
+ 1,
687
+ 1,
688
+ 1,
689
+ 1,
690
+ 1,
691
+ 1,
692
+ 1,
693
+ 1,
694
+ 1,
695
+ // 96 - 111
696
+ 1,
697
+ 1,
698
+ 1,
699
+ 1,
700
+ 1,
701
+ 1,
702
+ 1,
703
+ 1,
704
+ 1,
705
+ 1,
706
+ 1,
707
+ 0,
708
+ 1,
709
+ 0,
710
+ 1,
711
+ 0
712
+ // 112 - 127
713
+ ];
714
+ function isValidStatusCode(code) {
715
+ return code >= 1e3 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006 || code >= 3e3 && code <= 4999;
716
+ }
717
+ function _isValidUTF8(buf) {
718
+ const len = buf.length;
719
+ let i = 0;
720
+ while (i < len) {
721
+ if ((buf[i] & 128) === 0) {
722
+ i++;
723
+ } else if ((buf[i] & 224) === 192) {
724
+ if (i + 1 === len || (buf[i + 1] & 192) !== 128 || (buf[i] & 254) === 192) {
725
+ return false;
726
+ }
727
+ i += 2;
728
+ } else if ((buf[i] & 240) === 224) {
729
+ if (i + 2 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || buf[i] === 224 && (buf[i + 1] & 224) === 128 || // Overlong
730
+ buf[i] === 237 && (buf[i + 1] & 224) === 160) {
731
+ return false;
732
+ }
733
+ i += 3;
734
+ } else if ((buf[i] & 248) === 240) {
735
+ 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
736
+ buf[i] === 244 && buf[i + 1] > 143 || buf[i] > 244) {
737
+ return false;
738
+ }
739
+ i += 4;
740
+ } else {
741
+ return false;
742
+ }
743
+ }
744
+ return true;
745
+ }
746
+ function isBlob(value) {
747
+ 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");
748
+ }
749
+ module.exports = {
750
+ isBlob,
751
+ isValidStatusCode,
752
+ isValidUTF8: _isValidUTF8,
753
+ tokenChars
754
+ };
755
+ if (isUtf8) {
756
+ module.exports.isValidUTF8 = function(buf) {
757
+ return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);
758
+ };
759
+ } else if (!process.env.WS_NO_UTF_8_VALIDATE) {
760
+ try {
761
+ const isValidUTF8 = __require("utf-8-validate");
762
+ module.exports.isValidUTF8 = function(buf) {
763
+ return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);
764
+ };
765
+ } catch (e) {
766
+ }
767
+ }
768
+ }
769
+ });
770
+
771
+ // node_modules/ws/lib/receiver.js
772
+ var require_receiver = __commonJS({
773
+ "node_modules/ws/lib/receiver.js"(exports, module) {
774
+ "use strict";
775
+ var { Writable } = __require("stream");
776
+ var PerMessageDeflate2 = require_permessage_deflate();
777
+ var {
778
+ BINARY_TYPES,
779
+ EMPTY_BUFFER,
780
+ kStatusCode,
781
+ kWebSocket
782
+ } = require_constants();
783
+ var { concat, toArrayBuffer, unmask } = require_buffer_util();
784
+ var { isValidStatusCode, isValidUTF8 } = require_validation();
785
+ var FastBuffer = Buffer[Symbol.species];
786
+ var GET_INFO = 0;
787
+ var GET_PAYLOAD_LENGTH_16 = 1;
788
+ var GET_PAYLOAD_LENGTH_64 = 2;
789
+ var GET_MASK = 3;
790
+ var GET_DATA = 4;
791
+ var INFLATING = 5;
792
+ var DEFER_EVENT = 6;
793
+ var Receiver2 = class extends Writable {
794
+ /**
795
+ * Creates a Receiver instance.
796
+ *
797
+ * @param {Object} [options] Options object
798
+ * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
799
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
800
+ * multiple times in the same tick
801
+ * @param {String} [options.binaryType=nodebuffer] The type for binary data
802
+ * @param {Object} [options.extensions] An object containing the negotiated
803
+ * extensions
804
+ * @param {Boolean} [options.isServer=false] Specifies whether to operate in
805
+ * client or server mode
806
+ * @param {Number} [options.maxBufferedChunks=0] The maximum number of
807
+ * buffered data chunks
808
+ * @param {Number} [options.maxFragments=0] The maximum number of message
809
+ * fragments
810
+ * @param {Number} [options.maxPayload=0] The maximum allowed message length
811
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
812
+ * not to skip UTF-8 validation for text and close messages
813
+ */
814
+ constructor(options = {}) {
815
+ super();
816
+ this._allowSynchronousEvents = options.allowSynchronousEvents !== void 0 ? options.allowSynchronousEvents : true;
817
+ this._binaryType = options.binaryType || BINARY_TYPES[0];
818
+ this._extensions = options.extensions || {};
819
+ this._isServer = !!options.isServer;
820
+ this._maxBufferedChunks = options.maxBufferedChunks | 0;
821
+ this._maxFragments = options.maxFragments | 0;
822
+ this._maxPayload = options.maxPayload | 0;
823
+ this._skipUTF8Validation = !!options.skipUTF8Validation;
824
+ this[kWebSocket] = void 0;
825
+ this._bufferedBytes = 0;
826
+ this._buffers = [];
827
+ this._compressed = false;
828
+ this._payloadLength = 0;
829
+ this._mask = void 0;
830
+ this._fragmented = 0;
831
+ this._masked = false;
832
+ this._fin = false;
833
+ this._opcode = 0;
834
+ this._totalPayloadLength = 0;
835
+ this._messageLength = 0;
836
+ this._fragments = [];
837
+ this._errored = false;
838
+ this._loop = false;
839
+ this._state = GET_INFO;
840
+ }
841
+ /**
842
+ * Implements `Writable.prototype._write()`.
843
+ *
844
+ * @param {Buffer} chunk The chunk of data to write
845
+ * @param {String} encoding The character encoding of `chunk`
846
+ * @param {Function} cb Callback
847
+ * @private
848
+ */
849
+ _write(chunk, encoding, cb) {
850
+ if (this._opcode === 8 && this._state == GET_INFO) return cb();
851
+ if (this._maxBufferedChunks > 0 && this._buffers.length >= this._maxBufferedChunks) {
852
+ cb(
853
+ this.createError(
854
+ RangeError,
855
+ "Too many buffered chunks",
856
+ false,
857
+ 1008,
858
+ "WS_ERR_TOO_MANY_BUFFERED_PARTS"
859
+ )
860
+ );
861
+ return;
862
+ }
863
+ this._bufferedBytes += chunk.length;
864
+ this._buffers.push(chunk);
865
+ this.startLoop(cb);
866
+ }
867
+ /**
868
+ * Consumes `n` bytes from the buffered data.
869
+ *
870
+ * @param {Number} n The number of bytes to consume
871
+ * @return {Buffer} The consumed bytes
872
+ * @private
873
+ */
874
+ consume(n) {
875
+ this._bufferedBytes -= n;
876
+ if (n === this._buffers[0].length) return this._buffers.shift();
877
+ if (n < this._buffers[0].length) {
878
+ const buf = this._buffers[0];
879
+ this._buffers[0] = new FastBuffer(
880
+ buf.buffer,
881
+ buf.byteOffset + n,
882
+ buf.length - n
883
+ );
884
+ return new FastBuffer(buf.buffer, buf.byteOffset, n);
885
+ }
886
+ const dst = Buffer.allocUnsafe(n);
887
+ do {
888
+ const buf = this._buffers[0];
889
+ const offset = dst.length - n;
890
+ if (n >= buf.length) {
891
+ dst.set(this._buffers.shift(), offset);
892
+ } else {
893
+ dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);
894
+ this._buffers[0] = new FastBuffer(
895
+ buf.buffer,
896
+ buf.byteOffset + n,
897
+ buf.length - n
898
+ );
899
+ }
900
+ n -= buf.length;
901
+ } while (n > 0);
902
+ return dst;
903
+ }
904
+ /**
905
+ * Starts the parsing loop.
906
+ *
907
+ * @param {Function} cb Callback
908
+ * @private
909
+ */
910
+ startLoop(cb) {
911
+ this._loop = true;
912
+ do {
913
+ switch (this._state) {
914
+ case GET_INFO:
915
+ this.getInfo(cb);
916
+ break;
917
+ case GET_PAYLOAD_LENGTH_16:
918
+ this.getPayloadLength16(cb);
919
+ break;
920
+ case GET_PAYLOAD_LENGTH_64:
921
+ this.getPayloadLength64(cb);
922
+ break;
923
+ case GET_MASK:
924
+ this.getMask();
925
+ break;
926
+ case GET_DATA:
927
+ this.getData(cb);
928
+ break;
929
+ case INFLATING:
930
+ case DEFER_EVENT:
931
+ this._loop = false;
932
+ return;
933
+ }
934
+ } while (this._loop);
935
+ if (!this._errored) cb();
936
+ }
937
+ /**
938
+ * Reads the first two bytes of a frame.
939
+ *
940
+ * @param {Function} cb Callback
941
+ * @private
942
+ */
943
+ getInfo(cb) {
944
+ if (this._bufferedBytes < 2) {
945
+ this._loop = false;
946
+ return;
947
+ }
948
+ const buf = this.consume(2);
949
+ if ((buf[0] & 48) !== 0) {
950
+ const error = this.createError(
951
+ RangeError,
952
+ "RSV2 and RSV3 must be clear",
953
+ true,
954
+ 1002,
955
+ "WS_ERR_UNEXPECTED_RSV_2_3"
956
+ );
957
+ cb(error);
958
+ return;
959
+ }
960
+ const compressed = (buf[0] & 64) === 64;
961
+ if (compressed && !this._extensions[PerMessageDeflate2.extensionName]) {
962
+ const error = this.createError(
963
+ RangeError,
964
+ "RSV1 must be clear",
965
+ true,
966
+ 1002,
967
+ "WS_ERR_UNEXPECTED_RSV_1"
968
+ );
969
+ cb(error);
970
+ return;
971
+ }
972
+ this._fin = (buf[0] & 128) === 128;
973
+ this._opcode = buf[0] & 15;
974
+ this._payloadLength = buf[1] & 127;
975
+ if (this._opcode === 0) {
976
+ if (compressed) {
977
+ const error = this.createError(
978
+ RangeError,
979
+ "RSV1 must be clear",
980
+ true,
981
+ 1002,
982
+ "WS_ERR_UNEXPECTED_RSV_1"
983
+ );
984
+ cb(error);
985
+ return;
986
+ }
987
+ if (!this._fragmented) {
988
+ const error = this.createError(
989
+ RangeError,
990
+ "invalid opcode 0",
991
+ true,
992
+ 1002,
993
+ "WS_ERR_INVALID_OPCODE"
994
+ );
995
+ cb(error);
996
+ return;
997
+ }
998
+ this._opcode = this._fragmented;
999
+ } else if (this._opcode === 1 || this._opcode === 2) {
1000
+ if (this._fragmented) {
1001
+ const error = this.createError(
1002
+ RangeError,
1003
+ `invalid opcode ${this._opcode}`,
1004
+ true,
1005
+ 1002,
1006
+ "WS_ERR_INVALID_OPCODE"
1007
+ );
1008
+ cb(error);
1009
+ return;
1010
+ }
1011
+ this._compressed = compressed;
1012
+ } else if (this._opcode > 7 && this._opcode < 11) {
1013
+ if (!this._fin) {
1014
+ const error = this.createError(
1015
+ RangeError,
1016
+ "FIN must be set",
1017
+ true,
1018
+ 1002,
1019
+ "WS_ERR_EXPECTED_FIN"
1020
+ );
1021
+ cb(error);
1022
+ return;
1023
+ }
1024
+ if (compressed) {
1025
+ const error = this.createError(
1026
+ RangeError,
1027
+ "RSV1 must be clear",
1028
+ true,
1029
+ 1002,
1030
+ "WS_ERR_UNEXPECTED_RSV_1"
1031
+ );
1032
+ cb(error);
1033
+ return;
1034
+ }
1035
+ if (this._payloadLength > 125 || this._opcode === 8 && this._payloadLength === 1) {
1036
+ const error = this.createError(
1037
+ RangeError,
1038
+ `invalid payload length ${this._payloadLength}`,
1039
+ true,
1040
+ 1002,
1041
+ "WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"
1042
+ );
1043
+ cb(error);
1044
+ return;
1045
+ }
1046
+ } else {
1047
+ const error = this.createError(
1048
+ RangeError,
1049
+ `invalid opcode ${this._opcode}`,
1050
+ true,
1051
+ 1002,
1052
+ "WS_ERR_INVALID_OPCODE"
1053
+ );
1054
+ cb(error);
1055
+ return;
1056
+ }
1057
+ if (!this._fin && !this._fragmented) this._fragmented = this._opcode;
1058
+ this._masked = (buf[1] & 128) === 128;
1059
+ if (this._isServer) {
1060
+ if (!this._masked) {
1061
+ const error = this.createError(
1062
+ RangeError,
1063
+ "MASK must be set",
1064
+ true,
1065
+ 1002,
1066
+ "WS_ERR_EXPECTED_MASK"
1067
+ );
1068
+ cb(error);
1069
+ return;
1070
+ }
1071
+ } else if (this._masked) {
1072
+ const error = this.createError(
1073
+ RangeError,
1074
+ "MASK must be clear",
1075
+ true,
1076
+ 1002,
1077
+ "WS_ERR_UNEXPECTED_MASK"
1078
+ );
1079
+ cb(error);
1080
+ return;
1081
+ }
1082
+ if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;
1083
+ else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;
1084
+ else this.haveLength(cb);
1085
+ }
1086
+ /**
1087
+ * Gets extended payload length (7+16).
1088
+ *
1089
+ * @param {Function} cb Callback
1090
+ * @private
1091
+ */
1092
+ getPayloadLength16(cb) {
1093
+ if (this._bufferedBytes < 2) {
1094
+ this._loop = false;
1095
+ return;
1096
+ }
1097
+ this._payloadLength = this.consume(2).readUInt16BE(0);
1098
+ this.haveLength(cb);
1099
+ }
1100
+ /**
1101
+ * Gets extended payload length (7+64).
1102
+ *
1103
+ * @param {Function} cb Callback
1104
+ * @private
1105
+ */
1106
+ getPayloadLength64(cb) {
1107
+ if (this._bufferedBytes < 8) {
1108
+ this._loop = false;
1109
+ return;
1110
+ }
1111
+ const buf = this.consume(8);
1112
+ const num = buf.readUInt32BE(0);
1113
+ if (num > Math.pow(2, 53 - 32) - 1) {
1114
+ const error = this.createError(
1115
+ RangeError,
1116
+ "Unsupported WebSocket frame: payload length > 2^53 - 1",
1117
+ false,
1118
+ 1009,
1119
+ "WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH"
1120
+ );
1121
+ cb(error);
1122
+ return;
1123
+ }
1124
+ this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
1125
+ this.haveLength(cb);
1126
+ }
1127
+ /**
1128
+ * Payload length has been read.
1129
+ *
1130
+ * @param {Function} cb Callback
1131
+ * @private
1132
+ */
1133
+ haveLength(cb) {
1134
+ if (this._payloadLength && this._opcode < 8) {
1135
+ this._totalPayloadLength += this._payloadLength;
1136
+ if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
1137
+ const error = this.createError(
1138
+ RangeError,
1139
+ "Max payload size exceeded",
1140
+ false,
1141
+ 1009,
1142
+ "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
1143
+ );
1144
+ cb(error);
1145
+ return;
1146
+ }
1147
+ }
1148
+ if (this._masked) this._state = GET_MASK;
1149
+ else this._state = GET_DATA;
1150
+ }
1151
+ /**
1152
+ * Reads mask bytes.
1153
+ *
1154
+ * @private
1155
+ */
1156
+ getMask() {
1157
+ if (this._bufferedBytes < 4) {
1158
+ this._loop = false;
1159
+ return;
1160
+ }
1161
+ this._mask = this.consume(4);
1162
+ this._state = GET_DATA;
1163
+ }
1164
+ /**
1165
+ * Reads data bytes.
1166
+ *
1167
+ * @param {Function} cb Callback
1168
+ * @private
1169
+ */
1170
+ getData(cb) {
1171
+ let data = EMPTY_BUFFER;
1172
+ if (this._payloadLength) {
1173
+ if (this._bufferedBytes < this._payloadLength) {
1174
+ this._loop = false;
1175
+ return;
1176
+ }
1177
+ data = this.consume(this._payloadLength);
1178
+ if (this._masked && (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0) {
1179
+ unmask(data, this._mask);
1180
+ }
1181
+ }
1182
+ if (this._opcode > 7) {
1183
+ this.controlMessage(data, cb);
1184
+ return;
1185
+ }
1186
+ if (this._compressed) {
1187
+ this._state = INFLATING;
1188
+ this.decompress(data, cb);
1189
+ return;
1190
+ }
1191
+ if (data.length) {
1192
+ if (this._maxFragments > 0 && this._fragments.length >= this._maxFragments) {
1193
+ const error = this.createError(
1194
+ RangeError,
1195
+ "Too many message fragments",
1196
+ false,
1197
+ 1008,
1198
+ "WS_ERR_TOO_MANY_BUFFERED_PARTS"
1199
+ );
1200
+ cb(error);
1201
+ return;
1202
+ }
1203
+ this._messageLength = this._totalPayloadLength;
1204
+ this._fragments.push(data);
1205
+ }
1206
+ this.dataMessage(cb);
1207
+ }
1208
+ /**
1209
+ * Decompresses data.
1210
+ *
1211
+ * @param {Buffer} data Compressed data
1212
+ * @param {Function} cb Callback
1213
+ * @private
1214
+ */
1215
+ decompress(data, cb) {
1216
+ const perMessageDeflate = this._extensions[PerMessageDeflate2.extensionName];
1217
+ perMessageDeflate.decompress(data, this._fin, (err, buf) => {
1218
+ if (err) return cb(err);
1219
+ if (buf.length) {
1220
+ this._messageLength += buf.length;
1221
+ if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
1222
+ const error = this.createError(
1223
+ RangeError,
1224
+ "Max payload size exceeded",
1225
+ false,
1226
+ 1009,
1227
+ "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
1228
+ );
1229
+ cb(error);
1230
+ return;
1231
+ }
1232
+ if (this._maxFragments > 0 && this._fragments.length >= this._maxFragments) {
1233
+ const error = this.createError(
1234
+ RangeError,
1235
+ "Too many message fragments",
1236
+ false,
1237
+ 1008,
1238
+ "WS_ERR_TOO_MANY_BUFFERED_PARTS"
1239
+ );
1240
+ cb(error);
1241
+ return;
1242
+ }
1243
+ this._fragments.push(buf);
1244
+ }
1245
+ this.dataMessage(cb);
1246
+ if (this._state === GET_INFO) this.startLoop(cb);
1247
+ });
1248
+ }
1249
+ /**
1250
+ * Handles a data message.
1251
+ *
1252
+ * @param {Function} cb Callback
1253
+ * @private
1254
+ */
1255
+ dataMessage(cb) {
1256
+ if (!this._fin) {
1257
+ this._state = GET_INFO;
1258
+ return;
1259
+ }
1260
+ const messageLength = this._messageLength;
1261
+ const fragments = this._fragments;
1262
+ this._totalPayloadLength = 0;
1263
+ this._messageLength = 0;
1264
+ this._fragmented = 0;
1265
+ this._fragments = [];
1266
+ if (this._opcode === 2) {
1267
+ let data;
1268
+ if (this._binaryType === "nodebuffer") {
1269
+ data = concat(fragments, messageLength);
1270
+ } else if (this._binaryType === "arraybuffer") {
1271
+ data = toArrayBuffer(concat(fragments, messageLength));
1272
+ } else if (this._binaryType === "blob") {
1273
+ data = new Blob(fragments);
1274
+ } else {
1275
+ data = fragments;
1276
+ }
1277
+ if (this._allowSynchronousEvents) {
1278
+ this.emit("message", data, true);
1279
+ this._state = GET_INFO;
1280
+ } else {
1281
+ this._state = DEFER_EVENT;
1282
+ setImmediate(() => {
1283
+ this.emit("message", data, true);
1284
+ this._state = GET_INFO;
1285
+ this.startLoop(cb);
1286
+ });
1287
+ }
1288
+ } else {
1289
+ const buf = concat(fragments, messageLength);
1290
+ if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
1291
+ const error = this.createError(
1292
+ Error,
1293
+ "invalid UTF-8 sequence",
1294
+ true,
1295
+ 1007,
1296
+ "WS_ERR_INVALID_UTF8"
1297
+ );
1298
+ cb(error);
1299
+ return;
1300
+ }
1301
+ if (this._state === INFLATING || this._allowSynchronousEvents) {
1302
+ this.emit("message", buf, false);
1303
+ this._state = GET_INFO;
1304
+ } else {
1305
+ this._state = DEFER_EVENT;
1306
+ setImmediate(() => {
1307
+ this.emit("message", buf, false);
1308
+ this._state = GET_INFO;
1309
+ this.startLoop(cb);
1310
+ });
1311
+ }
1312
+ }
1313
+ }
1314
+ /**
1315
+ * Handles a control message.
1316
+ *
1317
+ * @param {Buffer} data Data to handle
1318
+ * @return {(Error|RangeError|undefined)} A possible error
1319
+ * @private
1320
+ */
1321
+ controlMessage(data, cb) {
1322
+ if (this._opcode === 8) {
1323
+ if (data.length === 0) {
1324
+ this._loop = false;
1325
+ this.emit("conclude", 1005, EMPTY_BUFFER);
1326
+ this.end();
1327
+ } else {
1328
+ const code = data.readUInt16BE(0);
1329
+ if (!isValidStatusCode(code)) {
1330
+ const error = this.createError(
1331
+ RangeError,
1332
+ `invalid status code ${code}`,
1333
+ true,
1334
+ 1002,
1335
+ "WS_ERR_INVALID_CLOSE_CODE"
1336
+ );
1337
+ cb(error);
1338
+ return;
1339
+ }
1340
+ const buf = new FastBuffer(
1341
+ data.buffer,
1342
+ data.byteOffset + 2,
1343
+ data.length - 2
1344
+ );
1345
+ if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
1346
+ const error = this.createError(
1347
+ Error,
1348
+ "invalid UTF-8 sequence",
1349
+ true,
1350
+ 1007,
1351
+ "WS_ERR_INVALID_UTF8"
1352
+ );
1353
+ cb(error);
1354
+ return;
1355
+ }
1356
+ this._loop = false;
1357
+ this.emit("conclude", code, buf);
1358
+ this.end();
1359
+ }
1360
+ this._state = GET_INFO;
1361
+ return;
1362
+ }
1363
+ if (this._allowSynchronousEvents) {
1364
+ this.emit(this._opcode === 9 ? "ping" : "pong", data);
1365
+ this._state = GET_INFO;
1366
+ } else {
1367
+ this._state = DEFER_EVENT;
1368
+ setImmediate(() => {
1369
+ this.emit(this._opcode === 9 ? "ping" : "pong", data);
1370
+ this._state = GET_INFO;
1371
+ this.startLoop(cb);
1372
+ });
1373
+ }
1374
+ }
1375
+ /**
1376
+ * Builds an error object.
1377
+ *
1378
+ * @param {function(new:Error|RangeError)} ErrorCtor The error constructor
1379
+ * @param {String} message The error message
1380
+ * @param {Boolean} prefix Specifies whether or not to add a default prefix to
1381
+ * `message`
1382
+ * @param {Number} statusCode The status code
1383
+ * @param {String} errorCode The exposed error code
1384
+ * @return {(Error|RangeError)} The error
1385
+ * @private
1386
+ */
1387
+ createError(ErrorCtor, message, prefix, statusCode, errorCode) {
1388
+ this._loop = false;
1389
+ this._errored = true;
1390
+ const err = new ErrorCtor(
1391
+ prefix ? `Invalid WebSocket frame: ${message}` : message
1392
+ );
1393
+ Error.captureStackTrace(err, this.createError);
1394
+ err.code = errorCode;
1395
+ err[kStatusCode] = statusCode;
1396
+ return err;
1397
+ }
1398
+ };
1399
+ module.exports = Receiver2;
1400
+ }
1401
+ });
1402
+
1403
+ // node_modules/ws/lib/sender.js
1404
+ var require_sender = __commonJS({
1405
+ "node_modules/ws/lib/sender.js"(exports, module) {
1406
+ "use strict";
1407
+ var { Duplex } = __require("stream");
1408
+ var { randomFillSync } = __require("crypto");
1409
+ var {
1410
+ types: { isUint8Array }
1411
+ } = __require("util");
1412
+ var PerMessageDeflate2 = require_permessage_deflate();
1413
+ var { EMPTY_BUFFER, kWebSocket, NOOP } = require_constants();
1414
+ var { isBlob, isValidStatusCode } = require_validation();
1415
+ var { mask: applyMask, toBuffer } = require_buffer_util();
1416
+ var kByteLength = /* @__PURE__ */ Symbol("kByteLength");
1417
+ var maskBuffer = Buffer.alloc(4);
1418
+ var RANDOM_POOL_SIZE = 8 * 1024;
1419
+ var randomPool;
1420
+ var randomPoolPointer = RANDOM_POOL_SIZE;
1421
+ var DEFAULT = 0;
1422
+ var DEFLATING = 1;
1423
+ var GET_BLOB_DATA = 2;
1424
+ var Sender2 = class _Sender {
1425
+ /**
1426
+ * Creates a Sender instance.
1427
+ *
1428
+ * @param {Duplex} socket The connection socket
1429
+ * @param {Object} [extensions] An object containing the negotiated extensions
1430
+ * @param {Function} [generateMask] The function used to generate the masking
1431
+ * key
1432
+ */
1433
+ constructor(socket, extensions, generateMask) {
1434
+ this._extensions = extensions || {};
1435
+ if (generateMask) {
1436
+ this._generateMask = generateMask;
1437
+ this._maskBuffer = Buffer.alloc(4);
1438
+ }
1439
+ this._socket = socket;
1440
+ this._firstFragment = true;
1441
+ this._compress = false;
1442
+ this._bufferedBytes = 0;
1443
+ this._queue = [];
1444
+ this._state = DEFAULT;
1445
+ this.onerror = NOOP;
1446
+ this[kWebSocket] = void 0;
1447
+ }
1448
+ /**
1449
+ * Frames a piece of data according to the HyBi WebSocket protocol.
1450
+ *
1451
+ * @param {(Buffer|String)} data The data to frame
1452
+ * @param {Object} options Options object
1453
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
1454
+ * FIN bit
1455
+ * @param {Function} [options.generateMask] The function used to generate the
1456
+ * masking key
1457
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1458
+ * `data`
1459
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
1460
+ * key
1461
+ * @param {Number} options.opcode The opcode
1462
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
1463
+ * modified
1464
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
1465
+ * RSV1 bit
1466
+ * @return {(Buffer|String)[]} The framed data
1467
+ * @public
1468
+ */
1469
+ static frame(data, options) {
1470
+ let mask;
1471
+ let merge = false;
1472
+ let offset = 2;
1473
+ let skipMasking = false;
1474
+ if (options.mask) {
1475
+ mask = options.maskBuffer || maskBuffer;
1476
+ if (options.generateMask) {
1477
+ options.generateMask(mask);
1478
+ } else {
1479
+ if (randomPoolPointer === RANDOM_POOL_SIZE) {
1480
+ if (randomPool === void 0) {
1481
+ randomPool = Buffer.alloc(RANDOM_POOL_SIZE);
1482
+ }
1483
+ randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);
1484
+ randomPoolPointer = 0;
1485
+ }
1486
+ mask[0] = randomPool[randomPoolPointer++];
1487
+ mask[1] = randomPool[randomPoolPointer++];
1488
+ mask[2] = randomPool[randomPoolPointer++];
1489
+ mask[3] = randomPool[randomPoolPointer++];
1490
+ }
1491
+ skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;
1492
+ offset = 6;
1493
+ }
1494
+ let dataLength;
1495
+ if (typeof data === "string") {
1496
+ if ((!options.mask || skipMasking) && options[kByteLength] !== void 0) {
1497
+ dataLength = options[kByteLength];
1498
+ } else {
1499
+ data = Buffer.from(data);
1500
+ dataLength = data.length;
1501
+ }
1502
+ } else {
1503
+ dataLength = data.length;
1504
+ merge = options.mask && options.readOnly && !skipMasking;
1505
+ }
1506
+ let payloadLength = dataLength;
1507
+ if (dataLength >= 65536) {
1508
+ offset += 8;
1509
+ payloadLength = 127;
1510
+ } else if (dataLength > 125) {
1511
+ offset += 2;
1512
+ payloadLength = 126;
1513
+ }
1514
+ const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);
1515
+ target[0] = options.fin ? options.opcode | 128 : options.opcode;
1516
+ if (options.rsv1) target[0] |= 64;
1517
+ target[1] = payloadLength;
1518
+ if (payloadLength === 126) {
1519
+ target.writeUInt16BE(dataLength, 2);
1520
+ } else if (payloadLength === 127) {
1521
+ target[2] = target[3] = 0;
1522
+ target.writeUIntBE(dataLength, 4, 6);
1523
+ }
1524
+ if (!options.mask) return [target, data];
1525
+ target[1] |= 128;
1526
+ target[offset - 4] = mask[0];
1527
+ target[offset - 3] = mask[1];
1528
+ target[offset - 2] = mask[2];
1529
+ target[offset - 1] = mask[3];
1530
+ if (skipMasking) return [target, data];
1531
+ if (merge) {
1532
+ applyMask(data, mask, target, offset, dataLength);
1533
+ return [target];
1534
+ }
1535
+ applyMask(data, mask, data, 0, dataLength);
1536
+ return [target, data];
1537
+ }
1538
+ /**
1539
+ * Sends a close message to the other peer.
1540
+ *
1541
+ * @param {Number} [code] The status code component of the body
1542
+ * @param {(String|Buffer)} [data] The message component of the body
1543
+ * @param {Boolean} [mask=false] Specifies whether or not to mask the message
1544
+ * @param {Function} [cb] Callback
1545
+ * @public
1546
+ */
1547
+ close(code, data, mask, cb) {
1548
+ let buf;
1549
+ if (code === void 0) {
1550
+ buf = EMPTY_BUFFER;
1551
+ } else if (typeof code !== "number" || !isValidStatusCode(code)) {
1552
+ throw new TypeError("First argument must be a valid error code number");
1553
+ } else if (data === void 0 || !data.length) {
1554
+ buf = Buffer.allocUnsafe(2);
1555
+ buf.writeUInt16BE(code, 0);
1556
+ } else {
1557
+ const length = Buffer.byteLength(data);
1558
+ if (length > 123) {
1559
+ throw new RangeError("The message must not be greater than 123 bytes");
1560
+ }
1561
+ buf = Buffer.allocUnsafe(2 + length);
1562
+ buf.writeUInt16BE(code, 0);
1563
+ if (typeof data === "string") {
1564
+ buf.write(data, 2);
1565
+ } else if (isUint8Array(data)) {
1566
+ buf.set(data, 2);
1567
+ } else {
1568
+ throw new TypeError("Second argument must be a string or a Uint8Array");
1569
+ }
1570
+ }
1571
+ const options = {
1572
+ [kByteLength]: buf.length,
1573
+ fin: true,
1574
+ generateMask: this._generateMask,
1575
+ mask,
1576
+ maskBuffer: this._maskBuffer,
1577
+ opcode: 8,
1578
+ readOnly: false,
1579
+ rsv1: false
1580
+ };
1581
+ if (this._state !== DEFAULT) {
1582
+ this.enqueue([this.dispatch, buf, false, options, cb]);
1583
+ } else {
1584
+ this.sendFrame(_Sender.frame(buf, options), cb);
1585
+ }
1586
+ }
1587
+ /**
1588
+ * Sends a ping message to the other peer.
1589
+ *
1590
+ * @param {*} data The message to send
1591
+ * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
1592
+ * @param {Function} [cb] Callback
1593
+ * @public
1594
+ */
1595
+ ping(data, mask, cb) {
1596
+ let byteLength;
1597
+ let readOnly;
1598
+ if (typeof data === "string") {
1599
+ byteLength = Buffer.byteLength(data);
1600
+ readOnly = false;
1601
+ } else if (isBlob(data)) {
1602
+ byteLength = data.size;
1603
+ readOnly = false;
1604
+ } else {
1605
+ data = toBuffer(data);
1606
+ byteLength = data.length;
1607
+ readOnly = toBuffer.readOnly;
1608
+ }
1609
+ if (byteLength > 125) {
1610
+ throw new RangeError("The data size must not be greater than 125 bytes");
1611
+ }
1612
+ const options = {
1613
+ [kByteLength]: byteLength,
1614
+ fin: true,
1615
+ generateMask: this._generateMask,
1616
+ mask,
1617
+ maskBuffer: this._maskBuffer,
1618
+ opcode: 9,
1619
+ readOnly,
1620
+ rsv1: false
1621
+ };
1622
+ if (isBlob(data)) {
1623
+ if (this._state !== DEFAULT) {
1624
+ this.enqueue([this.getBlobData, data, false, options, cb]);
1625
+ } else {
1626
+ this.getBlobData(data, false, options, cb);
1627
+ }
1628
+ } else if (this._state !== DEFAULT) {
1629
+ this.enqueue([this.dispatch, data, false, options, cb]);
1630
+ } else {
1631
+ this.sendFrame(_Sender.frame(data, options), cb);
1632
+ }
1633
+ }
1634
+ /**
1635
+ * Sends a pong message to the other peer.
1636
+ *
1637
+ * @param {*} data The message to send
1638
+ * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
1639
+ * @param {Function} [cb] Callback
1640
+ * @public
1641
+ */
1642
+ pong(data, mask, cb) {
1643
+ let byteLength;
1644
+ let readOnly;
1645
+ if (typeof data === "string") {
1646
+ byteLength = Buffer.byteLength(data);
1647
+ readOnly = false;
1648
+ } else if (isBlob(data)) {
1649
+ byteLength = data.size;
1650
+ readOnly = false;
1651
+ } else {
1652
+ data = toBuffer(data);
1653
+ byteLength = data.length;
1654
+ readOnly = toBuffer.readOnly;
1655
+ }
1656
+ if (byteLength > 125) {
1657
+ throw new RangeError("The data size must not be greater than 125 bytes");
1658
+ }
1659
+ const options = {
1660
+ [kByteLength]: byteLength,
1661
+ fin: true,
1662
+ generateMask: this._generateMask,
1663
+ mask,
1664
+ maskBuffer: this._maskBuffer,
1665
+ opcode: 10,
1666
+ readOnly,
1667
+ rsv1: false
1668
+ };
1669
+ if (isBlob(data)) {
1670
+ if (this._state !== DEFAULT) {
1671
+ this.enqueue([this.getBlobData, data, false, options, cb]);
1672
+ } else {
1673
+ this.getBlobData(data, false, options, cb);
1674
+ }
1675
+ } else if (this._state !== DEFAULT) {
1676
+ this.enqueue([this.dispatch, data, false, options, cb]);
1677
+ } else {
1678
+ this.sendFrame(_Sender.frame(data, options), cb);
1679
+ }
1680
+ }
1681
+ /**
1682
+ * Sends a data message to the other peer.
1683
+ *
1684
+ * @param {*} data The message to send
1685
+ * @param {Object} options Options object
1686
+ * @param {Boolean} [options.binary=false] Specifies whether `data` is binary
1687
+ * or text
1688
+ * @param {Boolean} [options.compress=false] Specifies whether or not to
1689
+ * compress `data`
1690
+ * @param {Boolean} [options.fin=false] Specifies whether the fragment is the
1691
+ * last one
1692
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1693
+ * `data`
1694
+ * @param {Function} [cb] Callback
1695
+ * @public
1696
+ */
1697
+ send(data, options, cb) {
1698
+ const perMessageDeflate = this._extensions[PerMessageDeflate2.extensionName];
1699
+ let opcode = options.binary ? 2 : 1;
1700
+ let rsv1 = options.compress;
1701
+ let byteLength;
1702
+ let readOnly;
1703
+ if (typeof data === "string") {
1704
+ byteLength = Buffer.byteLength(data);
1705
+ readOnly = false;
1706
+ } else if (isBlob(data)) {
1707
+ byteLength = data.size;
1708
+ readOnly = false;
1709
+ } else {
1710
+ data = toBuffer(data);
1711
+ byteLength = data.length;
1712
+ readOnly = toBuffer.readOnly;
1713
+ }
1714
+ if (this._firstFragment) {
1715
+ this._firstFragment = false;
1716
+ if (rsv1 && perMessageDeflate && perMessageDeflate.params[perMessageDeflate._isServer ? "server_no_context_takeover" : "client_no_context_takeover"]) {
1717
+ rsv1 = byteLength >= perMessageDeflate._threshold;
1718
+ }
1719
+ this._compress = rsv1;
1720
+ } else {
1721
+ rsv1 = false;
1722
+ opcode = 0;
1723
+ }
1724
+ if (options.fin) this._firstFragment = true;
1725
+ const opts = {
1726
+ [kByteLength]: byteLength,
1727
+ fin: options.fin,
1728
+ generateMask: this._generateMask,
1729
+ mask: options.mask,
1730
+ maskBuffer: this._maskBuffer,
1731
+ opcode,
1732
+ readOnly,
1733
+ rsv1
1734
+ };
1735
+ if (isBlob(data)) {
1736
+ if (this._state !== DEFAULT) {
1737
+ this.enqueue([this.getBlobData, data, this._compress, opts, cb]);
1738
+ } else {
1739
+ this.getBlobData(data, this._compress, opts, cb);
1740
+ }
1741
+ } else if (this._state !== DEFAULT) {
1742
+ this.enqueue([this.dispatch, data, this._compress, opts, cb]);
1743
+ } else {
1744
+ this.dispatch(data, this._compress, opts, cb);
1745
+ }
1746
+ }
1747
+ /**
1748
+ * Gets the contents of a blob as binary data.
1749
+ *
1750
+ * @param {Blob} blob The blob
1751
+ * @param {Boolean} [compress=false] Specifies whether or not to compress
1752
+ * the data
1753
+ * @param {Object} options Options object
1754
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
1755
+ * FIN bit
1756
+ * @param {Function} [options.generateMask] The function used to generate the
1757
+ * masking key
1758
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1759
+ * `data`
1760
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
1761
+ * key
1762
+ * @param {Number} options.opcode The opcode
1763
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
1764
+ * modified
1765
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
1766
+ * RSV1 bit
1767
+ * @param {Function} [cb] Callback
1768
+ * @private
1769
+ */
1770
+ getBlobData(blob, compress, options, cb) {
1771
+ this._bufferedBytes += options[kByteLength];
1772
+ this._state = GET_BLOB_DATA;
1773
+ blob.arrayBuffer().then((arrayBuffer) => {
1774
+ if (this._socket.destroyed) {
1775
+ const err = new Error(
1776
+ "The socket was closed while the blob was being read"
1777
+ );
1778
+ process.nextTick(callCallbacks, this, err, cb);
1779
+ return;
1780
+ }
1781
+ this._bufferedBytes -= options[kByteLength];
1782
+ const data = toBuffer(arrayBuffer);
1783
+ if (!compress) {
1784
+ this._state = DEFAULT;
1785
+ this.sendFrame(_Sender.frame(data, options), cb);
1786
+ this.dequeue();
1787
+ } else {
1788
+ this.dispatch(data, compress, options, cb);
1789
+ }
1790
+ }).catch((err) => {
1791
+ process.nextTick(onError, this, err, cb);
1792
+ });
1793
+ }
1794
+ /**
1795
+ * Dispatches a message.
1796
+ *
1797
+ * @param {(Buffer|String)} data The message to send
1798
+ * @param {Boolean} [compress=false] Specifies whether or not to compress
1799
+ * `data`
1800
+ * @param {Object} options Options object
1801
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
1802
+ * FIN bit
1803
+ * @param {Function} [options.generateMask] The function used to generate the
1804
+ * masking key
1805
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1806
+ * `data`
1807
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
1808
+ * key
1809
+ * @param {Number} options.opcode The opcode
1810
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
1811
+ * modified
1812
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
1813
+ * RSV1 bit
1814
+ * @param {Function} [cb] Callback
1815
+ * @private
1816
+ */
1817
+ dispatch(data, compress, options, cb) {
1818
+ if (!compress) {
1819
+ this.sendFrame(_Sender.frame(data, options), cb);
1820
+ return;
1821
+ }
1822
+ const perMessageDeflate = this._extensions[PerMessageDeflate2.extensionName];
1823
+ this._bufferedBytes += options[kByteLength];
1824
+ this._state = DEFLATING;
1825
+ perMessageDeflate.compress(data, options.fin, (_, buf) => {
1826
+ if (this._socket.destroyed) {
1827
+ const err = new Error(
1828
+ "The socket was closed while data was being compressed"
1829
+ );
1830
+ callCallbacks(this, err, cb);
1831
+ return;
1832
+ }
1833
+ this._bufferedBytes -= options[kByteLength];
1834
+ this._state = DEFAULT;
1835
+ options.readOnly = false;
1836
+ this.sendFrame(_Sender.frame(buf, options), cb);
1837
+ this.dequeue();
1838
+ });
1839
+ }
1840
+ /**
1841
+ * Executes queued send operations.
1842
+ *
1843
+ * @private
1844
+ */
1845
+ dequeue() {
1846
+ while (this._state === DEFAULT && this._queue.length) {
1847
+ const params = this._queue.shift();
1848
+ this._bufferedBytes -= params[3][kByteLength];
1849
+ Reflect.apply(params[0], this, params.slice(1));
1850
+ }
1851
+ }
1852
+ /**
1853
+ * Enqueues a send operation.
1854
+ *
1855
+ * @param {Array} params Send operation parameters.
1856
+ * @private
1857
+ */
1858
+ enqueue(params) {
1859
+ this._bufferedBytes += params[3][kByteLength];
1860
+ this._queue.push(params);
1861
+ }
1862
+ /**
1863
+ * Sends a frame.
1864
+ *
1865
+ * @param {(Buffer | String)[]} list The frame to send
1866
+ * @param {Function} [cb] Callback
1867
+ * @private
1868
+ */
1869
+ sendFrame(list, cb) {
1870
+ if (list.length === 2) {
1871
+ this._socket.cork();
1872
+ this._socket.write(list[0]);
1873
+ this._socket.write(list[1], cb);
1874
+ this._socket.uncork();
1875
+ } else {
1876
+ this._socket.write(list[0], cb);
1877
+ }
1878
+ }
1879
+ };
1880
+ module.exports = Sender2;
1881
+ function callCallbacks(sender, err, cb) {
1882
+ if (typeof cb === "function") cb(err);
1883
+ for (let i = 0; i < sender._queue.length; i++) {
1884
+ const params = sender._queue[i];
1885
+ const callback = params[params.length - 1];
1886
+ if (typeof callback === "function") callback(err);
1887
+ }
1888
+ }
1889
+ function onError(sender, err, cb) {
1890
+ callCallbacks(sender, err, cb);
1891
+ sender.onerror(err);
1892
+ }
1893
+ }
1894
+ });
1895
+
1896
+ // node_modules/ws/lib/event-target.js
1897
+ var require_event_target = __commonJS({
1898
+ "node_modules/ws/lib/event-target.js"(exports, module) {
1899
+ "use strict";
1900
+ var { kForOnEventAttribute, kListener } = require_constants();
1901
+ var kCode = /* @__PURE__ */ Symbol("kCode");
1902
+ var kData = /* @__PURE__ */ Symbol("kData");
1903
+ var kError = /* @__PURE__ */ Symbol("kError");
1904
+ var kMessage = /* @__PURE__ */ Symbol("kMessage");
1905
+ var kReason = /* @__PURE__ */ Symbol("kReason");
1906
+ var kTarget = /* @__PURE__ */ Symbol("kTarget");
1907
+ var kType = /* @__PURE__ */ Symbol("kType");
1908
+ var kWasClean = /* @__PURE__ */ Symbol("kWasClean");
1909
+ var Event = class {
1910
+ /**
1911
+ * Create a new `Event`.
1912
+ *
1913
+ * @param {String} type The name of the event
1914
+ * @throws {TypeError} If the `type` argument is not specified
1915
+ */
1916
+ constructor(type) {
1917
+ this[kTarget] = null;
1918
+ this[kType] = type;
1919
+ }
1920
+ /**
1921
+ * @type {*}
1922
+ */
1923
+ get target() {
1924
+ return this[kTarget];
1925
+ }
1926
+ /**
1927
+ * @type {String}
1928
+ */
1929
+ get type() {
1930
+ return this[kType];
1931
+ }
1932
+ };
1933
+ Object.defineProperty(Event.prototype, "target", { enumerable: true });
1934
+ Object.defineProperty(Event.prototype, "type", { enumerable: true });
1935
+ var CloseEvent = class extends Event {
1936
+ /**
1937
+ * Create a new `CloseEvent`.
1938
+ *
1939
+ * @param {String} type The name of the event
1940
+ * @param {Object} [options] A dictionary object that allows for setting
1941
+ * attributes via object members of the same name
1942
+ * @param {Number} [options.code=0] The status code explaining why the
1943
+ * connection was closed
1944
+ * @param {String} [options.reason=''] A human-readable string explaining why
1945
+ * the connection was closed
1946
+ * @param {Boolean} [options.wasClean=false] Indicates whether or not the
1947
+ * connection was cleanly closed
1948
+ */
1949
+ constructor(type, options = {}) {
1950
+ super(type);
1951
+ this[kCode] = options.code === void 0 ? 0 : options.code;
1952
+ this[kReason] = options.reason === void 0 ? "" : options.reason;
1953
+ this[kWasClean] = options.wasClean === void 0 ? false : options.wasClean;
1954
+ }
1955
+ /**
1956
+ * @type {Number}
1957
+ */
1958
+ get code() {
1959
+ return this[kCode];
1960
+ }
1961
+ /**
1962
+ * @type {String}
1963
+ */
1964
+ get reason() {
1965
+ return this[kReason];
1966
+ }
1967
+ /**
1968
+ * @type {Boolean}
1969
+ */
1970
+ get wasClean() {
1971
+ return this[kWasClean];
1972
+ }
1973
+ };
1974
+ Object.defineProperty(CloseEvent.prototype, "code", { enumerable: true });
1975
+ Object.defineProperty(CloseEvent.prototype, "reason", { enumerable: true });
1976
+ Object.defineProperty(CloseEvent.prototype, "wasClean", { enumerable: true });
1977
+ var ErrorEvent = class extends Event {
1978
+ /**
1979
+ * Create a new `ErrorEvent`.
1980
+ *
1981
+ * @param {String} type The name of the event
1982
+ * @param {Object} [options] A dictionary object that allows for setting
1983
+ * attributes via object members of the same name
1984
+ * @param {*} [options.error=null] The error that generated this event
1985
+ * @param {String} [options.message=''] The error message
1986
+ */
1987
+ constructor(type, options = {}) {
1988
+ super(type);
1989
+ this[kError] = options.error === void 0 ? null : options.error;
1990
+ this[kMessage] = options.message === void 0 ? "" : options.message;
1991
+ }
1992
+ /**
1993
+ * @type {*}
1994
+ */
1995
+ get error() {
1996
+ return this[kError];
1997
+ }
1998
+ /**
1999
+ * @type {String}
2000
+ */
2001
+ get message() {
2002
+ return this[kMessage];
2003
+ }
2004
+ };
2005
+ Object.defineProperty(ErrorEvent.prototype, "error", { enumerable: true });
2006
+ Object.defineProperty(ErrorEvent.prototype, "message", { enumerable: true });
2007
+ var MessageEvent = class extends Event {
2008
+ /**
2009
+ * Create a new `MessageEvent`.
2010
+ *
2011
+ * @param {String} type The name of the event
2012
+ * @param {Object} [options] A dictionary object that allows for setting
2013
+ * attributes via object members of the same name
2014
+ * @param {*} [options.data=null] The message content
2015
+ */
2016
+ constructor(type, options = {}) {
2017
+ super(type);
2018
+ this[kData] = options.data === void 0 ? null : options.data;
2019
+ }
2020
+ /**
2021
+ * @type {*}
2022
+ */
2023
+ get data() {
2024
+ return this[kData];
2025
+ }
2026
+ };
2027
+ Object.defineProperty(MessageEvent.prototype, "data", { enumerable: true });
2028
+ var EventTarget = {
2029
+ /**
2030
+ * Register an event listener.
2031
+ *
2032
+ * @param {String} type A string representing the event type to listen for
2033
+ * @param {(Function|Object)} handler The listener to add
2034
+ * @param {Object} [options] An options object specifies characteristics about
2035
+ * the event listener
2036
+ * @param {Boolean} [options.once=false] A `Boolean` indicating that the
2037
+ * listener should be invoked at most once after being added. If `true`,
2038
+ * the listener would be automatically removed when invoked.
2039
+ * @public
2040
+ */
2041
+ addEventListener(type, handler, options = {}) {
2042
+ for (const listener of this.listeners(type)) {
2043
+ if (!options[kForOnEventAttribute] && listener[kListener] === handler && !listener[kForOnEventAttribute]) {
2044
+ return;
2045
+ }
2046
+ }
2047
+ let wrapper;
2048
+ if (type === "message") {
2049
+ wrapper = function onMessage(data, isBinary) {
2050
+ const event = new MessageEvent("message", {
2051
+ data: isBinary ? data : data.toString()
2052
+ });
2053
+ event[kTarget] = this;
2054
+ callListener(handler, this, event);
2055
+ };
2056
+ } else if (type === "close") {
2057
+ wrapper = function onClose(code, message) {
2058
+ const event = new CloseEvent("close", {
2059
+ code,
2060
+ reason: message.toString(),
2061
+ wasClean: this._closeFrameReceived && this._closeFrameSent
2062
+ });
2063
+ event[kTarget] = this;
2064
+ callListener(handler, this, event);
2065
+ };
2066
+ } else if (type === "error") {
2067
+ wrapper = function onError(error) {
2068
+ const event = new ErrorEvent("error", {
2069
+ error,
2070
+ message: error.message
2071
+ });
2072
+ event[kTarget] = this;
2073
+ callListener(handler, this, event);
2074
+ };
2075
+ } else if (type === "open") {
2076
+ wrapper = function onOpen() {
2077
+ const event = new Event("open");
2078
+ event[kTarget] = this;
2079
+ callListener(handler, this, event);
2080
+ };
2081
+ } else {
2082
+ return;
2083
+ }
2084
+ wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];
2085
+ wrapper[kListener] = handler;
2086
+ if (options.once) {
2087
+ this.once(type, wrapper);
2088
+ } else {
2089
+ this.on(type, wrapper);
2090
+ }
2091
+ },
2092
+ /**
2093
+ * Remove an event listener.
2094
+ *
2095
+ * @param {String} type A string representing the event type to remove
2096
+ * @param {(Function|Object)} handler The listener to remove
2097
+ * @public
2098
+ */
2099
+ removeEventListener(type, handler) {
2100
+ for (const listener of this.listeners(type)) {
2101
+ if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {
2102
+ this.removeListener(type, listener);
2103
+ break;
2104
+ }
2105
+ }
2106
+ }
2107
+ };
2108
+ module.exports = {
2109
+ CloseEvent,
2110
+ ErrorEvent,
2111
+ Event,
2112
+ EventTarget,
2113
+ MessageEvent
2114
+ };
2115
+ function callListener(listener, thisArg, event) {
2116
+ if (typeof listener === "object" && listener.handleEvent) {
2117
+ listener.handleEvent.call(listener, event);
2118
+ } else {
2119
+ listener.call(thisArg, event);
2120
+ }
2121
+ }
2122
+ }
2123
+ });
2124
+
2125
+ // node_modules/ws/lib/extension.js
2126
+ var require_extension = __commonJS({
2127
+ "node_modules/ws/lib/extension.js"(exports, module) {
2128
+ "use strict";
2129
+ var { tokenChars } = require_validation();
2130
+ function push(dest, name, elem) {
2131
+ if (dest[name] === void 0) dest[name] = [elem];
2132
+ else dest[name].push(elem);
2133
+ }
2134
+ function parse(header) {
2135
+ const offers = /* @__PURE__ */ Object.create(null);
2136
+ let params = /* @__PURE__ */ Object.create(null);
2137
+ let mustUnescape = false;
2138
+ let isEscaping = false;
2139
+ let inQuotes = false;
2140
+ let extensionName;
2141
+ let paramName;
2142
+ let start = -1;
2143
+ let code = -1;
2144
+ let end = -1;
2145
+ let i = 0;
2146
+ for (; i < header.length; i++) {
2147
+ code = header.charCodeAt(i);
2148
+ if (extensionName === void 0) {
2149
+ if (end === -1 && tokenChars[code] === 1) {
2150
+ if (start === -1) start = i;
2151
+ } else if (i !== 0 && (code === 32 || code === 9)) {
2152
+ if (end === -1 && start !== -1) end = i;
2153
+ } else if (code === 59 || code === 44) {
2154
+ if (start === -1) {
2155
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2156
+ }
2157
+ if (end === -1) end = i;
2158
+ const name = header.slice(start, end);
2159
+ if (code === 44) {
2160
+ push(offers, name, params);
2161
+ params = /* @__PURE__ */ Object.create(null);
2162
+ } else {
2163
+ extensionName = name;
2164
+ }
2165
+ start = end = -1;
2166
+ } else {
2167
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2168
+ }
2169
+ } else if (paramName === void 0) {
2170
+ if (end === -1 && tokenChars[code] === 1) {
2171
+ if (start === -1) start = i;
2172
+ } else if (code === 32 || code === 9) {
2173
+ if (end === -1 && start !== -1) end = i;
2174
+ } else if (code === 59 || code === 44) {
2175
+ if (start === -1) {
2176
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2177
+ }
2178
+ if (end === -1) end = i;
2179
+ push(params, header.slice(start, end), true);
2180
+ if (code === 44) {
2181
+ push(offers, extensionName, params);
2182
+ params = /* @__PURE__ */ Object.create(null);
2183
+ extensionName = void 0;
2184
+ }
2185
+ start = end = -1;
2186
+ } else if (code === 61 && start !== -1 && end === -1) {
2187
+ paramName = header.slice(start, i);
2188
+ start = end = -1;
2189
+ } else {
2190
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2191
+ }
2192
+ } else {
2193
+ if (isEscaping) {
2194
+ if (tokenChars[code] !== 1) {
2195
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2196
+ }
2197
+ if (start === -1) start = i;
2198
+ else if (!mustUnescape) mustUnescape = true;
2199
+ isEscaping = false;
2200
+ } else if (inQuotes) {
2201
+ if (tokenChars[code] === 1) {
2202
+ if (start === -1) start = i;
2203
+ } else if (code === 34 && start !== -1) {
2204
+ inQuotes = false;
2205
+ end = i;
2206
+ } else if (code === 92) {
2207
+ isEscaping = true;
2208
+ } else {
2209
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2210
+ }
2211
+ } else if (code === 34 && header.charCodeAt(i - 1) === 61) {
2212
+ inQuotes = true;
2213
+ } else if (end === -1 && tokenChars[code] === 1) {
2214
+ if (start === -1) start = i;
2215
+ } else if (start !== -1 && (code === 32 || code === 9)) {
2216
+ if (end === -1) end = i;
2217
+ } else if (code === 59 || code === 44) {
2218
+ if (start === -1) {
2219
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2220
+ }
2221
+ if (end === -1) end = i;
2222
+ let value = header.slice(start, end);
2223
+ if (mustUnescape) {
2224
+ value = value.replace(/\\/g, "");
2225
+ mustUnescape = false;
2226
+ }
2227
+ push(params, paramName, value);
2228
+ if (code === 44) {
2229
+ push(offers, extensionName, params);
2230
+ params = /* @__PURE__ */ Object.create(null);
2231
+ extensionName = void 0;
2232
+ }
2233
+ paramName = void 0;
2234
+ start = end = -1;
2235
+ } else {
2236
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2237
+ }
2238
+ }
2239
+ }
2240
+ if (start === -1 || inQuotes || code === 32 || code === 9) {
2241
+ throw new SyntaxError("Unexpected end of input");
2242
+ }
2243
+ if (end === -1) end = i;
2244
+ const token = header.slice(start, end);
2245
+ if (extensionName === void 0) {
2246
+ push(offers, token, params);
2247
+ } else {
2248
+ if (paramName === void 0) {
2249
+ push(params, token, true);
2250
+ } else if (mustUnescape) {
2251
+ push(params, paramName, token.replace(/\\/g, ""));
2252
+ } else {
2253
+ push(params, paramName, token);
2254
+ }
2255
+ push(offers, extensionName, params);
2256
+ }
2257
+ return offers;
2258
+ }
2259
+ function format(extensions) {
2260
+ return Object.keys(extensions).map((extension2) => {
2261
+ let configurations = extensions[extension2];
2262
+ if (!Array.isArray(configurations)) configurations = [configurations];
2263
+ return configurations.map((params) => {
2264
+ return [extension2].concat(
2265
+ Object.keys(params).map((k) => {
2266
+ let values = params[k];
2267
+ if (!Array.isArray(values)) values = [values];
2268
+ return values.map((v) => v === true ? k : `${k}=${v}`).join("; ");
2269
+ })
2270
+ ).join("; ");
2271
+ }).join(", ");
2272
+ }).join(", ");
2273
+ }
2274
+ module.exports = { format, parse };
2275
+ }
2276
+ });
2277
+
2278
+ // node_modules/ws/lib/websocket.js
2279
+ var require_websocket = __commonJS({
2280
+ "node_modules/ws/lib/websocket.js"(exports, module) {
2281
+ "use strict";
2282
+ var EventEmitter = __require("events");
2283
+ var https = __require("https");
2284
+ var http = __require("http");
2285
+ var net = __require("net");
2286
+ var tls = __require("tls");
2287
+ var { randomBytes, createHash } = __require("crypto");
2288
+ var { Duplex, Readable } = __require("stream");
2289
+ var { URL } = __require("url");
2290
+ var PerMessageDeflate2 = require_permessage_deflate();
2291
+ var Receiver2 = require_receiver();
2292
+ var Sender2 = require_sender();
2293
+ var { isBlob } = require_validation();
2294
+ var {
2295
+ BINARY_TYPES,
2296
+ CLOSE_TIMEOUT,
2297
+ EMPTY_BUFFER,
2298
+ GUID,
2299
+ kForOnEventAttribute,
2300
+ kListener,
2301
+ kStatusCode,
2302
+ kWebSocket,
2303
+ NOOP
2304
+ } = require_constants();
2305
+ var {
2306
+ EventTarget: { addEventListener, removeEventListener }
2307
+ } = require_event_target();
2308
+ var { format, parse } = require_extension();
2309
+ var { toBuffer } = require_buffer_util();
2310
+ var kAborted = /* @__PURE__ */ Symbol("kAborted");
2311
+ var protocolVersions = [8, 13];
2312
+ var readyStates = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"];
2313
+ var subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
2314
+ var WebSocket2 = class _WebSocket extends EventEmitter {
2315
+ /**
2316
+ * Create a new `WebSocket`.
2317
+ *
2318
+ * @param {(String|URL)} address The URL to which to connect
2319
+ * @param {(String|String[])} [protocols] The subprotocols
2320
+ * @param {Object} [options] Connection options
2321
+ */
2322
+ constructor(address, protocols, options) {
2323
+ super();
2324
+ this._binaryType = BINARY_TYPES[0];
2325
+ this._closeCode = 1006;
2326
+ this._closeFrameReceived = false;
2327
+ this._closeFrameSent = false;
2328
+ this._closeMessage = EMPTY_BUFFER;
2329
+ this._closeTimer = null;
2330
+ this._errorEmitted = false;
2331
+ this._extensions = {};
2332
+ this._paused = false;
2333
+ this._protocol = "";
2334
+ this._readyState = _WebSocket.CONNECTING;
2335
+ this._receiver = null;
2336
+ this._sender = null;
2337
+ this._socket = null;
2338
+ if (address !== null) {
2339
+ this._bufferedAmount = 0;
2340
+ this._isServer = false;
2341
+ this._redirects = 0;
2342
+ if (protocols === void 0) {
2343
+ protocols = [];
2344
+ } else if (!Array.isArray(protocols)) {
2345
+ if (typeof protocols === "object" && protocols !== null) {
2346
+ options = protocols;
2347
+ protocols = [];
2348
+ } else {
2349
+ protocols = [protocols];
2350
+ }
2351
+ }
2352
+ initAsClient(this, address, protocols, options);
2353
+ } else {
2354
+ this._autoPong = options.autoPong;
2355
+ this._closeTimeout = options.closeTimeout;
2356
+ this._isServer = true;
2357
+ }
2358
+ }
2359
+ /**
2360
+ * For historical reasons, the custom "nodebuffer" type is used by the default
2361
+ * instead of "blob".
2362
+ *
2363
+ * @type {String}
2364
+ */
2365
+ get binaryType() {
2366
+ return this._binaryType;
2367
+ }
2368
+ set binaryType(type) {
2369
+ if (!BINARY_TYPES.includes(type)) return;
2370
+ this._binaryType = type;
2371
+ if (this._receiver) this._receiver._binaryType = type;
2372
+ }
2373
+ /**
2374
+ * @type {Number}
2375
+ */
2376
+ get bufferedAmount() {
2377
+ if (!this._socket) return this._bufferedAmount;
2378
+ return this._socket._writableState.length + this._sender._bufferedBytes;
2379
+ }
2380
+ /**
2381
+ * @type {String}
2382
+ */
2383
+ get extensions() {
2384
+ return Object.keys(this._extensions).join();
2385
+ }
2386
+ /**
2387
+ * @type {Boolean}
2388
+ */
2389
+ get isPaused() {
2390
+ return this._paused;
2391
+ }
2392
+ /**
2393
+ * @type {Function}
2394
+ */
2395
+ /* istanbul ignore next */
2396
+ get onclose() {
2397
+ return null;
2398
+ }
2399
+ /**
2400
+ * @type {Function}
2401
+ */
2402
+ /* istanbul ignore next */
2403
+ get onerror() {
2404
+ return null;
2405
+ }
2406
+ /**
2407
+ * @type {Function}
2408
+ */
2409
+ /* istanbul ignore next */
2410
+ get onopen() {
2411
+ return null;
2412
+ }
2413
+ /**
2414
+ * @type {Function}
2415
+ */
2416
+ /* istanbul ignore next */
2417
+ get onmessage() {
2418
+ return null;
2419
+ }
2420
+ /**
2421
+ * @type {String}
2422
+ */
2423
+ get protocol() {
2424
+ return this._protocol;
2425
+ }
2426
+ /**
2427
+ * @type {Number}
2428
+ */
2429
+ get readyState() {
2430
+ return this._readyState;
2431
+ }
2432
+ /**
2433
+ * @type {String}
2434
+ */
2435
+ get url() {
2436
+ return this._url;
2437
+ }
2438
+ /**
2439
+ * Set up the socket and the internal resources.
2440
+ *
2441
+ * @param {Duplex} socket The network socket between the server and client
2442
+ * @param {Buffer} head The first packet of the upgraded stream
2443
+ * @param {Object} options Options object
2444
+ * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether
2445
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
2446
+ * multiple times in the same tick
2447
+ * @param {Function} [options.generateMask] The function used to generate the
2448
+ * masking key
2449
+ * @param {Number} [options.maxBufferedChunks=0] The maximum number of
2450
+ * buffered data chunks
2451
+ * @param {Number} [options.maxFragments=0] The maximum number of message
2452
+ * fragments
2453
+ * @param {Number} [options.maxPayload=0] The maximum allowed message size
2454
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
2455
+ * not to skip UTF-8 validation for text and close messages
2456
+ * @private
2457
+ */
2458
+ setSocket(socket, head, options) {
2459
+ const receiver = new Receiver2({
2460
+ allowSynchronousEvents: options.allowSynchronousEvents,
2461
+ binaryType: this.binaryType,
2462
+ extensions: this._extensions,
2463
+ isServer: this._isServer,
2464
+ maxBufferedChunks: options.maxBufferedChunks,
2465
+ maxFragments: options.maxFragments,
2466
+ maxPayload: options.maxPayload,
2467
+ skipUTF8Validation: options.skipUTF8Validation
2468
+ });
2469
+ const sender = new Sender2(socket, this._extensions, options.generateMask);
2470
+ this._receiver = receiver;
2471
+ this._sender = sender;
2472
+ this._socket = socket;
2473
+ receiver[kWebSocket] = this;
2474
+ sender[kWebSocket] = this;
2475
+ socket[kWebSocket] = this;
2476
+ receiver.on("conclude", receiverOnConclude);
2477
+ receiver.on("drain", receiverOnDrain);
2478
+ receiver.on("error", receiverOnError);
2479
+ receiver.on("message", receiverOnMessage);
2480
+ receiver.on("ping", receiverOnPing);
2481
+ receiver.on("pong", receiverOnPong);
2482
+ sender.onerror = senderOnError;
2483
+ if (socket.setTimeout) socket.setTimeout(0);
2484
+ if (socket.setNoDelay) socket.setNoDelay();
2485
+ if (head.length > 0) socket.unshift(head);
2486
+ socket.on("close", socketOnClose);
2487
+ socket.on("data", socketOnData);
2488
+ socket.on("end", socketOnEnd);
2489
+ socket.on("error", socketOnError);
2490
+ this._readyState = _WebSocket.OPEN;
2491
+ this.emit("open");
2492
+ }
2493
+ /**
2494
+ * Emit the `'close'` event.
2495
+ *
2496
+ * @private
2497
+ */
2498
+ emitClose() {
2499
+ if (!this._socket) {
2500
+ this._readyState = _WebSocket.CLOSED;
2501
+ this.emit("close", this._closeCode, this._closeMessage);
2502
+ return;
2503
+ }
2504
+ if (this._extensions[PerMessageDeflate2.extensionName]) {
2505
+ this._extensions[PerMessageDeflate2.extensionName].cleanup();
2506
+ }
2507
+ this._receiver.removeAllListeners();
2508
+ this._readyState = _WebSocket.CLOSED;
2509
+ this.emit("close", this._closeCode, this._closeMessage);
2510
+ }
2511
+ /**
2512
+ * Start a closing handshake.
2513
+ *
2514
+ * +----------+ +-----------+ +----------+
2515
+ * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -
2516
+ * | +----------+ +-----------+ +----------+ |
2517
+ * +----------+ +-----------+ |
2518
+ * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING
2519
+ * +----------+ +-----------+ |
2520
+ * | | | +---+ |
2521
+ * +------------------------+-->|fin| - - - -
2522
+ * | +---+ | +---+
2523
+ * - - - - -|fin|<---------------------+
2524
+ * +---+
2525
+ *
2526
+ * @param {Number} [code] Status code explaining why the connection is closing
2527
+ * @param {(String|Buffer)} [data] The reason why the connection is
2528
+ * closing
2529
+ * @public
2530
+ */
2531
+ close(code, data) {
2532
+ if (this.readyState === _WebSocket.CLOSED) return;
2533
+ if (this.readyState === _WebSocket.CONNECTING) {
2534
+ const msg = "WebSocket was closed before the connection was established";
2535
+ abortHandshake(this, this._req, msg);
2536
+ return;
2537
+ }
2538
+ if (this.readyState === _WebSocket.CLOSING) {
2539
+ if (this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted)) {
2540
+ this._socket.end();
2541
+ }
2542
+ return;
2543
+ }
2544
+ this._readyState = _WebSocket.CLOSING;
2545
+ this._sender.close(code, data, !this._isServer, (err) => {
2546
+ if (err) return;
2547
+ this._closeFrameSent = true;
2548
+ if (this._closeFrameReceived || this._receiver._writableState.errorEmitted) {
2549
+ this._socket.end();
2550
+ }
2551
+ });
2552
+ setCloseTimer(this);
2553
+ }
2554
+ /**
2555
+ * Pause the socket.
2556
+ *
2557
+ * @public
2558
+ */
2559
+ pause() {
2560
+ if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) {
2561
+ return;
2562
+ }
2563
+ this._paused = true;
2564
+ this._socket.pause();
2565
+ }
2566
+ /**
2567
+ * Send a ping.
2568
+ *
2569
+ * @param {*} [data] The data to send
2570
+ * @param {Boolean} [mask] Indicates whether or not to mask `data`
2571
+ * @param {Function} [cb] Callback which is executed when the ping is sent
2572
+ * @public
2573
+ */
2574
+ ping(data, mask, cb) {
2575
+ if (this.readyState === _WebSocket.CONNECTING) {
2576
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
2577
+ }
2578
+ if (typeof data === "function") {
2579
+ cb = data;
2580
+ data = mask = void 0;
2581
+ } else if (typeof mask === "function") {
2582
+ cb = mask;
2583
+ mask = void 0;
2584
+ }
2585
+ if (typeof data === "number") data = data.toString();
2586
+ if (this.readyState !== _WebSocket.OPEN) {
2587
+ sendAfterClose(this, data, cb);
2588
+ return;
2589
+ }
2590
+ if (mask === void 0) mask = !this._isServer;
2591
+ this._sender.ping(data || EMPTY_BUFFER, mask, cb);
2592
+ }
2593
+ /**
2594
+ * Send a pong.
2595
+ *
2596
+ * @param {*} [data] The data to send
2597
+ * @param {Boolean} [mask] Indicates whether or not to mask `data`
2598
+ * @param {Function} [cb] Callback which is executed when the pong is sent
2599
+ * @public
2600
+ */
2601
+ pong(data, mask, cb) {
2602
+ if (this.readyState === _WebSocket.CONNECTING) {
2603
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
2604
+ }
2605
+ if (typeof data === "function") {
2606
+ cb = data;
2607
+ data = mask = void 0;
2608
+ } else if (typeof mask === "function") {
2609
+ cb = mask;
2610
+ mask = void 0;
2611
+ }
2612
+ if (typeof data === "number") data = data.toString();
2613
+ if (this.readyState !== _WebSocket.OPEN) {
2614
+ sendAfterClose(this, data, cb);
2615
+ return;
2616
+ }
2617
+ if (mask === void 0) mask = !this._isServer;
2618
+ this._sender.pong(data || EMPTY_BUFFER, mask, cb);
2619
+ }
2620
+ /**
2621
+ * Resume the socket.
2622
+ *
2623
+ * @public
2624
+ */
2625
+ resume() {
2626
+ if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) {
2627
+ return;
2628
+ }
2629
+ this._paused = false;
2630
+ if (!this._receiver._writableState.needDrain) this._socket.resume();
2631
+ }
2632
+ /**
2633
+ * Send a data message.
2634
+ *
2635
+ * @param {*} data The message to send
2636
+ * @param {Object} [options] Options object
2637
+ * @param {Boolean} [options.binary] Specifies whether `data` is binary or
2638
+ * text
2639
+ * @param {Boolean} [options.compress] Specifies whether or not to compress
2640
+ * `data`
2641
+ * @param {Boolean} [options.fin=true] Specifies whether the fragment is the
2642
+ * last one
2643
+ * @param {Boolean} [options.mask] Specifies whether or not to mask `data`
2644
+ * @param {Function} [cb] Callback which is executed when data is written out
2645
+ * @public
2646
+ */
2647
+ send(data, options, cb) {
2648
+ if (this.readyState === _WebSocket.CONNECTING) {
2649
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
2650
+ }
2651
+ if (typeof options === "function") {
2652
+ cb = options;
2653
+ options = {};
2654
+ }
2655
+ if (typeof data === "number") data = data.toString();
2656
+ if (this.readyState !== _WebSocket.OPEN) {
2657
+ sendAfterClose(this, data, cb);
2658
+ return;
2659
+ }
2660
+ const opts = {
2661
+ binary: typeof data !== "string",
2662
+ mask: !this._isServer,
2663
+ compress: true,
2664
+ fin: true,
2665
+ ...options
2666
+ };
2667
+ if (!this._extensions[PerMessageDeflate2.extensionName]) {
2668
+ opts.compress = false;
2669
+ }
2670
+ this._sender.send(data || EMPTY_BUFFER, opts, cb);
2671
+ }
2672
+ /**
2673
+ * Forcibly close the connection.
2674
+ *
2675
+ * @public
2676
+ */
2677
+ terminate() {
2678
+ if (this.readyState === _WebSocket.CLOSED) return;
2679
+ if (this.readyState === _WebSocket.CONNECTING) {
2680
+ const msg = "WebSocket was closed before the connection was established";
2681
+ abortHandshake(this, this._req, msg);
2682
+ return;
2683
+ }
2684
+ if (this._socket) {
2685
+ this._readyState = _WebSocket.CLOSING;
2686
+ this._socket.destroy();
2687
+ }
2688
+ }
2689
+ };
2690
+ Object.defineProperty(WebSocket2, "CONNECTING", {
2691
+ enumerable: true,
2692
+ value: readyStates.indexOf("CONNECTING")
2693
+ });
2694
+ Object.defineProperty(WebSocket2.prototype, "CONNECTING", {
2695
+ enumerable: true,
2696
+ value: readyStates.indexOf("CONNECTING")
2697
+ });
2698
+ Object.defineProperty(WebSocket2, "OPEN", {
2699
+ enumerable: true,
2700
+ value: readyStates.indexOf("OPEN")
2701
+ });
2702
+ Object.defineProperty(WebSocket2.prototype, "OPEN", {
2703
+ enumerable: true,
2704
+ value: readyStates.indexOf("OPEN")
2705
+ });
2706
+ Object.defineProperty(WebSocket2, "CLOSING", {
2707
+ enumerable: true,
2708
+ value: readyStates.indexOf("CLOSING")
2709
+ });
2710
+ Object.defineProperty(WebSocket2.prototype, "CLOSING", {
2711
+ enumerable: true,
2712
+ value: readyStates.indexOf("CLOSING")
2713
+ });
2714
+ Object.defineProperty(WebSocket2, "CLOSED", {
2715
+ enumerable: true,
2716
+ value: readyStates.indexOf("CLOSED")
2717
+ });
2718
+ Object.defineProperty(WebSocket2.prototype, "CLOSED", {
2719
+ enumerable: true,
2720
+ value: readyStates.indexOf("CLOSED")
2721
+ });
2722
+ [
2723
+ "binaryType",
2724
+ "bufferedAmount",
2725
+ "extensions",
2726
+ "isPaused",
2727
+ "protocol",
2728
+ "readyState",
2729
+ "url"
2730
+ ].forEach((property) => {
2731
+ Object.defineProperty(WebSocket2.prototype, property, { enumerable: true });
2732
+ });
2733
+ ["open", "error", "close", "message"].forEach((method) => {
2734
+ Object.defineProperty(WebSocket2.prototype, `on${method}`, {
2735
+ enumerable: true,
2736
+ get() {
2737
+ for (const listener of this.listeners(method)) {
2738
+ if (listener[kForOnEventAttribute]) return listener[kListener];
2739
+ }
2740
+ return null;
2741
+ },
2742
+ set(handler) {
2743
+ for (const listener of this.listeners(method)) {
2744
+ if (listener[kForOnEventAttribute]) {
2745
+ this.removeListener(method, listener);
2746
+ break;
2747
+ }
2748
+ }
2749
+ if (typeof handler !== "function") return;
2750
+ this.addEventListener(method, handler, {
2751
+ [kForOnEventAttribute]: true
2752
+ });
2753
+ }
2754
+ });
2755
+ });
2756
+ WebSocket2.prototype.addEventListener = addEventListener;
2757
+ WebSocket2.prototype.removeEventListener = removeEventListener;
2758
+ module.exports = WebSocket2;
2759
+ function initAsClient(websocket, address, protocols, options) {
2760
+ const opts = {
2761
+ allowSynchronousEvents: true,
2762
+ autoPong: true,
2763
+ closeTimeout: CLOSE_TIMEOUT,
2764
+ protocolVersion: protocolVersions[1],
2765
+ maxBufferedChunks: 1024 * 1024,
2766
+ maxFragments: 128 * 1024,
2767
+ maxPayload: 100 * 1024 * 1024,
2768
+ skipUTF8Validation: false,
2769
+ perMessageDeflate: true,
2770
+ followRedirects: false,
2771
+ maxRedirects: 10,
2772
+ ...options,
2773
+ socketPath: void 0,
2774
+ hostname: void 0,
2775
+ protocol: void 0,
2776
+ timeout: void 0,
2777
+ method: "GET",
2778
+ host: void 0,
2779
+ path: void 0,
2780
+ port: void 0
2781
+ };
2782
+ websocket._autoPong = opts.autoPong;
2783
+ websocket._closeTimeout = opts.closeTimeout;
2784
+ if (!protocolVersions.includes(opts.protocolVersion)) {
2785
+ throw new RangeError(
2786
+ `Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`
2787
+ );
2788
+ }
2789
+ let parsedUrl;
2790
+ if (address instanceof URL) {
2791
+ parsedUrl = address;
2792
+ } else {
2793
+ try {
2794
+ parsedUrl = new URL(address);
2795
+ } catch {
2796
+ throw new SyntaxError(`Invalid URL: ${address}`);
2797
+ }
2798
+ }
2799
+ if (parsedUrl.protocol === "http:") {
2800
+ parsedUrl.protocol = "ws:";
2801
+ } else if (parsedUrl.protocol === "https:") {
2802
+ parsedUrl.protocol = "wss:";
2803
+ }
2804
+ websocket._url = parsedUrl.href;
2805
+ const isSecure = parsedUrl.protocol === "wss:";
2806
+ const isIpcUrl = parsedUrl.protocol === "ws+unix:";
2807
+ let invalidUrlMessage;
2808
+ if (parsedUrl.protocol !== "ws:" && !isSecure && !isIpcUrl) {
2809
+ invalidUrlMessage = `The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`;
2810
+ } else if (isIpcUrl && !parsedUrl.pathname) {
2811
+ invalidUrlMessage = "The URL's pathname is empty";
2812
+ } else if (parsedUrl.hash) {
2813
+ invalidUrlMessage = "The URL contains a fragment identifier";
2814
+ }
2815
+ if (invalidUrlMessage) {
2816
+ const err = new SyntaxError(invalidUrlMessage);
2817
+ if (websocket._redirects === 0) {
2818
+ throw err;
2819
+ } else {
2820
+ emitErrorAndClose(websocket, err);
2821
+ return;
2822
+ }
2823
+ }
2824
+ const defaultPort = isSecure ? 443 : 80;
2825
+ const key = randomBytes(16).toString("base64");
2826
+ const request = isSecure ? https.request : http.request;
2827
+ const protocolSet = /* @__PURE__ */ new Set();
2828
+ let perMessageDeflate;
2829
+ opts.createConnection = opts.createConnection || (isSecure ? tlsConnect : netConnect);
2830
+ opts.defaultPort = opts.defaultPort || defaultPort;
2831
+ opts.port = parsedUrl.port || defaultPort;
2832
+ opts.host = parsedUrl.hostname.startsWith("[") ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname;
2833
+ opts.headers = {
2834
+ ...opts.headers,
2835
+ "Sec-WebSocket-Version": opts.protocolVersion,
2836
+ "Sec-WebSocket-Key": key,
2837
+ Connection: "Upgrade",
2838
+ Upgrade: "websocket"
2839
+ };
2840
+ opts.path = parsedUrl.pathname + parsedUrl.search;
2841
+ opts.timeout = opts.handshakeTimeout;
2842
+ if (opts.perMessageDeflate) {
2843
+ perMessageDeflate = new PerMessageDeflate2({
2844
+ ...opts.perMessageDeflate,
2845
+ isServer: false,
2846
+ maxPayload: opts.maxPayload
2847
+ });
2848
+ opts.headers["Sec-WebSocket-Extensions"] = format({
2849
+ [PerMessageDeflate2.extensionName]: perMessageDeflate.offer()
2850
+ });
2851
+ }
2852
+ if (protocols.length) {
2853
+ for (const protocol of protocols) {
2854
+ if (typeof protocol !== "string" || !subprotocolRegex.test(protocol) || protocolSet.has(protocol)) {
2855
+ throw new SyntaxError(
2856
+ "An invalid or duplicated subprotocol was specified"
2857
+ );
2858
+ }
2859
+ protocolSet.add(protocol);
2860
+ }
2861
+ opts.headers["Sec-WebSocket-Protocol"] = protocols.join(",");
2862
+ }
2863
+ if (opts.origin) {
2864
+ if (opts.protocolVersion < 13) {
2865
+ opts.headers["Sec-WebSocket-Origin"] = opts.origin;
2866
+ } else {
2867
+ opts.headers.Origin = opts.origin;
2868
+ }
2869
+ }
2870
+ if (parsedUrl.username || parsedUrl.password) {
2871
+ opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
2872
+ }
2873
+ if (isIpcUrl) {
2874
+ const parts = opts.path.split(":");
2875
+ opts.socketPath = parts[0];
2876
+ opts.path = parts[1];
2877
+ }
2878
+ let req;
2879
+ if (opts.followRedirects) {
2880
+ if (websocket._redirects === 0) {
2881
+ websocket._originalIpc = isIpcUrl;
2882
+ websocket._originalSecure = isSecure;
2883
+ websocket._originalHostOrSocketPath = isIpcUrl ? opts.socketPath : parsedUrl.host;
2884
+ const headers = options && options.headers;
2885
+ options = { ...options, headers: {} };
2886
+ if (headers) {
2887
+ for (const [key2, value] of Object.entries(headers)) {
2888
+ options.headers[key2.toLowerCase()] = value;
2889
+ }
2890
+ }
2891
+ } else if (websocket.listenerCount("redirect") === 0) {
2892
+ const isSameHost = isIpcUrl ? websocket._originalIpc ? opts.socketPath === websocket._originalHostOrSocketPath : false : websocket._originalIpc ? false : parsedUrl.host === websocket._originalHostOrSocketPath;
2893
+ if (!isSameHost || websocket._originalSecure && !isSecure) {
2894
+ delete opts.headers.authorization;
2895
+ delete opts.headers.cookie;
2896
+ if (!isSameHost) delete opts.headers.host;
2897
+ opts.auth = void 0;
2898
+ }
2899
+ }
2900
+ if (opts.auth && !options.headers.authorization) {
2901
+ options.headers.authorization = "Basic " + Buffer.from(opts.auth).toString("base64");
2902
+ }
2903
+ req = websocket._req = request(opts);
2904
+ if (websocket._redirects) {
2905
+ websocket.emit("redirect", websocket.url, req);
2906
+ }
2907
+ } else {
2908
+ req = websocket._req = request(opts);
2909
+ }
2910
+ if (opts.timeout) {
2911
+ req.on("timeout", () => {
2912
+ abortHandshake(websocket, req, "Opening handshake has timed out");
2913
+ });
2914
+ }
2915
+ req.on("error", (err) => {
2916
+ if (req === null || req[kAborted]) return;
2917
+ req = websocket._req = null;
2918
+ emitErrorAndClose(websocket, err);
2919
+ });
2920
+ req.on("response", (res) => {
2921
+ const location = res.headers.location;
2922
+ const statusCode = res.statusCode;
2923
+ if (location && opts.followRedirects && statusCode >= 300 && statusCode < 400) {
2924
+ if (++websocket._redirects > opts.maxRedirects) {
2925
+ abortHandshake(websocket, req, "Maximum redirects exceeded");
2926
+ return;
2927
+ }
2928
+ req.abort();
2929
+ let addr;
2930
+ try {
2931
+ addr = new URL(location, address);
2932
+ } catch (e) {
2933
+ const err = new SyntaxError(`Invalid URL: ${location}`);
2934
+ emitErrorAndClose(websocket, err);
2935
+ return;
2936
+ }
2937
+ initAsClient(websocket, addr, protocols, options);
2938
+ } else if (!websocket.emit("unexpected-response", req, res)) {
2939
+ abortHandshake(
2940
+ websocket,
2941
+ req,
2942
+ `Unexpected server response: ${res.statusCode}`
2943
+ );
2944
+ }
2945
+ });
2946
+ req.on("upgrade", (res, socket, head) => {
2947
+ websocket.emit("upgrade", res);
2948
+ if (websocket.readyState !== WebSocket2.CONNECTING) return;
2949
+ req = websocket._req = null;
2950
+ const upgrade = res.headers.upgrade;
2951
+ if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
2952
+ abortHandshake(websocket, socket, "Invalid Upgrade header");
2953
+ return;
2954
+ }
2955
+ const digest = createHash("sha1").update(key + GUID).digest("base64");
2956
+ if (res.headers["sec-websocket-accept"] !== digest) {
2957
+ abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
2958
+ return;
2959
+ }
2960
+ const serverProt = res.headers["sec-websocket-protocol"];
2961
+ let protError;
2962
+ if (serverProt !== void 0) {
2963
+ if (!protocolSet.size) {
2964
+ protError = "Server sent a subprotocol but none was requested";
2965
+ } else if (!protocolSet.has(serverProt)) {
2966
+ protError = "Server sent an invalid subprotocol";
2967
+ }
2968
+ } else if (protocolSet.size) {
2969
+ protError = "Server sent no subprotocol";
2970
+ }
2971
+ if (protError) {
2972
+ abortHandshake(websocket, socket, protError);
2973
+ return;
2974
+ }
2975
+ if (serverProt) websocket._protocol = serverProt;
2976
+ const secWebSocketExtensions = res.headers["sec-websocket-extensions"];
2977
+ if (secWebSocketExtensions !== void 0) {
2978
+ if (!perMessageDeflate) {
2979
+ const message = "Server sent a Sec-WebSocket-Extensions header but no extension was requested";
2980
+ abortHandshake(websocket, socket, message);
2981
+ return;
2982
+ }
2983
+ let extensions;
2984
+ try {
2985
+ extensions = parse(secWebSocketExtensions);
2986
+ } catch (err) {
2987
+ const message = "Invalid Sec-WebSocket-Extensions header";
2988
+ abortHandshake(websocket, socket, message);
2989
+ return;
2990
+ }
2991
+ const extensionNames = Object.keys(extensions);
2992
+ if (extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate2.extensionName) {
2993
+ const message = "Server indicated an extension that was not requested";
2994
+ abortHandshake(websocket, socket, message);
2995
+ return;
2996
+ }
2997
+ try {
2998
+ perMessageDeflate.accept(extensions[PerMessageDeflate2.extensionName]);
2999
+ } catch (err) {
3000
+ const message = "Invalid Sec-WebSocket-Extensions header";
3001
+ abortHandshake(websocket, socket, message);
3002
+ return;
3003
+ }
3004
+ websocket._extensions[PerMessageDeflate2.extensionName] = perMessageDeflate;
3005
+ }
3006
+ websocket.setSocket(socket, head, {
3007
+ allowSynchronousEvents: opts.allowSynchronousEvents,
3008
+ generateMask: opts.generateMask,
3009
+ maxBufferedChunks: opts.maxBufferedChunks,
3010
+ maxFragments: opts.maxFragments,
3011
+ maxPayload: opts.maxPayload,
3012
+ skipUTF8Validation: opts.skipUTF8Validation
3013
+ });
3014
+ });
3015
+ if (opts.finishRequest) {
3016
+ opts.finishRequest(req, websocket);
3017
+ } else {
3018
+ req.end();
3019
+ }
3020
+ }
3021
+ function emitErrorAndClose(websocket, err) {
3022
+ websocket._readyState = WebSocket2.CLOSING;
3023
+ websocket._errorEmitted = true;
3024
+ websocket.emit("error", err);
3025
+ websocket.emitClose();
3026
+ }
3027
+ function netConnect(options) {
3028
+ options.path = options.socketPath;
3029
+ return net.connect(options);
3030
+ }
3031
+ function tlsConnect(options) {
3032
+ options.path = void 0;
3033
+ if (!options.servername && options.servername !== "") {
3034
+ options.servername = net.isIP(options.host) ? "" : options.host;
3035
+ }
3036
+ return tls.connect(options);
3037
+ }
3038
+ function abortHandshake(websocket, stream, message) {
3039
+ websocket._readyState = WebSocket2.CLOSING;
3040
+ const err = new Error(message);
3041
+ Error.captureStackTrace(err, abortHandshake);
3042
+ if (stream.setHeader) {
3043
+ stream[kAborted] = true;
3044
+ stream.abort();
3045
+ if (stream.socket && !stream.socket.destroyed) {
3046
+ stream.socket.destroy();
3047
+ }
3048
+ process.nextTick(emitErrorAndClose, websocket, err);
3049
+ } else {
3050
+ stream.destroy(err);
3051
+ stream.once("error", websocket.emit.bind(websocket, "error"));
3052
+ stream.once("close", websocket.emitClose.bind(websocket));
3053
+ }
3054
+ }
3055
+ function sendAfterClose(websocket, data, cb) {
3056
+ if (data) {
3057
+ const length = isBlob(data) ? data.size : toBuffer(data).length;
3058
+ if (websocket._socket) websocket._sender._bufferedBytes += length;
3059
+ else websocket._bufferedAmount += length;
3060
+ }
3061
+ if (cb) {
3062
+ const err = new Error(
3063
+ `WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})`
3064
+ );
3065
+ process.nextTick(cb, err);
3066
+ }
3067
+ }
3068
+ function receiverOnConclude(code, reason) {
3069
+ const websocket = this[kWebSocket];
3070
+ websocket._closeFrameReceived = true;
3071
+ websocket._closeMessage = reason;
3072
+ websocket._closeCode = code;
3073
+ if (websocket._socket[kWebSocket] === void 0) return;
3074
+ websocket._socket.removeListener("data", socketOnData);
3075
+ process.nextTick(resume, websocket._socket);
3076
+ if (code === 1005) websocket.close();
3077
+ else websocket.close(code, reason);
3078
+ }
3079
+ function receiverOnDrain() {
3080
+ const websocket = this[kWebSocket];
3081
+ if (!websocket.isPaused) websocket._socket.resume();
3082
+ }
3083
+ function receiverOnError(err) {
3084
+ const websocket = this[kWebSocket];
3085
+ if (websocket._socket[kWebSocket] !== void 0) {
3086
+ websocket._socket.removeListener("data", socketOnData);
3087
+ process.nextTick(resume, websocket._socket);
3088
+ websocket.close(err[kStatusCode]);
3089
+ }
3090
+ if (!websocket._errorEmitted) {
3091
+ websocket._errorEmitted = true;
3092
+ websocket.emit("error", err);
3093
+ }
3094
+ }
3095
+ function receiverOnFinish() {
3096
+ this[kWebSocket].emitClose();
3097
+ }
3098
+ function receiverOnMessage(data, isBinary) {
3099
+ this[kWebSocket].emit("message", data, isBinary);
3100
+ }
3101
+ function receiverOnPing(data) {
3102
+ const websocket = this[kWebSocket];
3103
+ if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP);
3104
+ websocket.emit("ping", data);
3105
+ }
3106
+ function receiverOnPong(data) {
3107
+ this[kWebSocket].emit("pong", data);
3108
+ }
3109
+ function resume(stream) {
3110
+ stream.resume();
3111
+ }
3112
+ function senderOnError(err) {
3113
+ const websocket = this[kWebSocket];
3114
+ if (websocket.readyState === WebSocket2.CLOSED) return;
3115
+ if (websocket.readyState === WebSocket2.OPEN) {
3116
+ websocket._readyState = WebSocket2.CLOSING;
3117
+ setCloseTimer(websocket);
3118
+ }
3119
+ this._socket.end();
3120
+ if (!websocket._errorEmitted) {
3121
+ websocket._errorEmitted = true;
3122
+ websocket.emit("error", err);
3123
+ }
3124
+ }
3125
+ function setCloseTimer(websocket) {
3126
+ websocket._closeTimer = setTimeout(
3127
+ websocket._socket.destroy.bind(websocket._socket),
3128
+ websocket._closeTimeout
3129
+ );
3130
+ }
3131
+ function socketOnClose() {
3132
+ const websocket = this[kWebSocket];
3133
+ this.removeListener("close", socketOnClose);
3134
+ this.removeListener("data", socketOnData);
3135
+ this.removeListener("end", socketOnEnd);
3136
+ websocket._readyState = WebSocket2.CLOSING;
3137
+ if (!this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && this._readableState.length !== 0) {
3138
+ const chunk = this.read(this._readableState.length);
3139
+ websocket._receiver.write(chunk);
3140
+ }
3141
+ websocket._receiver.end();
3142
+ this[kWebSocket] = void 0;
3143
+ clearTimeout(websocket._closeTimer);
3144
+ if (websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted) {
3145
+ websocket.emitClose();
3146
+ } else {
3147
+ websocket._receiver.on("error", receiverOnFinish);
3148
+ websocket._receiver.on("finish", receiverOnFinish);
3149
+ }
3150
+ }
3151
+ function socketOnData(chunk) {
3152
+ if (!this[kWebSocket]._receiver.write(chunk)) {
3153
+ this.pause();
3154
+ }
3155
+ }
3156
+ function socketOnEnd() {
3157
+ const websocket = this[kWebSocket];
3158
+ websocket._readyState = WebSocket2.CLOSING;
3159
+ websocket._receiver.end();
3160
+ this.end();
3161
+ }
3162
+ function socketOnError() {
3163
+ const websocket = this[kWebSocket];
3164
+ this.removeListener("error", socketOnError);
3165
+ this.on("error", NOOP);
3166
+ if (websocket) {
3167
+ websocket._readyState = WebSocket2.CLOSING;
3168
+ this.destroy();
3169
+ }
3170
+ }
3171
+ }
3172
+ });
3173
+
3174
+ // node_modules/ws/lib/stream.js
3175
+ var require_stream = __commonJS({
3176
+ "node_modules/ws/lib/stream.js"(exports, module) {
3177
+ "use strict";
3178
+ var WebSocket2 = require_websocket();
3179
+ var { Duplex } = __require("stream");
3180
+ function emitClose(stream) {
3181
+ stream.emit("close");
3182
+ }
3183
+ function duplexOnEnd() {
3184
+ if (!this.destroyed && this._writableState.finished) {
3185
+ this.destroy();
3186
+ }
3187
+ }
3188
+ function duplexOnError(err) {
3189
+ this.removeListener("error", duplexOnError);
3190
+ this.destroy();
3191
+ if (this.listenerCount("error") === 0) {
3192
+ this.emit("error", err);
3193
+ }
3194
+ }
3195
+ function createWebSocketStream2(ws, options) {
3196
+ let terminateOnDestroy = true;
3197
+ const duplex = new Duplex({
3198
+ ...options,
3199
+ autoDestroy: false,
3200
+ emitClose: false,
3201
+ objectMode: false,
3202
+ writableObjectMode: false
3203
+ });
3204
+ ws.on("message", function message(msg, isBinary) {
3205
+ const data = !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;
3206
+ if (!duplex.push(data)) ws.pause();
3207
+ });
3208
+ ws.once("error", function error(err) {
3209
+ if (duplex.destroyed) return;
3210
+ terminateOnDestroy = false;
3211
+ duplex.destroy(err);
3212
+ });
3213
+ ws.once("close", function close() {
3214
+ if (duplex.destroyed) return;
3215
+ duplex.push(null);
3216
+ });
3217
+ duplex._destroy = function(err, callback) {
3218
+ if (ws.readyState === ws.CLOSED) {
3219
+ callback(err);
3220
+ process.nextTick(emitClose, duplex);
3221
+ return;
3222
+ }
3223
+ let called = false;
3224
+ ws.once("error", function error(err2) {
3225
+ called = true;
3226
+ callback(err2);
3227
+ });
3228
+ ws.once("close", function close() {
3229
+ if (!called) callback(err);
3230
+ process.nextTick(emitClose, duplex);
3231
+ });
3232
+ if (terminateOnDestroy) ws.terminate();
3233
+ };
3234
+ duplex._final = function(callback) {
3235
+ if (ws.readyState === ws.CONNECTING) {
3236
+ ws.once("open", function open() {
3237
+ duplex._final(callback);
3238
+ });
3239
+ return;
3240
+ }
3241
+ if (ws._socket === null) return;
3242
+ if (ws._socket._writableState.finished) {
3243
+ callback();
3244
+ if (duplex._readableState.endEmitted) duplex.destroy();
3245
+ } else {
3246
+ ws._socket.once("finish", function finish() {
3247
+ callback();
3248
+ });
3249
+ ws.close();
3250
+ }
3251
+ };
3252
+ duplex._read = function() {
3253
+ if (ws.isPaused) ws.resume();
3254
+ };
3255
+ duplex._write = function(chunk, encoding, callback) {
3256
+ if (ws.readyState === ws.CONNECTING) {
3257
+ ws.once("open", function open() {
3258
+ duplex._write(chunk, encoding, callback);
3259
+ });
3260
+ return;
3261
+ }
3262
+ ws.send(chunk, callback);
3263
+ };
3264
+ duplex.on("end", duplexOnEnd);
3265
+ duplex.on("error", duplexOnError);
3266
+ return duplex;
3267
+ }
3268
+ module.exports = createWebSocketStream2;
3269
+ }
3270
+ });
3271
+
3272
+ // node_modules/ws/lib/subprotocol.js
3273
+ var require_subprotocol = __commonJS({
3274
+ "node_modules/ws/lib/subprotocol.js"(exports, module) {
3275
+ "use strict";
3276
+ var { tokenChars } = require_validation();
3277
+ function parse(header) {
3278
+ const protocols = /* @__PURE__ */ new Set();
3279
+ let start = -1;
3280
+ let end = -1;
3281
+ let i = 0;
3282
+ for (i; i < header.length; i++) {
3283
+ const code = header.charCodeAt(i);
3284
+ if (end === -1 && tokenChars[code] === 1) {
3285
+ if (start === -1) start = i;
3286
+ } else if (i !== 0 && (code === 32 || code === 9)) {
3287
+ if (end === -1 && start !== -1) end = i;
3288
+ } else if (code === 44) {
3289
+ if (start === -1) {
3290
+ throw new SyntaxError(`Unexpected character at index ${i}`);
3291
+ }
3292
+ if (end === -1) end = i;
3293
+ const protocol2 = header.slice(start, end);
3294
+ if (protocols.has(protocol2)) {
3295
+ throw new SyntaxError(`The "${protocol2}" subprotocol is duplicated`);
3296
+ }
3297
+ protocols.add(protocol2);
3298
+ start = end = -1;
3299
+ } else {
3300
+ throw new SyntaxError(`Unexpected character at index ${i}`);
3301
+ }
3302
+ }
3303
+ if (start === -1 || end !== -1) {
3304
+ throw new SyntaxError("Unexpected end of input");
3305
+ }
3306
+ const protocol = header.slice(start, i);
3307
+ if (protocols.has(protocol)) {
3308
+ throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
3309
+ }
3310
+ protocols.add(protocol);
3311
+ return protocols;
3312
+ }
3313
+ module.exports = { parse };
3314
+ }
3315
+ });
3316
+
3317
+ // node_modules/ws/lib/websocket-server.js
3318
+ var require_websocket_server = __commonJS({
3319
+ "node_modules/ws/lib/websocket-server.js"(exports, module) {
3320
+ "use strict";
3321
+ var EventEmitter = __require("events");
3322
+ var http = __require("http");
3323
+ var { Duplex } = __require("stream");
3324
+ var { createHash } = __require("crypto");
3325
+ var extension2 = require_extension();
3326
+ var PerMessageDeflate2 = require_permessage_deflate();
3327
+ var subprotocol2 = require_subprotocol();
3328
+ var WebSocket2 = require_websocket();
3329
+ var { CLOSE_TIMEOUT, GUID, kWebSocket } = require_constants();
3330
+ var keyRegex = /^[+/0-9A-Za-z]{22}==$/;
3331
+ var RUNNING = 0;
3332
+ var CLOSING = 1;
3333
+ var CLOSED = 2;
3334
+ var WebSocketServer2 = class extends EventEmitter {
3335
+ /**
3336
+ * Create a `WebSocketServer` instance.
3337
+ *
3338
+ * @param {Object} options Configuration options
3339
+ * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
3340
+ * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
3341
+ * multiple times in the same tick
3342
+ * @param {Boolean} [options.autoPong=true] Specifies whether or not to
3343
+ * automatically send a pong in response to a ping
3344
+ * @param {Number} [options.backlog=511] The maximum length of the queue of
3345
+ * pending connections
3346
+ * @param {Boolean} [options.clientTracking=true] Specifies whether or not to
3347
+ * track clients
3348
+ * @param {Number} [options.closeTimeout=30000] Duration in milliseconds to
3349
+ * wait for the closing handshake to finish after `websocket.close()` is
3350
+ * called
3351
+ * @param {Function} [options.handleProtocols] A hook to handle protocols
3352
+ * @param {String} [options.host] The hostname where to bind the server
3353
+ * @param {Number} [options.maxBufferedChunks=1048576] The maximum number of
3354
+ * buffered data chunks
3355
+ * @param {Number} [options.maxFragments=131072] The maximum number of message
3356
+ * fragments
3357
+ * @param {Number} [options.maxPayload=104857600] The maximum allowed message
3358
+ * size
3359
+ * @param {Boolean} [options.noServer=false] Enable no server mode
3360
+ * @param {String} [options.path] Accept only connections matching this path
3361
+ * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable
3362
+ * permessage-deflate
3363
+ * @param {Number} [options.port] The port where to bind the server
3364
+ * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S
3365
+ * server to use
3366
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
3367
+ * not to skip UTF-8 validation for text and close messages
3368
+ * @param {Function} [options.verifyClient] A hook to reject connections
3369
+ * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`
3370
+ * class to use. It must be the `WebSocket` class or class that extends it
3371
+ * @param {Function} [callback] A listener for the `listening` event
3372
+ */
3373
+ constructor(options, callback) {
3374
+ super();
3375
+ options = {
3376
+ allowSynchronousEvents: true,
3377
+ autoPong: true,
3378
+ maxBufferedChunks: 1024 * 1024,
3379
+ maxFragments: 128 * 1024,
3380
+ maxPayload: 100 * 1024 * 1024,
3381
+ skipUTF8Validation: false,
3382
+ perMessageDeflate: false,
3383
+ handleProtocols: null,
3384
+ clientTracking: true,
3385
+ closeTimeout: CLOSE_TIMEOUT,
3386
+ verifyClient: null,
3387
+ noServer: false,
3388
+ backlog: null,
3389
+ // use default (511 as implemented in net.js)
3390
+ server: null,
3391
+ host: null,
3392
+ path: null,
3393
+ port: null,
3394
+ WebSocket: WebSocket2,
3395
+ ...options
3396
+ };
3397
+ if (options.port == null && !options.server && !options.noServer || options.port != null && (options.server || options.noServer) || options.server && options.noServer) {
3398
+ throw new TypeError(
3399
+ 'One and only one of the "port", "server", or "noServer" options must be specified'
3400
+ );
3401
+ }
3402
+ if (options.port != null) {
3403
+ this._server = http.createServer((req, res) => {
3404
+ const body = http.STATUS_CODES[426];
3405
+ res.writeHead(426, {
3406
+ "Content-Length": body.length,
3407
+ "Content-Type": "text/plain"
3408
+ });
3409
+ res.end(body);
3410
+ });
3411
+ this._server.listen(
3412
+ options.port,
3413
+ options.host,
3414
+ options.backlog,
3415
+ callback
3416
+ );
3417
+ } else if (options.server) {
3418
+ this._server = options.server;
3419
+ }
3420
+ if (this._server) {
3421
+ const emitConnection = this.emit.bind(this, "connection");
3422
+ this._removeListeners = addListeners(this._server, {
3423
+ listening: this.emit.bind(this, "listening"),
3424
+ error: this.emit.bind(this, "error"),
3425
+ upgrade: (req, socket, head) => {
3426
+ this.handleUpgrade(req, socket, head, emitConnection);
3427
+ }
3428
+ });
3429
+ }
3430
+ if (options.perMessageDeflate === true) options.perMessageDeflate = {};
3431
+ if (options.clientTracking) {
3432
+ this.clients = /* @__PURE__ */ new Set();
3433
+ this._shouldEmitClose = false;
3434
+ }
3435
+ this.options = options;
3436
+ this._state = RUNNING;
3437
+ }
3438
+ /**
3439
+ * Returns the bound address, the address family name, and port of the server
3440
+ * as reported by the operating system if listening on an IP socket.
3441
+ * If the server is listening on a pipe or UNIX domain socket, the name is
3442
+ * returned as a string.
3443
+ *
3444
+ * @return {(Object|String|null)} The address of the server
3445
+ * @public
3446
+ */
3447
+ address() {
3448
+ if (this.options.noServer) {
3449
+ throw new Error('The server is operating in "noServer" mode');
3450
+ }
3451
+ if (!this._server) return null;
3452
+ return this._server.address();
3453
+ }
3454
+ /**
3455
+ * Stop the server from accepting new connections and emit the `'close'` event
3456
+ * when all existing connections are closed.
3457
+ *
3458
+ * @param {Function} [cb] A one-time listener for the `'close'` event
3459
+ * @public
3460
+ */
3461
+ close(cb) {
3462
+ if (this._state === CLOSED) {
3463
+ if (cb) {
3464
+ this.once("close", () => {
3465
+ cb(new Error("The server is not running"));
3466
+ });
3467
+ }
3468
+ process.nextTick(emitClose, this);
3469
+ return;
3470
+ }
3471
+ if (cb) this.once("close", cb);
3472
+ if (this._state === CLOSING) return;
3473
+ this._state = CLOSING;
3474
+ if (this.options.noServer || this.options.server) {
3475
+ if (this._server) {
3476
+ this._removeListeners();
3477
+ this._removeListeners = this._server = null;
3478
+ }
3479
+ if (this.clients) {
3480
+ if (!this.clients.size) {
3481
+ process.nextTick(emitClose, this);
3482
+ } else {
3483
+ this._shouldEmitClose = true;
3484
+ }
3485
+ } else {
3486
+ process.nextTick(emitClose, this);
3487
+ }
3488
+ } else {
3489
+ const server = this._server;
3490
+ this._removeListeners();
3491
+ this._removeListeners = this._server = null;
3492
+ server.close(() => {
3493
+ emitClose(this);
3494
+ });
3495
+ }
3496
+ }
3497
+ /**
3498
+ * See if a given request should be handled by this server instance.
3499
+ *
3500
+ * @param {http.IncomingMessage} req Request object to inspect
3501
+ * @return {Boolean} `true` if the request is valid, else `false`
3502
+ * @public
3503
+ */
3504
+ shouldHandle(req) {
3505
+ if (this.options.path) {
3506
+ const index = req.url.indexOf("?");
3507
+ const pathname = index !== -1 ? req.url.slice(0, index) : req.url;
3508
+ if (pathname !== this.options.path) return false;
3509
+ }
3510
+ return true;
3511
+ }
3512
+ /**
3513
+ * Handle a HTTP Upgrade request.
3514
+ *
3515
+ * @param {http.IncomingMessage} req The request object
3516
+ * @param {Duplex} socket The network socket between the server and client
3517
+ * @param {Buffer} head The first packet of the upgraded stream
3518
+ * @param {Function} cb Callback
3519
+ * @public
3520
+ */
3521
+ handleUpgrade(req, socket, head, cb) {
3522
+ socket.on("error", socketOnError);
3523
+ const key = req.headers["sec-websocket-key"];
3524
+ const upgrade = req.headers.upgrade;
3525
+ const version = +req.headers["sec-websocket-version"];
3526
+ if (req.method !== "GET") {
3527
+ const message = "Invalid HTTP method";
3528
+ abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);
3529
+ return;
3530
+ }
3531
+ if (upgrade === void 0 || upgrade.toLowerCase() !== "websocket") {
3532
+ const message = "Invalid Upgrade header";
3533
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3534
+ return;
3535
+ }
3536
+ if (key === void 0 || !keyRegex.test(key)) {
3537
+ const message = "Missing or invalid Sec-WebSocket-Key header";
3538
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3539
+ return;
3540
+ }
3541
+ if (version !== 13 && version !== 8) {
3542
+ const message = "Missing or invalid Sec-WebSocket-Version header";
3543
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message, {
3544
+ "Sec-WebSocket-Version": "13, 8"
3545
+ });
3546
+ return;
3547
+ }
3548
+ if (!this.shouldHandle(req)) {
3549
+ abortHandshake(socket, 400);
3550
+ return;
3551
+ }
3552
+ const secWebSocketProtocol = req.headers["sec-websocket-protocol"];
3553
+ let protocols = /* @__PURE__ */ new Set();
3554
+ if (secWebSocketProtocol !== void 0) {
3555
+ try {
3556
+ protocols = subprotocol2.parse(secWebSocketProtocol);
3557
+ } catch (err) {
3558
+ const message = "Invalid Sec-WebSocket-Protocol header";
3559
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3560
+ return;
3561
+ }
3562
+ }
3563
+ const secWebSocketExtensions = req.headers["sec-websocket-extensions"];
3564
+ const extensions = {};
3565
+ if (this.options.perMessageDeflate && secWebSocketExtensions !== void 0) {
3566
+ const perMessageDeflate = new PerMessageDeflate2({
3567
+ ...this.options.perMessageDeflate,
3568
+ isServer: true,
3569
+ maxPayload: this.options.maxPayload
3570
+ });
3571
+ try {
3572
+ const offers = extension2.parse(secWebSocketExtensions);
3573
+ if (offers[PerMessageDeflate2.extensionName]) {
3574
+ perMessageDeflate.accept(offers[PerMessageDeflate2.extensionName]);
3575
+ extensions[PerMessageDeflate2.extensionName] = perMessageDeflate;
3576
+ }
3577
+ } catch (err) {
3578
+ const message = "Invalid or unacceptable Sec-WebSocket-Extensions header";
3579
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3580
+ return;
3581
+ }
3582
+ }
3583
+ if (this.options.verifyClient) {
3584
+ const info = {
3585
+ origin: req.headers[`${version === 8 ? "sec-websocket-origin" : "origin"}`],
3586
+ secure: !!(req.socket.authorized || req.socket.encrypted),
3587
+ req
3588
+ };
3589
+ if (this.options.verifyClient.length === 2) {
3590
+ this.options.verifyClient(info, (verified, code, message, headers) => {
3591
+ if (!verified) {
3592
+ return abortHandshake(socket, code || 401, message, headers);
3593
+ }
3594
+ this.completeUpgrade(
3595
+ extensions,
3596
+ key,
3597
+ protocols,
3598
+ req,
3599
+ socket,
3600
+ head,
3601
+ cb
3602
+ );
3603
+ });
3604
+ return;
3605
+ }
3606
+ if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);
3607
+ }
3608
+ this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
3609
+ }
3610
+ /**
3611
+ * Upgrade the connection to WebSocket.
3612
+ *
3613
+ * @param {Object} extensions The accepted extensions
3614
+ * @param {String} key The value of the `Sec-WebSocket-Key` header
3615
+ * @param {Set} protocols The subprotocols
3616
+ * @param {http.IncomingMessage} req The request object
3617
+ * @param {Duplex} socket The network socket between the server and client
3618
+ * @param {Buffer} head The first packet of the upgraded stream
3619
+ * @param {Function} cb Callback
3620
+ * @throws {Error} If called more than once with the same socket
3621
+ * @private
3622
+ */
3623
+ completeUpgrade(extensions, key, protocols, req, socket, head, cb) {
3624
+ if (!socket.readable || !socket.writable) return socket.destroy();
3625
+ if (socket[kWebSocket]) {
3626
+ throw new Error(
3627
+ "server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration"
3628
+ );
3629
+ }
3630
+ if (this._state > RUNNING) return abortHandshake(socket, 503);
3631
+ const digest = createHash("sha1").update(key + GUID).digest("base64");
3632
+ const headers = [
3633
+ "HTTP/1.1 101 Switching Protocols",
3634
+ "Upgrade: websocket",
3635
+ "Connection: Upgrade",
3636
+ `Sec-WebSocket-Accept: ${digest}`
3637
+ ];
3638
+ const ws = new this.options.WebSocket(null, void 0, this.options);
3639
+ if (protocols.size) {
3640
+ const protocol = this.options.handleProtocols ? this.options.handleProtocols(protocols, req) : protocols.values().next().value;
3641
+ if (protocol) {
3642
+ headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
3643
+ ws._protocol = protocol;
3644
+ }
3645
+ }
3646
+ if (extensions[PerMessageDeflate2.extensionName]) {
3647
+ const params = extensions[PerMessageDeflate2.extensionName].params;
3648
+ const value = extension2.format({
3649
+ [PerMessageDeflate2.extensionName]: [params]
3650
+ });
3651
+ headers.push(`Sec-WebSocket-Extensions: ${value}`);
3652
+ ws._extensions = extensions;
3653
+ }
3654
+ this.emit("headers", headers, req);
3655
+ socket.write(headers.concat("\r\n").join("\r\n"));
3656
+ socket.removeListener("error", socketOnError);
3657
+ ws.setSocket(socket, head, {
3658
+ allowSynchronousEvents: this.options.allowSynchronousEvents,
3659
+ maxBufferedChunks: this.options.maxBufferedChunks,
3660
+ maxFragments: this.options.maxFragments,
3661
+ maxPayload: this.options.maxPayload,
3662
+ skipUTF8Validation: this.options.skipUTF8Validation
3663
+ });
3664
+ if (this.clients) {
3665
+ this.clients.add(ws);
3666
+ ws.on("close", () => {
3667
+ this.clients.delete(ws);
3668
+ if (this._shouldEmitClose && !this.clients.size) {
3669
+ process.nextTick(emitClose, this);
3670
+ }
3671
+ });
3672
+ }
3673
+ cb(ws, req);
3674
+ }
3675
+ };
3676
+ module.exports = WebSocketServer2;
3677
+ function addListeners(server, map) {
3678
+ for (const event of Object.keys(map)) server.on(event, map[event]);
3679
+ return function removeListeners() {
3680
+ for (const event of Object.keys(map)) {
3681
+ server.removeListener(event, map[event]);
3682
+ }
3683
+ };
3684
+ }
3685
+ function emitClose(server) {
3686
+ server._state = CLOSED;
3687
+ server.emit("close");
3688
+ }
3689
+ function socketOnError() {
3690
+ this.destroy();
3691
+ }
3692
+ function abortHandshake(socket, code, message, headers) {
3693
+ message = message || http.STATUS_CODES[code];
3694
+ headers = {
3695
+ Connection: "close",
3696
+ "Content-Type": "text/html",
3697
+ "Content-Length": Buffer.byteLength(message),
3698
+ ...headers
3699
+ };
3700
+ socket.once("finish", socket.destroy);
3701
+ socket.end(
3702
+ `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r
3703
+ ` + Object.keys(headers).map((h) => `${h}: ${headers[h]}`).join("\r\n") + "\r\n\r\n" + message
3704
+ );
3705
+ }
3706
+ function abortHandshakeOrEmitwsClientError(server, req, socket, code, message, headers) {
3707
+ if (server.listenerCount("wsClientError")) {
3708
+ const err = new Error(message);
3709
+ Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);
3710
+ server.emit("wsClientError", err, socket, req);
3711
+ } else {
3712
+ abortHandshake(socket, code, message, headers);
3713
+ }
3714
+ }
3715
+ }
3716
+ });
3717
+
3718
+ // src/env.ts
3719
+ var envFile = process.env.ENV_FILE || ".env";
3720
+ try {
3721
+ process.loadEnvFile?.(envFile);
3722
+ } catch {
3723
+ }
3724
+
3725
+ // src/daemon/index.ts
3726
+ import os4 from "node:os";
3727
+ import fs3 from "node:fs";
3728
+ import path7 from "node:path";
3729
+
3730
+ // node_modules/ws/wrapper.mjs
3731
+ var import_stream = __toESM(require_stream(), 1);
3732
+ var import_extension = __toESM(require_extension(), 1);
3733
+ var import_permessage_deflate = __toESM(require_permessage_deflate(), 1);
3734
+ var import_receiver = __toESM(require_receiver(), 1);
3735
+ var import_sender = __toESM(require_sender(), 1);
3736
+ var import_subprotocol = __toESM(require_subprotocol(), 1);
3737
+ var import_websocket = __toESM(require_websocket(), 1);
3738
+ var import_websocket_server = __toESM(require_websocket_server(), 1);
3739
+ var wrapper_default = import_websocket.default;
3740
+
3741
+ // src/log.ts
3742
+ import fs from "node:fs";
3743
+ import path2 from "node:path";
3744
+
3745
+ // src/paths.ts
3746
+ import os from "node:os";
3747
+ import path from "node:path";
3748
+ var openTagHome = () => process.env.OPEN_TAG_HOME ?? path.join(os.homedir(), ".open-tag");
3749
+ var agentsDir = () => path.join(openTagHome(), "agents");
3750
+ var binDir = () => path.join(openTagHome(), "bin");
3751
+ var machineIdFile = () => path.join(openTagHome(), "machine-id");
3752
+ var logsDir = () => process.env.OPEN_TAG_LOG_DIR ?? path.join(openTagHome(), "logs");
3753
+
3754
+ // src/log.ts
3755
+ var LOG_DIR = logsDir();
3756
+ try {
3757
+ fs.mkdirSync(LOG_DIR, { recursive: true });
3758
+ } catch {
3759
+ }
3760
+ var order = { debug: 10, info: 20, warn: 30, error: 40 };
3761
+ var MIN = order[process.env.OPEN_TAG_LOG_LEVEL ?? "debug"] ?? 10;
3762
+ function createLogger(component) {
3763
+ const file = path2.join(LOG_DIR, `${component.split(":")[0]}.log`);
3764
+ function write(level, msg, fields) {
3765
+ if (order[level] < MIN) return;
3766
+ const rec = { t: (/* @__PURE__ */ new Date()).toISOString(), level, comp: component, msg, ...fields ?? {} };
3767
+ try {
3768
+ fs.appendFileSync(file, JSON.stringify(rec) + "\n");
3769
+ } catch {
3770
+ }
3771
+ const extra = fields && Object.keys(fields).length ? " " + safeJson(fields) : "";
3772
+ const line = `${rec.t} ${level.toUpperCase().padEnd(5)} [${component}] ${msg}${extra}`;
3773
+ try {
3774
+ process.stderr.write(line + "\n");
3775
+ } catch {
3776
+ }
3777
+ }
3778
+ return {
3779
+ debug: (m, f) => write("debug", m, f),
3780
+ info: (m, f) => write("info", m, f),
3781
+ warn: (m, f) => write("warn", m, f),
3782
+ error: (m, f) => write("error", m, f),
3783
+ child: (sub) => createLogger(`${component}:${sub}`)
3784
+ };
3785
+ }
3786
+ function safeJson(o) {
3787
+ try {
3788
+ return JSON.stringify(o, (_k, v) => typeof v === "string" && v.length > 300 ? v.slice(0, 300) + "\u2026" : v);
3789
+ } catch {
3790
+ return "[unserializable]";
3791
+ }
3792
+ }
3793
+
3794
+ // src/daemon/connection.ts
3795
+ var Connection = class {
3796
+ constructor(url, key, onMsg, onOpen) {
3797
+ this.url = url;
3798
+ this.key = key;
3799
+ this.onMsg = onMsg;
3800
+ this.onOpen = onOpen;
3801
+ }
3802
+ url;
3803
+ key;
3804
+ onMsg;
3805
+ onOpen;
3806
+ ws = null;
3807
+ delay = 1e3;
3808
+ timer = null;
3809
+ should = true;
3810
+ log = createLogger("daemon:conn");
3811
+ connect() {
3812
+ this.should = true;
3813
+ this.doConnect();
3814
+ }
3815
+ send(m) {
3816
+ if (this.ws?.readyState === wrapper_default.OPEN) this.ws.send(JSON.stringify(m));
3817
+ }
3818
+ close() {
3819
+ this.should = false;
3820
+ if (this.timer) clearTimeout(this.timer);
3821
+ this.ws?.close();
3822
+ }
3823
+ doConnect() {
3824
+ if (!this.should) return;
3825
+ const wsUrl = this.url.replace(/^http/, "ws") + `/daemon/connect?key=${encodeURIComponent(this.key)}`;
3826
+ this.log.info("connecting", { url: this.url });
3827
+ this.ws = new wrapper_default(wsUrl);
3828
+ this.ws.on("open", () => {
3829
+ this.delay = 1e3;
3830
+ this.log.info("connected");
3831
+ this.onOpen();
3832
+ });
3833
+ this.ws.on("message", (d) => {
3834
+ let m;
3835
+ try {
3836
+ m = JSON.parse(d.toString());
3837
+ } catch {
3838
+ return;
3839
+ }
3840
+ this.onMsg(m);
3841
+ });
3842
+ this.ws.on("close", () => {
3843
+ this.log.warn("disconnected");
3844
+ this.scheduleReconnect();
3845
+ });
3846
+ this.ws.on("error", (e) => this.log.error("ws error", { detail: String(e?.message ?? e) }));
3847
+ }
3848
+ scheduleReconnect() {
3849
+ if (!this.should || this.timer) return;
3850
+ this.log.info("reconnecting", { ms: this.delay });
3851
+ this.timer = setTimeout(() => {
3852
+ this.timer = null;
3853
+ this.doConnect();
3854
+ }, this.delay);
3855
+ this.delay = Math.min(this.delay * 2, 3e4);
3856
+ }
3857
+ };
3858
+
3859
+ // src/daemon/agentManager.ts
3860
+ import { mkdir, writeFile, readFile, access, rm } from "node:fs/promises";
3861
+ import path5 from "node:path";
3862
+ import os2 from "node:os";
3863
+
3864
+ // src/daemon/prompt.ts
3865
+ function buildSystemPrompt(c) {
3866
+ return `You are "${c.displayName}", an AI agent in open-tag \u2014 a collaborative workspace where humans and AI agents (possibly on different machines) work together over a shared message bus. You are a persistent colleague: started, slept when idle, woken when messaged. Your workspace and MEMORY.md persist across turns.
3867
+
3868
+ ## Current Runtime Context
3869
+ This is authoritative context injected by open-tag. Do NOT infer identity from hostname or cwd.
3870
+ - Agent ID: ${c.agentId}
3871
+ - Server ID: ${c.serverId}
3872
+ - Hostname: ${c.hostname}
3873
+ - OS: ${c.os}
3874
+ - Workspace: ${c.workspace}
3875
+ - Your @handle: @${c.name}
3876
+
3877
+ ## Communication \u2014 the \`open-tag\` CLI ONLY
3878
+ A local \`open-tag\` command is on your PATH. Use ONLY it to communicate, via your shell/bash tool, ONE command per call:
3879
+ - \`open-tag message check\` \u2014 non-blocking: read new messages addressed to you. Run it at the start and after notifications.
3880
+ - \`open-tag message send --target <t>\` \u2014 send a message; the BODY is read from STDIN (use a heredoc).
3881
+ - \`open-tag message read --channel <t> [--limit N]\` \u2014 read history.
3882
+ - \`open-tag server info\` \u2014 list channels / agents / humans.
3883
+ - \`open-tag channel join --target "#name"\` \u2014 join a public channel.
3884
+ - \`open-tag task list --channel <t>\` \xB7 \`open-tag task claim --message-id <id>\` \xB7 \`open-tag task update --message-id <id> --status <todo|in_progress|in_review|done>\` \xB7 \`open-tag task create --channel <t> --title <t>\`(delegate a task)
3885
+ - **Threads (no dedicated thread command \u2014 use message send/read with a thread-suffix target)**: reply to / open a thread = \`open-tag message send --target "#channel:shortid"\` (suffix shortid = the 8-char short id from the \`msg=\` field in the message header; if it does not exist, a thread is created automatically); read a thread = \`open-tag message read --channel "#channel:shortid"\`; stop receiving deliveries for a thread = \`open-tag thread unfollow --target "#channel:shortid"\` (only when work in that thread is clearly done or irrelevant). Threads cannot be nested.
3886
+ - \`open-tag message react --message-id <id> --emoji <e> [--remove]\`(emoji reaction) \xB7 \`open-tag message search --query <q>\`(search channels you are in)
3887
+ - \`open-tag attachment upload --file <path> --channel <t>\`(upload a file, returns an id; then use \`message send --attach <id>\`) \xB7 \`open-tag attachment view --id <id>\`(downloads the attachment to the local \`attachments/\` directory and prints its local path for inspection \u2014 this command only handles the download and path; how you open it is up to your local tools)
3888
+ - \`open-tag message resolve --id <id>\`(verify that a cited message id is real \u2014 always resolve before referencing, never invent ids from memory) \xB7 \`open-tag channel members --channel <t>\` \xB7 \`open-tag channel leave --target "#name"\` \xB7 \`open-tag task unclaim --message-id <id>\`
3889
+ - \`open-tag profile show [--handle @name]\`(view your own or another person's profile) \xB7 \`open-tag profile update [--display-name <n>] [--description <t>] [--avatar-url pixel:random:<seed>]\`(update your own profile)
3890
+ - \`open-tag reminder schedule --content <t> --in <seconds> [--anchor <msgId>] [--recurring <seconds>]\`(schedule a future wakeup for yourself \u2014 at the scheduled time the system will @-mention you to wake you up) \xB7 \`open-tag reminder list/cancel/snooze\`. For anything that depends on a future state, use a reminder instead of busy-waiting.
3891
+ - \`open-tag action prepare --target <t>\` \u2014 prepare an action card for a human to commit (B-mode quick-commit). You do NOT have permission to create channels/agents yourself; instead pipe the action JSON on STDIN and post a card the human clicks to execute under their own identity. Variants: \`channel:create\` (\`{"type":"channel:create","name":"x","description":"...","visibility":"public"}\`), \`agent:create\` (\`{"type":"agent:create","name":"y","description":"..."}\`). Use when a human asks you to set up a channel/agent \u2014 propose it as a card, don't ask them to do it manually.
3892
+
3893
+ Targets: \`#channel\`, \`dm:@name\`, thread \`#channel:shortid\`. Send the body via stdin heredoc:
3894
+ \`\`\`bash
3895
+ open-tag message send --target "#all" <<'MSG'
3896
+ Your reply. Quotes, $vars, \`backticks\`, code blocks are all safe here.
3897
+ MSG
3898
+ \`\`\`
3899
+ CRITICAL: Text you print outside a \`open-tag\` command is NOT delivered to anyone. Only \`open-tag message send\` reaches people. Do not use curl/echo to talk \u2014 only the \`open-tag\` CLI.
3900
+
3901
+ FRESHNESS HOLD (collaboration safety): if new messages arrived in that target since you last read it, \`send\` does NOT post \u2014 it saves your text as a draft and shows you the newer messages ("Freshness hold: \u2026"). Read that bounded context, then EITHER revise (run \`send --target <t>\` again with new content \u2014 e.g. drop what a teammate already covered, to avoid redundant replies) OR commit unchanged with \`open-tag message send --send-draft --target <t>\`. This is how teammates avoid talking over each other \u2014 use it: if someone already answered, shorten or skip your reply.
3902
+
3903
+ ## Received message format
3904
+ \`[target=<id> msg=<shortid> time=<iso> type=human|agent|system] @sender: content\`
3905
+ Reuse the \`target=\` value when replying so it lands in the right channel/DM/thread. @mention people by their @handle. \`msg=\` is the 8-char short id \u2014 use it as a thread suffix (\`#channel:shortid\`) to start/reply in a thread, and pass it to \`open-tag message resolve\` to verify a cited id is real. \`type=system\` messages announce state changes (task events, reminders) \u2014 don't reply unless they clearly ask you to act.
3906
+
3907
+ ### Formatting \u2014 so refs/links render
3908
+ open-tag auto-renders these **bare-text** tokens into clickable refs; write them as plain words, NOT wrapped in backticks (code spans are literal, won't render):
3909
+ - \`@handle\` \u2192 user/agent \xB7 \`#channel\` \u2192 channel \xB7 \`#channel:shortid\` \u2192 thread \xB7 \`task #N\` \u2192 task (write "task #N", not bare "#N").
3910
+ - **URL next to CJK/non-ASCII punctuation**: wrap it in \`<url>\` or \`[text](url)\`, else the punctuation gets swallowed into the link. Wrong: \`env:http://x:3000,see\` \u2192 Right: \`env:<http://x:3000>,see\`.
3911
+
3912
+ ### Citing prior discussion
3913
+ When someone refers to earlier discussion you don't have in context, first \`open-tag message search --query <q>\` + \`open-tag message read\` (use \`--around <id>\` to jump to a message's surrounding context) to find the original thread/decision before answering \u2014 then summarize it **with the source**, or say explicitly you couldn't find it. Don't invent prior context.
3914
+
3915
+ ## Channels & people
3916
+ Run \`open-tag server info\` to see every channel in this server (with its description and whether you've joined), plus the other agents and humans \u2014 this is how you learn where you are and who you can talk to. Don't assume which channels or teammates exist; check it.
3917
+ - A public channel may show \`joined: false\`. You can still inspect it with \`open-tag message read --channel "#name"\` and \`open-tag channel members --channel "#name"\`, but you cannot post there or receive ordinary delivery until you join with \`open-tag channel join --target "#name"\`. Leave a joined channel with \`open-tag channel leave --target "#name"\`.
3918
+
3919
+ ### Channel awareness
3920
+ Each channel has a **name** and optionally a **description** that define its purpose (both shown by \`open-tag server info\`). Respect them:
3921
+ - **Reply in context** \u2014 answer in the channel/thread the message came from (reuse its \`target=\`).
3922
+ - **Stay on topic** \u2014 when proactively posting results or updates, use the channel most relevant to the work; don't scatter across unrelated channels.
3923
+ - **If you're unsure what a channel is for or where something belongs, run \`open-tag server info\` to review channel descriptions before posting.**
3924
+ - **Private channels are confidential** \u2014 if a channel is private, treat its name / members / content as private to that channel; never disclose it in other channels, DMs, summaries, or task reports unless a human explicitly asks within that authorized context.
3925
+
3926
+ ## Tasks
3927
+ When a message asks you to DO something (fix a bug, write code, investigate) \u2014 that's work. **Claim it before you start** (\`open-tag task claim --message-id <id>\`); if the claim fails someone else has it, move on. Just answering a question needs no claim. Status flow: \`todo \u2192 in_progress \u2192 in_review \u2192 done\`. When done, set \`in_review\` so a human can validate; after approval set \`done\`. Reuse existing tasks/threads instead of creating duplicates \u2014 only \`task create\` for genuinely new work. Post progress in the task's thread (\`--target "#channel:msgShortid"\`).
3928
+ When splitting a big task into subtasks, structure them for **parallel** work: group by phase with clear labels ("Phase 1: \u2026") when there are real dependencies; prefer independent subtasks that don't block each other; avoid sequential chains that force agents to work one-at-a-time.
3929
+
3930
+ ## Etiquette & safety
3931
+ - **Respect ongoing conversations.** If two people are going back-and-forth, their follow-ups are for each other \u2014 only join if @mentioned or clearly addressed. Don't insert yourself when not @-ed (decide relevance, default to staying idle).
3932
+ - **Only the person who did the work reports on it.** Don't echo or summarize someone else's task/PR.
3933
+ - **Before stopping, clear blockers you own** \u2014 if you owe a specific reply/handoff/decision blocking someone, send one minimal message first. Otherwise skip idle narration (don't broadcast that you're waiting/idle).
3934
+ - **Credential hygiene (CRITICAL):** NEVER paste credentials (\`sk_agent_*\`, \`sk_machine_*\`, JWTs, \`.env\`, tokens) into public channels. DMs/private channels only for authorized secret handoff. If a tool output contains credential-shaped strings, redact to \`sk_agent_<redacted>\` before posting publicly.
3935
+
3936
+ ## Startup sequence
3937
+ 1. Run \`open-tag message check\` to see anything waiting.
3938
+ 2. Read \`MEMORY.md\` in your cwd for your role and context.
3939
+ 3. If there is a message, handle it and reply with \`open-tag message send\`. If it requires real work (code/tools), claim it first with \`open-tag task claim\`.
3940
+ 4. Finish ALL the work, report the result. New messages are delivered into your session automatically \u2014 you do not need to poll.
3941
+ 5. **Before you stop, update your memory if you learned anything durable** \u2014 a decision you made, a fact about the project/people, what you were mid-way through. Write it into \`MEMORY.md\` (keep the index current) or \`notes/\` (details). This is the ONLY thing that survives context compaction; if you skip it, after a compaction you'll wake up as a blank slate. Skip only for trivial one-off replies that taught you nothing.
3942
+
3943
+ ## Communication style
3944
+ People can't see your reasoning. So: when you get a task, acknowledge it and briefly outline your plan before starting; for multi-step work send short progress updates ("step 2/3\u2026"); summarize when done. One or two sentences \u2014 don't flood the channel.
3945
+
3946
+ ## Workspace & memory
3947
+ Your cwd is your persistent workspace \u2014 everything you write survives sleep, restart, and context compaction.
3948
+
3949
+ \`MEMORY.md\` is your memory index \u2014 the FIRST file you read on every startup (including after compaction). Keep it as a self-sufficient table of contents, e.g.:
3950
+ \`\`\`markdown
3951
+ # ${c.displayName}
3952
+ ## Role
3953
+ <your role, evolved over time>
3954
+ ## Key knowledge
3955
+ - notes/user-preferences.md \u2014 how the user likes things done, conventions
3956
+ - notes/channels.md \u2014 what each channel is about + ongoing work per channel
3957
+ - notes/work-log.md \u2014 decisions made and why, problems solved
3958
+ - notes/<domain>.md \u2014 domain-specific knowledge
3959
+ ## Active context
3960
+ - Currently working on: <brief>
3961
+ - Last interaction: <brief>
3962
+ \`\`\`
3963
+ Put detailed knowledge in \`notes/\`; write it proactively when you learn something (don't wait to be asked), and keep the MEMORY.md index current.
3964
+
3965
+ ## Compaction safety (CRITICAL)
3966
+ Your context is periodically compressed to stay within limits \u2014 you lose in-context conversation history, but MEMORY.md is always re-read. Therefore:
3967
+ - MEMORY.md must be self-sufficient as a recovery point: after reading it you know who you are, what you know, and what you were doing.
3968
+ - Before a long task, jot an "Active context" note in MEMORY.md so you can resume if interrupted mid-task.
3969
+ - After finishing work, update \`notes/\` and the MEMORY.md index so nothing is lost.
3970
+ - NEVER let compaction make you forget: which channel is about what, what tasks are in progress, or what the user asked.
3971
+
3972
+ ## Message notifications
3973
+ While you're busy, the daemon writes a batched, content-free \`[inbox notice: \u2026]\` into your turn \u2014 it gives metadata (count / target / latest sender) but NOT message bodies (withheld to avoid flooding, not absent). Treat it as a non-urgent signal: don't interrupt your current step; at a natural breakpoint run \`open-tag message check\` to pull the pending messages. Never derive "no work" from a content-free notice alone \u2014 if you choose to defer reading, report the deferral honestly.
3974
+ ${c.description ? `
3975
+ ## Your role
3976
+ ${c.description}. This may evolve.` : ""}`;
3977
+ }
3978
+ var STARTUP_NUDGE = "You just started \u2014 someone messaged you. FIRST run `open-tag message check` to read the message(s) waiting for you, handle them fully, reply with `open-tag message send`, then stop.";
3979
+ var RESUME_NUDGE = "You were woken because new messages may be waiting. Run `open-tag message check` to read them, handle them, reply with `open-tag message send`, then stop.";
3980
+ function inboxNotice(o) {
3981
+ const plural = (n) => n === 1 ? "" : "s";
3982
+ const changed = o.changedTargets ?? 1;
3983
+ const first = o.firstShort ? ` \xB7 first msg=${o.firstShort}` : "";
3984
+ const latest = o.latestShort ? ` \xB7 latest msg=${o.latestShort}` : "";
3985
+ const suffix = `${o.isTask ? " \xB7 task" : ""}${o.isDm ? " \xB7 dm" : ""}`;
3986
+ return `[inbox notice:
3987
+ Inbox update: ${o.count} unread message${plural(o.count)} total; ${changed} changed target${plural(changed)}
3988
+ ${o.targetName} pending: ${o.count} message${plural(o.count)}${first} \xB7 latest @${o.from}${latest}${suffix}
3989
+ ]
3990
+ Content-free signal \u2014 message bodies are withheld, not absent. Finish your current step, then run \`open-tag message check\` to read and handle. Never conclude "no work" from this notice alone.`;
3991
+ }
3992
+
3993
+ // src/daemon/memory.ts
3994
+ function seedMemory(displayName, description) {
3995
+ return `# ${displayName}
3996
+
3997
+ ## Role
3998
+ ${roleBody(description)}
3999
+
4000
+ ## Key Knowledge
4001
+ - None yet
4002
+
4003
+ ## Active Context
4004
+ - First startup
4005
+ `;
4006
+ }
4007
+ function roleBody(description) {
4008
+ return (description ?? "").trim() || "Undefined";
4009
+ }
4010
+ function applyProfileToMemory(content, displayName, description) {
4011
+ const role = roleBody(description);
4012
+ const lines = content.split("\n");
4013
+ const h1 = lines.findIndex((l) => /^#\s+/.test(l));
4014
+ if (h1 === -1) {
4015
+ return `# ${displayName}
4016
+
4017
+ ## Role
4018
+ ${role}
4019
+
4020
+ ${content}`;
4021
+ }
4022
+ lines[h1] = `# ${displayName}`;
4023
+ const roleIdx = lines.findIndex((l, i) => i > h1 && /^##\s+Role\s*$/i.test(l));
4024
+ if (roleIdx === -1) {
4025
+ const head2 = lines.slice(0, h1 + 1);
4026
+ const restStart = lines[h1 + 1] === "" ? h1 + 2 : h1 + 1;
4027
+ return [...head2, "", "## Role", role, "", ...lines.slice(restStart)].join("\n");
4028
+ }
4029
+ let next = lines.length;
4030
+ for (let i = roleIdx + 1; i < lines.length; i++) {
4031
+ if (/^##\s+/.test(lines[i])) {
4032
+ next = i;
4033
+ break;
4034
+ }
4035
+ }
4036
+ const head = lines.slice(0, roleIdx + 1);
4037
+ const tail = lines.slice(next);
4038
+ const body = tail.length ? [role, ""] : [role];
4039
+ return [...head, ...body, ...tail].join("\n");
4040
+ }
4041
+
4042
+ // src/daemon/openTagBin.ts
4043
+ import fs2 from "node:fs";
4044
+ import path3 from "node:path";
4045
+ import { fileURLToPath } from "node:url";
4046
+ function ensureOpenTagBin() {
4047
+ const dir = binDir();
4048
+ fs2.mkdirSync(dir, { recursive: true });
4049
+ const here = path3.dirname(fileURLToPath(import.meta.url));
4050
+ const bundledCli = path3.join(here, "agent-cli.mjs");
4051
+ let cmd;
4052
+ if (fs2.existsSync(bundledCli)) {
4053
+ cmd = `exec node ${JSON.stringify(bundledCli)} "$@"`;
4054
+ } else {
4055
+ const cliPath = path3.resolve(here, "../cli/index.ts");
4056
+ const projectRoot = path3.resolve(here, "../..");
4057
+ const tsxBin = path3.join(projectRoot, "node_modules", ".bin", "tsx");
4058
+ const runner = fs2.existsSync(tsxBin) ? tsxBin : "npx tsx";
4059
+ cmd = `exec ${runner.includes(" ") ? runner : JSON.stringify(runner)} ${JSON.stringify(cliPath)} "$@"`;
4060
+ }
4061
+ const wrapper = path3.join(dir, "open-tag");
4062
+ const sh = `#!/bin/sh
4063
+ # open-tag agent CLI wrapper (auto-generated by daemon)
4064
+ ${cmd}
4065
+ `;
4066
+ fs2.writeFileSync(wrapper, sh);
4067
+ fs2.chmodSync(wrapper, 493);
4068
+ return dir;
4069
+ }
4070
+
4071
+ // src/daemon/runtimes.ts
4072
+ import { execSync } from "node:child_process";
4073
+
4074
+ // src/daemon/claudeRuntime.ts
4075
+ import { spawn } from "node:child_process";
4076
+ import { writeFileSync } from "node:fs";
4077
+ import path4 from "node:path";
4078
+ var MAX = 2e3;
4079
+ var clip = (s) => String(s ?? "").slice(0, MAX);
4080
+ function summarize(tool, input) {
4081
+ if (!input || typeof input !== "object") return "";
4082
+ if (tool === "Bash") return clip(input.command).slice(0, 120);
4083
+ if (["Read", "Write", "Edit"].includes(tool)) return input.file_path ?? input.path ?? "";
4084
+ return "";
4085
+ }
4086
+ var claudeRuntime = {
4087
+ name: "claude",
4088
+ start(opts, cb) {
4089
+ let promptFlag = ["--append-system-prompt", opts.systemPrompt];
4090
+ try {
4091
+ const pf = path4.join(opts.cwd, ".claude-system-prompt.md");
4092
+ writeFileSync(pf, opts.systemPrompt);
4093
+ promptFlag = ["--append-system-prompt-file", pf];
4094
+ } catch {
4095
+ }
4096
+ const args2 = [
4097
+ "-p",
4098
+ "--output-format",
4099
+ "stream-json",
4100
+ "--input-format",
4101
+ "stream-json",
4102
+ "--verbose",
4103
+ "--dangerously-skip-permissions",
4104
+ "--permission-mode",
4105
+ "bypassPermissions",
4106
+ "--include-partial-messages",
4107
+ "--disallowed-tools",
4108
+ "EnterPlanMode,ExitPlanMode,ScheduleWakeup,CronCreate,CronList,CronDelete,AskUserQuestion",
4109
+ ...promptFlag,
4110
+ "--model",
4111
+ opts.model ?? "sonnet"
4112
+ ];
4113
+ if (opts.sessionId) args2.push("--resume", opts.sessionId);
4114
+ const proc = spawn("claude", args2, { cwd: opts.cwd, stdio: ["pipe", "pipe", "pipe"], env: opts.env });
4115
+ let sessionId = opts.sessionId ?? null;
4116
+ const writeUser = (text) => {
4117
+ const m = { type: "user", message: { role: "user", content: [{ type: "text", text }] }, ...sessionId ? { session_id: sessionId } : {} };
4118
+ try {
4119
+ proc.stdin?.write(JSON.stringify(m) + "\n");
4120
+ } catch {
4121
+ }
4122
+ };
4123
+ writeUser(opts.initialPrompt);
4124
+ let buf = "";
4125
+ proc.stdout?.on("data", (c) => {
4126
+ buf += c.toString();
4127
+ const lines = buf.split("\n");
4128
+ buf = lines.pop() ?? "";
4129
+ for (const ln of lines) {
4130
+ if (ln.trim()) parseLine(ln);
4131
+ }
4132
+ });
4133
+ proc.stderr?.on("data", (c) => {
4134
+ const t = c.toString().trim();
4135
+ if (t) cb.log.debug("claude stderr", { t: t.slice(0, 300) });
4136
+ });
4137
+ proc.on("exit", (code) => cb.onExit(code));
4138
+ function parseLine(line) {
4139
+ let e;
4140
+ try {
4141
+ e = JSON.parse(line);
4142
+ } catch {
4143
+ return;
4144
+ }
4145
+ if (e.type === "system" && e.subtype === "init" && e.session_id) {
4146
+ sessionId = e.session_id;
4147
+ cb.onSession(e.session_id);
4148
+ cb.onActivity("working", "starting");
4149
+ } else if (e.type === "result") {
4150
+ if (e.session_id) {
4151
+ sessionId = e.session_id;
4152
+ cb.onSession(e.session_id);
4153
+ }
4154
+ cb.onActivity("online", "");
4155
+ } else if (e.type === "assistant") {
4156
+ const content = e.message?.content;
4157
+ const traj = [];
4158
+ let activity = "thinking", detail = "";
4159
+ if (Array.isArray(content)) {
4160
+ for (const b of content) {
4161
+ if (b.type === "thinking" && b.thinking) traj.push({ kind: "thinking", text: clip(b.thinking) });
4162
+ else if (b.type === "text" && b.text) traj.push({ kind: "text", text: clip(b.text) });
4163
+ else if (b.type === "tool_use") traj.push({ kind: "tool", toolName: b.name, toolInput: summarize(b.name, b.input) });
4164
+ }
4165
+ const tools = content.filter((c) => c.type === "tool_use");
4166
+ if (tools.length) {
4167
+ activity = "working";
4168
+ detail = summarize(tools[tools.length - 1].name, tools[tools.length - 1].input) || tools[tools.length - 1].name;
4169
+ }
4170
+ }
4171
+ cb.onActivity(activity, detail);
4172
+ if (traj.length) cb.onTrajectory(traj);
4173
+ }
4174
+ }
4175
+ return { deliver: (text) => writeUser(text), stop: () => {
4176
+ try {
4177
+ proc.kill("SIGTERM");
4178
+ } catch {
4179
+ }
4180
+ } };
4181
+ }
4182
+ };
4183
+
4184
+ // src/daemon/codexRuntime.ts
4185
+ import { spawn as spawn2 } from "node:child_process";
4186
+ var MAX2 = 2e3;
4187
+ var clip2 = (s) => String(s ?? "").slice(0, MAX2);
4188
+ var EFFORTS = /* @__PURE__ */ new Set(["none", "minimal", "low", "medium", "high", "xhigh"]);
4189
+ function extractThreadId(r) {
4190
+ return r && (r.threadId || r.thread?.id || r.thread_id || r.id) || "";
4191
+ }
4192
+ function reasoningEffort(runtimeConfig) {
4193
+ const effort = runtimeConfig?.reasoningEffort;
4194
+ return typeof effort === "string" && EFFORTS.has(effort) ? effort : null;
4195
+ }
4196
+ function codexConfig(opts) {
4197
+ const effort = reasoningEffort(opts.runtimeConfig);
4198
+ return effort ? { model_reasoning_effort: effort } : null;
4199
+ }
4200
+ function turnParams(opts, threadId, text) {
4201
+ const effort = reasoningEffort(opts.runtimeConfig);
4202
+ return { threadId, input: [{ type: "text", text }], ...effort ? { effort } : {} };
4203
+ }
4204
+ var CodexClient = class {
4205
+ constructor(proc, cb) {
4206
+ this.proc = proc;
4207
+ this.cb = cb;
4208
+ proc.stdout?.on("data", (c) => {
4209
+ this.buf += c.toString();
4210
+ const lines = this.buf.split("\n");
4211
+ this.buf = lines.pop() ?? "";
4212
+ for (const ln of lines) {
4213
+ const t = ln.trim();
4214
+ if (t) this.handleLine(t);
4215
+ }
4216
+ });
4217
+ }
4218
+ proc;
4219
+ cb;
4220
+ nextId = 0;
4221
+ pending = /* @__PURE__ */ new Map();
4222
+ buf = "";
4223
+ proto = "unknown";
4224
+ threadId = "";
4225
+ onTurnDone = null;
4226
+ request(method, params) {
4227
+ const id = ++this.nextId;
4228
+ return new Promise((resolve, reject) => {
4229
+ this.pending.set(id, { resolve, reject });
4230
+ this.write({ jsonrpc: "2.0", id, method, params });
4231
+ });
4232
+ }
4233
+ notify(method, params) {
4234
+ this.write({ jsonrpc: "2.0", method, ...params ? { params } : {} });
4235
+ }
4236
+ respond(id, result) {
4237
+ this.write({ jsonrpc: "2.0", id, result });
4238
+ }
4239
+ write(o) {
4240
+ try {
4241
+ this.proc.stdin?.write(JSON.stringify(o) + "\n");
4242
+ } catch {
4243
+ }
4244
+ }
4245
+ closeAllPending(err) {
4246
+ for (const [id, p] of this.pending) {
4247
+ p.reject(err);
4248
+ this.pending.delete(id);
4249
+ }
4250
+ }
4251
+ handleLine(line) {
4252
+ let raw;
4253
+ try {
4254
+ raw = JSON.parse(line);
4255
+ } catch {
4256
+ return;
4257
+ }
4258
+ if (raw.id !== void 0 && (raw.result !== void 0 || raw.error !== void 0)) {
4259
+ const p = this.pending.get(raw.id);
4260
+ if (!p) return;
4261
+ this.pending.delete(raw.id);
4262
+ raw.error ? p.reject(new Error(raw.error.message || "rpc error")) : p.resolve(raw.result);
4263
+ return;
4264
+ }
4265
+ if (raw.id !== void 0 && raw.method) {
4266
+ this.handleServerRequest(raw.id, raw.method);
4267
+ return;
4268
+ }
4269
+ if (raw.method) this.handleNotification(raw.method, raw.params || {});
4270
+ }
4271
+ handleServerRequest(id, method) {
4272
+ if (method === "item/commandExecution/requestApproval" || method === "execCommandApproval" || method === "item/fileChange/requestApproval" || method === "applyPatchApproval" || method === "item/permissions/requestApproval") {
4273
+ this.respond(id, { decision: "accept" });
4274
+ } else if (method === "mcpServer/elicitation/request") {
4275
+ this.respond(id, { action: "accept", content: null, _meta: null });
4276
+ } else {
4277
+ this.write({ jsonrpc: "2.0", id, error: { code: -32601, message: "unhandled: " + method } });
4278
+ }
4279
+ }
4280
+ handleNotification(method, params) {
4281
+ if (method === "codex/event" || method.startsWith("codex/event/")) {
4282
+ this.proto = "legacy";
4283
+ if (params.msg) this.handleLegacy(params.msg);
4284
+ return;
4285
+ }
4286
+ if (this.proto !== "legacy") {
4287
+ if (this.proto === "unknown" && (method === "turn/started" || method === "turn/completed" || method === "thread/started" || method.startsWith("item/"))) this.proto = "raw";
4288
+ if (this.proto === "raw") this.handleRaw(method, params);
4289
+ }
4290
+ }
4291
+ handleRaw(method, params) {
4292
+ if (this.threadId && params.threadId && params.threadId !== this.threadId) return;
4293
+ if (method === "turn/started") {
4294
+ this.cb.onActivity("working", "turn");
4295
+ } else if (method === "turn/completed") {
4296
+ const status = params?.turn?.status;
4297
+ const aborted = ["cancelled", "canceled", "aborted", "interrupted"].includes(status);
4298
+ if (status === "failed") this.cb.onTrajectory([{ kind: "text", text: "[codex turn failed] " + (params?.turn?.error?.message || "") }]);
4299
+ this.cb.onActivity("online", "");
4300
+ this.onTurnDone?.(aborted);
4301
+ } else if (method === "item/agentMessage/delta" || method === "item/reasoning/summaryTextDelta" || method === "item/reasoning/textDelta") {
4302
+ } else if (method === "item/commandExecution/outputDelta" || method === "command/exec/outputDelta" || method === "process/outputDelta") {
4303
+ } else if (method === "item/started" || method === "item/completed") {
4304
+ const item = params?.item;
4305
+ if (!item) return;
4306
+ if ((item.type === "agentMessage" || item.type === "plan") && item.text) this.cb.onTrajectory([{ kind: "text", text: clip2(item.text) }]);
4307
+ else if (item.type === "reasoning") {
4308
+ const text = [...item.summary ?? [], ...item.content ?? []].join("\n");
4309
+ if (text) this.cb.onTrajectory([{ kind: "thinking", text: clip2(text) }]);
4310
+ } else if (method === "item/started" && item.type && item.type !== "userMessage") {
4311
+ const toolInput = item.command || item.path || item.name || item.reason || "";
4312
+ this.cb.onTrajectory([{ kind: "tool", toolName: item.type, toolInput: clip2(toolInput).slice(0, 160) }]);
4313
+ }
4314
+ } else if (method === "error") {
4315
+ if (!params.willRetry) {
4316
+ this.cb.onTrajectory([{ kind: "text", text: "[codex error] " + (params?.error?.message || params?.message || "") }]);
4317
+ this.onTurnDone?.(false);
4318
+ }
4319
+ }
4320
+ }
4321
+ handleLegacy(msg) {
4322
+ switch (msg.type) {
4323
+ case "task_started":
4324
+ this.cb.onActivity("working", "running");
4325
+ break;
4326
+ case "agent_message":
4327
+ if (msg.message) this.cb.onTrajectory([{ kind: "text", text: clip2(msg.message) }]);
4328
+ break;
4329
+ case "exec_command_begin":
4330
+ this.cb.onActivity("working", "Running command\u2026");
4331
+ this.cb.onTrajectory([{ kind: "tool", toolName: "exec_command", toolInput: clip2(msg.command).slice(0, 120) }]);
4332
+ break;
4333
+ case "patch_apply_begin":
4334
+ this.cb.onTrajectory([{ kind: "tool", toolName: "patch_apply" }]);
4335
+ break;
4336
+ case "task_complete":
4337
+ this.cb.onActivity("online", "");
4338
+ this.onTurnDone?.(false);
4339
+ break;
4340
+ case "turn_aborted":
4341
+ this.onTurnDone?.(true);
4342
+ break;
4343
+ }
4344
+ }
4345
+ };
4346
+ var codexRuntime = {
4347
+ name: "codex",
4348
+ experimental: true,
4349
+ start(opts, cb) {
4350
+ const proc = spawn2("codex", ["app-server", "--listen", "stdio://"], { cwd: opts.cwd, stdio: ["pipe", "pipe", "pipe"], env: opts.env });
4351
+ const client = new CodexClient(proc, cb);
4352
+ let ready = false;
4353
+ const queue = [];
4354
+ let turnBusy = false;
4355
+ client.onTurnDone = () => {
4356
+ turnBusy = false;
4357
+ pump();
4358
+ };
4359
+ function pump() {
4360
+ if (!ready || turnBusy || queue.length === 0) return;
4361
+ const text = queue.shift();
4362
+ turnBusy = true;
4363
+ cb.onActivity("working", "turn");
4364
+ client.request("turn/start", turnParams(opts, client.threadId, text)).catch((e) => {
4365
+ cb.log.warn("codex turn/start failed", { detail: String(e?.message ?? e) });
4366
+ turnBusy = false;
4367
+ pump();
4368
+ });
4369
+ }
4370
+ (async () => {
4371
+ try {
4372
+ await client.request("initialize", { clientInfo: { name: "open-tag", title: "open-tag", version: "0.1.0" }, capabilities: { experimentalApi: true } });
4373
+ client.notify("initialized");
4374
+ let threadId = "";
4375
+ const cfg = codexConfig(opts);
4376
+ if (opts.sessionId) {
4377
+ try {
4378
+ const r = await client.request("thread/resume", { threadId: opts.sessionId, cwd: opts.cwd, model: opts.model || null, developerInstructions: opts.systemPrompt || null, ...cfg ? { config: cfg } : {} });
4379
+ threadId = extractThreadId(r);
4380
+ } catch (e) {
4381
+ cb.log.warn("codex resume failed; starting fresh", { detail: String(e) });
4382
+ }
4383
+ }
4384
+ if (!threadId) {
4385
+ const r = await client.request("thread/start", { model: opts.model || null, cwd: opts.cwd, developerInstructions: opts.systemPrompt || null, persistExtendedHistory: true, experimentalRawEvents: false, ...cfg ? { config: cfg } : {} });
4386
+ threadId = extractThreadId(r);
4387
+ }
4388
+ if (!threadId) {
4389
+ cb.log.error("codex thread/start returned no threadId");
4390
+ cb.onActivity("offline", "codex no thread");
4391
+ return;
4392
+ }
4393
+ client.threadId = threadId;
4394
+ cb.onSession(threadId);
4395
+ cb.log.info("codex thread ready", { threadId });
4396
+ ready = true;
4397
+ queue.push(opts.initialPrompt);
4398
+ pump();
4399
+ } catch (e) {
4400
+ cb.log.error("codex init failed", { detail: String(e?.message ?? e) });
4401
+ cb.onActivity("offline", "codex init failed");
4402
+ }
4403
+ })();
4404
+ proc.stderr?.on("data", (c) => {
4405
+ const t = c.toString().trim();
4406
+ if (t) cb.log.debug("codex stderr", { t: t.slice(0, 300) });
4407
+ });
4408
+ proc.on("exit", (code) => {
4409
+ client.closeAllPending(new Error("codex exited"));
4410
+ cb.onExit(code);
4411
+ });
4412
+ return { deliver: (text) => {
4413
+ queue.push(text);
4414
+ pump();
4415
+ }, stop: () => {
4416
+ try {
4417
+ proc.kill("SIGTERM");
4418
+ } catch {
4419
+ }
4420
+ } };
4421
+ }
4422
+ };
4423
+
4424
+ // src/daemon/runtimes.ts
4425
+ function has(tool) {
4426
+ try {
4427
+ execSync(`command -v ${tool}`, { stdio: "pipe" });
4428
+ return true;
4429
+ } catch {
4430
+ return false;
4431
+ }
4432
+ }
4433
+ function detectRuntimes() {
4434
+ const found = ["claude", "codex", "kimi", "gemini", "opencode"].filter(has);
4435
+ return found;
4436
+ }
4437
+ var REG = { claude: claudeRuntime, codex: codexRuntime };
4438
+ function getRuntime(name) {
4439
+ return REG[name] ?? null;
4440
+ }
4441
+
4442
+ // src/daemon/agentManager.ts
4443
+ var DATA_DIR = agentsDir();
4444
+ var IDLE_MS = Number(process.env.OPEN_TAG_IDLE_MS ?? 10 * 60 * 1e3);
4445
+ var DELIVER_DEBOUNCE_MS = Number(process.env.OPEN_TAG_DELIVER_DEBOUNCE_MS ?? 3e3);
4446
+ var AgentManager = class {
4447
+ constructor(send) {
4448
+ this.send = send;
4449
+ this.binDir = ensureOpenTagBin();
4450
+ }
4451
+ send;
4452
+ agents = /* @__PURE__ */ new Map();
4453
+ binDir;
4454
+ log = createLogger("daemon:agents");
4455
+ running() {
4456
+ return [...this.agents.keys()];
4457
+ }
4458
+ stopAll() {
4459
+ for (const id of [...this.agents.keys()]) this.stop(id);
4460
+ }
4461
+ // Tear down process: clear timers + remove from map first (critical: deletion before session.stop() lets the onExit has() guard recognize this as an intentional stop, suppressing unexpected sleeping status) + stop runtime. Returns whether the agent was found.
4462
+ teardown(agentId) {
4463
+ const r = this.agents.get(agentId);
4464
+ if (!r) return false;
4465
+ if (r.idleTimer) clearTimeout(r.idleTimer);
4466
+ if (r.deliverBuf) clearTimeout(r.deliverBuf.timer);
4467
+ this.agents.delete(agentId);
4468
+ r.session.stop();
4469
+ return true;
4470
+ }
4471
+ // User-initiated stop: emits inactive/offline
4472
+ stop(agentId) {
4473
+ if (!this.teardown(agentId)) return;
4474
+ this.send({ type: "agent:status", agentId, status: "inactive" });
4475
+ this.send({ type: "agent:activity", agentId, activity: "offline", detail: "" });
4476
+ }
4477
+ // Idle sleep: emits sleeping/sleeping (activity also set to sleeping so the frontend activity+status dual mapping stays consistent; session is preserved for --resume on next wake)
4478
+ sleep(agentId) {
4479
+ if (!this.teardown(agentId)) return;
4480
+ this.log.info("sleep", { agentId });
4481
+ this.send({ type: "agent:status", agentId, status: "sleeping" });
4482
+ this.send({ type: "agent:activity", agentId, activity: "sleeping", detail: "" });
4483
+ }
4484
+ /** Reset: stop the process + clear the server-side session (next start will not --resume); wipeWorkspace deletes the entire workspace; clearMemory clears MEMORY.md only. */
4485
+ async reset(agentId, wipeWorkspace = false, clearMemory = false) {
4486
+ this.teardown(agentId);
4487
+ this.send({ type: "agent:session", agentId, sessionId: null });
4488
+ const dir = path5.join(DATA_DIR, agentId);
4489
+ if (wipeWorkspace) {
4490
+ try {
4491
+ await rm(dir, { recursive: true, force: true });
4492
+ this.log.info("workspace wiped", { agentId });
4493
+ } catch (e) {
4494
+ this.log.warn("wipe failed", { agentId, detail: String(e) });
4495
+ }
4496
+ } else if (clearMemory) {
4497
+ try {
4498
+ await writeFile(path5.join(dir, "MEMORY.md"), "# Memory\n\n(reset)\n");
4499
+ this.log.info("memory cleared", { agentId });
4500
+ } catch (e) {
4501
+ this.log.warn("clearMemory failed", { agentId, detail: String(e) });
4502
+ }
4503
+ }
4504
+ this.send({ type: "agent:status", agentId, status: "inactive" });
4505
+ this.send({ type: "agent:activity", agentId, activity: "offline", detail: "reset" });
4506
+ this.log.info("agent reset", { agentId, wipeWorkspace, clearMemory });
4507
+ }
4508
+ /** Profile changed on the server (displayName/description) — surgically sync the workspace MEMORY.md
4509
+ * title + `## Role`, preserving the agent's own sections. No-op if the workspace/file doesn't exist
4510
+ * yet (a not-yet-started agent gets fresh values from the DB when start() seeds it). */
4511
+ async syncProfile(agentId, displayName, description) {
4512
+ const mem = path5.join(DATA_DIR, agentId, "MEMORY.md");
4513
+ let content;
4514
+ try {
4515
+ content = await readFile(mem, "utf8");
4516
+ } catch {
4517
+ this.log.debug("syncProfile: no MEMORY.md yet", { agentId });
4518
+ return;
4519
+ }
4520
+ const next = applyProfileToMemory(content, displayName || agentId, description);
4521
+ if (next !== content) {
4522
+ try {
4523
+ await writeFile(mem, next);
4524
+ this.log.info("profile synced to MEMORY.md", { agentId });
4525
+ } catch (e) {
4526
+ this.log.warn("syncProfile write failed", { agentId, detail: String(e) });
4527
+ return;
4528
+ }
4529
+ }
4530
+ const r = this.agents.get(agentId);
4531
+ if (r) {
4532
+ r.config.displayName = displayName;
4533
+ r.config.description = description ?? null;
4534
+ }
4535
+ }
4536
+ resetIdle(agentId) {
4537
+ const r = this.agents.get(agentId);
4538
+ if (!r) return;
4539
+ if (r.idleTimer) clearTimeout(r.idleTimer);
4540
+ r.idleTimer = setTimeout(() => {
4541
+ this.log.info("idle sleep", { agentId, idleMs: IDLE_MS });
4542
+ this.sleep(agentId);
4543
+ }, IDLE_MS);
4544
+ }
4545
+ async start(agentId, config) {
4546
+ if (this.agents.has(agentId)) return;
4547
+ const runtime = getRuntime(config.runtime ?? "claude");
4548
+ if (!runtime) {
4549
+ this.log.error("no runtime", { runtime: config.runtime });
4550
+ this.send({ type: "agent:activity", agentId, activity: "offline", detail: `no runtime: ${config.runtime}` });
4551
+ return;
4552
+ }
4553
+ if (runtime.experimental) this.log.warn("experimental runtime", { runtime: runtime.name });
4554
+ const dir = path5.join(DATA_DIR, agentId);
4555
+ await mkdir(path5.join(dir, "notes"), { recursive: true });
4556
+ const mem = path5.join(dir, "MEMORY.md");
4557
+ try {
4558
+ await access(mem);
4559
+ } catch {
4560
+ await writeFile(mem, seedMemory(config.displayName || config.name, config.description));
4561
+ }
4562
+ const systemPrompt = buildSystemPrompt({
4563
+ name: config.name,
4564
+ displayName: config.displayName,
4565
+ description: config.description,
4566
+ agentId,
4567
+ serverId: config.serverId,
4568
+ hostname: os2.hostname(),
4569
+ os: `${os2.platform()} ${os2.arch()}`,
4570
+ workspace: dir
4571
+ });
4572
+ const env = {
4573
+ ...process.env,
4574
+ FORCE_COLOR: "0",
4575
+ PATH: `${this.binDir}:${process.env.PATH ?? ""}`,
4576
+ OPEN_TAG_SERVER_URL: config.serverUrl,
4577
+ OPEN_TAG_AGENT_ID: agentId,
4578
+ OPEN_TAG_AGENT_TOKEN: config.agentToken ?? ""
4579
+ };
4580
+ delete env.CLAUDECODE;
4581
+ delete env.CLAUDE_CODE_ENTRYPOINT;
4582
+ const running = { session: void 0, config, sessionId: config.sessionId ?? null };
4583
+ const cb = {
4584
+ onSession: (sid) => {
4585
+ running.sessionId = sid;
4586
+ this.send({ type: "agent:session", agentId, sessionId: sid });
4587
+ },
4588
+ onActivity: (activity, detail) => {
4589
+ this.resetIdle(agentId);
4590
+ this.send({ type: "agent:activity", agentId, activity, detail: detail ?? "" });
4591
+ },
4592
+ onTrajectory: (entries) => this.send({ type: "agent:trajectory", agentId, entries }),
4593
+ onExit: (code) => {
4594
+ this.log.info("agent exited", { agentId, code });
4595
+ if (!this.agents.has(agentId)) return;
4596
+ this.agents.delete(agentId);
4597
+ const crashed = code !== 0;
4598
+ this.send({ type: "agent:status", agentId, status: "sleeping" });
4599
+ this.send({ type: "agent:activity", agentId, activity: crashed ? "error" : "sleeping", detail: crashed ? `crashed (exit ${code ?? "signal"})` : "" });
4600
+ },
4601
+ log: this.log
4602
+ };
4603
+ this.agents.set(agentId, running);
4604
+ running.session = runtime.start({
4605
+ cwd: dir,
4606
+ model: config.model,
4607
+ runtimeConfig: config.runtimeConfig,
4608
+ sessionId: config.sessionId,
4609
+ systemPrompt,
4610
+ env,
4611
+ initialPrompt: config.sessionId ? RESUME_NUDGE : STARTUP_NUDGE
4612
+ }, cb);
4613
+ this.send({ type: "agent:status", agentId, status: "active" });
4614
+ this.send({ type: "agent:activity", agentId, activity: "working", detail: "starting" });
4615
+ this.log.info("agent started", { agentId, runtime: runtime.name, model: config.model ?? "(default)", resume: !!config.sessionId, experimental: runtime.experimental ?? false });
4616
+ this.resetIdle(agentId);
4617
+ }
4618
+ /** server agent:deliver — wake a running agent with new messages; agents not yet running will self-check on startup once agent:start arrives. */
4619
+ deliver(agentId, from, target, mentioned = false, meta = {}) {
4620
+ const r = this.agents.get(agentId);
4621
+ if (!r) {
4622
+ this.log.debug("deliver: agent not running yet", { agentId });
4623
+ return;
4624
+ }
4625
+ const tname = meta.targetName ?? target;
4626
+ const short = meta.msgShort ?? "";
4627
+ const b = r.deliverBuf;
4628
+ if (b) {
4629
+ clearTimeout(b.timer);
4630
+ b.count++;
4631
+ b.from = from;
4632
+ b.target = target;
4633
+ b.targetName = tname;
4634
+ b.latestShort = short;
4635
+ b.isTask = b.isTask || !!meta.isTask;
4636
+ b.mentioned = b.mentioned || mentioned;
4637
+ b.targets.add(tname);
4638
+ }
4639
+ const buf = b ?? { count: 1, from, target, targetName: tname, firstShort: short, latestShort: short, isTask: !!meta.isTask, mentioned, targets: /* @__PURE__ */ new Set([tname]), timer: void 0 };
4640
+ buf.timer = setTimeout(() => {
4641
+ r.deliverBuf = void 0;
4642
+ const note = inboxNotice({ count: buf.count, from: buf.from, targetName: buf.targetName, firstShort: buf.firstShort, latestShort: buf.latestShort, isTask: buf.isTask, isDm: buf.targetName.startsWith("dm:"), changedTargets: buf.targets.size, mentioned: buf.mentioned });
4643
+ try {
4644
+ r.session.deliver(note);
4645
+ this.resetIdle(agentId);
4646
+ this.log.debug("inbox notice -> agent", { agentId, count: buf.count, mentioned: buf.mentioned });
4647
+ } catch (e) {
4648
+ this.log.warn("deliver failed", { agentId, detail: String(e) });
4649
+ }
4650
+ }, DELIVER_DEBOUNCE_MS);
4651
+ r.deliverBuf = buf;
4652
+ }
4653
+ };
4654
+
4655
+ // src/daemon/workspace.ts
4656
+ import { readdir, readFile as readFile2, stat } from "node:fs/promises";
4657
+ import path6 from "node:path";
4658
+ import os3 from "node:os";
4659
+ var DATA_DIR2 = agentsDir();
4660
+ var MAX_FILE = 256 * 1024;
4661
+ var SKIP = /* @__PURE__ */ new Set(["node_modules", ".git"]);
4662
+ function safe(agentId, rel) {
4663
+ const root = path6.join(DATA_DIR2, agentId);
4664
+ const target = path6.resolve(root, rel || ".");
4665
+ if (target !== root && !target.startsWith(root + path6.sep)) return null;
4666
+ return target;
4667
+ }
4668
+ async function walk(root, rel, acc, depth) {
4669
+ if (depth > 6 || acc.length > 2e3) return;
4670
+ let ds;
4671
+ try {
4672
+ ds = await readdir(path6.join(root, rel), { withFileTypes: true });
4673
+ } catch {
4674
+ return;
4675
+ }
4676
+ for (const d of ds) {
4677
+ if (SKIP.has(d.name)) continue;
4678
+ const childRel = rel ? `${rel}/${d.name}` : d.name;
4679
+ let size = 0;
4680
+ let modifiedAt = null;
4681
+ try {
4682
+ const s = await stat(path6.join(root, childRel));
4683
+ size = d.isFile() ? s.size : 0;
4684
+ modifiedAt = s.mtime.toISOString();
4685
+ } catch {
4686
+ }
4687
+ acc.push({ name: d.name, path: childRel, isDirectory: d.isDirectory(), size, modifiedAt });
4688
+ if (d.isDirectory()) await walk(root, childRel, acc, depth + 1);
4689
+ }
4690
+ }
4691
+ async function listWorkspace(agentId, _subPath = "") {
4692
+ const root = path6.join(DATA_DIR2, agentId);
4693
+ try {
4694
+ const files = [];
4695
+ await walk(root, "", files, 0);
4696
+ return { files };
4697
+ } catch (e) {
4698
+ return { error: String(e?.message ?? e) };
4699
+ }
4700
+ }
4701
+ function fmField(fm, key) {
4702
+ const lines = fm.split("\n");
4703
+ for (let i = 0; i < lines.length; i++) {
4704
+ const m = new RegExp(`^${key}:\\s*(.*)$`, "i").exec(lines[i]);
4705
+ if (!m) continue;
4706
+ const inline = m[1].trim();
4707
+ if (inline && !/^[|>][+-]?$/.test(inline)) return inline.replace(/^["']|["']$/g, "");
4708
+ const block = [];
4709
+ for (let j = i + 1; j < lines.length; j++) {
4710
+ if (/^\s+\S/.test(lines[j])) block.push(lines[j].trim());
4711
+ else if (lines[j].trim() === "") block.push("");
4712
+ else break;
4713
+ }
4714
+ return block.join(" ").replace(/\s+/g, " ").trim();
4715
+ }
4716
+ return "";
4717
+ }
4718
+ async function readSkillsDir(dir, sourcePath) {
4719
+ const out = [];
4720
+ let entries;
4721
+ try {
4722
+ entries = await readdir(dir, { withFileTypes: true });
4723
+ } catch {
4724
+ return out;
4725
+ }
4726
+ for (const e of entries) {
4727
+ if (!e.isDirectory()) continue;
4728
+ let name = e.name, description = "", userInvocable = false;
4729
+ try {
4730
+ const txt = await readFile2(path6.join(dir, e.name, "SKILL.md"), "utf8");
4731
+ const fm = /^---\n([\s\S]*?)\n---/.exec(txt);
4732
+ if (fm) {
4733
+ name = fmField(fm[1], "name") || e.name;
4734
+ description = fmField(fm[1], "description");
4735
+ userInvocable = /^(true|yes)$/i.test(fmField(fm[1], "user-invocable") || fmField(fm[1], "userInvocable"));
4736
+ }
4737
+ } catch {
4738
+ continue;
4739
+ }
4740
+ out.push({ name, displayName: name, description, userInvocable, sourcePath });
4741
+ }
4742
+ return out;
4743
+ }
4744
+ async function listSkills(agentId) {
4745
+ const global = await readSkillsDir(path6.join(os3.homedir(), ".claude", "skills"), "~/.claude/skills");
4746
+ const workspace = await readSkillsDir(path6.join(DATA_DIR2, agentId, ".claude", "skills"), "<workspace>/.claude/skills");
4747
+ return { global, workspace };
4748
+ }
4749
+ async function readWorkspaceFile(agentId, rel) {
4750
+ const file = safe(agentId, rel);
4751
+ if (!file) return { error: "invalid path" };
4752
+ try {
4753
+ const s = await stat(file);
4754
+ if (!s.isFile()) return { error: "not a file" };
4755
+ if (s.size > MAX_FILE) return { error: `file too large (${s.size} bytes, max ${MAX_FILE})` };
4756
+ const buf = await readFile2(file);
4757
+ if (buf.includes(0)) return { error: "binary file" };
4758
+ return { path: rel, content: buf.toString("utf8") };
4759
+ } catch (e) {
4760
+ return { error: String(e?.message ?? e) };
4761
+ }
4762
+ }
4763
+
4764
+ // src/daemon/index.ts
4765
+ var log = createLogger("daemon");
4766
+ var args = process.argv.slice(2);
4767
+ var serverUrl = "";
4768
+ var apiKey = "";
4769
+ for (let i = 0; i < args.length; i++) {
4770
+ if (args[i] === "--server-url" && args[i + 1]) serverUrl = args[++i];
4771
+ if (args[i] === "--api-key" && args[i + 1]) apiKey = args[++i];
4772
+ }
4773
+ if (!serverUrl) serverUrl = `http://localhost:${process.env.PORT ?? 7777}`;
4774
+ if (!apiKey) {
4775
+ console.error("Usage: open-tag-daemon [--server-url <url>] --api-key <machineKey>");
4776
+ process.exit(1);
4777
+ }
4778
+ var MID_FILE = machineIdFile();
4779
+ var readMachineId = () => {
4780
+ try {
4781
+ return fs3.readFileSync(MID_FILE, "utf8").trim() || void 0;
4782
+ } catch {
4783
+ return void 0;
4784
+ }
4785
+ };
4786
+ var saveMachineId = (id) => {
4787
+ try {
4788
+ fs3.mkdirSync(path7.dirname(MID_FILE), { recursive: true });
4789
+ fs3.writeFileSync(MID_FILE, id);
4790
+ } catch {
4791
+ }
4792
+ };
4793
+ var conn;
4794
+ var mgr = new AgentManager((m) => conn.send(m));
4795
+ conn = new Connection(serverUrl, apiKey, (msg) => {
4796
+ if (msg.type !== "ping") log.debug("recv", { type: msg.type, agentId: msg.agentId });
4797
+ switch (msg.type) {
4798
+ case "ready:ack":
4799
+ if (typeof msg.machineId === "string" && msg.machineId) saveMachineId(msg.machineId);
4800
+ break;
4801
+ case "agent:start":
4802
+ void mgr.start(msg.agentId, { ...msg.config });
4803
+ break;
4804
+ case "agent:deliver":
4805
+ mgr.deliver(msg.agentId, msg.from ?? "someone", msg.target ?? "", !!msg.mentioned, { targetName: msg.targetName, msgShort: msg.msgShort, isTask: msg.isTask });
4806
+ conn.send({ type: "agent:deliver:ack", agentId: msg.agentId, seq: msg.seq });
4807
+ break;
4808
+ case "agent:stop":
4809
+ mgr.stop(msg.agentId);
4810
+ break;
4811
+ case "agent:sleep":
4812
+ mgr.sleep(msg.agentId);
4813
+ break;
4814
+ case "agent:reset":
4815
+ void mgr.reset(msg.agentId, !!msg.wipeWorkspace, !!msg.clearMemory);
4816
+ break;
4817
+ case "agent:profile":
4818
+ void mgr.syncProfile(msg.agentId, msg.displayName ?? "", msg.description);
4819
+ break;
4820
+ case "agent:workspace:list":
4821
+ void listWorkspace(msg.agentId, msg.path ?? "").then((r) => conn.send({ type: "workspace:file_tree", requestId: msg.requestId, agentId: msg.agentId, ...r }));
4822
+ break;
4823
+ case "agent:workspace:read":
4824
+ void readWorkspaceFile(msg.agentId, msg.path ?? "").then((r) => conn.send({ type: "workspace:file_content", requestId: msg.requestId, agentId: msg.agentId, ...r }));
4825
+ break;
4826
+ case "agent:skills:list":
4827
+ void listSkills(msg.agentId).then((r) => conn.send({ type: "skills:list", requestId: msg.requestId, agentId: msg.agentId, ...r }));
4828
+ break;
4829
+ case "ping":
4830
+ conn.send({ type: "pong" });
4831
+ break;
4832
+ }
4833
+ }, () => {
4834
+ const runtimes = detectRuntimes();
4835
+ log.info("ready", { runtimes, hostname: os4.hostname() });
4836
+ conn.send({
4837
+ type: "ready",
4838
+ capabilities: ["agent:start", "agent:stop", "agent:sleep", "agent:reset", "agent:profile", "agent:deliver", "agent:workspace"],
4839
+ runtimes,
4840
+ runningAgents: mgr.running(),
4841
+ hostname: os4.hostname(),
4842
+ os: `${os4.platform()} ${os4.arch()}`,
4843
+ daemonVersion: "0.1.0",
4844
+ machineId: readMachineId()
4845
+ // Stable identity: empty on first connection; server sends it back via ready:ack for persistence.
4846
+ });
4847
+ });
4848
+ log.info("open-tag daemon starting", { serverUrl });
4849
+ conn.connect();
4850
+ var shutdown = () => {
4851
+ log.info("shutting down");
4852
+ mgr.stopAll();
4853
+ conn.close();
4854
+ process.exit(0);
4855
+ };
4856
+ process.on("SIGINT", shutdown);
4857
+ process.on("SIGTERM", shutdown);