mirror of
https://github.com/xtr-dev/rondevu-client.git
synced 2025-12-10 02:43:25 +00:00
Compare commits
75 Commits
v0.1.2
...
177ee2ec2d
| Author | SHA1 | Date | |
|---|---|---|---|
| 177ee2ec2d | |||
| d06b2166c1 | |||
| cbb0cc3f83 | |||
| fbd3be57d4 | |||
| 54355323d9 | |||
| 945d5a8792 | |||
| 58cd610694 | |||
| 5e673ac993 | |||
| 511bac8033 | |||
| eb2c61bdb8 | |||
| 3139897b25 | |||
| a550641993 | |||
| 04603cfe2d | |||
| 6c2fd7952e | |||
| d6f2a10e3e | |||
| a6dc342f3b | |||
| 9486376442 | |||
| cffb092d3f | |||
| 122f211e7c | |||
| 4a6d0ee091 | |||
| b2d42fa776 | |||
| 63e14ddc5b | |||
| c9f6119148 | |||
| 15f821f08a | |||
| 895e7765f9 | |||
| 49d3984640 | |||
| 6057c3c582 | |||
| 255fe42a43 | |||
| 83fd0f84a4 | |||
| aa53d5bc3d | |||
| f5aa6e2189 | |||
| afdca83640 | |||
| c7ea1b9b8f | |||
| 660663945e | |||
| f119a42fcd | |||
| cd55072acb | |||
| 26f71e7a2b | |||
| 0ac1f94502 | |||
| 3530213870 | |||
| e052464482 | |||
| 53206d306b | |||
| c860419e66 | |||
| e22e74fb74 | |||
| 135eda73cf | |||
| 8d7075ccc4 | |||
| db8f0f4ced | |||
| 3a227a21ac | |||
| de1f3eac9c | |||
| 557cc0a838 | |||
| 6e661f69bc | |||
| 00f4da7250 | |||
| 6c344ec8e1 | |||
| 5a5da124a6 | |||
| c8b7a2913f | |||
| 6ddf7cb7f0 | |||
| 35ce051a26 | |||
| 280c8c284f | |||
| 14d3f943da | |||
| 2989326a50 | |||
| 7b82f963a3 | |||
| d25141a765 | |||
| 9d9aba2cf5 | |||
| dd64a565aa | |||
| cd78a16c66 | |||
| c202e1c627 | |||
| f6004a9bc0 | |||
| 5a47e0a397 | |||
| e1ca8e1c16 | |||
| 2f47107018 | |||
| d200d73cd9 | |||
| c8e5e4d17a | |||
| 6466a6f52a | |||
| 2e4d0d6a54 | |||
| 2b73e6ba44 | |||
| a893c7d040 |
9
.prettierrc.json
Normal file
9
.prettierrc.json
Normal file
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"semi": false,
|
||||
"singleQuote": true,
|
||||
"tabWidth": 4,
|
||||
"useTabs": false,
|
||||
"trailingComma": "es5",
|
||||
"printWidth": 100,
|
||||
"arrowParens": "avoid"
|
||||
}
|
||||
547
MIGRATION.md
Normal file
547
MIGRATION.md
Normal file
@@ -0,0 +1,547 @@
|
||||
# Migration Guide: v0.8.x → v0.9.0
|
||||
|
||||
This guide helps you migrate from Rondevu Client v0.8.x to v0.9.0.
|
||||
|
||||
## Overview
|
||||
|
||||
v0.9.0 is a **breaking change** that completely replaces low-level APIs with high-level durable connections featuring automatic reconnection and message queuing.
|
||||
|
||||
### What's New
|
||||
|
||||
✅ **Durable Connections**: Automatic reconnection on network drops
|
||||
✅ **Message Queuing**: Messages sent during disconnections are queued and flushed on reconnect
|
||||
✅ **Durable Channels**: RTCDataChannel wrappers that survive connection drops
|
||||
✅ **TTL Auto-Refresh**: Services automatically republish before expiration
|
||||
✅ **Simplified API**: Direct methods on main client instead of nested APIs
|
||||
|
||||
### What's Removed
|
||||
|
||||
❌ **Low-level APIs**: `client.services.*`, `client.discovery.*`, `client.createPeer()` no longer exported
|
||||
❌ **Manual Connection Management**: No need to handle WebRTC peer lifecycle manually
|
||||
❌ **Service Handles**: Replaced with DurableService instances
|
||||
|
||||
## Breaking Changes
|
||||
|
||||
### 1. Service Exposure
|
||||
|
||||
#### v0.8.x (Old)
|
||||
```typescript
|
||||
import { Rondevu } from '@xtr-dev/rondevu-client';
|
||||
|
||||
const client = new Rondevu();
|
||||
await client.register();
|
||||
|
||||
const handle = await client.services.exposeService({
|
||||
username: 'alice',
|
||||
privateKey: keypair.privateKey,
|
||||
serviceFqn: 'chat@1.0.0',
|
||||
isPublic: true,
|
||||
handler: (channel, peer) => {
|
||||
channel.onmessage = (e) => {
|
||||
console.log('Received:', e.data);
|
||||
channel.send(`Echo: ${e.data}`);
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
// Unpublish
|
||||
await handle.unpublish();
|
||||
```
|
||||
|
||||
#### v0.9.0 (New)
|
||||
```typescript
|
||||
import { Rondevu } from '@xtr-dev/rondevu-client';
|
||||
|
||||
const client = new Rondevu();
|
||||
await client.register();
|
||||
|
||||
const service = await client.exposeService({
|
||||
username: 'alice',
|
||||
privateKey: keypair.privateKey,
|
||||
serviceFqn: 'chat@1.0.0',
|
||||
isPublic: true,
|
||||
poolSize: 10, // NEW: Handle multiple concurrent connections
|
||||
handler: (channel, connectionId) => {
|
||||
// NEW: DurableChannel with event emitters
|
||||
channel.on('message', (data) => {
|
||||
console.log('Received:', data);
|
||||
channel.send(`Echo: ${data}`);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// NEW: Start the service
|
||||
await service.start();
|
||||
|
||||
// NEW: Stop the service
|
||||
await service.stop();
|
||||
```
|
||||
|
||||
**Key Differences:**
|
||||
- `client.services.exposeService()` → `client.exposeService()`
|
||||
- Returns `DurableService` instead of `ServiceHandle`
|
||||
- Handler receives `DurableChannel` instead of `RTCDataChannel`
|
||||
- Handler receives `connectionId` string instead of `RondevuPeer`
|
||||
- DurableChannel uses `.on('message', ...)` instead of `.onmessage = ...`
|
||||
- Must call `service.start()` to begin accepting connections
|
||||
- Use `service.stop()` instead of `handle.unpublish()`
|
||||
|
||||
### 2. Connecting to Services
|
||||
|
||||
#### v0.8.x (Old)
|
||||
```typescript
|
||||
// Connect by username + FQN
|
||||
const { peer, channel } = await client.discovery.connect(
|
||||
'alice',
|
||||
'chat@1.0.0'
|
||||
);
|
||||
|
||||
channel.onmessage = (e) => {
|
||||
console.log('Received:', e.data);
|
||||
};
|
||||
|
||||
channel.onopen = () => {
|
||||
channel.send('Hello!');
|
||||
};
|
||||
|
||||
peer.on('connected', () => {
|
||||
console.log('Connected');
|
||||
});
|
||||
|
||||
peer.on('failed', (error) => {
|
||||
console.error('Failed:', error);
|
||||
});
|
||||
```
|
||||
|
||||
#### v0.9.0 (New)
|
||||
```typescript
|
||||
// Connect by username + FQN
|
||||
const connection = await client.connect('alice', 'chat@1.0.0', {
|
||||
maxReconnectAttempts: 10 // NEW: Configurable reconnection
|
||||
});
|
||||
|
||||
// NEW: Create durable channel
|
||||
const channel = connection.createChannel('main');
|
||||
|
||||
channel.on('message', (data) => {
|
||||
console.log('Received:', data);
|
||||
});
|
||||
|
||||
channel.on('open', () => {
|
||||
channel.send('Hello!');
|
||||
});
|
||||
|
||||
// NEW: Connection lifecycle events
|
||||
connection.on('connected', () => {
|
||||
console.log('Connected');
|
||||
});
|
||||
|
||||
connection.on('reconnecting', (attempt, max, delay) => {
|
||||
console.log(`Reconnecting (${attempt}/${max})...`);
|
||||
});
|
||||
|
||||
connection.on('failed', (error) => {
|
||||
console.error('Failed permanently:', error);
|
||||
});
|
||||
|
||||
// NEW: Must explicitly connect
|
||||
await connection.connect();
|
||||
```
|
||||
|
||||
**Key Differences:**
|
||||
- `client.discovery.connect()` → `client.connect()`
|
||||
- Returns `DurableConnection` instead of `{ peer, channel }`
|
||||
- Must create channels with `connection.createChannel()`
|
||||
- Must call `connection.connect()` to establish connection
|
||||
- Automatic reconnection with configurable retry limits
|
||||
- Messages sent during disconnection are automatically queued
|
||||
|
||||
### 3. Connecting by UUID
|
||||
|
||||
#### v0.8.x (Old)
|
||||
```typescript
|
||||
const { peer, channel } = await client.discovery.connectByUuid('service-uuid');
|
||||
|
||||
channel.onmessage = (e) => {
|
||||
console.log('Received:', e.data);
|
||||
};
|
||||
```
|
||||
|
||||
#### v0.9.0 (New)
|
||||
```typescript
|
||||
const connection = await client.connectByUuid('service-uuid', {
|
||||
maxReconnectAttempts: 5
|
||||
});
|
||||
|
||||
const channel = connection.createChannel('main');
|
||||
|
||||
channel.on('message', (data) => {
|
||||
console.log('Received:', data);
|
||||
});
|
||||
|
||||
await connection.connect();
|
||||
```
|
||||
|
||||
**Key Differences:**
|
||||
- `client.discovery.connectByUuid()` → `client.connectByUuid()`
|
||||
- Returns `DurableConnection` instead of `{ peer, channel }`
|
||||
- Must create channels and connect explicitly
|
||||
|
||||
### 4. Multi-Connection Services (Offer Pooling)
|
||||
|
||||
#### v0.8.x (Old)
|
||||
```typescript
|
||||
const handle = await client.services.exposeService({
|
||||
username: 'alice',
|
||||
privateKey: keypair.privateKey,
|
||||
serviceFqn: 'chat@1.0.0',
|
||||
poolSize: 5,
|
||||
pollingInterval: 2000,
|
||||
handler: (channel, peer, connectionId) => {
|
||||
console.log(`Connection: ${connectionId}`);
|
||||
},
|
||||
onPoolStatus: (status) => {
|
||||
console.log('Pool status:', status);
|
||||
}
|
||||
});
|
||||
|
||||
const status = handle.getStatus();
|
||||
await handle.addOffers(3);
|
||||
```
|
||||
|
||||
#### v0.9.0 (New)
|
||||
```typescript
|
||||
const service = await client.exposeService({
|
||||
username: 'alice',
|
||||
privateKey: keypair.privateKey,
|
||||
serviceFqn: 'chat@1.0.0',
|
||||
poolSize: 5, // SAME: Pool size
|
||||
pollingInterval: 2000, // SAME: Polling interval
|
||||
handler: (channel, connectionId) => {
|
||||
console.log(`Connection: ${connectionId}`);
|
||||
}
|
||||
});
|
||||
|
||||
await service.start();
|
||||
|
||||
// Get active connections
|
||||
const connections = service.getActiveConnections();
|
||||
|
||||
// Listen for connection events
|
||||
service.on('connection', (connectionId) => {
|
||||
console.log('New connection:', connectionId);
|
||||
});
|
||||
```
|
||||
|
||||
**Key Differences:**
|
||||
- `onPoolStatus` callback removed (use `service.on('connection')` instead)
|
||||
- `handle.getStatus()` replaced with `service.getActiveConnections()`
|
||||
- `handle.addOffers()` removed (pool auto-manages offers)
|
||||
- Handler receives `DurableChannel` instead of `RTCDataChannel`
|
||||
|
||||
## Feature Comparison
|
||||
|
||||
| Feature | v0.8.x | v0.9.0 |
|
||||
|---------|--------|--------|
|
||||
| Service exposure | `client.services.exposeService()` | `client.exposeService()` |
|
||||
| Connection | `client.discovery.connect()` | `client.connect()` |
|
||||
| Connection by UUID | `client.discovery.connectByUuid()` | `client.connectByUuid()` |
|
||||
| Channel type | `RTCDataChannel` | `DurableChannel` |
|
||||
| Event handling | `.onmessage`, `.onopen`, etc. | `.on('message')`, `.on('open')`, etc. |
|
||||
| Automatic reconnection | ❌ No | ✅ Yes (configurable) |
|
||||
| Message queuing | ❌ No | ✅ Yes (during disconnections) |
|
||||
| TTL auto-refresh | ❌ No | ✅ Yes (configurable) |
|
||||
| Peer lifecycle | Manual | Automatic |
|
||||
| Connection pooling | ✅ Yes | ✅ Yes (same API) |
|
||||
|
||||
## API Mapping
|
||||
|
||||
### Removed Exports
|
||||
|
||||
These are no longer exported in v0.9.0:
|
||||
|
||||
```typescript
|
||||
// ❌ Removed
|
||||
import {
|
||||
RondevuServices,
|
||||
RondevuDiscovery,
|
||||
RondevuPeer,
|
||||
ServiceHandle,
|
||||
PooledServiceHandle,
|
||||
ConnectResult
|
||||
} from '@xtr-dev/rondevu-client';
|
||||
```
|
||||
|
||||
### New Exports
|
||||
|
||||
These are new in v0.9.0:
|
||||
|
||||
```typescript
|
||||
// ✅ New
|
||||
import {
|
||||
DurableConnection,
|
||||
DurableChannel,
|
||||
DurableService,
|
||||
DurableConnectionState,
|
||||
DurableChannelState,
|
||||
DurableConnectionConfig,
|
||||
DurableChannelConfig,
|
||||
DurableServiceConfig,
|
||||
DurableConnectionEvents,
|
||||
DurableChannelEvents,
|
||||
DurableServiceEvents,
|
||||
ConnectionInfo,
|
||||
ServiceInfo,
|
||||
QueuedMessage
|
||||
} from '@xtr-dev/rondevu-client';
|
||||
```
|
||||
|
||||
### Unchanged Exports
|
||||
|
||||
These work the same in both versions:
|
||||
|
||||
```typescript
|
||||
// ✅ Unchanged
|
||||
import {
|
||||
Rondevu,
|
||||
RondevuAuth,
|
||||
RondevuUsername,
|
||||
Credentials,
|
||||
UsernameClaimResult,
|
||||
UsernameCheckResult
|
||||
} from '@xtr-dev/rondevu-client';
|
||||
```
|
||||
|
||||
## Configuration Options
|
||||
|
||||
### New Connection Options
|
||||
|
||||
v0.9.0 adds extensive configuration for automatic reconnection and message queuing:
|
||||
|
||||
```typescript
|
||||
const connection = await client.connect('alice', 'chat@1.0.0', {
|
||||
// Reconnection
|
||||
maxReconnectAttempts: 10, // default: 10
|
||||
reconnectBackoffBase: 1000, // default: 1000ms
|
||||
reconnectBackoffMax: 30000, // default: 30000ms (30 seconds)
|
||||
reconnectJitter: 0.2, // default: 0.2 (±20%)
|
||||
connectionTimeout: 30000, // default: 30000ms
|
||||
|
||||
// Message queuing
|
||||
maxQueueSize: 1000, // default: 1000 messages
|
||||
maxMessageAge: 60000, // default: 60000ms (1 minute)
|
||||
|
||||
// WebRTC
|
||||
rtcConfig: {
|
||||
iceServers: [...]
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
### New Service Options
|
||||
|
||||
Services can now auto-refresh TTL:
|
||||
|
||||
```typescript
|
||||
const service = await client.exposeService({
|
||||
username: 'alice',
|
||||
privateKey: keypair.privateKey,
|
||||
serviceFqn: 'chat@1.0.0',
|
||||
|
||||
// TTL auto-refresh (NEW)
|
||||
ttl: 300000, // default: 300000ms (5 minutes)
|
||||
ttlRefreshMargin: 0.2, // default: 0.2 (refresh at 80% of TTL)
|
||||
|
||||
// All connection options also apply to incoming connections
|
||||
maxReconnectAttempts: 10,
|
||||
maxQueueSize: 1000,
|
||||
// ...
|
||||
});
|
||||
```
|
||||
|
||||
## Migration Checklist
|
||||
|
||||
- [ ] Replace `client.services.exposeService()` with `client.exposeService()`
|
||||
- [ ] Add `await service.start()` after creating service
|
||||
- [ ] Replace `handle.unpublish()` with `service.stop()`
|
||||
- [ ] Replace `client.discovery.connect()` with `client.connect()`
|
||||
- [ ] Replace `client.discovery.connectByUuid()` with `client.connectByUuid()`
|
||||
- [ ] Create channels with `connection.createChannel()` instead of receiving them directly
|
||||
- [ ] Add `await connection.connect()` to establish connection
|
||||
- [ ] Update handlers from `(channel, peer, connectionId?)` to `(channel, connectionId)`
|
||||
- [ ] Replace `.onmessage` with `.on('message', ...)`
|
||||
- [ ] Replace `.onopen` with `.on('open', ...)`
|
||||
- [ ] Replace `.onclose` with `.on('close', ...)`
|
||||
- [ ] Replace `.onerror` with `.on('error', ...)`
|
||||
- [ ] Add reconnection event handlers (`connection.on('reconnecting', ...)`)
|
||||
- [ ] Review and configure reconnection options if needed
|
||||
- [ ] Review and configure message queue limits if needed
|
||||
- [ ] Update TypeScript imports to use new types
|
||||
- [ ] Test automatic reconnection behavior
|
||||
- [ ] Test message queuing during disconnections
|
||||
|
||||
## Common Migration Patterns
|
||||
|
||||
### Pattern 1: Simple Echo Service
|
||||
|
||||
#### Before (v0.8.x)
|
||||
```typescript
|
||||
await client.services.exposeService({
|
||||
username: 'alice',
|
||||
privateKey: keypair.privateKey,
|
||||
serviceFqn: 'echo@1.0.0',
|
||||
handler: (channel) => {
|
||||
channel.onmessage = (e) => {
|
||||
channel.send(`Echo: ${e.data}`);
|
||||
};
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
#### After (v0.9.0)
|
||||
```typescript
|
||||
const service = await client.exposeService({
|
||||
username: 'alice',
|
||||
privateKey: keypair.privateKey,
|
||||
serviceFqn: 'echo@1.0.0',
|
||||
handler: (channel) => {
|
||||
channel.on('message', (data) => {
|
||||
channel.send(`Echo: ${data}`);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
await service.start();
|
||||
```
|
||||
|
||||
### Pattern 2: Connection with Error Handling
|
||||
|
||||
#### Before (v0.8.x)
|
||||
```typescript
|
||||
try {
|
||||
const { peer, channel } = await client.discovery.connect('alice', 'chat@1.0.0');
|
||||
|
||||
channel.onopen = () => {
|
||||
channel.send('Hello!');
|
||||
};
|
||||
|
||||
peer.on('failed', (error) => {
|
||||
console.error('Connection failed:', error);
|
||||
// Manual reconnection logic here
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Failed to connect:', error);
|
||||
}
|
||||
```
|
||||
|
||||
#### After (v0.9.0)
|
||||
```typescript
|
||||
const connection = await client.connect('alice', 'chat@1.0.0', {
|
||||
maxReconnectAttempts: 5
|
||||
});
|
||||
|
||||
const channel = connection.createChannel('main');
|
||||
|
||||
channel.on('open', () => {
|
||||
channel.send('Hello!');
|
||||
});
|
||||
|
||||
connection.on('reconnecting', (attempt, max, delay) => {
|
||||
console.log(`Reconnecting (${attempt}/${max}) in ${delay}ms`);
|
||||
});
|
||||
|
||||
connection.on('failed', (error) => {
|
||||
console.error('Connection failed permanently:', error);
|
||||
});
|
||||
|
||||
try {
|
||||
await connection.connect();
|
||||
} catch (error) {
|
||||
console.error('Initial connection failed:', error);
|
||||
}
|
||||
```
|
||||
|
||||
### Pattern 3: Multi-User Chat Server
|
||||
|
||||
#### Before (v0.8.x)
|
||||
```typescript
|
||||
const connections = new Map();
|
||||
|
||||
await client.services.exposeService({
|
||||
username: 'alice',
|
||||
privateKey: keypair.privateKey,
|
||||
serviceFqn: 'chat@1.0.0',
|
||||
poolSize: 10,
|
||||
handler: (channel, peer, connectionId) => {
|
||||
connections.set(connectionId, channel);
|
||||
|
||||
channel.onmessage = (e) => {
|
||||
// Broadcast to all
|
||||
for (const [id, ch] of connections) {
|
||||
if (id !== connectionId) {
|
||||
ch.send(e.data);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
channel.onclose = () => {
|
||||
connections.delete(connectionId);
|
||||
};
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
#### After (v0.9.0)
|
||||
```typescript
|
||||
const channels = new Map();
|
||||
|
||||
const service = await client.exposeService({
|
||||
username: 'alice',
|
||||
privateKey: keypair.privateKey,
|
||||
serviceFqn: 'chat@1.0.0',
|
||||
poolSize: 10,
|
||||
handler: (channel, connectionId) => {
|
||||
channels.set(connectionId, channel);
|
||||
|
||||
channel.on('message', (data) => {
|
||||
// Broadcast to all
|
||||
for (const [id, ch] of channels) {
|
||||
if (id !== connectionId) {
|
||||
ch.send(data);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
channel.on('close', () => {
|
||||
channels.delete(connectionId);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
await service.start();
|
||||
|
||||
// Optional: Track connections
|
||||
service.on('connection', (connectionId) => {
|
||||
console.log(`User ${connectionId} joined`);
|
||||
});
|
||||
|
||||
service.on('disconnection', (connectionId) => {
|
||||
console.log(`User ${connectionId} left`);
|
||||
});
|
||||
```
|
||||
|
||||
## Benefits of Migration
|
||||
|
||||
1. **Reliability**: Automatic reconnection handles network hiccups transparently
|
||||
2. **Simplicity**: No need to manage WebRTC peer lifecycle manually
|
||||
3. **Durability**: Messages sent during disconnections are queued and delivered when connection restores
|
||||
4. **Uptime**: Services automatically refresh TTL before expiration
|
||||
5. **Type Safety**: Better TypeScript types with DurableChannel event emitters
|
||||
6. **Debugging**: Queue size monitoring, connection state tracking, and detailed events
|
||||
|
||||
## Getting Help
|
||||
|
||||
If you encounter issues during migration:
|
||||
1. Check the [README](./README.md) for complete API documentation
|
||||
2. Review the examples for common patterns
|
||||
3. Open an issue on [GitHub](https://github.com/xtr-dev/rondevu-client/issues)
|
||||
494
README.md
494
README.md
@@ -1,82 +1,458 @@
|
||||
# Rondevu
|
||||
|
||||
🎯 **Simple WebRTC peer signaling and discovery**
|
||||
|
||||
Meet peers by topic, by peer ID, or by connection ID.
|
||||
|
||||
**Related repositories:**
|
||||
- [rondevu-server](https://github.com/xtr-dev/rondevu-server) - HTTP signaling server
|
||||
- [rondevu-demo](https://github.com/xtr-dev/rondevu-demo) - Interactive demo
|
||||
|
||||
---
|
||||
|
||||
## @xtr-dev/rondevu-client
|
||||
# Rondevu Client
|
||||
|
||||
[](https://www.npmjs.com/package/@xtr-dev/rondevu-client)
|
||||
|
||||
TypeScript client library for Rondevu peer signaling and WebRTC connection management. Handles automatic signaling, ICE candidate exchange, and connection establishment.
|
||||
🌐 **Simple, high-level WebRTC peer-to-peer connections**
|
||||
|
||||
### Install
|
||||
TypeScript/JavaScript client for Rondevu, providing easy-to-use WebRTC connections with automatic signaling, username-based discovery, and built-in reconnection support.
|
||||
|
||||
**Related repositories:**
|
||||
- [@xtr-dev/rondevu-client](https://github.com/xtr-dev/rondevu-client) - TypeScript client library ([npm](https://www.npmjs.com/package/@xtr-dev/rondevu-client))
|
||||
- [@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))
|
||||
|
||||
---
|
||||
|
||||
## Features
|
||||
|
||||
- **High-Level Wrappers**: ServiceHost and ServiceClient eliminate WebRTC boilerplate
|
||||
- **Username-Based Discovery**: Connect to peers by username, not complex offer/answer exchange
|
||||
- **Semver-Compatible Matching**: Requesting chat@1.0.0 matches any compatible 1.x.x version
|
||||
- **Privacy-First Design**: Services are hidden by default - no enumeration possible
|
||||
- **Automatic Reconnection**: Built-in retry logic with exponential backoff
|
||||
- **Message Queuing**: Messages sent while disconnected are queued and flushed on reconnect
|
||||
- **Cryptographic Username Claiming**: Secure ownership with Ed25519 signatures
|
||||
- **Service Publishing**: Package-style naming (chat.app@1.0.0) with multiple simultaneous offers
|
||||
- **TypeScript**: Full type safety and autocomplete
|
||||
- **Configurable Polling**: Exponential backoff with jitter to reduce server load
|
||||
|
||||
## Install
|
||||
|
||||
```bash
|
||||
npm install @xtr-dev/rondevu-client
|
||||
```
|
||||
|
||||
### Usage
|
||||
## Quick Start
|
||||
|
||||
### Hosting a Service (Alice)
|
||||
|
||||
```typescript
|
||||
import { Rondevu } from '@xtr-dev/rondevu-client';
|
||||
import { RondevuService, ServiceHost } from '@xtr-dev/rondevu-client'
|
||||
|
||||
const rdv = new Rondevu({
|
||||
baseUrl: 'https://server.com',
|
||||
rtcConfig: {
|
||||
iceServers: [
|
||||
// your ICE servers here
|
||||
{ urls: 'stun:stun.l.google.com:19302' },
|
||||
{ urls: 'stun:stun1.l.google.com:19302' },
|
||||
{
|
||||
urls: 'turn:relay1.example.com:3480',
|
||||
username: 'example',
|
||||
credential: 'example'
|
||||
}
|
||||
]
|
||||
}
|
||||
});
|
||||
// Step 1: Create and initialize service
|
||||
const service = new RondevuService({
|
||||
apiUrl: 'https://api.ronde.vu',
|
||||
username: 'alice'
|
||||
})
|
||||
|
||||
// Connect by topic
|
||||
const conn = await rdv.join('room');
|
||||
await service.initialize() // Generates keypair
|
||||
await service.claimUsername() // Claims username with signature
|
||||
|
||||
// Or connect by ID
|
||||
const conn = await rdv.connect('meeting-123');
|
||||
// Step 2: Create ServiceHost
|
||||
const host = new ServiceHost({
|
||||
service: 'chat.app@1.0.0',
|
||||
rondevuService: service,
|
||||
maxPeers: 5, // Accept up to 5 connections
|
||||
ttl: 300000 // 5 minutes
|
||||
})
|
||||
|
||||
// Use the connection
|
||||
conn.on('connect', () => {
|
||||
const channel = conn.dataChannel('chat');
|
||||
channel.send('Hello!');
|
||||
});
|
||||
// Step 3: Listen for incoming connections
|
||||
host.events.on('connection', (connection) => {
|
||||
console.log('✅ New connection!')
|
||||
|
||||
connection.events.on('message', (msg) => {
|
||||
console.log('📨 Received:', msg)
|
||||
connection.sendMessage('Hello from Alice!')
|
||||
})
|
||||
|
||||
connection.events.on('state-change', (state) => {
|
||||
console.log('Connection state:', state)
|
||||
})
|
||||
})
|
||||
|
||||
host.events.on('error', (error) => {
|
||||
console.error('Host error:', error)
|
||||
})
|
||||
|
||||
// Step 4: Start hosting
|
||||
await host.start()
|
||||
console.log('Service is now live! Others can connect to @alice')
|
||||
|
||||
// Later: stop hosting
|
||||
host.dispose()
|
||||
```
|
||||
|
||||
### API
|
||||
### Connecting to a Service (Bob)
|
||||
|
||||
**Main Methods:**
|
||||
- `rdv.join(topic)` - Auto-connect to first peer in topic
|
||||
- `rdv.join(topic, {filter})` - Connect to specific peer by ID
|
||||
- `rdv.create(id, topic)` - Create connection for others to join
|
||||
- `rdv.connect(id)` - Join connection by ID
|
||||
```typescript
|
||||
import { RondevuService, ServiceClient } from '@xtr-dev/rondevu-client'
|
||||
|
||||
**Connection Events:**
|
||||
- `connect` - Connection established
|
||||
- `disconnect` - Connection closed
|
||||
- `datachannel` - Remote peer created data channel
|
||||
- `stream` - Remote media stream received
|
||||
- `error` - Error occurred
|
||||
// Step 1: Create and initialize service
|
||||
const service = new RondevuService({
|
||||
apiUrl: 'https://api.ronde.vu',
|
||||
username: 'bob'
|
||||
})
|
||||
|
||||
**Connection Methods:**
|
||||
- `conn.dataChannel(label)` - Get or create data channel
|
||||
- `conn.addStream(stream)` - Add media stream
|
||||
- `conn.getPeerConnection()` - Get underlying RTCPeerConnection
|
||||
- `conn.close()` - Close connection
|
||||
await service.initialize()
|
||||
await service.claimUsername()
|
||||
|
||||
### License
|
||||
// Step 2: Create ServiceClient
|
||||
const client = new ServiceClient({
|
||||
username: 'alice', // Connect to Alice
|
||||
serviceFqn: 'chat.app@1.0.0',
|
||||
rondevuService: service,
|
||||
autoReconnect: true,
|
||||
maxReconnectAttempts: 5
|
||||
})
|
||||
|
||||
// Step 3: Listen for connection events
|
||||
client.events.on('connected', (connection) => {
|
||||
console.log('✅ Connected to Alice!')
|
||||
|
||||
connection.events.on('message', (msg) => {
|
||||
console.log('📨 Received:', msg)
|
||||
})
|
||||
|
||||
// Send a message
|
||||
connection.sendMessage('Hello from Bob!')
|
||||
})
|
||||
|
||||
client.events.on('disconnected', () => {
|
||||
console.log('🔌 Disconnected')
|
||||
})
|
||||
|
||||
client.events.on('reconnecting', ({ attempt, maxAttempts }) => {
|
||||
console.log(`🔄 Reconnecting (${attempt}/${maxAttempts})...`)
|
||||
})
|
||||
|
||||
client.events.on('error', (error) => {
|
||||
console.error('❌ Error:', error)
|
||||
})
|
||||
|
||||
// Step 4: Connect
|
||||
await client.connect()
|
||||
|
||||
// Later: disconnect
|
||||
client.dispose()
|
||||
```
|
||||
|
||||
## Core Concepts
|
||||
|
||||
### RondevuService
|
||||
|
||||
Handles authentication and username management:
|
||||
- Generates Ed25519 keypair for signing
|
||||
- Claims usernames with cryptographic proof
|
||||
- Provides API client for signaling server
|
||||
|
||||
### ServiceHost
|
||||
|
||||
High-level wrapper for hosting a WebRTC service:
|
||||
- Automatically creates and publishes offers
|
||||
- Handles incoming connections
|
||||
- Manages ICE candidate exchange
|
||||
- Supports multiple simultaneous peers
|
||||
|
||||
### ServiceClient
|
||||
|
||||
High-level wrapper for connecting to services:
|
||||
- Discovers services by username
|
||||
- Handles offer/answer exchange automatically
|
||||
- Built-in auto-reconnection with exponential backoff
|
||||
- Event-driven API
|
||||
|
||||
### RTCDurableConnection
|
||||
|
||||
Low-level connection wrapper (used internally):
|
||||
- Manages WebRTC PeerConnection lifecycle
|
||||
- Handles ICE candidate polling
|
||||
- Provides message queue for reliability
|
||||
- State management and events
|
||||
|
||||
## API Reference
|
||||
|
||||
### RondevuService
|
||||
|
||||
```typescript
|
||||
const service = new RondevuService({
|
||||
apiUrl: string, // Signaling server URL
|
||||
username: string, // Your username
|
||||
keypair?: Keypair // Optional: reuse existing keypair
|
||||
})
|
||||
|
||||
// Initialize service (generates keypair if not provided)
|
||||
await service.initialize(): Promise<void>
|
||||
|
||||
// Claim username with cryptographic signature
|
||||
await service.claimUsername(): Promise<void>
|
||||
|
||||
// Check if username is claimed
|
||||
service.isUsernameClaimed(): boolean
|
||||
|
||||
// Get current username
|
||||
service.getUsername(): string
|
||||
|
||||
// Get keypair
|
||||
service.getKeypair(): Keypair
|
||||
|
||||
// Get API client
|
||||
service.getAPI(): RondevuAPI
|
||||
```
|
||||
|
||||
### ServiceHost
|
||||
|
||||
```typescript
|
||||
const host = new ServiceHost({
|
||||
service: string, // Service FQN (e.g., 'chat.app@1.0.0')
|
||||
rondevuService: RondevuService,
|
||||
maxPeers?: number, // Default: 5
|
||||
ttl?: number, // Default: 300000 (5 minutes)
|
||||
isPublic?: boolean, // Default: true
|
||||
rtcConfiguration?: RTCConfiguration
|
||||
})
|
||||
|
||||
// Start hosting
|
||||
await host.start(): Promise<void>
|
||||
|
||||
// Stop hosting and cleanup
|
||||
host.dispose(): void
|
||||
|
||||
// Get all active connections
|
||||
host.getConnections(): RTCDurableConnection[]
|
||||
|
||||
// Events
|
||||
host.events.on('connection', (conn: RTCDurableConnection) => {})
|
||||
host.events.on('error', (error: Error) => {})
|
||||
```
|
||||
|
||||
### ServiceClient
|
||||
|
||||
```typescript
|
||||
const client = new ServiceClient({
|
||||
username: string, // Host username to connect to
|
||||
serviceFqn: string, // Service FQN (e.g., 'chat.app@1.0.0')
|
||||
rondevuService: RondevuService,
|
||||
autoReconnect?: boolean, // Default: true
|
||||
maxReconnectAttempts?: number, // Default: 5
|
||||
rtcConfiguration?: RTCConfiguration
|
||||
})
|
||||
|
||||
// Connect to service
|
||||
await client.connect(): Promise<RTCDurableConnection>
|
||||
|
||||
// Disconnect and cleanup
|
||||
client.dispose(): void
|
||||
|
||||
// Get current connection
|
||||
client.getConnection(): RTCDurableConnection | null
|
||||
|
||||
// Events
|
||||
client.events.on('connected', (conn: RTCDurableConnection) => {})
|
||||
client.events.on('disconnected', () => {})
|
||||
client.events.on('reconnecting', (info: { attempt: number, maxAttempts: number }) => {})
|
||||
client.events.on('error', (error: Error) => {})
|
||||
```
|
||||
|
||||
### RTCDurableConnection
|
||||
|
||||
```typescript
|
||||
// Connection state
|
||||
connection.state: 'connected' | 'connecting' | 'disconnected'
|
||||
|
||||
// Send message (returns true if sent, false if queued)
|
||||
await connection.sendMessage(message: string): Promise<boolean>
|
||||
|
||||
// Queue message for sending when connected
|
||||
await connection.queueMessage(message: string, options?: QueueMessageOptions): Promise<void>
|
||||
|
||||
// Disconnect
|
||||
connection.disconnect(): void
|
||||
|
||||
// Events
|
||||
connection.events.on('message', (msg: string) => {})
|
||||
connection.events.on('state-change', (state: ConnectionStates) => {})
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
### Polling Configuration
|
||||
|
||||
The signaling uses configurable polling with exponential backoff:
|
||||
|
||||
```typescript
|
||||
// Default polling config
|
||||
{
|
||||
initialInterval: 500, // Start at 500ms
|
||||
maxInterval: 5000, // Max 5 seconds
|
||||
backoffMultiplier: 1.5, // Increase by 1.5x each time
|
||||
maxRetries: 50, // Max 50 attempts
|
||||
jitter: true // Add random 0-100ms to prevent thundering herd
|
||||
}
|
||||
```
|
||||
|
||||
This is handled automatically - no configuration needed.
|
||||
|
||||
### WebRTC Configuration
|
||||
|
||||
Provide custom STUN/TURN servers:
|
||||
|
||||
```typescript
|
||||
const host = new ServiceHost({
|
||||
service: 'chat.app@1.0.0',
|
||||
rondevuService: service,
|
||||
rtcConfiguration: {
|
||||
iceServers: [
|
||||
{ urls: 'stun:stun.l.google.com:19302' },
|
||||
{
|
||||
urls: 'turn:turn.example.com:3478',
|
||||
username: 'user',
|
||||
credential: 'pass'
|
||||
}
|
||||
]
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
## Username Rules
|
||||
|
||||
- **Format**: Lowercase alphanumeric + dash (`a-z`, `0-9`, `-`)
|
||||
- **Length**: 3-32 characters
|
||||
- **Pattern**: `^[a-z0-9][a-z0-9-]*[a-z0-9]$`
|
||||
- **Validity**: 365 days from claim/last use
|
||||
- **Ownership**: Secured by Ed25519 public key signature
|
||||
|
||||
## Examples
|
||||
|
||||
### Chat Application
|
||||
|
||||
See [demo/demo.js](./demo/demo.js) for a complete working example.
|
||||
|
||||
### Persistent Keypair
|
||||
|
||||
```typescript
|
||||
// Save keypair to localStorage
|
||||
const service = new RondevuService({
|
||||
apiUrl: 'https://api.ronde.vu',
|
||||
username: 'alice'
|
||||
})
|
||||
|
||||
await service.initialize()
|
||||
await service.claimUsername()
|
||||
|
||||
// Save for later
|
||||
localStorage.setItem('rondevu-keypair', JSON.stringify(service.getKeypair()))
|
||||
localStorage.setItem('rondevu-username', service.getUsername())
|
||||
|
||||
// Load on next session
|
||||
const savedKeypair = JSON.parse(localStorage.getItem('rondevu-keypair'))
|
||||
const savedUsername = localStorage.getItem('rondevu-username')
|
||||
|
||||
const service2 = new RondevuService({
|
||||
apiUrl: 'https://api.ronde.vu',
|
||||
username: savedUsername,
|
||||
keypair: savedKeypair
|
||||
})
|
||||
|
||||
await service2.initialize() // Reuses keypair
|
||||
```
|
||||
|
||||
### Message Queue Example
|
||||
|
||||
```typescript
|
||||
// Messages are automatically queued if not connected yet
|
||||
client.events.on('connected', (connection) => {
|
||||
// Send immediately
|
||||
connection.sendMessage('Hello!')
|
||||
})
|
||||
|
||||
// Or queue for later
|
||||
await client.connect()
|
||||
const conn = client.getConnection()
|
||||
await conn.queueMessage('This will be sent when connected', {
|
||||
expiresAt: Date.now() + 60000 // Expire after 1 minute
|
||||
})
|
||||
```
|
||||
|
||||
## Migration from v0.9.x
|
||||
|
||||
v0.11.0+ introduces high-level wrappers, RESTful API changes, and semver-compatible discovery:
|
||||
|
||||
**API Changes:**
|
||||
- Server endpoints restructured (`/usernames/*` → `/users/*`)
|
||||
- Added `ServiceHost` and `ServiceClient` wrappers
|
||||
- Message queue fully implemented
|
||||
- Configurable polling with exponential backoff
|
||||
- Removed deprecated `cleanup()` methods (use `dispose()`)
|
||||
- **v0.11.0+**: Services use `offers` array instead of single `sdp`
|
||||
- **v0.11.0+**: Semver-compatible service discovery (chat@1.0.0 matches 1.x.x)
|
||||
- **v0.11.0+**: All services are hidden - no listing endpoint
|
||||
- **v0.11.0+**: Services support multiple simultaneous offers for connection pooling
|
||||
|
||||
**Migration Guide:**
|
||||
|
||||
```typescript
|
||||
// Before (v0.9.x) - Manual WebRTC setup
|
||||
const signaler = new RondevuSignaler(service, 'chat@1.0.0')
|
||||
const context = new WebRTCContext()
|
||||
const pc = context.createPeerConnection()
|
||||
// ... 50+ lines of boilerplate
|
||||
|
||||
// After (v0.11.0) - ServiceHost wrapper
|
||||
const host = new ServiceHost({
|
||||
service: 'chat@1.0.0',
|
||||
rondevuService: service
|
||||
})
|
||||
await host.start()
|
||||
// Done!
|
||||
```
|
||||
|
||||
## Platform Support
|
||||
|
||||
### Modern Browsers
|
||||
Works out of the box - no additional setup needed.
|
||||
|
||||
### Node.js 18+
|
||||
Native fetch is available, but WebRTC requires polyfills:
|
||||
|
||||
```bash
|
||||
npm install wrtc
|
||||
```
|
||||
|
||||
```typescript
|
||||
import { WebRTCContext } from '@xtr-dev/rondevu-client'
|
||||
import { RTCPeerConnection, RTCSessionDescription, RTCIceCandidate } from 'wrtc'
|
||||
|
||||
// Configure WebRTC context
|
||||
const context = new WebRTCContext({
|
||||
RTCPeerConnection,
|
||||
RTCSessionDescription,
|
||||
RTCIceCandidate
|
||||
} as any)
|
||||
```
|
||||
|
||||
## TypeScript
|
||||
|
||||
All types are exported:
|
||||
|
||||
```typescript
|
||||
import type {
|
||||
RondevuServiceOptions,
|
||||
ServiceHostOptions,
|
||||
ServiceHostEvents,
|
||||
ServiceClientOptions,
|
||||
ServiceClientEvents,
|
||||
ConnectionInterface,
|
||||
ConnectionEvents,
|
||||
ConnectionStates,
|
||||
Message,
|
||||
QueueMessageOptions,
|
||||
Signaler,
|
||||
PollingConfig,
|
||||
Credentials,
|
||||
Keypair
|
||||
} from '@xtr-dev/rondevu-client'
|
||||
```
|
||||
|
||||
## License
|
||||
|
||||
MIT
|
||||
|
||||
281
USAGE.md
Normal file
281
USAGE.md
Normal file
@@ -0,0 +1,281 @@
|
||||
# Rondevu Client Usage Guide
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
npm install @xtr-dev/rondevu-client
|
||||
```
|
||||
|
||||
## Quick Start
|
||||
|
||||
### 1. Register and Create Connection
|
||||
|
||||
```typescript
|
||||
import { RondevuAPI, RondevuSignaler, WebRTCRondevuConnection } from '@xtr-dev/rondevu-client';
|
||||
|
||||
const API_URL = 'https://api.ronde.vu';
|
||||
|
||||
// Register to get credentials
|
||||
const api = new RondevuAPI(API_URL);
|
||||
const credentials = await api.register();
|
||||
|
||||
// Create authenticated API client
|
||||
const authenticatedApi = new RondevuAPI(API_URL, credentials);
|
||||
```
|
||||
|
||||
### 2. Create an Offer (Offerer Side)
|
||||
|
||||
```typescript
|
||||
// Create a connection
|
||||
const connection = new WebRTCRondevuConnection(
|
||||
'connection-id',
|
||||
'host-username',
|
||||
'service-name'
|
||||
);
|
||||
|
||||
// Wait for local description
|
||||
await connection.ready;
|
||||
|
||||
// Create offer on server
|
||||
const offers = await authenticatedApi.createOffers([{
|
||||
sdp: connection.connection.localDescription!.sdp!,
|
||||
ttl: 300000 // 5 minutes
|
||||
}]);
|
||||
|
||||
const offerId = offers[0].id;
|
||||
|
||||
// Set up signaler for ICE candidate exchange
|
||||
const signaler = new RondevuSignaler(authenticatedApi, offerId);
|
||||
connection.setSignaler(signaler);
|
||||
|
||||
// Poll for answer
|
||||
const checkAnswer = setInterval(async () => {
|
||||
const answer = await authenticatedApi.getAnswer(offerId);
|
||||
if (answer) {
|
||||
clearInterval(checkAnswer);
|
||||
await connection.connection.setRemoteDescription({
|
||||
type: 'answer',
|
||||
sdp: answer.sdp
|
||||
});
|
||||
console.log('Connection established!');
|
||||
}
|
||||
}, 1000);
|
||||
```
|
||||
|
||||
### 3. Answer an Offer (Answerer Side)
|
||||
|
||||
```typescript
|
||||
// Get the offer
|
||||
const offer = await authenticatedApi.getOffer(offerId);
|
||||
|
||||
// Create connection with remote offer
|
||||
const connection = new WebRTCRondevuConnection(
|
||||
'connection-id',
|
||||
'peer-username',
|
||||
'service-name',
|
||||
{
|
||||
type: 'offer',
|
||||
sdp: offer.sdp
|
||||
}
|
||||
);
|
||||
|
||||
// Wait for local description (answer)
|
||||
await connection.ready;
|
||||
|
||||
// Send answer to server
|
||||
await authenticatedApi.answerOffer(
|
||||
offerId,
|
||||
connection.connection.localDescription!.sdp!
|
||||
);
|
||||
|
||||
// Set up signaler for ICE candidate exchange
|
||||
const signaler = new RondevuSignaler(authenticatedApi, offerId);
|
||||
connection.setSignaler(signaler);
|
||||
|
||||
console.log('Connection established!');
|
||||
```
|
||||
|
||||
## Using Services
|
||||
|
||||
### Publish a Service
|
||||
|
||||
```typescript
|
||||
import { RondevuAPI } from '@xtr-dev/rondevu-client';
|
||||
|
||||
const api = new RondevuAPI(API_URL, credentials);
|
||||
|
||||
const service = await api.publishService({
|
||||
username: 'my-username',
|
||||
serviceFqn: 'chat.app@1.0.0',
|
||||
sdp: localDescription.sdp,
|
||||
ttl: 300000,
|
||||
isPublic: true,
|
||||
metadata: { description: 'My chat service' },
|
||||
signature: '...', // Ed25519 signature
|
||||
message: '...' // Signed message
|
||||
});
|
||||
|
||||
console.log('Service UUID:', service.uuid);
|
||||
```
|
||||
|
||||
### Connect to a Service
|
||||
|
||||
```typescript
|
||||
// Search for services
|
||||
const services = await api.searchServices('username', 'chat.app@1.0.0');
|
||||
|
||||
if (services.length > 0) {
|
||||
// Get service details with offer
|
||||
const service = await api.getService(services[0].uuid);
|
||||
|
||||
// Create connection with service offer
|
||||
const connection = new WebRTCRondevuConnection(
|
||||
service.serviceId,
|
||||
service.username,
|
||||
service.serviceFqn,
|
||||
{
|
||||
type: 'offer',
|
||||
sdp: service.sdp
|
||||
}
|
||||
);
|
||||
|
||||
await connection.ready;
|
||||
|
||||
// Answer the service offer
|
||||
await api.answerOffer(
|
||||
service.offerId,
|
||||
connection.connection.localDescription!.sdp!
|
||||
);
|
||||
|
||||
// Set up signaler
|
||||
const signaler = new RondevuSignaler(api, service.offerId);
|
||||
connection.setSignaler(signaler);
|
||||
}
|
||||
```
|
||||
|
||||
## Event Handling
|
||||
|
||||
```typescript
|
||||
import { EventBus } from '@xtr-dev/rondevu-client';
|
||||
|
||||
// Connection events
|
||||
connection.events.on('state-change', (state) => {
|
||||
console.log('Connection state:', state);
|
||||
});
|
||||
|
||||
connection.events.on('message', (message) => {
|
||||
console.log('Received message:', message);
|
||||
});
|
||||
|
||||
// Custom events with EventBus
|
||||
interface MyEvents {
|
||||
'user:connected': { userId: string; timestamp: number };
|
||||
'message:sent': string;
|
||||
}
|
||||
|
||||
const events = new EventBus<MyEvents>();
|
||||
|
||||
events.on('user:connected', (data) => {
|
||||
console.log(`User ${data.userId} connected at ${data.timestamp}`);
|
||||
});
|
||||
|
||||
events.emit('user:connected', {
|
||||
userId: '123',
|
||||
timestamp: Date.now()
|
||||
});
|
||||
```
|
||||
|
||||
## Cleanup
|
||||
|
||||
```typescript
|
||||
import { createBin } from '@xtr-dev/rondevu-client';
|
||||
|
||||
const bin = createBin();
|
||||
|
||||
// Add cleanup functions
|
||||
bin(
|
||||
() => console.log('Cleanup 1'),
|
||||
() => console.log('Cleanup 2')
|
||||
);
|
||||
|
||||
// Clean all
|
||||
bin.clean();
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
### RondevuAPI
|
||||
|
||||
Complete API client for Rondevu signaling server.
|
||||
|
||||
**Methods:**
|
||||
- `register()` - Register new peer
|
||||
- `createOffers(offers)` - Create offers
|
||||
- `getOffer(offerId)` - Get offer by ID
|
||||
- `answerOffer(offerId, sdp)` - Answer an offer
|
||||
- `getAnswer(offerId)` - Poll for answer
|
||||
- `searchOffers(topic)` - Search by topic
|
||||
- `addIceCandidates(offerId, candidates)` - Add ICE candidates
|
||||
- `getIceCandidates(offerId, since)` - Get ICE candidates (polling)
|
||||
- `publishService(service)` - Publish service
|
||||
- `getService(uuid)` - Get service by UUID
|
||||
- `searchServices(username, serviceFqn)` - Search services
|
||||
- `checkUsername(username)` - Check availability
|
||||
- `claimUsername(username, publicKey, signature, message)` - Claim username
|
||||
|
||||
### RondevuSignaler
|
||||
|
||||
Handles ICE candidate exchange via polling.
|
||||
|
||||
**Constructor:**
|
||||
```typescript
|
||||
new RondevuSignaler(api: RondevuAPI, offerId: string)
|
||||
```
|
||||
|
||||
**Methods:**
|
||||
- `addIceCandidate(candidate)` - Send local candidate
|
||||
- `addListener(callback)` - Poll for remote candidates (returns cleanup function)
|
||||
|
||||
### WebRTCRondevuConnection
|
||||
|
||||
WebRTC connection wrapper with type-safe events.
|
||||
|
||||
**Constructor:**
|
||||
```typescript
|
||||
new WebRTCRondevuConnection(
|
||||
id: string,
|
||||
host: string,
|
||||
service: string,
|
||||
offer?: RTCSessionDescriptionInit
|
||||
)
|
||||
```
|
||||
|
||||
**Properties:**
|
||||
- `id` - Connection ID
|
||||
- `host` - Host username
|
||||
- `service` - Service FQN
|
||||
- `state` - Connection state
|
||||
- `events` - EventBus for state changes and messages
|
||||
- `ready` - Promise that resolves when local description is set
|
||||
|
||||
**Methods:**
|
||||
- `setSignaler(signaler)` - Set signaler for ICE exchange
|
||||
- `queueMessage(message, options)` - Queue message for sending
|
||||
- `sendMessage(message)` - Send message immediately
|
||||
|
||||
### EventBus<TEvents>
|
||||
|
||||
Type-safe event emitter with inferred types.
|
||||
|
||||
**Methods:**
|
||||
- `on(event, handler)` - Subscribe
|
||||
- `once(event, handler)` - Subscribe once
|
||||
- `off(event, handler)` - Unsubscribe
|
||||
- `emit(event, data)` - Emit event
|
||||
- `clear(event?)` - Clear handlers
|
||||
- `listenerCount(event)` - Get listener count
|
||||
- `eventNames()` - Get event names
|
||||
|
||||
## Examples
|
||||
|
||||
See the demo application at https://github.com/xtr-dev/rondevu-demo for a complete working example.
|
||||
52
eslint.config.js
Normal file
52
eslint.config.js
Normal file
@@ -0,0 +1,52 @@
|
||||
import js from '@eslint/js'
|
||||
import tsPlugin from '@typescript-eslint/eslint-plugin'
|
||||
import tsParser from '@typescript-eslint/parser'
|
||||
import prettierConfig from 'eslint-config-prettier'
|
||||
import prettierPlugin from 'eslint-plugin-prettier'
|
||||
import unicorn from 'eslint-plugin-unicorn'
|
||||
import globals from 'globals'
|
||||
|
||||
export default [
|
||||
js.configs.recommended,
|
||||
{
|
||||
files: ['**/*.ts', '**/*.tsx', '**/*.js'],
|
||||
languageOptions: {
|
||||
parser: tsParser,
|
||||
parserOptions: {
|
||||
ecmaVersion: 'latest',
|
||||
sourceType: 'module',
|
||||
},
|
||||
globals: {
|
||||
...globals.browser,
|
||||
...globals.node,
|
||||
RTCPeerConnection: 'readonly',
|
||||
RTCIceCandidate: 'readonly',
|
||||
RTCSessionDescriptionInit: 'readonly',
|
||||
RTCIceCandidateInit: 'readonly',
|
||||
BufferSource: 'readonly',
|
||||
},
|
||||
},
|
||||
plugins: {
|
||||
'@typescript-eslint': tsPlugin,
|
||||
prettier: prettierPlugin,
|
||||
unicorn: unicorn,
|
||||
},
|
||||
rules: {
|
||||
...tsPlugin.configs.recommended.rules,
|
||||
...prettierConfig.rules,
|
||||
'prettier/prettier': 'error',
|
||||
'@typescript-eslint/no-explicit-any': 'off',
|
||||
'@typescript-eslint/no-unused-vars': ['warn', { argsIgnorePattern: '^_' }],
|
||||
'unicorn/filename-case': [
|
||||
'error',
|
||||
{
|
||||
case: 'kebabCase',
|
||||
ignore: ['^README\\.md$'],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
ignores: ['dist/**', 'node_modules/**', '*.config.js'],
|
||||
},
|
||||
]
|
||||
2997
package-lock.json
generated
Normal file
2997
package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
28
package.json
28
package.json
@@ -1,15 +1,18 @@
|
||||
{
|
||||
"name": "@xtr-dev/rondevu-client",
|
||||
"version": "0.1.2",
|
||||
"description": "TypeScript client for Rondevu peer signaling and discovery server",
|
||||
"version": "0.12.0",
|
||||
"description": "TypeScript client for Rondevu with durable WebRTC connections, automatic reconnection, and message queuing",
|
||||
"type": "module",
|
||||
"main": "dist/index.js",
|
||||
"types": "dist/index.d.ts",
|
||||
"scripts": {
|
||||
"build": "tsc",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"prepublishOnly": "npm run build",
|
||||
"publish": "npm publish"
|
||||
"dev": "vite",
|
||||
"lint": "eslint src demo --ext .ts,.tsx,.js",
|
||||
"lint:fix": "eslint src demo --ext .ts,.tsx,.js --fix",
|
||||
"format": "prettier --write \"src/**/*.{ts,tsx,js}\" \"demo/**/*.{ts,tsx,js,html}\"",
|
||||
"prepublishOnly": "npm run build"
|
||||
},
|
||||
"keywords": [
|
||||
"webrtc",
|
||||
@@ -21,10 +24,23 @@
|
||||
"author": "",
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
"typescript": "^5.9.3"
|
||||
"@eslint/js": "^9.39.1",
|
||||
"@typescript-eslint/eslint-plugin": "^8.48.1",
|
||||
"@typescript-eslint/parser": "^8.48.1",
|
||||
"eslint": "^9.39.1",
|
||||
"eslint-config-prettier": "^10.1.8",
|
||||
"eslint-plugin-prettier": "^5.5.4",
|
||||
"eslint-plugin-unicorn": "^62.0.0",
|
||||
"globals": "^16.5.0",
|
||||
"prettier": "^3.7.4",
|
||||
"typescript": "^5.9.3",
|
||||
"vite": "^7.2.6"
|
||||
},
|
||||
"files": [
|
||||
"dist",
|
||||
"README.md"
|
||||
]
|
||||
],
|
||||
"dependencies": {
|
||||
"@noble/ed25519": "^3.0.0"
|
||||
}
|
||||
}
|
||||
|
||||
466
src/api.ts
Normal file
466
src/api.ts
Normal file
@@ -0,0 +1,466 @@
|
||||
/**
|
||||
* Rondevu API Client - Single class for all API endpoints
|
||||
*/
|
||||
|
||||
import * as ed25519 from '@noble/ed25519'
|
||||
|
||||
// Set SHA-512 hash function for ed25519 (required in @noble/ed25519 v3+)
|
||||
ed25519.hashes.sha512Async = async (message: Uint8Array) => {
|
||||
return new Uint8Array(await crypto.subtle.digest('SHA-512', message as BufferSource))
|
||||
}
|
||||
|
||||
export interface Credentials {
|
||||
peerId: string
|
||||
secret: string
|
||||
}
|
||||
|
||||
export interface Keypair {
|
||||
publicKey: string
|
||||
privateKey: string
|
||||
}
|
||||
|
||||
export interface OfferRequest {
|
||||
sdp: string
|
||||
topics?: string[]
|
||||
ttl?: number
|
||||
secret?: string
|
||||
}
|
||||
|
||||
export interface Offer {
|
||||
id: string
|
||||
peerId: string
|
||||
sdp: string
|
||||
topics: string[]
|
||||
ttl: number
|
||||
createdAt: number
|
||||
expiresAt: number
|
||||
answererPeerId?: string
|
||||
}
|
||||
|
||||
export interface OfferRequest {
|
||||
sdp: string
|
||||
}
|
||||
|
||||
export interface ServiceRequest {
|
||||
username: string
|
||||
serviceFqn: string
|
||||
offers: OfferRequest[]
|
||||
ttl?: number
|
||||
isPublic?: boolean
|
||||
metadata?: Record<string, any>
|
||||
signature: string
|
||||
message: string
|
||||
}
|
||||
|
||||
export interface ServiceOffer {
|
||||
offerId: string
|
||||
sdp: string
|
||||
createdAt: number
|
||||
expiresAt: number
|
||||
}
|
||||
|
||||
export interface Service {
|
||||
serviceId: string
|
||||
uuid: string
|
||||
offers: ServiceOffer[]
|
||||
username: string
|
||||
serviceFqn: string
|
||||
isPublic: boolean
|
||||
metadata?: Record<string, any>
|
||||
createdAt: number
|
||||
expiresAt: number
|
||||
}
|
||||
|
||||
export interface IceCandidate {
|
||||
candidate: RTCIceCandidateInit
|
||||
createdAt: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper: Convert Uint8Array to base64 string
|
||||
*/
|
||||
function bytesToBase64(bytes: Uint8Array): string {
|
||||
const binString = Array.from(bytes, byte => String.fromCodePoint(byte)).join('')
|
||||
return btoa(binString)
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper: Convert base64 string to Uint8Array
|
||||
*/
|
||||
function base64ToBytes(base64: string): Uint8Array {
|
||||
const binString = atob(base64)
|
||||
return Uint8Array.from(binString, char => char.codePointAt(0)!)
|
||||
}
|
||||
|
||||
/**
|
||||
* RondevuAPI - Complete API client for Rondevu signaling server
|
||||
*/
|
||||
export class RondevuAPI {
|
||||
constructor(
|
||||
private baseUrl: string,
|
||||
private credentials?: Credentials
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Set credentials for authentication
|
||||
*/
|
||||
setCredentials(credentials: Credentials): void {
|
||||
this.credentials = credentials
|
||||
}
|
||||
|
||||
/**
|
||||
* Authentication header
|
||||
*/
|
||||
private getAuthHeader(): Record<string, string> {
|
||||
if (!this.credentials) {
|
||||
return {}
|
||||
}
|
||||
return {
|
||||
Authorization: `Bearer ${this.credentials.peerId}:${this.credentials.secret}`,
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Ed25519 Cryptography Helpers
|
||||
// ============================================
|
||||
|
||||
/**
|
||||
* Generate an Ed25519 keypair for username claiming and service publishing
|
||||
*/
|
||||
static async generateKeypair(): Promise<Keypair> {
|
||||
const privateKey = ed25519.utils.randomSecretKey()
|
||||
const publicKey = await ed25519.getPublicKeyAsync(privateKey)
|
||||
|
||||
return {
|
||||
publicKey: bytesToBase64(publicKey),
|
||||
privateKey: bytesToBase64(privateKey),
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sign a message with an Ed25519 private key
|
||||
*/
|
||||
static async signMessage(message: string, privateKeyBase64: string): Promise<string> {
|
||||
const privateKey = base64ToBytes(privateKeyBase64)
|
||||
const encoder = new TextEncoder()
|
||||
const messageBytes = encoder.encode(message)
|
||||
|
||||
const signature = await ed25519.signAsync(messageBytes, privateKey)
|
||||
return bytesToBase64(signature)
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify a signature
|
||||
*/
|
||||
static async verifySignature(
|
||||
message: string,
|
||||
signatureBase64: string,
|
||||
publicKeyBase64: string
|
||||
): Promise<boolean> {
|
||||
const publicKey = base64ToBytes(publicKeyBase64)
|
||||
const signature = base64ToBytes(signatureBase64)
|
||||
const encoder = new TextEncoder()
|
||||
const messageBytes = encoder.encode(message)
|
||||
|
||||
return await ed25519.verifyAsync(signature, messageBytes, publicKey)
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Authentication
|
||||
// ============================================
|
||||
|
||||
/**
|
||||
* Register a new peer and get credentials
|
||||
*/
|
||||
async register(): Promise<Credentials> {
|
||||
const response = await fetch(`${this.baseUrl}/register`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await response.json().catch(() => ({ error: 'Unknown error' }))
|
||||
throw new Error(`Registration failed: ${error.error || response.statusText}`)
|
||||
}
|
||||
|
||||
return await response.json()
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Offers
|
||||
// ============================================
|
||||
|
||||
/**
|
||||
* Create one or more offers
|
||||
*/
|
||||
async createOffers(offers: OfferRequest[]): Promise<Offer[]> {
|
||||
const response = await fetch(`${this.baseUrl}/offers`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...this.getAuthHeader(),
|
||||
},
|
||||
body: JSON.stringify({ offers }),
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await response.json().catch(() => ({ error: 'Unknown error' }))
|
||||
throw new Error(`Failed to create offers: ${error.error || response.statusText}`)
|
||||
}
|
||||
|
||||
return await response.json()
|
||||
}
|
||||
|
||||
/**
|
||||
* Get offer by ID
|
||||
*/
|
||||
async getOffer(offerId: string): Promise<Offer> {
|
||||
const response = await fetch(`${this.baseUrl}/offers/${offerId}`, {
|
||||
headers: this.getAuthHeader(),
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await response.json().catch(() => ({ error: 'Unknown error' }))
|
||||
throw new Error(`Failed to get offer: ${error.error || response.statusText}`)
|
||||
}
|
||||
|
||||
return await response.json()
|
||||
}
|
||||
|
||||
/**
|
||||
* Answer a service
|
||||
*/
|
||||
async answerService(serviceUuid: string, sdp: string): Promise<{ offerId: string }> {
|
||||
const response = await fetch(`${this.baseUrl}/services/${serviceUuid}/answer`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...this.getAuthHeader(),
|
||||
},
|
||||
body: JSON.stringify({ sdp }),
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await response.json().catch(() => ({ error: 'Unknown error' }))
|
||||
throw new Error(`Failed to answer service: ${error.error || response.statusText}`)
|
||||
}
|
||||
|
||||
return await response.json()
|
||||
}
|
||||
|
||||
/**
|
||||
* Get answer for a service (offerer polls this)
|
||||
*/
|
||||
async getServiceAnswer(serviceUuid: string): Promise<{ sdp: string; offerId: string } | null> {
|
||||
const response = await fetch(`${this.baseUrl}/services/${serviceUuid}/answer`, {
|
||||
headers: this.getAuthHeader(),
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
// 404 means not yet answered
|
||||
if (response.status === 404) {
|
||||
return null
|
||||
}
|
||||
const error = await response.json().catch(() => ({ error: 'Unknown error' }))
|
||||
throw new Error(`Failed to get answer: ${error.error || response.statusText}`)
|
||||
}
|
||||
|
||||
const data = await response.json()
|
||||
return { sdp: data.sdp, offerId: data.offerId }
|
||||
}
|
||||
|
||||
/**
|
||||
* Search offers by topic
|
||||
*/
|
||||
async searchOffers(topic: string): Promise<Offer[]> {
|
||||
const response = await fetch(`${this.baseUrl}/offers?topic=${encodeURIComponent(topic)}`, {
|
||||
headers: this.getAuthHeader(),
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await response.json().catch(() => ({ error: 'Unknown error' }))
|
||||
throw new Error(`Failed to search offers: ${error.error || response.statusText}`)
|
||||
}
|
||||
|
||||
return await response.json()
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// ICE Candidates
|
||||
// ============================================
|
||||
|
||||
/**
|
||||
* Add ICE candidates to a service
|
||||
*/
|
||||
async addServiceIceCandidates(serviceUuid: string, candidates: RTCIceCandidateInit[], offerId?: string): Promise<{ offerId: string }> {
|
||||
const response = await fetch(`${this.baseUrl}/services/${serviceUuid}/ice-candidates`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...this.getAuthHeader(),
|
||||
},
|
||||
body: JSON.stringify({ candidates, offerId }),
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await response.json().catch(() => ({ error: 'Unknown error' }))
|
||||
throw new Error(`Failed to add ICE candidates: ${error.error || response.statusText}`)
|
||||
}
|
||||
|
||||
return await response.json()
|
||||
}
|
||||
|
||||
/**
|
||||
* Get ICE candidates for a service (with polling support)
|
||||
*/
|
||||
async getServiceIceCandidates(serviceUuid: string, since: number = 0, offerId?: string): Promise<{ candidates: IceCandidate[]; offerId: string }> {
|
||||
const url = new URL(`${this.baseUrl}/services/${serviceUuid}/ice-candidates`)
|
||||
url.searchParams.set('since', since.toString())
|
||||
if (offerId) {
|
||||
url.searchParams.set('offerId', offerId)
|
||||
}
|
||||
|
||||
const response = await fetch(url.toString(), { headers: this.getAuthHeader() })
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await response.json().catch(() => ({ error: 'Unknown error' }))
|
||||
throw new Error(`Failed to get ICE candidates: ${error.error || response.statusText}`)
|
||||
}
|
||||
|
||||
const data = await response.json()
|
||||
return {
|
||||
candidates: data.candidates || [],
|
||||
offerId: data.offerId
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Services
|
||||
// ============================================
|
||||
|
||||
/**
|
||||
* Publish a service
|
||||
*/
|
||||
async publishService(service: ServiceRequest): Promise<Service> {
|
||||
const response = await fetch(`${this.baseUrl}/users/${encodeURIComponent(service.username)}/services`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...this.getAuthHeader(),
|
||||
},
|
||||
body: JSON.stringify(service),
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await response.json().catch(() => ({ error: 'Unknown error' }))
|
||||
throw new Error(`Failed to publish service: ${error.error || response.statusText}`)
|
||||
}
|
||||
|
||||
return await response.json()
|
||||
}
|
||||
|
||||
/**
|
||||
* Get service by UUID
|
||||
*/
|
||||
async getService(uuid: string): Promise<Service & { offerId: string; sdp: string }> {
|
||||
const response = await fetch(`${this.baseUrl}/services/${uuid}`, {
|
||||
headers: this.getAuthHeader(),
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await response.json().catch(() => ({ error: 'Unknown error' }))
|
||||
throw new Error(`Failed to get service: ${error.error || response.statusText}`)
|
||||
}
|
||||
|
||||
return await response.json()
|
||||
}
|
||||
|
||||
/**
|
||||
* Search services by username - lists all services for a username
|
||||
*/
|
||||
async searchServicesByUsername(username: string): Promise<Service[]> {
|
||||
const response = await fetch(
|
||||
`${this.baseUrl}/users/${encodeURIComponent(username)}/services`,
|
||||
{ headers: this.getAuthHeader() }
|
||||
)
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await response.json().catch(() => ({ error: 'Unknown error' }))
|
||||
throw new Error(`Failed to search services: ${error.error || response.statusText}`)
|
||||
}
|
||||
|
||||
const data = await response.json()
|
||||
return data.services || []
|
||||
}
|
||||
|
||||
/**
|
||||
* Search services by username AND FQN - returns full service details
|
||||
*/
|
||||
async searchServices(username: string, serviceFqn: string): Promise<Service[]> {
|
||||
const response = await fetch(
|
||||
`${this.baseUrl}/users/${encodeURIComponent(username)}/services/${encodeURIComponent(serviceFqn)}`,
|
||||
{ headers: this.getAuthHeader() }
|
||||
)
|
||||
|
||||
if (!response.ok) {
|
||||
if (response.status === 404) {
|
||||
return []
|
||||
}
|
||||
const error = await response.json().catch(() => ({ error: 'Unknown error' }))
|
||||
throw new Error(`Failed to search services: ${error.error || response.statusText}`)
|
||||
}
|
||||
|
||||
const service = await response.json()
|
||||
return [service]
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Usernames
|
||||
// ============================================
|
||||
|
||||
/**
|
||||
* Check if username is available
|
||||
*/
|
||||
async checkUsername(username: string): Promise<{ available: boolean; owner?: string }> {
|
||||
const response = await fetch(
|
||||
`${this.baseUrl}/users/${encodeURIComponent(username)}`
|
||||
)
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await response.json().catch(() => ({ error: 'Unknown error' }))
|
||||
throw new Error(`Failed to check username: ${error.error || response.statusText}`)
|
||||
}
|
||||
|
||||
return await response.json()
|
||||
}
|
||||
|
||||
/**
|
||||
* Claim a username (requires Ed25519 signature)
|
||||
*/
|
||||
async claimUsername(
|
||||
username: string,
|
||||
publicKey: string,
|
||||
signature: string,
|
||||
message: string
|
||||
): Promise<{ success: boolean; username: string }> {
|
||||
const response = await fetch(`${this.baseUrl}/users/${encodeURIComponent(username)}`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...this.getAuthHeader(),
|
||||
},
|
||||
body: JSON.stringify({
|
||||
publicKey,
|
||||
signature,
|
||||
message,
|
||||
}),
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await response.json().catch(() => ({ error: 'Unknown error' }))
|
||||
throw new Error(`Failed to claim username: ${error.error || response.statusText}`)
|
||||
}
|
||||
|
||||
return await response.json()
|
||||
}
|
||||
}
|
||||
42
src/bin.ts
Normal file
42
src/bin.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
/**
|
||||
* Binnable - A cleanup function that can be synchronous or asynchronous
|
||||
*
|
||||
* Used to unsubscribe from events, close connections, or perform other cleanup operations.
|
||||
*/
|
||||
export type Binnable = () => void | Promise<void>
|
||||
|
||||
/**
|
||||
* Create a cleanup function collector (garbage bin)
|
||||
*
|
||||
* Collects cleanup functions and provides a single `clean()` method to execute all of them.
|
||||
* Useful for managing multiple cleanup operations in a single place.
|
||||
*
|
||||
* @returns A function that accepts cleanup functions and has a `clean()` method
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const bin = createBin();
|
||||
*
|
||||
* // Add cleanup functions
|
||||
* bin(
|
||||
* () => console.log('Cleanup 1'),
|
||||
* () => connection.close(),
|
||||
* () => clearInterval(timer)
|
||||
* );
|
||||
*
|
||||
* // Later, clean everything
|
||||
* bin.clean(); // Executes all cleanup functions
|
||||
* ```
|
||||
*/
|
||||
export const createBin = () => {
|
||||
const bin: Binnable[] = []
|
||||
return Object.assign((...rubbish: Binnable[]) => bin.push(...rubbish), {
|
||||
/**
|
||||
* Execute all cleanup functions and clear the bin
|
||||
*/
|
||||
clean: (): void => {
|
||||
bin.forEach(binnable => binnable())
|
||||
bin.length = 0
|
||||
},
|
||||
})
|
||||
}
|
||||
239
src/client.ts
239
src/client.ts
@@ -1,239 +0,0 @@
|
||||
import {
|
||||
RondevuClientOptions,
|
||||
ListTopicsResponse,
|
||||
ListSessionsResponse,
|
||||
CreateOfferRequest,
|
||||
CreateOfferResponse,
|
||||
AnswerRequest,
|
||||
AnswerResponse,
|
||||
PollRequest,
|
||||
PollOffererResponse,
|
||||
PollAnswererResponse,
|
||||
VersionResponse,
|
||||
HealthResponse,
|
||||
ErrorResponse,
|
||||
Side,
|
||||
} from './types';
|
||||
|
||||
/**
|
||||
* HTTP client for Rondevu peer signaling and discovery server
|
||||
*/
|
||||
export class RondevuClient {
|
||||
private readonly baseUrl: string;
|
||||
private readonly fetchImpl: typeof fetch;
|
||||
|
||||
/**
|
||||
* Creates a new Rondevu 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 (git commit hash)
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const client = new RondevuClient({ baseUrl: 'https://example.com' });
|
||||
* const { version } = await client.getVersion();
|
||||
* console.log('Server version:', version);
|
||||
* ```
|
||||
*/
|
||||
async getVersion(): Promise<VersionResponse> {
|
||||
return this.request<VersionResponse>('/', {
|
||||
method: 'GET',
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Lists all topics with peer counts
|
||||
*
|
||||
* @param page - Page number (starting from 1)
|
||||
* @param limit - Results per page (max 1000)
|
||||
* @returns List of topics with pagination info
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const client = new RondevuClient({ baseUrl: 'https://example.com' });
|
||||
* const { topics, pagination } = await client.listTopics();
|
||||
* console.log(`Found ${topics.length} topics`);
|
||||
* ```
|
||||
*/
|
||||
async listTopics(page = 1, limit = 100): Promise<ListTopicsResponse> {
|
||||
const params = new URLSearchParams({
|
||||
page: page.toString(),
|
||||
limit: limit.toString(),
|
||||
});
|
||||
return this.request<ListTopicsResponse>(`/topics?${params}`, {
|
||||
method: 'GET',
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Discovers available peers for a given topic
|
||||
*
|
||||
* @param topic - Topic identifier
|
||||
* @returns List of available sessions
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const client = new RondevuClient({ baseUrl: 'https://example.com' });
|
||||
* const { sessions } = await client.listSessions('my-room');
|
||||
* const otherPeers = sessions.filter(s => s.peerId !== myPeerId);
|
||||
* ```
|
||||
*/
|
||||
async listSessions(topic: string): Promise<ListSessionsResponse> {
|
||||
return this.request<ListSessionsResponse>(`/${encodeURIComponent(topic)}/sessions`, {
|
||||
method: 'GET',
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Announces peer availability and creates a new session
|
||||
*
|
||||
* @param topic - Topic identifier for grouping peers (max 1024 characters)
|
||||
* @param request - Offer details including peer ID and signaling data
|
||||
* @returns Unique session code (UUID)
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const client = new RondevuClient({ baseUrl: 'https://example.com' });
|
||||
* const { code } = await client.createOffer('my-room', {
|
||||
* peerId: 'peer-123',
|
||||
* offer: signalingData
|
||||
* });
|
||||
* console.log('Session code:', code);
|
||||
* ```
|
||||
*/
|
||||
async createOffer(
|
||||
topic: string,
|
||||
request: CreateOfferRequest
|
||||
): Promise<CreateOfferResponse> {
|
||||
return this.request<CreateOfferResponse>(
|
||||
`/${encodeURIComponent(topic)}/offer`,
|
||||
{
|
||||
method: 'POST',
|
||||
body: JSON.stringify(request),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends an answer or candidate to an existing session
|
||||
*
|
||||
* @param request - Answer details including session code and signaling data
|
||||
* @returns Success confirmation
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const client = new RondevuClient({ baseUrl: 'https://example.com' });
|
||||
*
|
||||
* // Send answer
|
||||
* await client.sendAnswer({
|
||||
* code: sessionCode,
|
||||
* answer: answerData,
|
||||
* side: 'answerer'
|
||||
* });
|
||||
*
|
||||
* // Send candidate
|
||||
* await client.sendAnswer({
|
||||
* code: sessionCode,
|
||||
* candidate: candidateData,
|
||||
* side: 'offerer'
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
async sendAnswer(request: AnswerRequest): Promise<AnswerResponse> {
|
||||
return this.request<AnswerResponse>('/answer', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(request),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Polls for session data from the other peer
|
||||
*
|
||||
* @param code - Session UUID
|
||||
* @param side - Which side is polling ('offerer' or 'answerer')
|
||||
* @returns Session data including offers, answers, and candidates
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const client = new RondevuClient({ baseUrl: 'https://example.com' });
|
||||
*
|
||||
* // Offerer polls for answer
|
||||
* const offererData = await client.poll(sessionCode, 'offerer');
|
||||
* if (offererData.answer) {
|
||||
* console.log('Received answer:', offererData.answer);
|
||||
* }
|
||||
*
|
||||
* // Answerer polls for offer
|
||||
* const answererData = await client.poll(sessionCode, '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
|
||||
*
|
||||
* @returns Health status and timestamp
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const client = new RondevuClient({ baseUrl: 'https://example.com' });
|
||||
* const health = await client.health();
|
||||
* console.log('Server status:', health.status);
|
||||
* ```
|
||||
*/
|
||||
async health(): Promise<HealthResponse> {
|
||||
return this.request<HealthResponse>('/health', {
|
||||
method: 'GET',
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,310 +0,0 @@
|
||||
import { EventEmitter } from './event-emitter';
|
||||
import { RondevuClient } from './client';
|
||||
import { RondevuConnectionParams } from './types';
|
||||
|
||||
/**
|
||||
* Represents a WebRTC connection with automatic signaling and ICE exchange
|
||||
*/
|
||||
export class RondevuConnection extends EventEmitter {
|
||||
readonly id: string;
|
||||
readonly topic: string;
|
||||
readonly role: 'offerer' | 'answerer';
|
||||
readonly remotePeerId: string;
|
||||
|
||||
private pc: RTCPeerConnection;
|
||||
private client: RondevuClient;
|
||||
private localPeerId: string;
|
||||
private dataChannels: Map<string, RTCDataChannel>;
|
||||
private pollingInterval?: ReturnType<typeof setInterval>;
|
||||
private pollingIntervalMs: number;
|
||||
private connectionTimeoutMs: number;
|
||||
private connectionTimer?: ReturnType<typeof setTimeout>;
|
||||
private isPolling: boolean = false;
|
||||
private isClosed: boolean = false;
|
||||
|
||||
constructor(params: RondevuConnectionParams, client: RondevuClient) {
|
||||
super();
|
||||
this.id = params.id;
|
||||
this.topic = params.topic;
|
||||
this.role = params.role;
|
||||
this.pc = params.pc;
|
||||
this.localPeerId = params.localPeerId;
|
||||
this.remotePeerId = params.remotePeerId;
|
||||
this.client = client;
|
||||
this.dataChannels = new Map();
|
||||
this.pollingIntervalMs = params.pollingInterval;
|
||||
this.connectionTimeoutMs = params.connectionTimeout;
|
||||
|
||||
this.setupEventHandlers();
|
||||
this.startConnectionTimeout();
|
||||
}
|
||||
|
||||
/**
|
||||
* Setup RTCPeerConnection event handlers
|
||||
*/
|
||||
private setupEventHandlers(): void {
|
||||
// ICE candidate gathering
|
||||
this.pc.onicecandidate = (event) => {
|
||||
if (event.candidate && !this.isClosed) {
|
||||
this.sendIceCandidate(event.candidate).catch((err) => {
|
||||
this.emit('error', new Error(`Failed to send ICE candidate: ${err.message}`));
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// Connection state changes
|
||||
this.pc.onconnectionstatechange = () => {
|
||||
this.handleConnectionStateChange();
|
||||
};
|
||||
|
||||
// Remote data channels
|
||||
this.pc.ondatachannel = (event) => {
|
||||
this.handleRemoteDataChannel(event.channel);
|
||||
};
|
||||
|
||||
// Remote media streams
|
||||
this.pc.ontrack = (event) => {
|
||||
if (event.streams && event.streams[0]) {
|
||||
this.emit('stream', event.streams[0]);
|
||||
}
|
||||
};
|
||||
|
||||
// ICE connection state changes
|
||||
this.pc.oniceconnectionstatechange = () => {
|
||||
const state = this.pc.iceConnectionState;
|
||||
|
||||
if (state === 'failed' || state === 'closed') {
|
||||
this.emit('error', new Error(`ICE connection ${state}`));
|
||||
if (state === 'failed') {
|
||||
this.close();
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle RTCPeerConnection state changes
|
||||
*/
|
||||
private handleConnectionStateChange(): void {
|
||||
const state = this.pc.connectionState;
|
||||
|
||||
switch (state) {
|
||||
case 'connected':
|
||||
this.clearConnectionTimeout();
|
||||
this.stopPolling();
|
||||
this.emit('connect');
|
||||
break;
|
||||
|
||||
case 'disconnected':
|
||||
this.emit('disconnect');
|
||||
break;
|
||||
|
||||
case 'failed':
|
||||
this.emit('error', new Error('Connection failed'));
|
||||
this.close();
|
||||
break;
|
||||
|
||||
case 'closed':
|
||||
this.emit('disconnect');
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Send an ICE candidate to the remote peer via signaling server
|
||||
*/
|
||||
private async sendIceCandidate(candidate: RTCIceCandidate): Promise<void> {
|
||||
try {
|
||||
await this.client.sendAnswer({
|
||||
code: this.id,
|
||||
candidate: JSON.stringify(candidate.toJSON()),
|
||||
side: this.role,
|
||||
});
|
||||
} catch (err: any) {
|
||||
throw new Error(`Failed to send ICE candidate: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Start polling for remote session data (answer/candidates)
|
||||
*/
|
||||
startPolling(): void {
|
||||
if (this.isPolling || this.isClosed) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.isPolling = true;
|
||||
|
||||
// Poll immediately
|
||||
this.poll().catch((err) => {
|
||||
this.emit('error', new Error(`Poll error: ${err.message}`));
|
||||
});
|
||||
|
||||
// Set up interval polling
|
||||
this.pollingInterval = setInterval(() => {
|
||||
this.poll().catch((err) => {
|
||||
this.emit('error', new Error(`Poll error: ${err.message}`));
|
||||
});
|
||||
}, this.pollingIntervalMs);
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop polling
|
||||
*/
|
||||
private stopPolling(): void {
|
||||
this.isPolling = false;
|
||||
if (this.pollingInterval) {
|
||||
clearInterval(this.pollingInterval);
|
||||
this.pollingInterval = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Poll the signaling server for remote data
|
||||
*/
|
||||
private async poll(): Promise<void> {
|
||||
if (this.isClosed) {
|
||||
this.stopPolling();
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await this.client.poll(this.id, this.role);
|
||||
|
||||
if (this.role === 'offerer') {
|
||||
const offererResponse = response as { answer: string | null; answerCandidates: string[] };
|
||||
|
||||
// Apply answer if received and not yet applied
|
||||
if (offererResponse.answer && !this.pc.currentRemoteDescription) {
|
||||
await this.pc.setRemoteDescription({
|
||||
type: 'answer',
|
||||
sdp: offererResponse.answer,
|
||||
});
|
||||
}
|
||||
|
||||
// Apply ICE candidates
|
||||
if (offererResponse.answerCandidates && offererResponse.answerCandidates.length > 0) {
|
||||
for (const candidateStr of offererResponse.answerCandidates) {
|
||||
try {
|
||||
const candidate = JSON.parse(candidateStr);
|
||||
await this.pc.addIceCandidate(new RTCIceCandidate(candidate));
|
||||
} catch (err) {
|
||||
console.warn('Failed to add ICE candidate:', err);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Answerer role
|
||||
const answererResponse = response as { offer: string; offerCandidates: string[] };
|
||||
|
||||
// Apply ICE candidates from offerer
|
||||
if (answererResponse.offerCandidates && answererResponse.offerCandidates.length > 0) {
|
||||
for (const candidateStr of answererResponse.offerCandidates) {
|
||||
try {
|
||||
const candidate = JSON.parse(candidateStr);
|
||||
await this.pc.addIceCandidate(new RTCIceCandidate(candidate));
|
||||
} catch (err) {
|
||||
console.warn('Failed to add ICE candidate:', err);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (err: any) {
|
||||
// Session not found or expired
|
||||
if (err.message.includes('404') || err.message.includes('not found')) {
|
||||
this.emit('error', new Error('Session not found or expired'));
|
||||
this.close();
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle remotely created data channel
|
||||
*/
|
||||
private handleRemoteDataChannel(channel: RTCDataChannel): void {
|
||||
this.dataChannels.set(channel.label, channel);
|
||||
this.emit('datachannel', channel);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get or create a data channel
|
||||
*/
|
||||
dataChannel(label: string, options?: RTCDataChannelInit): RTCDataChannel {
|
||||
let channel = this.dataChannels.get(label);
|
||||
|
||||
if (!channel) {
|
||||
channel = this.pc.createDataChannel(label, options);
|
||||
this.dataChannels.set(label, channel);
|
||||
}
|
||||
|
||||
return channel;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a local media stream to the connection
|
||||
*/
|
||||
addStream(stream: MediaStream): void {
|
||||
stream.getTracks().forEach(track => {
|
||||
this.pc.addTrack(track, stream);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the underlying RTCPeerConnection for advanced usage
|
||||
*/
|
||||
getPeerConnection(): RTCPeerConnection {
|
||||
return this.pc;
|
||||
}
|
||||
|
||||
/**
|
||||
* Start connection timeout
|
||||
*/
|
||||
private startConnectionTimeout(): void {
|
||||
this.connectionTimer = setTimeout(() => {
|
||||
if (this.pc.connectionState !== 'connected') {
|
||||
this.emit('error', new Error('Connection timeout'));
|
||||
this.close();
|
||||
}
|
||||
}, this.connectionTimeoutMs);
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear connection timeout
|
||||
*/
|
||||
private clearConnectionTimeout(): void {
|
||||
if (this.connectionTimer) {
|
||||
clearTimeout(this.connectionTimer);
|
||||
this.connectionTimer = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Close the connection and cleanup resources
|
||||
*/
|
||||
close(): void {
|
||||
if (this.isClosed) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.isClosed = true;
|
||||
|
||||
this.stopPolling();
|
||||
this.clearConnectionTimeout();
|
||||
|
||||
// Close all data channels
|
||||
this.dataChannels.forEach(dc => {
|
||||
if (dc.readyState === 'open' || dc.readyState === 'connecting') {
|
||||
dc.close();
|
||||
}
|
||||
});
|
||||
this.dataChannels.clear();
|
||||
|
||||
// Close peer connection
|
||||
if (this.pc.connectionState !== 'closed') {
|
||||
this.pc.close();
|
||||
}
|
||||
|
||||
this.emit('disconnect');
|
||||
}
|
||||
}
|
||||
290
src/durable-connection.ts
Normal file
290
src/durable-connection.ts
Normal file
@@ -0,0 +1,290 @@
|
||||
import {
|
||||
ConnectionEvents,
|
||||
ConnectionInterface,
|
||||
ConnectionStates,
|
||||
isConnectionState,
|
||||
Message,
|
||||
QueueMessageOptions,
|
||||
Signaler,
|
||||
} from './types.js'
|
||||
import { EventBus } from './event-bus.js'
|
||||
import { createBin } from './bin.js'
|
||||
import { WebRTCContext } from './webrtc-context'
|
||||
|
||||
export type WebRTCRondevuConnectionOptions = {
|
||||
offer?: RTCSessionDescriptionInit | null
|
||||
context: WebRTCContext
|
||||
signaler: Signaler
|
||||
}
|
||||
|
||||
/**
|
||||
* WebRTCRondevuConnection - WebRTC peer connection wrapper with Rondevu signaling
|
||||
*
|
||||
* Manages a WebRTC peer connection lifecycle including:
|
||||
* - Automatic offer/answer creation based on role
|
||||
* - ICE candidate exchange via Rondevu signaling server
|
||||
* - Connection state management with type-safe events
|
||||
* - Data channel creation and message handling
|
||||
*
|
||||
* The connection automatically determines its role (offerer or answerer) based on whether
|
||||
* an offer is provided in the constructor. The offerer creates the data channel, while
|
||||
* the answerer receives it via the 'datachannel' event.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* // Offerer side (creates offer)
|
||||
* const connection = new WebRTCRondevuConnection(
|
||||
* 'conn-123',
|
||||
* 'peer-username',
|
||||
* 'chat.service@1.0.0'
|
||||
* );
|
||||
*
|
||||
* await connection.ready; // Wait for local offer
|
||||
* const sdp = connection.connection.localDescription!.sdp!;
|
||||
* // Send sdp to signaling server...
|
||||
*
|
||||
* // Answerer side (receives offer)
|
||||
* const connection = new WebRTCRondevuConnection(
|
||||
* 'conn-123',
|
||||
* 'peer-username',
|
||||
* 'chat.service@1.0.0',
|
||||
* { type: 'offer', sdp: remoteOfferSdp }
|
||||
* );
|
||||
*
|
||||
* await connection.ready; // Wait for local answer
|
||||
* const answerSdp = connection.connection.localDescription!.sdp!;
|
||||
* // Send answer to signaling server...
|
||||
*
|
||||
* // Both sides: Set up signaler and listen for state changes
|
||||
* connection.setSignaler(signaler);
|
||||
* connection.events.on('state-change', (state) => {
|
||||
* console.log('Connection state:', state);
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
export class RTCDurableConnection implements ConnectionInterface {
|
||||
private readonly side: 'offer' | 'answer'
|
||||
public readonly expiresAt: number = 0
|
||||
public readonly lastActive: number = 0
|
||||
public readonly events: EventBus<ConnectionEvents> = new EventBus()
|
||||
public readonly ready: Promise<void>
|
||||
private iceBin = createBin()
|
||||
private context: WebRTCContext
|
||||
private readonly signaler: Signaler
|
||||
private _conn: RTCPeerConnection | null = null
|
||||
private _state: ConnectionInterface['state'] = 'disconnected'
|
||||
private _dataChannel: RTCDataChannel | null = null
|
||||
private messageQueue: Array<{
|
||||
message: Message
|
||||
options: QueueMessageOptions
|
||||
timestamp: number
|
||||
}> = []
|
||||
|
||||
constructor({ context, offer, signaler }: WebRTCRondevuConnectionOptions) {
|
||||
this.context = context
|
||||
this.signaler = signaler
|
||||
this._conn = context.createPeerConnection()
|
||||
this.side = offer ? 'answer' : 'offer'
|
||||
|
||||
// setup data channel
|
||||
if (offer) {
|
||||
this._conn.addEventListener('datachannel', e => {
|
||||
this._dataChannel = e.channel
|
||||
this.setupDataChannelListeners(this._dataChannel)
|
||||
})
|
||||
} else {
|
||||
this._dataChannel = this._conn.createDataChannel('vu.ronde.protocol')
|
||||
this.setupDataChannelListeners(this._dataChannel)
|
||||
}
|
||||
|
||||
// setup description exchange
|
||||
this.ready = offer
|
||||
? this._conn
|
||||
.setRemoteDescription(offer)
|
||||
.then(() => this._conn?.createAnswer())
|
||||
.then(async answer => {
|
||||
if (!answer || !this._conn) throw new Error('Connection disappeared')
|
||||
await this._conn.setLocalDescription(answer)
|
||||
return await signaler.setAnswer(answer)
|
||||
})
|
||||
: this._conn.createOffer().then(async offer => {
|
||||
if (!this._conn) throw new Error('Connection disappeared')
|
||||
await this._conn.setLocalDescription(offer)
|
||||
return await signaler.setOffer(offer)
|
||||
})
|
||||
|
||||
// propagate connection state changes
|
||||
this._conn.addEventListener('connectionstatechange', () => {
|
||||
console.log(this.side, 'connection state changed: ', this._conn!.connectionState)
|
||||
const state = isConnectionState(this._conn!.connectionState)
|
||||
? this._conn!.connectionState
|
||||
: 'disconnected'
|
||||
this.setState(state)
|
||||
})
|
||||
|
||||
this._conn.addEventListener('iceconnectionstatechange', () => {
|
||||
console.log(this.side, 'ice connection state changed: ', this._conn!.iceConnectionState)
|
||||
})
|
||||
|
||||
// start ICE candidate exchange when gathering begins
|
||||
this._conn.addEventListener('icegatheringstatechange', () => {
|
||||
if (this._conn!.iceGatheringState === 'gathering') {
|
||||
this.startIce()
|
||||
} else if (this._conn!.iceGatheringState === 'complete') {
|
||||
this.stopIce()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Getter method for retrieving the current connection.
|
||||
*
|
||||
* @return {RTCPeerConnection|null} The current connection instance.
|
||||
*/
|
||||
public get connection(): RTCPeerConnection | null {
|
||||
return this._conn
|
||||
}
|
||||
|
||||
/**
|
||||
* Update connection state and emit state-change event
|
||||
*/
|
||||
private setState(state: ConnectionInterface['state']) {
|
||||
this._state = state
|
||||
this.events.emit('state-change', state)
|
||||
}
|
||||
|
||||
/**
|
||||
* Start ICE candidate exchange when gathering begins
|
||||
*/
|
||||
private startIce() {
|
||||
const listener = ({ candidate }: { candidate: RTCIceCandidate | null }) => {
|
||||
if (candidate) this.signaler.addIceCandidate(candidate)
|
||||
}
|
||||
if (!this._conn) throw new Error('Connection disappeared')
|
||||
this._conn.addEventListener('icecandidate', listener)
|
||||
this.iceBin(
|
||||
this.signaler.addListener((candidate: RTCIceCandidate) =>
|
||||
this._conn?.addIceCandidate(candidate)
|
||||
),
|
||||
() => this._conn?.removeEventListener('icecandidate', listener)
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop ICE candidate exchange when gathering completes
|
||||
*/
|
||||
private stopIce() {
|
||||
this.iceBin.clean()
|
||||
}
|
||||
|
||||
/**
|
||||
* Disconnects the current connection and cleans up resources.
|
||||
* Closes the active connection if it exists, resets the connection instance to null,
|
||||
* stops the ICE process, and updates the state to 'disconnected'.
|
||||
*
|
||||
* @return {void} No return value.
|
||||
*/
|
||||
disconnect(): void {
|
||||
this._conn?.close()
|
||||
this._conn = null
|
||||
this.stopIce()
|
||||
this.setState('disconnected')
|
||||
}
|
||||
|
||||
/**
|
||||
* Current connection state
|
||||
*/
|
||||
get state() {
|
||||
return this._state
|
||||
}
|
||||
|
||||
/**
|
||||
* Setup data channel event listeners
|
||||
*/
|
||||
private setupDataChannelListeners(channel: RTCDataChannel): void {
|
||||
channel.addEventListener('message', e => {
|
||||
this.events.emit('message', e.data)
|
||||
})
|
||||
|
||||
channel.addEventListener('open', () => {
|
||||
// Channel opened - flush queued messages
|
||||
this.flushQueue().catch(err => {
|
||||
console.error('Failed to flush message queue:', err)
|
||||
})
|
||||
})
|
||||
|
||||
channel.addEventListener('error', err => {
|
||||
console.error('Data channel error:', err)
|
||||
})
|
||||
|
||||
channel.addEventListener('close', () => {
|
||||
console.log('Data channel closed')
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Flush the message queue
|
||||
*/
|
||||
private async flushQueue(): Promise<void> {
|
||||
while (this.messageQueue.length > 0 && this._state === 'connected') {
|
||||
const item = this.messageQueue.shift()!
|
||||
|
||||
// Check expiration
|
||||
if (item.options.expiresAt && Date.now() > item.options.expiresAt) {
|
||||
continue
|
||||
}
|
||||
|
||||
const success = await this.sendMessage(item.message)
|
||||
if (!success) {
|
||||
// Re-queue on failure
|
||||
this.messageQueue.unshift(item)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Queue a message for sending when connection is established
|
||||
*
|
||||
* @param message - Message to queue (string or ArrayBuffer)
|
||||
* @param options - Queue options (e.g., expiration time)
|
||||
*/
|
||||
async queueMessage(message: Message, options: QueueMessageOptions = {}): Promise<void> {
|
||||
this.messageQueue.push({
|
||||
message,
|
||||
options,
|
||||
timestamp: Date.now()
|
||||
})
|
||||
|
||||
// Try immediate send if connected
|
||||
if (this._state === 'connected') {
|
||||
await this.flushQueue()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a message immediately
|
||||
*
|
||||
* @param message - Message to send (string or ArrayBuffer)
|
||||
* @returns Promise resolving to true if sent successfully
|
||||
*/
|
||||
async sendMessage(message: Message): Promise<boolean> {
|
||||
if (this._state !== 'connected' || !this._dataChannel) {
|
||||
return false
|
||||
}
|
||||
|
||||
if (this._dataChannel.readyState !== 'open') {
|
||||
return false
|
||||
}
|
||||
|
||||
try {
|
||||
// TypeScript has trouble with the union type, so we cast to any
|
||||
// Both string and ArrayBuffer are valid for RTCDataChannel.send()
|
||||
this._dataChannel.send(message as any)
|
||||
return true
|
||||
} catch (err) {
|
||||
console.error('Send failed:', err)
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
94
src/event-bus.ts
Normal file
94
src/event-bus.ts
Normal file
@@ -0,0 +1,94 @@
|
||||
/**
|
||||
* Type-safe EventBus with event name to payload type mapping
|
||||
*/
|
||||
|
||||
type EventHandler<T = any> = (data: T) => void
|
||||
|
||||
/**
|
||||
* EventBus - Type-safe event emitter with inferred event data types
|
||||
*
|
||||
* @example
|
||||
* interface MyEvents {
|
||||
* 'user:connected': { userId: string; timestamp: number };
|
||||
* 'user:disconnected': { userId: string };
|
||||
* 'message:received': string;
|
||||
* }
|
||||
*
|
||||
* const bus = new EventBus<MyEvents>();
|
||||
*
|
||||
* // TypeScript knows data is { userId: string; timestamp: number }
|
||||
* bus.on('user:connected', (data) => {
|
||||
* console.log(data.userId, data.timestamp);
|
||||
* });
|
||||
*
|
||||
* // TypeScript knows data is string
|
||||
* bus.on('message:received', (data) => {
|
||||
* console.log(data.toUpperCase());
|
||||
* });
|
||||
*/
|
||||
export class EventBus<TEvents extends Record<string, any>> {
|
||||
private handlers: Map<keyof TEvents, Set<EventHandler>>
|
||||
|
||||
constructor() {
|
||||
this.handlers = new Map()
|
||||
}
|
||||
|
||||
/**
|
||||
* Subscribe to an event
|
||||
* Returns a cleanup function to unsubscribe
|
||||
*/
|
||||
on<K extends keyof TEvents>(event: K, handler: EventHandler<TEvents[K]>): () => void {
|
||||
if (!this.handlers.has(event)) {
|
||||
this.handlers.set(event, new Set())
|
||||
}
|
||||
this.handlers.get(event)!.add(handler)
|
||||
|
||||
// Return cleanup function
|
||||
return () => this.off(event, handler)
|
||||
}
|
||||
|
||||
/**
|
||||
* Subscribe to an event once (auto-unsubscribe after first call)
|
||||
*/
|
||||
once<K extends keyof TEvents>(event: K, handler: EventHandler<TEvents[K]>): void {
|
||||
const wrappedHandler = (data: TEvents[K]) => {
|
||||
handler(data)
|
||||
this.off(event, wrappedHandler)
|
||||
}
|
||||
this.on(event, wrappedHandler)
|
||||
}
|
||||
|
||||
/**
|
||||
* Unsubscribe from an event
|
||||
*/
|
||||
off<K extends keyof TEvents>(event: K, handler: EventHandler<TEvents[K]>): void {
|
||||
const eventHandlers = this.handlers.get(event)
|
||||
if (eventHandlers) {
|
||||
eventHandlers.delete(handler)
|
||||
if (eventHandlers.size === 0) {
|
||||
this.handlers.delete(event)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Emit an event with data
|
||||
*/
|
||||
emit<K extends keyof TEvents>(event: K, data: TEvents[K]): void {
|
||||
const eventHandlers = this.handlers.get(event)
|
||||
if (eventHandlers) {
|
||||
eventHandlers.forEach(handler => handler(data))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove all handlers for a specific event, or all handlers if no event specified
|
||||
*/
|
||||
clear<K extends keyof TEvents>(event?: K): void {
|
||||
if (event !== undefined) {
|
||||
this.handlers.delete(event)
|
||||
} else {
|
||||
this.handlers.clear()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,86 +0,0 @@
|
||||
/**
|
||||
* Simple EventEmitter implementation for browser and Node.js compatibility
|
||||
*/
|
||||
export class EventEmitter {
|
||||
private events: Map<string, Set<Function>>;
|
||||
|
||||
constructor() {
|
||||
this.events = new Map();
|
||||
}
|
||||
|
||||
/**
|
||||
* Register an event listener
|
||||
*/
|
||||
on(event: string, listener: Function): this {
|
||||
if (!this.events.has(event)) {
|
||||
this.events.set(event, new Set());
|
||||
}
|
||||
this.events.get(event)!.add(listener);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a one-time event listener
|
||||
*/
|
||||
once(event: string, listener: Function): this {
|
||||
const onceWrapper = (...args: any[]) => {
|
||||
this.off(event, onceWrapper);
|
||||
listener.apply(this, args);
|
||||
};
|
||||
return this.on(event, onceWrapper);
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove an event listener
|
||||
*/
|
||||
off(event: string, listener: Function): this {
|
||||
const listeners = this.events.get(event);
|
||||
if (listeners) {
|
||||
listeners.delete(listener);
|
||||
if (listeners.size === 0) {
|
||||
this.events.delete(event);
|
||||
}
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Emit an event
|
||||
*/
|
||||
emit(event: string, ...args: any[]): boolean {
|
||||
const listeners = this.events.get(event);
|
||||
if (!listeners || listeners.size === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
listeners.forEach(listener => {
|
||||
try {
|
||||
listener.apply(this, args);
|
||||
} catch (err) {
|
||||
console.error(`Error in ${event} event listener:`, err);
|
||||
}
|
||||
});
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove all listeners for an event (or all events if not specified)
|
||||
*/
|
||||
removeAllListeners(event?: string): this {
|
||||
if (event) {
|
||||
this.events.delete(event);
|
||||
} else {
|
||||
this.events.clear();
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get listener count for an event
|
||||
*/
|
||||
listenerCount(event: string): number {
|
||||
const listeners = this.events.get(event);
|
||||
return listeners ? listeners.size : 0;
|
||||
}
|
||||
}
|
||||
74
src/index.ts
74
src/index.ts
@@ -1,42 +1,44 @@
|
||||
/**
|
||||
* @xtr-dev/rondevu-client
|
||||
* WebRTC peer signaling and discovery client
|
||||
* WebRTC peer signaling client
|
||||
*/
|
||||
|
||||
// Export main WebRTC client class
|
||||
export { Rondevu } from './rondevu';
|
||||
export { EventBus } from './event-bus.js'
|
||||
export { RondevuAPI } from './api.js'
|
||||
export { RondevuService } from './rondevu-service.js'
|
||||
export { RondevuSignaler } from './rondevu-signaler.js'
|
||||
export { WebRTCContext } from './webrtc-context.js'
|
||||
export { RTCDurableConnection } from './durable-connection'
|
||||
export { ServiceHost } from './service-host.js'
|
||||
export { ServiceClient } from './service-client.js'
|
||||
export { createBin } from './bin.js'
|
||||
|
||||
// Export connection class
|
||||
export { RondevuConnection } from './connection';
|
||||
|
||||
// Export low-level signaling client (for advanced usage)
|
||||
export { RondevuClient } from './client';
|
||||
|
||||
// Export all types
|
||||
// Export types
|
||||
export type {
|
||||
// WebRTC types
|
||||
RondevuOptions,
|
||||
JoinOptions,
|
||||
ConnectionRole,
|
||||
RondevuConnectionParams,
|
||||
RondevuConnectionEvents,
|
||||
// Signaling types
|
||||
Side,
|
||||
Session,
|
||||
TopicInfo,
|
||||
Pagination,
|
||||
ListTopicsResponse,
|
||||
ListSessionsResponse,
|
||||
CreateOfferRequest,
|
||||
CreateOfferResponse,
|
||||
AnswerRequest,
|
||||
AnswerResponse,
|
||||
PollRequest,
|
||||
PollOffererResponse,
|
||||
PollAnswererResponse,
|
||||
PollResponse,
|
||||
VersionResponse,
|
||||
HealthResponse,
|
||||
ErrorResponse,
|
||||
RondevuClientOptions,
|
||||
} from './types';
|
||||
ConnectionInterface,
|
||||
QueueMessageOptions,
|
||||
Message,
|
||||
ConnectionEvents,
|
||||
Signaler,
|
||||
} from './types.js'
|
||||
|
||||
export type {
|
||||
Credentials,
|
||||
Keypair,
|
||||
OfferRequest,
|
||||
Offer,
|
||||
ServiceRequest,
|
||||
Service,
|
||||
IceCandidate,
|
||||
} from './api.js'
|
||||
|
||||
export type { Binnable } from './bin.js'
|
||||
|
||||
export type { RondevuServiceOptions, PublishServiceOptions } from './rondevu-service.js'
|
||||
|
||||
export type { ServiceHostOptions, ServiceHostEvents } from './service-host.js'
|
||||
|
||||
export type { ServiceClientOptions, ServiceClientEvents } from './service-client.js'
|
||||
|
||||
export type { PollingConfig } from './rondevu-signaler.js'
|
||||
|
||||
|
||||
175
src/rondevu-service.ts
Normal file
175
src/rondevu-service.ts
Normal file
@@ -0,0 +1,175 @@
|
||||
import { RondevuAPI, Credentials, Keypair, Service, ServiceRequest } from './api.js'
|
||||
|
||||
export interface RondevuServiceOptions {
|
||||
apiUrl: string
|
||||
username: string
|
||||
keypair?: Keypair
|
||||
credentials?: Credentials
|
||||
}
|
||||
|
||||
export interface PublishServiceOptions {
|
||||
serviceFqn: string
|
||||
offers: Array<{ sdp: string }>
|
||||
ttl?: number
|
||||
isPublic?: boolean
|
||||
metadata?: Record<string, any>
|
||||
}
|
||||
|
||||
/**
|
||||
* RondevuService - High-level service management with automatic signature handling
|
||||
*
|
||||
* Provides a simplified API for:
|
||||
* - Username claiming with Ed25519 signatures
|
||||
* - Service publishing with automatic signature generation
|
||||
* - Keypair management
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* // Initialize service (generates keypair automatically)
|
||||
* const service = new RondevuService({
|
||||
* apiUrl: 'https://signal.example.com',
|
||||
* username: 'myusername',
|
||||
* })
|
||||
*
|
||||
* await service.initialize()
|
||||
*
|
||||
* // Claim username (one time)
|
||||
* await service.claimUsername()
|
||||
*
|
||||
* // Publish a service
|
||||
* const publishedService = await service.publishService({
|
||||
* serviceFqn: 'chat.app@1.0.0',
|
||||
* offers: [{ sdp: offerSdp }],
|
||||
* ttl: 300000,
|
||||
* isPublic: true,
|
||||
* })
|
||||
* ```
|
||||
*/
|
||||
export class RondevuService {
|
||||
private readonly api: RondevuAPI
|
||||
private readonly username: string
|
||||
private keypair: Keypair | null = null
|
||||
private usernameClaimed = false
|
||||
|
||||
constructor(options: RondevuServiceOptions) {
|
||||
this.username = options.username
|
||||
this.keypair = options.keypair || null
|
||||
this.api = new RondevuAPI(options.apiUrl, options.credentials)
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the service - generates keypair if not provided
|
||||
* Call this before using other methods
|
||||
*/
|
||||
async initialize(): Promise<void> {
|
||||
if (!this.keypair) {
|
||||
this.keypair = await RondevuAPI.generateKeypair()
|
||||
}
|
||||
|
||||
// Register with API if no credentials provided
|
||||
if (!this.api['credentials']) {
|
||||
const credentials = await this.api.register()
|
||||
this.api.setCredentials(credentials)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Claim the username with Ed25519 signature
|
||||
* Should be called once before publishing services
|
||||
*/
|
||||
async claimUsername(): Promise<void> {
|
||||
if (!this.keypair) {
|
||||
throw new Error('Service not initialized. Call initialize() first.')
|
||||
}
|
||||
|
||||
// Check if username is already claimed
|
||||
const check = await this.api.checkUsername(this.username)
|
||||
if (!check.available) {
|
||||
// Verify it's claimed by us
|
||||
if (check.owner === this.keypair.publicKey) {
|
||||
this.usernameClaimed = true
|
||||
return
|
||||
}
|
||||
throw new Error(`Username "${this.username}" is already claimed by another user`)
|
||||
}
|
||||
|
||||
// Generate signature for username claim
|
||||
const message = `claim:${this.username}:${Date.now()}`
|
||||
const signature = await RondevuAPI.signMessage(message, this.keypair.privateKey)
|
||||
|
||||
// Claim the username
|
||||
await this.api.claimUsername(this.username, this.keypair.publicKey, signature, message)
|
||||
this.usernameClaimed = true
|
||||
}
|
||||
|
||||
/**
|
||||
* Publish a service with automatic signature generation
|
||||
*/
|
||||
async publishService(options: PublishServiceOptions): Promise<Service> {
|
||||
if (!this.keypair) {
|
||||
throw new Error('Service not initialized. Call initialize() first.')
|
||||
}
|
||||
|
||||
if (!this.usernameClaimed) {
|
||||
throw new Error(
|
||||
'Username not claimed. Call claimUsername() first or the server will reject the service.'
|
||||
)
|
||||
}
|
||||
|
||||
const { serviceFqn, offers, ttl, isPublic, metadata } = options
|
||||
|
||||
// Generate signature for service publication
|
||||
const message = `publish:${this.username}:${serviceFqn}:${Date.now()}`
|
||||
const signature = await RondevuAPI.signMessage(message, this.keypair.privateKey)
|
||||
|
||||
// Create service request
|
||||
const serviceRequest: ServiceRequest = {
|
||||
username: this.username,
|
||||
serviceFqn,
|
||||
offers,
|
||||
signature,
|
||||
message,
|
||||
ttl,
|
||||
isPublic,
|
||||
metadata,
|
||||
}
|
||||
|
||||
// Publish to server
|
||||
return await this.api.publishService(serviceRequest)
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the current keypair (for backup/storage)
|
||||
*/
|
||||
getKeypair(): Keypair | null {
|
||||
return this.keypair
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the username
|
||||
*/
|
||||
getUsername(): string {
|
||||
return this.username
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the public key
|
||||
*/
|
||||
getPublicKey(): string | null {
|
||||
return this.keypair?.publicKey || null
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if username has been claimed
|
||||
*/
|
||||
isUsernameClaimed(): boolean {
|
||||
return this.usernameClaimed
|
||||
}
|
||||
|
||||
/**
|
||||
* Access to underlying API for advanced operations
|
||||
*/
|
||||
getAPI(): RondevuAPI {
|
||||
return this.api
|
||||
}
|
||||
}
|
||||
462
src/rondevu-signaler.ts
Normal file
462
src/rondevu-signaler.ts
Normal file
@@ -0,0 +1,462 @@
|
||||
import { Signaler } from './types.js'
|
||||
import { RondevuService } from './rondevu-service.js'
|
||||
import { Binnable } from './bin.js'
|
||||
|
||||
export interface PollingConfig {
|
||||
initialInterval?: number // Default: 500ms
|
||||
maxInterval?: number // Default: 5000ms
|
||||
backoffMultiplier?: number // Default: 1.5
|
||||
maxRetries?: number // Default: 50 (50 seconds max)
|
||||
jitter?: boolean // Default: true
|
||||
}
|
||||
|
||||
/**
|
||||
* RondevuSignaler - Handles WebRTC signaling via Rondevu service
|
||||
*
|
||||
* Manages offer/answer exchange and ICE candidate polling for establishing
|
||||
* WebRTC connections through the Rondevu signaling server.
|
||||
*
|
||||
* Supports configurable polling with exponential backoff and jitter to reduce
|
||||
* server load and prevent thundering herd issues.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const signaler = new RondevuSignaler(
|
||||
* rondevuService,
|
||||
* 'chat.app@1.0.0',
|
||||
* 'peer-username',
|
||||
* { initialInterval: 500, maxInterval: 5000, jitter: true }
|
||||
* )
|
||||
*
|
||||
* // For offerer:
|
||||
* await signaler.setOffer(offer)
|
||||
* signaler.addAnswerListener(answer => {
|
||||
* // Handle remote answer
|
||||
* })
|
||||
*
|
||||
* // For answerer:
|
||||
* signaler.addOfferListener(offer => {
|
||||
* // Handle remote offer
|
||||
* })
|
||||
* await signaler.setAnswer(answer)
|
||||
* ```
|
||||
*/
|
||||
export class RondevuSignaler implements Signaler {
|
||||
private offerId: string | null = null
|
||||
private serviceUuid: string | null = null
|
||||
private offerListeners: Array<(offer: RTCSessionDescriptionInit) => void> = []
|
||||
private answerListeners: Array<(answer: RTCSessionDescriptionInit) => void> = []
|
||||
private iceListeners: Array<(candidate: RTCIceCandidate) => void> = []
|
||||
private answerPollingTimeout: ReturnType<typeof setTimeout> | null = null
|
||||
private icePollingTimeout: ReturnType<typeof setTimeout> | null = null
|
||||
private lastIceTimestamp = 0
|
||||
private isPolling = false
|
||||
private pollingConfig: Required<PollingConfig>
|
||||
|
||||
constructor(
|
||||
private readonly rondevu: RondevuService,
|
||||
private readonly service: string,
|
||||
private readonly host?: string,
|
||||
pollingConfig?: PollingConfig
|
||||
) {
|
||||
this.pollingConfig = {
|
||||
initialInterval: pollingConfig?.initialInterval ?? 500,
|
||||
maxInterval: pollingConfig?.maxInterval ?? 5000,
|
||||
backoffMultiplier: pollingConfig?.backoffMultiplier ?? 1.5,
|
||||
maxRetries: pollingConfig?.maxRetries ?? 50,
|
||||
jitter: pollingConfig?.jitter ?? true
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Publish an offer as a service
|
||||
* Used by the offerer to make their offer available
|
||||
*/
|
||||
async setOffer(offer: RTCSessionDescriptionInit): Promise<void> {
|
||||
if (!offer.sdp) {
|
||||
throw new Error('Offer SDP is required')
|
||||
}
|
||||
|
||||
// Publish service with the offer SDP
|
||||
const publishedService = await this.rondevu.publishService({
|
||||
serviceFqn: this.service,
|
||||
offers: [{ sdp: offer.sdp }],
|
||||
ttl: 300000, // 5 minutes
|
||||
isPublic: true,
|
||||
})
|
||||
|
||||
// Get the first offer from the published service
|
||||
if (!publishedService.offers || publishedService.offers.length === 0) {
|
||||
throw new Error('No offers returned from service publication')
|
||||
}
|
||||
|
||||
this.offerId = publishedService.offers[0].offerId
|
||||
this.serviceUuid = publishedService.uuid
|
||||
|
||||
// Start polling for answer
|
||||
this.startAnswerPolling()
|
||||
|
||||
// Start polling for ICE candidates
|
||||
this.startIcePolling()
|
||||
}
|
||||
|
||||
/**
|
||||
* Send an answer to the offerer
|
||||
* Used by the answerer to respond to an offer
|
||||
*/
|
||||
async setAnswer(answer: RTCSessionDescriptionInit): Promise<void> {
|
||||
if (!answer.sdp) {
|
||||
throw new Error('Answer SDP is required')
|
||||
}
|
||||
|
||||
if (!this.serviceUuid) {
|
||||
throw new Error('No service UUID available. Must receive offer first.')
|
||||
}
|
||||
|
||||
// Send answer to the service
|
||||
const result = await this.rondevu.getAPI().answerService(this.serviceUuid, answer.sdp)
|
||||
this.offerId = result.offerId
|
||||
|
||||
// Start polling for ICE candidates
|
||||
this.startIcePolling()
|
||||
}
|
||||
|
||||
/**
|
||||
* Listen for incoming offers
|
||||
* Used by the answerer to receive offers from the offerer
|
||||
*/
|
||||
addOfferListener(callback: (offer: RTCSessionDescriptionInit) => void): Binnable {
|
||||
this.offerListeners.push(callback)
|
||||
|
||||
// If we have a host, start searching for their service
|
||||
if (this.host && !this.isPolling) {
|
||||
this.searchForOffer()
|
||||
}
|
||||
|
||||
// Return cleanup function
|
||||
return () => {
|
||||
const index = this.offerListeners.indexOf(callback)
|
||||
if (index > -1) {
|
||||
this.offerListeners.splice(index, 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Listen for incoming answers
|
||||
* Used by the offerer to receive the answer from the answerer
|
||||
*/
|
||||
addAnswerListener(callback: (answer: RTCSessionDescriptionInit) => void): Binnable {
|
||||
this.answerListeners.push(callback)
|
||||
|
||||
// Return cleanup function
|
||||
return () => {
|
||||
const index = this.answerListeners.indexOf(callback)
|
||||
if (index > -1) {
|
||||
this.answerListeners.splice(index, 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Send an ICE candidate to the remote peer
|
||||
*/
|
||||
async addIceCandidate(candidate: RTCIceCandidate): Promise<void> {
|
||||
if (!this.serviceUuid) {
|
||||
console.warn('Cannot send ICE candidate: no service UUID')
|
||||
return
|
||||
}
|
||||
|
||||
const candidateData = candidate.toJSON()
|
||||
|
||||
// Skip empty candidates
|
||||
if (!candidateData.candidate || candidateData.candidate === '') {
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await this.rondevu.getAPI().addServiceIceCandidates(
|
||||
this.serviceUuid,
|
||||
[candidateData],
|
||||
this.offerId || undefined
|
||||
)
|
||||
// Store offerId if we didn't have it yet
|
||||
if (!this.offerId) {
|
||||
this.offerId = result.offerId
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Failed to send ICE candidate:', err)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Listen for ICE candidates from the remote peer
|
||||
*/
|
||||
addListener(callback: (candidate: RTCIceCandidate) => void): Binnable {
|
||||
this.iceListeners.push(callback)
|
||||
|
||||
// Return cleanup function
|
||||
return () => {
|
||||
const index = this.iceListeners.indexOf(callback)
|
||||
if (index > -1) {
|
||||
this.iceListeners.splice(index, 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Search for an offer from the host
|
||||
* Used by the answerer to find the offerer's service
|
||||
*/
|
||||
private async searchForOffer(): Promise<void> {
|
||||
if (!this.host) {
|
||||
throw new Error('No host specified for offer search')
|
||||
}
|
||||
|
||||
this.isPolling = true
|
||||
|
||||
try {
|
||||
// Search for services by username and service FQN
|
||||
const services = await this.rondevu.getAPI().searchServices(this.host, this.service)
|
||||
|
||||
if (services.length === 0) {
|
||||
console.warn(`No services found for ${this.host}/${this.service}`)
|
||||
this.isPolling = false
|
||||
return
|
||||
}
|
||||
|
||||
// Get the first available service (already has full details from searchServices)
|
||||
const service = services[0] as any
|
||||
|
||||
// Get the first available offer from the service
|
||||
if (!service.offers || service.offers.length === 0) {
|
||||
console.warn(`No offers available for service ${this.host}/${this.service}`)
|
||||
this.isPolling = false
|
||||
return
|
||||
}
|
||||
|
||||
const firstOffer = service.offers[0]
|
||||
this.offerId = firstOffer.offerId
|
||||
this.serviceUuid = service.uuid
|
||||
|
||||
// Notify offer listeners
|
||||
const offer: RTCSessionDescriptionInit = {
|
||||
type: 'offer',
|
||||
sdp: firstOffer.sdp,
|
||||
}
|
||||
|
||||
this.offerListeners.forEach(listener => {
|
||||
try {
|
||||
listener(offer)
|
||||
} catch (err) {
|
||||
console.error('Offer listener error:', err)
|
||||
}
|
||||
})
|
||||
} catch (err) {
|
||||
console.error('Failed to search for offer:', err)
|
||||
this.isPolling = false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Start polling for answer (offerer side) with exponential backoff
|
||||
*/
|
||||
private startAnswerPolling(): void {
|
||||
if (this.answerPollingTimeout || !this.serviceUuid) {
|
||||
return
|
||||
}
|
||||
|
||||
let interval = this.pollingConfig.initialInterval
|
||||
let retries = 0
|
||||
|
||||
const poll = async () => {
|
||||
if (!this.serviceUuid) {
|
||||
this.stopAnswerPolling()
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
const answer = await this.rondevu.getAPI().getServiceAnswer(this.serviceUuid)
|
||||
|
||||
if (answer && answer.sdp) {
|
||||
// Store offerId if we didn't have it yet
|
||||
if (!this.offerId) {
|
||||
this.offerId = answer.offerId
|
||||
}
|
||||
|
||||
// Got answer - notify listeners and stop polling
|
||||
const answerDesc: RTCSessionDescriptionInit = {
|
||||
type: 'answer',
|
||||
sdp: answer.sdp,
|
||||
}
|
||||
|
||||
this.answerListeners.forEach(listener => {
|
||||
try {
|
||||
listener(answerDesc)
|
||||
} catch (err) {
|
||||
console.error('Answer listener error:', err)
|
||||
}
|
||||
})
|
||||
|
||||
// Stop polling once we get the answer
|
||||
this.stopAnswerPolling()
|
||||
return
|
||||
}
|
||||
|
||||
// No answer yet - exponential backoff
|
||||
retries++
|
||||
if (retries > this.pollingConfig.maxRetries) {
|
||||
console.warn('Max retries reached for answer polling')
|
||||
this.stopAnswerPolling()
|
||||
return
|
||||
}
|
||||
|
||||
interval = Math.min(
|
||||
interval * this.pollingConfig.backoffMultiplier,
|
||||
this.pollingConfig.maxInterval
|
||||
)
|
||||
|
||||
// Add jitter to prevent thundering herd
|
||||
const finalInterval = this.pollingConfig.jitter
|
||||
? interval + Math.random() * 100
|
||||
: interval
|
||||
|
||||
this.answerPollingTimeout = setTimeout(poll, finalInterval)
|
||||
|
||||
} catch (err) {
|
||||
// 404 is expected when answer isn't available yet
|
||||
if (err instanceof Error && !err.message?.includes('404')) {
|
||||
console.error('Error polling for answer:', err)
|
||||
}
|
||||
|
||||
// Retry with backoff
|
||||
const finalInterval = this.pollingConfig.jitter
|
||||
? interval + Math.random() * 100
|
||||
: interval
|
||||
this.answerPollingTimeout = setTimeout(poll, finalInterval)
|
||||
}
|
||||
}
|
||||
|
||||
poll() // Start immediately
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop polling for answer
|
||||
*/
|
||||
private stopAnswerPolling(): void {
|
||||
if (this.answerPollingTimeout) {
|
||||
clearTimeout(this.answerPollingTimeout)
|
||||
this.answerPollingTimeout = null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Start polling for ICE candidates with adaptive backoff
|
||||
*/
|
||||
private startIcePolling(): void {
|
||||
if (this.icePollingTimeout || !this.serviceUuid) {
|
||||
return
|
||||
}
|
||||
|
||||
let interval = this.pollingConfig.initialInterval
|
||||
|
||||
const poll = async () => {
|
||||
if (!this.serviceUuid) {
|
||||
this.stopIcePolling()
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await this.rondevu
|
||||
.getAPI()
|
||||
.getServiceIceCandidates(this.serviceUuid, this.lastIceTimestamp, this.offerId || undefined)
|
||||
|
||||
// Store offerId if we didn't have it yet
|
||||
if (!this.offerId) {
|
||||
this.offerId = result.offerId
|
||||
}
|
||||
|
||||
let foundCandidates = false
|
||||
|
||||
for (const item of result.candidates) {
|
||||
if (item.candidate && item.candidate.candidate && item.candidate.candidate !== '') {
|
||||
foundCandidates = true
|
||||
try {
|
||||
const rtcCandidate = new RTCIceCandidate(item.candidate)
|
||||
|
||||
this.iceListeners.forEach(listener => {
|
||||
try {
|
||||
listener(rtcCandidate)
|
||||
} catch (err) {
|
||||
console.error('ICE listener error:', err)
|
||||
}
|
||||
})
|
||||
|
||||
this.lastIceTimestamp = item.createdAt
|
||||
} catch (err) {
|
||||
console.warn('Failed to process ICE candidate:', err)
|
||||
this.lastIceTimestamp = item.createdAt
|
||||
}
|
||||
} else {
|
||||
this.lastIceTimestamp = item.createdAt
|
||||
}
|
||||
}
|
||||
|
||||
// If candidates found, reset interval to initial value
|
||||
// Otherwise, increase interval with backoff
|
||||
if (foundCandidates) {
|
||||
interval = this.pollingConfig.initialInterval
|
||||
} else {
|
||||
interval = Math.min(
|
||||
interval * this.pollingConfig.backoffMultiplier,
|
||||
this.pollingConfig.maxInterval
|
||||
)
|
||||
}
|
||||
|
||||
// Add jitter
|
||||
const finalInterval = this.pollingConfig.jitter
|
||||
? interval + Math.random() * 100
|
||||
: interval
|
||||
|
||||
this.icePollingTimeout = setTimeout(poll, finalInterval)
|
||||
|
||||
} catch (err) {
|
||||
// 404/410 means offer expired, stop polling
|
||||
if (err instanceof Error && (err.message?.includes('404') || err.message?.includes('410'))) {
|
||||
console.warn('Offer not found or expired, stopping ICE polling')
|
||||
this.stopIcePolling()
|
||||
} else if (err instanceof Error && !err.message?.includes('404')) {
|
||||
console.error('Error polling for ICE candidates:', err)
|
||||
// Continue polling despite errors
|
||||
const finalInterval = this.pollingConfig.jitter
|
||||
? interval + Math.random() * 100
|
||||
: interval
|
||||
this.icePollingTimeout = setTimeout(poll, finalInterval)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
poll() // Start immediately
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop polling for ICE candidates
|
||||
*/
|
||||
private stopIcePolling(): void {
|
||||
if (this.icePollingTimeout) {
|
||||
clearTimeout(this.icePollingTimeout)
|
||||
this.icePollingTimeout = null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop all polling and cleanup
|
||||
*/
|
||||
dispose(): void {
|
||||
this.stopAnswerPolling()
|
||||
this.stopIcePolling()
|
||||
this.offerListeners = []
|
||||
this.answerListeners = []
|
||||
this.iceListeners = []
|
||||
}
|
||||
}
|
||||
273
src/rondevu.ts
273
src/rondevu.ts
@@ -1,273 +0,0 @@
|
||||
import { RondevuClient } from './client';
|
||||
import { RondevuConnection } from './connection';
|
||||
import { RondevuOptions, JoinOptions, RondevuConnectionParams } from './types';
|
||||
|
||||
/**
|
||||
* Main Rondevu WebRTC client with automatic connection management
|
||||
*/
|
||||
export class Rondevu {
|
||||
readonly peerId: string;
|
||||
|
||||
private client: RondevuClient;
|
||||
private baseUrl: string;
|
||||
private fetchImpl?: typeof fetch;
|
||||
private rtcConfig?: RTCConfiguration;
|
||||
private pollingInterval: number;
|
||||
private connectionTimeout: number;
|
||||
|
||||
/**
|
||||
* Creates a new Rondevu client instance
|
||||
* @param options - Client configuration options
|
||||
*/
|
||||
constructor(options: RondevuOptions = {}) {
|
||||
this.baseUrl = options.baseUrl || 'https://rondevu.xtrdev.workers.dev';
|
||||
this.fetchImpl = options.fetch;
|
||||
|
||||
this.client = new RondevuClient({
|
||||
baseUrl: this.baseUrl,
|
||||
fetch: options.fetch,
|
||||
});
|
||||
|
||||
// Auto-generate peer ID if not provided
|
||||
this.peerId = options.peerId || this.generatePeerId();
|
||||
this.rtcConfig = options.rtcConfig;
|
||||
this.pollingInterval = options.pollingInterval || 1000;
|
||||
this.connectionTimeout = options.connectionTimeout || 30000;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a unique peer ID
|
||||
*/
|
||||
private generatePeerId(): string {
|
||||
return `rdv_${Math.random().toString(36).substring(2, 14)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the peer ID (useful when user identity changes)
|
||||
*/
|
||||
updatePeerId(newPeerId: string): void {
|
||||
(this as any).peerId = newPeerId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new connection (offerer role)
|
||||
* @param id - Connection identifier
|
||||
* @param topic - Topic name for grouping connections
|
||||
* @returns Promise that resolves to RondevuConnection
|
||||
*/
|
||||
async create(id: string, topic: string): Promise<RondevuConnection> {
|
||||
// Create peer connection
|
||||
const pc = new RTCPeerConnection(this.rtcConfig);
|
||||
|
||||
// Create initial data channel for negotiation (required for offer creation)
|
||||
pc.createDataChannel('_negotiation');
|
||||
|
||||
// Generate offer
|
||||
const offer = await pc.createOffer();
|
||||
await pc.setLocalDescription(offer);
|
||||
|
||||
// Wait for ICE gathering to complete
|
||||
await this.waitForIceGathering(pc);
|
||||
|
||||
// Create session on server with custom code
|
||||
await this.client.createOffer(topic, {
|
||||
peerId: this.peerId,
|
||||
offer: pc.localDescription!.sdp,
|
||||
code: id,
|
||||
});
|
||||
|
||||
// Create connection object
|
||||
const connectionParams: RondevuConnectionParams = {
|
||||
id,
|
||||
topic,
|
||||
role: 'offerer',
|
||||
pc,
|
||||
localPeerId: this.peerId,
|
||||
remotePeerId: '', // Will be populated when answer is received
|
||||
pollingInterval: this.pollingInterval,
|
||||
connectionTimeout: this.connectionTimeout,
|
||||
};
|
||||
|
||||
const connection = new RondevuConnection(connectionParams, this.client);
|
||||
|
||||
// Start polling for answer
|
||||
connection.startPolling();
|
||||
|
||||
return connection;
|
||||
}
|
||||
|
||||
/**
|
||||
* Connect to an existing connection by ID (answerer role)
|
||||
* @param id - Connection identifier
|
||||
* @returns Promise that resolves to RondevuConnection
|
||||
*/
|
||||
async connect(id: string): Promise<RondevuConnection> {
|
||||
// Poll server to get session by ID
|
||||
const sessionData = await this.findSessionByIdWithClient(id, this.client);
|
||||
|
||||
if (!sessionData) {
|
||||
throw new Error(`Connection ${id} not found or expired`);
|
||||
}
|
||||
|
||||
// Create peer connection
|
||||
const pc = new RTCPeerConnection(this.rtcConfig);
|
||||
|
||||
// Set remote offer
|
||||
await pc.setRemoteDescription({
|
||||
type: 'offer',
|
||||
sdp: sessionData.offer,
|
||||
});
|
||||
|
||||
// Generate answer
|
||||
const answer = await pc.createAnswer();
|
||||
await pc.setLocalDescription(answer);
|
||||
|
||||
// Wait for ICE gathering
|
||||
await this.waitForIceGathering(pc);
|
||||
|
||||
// Send answer to server
|
||||
await this.client.sendAnswer({
|
||||
code: id,
|
||||
answer: pc.localDescription!.sdp,
|
||||
side: 'answerer',
|
||||
});
|
||||
|
||||
// Create connection object
|
||||
const connectionParams: RondevuConnectionParams = {
|
||||
id,
|
||||
topic: sessionData.topic || 'unknown',
|
||||
role: 'answerer',
|
||||
pc,
|
||||
localPeerId: this.peerId,
|
||||
remotePeerId: sessionData.peerId,
|
||||
pollingInterval: this.pollingInterval,
|
||||
connectionTimeout: this.connectionTimeout,
|
||||
};
|
||||
|
||||
const connection = new RondevuConnection(connectionParams, this.client);
|
||||
|
||||
// Start polling for ICE candidates
|
||||
connection.startPolling();
|
||||
|
||||
return connection;
|
||||
}
|
||||
|
||||
/**
|
||||
* Join a topic and discover available peers (answerer role)
|
||||
* @param topic - Topic name
|
||||
* @param options - Optional join options for filtering and selection
|
||||
* @returns Promise that resolves to RondevuConnection
|
||||
*/
|
||||
async join(topic: string, options?: JoinOptions): Promise<RondevuConnection> {
|
||||
// List sessions in topic
|
||||
const { sessions } = await this.client.listSessions(topic);
|
||||
|
||||
// Filter out self (sessions with our peer ID)
|
||||
let availableSessions = sessions.filter(
|
||||
session => session.peerId !== this.peerId
|
||||
);
|
||||
|
||||
// Apply custom filter if provided
|
||||
if (options?.filter) {
|
||||
availableSessions = availableSessions.filter(options.filter);
|
||||
}
|
||||
|
||||
if (availableSessions.length === 0) {
|
||||
throw new Error(`No available peers in topic: ${topic}`);
|
||||
}
|
||||
|
||||
// Select session based on strategy
|
||||
const selectedSession = this.selectSession(
|
||||
availableSessions,
|
||||
options?.select || 'first'
|
||||
);
|
||||
|
||||
// Connect to selected session
|
||||
return this.connect(selectedSession.code);
|
||||
}
|
||||
|
||||
/**
|
||||
* Select a session based on strategy
|
||||
*/
|
||||
private selectSession(
|
||||
sessions: Array<{ code: string; peerId: string; createdAt: number }>,
|
||||
strategy: 'first' | 'newest' | 'oldest' | 'random'
|
||||
): { code: string; peerId: string; createdAt: number } {
|
||||
switch (strategy) {
|
||||
case 'first':
|
||||
return sessions[0];
|
||||
case 'newest':
|
||||
return sessions.reduce((newest, session) =>
|
||||
session.createdAt > newest.createdAt ? session : newest
|
||||
);
|
||||
case 'oldest':
|
||||
return sessions.reduce((oldest, session) =>
|
||||
session.createdAt < oldest.createdAt ? session : oldest
|
||||
);
|
||||
case 'random':
|
||||
return sessions[Math.floor(Math.random() * sessions.length)];
|
||||
default:
|
||||
return sessions[0];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Wait for ICE gathering to complete
|
||||
*/
|
||||
private async waitForIceGathering(pc: RTCPeerConnection): Promise<void> {
|
||||
if (pc.iceGatheringState === 'complete') {
|
||||
return;
|
||||
}
|
||||
|
||||
return new Promise((resolve) => {
|
||||
const checkState = () => {
|
||||
if (pc.iceGatheringState === 'complete') {
|
||||
pc.removeEventListener('icegatheringstatechange', checkState);
|
||||
resolve();
|
||||
}
|
||||
};
|
||||
|
||||
pc.addEventListener('icegatheringstatechange', checkState);
|
||||
|
||||
// Also set a timeout in case gathering takes too long
|
||||
setTimeout(() => {
|
||||
pc.removeEventListener('icegatheringstatechange', checkState);
|
||||
resolve();
|
||||
}, 5000);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Find a session by connection ID
|
||||
* This requires polling since we don't know which topic it's in
|
||||
*/
|
||||
private async findSessionByIdWithClient(
|
||||
id: string,
|
||||
client: RondevuClient
|
||||
): Promise<{
|
||||
code: string;
|
||||
peerId: string;
|
||||
offer: string;
|
||||
topic?: string;
|
||||
} | null> {
|
||||
try {
|
||||
// Try to poll for the session directly
|
||||
// The poll endpoint should return the session data
|
||||
const response = await client.poll(id, 'answerer');
|
||||
const answererResponse = response as { offer: string; offerCandidates: string[] };
|
||||
|
||||
if (answererResponse.offer) {
|
||||
return {
|
||||
code: id,
|
||||
peerId: '', // Will be populated from session data
|
||||
offer: answererResponse.offer,
|
||||
topic: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
return null;
|
||||
} catch (err) {
|
||||
throw new Error(`Failed to find session ${id}: ${(err as Error).message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
203
src/service-client.ts
Normal file
203
src/service-client.ts
Normal file
@@ -0,0 +1,203 @@
|
||||
import { RondevuService } from './rondevu-service.js'
|
||||
import { RondevuSignaler } from './rondevu-signaler.js'
|
||||
import { WebRTCContext } from './webrtc-context.js'
|
||||
import { RTCDurableConnection } from './durable-connection.js'
|
||||
import { EventBus } from './event-bus.js'
|
||||
|
||||
export interface ServiceClientOptions {
|
||||
username: string // Host username
|
||||
serviceFqn: string // e.g., 'chat.app@1.0.0'
|
||||
rondevuService: RondevuService
|
||||
autoReconnect?: boolean // Default: true
|
||||
maxReconnectAttempts?: number // Default: 5
|
||||
rtcConfiguration?: RTCConfiguration
|
||||
}
|
||||
|
||||
export interface ServiceClientEvents {
|
||||
connected: RTCDurableConnection
|
||||
disconnected: void
|
||||
reconnecting: { attempt: number; maxAttempts: number }
|
||||
error: Error
|
||||
}
|
||||
|
||||
/**
|
||||
* ServiceClient - High-level wrapper for connecting to a WebRTC service
|
||||
*
|
||||
* Simplifies client connection by handling:
|
||||
* - Service discovery
|
||||
* - Offer/answer exchange
|
||||
* - ICE candidate polling
|
||||
* - Automatic reconnection
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const client = new ServiceClient({
|
||||
* username: 'host-user',
|
||||
* serviceFqn: 'chat.app@1.0.0',
|
||||
* rondevuService: myService
|
||||
* })
|
||||
*
|
||||
* client.events.on('connected', conn => {
|
||||
* conn.events.on('message', msg => console.log('Received:', msg))
|
||||
* conn.sendMessage('Hello from client!')
|
||||
* })
|
||||
*
|
||||
* await client.connect()
|
||||
* ```
|
||||
*/
|
||||
export class ServiceClient {
|
||||
events: EventBus<ServiceClientEvents>
|
||||
|
||||
private signaler: RondevuSignaler | null = null
|
||||
private webrtcContext: WebRTCContext
|
||||
private connection: RTCDurableConnection | null = null
|
||||
private autoReconnect: boolean
|
||||
private maxReconnectAttempts: number
|
||||
private reconnectAttempts = 0
|
||||
private isConnecting = false
|
||||
|
||||
constructor(private options: ServiceClientOptions) {
|
||||
this.events = new EventBus<ServiceClientEvents>()
|
||||
this.webrtcContext = new WebRTCContext(options.rtcConfiguration)
|
||||
this.autoReconnect = options.autoReconnect !== undefined ? options.autoReconnect : true
|
||||
this.maxReconnectAttempts = options.maxReconnectAttempts || 5
|
||||
}
|
||||
|
||||
/**
|
||||
* Connect to the service
|
||||
*/
|
||||
async connect(): Promise<RTCDurableConnection> {
|
||||
if (this.isConnecting) {
|
||||
throw new Error('Connection already in progress')
|
||||
}
|
||||
|
||||
if (this.connection) {
|
||||
throw new Error('Already connected. Disconnect first.')
|
||||
}
|
||||
|
||||
this.isConnecting = true
|
||||
|
||||
try {
|
||||
// Create signaler
|
||||
this.signaler = new RondevuSignaler(
|
||||
this.options.rondevuService,
|
||||
this.options.serviceFqn,
|
||||
this.options.username
|
||||
)
|
||||
|
||||
// Wait for remote offer from signaler
|
||||
const remoteOffer = await new Promise<RTCSessionDescriptionInit>((resolve, reject) => {
|
||||
const timeout = setTimeout(() => {
|
||||
reject(new Error('Service discovery timeout'))
|
||||
}, 30000)
|
||||
|
||||
this.signaler!.addOfferListener((offer) => {
|
||||
clearTimeout(timeout)
|
||||
resolve(offer)
|
||||
})
|
||||
})
|
||||
|
||||
// Create connection with remote offer (makes us the answerer)
|
||||
const connection = new RTCDurableConnection({
|
||||
context: this.webrtcContext,
|
||||
signaler: this.signaler,
|
||||
offer: remoteOffer
|
||||
})
|
||||
|
||||
// Wait for connection to be ready
|
||||
await connection.ready
|
||||
|
||||
// Set up connection event listeners
|
||||
connection.events.on('state-change', (state) => {
|
||||
if (state === 'connected') {
|
||||
this.reconnectAttempts = 0
|
||||
this.events.emit('connected', connection)
|
||||
} else if (state === 'disconnected') {
|
||||
this.events.emit('disconnected', undefined)
|
||||
if (this.autoReconnect && this.reconnectAttempts < this.maxReconnectAttempts) {
|
||||
this.attemptReconnect()
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
this.connection = connection
|
||||
this.isConnecting = false
|
||||
|
||||
return connection
|
||||
|
||||
} catch (err) {
|
||||
this.isConnecting = false
|
||||
const error = err instanceof Error ? err : new Error(String(err))
|
||||
this.events.emit('error', error)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Disconnect from the service
|
||||
*/
|
||||
dispose(): void {
|
||||
if (this.signaler) {
|
||||
this.signaler.dispose()
|
||||
this.signaler = null
|
||||
}
|
||||
|
||||
if (this.connection) {
|
||||
this.connection.disconnect()
|
||||
this.connection = null
|
||||
}
|
||||
|
||||
this.isConnecting = false
|
||||
this.reconnectAttempts = 0
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated Use dispose() instead
|
||||
*/
|
||||
disconnect(): void {
|
||||
this.dispose()
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempt to reconnect
|
||||
*/
|
||||
private async attemptReconnect(): Promise<void> {
|
||||
this.reconnectAttempts++
|
||||
this.events.emit('reconnecting', {
|
||||
attempt: this.reconnectAttempts,
|
||||
maxAttempts: this.maxReconnectAttempts
|
||||
})
|
||||
|
||||
// Cleanup old connection
|
||||
if (this.signaler) {
|
||||
this.signaler.dispose()
|
||||
this.signaler = null
|
||||
}
|
||||
|
||||
if (this.connection) {
|
||||
this.connection = null
|
||||
}
|
||||
|
||||
// Wait a bit before reconnecting
|
||||
await new Promise(resolve => setTimeout(resolve, 1000 * this.reconnectAttempts))
|
||||
|
||||
try {
|
||||
await this.connect()
|
||||
} catch (err) {
|
||||
console.error('Reconnection attempt failed:', err)
|
||||
if (this.reconnectAttempts < this.maxReconnectAttempts) {
|
||||
this.attemptReconnect()
|
||||
} else {
|
||||
const error = new Error('Max reconnection attempts reached')
|
||||
this.events.emit('error', error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the current connection
|
||||
*/
|
||||
getConnection(): RTCDurableConnection | null {
|
||||
return this.connection
|
||||
}
|
||||
}
|
||||
158
src/service-host.ts
Normal file
158
src/service-host.ts
Normal file
@@ -0,0 +1,158 @@
|
||||
import { RondevuService } from './rondevu-service.js'
|
||||
import { RondevuSignaler } from './rondevu-signaler.js'
|
||||
import { WebRTCContext } from './webrtc-context.js'
|
||||
import { RTCDurableConnection } from './durable-connection.js'
|
||||
import { EventBus } from './event-bus.js'
|
||||
|
||||
export interface ServiceHostOptions {
|
||||
service: string // e.g., 'chat.app@1.0.0'
|
||||
rondevuService: RondevuService
|
||||
maxPeers?: number // Default: 5
|
||||
ttl?: number // Default: 300000 (5 min)
|
||||
isPublic?: boolean // Default: true
|
||||
rtcConfiguration?: RTCConfiguration
|
||||
metadata?: Record<string, any>
|
||||
}
|
||||
|
||||
export interface ServiceHostEvents {
|
||||
connection: RTCDurableConnection
|
||||
error: Error
|
||||
}
|
||||
|
||||
/**
|
||||
* ServiceHost - High-level wrapper for hosting a WebRTC service
|
||||
*
|
||||
* Simplifies hosting by handling:
|
||||
* - Offer/answer exchange
|
||||
* - ICE candidate polling
|
||||
* - Connection pool management
|
||||
* - Automatic reconnection
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const host = new ServiceHost({
|
||||
* service: 'chat.app@1.0.0',
|
||||
* rondevuService: myService,
|
||||
* maxPeers: 5
|
||||
* })
|
||||
*
|
||||
* host.events.on('connection', conn => {
|
||||
* conn.events.on('message', msg => console.log('Received:', msg))
|
||||
* conn.sendMessage('Hello!')
|
||||
* })
|
||||
*
|
||||
* await host.start()
|
||||
* ```
|
||||
*/
|
||||
export class ServiceHost {
|
||||
events: EventBus<ServiceHostEvents>
|
||||
|
||||
private signaler: RondevuSignaler | null = null
|
||||
private webrtcContext: WebRTCContext
|
||||
private connections: RTCDurableConnection[] = []
|
||||
private maxPeers: number
|
||||
private running = false
|
||||
|
||||
constructor(private options: ServiceHostOptions) {
|
||||
this.events = new EventBus<ServiceHostEvents>()
|
||||
this.webrtcContext = new WebRTCContext(options.rtcConfiguration)
|
||||
this.maxPeers = options.maxPeers || 5
|
||||
}
|
||||
|
||||
/**
|
||||
* Start hosting the service
|
||||
*/
|
||||
async start(): Promise<void> {
|
||||
if (this.running) {
|
||||
throw new Error('ServiceHost already running')
|
||||
}
|
||||
|
||||
this.running = true
|
||||
|
||||
// Create signaler
|
||||
this.signaler = new RondevuSignaler(
|
||||
this.options.rondevuService,
|
||||
this.options.service
|
||||
)
|
||||
|
||||
// Create first connection (offerer)
|
||||
const connection = new RTCDurableConnection({
|
||||
context: this.webrtcContext,
|
||||
signaler: this.signaler,
|
||||
offer: null // null means we're the offerer
|
||||
})
|
||||
|
||||
// Wait for connection to be ready
|
||||
await connection.ready
|
||||
|
||||
// Set up connection event listeners
|
||||
connection.events.on('state-change', (state) => {
|
||||
if (state === 'connected') {
|
||||
this.connections.push(connection)
|
||||
this.events.emit('connection', connection)
|
||||
|
||||
// Create next connection if under maxPeers
|
||||
if (this.connections.length < this.maxPeers) {
|
||||
this.createNextConnection().catch(err => {
|
||||
console.error('Failed to create next connection:', err)
|
||||
this.events.emit('error', err)
|
||||
})
|
||||
}
|
||||
} else if (state === 'disconnected') {
|
||||
// Remove from connections list
|
||||
const index = this.connections.indexOf(connection)
|
||||
if (index > -1) {
|
||||
this.connections.splice(index, 1)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
// Publish service with the offer
|
||||
const offer = connection.connection?.localDescription
|
||||
if (!offer?.sdp) {
|
||||
throw new Error('Offer SDP is empty')
|
||||
}
|
||||
|
||||
await this.signaler.setOffer(offer)
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the next connection for incoming peers
|
||||
*/
|
||||
private async createNextConnection(): Promise<void> {
|
||||
if (!this.signaler || !this.running) {
|
||||
return
|
||||
}
|
||||
|
||||
// For now, we'll use the same offer for all connections
|
||||
// In a production scenario, you'd create multiple offers
|
||||
// This is a limitation of the current service model
|
||||
// which publishes one offer per service
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop hosting the service
|
||||
*/
|
||||
dispose(): void {
|
||||
this.running = false
|
||||
|
||||
// Cleanup signaler
|
||||
if (this.signaler) {
|
||||
this.signaler.dispose()
|
||||
this.signaler = null
|
||||
}
|
||||
|
||||
// Disconnect all connections
|
||||
for (const conn of this.connections) {
|
||||
conn.disconnect()
|
||||
}
|
||||
this.connections = []
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all active connections
|
||||
*/
|
||||
getConnections(): RTCDurableConnection[] {
|
||||
return [...this.connections]
|
||||
}
|
||||
}
|
||||
260
src/types.ts
260
src/types.ts
@@ -1,236 +1,44 @@
|
||||
// ============================================================================
|
||||
// Signaling Types
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* Session side - identifies which peer in a connection
|
||||
* Core connection types
|
||||
*/
|
||||
export type Side = 'offerer' | 'answerer';
|
||||
import { EventBus } from './event-bus.js'
|
||||
import { Binnable } from './bin.js'
|
||||
|
||||
/**
|
||||
* Session information returned from discovery endpoints
|
||||
*/
|
||||
export interface Session {
|
||||
/** Unique session identifier (UUID) */
|
||||
code: string;
|
||||
/** Peer identifier/metadata */
|
||||
peerId: string;
|
||||
/** Signaling data for peer connection */
|
||||
offer: string;
|
||||
/** Additional signaling data from offerer */
|
||||
offerCandidates: string[];
|
||||
/** Unix timestamp when session was created */
|
||||
createdAt: number;
|
||||
/** Unix timestamp when session expires */
|
||||
expiresAt: number;
|
||||
export type Message = string | ArrayBuffer
|
||||
|
||||
export interface QueueMessageOptions {
|
||||
expiresAt?: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Topic information with peer count
|
||||
*/
|
||||
export interface TopicInfo {
|
||||
/** Topic identifier */
|
||||
topic: string;
|
||||
/** Number of available peers in this topic */
|
||||
count: number;
|
||||
export interface ConnectionEvents {
|
||||
'state-change': ConnectionInterface['state']
|
||||
message: Message
|
||||
}
|
||||
|
||||
/**
|
||||
* Pagination information
|
||||
*/
|
||||
export interface Pagination {
|
||||
/** Current page number */
|
||||
page: number;
|
||||
/** Results per page */
|
||||
limit: number;
|
||||
/** Total number of results */
|
||||
total: number;
|
||||
/** Whether there are more results available */
|
||||
hasMore: boolean;
|
||||
export const ConnectionStates = [
|
||||
'connected',
|
||||
'disconnected',
|
||||
'connecting'
|
||||
] as const
|
||||
|
||||
export const isConnectionState = (state: string): state is (typeof ConnectionStates)[number] =>
|
||||
ConnectionStates.includes(state as any)
|
||||
|
||||
export interface ConnectionInterface {
|
||||
state: (typeof ConnectionStates)[number]
|
||||
lastActive: number
|
||||
expiresAt?: number
|
||||
events: EventBus<ConnectionEvents>
|
||||
|
||||
queueMessage(message: Message, options?: QueueMessageOptions): Promise<void>
|
||||
sendMessage(message: Message): Promise<boolean>
|
||||
}
|
||||
|
||||
/**
|
||||
* Response from GET / - list all topics
|
||||
*/
|
||||
export interface ListTopicsResponse {
|
||||
topics: TopicInfo[];
|
||||
pagination: Pagination;
|
||||
}
|
||||
|
||||
/**
|
||||
* Response from GET /:topic/sessions - list sessions in a topic
|
||||
*/
|
||||
export interface ListSessionsResponse {
|
||||
sessions: Session[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Request body for POST /:topic/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 /:topic/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;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* Configuration options for Rondevu WebRTC client
|
||||
*/
|
||||
export interface RondevuOptions {
|
||||
/** Base URL of the Rondevu server (defaults to 'https://rondevu.xtrdev.workers.dev') */
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
* Options for joining a topic
|
||||
*/
|
||||
export interface JoinOptions {
|
||||
/** Filter function to select specific sessions */
|
||||
filter?: (session: { code: string; peerId: string }) => boolean;
|
||||
/** Selection strategy for choosing a session */
|
||||
select?: 'first' | 'newest' | 'oldest' | 'random';
|
||||
}
|
||||
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
|
||||
/**
|
||||
* Event map for RondevuConnection events
|
||||
*/
|
||||
export interface RondevuConnectionEvents {
|
||||
connect: () => void;
|
||||
disconnect: () => void;
|
||||
error: (error: Error) => void;
|
||||
datachannel: (channel: RTCDataChannel) => void;
|
||||
stream: (stream: MediaStream) => void;
|
||||
export interface Signaler {
|
||||
addIceCandidate(candidate: RTCIceCandidate): Promise<void>
|
||||
addListener(callback: (candidate: RTCIceCandidate) => void): Binnable
|
||||
addOfferListener(callback: (offer: RTCSessionDescriptionInit) => void): Binnable
|
||||
addAnswerListener(callback: (answer: RTCSessionDescriptionInit) => void): Binnable
|
||||
setOffer(offer: RTCSessionDescriptionInit): Promise<void>
|
||||
setAnswer(answer: RTCSessionDescriptionInit): Promise<void>
|
||||
}
|
||||
|
||||
39
src/webrtc-context.ts
Normal file
39
src/webrtc-context.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
import { Signaler } from './types'
|
||||
|
||||
const DEFAULT_RTC_CONFIGURATION: RTCConfiguration = {
|
||||
iceServers: [
|
||||
{
|
||||
urls: 'stun:stun.relay.metered.ca:80',
|
||||
},
|
||||
{
|
||||
urls: 'turn:standard.relay.metered.ca:80',
|
||||
username: 'c53a9c971da5e6f3bc959d8d',
|
||||
credential: 'QaccPqtPPaxyokXp',
|
||||
},
|
||||
{
|
||||
urls: 'turn:standard.relay.metered.ca:80?transport=tcp',
|
||||
username: 'c53a9c971da5e6f3bc959d8d',
|
||||
credential: 'QaccPqtPPaxyokXp',
|
||||
},
|
||||
{
|
||||
urls: 'turn:standard.relay.metered.ca:443',
|
||||
username: 'c53a9c971da5e6f3bc959d8d',
|
||||
credential: 'QaccPqtPPaxyokXp',
|
||||
},
|
||||
{
|
||||
urls: 'turns:standard.relay.metered.ca:443?transport=tcp',
|
||||
username: 'c53a9c971da5e6f3bc959d8d',
|
||||
credential: 'QaccPqtPPaxyokXp',
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
export class WebRTCContext {
|
||||
constructor(
|
||||
private readonly config?: RTCConfiguration
|
||||
) {}
|
||||
|
||||
createPeerConnection(): RTCPeerConnection {
|
||||
return new RTCPeerConnection(this.config || DEFAULT_RTC_CONFIGURATION)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user