@anthropic-ai/claude-code 1.0.85 → 1.0.87

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/sdk.mjs CHANGED
@@ -2,17 +2,3537 @@
2
2
 
3
3
  // (c) Anthropic PBC. All rights reserved. Use is subject to Anthropic's Commercial Terms of Service (https://www.anthropic.com/legal/commercial-terms).
4
4
 
5
- // Version: 1.0.85
5
+ // Version: 1.0.87
6
6
 
7
7
  // Want to see the unminified source? We're hiring!
8
8
  // https://job-boards.greenhouse.io/anthropic/jobs/4816199008
9
9
 
10
+ import { createRequire } from "node:module";
11
+ var __create = Object.create;
12
+ var __getProtoOf = Object.getPrototypeOf;
13
+ var __defProp = Object.defineProperty;
14
+ var __getOwnPropNames = Object.getOwnPropertyNames;
15
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
16
+ var __toESM = (mod, isNodeMode, target) => {
17
+ target = mod != null ? __create(__getProtoOf(mod)) : {};
18
+ const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
19
+ for (let key of __getOwnPropNames(mod))
20
+ if (!__hasOwnProp.call(to, key))
21
+ __defProp(to, key, {
22
+ get: () => mod[key],
23
+ enumerable: true
24
+ });
25
+ return to;
26
+ };
27
+ var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
28
+ var __require = /* @__PURE__ */ createRequire(import.meta.url);
29
+
30
+ // node_modules/ws/lib/constants.js
31
+ var require_constants = __commonJS((exports, module) => {
32
+ var BINARY_TYPES = ["nodebuffer", "arraybuffer", "fragments"];
33
+ var hasBlob = typeof Blob !== "undefined";
34
+ if (hasBlob)
35
+ BINARY_TYPES.push("blob");
36
+ module.exports = {
37
+ BINARY_TYPES,
38
+ EMPTY_BUFFER: Buffer.alloc(0),
39
+ GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
40
+ hasBlob,
41
+ kForOnEventAttribute: Symbol("kIsForOnEventAttribute"),
42
+ kListener: Symbol("kListener"),
43
+ kStatusCode: Symbol("status-code"),
44
+ kWebSocket: Symbol("websocket"),
45
+ NOOP: () => {}
46
+ };
47
+ });
48
+
49
+ // node_modules/ws/lib/buffer-util.js
50
+ var require_buffer_util = __commonJS((exports, module) => {
51
+ var { EMPTY_BUFFER } = require_constants();
52
+ var FastBuffer = Buffer[Symbol.species];
53
+ function concat(list, totalLength) {
54
+ if (list.length === 0)
55
+ return EMPTY_BUFFER;
56
+ if (list.length === 1)
57
+ return list[0];
58
+ const target = Buffer.allocUnsafe(totalLength);
59
+ let offset = 0;
60
+ for (let i = 0;i < list.length; i++) {
61
+ const buf = list[i];
62
+ target.set(buf, offset);
63
+ offset += buf.length;
64
+ }
65
+ if (offset < totalLength) {
66
+ return new FastBuffer(target.buffer, target.byteOffset, offset);
67
+ }
68
+ return target;
69
+ }
70
+ function _mask(source, mask, output, offset, length) {
71
+ for (let i = 0;i < length; i++) {
72
+ output[offset + i] = source[i] ^ mask[i & 3];
73
+ }
74
+ }
75
+ function _unmask(buffer, mask) {
76
+ for (let i = 0;i < buffer.length; i++) {
77
+ buffer[i] ^= mask[i & 3];
78
+ }
79
+ }
80
+ function toArrayBuffer(buf) {
81
+ if (buf.length === buf.buffer.byteLength) {
82
+ return buf.buffer;
83
+ }
84
+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);
85
+ }
86
+ function toBuffer(data) {
87
+ toBuffer.readOnly = true;
88
+ if (Buffer.isBuffer(data))
89
+ return data;
90
+ let buf;
91
+ if (data instanceof ArrayBuffer) {
92
+ buf = new FastBuffer(data);
93
+ } else if (ArrayBuffer.isView(data)) {
94
+ buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);
95
+ } else {
96
+ buf = Buffer.from(data);
97
+ toBuffer.readOnly = false;
98
+ }
99
+ return buf;
100
+ }
101
+ module.exports = {
102
+ concat,
103
+ mask: _mask,
104
+ toArrayBuffer,
105
+ toBuffer,
106
+ unmask: _unmask
107
+ };
108
+ if (!process.env.WS_NO_BUFFER_UTIL) {
109
+ try {
110
+ const bufferUtil = (()=>{throw new Error("Cannot require module "+"bufferutil");})();
111
+ module.exports.mask = function(source, mask, output, offset, length) {
112
+ if (length < 48)
113
+ _mask(source, mask, output, offset, length);
114
+ else
115
+ bufferUtil.mask(source, mask, output, offset, length);
116
+ };
117
+ module.exports.unmask = function(buffer, mask) {
118
+ if (buffer.length < 32)
119
+ _unmask(buffer, mask);
120
+ else
121
+ bufferUtil.unmask(buffer, mask);
122
+ };
123
+ } catch (e) {}
124
+ }
125
+ });
126
+
127
+ // node_modules/ws/lib/limiter.js
128
+ var require_limiter = __commonJS((exports, module) => {
129
+ var kDone = Symbol("kDone");
130
+ var kRun = Symbol("kRun");
131
+
132
+ class Limiter {
133
+ constructor(concurrency) {
134
+ this[kDone] = () => {
135
+ this.pending--;
136
+ this[kRun]();
137
+ };
138
+ this.concurrency = concurrency || Infinity;
139
+ this.jobs = [];
140
+ this.pending = 0;
141
+ }
142
+ add(job) {
143
+ this.jobs.push(job);
144
+ this[kRun]();
145
+ }
146
+ [kRun]() {
147
+ if (this.pending === this.concurrency)
148
+ return;
149
+ if (this.jobs.length) {
150
+ const job = this.jobs.shift();
151
+ this.pending++;
152
+ job(this[kDone]);
153
+ }
154
+ }
155
+ }
156
+ module.exports = Limiter;
157
+ });
158
+
159
+ // node_modules/ws/lib/permessage-deflate.js
160
+ var require_permessage_deflate = __commonJS((exports, module) => {
161
+ var zlib = __require("zlib");
162
+ var bufferUtil = require_buffer_util();
163
+ var Limiter = require_limiter();
164
+ var { kStatusCode } = require_constants();
165
+ var FastBuffer = Buffer[Symbol.species];
166
+ var TRAILER = Buffer.from([0, 0, 255, 255]);
167
+ var kPerMessageDeflate = Symbol("permessage-deflate");
168
+ var kTotalLength = Symbol("total-length");
169
+ var kCallback = Symbol("callback");
170
+ var kBuffers = Symbol("buffers");
171
+ var kError = Symbol("error");
172
+ var zlibLimiter;
173
+
174
+ class PerMessageDeflate {
175
+ constructor(options, isServer, maxPayload) {
176
+ this._maxPayload = maxPayload | 0;
177
+ this._options = options || {};
178
+ this._threshold = this._options.threshold !== undefined ? this._options.threshold : 1024;
179
+ this._isServer = !!isServer;
180
+ this._deflate = null;
181
+ this._inflate = null;
182
+ this.params = null;
183
+ if (!zlibLimiter) {
184
+ const concurrency = this._options.concurrencyLimit !== undefined ? this._options.concurrencyLimit : 10;
185
+ zlibLimiter = new Limiter(concurrency);
186
+ }
187
+ }
188
+ static get extensionName() {
189
+ return "permessage-deflate";
190
+ }
191
+ offer() {
192
+ const params = {};
193
+ if (this._options.serverNoContextTakeover) {
194
+ params.server_no_context_takeover = true;
195
+ }
196
+ if (this._options.clientNoContextTakeover) {
197
+ params.client_no_context_takeover = true;
198
+ }
199
+ if (this._options.serverMaxWindowBits) {
200
+ params.server_max_window_bits = this._options.serverMaxWindowBits;
201
+ }
202
+ if (this._options.clientMaxWindowBits) {
203
+ params.client_max_window_bits = this._options.clientMaxWindowBits;
204
+ } else if (this._options.clientMaxWindowBits == null) {
205
+ params.client_max_window_bits = true;
206
+ }
207
+ return params;
208
+ }
209
+ accept(configurations) {
210
+ configurations = this.normalizeParams(configurations);
211
+ this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations);
212
+ return this.params;
213
+ }
214
+ cleanup() {
215
+ if (this._inflate) {
216
+ this._inflate.close();
217
+ this._inflate = null;
218
+ }
219
+ if (this._deflate) {
220
+ const callback = this._deflate[kCallback];
221
+ this._deflate.close();
222
+ this._deflate = null;
223
+ if (callback) {
224
+ callback(new Error("The deflate stream was closed while data was being processed"));
225
+ }
226
+ }
227
+ }
228
+ acceptAsServer(offers) {
229
+ const opts = this._options;
230
+ const accepted = offers.find((params) => {
231
+ 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) {
232
+ return false;
233
+ }
234
+ return true;
235
+ });
236
+ if (!accepted) {
237
+ throw new Error("None of the extension offers can be accepted");
238
+ }
239
+ if (opts.serverNoContextTakeover) {
240
+ accepted.server_no_context_takeover = true;
241
+ }
242
+ if (opts.clientNoContextTakeover) {
243
+ accepted.client_no_context_takeover = true;
244
+ }
245
+ if (typeof opts.serverMaxWindowBits === "number") {
246
+ accepted.server_max_window_bits = opts.serverMaxWindowBits;
247
+ }
248
+ if (typeof opts.clientMaxWindowBits === "number") {
249
+ accepted.client_max_window_bits = opts.clientMaxWindowBits;
250
+ } else if (accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false) {
251
+ delete accepted.client_max_window_bits;
252
+ }
253
+ return accepted;
254
+ }
255
+ acceptAsClient(response) {
256
+ const params = response[0];
257
+ if (this._options.clientNoContextTakeover === false && params.client_no_context_takeover) {
258
+ throw new Error('Unexpected parameter "client_no_context_takeover"');
259
+ }
260
+ if (!params.client_max_window_bits) {
261
+ if (typeof this._options.clientMaxWindowBits === "number") {
262
+ params.client_max_window_bits = this._options.clientMaxWindowBits;
263
+ }
264
+ } else if (this._options.clientMaxWindowBits === false || typeof this._options.clientMaxWindowBits === "number" && params.client_max_window_bits > this._options.clientMaxWindowBits) {
265
+ throw new Error('Unexpected or invalid parameter "client_max_window_bits"');
266
+ }
267
+ return params;
268
+ }
269
+ normalizeParams(configurations) {
270
+ configurations.forEach((params) => {
271
+ Object.keys(params).forEach((key) => {
272
+ let value = params[key];
273
+ if (value.length > 1) {
274
+ throw new Error(`Parameter "${key}" must have only a single value`);
275
+ }
276
+ value = value[0];
277
+ if (key === "client_max_window_bits") {
278
+ if (value !== true) {
279
+ const num = +value;
280
+ if (!Number.isInteger(num) || num < 8 || num > 15) {
281
+ throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
282
+ }
283
+ value = num;
284
+ } else if (!this._isServer) {
285
+ throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
286
+ }
287
+ } else if (key === "server_max_window_bits") {
288
+ const num = +value;
289
+ if (!Number.isInteger(num) || num < 8 || num > 15) {
290
+ throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
291
+ }
292
+ value = num;
293
+ } else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") {
294
+ if (value !== true) {
295
+ throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
296
+ }
297
+ } else {
298
+ throw new Error(`Unknown parameter "${key}"`);
299
+ }
300
+ params[key] = value;
301
+ });
302
+ });
303
+ return configurations;
304
+ }
305
+ decompress(data, fin, callback) {
306
+ zlibLimiter.add((done) => {
307
+ this._decompress(data, fin, (err, result) => {
308
+ done();
309
+ callback(err, result);
310
+ });
311
+ });
312
+ }
313
+ compress(data, fin, callback) {
314
+ zlibLimiter.add((done) => {
315
+ this._compress(data, fin, (err, result) => {
316
+ done();
317
+ callback(err, result);
318
+ });
319
+ });
320
+ }
321
+ _decompress(data, fin, callback) {
322
+ const endpoint = this._isServer ? "client" : "server";
323
+ if (!this._inflate) {
324
+ const key = `${endpoint}_max_window_bits`;
325
+ const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
326
+ this._inflate = zlib.createInflateRaw({
327
+ ...this._options.zlibInflateOptions,
328
+ windowBits
329
+ });
330
+ this._inflate[kPerMessageDeflate] = this;
331
+ this._inflate[kTotalLength] = 0;
332
+ this._inflate[kBuffers] = [];
333
+ this._inflate.on("error", inflateOnError);
334
+ this._inflate.on("data", inflateOnData);
335
+ }
336
+ this._inflate[kCallback] = callback;
337
+ this._inflate.write(data);
338
+ if (fin)
339
+ this._inflate.write(TRAILER);
340
+ this._inflate.flush(() => {
341
+ const err = this._inflate[kError];
342
+ if (err) {
343
+ this._inflate.close();
344
+ this._inflate = null;
345
+ callback(err);
346
+ return;
347
+ }
348
+ const data2 = bufferUtil.concat(this._inflate[kBuffers], this._inflate[kTotalLength]);
349
+ if (this._inflate._readableState.endEmitted) {
350
+ this._inflate.close();
351
+ this._inflate = null;
352
+ } else {
353
+ this._inflate[kTotalLength] = 0;
354
+ this._inflate[kBuffers] = [];
355
+ if (fin && this.params[`${endpoint}_no_context_takeover`]) {
356
+ this._inflate.reset();
357
+ }
358
+ }
359
+ callback(null, data2);
360
+ });
361
+ }
362
+ _compress(data, fin, callback) {
363
+ const endpoint = this._isServer ? "server" : "client";
364
+ if (!this._deflate) {
365
+ const key = `${endpoint}_max_window_bits`;
366
+ const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
367
+ this._deflate = zlib.createDeflateRaw({
368
+ ...this._options.zlibDeflateOptions,
369
+ windowBits
370
+ });
371
+ this._deflate[kTotalLength] = 0;
372
+ this._deflate[kBuffers] = [];
373
+ this._deflate.on("data", deflateOnData);
374
+ }
375
+ this._deflate[kCallback] = callback;
376
+ this._deflate.write(data);
377
+ this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {
378
+ if (!this._deflate) {
379
+ return;
380
+ }
381
+ let data2 = bufferUtil.concat(this._deflate[kBuffers], this._deflate[kTotalLength]);
382
+ if (fin) {
383
+ data2 = new FastBuffer(data2.buffer, data2.byteOffset, data2.length - 4);
384
+ }
385
+ this._deflate[kCallback] = null;
386
+ this._deflate[kTotalLength] = 0;
387
+ this._deflate[kBuffers] = [];
388
+ if (fin && this.params[`${endpoint}_no_context_takeover`]) {
389
+ this._deflate.reset();
390
+ }
391
+ callback(null, data2);
392
+ });
393
+ }
394
+ }
395
+ module.exports = PerMessageDeflate;
396
+ function deflateOnData(chunk) {
397
+ this[kBuffers].push(chunk);
398
+ this[kTotalLength] += chunk.length;
399
+ }
400
+ function inflateOnData(chunk) {
401
+ this[kTotalLength] += chunk.length;
402
+ if (this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) {
403
+ this[kBuffers].push(chunk);
404
+ return;
405
+ }
406
+ this[kError] = new RangeError("Max payload size exceeded");
407
+ this[kError].code = "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH";
408
+ this[kError][kStatusCode] = 1009;
409
+ this.removeListener("data", inflateOnData);
410
+ this.reset();
411
+ }
412
+ function inflateOnError(err) {
413
+ this[kPerMessageDeflate]._inflate = null;
414
+ if (this[kError]) {
415
+ this[kCallback](this[kError]);
416
+ return;
417
+ }
418
+ err[kStatusCode] = 1007;
419
+ this[kCallback](err);
420
+ }
421
+ });
422
+
423
+ // node_modules/ws/lib/validation.js
424
+ var require_validation = __commonJS((exports, module) => {
425
+ var { isUtf8 } = __require("buffer");
426
+ var { hasBlob } = require_constants();
427
+ var tokenChars = [
428
+ 0,
429
+ 0,
430
+ 0,
431
+ 0,
432
+ 0,
433
+ 0,
434
+ 0,
435
+ 0,
436
+ 0,
437
+ 0,
438
+ 0,
439
+ 0,
440
+ 0,
441
+ 0,
442
+ 0,
443
+ 0,
444
+ 0,
445
+ 0,
446
+ 0,
447
+ 0,
448
+ 0,
449
+ 0,
450
+ 0,
451
+ 0,
452
+ 0,
453
+ 0,
454
+ 0,
455
+ 0,
456
+ 0,
457
+ 0,
458
+ 0,
459
+ 0,
460
+ 0,
461
+ 1,
462
+ 0,
463
+ 1,
464
+ 1,
465
+ 1,
466
+ 1,
467
+ 1,
468
+ 0,
469
+ 0,
470
+ 1,
471
+ 1,
472
+ 0,
473
+ 1,
474
+ 1,
475
+ 0,
476
+ 1,
477
+ 1,
478
+ 1,
479
+ 1,
480
+ 1,
481
+ 1,
482
+ 1,
483
+ 1,
484
+ 1,
485
+ 1,
486
+ 0,
487
+ 0,
488
+ 0,
489
+ 0,
490
+ 0,
491
+ 0,
492
+ 0,
493
+ 1,
494
+ 1,
495
+ 1,
496
+ 1,
497
+ 1,
498
+ 1,
499
+ 1,
500
+ 1,
501
+ 1,
502
+ 1,
503
+ 1,
504
+ 1,
505
+ 1,
506
+ 1,
507
+ 1,
508
+ 1,
509
+ 1,
510
+ 1,
511
+ 1,
512
+ 1,
513
+ 1,
514
+ 1,
515
+ 1,
516
+ 1,
517
+ 1,
518
+ 1,
519
+ 0,
520
+ 0,
521
+ 0,
522
+ 1,
523
+ 1,
524
+ 1,
525
+ 1,
526
+ 1,
527
+ 1,
528
+ 1,
529
+ 1,
530
+ 1,
531
+ 1,
532
+ 1,
533
+ 1,
534
+ 1,
535
+ 1,
536
+ 1,
537
+ 1,
538
+ 1,
539
+ 1,
540
+ 1,
541
+ 1,
542
+ 1,
543
+ 1,
544
+ 1,
545
+ 1,
546
+ 1,
547
+ 1,
548
+ 1,
549
+ 1,
550
+ 1,
551
+ 0,
552
+ 1,
553
+ 0,
554
+ 1,
555
+ 0
556
+ ];
557
+ function isValidStatusCode(code) {
558
+ return code >= 1000 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006 || code >= 3000 && code <= 4999;
559
+ }
560
+ function _isValidUTF8(buf) {
561
+ const len = buf.length;
562
+ let i = 0;
563
+ while (i < len) {
564
+ if ((buf[i] & 128) === 0) {
565
+ i++;
566
+ } else if ((buf[i] & 224) === 192) {
567
+ if (i + 1 === len || (buf[i + 1] & 192) !== 128 || (buf[i] & 254) === 192) {
568
+ return false;
569
+ }
570
+ i += 2;
571
+ } else if ((buf[i] & 240) === 224) {
572
+ if (i + 2 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || buf[i] === 224 && (buf[i + 1] & 224) === 128 || buf[i] === 237 && (buf[i + 1] & 224) === 160) {
573
+ return false;
574
+ }
575
+ i += 3;
576
+ } else if ((buf[i] & 248) === 240) {
577
+ if (i + 3 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || (buf[i + 3] & 192) !== 128 || buf[i] === 240 && (buf[i + 1] & 240) === 128 || buf[i] === 244 && buf[i + 1] > 143 || buf[i] > 244) {
578
+ return false;
579
+ }
580
+ i += 4;
581
+ } else {
582
+ return false;
583
+ }
584
+ }
585
+ return true;
586
+ }
587
+ function isBlob(value) {
588
+ return hasBlob && typeof value === "object" && typeof value.arrayBuffer === "function" && typeof value.type === "string" && typeof value.stream === "function" && (value[Symbol.toStringTag] === "Blob" || value[Symbol.toStringTag] === "File");
589
+ }
590
+ module.exports = {
591
+ isBlob,
592
+ isValidStatusCode,
593
+ isValidUTF8: _isValidUTF8,
594
+ tokenChars
595
+ };
596
+ if (isUtf8) {
597
+ module.exports.isValidUTF8 = function(buf) {
598
+ return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);
599
+ };
600
+ } else if (!process.env.WS_NO_UTF_8_VALIDATE) {
601
+ try {
602
+ const isValidUTF8 = (()=>{throw new Error("Cannot require module "+"utf-8-validate");})();
603
+ module.exports.isValidUTF8 = function(buf) {
604
+ return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);
605
+ };
606
+ } catch (e) {}
607
+ }
608
+ });
609
+
610
+ // node_modules/ws/lib/receiver.js
611
+ var require_receiver = __commonJS((exports, module) => {
612
+ var { Writable } = __require("stream");
613
+ var PerMessageDeflate = require_permessage_deflate();
614
+ var {
615
+ BINARY_TYPES,
616
+ EMPTY_BUFFER,
617
+ kStatusCode,
618
+ kWebSocket
619
+ } = require_constants();
620
+ var { concat, toArrayBuffer, unmask } = require_buffer_util();
621
+ var { isValidStatusCode, isValidUTF8 } = require_validation();
622
+ var FastBuffer = Buffer[Symbol.species];
623
+ var GET_INFO = 0;
624
+ var GET_PAYLOAD_LENGTH_16 = 1;
625
+ var GET_PAYLOAD_LENGTH_64 = 2;
626
+ var GET_MASK = 3;
627
+ var GET_DATA = 4;
628
+ var INFLATING = 5;
629
+ var DEFER_EVENT = 6;
630
+
631
+ class Receiver extends Writable {
632
+ constructor(options = {}) {
633
+ super();
634
+ this._allowSynchronousEvents = options.allowSynchronousEvents !== undefined ? options.allowSynchronousEvents : true;
635
+ this._binaryType = options.binaryType || BINARY_TYPES[0];
636
+ this._extensions = options.extensions || {};
637
+ this._isServer = !!options.isServer;
638
+ this._maxPayload = options.maxPayload | 0;
639
+ this._skipUTF8Validation = !!options.skipUTF8Validation;
640
+ this[kWebSocket] = undefined;
641
+ this._bufferedBytes = 0;
642
+ this._buffers = [];
643
+ this._compressed = false;
644
+ this._payloadLength = 0;
645
+ this._mask = undefined;
646
+ this._fragmented = 0;
647
+ this._masked = false;
648
+ this._fin = false;
649
+ this._opcode = 0;
650
+ this._totalPayloadLength = 0;
651
+ this._messageLength = 0;
652
+ this._fragments = [];
653
+ this._errored = false;
654
+ this._loop = false;
655
+ this._state = GET_INFO;
656
+ }
657
+ _write(chunk, encoding, cb) {
658
+ if (this._opcode === 8 && this._state == GET_INFO)
659
+ return cb();
660
+ this._bufferedBytes += chunk.length;
661
+ this._buffers.push(chunk);
662
+ this.startLoop(cb);
663
+ }
664
+ consume(n) {
665
+ this._bufferedBytes -= n;
666
+ if (n === this._buffers[0].length)
667
+ return this._buffers.shift();
668
+ if (n < this._buffers[0].length) {
669
+ const buf = this._buffers[0];
670
+ this._buffers[0] = new FastBuffer(buf.buffer, buf.byteOffset + n, buf.length - n);
671
+ return new FastBuffer(buf.buffer, buf.byteOffset, n);
672
+ }
673
+ const dst = Buffer.allocUnsafe(n);
674
+ do {
675
+ const buf = this._buffers[0];
676
+ const offset = dst.length - n;
677
+ if (n >= buf.length) {
678
+ dst.set(this._buffers.shift(), offset);
679
+ } else {
680
+ dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);
681
+ this._buffers[0] = new FastBuffer(buf.buffer, buf.byteOffset + n, buf.length - n);
682
+ }
683
+ n -= buf.length;
684
+ } while (n > 0);
685
+ return dst;
686
+ }
687
+ startLoop(cb) {
688
+ this._loop = true;
689
+ do {
690
+ switch (this._state) {
691
+ case GET_INFO:
692
+ this.getInfo(cb);
693
+ break;
694
+ case GET_PAYLOAD_LENGTH_16:
695
+ this.getPayloadLength16(cb);
696
+ break;
697
+ case GET_PAYLOAD_LENGTH_64:
698
+ this.getPayloadLength64(cb);
699
+ break;
700
+ case GET_MASK:
701
+ this.getMask();
702
+ break;
703
+ case GET_DATA:
704
+ this.getData(cb);
705
+ break;
706
+ case INFLATING:
707
+ case DEFER_EVENT:
708
+ this._loop = false;
709
+ return;
710
+ }
711
+ } while (this._loop);
712
+ if (!this._errored)
713
+ cb();
714
+ }
715
+ getInfo(cb) {
716
+ if (this._bufferedBytes < 2) {
717
+ this._loop = false;
718
+ return;
719
+ }
720
+ const buf = this.consume(2);
721
+ if ((buf[0] & 48) !== 0) {
722
+ const error = this.createError(RangeError, "RSV2 and RSV3 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_2_3");
723
+ cb(error);
724
+ return;
725
+ }
726
+ const compressed = (buf[0] & 64) === 64;
727
+ if (compressed && !this._extensions[PerMessageDeflate.extensionName]) {
728
+ const error = this.createError(RangeError, "RSV1 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_1");
729
+ cb(error);
730
+ return;
731
+ }
732
+ this._fin = (buf[0] & 128) === 128;
733
+ this._opcode = buf[0] & 15;
734
+ this._payloadLength = buf[1] & 127;
735
+ if (this._opcode === 0) {
736
+ if (compressed) {
737
+ const error = this.createError(RangeError, "RSV1 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_1");
738
+ cb(error);
739
+ return;
740
+ }
741
+ if (!this._fragmented) {
742
+ const error = this.createError(RangeError, "invalid opcode 0", true, 1002, "WS_ERR_INVALID_OPCODE");
743
+ cb(error);
744
+ return;
745
+ }
746
+ this._opcode = this._fragmented;
747
+ } else if (this._opcode === 1 || this._opcode === 2) {
748
+ if (this._fragmented) {
749
+ const error = this.createError(RangeError, `invalid opcode ${this._opcode}`, true, 1002, "WS_ERR_INVALID_OPCODE");
750
+ cb(error);
751
+ return;
752
+ }
753
+ this._compressed = compressed;
754
+ } else if (this._opcode > 7 && this._opcode < 11) {
755
+ if (!this._fin) {
756
+ const error = this.createError(RangeError, "FIN must be set", true, 1002, "WS_ERR_EXPECTED_FIN");
757
+ cb(error);
758
+ return;
759
+ }
760
+ if (compressed) {
761
+ const error = this.createError(RangeError, "RSV1 must be clear", true, 1002, "WS_ERR_UNEXPECTED_RSV_1");
762
+ cb(error);
763
+ return;
764
+ }
765
+ if (this._payloadLength > 125 || this._opcode === 8 && this._payloadLength === 1) {
766
+ const error = this.createError(RangeError, `invalid payload length ${this._payloadLength}`, true, 1002, "WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");
767
+ cb(error);
768
+ return;
769
+ }
770
+ } else {
771
+ const error = this.createError(RangeError, `invalid opcode ${this._opcode}`, true, 1002, "WS_ERR_INVALID_OPCODE");
772
+ cb(error);
773
+ return;
774
+ }
775
+ if (!this._fin && !this._fragmented)
776
+ this._fragmented = this._opcode;
777
+ this._masked = (buf[1] & 128) === 128;
778
+ if (this._isServer) {
779
+ if (!this._masked) {
780
+ const error = this.createError(RangeError, "MASK must be set", true, 1002, "WS_ERR_EXPECTED_MASK");
781
+ cb(error);
782
+ return;
783
+ }
784
+ } else if (this._masked) {
785
+ const error = this.createError(RangeError, "MASK must be clear", true, 1002, "WS_ERR_UNEXPECTED_MASK");
786
+ cb(error);
787
+ return;
788
+ }
789
+ if (this._payloadLength === 126)
790
+ this._state = GET_PAYLOAD_LENGTH_16;
791
+ else if (this._payloadLength === 127)
792
+ this._state = GET_PAYLOAD_LENGTH_64;
793
+ else
794
+ this.haveLength(cb);
795
+ }
796
+ getPayloadLength16(cb) {
797
+ if (this._bufferedBytes < 2) {
798
+ this._loop = false;
799
+ return;
800
+ }
801
+ this._payloadLength = this.consume(2).readUInt16BE(0);
802
+ this.haveLength(cb);
803
+ }
804
+ getPayloadLength64(cb) {
805
+ if (this._bufferedBytes < 8) {
806
+ this._loop = false;
807
+ return;
808
+ }
809
+ const buf = this.consume(8);
810
+ const num = buf.readUInt32BE(0);
811
+ if (num > Math.pow(2, 53 - 32) - 1) {
812
+ const error = this.createError(RangeError, "Unsupported WebSocket frame: payload length > 2^53 - 1", false, 1009, "WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");
813
+ cb(error);
814
+ return;
815
+ }
816
+ this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
817
+ this.haveLength(cb);
818
+ }
819
+ haveLength(cb) {
820
+ if (this._payloadLength && this._opcode < 8) {
821
+ this._totalPayloadLength += this._payloadLength;
822
+ if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
823
+ const error = this.createError(RangeError, "Max payload size exceeded", false, 1009, "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");
824
+ cb(error);
825
+ return;
826
+ }
827
+ }
828
+ if (this._masked)
829
+ this._state = GET_MASK;
830
+ else
831
+ this._state = GET_DATA;
832
+ }
833
+ getMask() {
834
+ if (this._bufferedBytes < 4) {
835
+ this._loop = false;
836
+ return;
837
+ }
838
+ this._mask = this.consume(4);
839
+ this._state = GET_DATA;
840
+ }
841
+ getData(cb) {
842
+ let data = EMPTY_BUFFER;
843
+ if (this._payloadLength) {
844
+ if (this._bufferedBytes < this._payloadLength) {
845
+ this._loop = false;
846
+ return;
847
+ }
848
+ data = this.consume(this._payloadLength);
849
+ if (this._masked && (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0) {
850
+ unmask(data, this._mask);
851
+ }
852
+ }
853
+ if (this._opcode > 7) {
854
+ this.controlMessage(data, cb);
855
+ return;
856
+ }
857
+ if (this._compressed) {
858
+ this._state = INFLATING;
859
+ this.decompress(data, cb);
860
+ return;
861
+ }
862
+ if (data.length) {
863
+ this._messageLength = this._totalPayloadLength;
864
+ this._fragments.push(data);
865
+ }
866
+ this.dataMessage(cb);
867
+ }
868
+ decompress(data, cb) {
869
+ const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
870
+ perMessageDeflate.decompress(data, this._fin, (err, buf) => {
871
+ if (err)
872
+ return cb(err);
873
+ if (buf.length) {
874
+ this._messageLength += buf.length;
875
+ if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
876
+ const error = this.createError(RangeError, "Max payload size exceeded", false, 1009, "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");
877
+ cb(error);
878
+ return;
879
+ }
880
+ this._fragments.push(buf);
881
+ }
882
+ this.dataMessage(cb);
883
+ if (this._state === GET_INFO)
884
+ this.startLoop(cb);
885
+ });
886
+ }
887
+ dataMessage(cb) {
888
+ if (!this._fin) {
889
+ this._state = GET_INFO;
890
+ return;
891
+ }
892
+ const messageLength = this._messageLength;
893
+ const fragments = this._fragments;
894
+ this._totalPayloadLength = 0;
895
+ this._messageLength = 0;
896
+ this._fragmented = 0;
897
+ this._fragments = [];
898
+ if (this._opcode === 2) {
899
+ let data;
900
+ if (this._binaryType === "nodebuffer") {
901
+ data = concat(fragments, messageLength);
902
+ } else if (this._binaryType === "arraybuffer") {
903
+ data = toArrayBuffer(concat(fragments, messageLength));
904
+ } else if (this._binaryType === "blob") {
905
+ data = new Blob(fragments);
906
+ } else {
907
+ data = fragments;
908
+ }
909
+ if (this._allowSynchronousEvents) {
910
+ this.emit("message", data, true);
911
+ this._state = GET_INFO;
912
+ } else {
913
+ this._state = DEFER_EVENT;
914
+ setImmediate(() => {
915
+ this.emit("message", data, true);
916
+ this._state = GET_INFO;
917
+ this.startLoop(cb);
918
+ });
919
+ }
920
+ } else {
921
+ const buf = concat(fragments, messageLength);
922
+ if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
923
+ const error = this.createError(Error, "invalid UTF-8 sequence", true, 1007, "WS_ERR_INVALID_UTF8");
924
+ cb(error);
925
+ return;
926
+ }
927
+ if (this._state === INFLATING || this._allowSynchronousEvents) {
928
+ this.emit("message", buf, false);
929
+ this._state = GET_INFO;
930
+ } else {
931
+ this._state = DEFER_EVENT;
932
+ setImmediate(() => {
933
+ this.emit("message", buf, false);
934
+ this._state = GET_INFO;
935
+ this.startLoop(cb);
936
+ });
937
+ }
938
+ }
939
+ }
940
+ controlMessage(data, cb) {
941
+ if (this._opcode === 8) {
942
+ if (data.length === 0) {
943
+ this._loop = false;
944
+ this.emit("conclude", 1005, EMPTY_BUFFER);
945
+ this.end();
946
+ } else {
947
+ const code = data.readUInt16BE(0);
948
+ if (!isValidStatusCode(code)) {
949
+ const error = this.createError(RangeError, `invalid status code ${code}`, true, 1002, "WS_ERR_INVALID_CLOSE_CODE");
950
+ cb(error);
951
+ return;
952
+ }
953
+ const buf = new FastBuffer(data.buffer, data.byteOffset + 2, data.length - 2);
954
+ if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
955
+ const error = this.createError(Error, "invalid UTF-8 sequence", true, 1007, "WS_ERR_INVALID_UTF8");
956
+ cb(error);
957
+ return;
958
+ }
959
+ this._loop = false;
960
+ this.emit("conclude", code, buf);
961
+ this.end();
962
+ }
963
+ this._state = GET_INFO;
964
+ return;
965
+ }
966
+ if (this._allowSynchronousEvents) {
967
+ this.emit(this._opcode === 9 ? "ping" : "pong", data);
968
+ this._state = GET_INFO;
969
+ } else {
970
+ this._state = DEFER_EVENT;
971
+ setImmediate(() => {
972
+ this.emit(this._opcode === 9 ? "ping" : "pong", data);
973
+ this._state = GET_INFO;
974
+ this.startLoop(cb);
975
+ });
976
+ }
977
+ }
978
+ createError(ErrorCtor, message, prefix, statusCode, errorCode) {
979
+ this._loop = false;
980
+ this._errored = true;
981
+ const err = new ErrorCtor(prefix ? `Invalid WebSocket frame: ${message}` : message);
982
+ Error.captureStackTrace(err, this.createError);
983
+ err.code = errorCode;
984
+ err[kStatusCode] = statusCode;
985
+ return err;
986
+ }
987
+ }
988
+ module.exports = Receiver;
989
+ });
990
+
991
+ // node_modules/ws/lib/sender.js
992
+ var require_sender = __commonJS((exports, module) => {
993
+ var { Duplex } = __require("stream");
994
+ var { randomFillSync } = __require("crypto");
995
+ var PerMessageDeflate = require_permessage_deflate();
996
+ var { EMPTY_BUFFER, kWebSocket, NOOP } = require_constants();
997
+ var { isBlob, isValidStatusCode } = require_validation();
998
+ var { mask: applyMask, toBuffer } = require_buffer_util();
999
+ var kByteLength = Symbol("kByteLength");
1000
+ var maskBuffer = Buffer.alloc(4);
1001
+ var RANDOM_POOL_SIZE = 8 * 1024;
1002
+ var randomPool;
1003
+ var randomPoolPointer = RANDOM_POOL_SIZE;
1004
+ var DEFAULT = 0;
1005
+ var DEFLATING = 1;
1006
+ var GET_BLOB_DATA = 2;
1007
+
1008
+ class Sender {
1009
+ constructor(socket, extensions, generateMask) {
1010
+ this._extensions = extensions || {};
1011
+ if (generateMask) {
1012
+ this._generateMask = generateMask;
1013
+ this._maskBuffer = Buffer.alloc(4);
1014
+ }
1015
+ this._socket = socket;
1016
+ this._firstFragment = true;
1017
+ this._compress = false;
1018
+ this._bufferedBytes = 0;
1019
+ this._queue = [];
1020
+ this._state = DEFAULT;
1021
+ this.onerror = NOOP;
1022
+ this[kWebSocket] = undefined;
1023
+ }
1024
+ static frame(data, options) {
1025
+ let mask;
1026
+ let merge = false;
1027
+ let offset = 2;
1028
+ let skipMasking = false;
1029
+ if (options.mask) {
1030
+ mask = options.maskBuffer || maskBuffer;
1031
+ if (options.generateMask) {
1032
+ options.generateMask(mask);
1033
+ } else {
1034
+ if (randomPoolPointer === RANDOM_POOL_SIZE) {
1035
+ if (randomPool === undefined) {
1036
+ randomPool = Buffer.alloc(RANDOM_POOL_SIZE);
1037
+ }
1038
+ randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);
1039
+ randomPoolPointer = 0;
1040
+ }
1041
+ mask[0] = randomPool[randomPoolPointer++];
1042
+ mask[1] = randomPool[randomPoolPointer++];
1043
+ mask[2] = randomPool[randomPoolPointer++];
1044
+ mask[3] = randomPool[randomPoolPointer++];
1045
+ }
1046
+ skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;
1047
+ offset = 6;
1048
+ }
1049
+ let dataLength;
1050
+ if (typeof data === "string") {
1051
+ if ((!options.mask || skipMasking) && options[kByteLength] !== undefined) {
1052
+ dataLength = options[kByteLength];
1053
+ } else {
1054
+ data = Buffer.from(data);
1055
+ dataLength = data.length;
1056
+ }
1057
+ } else {
1058
+ dataLength = data.length;
1059
+ merge = options.mask && options.readOnly && !skipMasking;
1060
+ }
1061
+ let payloadLength = dataLength;
1062
+ if (dataLength >= 65536) {
1063
+ offset += 8;
1064
+ payloadLength = 127;
1065
+ } else if (dataLength > 125) {
1066
+ offset += 2;
1067
+ payloadLength = 126;
1068
+ }
1069
+ const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);
1070
+ target[0] = options.fin ? options.opcode | 128 : options.opcode;
1071
+ if (options.rsv1)
1072
+ target[0] |= 64;
1073
+ target[1] = payloadLength;
1074
+ if (payloadLength === 126) {
1075
+ target.writeUInt16BE(dataLength, 2);
1076
+ } else if (payloadLength === 127) {
1077
+ target[2] = target[3] = 0;
1078
+ target.writeUIntBE(dataLength, 4, 6);
1079
+ }
1080
+ if (!options.mask)
1081
+ return [target, data];
1082
+ target[1] |= 128;
1083
+ target[offset - 4] = mask[0];
1084
+ target[offset - 3] = mask[1];
1085
+ target[offset - 2] = mask[2];
1086
+ target[offset - 1] = mask[3];
1087
+ if (skipMasking)
1088
+ return [target, data];
1089
+ if (merge) {
1090
+ applyMask(data, mask, target, offset, dataLength);
1091
+ return [target];
1092
+ }
1093
+ applyMask(data, mask, data, 0, dataLength);
1094
+ return [target, data];
1095
+ }
1096
+ close(code, data, mask, cb) {
1097
+ let buf;
1098
+ if (code === undefined) {
1099
+ buf = EMPTY_BUFFER;
1100
+ } else if (typeof code !== "number" || !isValidStatusCode(code)) {
1101
+ throw new TypeError("First argument must be a valid error code number");
1102
+ } else if (data === undefined || !data.length) {
1103
+ buf = Buffer.allocUnsafe(2);
1104
+ buf.writeUInt16BE(code, 0);
1105
+ } else {
1106
+ const length = Buffer.byteLength(data);
1107
+ if (length > 123) {
1108
+ throw new RangeError("The message must not be greater than 123 bytes");
1109
+ }
1110
+ buf = Buffer.allocUnsafe(2 + length);
1111
+ buf.writeUInt16BE(code, 0);
1112
+ if (typeof data === "string") {
1113
+ buf.write(data, 2);
1114
+ } else {
1115
+ buf.set(data, 2);
1116
+ }
1117
+ }
1118
+ const options = {
1119
+ [kByteLength]: buf.length,
1120
+ fin: true,
1121
+ generateMask: this._generateMask,
1122
+ mask,
1123
+ maskBuffer: this._maskBuffer,
1124
+ opcode: 8,
1125
+ readOnly: false,
1126
+ rsv1: false
1127
+ };
1128
+ if (this._state !== DEFAULT) {
1129
+ this.enqueue([this.dispatch, buf, false, options, cb]);
1130
+ } else {
1131
+ this.sendFrame(Sender.frame(buf, options), cb);
1132
+ }
1133
+ }
1134
+ ping(data, mask, cb) {
1135
+ let byteLength;
1136
+ let readOnly;
1137
+ if (typeof data === "string") {
1138
+ byteLength = Buffer.byteLength(data);
1139
+ readOnly = false;
1140
+ } else if (isBlob(data)) {
1141
+ byteLength = data.size;
1142
+ readOnly = false;
1143
+ } else {
1144
+ data = toBuffer(data);
1145
+ byteLength = data.length;
1146
+ readOnly = toBuffer.readOnly;
1147
+ }
1148
+ if (byteLength > 125) {
1149
+ throw new RangeError("The data size must not be greater than 125 bytes");
1150
+ }
1151
+ const options = {
1152
+ [kByteLength]: byteLength,
1153
+ fin: true,
1154
+ generateMask: this._generateMask,
1155
+ mask,
1156
+ maskBuffer: this._maskBuffer,
1157
+ opcode: 9,
1158
+ readOnly,
1159
+ rsv1: false
1160
+ };
1161
+ if (isBlob(data)) {
1162
+ if (this._state !== DEFAULT) {
1163
+ this.enqueue([this.getBlobData, data, false, options, cb]);
1164
+ } else {
1165
+ this.getBlobData(data, false, options, cb);
1166
+ }
1167
+ } else if (this._state !== DEFAULT) {
1168
+ this.enqueue([this.dispatch, data, false, options, cb]);
1169
+ } else {
1170
+ this.sendFrame(Sender.frame(data, options), cb);
1171
+ }
1172
+ }
1173
+ pong(data, mask, cb) {
1174
+ let byteLength;
1175
+ let readOnly;
1176
+ if (typeof data === "string") {
1177
+ byteLength = Buffer.byteLength(data);
1178
+ readOnly = false;
1179
+ } else if (isBlob(data)) {
1180
+ byteLength = data.size;
1181
+ readOnly = false;
1182
+ } else {
1183
+ data = toBuffer(data);
1184
+ byteLength = data.length;
1185
+ readOnly = toBuffer.readOnly;
1186
+ }
1187
+ if (byteLength > 125) {
1188
+ throw new RangeError("The data size must not be greater than 125 bytes");
1189
+ }
1190
+ const options = {
1191
+ [kByteLength]: byteLength,
1192
+ fin: true,
1193
+ generateMask: this._generateMask,
1194
+ mask,
1195
+ maskBuffer: this._maskBuffer,
1196
+ opcode: 10,
1197
+ readOnly,
1198
+ rsv1: false
1199
+ };
1200
+ if (isBlob(data)) {
1201
+ if (this._state !== DEFAULT) {
1202
+ this.enqueue([this.getBlobData, data, false, options, cb]);
1203
+ } else {
1204
+ this.getBlobData(data, false, options, cb);
1205
+ }
1206
+ } else if (this._state !== DEFAULT) {
1207
+ this.enqueue([this.dispatch, data, false, options, cb]);
1208
+ } else {
1209
+ this.sendFrame(Sender.frame(data, options), cb);
1210
+ }
1211
+ }
1212
+ send(data, options, cb) {
1213
+ const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
1214
+ let opcode = options.binary ? 2 : 1;
1215
+ let rsv1 = options.compress;
1216
+ let byteLength;
1217
+ let readOnly;
1218
+ if (typeof data === "string") {
1219
+ byteLength = Buffer.byteLength(data);
1220
+ readOnly = false;
1221
+ } else if (isBlob(data)) {
1222
+ byteLength = data.size;
1223
+ readOnly = false;
1224
+ } else {
1225
+ data = toBuffer(data);
1226
+ byteLength = data.length;
1227
+ readOnly = toBuffer.readOnly;
1228
+ }
1229
+ if (this._firstFragment) {
1230
+ this._firstFragment = false;
1231
+ if (rsv1 && perMessageDeflate && perMessageDeflate.params[perMessageDeflate._isServer ? "server_no_context_takeover" : "client_no_context_takeover"]) {
1232
+ rsv1 = byteLength >= perMessageDeflate._threshold;
1233
+ }
1234
+ this._compress = rsv1;
1235
+ } else {
1236
+ rsv1 = false;
1237
+ opcode = 0;
1238
+ }
1239
+ if (options.fin)
1240
+ this._firstFragment = true;
1241
+ const opts = {
1242
+ [kByteLength]: byteLength,
1243
+ fin: options.fin,
1244
+ generateMask: this._generateMask,
1245
+ mask: options.mask,
1246
+ maskBuffer: this._maskBuffer,
1247
+ opcode,
1248
+ readOnly,
1249
+ rsv1
1250
+ };
1251
+ if (isBlob(data)) {
1252
+ if (this._state !== DEFAULT) {
1253
+ this.enqueue([this.getBlobData, data, this._compress, opts, cb]);
1254
+ } else {
1255
+ this.getBlobData(data, this._compress, opts, cb);
1256
+ }
1257
+ } else if (this._state !== DEFAULT) {
1258
+ this.enqueue([this.dispatch, data, this._compress, opts, cb]);
1259
+ } else {
1260
+ this.dispatch(data, this._compress, opts, cb);
1261
+ }
1262
+ }
1263
+ getBlobData(blob, compress, options, cb) {
1264
+ this._bufferedBytes += options[kByteLength];
1265
+ this._state = GET_BLOB_DATA;
1266
+ blob.arrayBuffer().then((arrayBuffer) => {
1267
+ if (this._socket.destroyed) {
1268
+ const err = new Error("The socket was closed while the blob was being read");
1269
+ process.nextTick(callCallbacks, this, err, cb);
1270
+ return;
1271
+ }
1272
+ this._bufferedBytes -= options[kByteLength];
1273
+ const data = toBuffer(arrayBuffer);
1274
+ if (!compress) {
1275
+ this._state = DEFAULT;
1276
+ this.sendFrame(Sender.frame(data, options), cb);
1277
+ this.dequeue();
1278
+ } else {
1279
+ this.dispatch(data, compress, options, cb);
1280
+ }
1281
+ }).catch((err) => {
1282
+ process.nextTick(onError, this, err, cb);
1283
+ });
1284
+ }
1285
+ dispatch(data, compress, options, cb) {
1286
+ if (!compress) {
1287
+ this.sendFrame(Sender.frame(data, options), cb);
1288
+ return;
1289
+ }
1290
+ const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
1291
+ this._bufferedBytes += options[kByteLength];
1292
+ this._state = DEFLATING;
1293
+ perMessageDeflate.compress(data, options.fin, (_, buf) => {
1294
+ if (this._socket.destroyed) {
1295
+ const err = new Error("The socket was closed while data was being compressed");
1296
+ callCallbacks(this, err, cb);
1297
+ return;
1298
+ }
1299
+ this._bufferedBytes -= options[kByteLength];
1300
+ this._state = DEFAULT;
1301
+ options.readOnly = false;
1302
+ this.sendFrame(Sender.frame(buf, options), cb);
1303
+ this.dequeue();
1304
+ });
1305
+ }
1306
+ dequeue() {
1307
+ while (this._state === DEFAULT && this._queue.length) {
1308
+ const params = this._queue.shift();
1309
+ this._bufferedBytes -= params[3][kByteLength];
1310
+ Reflect.apply(params[0], this, params.slice(1));
1311
+ }
1312
+ }
1313
+ enqueue(params) {
1314
+ this._bufferedBytes += params[3][kByteLength];
1315
+ this._queue.push(params);
1316
+ }
1317
+ sendFrame(list, cb) {
1318
+ if (list.length === 2) {
1319
+ this._socket.cork();
1320
+ this._socket.write(list[0]);
1321
+ this._socket.write(list[1], cb);
1322
+ this._socket.uncork();
1323
+ } else {
1324
+ this._socket.write(list[0], cb);
1325
+ }
1326
+ }
1327
+ }
1328
+ module.exports = Sender;
1329
+ function callCallbacks(sender, err, cb) {
1330
+ if (typeof cb === "function")
1331
+ cb(err);
1332
+ for (let i = 0;i < sender._queue.length; i++) {
1333
+ const params = sender._queue[i];
1334
+ const callback = params[params.length - 1];
1335
+ if (typeof callback === "function")
1336
+ callback(err);
1337
+ }
1338
+ }
1339
+ function onError(sender, err, cb) {
1340
+ callCallbacks(sender, err, cb);
1341
+ sender.onerror(err);
1342
+ }
1343
+ });
1344
+
1345
+ // node_modules/ws/lib/event-target.js
1346
+ var require_event_target = __commonJS((exports, module) => {
1347
+ var { kForOnEventAttribute, kListener } = require_constants();
1348
+ var kCode = Symbol("kCode");
1349
+ var kData = Symbol("kData");
1350
+ var kError = Symbol("kError");
1351
+ var kMessage = Symbol("kMessage");
1352
+ var kReason = Symbol("kReason");
1353
+ var kTarget = Symbol("kTarget");
1354
+ var kType = Symbol("kType");
1355
+ var kWasClean = Symbol("kWasClean");
1356
+
1357
+ class Event {
1358
+ constructor(type) {
1359
+ this[kTarget] = null;
1360
+ this[kType] = type;
1361
+ }
1362
+ get target() {
1363
+ return this[kTarget];
1364
+ }
1365
+ get type() {
1366
+ return this[kType];
1367
+ }
1368
+ }
1369
+ Object.defineProperty(Event.prototype, "target", { enumerable: true });
1370
+ Object.defineProperty(Event.prototype, "type", { enumerable: true });
1371
+
1372
+ class CloseEvent extends Event {
1373
+ constructor(type, options = {}) {
1374
+ super(type);
1375
+ this[kCode] = options.code === undefined ? 0 : options.code;
1376
+ this[kReason] = options.reason === undefined ? "" : options.reason;
1377
+ this[kWasClean] = options.wasClean === undefined ? false : options.wasClean;
1378
+ }
1379
+ get code() {
1380
+ return this[kCode];
1381
+ }
1382
+ get reason() {
1383
+ return this[kReason];
1384
+ }
1385
+ get wasClean() {
1386
+ return this[kWasClean];
1387
+ }
1388
+ }
1389
+ Object.defineProperty(CloseEvent.prototype, "code", { enumerable: true });
1390
+ Object.defineProperty(CloseEvent.prototype, "reason", { enumerable: true });
1391
+ Object.defineProperty(CloseEvent.prototype, "wasClean", { enumerable: true });
1392
+
1393
+ class ErrorEvent extends Event {
1394
+ constructor(type, options = {}) {
1395
+ super(type);
1396
+ this[kError] = options.error === undefined ? null : options.error;
1397
+ this[kMessage] = options.message === undefined ? "" : options.message;
1398
+ }
1399
+ get error() {
1400
+ return this[kError];
1401
+ }
1402
+ get message() {
1403
+ return this[kMessage];
1404
+ }
1405
+ }
1406
+ Object.defineProperty(ErrorEvent.prototype, "error", { enumerable: true });
1407
+ Object.defineProperty(ErrorEvent.prototype, "message", { enumerable: true });
1408
+
1409
+ class MessageEvent extends Event {
1410
+ constructor(type, options = {}) {
1411
+ super(type);
1412
+ this[kData] = options.data === undefined ? null : options.data;
1413
+ }
1414
+ get data() {
1415
+ return this[kData];
1416
+ }
1417
+ }
1418
+ Object.defineProperty(MessageEvent.prototype, "data", { enumerable: true });
1419
+ var EventTarget = {
1420
+ addEventListener(type, handler, options = {}) {
1421
+ for (const listener of this.listeners(type)) {
1422
+ if (!options[kForOnEventAttribute] && listener[kListener] === handler && !listener[kForOnEventAttribute]) {
1423
+ return;
1424
+ }
1425
+ }
1426
+ let wrapper;
1427
+ if (type === "message") {
1428
+ wrapper = function onMessage(data, isBinary) {
1429
+ const event = new MessageEvent("message", {
1430
+ data: isBinary ? data : data.toString()
1431
+ });
1432
+ event[kTarget] = this;
1433
+ callListener(handler, this, event);
1434
+ };
1435
+ } else if (type === "close") {
1436
+ wrapper = function onClose(code, message) {
1437
+ const event = new CloseEvent("close", {
1438
+ code,
1439
+ reason: message.toString(),
1440
+ wasClean: this._closeFrameReceived && this._closeFrameSent
1441
+ });
1442
+ event[kTarget] = this;
1443
+ callListener(handler, this, event);
1444
+ };
1445
+ } else if (type === "error") {
1446
+ wrapper = function onError(error) {
1447
+ const event = new ErrorEvent("error", {
1448
+ error,
1449
+ message: error.message
1450
+ });
1451
+ event[kTarget] = this;
1452
+ callListener(handler, this, event);
1453
+ };
1454
+ } else if (type === "open") {
1455
+ wrapper = function onOpen() {
1456
+ const event = new Event("open");
1457
+ event[kTarget] = this;
1458
+ callListener(handler, this, event);
1459
+ };
1460
+ } else {
1461
+ return;
1462
+ }
1463
+ wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];
1464
+ wrapper[kListener] = handler;
1465
+ if (options.once) {
1466
+ this.once(type, wrapper);
1467
+ } else {
1468
+ this.on(type, wrapper);
1469
+ }
1470
+ },
1471
+ removeEventListener(type, handler) {
1472
+ for (const listener of this.listeners(type)) {
1473
+ if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {
1474
+ this.removeListener(type, listener);
1475
+ break;
1476
+ }
1477
+ }
1478
+ }
1479
+ };
1480
+ module.exports = {
1481
+ CloseEvent,
1482
+ ErrorEvent,
1483
+ Event,
1484
+ EventTarget,
1485
+ MessageEvent
1486
+ };
1487
+ function callListener(listener, thisArg, event) {
1488
+ if (typeof listener === "object" && listener.handleEvent) {
1489
+ listener.handleEvent.call(listener, event);
1490
+ } else {
1491
+ listener.call(thisArg, event);
1492
+ }
1493
+ }
1494
+ });
1495
+
1496
+ // node_modules/ws/lib/extension.js
1497
+ var require_extension = __commonJS((exports, module) => {
1498
+ var { tokenChars } = require_validation();
1499
+ function push(dest, name, elem) {
1500
+ if (dest[name] === undefined)
1501
+ dest[name] = [elem];
1502
+ else
1503
+ dest[name].push(elem);
1504
+ }
1505
+ function parse(header) {
1506
+ const offers = Object.create(null);
1507
+ let params = Object.create(null);
1508
+ let mustUnescape = false;
1509
+ let isEscaping = false;
1510
+ let inQuotes = false;
1511
+ let extensionName;
1512
+ let paramName;
1513
+ let start = -1;
1514
+ let code = -1;
1515
+ let end = -1;
1516
+ let i = 0;
1517
+ for (;i < header.length; i++) {
1518
+ code = header.charCodeAt(i);
1519
+ if (extensionName === undefined) {
1520
+ if (end === -1 && tokenChars[code] === 1) {
1521
+ if (start === -1)
1522
+ start = i;
1523
+ } else if (i !== 0 && (code === 32 || code === 9)) {
1524
+ if (end === -1 && start !== -1)
1525
+ end = i;
1526
+ } else if (code === 59 || code === 44) {
1527
+ if (start === -1) {
1528
+ throw new SyntaxError(`Unexpected character at index ${i}`);
1529
+ }
1530
+ if (end === -1)
1531
+ end = i;
1532
+ const name = header.slice(start, end);
1533
+ if (code === 44) {
1534
+ push(offers, name, params);
1535
+ params = Object.create(null);
1536
+ } else {
1537
+ extensionName = name;
1538
+ }
1539
+ start = end = -1;
1540
+ } else {
1541
+ throw new SyntaxError(`Unexpected character at index ${i}`);
1542
+ }
1543
+ } else if (paramName === undefined) {
1544
+ if (end === -1 && tokenChars[code] === 1) {
1545
+ if (start === -1)
1546
+ start = i;
1547
+ } else if (code === 32 || code === 9) {
1548
+ if (end === -1 && start !== -1)
1549
+ end = i;
1550
+ } else if (code === 59 || code === 44) {
1551
+ if (start === -1) {
1552
+ throw new SyntaxError(`Unexpected character at index ${i}`);
1553
+ }
1554
+ if (end === -1)
1555
+ end = i;
1556
+ push(params, header.slice(start, end), true);
1557
+ if (code === 44) {
1558
+ push(offers, extensionName, params);
1559
+ params = Object.create(null);
1560
+ extensionName = undefined;
1561
+ }
1562
+ start = end = -1;
1563
+ } else if (code === 61 && start !== -1 && end === -1) {
1564
+ paramName = header.slice(start, i);
1565
+ start = end = -1;
1566
+ } else {
1567
+ throw new SyntaxError(`Unexpected character at index ${i}`);
1568
+ }
1569
+ } else {
1570
+ if (isEscaping) {
1571
+ if (tokenChars[code] !== 1) {
1572
+ throw new SyntaxError(`Unexpected character at index ${i}`);
1573
+ }
1574
+ if (start === -1)
1575
+ start = i;
1576
+ else if (!mustUnescape)
1577
+ mustUnescape = true;
1578
+ isEscaping = false;
1579
+ } else if (inQuotes) {
1580
+ if (tokenChars[code] === 1) {
1581
+ if (start === -1)
1582
+ start = i;
1583
+ } else if (code === 34 && start !== -1) {
1584
+ inQuotes = false;
1585
+ end = i;
1586
+ } else if (code === 92) {
1587
+ isEscaping = true;
1588
+ } else {
1589
+ throw new SyntaxError(`Unexpected character at index ${i}`);
1590
+ }
1591
+ } else if (code === 34 && header.charCodeAt(i - 1) === 61) {
1592
+ inQuotes = true;
1593
+ } else if (end === -1 && tokenChars[code] === 1) {
1594
+ if (start === -1)
1595
+ start = i;
1596
+ } else if (start !== -1 && (code === 32 || code === 9)) {
1597
+ if (end === -1)
1598
+ end = i;
1599
+ } else if (code === 59 || code === 44) {
1600
+ if (start === -1) {
1601
+ throw new SyntaxError(`Unexpected character at index ${i}`);
1602
+ }
1603
+ if (end === -1)
1604
+ end = i;
1605
+ let value = header.slice(start, end);
1606
+ if (mustUnescape) {
1607
+ value = value.replace(/\\/g, "");
1608
+ mustUnescape = false;
1609
+ }
1610
+ push(params, paramName, value);
1611
+ if (code === 44) {
1612
+ push(offers, extensionName, params);
1613
+ params = Object.create(null);
1614
+ extensionName = undefined;
1615
+ }
1616
+ paramName = undefined;
1617
+ start = end = -1;
1618
+ } else {
1619
+ throw new SyntaxError(`Unexpected character at index ${i}`);
1620
+ }
1621
+ }
1622
+ }
1623
+ if (start === -1 || inQuotes || code === 32 || code === 9) {
1624
+ throw new SyntaxError("Unexpected end of input");
1625
+ }
1626
+ if (end === -1)
1627
+ end = i;
1628
+ const token = header.slice(start, end);
1629
+ if (extensionName === undefined) {
1630
+ push(offers, token, params);
1631
+ } else {
1632
+ if (paramName === undefined) {
1633
+ push(params, token, true);
1634
+ } else if (mustUnescape) {
1635
+ push(params, paramName, token.replace(/\\/g, ""));
1636
+ } else {
1637
+ push(params, paramName, token);
1638
+ }
1639
+ push(offers, extensionName, params);
1640
+ }
1641
+ return offers;
1642
+ }
1643
+ function format(extensions) {
1644
+ return Object.keys(extensions).map((extension) => {
1645
+ let configurations = extensions[extension];
1646
+ if (!Array.isArray(configurations))
1647
+ configurations = [configurations];
1648
+ return configurations.map((params) => {
1649
+ return [extension].concat(Object.keys(params).map((k) => {
1650
+ let values = params[k];
1651
+ if (!Array.isArray(values))
1652
+ values = [values];
1653
+ return values.map((v) => v === true ? k : `${k}=${v}`).join("; ");
1654
+ })).join("; ");
1655
+ }).join(", ");
1656
+ }).join(", ");
1657
+ }
1658
+ module.exports = { format, parse };
1659
+ });
1660
+
1661
+ // node_modules/ws/lib/websocket.js
1662
+ var require_websocket = __commonJS((exports, module) => {
1663
+ var EventEmitter = __require("events");
1664
+ var https = __require("https");
1665
+ var http = __require("http");
1666
+ var net = __require("net");
1667
+ var tls = __require("tls");
1668
+ var { randomBytes, createHash } = __require("crypto");
1669
+ var { Duplex, Readable } = __require("stream");
1670
+ var { URL: URL2 } = __require("url");
1671
+ var PerMessageDeflate = require_permessage_deflate();
1672
+ var Receiver = require_receiver();
1673
+ var Sender = require_sender();
1674
+ var { isBlob } = require_validation();
1675
+ var {
1676
+ BINARY_TYPES,
1677
+ EMPTY_BUFFER,
1678
+ GUID,
1679
+ kForOnEventAttribute,
1680
+ kListener,
1681
+ kStatusCode,
1682
+ kWebSocket,
1683
+ NOOP
1684
+ } = require_constants();
1685
+ var {
1686
+ EventTarget: { addEventListener, removeEventListener }
1687
+ } = require_event_target();
1688
+ var { format, parse } = require_extension();
1689
+ var { toBuffer } = require_buffer_util();
1690
+ var closeTimeout = 30 * 1000;
1691
+ var kAborted = Symbol("kAborted");
1692
+ var protocolVersions = [8, 13];
1693
+ var readyStates = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"];
1694
+ var subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
1695
+
1696
+ class WebSocket extends EventEmitter {
1697
+ constructor(address, protocols, options) {
1698
+ super();
1699
+ this._binaryType = BINARY_TYPES[0];
1700
+ this._closeCode = 1006;
1701
+ this._closeFrameReceived = false;
1702
+ this._closeFrameSent = false;
1703
+ this._closeMessage = EMPTY_BUFFER;
1704
+ this._closeTimer = null;
1705
+ this._errorEmitted = false;
1706
+ this._extensions = {};
1707
+ this._paused = false;
1708
+ this._protocol = "";
1709
+ this._readyState = WebSocket.CONNECTING;
1710
+ this._receiver = null;
1711
+ this._sender = null;
1712
+ this._socket = null;
1713
+ if (address !== null) {
1714
+ this._bufferedAmount = 0;
1715
+ this._isServer = false;
1716
+ this._redirects = 0;
1717
+ if (protocols === undefined) {
1718
+ protocols = [];
1719
+ } else if (!Array.isArray(protocols)) {
1720
+ if (typeof protocols === "object" && protocols !== null) {
1721
+ options = protocols;
1722
+ protocols = [];
1723
+ } else {
1724
+ protocols = [protocols];
1725
+ }
1726
+ }
1727
+ initAsClient(this, address, protocols, options);
1728
+ } else {
1729
+ this._autoPong = options.autoPong;
1730
+ this._isServer = true;
1731
+ }
1732
+ }
1733
+ get binaryType() {
1734
+ return this._binaryType;
1735
+ }
1736
+ set binaryType(type) {
1737
+ if (!BINARY_TYPES.includes(type))
1738
+ return;
1739
+ this._binaryType = type;
1740
+ if (this._receiver)
1741
+ this._receiver._binaryType = type;
1742
+ }
1743
+ get bufferedAmount() {
1744
+ if (!this._socket)
1745
+ return this._bufferedAmount;
1746
+ return this._socket._writableState.length + this._sender._bufferedBytes;
1747
+ }
1748
+ get extensions() {
1749
+ return Object.keys(this._extensions).join();
1750
+ }
1751
+ get isPaused() {
1752
+ return this._paused;
1753
+ }
1754
+ get onclose() {
1755
+ return null;
1756
+ }
1757
+ get onerror() {
1758
+ return null;
1759
+ }
1760
+ get onopen() {
1761
+ return null;
1762
+ }
1763
+ get onmessage() {
1764
+ return null;
1765
+ }
1766
+ get protocol() {
1767
+ return this._protocol;
1768
+ }
1769
+ get readyState() {
1770
+ return this._readyState;
1771
+ }
1772
+ get url() {
1773
+ return this._url;
1774
+ }
1775
+ setSocket(socket, head, options) {
1776
+ const receiver = new Receiver({
1777
+ allowSynchronousEvents: options.allowSynchronousEvents,
1778
+ binaryType: this.binaryType,
1779
+ extensions: this._extensions,
1780
+ isServer: this._isServer,
1781
+ maxPayload: options.maxPayload,
1782
+ skipUTF8Validation: options.skipUTF8Validation
1783
+ });
1784
+ const sender = new Sender(socket, this._extensions, options.generateMask);
1785
+ this._receiver = receiver;
1786
+ this._sender = sender;
1787
+ this._socket = socket;
1788
+ receiver[kWebSocket] = this;
1789
+ sender[kWebSocket] = this;
1790
+ socket[kWebSocket] = this;
1791
+ receiver.on("conclude", receiverOnConclude);
1792
+ receiver.on("drain", receiverOnDrain);
1793
+ receiver.on("error", receiverOnError);
1794
+ receiver.on("message", receiverOnMessage);
1795
+ receiver.on("ping", receiverOnPing);
1796
+ receiver.on("pong", receiverOnPong);
1797
+ sender.onerror = senderOnError;
1798
+ if (socket.setTimeout)
1799
+ socket.setTimeout(0);
1800
+ if (socket.setNoDelay)
1801
+ socket.setNoDelay();
1802
+ if (head.length > 0)
1803
+ socket.unshift(head);
1804
+ socket.on("close", socketOnClose);
1805
+ socket.on("data", socketOnData);
1806
+ socket.on("end", socketOnEnd);
1807
+ socket.on("error", socketOnError);
1808
+ this._readyState = WebSocket.OPEN;
1809
+ this.emit("open");
1810
+ }
1811
+ emitClose() {
1812
+ if (!this._socket) {
1813
+ this._readyState = WebSocket.CLOSED;
1814
+ this.emit("close", this._closeCode, this._closeMessage);
1815
+ return;
1816
+ }
1817
+ if (this._extensions[PerMessageDeflate.extensionName]) {
1818
+ this._extensions[PerMessageDeflate.extensionName].cleanup();
1819
+ }
1820
+ this._receiver.removeAllListeners();
1821
+ this._readyState = WebSocket.CLOSED;
1822
+ this.emit("close", this._closeCode, this._closeMessage);
1823
+ }
1824
+ close(code, data) {
1825
+ if (this.readyState === WebSocket.CLOSED)
1826
+ return;
1827
+ if (this.readyState === WebSocket.CONNECTING) {
1828
+ const msg = "WebSocket was closed before the connection was established";
1829
+ abortHandshake(this, this._req, msg);
1830
+ return;
1831
+ }
1832
+ if (this.readyState === WebSocket.CLOSING) {
1833
+ if (this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted)) {
1834
+ this._socket.end();
1835
+ }
1836
+ return;
1837
+ }
1838
+ this._readyState = WebSocket.CLOSING;
1839
+ this._sender.close(code, data, !this._isServer, (err) => {
1840
+ if (err)
1841
+ return;
1842
+ this._closeFrameSent = true;
1843
+ if (this._closeFrameReceived || this._receiver._writableState.errorEmitted) {
1844
+ this._socket.end();
1845
+ }
1846
+ });
1847
+ setCloseTimer(this);
1848
+ }
1849
+ pause() {
1850
+ if (this.readyState === WebSocket.CONNECTING || this.readyState === WebSocket.CLOSED) {
1851
+ return;
1852
+ }
1853
+ this._paused = true;
1854
+ this._socket.pause();
1855
+ }
1856
+ ping(data, mask, cb) {
1857
+ if (this.readyState === WebSocket.CONNECTING) {
1858
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
1859
+ }
1860
+ if (typeof data === "function") {
1861
+ cb = data;
1862
+ data = mask = undefined;
1863
+ } else if (typeof mask === "function") {
1864
+ cb = mask;
1865
+ mask = undefined;
1866
+ }
1867
+ if (typeof data === "number")
1868
+ data = data.toString();
1869
+ if (this.readyState !== WebSocket.OPEN) {
1870
+ sendAfterClose(this, data, cb);
1871
+ return;
1872
+ }
1873
+ if (mask === undefined)
1874
+ mask = !this._isServer;
1875
+ this._sender.ping(data || EMPTY_BUFFER, mask, cb);
1876
+ }
1877
+ pong(data, mask, cb) {
1878
+ if (this.readyState === WebSocket.CONNECTING) {
1879
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
1880
+ }
1881
+ if (typeof data === "function") {
1882
+ cb = data;
1883
+ data = mask = undefined;
1884
+ } else if (typeof mask === "function") {
1885
+ cb = mask;
1886
+ mask = undefined;
1887
+ }
1888
+ if (typeof data === "number")
1889
+ data = data.toString();
1890
+ if (this.readyState !== WebSocket.OPEN) {
1891
+ sendAfterClose(this, data, cb);
1892
+ return;
1893
+ }
1894
+ if (mask === undefined)
1895
+ mask = !this._isServer;
1896
+ this._sender.pong(data || EMPTY_BUFFER, mask, cb);
1897
+ }
1898
+ resume() {
1899
+ if (this.readyState === WebSocket.CONNECTING || this.readyState === WebSocket.CLOSED) {
1900
+ return;
1901
+ }
1902
+ this._paused = false;
1903
+ if (!this._receiver._writableState.needDrain)
1904
+ this._socket.resume();
1905
+ }
1906
+ send(data, options, cb) {
1907
+ if (this.readyState === WebSocket.CONNECTING) {
1908
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
1909
+ }
1910
+ if (typeof options === "function") {
1911
+ cb = options;
1912
+ options = {};
1913
+ }
1914
+ if (typeof data === "number")
1915
+ data = data.toString();
1916
+ if (this.readyState !== WebSocket.OPEN) {
1917
+ sendAfterClose(this, data, cb);
1918
+ return;
1919
+ }
1920
+ const opts = {
1921
+ binary: typeof data !== "string",
1922
+ mask: !this._isServer,
1923
+ compress: true,
1924
+ fin: true,
1925
+ ...options
1926
+ };
1927
+ if (!this._extensions[PerMessageDeflate.extensionName]) {
1928
+ opts.compress = false;
1929
+ }
1930
+ this._sender.send(data || EMPTY_BUFFER, opts, cb);
1931
+ }
1932
+ terminate() {
1933
+ if (this.readyState === WebSocket.CLOSED)
1934
+ return;
1935
+ if (this.readyState === WebSocket.CONNECTING) {
1936
+ const msg = "WebSocket was closed before the connection was established";
1937
+ abortHandshake(this, this._req, msg);
1938
+ return;
1939
+ }
1940
+ if (this._socket) {
1941
+ this._readyState = WebSocket.CLOSING;
1942
+ this._socket.destroy();
1943
+ }
1944
+ }
1945
+ }
1946
+ Object.defineProperty(WebSocket, "CONNECTING", {
1947
+ enumerable: true,
1948
+ value: readyStates.indexOf("CONNECTING")
1949
+ });
1950
+ Object.defineProperty(WebSocket.prototype, "CONNECTING", {
1951
+ enumerable: true,
1952
+ value: readyStates.indexOf("CONNECTING")
1953
+ });
1954
+ Object.defineProperty(WebSocket, "OPEN", {
1955
+ enumerable: true,
1956
+ value: readyStates.indexOf("OPEN")
1957
+ });
1958
+ Object.defineProperty(WebSocket.prototype, "OPEN", {
1959
+ enumerable: true,
1960
+ value: readyStates.indexOf("OPEN")
1961
+ });
1962
+ Object.defineProperty(WebSocket, "CLOSING", {
1963
+ enumerable: true,
1964
+ value: readyStates.indexOf("CLOSING")
1965
+ });
1966
+ Object.defineProperty(WebSocket.prototype, "CLOSING", {
1967
+ enumerable: true,
1968
+ value: readyStates.indexOf("CLOSING")
1969
+ });
1970
+ Object.defineProperty(WebSocket, "CLOSED", {
1971
+ enumerable: true,
1972
+ value: readyStates.indexOf("CLOSED")
1973
+ });
1974
+ Object.defineProperty(WebSocket.prototype, "CLOSED", {
1975
+ enumerable: true,
1976
+ value: readyStates.indexOf("CLOSED")
1977
+ });
1978
+ [
1979
+ "binaryType",
1980
+ "bufferedAmount",
1981
+ "extensions",
1982
+ "isPaused",
1983
+ "protocol",
1984
+ "readyState",
1985
+ "url"
1986
+ ].forEach((property) => {
1987
+ Object.defineProperty(WebSocket.prototype, property, { enumerable: true });
1988
+ });
1989
+ ["open", "error", "close", "message"].forEach((method) => {
1990
+ Object.defineProperty(WebSocket.prototype, `on${method}`, {
1991
+ enumerable: true,
1992
+ get() {
1993
+ for (const listener of this.listeners(method)) {
1994
+ if (listener[kForOnEventAttribute])
1995
+ return listener[kListener];
1996
+ }
1997
+ return null;
1998
+ },
1999
+ set(handler) {
2000
+ for (const listener of this.listeners(method)) {
2001
+ if (listener[kForOnEventAttribute]) {
2002
+ this.removeListener(method, listener);
2003
+ break;
2004
+ }
2005
+ }
2006
+ if (typeof handler !== "function")
2007
+ return;
2008
+ this.addEventListener(method, handler, {
2009
+ [kForOnEventAttribute]: true
2010
+ });
2011
+ }
2012
+ });
2013
+ });
2014
+ WebSocket.prototype.addEventListener = addEventListener;
2015
+ WebSocket.prototype.removeEventListener = removeEventListener;
2016
+ module.exports = WebSocket;
2017
+ function initAsClient(websocket, address, protocols, options) {
2018
+ const opts = {
2019
+ allowSynchronousEvents: true,
2020
+ autoPong: true,
2021
+ protocolVersion: protocolVersions[1],
2022
+ maxPayload: 100 * 1024 * 1024,
2023
+ skipUTF8Validation: false,
2024
+ perMessageDeflate: true,
2025
+ followRedirects: false,
2026
+ maxRedirects: 10,
2027
+ ...options,
2028
+ socketPath: undefined,
2029
+ hostname: undefined,
2030
+ protocol: undefined,
2031
+ timeout: undefined,
2032
+ method: "GET",
2033
+ host: undefined,
2034
+ path: undefined,
2035
+ port: undefined
2036
+ };
2037
+ websocket._autoPong = opts.autoPong;
2038
+ if (!protocolVersions.includes(opts.protocolVersion)) {
2039
+ throw new RangeError(`Unsupported protocol version: ${opts.protocolVersion} ` + `(supported versions: ${protocolVersions.join(", ")})`);
2040
+ }
2041
+ let parsedUrl;
2042
+ if (address instanceof URL2) {
2043
+ parsedUrl = address;
2044
+ } else {
2045
+ try {
2046
+ parsedUrl = new URL2(address);
2047
+ } catch (e) {
2048
+ throw new SyntaxError(`Invalid URL: ${address}`);
2049
+ }
2050
+ }
2051
+ if (parsedUrl.protocol === "http:") {
2052
+ parsedUrl.protocol = "ws:";
2053
+ } else if (parsedUrl.protocol === "https:") {
2054
+ parsedUrl.protocol = "wss:";
2055
+ }
2056
+ websocket._url = parsedUrl.href;
2057
+ const isSecure = parsedUrl.protocol === "wss:";
2058
+ const isIpcUrl = parsedUrl.protocol === "ws+unix:";
2059
+ let invalidUrlMessage;
2060
+ if (parsedUrl.protocol !== "ws:" && !isSecure && !isIpcUrl) {
2061
+ invalidUrlMessage = `The URL's protocol must be one of "ws:", "wss:", ` + '"http:", "https:", or "ws+unix:"';
2062
+ } else if (isIpcUrl && !parsedUrl.pathname) {
2063
+ invalidUrlMessage = "The URL's pathname is empty";
2064
+ } else if (parsedUrl.hash) {
2065
+ invalidUrlMessage = "The URL contains a fragment identifier";
2066
+ }
2067
+ if (invalidUrlMessage) {
2068
+ const err = new SyntaxError(invalidUrlMessage);
2069
+ if (websocket._redirects === 0) {
2070
+ throw err;
2071
+ } else {
2072
+ emitErrorAndClose(websocket, err);
2073
+ return;
2074
+ }
2075
+ }
2076
+ const defaultPort = isSecure ? 443 : 80;
2077
+ const key = randomBytes(16).toString("base64");
2078
+ const request = isSecure ? https.request : http.request;
2079
+ const protocolSet = new Set;
2080
+ let perMessageDeflate;
2081
+ opts.createConnection = opts.createConnection || (isSecure ? tlsConnect : netConnect);
2082
+ opts.defaultPort = opts.defaultPort || defaultPort;
2083
+ opts.port = parsedUrl.port || defaultPort;
2084
+ opts.host = parsedUrl.hostname.startsWith("[") ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname;
2085
+ opts.headers = {
2086
+ ...opts.headers,
2087
+ "Sec-WebSocket-Version": opts.protocolVersion,
2088
+ "Sec-WebSocket-Key": key,
2089
+ Connection: "Upgrade",
2090
+ Upgrade: "websocket"
2091
+ };
2092
+ opts.path = parsedUrl.pathname + parsedUrl.search;
2093
+ opts.timeout = opts.handshakeTimeout;
2094
+ if (opts.perMessageDeflate) {
2095
+ perMessageDeflate = new PerMessageDeflate(opts.perMessageDeflate !== true ? opts.perMessageDeflate : {}, false, opts.maxPayload);
2096
+ opts.headers["Sec-WebSocket-Extensions"] = format({
2097
+ [PerMessageDeflate.extensionName]: perMessageDeflate.offer()
2098
+ });
2099
+ }
2100
+ if (protocols.length) {
2101
+ for (const protocol of protocols) {
2102
+ if (typeof protocol !== "string" || !subprotocolRegex.test(protocol) || protocolSet.has(protocol)) {
2103
+ throw new SyntaxError("An invalid or duplicated subprotocol was specified");
2104
+ }
2105
+ protocolSet.add(protocol);
2106
+ }
2107
+ opts.headers["Sec-WebSocket-Protocol"] = protocols.join(",");
2108
+ }
2109
+ if (opts.origin) {
2110
+ if (opts.protocolVersion < 13) {
2111
+ opts.headers["Sec-WebSocket-Origin"] = opts.origin;
2112
+ } else {
2113
+ opts.headers.Origin = opts.origin;
2114
+ }
2115
+ }
2116
+ if (parsedUrl.username || parsedUrl.password) {
2117
+ opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
2118
+ }
2119
+ if (isIpcUrl) {
2120
+ const parts = opts.path.split(":");
2121
+ opts.socketPath = parts[0];
2122
+ opts.path = parts[1];
2123
+ }
2124
+ let req;
2125
+ if (opts.followRedirects) {
2126
+ if (websocket._redirects === 0) {
2127
+ websocket._originalIpc = isIpcUrl;
2128
+ websocket._originalSecure = isSecure;
2129
+ websocket._originalHostOrSocketPath = isIpcUrl ? opts.socketPath : parsedUrl.host;
2130
+ const headers = options && options.headers;
2131
+ options = { ...options, headers: {} };
2132
+ if (headers) {
2133
+ for (const [key2, value] of Object.entries(headers)) {
2134
+ options.headers[key2.toLowerCase()] = value;
2135
+ }
2136
+ }
2137
+ } else if (websocket.listenerCount("redirect") === 0) {
2138
+ const isSameHost = isIpcUrl ? websocket._originalIpc ? opts.socketPath === websocket._originalHostOrSocketPath : false : websocket._originalIpc ? false : parsedUrl.host === websocket._originalHostOrSocketPath;
2139
+ if (!isSameHost || websocket._originalSecure && !isSecure) {
2140
+ delete opts.headers.authorization;
2141
+ delete opts.headers.cookie;
2142
+ if (!isSameHost)
2143
+ delete opts.headers.host;
2144
+ opts.auth = undefined;
2145
+ }
2146
+ }
2147
+ if (opts.auth && !options.headers.authorization) {
2148
+ options.headers.authorization = "Basic " + Buffer.from(opts.auth).toString("base64");
2149
+ }
2150
+ req = websocket._req = request(opts);
2151
+ if (websocket._redirects) {
2152
+ websocket.emit("redirect", websocket.url, req);
2153
+ }
2154
+ } else {
2155
+ req = websocket._req = request(opts);
2156
+ }
2157
+ if (opts.timeout) {
2158
+ req.on("timeout", () => {
2159
+ abortHandshake(websocket, req, "Opening handshake has timed out");
2160
+ });
2161
+ }
2162
+ req.on("error", (err) => {
2163
+ if (req === null || req[kAborted])
2164
+ return;
2165
+ req = websocket._req = null;
2166
+ emitErrorAndClose(websocket, err);
2167
+ });
2168
+ req.on("response", (res) => {
2169
+ const location = res.headers.location;
2170
+ const statusCode = res.statusCode;
2171
+ if (location && opts.followRedirects && statusCode >= 300 && statusCode < 400) {
2172
+ if (++websocket._redirects > opts.maxRedirects) {
2173
+ abortHandshake(websocket, req, "Maximum redirects exceeded");
2174
+ return;
2175
+ }
2176
+ req.abort();
2177
+ let addr;
2178
+ try {
2179
+ addr = new URL2(location, address);
2180
+ } catch (e) {
2181
+ const err = new SyntaxError(`Invalid URL: ${location}`);
2182
+ emitErrorAndClose(websocket, err);
2183
+ return;
2184
+ }
2185
+ initAsClient(websocket, addr, protocols, options);
2186
+ } else if (!websocket.emit("unexpected-response", req, res)) {
2187
+ abortHandshake(websocket, req, `Unexpected server response: ${res.statusCode}`);
2188
+ }
2189
+ });
2190
+ req.on("upgrade", (res, socket, head) => {
2191
+ websocket.emit("upgrade", res);
2192
+ if (websocket.readyState !== WebSocket.CONNECTING)
2193
+ return;
2194
+ req = websocket._req = null;
2195
+ const upgrade = res.headers.upgrade;
2196
+ if (upgrade === undefined || upgrade.toLowerCase() !== "websocket") {
2197
+ abortHandshake(websocket, socket, "Invalid Upgrade header");
2198
+ return;
2199
+ }
2200
+ const digest = createHash("sha1").update(key + GUID).digest("base64");
2201
+ if (res.headers["sec-websocket-accept"] !== digest) {
2202
+ abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
2203
+ return;
2204
+ }
2205
+ const serverProt = res.headers["sec-websocket-protocol"];
2206
+ let protError;
2207
+ if (serverProt !== undefined) {
2208
+ if (!protocolSet.size) {
2209
+ protError = "Server sent a subprotocol but none was requested";
2210
+ } else if (!protocolSet.has(serverProt)) {
2211
+ protError = "Server sent an invalid subprotocol";
2212
+ }
2213
+ } else if (protocolSet.size) {
2214
+ protError = "Server sent no subprotocol";
2215
+ }
2216
+ if (protError) {
2217
+ abortHandshake(websocket, socket, protError);
2218
+ return;
2219
+ }
2220
+ if (serverProt)
2221
+ websocket._protocol = serverProt;
2222
+ const secWebSocketExtensions = res.headers["sec-websocket-extensions"];
2223
+ if (secWebSocketExtensions !== undefined) {
2224
+ if (!perMessageDeflate) {
2225
+ const message = "Server sent a Sec-WebSocket-Extensions header but no extension " + "was requested";
2226
+ abortHandshake(websocket, socket, message);
2227
+ return;
2228
+ }
2229
+ let extensions;
2230
+ try {
2231
+ extensions = parse(secWebSocketExtensions);
2232
+ } catch (err) {
2233
+ const message = "Invalid Sec-WebSocket-Extensions header";
2234
+ abortHandshake(websocket, socket, message);
2235
+ return;
2236
+ }
2237
+ const extensionNames = Object.keys(extensions);
2238
+ if (extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate.extensionName) {
2239
+ const message = "Server indicated an extension that was not requested";
2240
+ abortHandshake(websocket, socket, message);
2241
+ return;
2242
+ }
2243
+ try {
2244
+ perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]);
2245
+ } catch (err) {
2246
+ const message = "Invalid Sec-WebSocket-Extensions header";
2247
+ abortHandshake(websocket, socket, message);
2248
+ return;
2249
+ }
2250
+ websocket._extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
2251
+ }
2252
+ websocket.setSocket(socket, head, {
2253
+ allowSynchronousEvents: opts.allowSynchronousEvents,
2254
+ generateMask: opts.generateMask,
2255
+ maxPayload: opts.maxPayload,
2256
+ skipUTF8Validation: opts.skipUTF8Validation
2257
+ });
2258
+ });
2259
+ if (opts.finishRequest) {
2260
+ opts.finishRequest(req, websocket);
2261
+ } else {
2262
+ req.end();
2263
+ }
2264
+ }
2265
+ function emitErrorAndClose(websocket, err) {
2266
+ websocket._readyState = WebSocket.CLOSING;
2267
+ websocket._errorEmitted = true;
2268
+ websocket.emit("error", err);
2269
+ websocket.emitClose();
2270
+ }
2271
+ function netConnect(options) {
2272
+ options.path = options.socketPath;
2273
+ return net.connect(options);
2274
+ }
2275
+ function tlsConnect(options) {
2276
+ options.path = undefined;
2277
+ if (!options.servername && options.servername !== "") {
2278
+ options.servername = net.isIP(options.host) ? "" : options.host;
2279
+ }
2280
+ return tls.connect(options);
2281
+ }
2282
+ function abortHandshake(websocket, stream, message) {
2283
+ websocket._readyState = WebSocket.CLOSING;
2284
+ const err = new Error(message);
2285
+ Error.captureStackTrace(err, abortHandshake);
2286
+ if (stream.setHeader) {
2287
+ stream[kAborted] = true;
2288
+ stream.abort();
2289
+ if (stream.socket && !stream.socket.destroyed) {
2290
+ stream.socket.destroy();
2291
+ }
2292
+ process.nextTick(emitErrorAndClose, websocket, err);
2293
+ } else {
2294
+ stream.destroy(err);
2295
+ stream.once("error", websocket.emit.bind(websocket, "error"));
2296
+ stream.once("close", websocket.emitClose.bind(websocket));
2297
+ }
2298
+ }
2299
+ function sendAfterClose(websocket, data, cb) {
2300
+ if (data) {
2301
+ const length = isBlob(data) ? data.size : toBuffer(data).length;
2302
+ if (websocket._socket)
2303
+ websocket._sender._bufferedBytes += length;
2304
+ else
2305
+ websocket._bufferedAmount += length;
2306
+ }
2307
+ if (cb) {
2308
+ const err = new Error(`WebSocket is not open: readyState ${websocket.readyState} ` + `(${readyStates[websocket.readyState]})`);
2309
+ process.nextTick(cb, err);
2310
+ }
2311
+ }
2312
+ function receiverOnConclude(code, reason) {
2313
+ const websocket = this[kWebSocket];
2314
+ websocket._closeFrameReceived = true;
2315
+ websocket._closeMessage = reason;
2316
+ websocket._closeCode = code;
2317
+ if (websocket._socket[kWebSocket] === undefined)
2318
+ return;
2319
+ websocket._socket.removeListener("data", socketOnData);
2320
+ process.nextTick(resume, websocket._socket);
2321
+ if (code === 1005)
2322
+ websocket.close();
2323
+ else
2324
+ websocket.close(code, reason);
2325
+ }
2326
+ function receiverOnDrain() {
2327
+ const websocket = this[kWebSocket];
2328
+ if (!websocket.isPaused)
2329
+ websocket._socket.resume();
2330
+ }
2331
+ function receiverOnError(err) {
2332
+ const websocket = this[kWebSocket];
2333
+ if (websocket._socket[kWebSocket] !== undefined) {
2334
+ websocket._socket.removeListener("data", socketOnData);
2335
+ process.nextTick(resume, websocket._socket);
2336
+ websocket.close(err[kStatusCode]);
2337
+ }
2338
+ if (!websocket._errorEmitted) {
2339
+ websocket._errorEmitted = true;
2340
+ websocket.emit("error", err);
2341
+ }
2342
+ }
2343
+ function receiverOnFinish() {
2344
+ this[kWebSocket].emitClose();
2345
+ }
2346
+ function receiverOnMessage(data, isBinary) {
2347
+ this[kWebSocket].emit("message", data, isBinary);
2348
+ }
2349
+ function receiverOnPing(data) {
2350
+ const websocket = this[kWebSocket];
2351
+ if (websocket._autoPong)
2352
+ websocket.pong(data, !this._isServer, NOOP);
2353
+ websocket.emit("ping", data);
2354
+ }
2355
+ function receiverOnPong(data) {
2356
+ this[kWebSocket].emit("pong", data);
2357
+ }
2358
+ function resume(stream) {
2359
+ stream.resume();
2360
+ }
2361
+ function senderOnError(err) {
2362
+ const websocket = this[kWebSocket];
2363
+ if (websocket.readyState === WebSocket.CLOSED)
2364
+ return;
2365
+ if (websocket.readyState === WebSocket.OPEN) {
2366
+ websocket._readyState = WebSocket.CLOSING;
2367
+ setCloseTimer(websocket);
2368
+ }
2369
+ this._socket.end();
2370
+ if (!websocket._errorEmitted) {
2371
+ websocket._errorEmitted = true;
2372
+ websocket.emit("error", err);
2373
+ }
2374
+ }
2375
+ function setCloseTimer(websocket) {
2376
+ websocket._closeTimer = setTimeout(websocket._socket.destroy.bind(websocket._socket), closeTimeout);
2377
+ }
2378
+ function socketOnClose() {
2379
+ const websocket = this[kWebSocket];
2380
+ this.removeListener("close", socketOnClose);
2381
+ this.removeListener("data", socketOnData);
2382
+ this.removeListener("end", socketOnEnd);
2383
+ websocket._readyState = WebSocket.CLOSING;
2384
+ let chunk;
2385
+ if (!this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && (chunk = websocket._socket.read()) !== null) {
2386
+ websocket._receiver.write(chunk);
2387
+ }
2388
+ websocket._receiver.end();
2389
+ this[kWebSocket] = undefined;
2390
+ clearTimeout(websocket._closeTimer);
2391
+ if (websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted) {
2392
+ websocket.emitClose();
2393
+ } else {
2394
+ websocket._receiver.on("error", receiverOnFinish);
2395
+ websocket._receiver.on("finish", receiverOnFinish);
2396
+ }
2397
+ }
2398
+ function socketOnData(chunk) {
2399
+ if (!this[kWebSocket]._receiver.write(chunk)) {
2400
+ this.pause();
2401
+ }
2402
+ }
2403
+ function socketOnEnd() {
2404
+ const websocket = this[kWebSocket];
2405
+ websocket._readyState = WebSocket.CLOSING;
2406
+ websocket._receiver.end();
2407
+ this.end();
2408
+ }
2409
+ function socketOnError() {
2410
+ const websocket = this[kWebSocket];
2411
+ this.removeListener("error", socketOnError);
2412
+ this.on("error", NOOP);
2413
+ if (websocket) {
2414
+ websocket._readyState = WebSocket.CLOSING;
2415
+ this.destroy();
2416
+ }
2417
+ }
2418
+ });
2419
+
2420
+ // node_modules/ws/lib/stream.js
2421
+ var require_stream = __commonJS((exports, module) => {
2422
+ var WebSocket = require_websocket();
2423
+ var { Duplex } = __require("stream");
2424
+ function emitClose(stream) {
2425
+ stream.emit("close");
2426
+ }
2427
+ function duplexOnEnd() {
2428
+ if (!this.destroyed && this._writableState.finished) {
2429
+ this.destroy();
2430
+ }
2431
+ }
2432
+ function duplexOnError(err) {
2433
+ this.removeListener("error", duplexOnError);
2434
+ this.destroy();
2435
+ if (this.listenerCount("error") === 0) {
2436
+ this.emit("error", err);
2437
+ }
2438
+ }
2439
+ function createWebSocketStream(ws, options) {
2440
+ let terminateOnDestroy = true;
2441
+ const duplex = new Duplex({
2442
+ ...options,
2443
+ autoDestroy: false,
2444
+ emitClose: false,
2445
+ objectMode: false,
2446
+ writableObjectMode: false
2447
+ });
2448
+ ws.on("message", function message(msg, isBinary) {
2449
+ const data = !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;
2450
+ if (!duplex.push(data))
2451
+ ws.pause();
2452
+ });
2453
+ ws.once("error", function error(err) {
2454
+ if (duplex.destroyed)
2455
+ return;
2456
+ terminateOnDestroy = false;
2457
+ duplex.destroy(err);
2458
+ });
2459
+ ws.once("close", function close() {
2460
+ if (duplex.destroyed)
2461
+ return;
2462
+ duplex.push(null);
2463
+ });
2464
+ duplex._destroy = function(err, callback) {
2465
+ if (ws.readyState === ws.CLOSED) {
2466
+ callback(err);
2467
+ process.nextTick(emitClose, duplex);
2468
+ return;
2469
+ }
2470
+ let called = false;
2471
+ ws.once("error", function error(err2) {
2472
+ called = true;
2473
+ callback(err2);
2474
+ });
2475
+ ws.once("close", function close() {
2476
+ if (!called)
2477
+ callback(err);
2478
+ process.nextTick(emitClose, duplex);
2479
+ });
2480
+ if (terminateOnDestroy)
2481
+ ws.terminate();
2482
+ };
2483
+ duplex._final = function(callback) {
2484
+ if (ws.readyState === ws.CONNECTING) {
2485
+ ws.once("open", function open() {
2486
+ duplex._final(callback);
2487
+ });
2488
+ return;
2489
+ }
2490
+ if (ws._socket === null)
2491
+ return;
2492
+ if (ws._socket._writableState.finished) {
2493
+ callback();
2494
+ if (duplex._readableState.endEmitted)
2495
+ duplex.destroy();
2496
+ } else {
2497
+ ws._socket.once("finish", function finish() {
2498
+ callback();
2499
+ });
2500
+ ws.close();
2501
+ }
2502
+ };
2503
+ duplex._read = function() {
2504
+ if (ws.isPaused)
2505
+ ws.resume();
2506
+ };
2507
+ duplex._write = function(chunk, encoding, callback) {
2508
+ if (ws.readyState === ws.CONNECTING) {
2509
+ ws.once("open", function open() {
2510
+ duplex._write(chunk, encoding, callback);
2511
+ });
2512
+ return;
2513
+ }
2514
+ ws.send(chunk, callback);
2515
+ };
2516
+ duplex.on("end", duplexOnEnd);
2517
+ duplex.on("error", duplexOnError);
2518
+ return duplex;
2519
+ }
2520
+ module.exports = createWebSocketStream;
2521
+ });
2522
+
2523
+ // node_modules/ws/lib/subprotocol.js
2524
+ var require_subprotocol = __commonJS((exports, module) => {
2525
+ var { tokenChars } = require_validation();
2526
+ function parse(header) {
2527
+ const protocols = new Set;
2528
+ let start = -1;
2529
+ let end = -1;
2530
+ let i = 0;
2531
+ for (i;i < header.length; i++) {
2532
+ const code = header.charCodeAt(i);
2533
+ if (end === -1 && tokenChars[code] === 1) {
2534
+ if (start === -1)
2535
+ start = i;
2536
+ } else if (i !== 0 && (code === 32 || code === 9)) {
2537
+ if (end === -1 && start !== -1)
2538
+ end = i;
2539
+ } else if (code === 44) {
2540
+ if (start === -1) {
2541
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2542
+ }
2543
+ if (end === -1)
2544
+ end = i;
2545
+ const protocol2 = header.slice(start, end);
2546
+ if (protocols.has(protocol2)) {
2547
+ throw new SyntaxError(`The "${protocol2}" subprotocol is duplicated`);
2548
+ }
2549
+ protocols.add(protocol2);
2550
+ start = end = -1;
2551
+ } else {
2552
+ throw new SyntaxError(`Unexpected character at index ${i}`);
2553
+ }
2554
+ }
2555
+ if (start === -1 || end !== -1) {
2556
+ throw new SyntaxError("Unexpected end of input");
2557
+ }
2558
+ const protocol = header.slice(start, i);
2559
+ if (protocols.has(protocol)) {
2560
+ throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
2561
+ }
2562
+ protocols.add(protocol);
2563
+ return protocols;
2564
+ }
2565
+ module.exports = { parse };
2566
+ });
2567
+
2568
+ // node_modules/ws/lib/websocket-server.js
2569
+ var require_websocket_server = __commonJS((exports, module) => {
2570
+ var EventEmitter = __require("events");
2571
+ var http = __require("http");
2572
+ var { Duplex } = __require("stream");
2573
+ var { createHash } = __require("crypto");
2574
+ var extension = require_extension();
2575
+ var PerMessageDeflate = require_permessage_deflate();
2576
+ var subprotocol = require_subprotocol();
2577
+ var WebSocket = require_websocket();
2578
+ var { GUID, kWebSocket } = require_constants();
2579
+ var keyRegex = /^[+/0-9A-Za-z]{22}==$/;
2580
+ var RUNNING = 0;
2581
+ var CLOSING = 1;
2582
+ var CLOSED = 2;
2583
+
2584
+ class WebSocketServer extends EventEmitter {
2585
+ constructor(options, callback) {
2586
+ super();
2587
+ options = {
2588
+ allowSynchronousEvents: true,
2589
+ autoPong: true,
2590
+ maxPayload: 100 * 1024 * 1024,
2591
+ skipUTF8Validation: false,
2592
+ perMessageDeflate: false,
2593
+ handleProtocols: null,
2594
+ clientTracking: true,
2595
+ verifyClient: null,
2596
+ noServer: false,
2597
+ backlog: null,
2598
+ server: null,
2599
+ host: null,
2600
+ path: null,
2601
+ port: null,
2602
+ WebSocket,
2603
+ ...options
2604
+ };
2605
+ if (options.port == null && !options.server && !options.noServer || options.port != null && (options.server || options.noServer) || options.server && options.noServer) {
2606
+ throw new TypeError('One and only one of the "port", "server", or "noServer" options ' + "must be specified");
2607
+ }
2608
+ if (options.port != null) {
2609
+ this._server = http.createServer((req, res) => {
2610
+ const body = http.STATUS_CODES[426];
2611
+ res.writeHead(426, {
2612
+ "Content-Length": body.length,
2613
+ "Content-Type": "text/plain"
2614
+ });
2615
+ res.end(body);
2616
+ });
2617
+ this._server.listen(options.port, options.host, options.backlog, callback);
2618
+ } else if (options.server) {
2619
+ this._server = options.server;
2620
+ }
2621
+ if (this._server) {
2622
+ const emitConnection = this.emit.bind(this, "connection");
2623
+ this._removeListeners = addListeners(this._server, {
2624
+ listening: this.emit.bind(this, "listening"),
2625
+ error: this.emit.bind(this, "error"),
2626
+ upgrade: (req, socket, head) => {
2627
+ this.handleUpgrade(req, socket, head, emitConnection);
2628
+ }
2629
+ });
2630
+ }
2631
+ if (options.perMessageDeflate === true)
2632
+ options.perMessageDeflate = {};
2633
+ if (options.clientTracking) {
2634
+ this.clients = new Set;
2635
+ this._shouldEmitClose = false;
2636
+ }
2637
+ this.options = options;
2638
+ this._state = RUNNING;
2639
+ }
2640
+ address() {
2641
+ if (this.options.noServer) {
2642
+ throw new Error('The server is operating in "noServer" mode');
2643
+ }
2644
+ if (!this._server)
2645
+ return null;
2646
+ return this._server.address();
2647
+ }
2648
+ close(cb) {
2649
+ if (this._state === CLOSED) {
2650
+ if (cb) {
2651
+ this.once("close", () => {
2652
+ cb(new Error("The server is not running"));
2653
+ });
2654
+ }
2655
+ process.nextTick(emitClose, this);
2656
+ return;
2657
+ }
2658
+ if (cb)
2659
+ this.once("close", cb);
2660
+ if (this._state === CLOSING)
2661
+ return;
2662
+ this._state = CLOSING;
2663
+ if (this.options.noServer || this.options.server) {
2664
+ if (this._server) {
2665
+ this._removeListeners();
2666
+ this._removeListeners = this._server = null;
2667
+ }
2668
+ if (this.clients) {
2669
+ if (!this.clients.size) {
2670
+ process.nextTick(emitClose, this);
2671
+ } else {
2672
+ this._shouldEmitClose = true;
2673
+ }
2674
+ } else {
2675
+ process.nextTick(emitClose, this);
2676
+ }
2677
+ } else {
2678
+ const server = this._server;
2679
+ this._removeListeners();
2680
+ this._removeListeners = this._server = null;
2681
+ server.close(() => {
2682
+ emitClose(this);
2683
+ });
2684
+ }
2685
+ }
2686
+ shouldHandle(req) {
2687
+ if (this.options.path) {
2688
+ const index = req.url.indexOf("?");
2689
+ const pathname = index !== -1 ? req.url.slice(0, index) : req.url;
2690
+ if (pathname !== this.options.path)
2691
+ return false;
2692
+ }
2693
+ return true;
2694
+ }
2695
+ handleUpgrade(req, socket, head, cb) {
2696
+ socket.on("error", socketOnError);
2697
+ const key = req.headers["sec-websocket-key"];
2698
+ const upgrade = req.headers.upgrade;
2699
+ const version = +req.headers["sec-websocket-version"];
2700
+ if (req.method !== "GET") {
2701
+ const message = "Invalid HTTP method";
2702
+ abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);
2703
+ return;
2704
+ }
2705
+ if (upgrade === undefined || upgrade.toLowerCase() !== "websocket") {
2706
+ const message = "Invalid Upgrade header";
2707
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
2708
+ return;
2709
+ }
2710
+ if (key === undefined || !keyRegex.test(key)) {
2711
+ const message = "Missing or invalid Sec-WebSocket-Key header";
2712
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
2713
+ return;
2714
+ }
2715
+ if (version !== 13 && version !== 8) {
2716
+ const message = "Missing or invalid Sec-WebSocket-Version header";
2717
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message, {
2718
+ "Sec-WebSocket-Version": "13, 8"
2719
+ });
2720
+ return;
2721
+ }
2722
+ if (!this.shouldHandle(req)) {
2723
+ abortHandshake(socket, 400);
2724
+ return;
2725
+ }
2726
+ const secWebSocketProtocol = req.headers["sec-websocket-protocol"];
2727
+ let protocols = new Set;
2728
+ if (secWebSocketProtocol !== undefined) {
2729
+ try {
2730
+ protocols = subprotocol.parse(secWebSocketProtocol);
2731
+ } catch (err) {
2732
+ const message = "Invalid Sec-WebSocket-Protocol header";
2733
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
2734
+ return;
2735
+ }
2736
+ }
2737
+ const secWebSocketExtensions = req.headers["sec-websocket-extensions"];
2738
+ const extensions = {};
2739
+ if (this.options.perMessageDeflate && secWebSocketExtensions !== undefined) {
2740
+ const perMessageDeflate = new PerMessageDeflate(this.options.perMessageDeflate, true, this.options.maxPayload);
2741
+ try {
2742
+ const offers = extension.parse(secWebSocketExtensions);
2743
+ if (offers[PerMessageDeflate.extensionName]) {
2744
+ perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);
2745
+ extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
2746
+ }
2747
+ } catch (err) {
2748
+ const message = "Invalid or unacceptable Sec-WebSocket-Extensions header";
2749
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
2750
+ return;
2751
+ }
2752
+ }
2753
+ if (this.options.verifyClient) {
2754
+ const info = {
2755
+ origin: req.headers[`${version === 8 ? "sec-websocket-origin" : "origin"}`],
2756
+ secure: !!(req.socket.authorized || req.socket.encrypted),
2757
+ req
2758
+ };
2759
+ if (this.options.verifyClient.length === 2) {
2760
+ this.options.verifyClient(info, (verified, code, message, headers) => {
2761
+ if (!verified) {
2762
+ return abortHandshake(socket, code || 401, message, headers);
2763
+ }
2764
+ this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
2765
+ });
2766
+ return;
2767
+ }
2768
+ if (!this.options.verifyClient(info))
2769
+ return abortHandshake(socket, 401);
2770
+ }
2771
+ this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
2772
+ }
2773
+ completeUpgrade(extensions, key, protocols, req, socket, head, cb) {
2774
+ if (!socket.readable || !socket.writable)
2775
+ return socket.destroy();
2776
+ if (socket[kWebSocket]) {
2777
+ throw new Error("server.handleUpgrade() was called more than once with the same " + "socket, possibly due to a misconfiguration");
2778
+ }
2779
+ if (this._state > RUNNING)
2780
+ return abortHandshake(socket, 503);
2781
+ const digest = createHash("sha1").update(key + GUID).digest("base64");
2782
+ const headers = [
2783
+ "HTTP/1.1 101 Switching Protocols",
2784
+ "Upgrade: websocket",
2785
+ "Connection: Upgrade",
2786
+ `Sec-WebSocket-Accept: ${digest}`
2787
+ ];
2788
+ const ws = new this.options.WebSocket(null, undefined, this.options);
2789
+ if (protocols.size) {
2790
+ const protocol = this.options.handleProtocols ? this.options.handleProtocols(protocols, req) : protocols.values().next().value;
2791
+ if (protocol) {
2792
+ headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
2793
+ ws._protocol = protocol;
2794
+ }
2795
+ }
2796
+ if (extensions[PerMessageDeflate.extensionName]) {
2797
+ const params = extensions[PerMessageDeflate.extensionName].params;
2798
+ const value = extension.format({
2799
+ [PerMessageDeflate.extensionName]: [params]
2800
+ });
2801
+ headers.push(`Sec-WebSocket-Extensions: ${value}`);
2802
+ ws._extensions = extensions;
2803
+ }
2804
+ this.emit("headers", headers, req);
2805
+ socket.write(headers.concat(`\r
2806
+ `).join(`\r
2807
+ `));
2808
+ socket.removeListener("error", socketOnError);
2809
+ ws.setSocket(socket, head, {
2810
+ allowSynchronousEvents: this.options.allowSynchronousEvents,
2811
+ maxPayload: this.options.maxPayload,
2812
+ skipUTF8Validation: this.options.skipUTF8Validation
2813
+ });
2814
+ if (this.clients) {
2815
+ this.clients.add(ws);
2816
+ ws.on("close", () => {
2817
+ this.clients.delete(ws);
2818
+ if (this._shouldEmitClose && !this.clients.size) {
2819
+ process.nextTick(emitClose, this);
2820
+ }
2821
+ });
2822
+ }
2823
+ cb(ws, req);
2824
+ }
2825
+ }
2826
+ module.exports = WebSocketServer;
2827
+ function addListeners(server, map) {
2828
+ for (const event of Object.keys(map))
2829
+ server.on(event, map[event]);
2830
+ return function removeListeners() {
2831
+ for (const event of Object.keys(map)) {
2832
+ server.removeListener(event, map[event]);
2833
+ }
2834
+ };
2835
+ }
2836
+ function emitClose(server) {
2837
+ server._state = CLOSED;
2838
+ server.emit("close");
2839
+ }
2840
+ function socketOnError() {
2841
+ this.destroy();
2842
+ }
2843
+ function abortHandshake(socket, code, message, headers) {
2844
+ message = message || http.STATUS_CODES[code];
2845
+ headers = {
2846
+ Connection: "close",
2847
+ "Content-Type": "text/html",
2848
+ "Content-Length": Buffer.byteLength(message),
2849
+ ...headers
2850
+ };
2851
+ socket.once("finish", socket.destroy);
2852
+ socket.end(`HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r
2853
+ ` + Object.keys(headers).map((h) => `${h}: ${headers[h]}`).join(`\r
2854
+ `) + `\r
2855
+ \r
2856
+ ` + message);
2857
+ }
2858
+ function abortHandshakeOrEmitwsClientError(server, req, socket, code, message, headers) {
2859
+ if (server.listenerCount("wsClientError")) {
2860
+ const err = new Error(message);
2861
+ Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);
2862
+ server.emit("wsClientError", err, socket, req);
2863
+ } else {
2864
+ abortHandshake(socket, code, message, headers);
2865
+ }
2866
+ }
2867
+ });
2868
+
10
2869
  // src/entrypoints/sdk.ts
2870
+ import { join as join2 } from "path";
2871
+ import { fileURLToPath as fileURLToPath2 } from "url";
2872
+
2873
+ // src/utils/abortController.ts
2874
+ import { setMaxListeners } from "events";
2875
+ var DEFAULT_MAX_LISTENERS = 50;
2876
+ function createAbortController(maxListeners = DEFAULT_MAX_LISTENERS) {
2877
+ const controller = new AbortController;
2878
+ setMaxListeners(maxListeners, controller.signal);
2879
+ return controller;
2880
+ }
2881
+
2882
+ // src/transport/ProcessTransport.ts
11
2883
  import { spawn } from "child_process";
12
2884
  import { join } from "path";
13
2885
  import { fileURLToPath } from "url";
14
2886
  import { createInterface } from "readline";
15
- import { existsSync } from "fs";
2887
+
2888
+ // src/utils/fsOperations.ts
2889
+ import * as fs from "fs";
2890
+ import { stat as statPromise } from "fs/promises";
2891
+ var NodeFsOperations = {
2892
+ accessSync(fsPath, mode) {
2893
+ fs.accessSync(fsPath, mode);
2894
+ },
2895
+ cwd() {
2896
+ return process.cwd();
2897
+ },
2898
+ chmodSync(fsPath, mode) {
2899
+ fs.chmodSync(fsPath, mode);
2900
+ },
2901
+ existsSync(fsPath) {
2902
+ return fs.existsSync(fsPath);
2903
+ },
2904
+ async stat(fsPath) {
2905
+ return statPromise(fsPath);
2906
+ },
2907
+ statSync(fsPath) {
2908
+ return fs.statSync(fsPath);
2909
+ },
2910
+ readFileSync(fsPath, options) {
2911
+ return fs.readFileSync(fsPath, { encoding: options.encoding });
2912
+ },
2913
+ readFileBytesSync(fsPath) {
2914
+ return fs.readFileSync(fsPath);
2915
+ },
2916
+ readSync(fsPath, options) {
2917
+ let fd = undefined;
2918
+ try {
2919
+ fd = fs.openSync(fsPath, "r");
2920
+ const buffer = Buffer.alloc(options.length);
2921
+ const bytesRead = fs.readSync(fd, buffer, 0, options.length, 0);
2922
+ return { buffer, bytesRead };
2923
+ } finally {
2924
+ if (fd)
2925
+ fs.closeSync(fd);
2926
+ }
2927
+ },
2928
+ writeFileSync(fsPath, data, options) {
2929
+ if (!options.flush) {
2930
+ fs.writeFileSync(fsPath, data, { encoding: options.encoding });
2931
+ return;
2932
+ }
2933
+ let fd;
2934
+ try {
2935
+ fd = fs.openSync(fsPath, "w");
2936
+ fs.writeFileSync(fd, data, { encoding: options.encoding });
2937
+ fs.fsyncSync(fd);
2938
+ } finally {
2939
+ if (fd) {
2940
+ fs.closeSync(fd);
2941
+ }
2942
+ }
2943
+ },
2944
+ appendFileSync(path, data) {
2945
+ fs.appendFileSync(path, data);
2946
+ },
2947
+ copyFileSync(src, dest) {
2948
+ fs.copyFileSync(src, dest);
2949
+ },
2950
+ unlinkSync(path) {
2951
+ fs.unlinkSync(path);
2952
+ },
2953
+ renameSync(oldPath, newPath) {
2954
+ fs.renameSync(oldPath, newPath);
2955
+ },
2956
+ symlinkSync(target, path) {
2957
+ fs.symlinkSync(target, path);
2958
+ },
2959
+ readlinkSync(path) {
2960
+ return fs.readlinkSync(path);
2961
+ },
2962
+ realpathSync(path) {
2963
+ return fs.realpathSync(path);
2964
+ },
2965
+ mkdirSync(dirPath) {
2966
+ if (!fs.existsSync(dirPath)) {
2967
+ fs.mkdirSync(dirPath, { recursive: true });
2968
+ }
2969
+ },
2970
+ readdirSync(dirPath) {
2971
+ return fs.readdirSync(dirPath, { withFileTypes: true });
2972
+ },
2973
+ readdirStringSync(dirPath) {
2974
+ return fs.readdirSync(dirPath);
2975
+ },
2976
+ isDirEmptySync(dirPath) {
2977
+ const files = this.readdirSync(dirPath);
2978
+ return files.length === 0;
2979
+ },
2980
+ rmdirSync(dirPath) {
2981
+ fs.rmdirSync(dirPath);
2982
+ },
2983
+ rmSync(path, options) {
2984
+ fs.rmSync(path, options);
2985
+ }
2986
+ };
2987
+ var activeFs = NodeFsOperations;
2988
+ function getFsImplementation() {
2989
+ return activeFs;
2990
+ }
2991
+
2992
+ // src/entrypoints/sdkTypes.ts
2993
+ class AbortError extends Error {
2994
+ }
2995
+
2996
+ // src/transport/ProcessTransport.ts
2997
+ class ProcessTransport {
2998
+ options;
2999
+ child;
3000
+ childStdin;
3001
+ childStdout;
3002
+ ready = false;
3003
+ abortController;
3004
+ exitError;
3005
+ exitListeners = [];
3006
+ processExitHandler;
3007
+ abortHandler;
3008
+ isStreaming;
3009
+ constructor(options) {
3010
+ this.options = options;
3011
+ this.abortController = options.abortController || createAbortController();
3012
+ this.isStreaming = typeof options.prompt !== "string";
3013
+ this.initialize();
3014
+ }
3015
+ initialize() {
3016
+ try {
3017
+ const {
3018
+ prompt,
3019
+ additionalDirectories = [],
3020
+ cwd,
3021
+ executable = this.isRunningWithBun() ? "bun" : "node",
3022
+ executableArgs = [],
3023
+ pathToClaudeCodeExecutable,
3024
+ env = { ...process.env },
3025
+ stderr,
3026
+ customSystemPrompt,
3027
+ appendSystemPrompt,
3028
+ maxTurns,
3029
+ model,
3030
+ fallbackModel,
3031
+ permissionMode,
3032
+ permissionPromptToolName,
3033
+ continueConversation,
3034
+ resume,
3035
+ allowedTools = [],
3036
+ disallowedTools = [],
3037
+ mcpServers,
3038
+ strictMcpConfig,
3039
+ canUseTool
3040
+ } = this.options;
3041
+ const args = ["--output-format", "stream-json", "--verbose"];
3042
+ if (customSystemPrompt)
3043
+ args.push("--system-prompt", customSystemPrompt);
3044
+ if (appendSystemPrompt)
3045
+ args.push("--append-system-prompt", appendSystemPrompt);
3046
+ if (maxTurns)
3047
+ args.push("--max-turns", maxTurns.toString());
3048
+ if (model)
3049
+ args.push("--model", model);
3050
+ if (env.DEBUG)
3051
+ args.push("--debug-to-stderr");
3052
+ if (canUseTool) {
3053
+ if (typeof prompt === "string") {
3054
+ throw new Error("canUseTool callback requires --input-format stream-json. Please set prompt as an AsyncIterable.");
3055
+ }
3056
+ if (permissionPromptToolName) {
3057
+ throw new Error("canUseTool callback cannot be used with permissionPromptToolName. Please use one or the other.");
3058
+ }
3059
+ args.push("--permission-prompt-tool", "stdio");
3060
+ } else if (permissionPromptToolName) {
3061
+ args.push("--permission-prompt-tool", permissionPromptToolName);
3062
+ }
3063
+ if (continueConversation)
3064
+ args.push("--continue");
3065
+ if (resume)
3066
+ args.push("--resume", resume);
3067
+ if (allowedTools.length > 0) {
3068
+ args.push("--allowedTools", allowedTools.join(","));
3069
+ }
3070
+ if (disallowedTools.length > 0) {
3071
+ args.push("--disallowedTools", disallowedTools.join(","));
3072
+ }
3073
+ if (mcpServers && Object.keys(mcpServers).length > 0) {
3074
+ args.push("--mcp-config", JSON.stringify({ mcpServers }));
3075
+ }
3076
+ if (strictMcpConfig) {
3077
+ args.push("--strict-mcp-config");
3078
+ }
3079
+ if (permissionMode && permissionMode !== "default") {
3080
+ args.push("--permission-mode", permissionMode);
3081
+ }
3082
+ if (fallbackModel) {
3083
+ if (model && fallbackModel === model) {
3084
+ throw new Error("Fallback model cannot be the same as the main model. Please specify a different model for fallbackModel option.");
3085
+ }
3086
+ args.push("--fallback-model", fallbackModel);
3087
+ }
3088
+ if (typeof prompt === "string") {
3089
+ args.push("--print");
3090
+ args.push("--", prompt.trim());
3091
+ } else {
3092
+ args.push("--input-format", "stream-json");
3093
+ }
3094
+ for (const dir of additionalDirectories) {
3095
+ args.push("--add-dir", dir);
3096
+ }
3097
+ if (!env.CLAUDE_CODE_ENTRYPOINT) {
3098
+ env.CLAUDE_CODE_ENTRYPOINT = "sdk-ts";
3099
+ }
3100
+ const claudeCodePath = pathToClaudeCodeExecutable || this.getDefaultExecutablePath();
3101
+ const fs2 = getFsImplementation();
3102
+ if (!fs2.existsSync(claudeCodePath)) {
3103
+ throw new Error(`Claude Code executable not found at ${claudeCodePath}. Is options.pathToClaudeCodeExecutable set?`);
3104
+ }
3105
+ this.logDebug(`Spawning Claude Code process: ${executable} ${[...executableArgs, claudeCodePath, ...args].join(" ")}`);
3106
+ const stderrMode = env.DEBUG || stderr ? "pipe" : "ignore";
3107
+ this.child = spawn(executable, [...executableArgs, claudeCodePath, ...args], {
3108
+ cwd,
3109
+ stdio: ["pipe", "pipe", stderrMode],
3110
+ signal: this.abortController.signal,
3111
+ env
3112
+ });
3113
+ this.childStdin = this.child.stdin;
3114
+ this.childStdout = this.child.stdout;
3115
+ if (typeof prompt === "string") {
3116
+ this.childStdin.end();
3117
+ this.childStdin = undefined;
3118
+ }
3119
+ if (env.DEBUG || stderr) {
3120
+ this.child.stderr.on("data", (data) => {
3121
+ this.logDebug(`Claude Code stderr: ${data.toString()}`);
3122
+ if (stderr) {
3123
+ stderr(data.toString());
3124
+ }
3125
+ });
3126
+ }
3127
+ const cleanup = () => {
3128
+ if (this.child && !this.child.killed) {
3129
+ this.child.kill("SIGTERM");
3130
+ }
3131
+ };
3132
+ this.processExitHandler = cleanup;
3133
+ this.abortHandler = cleanup;
3134
+ process.on("exit", this.processExitHandler);
3135
+ this.abortController.signal.addEventListener("abort", this.abortHandler);
3136
+ this.child.on("error", (error) => {
3137
+ this.ready = false;
3138
+ if (this.abortController.signal.aborted) {
3139
+ this.exitError = new AbortError("Claude Code process aborted by user");
3140
+ } else {
3141
+ this.exitError = new Error(`Failed to spawn Claude Code process: ${error.message}`);
3142
+ this.logDebug(this.exitError.message);
3143
+ }
3144
+ });
3145
+ this.child.on("close", (code, signal) => {
3146
+ this.ready = false;
3147
+ if (this.abortController.signal.aborted) {
3148
+ this.exitError = new AbortError("Claude Code process aborted by user");
3149
+ } else {
3150
+ const error = this.getProcessExitError(code, signal);
3151
+ if (error) {
3152
+ this.exitError = error;
3153
+ this.logDebug(error.message);
3154
+ }
3155
+ }
3156
+ });
3157
+ this.ready = true;
3158
+ } catch (error) {
3159
+ this.ready = false;
3160
+ throw error;
3161
+ }
3162
+ }
3163
+ getProcessExitError(code, signal) {
3164
+ if (code !== 0 && code !== null) {
3165
+ return new Error(`Claude Code process exited with code ${code}`);
3166
+ } else if (signal) {
3167
+ return new Error(`Claude Code process terminated by signal ${signal}`);
3168
+ }
3169
+ return;
3170
+ }
3171
+ getDefaultExecutablePath() {
3172
+ const filename = fileURLToPath(import.meta.url);
3173
+ const dirname = join(filename, "..", "..");
3174
+ return join(dirname, "entrypoints", "cli.js");
3175
+ }
3176
+ isRunningWithBun() {
3177
+ return process.versions.bun !== undefined || process.env.BUN_INSTALL !== undefined;
3178
+ }
3179
+ logDebug(message) {
3180
+ if (process.env.DEBUG) {
3181
+ process.stderr.write(`${message}
3182
+ `);
3183
+ }
3184
+ }
3185
+ write(data) {
3186
+ if (this.abortController.signal.aborted) {
3187
+ throw new AbortError("Operation aborted");
3188
+ }
3189
+ if (!this.ready || !this.childStdin) {
3190
+ throw new Error("ProcessTransport is not ready for writing");
3191
+ }
3192
+ if (this.child?.killed || this.child?.exitCode !== null) {
3193
+ throw new Error("Cannot write to terminated process");
3194
+ }
3195
+ if (this.exitError) {
3196
+ throw new Error(`Cannot write to process that exited with error: ${this.exitError.message}`);
3197
+ }
3198
+ if (process.env.DEBUG_SDK) {
3199
+ process.stderr.write(`[ProcessTransport] Writing to stdin: ${data.substring(0, 100)}
3200
+ `);
3201
+ }
3202
+ try {
3203
+ const written = this.childStdin.write(data);
3204
+ if (!written && process.env.DEBUG_SDK) {
3205
+ console.warn("[ProcessTransport] Write buffer full, data queued");
3206
+ }
3207
+ } catch (error) {
3208
+ this.ready = false;
3209
+ throw new Error(`Failed to write to process stdin: ${error.message}`);
3210
+ }
3211
+ }
3212
+ close() {
3213
+ if (this.childStdin) {
3214
+ this.childStdin.end();
3215
+ this.childStdin = undefined;
3216
+ }
3217
+ if (this.processExitHandler) {
3218
+ process.off("exit", this.processExitHandler);
3219
+ this.processExitHandler = undefined;
3220
+ }
3221
+ if (this.abortHandler) {
3222
+ this.abortController.signal.removeEventListener("abort", this.abortHandler);
3223
+ this.abortHandler = undefined;
3224
+ }
3225
+ for (const { handler } of this.exitListeners) {
3226
+ this.child?.off("exit", handler);
3227
+ }
3228
+ this.exitListeners = [];
3229
+ if (this.child && !this.child.killed) {
3230
+ this.child.kill("SIGTERM");
3231
+ setTimeout(() => {
3232
+ if (this.child && !this.child.killed) {
3233
+ this.child.kill("SIGKILL");
3234
+ }
3235
+ }, 5000);
3236
+ }
3237
+ this.ready = false;
3238
+ }
3239
+ isReady() {
3240
+ return this.ready;
3241
+ }
3242
+ async* readMessages() {
3243
+ if (!this.childStdout) {
3244
+ throw new Error("ProcessTransport output stream not available");
3245
+ }
3246
+ const rl = createInterface({ input: this.childStdout });
3247
+ try {
3248
+ for await (const line of rl) {
3249
+ if (line.trim()) {
3250
+ const message = JSON.parse(line);
3251
+ yield message;
3252
+ }
3253
+ }
3254
+ await this.waitForExit();
3255
+ } catch (error) {
3256
+ throw error;
3257
+ } finally {
3258
+ rl.close();
3259
+ }
3260
+ }
3261
+ endInput() {
3262
+ if (this.childStdin) {
3263
+ this.childStdin.end();
3264
+ }
3265
+ }
3266
+ getInputStream() {
3267
+ return this.childStdin;
3268
+ }
3269
+ onExit(callback) {
3270
+ if (!this.child)
3271
+ return () => {};
3272
+ const handler = (code, signal) => {
3273
+ const error = this.getProcessExitError(code, signal);
3274
+ callback(error);
3275
+ };
3276
+ this.child.on("exit", handler);
3277
+ this.exitListeners.push({ callback, handler });
3278
+ return () => {
3279
+ if (this.child) {
3280
+ this.child.off("exit", handler);
3281
+ }
3282
+ const index = this.exitListeners.findIndex((l) => l.handler === handler);
3283
+ if (index !== -1) {
3284
+ this.exitListeners.splice(index, 1);
3285
+ }
3286
+ };
3287
+ }
3288
+ async waitForExit() {
3289
+ if (!this.child) {
3290
+ if (this.exitError) {
3291
+ throw this.exitError;
3292
+ }
3293
+ return;
3294
+ }
3295
+ if (this.child.exitCode !== null || this.child.killed) {
3296
+ if (this.exitError) {
3297
+ throw this.exitError;
3298
+ }
3299
+ return;
3300
+ }
3301
+ return new Promise((resolve, reject) => {
3302
+ const exitHandler = (code, signal) => {
3303
+ if (this.abortController.signal.aborted) {
3304
+ reject(new AbortError("Operation aborted"));
3305
+ return;
3306
+ }
3307
+ const error = this.getProcessExitError(code, signal);
3308
+ if (error) {
3309
+ reject(error);
3310
+ } else {
3311
+ resolve();
3312
+ }
3313
+ };
3314
+ this.child.once("exit", exitHandler);
3315
+ const errorHandler = (error) => {
3316
+ this.child.off("exit", exitHandler);
3317
+ reject(error);
3318
+ };
3319
+ this.child.once("error", errorHandler);
3320
+ this.child.once("exit", () => {
3321
+ this.child.off("error", errorHandler);
3322
+ });
3323
+ });
3324
+ }
3325
+ }
3326
+
3327
+ // node_modules/ws/wrapper.mjs
3328
+ var import_stream = __toESM(require_stream(), 1);
3329
+ var import_receiver = __toESM(require_receiver(), 1);
3330
+ var import_sender = __toESM(require_sender(), 1);
3331
+ var import_websocket = __toESM(require_websocket(), 1);
3332
+ var import_websocket_server = __toESM(require_websocket_server(), 1);
3333
+ var wrapper_default = import_websocket.default;
3334
+
3335
+ // src/transport/WebSocketTransport.ts
3336
+ var WEBSOCKET_CONNECT_TIMEOUT_MS = 5000;
3337
+ var WS_CLOSE_NORMAL = 1000;
3338
+ var WS_CLOSE_GOING_AWAY = 1001;
3339
+ function logDebug(message) {
3340
+ if (process.env.DEBUG || process.env.DEBUG_SDK) {
3341
+ console.log(message);
3342
+ }
3343
+ }
3344
+ function logDebugError(message) {
3345
+ if (process.env.DEBUG || process.env.DEBUG_SDK) {
3346
+ console.error(message);
3347
+ }
3348
+ }
3349
+
3350
+ class WebSocketTransport {
3351
+ options;
3352
+ ws;
3353
+ ready = false;
3354
+ abortController;
3355
+ messageQueue = [];
3356
+ messageResolve;
3357
+ messageReject;
3358
+ closed = false;
3359
+ exitError;
3360
+ readyPromise;
3361
+ readyResolve;
3362
+ readyReject;
3363
+ abortHandler;
3364
+ constructor(options) {
3365
+ this.options = options;
3366
+ this.abortController = options.abortController || createAbortController();
3367
+ this.readyPromise = new Promise((resolve, reject) => {
3368
+ this.readyResolve = resolve;
3369
+ this.readyReject = reject;
3370
+ });
3371
+ this.initialize();
3372
+ }
3373
+ initialize() {
3374
+ try {
3375
+ const { url, headers } = this.options;
3376
+ const wsUrl = new URL(url);
3377
+ if (!wsUrl.protocol.startsWith("ws")) {
3378
+ throw new Error("WebSocket URL must use ws:// or wss:// protocol");
3379
+ }
3380
+ const wsOptions = {
3381
+ headers,
3382
+ handshakeTimeout: WEBSOCKET_CONNECT_TIMEOUT_MS
3383
+ };
3384
+ this.ws = new wrapper_default(wsUrl.toString(), wsOptions);
3385
+ const timeoutId = setTimeout(() => {
3386
+ if (!this.ready) {
3387
+ this.ws?.close();
3388
+ const error = new Error(`WebSocket connection timeout after ${WEBSOCKET_CONNECT_TIMEOUT_MS}ms`);
3389
+ this.exitError = error;
3390
+ if (this.readyReject) {
3391
+ this.readyReject(error);
3392
+ }
3393
+ }
3394
+ }, WEBSOCKET_CONNECT_TIMEOUT_MS);
3395
+ this.ws.on("open", () => {
3396
+ clearTimeout(timeoutId);
3397
+ this.ready = true;
3398
+ if (this.readyResolve) {
3399
+ this.readyResolve();
3400
+ }
3401
+ logDebug(`WebSocket connected to ${url}`);
3402
+ });
3403
+ this.ws.on("error", (error) => {
3404
+ clearTimeout(timeoutId);
3405
+ this.ready = false;
3406
+ this.exitError = error;
3407
+ if (this.readyReject) {
3408
+ this.readyReject(error);
3409
+ }
3410
+ logDebugError(`WebSocket error: ${error.message}`);
3411
+ if (this.messageReject) {
3412
+ this.messageReject(error);
3413
+ this.messageReject = undefined;
3414
+ this.messageResolve = undefined;
3415
+ }
3416
+ });
3417
+ this.ws.on("close", (code, reason) => {
3418
+ this.ready = false;
3419
+ this.closed = true;
3420
+ const reasonString = reason.toString();
3421
+ if (code !== WS_CLOSE_NORMAL && code !== WS_CLOSE_GOING_AWAY) {
3422
+ this.exitError = new Error(`WebSocket closed abnormally with code ${code}: ${reasonString}`);
3423
+ }
3424
+ logDebug(`WebSocket closed: ${code} ${reasonString}`);
3425
+ if (this.messageResolve) {
3426
+ this.messageResolve({ done: true, value: undefined });
3427
+ this.messageResolve = undefined;
3428
+ this.messageReject = undefined;
3429
+ }
3430
+ });
3431
+ this.ws.on("message", (data) => {
3432
+ const message = data.toString();
3433
+ const lines = message.split(`
3434
+ `);
3435
+ for (const line of lines) {
3436
+ if (line.trim()) {
3437
+ try {
3438
+ const parsedMessage = JSON.parse(line);
3439
+ this.enqueueMessage(parsedMessage);
3440
+ } catch (_error) {
3441
+ logDebugError(`Failed to parse WebSocket message: ${line}`);
3442
+ }
3443
+ }
3444
+ }
3445
+ });
3446
+ if (this.abortController) {
3447
+ this.abortHandler = () => {
3448
+ this.close();
3449
+ this.exitError = new AbortError("WebSocket connection aborted by user");
3450
+ };
3451
+ if (this.abortController.signal.aborted) {
3452
+ this.abortHandler();
3453
+ } else {
3454
+ this.abortController.signal.addEventListener("abort", this.abortHandler);
3455
+ }
3456
+ }
3457
+ } catch (error) {
3458
+ this.ready = false;
3459
+ this.exitError = error;
3460
+ if (this.readyReject) {
3461
+ this.readyReject(error);
3462
+ }
3463
+ throw error;
3464
+ }
3465
+ }
3466
+ enqueueMessage(message) {
3467
+ if (this.messageResolve) {
3468
+ this.messageResolve({ done: false, value: message });
3469
+ this.messageResolve = undefined;
3470
+ this.messageReject = undefined;
3471
+ } else {
3472
+ this.messageQueue.push(message);
3473
+ }
3474
+ }
3475
+ async write(data) {
3476
+ if (this.abortController.signal.aborted) {
3477
+ throw new AbortError("Operation aborted");
3478
+ }
3479
+ if (!this.ready) {
3480
+ await this.readyPromise;
3481
+ }
3482
+ if (!this.ready || !this.ws || this.ws.readyState !== wrapper_default.OPEN) {
3483
+ throw new Error("WebSocketTransport is not ready for writing");
3484
+ }
3485
+ logDebug(`[WebSocketTransport] Writing: ${data.substring(0, 100)}`);
3486
+ this.ws.send(data);
3487
+ }
3488
+ close() {
3489
+ if (this.abortHandler && this.abortController) {
3490
+ this.abortController.signal.removeEventListener("abort", this.abortHandler);
3491
+ this.abortHandler = undefined;
3492
+ }
3493
+ if (this.ws && this.ws.readyState === wrapper_default.OPEN) {
3494
+ this.ws.close(1000, "Normal closure");
3495
+ }
3496
+ this.ready = false;
3497
+ this.closed = true;
3498
+ }
3499
+ isReady() {
3500
+ return this.ready && this.ws?.readyState === wrapper_default.OPEN;
3501
+ }
3502
+ endInput() {}
3503
+ async* readMessages() {
3504
+ while (!this.closed || this.messageQueue.length > 0) {
3505
+ if (this.messageQueue.length > 0) {
3506
+ const message = this.messageQueue.shift();
3507
+ yield message;
3508
+ continue;
3509
+ }
3510
+ if (this.closed) {
3511
+ break;
3512
+ }
3513
+ const result = await new Promise((resolve, reject) => {
3514
+ if (this.messageQueue.length > 0) {
3515
+ const message = this.messageQueue.shift();
3516
+ resolve({ done: false, value: message });
3517
+ return;
3518
+ }
3519
+ if (this.closed) {
3520
+ resolve({ done: true, value: undefined });
3521
+ return;
3522
+ }
3523
+ this.messageResolve = resolve;
3524
+ this.messageReject = reject;
3525
+ });
3526
+ if (result.done) {
3527
+ break;
3528
+ }
3529
+ yield result.value;
3530
+ }
3531
+ if (this.exitError) {
3532
+ throw this.exitError;
3533
+ }
3534
+ }
3535
+ }
16
3536
 
17
3537
  // src/utils/stream.ts
18
3538
  class Stream {
@@ -88,204 +3608,50 @@ class Stream {
88
3608
  }
89
3609
  }
90
3610
 
91
- // src/utils/abortController.ts
92
- import { setMaxListeners } from "events";
93
- var DEFAULT_MAX_LISTENERS = 50;
94
- function createAbortController(maxListeners = DEFAULT_MAX_LISTENERS) {
95
- const controller = new AbortController;
96
- setMaxListeners(maxListeners, controller.signal);
97
- return controller;
98
- }
99
-
100
- // src/entrypoints/sdkTypes.ts
101
- class AbortError extends Error {
102
- }
103
-
104
- // src/entrypoints/sdk.ts
105
- function query({
106
- prompt,
107
- options: {
108
- abortController = createAbortController(),
109
- additionalDirectories = [],
110
- allowedTools = [],
111
- appendSystemPrompt,
112
- canUseTool,
113
- continue: continueConversation,
114
- customSystemPrompt,
115
- cwd,
116
- disallowedTools = [],
117
- env,
118
- executable = isRunningWithBun() ? "bun" : "node",
119
- executableArgs = [],
120
- fallbackModel,
121
- hooks,
122
- maxTurns,
123
- mcpServers,
124
- model,
125
- pathToClaudeCodeExecutable,
126
- permissionMode = "default",
127
- permissionPromptToolName,
128
- resume,
129
- stderr,
130
- strictMcpConfig
131
- } = {}
132
- }) {
133
- if (!env) {
134
- env = { ...process.env };
135
- }
136
- if (!env.CLAUDE_CODE_ENTRYPOINT) {
137
- env.CLAUDE_CODE_ENTRYPOINT = "sdk-ts";
138
- }
139
- if (pathToClaudeCodeExecutable === undefined) {
140
- const filename = fileURLToPath(import.meta.url);
141
- const dirname = join(filename, "..");
142
- pathToClaudeCodeExecutable = join(dirname, "cli.js");
143
- }
144
- const args = ["--output-format", "stream-json", "--verbose"];
145
- if (customSystemPrompt)
146
- args.push("--system-prompt", customSystemPrompt);
147
- if (appendSystemPrompt)
148
- args.push("--append-system-prompt", appendSystemPrompt);
149
- if (maxTurns)
150
- args.push("--max-turns", maxTurns.toString());
151
- if (model)
152
- args.push("--model", model);
153
- if (canUseTool) {
154
- if (typeof prompt === "string") {
155
- throw new Error("canUseTool callback requires --input-format stream-json. Please set prompt as an AsyncIterable.");
156
- }
157
- if (permissionPromptToolName) {
158
- throw new Error("canUseTool callback cannot be used with permissionPromptToolName. Please use one or the other.");
159
- }
160
- permissionPromptToolName = "stdio";
161
- }
162
- if (permissionPromptToolName) {
163
- args.push("--permission-prompt-tool", permissionPromptToolName);
164
- }
165
- if (continueConversation)
166
- args.push("--continue");
167
- if (resume)
168
- args.push("--resume", resume);
169
- if (allowedTools.length > 0) {
170
- args.push("--allowedTools", allowedTools.join(","));
171
- }
172
- if (disallowedTools.length > 0) {
173
- args.push("--disallowedTools", disallowedTools.join(","));
174
- }
175
- if (mcpServers && Object.keys(mcpServers).length > 0) {
176
- args.push("--mcp-config", JSON.stringify({ mcpServers }));
177
- }
178
- if (strictMcpConfig) {
179
- args.push("--strict-mcp-config");
180
- }
181
- if (permissionMode !== "default") {
182
- args.push("--permission-mode", permissionMode);
183
- }
184
- if (fallbackModel) {
185
- if (model && fallbackModel === model) {
186
- throw new Error("Fallback model cannot be the same as the main model. Please specify a different model for fallbackModel option.");
187
- }
188
- args.push("--fallback-model", fallbackModel);
189
- }
190
- if (typeof prompt === "string") {
191
- args.push("--print");
192
- args.push("--", prompt.trim());
193
- } else {
194
- args.push("--input-format", "stream-json");
195
- }
196
- for (const dir of additionalDirectories) {
197
- args.push("--add-dir", dir);
198
- }
199
- if (!existsSync(pathToClaudeCodeExecutable)) {
200
- throw new ReferenceError(`Claude Code executable not found at ${pathToClaudeCodeExecutable}. Is options.pathToClaudeCodeExecutable set?`);
201
- }
202
- logDebug(`Spawning Claude Code process: ${executable} ${[...executableArgs, pathToClaudeCodeExecutable, ...args].join(" ")}`);
203
- const stderrMode = env.DEBUG || stderr ? "pipe" : "ignore";
204
- const child = spawn(executable, [...executableArgs, pathToClaudeCodeExecutable, ...args], {
205
- cwd,
206
- stdio: ["pipe", "pipe", stderrMode],
207
- signal: abortController.signal,
208
- env
209
- });
210
- let childStdin;
211
- if (typeof prompt === "string") {
212
- child.stdin.end();
213
- } else {
214
- streamToStdin(prompt, child.stdin, abortController);
215
- childStdin = child.stdin;
216
- }
217
- if (env.DEBUG || stderr) {
218
- child.stderr.on("data", (data) => {
219
- if (env.DEBUG) {
220
- console.error("Claude Code stderr:", data.toString());
221
- }
222
- if (stderr) {
223
- stderr(data.toString());
224
- }
225
- });
226
- }
227
- const cleanup = () => {
228
- if (!child.killed) {
229
- child.kill("SIGTERM");
230
- }
231
- };
232
- abortController.signal.addEventListener("abort", cleanup);
233
- process.on("exit", cleanup);
234
- const processExitPromise = new Promise((resolve) => {
235
- child.on("close", (code) => {
236
- if (abortController.signal.aborted) {
237
- query2.setError(new AbortError("Claude Code process aborted by user"));
238
- }
239
- if (code !== 0) {
240
- query2.setError(new Error(`Claude Code process exited with code ${code}`));
241
- } else {
242
- resolve();
243
- }
244
- });
245
- });
246
- const query2 = new Query(childStdin, child.stdout, processExitPromise, canUseTool, hooks);
247
- child.on("error", (error) => {
248
- if (abortController.signal.aborted) {
249
- query2.setError(new AbortError("Claude Code process aborted by user"));
250
- } else {
251
- query2.setError(new Error(`Failed to spawn Claude Code process: ${error.message}`));
252
- }
253
- });
254
- processExitPromise.finally(() => {
255
- cleanup();
256
- abortController.signal.removeEventListener("abort", cleanup);
257
- });
258
- return query2;
259
- }
260
-
3611
+ // src/core/Query.ts
261
3612
  class Query {
262
- childStdin;
263
- childStdout;
264
- processExitPromise;
3613
+ transport;
3614
+ isStreamingMode;
265
3615
  canUseTool;
266
3616
  hooks;
3617
+ abortController;
267
3618
  pendingControlResponses = new Map;
3619
+ cleanupPerformed = false;
268
3620
  sdkMessages;
269
3621
  inputStream = new Stream;
270
3622
  intialization;
271
3623
  cancelControllers = new Map;
272
3624
  hookCallbacks = new Map;
273
3625
  nextCallbackId = 0;
274
- constructor(childStdin, childStdout, processExitPromise, canUseTool, hooks) {
275
- this.childStdin = childStdin;
276
- this.childStdout = childStdout;
277
- this.processExitPromise = processExitPromise;
3626
+ constructor(transport, isStreamingMode, canUseTool, hooks, abortController) {
3627
+ this.transport = transport;
3628
+ this.isStreamingMode = isStreamingMode;
278
3629
  this.canUseTool = canUseTool;
279
3630
  this.hooks = hooks;
280
- this.readMessages();
3631
+ this.abortController = abortController;
281
3632
  this.sdkMessages = this.readSdkMessages();
282
- if (this.childStdin) {
3633
+ this.readMessages();
3634
+ if (this.isStreamingMode) {
283
3635
  this.intialization = this.initialize();
284
3636
  }
285
3637
  }
286
3638
  setError(error) {
287
3639
  this.inputStream.error(error);
288
3640
  }
3641
+ cleanup(error) {
3642
+ if (this.cleanupPerformed)
3643
+ return;
3644
+ this.cleanupPerformed = true;
3645
+ try {
3646
+ this.transport.close();
3647
+ this.pendingControlResponses.clear();
3648
+ if (error) {
3649
+ this.inputStream.error(error);
3650
+ } else {
3651
+ this.inputStream.done();
3652
+ }
3653
+ } catch (_error) {}
3654
+ }
289
3655
  next(...[value]) {
290
3656
  return this.sdkMessages.next(...[value]);
291
3657
  }
@@ -302,33 +3668,28 @@ class Query {
302
3668
  return this.sdkMessages[Symbol.asyncDispose]();
303
3669
  }
304
3670
  async readMessages() {
305
- const rl = createInterface({ input: this.childStdout });
306
3671
  try {
307
- for await (const line of rl) {
308
- if (line.trim()) {
309
- const message = JSON.parse(line);
310
- if (message.type === "control_response") {
311
- const handler = this.pendingControlResponses.get(message.response.request_id);
312
- if (handler) {
313
- handler(message.response);
314
- }
315
- continue;
316
- } else if (message.type === "control_request") {
317
- this.handleControlRequest(message);
318
- continue;
319
- } else if (message.type === "control_cancel_request") {
320
- this.handleControlCancelRequest(message);
321
- continue;
3672
+ for await (const message of this.transport.readMessages()) {
3673
+ if (message.type === "control_response") {
3674
+ const handler = this.pendingControlResponses.get(message.response.request_id);
3675
+ if (handler) {
3676
+ handler(message.response);
322
3677
  }
323
- this.inputStream.enqueue(message);
3678
+ continue;
3679
+ } else if (message.type === "control_request") {
3680
+ this.handleControlRequest(message);
3681
+ continue;
3682
+ } else if (message.type === "control_cancel_request") {
3683
+ this.handleControlCancelRequest(message);
3684
+ continue;
324
3685
  }
3686
+ this.inputStream.enqueue(message);
325
3687
  }
326
- await this.processExitPromise;
3688
+ this.inputStream.done();
3689
+ this.cleanup();
327
3690
  } catch (error) {
328
3691
  this.inputStream.error(error);
329
- } finally {
330
- this.inputStream.done();
331
- rl.close();
3692
+ this.cleanup(error);
332
3693
  }
333
3694
  }
334
3695
  async handleControlRequest(request) {
@@ -344,8 +3705,8 @@ class Query {
344
3705
  response
345
3706
  }
346
3707
  };
347
- this.childStdin?.write(JSON.stringify(controlResponse) + `
348
- `);
3708
+ await Promise.resolve(this.transport.write(JSON.stringify(controlResponse) + `
3709
+ `));
349
3710
  } catch (error) {
350
3711
  const controlErrorResponse = {
351
3712
  type: "control_response",
@@ -355,8 +3716,8 @@ class Query {
355
3716
  error: error.message || String(error)
356
3717
  }
357
3718
  };
358
- this.childStdin?.write(JSON.stringify(controlErrorResponse) + `
359
- `);
3719
+ await Promise.resolve(this.transport.write(JSON.stringify(controlErrorResponse) + `
3720
+ `));
360
3721
  } finally {
361
3722
  this.cancelControllers.delete(request.request_id);
362
3723
  }
@@ -388,9 +3749,6 @@ class Query {
388
3749
  }
389
3750
  }
390
3751
  async initialize() {
391
- if (!this.childStdin) {
392
- throw new Error("Cannot initialize without child stdin");
393
- }
394
3752
  let hooks;
395
3753
  if (this.hooks) {
396
3754
  hooks = {};
@@ -415,27 +3773,27 @@ class Query {
415
3773
  subtype: "initialize",
416
3774
  hooks
417
3775
  };
418
- const response = await this.request(initRequest, this.childStdin);
3776
+ const response = await this.request(initRequest);
419
3777
  return response.response;
420
3778
  }
421
3779
  async interrupt() {
422
- if (!this.childStdin) {
3780
+ if (!this.isStreamingMode) {
423
3781
  throw new Error("Interrupt requires --input-format stream-json");
424
3782
  }
425
3783
  await this.request({
426
3784
  subtype: "interrupt"
427
- }, this.childStdin);
3785
+ });
428
3786
  }
429
3787
  async setPermissionMode(mode) {
430
- if (!this.childStdin) {
3788
+ if (!this.isStreamingMode) {
431
3789
  throw new Error("setPermissionMode requires --input-format stream-json");
432
3790
  }
433
3791
  await this.request({
434
3792
  subtype: "set_permission_mode",
435
3793
  mode
436
- }, this.childStdin);
3794
+ });
437
3795
  }
438
- request(request, childStdin) {
3796
+ request(request) {
439
3797
  const requestId = Math.random().toString(36).substring(2, 15);
440
3798
  const sdkRequest = {
441
3799
  request_id: requestId,
@@ -450,16 +3808,34 @@ class Query {
450
3808
  reject(new Error(response.error));
451
3809
  }
452
3810
  });
453
- childStdin.write(JSON.stringify(sdkRequest) + `
454
- `);
3811
+ Promise.resolve(this.transport.write(JSON.stringify(sdkRequest) + `
3812
+ `));
455
3813
  });
456
3814
  }
457
3815
  async supportedCommands() {
3816
+ if (!this.isStreamingMode) {
3817
+ throw new Error("supportedCommands requires --input-format stream-json");
3818
+ }
458
3819
  if (!this.intialization) {
459
- throw new Error("Interrupt requires --input-format stream-json");
3820
+ throw new Error("supportedCommands requires transport with bidirectional communication");
460
3821
  }
461
3822
  return (await this.intialization).commands;
462
3823
  }
3824
+ async streamInput(stream) {
3825
+ try {
3826
+ for await (const message of stream) {
3827
+ if (this.abortController?.signal.aborted)
3828
+ break;
3829
+ await Promise.resolve(this.transport.write(JSON.stringify(message) + `
3830
+ `));
3831
+ }
3832
+ this.transport.endInput();
3833
+ } catch (error) {
3834
+ if (!(error instanceof AbortError)) {
3835
+ throw error;
3836
+ }
3837
+ }
3838
+ }
463
3839
  handleHookCallbacks(callbackId, input, toolUseID, abortSignal) {
464
3840
  const callback = this.hookCallbacks.get(callbackId);
465
3841
  if (!callback) {
@@ -470,24 +3846,98 @@ class Query {
470
3846
  });
471
3847
  }
472
3848
  }
473
- async function streamToStdin(stream, stdin, abortController) {
474
- for await (const message of stream) {
475
- if (abortController.signal.aborted)
476
- break;
477
- stdin.write(JSON.stringify(message) + `
478
- `);
3849
+
3850
+ // src/entrypoints/sdk.ts
3851
+ function query({
3852
+ prompt,
3853
+ options: {
3854
+ abortController = createAbortController(),
3855
+ additionalDirectories = [],
3856
+ allowedTools = [],
3857
+ appendSystemPrompt,
3858
+ canUseTool,
3859
+ continue: continueConversation,
3860
+ customSystemPrompt,
3861
+ cwd,
3862
+ disallowedTools = [],
3863
+ env,
3864
+ executable = isRunningWithBun() ? "bun" : "node",
3865
+ executableArgs = [],
3866
+ fallbackModel,
3867
+ hooks,
3868
+ maxTurns,
3869
+ mcpServers,
3870
+ model,
3871
+ pathToClaudeCodeExecutable,
3872
+ permissionMode = "default",
3873
+ permissionPromptToolName,
3874
+ resume,
3875
+ stderr,
3876
+ strictMcpConfig,
3877
+ websocket
3878
+ } = {}
3879
+ }) {
3880
+ if (!env) {
3881
+ env = { ...process.env };
479
3882
  }
480
- stdin.end();
481
- }
482
- function logDebug(message) {
483
- if (process.env.DEBUG) {
484
- console.debug(message);
3883
+ if (!env.CLAUDE_CODE_ENTRYPOINT) {
3884
+ env.CLAUDE_CODE_ENTRYPOINT = "sdk-ts";
3885
+ }
3886
+ if (pathToClaudeCodeExecutable === undefined) {
3887
+ const filename = fileURLToPath2(import.meta.url);
3888
+ const dirname = join2(filename, "..");
3889
+ pathToClaudeCodeExecutable = join2(dirname, "cli.js");
485
3890
  }
3891
+ const isStreamingMode = typeof prompt !== "string";
3892
+ let transport;
3893
+ if (websocket) {
3894
+ if (typeof prompt === "string") {
3895
+ throw new Error("WebSocket transport requires prompt as AsyncIterable for bidirectional communication");
3896
+ }
3897
+ transport = new WebSocketTransport({
3898
+ url: websocket.url,
3899
+ headers: websocket.headers,
3900
+ abortController
3901
+ });
3902
+ } else {
3903
+ transport = new ProcessTransport({
3904
+ prompt,
3905
+ abortController,
3906
+ additionalDirectories,
3907
+ cwd,
3908
+ executable,
3909
+ executableArgs,
3910
+ pathToClaudeCodeExecutable,
3911
+ env,
3912
+ stderr,
3913
+ customSystemPrompt,
3914
+ appendSystemPrompt,
3915
+ maxTurns,
3916
+ model,
3917
+ fallbackModel,
3918
+ permissionMode,
3919
+ permissionPromptToolName,
3920
+ continueConversation,
3921
+ resume,
3922
+ allowedTools,
3923
+ disallowedTools,
3924
+ mcpServers,
3925
+ strictMcpConfig,
3926
+ canUseTool: !!canUseTool,
3927
+ hooks: !!hooks
3928
+ });
3929
+ }
3930
+ const query2 = new Query(transport, isStreamingMode, canUseTool, hooks, abortController);
3931
+ if (typeof prompt !== "string") {
3932
+ query2.streamInput(prompt);
3933
+ }
3934
+ return query2;
486
3935
  }
487
3936
  function isRunningWithBun() {
488
3937
  return process.versions.bun !== undefined || process.env.BUN_INSTALL !== undefined;
489
3938
  }
490
3939
  export {
491
3940
  query,
492
- Query
3941
+ Query,
3942
+ AbortError
493
3943
  };