@panyam/servicekit-client 0.0.4 → 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.
@@ -26,7 +26,8 @@ var ServiceKit = (() => {
26
26
  GRPCWSClient: () => GRPCWSClient,
27
27
  JSONCodec: () => JSONCodec,
28
28
  ReadyState: () => ReadyState,
29
- TypedGRPCWSClient: () => TypedGRPCWSClient
29
+ TypedGRPCWSClient: () => TypedGRPCWSClient,
30
+ createMockWSPair: () => createMockWSPair
30
31
  });
31
32
 
32
33
  // src/types.ts
@@ -227,8 +228,68 @@ var ServiceKit = (() => {
227
228
  }
228
229
  };
229
230
 
231
+ // src/mock.ts
232
+ function createMockWSPair() {
233
+ let ws = null;
234
+ class MockWebSocket {
235
+ constructor(_url) {
236
+ this.readyState = ReadyState.CONNECTING;
237
+ this.binaryType = "";
238
+ this.onopen = null;
239
+ this.onmessage = null;
240
+ this.onerror = null;
241
+ this.onclose = null;
242
+ this._sent = [];
243
+ ws = this;
244
+ }
245
+ send(data) {
246
+ this._sent.push(data);
247
+ }
248
+ close() {
249
+ this.readyState = ReadyState.CLOSED;
250
+ this.onclose?.({});
251
+ }
252
+ get sentRaw() {
253
+ return this._sent;
254
+ }
255
+ }
256
+ const assertConnected = (method) => {
257
+ if (!ws) throw new Error(`Call client.connect() before ${method}()`);
258
+ };
259
+ const controller = {
260
+ get sentRaw() {
261
+ return ws?.sentRaw ?? [];
262
+ },
263
+ simulateOpen() {
264
+ assertConnected("simulateOpen");
265
+ ws.readyState = ReadyState.OPEN;
266
+ ws.onopen?.({});
267
+ },
268
+ simulateRawMessage(data) {
269
+ assertConnected("simulateRawMessage");
270
+ ws.onmessage?.({ data });
271
+ },
272
+ simulateWsError() {
273
+ assertConnected("simulateWsError");
274
+ ws.onerror?.({});
275
+ },
276
+ simulateClose(code) {
277
+ assertConnected("simulateClose");
278
+ ws.readyState = ReadyState.CLOSED;
279
+ ws.onclose?.({});
280
+ },
281
+ get readyState() {
282
+ return ws?.readyState ?? ReadyState.CLOSED;
283
+ }
284
+ };
285
+ return {
286
+ WebSocket: MockWebSocket,
287
+ controller
288
+ };
289
+ }
290
+
230
291
  // src/grpcws-client.ts
231
- var GRPCWSClient = class {
292
+ var GRPCWSClient = class _GRPCWSClient {
232
293
  constructor(options = {}) {
233
294
  /** Called when a data message is received */
234
295
  this.onMessage = () => {
@@ -301,6 +362,65 @@ var ServiceKit = (() => {
301
362
  get readyState() {
302
363
  return this.base.readyState;
303
364
  }
365
+ /**
366
+ * Create a mock client + controller pair for testing.
367
+ *
368
+ * Returns a pre-wired GRPCWSClient backed by a fake WebSocket, so
369
+ * consumers don't need to mock WebSocket internals or know about the
370
+ * servicekit envelope protocol.
371
+ *
372
+ * @example
373
+ * ```typescript
374
+ * const { client, controller } = GRPCWSClient.createMock();
375
+ *
376
+ * client.onMessage = (data) => { handle(data); };
377
+ * client.connect('ws://test');
378
+ * controller.simulateOpen();
379
+ *
380
+ * controller.simulateMessage({ event: { case: 'roomJoined', value: {} } });
381
+ * expect(controller.sentMessages).toHaveLength(0);
382
+ *
383
+ * client.send({ action: { case: 'join' } });
384
+ * expect(controller.sentMessages[0]).toMatchObject({ action: { case: 'join' } });
385
+ * ```
386
+ */
387
+ static createMock() {
388
+ const { WebSocket, controller: wsCtrl } = createMockWSPair();
389
+ const client = new _GRPCWSClient({ WebSocket });
390
+ const controller = {
391
+ get sentMessages() {
392
+ const messages = [];
393
+ for (const raw of wsCtrl.sentRaw) {
394
+ try {
395
+ const parsed = JSON.parse(raw);
396
+ if (parsed.type === "data") {
397
+ messages.push(parsed.data);
398
+ }
399
+ } catch {
400
+ }
401
+ }
402
+ return messages;
403
+ },
404
+ simulateOpen() {
405
+ wsCtrl.simulateOpen();
406
+ },
407
+ simulateMessage(data) {
408
+ wsCtrl.simulateRawMessage(JSON.stringify({ type: "data", data }));
409
+ },
410
+ simulateError(message) {
411
+ wsCtrl.simulateRawMessage(
412
+ JSON.stringify({ type: "error", error: message ?? "Mock error" })
413
+ );
414
+ },
415
+ simulateClose(code) {
416
+ wsCtrl.simulateClose(code);
417
+ },
418
+ get readyState() {
419
+ return wsCtrl.readyState;
420
+ }
421
+ };
422
+ return { client, controller };
423
+ }
304
424
  /**
305
425
  * Set up handlers on the base client to process grpcws envelope messages.
306
426
  */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@panyam/servicekit-client",
3
- "version": "0.0.4",
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"
@@ -10,6 +10,7 @@
10
10
  */
11
11
 
12
12
  import { BaseWSClient } from './base-client';
13
+ import { createMockWSPair } from './mock';
13
14
  import {
14
15
  ControlMessage,
15
16
  ClientOptions,
@@ -18,6 +19,42 @@ import {
18
19
  VoidHandler,
19
20
  } from './types';
20
21
 
22
+ /**
23
+ * Mock controller for testing GRPCWSClient without real WebSocket connections.
24
+ *
25
+ * The controller wraps/unwraps the servicekit envelope automatically —
26
+ * consumers only see application-level data.
27
+ *
28
+ * @example
29
+ * ```typescript
30
+ * const { client, controller } = GRPCWSClient.createMock();
31
+ * client.onMessage = (data) => received.push(data);
32
+ * client.connect('ws://test');
33
+ * controller.simulateOpen();
34
+ * controller.simulateMessage({ event: 'joined' });
35
+ * expect(received).toEqual([{ event: 'joined' }]);
36
+ * ```
37
+ */
38
+ export interface MockController {
39
+ /** Messages sent by the client (already unwrapped from envelope) */
40
+ readonly sentMessages: unknown[];
41
+
42
+ /** Simulate WebSocket open — resolves the connect() Promise */
43
+ simulateOpen(): void;
44
+
45
+ /** Simulate receiving a data message (auto-wraps in {type: "data"} envelope) */
46
+ simulateMessage(data: unknown): void;
47
+
48
+ /** Simulate a server error (delivers {type: "error"} envelope to onError) */
49
+ simulateError(message?: string): void;
50
+
51
+ /** Simulate WebSocket close */
52
+ simulateClose(code?: number): void;
53
+
54
+ /** Current WebSocket ready state */
55
+ readonly readyState: number;
56
+ }
57
+
21
58
  /**
22
59
  * WebSocket client for gRPC-style streaming protocol.
23
60
  *
@@ -140,6 +177,74 @@ export class GRPCWSClient {
140
177
  return this.base.readyState;
141
178
  }
142
179
 
180
+ /**
181
+ * Create a mock client + controller pair for testing.
182
+ *
183
+ * Returns a pre-wired GRPCWSClient backed by a fake WebSocket, so
184
+ * consumers don't need to mock WebSocket internals or know about the
185
+ * servicekit envelope protocol.
186
+ *
187
+ * @example
188
+ * ```typescript
189
+ * const { client, controller } = GRPCWSClient.createMock();
190
+ *
191
+ * client.onMessage = (data) => { handle(data); };
192
+ * client.connect('ws://test');
193
+ * controller.simulateOpen();
194
+ *
195
+ * controller.simulateMessage({ event: { case: 'roomJoined', value: {} } });
196
+ * expect(controller.sentMessages).toHaveLength(0);
197
+ *
198
+ * client.send({ action: { case: 'join' } });
199
+ * expect(controller.sentMessages[0]).toMatchObject({ action: { case: 'join' } });
200
+ * ```
201
+ */
202
+ static createMock(): { client: GRPCWSClient; controller: MockController } {
203
+ const { WebSocket, controller: wsCtrl } = createMockWSPair();
204
+ const client = new GRPCWSClient({ WebSocket });
205
+
206
+ const controller: MockController = {
207
+ get sentMessages(): unknown[] {
208
+ const messages: unknown[] = [];
209
+ for (const raw of wsCtrl.sentRaw) {
210
+ try {
211
+ const parsed = JSON.parse(raw as string);
212
+ if (parsed.type === 'data') {
213
+ messages.push(parsed.data);
214
+ }
215
+ } catch {
216
+ // Skip non-JSON messages (e.g. binary)
217
+ }
218
+ }
219
+ return messages;
220
+ },
221
+
222
+ simulateOpen() {
223
+ wsCtrl.simulateOpen();
224
+ },
225
+
226
+ simulateMessage(data: unknown) {
227
+ wsCtrl.simulateRawMessage(JSON.stringify({ type: 'data', data }));
228
+ },
229
+
230
+ simulateError(message?: string) {
231
+ wsCtrl.simulateRawMessage(
232
+ JSON.stringify({ type: 'error', error: message ?? 'Mock error' })
233
+ );
234
+ },
235
+
236
+ simulateClose(code?: number) {
237
+ wsCtrl.simulateClose(code);
238
+ },
239
+
240
+ get readyState(): number {
241
+ return wsCtrl.readyState;
242
+ },
243
+ };
244
+
245
+ return { client, controller };
246
+ }
247
+
143
248
  /**
144
249
  * Set up handlers on the base client to process grpcws envelope messages.
145
250
  */
package/src/index.ts CHANGED
@@ -77,5 +77,8 @@ export {
77
77
 
78
78
  // Clients
79
79
  export { BaseWSClient } from './base-client';
80
- export { GRPCWSClient } from './grpcws-client';
80
+ export { GRPCWSClient, MockController } from './grpcws-client';
81
81
  export { TypedGRPCWSClient } from './typed-client';
82
+
83
+ // Test utilities
84
+ export { createMockWSPair, MockWSController } from './mock';
package/src/mock.ts ADDED
@@ -0,0 +1,132 @@
1
+ /**
2
+ * Mock WebSocket utilities for testing.
3
+ *
4
+ * Provides a fake WebSocket implementation and controller that can be used
5
+ * to test any client built on BaseWSClient without real connections.
6
+ *
7
+ * @example
8
+ * ```typescript
9
+ * import { BaseWSClient } from './base-client';
10
+ * import { createMockWSPair } from './mock';
11
+ *
12
+ * const { WebSocket, controller } = createMockWSPair();
13
+ * const client = new BaseWSClient({ WebSocket });
14
+ * client.connect('ws://test');
15
+ * controller.simulateOpen();
16
+ * controller.simulateRawMessage('{"hello":"world"}');
17
+ * ```
18
+ */
19
+
20
+ import { ReadyState } from './types';
21
+
22
+ /**
23
+ * Low-level mock WebSocket controller.
24
+ *
25
+ * Operates at the WebSocket transport level — no protocol awareness.
26
+ * Use this directly with BaseWSClient, or wrap with protocol-specific
27
+ * logic for GRPCWSClient.
28
+ */
29
+ export interface MockWSController {
30
+ /** Raw messages sent via ws.send() (strings or ArrayBuffers) */
31
+ readonly sentRaw: readonly (string | ArrayBuffer)[];
32
+
33
+ /** Simulate WebSocket open — resolves the connect() Promise */
34
+ simulateOpen(): void;
35
+
36
+ /** Simulate receiving a raw WebSocket message (no wrapping) */
37
+ simulateRawMessage(data: string | ArrayBuffer): void;
38
+
39
+ /** Simulate a WebSocket error event */
40
+ simulateWsError(): void;
41
+
42
+ /** Simulate WebSocket close */
43
+ simulateClose(code?: number): void;
44
+
45
+ /** Current WebSocket ready state */
46
+ readonly readyState: number;
47
+ }
48
+
49
+ /**
50
+ * Create a mock WebSocket constructor + controller pair.
51
+ *
52
+ * The returned `WebSocket` can be passed as `ClientOptions.WebSocket`
53
+ * to any client. The controller lets tests drive the fake connection.
54
+ *
55
+ * A new MockWebSocket instance is captured each time the client calls
56
+ * `connect()`, so the controller always refers to the latest connection.
57
+ */
58
+ export function createMockWSPair(): {
59
+ WebSocket: typeof globalThis.WebSocket;
60
+ controller: MockWSController;
61
+ } {
62
+ let ws: MockWebSocket | null = null;
63
+
64
+ class MockWebSocket {
65
+ readyState: number = ReadyState.CONNECTING;
66
+ binaryType = '';
67
+ onopen: ((ev: unknown) => void) | null = null;
68
+ onmessage: ((ev: { data: string | ArrayBuffer }) => void) | null = null;
69
+ onerror: ((ev: unknown) => void) | null = null;
70
+ onclose: ((ev: unknown) => void) | null = null;
71
+
72
+ private _sent: (string | ArrayBuffer)[] = [];
73
+
74
+ constructor(_url: string) {
75
+ ws = this;
76
+ }
77
+
78
+ send(data: string | ArrayBuffer) {
79
+ this._sent.push(data);
80
+ }
81
+
82
+ close() {
83
+ this.readyState = ReadyState.CLOSED;
84
+ this.onclose?.({});
85
+ }
86
+
87
+ get sentRaw(): readonly (string | ArrayBuffer)[] {
88
+ return this._sent;
89
+ }
90
+ }
91
+
92
+ const assertConnected = (method: string) => {
93
+ if (!ws) throw new Error(`Call client.connect() before ${method}()`);
94
+ };
95
+
96
+ const controller: MockWSController = {
97
+ get sentRaw() {
98
+ return ws?.sentRaw ?? [];
99
+ },
100
+
101
+ simulateOpen() {
102
+ assertConnected('simulateOpen');
103
+ ws!.readyState = ReadyState.OPEN;
104
+ ws!.onopen?.({});
105
+ },
106
+
107
+ simulateRawMessage(data: string | ArrayBuffer) {
108
+ assertConnected('simulateRawMessage');
109
+ ws!.onmessage?.({ data });
110
+ },
111
+
112
+ simulateWsError() {
113
+ assertConnected('simulateWsError');
114
+ ws!.onerror?.({});
115
+ },
116
+
117
+ simulateClose(code?: number) {
118
+ assertConnected('simulateClose');
119
+ ws!.readyState = ReadyState.CLOSED;
120
+ ws!.onclose?.({});
121
+ },
122
+
123
+ get readyState() {
124
+ return ws?.readyState ?? ReadyState.CLOSED;
125
+ },
126
+ };
127
+
128
+ return {
129
+ WebSocket: MockWebSocket as unknown as typeof globalThis.WebSocket,
130
+ controller,
131
+ };
132
+ }