@belsmart/crm-sdk
v0.12.0
Published
Click-to-call SDK and floating softphone widget for third-party CRM integrations with Belsmart.
Readme
@belsmart/crm-sdk
Click-to-call SDK and floating softphone widget for embedding Belsmart calling into a third-party CRM.
New to this SDK, or integrated before 0.8.0? Start with docs/INTEGRATION_GUIDE.md — a current, end-to-end walkthrough of the recommended setup. This README is the narrative reference; docs/API.md is the full method-by-method reference.
How it fits together
- The Belsmart gateway (
partner-apimodule in the main API) issues each CRM integration an API key/secret pair, scoped to one tenant. - That key/secret gets exchanged for a short-lived (12h) session token + SIP credentials via
POST /partner-api/v1/session. The SDK can do this exchange itself (BelsmartCrmConfig, below) — simplest to wire up, but it meansapiSecrethas to be constructed with by browser code, which makes it readable from dev tools by any signed-in agent. We recommend instead having your own backend perform this exchange (BelsmartCrmSessionConfig) and handing the browser only the resulting session — see "KeepingapiSecretoff the browser" below. - Either way, the SDK then registers a WebRTC softphone for the mapped agent using that session and exposes
call()/hangup()/ events. - The widget is an optional floating UI built on top of the SDK — a dial pad, active-call bar, and incoming-call popup, rendered inside a Shadow DOM so it never inherits the host CRM's styles.
Click-to-call works by ringing the agent's own SIP device first; once the SDK's softphone answers that leg, the Belsmart PBX bridges it to the destination number — the same mechanism the internal agent portal and HubSpot integration use.
Setup (one-time, done by the tenant admin)
- In the Belsmart admin, create a partner API key:
POST /partner-api/keys { "name": "Acme CRM" }. The response'skey_secretis shown once — store it securely. - Map each CRM user to a Belsmart agent (
agent_uuid) — store that mapping on the CRM side. UseBelsmartCrmClient.listAgents()(below) to fetch the options for that mapping UI instead of hardcoding UUIDs.
Usage
Map a CRM user to an agent (once, e.g. in a settings screen), then construct the client:
import { BelsmartCrmClient } from "@belsmart/crm-sdk";
// No agentUuid needed yet — just the key pair.
const agents = await BelsmartCrmClient.listAgents({ apiBaseUrl, apiKey, apiSecret });
// agents: [{ agentUuid, name, email, extension }, ...]
// Show these in your own UI, let the CRM user pick one, store their choice
// (e.g. as a custom field on your CRM user record) — then:
const client = new BelsmartCrmClient({ apiBaseUrl, apiKey, apiSecret, agentUuid: picked.agentUuid });<!-- Pinned to a specific version — bump deliberately, don't float on latest. -->
<script src="https://unpkg.com/@belsmart/[email protected]/dist/index.global.js"></script>
<script>
// `session` comes from YOUR OWN backend, which already did the apiKey/apiSecret
// exchange server-side (see "Keeping apiSecret off the browser" below) — fetch
// it from your own endpoint however your CRM's frontend normally talks to its
// backend. apiKey/apiSecret never appear in this page.
fetch("/api/belsmart-session", { credentials: "include" })
.then((res) => res.json())
.then((session) => {
const client = new BelSmartCRM.BelsmartCrmClient({
apiBaseUrl: "https://pbx.example.com",
agentUuid: "<belsmart-agent-uuid-for-this-crm-user>",
session,
});
client.on("incoming", (call) => { /* show your own UI, or let the widget handle it */ });
client.on("active", (call) => console.log("call active", call));
client.on("ended", (call) => console.log("call ended", call, `${call.duration}s`));
// Fires for things like a denied/missing microphone (SDK 0.8.1+) — the
// call is also reported "ended" in that case, not left hanging.
client.on("error", (err) => console.error("BelSmart CRM error:", err.message));
client.init().then(() => {
BelSmartCRM.createWidget(client);
});
});
</script>Simplest-to-wire-up alternative, if you're prototyping and don't yet have a backend endpoint for the session exchange — not recommended for production, since apiSecret ends up readable from this page's own source/dev tools:
<script src="https://unpkg.com/@belsmart/[email protected]/dist/index.global.js"></script>
<script>
const client = new BelSmartCRM.BelsmartCrmClient({
apiBaseUrl: "https://pbx.example.com",
apiKey: "pk_...",
apiSecret: "...",
agentUuid: "<belsmart-agent-uuid-for-this-crm-user>",
});
client.on("error", (err) => console.error("BelSmart CRM error:", err.message));
client.init().then(() => {
BelSmartCRM.createWidget(client);
});
</script>Or via npm, with your own UI instead of the built-in widget:
import { BelsmartCrmClient } from "@belsmart/crm-sdk";
const client = new BelsmartCrmClient({ apiBaseUrl, apiKey, apiSecret, agentUuid });
await client.init();
document.querySelector("#call-btn")?.addEventListener("click", () => {
// Country code + national number, digits only — no leading "+", no separators.
client.call("15551234567", "crm-contact-42");
});Keeping apiSecret off the browser (recommended)
apiKey/apiSecret are tenant-wide credentials meant to live server-side. The only thing they're ever used for is the one-time exchange at POST /partner-api/v1/session — every call-control operation afterwards (call(), hangup(), conference/consult, CDR, recording) runs off the short-lived sessionToken that exchange returns. So instead of constructing BelsmartCrmClient with the raw key pair in browser code, have your own backend perform that exchange and hand the browser only the resulting session:
// --- your backend (holds apiKey/apiSecret) ---
const res = await fetch(`${apiBaseUrl}/partner-api/v1/session`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-Api-Key": apiKey,
"X-Api-Secret": apiSecret,
},
body: JSON.stringify({ agent_uuid: pickedAgentUuid }),
});
const { data } = await res.json();
// Hand `data` down to the browser over your own authenticated session/API —
// map it to SessionInfo's camelCase shape (sessionToken, expiresIn, tenantUuid,
// agentUuid, sip, wssUrl, iceServers, defaultCountryCode) the same way
// ApiClient.createSession() does internally.// --- browser (never sees apiKey/apiSecret) ---
import { BelsmartCrmClient } from "@belsmart/crm-sdk";
const client = new BelsmartCrmClient({
apiBaseUrl,
agentUuid: pickedAgentUuid,
session, // the SessionInfo your backend fetched above
});
await client.init(); // adopts `session` directly — no session-mint call, no secret involvedBelsmartCrmClient.listAgents()/listDispositions() also take the raw key pair (they're just thin GET wrappers) — call these from your backend too, and pass down only the resulting AgentInfo[]/DispositionInfo[] arrays for your agent/disposition-mapping UI.
API
Full function-level reference: docs/API.md.
Setup / session
BelsmartCrmClient.listAgents({ apiBaseUrl, apiKey, apiSecret })— static; lists active agents for the tenant (agentUuid,name,email,extension) so the CRM can build its own agent-mapping UI. Only needs the key pair — call this before constructing a client. Prefer calling this from your backend (see "KeepingapiSecretoff the browser") and passing just the result down.BelsmartCrmClient.listDispositions({ apiBaseUrl, apiKey, apiSecret }, agentUuid?)— static; lists dispositions for the campaign bound to the key (or, withagentUuid, the campaign that agent picked viasetCampaign()) (dispositionUuid,name,code), for building your own outcome-mapping UI. Returns[](not an error) if the key has no campaign bound. Same backend-first recommendation aslistAgents().new BelsmartCrmClient(config)—configis either:BelsmartCrmConfig:apiBaseUrl,apiKey,apiSecret,agentUuid,debug?— the SDK exchanges the key pair for a session itself ininit(). Simplest, but putsapiSecretin browser code.BelsmartCrmSessionConfig:apiBaseUrl,agentUuid,session(aSessionInfoyour backend already fetched fromPOST /partner-api/v1/session),debug?—init()adoptssessiondirectly, no secret involved. Recommended — see "KeepingapiSecretoff the browser" above.debug?(both forms, defaultfalse) enables the SDK's own verbose internal logging for session/mute/hold/conference internals;sip.js's own wire-level SIP logging is always kept suppressed regardless of this flag.
client.init()— authenticate and register the softphone. Call once before anything else.client.destroy()— unregisters and tears down the transport.client.getAgentLabel()— the signed-in agent's own SIP extension username (e.g."Agent16"), ornullbeforeinit()/afterdestroy(). Used by the built-in widget to label the agent's own row in a conference roster.client.getDefaultCountryCode()— the country code configured on the agent's current campaign (seesetCampaign(); the key's campaign by default), e.g."1", or""if none is set. Purely informational —call()never reads it; it's there so your own custom UI can pre-fill a country-code picker the same way the built-in widget's dial pad does.
Campaign
The API key's campaign is the default. An agent assigned to more than one campaign (their user group in the tenant portal — active outbound campaigns only) can switch: calls, caller ID, outgoing rules, DNC, dispositions, the dial-pad country code and their live-dashboard presence then run under the picked campaign. The choice is remembered server-side for that agent + key, so it survives session refresh and the next sign-in.
client.listCampaigns()—{ campaigns: CampaignInfo[], activeCampaignUuid, defaultCampaignUuid }.client.getCampaign()— the currentCampaignInfo(campaignUuid,name,allowCustomCallerId), ornullif the key has none bound.client.isCustomCallerIdAllowed()— whether the current campaign lets the agent use their own caller ID (set per campaign by the master admin, "Allow Custom Caller ID").client.setCampaign(campaignUuid)— switch; resolves with the newCampaignInfo, updatesgetDefaultCountryCode()and fires"campaign_changed". Rejects withBelsmartApiError409 during a call, 403 if the campaign isn't assigned to the agent or is inactive. In the built-in widget the campaign picker is under the settings (gear) icon in the header, shown while idle.
Pause
client.setStatus("pause" | "idle")— pause the agent (live dashboard shows Pause, no queue calls; the agent can still call out) or resume to Idle. Kept across session refresh and sign-in until resumed or signed off. Fires"status_changed". Rejects withBelsmartApiError409 during a call.client.getStatus()—"pause"or"idle".- The built-in widget shows a Pause / Resume button above the dial pad and a "Paused" badge in its header.
Custom caller ID
On campaigns the master admin allowed, the agent can choose the caller ID the customer sees: client.call(number, { callerId: "14155550123" }) (7-15 digits, optional leading +). On any other campaign the gateway rejects the call with BelsmartApiError 403. Checked on every call, so revoking takes effect immediately. The built-in widget shows an optional "Your caller ID" field on the dial pad only when isCustomCallerIdAllowed() is true, and remembers the last value in that browser. Transfers and conference keep their usual caller-ID rules.
Calls
client.call(toNumber, externalRef?, leadName?)— click-to-call;externalRefis echoed back untouched (e.g. a CRM contact id),leadNameis display-only (shown by the built-in widget in place of the raw number). Rejects immediately if not currently connected (see "Connection resilience" below) or if a call is already in progress.client.hangup()— ends an active call, or cancels one still waiting on its bridge leg. In a conference, this only drops your own leg — seehangupAll().client.setMuted(bool),client.isMuted()— instant, client-side (no re-INVITE).client.hold(),client.unhold(),client.isOnHold()— re-INVITEs with a held SDP so FreeSWITCH plays hold music to the far end; also mutes local playback.client.setVolume(0..1),client.getVolume()— local playback volume of the remote party only.client.setSoundsEnabled(bool),client.isSoundsEnabled()— short local beeps on connect/disconnect, mute/unmute and hold/unhold (agent's speakers only, never sent to the far end). On by default; setsounds: falsein the config to start with them off.client.getConnectionStatus()("disconnected" | "connecting" | "connected"),client.isConnected()— tracked continuously, including reconnects after a WSS drop, not just the firstinit().client.sendDtmf(digit)client.getCurrentCall()— the in-progress call, if any.
Conference (add a party)
client.addToConference(toNumber, leadName?)— adds a third party to the current call; from this point on, everyone (you, the customer, and every added party) can hear each other.leadNameis display-only, shown by the built-in widget's roster in place of the raw number — same convention ascall()'s. SetsCallInfo.inConference = true.client.hangupAll()— ends the call for every party on it, not just your own leg. Only valid onceinConferenceistrue.client.listConferenceParticipants()—Promise<ConferenceParticipant[]>; everyone currently on the call (you included), for building a roster with per-person controls. Returns[]if not currently in a conference. There's no push update for membership changes — call this again to refresh. The built-in widget does this automatically: after every action, briefly (every 2s, up to 60s) after adding a party until they actually answer, and continuously (every 5s) for as long as the call stays a conference, so someone hanging up on their own also disappears from the roster without a manual refresh.client.muteConferenceParticipant(memberId)/unmuteConferenceParticipant(memberId)— mute/unmute one participant (server-side, via FreeSWITCH's conference member commands — not a local WebRTC track toggle, unlikesetMuted()).client.holdConferenceParticipant(memberId)/unholdConferenceParticipant(memberId)— hold/unhold one participant; they can't hear or be heard while held, everyone else is unaffected.client.kickConferenceParticipant(memberId)— removes one participant; everyone else stays connected.memberIdcomes fromlistConferenceParticipants()— it's a FreeSWITCH conference member id, not a channel UUID.
Park & grab
Parked calls are shared across the whole tenant — with the Chrome extension and agent portal too — so any agent can grab any parked call. They don't time out, and there are no push updates: poll the list.
client.park()—Promise<{ parkedCallId }>; parks the current call. The gateway drops your leg and closes the call record itself, so no/endis sent."parked"fires, then"ended"withparked: true. Not available on a conference (400).client.listParkedCalls()—Promise<ParkedCall[]>; everything currently parked in the tenant. The built-in widget polls it every 5s while its "Parked calls" list is open.client.grabParkedCall(parked)—Promise<CallInfo>; takes a parked call. The gateway rings you and the SDK answers that ring itself, so the call goes straight to"active"(caller shown from the park list, not FreeSWITCH's placeholder). Resolves once connected, with the call's newcallId— hold, transfer,/end, heartbeats and CDR all use it from then on. Can take up to ~30s. Only while idle. Rejects with the gateway's message as-is: 409 already grabbed by someone else / not answered (back in the list), 404 caller hung up / no extension for this agent.client.mergeParkedCall(parked)—Promise<void>; pulls any parked call into the current call. It becomes a conference, as withaddToConference(), and the parked customer joins with no ring. Rejects with the gateway's message as-is: 409 already taken, 404 caller hung up.
Disposition
client.setDisposition(disposition?, callId?)— records an outcome for the most recently ended call (or a specificcallId). Safe to call any time after a call ends. Not yet reflected in Belsmart's own CDR/reporting — purely for your own tracking today; wiring it into Belsmart's own reporting is coming soon.
CDR & recording
client.getCallCdr(callId?)—Promise<CallCdr>; the gateway's own call detail record (direction, numbers, start/answer/end timestamps, duration, talk-time, hangup cause, disposition). Defaults to the most recently ended call, same convention assetDisposition().client.getCallRecording(callId?)—Promise<CallRecording | null>; a short-lived signed playback/download URL (expires in ~10 minutes), ornullif the call wasn't recorded or the gateway hasn't finished processing it yet — retry shortly after if you getnullright after the call ends. Fetch/play or copy the file promptly — the URL isn't meant to be stored for later; callgetCallRecording()again to mint a fresh one. SamecallIdconvention as above.
Events & widget
client.on(event, handler)/client.off(event, handler)—registered | unregistered | connection_status | incoming | connecting | ringing | active | consulting | ended | campaign_changed | mute | hold | error.on()returns an unsubscribe function.createWidget(client, options?)— mounts the floating dialer (dialpad with a country-code selector, mute/hold/keypad/conference controls, live SIP status dot, draggable by its header); returns{ destroy() }. The dial pad's country-code selector pre-fills fromgetDefaultCountryCode()but is always editable — the agent types the local number and the widget composes the full number itself before callingcall().addToConference()/startConsult()'s own number panels have no selector — the agent types the full number directly there, same ascall()'s own contract.
Call lifecycle
CallInfo.state moves through "connecting" → "ringing" → "active" → "ended" (or "consulting" in between, during an attended transfer):
connecting—call()has originated the click-to-call and is waiting for the bridge-leg INVITE to reach your own device.ringing— your own leg is up (the bridge-leg INVITE was accepted), and Belsmart has started dialing the customer's number. This is not the same moment asconnectingresolving — your leg connecting to Belsmart happens before the customer's phone ever rings. The SDK polls the gateway (~400ms intervals, up to 90s) to find out the moment the customer actually answers, since your browser's own SIP session has no visibility into that second leg at all.active— the customer answered. This is also whenstartedAtis (re)stamped and the duration clock genuinely starts — not atconnecting, and not merely at your own leg connecting.consulting— mid-attended-transfer (startConsult()was called); the customer is held while you talk privately to a consult target.ended— self-explanatory.durationreflects actual talk time (customer-answer to end), not total elapsed time sincecall().
If you're building a custom UI, listen for ringing and active separately rather than treating ringing as already-connected — a duration timer or "on call" indicator should start at active, not ringing.
Connection resilience
- Registration refresh: handled by
sip.js's own Registerer before the negotiatedexpiresinterval lapses — no extra polling on top of that. - Unexpected unregistration: if the registration itself drops to
Unregistered(without the transport disconnecting), the SDK retries registering up to 5 times, 3 seconds apart, before giving up. - Transport drop: sip.js's own built-in transport reconnect runs first (a handful of attempts a few seconds apart); on top of that, the SDK runs its own backstop — a watchdog that keeps retrying every 10s for as long as it should be connected, plus an immediate retry on the browser's
onlineevent (covers a laptop sleep/wake or an outage longer than sip.js's own attempts). Either way, once reconnected the SDK re-registers automatically if it isn't already registered. - Stuck bridge leg: if
call()originates but the bridge-leg INVITE never arrives within ~15s (e.g. the extension wasn't actually reachable when originated), the call auto-resolves toended(withendReason: "bridge_timeout", after acall_failedwith the same reason) instead of sitting on"connecting"forever.hangup()also works on a call in this state, ending it immediately rather than waiting out the timeout. - Bridge leg ahead of the call id: the gateway can ring the browser before its
POST /callsresponse arrives. The SDK holds such an INVITE until the call id is known and then matches it, instead of mistaking the call's own leg for an unrelated incoming call. - What's deliberately not covered: a registration removed directly server-side (e.g. an admin flushing the registrar cache) sends no SIP message to the client at all, so nothing above can detect it until the next natural refresh or an actual failed registration attempt — this is a genuinely silent case, not something the watchdog above can help with (it reacts to a signaled disconnect; this has none). Closing it properly would need a signal outside SIP itself (e.g. your backend checking the registrar via ESL).
- Already-established calls are left alone: a transient disconnect never force-ends a call that's already bridged — only a call still waiting on its bridge leg is treated as recoverable. An established call's media is independent of the signaling transport once negotiated, so a signaling blip doesn't mean the call died.
- Agent tab/browser closing mid-call:
pagehidefires the same way whether the agent closes just the tab, closes the whole browser, or navigates away — the SDK reacts to it with two independent best-effort signals: a SIPBYEover the still-open WS, and akeepalive: truecall to/calls/:id/end(the browser explicitly keeps trying this one even after the page is gone, so it's the more reliable of the two). This usually ends the customer's leg on a deliberate close. It does not cover a browser crash, force-quit, or sudden loss of network —pagehidenever fires for those, and the customer's leg is left connected with no agent on it until the gateway's own transport/RTP timeout (if any) clears it. See "Known limitations" below.
ICE servers (NAT traversal)
SessionInfo.iceServers comes from the gateway's POST /partner-api/v1/session response (ice_servers) and is applied automatically when the SDK builds its UserAgent — no config needed on the SDK side. The gateway defaults to a public STUN server; set PARTNER_STUN_URLS there to override, and add TURN once available for agents behind symmetric NAT/strict firewalls (STUN alone won't help them).
Known limitations
- The widget's "incoming call" UI doesn't yet surface the caller's number once answered as an active call — cosmetic only, the call itself works.
- No TURN relay yet — only STUN. Agents behind symmetric NAT or strict corporate firewalls may still fail to establish the WebRTC leg.
- Hold is implemented via hand-rolled SDP direction mangling — whether the far end actually hears hold music depends on the FreeSWITCH channel's hold-music configuration for that domain/extension.
- A registration removed directly server-side (bypassing SIP signaling entirely) isn't detected until the next natural refresh — see "Connection resilience" above.
setDisposition()records an outcome on Belsmart's partner-call tracking record only — it does not yet update Belsmart's own CDR, lead status, or reporting. Wiring this into Belsmart's own reporting is coming soon.- Conference participants'
callerIdNameis always a generic placeholder from FreeSWITCH ("Outbound Call"), never a real per-party name — the roster relies on theleadNameyou pass intoaddToConference(), falling back to the raw number. listConferenceParticipants()has no live/push updates of its own — membership and mute/hold state are only as fresh as the last call to it (the built-in widget covers this with its own polling; a custom UI needs to poll or re-call it itself).- Attended transfer has no built-in widget UI (a deliberate scope choice, not a bug) — only usable via a custom UI today.
- A browser crash/force-quit/sudden network loss mid-call leaves the customer's leg connected with no agent on it — the
pagehidebest-effort hangup (see "Connection resilience") only covers a deliberate tab/browser close or navigation. Fully closing this gap needs a gateway-side keepalive/RTP timeout, which is outside the SDK's control. - Whether
POST /calls/:id/end(used by thepagehidefallback above) actually terminates the live FreeSWITCH channel, or only records CDR metadata, is unconfirmed — seePARTNER-INTEGRATION-QA.md. If it's metadata-only, thekeepalivebeacon reports the call as ended without truly disconnecting the customer, and the SIPBYEremains the only signal that can actually hang it up.
Changelog
0.12.0
Fixed
- Outbound calls could fail when FreeSWITCH rang the agent's browser before the gateway's
POST /callsresponse (with the call id) arrived. The SDK took the call's own leg for an unrelated incoming call, so the call either sat until the 15s bridge timeout or was rejected (SIP 480). The SDK now holds that INVITE until the call id is known.
Added
CallFailedInfo.reason(CallFailureReason) andCallFailedInfo.callId, so a CRM can tell failures apart:sip_not_registered,gateway_rejected,gateway_unreachable,bridge_timeout,sip_disconnected.call_failednow also fires whencall()is refused because the softphone isn't connected (it throws the newBelsmartCallErrorwithreason: "sip_not_registered"), and when an accepted call never reaches the agent (bridge_timeout/sip_disconnected).CallInfo.endReason(CallEndReason) on"ended"when the agent's own leg never connected.
0.11.0
Added
- Pause:
client.setStatus(),client.getStatus(), the"status_changed"event,SessionInfo.paused, and a Pause / Resume button in the widget. Needs gateway endpointPUT /partner-api/v1/session/status. - Campaign switching:
client.listCampaigns(),client.getCampaign(),client.setCampaign(campaignUuid), the"campaign_changed"event andSessionInfo.campaign. The built-in widget has the campaign picker under a settings (gear) icon in its header. Needs gateway endpointsGET /partner-api/v1/campaignsandPUT /partner-api/v1/session/campaign. BelsmartCrmClient.listDispositions(credentials, agentUuid?)— optionalagentUuidreturns the dispositions of that agent's picked campaign.- Custom caller ID:
CallOptions.callerId,CampaignInfo.allowCustomCallerId,client.isCustomCallerIdAllowed(), and a "Your caller ID" field in the widget for allowed campaigns. Needs the gateway's Allow Custom Caller ID permission (master admin).
Fixed
- Agent-to-agent transfers (and conferences) from another partner-SDK agent no longer fail: FreeSWITCH carries the transferring agent's
P-uniqueIdonto the leg it sends the receiving agent, and the receiving SDK rejected any unexpectedP-uniqueIdas a stale bridge leg of its own (486). Only this device's own recent call ids are treated as stale now; the transfer arrives as a normal"incoming"call.
0.9.0
Added
session_expiredevent — fires when a REST call 401s with a gateway-confirmederror: "session_expired"body, distinguishing an expired session from any other request failure (SessionExpiredError, exported from the client's internals).- Automatic session refresh: when constructed with
apiKey/apiSecret(not a pre-fetchedBelsmartCrmSessionConfig), the SDK silently re-mints a new session at ~90% of the current one's TTL, so a 12h shift-length session should now rarely, if ever, actually hit expiry.session_expiredstill fires for the cases auto-refresh can't cover — aBelsmartCrmSessionConfighas no secret in the browser to remint with, or auto-refresh itself exhausts its retries. - A call-active heartbeat (
PATCH /calls/:id/heartbeat, ~20s) sent for the duration of every call, so the gateway can tell a crashed/force-closed browser apart from a call that's just quiet, and force-end an abandoned customer leg (~60-80s) instead of leaving it connected indefinitely — closes the gap noted in 0.8.1's "Known limitations" for the crash/force-quit/ network-loss case. - A session-presence heartbeat (
PATCH /session/heartbeat, ~60s, independent of any call) plus an explicit best-effort sign-off (POST /session/offline) ondestroy()/pagehide, so the gateway's live dashboard reflects this agent's online/idle/logged-out state with the same fidelity as its browser extension.
0.8.1
Added
BelsmartCrmSessionConfig— constructBelsmartCrmClientwith a pre-fetchedSessionInfoinstead ofapiKey/apiSecret, so a backend-side session exchange (POST /partner-api/v1/session) can keep the tenant secret out of the browser entirely. See "KeepingapiSecretoff the browser".ApiClient.createSession()/browser-side key pair usage is unchanged and still supported for simpler integrations.- Best-effort call termination on the browser's
pagehideevent (agent tab/browser close or navigation, mid-call) — sends both a SIPBYEover the WS and akeepalive: truePOST /calls/:id/end, to mitigate the customer's leg being left connected with no agent on it. Doesn't cover a crash/force-quit/network loss; see "Connection resilience" and "Known limitations".
Fixed
- A denied/blocked/missing microphone (or a mic already in use by another application) no longer leaves a call silently stuck on
"connecting"/"ringing"forever. It's now caught wheresip.jsactually requests the microphone (accepting the bridge-leg INVITE forcall(), orIncomingCall.answer()), and reported as a real"ended"plus a clear"error"event whose message names the actual problem (permission denied, no device, device busy) instead of surfacing nothing at all.
0.7.0
Added
client.getCallCdr(callId?)— the gateway's own CDR for a completed call.client.getCallRecording(callId?)— the recording URL for a completed call, once the gateway has finished processing it.
Fixed
- The
"ended"event now fires only after the gateway has recorded the call'sended_at/duration(the SDK now awaits its ownendCall()report before emitting), instead of firing immediately and reporting that in the background. Previously, callinggetCallCdr()/getCallRecording()from inside an"ended"handler could race that in-flight report and see a call that looked answered but not yet ended. This delays"ended"by one network round-trip to the gateway (normally well under 100ms) — if you were relying on it firing instantaneously for UI feedback, account for that small added latency.
0.6.0
Added
- A country-code selector on the built-in widget's dial pad, pre-filled from
client.getDefaultCountryCode()(the campaign's own country code, tenant portal) but always editable for a one-off call to a different country.call()/addToConference()/startConsult()themselves are unaffected — they still dialtoNumberexactly as given. client.getDefaultCountryCode().
Fixed
- Tightened the customer-answer detection poll (gateway and SDK sides) from 1.5s to 400ms — cut the delay between the customer actually answering and the widget's duration timer starting from up to ~3s down to well under a second.
0.5.0
Added
- Conference calling:
addToConference(),hangupAll(),listConferenceParticipants(), per-participant mute/hold/kick, and a roster UI in the built-in widget — with continuous background refresh (every 5s) so someone hanging up on their own drops off the roster automatically. - Attended transfer:
startConsult(),completeTransfer(),cancelConsult()(SDK-only, no built-in widget UI yet). - A real
"ringing"call state, distinct from the agent's own leg connecting —"active"now fires only once the customer actually answers (detected server-side; see "Call lifecycle" above). This is a behavior change from earlier versions, where"active"fired as soon as your own leg connected. - DTMF keypad button in the built-in widget (
sendDtmf()itself already existed). client.getAgentLabel().debugconfig option and the SDK's own structured internal logging, replacing sip.js's raw wire-level SIP logs (always suppressed now, regardless ofdebug).
Fixed
- The built-in widget's buttons could go permanently unresponsive after the widget was dragged even once (a capture-phase click guard never reset its flag after first use).
- The widget rebuilt its entire DOM every second just to tick the duration display, which could occasionally eat a button click if a click's mousedown/mouseup straddled a rebuild.
- sip.js's own built-in transport reconnect never actually ran at all —
reconnectionAttempts/reconnectionDelaywere set on the wrong options object (transportOptionsinstead of top-levelUserAgentOptions), so the effective value silently stayed at sip.js's default of0("never attempt"). Corrected, and backed by the new watchdog/online-event mechanism described in "Connection resilience". - A stale/abandoned call attempt's INVITE (e.g. one that arrived late after you'd already hung up or moved on) could be misclassified as a genuine new incoming call. Now matched exactly against the
P-uniqueIdheader Belsmart stamps on every self-originated bridge-leg INVITE, instead of a timing-window guess. - Holding a conference participant also showed them as muted — FreeSWITCH sets
can_speak: falseas a side effect of hold, which was being read as an explicit mute. - Call duration (both the stored value and, now that
"active"means true answer, the widget's live timer) was measured from whencall()was invoked, not from when the customer actually answered — could overstate duration by the full ring time. - A party added via
addToConference()or consulted viastartConsult()could join already muted — FreeSWITCH's default conference profile joins non-moderator members muted, which nothing in the gateway was correcting for. The gateway now waits for them to join and explicitly unmutes them.
Building
npm install
npm run build # outputs dist/index.js (cjs), dist/index.mjs (esm), dist/index.global.js (iife)