@panyam/servicekit-client 0.0.5 → 0.0.6

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.
Files changed (2) hide show
  1. package/dist/index.mjs +535 -0
  2. package/package.json +3 -2
package/dist/index.mjs ADDED
@@ -0,0 +1,535 @@
1
+ // src/types.ts
2
+ var ReadyState = {
3
+ CONNECTING: 0,
4
+ OPEN: 1,
5
+ CLOSING: 2,
6
+ CLOSED: 3
7
+ };
8
+ var JSONCodec = class {
9
+ decode(data) {
10
+ if (typeof data === "string") {
11
+ return JSON.parse(data);
12
+ }
13
+ const text = new TextDecoder().decode(data);
14
+ return JSON.parse(text);
15
+ }
16
+ encode(msg) {
17
+ return JSON.stringify(msg);
18
+ }
19
+ };
20
+ var BinaryCodec = class {
21
+ constructor(decodeFunc, encodeFunc) {
22
+ this.decodeFunc = decodeFunc;
23
+ this.encodeFunc = encodeFunc;
24
+ }
25
+ decode(data) {
26
+ if (typeof data === "string") {
27
+ throw new Error("BinaryCodec received text data, expected binary");
28
+ }
29
+ return this.decodeFunc(data);
30
+ }
31
+ encode(msg) {
32
+ const encoded = this.encodeFunc(msg);
33
+ return encoded.buffer.slice(encoded.byteOffset, encoded.byteOffset + encoded.byteLength);
34
+ }
35
+ };
36
+
37
+ // src/base-client.ts
38
+ var BaseWSClient = class {
39
+ constructor(options = {}) {
40
+ this.ws = null;
41
+ /** Called when a data message is received (decoded by codec) */
42
+ this.onMessage = () => {
43
+ };
44
+ /** Called when a ping is received (after auto-pong if enabled) */
45
+ this.onPing = () => {
46
+ };
47
+ /** Called when the connection closes */
48
+ this.onClose = () => {
49
+ };
50
+ /** Called when a WebSocket error occurs */
51
+ this.onError = () => {
52
+ };
53
+ this._autoPong = options.autoPong ?? true;
54
+ this._WebSocket = options.WebSocket ?? globalThis.WebSocket;
55
+ this._codec = options.codec ?? new JSONCodec();
56
+ }
57
+ /** Get the codec used for encoding/decoding data messages */
58
+ get codec() {
59
+ return this._codec;
60
+ }
61
+ /**
62
+ * Connect to a WebSocket server.
63
+ * @param url The WebSocket URL to connect to
64
+ * @returns Promise that resolves when connected
65
+ */
66
+ connect(url) {
67
+ return new Promise((resolve, reject) => {
68
+ if (this.ws && this.ws.readyState === ReadyState.OPEN) {
69
+ resolve();
70
+ return;
71
+ }
72
+ try {
73
+ this.ws = new this._WebSocket(url);
74
+ } catch (error) {
75
+ reject(error);
76
+ return;
77
+ }
78
+ this.ws.binaryType = "arraybuffer";
79
+ this.ws.onopen = () => {
80
+ resolve();
81
+ };
82
+ this.ws.onerror = (event) => {
83
+ const errorMsg = "WebSocket error";
84
+ this.onError(errorMsg);
85
+ reject(new Error(errorMsg));
86
+ };
87
+ this.ws.onclose = () => {
88
+ this.onClose();
89
+ };
90
+ this.ws.onmessage = (event) => {
91
+ this.handleRawMessage(event.data);
92
+ };
93
+ });
94
+ }
95
+ /**
96
+ * Send a data message to the server using the configured codec.
97
+ * @param data The data to send (will be encoded by codec)
98
+ */
99
+ send(data) {
100
+ if (!this.ws || this.ws.readyState !== ReadyState.OPEN) {
101
+ throw new Error("WebSocket is not connected");
102
+ }
103
+ const encoded = this._codec.encode(data);
104
+ this.ws.send(encoded);
105
+ }
106
+ /**
107
+ * Send a raw message to the server (bypasses codec).
108
+ * Useful for control messages like pong.
109
+ * @param message The raw string or ArrayBuffer to send
110
+ */
111
+ sendRaw(message) {
112
+ if (!this.ws || this.ws.readyState !== ReadyState.OPEN) {
113
+ throw new Error("WebSocket is not connected");
114
+ }
115
+ this.ws.send(message);
116
+ }
117
+ /**
118
+ * Close the WebSocket connection.
119
+ */
120
+ close() {
121
+ if (this.ws) {
122
+ this.ws.close();
123
+ this.ws = null;
124
+ }
125
+ }
126
+ /**
127
+ * Check if the client is connected.
128
+ */
129
+ get isConnected() {
130
+ return this.ws !== null && this.ws.readyState === ReadyState.OPEN;
131
+ }
132
+ /**
133
+ * Get the WebSocket ready state.
134
+ */
135
+ get readyState() {
136
+ return this.ws?.readyState ?? ReadyState.CLOSED;
137
+ }
138
+ /**
139
+ * Handle incoming raw message data.
140
+ * - Text frames: Check for control messages (ping), then decode with codec
141
+ * - Binary frames: Decode directly with codec
142
+ *
143
+ * Control messages (ping/pong/error) are always JSON text frames,
144
+ * regardless of what codec is used for data messages.
145
+ */
146
+ handleRawMessage(data) {
147
+ if (data instanceof ArrayBuffer) {
148
+ try {
149
+ const decoded = this._codec.decode(data);
150
+ this.onMessage(decoded);
151
+ } catch (err) {
152
+ this.onError(`Failed to decode binary message: ${err}`);
153
+ }
154
+ return;
155
+ }
156
+ let parsed;
157
+ try {
158
+ parsed = JSON.parse(data);
159
+ } catch {
160
+ try {
161
+ const decoded = this._codec.decode(data);
162
+ this.onMessage(decoded);
163
+ } catch (err) {
164
+ this.onError(`Failed to decode text message: ${err}`);
165
+ }
166
+ return;
167
+ }
168
+ if (this.isPingMessage(parsed)) {
169
+ const pingId = parsed.pingId;
170
+ if (this._autoPong && pingId !== void 0) {
171
+ this.sendPong(pingId);
172
+ }
173
+ this.onPing(pingId ?? 0);
174
+ return;
175
+ }
176
+ try {
177
+ const decoded = this._codec.decode(data);
178
+ this.onMessage(decoded);
179
+ } catch (err) {
180
+ this.onError(`Failed to decode message: ${err}`);
181
+ }
182
+ }
183
+ /**
184
+ * Check if a message is a ping message.
185
+ * Pings are always JSON with type: "ping".
186
+ */
187
+ isPingMessage(msg) {
188
+ return typeof msg === "object" && msg !== null && "type" in msg && msg.type === "ping";
189
+ }
190
+ /**
191
+ * Send a pong response.
192
+ * Pongs are always JSON, bypassing the codec.
193
+ */
194
+ sendPong(pingId) {
195
+ this.sendRaw(JSON.stringify({ type: "pong", pingId }));
196
+ }
197
+ };
198
+
199
+ // src/mock.ts
200
+ function createMockWSPair() {
201
+ let ws = null;
202
+ class MockWebSocket {
203
+ constructor(_url) {
204
+ this.readyState = ReadyState.CONNECTING;
205
+ this.binaryType = "";
206
+ this.onopen = null;
207
+ this.onmessage = null;
208
+ this.onerror = null;
209
+ this.onclose = null;
210
+ this._sent = [];
211
+ ws = this;
212
+ }
213
+ send(data) {
214
+ this._sent.push(data);
215
+ }
216
+ close() {
217
+ this.readyState = ReadyState.CLOSED;
218
+ this.onclose?.({});
219
+ }
220
+ get sentRaw() {
221
+ return this._sent;
222
+ }
223
+ }
224
+ const assertConnected = (method) => {
225
+ if (!ws) throw new Error(`Call client.connect() before ${method}()`);
226
+ };
227
+ const controller = {
228
+ get sentRaw() {
229
+ return ws?.sentRaw ?? [];
230
+ },
231
+ simulateOpen() {
232
+ assertConnected("simulateOpen");
233
+ ws.readyState = ReadyState.OPEN;
234
+ ws.onopen?.({});
235
+ },
236
+ simulateRawMessage(data) {
237
+ assertConnected("simulateRawMessage");
238
+ ws.onmessage?.({ data });
239
+ },
240
+ simulateWsError() {
241
+ assertConnected("simulateWsError");
242
+ ws.onerror?.({});
243
+ },
244
+ simulateClose(code) {
245
+ assertConnected("simulateClose");
246
+ ws.readyState = ReadyState.CLOSED;
247
+ ws.onclose?.({});
248
+ },
249
+ get readyState() {
250
+ return ws?.readyState ?? ReadyState.CLOSED;
251
+ }
252
+ };
253
+ return {
254
+ WebSocket: MockWebSocket,
255
+ controller
256
+ };
257
+ }
258
+
259
+ // src/grpcws-client.ts
260
+ var GRPCWSClient = class _GRPCWSClient {
261
+ constructor(options = {}) {
262
+ /** Called when a data message is received */
263
+ this.onMessage = () => {
264
+ };
265
+ /** Called when the stream ends normally */
266
+ this.onStreamEnd = () => {
267
+ };
268
+ /** Called when the server sends an error */
269
+ this.onError = () => {
270
+ };
271
+ /** Called when the connection closes */
272
+ this.onClose = () => {
273
+ };
274
+ /** Called when a ping is received */
275
+ this.onPing = () => {
276
+ };
277
+ this.base = new BaseWSClient(options);
278
+ this.setupBaseHandlers();
279
+ }
280
+ /**
281
+ * Connect to a grpcws WebSocket server.
282
+ * @param url The WebSocket URL to connect to
283
+ * @returns Promise that resolves when connected
284
+ */
285
+ connect(url) {
286
+ return this.base.connect(url);
287
+ }
288
+ /**
289
+ * Send data to the server.
290
+ * The data is wrapped in a {type: "data", data: ...} envelope.
291
+ * @param data The data payload to send
292
+ */
293
+ send(data) {
294
+ const envelope = {
295
+ type: "data",
296
+ data
297
+ };
298
+ this.base.send(envelope);
299
+ }
300
+ /**
301
+ * Signal that the client is done sending (half-close).
302
+ * Used in client streaming and bidirectional streaming to indicate
303
+ * the client won't send any more messages.
304
+ */
305
+ endSend() {
306
+ this.base.send({ type: "end_send" });
307
+ }
308
+ /**
309
+ * Cancel the stream.
310
+ * Signals to the server that the client wants to terminate the stream.
311
+ */
312
+ cancel() {
313
+ this.base.send({ type: "cancel" });
314
+ }
315
+ /**
316
+ * Close the WebSocket connection.
317
+ */
318
+ close() {
319
+ this.base.close();
320
+ }
321
+ /**
322
+ * Check if the client is connected.
323
+ */
324
+ get isConnected() {
325
+ return this.base.isConnected;
326
+ }
327
+ /**
328
+ * Get the WebSocket ready state.
329
+ */
330
+ get readyState() {
331
+ return this.base.readyState;
332
+ }
333
+ /**
334
+ * Create a mock client + controller pair for testing.
335
+ *
336
+ * Returns a pre-wired GRPCWSClient backed by a fake WebSocket, so
337
+ * consumers don't need to mock WebSocket internals or know about the
338
+ * servicekit envelope protocol.
339
+ *
340
+ * @example
341
+ * ```typescript
342
+ * const { client, controller } = GRPCWSClient.createMock();
343
+ *
344
+ * client.onMessage = (data) => { handle(data); };
345
+ * client.connect('ws://test');
346
+ * controller.simulateOpen();
347
+ *
348
+ * controller.simulateMessage({ event: { case: 'roomJoined', value: {} } });
349
+ * expect(controller.sentMessages).toHaveLength(0);
350
+ *
351
+ * client.send({ action: { case: 'join' } });
352
+ * expect(controller.sentMessages[0]).toMatchObject({ action: { case: 'join' } });
353
+ * ```
354
+ */
355
+ static createMock() {
356
+ const { WebSocket, controller: wsCtrl } = createMockWSPair();
357
+ const client = new _GRPCWSClient({ WebSocket });
358
+ const controller = {
359
+ get sentMessages() {
360
+ const messages = [];
361
+ for (const raw of wsCtrl.sentRaw) {
362
+ try {
363
+ const parsed = JSON.parse(raw);
364
+ if (parsed.type === "data") {
365
+ messages.push(parsed.data);
366
+ }
367
+ } catch {
368
+ }
369
+ }
370
+ return messages;
371
+ },
372
+ simulateOpen() {
373
+ wsCtrl.simulateOpen();
374
+ },
375
+ simulateMessage(data) {
376
+ wsCtrl.simulateRawMessage(JSON.stringify({ type: "data", data }));
377
+ },
378
+ simulateError(message) {
379
+ wsCtrl.simulateRawMessage(
380
+ JSON.stringify({ type: "error", error: message ?? "Mock error" })
381
+ );
382
+ },
383
+ simulateClose(code) {
384
+ wsCtrl.simulateClose(code);
385
+ },
386
+ get readyState() {
387
+ return wsCtrl.readyState;
388
+ }
389
+ };
390
+ return { client, controller };
391
+ }
392
+ /**
393
+ * Set up handlers on the base client to process grpcws envelope messages.
394
+ */
395
+ setupBaseHandlers() {
396
+ this.base.onMessage = (msg) => {
397
+ this.handleEnvelopeMessage(msg);
398
+ };
399
+ this.base.onClose = () => {
400
+ this.onClose();
401
+ };
402
+ this.base.onError = (error) => {
403
+ this.onError(error);
404
+ };
405
+ this.base.onPing = (pingId) => {
406
+ this.onPing(pingId);
407
+ };
408
+ }
409
+ /**
410
+ * Handle an incoming envelope message.
411
+ */
412
+ handleEnvelopeMessage(msg) {
413
+ if (!this.isControlMessage(msg)) {
414
+ console.warn("Received non-envelope message:", msg);
415
+ return;
416
+ }
417
+ const controlMsg = msg;
418
+ switch (controlMsg.type) {
419
+ case "data":
420
+ this.onMessage(controlMsg.data);
421
+ break;
422
+ case "stream_end":
423
+ this.onStreamEnd();
424
+ break;
425
+ case "error":
426
+ this.onError(controlMsg.error ?? "Unknown error");
427
+ break;
428
+ default:
429
+ console.warn("Unknown message type:", controlMsg.type);
430
+ }
431
+ }
432
+ /**
433
+ * Check if a message is a valid control message.
434
+ */
435
+ isControlMessage(msg) {
436
+ return typeof msg === "object" && msg !== null && "type" in msg && typeof msg.type === "string";
437
+ }
438
+ };
439
+
440
+ // src/typed-client.ts
441
+ var TypedGRPCWSClient = class {
442
+ constructor(options = {}) {
443
+ /** Called when a typed message is received */
444
+ this.onMessage = () => {
445
+ };
446
+ /** Called when the stream ends normally */
447
+ this.onStreamEnd = () => {
448
+ };
449
+ /** Called when the server sends an error */
450
+ this.onError = () => {
451
+ };
452
+ /** Called when the connection closes */
453
+ this.onClose = () => {
454
+ };
455
+ /** Called when a ping is received */
456
+ this.onPing = () => {
457
+ };
458
+ this.client = new GRPCWSClient(options);
459
+ this.setupHandlers();
460
+ }
461
+ /**
462
+ * Connect to a grpcws WebSocket server.
463
+ * @param url The WebSocket URL to connect to
464
+ * @returns Promise that resolves when connected
465
+ */
466
+ connect(url) {
467
+ return this.client.connect(url);
468
+ }
469
+ /**
470
+ * Send a typed message to the server.
471
+ * @param data The typed data payload to send
472
+ */
473
+ send(data) {
474
+ this.client.send(data);
475
+ }
476
+ /**
477
+ * Signal that the client is done sending (half-close).
478
+ */
479
+ endSend() {
480
+ this.client.endSend();
481
+ }
482
+ /**
483
+ * Cancel the stream.
484
+ */
485
+ cancel() {
486
+ this.client.cancel();
487
+ }
488
+ /**
489
+ * Close the WebSocket connection.
490
+ */
491
+ close() {
492
+ this.client.close();
493
+ }
494
+ /**
495
+ * Check if the client is connected.
496
+ */
497
+ get isConnected() {
498
+ return this.client.isConnected;
499
+ }
500
+ /**
501
+ * Get the WebSocket ready state.
502
+ */
503
+ get readyState() {
504
+ return this.client.readyState;
505
+ }
506
+ /**
507
+ * Set up handlers to forward events with proper typing.
508
+ */
509
+ setupHandlers() {
510
+ this.client.onMessage = (data) => {
511
+ this.onMessage(data);
512
+ };
513
+ this.client.onStreamEnd = () => {
514
+ this.onStreamEnd();
515
+ };
516
+ this.client.onError = (error) => {
517
+ this.onError(error);
518
+ };
519
+ this.client.onClose = () => {
520
+ this.onClose();
521
+ };
522
+ this.client.onPing = (pingId) => {
523
+ this.onPing(pingId);
524
+ };
525
+ }
526
+ };
527
+ export {
528
+ BaseWSClient,
529
+ BinaryCodec,
530
+ GRPCWSClient,
531
+ JSONCodec,
532
+ ReadyState,
533
+ TypedGRPCWSClient,
534
+ createMockWSPair
535
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@panyam/servicekit-client",
3
- "version": "0.0.5",
3
+ "version": "0.0.6",
4
4
  "description": "TypeScript client for gRPC-WebSocket streaming protocol",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",
@@ -11,7 +11,8 @@
11
11
  "src"
12
12
  ],
13
13
  "scripts": {
14
- "build": "tsc && npm run build:browser",
14
+ "build": "tsc && npm run build:esm && npm run build:browser",
15
+ "build:esm": "esbuild src/index.ts --bundle --format=esm --outfile=dist/index.mjs",
15
16
  "build:browser": "esbuild src/index.ts --bundle --format=iife --global-name=ServiceKit --outfile=dist/servicekit-client.browser.js",
16
17
  "clean": "rm -rf dist",
17
18
  "prepublishOnly": "npm run build"