@tetrax/sdk
v1.0.3
Published
Tetrax CPaaS — Multi-product SDK. Voice (real-time audio rooms), Video (room management), SMS (REST API), and Call API (OTP voice calls) for web and React Native.
Maintainers
Readme
@tetrax/sdk
Tetrax CPaaS — Multi-Product Client SDK · v1.0.2
Client SDK for the Tetrax Communications Platform as a Service (CPaaS). Provides JavaScript/TypeScript clients for Voice, SMS, Video, Call, and TTS APIs — works in web browsers and React Native.
Platform: Tetrax CPaaS (tetrax.in)
Product: Voice API ● Available Now
SMS API ● Available Now
Video API ● Available Now
Call API ● Available Now
TTS API ● Available NowInstallation
npm install @tetrax/sdkOr reference locally (monorepo / development):
"dependencies": {
"@tetrax/sdk": "file:../tetrax-sdk"
}Named Exports
import { Voice } from '@tetrax/sdk'; // Real-time audio rooms
import { Sms } from '@tetrax/sdk'; // DLT-compliant SMS send & delivery tracking
import { Video } from '@tetrax/sdk'; // Video room management
import { Call } from '@tetrax/sdk'; // Programmatic OTP voice calls
import { Tts } from '@tetrax/sdk'; // Neural text-to-speech synthesisBackward compatible:
import { TetraxVoice } from '@tetrax/sdk'still works — it is an alias ofVoice.
Quick Start — Voice
import { Voice } from '@tetrax/sdk';
// 1. Initialize
const voice = new Voice({
apiKey: 'trx_voice_your_key_here',
apiUri: 'https://video.tetrax.in' // or your self-hosted server
});
// 2. Register event listeners
voice.on('track', ({ stream, userId }) => {
const audio = new Audio();
audio.srcObject = stream;
audio.play();
});
voice.on('user-joined', ({ userId }) => console.log(`${userId} joined`));
voice.on('user-left', ({ userId }) => console.log(`${userId} left`));
voice.on('user-muted', ({ userId }) => { /* update UI */ });
voice.on('user-unmuted', ({ userId }) => { /* update UI */ });
voice.on('warning', (msg) => console.warn(msg));
// 3. Obtain a short-lived token from your backend:
// POST /v1/token { apiKey, userId } → { token }
const { token } = await fetch('/api/voice-token').then(r => r.json());
// 4. Connect and join
await voice.connect(token);
await voice.joinRoom('room_a4f91bc2d8e3');
// 5. Mic controls
await voice.mute();
await voice.unmute();
// 6. Leave
await voice.leaveRoom();
voice.disconnect();Quick Start — SMS
import { Sms } from '@tetrax/sdk';
const sms = new Sms({
apiKey: 'trx_sms_your_key_here',
apiUri: 'https://APIURL.tetrax.in',
token: customerJwt, // required for getLogs / getStats
});
// Send a DLT-compliant message
const result = await sms.send({
to: '+919876543210',
from: 'TETRAX', // optional — falls back to server default
templateId: '1207162693910474054',
variables: ['123456', '5'], // OTP code, expiry minutes
});
// → { messageId, status, smsCount, totalCharge, walletBalance }
// Send bulk DLT-compliant messages
const bulkResult = await sms.sendBulk({
to: ['+919876543210', '+919876543211'],
from: 'TETRAX',
templateId: '1207162693910474054',
variables: ['123456', '5'],
});
// → { totalRecipients, queued, failed, totalCharge, walletBalance, messageIds }
// Dashboard helpers (require access token)
const logs = await sms.getLogs();
const stats = await sms.getStats();
// → { total, messages } and { total, delivered, failed, sent, queued }Quick Start — Video
import { Video } from '@tetrax/sdk';
const video = new Video({
apiKey: 'trx_video_your_key_here',
apiUri: 'https://video.tetrax.in',
token: customerJwt, // required for getLiveRooms / closeRoom / getStats
});
// Create a video room (API key auth)
const room = await video.createRoom({ name: 'Team Standup', maxParticipants: 25 });
// → { roomId, name, status, maxParticipants, createdAt }
// Dashboard helpers (access token required)
const rooms = await video.getLiveRooms();
const ok = await video.closeRoom(room.roomId);
const stats = await video.getStats();
// → { total, active }Quick Start — Call
import { Call } from '@tetrax/sdk';
const callApi = new Call({
apiKey: 'trx_call_your_key_here',
baseUrl: 'https://APIURL.tetrax.in/v1',
});
// Send an OTP voice call
const result = await callApi.sendOtpCall({
phone: '+919876543210',
otp: '4324',
language: 'hi-IN',
serviceName: 'Acme Bank',
});
// → { success, callId, message, call }
// Dashboard helpers
const history = await callApi.getCallHistory({ limit: 10 });
const stats = await callApi.getAnalytics();
const health = await callApi.health();Quick Start — TTS
import { Tts } from '@tetrax/sdk';
const tts = new Tts({
apiKey: 'trx_tts_your_key_here',
apiUri: 'https://APIURL.tetrax.in',
token: customerJwt, // required for getJobs / getAnalytics
});
// One line — synthesize natural text into hosted audio
const { job, meta, pricing } = await tts.synthesize({
text: 'Hello from Tetrax TTS!',
voice: 'alloy', // default | alloy | echo | fable | onyx | nova | shimmer
format: 'mp3', // mp3 | pcm
});
// → { success, job: { audio_url, characters, charge }, meta, pricing }
// Estimate the wallet charge before synthesizing (no API call)
const { characters, estimatedCharge } = tts.estimateCost('Hello, world!');
// → { characters: 13, estimatedCharge: 0.013 }
// Dashboard helpers (require access token)
const jobs = await tts.getJobs();
const stats = await tts.getAnalytics();
const voices = await tts.getVoices();API Reference — Voice
new Voice(options) (alias: new TetraxVoice(options))
| Option | Type | Required | Description |
|---|---|---|---|
| apiKey | string | ✓ | Your trx_voice_ API key from the Tetrax Console |
| apiUri | string | ✓ | Signaling server URL (e.g. https://api.tetrax.io) |
| socketOptions | object | — | Extra options passed to socket.io-client |
| mediaDevices | object | — | Custom mediaDevices implementation (React Native) |
| MediaStream | class | — | Custom MediaStream class (React Native) |
Methods
| Method | Returns | Description |
|---|---|---|
| connect(token) | Promise<void> | Connect to signaling server using a voice token |
| joinRoom(roomId, opts?) | Promise<res> | Join a room and set up audio send/receive |
| mute() | Promise<void> | Pause local audio producer + emit mute signal |
| unmute() | Promise<void> | Resume local audio producer + emit unmute signal |
| leaveRoom() | Promise<void> | Leave room, stop local tracks, close transports |
| disconnect() | void | Disconnect from signaling server entirely |
joinRoom(roomId, options?)
| Option | Type | Description |
|---|---|---|
| audioTrack | MediaStreamTrack | Pre-captured audio track (skip getUserMedia) |
| localStream | MediaStream | Pre-captured stream — uses first audio track |
| audioConstraints | object | Passed to getUserMedia if no track/stream provided |
Events
| Event | Payload | Fired when |
|---|---|---|
| connected | — | Successfully connected to signaling server |
| joined | res | Successfully joined a room |
| track | { track, stream, userId, consumerId } | A remote participant's audio track is ready to play |
| user-joined | { userId } | A participant joined the room |
| user-left | { userId } | A participant left the room |
| user-muted | { userId } | A remote participant muted |
| user-unmuted | { userId } | A remote participant unmuted |
| local-mute-changed | boolean | Local mute state changed (true = muted) |
| warning | string | Non-fatal warning (e.g. listen-only mode due to no mic) |
| error | Error | Connection error |
API Reference — Sms
new Sms({ apiKey, apiUri, token? })
| Method | Auth | Returns | Description |
|---|---|---|---|
| send({ to, from, templateId, variables?, webhookUrl? }) | API key | Promise<SmsSendResponse> | Send a single DLT-compliant SMS via POST /v1/sms/send |
| sendBulk({ to, from, templateId, variables?, webhookUrl? }) | API key | Promise<SmsBulkSendResponse> | Send bulk SMS to multiple recipients via POST /v1/sms/bulk-send |
| getStatus(messageId) | API key | Promise<SmsStatusResponse> | Fetch delivery status of a specific message via GET /v1/sms/:messageId/status |
| getLogs(options?) | Token | Promise<SmsLogsResponse> | Retrieve SMS delivery logs via GET /v1/sms/messages |
| getStats() | Token | Promise<SmsStatsResponse> | Retrieve SMS delivery statistics via GET /v1/sms/stats |
API Reference — Video
new Video({ apiKey, apiUri, token? })
| Method | Auth | Returns | Description |
|---|---|---|---|
| createRoom(params?) | API key | Promise<VideoCreateRoomResponse> | Create a new video room via POST /v1/video/rooms |
| getLiveRooms() | Token | Promise<VideoLiveRoomsResponse> | List active video rooms via GET /v1/video/rooms/live |
| closeRoom(roomId) | Token | Promise<boolean> | Close a video room via DELETE /v1/video/rooms/:id |
| getStats() | Token | Promise<VideoStatsResponse> | Retrieve video usage statistics via GET /v1/video/stats |
API Reference — Tts
new Tts({ apiKey, apiUri, token? })
| Method | Auth | Returns | Description |
|---|---|---|---|
| synthesize({ text, voice?, format? }) | API key | Promise<TtsSynthesizeResponse> | Convert text to hosted audio via POST /v1/tts/synthesize |
| estimateCost(text) | — | TtsCostEstimate | Estimate wallet charge (₹0.001/char, min ₹0.01) — no API call |
| getJobs(options?) | Token | Promise<TtsJobsResponse> | Retrieve synthesis history via GET /v1/tts/jobs |
| getAnalytics() | Token | Promise<TtsAnalyticsResponse> | Month-to-date synthesis analytics via GET /v1/tts/analytics |
| getVoices() | — | Promise<TtsVoicesResponse> | List available voice presets via GET /v1/tts/voices |
| health() | — | Promise<TtsHealthResponse> | Check TTS API health via GET /v1/tts/health |
Billing: TTS is wallet-based, billed ₹0.001 per character (minimum ₹0.01 per synthesis). A 10,000-character synthesis costs ₹10. Text is limited to 5,000 characters per request.
API Reference — Call
new Call({ apiKey, baseUrl?, fetchImpl?, debug? })
| Option | Type | Required | Description |
|---|---|---|---|
| apiKey | string | ✓ | Your trx_call_ API key from the Tetrax Console |
| baseUrl | string | — | API base URL (default: https://APIURL.tetrax.in/v1) |
| fetchImpl | function | — | Custom fetch implementation (React Native / Node) |
| debug | boolean | — | Enable debug logging to console (default: false) |
Methods
| Method | Auth | Returns | Description |
|---|---|---|---|
| sendOtpCall({ phone, otp, language?, voice?, serviceName? }) | API key | Promise<CallSendOtpResponse> | Send an OTP via automated voice call via POST /v1/call/otp |
| getAvailableLanguages() | API key | Promise<Language[]> | Get list of available language profiles |
| getAvailableVoices() | API key | Promise<Language[]> | Alias for getAvailableLanguages() |
| getCallHistory(options?) | API key | Promise<CallHistoryResponse> | Fetch OTP call history via GET /v1/call/calls |
| getAnalytics() | API key | Promise<CallAnalyticsResponse> | Get OTP call analytics via GET /v1/call/analytics |
| health() | — | Promise<CallHealthResponse> | Check API health via GET /v1/call/health |
Frontend Implementation Guides
1. Next.js (App Router / Pages Router)
Add serverExternalPackages so Next.js doesn't bundle React Native bindings on the server:
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
serverExternalPackages: ['react-native-webrtc'],
};
export default nextConfig;Use 'use client' components:
'use client';
import { Voice } from '@tetrax/sdk';
export default function VoiceRoom() {
const startCall = async (token) => {
const voice = new Voice({ apiKey: 'trx_voice_xxx', apiUri: 'https://api.tetrax.io' });
voice.on('track', ({ stream }) => {
const audio = new Audio();
audio.srcObject = stream;
audio.autoplay = true;
document.body.appendChild(audio);
});
await voice.connect(token);
await voice.joinRoom('room_demo');
};
return <button onClick={startCall}>Join Voice Room</button>;
}2. React (Vite / Create React App)
Webpack and Vite automatically respect the "browser" field — SDK works out-of-the-box:
import { Voice, Sms, Video } from '@tetrax/sdk';3. React Native
The SDK auto-detects React Native via navigator.product === 'ReactNative' and registers required globals automatically:
import { Voice } from '@tetrax/sdk';
const voice = new Voice({
apiKey: 'trx_voice_xxx',
apiUri: 'http://YOUR_SERVER_IP:5000',
socketOptions: { transports: ['websocket'] }
});
// Pre-captured audio track:
const stream = await mediaDevices.getUserMedia({ audio: true });
await voice.connect(token);
await voice.joinRoom('room_123', { audioTrack: stream.getAudioTracks()[0] });SDK Metadata
import { TETRAX_SDK_INFO, SDK_VERSION } from '@tetrax/sdk';
console.log(TETRAX_SDK_INFO);
// {
// platform: 'tetrax-cpaas',
// version: '1.0.2',
// products: ['voice', 'video', 'sms', 'call', 'tts'],
// }API Key Namespace
| Product | Key Prefix | Status |
|---|---|---|
| Voice API | trx_voice_ | ✅ Available |
| SMS API | trx_sms_ | ✅ Available |
| Video API | trx_video_ | ✅ Available |
| Call API | trx_call_ | ✅ Available |
| TTS API | trx_tts_ | ✅ Available |
Note: The Call API (
trx_call_*) is used for OTP voice calls. You can use theCallclass in the SDK or call the REST API endpoints directly.
Get your API keys from the Tetrax Console → Applications.
Publishing to npm
# Inside tetrax-sdk/
npm login
npm publish --access publicChangelog
v1.0.2
- TTS API: Added
Ttsclient (trx_tts_key prefix) — one-line neural text-to-speech synthesis viasynthesize(), plusestimateCost(),getJobs(),getAnalytics(),getVoices(), andhealth() - Exported
TetraxTTSalias andTTS_VOICESpreset list - Bumped
SDK_VERSIONto1.0.2and addedttstoTETRAX_SDK_INFO.products - Version aligned to 1.0.2 as the current release
v1.3.0 (previously released as 1.3.0; now consolidated under 1.0.2)
- TTS API: Added
Ttsclient (trx_tts_key prefix) — one-line neural text-to-speech synthesis viasynthesize(), plusestimateCost(),getJobs(),getAnalytics(),getVoices(), andhealth() - Exported
TetraxTTSalias andTTS_VOICESpreset list - Bumped
SDK_VERSIONto1.3.0and addedttstoTETRAX_SDK_INFO.products
v1.2.0
- Multi-product SDK: Added
SmsandVideonamed exports alongside existingVoice Voiceis the new canonical class name;TetraxVoiceis kept as a backward-compat alias- Restructured into
src/voice/,src/sms/,src/video/sub-modules - Updated
SDK_VERSIONandTETRAX_SDK_INFO.productsto reflect all three products - Call API documented (
trx_call_key prefix added)
v1.1.5
- Minor dependency updates
v1.1.4
- Fixed Next.js (Turbopack/Webpack) module resolution errors by properly aliasing
react-native-webrtcin the"browser"package field
v1.1.3
- CPaaS rebranding:
TETRAX_SDK_INFOandSDK_VERSIONexports - API key namespace documented (
trx_voice_) - README restructured with full API reference table
v1.1.2
- React Native auto-detection and
react-native-webrtcglobal registration - Pre-captured track/stream support via
joinRoomoptions - Listen-only mode fallback when no microphone is available
License
MIT © Tetrax Inc.
