@ipcom/asterisk-ari 0.0.37 → 0.0.39

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.
@@ -1700,6 +1700,8 @@ var AriClient = class {
1700
1700
  eventEmitter = new import_events4.EventEmitter();
1701
1701
  wsConnections = /* @__PURE__ */ new Map();
1702
1702
  isWebSocketConnectedFlag = false;
1703
+ webSocketReady = null;
1704
+ // Promise para rastrear o estado do WebSocket
1703
1705
  pendingListeners = [];
1704
1706
  processPendingListeners() {
1705
1707
  if (!this.wsClient || !this.isWebSocketConnectedFlag) {
@@ -1738,58 +1740,67 @@ var AriClient = class {
1738
1740
  async connectWebSocket(app, subscribedEvents) {
1739
1741
  if (!app) {
1740
1742
  throw new Error(
1741
- "The 'app' parameter is required to connect to the WebSocket."
1743
+ "O par\xE2metro 'app' \xE9 obrigat\xF3rio para conectar ao WebSocket."
1742
1744
  );
1743
1745
  }
1744
- if (this.isReconnecting) {
1745
- console.warn("Already attempting to reconnect. Skipping this attempt.");
1746
- return;
1747
- }
1748
- this.isReconnecting = true;
1749
- const eventsParam = subscribedEvents && subscribedEvents.length > 0 ? `&event=${subscribedEvents.join(",")}` : "&subscribeAll=true";
1750
- const protocol = this.config.secure ? "wss" : "ws";
1751
- const wsUrl = `${protocol}://${encodeURIComponent(this.config.username)}:${encodeURIComponent(this.config.password)}@${this.config.host}:${this.config.port}/ari/events?app=${app}${eventsParam}`;
1752
- const backoffOptions = {
1753
- delayFirstAttempt: false,
1754
- startingDelay: 1e3,
1755
- timeMultiple: 2,
1756
- maxDelay: 3e4,
1757
- numOfAttempts: 10,
1758
- jitter: "full",
1759
- retry: (error, attemptNumber) => {
1760
- console.warn(`Tentativa ${attemptNumber} falhou: ${error.message}`);
1761
- return !this.wsClient?.isConnected();
1762
- }
1763
- };
1764
- if (this.wsClient?.isConnected()) {
1765
- console.log("WebSocket j\xE1 conectado. Removendo listeners antigos...");
1766
- this.wsClient.removeAllListeners();
1767
- this.wsClient.close();
1768
- }
1769
- if (!this.wsClient) {
1770
- console.log("Criando nova inst\xE2ncia do WebSocketClient...");
1771
- this.wsClient = new WebSocketClient(wsUrl);
1746
+ if (this.webSocketReady) {
1747
+ console.log("J\xE1 existe uma tentativa de conex\xE3o ativa. Aguardando...");
1748
+ return this.webSocketReady;
1772
1749
  }
1773
- try {
1774
- await (0, import_exponential_backoff.backOff)(async () => {
1775
- if (!this.wsClient) {
1776
- throw new Error("WebSocketClient instance is null.");
1750
+ this.webSocketReady = new Promise(async (resolve, reject) => {
1751
+ try {
1752
+ if (this.isReconnecting) {
1753
+ console.warn(
1754
+ "J\xE1 est\xE1 tentando reconectar. Ignorando esta tentativa."
1755
+ );
1756
+ return;
1777
1757
  }
1778
- await this.wsClient.connect();
1779
- this.integrateWebSocketEvents(app, this.wsClient);
1780
- console.log(`WebSocket conectado para o app: ${app}`);
1781
- await this.ensureAppRegistered(app);
1782
- this.processPendingListeners();
1783
- }, backoffOptions);
1784
- } catch (err) {
1785
- console.error(
1786
- "N\xE3o foi poss\xEDvel conectar ao WebSocket ap\xF3s m\xFAltiplas tentativas:",
1787
- err
1788
- );
1789
- throw err;
1790
- } finally {
1791
- this.isReconnecting = false;
1792
- }
1758
+ this.isReconnecting = true;
1759
+ const eventsParam = subscribedEvents && subscribedEvents.length > 0 ? `&event=${subscribedEvents.join(",")}` : "&subscribeAll=true";
1760
+ const protocol = this.config.secure ? "wss" : "ws";
1761
+ const wsUrl = `${protocol}://${encodeURIComponent(this.config.username)}:${encodeURIComponent(this.config.password)}@${this.config.host}:${this.config.port}/ari/events?app=${app}${eventsParam}`;
1762
+ const backoffOptions = {
1763
+ delayFirstAttempt: false,
1764
+ startingDelay: 1e3,
1765
+ timeMultiple: 2,
1766
+ maxDelay: 3e4,
1767
+ numOfAttempts: 10,
1768
+ jitter: "full",
1769
+ retry: (error, attemptNumber) => {
1770
+ console.warn(`Tentativa ${attemptNumber} falhou: ${error.message}`);
1771
+ return !this.wsClient?.isConnected();
1772
+ }
1773
+ };
1774
+ if (this.wsClient?.isConnected()) {
1775
+ console.log("WebSocket j\xE1 conectado. Removendo listeners antigos...");
1776
+ this.wsClient.removeAllListeners();
1777
+ this.wsClient.close();
1778
+ }
1779
+ this.wsClient = new WebSocketClient(wsUrl);
1780
+ await (0, import_exponential_backoff.backOff)(async () => {
1781
+ if (!this.wsClient) {
1782
+ throw new Error("WebSocketClient instance is null.");
1783
+ }
1784
+ await this.wsClient.connect();
1785
+ this.integrateWebSocketEvents(app, this.wsClient);
1786
+ console.log(`WebSocket conectado para o app: ${app}`);
1787
+ await this.ensureAppRegistered(app);
1788
+ this.processPendingListeners();
1789
+ this.isWebSocketConnectedFlag = true;
1790
+ }, backoffOptions);
1791
+ resolve();
1792
+ } catch (err) {
1793
+ console.error(
1794
+ "N\xE3o foi poss\xEDvel conectar ao WebSocket ap\xF3s m\xFAltiplas tentativas:",
1795
+ err
1796
+ );
1797
+ reject(err);
1798
+ } finally {
1799
+ this.isReconnecting = false;
1800
+ this.webSocketReady = null;
1801
+ }
1802
+ });
1803
+ return this.webSocketReady;
1793
1804
  }
1794
1805
  /**
1795
1806
  * Integrates WebSocket events with playback listeners.
@@ -1800,6 +1811,7 @@ var AriClient = class {
1800
1811
  `WebSocket client para o app '${app}' n\xE3o est\xE1 conectado.`
1801
1812
  );
1802
1813
  }
1814
+ console.log(`[${app}] Registrando eventos do WebSocket...`);
1803
1815
  const eventHandlers = {
1804
1816
  PlaybackFinished: (data) => {
1805
1817
  if ("playbackId" in data) {
@@ -1827,20 +1839,6 @@ var AriClient = class {
1827
1839
  this.channels.emitChannelEvent("ChannelDtmfReceived", data);
1828
1840
  }
1829
1841
  this.emitGlobalEvent(data);
1830
- },
1831
- // Adicione mais eventos conforme necessário
1832
- EndpointStateChange: (data) => {
1833
- if ("endpoint" in data) {
1834
- console.log(`[${app}] Estado do endpoint alterado:`, data.endpoint);
1835
- }
1836
- this.emitGlobalEvent(data);
1837
- },
1838
- ChannelHangupRequest: (data) => {
1839
- if ("channel" in data) {
1840
- console.log(`[${app}] Requisi\xE7\xE3o de hangup no canal:`, data.channel);
1841
- this.channels.emitChannelEvent("ChannelHangupRequest", data);
1842
- }
1843
- this.emitGlobalEvent(data);
1844
1842
  }
1845
1843
  };
1846
1844
  for (const [eventType, handler] of Object.entries(eventHandlers)) {
@@ -1948,13 +1946,13 @@ var AriClient = class {
1948
1946
  * @throws {Error} Throws an error if the WebSocket client is not connected when this method is called.
1949
1947
  * @returns {void} This function doesn't return a value.
1950
1948
  */
1951
- onWebSocketEvent(event, callback) {
1949
+ async onWebSocketEvent(event, callback) {
1950
+ if (this.webSocketReady) {
1951
+ console.log(`Aguardando WebSocket conectar antes de registrar: ${event}`);
1952
+ await this.webSocketReady;
1953
+ }
1952
1954
  if (!this.wsClient || !this.isWebSocketConnectedFlag) {
1953
- console.warn(
1954
- `WebSocket ainda n\xE3o est\xE1 conectado. Colocando o listener na fila para: ${event}`
1955
- );
1956
- this.pendingListeners.push({ event, callback });
1957
- return;
1955
+ throw new Error("WebSocket ainda n\xE3o est\xE1 conectado.");
1958
1956
  }
1959
1957
  console.log(`Registrando listener para evento: ${event}`);
1960
1958
  this.wsClient.on(event, callback);