@panyam/servicekit-client 0.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.ts ADDED
@@ -0,0 +1,81 @@
1
+ /**
2
+ * @panyam/servicekit-client
3
+ *
4
+ * TypeScript client library for ServiceKit WebSocket protocols.
5
+ *
6
+ * ## Architecture
7
+ *
8
+ * The client mirrors the server-side architecture with two layers:
9
+ * - **Transport layer**: Handles WebSocket connection, ping/pong heartbeats
10
+ * - **Codec layer**: Handles encoding/decoding of data messages
11
+ *
12
+ * Control messages (ping, pong, error) are always JSON at the transport layer,
13
+ * while data messages use the configured codec (JSON, binary protobuf, etc.).
14
+ *
15
+ * ## Clients
16
+ *
17
+ * - `BaseWSClient`: Low-level WebSocket with auto ping/pong (for http/JSONConn)
18
+ * - `GRPCWSClient`: gRPC-style streaming with envelope protocol (for grpcws)
19
+ * - `TypedGRPCWSClient`: Type-safe wrapper for GRPCWSClient
20
+ *
21
+ * ## Codecs
22
+ *
23
+ * - `JSONCodec`: Default, matches server-side JSONCodec
24
+ * - `BinaryCodec`: For binary protobuf, matches server-side BinaryProtoCodec
25
+ *
26
+ * @example Basic WebSocket with JSON (default)
27
+ * ```typescript
28
+ * import { BaseWSClient } from '@panyam/servicekit-client';
29
+ *
30
+ * const client = new BaseWSClient();
31
+ * client.onMessage = (data) => console.log('Received:', data);
32
+ * await client.connect('ws://localhost:8080/ws');
33
+ * client.send({ hello: 'world' });
34
+ * ```
35
+ *
36
+ * @example Binary Protobuf Protocol
37
+ * ```typescript
38
+ * import { BaseWSClient, BinaryCodec } from '@panyam/servicekit-client';
39
+ * import { MyMessage } from './gen/my_pb';
40
+ *
41
+ * const codec = new BinaryCodec<MyMessage, MyMessage>(
42
+ * (data) => MyMessage.decode(new Uint8Array(data)),
43
+ * (msg) => MyMessage.encode(msg).finish()
44
+ * );
45
+ * const client = new BaseWSClient({ codec });
46
+ * client.onMessage = (msg) => console.log('Received:', msg);
47
+ * await client.connect('ws://localhost:8080/ws');
48
+ * ```
49
+ *
50
+ * @example gRPC-WebSocket Streaming
51
+ * ```typescript
52
+ * import { GRPCWSClient } from '@panyam/servicekit-client';
53
+ *
54
+ * const client = new GRPCWSClient();
55
+ * client.onMessage = (data) => console.log('Event:', data);
56
+ * client.onStreamEnd = () => console.log('Done');
57
+ * await client.connect('ws://localhost:8080/ws/v1/subscribe');
58
+ * ```
59
+ *
60
+ * @packageDocumentation
61
+ */
62
+
63
+ // Types and Codecs
64
+ export {
65
+ MessageType,
66
+ ControlMessage,
67
+ ReadyState,
68
+ ReadyStateType,
69
+ ClientOptions,
70
+ Codec,
71
+ JSONCodec,
72
+ BinaryCodec,
73
+ MessageHandler,
74
+ ErrorHandler,
75
+ VoidHandler,
76
+ } from './types';
77
+
78
+ // Clients
79
+ export { BaseWSClient } from './base-client';
80
+ export { GRPCWSClient } from './grpcws-client';
81
+ export { TypedGRPCWSClient } from './typed-client';
@@ -0,0 +1,150 @@
1
+ /**
2
+ * TypedGRPCWSClient - Type-safe wrapper for GRPCWSClient.
3
+ *
4
+ * This wrapper provides compile-time type safety for protobuf messages.
5
+ * Use with types generated by any TypeScript protoc plugin:
6
+ * - @bufbuild/protobuf
7
+ * - protobuf-ts
8
+ * - ts-proto
9
+ * - etc.
10
+ */
11
+
12
+ import { GRPCWSClient } from './grpcws-client';
13
+ import { ClientOptions, VoidHandler, ErrorHandler } from './types';
14
+
15
+ /**
16
+ * Type-safe gRPC-WebSocket client with generic input/output types.
17
+ *
18
+ * This wrapper enforces type safety at compile time by parameterizing
19
+ * the send and receive message types. Use with your protobuf-generated
20
+ * TypeScript types.
21
+ *
22
+ * @typeParam TIn - The type of messages sent to the server
23
+ * @typeParam TOut - The type of messages received from the server
24
+ *
25
+ * @example With @bufbuild/protobuf types
26
+ * ```typescript
27
+ * import { PlayerAction, GameState } from './gen/game_pb';
28
+ *
29
+ * const client = new TypedGRPCWSClient<PlayerAction, GameState>();
30
+ * client.onMessage = (state: GameState) => {
31
+ * console.log('Players:', state.players);
32
+ * };
33
+ * await client.connect('ws://localhost:8080/ws/v1/sync');
34
+ * client.send({ actionId: '1', move: { x: 10, y: 20 } });
35
+ * ```
36
+ *
37
+ * @example With ts-proto types
38
+ * ```typescript
39
+ * import { GameCommand, CommandSummary } from './gen/game';
40
+ *
41
+ * const client = new TypedGRPCWSClient<GameCommand, CommandSummary>();
42
+ * client.onMessage = (summary: CommandSummary) => {
43
+ * console.log(`Executed ${summary.commandsExecuted} commands`);
44
+ * };
45
+ * await client.connect('ws://localhost:8080/ws/v1/commands');
46
+ * client.send({ commandId: '1', commandType: 'move' });
47
+ * client.endSend();
48
+ * ```
49
+ */
50
+ export class TypedGRPCWSClient<TIn, TOut> {
51
+ private client: GRPCWSClient;
52
+
53
+ /** Called when a typed message is received */
54
+ public onMessage: (data: TOut) => void = () => {};
55
+
56
+ /** Called when the stream ends normally */
57
+ public onStreamEnd: VoidHandler = () => {};
58
+
59
+ /** Called when the server sends an error */
60
+ public onError: ErrorHandler = () => {};
61
+
62
+ /** Called when the connection closes */
63
+ public onClose: VoidHandler = () => {};
64
+
65
+ /** Called when a ping is received */
66
+ public onPing: (pingId: number) => void = () => {};
67
+
68
+ constructor(options: ClientOptions = {}) {
69
+ this.client = new GRPCWSClient(options);
70
+ this.setupHandlers();
71
+ }
72
+
73
+ /**
74
+ * Connect to a grpcws WebSocket server.
75
+ * @param url The WebSocket URL to connect to
76
+ * @returns Promise that resolves when connected
77
+ */
78
+ connect(url: string): Promise<void> {
79
+ return this.client.connect(url);
80
+ }
81
+
82
+ /**
83
+ * Send a typed message to the server.
84
+ * @param data The typed data payload to send
85
+ */
86
+ send(data: TIn): void {
87
+ this.client.send(data);
88
+ }
89
+
90
+ /**
91
+ * Signal that the client is done sending (half-close).
92
+ */
93
+ endSend(): void {
94
+ this.client.endSend();
95
+ }
96
+
97
+ /**
98
+ * Cancel the stream.
99
+ */
100
+ cancel(): void {
101
+ this.client.cancel();
102
+ }
103
+
104
+ /**
105
+ * Close the WebSocket connection.
106
+ */
107
+ close(): void {
108
+ this.client.close();
109
+ }
110
+
111
+ /**
112
+ * Check if the client is connected.
113
+ */
114
+ get isConnected(): boolean {
115
+ return this.client.isConnected;
116
+ }
117
+
118
+ /**
119
+ * Get the WebSocket ready state.
120
+ */
121
+ get readyState(): number {
122
+ return this.client.readyState;
123
+ }
124
+
125
+ /**
126
+ * Set up handlers to forward events with proper typing.
127
+ */
128
+ private setupHandlers(): void {
129
+ this.client.onMessage = (data: unknown) => {
130
+ // Cast to TOut - the protobuf JSON matches the TypeScript type
131
+ this.onMessage(data as TOut);
132
+ };
133
+
134
+ this.client.onStreamEnd = () => {
135
+ this.onStreamEnd();
136
+ };
137
+
138
+ this.client.onError = (error: string) => {
139
+ this.onError(error);
140
+ };
141
+
142
+ this.client.onClose = () => {
143
+ this.onClose();
144
+ };
145
+
146
+ this.client.onPing = (pingId: number) => {
147
+ this.onPing(pingId);
148
+ };
149
+ }
150
+ }
package/src/types.ts ADDED
@@ -0,0 +1,167 @@
1
+ /**
2
+ * Protocol types for the gRPC-WebSocket streaming protocol.
3
+ *
4
+ * These types define the JSON envelope format used for communication
5
+ * between the client and server over WebSocket.
6
+ */
7
+
8
+ /**
9
+ * Message types used in the control envelope.
10
+ *
11
+ * - `data`: Contains a protobuf message as JSON payload
12
+ * - `error`: Server-side error notification
13
+ * - `stream_end`: Indicates the stream has completed
14
+ * - `ping`: Server heartbeat request
15
+ * - `pong`: Client heartbeat response
16
+ * - `cancel`: Client requests stream cancellation
17
+ * - `end_send`: Client signals done sending (half-close)
18
+ */
19
+ export type MessageType =
20
+ | 'data'
21
+ | 'error'
22
+ | 'stream_end'
23
+ | 'ping'
24
+ | 'pong'
25
+ | 'cancel'
26
+ | 'end_send';
27
+
28
+ /**
29
+ * Control message envelope used for all WebSocket communication.
30
+ *
31
+ * All messages are JSON objects with a `type` field indicating the message kind.
32
+ * Additional fields depend on the message type:
33
+ * - `data` messages include a `data` field with the payload
34
+ * - `error` messages include an `error` field with the error description
35
+ * - `ping`/`pong` messages include a `pingId` field for correlation
36
+ */
37
+ export interface ControlMessage {
38
+ /** The type of control message */
39
+ type: MessageType;
40
+ /** Payload data for 'data' messages (protobuf as JSON) */
41
+ data?: unknown;
42
+ /** Error description for 'error' messages */
43
+ error?: string;
44
+ /** Ping/pong identifier for heartbeat correlation */
45
+ pingId?: number;
46
+ }
47
+
48
+ /**
49
+ * WebSocket ready state constants.
50
+ * Mirrors the WebSocket.readyState values.
51
+ */
52
+ export const ReadyState = {
53
+ CONNECTING: 0,
54
+ OPEN: 1,
55
+ CLOSING: 2,
56
+ CLOSED: 3,
57
+ } as const;
58
+
59
+ export type ReadyStateType = (typeof ReadyState)[keyof typeof ReadyState];
60
+
61
+ /**
62
+ * Options for configuring the BaseWSClient.
63
+ */
64
+ export interface ClientOptions<I = unknown, O = unknown> {
65
+ /**
66
+ * Whether to automatically respond to ping messages.
67
+ * Default: true
68
+ */
69
+ autoPong?: boolean;
70
+
71
+ /**
72
+ * Custom WebSocket implementation (for Node.js or testing).
73
+ * Default: globalThis.WebSocket
74
+ */
75
+ WebSocket?: typeof WebSocket;
76
+
77
+ /**
78
+ * Codec for encoding/decoding data messages.
79
+ * Default: JSONCodec (matches server-side JSONCodec)
80
+ */
81
+ codec?: Codec<I, O>;
82
+ }
83
+
84
+ /**
85
+ * Event handler types for the client.
86
+ */
87
+ export type MessageHandler<T = unknown> = (data: T) => void;
88
+ export type ErrorHandler = (error: string) => void;
89
+ export type VoidHandler = () => void;
90
+
91
+ /**
92
+ * Codec interface for encoding/decoding data messages.
93
+ * This mirrors the server-side Codec interface.
94
+ *
95
+ * Note: Control messages (ping/pong/error) are handled at the transport layer
96
+ * and always use JSON. The codec only handles business data messages.
97
+ */
98
+ export interface Codec<I = unknown, O = unknown> {
99
+ /**
100
+ * Decode incoming data from the server.
101
+ * @param data Raw data from WebSocket (string for text frames, ArrayBuffer for binary)
102
+ * @returns Decoded message of type I
103
+ */
104
+ decode(data: string | ArrayBuffer): I;
105
+
106
+ /**
107
+ * Encode outgoing data to send to the server.
108
+ * @param msg Message to encode
109
+ * @returns Encoded data (string for text, ArrayBuffer for binary)
110
+ */
111
+ encode(msg: O): string | ArrayBuffer;
112
+ }
113
+
114
+ /**
115
+ * JSON codec - encodes/decodes messages as JSON.
116
+ * This is the default codec, matching server-side JSONCodec.
117
+ */
118
+ export class JSONCodec<I = unknown, O = unknown> implements Codec<I, O> {
119
+ decode(data: string | ArrayBuffer): I {
120
+ if (typeof data === 'string') {
121
+ return JSON.parse(data) as I;
122
+ }
123
+ // ArrayBuffer -> string -> JSON
124
+ const text = new TextDecoder().decode(data);
125
+ return JSON.parse(text) as I;
126
+ }
127
+
128
+ encode(msg: O): string {
129
+ return JSON.stringify(msg);
130
+ }
131
+ }
132
+
133
+ /**
134
+ * Binary protobuf codec - for use with server-side BinaryProtoCodec.
135
+ *
136
+ * Users provide their own encode/decode functions from their protobuf library.
137
+ * Works with any TS protoc plugin (@bufbuild/protobuf, ts-proto, protobuf-ts).
138
+ *
139
+ * @example
140
+ * ```typescript
141
+ * import { MyMessage } from './gen/my_pb';
142
+ *
143
+ * const codec = new BinaryCodec<MyMessage, MyMessage>(
144
+ * (data) => MyMessage.decode(new Uint8Array(data)),
145
+ * (msg) => MyMessage.encode(msg).finish()
146
+ * );
147
+ * ```
148
+ */
149
+ export class BinaryCodec<I, O> implements Codec<I, O> {
150
+ constructor(
151
+ private decodeFunc: (data: ArrayBuffer) => I,
152
+ private encodeFunc: (msg: O) => Uint8Array
153
+ ) {}
154
+
155
+ decode(data: string | ArrayBuffer): I {
156
+ if (typeof data === 'string') {
157
+ throw new Error('BinaryCodec received text data, expected binary');
158
+ }
159
+ return this.decodeFunc(data);
160
+ }
161
+
162
+ encode(msg: O): ArrayBuffer {
163
+ const encoded = this.encodeFunc(msg);
164
+ // Ensure we return a proper ArrayBuffer (not SharedArrayBuffer)
165
+ return encoded.buffer.slice(encoded.byteOffset, encoded.byteOffset + encoded.byteLength) as ArrayBuffer;
166
+ }
167
+ }