@stacksjs/stx
Version:
A performant UI Framework. Powered by Bun.
69 lines • 2.07 kB
TypeScript
/**
* Check if WebSocket is supported
*/
export declare function isWebSocketSupported(): boolean;
/**
* Create a reactive WebSocket connection
*
* @example
* ```ts
* const ws = useWebSocket('wss://echo.websocket.org', {
* autoReconnect: true,
* onMessage: (event) => console.log('Received:', event.data),
* })
*
* // Subscribe to state changes
* ws.subscribe((state) => {
* console.log('Status:', state.status)
* console.log('Last data:', state.data)
* })
*
* // Send a message
* ws.send('Hello!')
*
* // Close connection
* ws.close()
* ```
*/
export declare function useWebSocket<T = unknown>(url: string | URL, options?: WebSocketOptions): WebSocketRef<T> & { on: (event: WebSocketEventType, callback: WebSocketEventCallback) => () => void };
export declare interface WebSocketState<T = unknown> {
status: WebSocketStatus
data: T | null
error: Event | null
ws: WebSocket | null
}
export declare interface WebSocketOptions {
protocols?: string | string[]
autoReconnect?: boolean | {
retries?: number
delay?: number
maxDelay?: number
onFailed?: () => void
}
heartbeat?: boolean | {
message?: string | ArrayBuffer | Blob
interval?: number
pongTimeout?: number
}
immediate?: boolean
onOpen?: (event: Event) => void
onMessage?: (event: MessageEvent) => void
onClose?: (event: CloseEvent) => void
onError?: (event: Event) => void
}
export declare interface WebSocketRef<T = unknown> {
get: () => WebSocketState<T>
subscribe: (fn: (state: WebSocketState<T>) => void) => () => void
send: (data: string | ArrayBuffer | Blob) => boolean
open: () => void
close: (code?: number, reason?: string) => void
ws: () => WebSocket | null
}
/**
* WebSocket Composables
*
* Reactive utilities for WebSocket communication with auto-reconnect support.
*/
export type WebSocketStatus = 'connecting' | 'open' | 'closing' | 'closed'
declare type WebSocketEventType = 'open' | 'message' | 'close' | 'error'
declare type WebSocketEventCallback = (event: Event | MessageEvent | CloseEvent) => void