@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.
@@ -0,0 +1,127 @@
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
+ * Message types used in the control envelope.
9
+ *
10
+ * - `data`: Contains a protobuf message as JSON payload
11
+ * - `error`: Server-side error notification
12
+ * - `stream_end`: Indicates the stream has completed
13
+ * - `ping`: Server heartbeat request
14
+ * - `pong`: Client heartbeat response
15
+ * - `cancel`: Client requests stream cancellation
16
+ * - `end_send`: Client signals done sending (half-close)
17
+ */
18
+ export type MessageType = 'data' | 'error' | 'stream_end' | 'ping' | 'pong' | 'cancel' | 'end_send';
19
+ /**
20
+ * Control message envelope used for all WebSocket communication.
21
+ *
22
+ * All messages are JSON objects with a `type` field indicating the message kind.
23
+ * Additional fields depend on the message type:
24
+ * - `data` messages include a `data` field with the payload
25
+ * - `error` messages include an `error` field with the error description
26
+ * - `ping`/`pong` messages include a `pingId` field for correlation
27
+ */
28
+ export interface ControlMessage {
29
+ /** The type of control message */
30
+ type: MessageType;
31
+ /** Payload data for 'data' messages (protobuf as JSON) */
32
+ data?: unknown;
33
+ /** Error description for 'error' messages */
34
+ error?: string;
35
+ /** Ping/pong identifier for heartbeat correlation */
36
+ pingId?: number;
37
+ }
38
+ /**
39
+ * WebSocket ready state constants.
40
+ * Mirrors the WebSocket.readyState values.
41
+ */
42
+ export declare const ReadyState: {
43
+ readonly CONNECTING: 0;
44
+ readonly OPEN: 1;
45
+ readonly CLOSING: 2;
46
+ readonly CLOSED: 3;
47
+ };
48
+ export type ReadyStateType = (typeof ReadyState)[keyof typeof ReadyState];
49
+ /**
50
+ * Options for configuring the BaseWSClient.
51
+ */
52
+ export interface ClientOptions<I = unknown, O = unknown> {
53
+ /**
54
+ * Whether to automatically respond to ping messages.
55
+ * Default: true
56
+ */
57
+ autoPong?: boolean;
58
+ /**
59
+ * Custom WebSocket implementation (for Node.js or testing).
60
+ * Default: globalThis.WebSocket
61
+ */
62
+ WebSocket?: typeof WebSocket;
63
+ /**
64
+ * Codec for encoding/decoding data messages.
65
+ * Default: JSONCodec (matches server-side JSONCodec)
66
+ */
67
+ codec?: Codec<I, O>;
68
+ }
69
+ /**
70
+ * Event handler types for the client.
71
+ */
72
+ export type MessageHandler<T = unknown> = (data: T) => void;
73
+ export type ErrorHandler = (error: string) => void;
74
+ export type VoidHandler = () => void;
75
+ /**
76
+ * Codec interface for encoding/decoding data messages.
77
+ * This mirrors the server-side Codec interface.
78
+ *
79
+ * Note: Control messages (ping/pong/error) are handled at the transport layer
80
+ * and always use JSON. The codec only handles business data messages.
81
+ */
82
+ export interface Codec<I = unknown, O = unknown> {
83
+ /**
84
+ * Decode incoming data from the server.
85
+ * @param data Raw data from WebSocket (string for text frames, ArrayBuffer for binary)
86
+ * @returns Decoded message of type I
87
+ */
88
+ decode(data: string | ArrayBuffer): I;
89
+ /**
90
+ * Encode outgoing data to send to the server.
91
+ * @param msg Message to encode
92
+ * @returns Encoded data (string for text, ArrayBuffer for binary)
93
+ */
94
+ encode(msg: O): string | ArrayBuffer;
95
+ }
96
+ /**
97
+ * JSON codec - encodes/decodes messages as JSON.
98
+ * This is the default codec, matching server-side JSONCodec.
99
+ */
100
+ export declare class JSONCodec<I = unknown, O = unknown> implements Codec<I, O> {
101
+ decode(data: string | ArrayBuffer): I;
102
+ encode(msg: O): string;
103
+ }
104
+ /**
105
+ * Binary protobuf codec - for use with server-side BinaryProtoCodec.
106
+ *
107
+ * Users provide their own encode/decode functions from their protobuf library.
108
+ * Works with any TS protoc plugin (@bufbuild/protobuf, ts-proto, protobuf-ts).
109
+ *
110
+ * @example
111
+ * ```typescript
112
+ * import { MyMessage } from './gen/my_pb';
113
+ *
114
+ * const codec = new BinaryCodec<MyMessage, MyMessage>(
115
+ * (data) => MyMessage.decode(new Uint8Array(data)),
116
+ * (msg) => MyMessage.encode(msg).finish()
117
+ * );
118
+ * ```
119
+ */
120
+ export declare class BinaryCodec<I, O> implements Codec<I, O> {
121
+ private decodeFunc;
122
+ private encodeFunc;
123
+ constructor(decodeFunc: (data: ArrayBuffer) => I, encodeFunc: (msg: O) => Uint8Array);
124
+ decode(data: string | ArrayBuffer): I;
125
+ encode(msg: O): ArrayBuffer;
126
+ }
127
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH;;;;;;;;;;GAUG;AACH,MAAM,MAAM,WAAW,GACnB,MAAM,GACN,OAAO,GACP,YAAY,GACZ,MAAM,GACN,MAAM,GACN,QAAQ,GACR,UAAU,CAAC;AAEf;;;;;;;;GAQG;AACH,MAAM,WAAW,cAAc;IAC7B,kCAAkC;IAClC,IAAI,EAAE,WAAW,CAAC;IAClB,0DAA0D;IAC1D,IAAI,CAAC,EAAE,OAAO,CAAC;IACf,6CAA6C;IAC7C,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,qDAAqD;IACrD,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED;;;GAGG;AACH,eAAO,MAAM,UAAU;;;;;CAKb,CAAC;AAEX,MAAM,MAAM,cAAc,GAAG,CAAC,OAAO,UAAU,CAAC,CAAC,MAAM,OAAO,UAAU,CAAC,CAAC;AAE1E;;GAEG;AACH,MAAM,WAAW,aAAa,CAAC,CAAC,GAAG,OAAO,EAAE,CAAC,GAAG,OAAO;IACrD;;;OAGG;IACH,QAAQ,CAAC,EAAE,OAAO,CAAC;IAEnB;;;OAGG;IACH,SAAS,CAAC,EAAE,OAAO,SAAS,CAAC;IAE7B;;;OAGG;IACH,KAAK,CAAC,EAAE,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;CACrB;AAED;;GAEG;AACH,MAAM,MAAM,cAAc,CAAC,CAAC,GAAG,OAAO,IAAI,CAAC,IAAI,EAAE,CAAC,KAAK,IAAI,CAAC;AAC5D,MAAM,MAAM,YAAY,GAAG,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC;AACnD,MAAM,MAAM,WAAW,GAAG,MAAM,IAAI,CAAC;AAErC;;;;;;GAMG;AACH,MAAM,WAAW,KAAK,CAAC,CAAC,GAAG,OAAO,EAAE,CAAC,GAAG,OAAO;IAC7C;;;;OAIG;IACH,MAAM,CAAC,IAAI,EAAE,MAAM,GAAG,WAAW,GAAG,CAAC,CAAC;IAEtC;;;;OAIG;IACH,MAAM,CAAC,GAAG,EAAE,CAAC,GAAG,MAAM,GAAG,WAAW,CAAC;CACtC;AAED;;;GAGG;AACH,qBAAa,SAAS,CAAC,CAAC,GAAG,OAAO,EAAE,CAAC,GAAG,OAAO,CAAE,YAAW,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC;IACrE,MAAM,CAAC,IAAI,EAAE,MAAM,GAAG,WAAW,GAAG,CAAC;IASrC,MAAM,CAAC,GAAG,EAAE,CAAC,GAAG,MAAM;CAGvB;AAED;;;;;;;;;;;;;;;GAeG;AACH,qBAAa,WAAW,CAAC,CAAC,EAAE,CAAC,CAAE,YAAW,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC;IAEjD,OAAO,CAAC,UAAU;IAClB,OAAO,CAAC,UAAU;gBADV,UAAU,EAAE,CAAC,IAAI,EAAE,WAAW,KAAK,CAAC,EACpC,UAAU,EAAE,CAAC,GAAG,EAAE,CAAC,KAAK,UAAU;IAG5C,MAAM,CAAC,IAAI,EAAE,MAAM,GAAG,WAAW,GAAG,CAAC;IAOrC,MAAM,CAAC,GAAG,EAAE,CAAC,GAAG,WAAW;CAK5B"}
package/dist/types.js ADDED
@@ -0,0 +1,72 @@
1
+ "use strict";
2
+ /**
3
+ * Protocol types for the gRPC-WebSocket streaming protocol.
4
+ *
5
+ * These types define the JSON envelope format used for communication
6
+ * between the client and server over WebSocket.
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.BinaryCodec = exports.JSONCodec = exports.ReadyState = void 0;
10
+ /**
11
+ * WebSocket ready state constants.
12
+ * Mirrors the WebSocket.readyState values.
13
+ */
14
+ exports.ReadyState = {
15
+ CONNECTING: 0,
16
+ OPEN: 1,
17
+ CLOSING: 2,
18
+ CLOSED: 3,
19
+ };
20
+ /**
21
+ * JSON codec - encodes/decodes messages as JSON.
22
+ * This is the default codec, matching server-side JSONCodec.
23
+ */
24
+ class JSONCodec {
25
+ decode(data) {
26
+ if (typeof data === 'string') {
27
+ return JSON.parse(data);
28
+ }
29
+ // ArrayBuffer -> string -> JSON
30
+ const text = new TextDecoder().decode(data);
31
+ return JSON.parse(text);
32
+ }
33
+ encode(msg) {
34
+ return JSON.stringify(msg);
35
+ }
36
+ }
37
+ exports.JSONCodec = JSONCodec;
38
+ /**
39
+ * Binary protobuf codec - for use with server-side BinaryProtoCodec.
40
+ *
41
+ * Users provide their own encode/decode functions from their protobuf library.
42
+ * Works with any TS protoc plugin (@bufbuild/protobuf, ts-proto, protobuf-ts).
43
+ *
44
+ * @example
45
+ * ```typescript
46
+ * import { MyMessage } from './gen/my_pb';
47
+ *
48
+ * const codec = new BinaryCodec<MyMessage, MyMessage>(
49
+ * (data) => MyMessage.decode(new Uint8Array(data)),
50
+ * (msg) => MyMessage.encode(msg).finish()
51
+ * );
52
+ * ```
53
+ */
54
+ class BinaryCodec {
55
+ constructor(decodeFunc, encodeFunc) {
56
+ this.decodeFunc = decodeFunc;
57
+ this.encodeFunc = encodeFunc;
58
+ }
59
+ decode(data) {
60
+ if (typeof data === 'string') {
61
+ throw new Error('BinaryCodec received text data, expected binary');
62
+ }
63
+ return this.decodeFunc(data);
64
+ }
65
+ encode(msg) {
66
+ const encoded = this.encodeFunc(msg);
67
+ // Ensure we return a proper ArrayBuffer (not SharedArrayBuffer)
68
+ return encoded.buffer.slice(encoded.byteOffset, encoded.byteOffset + encoded.byteLength);
69
+ }
70
+ }
71
+ exports.BinaryCodec = BinaryCodec;
72
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;;;AA0CH;;;GAGG;AACU,QAAA,UAAU,GAAG;IACxB,UAAU,EAAE,CAAC;IACb,IAAI,EAAE,CAAC;IACP,OAAO,EAAE,CAAC;IACV,MAAM,EAAE,CAAC;CACD,CAAC;AAyDX;;;GAGG;AACH,MAAa,SAAS;IACpB,MAAM,CAAC,IAA0B;QAC/B,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE,CAAC;YAC7B,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAM,CAAC;QAC/B,CAAC;QACD,gCAAgC;QAChC,MAAM,IAAI,GAAG,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;QAC5C,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAM,CAAC;IAC/B,CAAC;IAED,MAAM,CAAC,GAAM;QACX,OAAO,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC;IAC7B,CAAC;CACF;AAbD,8BAaC;AAED;;;;;;;;;;;;;;;GAeG;AACH,MAAa,WAAW;IACtB,YACU,UAAoC,EACpC,UAAkC;QADlC,eAAU,GAAV,UAAU,CAA0B;QACpC,eAAU,GAAV,UAAU,CAAwB;IACzC,CAAC;IAEJ,MAAM,CAAC,IAA0B;QAC/B,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE,CAAC;YAC7B,MAAM,IAAI,KAAK,CAAC,iDAAiD,CAAC,CAAC;QACrE,CAAC;QACD,OAAO,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;IAC/B,CAAC;IAED,MAAM,CAAC,GAAM;QACX,MAAM,OAAO,GAAG,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC;QACrC,gEAAgE;QAChE,OAAO,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,UAAU,EAAE,OAAO,CAAC,UAAU,GAAG,OAAO,CAAC,UAAU,CAAgB,CAAC;IAC1G,CAAC;CACF;AAlBD,kCAkBC"}
package/package.json ADDED
@@ -0,0 +1,41 @@
1
+ {
2
+ "name": "@panyam/servicekit-client",
3
+ "version": "0.0.4",
4
+ "description": "TypeScript client for gRPC-WebSocket streaming protocol",
5
+ "main": "dist/index.js",
6
+ "module": "dist/index.mjs",
7
+ "types": "dist/index.d.ts",
8
+ "browser": "dist/servicekit-client.browser.js",
9
+ "files": [
10
+ "dist",
11
+ "src"
12
+ ],
13
+ "scripts": {
14
+ "build": "tsc && npm run build:browser",
15
+ "build:browser": "esbuild src/index.ts --bundle --format=iife --global-name=ServiceKit --outfile=dist/servicekit-client.browser.js",
16
+ "clean": "rm -rf dist",
17
+ "prepublishOnly": "npm run build"
18
+ },
19
+ "keywords": [
20
+ "grpc",
21
+ "websocket",
22
+ "streaming",
23
+ "protobuf",
24
+ "typescript",
25
+ "servicekit"
26
+ ],
27
+ "author": "panyam",
28
+ "license": "MIT",
29
+ "repository": {
30
+ "type": "git",
31
+ "url": "https://github.com/panyam/servicekit.git",
32
+ "directory": "clients/typescript"
33
+ },
34
+ "devDependencies": {
35
+ "esbuild": "^0.24.0",
36
+ "typescript": "^5.3.0"
37
+ },
38
+ "engines": {
39
+ "node": ">=16.0.0"
40
+ }
41
+ }
@@ -0,0 +1,234 @@
1
+ /**
2
+ * BaseWSClient - Low-level WebSocket client with automatic ping/pong handling.
3
+ *
4
+ * This client handles the connection lifecycle and heartbeat mechanism.
5
+ * It sends and receives raw JSON messages without any envelope wrapping.
6
+ *
7
+ * Use this directly for http/JSONConn servers, or as the base for GRPCWSClient.
8
+ */
9
+
10
+ import {
11
+ ControlMessage,
12
+ ClientOptions,
13
+ Codec,
14
+ JSONCodec,
15
+ MessageHandler,
16
+ ErrorHandler,
17
+ VoidHandler,
18
+ ReadyState,
19
+ } from './types';
20
+
21
+ /**
22
+ * Base WebSocket client with automatic ping/pong heartbeat handling.
23
+ *
24
+ * Features:
25
+ * - Automatic ping/pong response (keeps connection alive)
26
+ * - Promise-based connect()
27
+ * - Event handlers for messages, errors, and close
28
+ * - Connection state tracking
29
+ *
30
+ * @example
31
+ * ```typescript
32
+ * const client = new BaseWSClient();
33
+ * client.onMessage = (data) => console.log('Received:', data);
34
+ * client.onClose = () => console.log('Disconnected');
35
+ * await client.connect('ws://localhost:8080/ws');
36
+ * client.send({ hello: 'world' });
37
+ * ```
38
+ */
39
+ export class BaseWSClient<I = unknown, O = unknown> {
40
+ private ws: WebSocket | null = null;
41
+ private _codec: Codec<I, O>;
42
+ private _autoPong: boolean;
43
+ private _WebSocket: typeof WebSocket;
44
+
45
+ /** Called when a data message is received (decoded by codec) */
46
+ public onMessage: MessageHandler<I> = () => {};
47
+
48
+ /** Called when a ping is received (after auto-pong if enabled) */
49
+ public onPing: (pingId: number) => void = () => {};
50
+
51
+ /** Called when the connection closes */
52
+ public onClose: VoidHandler = () => {};
53
+
54
+ /** Called when a WebSocket error occurs */
55
+ public onError: ErrorHandler = () => {};
56
+
57
+ constructor(options: ClientOptions<I, O> = {}) {
58
+ this._autoPong = options.autoPong ?? true;
59
+ this._WebSocket = options.WebSocket ?? globalThis.WebSocket;
60
+ this._codec = options.codec ?? (new JSONCodec() as unknown as Codec<I, O>);
61
+ }
62
+
63
+ /** Get the codec used for encoding/decoding data messages */
64
+ get codec(): Codec<I, O> {
65
+ return this._codec;
66
+ }
67
+
68
+ /**
69
+ * Connect to a WebSocket server.
70
+ * @param url The WebSocket URL to connect to
71
+ * @returns Promise that resolves when connected
72
+ */
73
+ connect(url: string): Promise<void> {
74
+ return new Promise((resolve, reject) => {
75
+ if (this.ws && this.ws.readyState === ReadyState.OPEN) {
76
+ resolve();
77
+ return;
78
+ }
79
+
80
+ try {
81
+ this.ws = new this._WebSocket(url);
82
+ } catch (error) {
83
+ reject(error);
84
+ return;
85
+ }
86
+
87
+ // Set binary type for proper ArrayBuffer handling
88
+ this.ws.binaryType = 'arraybuffer';
89
+
90
+ this.ws.onopen = () => {
91
+ resolve();
92
+ };
93
+
94
+ this.ws.onerror = (event) => {
95
+ const errorMsg = 'WebSocket error';
96
+ this.onError(errorMsg);
97
+ reject(new Error(errorMsg));
98
+ };
99
+
100
+ this.ws.onclose = () => {
101
+ this.onClose();
102
+ };
103
+
104
+ this.ws.onmessage = (event) => {
105
+ this.handleRawMessage(event.data);
106
+ };
107
+ });
108
+ }
109
+
110
+ /**
111
+ * Send a data message to the server using the configured codec.
112
+ * @param data The data to send (will be encoded by codec)
113
+ */
114
+ send(data: O): void {
115
+ if (!this.ws || this.ws.readyState !== ReadyState.OPEN) {
116
+ throw new Error('WebSocket is not connected');
117
+ }
118
+ const encoded = this._codec.encode(data);
119
+ this.ws.send(encoded);
120
+ }
121
+
122
+ /**
123
+ * Send a raw message to the server (bypasses codec).
124
+ * Useful for control messages like pong.
125
+ * @param message The raw string or ArrayBuffer to send
126
+ */
127
+ sendRaw(message: string | ArrayBuffer): void {
128
+ if (!this.ws || this.ws.readyState !== ReadyState.OPEN) {
129
+ throw new Error('WebSocket is not connected');
130
+ }
131
+ this.ws.send(message);
132
+ }
133
+
134
+ /**
135
+ * Close the WebSocket connection.
136
+ */
137
+ close(): void {
138
+ if (this.ws) {
139
+ this.ws.close();
140
+ this.ws = null;
141
+ }
142
+ }
143
+
144
+ /**
145
+ * Check if the client is connected.
146
+ */
147
+ get isConnected(): boolean {
148
+ return this.ws !== null && this.ws.readyState === ReadyState.OPEN;
149
+ }
150
+
151
+ /**
152
+ * Get the WebSocket ready state.
153
+ */
154
+ get readyState(): number {
155
+ return this.ws?.readyState ?? ReadyState.CLOSED;
156
+ }
157
+
158
+ /**
159
+ * Handle incoming raw message data.
160
+ * - Text frames: Check for control messages (ping), then decode with codec
161
+ * - Binary frames: Decode directly with codec
162
+ *
163
+ * Control messages (ping/pong/error) are always JSON text frames,
164
+ * regardless of what codec is used for data messages.
165
+ */
166
+ private handleRawMessage(data: string | ArrayBuffer): void {
167
+ // Binary frame -> decode with codec directly
168
+ if (data instanceof ArrayBuffer) {
169
+ try {
170
+ const decoded = this._codec.decode(data);
171
+ this.onMessage(decoded);
172
+ } catch (err) {
173
+ this.onError(`Failed to decode binary message: ${err}`);
174
+ }
175
+ return;
176
+ }
177
+
178
+ // Text frame -> check for control messages first
179
+ let parsed: unknown;
180
+ try {
181
+ parsed = JSON.parse(data);
182
+ } catch {
183
+ // Not valid JSON, try to decode with codec
184
+ try {
185
+ const decoded = this._codec.decode(data);
186
+ this.onMessage(decoded);
187
+ } catch (err) {
188
+ this.onError(`Failed to decode text message: ${err}`);
189
+ }
190
+ return;
191
+ }
192
+
193
+ // Check if it's a ping message (control message)
194
+ if (this.isPingMessage(parsed)) {
195
+ const pingId = (parsed as ControlMessage).pingId;
196
+ if (this._autoPong && pingId !== undefined) {
197
+ this.sendPong(pingId);
198
+ }
199
+ this.onPing(pingId ?? 0);
200
+ return;
201
+ }
202
+
203
+ // Not a control message -> decode with codec
204
+ // For JSON codec, the parsed object is already decoded
205
+ // For other codecs, we pass the raw string
206
+ try {
207
+ const decoded = this._codec.decode(data);
208
+ this.onMessage(decoded);
209
+ } catch (err) {
210
+ this.onError(`Failed to decode message: ${err}`);
211
+ }
212
+ }
213
+
214
+ /**
215
+ * Check if a message is a ping message.
216
+ * Pings are always JSON with type: "ping".
217
+ */
218
+ private isPingMessage(msg: unknown): boolean {
219
+ return (
220
+ typeof msg === 'object' &&
221
+ msg !== null &&
222
+ 'type' in msg &&
223
+ (msg as ControlMessage).type === 'ping'
224
+ );
225
+ }
226
+
227
+ /**
228
+ * Send a pong response.
229
+ * Pongs are always JSON, bypassing the codec.
230
+ */
231
+ private sendPong(pingId: number): void {
232
+ this.sendRaw(JSON.stringify({ type: 'pong', pingId }));
233
+ }
234
+ }
@@ -0,0 +1,206 @@
1
+ /**
2
+ * GRPCWSClient - WebSocket client for gRPC-style streaming over WebSocket.
3
+ *
4
+ * This client handles the grpcws protocol envelope format:
5
+ * - Wraps outgoing data in {type: "data", data: ...}
6
+ * - Handles incoming stream_end, error, and data messages
7
+ * - Supports client streaming (end_send) and cancellation
8
+ *
9
+ * Uses BaseWSClient for connection and ping/pong handling.
10
+ */
11
+
12
+ import { BaseWSClient } from './base-client';
13
+ import {
14
+ ControlMessage,
15
+ ClientOptions,
16
+ MessageHandler,
17
+ ErrorHandler,
18
+ VoidHandler,
19
+ } from './types';
20
+
21
+ /**
22
+ * WebSocket client for gRPC-style streaming protocol.
23
+ *
24
+ * Implements the grpcws protocol with message envelope handling:
25
+ * - Server→Client: {type: "data", data: ...}, {type: "error", error: ...}, {type: "stream_end"}
26
+ * - Client→Server: {type: "data", data: ...}, {type: "end_send"}, {type: "cancel"}
27
+ *
28
+ * Supports all three gRPC streaming patterns:
29
+ * - **Server streaming**: connect, then receive multiple messages
30
+ * - **Client streaming**: send multiple messages, call endSend(), receive response
31
+ * - **Bidirectional**: send and receive messages concurrently
32
+ *
33
+ * @example Server Streaming
34
+ * ```typescript
35
+ * const client = new GRPCWSClient();
36
+ * client.onMessage = (data) => console.log('Event:', data);
37
+ * client.onStreamEnd = () => console.log('Stream ended');
38
+ * await client.connect('ws://localhost:8080/ws/v1/subscribe?game_id=123');
39
+ * ```
40
+ *
41
+ * @example Client Streaming
42
+ * ```typescript
43
+ * const client = new GRPCWSClient();
44
+ * client.onMessage = (summary) => console.log('Result:', summary);
45
+ * await client.connect('ws://localhost:8080/ws/v1/commands');
46
+ * client.send({ commandId: '1', commandType: 'move' });
47
+ * client.send({ commandId: '2', commandType: 'attack' });
48
+ * client.endSend(); // Server responds after this
49
+ * ```
50
+ *
51
+ * @example Bidirectional Streaming
52
+ * ```typescript
53
+ * const client = new GRPCWSClient();
54
+ * client.onMessage = (state) => updateUI(state);
55
+ * await client.connect('ws://localhost:8080/ws/v1/sync');
56
+ * client.send({ actionId: '1', move: { x: 10, y: 20 } });
57
+ * // Receives responses concurrently
58
+ * ```
59
+ */
60
+ export class GRPCWSClient {
61
+ private base: BaseWSClient;
62
+
63
+ /** Called when a data message is received */
64
+ public onMessage: MessageHandler = () => {};
65
+
66
+ /** Called when the stream ends normally */
67
+ public onStreamEnd: VoidHandler = () => {};
68
+
69
+ /** Called when the server sends an error */
70
+ public onError: ErrorHandler = () => {};
71
+
72
+ /** Called when the connection closes */
73
+ public onClose: VoidHandler = () => {};
74
+
75
+ /** Called when a ping is received */
76
+ public onPing: (pingId: number) => void = () => {};
77
+
78
+ constructor(options: ClientOptions = {}) {
79
+ this.base = new BaseWSClient(options);
80
+ this.setupBaseHandlers();
81
+ }
82
+
83
+ /**
84
+ * Connect to a grpcws WebSocket server.
85
+ * @param url The WebSocket URL to connect to
86
+ * @returns Promise that resolves when connected
87
+ */
88
+ connect(url: string): Promise<void> {
89
+ return this.base.connect(url);
90
+ }
91
+
92
+ /**
93
+ * Send data to the server.
94
+ * The data is wrapped in a {type: "data", data: ...} envelope.
95
+ * @param data The data payload to send
96
+ */
97
+ send(data: unknown): void {
98
+ const envelope: ControlMessage = {
99
+ type: 'data',
100
+ data,
101
+ };
102
+ this.base.send(envelope);
103
+ }
104
+
105
+ /**
106
+ * Signal that the client is done sending (half-close).
107
+ * Used in client streaming and bidirectional streaming to indicate
108
+ * the client won't send any more messages.
109
+ */
110
+ endSend(): void {
111
+ this.base.send({ type: 'end_send' });
112
+ }
113
+
114
+ /**
115
+ * Cancel the stream.
116
+ * Signals to the server that the client wants to terminate the stream.
117
+ */
118
+ cancel(): void {
119
+ this.base.send({ type: 'cancel' });
120
+ }
121
+
122
+ /**
123
+ * Close the WebSocket connection.
124
+ */
125
+ close(): void {
126
+ this.base.close();
127
+ }
128
+
129
+ /**
130
+ * Check if the client is connected.
131
+ */
132
+ get isConnected(): boolean {
133
+ return this.base.isConnected;
134
+ }
135
+
136
+ /**
137
+ * Get the WebSocket ready state.
138
+ */
139
+ get readyState(): number {
140
+ return this.base.readyState;
141
+ }
142
+
143
+ /**
144
+ * Set up handlers on the base client to process grpcws envelope messages.
145
+ */
146
+ private setupBaseHandlers(): void {
147
+ this.base.onMessage = (msg: unknown) => {
148
+ this.handleEnvelopeMessage(msg);
149
+ };
150
+
151
+ this.base.onClose = () => {
152
+ this.onClose();
153
+ };
154
+
155
+ this.base.onError = (error: string) => {
156
+ this.onError(error);
157
+ };
158
+
159
+ this.base.onPing = (pingId: number) => {
160
+ this.onPing(pingId);
161
+ };
162
+ }
163
+
164
+ /**
165
+ * Handle an incoming envelope message.
166
+ */
167
+ private handleEnvelopeMessage(msg: unknown): void {
168
+ if (!this.isControlMessage(msg)) {
169
+ // Not a valid control message, ignore or pass through
170
+ console.warn('Received non-envelope message:', msg);
171
+ return;
172
+ }
173
+
174
+ const controlMsg = msg as ControlMessage;
175
+
176
+ switch (controlMsg.type) {
177
+ case 'data':
178
+ this.onMessage(controlMsg.data);
179
+ break;
180
+
181
+ case 'stream_end':
182
+ this.onStreamEnd();
183
+ break;
184
+
185
+ case 'error':
186
+ this.onError(controlMsg.error ?? 'Unknown error');
187
+ break;
188
+
189
+ default:
190
+ // Unknown message type, ignore
191
+ console.warn('Unknown message type:', controlMsg.type);
192
+ }
193
+ }
194
+
195
+ /**
196
+ * Check if a message is a valid control message.
197
+ */
198
+ private isControlMessage(msg: unknown): boolean {
199
+ return (
200
+ typeof msg === 'object' &&
201
+ msg !== null &&
202
+ 'type' in msg &&
203
+ typeof (msg as ControlMessage).type === 'string'
204
+ );
205
+ }
206
+ }