@sayna-ai/node-sdk 0.0.13 → 0.0.15

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