@andresaya/edge-tts 1.2.0 → 1.2.4

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