@todoforai/tfa-review 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.
Files changed (2) hide show
  1. package/dist/cli.js +3232 -0
  2. package/package.json +21 -0
package/dist/cli.js ADDED
@@ -0,0 +1,3232 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire } from "node:module";
3
+ var __create = Object.create;
4
+ var __getProtoOf = Object.getPrototypeOf;
5
+ var __defProp = Object.defineProperty;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __toESM = (mod, isNodeMode, target) => {
9
+ target = mod != null ? __create(__getProtoOf(mod)) : {};
10
+ const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
11
+ for (let key of __getOwnPropNames(mod))
12
+ if (!__hasOwnProp.call(to, key))
13
+ __defProp(to, key, {
14
+ get: () => mod[key],
15
+ enumerable: true
16
+ });
17
+ return to;
18
+ };
19
+ var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
20
+ var __require = /* @__PURE__ */ createRequire(import.meta.url);
21
+
22
+ // ../node_modules/ws/lib/constants.js
23
+ var require_constants = __commonJS((exports, module) => {
24
+ var BINARY_TYPES = ["nodebuffer", "arraybuffer", "fragments"];
25
+ var hasBlob = typeof Blob !== "undefined";
26
+ if (hasBlob)
27
+ BINARY_TYPES.push("blob");
28
+ module.exports = {
29
+ BINARY_TYPES,
30
+ CLOSE_TIMEOUT: 30000,
31
+ EMPTY_BUFFER: Buffer.alloc(0),
32
+ GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
33
+ hasBlob,
34
+ kForOnEventAttribute: Symbol("kIsForOnEventAttribute"),
35
+ kListener: Symbol("kListener"),
36
+ kStatusCode: Symbol("status-code"),
37
+ kWebSocket: Symbol("websocket"),
38
+ NOOP: () => {}
39
+ };
40
+ });
41
+
42
+ // ../node_modules/ws/lib/buffer-util.js
43
+ var require_buffer_util = __commonJS((exports, module) => {
44
+ var { EMPTY_BUFFER } = require_constants();
45
+ var FastBuffer = Buffer[Symbol.species];
46
+ function concat(list, totalLength) {
47
+ if (list.length === 0)
48
+ return EMPTY_BUFFER;
49
+ if (list.length === 1)
50
+ return list[0];
51
+ const target = Buffer.allocUnsafe(totalLength);
52
+ let offset = 0;
53
+ for (let i = 0;i < list.length; i++) {
54
+ const buf = list[i];
55
+ target.set(buf, offset);
56
+ offset += buf.length;
57
+ }
58
+ if (offset < totalLength) {
59
+ return new FastBuffer(target.buffer, target.byteOffset, offset);
60
+ }
61
+ return target;
62
+ }
63
+ function _mask(source, mask, output, offset, length) {
64
+ for (let i = 0;i < length; i++) {
65
+ output[offset + i] = source[i] ^ mask[i & 3];
66
+ }
67
+ }
68
+ function _unmask(buffer, mask) {
69
+ for (let i = 0;i < buffer.length; i++) {
70
+ buffer[i] ^= mask[i & 3];
71
+ }
72
+ }
73
+ function toArrayBuffer(buf) {
74
+ if (buf.length === buf.buffer.byteLength) {
75
+ return buf.buffer;
76
+ }
77
+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);
78
+ }
79
+ function toBuffer(data) {
80
+ toBuffer.readOnly = true;
81
+ if (Buffer.isBuffer(data))
82
+ return data;
83
+ let buf;
84
+ if (data instanceof ArrayBuffer) {
85
+ buf = new FastBuffer(data);
86
+ } else if (ArrayBuffer.isView(data)) {
87
+ buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);
88
+ } else {
89
+ buf = Buffer.from(data);
90
+ toBuffer.readOnly = false;
91
+ }
92
+ return buf;
93
+ }
94
+ module.exports = {
95
+ concat,
96
+ mask: _mask,
97
+ toArrayBuffer,
98
+ toBuffer,
99
+ unmask: _unmask
100
+ };
101
+ if (!process.env.WS_NO_BUFFER_UTIL) {
102
+ try {
103
+ const bufferUtil = (()=>{throw new Error("Cannot require module "+"bufferutil");})();
104
+ module.exports.mask = function(source, mask, output, offset, length) {
105
+ if (length < 48)
106
+ _mask(source, mask, output, offset, length);
107
+ else
108
+ bufferUtil.mask(source, mask, output, offset, length);
109
+ };
110
+ module.exports.unmask = function(buffer, mask) {
111
+ if (buffer.length < 32)
112
+ _unmask(buffer, mask);
113
+ else
114
+ bufferUtil.unmask(buffer, mask);
115
+ };
116
+ } catch (e) {}
117
+ }
118
+ });
119
+
120
+ // ../node_modules/ws/lib/limiter.js
121
+ var require_limiter = __commonJS((exports, module) => {
122
+ var kDone = Symbol("kDone");
123
+ var kRun = Symbol("kRun");
124
+
125
+ class Limiter {
126
+ constructor(concurrency) {
127
+ this[kDone] = () => {
128
+ this.pending--;
129
+ this[kRun]();
130
+ };
131
+ this.concurrency = concurrency || Infinity;
132
+ this.jobs = [];
133
+ this.pending = 0;
134
+ }
135
+ add(job) {
136
+ this.jobs.push(job);
137
+ this[kRun]();
138
+ }
139
+ [kRun]() {
140
+ if (this.pending === this.concurrency)
141
+ return;
142
+ if (this.jobs.length) {
143
+ const job = this.jobs.shift();
144
+ this.pending++;
145
+ job(this[kDone]);
146
+ }
147
+ }
148
+ }
149
+ module.exports = Limiter;
150
+ });
151
+
152
+ // ../node_modules/ws/lib/permessage-deflate.js
153
+ var require_permessage_deflate = __commonJS((exports, module) => {
154
+ var zlib = __require("zlib");
155
+ var bufferUtil = require_buffer_util();
156
+ var Limiter = require_limiter();
157
+ var { kStatusCode } = require_constants();
158
+ var FastBuffer = Buffer[Symbol.species];
159
+ var TRAILER = Buffer.from([0, 0, 255, 255]);
160
+ var kPerMessageDeflate = Symbol("permessage-deflate");
161
+ var kTotalLength = Symbol("total-length");
162
+ var kCallback = Symbol("callback");
163
+ var kBuffers = Symbol("buffers");
164
+ var kError = Symbol("error");
165
+ var zlibLimiter;
166
+
167
+ class PerMessageDeflate {
168
+ constructor(options) {
169
+ this._options = options || {};
170
+ this._threshold = this._options.threshold !== undefined ? this._options.threshold : 1024;
171
+ this._maxPayload = this._options.maxPayload | 0;
172
+ this._isServer = !!this._options.isServer;
173
+ this._deflate = null;
174
+ this._inflate = null;
175
+ this.params = null;
176
+ if (!zlibLimiter) {
177
+ const concurrency = this._options.concurrencyLimit !== undefined ? this._options.concurrencyLimit : 10;
178
+ zlibLimiter = new Limiter(concurrency);
179
+ }
180
+ }
181
+ static get extensionName() {
182
+ return "permessage-deflate";
183
+ }
184
+ offer() {
185
+ const params = {};
186
+ if (this._options.serverNoContextTakeover) {
187
+ params.server_no_context_takeover = true;
188
+ }
189
+ if (this._options.clientNoContextTakeover) {
190
+ params.client_no_context_takeover = true;
191
+ }
192
+ if (this._options.serverMaxWindowBits) {
193
+ params.server_max_window_bits = this._options.serverMaxWindowBits;
194
+ }
195
+ if (this._options.clientMaxWindowBits) {
196
+ params.client_max_window_bits = this._options.clientMaxWindowBits;
197
+ } else if (this._options.clientMaxWindowBits == null) {
198
+ params.client_max_window_bits = true;
199
+ }
200
+ return params;
201
+ }
202
+ accept(configurations) {
203
+ configurations = this.normalizeParams(configurations);
204
+ this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations);
205
+ return this.params;
206
+ }
207
+ cleanup() {
208
+ if (this._inflate) {
209
+ this._inflate.close();
210
+ this._inflate = null;
211
+ }
212
+ if (this._deflate) {
213
+ const callback = this._deflate[kCallback];
214
+ this._deflate.close();
215
+ this._deflate = null;
216
+ if (callback) {
217
+ callback(new Error("The deflate stream was closed while data was being processed"));
218
+ }
219
+ }
220
+ }
221
+ acceptAsServer(offers) {
222
+ const opts = this._options;
223
+ const accepted = offers.find((params) => {
224
+ 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) {
225
+ return false;
226
+ }
227
+ return true;
228
+ });
229
+ if (!accepted) {
230
+ throw new Error("None of the extension offers can be accepted");
231
+ }
232
+ if (opts.serverNoContextTakeover) {
233
+ accepted.server_no_context_takeover = true;
234
+ }
235
+ if (opts.clientNoContextTakeover) {
236
+ accepted.client_no_context_takeover = true;
237
+ }
238
+ if (typeof opts.serverMaxWindowBits === "number") {
239
+ accepted.server_max_window_bits = opts.serverMaxWindowBits;
240
+ }
241
+ if (typeof opts.clientMaxWindowBits === "number") {
242
+ accepted.client_max_window_bits = opts.clientMaxWindowBits;
243
+ } else if (accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false) {
244
+ delete accepted.client_max_window_bits;
245
+ }
246
+ return accepted;
247
+ }
248
+ acceptAsClient(response) {
249
+ const params = response[0];
250
+ if (this._options.clientNoContextTakeover === false && params.client_no_context_takeover) {
251
+ throw new Error('Unexpected parameter "client_no_context_takeover"');
252
+ }
253
+ if (!params.client_max_window_bits) {
254
+ if (typeof this._options.clientMaxWindowBits === "number") {
255
+ params.client_max_window_bits = this._options.clientMaxWindowBits;
256
+ }
257
+ } else if (this._options.clientMaxWindowBits === false || typeof this._options.clientMaxWindowBits === "number" && params.client_max_window_bits > this._options.clientMaxWindowBits) {
258
+ throw new Error('Unexpected or invalid parameter "client_max_window_bits"');
259
+ }
260
+ return params;
261
+ }
262
+ normalizeParams(configurations) {
263
+ configurations.forEach((params) => {
264
+ Object.keys(params).forEach((key) => {
265
+ let value = params[key];
266
+ if (value.length > 1) {
267
+ throw new Error(`Parameter "${key}" must have only a single value`);
268
+ }
269
+ value = value[0];
270
+ if (key === "client_max_window_bits") {
271
+ if (value !== true) {
272
+ const num = +value;
273
+ if (!Number.isInteger(num) || num < 8 || num > 15) {
274
+ throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
275
+ }
276
+ value = num;
277
+ } else if (!this._isServer) {
278
+ throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
279
+ }
280
+ } else if (key === "server_max_window_bits") {
281
+ const num = +value;
282
+ if (!Number.isInteger(num) || num < 8 || num > 15) {
283
+ throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
284
+ }
285
+ value = num;
286
+ } else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") {
287
+ if (value !== true) {
288
+ throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
289
+ }
290
+ } else {
291
+ throw new Error(`Unknown parameter "${key}"`);
292
+ }
293
+ params[key] = value;
294
+ });
295
+ });
296
+ return configurations;
297
+ }
298
+ decompress(data, fin, callback) {
299
+ zlibLimiter.add((done) => {
300
+ this._decompress(data, fin, (err, result) => {
301
+ done();
302
+ callback(err, result);
303
+ });
304
+ });
305
+ }
306
+ compress(data, fin, callback) {
307
+ zlibLimiter.add((done) => {
308
+ this._compress(data, fin, (err, result) => {
309
+ done();
310
+ callback(err, result);
311
+ });
312
+ });
313
+ }
314
+ _decompress(data, fin, callback) {
315
+ const endpoint = this._isServer ? "client" : "server";
316
+ if (!this._inflate) {
317
+ const key = `${endpoint}_max_window_bits`;
318
+ const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
319
+ this._inflate = zlib.createInflateRaw({
320
+ ...this._options.zlibInflateOptions,
321
+ windowBits
322
+ });
323
+ this._inflate[kPerMessageDeflate] = this;
324
+ this._inflate[kTotalLength] = 0;
325
+ this._inflate[kBuffers] = [];
326
+ this._inflate.on("error", inflateOnError);
327
+ this._inflate.on("data", inflateOnData);
328
+ }
329
+ this._inflate[kCallback] = callback;
330
+ this._inflate.write(data);
331
+ if (fin)
332
+ this._inflate.write(TRAILER);
333
+ this._inflate.flush(() => {
334
+ const err = this._inflate[kError];
335
+ if (err) {
336
+ this._inflate.close();
337
+ this._inflate = null;
338
+ callback(err);
339
+ return;
340
+ }
341
+ const data2 = bufferUtil.concat(this._inflate[kBuffers], this._inflate[kTotalLength]);
342
+ if (this._inflate._readableState.endEmitted) {
343
+ this._inflate.close();
344
+ this._inflate = null;
345
+ } else {
346
+ this._inflate[kTotalLength] = 0;
347
+ this._inflate[kBuffers] = [];
348
+ if (fin && this.params[`${endpoint}_no_context_takeover`]) {
349
+ this._inflate.reset();
350
+ }
351
+ }
352
+ callback(null, data2);
353
+ });
354
+ }
355
+ _compress(data, fin, callback) {
356
+ const endpoint = this._isServer ? "server" : "client";
357
+ if (!this._deflate) {
358
+ const key = `${endpoint}_max_window_bits`;
359
+ const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
360
+ this._deflate = zlib.createDeflateRaw({
361
+ ...this._options.zlibDeflateOptions,
362
+ windowBits
363
+ });
364
+ this._deflate[kTotalLength] = 0;
365
+ this._deflate[kBuffers] = [];
366
+ this._deflate.on("data", deflateOnData);
367
+ }
368
+ this._deflate[kCallback] = callback;
369
+ this._deflate.write(data);
370
+ this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {
371
+ if (!this._deflate) {
372
+ return;
373
+ }
374
+ let data2 = bufferUtil.concat(this._deflate[kBuffers], this._deflate[kTotalLength]);
375
+ if (fin) {
376
+ data2 = new FastBuffer(data2.buffer, data2.byteOffset, data2.length - 4);
377
+ }
378
+ this._deflate[kCallback] = null;
379
+ this._deflate[kTotalLength] = 0;
380
+ this._deflate[kBuffers] = [];
381
+ if (fin && this.params[`${endpoint}_no_context_takeover`]) {
382
+ this._deflate.reset();
383
+ }
384
+ callback(null, data2);
385
+ });
386
+ }
387
+ }
388
+ module.exports = PerMessageDeflate;
389
+ function deflateOnData(chunk) {
390
+ this[kBuffers].push(chunk);
391
+ this[kTotalLength] += chunk.length;
392
+ }
393
+ function inflateOnData(chunk) {
394
+ this[kTotalLength] += chunk.length;
395
+ if (this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) {
396
+ this[kBuffers].push(chunk);
397
+ return;
398
+ }
399
+ this[kError] = new RangeError("Max payload size exceeded");
400
+ this[kError].code = "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH";
401
+ this[kError][kStatusCode] = 1009;
402
+ this.removeListener("data", inflateOnData);
403
+ this.reset();
404
+ }
405
+ function inflateOnError(err) {
406
+ this[kPerMessageDeflate]._inflate = null;
407
+ if (this[kError]) {
408
+ this[kCallback](this[kError]);
409
+ return;
410
+ }
411
+ err[kStatusCode] = 1007;
412
+ this[kCallback](err);
413
+ }
414
+ });
415
+
416
+ // ../node_modules/ws/lib/validation.js
417
+ var require_validation = __commonJS((exports, module) => {
418
+ var { isUtf8 } = __require("buffer");
419
+ var { hasBlob } = require_constants();
420
+ var tokenChars = [
421
+ 0,
422
+ 0,
423
+ 0,
424
+ 0,
425
+ 0,
426
+ 0,
427
+ 0,
428
+ 0,
429
+ 0,
430
+ 0,
431
+ 0,
432
+ 0,
433
+ 0,
434
+ 0,
435
+ 0,
436
+ 0,
437
+ 0,
438
+ 0,
439
+ 0,
440
+ 0,
441
+ 0,
442
+ 0,
443
+ 0,
444
+ 0,
445
+ 0,
446
+ 0,
447
+ 0,
448
+ 0,
449
+ 0,
450
+ 0,
451
+ 0,
452
+ 0,
453
+ 0,
454
+ 1,
455
+ 0,
456
+ 1,
457
+ 1,
458
+ 1,
459
+ 1,
460
+ 1,
461
+ 0,
462
+ 0,
463
+ 1,
464
+ 1,
465
+ 0,
466
+ 1,
467
+ 1,
468
+ 0,
469
+ 1,
470
+ 1,
471
+ 1,
472
+ 1,
473
+ 1,
474
+ 1,
475
+ 1,
476
+ 1,
477
+ 1,
478
+ 1,
479
+ 0,
480
+ 0,
481
+ 0,
482
+ 0,
483
+ 0,
484
+ 0,
485
+ 0,
486
+ 1,
487
+ 1,
488
+ 1,
489
+ 1,
490
+ 1,
491
+ 1,
492
+ 1,
493
+ 1,
494
+ 1,
495
+ 1,
496
+ 1,
497
+ 1,
498
+ 1,
499
+ 1,
500
+ 1,
501
+ 1,
502
+ 1,
503
+ 1,
504
+ 1,
505
+ 1,
506
+ 1,
507
+ 1,
508
+ 1,
509
+ 1,
510
+ 1,
511
+ 1,
512
+ 0,
513
+ 0,
514
+ 0,
515
+ 1,
516
+ 1,
517
+ 1,
518
+ 1,
519
+ 1,
520
+ 1,
521
+ 1,
522
+ 1,
523
+ 1,
524
+ 1,
525
+ 1,
526
+ 1,
527
+ 1,
528
+ 1,
529
+ 1,
530
+ 1,
531
+ 1,
532
+ 1,
533
+ 1,
534
+ 1,
535
+ 1,
536
+ 1,
537
+ 1,
538
+ 1,
539
+ 1,
540
+ 1,
541
+ 1,
542
+ 1,
543
+ 1,
544
+ 0,
545
+ 1,
546
+ 0,
547
+ 1,
548
+ 0
549
+ ];
550
+ function isValidStatusCode(code) {
551
+ return code >= 1000 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006 || code >= 3000 && code <= 4999;
552
+ }
553
+ function _isValidUTF8(buf) {
554
+ const len = buf.length;
555
+ let i = 0;
556
+ while (i < len) {
557
+ if ((buf[i] & 128) === 0) {
558
+ i++;
559
+ } else if ((buf[i] & 224) === 192) {
560
+ if (i + 1 === len || (buf[i + 1] & 192) !== 128 || (buf[i] & 254) === 192) {
561
+ return false;
562
+ }
563
+ i += 2;
564
+ } else if ((buf[i] & 240) === 224) {
565
+ if (i + 2 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || buf[i] === 224 && (buf[i + 1] & 224) === 128 || buf[i] === 237 && (buf[i + 1] & 224) === 160) {
566
+ return false;
567
+ }
568
+ i += 3;
569
+ } else if ((buf[i] & 248) === 240) {
570
+ if (i + 3 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || (buf[i + 3] & 192) !== 128 || buf[i] === 240 && (buf[i + 1] & 240) === 128 || buf[i] === 244 && buf[i + 1] > 143 || buf[i] > 244) {
571
+ return false;
572
+ }
573
+ i += 4;
574
+ } else {
575
+ return false;
576
+ }
577
+ }
578
+ return true;
579
+ }
580
+ function isBlob(value) {
581
+ 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");
582
+ }
583
+ module.exports = {
584
+ isBlob,
585
+ isValidStatusCode,
586
+ isValidUTF8: _isValidUTF8,
587
+ tokenChars
588
+ };
589
+ if (isUtf8) {
590
+ module.exports.isValidUTF8 = function(buf) {
591
+ return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);
592
+ };
593
+ } else if (!process.env.WS_NO_UTF_8_VALIDATE) {
594
+ try {
595
+ const isValidUTF8 = (()=>{throw new Error("Cannot require module "+"utf-8-validate");})();
596
+ module.exports.isValidUTF8 = function(buf) {
597
+ return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);
598
+ };
599
+ } catch (e) {}
600
+ }
601
+ });
602
+
603
+ // ../node_modules/ws/lib/receiver.js
604
+ var require_receiver = __commonJS((exports, module) => {
605
+ var { Writable } = __require("stream");
606
+ var PerMessageDeflate = require_permessage_deflate();
607
+ var {
608
+ BINARY_TYPES,
609
+ EMPTY_BUFFER,
610
+ kStatusCode,
611
+ kWebSocket
612
+ } = require_constants();
613
+ var { concat, toArrayBuffer, unmask } = require_buffer_util();
614
+ var { isValidStatusCode, isValidUTF8 } = require_validation();
615
+ var FastBuffer = Buffer[Symbol.species];
616
+ var GET_INFO = 0;
617
+ var GET_PAYLOAD_LENGTH_16 = 1;
618
+ var GET_PAYLOAD_LENGTH_64 = 2;
619
+ var GET_MASK = 3;
620
+ var GET_DATA = 4;
621
+ var INFLATING = 5;
622
+ var DEFER_EVENT = 6;
623
+
624
+ class Receiver extends Writable {
625
+ constructor(options = {}) {
626
+ super();
627
+ this._allowSynchronousEvents = options.allowSynchronousEvents !== undefined ? options.allowSynchronousEvents : true;
628
+ this._binaryType = options.binaryType || BINARY_TYPES[0];
629
+ this._extensions = options.extensions || {};
630
+ this._isServer = !!options.isServer;
631
+ this._maxPayload = options.maxPayload | 0;
632
+ this._skipUTF8Validation = !!options.skipUTF8Validation;
633
+ this[kWebSocket] = undefined;
634
+ this._bufferedBytes = 0;
635
+ this._buffers = [];
636
+ this._compressed = false;
637
+ this._payloadLength = 0;
638
+ this._mask = undefined;
639
+ this._fragmented = 0;
640
+ this._masked = false;
641
+ this._fin = false;
642
+ this._opcode = 0;
643
+ this._totalPayloadLength = 0;
644
+ this._messageLength = 0;
645
+ this._fragments = [];
646
+ this._errored = false;
647
+ this._loop = false;
648
+ this._state = GET_INFO;
649
+ }
650
+ _write(chunk, encoding, cb) {
651
+ if (this._opcode === 8 && this._state == GET_INFO)
652
+ return cb();
653
+ this._bufferedBytes += chunk.length;
654
+ this._buffers.push(chunk);
655
+ this.startLoop(cb);
656
+ }
657
+ consume(n) {
658
+ this._bufferedBytes -= n;
659
+ if (n === this._buffers[0].length)
660
+ return this._buffers.shift();
661
+ if (n < this._buffers[0].length) {
662
+ const buf = this._buffers[0];
663
+ this._buffers[0] = new FastBuffer(buf.buffer, buf.byteOffset + n, buf.length - n);
664
+ return new FastBuffer(buf.buffer, buf.byteOffset, n);
665
+ }
666
+ const dst = Buffer.allocUnsafe(n);
667
+ do {
668
+ const buf = this._buffers[0];
669
+ const offset = dst.length - n;
670
+ if (n >= buf.length) {
671
+ dst.set(this._buffers.shift(), offset);
672
+ } else {
673
+ dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);
674
+ this._buffers[0] = new FastBuffer(buf.buffer, buf.byteOffset + n, buf.length - n);
675
+ }
676
+ n -= buf.length;
677
+ } while (n > 0);
678
+ return dst;
679
+ }
680
+ startLoop(cb) {
681
+ this._loop = true;
682
+ do {
683
+ switch (this._state) {
684
+ case GET_INFO:
685
+ this.getInfo(cb);
686
+ break;
687
+ case GET_PAYLOAD_LENGTH_16:
688
+ this.getPayloadLength16(cb);
689
+ break;
690
+ case GET_PAYLOAD_LENGTH_64:
691
+ this.getPayloadLength64(cb);
692
+ break;
693
+ case GET_MASK:
694
+ this.getMask();
695
+ break;
696
+ case GET_DATA:
697
+ this.getData(cb);
698
+ break;
699
+ case INFLATING:
700
+ case DEFER_EVENT:
701
+ this._loop = false;
702
+ return;
703
+ }
704
+ } while (this._loop);
705
+ if (!this._errored)
706
+ cb();
707
+ }
708
+ getInfo(cb) {
709
+ if (this._bufferedBytes < 2) {
710
+ this._loop = false;
711
+ return;
712
+ }
713
+ const buf = this.consume(2);
714
+ if ((buf[0] & 48) !== 0) {
715
+ const error = this.createError(RangeError, "RSV2 and RSV3 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_2_3");
716
+ cb(error);
717
+ return;
718
+ }
719
+ const compressed = (buf[0] & 64) === 64;
720
+ if (compressed && !this._extensions[PerMessageDeflate.extensionName]) {
721
+ const error = this.createError(RangeError, "RSV1 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_1");
722
+ cb(error);
723
+ return;
724
+ }
725
+ this._fin = (buf[0] & 128) === 128;
726
+ this._opcode = buf[0] & 15;
727
+ this._payloadLength = buf[1] & 127;
728
+ if (this._opcode === 0) {
729
+ if (compressed) {
730
+ const error = this.createError(RangeError, "RSV1 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_1");
731
+ cb(error);
732
+ return;
733
+ }
734
+ if (!this._fragmented) {
735
+ const error = this.createError(RangeError, "invalid opcode 0", true, 1002, "WS_ERR_INVALID_OPCODE");
736
+ cb(error);
737
+ return;
738
+ }
739
+ this._opcode = this._fragmented;
740
+ } else if (this._opcode === 1 || this._opcode === 2) {
741
+ if (this._fragmented) {
742
+ const error = this.createError(RangeError, `invalid opcode ${this._opcode}`, true, 1002, "WS_ERR_INVALID_OPCODE");
743
+ cb(error);
744
+ return;
745
+ }
746
+ this._compressed = compressed;
747
+ } else if (this._opcode > 7 && this._opcode < 11) {
748
+ if (!this._fin) {
749
+ const error = this.createError(RangeError, "FIN must be set", true, 1002, "WS_ERR_EXPECTED_FIN");
750
+ cb(error);
751
+ return;
752
+ }
753
+ if (compressed) {
754
+ const error = this.createError(RangeError, "RSV1 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_1");
755
+ cb(error);
756
+ return;
757
+ }
758
+ if (this._payloadLength > 125 || this._opcode === 8 && this._payloadLength === 1) {
759
+ const error = this.createError(RangeError, `invalid payload length ${this._payloadLength}`, true, 1002, "WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");
760
+ cb(error);
761
+ return;
762
+ }
763
+ } else {
764
+ const error = this.createError(RangeError, `invalid opcode ${this._opcode}`, true, 1002, "WS_ERR_INVALID_OPCODE");
765
+ cb(error);
766
+ return;
767
+ }
768
+ if (!this._fin && !this._fragmented)
769
+ this._fragmented = this._opcode;
770
+ this._masked = (buf[1] & 128) === 128;
771
+ if (this._isServer) {
772
+ if (!this._masked) {
773
+ const error = this.createError(RangeError, "MASK must be set", true, 1002, "WS_ERR_EXPECTED_MASK");
774
+ cb(error);
775
+ return;
776
+ }
777
+ } else if (this._masked) {
778
+ const error = this.createError(RangeError, "MASK must be clear", true, 1002, "WS_ERR_UNEXPECTED_MASK");
779
+ cb(error);
780
+ return;
781
+ }
782
+ if (this._payloadLength === 126)
783
+ this._state = GET_PAYLOAD_LENGTH_16;
784
+ else if (this._payloadLength === 127)
785
+ this._state = GET_PAYLOAD_LENGTH_64;
786
+ else
787
+ this.haveLength(cb);
788
+ }
789
+ getPayloadLength16(cb) {
790
+ if (this._bufferedBytes < 2) {
791
+ this._loop = false;
792
+ return;
793
+ }
794
+ this._payloadLength = this.consume(2).readUInt16BE(0);
795
+ this.haveLength(cb);
796
+ }
797
+ getPayloadLength64(cb) {
798
+ if (this._bufferedBytes < 8) {
799
+ this._loop = false;
800
+ return;
801
+ }
802
+ const buf = this.consume(8);
803
+ const num = buf.readUInt32BE(0);
804
+ if (num > Math.pow(2, 53 - 32) - 1) {
805
+ const error = this.createError(RangeError, "Unsupported WebSocket frame: payload length > 2^53 - 1", false, 1009, "WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");
806
+ cb(error);
807
+ return;
808
+ }
809
+ this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
810
+ this.haveLength(cb);
811
+ }
812
+ haveLength(cb) {
813
+ if (this._payloadLength && this._opcode < 8) {
814
+ this._totalPayloadLength += this._payloadLength;
815
+ if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
816
+ const error = this.createError(RangeError, "Max payload size exceeded", false, 1009, "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");
817
+ cb(error);
818
+ return;
819
+ }
820
+ }
821
+ if (this._masked)
822
+ this._state = GET_MASK;
823
+ else
824
+ this._state = GET_DATA;
825
+ }
826
+ getMask() {
827
+ if (this._bufferedBytes < 4) {
828
+ this._loop = false;
829
+ return;
830
+ }
831
+ this._mask = this.consume(4);
832
+ this._state = GET_DATA;
833
+ }
834
+ getData(cb) {
835
+ let data = EMPTY_BUFFER;
836
+ if (this._payloadLength) {
837
+ if (this._bufferedBytes < this._payloadLength) {
838
+ this._loop = false;
839
+ return;
840
+ }
841
+ data = this.consume(this._payloadLength);
842
+ if (this._masked && (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0) {
843
+ unmask(data, this._mask);
844
+ }
845
+ }
846
+ if (this._opcode > 7) {
847
+ this.controlMessage(data, cb);
848
+ return;
849
+ }
850
+ if (this._compressed) {
851
+ this._state = INFLATING;
852
+ this.decompress(data, cb);
853
+ return;
854
+ }
855
+ if (data.length) {
856
+ this._messageLength = this._totalPayloadLength;
857
+ this._fragments.push(data);
858
+ }
859
+ this.dataMessage(cb);
860
+ }
861
+ decompress(data, cb) {
862
+ const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
863
+ perMessageDeflate.decompress(data, this._fin, (err, buf) => {
864
+ if (err)
865
+ return cb(err);
866
+ if (buf.length) {
867
+ this._messageLength += buf.length;
868
+ if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
869
+ const error = this.createError(RangeError, "Max payload size exceeded", false, 1009, "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");
870
+ cb(error);
871
+ return;
872
+ }
873
+ this._fragments.push(buf);
874
+ }
875
+ this.dataMessage(cb);
876
+ if (this._state === GET_INFO)
877
+ this.startLoop(cb);
878
+ });
879
+ }
880
+ dataMessage(cb) {
881
+ if (!this._fin) {
882
+ this._state = GET_INFO;
883
+ return;
884
+ }
885
+ const messageLength = this._messageLength;
886
+ const fragments = this._fragments;
887
+ this._totalPayloadLength = 0;
888
+ this._messageLength = 0;
889
+ this._fragmented = 0;
890
+ this._fragments = [];
891
+ if (this._opcode === 2) {
892
+ let data;
893
+ if (this._binaryType === "nodebuffer") {
894
+ data = concat(fragments, messageLength);
895
+ } else if (this._binaryType === "arraybuffer") {
896
+ data = toArrayBuffer(concat(fragments, messageLength));
897
+ } else if (this._binaryType === "blob") {
898
+ data = new Blob(fragments);
899
+ } else {
900
+ data = fragments;
901
+ }
902
+ if (this._allowSynchronousEvents) {
903
+ this.emit("message", data, true);
904
+ this._state = GET_INFO;
905
+ } else {
906
+ this._state = DEFER_EVENT;
907
+ setImmediate(() => {
908
+ this.emit("message", data, true);
909
+ this._state = GET_INFO;
910
+ this.startLoop(cb);
911
+ });
912
+ }
913
+ } else {
914
+ const buf = concat(fragments, messageLength);
915
+ if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
916
+ const error = this.createError(Error, "invalid UTF-8 sequence", true, 1007, "WS_ERR_INVALID_UTF8");
917
+ cb(error);
918
+ return;
919
+ }
920
+ if (this._state === INFLATING || this._allowSynchronousEvents) {
921
+ this.emit("message", buf, false);
922
+ this._state = GET_INFO;
923
+ } else {
924
+ this._state = DEFER_EVENT;
925
+ setImmediate(() => {
926
+ this.emit("message", buf, false);
927
+ this._state = GET_INFO;
928
+ this.startLoop(cb);
929
+ });
930
+ }
931
+ }
932
+ }
933
+ controlMessage(data, cb) {
934
+ if (this._opcode === 8) {
935
+ if (data.length === 0) {
936
+ this._loop = false;
937
+ this.emit("conclude", 1005, EMPTY_BUFFER);
938
+ this.end();
939
+ } else {
940
+ const code = data.readUInt16BE(0);
941
+ if (!isValidStatusCode(code)) {
942
+ const error = this.createError(RangeError, `invalid status code ${code}`, true, 1002, "WS_ERR_INVALID_CLOSE_CODE");
943
+ cb(error);
944
+ return;
945
+ }
946
+ const buf = new FastBuffer(data.buffer, data.byteOffset + 2, data.length - 2);
947
+ if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
948
+ const error = this.createError(Error, "invalid UTF-8 sequence", true, 1007, "WS_ERR_INVALID_UTF8");
949
+ cb(error);
950
+ return;
951
+ }
952
+ this._loop = false;
953
+ this.emit("conclude", code, buf);
954
+ this.end();
955
+ }
956
+ this._state = GET_INFO;
957
+ return;
958
+ }
959
+ if (this._allowSynchronousEvents) {
960
+ this.emit(this._opcode === 9 ? "ping" : "pong", data);
961
+ this._state = GET_INFO;
962
+ } else {
963
+ this._state = DEFER_EVENT;
964
+ setImmediate(() => {
965
+ this.emit(this._opcode === 9 ? "ping" : "pong", data);
966
+ this._state = GET_INFO;
967
+ this.startLoop(cb);
968
+ });
969
+ }
970
+ }
971
+ createError(ErrorCtor, message, prefix, statusCode, errorCode) {
972
+ this._loop = false;
973
+ this._errored = true;
974
+ const err = new ErrorCtor(prefix ? `Invalid WebSocket frame: ${message}` : message);
975
+ Error.captureStackTrace(err, this.createError);
976
+ err.code = errorCode;
977
+ err[kStatusCode] = statusCode;
978
+ return err;
979
+ }
980
+ }
981
+ module.exports = Receiver;
982
+ });
983
+
984
+ // ../node_modules/ws/lib/sender.js
985
+ var require_sender = __commonJS((exports, module) => {
986
+ var { Duplex } = __require("stream");
987
+ var { randomFillSync } = __require("crypto");
988
+ var {
989
+ types: { isUint8Array }
990
+ } = __require("util");
991
+ var PerMessageDeflate = require_permessage_deflate();
992
+ var { EMPTY_BUFFER, kWebSocket, NOOP } = require_constants();
993
+ var { isBlob, isValidStatusCode } = require_validation();
994
+ var { mask: applyMask, toBuffer } = require_buffer_util();
995
+ var kByteLength = Symbol("kByteLength");
996
+ var maskBuffer = Buffer.alloc(4);
997
+ var RANDOM_POOL_SIZE = 8 * 1024;
998
+ var randomPool;
999
+ var randomPoolPointer = RANDOM_POOL_SIZE;
1000
+ var DEFAULT = 0;
1001
+ var DEFLATING = 1;
1002
+ var GET_BLOB_DATA = 2;
1003
+
1004
+ class Sender {
1005
+ constructor(socket, extensions, generateMask) {
1006
+ this._extensions = extensions || {};
1007
+ if (generateMask) {
1008
+ this._generateMask = generateMask;
1009
+ this._maskBuffer = Buffer.alloc(4);
1010
+ }
1011
+ this._socket = socket;
1012
+ this._firstFragment = true;
1013
+ this._compress = false;
1014
+ this._bufferedBytes = 0;
1015
+ this._queue = [];
1016
+ this._state = DEFAULT;
1017
+ this.onerror = NOOP;
1018
+ this[kWebSocket] = undefined;
1019
+ }
1020
+ static frame(data, options) {
1021
+ let mask;
1022
+ let merge = false;
1023
+ let offset = 2;
1024
+ let skipMasking = false;
1025
+ if (options.mask) {
1026
+ mask = options.maskBuffer || maskBuffer;
1027
+ if (options.generateMask) {
1028
+ options.generateMask(mask);
1029
+ } else {
1030
+ if (randomPoolPointer === RANDOM_POOL_SIZE) {
1031
+ if (randomPool === undefined) {
1032
+ randomPool = Buffer.alloc(RANDOM_POOL_SIZE);
1033
+ }
1034
+ randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);
1035
+ randomPoolPointer = 0;
1036
+ }
1037
+ mask[0] = randomPool[randomPoolPointer++];
1038
+ mask[1] = randomPool[randomPoolPointer++];
1039
+ mask[2] = randomPool[randomPoolPointer++];
1040
+ mask[3] = randomPool[randomPoolPointer++];
1041
+ }
1042
+ skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;
1043
+ offset = 6;
1044
+ }
1045
+ let dataLength;
1046
+ if (typeof data === "string") {
1047
+ if ((!options.mask || skipMasking) && options[kByteLength] !== undefined) {
1048
+ dataLength = options[kByteLength];
1049
+ } else {
1050
+ data = Buffer.from(data);
1051
+ dataLength = data.length;
1052
+ }
1053
+ } else {
1054
+ dataLength = data.length;
1055
+ merge = options.mask && options.readOnly && !skipMasking;
1056
+ }
1057
+ let payloadLength = dataLength;
1058
+ if (dataLength >= 65536) {
1059
+ offset += 8;
1060
+ payloadLength = 127;
1061
+ } else if (dataLength > 125) {
1062
+ offset += 2;
1063
+ payloadLength = 126;
1064
+ }
1065
+ const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);
1066
+ target[0] = options.fin ? options.opcode | 128 : options.opcode;
1067
+ if (options.rsv1)
1068
+ target[0] |= 64;
1069
+ target[1] = payloadLength;
1070
+ if (payloadLength === 126) {
1071
+ target.writeUInt16BE(dataLength, 2);
1072
+ } else if (payloadLength === 127) {
1073
+ target[2] = target[3] = 0;
1074
+ target.writeUIntBE(dataLength, 4, 6);
1075
+ }
1076
+ if (!options.mask)
1077
+ return [target, data];
1078
+ target[1] |= 128;
1079
+ target[offset - 4] = mask[0];
1080
+ target[offset - 3] = mask[1];
1081
+ target[offset - 2] = mask[2];
1082
+ target[offset - 1] = mask[3];
1083
+ if (skipMasking)
1084
+ return [target, data];
1085
+ if (merge) {
1086
+ applyMask(data, mask, target, offset, dataLength);
1087
+ return [target];
1088
+ }
1089
+ applyMask(data, mask, data, 0, dataLength);
1090
+ return [target, data];
1091
+ }
1092
+ close(code, data, mask, cb) {
1093
+ let buf;
1094
+ if (code === undefined) {
1095
+ buf = EMPTY_BUFFER;
1096
+ } else if (typeof code !== "number" || !isValidStatusCode(code)) {
1097
+ throw new TypeError("First argument must be a valid error code number");
1098
+ } else if (data === undefined || !data.length) {
1099
+ buf = Buffer.allocUnsafe(2);
1100
+ buf.writeUInt16BE(code, 0);
1101
+ } else {
1102
+ const length = Buffer.byteLength(data);
1103
+ if (length > 123) {
1104
+ throw new RangeError("The message must not be greater than 123 bytes");
1105
+ }
1106
+ buf = Buffer.allocUnsafe(2 + length);
1107
+ buf.writeUInt16BE(code, 0);
1108
+ if (typeof data === "string") {
1109
+ buf.write(data, 2);
1110
+ } else if (isUint8Array(data)) {
1111
+ buf.set(data, 2);
1112
+ } else {
1113
+ throw new TypeError("Second argument must be a string or a Uint8Array");
1114
+ }
1115
+ }
1116
+ const options = {
1117
+ [kByteLength]: buf.length,
1118
+ fin: true,
1119
+ generateMask: this._generateMask,
1120
+ mask,
1121
+ maskBuffer: this._maskBuffer,
1122
+ opcode: 8,
1123
+ readOnly: false,
1124
+ rsv1: false
1125
+ };
1126
+ if (this._state !== DEFAULT) {
1127
+ this.enqueue([this.dispatch, buf, false, options, cb]);
1128
+ } else {
1129
+ this.sendFrame(Sender.frame(buf, options), cb);
1130
+ }
1131
+ }
1132
+ ping(data, mask, cb) {
1133
+ let byteLength;
1134
+ let readOnly;
1135
+ if (typeof data === "string") {
1136
+ byteLength = Buffer.byteLength(data);
1137
+ readOnly = false;
1138
+ } else if (isBlob(data)) {
1139
+ byteLength = data.size;
1140
+ readOnly = false;
1141
+ } else {
1142
+ data = toBuffer(data);
1143
+ byteLength = data.length;
1144
+ readOnly = toBuffer.readOnly;
1145
+ }
1146
+ if (byteLength > 125) {
1147
+ throw new RangeError("The data size must not be greater than 125 bytes");
1148
+ }
1149
+ const options = {
1150
+ [kByteLength]: byteLength,
1151
+ fin: true,
1152
+ generateMask: this._generateMask,
1153
+ mask,
1154
+ maskBuffer: this._maskBuffer,
1155
+ opcode: 9,
1156
+ readOnly,
1157
+ rsv1: false
1158
+ };
1159
+ if (isBlob(data)) {
1160
+ if (this._state !== DEFAULT) {
1161
+ this.enqueue([this.getBlobData, data, false, options, cb]);
1162
+ } else {
1163
+ this.getBlobData(data, false, options, cb);
1164
+ }
1165
+ } else if (this._state !== DEFAULT) {
1166
+ this.enqueue([this.dispatch, data, false, options, cb]);
1167
+ } else {
1168
+ this.sendFrame(Sender.frame(data, options), cb);
1169
+ }
1170
+ }
1171
+ pong(data, mask, cb) {
1172
+ let byteLength;
1173
+ let readOnly;
1174
+ if (typeof data === "string") {
1175
+ byteLength = Buffer.byteLength(data);
1176
+ readOnly = false;
1177
+ } else if (isBlob(data)) {
1178
+ byteLength = data.size;
1179
+ readOnly = false;
1180
+ } else {
1181
+ data = toBuffer(data);
1182
+ byteLength = data.length;
1183
+ readOnly = toBuffer.readOnly;
1184
+ }
1185
+ if (byteLength > 125) {
1186
+ throw new RangeError("The data size must not be greater than 125 bytes");
1187
+ }
1188
+ const options = {
1189
+ [kByteLength]: byteLength,
1190
+ fin: true,
1191
+ generateMask: this._generateMask,
1192
+ mask,
1193
+ maskBuffer: this._maskBuffer,
1194
+ opcode: 10,
1195
+ readOnly,
1196
+ rsv1: false
1197
+ };
1198
+ if (isBlob(data)) {
1199
+ if (this._state !== DEFAULT) {
1200
+ this.enqueue([this.getBlobData, data, false, options, cb]);
1201
+ } else {
1202
+ this.getBlobData(data, false, options, cb);
1203
+ }
1204
+ } else if (this._state !== DEFAULT) {
1205
+ this.enqueue([this.dispatch, data, false, options, cb]);
1206
+ } else {
1207
+ this.sendFrame(Sender.frame(data, options), cb);
1208
+ }
1209
+ }
1210
+ send(data, options, cb) {
1211
+ const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
1212
+ let opcode = options.binary ? 2 : 1;
1213
+ let rsv1 = options.compress;
1214
+ let byteLength;
1215
+ let readOnly;
1216
+ if (typeof data === "string") {
1217
+ byteLength = Buffer.byteLength(data);
1218
+ readOnly = false;
1219
+ } else if (isBlob(data)) {
1220
+ byteLength = data.size;
1221
+ readOnly = false;
1222
+ } else {
1223
+ data = toBuffer(data);
1224
+ byteLength = data.length;
1225
+ readOnly = toBuffer.readOnly;
1226
+ }
1227
+ if (this._firstFragment) {
1228
+ this._firstFragment = false;
1229
+ if (rsv1 && perMessageDeflate && perMessageDeflate.params[perMessageDeflate._isServer ? "server_no_context_takeover" : "client_no_context_takeover"]) {
1230
+ rsv1 = byteLength >= perMessageDeflate._threshold;
1231
+ }
1232
+ this._compress = rsv1;
1233
+ } else {
1234
+ rsv1 = false;
1235
+ opcode = 0;
1236
+ }
1237
+ if (options.fin)
1238
+ this._firstFragment = true;
1239
+ const opts = {
1240
+ [kByteLength]: byteLength,
1241
+ fin: options.fin,
1242
+ generateMask: this._generateMask,
1243
+ mask: options.mask,
1244
+ maskBuffer: this._maskBuffer,
1245
+ opcode,
1246
+ readOnly,
1247
+ rsv1
1248
+ };
1249
+ if (isBlob(data)) {
1250
+ if (this._state !== DEFAULT) {
1251
+ this.enqueue([this.getBlobData, data, this._compress, opts, cb]);
1252
+ } else {
1253
+ this.getBlobData(data, this._compress, opts, cb);
1254
+ }
1255
+ } else if (this._state !== DEFAULT) {
1256
+ this.enqueue([this.dispatch, data, this._compress, opts, cb]);
1257
+ } else {
1258
+ this.dispatch(data, this._compress, opts, cb);
1259
+ }
1260
+ }
1261
+ getBlobData(blob, compress, options, cb) {
1262
+ this._bufferedBytes += options[kByteLength];
1263
+ this._state = GET_BLOB_DATA;
1264
+ blob.arrayBuffer().then((arrayBuffer) => {
1265
+ if (this._socket.destroyed) {
1266
+ const err = new Error("The socket was closed while the blob was being read");
1267
+ process.nextTick(callCallbacks, this, err, cb);
1268
+ return;
1269
+ }
1270
+ this._bufferedBytes -= options[kByteLength];
1271
+ const data = toBuffer(arrayBuffer);
1272
+ if (!compress) {
1273
+ this._state = DEFAULT;
1274
+ this.sendFrame(Sender.frame(data, options), cb);
1275
+ this.dequeue();
1276
+ } else {
1277
+ this.dispatch(data, compress, options, cb);
1278
+ }
1279
+ }).catch((err) => {
1280
+ process.nextTick(onError, this, err, cb);
1281
+ });
1282
+ }
1283
+ dispatch(data, compress, options, cb) {
1284
+ if (!compress) {
1285
+ this.sendFrame(Sender.frame(data, options), cb);
1286
+ return;
1287
+ }
1288
+ const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
1289
+ this._bufferedBytes += options[kByteLength];
1290
+ this._state = DEFLATING;
1291
+ perMessageDeflate.compress(data, options.fin, (_, buf) => {
1292
+ if (this._socket.destroyed) {
1293
+ const err = new Error("The socket was closed while data was being compressed");
1294
+ callCallbacks(this, err, cb);
1295
+ return;
1296
+ }
1297
+ this._bufferedBytes -= options[kByteLength];
1298
+ this._state = DEFAULT;
1299
+ options.readOnly = false;
1300
+ this.sendFrame(Sender.frame(buf, options), cb);
1301
+ this.dequeue();
1302
+ });
1303
+ }
1304
+ dequeue() {
1305
+ while (this._state === DEFAULT && this._queue.length) {
1306
+ const params = this._queue.shift();
1307
+ this._bufferedBytes -= params[3][kByteLength];
1308
+ Reflect.apply(params[0], this, params.slice(1));
1309
+ }
1310
+ }
1311
+ enqueue(params) {
1312
+ this._bufferedBytes += params[3][kByteLength];
1313
+ this._queue.push(params);
1314
+ }
1315
+ sendFrame(list, cb) {
1316
+ if (list.length === 2) {
1317
+ this._socket.cork();
1318
+ this._socket.write(list[0]);
1319
+ this._socket.write(list[1], cb);
1320
+ this._socket.uncork();
1321
+ } else {
1322
+ this._socket.write(list[0], cb);
1323
+ }
1324
+ }
1325
+ }
1326
+ module.exports = Sender;
1327
+ function callCallbacks(sender, err, cb) {
1328
+ if (typeof cb === "function")
1329
+ cb(err);
1330
+ for (let i = 0;i < sender._queue.length; i++) {
1331
+ const params = sender._queue[i];
1332
+ const callback = params[params.length - 1];
1333
+ if (typeof callback === "function")
1334
+ callback(err);
1335
+ }
1336
+ }
1337
+ function onError(sender, err, cb) {
1338
+ callCallbacks(sender, err, cb);
1339
+ sender.onerror(err);
1340
+ }
1341
+ });
1342
+
1343
+ // ../node_modules/ws/lib/event-target.js
1344
+ var require_event_target = __commonJS((exports, module) => {
1345
+ var { kForOnEventAttribute, kListener } = require_constants();
1346
+ var kCode = Symbol("kCode");
1347
+ var kData = Symbol("kData");
1348
+ var kError = Symbol("kError");
1349
+ var kMessage = Symbol("kMessage");
1350
+ var kReason = Symbol("kReason");
1351
+ var kTarget = Symbol("kTarget");
1352
+ var kType = Symbol("kType");
1353
+ var kWasClean = Symbol("kWasClean");
1354
+
1355
+ class Event {
1356
+ constructor(type) {
1357
+ this[kTarget] = null;
1358
+ this[kType] = type;
1359
+ }
1360
+ get target() {
1361
+ return this[kTarget];
1362
+ }
1363
+ get type() {
1364
+ return this[kType];
1365
+ }
1366
+ }
1367
+ Object.defineProperty(Event.prototype, "target", { enumerable: true });
1368
+ Object.defineProperty(Event.prototype, "type", { enumerable: true });
1369
+
1370
+ class CloseEvent extends Event {
1371
+ constructor(type, options = {}) {
1372
+ super(type);
1373
+ this[kCode] = options.code === undefined ? 0 : options.code;
1374
+ this[kReason] = options.reason === undefined ? "" : options.reason;
1375
+ this[kWasClean] = options.wasClean === undefined ? false : options.wasClean;
1376
+ }
1377
+ get code() {
1378
+ return this[kCode];
1379
+ }
1380
+ get reason() {
1381
+ return this[kReason];
1382
+ }
1383
+ get wasClean() {
1384
+ return this[kWasClean];
1385
+ }
1386
+ }
1387
+ Object.defineProperty(CloseEvent.prototype, "code", { enumerable: true });
1388
+ Object.defineProperty(CloseEvent.prototype, "reason", { enumerable: true });
1389
+ Object.defineProperty(CloseEvent.prototype, "wasClean", { enumerable: true });
1390
+
1391
+ class ErrorEvent extends Event {
1392
+ constructor(type, options = {}) {
1393
+ super(type);
1394
+ this[kError] = options.error === undefined ? null : options.error;
1395
+ this[kMessage] = options.message === undefined ? "" : options.message;
1396
+ }
1397
+ get error() {
1398
+ return this[kError];
1399
+ }
1400
+ get message() {
1401
+ return this[kMessage];
1402
+ }
1403
+ }
1404
+ Object.defineProperty(ErrorEvent.prototype, "error", { enumerable: true });
1405
+ Object.defineProperty(ErrorEvent.prototype, "message", { enumerable: true });
1406
+
1407
+ class MessageEvent extends Event {
1408
+ constructor(type, options = {}) {
1409
+ super(type);
1410
+ this[kData] = options.data === undefined ? null : options.data;
1411
+ }
1412
+ get data() {
1413
+ return this[kData];
1414
+ }
1415
+ }
1416
+ Object.defineProperty(MessageEvent.prototype, "data", { enumerable: true });
1417
+ var EventTarget = {
1418
+ addEventListener(type, handler, options = {}) {
1419
+ for (const listener of this.listeners(type)) {
1420
+ if (!options[kForOnEventAttribute] && listener[kListener] === handler && !listener[kForOnEventAttribute]) {
1421
+ return;
1422
+ }
1423
+ }
1424
+ let wrapper;
1425
+ if (type === "message") {
1426
+ wrapper = function onMessage(data, isBinary) {
1427
+ const event = new MessageEvent("message", {
1428
+ data: isBinary ? data : data.toString()
1429
+ });
1430
+ event[kTarget] = this;
1431
+ callListener(handler, this, event);
1432
+ };
1433
+ } else if (type === "close") {
1434
+ wrapper = function onClose(code, message) {
1435
+ const event = new CloseEvent("close", {
1436
+ code,
1437
+ reason: message.toString(),
1438
+ wasClean: this._closeFrameReceived && this._closeFrameSent
1439
+ });
1440
+ event[kTarget] = this;
1441
+ callListener(handler, this, event);
1442
+ };
1443
+ } else if (type === "error") {
1444
+ wrapper = function onError(error) {
1445
+ const event = new ErrorEvent("error", {
1446
+ error,
1447
+ message: error.message
1448
+ });
1449
+ event[kTarget] = this;
1450
+ callListener(handler, this, event);
1451
+ };
1452
+ } else if (type === "open") {
1453
+ wrapper = function onOpen() {
1454
+ const event = new Event("open");
1455
+ event[kTarget] = this;
1456
+ callListener(handler, this, event);
1457
+ };
1458
+ } else {
1459
+ return;
1460
+ }
1461
+ wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];
1462
+ wrapper[kListener] = handler;
1463
+ if (options.once) {
1464
+ this.once(type, wrapper);
1465
+ } else {
1466
+ this.on(type, wrapper);
1467
+ }
1468
+ },
1469
+ removeEventListener(type, handler) {
1470
+ for (const listener of this.listeners(type)) {
1471
+ if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {
1472
+ this.removeListener(type, listener);
1473
+ break;
1474
+ }
1475
+ }
1476
+ }
1477
+ };
1478
+ module.exports = {
1479
+ CloseEvent,
1480
+ ErrorEvent,
1481
+ Event,
1482
+ EventTarget,
1483
+ MessageEvent
1484
+ };
1485
+ function callListener(listener, thisArg, event) {
1486
+ if (typeof listener === "object" && listener.handleEvent) {
1487
+ listener.handleEvent.call(listener, event);
1488
+ } else {
1489
+ listener.call(thisArg, event);
1490
+ }
1491
+ }
1492
+ });
1493
+
1494
+ // ../node_modules/ws/lib/extension.js
1495
+ var require_extension = __commonJS((exports, module) => {
1496
+ var { tokenChars } = require_validation();
1497
+ function push(dest, name, elem) {
1498
+ if (dest[name] === undefined)
1499
+ dest[name] = [elem];
1500
+ else
1501
+ dest[name].push(elem);
1502
+ }
1503
+ function parse(header) {
1504
+ const offers = Object.create(null);
1505
+ let params = Object.create(null);
1506
+ let mustUnescape = false;
1507
+ let isEscaping = false;
1508
+ let inQuotes = false;
1509
+ let extensionName;
1510
+ let paramName;
1511
+ let start = -1;
1512
+ let code = -1;
1513
+ let end = -1;
1514
+ let i = 0;
1515
+ for (;i < header.length; i++) {
1516
+ code = header.charCodeAt(i);
1517
+ if (extensionName === undefined) {
1518
+ if (end === -1 && tokenChars[code] === 1) {
1519
+ if (start === -1)
1520
+ start = i;
1521
+ } else if (i !== 0 && (code === 32 || code === 9)) {
1522
+ if (end === -1 && start !== -1)
1523
+ end = i;
1524
+ } else if (code === 59 || code === 44) {
1525
+ if (start === -1) {
1526
+ throw new SyntaxError(`Unexpected character at index ${i}`);
1527
+ }
1528
+ if (end === -1)
1529
+ end = i;
1530
+ const name = header.slice(start, end);
1531
+ if (code === 44) {
1532
+ push(offers, name, params);
1533
+ params = Object.create(null);
1534
+ } else {
1535
+ extensionName = name;
1536
+ }
1537
+ start = end = -1;
1538
+ } else {
1539
+ throw new SyntaxError(`Unexpected character at index ${i}`);
1540
+ }
1541
+ } else if (paramName === undefined) {
1542
+ if (end === -1 && tokenChars[code] === 1) {
1543
+ if (start === -1)
1544
+ start = i;
1545
+ } else if (code === 32 || code === 9) {
1546
+ if (end === -1 && start !== -1)
1547
+ end = i;
1548
+ } else if (code === 59 || code === 44) {
1549
+ if (start === -1) {
1550
+ throw new SyntaxError(`Unexpected character at index ${i}`);
1551
+ }
1552
+ if (end === -1)
1553
+ end = i;
1554
+ push(params, header.slice(start, end), true);
1555
+ if (code === 44) {
1556
+ push(offers, extensionName, params);
1557
+ params = Object.create(null);
1558
+ extensionName = undefined;
1559
+ }
1560
+ start = end = -1;
1561
+ } else if (code === 61 && start !== -1 && end === -1) {
1562
+ paramName = header.slice(start, i);
1563
+ start = end = -1;
1564
+ } else {
1565
+ throw new SyntaxError(`Unexpected character at index ${i}`);
1566
+ }
1567
+ } else {
1568
+ if (isEscaping) {
1569
+ if (tokenChars[code] !== 1) {
1570
+ throw new SyntaxError(`Unexpected character at index ${i}`);
1571
+ }
1572
+ if (start === -1)
1573
+ start = i;
1574
+ else if (!mustUnescape)
1575
+ mustUnescape = true;
1576
+ isEscaping = false;
1577
+ } else if (inQuotes) {
1578
+ if (tokenChars[code] === 1) {
1579
+ if (start === -1)
1580
+ start = i;
1581
+ } else if (code === 34 && start !== -1) {
1582
+ inQuotes = false;
1583
+ end = i;
1584
+ } else if (code === 92) {
1585
+ isEscaping = true;
1586
+ } else {
1587
+ throw new SyntaxError(`Unexpected character at index ${i}`);
1588
+ }
1589
+ } else if (code === 34 && header.charCodeAt(i - 1) === 61) {
1590
+ inQuotes = true;
1591
+ } else if (end === -1 && tokenChars[code] === 1) {
1592
+ if (start === -1)
1593
+ start = i;
1594
+ } else if (start !== -1 && (code === 32 || code === 9)) {
1595
+ if (end === -1)
1596
+ end = i;
1597
+ } else if (code === 59 || code === 44) {
1598
+ if (start === -1) {
1599
+ throw new SyntaxError(`Unexpected character at index ${i}`);
1600
+ }
1601
+ if (end === -1)
1602
+ end = i;
1603
+ let value = header.slice(start, end);
1604
+ if (mustUnescape) {
1605
+ value = value.replace(/\\/g, "");
1606
+ mustUnescape = false;
1607
+ }
1608
+ push(params, paramName, value);
1609
+ if (code === 44) {
1610
+ push(offers, extensionName, params);
1611
+ params = Object.create(null);
1612
+ extensionName = undefined;
1613
+ }
1614
+ paramName = undefined;
1615
+ start = end = -1;
1616
+ } else {
1617
+ throw new SyntaxError(`Unexpected character at index ${i}`);
1618
+ }
1619
+ }
1620
+ }
1621
+ if (start === -1 || inQuotes || code === 32 || code === 9) {
1622
+ throw new SyntaxError("Unexpected end of input");
1623
+ }
1624
+ if (end === -1)
1625
+ end = i;
1626
+ const token = header.slice(start, end);
1627
+ if (extensionName === undefined) {
1628
+ push(offers, token, params);
1629
+ } else {
1630
+ if (paramName === undefined) {
1631
+ push(params, token, true);
1632
+ } else if (mustUnescape) {
1633
+ push(params, paramName, token.replace(/\\/g, ""));
1634
+ } else {
1635
+ push(params, paramName, token);
1636
+ }
1637
+ push(offers, extensionName, params);
1638
+ }
1639
+ return offers;
1640
+ }
1641
+ function format(extensions) {
1642
+ return Object.keys(extensions).map((extension) => {
1643
+ let configurations = extensions[extension];
1644
+ if (!Array.isArray(configurations))
1645
+ configurations = [configurations];
1646
+ return configurations.map((params) => {
1647
+ return [extension].concat(Object.keys(params).map((k) => {
1648
+ let values = params[k];
1649
+ if (!Array.isArray(values))
1650
+ values = [values];
1651
+ return values.map((v) => v === true ? k : `${k}=${v}`).join("; ");
1652
+ })).join("; ");
1653
+ }).join(", ");
1654
+ }).join(", ");
1655
+ }
1656
+ module.exports = { format, parse };
1657
+ });
1658
+
1659
+ // ../node_modules/ws/lib/websocket.js
1660
+ var require_websocket = __commonJS((exports, module) => {
1661
+ var EventEmitter = __require("events");
1662
+ var https = __require("https");
1663
+ var http = __require("http");
1664
+ var net = __require("net");
1665
+ var tls = __require("tls");
1666
+ var { randomBytes, createHash } = __require("crypto");
1667
+ var { Duplex, Readable } = __require("stream");
1668
+ var { URL } = __require("url");
1669
+ var PerMessageDeflate = require_permessage_deflate();
1670
+ var Receiver = require_receiver();
1671
+ var Sender = require_sender();
1672
+ var { isBlob } = require_validation();
1673
+ var {
1674
+ BINARY_TYPES,
1675
+ CLOSE_TIMEOUT,
1676
+ EMPTY_BUFFER,
1677
+ GUID,
1678
+ kForOnEventAttribute,
1679
+ kListener,
1680
+ kStatusCode,
1681
+ kWebSocket,
1682
+ NOOP
1683
+ } = require_constants();
1684
+ var {
1685
+ EventTarget: { addEventListener, removeEventListener }
1686
+ } = require_event_target();
1687
+ var { format, parse } = require_extension();
1688
+ var { toBuffer } = require_buffer_util();
1689
+ var kAborted = Symbol("kAborted");
1690
+ var protocolVersions = [8, 13];
1691
+ var readyStates = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"];
1692
+ var subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
1693
+
1694
+ class WebSocket extends EventEmitter {
1695
+ constructor(address, protocols, options) {
1696
+ super();
1697
+ this._binaryType = BINARY_TYPES[0];
1698
+ this._closeCode = 1006;
1699
+ this._closeFrameReceived = false;
1700
+ this._closeFrameSent = false;
1701
+ this._closeMessage = EMPTY_BUFFER;
1702
+ this._closeTimer = null;
1703
+ this._errorEmitted = false;
1704
+ this._extensions = {};
1705
+ this._paused = false;
1706
+ this._protocol = "";
1707
+ this._readyState = WebSocket.CONNECTING;
1708
+ this._receiver = null;
1709
+ this._sender = null;
1710
+ this._socket = null;
1711
+ if (address !== null) {
1712
+ this._bufferedAmount = 0;
1713
+ this._isServer = false;
1714
+ this._redirects = 0;
1715
+ if (protocols === undefined) {
1716
+ protocols = [];
1717
+ } else if (!Array.isArray(protocols)) {
1718
+ if (typeof protocols === "object" && protocols !== null) {
1719
+ options = protocols;
1720
+ protocols = [];
1721
+ } else {
1722
+ protocols = [protocols];
1723
+ }
1724
+ }
1725
+ initAsClient(this, address, protocols, options);
1726
+ } else {
1727
+ this._autoPong = options.autoPong;
1728
+ this._closeTimeout = options.closeTimeout;
1729
+ this._isServer = true;
1730
+ }
1731
+ }
1732
+ get binaryType() {
1733
+ return this._binaryType;
1734
+ }
1735
+ set binaryType(type) {
1736
+ if (!BINARY_TYPES.includes(type))
1737
+ return;
1738
+ this._binaryType = type;
1739
+ if (this._receiver)
1740
+ this._receiver._binaryType = type;
1741
+ }
1742
+ get bufferedAmount() {
1743
+ if (!this._socket)
1744
+ return this._bufferedAmount;
1745
+ return this._socket._writableState.length + this._sender._bufferedBytes;
1746
+ }
1747
+ get extensions() {
1748
+ return Object.keys(this._extensions).join();
1749
+ }
1750
+ get isPaused() {
1751
+ return this._paused;
1752
+ }
1753
+ get onclose() {
1754
+ return null;
1755
+ }
1756
+ get onerror() {
1757
+ return null;
1758
+ }
1759
+ get onopen() {
1760
+ return null;
1761
+ }
1762
+ get onmessage() {
1763
+ return null;
1764
+ }
1765
+ get protocol() {
1766
+ return this._protocol;
1767
+ }
1768
+ get readyState() {
1769
+ return this._readyState;
1770
+ }
1771
+ get url() {
1772
+ return this._url;
1773
+ }
1774
+ setSocket(socket, head, options) {
1775
+ const receiver = new Receiver({
1776
+ allowSynchronousEvents: options.allowSynchronousEvents,
1777
+ binaryType: this.binaryType,
1778
+ extensions: this._extensions,
1779
+ isServer: this._isServer,
1780
+ maxPayload: options.maxPayload,
1781
+ skipUTF8Validation: options.skipUTF8Validation
1782
+ });
1783
+ const sender = new Sender(socket, this._extensions, options.generateMask);
1784
+ this._receiver = receiver;
1785
+ this._sender = sender;
1786
+ this._socket = socket;
1787
+ receiver[kWebSocket] = this;
1788
+ sender[kWebSocket] = this;
1789
+ socket[kWebSocket] = this;
1790
+ receiver.on("conclude", receiverOnConclude);
1791
+ receiver.on("drain", receiverOnDrain);
1792
+ receiver.on("error", receiverOnError);
1793
+ receiver.on("message", receiverOnMessage);
1794
+ receiver.on("ping", receiverOnPing);
1795
+ receiver.on("pong", receiverOnPong);
1796
+ sender.onerror = senderOnError;
1797
+ if (socket.setTimeout)
1798
+ socket.setTimeout(0);
1799
+ if (socket.setNoDelay)
1800
+ socket.setNoDelay();
1801
+ if (head.length > 0)
1802
+ socket.unshift(head);
1803
+ socket.on("close", socketOnClose);
1804
+ socket.on("data", socketOnData);
1805
+ socket.on("end", socketOnEnd);
1806
+ socket.on("error", socketOnError);
1807
+ this._readyState = WebSocket.OPEN;
1808
+ this.emit("open");
1809
+ }
1810
+ emitClose() {
1811
+ if (!this._socket) {
1812
+ this._readyState = WebSocket.CLOSED;
1813
+ this.emit("close", this._closeCode, this._closeMessage);
1814
+ return;
1815
+ }
1816
+ if (this._extensions[PerMessageDeflate.extensionName]) {
1817
+ this._extensions[PerMessageDeflate.extensionName].cleanup();
1818
+ }
1819
+ this._receiver.removeAllListeners();
1820
+ this._readyState = WebSocket.CLOSED;
1821
+ this.emit("close", this._closeCode, this._closeMessage);
1822
+ }
1823
+ close(code, data) {
1824
+ if (this.readyState === WebSocket.CLOSED)
1825
+ return;
1826
+ if (this.readyState === WebSocket.CONNECTING) {
1827
+ const msg = "WebSocket was closed before the connection was established";
1828
+ abortHandshake(this, this._req, msg);
1829
+ return;
1830
+ }
1831
+ if (this.readyState === WebSocket.CLOSING) {
1832
+ if (this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted)) {
1833
+ this._socket.end();
1834
+ }
1835
+ return;
1836
+ }
1837
+ this._readyState = WebSocket.CLOSING;
1838
+ this._sender.close(code, data, !this._isServer, (err) => {
1839
+ if (err)
1840
+ return;
1841
+ this._closeFrameSent = true;
1842
+ if (this._closeFrameReceived || this._receiver._writableState.errorEmitted) {
1843
+ this._socket.end();
1844
+ }
1845
+ });
1846
+ setCloseTimer(this);
1847
+ }
1848
+ pause() {
1849
+ if (this.readyState === WebSocket.CONNECTING || this.readyState === WebSocket.CLOSED) {
1850
+ return;
1851
+ }
1852
+ this._paused = true;
1853
+ this._socket.pause();
1854
+ }
1855
+ ping(data, mask, cb) {
1856
+ if (this.readyState === WebSocket.CONNECTING) {
1857
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
1858
+ }
1859
+ if (typeof data === "function") {
1860
+ cb = data;
1861
+ data = mask = undefined;
1862
+ } else if (typeof mask === "function") {
1863
+ cb = mask;
1864
+ mask = undefined;
1865
+ }
1866
+ if (typeof data === "number")
1867
+ data = data.toString();
1868
+ if (this.readyState !== WebSocket.OPEN) {
1869
+ sendAfterClose(this, data, cb);
1870
+ return;
1871
+ }
1872
+ if (mask === undefined)
1873
+ mask = !this._isServer;
1874
+ this._sender.ping(data || EMPTY_BUFFER, mask, cb);
1875
+ }
1876
+ pong(data, mask, cb) {
1877
+ if (this.readyState === WebSocket.CONNECTING) {
1878
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
1879
+ }
1880
+ if (typeof data === "function") {
1881
+ cb = data;
1882
+ data = mask = undefined;
1883
+ } else if (typeof mask === "function") {
1884
+ cb = mask;
1885
+ mask = undefined;
1886
+ }
1887
+ if (typeof data === "number")
1888
+ data = data.toString();
1889
+ if (this.readyState !== WebSocket.OPEN) {
1890
+ sendAfterClose(this, data, cb);
1891
+ return;
1892
+ }
1893
+ if (mask === undefined)
1894
+ mask = !this._isServer;
1895
+ this._sender.pong(data || EMPTY_BUFFER, mask, cb);
1896
+ }
1897
+ resume() {
1898
+ if (this.readyState === WebSocket.CONNECTING || this.readyState === WebSocket.CLOSED) {
1899
+ return;
1900
+ }
1901
+ this._paused = false;
1902
+ if (!this._receiver._writableState.needDrain)
1903
+ this._socket.resume();
1904
+ }
1905
+ send(data, options, cb) {
1906
+ if (this.readyState === WebSocket.CONNECTING) {
1907
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
1908
+ }
1909
+ if (typeof options === "function") {
1910
+ cb = options;
1911
+ options = {};
1912
+ }
1913
+ if (typeof data === "number")
1914
+ data = data.toString();
1915
+ if (this.readyState !== WebSocket.OPEN) {
1916
+ sendAfterClose(this, data, cb);
1917
+ return;
1918
+ }
1919
+ const opts = {
1920
+ binary: typeof data !== "string",
1921
+ mask: !this._isServer,
1922
+ compress: true,
1923
+ fin: true,
1924
+ ...options
1925
+ };
1926
+ if (!this._extensions[PerMessageDeflate.extensionName]) {
1927
+ opts.compress = false;
1928
+ }
1929
+ this._sender.send(data || EMPTY_BUFFER, opts, cb);
1930
+ }
1931
+ terminate() {
1932
+ if (this.readyState === WebSocket.CLOSED)
1933
+ return;
1934
+ if (this.readyState === WebSocket.CONNECTING) {
1935
+ const msg = "WebSocket was closed before the connection was established";
1936
+ abortHandshake(this, this._req, msg);
1937
+ return;
1938
+ }
1939
+ if (this._socket) {
1940
+ this._readyState = WebSocket.CLOSING;
1941
+ this._socket.destroy();
1942
+ }
1943
+ }
1944
+ }
1945
+ Object.defineProperty(WebSocket, "CONNECTING", {
1946
+ enumerable: true,
1947
+ value: readyStates.indexOf("CONNECTING")
1948
+ });
1949
+ Object.defineProperty(WebSocket.prototype, "CONNECTING", {
1950
+ enumerable: true,
1951
+ value: readyStates.indexOf("CONNECTING")
1952
+ });
1953
+ Object.defineProperty(WebSocket, "OPEN", {
1954
+ enumerable: true,
1955
+ value: readyStates.indexOf("OPEN")
1956
+ });
1957
+ Object.defineProperty(WebSocket.prototype, "OPEN", {
1958
+ enumerable: true,
1959
+ value: readyStates.indexOf("OPEN")
1960
+ });
1961
+ Object.defineProperty(WebSocket, "CLOSING", {
1962
+ enumerable: true,
1963
+ value: readyStates.indexOf("CLOSING")
1964
+ });
1965
+ Object.defineProperty(WebSocket.prototype, "CLOSING", {
1966
+ enumerable: true,
1967
+ value: readyStates.indexOf("CLOSING")
1968
+ });
1969
+ Object.defineProperty(WebSocket, "CLOSED", {
1970
+ enumerable: true,
1971
+ value: readyStates.indexOf("CLOSED")
1972
+ });
1973
+ Object.defineProperty(WebSocket.prototype, "CLOSED", {
1974
+ enumerable: true,
1975
+ value: readyStates.indexOf("CLOSED")
1976
+ });
1977
+ [
1978
+ "binaryType",
1979
+ "bufferedAmount",
1980
+ "extensions",
1981
+ "isPaused",
1982
+ "protocol",
1983
+ "readyState",
1984
+ "url"
1985
+ ].forEach((property) => {
1986
+ Object.defineProperty(WebSocket.prototype, property, { enumerable: true });
1987
+ });
1988
+ ["open", "error", "close", "message"].forEach((method) => {
1989
+ Object.defineProperty(WebSocket.prototype, `on${method}`, {
1990
+ enumerable: true,
1991
+ get() {
1992
+ for (const listener of this.listeners(method)) {
1993
+ if (listener[kForOnEventAttribute])
1994
+ return listener[kListener];
1995
+ }
1996
+ return null;
1997
+ },
1998
+ set(handler) {
1999
+ for (const listener of this.listeners(method)) {
2000
+ if (listener[kForOnEventAttribute]) {
2001
+ this.removeListener(method, listener);
2002
+ break;
2003
+ }
2004
+ }
2005
+ if (typeof handler !== "function")
2006
+ return;
2007
+ this.addEventListener(method, handler, {
2008
+ [kForOnEventAttribute]: true
2009
+ });
2010
+ }
2011
+ });
2012
+ });
2013
+ WebSocket.prototype.addEventListener = addEventListener;
2014
+ WebSocket.prototype.removeEventListener = removeEventListener;
2015
+ module.exports = WebSocket;
2016
+ function initAsClient(websocket, address, protocols, options) {
2017
+ const opts = {
2018
+ allowSynchronousEvents: true,
2019
+ autoPong: true,
2020
+ closeTimeout: CLOSE_TIMEOUT,
2021
+ protocolVersion: protocolVersions[1],
2022
+ maxPayload: 100 * 1024 * 1024,
2023
+ skipUTF8Validation: false,
2024
+ perMessageDeflate: true,
2025
+ followRedirects: false,
2026
+ maxRedirects: 10,
2027
+ ...options,
2028
+ socketPath: undefined,
2029
+ hostname: undefined,
2030
+ protocol: undefined,
2031
+ timeout: undefined,
2032
+ method: "GET",
2033
+ host: undefined,
2034
+ path: undefined,
2035
+ port: undefined
2036
+ };
2037
+ websocket._autoPong = opts.autoPong;
2038
+ websocket._closeTimeout = opts.closeTimeout;
2039
+ if (!protocolVersions.includes(opts.protocolVersion)) {
2040
+ throw new RangeError(`Unsupported protocol version: ${opts.protocolVersion} ` + `(supported versions: ${protocolVersions.join(", ")})`);
2041
+ }
2042
+ let parsedUrl;
2043
+ if (address instanceof URL) {
2044
+ parsedUrl = address;
2045
+ } else {
2046
+ try {
2047
+ parsedUrl = new URL(address);
2048
+ } catch {
2049
+ throw new SyntaxError(`Invalid URL: ${address}`);
2050
+ }
2051
+ }
2052
+ if (parsedUrl.protocol === "http:") {
2053
+ parsedUrl.protocol = "ws:";
2054
+ } else if (parsedUrl.protocol === "https:") {
2055
+ parsedUrl.protocol = "wss:";
2056
+ }
2057
+ websocket._url = parsedUrl.href;
2058
+ const isSecure = parsedUrl.protocol === "wss:";
2059
+ const isIpcUrl = parsedUrl.protocol === "ws+unix:";
2060
+ let invalidUrlMessage;
2061
+ if (parsedUrl.protocol !== "ws:" && !isSecure && !isIpcUrl) {
2062
+ invalidUrlMessage = `The URL's protocol must be one of "ws:", "wss:", ` + '"http:", "https:", or "ws+unix:"';
2063
+ } else if (isIpcUrl && !parsedUrl.pathname) {
2064
+ invalidUrlMessage = "The URL's pathname is empty";
2065
+ } else if (parsedUrl.hash) {
2066
+ invalidUrlMessage = "The URL contains a fragment identifier";
2067
+ }
2068
+ if (invalidUrlMessage) {
2069
+ const err = new SyntaxError(invalidUrlMessage);
2070
+ if (websocket._redirects === 0) {
2071
+ throw err;
2072
+ } else {
2073
+ emitErrorAndClose(websocket, err);
2074
+ return;
2075
+ }
2076
+ }
2077
+ const defaultPort = isSecure ? 443 : 80;
2078
+ const key = randomBytes(16).toString("base64");
2079
+ const request = isSecure ? https.request : http.request;
2080
+ const protocolSet = new Set;
2081
+ let perMessageDeflate;
2082
+ opts.createConnection = opts.createConnection || (isSecure ? tlsConnect : netConnect);
2083
+ opts.defaultPort = opts.defaultPort || defaultPort;
2084
+ opts.port = parsedUrl.port || defaultPort;
2085
+ opts.host = parsedUrl.hostname.startsWith("[") ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname;
2086
+ opts.headers = {
2087
+ ...opts.headers,
2088
+ "Sec-WebSocket-Version": opts.protocolVersion,
2089
+ "Sec-WebSocket-Key": key,
2090
+ Connection: "Upgrade",
2091
+ Upgrade: "websocket"
2092
+ };
2093
+ opts.path = parsedUrl.pathname + parsedUrl.search;
2094
+ opts.timeout = opts.handshakeTimeout;
2095
+ if (opts.perMessageDeflate) {
2096
+ perMessageDeflate = new PerMessageDeflate({
2097
+ ...opts.perMessageDeflate,
2098
+ isServer: false,
2099
+ maxPayload: opts.maxPayload
2100
+ });
2101
+ opts.headers["Sec-WebSocket-Extensions"] = format({
2102
+ [PerMessageDeflate.extensionName]: perMessageDeflate.offer()
2103
+ });
2104
+ }
2105
+ if (protocols.length) {
2106
+ for (const protocol of protocols) {
2107
+ if (typeof protocol !== "string" || !subprotocolRegex.test(protocol) || protocolSet.has(protocol)) {
2108
+ throw new SyntaxError("An invalid or duplicated subprotocol was specified");
2109
+ }
2110
+ protocolSet.add(protocol);
2111
+ }
2112
+ opts.headers["Sec-WebSocket-Protocol"] = protocols.join(",");
2113
+ }
2114
+ if (opts.origin) {
2115
+ if (opts.protocolVersion < 13) {
2116
+ opts.headers["Sec-WebSocket-Origin"] = opts.origin;
2117
+ } else {
2118
+ opts.headers.Origin = opts.origin;
2119
+ }
2120
+ }
2121
+ if (parsedUrl.username || parsedUrl.password) {
2122
+ opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
2123
+ }
2124
+ if (isIpcUrl) {
2125
+ const parts = opts.path.split(":");
2126
+ opts.socketPath = parts[0];
2127
+ opts.path = parts[1];
2128
+ }
2129
+ let req;
2130
+ if (opts.followRedirects) {
2131
+ if (websocket._redirects === 0) {
2132
+ websocket._originalIpc = isIpcUrl;
2133
+ websocket._originalSecure = isSecure;
2134
+ websocket._originalHostOrSocketPath = isIpcUrl ? opts.socketPath : parsedUrl.host;
2135
+ const headers = options && options.headers;
2136
+ options = { ...options, headers: {} };
2137
+ if (headers) {
2138
+ for (const [key2, value] of Object.entries(headers)) {
2139
+ options.headers[key2.toLowerCase()] = value;
2140
+ }
2141
+ }
2142
+ } else if (websocket.listenerCount("redirect") === 0) {
2143
+ const isSameHost = isIpcUrl ? websocket._originalIpc ? opts.socketPath === websocket._originalHostOrSocketPath : false : websocket._originalIpc ? false : parsedUrl.host === websocket._originalHostOrSocketPath;
2144
+ if (!isSameHost || websocket._originalSecure && !isSecure) {
2145
+ delete opts.headers.authorization;
2146
+ delete opts.headers.cookie;
2147
+ if (!isSameHost)
2148
+ delete opts.headers.host;
2149
+ opts.auth = undefined;
2150
+ }
2151
+ }
2152
+ if (opts.auth && !options.headers.authorization) {
2153
+ options.headers.authorization = "Basic " + Buffer.from(opts.auth).toString("base64");
2154
+ }
2155
+ req = websocket._req = request(opts);
2156
+ if (websocket._redirects) {
2157
+ websocket.emit("redirect", websocket.url, req);
2158
+ }
2159
+ } else {
2160
+ req = websocket._req = request(opts);
2161
+ }
2162
+ if (opts.timeout) {
2163
+ req.on("timeout", () => {
2164
+ abortHandshake(websocket, req, "Opening handshake has timed out");
2165
+ });
2166
+ }
2167
+ req.on("error", (err) => {
2168
+ if (req === null || req[kAborted])
2169
+ return;
2170
+ req = websocket._req = null;
2171
+ emitErrorAndClose(websocket, err);
2172
+ });
2173
+ req.on("response", (res) => {
2174
+ const location = res.headers.location;
2175
+ const statusCode = res.statusCode;
2176
+ if (location && opts.followRedirects && statusCode >= 300 && statusCode < 400) {
2177
+ if (++websocket._redirects > opts.maxRedirects) {
2178
+ abortHandshake(websocket, req, "Maximum redirects exceeded");
2179
+ return;
2180
+ }
2181
+ req.abort();
2182
+ let addr;
2183
+ try {
2184
+ addr = new URL(location, address);
2185
+ } catch (e) {
2186
+ const err = new SyntaxError(`Invalid URL: ${location}`);
2187
+ emitErrorAndClose(websocket, err);
2188
+ return;
2189
+ }
2190
+ initAsClient(websocket, addr, protocols, options);
2191
+ } else if (!websocket.emit("unexpected-response", req, res)) {
2192
+ abortHandshake(websocket, req, `Unexpected server response: ${res.statusCode}`);
2193
+ }
2194
+ });
2195
+ req.on("upgrade", (res, socket, head) => {
2196
+ websocket.emit("upgrade", res);
2197
+ if (websocket.readyState !== WebSocket.CONNECTING)
2198
+ return;
2199
+ req = websocket._req = null;
2200
+ const upgrade = res.headers.upgrade;
2201
+ if (upgrade === undefined || upgrade.toLowerCase() !== "websocket") {
2202
+ abortHandshake(websocket, socket, "Invalid Upgrade header");
2203
+ return;
2204
+ }
2205
+ const digest = createHash("sha1").update(key + GUID).digest("base64");
2206
+ if (res.headers["sec-websocket-accept"] !== digest) {
2207
+ abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
2208
+ return;
2209
+ }
2210
+ const serverProt = res.headers["sec-websocket-protocol"];
2211
+ let protError;
2212
+ if (serverProt !== undefined) {
2213
+ if (!protocolSet.size) {
2214
+ protError = "Server sent a subprotocol but none was requested";
2215
+ } else if (!protocolSet.has(serverProt)) {
2216
+ protError = "Server sent an invalid subprotocol";
2217
+ }
2218
+ } else if (protocolSet.size) {
2219
+ protError = "Server sent no subprotocol";
2220
+ }
2221
+ if (protError) {
2222
+ abortHandshake(websocket, socket, protError);
2223
+ return;
2224
+ }
2225
+ if (serverProt)
2226
+ websocket._protocol = serverProt;
2227
+ const secWebSocketExtensions = res.headers["sec-websocket-extensions"];
2228
+ if (secWebSocketExtensions !== undefined) {
2229
+ if (!perMessageDeflate) {
2230
+ const message = "Server sent a Sec-WebSocket-Extensions header but no extension " + "was requested";
2231
+ abortHandshake(websocket, socket, message);
2232
+ return;
2233
+ }
2234
+ let extensions;
2235
+ try {
2236
+ extensions = parse(secWebSocketExtensions);
2237
+ } catch (err) {
2238
+ const message = "Invalid Sec-WebSocket-Extensions header";
2239
+ abortHandshake(websocket, socket, message);
2240
+ return;
2241
+ }
2242
+ const extensionNames = Object.keys(extensions);
2243
+ if (extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate.extensionName) {
2244
+ const message = "Server indicated an extension that was not requested";
2245
+ abortHandshake(websocket, socket, message);
2246
+ return;
2247
+ }
2248
+ try {
2249
+ perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]);
2250
+ } catch (err) {
2251
+ const message = "Invalid Sec-WebSocket-Extensions header";
2252
+ abortHandshake(websocket, socket, message);
2253
+ return;
2254
+ }
2255
+ websocket._extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
2256
+ }
2257
+ websocket.setSocket(socket, head, {
2258
+ allowSynchronousEvents: opts.allowSynchronousEvents,
2259
+ generateMask: opts.generateMask,
2260
+ maxPayload: opts.maxPayload,
2261
+ skipUTF8Validation: opts.skipUTF8Validation
2262
+ });
2263
+ });
2264
+ if (opts.finishRequest) {
2265
+ opts.finishRequest(req, websocket);
2266
+ } else {
2267
+ req.end();
2268
+ }
2269
+ }
2270
+ function emitErrorAndClose(websocket, err) {
2271
+ websocket._readyState = WebSocket.CLOSING;
2272
+ websocket._errorEmitted = true;
2273
+ websocket.emit("error", err);
2274
+ websocket.emitClose();
2275
+ }
2276
+ function netConnect(options) {
2277
+ options.path = options.socketPath;
2278
+ return net.connect(options);
2279
+ }
2280
+ function tlsConnect(options) {
2281
+ options.path = undefined;
2282
+ if (!options.servername && options.servername !== "") {
2283
+ options.servername = net.isIP(options.host) ? "" : options.host;
2284
+ }
2285
+ return tls.connect(options);
2286
+ }
2287
+ function abortHandshake(websocket, stream, message) {
2288
+ websocket._readyState = WebSocket.CLOSING;
2289
+ const err = new Error(message);
2290
+ Error.captureStackTrace(err, abortHandshake);
2291
+ if (stream.setHeader) {
2292
+ stream[kAborted] = true;
2293
+ stream.abort();
2294
+ if (stream.socket && !stream.socket.destroyed) {
2295
+ stream.socket.destroy();
2296
+ }
2297
+ process.nextTick(emitErrorAndClose, websocket, err);
2298
+ } else {
2299
+ stream.destroy(err);
2300
+ stream.once("error", websocket.emit.bind(websocket, "error"));
2301
+ stream.once("close", websocket.emitClose.bind(websocket));
2302
+ }
2303
+ }
2304
+ function sendAfterClose(websocket, data, cb) {
2305
+ if (data) {
2306
+ const length = isBlob(data) ? data.size : toBuffer(data).length;
2307
+ if (websocket._socket)
2308
+ websocket._sender._bufferedBytes += length;
2309
+ else
2310
+ websocket._bufferedAmount += length;
2311
+ }
2312
+ if (cb) {
2313
+ const err = new Error(`WebSocket is not open: readyState ${websocket.readyState} ` + `(${readyStates[websocket.readyState]})`);
2314
+ process.nextTick(cb, err);
2315
+ }
2316
+ }
2317
+ function receiverOnConclude(code, reason) {
2318
+ const websocket = this[kWebSocket];
2319
+ websocket._closeFrameReceived = true;
2320
+ websocket._closeMessage = reason;
2321
+ websocket._closeCode = code;
2322
+ if (websocket._socket[kWebSocket] === undefined)
2323
+ return;
2324
+ websocket._socket.removeListener("data", socketOnData);
2325
+ process.nextTick(resume, websocket._socket);
2326
+ if (code === 1005)
2327
+ websocket.close();
2328
+ else
2329
+ websocket.close(code, reason);
2330
+ }
2331
+ function receiverOnDrain() {
2332
+ const websocket = this[kWebSocket];
2333
+ if (!websocket.isPaused)
2334
+ websocket._socket.resume();
2335
+ }
2336
+ function receiverOnError(err) {
2337
+ const websocket = this[kWebSocket];
2338
+ if (websocket._socket[kWebSocket] !== undefined) {
2339
+ websocket._socket.removeListener("data", socketOnData);
2340
+ process.nextTick(resume, websocket._socket);
2341
+ websocket.close(err[kStatusCode]);
2342
+ }
2343
+ if (!websocket._errorEmitted) {
2344
+ websocket._errorEmitted = true;
2345
+ websocket.emit("error", err);
2346
+ }
2347
+ }
2348
+ function receiverOnFinish() {
2349
+ this[kWebSocket].emitClose();
2350
+ }
2351
+ function receiverOnMessage(data, isBinary) {
2352
+ this[kWebSocket].emit("message", data, isBinary);
2353
+ }
2354
+ function receiverOnPing(data) {
2355
+ const websocket = this[kWebSocket];
2356
+ if (websocket._autoPong)
2357
+ websocket.pong(data, !this._isServer, NOOP);
2358
+ websocket.emit("ping", data);
2359
+ }
2360
+ function receiverOnPong(data) {
2361
+ this[kWebSocket].emit("pong", data);
2362
+ }
2363
+ function resume(stream) {
2364
+ stream.resume();
2365
+ }
2366
+ function senderOnError(err) {
2367
+ const websocket = this[kWebSocket];
2368
+ if (websocket.readyState === WebSocket.CLOSED)
2369
+ return;
2370
+ if (websocket.readyState === WebSocket.OPEN) {
2371
+ websocket._readyState = WebSocket.CLOSING;
2372
+ setCloseTimer(websocket);
2373
+ }
2374
+ this._socket.end();
2375
+ if (!websocket._errorEmitted) {
2376
+ websocket._errorEmitted = true;
2377
+ websocket.emit("error", err);
2378
+ }
2379
+ }
2380
+ function setCloseTimer(websocket) {
2381
+ websocket._closeTimer = setTimeout(websocket._socket.destroy.bind(websocket._socket), websocket._closeTimeout);
2382
+ }
2383
+ function socketOnClose() {
2384
+ const websocket = this[kWebSocket];
2385
+ this.removeListener("close", socketOnClose);
2386
+ this.removeListener("data", socketOnData);
2387
+ this.removeListener("end", socketOnEnd);
2388
+ websocket._readyState = WebSocket.CLOSING;
2389
+ if (!this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && this._readableState.length !== 0) {
2390
+ const chunk = this.read(this._readableState.length);
2391
+ websocket._receiver.write(chunk);
2392
+ }
2393
+ websocket._receiver.end();
2394
+ this[kWebSocket] = undefined;
2395
+ clearTimeout(websocket._closeTimer);
2396
+ if (websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted) {
2397
+ websocket.emitClose();
2398
+ } else {
2399
+ websocket._receiver.on("error", receiverOnFinish);
2400
+ websocket._receiver.on("finish", receiverOnFinish);
2401
+ }
2402
+ }
2403
+ function socketOnData(chunk) {
2404
+ if (!this[kWebSocket]._receiver.write(chunk)) {
2405
+ this.pause();
2406
+ }
2407
+ }
2408
+ function socketOnEnd() {
2409
+ const websocket = this[kWebSocket];
2410
+ websocket._readyState = WebSocket.CLOSING;
2411
+ websocket._receiver.end();
2412
+ this.end();
2413
+ }
2414
+ function socketOnError() {
2415
+ const websocket = this[kWebSocket];
2416
+ this.removeListener("error", socketOnError);
2417
+ this.on("error", NOOP);
2418
+ if (websocket) {
2419
+ websocket._readyState = WebSocket.CLOSING;
2420
+ this.destroy();
2421
+ }
2422
+ }
2423
+ });
2424
+
2425
+ // ../node_modules/ws/lib/stream.js
2426
+ var require_stream = __commonJS((exports, module) => {
2427
+ var WebSocket = require_websocket();
2428
+ var { Duplex } = __require("stream");
2429
+ function emitClose(stream) {
2430
+ stream.emit("close");
2431
+ }
2432
+ function duplexOnEnd() {
2433
+ if (!this.destroyed && this._writableState.finished) {
2434
+ this.destroy();
2435
+ }
2436
+ }
2437
+ function duplexOnError(err) {
2438
+ this.removeListener("error", duplexOnError);
2439
+ this.destroy();
2440
+ if (this.listenerCount("error") === 0) {
2441
+ this.emit("error", err);
2442
+ }
2443
+ }
2444
+ function createWebSocketStream(ws, options) {
2445
+ let terminateOnDestroy = true;
2446
+ const duplex = new Duplex({
2447
+ ...options,
2448
+ autoDestroy: false,
2449
+ emitClose: false,
2450
+ objectMode: false,
2451
+ writableObjectMode: false
2452
+ });
2453
+ ws.on("message", function message(msg, isBinary) {
2454
+ const data = !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;
2455
+ if (!duplex.push(data))
2456
+ ws.pause();
2457
+ });
2458
+ ws.once("error", function error(err) {
2459
+ if (duplex.destroyed)
2460
+ return;
2461
+ terminateOnDestroy = false;
2462
+ duplex.destroy(err);
2463
+ });
2464
+ ws.once("close", function close() {
2465
+ if (duplex.destroyed)
2466
+ return;
2467
+ duplex.push(null);
2468
+ });
2469
+ duplex._destroy = function(err, callback) {
2470
+ if (ws.readyState === ws.CLOSED) {
2471
+ callback(err);
2472
+ process.nextTick(emitClose, duplex);
2473
+ return;
2474
+ }
2475
+ let called = false;
2476
+ ws.once("error", function error(err2) {
2477
+ called = true;
2478
+ callback(err2);
2479
+ });
2480
+ ws.once("close", function close() {
2481
+ if (!called)
2482
+ callback(err);
2483
+ process.nextTick(emitClose, duplex);
2484
+ });
2485
+ if (terminateOnDestroy)
2486
+ ws.terminate();
2487
+ };
2488
+ duplex._final = function(callback) {
2489
+ if (ws.readyState === ws.CONNECTING) {
2490
+ ws.once("open", function open() {
2491
+ duplex._final(callback);
2492
+ });
2493
+ return;
2494
+ }
2495
+ if (ws._socket === null)
2496
+ return;
2497
+ if (ws._socket._writableState.finished) {
2498
+ callback();
2499
+ if (duplex._readableState.endEmitted)
2500
+ duplex.destroy();
2501
+ } else {
2502
+ ws._socket.once("finish", function finish() {
2503
+ callback();
2504
+ });
2505
+ ws.close();
2506
+ }
2507
+ };
2508
+ duplex._read = function() {
2509
+ if (ws.isPaused)
2510
+ ws.resume();
2511
+ };
2512
+ duplex._write = function(chunk, encoding, callback) {
2513
+ if (ws.readyState === ws.CONNECTING) {
2514
+ ws.once("open", function open() {
2515
+ duplex._write(chunk, encoding, callback);
2516
+ });
2517
+ return;
2518
+ }
2519
+ ws.send(chunk, callback);
2520
+ };
2521
+ duplex.on("end", duplexOnEnd);
2522
+ duplex.on("error", duplexOnError);
2523
+ return duplex;
2524
+ }
2525
+ module.exports = createWebSocketStream;
2526
+ });
2527
+
2528
+ // ../node_modules/ws/lib/subprotocol.js
2529
+ var require_subprotocol = __commonJS((exports, module) => {
2530
+ var { tokenChars } = require_validation();
2531
+ function parse(header) {
2532
+ const protocols = new Set;
2533
+ let start = -1;
2534
+ let end = -1;
2535
+ let i = 0;
2536
+ for (i;i < header.length; i++) {
2537
+ const code = header.charCodeAt(i);
2538
+ if (end === -1 && tokenChars[code] === 1) {
2539
+ if (start === -1)
2540
+ start = i;
2541
+ } else if (i !== 0 && (code === 32 || code === 9)) {
2542
+ if (end === -1 && start !== -1)
2543
+ end = i;
2544
+ } else if (code === 44) {
2545
+ if (start === -1) {
2546
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2547
+ }
2548
+ if (end === -1)
2549
+ end = i;
2550
+ const protocol2 = header.slice(start, end);
2551
+ if (protocols.has(protocol2)) {
2552
+ throw new SyntaxError(`The "${protocol2}" subprotocol is duplicated`);
2553
+ }
2554
+ protocols.add(protocol2);
2555
+ start = end = -1;
2556
+ } else {
2557
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2558
+ }
2559
+ }
2560
+ if (start === -1 || end !== -1) {
2561
+ throw new SyntaxError("Unexpected end of input");
2562
+ }
2563
+ const protocol = header.slice(start, i);
2564
+ if (protocols.has(protocol)) {
2565
+ throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
2566
+ }
2567
+ protocols.add(protocol);
2568
+ return protocols;
2569
+ }
2570
+ module.exports = { parse };
2571
+ });
2572
+
2573
+ // ../node_modules/ws/lib/websocket-server.js
2574
+ var require_websocket_server = __commonJS((exports, module) => {
2575
+ var EventEmitter = __require("events");
2576
+ var http = __require("http");
2577
+ var { Duplex } = __require("stream");
2578
+ var { createHash } = __require("crypto");
2579
+ var extension = require_extension();
2580
+ var PerMessageDeflate = require_permessage_deflate();
2581
+ var subprotocol = require_subprotocol();
2582
+ var WebSocket = require_websocket();
2583
+ var { CLOSE_TIMEOUT, GUID, kWebSocket } = require_constants();
2584
+ var keyRegex = /^[+/0-9A-Za-z]{22}==$/;
2585
+ var RUNNING = 0;
2586
+ var CLOSING = 1;
2587
+ var CLOSED = 2;
2588
+
2589
+ class WebSocketServer extends EventEmitter {
2590
+ constructor(options, callback) {
2591
+ super();
2592
+ options = {
2593
+ allowSynchronousEvents: true,
2594
+ autoPong: true,
2595
+ maxPayload: 100 * 1024 * 1024,
2596
+ skipUTF8Validation: false,
2597
+ perMessageDeflate: false,
2598
+ handleProtocols: null,
2599
+ clientTracking: true,
2600
+ closeTimeout: CLOSE_TIMEOUT,
2601
+ verifyClient: null,
2602
+ noServer: false,
2603
+ backlog: null,
2604
+ server: null,
2605
+ host: null,
2606
+ path: null,
2607
+ port: null,
2608
+ WebSocket,
2609
+ ...options
2610
+ };
2611
+ if (options.port == null && !options.server && !options.noServer || options.port != null && (options.server || options.noServer) || options.server && options.noServer) {
2612
+ throw new TypeError('One and only one of the "port", "server", or "noServer" options ' + "must be specified");
2613
+ }
2614
+ if (options.port != null) {
2615
+ this._server = http.createServer((req, res) => {
2616
+ const body = http.STATUS_CODES[426];
2617
+ res.writeHead(426, {
2618
+ "Content-Length": body.length,
2619
+ "Content-Type": "text/plain"
2620
+ });
2621
+ res.end(body);
2622
+ });
2623
+ this._server.listen(options.port, options.host, options.backlog, callback);
2624
+ } else if (options.server) {
2625
+ this._server = options.server;
2626
+ }
2627
+ if (this._server) {
2628
+ const emitConnection = this.emit.bind(this, "connection");
2629
+ this._removeListeners = addListeners(this._server, {
2630
+ listening: this.emit.bind(this, "listening"),
2631
+ error: this.emit.bind(this, "error"),
2632
+ upgrade: (req, socket, head) => {
2633
+ this.handleUpgrade(req, socket, head, emitConnection);
2634
+ }
2635
+ });
2636
+ }
2637
+ if (options.perMessageDeflate === true)
2638
+ options.perMessageDeflate = {};
2639
+ if (options.clientTracking) {
2640
+ this.clients = new Set;
2641
+ this._shouldEmitClose = false;
2642
+ }
2643
+ this.options = options;
2644
+ this._state = RUNNING;
2645
+ }
2646
+ address() {
2647
+ if (this.options.noServer) {
2648
+ throw new Error('The server is operating in "noServer" mode');
2649
+ }
2650
+ if (!this._server)
2651
+ return null;
2652
+ return this._server.address();
2653
+ }
2654
+ close(cb) {
2655
+ if (this._state === CLOSED) {
2656
+ if (cb) {
2657
+ this.once("close", () => {
2658
+ cb(new Error("The server is not running"));
2659
+ });
2660
+ }
2661
+ process.nextTick(emitClose, this);
2662
+ return;
2663
+ }
2664
+ if (cb)
2665
+ this.once("close", cb);
2666
+ if (this._state === CLOSING)
2667
+ return;
2668
+ this._state = CLOSING;
2669
+ if (this.options.noServer || this.options.server) {
2670
+ if (this._server) {
2671
+ this._removeListeners();
2672
+ this._removeListeners = this._server = null;
2673
+ }
2674
+ if (this.clients) {
2675
+ if (!this.clients.size) {
2676
+ process.nextTick(emitClose, this);
2677
+ } else {
2678
+ this._shouldEmitClose = true;
2679
+ }
2680
+ } else {
2681
+ process.nextTick(emitClose, this);
2682
+ }
2683
+ } else {
2684
+ const server = this._server;
2685
+ this._removeListeners();
2686
+ this._removeListeners = this._server = null;
2687
+ server.close(() => {
2688
+ emitClose(this);
2689
+ });
2690
+ }
2691
+ }
2692
+ shouldHandle(req) {
2693
+ if (this.options.path) {
2694
+ const index = req.url.indexOf("?");
2695
+ const pathname = index !== -1 ? req.url.slice(0, index) : req.url;
2696
+ if (pathname !== this.options.path)
2697
+ return false;
2698
+ }
2699
+ return true;
2700
+ }
2701
+ handleUpgrade(req, socket, head, cb) {
2702
+ socket.on("error", socketOnError);
2703
+ const key = req.headers["sec-websocket-key"];
2704
+ const upgrade = req.headers.upgrade;
2705
+ const version = +req.headers["sec-websocket-version"];
2706
+ if (req.method !== "GET") {
2707
+ const message = "Invalid HTTP method";
2708
+ abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);
2709
+ return;
2710
+ }
2711
+ if (upgrade === undefined || upgrade.toLowerCase() !== "websocket") {
2712
+ const message = "Invalid Upgrade header";
2713
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
2714
+ return;
2715
+ }
2716
+ if (key === undefined || !keyRegex.test(key)) {
2717
+ const message = "Missing or invalid Sec-WebSocket-Key header";
2718
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
2719
+ return;
2720
+ }
2721
+ if (version !== 13 && version !== 8) {
2722
+ const message = "Missing or invalid Sec-WebSocket-Version header";
2723
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message, {
2724
+ "Sec-WebSocket-Version": "13, 8"
2725
+ });
2726
+ return;
2727
+ }
2728
+ if (!this.shouldHandle(req)) {
2729
+ abortHandshake(socket, 400);
2730
+ return;
2731
+ }
2732
+ const secWebSocketProtocol = req.headers["sec-websocket-protocol"];
2733
+ let protocols = new Set;
2734
+ if (secWebSocketProtocol !== undefined) {
2735
+ try {
2736
+ protocols = subprotocol.parse(secWebSocketProtocol);
2737
+ } catch (err) {
2738
+ const message = "Invalid Sec-WebSocket-Protocol header";
2739
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
2740
+ return;
2741
+ }
2742
+ }
2743
+ const secWebSocketExtensions = req.headers["sec-websocket-extensions"];
2744
+ const extensions = {};
2745
+ if (this.options.perMessageDeflate && secWebSocketExtensions !== undefined) {
2746
+ const perMessageDeflate = new PerMessageDeflate({
2747
+ ...this.options.perMessageDeflate,
2748
+ isServer: true,
2749
+ maxPayload: this.options.maxPayload
2750
+ });
2751
+ try {
2752
+ const offers = extension.parse(secWebSocketExtensions);
2753
+ if (offers[PerMessageDeflate.extensionName]) {
2754
+ perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);
2755
+ extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
2756
+ }
2757
+ } catch (err) {
2758
+ const message = "Invalid or unacceptable Sec-WebSocket-Extensions header";
2759
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
2760
+ return;
2761
+ }
2762
+ }
2763
+ if (this.options.verifyClient) {
2764
+ const info = {
2765
+ origin: req.headers[`${version === 8 ? "sec-websocket-origin" : "origin"}`],
2766
+ secure: !!(req.socket.authorized || req.socket.encrypted),
2767
+ req
2768
+ };
2769
+ if (this.options.verifyClient.length === 2) {
2770
+ this.options.verifyClient(info, (verified, code, message, headers) => {
2771
+ if (!verified) {
2772
+ return abortHandshake(socket, code || 401, message, headers);
2773
+ }
2774
+ this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
2775
+ });
2776
+ return;
2777
+ }
2778
+ if (!this.options.verifyClient(info))
2779
+ return abortHandshake(socket, 401);
2780
+ }
2781
+ this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
2782
+ }
2783
+ completeUpgrade(extensions, key, protocols, req, socket, head, cb) {
2784
+ if (!socket.readable || !socket.writable)
2785
+ return socket.destroy();
2786
+ if (socket[kWebSocket]) {
2787
+ throw new Error("server.handleUpgrade() was called more than once with the same " + "socket, possibly due to a misconfiguration");
2788
+ }
2789
+ if (this._state > RUNNING)
2790
+ return abortHandshake(socket, 503);
2791
+ const digest = createHash("sha1").update(key + GUID).digest("base64");
2792
+ const headers = [
2793
+ "HTTP/1.1 101 Switching Protocols",
2794
+ "Upgrade: websocket",
2795
+ "Connection: Upgrade",
2796
+ `Sec-WebSocket-Accept: ${digest}`
2797
+ ];
2798
+ const ws = new this.options.WebSocket(null, undefined, this.options);
2799
+ if (protocols.size) {
2800
+ const protocol = this.options.handleProtocols ? this.options.handleProtocols(protocols, req) : protocols.values().next().value;
2801
+ if (protocol) {
2802
+ headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
2803
+ ws._protocol = protocol;
2804
+ }
2805
+ }
2806
+ if (extensions[PerMessageDeflate.extensionName]) {
2807
+ const params = extensions[PerMessageDeflate.extensionName].params;
2808
+ const value = extension.format({
2809
+ [PerMessageDeflate.extensionName]: [params]
2810
+ });
2811
+ headers.push(`Sec-WebSocket-Extensions: ${value}`);
2812
+ ws._extensions = extensions;
2813
+ }
2814
+ this.emit("headers", headers, req);
2815
+ socket.write(headers.concat(`\r
2816
+ `).join(`\r
2817
+ `));
2818
+ socket.removeListener("error", socketOnError);
2819
+ ws.setSocket(socket, head, {
2820
+ allowSynchronousEvents: this.options.allowSynchronousEvents,
2821
+ maxPayload: this.options.maxPayload,
2822
+ skipUTF8Validation: this.options.skipUTF8Validation
2823
+ });
2824
+ if (this.clients) {
2825
+ this.clients.add(ws);
2826
+ ws.on("close", () => {
2827
+ this.clients.delete(ws);
2828
+ if (this._shouldEmitClose && !this.clients.size) {
2829
+ process.nextTick(emitClose, this);
2830
+ }
2831
+ });
2832
+ }
2833
+ cb(ws, req);
2834
+ }
2835
+ }
2836
+ module.exports = WebSocketServer;
2837
+ function addListeners(server, map) {
2838
+ for (const event of Object.keys(map))
2839
+ server.on(event, map[event]);
2840
+ return function removeListeners() {
2841
+ for (const event of Object.keys(map)) {
2842
+ server.removeListener(event, map[event]);
2843
+ }
2844
+ };
2845
+ }
2846
+ function emitClose(server) {
2847
+ server._state = CLOSED;
2848
+ server.emit("close");
2849
+ }
2850
+ function socketOnError() {
2851
+ this.destroy();
2852
+ }
2853
+ function abortHandshake(socket, code, message, headers) {
2854
+ message = message || http.STATUS_CODES[code];
2855
+ headers = {
2856
+ Connection: "close",
2857
+ "Content-Type": "text/html",
2858
+ "Content-Length": Buffer.byteLength(message),
2859
+ ...headers
2860
+ };
2861
+ socket.once("finish", socket.destroy);
2862
+ socket.end(`HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r
2863
+ ` + Object.keys(headers).map((h) => `${h}: ${headers[h]}`).join(`\r
2864
+ `) + `\r
2865
+ \r
2866
+ ` + message);
2867
+ }
2868
+ function abortHandshakeOrEmitwsClientError(server, req, socket, code, message, headers) {
2869
+ if (server.listenerCount("wsClientError")) {
2870
+ const err = new Error(message);
2871
+ Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);
2872
+ server.emit("wsClientError", err, socket, req);
2873
+ } else {
2874
+ abortHandshake(socket, code, message, headers);
2875
+ }
2876
+ }
2877
+ });
2878
+
2879
+ // src/cli.ts
2880
+ import { parseArgs } from "node:util";
2881
+ import { execFileSync } from "node:child_process";
2882
+
2883
+ // ../tfa-subagent/dist/index.js
2884
+ import { homedir, platform } from "os";
2885
+ import { readFileSync } from "fs";
2886
+ import { join } from "path";
2887
+
2888
+ // ../node_modules/ws/wrapper.mjs
2889
+ var import_stream = __toESM(require_stream(), 1);
2890
+ var import_extension = __toESM(require_extension(), 1);
2891
+ var import_permessage_deflate = __toESM(require_permessage_deflate(), 1);
2892
+ var import_receiver = __toESM(require_receiver(), 1);
2893
+ var import_sender = __toESM(require_sender(), 1);
2894
+ var import_subprotocol = __toESM(require_subprotocol(), 1);
2895
+ var import_websocket = __toESM(require_websocket(), 1);
2896
+ var import_websocket_server = __toESM(require_websocket_server(), 1);
2897
+ var wrapper_default = import_websocket.default;
2898
+
2899
+ // ../tfa-subagent/dist/index.js
2900
+ var DEFAULT_API_URL = "https://api.todofor.ai";
2901
+ function getEnv(name) {
2902
+ const bare = name.replace(/^TODOFORAI_/, "");
2903
+ return process.env[`TODOFORAI_${bare}`] || process.env[bare] || "";
2904
+ }
2905
+ function normalizeApiUrl(url) {
2906
+ if (url.startsWith("localhost"))
2907
+ return `http://${url}`;
2908
+ if (!url.startsWith("http://") && !url.startsWith("https://"))
2909
+ return `https://${url}`;
2910
+ return url.replace(/\/+$/, "");
2911
+ }
2912
+ function credentialsPath() {
2913
+ const home = homedir();
2914
+ if (platform() === "win32")
2915
+ return join(home, "AppData", "Roaming", "todoforai", "credentials.json");
2916
+ if (platform() === "darwin")
2917
+ return join(home, "Library", "Application Support", "todoforai", "credentials.json");
2918
+ const xdg = process.env.XDG_CONFIG_HOME;
2919
+ return xdg ? join(xdg, "todoforai", "credentials.json") : join(home, ".config", "todoforai", "credentials.json");
2920
+ }
2921
+ var _credsCache;
2922
+ function loadCredentials() {
2923
+ if (_credsCache !== undefined)
2924
+ return _credsCache;
2925
+ try {
2926
+ _credsCache = JSON.parse(readFileSync(credentialsPath(), "utf8"));
2927
+ } catch {
2928
+ _credsCache = null;
2929
+ }
2930
+ return _credsCache;
2931
+ }
2932
+ function resolveAuth(opts = {}) {
2933
+ const creds = loadCredentials();
2934
+ const credsApiUrl = creds?.backendHost ? normalizeApiUrl(creds.backendHost) : "";
2935
+ const apiUrl = normalizeApiUrl(opts.apiUrl || getEnv("TODOFORAI_API_URL") || credsApiUrl || DEFAULT_API_URL);
2936
+ const apiKey = opts.apiKey || getEnv("TODOFORAI_API_KEY") || getEnv("TODOFORAI_API_TOKEN") || creds?.apiKey || "";
2937
+ const agentSettingsId = opts.agentSettingsId || getEnv("TODOFORAI_AGENT_SETTINGS_ID");
2938
+ if (!apiKey)
2939
+ throw new Error("no API key (run `todoforai-bridge login`, or set TODOFORAI_API_KEY, or pass --api-key)");
2940
+ if (!agentSettingsId)
2941
+ throw new Error("agent settings id required (set TODOFORAI_AGENT_SETTINGS_ID or pass --agent <id>)");
2942
+ const apiBase = apiKey.startsWith("dst_") ? "/dst/v1" : "/api/v1";
2943
+ return { apiUrl, apiKey, agentSettingsId, apiBase };
2944
+ }
2945
+ async function api(path, init = {}, apiUrl, apiKey, tabId) {
2946
+ const res = await fetch(`${apiUrl}${path}`, {
2947
+ ...init,
2948
+ headers: {
2949
+ "content-type": "application/json",
2950
+ "x-api-key": apiKey,
2951
+ ...tabId ? { "x-tab-id": tabId } : {},
2952
+ ...init.headers ?? {}
2953
+ }
2954
+ });
2955
+ if (!res.ok)
2956
+ throw new Error(`HTTP ${res.status} ${path}: ${await res.text()}`);
2957
+ return res.status === 204 ? null : await res.json();
2958
+ }
2959
+ function patchSettings(settings, input) {
2960
+ const keep = new Set(input.allowTools);
2961
+ const oldAllow = settings.permissions?.allow ?? [];
2962
+ const oldDeny = settings.permissions?.deny ?? [];
2963
+ const patched = {
2964
+ ...settings,
2965
+ systemMessage: input.systemMessage,
2966
+ permissions: {
2967
+ allow: [...new Set([...oldAllow.filter((p) => keep.has(p)), ...input.allowTools])],
2968
+ ask: [],
2969
+ deny: [...new Set([...oldDeny, ...oldAllow.filter((p) => !keep.has(p))])]
2970
+ },
2971
+ ...input.model ? { model: input.model } : {}
2972
+ };
2973
+ if (input.repo)
2974
+ reorderWorkspaceToFront(patched, input.repo);
2975
+ return patched;
2976
+ }
2977
+ function reorderWorkspaceToFront(patched, repo) {
2978
+ const arrays = [
2979
+ ...Object.values(patched.devicesConfig ?? {}).map((d) => d?.workspacePaths),
2980
+ ...Object.values(patched.edgesMcpConfigs ?? {}).map((e) => e?.todoai_edge?.workspacePaths)
2981
+ ].filter(Array.isArray);
2982
+ const target = arrays.find((a) => a.includes(repo));
2983
+ if (!target) {
2984
+ throw new Error(`--repo ${repo} is not in any authorized workspace for this agent.
2985
+ ` + `Add it via the UI (Device or Edge workspacePaths) or omit --repo to use the agent's default.`);
2986
+ }
2987
+ const i = target.indexOf(repo);
2988
+ if (i > 0)
2989
+ target.unshift(target.splice(i, 1)[0]);
2990
+ }
2991
+ var TERMINAL = new Set([
2992
+ "DONE",
2993
+ "READY",
2994
+ "ERROR",
2995
+ "CANCELLED",
2996
+ "READY_CHECKED",
2997
+ "ERROR_CHECKED",
2998
+ "CANCELLED_CHECKED"
2999
+ ]);
3000
+ async function openSocket(opts) {
3001
+ const wsUrl = opts.apiUrl.replace(/^http/, "ws") + "/ws/v1/frontend?tabId=" + encodeURIComponent(opts.tabId);
3002
+ const ws = new wrapper_default(wsUrl, [opts.apiKey]);
3003
+ ws.on("error", (err) => process.stderr.write(`[ws error] ${err.message}
3004
+ `));
3005
+ await new Promise((ok, fail) => {
3006
+ const onMsg = (raw) => {
3007
+ try {
3008
+ const ev = JSON.parse(raw.toString());
3009
+ if (ev?.type === "connected_frontend") {
3010
+ ws.off("message", onMsg);
3011
+ ok();
3012
+ }
3013
+ } catch {}
3014
+ };
3015
+ ws.on("message", onMsg);
3016
+ ws.once("error", fail);
3017
+ ws.once("close", () => fail(new Error("WS closed before connected_frontend")));
3018
+ });
3019
+ return ws;
3020
+ }
3021
+ async function streamToTerminal(ws, opts = {}) {
3022
+ const streamStdout = opts.streamStdout !== false;
3023
+ return new Promise((resolve) => {
3024
+ let exitCode = 0;
3025
+ let result = "";
3026
+ let inText = false;
3027
+ const finish = (code) => {
3028
+ exitCode = code;
3029
+ ws.close();
3030
+ resolve({ exitCode, result });
3031
+ };
3032
+ ws.on("message", (raw) => {
3033
+ let ev;
3034
+ try {
3035
+ ev = JSON.parse(raw.toString());
3036
+ } catch {
3037
+ return;
3038
+ }
3039
+ const t = ev?.type;
3040
+ if (!t)
3041
+ return;
3042
+ if (t === "block:message" && typeof ev.payload?.content === "string") {
3043
+ if (inText)
3044
+ result += ev.payload.content;
3045
+ if (streamStdout)
3046
+ process.stdout.write(ev.payload.content);
3047
+ return;
3048
+ }
3049
+ if (t === "block:start_universal" && ev.payload?.block_type) {
3050
+ const bt = ev.payload.block_type;
3051
+ inText = bt === "TEXT";
3052
+ if (inText)
3053
+ result = "";
3054
+ else if (streamStdout && bt !== "REASON")
3055
+ process.stderr.write(`
3056
+ → ${bt}
3057
+ `);
3058
+ return;
3059
+ }
3060
+ if (t === "todo:status" && TERMINAL.has(ev.payload?.status)) {
3061
+ if (streamStdout)
3062
+ process.stdout.write(`
3063
+ `);
3064
+ const isErr = ev.payload.status === "ERROR" || ev.payload.status === "ERROR_CHECKED";
3065
+ finish(isErr ? 1 : 0);
3066
+ }
3067
+ });
3068
+ ws.on("close", () => resolve({ exitCode, result }));
3069
+ ws.on("error", (err) => {
3070
+ console.error(`
3071
+ [ws error]`, err.message);
3072
+ finish(1);
3073
+ });
3074
+ });
3075
+ }
3076
+ async function runTfa(spec) {
3077
+ const { apiUrl, apiKey, agentSettingsId, apiBase } = resolveAuth({
3078
+ apiUrl: spec.apiUrl,
3079
+ apiKey: spec.apiKey,
3080
+ agentSettingsId: spec.agentSettingsId
3081
+ });
3082
+ const allowed = new Set(spec.allowedTools);
3083
+ const requested = spec.requestedTools ?? [];
3084
+ const invalid = requested.filter((t) => !allowed.has(t));
3085
+ if (invalid.length) {
3086
+ throw new Error(`--tools values not allowed for ${spec.binName}: ${invalid.join(", ")}
3087
+ ` + `Allowed: ${spec.allowedTools.join(", ")}`);
3088
+ }
3089
+ const allowTools = requested.length ? requested : spec.allowedTools;
3090
+ const tabId = crypto.randomUUID();
3091
+ const settings = await api(`${apiBase}/agents/${agentSettingsId}`, {}, apiUrl, apiKey);
3092
+ const patched = patchSettings(settings, {
3093
+ systemMessage: spec.systemMessage,
3094
+ allowTools,
3095
+ repo: spec.repo,
3096
+ model: spec.model
3097
+ });
3098
+ let projectId = spec.projectId || "";
3099
+ if (!projectId) {
3100
+ const projects = await api(`${apiBase}/projects`, {}, apiUrl, apiKey);
3101
+ if (!projects?.length)
3102
+ throw new Error("no project found. Pass --project <id>.");
3103
+ projectId = projects[0].project?.id ?? projects[0].id;
3104
+ }
3105
+ const ws = await openSocket({ apiUrl, apiKey, tabId });
3106
+ const visible = spec.visible === true;
3107
+ const todoRes = await api(`${apiBase}/projects/${projectId}/todos`, {
3108
+ method: "POST",
3109
+ body: JSON.stringify({ content: spec.content, agentSettings: patched, visible })
3110
+ }, apiUrl, apiKey, tabId);
3111
+ const todoId = todoRes.id;
3112
+ await api(`${apiBase}/todos/${todoId}/subscribe`, {
3113
+ method: "POST",
3114
+ body: JSON.stringify({ todoId })
3115
+ }, apiUrl, apiKey, tabId);
3116
+ process.stderr.write(`[${spec.binName}] todo=${todoId}${visible ? "" : " (hidden)"}
3117
+ `);
3118
+ const { exitCode, result } = await streamToTerminal(ws, { streamStdout: visible });
3119
+ return { exitCode, todoId, result };
3120
+ }
3121
+
3122
+ // src/cli.ts
3123
+ var REVIEW_SYS_PROMPT = `You are a review and advisory agent. Your job is to evaluate whether the original goal was accomplished optimally.
3124
+
3125
+ Use git diff, git status, read files, and search to understand what was done. Then:
3126
+ - Assess whether the goal was fully and correctly achieved
3127
+ - Identify issues, bugs, or missing pieces
3128
+ - Suggest simpler or cleaner approaches that could achieve the same goal
3129
+ - Propose alternative solutions or architectural improvements
3130
+ - Question whether the approach taken was the best path
3131
+
3132
+ ## Investigation workflow
3133
+ 1. **Understand:** Use 'grep' search extensively (in parallel if independent) to understand file structures, existing code patterns, and conventions. Use 'read' to validate any assumptions you may have.
3134
+ 2. **Synthesize:** Form a coherent and grounded picture from the evidence; cite specific file paths and line numbers when reporting findings.
3135
+
3136
+ IMPORTANT: You are read-only. Do NOT modify, create, or delete any files. Do NOT run commands that change state. Only read, inspect, and report findings.
3137
+ If a tool fails 3 times, stop retrying and report that the tools are faulty.`;
3138
+ var ALLOWED_TOOLS = ["read", "grep", "bash"];
3139
+ function captureGitDiff(repo, against) {
3140
+ const args = against === "WORKING" ? ["-C", repo, "diff", "HEAD"] : ["-C", repo, "diff", `${against}...HEAD`];
3141
+ try {
3142
+ return execFileSync("git", args, { encoding: "utf-8", maxBuffer: 50 * 1024 * 1024 });
3143
+ } catch (e) {
3144
+ console.error(`git diff failed: ${e?.message ?? e}`);
3145
+ process.exit(1);
3146
+ }
3147
+ }
3148
+ function printHelp() {
3149
+ console.log(`tfa-review — review a git diff as a real TODO; stream output to terminal.
3150
+
3151
+ Usage:
3152
+ tfa-review [options] <goal>
3153
+
3154
+ Options:
3155
+ --repo <path> Repo path (default: cwd). Must be in an authorized workspace
3156
+ of your agent's devicesConfig/edgesMcpConfigs.
3157
+ --against <ref> Git ref to diff against HEAD; "WORKING" = uncommitted (default: WORKING)
3158
+ -m, --model <name> Override model
3159
+ -a, --agent <id> Agent settings ID (default: $TODOFORAI_AGENT_SETTINGS_ID)
3160
+ -p, --project <id> Project ID (default: first project the user owns)
3161
+ --tools <a,b,c> Restrict to a subset of ${ALLOWED_TOOLS.join(",")} (comma-separated)
3162
+ -h, --help Show this help
3163
+ -v, --version Show version
3164
+
3165
+ Env (auto-injected by edge shell):
3166
+ TODOFORAI_API_URL, TODOFORAI_API_KEY, TODOFORAI_AGENT_SETTINGS_ID
3167
+ `);
3168
+ }
3169
+ async function main() {
3170
+ const { values, positionals } = parseArgs({
3171
+ args: process.argv.slice(2),
3172
+ options: {
3173
+ repo: { type: "string" },
3174
+ against: { type: "string" },
3175
+ model: { type: "string", short: "m" },
3176
+ agent: { type: "string", short: "a" },
3177
+ project: { type: "string", short: "p" },
3178
+ tools: { type: "string" },
3179
+ help: { type: "boolean", short: "h", default: false },
3180
+ version: { type: "boolean", short: "v", default: false }
3181
+ },
3182
+ allowPositionals: true,
3183
+ strict: false
3184
+ });
3185
+ if (values.help) {
3186
+ printHelp();
3187
+ return;
3188
+ }
3189
+ if (values.version) {
3190
+ console.log("tfa-review 0.1.0");
3191
+ return;
3192
+ }
3193
+ const goal = positionals.join(" ").trim();
3194
+ if (!goal) {
3195
+ console.error("Error: missing goal. Run `tfa-review --help`.");
3196
+ process.exit(2);
3197
+ }
3198
+ const repo = values.repo || process.cwd();
3199
+ const against = values.against || "WORKING";
3200
+ const diff = captureGitDiff(repo, against);
3201
+ if (!diff.trim()) {
3202
+ console.error(`No changes between ${against} and HEAD in ${repo}.`);
3203
+ process.exit(1);
3204
+ }
3205
+ const content = `# Goal
3206
+ ${goal}
3207
+
3208
+ # Repo
3209
+ ${repo}
3210
+
3211
+ # Diff (${against}...HEAD)
3212
+ \`\`\`diff
3213
+ ${diff}
3214
+ \`\`\``;
3215
+ const requestedTools = values.tools ? String(values.tools).split(",").map((s) => s.trim()).filter(Boolean) : [];
3216
+ const exit = await runTfa({
3217
+ binName: "tfa-review",
3218
+ systemMessage: REVIEW_SYS_PROMPT,
3219
+ allowedTools: ALLOWED_TOOLS,
3220
+ content,
3221
+ repo: values.repo,
3222
+ model: values.model,
3223
+ agentSettingsId: values.agent,
3224
+ projectId: values.project,
3225
+ requestedTools
3226
+ });
3227
+ process.exit(exit);
3228
+ }
3229
+ main().catch((e) => {
3230
+ console.error(`Error: ${e?.message ?? e}`);
3231
+ process.exit(1);
3232
+ });