@ipcom/asterisk-ari 0.0.37 → 0.0.38

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) {
@@ -1741,55 +1743,65 @@ var AriClient = class {
1741
1743
  "The 'app' parameter is required to connect to the 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();
1746
+ if (this.webSocketReady) {
1747
+ console.log("J\xE1 existe uma tentativa de conex\xE3o ativa. Aguardando...");
1748
+ return this.webSocketReady;
1768
1749
  }
1769
- if (!this.wsClient) {
1770
- console.log("Criando nova inst\xE2ncia do WebSocketClient...");
1771
- this.wsClient = new WebSocketClient(wsUrl);
1772
- }
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
+ "Already attempting to reconnect. Skipping this attempt."
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(
1762
+ this.config.username
1763
+ )}:${encodeURIComponent(this.config.password)}@${this.config.host}:${this.config.port}/ari/events?app=${app}${eventsParam}`;
1764
+ const backoffOptions = {
1765
+ delayFirstAttempt: false,
1766
+ startingDelay: 1e3,
1767
+ timeMultiple: 2,
1768
+ maxDelay: 3e4,
1769
+ numOfAttempts: 10,
1770
+ jitter: "full",
1771
+ retry: (error, attemptNumber) => {
1772
+ console.warn(`Tentativa ${attemptNumber} falhou: ${error.message}`);
1773
+ return !this.wsClient?.isConnected();
1774
+ }
1775
+ };
1776
+ if (this.wsClient?.isConnected()) {
1777
+ console.log("WebSocket j\xE1 conectado. Removendo listeners antigos...");
1778
+ this.wsClient.removeAllListeners();
1779
+ this.wsClient.close();
1780
+ }
1781
+ this.wsClient = new WebSocketClient(wsUrl);
1782
+ await (0, import_exponential_backoff.backOff)(async () => {
1783
+ if (!this.wsClient) {
1784
+ throw new Error("WebSocketClient instance is null.");
1785
+ }
1786
+ await this.wsClient.connect();
1787
+ this.integrateWebSocketEvents(app, this.wsClient);
1788
+ console.log(`WebSocket conectado para o app: ${app}`);
1789
+ await this.ensureAppRegistered(app);
1790
+ this.processPendingListeners();
1791
+ }, backoffOptions);
1792
+ resolve();
1793
+ } catch (err) {
1794
+ console.error(
1795
+ "N\xE3o foi poss\xEDvel conectar ao WebSocket ap\xF3s m\xFAltiplas tentativas:",
1796
+ err
1797
+ );
1798
+ reject(err);
1799
+ } finally {
1800
+ this.isReconnecting = false;
1801
+ this.webSocketReady = null;
1802
+ }
1803
+ });
1804
+ return this.webSocketReady;
1793
1805
  }
1794
1806
  /**
1795
1807
  * Integrates WebSocket events with playback listeners.
@@ -1948,13 +1960,13 @@ var AriClient = class {
1948
1960
  * @throws {Error} Throws an error if the WebSocket client is not connected when this method is called.
1949
1961
  * @returns {void} This function doesn't return a value.
1950
1962
  */
1951
- onWebSocketEvent(event, callback) {
1963
+ async onWebSocketEvent(event, callback) {
1964
+ if (this.webSocketReady) {
1965
+ console.log(`Aguardando WebSocket conectar antes de registrar: ${event}`);
1966
+ await this.webSocketReady;
1967
+ }
1952
1968
  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;
1969
+ throw new Error("WebSocket ainda n\xE3o est\xE1 conectado.");
1958
1970
  }
1959
1971
  console.log(`Registrando listener para evento: ${event}`);
1960
1972
  this.wsClient.on(event, callback);