@ipcom/asterisk-ari 0.0.153 → 0.0.154

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.
@@ -2335,17 +2335,22 @@ var Sounds = class {
2335
2335
  var import_events3 = require("events");
2336
2336
  var import_exponential_backoff = __toESM(require_backoff(), 1);
2337
2337
  var import_ws = __toESM(require("ws"), 1);
2338
- var DEFAULT_MAX_RECONNECT_ATTEMPTS = 10;
2338
+ var DEFAULT_MAX_RECONNECT_ATTEMPTS = 30;
2339
2339
  var DEFAULT_STARTING_DELAY = 500;
2340
2340
  var DEFAULT_MAX_DELAY = 1e4;
2341
2341
  var WebSocketClient = class extends import_events3.EventEmitter {
2342
2342
  /**
2343
- * Creates a new WebSocket client instance.
2343
+ * Creates a new WebSocketClient instance.
2344
2344
  *
2345
- * @param {BaseClient} baseClient - The base client containing connection details
2346
- * @param {string[]} apps - List of applications to connect to
2347
- * @param {WebSocketEventType[]} [subscribedEvents] - Optional list of events to subscribe to
2348
- * @param {AriClient} [ariClient] - Optional ARI client for handling channel and playback events
2345
+ * This constructor initializes a WebSocketClient with the necessary dependencies and configuration.
2346
+ * It ensures that at least one application name is provided.
2347
+ *
2348
+ * @param baseClient - The BaseClient instance used for basic ARI operations and authentication.
2349
+ * @param apps - An array of application names to connect to via the WebSocket.
2350
+ * @param subscribedEvents - Optional. An array of WebSocketEventTypes to subscribe to. If not provided, all events will be subscribed.
2351
+ * @param ariClient - Optional. The AriClient instance, used for creating Channel and Playback instances when processing events.
2352
+ *
2353
+ * @throws {Error} Throws an error if the apps array is empty.
2349
2354
  */
2350
2355
  constructor(baseClient, apps, subscribedEvents, ariClient) {
2351
2356
  super();
@@ -2360,6 +2365,8 @@ var WebSocketClient = class extends import_events3.EventEmitter {
2360
2365
  ws;
2361
2366
  isReconnecting = false;
2362
2367
  maxReconnectAttempts = DEFAULT_MAX_RECONNECT_ATTEMPTS;
2368
+ reconnectionAttempts = 0;
2369
+ lastWsUrl = "";
2363
2370
  backOffOptions = {
2364
2371
  numOfAttempts: DEFAULT_MAX_RECONNECT_ATTEMPTS,
2365
2372
  startingDelay: DEFAULT_STARTING_DELAY,
@@ -2376,10 +2383,14 @@ var WebSocketClient = class extends import_events3.EventEmitter {
2376
2383
  }
2377
2384
  };
2378
2385
  /**
2379
- * Establishes a WebSocket connection.
2386
+ * Establishes a WebSocket connection to the Asterisk server.
2380
2387
  *
2381
- * @returns {Promise<void>} Resolves when connection is established
2382
- * @throws {Error} If connection fails
2388
+ * This method constructs the WebSocket URL using the base URL, credentials,
2389
+ * application names, and subscribed events. It then initiates the connection
2390
+ * using the constructed URL.
2391
+ *
2392
+ * @returns A Promise that resolves when the WebSocket connection is successfully established.
2393
+ * @throws Will throw an error if the connection cannot be established.
2383
2394
  */
2384
2395
  async connect() {
2385
2396
  const { baseUrl, username, password } = this.baseClient.getCredentials();
@@ -2394,15 +2405,24 @@ var WebSocketClient = class extends import_events3.EventEmitter {
2394
2405
  } else {
2395
2406
  queryParams.append("subscribeAll", "true");
2396
2407
  }
2397
- const wsUrl = `${protocol}://${encodeURIComponent(username)}:${encodeURIComponent(password)}@${normalizedHost}/ari/events?${queryParams.toString()}`;
2408
+ this.lastWsUrl = `${protocol}://${encodeURIComponent(username)}:${encodeURIComponent(password)}@${normalizedHost}/ari/events?${queryParams.toString()}`;
2398
2409
  console.log("Connecting to WebSocket...");
2399
- return this.initializeWebSocket(wsUrl);
2410
+ return this.initializeWebSocket(this.lastWsUrl);
2400
2411
  }
2401
2412
  /**
2402
- * Initializes WebSocket connection with reconnection logic.
2413
+ * Initializes a WebSocket connection with exponential backoff retry mechanism.
2403
2414
  *
2404
- * @param {string} wsUrl - The WebSocket URL to connect to
2405
- * @returns {Promise<void>} Resolves when connection is established
2415
+ * This method attempts to establish a WebSocket connection to the specified URL.
2416
+ * It sets up event listeners for the WebSocket's 'open', 'message', 'close', and 'error' events.
2417
+ * If the connection is successful, it emits a 'connected' event. If it's a reconnection,
2418
+ * it also emits a 'reconnected' event with the current apps and subscribed events.
2419
+ * In case of connection failure, it uses an exponential backoff strategy to retry.
2420
+ *
2421
+ * @param wsUrl - The WebSocket URL to connect to.
2422
+ * @returns A Promise that resolves when the connection is successfully established,
2423
+ * or rejects if an error occurs during the connection process.
2424
+ * @throws Will throw an error if the WebSocket connection cannot be established
2425
+ * after the maximum number of retry attempts.
2406
2426
  */
2407
2427
  async initializeWebSocket(wsUrl) {
2408
2428
  return (0, import_exponential_backoff.backOff)(async () => {
@@ -2411,7 +2431,14 @@ var WebSocketClient = class extends import_events3.EventEmitter {
2411
2431
  this.ws = new import_ws.default(wsUrl);
2412
2432
  this.ws.on("open", () => {
2413
2433
  console.log("WebSocket connection established successfully");
2434
+ if (this.isReconnecting) {
2435
+ this.emit("reconnected", {
2436
+ apps: this.apps,
2437
+ subscribedEvents: this.subscribedEvents
2438
+ });
2439
+ }
2414
2440
  this.isReconnecting = false;
2441
+ this.reconnectionAttempts = 0;
2415
2442
  this.emit("connected");
2416
2443
  resolve();
2417
2444
  });
@@ -2421,13 +2448,13 @@ var WebSocketClient = class extends import_events3.EventEmitter {
2421
2448
  `WebSocket disconnected with code ${code}. Attempting to reconnect...`
2422
2449
  );
2423
2450
  if (!this.isReconnecting) {
2424
- this.reconnect(wsUrl);
2451
+ this.reconnect(this.lastWsUrl);
2425
2452
  }
2426
2453
  });
2427
2454
  this.ws.on("error", (err) => {
2428
2455
  console.error("WebSocket error:", err.message);
2429
2456
  if (!this.isReconnecting) {
2430
- this.reconnect(wsUrl);
2457
+ this.reconnect(this.lastWsUrl);
2431
2458
  }
2432
2459
  reject(err);
2433
2460
  });
@@ -2438,9 +2465,16 @@ var WebSocketClient = class extends import_events3.EventEmitter {
2438
2465
  }, this.backOffOptions);
2439
2466
  }
2440
2467
  /**
2441
- * Processes incoming WebSocket messages.
2468
+ * Handles incoming WebSocket messages by parsing and processing events.
2469
+ *
2470
+ * This method parses the raw message into a WebSocketEvent, filters it based on
2471
+ * subscribed events (if any), processes channel and playback events, and emits
2472
+ * the event to listeners. It also handles any errors that occur during processing.
2473
+ *
2474
+ * @param rawMessage - The raw message string received from the WebSocket connection.
2475
+ * @returns void This method doesn't return a value but emits events.
2442
2476
  *
2443
- * @param {string} rawMessage - The raw message received from WebSocket
2477
+ * @throws Will emit an 'error' event if the message cannot be parsed or processed.
2444
2478
  */
2445
2479
  handleMessage(rawMessage) {
2446
2480
  try {
@@ -2468,18 +2502,27 @@ var WebSocketClient = class extends import_events3.EventEmitter {
2468
2502
  }
2469
2503
  }
2470
2504
  /**
2471
- * Attempts to reconnect to the WebSocket.
2505
+ * Attempts to reconnect to the WebSocket server using an exponential backoff strategy.
2472
2506
  *
2473
- * @param {string} wsUrl - The WebSocket URL to reconnect to
2507
+ * This method is called when the WebSocket connection is closed unexpectedly.
2508
+ * It increments the reconnection attempt counter, logs the attempt, and uses
2509
+ * the backOff utility to retry the connection with exponential delays between attempts.
2510
+ *
2511
+ * @param wsUrl - The WebSocket URL to reconnect to.
2512
+ * @returns void - This method doesn't return a value.
2513
+ *
2514
+ * @emits reconnectFailed - Emitted if all reconnection attempts fail.
2474
2515
  */
2475
2516
  reconnect(wsUrl) {
2476
2517
  this.isReconnecting = true;
2477
- console.log("Initiating reconnection attempt...");
2478
- this.removeAllListeners();
2518
+ this.reconnectionAttempts++;
2519
+ console.log(
2520
+ `Initiating reconnection attempt #${this.reconnectionAttempts}...`
2521
+ );
2479
2522
  (0, import_exponential_backoff.backOff)(() => this.initializeWebSocket(wsUrl), this.backOffOptions).catch(
2480
2523
  (error) => {
2481
2524
  console.error(
2482
- "Failed to reconnect after multiple attempts:",
2525
+ `Failed to reconnect after ${this.reconnectionAttempts} attempts:`,
2483
2526
  error instanceof Error ? error.message : "Unknown error"
2484
2527
  );
2485
2528
  this.emit("reconnectFailed", error);
@@ -2487,7 +2530,13 @@ var WebSocketClient = class extends import_events3.EventEmitter {
2487
2530
  );
2488
2531
  }
2489
2532
  /**
2490
- * Manually closes the WebSocket connection.
2533
+ * Closes the WebSocket connection if it exists.
2534
+ *
2535
+ * This method attempts to gracefully close the WebSocket connection
2536
+ * and sets the WebSocket instance to undefined. If an error occurs
2537
+ * during the closing process, it will be caught and logged.
2538
+ *
2539
+ * @throws {Error} Logs an error message if closing the WebSocket fails.
2491
2540
  */
2492
2541
  close() {
2493
2542
  try {
@@ -2504,17 +2553,30 @@ var WebSocketClient = class extends import_events3.EventEmitter {
2504
2553
  }
2505
2554
  }
2506
2555
  /**
2507
- * Checks if the WebSocket is currently connected.
2556
+ * Checks if the WebSocket connection is currently open and active.
2557
+ *
2558
+ * This method provides a way to determine the current state of the WebSocket connection.
2559
+ * It checks if the WebSocket's readyState property is equal to WebSocket.OPEN,
2560
+ * which indicates an active connection.
2508
2561
  *
2509
- * @returns {boolean} True if connected, false otherwise
2562
+ * @returns {boolean} True if the WebSocket connection is open and active, false otherwise.
2510
2563
  */
2511
2564
  isConnected() {
2512
2565
  return this.ws?.readyState === import_ws.default.OPEN;
2513
2566
  }
2514
2567
  /**
2515
- * Gets the current connection state.
2568
+ * Retrieves the current state of the WebSocket connection.
2569
+ *
2570
+ * This method provides a way to check the current state of the WebSocket connection.
2571
+ * It returns a number corresponding to one of the WebSocket readyState values:
2572
+ * - 0 (CONNECTING): The connection is not yet open.
2573
+ * - 1 (OPEN): The connection is open and ready to communicate.
2574
+ * - 2 (CLOSING): The connection is in the process of closing.
2575
+ * - 3 (CLOSED): The connection is closed or couldn't be opened.
2576
+ *
2577
+ * If the WebSocket instance doesn't exist, it returns WebSocket.CLOSED (3).
2516
2578
  *
2517
- * @returns {number} The WebSocket ready state
2579
+ * @returns {number} A number representing the current state of the WebSocket connection.
2518
2580
  */
2519
2581
  getState() {
2520
2582
  return this.ws?.readyState ?? import_ws.default.CLOSED;