This is the Changelog for v2 of the Voice JavaScript SDK. Click here to see the v1 Changelog.
If you are upgrading to version 2.3.0 or later and have firewall rules or network configuration that blocks any unknown traffic by default, you need to update your configuration to allow connections to the new DNS names and IP addresses. Please refer to this changelog for more details.
originalError
property is not populated when a general ConnectionError (31005)
happens.chunderw
parameter is not being used during signaling reconnection. Note that this parameter is intended solely for testing purposes.device.connect()
without waiting for the promise to get resolved, then calling device.audio.setInputDevice()
right away results in an AcquisitionFailedError
.The Call Message Events, originally released in 2.2.0, has been promoted to GA. This release includes the following breaking changes.
Call.MessageType
enum to string
.31209
is raised if the payload size of a Call Message Event exceeds the authorized limit. With this release, 31212
is raised instead.PreflightTest
throws an error when RTCIceCandidateStatsReport
is not available. Thanks to @phi-line for your contribution.AcquisitionFailedError
is raised when making a call while a setInputDevice
invocation is still in progress. The following snippet will reproduce the issue in versions <2.11.2:1// Call setInputDevice without waiting for it to resolve e.g. using 'await'2device.audio.setInputDevice(id);34// Calling device.connect immediately raises an AcquisitionFailedError error5device.connect(...);
Fixed an issue where the input stream stops working after changing the default input device. Thanks @varunm0503 for your contribution.
Fixed an echo issue where the audio output is duplicated after the device permission is granted. Thanks @kmteras for your contribution.
In Manifest V2, Chrome Extensions had the capability to run the Voice JS SDK in the background for making calls. However, with the introduction of Manifest V3, running the Voice JS SDK in the background is now possible only through service workers. Service workers lack access to certain features, such as DOM, getUserMedia
, and audio playback, making it impossible to make calls with previous versions of the SDK.
This new release enables the SDK to run in a service worker context, allowing it to listen for incoming calls or initiate outgoing calls. Once a call object is created, it can be forwarded to an offscreen document, where the SDK gains access to all necessary APIs to fully establish and interact with the call. For implementation details, refer to our example.
Previous versions of the SDK supported simultaneous outgoing and incoming calls using different identities. If an incoming call was received while the Device
with the same identity was busy, the active call had to be disconnected before accepting the incoming call. With this SDK release, multiple incoming calls for the same identity can be accepted, muted, or put on hold, without disconnecting any existing active calls. This is achieved by forwarding the incoming call to a different Device
instance. Below are the new APIs and an example for more details.
1// Create a Device instance that handles receiving all incoming calls for the same identity.2const receiverDevice = new Device(token, options);3await receiverDevice.register();45receiverDevice.on('incoming', (call) => {6// Forward this call to a new Device instance using the call.connectToken string.7forwardCall(call.connectToken);8});910// The forwardCall function may look something like the following.11async function forwardCall(connectToken) {12// For each incoming call, create a new Device instance for interaction13// without affecting other calls.14// IMPORTANT: The token for this new Device needs to have the same identity15// as the token used in the receiverDevice.16const device = new Device(token, options);17const call = await device.connect({ connectToken });1819// Destroy the Device after the call is completed20call.on('disconnect', () => device.destroy());21}
device.register()
does not return a promise rejection when the WebSocket fails to connect. Thank you @kamalbennani for your contribution.Device.Options.logLevel
is only accepting a number
type. With this release, strings
are now also allowed. See Device.Options.logLevel for a list of possible values.call.mute()
does not have an effect while the call.status()
is either ringing
or connecting
. Thank you @zyzmoz for your contribution.The SDK now includes Audio Processor APIs, enabling access to raw audio input and the ability to modify audio data before sending it to Twilio. With this new feature, the following use cases can now be achieved on the client side:
Please visit this page for more details about the Audio Processor APIs.
Added a new feature flag enableImprovedSignalingErrorPrecision
to enhance the precision of errors emitted by Device
and Call
objects.
1const token = ...;2const device = new Device(token, {3enableImprovedSignalingErrorPrecision: true,4});
The default value of this option is false
.
When this flag is enabled, some errors that would have been described with a generic error code are now described with a more precise error code. With this feature, the following errors now have their own error codes. Please see this page for more details about each error.
Device Error Changes
1const device = new Device(token, {2enableImprovedSignalingErrorPrecision: true,3});4device.on('error', (deviceError) => {5// the following table describes how deviceError will change with this feature flag6});
Device Error Name | Device Error Code with Feature Flag Enabled | Device Error Code with Feature Flag Disabled |
---|---|---|
GeneralErrors.ApplicationNotFoundError | 31001 | 53000 |
GeneralErrors.ConnectionDeclinedError | 31002 | 53000 |
GeneralErrors.ConnectionTimeoutError | 31003 | 53000 |
MalformedRequestErrors.MissingParameterArrayError | 31101 | 53000 |
MalformedRequestErrors.AuthorizationTokenMissingError | 31102 | 53000 |
MalformedRequestErrors.MaxParameterLengthExceededError | 31103 | 53000 |
MalformedRequestErrors.InvalidBridgeTokenError | 31104 | 53000 |
MalformedRequestErrors.InvalidClientNameError | 31105 | 53000 |
MalformedRequestErrors.ReconnectParameterInvalidError | 31107 | 53000 |
SignatureValidationErrors.AccessTokenSignatureValidationFailed | 31202 | 53000 |
AuthorizationErrors.NoValidAccountError | 31203 | 53000 |
AuthorizationErrors.JWTTokenExpirationTooLongError | 31207 | 53000 |
ClientErrors.NotFound | 31404 | 53000 |
ClientErrors.TemporarilyUnavilable | 31480 | 53000 |
ClientErrors.BusyHere | 31486 | 53000 |
SIPServerErrors.Decline | 31603 | 53000 |
Call Error Changes
1const device = new Device(token, {2enableImprovedSignalingErrorPrecision: true,3});4const call = device.connect(...);5call.on('error', (callError) => {6// the following table describes how callError will change with this feature flag7});
Call Error Name | Call Error Code with Feature Flag Enabled | Call Error Code with Feature Flag Disabled |
---|---|---|
GeneralErrors.ConnectionDeclinedError | 31002 | 31005 |
AuthorizationErrors.InvalidJWTTokenError | 31204 | 31005 |
AuthorizationErrors.JWTTokenExpiredError | 31205 | 31005 |
IMPORTANT: If your application logic currently relies on listening to the
generic error code 53000
or 31005
, and you opt into enabling the feature
flag, then your application logic needs to be updated to anticipate the new error code when any of the above errors happen.
Updated November 1, 2023
We have identified an issue on Chromium-based browsers running on MacOS 14 (Sonoma) where the audio deteriorates during a call. This issue happens due to the excessive calls to MediaDevices: enumerateDevices() API. With this release, the SDK calls this API only when necessary to avoid audio deterioration.
call.on('ringing', handler)
call.on('warning', handler)
call.on('warning-cleared', handler)
device.on('destroyed', handler)
call.sendMessage()
API throws an error if the SDK is imported as an ECMAScript Module (ESM) using the @twilio/voice-sdk/esm
path.Currently, the SDK is imported as a CommonJS Module (CJS) using the root path @twilio/voice-sdk
. With this release, the SDK contains an experimental feature that allows it to be imported as an ECMAScript Module (ESM) using the @twilio/voice-sdk/esm
path. As this is an experimental feature, some frameworks using bundlers like Vite
and Rollup
may not work. Full support for ESM will be available in a future release and will become the default import behavior of the SDK.
Example:
import { Device } from '@twilio/voice-sdk/esm';
npm audit
.device.updateOptions
would reset the device.audio._enabledSounds
state.1const device = new Device(token, {2sounds: {3dtmf8: 'http://mysite.com/8_button.mp3',4// Other custom sounds5},6// Other options7});
--legacy-peer-deps
flag.ws
package has been moved to devDependencies
.xmlhttprequest
npm package.Updated: This is now GA as of December 14, 2023
The SDK now allows you to override WebRTC APIs using the following options and events. If your environment supports WebRTC redirection, such as Citrix HDX's WebRTC redirection technologies, your application can use this new beta feature for improved audio quality in those environments.
Updated the description of Device.updateToken API. It is recommended to call this API after Device.tokenWillExpireEvent is emitted, and before or after a call to prevent a potential ~1s audio loss during the update process.
Updated stats reporting to stop using deprecated RTCIceCandidateStats
- ip
and deleted
.
Fixed an issue where a TypeError
is thrown after rejecting a call then invoking updateToken
.
Fixed an issue (#87, #145) where the PeerConnection
object is not properly disposed.
Fixed an issue where device.audio.disconnect
, device.audio.incoming
and device.audio.outgoing
do not have the correct type definitions.
Fixed an issue where the internal deviceinfochange
event is being emitted indefinitely, causing high cpu usage.
This release includes updated DNS names for Twilio Edge Locations. The Voice JS SDK uses these Edge Locations to connect to Twilio's infrastructure via the parameter Device.Options.edge
. The current usage of this parameter does not change as the SDK automatically maps the edge value to the new DNS names.
Additionally, you need to update your Content Security Policies (CSP) if you have it enabled for your application. You also need to update your network configuration such as firewalls, if necessary, to allow connections to the new DNS names and IP addresses.
The SDK can now send and receive custom messages to and from Twilio's backend via the following new Call
APIs.
Please visit this page for more details about this feature. Additionally, please see the following for more information on how to send and receive messages on the server.
NOTE: This feature should not be used with PII.
Example
1const device = new Device(token, options);23const setupCallHandlers = call => {4call.on('messageReceived', message => messageReceivedHandler(message));5call.on('messageSent', message => messageSentHandler(message));6};78// For outgoing calls9const call = await device.connect();10setupCallHandlers(call);1112// For incoming calls13device.on('incoming', call => setupCallHandlers(call));14await device.register();1516// For sending a message17const eventSid = call.sendMessage({18content: { foo: 'foo' },19messageType: Call.MessageType.UserDefinedMessage,20});
device.updateOptions
.The Voice JavaScript SDK now fully supports Call reconnection. If the media connection or signaling websocket is lost, the SDK is able to attempt to reconnect the Call. A Call can now potentially be recovered up to 30 seconds after a media or signaling connection loss.
The Twilio.Device
will emit a 'reconnecting' event when a connectivity loss occurs, and a 'reconnected' event upon successful reconnection.
There exists a limitation such that Signaling Reconnection and Edge Fallback are mutually exclusive. To opt-in to the Signaling Reconnection feature, a new option can be passed to the SDK: maxCallSignalingTimeoutMs
. If this value is not present in the options object passed to the Device
constructor, the default value will be 0
. Reconnection can only happen with an up-to-date AccessToken.
Customers relying on edge fallback, along with a small subset of customers using the 'roaming'
edge, will not automatically benefit from this feature without additional configuration. Go to the Edge Locations page for more information.
The Voice JavaScript SDK now provides two additional features to help keep your AccessTokens up to date:
'tokenWillExpire'
event, which will be emitted by the Twilio.Device before its associated AccessToken is set to expire. By default, it will be emitted 10 seconds before the AccessToken's expiration.DeviceOptions.tokenRefreshMs
property that can configure the timing of the 'tokenWillExpire'
event.You can use these new features in conjunction with the device.updateToken()
method to automatically keep an AccessToken up to date.
In the following example, the 'tokenWillExpire'
event will be emitted 30 seconds (3000 milliseconds) before the AccessToken is set to expire, and the event listener for the 'tokenWillExpire'
event will retrieve a new AccessToken and update the Device's AccessToken with the device.updateToken()
method.
1const device = new Device(token, {2// 'tokenWillExpire' event will be emitted 30 seconds before the AccessToken expires3tokenRefreshMs: 30000,4});56device.on('tokenWillExpire', () => {7return getTokenViaAjax().then(token => dev.updateToken(token));8});
The Twilio Voice JavaScript SDK now supports Twilio Regions.
If you are part of the Twilio Regions Pilot and wish to specify a home region when using the Voice JavaScript SDK, you will need to:
Twilio.Device
.Below is an example of how you would use the Node.js Helper Library to create AccessTokens for the Voice JavaScript SDK for a Region.
1const accessToken = const accessToken = new twilio.jwt.AccessToken(2credentials.accountSid,3credentials.apiKeySid,4credentials.apiKeySecret, {5identity,6ttl,7region: 'au1',8},9);1011const grant = new VoiceGrant({12outgoingApplicationSid: credentials.twimlAppSid,13incomingAllow: true,14});1516accessToken.addGrant(grant);
Note: The API Key and Secret above must be created within the au1
region. It's recommended that the TwiML App used in the Voice Grant is also created in the same Region.
The example below shows how to pass the au1
-related edge location to the Twilio.Device
constructor.
1const device = new Device(accessToken, {2edge: 'sydney',3});
The new Twilio.Device.home
accessor will return a string value of the home region of the device instance, given that it successfully connected with Twilio.
Existing EU customers can now migrate their Voice use-cases to the data center in Ireland to establish data residency within the region. In addition, new customers may now select Ireland as their region of choice for Voice related use cases. There is no additional cost to use the new data center in Ireland. To learn more about Regional Voice in Ireland, check out our blog post or head over to our Global Infrastructure docs to get started.
The Voice JavaScript SDK now exposes a Twilio.Device.identity
accessor.
Given that a Twilio.Device
has registered successfully with Twilio, the Twilio.Device.identity
accessor will return a read-only string containing the identity
that was passed to the AccessToken used to instantiate the Twilio.Device
.
ws
version to fix a potential security vulnerabilityTwilio.Device.destroy()
Device must now be instantiated before it can be used. Calling Device.setup()
will no longer
work; instead, a new Device
must be instantiated via new Device(token, options?)
.
As Connection is an overloaded and ambiguous term, the class has been renamed Call to better indicate what the object represents and be more consistent with Mobile SDKs and our REST APIs.
Device.setup()
has been removed, and new Device(...)
will not automatically begin
connecting to signaling. There is no need to listen for Device.on('ready')
. Instead,
the signaling connection will automatically be acquired in one of two scenarios:
Device.connect()
, creating an outbound Call. In this case,
the state of the signaling connection will be represented in the Call.Device.register()
, which will register the client to listen
for incoming calls at the identity specified in the AccessToken.As long as outgoing calls are expected to be made, or incoming calls are expected to be received,
the token supplied to Device
should be fresh and not expired. This can be done by setting a
timer in the application to call updateToken
with the new token shortly before the prior
token expires. This is important, because signaling connection is lazy loaded and will fail if
the token is not valid at the time of creation.
Example:
1const TTL = 600000; // Assuming our endpoint issues tokens for 600 seconds (10 minutes)2const REFRESH_TIMER = TTL - 30000; // We update our token 30 seconds before expiration;3const interval = setInterval(async () => {4const newToken = await getNewTokenViaAjax();5device.updateToken(newToken);6}, REFRESH_TIMER);
The Device states have changed. The states were: [Ready, Busy, Offline]
. These
have been changed to more accurately and clearly represent the states of the
Device. There are two changes to Device state:
[Registered, Registering, Unregistered, Destroyed]
. This
removes the idea of "Busy" from the state, as technically the Device can have an active
Call whether it is registered or not, depending on the use case. The Device will always
start as Unregistered
. In this state, it can still make outbound Calls. Once Device.register()
has been called, this state will change to Registering
and finally Registered
. If
Device.unregister()
is called the state will revert to Unregistered
. If the signaling
connection is lost, the state will transition to Registering
or `Unregistered' depending
on whether or not the connection can be re-established.The destroyed
state represents a Device
that has been "destroyed" by calling
Device.destroy
. The device should be considered unusable at this point and a
new one should be constructed for further use.
Device.isBusy
. This is a very basic
shortcut for the logic return !!device.activeConnection
.The events emitted by the Device
are represented by the Device.EventName
enum and represent the new Device states:
1export enum EventName {2Destroyed = 'destroyed',3Error = 'error',4Incoming = 'incoming',5Unregistered = 'unregistered',6Registering = 'registering',7Registered = 'registered',8}
Note that unregistered
, registering
, and registered
have replaced
offline
and ready
. Although frequently used to represent connected or disconnected,
ready
and offline
actually were meant to represent registered
and unregistered
,
which was quite ambiguous and a primary reason for the change.
When the device is destroyed using Device.destroy
, a "destroyed"
event will
be emitted.
The construction signature and usage of Device
has changed. These are the new API signatures:
1/**2* Create a new Device. This is synchronous and will not open a signaling socket immediately.3*/4new Device(token: string, options?: Device.Options): Device;56/**7* Promise resolves when the Device has successfully registered.8* Replaces Device.registerPresence()9* Can reject if the Device is unusable, i.e. "destroyed".10*/11async Device.register(): Promise<void>;12/**13* Promise resolves when the Device has successfully unregistered.14* Replaces Device.unregisterPresence()15* Can reject if the Device is unusable, i.e. "destroyed".16*/17async Device.unregister(): Promise<void>;18/**19* Promise resolves when signaling is established and a Call has been created.20* Can reject if the Device is unusable, i.e. "destroyed".21*/22async Device.connect(options?: Device.ConnectOptions): Promise<Call>;
1const device = new Device(token, { edge: 'ashburn' });23device.on(Device.EventName.Incoming, call => { /* use `call` here */ });4await device.register();
1const device = new Device(token, { edge: 'ashburn' });2const call = await device.connect({ To: 'alice' });
The arguments for Device.connect()
and Call.accept()
have been standardized
to the following options objects:
1interface Call.AcceptOptions {2/**3* An RTCConfiguration to pass to the RTCPeerConnection constructor.4*/5rtcConfiguration?: RTCConfiguration;67/**8* MediaStreamConstraints to pass to getUserMedia when making or accepting a Call.9*/10rtcConstraints?: MediaStreamConstraints;11}
1interface Device.ConnectOptions extends Call.AcceptOptions {2/**3* A flat object containing key\:value pairs to be sent to the TwiML app.4*/5params?: Record<string, string>;6}
Note that these now take a MediaStreamConstraints rather than just the audio constraints. For example:
device.connect({ To: 'client:alice' }, { deviceId: 'default' });
might be re-written as:
1device.connect({2params: { To: 'client:alice' },3rtcConstraints: { audio: { deviceId: 'default' } },4});
For backward compatibility, the new error format was attached to the old format under error.twilioError
:
1class oldError extends Error {2//...3code: number;4message: string;5twilioError: TwilioError;6}
The new Error format is:
1class TwilioError extends Error {2/**3* A list of possible causes for the Error.4*/5causes: string[];67/**8* The numerical code associated with this Error.9*/10code: number;1112/**13* A description of what the Error means.14*/15description: string;1617/**18* An explanation of when the Error may be observed.19*/20explanation: string;2122/**23* Any further information discovered and passed along at run-time.24*/25message: string;2627/**28* The name of this Error.29*/30name: string;3132/**33* The original Error received from the external system, if any.34*/35originalError?: Error;3637/**38* A list of potential solutions for the Error.39*/40solutions: string[];41}
With the transition, the following error codes have changed:
Previously, Device.setup()
could only be used the set options once. Now, we've added
Device.updateOptions(options: Device.Options)
which will allow changing
the Device options without instantiating a new Device. Note that the edge
cannot be changed
during an active Call.
Example usage:
1const options = { edge: 'ashburn' };2const device = new Device(token, options);34// Later...56device.updateOptions({ allowIncomingWhileBusy: true });
The resulting (non-default) options would now be:
1{2allowIncomingWhileBusy: true,3edge: 'ashburn',4}
This function will throw with an InvalidStateError
if the Device has been
destroyed beforehand.
The SDK now uses the loglevel
module. This exposes
several new features for the SDK, including the ability to intercept log messages with custom
handlers and the ability to set logging levels after instantiating a Device
. To get an instance
of the loglevel
Logger
class used internally by the SDK:
1import { Logger as TwilioClientLogger } from '@twilio/voice-client-sdk';2...3TwilioClientLogger.setLogLevel('DEBUG');
Please see the original loglevel
project for more
documentation on usage.
Connection.mediaStream
. To access the MediaStreams, use Connection.getRemoteStream()
and Connection.getLocalStream()
Connection.message
in favor of the newer Connection.customParameters
. Where .message
was an Object, .customParameters
is a Map
.Connection.options
Connection.pstream
Connection.sendHangup
Connection.on('cancel')
logic so that we no longer emit cancel
in response to Connection.ignore()
.Some deprecated Device
options have been removed. This includes:
enableIceRestart
enableRingingState
fakeLocalDtmf
The above three removed options are now assumed true
. The new Device.Options
interface is now:
1export interface Options {2allowIncomingWhileBusy?: boolean;3appName?: string;4appVersion?: string;5audioConstraints?: MediaTrackConstraints | boolean;6closeProtection?: boolean | string;7codecPreferences?: Connection.Codec[];8disableAudioContextSounds?: boolean;9dscp?: boolean;10edge?: string[] | string;11forceAggressiveIceNomination?: boolean;12maxAverageBitrate?: number;13rtcConfiguration?: RTCConfiguration;14sounds?: Partial<Record<Device.SoundName, string>>;15}
The formula used to calculate the mean-opinion score (MOS) has been fixed for extreme network conditions. These fixes will not affect scores for nominal network conditions.