mirror of
https://github.com/xtr-dev/rondevu-client.git
synced 2025-12-10 10:53:24 +00:00
Compare commits
22 Commits
v0.7.2
...
895e7765f9
| Author | SHA1 | Date | |
|---|---|---|---|
| 895e7765f9 | |||
| 49d3984640 | |||
| 6057c3c582 | |||
| 255fe42a43 | |||
| 83fd0f84a4 | |||
| aa53d5bc3d | |||
| f5aa6e2189 | |||
| afdca83640 | |||
| c7ea1b9b8f | |||
| 660663945e | |||
| f119a42fcd | |||
| cd55072acb | |||
| 26f71e7a2b | |||
| 0ac1f94502 | |||
| 3530213870 | |||
| e052464482 | |||
| 53206d306b | |||
| c860419e66 | |||
| e22e74fb74 | |||
| 135eda73cf | |||
| 8d7075ccc4 | |||
| db8f0f4ced |
333
README.md
333
README.md
@@ -1,14 +1,15 @@
|
|||||||
# @xtr-dev/rondevu-client
|
# Rondevu Client
|
||||||
|
|
||||||
[](https://www.npmjs.com/package/@xtr-dev/rondevu-client)
|
[](https://www.npmjs.com/package/@xtr-dev/rondevu-client)
|
||||||
|
|
||||||
🌐 **Topic-based peer discovery and WebRTC signaling client**
|
🌐 **Topic-based peer discovery and WebRTC signaling client**
|
||||||
|
|
||||||
TypeScript/JavaScript client for Rondevu, providing topic-based peer discovery, stateless authentication, and complete WebRTC signaling.
|
TypeScript/JavaScript client for Rondevu, providing topic-based peer discovery, stateless authentication, and complete WebRTC signaling with trickle ICE support.
|
||||||
|
|
||||||
**Related repositories:**
|
**Related repositories:**
|
||||||
- [rondevu-server](https://github.com/xtr-dev/rondevu) - HTTP signaling server
|
- [@xtr-dev/rondevu-client](https://github.com/xtr-dev/rondevu-client) - TypeScript client library ([npm](https://www.npmjs.com/package/@xtr-dev/rondevu-client))
|
||||||
- [rondevu-demo](https://rondevu-demo.pages.dev) - Interactive demo
|
- [@xtr-dev/rondevu-server](https://github.com/xtr-dev/rondevu-server) - HTTP signaling server ([npm](https://www.npmjs.com/package/@xtr-dev/rondevu-server), [live](https://api.ronde.vu))
|
||||||
|
- [@xtr-dev/rondevu-demo](https://github.com/xtr-dev/rondevu-demo) - Interactive demo ([live](https://ronde.vu))
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -16,9 +17,12 @@ TypeScript/JavaScript client for Rondevu, providing topic-based peer discovery,
|
|||||||
|
|
||||||
- **Topic-Based Discovery**: Find peers by topics (e.g., torrent infohashes)
|
- **Topic-Based Discovery**: Find peers by topics (e.g., torrent infohashes)
|
||||||
- **Stateless Authentication**: No server-side sessions, portable credentials
|
- **Stateless Authentication**: No server-side sessions, portable credentials
|
||||||
|
- **Protected Connections**: Optional secret-protected offers for access control
|
||||||
- **Bloom Filters**: Efficient peer exclusion for repeated discoveries
|
- **Bloom Filters**: Efficient peer exclusion for repeated discoveries
|
||||||
- **Multi-Offer Management**: Create and manage multiple offers per peer
|
- **Multi-Offer Management**: Create and manage multiple offers per peer
|
||||||
- **Complete WebRTC Signaling**: Full offer/answer and ICE candidate exchange
|
- **Complete WebRTC Signaling**: Full offer/answer and ICE candidate exchange
|
||||||
|
- **Trickle ICE**: Send ICE candidates as they're discovered (faster connections)
|
||||||
|
- **State Machine**: Clean state-based connection lifecycle
|
||||||
- **TypeScript**: Full type safety and autocomplete
|
- **TypeScript**: Full type safety and autocomplete
|
||||||
|
|
||||||
## Install
|
## Install
|
||||||
@@ -29,38 +33,45 @@ npm install @xtr-dev/rondevu-client
|
|||||||
|
|
||||||
## Quick Start
|
## Quick Start
|
||||||
|
|
||||||
The easiest way to use Rondevu is with the high-level `RondevuConnection` class, which handles all WebRTC connection complexity including offer/answer exchange, ICE candidates, and connection lifecycle.
|
|
||||||
|
|
||||||
### Creating an Offer (Peer A)
|
### Creating an Offer (Peer A)
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
import { Rondevu } from '@xtr-dev/rondevu-client';
|
import { Rondevu } from '@xtr-dev/rondevu-client';
|
||||||
|
|
||||||
|
// Initialize client and register
|
||||||
const client = new Rondevu({ baseUrl: 'https://api.ronde.vu' });
|
const client = new Rondevu({ baseUrl: 'https://api.ronde.vu' });
|
||||||
await client.register();
|
await client.register();
|
||||||
|
|
||||||
// Create a connection
|
// Create peer connection
|
||||||
const conn = client.createConnection();
|
const peer = client.createPeer();
|
||||||
|
|
||||||
// Set up event listeners
|
// Set up event listeners
|
||||||
conn.on('connected', () => {
|
peer.on('state', (state) => {
|
||||||
console.log('Connected to peer!');
|
console.log('Peer state:', state);
|
||||||
|
// States: idle → creating-offer → waiting-for-answer → exchanging-ice → connected
|
||||||
});
|
});
|
||||||
|
|
||||||
conn.on('datachannel', (channel) => {
|
peer.on('connected', () => {
|
||||||
console.log('Data channel ready');
|
console.log('✅ Connected to peer!');
|
||||||
|
});
|
||||||
|
|
||||||
channel.onmessage = (event) => {
|
peer.on('datachannel', (channel) => {
|
||||||
console.log('Received:', event.data);
|
console.log('📡 Data channel ready');
|
||||||
};
|
|
||||||
|
|
||||||
|
channel.addEventListener('message', (event) => {
|
||||||
|
console.log('📥 Received:', event.data);
|
||||||
|
});
|
||||||
|
|
||||||
|
channel.addEventListener('open', () => {
|
||||||
channel.send('Hello from peer A!');
|
channel.send('Hello from peer A!');
|
||||||
});
|
});
|
||||||
|
});
|
||||||
|
|
||||||
// Create offer and advertise on topics
|
// Create offer and advertise on topics
|
||||||
const offerId = await conn.createOffer({
|
const offerId = await peer.createOffer({
|
||||||
topics: ['my-app', 'room-123'],
|
topics: ['my-app', 'room-123'],
|
||||||
ttl: 300000 // 5 minutes
|
ttl: 300000, // 5 minutes
|
||||||
|
secret: 'my-secret-password' // Optional: protect offer (max 128 chars)
|
||||||
});
|
});
|
||||||
|
|
||||||
console.log('Offer created:', offerId);
|
console.log('Offer created:', offerId);
|
||||||
@@ -72,6 +83,7 @@ console.log('Share these topics with peers:', ['my-app', 'room-123']);
|
|||||||
```typescript
|
```typescript
|
||||||
import { Rondevu } from '@xtr-dev/rondevu-client';
|
import { Rondevu } from '@xtr-dev/rondevu-client';
|
||||||
|
|
||||||
|
// Initialize client and register
|
||||||
const client = new Rondevu({ baseUrl: 'https://api.ronde.vu' });
|
const client = new Rondevu({ baseUrl: 'https://api.ronde.vu' });
|
||||||
await client.register();
|
await client.register();
|
||||||
|
|
||||||
@@ -81,65 +93,143 @@ const offers = await client.offers.findByTopic('my-app', { limit: 10 });
|
|||||||
if (offers.length > 0) {
|
if (offers.length > 0) {
|
||||||
const offer = offers[0];
|
const offer = offers[0];
|
||||||
|
|
||||||
// Create connection
|
// Create peer connection
|
||||||
const conn = client.createConnection();
|
const peer = client.createPeer();
|
||||||
|
|
||||||
// Set up event listeners
|
// Set up event listeners
|
||||||
conn.on('connecting', () => {
|
peer.on('state', (state) => {
|
||||||
console.log('Connecting...');
|
console.log('Peer state:', state);
|
||||||
|
// States: idle → answering → exchanging-ice → connected
|
||||||
});
|
});
|
||||||
|
|
||||||
conn.on('connected', () => {
|
peer.on('connected', () => {
|
||||||
console.log('Connected!');
|
console.log('✅ Connected!');
|
||||||
});
|
});
|
||||||
|
|
||||||
conn.on('datachannel', (channel) => {
|
peer.on('datachannel', (channel) => {
|
||||||
console.log('Data channel ready');
|
console.log('📡 Data channel ready');
|
||||||
|
|
||||||
channel.onmessage = (event) => {
|
channel.addEventListener('message', (event) => {
|
||||||
console.log('Received:', event.data);
|
console.log('📥 Received:', event.data);
|
||||||
};
|
});
|
||||||
|
|
||||||
|
channel.addEventListener('open', () => {
|
||||||
channel.send('Hello from peer B!');
|
channel.send('Hello from peer B!');
|
||||||
});
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
peer.on('failed', (error) => {
|
||||||
|
console.error('❌ Connection failed:', error);
|
||||||
|
});
|
||||||
|
|
||||||
// Answer the offer
|
// Answer the offer
|
||||||
await conn.answer(offer.id, offer.sdp);
|
await peer.answer(offer.id, offer.sdp, {
|
||||||
|
topics: offer.topics,
|
||||||
|
secret: 'my-secret-password' // Required if offer.hasSecret is true
|
||||||
|
});
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
### Connection Events
|
## Protected Offers
|
||||||
|
|
||||||
|
You can protect offers with a secret to control who can answer them. This is useful for private rooms or invite-only connections.
|
||||||
|
|
||||||
|
### Creating a Protected Offer
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
conn.on('connecting', () => {
|
const offerId = await peer.createOffer({
|
||||||
// Connection is being established
|
topics: ['private-room'],
|
||||||
|
secret: 'my-secret-password' // Max 128 characters
|
||||||
});
|
});
|
||||||
|
|
||||||
conn.on('connected', () => {
|
// Share the secret with authorized peers through a secure channel
|
||||||
|
```
|
||||||
|
|
||||||
|
### Answering a Protected Offer
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const offers = await client.offers.findByTopic('private-room');
|
||||||
|
|
||||||
|
// Check if offer requires a secret
|
||||||
|
if (offers[0].hasSecret) {
|
||||||
|
console.log('This offer requires a secret');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Provide the secret when answering
|
||||||
|
await peer.answer(offers[0].id, offers[0].sdp, {
|
||||||
|
topics: offers[0].topics,
|
||||||
|
secret: 'my-secret-password' // Must match the offer's secret
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
**Notes:**
|
||||||
|
- The actual secret is never exposed in public API responses - only a `hasSecret` boolean flag
|
||||||
|
- Answerers must provide the correct secret, or the answer will be rejected
|
||||||
|
- Secrets are limited to 128 characters
|
||||||
|
- Use this for access control, not for cryptographic security (use end-to-end encryption for that)
|
||||||
|
|
||||||
|
## Connection Lifecycle
|
||||||
|
|
||||||
|
The `RondevuPeer` uses a state machine for connection management:
|
||||||
|
|
||||||
|
### Offerer States
|
||||||
|
1. **idle** - Initial state
|
||||||
|
2. **creating-offer** - Creating WebRTC offer
|
||||||
|
3. **waiting-for-answer** - Polling for answer from peer
|
||||||
|
4. **exchanging-ice** - Exchanging ICE candidates
|
||||||
|
5. **connected** - Successfully connected
|
||||||
|
6. **failed** - Connection failed
|
||||||
|
7. **closed** - Connection closed
|
||||||
|
|
||||||
|
### Answerer States
|
||||||
|
1. **idle** - Initial state
|
||||||
|
2. **answering** - Creating WebRTC answer
|
||||||
|
3. **exchanging-ice** - Exchanging ICE candidates
|
||||||
|
4. **connected** - Successfully connected
|
||||||
|
5. **failed** - Connection failed
|
||||||
|
6. **closed** - Connection closed
|
||||||
|
|
||||||
|
### State Events
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
peer.on('state', (stateName) => {
|
||||||
|
console.log('Current state:', stateName);
|
||||||
|
});
|
||||||
|
|
||||||
|
peer.on('connected', () => {
|
||||||
// Connection established successfully
|
// Connection established successfully
|
||||||
});
|
});
|
||||||
|
|
||||||
conn.on('disconnected', () => {
|
peer.on('disconnected', () => {
|
||||||
// Connection lost or closed
|
// Connection lost or closed
|
||||||
});
|
});
|
||||||
|
|
||||||
conn.on('error', (error) => {
|
peer.on('failed', (error) => {
|
||||||
// An error occurred
|
// Connection failed
|
||||||
console.error('Connection error:', error);
|
console.error('Connection error:', error);
|
||||||
});
|
});
|
||||||
|
|
||||||
conn.on('datachannel', (channel) => {
|
peer.on('datachannel', (channel) => {
|
||||||
// Data channel is ready to use
|
// Data channel is ready (use channel.addEventListener)
|
||||||
});
|
});
|
||||||
|
|
||||||
conn.on('track', (event) => {
|
peer.on('track', (event) => {
|
||||||
// Media track received (for audio/video streaming)
|
// Media track received (for audio/video streaming)
|
||||||
const stream = event.streams[0];
|
const stream = event.streams[0];
|
||||||
videoElement.srcObject = stream;
|
videoElement.srcObject = stream;
|
||||||
});
|
});
|
||||||
```
|
```
|
||||||
|
|
||||||
### Adding Media Tracks
|
## Trickle ICE
|
||||||
|
|
||||||
|
This library implements **trickle ICE** for faster connection establishment:
|
||||||
|
|
||||||
|
- ICE candidates are sent to the server as they're discovered
|
||||||
|
- No waiting for all candidates before sending offer/answer
|
||||||
|
- Connections establish much faster (milliseconds vs seconds)
|
||||||
|
- Proper event listener cleanup to prevent memory leaks
|
||||||
|
|
||||||
|
## Adding Media Tracks
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
// Get user's camera/microphone
|
// Get user's camera/microphone
|
||||||
@@ -148,29 +238,64 @@ const stream = await navigator.mediaDevices.getUserMedia({
|
|||||||
audio: true
|
audio: true
|
||||||
});
|
});
|
||||||
|
|
||||||
// Add tracks to connection
|
// Add tracks to peer connection
|
||||||
stream.getTracks().forEach(track => {
|
stream.getTracks().forEach(track => {
|
||||||
conn.addTrack(track, stream);
|
peer.addTrack(track, stream);
|
||||||
});
|
});
|
||||||
```
|
```
|
||||||
|
|
||||||
### Connection Properties
|
## Peer Properties
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
|
// Get current state name
|
||||||
|
console.log(peer.stateName); // 'idle', 'creating-offer', 'connected', etc.
|
||||||
|
|
||||||
// Get connection state
|
// Get connection state
|
||||||
console.log(conn.connectionState); // 'connecting', 'connected', 'disconnected', etc.
|
console.log(peer.connectionState); // RTCPeerConnectionState
|
||||||
|
|
||||||
// Get offer ID
|
// Get offer ID (after creating offer or answering)
|
||||||
console.log(conn.id);
|
console.log(peer.offerId);
|
||||||
|
|
||||||
// Get data channel
|
// Get role
|
||||||
console.log(conn.channel);
|
console.log(peer.role); // 'offerer' or 'answerer'
|
||||||
```
|
```
|
||||||
|
|
||||||
### Closing a Connection
|
## Closing a Connection
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
conn.close();
|
await peer.close();
|
||||||
|
```
|
||||||
|
|
||||||
|
## Custom RTCConfiguration
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const peer = client.createPeer({
|
||||||
|
iceServers: [
|
||||||
|
{ urls: 'stun:stun.l.google.com:19302' },
|
||||||
|
{
|
||||||
|
urls: 'turn:turn.example.com:3478',
|
||||||
|
username: 'user',
|
||||||
|
credential: 'pass'
|
||||||
|
}
|
||||||
|
],
|
||||||
|
iceTransportPolicy: 'relay' // Force TURN relay (useful for testing)
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
## Timeouts
|
||||||
|
|
||||||
|
Configure connection timeouts:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
await peer.createOffer({
|
||||||
|
topics: ['my-topic'],
|
||||||
|
timeouts: {
|
||||||
|
iceGathering: 10000, // ICE gathering timeout (10s)
|
||||||
|
waitingForAnswer: 30000, // Waiting for answer timeout (30s)
|
||||||
|
creatingAnswer: 10000, // Creating answer timeout (10s)
|
||||||
|
iceConnection: 30000 // ICE connection timeout (30s)
|
||||||
|
}
|
||||||
|
});
|
||||||
```
|
```
|
||||||
|
|
||||||
## Platform-Specific Setup
|
## Platform-Specific Setup
|
||||||
@@ -197,6 +322,43 @@ const client = new Rondevu({
|
|||||||
});
|
});
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### Node.js with WebRTC (wrtc)
|
||||||
|
|
||||||
|
For WebRTC functionality in Node.js, you need to provide WebRTC polyfills since Node.js doesn't have native WebRTC support:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm install wrtc node-fetch
|
||||||
|
```
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { Rondevu } from '@xtr-dev/rondevu-client';
|
||||||
|
import fetch from 'node-fetch';
|
||||||
|
import { RTCPeerConnection, RTCSessionDescription, RTCIceCandidate } from 'wrtc';
|
||||||
|
|
||||||
|
const client = new Rondevu({
|
||||||
|
baseUrl: 'https://api.ronde.vu',
|
||||||
|
fetch: fetch as any,
|
||||||
|
RTCPeerConnection,
|
||||||
|
RTCSessionDescription,
|
||||||
|
RTCIceCandidate
|
||||||
|
});
|
||||||
|
|
||||||
|
// Now you can use WebRTC features
|
||||||
|
await client.register();
|
||||||
|
const peer = client.createPeer({
|
||||||
|
iceServers: [
|
||||||
|
{ urls: 'stun:stun.l.google.com:19302' }
|
||||||
|
]
|
||||||
|
});
|
||||||
|
|
||||||
|
// Create offers, answer, etc.
|
||||||
|
const offerId = await peer.createOffer({
|
||||||
|
topics: ['my-topic']
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
**Note:** The `wrtc` package provides WebRTC bindings for Node.js. Alternative packages like `node-webrtc` can also be used - just pass their implementations to the Rondevu constructor.
|
||||||
|
|
||||||
### Deno
|
### Deno
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
@@ -230,7 +392,7 @@ export default {
|
|||||||
|
|
||||||
## Low-Level API Usage
|
## Low-Level API Usage
|
||||||
|
|
||||||
For advanced use cases where you need direct control over the signaling process, you can use the low-level API:
|
For direct control over the signaling process without WebRTC:
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
import { Rondevu, BloomFilter } from '@xtr-dev/rondevu-client';
|
import { Rondevu, BloomFilter } from '@xtr-dev/rondevu-client';
|
||||||
@@ -248,7 +410,9 @@ localStorage.setItem('rondevu-creds', JSON.stringify(creds));
|
|||||||
const offers = await client.offers.create([{
|
const offers = await client.offers.create([{
|
||||||
sdp: 'v=0...', // Your WebRTC offer SDP
|
sdp: 'v=0...', // Your WebRTC offer SDP
|
||||||
topics: ['movie-xyz', 'hd-content'],
|
topics: ['movie-xyz', 'hd-content'],
|
||||||
ttl: 300000 // 5 minutes
|
ttl: 300000, // 5 minutes
|
||||||
|
secret: 'my-secret-password', // Optional: protect offer (max 128 chars)
|
||||||
|
info: 'Looking for peers in EU region' // Optional: public info (max 128 chars)
|
||||||
}]);
|
}]);
|
||||||
|
|
||||||
// Discover peers by topic
|
// Discover peers by topic
|
||||||
@@ -276,9 +440,11 @@ const newPeers = await client.offers.findByTopic('movie-xyz', {
|
|||||||
#### `client.register()`
|
#### `client.register()`
|
||||||
Register a new peer and receive credentials.
|
Register a new peer and receive credentials.
|
||||||
|
|
||||||
|
Generates a cryptographically random 128-bit peer ID.
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
const creds = await client.register();
|
const creds = await client.register();
|
||||||
// { peerId: '...', secret: '...' }
|
// { peerId: 'f17c195f067255e357232e34cf0735d9', secret: '...' }
|
||||||
```
|
```
|
||||||
|
|
||||||
### Topics
|
### Topics
|
||||||
@@ -313,7 +479,9 @@ const offers = await client.offers.create([
|
|||||||
{
|
{
|
||||||
sdp: 'v=0...',
|
sdp: 'v=0...',
|
||||||
topics: ['topic-1', 'topic-2'],
|
topics: ['topic-1', 'topic-2'],
|
||||||
ttl: 300000 // optional, default 5 minutes
|
ttl: 300000, // optional, default 5 minutes
|
||||||
|
secret: 'my-secret-password', // optional, max 128 chars
|
||||||
|
info: 'Looking for peers in EU region' // optional, public info, max 128 chars
|
||||||
}
|
}
|
||||||
]);
|
]);
|
||||||
```
|
```
|
||||||
@@ -335,13 +503,6 @@ Get all offers owned by the authenticated peer.
|
|||||||
const myOffers = await client.offers.getMine();
|
const myOffers = await client.offers.getMine();
|
||||||
```
|
```
|
||||||
|
|
||||||
#### `client.offers.heartbeat(offerId)`
|
|
||||||
Update last_seen timestamp for an offer.
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
await client.offers.heartbeat(offerId);
|
|
||||||
```
|
|
||||||
|
|
||||||
#### `client.offers.delete(offerId)`
|
#### `client.offers.delete(offerId)`
|
||||||
Delete a specific offer.
|
Delete a specific offer.
|
||||||
|
|
||||||
@@ -349,13 +510,18 @@ Delete a specific offer.
|
|||||||
await client.offers.delete(offerId);
|
await client.offers.delete(offerId);
|
||||||
```
|
```
|
||||||
|
|
||||||
#### `client.offers.answer(offerId, sdp)`
|
#### `client.offers.answer(offerId, sdp, secret?)`
|
||||||
Answer an offer (locks it to answerer).
|
Answer an offer (locks it to answerer).
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
await client.offers.answer(offerId, answerSdp);
|
await client.offers.answer(offerId, answerSdp, 'my-secret-password');
|
||||||
```
|
```
|
||||||
|
|
||||||
|
**Parameters:**
|
||||||
|
- `offerId`: The offer ID to answer
|
||||||
|
- `sdp`: The WebRTC answer SDP
|
||||||
|
- `secret` (optional): Required if the offer has `hasSecret: true`
|
||||||
|
|
||||||
#### `client.offers.getAnswers()`
|
#### `client.offers.getAnswers()`
|
||||||
Poll for answers to your offers.
|
Poll for answers to your offers.
|
||||||
|
|
||||||
@@ -370,7 +536,7 @@ Post ICE candidates for an offer.
|
|||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
await client.offers.addIceCandidates(offerId, [
|
await client.offers.addIceCandidates(offerId, [
|
||||||
'candidate:1 1 UDP...'
|
{ candidate: 'candidate:1 1 UDP...', sdpMid: '0', sdpMLineIndex: 0 }
|
||||||
]);
|
]);
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -378,7 +544,7 @@ await client.offers.addIceCandidates(offerId, [
|
|||||||
Get ICE candidates from the other peer.
|
Get ICE candidates from the other peer.
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
const candidates = await client.offers.getIceCandidates(offerId);
|
const candidates = await client.offers.getIceCandidates(offerId, since);
|
||||||
```
|
```
|
||||||
|
|
||||||
### Bloom Filter
|
### Bloom Filter
|
||||||
@@ -414,8 +580,9 @@ import type {
|
|||||||
IceCandidate,
|
IceCandidate,
|
||||||
FetchFunction,
|
FetchFunction,
|
||||||
RondevuOptions,
|
RondevuOptions,
|
||||||
ConnectionOptions,
|
PeerOptions,
|
||||||
RondevuConnectionEvents
|
PeerEvents,
|
||||||
|
PeerTimeouts
|
||||||
} from '@xtr-dev/rondevu-client';
|
} from '@xtr-dev/rondevu-client';
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -423,28 +590,36 @@ import type {
|
|||||||
|
|
||||||
The client library is designed to work across different JavaScript runtimes:
|
The client library is designed to work across different JavaScript runtimes:
|
||||||
|
|
||||||
| Environment | Native Fetch | Custom Fetch Needed |
|
| Environment | Native Fetch | Native WebRTC | Polyfills Needed |
|
||||||
|-------------|--------------|---------------------|
|
|-------------|--------------|---------------|------------------|
|
||||||
| Modern Browsers | ✅ Yes | ❌ No |
|
| Modern Browsers | ✅ Yes | ✅ Yes | ❌ None |
|
||||||
| Node.js 18+ | ✅ Yes | ❌ No |
|
| Node.js 18+ | ✅ Yes | ❌ No | ✅ WebRTC (wrtc) |
|
||||||
| Node.js < 18 | ❌ No | ✅ Yes (node-fetch) |
|
| Node.js < 18 | ❌ No | ❌ No | ✅ Fetch + WebRTC |
|
||||||
| Deno | ✅ Yes | ❌ No |
|
| Deno | ✅ Yes | ⚠️ Partial | ❌ None (signaling only) |
|
||||||
| Bun | ✅ Yes | ❌ No |
|
| Bun | ✅ Yes | ❌ No | ✅ WebRTC (wrtc) |
|
||||||
| Cloudflare Workers | ✅ Yes | ❌ No |
|
| Cloudflare Workers | ✅ Yes | ❌ No | ❌ None (signaling only) |
|
||||||
|
|
||||||
**If your environment doesn't have native fetch:**
|
**For signaling-only (no WebRTC peer connections):**
|
||||||
|
|
||||||
|
Use the low-level API with `client.offers` - no WebRTC polyfills needed.
|
||||||
|
|
||||||
|
**For full WebRTC support in Node.js:**
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
npm install node-fetch
|
npm install wrtc node-fetch
|
||||||
```
|
```
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
import { Rondevu } from '@xtr-dev/rondevu-client';
|
import { Rondevu } from '@xtr-dev/rondevu-client';
|
||||||
import fetch from 'node-fetch';
|
import fetch from 'node-fetch';
|
||||||
|
import { RTCPeerConnection, RTCSessionDescription, RTCIceCandidate } from 'wrtc';
|
||||||
|
|
||||||
const client = new Rondevu({
|
const client = new Rondevu({
|
||||||
baseUrl: 'https://rondevu.xtrdev.workers.dev',
|
baseUrl: 'https://api.ronde.vu',
|
||||||
fetch: fetch as any
|
fetch: fetch as any,
|
||||||
|
RTCPeerConnection,
|
||||||
|
RTCSessionDescription,
|
||||||
|
RTCIceCandidate
|
||||||
});
|
});
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|||||||
4
package-lock.json
generated
4
package-lock.json
generated
@@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "@xtr-dev/rondevu-client",
|
"name": "@xtr-dev/rondevu-client",
|
||||||
"version": "0.7.2",
|
"version": "0.7.11",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "@xtr-dev/rondevu-client",
|
"name": "@xtr-dev/rondevu-client",
|
||||||
"version": "0.7.2",
|
"version": "0.7.11",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@xtr-dev/rondevu-client": "^0.5.1"
|
"@xtr-dev/rondevu-client": "^0.5.1"
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@xtr-dev/rondevu-client",
|
"name": "@xtr-dev/rondevu-client",
|
||||||
"version": "0.7.2",
|
"version": "0.7.12",
|
||||||
"description": "TypeScript client for Rondevu topic-based peer discovery and signaling server",
|
"description": "TypeScript client for Rondevu topic-based peer discovery and signaling server",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "dist/index.js",
|
"main": "dist/index.js",
|
||||||
|
|||||||
@@ -29,6 +29,8 @@ export class RondevuAuth {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Register a new peer and receive credentials
|
* Register a new peer and receive credentials
|
||||||
|
* Generates a cryptographically random peer ID (128-bit)
|
||||||
|
* @throws Error if registration fails
|
||||||
*/
|
*/
|
||||||
async register(): Promise<Credentials> {
|
async register(): Promise<Credentials> {
|
||||||
const response = await this.fetchFn(`${this.baseUrl}/register`, {
|
const response = await this.fetchFn(`${this.baseUrl}/register`, {
|
||||||
|
|||||||
208
src/client.ts
208
src/client.ts
@@ -1,208 +0,0 @@
|
|||||||
import {
|
|
||||||
RondevuClientOptions,
|
|
||||||
CreateOfferRequest,
|
|
||||||
CreateOfferResponse,
|
|
||||||
AnswerRequest,
|
|
||||||
AnswerResponse,
|
|
||||||
PollRequest,
|
|
||||||
PollOffererResponse,
|
|
||||||
PollAnswererResponse,
|
|
||||||
VersionResponse,
|
|
||||||
HealthResponse,
|
|
||||||
ErrorResponse,
|
|
||||||
Side,
|
|
||||||
} from './types.js';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* HTTP API client for Rondevu peer signaling server
|
|
||||||
*/
|
|
||||||
export class RondevuAPI {
|
|
||||||
private readonly baseUrl: string;
|
|
||||||
private readonly fetchImpl: typeof fetch;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Creates a new Rondevu API client instance
|
|
||||||
* @param options - Client configuration options
|
|
||||||
*/
|
|
||||||
constructor(options: RondevuClientOptions) {
|
|
||||||
this.baseUrl = options.baseUrl.replace(/\/$/, ''); // Remove trailing slash
|
|
||||||
this.fetchImpl = options.fetch || globalThis.fetch.bind(globalThis);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Makes an HTTP request to the Rondevu server
|
|
||||||
*/
|
|
||||||
private async request<T>(
|
|
||||||
endpoint: string,
|
|
||||||
options: RequestInit = {}
|
|
||||||
): Promise<T> {
|
|
||||||
const url = `${this.baseUrl}${endpoint}`;
|
|
||||||
|
|
||||||
const headers: Record<string, string> = {
|
|
||||||
...(options.headers as Record<string, string>),
|
|
||||||
};
|
|
||||||
|
|
||||||
if (options.body) {
|
|
||||||
headers['Content-Type'] = 'application/json';
|
|
||||||
}
|
|
||||||
|
|
||||||
const response = await this.fetchImpl(url, {
|
|
||||||
...options,
|
|
||||||
headers,
|
|
||||||
});
|
|
||||||
|
|
||||||
const data = await response.json();
|
|
||||||
|
|
||||||
if (!response.ok) {
|
|
||||||
const error = data as ErrorResponse;
|
|
||||||
throw new Error(error.error || `HTTP ${response.status}: ${response.statusText}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
return data as T;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Gets server version information
|
|
||||||
*
|
|
||||||
* @returns Server version
|
|
||||||
*
|
|
||||||
* @example
|
|
||||||
* ```typescript
|
|
||||||
* const api = new RondevuAPI({ baseUrl: 'https://example.com' });
|
|
||||||
* const { version } = await api.getVersion();
|
|
||||||
* console.log('Server version:', version);
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
async getVersion(): Promise<VersionResponse> {
|
|
||||||
return this.request<VersionResponse>('/', {
|
|
||||||
method: 'GET',
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Creates a new offer
|
|
||||||
*
|
|
||||||
* @param request - Offer details including peer ID, signaling data, and optional custom code
|
|
||||||
* @returns Unique offer code (UUID or custom code)
|
|
||||||
*
|
|
||||||
* @example
|
|
||||||
* ```typescript
|
|
||||||
* const api = new RondevuAPI({ baseUrl: 'https://example.com' });
|
|
||||||
* const { code } = await api.createOffer({
|
|
||||||
* peerId: 'peer-123',
|
|
||||||
* offer: signalingData,
|
|
||||||
* code: 'my-custom-code' // optional
|
|
||||||
* });
|
|
||||||
* console.log('Offer code:', code);
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
async createOffer(request: CreateOfferRequest): Promise<CreateOfferResponse> {
|
|
||||||
return this.request<CreateOfferResponse>('/offer', {
|
|
||||||
method: 'POST',
|
|
||||||
body: JSON.stringify(request),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sends an answer or candidate to an existing offer
|
|
||||||
*
|
|
||||||
* @param request - Answer details including offer code and signaling data
|
|
||||||
* @returns Success confirmation
|
|
||||||
*
|
|
||||||
* @example
|
|
||||||
* ```typescript
|
|
||||||
* const api = new RondevuAPI({ baseUrl: 'https://example.com' });
|
|
||||||
*
|
|
||||||
* // Send answer
|
|
||||||
* await api.sendAnswer({
|
|
||||||
* code: offerCode,
|
|
||||||
* answer: answerData,
|
|
||||||
* side: 'answerer'
|
|
||||||
* });
|
|
||||||
*
|
|
||||||
* // Send candidate
|
|
||||||
* await api.sendAnswer({
|
|
||||||
* code: offerCode,
|
|
||||||
* candidate: candidateData,
|
|
||||||
* side: 'offerer'
|
|
||||||
* });
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
async sendAnswer(request: AnswerRequest): Promise<AnswerResponse> {
|
|
||||||
return this.request<AnswerResponse>('/answer', {
|
|
||||||
method: 'POST',
|
|
||||||
body: JSON.stringify(request),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Polls for offer data from the other peer
|
|
||||||
*
|
|
||||||
* @param code - Offer code
|
|
||||||
* @param side - Which side is polling ('offerer' or 'answerer')
|
|
||||||
* @returns Offer data including offers, answers, and candidates
|
|
||||||
*
|
|
||||||
* @example
|
|
||||||
* ```typescript
|
|
||||||
* const api = new RondevuAPI({ baseUrl: 'https://example.com' });
|
|
||||||
*
|
|
||||||
* // Offerer polls for answer
|
|
||||||
* const offererData = await api.poll(offerCode, 'offerer');
|
|
||||||
* if (offererData.answer) {
|
|
||||||
* console.log('Received answer:', offererData.answer);
|
|
||||||
* }
|
|
||||||
*
|
|
||||||
* // Answerer polls for offer
|
|
||||||
* const answererData = await api.poll(offerCode, 'answerer');
|
|
||||||
* console.log('Received offer:', answererData.offer);
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
async poll(
|
|
||||||
code: string,
|
|
||||||
side: Side
|
|
||||||
): Promise<PollOffererResponse | PollAnswererResponse> {
|
|
||||||
const request: PollRequest = { code, side };
|
|
||||||
return this.request<PollOffererResponse | PollAnswererResponse>('/poll', {
|
|
||||||
method: 'POST',
|
|
||||||
body: JSON.stringify(request),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Checks server health and version
|
|
||||||
*
|
|
||||||
* @returns Health status, timestamp, and version
|
|
||||||
*
|
|
||||||
* @example
|
|
||||||
* ```typescript
|
|
||||||
* const api = new RondevuAPI({ baseUrl: 'https://example.com' });
|
|
||||||
* const health = await api.health();
|
|
||||||
* console.log('Server status:', health.status);
|
|
||||||
* console.log('Server version:', health.version);
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
async health(): Promise<HealthResponse> {
|
|
||||||
return this.request<HealthResponse>('/health', {
|
|
||||||
method: 'GET',
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Ends a session by deleting the offer from the server
|
|
||||||
*
|
|
||||||
* @param code - The offer code
|
|
||||||
* @returns Success confirmation
|
|
||||||
*
|
|
||||||
* @example
|
|
||||||
* ```typescript
|
|
||||||
* const api = new RondevuAPI({ baseUrl: 'https://example.com' });
|
|
||||||
* await api.leave('my-offer-code');
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
async leave(code: string): Promise<{ success: boolean }> {
|
|
||||||
return this.request<{ success: boolean }>('/leave', {
|
|
||||||
method: 'POST',
|
|
||||||
body: JSON.stringify({ code }),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -8,6 +8,8 @@ export interface CreateOfferRequest {
|
|||||||
sdp: string;
|
sdp: string;
|
||||||
topics: string[];
|
topics: string[];
|
||||||
ttl?: number;
|
ttl?: number;
|
||||||
|
secret?: string;
|
||||||
|
info?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface Offer {
|
export interface Offer {
|
||||||
@@ -18,6 +20,9 @@ export interface Offer {
|
|||||||
createdAt?: number;
|
createdAt?: number;
|
||||||
expiresAt: number;
|
expiresAt: number;
|
||||||
lastSeen: number;
|
lastSeen: number;
|
||||||
|
secret?: string;
|
||||||
|
hasSecret?: boolean;
|
||||||
|
info?: string;
|
||||||
answererPeerId?: string;
|
answererPeerId?: string;
|
||||||
answerSdp?: string;
|
answerSdp?: string;
|
||||||
answeredAt?: number;
|
answeredAt?: number;
|
||||||
@@ -143,11 +148,13 @@ export class RondevuOffers {
|
|||||||
async getTopics(options?: {
|
async getTopics(options?: {
|
||||||
limit?: number;
|
limit?: number;
|
||||||
offset?: number;
|
offset?: number;
|
||||||
|
startsWith?: string;
|
||||||
}): Promise<{
|
}): Promise<{
|
||||||
topics: TopicInfo[];
|
topics: TopicInfo[];
|
||||||
total: number;
|
total: number;
|
||||||
limit: number;
|
limit: number;
|
||||||
offset: number;
|
offset: number;
|
||||||
|
startsWith?: string;
|
||||||
}> {
|
}> {
|
||||||
const params = new URLSearchParams();
|
const params = new URLSearchParams();
|
||||||
|
|
||||||
@@ -159,6 +166,10 @@ export class RondevuOffers {
|
|||||||
params.set('offset', options.offset.toString());
|
params.set('offset', options.offset.toString());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (options?.startsWith) {
|
||||||
|
params.set('startsWith', options.startsWith);
|
||||||
|
}
|
||||||
|
|
||||||
const url = `${this.baseUrl}/topics${
|
const url = `${this.baseUrl}/topics${
|
||||||
params.toString() ? '?' + params.toString() : ''
|
params.toString() ? '?' + params.toString() : ''
|
||||||
}`;
|
}`;
|
||||||
@@ -195,23 +206,6 @@ export class RondevuOffers {
|
|||||||
return data.offers;
|
return data.offers;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Update offer heartbeat
|
|
||||||
*/
|
|
||||||
async heartbeat(offerId: string): Promise<void> {
|
|
||||||
const response = await this.fetchFn(`${this.baseUrl}/offers/${encodeURIComponent(offerId)}/heartbeat`, {
|
|
||||||
method: 'PUT',
|
|
||||||
headers: {
|
|
||||||
Authorization: RondevuAuth.createAuthHeader(this.credentials),
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!response.ok) {
|
|
||||||
const error = await response.json().catch(() => ({ error: 'Unknown error' }));
|
|
||||||
throw new Error(`Failed to update heartbeat: ${error.error || response.statusText}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Delete an offer
|
* Delete an offer
|
||||||
*/
|
*/
|
||||||
@@ -232,14 +226,14 @@ export class RondevuOffers {
|
|||||||
/**
|
/**
|
||||||
* Answer an offer
|
* Answer an offer
|
||||||
*/
|
*/
|
||||||
async answer(offerId: string, sdp: string): Promise<void> {
|
async answer(offerId: string, sdp: string, secret?: string): Promise<void> {
|
||||||
const response = await this.fetchFn(`${this.baseUrl}/offers/${encodeURIComponent(offerId)}/answer`, {
|
const response = await this.fetchFn(`${this.baseUrl}/offers/${encodeURIComponent(offerId)}/answer`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': 'application/json',
|
'Content-Type': 'application/json',
|
||||||
Authorization: RondevuAuth.createAuthHeader(this.credentials),
|
Authorization: RondevuAuth.createAuthHeader(this.credentials),
|
||||||
},
|
},
|
||||||
body: JSON.stringify({ sdp }),
|
body: JSON.stringify({ sdp, secret }),
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
|
|||||||
@@ -23,15 +23,19 @@ export class AnsweringState extends PeerState {
|
|||||||
sdp: offerSdp
|
sdp: offerSdp
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Create answer
|
||||||
|
const answer = await this.peer.pc.createAnswer();
|
||||||
|
|
||||||
|
// Send answer to server BEFORE setLocalDescription
|
||||||
|
// This registers us as the answerer so ICE candidates will be accepted
|
||||||
|
await this.peer.offersApi.answer(offerId, answer.sdp!, options.secret);
|
||||||
|
|
||||||
// Enable trickle ICE - set up handler before ICE gathering starts
|
// Enable trickle ICE - set up handler before ICE gathering starts
|
||||||
this.setupIceCandidateHandler();
|
this.setupIceCandidateHandler();
|
||||||
|
|
||||||
// Create answer
|
// Set local description - ICE gathering starts here
|
||||||
const answer = await this.peer.pc.createAnswer();
|
// Server already knows we're the answerer, so candidates will be accepted
|
||||||
await this.peer.pc.setLocalDescription(answer); // ICE gathering starts here
|
await this.peer.pc.setLocalDescription(answer);
|
||||||
|
|
||||||
// Send answer to server immediately (don't wait for ICE)
|
|
||||||
await this.peer.offersApi.answer(offerId, answer.sdp!);
|
|
||||||
|
|
||||||
// Transition to exchanging ICE
|
// Transition to exchanging ICE
|
||||||
const { ExchangingIceState } = await import('./exchanging-ice-state.js');
|
const { ExchangingIceState } = await import('./exchanging-ice-state.js');
|
||||||
|
|||||||
@@ -36,7 +36,8 @@ export class CreatingOfferState extends PeerState {
|
|||||||
const offers = await this.peer.offersApi.create([{
|
const offers = await this.peer.offersApi.create([{
|
||||||
sdp: offer.sdp!,
|
sdp: offer.sdp!,
|
||||||
topics: options.topics,
|
topics: options.topics,
|
||||||
ttl: options.ttl || 300000
|
ttl: options.ttl || 300000,
|
||||||
|
secret: options.secret
|
||||||
}]);
|
}]);
|
||||||
|
|
||||||
const offerId = offers[0].id;
|
const offerId = offers[0].id;
|
||||||
|
|||||||
@@ -43,7 +43,7 @@ export class ExchangingIceState extends PeerState {
|
|||||||
for (const cand of candidates) {
|
for (const cand of candidates) {
|
||||||
if (cand.candidate && cand.candidate.candidate && cand.candidate.candidate !== '') {
|
if (cand.candidate && cand.candidate.candidate && cand.candidate.candidate !== '') {
|
||||||
try {
|
try {
|
||||||
await this.peer.pc.addIceCandidate(new RTCIceCandidate(cand.candidate));
|
await this.peer.pc.addIceCandidate(new this.peer.RTCIceCandidate(cand.candidate));
|
||||||
this.lastIceTimestamp = cand.createdAt;
|
this.lastIceTimestamp = cand.createdAt;
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.warn('Failed to add ICE candidate:', err);
|
console.warn('Failed to add ICE candidate:', err);
|
||||||
|
|||||||
@@ -24,6 +24,11 @@ export default class RondevuPeer extends EventEmitter<PeerEvents> {
|
|||||||
offerId?: string;
|
offerId?: string;
|
||||||
role?: 'offerer' | 'answerer';
|
role?: 'offerer' | 'answerer';
|
||||||
|
|
||||||
|
// WebRTC polyfills for Node.js compatibility
|
||||||
|
RTCPeerConnection: typeof RTCPeerConnection;
|
||||||
|
RTCSessionDescription: typeof RTCSessionDescription;
|
||||||
|
RTCIceCandidate: typeof RTCIceCandidate;
|
||||||
|
|
||||||
private _state: PeerState;
|
private _state: PeerState;
|
||||||
|
|
||||||
// Event handler references for cleanup
|
// Event handler references for cleanup
|
||||||
@@ -60,11 +65,34 @@ export default class RondevuPeer extends EventEmitter<PeerEvents> {
|
|||||||
{ urls: 'stun:stun.l.google.com:19302' },
|
{ urls: 'stun:stun.l.google.com:19302' },
|
||||||
{ urls: 'stun:stun1.l.google.com:19302' }
|
{ urls: 'stun:stun1.l.google.com:19302' }
|
||||||
]
|
]
|
||||||
}
|
},
|
||||||
|
rtcPeerConnection?: typeof RTCPeerConnection,
|
||||||
|
rtcSessionDescription?: typeof RTCSessionDescription,
|
||||||
|
rtcIceCandidate?: typeof RTCIceCandidate
|
||||||
) {
|
) {
|
||||||
super();
|
super();
|
||||||
this.offersApi = offersApi;
|
this.offersApi = offersApi;
|
||||||
this.pc = new RTCPeerConnection(rtcConfig);
|
|
||||||
|
// Use provided polyfills or fall back to globals
|
||||||
|
this.RTCPeerConnection = rtcPeerConnection || (typeof globalThis.RTCPeerConnection !== 'undefined'
|
||||||
|
? globalThis.RTCPeerConnection
|
||||||
|
: (() => {
|
||||||
|
throw new Error('RTCPeerConnection is not available. Please provide it in the Rondevu constructor options for Node.js environments.');
|
||||||
|
}) as any);
|
||||||
|
|
||||||
|
this.RTCSessionDescription = rtcSessionDescription || (typeof globalThis.RTCSessionDescription !== 'undefined'
|
||||||
|
? globalThis.RTCSessionDescription
|
||||||
|
: (() => {
|
||||||
|
throw new Error('RTCSessionDescription is not available. Please provide it in the Rondevu constructor options for Node.js environments.');
|
||||||
|
}) as any);
|
||||||
|
|
||||||
|
this.RTCIceCandidate = rtcIceCandidate || (typeof globalThis.RTCIceCandidate !== 'undefined'
|
||||||
|
? globalThis.RTCIceCandidate
|
||||||
|
: (() => {
|
||||||
|
throw new Error('RTCIceCandidate is not available. Please provide it in the Rondevu constructor options for Node.js environments.');
|
||||||
|
}) as any);
|
||||||
|
|
||||||
|
this.pc = new this.RTCPeerConnection(rtcConfig);
|
||||||
this._state = new IdleState(this);
|
this._state = new IdleState(this);
|
||||||
|
|
||||||
this.setupPeerConnection();
|
this.setupPeerConnection();
|
||||||
@@ -151,6 +179,15 @@ export default class RondevuPeer extends EventEmitter<PeerEvents> {
|
|||||||
return this.pc.addTrack(track, ...streams);
|
return this.pc.addTrack(track, ...streams);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a data channel for sending and receiving arbitrary data
|
||||||
|
* This should typically be called by the offerer before creating the offer
|
||||||
|
* The answerer will receive the channel via the 'datachannel' event
|
||||||
|
*/
|
||||||
|
createDataChannel(label: string, options?: RTCDataChannelInit): RTCDataChannel {
|
||||||
|
return this.pc.createDataChannel(label, options);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Close the connection and clean up
|
* Close the connection and clean up
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -27,7 +27,7 @@ export abstract class PeerState {
|
|||||||
async handleIceCandidate(candidate: any): Promise<void> {
|
async handleIceCandidate(candidate: any): Promise<void> {
|
||||||
// ICE candidates can arrive in multiple states, so default is to add them
|
// ICE candidates can arrive in multiple states, so default is to add them
|
||||||
if (this.peer.pc.remoteDescription) {
|
if (this.peer.pc.remoteDescription) {
|
||||||
await this.peer.pc.addIceCandidate(new RTCIceCandidate(candidate));
|
await this.peer.pc.addIceCandidate(new this.peer.RTCIceCandidate(candidate));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -22,6 +22,8 @@ export interface PeerOptions {
|
|||||||
topics: string[];
|
topics: string[];
|
||||||
/** How long the offer should live (milliseconds) */
|
/** How long the offer should live (milliseconds) */
|
||||||
ttl?: number;
|
ttl?: number;
|
||||||
|
/** Optional secret to protect the offer (max 128 characters) */
|
||||||
|
secret?: string;
|
||||||
/** Whether to create a data channel automatically (for offerer) */
|
/** Whether to create a data channel automatically (for offerer) */
|
||||||
createDataChannel?: boolean;
|
createDataChannel?: boolean;
|
||||||
/** Label for the automatically created data channel */
|
/** Label for the automatically created data channel */
|
||||||
|
|||||||
@@ -25,6 +25,42 @@ export interface RondevuOptions {
|
|||||||
* ```
|
* ```
|
||||||
*/
|
*/
|
||||||
fetch?: FetchFunction;
|
fetch?: FetchFunction;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Custom RTCPeerConnection implementation for Node.js environments
|
||||||
|
* Required when using in Node.js with wrtc or similar polyfills
|
||||||
|
*
|
||||||
|
* @example Node.js with wrtc
|
||||||
|
* ```typescript
|
||||||
|
* import { RTCPeerConnection } from 'wrtc';
|
||||||
|
* const client = new Rondevu({ RTCPeerConnection });
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
RTCPeerConnection?: typeof RTCPeerConnection;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Custom RTCSessionDescription implementation for Node.js environments
|
||||||
|
* Required when using in Node.js with wrtc or similar polyfills
|
||||||
|
*
|
||||||
|
* @example Node.js with wrtc
|
||||||
|
* ```typescript
|
||||||
|
* import { RTCSessionDescription } from 'wrtc';
|
||||||
|
* const client = new Rondevu({ RTCSessionDescription });
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
RTCSessionDescription?: typeof RTCSessionDescription;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Custom RTCIceCandidate implementation for Node.js environments
|
||||||
|
* Required when using in Node.js with wrtc or similar polyfills
|
||||||
|
*
|
||||||
|
* @example Node.js with wrtc
|
||||||
|
* ```typescript
|
||||||
|
* import { RTCIceCandidate } from 'wrtc';
|
||||||
|
* const client = new Rondevu({ RTCIceCandidate });
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
RTCIceCandidate?: typeof RTCIceCandidate;
|
||||||
}
|
}
|
||||||
|
|
||||||
export class Rondevu {
|
export class Rondevu {
|
||||||
@@ -33,10 +69,16 @@ export class Rondevu {
|
|||||||
private credentials?: Credentials;
|
private credentials?: Credentials;
|
||||||
private baseUrl: string;
|
private baseUrl: string;
|
||||||
private fetchFn?: FetchFunction;
|
private fetchFn?: FetchFunction;
|
||||||
|
private rtcPeerConnection?: typeof RTCPeerConnection;
|
||||||
|
private rtcSessionDescription?: typeof RTCSessionDescription;
|
||||||
|
private rtcIceCandidate?: typeof RTCIceCandidate;
|
||||||
|
|
||||||
constructor(options: RondevuOptions = {}) {
|
constructor(options: RondevuOptions = {}) {
|
||||||
this.baseUrl = options.baseUrl || 'https://api.ronde.vu';
|
this.baseUrl = options.baseUrl || 'https://api.ronde.vu';
|
||||||
this.fetchFn = options.fetch;
|
this.fetchFn = options.fetch;
|
||||||
|
this.rtcPeerConnection = options.RTCPeerConnection;
|
||||||
|
this.rtcSessionDescription = options.RTCSessionDescription;
|
||||||
|
this.rtcIceCandidate = options.RTCIceCandidate;
|
||||||
|
|
||||||
this.auth = new RondevuAuth(this.baseUrl, this.fetchFn);
|
this.auth = new RondevuAuth(this.baseUrl, this.fetchFn);
|
||||||
|
|
||||||
@@ -58,6 +100,7 @@ export class Rondevu {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Register and initialize authenticated client
|
* Register and initialize authenticated client
|
||||||
|
* Generates a cryptographically random peer ID (128-bit)
|
||||||
*/
|
*/
|
||||||
async register(): Promise<Credentials> {
|
async register(): Promise<Credentials> {
|
||||||
this.credentials = await this.auth.register();
|
this.credentials = await this.auth.register();
|
||||||
@@ -98,6 +141,12 @@ export class Rondevu {
|
|||||||
throw new Error('Not authenticated. Call register() first or provide credentials.');
|
throw new Error('Not authenticated. Call register() first or provide credentials.');
|
||||||
}
|
}
|
||||||
|
|
||||||
return new RondevuPeer(this._offers, rtcConfig);
|
return new RondevuPeer(
|
||||||
|
this._offers,
|
||||||
|
rtcConfig,
|
||||||
|
this.rtcPeerConnection,
|
||||||
|
this.rtcSessionDescription,
|
||||||
|
this.rtcIceCandidate
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
182
src/types.ts
182
src/types.ts
@@ -1,182 +0,0 @@
|
|||||||
// ============================================================================
|
|
||||||
// Signaling Types
|
|
||||||
// ============================================================================
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Session side - identifies which peer in a connection
|
|
||||||
*/
|
|
||||||
export type Side = 'offerer' | 'answerer';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Request body for POST /offer
|
|
||||||
*/
|
|
||||||
export interface CreateOfferRequest {
|
|
||||||
/** Peer identifier/metadata (max 1024 characters) */
|
|
||||||
peerId: string;
|
|
||||||
/** Signaling data for peer connection */
|
|
||||||
offer: string;
|
|
||||||
/** Optional custom connection code (if not provided, server generates UUID) */
|
|
||||||
code?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Response from POST /offer
|
|
||||||
*/
|
|
||||||
export interface CreateOfferResponse {
|
|
||||||
/** Unique session identifier (UUID) */
|
|
||||||
code: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Request body for POST /answer
|
|
||||||
*/
|
|
||||||
export interface AnswerRequest {
|
|
||||||
/** Session UUID from the offer */
|
|
||||||
code: string;
|
|
||||||
/** Response signaling data (required if candidate not provided) */
|
|
||||||
answer?: string;
|
|
||||||
/** Additional signaling data (required if answer not provided) */
|
|
||||||
candidate?: string;
|
|
||||||
/** Which peer is sending the data */
|
|
||||||
side: Side;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Response from POST /answer
|
|
||||||
*/
|
|
||||||
export interface AnswerResponse {
|
|
||||||
success: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Request body for POST /poll
|
|
||||||
*/
|
|
||||||
export interface PollRequest {
|
|
||||||
/** Session UUID */
|
|
||||||
code: string;
|
|
||||||
/** Which side is polling */
|
|
||||||
side: Side;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Response from POST /poll when side=offerer
|
|
||||||
*/
|
|
||||||
export interface PollOffererResponse {
|
|
||||||
/** Answer from answerer (null if not yet received) */
|
|
||||||
answer: string | null;
|
|
||||||
/** Additional signaling data from answerer */
|
|
||||||
answerCandidates: string[];
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Response from POST /poll when side=answerer
|
|
||||||
*/
|
|
||||||
export interface PollAnswererResponse {
|
|
||||||
/** Offer from offerer */
|
|
||||||
offer: string;
|
|
||||||
/** Additional signaling data from offerer */
|
|
||||||
offerCandidates: string[];
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Response from POST /poll (union type)
|
|
||||||
*/
|
|
||||||
export type PollResponse = PollOffererResponse | PollAnswererResponse;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Response from GET / - server version information
|
|
||||||
*/
|
|
||||||
export interface VersionResponse {
|
|
||||||
/** Git commit hash or version identifier */
|
|
||||||
version: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Response from GET /health
|
|
||||||
*/
|
|
||||||
export interface HealthResponse {
|
|
||||||
status: 'ok';
|
|
||||||
timestamp: number;
|
|
||||||
version: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Error response structure
|
|
||||||
*/
|
|
||||||
export interface ErrorResponse {
|
|
||||||
error: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Client configuration options
|
|
||||||
*/
|
|
||||||
export interface RondevuClientOptions {
|
|
||||||
/** Base URL of the Rondevu server (e.g., 'https://example.com') */
|
|
||||||
baseUrl: string;
|
|
||||||
/** Optional fetch implementation (for Node.js environments) */
|
|
||||||
fetch?: typeof fetch;
|
|
||||||
}
|
|
||||||
|
|
||||||
// ============================================================================
|
|
||||||
// WebRTC Types
|
|
||||||
// ============================================================================
|
|
||||||
|
|
||||||
/**
|
|
||||||
* WebRTC polyfill for Node.js and other non-browser platforms
|
|
||||||
*/
|
|
||||||
export interface WebRTCPolyfill {
|
|
||||||
RTCPeerConnection: typeof RTCPeerConnection;
|
|
||||||
RTCSessionDescription: typeof RTCSessionDescription;
|
|
||||||
RTCIceCandidate: typeof RTCIceCandidate;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Configuration options for Rondevu WebRTC client
|
|
||||||
*/
|
|
||||||
export interface RondevuOptions {
|
|
||||||
/** Base URL of the Rondevu server (defaults to 'https://api.ronde.vu') */
|
|
||||||
baseUrl?: string;
|
|
||||||
/** Peer identifier (optional, auto-generated if not provided) */
|
|
||||||
peerId?: string;
|
|
||||||
/** Optional fetch implementation (for Node.js environments) */
|
|
||||||
fetch?: typeof fetch;
|
|
||||||
/** WebRTC configuration (ICE servers, etc.) */
|
|
||||||
rtcConfig?: RTCConfiguration;
|
|
||||||
/** Polling interval in milliseconds (default: 1000) */
|
|
||||||
pollingInterval?: number;
|
|
||||||
/** Connection timeout in milliseconds (default: 30000) */
|
|
||||||
connectionTimeout?: number;
|
|
||||||
/** WebRTC polyfill for Node.js (e.g., wrtc or @roamhq/wrtc) */
|
|
||||||
wrtc?: WebRTCPolyfill;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Connection role - whether this peer is creating or answering
|
|
||||||
*/
|
|
||||||
export type ConnectionRole = 'offerer' | 'answerer';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Parameters for creating a RondevuConnection
|
|
||||||
*/
|
|
||||||
export interface RondevuConnectionParams {
|
|
||||||
id: string;
|
|
||||||
topic?: string;
|
|
||||||
role: ConnectionRole;
|
|
||||||
pc: RTCPeerConnection;
|
|
||||||
localPeerId: string;
|
|
||||||
remotePeerId: string;
|
|
||||||
pollingInterval: number;
|
|
||||||
connectionTimeout: number;
|
|
||||||
wrtc?: WebRTCPolyfill;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Event map for RondevuConnection events
|
|
||||||
*/
|
|
||||||
export interface RondevuConnectionEvents {
|
|
||||||
connect: () => void;
|
|
||||||
disconnect: () => void;
|
|
||||||
error: (error: Error) => void;
|
|
||||||
datachannel: (channel: RTCDataChannel) => void;
|
|
||||||
stream: (stream: MediaStream) => void;
|
|
||||||
}
|
|
||||||
Reference in New Issue
Block a user