@google/gemini-cli 0.69.0 → 0.70.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 (75) hide show
  1. package/bundle/{chunk-TPD3RZ2B.js → chunk-37D3S3FZ.js} +65559 -51236
  2. package/bundle/{chunk-MJHJIOO6.js → chunk-3VGGGCOZ.js} +35 -29
  3. package/bundle/{chunk-RRELGD6D.js → chunk-4BWP3TDK.js} +1 -1
  4. package/bundle/{chunk-76IL5AQS.js → chunk-5VFAWK3F.js} +1 -1
  5. package/bundle/{chunk-2NIO2MYP.js → chunk-6IKD2NB3.js} +1 -1
  6. package/bundle/{chunk-FZXMW23P.js → chunk-7JS2T75Z.js} +1 -1
  7. package/bundle/{chunk-TEYXLQ5H.js → chunk-AMHNNZY2.js} +1165 -21669
  8. package/bundle/{chunk-SM722TVE.js → chunk-BOIBJEIO.js} +3 -3
  9. package/bundle/{chunk-XXN6WBQW.js → chunk-CB37EK5Y.js} +3 -3
  10. package/bundle/{chunk-BBQ3J3KD.js → chunk-CMKRWIX6.js} +1165 -21669
  11. package/bundle/{chunk-66UT6FAS.js → chunk-EG2BSKPF.js} +1 -1
  12. package/bundle/{chunk-5WVS3LFE.js → chunk-FHK4RNCX.js} +1165 -21669
  13. package/bundle/{chunk-6CG4XKVB.js → chunk-FXAACYC3.js} +1 -1
  14. package/bundle/{chunk-6MSIVBAV.js → chunk-G6SC5BOV.js} +1 -1
  15. package/bundle/{chunk-HFG3LZOT.js → chunk-GFBMTAPD.js} +625 -22
  16. package/bundle/{chunk-2NWFKUZR.js → chunk-JLKRLYZG.js} +35 -29
  17. package/bundle/{chunk-KZYASN6P.js → chunk-KV6XIC2Z.js} +1 -1
  18. package/bundle/{chunk-Y4PW6PYG.js → chunk-LMBUPWFC.js} +65559 -51236
  19. package/bundle/{chunk-RPOY63FV.js → chunk-LMNAB62M.js} +625 -22
  20. package/bundle/{chunk-IUUIT4SU.js → chunk-N7J54YNL.js} +1 -0
  21. package/bundle/{chunk-E2O7673V.js → chunk-QYKA4YD7.js} +3 -3
  22. package/bundle/{chunk-4ICD47UK.js → chunk-RFQXG324.js} +1 -1
  23. package/bundle/{chunk-CU3LIREC.js → chunk-SPAMAY26.js} +1 -1
  24. package/bundle/{chunk-X4P3RZYU.js → chunk-UF44X63P.js} +65411 -51125
  25. package/bundle/{chunk-7JVLRJNT.js → chunk-V4HIE5G5.js} +1 -1
  26. package/bundle/{chunk-TO7WASPI.js → chunk-VHXUWMGE.js} +35 -29
  27. package/bundle/{chunk-664ZODQF.js → chunk-W2AJR23G.js} +137 -58
  28. package/bundle/{chunk-VWFWPAOZ.js → chunk-WRWAVEME.js} +1 -1
  29. package/bundle/{chunk-L7UQY2JQ.js → chunk-YOEWNBDC.js} +625 -22
  30. package/bundle/{cleanup-4RG2PSND.js → cleanup-BMYAIPAL.js} +4 -4
  31. package/bundle/{cleanup-QM4BFPJ4.js → cleanup-CWOSCK57.js} +4 -4
  32. package/bundle/{cleanup-XYZT64H7.js → cleanup-JTPRPYIQ.js} +4 -4
  33. package/bundle/{core-JN57UMDL.js → core-HYVGBZPP.js} +13 -3
  34. package/bundle/{dist-RVQZS637.js → core-XZECNCR2.js} +13 -3
  35. package/bundle/{devtools-TYCPOPV3.js → devtools-WUGMIOCT.js} +1 -1
  36. package/bundle/devtoolsService-ER22TM2Y.js +919 -0
  37. package/bundle/devtoolsService-O5VD5YWD.js +918 -0
  38. package/bundle/devtoolsService-WNJOZ7ZT.js +918 -0
  39. package/bundle/{core-3UXW77KZ.js → dist-75NDR3EX.js} +13 -3
  40. package/bundle/docs/changelogs/index.md +22 -0
  41. package/bundle/docs/changelogs/latest.md +100 -92
  42. package/bundle/docs/changelogs/preview.md +116 -104
  43. package/bundle/docs/cli/enterprise.md +23 -5
  44. package/bundle/docs/ide-integration/ide-companion-spec.md +10 -4
  45. package/bundle/docs/reference/policy-engine.md +45 -6
  46. package/bundle/docs/tools/shell.md +2 -1
  47. package/bundle/{formatError-I6YST2IJ.js → formatError-FYLLVZDF.js} +4 -4
  48. package/bundle/{formatError-R5NIXYBT.js → formatError-M4GLDFGE.js} +4 -4
  49. package/bundle/{formatError-5QTHC2BU.js → formatError-QOZLAZ32.js} +4 -4
  50. package/bundle/{gemini-SS7CDNKE.js → gemini-AYDYW6NZ.js} +676 -288
  51. package/bundle/{gemini-VN2552TI.js → gemini-FRSP6LA3.js} +676 -288
  52. package/bundle/{gemini-BCCY3LUV.js → gemini-PG2FEK5D.js} +676 -288
  53. package/bundle/gemini.js +35 -17
  54. package/bundle/{getMachineId-bsd-TXG52NKR.js → getMachineId-bsd-3TGNBDZQ.js} +1 -1
  55. package/bundle/{getMachineId-darwin-7OE4DDZ6.js → getMachineId-darwin-2CFT4JKO.js} +1 -1
  56. package/bundle/{getMachineId-linux-SHIFKOOX.js → getMachineId-linux-BXATTKN2.js} +1 -1
  57. package/bundle/{getMachineId-unsupported-5U5DOEYY.js → getMachineId-unsupported-VHPOSMKR.js} +1 -1
  58. package/bundle/{getMachineId-win-6KLLGOI4.js → getMachineId-win-IGXROMTR.js} +1 -1
  59. package/bundle/{interactiveCli-X6WWC2C6.js → interactiveCli-6TVFB4R5.js} +36 -18
  60. package/bundle/{interactiveCli-SGZ2VGTY.js → interactiveCli-76LAQB3B.js} +36 -18
  61. package/bundle/{interactiveCli-MX4SNKPZ.js → interactiveCli-BYWR7IEK.js} +36 -18
  62. package/bundle/{liteRtServerManager-CAJIW3PE.js → liteRtServerManager-BYJWS5BO.js} +6 -6
  63. package/bundle/{liteRtServerManager-FQPKIHVD.js → liteRtServerManager-GIRVSE6M.js} +6 -6
  64. package/bundle/{liteRtServerManager-6PM4BXYU.js → liteRtServerManager-KZ62KJW3.js} +6 -6
  65. package/bundle/{oauth2-provider-T3DF3FTA.js → oauth2-provider-SFFQQ6OE.js} +3 -3
  66. package/bundle/{oauth2-provider-RIS25NZW.js → oauth2-provider-SRH6I6G7.js} +3 -3
  67. package/bundle/{oauth2-provider-D4UNDFN3.js → oauth2-provider-ZBFFAIQE.js} +3 -3
  68. package/bundle/{src-XZYPU6PJ.js → src-MVBNXN6P.js} +3 -3504
  69. package/bundle/{start-FVNQP7EB.js → start-OLEVDFQS.js} +8 -8
  70. package/bundle/{start-WSOZZWBK.js → start-PLK5XHJC.js} +8 -8
  71. package/bundle/{start-76F65FZ5.js → start-Q66LTS3Y.js} +8 -8
  72. package/package.json +1 -1
  73. package/bundle/devtoolsService-K3FKQFZP.js +0 -4422
  74. package/bundle/devtoolsService-QLI75YCI.js +0 -4421
  75. package/bundle/devtoolsService-XZRXARUU.js +0 -4421
@@ -1,4421 +0,0 @@
1
- const require = (await import('node:module')).createRequire(import.meta.url); const __chunk_filename = (await import('node:url')).fileURLToPath(import.meta.url); const __chunk_dirname = (await import('node:path')).dirname(__chunk_filename);
2
- import {
3
- coreEvents,
4
- debugLogger
5
- } from "./chunk-Y4PW6PYG.js";
6
- import "./chunk-664ZODQF.js";
7
- import "./chunk-IUUIT4SU.js";
8
- import "./chunk-L6PII3GR.js";
9
- import {
10
- __commonJS,
11
- __require,
12
- __toESM
13
- } from "./chunk-34MYV7JD.js";
14
-
15
- // packages/cli/node_modules/ws/lib/stream.js
16
- var require_stream = __commonJS({
17
- "packages/cli/node_modules/ws/lib/stream.js"(exports, module) {
18
- "use strict";
19
- var { Duplex } = __require("stream");
20
- function emitClose(stream) {
21
- stream.emit("close");
22
- }
23
- function duplexOnEnd() {
24
- if (!this.destroyed && this._writableState.finished) {
25
- this.destroy();
26
- }
27
- }
28
- function duplexOnError(err) {
29
- this.removeListener("error", duplexOnError);
30
- this.destroy();
31
- if (this.listenerCount("error") === 0) {
32
- this.emit("error", err);
33
- }
34
- }
35
- function createWebSocketStream2(ws, options) {
36
- let terminateOnDestroy = true;
37
- const duplex = new Duplex({
38
- ...options,
39
- autoDestroy: false,
40
- emitClose: false,
41
- objectMode: false,
42
- writableObjectMode: false
43
- });
44
- ws.on("message", function message(msg, isBinary) {
45
- const data = !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;
46
- if (!duplex.push(data)) ws.pause();
47
- });
48
- ws.once("error", function error(err) {
49
- if (duplex.destroyed) return;
50
- terminateOnDestroy = false;
51
- duplex.destroy(err);
52
- });
53
- ws.once("close", function close() {
54
- if (duplex.destroyed) return;
55
- duplex.push(null);
56
- });
57
- duplex._destroy = function(err, callback) {
58
- if (ws.readyState === ws.CLOSED) {
59
- callback(err);
60
- process.nextTick(emitClose, duplex);
61
- return;
62
- }
63
- let called = false;
64
- ws.once("error", function error(err2) {
65
- called = true;
66
- callback(err2);
67
- });
68
- ws.once("close", function close() {
69
- if (!called) callback(err);
70
- process.nextTick(emitClose, duplex);
71
- });
72
- if (terminateOnDestroy) ws.terminate();
73
- };
74
- duplex._final = function(callback) {
75
- if (ws.readyState === ws.CONNECTING) {
76
- ws.once("open", function open() {
77
- duplex._final(callback);
78
- });
79
- return;
80
- }
81
- if (ws._socket === null) return;
82
- if (ws._socket._writableState.finished) {
83
- callback();
84
- if (duplex._readableState.endEmitted) duplex.destroy();
85
- } else {
86
- ws._socket.once("finish", function finish() {
87
- callback();
88
- });
89
- ws.close();
90
- }
91
- };
92
- duplex._read = function() {
93
- if (ws.isPaused) ws.resume();
94
- };
95
- duplex._write = function(chunk, encoding, callback) {
96
- if (ws.readyState === ws.CONNECTING) {
97
- ws.once("open", function open() {
98
- duplex._write(chunk, encoding, callback);
99
- });
100
- return;
101
- }
102
- ws.send(chunk, callback);
103
- };
104
- duplex.on("end", duplexOnEnd);
105
- duplex.on("error", duplexOnError);
106
- return duplex;
107
- }
108
- module.exports = createWebSocketStream2;
109
- }
110
- });
111
-
112
- // packages/cli/node_modules/ws/lib/constants.js
113
- var require_constants = __commonJS({
114
- "packages/cli/node_modules/ws/lib/constants.js"(exports, module) {
115
- "use strict";
116
- module.exports = {
117
- BINARY_TYPES: ["nodebuffer", "arraybuffer", "fragments"],
118
- EMPTY_BUFFER: Buffer.alloc(0),
119
- GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
120
- kForOnEventAttribute: Symbol("kIsForOnEventAttribute"),
121
- kListener: Symbol("kListener"),
122
- kStatusCode: Symbol("status-code"),
123
- kWebSocket: Symbol("websocket"),
124
- NOOP: () => {
125
- }
126
- };
127
- }
128
- });
129
-
130
- // packages/cli/node_modules/ws/lib/buffer-util.js
131
- var require_buffer_util = __commonJS({
132
- "packages/cli/node_modules/ws/lib/buffer-util.js"(exports, module) {
133
- "use strict";
134
- var { EMPTY_BUFFER } = require_constants();
135
- var FastBuffer = Buffer[Symbol.species];
136
- function concat(list, totalLength) {
137
- if (list.length === 0) return EMPTY_BUFFER;
138
- if (list.length === 1) return list[0];
139
- const target = Buffer.allocUnsafe(totalLength);
140
- let offset = 0;
141
- for (let i = 0; i < list.length; i++) {
142
- const buf = list[i];
143
- target.set(buf, offset);
144
- offset += buf.length;
145
- }
146
- if (offset < totalLength) {
147
- return new FastBuffer(target.buffer, target.byteOffset, offset);
148
- }
149
- return target;
150
- }
151
- function _mask(source, mask, output, offset, length) {
152
- for (let i = 0; i < length; i++) {
153
- output[offset + i] = source[i] ^ mask[i & 3];
154
- }
155
- }
156
- function _unmask(buffer, mask) {
157
- for (let i = 0; i < buffer.length; i++) {
158
- buffer[i] ^= mask[i & 3];
159
- }
160
- }
161
- function toArrayBuffer(buf) {
162
- if (buf.length === buf.buffer.byteLength) {
163
- return buf.buffer;
164
- }
165
- return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);
166
- }
167
- function toBuffer(data) {
168
- toBuffer.readOnly = true;
169
- if (Buffer.isBuffer(data)) return data;
170
- let buf;
171
- if (data instanceof ArrayBuffer) {
172
- buf = new FastBuffer(data);
173
- } else if (ArrayBuffer.isView(data)) {
174
- buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);
175
- } else {
176
- buf = Buffer.from(data);
177
- toBuffer.readOnly = false;
178
- }
179
- return buf;
180
- }
181
- module.exports = {
182
- concat,
183
- mask: _mask,
184
- toArrayBuffer,
185
- toBuffer,
186
- unmask: _unmask
187
- };
188
- if (!process.env.WS_NO_BUFFER_UTIL) {
189
- try {
190
- const bufferUtil = __require("bufferutil");
191
- module.exports.mask = function(source, mask, output, offset, length) {
192
- if (length < 48) _mask(source, mask, output, offset, length);
193
- else bufferUtil.mask(source, mask, output, offset, length);
194
- };
195
- module.exports.unmask = function(buffer, mask) {
196
- if (buffer.length < 32) _unmask(buffer, mask);
197
- else bufferUtil.unmask(buffer, mask);
198
- };
199
- } catch (e) {
200
- }
201
- }
202
- }
203
- });
204
-
205
- // packages/cli/node_modules/ws/lib/limiter.js
206
- var require_limiter = __commonJS({
207
- "packages/cli/node_modules/ws/lib/limiter.js"(exports, module) {
208
- "use strict";
209
- var kDone = Symbol("kDone");
210
- var kRun = Symbol("kRun");
211
- var Limiter = class {
212
- /**
213
- * Creates a new `Limiter`.
214
- *
215
- * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed
216
- * to run concurrently
217
- */
218
- constructor(concurrency) {
219
- this[kDone] = () => {
220
- this.pending--;
221
- this[kRun]();
222
- };
223
- this.concurrency = concurrency || Infinity;
224
- this.jobs = [];
225
- this.pending = 0;
226
- }
227
- /**
228
- * Adds a job to the queue.
229
- *
230
- * @param {Function} job The job to run
231
- * @public
232
- */
233
- add(job) {
234
- this.jobs.push(job);
235
- this[kRun]();
236
- }
237
- /**
238
- * Removes a job from the queue and runs it if possible.
239
- *
240
- * @private
241
- */
242
- [kRun]() {
243
- if (this.pending === this.concurrency) return;
244
- if (this.jobs.length) {
245
- const job = this.jobs.shift();
246
- this.pending++;
247
- job(this[kDone]);
248
- }
249
- }
250
- };
251
- module.exports = Limiter;
252
- }
253
- });
254
-
255
- // packages/cli/node_modules/ws/lib/permessage-deflate.js
256
- var require_permessage_deflate = __commonJS({
257
- "packages/cli/node_modules/ws/lib/permessage-deflate.js"(exports, module) {
258
- "use strict";
259
- var zlib2 = __require("zlib");
260
- var bufferUtil = require_buffer_util();
261
- var Limiter = require_limiter();
262
- var { kStatusCode } = require_constants();
263
- var FastBuffer = Buffer[Symbol.species];
264
- var TRAILER = Buffer.from([0, 0, 255, 255]);
265
- var kPerMessageDeflate = Symbol("permessage-deflate");
266
- var kTotalLength = Symbol("total-length");
267
- var kCallback = Symbol("callback");
268
- var kBuffers = Symbol("buffers");
269
- var kError = Symbol("error");
270
- var zlibLimiter;
271
- var PerMessageDeflate = class {
272
- /**
273
- * Creates a PerMessageDeflate instance.
274
- *
275
- * @param {Object} [options] Configuration options
276
- * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support
277
- * for, or request, a custom client window size
278
- * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/
279
- * acknowledge disabling of client context takeover
280
- * @param {Number} [options.concurrencyLimit=10] The number of concurrent
281
- * calls to zlib
282
- * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the
283
- * use of a custom server window size
284
- * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept
285
- * disabling of server context takeover
286
- * @param {Number} [options.threshold=1024] Size (in bytes) below which
287
- * messages should not be compressed if context takeover is disabled
288
- * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on
289
- * deflate
290
- * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on
291
- * inflate
292
- * @param {Boolean} [isServer=false] Create the instance in either server or
293
- * client mode
294
- * @param {Number} [maxPayload=0] The maximum allowed message length
295
- */
296
- constructor(options, isServer, maxPayload) {
297
- this._maxPayload = maxPayload | 0;
298
- this._options = options || {};
299
- this._threshold = this._options.threshold !== void 0 ? this._options.threshold : 1024;
300
- this._isServer = !!isServer;
301
- this._deflate = null;
302
- this._inflate = null;
303
- this.params = null;
304
- if (!zlibLimiter) {
305
- const concurrency = this._options.concurrencyLimit !== void 0 ? this._options.concurrencyLimit : 10;
306
- zlibLimiter = new Limiter(concurrency);
307
- }
308
- }
309
- /**
310
- * @type {String}
311
- */
312
- static get extensionName() {
313
- return "permessage-deflate";
314
- }
315
- /**
316
- * Create an extension negotiation offer.
317
- *
318
- * @return {Object} Extension parameters
319
- * @public
320
- */
321
- offer() {
322
- const params = {};
323
- if (this._options.serverNoContextTakeover) {
324
- params.server_no_context_takeover = true;
325
- }
326
- if (this._options.clientNoContextTakeover) {
327
- params.client_no_context_takeover = true;
328
- }
329
- if (this._options.serverMaxWindowBits) {
330
- params.server_max_window_bits = this._options.serverMaxWindowBits;
331
- }
332
- if (this._options.clientMaxWindowBits) {
333
- params.client_max_window_bits = this._options.clientMaxWindowBits;
334
- } else if (this._options.clientMaxWindowBits == null) {
335
- params.client_max_window_bits = true;
336
- }
337
- return params;
338
- }
339
- /**
340
- * Accept an extension negotiation offer/response.
341
- *
342
- * @param {Array} configurations The extension negotiation offers/reponse
343
- * @return {Object} Accepted configuration
344
- * @public
345
- */
346
- accept(configurations) {
347
- configurations = this.normalizeParams(configurations);
348
- this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations);
349
- return this.params;
350
- }
351
- /**
352
- * Releases all resources used by the extension.
353
- *
354
- * @public
355
- */
356
- cleanup() {
357
- if (this._inflate) {
358
- this._inflate.close();
359
- this._inflate = null;
360
- }
361
- if (this._deflate) {
362
- const callback = this._deflate[kCallback];
363
- this._deflate.close();
364
- this._deflate = null;
365
- if (callback) {
366
- callback(
367
- new Error(
368
- "The deflate stream was closed while data was being processed"
369
- )
370
- );
371
- }
372
- }
373
- }
374
- /**
375
- * Accept an extension negotiation offer.
376
- *
377
- * @param {Array} offers The extension negotiation offers
378
- * @return {Object} Accepted configuration
379
- * @private
380
- */
381
- acceptAsServer(offers) {
382
- const opts = this._options;
383
- const accepted = offers.find((params) => {
384
- 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) {
385
- return false;
386
- }
387
- return true;
388
- });
389
- if (!accepted) {
390
- throw new Error("None of the extension offers can be accepted");
391
- }
392
- if (opts.serverNoContextTakeover) {
393
- accepted.server_no_context_takeover = true;
394
- }
395
- if (opts.clientNoContextTakeover) {
396
- accepted.client_no_context_takeover = true;
397
- }
398
- if (typeof opts.serverMaxWindowBits === "number") {
399
- accepted.server_max_window_bits = opts.serverMaxWindowBits;
400
- }
401
- if (typeof opts.clientMaxWindowBits === "number") {
402
- accepted.client_max_window_bits = opts.clientMaxWindowBits;
403
- } else if (accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false) {
404
- delete accepted.client_max_window_bits;
405
- }
406
- return accepted;
407
- }
408
- /**
409
- * Accept the extension negotiation response.
410
- *
411
- * @param {Array} response The extension negotiation response
412
- * @return {Object} Accepted configuration
413
- * @private
414
- */
415
- acceptAsClient(response) {
416
- const params = response[0];
417
- if (this._options.clientNoContextTakeover === false && params.client_no_context_takeover) {
418
- throw new Error('Unexpected parameter "client_no_context_takeover"');
419
- }
420
- if (!params.client_max_window_bits) {
421
- if (typeof this._options.clientMaxWindowBits === "number") {
422
- params.client_max_window_bits = this._options.clientMaxWindowBits;
423
- }
424
- } else if (this._options.clientMaxWindowBits === false || typeof this._options.clientMaxWindowBits === "number" && params.client_max_window_bits > this._options.clientMaxWindowBits) {
425
- throw new Error(
426
- 'Unexpected or invalid parameter "client_max_window_bits"'
427
- );
428
- }
429
- return params;
430
- }
431
- /**
432
- * Normalize parameters.
433
- *
434
- * @param {Array} configurations The extension negotiation offers/reponse
435
- * @return {Array} The offers/response with normalized parameters
436
- * @private
437
- */
438
- normalizeParams(configurations) {
439
- configurations.forEach((params) => {
440
- Object.keys(params).forEach((key) => {
441
- let value = params[key];
442
- if (value.length > 1) {
443
- throw new Error(`Parameter "${key}" must have only a single value`);
444
- }
445
- value = value[0];
446
- if (key === "client_max_window_bits") {
447
- if (value !== true) {
448
- const num = +value;
449
- if (!Number.isInteger(num) || num < 8 || num > 15) {
450
- throw new TypeError(
451
- `Invalid value for parameter "${key}": ${value}`
452
- );
453
- }
454
- value = num;
455
- } else if (!this._isServer) {
456
- throw new TypeError(
457
- `Invalid value for parameter "${key}": ${value}`
458
- );
459
- }
460
- } else if (key === "server_max_window_bits") {
461
- const num = +value;
462
- if (!Number.isInteger(num) || num < 8 || num > 15) {
463
- throw new TypeError(
464
- `Invalid value for parameter "${key}": ${value}`
465
- );
466
- }
467
- value = num;
468
- } else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") {
469
- if (value !== true) {
470
- throw new TypeError(
471
- `Invalid value for parameter "${key}": ${value}`
472
- );
473
- }
474
- } else {
475
- throw new Error(`Unknown parameter "${key}"`);
476
- }
477
- params[key] = value;
478
- });
479
- });
480
- return configurations;
481
- }
482
- /**
483
- * Decompress data. Concurrency limited.
484
- *
485
- * @param {Buffer} data Compressed data
486
- * @param {Boolean} fin Specifies whether or not this is the last fragment
487
- * @param {Function} callback Callback
488
- * @public
489
- */
490
- decompress(data, fin, callback) {
491
- zlibLimiter.add((done) => {
492
- this._decompress(data, fin, (err, result) => {
493
- done();
494
- callback(err, result);
495
- });
496
- });
497
- }
498
- /**
499
- * Compress data. Concurrency limited.
500
- *
501
- * @param {(Buffer|String)} data Data to compress
502
- * @param {Boolean} fin Specifies whether or not this is the last fragment
503
- * @param {Function} callback Callback
504
- * @public
505
- */
506
- compress(data, fin, callback) {
507
- zlibLimiter.add((done) => {
508
- this._compress(data, fin, (err, result) => {
509
- done();
510
- callback(err, result);
511
- });
512
- });
513
- }
514
- /**
515
- * Decompress data.
516
- *
517
- * @param {Buffer} data Compressed data
518
- * @param {Boolean} fin Specifies whether or not this is the last fragment
519
- * @param {Function} callback Callback
520
- * @private
521
- */
522
- _decompress(data, fin, callback) {
523
- const endpoint = this._isServer ? "client" : "server";
524
- if (!this._inflate) {
525
- const key = `${endpoint}_max_window_bits`;
526
- const windowBits = typeof this.params[key] !== "number" ? zlib2.Z_DEFAULT_WINDOWBITS : this.params[key];
527
- this._inflate = zlib2.createInflateRaw({
528
- ...this._options.zlibInflateOptions,
529
- windowBits
530
- });
531
- this._inflate[kPerMessageDeflate] = this;
532
- this._inflate[kTotalLength] = 0;
533
- this._inflate[kBuffers] = [];
534
- this._inflate.on("error", inflateOnError);
535
- this._inflate.on("data", inflateOnData);
536
- }
537
- this._inflate[kCallback] = callback;
538
- this._inflate.write(data);
539
- if (fin) this._inflate.write(TRAILER);
540
- this._inflate.flush(() => {
541
- const err = this._inflate[kError];
542
- if (err) {
543
- this._inflate.close();
544
- this._inflate = null;
545
- callback(err);
546
- return;
547
- }
548
- const data2 = bufferUtil.concat(
549
- this._inflate[kBuffers],
550
- this._inflate[kTotalLength]
551
- );
552
- if (this._inflate._readableState.endEmitted) {
553
- this._inflate.close();
554
- this._inflate = null;
555
- } else {
556
- this._inflate[kTotalLength] = 0;
557
- this._inflate[kBuffers] = [];
558
- if (fin && this.params[`${endpoint}_no_context_takeover`]) {
559
- this._inflate.reset();
560
- }
561
- }
562
- callback(null, data2);
563
- });
564
- }
565
- /**
566
- * Compress data.
567
- *
568
- * @param {(Buffer|String)} data Data to compress
569
- * @param {Boolean} fin Specifies whether or not this is the last fragment
570
- * @param {Function} callback Callback
571
- * @private
572
- */
573
- _compress(data, fin, callback) {
574
- const endpoint = this._isServer ? "server" : "client";
575
- if (!this._deflate) {
576
- const key = `${endpoint}_max_window_bits`;
577
- const windowBits = typeof this.params[key] !== "number" ? zlib2.Z_DEFAULT_WINDOWBITS : this.params[key];
578
- this._deflate = zlib2.createDeflateRaw({
579
- ...this._options.zlibDeflateOptions,
580
- windowBits
581
- });
582
- this._deflate[kTotalLength] = 0;
583
- this._deflate[kBuffers] = [];
584
- this._deflate.on("data", deflateOnData);
585
- }
586
- this._deflate[kCallback] = callback;
587
- this._deflate.write(data);
588
- this._deflate.flush(zlib2.Z_SYNC_FLUSH, () => {
589
- if (!this._deflate) {
590
- return;
591
- }
592
- let data2 = bufferUtil.concat(
593
- this._deflate[kBuffers],
594
- this._deflate[kTotalLength]
595
- );
596
- if (fin) {
597
- data2 = new FastBuffer(data2.buffer, data2.byteOffset, data2.length - 4);
598
- }
599
- this._deflate[kCallback] = null;
600
- this._deflate[kTotalLength] = 0;
601
- this._deflate[kBuffers] = [];
602
- if (fin && this.params[`${endpoint}_no_context_takeover`]) {
603
- this._deflate.reset();
604
- }
605
- callback(null, data2);
606
- });
607
- }
608
- };
609
- module.exports = PerMessageDeflate;
610
- function deflateOnData(chunk) {
611
- this[kBuffers].push(chunk);
612
- this[kTotalLength] += chunk.length;
613
- }
614
- function inflateOnData(chunk) {
615
- this[kTotalLength] += chunk.length;
616
- if (this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) {
617
- this[kBuffers].push(chunk);
618
- return;
619
- }
620
- this[kError] = new RangeError("Max payload size exceeded");
621
- this[kError].code = "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH";
622
- this[kError][kStatusCode] = 1009;
623
- this.removeListener("data", inflateOnData);
624
- this.reset();
625
- }
626
- function inflateOnError(err) {
627
- this[kPerMessageDeflate]._inflate = null;
628
- err[kStatusCode] = 1007;
629
- this[kCallback](err);
630
- }
631
- }
632
- });
633
-
634
- // packages/cli/node_modules/ws/lib/validation.js
635
- var require_validation = __commonJS({
636
- "packages/cli/node_modules/ws/lib/validation.js"(exports, module) {
637
- "use strict";
638
- var { isUtf8 } = __require("buffer");
639
- var tokenChars = [
640
- 0,
641
- 0,
642
- 0,
643
- 0,
644
- 0,
645
- 0,
646
- 0,
647
- 0,
648
- 0,
649
- 0,
650
- 0,
651
- 0,
652
- 0,
653
- 0,
654
- 0,
655
- 0,
656
- // 0 - 15
657
- 0,
658
- 0,
659
- 0,
660
- 0,
661
- 0,
662
- 0,
663
- 0,
664
- 0,
665
- 0,
666
- 0,
667
- 0,
668
- 0,
669
- 0,
670
- 0,
671
- 0,
672
- 0,
673
- // 16 - 31
674
- 0,
675
- 1,
676
- 0,
677
- 1,
678
- 1,
679
- 1,
680
- 1,
681
- 1,
682
- 0,
683
- 0,
684
- 1,
685
- 1,
686
- 0,
687
- 1,
688
- 1,
689
- 0,
690
- // 32 - 47
691
- 1,
692
- 1,
693
- 1,
694
- 1,
695
- 1,
696
- 1,
697
- 1,
698
- 1,
699
- 1,
700
- 1,
701
- 0,
702
- 0,
703
- 0,
704
- 0,
705
- 0,
706
- 0,
707
- // 48 - 63
708
- 0,
709
- 1,
710
- 1,
711
- 1,
712
- 1,
713
- 1,
714
- 1,
715
- 1,
716
- 1,
717
- 1,
718
- 1,
719
- 1,
720
- 1,
721
- 1,
722
- 1,
723
- 1,
724
- // 64 - 79
725
- 1,
726
- 1,
727
- 1,
728
- 1,
729
- 1,
730
- 1,
731
- 1,
732
- 1,
733
- 1,
734
- 1,
735
- 1,
736
- 0,
737
- 0,
738
- 0,
739
- 1,
740
- 1,
741
- // 80 - 95
742
- 1,
743
- 1,
744
- 1,
745
- 1,
746
- 1,
747
- 1,
748
- 1,
749
- 1,
750
- 1,
751
- 1,
752
- 1,
753
- 1,
754
- 1,
755
- 1,
756
- 1,
757
- 1,
758
- // 96 - 111
759
- 1,
760
- 1,
761
- 1,
762
- 1,
763
- 1,
764
- 1,
765
- 1,
766
- 1,
767
- 1,
768
- 1,
769
- 1,
770
- 0,
771
- 1,
772
- 0,
773
- 1,
774
- 0
775
- // 112 - 127
776
- ];
777
- function isValidStatusCode(code) {
778
- return code >= 1e3 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006 || code >= 3e3 && code <= 4999;
779
- }
780
- function _isValidUTF8(buf) {
781
- const len = buf.length;
782
- let i = 0;
783
- while (i < len) {
784
- if ((buf[i] & 128) === 0) {
785
- i++;
786
- } else if ((buf[i] & 224) === 192) {
787
- if (i + 1 === len || (buf[i + 1] & 192) !== 128 || (buf[i] & 254) === 192) {
788
- return false;
789
- }
790
- i += 2;
791
- } else if ((buf[i] & 240) === 224) {
792
- if (i + 2 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || buf[i] === 224 && (buf[i + 1] & 224) === 128 || // Overlong
793
- buf[i] === 237 && (buf[i + 1] & 224) === 160) {
794
- return false;
795
- }
796
- i += 3;
797
- } else if ((buf[i] & 248) === 240) {
798
- if (i + 3 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || (buf[i + 3] & 192) !== 128 || buf[i] === 240 && (buf[i + 1] & 240) === 128 || // Overlong
799
- buf[i] === 244 && buf[i + 1] > 143 || buf[i] > 244) {
800
- return false;
801
- }
802
- i += 4;
803
- } else {
804
- return false;
805
- }
806
- }
807
- return true;
808
- }
809
- module.exports = {
810
- isValidStatusCode,
811
- isValidUTF8: _isValidUTF8,
812
- tokenChars
813
- };
814
- if (isUtf8) {
815
- module.exports.isValidUTF8 = function(buf) {
816
- return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);
817
- };
818
- } else if (!process.env.WS_NO_UTF_8_VALIDATE) {
819
- try {
820
- const isValidUTF8 = __require("utf-8-validate");
821
- module.exports.isValidUTF8 = function(buf) {
822
- return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);
823
- };
824
- } catch (e) {
825
- }
826
- }
827
- }
828
- });
829
-
830
- // packages/cli/node_modules/ws/lib/receiver.js
831
- var require_receiver = __commonJS({
832
- "packages/cli/node_modules/ws/lib/receiver.js"(exports, module) {
833
- "use strict";
834
- var { Writable } = __require("stream");
835
- var PerMessageDeflate = require_permessage_deflate();
836
- var {
837
- BINARY_TYPES,
838
- EMPTY_BUFFER,
839
- kStatusCode,
840
- kWebSocket
841
- } = require_constants();
842
- var { concat, toArrayBuffer, unmask } = require_buffer_util();
843
- var { isValidStatusCode, isValidUTF8 } = require_validation();
844
- var FastBuffer = Buffer[Symbol.species];
845
- var promise = Promise.resolve();
846
- var queueTask = typeof queueMicrotask === "function" ? queueMicrotask : queueMicrotaskShim;
847
- var GET_INFO = 0;
848
- var GET_PAYLOAD_LENGTH_16 = 1;
849
- var GET_PAYLOAD_LENGTH_64 = 2;
850
- var GET_MASK = 3;
851
- var GET_DATA = 4;
852
- var INFLATING = 5;
853
- var DEFER_EVENT = 6;
854
- var Receiver2 = class extends Writable {
855
- /**
856
- * Creates a Receiver instance.
857
- *
858
- * @param {Object} [options] Options object
859
- * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether
860
- * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
861
- * multiple times in the same tick
862
- * @param {String} [options.binaryType=nodebuffer] The type for binary data
863
- * @param {Object} [options.extensions] An object containing the negotiated
864
- * extensions
865
- * @param {Boolean} [options.isServer=false] Specifies whether to operate in
866
- * client or server mode
867
- * @param {Number} [options.maxPayload=0] The maximum allowed message length
868
- * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
869
- * not to skip UTF-8 validation for text and close messages
870
- */
871
- constructor(options = {}) {
872
- super();
873
- this._allowSynchronousEvents = !!options.allowSynchronousEvents;
874
- this._binaryType = options.binaryType || BINARY_TYPES[0];
875
- this._extensions = options.extensions || {};
876
- this._isServer = !!options.isServer;
877
- this._maxPayload = options.maxPayload | 0;
878
- this._skipUTF8Validation = !!options.skipUTF8Validation;
879
- this[kWebSocket] = void 0;
880
- this._bufferedBytes = 0;
881
- this._buffers = [];
882
- this._compressed = false;
883
- this._payloadLength = 0;
884
- this._mask = void 0;
885
- this._fragmented = 0;
886
- this._masked = false;
887
- this._fin = false;
888
- this._opcode = 0;
889
- this._totalPayloadLength = 0;
890
- this._messageLength = 0;
891
- this._fragments = [];
892
- this._errored = false;
893
- this._loop = false;
894
- this._state = GET_INFO;
895
- }
896
- /**
897
- * Implements `Writable.prototype._write()`.
898
- *
899
- * @param {Buffer} chunk The chunk of data to write
900
- * @param {String} encoding The character encoding of `chunk`
901
- * @param {Function} cb Callback
902
- * @private
903
- */
904
- _write(chunk, encoding, cb) {
905
- if (this._opcode === 8 && this._state == GET_INFO) return cb();
906
- this._bufferedBytes += chunk.length;
907
- this._buffers.push(chunk);
908
- this.startLoop(cb);
909
- }
910
- /**
911
- * Consumes `n` bytes from the buffered data.
912
- *
913
- * @param {Number} n The number of bytes to consume
914
- * @return {Buffer} The consumed bytes
915
- * @private
916
- */
917
- consume(n) {
918
- this._bufferedBytes -= n;
919
- if (n === this._buffers[0].length) return this._buffers.shift();
920
- if (n < this._buffers[0].length) {
921
- const buf = this._buffers[0];
922
- this._buffers[0] = new FastBuffer(
923
- buf.buffer,
924
- buf.byteOffset + n,
925
- buf.length - n
926
- );
927
- return new FastBuffer(buf.buffer, buf.byteOffset, n);
928
- }
929
- const dst = Buffer.allocUnsafe(n);
930
- do {
931
- const buf = this._buffers[0];
932
- const offset = dst.length - n;
933
- if (n >= buf.length) {
934
- dst.set(this._buffers.shift(), offset);
935
- } else {
936
- dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);
937
- this._buffers[0] = new FastBuffer(
938
- buf.buffer,
939
- buf.byteOffset + n,
940
- buf.length - n
941
- );
942
- }
943
- n -= buf.length;
944
- } while (n > 0);
945
- return dst;
946
- }
947
- /**
948
- * Starts the parsing loop.
949
- *
950
- * @param {Function} cb Callback
951
- * @private
952
- */
953
- startLoop(cb) {
954
- this._loop = true;
955
- do {
956
- switch (this._state) {
957
- case GET_INFO:
958
- this.getInfo(cb);
959
- break;
960
- case GET_PAYLOAD_LENGTH_16:
961
- this.getPayloadLength16(cb);
962
- break;
963
- case GET_PAYLOAD_LENGTH_64:
964
- this.getPayloadLength64(cb);
965
- break;
966
- case GET_MASK:
967
- this.getMask();
968
- break;
969
- case GET_DATA:
970
- this.getData(cb);
971
- break;
972
- case INFLATING:
973
- case DEFER_EVENT:
974
- this._loop = false;
975
- return;
976
- }
977
- } while (this._loop);
978
- if (!this._errored) cb();
979
- }
980
- /**
981
- * Reads the first two bytes of a frame.
982
- *
983
- * @param {Function} cb Callback
984
- * @private
985
- */
986
- getInfo(cb) {
987
- if (this._bufferedBytes < 2) {
988
- this._loop = false;
989
- return;
990
- }
991
- const buf = this.consume(2);
992
- if ((buf[0] & 48) !== 0) {
993
- const error = this.createError(
994
- RangeError,
995
- "RSV2 and RSV3 must be clear",
996
- true,
997
- 1002,
998
- "WS_ERR_UNEXPECTED_RSV_2_3"
999
- );
1000
- cb(error);
1001
- return;
1002
- }
1003
- const compressed = (buf[0] & 64) === 64;
1004
- if (compressed && !this._extensions[PerMessageDeflate.extensionName]) {
1005
- const error = this.createError(
1006
- RangeError,
1007
- "RSV1 must be clear",
1008
- true,
1009
- 1002,
1010
- "WS_ERR_UNEXPECTED_RSV_1"
1011
- );
1012
- cb(error);
1013
- return;
1014
- }
1015
- this._fin = (buf[0] & 128) === 128;
1016
- this._opcode = buf[0] & 15;
1017
- this._payloadLength = buf[1] & 127;
1018
- if (this._opcode === 0) {
1019
- if (compressed) {
1020
- const error = this.createError(
1021
- RangeError,
1022
- "RSV1 must be clear",
1023
- true,
1024
- 1002,
1025
- "WS_ERR_UNEXPECTED_RSV_1"
1026
- );
1027
- cb(error);
1028
- return;
1029
- }
1030
- if (!this._fragmented) {
1031
- const error = this.createError(
1032
- RangeError,
1033
- "invalid opcode 0",
1034
- true,
1035
- 1002,
1036
- "WS_ERR_INVALID_OPCODE"
1037
- );
1038
- cb(error);
1039
- return;
1040
- }
1041
- this._opcode = this._fragmented;
1042
- } else if (this._opcode === 1 || this._opcode === 2) {
1043
- if (this._fragmented) {
1044
- const error = this.createError(
1045
- RangeError,
1046
- `invalid opcode ${this._opcode}`,
1047
- true,
1048
- 1002,
1049
- "WS_ERR_INVALID_OPCODE"
1050
- );
1051
- cb(error);
1052
- return;
1053
- }
1054
- this._compressed = compressed;
1055
- } else if (this._opcode > 7 && this._opcode < 11) {
1056
- if (!this._fin) {
1057
- const error = this.createError(
1058
- RangeError,
1059
- "FIN must be set",
1060
- true,
1061
- 1002,
1062
- "WS_ERR_EXPECTED_FIN"
1063
- );
1064
- cb(error);
1065
- return;
1066
- }
1067
- if (compressed) {
1068
- const error = this.createError(
1069
- RangeError,
1070
- "RSV1 must be clear",
1071
- true,
1072
- 1002,
1073
- "WS_ERR_UNEXPECTED_RSV_1"
1074
- );
1075
- cb(error);
1076
- return;
1077
- }
1078
- if (this._payloadLength > 125 || this._opcode === 8 && this._payloadLength === 1) {
1079
- const error = this.createError(
1080
- RangeError,
1081
- `invalid payload length ${this._payloadLength}`,
1082
- true,
1083
- 1002,
1084
- "WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"
1085
- );
1086
- cb(error);
1087
- return;
1088
- }
1089
- } else {
1090
- const error = this.createError(
1091
- RangeError,
1092
- `invalid opcode ${this._opcode}`,
1093
- true,
1094
- 1002,
1095
- "WS_ERR_INVALID_OPCODE"
1096
- );
1097
- cb(error);
1098
- return;
1099
- }
1100
- if (!this._fin && !this._fragmented) this._fragmented = this._opcode;
1101
- this._masked = (buf[1] & 128) === 128;
1102
- if (this._isServer) {
1103
- if (!this._masked) {
1104
- const error = this.createError(
1105
- RangeError,
1106
- "MASK must be set",
1107
- true,
1108
- 1002,
1109
- "WS_ERR_EXPECTED_MASK"
1110
- );
1111
- cb(error);
1112
- return;
1113
- }
1114
- } else if (this._masked) {
1115
- const error = this.createError(
1116
- RangeError,
1117
- "MASK must be clear",
1118
- true,
1119
- 1002,
1120
- "WS_ERR_UNEXPECTED_MASK"
1121
- );
1122
- cb(error);
1123
- return;
1124
- }
1125
- if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;
1126
- else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;
1127
- else this.haveLength(cb);
1128
- }
1129
- /**
1130
- * Gets extended payload length (7+16).
1131
- *
1132
- * @param {Function} cb Callback
1133
- * @private
1134
- */
1135
- getPayloadLength16(cb) {
1136
- if (this._bufferedBytes < 2) {
1137
- this._loop = false;
1138
- return;
1139
- }
1140
- this._payloadLength = this.consume(2).readUInt16BE(0);
1141
- this.haveLength(cb);
1142
- }
1143
- /**
1144
- * Gets extended payload length (7+64).
1145
- *
1146
- * @param {Function} cb Callback
1147
- * @private
1148
- */
1149
- getPayloadLength64(cb) {
1150
- if (this._bufferedBytes < 8) {
1151
- this._loop = false;
1152
- return;
1153
- }
1154
- const buf = this.consume(8);
1155
- const num = buf.readUInt32BE(0);
1156
- if (num > Math.pow(2, 53 - 32) - 1) {
1157
- const error = this.createError(
1158
- RangeError,
1159
- "Unsupported WebSocket frame: payload length > 2^53 - 1",
1160
- false,
1161
- 1009,
1162
- "WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH"
1163
- );
1164
- cb(error);
1165
- return;
1166
- }
1167
- this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
1168
- this.haveLength(cb);
1169
- }
1170
- /**
1171
- * Payload length has been read.
1172
- *
1173
- * @param {Function} cb Callback
1174
- * @private
1175
- */
1176
- haveLength(cb) {
1177
- if (this._payloadLength && this._opcode < 8) {
1178
- this._totalPayloadLength += this._payloadLength;
1179
- if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
1180
- const error = this.createError(
1181
- RangeError,
1182
- "Max payload size exceeded",
1183
- false,
1184
- 1009,
1185
- "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
1186
- );
1187
- cb(error);
1188
- return;
1189
- }
1190
- }
1191
- if (this._masked) this._state = GET_MASK;
1192
- else this._state = GET_DATA;
1193
- }
1194
- /**
1195
- * Reads mask bytes.
1196
- *
1197
- * @private
1198
- */
1199
- getMask() {
1200
- if (this._bufferedBytes < 4) {
1201
- this._loop = false;
1202
- return;
1203
- }
1204
- this._mask = this.consume(4);
1205
- this._state = GET_DATA;
1206
- }
1207
- /**
1208
- * Reads data bytes.
1209
- *
1210
- * @param {Function} cb Callback
1211
- * @private
1212
- */
1213
- getData(cb) {
1214
- let data = EMPTY_BUFFER;
1215
- if (this._payloadLength) {
1216
- if (this._bufferedBytes < this._payloadLength) {
1217
- this._loop = false;
1218
- return;
1219
- }
1220
- data = this.consume(this._payloadLength);
1221
- if (this._masked && (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0) {
1222
- unmask(data, this._mask);
1223
- }
1224
- }
1225
- if (this._opcode > 7) {
1226
- this.controlMessage(data, cb);
1227
- return;
1228
- }
1229
- if (this._compressed) {
1230
- this._state = INFLATING;
1231
- this.decompress(data, cb);
1232
- return;
1233
- }
1234
- if (data.length) {
1235
- this._messageLength = this._totalPayloadLength;
1236
- this._fragments.push(data);
1237
- }
1238
- this.dataMessage(cb);
1239
- }
1240
- /**
1241
- * Decompresses data.
1242
- *
1243
- * @param {Buffer} data Compressed data
1244
- * @param {Function} cb Callback
1245
- * @private
1246
- */
1247
- decompress(data, cb) {
1248
- const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
1249
- perMessageDeflate.decompress(data, this._fin, (err, buf) => {
1250
- if (err) return cb(err);
1251
- if (buf.length) {
1252
- this._messageLength += buf.length;
1253
- if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
1254
- const error = this.createError(
1255
- RangeError,
1256
- "Max payload size exceeded",
1257
- false,
1258
- 1009,
1259
- "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
1260
- );
1261
- cb(error);
1262
- return;
1263
- }
1264
- this._fragments.push(buf);
1265
- }
1266
- this.dataMessage(cb);
1267
- if (this._state === GET_INFO) this.startLoop(cb);
1268
- });
1269
- }
1270
- /**
1271
- * Handles a data message.
1272
- *
1273
- * @param {Function} cb Callback
1274
- * @private
1275
- */
1276
- dataMessage(cb) {
1277
- if (!this._fin) {
1278
- this._state = GET_INFO;
1279
- return;
1280
- }
1281
- const messageLength = this._messageLength;
1282
- const fragments = this._fragments;
1283
- this._totalPayloadLength = 0;
1284
- this._messageLength = 0;
1285
- this._fragmented = 0;
1286
- this._fragments = [];
1287
- if (this._opcode === 2) {
1288
- let data;
1289
- if (this._binaryType === "nodebuffer") {
1290
- data = concat(fragments, messageLength);
1291
- } else if (this._binaryType === "arraybuffer") {
1292
- data = toArrayBuffer(concat(fragments, messageLength));
1293
- } else {
1294
- data = fragments;
1295
- }
1296
- if (this._state === INFLATING || this._allowSynchronousEvents) {
1297
- this.emit("message", data, true);
1298
- this._state = GET_INFO;
1299
- } else {
1300
- this._state = DEFER_EVENT;
1301
- queueTask(() => {
1302
- this.emit("message", data, true);
1303
- this._state = GET_INFO;
1304
- this.startLoop(cb);
1305
- });
1306
- }
1307
- } else {
1308
- const buf = concat(fragments, messageLength);
1309
- if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
1310
- const error = this.createError(
1311
- Error,
1312
- "invalid UTF-8 sequence",
1313
- true,
1314
- 1007,
1315
- "WS_ERR_INVALID_UTF8"
1316
- );
1317
- cb(error);
1318
- return;
1319
- }
1320
- if (this._state === INFLATING || this._allowSynchronousEvents) {
1321
- this.emit("message", buf, false);
1322
- this._state = GET_INFO;
1323
- } else {
1324
- this._state = DEFER_EVENT;
1325
- queueTask(() => {
1326
- this.emit("message", buf, false);
1327
- this._state = GET_INFO;
1328
- this.startLoop(cb);
1329
- });
1330
- }
1331
- }
1332
- }
1333
- /**
1334
- * Handles a control message.
1335
- *
1336
- * @param {Buffer} data Data to handle
1337
- * @return {(Error|RangeError|undefined)} A possible error
1338
- * @private
1339
- */
1340
- controlMessage(data, cb) {
1341
- if (this._opcode === 8) {
1342
- if (data.length === 0) {
1343
- this._loop = false;
1344
- this.emit("conclude", 1005, EMPTY_BUFFER);
1345
- this.end();
1346
- } else {
1347
- const code = data.readUInt16BE(0);
1348
- if (!isValidStatusCode(code)) {
1349
- const error = this.createError(
1350
- RangeError,
1351
- `invalid status code ${code}`,
1352
- true,
1353
- 1002,
1354
- "WS_ERR_INVALID_CLOSE_CODE"
1355
- );
1356
- cb(error);
1357
- return;
1358
- }
1359
- const buf = new FastBuffer(
1360
- data.buffer,
1361
- data.byteOffset + 2,
1362
- data.length - 2
1363
- );
1364
- if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
1365
- const error = this.createError(
1366
- Error,
1367
- "invalid UTF-8 sequence",
1368
- true,
1369
- 1007,
1370
- "WS_ERR_INVALID_UTF8"
1371
- );
1372
- cb(error);
1373
- return;
1374
- }
1375
- this._loop = false;
1376
- this.emit("conclude", code, buf);
1377
- this.end();
1378
- }
1379
- this._state = GET_INFO;
1380
- return;
1381
- }
1382
- if (this._allowSynchronousEvents) {
1383
- this.emit(this._opcode === 9 ? "ping" : "pong", data);
1384
- this._state = GET_INFO;
1385
- } else {
1386
- this._state = DEFER_EVENT;
1387
- queueTask(() => {
1388
- this.emit(this._opcode === 9 ? "ping" : "pong", data);
1389
- this._state = GET_INFO;
1390
- this.startLoop(cb);
1391
- });
1392
- }
1393
- }
1394
- /**
1395
- * Builds an error object.
1396
- *
1397
- * @param {function(new:Error|RangeError)} ErrorCtor The error constructor
1398
- * @param {String} message The error message
1399
- * @param {Boolean} prefix Specifies whether or not to add a default prefix to
1400
- * `message`
1401
- * @param {Number} statusCode The status code
1402
- * @param {String} errorCode The exposed error code
1403
- * @return {(Error|RangeError)} The error
1404
- * @private
1405
- */
1406
- createError(ErrorCtor, message, prefix, statusCode, errorCode) {
1407
- this._loop = false;
1408
- this._errored = true;
1409
- const err = new ErrorCtor(
1410
- prefix ? `Invalid WebSocket frame: ${message}` : message
1411
- );
1412
- Error.captureStackTrace(err, this.createError);
1413
- err.code = errorCode;
1414
- err[kStatusCode] = statusCode;
1415
- return err;
1416
- }
1417
- };
1418
- module.exports = Receiver2;
1419
- function queueMicrotaskShim(cb) {
1420
- promise.then(cb).catch(throwErrorNextTick);
1421
- }
1422
- function throwError(err) {
1423
- throw err;
1424
- }
1425
- function throwErrorNextTick(err) {
1426
- process.nextTick(throwError, err);
1427
- }
1428
- }
1429
- });
1430
-
1431
- // packages/cli/node_modules/ws/lib/sender.js
1432
- var require_sender = __commonJS({
1433
- "packages/cli/node_modules/ws/lib/sender.js"(exports, module) {
1434
- "use strict";
1435
- var { Duplex } = __require("stream");
1436
- var { randomFillSync } = __require("crypto");
1437
- var PerMessageDeflate = require_permessage_deflate();
1438
- var { EMPTY_BUFFER } = require_constants();
1439
- var { isValidStatusCode } = require_validation();
1440
- var { mask: applyMask, toBuffer } = require_buffer_util();
1441
- var kByteLength = Symbol("kByteLength");
1442
- var maskBuffer = Buffer.alloc(4);
1443
- var Sender2 = class _Sender {
1444
- /**
1445
- * Creates a Sender instance.
1446
- *
1447
- * @param {Duplex} socket The connection socket
1448
- * @param {Object} [extensions] An object containing the negotiated extensions
1449
- * @param {Function} [generateMask] The function used to generate the masking
1450
- * key
1451
- */
1452
- constructor(socket, extensions, generateMask) {
1453
- this._extensions = extensions || {};
1454
- if (generateMask) {
1455
- this._generateMask = generateMask;
1456
- this._maskBuffer = Buffer.alloc(4);
1457
- }
1458
- this._socket = socket;
1459
- this._firstFragment = true;
1460
- this._compress = false;
1461
- this._bufferedBytes = 0;
1462
- this._deflating = false;
1463
- this._queue = [];
1464
- }
1465
- /**
1466
- * Frames a piece of data according to the HyBi WebSocket protocol.
1467
- *
1468
- * @param {(Buffer|String)} data The data to frame
1469
- * @param {Object} options Options object
1470
- * @param {Boolean} [options.fin=false] Specifies whether or not to set the
1471
- * FIN bit
1472
- * @param {Function} [options.generateMask] The function used to generate the
1473
- * masking key
1474
- * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1475
- * `data`
1476
- * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
1477
- * key
1478
- * @param {Number} options.opcode The opcode
1479
- * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
1480
- * modified
1481
- * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
1482
- * RSV1 bit
1483
- * @return {(Buffer|String)[]} The framed data
1484
- * @public
1485
- */
1486
- static frame(data, options) {
1487
- let mask;
1488
- let merge = false;
1489
- let offset = 2;
1490
- let skipMasking = false;
1491
- if (options.mask) {
1492
- mask = options.maskBuffer || maskBuffer;
1493
- if (options.generateMask) {
1494
- options.generateMask(mask);
1495
- } else {
1496
- randomFillSync(mask, 0, 4);
1497
- }
1498
- skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;
1499
- offset = 6;
1500
- }
1501
- let dataLength;
1502
- if (typeof data === "string") {
1503
- if ((!options.mask || skipMasking) && options[kByteLength] !== void 0) {
1504
- dataLength = options[kByteLength];
1505
- } else {
1506
- data = Buffer.from(data);
1507
- dataLength = data.length;
1508
- }
1509
- } else {
1510
- dataLength = data.length;
1511
- merge = options.mask && options.readOnly && !skipMasking;
1512
- }
1513
- let payloadLength = dataLength;
1514
- if (dataLength >= 65536) {
1515
- offset += 8;
1516
- payloadLength = 127;
1517
- } else if (dataLength > 125) {
1518
- offset += 2;
1519
- payloadLength = 126;
1520
- }
1521
- const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);
1522
- target[0] = options.fin ? options.opcode | 128 : options.opcode;
1523
- if (options.rsv1) target[0] |= 64;
1524
- target[1] = payloadLength;
1525
- if (payloadLength === 126) {
1526
- target.writeUInt16BE(dataLength, 2);
1527
- } else if (payloadLength === 127) {
1528
- target[2] = target[3] = 0;
1529
- target.writeUIntBE(dataLength, 4, 6);
1530
- }
1531
- if (!options.mask) return [target, data];
1532
- target[1] |= 128;
1533
- target[offset - 4] = mask[0];
1534
- target[offset - 3] = mask[1];
1535
- target[offset - 2] = mask[2];
1536
- target[offset - 1] = mask[3];
1537
- if (skipMasking) return [target, data];
1538
- if (merge) {
1539
- applyMask(data, mask, target, offset, dataLength);
1540
- return [target];
1541
- }
1542
- applyMask(data, mask, data, 0, dataLength);
1543
- return [target, data];
1544
- }
1545
- /**
1546
- * Sends a close message to the other peer.
1547
- *
1548
- * @param {Number} [code] The status code component of the body
1549
- * @param {(String|Buffer)} [data] The message component of the body
1550
- * @param {Boolean} [mask=false] Specifies whether or not to mask the message
1551
- * @param {Function} [cb] Callback
1552
- * @public
1553
- */
1554
- close(code, data, mask, cb) {
1555
- let buf;
1556
- if (code === void 0) {
1557
- buf = EMPTY_BUFFER;
1558
- } else if (typeof code !== "number" || !isValidStatusCode(code)) {
1559
- throw new TypeError("First argument must be a valid error code number");
1560
- } else if (data === void 0 || !data.length) {
1561
- buf = Buffer.allocUnsafe(2);
1562
- buf.writeUInt16BE(code, 0);
1563
- } else {
1564
- const length = Buffer.byteLength(data);
1565
- if (length > 123) {
1566
- throw new RangeError("The message must not be greater than 123 bytes");
1567
- }
1568
- buf = Buffer.allocUnsafe(2 + length);
1569
- buf.writeUInt16BE(code, 0);
1570
- if (typeof data === "string") {
1571
- buf.write(data, 2);
1572
- } else {
1573
- buf.set(data, 2);
1574
- }
1575
- }
1576
- const options = {
1577
- [kByteLength]: buf.length,
1578
- fin: true,
1579
- generateMask: this._generateMask,
1580
- mask,
1581
- maskBuffer: this._maskBuffer,
1582
- opcode: 8,
1583
- readOnly: false,
1584
- rsv1: false
1585
- };
1586
- if (this._deflating) {
1587
- this.enqueue([this.dispatch, buf, false, options, cb]);
1588
- } else {
1589
- this.sendFrame(_Sender.frame(buf, options), cb);
1590
- }
1591
- }
1592
- /**
1593
- * Sends a ping message to the other peer.
1594
- *
1595
- * @param {*} data The message to send
1596
- * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
1597
- * @param {Function} [cb] Callback
1598
- * @public
1599
- */
1600
- ping(data, mask, cb) {
1601
- let byteLength;
1602
- let readOnly;
1603
- if (typeof data === "string") {
1604
- byteLength = Buffer.byteLength(data);
1605
- readOnly = false;
1606
- } else {
1607
- data = toBuffer(data);
1608
- byteLength = data.length;
1609
- readOnly = toBuffer.readOnly;
1610
- }
1611
- if (byteLength > 125) {
1612
- throw new RangeError("The data size must not be greater than 125 bytes");
1613
- }
1614
- const options = {
1615
- [kByteLength]: byteLength,
1616
- fin: true,
1617
- generateMask: this._generateMask,
1618
- mask,
1619
- maskBuffer: this._maskBuffer,
1620
- opcode: 9,
1621
- readOnly,
1622
- rsv1: false
1623
- };
1624
- if (this._deflating) {
1625
- this.enqueue([this.dispatch, data, false, options, cb]);
1626
- } else {
1627
- this.sendFrame(_Sender.frame(data, options), cb);
1628
- }
1629
- }
1630
- /**
1631
- * Sends a pong message to the other peer.
1632
- *
1633
- * @param {*} data The message to send
1634
- * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
1635
- * @param {Function} [cb] Callback
1636
- * @public
1637
- */
1638
- pong(data, mask, cb) {
1639
- let byteLength;
1640
- let readOnly;
1641
- if (typeof data === "string") {
1642
- byteLength = Buffer.byteLength(data);
1643
- readOnly = false;
1644
- } else {
1645
- data = toBuffer(data);
1646
- byteLength = data.length;
1647
- readOnly = toBuffer.readOnly;
1648
- }
1649
- if (byteLength > 125) {
1650
- throw new RangeError("The data size must not be greater than 125 bytes");
1651
- }
1652
- const options = {
1653
- [kByteLength]: byteLength,
1654
- fin: true,
1655
- generateMask: this._generateMask,
1656
- mask,
1657
- maskBuffer: this._maskBuffer,
1658
- opcode: 10,
1659
- readOnly,
1660
- rsv1: false
1661
- };
1662
- if (this._deflating) {
1663
- this.enqueue([this.dispatch, data, false, options, cb]);
1664
- } else {
1665
- this.sendFrame(_Sender.frame(data, options), cb);
1666
- }
1667
- }
1668
- /**
1669
- * Sends a data message to the other peer.
1670
- *
1671
- * @param {*} data The message to send
1672
- * @param {Object} options Options object
1673
- * @param {Boolean} [options.binary=false] Specifies whether `data` is binary
1674
- * or text
1675
- * @param {Boolean} [options.compress=false] Specifies whether or not to
1676
- * compress `data`
1677
- * @param {Boolean} [options.fin=false] Specifies whether the fragment is the
1678
- * last one
1679
- * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1680
- * `data`
1681
- * @param {Function} [cb] Callback
1682
- * @public
1683
- */
1684
- send(data, options, cb) {
1685
- const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
1686
- let opcode = options.binary ? 2 : 1;
1687
- let rsv1 = options.compress;
1688
- let byteLength;
1689
- let readOnly;
1690
- if (typeof data === "string") {
1691
- byteLength = Buffer.byteLength(data);
1692
- readOnly = false;
1693
- } else {
1694
- data = toBuffer(data);
1695
- byteLength = data.length;
1696
- readOnly = toBuffer.readOnly;
1697
- }
1698
- if (this._firstFragment) {
1699
- this._firstFragment = false;
1700
- if (rsv1 && perMessageDeflate && perMessageDeflate.params[perMessageDeflate._isServer ? "server_no_context_takeover" : "client_no_context_takeover"]) {
1701
- rsv1 = byteLength >= perMessageDeflate._threshold;
1702
- }
1703
- this._compress = rsv1;
1704
- } else {
1705
- rsv1 = false;
1706
- opcode = 0;
1707
- }
1708
- if (options.fin) this._firstFragment = true;
1709
- if (perMessageDeflate) {
1710
- const opts = {
1711
- [kByteLength]: byteLength,
1712
- fin: options.fin,
1713
- generateMask: this._generateMask,
1714
- mask: options.mask,
1715
- maskBuffer: this._maskBuffer,
1716
- opcode,
1717
- readOnly,
1718
- rsv1
1719
- };
1720
- if (this._deflating) {
1721
- this.enqueue([this.dispatch, data, this._compress, opts, cb]);
1722
- } else {
1723
- this.dispatch(data, this._compress, opts, cb);
1724
- }
1725
- } else {
1726
- this.sendFrame(
1727
- _Sender.frame(data, {
1728
- [kByteLength]: byteLength,
1729
- fin: options.fin,
1730
- generateMask: this._generateMask,
1731
- mask: options.mask,
1732
- maskBuffer: this._maskBuffer,
1733
- opcode,
1734
- readOnly,
1735
- rsv1: false
1736
- }),
1737
- cb
1738
- );
1739
- }
1740
- }
1741
- /**
1742
- * Dispatches a message.
1743
- *
1744
- * @param {(Buffer|String)} data The message to send
1745
- * @param {Boolean} [compress=false] Specifies whether or not to compress
1746
- * `data`
1747
- * @param {Object} options Options object
1748
- * @param {Boolean} [options.fin=false] Specifies whether or not to set the
1749
- * FIN bit
1750
- * @param {Function} [options.generateMask] The function used to generate the
1751
- * masking key
1752
- * @param {Boolean} [options.mask=false] Specifies whether or not to mask
1753
- * `data`
1754
- * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
1755
- * key
1756
- * @param {Number} options.opcode The opcode
1757
- * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
1758
- * modified
1759
- * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
1760
- * RSV1 bit
1761
- * @param {Function} [cb] Callback
1762
- * @private
1763
- */
1764
- dispatch(data, compress, options, cb) {
1765
- if (!compress) {
1766
- this.sendFrame(_Sender.frame(data, options), cb);
1767
- return;
1768
- }
1769
- const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
1770
- this._bufferedBytes += options[kByteLength];
1771
- this._deflating = true;
1772
- perMessageDeflate.compress(data, options.fin, (_, buf) => {
1773
- if (this._socket.destroyed) {
1774
- const err = new Error(
1775
- "The socket was closed while data was being compressed"
1776
- );
1777
- if (typeof cb === "function") cb(err);
1778
- for (let i = 0; i < this._queue.length; i++) {
1779
- const params = this._queue[i];
1780
- const callback = params[params.length - 1];
1781
- if (typeof callback === "function") callback(err);
1782
- }
1783
- return;
1784
- }
1785
- this._bufferedBytes -= options[kByteLength];
1786
- this._deflating = false;
1787
- options.readOnly = false;
1788
- this.sendFrame(_Sender.frame(buf, options), cb);
1789
- this.dequeue();
1790
- });
1791
- }
1792
- /**
1793
- * Executes queued send operations.
1794
- *
1795
- * @private
1796
- */
1797
- dequeue() {
1798
- while (!this._deflating && this._queue.length) {
1799
- const params = this._queue.shift();
1800
- this._bufferedBytes -= params[3][kByteLength];
1801
- Reflect.apply(params[0], this, params.slice(1));
1802
- }
1803
- }
1804
- /**
1805
- * Enqueues a send operation.
1806
- *
1807
- * @param {Array} params Send operation parameters.
1808
- * @private
1809
- */
1810
- enqueue(params) {
1811
- this._bufferedBytes += params[3][kByteLength];
1812
- this._queue.push(params);
1813
- }
1814
- /**
1815
- * Sends a frame.
1816
- *
1817
- * @param {Buffer[]} list The frame to send
1818
- * @param {Function} [cb] Callback
1819
- * @private
1820
- */
1821
- sendFrame(list, cb) {
1822
- if (list.length === 2) {
1823
- this._socket.cork();
1824
- this._socket.write(list[0]);
1825
- this._socket.write(list[1], cb);
1826
- this._socket.uncork();
1827
- } else {
1828
- this._socket.write(list[0], cb);
1829
- }
1830
- }
1831
- };
1832
- module.exports = Sender2;
1833
- }
1834
- });
1835
-
1836
- // packages/cli/node_modules/ws/lib/event-target.js
1837
- var require_event_target = __commonJS({
1838
- "packages/cli/node_modules/ws/lib/event-target.js"(exports, module) {
1839
- "use strict";
1840
- var { kForOnEventAttribute, kListener } = require_constants();
1841
- var kCode = Symbol("kCode");
1842
- var kData = Symbol("kData");
1843
- var kError = Symbol("kError");
1844
- var kMessage = Symbol("kMessage");
1845
- var kReason = Symbol("kReason");
1846
- var kTarget = Symbol("kTarget");
1847
- var kType = Symbol("kType");
1848
- var kWasClean = Symbol("kWasClean");
1849
- var Event = class {
1850
- /**
1851
- * Create a new `Event`.
1852
- *
1853
- * @param {String} type The name of the event
1854
- * @throws {TypeError} If the `type` argument is not specified
1855
- */
1856
- constructor(type) {
1857
- this[kTarget] = null;
1858
- this[kType] = type;
1859
- }
1860
- /**
1861
- * @type {*}
1862
- */
1863
- get target() {
1864
- return this[kTarget];
1865
- }
1866
- /**
1867
- * @type {String}
1868
- */
1869
- get type() {
1870
- return this[kType];
1871
- }
1872
- };
1873
- Object.defineProperty(Event.prototype, "target", { enumerable: true });
1874
- Object.defineProperty(Event.prototype, "type", { enumerable: true });
1875
- var CloseEvent = class extends Event {
1876
- /**
1877
- * Create a new `CloseEvent`.
1878
- *
1879
- * @param {String} type The name of the event
1880
- * @param {Object} [options] A dictionary object that allows for setting
1881
- * attributes via object members of the same name
1882
- * @param {Number} [options.code=0] The status code explaining why the
1883
- * connection was closed
1884
- * @param {String} [options.reason=''] A human-readable string explaining why
1885
- * the connection was closed
1886
- * @param {Boolean} [options.wasClean=false] Indicates whether or not the
1887
- * connection was cleanly closed
1888
- */
1889
- constructor(type, options = {}) {
1890
- super(type);
1891
- this[kCode] = options.code === void 0 ? 0 : options.code;
1892
- this[kReason] = options.reason === void 0 ? "" : options.reason;
1893
- this[kWasClean] = options.wasClean === void 0 ? false : options.wasClean;
1894
- }
1895
- /**
1896
- * @type {Number}
1897
- */
1898
- get code() {
1899
- return this[kCode];
1900
- }
1901
- /**
1902
- * @type {String}
1903
- */
1904
- get reason() {
1905
- return this[kReason];
1906
- }
1907
- /**
1908
- * @type {Boolean}
1909
- */
1910
- get wasClean() {
1911
- return this[kWasClean];
1912
- }
1913
- };
1914
- Object.defineProperty(CloseEvent.prototype, "code", { enumerable: true });
1915
- Object.defineProperty(CloseEvent.prototype, "reason", { enumerable: true });
1916
- Object.defineProperty(CloseEvent.prototype, "wasClean", { enumerable: true });
1917
- var ErrorEvent = class extends Event {
1918
- /**
1919
- * Create a new `ErrorEvent`.
1920
- *
1921
- * @param {String} type The name of the event
1922
- * @param {Object} [options] A dictionary object that allows for setting
1923
- * attributes via object members of the same name
1924
- * @param {*} [options.error=null] The error that generated this event
1925
- * @param {String} [options.message=''] The error message
1926
- */
1927
- constructor(type, options = {}) {
1928
- super(type);
1929
- this[kError] = options.error === void 0 ? null : options.error;
1930
- this[kMessage] = options.message === void 0 ? "" : options.message;
1931
- }
1932
- /**
1933
- * @type {*}
1934
- */
1935
- get error() {
1936
- return this[kError];
1937
- }
1938
- /**
1939
- * @type {String}
1940
- */
1941
- get message() {
1942
- return this[kMessage];
1943
- }
1944
- };
1945
- Object.defineProperty(ErrorEvent.prototype, "error", { enumerable: true });
1946
- Object.defineProperty(ErrorEvent.prototype, "message", { enumerable: true });
1947
- var MessageEvent = class extends Event {
1948
- /**
1949
- * Create a new `MessageEvent`.
1950
- *
1951
- * @param {String} type The name of the event
1952
- * @param {Object} [options] A dictionary object that allows for setting
1953
- * attributes via object members of the same name
1954
- * @param {*} [options.data=null] The message content
1955
- */
1956
- constructor(type, options = {}) {
1957
- super(type);
1958
- this[kData] = options.data === void 0 ? null : options.data;
1959
- }
1960
- /**
1961
- * @type {*}
1962
- */
1963
- get data() {
1964
- return this[kData];
1965
- }
1966
- };
1967
- Object.defineProperty(MessageEvent.prototype, "data", { enumerable: true });
1968
- var EventTarget = {
1969
- /**
1970
- * Register an event listener.
1971
- *
1972
- * @param {String} type A string representing the event type to listen for
1973
- * @param {(Function|Object)} handler The listener to add
1974
- * @param {Object} [options] An options object specifies characteristics about
1975
- * the event listener
1976
- * @param {Boolean} [options.once=false] A `Boolean` indicating that the
1977
- * listener should be invoked at most once after being added. If `true`,
1978
- * the listener would be automatically removed when invoked.
1979
- * @public
1980
- */
1981
- addEventListener(type, handler, options = {}) {
1982
- for (const listener of this.listeners(type)) {
1983
- if (!options[kForOnEventAttribute] && listener[kListener] === handler && !listener[kForOnEventAttribute]) {
1984
- return;
1985
- }
1986
- }
1987
- let wrapper;
1988
- if (type === "message") {
1989
- wrapper = function onMessage(data, isBinary) {
1990
- const event = new MessageEvent("message", {
1991
- data: isBinary ? data : data.toString()
1992
- });
1993
- event[kTarget] = this;
1994
- callListener(handler, this, event);
1995
- };
1996
- } else if (type === "close") {
1997
- wrapper = function onClose(code, message) {
1998
- const event = new CloseEvent("close", {
1999
- code,
2000
- reason: message.toString(),
2001
- wasClean: this._closeFrameReceived && this._closeFrameSent
2002
- });
2003
- event[kTarget] = this;
2004
- callListener(handler, this, event);
2005
- };
2006
- } else if (type === "error") {
2007
- wrapper = function onError(error) {
2008
- const event = new ErrorEvent("error", {
2009
- error,
2010
- message: error.message
2011
- });
2012
- event[kTarget] = this;
2013
- callListener(handler, this, event);
2014
- };
2015
- } else if (type === "open") {
2016
- wrapper = function onOpen() {
2017
- const event = new Event("open");
2018
- event[kTarget] = this;
2019
- callListener(handler, this, event);
2020
- };
2021
- } else {
2022
- return;
2023
- }
2024
- wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];
2025
- wrapper[kListener] = handler;
2026
- if (options.once) {
2027
- this.once(type, wrapper);
2028
- } else {
2029
- this.on(type, wrapper);
2030
- }
2031
- },
2032
- /**
2033
- * Remove an event listener.
2034
- *
2035
- * @param {String} type A string representing the event type to remove
2036
- * @param {(Function|Object)} handler The listener to remove
2037
- * @public
2038
- */
2039
- removeEventListener(type, handler) {
2040
- for (const listener of this.listeners(type)) {
2041
- if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {
2042
- this.removeListener(type, listener);
2043
- break;
2044
- }
2045
- }
2046
- }
2047
- };
2048
- module.exports = {
2049
- CloseEvent,
2050
- ErrorEvent,
2051
- Event,
2052
- EventTarget,
2053
- MessageEvent
2054
- };
2055
- function callListener(listener, thisArg, event) {
2056
- if (typeof listener === "object" && listener.handleEvent) {
2057
- listener.handleEvent.call(listener, event);
2058
- } else {
2059
- listener.call(thisArg, event);
2060
- }
2061
- }
2062
- }
2063
- });
2064
-
2065
- // packages/cli/node_modules/ws/lib/extension.js
2066
- var require_extension = __commonJS({
2067
- "packages/cli/node_modules/ws/lib/extension.js"(exports, module) {
2068
- "use strict";
2069
- var { tokenChars } = require_validation();
2070
- function push(dest, name, elem) {
2071
- if (dest[name] === void 0) dest[name] = [elem];
2072
- else dest[name].push(elem);
2073
- }
2074
- function parse(header) {
2075
- const offers = /* @__PURE__ */ Object.create(null);
2076
- let params = /* @__PURE__ */ Object.create(null);
2077
- let mustUnescape = false;
2078
- let isEscaping = false;
2079
- let inQuotes = false;
2080
- let extensionName;
2081
- let paramName;
2082
- let start = -1;
2083
- let code = -1;
2084
- let end = -1;
2085
- let i = 0;
2086
- for (; i < header.length; i++) {
2087
- code = header.charCodeAt(i);
2088
- if (extensionName === void 0) {
2089
- if (end === -1 && tokenChars[code] === 1) {
2090
- if (start === -1) start = i;
2091
- } else if (i !== 0 && (code === 32 || code === 9)) {
2092
- if (end === -1 && start !== -1) end = i;
2093
- } else if (code === 59 || code === 44) {
2094
- if (start === -1) {
2095
- throw new SyntaxError(`Unexpected character at index ${i}`);
2096
- }
2097
- if (end === -1) end = i;
2098
- const name = header.slice(start, end);
2099
- if (code === 44) {
2100
- push(offers, name, params);
2101
- params = /* @__PURE__ */ Object.create(null);
2102
- } else {
2103
- extensionName = name;
2104
- }
2105
- start = end = -1;
2106
- } else {
2107
- throw new SyntaxError(`Unexpected character at index ${i}`);
2108
- }
2109
- } else if (paramName === void 0) {
2110
- if (end === -1 && tokenChars[code] === 1) {
2111
- if (start === -1) start = i;
2112
- } else if (code === 32 || code === 9) {
2113
- if (end === -1 && start !== -1) end = i;
2114
- } else if (code === 59 || code === 44) {
2115
- if (start === -1) {
2116
- throw new SyntaxError(`Unexpected character at index ${i}`);
2117
- }
2118
- if (end === -1) end = i;
2119
- push(params, header.slice(start, end), true);
2120
- if (code === 44) {
2121
- push(offers, extensionName, params);
2122
- params = /* @__PURE__ */ Object.create(null);
2123
- extensionName = void 0;
2124
- }
2125
- start = end = -1;
2126
- } else if (code === 61 && start !== -1 && end === -1) {
2127
- paramName = header.slice(start, i);
2128
- start = end = -1;
2129
- } else {
2130
- throw new SyntaxError(`Unexpected character at index ${i}`);
2131
- }
2132
- } else {
2133
- if (isEscaping) {
2134
- if (tokenChars[code] !== 1) {
2135
- throw new SyntaxError(`Unexpected character at index ${i}`);
2136
- }
2137
- if (start === -1) start = i;
2138
- else if (!mustUnescape) mustUnescape = true;
2139
- isEscaping = false;
2140
- } else if (inQuotes) {
2141
- if (tokenChars[code] === 1) {
2142
- if (start === -1) start = i;
2143
- } else if (code === 34 && start !== -1) {
2144
- inQuotes = false;
2145
- end = i;
2146
- } else if (code === 92) {
2147
- isEscaping = true;
2148
- } else {
2149
- throw new SyntaxError(`Unexpected character at index ${i}`);
2150
- }
2151
- } else if (code === 34 && header.charCodeAt(i - 1) === 61) {
2152
- inQuotes = true;
2153
- } else if (end === -1 && tokenChars[code] === 1) {
2154
- if (start === -1) start = i;
2155
- } else if (start !== -1 && (code === 32 || code === 9)) {
2156
- if (end === -1) end = i;
2157
- } else if (code === 59 || code === 44) {
2158
- if (start === -1) {
2159
- throw new SyntaxError(`Unexpected character at index ${i}`);
2160
- }
2161
- if (end === -1) end = i;
2162
- let value = header.slice(start, end);
2163
- if (mustUnescape) {
2164
- value = value.replace(/\\/g, "");
2165
- mustUnescape = false;
2166
- }
2167
- push(params, paramName, value);
2168
- if (code === 44) {
2169
- push(offers, extensionName, params);
2170
- params = /* @__PURE__ */ Object.create(null);
2171
- extensionName = void 0;
2172
- }
2173
- paramName = void 0;
2174
- start = end = -1;
2175
- } else {
2176
- throw new SyntaxError(`Unexpected character at index ${i}`);
2177
- }
2178
- }
2179
- }
2180
- if (start === -1 || inQuotes || code === 32 || code === 9) {
2181
- throw new SyntaxError("Unexpected end of input");
2182
- }
2183
- if (end === -1) end = i;
2184
- const token = header.slice(start, end);
2185
- if (extensionName === void 0) {
2186
- push(offers, token, params);
2187
- } else {
2188
- if (paramName === void 0) {
2189
- push(params, token, true);
2190
- } else if (mustUnescape) {
2191
- push(params, paramName, token.replace(/\\/g, ""));
2192
- } else {
2193
- push(params, paramName, token);
2194
- }
2195
- push(offers, extensionName, params);
2196
- }
2197
- return offers;
2198
- }
2199
- function format(extensions) {
2200
- return Object.keys(extensions).map((extension) => {
2201
- let configurations = extensions[extension];
2202
- if (!Array.isArray(configurations)) configurations = [configurations];
2203
- return configurations.map((params) => {
2204
- return [extension].concat(
2205
- Object.keys(params).map((k) => {
2206
- let values = params[k];
2207
- if (!Array.isArray(values)) values = [values];
2208
- return values.map((v) => v === true ? k : `${k}=${v}`).join("; ");
2209
- })
2210
- ).join("; ");
2211
- }).join(", ");
2212
- }).join(", ");
2213
- }
2214
- module.exports = { format, parse };
2215
- }
2216
- });
2217
-
2218
- // packages/cli/node_modules/ws/lib/websocket.js
2219
- var require_websocket = __commonJS({
2220
- "packages/cli/node_modules/ws/lib/websocket.js"(exports, module) {
2221
- "use strict";
2222
- var EventEmitter2 = __require("events");
2223
- var https2 = __require("https");
2224
- var http2 = __require("http");
2225
- var net = __require("net");
2226
- var tls = __require("tls");
2227
- var { randomBytes, createHash } = __require("crypto");
2228
- var { Duplex, Readable } = __require("stream");
2229
- var { URL: URL2 } = __require("url");
2230
- var PerMessageDeflate = require_permessage_deflate();
2231
- var Receiver2 = require_receiver();
2232
- var Sender2 = require_sender();
2233
- var {
2234
- BINARY_TYPES,
2235
- EMPTY_BUFFER,
2236
- GUID,
2237
- kForOnEventAttribute,
2238
- kListener,
2239
- kStatusCode,
2240
- kWebSocket,
2241
- NOOP
2242
- } = require_constants();
2243
- var {
2244
- EventTarget: { addEventListener, removeEventListener }
2245
- } = require_event_target();
2246
- var { format, parse } = require_extension();
2247
- var { toBuffer } = require_buffer_util();
2248
- var closeTimeout = 30 * 1e3;
2249
- var kAborted = Symbol("kAborted");
2250
- var protocolVersions = [8, 13];
2251
- var readyStates = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"];
2252
- var subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
2253
- var WebSocket2 = class _WebSocket extends EventEmitter2 {
2254
- /**
2255
- * Create a new `WebSocket`.
2256
- *
2257
- * @param {(String|URL)} address The URL to which to connect
2258
- * @param {(String|String[])} [protocols] The subprotocols
2259
- * @param {Object} [options] Connection options
2260
- */
2261
- constructor(address, protocols, options) {
2262
- super();
2263
- this._binaryType = BINARY_TYPES[0];
2264
- this._closeCode = 1006;
2265
- this._closeFrameReceived = false;
2266
- this._closeFrameSent = false;
2267
- this._closeMessage = EMPTY_BUFFER;
2268
- this._closeTimer = null;
2269
- this._extensions = {};
2270
- this._paused = false;
2271
- this._protocol = "";
2272
- this._readyState = _WebSocket.CONNECTING;
2273
- this._receiver = null;
2274
- this._sender = null;
2275
- this._socket = null;
2276
- if (address !== null) {
2277
- this._bufferedAmount = 0;
2278
- this._isServer = false;
2279
- this._redirects = 0;
2280
- if (protocols === void 0) {
2281
- protocols = [];
2282
- } else if (!Array.isArray(protocols)) {
2283
- if (typeof protocols === "object" && protocols !== null) {
2284
- options = protocols;
2285
- protocols = [];
2286
- } else {
2287
- protocols = [protocols];
2288
- }
2289
- }
2290
- initAsClient(this, address, protocols, options);
2291
- } else {
2292
- this._autoPong = options.autoPong;
2293
- this._isServer = true;
2294
- }
2295
- }
2296
- /**
2297
- * This deviates from the WHATWG interface since ws doesn't support the
2298
- * required default "blob" type (instead we define a custom "nodebuffer"
2299
- * type).
2300
- *
2301
- * @type {String}
2302
- */
2303
- get binaryType() {
2304
- return this._binaryType;
2305
- }
2306
- set binaryType(type) {
2307
- if (!BINARY_TYPES.includes(type)) return;
2308
- this._binaryType = type;
2309
- if (this._receiver) this._receiver._binaryType = type;
2310
- }
2311
- /**
2312
- * @type {Number}
2313
- */
2314
- get bufferedAmount() {
2315
- if (!this._socket) return this._bufferedAmount;
2316
- return this._socket._writableState.length + this._sender._bufferedBytes;
2317
- }
2318
- /**
2319
- * @type {String}
2320
- */
2321
- get extensions() {
2322
- return Object.keys(this._extensions).join();
2323
- }
2324
- /**
2325
- * @type {Boolean}
2326
- */
2327
- get isPaused() {
2328
- return this._paused;
2329
- }
2330
- /**
2331
- * @type {Function}
2332
- */
2333
- /* istanbul ignore next */
2334
- get onclose() {
2335
- return null;
2336
- }
2337
- /**
2338
- * @type {Function}
2339
- */
2340
- /* istanbul ignore next */
2341
- get onerror() {
2342
- return null;
2343
- }
2344
- /**
2345
- * @type {Function}
2346
- */
2347
- /* istanbul ignore next */
2348
- get onopen() {
2349
- return null;
2350
- }
2351
- /**
2352
- * @type {Function}
2353
- */
2354
- /* istanbul ignore next */
2355
- get onmessage() {
2356
- return null;
2357
- }
2358
- /**
2359
- * @type {String}
2360
- */
2361
- get protocol() {
2362
- return this._protocol;
2363
- }
2364
- /**
2365
- * @type {Number}
2366
- */
2367
- get readyState() {
2368
- return this._readyState;
2369
- }
2370
- /**
2371
- * @type {String}
2372
- */
2373
- get url() {
2374
- return this._url;
2375
- }
2376
- /**
2377
- * Set up the socket and the internal resources.
2378
- *
2379
- * @param {Duplex} socket The network socket between the server and client
2380
- * @param {Buffer} head The first packet of the upgraded stream
2381
- * @param {Object} options Options object
2382
- * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether
2383
- * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
2384
- * multiple times in the same tick
2385
- * @param {Function} [options.generateMask] The function used to generate the
2386
- * masking key
2387
- * @param {Number} [options.maxPayload=0] The maximum allowed message size
2388
- * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
2389
- * not to skip UTF-8 validation for text and close messages
2390
- * @private
2391
- */
2392
- setSocket(socket, head, options) {
2393
- const receiver = new Receiver2({
2394
- allowSynchronousEvents: options.allowSynchronousEvents,
2395
- binaryType: this.binaryType,
2396
- extensions: this._extensions,
2397
- isServer: this._isServer,
2398
- maxPayload: options.maxPayload,
2399
- skipUTF8Validation: options.skipUTF8Validation
2400
- });
2401
- this._sender = new Sender2(socket, this._extensions, options.generateMask);
2402
- this._receiver = receiver;
2403
- this._socket = socket;
2404
- receiver[kWebSocket] = this;
2405
- socket[kWebSocket] = this;
2406
- receiver.on("conclude", receiverOnConclude);
2407
- receiver.on("drain", receiverOnDrain);
2408
- receiver.on("error", receiverOnError);
2409
- receiver.on("message", receiverOnMessage);
2410
- receiver.on("ping", receiverOnPing);
2411
- receiver.on("pong", receiverOnPong);
2412
- if (socket.setTimeout) socket.setTimeout(0);
2413
- if (socket.setNoDelay) socket.setNoDelay();
2414
- if (head.length > 0) socket.unshift(head);
2415
- socket.on("close", socketOnClose);
2416
- socket.on("data", socketOnData);
2417
- socket.on("end", socketOnEnd);
2418
- socket.on("error", socketOnError);
2419
- this._readyState = _WebSocket.OPEN;
2420
- this.emit("open");
2421
- }
2422
- /**
2423
- * Emit the `'close'` event.
2424
- *
2425
- * @private
2426
- */
2427
- emitClose() {
2428
- if (!this._socket) {
2429
- this._readyState = _WebSocket.CLOSED;
2430
- this.emit("close", this._closeCode, this._closeMessage);
2431
- return;
2432
- }
2433
- if (this._extensions[PerMessageDeflate.extensionName]) {
2434
- this._extensions[PerMessageDeflate.extensionName].cleanup();
2435
- }
2436
- this._receiver.removeAllListeners();
2437
- this._readyState = _WebSocket.CLOSED;
2438
- this.emit("close", this._closeCode, this._closeMessage);
2439
- }
2440
- /**
2441
- * Start a closing handshake.
2442
- *
2443
- * +----------+ +-----------+ +----------+
2444
- * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -
2445
- * | +----------+ +-----------+ +----------+ |
2446
- * +----------+ +-----------+ |
2447
- * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING
2448
- * +----------+ +-----------+ |
2449
- * | | | +---+ |
2450
- * +------------------------+-->|fin| - - - -
2451
- * | +---+ | +---+
2452
- * - - - - -|fin|<---------------------+
2453
- * +---+
2454
- *
2455
- * @param {Number} [code] Status code explaining why the connection is closing
2456
- * @param {(String|Buffer)} [data] The reason why the connection is
2457
- * closing
2458
- * @public
2459
- */
2460
- close(code, data) {
2461
- if (this.readyState === _WebSocket.CLOSED) return;
2462
- if (this.readyState === _WebSocket.CONNECTING) {
2463
- const msg = "WebSocket was closed before the connection was established";
2464
- abortHandshake(this, this._req, msg);
2465
- return;
2466
- }
2467
- if (this.readyState === _WebSocket.CLOSING) {
2468
- if (this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted)) {
2469
- this._socket.end();
2470
- }
2471
- return;
2472
- }
2473
- this._readyState = _WebSocket.CLOSING;
2474
- this._sender.close(code, data, !this._isServer, (err) => {
2475
- if (err) return;
2476
- this._closeFrameSent = true;
2477
- if (this._closeFrameReceived || this._receiver._writableState.errorEmitted) {
2478
- this._socket.end();
2479
- }
2480
- });
2481
- this._closeTimer = setTimeout(
2482
- this._socket.destroy.bind(this._socket),
2483
- closeTimeout
2484
- );
2485
- }
2486
- /**
2487
- * Pause the socket.
2488
- *
2489
- * @public
2490
- */
2491
- pause() {
2492
- if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) {
2493
- return;
2494
- }
2495
- this._paused = true;
2496
- this._socket.pause();
2497
- }
2498
- /**
2499
- * Send a ping.
2500
- *
2501
- * @param {*} [data] The data to send
2502
- * @param {Boolean} [mask] Indicates whether or not to mask `data`
2503
- * @param {Function} [cb] Callback which is executed when the ping is sent
2504
- * @public
2505
- */
2506
- ping(data, mask, cb) {
2507
- if (this.readyState === _WebSocket.CONNECTING) {
2508
- throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
2509
- }
2510
- if (typeof data === "function") {
2511
- cb = data;
2512
- data = mask = void 0;
2513
- } else if (typeof mask === "function") {
2514
- cb = mask;
2515
- mask = void 0;
2516
- }
2517
- if (typeof data === "number") data = data.toString();
2518
- if (this.readyState !== _WebSocket.OPEN) {
2519
- sendAfterClose(this, data, cb);
2520
- return;
2521
- }
2522
- if (mask === void 0) mask = !this._isServer;
2523
- this._sender.ping(data || EMPTY_BUFFER, mask, cb);
2524
- }
2525
- /**
2526
- * Send a pong.
2527
- *
2528
- * @param {*} [data] The data to send
2529
- * @param {Boolean} [mask] Indicates whether or not to mask `data`
2530
- * @param {Function} [cb] Callback which is executed when the pong is sent
2531
- * @public
2532
- */
2533
- pong(data, mask, cb) {
2534
- if (this.readyState === _WebSocket.CONNECTING) {
2535
- throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
2536
- }
2537
- if (typeof data === "function") {
2538
- cb = data;
2539
- data = mask = void 0;
2540
- } else if (typeof mask === "function") {
2541
- cb = mask;
2542
- mask = void 0;
2543
- }
2544
- if (typeof data === "number") data = data.toString();
2545
- if (this.readyState !== _WebSocket.OPEN) {
2546
- sendAfterClose(this, data, cb);
2547
- return;
2548
- }
2549
- if (mask === void 0) mask = !this._isServer;
2550
- this._sender.pong(data || EMPTY_BUFFER, mask, cb);
2551
- }
2552
- /**
2553
- * Resume the socket.
2554
- *
2555
- * @public
2556
- */
2557
- resume() {
2558
- if (this.readyState === _WebSocket.CONNECTING || this.readyState === _WebSocket.CLOSED) {
2559
- return;
2560
- }
2561
- this._paused = false;
2562
- if (!this._receiver._writableState.needDrain) this._socket.resume();
2563
- }
2564
- /**
2565
- * Send a data message.
2566
- *
2567
- * @param {*} data The message to send
2568
- * @param {Object} [options] Options object
2569
- * @param {Boolean} [options.binary] Specifies whether `data` is binary or
2570
- * text
2571
- * @param {Boolean} [options.compress] Specifies whether or not to compress
2572
- * `data`
2573
- * @param {Boolean} [options.fin=true] Specifies whether the fragment is the
2574
- * last one
2575
- * @param {Boolean} [options.mask] Specifies whether or not to mask `data`
2576
- * @param {Function} [cb] Callback which is executed when data is written out
2577
- * @public
2578
- */
2579
- send(data, options, cb) {
2580
- if (this.readyState === _WebSocket.CONNECTING) {
2581
- throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
2582
- }
2583
- if (typeof options === "function") {
2584
- cb = options;
2585
- options = {};
2586
- }
2587
- if (typeof data === "number") data = data.toString();
2588
- if (this.readyState !== _WebSocket.OPEN) {
2589
- sendAfterClose(this, data, cb);
2590
- return;
2591
- }
2592
- const opts = {
2593
- binary: typeof data !== "string",
2594
- mask: !this._isServer,
2595
- compress: true,
2596
- fin: true,
2597
- ...options
2598
- };
2599
- if (!this._extensions[PerMessageDeflate.extensionName]) {
2600
- opts.compress = false;
2601
- }
2602
- this._sender.send(data || EMPTY_BUFFER, opts, cb);
2603
- }
2604
- /**
2605
- * Forcibly close the connection.
2606
- *
2607
- * @public
2608
- */
2609
- terminate() {
2610
- if (this.readyState === _WebSocket.CLOSED) return;
2611
- if (this.readyState === _WebSocket.CONNECTING) {
2612
- const msg = "WebSocket was closed before the connection was established";
2613
- abortHandshake(this, this._req, msg);
2614
- return;
2615
- }
2616
- if (this._socket) {
2617
- this._readyState = _WebSocket.CLOSING;
2618
- this._socket.destroy();
2619
- }
2620
- }
2621
- };
2622
- Object.defineProperty(WebSocket2, "CONNECTING", {
2623
- enumerable: true,
2624
- value: readyStates.indexOf("CONNECTING")
2625
- });
2626
- Object.defineProperty(WebSocket2.prototype, "CONNECTING", {
2627
- enumerable: true,
2628
- value: readyStates.indexOf("CONNECTING")
2629
- });
2630
- Object.defineProperty(WebSocket2, "OPEN", {
2631
- enumerable: true,
2632
- value: readyStates.indexOf("OPEN")
2633
- });
2634
- Object.defineProperty(WebSocket2.prototype, "OPEN", {
2635
- enumerable: true,
2636
- value: readyStates.indexOf("OPEN")
2637
- });
2638
- Object.defineProperty(WebSocket2, "CLOSING", {
2639
- enumerable: true,
2640
- value: readyStates.indexOf("CLOSING")
2641
- });
2642
- Object.defineProperty(WebSocket2.prototype, "CLOSING", {
2643
- enumerable: true,
2644
- value: readyStates.indexOf("CLOSING")
2645
- });
2646
- Object.defineProperty(WebSocket2, "CLOSED", {
2647
- enumerable: true,
2648
- value: readyStates.indexOf("CLOSED")
2649
- });
2650
- Object.defineProperty(WebSocket2.prototype, "CLOSED", {
2651
- enumerable: true,
2652
- value: readyStates.indexOf("CLOSED")
2653
- });
2654
- [
2655
- "binaryType",
2656
- "bufferedAmount",
2657
- "extensions",
2658
- "isPaused",
2659
- "protocol",
2660
- "readyState",
2661
- "url"
2662
- ].forEach((property) => {
2663
- Object.defineProperty(WebSocket2.prototype, property, { enumerable: true });
2664
- });
2665
- ["open", "error", "close", "message"].forEach((method) => {
2666
- Object.defineProperty(WebSocket2.prototype, `on${method}`, {
2667
- enumerable: true,
2668
- get() {
2669
- for (const listener of this.listeners(method)) {
2670
- if (listener[kForOnEventAttribute]) return listener[kListener];
2671
- }
2672
- return null;
2673
- },
2674
- set(handler) {
2675
- for (const listener of this.listeners(method)) {
2676
- if (listener[kForOnEventAttribute]) {
2677
- this.removeListener(method, listener);
2678
- break;
2679
- }
2680
- }
2681
- if (typeof handler !== "function") return;
2682
- this.addEventListener(method, handler, {
2683
- [kForOnEventAttribute]: true
2684
- });
2685
- }
2686
- });
2687
- });
2688
- WebSocket2.prototype.addEventListener = addEventListener;
2689
- WebSocket2.prototype.removeEventListener = removeEventListener;
2690
- module.exports = WebSocket2;
2691
- function initAsClient(websocket, address, protocols, options) {
2692
- const opts = {
2693
- allowSynchronousEvents: false,
2694
- autoPong: true,
2695
- protocolVersion: protocolVersions[1],
2696
- maxPayload: 100 * 1024 * 1024,
2697
- skipUTF8Validation: false,
2698
- perMessageDeflate: true,
2699
- followRedirects: false,
2700
- maxRedirects: 10,
2701
- ...options,
2702
- createConnection: void 0,
2703
- socketPath: void 0,
2704
- hostname: void 0,
2705
- protocol: void 0,
2706
- timeout: void 0,
2707
- method: "GET",
2708
- host: void 0,
2709
- path: void 0,
2710
- port: void 0
2711
- };
2712
- websocket._autoPong = opts.autoPong;
2713
- if (!protocolVersions.includes(opts.protocolVersion)) {
2714
- throw new RangeError(
2715
- `Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`
2716
- );
2717
- }
2718
- let parsedUrl;
2719
- if (address instanceof URL2) {
2720
- parsedUrl = address;
2721
- } else {
2722
- try {
2723
- parsedUrl = new URL2(address);
2724
- } catch (e) {
2725
- throw new SyntaxError(`Invalid URL: ${address}`);
2726
- }
2727
- }
2728
- if (parsedUrl.protocol === "http:") {
2729
- parsedUrl.protocol = "ws:";
2730
- } else if (parsedUrl.protocol === "https:") {
2731
- parsedUrl.protocol = "wss:";
2732
- }
2733
- websocket._url = parsedUrl.href;
2734
- const isSecure = parsedUrl.protocol === "wss:";
2735
- const isIpcUrl = parsedUrl.protocol === "ws+unix:";
2736
- let invalidUrlMessage;
2737
- if (parsedUrl.protocol !== "ws:" && !isSecure && !isIpcUrl) {
2738
- invalidUrlMessage = `The URL's protocol must be one of "ws:", "wss:", "http:", "https", or "ws+unix:"`;
2739
- } else if (isIpcUrl && !parsedUrl.pathname) {
2740
- invalidUrlMessage = "The URL's pathname is empty";
2741
- } else if (parsedUrl.hash) {
2742
- invalidUrlMessage = "The URL contains a fragment identifier";
2743
- }
2744
- if (invalidUrlMessage) {
2745
- const err = new SyntaxError(invalidUrlMessage);
2746
- if (websocket._redirects === 0) {
2747
- throw err;
2748
- } else {
2749
- emitErrorAndClose(websocket, err);
2750
- return;
2751
- }
2752
- }
2753
- const defaultPort = isSecure ? 443 : 80;
2754
- const key = randomBytes(16).toString("base64");
2755
- const request = isSecure ? https2.request : http2.request;
2756
- const protocolSet = /* @__PURE__ */ new Set();
2757
- let perMessageDeflate;
2758
- opts.createConnection = isSecure ? tlsConnect : netConnect;
2759
- opts.defaultPort = opts.defaultPort || defaultPort;
2760
- opts.port = parsedUrl.port || defaultPort;
2761
- opts.host = parsedUrl.hostname.startsWith("[") ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname;
2762
- opts.headers = {
2763
- ...opts.headers,
2764
- "Sec-WebSocket-Version": opts.protocolVersion,
2765
- "Sec-WebSocket-Key": key,
2766
- Connection: "Upgrade",
2767
- Upgrade: "websocket"
2768
- };
2769
- opts.path = parsedUrl.pathname + parsedUrl.search;
2770
- opts.timeout = opts.handshakeTimeout;
2771
- if (opts.perMessageDeflate) {
2772
- perMessageDeflate = new PerMessageDeflate(
2773
- opts.perMessageDeflate !== true ? opts.perMessageDeflate : {},
2774
- false,
2775
- opts.maxPayload
2776
- );
2777
- opts.headers["Sec-WebSocket-Extensions"] = format({
2778
- [PerMessageDeflate.extensionName]: perMessageDeflate.offer()
2779
- });
2780
- }
2781
- if (protocols.length) {
2782
- for (const protocol of protocols) {
2783
- if (typeof protocol !== "string" || !subprotocolRegex.test(protocol) || protocolSet.has(protocol)) {
2784
- throw new SyntaxError(
2785
- "An invalid or duplicated subprotocol was specified"
2786
- );
2787
- }
2788
- protocolSet.add(protocol);
2789
- }
2790
- opts.headers["Sec-WebSocket-Protocol"] = protocols.join(",");
2791
- }
2792
- if (opts.origin) {
2793
- if (opts.protocolVersion < 13) {
2794
- opts.headers["Sec-WebSocket-Origin"] = opts.origin;
2795
- } else {
2796
- opts.headers.Origin = opts.origin;
2797
- }
2798
- }
2799
- if (parsedUrl.username || parsedUrl.password) {
2800
- opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
2801
- }
2802
- if (isIpcUrl) {
2803
- const parts = opts.path.split(":");
2804
- opts.socketPath = parts[0];
2805
- opts.path = parts[1];
2806
- }
2807
- let req;
2808
- if (opts.followRedirects) {
2809
- if (websocket._redirects === 0) {
2810
- websocket._originalIpc = isIpcUrl;
2811
- websocket._originalSecure = isSecure;
2812
- websocket._originalHostOrSocketPath = isIpcUrl ? opts.socketPath : parsedUrl.host;
2813
- const headers = options && options.headers;
2814
- options = { ...options, headers: {} };
2815
- if (headers) {
2816
- for (const [key2, value] of Object.entries(headers)) {
2817
- options.headers[key2.toLowerCase()] = value;
2818
- }
2819
- }
2820
- } else if (websocket.listenerCount("redirect") === 0) {
2821
- const isSameHost = isIpcUrl ? websocket._originalIpc ? opts.socketPath === websocket._originalHostOrSocketPath : false : websocket._originalIpc ? false : parsedUrl.host === websocket._originalHostOrSocketPath;
2822
- if (!isSameHost || websocket._originalSecure && !isSecure) {
2823
- delete opts.headers.authorization;
2824
- delete opts.headers.cookie;
2825
- if (!isSameHost) delete opts.headers.host;
2826
- opts.auth = void 0;
2827
- }
2828
- }
2829
- if (opts.auth && !options.headers.authorization) {
2830
- options.headers.authorization = "Basic " + Buffer.from(opts.auth).toString("base64");
2831
- }
2832
- req = websocket._req = request(opts);
2833
- if (websocket._redirects) {
2834
- websocket.emit("redirect", websocket.url, req);
2835
- }
2836
- } else {
2837
- req = websocket._req = request(opts);
2838
- }
2839
- if (opts.timeout) {
2840
- req.on("timeout", () => {
2841
- abortHandshake(websocket, req, "Opening handshake has timed out");
2842
- });
2843
- }
2844
- req.on("error", (err) => {
2845
- if (req === null || req[kAborted]) return;
2846
- req = websocket._req = null;
2847
- emitErrorAndClose(websocket, err);
2848
- });
2849
- req.on("response", (res) => {
2850
- const location = res.headers.location;
2851
- const statusCode = res.statusCode;
2852
- if (location && opts.followRedirects && statusCode >= 300 && statusCode < 400) {
2853
- if (++websocket._redirects > opts.maxRedirects) {
2854
- abortHandshake(websocket, req, "Maximum redirects exceeded");
2855
- return;
2856
- }
2857
- req.abort();
2858
- let addr;
2859
- try {
2860
- addr = new URL2(location, address);
2861
- } catch (e) {
2862
- const err = new SyntaxError(`Invalid URL: ${location}`);
2863
- emitErrorAndClose(websocket, err);
2864
- return;
2865
- }
2866
- initAsClient(websocket, addr, protocols, options);
2867
- } else if (!websocket.emit("unexpected-response", req, res)) {
2868
- abortHandshake(
2869
- websocket,
2870
- req,
2871
- `Unexpected server response: ${res.statusCode}`
2872
- );
2873
- }
2874
- });
2875
- req.on("upgrade", (res, socket, head) => {
2876
- websocket.emit("upgrade", res);
2877
- if (websocket.readyState !== WebSocket2.CONNECTING) return;
2878
- req = websocket._req = null;
2879
- if (res.headers.upgrade.toLowerCase() !== "websocket") {
2880
- abortHandshake(websocket, socket, "Invalid Upgrade header");
2881
- return;
2882
- }
2883
- const digest = createHash("sha1").update(key + GUID).digest("base64");
2884
- if (res.headers["sec-websocket-accept"] !== digest) {
2885
- abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
2886
- return;
2887
- }
2888
- const serverProt = res.headers["sec-websocket-protocol"];
2889
- let protError;
2890
- if (serverProt !== void 0) {
2891
- if (!protocolSet.size) {
2892
- protError = "Server sent a subprotocol but none was requested";
2893
- } else if (!protocolSet.has(serverProt)) {
2894
- protError = "Server sent an invalid subprotocol";
2895
- }
2896
- } else if (protocolSet.size) {
2897
- protError = "Server sent no subprotocol";
2898
- }
2899
- if (protError) {
2900
- abortHandshake(websocket, socket, protError);
2901
- return;
2902
- }
2903
- if (serverProt) websocket._protocol = serverProt;
2904
- const secWebSocketExtensions = res.headers["sec-websocket-extensions"];
2905
- if (secWebSocketExtensions !== void 0) {
2906
- if (!perMessageDeflate) {
2907
- const message = "Server sent a Sec-WebSocket-Extensions header but no extension was requested";
2908
- abortHandshake(websocket, socket, message);
2909
- return;
2910
- }
2911
- let extensions;
2912
- try {
2913
- extensions = parse(secWebSocketExtensions);
2914
- } catch (err) {
2915
- const message = "Invalid Sec-WebSocket-Extensions header";
2916
- abortHandshake(websocket, socket, message);
2917
- return;
2918
- }
2919
- const extensionNames = Object.keys(extensions);
2920
- if (extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate.extensionName) {
2921
- const message = "Server indicated an extension that was not requested";
2922
- abortHandshake(websocket, socket, message);
2923
- return;
2924
- }
2925
- try {
2926
- perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]);
2927
- } catch (err) {
2928
- const message = "Invalid Sec-WebSocket-Extensions header";
2929
- abortHandshake(websocket, socket, message);
2930
- return;
2931
- }
2932
- websocket._extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
2933
- }
2934
- websocket.setSocket(socket, head, {
2935
- allowSynchronousEvents: opts.allowSynchronousEvents,
2936
- generateMask: opts.generateMask,
2937
- maxPayload: opts.maxPayload,
2938
- skipUTF8Validation: opts.skipUTF8Validation
2939
- });
2940
- });
2941
- if (opts.finishRequest) {
2942
- opts.finishRequest(req, websocket);
2943
- } else {
2944
- req.end();
2945
- }
2946
- }
2947
- function emitErrorAndClose(websocket, err) {
2948
- websocket._readyState = WebSocket2.CLOSING;
2949
- websocket.emit("error", err);
2950
- websocket.emitClose();
2951
- }
2952
- function netConnect(options) {
2953
- options.path = options.socketPath;
2954
- return net.connect(options);
2955
- }
2956
- function tlsConnect(options) {
2957
- options.path = void 0;
2958
- if (!options.servername && options.servername !== "") {
2959
- options.servername = net.isIP(options.host) ? "" : options.host;
2960
- }
2961
- return tls.connect(options);
2962
- }
2963
- function abortHandshake(websocket, stream, message) {
2964
- websocket._readyState = WebSocket2.CLOSING;
2965
- const err = new Error(message);
2966
- Error.captureStackTrace(err, abortHandshake);
2967
- if (stream.setHeader) {
2968
- stream[kAborted] = true;
2969
- stream.abort();
2970
- if (stream.socket && !stream.socket.destroyed) {
2971
- stream.socket.destroy();
2972
- }
2973
- process.nextTick(emitErrorAndClose, websocket, err);
2974
- } else {
2975
- stream.destroy(err);
2976
- stream.once("error", websocket.emit.bind(websocket, "error"));
2977
- stream.once("close", websocket.emitClose.bind(websocket));
2978
- }
2979
- }
2980
- function sendAfterClose(websocket, data, cb) {
2981
- if (data) {
2982
- const length = toBuffer(data).length;
2983
- if (websocket._socket) websocket._sender._bufferedBytes += length;
2984
- else websocket._bufferedAmount += length;
2985
- }
2986
- if (cb) {
2987
- const err = new Error(
2988
- `WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})`
2989
- );
2990
- process.nextTick(cb, err);
2991
- }
2992
- }
2993
- function receiverOnConclude(code, reason) {
2994
- const websocket = this[kWebSocket];
2995
- websocket._closeFrameReceived = true;
2996
- websocket._closeMessage = reason;
2997
- websocket._closeCode = code;
2998
- if (websocket._socket[kWebSocket] === void 0) return;
2999
- websocket._socket.removeListener("data", socketOnData);
3000
- process.nextTick(resume, websocket._socket);
3001
- if (code === 1005) websocket.close();
3002
- else websocket.close(code, reason);
3003
- }
3004
- function receiverOnDrain() {
3005
- const websocket = this[kWebSocket];
3006
- if (!websocket.isPaused) websocket._socket.resume();
3007
- }
3008
- function receiverOnError(err) {
3009
- const websocket = this[kWebSocket];
3010
- if (websocket._socket[kWebSocket] !== void 0) {
3011
- websocket._socket.removeListener("data", socketOnData);
3012
- process.nextTick(resume, websocket._socket);
3013
- websocket.close(err[kStatusCode]);
3014
- }
3015
- websocket.emit("error", err);
3016
- }
3017
- function receiverOnFinish() {
3018
- this[kWebSocket].emitClose();
3019
- }
3020
- function receiverOnMessage(data, isBinary) {
3021
- this[kWebSocket].emit("message", data, isBinary);
3022
- }
3023
- function receiverOnPing(data) {
3024
- const websocket = this[kWebSocket];
3025
- if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP);
3026
- websocket.emit("ping", data);
3027
- }
3028
- function receiverOnPong(data) {
3029
- this[kWebSocket].emit("pong", data);
3030
- }
3031
- function resume(stream) {
3032
- stream.resume();
3033
- }
3034
- function socketOnClose() {
3035
- const websocket = this[kWebSocket];
3036
- this.removeListener("close", socketOnClose);
3037
- this.removeListener("data", socketOnData);
3038
- this.removeListener("end", socketOnEnd);
3039
- websocket._readyState = WebSocket2.CLOSING;
3040
- let chunk;
3041
- if (!this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && (chunk = websocket._socket.read()) !== null) {
3042
- websocket._receiver.write(chunk);
3043
- }
3044
- websocket._receiver.end();
3045
- this[kWebSocket] = void 0;
3046
- clearTimeout(websocket._closeTimer);
3047
- if (websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted) {
3048
- websocket.emitClose();
3049
- } else {
3050
- websocket._receiver.on("error", receiverOnFinish);
3051
- websocket._receiver.on("finish", receiverOnFinish);
3052
- }
3053
- }
3054
- function socketOnData(chunk) {
3055
- if (!this[kWebSocket]._receiver.write(chunk)) {
3056
- this.pause();
3057
- }
3058
- }
3059
- function socketOnEnd() {
3060
- const websocket = this[kWebSocket];
3061
- websocket._readyState = WebSocket2.CLOSING;
3062
- websocket._receiver.end();
3063
- this.end();
3064
- }
3065
- function socketOnError() {
3066
- const websocket = this[kWebSocket];
3067
- this.removeListener("error", socketOnError);
3068
- this.on("error", NOOP);
3069
- if (websocket) {
3070
- websocket._readyState = WebSocket2.CLOSING;
3071
- this.destroy();
3072
- }
3073
- }
3074
- }
3075
- });
3076
-
3077
- // packages/cli/node_modules/ws/lib/subprotocol.js
3078
- var require_subprotocol = __commonJS({
3079
- "packages/cli/node_modules/ws/lib/subprotocol.js"(exports, module) {
3080
- "use strict";
3081
- var { tokenChars } = require_validation();
3082
- function parse(header) {
3083
- const protocols = /* @__PURE__ */ new Set();
3084
- let start = -1;
3085
- let end = -1;
3086
- let i = 0;
3087
- for (i; i < header.length; i++) {
3088
- const code = header.charCodeAt(i);
3089
- if (end === -1 && tokenChars[code] === 1) {
3090
- if (start === -1) start = i;
3091
- } else if (i !== 0 && (code === 32 || code === 9)) {
3092
- if (end === -1 && start !== -1) end = i;
3093
- } else if (code === 44) {
3094
- if (start === -1) {
3095
- throw new SyntaxError(`Unexpected character at index ${i}`);
3096
- }
3097
- if (end === -1) end = i;
3098
- const protocol2 = header.slice(start, end);
3099
- if (protocols.has(protocol2)) {
3100
- throw new SyntaxError(`The "${protocol2}" subprotocol is duplicated`);
3101
- }
3102
- protocols.add(protocol2);
3103
- start = end = -1;
3104
- } else {
3105
- throw new SyntaxError(`Unexpected character at index ${i}`);
3106
- }
3107
- }
3108
- if (start === -1 || end !== -1) {
3109
- throw new SyntaxError("Unexpected end of input");
3110
- }
3111
- const protocol = header.slice(start, i);
3112
- if (protocols.has(protocol)) {
3113
- throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
3114
- }
3115
- protocols.add(protocol);
3116
- return protocols;
3117
- }
3118
- module.exports = { parse };
3119
- }
3120
- });
3121
-
3122
- // packages/cli/node_modules/ws/lib/websocket-server.js
3123
- var require_websocket_server = __commonJS({
3124
- "packages/cli/node_modules/ws/lib/websocket-server.js"(exports, module) {
3125
- "use strict";
3126
- var EventEmitter2 = __require("events");
3127
- var http2 = __require("http");
3128
- var { Duplex } = __require("stream");
3129
- var { createHash } = __require("crypto");
3130
- var extension = require_extension();
3131
- var PerMessageDeflate = require_permessage_deflate();
3132
- var subprotocol = require_subprotocol();
3133
- var WebSocket2 = require_websocket();
3134
- var { GUID, kWebSocket } = require_constants();
3135
- var keyRegex = /^[+/0-9A-Za-z]{22}==$/;
3136
- var RUNNING = 0;
3137
- var CLOSING = 1;
3138
- var CLOSED = 2;
3139
- var WebSocketServer2 = class extends EventEmitter2 {
3140
- /**
3141
- * Create a `WebSocketServer` instance.
3142
- *
3143
- * @param {Object} options Configuration options
3144
- * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether
3145
- * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
3146
- * multiple times in the same tick
3147
- * @param {Boolean} [options.autoPong=true] Specifies whether or not to
3148
- * automatically send a pong in response to a ping
3149
- * @param {Number} [options.backlog=511] The maximum length of the queue of
3150
- * pending connections
3151
- * @param {Boolean} [options.clientTracking=true] Specifies whether or not to
3152
- * track clients
3153
- * @param {Function} [options.handleProtocols] A hook to handle protocols
3154
- * @param {String} [options.host] The hostname where to bind the server
3155
- * @param {Number} [options.maxPayload=104857600] The maximum allowed message
3156
- * size
3157
- * @param {Boolean} [options.noServer=false] Enable no server mode
3158
- * @param {String} [options.path] Accept only connections matching this path
3159
- * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable
3160
- * permessage-deflate
3161
- * @param {Number} [options.port] The port where to bind the server
3162
- * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S
3163
- * server to use
3164
- * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
3165
- * not to skip UTF-8 validation for text and close messages
3166
- * @param {Function} [options.verifyClient] A hook to reject connections
3167
- * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`
3168
- * class to use. It must be the `WebSocket` class or class that extends it
3169
- * @param {Function} [callback] A listener for the `listening` event
3170
- */
3171
- constructor(options, callback) {
3172
- super();
3173
- options = {
3174
- allowSynchronousEvents: false,
3175
- autoPong: true,
3176
- maxPayload: 100 * 1024 * 1024,
3177
- skipUTF8Validation: false,
3178
- perMessageDeflate: false,
3179
- handleProtocols: null,
3180
- clientTracking: true,
3181
- verifyClient: null,
3182
- noServer: false,
3183
- backlog: null,
3184
- // use default (511 as implemented in net.js)
3185
- server: null,
3186
- host: null,
3187
- path: null,
3188
- port: null,
3189
- WebSocket: WebSocket2,
3190
- ...options
3191
- };
3192
- if (options.port == null && !options.server && !options.noServer || options.port != null && (options.server || options.noServer) || options.server && options.noServer) {
3193
- throw new TypeError(
3194
- 'One and only one of the "port", "server", or "noServer" options must be specified'
3195
- );
3196
- }
3197
- if (options.port != null) {
3198
- this._server = http2.createServer((req, res) => {
3199
- const body = http2.STATUS_CODES[426];
3200
- res.writeHead(426, {
3201
- "Content-Length": body.length,
3202
- "Content-Type": "text/plain"
3203
- });
3204
- res.end(body);
3205
- });
3206
- this._server.listen(
3207
- options.port,
3208
- options.host,
3209
- options.backlog,
3210
- callback
3211
- );
3212
- } else if (options.server) {
3213
- this._server = options.server;
3214
- }
3215
- if (this._server) {
3216
- const emitConnection = this.emit.bind(this, "connection");
3217
- this._removeListeners = addListeners(this._server, {
3218
- listening: this.emit.bind(this, "listening"),
3219
- error: this.emit.bind(this, "error"),
3220
- upgrade: (req, socket, head) => {
3221
- this.handleUpgrade(req, socket, head, emitConnection);
3222
- }
3223
- });
3224
- }
3225
- if (options.perMessageDeflate === true) options.perMessageDeflate = {};
3226
- if (options.clientTracking) {
3227
- this.clients = /* @__PURE__ */ new Set();
3228
- this._shouldEmitClose = false;
3229
- }
3230
- this.options = options;
3231
- this._state = RUNNING;
3232
- }
3233
- /**
3234
- * Returns the bound address, the address family name, and port of the server
3235
- * as reported by the operating system if listening on an IP socket.
3236
- * If the server is listening on a pipe or UNIX domain socket, the name is
3237
- * returned as a string.
3238
- *
3239
- * @return {(Object|String|null)} The address of the server
3240
- * @public
3241
- */
3242
- address() {
3243
- if (this.options.noServer) {
3244
- throw new Error('The server is operating in "noServer" mode');
3245
- }
3246
- if (!this._server) return null;
3247
- return this._server.address();
3248
- }
3249
- /**
3250
- * Stop the server from accepting new connections and emit the `'close'` event
3251
- * when all existing connections are closed.
3252
- *
3253
- * @param {Function} [cb] A one-time listener for the `'close'` event
3254
- * @public
3255
- */
3256
- close(cb) {
3257
- if (this._state === CLOSED) {
3258
- if (cb) {
3259
- this.once("close", () => {
3260
- cb(new Error("The server is not running"));
3261
- });
3262
- }
3263
- process.nextTick(emitClose, this);
3264
- return;
3265
- }
3266
- if (cb) this.once("close", cb);
3267
- if (this._state === CLOSING) return;
3268
- this._state = CLOSING;
3269
- if (this.options.noServer || this.options.server) {
3270
- if (this._server) {
3271
- this._removeListeners();
3272
- this._removeListeners = this._server = null;
3273
- }
3274
- if (this.clients) {
3275
- if (!this.clients.size) {
3276
- process.nextTick(emitClose, this);
3277
- } else {
3278
- this._shouldEmitClose = true;
3279
- }
3280
- } else {
3281
- process.nextTick(emitClose, this);
3282
- }
3283
- } else {
3284
- const server = this._server;
3285
- this._removeListeners();
3286
- this._removeListeners = this._server = null;
3287
- server.close(() => {
3288
- emitClose(this);
3289
- });
3290
- }
3291
- }
3292
- /**
3293
- * See if a given request should be handled by this server instance.
3294
- *
3295
- * @param {http.IncomingMessage} req Request object to inspect
3296
- * @return {Boolean} `true` if the request is valid, else `false`
3297
- * @public
3298
- */
3299
- shouldHandle(req) {
3300
- if (this.options.path) {
3301
- const index = req.url.indexOf("?");
3302
- const pathname = index !== -1 ? req.url.slice(0, index) : req.url;
3303
- if (pathname !== this.options.path) return false;
3304
- }
3305
- return true;
3306
- }
3307
- /**
3308
- * Handle a HTTP Upgrade request.
3309
- *
3310
- * @param {http.IncomingMessage} req The request object
3311
- * @param {Duplex} socket The network socket between the server and client
3312
- * @param {Buffer} head The first packet of the upgraded stream
3313
- * @param {Function} cb Callback
3314
- * @public
3315
- */
3316
- handleUpgrade(req, socket, head, cb) {
3317
- socket.on("error", socketOnError);
3318
- const key = req.headers["sec-websocket-key"];
3319
- const version = +req.headers["sec-websocket-version"];
3320
- if (req.method !== "GET") {
3321
- const message = "Invalid HTTP method";
3322
- abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);
3323
- return;
3324
- }
3325
- if (req.headers.upgrade.toLowerCase() !== "websocket") {
3326
- const message = "Invalid Upgrade header";
3327
- abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3328
- return;
3329
- }
3330
- if (!key || !keyRegex.test(key)) {
3331
- const message = "Missing or invalid Sec-WebSocket-Key header";
3332
- abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3333
- return;
3334
- }
3335
- if (version !== 8 && version !== 13) {
3336
- const message = "Missing or invalid Sec-WebSocket-Version header";
3337
- abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3338
- return;
3339
- }
3340
- if (!this.shouldHandle(req)) {
3341
- abortHandshake(socket, 400);
3342
- return;
3343
- }
3344
- const secWebSocketProtocol = req.headers["sec-websocket-protocol"];
3345
- let protocols = /* @__PURE__ */ new Set();
3346
- if (secWebSocketProtocol !== void 0) {
3347
- try {
3348
- protocols = subprotocol.parse(secWebSocketProtocol);
3349
- } catch (err) {
3350
- const message = "Invalid Sec-WebSocket-Protocol header";
3351
- abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3352
- return;
3353
- }
3354
- }
3355
- const secWebSocketExtensions = req.headers["sec-websocket-extensions"];
3356
- const extensions = {};
3357
- if (this.options.perMessageDeflate && secWebSocketExtensions !== void 0) {
3358
- const perMessageDeflate = new PerMessageDeflate(
3359
- this.options.perMessageDeflate,
3360
- true,
3361
- this.options.maxPayload
3362
- );
3363
- try {
3364
- const offers = extension.parse(secWebSocketExtensions);
3365
- if (offers[PerMessageDeflate.extensionName]) {
3366
- perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);
3367
- extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
3368
- }
3369
- } catch (err) {
3370
- const message = "Invalid or unacceptable Sec-WebSocket-Extensions header";
3371
- abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
3372
- return;
3373
- }
3374
- }
3375
- if (this.options.verifyClient) {
3376
- const info = {
3377
- origin: req.headers[`${version === 8 ? "sec-websocket-origin" : "origin"}`],
3378
- secure: !!(req.socket.authorized || req.socket.encrypted),
3379
- req
3380
- };
3381
- if (this.options.verifyClient.length === 2) {
3382
- this.options.verifyClient(info, (verified, code, message, headers) => {
3383
- if (!verified) {
3384
- return abortHandshake(socket, code || 401, message, headers);
3385
- }
3386
- this.completeUpgrade(
3387
- extensions,
3388
- key,
3389
- protocols,
3390
- req,
3391
- socket,
3392
- head,
3393
- cb
3394
- );
3395
- });
3396
- return;
3397
- }
3398
- if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);
3399
- }
3400
- this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
3401
- }
3402
- /**
3403
- * Upgrade the connection to WebSocket.
3404
- *
3405
- * @param {Object} extensions The accepted extensions
3406
- * @param {String} key The value of the `Sec-WebSocket-Key` header
3407
- * @param {Set} protocols The subprotocols
3408
- * @param {http.IncomingMessage} req The request object
3409
- * @param {Duplex} socket The network socket between the server and client
3410
- * @param {Buffer} head The first packet of the upgraded stream
3411
- * @param {Function} cb Callback
3412
- * @throws {Error} If called more than once with the same socket
3413
- * @private
3414
- */
3415
- completeUpgrade(extensions, key, protocols, req, socket, head, cb) {
3416
- if (!socket.readable || !socket.writable) return socket.destroy();
3417
- if (socket[kWebSocket]) {
3418
- throw new Error(
3419
- "server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration"
3420
- );
3421
- }
3422
- if (this._state > RUNNING) return abortHandshake(socket, 503);
3423
- const digest = createHash("sha1").update(key + GUID).digest("base64");
3424
- const headers = [
3425
- "HTTP/1.1 101 Switching Protocols",
3426
- "Upgrade: websocket",
3427
- "Connection: Upgrade",
3428
- `Sec-WebSocket-Accept: ${digest}`
3429
- ];
3430
- const ws = new this.options.WebSocket(null, void 0, this.options);
3431
- if (protocols.size) {
3432
- const protocol = this.options.handleProtocols ? this.options.handleProtocols(protocols, req) : protocols.values().next().value;
3433
- if (protocol) {
3434
- headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
3435
- ws._protocol = protocol;
3436
- }
3437
- }
3438
- if (extensions[PerMessageDeflate.extensionName]) {
3439
- const params = extensions[PerMessageDeflate.extensionName].params;
3440
- const value = extension.format({
3441
- [PerMessageDeflate.extensionName]: [params]
3442
- });
3443
- headers.push(`Sec-WebSocket-Extensions: ${value}`);
3444
- ws._extensions = extensions;
3445
- }
3446
- this.emit("headers", headers, req);
3447
- socket.write(headers.concat("\r\n").join("\r\n"));
3448
- socket.removeListener("error", socketOnError);
3449
- ws.setSocket(socket, head, {
3450
- allowSynchronousEvents: this.options.allowSynchronousEvents,
3451
- maxPayload: this.options.maxPayload,
3452
- skipUTF8Validation: this.options.skipUTF8Validation
3453
- });
3454
- if (this.clients) {
3455
- this.clients.add(ws);
3456
- ws.on("close", () => {
3457
- this.clients.delete(ws);
3458
- if (this._shouldEmitClose && !this.clients.size) {
3459
- process.nextTick(emitClose, this);
3460
- }
3461
- });
3462
- }
3463
- cb(ws, req);
3464
- }
3465
- };
3466
- module.exports = WebSocketServer2;
3467
- function addListeners(server, map) {
3468
- for (const event of Object.keys(map)) server.on(event, map[event]);
3469
- return function removeListeners() {
3470
- for (const event of Object.keys(map)) {
3471
- server.removeListener(event, map[event]);
3472
- }
3473
- };
3474
- }
3475
- function emitClose(server) {
3476
- server._state = CLOSED;
3477
- server.emit("close");
3478
- }
3479
- function socketOnError() {
3480
- this.destroy();
3481
- }
3482
- function abortHandshake(socket, code, message, headers) {
3483
- message = message || http2.STATUS_CODES[code];
3484
- headers = {
3485
- Connection: "close",
3486
- "Content-Type": "text/html",
3487
- "Content-Length": Buffer.byteLength(message),
3488
- ...headers
3489
- };
3490
- socket.once("finish", socket.destroy);
3491
- socket.end(
3492
- `HTTP/1.1 ${code} ${http2.STATUS_CODES[code]}\r
3493
- ` + Object.keys(headers).map((h) => `${h}: ${headers[h]}`).join("\r\n") + "\r\n\r\n" + message
3494
- );
3495
- }
3496
- function abortHandshakeOrEmitwsClientError(server, req, socket, code, message) {
3497
- if (server.listenerCount("wsClientError")) {
3498
- const err = new Error(message);
3499
- Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);
3500
- server.emit("wsClientError", err, socket, req);
3501
- } else {
3502
- abortHandshake(socket, code, message);
3503
- }
3504
- }
3505
- }
3506
- });
3507
-
3508
- // packages/cli/node_modules/ws/wrapper.mjs
3509
- var import_stream = __toESM(require_stream(), 1);
3510
- var import_receiver = __toESM(require_receiver(), 1);
3511
- var import_sender = __toESM(require_sender(), 1);
3512
- var import_websocket = __toESM(require_websocket(), 1);
3513
- var import_websocket_server = __toESM(require_websocket_server(), 1);
3514
- var wrapper_default = import_websocket.default;
3515
-
3516
- // packages/cli/src/utils/activityLogger.ts
3517
- import http from "node:http";
3518
- import https from "node:https";
3519
- import zlib from "node:zlib";
3520
- import fs from "node:fs";
3521
- import path from "node:path";
3522
- import { EventEmitter } from "node:events";
3523
- import { StringDecoder } from "node:string_decoder";
3524
- var ACTIVITY_ID_HEADER = "x-activity-request-id";
3525
- var MAX_BUFFER_SIZE = 100;
3526
- function isHeaderRecord(h) {
3527
- return !Array.isArray(h);
3528
- }
3529
- function isRequestOptions(value) {
3530
- return typeof value === "object" && value !== null && !(value instanceof URL) && !Array.isArray(value);
3531
- }
3532
- function isIncomingMessageCallback(value) {
3533
- return typeof value === "function";
3534
- }
3535
- function callHttpRequest(originalFn, args) {
3536
- if (args.length === 0) {
3537
- return originalFn({});
3538
- }
3539
- if (args.length === 1) {
3540
- const first = args[0];
3541
- if (typeof first === "string" || first instanceof URL) {
3542
- return originalFn(first);
3543
- }
3544
- if (isRequestOptions(first)) {
3545
- return originalFn(first);
3546
- }
3547
- return originalFn({});
3548
- }
3549
- if (args.length === 2) {
3550
- const first = args[0];
3551
- const second = args[1];
3552
- if (typeof first === "string" || first instanceof URL) {
3553
- if (isIncomingMessageCallback(second)) {
3554
- return originalFn(first, second);
3555
- }
3556
- if (isRequestOptions(second)) {
3557
- return originalFn(first, second);
3558
- }
3559
- }
3560
- if (isRequestOptions(first) && isIncomingMessageCallback(second)) {
3561
- return originalFn(first, second);
3562
- }
3563
- }
3564
- if (args.length === 3) {
3565
- const first = args[0];
3566
- const second = args[1];
3567
- const third = args[2];
3568
- if ((typeof first === "string" || first instanceof URL) && isRequestOptions(second) && isIncomingMessageCallback(third)) {
3569
- return originalFn(first, second, third);
3570
- }
3571
- }
3572
- return originalFn({});
3573
- }
3574
- var ActivityLogger = class _ActivityLogger extends EventEmitter {
3575
- static instance;
3576
- isInterceptionEnabled = false;
3577
- requestStartTimes = /* @__PURE__ */ new Map();
3578
- networkLoggingEnabled = false;
3579
- networkBufferMap = /* @__PURE__ */ new Map();
3580
- networkBufferIds = [];
3581
- consoleBuffer = [];
3582
- bufferLimit = 10;
3583
- static getInstance() {
3584
- if (!_ActivityLogger.instance) {
3585
- _ActivityLogger.instance = new _ActivityLogger();
3586
- }
3587
- return _ActivityLogger.instance;
3588
- }
3589
- enableNetworkLogging() {
3590
- this.networkLoggingEnabled = true;
3591
- this.emit("network-logging-enabled");
3592
- }
3593
- disableNetworkLogging() {
3594
- this.networkLoggingEnabled = false;
3595
- }
3596
- isNetworkLoggingEnabled() {
3597
- return this.networkLoggingEnabled;
3598
- }
3599
- /**
3600
- * Atomically returns and clears all buffered logs.
3601
- * Prevents data loss from events emitted between get and clear.
3602
- */
3603
- drainBufferedLogs() {
3604
- const network = [];
3605
- for (const id of this.networkBufferIds) {
3606
- const events = this.networkBufferMap.get(id);
3607
- if (events) network.push(...events);
3608
- }
3609
- const console = [...this.consoleBuffer];
3610
- this.networkBufferMap.clear();
3611
- this.networkBufferIds = [];
3612
- this.consoleBuffer = [];
3613
- return { network, console };
3614
- }
3615
- getBufferedLogs() {
3616
- const network = [];
3617
- for (const id of this.networkBufferIds) {
3618
- const events = this.networkBufferMap.get(id);
3619
- if (events) network.push(...events);
3620
- }
3621
- return {
3622
- network,
3623
- console: [...this.consoleBuffer]
3624
- };
3625
- }
3626
- clearBufferedLogs() {
3627
- this.networkBufferMap.clear();
3628
- this.networkBufferIds = [];
3629
- this.consoleBuffer = [];
3630
- }
3631
- stringifyHeaders(headers) {
3632
- const result = {};
3633
- if (!headers) return result;
3634
- if (headers instanceof Headers) {
3635
- headers.forEach((v, k) => {
3636
- result[k.toLowerCase()] = v;
3637
- });
3638
- } else if (typeof headers === "object" && headers !== null) {
3639
- for (const [key, val] of Object.entries(headers)) {
3640
- result[key.toLowerCase()] = Array.isArray(val) ? val.join(", ") : String(val);
3641
- }
3642
- }
3643
- return result;
3644
- }
3645
- sanitizeNetworkLog(log) {
3646
- if (!log || typeof log !== "object") return log;
3647
- const sanitized = { ...log };
3648
- if ("headers" in sanitized && sanitized.headers) {
3649
- const headers = { ...sanitized.headers };
3650
- for (const key of Object.keys(headers)) {
3651
- if (["authorization", "cookie", "x-goog-api-key"].includes(
3652
- key.toLowerCase()
3653
- )) {
3654
- headers[key] = "[REDACTED]";
3655
- }
3656
- }
3657
- sanitized.headers = headers;
3658
- }
3659
- if ("response" in sanitized && sanitized.response?.headers) {
3660
- const resHeaders = { ...sanitized.response.headers };
3661
- for (const key of Object.keys(resHeaders)) {
3662
- if (["set-cookie"].includes(key.toLowerCase())) {
3663
- resHeaders[key] = "[REDACTED]";
3664
- }
3665
- }
3666
- sanitized.response = { ...sanitized.response, headers: resHeaders };
3667
- }
3668
- return sanitized;
3669
- }
3670
- /** @internal Emit a network event — public for testing only. */
3671
- emitNetworkEvent(payload) {
3672
- this.safeEmitNetwork(payload);
3673
- }
3674
- safeEmitNetwork(payload) {
3675
- const sanitized = this.sanitizeNetworkLog(payload);
3676
- const id = sanitized.id;
3677
- if (!this.networkBufferMap.has(id)) {
3678
- this.networkBufferIds.push(id);
3679
- this.networkBufferMap.set(id, []);
3680
- if (this.networkBufferIds.length > this.bufferLimit) {
3681
- const evictId = this.networkBufferIds.shift();
3682
- this.networkBufferMap.delete(evictId);
3683
- }
3684
- }
3685
- this.networkBufferMap.get(id).push(sanitized);
3686
- this.emit("network", sanitized);
3687
- }
3688
- enable() {
3689
- if (this.isInterceptionEnabled) return;
3690
- this.isInterceptionEnabled = true;
3691
- this.patchGlobalFetch();
3692
- this.patchNodeHttp();
3693
- }
3694
- patchGlobalFetch() {
3695
- if (!global.fetch) return;
3696
- const originalFetch = global.fetch;
3697
- global.fetch = async (input, init) => {
3698
- const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
3699
- if (url.includes("127.0.0.1") || url.includes("localhost"))
3700
- return originalFetch(input, init);
3701
- const id = Math.random().toString(36).substring(7);
3702
- const inputMethod = typeof input === "object" && "method" in input ? input.method : void 0;
3703
- const inputHeaders = typeof input === "object" && "headers" in input ? input.headers : void 0;
3704
- const method = (init?.method ?? inputMethod ?? "GET").toUpperCase();
3705
- const headers = new Headers(init?.headers ?? inputHeaders ?? {});
3706
- headers.set(ACTIVITY_ID_HEADER, id);
3707
- const newInit = {
3708
- ...init,
3709
- method,
3710
- headers
3711
- };
3712
- let reqBody = "";
3713
- const body = newInit.body;
3714
- if (body) {
3715
- if (typeof body === "string") reqBody = body;
3716
- else if (body instanceof URLSearchParams) reqBody = body.toString();
3717
- }
3718
- this.requestStartTimes.set(id, Date.now());
3719
- this.safeEmitNetwork({
3720
- id,
3721
- timestamp: Date.now(),
3722
- method,
3723
- url,
3724
- headers: this.stringifyHeaders(newInit.headers),
3725
- body: reqBody,
3726
- pending: true
3727
- });
3728
- try {
3729
- const response = await originalFetch(input, newInit);
3730
- const clonedRes = response.clone();
3731
- if (clonedRes.body) {
3732
- const reader = clonedRes.body.getReader();
3733
- const decoder = new TextDecoder();
3734
- const chunks = [];
3735
- let chunkIndex = 0;
3736
- const readStream = async () => {
3737
- try {
3738
- while (true) {
3739
- const { done, value } = await reader.read();
3740
- if (done) break;
3741
- const chunkData = decoder.decode(value, { stream: true });
3742
- chunks.push(chunkData);
3743
- this.safeEmitNetwork({
3744
- id,
3745
- pending: true,
3746
- chunk: {
3747
- index: chunkIndex++,
3748
- data: chunkData,
3749
- timestamp: Date.now()
3750
- }
3751
- });
3752
- }
3753
- const startTime = this.requestStartTimes.get(id);
3754
- const durationMs = startTime ? Date.now() - startTime : 0;
3755
- this.requestStartTimes.delete(id);
3756
- this.safeEmitNetwork({
3757
- id,
3758
- pending: false,
3759
- response: {
3760
- status: response.status,
3761
- headers: this.stringifyHeaders(response.headers),
3762
- body: chunks.join(""),
3763
- durationMs
3764
- }
3765
- });
3766
- } catch (err) {
3767
- const message = err instanceof Error ? err.message : String(err);
3768
- this.safeEmitNetwork({
3769
- id,
3770
- pending: false,
3771
- error: `Failed to read response body: ${message}`
3772
- });
3773
- }
3774
- };
3775
- void readStream();
3776
- } else {
3777
- clonedRes.text().then((text) => {
3778
- const startTime = this.requestStartTimes.get(id);
3779
- const durationMs = startTime ? Date.now() - startTime : 0;
3780
- this.requestStartTimes.delete(id);
3781
- this.safeEmitNetwork({
3782
- id,
3783
- pending: false,
3784
- response: {
3785
- status: response.status,
3786
- headers: this.stringifyHeaders(response.headers),
3787
- body: text,
3788
- durationMs
3789
- }
3790
- });
3791
- }).catch((err) => {
3792
- const message = err instanceof Error ? err.message : String(err);
3793
- this.safeEmitNetwork({
3794
- id,
3795
- pending: false,
3796
- error: `Failed to read response body: ${message}`
3797
- });
3798
- });
3799
- }
3800
- return response;
3801
- } catch (err) {
3802
- this.requestStartTimes.delete(id);
3803
- const message = err instanceof Error ? err.message : String(err);
3804
- this.safeEmitNetwork({ id, pending: false, error: message });
3805
- throw err;
3806
- }
3807
- };
3808
- }
3809
- patchNodeHttp() {
3810
- const self = this;
3811
- const originalRequest = http.request;
3812
- const originalHttpsRequest = https.request;
3813
- const wrapRequest = (originalFn, args, protocol) => {
3814
- const firstArg = args[0];
3815
- let options;
3816
- if (typeof firstArg === "string") {
3817
- options = firstArg;
3818
- } else if (firstArg instanceof URL) {
3819
- options = firstArg;
3820
- } else if (firstArg && typeof firstArg === "object") {
3821
- options = isRequestOptions(firstArg) ? firstArg : {};
3822
- } else {
3823
- options = {};
3824
- }
3825
- let url = "";
3826
- if (typeof options === "string") {
3827
- url = options;
3828
- } else if (options instanceof URL) {
3829
- url = options.href;
3830
- } else {
3831
- const href = "href" in options && typeof options.href === "string" ? options.href : "";
3832
- url = href || `${protocol}//${options.hostname || options.host || "localhost"}${options.path || "/"}`;
3833
- }
3834
- if (url.includes("127.0.0.1") || url.includes("localhost")) {
3835
- return callHttpRequest(originalFn, args);
3836
- }
3837
- const rawHeaders = typeof options === "object" && options !== null && !(options instanceof URL) ? options.headers : void 0;
3838
- let headers = {};
3839
- if (rawHeaders && isHeaderRecord(rawHeaders)) {
3840
- headers = rawHeaders;
3841
- }
3842
- if (headers[ACTIVITY_ID_HEADER]) {
3843
- delete headers[ACTIVITY_ID_HEADER];
3844
- return callHttpRequest(originalFn, args);
3845
- }
3846
- const id = Math.random().toString(36).substring(7);
3847
- this.requestStartTimes.set(id, Date.now());
3848
- const req = callHttpRequest(originalFn, args);
3849
- const requestChunks = [];
3850
- const oldWrite = req.write;
3851
- const oldEnd = req.end;
3852
- req.write = function(chunk, ...etc) {
3853
- if (chunk) {
3854
- const arg0 = etc[0];
3855
- const encoding = typeof arg0 === "string" && Buffer.isEncoding(arg0) ? arg0 : void 0;
3856
- requestChunks.push(
3857
- Buffer.isBuffer(chunk) ? chunk : typeof chunk === "string" ? Buffer.from(chunk, encoding) : Buffer.from(
3858
- chunk instanceof Uint8Array ? chunk : String(chunk)
3859
- )
3860
- );
3861
- }
3862
- return oldWrite.apply(this, [chunk, ...etc]);
3863
- };
3864
- req.end = function(chunkOrCb, ...etc) {
3865
- const chunk = typeof chunkOrCb === "function" ? void 0 : chunkOrCb;
3866
- if (chunk) {
3867
- const arg0 = etc[0];
3868
- const encoding = typeof arg0 === "string" && Buffer.isEncoding(arg0) ? arg0 : void 0;
3869
- requestChunks.push(
3870
- Buffer.isBuffer(chunk) ? chunk : typeof chunk === "string" ? Buffer.from(chunk, encoding) : Buffer.from(
3871
- chunk instanceof Uint8Array ? chunk : String(chunk)
3872
- )
3873
- );
3874
- }
3875
- const body = Buffer.concat(requestChunks).toString("utf8");
3876
- self.safeEmitNetwork({
3877
- id,
3878
- timestamp: Date.now(),
3879
- method: req.method || "GET",
3880
- url,
3881
- headers: self.stringifyHeaders(req.getHeaders()),
3882
- body,
3883
- pending: true
3884
- });
3885
- return oldEnd.apply(this, [chunkOrCb, ...etc]);
3886
- };
3887
- req.on("response", (res) => {
3888
- const responseChunks = [];
3889
- const decompressedChunks = [];
3890
- const decoder = new StringDecoder("utf8");
3891
- let chunkIndex = 0;
3892
- const emitChunk = (chunkData) => {
3893
- if (!chunkData) return;
3894
- self.safeEmitNetwork({
3895
- id,
3896
- pending: true,
3897
- chunk: {
3898
- index: chunkIndex++,
3899
- data: chunkData,
3900
- timestamp: Date.now()
3901
- }
3902
- });
3903
- };
3904
- let responseEmitted = false;
3905
- const processBuffer = (finalBuffer) => {
3906
- if (responseEmitted) return;
3907
- responseEmitted = true;
3908
- const resBody = finalBuffer.toString("utf8");
3909
- const startTime = self.requestStartTimes.get(id);
3910
- const durationMs = startTime ? Date.now() - startTime : 0;
3911
- self.requestStartTimes.delete(id);
3912
- self.safeEmitNetwork({
3913
- id,
3914
- pending: false,
3915
- response: {
3916
- status: res.statusCode || 0,
3917
- headers: self.stringifyHeaders(res.headers),
3918
- body: resBody,
3919
- durationMs
3920
- }
3921
- });
3922
- };
3923
- const rawEncoding = res.headers["content-encoding"];
3924
- const encoding = typeof rawEncoding === "string" ? rawEncoding.toLowerCase().trim() : "";
3925
- let decompressor = null;
3926
- if (encoding === "gzip" || encoding === "x-gzip") {
3927
- decompressor = zlib.createGunzip({
3928
- flush: zlib.constants.Z_SYNC_FLUSH
3929
- });
3930
- } else if (encoding === "deflate") {
3931
- decompressor = zlib.createInflate({
3932
- flush: zlib.constants.Z_SYNC_FLUSH
3933
- });
3934
- }
3935
- let decompressionFailed = false;
3936
- let responseEnded = false;
3937
- if (decompressor) {
3938
- decompressor.on("data", (decompressedChunk) => {
3939
- if (decompressionFailed || responseEmitted) return;
3940
- decompressedChunks.push(decompressedChunk);
3941
- emitChunk(decoder.write(decompressedChunk));
3942
- });
3943
- decompressor.on("end", () => {
3944
- if (decompressionFailed || responseEmitted) return;
3945
- emitChunk(decoder.end());
3946
- processBuffer(Buffer.concat(decompressedChunks));
3947
- });
3948
- decompressor.on("error", () => {
3949
- decompressionFailed = true;
3950
- if (responseEnded) {
3951
- processBuffer(Buffer.concat(responseChunks));
3952
- }
3953
- });
3954
- decompressor.on("close", () => {
3955
- if (responseEnded && !responseEmitted) {
3956
- processBuffer(Buffer.concat(responseChunks));
3957
- }
3958
- });
3959
- }
3960
- res.on("data", (chunk) => {
3961
- const chunkBuffer = Buffer.from(chunk);
3962
- responseChunks.push(chunkBuffer);
3963
- if (decompressor) {
3964
- if (!decompressionFailed && !decompressor.destroyed && !decompressor.writableEnded) {
3965
- try {
3966
- decompressor.write(chunkBuffer);
3967
- } catch {
3968
- decompressionFailed = true;
3969
- if (responseEnded) {
3970
- processBuffer(Buffer.concat(responseChunks));
3971
- }
3972
- }
3973
- }
3974
- } else {
3975
- emitChunk(decoder.write(chunkBuffer));
3976
- }
3977
- });
3978
- res.on("end", () => {
3979
- responseEnded = true;
3980
- if (decompressor) {
3981
- if (decompressionFailed || decompressor.destroyed || decompressor.writableEnded) {
3982
- processBuffer(Buffer.concat(responseChunks));
3983
- } else {
3984
- try {
3985
- decompressor.end();
3986
- } catch {
3987
- decompressionFailed = true;
3988
- processBuffer(Buffer.concat(responseChunks));
3989
- }
3990
- }
3991
- } else {
3992
- emitChunk(decoder.end());
3993
- processBuffer(Buffer.concat(responseChunks));
3994
- }
3995
- });
3996
- });
3997
- req.on("error", (err) => {
3998
- self.requestStartTimes.delete(id);
3999
- const message = err.message;
4000
- self.safeEmitNetwork({
4001
- id,
4002
- pending: false,
4003
- error: message
4004
- });
4005
- });
4006
- return req;
4007
- };
4008
- Object.defineProperty(http, "request", {
4009
- value: (url, options, callback) => {
4010
- const args = callback !== void 0 ? [url, options, callback] : options !== void 0 ? [url, options] : [url];
4011
- return wrapRequest(originalRequest, args, "http:");
4012
- },
4013
- writable: true,
4014
- configurable: true
4015
- });
4016
- Object.defineProperty(https, "request", {
4017
- value: (url, options, callback) => {
4018
- const args = callback !== void 0 ? [url, options, callback] : options !== void 0 ? [url, options] : [url];
4019
- return wrapRequest(
4020
- originalHttpsRequest,
4021
- args,
4022
- "https:"
4023
- );
4024
- },
4025
- writable: true,
4026
- configurable: true
4027
- });
4028
- }
4029
- logConsole(payload) {
4030
- const enriched = { ...payload, timestamp: Date.now() };
4031
- this.consoleBuffer.push(enriched);
4032
- if (this.consoleBuffer.length > this.bufferLimit) {
4033
- this.consoleBuffer.shift();
4034
- }
4035
- this.emit("console", enriched);
4036
- }
4037
- };
4038
- function setupFileLogging(capture, config, customPath) {
4039
- const logFile = customPath || (config.storage ? path.join(
4040
- config.storage.getProjectTempLogsDir(),
4041
- `session-${config.getSessionId()}.jsonl`
4042
- ) : null);
4043
- if (!logFile) return;
4044
- const logsDir = path.dirname(logFile);
4045
- if (!fs.existsSync(logsDir)) {
4046
- fs.mkdirSync(logsDir, { recursive: true });
4047
- }
4048
- const writeToLog = (type, payload) => {
4049
- try {
4050
- const entry = JSON.stringify({
4051
- type,
4052
- payload,
4053
- sessionId: config.getSessionId(),
4054
- timestamp: Date.now()
4055
- }) + "\n";
4056
- fs.promises.appendFile(logFile, entry).catch((err) => {
4057
- debugLogger.error("Failed to write to activity log:", err);
4058
- });
4059
- } catch (err) {
4060
- debugLogger.error("Failed to prepare activity log entry:", err);
4061
- }
4062
- };
4063
- capture.on("console", (payload) => writeToLog("console", payload));
4064
- capture.on("network", (payload) => writeToLog("network", payload));
4065
- }
4066
- function setupNetworkLogging(capture, host, port, config, onReconnectFailed) {
4067
- const transportBuffer = [];
4068
- let ws = null;
4069
- let reconnectTimer = null;
4070
- let sessionId = null;
4071
- let pingInterval = null;
4072
- let reconnectAttempts = 0;
4073
- const MAX_RECONNECT_ATTEMPTS = 2;
4074
- const connect = () => {
4075
- try {
4076
- ws = new wrapper_default(`ws://${host}:${port}/ws`);
4077
- ws.on("open", () => {
4078
- debugLogger.debug(`WebSocket connected to ${host}:${port}`);
4079
- reconnectAttempts = 0;
4080
- sendMessage({
4081
- type: "register",
4082
- sessionId: config.getSessionId(),
4083
- timestamp: Date.now()
4084
- });
4085
- });
4086
- ws.on("message", (data) => {
4087
- try {
4088
- const parsed = JSON.parse(data.toString());
4089
- if (typeof parsed === "object" && parsed !== null && "type" in parsed && typeof parsed.type === "string") {
4090
- handleServerMessage({
4091
- type: parsed.type,
4092
- sessionId: "sessionId" in parsed && typeof parsed.sessionId === "string" ? parsed.sessionId : void 0
4093
- });
4094
- }
4095
- } catch (err) {
4096
- debugLogger.debug("Invalid WebSocket message:", err);
4097
- }
4098
- });
4099
- ws.on("close", () => {
4100
- debugLogger.debug(`WebSocket disconnected from ${host}:${port}`);
4101
- cleanup();
4102
- scheduleReconnect();
4103
- });
4104
- ws.on("error", (err) => {
4105
- debugLogger.debug(`WebSocket error:`, err);
4106
- });
4107
- } catch (err) {
4108
- debugLogger.debug(`Failed to connect WebSocket:`, err);
4109
- scheduleReconnect();
4110
- }
4111
- };
4112
- const handleServerMessage = (message) => {
4113
- switch (message.type) {
4114
- case "registered":
4115
- sessionId = message.sessionId || null;
4116
- debugLogger.debug(`WebSocket session registered: ${sessionId}`);
4117
- if (pingInterval) clearInterval(pingInterval);
4118
- pingInterval = setInterval(() => {
4119
- sendMessage({ type: "pong", timestamp: Date.now() });
4120
- }, 15e3);
4121
- flushBuffer();
4122
- break;
4123
- case "trigger-debugger": {
4124
- import("node:inspector").then((inspector) => {
4125
- inspector.open();
4126
- debugLogger.log(
4127
- "Node debugger attached. Open chrome://inspect in Chrome to start debugging."
4128
- );
4129
- return import("./events-XB7DADIJ.js");
4130
- }).then(({ appEvents, AppEvent, TransientMessageType }) => {
4131
- appEvents.emit(AppEvent.TransientMessage, {
4132
- message: "Debugger attached from DevTools.",
4133
- type: TransientMessageType.Hint
4134
- });
4135
- }).catch(
4136
- (err) => debugLogger.debug("Failed to trigger debugger:", err)
4137
- );
4138
- break;
4139
- }
4140
- case "ping":
4141
- sendMessage({ type: "pong", timestamp: Date.now() });
4142
- break;
4143
- default:
4144
- break;
4145
- }
4146
- };
4147
- const sendMessage = (message) => {
4148
- if (ws && ws.readyState === wrapper_default.OPEN) {
4149
- ws.send(JSON.stringify(message));
4150
- }
4151
- };
4152
- const sendToNetwork = (type, payload) => {
4153
- const message = {
4154
- type,
4155
- payload,
4156
- sessionId: sessionId || config.getSessionId(),
4157
- timestamp: Date.now()
4158
- };
4159
- if (!ws || ws.readyState !== wrapper_default.OPEN || !capture.isNetworkLoggingEnabled()) {
4160
- transportBuffer.push(message);
4161
- if (transportBuffer.length > MAX_BUFFER_SIZE) transportBuffer.shift();
4162
- return;
4163
- }
4164
- sendMessage(message);
4165
- };
4166
- const flushBuffer = () => {
4167
- if (!ws || ws.readyState !== wrapper_default.OPEN || !capture.isNetworkLoggingEnabled()) {
4168
- return;
4169
- }
4170
- const { network, console: consoleLogs } = capture.drainBufferedLogs();
4171
- const allInitialLogs = [
4172
- ...network.map((l) => ({
4173
- type: "network",
4174
- payload: l,
4175
- timestamp: "timestamp" in l && l.timestamp ? l.timestamp : Date.now()
4176
- })),
4177
- ...consoleLogs.map((l) => ({
4178
- type: "console",
4179
- payload: l,
4180
- timestamp: l.timestamp
4181
- }))
4182
- ].sort((a, b) => a.timestamp - b.timestamp);
4183
- debugLogger.debug(
4184
- `Flushing ${allInitialLogs.length} initial buffered logs and ${transportBuffer.length} transport buffered logs...`
4185
- );
4186
- for (const log of allInitialLogs) {
4187
- sendMessage({
4188
- type: log.type,
4189
- payload: log.payload,
4190
- sessionId: sessionId || config.getSessionId(),
4191
- timestamp: Date.now()
4192
- });
4193
- }
4194
- while (transportBuffer.length > 0) {
4195
- const message = transportBuffer.shift();
4196
- sendMessage(message);
4197
- }
4198
- };
4199
- const cleanup = () => {
4200
- if (pingInterval) {
4201
- clearInterval(pingInterval);
4202
- pingInterval = null;
4203
- }
4204
- ws = null;
4205
- };
4206
- const scheduleReconnect = () => {
4207
- if (reconnectTimer) return;
4208
- reconnectAttempts++;
4209
- if (reconnectAttempts > MAX_RECONNECT_ATTEMPTS && onReconnectFailed) {
4210
- debugLogger.debug(
4211
- `WebSocket reconnect failed after ${MAX_RECONNECT_ATTEMPTS} attempts, promoting to server...`
4212
- );
4213
- onReconnectFailed();
4214
- return;
4215
- }
4216
- reconnectTimer = setTimeout(() => {
4217
- reconnectTimer = null;
4218
- debugLogger.debug("Reconnecting WebSocket...");
4219
- connect();
4220
- }, 1e3);
4221
- };
4222
- connect();
4223
- capture.on("console", (payload) => sendToNetwork("console", payload));
4224
- capture.on("network", (payload) => sendToNetwork("network", payload));
4225
- capture.on("network-logging-enabled", () => {
4226
- debugLogger.debug("Network logging enabled, flushing buffer...");
4227
- flushBuffer();
4228
- });
4229
- process.on("exit", () => {
4230
- if (reconnectTimer) clearTimeout(reconnectTimer);
4231
- if (ws) ws.close();
4232
- cleanup();
4233
- });
4234
- }
4235
- var bridgeAttached = false;
4236
- function bridgeCoreEvents(capture) {
4237
- if (bridgeAttached) return;
4238
- bridgeAttached = true;
4239
- coreEvents.on("console-log" /* ConsoleLog */, (payload) => {
4240
- capture.logConsole(payload);
4241
- });
4242
- }
4243
- function initActivityLogger(config, options) {
4244
- const capture = ActivityLogger.getInstance();
4245
- capture.enable();
4246
- if (options.mode === "network") {
4247
- setupNetworkLogging(
4248
- capture,
4249
- options.host,
4250
- options.port,
4251
- config,
4252
- options.onReconnectFailed
4253
- );
4254
- capture.enableNetworkLogging();
4255
- } else if (options.mode === "file") {
4256
- setupFileLogging(capture, config, options.filePath);
4257
- }
4258
- bridgeCoreEvents(capture);
4259
- }
4260
- function addNetworkTransport(config, host, port, onReconnectFailed) {
4261
- const capture = ActivityLogger.getInstance();
4262
- setupNetworkLogging(capture, host, port, config, onReconnectFailed);
4263
- }
4264
-
4265
- // packages/cli/src/utils/devtoolsService.ts
4266
- var DEFAULT_DEVTOOLS_PORT = 25417;
4267
- var DEFAULT_DEVTOOLS_HOST = "127.0.0.1";
4268
- var MAX_PROMOTION_ATTEMPTS = 3;
4269
- var promotionAttempts = 0;
4270
- var serverStartPromise = null;
4271
- var connectedUrl = null;
4272
- function probeDevTools(host, port) {
4273
- return new Promise((resolve) => {
4274
- const ws = new wrapper_default(`ws://${host}:${port}/ws`);
4275
- const timer = setTimeout(() => {
4276
- ws.close();
4277
- resolve(false);
4278
- }, 500);
4279
- ws.on("open", () => {
4280
- clearTimeout(timer);
4281
- ws.close();
4282
- resolve(true);
4283
- });
4284
- ws.on("error", () => {
4285
- clearTimeout(timer);
4286
- ws.close();
4287
- resolve(false);
4288
- });
4289
- });
4290
- }
4291
- async function startOrJoinDevTools(defaultHost, defaultPort) {
4292
- const mod = await import("./src-XZYPU6PJ.js");
4293
- const devtools = mod.DevTools.getInstance();
4294
- const url = await devtools.start();
4295
- const actualPort = devtools.getPort();
4296
- if (actualPort === defaultPort) {
4297
- debugLogger.log(`DevTools available at: ${url}`);
4298
- return { host: defaultHost, port: actualPort };
4299
- }
4300
- const winnerAlive = await probeDevTools(defaultHost, defaultPort);
4301
- if (winnerAlive) {
4302
- await devtools.stop();
4303
- debugLogger.log(
4304
- `DevTools (existing) at: http://${defaultHost}:${defaultPort}`
4305
- );
4306
- return { host: defaultHost, port: defaultPort };
4307
- }
4308
- debugLogger.log(`DevTools available at: ${url}`);
4309
- return { host: defaultHost, port: actualPort };
4310
- }
4311
- async function handlePromotion(config) {
4312
- promotionAttempts++;
4313
- if (promotionAttempts > MAX_PROMOTION_ATTEMPTS) {
4314
- debugLogger.debug(
4315
- `Giving up on DevTools promotion after ${MAX_PROMOTION_ATTEMPTS} attempts`
4316
- );
4317
- return;
4318
- }
4319
- try {
4320
- const result = await startOrJoinDevTools(
4321
- DEFAULT_DEVTOOLS_HOST,
4322
- DEFAULT_DEVTOOLS_PORT
4323
- );
4324
- addNetworkTransport(
4325
- config,
4326
- result.host,
4327
- result.port,
4328
- () => handlePromotion(config)
4329
- );
4330
- } catch (err) {
4331
- debugLogger.debug("Failed to promote to DevTools server:", err);
4332
- }
4333
- }
4334
- function setupInitialActivityLogger(config) {
4335
- const target = process.env["GEMINI_CLI_ACTIVITY_LOG_TARGET"];
4336
- if (target) {
4337
- if (!config.storage) return;
4338
- initActivityLogger(config, { mode: "file", filePath: target });
4339
- } else {
4340
- initActivityLogger(config, { mode: "buffer" });
4341
- }
4342
- }
4343
- function startDevToolsServer(config) {
4344
- if (connectedUrl) return Promise.resolve(connectedUrl);
4345
- if (serverStartPromise) return serverStartPromise;
4346
- serverStartPromise = startDevToolsServerImpl(config).catch((err) => {
4347
- serverStartPromise = null;
4348
- throw err;
4349
- });
4350
- return serverStartPromise;
4351
- }
4352
- async function startDevToolsServerImpl(config) {
4353
- const onReconnectFailed = () => handlePromotion(config);
4354
- const existing = await probeDevTools(
4355
- DEFAULT_DEVTOOLS_HOST,
4356
- DEFAULT_DEVTOOLS_PORT
4357
- );
4358
- let host = DEFAULT_DEVTOOLS_HOST;
4359
- let port = DEFAULT_DEVTOOLS_PORT;
4360
- if (existing) {
4361
- debugLogger.log(
4362
- `DevTools (existing) at: http://${DEFAULT_DEVTOOLS_HOST}:${DEFAULT_DEVTOOLS_PORT}`
4363
- );
4364
- } else {
4365
- try {
4366
- const result = await startOrJoinDevTools(
4367
- DEFAULT_DEVTOOLS_HOST,
4368
- DEFAULT_DEVTOOLS_PORT
4369
- );
4370
- host = result.host;
4371
- port = result.port;
4372
- } catch (err) {
4373
- debugLogger.debug("Failed to start DevTools:", err);
4374
- throw err;
4375
- }
4376
- }
4377
- addNetworkTransport(config, host, port, onReconnectFailed);
4378
- const capture = ActivityLogger.getInstance();
4379
- capture.enableNetworkLogging();
4380
- const url = `http://localhost:${port}`;
4381
- connectedUrl = url;
4382
- return url;
4383
- }
4384
- async function toggleDevToolsPanel(config, isOpen, toggle, setOpen) {
4385
- if (isOpen) {
4386
- toggle();
4387
- return;
4388
- }
4389
- try {
4390
- const { openBrowserSecurely, shouldLaunchBrowser } = await import("./core-3UXW77KZ.js");
4391
- const url = await startDevToolsServer(config);
4392
- if (shouldLaunchBrowser()) {
4393
- try {
4394
- await openBrowserSecurely(url);
4395
- return;
4396
- } catch (e) {
4397
- debugLogger.warn("Failed to open browser securely:", e);
4398
- }
4399
- }
4400
- setOpen();
4401
- } catch (e) {
4402
- setOpen();
4403
- debugLogger.error("Failed to start DevTools server:", e);
4404
- }
4405
- }
4406
- function resetForTesting() {
4407
- promotionAttempts = 0;
4408
- serverStartPromise = null;
4409
- connectedUrl = null;
4410
- }
4411
- export {
4412
- resetForTesting,
4413
- setupInitialActivityLogger,
4414
- startDevToolsServer,
4415
- toggleDevToolsPanel
4416
- };
4417
- /**
4418
- * @license
4419
- * Copyright 2025 Google LLC
4420
- * SPDX-License-Identifier: Apache-2.0
4421
- */