@ipcom/asterisk-ari 0.0.71 → 0.0.74

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/esm/index.js CHANGED
@@ -1,578 +1,3 @@
1
- var __create = Object.create;
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __getProtoOf = Object.getPrototypeOf;
6
- var __hasOwnProp = Object.prototype.hasOwnProperty;
7
- var __commonJS = (cb, mod) => function __require() {
8
- return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
19
- // If the importer is in node compatibility mode or this is not an ESM
20
- // file that has been converted to a CommonJS file using a Babel-
21
- // compatible transform (i.e. "__esModule" has not been set), then set
22
- // "default" to the CommonJS "module.exports" for node compatibility.
23
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
24
- mod
25
- ));
26
-
27
- // node_modules/exponential-backoff/dist/options.js
28
- var require_options = __commonJS({
29
- "node_modules/exponential-backoff/dist/options.js"(exports) {
30
- "use strict";
31
- var __assign = exports && exports.__assign || function() {
32
- __assign = Object.assign || function(t) {
33
- for (var s, i = 1, n = arguments.length; i < n; i++) {
34
- s = arguments[i];
35
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
36
- t[p] = s[p];
37
- }
38
- return t;
39
- };
40
- return __assign.apply(this, arguments);
41
- };
42
- Object.defineProperty(exports, "__esModule", { value: true });
43
- var defaultOptions = {
44
- delayFirstAttempt: false,
45
- jitter: "none",
46
- maxDelay: Infinity,
47
- numOfAttempts: 10,
48
- retry: function() {
49
- return true;
50
- },
51
- startingDelay: 100,
52
- timeMultiple: 2
53
- };
54
- function getSanitizedOptions(options) {
55
- var sanitized = __assign(__assign({}, defaultOptions), options);
56
- if (sanitized.numOfAttempts < 1) {
57
- sanitized.numOfAttempts = 1;
58
- }
59
- return sanitized;
60
- }
61
- exports.getSanitizedOptions = getSanitizedOptions;
62
- }
63
- });
64
-
65
- // node_modules/exponential-backoff/dist/jitter/full/full.jitter.js
66
- var require_full_jitter = __commonJS({
67
- "node_modules/exponential-backoff/dist/jitter/full/full.jitter.js"(exports) {
68
- "use strict";
69
- Object.defineProperty(exports, "__esModule", { value: true });
70
- function fullJitter(delay) {
71
- var jitteredDelay = Math.random() * delay;
72
- return Math.round(jitteredDelay);
73
- }
74
- exports.fullJitter = fullJitter;
75
- }
76
- });
77
-
78
- // node_modules/exponential-backoff/dist/jitter/no/no.jitter.js
79
- var require_no_jitter = __commonJS({
80
- "node_modules/exponential-backoff/dist/jitter/no/no.jitter.js"(exports) {
81
- "use strict";
82
- Object.defineProperty(exports, "__esModule", { value: true });
83
- function noJitter(delay) {
84
- return delay;
85
- }
86
- exports.noJitter = noJitter;
87
- }
88
- });
89
-
90
- // node_modules/exponential-backoff/dist/jitter/jitter.factory.js
91
- var require_jitter_factory = __commonJS({
92
- "node_modules/exponential-backoff/dist/jitter/jitter.factory.js"(exports) {
93
- "use strict";
94
- Object.defineProperty(exports, "__esModule", { value: true });
95
- var full_jitter_1 = require_full_jitter();
96
- var no_jitter_1 = require_no_jitter();
97
- function JitterFactory(options) {
98
- switch (options.jitter) {
99
- case "full":
100
- return full_jitter_1.fullJitter;
101
- case "none":
102
- default:
103
- return no_jitter_1.noJitter;
104
- }
105
- }
106
- exports.JitterFactory = JitterFactory;
107
- }
108
- });
109
-
110
- // node_modules/exponential-backoff/dist/delay/delay.base.js
111
- var require_delay_base = __commonJS({
112
- "node_modules/exponential-backoff/dist/delay/delay.base.js"(exports) {
113
- "use strict";
114
- Object.defineProperty(exports, "__esModule", { value: true });
115
- var jitter_factory_1 = require_jitter_factory();
116
- var Delay = (
117
- /** @class */
118
- function() {
119
- function Delay2(options) {
120
- this.options = options;
121
- this.attempt = 0;
122
- }
123
- Delay2.prototype.apply = function() {
124
- var _this = this;
125
- return new Promise(function(resolve) {
126
- return setTimeout(resolve, _this.jitteredDelay);
127
- });
128
- };
129
- Delay2.prototype.setAttemptNumber = function(attempt) {
130
- this.attempt = attempt;
131
- };
132
- Object.defineProperty(Delay2.prototype, "jitteredDelay", {
133
- get: function() {
134
- var jitter = jitter_factory_1.JitterFactory(this.options);
135
- return jitter(this.delay);
136
- },
137
- enumerable: true,
138
- configurable: true
139
- });
140
- Object.defineProperty(Delay2.prototype, "delay", {
141
- get: function() {
142
- var constant = this.options.startingDelay;
143
- var base = this.options.timeMultiple;
144
- var power = this.numOfDelayedAttempts;
145
- var delay = constant * Math.pow(base, power);
146
- return Math.min(delay, this.options.maxDelay);
147
- },
148
- enumerable: true,
149
- configurable: true
150
- });
151
- Object.defineProperty(Delay2.prototype, "numOfDelayedAttempts", {
152
- get: function() {
153
- return this.attempt;
154
- },
155
- enumerable: true,
156
- configurable: true
157
- });
158
- return Delay2;
159
- }()
160
- );
161
- exports.Delay = Delay;
162
- }
163
- });
164
-
165
- // node_modules/exponential-backoff/dist/delay/skip-first/skip-first.delay.js
166
- var require_skip_first_delay = __commonJS({
167
- "node_modules/exponential-backoff/dist/delay/skip-first/skip-first.delay.js"(exports) {
168
- "use strict";
169
- var __extends = exports && exports.__extends || /* @__PURE__ */ function() {
170
- var extendStatics = function(d, b) {
171
- extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
172
- d2.__proto__ = b2;
173
- } || function(d2, b2) {
174
- for (var p in b2) if (b2.hasOwnProperty(p)) d2[p] = b2[p];
175
- };
176
- return extendStatics(d, b);
177
- };
178
- return function(d, b) {
179
- extendStatics(d, b);
180
- function __() {
181
- this.constructor = d;
182
- }
183
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
184
- };
185
- }();
186
- var __awaiter = exports && exports.__awaiter || function(thisArg, _arguments, P, generator) {
187
- function adopt(value) {
188
- return value instanceof P ? value : new P(function(resolve) {
189
- resolve(value);
190
- });
191
- }
192
- return new (P || (P = Promise))(function(resolve, reject) {
193
- function fulfilled(value) {
194
- try {
195
- step(generator.next(value));
196
- } catch (e) {
197
- reject(e);
198
- }
199
- }
200
- function rejected(value) {
201
- try {
202
- step(generator["throw"](value));
203
- } catch (e) {
204
- reject(e);
205
- }
206
- }
207
- function step(result) {
208
- result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
209
- }
210
- step((generator = generator.apply(thisArg, _arguments || [])).next());
211
- });
212
- };
213
- var __generator = exports && exports.__generator || function(thisArg, body) {
214
- var _ = { label: 0, sent: function() {
215
- if (t[0] & 1) throw t[1];
216
- return t[1];
217
- }, trys: [], ops: [] }, f, y, t, g;
218
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
219
- return this;
220
- }), g;
221
- function verb(n) {
222
- return function(v) {
223
- return step([n, v]);
224
- };
225
- }
226
- function step(op) {
227
- if (f) throw new TypeError("Generator is already executing.");
228
- while (_) try {
229
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
230
- if (y = 0, t) op = [op[0] & 2, t.value];
231
- switch (op[0]) {
232
- case 0:
233
- case 1:
234
- t = op;
235
- break;
236
- case 4:
237
- _.label++;
238
- return { value: op[1], done: false };
239
- case 5:
240
- _.label++;
241
- y = op[1];
242
- op = [0];
243
- continue;
244
- case 7:
245
- op = _.ops.pop();
246
- _.trys.pop();
247
- continue;
248
- default:
249
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
250
- _ = 0;
251
- continue;
252
- }
253
- if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
254
- _.label = op[1];
255
- break;
256
- }
257
- if (op[0] === 6 && _.label < t[1]) {
258
- _.label = t[1];
259
- t = op;
260
- break;
261
- }
262
- if (t && _.label < t[2]) {
263
- _.label = t[2];
264
- _.ops.push(op);
265
- break;
266
- }
267
- if (t[2]) _.ops.pop();
268
- _.trys.pop();
269
- continue;
270
- }
271
- op = body.call(thisArg, _);
272
- } catch (e) {
273
- op = [6, e];
274
- y = 0;
275
- } finally {
276
- f = t = 0;
277
- }
278
- if (op[0] & 5) throw op[1];
279
- return { value: op[0] ? op[1] : void 0, done: true };
280
- }
281
- };
282
- Object.defineProperty(exports, "__esModule", { value: true });
283
- var delay_base_1 = require_delay_base();
284
- var SkipFirstDelay = (
285
- /** @class */
286
- function(_super) {
287
- __extends(SkipFirstDelay2, _super);
288
- function SkipFirstDelay2() {
289
- return _super !== null && _super.apply(this, arguments) || this;
290
- }
291
- SkipFirstDelay2.prototype.apply = function() {
292
- return __awaiter(this, void 0, void 0, function() {
293
- return __generator(this, function(_a) {
294
- return [2, this.isFirstAttempt ? true : _super.prototype.apply.call(this)];
295
- });
296
- });
297
- };
298
- Object.defineProperty(SkipFirstDelay2.prototype, "isFirstAttempt", {
299
- get: function() {
300
- return this.attempt === 0;
301
- },
302
- enumerable: true,
303
- configurable: true
304
- });
305
- Object.defineProperty(SkipFirstDelay2.prototype, "numOfDelayedAttempts", {
306
- get: function() {
307
- return this.attempt - 1;
308
- },
309
- enumerable: true,
310
- configurable: true
311
- });
312
- return SkipFirstDelay2;
313
- }(delay_base_1.Delay)
314
- );
315
- exports.SkipFirstDelay = SkipFirstDelay;
316
- }
317
- });
318
-
319
- // node_modules/exponential-backoff/dist/delay/always/always.delay.js
320
- var require_always_delay = __commonJS({
321
- "node_modules/exponential-backoff/dist/delay/always/always.delay.js"(exports) {
322
- "use strict";
323
- var __extends = exports && exports.__extends || /* @__PURE__ */ function() {
324
- var extendStatics = function(d, b) {
325
- extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
326
- d2.__proto__ = b2;
327
- } || function(d2, b2) {
328
- for (var p in b2) if (b2.hasOwnProperty(p)) d2[p] = b2[p];
329
- };
330
- return extendStatics(d, b);
331
- };
332
- return function(d, b) {
333
- extendStatics(d, b);
334
- function __() {
335
- this.constructor = d;
336
- }
337
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
338
- };
339
- }();
340
- Object.defineProperty(exports, "__esModule", { value: true });
341
- var delay_base_1 = require_delay_base();
342
- var AlwaysDelay = (
343
- /** @class */
344
- function(_super) {
345
- __extends(AlwaysDelay2, _super);
346
- function AlwaysDelay2() {
347
- return _super !== null && _super.apply(this, arguments) || this;
348
- }
349
- return AlwaysDelay2;
350
- }(delay_base_1.Delay)
351
- );
352
- exports.AlwaysDelay = AlwaysDelay;
353
- }
354
- });
355
-
356
- // node_modules/exponential-backoff/dist/delay/delay.factory.js
357
- var require_delay_factory = __commonJS({
358
- "node_modules/exponential-backoff/dist/delay/delay.factory.js"(exports) {
359
- "use strict";
360
- Object.defineProperty(exports, "__esModule", { value: true });
361
- var skip_first_delay_1 = require_skip_first_delay();
362
- var always_delay_1 = require_always_delay();
363
- function DelayFactory(options, attempt) {
364
- var delay = initDelayClass(options);
365
- delay.setAttemptNumber(attempt);
366
- return delay;
367
- }
368
- exports.DelayFactory = DelayFactory;
369
- function initDelayClass(options) {
370
- if (!options.delayFirstAttempt) {
371
- return new skip_first_delay_1.SkipFirstDelay(options);
372
- }
373
- return new always_delay_1.AlwaysDelay(options);
374
- }
375
- }
376
- });
377
-
378
- // node_modules/exponential-backoff/dist/backoff.js
379
- var require_backoff = __commonJS({
380
- "node_modules/exponential-backoff/dist/backoff.js"(exports) {
381
- "use strict";
382
- var __awaiter = exports && exports.__awaiter || function(thisArg, _arguments, P, generator) {
383
- function adopt(value) {
384
- return value instanceof P ? value : new P(function(resolve) {
385
- resolve(value);
386
- });
387
- }
388
- return new (P || (P = Promise))(function(resolve, reject) {
389
- function fulfilled(value) {
390
- try {
391
- step(generator.next(value));
392
- } catch (e) {
393
- reject(e);
394
- }
395
- }
396
- function rejected(value) {
397
- try {
398
- step(generator["throw"](value));
399
- } catch (e) {
400
- reject(e);
401
- }
402
- }
403
- function step(result) {
404
- result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
405
- }
406
- step((generator = generator.apply(thisArg, _arguments || [])).next());
407
- });
408
- };
409
- var __generator = exports && exports.__generator || function(thisArg, body) {
410
- var _ = { label: 0, sent: function() {
411
- if (t[0] & 1) throw t[1];
412
- return t[1];
413
- }, trys: [], ops: [] }, f, y, t, g;
414
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
415
- return this;
416
- }), g;
417
- function verb(n) {
418
- return function(v) {
419
- return step([n, v]);
420
- };
421
- }
422
- function step(op) {
423
- if (f) throw new TypeError("Generator is already executing.");
424
- while (_) try {
425
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
426
- if (y = 0, t) op = [op[0] & 2, t.value];
427
- switch (op[0]) {
428
- case 0:
429
- case 1:
430
- t = op;
431
- break;
432
- case 4:
433
- _.label++;
434
- return { value: op[1], done: false };
435
- case 5:
436
- _.label++;
437
- y = op[1];
438
- op = [0];
439
- continue;
440
- case 7:
441
- op = _.ops.pop();
442
- _.trys.pop();
443
- continue;
444
- default:
445
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
446
- _ = 0;
447
- continue;
448
- }
449
- if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
450
- _.label = op[1];
451
- break;
452
- }
453
- if (op[0] === 6 && _.label < t[1]) {
454
- _.label = t[1];
455
- t = op;
456
- break;
457
- }
458
- if (t && _.label < t[2]) {
459
- _.label = t[2];
460
- _.ops.push(op);
461
- break;
462
- }
463
- if (t[2]) _.ops.pop();
464
- _.trys.pop();
465
- continue;
466
- }
467
- op = body.call(thisArg, _);
468
- } catch (e) {
469
- op = [6, e];
470
- y = 0;
471
- } finally {
472
- f = t = 0;
473
- }
474
- if (op[0] & 5) throw op[1];
475
- return { value: op[0] ? op[1] : void 0, done: true };
476
- }
477
- };
478
- Object.defineProperty(exports, "__esModule", { value: true });
479
- var options_1 = require_options();
480
- var delay_factory_1 = require_delay_factory();
481
- function backOff2(request, options) {
482
- if (options === void 0) {
483
- options = {};
484
- }
485
- return __awaiter(this, void 0, void 0, function() {
486
- var sanitizedOptions, backOff3;
487
- return __generator(this, function(_a) {
488
- switch (_a.label) {
489
- case 0:
490
- sanitizedOptions = options_1.getSanitizedOptions(options);
491
- backOff3 = new BackOff(request, sanitizedOptions);
492
- return [4, backOff3.execute()];
493
- case 1:
494
- return [2, _a.sent()];
495
- }
496
- });
497
- });
498
- }
499
- exports.backOff = backOff2;
500
- var BackOff = (
501
- /** @class */
502
- function() {
503
- function BackOff2(request, options) {
504
- this.request = request;
505
- this.options = options;
506
- this.attemptNumber = 0;
507
- }
508
- BackOff2.prototype.execute = function() {
509
- return __awaiter(this, void 0, void 0, function() {
510
- var e_1, shouldRetry;
511
- return __generator(this, function(_a) {
512
- switch (_a.label) {
513
- case 0:
514
- if (!!this.attemptLimitReached) return [3, 7];
515
- _a.label = 1;
516
- case 1:
517
- _a.trys.push([1, 4, , 6]);
518
- return [4, this.applyDelay()];
519
- case 2:
520
- _a.sent();
521
- return [4, this.request()];
522
- case 3:
523
- return [2, _a.sent()];
524
- case 4:
525
- e_1 = _a.sent();
526
- this.attemptNumber++;
527
- return [4, this.options.retry(e_1, this.attemptNumber)];
528
- case 5:
529
- shouldRetry = _a.sent();
530
- if (!shouldRetry || this.attemptLimitReached) {
531
- throw e_1;
532
- }
533
- return [3, 6];
534
- case 6:
535
- return [3, 0];
536
- case 7:
537
- throw new Error("Something went wrong.");
538
- }
539
- });
540
- });
541
- };
542
- Object.defineProperty(BackOff2.prototype, "attemptLimitReached", {
543
- get: function() {
544
- return this.attemptNumber >= this.options.numOfAttempts;
545
- },
546
- enumerable: true,
547
- configurable: true
548
- });
549
- BackOff2.prototype.applyDelay = function() {
550
- return __awaiter(this, void 0, void 0, function() {
551
- var delay;
552
- return __generator(this, function(_a) {
553
- switch (_a.label) {
554
- case 0:
555
- delay = delay_factory_1.DelayFactory(this.options, this.attemptNumber);
556
- return [4, delay.apply()];
557
- case 1:
558
- _a.sent();
559
- return [
560
- 2
561
- /*return*/
562
- ];
563
- }
564
- });
565
- });
566
- };
567
- return BackOff2;
568
- }()
569
- );
570
- }
571
- });
572
-
573
- // src/ari-client/ariClient.ts
574
- var import_exponential_backoff = __toESM(require_backoff(), 1);
575
-
576
1
  // src/ari-client/baseClient.ts
577
2
  import { EventEmitter } from "events";
578
3
  import axios from "axios";
@@ -874,8 +299,17 @@ var ChannelInstance = class extends EventEmitter2 {
874
299
  this.baseClient = baseClient;
875
300
  this.channelId = channelId;
876
301
  this.id = channelId || `channel-${Date.now()}`;
877
- this.baseClient.onWebSocketEvent((event) => {
878
- if (this.isChannelEvent(event) && event.channel?.id === this.channelId) {
302
+ const wsClients = this.client.getWebSocketClients();
303
+ const wsClient = Array.from(wsClients.values()).find(
304
+ (client2) => client2.isConnected()
305
+ );
306
+ if (!wsClient) {
307
+ throw new Error(
308
+ `Nenhum WebSocket conectado dispon\xEDvel para o canal: ${this.channelId}`
309
+ );
310
+ }
311
+ wsClient.on("message", (event) => {
312
+ if (this.isChannelEvent(event)) {
879
313
  console.log(`Evento recebido no ChannelInstance: ${event.type}`, event);
880
314
  this.emit(event.type, event);
881
315
  }
@@ -1701,22 +1135,14 @@ var AriClient = class {
1701
1135
  channelInstances = /* @__PURE__ */ new Map();
1702
1136
  pendingListeners = [];
1703
1137
  processPendingListeners() {
1704
- if (this.wsClients.size === 0) {
1705
- console.warn(
1706
- "Nenhuma conex\xE3o WebSocket est\xE1 pronta. N\xE3o \xE9 poss\xEDvel processar a fila."
1707
- );
1708
- return;
1709
- }
1710
- console.log(
1711
- `Processando ${this.pendingListeners.length} listeners pendentes...`
1712
- );
1713
- while (this.pendingListeners.length > 0) {
1714
- const { event, callback } = this.pendingListeners.shift();
1715
- console.log(`Registrando listener pendente para evento: ${event}`);
1716
- for (const [app, wsClient] of this.wsClients.entries()) {
1717
- console.log(
1718
- `Registrando listener no app '${app}' para evento: ${event}`
1719
- );
1138
+ for (const [app, wsClient] of this.wsClients.entries()) {
1139
+ if (!wsClient.isConnected()) {
1140
+ console.warn(`WebSocket para o app '${app}' ainda n\xE3o est\xE1 conectado.`);
1141
+ continue;
1142
+ }
1143
+ while (this.pendingListeners.length > 0) {
1144
+ const { event, callback } = this.pendingListeners.shift();
1145
+ console.log(`Registrando listener para '${app}' no evento: ${event}`);
1720
1146
  wsClient.on(event, callback);
1721
1147
  }
1722
1148
  }
@@ -1728,6 +1154,10 @@ var AriClient = class {
1728
1154
  sounds;
1729
1155
  asterisk;
1730
1156
  bridges;
1157
+ // Getter para wsClients
1158
+ getWebSocketClients() {
1159
+ return this.wsClients;
1160
+ }
1731
1161
  /**
1732
1162
  * Registra um listener para eventos de WebSocket relacionados a canais.
1733
1163
  * @param eventType Tipo de evento.
@@ -1747,8 +1177,7 @@ var AriClient = class {
1747
1177
  }
1748
1178
  }
1749
1179
  /**
1750
- * Registra um listener para eventos globais de WebSocket.
1751
- * O channel no evento será automaticamente transformado em uma instância de ChannelInstance.
1180
+ * Registra listeners globais para eventos de WebSocket.
1752
1181
  */
1753
1182
  on(eventType, callback) {
1754
1183
  console.log(`Registrando listener global para evento: ${eventType}`);
@@ -1765,9 +1194,10 @@ var AriClient = class {
1765
1194
  }
1766
1195
  callback(event);
1767
1196
  };
1197
+ for (const [_app, wsClient] of this.wsClients.entries()) {
1198
+ wsClient.on(eventType, wrappedCallback);
1199
+ }
1768
1200
  this.eventListeners.set(eventType, wrappedCallback);
1769
- this.pendingListeners.push({ event: eventType, callback: wrappedCallback });
1770
- this.processPendingListeners();
1771
1201
  }
1772
1202
  /**
1773
1203
  * Type guard to check if the given data object contains a valid channel property.
@@ -1830,7 +1260,13 @@ var AriClient = class {
1830
1260
  throw new Error("\xC9 necess\xE1rio fornecer pelo menos um aplicativo.");
1831
1261
  }
1832
1262
  return Promise.all(
1833
- apps.map((app) => this.connectSingleWebSocket(app, subscribedEvents))
1263
+ apps.map(async (app) => {
1264
+ if (this.wsClients.has(app)) {
1265
+ console.log(`Conex\xE3o WebSocket para '${app}' j\xE1 existe. Ignorando.`);
1266
+ return;
1267
+ }
1268
+ await this.connectSingleWebSocket(app, subscribedEvents);
1269
+ })
1834
1270
  );
1835
1271
  }
1836
1272
  /**
@@ -1840,60 +1276,26 @@ var AriClient = class {
1840
1276
  if (!app) {
1841
1277
  throw new Error("O nome do aplicativo \xE9 obrigat\xF3rio.");
1842
1278
  }
1843
- if (this.webSocketReady.get(app)) {
1844
- console.log(`Conex\xE3o WebSocket para '${app}' j\xE1 est\xE1 ativa.`);
1845
- return this.webSocketReady.get(app);
1279
+ if (this.wsClients.has(app)) {
1280
+ console.log(`Conex\xE3o WebSocket para '${app}' j\xE1 existe. Reutilizando...`);
1281
+ return;
1846
1282
  }
1847
1283
  const protocol = this.config.secure ? "wss" : "ws";
1848
1284
  const eventsParam = subscribedEvents && subscribedEvents.length > 0 ? `&event=${subscribedEvents.join(",")}` : "&subscribeAll=true";
1849
1285
  const wsUrl = `${protocol}://${encodeURIComponent(
1850
1286
  this.config.username
1851
1287
  )}:${encodeURIComponent(this.config.password)}@${this.config.host}:${this.config.port}/ari/events?app=${app}${eventsParam}`;
1852
- const backoffOptions = {
1853
- delayFirstAttempt: false,
1854
- startingDelay: 1e3,
1855
- timeMultiple: 2,
1856
- maxDelay: 3e4,
1857
- numOfAttempts: 10,
1858
- jitter: "full",
1859
- retry: (error, attemptNumber) => {
1860
- console.warn(`Tentativa ${attemptNumber} falhou: ${error.message}`);
1861
- return Array.from(this.wsClients.values()).some(
1862
- (wsClient) => !wsClient.isConnected()
1863
- );
1864
- }
1865
- };
1866
- const webSocketPromise = new Promise(async (resolve, reject) => {
1867
- try {
1868
- if (this.isReconnecting.get(app)) {
1869
- console.warn(`J\xE1 est\xE1 tentando reconectar para o app '${app}'.`);
1870
- return;
1871
- }
1872
- this.isReconnecting.set(app, true);
1873
- const wsClient = new WebSocketClient(wsUrl);
1874
- await (0, import_exponential_backoff.backOff)(async () => {
1875
- if (!wsClient) {
1876
- throw new Error("WebSocketClient instance is null.");
1877
- }
1878
- await wsClient.connect();
1879
- this.integrateWebSocketEvents(app, wsClient);
1880
- console.log(`WebSocket conectado para o app: ${app}`);
1881
- await this.ensureAppRegistered(app);
1882
- this.wsClients.set(app, wsClient);
1883
- }, backoffOptions);
1884
- resolve();
1885
- } catch (error) {
1886
- console.error(
1887
- `Erro ao conectar o WebSocket para o app '${app}':`,
1888
- error
1889
- );
1890
- reject(error);
1891
- } finally {
1892
- this.isReconnecting.delete(app);
1893
- }
1894
- });
1895
- this.webSocketReady.set(app, webSocketPromise);
1896
- return webSocketPromise;
1288
+ const wsClient = new WebSocketClient(wsUrl);
1289
+ try {
1290
+ await wsClient.connect();
1291
+ console.log(`WebSocket conectado para o app: ${app}`);
1292
+ this.integrateWebSocketEvents(app, wsClient);
1293
+ await this.ensureAppRegistered(app);
1294
+ this.wsClients.set(app, wsClient);
1295
+ } catch (error) {
1296
+ console.error(`Erro ao conectar WebSocket para '${app}':`, error);
1297
+ throw error;
1298
+ }
1897
1299
  }
1898
1300
  /**
1899
1301
  * Integrates WebSocket events with playback listeners.
@@ -1904,6 +1306,10 @@ var AriClient = class {
1904
1306
  `WebSocket client para o app '${app}' n\xE3o est\xE1 conectado.`
1905
1307
  );
1906
1308
  }
1309
+ if (wsClient.listenerCount("PlaybackStarted") > 0) {
1310
+ console.log(`[${app}] Eventos j\xE1 registrados. Ignorando.`);
1311
+ return;
1312
+ }
1907
1313
  const eventHandlers = {
1908
1314
  PlaybackStarted: (data) => {
1909
1315
  if ("playbackId" in data) {