UNPKG

@api.global/typedsocket

Version:

A library for creating typed WebSocket connections, supporting bi-directional communication with type safety.

165 lines (164 loc) 5.97 kB
import * as plugins from './typedsocket.plugins.js'; export type TTypedSocketSide = 'server' | 'client'; export type TConnectionStatus = 'new' | 'connecting' | 'connected' | 'disconnected' | 'reconnecting'; /** * Options for creating a TypedSocket client */ export interface ITypedSocketClientOptions { autoReconnect?: boolean; maxRetries?: number; initialBackoffMs?: number; maxBackoffMs?: number; } /** * Wrapper for SmartServe's IWebSocketPeer to provide tag compatibility */ export interface ISmartServeConnectionWrapper { peer: plugins.IWebSocketPeer; getTagById(tagId: string): Promise<{ id: string; payload: any; } | undefined>; } export declare class TypedSocket { /** * Creates a TypedSocket client using native WebSocket. * Works in both browser and Node.js environments. * * @param typedrouterArg - TypedRouter for handling server-initiated requests * @param serverUrlArg - Server URL (e.g., 'http://localhost:3000' or 'wss://example.com') * @param options - Connection options * * @example * ```typescript * const typedRouter = new TypedRouter(); * const client = await TypedSocket.createClient( * typedRouter, * 'http://localhost:3000', * { autoReconnect: true } * ); * ``` */ static createClient(typedrouterArg: plugins.typedrequest.TypedRouter, serverUrlArg: string, options?: ITypedSocketClientOptions): Promise<TypedSocket>; /** * Returns the current window location origin URL. * Useful in browser environments for connecting to the same origin. */ static useWindowLocationOriginUrl: () => string; /** * Creates a TypedSocket server from an existing SmartServe instance. * This is the only way to create a server-side TypedSocket. * * @param smartServeArg - SmartServe instance with typedRouter configured in websocket options * @param typedRouterArg - TypedRouter for handling requests (must match SmartServe's typedRouter) * * @example * ```typescript * const typedRouter = new TypedRouter(); * const smartServe = new SmartServe({ * port: 3000, * websocket: { * typedRouter, * onConnectionOpen: (peer) => peer.tags.add('client') * } * }); * await smartServe.start(); * const typedSocket = TypedSocket.fromSmartServe(smartServe, typedRouter); * ``` */ static fromSmartServe(smartServeArg: plugins.SmartServe, typedRouterArg: plugins.typedrequest.TypedRouter): TypedSocket; /** * Registers built-in TypedHandlers for tag management */ private static registerTagHandlers; readonly side: TTypedSocketSide; readonly typedrouter: plugins.typedrequest.TypedRouter; statusSubject: plugins.smartrx.rxjs.Subject<TConnectionStatus>; private connectionStatus; private websocket; private clientOptions; private serverUrl; private retryCount; private currentBackoff; private pendingRequests; private smartServeRef; private smartServeConnectionWrappers; private constructor(); /** * Connects the client to the server using native WebSocket */ private connect; /** * Converts an HTTP(S) URL to a WebSocket URL */ private toWebSocketUrl; /** * Handles incoming WebSocket messages */ private handleMessage; /** * Handles WebSocket disconnection */ private handleDisconnect; /** * Schedules a reconnection attempt with exponential backoff */ private scheduleReconnect; /** * Updates connection status and notifies subscribers */ private updateStatus; /** * Sends a request to the server and waits for response (client-side) */ private sendRequest; /** * Creates a TypedRequest for the specified method. * On clients, sends to the server. * On servers, sends to the specified target connection. */ createTypedRequest<T extends plugins.typedrequestInterfaces.ITypedRequest>(methodName: T['method'], targetConnection?: ISmartServeConnectionWrapper): plugins.typedrequest.TypedRequest<T>; /** * Gets the current connection status */ getStatus(): TConnectionStatus; /** * Stops the TypedSocket client or cleans up server state */ stop(): Promise<void>; /** * Sets a tag on this client connection. * Tags are stored on the server and can be used for filtering. * @client-only */ setTag<T extends plugins.typedrequestInterfaces.ITag>(name: T['name'], payload: T['payload']): Promise<void>; /** * Removes a tag from this client connection. * @client-only */ removeTag(name: string): Promise<void>; /** * Gets or creates a connection wrapper for a peer */ private getOrCreateWrapper; /** * Finds all connections matching the filter function. * @server-only */ findAllTargetConnections(asyncFindFuncArg: (connectionArg: ISmartServeConnectionWrapper) => Promise<boolean>): Promise<ISmartServeConnectionWrapper[]>; /** * Finds the first connection matching the filter function. * @server-only */ findTargetConnection(asyncFindFuncArg: (connectionArg: ISmartServeConnectionWrapper) => Promise<boolean>): Promise<ISmartServeConnectionWrapper | undefined>; /** * Finds all connections with the specified tag. * @server-only */ findAllTargetConnectionsByTag<TTag extends plugins.typedrequestInterfaces.ITag = any>(keyArg: TTag['name'], payloadArg?: TTag['payload']): Promise<ISmartServeConnectionWrapper[]>; /** * Finds the first connection with the specified tag. * @server-only */ findTargetConnectionByTag<TTag extends plugins.typedrequestInterfaces.ITag = any>(keyArg: TTag['name'], payloadArg?: TTag['payload']): Promise<ISmartServeConnectionWrapper | undefined>; }