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 🙏

© 2025 – Pkg Stats / Ryan Hefner

webrtc2-peer

v1.0.0

Published

WebRTC2 Peer - Low-level WebRTC peer connection management for cross-platform real-time communication with signaling, ICE handling, and media streaming

Readme

@webrtc2/peer - WebRTC Peer Connection Management

npm version TypeScript WebRTC

Low-level WebRTC peer connection management - Handle RTCPeerConnection, ICE candidates, signaling, and media streaming for cross-platform real-time communication.

🚀 WebRTC Peer Connection Made Easy

@webrtc2/peer provides the foundational layer for WebRTC applications:

  • 🔗 RTCPeerConnection Management: Create, configure, and manage peer connections
  • 🧊 ICE Handling: Automatic ICE candidate gathering and exchange
  • 📡 Signaling Client: WebSocket-based signaling for connection establishment
  • 🎥 Media Manager: Stream management and media device handling
  • ⚡ Event-Driven: EventEmitter-based architecture for real-time updates
  • 🌐 Cross-Platform: Works in browsers, React Native, and Electron

📦 Installation

npm install @webrtc2/peer

🎯 Quick Start

Basic Peer Connection

import { PeerConnection } from '@webrtc2/peer';

const peer = new PeerConnection({
  iceServers: [
    { urls: 'stun:stun.l.google.com:19302' },
    { 
      urls: 'turn:your-turn-server.com:3478',
      username: 'user',
      credential: 'password'
    }
  ]
});

// Handle connection events
peer.on('connected', () => {
  console.log('Peer connected!');
});

peer.on('stream', (stream) => {
  console.log('Received remote stream:', stream);
});

peer.on('disconnected', () => {
  console.log('Peer disconnected');
});

// Connect to remote peer
await peer.connect('remote-peer-id');

Signaling Client

import { SignalingClient } from '@webrtc2/peer';

const signaling = new SignalingClient('wss://your-signaling-server.com');

signaling.on('offer', async (offer, peerId) => {
  await peer.handleOffer(offer, peerId);
});

signaling.on('answer', async (answer, peerId) => {
  await peer.handleAnswer(answer, peerId);
});

signaling.on('ice-candidate', async (candidate, peerId) => {
  await peer.addIceCandidate(candidate, peerId);
});

await signaling.connect();

Media Manager

import { MediaManager } from '@webrtc2/peer';

const mediaManager = new MediaManager();

// Get user media
const localStream = await mediaManager.getUserMedia({
  video: { width: 1280, height: 720 },
  audio: true
});

// Add stream to peer connection
peer.addStream(localStream);

// Handle device changes
mediaManager.on('device-change', (devices) => {
  console.log('Available devices:', devices);
});

🔧 Advanced Features

Custom ICE Configuration

import { PeerConnection, ICEConfiguration } from '@webrtc2/peer';

const iceConfig: ICEConfiguration = {
  iceServers: [
    { urls: 'stun:stun.l.google.com:19302' },
    { urls: 'stun:stun1.l.google.com:19302' }
  ],
  iceCandidatePoolSize: 10,
  bundlePolicy: 'max-bundle',
  rtcpMuxPolicy: 'require'
};

const peer = new PeerConnection(iceConfig);

Data Channel Support

// Create data channel
const dataChannel = peer.createDataChannel('messages', {
  ordered: true,
  maxRetransmits: 3
});

dataChannel.onopen = () => {
  console.log('Data channel opened');
  dataChannel.send('Hello from peer!');
};

dataChannel.onmessage = (event) => {
  console.log('Received message:', event.data);
};

// Handle incoming data channels
peer.on('datachannel', (channel) => {
  console.log('Received data channel:', channel.label);
});

Connection Statistics

// Get connection stats
const stats = await peer.getStats();

console.log('Connection stats:', {
  bitrate: stats.bitrate,
  packetLoss: stats.packetLoss,
  latency: stats.roundTripTime,
  jitter: stats.jitter
});

// Monitor stats continuously
peer.on('stats', (stats) => {
  if (stats.packetLoss > 0.05) {
    console.warn('High packet loss detected:', stats.packetLoss);
  }
});

🌐 Cross-Platform Usage

React Native Integration

import { PeerConnection } from '@webrtc2/peer';
import { mediaDevices } from 'react-native-webrtc';

// React Native specific media constraints
const peer = new PeerConnection({
  iceServers: [{ urls: 'stun:stun.l.google.com:19302' }]
});

// Get camera stream for React Native
const stream = await mediaDevices.getUserMedia({
  video: {
    width: 640,
    height: 480,
    frameRate: 30,
    facingMode: 'user'
  },
  audio: true
});

peer.addStream(stream);

Electron Desktop

// Electron main process
import { PeerConnection } from '@webrtc2/peer';

const peer = new PeerConnection({
  iceServers: [{ urls: 'stun:stun.l.google.com:19302' }]
});

// Desktop screen sharing
const screenStream = await navigator.mediaDevices.getDisplayMedia({
  video: { mediaSource: 'screen' },
  audio: true
});

peer.addStream(screenStream);

🔧 API Reference

PeerConnection Class

class PeerConnection extends EventEmitter {
  constructor(config: RTCConfiguration);
  
  // Connection management
  connect(peerId: string): Promise<void>;
  disconnect(): void;
  
  // Media handling
  addStream(stream: MediaStream): void;
  removeStream(stream: MediaStream): void;
  
  // Data channels
  createDataChannel(label: string, options?: RTCDataChannelInit): RTCDataChannel;
  
  // Statistics
  getStats(): Promise<RTCStatsReport>;
  
  // Events
  on('connected', callback: () => void): this;
  on('disconnected', callback: () => void): this;
  on('stream', callback: (stream: MediaStream) => void): this;
  on('datachannel', callback: (channel: RTCDataChannel) => void): this;
}

SignalingClient Class

class SignalingClient extends EventEmitter {
  constructor(url: string);
  
  connect(): Promise<void>;
  disconnect(): void;
  
  sendOffer(offer: RTCSessionDescriptionInit, peerId: string): void;
  sendAnswer(answer: RTCSessionDescriptionInit, peerId: string): void;
  sendIceCandidate(candidate: RTCIceCandidateInit, peerId: string): void;
  
  // Events
  on('offer', callback: (offer: RTCSessionDescriptionInit, peerId: string) => void): this;
  on('answer', callback: (answer: RTCSessionDescriptionInit, peerId: string) => void): this;
  on('ice-candidate', callback: (candidate: RTCIceCandidateInit, peerId: string) => void): this;
}

MediaManager Class

class MediaManager extends EventEmitter {
  getUserMedia(constraints: MediaStreamConstraints): Promise<MediaStream>;
  getDisplayMedia(constraints?: DisplayMediaStreamConstraints): Promise<MediaStream>;
  enumerateDevices(): Promise<MediaDeviceInfo[]>;
  
  // Events
  on('device-change', callback: (devices: MediaDeviceInfo[]) => void): this;
}

🐛 Troubleshooting

Common ICE Connection Issues

// Debug ICE connection state
peer.on('ice-connection-state-change', (state) => {
  console.log('ICE connection state:', state);
  
  if (state === 'failed') {
    console.error('ICE connection failed - check TURN servers');
  }
});

// Monitor ICE candidates
peer.on('ice-candidate', (candidate) => {
  console.log('ICE candidate:', candidate);
});

Signaling Connection Problems

signaling.on('error', (error) => {
  console.error('Signaling error:', error);
  
  // Attempt reconnection
  setTimeout(() => {
    signaling.connect();
  }, 5000);
});

signaling.on('disconnect', () => {
  console.warn('Signaling disconnected - attempting reconnection');
});

📚 Related Packages

🤝 Contributing

We welcome contributions! Please see our Contributing Guide for details.

📄 License

MIT License - see LICENSE for details.


Keywords: WebRTC peer connection, RTCPeerConnection, WebRTC signaling, ICE candidates, STUN TURN servers, WebRTC media streaming, peer-to-peer connection, WebRTC JavaScript, WebRTC TypeScript, cross-platform WebRTC