@celljs/rpc 4.33.0 → 4.35.0

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 (90) hide show
  1. package/README.md +6 -0
  2. package/README.zh-cn.md +6 -0
  3. package/esm/common/protocol/json-rpc.d.ts +2 -0
  4. package/esm/common/protocol/json-rpc.js +2 -0
  5. package/esm/common/protocol/json-rpc.js.map +1 -1
  6. package/esm/common/transport/index.d.ts +1 -0
  7. package/esm/common/transport/index.js +1 -0
  8. package/esm/common/transport/index.js.map +1 -1
  9. package/esm/common/transport/rpc-websocket-client.d.ts +139 -0
  10. package/esm/common/transport/rpc-websocket-client.js +404 -0
  11. package/esm/common/transport/rpc-websocket-client.js.map +1 -0
  12. package/esm/common/transport/websocket-transport.d.ts +10 -19
  13. package/esm/common/transport/websocket-transport.js +50 -121
  14. package/esm/common/transport/websocket-transport.js.map +1 -1
  15. package/esm/node/connection/index.d.ts +1 -0
  16. package/esm/node/connection/index.js +1 -0
  17. package/esm/node/connection/index.js.map +1 -1
  18. package/esm/node/connection/rpc-push-channel.d.ts +43 -0
  19. package/esm/node/connection/rpc-push-channel.js +83 -0
  20. package/esm/node/connection/rpc-push-channel.js.map +1 -0
  21. package/esm/node/websocket/index.d.ts +1 -0
  22. package/esm/node/websocket/index.js +1 -0
  23. package/esm/node/websocket/index.js.map +1 -1
  24. package/esm/node/websocket/rpc-websocket-server.d.ts +1 -2
  25. package/esm/node/websocket/rpc-websocket-server.js +10 -19
  26. package/esm/node/websocket/rpc-websocket-server.js.map +1 -1
  27. package/esm/node/websocket/websocket-upgrades.d.ts +46 -0
  28. package/esm/node/websocket/websocket-upgrades.js +76 -0
  29. package/esm/node/websocket/websocket-upgrades.js.map +1 -0
  30. package/lib/common/protocol/json-rpc.d.ts +2 -0
  31. package/lib/common/protocol/json-rpc.d.ts.map +1 -1
  32. package/lib/common/protocol/json-rpc.js +2 -0
  33. package/lib/common/protocol/json-rpc.js.map +1 -1
  34. package/lib/common/transport/index.d.ts +1 -0
  35. package/lib/common/transport/index.d.ts.map +1 -1
  36. package/lib/common/transport/index.js +1 -0
  37. package/lib/common/transport/index.js.map +1 -1
  38. package/lib/common/transport/rpc-websocket-client.d.ts +140 -0
  39. package/lib/common/transport/rpc-websocket-client.d.ts.map +1 -0
  40. package/lib/common/transport/rpc-websocket-client.js +408 -0
  41. package/lib/common/transport/rpc-websocket-client.js.map +1 -0
  42. package/lib/common/transport/rpc-websocket-client.spec.d.ts +2 -0
  43. package/lib/common/transport/rpc-websocket-client.spec.d.ts.map +1 -0
  44. package/lib/common/transport/rpc-websocket-client.spec.js +162 -0
  45. package/lib/common/transport/rpc-websocket-client.spec.js.map +1 -0
  46. package/lib/common/transport/websocket-transport.d.ts +10 -19
  47. package/lib/common/transport/websocket-transport.d.ts.map +1 -1
  48. package/lib/common/transport/websocket-transport.js +50 -121
  49. package/lib/common/transport/websocket-transport.js.map +1 -1
  50. package/lib/node/connection/index.d.ts +1 -0
  51. package/lib/node/connection/index.d.ts.map +1 -1
  52. package/lib/node/connection/index.js +1 -0
  53. package/lib/node/connection/index.js.map +1 -1
  54. package/lib/node/connection/rpc-push-channel.d.ts +44 -0
  55. package/lib/node/connection/rpc-push-channel.d.ts.map +1 -0
  56. package/lib/node/connection/rpc-push-channel.js +87 -0
  57. package/lib/node/connection/rpc-push-channel.js.map +1 -0
  58. package/lib/node/connection/rpc-push-channel.spec.d.ts +2 -0
  59. package/lib/node/connection/rpc-push-channel.spec.d.ts.map +1 -0
  60. package/lib/node/connection/rpc-push-channel.spec.js +59 -0
  61. package/lib/node/connection/rpc-push-channel.spec.js.map +1 -0
  62. package/lib/node/websocket/index.d.ts +1 -0
  63. package/lib/node/websocket/index.d.ts.map +1 -1
  64. package/lib/node/websocket/index.js +1 -0
  65. package/lib/node/websocket/index.js.map +1 -1
  66. package/lib/node/websocket/rpc-websocket-server.d.ts +1 -2
  67. package/lib/node/websocket/rpc-websocket-server.d.ts.map +1 -1
  68. package/lib/node/websocket/rpc-websocket-server.js +10 -19
  69. package/lib/node/websocket/rpc-websocket-server.js.map +1 -1
  70. package/lib/node/websocket/websocket-upgrades.d.ts +47 -0
  71. package/lib/node/websocket/websocket-upgrades.d.ts.map +1 -0
  72. package/lib/node/websocket/websocket-upgrades.js +80 -0
  73. package/lib/node/websocket/websocket-upgrades.js.map +1 -0
  74. package/lib/node/websocket/websocket-upgrades.spec.d.ts +2 -0
  75. package/lib/node/websocket/websocket-upgrades.spec.d.ts.map +1 -0
  76. package/lib/node/websocket/websocket-upgrades.spec.js +64 -0
  77. package/lib/node/websocket/websocket-upgrades.spec.js.map +1 -0
  78. package/package.json +4 -4
  79. package/src/common/protocol/json-rpc.ts +2 -0
  80. package/src/common/transport/index.ts +1 -0
  81. package/src/common/transport/rpc-websocket-client.spec.ts +164 -0
  82. package/src/common/transport/rpc-websocket-client.ts +476 -0
  83. package/src/common/transport/websocket-transport.ts +51 -126
  84. package/src/node/connection/index.ts +3 -1
  85. package/src/node/connection/rpc-push-channel.spec.ts +61 -0
  86. package/src/node/connection/rpc-push-channel.ts +98 -0
  87. package/src/node/websocket/index.ts +1 -0
  88. package/src/node/websocket/rpc-websocket-server.ts +5 -16
  89. package/src/node/websocket/websocket-upgrades.spec.ts +64 -0
  90. package/src/node/websocket/websocket-upgrades.ts +95 -0
@@ -0,0 +1,476 @@
1
+ import { JsonRpc } from '../protocol/json-rpc';
2
+
3
+ /** What the client uses of a WebSocket: that of the platform (browsers, Bun, Deno, Node.js 22), or another way (a relay). */
4
+ export interface RpcSocket {
5
+ readonly readyState: number;
6
+ onopen: ((event?: unknown) => void) | null;
7
+ onmessage: ((message: { data: unknown }) => void) | null;
8
+ onclose: ((event?: unknown) => void) | null;
9
+ onerror?: ((event?: unknown) => void) | null;
10
+ send(text: string): void;
11
+ close(code?: number, reason?: string): void;
12
+ }
13
+
14
+ export interface RpcWebSocketClientOptions {
15
+ /** A new socket for each connection. */
16
+ createSocket(): RpcSocket;
17
+ /** Makes the connection again after a loss, until closed. Default true. */
18
+ reconnect?: boolean;
19
+ /** First wait before making it again; it doubles up to `maxReconnectDelayMs`. Default 250. */
20
+ reconnectDelayMs?: number;
21
+ /** Default 10000. */
22
+ maxReconnectDelayMs?: number;
23
+ /** A socket not open within this is given up (a server that never answers the upgrade). Default 0: no limit. */
24
+ openTimeoutMs?: number;
25
+ /**
26
+ * How long a call made while the connection is down waits for it, so that a short drop goes unnoticed; it was not
27
+ * sent. Default 5000; 0 answers {@link JsonRpc.NOT_CONNECTED} at once.
28
+ */
29
+ waitForOpenMs?: number;
30
+ /**
31
+ * Whether a call may go again on the next connection when the one it went on is lost, as doing it twice does
32
+ * what doing it once does (a read; a message the server takes once by its id). Default: none.
33
+ */
34
+ resendable?(method: string, params: readonly unknown[]): boolean;
35
+ /** How long a resendable call keeps trying across lost connections. Default `waitForOpenMs`. */
36
+ retryForMs?: number;
37
+ /**
38
+ * A call unanswered this long while nothing at all came makes the client check the connection ({@link wake}):
39
+ * one gone without a word is made again in seconds, not when the system notices. Default 5000; 0 never.
40
+ */
41
+ stallMs?: number;
42
+ /** What the check asks: any answer but a lost connection says it is alive. Default `rpc.ping`. */
43
+ probe?: { method: string; params: unknown[] };
44
+ /** A call unanswered this long answers {@link JsonRpc.TIMEOUT}. Default 0: no limit. */
45
+ callTimeoutMs?: number;
46
+ /**
47
+ * Answers what the server asks (`@RpcClient`, events it pushes). An answer that is not a promise leaves at once,
48
+ * in the same turn; one that throws or rejects answers {@link JsonRpc.SERVER_ERROR}.
49
+ */
50
+ handle?(request: JsonRpc.Request): JsonRpc.Response | Promise<JsonRpc.Response>;
51
+ }
52
+
53
+ interface Pending {
54
+ resolve(response: JsonRpc.Response): void;
55
+ /** When it was sent, on the clock of Date.now(). */
56
+ sentAt: number;
57
+ timer?: ReturnType<typeof setTimeout>;
58
+ }
59
+
60
+ const OPEN = 1;
61
+ const CONNECTING = 0;
62
+
63
+ /**
64
+ * JSON-RPC 2.0 over one WebSocket to a server, for a browser, Electron, a mobile app or a backend, with no other
65
+ * dependency. Calls answer {@link JsonRpc.Response}s; they do not throw.
66
+ *
67
+ * - It makes the connection again after a loss (`reconnect`), after a wait that doubles; `onOpen` runs each time.
68
+ * A first connection that cannot be made rejects `connect`, and is not tried again on its own.
69
+ * - A call made while it is down waits a little for it (`waitForOpenMs`).
70
+ * - A call sent on a connection lost before its answer answers {@link JsonRpc.CONNECTION_CLOSED}, unless it is
71
+ * `resendable`: it goes again on the next one, for up to `retryForMs`.
72
+ * - A call that stalls while nothing comes makes it check the connection (`stallMs`), and make another at once
73
+ * when the check goes unanswered.
74
+ */
75
+ export class RpcWebSocketClient {
76
+ protected socket?: RpcSocket;
77
+ protected closed = false;
78
+ protected attempts = 0;
79
+ protected reconnectTimer?: ReturnType<typeof setTimeout>;
80
+ protected nextId = 0;
81
+ protected readonly pending = new Map<number, Pending>();
82
+ protected readonly waiting = new Set<{ go(): void; fail(): void }>();
83
+ protected readonly openListeners = new Set<() => void>();
84
+ protected readonly closeListeners = new Set<() => void>();
85
+ protected readonly reconnectingListeners = new Set<(delayMs: number, attempt: number) => void>();
86
+ /** When the last message came, on the clock of Date.now(). */
87
+ protected lastReceivedAt = 0;
88
+ protected stallTimer?: ReturnType<typeof setInterval>;
89
+ protected probing = false;
90
+
91
+ constructor(protected readonly options: RpcWebSocketClientOptions) {}
92
+
93
+ get connected(): boolean {
94
+ return this.socket?.readyState === OPEN;
95
+ }
96
+
97
+ /**
98
+ * Opens a connection unless one is open or opening: resolves once it is open, rejects when it cannot be made.
99
+ * With `reconnect`, losses after the first are made again on their own.
100
+ */
101
+ connect(): Promise<void> {
102
+ if (this.closed) {
103
+ return Promise.reject(new Error('The connection is closed.'));
104
+ }
105
+ if (this.connected) {
106
+ return Promise.resolve();
107
+ }
108
+ if (this.socket?.readyState === CONNECTING) {
109
+ return this.opening();
110
+ }
111
+ return new Promise((resolve, reject) => {
112
+ clearTimeout(this.reconnectTimer);
113
+ this.open(resolve, reject);
114
+ });
115
+ }
116
+
117
+ /** Closes it for good: what waits for it fails. */
118
+ close(code = 1000): void {
119
+ this.closed = true;
120
+ clearTimeout(this.reconnectTimer);
121
+ clearInterval(this.stallTimer);
122
+ for (const call of [...this.waiting]) {
123
+ call.fail();
124
+ }
125
+ this.socket?.close(code);
126
+ this.failPending();
127
+ }
128
+
129
+ onOpen(listener: () => void): () => void {
130
+ this.openListeners.add(listener);
131
+ return () => this.openListeners.delete(listener);
132
+ }
133
+
134
+ /** Runs each time an open connection is lost. */
135
+ onClose(listener: () => void): () => void {
136
+ this.closeListeners.add(listener);
137
+ return () => this.closeListeners.delete(listener);
138
+ }
139
+
140
+ /** Runs each time it waits to try again: how long, and which try it is (1 for the first after a loss). */
141
+ onReconnecting(listener: (delayMs: number, attempt: number) => void): () => void {
142
+ this.reconnectingListeners.add(listener);
143
+ return () => this.reconnectingListeners.delete(listener);
144
+ }
145
+
146
+ /** While the connection is down, tries again now rather than at the end of the wait, which starts over. */
147
+ reconnect(): void {
148
+ const state = this.socket?.readyState;
149
+ if (this.closed || state === OPEN || state === CONNECTING) {
150
+ return;
151
+ }
152
+ clearTimeout(this.reconnectTimer);
153
+ this.attempts = 0;
154
+ this.open();
155
+ }
156
+
157
+ /**
158
+ * After the device slept or its network changed, when a connection may be gone without a word: one that is down
159
+ * is tried at once, and an open one that does not answer the probe within `timeoutMs` is given up and made again.
160
+ */
161
+ wake(timeoutMs = 3000): void {
162
+ const socket = this.socket;
163
+ if (this.closed || socket?.readyState === CONNECTING) {
164
+ return;
165
+ }
166
+ if (socket?.readyState !== OPEN) {
167
+ this.reconnect();
168
+ return;
169
+ }
170
+ let answered = false;
171
+ const since = Date.now();
172
+ this.probing = true;
173
+ const timer = setTimeout(() => {
174
+ this.probing = false;
175
+ // Anything that came meanwhile says it is alive, only slow: the answer waits behind it.
176
+ if (!answered && this.socket === socket && this.lastReceivedAt <= since) {
177
+ socket.onclose = null;
178
+ socket.onmessage = null;
179
+ socket.close();
180
+ this.attempts = 0;
181
+ this.lost(socket, true, true);
182
+ }
183
+ }, timeoutMs);
184
+ const { method, params } = this.options.probe ?? { method: 'rpc.ping', params: [] };
185
+ // Sent once, not again after a loss: it asks about this connection.
186
+ void this.send(method, params).then(response => {
187
+ if (response.error?.code !== JsonRpc.CONNECTION_CLOSED) {
188
+ answered = true;
189
+ this.probing = false;
190
+ clearTimeout(timer);
191
+ }
192
+ });
193
+ }
194
+
195
+ /** `<service>/<method>` as the server names it. */
196
+ async call(method: string, params: unknown[]): Promise<JsonRpc.Response> {
197
+ const resendable = this.options.resendable?.(method, params) ?? false;
198
+ if (!resendable) {
199
+ if (!this.connected) {
200
+ const failed = await this.waitForOpen().then(() => undefined, (response: JsonRpc.Response) => response);
201
+ if (failed) {
202
+ return failed;
203
+ }
204
+ }
205
+ return this.send(method, params);
206
+ }
207
+ const { waitForOpenMs = 5000, retryForMs = waitForOpenMs } = this.options;
208
+ const deadline = Date.now() + Math.max(retryForMs, 1);
209
+ for (;;) {
210
+ if (!this.connected) {
211
+ const failed = await this.waitForOpen(Math.max(1, deadline - Date.now())).then(() => undefined, (response: JsonRpc.Response) => response);
212
+ if (failed) {
213
+ return failed;
214
+ }
215
+ }
216
+ const response = await this.send(method, params);
217
+ if (response.error?.code !== JsonRpc.CONNECTION_CLOSED || this.closed || Date.now() >= deadline) {
218
+ return response;
219
+ }
220
+ }
221
+ }
222
+
223
+ /** Sends a call on the open connection: its answer, or {@link JsonRpc.CONNECTION_CLOSED} when it is lost first. */
224
+ protected send(method: string, params: unknown[]): Promise<JsonRpc.Response> {
225
+ const socket = this.socket;
226
+ const id = ++this.nextId;
227
+ if (socket?.readyState !== OPEN) {
228
+ return Promise.resolve(RpcWebSocketClient.notConnected(id));
229
+ }
230
+ // JSON has no undefined: a left-out optional argument must not arrive as null.
231
+ let length = params.length;
232
+ while (length > 0 && params[length - 1] === undefined) {
233
+ length--;
234
+ }
235
+ return new Promise(resolve => {
236
+ const pending: Pending = { resolve, sentAt: Date.now() };
237
+ const { callTimeoutMs = 0 } = this.options;
238
+ if (callTimeoutMs > 0) {
239
+ pending.timer = setTimeout(() => {
240
+ this.pending.delete(id);
241
+ resolve(JsonRpc.error(id, JsonRpc.TIMEOUT, `No response to ${method} within ${callTimeoutMs} ms.`));
242
+ }, callTimeoutMs);
243
+ }
244
+ this.pending.set(id, pending);
245
+ this.watchStalls();
246
+ socket.send(JSON.stringify(JsonRpc.request(id, method, params.slice(0, length))));
247
+ });
248
+ }
249
+
250
+ /** With `resolve` and `reject`: a connection asked for, whose failure is the caller's to handle. */
251
+ protected open(resolve?: () => void, reject?: (error: Error) => void): void {
252
+ let opened = false;
253
+ const socket = this.options.createSocket();
254
+ this.socket = socket;
255
+ const { openTimeoutMs = 0 } = this.options;
256
+ const timer =
257
+ openTimeoutMs > 0
258
+ ? setTimeout(() => {
259
+ if (!opened && this.socket === socket) {
260
+ socket.onclose = null;
261
+ socket.close();
262
+ this.unopened(socket, reject);
263
+ }
264
+ }, openTimeoutMs)
265
+ : undefined;
266
+ socket.onopen = () => {
267
+ clearTimeout(timer);
268
+ if (this.socket !== socket) {
269
+ socket.close(1000);
270
+ return;
271
+ }
272
+ opened = true;
273
+ this.attempts = 0;
274
+ resolve?.();
275
+ for (const call of [...this.waiting]) {
276
+ call.go();
277
+ }
278
+ for (const listener of [...this.openListeners]) {
279
+ listener();
280
+ }
281
+ };
282
+ socket.onmessage = message => this.receive(socket, String(message.data));
283
+ socket.onerror = () => undefined;
284
+ socket.onclose = () => {
285
+ clearTimeout(timer);
286
+ // A socket given up for another (`wake`, `reconnect`) closes late: the one after it is not lost.
287
+ if (this.socket !== socket) {
288
+ return;
289
+ }
290
+ if (!opened) {
291
+ this.unopened(socket, reject);
292
+ return;
293
+ }
294
+ this.lost(socket, true);
295
+ };
296
+ }
297
+
298
+ /**
299
+ * A socket that never opened: the caller who asked for it is told, and decides what next (`connect` again,
300
+ * `reconnect`, `close`); one opened to make a lost connection again is tried again.
301
+ */
302
+ protected unopened(socket: RpcSocket, reject?: (error: Error) => void): void {
303
+ if (reject) {
304
+ this.failPending();
305
+ reject(new Error('Cannot connect.'));
306
+ return;
307
+ }
308
+ this.lost(socket, false);
309
+ }
310
+
311
+ /** The connection on `socket` is gone: the calls sent on it fail, and another is made, `atOnce` or after the wait. */
312
+ protected lost(socket: RpcSocket, opened: boolean, atOnce = false): void {
313
+ this.failPending();
314
+ if (opened) {
315
+ for (const listener of [...this.closeListeners]) {
316
+ listener();
317
+ }
318
+ }
319
+ if (this.socket !== socket || this.closed) {
320
+ return;
321
+ }
322
+ if (this.options.reconnect === false) {
323
+ for (const call of [...this.waiting]) {
324
+ call.fail();
325
+ }
326
+ return;
327
+ }
328
+ if (atOnce) {
329
+ this.open();
330
+ } else {
331
+ this.scheduleReconnect();
332
+ }
333
+ }
334
+
335
+ protected scheduleReconnect(): void {
336
+ if (this.closed) {
337
+ return;
338
+ }
339
+ const { reconnectDelayMs = 250, maxReconnectDelayMs = 10000 } = this.options;
340
+ const delay = Math.min(reconnectDelayMs * 2 ** this.attempts++, maxReconnectDelayMs);
341
+ clearTimeout(this.reconnectTimer);
342
+ this.reconnectTimer = setTimeout(() => this.open(), delay);
343
+ for (const listener of [...this.reconnectingListeners]) {
344
+ listener(delay, this.attempts);
345
+ }
346
+ }
347
+
348
+ /** The socket opening now, for one who asks to connect meanwhile: open, or given up after `openTimeoutMs` (else 5 s). */
349
+ protected opening(): Promise<void> {
350
+ return new Promise((resolve, reject) => {
351
+ const call = {
352
+ go: () => {
353
+ clearTimeout(timer);
354
+ this.waiting.delete(call);
355
+ resolve();
356
+ },
357
+ fail: () => {
358
+ clearTimeout(timer);
359
+ this.waiting.delete(call);
360
+ reject(new Error('Cannot connect.'));
361
+ },
362
+ };
363
+ const timer = setTimeout(call.fail, this.options.openTimeoutMs || 5000);
364
+ this.waiting.add(call);
365
+ });
366
+ }
367
+
368
+ /** Resolves once the connection is open; rejects with {@link JsonRpc.NOT_CONNECTED} after the wait, or at once when it is closed. */
369
+ protected waitForOpen(waitMs?: number): Promise<void> {
370
+ const { waitForOpenMs: configured = 5000 } = this.options;
371
+ const wait = configured <= 0 ? 0 : (waitMs ?? configured);
372
+ if (this.closed || wait <= 0) {
373
+ return Promise.reject(RpcWebSocketClient.notConnected(null));
374
+ }
375
+ return new Promise((resolve, reject) => {
376
+ const call = {
377
+ go: () => {
378
+ clearTimeout(timer);
379
+ this.waiting.delete(call);
380
+ resolve();
381
+ },
382
+ fail: () => {
383
+ clearTimeout(timer);
384
+ this.waiting.delete(call);
385
+ reject(RpcWebSocketClient.notConnected(null));
386
+ },
387
+ };
388
+ const timer = setTimeout(call.fail, wait);
389
+ this.waiting.add(call);
390
+ });
391
+ }
392
+
393
+ protected failPending(): void {
394
+ const pending = [...this.pending];
395
+ this.pending.clear();
396
+ for (const [id, call] of pending) {
397
+ clearTimeout(call.timer);
398
+ call.resolve(JsonRpc.error(id, JsonRpc.CONNECTION_CLOSED, 'The connection was lost before the response arrived; the call may or may not have run.'));
399
+ }
400
+ }
401
+
402
+ /** While calls wait for answers: one that waits past `stallMs` with nothing come since makes it check the connection. */
403
+ protected watchStalls(): void {
404
+ const { stallMs = 5000 } = this.options;
405
+ if (this.stallTimer !== undefined || stallMs <= 0) {
406
+ return;
407
+ }
408
+ this.stallTimer = setInterval(
409
+ () => {
410
+ const [oldest] = this.pending.values();
411
+ if (!oldest) {
412
+ clearInterval(this.stallTimer);
413
+ this.stallTimer = undefined;
414
+ return;
415
+ }
416
+ if (!this.probing && Date.now() - Math.max(oldest.sentAt, this.lastReceivedAt) >= stallMs) {
417
+ this.wake(stallMs);
418
+ }
419
+ },
420
+ Math.min(1000, stallMs),
421
+ );
422
+ }
423
+
424
+ protected receive(socket: RpcSocket, text: string): void {
425
+ this.lastReceivedAt = Date.now();
426
+ let message: unknown;
427
+ try {
428
+ message = JSON.parse(text);
429
+ } catch {
430
+ return;
431
+ }
432
+ if (JsonRpc.isRequest(message)) {
433
+ this.answer(socket, message);
434
+ return;
435
+ }
436
+ if (JsonRpc.isResponse(message) && typeof message.id === 'number') {
437
+ const call = this.pending.get(message.id);
438
+ if (call) {
439
+ clearTimeout(call.timer);
440
+ this.pending.delete(message.id);
441
+ call.resolve(message);
442
+ }
443
+ }
444
+ }
445
+
446
+ /** What the server asks, answered on the socket it came on, when it has an id. */
447
+ protected answer(socket: RpcSocket, request: JsonRpc.Request): void {
448
+ const reply = (response: JsonRpc.Response) => {
449
+ if (request.id !== undefined && socket === this.socket && socket.readyState === OPEN) {
450
+ socket.send(JSON.stringify(response));
451
+ }
452
+ };
453
+ const id = request.id ?? null;
454
+ const failed = (error: unknown) => reply(JsonRpc.error(id, JsonRpc.SERVER_ERROR, error instanceof Error ? error.message : String(error)));
455
+ if (!this.options.handle) {
456
+ reply(JsonRpc.error(id, JsonRpc.METHOD_NOT_FOUND, `No handler for ${request.method}.`));
457
+ return;
458
+ }
459
+ let response: JsonRpc.Response | Promise<JsonRpc.Response>;
460
+ try {
461
+ response = this.options.handle(request);
462
+ } catch (error) {
463
+ failed(error);
464
+ return;
465
+ }
466
+ if (response instanceof Promise) {
467
+ response.then(reply, failed);
468
+ } else {
469
+ reply(response);
470
+ }
471
+ }
472
+
473
+ protected static notConnected(id: JsonRpc.Id | null): JsonRpc.Response {
474
+ return JsonRpc.error(id, JsonRpc.NOT_CONNECTED, 'Not connected; the call was not sent.');
475
+ }
476
+ }