@ipcom/asterisk-ari 0.0.25 → 0.0.26

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.
@@ -591,6 +591,7 @@ __export(src_exports, {
591
591
  module.exports = __toCommonJS(src_exports);
592
592
 
593
593
  // src/ari-client/ariClient.ts
594
+ var import_events3 = require("events");
594
595
  var import_exponential_backoff = __toESM(require_backoff(), 1);
595
596
 
596
597
  // src/ari-client/baseClient.ts
@@ -1201,8 +1202,10 @@ var Endpoints = class {
1201
1202
  };
1202
1203
 
1203
1204
  // src/ari-client/resources/playbacks.ts
1204
- var Playbacks = class {
1205
+ var import_events = require("events");
1206
+ var Playbacks = class extends import_events.EventEmitter {
1205
1207
  constructor(client) {
1208
+ super();
1206
1209
  this.client = client;
1207
1210
  }
1208
1211
  /**
@@ -1241,6 +1244,50 @@ var Playbacks = class {
1241
1244
  async stop(playbackId) {
1242
1245
  await this.client.post(`/playbacks/${playbackId}/stop`);
1243
1246
  }
1247
+ /**
1248
+ * Registers a listener for playback events.
1249
+ * The listener is triggered for events such as "PlaybackFinished".
1250
+ *
1251
+ * @param eventType - The type of event to listen for.
1252
+ * @param playbackId - The ID of the playback to associate with this listener.
1253
+ * @param callback - The callback function to execute when the event occurs.
1254
+ */
1255
+ registerListener(eventType, playbackId, callback) {
1256
+ this.on(`${eventType}:${playbackId}`, callback);
1257
+ }
1258
+ /**
1259
+ * Unregisters a listener for playback events.
1260
+ *
1261
+ * @param eventType - The type of event to stop listening for.
1262
+ * @param playbackId - The ID of the playback associated with the listener.
1263
+ * @param callback - The callback function to remove.
1264
+ */
1265
+ unregisterListener(eventType, playbackId, callback) {
1266
+ this.off(`${eventType}:${playbackId}`, callback);
1267
+ }
1268
+ /**
1269
+ * Checks if a listener is already registered for a specific event and playback.
1270
+ *
1271
+ * @param eventType - The type of event to check.
1272
+ * @param playbackId - The playback ID associated with the listener.
1273
+ * @returns True if a listener is already registered, false otherwise.
1274
+ */
1275
+ isListenerRegistered(eventType, playbackId) {
1276
+ return this.listenerCount(`${eventType}:${playbackId}`) > 0;
1277
+ }
1278
+ /**
1279
+ * Emits playback events received via WebSocket.
1280
+ * This method should be called by the WebSocket client when playback events occur.
1281
+ *
1282
+ * @param eventType - The type of the WebSocket event.
1283
+ * @param data - The data associated with the event.
1284
+ */
1285
+ emitPlaybackEvent(eventType, data) {
1286
+ if ("playbackId" in data) {
1287
+ this.emit(`${eventType}:${data.playbackId}`, data);
1288
+ }
1289
+ this.emit(eventType, data);
1290
+ }
1244
1291
  };
1245
1292
 
1246
1293
  // src/ari-client/resources/sounds.ts
@@ -1275,16 +1322,25 @@ var Sounds = class {
1275
1322
  };
1276
1323
 
1277
1324
  // src/ari-client/websocketClient.ts
1325
+ var import_events2 = require("events");
1278
1326
  var import_ws = __toESM(require("ws"), 1);
1279
- var WebSocketClient = class {
1280
- // Para evitar reconexões paralelas
1327
+ var WebSocketClient = class extends import_events2.EventEmitter {
1328
+ /**
1329
+ * Creates a new WebSocketClient instance.
1330
+ * @param url - The WebSocket server URL to connect to.
1331
+ */
1281
1332
  constructor(url) {
1333
+ super();
1282
1334
  this.url = url;
1283
1335
  }
1284
1336
  ws = null;
1285
1337
  isClosedManually = false;
1286
- // Para evitar reconexões automáticas quando fechado manualmente
1287
1338
  isReconnecting = false;
1339
+ /**
1340
+ * Establishes a connection to the WebSocket server.
1341
+ * @returns A Promise that resolves when the connection is established, or rejects if an error occurs.
1342
+ * @throws Will throw an error if the connection fails.
1343
+ */
1288
1344
  async connect() {
1289
1345
  if (this.isReconnecting) return;
1290
1346
  return new Promise((resolve, reject) => {
@@ -1302,47 +1358,70 @@ var WebSocketClient = class {
1302
1358
  this.ws.on("close", (code, reason) => {
1303
1359
  console.warn(`WebSocket desconectado: ${code} - ${reason}`);
1304
1360
  this.isReconnecting = false;
1361
+ this.emit("close", { code, reason });
1362
+ });
1363
+ this.ws.on("message", (rawData) => {
1364
+ this.handleMessage(rawData);
1305
1365
  });
1306
1366
  });
1307
1367
  }
1308
- async reconnect() {
1309
- if (this.isClosedManually || this.isReconnecting) return;
1310
- console.log("Tentando reconectar ao WebSocket...");
1311
- this.isReconnecting = true;
1312
- try {
1313
- await this.connect();
1314
- console.log("Reconex\xE3o bem-sucedida.");
1315
- } catch (err) {
1316
- console.error("Erro ao tentar reconectar:", err);
1317
- } finally {
1318
- this.isReconnecting = false;
1319
- }
1320
- }
1368
+ /**
1369
+ * Checks if the WebSocket connection is currently open.
1370
+ * @returns True if the connection is open, false otherwise.
1371
+ */
1321
1372
  isConnected() {
1322
1373
  return this.ws?.readyState === import_ws.default.OPEN;
1323
1374
  }
1375
+ /**
1376
+ * Adds a listener for WebSocket events.
1377
+ * @param event - The event type to listen for.
1378
+ * @param callback - The function to call when the event occurs.
1379
+ * @returns The WebSocketClient instance for chaining.
1380
+ */
1324
1381
  on(event, callback) {
1325
- if (!this.ws || this.ws.readyState !== import_ws.default.OPEN) {
1326
- throw new Error("WebSocket n\xE3o est\xE1 conectado.");
1327
- }
1328
- if (event === "message") {
1329
- this.ws.on(event, (rawData) => {
1330
- try {
1331
- const decodedData = JSON.parse(rawData.toString());
1332
- if (decodedData?.type) {
1333
- const matchedEvent = decodedData;
1334
- callback(matchedEvent);
1335
- } else {
1336
- console.warn("Mensagem sem tipo:", decodedData);
1337
- }
1338
- } catch (err) {
1339
- console.error("Erro ao decodificar mensagem do WebSocket:", err);
1340
- }
1341
- });
1342
- } else {
1343
- this.ws.on(event, callback);
1382
+ super.on(event, callback);
1383
+ return this;
1384
+ }
1385
+ /**
1386
+ * Removes a specific listener from a WebSocket event.
1387
+ * @param event - The event type to remove the listener from.
1388
+ * @param callback - The function to remove from the event listeners.
1389
+ * @returns The WebSocketClient instance for chaining.
1390
+ */
1391
+ off(event, callback) {
1392
+ super.off(event, callback);
1393
+ return this;
1394
+ }
1395
+ /**
1396
+ * Removes all listeners for a specific event, or all events if no event is specified.
1397
+ * @param event - Optional. The event to remove all listeners from.
1398
+ * @returns The WebSocketClient instance for chaining.
1399
+ */
1400
+ removeAllListeners(event) {
1401
+ super.removeAllListeners(event);
1402
+ return this;
1403
+ }
1404
+ /**
1405
+ * Handles incoming WebSocket messages.
1406
+ * @param rawData - The raw data received from the WebSocket.
1407
+ */
1408
+ handleMessage(rawData) {
1409
+ try {
1410
+ const decodedData = JSON.parse(rawData.toString());
1411
+ if (decodedData?.type) {
1412
+ this.emit(decodedData.type, decodedData);
1413
+ } else {
1414
+ console.warn("Mensagem recebida sem tipo:", decodedData);
1415
+ }
1416
+ } catch (err) {
1417
+ console.error("Erro ao decodificar mensagem do WebSocket:", err);
1344
1418
  }
1345
1419
  }
1420
+ /**
1421
+ * Sends data through the WebSocket connection.
1422
+ * @param data - The data to send.
1423
+ * @throws Will throw an error if the WebSocket is not connected.
1424
+ */
1346
1425
  send(data) {
1347
1426
  if (!this.ws || this.ws.readyState !== import_ws.default.OPEN) {
1348
1427
  throw new Error("WebSocket n\xE3o est\xE1 conectado.");
@@ -1353,6 +1432,9 @@ var WebSocketClient = class {
1353
1432
  }
1354
1433
  });
1355
1434
  }
1435
+ /**
1436
+ * Closes the WebSocket connection manually.
1437
+ */
1356
1438
  close() {
1357
1439
  if (this.ws) {
1358
1440
  this.isClosedManually = true;
@@ -1381,6 +1463,7 @@ var AriClient = class {
1381
1463
  wsClient = null;
1382
1464
  baseClient;
1383
1465
  isReconnecting = false;
1466
+ eventEmitter = new import_events3.EventEmitter();
1384
1467
  channels;
1385
1468
  endpoints;
1386
1469
  applications;
@@ -1390,10 +1473,14 @@ var AriClient = class {
1390
1473
  bridges;
1391
1474
  /**
1392
1475
  * Connects to the ARI WebSocket for a specific application.
1476
+ * This function establishes a WebSocket connection to the Asterisk ARI, sets up event listeners,
1477
+ * and ensures the application is registered. It uses an exponential backoff strategy for connection attempts.
1393
1478
  *
1394
- * @param app - The application name to connect to.
1395
- * @param subscribedEvents
1396
- * @returns {Promise<void>} Resolves when the WebSocket connects successfully.
1479
+ * @param app - The name of the application to connect to. This is required and used to identify the application in ARI.
1480
+ * @param subscribedEvents - Optional array of WebSocketEventType to subscribe to specific events.
1481
+ * If not provided or empty, it subscribes to all events.
1482
+ * @returns A Promise that resolves when the WebSocket connection is successfully established and the application is registered.
1483
+ * @throws Error if the 'app' parameter is not provided, or if connection attempts fail after multiple retries.
1397
1484
  */
1398
1485
  async connectWebSocket(app, subscribedEvents) {
1399
1486
  if (!app) {
@@ -1421,6 +1508,11 @@ var AriClient = class {
1421
1508
  return !this.wsClient?.isConnected();
1422
1509
  }
1423
1510
  };
1511
+ if (this.wsClient?.isConnected()) {
1512
+ console.log("WebSocket j\xE1 conectado. Removendo listeners antigos...");
1513
+ this.wsClient.removeAllListeners();
1514
+ this.wsClient.close();
1515
+ }
1424
1516
  this.wsClient = new WebSocketClient(wsUrl);
1425
1517
  try {
1426
1518
  await (0, import_exponential_backoff.backOff)(async () => {
@@ -1428,6 +1520,7 @@ var AriClient = class {
1428
1520
  throw new Error("WebSocketClient instance is null.");
1429
1521
  }
1430
1522
  await this.wsClient.connect();
1523
+ this.integrateWebSocketEvents();
1431
1524
  console.log(`WebSocket conectado para o app: ${app}`);
1432
1525
  await this.ensureAppRegistered(app);
1433
1526
  }, backoffOptions);
@@ -1441,6 +1534,103 @@ var AriClient = class {
1441
1534
  this.isReconnecting = false;
1442
1535
  }
1443
1536
  }
1537
+ /**
1538
+ * Integrates WebSocket events with playback listeners.
1539
+ */
1540
+ integrateWebSocketEvents() {
1541
+ if (!this.wsClient) {
1542
+ throw new Error("WebSocket client n\xE3o est\xE1 conectado.");
1543
+ }
1544
+ const eventHandlers = {
1545
+ PlaybackFinished: (data) => {
1546
+ if ("playbackId" in data) {
1547
+ this.playbacks.emitPlaybackEvent("PlaybackFinished", data);
1548
+ }
1549
+ this.emitGlobalEvent(data);
1550
+ },
1551
+ ChannelStateChange: (data) => {
1552
+ if ("channel" in data) {
1553
+ console.log("Estado do canal alterado:", data.channel);
1554
+ }
1555
+ this.emitGlobalEvent(data);
1556
+ },
1557
+ BridgeDestroyed: (data) => {
1558
+ if ("bridge" in data) {
1559
+ console.log("Bridge destru\xEDda:", data.bridge);
1560
+ }
1561
+ this.emitGlobalEvent(data);
1562
+ },
1563
+ // Adicione mais eventos conforme necessário
1564
+ // Exemplo:
1565
+ ChannelDtmfReceived: (data) => {
1566
+ if ("channel" in data) {
1567
+ console.log("DTMF recebido no canal:", data.channel);
1568
+ }
1569
+ this.emitGlobalEvent(data);
1570
+ }
1571
+ };
1572
+ for (const [eventType, handler] of Object.entries(eventHandlers)) {
1573
+ if (handler) {
1574
+ this.wsClient.on(eventType, handler);
1575
+ }
1576
+ }
1577
+ console.log("Todos os eventos do WebSocket foram registrados.");
1578
+ }
1579
+ /**
1580
+ * Registra um listener para eventos globais.
1581
+ * @param callback - A função a ser executada quando um evento global for recebido.
1582
+ */
1583
+ onGlobalEvent(callback) {
1584
+ this.eventEmitter.on("globalEvent", callback);
1585
+ }
1586
+ /**
1587
+ * Remove um listener para eventos globais.
1588
+ * @param callback - A função a ser removida dos eventos globais.
1589
+ */
1590
+ offGlobalEvent(callback) {
1591
+ this.eventEmitter.off("globalEvent", callback);
1592
+ }
1593
+ /**
1594
+ * Emite um evento global.
1595
+ * @param data - Os dados do evento a serem emitidos.
1596
+ */
1597
+ emitGlobalEvent(data) {
1598
+ this.eventEmitter.emit("globalEvent", data);
1599
+ }
1600
+ /**
1601
+ * Unregisters a listener for playback events.
1602
+ *
1603
+ * This method removes a specific listener registered for a playback event type,
1604
+ * ensuring that no further notifications are sent to the callback function.
1605
+ *
1606
+ * @param eventType - The type of event to stop listening for.
1607
+ * @param playbackId - The unique ID of the playback associated with the listener.
1608
+ * @param callback - The callback function to remove from the listener.
1609
+ */
1610
+ unregisterPlaybackListener(eventType, playbackId, callback) {
1611
+ this.playbacks.unregisterListener(eventType, playbackId, callback);
1612
+ }
1613
+ /**
1614
+ * Registers a listener for playback events.
1615
+ * The listener is triggered for events such as "PlaybackFinished".
1616
+ *
1617
+ * @param eventType - The type of event to listen for.
1618
+ * @param playbackId - The ID of the playback to associate with this listener.
1619
+ * @param callback - The callback function to execute when the event occurs.
1620
+ */
1621
+ registerPlaybackListener(eventType, playbackId, callback) {
1622
+ this.playbacks.registerListener(eventType, playbackId, callback);
1623
+ }
1624
+ /**
1625
+ * Checks if a listener is already registered for a specific event and playback.
1626
+ *
1627
+ * @param eventType - The type of event to check.
1628
+ * @param playbackId - The playback ID associated with the listener.
1629
+ * @returns True if a listener is already registered, false otherwise.
1630
+ */
1631
+ isPlaybackListenerRegistered(eventType, playbackId) {
1632
+ return this.playbacks.isListenerRegistered(eventType, playbackId);
1633
+ }
1444
1634
  /**
1445
1635
  * Ensures the ARI application is registered.
1446
1636
  *
@@ -1472,23 +1662,72 @@ var AriClient = class {
1472
1662
  return this.wsClient ? this.wsClient.isConnected() : false;
1473
1663
  }
1474
1664
  /**
1475
- * Registers a callback function for WebSocket events.
1476
- * This method allows you to listen for and respond to WebSocket messages
1477
- * and process specific event types.
1665
+ * Registers a listener for WebSocket events.
1666
+ *
1667
+ * This function allows you to attach a callback function to a specific WebSocket event type.
1668
+ * The callback will be executed whenever an event of the specified type is received.
1669
+ *
1670
+ * @template T - The type of WebSocket event, extending WebSocketEvent["type"].
1671
+ * @param {T} event - The type of WebSocket event to listen for.
1672
+ * @param {(data: Extract<WebSocketEvent, { type: T }>) => void} callback - The function to be called when the event is received.
1673
+ * The callback receives the event data as its parameter.
1674
+ * @throws {Error} Throws an error if the WebSocket client is not connected when this method is called.
1675
+ * @returns {void} This function doesn't return a value.
1676
+ */
1677
+ onWebSocketEvent(event, callback) {
1678
+ if (!this.wsClient) {
1679
+ throw new Error("WebSocket n\xE3o est\xE1 conectado.");
1680
+ }
1681
+ this.wsClient.on(event, callback);
1682
+ }
1683
+ /**
1684
+ * Removes a specific listener for WebSocket events.
1685
+ *
1686
+ * This function unregisters a previously registered callback function for a specific WebSocket event type.
1687
+ * It's useful for removing event handlers when they are no longer needed or for cleaning up resources.
1688
+ *
1689
+ * @template T - The type of WebSocket event, extending WebSocketEvent["type"].
1690
+ * @param {T} event - The type of WebSocket event to remove the listener from.
1691
+ * @param {(data: Extract<WebSocketEvent, { type: T }>) => void} callback - The callback function to be removed.
1692
+ * This should be the same function reference that was used when adding the event listener.
1693
+ * @throws {Error} Throws an error if the WebSocket client is not connected when this method is called.
1694
+ * @returns {void} This function doesn't return a value.
1695
+ */
1696
+ offWebSocketEvent(event, callback) {
1697
+ if (!this.wsClient) {
1698
+ throw new Error("WebSocket n\xE3o est\xE1 conectado.");
1699
+ }
1700
+ this.wsClient.off(event, callback);
1701
+ }
1702
+ /**
1703
+ * Removes all listeners for a specific WebSocket event type.
1478
1704
  *
1479
- * @param callback - The callback function to execute when a WebSocket message is received.
1480
- * The function will receive the parsed event data as its parameter.
1481
- * @throws {Error} Throws an error if the WebSocket is not connected when trying to register the event.
1482
- * @returns {void}
1705
+ * This function removes all event listeners that have been registered for a particular
1706
+ * WebSocket event type. It's useful for cleaning up event listeners when they are no
1707
+ * longer needed or before re-registering new listeners.
1708
+ *
1709
+ * @param event - The type of WebSocket event for which all listeners should be removed.
1710
+ * This should be a string identifying the event type (e.g., 'message', 'close', etc.).
1711
+ *
1712
+ * @throws {Error} Throws an error if the WebSocket client is not connected when this method is called.
1713
+ *
1714
+ * @returns {void} This function doesn't return a value.
1483
1715
  */
1484
- onWebSocketEvent(callback) {
1716
+ removeAllWebSocketListeners(event) {
1485
1717
  if (!this.wsClient) {
1486
- throw new Error("WebSocket is not connected.");
1718
+ throw new Error("WebSocket n\xE3o est\xE1 conectado.");
1487
1719
  }
1488
- this.wsClient.on("message", callback);
1720
+ this.wsClient.removeAllListeners(event);
1489
1721
  }
1490
1722
  /**
1491
- * Closes the WebSocket connection.
1723
+ * Closes the WebSocket connection and removes all associated listeners.
1724
+ *
1725
+ * This function terminates the active WebSocket connection if one exists,
1726
+ * and cleans up by removing all event listeners attached to it. After calling
1727
+ * this function, the WebSocket client will be set to null, effectively
1728
+ * ending the connection and preparing for potential future connections.
1729
+ *
1730
+ * @returns {void} This function doesn't return a value.
1492
1731
  */
1493
1732
  closeWebSocket() {
1494
1733
  if (this.wsClient) {
@@ -1899,20 +2138,20 @@ var AriClient = class {
1899
2138
  return this.playbacks.getDetails(playbackId);
1900
2139
  }
1901
2140
  /**
1902
- * Controls a specific playback in the Asterisk server.
1903
- * This function allows manipulation of an ongoing playback, such as pausing, resuming, or skipping.
1904
- *
1905
- * @param playbackId - The unique identifier of the playback to control.
1906
- * This should be a string that uniquely identifies the playback in the Asterisk system.
1907
- * @param controlRequest - An object containing the control operation details.
1908
- * This object should conform to the PlaybackControlRequest interface,
1909
- * which includes an 'operation' property specifying the control action to perform.
1910
- * @returns A Promise that resolves when the control operation is successfully executed.
1911
- * The promise resolves to void, indicating no specific return value.
1912
- * If an error occurs during the operation, the promise will be rejected with an error object.
1913
- * @throws Will throw an error if the playback control operation fails, e.g., if the playback doesn't exist
1914
- * or the requested operation is invalid.
1915
- */
2141
+ * Controls a specific playback in the Asterisk server.
2142
+ * This function allows manipulation of an ongoing playback, such as pausing, resuming, or skipping.
2143
+ *
2144
+ * @param playbackId - The unique identifier of the playback to control.
2145
+ * This should be a string that uniquely identifies the playback in the Asterisk system.
2146
+ * @param controlRequest - An object containing the control operation details.
2147
+ * This object should conform to the PlaybackControlRequest interface,
2148
+ * which includes an 'operation' property specifying the control action to perform.
2149
+ * @returns A Promise that resolves when the control operation is successfully executed.
2150
+ * The promise resolves to void, indicating no specific return value.
2151
+ * If an error occurs during the operation, the promise will be rejected with an error object.
2152
+ * @throws Will throw an error if the playback control operation fails, e.g., if the playback doesn't exist
2153
+ * or the requested operation is invalid.
2154
+ */
1916
2155
  async controlPlayback(playbackId, controlRequest) {
1917
2156
  const { operation } = controlRequest;
1918
2157
  return this.playbacks.control(playbackId, operation);