# @webrtc2/peer - WebRTC Peer Connection Management

[![npm version](https://img.shields.io/npm/v/@webrtc2/peer.svg)](https://www.npmjs.com/package/@webrtc2/peer)
[![TypeScript](https://img.shields.io/badge/TypeScript-Ready-blue.svg)](https://typescriptlang.org/)
[![WebRTC](https://img.shields.io/badge/WebRTC-Core-green.svg)](https://webrtc.org/)

**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

```bash
npm install @webrtc2/peer
```

## 🎯 Quick Start

### Basic Peer Connection

```typescript
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

```typescript
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

```typescript
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

```typescript
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

```typescript
// 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

```typescript
// 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

```typescript
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

```typescript
// 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

```typescript
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

```typescript
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

```typescript
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

```typescript
// 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

```typescript
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

- [@webrtc2/client](../client) - React hooks and components
- [@webrtc2/types](../types) - TypeScript definitions
- [@webrtc2/utils](../utils) - Utility functions
- [@webrtc2/config](../config) - Configuration management

## 🤝 Contributing

We welcome contributions! Please see our [Contributing Guide](../../CONTRIBUTING.md) for details.

## 📄 License

MIT License - see [LICENSE](../../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
