Skip to content

Client SDK

Client WebSocket

Real-time WebSocket client

Client WebSocket#

Connect via WebSocket for real-time command execution and event subscriptions:

TypeScript
// Connect to WebSocket
const ws = await client.connect()
ย 
// Execute commands over WebSocket
const result = await ws.execute('search', { query: 'laptop' })
ย 
// Listen for events
const unsubscribe = ws.on('order.updated', (data) => {
console.log('Order updated:', data)
})
ย 
// Check connection state
console.log(ws.state) // 'connected' | 'connecting' | 'disconnected' | 'reconnecting'
ย 
// Disconnect when done
client.disconnect()

Connection Options

WebSocketTransport supports auto-reconnect with exponential backoff, ping keepalive, and connection state callbacks:

TypeScript
import { WebSocketTransport } from '@surfjs/client'
ย 
const ws = new WebSocketTransport({
reconnect: true, // Auto-reconnect on disconnect (default: true)
maxReconnectAttempts: Infinity, // Max reconnect attempts (default: Infinity)
reconnectDelay: 1000, // Initial delay in ms (default: 1000)
maxReconnectDelay: 16000, // Max delay in ms (default: 16000)
pingInterval: 30000, // Keepalive ping interval in ms (default: 30000)
onDisconnect: () => console.log('Lost connection'),
onReconnect: () => console.log('Reconnected!'),
onStateChange: (state) => console.log('State:', state),
})
ย 
await ws.connect('wss://shop.example.com/surf/ws', 'sk-token')

Retry & Cache

The SurfClient supports automatic retry with exponential backoff and an LRU response cache for HTTP requests:

TypeScript
const client = await SurfClient.discover(url, {
// Retry configuration
retry: {
maxAttempts: 3,
backoffMs: 500,
backoffMultiplier: 2,
retryOn: [429, 502, 503, 504],
},
ย 
// Response caching (skips commands with sideEffects: true)
cache: {
ttlMs: 60_000, // 60s TTL
maxSize: 100, // Max 100 cached entries
},
})
ย 
// Execute โ€” automatically retries and caches
const result = await client.execute('search', { query: 'laptop' })
ย 
// Clear cache for a specific command
client.clearCache('search')
ย 
// Clear all caches
client.clearCache()
ย 
// Check for manifest updates (checksum comparison)
const update = await client.checkForUpdates()
if (update.changed) {
console.log('Manifest updated:', update.checksum)
console.log('New manifest:', update.manifest)
}