@ipcom/asterisk-ari 0.0.152 → 0.0.153

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.
@@ -2340,17 +2340,12 @@ 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 WebSocketClient instance.
2343
+ * Creates a new WebSocket client instance.
2344
2344
  *
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.
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
2354
2349
  */
2355
2350
  constructor(baseClient, apps, subscribedEvents, ariClient) {
2356
2351
  super();
@@ -2365,8 +2360,6 @@ var WebSocketClient = class extends import_events3.EventEmitter {
2365
2360
  ws;
2366
2361
  isReconnecting = false;
2367
2362
  maxReconnectAttempts = DEFAULT_MAX_RECONNECT_ATTEMPTS;
2368
- reconnectionAttempts = 0;
2369
- lastWsUrl = "";
2370
2363
  backOffOptions = {
2371
2364
  numOfAttempts: DEFAULT_MAX_RECONNECT_ATTEMPTS,
2372
2365
  startingDelay: DEFAULT_STARTING_DELAY,
@@ -2383,14 +2376,10 @@ var WebSocketClient = class extends import_events3.EventEmitter {
2383
2376
  }
2384
2377
  };
2385
2378
  /**
2386
- * Establishes a WebSocket connection to the Asterisk server.
2387
- *
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.
2379
+ * Establishes a WebSocket connection.
2391
2380
  *
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.
2381
+ * @returns {Promise<void>} Resolves when connection is established
2382
+ * @throws {Error} If connection fails
2394
2383
  */
2395
2384
  async connect() {
2396
2385
  const { baseUrl, username, password } = this.baseClient.getCredentials();
@@ -2405,24 +2394,15 @@ var WebSocketClient = class extends import_events3.EventEmitter {
2405
2394
  } else {
2406
2395
  queryParams.append("subscribeAll", "true");
2407
2396
  }
2408
- this.lastWsUrl = `${protocol}://${encodeURIComponent(username)}:${encodeURIComponent(password)}@${normalizedHost}/ari/events?${queryParams.toString()}`;
2397
+ const wsUrl = `${protocol}://${encodeURIComponent(username)}:${encodeURIComponent(password)}@${normalizedHost}/ari/events?${queryParams.toString()}`;
2409
2398
  console.log("Connecting to WebSocket...");
2410
- return this.initializeWebSocket(this.lastWsUrl);
2399
+ return this.initializeWebSocket(wsUrl);
2411
2400
  }
2412
2401
  /**
2413
- * Initializes a WebSocket connection with exponential backoff retry mechanism.
2414
- *
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.
2402
+ * Initializes WebSocket connection with reconnection logic.
2420
2403
  *
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.
2404
+ * @param {string} wsUrl - The WebSocket URL to connect to
2405
+ * @returns {Promise<void>} Resolves when connection is established
2426
2406
  */
2427
2407
  async initializeWebSocket(wsUrl) {
2428
2408
  return (0, import_exponential_backoff.backOff)(async () => {
@@ -2431,14 +2411,7 @@ var WebSocketClient = class extends import_events3.EventEmitter {
2431
2411
  this.ws = new import_ws.default(wsUrl);
2432
2412
  this.ws.on("open", () => {
2433
2413
  console.log("WebSocket connection established successfully");
2434
- if (this.isReconnecting) {
2435
- this.emit("reconnected", {
2436
- apps: this.apps,
2437
- subscribedEvents: this.subscribedEvents
2438
- });
2439
- }
2440
2414
  this.isReconnecting = false;
2441
- this.reconnectionAttempts = 0;
2442
2415
  this.emit("connected");
2443
2416
  resolve();
2444
2417
  });
@@ -2448,13 +2421,13 @@ var WebSocketClient = class extends import_events3.EventEmitter {
2448
2421
  `WebSocket disconnected with code ${code}. Attempting to reconnect...`
2449
2422
  );
2450
2423
  if (!this.isReconnecting) {
2451
- this.reconnect(this.lastWsUrl);
2424
+ this.reconnect(wsUrl);
2452
2425
  }
2453
2426
  });
2454
2427
  this.ws.on("error", (err) => {
2455
2428
  console.error("WebSocket error:", err.message);
2456
2429
  if (!this.isReconnecting) {
2457
- this.reconnect(this.lastWsUrl);
2430
+ this.reconnect(wsUrl);
2458
2431
  }
2459
2432
  reject(err);
2460
2433
  });
@@ -2465,16 +2438,9 @@ var WebSocketClient = class extends import_events3.EventEmitter {
2465
2438
  }, this.backOffOptions);
2466
2439
  }
2467
2440
  /**
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.
2441
+ * Processes incoming WebSocket messages.
2473
2442
  *
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.
2476
- *
2477
- * @throws Will emit an 'error' event if the message cannot be parsed or processed.
2443
+ * @param {string} rawMessage - The raw message received from WebSocket
2478
2444
  */
2479
2445
  handleMessage(rawMessage) {
2480
2446
  try {
@@ -2502,27 +2468,18 @@ var WebSocketClient = class extends import_events3.EventEmitter {
2502
2468
  }
2503
2469
  }
2504
2470
  /**
2505
- * Attempts to reconnect to the WebSocket server using an exponential backoff strategy.
2506
- *
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.
2471
+ * Attempts to reconnect to the WebSocket.
2510
2472
  *
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.
2473
+ * @param {string} wsUrl - The WebSocket URL to reconnect to
2515
2474
  */
2516
2475
  reconnect(wsUrl) {
2517
2476
  this.isReconnecting = true;
2518
- this.reconnectionAttempts++;
2519
- console.log(
2520
- `Initiating reconnection attempt #${this.reconnectionAttempts}...`
2521
- );
2477
+ console.log("Initiating reconnection attempt...");
2478
+ this.removeAllListeners();
2522
2479
  (0, import_exponential_backoff.backOff)(() => this.initializeWebSocket(wsUrl), this.backOffOptions).catch(
2523
2480
  (error) => {
2524
2481
  console.error(
2525
- `Failed to reconnect after ${this.reconnectionAttempts} attempts:`,
2482
+ "Failed to reconnect after multiple attempts:",
2526
2483
  error instanceof Error ? error.message : "Unknown error"
2527
2484
  );
2528
2485
  this.emit("reconnectFailed", error);
@@ -2530,13 +2487,7 @@ var WebSocketClient = class extends import_events3.EventEmitter {
2530
2487
  );
2531
2488
  }
2532
2489
  /**
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.
2490
+ * Manually closes the WebSocket connection.
2540
2491
  */
2541
2492
  close() {
2542
2493
  try {
@@ -2552,9 +2503,19 @@ var WebSocketClient = class extends import_events3.EventEmitter {
2552
2503
  );
2553
2504
  }
2554
2505
  }
2506
+ /**
2507
+ * Checks if the WebSocket is currently connected.
2508
+ *
2509
+ * @returns {boolean} True if connected, false otherwise
2510
+ */
2555
2511
  isConnected() {
2556
2512
  return this.ws?.readyState === import_ws.default.OPEN;
2557
2513
  }
2514
+ /**
2515
+ * Gets the current connection state.
2516
+ *
2517
+ * @returns {number} The WebSocket ready state
2518
+ */
2558
2519
  getState() {
2559
2520
  return this.ws?.readyState ?? import_ws.default.CLOSED;
2560
2521
  }