import { S as Selector, k as StorageDeleteEvent, l as SerializedStorageDeleteEvent, R as ResourceTransactionEvent, h as SerializedResourceTransactionEvent, m as ResourceSetContentsEvent, n as SerializedResourceSetContentsEvent, o as Emitter } from './hive.DlaRxYsk.js'; import { Transaction, TransactionResult } from '../sdk/transaction.js'; import z from 'zod'; //#region src/protocol.d.ts type Protocol = { Handshake: { request: { token?: string | null | undefined; }; }; Join: { request: { token?: string | null | undefined; resource: Selector['key']; }; }; Messages: { [StorageDeleteEvent.type]: SerializedStorageDeleteEvent; [ResourceTransactionEvent.type]: SerializedResourceTransactionEvent; [ResourceSetContentsEvent.type]: SerializedResourceSetContentsEvent; }; Requests: { [ResourceTransactionEvent.type]: { request: { resource: Selector['key']; transaction: Transaction; trace: string; }; response: { resource: Selector['key']; results: TransactionResult<[]>; }; }; }; }; declare const PulseMessageSchema: z.ZodObject<{ id: z.ZodString; ts: z.ZodNumber; type: z.ZodLiteral<"pulse">; }, z.core.$strip>; type PulseMessage = z.output; declare const EnvelopeMessageSchema: z.ZodObject<{ id: z.ZodString; ts: z.ZodNumber; type: z.ZodLiteral<"envelope">; channel: z.ZodNullable; key: z.ZodNullable; data: z.ZodAny; }, z.core.$strip>; type EnvelopeMessage = z.output; declare const RequestMessageSchema: z.ZodObject<{ id: z.ZodString; ts: z.ZodNumber; type: z.ZodLiteral<"request">; channel: z.ZodNullable; key: z.ZodNullable; req: z.ZodUUID; data: z.ZodAny; }, z.core.$strip>; type RequestMessage = z.output; declare const ResponseMessageSchema: z.ZodUnion; channel: z.ZodNullable; req: z.ZodUUID; data: z.ZodAny; error: z.ZodNull; }, z.core.$strip>, z.ZodObject<{ id: z.ZodString; ts: z.ZodNumber; type: z.ZodLiteral<"response">; channel: z.ZodNullable; req: z.ZodUUID; data: z.ZodNull; error: z.ZodObject<{ name: z.ZodString; message: z.ZodString; }, z.core.$strip>; }, z.core.$strip>]>; type ResponseMessage = z.output; //#endregion //#region src/utils/listener.d.ts type ListenerFor, K extends keyof T = keyof T> = { bivarianceHack(payload: T[K]): void; }["bivarianceHack"]; type Listener, K extends keyof T = keyof T> = ListenerFor; //#region src/server/messages.d.ts declare const HandshakeResponseMessageSchema: z.ZodUnion; channel: z.ZodNullable; req: z.ZodUUID; pulse: z.ZodObject<{ interval: z.ZodNumber; threshold: z.ZodNumber; }, z.core.$strip>; data: z.ZodAny; error: z.ZodNull; }, z.core.$strip>, z.ZodObject<{ id: z.ZodString; ts: z.ZodNumber; type: z.ZodLiteral<"handshake:res">; req: z.ZodUUID; data: z.ZodNull; error: z.ZodObject<{ name: z.ZodString; message: z.ZodString; }, z.core.$strip>; }, z.core.$strip>]>; type HandshakeResponseMessage = z.output; declare const JoinResponseMessageSchema: z.ZodObject<{ id: z.ZodString; ts: z.ZodNumber; type: z.ZodLiteral<"join:res">; channel: z.ZodString; req: z.ZodUUID; data: z.ZodAny; error: z.ZodUnion]>; }, z.core.$strip>; type JoinResponseMessage = z.output; declare const LeaveResponseMessageSchema: z.ZodObject<{ id: z.ZodString; ts: z.ZodNumber; type: z.ZodLiteral<"leave:res">; channel: z.ZodString; data: z.ZodAny; error: z.ZodUnion]>; }, z.core.$strip>; type LeaveResponseMessage = z.output; type ServerMessage = PulseMessage | HandshakeResponseMessage | JoinResponseMessage | LeaveResponseMessage | EnvelopeMessage | RequestMessage | ResponseMessage; //#endregion //#region src/utils/types.d.ts type Schema = { Requests?: Record; Messages?: Record; Handshake?: { request?: any; response?: any; }; Join?: { request?: any; response?: any; }; Leave?: { request?: any; response?: any; }; }; type RequestKeys = S["Requests"] extends Record ? keyof S["Requests"] : never; type MessageKeys = S["Messages"] extends Record ? keyof S["Messages"] : never; type RequestData> = S["Requests"] extends Record ? K extends keyof S["Requests"] ? "request" extends keyof S["Requests"][K] ? S["Requests"][K]["request"] : undefined : never : never; type ResponseData> = S["Requests"] extends Record ? K extends keyof S["Requests"] ? "response" extends keyof S["Requests"][K] ? S["Requests"][K]["response"] : undefined : never : never; type MessageData> = S["Messages"] extends Record ? K extends keyof S["Messages"] ? S["Messages"][K] : never : never; type HandshakeRequestData = S["Handshake"] extends { request: any; } ? S["Handshake"]["request"] : undefined; type JoinRequestData = S["Join"] extends { request: any; } ? S["Join"]["request"] : undefined; type LeaveRequestData = S["Leave"] extends { request: any; } ? S["Leave"]["request"] : undefined; /** * Helper type for request parameters that makes data optional when undefined. */ type RequestParams> = RequestData extends undefined ? { key: K; data?: undefined; timeout?: number; } : { key: K; data: RequestData; timeout?: number; }; /** * Helper type for handshake parameters that makes data optional when undefined. */ type HandshakeParams = HandshakeRequestData extends undefined ? { data?: undefined; timeout?: number; } : { data: HandshakeRequestData; timeout?: number; }; /** * Helper type for join parameters that makes data optional when undefined. */ type JoinParams = JoinRequestData extends undefined ? { data?: undefined; timeout?: number; } : { data: JoinRequestData; timeout?: number; }; /** * Helper type for leave parameters that makes data optional when undefined. */ type LeaveParams = LeaveRequestData extends undefined ? { data?: undefined; timeout?: number; } : { data: LeaveRequestData; timeout?: number; }; /** * Helper type that creates a union of all possible request handler props. * This allows TypeScript to narrow the data type based on the request key. */ type RequestHandlerProps = S["Requests"] extends Record ? { [K in keyof S["Requests"]]: { key: K; data: K extends RequestKeys ? RequestData : unknown; } }[keyof S["Requests"]] | { key: null; data: unknown; } : { key: null; data: unknown; }; /** * Helper type that creates a union of all possible client message event payloads. * This allows TypeScript to narrow the data type based on the message key. */ type ClientMessageEventPayload = S["Messages"] extends Record ? { [K in MessageKeys]: { channel: string | null; key: K; data: MessageData; } }[MessageKeys] | { channel: string | null; key: null; data: unknown; } : { channel: string | null; key: null; data: unknown; }; //#region src/client/channel.d.ts interface ChannelOptions> { client: WebSocketClient; name: string; } declare class Channel> { /** * Unique name of the Channel. */ readonly name: string; /** * Reference to the `WebSocketClient` instance that the Channel belongs to. */ readonly client: WebSocketClient; /** * Whether this Channel is currently active (joined) on the Server. */ active: boolean; constructor(opts: ChannelOptions); /** * Send a Message to this Channel. */ readonly send: >(params: K extends never ? { key?: null; data: unknown; } : { key: K; data: MessageData; }) => Promise; } //#endregion //#region src/client/events.d.ts /** * Map of events emitted by the `WebSocketClient`. * * Public events are emitted after processing to indicate that operations have * completed successfully. These events fire after handlers and business logic * have been invoked, confirming the success of the operation. */ type WebSocketClientEvents> = { /** * Emitted when the Client has successfully connected to the remote * `WebSocketServer` and completed the Handshake. */ connect: unknown; /** * Emitted when the Client has closed the Connection to the * remote `WebSocketServer`. */ disconnect: unknown; /** * Emitted after the Client has successfully joined a Channel. */ join: Channel; /** * Emitted after the Client has successfully left a Channel. */ leave: Channel; /** * Emitted after a Message has been received from the remote `WebSocketServer`. */ message: ClientMessageEventPayload; }; //#endregion //#region src/client/internal.d.ts /** * Map of internal events emitted by the `WebSocketClient`. * * Most internal events are intentionally emitted before processing to provide * raw, protocol-level observability and debuggability. */ type WebSocketClientInternalEvents = { /** * Emitted when a Connection to the remote `WebSocketServer` is opened. */ open: unknown; /** * Emitted when a Connection to the remote `WebSocketServer` is closed. */ close: unknown; /** * Emitted when the `WebSocketClient` has successfully completed the Handshake * with the remote `WebSocketServer`. */ handshake: HandshakeResponseMessage; /** * Emitted for any WebSocket message received from the remote `WebSocketServer`. */ message: ServerMessage; /** * Emitted when a Response is received from the remote `WebSocketServer`. */ response: { /** * Unique ID of the Request the Response is for. */ req: string; /** * Data of the Response. */ data: unknown; /** * Error of the Response. */ error: { name: string; message: string; } | null; }; /** * Emitted when a Connection attempt to the remote `WebSocketServer` is made. */ attempt: { attempt: number; delay: number; }; /** * Emitted when an error occurs during the Connection with the remote * `WebSocketServer`. * * This event is only emitted for asynchronous/background errors (message * parsing, pulse timeouts, unexpected disconnections). * * Errors from explicit operations like `connect()`, `join()`, or * `request()` are communicated through promise rejections only. */ error: Error; }; /** * Internal `EventEmitter` instance used to distribute internal events. */ declare class WebSocketClientInternal { private readonly emitter; readonly on: (event: K, listener: Listener) => void; readonly off: (event: K, listener: Listener) => void; readonly emit: (event: K, payload: WebSocketClientInternalEvents[K]) => void; } //#endregion //#region src/client/index.d.ts interface WebSocketClientConfig> { /** * URL of the `WebSocketServer` to connect to. */ url: string; /** * Optional Error handler function. Invoked when asynchronous/background * errors occur during the Connection with the `WebSocketServer`. * * This handler is only invoked for asynchronous/background errors (message * parsing, pulse timeouts, unexpected disconnections). * * Errors from explicit operations like `connect()`, `join()`, or * `request()` are communicated through promise rejections only. * * @default console.error */ onError?: (props: { error: Error; }) => void; /** * Optional Request handler function. Invoked when the `WebSocketServer` * sends a Request to the Client. * * If the handler returns or resolves, a `SuccessfulResponseMessage` is * returned to the Server with the returned data. * * If the handler throws or rejects, a `FailedResponseMessage` is returned to * the Server. * * If no handler is provided, a `RequestHandlerNotFoundError` is returned to * the Server for any Requests. * * @default undefined */ handleRequest?: (props: RequestHandlerProps) => unknown | Promise; /** * Connection configuration options. */ connection?: { /** * Maximum number of connection retry attempts. * * @default 8 */ maxRetries?: number; }; } declare class WebSocketClient> { /** * URL of the `WebSocketServer` to connect to. */ private readonly url; /** * Error handler function. Called whenever an error occurs. */ private readonly onError; /** * Request handler function. Called when the server sends a request. */ private readonly handleRequest?; /** * Maximum number of connection retry attempts. */ private readonly maxRetries; /** * Public `EventEmitter` instance used to distribute user-facing events. */ readonly emitter: Emitter>; /** * Internal `EventEmitter` instance used to distribute internal events. */ readonly internal: WebSocketClientInternal; /** * Reference to the raw `WebSocket` instance. */ ws: WebSocket | null; /** * Internal timer used to send a `PulseMessage` to the remote * `WebSocketServer` if no other message was sent within the Pulse interval * shared by the remote `WebSocketServer` during the Handshake. */ private pulseTimer; /** * Internal timer used to abort the connection if no message was received * within the Pulse interval and the timeout threshold shared by the remote * `WebSocketServer` during the Handshake. */ private pulseTimeout; /** * Internal timer used to schedule reconnection attempts after connection loss. */ private reconnectTimer; /** * Pulse configuration negotiated during handshake. */ private pulseInterval; private pulseThreshold; /** * Reference to the parameters initially passed to the `connect` method. * * Required when reconnecting the `WebSocketClient` after the connection has * been lost. */ private handshakeParams; /** * Current state of the client. Derived directly from the underlying * `WebSocket` instance. */ get state(): "connecting" | "connected" | "disconnecting" | "disconnected"; private readonly pending; readonly channels: Map>; constructor(config: WebSocketClientConfig); /** * WebSocket `message` event handler. * * If the raw message cannot be parsed or does not satisfy the expected * structure, an error is logged and the message is ignored. * * @param event Message event. */ private readonly handleSocketMessage; /** * WebSocket `error` event handler. * * @param event Error event. */ private readonly handleSocketError; private readonly schedulePulse; private readonly resetPulseTimeout; private readonly rejectAllPending; private readonly handshake; private readonly sendMessage; readonly connect: (params?: HandshakeParams) => Promise>; readonly disconnect: (reconnect?: boolean) => Promise; readonly join: (channel: string, params?: JoinParams) => Promise>; readonly leave: (channel: string, params?: LeaveParams) => Promise; readonly send: >(params: K extends never ? { key?: null; data: unknown; channel?: string | null; } : { key: K; data: MessageData; channel?: string | null; }) => Promise; readonly request: >(params: K extends never ? { key?: null; data?: unknown; timeout?: number; } : RequestParams) => Promise>; /** * Register a new event listener. * * @param event Name of the event to listen for. * @param listener Function to call when the event is emitted. * * @returns `this` to allow chaining. */ on>(event: K, listener: Listener, K>): this; /** * Remove an event listener. * * @param event Name of the event to remove the listener from. * @param listener Function to remove from the event. * * @returns `this` to allow chaining. */ off>(event: K, listener: Listener, K>): this; /** * Destroy the client and clean up all resources. * * This method must be manually called to prevent memory leaks. * * It unsubscribes event handlers, disconnects the socket, rejects all pending * operations, and clears all channels. * * @returns Promise resolving when the client has been destroyed. */ readonly destroy: () => Promise; } export { WebSocketClient as W }; export type { Protocol as P };