@ipcom/asterisk-ari 0.0.76 → 0.0.78

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.
@@ -5,6 +5,9 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
6
  var __getProtoOf = Object.getPrototypeOf;
7
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __commonJS = (cb, mod) => function __require() {
9
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
10
+ };
8
11
  var __export = (target, all) => {
9
12
  for (var name in all)
10
13
  __defProp(target, name, { get: all[name], enumerable: true });
@@ -27,6 +30,552 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
27
30
  ));
28
31
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
32
 
33
+ // node_modules/exponential-backoff/dist/options.js
34
+ var require_options = __commonJS({
35
+ "node_modules/exponential-backoff/dist/options.js"(exports2) {
36
+ "use strict";
37
+ var __assign = exports2 && exports2.__assign || function() {
38
+ __assign = Object.assign || function(t) {
39
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
40
+ s = arguments[i];
41
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
42
+ t[p] = s[p];
43
+ }
44
+ return t;
45
+ };
46
+ return __assign.apply(this, arguments);
47
+ };
48
+ Object.defineProperty(exports2, "__esModule", { value: true });
49
+ var defaultOptions = {
50
+ delayFirstAttempt: false,
51
+ jitter: "none",
52
+ maxDelay: Infinity,
53
+ numOfAttempts: 10,
54
+ retry: function() {
55
+ return true;
56
+ },
57
+ startingDelay: 100,
58
+ timeMultiple: 2
59
+ };
60
+ function getSanitizedOptions(options) {
61
+ var sanitized = __assign(__assign({}, defaultOptions), options);
62
+ if (sanitized.numOfAttempts < 1) {
63
+ sanitized.numOfAttempts = 1;
64
+ }
65
+ return sanitized;
66
+ }
67
+ exports2.getSanitizedOptions = getSanitizedOptions;
68
+ }
69
+ });
70
+
71
+ // node_modules/exponential-backoff/dist/jitter/full/full.jitter.js
72
+ var require_full_jitter = __commonJS({
73
+ "node_modules/exponential-backoff/dist/jitter/full/full.jitter.js"(exports2) {
74
+ "use strict";
75
+ Object.defineProperty(exports2, "__esModule", { value: true });
76
+ function fullJitter(delay) {
77
+ var jitteredDelay = Math.random() * delay;
78
+ return Math.round(jitteredDelay);
79
+ }
80
+ exports2.fullJitter = fullJitter;
81
+ }
82
+ });
83
+
84
+ // node_modules/exponential-backoff/dist/jitter/no/no.jitter.js
85
+ var require_no_jitter = __commonJS({
86
+ "node_modules/exponential-backoff/dist/jitter/no/no.jitter.js"(exports2) {
87
+ "use strict";
88
+ Object.defineProperty(exports2, "__esModule", { value: true });
89
+ function noJitter(delay) {
90
+ return delay;
91
+ }
92
+ exports2.noJitter = noJitter;
93
+ }
94
+ });
95
+
96
+ // node_modules/exponential-backoff/dist/jitter/jitter.factory.js
97
+ var require_jitter_factory = __commonJS({
98
+ "node_modules/exponential-backoff/dist/jitter/jitter.factory.js"(exports2) {
99
+ "use strict";
100
+ Object.defineProperty(exports2, "__esModule", { value: true });
101
+ var full_jitter_1 = require_full_jitter();
102
+ var no_jitter_1 = require_no_jitter();
103
+ function JitterFactory(options) {
104
+ switch (options.jitter) {
105
+ case "full":
106
+ return full_jitter_1.fullJitter;
107
+ case "none":
108
+ default:
109
+ return no_jitter_1.noJitter;
110
+ }
111
+ }
112
+ exports2.JitterFactory = JitterFactory;
113
+ }
114
+ });
115
+
116
+ // node_modules/exponential-backoff/dist/delay/delay.base.js
117
+ var require_delay_base = __commonJS({
118
+ "node_modules/exponential-backoff/dist/delay/delay.base.js"(exports2) {
119
+ "use strict";
120
+ Object.defineProperty(exports2, "__esModule", { value: true });
121
+ var jitter_factory_1 = require_jitter_factory();
122
+ var Delay = (
123
+ /** @class */
124
+ function() {
125
+ function Delay2(options) {
126
+ this.options = options;
127
+ this.attempt = 0;
128
+ }
129
+ Delay2.prototype.apply = function() {
130
+ var _this = this;
131
+ return new Promise(function(resolve) {
132
+ return setTimeout(resolve, _this.jitteredDelay);
133
+ });
134
+ };
135
+ Delay2.prototype.setAttemptNumber = function(attempt) {
136
+ this.attempt = attempt;
137
+ };
138
+ Object.defineProperty(Delay2.prototype, "jitteredDelay", {
139
+ get: function() {
140
+ var jitter = jitter_factory_1.JitterFactory(this.options);
141
+ return jitter(this.delay);
142
+ },
143
+ enumerable: true,
144
+ configurable: true
145
+ });
146
+ Object.defineProperty(Delay2.prototype, "delay", {
147
+ get: function() {
148
+ var constant = this.options.startingDelay;
149
+ var base = this.options.timeMultiple;
150
+ var power = this.numOfDelayedAttempts;
151
+ var delay = constant * Math.pow(base, power);
152
+ return Math.min(delay, this.options.maxDelay);
153
+ },
154
+ enumerable: true,
155
+ configurable: true
156
+ });
157
+ Object.defineProperty(Delay2.prototype, "numOfDelayedAttempts", {
158
+ get: function() {
159
+ return this.attempt;
160
+ },
161
+ enumerable: true,
162
+ configurable: true
163
+ });
164
+ return Delay2;
165
+ }()
166
+ );
167
+ exports2.Delay = Delay;
168
+ }
169
+ });
170
+
171
+ // node_modules/exponential-backoff/dist/delay/skip-first/skip-first.delay.js
172
+ var require_skip_first_delay = __commonJS({
173
+ "node_modules/exponential-backoff/dist/delay/skip-first/skip-first.delay.js"(exports2) {
174
+ "use strict";
175
+ var __extends = exports2 && exports2.__extends || /* @__PURE__ */ function() {
176
+ var extendStatics = function(d, b) {
177
+ extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
178
+ d2.__proto__ = b2;
179
+ } || function(d2, b2) {
180
+ for (var p in b2) if (b2.hasOwnProperty(p)) d2[p] = b2[p];
181
+ };
182
+ return extendStatics(d, b);
183
+ };
184
+ return function(d, b) {
185
+ extendStatics(d, b);
186
+ function __() {
187
+ this.constructor = d;
188
+ }
189
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
190
+ };
191
+ }();
192
+ var __awaiter = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
193
+ function adopt(value) {
194
+ return value instanceof P ? value : new P(function(resolve) {
195
+ resolve(value);
196
+ });
197
+ }
198
+ return new (P || (P = Promise))(function(resolve, reject) {
199
+ function fulfilled(value) {
200
+ try {
201
+ step(generator.next(value));
202
+ } catch (e) {
203
+ reject(e);
204
+ }
205
+ }
206
+ function rejected(value) {
207
+ try {
208
+ step(generator["throw"](value));
209
+ } catch (e) {
210
+ reject(e);
211
+ }
212
+ }
213
+ function step(result) {
214
+ result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
215
+ }
216
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
217
+ });
218
+ };
219
+ var __generator = exports2 && exports2.__generator || function(thisArg, body) {
220
+ var _ = { label: 0, sent: function() {
221
+ if (t[0] & 1) throw t[1];
222
+ return t[1];
223
+ }, trys: [], ops: [] }, f, y, t, g;
224
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
225
+ return this;
226
+ }), g;
227
+ function verb(n) {
228
+ return function(v) {
229
+ return step([n, v]);
230
+ };
231
+ }
232
+ function step(op) {
233
+ if (f) throw new TypeError("Generator is already executing.");
234
+ while (_) try {
235
+ 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;
236
+ if (y = 0, t) op = [op[0] & 2, t.value];
237
+ switch (op[0]) {
238
+ case 0:
239
+ case 1:
240
+ t = op;
241
+ break;
242
+ case 4:
243
+ _.label++;
244
+ return { value: op[1], done: false };
245
+ case 5:
246
+ _.label++;
247
+ y = op[1];
248
+ op = [0];
249
+ continue;
250
+ case 7:
251
+ op = _.ops.pop();
252
+ _.trys.pop();
253
+ continue;
254
+ default:
255
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
256
+ _ = 0;
257
+ continue;
258
+ }
259
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
260
+ _.label = op[1];
261
+ break;
262
+ }
263
+ if (op[0] === 6 && _.label < t[1]) {
264
+ _.label = t[1];
265
+ t = op;
266
+ break;
267
+ }
268
+ if (t && _.label < t[2]) {
269
+ _.label = t[2];
270
+ _.ops.push(op);
271
+ break;
272
+ }
273
+ if (t[2]) _.ops.pop();
274
+ _.trys.pop();
275
+ continue;
276
+ }
277
+ op = body.call(thisArg, _);
278
+ } catch (e) {
279
+ op = [6, e];
280
+ y = 0;
281
+ } finally {
282
+ f = t = 0;
283
+ }
284
+ if (op[0] & 5) throw op[1];
285
+ return { value: op[0] ? op[1] : void 0, done: true };
286
+ }
287
+ };
288
+ Object.defineProperty(exports2, "__esModule", { value: true });
289
+ var delay_base_1 = require_delay_base();
290
+ var SkipFirstDelay = (
291
+ /** @class */
292
+ function(_super) {
293
+ __extends(SkipFirstDelay2, _super);
294
+ function SkipFirstDelay2() {
295
+ return _super !== null && _super.apply(this, arguments) || this;
296
+ }
297
+ SkipFirstDelay2.prototype.apply = function() {
298
+ return __awaiter(this, void 0, void 0, function() {
299
+ return __generator(this, function(_a) {
300
+ return [2, this.isFirstAttempt ? true : _super.prototype.apply.call(this)];
301
+ });
302
+ });
303
+ };
304
+ Object.defineProperty(SkipFirstDelay2.prototype, "isFirstAttempt", {
305
+ get: function() {
306
+ return this.attempt === 0;
307
+ },
308
+ enumerable: true,
309
+ configurable: true
310
+ });
311
+ Object.defineProperty(SkipFirstDelay2.prototype, "numOfDelayedAttempts", {
312
+ get: function() {
313
+ return this.attempt - 1;
314
+ },
315
+ enumerable: true,
316
+ configurable: true
317
+ });
318
+ return SkipFirstDelay2;
319
+ }(delay_base_1.Delay)
320
+ );
321
+ exports2.SkipFirstDelay = SkipFirstDelay;
322
+ }
323
+ });
324
+
325
+ // node_modules/exponential-backoff/dist/delay/always/always.delay.js
326
+ var require_always_delay = __commonJS({
327
+ "node_modules/exponential-backoff/dist/delay/always/always.delay.js"(exports2) {
328
+ "use strict";
329
+ var __extends = exports2 && exports2.__extends || /* @__PURE__ */ function() {
330
+ var extendStatics = function(d, b) {
331
+ extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
332
+ d2.__proto__ = b2;
333
+ } || function(d2, b2) {
334
+ for (var p in b2) if (b2.hasOwnProperty(p)) d2[p] = b2[p];
335
+ };
336
+ return extendStatics(d, b);
337
+ };
338
+ return function(d, b) {
339
+ extendStatics(d, b);
340
+ function __() {
341
+ this.constructor = d;
342
+ }
343
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
344
+ };
345
+ }();
346
+ Object.defineProperty(exports2, "__esModule", { value: true });
347
+ var delay_base_1 = require_delay_base();
348
+ var AlwaysDelay = (
349
+ /** @class */
350
+ function(_super) {
351
+ __extends(AlwaysDelay2, _super);
352
+ function AlwaysDelay2() {
353
+ return _super !== null && _super.apply(this, arguments) || this;
354
+ }
355
+ return AlwaysDelay2;
356
+ }(delay_base_1.Delay)
357
+ );
358
+ exports2.AlwaysDelay = AlwaysDelay;
359
+ }
360
+ });
361
+
362
+ // node_modules/exponential-backoff/dist/delay/delay.factory.js
363
+ var require_delay_factory = __commonJS({
364
+ "node_modules/exponential-backoff/dist/delay/delay.factory.js"(exports2) {
365
+ "use strict";
366
+ Object.defineProperty(exports2, "__esModule", { value: true });
367
+ var skip_first_delay_1 = require_skip_first_delay();
368
+ var always_delay_1 = require_always_delay();
369
+ function DelayFactory(options, attempt) {
370
+ var delay = initDelayClass(options);
371
+ delay.setAttemptNumber(attempt);
372
+ return delay;
373
+ }
374
+ exports2.DelayFactory = DelayFactory;
375
+ function initDelayClass(options) {
376
+ if (!options.delayFirstAttempt) {
377
+ return new skip_first_delay_1.SkipFirstDelay(options);
378
+ }
379
+ return new always_delay_1.AlwaysDelay(options);
380
+ }
381
+ }
382
+ });
383
+
384
+ // node_modules/exponential-backoff/dist/backoff.js
385
+ var require_backoff = __commonJS({
386
+ "node_modules/exponential-backoff/dist/backoff.js"(exports2) {
387
+ "use strict";
388
+ var __awaiter = exports2 && exports2.__awaiter || function(thisArg, _arguments, P, generator) {
389
+ function adopt(value) {
390
+ return value instanceof P ? value : new P(function(resolve) {
391
+ resolve(value);
392
+ });
393
+ }
394
+ return new (P || (P = Promise))(function(resolve, reject) {
395
+ function fulfilled(value) {
396
+ try {
397
+ step(generator.next(value));
398
+ } catch (e) {
399
+ reject(e);
400
+ }
401
+ }
402
+ function rejected(value) {
403
+ try {
404
+ step(generator["throw"](value));
405
+ } catch (e) {
406
+ reject(e);
407
+ }
408
+ }
409
+ function step(result) {
410
+ result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
411
+ }
412
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
413
+ });
414
+ };
415
+ var __generator = exports2 && exports2.__generator || function(thisArg, body) {
416
+ var _ = { label: 0, sent: function() {
417
+ if (t[0] & 1) throw t[1];
418
+ return t[1];
419
+ }, trys: [], ops: [] }, f, y, t, g;
420
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
421
+ return this;
422
+ }), g;
423
+ function verb(n) {
424
+ return function(v) {
425
+ return step([n, v]);
426
+ };
427
+ }
428
+ function step(op) {
429
+ if (f) throw new TypeError("Generator is already executing.");
430
+ while (_) try {
431
+ 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;
432
+ if (y = 0, t) op = [op[0] & 2, t.value];
433
+ switch (op[0]) {
434
+ case 0:
435
+ case 1:
436
+ t = op;
437
+ break;
438
+ case 4:
439
+ _.label++;
440
+ return { value: op[1], done: false };
441
+ case 5:
442
+ _.label++;
443
+ y = op[1];
444
+ op = [0];
445
+ continue;
446
+ case 7:
447
+ op = _.ops.pop();
448
+ _.trys.pop();
449
+ continue;
450
+ default:
451
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
452
+ _ = 0;
453
+ continue;
454
+ }
455
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
456
+ _.label = op[1];
457
+ break;
458
+ }
459
+ if (op[0] === 6 && _.label < t[1]) {
460
+ _.label = t[1];
461
+ t = op;
462
+ break;
463
+ }
464
+ if (t && _.label < t[2]) {
465
+ _.label = t[2];
466
+ _.ops.push(op);
467
+ break;
468
+ }
469
+ if (t[2]) _.ops.pop();
470
+ _.trys.pop();
471
+ continue;
472
+ }
473
+ op = body.call(thisArg, _);
474
+ } catch (e) {
475
+ op = [6, e];
476
+ y = 0;
477
+ } finally {
478
+ f = t = 0;
479
+ }
480
+ if (op[0] & 5) throw op[1];
481
+ return { value: op[0] ? op[1] : void 0, done: true };
482
+ }
483
+ };
484
+ Object.defineProperty(exports2, "__esModule", { value: true });
485
+ var options_1 = require_options();
486
+ var delay_factory_1 = require_delay_factory();
487
+ function backOff3(request, options) {
488
+ if (options === void 0) {
489
+ options = {};
490
+ }
491
+ return __awaiter(this, void 0, void 0, function() {
492
+ var sanitizedOptions, backOff4;
493
+ return __generator(this, function(_a) {
494
+ switch (_a.label) {
495
+ case 0:
496
+ sanitizedOptions = options_1.getSanitizedOptions(options);
497
+ backOff4 = new BackOff(request, sanitizedOptions);
498
+ return [4, backOff4.execute()];
499
+ case 1:
500
+ return [2, _a.sent()];
501
+ }
502
+ });
503
+ });
504
+ }
505
+ exports2.backOff = backOff3;
506
+ var BackOff = (
507
+ /** @class */
508
+ function() {
509
+ function BackOff2(request, options) {
510
+ this.request = request;
511
+ this.options = options;
512
+ this.attemptNumber = 0;
513
+ }
514
+ BackOff2.prototype.execute = function() {
515
+ return __awaiter(this, void 0, void 0, function() {
516
+ var e_1, shouldRetry;
517
+ return __generator(this, function(_a) {
518
+ switch (_a.label) {
519
+ case 0:
520
+ if (!!this.attemptLimitReached) return [3, 7];
521
+ _a.label = 1;
522
+ case 1:
523
+ _a.trys.push([1, 4, , 6]);
524
+ return [4, this.applyDelay()];
525
+ case 2:
526
+ _a.sent();
527
+ return [4, this.request()];
528
+ case 3:
529
+ return [2, _a.sent()];
530
+ case 4:
531
+ e_1 = _a.sent();
532
+ this.attemptNumber++;
533
+ return [4, this.options.retry(e_1, this.attemptNumber)];
534
+ case 5:
535
+ shouldRetry = _a.sent();
536
+ if (!shouldRetry || this.attemptLimitReached) {
537
+ throw e_1;
538
+ }
539
+ return [3, 6];
540
+ case 6:
541
+ return [3, 0];
542
+ case 7:
543
+ throw new Error("Something went wrong.");
544
+ }
545
+ });
546
+ });
547
+ };
548
+ Object.defineProperty(BackOff2.prototype, "attemptLimitReached", {
549
+ get: function() {
550
+ return this.attemptNumber >= this.options.numOfAttempts;
551
+ },
552
+ enumerable: true,
553
+ configurable: true
554
+ });
555
+ BackOff2.prototype.applyDelay = function() {
556
+ return __awaiter(this, void 0, void 0, function() {
557
+ var delay;
558
+ return __generator(this, function(_a) {
559
+ switch (_a.label) {
560
+ case 0:
561
+ delay = delay_factory_1.DelayFactory(this.options, this.attemptNumber);
562
+ return [4, delay.apply()];
563
+ case 1:
564
+ _a.sent();
565
+ return [
566
+ 2
567
+ /*return*/
568
+ ];
569
+ }
570
+ });
571
+ });
572
+ };
573
+ return BackOff2;
574
+ }()
575
+ );
576
+ }
577
+ });
578
+
30
579
  // src/index.ts
31
580
  var src_exports = {};
32
581
  __export(src_exports, {
@@ -43,12 +592,17 @@ __export(src_exports, {
43
592
  });
44
593
  module.exports = __toCommonJS(src_exports);
45
594
 
595
+ // src/ari-client/ariClient.ts
596
+ var import_exponential_backoff2 = __toESM(require_backoff(), 1);
597
+
46
598
  // src/ari-client/baseClient.ts
47
599
  var import_events = require("events");
48
600
  var import_axios = __toESM(require("axios"), 1);
49
601
  var BaseClient = class {
50
602
  client;
51
603
  eventEmitter = new import_events.EventEmitter();
604
+ wsClients = /* @__PURE__ */ new Map();
605
+ // Gerencia os WebSocket clients
52
606
  constructor(baseUrl, username, password) {
53
607
  this.client = import_axios.default.create({
54
608
  baseURL: baseUrl,
@@ -89,9 +643,46 @@ var BaseClient = class {
89
643
  const response = await this.client.delete(path);
90
644
  return response.data;
91
645
  }
646
+ // Gerenciamento de WebSocket clients
647
+ /**
648
+ * Adiciona um WebSocket client ao gerenciador.
649
+ * @param app - Nome do aplicativo ou contexto associado.
650
+ * @param wsClient - Instância do WebSocketClient.
651
+ */
652
+ addWebSocketClient(app, wsClient) {
653
+ if (this.wsClients.has(app)) {
654
+ throw new Error(`J\xE1 existe um WebSocket client registrado para '${app}'`);
655
+ }
656
+ this.wsClients.set(app, wsClient);
657
+ console.log(`WebSocket client adicionado para '${app}'`);
658
+ }
659
+ /**
660
+ * Remove um WebSocket client do gerenciador.
661
+ * @param app - Nome do aplicativo ou contexto associado.
662
+ */
663
+ removeWebSocketClient(app) {
664
+ if (!this.wsClients.has(app)) {
665
+ throw new Error(`Nenhum WebSocket client encontrado para '${app}'`);
666
+ }
667
+ this.wsClients.delete(app);
668
+ console.log(`WebSocket client removido para '${app}'`);
669
+ }
670
+ /**
671
+ * Obtém todos os WebSocket clients.
672
+ * @returns Um Map contendo todos os WebSocket clients registrados.
673
+ */
674
+ getWebSocketClients() {
675
+ return this.wsClients;
676
+ }
92
677
  /**
93
- * Escuta eventos do WebSocket.
678
+ * Obtém um WebSocket client específico.
679
+ * @param app - Nome do aplicativo ou contexto associado.
680
+ * @returns O WebSocket client correspondente.
94
681
  */
682
+ getWebSocketClient(app) {
683
+ return this.wsClients.get(app);
684
+ }
685
+ // Gerenciamento de eventos WebSocket
95
686
  onWebSocketEvent(callback) {
96
687
  console.log("Registrando callback para eventos do WebSocket");
97
688
  this.eventEmitter.on("websocketEvent", (event) => {
@@ -99,9 +690,6 @@ var BaseClient = class {
99
690
  callback(event);
100
691
  });
101
692
  }
102
- /**
103
- * Emite eventos do WebSocket.
104
- */
105
693
  emitWebSocketEvent(event) {
106
694
  console.log("Emitindo evento do WebSocket:", event);
107
695
  this.eventEmitter.emit("websocketEvent", event);
@@ -332,6 +920,9 @@ function toQueryParams2(options) {
332
920
  Object.entries(options).filter(([, value]) => value !== void 0).map(([key, value]) => [key, value])
333
921
  ).toString();
334
922
  }
923
+ function isPlaybackEvent(event, playbackId) {
924
+ return event.type.startsWith("Playback") && "playbackId" in event && event.playbackId !== void 0 && (!playbackId || event.playbackId === playbackId);
925
+ }
335
926
  function isChannelEvent(event, channelId) {
336
927
  const hasChannel = "channel" in event && event.channel?.id !== void 0;
337
928
  const matchesChannelId = hasChannel && (!channelId || event.channel?.id === channelId);
@@ -578,7 +1169,7 @@ var Channels = class extends import_events2.EventEmitter {
578
1169
  this.baseClient = baseClient;
579
1170
  this.client = client;
580
1171
  }
581
- createChannelInstance(channelId) {
1172
+ Channel(channelId) {
582
1173
  return new ChannelInstance(this.client, this.baseClient, channelId);
583
1174
  }
584
1175
  /**
@@ -809,25 +1400,30 @@ var Endpoints = class {
809
1400
  var import_events3 = require("events");
810
1401
  var PlaybackInstance = class extends import_events3.EventEmitter {
811
1402
  // Garantimos que o ID esteja disponível
812
- constructor(baseClient, playbackId) {
1403
+ constructor(client, baseClient, playbackId) {
813
1404
  super();
1405
+ this.client = client;
814
1406
  this.baseClient = baseClient;
815
1407
  this.playbackId = playbackId;
816
1408
  this.id = playbackId || `playback-${Date.now()}`;
817
- this.baseClient.onWebSocketEvent((event) => {
818
- if (this.isPlaybackEvent(event) && event.playbackId === this.playbackId) {
1409
+ const wsClients = this.client.getWebSocketClients();
1410
+ const wsClient = Array.from(wsClients.values()).find(
1411
+ (client2) => client2.isConnected()
1412
+ );
1413
+ if (!wsClient) {
1414
+ throw new Error(
1415
+ `Nenhum WebSocket conectado dispon\xEDvel para o playback: ${this.id}`
1416
+ );
1417
+ }
1418
+ wsClient.on("message", (event) => {
1419
+ if (isPlaybackEvent(event, this.id)) {
1420
+ console.log(`Evento recebido no ChannelInstance: ${event.type}`, event);
819
1421
  this.emit(event.type, event);
820
1422
  }
821
1423
  });
822
1424
  }
823
1425
  playbackData = null;
824
1426
  id;
825
- /**
826
- * Verifica se o evento é relacionado a um playback.
827
- */
828
- isPlaybackEvent(event) {
829
- return event && typeof event === "object" && "playbackId" in event;
830
- }
831
1427
  /**
832
1428
  * Obtém os detalhes do playback.
833
1429
  */
@@ -882,32 +1478,23 @@ var PlaybackInstance = class extends import_events3.EventEmitter {
882
1478
  }
883
1479
  };
884
1480
  var Playbacks = class extends import_events3.EventEmitter {
885
- constructor(client) {
1481
+ constructor(baseClient, client) {
886
1482
  super();
1483
+ this.baseClient = baseClient;
887
1484
  this.client = client;
888
- this.client.onWebSocketEvent((event) => {
889
- if (this.isPlaybackEvent(event)) {
890
- const playbackId = event.playbackId;
891
- if (playbackId) {
892
- this.emit(`${event.type}:${playbackId}`, event);
893
- }
894
- this.emit(event.type, event);
895
- }
896
- });
897
- }
898
- /**
899
- * Verifica se o evento é relacionado a um playback.
900
- */
901
- isPlaybackEvent(event) {
902
- console.log({ eventAri: event });
903
- return event && typeof event === "object" && "playbackId" in event;
904
1485
  }
905
1486
  /**
906
1487
  * Inicializa uma nova instância de `PlaybackInstance`.
907
1488
  */
908
1489
  Playback(playbackId) {
909
1490
  const id = playbackId || `playback-${Date.now()}`;
910
- return new PlaybackInstance(this.client, id);
1491
+ return new PlaybackInstance(this.client, this.baseClient, id);
1492
+ }
1493
+ /**
1494
+ * Obtém os clientes WebSocket disponíveis.
1495
+ */
1496
+ getWebSocketClients() {
1497
+ return this.client.getWebSocketClients();
911
1498
  }
912
1499
  /**
913
1500
  * Emite eventos de playback.
@@ -929,7 +1516,7 @@ var Playbacks = class extends import_events3.EventEmitter {
929
1516
  * @returns A promise that resolves to a Playback object containing the details of the specified playback.
930
1517
  */
931
1518
  async getDetails(playbackId) {
932
- return this.client.get(`/playbacks/${playbackId}`);
1519
+ return this.baseClient.get(`/playbacks/${playbackId}`);
933
1520
  }
934
1521
  /**
935
1522
  * Controls a specific playback by performing various operations such as pause, resume, restart, reverse, forward, or stop.
@@ -945,7 +1532,7 @@ var Playbacks = class extends import_events3.EventEmitter {
945
1532
  * @returns A promise that resolves when the control operation is successfully executed.
946
1533
  */
947
1534
  async control(playbackId, operation) {
948
- await this.client.post(
1535
+ await this.baseClient.post(
949
1536
  `/playbacks/${playbackId}/control?operation=${operation}`
950
1537
  );
951
1538
  }
@@ -956,7 +1543,7 @@ var Playbacks = class extends import_events3.EventEmitter {
956
1543
  * @returns A promise that resolves when the playback is successfully stopped.
957
1544
  */
958
1545
  async stop(playbackId) {
959
- await this.client.delete(`/playbacks/${playbackId}`);
1546
+ await this.baseClient.delete(`/playbacks/${playbackId}`);
960
1547
  }
961
1548
  /**
962
1549
  * Registers a listener for playback events.
@@ -1024,8 +1611,10 @@ var Sounds = class {
1024
1611
 
1025
1612
  // src/ari-client/websocketClient.ts
1026
1613
  var import_events4 = require("events");
1614
+ var import_exponential_backoff = __toESM(require_backoff(), 1);
1027
1615
  var import_ws = __toESM(require("ws"), 1);
1028
1616
  var WebSocketClient = class extends import_events4.EventEmitter {
1617
+ // Para gerenciar tentativas de reconexão
1029
1618
  /**
1030
1619
  * Creates a new WebSocketClient instance.
1031
1620
  * @param url - The WebSocket server URL to connect to.
@@ -1038,6 +1627,44 @@ var WebSocketClient = class extends import_events4.EventEmitter {
1038
1627
  isClosedManually = false;
1039
1628
  isReconnecting = false;
1040
1629
  messageListeners = [];
1630
+ maxReconnectAttempts = 30;
1631
+ reconnectAttempts = 0;
1632
+ async reconnect() {
1633
+ console.log("Iniciando processo de reconex\xE3o...");
1634
+ const backoffOptions = {
1635
+ delayFirstAttempt: false,
1636
+ startingDelay: 1e3,
1637
+ // 1 segundo inicial
1638
+ timeMultiple: 2,
1639
+ // Multiplicador exponencial
1640
+ maxDelay: 3e4,
1641
+ // 30 segundos de atraso máximo
1642
+ numOfAttempts: this.maxReconnectAttempts,
1643
+ // Limite de tentativas
1644
+ jitter: "full",
1645
+ retry: (error, attemptNumber) => {
1646
+ console.warn(
1647
+ `Tentativa ${attemptNumber} de reconex\xE3o falhou: ${error.message}`
1648
+ );
1649
+ return !this.isClosedManually;
1650
+ }
1651
+ };
1652
+ try {
1653
+ await (0, import_exponential_backoff.backOff)(async () => {
1654
+ console.log(`Tentando reconectar (#${this.reconnectAttempts + 1})...`);
1655
+ await this.connect();
1656
+ console.log("Reconex\xE3o bem-sucedida.");
1657
+ }, backoffOptions);
1658
+ this.reconnectAttempts = 0;
1659
+ this.isReconnecting = false;
1660
+ } catch (error) {
1661
+ console.error(
1662
+ `Reconex\xE3o falhou ap\xF3s ${this.maxReconnectAttempts} tentativas.`,
1663
+ error
1664
+ );
1665
+ this.isReconnecting = false;
1666
+ }
1667
+ }
1041
1668
  /**
1042
1669
  * Establishes a connection to the WebSocket server.
1043
1670
  * @returns A Promise that resolves when the connection is established, or rejects if an error occurs.
@@ -1051,6 +1678,7 @@ var WebSocketClient = class extends import_events4.EventEmitter {
1051
1678
  console.log("WebSocket conectado.");
1052
1679
  this.isClosedManually = false;
1053
1680
  this.isReconnecting = false;
1681
+ this.reconnectAttempts = 0;
1054
1682
  resolve();
1055
1683
  });
1056
1684
  this.ws.on("error", (err) => {
@@ -1059,8 +1687,10 @@ var WebSocketClient = class extends import_events4.EventEmitter {
1059
1687
  });
1060
1688
  this.ws.on("close", (code, reason) => {
1061
1689
  console.warn(`WebSocket desconectado: ${code} - ${reason}`);
1062
- this.isReconnecting = false;
1063
1690
  this.emit("close", { code, reason });
1691
+ if (!this.isClosedManually) {
1692
+ this.reconnect();
1693
+ }
1064
1694
  });
1065
1695
  this.ws.on("message", (rawData) => {
1066
1696
  this.handleMessage(rawData);
@@ -1160,9 +1790,9 @@ var AriClient = class {
1160
1790
  const baseUrl = `${httpProtocol}://${normalizedHost}:${config.port}/ari`;
1161
1791
  this.baseClient = new BaseClient(baseUrl, config.username, config.password);
1162
1792
  this.channels = new Channels(this.baseClient, this);
1793
+ this.playbacks = new Playbacks(this.baseClient, this);
1163
1794
  this.endpoints = new Endpoints(this.baseClient);
1164
1795
  this.applications = new Applications(this.baseClient);
1165
- this.playbacks = new Playbacks(this.baseClient);
1166
1796
  this.sounds = new Sounds(this.baseClient);
1167
1797
  this.asterisk = new Asterisk(this.baseClient);
1168
1798
  this.bridges = new Bridges(this.baseClient);
@@ -1185,11 +1815,27 @@ var AriClient = class {
1185
1815
  }
1186
1816
  while (this.pendingListeners.length > 0) {
1187
1817
  const { event, callback } = this.pendingListeners.shift();
1818
+ if (wsClient.listenerCount(event) > 0) {
1819
+ console.log(
1820
+ `Listener j\xE1 registrado para o evento '${event}' no app '${app}'. Ignorando duplicata.`
1821
+ );
1822
+ continue;
1823
+ }
1188
1824
  console.log(`Registrando listener para '${app}' no evento: ${event}`);
1189
1825
  wsClient.on(event, callback);
1190
1826
  }
1191
1827
  }
1192
1828
  }
1829
+ async reconnectWebSocket(app) {
1830
+ console.log(`Tentando reconectar o WebSocket para o app '${app}'...`);
1831
+ try {
1832
+ await this.connectSingleWebSocket(app);
1833
+ this.processPendingListeners();
1834
+ console.log(`Reconex\xE3o bem-sucedida para o app '${app}'.`);
1835
+ } catch (error) {
1836
+ console.error(`Erro ao reconectar o WebSocket para '${app}':`, error);
1837
+ }
1838
+ }
1193
1839
  channels;
1194
1840
  endpoints;
1195
1841
  applications;
@@ -1201,24 +1847,6 @@ var AriClient = class {
1201
1847
  getWebSocketClients() {
1202
1848
  return this.wsClients;
1203
1849
  }
1204
- /**
1205
- * Registra um listener para eventos de WebSocket relacionados a canais.
1206
- * @param eventType Tipo de evento.
1207
- * @param callback Callback a ser executado quando o evento for recebido.
1208
- */
1209
- onChannelEvent(eventType, callback) {
1210
- if (this.wsClients.size === 0) {
1211
- console.warn(
1212
- "Nenhuma conex\xE3o WebSocket est\xE1 ativa. O listener ser\xE1 pendente."
1213
- );
1214
- this.pendingListeners.push({ event: eventType, callback });
1215
- return;
1216
- }
1217
- for (const [app, wsClient] of this.wsClients.entries()) {
1218
- console.log(`Registrando evento '${eventType}' no app '${app}'`);
1219
- wsClient.on(eventType, callback);
1220
- }
1221
- }
1222
1850
  /**
1223
1851
  * Registra listeners globais para eventos de WebSocket.
1224
1852
  */
@@ -1256,7 +1884,7 @@ var AriClient = class {
1256
1884
  }
1257
1885
  // Método para criar uma instância de ChannelInstance
1258
1886
  createChannelInstance(channelId) {
1259
- return this.channels.createChannelInstance(channelId);
1887
+ return this.channels.Channel(channelId);
1260
1888
  }
1261
1889
  handleWebSocketEvent(event) {
1262
1890
  console.log("Evento recebido no WebSocket:", event.type, event);
@@ -1320,26 +1948,58 @@ var AriClient = class {
1320
1948
  if (!app) {
1321
1949
  throw new Error("O nome do aplicativo \xE9 obrigat\xF3rio.");
1322
1950
  }
1323
- if (this.wsClients.has(app)) {
1324
- console.log(`Conex\xE3o WebSocket para '${app}' j\xE1 existe. Reutilizando...`);
1325
- return;
1951
+ if (this.webSocketReady.get(app)) {
1952
+ console.log(`Conex\xE3o WebSocket para '${app}' j\xE1 est\xE1 ativa.`);
1953
+ return this.webSocketReady.get(app);
1326
1954
  }
1327
1955
  const protocol = this.config.secure ? "wss" : "ws";
1328
1956
  const eventsParam = subscribedEvents && subscribedEvents.length > 0 ? `&event=${subscribedEvents.join(",")}` : "&subscribeAll=true";
1329
1957
  const wsUrl = `${protocol}://${encodeURIComponent(
1330
1958
  this.config.username
1331
1959
  )}:${encodeURIComponent(this.config.password)}@${this.config.host}:${this.config.port}/ari/events?app=${app}${eventsParam}`;
1332
- const wsClient = new WebSocketClient(wsUrl);
1333
- try {
1334
- await wsClient.connect();
1335
- console.log(`WebSocket conectado para o app: ${app}`);
1336
- this.integrateWebSocketEvents(app, wsClient);
1337
- await this.ensureAppRegistered(app);
1338
- this.wsClients.set(app, wsClient);
1339
- } catch (error) {
1340
- console.error(`Erro ao conectar WebSocket para '${app}':`, error);
1341
- throw error;
1342
- }
1960
+ const backoffOptions = {
1961
+ delayFirstAttempt: false,
1962
+ startingDelay: 1e3,
1963
+ timeMultiple: 2,
1964
+ maxDelay: 3e4,
1965
+ numOfAttempts: 10,
1966
+ jitter: "full",
1967
+ retry: (error, attemptNumber) => {
1968
+ console.warn(
1969
+ `Tentativa ${attemptNumber} falhou para '${app}': ${error.message}`
1970
+ );
1971
+ return !this.wsClients.has(app) || !this.wsClients.get(app)?.isConnected();
1972
+ }
1973
+ };
1974
+ const webSocketPromise = new Promise(async (resolve, reject) => {
1975
+ try {
1976
+ if (this.isReconnecting.get(app)) {
1977
+ console.warn(`J\xE1 est\xE1 tentando reconectar para o app '${app}'.`);
1978
+ return;
1979
+ }
1980
+ this.isReconnecting.set(app, true);
1981
+ const wsClient = new WebSocketClient(wsUrl);
1982
+ await (0, import_exponential_backoff2.backOff)(async () => {
1983
+ if (!wsClient) {
1984
+ throw new Error("WebSocketClient instance is null.");
1985
+ }
1986
+ await wsClient.connect();
1987
+ console.log(`WebSocket conectado para o app: ${app}`);
1988
+ this.integrateWebSocketEvents(app, wsClient);
1989
+ await this.ensureAppRegistered(app);
1990
+ this.wsClients.set(app, wsClient);
1991
+ this.processPendingListeners();
1992
+ }, backoffOptions);
1993
+ resolve();
1994
+ } catch (error) {
1995
+ console.error(`Erro ao conectar WebSocket para '${app}':`, error);
1996
+ reject(error);
1997
+ } finally {
1998
+ this.isReconnecting.delete(app);
1999
+ }
2000
+ });
2001
+ this.webSocketReady.set(app, webSocketPromise);
2002
+ return webSocketPromise;
1343
2003
  }
1344
2004
  /**
1345
2005
  * Integrates WebSocket events with playback listeners.
@@ -1452,465 +2112,6 @@ var AriClient = class {
1452
2112
  this.wsClients.clear();
1453
2113
  console.log("Todos os WebSockets foram fechados.");
1454
2114
  }
1455
- /**
1456
- * Retrieves a list of active channels from the Asterisk ARI.
1457
- *
1458
- * @returns {Promise<Channel[]>} A promise resolving to the list of active channels.
1459
- */
1460
- /**
1461
- * Lists all active channels.
1462
- */
1463
- async listChannels() {
1464
- return this.channels.list();
1465
- }
1466
- async hangupChannel(channelId) {
1467
- return this.channels.hangup(channelId);
1468
- }
1469
- /**
1470
- * Creates a new channel.
1471
- */
1472
- async originateChannel(data) {
1473
- return this.channels.originate(data);
1474
- }
1475
- /**
1476
- * Continues the dialplan for a specific channel.
1477
- */
1478
- async continueChannelDialplan(channelId, context, extension, priority, label) {
1479
- return this.channels.continueDialplan(
1480
- channelId,
1481
- context,
1482
- extension,
1483
- priority,
1484
- label
1485
- );
1486
- }
1487
- /**
1488
- * Moves a channel to another Stasis application.
1489
- */
1490
- async moveChannelToApplication(channelId, app, appArgs) {
1491
- return this.channels.moveToApplication(channelId, app, appArgs);
1492
- }
1493
- /**
1494
- * Sets a channel variable.
1495
- */
1496
- async setChannelVariable(channelId, variable, value) {
1497
- return this.channels.setChannelVariable(channelId, variable, value);
1498
- }
1499
- /**
1500
- * Gets a channel variable.
1501
- */
1502
- async getChannelVariable(channelId, variable) {
1503
- return this.channels.getChannelVariable(channelId, variable);
1504
- }
1505
- /**
1506
- * Starts music on hold for a channel.
1507
- */
1508
- async startChannelMusicOnHold(channelId) {
1509
- return this.channels.startMusicOnHold(channelId);
1510
- }
1511
- /**
1512
- * Stops music on hold for a channel.
1513
- */
1514
- async stopChannelMusicOnHold(channelId) {
1515
- return this.channels.stopMusicOnHold(channelId);
1516
- }
1517
- /**
1518
- * Records audio from a channel.
1519
- */
1520
- async recordAudio(channelId, options) {
1521
- return this.channels.record(channelId, options);
1522
- }
1523
- /**
1524
- * Starts snooping on a channel.
1525
- */
1526
- async snoopChannel(channelId, options) {
1527
- return this.channels.snoopChannel(channelId, options);
1528
- }
1529
- /**
1530
- * Starts snooping on a channel with a specific snoop ID.
1531
- */
1532
- async snoopChannelWithId(channelId, snoopId, options) {
1533
- return this.channels.snoopChannelWithId(channelId, snoopId, options);
1534
- }
1535
- /**
1536
- * Initiates a dial operation on a previously created channel.
1537
- * This function attempts to connect the specified channel to its configured destination.
1538
- *
1539
- * @param channelId - The unique identifier of the channel to dial.
1540
- * @param caller - Optional. The caller ID to use for the outgoing call. If not provided, the default caller ID for the channel will be used.
1541
- * @param timeout - Optional. The maximum time in seconds to wait for the dial operation to complete. If not specified, the system's default timeout will be used.
1542
- * @returns A Promise that resolves when the dial operation has been initiated successfully. Note that this does not guarantee that the call was answered, only that dialing has begun.
1543
- * @throws Will throw an error if the dial operation fails, e.g., if the channel doesn't exist or is in an invalid state.
1544
- */
1545
- async dialChannel(channelId, caller, timeout) {
1546
- return this.channels.dial(channelId, caller, timeout);
1547
- }
1548
- /**
1549
- * Retrieves RTP statistics for a channel.
1550
- */
1551
- async getRTPStatistics(channelId) {
1552
- return this.channels.getRTPStatistics(channelId);
1553
- }
1554
- /**
1555
- * Creates a channel to an external media source/sink.
1556
- */
1557
- async createExternalMedia(options) {
1558
- return this.channels.createExternalMedia(options);
1559
- }
1560
- /**
1561
- * Redirects a channel to a different location.
1562
- */
1563
- async redirectChannel(channelId, endpoint) {
1564
- return this.channels.redirectChannel(channelId, endpoint);
1565
- }
1566
- /**
1567
- * Sends a ringing indication to a channel.
1568
- */
1569
- async ringChannel(channelId) {
1570
- return this.channels.ringChannel(channelId);
1571
- }
1572
- /**
1573
- * Stops the ringing indication on a specified channel in the Asterisk system.
1574
- *
1575
- * This function sends a request to the Asterisk server to cease the ringing
1576
- * indication on a particular channel. This is typically used when you want to
1577
- * stop the ringing sound on a channel without answering or hanging up the call.
1578
- *
1579
- * @param channelId - The unique identifier of the channel on which to stop the ringing.
1580
- * This should be a string that uniquely identifies the channel in the Asterisk system.
1581
- *
1582
- * @returns A Promise that resolves when the ringing has been successfully stopped on the specified channel.
1583
- * The promise resolves to void, indicating no specific return value.
1584
- * If an error occurs during the operation, the promise will be rejected with an error object.
1585
- */
1586
- async stopRingChannel(channelId) {
1587
- return this.channels.stopRingChannel(channelId);
1588
- }
1589
- /**
1590
- * Sends DTMF (Dual-Tone Multi-Frequency) tones to a specified channel.
1591
- *
1592
- * This function allows sending DTMF tones to a channel, which can be used for various purposes
1593
- * such as interacting with IVR systems or sending signals during a call.
1594
- *
1595
- * @param channelId - The unique identifier of the channel to send DTMF tones to.
1596
- * @param dtmf - A string representing the DTMF tones to send (e.g., "123#").
1597
- * @param options - Optional parameters to control the timing of DTMF tones.
1598
- * @param options.before - The time (in milliseconds) to wait before sending DTMF.
1599
- * @param options.between - The time (in milliseconds) to wait between each DTMF tone.
1600
- * @param options.duration - The duration (in milliseconds) of each DTMF tone.
1601
- * @param options.after - The time (in milliseconds) to wait after sending all DTMF tones.
1602
- * @returns A Promise that resolves when the DTMF tones have been successfully sent.
1603
- */
1604
- async sendDTMF(channelId, dtmf, options) {
1605
- return this.channels.sendDTMF(channelId, dtmf, options);
1606
- }
1607
- /**
1608
- * Mutes a channel in the Asterisk system.
1609
- *
1610
- * This function initiates a mute operation on the specified channel, preventing
1611
- * audio transmission in the specified direction(s).
1612
- *
1613
- * @param channelId - The unique identifier of the channel to be muted.
1614
- * This should be a string that uniquely identifies the channel in the Asterisk system.
1615
- * @param direction - The direction of audio to mute. Can be one of:
1616
- * - "both": Mute both incoming and outgoing audio (default)
1617
- * - "in": Mute only incoming audio
1618
- * - "out": Mute only outgoing audio
1619
- *
1620
- * @returns A Promise that resolves when the mute operation has been successfully completed.
1621
- * The promise resolves to void, indicating no specific return value.
1622
- * If an error occurs during the operation, the promise will be rejected with an error object.
1623
- */
1624
- async muteChannel(channelId, direction = "both") {
1625
- return this.channels.muteChannel(channelId, direction);
1626
- }
1627
- /**
1628
- * Unmutes a channel in the Asterisk system.
1629
- *
1630
- * This function removes the mute status from a specified channel, allowing audio
1631
- * transmission to resume in the specified direction(s).
1632
- *
1633
- * @param channelId - The unique identifier of the channel to be unmuted.
1634
- * This should be a string that uniquely identifies the channel in the Asterisk system.
1635
- * @param direction - The direction of audio to unmute. Can be one of:
1636
- * - "both": Unmute both incoming and outgoing audio (default)
1637
- * - "in": Unmute only incoming audio
1638
- * - "out": Unmute only outgoing audio
1639
- *
1640
- * @returns A Promise that resolves when the unmute operation has been successfully completed.
1641
- * The promise resolves to void, indicating no specific return value.
1642
- * If an error occurs during the operation, the promise will be rejected with an error object.
1643
- */
1644
- async unmuteChannel(channelId, direction = "both") {
1645
- return this.channels.unmuteChannel(channelId, direction);
1646
- }
1647
- /**
1648
- * Puts a specified channel on hold.
1649
- *
1650
- * This function initiates a hold operation on the specified channel in the Asterisk system.
1651
- * When a channel is put on hold, typically the audio is muted or replaced with hold music,
1652
- * depending on the system configuration.
1653
- *
1654
- * @param channelId - The unique identifier of the channel to be put on hold.
1655
- * This should be a string that uniquely identifies the channel in the Asterisk system.
1656
- *
1657
- * @returns A Promise that resolves when the hold operation has been successfully initiated.
1658
- * The promise resolves to void, indicating no specific return value.
1659
- * If an error occurs during the operation, the promise will be rejected with an error object.
1660
- */
1661
- async holdChannel(channelId) {
1662
- return this.channels.holdChannel(channelId);
1663
- }
1664
- /**
1665
- * Removes a specified channel from hold.
1666
- *
1667
- * This function initiates an unhold operation on the specified channel in the Asterisk system.
1668
- * When a channel is taken off hold, it typically resumes normal audio transmission,
1669
- * allowing the parties to continue their conversation.
1670
- *
1671
- * @param channelId - The unique identifier of the channel to be taken off hold.
1672
- * This should be a string that uniquely identifies the channel in the Asterisk system.
1673
- *
1674
- * @returns A Promise that resolves when the unhold operation has been successfully initiated.
1675
- * The promise resolves to void, indicating no specific return value.
1676
- * If an error occurs during the operation, the promise will be rejected with an error object.
1677
- */
1678
- async unholdChannel(channelId) {
1679
- return this.channels.unholdChannel(channelId);
1680
- }
1681
- /**
1682
- * Creates a new channel in the Asterisk system using the provided originate request data.
1683
- * This function initiates a new communication channel based on the specified parameters.
1684
- *
1685
- * @param data - An object containing the originate request data for channel creation.
1686
- * This includes details such as the endpoint to call, the context to use,
1687
- * and any variables to set on the new channel.
1688
- * @param data.endpoint - The endpoint to call (e.g., "SIP/1234").
1689
- * @param data.extension - The extension to dial after the channel is created.
1690
- * @param data.context - The dialplan context to use for the new channel.
1691
- * @param data.priority - The priority to start at in the dialplan.
1692
- * @param data.app - The application to execute on the channel (alternative to extension/context/priority).
1693
- * @param data.appArgs - The arguments to pass to the application, if 'app' is specified.
1694
- * @param data.callerId - The caller ID to set on the new channel.
1695
- * @param data.timeout - The timeout (in seconds) to wait for the channel to be answered.
1696
- * @param data.variables - An object containing key-value pairs of channel variables to set.
1697
- * @param data.channelId - An optional ID to assign to the new channel.
1698
- * @param data.otherChannelId - The ID of another channel to bridge with after creation.
1699
- *
1700
- * @returns A Promise that resolves to the created Channel object.
1701
- * The Channel object contains details about the newly created channel,
1702
- * such as its unique identifier, state, and other relevant information.
1703
- *
1704
- * @throws Will throw an error if the channel creation fails for any reason,
1705
- * such as invalid parameters or system issues.
1706
- */
1707
- async createChannel(data) {
1708
- return this.channels.createChannel(data);
1709
- }
1710
- /**
1711
- * Originates a new channel with a specified ID using the provided originate request data.
1712
- *
1713
- * @param channelId - The desired unique identifier for the new channel.
1714
- * @param data - The originate request data containing channel creation parameters.
1715
- * @returns A promise that resolves to the created Channel object.
1716
- */
1717
- async originateWithId(channelId, data) {
1718
- return this.channels.originateWithId(channelId, data);
1719
- }
1720
- // Métodos relacionados a endpoints:
1721
- /**
1722
- * Lists all endpoints.
1723
- *
1724
- * @returns {Promise<Endpoint[]>} A promise resolving to the list of endpoints.
1725
- */
1726
- async listEndpoints() {
1727
- return this.endpoints.list();
1728
- }
1729
- /**
1730
- * Retrieves details of a specific endpoint.
1731
- *
1732
- * @param technology - The technology of the endpoint.
1733
- * @param resource - The resource name of the endpoint.
1734
- * @returns {Promise<EndpointDetails>} A promise resolving to the details of the endpoint.
1735
- */
1736
- async getEndpointDetails(technology, resource) {
1737
- return this.endpoints.getDetails(technology, resource);
1738
- }
1739
- /**
1740
- * Sends a message to an endpoint.
1741
- *
1742
- * @param technology - The technology of the endpoint.
1743
- * @param resource - The resource name of the endpoint.
1744
- * @param body - The message body to send.
1745
- * @returns {Promise<void>} A promise resolving when the message is sent.
1746
- */
1747
- async sendMessageToEndpoint(technology, resource, body) {
1748
- return this.endpoints.sendMessage(technology, resource, body);
1749
- }
1750
- // Métodos relacionados a applications
1751
- /**
1752
- * Lists all applications.
1753
- *
1754
- * @returns {Promise<Application[]>} A promise resolving to the list of applications.
1755
- */
1756
- async listApplications() {
1757
- return this.applications.list();
1758
- }
1759
- /**
1760
- * Retrieves details of a specific application.
1761
- *
1762
- * @param appName - The name of the application.
1763
- * @returns {Promise<ApplicationDetails>} A promise resolving to the application details.
1764
- */
1765
- async getApplicationDetails(appName) {
1766
- return this.applications.getDetails(appName);
1767
- }
1768
- /**
1769
- * Sends a message to a specific application.
1770
- *
1771
- * @param appName - The name of the application.
1772
- * @param body - The message body to send.
1773
- * @returns {Promise<void>} A promise resolving when the message is sent successfully.
1774
- */
1775
- async sendMessageToApplication(appName, body) {
1776
- return this.applications.sendMessage(appName, body);
1777
- }
1778
- // Métodos relacionados a playbacks
1779
- /**
1780
- * Retrieves details of a specific playback.
1781
- *
1782
- * @param playbackId - The unique identifier of the playback.
1783
- * @returns {Promise<Playback>} A promise resolving to the playback details.
1784
- */
1785
- async getPlaybackDetails(playbackId) {
1786
- return this.playbacks.getDetails(playbackId);
1787
- }
1788
- /**
1789
- * Controls a specific playback in the Asterisk server.
1790
- * This function allows manipulation of an ongoing playback, such as pausing, resuming, or skipping.
1791
- *
1792
- * @param playbackId - The unique identifier of the playback to control.
1793
- * This should be a string that uniquely identifies the playback in the Asterisk system.
1794
- * @param controlRequest - An object containing the control operation details.
1795
- * This object should conform to the PlaybackControlRequest interface,
1796
- * which includes an 'operation' property specifying the control action to perform.
1797
- * @returns A Promise that resolves when the control operation is successfully executed.
1798
- * The promise resolves to void, indicating no specific return value.
1799
- * If an error occurs during the operation, the promise will be rejected with an error object.
1800
- * @throws Will throw an error if the playback control operation fails, e.g., if the playback doesn't exist
1801
- * or the requested operation is invalid.
1802
- */
1803
- async controlPlayback(playbackId, controlRequest) {
1804
- const { operation } = controlRequest;
1805
- return this.playbacks.control(playbackId, operation);
1806
- }
1807
- /**
1808
- * Stops a specific playback in the Asterisk server.
1809
- *
1810
- * @param playbackId - The unique identifier of the playback to stop.
1811
- * @returns A Promise that resolves when the playback is successfully stopped.
1812
- */
1813
- async stopPlayback(playbackId) {
1814
- return this.playbacks.stop(playbackId);
1815
- }
1816
- /**
1817
- * Retrieves a list of all available sounds in the Asterisk server.
1818
- *
1819
- * @param params - Optional parameters to filter the list of sounds.
1820
- * @returns A Promise that resolves to an array of Sound objects representing the available sounds.
1821
- */
1822
- async listSounds(params) {
1823
- return this.sounds.list(params);
1824
- }
1825
- /**
1826
- * Retrieves detailed information about a specific sound in the Asterisk server.
1827
- *
1828
- * @param soundId - The unique identifier of the sound to retrieve details for.
1829
- * @returns A Promise that resolves to a Sound object containing the details of the specified sound.
1830
- */
1831
- async getSoundDetails(soundId) {
1832
- return this.sounds.getDetails(soundId);
1833
- }
1834
- /**
1835
- * Retrieves general information about the Asterisk server.
1836
- *
1837
- * @returns A Promise that resolves to an AsteriskInfo object containing server information.
1838
- */
1839
- async getAsteriskInfo() {
1840
- return this.asterisk.getInfo();
1841
- }
1842
- /**
1843
- * Retrieves a list of all loaded modules in the Asterisk server.
1844
- *
1845
- * @returns A Promise that resolves to an array of Module objects representing the loaded modules.
1846
- */
1847
- async listModules() {
1848
- return this.asterisk.listModules();
1849
- }
1850
- /**
1851
- * Manages a specific module in the Asterisk server by loading, unloading, or reloading it.
1852
- *
1853
- * @param moduleName - The name of the module to manage.
1854
- * @param action - The action to perform on the module: "load", "unload", or "reload".
1855
- * @returns A Promise that resolves when the module management action is completed successfully.
1856
- */
1857
- async manageModule(moduleName, action) {
1858
- return this.asterisk.manageModule(moduleName, action);
1859
- }
1860
- /**
1861
- * Retrieves a list of all configured logging channels in the Asterisk server.
1862
- *
1863
- * @returns A Promise that resolves to an array of Logging objects representing the configured logging channels.
1864
- */
1865
- async listLoggingChannels() {
1866
- return this.asterisk.listLoggingChannels();
1867
- }
1868
- /**
1869
- * Adds or removes a log channel in the Asterisk server.
1870
- *
1871
- * @param logChannelName - The name of the log channel to manage.
1872
- * @param action - The action to perform: "add" to create a new log channel or "remove" to delete an existing one.
1873
- * @param configuration - Optional configuration object for adding a log channel. Ignored when removing a channel.
1874
- * @param configuration.type - The type of the log channel.
1875
- * @param configuration.configuration - Additional configuration details for the log channel.
1876
- * @returns A Promise that resolves when the log channel management action is completed successfully.
1877
- */
1878
- async manageLogChannel(logChannelName, action, configuration) {
1879
- return this.asterisk.manageLogChannel(
1880
- logChannelName,
1881
- action,
1882
- configuration
1883
- );
1884
- }
1885
- /**
1886
- * Retrieves the value of a global variable from the Asterisk server.
1887
- *
1888
- * @param variableName - The name of the global variable to retrieve.
1889
- * @returns A Promise that resolves to a Variable object containing the name and value of the global variable.
1890
- */
1891
- async getGlobalVariable(variableName) {
1892
- return this.asterisk.getGlobalVariable(variableName);
1893
- }
1894
- /**
1895
- * Sets a global variable in the Asterisk server.
1896
- *
1897
- * This function allows you to set or update the value of a global variable
1898
- * in the Asterisk server. Global variables are accessible throughout the
1899
- * entire Asterisk system and can be used for various purposes such as
1900
- * configuration settings or sharing data between different parts of the system.
1901
- *
1902
- * @param variableName - The name of the global variable to set or update.
1903
- * This should be a string identifying the variable uniquely.
1904
- * @param value - The value to assign to the global variable. This can be any
1905
- * string value, including empty strings.
1906
- * @returns A Promise that resolves when the global variable has been successfully
1907
- * set. The promise resolves to void, indicating no specific return value.
1908
- * If an error occurs during the operation, the promise will be rejected
1909
- * with an error object.
1910
- */
1911
- async setGlobalVariable(variableName, value) {
1912
- return this.asterisk.setGlobalVariable(variableName, value);
1913
- }
1914
2115
  /**
1915
2116
  * Inicializa uma nova instância de `ChannelInstance` para manipular canais localmente.
1916
2117
  *
@@ -1918,7 +2119,7 @@ var AriClient = class {
1918
2119
  * @returns Uma instância de `ChannelInstance` vinculada ao cliente atual.
1919
2120
  */
1920
2121
  Channel(channelId) {
1921
- return this.channels.createChannelInstance(channelId);
2122
+ return this.channels.Channel(channelId);
1922
2123
  }
1923
2124
  /**
1924
2125
  * Inicializa uma nova instância de `PlaybackInstance` para manipular playbacks.