@dxos/rpc 0.8.4-main.b97322e → 0.8.4-main.bcb3aa67d6

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.
@@ -1,915 +0,0 @@
1
- import { createRequire } from 'node:module';const require = createRequire(import.meta.url);
2
-
3
- // src/errors.ts
4
- import { StackTrace } from "@dxos/debug";
5
- import { decodeError } from "@dxos/protocols";
6
- var decodeRpcError = (err, rpcMethod) => decodeError(err, {
7
- appendStack: `
8
- at RPC ${rpcMethod}
9
- ` + new StackTrace().getStack(1)
10
- });
11
-
12
- // src/rpc.ts
13
- import { asyncTimeout, synchronized, Trigger } from "@dxos/async";
14
- import { Stream } from "@dxos/codec-protobuf";
15
- import { StackTrace as StackTrace2 } from "@dxos/debug";
16
- import { invariant } from "@dxos/invariant";
17
- import { log } from "@dxos/log";
18
- import { encodeError, RpcClosedError, RpcNotOpenError } from "@dxos/protocols";
19
- import { schema } from "@dxos/protocols/proto";
20
- import { exponentialBackoffInterval } from "@dxos/util";
21
- function _ts_decorate(decorators, target, key, desc) {
22
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
23
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
24
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
25
- return c > 3 && r && Object.defineProperty(target, key, r), r;
26
- }
27
- var __dxlog_file = "/__w/dxos/dxos/packages/core/mesh/rpc/src/rpc.ts";
28
- var DEFAULT_TIMEOUT = 3e3;
29
- var BYE_SEND_TIMEOUT = 2e3;
30
- var DEBUG_CALLS = true;
31
- var CLOSE_TIMEOUT = 3e3;
32
- var PendingRpcRequest = class {
33
- constructor(resolve, reject, stream) {
34
- this.resolve = resolve;
35
- this.reject = reject;
36
- this.stream = stream;
37
- }
38
- };
39
- var RpcMessageCodec;
40
- var getRpcMessageCodec = () => RpcMessageCodec ??= schema.getCodecForType("dxos.rpc.RpcMessage");
41
- var RpcPeer = class {
42
- constructor(params) {
43
- this._outgoingRequests = /* @__PURE__ */ new Map();
44
- this._localStreams = /* @__PURE__ */ new Map();
45
- this._remoteOpenTrigger = new Trigger();
46
- /**
47
- * Triggered when the peer starts closing.
48
- */
49
- this._closingTrigger = new Trigger();
50
- /**
51
- * Triggered when peer receives a bye message.
52
- */
53
- this._byeTrigger = new Trigger();
54
- this._nextId = 0;
55
- this._state = "INITIAL";
56
- this._unsubscribeFromPort = void 0;
57
- this._clearOpenInterval = void 0;
58
- this._params = {
59
- timeout: void 0,
60
- streamHandler: void 0,
61
- noHandshake: false,
62
- ...params
63
- };
64
- }
65
- /**
66
- * Open the peer. Required before making any calls.
67
- *
68
- * Will block before the other peer calls `open`.
69
- */
70
- async open() {
71
- if (this._state !== "INITIAL") {
72
- return;
73
- }
74
- this._unsubscribeFromPort = this._params.port.subscribe(async (msg) => {
75
- try {
76
- await this._receive(msg);
77
- } catch (err) {
78
- log.catch(err, void 0, {
79
- F: __dxlog_file,
80
- L: 156,
81
- S: this,
82
- C: (f, a) => f(...a)
83
- });
84
- }
85
- });
86
- this._state = "OPENING";
87
- if (this._params.noHandshake) {
88
- this._state = "OPENED";
89
- this._remoteOpenTrigger.wake();
90
- return;
91
- }
92
- log("sending open message", {
93
- state: this._state
94
- }, {
95
- F: __dxlog_file,
96
- L: 168,
97
- S: this,
98
- C: (f, a) => f(...a)
99
- });
100
- await this._sendMessage({
101
- open: true
102
- });
103
- if (this._state !== "OPENING") {
104
- return;
105
- }
106
- this._clearOpenInterval = exponentialBackoffInterval(() => {
107
- void this._sendMessage({
108
- open: true
109
- }).catch((err) => log.warn(err, void 0, {
110
- F: __dxlog_file,
111
- L: 177,
112
- S: this,
113
- C: (f, a) => f(...a)
114
- }));
115
- }, 50);
116
- await Promise.race([
117
- this._remoteOpenTrigger.wait(),
118
- this._closingTrigger.wait()
119
- ]);
120
- this._clearOpenInterval?.();
121
- if (this._state !== "OPENED") {
122
- return;
123
- }
124
- log("resending open message", {
125
- state: this._state
126
- }, {
127
- F: __dxlog_file,
128
- L: 191,
129
- S: this,
130
- C: (f, a) => f(...a)
131
- });
132
- await this._sendMessage({
133
- openAck: true
134
- });
135
- }
136
- /**
137
- * Close the peer.
138
- * Stop taking or making requests.
139
- * Will wait for confirmation from the other side.
140
- * Any responses for RPC calls made before close will be delivered.
141
- */
142
- async close({ timeout = CLOSE_TIMEOUT } = {}) {
143
- if (this._state === "CLOSED") {
144
- return;
145
- }
146
- this._abortRequests();
147
- if (this._state === "OPENED" && !this._params.noHandshake) {
148
- try {
149
- this._state = "CLOSING";
150
- await this._sendMessage({
151
- bye: {}
152
- }, BYE_SEND_TIMEOUT);
153
- } catch (err) {
154
- log("error closing peer, sending bye", {
155
- err
156
- }, {
157
- F: __dxlog_file,
158
- L: 213,
159
- S: this,
160
- C: (f, a) => f(...a)
161
- });
162
- }
163
- try {
164
- log("closing waiting on bye", void 0, {
165
- F: __dxlog_file,
166
- L: 216,
167
- S: this,
168
- C: (f, a) => f(...a)
169
- });
170
- await this._byeTrigger.wait({
171
- timeout
172
- });
173
- } catch (err) {
174
- log("error closing peer", {
175
- err
176
- }, {
177
- F: __dxlog_file,
178
- L: 219,
179
- S: this,
180
- C: (f, a) => f(...a)
181
- });
182
- return;
183
- }
184
- }
185
- this._disposeAndClose();
186
- }
187
- /**
188
- * Dispose the connection without waiting for the other side.
189
- */
190
- async abort() {
191
- if (this._state === "CLOSED") {
192
- return;
193
- }
194
- this._abortRequests();
195
- this._disposeAndClose();
196
- }
197
- _abortRequests() {
198
- this._clearOpenInterval?.();
199
- this._closingTrigger.wake();
200
- for (const req of this._outgoingRequests.values()) {
201
- req.reject(new RpcClosedError());
202
- }
203
- this._outgoingRequests.clear();
204
- }
205
- _disposeAndClose() {
206
- this._unsubscribeFromPort?.();
207
- this._unsubscribeFromPort = void 0;
208
- this._clearOpenInterval?.();
209
- this._state = "CLOSED";
210
- }
211
- /**
212
- * Handle incoming message. Should be called as the result of other peer's `send` callback.
213
- */
214
- async _receive(msg) {
215
- const decoded = getRpcMessageCodec().decode(msg, {
216
- preserveAny: true
217
- });
218
- DEBUG_CALLS && log("received message", {
219
- type: Object.keys(decoded)[0]
220
- }, {
221
- F: __dxlog_file,
222
- L: 263,
223
- S: this,
224
- C: (f, a) => f(...a)
225
- });
226
- if (decoded.request) {
227
- if (this._state !== "OPENED" && this._state !== "OPENING") {
228
- log("received request while closed", void 0, {
229
- F: __dxlog_file,
230
- L: 267,
231
- S: this,
232
- C: (f, a) => f(...a)
233
- });
234
- await this._sendMessage({
235
- response: {
236
- id: decoded.request.id,
237
- error: encodeError(new RpcClosedError())
238
- }
239
- });
240
- return;
241
- }
242
- const req = decoded.request;
243
- if (req.stream) {
244
- log("stream request", {
245
- method: req.method
246
- }, {
247
- F: __dxlog_file,
248
- L: 279,
249
- S: this,
250
- C: (f, a) => f(...a)
251
- });
252
- this._callStreamHandler(req, (response) => {
253
- log("sending stream response", {
254
- method: req.method,
255
- response: response.payload?.type_url,
256
- error: response.error,
257
- close: response.close
258
- }, {
259
- F: __dxlog_file,
260
- L: 281,
261
- S: this,
262
- C: (f, a) => f(...a)
263
- });
264
- void this._sendMessage({
265
- response
266
- }).catch((err) => {
267
- log.warn("failed during close", err, {
268
- F: __dxlog_file,
269
- L: 289,
270
- S: this,
271
- C: (f, a) => f(...a)
272
- });
273
- });
274
- });
275
- } else {
276
- DEBUG_CALLS && log("requesting...", {
277
- method: req.method
278
- }, {
279
- F: __dxlog_file,
280
- L: 293,
281
- S: this,
282
- C: (f, a) => f(...a)
283
- });
284
- const response = await this._callHandler(req);
285
- DEBUG_CALLS && log("sending response", {
286
- method: req.method,
287
- response: response.payload?.type_url,
288
- error: response.error
289
- }, {
290
- F: __dxlog_file,
291
- L: 296,
292
- S: this,
293
- C: (f, a) => f(...a)
294
- });
295
- await this._sendMessage({
296
- response
297
- });
298
- }
299
- } else if (decoded.response) {
300
- if (this._state !== "OPENED") {
301
- log("received response while closed", void 0, {
302
- F: __dxlog_file,
303
- L: 305,
304
- S: this,
305
- C: (f, a) => f(...a)
306
- });
307
- return;
308
- }
309
- const responseId = decoded.response.id;
310
- invariant(typeof responseId === "number", void 0, {
311
- F: __dxlog_file,
312
- L: 310,
313
- S: this,
314
- A: [
315
- "typeof responseId === 'number'",
316
- ""
317
- ]
318
- });
319
- if (!this._outgoingRequests.has(responseId)) {
320
- log("received response with invalid id", {
321
- responseId
322
- }, {
323
- F: __dxlog_file,
324
- L: 312,
325
- S: this,
326
- C: (f, a) => f(...a)
327
- });
328
- return;
329
- }
330
- const item = this._outgoingRequests.get(responseId);
331
- if (!item.stream) {
332
- this._outgoingRequests.delete(responseId);
333
- }
334
- DEBUG_CALLS && log("response", {
335
- type_url: decoded.response.payload?.type_url
336
- }, {
337
- F: __dxlog_file,
338
- L: 322,
339
- S: this,
340
- C: (f, a) => f(...a)
341
- });
342
- item.resolve(decoded.response);
343
- } else if (decoded.open) {
344
- log("received open message", {
345
- state: this._state
346
- }, {
347
- F: __dxlog_file,
348
- L: 325,
349
- S: this,
350
- C: (f, a) => f(...a)
351
- });
352
- if (this._params.noHandshake) {
353
- return;
354
- }
355
- await this._sendMessage({
356
- openAck: true
357
- });
358
- } else if (decoded.openAck) {
359
- log("received openAck message", {
360
- state: this._state
361
- }, {
362
- F: __dxlog_file,
363
- L: 332,
364
- S: this,
365
- C: (f, a) => f(...a)
366
- });
367
- if (this._params.noHandshake) {
368
- return;
369
- }
370
- this._state = "OPENED";
371
- this._remoteOpenTrigger.wake();
372
- } else if (decoded.streamClose) {
373
- if (this._state !== "OPENED") {
374
- log("received stream close while closed", void 0, {
375
- F: __dxlog_file,
376
- L: 341,
377
- S: this,
378
- C: (f, a) => f(...a)
379
- });
380
- return;
381
- }
382
- log("received stream close", {
383
- id: decoded.streamClose.id
384
- }, {
385
- F: __dxlog_file,
386
- L: 345,
387
- S: this,
388
- C: (f, a) => f(...a)
389
- });
390
- invariant(typeof decoded.streamClose.id === "number", void 0, {
391
- F: __dxlog_file,
392
- L: 346,
393
- S: this,
394
- A: [
395
- "typeof decoded.streamClose.id === 'number'",
396
- ""
397
- ]
398
- });
399
- const stream = this._localStreams.get(decoded.streamClose.id);
400
- if (!stream) {
401
- log("no local stream", {
402
- id: decoded.streamClose.id
403
- }, {
404
- F: __dxlog_file,
405
- L: 349,
406
- S: this,
407
- C: (f, a) => f(...a)
408
- });
409
- return;
410
- }
411
- this._localStreams.delete(decoded.streamClose.id);
412
- await stream.close();
413
- } else if (decoded.bye) {
414
- this._byeTrigger.wake();
415
- if (this._state !== "CLOSING" && this._state !== "CLOSED") {
416
- log("replying to bye", void 0, {
417
- F: __dxlog_file,
418
- L: 359,
419
- S: this,
420
- C: (f, a) => f(...a)
421
- });
422
- this._state = "CLOSING";
423
- await this._sendMessage({
424
- bye: {}
425
- });
426
- this._abortRequests();
427
- this._disposeAndClose();
428
- }
429
- } else {
430
- log.error("received malformed message", {
431
- msg
432
- }, {
433
- F: __dxlog_file,
434
- L: 367,
435
- S: this,
436
- C: (f, a) => f(...a)
437
- });
438
- throw new Error("Malformed message.");
439
- }
440
- }
441
- /**
442
- * Make RPC call. Will trigger a handler on the other side.
443
- * Peer should be open before making this call.
444
- */
445
- async call(method, request, options) {
446
- DEBUG_CALLS && log("calling...", {
447
- method
448
- }, {
449
- F: __dxlog_file,
450
- L: 377,
451
- S: this,
452
- C: (f, a) => f(...a)
453
- });
454
- throwIfNotOpen(this._state);
455
- let response;
456
- try {
457
- const id = this._nextId++;
458
- const responseReceived = new Promise((resolve, reject) => {
459
- this._outgoingRequests.set(id, new PendingRpcRequest(resolve, reject, false));
460
- });
461
- const sending = this._sendMessage({
462
- request: {
463
- id,
464
- method,
465
- payload: request,
466
- stream: false
467
- }
468
- });
469
- const timeout = options?.timeout ?? this._params.timeout;
470
- const waiting = timeout === 0 ? responseReceived : asyncTimeout(responseReceived, timeout ?? DEFAULT_TIMEOUT);
471
- await Promise.race([
472
- sending,
473
- waiting
474
- ]);
475
- response = await waiting;
476
- invariant(response.id === id, void 0, {
477
- F: __dxlog_file,
478
- L: 405,
479
- S: this,
480
- A: [
481
- "response.id === id",
482
- ""
483
- ]
484
- });
485
- } catch (err) {
486
- if (err instanceof RpcClosedError) {
487
- const error = new RpcClosedError();
488
- error.stack += `
489
-
490
- info: RPC client was closed at:
491
- ${err.stack?.split("\n").slice(1).join("\n")}`;
492
- throw error;
493
- }
494
- throw err;
495
- }
496
- if (response.payload) {
497
- return response.payload;
498
- } else if (response.error) {
499
- throw decodeRpcError(response.error, method);
500
- } else {
501
- throw new Error("Malformed response.");
502
- }
503
- }
504
- /**
505
- * Make RPC call with a streaming response.
506
- * Will trigger a handler on the other side.
507
- * Peer should be open before making this call.
508
- */
509
- callStream(method, request, options) {
510
- throwIfNotOpen(this._state);
511
- const id = this._nextId++;
512
- return new Stream(({ ready, next, close }) => {
513
- const onResponse = (response) => {
514
- if (response.streamReady) {
515
- ready();
516
- } else if (response.close) {
517
- close();
518
- } else if (response.error) {
519
- close(decodeRpcError(response.error, method));
520
- } else if (response.payload) {
521
- next(response.payload);
522
- } else {
523
- throw new Error("Malformed response.");
524
- }
525
- };
526
- const stack = new StackTrace2();
527
- const closeStream = (err) => {
528
- if (!err) {
529
- close();
530
- } else {
531
- err.stack += `
532
-
533
- Error happened in the stream at:
534
- ${stack.getStack()}`;
535
- close(err);
536
- }
537
- };
538
- this._outgoingRequests.set(id, new PendingRpcRequest(onResponse, closeStream, true));
539
- this._sendMessage({
540
- request: {
541
- id,
542
- method,
543
- payload: request,
544
- stream: true
545
- }
546
- }).catch((err) => {
547
- close(err);
548
- });
549
- return () => {
550
- this._sendMessage({
551
- streamClose: {
552
- id
553
- }
554
- }).catch((err) => {
555
- log.catch(err, void 0, {
556
- F: __dxlog_file,
557
- L: 478,
558
- S: this,
559
- C: (f, a) => f(...a)
560
- });
561
- });
562
- this._outgoingRequests.delete(id);
563
- };
564
- });
565
- }
566
- async _sendMessage(message, timeout) {
567
- DEBUG_CALLS && log("sending message", {
568
- type: Object.keys(message)[0]
569
- }, {
570
- F: __dxlog_file,
571
- L: 486,
572
- S: this,
573
- C: (f, a) => f(...a)
574
- });
575
- await this._params.port.send(getRpcMessageCodec().encode(message, {
576
- preserveAny: true
577
- }), timeout);
578
- }
579
- async _callHandler(req) {
580
- try {
581
- invariant(typeof req.id === "number", void 0, {
582
- F: __dxlog_file,
583
- L: 492,
584
- S: this,
585
- A: [
586
- "typeof req.id === 'number'",
587
- ""
588
- ]
589
- });
590
- invariant(req.payload, void 0, {
591
- F: __dxlog_file,
592
- L: 493,
593
- S: this,
594
- A: [
595
- "req.payload",
596
- ""
597
- ]
598
- });
599
- invariant(req.method, void 0, {
600
- F: __dxlog_file,
601
- L: 494,
602
- S: this,
603
- A: [
604
- "req.method",
605
- ""
606
- ]
607
- });
608
- const response = await this._params.callHandler(req.method, req.payload, this._params.handlerRpcOptions);
609
- return {
610
- id: req.id,
611
- payload: response
612
- };
613
- } catch (err) {
614
- return {
615
- id: req.id,
616
- error: encodeError(err)
617
- };
618
- }
619
- }
620
- _callStreamHandler(req, callback) {
621
- try {
622
- invariant(this._params.streamHandler, "Requests with streaming responses are not supported.", {
623
- F: __dxlog_file,
624
- L: 511,
625
- S: this,
626
- A: [
627
- "this._params.streamHandler",
628
- "'Requests with streaming responses are not supported.'"
629
- ]
630
- });
631
- invariant(typeof req.id === "number", void 0, {
632
- F: __dxlog_file,
633
- L: 512,
634
- S: this,
635
- A: [
636
- "typeof req.id === 'number'",
637
- ""
638
- ]
639
- });
640
- invariant(req.payload, void 0, {
641
- F: __dxlog_file,
642
- L: 513,
643
- S: this,
644
- A: [
645
- "req.payload",
646
- ""
647
- ]
648
- });
649
- invariant(req.method, void 0, {
650
- F: __dxlog_file,
651
- L: 514,
652
- S: this,
653
- A: [
654
- "req.method",
655
- ""
656
- ]
657
- });
658
- const responseStream = this._params.streamHandler(req.method, req.payload, this._params.handlerRpcOptions);
659
- responseStream.onReady(() => {
660
- callback({
661
- id: req.id,
662
- streamReady: true
663
- });
664
- });
665
- responseStream.subscribe((msg) => {
666
- callback({
667
- id: req.id,
668
- payload: msg
669
- });
670
- }, (error) => {
671
- if (error) {
672
- callback({
673
- id: req.id,
674
- error: encodeError(error)
675
- });
676
- } else {
677
- callback({
678
- id: req.id,
679
- close: true
680
- });
681
- }
682
- });
683
- this._localStreams.set(req.id, responseStream);
684
- } catch (err) {
685
- callback({
686
- id: req.id,
687
- error: encodeError(err)
688
- });
689
- }
690
- }
691
- };
692
- _ts_decorate([
693
- synchronized
694
- ], RpcPeer.prototype, "open", null);
695
- var throwIfNotOpen = (state) => {
696
- switch (state) {
697
- case "OPENED": {
698
- return;
699
- }
700
- case "INITIAL": {
701
- throw new RpcNotOpenError();
702
- }
703
- case "CLOSED": {
704
- throw new RpcClosedError();
705
- }
706
- }
707
- };
708
-
709
- // src/service.ts
710
- import { invariant as invariant2 } from "@dxos/invariant";
711
- var __dxlog_file2 = "/__w/dxos/dxos/packages/core/mesh/rpc/src/service.ts";
712
- var createServiceBundle = (services) => services;
713
- var ProtoRpcPeer = class {
714
- constructor(rpc, _peer) {
715
- this.rpc = rpc;
716
- this._peer = _peer;
717
- }
718
- async open() {
719
- await this._peer.open();
720
- }
721
- async close() {
722
- await this._peer.close();
723
- }
724
- async abort() {
725
- await this._peer.abort();
726
- }
727
- };
728
- var createProtoRpcPeer = ({ requested, exposed, handlers, encodingOptions, ...rest }) => {
729
- const exposedRpcs = {};
730
- if (exposed) {
731
- invariant2(handlers, void 0, {
732
- F: __dxlog_file2,
733
- L: 93,
734
- S: void 0,
735
- A: [
736
- "handlers",
737
- ""
738
- ]
739
- });
740
- for (const serviceName of Object.keys(exposed)) {
741
- const serviceFqn = exposed[serviceName].serviceProto.fullName.slice(1);
742
- const serviceProvider = handlers[serviceName];
743
- exposedRpcs[serviceFqn] = exposed[serviceName].createServer(serviceProvider, encodingOptions);
744
- }
745
- }
746
- const peer = new RpcPeer({
747
- ...rest,
748
- callHandler: (method, request, options) => {
749
- const [serviceName, methodName] = parseMethodName(method);
750
- if (!exposedRpcs[serviceName]) {
751
- throw new Error(`Service not supported: ${serviceName}`);
752
- }
753
- return exposedRpcs[serviceName].call(methodName, request, options);
754
- },
755
- streamHandler: (method, request, options) => {
756
- const [serviceName, methodName] = parseMethodName(method);
757
- if (!exposedRpcs[serviceName]) {
758
- throw new Error(`Service not supported: ${serviceName}`);
759
- }
760
- return exposedRpcs[serviceName].callStream(methodName, request, options);
761
- }
762
- });
763
- const requestedRpcs = {};
764
- if (requested) {
765
- for (const serviceName of Object.keys(requested)) {
766
- const serviceFqn = requested[serviceName].serviceProto.fullName.slice(1);
767
- requestedRpcs[serviceName] = requested[serviceName].createClient({
768
- call: (method, req, options) => peer.call(`${serviceFqn}.${method}`, req, options),
769
- callStream: (method, req, options) => peer.callStream(`${serviceFqn}.${method}`, req, options)
770
- }, encodingOptions);
771
- }
772
- }
773
- return new ProtoRpcPeer(requestedRpcs, peer);
774
- };
775
- var parseMethodName = (method) => {
776
- const separator = method.lastIndexOf(".");
777
- const serviceName = method.slice(0, separator);
778
- const methodName = method.slice(separator + 1);
779
- if (serviceName.length === 0 || methodName.length === 0) {
780
- throw new Error(`Invalid method: ${method}`);
781
- }
782
- return [
783
- serviceName,
784
- methodName
785
- ];
786
- };
787
- var createRpcClient = (serviceDef, options) => {
788
- const peer = new RpcPeer({
789
- ...options,
790
- callHandler: () => {
791
- throw new Error("Requests to client are not supported.");
792
- }
793
- });
794
- const client = serviceDef.createClient({
795
- call: peer.call.bind(peer),
796
- callStream: peer.callStream.bind(peer)
797
- });
798
- return new ProtoRpcPeer(client, peer);
799
- };
800
- var createRpcServer = ({ service, handlers, ...rest }) => {
801
- const server = service.createServer(handlers);
802
- return new RpcPeer({
803
- ...rest,
804
- callHandler: server.call.bind(server),
805
- streamHandler: server.callStream.bind(server)
806
- });
807
- };
808
- var createBundledRpcClient = (descriptors, options) => {
809
- return createProtoRpcPeer({
810
- requested: descriptors,
811
- ...options
812
- });
813
- };
814
- var createBundledRpcServer = ({ services, handlers, ...rest }) => {
815
- const rpc = {};
816
- for (const serviceName of Object.keys(services)) {
817
- const serviceFqn = services[serviceName].serviceProto.fullName.slice(1);
818
- rpc[serviceFqn] = services[serviceName].createServer(handlers[serviceName]);
819
- }
820
- return new RpcPeer({
821
- ...rest,
822
- callHandler: (method, request) => {
823
- const [serviceName, methodName] = parseMethodName(method);
824
- if (!rpc[serviceName]) {
825
- throw new Error(`Service not supported: ${serviceName}`);
826
- }
827
- return rpc[serviceName].call(methodName, request);
828
- },
829
- streamHandler: (method, request) => {
830
- const [serviceName, methodName] = parseMethodName(method);
831
- if (!rpc[serviceName]) {
832
- throw new Error(`Service not supported: ${serviceName}`);
833
- }
834
- return rpc[serviceName].callStream(methodName, request);
835
- }
836
- });
837
- };
838
-
839
- // src/testing.ts
840
- import { isNode } from "@dxos/util";
841
- var createLinkedPorts = ({ delay } = {}) => {
842
- let port1Received;
843
- let port2Received;
844
- const send = (handler, msg) => {
845
- if (delay) {
846
- setTimeout(() => handler?.(msg), delay);
847
- } else {
848
- void handler?.(msg);
849
- }
850
- };
851
- const port1 = {
852
- send: (msg) => send(port2Received, msg),
853
- subscribe: (cb) => {
854
- port1Received = cb;
855
- }
856
- };
857
- const port2 = {
858
- send: (msg) => send(port1Received, msg),
859
- subscribe: (cb) => {
860
- port2Received = cb;
861
- }
862
- };
863
- return [
864
- port1,
865
- port2
866
- ];
867
- };
868
- var encodeMessage = (msg) => isNode() ? Buffer.from(msg) : new TextEncoder().encode(msg);
869
-
870
- // src/trace.ts
871
- import { Event } from "@dxos/async";
872
- import { MessageTrace } from "@dxos/protocols/proto/dxos/rpc";
873
- var PortTracer = class {
874
- constructor(_wrappedPort) {
875
- this._wrappedPort = _wrappedPort;
876
- this.message = new Event();
877
- this._port = {
878
- send: (msg) => {
879
- this.message.emit({
880
- direction: MessageTrace.Direction.OUTGOING,
881
- data: msg
882
- });
883
- return this._wrappedPort.send(msg);
884
- },
885
- subscribe: (cb) => {
886
- return this._wrappedPort.subscribe((msg) => {
887
- this.message.emit({
888
- direction: MessageTrace.Direction.INCOMING,
889
- data: msg
890
- });
891
- cb(msg);
892
- });
893
- }
894
- };
895
- }
896
- get port() {
897
- return this._port;
898
- }
899
- };
900
- export {
901
- PortTracer,
902
- ProtoRpcPeer,
903
- RpcPeer,
904
- createBundledRpcClient,
905
- createBundledRpcServer,
906
- createLinkedPorts,
907
- createProtoRpcPeer,
908
- createRpcClient,
909
- createRpcServer,
910
- createServiceBundle,
911
- decodeRpcError,
912
- encodeMessage,
913
- parseMethodName
914
- };
915
- //# sourceMappingURL=index.mjs.map