mirror of
https://github.com/xtr-dev/rondevu-client.git
synced 2025-12-10 10:53:24 +00:00
Compare commits
32 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| a3b4dfa15f | |||
| 5c38f8f36c | |||
| 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 |
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)
|
||||||
884
README.md
884
README.md
@@ -2,9 +2,9 @@
|
|||||||
|
|
||||||
[](https://www.npmjs.com/package/@xtr-dev/rondevu-client)
|
[](https://www.npmjs.com/package/@xtr-dev/rondevu-client)
|
||||||
|
|
||||||
🌐 **Topic-based peer discovery and WebRTC signaling client**
|
🌐 **Simple, high-level WebRTC peer-to-peer connections**
|
||||||
|
|
||||||
TypeScript/JavaScript client for Rondevu, providing topic-based peer discovery, stateless authentication, and complete WebRTC signaling with trickle ICE support.
|
TypeScript/JavaScript client for Rondevu, providing easy-to-use WebRTC connections with automatic signaling, username-based discovery, and built-in reconnection support.
|
||||||
|
|
||||||
**Related repositories:**
|
**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-client](https://github.com/xtr-dev/rondevu-client) - TypeScript client library ([npm](https://www.npmjs.com/package/@xtr-dev/rondevu-client))
|
||||||
@@ -15,15 +15,16 @@ TypeScript/JavaScript client for Rondevu, providing topic-based peer discovery,
|
|||||||
|
|
||||||
## Features
|
## Features
|
||||||
|
|
||||||
- **Topic-Based Discovery**: Find peers by topics (e.g., torrent infohashes)
|
- **High-Level Wrappers**: ServiceHost and ServiceClient eliminate WebRTC boilerplate
|
||||||
- **Stateless Authentication**: No server-side sessions, portable credentials
|
- **Username-Based Discovery**: Connect to peers by username, not complex offer/answer exchange
|
||||||
- **Protected Connections**: Optional secret-protected offers for access control
|
- **Semver-Compatible Matching**: Requesting chat@1.0.0 matches any compatible 1.x.x version
|
||||||
- **Bloom Filters**: Efficient peer exclusion for repeated discoveries
|
- **Privacy-First Design**: Services are hidden by default - no enumeration possible
|
||||||
- **Multi-Offer Management**: Create and manage multiple offers per peer
|
- **Automatic Reconnection**: Built-in retry logic with exponential backoff
|
||||||
- **Complete WebRTC Signaling**: Full offer/answer and ICE candidate exchange
|
- **Message Queuing**: Messages sent while disconnected are queued and flushed on reconnect
|
||||||
- **Trickle ICE**: Send ICE candidates as they're discovered (faster connections)
|
- **Cryptographic Username Claiming**: Secure ownership with Ed25519 signatures
|
||||||
- **State Machine**: Clean state-based connection lifecycle
|
- **Service Publishing**: Package-style naming (chat.app@1.0.0) with multiple simultaneous offers
|
||||||
- **TypeScript**: Full type safety and autocomplete
|
- **TypeScript**: Full type safety and autocomplete
|
||||||
|
- **Configurable Polling**: Exponential backoff with jitter to reduce server load
|
||||||
|
|
||||||
## Install
|
## Install
|
||||||
|
|
||||||
@@ -33,243 +34,273 @@ npm install @xtr-dev/rondevu-client
|
|||||||
|
|
||||||
## Quick Start
|
## Quick Start
|
||||||
|
|
||||||
### Creating an Offer (Peer A)
|
### Hosting a Service (Alice)
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
import { Rondevu } from '@xtr-dev/rondevu-client';
|
import { RondevuService, ServiceHost } from '@xtr-dev/rondevu-client'
|
||||||
|
|
||||||
// Initialize client and register
|
// Step 1: Create and initialize service
|
||||||
const client = new Rondevu({ baseUrl: 'https://api.ronde.vu' });
|
const service = new RondevuService({
|
||||||
await client.register();
|
apiUrl: 'https://api.ronde.vu',
|
||||||
|
username: 'alice'
|
||||||
|
})
|
||||||
|
|
||||||
// Create peer connection
|
await service.initialize() // Generates keypair
|
||||||
const peer = client.createPeer();
|
await service.claimUsername() // Claims username with signature
|
||||||
|
|
||||||
// Set up event listeners
|
// Step 2: Create ServiceHost
|
||||||
peer.on('state', (state) => {
|
const host = new ServiceHost({
|
||||||
console.log('Peer state:', state);
|
service: 'chat.app@1.0.0',
|
||||||
// States: idle → creating-offer → waiting-for-answer → exchanging-ice → connected
|
rondevuService: service,
|
||||||
});
|
maxPeers: 5, // Accept up to 5 connections
|
||||||
|
ttl: 300000 // 5 minutes
|
||||||
|
})
|
||||||
|
|
||||||
peer.on('connected', () => {
|
// Step 3: Listen for incoming connections
|
||||||
console.log('✅ Connected to peer!');
|
host.events.on('connection', (connection) => {
|
||||||
});
|
console.log('✅ New connection!')
|
||||||
|
|
||||||
peer.on('datachannel', (channel) => {
|
connection.events.on('message', (msg) => {
|
||||||
console.log('📡 Data channel ready');
|
console.log('📨 Received:', msg)
|
||||||
|
connection.sendMessage('Hello from Alice!')
|
||||||
|
})
|
||||||
|
|
||||||
channel.addEventListener('message', (event) => {
|
connection.events.on('state-change', (state) => {
|
||||||
console.log('📥 Received:', event.data);
|
console.log('Connection state:', state)
|
||||||
});
|
})
|
||||||
|
})
|
||||||
|
|
||||||
channel.addEventListener('open', () => {
|
host.events.on('error', (error) => {
|
||||||
channel.send('Hello from peer A!');
|
console.error('Host error:', error)
|
||||||
});
|
})
|
||||||
});
|
|
||||||
|
|
||||||
// Create offer and advertise on topics
|
// Step 4: Start hosting
|
||||||
const offerId = await peer.createOffer({
|
await host.start()
|
||||||
topics: ['my-app', 'room-123'],
|
console.log('Service is now live! Others can connect to @alice')
|
||||||
ttl: 300000, // 5 minutes
|
|
||||||
secret: 'my-secret-password' // Optional: protect offer (max 128 chars)
|
|
||||||
});
|
|
||||||
|
|
||||||
console.log('Offer created:', offerId);
|
// Later: stop hosting
|
||||||
console.log('Share these topics with peers:', ['my-app', 'room-123']);
|
host.dispose()
|
||||||
```
|
```
|
||||||
|
|
||||||
### Answering an Offer (Peer B)
|
### Connecting to a Service (Bob)
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
import { Rondevu } from '@xtr-dev/rondevu-client';
|
import { RondevuService, ServiceClient } from '@xtr-dev/rondevu-client'
|
||||||
|
|
||||||
// Initialize client and register
|
// Step 1: Create and initialize service
|
||||||
const client = new Rondevu({ baseUrl: 'https://api.ronde.vu' });
|
const service = new RondevuService({
|
||||||
await client.register();
|
apiUrl: 'https://api.ronde.vu',
|
||||||
|
username: 'bob'
|
||||||
|
})
|
||||||
|
|
||||||
// Discover offers by topic
|
await service.initialize()
|
||||||
const offers = await client.offers.findByTopic('my-app', { limit: 10 });
|
await service.claimUsername()
|
||||||
|
|
||||||
if (offers.length > 0) {
|
// Step 2: Create ServiceClient
|
||||||
const offer = offers[0];
|
const client = new ServiceClient({
|
||||||
|
username: 'alice', // Connect to Alice
|
||||||
|
serviceFqn: 'chat.app@1.0.0',
|
||||||
|
rondevuService: service,
|
||||||
|
autoReconnect: true,
|
||||||
|
maxReconnectAttempts: 5
|
||||||
|
})
|
||||||
|
|
||||||
// Create peer connection
|
// Step 3: Listen for connection events
|
||||||
const peer = client.createPeer();
|
client.events.on('connected', (connection) => {
|
||||||
|
console.log('✅ Connected to Alice!')
|
||||||
|
|
||||||
// Set up event listeners
|
connection.events.on('message', (msg) => {
|
||||||
peer.on('state', (state) => {
|
console.log('📨 Received:', msg)
|
||||||
console.log('Peer state:', state);
|
})
|
||||||
// States: idle → answering → exchanging-ice → connected
|
|
||||||
});
|
|
||||||
|
|
||||||
peer.on('connected', () => {
|
// Send a message
|
||||||
console.log('✅ Connected!');
|
connection.sendMessage('Hello from Bob!')
|
||||||
});
|
})
|
||||||
|
|
||||||
peer.on('datachannel', (channel) => {
|
client.events.on('disconnected', () => {
|
||||||
console.log('📡 Data channel ready');
|
console.log('🔌 Disconnected')
|
||||||
|
})
|
||||||
|
|
||||||
channel.addEventListener('message', (event) => {
|
client.events.on('reconnecting', ({ attempt, maxAttempts }) => {
|
||||||
console.log('📥 Received:', event.data);
|
console.log(`🔄 Reconnecting (${attempt}/${maxAttempts})...`)
|
||||||
});
|
})
|
||||||
|
|
||||||
channel.addEventListener('open', () => {
|
client.events.on('error', (error) => {
|
||||||
channel.send('Hello from peer B!');
|
console.error('❌ Error:', error)
|
||||||
});
|
})
|
||||||
});
|
|
||||||
|
|
||||||
peer.on('failed', (error) => {
|
// Step 4: Connect
|
||||||
console.error('❌ Connection failed:', error);
|
await client.connect()
|
||||||
});
|
|
||||||
|
|
||||||
// Answer the offer
|
// Later: disconnect
|
||||||
await peer.answer(offer.id, offer.sdp, {
|
client.dispose()
|
||||||
topics: offer.topics,
|
```
|
||||||
secret: 'my-secret-password' // Required if offer.hasSecret is true
|
|
||||||
});
|
## 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
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
## Protected Offers
|
This is handled automatically - no configuration needed.
|
||||||
|
|
||||||
You can protect offers with a secret to control who can answer them. This is useful for private rooms or invite-only connections.
|
### WebRTC Configuration
|
||||||
|
|
||||||
### Creating a Protected Offer
|
Provide custom STUN/TURN servers:
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
const offerId = await peer.createOffer({
|
const host = new ServiceHost({
|
||||||
topics: ['private-room'],
|
service: 'chat.app@1.0.0',
|
||||||
secret: 'my-secret-password' // Max 128 characters
|
rondevuService: service,
|
||||||
});
|
rtcConfiguration: {
|
||||||
|
|
||||||
// Share the secret with authorized peers through a secure channel
|
|
||||||
```
|
|
||||||
|
|
||||||
### Answering a Protected Offer
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
const offers = await client.offers.findByTopic('private-room');
|
|
||||||
|
|
||||||
// Check if offer requires a secret
|
|
||||||
if (offers[0].hasSecret) {
|
|
||||||
console.log('This offer requires a secret');
|
|
||||||
}
|
|
||||||
|
|
||||||
// Provide the secret when answering
|
|
||||||
await peer.answer(offers[0].id, offers[0].sdp, {
|
|
||||||
topics: offers[0].topics,
|
|
||||||
secret: 'my-secret-password' // Must match the offer's secret
|
|
||||||
});
|
|
||||||
```
|
|
||||||
|
|
||||||
**Notes:**
|
|
||||||
- The actual secret is never exposed in public API responses - only a `hasSecret` boolean flag
|
|
||||||
- Answerers must provide the correct secret, or the answer will be rejected
|
|
||||||
- Secrets are limited to 128 characters
|
|
||||||
- Use this for access control, not for cryptographic security (use end-to-end encryption for that)
|
|
||||||
|
|
||||||
## Connection Lifecycle
|
|
||||||
|
|
||||||
The `RondevuPeer` uses a state machine for connection management:
|
|
||||||
|
|
||||||
### Offerer States
|
|
||||||
1. **idle** - Initial state
|
|
||||||
2. **creating-offer** - Creating WebRTC offer
|
|
||||||
3. **waiting-for-answer** - Polling for answer from peer
|
|
||||||
4. **exchanging-ice** - Exchanging ICE candidates
|
|
||||||
5. **connected** - Successfully connected
|
|
||||||
6. **failed** - Connection failed
|
|
||||||
7. **closed** - Connection closed
|
|
||||||
|
|
||||||
### Answerer States
|
|
||||||
1. **idle** - Initial state
|
|
||||||
2. **answering** - Creating WebRTC answer
|
|
||||||
3. **exchanging-ice** - Exchanging ICE candidates
|
|
||||||
4. **connected** - Successfully connected
|
|
||||||
5. **failed** - Connection failed
|
|
||||||
6. **closed** - Connection closed
|
|
||||||
|
|
||||||
### State Events
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
peer.on('state', (stateName) => {
|
|
||||||
console.log('Current state:', stateName);
|
|
||||||
});
|
|
||||||
|
|
||||||
peer.on('connected', () => {
|
|
||||||
// Connection established successfully
|
|
||||||
});
|
|
||||||
|
|
||||||
peer.on('disconnected', () => {
|
|
||||||
// Connection lost or closed
|
|
||||||
});
|
|
||||||
|
|
||||||
peer.on('failed', (error) => {
|
|
||||||
// Connection failed
|
|
||||||
console.error('Connection error:', error);
|
|
||||||
});
|
|
||||||
|
|
||||||
peer.on('datachannel', (channel) => {
|
|
||||||
// Data channel is ready (use channel.addEventListener)
|
|
||||||
});
|
|
||||||
|
|
||||||
peer.on('track', (event) => {
|
|
||||||
// Media track received (for audio/video streaming)
|
|
||||||
const stream = event.streams[0];
|
|
||||||
videoElement.srcObject = stream;
|
|
||||||
});
|
|
||||||
```
|
|
||||||
|
|
||||||
## Trickle ICE
|
|
||||||
|
|
||||||
This library implements **trickle ICE** for faster connection establishment:
|
|
||||||
|
|
||||||
- ICE candidates are sent to the server as they're discovered
|
|
||||||
- No waiting for all candidates before sending offer/answer
|
|
||||||
- Connections establish much faster (milliseconds vs seconds)
|
|
||||||
- Proper event listener cleanup to prevent memory leaks
|
|
||||||
|
|
||||||
## Adding Media Tracks
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
// Get user's camera/microphone
|
|
||||||
const stream = await navigator.mediaDevices.getUserMedia({
|
|
||||||
video: true,
|
|
||||||
audio: true
|
|
||||||
});
|
|
||||||
|
|
||||||
// Add tracks to peer connection
|
|
||||||
stream.getTracks().forEach(track => {
|
|
||||||
peer.addTrack(track, stream);
|
|
||||||
});
|
|
||||||
```
|
|
||||||
|
|
||||||
## Peer Properties
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
// Get current state name
|
|
||||||
console.log(peer.stateName); // 'idle', 'creating-offer', 'connected', etc.
|
|
||||||
|
|
||||||
// Get connection state
|
|
||||||
console.log(peer.connectionState); // RTCPeerConnectionState
|
|
||||||
|
|
||||||
// Get offer ID (after creating offer or answering)
|
|
||||||
console.log(peer.offerId);
|
|
||||||
|
|
||||||
// Get role
|
|
||||||
console.log(peer.role); // 'offerer' or 'answerer'
|
|
||||||
```
|
|
||||||
|
|
||||||
## Closing a Connection
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
await peer.close();
|
|
||||||
```
|
|
||||||
|
|
||||||
## Custom RTCConfiguration
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
const peer = client.createPeer({
|
|
||||||
iceServers: [
|
iceServers: [
|
||||||
{ urls: 'stun:stun.l.google.com:19302' },
|
{ urls: 'stun:stun.l.google.com:19302' },
|
||||||
{
|
{
|
||||||
@@ -277,290 +308,126 @@ const peer = client.createPeer({
|
|||||||
username: 'user',
|
username: 'user',
|
||||||
credential: 'pass'
|
credential: 'pass'
|
||||||
}
|
}
|
||||||
],
|
]
|
||||||
iceTransportPolicy: 'relay' // Force TURN relay (useful for testing)
|
}
|
||||||
});
|
})
|
||||||
```
|
```
|
||||||
|
|
||||||
## Timeouts
|
## Username Rules
|
||||||
|
|
||||||
Configure connection timeouts:
|
- **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
|
```typescript
|
||||||
await peer.createOffer({
|
// Save keypair to localStorage
|
||||||
topics: ['my-topic'],
|
const service = new RondevuService({
|
||||||
timeouts: {
|
apiUrl: 'https://api.ronde.vu',
|
||||||
iceGathering: 10000, // ICE gathering timeout (10s)
|
username: 'alice'
|
||||||
waitingForAnswer: 30000, // Waiting for answer timeout (30s)
|
})
|
||||||
creatingAnswer: 10000, // Creating answer timeout (10s)
|
|
||||||
iceConnection: 30000 // ICE connection timeout (30s)
|
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
|
||||||
```
|
```
|
||||||
|
|
||||||
## Platform-Specific Setup
|
### Message Queue Example
|
||||||
|
|
||||||
### Node.js 18+ (with native fetch)
|
```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.
|
Works out of the box - no additional setup needed.
|
||||||
|
|
||||||
### Node.js < 18 (without native fetch)
|
### Node.js 18+
|
||||||
|
Native fetch is available, but WebRTC requires polyfills:
|
||||||
Install node-fetch and provide it to the client:
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
npm install node-fetch
|
npm install wrtc
|
||||||
```
|
```
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
import { Rondevu } from '@xtr-dev/rondevu-client';
|
import { WebRTCContext } from '@xtr-dev/rondevu-client'
|
||||||
import fetch from 'node-fetch';
|
import { RTCPeerConnection, RTCSessionDescription, RTCIceCandidate } from 'wrtc'
|
||||||
|
|
||||||
const client = new Rondevu({
|
// Configure WebRTC context
|
||||||
baseUrl: 'https://api.ronde.vu',
|
const context = new WebRTCContext({
|
||||||
fetch: fetch as any
|
|
||||||
});
|
|
||||||
```
|
|
||||||
|
|
||||||
### Node.js with WebRTC (wrtc)
|
|
||||||
|
|
||||||
For WebRTC functionality in Node.js, you need to provide WebRTC polyfills since Node.js doesn't have native WebRTC support:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
npm install wrtc node-fetch
|
|
||||||
```
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
import { Rondevu } from '@xtr-dev/rondevu-client';
|
|
||||||
import fetch from 'node-fetch';
|
|
||||||
import { RTCPeerConnection, RTCSessionDescription, RTCIceCandidate } from 'wrtc';
|
|
||||||
|
|
||||||
const client = new Rondevu({
|
|
||||||
baseUrl: 'https://api.ronde.vu',
|
|
||||||
fetch: fetch as any,
|
|
||||||
RTCPeerConnection,
|
RTCPeerConnection,
|
||||||
RTCSessionDescription,
|
RTCSessionDescription,
|
||||||
RTCIceCandidate
|
RTCIceCandidate
|
||||||
});
|
} as any)
|
||||||
|
|
||||||
// Now you can use WebRTC features
|
|
||||||
await client.register();
|
|
||||||
const peer = client.createPeer({
|
|
||||||
iceServers: [
|
|
||||||
{ urls: 'stun:stun.l.google.com:19302' }
|
|
||||||
]
|
|
||||||
});
|
|
||||||
|
|
||||||
// Create offers, answer, etc.
|
|
||||||
const offerId = await peer.createOffer({
|
|
||||||
topics: ['my-topic']
|
|
||||||
});
|
|
||||||
```
|
|
||||||
|
|
||||||
**Note:** The `wrtc` package provides WebRTC bindings for Node.js. Alternative packages like `node-webrtc` can also be used - just pass their implementations to the Rondevu constructor.
|
|
||||||
|
|
||||||
### Deno
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
import { Rondevu } from 'npm:@xtr-dev/rondevu-client';
|
|
||||||
|
|
||||||
const client = new Rondevu({
|
|
||||||
baseUrl: 'https://api.ronde.vu'
|
|
||||||
});
|
|
||||||
```
|
|
||||||
|
|
||||||
### Bun
|
|
||||||
|
|
||||||
Works out of the box - no additional setup needed.
|
|
||||||
|
|
||||||
### Cloudflare Workers
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
import { Rondevu } from '@xtr-dev/rondevu-client';
|
|
||||||
|
|
||||||
export default {
|
|
||||||
async fetch(request: Request, env: Env) {
|
|
||||||
const client = new Rondevu({
|
|
||||||
baseUrl: 'https://api.ronde.vu'
|
|
||||||
});
|
|
||||||
|
|
||||||
const creds = await client.register();
|
|
||||||
return new Response(JSON.stringify(creds));
|
|
||||||
}
|
|
||||||
};
|
|
||||||
```
|
|
||||||
|
|
||||||
## Low-Level API Usage
|
|
||||||
|
|
||||||
For direct control over the signaling process without WebRTC:
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
import { Rondevu, BloomFilter } from '@xtr-dev/rondevu-client';
|
|
||||||
|
|
||||||
const client = new Rondevu({ baseUrl: 'https://api.ronde.vu' });
|
|
||||||
|
|
||||||
// Register and get credentials
|
|
||||||
const creds = await client.register();
|
|
||||||
console.log('Peer ID:', creds.peerId);
|
|
||||||
|
|
||||||
// Save credentials for later use
|
|
||||||
localStorage.setItem('rondevu-creds', JSON.stringify(creds));
|
|
||||||
|
|
||||||
// Create offer with topics
|
|
||||||
const offers = await client.offers.create([{
|
|
||||||
sdp: 'v=0...', // Your WebRTC offer SDP
|
|
||||||
topics: ['movie-xyz', 'hd-content'],
|
|
||||||
ttl: 300000, // 5 minutes
|
|
||||||
secret: 'my-secret-password' // Optional: protect offer (max 128 chars)
|
|
||||||
}]);
|
|
||||||
|
|
||||||
// Discover peers by topic
|
|
||||||
const discovered = await client.offers.findByTopic('movie-xyz', {
|
|
||||||
limit: 50
|
|
||||||
});
|
|
||||||
|
|
||||||
console.log(`Found ${discovered.length} peers`);
|
|
||||||
|
|
||||||
// Use bloom filter to exclude known peers
|
|
||||||
const knownPeers = new Set(['peer-id-1', 'peer-id-2']);
|
|
||||||
const bloom = new BloomFilter(1024, 3);
|
|
||||||
knownPeers.forEach(id => bloom.add(id));
|
|
||||||
|
|
||||||
const newPeers = await client.offers.findByTopic('movie-xyz', {
|
|
||||||
bloomFilter: bloom.toBytes(),
|
|
||||||
limit: 50
|
|
||||||
});
|
|
||||||
```
|
|
||||||
|
|
||||||
## API Reference
|
|
||||||
|
|
||||||
### Authentication
|
|
||||||
|
|
||||||
#### `client.register()`
|
|
||||||
Register a new peer and receive credentials.
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
const creds = await client.register();
|
|
||||||
// { peerId: '...', secret: '...' }
|
|
||||||
```
|
|
||||||
|
|
||||||
### Topics
|
|
||||||
|
|
||||||
#### `client.offers.getTopics(options?)`
|
|
||||||
List all topics with active peer counts (paginated).
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
const result = await client.offers.getTopics({
|
|
||||||
limit: 50,
|
|
||||||
offset: 0
|
|
||||||
});
|
|
||||||
|
|
||||||
// {
|
|
||||||
// topics: [
|
|
||||||
// { topic: 'movie-xyz', activePeers: 42 },
|
|
||||||
// { topic: 'torrent-abc', activePeers: 15 }
|
|
||||||
// ],
|
|
||||||
// total: 123,
|
|
||||||
// limit: 50,
|
|
||||||
// offset: 0
|
|
||||||
// }
|
|
||||||
```
|
|
||||||
|
|
||||||
### Offers
|
|
||||||
|
|
||||||
#### `client.offers.create(offers)`
|
|
||||||
Create one or more offers with topics.
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
const offers = await client.offers.create([
|
|
||||||
{
|
|
||||||
sdp: 'v=0...',
|
|
||||||
topics: ['topic-1', 'topic-2'],
|
|
||||||
ttl: 300000, // optional, default 5 minutes
|
|
||||||
secret: 'my-secret-password' // optional, max 128 chars
|
|
||||||
}
|
|
||||||
]);
|
|
||||||
```
|
|
||||||
|
|
||||||
#### `client.offers.findByTopic(topic, options?)`
|
|
||||||
Find offers by topic with optional bloom filter.
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
const offers = await client.offers.findByTopic('movie-xyz', {
|
|
||||||
limit: 50,
|
|
||||||
bloomFilter: bloomBytes // optional
|
|
||||||
});
|
|
||||||
```
|
|
||||||
|
|
||||||
#### `client.offers.getMine()`
|
|
||||||
Get all offers owned by the authenticated peer.
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
const myOffers = await client.offers.getMine();
|
|
||||||
```
|
|
||||||
|
|
||||||
#### `client.offers.delete(offerId)`
|
|
||||||
Delete a specific offer.
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
await client.offers.delete(offerId);
|
|
||||||
```
|
|
||||||
|
|
||||||
#### `client.offers.answer(offerId, sdp, secret?)`
|
|
||||||
Answer an offer (locks it to answerer).
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
await client.offers.answer(offerId, answerSdp, 'my-secret-password');
|
|
||||||
```
|
|
||||||
|
|
||||||
**Parameters:**
|
|
||||||
- `offerId`: The offer ID to answer
|
|
||||||
- `sdp`: The WebRTC answer SDP
|
|
||||||
- `secret` (optional): Required if the offer has `hasSecret: true`
|
|
||||||
|
|
||||||
#### `client.offers.getAnswers()`
|
|
||||||
Poll for answers to your offers.
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
const answers = await client.offers.getAnswers();
|
|
||||||
```
|
|
||||||
|
|
||||||
### ICE Candidates
|
|
||||||
|
|
||||||
#### `client.offers.addIceCandidates(offerId, candidates)`
|
|
||||||
Post ICE candidates for an offer.
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
await client.offers.addIceCandidates(offerId, [
|
|
||||||
{ candidate: 'candidate:1 1 UDP...', sdpMid: '0', sdpMLineIndex: 0 }
|
|
||||||
]);
|
|
||||||
```
|
|
||||||
|
|
||||||
#### `client.offers.getIceCandidates(offerId, since?)`
|
|
||||||
Get ICE candidates from the other peer.
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
const candidates = await client.offers.getIceCandidates(offerId, since);
|
|
||||||
```
|
|
||||||
|
|
||||||
### Bloom Filter
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
import { BloomFilter } from '@xtr-dev/rondevu-client';
|
|
||||||
|
|
||||||
// Create filter: size=1024 bits, hash=3 functions
|
|
||||||
const bloom = new BloomFilter(1024, 3);
|
|
||||||
|
|
||||||
// Add items
|
|
||||||
bloom.add('peer-id-1');
|
|
||||||
bloom.add('peer-id-2');
|
|
||||||
|
|
||||||
// Test membership
|
|
||||||
bloom.test('peer-id-1'); // true (probably)
|
|
||||||
bloom.test('unknown'); // false (definitely)
|
|
||||||
|
|
||||||
// Export for API
|
|
||||||
const bytes = bloom.toBytes();
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## TypeScript
|
## TypeScript
|
||||||
@@ -569,54 +436,21 @@ All types are exported:
|
|||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
import type {
|
import type {
|
||||||
|
RondevuServiceOptions,
|
||||||
|
ServiceHostOptions,
|
||||||
|
ServiceHostEvents,
|
||||||
|
ServiceClientOptions,
|
||||||
|
ServiceClientEvents,
|
||||||
|
ConnectionInterface,
|
||||||
|
ConnectionEvents,
|
||||||
|
ConnectionStates,
|
||||||
|
Message,
|
||||||
|
QueueMessageOptions,
|
||||||
|
Signaler,
|
||||||
|
PollingConfig,
|
||||||
Credentials,
|
Credentials,
|
||||||
Offer,
|
Keypair
|
||||||
CreateOfferRequest,
|
} from '@xtr-dev/rondevu-client'
|
||||||
TopicInfo,
|
|
||||||
IceCandidate,
|
|
||||||
FetchFunction,
|
|
||||||
RondevuOptions,
|
|
||||||
PeerOptions,
|
|
||||||
PeerEvents,
|
|
||||||
PeerTimeouts
|
|
||||||
} from '@xtr-dev/rondevu-client';
|
|
||||||
```
|
|
||||||
|
|
||||||
## Environment Compatibility
|
|
||||||
|
|
||||||
The client library is designed to work across different JavaScript runtimes:
|
|
||||||
|
|
||||||
| Environment | Native Fetch | Native WebRTC | Polyfills Needed |
|
|
||||||
|-------------|--------------|---------------|------------------|
|
|
||||||
| Modern Browsers | ✅ Yes | ✅ Yes | ❌ None |
|
|
||||||
| Node.js 18+ | ✅ Yes | ❌ No | ✅ WebRTC (wrtc) |
|
|
||||||
| Node.js < 18 | ❌ No | ❌ No | ✅ Fetch + WebRTC |
|
|
||||||
| Deno | ✅ Yes | ⚠️ Partial | ❌ None (signaling only) |
|
|
||||||
| Bun | ✅ Yes | ❌ No | ✅ WebRTC (wrtc) |
|
|
||||||
| Cloudflare Workers | ✅ Yes | ❌ No | ❌ None (signaling only) |
|
|
||||||
|
|
||||||
**For signaling-only (no WebRTC peer connections):**
|
|
||||||
|
|
||||||
Use the low-level API with `client.offers` - no WebRTC polyfills needed.
|
|
||||||
|
|
||||||
**For full WebRTC support in Node.js:**
|
|
||||||
|
|
||||||
```bash
|
|
||||||
npm install wrtc node-fetch
|
|
||||||
```
|
|
||||||
|
|
||||||
```typescript
|
|
||||||
import { Rondevu } from '@xtr-dev/rondevu-client';
|
|
||||||
import fetch from 'node-fetch';
|
|
||||||
import { RTCPeerConnection, RTCSessionDescription, RTCIceCandidate } from 'wrtc';
|
|
||||||
|
|
||||||
const client = new Rondevu({
|
|
||||||
baseUrl: 'https://api.ronde.vu',
|
|
||||||
fetch: fetch as any,
|
|
||||||
RTCPeerConnection,
|
|
||||||
RTCSessionDescription,
|
|
||||||
RTCIceCandidate
|
|
||||||
});
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|||||||
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'],
|
||||||
|
},
|
||||||
|
]
|
||||||
2972
package-lock.json
generated
2972
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
22
package.json
22
package.json
@@ -1,13 +1,17 @@
|
|||||||
{
|
{
|
||||||
"name": "@xtr-dev/rondevu-client",
|
"name": "@xtr-dev/rondevu-client",
|
||||||
"version": "0.7.9",
|
"version": "0.13.0",
|
||||||
"description": "TypeScript client for Rondevu topic-based peer discovery and signaling server",
|
"description": "TypeScript client for Rondevu with durable WebRTC connections, automatic reconnection, and message queuing",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "dist/index.js",
|
"main": "dist/index.js",
|
||||||
"types": "dist/index.d.ts",
|
"types": "dist/index.d.ts",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"build": "tsc",
|
"build": "tsc",
|
||||||
"typecheck": "tsc --noEmit",
|
"typecheck": "tsc --noEmit",
|
||||||
|
"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"
|
"prepublishOnly": "npm run build"
|
||||||
},
|
},
|
||||||
"keywords": [
|
"keywords": [
|
||||||
@@ -20,13 +24,23 @@
|
|||||||
"author": "",
|
"author": "",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"devDependencies": {
|
"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": [
|
"files": [
|
||||||
"dist",
|
"dist",
|
||||||
"README.md"
|
"README.md"
|
||||||
],
|
],
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@xtr-dev/rondevu-client": "^0.5.1"
|
"@noble/ed25519": "^3.0.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
458
src/api.ts
Normal file
458
src/api.ts
Normal file
@@ -0,0 +1,458 @@
|
|||||||
|
/**
|
||||||
|
* 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 {
|
||||||
|
serviceFqn: string // Must include username: service:version@username
|
||||||
|
offers: OfferRequest[]
|
||||||
|
ttl?: number
|
||||||
|
signature: string
|
||||||
|
message: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ServiceOffer {
|
||||||
|
offerId: string
|
||||||
|
sdp: string
|
||||||
|
createdAt: number
|
||||||
|
expiresAt: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Service {
|
||||||
|
serviceId: string
|
||||||
|
offers: ServiceOffer[]
|
||||||
|
username: string
|
||||||
|
serviceFqn: string
|
||||||
|
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 specific offer from a service
|
||||||
|
*/
|
||||||
|
async postOfferAnswer(serviceFqn: string, offerId: string, sdp: string): Promise<{ success: boolean; offerId: string }> {
|
||||||
|
const response = await fetch(`${this.baseUrl}/services/${encodeURIComponent(serviceFqn)}/offers/${offerId}/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 offer: ${error.error || response.statusText}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
return await response.json()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get answer for a specific offer (offerer polls this)
|
||||||
|
*/
|
||||||
|
async getOfferAnswer(serviceFqn: string, offerId: string): Promise<{ sdp: string; offerId: string; answererId: string; answeredAt: number } | null> {
|
||||||
|
const response = await fetch(`${this.baseUrl}/services/${encodeURIComponent(serviceFqn)}/offers/${offerId}/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}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
return await response.json()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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 specific offer
|
||||||
|
*/
|
||||||
|
async addOfferIceCandidates(serviceFqn: string, offerId: string, candidates: RTCIceCandidateInit[]): Promise<{ count: number; offerId: string }> {
|
||||||
|
const response = await fetch(`${this.baseUrl}/services/${encodeURIComponent(serviceFqn)}/offers/${offerId}/ice-candidates`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
...this.getAuthHeader(),
|
||||||
|
},
|
||||||
|
body: JSON.stringify({ candidates }),
|
||||||
|
})
|
||||||
|
|
||||||
|
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 specific offer (with polling support)
|
||||||
|
*/
|
||||||
|
async getOfferIceCandidates(serviceFqn: string, offerId: string, since: number = 0): Promise<{ candidates: IceCandidate[]; offerId: string }> {
|
||||||
|
const url = new URL(`${this.baseUrl}/services/${encodeURIComponent(serviceFqn)}/offers/${offerId}/ice-candidates`)
|
||||||
|
url.searchParams.set('since', since.toString())
|
||||||
|
|
||||||
|
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
|
||||||
|
* Service FQN must include username: service:version@username
|
||||||
|
*/
|
||||||
|
async publishService(service: ServiceRequest): Promise<Service> {
|
||||||
|
const response = await fetch(`${this.baseUrl}/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 FQN (with username) - Direct lookup
|
||||||
|
* Example: chat:1.0.0@alice
|
||||||
|
*/
|
||||||
|
async getService(serviceFqn: string): Promise<{ serviceId: string; username: string; serviceFqn: string; offerId: string; sdp: string; createdAt: number; expiresAt: number }> {
|
||||||
|
const response = await fetch(`${this.baseUrl}/services/${encodeURIComponent(serviceFqn)}`, {
|
||||||
|
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()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Discover a random available service without knowing the username
|
||||||
|
* Example: chat:1.0.0 (without @username)
|
||||||
|
*/
|
||||||
|
async discoverService(serviceVersion: string): Promise<{ serviceId: string; username: string; serviceFqn: string; offerId: string; sdp: string; createdAt: number; expiresAt: number }> {
|
||||||
|
const response = await fetch(`${this.baseUrl}/services/${encodeURIComponent(serviceVersion)}`, {
|
||||||
|
headers: this.getAuthHeader(),
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
const error = await response.json().catch(() => ({ error: 'Unknown error' }))
|
||||||
|
throw new Error(`Failed to discover service: ${error.error || response.statusText}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
return await response.json()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Discover multiple available services with pagination
|
||||||
|
* Example: chat:1.0.0 (without @username)
|
||||||
|
*/
|
||||||
|
async discoverServices(serviceVersion: string, limit: number = 10, offset: number = 0): Promise<{ services: Array<{ serviceId: string; username: string; serviceFqn: string; offerId: string; sdp: string; createdAt: number; expiresAt: number }>; count: number; limit: number; offset: number }> {
|
||||||
|
const url = new URL(`${this.baseUrl}/services/${encodeURIComponent(serviceVersion)}`)
|
||||||
|
url.searchParams.set('limit', limit.toString())
|
||||||
|
url.searchParams.set('offset', offset.toString())
|
||||||
|
|
||||||
|
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 discover services: ${error.error || response.statusText}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
return await response.json()
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// ============================================
|
||||||
|
// Usernames
|
||||||
|
// ============================================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if username is available
|
||||||
|
*/
|
||||||
|
async checkUsername(username: string): Promise<{ available: boolean; publicKey?: string; claimedAt?: number; expiresAt?: number }> {
|
||||||
|
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()
|
||||||
|
}
|
||||||
|
}
|
||||||
60
src/auth.ts
60
src/auth.ts
@@ -1,60 +0,0 @@
|
|||||||
export interface Credentials {
|
|
||||||
peerId: string;
|
|
||||||
secret: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fetch-compatible function type
|
|
||||||
export type FetchFunction = (
|
|
||||||
input: RequestInfo | URL,
|
|
||||||
init?: RequestInit
|
|
||||||
) => Promise<Response>;
|
|
||||||
|
|
||||||
export class RondevuAuth {
|
|
||||||
private fetchFn: FetchFunction;
|
|
||||||
|
|
||||||
constructor(
|
|
||||||
private baseUrl: string,
|
|
||||||
fetchFn?: FetchFunction
|
|
||||||
) {
|
|
||||||
// Use provided fetch or fall back to global fetch
|
|
||||||
this.fetchFn = fetchFn || ((...args) => {
|
|
||||||
if (typeof globalThis.fetch === 'function') {
|
|
||||||
return globalThis.fetch(...args);
|
|
||||||
}
|
|
||||||
throw new Error(
|
|
||||||
'fetch is not available. Please provide a fetch implementation in the constructor options.'
|
|
||||||
);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Register a new peer and receive credentials
|
|
||||||
*/
|
|
||||||
async register(): Promise<Credentials> {
|
|
||||||
const response = await this.fetchFn(`${this.baseUrl}/register`, {
|
|
||||||
method: 'POST',
|
|
||||||
headers: {
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
},
|
|
||||||
body: JSON.stringify({}),
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!response.ok) {
|
|
||||||
const error = await response.json().catch(() => ({ error: 'Unknown error' }));
|
|
||||||
throw new Error(`Registration failed: ${error.error || response.statusText}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
const data = await response.json();
|
|
||||||
return {
|
|
||||||
peerId: data.peerId,
|
|
||||||
secret: data.secret,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Create Authorization header value
|
|
||||||
*/
|
|
||||||
static createAuthHeader(credentials: Credentials): string {
|
|
||||||
return `Bearer ${credentials.peerId}:${credentials.secret}`;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
83
src/bloom.ts
83
src/bloom.ts
@@ -1,83 +0,0 @@
|
|||||||
// Declare Buffer for Node.js compatibility
|
|
||||||
declare const Buffer: any;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Simple bloom filter implementation for peer ID exclusion
|
|
||||||
* Uses multiple hash functions for better distribution
|
|
||||||
*/
|
|
||||||
export class BloomFilter {
|
|
||||||
private bits: Uint8Array;
|
|
||||||
private size: number;
|
|
||||||
private numHashes: number;
|
|
||||||
|
|
||||||
constructor(size: number = 1024, numHashes: number = 3) {
|
|
||||||
this.size = size;
|
|
||||||
this.numHashes = numHashes;
|
|
||||||
this.bits = new Uint8Array(Math.ceil(size / 8));
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Add a peer ID to the filter
|
|
||||||
*/
|
|
||||||
add(peerId: string): void {
|
|
||||||
for (let i = 0; i < this.numHashes; i++) {
|
|
||||||
const hash = this.hash(peerId, i);
|
|
||||||
const index = hash % this.size;
|
|
||||||
const byteIndex = Math.floor(index / 8);
|
|
||||||
const bitIndex = index % 8;
|
|
||||||
this.bits[byteIndex] |= 1 << bitIndex;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Test if peer ID might be in the filter
|
|
||||||
*/
|
|
||||||
test(peerId: string): boolean {
|
|
||||||
for (let i = 0; i < this.numHashes; i++) {
|
|
||||||
const hash = this.hash(peerId, i);
|
|
||||||
const index = hash % this.size;
|
|
||||||
const byteIndex = Math.floor(index / 8);
|
|
||||||
const bitIndex = index % 8;
|
|
||||||
if (!(this.bits[byteIndex] & (1 << bitIndex))) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get raw bits for transmission
|
|
||||||
*/
|
|
||||||
toBytes(): Uint8Array {
|
|
||||||
return this.bits;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Convert to base64 for URL parameters
|
|
||||||
*/
|
|
||||||
toBase64(): string {
|
|
||||||
// Convert Uint8Array to regular array then to string
|
|
||||||
const binaryString = String.fromCharCode(...Array.from(this.bits));
|
|
||||||
// Use btoa for browser, or Buffer for Node.js
|
|
||||||
if (typeof btoa !== 'undefined') {
|
|
||||||
return btoa(binaryString);
|
|
||||||
} else if (typeof Buffer !== 'undefined') {
|
|
||||||
return Buffer.from(this.bits).toString('base64');
|
|
||||||
} else {
|
|
||||||
// Fallback: manual base64 encoding
|
|
||||||
throw new Error('No base64 encoding available');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Simple hash function (FNV-1a variant)
|
|
||||||
*/
|
|
||||||
private hash(str: string, seed: number): number {
|
|
||||||
let hash = 2166136261 ^ seed;
|
|
||||||
for (let i = 0; i < str.length; i++) {
|
|
||||||
hash ^= str.charCodeAt(i);
|
|
||||||
hash += (hash << 1) + (hash << 4) + (hash << 7) + (hash << 8) + (hash << 24);
|
|
||||||
}
|
|
||||||
return hash >>> 0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,109 +0,0 @@
|
|||||||
/**
|
|
||||||
* Type-safe EventEmitter implementation for browser and Node.js compatibility
|
|
||||||
*
|
|
||||||
* @template EventMap - A type mapping event names to their handler signatures
|
|
||||||
*
|
|
||||||
* @example
|
|
||||||
* ```typescript
|
|
||||||
* interface MyEvents {
|
|
||||||
* 'data': (value: string) => void;
|
|
||||||
* 'error': (error: Error) => void;
|
|
||||||
* 'ready': () => void;
|
|
||||||
* }
|
|
||||||
*
|
|
||||||
* class MyClass extends EventEmitter<MyEvents> {
|
|
||||||
* doSomething() {
|
|
||||||
* this.emit('data', 'hello'); // Type-safe!
|
|
||||||
* this.emit('error', new Error('oops')); // Type-safe!
|
|
||||||
* this.emit('ready'); // Type-safe!
|
|
||||||
* }
|
|
||||||
* }
|
|
||||||
*
|
|
||||||
* const instance = new MyClass();
|
|
||||||
* instance.on('data', (value) => {
|
|
||||||
* console.log(value.toUpperCase()); // 'value' is typed as string
|
|
||||||
* });
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
export class EventEmitter<EventMap extends Record<string, (...args: any[]) => void>> {
|
|
||||||
private events: Map<keyof EventMap, Set<Function>> = new Map();
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Register an event listener
|
|
||||||
*/
|
|
||||||
on<K extends keyof EventMap>(event: K, listener: EventMap[K]): 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<K extends keyof EventMap>(event: K, listener: EventMap[K]): this {
|
|
||||||
const onceWrapper = (...args: Parameters<EventMap[K]>) => {
|
|
||||||
this.off(event, onceWrapper as EventMap[K]);
|
|
||||||
listener(...args);
|
|
||||||
};
|
|
||||||
return this.on(event, onceWrapper as EventMap[K]);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Remove an event listener
|
|
||||||
*/
|
|
||||||
off<K extends keyof EventMap>(event: K, listener: EventMap[K]): 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
|
|
||||||
*/
|
|
||||||
protected emit<K extends keyof EventMap>(
|
|
||||||
event: K,
|
|
||||||
...args: Parameters<EventMap[K]>
|
|
||||||
): boolean {
|
|
||||||
const listeners = this.events.get(event);
|
|
||||||
if (!listeners || listeners.size === 0) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
listeners.forEach(listener => {
|
|
||||||
try {
|
|
||||||
(listener as EventMap[K])(...args);
|
|
||||||
} catch (err) {
|
|
||||||
console.error(`Error in ${String(event)} event listener:`, err);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Remove all listeners for an event (or all events if not specified)
|
|
||||||
*/
|
|
||||||
removeAllListeners<K extends keyof EventMap>(event?: K): this {
|
|
||||||
if (event !== undefined) {
|
|
||||||
this.events.delete(event);
|
|
||||||
} else {
|
|
||||||
this.events.clear();
|
|
||||||
}
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get listener count for an event
|
|
||||||
*/
|
|
||||||
listenerCount<K extends keyof EventMap>(event: K): number {
|
|
||||||
const listeners = this.events.get(event);
|
|
||||||
return listeners ? listeners.size : 0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
41
src/index.ts
41
src/index.ts
@@ -1,32 +1,29 @@
|
|||||||
/**
|
/**
|
||||||
* @xtr-dev/rondevu-client
|
* @xtr-dev/rondevu-client
|
||||||
* WebRTC peer signaling and discovery client with topic-based discovery
|
* WebRTC peer signaling client
|
||||||
*/
|
*/
|
||||||
|
|
||||||
// Export main client class
|
export { Rondevu } from './rondevu.js'
|
||||||
export { Rondevu } from './rondevu.js';
|
export { RondevuAPI } from './api.js'
|
||||||
export type { RondevuOptions } from './rondevu.js';
|
export { RondevuSignaler } from './rondevu-signaler.js'
|
||||||
|
|
||||||
// Export authentication
|
// Export types
|
||||||
export { RondevuAuth } from './auth.js';
|
|
||||||
export type { Credentials, FetchFunction } from './auth.js';
|
|
||||||
|
|
||||||
// Export offers API
|
|
||||||
export { RondevuOffers } from './offers.js';
|
|
||||||
export type {
|
export type {
|
||||||
CreateOfferRequest,
|
Signaler,
|
||||||
|
Binnable,
|
||||||
|
} from './types.js'
|
||||||
|
|
||||||
|
export type {
|
||||||
|
Credentials,
|
||||||
|
Keypair,
|
||||||
|
OfferRequest,
|
||||||
Offer,
|
Offer,
|
||||||
|
ServiceRequest,
|
||||||
|
Service,
|
||||||
IceCandidate,
|
IceCandidate,
|
||||||
TopicInfo
|
} from './api.js'
|
||||||
} from './offers.js';
|
|
||||||
|
|
||||||
// Export bloom filter
|
export type { RondevuOptions, PublishServiceOptions } from './rondevu.js'
|
||||||
export { BloomFilter } from './bloom.js';
|
|
||||||
|
export type { PollingConfig } from './rondevu-signaler.js'
|
||||||
|
|
||||||
// Export peer manager
|
|
||||||
export { default as RondevuPeer } from './peer/index.js';
|
|
||||||
export type {
|
|
||||||
PeerOptions,
|
|
||||||
PeerEvents,
|
|
||||||
PeerTimeouts
|
|
||||||
} from './peer/index.js';
|
|
||||||
|
|||||||
319
src/offers.ts
319
src/offers.ts
@@ -1,319 +0,0 @@
|
|||||||
import { Credentials, FetchFunction } from './auth.js';
|
|
||||||
import { RondevuAuth } from './auth.js';
|
|
||||||
|
|
||||||
// Declare Buffer for Node.js compatibility
|
|
||||||
declare const Buffer: any;
|
|
||||||
|
|
||||||
export interface CreateOfferRequest {
|
|
||||||
sdp: string;
|
|
||||||
topics: string[];
|
|
||||||
ttl?: number;
|
|
||||||
secret?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface Offer {
|
|
||||||
id: string;
|
|
||||||
peerId: string;
|
|
||||||
sdp: string;
|
|
||||||
topics: string[];
|
|
||||||
createdAt?: number;
|
|
||||||
expiresAt: number;
|
|
||||||
lastSeen: number;
|
|
||||||
secret?: string;
|
|
||||||
hasSecret?: boolean;
|
|
||||||
answererPeerId?: string;
|
|
||||||
answerSdp?: string;
|
|
||||||
answeredAt?: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface IceCandidate {
|
|
||||||
candidate: any; // Full candidate object as plain JSON - don't enforce structure
|
|
||||||
peerId: string;
|
|
||||||
role: 'offerer' | 'answerer';
|
|
||||||
createdAt: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface TopicInfo {
|
|
||||||
topic: string;
|
|
||||||
activePeers: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export class RondevuOffers {
|
|
||||||
private fetchFn: FetchFunction;
|
|
||||||
|
|
||||||
constructor(
|
|
||||||
private baseUrl: string,
|
|
||||||
private credentials: Credentials,
|
|
||||||
fetchFn?: FetchFunction
|
|
||||||
) {
|
|
||||||
// Use provided fetch or fall back to global fetch
|
|
||||||
this.fetchFn = fetchFn || ((...args) => {
|
|
||||||
if (typeof globalThis.fetch === 'function') {
|
|
||||||
return globalThis.fetch(...args);
|
|
||||||
}
|
|
||||||
throw new Error(
|
|
||||||
'fetch is not available. Please provide a fetch implementation in the constructor options.'
|
|
||||||
);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Create one or more offers
|
|
||||||
*/
|
|
||||||
async create(offers: CreateOfferRequest[]): Promise<Offer[]> {
|
|
||||||
const response = await this.fetchFn(`${this.baseUrl}/offers`, {
|
|
||||||
method: 'POST',
|
|
||||||
headers: {
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
Authorization: RondevuAuth.createAuthHeader(this.credentials),
|
|
||||||
},
|
|
||||||
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}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
const data = await response.json();
|
|
||||||
return data.offers;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Find offers by topic with optional bloom filter
|
|
||||||
*/
|
|
||||||
async findByTopic(
|
|
||||||
topic: string,
|
|
||||||
options?: {
|
|
||||||
bloomFilter?: Uint8Array;
|
|
||||||
limit?: number;
|
|
||||||
}
|
|
||||||
): Promise<Offer[]> {
|
|
||||||
const params = new URLSearchParams();
|
|
||||||
|
|
||||||
if (options?.bloomFilter) {
|
|
||||||
// Convert to base64
|
|
||||||
const binaryString = String.fromCharCode(...Array.from(options.bloomFilter));
|
|
||||||
const base64 = typeof btoa !== 'undefined'
|
|
||||||
? btoa(binaryString)
|
|
||||||
: (typeof Buffer !== 'undefined' ? Buffer.from(options.bloomFilter).toString('base64') : '');
|
|
||||||
params.set('bloom', base64);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (options?.limit) {
|
|
||||||
params.set('limit', options.limit.toString());
|
|
||||||
}
|
|
||||||
|
|
||||||
const url = `${this.baseUrl}/offers/by-topic/${encodeURIComponent(topic)}${
|
|
||||||
params.toString() ? '?' + params.toString() : ''
|
|
||||||
}`;
|
|
||||||
|
|
||||||
const response = await this.fetchFn(url, {
|
|
||||||
method: 'GET',
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!response.ok) {
|
|
||||||
const error = await response.json().catch(() => ({ error: 'Unknown error' }));
|
|
||||||
throw new Error(`Failed to find offers: ${error.error || response.statusText}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
const data = await response.json();
|
|
||||||
return data.offers;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get all offers from a specific peer
|
|
||||||
*/
|
|
||||||
async getByPeerId(peerId: string): Promise<{
|
|
||||||
offers: Offer[];
|
|
||||||
topics: string[];
|
|
||||||
}> {
|
|
||||||
const response = await this.fetchFn(`${this.baseUrl}/peers/${encodeURIComponent(peerId)}/offers`, {
|
|
||||||
method: 'GET',
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!response.ok) {
|
|
||||||
const error = await response.json().catch(() => ({ error: 'Unknown error' }));
|
|
||||||
throw new Error(`Failed to get peer offers: ${error.error || response.statusText}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
return await response.json();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get topics with active peer counts (paginated)
|
|
||||||
*/
|
|
||||||
async getTopics(options?: {
|
|
||||||
limit?: number;
|
|
||||||
offset?: number;
|
|
||||||
startsWith?: string;
|
|
||||||
}): Promise<{
|
|
||||||
topics: TopicInfo[];
|
|
||||||
total: number;
|
|
||||||
limit: number;
|
|
||||||
offset: number;
|
|
||||||
startsWith?: string;
|
|
||||||
}> {
|
|
||||||
const params = new URLSearchParams();
|
|
||||||
|
|
||||||
if (options?.limit) {
|
|
||||||
params.set('limit', options.limit.toString());
|
|
||||||
}
|
|
||||||
|
|
||||||
if (options?.offset) {
|
|
||||||
params.set('offset', options.offset.toString());
|
|
||||||
}
|
|
||||||
|
|
||||||
if (options?.startsWith) {
|
|
||||||
params.set('startsWith', options.startsWith);
|
|
||||||
}
|
|
||||||
|
|
||||||
const url = `${this.baseUrl}/topics${
|
|
||||||
params.toString() ? '?' + params.toString() : ''
|
|
||||||
}`;
|
|
||||||
|
|
||||||
const response = await this.fetchFn(url, {
|
|
||||||
method: 'GET',
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!response.ok) {
|
|
||||||
const error = await response.json().catch(() => ({ error: 'Unknown error' }));
|
|
||||||
throw new Error(`Failed to get topics: ${error.error || response.statusText}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
return await response.json();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get own offers
|
|
||||||
*/
|
|
||||||
async getMine(): Promise<Offer[]> {
|
|
||||||
const response = await this.fetchFn(`${this.baseUrl}/offers/mine`, {
|
|
||||||
method: 'GET',
|
|
||||||
headers: {
|
|
||||||
Authorization: RondevuAuth.createAuthHeader(this.credentials),
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!response.ok) {
|
|
||||||
const error = await response.json().catch(() => ({ error: 'Unknown error' }));
|
|
||||||
throw new Error(`Failed to get own offers: ${error.error || response.statusText}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
const data = await response.json();
|
|
||||||
return data.offers;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Delete an offer
|
|
||||||
*/
|
|
||||||
async delete(offerId: string): Promise<void> {
|
|
||||||
const response = await this.fetchFn(`${this.baseUrl}/offers/${encodeURIComponent(offerId)}`, {
|
|
||||||
method: 'DELETE',
|
|
||||||
headers: {
|
|
||||||
Authorization: RondevuAuth.createAuthHeader(this.credentials),
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!response.ok) {
|
|
||||||
const error = await response.json().catch(() => ({ error: 'Unknown error' }));
|
|
||||||
throw new Error(`Failed to delete offer: ${error.error || response.statusText}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Answer an offer
|
|
||||||
*/
|
|
||||||
async answer(offerId: string, sdp: string, secret?: string): Promise<void> {
|
|
||||||
const response = await this.fetchFn(`${this.baseUrl}/offers/${encodeURIComponent(offerId)}/answer`, {
|
|
||||||
method: 'POST',
|
|
||||||
headers: {
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
Authorization: RondevuAuth.createAuthHeader(this.credentials),
|
|
||||||
},
|
|
||||||
body: JSON.stringify({ sdp, secret }),
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!response.ok) {
|
|
||||||
const error = await response.json().catch(() => ({ error: 'Unknown error' }));
|
|
||||||
throw new Error(`Failed to answer offer: ${error.error || response.statusText}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get answers to your offers
|
|
||||||
*/
|
|
||||||
async getAnswers(): Promise<Array<{
|
|
||||||
offerId: string;
|
|
||||||
answererId: string;
|
|
||||||
sdp: string;
|
|
||||||
answeredAt: number;
|
|
||||||
topics: string[];
|
|
||||||
}>> {
|
|
||||||
const response = await this.fetchFn(`${this.baseUrl}/offers/answers`, {
|
|
||||||
method: 'GET',
|
|
||||||
headers: {
|
|
||||||
Authorization: RondevuAuth.createAuthHeader(this.credentials),
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!response.ok) {
|
|
||||||
const error = await response.json().catch(() => ({ error: 'Unknown error' }));
|
|
||||||
throw new Error(`Failed to get answers: ${error.error || response.statusText}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
const data = await response.json();
|
|
||||||
return data.answers;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Post ICE candidates for an offer
|
|
||||||
*/
|
|
||||||
async addIceCandidates(
|
|
||||||
offerId: string,
|
|
||||||
candidates: any[]
|
|
||||||
): Promise<void> {
|
|
||||||
const response = await this.fetchFn(`${this.baseUrl}/offers/${encodeURIComponent(offerId)}/ice-candidates`, {
|
|
||||||
method: 'POST',
|
|
||||||
headers: {
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
Authorization: RondevuAuth.createAuthHeader(this.credentials),
|
|
||||||
},
|
|
||||||
body: JSON.stringify({ candidates }),
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!response.ok) {
|
|
||||||
const error = await response.json().catch(() => ({ error: 'Unknown error' }));
|
|
||||||
throw new Error(`Failed to add ICE candidates: ${error.error || response.statusText}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get ICE candidates for an offer
|
|
||||||
*/
|
|
||||||
async getIceCandidates(offerId: string, since?: number): Promise<IceCandidate[]> {
|
|
||||||
const params = new URLSearchParams();
|
|
||||||
if (since !== undefined) {
|
|
||||||
params.set('since', since.toString());
|
|
||||||
}
|
|
||||||
|
|
||||||
const url = `${this.baseUrl}/offers/${encodeURIComponent(offerId)}/ice-candidates${
|
|
||||||
params.toString() ? '?' + params.toString() : ''
|
|
||||||
}`;
|
|
||||||
|
|
||||||
const response = await this.fetchFn(url, {
|
|
||||||
method: 'GET',
|
|
||||||
headers: {
|
|
||||||
Authorization: RondevuAuth.createAuthHeader(this.credentials),
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
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 data.candidates;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,49 +0,0 @@
|
|||||||
import { PeerState } from './state.js';
|
|
||||||
import type { PeerOptions } from './types.js';
|
|
||||||
import type RondevuPeer from './index.js';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Answering an offer and sending to server
|
|
||||||
*/
|
|
||||||
export class AnsweringState extends PeerState {
|
|
||||||
constructor(peer: RondevuPeer) {
|
|
||||||
super(peer);
|
|
||||||
}
|
|
||||||
|
|
||||||
get name() { return 'answering'; }
|
|
||||||
|
|
||||||
async answer(offerId: string, offerSdp: string, options: PeerOptions): Promise<void> {
|
|
||||||
try {
|
|
||||||
this.peer.role = 'answerer';
|
|
||||||
this.peer.offerId = offerId;
|
|
||||||
|
|
||||||
// Set remote description
|
|
||||||
await this.peer.pc.setRemoteDescription({
|
|
||||||
type: 'offer',
|
|
||||||
sdp: offerSdp
|
|
||||||
});
|
|
||||||
|
|
||||||
// Create answer
|
|
||||||
const answer = await this.peer.pc.createAnswer();
|
|
||||||
|
|
||||||
// Send answer to server BEFORE setLocalDescription
|
|
||||||
// This registers us as the answerer so ICE candidates will be accepted
|
|
||||||
await this.peer.offersApi.answer(offerId, answer.sdp!, options.secret);
|
|
||||||
|
|
||||||
// Enable trickle ICE - set up handler before ICE gathering starts
|
|
||||||
this.setupIceCandidateHandler();
|
|
||||||
|
|
||||||
// Set local description - ICE gathering starts here
|
|
||||||
// Server already knows we're the answerer, so candidates will be accepted
|
|
||||||
await this.peer.pc.setLocalDescription(answer);
|
|
||||||
|
|
||||||
// Transition to exchanging ICE
|
|
||||||
const { ExchangingIceState } = await import('./exchanging-ice-state.js');
|
|
||||||
this.peer.setState(new ExchangingIceState(this.peer, offerId, options));
|
|
||||||
} catch (error) {
|
|
||||||
const { FailedState } = await import('./failed-state.js');
|
|
||||||
this.peer.setState(new FailedState(this.peer, error as Error));
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,12 +0,0 @@
|
|||||||
import { PeerState } from './state.js';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Closed state - connection has been terminated
|
|
||||||
*/
|
|
||||||
export class ClosedState extends PeerState {
|
|
||||||
get name() { return 'closed'; }
|
|
||||||
|
|
||||||
cleanup(): void {
|
|
||||||
this.peer.pc.close();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
import { PeerState } from './state.js';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Connected state - peer connection is established
|
|
||||||
*/
|
|
||||||
export class ConnectedState extends PeerState {
|
|
||||||
get name() { return 'connected'; }
|
|
||||||
|
|
||||||
cleanup(): void {
|
|
||||||
// Keep connection alive, but stop any polling
|
|
||||||
// The peer connection will handle disconnects via onconnectionstatechange
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,57 +0,0 @@
|
|||||||
import { PeerState } from './state.js';
|
|
||||||
import type { PeerOptions } from './types.js';
|
|
||||||
import type RondevuPeer from './index.js';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Creating offer and sending to server
|
|
||||||
*/
|
|
||||||
export class CreatingOfferState extends PeerState {
|
|
||||||
constructor(peer: RondevuPeer, private options: PeerOptions) {
|
|
||||||
super(peer);
|
|
||||||
}
|
|
||||||
|
|
||||||
get name() { return 'creating-offer'; }
|
|
||||||
|
|
||||||
async createOffer(options: PeerOptions): Promise<string> {
|
|
||||||
try {
|
|
||||||
this.peer.role = 'offerer';
|
|
||||||
|
|
||||||
// Create data channel if requested
|
|
||||||
if (options.createDataChannel !== false) {
|
|
||||||
const channel = this.peer.pc.createDataChannel(
|
|
||||||
options.dataChannelLabel || 'data'
|
|
||||||
);
|
|
||||||
this.peer.emitEvent('datachannel', channel);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Enable trickle ICE - set up handler before ICE gathering starts
|
|
||||||
// Handler will check this.peer.offerId before sending
|
|
||||||
this.setupIceCandidateHandler();
|
|
||||||
|
|
||||||
// Create WebRTC offer
|
|
||||||
const offer = await this.peer.pc.createOffer();
|
|
||||||
await this.peer.pc.setLocalDescription(offer); // ICE gathering starts here
|
|
||||||
|
|
||||||
// Send offer to server immediately (don't wait for ICE)
|
|
||||||
const offers = await this.peer.offersApi.create([{
|
|
||||||
sdp: offer.sdp!,
|
|
||||||
topics: options.topics,
|
|
||||||
ttl: options.ttl || 300000,
|
|
||||||
secret: options.secret
|
|
||||||
}]);
|
|
||||||
|
|
||||||
const offerId = offers[0].id;
|
|
||||||
this.peer.offerId = offerId; // Now handler can send candidates
|
|
||||||
|
|
||||||
// Transition to waiting for answer
|
|
||||||
const { WaitingForAnswerState } = await import('./waiting-for-answer-state.js');
|
|
||||||
this.peer.setState(new WaitingForAnswerState(this.peer, offerId, options));
|
|
||||||
|
|
||||||
return offerId;
|
|
||||||
} catch (error) {
|
|
||||||
const { FailedState } = await import('./failed-state.js');
|
|
||||||
this.peer.setState(new FailedState(this.peer, error as Error));
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,74 +0,0 @@
|
|||||||
import { PeerState } from './state.js';
|
|
||||||
import type { PeerOptions } from './types.js';
|
|
||||||
import type RondevuPeer from './index.js';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Exchanging ICE candidates and waiting for connection
|
|
||||||
*/
|
|
||||||
export class ExchangingIceState extends PeerState {
|
|
||||||
private pollingInterval?: ReturnType<typeof setInterval>;
|
|
||||||
private timeout?: ReturnType<typeof setTimeout>;
|
|
||||||
private lastIceTimestamp = 0;
|
|
||||||
|
|
||||||
constructor(
|
|
||||||
peer: RondevuPeer,
|
|
||||||
private offerId: string,
|
|
||||||
private options: PeerOptions
|
|
||||||
) {
|
|
||||||
super(peer);
|
|
||||||
this.startPolling();
|
|
||||||
}
|
|
||||||
|
|
||||||
get name() { return 'exchanging-ice'; }
|
|
||||||
|
|
||||||
private startPolling(): void {
|
|
||||||
const connectionTimeout = this.options.timeouts?.iceConnection || 30000;
|
|
||||||
|
|
||||||
this.timeout = setTimeout(async () => {
|
|
||||||
this.cleanup();
|
|
||||||
const { FailedState } = await import('./failed-state.js');
|
|
||||||
this.peer.setState(new FailedState(
|
|
||||||
this.peer,
|
|
||||||
new Error('ICE connection timeout')
|
|
||||||
));
|
|
||||||
}, connectionTimeout);
|
|
||||||
|
|
||||||
this.pollingInterval = setInterval(async () => {
|
|
||||||
try {
|
|
||||||
const candidates = await this.peer.offersApi.getIceCandidates(
|
|
||||||
this.offerId,
|
|
||||||
this.lastIceTimestamp
|
|
||||||
);
|
|
||||||
|
|
||||||
for (const cand of candidates) {
|
|
||||||
if (cand.candidate && cand.candidate.candidate && cand.candidate.candidate !== '') {
|
|
||||||
try {
|
|
||||||
await this.peer.pc.addIceCandidate(new this.peer.RTCIceCandidate(cand.candidate));
|
|
||||||
this.lastIceTimestamp = cand.createdAt;
|
|
||||||
} catch (err) {
|
|
||||||
console.warn('Failed to add ICE candidate:', err);
|
|
||||||
this.lastIceTimestamp = cand.createdAt;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
this.lastIceTimestamp = cand.createdAt;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (err) {
|
|
||||||
console.error('Error polling for ICE candidates:', err);
|
|
||||||
if (err instanceof Error && err.message.includes('not found')) {
|
|
||||||
this.cleanup();
|
|
||||||
const { FailedState } = await import('./failed-state.js');
|
|
||||||
this.peer.setState(new FailedState(
|
|
||||||
this.peer,
|
|
||||||
new Error('Offer expired or not found')
|
|
||||||
));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}, 1000);
|
|
||||||
}
|
|
||||||
|
|
||||||
cleanup(): void {
|
|
||||||
if (this.pollingInterval) clearInterval(this.pollingInterval);
|
|
||||||
if (this.timeout) clearTimeout(this.timeout);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
import { PeerState } from './state.js';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Failed state - connection attempt failed
|
|
||||||
*/
|
|
||||||
export class FailedState extends PeerState {
|
|
||||||
constructor(peer: any, private error: Error) {
|
|
||||||
super(peer);
|
|
||||||
peer.emitEvent('failed', error);
|
|
||||||
}
|
|
||||||
|
|
||||||
get name() { return 'failed'; }
|
|
||||||
|
|
||||||
cleanup(): void {
|
|
||||||
// Connection is failed, clean up resources
|
|
||||||
this.peer.pc.close();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
import { PeerState } from './state.js';
|
|
||||||
import type { PeerOptions } from './types.js';
|
|
||||||
|
|
||||||
export class IdleState extends PeerState {
|
|
||||||
get name() { return 'idle'; }
|
|
||||||
|
|
||||||
async createOffer(options: PeerOptions): Promise<string> {
|
|
||||||
const { CreatingOfferState } = await import('./creating-offer-state.js');
|
|
||||||
this.peer.setState(new CreatingOfferState(this.peer, options));
|
|
||||||
return this.peer.state.createOffer(options);
|
|
||||||
}
|
|
||||||
|
|
||||||
async answer(offerId: string, offerSdp: string, options: PeerOptions): Promise<void> {
|
|
||||||
const { AnsweringState } = await import('./answering-state.js');
|
|
||||||
this.peer.setState(new AnsweringState(this.peer));
|
|
||||||
return this.peer.state.answer(offerId, offerSdp, options);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,212 +0,0 @@
|
|||||||
import { RondevuOffers } from '../offers.js';
|
|
||||||
import { EventEmitter } from '../event-emitter.js';
|
|
||||||
import type { PeerOptions, PeerEvents } from './types.js';
|
|
||||||
import { PeerState } from './state.js';
|
|
||||||
import { IdleState } from './idle-state.js';
|
|
||||||
import { CreatingOfferState } from './creating-offer-state.js';
|
|
||||||
import { WaitingForAnswerState } from './waiting-for-answer-state.js';
|
|
||||||
import { AnsweringState } from './answering-state.js';
|
|
||||||
import { ExchangingIceState } from './exchanging-ice-state.js';
|
|
||||||
import { ConnectedState } from './connected-state.js';
|
|
||||||
import { FailedState } from './failed-state.js';
|
|
||||||
import { ClosedState } from './closed-state.js';
|
|
||||||
|
|
||||||
// Re-export types for external consumers
|
|
||||||
export type { PeerTimeouts, PeerOptions, PeerEvents } from './types.js';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* High-level WebRTC peer connection manager with state-based lifecycle
|
|
||||||
* Handles offer/answer exchange, ICE candidates, timeouts, and error recovery
|
|
||||||
*/
|
|
||||||
export default class RondevuPeer extends EventEmitter<PeerEvents> {
|
|
||||||
pc: RTCPeerConnection;
|
|
||||||
offersApi: RondevuOffers;
|
|
||||||
offerId?: string;
|
|
||||||
role?: 'offerer' | 'answerer';
|
|
||||||
|
|
||||||
// WebRTC polyfills for Node.js compatibility
|
|
||||||
RTCPeerConnection: typeof RTCPeerConnection;
|
|
||||||
RTCSessionDescription: typeof RTCSessionDescription;
|
|
||||||
RTCIceCandidate: typeof RTCIceCandidate;
|
|
||||||
|
|
||||||
private _state: PeerState;
|
|
||||||
|
|
||||||
// Event handler references for cleanup
|
|
||||||
private connectionStateChangeHandler?: () => void;
|
|
||||||
private dataChannelHandler?: (event: RTCDataChannelEvent) => void;
|
|
||||||
private trackHandler?: (event: RTCTrackEvent) => void;
|
|
||||||
private iceCandidateErrorHandler?: (event: Event) => void;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Current connection state name
|
|
||||||
*/
|
|
||||||
get stateName(): string {
|
|
||||||
return this._state.name;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Current state object (internal use)
|
|
||||||
*/
|
|
||||||
get state(): PeerState {
|
|
||||||
return this._state;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* RTCPeerConnection state
|
|
||||||
*/
|
|
||||||
get connectionState(): RTCPeerConnectionState {
|
|
||||||
return this.pc.connectionState;
|
|
||||||
}
|
|
||||||
|
|
||||||
constructor(
|
|
||||||
offersApi: RondevuOffers,
|
|
||||||
rtcConfig: RTCConfiguration = {
|
|
||||||
iceServers: [
|
|
||||||
{ urls: 'stun:stun.l.google.com:19302' },
|
|
||||||
{ urls: 'stun:stun1.l.google.com:19302' }
|
|
||||||
]
|
|
||||||
},
|
|
||||||
rtcPeerConnection?: typeof RTCPeerConnection,
|
|
||||||
rtcSessionDescription?: typeof RTCSessionDescription,
|
|
||||||
rtcIceCandidate?: typeof RTCIceCandidate
|
|
||||||
) {
|
|
||||||
super();
|
|
||||||
this.offersApi = offersApi;
|
|
||||||
|
|
||||||
// Use provided polyfills or fall back to globals
|
|
||||||
this.RTCPeerConnection = rtcPeerConnection || (typeof globalThis.RTCPeerConnection !== 'undefined'
|
|
||||||
? globalThis.RTCPeerConnection
|
|
||||||
: (() => {
|
|
||||||
throw new Error('RTCPeerConnection is not available. Please provide it in the Rondevu constructor options for Node.js environments.');
|
|
||||||
}) as any);
|
|
||||||
|
|
||||||
this.RTCSessionDescription = rtcSessionDescription || (typeof globalThis.RTCSessionDescription !== 'undefined'
|
|
||||||
? globalThis.RTCSessionDescription
|
|
||||||
: (() => {
|
|
||||||
throw new Error('RTCSessionDescription is not available. Please provide it in the Rondevu constructor options for Node.js environments.');
|
|
||||||
}) as any);
|
|
||||||
|
|
||||||
this.RTCIceCandidate = rtcIceCandidate || (typeof globalThis.RTCIceCandidate !== 'undefined'
|
|
||||||
? globalThis.RTCIceCandidate
|
|
||||||
: (() => {
|
|
||||||
throw new Error('RTCIceCandidate is not available. Please provide it in the Rondevu constructor options for Node.js environments.');
|
|
||||||
}) as any);
|
|
||||||
|
|
||||||
this.pc = new this.RTCPeerConnection(rtcConfig);
|
|
||||||
this._state = new IdleState(this);
|
|
||||||
|
|
||||||
this.setupPeerConnection();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Set up peer connection event handlers
|
|
||||||
*/
|
|
||||||
private setupPeerConnection(): void {
|
|
||||||
this.connectionStateChangeHandler = () => {
|
|
||||||
switch (this.pc.connectionState) {
|
|
||||||
case 'connected':
|
|
||||||
this.setState(new ConnectedState(this));
|
|
||||||
this.emitEvent('connected');
|
|
||||||
break;
|
|
||||||
case 'disconnected':
|
|
||||||
this.emitEvent('disconnected');
|
|
||||||
break;
|
|
||||||
case 'failed':
|
|
||||||
this.setState(new FailedState(this, new Error('Connection failed')));
|
|
||||||
break;
|
|
||||||
case 'closed':
|
|
||||||
this.setState(new ClosedState(this));
|
|
||||||
this.emitEvent('disconnected');
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
this.pc.addEventListener('connectionstatechange', this.connectionStateChangeHandler);
|
|
||||||
|
|
||||||
this.dataChannelHandler = (event: RTCDataChannelEvent) => {
|
|
||||||
this.emitEvent('datachannel', event.channel);
|
|
||||||
};
|
|
||||||
this.pc.addEventListener('datachannel', this.dataChannelHandler);
|
|
||||||
|
|
||||||
this.trackHandler = (event: RTCTrackEvent) => {
|
|
||||||
this.emitEvent('track', event);
|
|
||||||
};
|
|
||||||
this.pc.addEventListener('track', this.trackHandler);
|
|
||||||
|
|
||||||
this.iceCandidateErrorHandler = (event: Event) => {
|
|
||||||
console.error('ICE candidate error:', event);
|
|
||||||
};
|
|
||||||
this.pc.addEventListener('icecandidateerror', this.iceCandidateErrorHandler);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Set new state and emit state change event
|
|
||||||
*/
|
|
||||||
setState(newState: PeerState): void {
|
|
||||||
this._state.cleanup();
|
|
||||||
this._state = newState;
|
|
||||||
this.emitEvent('state', newState.name);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Emit event (exposed for PeerState classes)
|
|
||||||
* @internal
|
|
||||||
*/
|
|
||||||
emitEvent<K extends keyof PeerEvents>(
|
|
||||||
event: K,
|
|
||||||
...args: Parameters<PeerEvents[K]>
|
|
||||||
): void {
|
|
||||||
this.emit(event, ...args);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Create an offer and advertise on topics
|
|
||||||
*/
|
|
||||||
async createOffer(options: PeerOptions): Promise<string> {
|
|
||||||
return this._state.createOffer(options);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Answer an existing offer
|
|
||||||
*/
|
|
||||||
async answer(offerId: string, offerSdp: string, options: PeerOptions): Promise<void> {
|
|
||||||
return this._state.answer(offerId, offerSdp, options);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Add a media track to the connection
|
|
||||||
*/
|
|
||||||
addTrack(track: MediaStreamTrack, ...streams: MediaStream[]): RTCRtpSender {
|
|
||||||
return this.pc.addTrack(track, ...streams);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Create a data channel for sending and receiving arbitrary data
|
|
||||||
* This should typically be called by the offerer before creating the offer
|
|
||||||
* The answerer will receive the channel via the 'datachannel' event
|
|
||||||
*/
|
|
||||||
createDataChannel(label: string, options?: RTCDataChannelInit): RTCDataChannel {
|
|
||||||
return this.pc.createDataChannel(label, options);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Close the connection and clean up
|
|
||||||
*/
|
|
||||||
async close(): Promise<void> {
|
|
||||||
// Remove RTCPeerConnection event listeners
|
|
||||||
if (this.connectionStateChangeHandler) {
|
|
||||||
this.pc.removeEventListener('connectionstatechange', this.connectionStateChangeHandler);
|
|
||||||
}
|
|
||||||
if (this.dataChannelHandler) {
|
|
||||||
this.pc.removeEventListener('datachannel', this.dataChannelHandler);
|
|
||||||
}
|
|
||||||
if (this.trackHandler) {
|
|
||||||
this.pc.removeEventListener('track', this.trackHandler);
|
|
||||||
}
|
|
||||||
if (this.iceCandidateErrorHandler) {
|
|
||||||
this.pc.removeEventListener('icecandidateerror', this.iceCandidateErrorHandler);
|
|
||||||
}
|
|
||||||
|
|
||||||
await this._state.close();
|
|
||||||
this.removeAllListeners();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,66 +0,0 @@
|
|||||||
import type { PeerOptions } from './types.js';
|
|
||||||
import type RondevuPeer from './index.js';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Base class for peer connection states
|
|
||||||
* Implements the State pattern for managing WebRTC connection lifecycle
|
|
||||||
*/
|
|
||||||
export abstract class PeerState {
|
|
||||||
protected iceCandidateHandler?: (event: RTCPeerConnectionIceEvent) => void;
|
|
||||||
|
|
||||||
constructor(protected peer: RondevuPeer) {}
|
|
||||||
|
|
||||||
abstract get name(): string;
|
|
||||||
|
|
||||||
async createOffer(options: PeerOptions): Promise<string> {
|
|
||||||
throw new Error(`Cannot create offer in ${this.name} state`);
|
|
||||||
}
|
|
||||||
|
|
||||||
async answer(offerId: string, offerSdp: string, options: PeerOptions): Promise<void> {
|
|
||||||
throw new Error(`Cannot answer in ${this.name} state`);
|
|
||||||
}
|
|
||||||
|
|
||||||
async handleAnswer(sdp: string): Promise<void> {
|
|
||||||
throw new Error(`Cannot handle answer in ${this.name} state`);
|
|
||||||
}
|
|
||||||
|
|
||||||
async handleIceCandidate(candidate: any): Promise<void> {
|
|
||||||
// ICE candidates can arrive in multiple states, so default is to add them
|
|
||||||
if (this.peer.pc.remoteDescription) {
|
|
||||||
await this.peer.pc.addIceCandidate(new this.peer.RTCIceCandidate(candidate));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Setup trickle ICE candidate handler
|
|
||||||
* Sends local ICE candidates to server as they are discovered
|
|
||||||
*/
|
|
||||||
protected setupIceCandidateHandler(): void {
|
|
||||||
this.iceCandidateHandler = async (event: RTCPeerConnectionIceEvent) => {
|
|
||||||
if (event.candidate && this.peer.offerId) {
|
|
||||||
const candidateData = event.candidate.toJSON();
|
|
||||||
if (candidateData.candidate && candidateData.candidate !== '') {
|
|
||||||
try {
|
|
||||||
await this.peer.offersApi.addIceCandidates(this.peer.offerId, [candidateData]);
|
|
||||||
} catch (err) {
|
|
||||||
console.error('Error sending ICE candidate:', err);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
this.peer.pc.addEventListener('icecandidate', this.iceCandidateHandler);
|
|
||||||
}
|
|
||||||
|
|
||||||
cleanup(): void {
|
|
||||||
// Clean up ICE candidate handler if it exists
|
|
||||||
if (this.iceCandidateHandler) {
|
|
||||||
this.peer.pc.removeEventListener('icecandidate', this.iceCandidateHandler);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async close(): Promise<void> {
|
|
||||||
this.cleanup();
|
|
||||||
const { ClosedState } = await import('./closed-state.js');
|
|
||||||
this.peer.setState(new ClosedState(this.peer));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,45 +0,0 @@
|
|||||||
/**
|
|
||||||
* Timeout configurations for different connection phases
|
|
||||||
*/
|
|
||||||
export interface PeerTimeouts {
|
|
||||||
/** Timeout for ICE gathering (default: 10000ms) */
|
|
||||||
iceGathering?: number;
|
|
||||||
/** Timeout for waiting for answer (default: 30000ms) */
|
|
||||||
waitingForAnswer?: number;
|
|
||||||
/** Timeout for creating answer (default: 10000ms) */
|
|
||||||
creatingAnswer?: number;
|
|
||||||
/** Timeout for ICE connection (default: 30000ms) */
|
|
||||||
iceConnection?: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Options for creating a peer connection
|
|
||||||
*/
|
|
||||||
export interface PeerOptions {
|
|
||||||
/** RTCConfiguration for the peer connection */
|
|
||||||
rtcConfig?: RTCConfiguration;
|
|
||||||
/** Topics to advertise this connection under */
|
|
||||||
topics: string[];
|
|
||||||
/** How long the offer should live (milliseconds) */
|
|
||||||
ttl?: number;
|
|
||||||
/** Optional secret to protect the offer (max 128 characters) */
|
|
||||||
secret?: string;
|
|
||||||
/** Whether to create a data channel automatically (for offerer) */
|
|
||||||
createDataChannel?: boolean;
|
|
||||||
/** Label for the automatically created data channel */
|
|
||||||
dataChannelLabel?: string;
|
|
||||||
/** Timeout configurations */
|
|
||||||
timeouts?: PeerTimeouts;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Events emitted by RondevuPeer
|
|
||||||
*/
|
|
||||||
export interface PeerEvents extends Record<string, (...args: any[]) => void> {
|
|
||||||
'state': (state: string) => void;
|
|
||||||
'connected': () => void;
|
|
||||||
'disconnected': () => void;
|
|
||||||
'failed': (error: Error) => void;
|
|
||||||
'datachannel': (channel: RTCDataChannel) => void;
|
|
||||||
'track': (event: RTCTrackEvent) => void;
|
|
||||||
}
|
|
||||||
@@ -1,78 +0,0 @@
|
|||||||
import { PeerState } from './state.js';
|
|
||||||
import type { PeerOptions } from './types.js';
|
|
||||||
import type RondevuPeer from './index.js';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Waiting for answer from another peer
|
|
||||||
*/
|
|
||||||
export class WaitingForAnswerState extends PeerState {
|
|
||||||
private pollingInterval?: ReturnType<typeof setInterval>;
|
|
||||||
private timeout?: ReturnType<typeof setTimeout>;
|
|
||||||
|
|
||||||
constructor(
|
|
||||||
peer: RondevuPeer,
|
|
||||||
private offerId: string,
|
|
||||||
private options: PeerOptions
|
|
||||||
) {
|
|
||||||
super(peer);
|
|
||||||
this.startPolling();
|
|
||||||
}
|
|
||||||
|
|
||||||
get name() { return 'waiting-for-answer'; }
|
|
||||||
|
|
||||||
private startPolling(): void {
|
|
||||||
const answerTimeout = this.options.timeouts?.waitingForAnswer || 30000;
|
|
||||||
|
|
||||||
this.timeout = setTimeout(async () => {
|
|
||||||
this.cleanup();
|
|
||||||
const { FailedState } = await import('./failed-state.js');
|
|
||||||
this.peer.setState(new FailedState(
|
|
||||||
this.peer,
|
|
||||||
new Error('Timeout waiting for answer')
|
|
||||||
));
|
|
||||||
}, answerTimeout);
|
|
||||||
|
|
||||||
this.pollingInterval = setInterval(async () => {
|
|
||||||
try {
|
|
||||||
const answers = await this.peer.offersApi.getAnswers();
|
|
||||||
const myAnswer = answers.find((a: any) => a.offerId === this.offerId);
|
|
||||||
|
|
||||||
if (myAnswer) {
|
|
||||||
this.cleanup();
|
|
||||||
await this.handleAnswer(myAnswer.sdp);
|
|
||||||
}
|
|
||||||
} catch (err) {
|
|
||||||
console.error('Error polling for answers:', err);
|
|
||||||
if (err instanceof Error && err.message.includes('not found')) {
|
|
||||||
this.cleanup();
|
|
||||||
const { FailedState } = await import('./failed-state.js');
|
|
||||||
this.peer.setState(new FailedState(
|
|
||||||
this.peer,
|
|
||||||
new Error('Offer expired or not found')
|
|
||||||
));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}, 2000);
|
|
||||||
}
|
|
||||||
|
|
||||||
async handleAnswer(sdp: string): Promise<void> {
|
|
||||||
try {
|
|
||||||
await this.peer.pc.setRemoteDescription({
|
|
||||||
type: 'answer',
|
|
||||||
sdp
|
|
||||||
});
|
|
||||||
|
|
||||||
// Transition to exchanging ICE
|
|
||||||
const { ExchangingIceState } = await import('./exchanging-ice-state.js');
|
|
||||||
this.peer.setState(new ExchangingIceState(this.peer, this.offerId, this.options));
|
|
||||||
} catch (error) {
|
|
||||||
const { FailedState } = await import('./failed-state.js');
|
|
||||||
this.peer.setState(new FailedState(this.peer, error as Error));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
cleanup(): void {
|
|
||||||
if (this.pollingInterval) clearInterval(this.pollingInterval);
|
|
||||||
if (this.timeout) clearTimeout(this.timeout);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
442
src/rondevu-signaler.ts
Normal file
442
src/rondevu-signaler.ts
Normal file
@@ -0,0 +1,442 @@
|
|||||||
|
import { Signaler, Binnable } from './types.js'
|
||||||
|
import { Rondevu } from './rondevu.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 serviceFqn: 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: Rondevu,
|
||||||
|
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
|
||||||
|
})
|
||||||
|
|
||||||
|
// 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.serviceFqn = publishedService.serviceFqn
|
||||||
|
|
||||||
|
// 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.serviceFqn || !this.offerId) {
|
||||||
|
throw new Error('No service FQN or offer ID available. Must receive offer first.')
|
||||||
|
}
|
||||||
|
|
||||||
|
// Send answer to the service
|
||||||
|
const result = await this.rondevu.getAPI().postOfferAnswer(this.serviceFqn, this.offerId, 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.serviceFqn || !this.offerId) {
|
||||||
|
console.warn('Cannot send ICE candidate: no service FQN or offer ID')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
const candidateData = candidate.toJSON()
|
||||||
|
|
||||||
|
// Skip empty candidates
|
||||||
|
if (!candidateData.candidate || candidateData.candidate === '') {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
await this.rondevu.getAPI().addOfferIceCandidates(
|
||||||
|
this.serviceFqn,
|
||||||
|
this.offerId,
|
||||||
|
[candidateData]
|
||||||
|
)
|
||||||
|
} 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 {
|
||||||
|
// Get service by FQN (service should include @username)
|
||||||
|
const serviceFqn = `${this.service}@${this.host}`
|
||||||
|
const serviceData = await this.rondevu.getAPI().getService(serviceFqn)
|
||||||
|
|
||||||
|
if (!serviceData) {
|
||||||
|
console.warn(`No service found for ${serviceFqn}`)
|
||||||
|
this.isPolling = false
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Store service details
|
||||||
|
this.offerId = serviceData.offerId
|
||||||
|
this.serviceFqn = serviceData.serviceFqn
|
||||||
|
|
||||||
|
// Notify offer listeners
|
||||||
|
const offer: RTCSessionDescriptionInit = {
|
||||||
|
type: 'offer',
|
||||||
|
sdp: serviceData.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.serviceFqn || !this.offerId) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
let interval = this.pollingConfig.initialInterval
|
||||||
|
let retries = 0
|
||||||
|
|
||||||
|
const poll = async () => {
|
||||||
|
if (!this.serviceFqn || !this.offerId) {
|
||||||
|
this.stopAnswerPolling()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const answer = await this.rondevu.getAPI().getOfferAnswer(this.serviceFqn, this.offerId)
|
||||||
|
|
||||||
|
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.serviceFqn || !this.offerId) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
let interval = this.pollingConfig.initialInterval
|
||||||
|
|
||||||
|
const poll = async () => {
|
||||||
|
if (!this.serviceFqn || !this.offerId) {
|
||||||
|
this.stopIcePolling()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await this.rondevu
|
||||||
|
.getAPI()
|
||||||
|
.getOfferIceCandidates(this.serviceFqn, this.offerId, this.lastIceTimestamp)
|
||||||
|
|
||||||
|
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 = []
|
||||||
|
}
|
||||||
|
}
|
||||||
420
src/rondevu.ts
420
src/rondevu.ts
@@ -1,151 +1,335 @@
|
|||||||
import { RondevuAuth, Credentials, FetchFunction } from './auth.js';
|
import { RondevuAPI, Credentials, Keypair, Service, ServiceRequest, IceCandidate } from './api.js'
|
||||||
import { RondevuOffers } from './offers.js';
|
|
||||||
import RondevuPeer from './peer/index.js';
|
|
||||||
|
|
||||||
export interface RondevuOptions {
|
export interface RondevuOptions {
|
||||||
/**
|
apiUrl: string
|
||||||
* Base URL of the Rondevu server
|
username: string
|
||||||
* @default 'https://api.ronde.vu'
|
keypair?: Keypair
|
||||||
*/
|
credentials?: Credentials
|
||||||
baseUrl?: string;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Existing credentials (peerId + secret) to skip registration
|
|
||||||
*/
|
|
||||||
credentials?: Credentials;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Custom fetch implementation for environments without native fetch
|
|
||||||
* (Node.js < 18, some Workers environments, etc.)
|
|
||||||
*
|
|
||||||
* @example Node.js
|
|
||||||
* ```typescript
|
|
||||||
* import fetch from 'node-fetch';
|
|
||||||
* const client = new Rondevu({ fetch });
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
fetch?: FetchFunction;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Custom RTCPeerConnection implementation for Node.js environments
|
|
||||||
* Required when using in Node.js with wrtc or similar polyfills
|
|
||||||
*
|
|
||||||
* @example Node.js with wrtc
|
|
||||||
* ```typescript
|
|
||||||
* import { RTCPeerConnection } from 'wrtc';
|
|
||||||
* const client = new Rondevu({ RTCPeerConnection });
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
RTCPeerConnection?: typeof RTCPeerConnection;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Custom RTCSessionDescription implementation for Node.js environments
|
|
||||||
* Required when using in Node.js with wrtc or similar polyfills
|
|
||||||
*
|
|
||||||
* @example Node.js with wrtc
|
|
||||||
* ```typescript
|
|
||||||
* import { RTCSessionDescription } from 'wrtc';
|
|
||||||
* const client = new Rondevu({ RTCSessionDescription });
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
RTCSessionDescription?: typeof RTCSessionDescription;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Custom RTCIceCandidate implementation for Node.js environments
|
|
||||||
* Required when using in Node.js with wrtc or similar polyfills
|
|
||||||
*
|
|
||||||
* @example Node.js with wrtc
|
|
||||||
* ```typescript
|
|
||||||
* import { RTCIceCandidate } from 'wrtc';
|
|
||||||
* const client = new Rondevu({ RTCIceCandidate });
|
|
||||||
* ```
|
|
||||||
*/
|
|
||||||
RTCIceCandidate?: typeof RTCIceCandidate;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface PublishServiceOptions {
|
||||||
|
serviceFqn: string // Must include @username (e.g., "chat:1.0.0@alice")
|
||||||
|
offers: Array<{ sdp: string }>
|
||||||
|
ttl?: number
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Rondevu - Complete WebRTC signaling client
|
||||||
|
*
|
||||||
|
* Provides a unified API for:
|
||||||
|
* - Username claiming with Ed25519 signatures
|
||||||
|
* - Service publishing with automatic signature generation
|
||||||
|
* - Service discovery (direct, random, paginated)
|
||||||
|
* - WebRTC signaling (offer/answer exchange, ICE relay)
|
||||||
|
* - Keypair management
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```typescript
|
||||||
|
* // Initialize (generates keypair automatically)
|
||||||
|
* const rondevu = new Rondevu({
|
||||||
|
* apiUrl: 'https://signal.example.com',
|
||||||
|
* username: 'alice',
|
||||||
|
* })
|
||||||
|
*
|
||||||
|
* await rondevu.initialize()
|
||||||
|
*
|
||||||
|
* // Claim username (one time)
|
||||||
|
* await rondevu.claimUsername()
|
||||||
|
*
|
||||||
|
* // Publish a service
|
||||||
|
* const publishedService = await rondevu.publishService({
|
||||||
|
* serviceFqn: 'chat:1.0.0@alice',
|
||||||
|
* offers: [{ sdp: offerSdp }],
|
||||||
|
* ttl: 300000,
|
||||||
|
* })
|
||||||
|
*
|
||||||
|
* // Discover a service
|
||||||
|
* const service = await rondevu.getService('chat:1.0.0@bob')
|
||||||
|
*
|
||||||
|
* // Post answer
|
||||||
|
* await rondevu.postOfferAnswer(service.serviceFqn, service.offerId, answerSdp)
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
export class Rondevu {
|
export class Rondevu {
|
||||||
readonly auth: RondevuAuth;
|
private readonly api: RondevuAPI
|
||||||
private _offers?: RondevuOffers;
|
private readonly username: string
|
||||||
private credentials?: Credentials;
|
private keypair: Keypair | null = null
|
||||||
private baseUrl: string;
|
private usernameClaimed = false
|
||||||
private fetchFn?: FetchFunction;
|
|
||||||
private rtcPeerConnection?: typeof RTCPeerConnection;
|
|
||||||
private rtcSessionDescription?: typeof RTCSessionDescription;
|
|
||||||
private rtcIceCandidate?: typeof RTCIceCandidate;
|
|
||||||
|
|
||||||
constructor(options: RondevuOptions = {}) {
|
constructor(options: RondevuOptions) {
|
||||||
this.baseUrl = options.baseUrl || 'https://api.ronde.vu';
|
this.username = options.username
|
||||||
this.fetchFn = options.fetch;
|
this.keypair = options.keypair || null
|
||||||
this.rtcPeerConnection = options.RTCPeerConnection;
|
this.api = new RondevuAPI(options.apiUrl, options.credentials)
|
||||||
this.rtcSessionDescription = options.RTCSessionDescription;
|
|
||||||
this.rtcIceCandidate = options.RTCIceCandidate;
|
|
||||||
|
|
||||||
this.auth = new RondevuAuth(this.baseUrl, this.fetchFn);
|
console.log('[Rondevu] Constructor called:', {
|
||||||
|
username: this.username,
|
||||||
if (options.credentials) {
|
hasKeypair: !!this.keypair,
|
||||||
this.credentials = options.credentials;
|
publicKey: this.keypair?.publicKey
|
||||||
this._offers = new RondevuOffers(this.baseUrl, this.credentials, this.fetchFn);
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ============================================
|
||||||
|
// Initialization
|
||||||
|
// ============================================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Initialize the service - generates keypair if not provided
|
||||||
|
* Call this before using other methods
|
||||||
|
*/
|
||||||
|
async initialize(): Promise<void> {
|
||||||
|
console.log('[Rondevu] Initialize called, hasKeypair:', !!this.keypair)
|
||||||
|
|
||||||
|
if (!this.keypair) {
|
||||||
|
console.log('[Rondevu] Generating new keypair...')
|
||||||
|
this.keypair = await RondevuAPI.generateKeypair()
|
||||||
|
console.log('[Rondevu] Generated keypair, publicKey:', this.keypair.publicKey)
|
||||||
|
} else {
|
||||||
|
console.log('[Rondevu] Using existing keypair, publicKey:', this.keypair.publicKey)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Register with API if no credentials provided
|
||||||
|
if (!this.api['credentials']) {
|
||||||
|
const credentials = await this.api.register()
|
||||||
|
this.api.setCredentials(credentials)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================================
|
||||||
|
// Username Management
|
||||||
|
// ============================================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Claim the username with Ed25519 signature
|
||||||
|
* Should be called once before publishing services
|
||||||
|
*/
|
||||||
|
async claimUsername(): Promise<void> {
|
||||||
|
if (!this.keypair) {
|
||||||
|
throw new Error('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.publicKey === 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
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get offers API (requires authentication)
|
* Check if username has been claimed (checks with server)
|
||||||
*/
|
*/
|
||||||
get offers(): RondevuOffers {
|
async isUsernameClaimed(): Promise<boolean> {
|
||||||
if (!this._offers) {
|
if (!this.keypair) {
|
||||||
throw new Error('Not authenticated. Call register() first or provide credentials.');
|
return false
|
||||||
}
|
}
|
||||||
return this._offers;
|
|
||||||
|
try {
|
||||||
|
const check = await this.api.checkUsername(this.username)
|
||||||
|
|
||||||
|
// Debug logging
|
||||||
|
console.log('[Rondevu] Username check:', {
|
||||||
|
username: this.username,
|
||||||
|
available: check.available,
|
||||||
|
serverPublicKey: check.publicKey,
|
||||||
|
localPublicKey: this.keypair.publicKey,
|
||||||
|
match: check.publicKey === this.keypair.publicKey
|
||||||
|
})
|
||||||
|
|
||||||
|
// Username is claimed if it's not available and owned by our public key
|
||||||
|
const claimed = !check.available && check.publicKey === this.keypair.publicKey
|
||||||
|
|
||||||
|
// Update internal flag to match server state
|
||||||
|
this.usernameClaimed = claimed
|
||||||
|
|
||||||
|
return claimed
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Failed to check username claim status:', err)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================================
|
||||||
|
// Service Publishing
|
||||||
|
// ============================================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Publish a service with automatic signature generation
|
||||||
|
*/
|
||||||
|
async publishService(options: PublishServiceOptions): Promise<Service> {
|
||||||
|
if (!this.keypair) {
|
||||||
|
throw new Error('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 } = 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 = {
|
||||||
|
serviceFqn, // Must include @username
|
||||||
|
offers,
|
||||||
|
signature,
|
||||||
|
message,
|
||||||
|
ttl,
|
||||||
|
}
|
||||||
|
|
||||||
|
// Publish to server
|
||||||
|
return await this.api.publishService(serviceRequest)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================================
|
||||||
|
// Service Discovery
|
||||||
|
// ============================================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get service by FQN (with username) - Direct lookup
|
||||||
|
* Example: chat:1.0.0@alice
|
||||||
|
*/
|
||||||
|
async getService(serviceFqn: string): Promise<{
|
||||||
|
serviceId: string
|
||||||
|
username: string
|
||||||
|
serviceFqn: string
|
||||||
|
offerId: string
|
||||||
|
sdp: string
|
||||||
|
createdAt: number
|
||||||
|
expiresAt: number
|
||||||
|
}> {
|
||||||
|
return await this.api.getService(serviceFqn)
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Register and initialize authenticated client
|
* Discover a random available service without knowing the username
|
||||||
|
* Example: chat:1.0.0 (without @username)
|
||||||
*/
|
*/
|
||||||
async register(): Promise<Credentials> {
|
async discoverService(serviceVersion: string): Promise<{
|
||||||
this.credentials = await this.auth.register();
|
serviceId: string
|
||||||
|
username: string
|
||||||
// Create offers API instance
|
serviceFqn: string
|
||||||
this._offers = new RondevuOffers(
|
offerId: string
|
||||||
this.baseUrl,
|
sdp: string
|
||||||
this.credentials,
|
createdAt: number
|
||||||
this.fetchFn
|
expiresAt: number
|
||||||
);
|
}> {
|
||||||
|
return await this.api.discoverService(serviceVersion)
|
||||||
return this.credentials;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Check if client is authenticated
|
* Discover multiple available services with pagination
|
||||||
|
* Example: chat:1.0.0 (without @username)
|
||||||
*/
|
*/
|
||||||
isAuthenticated(): boolean {
|
async discoverServices(serviceVersion: string, limit: number = 10, offset: number = 0): Promise<{
|
||||||
return !!this.credentials;
|
services: Array<{
|
||||||
|
serviceId: string
|
||||||
|
username: string
|
||||||
|
serviceFqn: string
|
||||||
|
offerId: string
|
||||||
|
sdp: string
|
||||||
|
createdAt: number
|
||||||
|
expiresAt: number
|
||||||
|
}>
|
||||||
|
count: number
|
||||||
|
limit: number
|
||||||
|
offset: number
|
||||||
|
}> {
|
||||||
|
return await this.api.discoverServices(serviceVersion, limit, offset)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================================
|
||||||
|
// WebRTC Signaling
|
||||||
|
// ============================================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Post answer SDP to specific offer
|
||||||
|
*/
|
||||||
|
async postOfferAnswer(serviceFqn: string, offerId: string, sdp: string): Promise<{
|
||||||
|
success: boolean
|
||||||
|
offerId: string
|
||||||
|
}> {
|
||||||
|
return await this.api.postOfferAnswer(serviceFqn, offerId, sdp)
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get current credentials
|
* Get answer SDP (offerer polls this)
|
||||||
*/
|
*/
|
||||||
getCredentials(): Credentials | undefined {
|
async getOfferAnswer(serviceFqn: string, offerId: string): Promise<{
|
||||||
return this.credentials;
|
sdp: string
|
||||||
|
offerId: string
|
||||||
|
answererId: string
|
||||||
|
answeredAt: number
|
||||||
|
} | null> {
|
||||||
|
return await this.api.getOfferAnswer(serviceFqn, offerId)
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Create a new WebRTC peer connection (requires authentication)
|
* Add ICE candidates to specific offer
|
||||||
* This is a high-level helper that creates and manages WebRTC connections with state management
|
|
||||||
*
|
|
||||||
* @param rtcConfig Optional RTCConfiguration for the peer connection
|
|
||||||
* @returns RondevuPeer instance
|
|
||||||
*/
|
*/
|
||||||
createPeer(rtcConfig?: RTCConfiguration): RondevuPeer {
|
async addOfferIceCandidates(serviceFqn: string, offerId: string, candidates: RTCIceCandidateInit[]): Promise<{
|
||||||
if (!this._offers) {
|
count: number
|
||||||
throw new Error('Not authenticated. Call register() first or provide credentials.');
|
offerId: string
|
||||||
|
}> {
|
||||||
|
return await this.api.addOfferIceCandidates(serviceFqn, offerId, candidates)
|
||||||
}
|
}
|
||||||
|
|
||||||
return new RondevuPeer(
|
/**
|
||||||
this._offers,
|
* Get ICE candidates for specific offer (with polling support)
|
||||||
rtcConfig,
|
*/
|
||||||
this.rtcPeerConnection,
|
async getOfferIceCandidates(serviceFqn: string, offerId: string, since: number = 0): Promise<{
|
||||||
this.rtcSessionDescription,
|
candidates: IceCandidate[]
|
||||||
this.rtcIceCandidate
|
offerId: string
|
||||||
);
|
}> {
|
||||||
|
return await this.api.getOfferIceCandidates(serviceFqn, offerId, since)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================================
|
||||||
|
// Utility Methods
|
||||||
|
// ============================================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Access to underlying API for advanced operations
|
||||||
|
* @deprecated Use direct methods on Rondevu instance instead
|
||||||
|
*/
|
||||||
|
getAPI(): RondevuAPI {
|
||||||
|
return this.api
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
20
src/types.ts
Normal file
20
src/types.ts
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
/**
|
||||||
|
* Core signaling types
|
||||||
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cleanup function returned by listener methods
|
||||||
|
*/
|
||||||
|
export type Binnable = () => void
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Signaler interface for WebRTC offer/answer/ICE exchange
|
||||||
|
*/
|
||||||
|
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>
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user