A WebSocket server implementation for Bun with method handling, reconnection support, and state persistence.
-
🔄 Request/Response System
- Method-based request handling
- Bidirectional communication
- Request timeout handling
- Request queuing for disconnected clients
-
🔌 Connection Management
- Automatic reconnection support
- Session state persistence with JWT
- Configurable disconnection timeout
- Message buffering during disconnection
-
🛠 Developer Tools
- Detailed debug logging with colors
- Event-driven architecture
- JSDoc type hints
-
⚡ Performance
- Message buffering with configurable size
- Efficient request queuing
- Automatic cleanup of expired sessions
bun add @killiandvcz/helios
import { Helios } from '@killiandvcz/helios';
// Create Helios instance
const helios = new Helios({
disconnectionTTL: 5 * 60 * 1000, // 5 minutes
connectionKey: 'your-secret-key'
});
// Register a method
helios.method('users:get', async (context) => {
const { id } = context.payload;
context.success({ id, name: 'John' });
});
// Enable debug logging
helios.debug();
// Create Bun WebSocket server
const server = Bun.serve({
port: 3000,
websocket: {
message: helios.message,
open: helios.open,
close: helios.close,
error: helios.error
}
});
console.log('Helios server running on port 3000');
Methods are the primary way to handle requests:
helios.method('namespace:action', async (context) => {
// Access request data
const { payload } = context;
// Send success response
context.success({ data: 'response' });
// Or send error response
context.error('ERROR_CODE', 'Error message');
// Send notification
context.notification({ status: 'processing' });
});
Each WebSocket connection is managed by a Starling instance that handles:
- Message parsing and routing
- Connection state management
- Request/response tracking
- Message buffering
Enable state persistence across reconnections:
starling.states.register('namespace', {
save: () => ({ /* state to save */ }),
restore: (data) => { /* restore state */ },
validate: (data) => /* validate state */
});
Standard message format:
{
protocol: "helios-starling",
version: "1.0.0",
timestamp: 1642441234567,
type: "request" | "response" | "notification",
requestId: "uuid",
method: "namespace:action",
payload: {}
}
const helios = new Helios({
// How long to keep session after disconnect
disconnectionTTL: 5 * 60 * 1000,
// JWT signing key for session tokens
connectionKey: 'your-secret-key'
});
Enable detailed logging:
helios.debug();
Provides colored console output for:
- 🔌 Connections/disconnections
- 📡 Method calls
- 📩 Messages
⚠️ Errors and warnings
Standard error codes:
METHOD_NOT_FOUND
INVALID_MESSAGE_FORMAT
REQUEST_TIMEOUT
REQUEST_CANCELLED
INTERNAL_ERROR
context.error('VALIDATION_ERROR', 'Invalid input');
Contributions are welcome! Please feel free to submit a Pull Request.
MIT