@echo-sdk/core
v0.1.2
Published
Framework-agnostic chatbot SDK with WebSocket management
Maintainers
Readme
@echo-core/sdk
A TypeScript-first, framework-agnostic chatbot SDK with robust WebSocket management and a shadcn-inspired component architecture.
Features
- 🔌 WebSocket Management: Automatic reconnection with exponential backoff + jitter
- 💓 Heartbeat Mechanism: Keep-alive ping/pong for connection health
- 📦 Message Queuing: Queue messages when offline, auto-flush on reconnection
- ✅ Acknowledgements: Track message delivery with configurable timeouts
- 🎨 Highly Configurable: Customize everything from connection settings to UI styling
- 📘 TypeScript-first: Full type safety with comprehensive type definitions
- 🎯 Framework-agnostic: Core SDK works anywhere, with optional framework wrappers
- 🔧 Modular Architecture: Import only what you need
Installation
npm install @echo-core/sdkQuick Start
import { ChatBotClient, ConnectionState } from '@echo-core/sdk';
// Initialize the client
const client = new ChatBotClient({
websocket: {
url: 'wss://your-websocket-server.com',
},
auth: {
apiKey: 'your-api-key',
},
ui: {
position: 'bottom-right',
},
});
// Listen for connection events
client.on('connection', ({ state }) => {
console.log('Connection state:', state);
});
// Listen for messages
client.on('message', ({ message }) => {
console.log('Received message:', message);
});
// Connect to the server
await client.connect();
// Send a message
await client.sendMessage('Hello, chatbot!');Configuration
Full Configuration Example
const client = new ChatBotClient({
websocket: {
url: 'wss://your-server.com',
protocols: ['chat-protocol'],
connectionTimeout: 10000,
heartbeatInterval: 30000,
headers: {
'X-Custom-Header': 'value',
},
},
auth: {
apiKey: 'your-api-key',
userId: 'user-123',
token: 'auth-token',
},
reconnection: {
enabled: true,
maxAttempts: 10,
baseDelay: 1000,
maxDelay: 30000,
jitter: 0.3,
},
ui: {
position: 'bottom-right',
zIndex: 1000,
theme: {
primaryColor: '#007bff',
backgroundColor: '#ffffff',
textColor: '#333333',
},
classNames: {
container: 'my-custom-container',
header: 'my-custom-header',
messageList: 'my-custom-message-list',
message: 'my-custom-message',
input: 'my-custom-input',
button: 'my-custom-button',
},
},
logger: {
enabled: true,
level: 'info',
},
debug: false,
});Configuration Options
WebSocket Configuration
url(required): WebSocket server URLprotocols: WebSocket sub-protocolsconnectionTimeout: Connection timeout in ms (default: 10000)heartbeatInterval: Heartbeat interval in ms (default: 30000)headers: Custom headers for the connection
Reconnection Configuration
enabled: Enable automatic reconnection (default: true)maxAttempts: Max reconnection attempts (default: Infinity)baseDelay: Base delay for exponential backoff in ms (default: 1000)maxDelay: Maximum delay in ms (default: 30000)jitter: Jitter factor 0-1 (default: 0.3)
UI Configuration
position: Widget position -'bottom-right' | 'bottom-left' | 'top-right' | 'top-left'zIndex: Z-index for the widget (default: 1000)theme: Custom theme colorsclassNames: Custom CSS class names for components
API Reference
ChatBotClient
Methods
connect(): Promise<void>
Connect to the WebSocket server.
await client.connect();disconnect(): void
Disconnect from the WebSocket server.
client.disconnect();sendMessage(content: string, options?: SendMessageOptions): Promise<MessageAcknowledgement | void>
Send a message.
await client.sendMessage('Hello!', {
type: MessageType.TEXT,
requireAck: true,
ackTimeout: 5000,
metadata: { custom: 'data' },
});on<T>(event: T, callback: EventCallback<T>): () => void
Subscribe to an event. Returns an unsubscribe function.
const unsubscribe = client.on('message', ({ message }) => {
console.log(message);
});
// Later...
unsubscribe();once<T>(event: T, callback: EventCallback<T>): () => void
Subscribe to an event once.
client.once('connection', ({ state }) => {
console.log('Connected!');
});onAny(callback: WildcardEventCallback): () => void
Subscribe to all events.
client.onAny((event) => {
console.log('Event:', event.type, event.data);
});isConnected(): boolean
Check if connected.
if (client.isConnected()) {
console.log('Connected!');
}getConnectionState(): ConnectionState
Get current connection state.
const state = client.getConnectionState();Events
connection: Connection state changesmessage: Incoming messagesmessageSent: Outgoing messageserror: Errorsacknowledgement: Message acknowledgementstyping: Typing indicatorsreconnecting: Reconnection attemptsreconnected: Successful reconnectionreconnectFailed: Failed reconnection
Types
All types are exported for use in your application:
import type {
ChatBotConfig,
Message,
MessageType,
MessageStatus,
ConnectionState,
EventCallback,
} from '@echo-core/sdk';Custom Styling
The SDK includes minimal CSS. Import it in your application:
import '@echo-core/sdk/styles.css';Override styles using the classNames configuration or CSS variables:
:root {
--chatbot-primary-color: #ff6b6b;
--chatbot-background-color: #1a1a1a;
--chatbot-text-color: #ffffff;
}Advanced Usage
Custom Logger
const client = new ChatBotClient({
websocket: { url: 'wss://...' },
logger: {
enabled: true,
level: 'debug',
customLogger: (level, message, ...args) => {
// Send to your logging service
myLogger.log(level, message, args);
},
},
});Message Queue Management
// Get queued messages count
const count = client.getQueuedMessagesCount();
// Clear message queue
client.clearMessageQueue();Event History
// Get event history
const history = client.getEventHistory();
// Clear event history
client.clearEventHistory();License
MIT
