### Install @telnyx/react-client Source: https://github.com/team-telnyx/webrtc/blob/main/packages/react-client/README.md Install the required packages via npm. ```bash npm install --save @telnyx/react-client @telnyx/webrtc ``` -------------------------------- ### Install Telnyx WebRTC Package Source: https://github.com/team-telnyx/webrtc/blob/main/packages/js/README.md Install the @telnyx/webrtc package using npm. This is the first step to using the client in your project. ```bash npm install @telnyx/webrtc --save ``` -------------------------------- ### Media Permissions Recovery Example Source: https://github.com/team-telnyx/webrtc/blob/main/packages/js/docs/ts/interfaces/IClientOptions.md Example demonstrating how to configure and handle media permissions recovery for inbound calls using the Telnyx WebRTC SDK. This includes setting up recovery options and listening for 'telnyx.error' events. ```javascript import { isMediaRecoveryErrorEvent } from '@telnyx/webrtc'; const client = new TelnyxRTC({ login_token: '...', mediaPermissionsRecovery: { enabled: true, timeout: 20000, onSuccess: () => console.log('Media recovered'), onError: (err) => console.error('Recovery failed', err), }, }); client.on('telnyx.error', (event) => { if (isMediaRecoveryErrorEvent(event)) { showPermissionDialog({ onContinue: () => event.resume(), onCancel: () => event.reject?.(), }); } }); ``` -------------------------------- ### Get All Devices (Async/Await) Source: https://github.com/team-telnyx/webrtc/blob/main/packages/js/docs/ts/classes/TelnyxRTC.md Retrieves a list of all devices supported by the browser using async/await syntax. Logs the result to the console. ```js async function() { const client = new TelnyxRTC(options); let result = await client.getDevices(); console.log(result); } ``` -------------------------------- ### TSDoc @examples Tag Example Source: https://github.com/team-telnyx/webrtc/blob/main/packages/js/README.md Shows how to use the '@examples' TSDoc tag to include code samples within the documentation. This is useful for demonstrating how to use a class or function. ```typescript /** * @examples * ```js * new PublicUseModule(options); * ``` */ ``` -------------------------------- ### Get Audio Input Devices (Async/Await) Source: https://github.com/team-telnyx/webrtc/blob/main/packages/js/docs/ts/classes/TelnyxRTC.md Retrieves a list of audio input devices supported by the browser using async/await syntax. Logs the result to the console. ```js async function() { const client = new TelnyxRTC(options); let result = await client.getAudioInDevices(); console.log(result); } ``` -------------------------------- ### Get Audio Output Devices (Async/Await) Source: https://github.com/team-telnyx/webrtc/blob/main/packages/js/docs/ts/classes/TelnyxRTC.md Retrieves a list of audio output devices supported by the browser using async/await syntax. Logs the result to the console. ```js async function() { const client = new TelnyxRTC(options); let result = await client.getAudioOutDevices(); console.log(result); } ``` -------------------------------- ### Handle SDK Errors Source: https://github.com/team-telnyx/webrtc/blob/main/packages/js/docs/error-handling.md Example implementation for listening to error events, including media permission recovery and standard error code handling. ```ts client.on(SwEvent.Error, (event) => { if (isMediaRecoveryErrorEvent(event)) { openPermissionsDialog({ deadline: event.retryDeadline, onRetry: () => event.resume(), onCancel: () => event.reject(), }); return; } if (!(event.error instanceof TelnyxError)) { showErrorMessage('An unknown SDK error occurred.'); return; } switch (event.error.code) { case TELNYX_ERROR_CODES.NETWORK_OFFLINE: showErrorMessage('You appear to be offline.'); break; case TELNYX_ERROR_CODES.AUTHENTICATION_REQUIRED: showErrorMessage('Session expired. Please authenticate again.'); break; default: showErrorMessage(event.error.message); } }); ``` -------------------------------- ### Get All Devices (Promises) Source: https://github.com/team-telnyx/webrtc/blob/main/packages/js/docs/ts/classes/TelnyxRTC.md Retrieves a list of all devices supported by the browser using ES6 Promises. Logs the result to the console. ```js client.getDevices().then((result) => { console.log(result); }); ``` -------------------------------- ### logCallEstablishmentTimings Source: https://github.com/team-telnyx/webrtc/blob/main/packages/js/docs/ts/README.md Logs call establishment timings in a readable table format. This method is useful for performance analysis and debugging of call setup processes. ```APIDOC ## logCallEstablishmentTimings ### Description Log call establishment timings as a readable table. ### Method ```typescript logCallEstablishmentTimings(timings: ICallEstablishmentTimings): void ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters #### `timings` - **timings** (ICallEstablishmentTimings) - Required - An object conforming to the ICallEstablishmentTimings interface, containing detailed timing information for call establishment. ### Request Example ```typescript // Example usage: // const timingsData = { ... }; // Populate with ICallEstablishmentTimings data // logCallEstablishmentTimings(timingsData); ``` ### Response #### Success Response (void) This method does not return any value. #### Response Example ```json // No response body ``` ``` -------------------------------- ### Get Video Devices (Async/Await) Source: https://github.com/team-telnyx/webrtc/blob/main/packages/js/docs/ts/classes/TelnyxRTC.md Retrieves a list of available media input devices (cameras) using async/await syntax. Ensure TelnyxRTC is initialized with appropriate options. ```javascript async function() { const client = new TelnyxRTC(options); let result = await client.getVideoDevices(); console.log(result); } ``` -------------------------------- ### Get Audio Output Devices (Promises) Source: https://github.com/team-telnyx/webrtc/blob/main/packages/js/docs/ts/classes/TelnyxRTC.md Retrieves a list of audio output devices supported by the browser using ES6 Promises. Logs the result to the console. ```js client.getAudioOutDevices().then((result) => { console.log(result); }); ``` -------------------------------- ### Get Device Resolutions (Async/Await, No Device ID) Source: https://github.com/team-telnyx/webrtc/blob/main/packages/js/docs/ts/classes/TelnyxRTC.md Retrieves supported resolutions for the default webcam using async/await. If no webcam is connected, an error is thrown. If multiple are connected, resolutions from the default are returned. ```js async function() { const client = new TelnyxRTC(options); let result = await client.getDeviceResolutions(); console.log(result); } ``` -------------------------------- ### Get Audio Input Devices (Promises) Source: https://github.com/team-telnyx/webrtc/blob/main/packages/js/docs/ts/classes/TelnyxRTC.md Retrieves a list of audio input devices supported by the browser using ES6 Promises. Logs the result to the console. ```js client.getAudioInDevices().then((result) => { console.log(result); }); ``` -------------------------------- ### collectCallEstablishmentTimings Source: https://github.com/team-telnyx/webrtc/blob/main/packages/js/docs/ts/README.md Collects and returns all call establishment timings by analyzing performance marks. It supports different ICE modes and call directions, providing detailed insights into call setup performance. ```APIDOC ## collectCallEstablishmentTimings ### Description Collect all call establishment timings from performance marks. All times are measured from the 'new-call-start' mark. ### Method Not applicable (TypeScript function) ### Parameters #### Path Parameters Not applicable #### Query Parameters Not applicable #### Request Body Not applicable ### Parameters - **callId** (string) - The call ID to scope mark lookups to. - **mode** (string) - 'trickle' or 'non-trickle' ICE mode. - **direction** (string) - 'outbound' or 'inbound'. ### Returns - [`ICallEstablishmentTimings`](https://github.com/team-telnyx/webrtc/tree/main/packages/js/docs/ts/interfaces/ICallEstablishmentTimings.md) - An object containing various call establishment timing metrics. ``` -------------------------------- ### Get Device Resolutions (Async/Await, With Device ID) Source: https://github.com/team-telnyx/webrtc/blob/main/packages/js/docs/ts/classes/TelnyxRTC.md Retrieves supported resolutions for a specific webcam identified by deviceId using async/await. Logs the result to the console. ```js async function() { const client = new TelnyxRTC(options); let result = await client.getDeviceResolutions(deviceId); console.log(result); } ``` -------------------------------- ### Start a New AI Assistant Conversation Source: https://github.com/team-telnyx/webrtc/blob/main/packages/js/docs/ts/interfaces/TargetParams.md Use this configuration to initiate a new AI Assistant conversation. This is the most common scenario for anonymous logins. ```typescript anonymous_login: { target_id: 'assistant-UUID', target_type: 'ai_assistant', } ``` -------------------------------- ### TypeScript Documentation Example Source: https://github.com/team-telnyx/webrtc/blob/main/packages/js/README.md Illustrates how to use TSDoc comments in TypeScript to control documentation generation. It shows which symbols will be included based on comment presence, visibility, and specific tags like '@ignore'. ```typescript // `PublicUseModule` will appear in docs due to the class-level TSDoc comment. /** * A module for public consumption * @category Public Modules */ class PublicUseModule { // `getSomething` WILL appear in docs because // there is a TSDoc comment /** * Gets something. */ getSomething() {} // `getSomethingElse` will NOT appear in docs // because of the `@ignore` tag /** * Adds another thing * @ignore */ getSomethingElse() {} // `addAnotherThing` will NOT appear in docs // because there is no TSDoc comment addAnotherThing() {} // `updateSomething` will NOT appear in docs // because of the `private` keyword private updateSomething() {} // `deleteSomething` will NOT appear in docs // because of the `protected` keyword protected deleteSomething() {} } // `InternalUseModule` will NOT appear in docs, // even if its members are documented, because // there is no class-level TSDoc comment. class InternalUseModule { doThis() {} doThat() {} } ``` -------------------------------- ### Accessing Media Constraints Source: https://github.com/team-telnyx/webrtc/blob/main/packages/js/docs/ts/classes/TelnyxRTC.md Get the current audio and video constraints applied to the WebRTC client. This can be useful for understanding the active media settings. ```javascript const client = new TelnyxRTC(options); console.log(client.mediaConstraints); // => { audio: true, video: false } ``` -------------------------------- ### Get Device Resolutions (Promises, No Device ID) Source: https://github.com/team-telnyx/webrtc/blob/main/packages/js/docs/ts/classes/TelnyxRTC.md Retrieves supported resolutions for the default webcam using ES6 Promises. If no webcam is connected, an error is thrown. If multiple are connected, resolutions from the default are returned. ```js client.getDeviceResolutions().then((result) => { console.log(result); }); ``` -------------------------------- ### Get Local Media Stream Source: https://github.com/team-telnyx/webrtc/blob/main/packages/js/docs/ts/classes/Call.md Retrieve the local media stream to play in a video or audio element. Ensure the element is ready to receive the stream. ```javascript const stream = call.localStream; document.querySelector('audio').srcObject = stream; ``` -------------------------------- ### Get Device Resolutions (Promises, With Device ID) Source: https://github.com/team-telnyx/webrtc/blob/main/packages/js/docs/ts/classes/TelnyxRTC.md Retrieves supported resolutions for a specific webcam identified by deviceId using ES6 Promises. Logs the result to the console. ```js client.getDeviceResolutions(deviceId).then((result) => { console.log(result); }); ``` -------------------------------- ### Configure TelnyxRTC with Trickle ICE Enabled Source: https://github.com/team-telnyx/webrtc/blob/main/docs/network-connectivity-requirements.md Enable trickle ICE to reduce call setup time by sending ICE candidates as they are discovered. This requires setting `trickleIce: true` in the SDK configuration. ```javascript new TelnyxRTC({ login: 'username', password: 'password', trickleIce: true, }) ``` -------------------------------- ### Get Server Registration State Source: https://github.com/team-telnyx/webrtc/blob/main/packages/js/README.md Retrieve the current registration state from the server gateway using the `client.getIsRegistered` method. This is useful for checking connection status. ```javascript client.getIsRegistered().then(isRegistered => {...}) ``` -------------------------------- ### Get WebRTC Supported Browser List Source: https://github.com/team-telnyx/webrtc/blob/main/packages/js/docs/ts/classes/TelnyxRTC.md Retrieve a list of browsers and operating systems supported by TelnyxRTC. The output includes details on audio and video support for each platform. ```javascript const browserList = TelnyxRTC.webRTCSupportedBrowserList(); console.log(browserList); // => [{"operationSystem": "Android", "supported": [{"browserName": "Chrome", "features": ["video", "audio"], "supported": "full"},{...}] ``` -------------------------------- ### Handle Telnyx WebRTC Warnings Source: https://github.com/team-telnyx/webrtc/blob/main/packages/js/docs/error-handling.md Listen for various warning events from the Telnyx WebRTC client. This example shows how to handle specific warnings like token expiration and peer connection failures, and provides a fallback for logging unknown warnings. ```typescript import { SwEvent, TELNYX_WARNING_CODES, SDK_WARNINGS } from '@telnyx/webrtc'; client.on(SwEvent.Warning, ({ warning, callId }) => { if (warning.code === TELNYX_WARNING_CODES.TOKEN_EXPIRING_SOON) { refreshTokenSoon(); return; } if (warning.code === TELNYX_WARNING_CODES.PEER_CONNECTION_FAILED) { showWarningBanner(`Call ${callId ?? ''} is reconnecting`.trim()); return; } console.debug(SDK_WARNINGS[warning.code]?.description); console.warn(`[${warning.code}] ${warning.name}: ${warning.message}`); }); ``` -------------------------------- ### Get Video Devices (Promises) Source: https://github.com/team-telnyx/webrtc/blob/main/packages/js/docs/ts/classes/TelnyxRTC.md Retrieves a list of available media input devices (cameras) using ES6 Promises. This method is useful for handling asynchronous operations in a chainable manner. ```javascript client.getVideoDevices().then((result) => { console.log(result); }); ``` -------------------------------- ### TSDoc @apialias Tag Example Source: https://github.com/team-telnyx/webrtc/blob/main/packages/js/README.md Demonstrates the use of the '@apialias' TSDoc tag to specify an alternative name for an interface in public documentation. This allows for cleaner API representation. ```typescript /** * @apialias PublicObject */ interface IPublicObject {} ``` -------------------------------- ### Development Commands Source: https://github.com/team-telnyx/webrtc/blob/main/packages/react-client/README.md Commands for setting up the development environment. ```bash yarn install yarn start yarn link # in another tab: git clone https://github.com/team-telnyx/webrtc-examples/tree/main/react-client/react-app # fill in .env yarn install yarn link @telnyx/react-client yarn start ``` -------------------------------- ### Set Video Device using Available Devices Source: https://github.com/team-telnyx/webrtc/blob/main/packages/js/docs/ts/classes/Call.md Demonstrates setting the video device by first retrieving available devices and then selecting one. ```js let result = await client.getVideoDevices(); if (result.length) { await call.setVideoDevice(result[1].deviceId); } ``` -------------------------------- ### Set Audio Input Device using Available Devices Source: https://github.com/team-telnyx/webrtc/blob/main/packages/js/docs/ts/classes/Call.md Demonstrates setting the audio input device by first retrieving available devices and then selecting one. ```js let result = await client.getAudioInDevices(); if (result.length) { call.setAudioInDevice(result[1].deviceId); } ``` -------------------------------- ### Set Audio Output Device using Available Devices Source: https://github.com/team-telnyx/webrtc/blob/main/packages/js/docs/ts/classes/Call.md Demonstrates setting the audio output device by first retrieving available devices and then selecting one. ```js let result = await client.getAudioOutDevices(); if (result.length) { await call.setAudioOutDevice(result[1].deviceId); } ``` -------------------------------- ### Get Telnyx Call IDs Source: https://github.com/team-telnyx/webrtc/blob/main/packages/js/docs/ts/classes/Call.md Retrieve Telnyx-specific call identifiers. These are useful for correlating calls within the Telnyx platform. ```javascript const { telnyxCallControlId, telnyxSessionId, telnyxLegId } = call.telnyxIDs; ``` -------------------------------- ### IClientOptions Source: https://github.com/team-telnyx/webrtc/blob/main/packages/js/docs/ts/interfaces/IClientOptions.md Configuration options for initializing the Telnyx WebRTC client. ```APIDOC ## enableCallReports ### Description Enable automatic call quality reporting to voice-sdk-proxy. When enabled, WebRTC stats are collected periodically during calls and posted to the voice-sdk-proxy /call_report endpoint when the call ends. ### Type `boolean` ### Default `true` --- ## env ### Description Environment to use for the connection. So far this property is only for internal purposes. ### Type `Environment` --- ## forceRelayCandidate ### Description Force the use of a relay ICE candidate. ### Type `boolean` --- ## hangupOnBeforeUnload ### Description Controls whether the SDK attempts to send BYE for active calls during browser page unload. Enabled by default to preserve graceful call cleanup, but applications that handle page lifecycle themselves can disable it to avoid best-effort unload BYE races. ### Type `boolean` ### Default `true` --- ## iceServers ### Description ICE Servers to use for all calls within the client connection. Overrides the default ones. ### Type `RTCIceServer[]` --- ## keepConnectionAliveOnSocketClose ### Description By passing `keepConnectionAliveOnSocketClose` as `true`, the SDK will attempt to keep Peer connection alive when the WebSocket connection is closed unexpectedly (e.g. network interruption, device sleep, etc). ### Type `boolean` --- ## login ### Description The `username` to authenticate with your SIP Connection. `login` and `password` will take precedence over `login_token` for authentication. ### Type `string` --- ## login_token ### Description The JSON Web Token (JWT) to authenticate with your SIP Connection. This is the recommended authentication strategy. ### Type `string` --- ## maxReconnectAttempts ### Description Maximum number of automatic socket reconnection attempts after an unexpected disconnect. When the limit is reached, no further automatic reconnects are scheduled and a `telnyx.error` event with code `RECONNECTION_EXHAUSTED` (45003) is emitted. A manual `connect()` call resets the counter and starts a fresh retry sequence. Set to `0` to allow unlimited automatic reconnect attempts. ### Type `number` ### Default `10` --- ## mediaPermissionsRecovery ### Description Configuration for media permissions recovery on inbound calls. When enabled and the initial `getUserMedia` call fails while answering, the SDK emits a recoverable `telnyx.error` event with `resume()` and `reject()` callbacks so the app can prompt the user to fix permissions before the call fails. Recovery is attempted only for inbound calls. If the app calls `resume()`, the SDK retries `getUserMedia`. If the app calls `reject()` or does not respond before `timeout`, recovery fails and the call is terminated with the usual media error flow. ### Type `Object` #### Properties | Name | Type | Description | | :----------- | :--------------------------- | :---------------------------------------------------------------------------------------------- | | `enabled` | `boolean` | Enable the recovery flow. | | `onError?` | (`error`: `Error`) => `void` | Called when retry fails, the timeout expires, or the app calls `reject()`. | | `onSuccess?` | () => `void` | Called when the retry `getUserMedia` succeeds after `resume()`. | | `timeout` | `number` | Maximum time in ms to wait for the app to call `resume()` or `reject()`. Recommended max 25000. | ### Example ```js import { isMediaRecoveryErrorEvent } from "@telnyx/webrtc"; const client = new TelnyxRTC({ login_token: "...", mediaPermissionsRecovery: { enabled: true, timeout: 20000, onSuccess: () => console.log('Media recovered'), onError: (err) => console.error('Recovery failed', err), }, }); client.on('telnyx.error', (event) => { if (isMediaRecoveryErrorEvent(event)) { showPermissionDialog({ onContinue: () => event.resume(), onCancel: () => event.reject?.(), }); } }); ``` --- ## mutedMicOnStart ### Description Disabled microphone by default when the call starts or adding a new audio source. ### Type `boolean` --- ## password ### Description The `password` to authenticate with your SIP Connection. ### Type `string` --- ## prefetchIceCandidates ### Description Enable or disable prefetching ICE candidates. Defaults to true. ### Type `boolean` --- ## region ### Description Region to use for the connection. ### Type `string` ``` -------------------------------- ### Set Video Device with Async/Await Source: https://github.com/team-telnyx/webrtc/blob/main/packages/js/docs/ts/classes/Call.md Change the video device (webcam) for the call using `async/await`. The promise resolves when the device is updated. ```js await call.setVideoDevice('abc123'); ``` -------------------------------- ### Get Remote Media Stream Source: https://github.com/team-telnyx/webrtc/blob/main/packages/js/docs/ts/classes/Call.md Retrieve the remote media stream to play in a video or audio element. Ensure the element is ready to receive the stream. ```javascript const stream = call.remoteStream; document.querySelector('audio').srcObject = stream; ``` -------------------------------- ### TSDoc @internalnote Tag Example Source: https://github.com/team-telnyx/webrtc/blob/main/packages/js/README.md Illustrates the use of the '@internalnote' TSDoc tag to add internal comments that should not be rendered in public documentation. This is useful for developer-specific notes. ```typescript /** * @internalnote {@see InternalUseModule} for implementation */ ``` -------------------------------- ### Set Audio Input Device with Async/Await Source: https://github.com/team-telnyx/webrtc/blob/main/packages/js/docs/ts/classes/Call.md Change the audio input device (microphone) for the call using `async/await`. The promise resolves when the device is updated. ```js await call.setAudioInDevice('abc123'); ``` -------------------------------- ### run Source: https://github.com/team-telnyx/webrtc/blob/main/packages/js/docs/ts/classes/PreCallDiagnosis.md Executes the pre-call diagnosis process and returns a comprehensive report. ```APIDOC ## run ### Description Executes the pre-call diagnosis and returns a report. ### Parameters - **options** (PreCallDiagnosisOptions) - Required - The options to use for the diagnosis. ### Response #### Success Response - **Promise** (object) - A promise that resolves with the diagnostic report. ``` -------------------------------- ### Check Browser Permissions (Audio and Video) Source: https://github.com/team-telnyx/webrtc/blob/main/packages/js/docs/ts/classes/TelnyxRTC.md Verify if the browser has the necessary permissions to access the microphone and webcam. This is a prerequisite for initiating calls. ```javascript const client = new TelnyxRTC(options); client.checkPermissions(); ``` -------------------------------- ### WebRTC Configuration Parameters Source: https://github.com/team-telnyx/webrtc/blob/main/packages/js/docs/ts/interfaces/ICallOptions.md This section outlines the available configuration parameters for WebRTC. ```APIDOC ## WebRTC Configuration ### trickleIce #### Description Enable or disable Trickle ICE. #### Parameters ##### Query Parameters - **trickleIce** (boolean) - Optional - Enable or disable Trickle ICE. ### useStereo #### Description Uses stereo audio instead of mono. #### Parameters ##### Query Parameters - **useStereo** (boolean) - Optional - Uses stereo audio instead of mono. ### video #### Description Overrides client's default video constraints. Defaults to `false`. #### Parameters ##### Query Parameters - **video** (boolean) - Optional - Overrides client's default video constraints. ``` -------------------------------- ### Initialize TelnyxRTCProvider Source: https://github.com/team-telnyx/webrtc/blob/main/packages/react-client/README.md Wrap your application with the provider to manage the Telnyx client lifecycle. ```jsx // App.jsx import { TelnyxRTCProvider } from '@telnyx/react-client'; function App() { const credential = { login_token: 'mytoken', }; return ( ); } ``` -------------------------------- ### Remove Event Handler for telnyx.error Source: https://github.com/team-telnyx/webrtc/blob/main/packages/js/docs/ts/classes/TelnyxRTC.md This example shows how to subscribe to the `telnyx.error` event using `.on()` and then remove the specific event handler using `.off()` with the same callback reference. ```javascript const errorHandler = (error) => { // Log the error.. }; const client = new TelnyxRTC(options); client.on('telnyx.error', errorHandler); // .. later client.off('telnyx.error', errorHandler); ``` -------------------------------- ### Set Audio Output Device with Async/Await Source: https://github.com/team-telnyx/webrtc/blob/main/packages/js/docs/ts/classes/Call.md Change the audio output device (speaker) for the call using `async/await`. The promise resolves with a boolean indicating success. ```js await call.setAudioOutDevice('abc123'); ``` -------------------------------- ### Authenticate TelnyxRTC with Username and Password Source: https://github.com/team-telnyx/webrtc/blob/main/packages/js/docs/ts/classes/TelnyxRTC.md Shows how to initialize the TelnyxRTC client using username and password credentials for authentication. ```js const client = new TelnyxRTC({ login: username, password: password, }); ``` -------------------------------- ### Disable ICE Candidate Prefetching Source: https://github.com/team-telnyx/webrtc/blob/main/packages/js/docs/ts/classes/TelnyxRTC.md ICE candidate prefetching is enabled by default for improved call setup performance. To disable it, pass `prefetchIceCandidates: false` to the `newCall` method. ```javascript client.newCall({ destinationNumber: 'xxx', prefetchIceCandidates: false, }); ``` -------------------------------- ### TelnyxRTC.serverDisconnect Source: https://github.com/team-telnyx/webrtc/blob/main/packages/js/docs/ts/classes/TelnyxRTC.md Handles a server-initiated disconnect. This method is called when the server disconnects the client, for example, due to a PUNT message, and it cleans up local calls without sending a BYE message. ```APIDOC ## TelnyxRTC.serverDisconnect ### Description Server-initiated disconnect (e.g. PUNT message). Purges all calls locally without sending BYE — server side may already be gone. ### Returns `Promise` ``` -------------------------------- ### answer Method Source: https://github.com/team-telnyx/webrtc/blob/main/packages/js/docs/ts/classes/Call.md The answer method initiates the process of accepting an incoming call. It can optionally take parameters to configure the answer process. ```APIDOC ### answer ▸ **answer**(`params?`): `Promise` Starts the process to answer the incoming call. #### Parameters | Name | Type | | :------- | :------------- | | `params` | `AnswerParams` | #### Returns `Promise` **`Examples`** ```js call.answer(); ``` #### Inherited from BaseCall.answer ``` -------------------------------- ### Default TelnyxRTC Initialization Source: https://github.com/team-telnyx/webrtc/blob/main/docs/network-connectivity-requirements.md Initializes the TelnyxRTC with default anycast DNS routing to select the nearest datacenter. ```javascript new TelnyxRTC({ login: 'username', password: 'password', }) ``` -------------------------------- ### Accessing Region and Datacenter Information Source: https://github.com/team-telnyx/webrtc/blob/main/packages/js/docs/sw-events.md Use the telnyx.ready event to access the client's region and datacenter after successful registration. ```ts client.on('telnyx.ready', () => { console.log('Region:', client.region); // e.g. "apac", "eu", "us-east" console.log('DC:', client.dc); // e.g. "cn1", "fr5", "at1" }); ``` -------------------------------- ### Initialize and Connect TelnyxRTC Client Source: https://github.com/team-telnyx/webrtc/blob/main/packages/js/docs/ts/classes/TelnyxRTC.md Initializes the TelnyxRTC client with authentication details, attaches event listeners for ready and notification events, and establishes a connection. Disconnect functionality and listener removal are also demonstrated. ```js // Initialize the client const client = new TelnyxRTC({ // Use a JWT to authenticate (recommended) login_token: login_token, // or use your Connection credentials // login: username, // password: password, }); // Attach event listeners client .on('telnyx.ready', () => console.log('ready to call')) .on('telnyx.notification', (notification) => { console.log('notification:', notification); }); // Connect and login client.connect(); // You can call client.disconnect() when you're done. // Note: When you call `client.disconnect()` you need to remove all ON event methods you've had attached before. // Disconnecting and Removing listeners. client.disconnect(); client.off('telnyx.ready'); client.off('telnyx.notification'); ``` -------------------------------- ### Anonymous Login for AI Assistant (Basic) Source: https://github.com/team-telnyx/webrtc/blob/main/packages/js/README.md Authenticate with the TelnyxRTC client using anonymous login for AI assistants. This method allows authentication without a SIP connection and starts a new AI assistant conversation by default. ```javascript const client = new TelnyxRTC({ anonymous_login: { /** Your AI assistant's ID */ target_id: 'assistant-UUID', target_type: 'ai_assistant', }, }); client.connect(); ``` -------------------------------- ### SDK ICE Server URLs for STUN/TURN Source: https://github.com/team-telnyx/webrtc/blob/main/docs/network-connectivity-requirements.md Default production ICE server configuration URLs for the JavaScript SDK, including STUN and TURN servers for NAT traversal and media relay. ```text stun:stun.telnyx.com:3478 stun:stun.l.google.com:19302 turn:turn.telnyx.com:3478?transport=udp turn:turn.telnyx.com:3478?transport=tcp ``` -------------------------------- ### getDeviceResolutions Source: https://github.com/team-telnyx/webrtc/blob/main/packages/js/docs/ts/classes/TelnyxRTC.md Returns the supported resolutions for a given webcam. If no `deviceId` is provided, it defaults to the system's default webcam. Handles cases where the device is not found or multiple devices are present. ```APIDOC ## getDeviceResolutions ### Description Returns supported resolution for the given webcam. ### Method TelnyxRTC ### Parameters #### Path Parameters - **deviceId** (string) - Description: the `deviceId` from your webcam. ### Returns `Promise` ### Examples If `deviceId` is `null`: 1. if `deviceId` is `null` and you don't have a webcam connected to your computer, it will throw an error with the message `"Requested device not found"`. 2. if `deviceId` is `null` and you have one or more webcam connected to your computer, it will return a list of resolutions from the default device set up in your operating system. Using async/await: ```js async function() { const client = new TelnyxRTC(options); let result = await client.getDeviceResolutions(); console.log(result); } ``` Using ES6 `Promises`: ```js client.getDeviceResolutions().then((result) => { console.log(result); }); ``` If `deviceId` is **not** `null`: it will return a list of resolutions from the `deviceId` sent. Using async/await: ```js async function() { const client = new TelnyxRTC(options); let result = await client.getDeviceResolutions(deviceId); console.log(result); } ``` Using ES6 `Promises`: ```js client.getDeviceResolutions(deviceId).then((result) => { console.log(result); }); ``` **Deprecated** ``` -------------------------------- ### Set Custom Headers for a New Call Source: https://github.com/team-telnyx/webrtc/blob/main/packages/js/docs/ts/classes/TelnyxRTC.md Demonstrates how to include custom headers when initiating a new call using the `newCall` method. ```javascript client.newCall({ destinationNumber: '18004377950', callerNumber: '155531234567', customHeaders: [{ name: 'X-Header', value: 'value' }], }); ``` -------------------------------- ### getDevices Source: https://github.com/team-telnyx/webrtc/blob/main/packages/js/docs/ts/classes/TelnyxRTC.md Retrieves a list of all media devices supported by the browser. This includes audio input, audio output, and video devices. ```APIDOC ## getDevices ### Description Returns a list of devices supported by the browser. ### Method TelnyxRTC ### Returns `Promise` ### Examples Using async/await: ```js async function() { const client = new TelnyxRTC(options); let result = await client.getDevices(); console.log(result); } ``` Using ES6 `Promises`: ```js client.getDevices().then((result) => { console.log(result); }); ``` ``` -------------------------------- ### Configure Custom Ringtone and Ringback Source: https://github.com/team-telnyx/webrtc/blob/main/packages/js/docs/ts/classes/TelnyxRTC.md Illustrates initializing the TelnyxRTC client with custom ringtone and ringback audio files. Ensure the 'Generate Ringback Tone' option is disabled in the Telnyx Portal connection settings. ```js const client = new TelnyxRTC({ login_token: login_token, ringtoneFile: './sounds/incoming_call.mp3', ringbackFile: './sounds/ringback_tone.mp3', }); ``` -------------------------------- ### Login with Updated Credentials and Callbacks Source: https://github.com/team-telnyx/webrtc/blob/main/packages/js/docs/ts/classes/TelnyxRTC.md Updates login credentials (username and password) and provides success and error callbacks for the authentication process. This is useful for handling user login flows with immediate feedback. ```javascript await client.login({ creds: { login: 'newuser@example.com', password: 'newpassword', }, onSuccess: () => { console.log('Successfully re-authenticated!'); }, onError: (error) => { console.error('Authentication failed:', error); }, }); ``` -------------------------------- ### getAudioInDevices Source: https://github.com/team-telnyx/webrtc/blob/main/packages/js/docs/ts/classes/TelnyxRTC.md Retrieves a list of audio input devices available to the browser. This method returns a Promise that resolves with an array of `MediaDeviceInfo` objects. ```APIDOC ## getAudioInDevices ### Description Returns the audio input devices supported by the browser. ### Method TelnyxRTC ### Returns `Promise` - Promise with an array of MediaDeviceInfo ### Examples Using async/await: ```js async function() { const client = new TelnyxRTC(options); let result = await client.getAudioInDevices(); console.log(result); } ``` Using ES6 `Promises`: ```js client.getAudioInDevices().then((result) => { console.log(result); }); ``` ``` -------------------------------- ### Run Pre-Call Diagnosis Source: https://github.com/team-telnyx/webrtc/blob/main/packages/js/README.md Initiate a pre-call diagnosis using the `PreCallDiagnosis.run` method. This requires providing credentials and a TeXML application number to assess call readiness. ```javascript import { PreCallDiagnosis } from '@telnyx/webrtc'; PreCallDiagnosis.run({ credentials: { login: clientOptions.login, password: clientOptions.password, loginToken: clientOptions.login_token, }, texMLApplicationNumber: '+1-240-775-8982', }) .then((report) => { console.log(report); }) .catch((error) => { console.error(error); }); ``` -------------------------------- ### IClientOptions Interface Source: https://github.com/team-telnyx/webrtc/blob/main/packages/js/docs/ts/interfaces/IClientOptions.md Defines the configuration options for the WebRTC client. These options allow customization of various aspects of the client's behavior and connection. ```APIDOC ## IClientOptions ### Description Interface for client options. ### Properties #### ringbackFile - **ringbackFile** (string) - Optional - A URL to a wav/mp3 ringback file that will be used when "Generate Ringback Tone" is disabled in your SIP Connection. #### ringtoneFile - **ringtoneFile** (string) - Optional - A URL to a wav/mp3 ringtone file. #### rtcIp - **rtcIp** (string) - Optional - RTC connection IP address to use instead of the default one. Useful when using a custom signaling server. #### rtcPort - **rtcPort** (number) - Optional - RTC connection port to use instead of the default one. Useful when using a custom signaling server. #### skipLastVoiceSdkId - **skipLastVoiceSdkId** (boolean) - Optional - When reconnecting with a stored `voice_sdk_id`, append `?skip_last_voice_sdk_id=true` to the WebSocket URL so VSP routes the connection to a different b2bua-rtc instance instead of sticky-reconnecting to the same one. Useful when retrying after errors caused by stale state on a specific b2bua-rtc node. Defaults to `false`. #### trickleIce - **trickleIce** (boolean) - Optional - Enable or disable Trickle ICE. #### useCanaryRtcServer - **useCanaryRtcServer** (boolean) - Optional - Use Telnyx's Canary RTC server. ``` -------------------------------- ### IClientOptions Configuration Source: https://github.com/team-telnyx/webrtc/blob/main/packages/js/docs/ts/interfaces/IClientOptions.md The IClientOptions interface allows for detailed configuration of the WebRTC client. This includes settings for authentication, call reporting intervals, debugging, network parameters, and media handling. ```APIDOC ## IClientOptions ### Description Configuration options for the WebRTC client. ### Properties #### anonymous_login • `Optional` **anonymous_login**: `Object` anonymous_login login options. #### Type declaration | Name | Type | | :------------------- | :------------------------------------------------------------------------------------------------ | | `target_id` | `string` | | `target_params?` | [`TargetParams`](https://developers.telnyx.com/development/webrtc/js-sdk/interfaces/targetparams) | | `target_type` | `string` | | `target_version_id?` | `string` | #### callReportFlushInterval • `Optional` **callReportFlushInterval**: `number` Interval in milliseconds for submitting intermediate call reports while a call is active. Set to 0 to disable time-based intermediate reports. **`Default`** ```ts 180000 (3 minutes) ``` #### callReportInterval • `Optional` **callReportInterval**: `number` Interval in milliseconds for collecting call statistics after the initial high-resolution startup window. Stats are aggregated over each interval and submitted as intermediate reports while the call is active. **`Default`** ```ts 5000 (5 seconds) ``` #### debug • `Optional` **debug**: `boolean` Enable debug mode for this client. This will gather WebRTC debugging information. #### debugOutput • `Optional` **debugOutput**: "file" | "socket" Debug output option. ``` -------------------------------- ### Connect to WebRTC Server Source: https://github.com/team-telnyx/webrtc/blob/main/packages/js/docs/ts/classes/TelnyxRTC.md Initiates a new connection to the WebRTC server for data exchange. This is a fundamental step before making or receiving calls. ```javascript const client = new TelnyxRTC(options); client.connect(); ``` -------------------------------- ### ICallOptions Interface Source: https://github.com/team-telnyx/webrtc/blob/main/packages/js/docs/ts/interfaces/ICallOptions.md The ICallOptions interface defines the structure for configuring individual WebRTC calls. Each property allows for customization of different aspects of the call. ```APIDOC ## ICallOptions Interface ### Description The `ICallOptions` interface provides a comprehensive set of properties to customize and control WebRTC calls initiated through the Telnyx SDK. These options allow for fine-grained control over media, caller identification, network settings, and Telnyx-specific features. ### Properties #### `audio` (boolean | MediaTrackConstraints) - Optional Overrides client's default audio constraints. Defaults to `true`. #### `callerName` (string) - Optional Name to use as the caller ID name when dialing out to a destination. #### `callerNumber` (string) - Optional Number to use as the caller ID when dialing out to a destination. A valid phone number is required for dials out to PSTN numbers. #### `camId` (string) - Optional `deviceId` to use as webcam. Overrides the client's default one. #### `clientState` (string) - Optional Telnyx's Call Control client_state. Can be used with Connections with Advanced -> Events enabled. `clientState` string should be base64 encoded. #### `customHeaders` (Array<{ name: string; value: string }>) - Optional Add custom headers to the INVITE and ANSWER request. #### `debug` (boolean) - Optional Enable debug mode for this call. #### `debugOutput` ("file" | "socket") - Optional Output debug logs to a file. #### `destinationNumber` (string) - Optional Phone number or SIP URI to dial. #### `forceRelayCandidate` (boolean) - Optional Force the use of a relay ICE candidate. #### `iceServers` (Array) - Optional Overrides client's default `iceServers` to use for certain call. #### `id` (string) - Optional Custom ID to identify the call. This will be used as the `callID` in place of the UUID generated by the client. #### `keepConnectionAliveOnSocketClose` (boolean) - Optional **`Deprecated`** Use only IClientOptions.keepConnectionAliveOnSocketClose By passing `keepConnectionAliveOnSocketClose` as `true`, the SDK will attempt to keep Peer connection alive when the WebSocket connection is closed unexpectedly (e.g. network interruption, device sleep, etc). #### `localElement` (string | HTMLMediaElement) - Optional Overrides client's default `localElement`. #### `localStream` (MediaStream) - Optional If set, the call will use this stream instead of retrieving a new one. #### `mediaSettings` (Object) - Optional Configures media (audio/video) in a call. ##### Type declaration - `sdpASBandwidthKbps?` (number) - `useSdpASBandwidthKbps?` (boolean) #### `micId` (string) - Optional `deviceId` to use as microphone. Overrides the client's default one. #### `onNotification` (Function) - Optional Overrides client's default `telnyx.notification` handler for this call. #### `preferred_codecs` (Array) - Optional Preferred codecs for the call. #### `prefetchIceCandidates` (boolean) - Optional Enable or disable ICE Candidate Prefetching. Defaults to true. #### `remoteElement` (string | HTMLMediaElement) - Optional Overrides client's default `remoteElement`. #### `remoteStream` (MediaStream) - Optional If set, the call will use this stream instead of retrieving a new one. #### `speakerId` (string) - Optional `deviceId` to use as speaker. Overrides the client's default one. #### `telnyxCallControlId` (string) - Optional Telnyx Call Control ID, if using Call Control services. #### `telnyxLegId` (string) - Optional Telnyx call leg ID, if using Call Control services. #### `telnyxSessionId` (string) - Optional Telnyx call session ID, if using Call Control services. #### `trickleIce` (boolean) - Optional Enable or disable trickle ICE. Defaults to true. #### `useStereo` (boolean) - Optional Enable or disable stereo audio. Defaults to false. #### `video` (boolean | MediaTrackConstraints) - Optional Overrides client's default video constraints. Defaults to `true`. ``` -------------------------------- ### getVideoDevices Source: https://github.com/team-telnyx/webrtc/blob/main/packages/js/docs/ts/classes/TelnyxRTC.md Retrieves a list of available media input and output devices (cameras, microphones, speakers). ```APIDOC ## getVideoDevices ### Description Retrieves an array of `MediaDeviceInfo` objects, representing available media devices. ### Returns `Promise` - A promise that resolves with an array of media device information. ### Examples **Using async/await:** ```js async function() { const client = new TelnyxRTC(options); let result = await client.getVideoDevices(); console.log(result); } ``` **Using ES6 Promises:** ```js client.getVideoDevices().then((result) => { console.log(result); }); ``` ``` -------------------------------- ### telnyx.ready Event Source: https://github.com/team-telnyx/webrtc/blob/main/packages/js/docs/sw-events.md The `telnyx.ready` event is emitted when the SDK is authenticated and the gateway reports a `REGED` state. This signifies that the user is ready to place or receive calls. It also provides information about the connected datacenter and region. ```APIDOC ## telnyx.ready Event ### Description Emitted after the server reports `REGISTER` or `REGED` gateway states. This is the canonical signal that the user can place or receive calls. It's also used to reset reconnection timers and hide "connecting" banners. ### Method Event Listener ### Endpoint N/A (Client-side event) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript client.on('telnyx.ready', () => { console.log('Client is ready to make/receive calls.'); console.log('Connected Region:', client.region); console.log('Connected Datacenter:', client.dc); }); ``` ### Response #### Success Response (Event Payload) - **client.region** (string | null) - The region the client is connected to (e.g., "apac", "eu", "us-east"). Null until registration is complete. - **client.dc** (string | null) - The specific datacenter code (e.g., "cn1", "fr5", "ch1"). Null until registration is complete. #### Response Example ```json { "client": { "region": "us-east", "dc": "us1" } } ``` ``` -------------------------------- ### Configure TelnyxRTC with Force Relay Candidate Source: https://github.com/team-telnyx/webrtc/blob/main/docs/network-connectivity-requirements.md Enable TURN over TCP/TLS by setting `forceRelayCandidate: true` when UDP traffic is blocked. This ensures media is relayed through the TURN server. ```javascript new TelnyxRTC({ login: 'username', password: 'password', forceRelayCandidate: true, }) ``` -------------------------------- ### Import webrtc-adapter and TelnyxRTC Source: https://github.com/team-telnyx/webrtc/blob/main/packages/js/README.md Extend browser support for TelnyxRTC by importing 'webrtc-adapter' before the main library. This is useful for ensuring compatibility across a wider range of browsers. ```javascript import 'webrtc-adapter'; import { TelnyxRTC } from '@telnyx/webrtc'; ``` -------------------------------- ### TelnyxRTC Constructor Source: https://github.com/team-telnyx/webrtc/blob/main/packages/js/docs/ts/classes/TelnyxRTC.md Initializes a new TelnyxRTC instance. You can authenticate using a JWT or connection credentials. Custom ringtones and HTML media elements for calls can also be configured. ```APIDOC ## constructor TelnyxRTC ### Description Creates a new `TelnyxRTC` instance with the provided options. ### Parameters #### Parameters - **options** (IClientOptions) - Options for initializing a client ### Examples #### Authenticating with a JSON Web Token: ```javascript const client = new TelnyxRTC({ login_token: login_token, }); ``` #### Authenticating with username and password credentials: ```javascript const client = new TelnyxRTC({ login: username, password: password, }); ``` #### Custom ringtone and ringback Custom ringback and ringtone files can be a wav/mp3 in your local public folder or a file hosted on a CDN, ex: https://cdn.company.com/sounds/call.mp3. To use the `ringbackFile`, make sure the "Generate Ringback Tone" option is **disabled** in your [Telnyx Portal connection](https://portaldev.telnyx.com/#/app/connections) configuration (Inbound tab.) ```javascript const client = new TelnyxRTC({ login_token: login_token, ringtoneFile: './sounds/incoming_call.mp3', ringbackFile: './sounds/ringback_tone.mp3', }); ``` #### To hear/view calls in the browser, you'll need to specify an HTML media element: ```javascript client.remoteElement = 'remoteMedia'; ``` The corresponding HTML: ```html