npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

xavia-webrtc-sdk

v1.0.0

Published

Complete backend SDK for Xavia Calling Service - REST API client and Socket.IO client for Node.js applications

Readme

Xavia Calling Backend SDK

Complete backend SDK for Xavia Calling Service integration. This SDK provides both REST API client and Socket.IO client for full WebRTC functionality in Node.js applications.

🚀 Features

  • REST API Client - Complete HTTP API integration
  • Socket.IO Client - Real-time WebRTC signaling
  • TypeScript Support - Full type definitions
  • Call Management - Create, join, leave calls
  • User Management - Online users, invitations
  • WebRTC Signaling - Offer/Answer/ICE handling
  • Server Helpers - Configuration utilities
  • Error Handling - Comprehensive error management
  • Event System - Flexible event handlers

📦 Installation

npm install @xavia-calling/backend-sdk

🔧 Quick Start

REST API Client

import { WebRTCClient } from '@xavia-calling/backend-sdk';

const client = new WebRTCClient({
  baseURL: 'http://localhost:4009'
});

// Create a call
const call = await client.createCall({
  callType: 'video',
  isGroup: false,
  maxParticipants: 2
});

console.log('Call created:', call.callId);

// Join the call
const participant = await client.joinCall(call.callId, {
  userName: 'John Doe',
  userId: 'user123'
});

console.log('Joined as:', participant.participantId);

Socket.IO Client

import { WebRTCSocketClient } from '@xavia-calling/backend-sdk';

const socketClient = new WebRTCSocketClient({
  serverUrl: 'http://localhost:4009',
  userId: 'user123',
  userName: 'John Doe'
});

// Set up event handlers
socketClient.setEventHandlers({
  onIncomingCall: (data) => {
    console.log(`Incoming ${data.callType} call from ${data.callerName}`);
    
    // Accept the call
    socketClient.acceptCall(data.callId, data.callerId);
  },
  
  onCallAccepted: (data) => {
    console.log(`Call accepted by ${data.acceptedByName}`);
  },
  
  onUserOnline: (users) => {
    console.log(`${users.length} users online`);
  },
  
  onSignal: (data) => {
    console.log('WebRTC signal received:', data.type);
    // Handle WebRTC signaling (offer, answer, ICE candidates)
  }
});

// Connect to the service
await socketClient.connect();

📚 API Reference

WebRTCClient (REST API)

Constructor

new WebRTCClient(config: WebRTCClientConfig)

Config Options:

  • baseURL (string) - WebRTC service URL
  • timeout? (number) - Request timeout in ms (default: 10000)
  • apiKey? (string) - API key for authentication
  • headers? (object) - Additional headers

Methods

createCall(options?)

Create a new call.

const call = await client.createCall({
  callType: 'video',    // 'audio' | 'video' | 'screen'
  isGroup: false,       // boolean
  maxParticipants: 10   // number
});
getCall(callId)

Get call information.

const callInfo = await client.getCall('call-123');
console.log('Participants:', callInfo.participantCount);
joinCall(callId, options)

Join a call.

const participant = await client.joinCall('call-123', {
  userName: 'John Doe',
  userId: 'user456'     // optional
});
leaveCall(callId, participantId)

Leave a call.

await client.leaveCall('call-123', 'participant-456');
getParticipants(callId)

Get all participants in a call.

const participants = await client.getParticipants('call-123');
participants.participants.forEach(p => {
  console.log(`- ${p.name} (joined: ${p.joinedAt})`);
});
getHealth()

Check server health.

const health = await client.getHealth();
console.log('Server status:', health.status);
console.log('Active calls:', health.activeCalls);
getTurnConfig()

Get TURN server configuration.

const turnConfig = await client.getTurnConfig();
console.log('ICE servers:', turnConfig.iceServers);
testConnection()

Test connection to the service.

const isConnected = await client.testConnection();
if (isConnected) {
  console.log('✅ Connected to WebRTC service');
}

WebRTCSocketClient (Socket.IO)

Constructor

new WebRTCSocketClient(config: WebRTCSocketConfig)

Config Options:

  • serverUrl (string) - WebRTC service URL
  • userId (string) - User ID
  • userName (string) - User name
  • autoConnect? (boolean) - Auto-connect on creation (default: true)
  • reconnection? (boolean) - Enable reconnection (default: true)
  • reconnectionAttempts? (number) - Max reconnection attempts (default: 5)
  • reconnectionDelay? (number) - Reconnection delay in ms (default: 1000)
  • timeout? (number) - Connection timeout in ms (default: 20000)

Methods

connect()

Connect to the WebRTC service.

await socketClient.connect();
console.log('Connected to WebRTC service');
disconnect()

Disconnect from the service.

socketClient.disconnect();
setEventHandlers(handlers)

Set event handlers.

socketClient.setEventHandlers({
  onIncomingCall: (data) => {
    console.log(`Incoming call from ${data.callerName}`);
  },
  onCallAccepted: (data) => {
    console.log(`Call accepted by ${data.acceptedByName}`);
  },
  onCallRejected: (data) => {
    console.log(`Call rejected by ${data.rejectedByName}`);
  },
  onUserOnline: (users) => {
    console.log(`${users.length} users online`);
  },
  onSignal: (data) => {
    // Handle WebRTC signaling
    console.log('Signal received:', data.type);
  },
  onError: (error) => {
    console.error('Socket error:', error.message);
  }
});
joinCall(callId, participantId, userName?)

Join a call room for real-time communication.

await socketClient.joinCall('call-123', 'participant-456');
sendSignal(callId, signal, type, targetId?)

Send WebRTC signaling data.

// Send offer to specific participant
socketClient.sendSignal('call-123', offerData, 'offer', 'participant-456');

// Broadcast ICE candidate to all participants
socketClient.sendSignal('call-123', iceCandidate, 'ice-candidate');
sendCallInvitation(targetUserId, callId, callType, callerName?)

Send call invitation to another user.

const result = await socketClient.sendCallInvitation(
  'user456',
  'call-123',
  'video'
);

if (result.success) {
  console.log('Invitation sent successfully');
}
acceptCall(callId, callerId)

Accept an incoming call.

socketClient.acceptCall('call-123', 'caller-456');
rejectCall(callId, callerId)

Reject an incoming call.

socketClient.rejectCall('call-123', 'caller-456');
leaveCall(callId?, reason?)

Leave a call.

socketClient.leaveCall('call-123', 'user ended call');

WebRTCServerHelper

Utility class for server configuration.

import { WebRTCServerHelper } from '@xavia-calling/backend-sdk';

const helper = new WebRTCServerHelper({
  port: 4009,
  turnUrls: ['turn:your-server.com:3478'],
  turnUsername: 'username',
  turnCredential: 'password'
});

// Get environment variables
const envVars = helper.getEnvConfig();

// Get ICE server configuration
const iceConfig = helper.getIceServers();

// Validate configuration
const validation = helper.validateConfig();
if (!validation.isValid) {
  console.error('Configuration errors:', validation.errors);
}

// Generate .env file
const envContent = helper.generateEnvFile();
require('fs').writeFileSync('.env', envContent);

🎯 Complete Example

Here's a complete example showing both REST API and Socket.IO usage:

import { WebRTCClient, WebRTCSocketClient } from '@xavia-calling/backend-sdk';

class XaviaCallingService {
  private client: WebRTCClient;
  private socketClient: WebRTCSocketClient;
  private currentCall: string | null = null;

  constructor(serverUrl: string, userId: string, userName: string) {
    // Initialize REST client
    this.client = new WebRTCClient({
      baseURL: serverUrl
    });

    // Initialize Socket client
    this.socketClient = new WebRTCSocketClient({
      serverUrl,
      userId,
      userName
    });

    this.setupEventHandlers();
  }

  private setupEventHandlers() {
    this.socketClient.setEventHandlers({
      onIncomingCall: async (data) => {
        console.log(`📞 Incoming ${data.callType} call from ${data.callerName}`);
        
        // Auto-accept for demo (you'd show UI here)
        this.socketClient.acceptCall(data.callId, data.callerId);
        this.currentCall = data.callId;
      },

      onCallAccepted: async (data) => {
        console.log(`✅ Call accepted by ${data.acceptedByName}`);
        
        // Join the call room
        const participant = await this.client.joinCall(data.callId, {
          userName: 'Current User'
        });
        
        await this.socketClient.joinCall(
          data.callId, 
          participant.participantId
        );
      },

      onSignal: (data) => {
        console.log(`📡 WebRTC signal: ${data.type} from ${data.fromId}`);
        // Handle WebRTC signaling here
        // This is where you'd process offers, answers, and ICE candidates
      },

      onUserOnline: (users) => {
        console.log(`👥 ${users.length} users online:`, 
          users.map(u => u.userName).join(', '));
      },

      onError: (error) => {
        console.error('❌ Socket error:', error.message);
      }
    });
  }

  async connect() {
    await this.socketClient.connect();
    console.log('🔌 Connected to Xavia Calling service');
  }

  async createCall(callType: 'audio' | 'video' = 'video') {
    const call = await this.client.createCall({
      callType,
      isGroup: false
    });

    this.currentCall = call.callId;
    console.log(`📞 Call created: ${call.callId}`);
    return call;
  }

  async inviteUser(targetUserId: string, callType: 'audio' | 'video' = 'video') {
    if (!this.currentCall) {
      const call = await this.createCall(callType);
      this.currentCall = call.callId;
    }

    const result = await this.socketClient.sendCallInvitation(
      targetUserId,
      this.currentCall,
      callType
    );

    if (result.success) {
      console.log(`📤 Invitation sent to ${targetUserId}`);
    } else {
      console.error(`❌ Failed to send invitation: ${result.error}`);
    }

    return result;
  }

  async endCall() {
    if (this.currentCall) {
      this.socketClient.leaveCall(this.currentCall, 'call ended');
      this.currentCall = null;
      console.log('📞 Call ended');
    }
  }

  disconnect() {
    this.socketClient.disconnect();
    console.log('🔌 Disconnected from Xavia Calling service');
  }
}

// Usage
async function main() {
  const xaviaCalling = new XaviaCallingService(
    'http://localhost:4009',
    'user123',
    'John Doe'
  );

  await xaviaCalling.connect();

  // Create a call and invite another user
  await xaviaCalling.inviteUser('user456', 'video');

  // End call after 30 seconds (for demo)
  setTimeout(() => {
    xaviaCalling.endCall();
    xaviaCalling.disconnect();
  }, 30000);
}

main().catch(console.error);

🔧 Configuration

Environment Variables

The SDK works with these environment variables:

# Server Configuration
PORT=4009
HOST=0.0.0.0
NODE_ENV=production

# TURN Server Configuration
TURN_URLS=turn:your-server.com:3478
TURN_USERNAME=username
TURN_CREDENTIAL=password

# Redis Configuration (for clustering)
USE_REDIS=false
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_PASSWORD=optional

Server Helper

Use WebRTCServerHelper to generate configuration:

import { WebRTCServerHelper } from '@xavia-calling/backend-sdk';

// Get recommended config for your scale
const config = WebRTCServerHelper.getRecommendedConfig('medium');
const helper = new WebRTCServerHelper(config);

// Generate .env file
const envContent = helper.generateEnvFile();
console.log(envContent);

🚨 Error Handling

The SDK provides comprehensive error handling:

try {
  const call = await client.createCall();
} catch (error) {
  if (error.message.includes('Network error')) {
    console.error('Connection failed - check server URL');
  } else if (error.message.includes('HTTP 404')) {
    console.error('API endpoint not found');
  } else {
    console.error('Unexpected error:', error.message);
  }
}

// Socket errors
socketClient.setEventHandlers({
  onError: (error) => {
    console.error('Socket error:', error.message);
    // Handle reconnection, show user message, etc.
  }
});

📝 TypeScript Support

The SDK is written in TypeScript and provides full type definitions:

import { 
  WebRTCClient, 
  WebRTCSocketClient,
  CallType,
  CreateCallResponse,
  CallEventHandlers 
} from '@xavia-calling/backend-sdk';

// All types are available for import
const handlers: CallEventHandlers = {
  onIncomingCall: (data) => {
    // data is fully typed
    console.log(data.callType); // 'audio' | 'video' | 'screen'
  }
};

🤝 Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

📄 License

MIT

👨‍💻 Author

Zohaib Rana - Xavia Calling

🏢 Company

Xavia Calling - Advanced WebRTC Communication Solutions


For more examples and advanced usage, check the /examples directory in the main repository.