Element API
@avaya/infinity-elements-api v1.2.0
ElementAPI
ElementAPI - Main API for web components to interact with the Infinity Extensibility Framework
This is the primary interface that elements use to communicate with core-agent-ui.
Uses window.postMessage for API requests/responses and events.
Sandboxed Iframe Environment
IMPORTANT: Elements run in sandboxed iframes using srcdoc, which means:
window.location.originreturns"null"(the literal string "null")document.referrermay be empty- Direct access to parent window properties is blocked
- BroadcastChannel doesn't work (requires valid origin for message scoping)
All communication with the host (core-agent-ui) must go through window.postMessage.
The host has a valid origin and can make HTTP requests, handle OAuth, etc.
The methods are organized into four API families:
- Interaction API Family - Controls and monitors customer interactions throughout their lifecycle. Initiate new voice and chat interactions, execute controls (transfer, consult, conference), and subscribe to interaction events.
- Media API Family - Manages channel-specific capabilities including DTMF tones on voice channels and rich text messages with formatting and attachments.
- Agent API Family - Manages agent presence and availability. Modify agent state and subscribe to state change notifications.
- Admin API Family - Provides environmental and configuration data including logged-in agent context, users, queues, and reason codes.
Examples
import { ElementAPI } from '@avaya/infinity-elements-api';
const api = new ElementAPI({
elementId: 'my-element',
timeout: 5000,
debug: true
});const userInfo = await api.getUserInfo();
console.log('Agent name:', userInfo.firstName, userInfo.lastName);
console.log('Email:', userInfo.email);api.onInteractionAccepted((interactionId) => {
console.log('Interaction accepted:', interactionId);
});
api.onInteractionEnded((interactionId) => {
console.log('Interaction ended:', interactionId);
});Constructors
Constructor
new ElementAPI(options?: ElementAPIOptions): ElementAPI;Creates a new ElementAPI instance
Parameters
| Parameter | Type |
|---|---|
| options | ElementAPIOptions |
Returns
ElementAPI
Example
const api = new ElementAPI({
elementId: 'my-custom-element',
timeout: 10000,
debug: true
});Interaction API Family
getInteraction()
getInteraction(options?: InteractionContextOptions): Promise<InteractionInfo>;Get information about the current active interaction
Parameters
| Parameter | Type | Description |
|---|---|---|
| options? | InteractionContextOptions | Optional parameters |
| options.interactionId? | string | Optional interaction ID (required for app-level widgets, auto-provided for interaction-level widgets) |
Returns
Promise<InteractionInfo>
Promise resolving to the interaction information
Throws
Error if no active interaction exists
Examples
// Interaction-level widget (no interactionId needed)
try {
const interaction = await api.getInteraction();
console.log('Interaction ID:', interaction.interactionId);
console.log('Customer:', interaction.customer?.name);
console.log('Status:', interaction.status);
} catch (error) {
console.error('No active interaction');
}// App-level widget (interactionId required)
const interaction = await api.getInteraction({ interactionId: 'int-123' });
console.log('Status:', interaction.status);getUserInteractions()
getUserInteractions(params?: GetUserInteractionsParams): Promise<GetUserInteractionsResponse>;Get user interactions including owned and viewing interactions
Retrieves all active interactions for the current or specified user,
including interactions they own and ones they are viewing.
Optionally includes queue and user details.
Parameters
| Parameter | Type | Description |
|---|---|---|
| params? | GetUserInteractionsParams | Optional parameters |
| params.userId? | string | User ID to get interactions for (defaults to current user) |
| params.details? | boolean | Include queue and user details (defaults to true) |
Returns
Promise<GetUserInteractionsResponse>
Promise resolving to user interactions data
Examples
// Get current user's interactions with full details
const result = await api.getUserInteractions({ details: true });
console.log('Owned interactions:', result.interactions);
console.log('Viewing interactions:', result.viewing);
console.log('Logged in queues:', result.queue.loggedIn);// Get interactions without queue/user details for better performance
const result = await api.getUserInteractions({ details: false });
const totalCount = result.interactions.length + result.viewing.length;
console.log('Total active interactions:', totalCount);viewerRemoveInteraction()
viewerRemoveInteraction(options?: InteractionContextOptions): Promise<{ message: string }>;Remove the current interaction from the viewer
Parameters
| Parameter | Type | Description |
|---|---|---|
| options? | InteractionContextOptions | Optional parameters |
| options.interactionId? | string | Optional interaction ID (required for app-level widgets, auto-provided for interaction-level widgets) |
Returns
Promise<{`message`: `string`}>
Promise resolving to a success message
Examples
// Interaction-level widget
await api.viewerRemoveInteraction();// App-level widget
await api.viewerRemoveInteraction({ interactionId: 'int-123' });endInteraction()
endInteraction(options?: InteractionContextOptions): Promise<{ message: string }>;End the current interaction
Terminates the active interaction and disconnects the call.
Parameters
| Parameter | Type | Description |
|---|---|---|
| options? | InteractionContextOptions | Optional parameters |
| options.interactionId? | string | Optional interaction ID (required for app-level widgets, auto-provided for interaction-level widgets) |
Returns
Promise<{`message`: `string`}>
Promise resolving to a success message
Examples
// Interaction-level widget
await api.endInteraction();
console.log('Interaction ended');// App-level widget
await api.endInteraction({ interactionId: 'int-123' });startVoiceCall()
startVoiceCall(options?: InteractionContextOptions): Promise<{ message: string }>;Start a voice call for the current interaction
Parameters
| Parameter | Type | Description |
|---|---|---|
| options? | InteractionContextOptions | Optional parameters |
| options.interactionId? | string | Optional interaction ID (required for app-level widgets, auto-provided for interaction-level widgets) |
Returns
Promise<{`message`: `string`}>
Promise resolving to a success message
Examples
// Interaction-level widget
await api.startVoiceCall();// App-level widget
await api.startVoiceCall({ interactionId: 'int-123' });createVoiceInteraction()
createVoiceInteraction(params: CreateVoiceInteractionParams): Promise<{ message: string }>;Create a new voice interaction with a Queue ID and Phone Number
Creates a new outbound voice call interaction to the specified phone number
and assigns it to the specified queue.
Parameters
| Parameter | Type | Description |
|---|---|---|
| params | CreateVoiceInteractionParams | Voice interaction parameters |
Returns
Promise<{`message`: `string`}>
Promise resolving to a success message
Example
await api.createVoiceInteraction({
phoneNumber: '+1234567890',
queueId: '003'
});completeBlindTransfer()
completeBlindTransfer(options: BlindTransferOptions): Promise<boolean>;Complete a blind transfer
Transfers the call to another agent or number without consultation.
Parameters
| Parameter | Type | Description |
|---|---|---|
| options | BlindTransferOptions | Transfer configuration |
Returns
Promise<boolean>
Promise resolving to true if successful
Example
const interaction = await api.getInteraction();
await api.completeBlindTransfer({
interactionId: interaction.interactionId,
transferTo: '[email protected]',
transferToName: 'John Doe',
transferCallerIdType: 'internal'
});singleStepTransfer()
singleStepTransfer(params: SingleStepTransferParams): Promise<{ message: string }>;Perform a single-step transfer
Transfers the interaction directly to the specified target.
Parameters
| Parameter | Type | Description |
|---|---|---|
| params | SingleStepTransferParams | Transfer parameters |
Returns
Promise<{`message`: `string`}>
Promise resolving to a success message
Examples
// Interaction-level widget (no interactionId needed)
await api.singleStepTransfer({
targetId: 'user123',
targetName: 'Support Team'
});// App-level widget (interactionId required)
await api.singleStepTransfer({
targetId: 'queue-456',
targetName: 'Sales Queue',
interactionId: 'int-123'
});consultCall()
consultCall(options: ConsultCallOptions): Promise<{ message: string }>;Initiate a consult call
Starts a consultation with another agent, phone number, or queue while keeping
the original caller on hold.
Parameters
| Parameter | Type | Description |
|---|---|---|
| options | ConsultCallOptions | Consult call configuration |
Returns
Promise<{`message`: `string`}>
Promise resolving to a success message
Examples
// Consult with agent
const interaction = await api.getInteraction();
await api.consultCall({
interactionId: interaction.interactionId,
transferTo: '[email protected]'
});// Consult with phone number
await api.consultCall({
interactionId: interaction.interactionId,
phoneNumber: '+1234567890'
});// Consult with queue
const queues = await api.getTransferQueuesInteraction();
const targetQueue = queues.find(q => q.name === 'Support Queue');
await api.consultCall({
interactionId: interaction.interactionId,
queueId: targetQueue.id
});completeAttendedTransfer()
completeAttendedTransfer(options?: InteractionContextOptions): Promise<{ message: string }>;Complete an attended transfer
Finalizes the attended transfer after consulting with the target party.
Parameters
| Parameter | Type | Description |
|---|---|---|
| options? | InteractionContextOptions | Optional parameters |
| options.interactionId? | string | Optional interaction ID (required for app-level widgets, auto-provided for interaction-level widgets) |
Returns
Promise<{`message`: `string`}>
Promise resolving to a success message
Examples
// Interaction-level widget
await api.completeAttendedTransfer();// App-level widget
await api.completeAttendedTransfer({ interactionId: 'int-123' });completeConference()
completeConference(options?: InteractionContextOptions): Promise<{ message: string }>;Complete the interaction as a conference
Merges all parties into a conference call instead of completing a transfer.
Parameters
| Parameter | Type | Description |
|---|---|---|
| options? | InteractionContextOptions | Optional parameters |
| options.interactionId? | string | Optional interaction ID (required for app-level widgets, auto-provided for interaction-level widgets) |
Returns
Promise<{`message`: `string`}>
Promise resolving to a success message
Examples
// Interaction-level widget — after consulting
await api.completeConference();// App-level widget
await api.completeConference({ interactionId: 'int-123' });attendedTransferWarm()
attendedTransferWarm(options?: InteractionContextOptions): Promise<{ message: string }>;Perform a warm attended transfer
Introduces the caller to the transfer target before completing the transfer.
Parameters
| Parameter | Type | Description |
|---|---|---|
| options? | InteractionContextOptions | Optional parameters |
| options.interactionId? | string | Optional interaction ID (required for app-level widgets, auto-provided for interaction-level widgets) |
Returns
Promise<{`message`: `string`}>
Promise resolving to a success message
Examples
// Interaction-level widget
await api.attendedTransferWarm();// App-level widget
await api.attendedTransferWarm({ interactionId: 'int-123' });attendedTransferCancel()
attendedTransferCancel(options?: InteractionContextOptions): Promise<{ message: string }>;Cancel an attended transfer
Cancels the ongoing attended transfer and returns to the original call.
Parameters
| Parameter | Type | Description |
|---|---|---|
| options? | InteractionContextOptions | Optional parameters |
| options.interactionId? | string | Optional interaction ID (required for app-level widgets, auto-provided for interaction-level widgets) |
Returns
Promise<{`message`: `string`}>
Promise resolving to a success message
Examples
// Interaction-level widget
await api.attendedTransferCancel();// App-level widget
await api.attendedTransferCancel({ interactionId: 'int-123' });acceptInteraction()
acceptInteraction(options?: InteractionContextOptions): Promise<{ message: string }>;Accept an incoming interaction
Accepts a queued or alerting interaction.
Parameters
| Parameter | Type | Description |
|---|---|---|
| options? | InteractionContextOptions | Optional parameters |
| options.interactionId? | string | Optional interaction ID (required for app-level widgets, auto-provided for interaction-level widgets) |
Returns
Promise<{`message`: `string`}>
Promise resolving to a success message
Examples
// Interaction-level widget
api.onInteractionAccepted(async (interactionId) => {
console.log('New interaction:', interactionId);
});
await api.acceptInteraction();// App-level widget
await api.acceptInteraction({ interactionId: 'int-123' });onInteractionStatusChanged()
onInteractionStatusChanged(callback: InteractionStatusChangedCallback): () => void;Subscribe to interaction status changes
Fires when the status of an interaction changes (e.g., alerting, connected, held)
Parameters
| Parameter | Type | Description |
|---|---|---|
| callback | InteractionStatusChangedCallback | Function to call when interaction status changes |
Returns
Unsubscribe function () => void
Example
const unsubscribe = api.onInteractionStatusChanged(({ interactionId, status }) => {
console.log(`Interaction ${interactionId} status changed to ${status}`);
});
// Later, to unsubscribe:
unsubscribe();onInteractionAccepted()
onInteractionAccepted(callback: InteractionAcceptedCallback): () => void;Subscribe to interaction accepted events
Fires when an agent accepts an incoming interaction
Parameters
| Parameter | Type | Description |
|---|---|---|
| callback | InteractionAcceptedCallback | Function to call when an interaction is accepted |
Returns
Unsubscribe function () => void
Example
api.onInteractionAccepted((interactionId) => {
console.log('Accepted interaction:', interactionId);
// Load customer data, show interaction UI, etc.
});onInteractionEnded()
onInteractionEnded(callback: InteractionEndedCallback): () => void;Subscribe to interaction ended events
Fires when an interaction is ended or disconnected
Parameters
| Parameter | Type | Description |
|---|---|---|
| callback | InteractionEndedCallback | Function to call when an interaction ends |
Returns
Unsubscribe function () => void
Example
api.onInteractionEnded((interactionId) => {
console.log('Interaction ended:', interactionId);
// Clean up UI, save data, etc.
});onInteractionUpdated()
onInteractionUpdated(callback: InteractionUpdatedCallback): () => void;Subscribe to interaction updated events
Fires when an interaction is updated with new information
Parameters
| Parameter | Type | Description |
|---|---|---|
| callback | InteractionUpdatedCallback | Function to call when an interaction is updated |
Returns
Unsubscribe function () => void
Example
api.onInteractionUpdated(({ interactionId, payload }) => {
console.log('Interaction updated:', interactionId);
console.log('New data:', payload);
});onConsultStatusChanged()
onConsultStatusChanged(callback: ConsultStatusChangedCallback): () => void;Subscribe to consult status changes
Fires when the status of a consultation changes
Parameters
| Parameter | Type | Description |
|---|---|---|
| callback | ConsultStatusChangedCallback | Function to call when consult status changes |
Returns
Unsubscribe function () => void
Example
api.onConsultStatusChanged(({ interactionId, consultStatus, consultParty }) => {
console.log(`Consult ${consultStatus} with ${consultParty}`);
});onCompleteAsConference()
onCompleteAsConference(callback: CompleteAsConferenceCallback): () => void;Subscribe to complete as conference events
Fires when an interaction is completed as a conference
Parameters
| Parameter | Type | Description |
|---|---|---|
| callback | CompleteAsConferenceCallback | Function to call when an interaction is completed as a conference |
Returns
Unsubscribe function () => void
Example
api.onCompleteAsConference(({ interactionId }) => {
console.log(`Interaction ${interactionId} completed as conference`);
});Media API Family
sendDialpadDigit()
sendDialpadDigit(
digit: DialpadDigit,
audioOutputDeviceId: string | null,
noSendDialTone: boolean,
audioContextOverride?: "standard" | "webkit" | "none",
options?: InteractionContextOptions
): Promise<{ message: string }>;Send a DTMF dialpad digit during a call
Parameters
| Parameter | Type | Description |
|---|---|---|
| digit | DialpadDigit | The dialpad digit to send (0-9) |
| audioOutputDeviceId | string | null | Audio output device ID or null for default |
| noSendDialTone | boolean | Whether to suppress the dial tone sound |
| audioContextOverride? | "standard" | "webkit" | "none" | Audio context type override |
| options? | InteractionContextOptions | Optional parameters |
| options.interactionId? | string | Optional interaction ID (required for app-level widgets, auto-provided for interaction-level widgets) |
Returns
Promise<{`message`: `string`}>
Promise resolving to a success message
Examples
// Interaction-level widget
import { DialpadDigit } from '@avaya/infinity-elements-api';
await api.sendDialpadDigit(
DialpadDigit.One,
null,
false
);// App-level widget
await api.sendDialpadDigit(
DialpadDigit.One,
null,
false,
undefined,
{ interactionId: 'int-123' }
);insertTextIntoFeedInput()
insertTextIntoFeedInput(
text: string,
options?: InteractionContextOptions
): Promise<{ message: string }>;Insert text into the chat feed input field
Parameters
| Parameter | Type | Description |
|---|---|---|
| text | string | The text to insert |
| options? | InteractionContextOptions | Optional parameters |
| options.interactionId? | string | Optional interaction ID (required for app-level widgets, auto-provided for interaction-level widgets) |
Returns
Promise<{`message`: `string`}>
Promise resolving to a success message
Examples
// Interaction-level widget
await api.insertTextIntoFeedInput('Hello, how can I help you today?');// App-level widget
await api.insertTextIntoFeedInput('Hello!', { interactionId: 'int-123' });sendRichMediaMessage()
sendRichMediaMessage(options: SendRichMediaMessageOptions): Promise<{ message: string }>;Send a rich media message (image, file, etc.) to the interaction
@deprecated This method is deprecated and will be removed in a future version. Use sendChatMessage() instead.
Parameters
| Parameter | Type | Description |
|---|---|---|
| options | SendRichMediaMessageOptions | Message options (must provide either mediaUrl or file) |
| options.interactionId? | string | Optional interaction ID (required for app-level widgets, auto-provided for interaction-level widgets) |
Returns
Promise<{`message`: `string`}>
Promise resolving to a success message
Examples
// Send image from URL (interaction-level widget)
await api.sendRichMediaMessage({
name: 'Product Image',
mediaUrl: 'https://example.com/image.jpg',
text: 'Here is the product you requested'
});// Send file upload (app-level widget)
const fileInput = document.querySelector('input[type="file"]');
const file = fileInput.files[0];
await api.sendRichMediaMessage({
name: 'Document',
file: file,
text: 'Attached document',
interactionId: 'int-123'
});sendChatMessage()
sendChatMessage(options: SendChatMessageOptions): Promise<{ message: string }>;Send a chat message to the interaction
Supports sending text messages, media from URLs, or file uploads.
At least one of text, mediaUrl, or file must be provided.
Parameters
| Parameter | Type | Description |
|---|---|---|
| options | SendChatMessageOptions | Message options (must provide interactionId and at least one of text, mediaUrl, or file) |
| options.interactionId | string | Required interaction ID |
Returns
Promise<{`message`: `string`}>
Promise resolving to a success message
Examples
// Send text message
await api.sendChatMessage({
interactionId: 'int-123',
text: 'Hello, how can I help you today?'
});// Send image from URL
await api.sendChatMessage({
interactionId: 'int-123',
mediaUrl: 'https://example.com/image.jpg',
text: 'Here is the product you requested'
});// Send file upload
const fileInput = document.querySelector('input[type="file"]');
const file = fileInput.files[0];
await api.sendChatMessage({
interactionId: 'int-123',
file: file,
text: 'Attached document'
});// Send text with file
await api.sendChatMessage({
interactionId: 'int-123',
text: 'Please review this document',
file: documentFile,
fileName: 'Important Document.pdf'
});onReceivedFeedMessage()
onReceivedFeedMessage(callback: FeedMessageCallback): () => void;Subscribe to feed messages
Fires when a new message is received in the interaction feed
Parameters
| Parameter | Type | Description |
|---|---|---|
| callback | FeedMessageCallback | Function to call when a feed message is received. Receives (message: Message, interactionId?: string) |
Returns
Unsubscribe function () => void
Example
api.onReceivedFeedMessage((message, interactionId) => {
// Helper function to extract text from a message
function getMessageText(msg: Message): string {
if (typeof msg.message === 'string') {
return msg.message;
}
// Handle rich content array
if (Array.isArray(msg.message)) {
return msg.message
.map(part => {
if (part.type === 'text') return part.text;
if (part.type === 'email' && part.email) return part.email.plainText;
return '';
})
.join(' ')
.trim();
}
return '';
}
const text = getMessageText(message);
console.log('New message:', text);
console.log('From:', message.author?.displayName);
console.log('For interaction:', interactionId);
});Agent API Family
getUserInfo()
getUserInfo(): Promise<UserInfo>;Get information about the current logged-in user/agent
Returns
Promise<UserInfo>
Promise resolving to the user information including agent status, queues, and profile
Example
const userInfo = await api.getUserInfo();
console.log('Agent:', userInfo.firstName, userInfo.lastName);
console.log('Queues:', userInfo.queues);
console.log('Email:', userInfo.email);setAgentStatus()
setAgentStatus(
userId: string,
status: AgentStatus,
reason?: { id: string; name: string }
): Promise<{ message: string }>;Set the agent's status (Available, Away, Busy, etc.)
Parameters
| Parameter | Type | Description |
|---|---|---|
| userId | string | The user ID of the agent |
| status | AgentStatus | The new agent status |
| reason? | {id: string; name: string} | Optional reason for the status change (required for some statuses) |
| reason.id? | string | - |
| reason.name? | string | - |
Returns
Promise<{`message`: `string`}>
Promise resolving to a success message
Examples
// Set agent to Available
const userInfo = await api.getUserInfo();
await api.setAgentStatus(
userInfo.userId,
{ id: 'available', name: 'Available', category: 'available' }
);// Set agent to Away with reason
const userInfo = await api.getUserInfo();
await api.setAgentStatus(
userInfo.userId,
{ id: 'away', name: 'Away', category: 'away' },
{ id: 'lunch', name: 'Lunch Break' }
);getAvayaJwt()
getAvayaJwt(options?: {
authorizationEndpoint?: string;
tokenEndpoint?: string;
clientId?: string;
scopes?: string[];
redirectUri?: string;
popupOptions?: PopupOptions;
forceRefresh?: boolean;
}): Promise<string>;Get Avaya JWT token with multi-level request deduplication and automatic refresh
- Returns cached token from localStorage if available and not expired
- Automatically refreshes token if expired (using refresh token)
- Prevents duplicate concurrent fetch requests (instance-level)
- Prevents duplicate OAuth popups across iframes/elements (cross-iframe coordination)
- Initiates Keycloak OAuth flow if no token exists
Cross-iframe coordination ensures that if 10 iframes all call getAvayaJwt(),
only ONE OAuth popup will appear, and all iframes will receive the same token.
Uses localStorage for coordination to ensure only one OAuth popup appears.
GUARANTEE: This function ALWAYS either returns a JWT string or throws an error.
There are no code paths that return undefined or hang indefinitely.
Parameters
| Parameter | Type | Description |
|---|---|---|
| options | object | Configuration options (all optional, uses defaults if not provided) |
| options.authorizationEndpoint? | string | Keycloak authorization endpoint URL |
| options.tokenEndpoint? | string | Keycloak token endpoint URL |
| options.clientId? | string | OAuth client ID |
| options.scopes? | string[] | OAuth scopes to request |
| options.redirectUri? | string | OAuth redirect URI (URL to redirect.html) |
| options.popupOptions? | PopupOptions | Popup window size/position (defaults to 500x600) |
| options.forceRefresh? | boolean | Force token refresh even if not expired (defaults to false) |
Returns
Promise<string>
The JWT token (never returns undefined, always throws on error)
Example
// Use defaults
const jwt = await api.getAvayaJwt();
// With configuration
const jwt = await api.getAvayaJwt({
authorizationEndpoint: 'https://keycloak.example.com/auth/realms/xxx/protocol/openid-connect/auth',
tokenEndpoint: 'https://keycloak.example.com/auth/realms/xxx/protocol/openid-connect/token',
clientId: 'my-client-id',
redirectUri: 'https://myapp.com/redirect.html',
forceRefresh: true
});refreshToken()
refreshToken(options?: {
tokenEndpoint?: string;
clientId?: string;
}): Promise<string>;Refresh the access token using the stored refresh token
Parameters
| Parameter | Type | Description |
|---|---|---|
| options | object | Configuration options |
| options.tokenEndpoint? | string | Keycloak token endpoint URL (required) |
| options.clientId? | string | OAuth client ID (required) |
Returns
Promise<string>
The new JWT access token
Throws
Error if refresh token is not available or refresh fails
Example
try {
const newJwt = await api.refreshToken({
tokenEndpoint: 'https://keycloak.example.com/auth/realms/xxx/protocol/openid-connect/token',
clientId: 'my-client-id'
});
console.log('Token refreshed successfully');
} catch (error) {
console.error('Token refresh failed:', error);
// May need to re-authenticate
}clearAvayaJwt()
clearAvayaJwt(): void;Clear the cached JWT token and force re-authentication on next getAvayaJwt call
Returns
void
Example
api.clearAvayaJwt();
const newJwt = await api.getAvayaJwt(); // Will trigger OAuth flowonChangedAgentState()
onChangedAgentState(callback: AgentStateChangedCallback): () => void;Subscribe to agent state changed events
Fires when the agent's state changes (e.g., Available, Away, Busy)
Parameters
| Parameter | Type | Description |
|---|---|---|
| callback | AgentStateChangedCallback | Function to call when agent state changes. Receives {previousState, currentState, reason?} |
Returns
Unsubscribe function () => void
Example
api.onChangedAgentState(({ previousState, currentState, reason }) => {
console.log(`Agent state changed from ${previousState} to ${currentState}`);
if (reason) console.log(`Reason: ${reason}`);
});Admin API Family
getUsers()
getUsers(params?: {
interactionId?: string;
filter?: string;
}): Promise<GetUsersResponse[]>;Get a list of users in Infinity
Returns users available for transfer or consult operations. Returns up to 100 users.
- App Level (sidebar widgets): Provide
interactionIdparameter - Interaction Level (interaction widgets): Omit
interactionId, uses interaction context automatically
Parameters
| Parameter | Type | Description |
|---|---|---|
| params? | object | Optional parameters |
| params.interactionId? | string | Required for app-level widgets, optional for interaction-level widgets |
| params.filter? | string | Optional substring search against user name fields |
Returns
Promise<GetUsersResponse[]>
Promise resolving to array of user information
Examples
// Get all users (interaction level - no interactionId needed)
const users = await api.getUsers();
users.forEach(user => {
console.log(`$USER.FULLNAME - ${user.cxStatus.status} - $USER.PRESENCE`);
});// Get filtered users by name (interaction level)
const users = await api.getUsers({ filter: 'john' });
console.log('Found users:', users.map(u => u.fullName));// Get all users (app level - requires interactionId)
const users = await api.getUsers({ interactionId: 'int-123' });
users.forEach(user => {
console.log(`$USER.FULLNAME - ${user.cxStatus.status} - $USER.PRESENCE`);
});// Get filtered users (app level)
const users = await api.getUsers({
interactionId: 'int-123',
filter: 'john'
});// Use for transfer target selection
const users = await api.getUsers({ filter: searchInput });
const eligibleUsers = users.filter(u => u.eligible);
eligibleUsers.forEach(user => {
console.log(`$USER.FULLNAME ($USER.EXTENSION) - ${user.cxStatus.status}`);
});getUserQueues()
getUserQueues(params?: { filter?: string }): Promise<UserQueueInfo[]>;Get all queues available to the current user (App Level)
Returns a basic list of queues the agent has access to.
Parameters
| Parameter | Type | Description |
|---|---|---|
| params? | object | Optional filter parameters |
| params.filter? | string | Optional substring search against queue names |
Returns
Promise<UserQueueInfo[]>
Promise resolving to array of user queue information
Example
const queues = await api.getUserQueues();
console.log('Available queues:', queues.map(q => q.name));
// With filter
const salesQueues = await api.getUserQueues({ filter: 'Sales' });getTransferQueues()
getTransferQueues(params: {
interactionId: string;
filter?: string;
}): Promise<InteractionQueueInfo[]>;Get transfer queues with real-time statistics (App Level)
Returns detailed queue information including waiting interactions, active agents,
and average wait times. Requires explicit interactionId since this is used at app level
where interaction context is not available.
Parameters
| Parameter | Type | Description |
|---|---|---|
| params | object | Required interactionId and optional filter parameters |
| params.interactionId | string | Required interaction ID |
| params.filter? | string | Optional substring search against queue names |
Returns
Promise<InteractionQueueInfo[]>
Promise resolving to array of queue information with statistics
Example
const queues = await api.getTransferQueues({
interactionId: 'int-123',
filter: 'support'
});
queues.forEach(queue => {
console.log(`${queue.name}: ${queue.waitingInteractions} waiting`);
console.log(`Active agents: ${queue.countActiveAgents}`);
});getTransferQueuesInteraction()
getTransferQueuesInteraction(params?: {
filter?: string;
interactionId?: string;
}): Promise<InteractionQueueInfo[]>;Get transfer queues with real-time statistics (Interaction Level)
Returns detailed queue information including waiting interactions, active agents,
and average wait times. Uses interaction context automatically for interaction-level widgets.
Parameters
| Parameter | Type | Description |
|---|---|---|
| params? | object | Optional filter parameters |
| params.filter? | string | Optional substring search against queue names |
| params.interactionId? | string | Optional interaction ID (required for app-level widgets, auto-provided for interaction-level widgets) |
Returns
Promise<InteractionQueueInfo[]>
Promise resolving to array of queue information with statistics
Examples
// Interaction-level widget
const queues = await api.getTransferQueuesInteraction({ filter: 'support' });
queues.forEach(queue => {
console.log(`${queue.name}: ${queue.waitingInteractions} waiting`);
console.log(`Active agents: ${queue.countActiveAgents}`);
});// App-level widget
const queues = await api.getTransferQueuesInteraction({
filter: 'support',
interactionId: 'int-123'
});getReasonCodes()
getReasonCodes(params?: GetReasonCodesParams): Promise<GetReasonCodesResponse>;Get reason codes for agent status changes
Returns available reason codes that can be used when changing agent status.
Parameters
| Parameter | Type | Description |
|---|---|---|
| params? | GetReasonCodesParams | Optional parameters |
| params.type? | "away" | "busy" | "available" | "queueLogout" | null | Filter by reason type |
Returns
Promise<GetReasonCodesResponse>
Promise resolving to reason codes response
Examples
// Get all reason codes
const response = await api.getReasonCodes();
console.log('Reason codes:', response.reasons);// Get away reason codes only
const response = await api.getReasonCodes({ type: 'away' });
const awayReasons = response.reasons;Inter-Element Communication
sendInterElementMessage()
sendInterElementMessage<T>(message: T): void;Send a message to other elements via the host (parent window)
Messages are routed through the host application which acts as a broker,
relaying messages to all other element iframes. This approach works in
sandboxed iframes where BroadcastChannel is not available.
Type Parameters
| Type Parameter | Description |
|---|---|
| T | The type of the message |
Parameters
| Parameter | Type | Description |
|---|---|---|
| message | T | The message to send (can be any serializable type) |
Returns
void
Example
api.sendInterElementMessage({ type: 'my-event', payload: { key: 'value' } });onInterElementMessage()
onInterElementMessage<T>(callback: (message: T) => void): () => void;Subscribe to messages from other elements routed through the host
The host application receives inter-element messages and relays them to
all element iframes. This works in sandboxed iframes where BroadcastChannel
is not available.
Type Parameters
| Type Parameter | Description |
|---|---|
| T | The expected type of messages |
Parameters
| Parameter | Type | Description |
|---|---|---|
| callback | (message: T) => void | Function called when a message is received |
Returns
Unsubscribe function () => void
Example
const unsubscribe = api.onInterElementMessage<MyMessageType>((message) => {
console.log('Received:', message);
});
// Later, stop listening
unsubscribe();Events
onError()
onError(callback: ErrorCallback): () => void;Subscribe to error events
Fires when an error occurs in the API
Parameters
| Parameter | Type | Description |
|---|---|---|
| callback | ErrorCallback | Function to call when an error occurs |
Returns
Unsubscribe function () => void
Example
api.onError((error) => {
console.error('API Error:', error.code, error.message);
// Display error notification to user
});Lifecycle
destroy()
destroy(): void;Clean up resources when the React component is unmounted or no longer needed
Removes all event listeners, closes channels, and clears pending requests.
Call this method in your React component's cleanup/unmount lifecycle.
Returns
void
Example
// In a React component
useEffect(() => {
const api = new ElementAPI();
return () => {
api.destroy(); // Cleanup on unmount
};
}, []);Enumerations
DialpadDigit
DTMF dialpad digits (0-9) for sending tones during calls
Example
import { DialpadDigit } from '@avaya/infinity-elements-api';
await api.sendDialpadDigit(DialpadDigit.Five, null, false);Functions
setupOAuthCallbackHandler()
function setupOAuthCallbackHandler(): void;Setup OAuth callback handler - call once at app initialization
Sets up listener for redirect.html config requests
Returns
void
refreshAccessToken()
function refreshAccessToken(
refreshToken: string,
tokenEndpoint: string,
clientId: string
): Promise<TokenResponse>;Refresh an expired access token using the refresh token
Elements run in sandboxed iframes (about:srcdoc) which have origin "null".
Direct fetch to Keycloak fails due to CORS.
This function delegates the refresh request to the host (agent-ui) via
postMessage. The host has a proper origin and can make the request
without CORS issues. This is completely silent - no popups or visible UI.
Parameters
| Parameter | Type | Description |
|---|---|---|
| refreshToken | string | The refresh token to use |
| tokenEndpoint | string | The token endpoint URL |
| clientId | string | The OAuth client ID |
Returns
Promise<TokenResponse>
getStoredTokenData()
function getStoredTokenData(jwtStorageKey: string): StoredTokenData | null;Get stored token data from localStorage
Parameters
| Parameter | Type |
|---|---|
| jwtStorageKey | string |
Returns
StoredTokenData | null
isTokenExpired()
function isTokenExpired(tokenData: StoredTokenData): boolean;Check if a token is expired
Parameters
| Parameter | Type |
|---|---|
| tokenData | StoredTokenData |
Returns
boolean
isRefreshTokenExpired()
function isRefreshTokenExpired(tokenData: StoredTokenData): boolean;Check if refresh token is expired
Parameters
| Parameter | Type |
|---|---|
| tokenData | StoredTokenData |
Returns
boolean
Interfaces
InteractionInfo
| Property | Type |
|---|---|
| id | string |
| interactionId | string |
| status | string |
| commType? | string |
| direction? | string |
| customer? | {name?: string; number?: string; id?: string} |
| startTime? | string |
| duration? | number |
| metadata? | Record<string, unknown> |
InteractionUpdatePayload
| Property | Type |
|---|---|
| id | string |
| status? | string |
| commType? | string |
| subCommType? | string |
| isAudio? | boolean |
| isHold? | boolean |
| isMute? | boolean |
| details? | {notes?: string; subject?: string} |
| sourceDetails? | {phoneNumber?: string; email?: string; name?: string} |
InteractionContextOptions
Common options for interaction-context methods. Used to optionally specify an interaction ID for app-level widgets.
| Property | Type | Description |
|---|---|---|
| interactionId? | string | Optional interaction ID (required for app-level widgets, auto-provided for interaction-level widgets) |
BlindTransferOptions
| Property | Type | Description |
|---|---|---|
| interactionId | string | - |
| transferTo | string | The target User ID, Queue ID, or Phone Number |
| transferToName | string | The display name of the target |
| transferCallerIdType? | string | - |
SingleStepTransferParams
| Property | Type | Description |
|---|---|---|
| targetId | string | The target User ID, Queue ID, or Phone Number |
| targetName | string | The display name of the target |
| interactionId? | string | Optional interaction ID (required for app-level widgets, auto-provided for interaction-level widgets) |
CreateVoiceInteractionParams
| Property | Type |
|---|---|
| phoneNumber | string |
| queueId | string |
SendRichMediaMessageOptions
| Property | Type |
|---|---|
| name? | string |
| mediaUrl? | string |
| file? | File |
| text? | string |
| interactionId? | string |
SendChatMessageOptions
| Property | Type | Description |
|---|---|---|
| interactionId | string | Required interaction ID |
| text? | string | Optional message text |
| mediaUrl? | string | Optional media URL (image, file, etc.) |
| file? | File | Optional file to upload |
| fileName? | string | Optional file name for the message/file |
ConsultCallOptions
| Property | Type | Description |
|---|---|---|
| interactionId | string | - |
| transferTo? | string | User ID or handle to consult with (internal user/agent) |
| phoneNumber? | string | Phone number to consult with (external number) |
| queueId? | string | Queue ID to consult to. Can be obtained via getTransferQueuesInteraction |
AgentStatus
| Property | Type |
|---|---|
| id | string |
| name | string |
| category | string |
ReasonCode
| Property | Type |
|---|---|
| id | string |
| reason | string |
| type | "away" | "busy" | "available" | "queueLogout" |
| typeDisplay | string |
| eliteAuxCode? | number |
| isDisabled | boolean |
| isSystemCode? | boolean |
| createdAt | string |
| createdBy | string |
| updatedAt | string | null |
| updatedBy | string | null |
| inWorkflowId | string | null |
| inWorkflowVersionId | string | null |
| outWorkflowId | string | null |
| outWorkflowVersionId | string | null |
| queryFieldId | string | null |
GetReasonCodesParams
| Property | Type |
|---|---|
| type? | "away" | "busy" | "available" | "queueLogout" | null |
GetReasonCodesResponse
| Property | Type |
|---|---|
| reasons | ReasonCode[] |
GetUserInteractionsParams
| Property | Type |
|---|---|
| userId? | string |
| details? | boolean |
QueueLoggedIn
| Property | Type |
|---|---|
| queueId | string |
| name | string |
| queueWeight | number |
| timeZone | string |
| extension | number | null |
| createdOn | string |
| createdOnUnix | number |
QueueAccess
| Property | Type |
|---|---|
| queueId | string |
| name | string |
| queueWeight | number |
| timeZone | string |
| extension | number | null |
UserInteractionsUser
| Property | Type |
|---|---|
| id | string |
| firstName | string |
| lastName | string |
| fullName | string |
| title | string | null |
| string | |
| extension | string | null |
GetUserInteractionsResponse
| Property | Type |
|---|---|
| interactions | Interaction[] |
| viewing | Interaction[] |
| combinedIds? | string[] |
| queue | {loggedIn: [QueueLoggedIn](#queueloggedin)[]; access: [QueueAccess](#queueaccess)[]} |
| user | UserInteractionsUser |
ElementAPIOptions
Configuration options for ElementAPI initialization
| Property | Type | Description |
|---|---|---|
| elementId? | string | Unique identifier for this element instance (auto-generated if not provided) |
| timeout? | number | API request timeout in milliseconds (default: 5000) |
| debug? | boolean | Enable debug logging to console (default: false) |
| requestTarget? | Window | When set (e.g. iframe.contentWindow), API sends requests to this window instead of window.parent. Use when ElementAPI runs in the adaptor/bridge and the Agent UI is in an iframe. |
InteractionQueueInfo
| Property | Type |
|---|---|
| id | string |
| name | string |
| extension | string | null |
| waitingInteractions | number |
| countOfCallbacks | number |
| countActiveAgents | number |
| totalCurrentInteractions | number |
| connectedInteractions | number |
| avgInteractionWaitTime | number |
| weight | number |
| eligible | boolean |
UserQueueInfo
| Property | Type |
|---|---|
| id | string |
| name | string |
KeycloakConfig
Keycloak OAuth 2.0 PKCE Authentication Module
Supports cross-iframe coordination to prevent multiple OAuth popups.
Uses postMessage-based config exchange with redirect.html:
- Component opens popup directly
- redirect.html requests config via postMessage
- Component responds with config + code verifier
- redirect.html performs token exchange
- redirect.html sends token back to component
No localStorage bridging needed - config stays in memory.
| Property | Type | Description |
|---|---|---|
| authorizationEndpoint? | string | - |
| tokenEndpoint? | string | - |
| clientId? | string | - |
| scopes? | string[] | - |
| redirectUri? | string | URL to redirect.html - used for OAuth callback and token refresh |
PopupOptions
| Property | Type |
|---|---|
| width? | number |
| height? | number |
| left? | number |
| top? | number |
TokenResponse
| Property | Type |
|---|---|
| access_token | string |
| refresh_token? | string |
| expires_in? | number |
| refresh_expires_in? | number |
| token_type? | string |
| id_token? | string |
StoredTokenData
| Property | Type |
|---|---|
| accessToken | string |
| refreshToken? | string |
| expiresAt? | number |
| refreshExpiresAt? | number |
Message
| Property | Type |
|---|---|
| id | string |
| author | {displayName?: string; id?: string; type: "user" | "phoneNumber"; details?: { displayName?: string; id?: string; avatarUrl?: string; imageLastChangedAt?: string | null }} |
| displayNameOverride? | string |
| channel? | string |
| channelMessageComponentId? | string |
| createdAt | string |
| direction | "in" | "out" |
| fromPhoneNumber? | string | null |
| isBot | boolean |
| isCanned? | boolean |
| isDeleted? | boolean |
| isEdited? | boolean |
| isEmail? | boolean |
| isMms? | boolean |
| isPinned? | boolean |
| isPrivate | boolean |
| isSaved? | boolean |
| isSms? | boolean |
| message | string | FancyMessage[] |
| paginationId | string |
| pinnedAt | string | null |
| pinnedBy | string | null |
| pinnedByUserFirstLastName | string | null |
| subType? | MessageSubType |
| type | "email" | "sms" | "chat" |
| updatedAt? | string | null |
| threadChannelMessageId? | string | null |
| translations? | Record<string, string> |
GetUsersResponse
Response from getUsers API. Used for transfer/consult target selection.
| Property | Type | Description |
|---|---|---|
| id | string | Handle / internal user ID |
| firstName | string | First name |
| lastName | string | Last name |
| fullName | string | Full name |
| string | Email address | |
| mobile | string | null | Mobile phone number |
| presence | string | null | VoIP/presence status (e.g., "available", "busy", "offline") |
| cxStatus | {statusType: string; status: string} | CX status information |
| cxStatus.statusType | string | CX status category (e.g., "available", "busy", "away") |
| cxStatus.status | string | CX status display name (e.g., "Available", "On Call", "Lunch") |
| extension | string | null | Extension number |
| eligible | boolean | Whether user is eligible for transfer |
UserLocation
| Property | Type |
|---|---|
| addressData? | {address1: string; address2: string; city: string; state: string; country: string; postalCode: string; locationName: string} |
| locationId | string |
| e911Number | string |
| isE911 | string | boolean |
| e911CallerIdNumber? | string | null |
QueueInfo
| Property | Type |
|---|---|
| queueId | string |
| name | string |
| isAccess | boolean |
| isAutoLogin | boolean |
| proficiency? | unknown |
UserTag
| Property | Type |
|---|---|
| tagId | string |
| backgroundColor | string |
| color | string |
| iconCode | string |
| name | string |
DefaultLeaveEventToStatus
| Property | Type |
|---|---|
| action | string |
| status | string |
InfinityElement
| Property | Type |
|---|---|
| accountId | string |
| apiVersionId | string |
| config | {file: { filename: string; mimetype: string; size: number; storageId: string }} |
| createdAt | string |
| createdBy | string |
| folderId | string | null |
| icon | string |
| id | string |
| name | string |
| tagName | string |
| updatedAt | string |
| updatedBy | string | null |
| uploadedAt | string | null |
| uploadedBy | string | null |
UserInfo
| Property | Type | Description |
|---|---|---|
| userId | string | User ID |
| status? | string | Whether the user is enabled (status === 'enabled' for yes) |
| firstName | string | First name |
| lastName | string | Last name |
| nameSuffix? | string | null | Name suffix (e.g., Jr., Sr., III) |
| title | string | Job title |
| string | Email address | |
| mobile? | string | null | Mobile phone number |
| languageCode? | string | Language code (e.g., 'en', 'es') |
| location? | UserLocation | null | E911 location information |
| timezone? | string | Timezone (e.g., 'America/New_York') |
| licenseType? | string | License type |
| consolePermissions? | object | Console permissions |
| appPermissions? | object | Application permissions |
| outboundPermissions? | {task: "0" | "1"; email: "0" | "1"; phone: "0" | "1"; messaging: "0" | "1"} | Outbound permissions by communication type |
| rejectInteractions? | boolean | Inbound permissions - can reject interactions |
| monitoringAction? | string | Monitoring action configuration |
| completedAction? | string | Completed action configuration |
| interactionViewsType? | string | Interaction view type |
| modifyInteractionViews? | boolean | Can create/edit interaction views |
| tags? | UserTag[] | List of assigned tags |
| personalQueueId? | string | Personal queue ID |
| defaultOutboundQueue? | string | Default outbound queue name |
| outboundActionAndStatus? | DefaultLeaveEventToStatus | Outbound call action and status |
| inboundActionAndStatus? | DefaultLeaveEventToStatus | Inbound call action and status |
| callbackActionAndStatus? | DefaultLeaveEventToStatus | Callback action and status |
| voicemailActionAndStatus? | DefaultLeaveEventToStatus | Voicemail action and status |
| queues? | QueueInfo[] | List of assigned queues with access, auto-login, and proficiency info |
| phoneSpaces? | number | Number of concurrent phone interactions allowed |
| messagingSpaces? | number | Number of concurrent messaging interactions allowed |
| emailSpaces? | number | Number of concurrent email interactions allowed |
| taskSpaces? | number | Number of concurrent task interactions allowed |
| eliteExtension? | string | null | Elite Agent Extension |
| eliteAgentId? | string | null | Elite Agent ID |
| eliteSipAddress? | string | null | SIP Address |
| eliteSbcGroupId? | string | null | SBC Group ID |
| crmConfigurations? | unknown | CRM Configuration object |
| infinityElements? | InfinityElement[] | App-level Infinity Elements assigned |
| authToken? | string | Authentication token (JWT) using accessToken |
Type Aliases
CHANNEL_NAMES
const CHANNEL_NAMES = {
INTERACTION_STATUS_CHANGED: "interaction-status-changed";
INTERACTION_ENDED: "on-interaction-ended";
INTERACTION_ACCEPTED: "on-interaction-accepted";
INTERACTION_UPDATED: "on-interaction-updated";
CONSULT_STATUS_CHANGED: "consult-status-changed";
COMPLETE_AS_CONFERENCE: "on-complete-as-conference";
FEED_MESSAGE: "feed-message";
AGENT_STATE_CHANGED: "agent-state-changed";
INTER_ELEMENT: "inter-element";
} as const;| Property | Value |
|---|---|
| INTERACTION_STATUS_CHANGED | "interaction-status-changed" |
| INTERACTION_ENDED | "on-interaction-ended" |
| INTERACTION_ACCEPTED | "on-interaction-accepted" |
| INTERACTION_UPDATED | "on-interaction-updated" |
| CONSULT_STATUS_CHANGED | "consult-status-changed" |
| COMPLETE_AS_CONFERENCE | "on-complete-as-conference" |
| FEED_MESSAGE | "feed-message" |
| AGENT_STATE_CHANGED | "agent-state-changed" |
| INTER_ELEMENT | "inter-element" |
InteractionStatusChangedCallback()
type InteractionStatusChangedCallback = (payload: {
interactionId: string;
status: string;
}) => void;InteractionEndedCallback()
type InteractionEndedCallback = (interactionId: string) => void;InteractionAcceptedCallback()
type InteractionAcceptedCallback = (interactionId: string) => void;InteractionUpdatedCallback()
type InteractionUpdatedCallback = (payload: {
interactionId: string;
event: "interaction.update";
payload: Interaction;
}) => void;ConsultStatusChangedCallback()
type ConsultStatusChangedCallback = (payload: {
interactionId: string;
consultStatus: string;
consultParty?: string;
error?: string;
}) => void;CompleteAsConferenceCallback()
type CompleteAsConferenceCallback = (payload: {
interactionId: string;
}) => void;FeedMessageCallback()
type FeedMessageCallback = (message: Message, interactionId?: string) => void;Parameters
| Parameter | Type | Description |
|---|---|---|
| message | Message | The message received |
| interactionId? | string | Optional interaction ID the message belongs to |
ErrorCallback()
type ErrorCallback = (error: {
code: string;
message: string;
details?: unknown;
}) => void;AgentStateChangedCallback()
type AgentStateChangedCallback = (payload: {
previousState: string;
currentState: string;
reason?: string;
}) => void;Parameters
| Parameter | Type | Description |
|---|---|---|
| payload.previousState | string | The previous agent state |
| payload.currentState | string | The new agent state |
| payload.reason? | string | Optional reason for the state change |
FancyMessage
type FancyMessage =
| AudioMessage
| TextMessage
| PreviewMessage
| FileMessage
| ActionMessage
| EmailMessage;MessageSubType
type MessageSubType = "babelVoice" | "transcription" | null;Variables
VERSION
export const VERSION = "1.2.0";Updated 11 days ago