@dxos/network-manager 0.6.13 → 0.6.14-main.2b6a0f3

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 (164) hide show
  1. package/dist/lib/browser/chunk-GW3YM55A.mjs +14 -0
  2. package/dist/lib/browser/chunk-GW3YM55A.mjs.map +7 -0
  3. package/dist/lib/browser/{chunk-XYSYUN63.mjs → chunk-V3IRGRVX.mjs} +1501 -1655
  4. package/dist/lib/browser/chunk-V3IRGRVX.mjs.map +7 -0
  5. package/dist/lib/browser/index.mjs +347 -22
  6. package/dist/lib/browser/index.mjs.map +4 -4
  7. package/dist/lib/browser/meta.json +1 -1
  8. package/dist/lib/browser/testing/index.mjs +22 -32
  9. package/dist/lib/browser/testing/index.mjs.map +3 -3
  10. package/dist/lib/browser/transport/tcp/index.mjs +39 -0
  11. package/dist/lib/browser/transport/tcp/index.mjs.map +7 -0
  12. package/dist/lib/node/{chunk-4YAYC7WN.cjs → chunk-4TTFBX3M.cjs} +1504 -1782
  13. package/dist/lib/node/chunk-4TTFBX3M.cjs.map +7 -0
  14. package/dist/lib/node/index.cjs +356 -37
  15. package/dist/lib/node/index.cjs.map +4 -4
  16. package/dist/lib/node/meta.json +1 -1
  17. package/dist/lib/node/testing/index.cjs +24 -34
  18. package/dist/lib/node/testing/index.cjs.map +3 -3
  19. package/dist/lib/node/transport/tcp/index.cjs +191 -0
  20. package/dist/lib/node/transport/tcp/index.cjs.map +7 -0
  21. package/dist/lib/node-esm/chunk-6MN5JVRP.mjs +4035 -0
  22. package/dist/lib/node-esm/chunk-6MN5JVRP.mjs.map +7 -0
  23. package/dist/lib/node-esm/index.mjs +382 -0
  24. package/dist/lib/node-esm/index.mjs.map +7 -0
  25. package/dist/lib/node-esm/meta.json +1 -0
  26. package/dist/lib/node-esm/testing/index.mjs +279 -0
  27. package/dist/lib/node-esm/testing/index.mjs.map +7 -0
  28. package/dist/lib/node-esm/transport/tcp/index.mjs +159 -0
  29. package/dist/lib/node-esm/transport/tcp/index.mjs.map +7 -0
  30. package/dist/types/src/network-manager.d.ts +2 -1
  31. package/dist/types/src/network-manager.d.ts.map +1 -1
  32. package/dist/types/src/signal/ice.d.ts.map +1 -1
  33. package/dist/types/src/signal/integration.node.test.d.ts +2 -0
  34. package/dist/types/src/signal/integration.node.test.d.ts.map +1 -0
  35. package/dist/types/src/signal/swarm-messenger.node.test.d.ts +2 -0
  36. package/dist/types/src/signal/swarm-messenger.node.test.d.ts.map +1 -0
  37. package/dist/types/src/swarm/connection.d.ts.map +1 -1
  38. package/dist/types/src/swarm/swarm.d.ts +1 -1
  39. package/dist/types/src/testing/test-builder.d.ts +2 -2
  40. package/dist/types/src/testing/test-builder.d.ts.map +1 -1
  41. package/dist/types/src/testing/test-wire-protocol.d.ts +1 -2
  42. package/dist/types/src/testing/test-wire-protocol.d.ts.map +1 -1
  43. package/dist/types/src/tests/basic-test-suite.d.ts.map +1 -1
  44. package/dist/types/src/tests/property-test-suite.d.ts.map +1 -1
  45. package/dist/types/src/tests/tcp-transport.node.test.d.ts +2 -0
  46. package/dist/types/src/tests/tcp-transport.node.test.d.ts.map +1 -0
  47. package/dist/types/src/tests/utils.d.ts.map +1 -1
  48. package/dist/types/src/transport/index.d.ts +1 -5
  49. package/dist/types/src/transport/index.d.ts.map +1 -1
  50. package/dist/types/src/transport/memory-transport.d.ts +2 -2
  51. package/dist/types/src/transport/memory-transport.d.ts.map +1 -1
  52. package/dist/types/src/transport/tcp/index.d.ts +2 -0
  53. package/dist/types/src/transport/tcp/index.d.ts.map +1 -0
  54. package/dist/types/src/transport/{tcp-transport.browser.d.ts → tcp/tcp-transport.browser.d.ts} +3 -3
  55. package/dist/types/src/transport/tcp/tcp-transport.browser.d.ts.map +1 -0
  56. package/dist/types/src/transport/{tcp-transport.d.ts → tcp/tcp-transport.d.ts} +3 -3
  57. package/dist/types/src/transport/tcp/tcp-transport.d.ts.map +1 -0
  58. package/dist/types/src/transport/transport.d.ts +7 -6
  59. package/dist/types/src/transport/transport.d.ts.map +1 -1
  60. package/dist/types/src/transport/webrtc/index.d.ts +4 -0
  61. package/dist/types/src/transport/webrtc/index.d.ts.map +1 -0
  62. package/dist/types/src/transport/webrtc/rtc-connection-factory.d.ts +14 -0
  63. package/dist/types/src/transport/webrtc/rtc-connection-factory.d.ts.map +1 -0
  64. package/dist/types/src/transport/webrtc/rtc-peer-connection.d.ts +68 -0
  65. package/dist/types/src/transport/webrtc/rtc-peer-connection.d.ts.map +1 -0
  66. package/dist/types/src/transport/webrtc/rtc-transport-channel.d.ts +33 -0
  67. package/dist/types/src/transport/webrtc/rtc-transport-channel.d.ts.map +1 -0
  68. package/dist/types/src/transport/webrtc/rtc-transport-channel.test.d.ts +2 -0
  69. package/dist/types/src/transport/webrtc/rtc-transport-channel.test.d.ts.map +1 -0
  70. package/dist/types/src/transport/webrtc/rtc-transport-factory.d.ts +4 -0
  71. package/dist/types/src/transport/webrtc/rtc-transport-factory.d.ts.map +1 -0
  72. package/dist/types/src/transport/{simplepeer-transport-proxy.d.ts → webrtc/rtc-transport-proxy.d.ts} +10 -12
  73. package/dist/types/src/transport/webrtc/rtc-transport-proxy.d.ts.map +1 -0
  74. package/dist/types/src/transport/webrtc/rtc-transport-proxy.test.d.ts +2 -0
  75. package/dist/types/src/transport/webrtc/rtc-transport-proxy.test.d.ts.map +1 -0
  76. package/dist/types/src/transport/{simplepeer-transport-service.d.ts → webrtc/rtc-transport-service.d.ts} +9 -7
  77. package/dist/types/src/transport/webrtc/rtc-transport-service.d.ts.map +1 -0
  78. package/dist/types/src/transport/webrtc/rtc-transport-stats.d.ts +4 -0
  79. package/dist/types/src/transport/webrtc/rtc-transport-stats.d.ts.map +1 -0
  80. package/dist/types/src/transport/webrtc/rtc-transport.test.d.ts +2 -0
  81. package/dist/types/src/transport/webrtc/rtc-transport.test.d.ts.map +1 -0
  82. package/dist/types/src/transport/webrtc/test-utils.d.ts +5 -0
  83. package/dist/types/src/transport/webrtc/test-utils.d.ts.map +1 -0
  84. package/dist/types/src/transport/webrtc/utils.d.ts +3 -0
  85. package/dist/types/src/transport/webrtc/utils.d.ts.map +1 -0
  86. package/package.json +56 -30
  87. package/src/network-manager.ts +5 -13
  88. package/src/signal/ice.test.ts +1 -3
  89. package/src/signal/ice.ts +6 -1
  90. package/src/signal/{integration.test.ts → integration.node.test.ts} +9 -15
  91. package/src/signal/{swarm-messenger.test.ts → swarm-messenger.node.test.ts} +13 -23
  92. package/src/swarm/connection-limiter.test.ts +3 -6
  93. package/src/swarm/connection.test.ts +63 -38
  94. package/src/swarm/connection.ts +5 -5
  95. package/src/swarm/swarm.test.ts +10 -12
  96. package/src/swarm/swarm.ts +1 -1
  97. package/src/testing/test-builder.ts +13 -29
  98. package/src/testing/test-wire-protocol.ts +1 -4
  99. package/src/tests/basic-test-suite.ts +34 -33
  100. package/src/tests/memory-transport.test.ts +40 -42
  101. package/src/tests/property-test-suite.ts +21 -22
  102. package/src/tests/tcp-transport.node.test.ts +65 -0
  103. package/src/tests/utils.ts +3 -2
  104. package/src/tests/webrtc-transport.test.ts +9 -9
  105. package/src/transport/index.ts +1 -5
  106. package/src/transport/memory-transport.ts +2 -0
  107. package/src/transport/tcp/index.ts +5 -0
  108. package/src/transport/{tcp-transport.browser.ts → tcp/tcp-transport.browser.ts} +7 -3
  109. package/src/transport/{tcp-transport.ts → tcp/tcp-transport.ts} +3 -1
  110. package/src/transport/transport.ts +8 -7
  111. package/src/transport/webrtc/index.ts +7 -0
  112. package/src/transport/webrtc/rtc-connection-factory.ts +82 -0
  113. package/src/transport/webrtc/rtc-peer-connection.ts +472 -0
  114. package/src/transport/webrtc/rtc-transport-channel.test.ts +176 -0
  115. package/src/transport/webrtc/rtc-transport-channel.ts +195 -0
  116. package/src/transport/webrtc/rtc-transport-factory.ts +28 -0
  117. package/src/transport/webrtc/rtc-transport-proxy.test.ts +413 -0
  118. package/src/transport/webrtc/rtc-transport-proxy.ts +264 -0
  119. package/src/transport/webrtc/rtc-transport-service.ts +192 -0
  120. package/src/transport/webrtc/rtc-transport-stats.ts +67 -0
  121. package/src/transport/webrtc/rtc-transport.test.ts +198 -0
  122. package/src/transport/webrtc/test-utils.ts +22 -0
  123. package/src/transport/webrtc/utils.ts +36 -0
  124. package/src/typings.d.ts +8 -2
  125. package/dist/lib/browser/chunk-XYSYUN63.mjs.map +0 -7
  126. package/dist/lib/node/chunk-4YAYC7WN.cjs.map +0 -7
  127. package/dist/types/src/signal/integration.test.d.ts +0 -2
  128. package/dist/types/src/signal/integration.test.d.ts.map +0 -1
  129. package/dist/types/src/signal/swarm-messenger.test.d.ts +0 -2
  130. package/dist/types/src/signal/swarm-messenger.test.d.ts.map +0 -1
  131. package/dist/types/src/tests/tcp-transport.test.d.ts +0 -2
  132. package/dist/types/src/tests/tcp-transport.test.d.ts.map +0 -1
  133. package/dist/types/src/transport/libdatachannel-transport.d.ts +0 -42
  134. package/dist/types/src/transport/libdatachannel-transport.d.ts.map +0 -1
  135. package/dist/types/src/transport/libdatachannel-transport.test.d.ts +0 -2
  136. package/dist/types/src/transport/libdatachannel-transport.test.d.ts.map +0 -1
  137. package/dist/types/src/transport/memory-transport.test.d.ts +0 -2
  138. package/dist/types/src/transport/memory-transport.test.d.ts.map +0 -1
  139. package/dist/types/src/transport/simplepeer-simple-peer.d.ts +0 -2
  140. package/dist/types/src/transport/simplepeer-simple-peer.d.ts.map +0 -1
  141. package/dist/types/src/transport/simplepeer-transport-proxy-test.d.ts +0 -2
  142. package/dist/types/src/transport/simplepeer-transport-proxy-test.d.ts.map +0 -1
  143. package/dist/types/src/transport/simplepeer-transport-proxy.d.ts.map +0 -1
  144. package/dist/types/src/transport/simplepeer-transport-service.d.ts.map +0 -1
  145. package/dist/types/src/transport/simplepeer-transport.d.ts +0 -36
  146. package/dist/types/src/transport/simplepeer-transport.d.ts.map +0 -1
  147. package/dist/types/src/transport/simplepeer-transport.test.d.ts +0 -2
  148. package/dist/types/src/transport/simplepeer-transport.test.d.ts.map +0 -1
  149. package/dist/types/src/transport/tcp-transport.browser.d.ts.map +0 -1
  150. package/dist/types/src/transport/tcp-transport.d.ts.map +0 -1
  151. package/dist/types/src/transport/webrtc.d.ts +0 -6
  152. package/dist/types/src/transport/webrtc.d.ts.map +0 -1
  153. package/src/globals.d.ts +0 -7
  154. package/src/tests/tcp-transport.test.ts +0 -67
  155. package/src/transport/libdatachannel-transport.test.ts +0 -100
  156. package/src/transport/libdatachannel-transport.ts +0 -376
  157. package/src/transport/memory-transport.test.ts +0 -74
  158. package/src/transport/simplepeer-simple-peer.ts +0 -26
  159. package/src/transport/simplepeer-transport-proxy-test.ts +0 -181
  160. package/src/transport/simplepeer-transport-proxy.ts +0 -246
  161. package/src/transport/simplepeer-transport-service.ts +0 -160
  162. package/src/transport/simplepeer-transport.test.ts +0 -61
  163. package/src/transport/simplepeer-transport.ts +0 -250
  164. package/src/transport/webrtc.ts +0 -15
@@ -1,17 +1,7 @@
1
1
  import "@dxos/node-std/globals";
2
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
3
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
4
- }) : x)(function(x) {
5
- if (typeof require !== "undefined") return require.apply(this, arguments);
6
- throw Error('Dynamic require of "' + x + '" is not supported');
7
- });
8
-
9
- // inject-globals:@inject-globals
10
2
  import {
11
- global,
12
- Buffer as Buffer2,
13
- process
14
- } from "@dxos/node-std/inject-globals";
3
+ Buffer
4
+ } from "./chunk-GW3YM55A.mjs";
15
5
 
16
6
  // packages/core/mesh/network-manager/src/swarm/connection.ts
17
7
  import { DeferredTask, Event, sleep, scheduleTask, scheduleTaskInterval, synchronized, Trigger } from "@dxos/async";
@@ -20,7 +10,7 @@ import { ErrorStream } from "@dxos/debug";
20
10
  import { invariant } from "@dxos/invariant";
21
11
  import { PublicKey } from "@dxos/keys";
22
12
  import { log, logInfo } from "@dxos/log";
23
- import { CancelledError, ProtocolError, ConnectionResetError, ConnectivityError, TimeoutError, UnknownProtocolError, trace } from "@dxos/protocols";
13
+ import { CancelledError, ProtocolError, ConnectionResetError, ConnectivityError, TimeoutError, trace } from "@dxos/protocols";
24
14
  function _ts_decorate(decorators, target, key, desc) {
25
15
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
26
16
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
@@ -56,11 +46,11 @@ var Connection = class {
56
46
  this._callbacks = _callbacks;
57
47
  this._ctx = new Context(void 0, {
58
48
  F: __dxlog_file,
59
- L: 101
49
+ L: 100
60
50
  });
61
51
  this.connectedTimeoutContext = new Context(void 0, {
62
52
  F: __dxlog_file,
63
- L: 102
53
+ L: 101
64
54
  });
65
55
  this._protocolClosed = new Trigger();
66
56
  this._transportClosed = new Trigger();
@@ -83,7 +73,7 @@ var Connection = class {
83
73
  initiator: this.initiator
84
74
  }, {
85
75
  F: __dxlog_file,
86
- L: 138,
76
+ L: 137,
87
77
  S: this,
88
78
  C: (f, a) => f(...a)
89
79
  });
@@ -106,7 +96,7 @@ var Connection = class {
106
96
  async openConnection() {
107
97
  invariant(this._state === "INITIAL", "Invalid state.", {
108
98
  F: __dxlog_file,
109
- L: 168,
99
+ L: 167,
110
100
  S: this,
111
101
  A: [
112
102
  "this._state === ConnectionState.INITIAL",
@@ -117,7 +107,7 @@ var Connection = class {
117
107
  id: this._instanceId
118
108
  }), {
119
109
  F: __dxlog_file,
120
- L: 169,
110
+ L: 168,
121
111
  S: this,
122
112
  C: (f, a) => f(...a)
123
113
  });
@@ -129,7 +119,7 @@ var Connection = class {
129
119
  initiator: this.initiator
130
120
  }, {
131
121
  F: __dxlog_file,
132
- L: 170,
122
+ L: 169,
133
123
  S: this,
134
124
  C: (f, a) => f(...a)
135
125
  });
@@ -140,7 +130,7 @@ var Connection = class {
140
130
  this._protocol.stream.on("close", () => {
141
131
  log("protocol stream closed", void 0, {
142
132
  F: __dxlog_file,
143
- L: 187,
133
+ L: 186,
144
134
  S: this,
145
135
  C: (f, a) => f(...a)
146
136
  });
@@ -150,7 +140,7 @@ var Connection = class {
150
140
  scheduleTask(this.connectedTimeoutContext, async () => {
151
141
  log.info(`timeout waiting ${TRANSPORT_CONNECTION_TIMEOUT / 1e3}s for transport to connect, aborting`, void 0, {
152
142
  F: __dxlog_file,
153
- L: 195,
143
+ L: 194,
154
144
  S: this,
155
145
  C: (f, a) => f(...a)
156
146
  });
@@ -158,7 +148,7 @@ var Connection = class {
158
148
  }, TRANSPORT_CONNECTION_TIMEOUT);
159
149
  invariant(!this._transport, void 0, {
160
150
  F: __dxlog_file,
161
- L: 203,
151
+ L: 202,
162
152
  S: this,
163
153
  A: [
164
154
  "!this._transport",
@@ -166,12 +156,14 @@ var Connection = class {
166
156
  ]
167
157
  });
168
158
  this._transport = this._transportFactory.createTransport({
159
+ ownPeerKey: this.localInfo.peerKey,
160
+ remotePeerKey: this.remoteInfo.peerKey,
161
+ topic: this.topic.toHex(),
169
162
  initiator: this.initiator,
170
163
  stream: this._protocol.stream,
171
164
  sendSignal: async (signal) => this._sendSignal(signal),
172
165
  sessionId: this.sessionId
173
166
  });
174
- await this._transport.open();
175
167
  this._transport.connected.once(async () => {
176
168
  this._changeState("CONNECTED");
177
169
  await this.connectedTimeoutContext.dispose();
@@ -217,21 +209,13 @@ var Connection = class {
217
209
  C: (f, a) => f(...a)
218
210
  });
219
211
  this.abort().catch((err2) => this.errors.raise(err2));
220
- } else if (err instanceof UnknownProtocolError) {
221
- log.warn("unsure what to do with UnknownProtocolError, will keep on truckin", {
222
- err
223
- }, {
224
- F: __dxlog_file,
225
- L: 242,
226
- S: this,
227
- C: (f, a) => f(...a)
228
- });
229
212
  }
230
213
  if (this._state !== "CLOSED" && this._state !== "CLOSING") {
231
214
  await this.connectedTimeoutContext.dispose();
232
215
  this.errors.raise(err);
233
216
  }
234
217
  });
218
+ await this._transport.open();
235
219
  for (const signal of this._incomingSignalBuffer) {
236
220
  void this._transport.onSignal(signal);
237
221
  }
@@ -584,48 +568,20 @@ _ts_decorate([
584
568
  synchronized
585
569
  ], Connection.prototype, "close", null);
586
570
 
587
- // packages/core/mesh/network-manager/src/signal/ice.ts
588
- import { asyncTimeout } from "@dxos/async";
589
- import { log as log2 } from "@dxos/log";
590
- import { isNotNullOrUndefined } from "@dxos/util";
591
- var __dxlog_file2 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/signal/ice.ts";
592
- var createIceProvider = (iceProviders) => {
593
- let cachedIceServers;
594
- return {
595
- getIceServers: async () => {
596
- if (cachedIceServers) {
597
- return cachedIceServers;
598
- }
599
- cachedIceServers = (await Promise.all(iceProviders.map(({ urls }) => asyncTimeout(fetch(urls, {
600
- method: "GET"
601
- }), 1e4).then((response) => response.json()).catch((err) => log2.error("Failed to fetch ICE servers from provider", {
602
- urls,
603
- err
604
- }, {
605
- F: __dxlog_file2,
606
- L: 27,
607
- S: void 0,
608
- C: (f, a) => f(...a)
609
- }))))).filter(isNotNullOrUndefined).map(({ iceServers }) => iceServers).flat();
610
- return cachedIceServers;
611
- }
612
- };
613
- };
614
-
615
571
  // packages/core/mesh/network-manager/src/signal/swarm-messenger.ts
616
572
  import { Context as Context2 } from "@dxos/context";
617
573
  import { invariant as invariant2 } from "@dxos/invariant";
618
574
  import { PublicKey as PublicKey2 } from "@dxos/keys";
619
- import { log as log3 } from "@dxos/log";
575
+ import { log as log2 } from "@dxos/log";
620
576
  import { TimeoutError as TimeoutError2 } from "@dxos/protocols";
621
577
  import { schema } from "@dxos/protocols/proto";
622
578
  import { ComplexMap } from "@dxos/util";
623
- var __dxlog_file3 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/signal/swarm-messenger.ts";
579
+ var __dxlog_file2 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/signal/swarm-messenger.ts";
624
580
  var SwarmMessage = schema.getCodecForType("dxos.mesh.swarm.SwarmMessage");
625
581
  var SwarmMessenger = class {
626
582
  constructor({ sendMessage, onSignal, onOffer, topic }) {
627
583
  this._ctx = new Context2(void 0, {
628
- F: __dxlog_file3,
584
+ F: __dxlog_file2,
629
585
  L: 35
630
586
  });
631
587
  this._offerRecords = new ComplexMap((key) => key.toHex());
@@ -642,12 +598,12 @@ var SwarmMessenger = class {
642
598
  if (!this._topic.equals(message.topic)) {
643
599
  return;
644
600
  }
645
- log3("received", {
601
+ log2("received", {
646
602
  from: author,
647
603
  to: recipient,
648
604
  msg: message
649
605
  }, {
650
- F: __dxlog_file3,
606
+ F: __dxlog_file2,
651
607
  L: 71,
652
608
  S: this,
653
609
  C: (f, a) => f(...a)
@@ -673,10 +629,10 @@ var SwarmMessenger = class {
673
629
  message
674
630
  });
675
631
  } else {
676
- log3.warn("unknown message", {
632
+ log2.warn("unknown message", {
677
633
  message
678
634
  }, {
679
- F: __dxlog_file3,
635
+ F: __dxlog_file2,
680
636
  L: 82,
681
637
  S: this,
682
638
  C: (f, a) => f(...a)
@@ -685,7 +641,7 @@ var SwarmMessenger = class {
685
641
  }
686
642
  async signal(message) {
687
643
  invariant2(message.data?.signal || message.data?.signalBatch, "Invalid message", {
688
- F: __dxlog_file3,
644
+ F: __dxlog_file2,
689
645
  L: 87,
690
646
  S: this,
691
647
  A: [
@@ -721,12 +677,12 @@ var SwarmMessenger = class {
721
677
  // Setting unique message_id if it not specified yet.
722
678
  messageId: message.messageId ?? PublicKey2.random()
723
679
  };
724
- log3("sending", {
680
+ log2("sending", {
725
681
  from: author,
726
682
  to: recipient,
727
683
  msg: networkMessage
728
684
  }, {
729
- F: __dxlog_file3,
685
+ F: __dxlog_file2,
730
686
  L: 125,
731
687
  S: this,
732
688
  C: (f, a) => f(...a)
@@ -742,7 +698,7 @@ var SwarmMessenger = class {
742
698
  }
743
699
  async _resolveAnswers(message) {
744
700
  invariant2(message.data?.answer?.offerMessageId, "No offerMessageId", {
745
- F: __dxlog_file3,
701
+ F: __dxlog_file2,
746
702
  L: 137,
747
703
  S: this,
748
704
  A: [
@@ -754,7 +710,7 @@ var SwarmMessenger = class {
754
710
  if (offerRecord) {
755
711
  this._offerRecords.delete(message.data.answer.offerMessageId);
756
712
  invariant2(message.data?.answer, "No answer", {
757
- F: __dxlog_file3,
713
+ F: __dxlog_file2,
758
714
  L: 141,
759
715
  S: this,
760
716
  A: [
@@ -762,10 +718,10 @@ var SwarmMessenger = class {
762
718
  "'No answer'"
763
719
  ]
764
720
  });
765
- log3("resolving", {
721
+ log2("resolving", {
766
722
  answer: message.data.answer
767
723
  }, {
768
- F: __dxlog_file3,
724
+ F: __dxlog_file2,
769
725
  L: 142,
770
726
  S: this,
771
727
  C: (f, a) => f(...a)
@@ -775,7 +731,7 @@ var SwarmMessenger = class {
775
731
  }
776
732
  async _handleOffer({ author, recipient, message }) {
777
733
  invariant2(message.data.offer, "No offer", {
778
- F: __dxlog_file3,
734
+ F: __dxlog_file2,
779
735
  L: 156,
780
736
  S: this,
781
737
  A: [
@@ -807,19 +763,19 @@ var SwarmMessenger = class {
807
763
  });
808
764
  } catch (err) {
809
765
  if (err instanceof TimeoutError2) {
810
- log3.info("timeout sending answer to offer", {
766
+ log2.info("timeout sending answer to offer", {
811
767
  err
812
768
  }, {
813
- F: __dxlog_file3,
769
+ F: __dxlog_file2,
814
770
  L: 177,
815
771
  S: this,
816
772
  C: (f, a) => f(...a)
817
773
  });
818
774
  } else {
819
- log3.info("error sending answer to offer", {
775
+ log2.info("error sending answer to offer", {
820
776
  err
821
777
  }, {
822
- F: __dxlog_file3,
778
+ F: __dxlog_file2,
823
779
  L: 179,
824
780
  S: this,
825
781
  C: (f, a) => f(...a)
@@ -829,7 +785,7 @@ var SwarmMessenger = class {
829
785
  }
830
786
  async _handleSignal({ author, recipient, message }) {
831
787
  invariant2(message.messageId, void 0, {
832
- F: __dxlog_file3,
788
+ F: __dxlog_file2,
833
789
  L: 193,
834
790
  S: this,
835
791
  A: [
@@ -838,7 +794,7 @@ var SwarmMessenger = class {
838
794
  ]
839
795
  });
840
796
  invariant2(message.data.signal || message.data.signalBatch, "Invalid message", {
841
- F: __dxlog_file3,
797
+ F: __dxlog_file2,
842
798
  L: 194,
843
799
  S: this,
844
800
  A: [
@@ -865,17 +821,17 @@ import { Context as Context4 } from "@dxos/context";
865
821
  import { ErrorStream as ErrorStream2 } from "@dxos/debug";
866
822
  import { invariant as invariant4 } from "@dxos/invariant";
867
823
  import { PublicKey as PublicKey4 } from "@dxos/keys";
868
- import { log as log5, logInfo as logInfo2 } from "@dxos/log";
824
+ import { log as log4, logInfo as logInfo2 } from "@dxos/log";
869
825
  import { PeerInfoHash } from "@dxos/messaging";
870
826
  import { trace as trace2 } from "@dxos/protocols";
871
- import { ComplexMap as ComplexMap2, isNotNullOrUndefined as isNotNullOrUndefined2 } from "@dxos/util";
827
+ import { ComplexMap as ComplexMap2, isNotNullOrUndefined } from "@dxos/util";
872
828
 
873
829
  // packages/core/mesh/network-manager/src/swarm/peer.ts
874
830
  import { Event as Event2, scheduleTask as scheduleTask2, synchronized as synchronized2 } from "@dxos/async";
875
831
  import { Context as Context3 } from "@dxos/context";
876
832
  import { invariant as invariant3 } from "@dxos/invariant";
877
833
  import { PublicKey as PublicKey3 } from "@dxos/keys";
878
- import { log as log4 } from "@dxos/log";
834
+ import { log as log3 } from "@dxos/log";
879
835
  import { CancelledError as CancelledError2, SystemError } from "@dxos/protocols";
880
836
  function _ts_decorate2(decorators, target, key, desc) {
881
837
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
@@ -883,7 +839,7 @@ function _ts_decorate2(decorators, target, key, desc) {
883
839
  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;
884
840
  return c > 3 && r && Object.defineProperty(target, key, r), r;
885
841
  }
886
- var __dxlog_file4 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/swarm/peer.ts";
842
+ var __dxlog_file3 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/swarm/peer.ts";
887
843
  var ConnectionDisplacedError = class extends SystemError {
888
844
  constructor() {
889
845
  super("Connection displaced by remote initiator.");
@@ -903,7 +859,7 @@ var Peer = class {
903
859
  this._availableAfter = 0;
904
860
  this.availableToConnect = true;
905
861
  this._ctx = new Context3(void 0, {
906
- F: __dxlog_file4,
862
+ F: __dxlog_file3,
907
863
  L: 80
908
864
  });
909
865
  this.advertizing = false;
@@ -920,8 +876,8 @@ var Peer = class {
920
876
  ConnectionState.INITIAL,
921
877
  ConnectionState.CONNECTING
922
878
  ].includes(this.connection.state)) {
923
- log4.info(`received offer when connection already in ${this.connection.state} state`, void 0, {
924
- F: __dxlog_file4,
879
+ log3.info(`received offer when connection already in ${this.connection.state} state`, void 0, {
880
+ F: __dxlog_file3,
925
881
  L: 115,
926
882
  S: this,
927
883
  C: (f, a) => f(...a)
@@ -932,13 +888,13 @@ var Peer = class {
932
888
  }
933
889
  if (this.connection || this.initiating) {
934
890
  if (remote.peerKey < this.localInfo.peerKey) {
935
- log4("close local connection", {
891
+ log3("close local connection", {
936
892
  localPeer: this.localInfo,
937
893
  topic: this.topic,
938
894
  remotePeer: this.remoteInfo,
939
895
  sessionId: this.connection?.sessionId
940
896
  }, {
941
- F: __dxlog_file4,
897
+ F: __dxlog_file3,
942
898
  L: 124,
943
899
  S: this,
944
900
  C: (f, a) => f(...a)
@@ -955,7 +911,7 @@ var Peer = class {
955
911
  if (await this._callbacks.onOffer(remote)) {
956
912
  if (!this.connection) {
957
913
  invariant3(message.sessionId, void 0, {
958
- F: __dxlog_file4,
914
+ F: __dxlog_file3,
959
915
  L: 144,
960
916
  S: this,
961
917
  A: [
@@ -970,13 +926,13 @@ var Peer = class {
970
926
  await connection.openConnection();
971
927
  } catch (err) {
972
928
  if (!(err instanceof CancelledError2)) {
973
- log4.info("connection error", {
929
+ log3.info("connection error", {
974
930
  topic: this.topic,
975
931
  peerId: this.localInfo,
976
932
  remoteId: this.remoteInfo,
977
933
  err
978
934
  }, {
979
- F: __dxlog_file4,
935
+ F: __dxlog_file3,
980
936
  L: 154,
981
937
  S: this,
982
938
  C: (f, a) => f(...a)
@@ -998,7 +954,7 @@ var Peer = class {
998
954
  */
999
955
  async initiateConnection() {
1000
956
  invariant3(!this.initiating, "Initiation in progress.", {
1001
- F: __dxlog_file4,
957
+ F: __dxlog_file3,
1002
958
  L: 171,
1003
959
  S: this,
1004
960
  A: [
@@ -1007,7 +963,7 @@ var Peer = class {
1007
963
  ]
1008
964
  });
1009
965
  invariant3(!this.connection, "Already connected.", {
1010
- F: __dxlog_file4,
966
+ F: __dxlog_file3,
1011
967
  L: 172,
1012
968
  S: this,
1013
969
  A: [
@@ -1016,13 +972,13 @@ var Peer = class {
1016
972
  ]
1017
973
  });
1018
974
  const sessionId = PublicKey3.random();
1019
- log4("initiating...", {
975
+ log3("initiating...", {
1020
976
  local: this.localInfo,
1021
977
  topic: this.topic,
1022
978
  remote: this.remoteInfo,
1023
979
  sessionId
1024
980
  }, {
1025
- F: __dxlog_file4,
981
+ F: __dxlog_file3,
1026
982
  L: 174,
1027
983
  S: this,
1028
984
  C: (f, a) => f(...a)
@@ -1042,20 +998,20 @@ var Peer = class {
1042
998
  offer: {}
1043
999
  }
1044
1000
  });
1045
- log4("received", {
1001
+ log3("received", {
1046
1002
  answer,
1047
1003
  topic: this.topic,
1048
1004
  local: this.localInfo,
1049
1005
  remote: this.remoteInfo
1050
1006
  }, {
1051
- F: __dxlog_file4,
1007
+ F: __dxlog_file3,
1052
1008
  L: 191,
1053
1009
  S: this,
1054
1010
  C: (f, a) => f(...a)
1055
1011
  });
1056
1012
  if (connection.state !== ConnectionState.INITIAL) {
1057
- log4("ignoring response", void 0, {
1058
- F: __dxlog_file4,
1013
+ log3("ignoring response", void 0, {
1014
+ F: __dxlog_file3,
1059
1015
  L: 193,
1060
1016
  S: this,
1061
1017
  C: (f, a) => f(...a)
@@ -1063,13 +1019,13 @@ var Peer = class {
1063
1019
  return;
1064
1020
  }
1065
1021
  } catch (err) {
1066
- log4("initiation error: send offer", {
1022
+ log3("initiation error: send offer", {
1067
1023
  err,
1068
1024
  topic: this.topic,
1069
1025
  local: this.localInfo,
1070
1026
  remote: this.remoteInfo
1071
1027
  }, {
1072
- F: __dxlog_file4,
1028
+ F: __dxlog_file3,
1073
1029
  L: 197,
1074
1030
  S: this,
1075
1031
  C: (f, a) => f(...a)
@@ -1085,13 +1041,13 @@ var Peer = class {
1085
1041
  return;
1086
1042
  }
1087
1043
  } catch (err) {
1088
- log4("initiation error: accept answer", {
1044
+ log3("initiation error: accept answer", {
1089
1045
  err,
1090
1046
  topic: this.topic,
1091
1047
  local: this.localInfo,
1092
1048
  remote: this.remoteInfo
1093
1049
  }, {
1094
- F: __dxlog_file4,
1050
+ F: __dxlog_file3,
1095
1051
  L: 210,
1096
1052
  S: this,
1097
1053
  C: (f, a) => f(...a)
@@ -1102,8 +1058,8 @@ var Peer = class {
1102
1058
  this.initiating = false;
1103
1059
  }
1104
1060
  try {
1105
- log4("opening connection as initiator", void 0, {
1106
- F: __dxlog_file4,
1061
+ log3("opening connection as initiator", void 0, {
1062
+ F: __dxlog_file3,
1107
1063
  L: 223,
1108
1064
  S: this,
1109
1065
  C: (f, a) => f(...a)
@@ -1111,21 +1067,21 @@ var Peer = class {
1111
1067
  await connection.openConnection();
1112
1068
  this._callbacks.onAccepted();
1113
1069
  } catch (err) {
1114
- log4("initiation error: open connection", {
1070
+ log3("initiation error: open connection", {
1115
1071
  err,
1116
1072
  topic: this.topic,
1117
1073
  local: this.localInfo,
1118
1074
  remote: this.remoteInfo
1119
1075
  }, {
1120
- F: __dxlog_file4,
1076
+ F: __dxlog_file3,
1121
1077
  L: 227,
1122
1078
  S: this,
1123
1079
  C: (f, a) => f(...a)
1124
1080
  });
1125
- log4.warn("closing connection due to unhandled error on openConnection", {
1081
+ log3.warn("closing connection due to unhandled error on openConnection", {
1126
1082
  err
1127
1083
  }, {
1128
- F: __dxlog_file4,
1084
+ F: __dxlog_file3,
1129
1085
  L: 234,
1130
1086
  S: this,
1131
1087
  C: (f, a) => f(...a)
@@ -1141,20 +1097,20 @@ var Peer = class {
1141
1097
  * Either we're initiating a connection or creating one in response to an offer from the other peer.
1142
1098
  */
1143
1099
  _createConnection(initiator, sessionId) {
1144
- log4("creating connection", {
1100
+ log3("creating connection", {
1145
1101
  topic: this.topic,
1146
1102
  peerId: this.localInfo,
1147
1103
  remoteId: this.remoteInfo,
1148
1104
  initiator,
1149
1105
  sessionId
1150
1106
  }, {
1151
- F: __dxlog_file4,
1107
+ F: __dxlog_file3,
1152
1108
  L: 248,
1153
1109
  S: this,
1154
1110
  C: (f, a) => f(...a)
1155
1111
  });
1156
1112
  invariant3(!this.connection, "Already connected.", {
1157
- F: __dxlog_file4,
1113
+ F: __dxlog_file3,
1158
1114
  L: 255,
1159
1115
  S: this,
1160
1116
  A: [
@@ -1183,34 +1139,34 @@ var Peer = class {
1183
1139
  this._lastConnectionTime = Date.now();
1184
1140
  this._callbacks.onConnected();
1185
1141
  this._connectionLimiter.doneConnecting(sessionId);
1186
- log4.trace("dxos.mesh.connection.connected", {
1142
+ log3.trace("dxos.mesh.connection.connected", {
1187
1143
  topic: this.topic,
1188
1144
  localPeerId: this.localInfo,
1189
1145
  remotePeerId: this.remoteInfo,
1190
1146
  sessionId,
1191
1147
  initiator
1192
1148
  }, {
1193
- F: __dxlog_file4,
1149
+ F: __dxlog_file3,
1194
1150
  L: 279,
1195
1151
  S: this,
1196
1152
  C: (f, a) => f(...a)
1197
1153
  });
1198
1154
  },
1199
1155
  onClosed: (err) => {
1200
- log4("connection closed", {
1156
+ log3("connection closed", {
1201
1157
  topic: this.topic,
1202
1158
  peerId: this.localInfo,
1203
1159
  remoteId: this.remoteInfo,
1204
1160
  initiator
1205
1161
  }, {
1206
- F: __dxlog_file4,
1162
+ F: __dxlog_file3,
1207
1163
  L: 288,
1208
1164
  S: this,
1209
1165
  C: (f, a) => f(...a)
1210
1166
  });
1211
1167
  this._connectionLimiter.doneConnecting(sessionId);
1212
1168
  invariant3(this.connection === connection, "Connection mismatch (race condition).", {
1213
- F: __dxlog_file4,
1169
+ F: __dxlog_file3,
1214
1170
  L: 293,
1215
1171
  S: this,
1216
1172
  A: [
@@ -1218,14 +1174,14 @@ var Peer = class {
1218
1174
  "'Connection mismatch (race condition).'"
1219
1175
  ]
1220
1176
  });
1221
- log4.trace("dxos.mesh.connection.closed", {
1177
+ log3.trace("dxos.mesh.connection.closed", {
1222
1178
  topic: this.topic,
1223
1179
  localPeerId: this.localInfo,
1224
1180
  remotePeerId: this.remoteInfo,
1225
1181
  sessionId,
1226
1182
  initiator
1227
1183
  }, {
1228
- F: __dxlog_file4,
1184
+ F: __dxlog_file3,
1229
1185
  L: 295,
1230
1186
  S: this,
1231
1187
  C: (f, a) => f(...a)
@@ -1253,19 +1209,19 @@ var Peer = class {
1253
1209
  void this._connectionCtx?.dispose();
1254
1210
  this._connectionCtx = this._ctx.derive();
1255
1211
  connection.errors.handle((err) => {
1256
- log4.info("connection error, closing", {
1212
+ log3.info("connection error, closing", {
1257
1213
  topic: this.topic,
1258
1214
  peerId: this.localInfo,
1259
1215
  remoteId: this.remoteInfo,
1260
1216
  initiator,
1261
1217
  err
1262
1218
  }, {
1263
- F: __dxlog_file4,
1219
+ F: __dxlog_file3,
1264
1220
  L: 335,
1265
1221
  S: this,
1266
1222
  C: (f, a) => f(...a)
1267
1223
  });
1268
- log4.trace("dxos.mesh.connection.error", {
1224
+ log3.trace("dxos.mesh.connection.error", {
1269
1225
  topic: this.topic,
1270
1226
  localPeerId: this.localInfo,
1271
1227
  remotePeerId: this.remoteInfo,
@@ -1273,7 +1229,7 @@ var Peer = class {
1273
1229
  initiator,
1274
1230
  err
1275
1231
  }, {
1276
- F: __dxlog_file4,
1232
+ F: __dxlog_file3,
1277
1233
  L: 342,
1278
1234
  S: this,
1279
1235
  C: (f, a) => f(...a)
@@ -1288,21 +1244,21 @@ var Peer = class {
1288
1244
  return;
1289
1245
  }
1290
1246
  const connection = this.connection;
1291
- log4("closing...", {
1247
+ log3("closing...", {
1292
1248
  peerId: this.remoteInfo,
1293
1249
  sessionId: connection.sessionId
1294
1250
  }, {
1295
- F: __dxlog_file4,
1251
+ F: __dxlog_file3,
1296
1252
  L: 367,
1297
1253
  S: this,
1298
1254
  C: (f, a) => f(...a)
1299
1255
  });
1300
1256
  await connection.close(err);
1301
- log4("closed", {
1257
+ log3("closed", {
1302
1258
  peerId: this.remoteInfo,
1303
1259
  sessionId: connection.sessionId
1304
1260
  }, {
1305
- F: __dxlog_file4,
1261
+ F: __dxlog_file3,
1306
1262
  L: 373,
1307
1263
  S: this,
1308
1264
  C: (f, a) => f(...a)
@@ -1310,10 +1266,10 @@ var Peer = class {
1310
1266
  }
1311
1267
  async onSignal(message) {
1312
1268
  if (!this.connection) {
1313
- log4("dropping signal message for non-existent connection", {
1269
+ log3("dropping signal message for non-existent connection", {
1314
1270
  message
1315
1271
  }, {
1316
- F: __dxlog_file4,
1272
+ F: __dxlog_file3,
1317
1273
  L: 378,
1318
1274
  S: this,
1319
1275
  C: (f, a) => f(...a)
@@ -1324,11 +1280,11 @@ var Peer = class {
1324
1280
  }
1325
1281
  async safeDestroy(reason) {
1326
1282
  await this._ctx.dispose();
1327
- log4("Destroying peer", {
1283
+ log3("Destroying peer", {
1328
1284
  peerId: this.remoteInfo,
1329
1285
  topic: this.topic
1330
1286
  }, {
1331
- F: __dxlog_file4,
1287
+ F: __dxlog_file3,
1332
1288
  L: 388,
1333
1289
  S: this,
1334
1290
  C: (f, a) => f(...a)
@@ -1359,7 +1315,7 @@ function _ts_decorate3(decorators, target, key, desc) {
1359
1315
  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;
1360
1316
  return c > 3 && r && Object.defineProperty(target, key, r), r;
1361
1317
  }
1362
- var __dxlog_file5 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/swarm/swarm.ts";
1318
+ var __dxlog_file4 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/swarm/swarm.ts";
1363
1319
  var INITIATION_DELAY = 100;
1364
1320
  var getClassName = (obj) => Object.getPrototypeOf(obj).constructor.name;
1365
1321
  var Swarm = class {
@@ -1376,7 +1332,7 @@ var Swarm = class {
1376
1332
  this._connectionLimiter = _connectionLimiter;
1377
1333
  this._initiationDelay = _initiationDelay;
1378
1334
  this._ctx = new Context4(void 0, {
1379
- F: __dxlog_file5,
1335
+ F: __dxlog_file4,
1380
1336
  L: 38
1381
1337
  });
1382
1338
  this._listeningHandle = void 0;
@@ -1386,22 +1342,22 @@ var Swarm = class {
1386
1342
  this.disconnected = new Event3();
1387
1343
  this.connected = new Event3();
1388
1344
  this.errors = new ErrorStream2();
1389
- log5.trace("dxos.mesh.swarm.constructor", trace2.begin({
1345
+ log4.trace("dxos.mesh.swarm.constructor", trace2.begin({
1390
1346
  id: this._instanceId,
1391
1347
  data: {
1392
1348
  topic: this._topic.toHex(),
1393
1349
  peer: this._ownPeer
1394
1350
  }
1395
1351
  }), {
1396
- F: __dxlog_file5,
1352
+ F: __dxlog_file4,
1397
1353
  L: 88,
1398
1354
  S: this,
1399
1355
  C: (f, a) => f(...a)
1400
1356
  });
1401
- log5("creating swarm", {
1357
+ log4("creating swarm", {
1402
1358
  peerId: _ownPeer
1403
1359
  }, {
1404
- F: __dxlog_file5,
1360
+ F: __dxlog_file4,
1405
1361
  L: 92,
1406
1362
  S: this,
1407
1363
  C: (f, a) => f(...a)
@@ -1413,17 +1369,17 @@ var Swarm = class {
1413
1369
  onOffer: async (msg) => await this.onOffer(msg),
1414
1370
  topic: this._topic
1415
1371
  });
1416
- log5.trace("dxos.mesh.swarm.constructor", trace2.end({
1372
+ log4.trace("dxos.mesh.swarm.constructor", trace2.end({
1417
1373
  id: this._instanceId
1418
1374
  }), {
1419
- F: __dxlog_file5,
1375
+ F: __dxlog_file4,
1420
1376
  L: 101,
1421
1377
  S: this,
1422
1378
  C: (f, a) => f(...a)
1423
1379
  });
1424
1380
  }
1425
1381
  get connections() {
1426
- return Array.from(this._peers.values()).map((peer) => peer.connection).filter(isNotNullOrUndefined2);
1382
+ return Array.from(this._peers.values()).map((peer) => peer.connection).filter(isNotNullOrUndefined);
1427
1383
  }
1428
1384
  get ownPeerId() {
1429
1385
  return PublicKey4.from(this._ownPeer.peerKey);
@@ -1442,7 +1398,7 @@ var Swarm = class {
1442
1398
  }
1443
1399
  async open() {
1444
1400
  invariant4(!this._listeningHandle, void 0, {
1445
- F: __dxlog_file5,
1401
+ F: __dxlog_file4,
1446
1402
  L: 132,
1447
1403
  S: this,
1448
1404
  A: [
@@ -1454,10 +1410,10 @@ var Swarm = class {
1454
1410
  peer: this._ownPeer,
1455
1411
  payloadType: "dxos.mesh.swarm.SwarmMessage",
1456
1412
  onMessage: async (message) => {
1457
- await this._swarmMessenger.receiveMessage(message).catch((err) => log5.info("Error while receiving message", {
1413
+ await this._swarmMessenger.receiveMessage(message).catch((err) => log4.info("Error while receiving message", {
1458
1414
  err
1459
1415
  }, {
1460
- F: __dxlog_file5,
1416
+ F: __dxlog_file4,
1461
1417
  L: 140,
1462
1418
  S: this,
1463
1419
  C: (f, a) => f(...a)
@@ -1466,8 +1422,8 @@ var Swarm = class {
1466
1422
  });
1467
1423
  }
1468
1424
  async destroy() {
1469
- log5("destroying...", void 0, {
1470
- F: __dxlog_file5,
1425
+ log4("destroying...", void 0, {
1426
+ F: __dxlog_file4,
1471
1427
  L: 146,
1472
1428
  S: this,
1473
1429
  C: (f, a) => f(...a)
@@ -1477,8 +1433,8 @@ var Swarm = class {
1477
1433
  await this._ctx.dispose();
1478
1434
  await this._topology.destroy();
1479
1435
  await Promise.all(Array.from(this._peers.keys()).map((key) => this._destroyPeer(key, "swarm destroyed")));
1480
- log5("destroyed", void 0, {
1481
- F: __dxlog_file5,
1436
+ log4("destroyed", void 0, {
1437
+ F: __dxlog_file4,
1482
1438
  L: 153,
1483
1439
  S: this,
1484
1440
  C: (f, a) => f(...a)
@@ -1486,7 +1442,7 @@ var Swarm = class {
1486
1442
  }
1487
1443
  async setTopology(topology) {
1488
1444
  invariant4(!this._ctx.disposed, "Swarm is offline", {
1489
- F: __dxlog_file5,
1445
+ F: __dxlog_file4,
1490
1446
  L: 157,
1491
1447
  S: this,
1492
1448
  A: [
@@ -1497,11 +1453,11 @@ var Swarm = class {
1497
1453
  if (topology === this._topology) {
1498
1454
  return;
1499
1455
  }
1500
- log5("setting topology", {
1456
+ log4("setting topology", {
1501
1457
  previous: getClassName(this._topology),
1502
1458
  topology: getClassName(topology)
1503
1459
  }, {
1504
- F: __dxlog_file5,
1460
+ F: __dxlog_file4,
1505
1461
  L: 161,
1506
1462
  S: this,
1507
1463
  C: (f, a) => f(...a)
@@ -1512,17 +1468,17 @@ var Swarm = class {
1512
1468
  this._topology.update();
1513
1469
  }
1514
1470
  onSwarmEvent(swarmEvent) {
1515
- log5("swarm event", {
1471
+ log4("swarm event", {
1516
1472
  swarmEvent
1517
1473
  }, {
1518
- F: __dxlog_file5,
1474
+ F: __dxlog_file4,
1519
1475
  L: 174,
1520
1476
  S: this,
1521
1477
  C: (f, a) => f(...a)
1522
1478
  });
1523
1479
  if (this._ctx.disposed) {
1524
- log5("swarm event ignored for disposed swarm", void 0, {
1525
- F: __dxlog_file5,
1480
+ log4("swarm event ignored for disposed swarm", void 0, {
1481
+ F: __dxlog_file4,
1526
1482
  L: 177,
1527
1483
  S: this,
1528
1484
  C: (f, a) => f(...a)
@@ -1532,10 +1488,10 @@ var Swarm = class {
1532
1488
  if (swarmEvent.peerAvailable) {
1533
1489
  const peerId = swarmEvent.peerAvailable.peer.peerKey;
1534
1490
  if (peerId !== this._ownPeer.peerKey) {
1535
- log5("new peer", {
1491
+ log4("new peer", {
1536
1492
  peerId
1537
1493
  }, {
1538
- F: __dxlog_file5,
1494
+ F: __dxlog_file4,
1539
1495
  L: 184,
1540
1496
  S: this,
1541
1497
  C: (f, a) => f(...a)
@@ -1548,18 +1504,18 @@ var Swarm = class {
1548
1504
  if (peer) {
1549
1505
  peer.advertizing = false;
1550
1506
  if (peer.connection?.state !== ConnectionState.CONNECTED) {
1551
- void this._destroyPeer(swarmEvent.peerLeft.peer, "peer left").catch((err) => log5.catch(err, void 0, {
1552
- F: __dxlog_file5,
1507
+ void this._destroyPeer(swarmEvent.peerLeft.peer, "peer left").catch((err) => log4.catch(err, void 0, {
1508
+ F: __dxlog_file4,
1553
1509
  L: 194,
1554
1510
  S: this,
1555
1511
  C: (f, a) => f(...a)
1556
1512
  }));
1557
1513
  }
1558
1514
  } else {
1559
- log5("received peerLeft but no peer found", {
1515
+ log4("received peerLeft but no peer found", {
1560
1516
  peer: swarmEvent.peerLeft.peer.peerKey
1561
1517
  }, {
1562
- F: __dxlog_file5,
1518
+ F: __dxlog_file4,
1563
1519
  L: 197,
1564
1520
  S: this,
1565
1521
  C: (f, a) => f(...a)
@@ -1569,17 +1525,17 @@ var Swarm = class {
1569
1525
  this._topology.update();
1570
1526
  }
1571
1527
  async onOffer(message) {
1572
- log5("offer", {
1528
+ log4("offer", {
1573
1529
  message
1574
1530
  }, {
1575
- F: __dxlog_file5,
1531
+ F: __dxlog_file4,
1576
1532
  L: 206,
1577
1533
  S: this,
1578
1534
  C: (f, a) => f(...a)
1579
1535
  });
1580
1536
  if (this._ctx.disposed) {
1581
- log5("ignored for disposed swarm", void 0, {
1582
- F: __dxlog_file5,
1537
+ log4("ignored for disposed swarm", void 0, {
1538
+ F: __dxlog_file4,
1583
1539
  L: 208,
1584
1540
  S: this,
1585
1541
  C: (f, a) => f(...a)
@@ -1589,7 +1545,7 @@ var Swarm = class {
1589
1545
  };
1590
1546
  }
1591
1547
  invariant4(message.author, void 0, {
1592
- F: __dxlog_file5,
1548
+ F: __dxlog_file4,
1593
1549
  L: 213,
1594
1550
  S: this,
1595
1551
  A: [
@@ -1598,10 +1554,10 @@ var Swarm = class {
1598
1554
  ]
1599
1555
  });
1600
1556
  if (message.recipient.peerKey !== this._ownPeer.peerKey) {
1601
- log5("rejecting offer with incorrect peerId", {
1557
+ log4("rejecting offer with incorrect peerId", {
1602
1558
  message
1603
1559
  }, {
1604
- F: __dxlog_file5,
1560
+ F: __dxlog_file4,
1605
1561
  L: 215,
1606
1562
  S: this,
1607
1563
  C: (f, a) => f(...a)
@@ -1611,10 +1567,10 @@ var Swarm = class {
1611
1567
  };
1612
1568
  }
1613
1569
  if (!message.topic?.equals(this._topic)) {
1614
- log5("rejecting offer with incorrect topic", {
1570
+ log4("rejecting offer with incorrect topic", {
1615
1571
  message
1616
1572
  }, {
1617
- F: __dxlog_file5,
1573
+ F: __dxlog_file4,
1618
1574
  L: 219,
1619
1575
  S: this,
1620
1576
  C: (f, a) => f(...a)
@@ -1629,17 +1585,17 @@ var Swarm = class {
1629
1585
  return answer;
1630
1586
  }
1631
1587
  async onSignal(message) {
1632
- log5("signal", {
1588
+ log4("signal", {
1633
1589
  message
1634
1590
  }, {
1635
- F: __dxlog_file5,
1591
+ F: __dxlog_file4,
1636
1592
  L: 230,
1637
1593
  S: this,
1638
1594
  C: (f, a) => f(...a)
1639
1595
  });
1640
1596
  if (this._ctx.disposed) {
1641
- log5.info("ignored for offline swarm", void 0, {
1642
- F: __dxlog_file5,
1597
+ log4.info("ignored for offline swarm", void 0, {
1598
+ F: __dxlog_file4,
1643
1599
  L: 232,
1644
1600
  S: this,
1645
1601
  C: (f, a) => f(...a)
@@ -1647,7 +1603,7 @@ var Swarm = class {
1647
1603
  return;
1648
1604
  }
1649
1605
  invariant4(message.recipient.peerKey === this._ownPeer.peerKey, `Invalid signal peer id expected=${this.ownPeerId}, actual=${message.recipient}`, {
1650
- F: __dxlog_file5,
1606
+ F: __dxlog_file4,
1651
1607
  L: 235,
1652
1608
  S: this,
1653
1609
  A: [
@@ -1656,7 +1612,7 @@ var Swarm = class {
1656
1612
  ]
1657
1613
  });
1658
1614
  invariant4(message.topic?.equals(this._topic), void 0, {
1659
- F: __dxlog_file5,
1615
+ F: __dxlog_file4,
1660
1616
  L: 239,
1661
1617
  S: this,
1662
1618
  A: [
@@ -1665,7 +1621,7 @@ var Swarm = class {
1665
1621
  ]
1666
1622
  });
1667
1623
  invariant4(message.author, void 0, {
1668
- F: __dxlog_file5,
1624
+ F: __dxlog_file4,
1669
1625
  L: 240,
1670
1626
  S: this,
1671
1627
  A: [
@@ -1686,13 +1642,13 @@ var Swarm = class {
1686
1642
  // For debug purposes
1687
1643
  async goOnline() {
1688
1644
  this._ctx = new Context4(void 0, {
1689
- F: __dxlog_file5,
1645
+ F: __dxlog_file4,
1690
1646
  L: 256
1691
1647
  });
1692
1648
  }
1693
1649
  _getOrCreatePeer(peerInfo) {
1694
1650
  invariant4(peerInfo.peerKey, "PeerInfo.peerKey is required", {
1695
- F: __dxlog_file5,
1651
+ F: __dxlog_file4,
1696
1652
  L: 260,
1697
1653
  S: this,
1698
1654
  A: [
@@ -1721,10 +1677,10 @@ var Swarm = class {
1721
1677
  },
1722
1678
  onRejected: () => {
1723
1679
  if (!this._isUnregistered(peer)) {
1724
- log5("peer rejected connection", {
1680
+ log4("peer rejected connection", {
1725
1681
  peerInfo
1726
1682
  }, {
1727
- F: __dxlog_file5,
1683
+ F: __dxlog_file4,
1728
1684
  L: 293,
1729
1685
  S: this,
1730
1686
  C: (f, a) => f(...a)
@@ -1749,7 +1705,7 @@ var Swarm = class {
1749
1705
  async _destroyPeer(peerInfo, reason) {
1750
1706
  const peer = this._peers.get(peerInfo);
1751
1707
  invariant4(peer, void 0, {
1752
- F: __dxlog_file5,
1708
+ F: __dxlog_file4,
1753
1709
  L: 316,
1754
1710
  S: this,
1755
1711
  A: [
@@ -1778,8 +1734,8 @@ var Swarm = class {
1778
1734
  peerKey: peer.toHex()
1779
1735
  });
1780
1736
  } catch (err) {
1781
- log5("initiation error", err, {
1782
- F: __dxlog_file5,
1737
+ log4("initiation error", err, {
1738
+ F: __dxlog_file4,
1783
1739
  L: 343,
1784
1740
  S: this,
1785
1741
  C: (f, a) => f(...a)
@@ -1807,10 +1763,10 @@ var Swarm = class {
1807
1763
  const ctx = this._ctx;
1808
1764
  const peer = this._getOrCreatePeer(remotePeer);
1809
1765
  if (remotePeer.peerKey < this._ownPeer.peerKey) {
1810
- log5("initiation delay", {
1766
+ log4("initiation delay", {
1811
1767
  remotePeer
1812
1768
  }, {
1813
- F: __dxlog_file5,
1769
+ F: __dxlog_file4,
1814
1770
  L: 371,
1815
1771
  S: this,
1816
1772
  C: (f, a) => f(...a)
@@ -1826,20 +1782,20 @@ var Swarm = class {
1826
1782
  if (peer.connection) {
1827
1783
  return;
1828
1784
  }
1829
- log5("initiating connection...", {
1785
+ log4("initiating connection...", {
1830
1786
  remotePeer
1831
1787
  }, {
1832
- F: __dxlog_file5,
1788
+ F: __dxlog_file4,
1833
1789
  L: 387,
1834
1790
  S: this,
1835
1791
  C: (f, a) => f(...a)
1836
1792
  });
1837
1793
  await peer.initiateConnection();
1838
1794
  this._topology.update();
1839
- log5("initiated", {
1795
+ log4("initiated", {
1840
1796
  remotePeer
1841
1797
  }, {
1842
- F: __dxlog_file5,
1798
+ F: __dxlog_file4,
1843
1799
  L: 390,
1844
1800
  S: this,
1845
1801
  C: (f, a) => f(...a)
@@ -1881,10 +1837,10 @@ _ts_decorate3([
1881
1837
  // packages/core/mesh/network-manager/src/swarm/swarm-mapper.ts
1882
1838
  import { Event as Event4, EventSubscriptions } from "@dxos/async";
1883
1839
  import { PublicKey as PublicKey5 } from "@dxos/keys";
1884
- import { log as log6 } from "@dxos/log";
1840
+ import { log as log5 } from "@dxos/log";
1885
1841
  import { PeerInfoHash as PeerInfoHash2 } from "@dxos/messaging";
1886
1842
  import { ComplexMap as ComplexMap3 } from "@dxos/util";
1887
- var __dxlog_file6 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/swarm/swarm-mapper.ts";
1843
+ var __dxlog_file5 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/swarm/swarm-mapper.ts";
1888
1844
  var SwarmMapper = class {
1889
1845
  get peers() {
1890
1846
  return Array.from(this._peers.values());
@@ -1909,8 +1865,8 @@ var SwarmMapper = class {
1909
1865
  this._update();
1910
1866
  }
1911
1867
  _update() {
1912
- log6("updating swarm", void 0, {
1913
- F: __dxlog_file6,
1868
+ log5("updating swarm", void 0, {
1869
+ F: __dxlog_file5,
1914
1870
  L: 73,
1915
1871
  S: this,
1916
1872
  C: (f, a) => f(...a)
@@ -1930,11 +1886,11 @@ var SwarmMapper = class {
1930
1886
  ]
1931
1887
  });
1932
1888
  }
1933
- log6("graph changed", {
1889
+ log5("graph changed", {
1934
1890
  directConnections: this._swarm.connections.length,
1935
1891
  totalPeersInSwarm: this._peers.size
1936
1892
  }, {
1937
- F: __dxlog_file6,
1893
+ F: __dxlog_file5,
1938
1894
  L: 114,
1939
1895
  S: this,
1940
1896
  C: (f, a) => f(...a)
@@ -1953,15 +1909,15 @@ import { DeferredTask as DeferredTask2 } from "@dxos/async";
1953
1909
  import { Context as Context5 } from "@dxos/context";
1954
1910
  import { invariant as invariant5 } from "@dxos/invariant";
1955
1911
  import { PublicKey as PublicKey6 } from "@dxos/keys";
1956
- import { log as log7 } from "@dxos/log";
1912
+ import { log as log6 } from "@dxos/log";
1957
1913
  import { CancelledError as CancelledError3 } from "@dxos/protocols";
1958
1914
  import { ComplexMap as ComplexMap4 } from "@dxos/util";
1959
- var __dxlog_file7 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/swarm/connection-limiter.ts";
1915
+ var __dxlog_file6 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/swarm/connection-limiter.ts";
1960
1916
  var MAX_CONCURRENT_INITIATING_CONNECTIONS = 50;
1961
1917
  var ConnectionLimiter = class {
1962
1918
  constructor({ maxConcurrentInitConnections = MAX_CONCURRENT_INITIATING_CONNECTIONS } = {}) {
1963
1919
  this._ctx = new Context5(void 0, {
1964
- F: __dxlog_file7,
1920
+ F: __dxlog_file6,
1965
1921
  L: 23
1966
1922
  });
1967
1923
  /**
@@ -1980,7 +1936,7 @@ var ConnectionLimiter = class {
1980
1936
  */
1981
1937
  async connecting(sessionId) {
1982
1938
  invariant5(!this._waitingPromises.has(sessionId), "Peer is already waiting for connection", {
1983
- F: __dxlog_file7,
1939
+ F: __dxlog_file6,
1984
1940
  L: 48,
1985
1941
  S: this,
1986
1942
  A: [
@@ -1988,10 +1944,10 @@ var ConnectionLimiter = class {
1988
1944
  "'Peer is already waiting for connection'"
1989
1945
  ]
1990
1946
  });
1991
- log7("waiting", {
1947
+ log6("waiting", {
1992
1948
  sessionId
1993
1949
  }, {
1994
- F: __dxlog_file7,
1950
+ F: __dxlog_file6,
1995
1951
  L: 49,
1996
1952
  S: this,
1997
1953
  C: (f, a) => f(...a)
@@ -2003,10 +1959,10 @@ var ConnectionLimiter = class {
2003
1959
  });
2004
1960
  this.resolveWaitingPromises.schedule();
2005
1961
  });
2006
- log7("allow", {
1962
+ log6("allow", {
2007
1963
  sessionId
2008
1964
  }, {
2009
- F: __dxlog_file7,
1965
+ F: __dxlog_file6,
2010
1966
  L: 57,
2011
1967
  S: this,
2012
1968
  C: (f, a) => f(...a)
@@ -2016,10 +1972,10 @@ var ConnectionLimiter = class {
2016
1972
  * Rejects promise returned by `connecting` method.
2017
1973
  */
2018
1974
  doneConnecting(sessionId) {
2019
- log7("done", {
1975
+ log6("done", {
2020
1976
  sessionId
2021
1977
  }, {
2022
- F: __dxlog_file7,
1978
+ F: __dxlog_file6,
2023
1979
  L: 64,
2024
1980
  S: this,
2025
1981
  C: (f, a) => f(...a)
@@ -2129,7 +2085,7 @@ var gcSwarm = (swarm) => {
2129
2085
  import { Event as Event6, synchronized as synchronized4 } from "@dxos/async";
2130
2086
  import { invariant as invariant6 } from "@dxos/invariant";
2131
2087
  import { PublicKey as PublicKey8 } from "@dxos/keys";
2132
- import { log as log8 } from "@dxos/log";
2088
+ import { log as log7 } from "@dxos/log";
2133
2089
  import { Messenger } from "@dxos/messaging";
2134
2090
  import { trace as trace3 } from "@dxos/protocols";
2135
2091
  import { ConnectionState as ConnectionState2 } from "@dxos/protocols/proto/dxos/client/services";
@@ -2140,7 +2096,7 @@ function _ts_decorate4(decorators, target, key, desc) {
2140
2096
  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;
2141
2097
  return c > 3 && r && Object.defineProperty(target, key, r), r;
2142
2098
  }
2143
- var __dxlog_file8 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/network-manager.ts";
2099
+ var __dxlog_file7 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/network-manager.ts";
2144
2100
  var SwarmNetworkManager = class {
2145
2101
  constructor({ transportFactory, signalManager, enableDevtoolsLogging, peerInfo }) {
2146
2102
  /**
@@ -2190,20 +2146,20 @@ var SwarmNetworkManager = class {
2190
2146
  this._peerInfo = peerInfo;
2191
2147
  }
2192
2148
  async open() {
2193
- log8.trace("dxos.mesh.network-manager.open", trace3.begin({
2149
+ log7.trace("dxos.mesh.network-manager.open", trace3.begin({
2194
2150
  id: this._instanceId
2195
2151
  }), {
2196
- F: __dxlog_file8,
2152
+ F: __dxlog_file7,
2197
2153
  L: 133,
2198
2154
  S: this,
2199
2155
  C: (f, a) => f(...a)
2200
2156
  });
2201
2157
  await this._messenger.open();
2202
2158
  await this._signalManager.open();
2203
- log8.trace("dxos.mesh.network-manager.open", trace3.end({
2159
+ log7.trace("dxos.mesh.network-manager.open", trace3.end({
2204
2160
  id: this._instanceId
2205
2161
  }), {
2206
- F: __dxlog_file8,
2162
+ F: __dxlog_file7,
2207
2163
  L: 136,
2208
2164
  S: this,
2209
2165
  C: (f, a) => f(...a)
@@ -2212,8 +2168,8 @@ var SwarmNetworkManager = class {
2212
2168
  async close() {
2213
2169
  for (const topic of this._swarms.keys()) {
2214
2170
  await this.leaveSwarm(topic).catch((err) => {
2215
- log8(err, void 0, {
2216
- F: __dxlog_file8,
2171
+ log7(err, void 0, {
2172
+ F: __dxlog_file7,
2217
2173
  L: 142,
2218
2174
  S: this,
2219
2175
  C: (f, a) => f(...a)
@@ -2226,52 +2182,37 @@ var SwarmNetworkManager = class {
2226
2182
  /**
2227
2183
  * Join the swarm.
2228
2184
  */
2229
- async joinSwarm({ topic, peerInfo, topology, protocolProvider: protocol, label }) {
2185
+ async joinSwarm({ topic, topology, protocolProvider: protocol, label }) {
2230
2186
  invariant6(PublicKey8.isPublicKey(topic), void 0, {
2231
- F: __dxlog_file8,
2232
- L: 161,
2187
+ F: __dxlog_file7,
2188
+ L: 160,
2233
2189
  S: this,
2234
2190
  A: [
2235
2191
  "PublicKey.isPublicKey(topic)",
2236
2192
  ""
2237
2193
  ]
2238
2194
  });
2239
- if (!peerInfo) {
2240
- peerInfo = {
2241
- peerKey: this._peerInfo?.peerKey ?? PublicKey8.random().toHex(),
2242
- identityKey: this._peerInfo?.identityKey ?? PublicKey8.random().toHex()
2243
- };
2244
- }
2245
- invariant6(PublicKey8.from(peerInfo.peerKey), void 0, {
2246
- F: __dxlog_file8,
2247
- L: 168,
2248
- S: this,
2249
- A: [
2250
- "PublicKey.from(peerInfo.peerKey)",
2251
- ""
2252
- ]
2253
- });
2254
- invariant6(PublicKey8.from(peerInfo.identityKey), void 0, {
2255
- F: __dxlog_file8,
2256
- L: 169,
2195
+ invariant6(topology, void 0, {
2196
+ F: __dxlog_file7,
2197
+ L: 161,
2257
2198
  S: this,
2258
2199
  A: [
2259
- "PublicKey.from(peerInfo.identityKey!)",
2200
+ "topology",
2260
2201
  ""
2261
2202
  ]
2262
2203
  });
2263
- invariant6(topology, void 0, {
2264
- F: __dxlog_file8,
2265
- L: 170,
2204
+ invariant6(this._peerInfo, void 0, {
2205
+ F: __dxlog_file7,
2206
+ L: 162,
2266
2207
  S: this,
2267
2208
  A: [
2268
- "topology",
2209
+ "this._peerInfo",
2269
2210
  ""
2270
2211
  ]
2271
2212
  });
2272
2213
  invariant6(typeof protocol === "function", void 0, {
2273
- F: __dxlog_file8,
2274
- L: 171,
2214
+ F: __dxlog_file7,
2215
+ L: 163,
2275
2216
  S: this,
2276
2217
  A: [
2277
2218
  "typeof protocol === 'function'",
@@ -2281,23 +2222,23 @@ var SwarmNetworkManager = class {
2281
2222
  if (this._swarms.has(topic)) {
2282
2223
  throw new Error(`Already connected to swarm: ${PublicKey8.from(topic)}`);
2283
2224
  }
2284
- log8("joining", {
2225
+ log7("joining", {
2285
2226
  topic: PublicKey8.from(topic),
2286
- peerInfo,
2227
+ peerInfo: this._peerInfo,
2287
2228
  topology: topology.toString()
2288
2229
  }, {
2289
- F: __dxlog_file8,
2290
- L: 176,
2230
+ F: __dxlog_file7,
2231
+ L: 168,
2291
2232
  S: this,
2292
2233
  C: (f, a) => f(...a)
2293
2234
  });
2294
- const swarm = new Swarm(topic, peerInfo, topology, protocol, this._messenger, this._transportFactory, label, this._connectionLimiter);
2235
+ const swarm = new Swarm(topic, this._peerInfo, topology, protocol, this._messenger, this._transportFactory, label, this._connectionLimiter);
2295
2236
  swarm.errors.handle((error) => {
2296
- log8("swarm error", {
2237
+ log7("swarm error", {
2297
2238
  error
2298
2239
  }, {
2299
- F: __dxlog_file8,
2300
- L: 189,
2240
+ F: __dxlog_file7,
2241
+ L: 181,
2301
2242
  S: this,
2302
2243
  C: (f, a) => f(...a)
2303
2244
  });
@@ -2307,21 +2248,21 @@ var SwarmNetworkManager = class {
2307
2248
  await swarm.open();
2308
2249
  this._signalConnection.join({
2309
2250
  topic,
2310
- peer: peerInfo
2311
- }).catch((error) => log8.catch(error, void 0, {
2312
- F: __dxlog_file8,
2313
- L: 198,
2251
+ peer: this._peerInfo
2252
+ }).catch((error) => log7.catch(error, void 0, {
2253
+ F: __dxlog_file7,
2254
+ L: 190,
2314
2255
  S: this,
2315
2256
  C: (f, a) => f(...a)
2316
2257
  }));
2317
2258
  this.topicsUpdated.emit();
2318
2259
  this._connectionLog?.joinedSwarm(swarm);
2319
- log8("joined", {
2260
+ log7("joined", {
2320
2261
  topic: PublicKey8.from(topic),
2321
2262
  count: this._swarms.size
2322
2263
  }, {
2323
- F: __dxlog_file8,
2324
- L: 202,
2264
+ F: __dxlog_file7,
2265
+ L: 194,
2325
2266
  S: this,
2326
2267
  C: (f, a) => f(...a)
2327
2268
  });
@@ -2336,11 +2277,11 @@ var SwarmNetworkManager = class {
2336
2277
  if (!this._swarms.has(topic)) {
2337
2278
  return;
2338
2279
  }
2339
- log8("leaving", {
2280
+ log7("leaving", {
2340
2281
  topic: PublicKey8.from(topic)
2341
2282
  }, {
2342
- F: __dxlog_file8,
2343
- L: 219,
2283
+ F: __dxlog_file7,
2284
+ L: 211,
2344
2285
  S: this,
2345
2286
  C: (f, a) => f(...a)
2346
2287
  });
@@ -2356,12 +2297,12 @@ var SwarmNetworkManager = class {
2356
2297
  await swarm.destroy();
2357
2298
  this._swarms.delete(topic);
2358
2299
  this.topicsUpdated.emit();
2359
- log8("left", {
2300
+ log7("left", {
2360
2301
  topic: PublicKey8.from(topic),
2361
2302
  count: this._swarms.size
2362
2303
  }, {
2363
- F: __dxlog_file8,
2364
- L: 233,
2304
+ F: __dxlog_file7,
2305
+ L: 225,
2365
2306
  S: this,
2366
2307
  C: (f, a) => f(...a)
2367
2308
  });
@@ -2402,14 +2343,14 @@ _ts_decorate4([
2402
2343
 
2403
2344
  // packages/core/mesh/network-manager/src/topology/fully-connected-topology.ts
2404
2345
  import { invariant as invariant7 } from "@dxos/invariant";
2405
- var __dxlog_file9 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/topology/fully-connected-topology.ts";
2346
+ var __dxlog_file8 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/topology/fully-connected-topology.ts";
2406
2347
  var FullyConnectedTopology = class {
2407
2348
  toString() {
2408
2349
  return "FullyConnectedTopology";
2409
2350
  }
2410
2351
  init(controller) {
2411
2352
  invariant7(!this._controller, "Already initialized", {
2412
- F: __dxlog_file9,
2353
+ F: __dxlog_file8,
2413
2354
  L: 18,
2414
2355
  S: this,
2415
2356
  A: [
@@ -2421,7 +2362,7 @@ var FullyConnectedTopology = class {
2421
2362
  }
2422
2363
  update() {
2423
2364
  invariant7(this._controller, "Not initialized", {
2424
- F: __dxlog_file9,
2365
+ F: __dxlog_file8,
2425
2366
  L: 23,
2426
2367
  S: this,
2427
2368
  A: [
@@ -2441,339 +2382,37 @@ var FullyConnectedTopology = class {
2441
2382
  }
2442
2383
  };
2443
2384
 
2444
- // packages/core/mesh/network-manager/src/topology/mmst-topology.ts
2385
+ // packages/core/mesh/network-manager/src/transport/memory-transport.ts
2386
+ import { Transform } from "@dxos/node-std/stream";
2387
+ import { Event as Event7, Trigger as Trigger2 } from "@dxos/async";
2388
+ import { ErrorStream as ErrorStream3 } from "@dxos/debug";
2445
2389
  import { invariant as invariant8 } from "@dxos/invariant";
2446
- import { log as log9 } from "@dxos/log";
2447
- var __dxlog_file10 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/topology/mmst-topology.ts";
2448
- var MIN_UPDATE_INTERVAL = 1e3 * 10;
2449
- var MAX_CHANGES_PER_UPDATE = 1;
2450
- var MMSTTopology = class {
2451
- constructor({ originateConnections = 2, maxPeers = 4, sampleSize = 10 } = {}) {
2452
- this._sampleCollected = false;
2453
- this._lastAction = /* @__PURE__ */ new Date(0);
2454
- this._originateConnections = originateConnections;
2455
- this._maxPeers = maxPeers;
2456
- this._sampleSize = sampleSize;
2457
- }
2458
- init(controller) {
2459
- invariant8(!this._controller, "Already initialized", {
2460
- F: __dxlog_file10,
2461
- L: 49,
2462
- S: this,
2463
- A: [
2464
- "!this._controller",
2465
- "'Already initialized'"
2466
- ]
2467
- });
2468
- this._controller = controller;
2469
- }
2470
- update() {
2471
- invariant8(this._controller, "Not initialized", {
2472
- F: __dxlog_file10,
2473
- L: 54,
2474
- S: this,
2475
- A: [
2476
- "this._controller",
2477
- "'Not initialized'"
2478
- ]
2479
- });
2480
- const { connected, candidates } = this._controller.getState();
2481
- if (this._sampleCollected || connected.length > this._maxPeers || candidates.length > 0) {
2482
- log9("Running the algorithm.", void 0, {
2483
- F: __dxlog_file10,
2484
- L: 58,
2485
- S: this,
2486
- C: (f, a) => f(...a)
2487
- });
2488
- this._sampleCollected = true;
2489
- this._runAlgorithm();
2490
- }
2491
- }
2492
- forceUpdate() {
2493
- this._lastAction = /* @__PURE__ */ new Date(0);
2494
- this.update();
2495
- }
2496
- async onOffer(peer) {
2497
- invariant8(this._controller, "Not initialized", {
2498
- F: __dxlog_file10,
2499
- L: 70,
2500
- S: this,
2501
- A: [
2502
- "this._controller",
2503
- "'Not initialized'"
2504
- ]
2505
- });
2506
- const { connected } = this._controller.getState();
2507
- const accept = connected.length < this._maxPeers;
2508
- log9(`Offer ${peer} accept=${accept}`, void 0, {
2509
- F: __dxlog_file10,
2510
- L: 73,
2511
- S: this,
2512
- C: (f, a) => f(...a)
2513
- });
2514
- return accept;
2515
- }
2516
- async destroy() {
2517
- }
2518
- _runAlgorithm() {
2519
- invariant8(this._controller, "Not initialized", {
2520
- F: __dxlog_file10,
2521
- L: 82,
2522
- S: this,
2523
- A: [
2524
- "this._controller",
2525
- "'Not initialized'"
2526
- ]
2527
- });
2528
- const { connected, candidates, ownPeerId } = this._controller.getState();
2529
- if (connected.length > this._maxPeers) {
2530
- log9(`disconnect ${connected.length - this._maxPeers} peers.`, void 0, {
2531
- F: __dxlog_file10,
2532
- L: 88,
2533
- S: this,
2534
- C: (f, a) => f(...a)
2535
- });
2536
- const sorted = sortByXorDistance(connected, ownPeerId).reverse().slice(0, this._maxPeers - connected.length);
2537
- invariant8(sorted.length === 0, void 0, {
2538
- F: __dxlog_file10,
2539
- L: 92,
2540
- S: this,
2541
- A: [
2542
- "sorted.length === 0",
2543
- ""
2544
- ]
2545
- });
2546
- if (sorted.length > MAX_CHANGES_PER_UPDATE) {
2547
- log9(`want to disconnect ${sorted.length} peers but limited to ${MAX_CHANGES_PER_UPDATE}`, void 0, {
2548
- F: __dxlog_file10,
2549
- L: 95,
2550
- S: this,
2551
- C: (f, a) => f(...a)
2552
- });
2553
- }
2554
- if (Date.now() - this._lastAction.getTime() > MIN_UPDATE_INTERVAL) {
2555
- for (const peer of sorted.slice(0, MAX_CHANGES_PER_UPDATE)) {
2556
- log9(`Disconnect ${peer}.`, void 0, {
2557
- F: __dxlog_file10,
2558
- L: 100,
2559
- S: this,
2560
- C: (f, a) => f(...a)
2561
- });
2562
- this._controller.disconnect(peer);
2563
- }
2564
- this._lastAction = /* @__PURE__ */ new Date();
2565
- } else {
2566
- log9("rate limited disconnect", void 0, {
2567
- F: __dxlog_file10,
2568
- L: 105,
2569
- S: this,
2570
- C: (f, a) => f(...a)
2571
- });
2572
- }
2573
- } else if (connected.length < this._originateConnections) {
2574
- log9(`connect ${this._originateConnections - connected.length} peers.`, void 0, {
2575
- F: __dxlog_file10,
2576
- L: 109,
2577
- S: this,
2578
- C: (f, a) => f(...a)
2579
- });
2580
- const sample = candidates.sort(() => Math.random() - 0.5).slice(0, this._sampleSize);
2581
- const sorted = sortByXorDistance(sample, ownPeerId).slice(0, this._originateConnections - connected.length);
2582
- if (sorted.length > MAX_CHANGES_PER_UPDATE) {
2583
- log9(`want to connect ${sorted.length} peers but limited to ${MAX_CHANGES_PER_UPDATE}`, void 0, {
2584
- F: __dxlog_file10,
2585
- L: 114,
2586
- S: this,
2587
- C: (f, a) => f(...a)
2588
- });
2589
- }
2590
- if (Date.now() - this._lastAction.getTime() > MIN_UPDATE_INTERVAL) {
2591
- for (const peer of sorted.slice(0, MAX_CHANGES_PER_UPDATE)) {
2592
- log9(`Connect ${peer}.`, void 0, {
2593
- F: __dxlog_file10,
2594
- L: 118,
2595
- S: this,
2596
- C: (f, a) => f(...a)
2597
- });
2598
- this._controller.connect(peer);
2599
- }
2600
- this._lastAction = /* @__PURE__ */ new Date();
2601
- } else {
2602
- log9("rate limited connect", void 0, {
2603
- F: __dxlog_file10,
2604
- L: 123,
2605
- S: this,
2606
- C: (f, a) => f(...a)
2607
- });
2608
- }
2609
- }
2610
- }
2611
- toString() {
2612
- return "MMSTTopology";
2613
- }
2614
- };
2615
- var sortByXorDistance = (keys, reference) => {
2616
- const sorted = keys.sort((a, b) => {
2617
- return compareXor(distXor(a.asBuffer(), reference.asBuffer()), distXor(b.asBuffer(), reference.asBuffer()));
2618
- });
2619
- log9("Sorted keys", {
2620
- keys,
2621
- reference,
2622
- sorted
2623
- }, {
2624
- F: __dxlog_file10,
2625
- L: 137,
2626
- S: void 0,
2627
- C: (f, a) => f(...a)
2628
- });
2629
- return sorted;
2630
- };
2631
- var distXor = (a, b) => {
2632
- const maxLength = Math.max(a.length, b.length);
2633
- const result = Buffer2.allocUnsafe(maxLength);
2634
- for (let i = 0; i < maxLength; i++) {
2635
- result[i] = (a[i] || 0) ^ (b[i] || 0);
2636
- }
2637
- return result;
2638
- };
2639
- var compareXor = (a, b) => {
2640
- const maxLength = Math.max(a.length, b.length);
2641
- for (let i = 0; i < maxLength; i++) {
2642
- if ((a[i] || 0) === (b[i] || 0)) {
2643
- continue;
2644
- }
2645
- return (a[i] || 0) < (b[i] || 0) ? -1 : 1;
2646
- }
2647
- return 0;
2648
- };
2649
-
2650
- // packages/core/mesh/network-manager/src/topology/star-topology.ts
2651
- import { invariant as invariant9 } from "@dxos/invariant";
2652
- import { log as log10 } from "@dxos/log";
2653
- var __dxlog_file11 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/topology/star-topology.ts";
2654
- var StarTopology = class {
2655
- constructor(_centralPeer) {
2656
- this._centralPeer = _centralPeer;
2657
- }
2658
- toString() {
2659
- return `StarTopology(${this._centralPeer.truncate()})`;
2660
- }
2661
- init(controller) {
2662
- invariant9(!this._controller, "Already initialized.", {
2663
- F: __dxlog_file11,
2664
- L: 21,
2665
- S: this,
2666
- A: [
2667
- "!this._controller",
2668
- "'Already initialized.'"
2669
- ]
2670
- });
2671
- this._controller = controller;
2672
- }
2673
- update() {
2674
- invariant9(this._controller, "Not initialized.", {
2675
- F: __dxlog_file11,
2676
- L: 26,
2677
- S: this,
2678
- A: [
2679
- "this._controller",
2680
- "'Not initialized.'"
2681
- ]
2682
- });
2683
- const { candidates, connected, ownPeerId } = this._controller.getState();
2684
- if (!ownPeerId.equals(this._centralPeer)) {
2685
- log10("leaf peer dropping all connections apart from central peer.", void 0, {
2686
- F: __dxlog_file11,
2687
- L: 29,
2688
- S: this,
2689
- C: (f, a) => f(...a)
2690
- });
2691
- for (const peer of connected) {
2692
- if (!peer.equals(this._centralPeer)) {
2693
- log10("dropping connection", {
2694
- peer
2695
- }, {
2696
- F: __dxlog_file11,
2697
- L: 34,
2698
- S: this,
2699
- C: (f, a) => f(...a)
2700
- });
2701
- this._controller.disconnect(peer);
2702
- }
2703
- }
2704
- }
2705
- for (const peer of candidates) {
2706
- if (peer.equals(this._centralPeer) || ownPeerId.equals(this._centralPeer)) {
2707
- log10("connecting to peer", {
2708
- peer
2709
- }, {
2710
- F: __dxlog_file11,
2711
- L: 43,
2712
- S: this,
2713
- C: (f, a) => f(...a)
2714
- });
2715
- this._controller.connect(peer);
2716
- }
2717
- }
2718
- }
2719
- async onOffer(peer) {
2720
- invariant9(this._controller, "Not initialized.", {
2721
- F: __dxlog_file11,
2722
- L: 50,
2723
- S: this,
2724
- A: [
2725
- "this._controller",
2726
- "'Not initialized.'"
2727
- ]
2728
- });
2729
- const { ownPeerId } = this._controller.getState();
2730
- log10("offer", {
2731
- peer,
2732
- isCentral: peer.equals(this._centralPeer),
2733
- isSelfCentral: ownPeerId.equals(this._centralPeer)
2734
- }, {
2735
- F: __dxlog_file11,
2736
- L: 52,
2737
- S: this,
2738
- C: (f, a) => f(...a)
2739
- });
2740
- return ownPeerId.equals(this._centralPeer) || peer.equals(this._centralPeer);
2741
- }
2742
- async destroy() {
2743
- }
2744
- };
2745
-
2746
- // packages/core/mesh/network-manager/src/transport/memory-transport.ts
2747
- import { Transform } from "@dxos/node-std/stream";
2748
- import { Event as Event7, Trigger as Trigger2 } from "@dxos/async";
2749
- import { ErrorStream as ErrorStream3 } from "@dxos/debug";
2750
- import { invariant as invariant10 } from "@dxos/invariant";
2751
- import { PublicKey as PublicKey9 } from "@dxos/keys";
2752
- import { log as log11, logInfo as logInfo3 } from "@dxos/log";
2753
- import { ComplexMap as ComplexMap7 } from "@dxos/util";
2754
- function _ts_decorate5(decorators, target, key, desc) {
2755
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
2756
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
2757
- 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;
2758
- return c > 3 && r && Object.defineProperty(target, key, r), r;
2759
- }
2760
- var __dxlog_file12 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/transport/memory-transport.ts";
2761
- var MEMORY_TRANSPORT_DELAY = 1;
2762
- var createStreamDelay = (delay) => {
2763
- return new Transform({
2764
- objectMode: true,
2765
- transform: (chunk, _, cb) => {
2766
- setTimeout(() => cb(null, chunk), delay);
2767
- }
2768
- });
2769
- };
2770
- var MemoryTransportFactory = {
2771
- createTransport: (options) => new MemoryTransport(options)
2772
- };
2773
- var MemoryTransport = class _MemoryTransport {
2774
- static {
2775
- // TODO(burdon): Remove static properties (inject context into constructor).
2776
- this._connections = new ComplexMap7(PublicKey9.hash);
2390
+ import { PublicKey as PublicKey9 } from "@dxos/keys";
2391
+ import { log as log8, logInfo as logInfo3 } from "@dxos/log";
2392
+ import { ComplexMap as ComplexMap7 } from "@dxos/util";
2393
+ function _ts_decorate5(decorators, target, key, desc) {
2394
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
2395
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
2396
+ 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;
2397
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
2398
+ }
2399
+ var __dxlog_file9 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/transport/memory-transport.ts";
2400
+ var MEMORY_TRANSPORT_DELAY = 1;
2401
+ var createStreamDelay = (delay) => {
2402
+ return new Transform({
2403
+ objectMode: true,
2404
+ transform: (chunk, _, cb) => {
2405
+ setTimeout(() => cb(null, chunk), delay);
2406
+ }
2407
+ });
2408
+ };
2409
+ var MemoryTransportFactory = {
2410
+ createTransport: (options) => new MemoryTransport(options)
2411
+ };
2412
+ var MemoryTransport = class _MemoryTransport {
2413
+ static {
2414
+ // TODO(burdon): Remove static properties (inject context into constructor).
2415
+ this._connections = new ComplexMap7(PublicKey9.hash);
2777
2416
  }
2778
2417
  constructor(_options) {
2779
2418
  this._options = _options;
@@ -2785,8 +2424,8 @@ var MemoryTransport = class _MemoryTransport {
2785
2424
  this.closed = new Event7();
2786
2425
  this.connected = new Event7();
2787
2426
  this.errors = new ErrorStream3();
2788
- invariant10(!_MemoryTransport._connections.has(this._instanceId), "Duplicate memory connection", {
2789
- F: __dxlog_file12,
2427
+ invariant8(!_MemoryTransport._connections.has(this._instanceId), "Duplicate memory connection", {
2428
+ F: __dxlog_file9,
2790
2429
  L: 64,
2791
2430
  S: this,
2792
2431
  A: [
@@ -2800,15 +2439,15 @@ var MemoryTransport = class _MemoryTransport {
2800
2439
  return !this._closed;
2801
2440
  }
2802
2441
  async open() {
2803
- log11("opening...", void 0, {
2804
- F: __dxlog_file12,
2442
+ log8("opening...", void 0, {
2443
+ F: __dxlog_file9,
2805
2444
  L: 74,
2806
2445
  S: this,
2807
2446
  C: (f, a) => f(...a)
2808
2447
  });
2809
2448
  if (this._options.initiator) {
2810
- log11("sending signal", void 0, {
2811
- F: __dxlog_file12,
2449
+ log8("sending signal", void 0, {
2450
+ F: __dxlog_file9,
2812
2451
  L: 78,
2813
2452
  S: this,
2814
2453
  C: (f, a) => f(...a)
@@ -2838,8 +2477,8 @@ var MemoryTransport = class _MemoryTransport {
2838
2477
  this.closed.emit();
2839
2478
  return;
2840
2479
  }
2841
- invariant10(!this._remoteConnection._remoteConnection, `Remote already connected: ${this._remoteInstanceId}`, {
2842
- F: __dxlog_file12,
2480
+ invariant8(!this._remoteConnection._remoteConnection, `Remote already connected: ${this._remoteInstanceId}`, {
2481
+ F: __dxlog_file9,
2843
2482
  L: 104,
2844
2483
  S: this,
2845
2484
  A: [
@@ -2849,8 +2488,8 @@ var MemoryTransport = class _MemoryTransport {
2849
2488
  });
2850
2489
  this._remoteConnection._remoteConnection = this;
2851
2490
  this._remoteConnection._remoteInstanceId = this._instanceId;
2852
- log11("connected", void 0, {
2853
- F: __dxlog_file12,
2491
+ log8("connected", void 0, {
2492
+ F: __dxlog_file9,
2854
2493
  L: 108,
2855
2494
  S: this,
2856
2495
  C: (f, a) => f(...a)
@@ -2865,11 +2504,12 @@ var MemoryTransport = class _MemoryTransport {
2865
2504
  this.errors.raise(err);
2866
2505
  });
2867
2506
  }
2507
+ return this;
2868
2508
  }
2869
2509
  async close() {
2870
- log11("closing...", void 0, {
2871
- F: __dxlog_file12,
2872
- L: 129,
2510
+ log8("closing...", void 0, {
2511
+ F: __dxlog_file9,
2512
+ L: 130,
2873
2513
  S: this,
2874
2514
  C: (f, a) => f(...a)
2875
2515
  });
@@ -2888,19 +2528,20 @@ var MemoryTransport = class _MemoryTransport {
2888
2528
  this._remoteConnection = void 0;
2889
2529
  }
2890
2530
  this.closed.emit();
2891
- log11("closed", void 0, {
2892
- F: __dxlog_file12,
2893
- L: 157,
2531
+ log8("closed", void 0, {
2532
+ F: __dxlog_file9,
2533
+ L: 158,
2894
2534
  S: this,
2895
2535
  C: (f, a) => f(...a)
2896
2536
  });
2537
+ return this;
2897
2538
  }
2898
2539
  async onSignal({ payload }) {
2899
- log11("received signal", {
2540
+ log8("received signal", {
2900
2541
  payload
2901
2542
  }, {
2902
- F: __dxlog_file12,
2903
- L: 161,
2543
+ F: __dxlog_file9,
2544
+ L: 163,
2904
2545
  S: this,
2905
2546
  C: (f, a) => f(...a)
2906
2547
  });
@@ -2936,525 +2577,979 @@ var toError = (err) => err instanceof Error ? err : new Error(String(err));
2936
2577
  // packages/core/mesh/network-manager/src/transport/transport.ts
2937
2578
  var TransportKind;
2938
2579
  (function(TransportKind2) {
2939
- TransportKind2["SIMPLE_PEER"] = "SIMPLE_PEER";
2940
- TransportKind2["SIMPLE_PEER_PROXY"] = "SIMPLE_PEER_PROXY";
2941
- TransportKind2["LIBDATACHANNEL"] = "LIBDATACHANNEL";
2580
+ TransportKind2["WEB_RTC"] = "WEB-RTC";
2581
+ TransportKind2["WEB_RTC_PROXY"] = "WEB-RTC_PROXY";
2942
2582
  TransportKind2["MEMORY"] = "MEMORY";
2943
2583
  TransportKind2["TCP"] = "TCP";
2944
2584
  })(TransportKind || (TransportKind = {}));
2945
2585
 
2946
- // packages/core/mesh/network-manager/src/transport/simplepeer-transport.ts
2947
- import SimplePeerConstructor from "simple-peer";
2948
- import invariant11 from "tiny-invariant";
2949
- import { Event as Event8, synchronized as synchronized5 } from "@dxos/async";
2950
- import { ErrorStream as ErrorStream4, raise as raise2 } from "@dxos/debug";
2951
- import { PublicKey as PublicKey10 } from "@dxos/keys";
2952
- import { log as log12 } from "@dxos/log";
2953
- import { ConnectionResetError as ConnectionResetError2, ConnectivityError as ConnectivityError2, ProtocolError as ProtocolError2, UnknownProtocolError as UnknownProtocolError2, trace as trace4 } from "@dxos/protocols";
2954
-
2955
- // packages/core/mesh/network-manager/src/transport/webrtc.ts
2956
- var wrtc = null;
2957
- try {
2958
- wrtc = __require("@koush/wrtc");
2959
- } catch {
2960
- }
2961
-
2962
- // packages/core/mesh/network-manager/src/transport/simplepeer-transport.ts
2963
- function _ts_decorate6(decorators, target, key, desc) {
2964
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
2965
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
2966
- 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;
2967
- return c > 3 && r && Object.defineProperty(target, key, r), r;
2968
- }
2969
- var __dxlog_file13 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/transport/simplepeer-transport.ts";
2970
- var createSimplePeerTransportFactory = (webrtcConfig, iceProvider) => ({
2971
- createTransport: (options) => new SimplePeerTransport({
2972
- ...options,
2973
- webrtcConfig,
2974
- iceProvider
2975
- })
2976
- });
2977
- var SimplePeerTransport = class {
2978
- get isOpen() {
2979
- return this._piped && !this._closed;
2586
+ // packages/core/mesh/network-manager/src/transport/webrtc/rtc-connection-factory.ts
2587
+ import { Mutex } from "@dxos/async";
2588
+ var BrowserRtcConnectionFactory = class {
2589
+ async initialize() {
2980
2590
  }
2981
- /**
2982
- * @params opts.config formatted as per https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/RTCPeerConnection
2983
- */
2984
- constructor(_params) {
2985
- this._params = _params;
2986
- this._peer = void 0;
2987
- this._closed = false;
2988
- this._piped = false;
2989
- this.closed = new Event8();
2990
- this.connected = new Event8();
2991
- this.errors = new ErrorStream4();
2992
- this._instanceId = PublicKey10.random().toHex();
2591
+ async onConnectionDestroyed() {
2993
2592
  }
2994
- async getStats() {
2995
- const stats = await this._getStats();
2996
- if (!stats) {
2997
- return {
2998
- bytesSent: 0,
2999
- bytesReceived: 0,
3000
- packetsSent: 0,
3001
- packetsReceived: 0,
3002
- rawStats: {}
3003
- };
3004
- }
3005
- return {
3006
- bytesSent: stats.transport.bytesSent,
3007
- bytesReceived: stats.transport.bytesReceived,
3008
- packetsSent: stats.transport.packetsSent,
3009
- packetsReceived: stats.transport.packetsReceived,
3010
- rawStats: stats.raw
3011
- };
2593
+ async createConnection(config) {
2594
+ return new RTCPeerConnection(config);
3012
2595
  }
3013
- async _getStats() {
3014
- if (typeof this._peer?._pc?.getStats !== "function") {
3015
- return null;
3016
- }
3017
- return await this._peer._pc.getStats().then((stats) => {
3018
- const statsEntries = Array.from(stats.entries());
3019
- const transport = statsEntries.filter((s) => s[1].type === "transport")[0][1];
3020
- const candidatePair = statsEntries.filter((s) => s[0] === transport.selectedCandidatePairId);
3021
- let selectedCandidatePair;
3022
- let remoteCandidate;
3023
- if (candidatePair.length > 0) {
3024
- selectedCandidatePair = candidatePair[0][1];
3025
- remoteCandidate = statsEntries.filter((s) => s[0] === selectedCandidatePair.remoteCandidateId)[0][1];
3026
- }
3027
- return {
3028
- datachannel: statsEntries.filter((s) => s[1].type === "data-channel")[0][1],
3029
- transport,
3030
- selectedCandidatePair,
3031
- remoteCandidate,
3032
- raw: Object.fromEntries(stats.entries())
3033
- };
3034
- });
2596
+ async initConnection(connection, info) {
3035
2597
  }
3036
- async getDetails() {
3037
- const stats = await this._getStats();
3038
- const rc = stats?.remoteCandidate;
3039
- if (!rc) {
3040
- return "unavailable";
3041
- }
3042
- if (rc.candidateType === "relay") {
3043
- return `${rc.ip}:${rc.port}/${rc.protocol} relay for ${rc.relatedAddress}:${rc.relatedPort}`;
3044
- }
3045
- return `${rc.ip}:${rc.port}/${rc.protocol} ${rc.candidateType}`;
2598
+ };
2599
+ var NodeRtcConnectionFactory = class _NodeRtcConnectionFactory {
2600
+ static {
2601
+ this._createdConnections = 0;
3046
2602
  }
3047
- async open() {
3048
- log12.trace("dxos.mesh.webrtc-transport.open", trace4.begin({
3049
- id: this._instanceId
3050
- }), {
3051
- F: __dxlog_file13,
3052
- L: 122,
3053
- S: this,
3054
- C: (f, a) => f(...a)
2603
+ static {
2604
+ this._cleanupMutex = new Mutex();
2605
+ }
2606
+ // This should be inside the function to avoid triggering `eval` in the global scope.
2607
+ // eslint-disable-next-line no-new-func
2608
+ // TODO(burdon): Do imports here?
2609
+ async initialize() {
2610
+ }
2611
+ async onConnectionDestroyed() {
2612
+ return _NodeRtcConnectionFactory._cleanupMutex.executeSynchronized(async () => {
2613
+ if (--_NodeRtcConnectionFactory._createdConnections === 0) {
2614
+ (await import("#node-datachannel")).cleanup();
2615
+ }
3055
2616
  });
3056
- log12("created connection", {
3057
- params: this._params
3058
- }, {
3059
- F: __dxlog_file13,
3060
- L: 123,
3061
- S: this,
3062
- C: (f, a) => f(...a)
2617
+ }
2618
+ async createConnection(config) {
2619
+ return _NodeRtcConnectionFactory._cleanupMutex.executeSynchronized(async () => {
2620
+ const { RTCPeerConnection: RTCPeerConnection1 } = await import("#node-datachannel/polyfill");
2621
+ _NodeRtcConnectionFactory._createdConnections++;
2622
+ return new RTCPeerConnection1(config);
3063
2623
  });
3064
- const providedIceServers = await this._params.iceProvider?.getIceServers();
3065
- if (!this._params.webrtcConfig) {
3066
- this._params.webrtcConfig = {};
2624
+ }
2625
+ async initConnection(connection, info) {
2626
+ if (info.initiator) {
2627
+ connection.onnegotiationneeded?.(null);
3067
2628
  }
3068
- this._params.webrtcConfig.iceServers = [
3069
- ...this._params.webrtcConfig.iceServers ?? [],
3070
- ...providedIceServers ?? []
3071
- ];
3072
- this._peer = new SimplePeerConstructor({
3073
- channelName: "dxos.mesh.transport",
3074
- initiator: this._params.initiator,
3075
- wrtc: SimplePeerConstructor.WEBRTC_SUPPORT ? void 0 : wrtc ?? raise2(new Error("wrtc not available")),
3076
- config: this._params.webrtcConfig
3077
- });
3078
- this._peer.on("signal", async (data) => {
3079
- log12("signal", data, {
3080
- F: __dxlog_file13,
3081
- L: 142,
3082
- S: this,
3083
- C: (f, a) => f(...a)
3084
- });
3085
- await this._params.sendSignal({
3086
- payload: {
3087
- data
3088
- }
3089
- });
2629
+ }
2630
+ };
2631
+ var getRtcConnectionFactory = () => {
2632
+ return typeof globalThis.RTCPeerConnection === "undefined" ? new NodeRtcConnectionFactory() : new BrowserRtcConnectionFactory();
2633
+ };
2634
+
2635
+ // packages/core/mesh/network-manager/src/transport/webrtc/rtc-peer-connection.ts
2636
+ import { synchronized as synchronized5, Trigger as Trigger3, Mutex as Mutex2 } from "@dxos/async";
2637
+ import { invariant as invariant10 } from "@dxos/invariant";
2638
+ import { log as log10, logInfo as logInfo4 } from "@dxos/log";
2639
+ import { ConnectivityError as ConnectivityError3 } from "@dxos/protocols";
2640
+ import { trace as trace4 } from "@dxos/tracing";
2641
+
2642
+ // packages/core/mesh/network-manager/src/transport/webrtc/rtc-transport-channel.ts
2643
+ import { Duplex } from "@dxos/node-std/stream";
2644
+ import { Event as AsyncEvent } from "@dxos/async";
2645
+ import { Resource } from "@dxos/context";
2646
+ import { ErrorStream as ErrorStream4 } from "@dxos/debug";
2647
+ import { invariant as invariant9 } from "@dxos/invariant";
2648
+ import { log as log9 } from "@dxos/log";
2649
+ import { ConnectivityError as ConnectivityError2 } from "@dxos/protocols";
2650
+
2651
+ // packages/core/mesh/network-manager/src/transport/webrtc/rtc-transport-stats.ts
2652
+ var describeSelectedRemoteCandidate = async (connection) => {
2653
+ const stats = connection && await getRtcConnectionStats(connection);
2654
+ const rc = stats?.remoteCandidate;
2655
+ if (!rc) {
2656
+ return "unavailable";
2657
+ }
2658
+ if (rc.candidateType === "relay") {
2659
+ return `${rc.ip}:${rc.port} relay for ${rc.relatedAddress}:${rc.relatedPort}`;
2660
+ }
2661
+ return `${rc.ip}:${rc.port} ${rc.candidateType}`;
2662
+ };
2663
+ var createRtcTransportStats = async (connection, topic) => {
2664
+ const stats = connection && await getRtcConnectionStats(connection, topic);
2665
+ if (!stats) {
2666
+ return {
2667
+ bytesSent: 0,
2668
+ bytesReceived: 0,
2669
+ packetsSent: 0,
2670
+ packetsReceived: 0,
2671
+ rawStats: {}
2672
+ };
2673
+ }
2674
+ return {
2675
+ bytesSent: stats.dataChannel?.bytesSent,
2676
+ bytesReceived: stats.dataChannel?.bytesReceived,
2677
+ packetsSent: 0,
2678
+ packetsReceived: 0,
2679
+ rawStats: stats.raw
2680
+ };
2681
+ };
2682
+ var getRtcConnectionStats = async (connection, channelTopic) => {
2683
+ const stats = await connection.getStats();
2684
+ const statsEntries = Array.from(stats.entries());
2685
+ const transport = statsEntries.find(([_, entry]) => entry.type === "transport")?.[1];
2686
+ const selectedCandidatePair = transport && statsEntries.find(([entryId]) => entryId === transport.selectedCandidatePairId)?.[1];
2687
+ const remoteCandidate = selectedCandidatePair && statsEntries.find(([entryId]) => entryId === selectedCandidatePair.remoteCandidateId)?.[1];
2688
+ const dataChannel = channelTopic && statsEntries.find(([_, entry]) => entry.type === "data-channel" && entry.label === channelTopic)?.[1];
2689
+ return {
2690
+ transport,
2691
+ selectedCandidatePair,
2692
+ dataChannel,
2693
+ remoteCandidate,
2694
+ raw: Object.fromEntries(stats)
2695
+ };
2696
+ };
2697
+
2698
+ // packages/core/mesh/network-manager/src/transport/webrtc/rtc-transport-channel.ts
2699
+ var __dxlog_file10 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/transport/webrtc/rtc-transport-channel.ts";
2700
+ var MAX_MESSAGE_SIZE = 64 * 1024;
2701
+ var MAX_BUFFERED_AMOUNT = 64 * 1024;
2702
+ var RtcTransportChannel = class extends Resource {
2703
+ constructor(_connection, _options) {
2704
+ super();
2705
+ this._connection = _connection;
2706
+ this._options = _options;
2707
+ this.closed = new AsyncEvent();
2708
+ this.connected = new AsyncEvent();
2709
+ this.errors = new ErrorStream4();
2710
+ this._streamDataFlushedCallback = null;
2711
+ this._isChannelCreationInProgress = false;
2712
+ }
2713
+ get isRtcChannelCreationInProgress() {
2714
+ return this._isChannelCreationInProgress;
2715
+ }
2716
+ onConnectionError(error) {
2717
+ if (this.isOpen) {
2718
+ this.errors.raise(error);
2719
+ }
2720
+ }
2721
+ async _open() {
2722
+ invariant9(!this._isChannelCreationInProgress, void 0, {
2723
+ F: __dxlog_file10,
2724
+ L: 56,
2725
+ S: this,
2726
+ A: [
2727
+ "!this._isChannelCreationInProgress",
2728
+ ""
2729
+ ]
3090
2730
  });
3091
- this._peer.on("connect", () => {
3092
- log12("connected", void 0, {
3093
- F: __dxlog_file13,
3094
- L: 147,
3095
- S: this,
3096
- C: (f, a) => f(...a)
3097
- });
3098
- this._params.stream.pipe(this._peer).pipe(this._params.stream);
3099
- this._piped = true;
3100
- this.connected.emit();
2731
+ this._isChannelCreationInProgress = true;
2732
+ this._connection.createDataChannel(this._options.topic).then((channel) => {
2733
+ if (this.isOpen) {
2734
+ this._channel = channel;
2735
+ this._initChannel(this._channel);
2736
+ } else {
2737
+ this._safeCloseChannel(channel);
2738
+ }
2739
+ }).catch((err) => {
2740
+ if (this.isOpen) {
2741
+ this.errors.raise(new ConnectivityError2(`Failed to create a channel: ${err?.message ?? "unknown reason."}`));
2742
+ }
2743
+ }).finally(() => {
2744
+ this._isChannelCreationInProgress = false;
3101
2745
  });
3102
- this._peer.on("close", async () => {
3103
- log12("closed", void 0, {
3104
- F: __dxlog_file13,
3105
- L: 154,
3106
- S: this,
3107
- C: (f, a) => f(...a)
3108
- });
3109
- await this.close();
2746
+ }
2747
+ async _close() {
2748
+ if (this._channel) {
2749
+ this._safeCloseChannel(this._channel);
2750
+ this._channel = void 0;
2751
+ this._stream = void 0;
2752
+ }
2753
+ this.closed.emit();
2754
+ log9("closed", void 0, {
2755
+ F: __dxlog_file10,
2756
+ L: 86,
2757
+ S: this,
2758
+ C: (f, a) => f(...a)
3110
2759
  });
3111
- this._peer.on("error", async (err) => {
3112
- if (typeof RTCError !== "undefined" && err instanceof RTCError) {
3113
- if (err.errorDetail === "sctp-failure") {
3114
- this.errors.raise(new ConnectionResetError2("sctp-failure from RTCError", err));
3115
- } else {
3116
- log12.info("unknown RTCError", {
3117
- err
2760
+ }
2761
+ _initChannel(channel) {
2762
+ Object.assign(channel, {
2763
+ onopen: () => {
2764
+ if (!this.isOpen) {
2765
+ log9.warn("channel opened in a closed transport", {
2766
+ topic: this._options.topic
3118
2767
  }, {
3119
- F: __dxlog_file13,
3120
- L: 165,
2768
+ F: __dxlog_file10,
2769
+ L: 93,
3121
2770
  S: this,
3122
2771
  C: (f, a) => f(...a)
3123
2772
  });
3124
- this.errors.raise(new UnknownProtocolError2("unknown RTCError", err));
2773
+ this._safeCloseChannel(channel);
2774
+ return;
3125
2775
  }
3126
- } else if ("code" in err) {
3127
- log12.info("simple-peer error", err, {
3128
- F: __dxlog_file13,
3129
- L: 170,
2776
+ log9("onopen", void 0, {
2777
+ F: __dxlog_file10,
2778
+ L: 98,
3130
2779
  S: this,
3131
2780
  C: (f, a) => f(...a)
3132
2781
  });
3133
- switch (err.code) {
3134
- case "ERR_WEBRTC_SUPPORT":
3135
- this.errors.raise(new ProtocolError2("WebRTC not supported", err));
3136
- break;
3137
- case "ERR_SIGNALING":
3138
- this.errors.raise(new ConnectivityError2("signaling failure", err));
3139
- break;
3140
- case "ERR_ICE_CONNECTION_FAILURE":
3141
- case "ERR_DATA_CHANNEL":
3142
- case "ERR_CONNECTION_FAILURE":
3143
- this.errors.raise(new ConnectivityError2("unknown communication failure", err));
3144
- break;
3145
- // errors due to library issues or improper API usage
3146
- case "ERR_CREATE_OFFER":
3147
- case "ERR_CREATE_ANSWER":
3148
- case "ERR_SET_LOCAL_DESCRIPTION":
3149
- case "ERR_SET_REMOTE_DESCRIPTION":
3150
- case "ERR_ADD_ICE_CANDIDATE":
3151
- this.errors.raise(new UnknownProtocolError2("unknown simple-peer library failure", err));
3152
- break;
3153
- default:
3154
- this.errors.raise(new Error("unknown simple-peer error"));
3155
- break;
3156
- }
3157
- } else {
3158
- log12.info("unknown peer connection error", err, {
3159
- F: __dxlog_file13,
3160
- L: 196,
2782
+ const duplex = new Duplex({
2783
+ read: () => {
2784
+ },
2785
+ write: (chunk, encoding, callback) => {
2786
+ return this._handleChannelWrite(chunk, callback);
2787
+ }
2788
+ });
2789
+ duplex.pipe(this._options.stream).pipe(duplex);
2790
+ this._stream = duplex;
2791
+ this.connected.emit();
2792
+ },
2793
+ onclose: async () => {
2794
+ log9("onclose", void 0, {
2795
+ F: __dxlog_file10,
2796
+ L: 111,
3161
2797
  S: this,
3162
2798
  C: (f, a) => f(...a)
3163
2799
  });
3164
- this.errors.raise(err);
3165
- }
3166
- try {
3167
- if (typeof this._peer?._pc?.getStats === "function") {
3168
- this._peer._pc.getStats().then((stats) => {
3169
- log12.info("report after webrtc error", {
3170
- config: this._params.webrtcConfig,
3171
- stats: Object.fromEntries(stats.entries())
3172
- }, {
3173
- F: __dxlog_file13,
3174
- L: 204,
3175
- S: this,
3176
- C: (f, a) => f(...a)
3177
- });
2800
+ await this.close();
2801
+ },
2802
+ onmessage: (event) => {
2803
+ if (!this._stream) {
2804
+ log9.warn("ignoring message on a closed channel", void 0, {
2805
+ F: __dxlog_file10,
2806
+ L: 117,
2807
+ S: this,
2808
+ C: (f, a) => f(...a)
3178
2809
  });
2810
+ return;
3179
2811
  }
3180
- } catch (err2) {
3181
- log12.catch(err2, void 0, {
3182
- F: __dxlog_file13,
3183
- L: 211,
3184
- S: this,
3185
- C: (f, a) => f(...a)
3186
- });
2812
+ let data = event.data;
2813
+ if (data instanceof ArrayBuffer) {
2814
+ data = Buffer.from(data);
2815
+ }
2816
+ this._stream.push(data);
2817
+ },
2818
+ onerror: (event) => {
2819
+ if (this.isOpen) {
2820
+ const err = event.error instanceof Error ? event.error : new Error(`Datachannel error: ${event.type}.`);
2821
+ this.errors.raise(err);
2822
+ }
2823
+ },
2824
+ onbufferedamountlow: () => {
2825
+ const cb = this._streamDataFlushedCallback;
2826
+ this._streamDataFlushedCallback = null;
2827
+ cb?.();
3187
2828
  }
3188
- await this.close();
3189
- });
3190
- log12.trace("dxos.mesh.webrtc-transport.open", trace4.end({
3191
- id: this._instanceId
3192
- }), {
3193
- F: __dxlog_file13,
3194
- L: 217,
3195
- S: this,
3196
- C: (f, a) => f(...a)
3197
2829
  });
3198
2830
  }
3199
- async close() {
3200
- log12("closing...", void 0, {
3201
- F: __dxlog_file13,
3202
- L: 222,
3203
- S: this,
3204
- C: (f, a) => f(...a)
3205
- });
3206
- if (this._closed) {
2831
+ async _handleChannelWrite(chunk, callback) {
2832
+ if (!this._channel) {
2833
+ log9.warn("writing to a channel after a connection was closed", void 0, {
2834
+ F: __dxlog_file10,
2835
+ L: 145,
2836
+ S: this,
2837
+ C: (f, a) => f(...a)
2838
+ });
3207
2839
  return;
3208
2840
  }
3209
- this._disconnectStreams();
3210
- this._peer.destroy();
3211
- this._closed = true;
3212
- this.closed.emit();
3213
- log12("closed", void 0, {
3214
- F: __dxlog_file13,
3215
- L: 230,
3216
- S: this,
3217
- C: (f, a) => f(...a)
3218
- });
3219
- }
3220
- async onSignal(signal) {
3221
- if (this._closed) {
2841
+ if (chunk.length > MAX_MESSAGE_SIZE) {
2842
+ const error = new Error(`Message too large: ${chunk.length} > ${MAX_MESSAGE_SIZE}.`);
2843
+ this.errors.raise(error);
2844
+ callback();
2845
+ return;
2846
+ }
2847
+ try {
2848
+ this._channel.send(chunk);
2849
+ } catch (err) {
2850
+ this.errors.raise(err);
2851
+ callback();
3222
2852
  return;
3223
2853
  }
3224
- invariant11(signal.payload.data, "Signal message must contain signal data.");
3225
- invariant11(this._peer, "Peer must be initialized before receiving signals.");
3226
- this._peer.signal(signal.payload.data);
2854
+ if (this._channel.bufferedAmount > MAX_BUFFERED_AMOUNT) {
2855
+ if (this._streamDataFlushedCallback !== null) {
2856
+ log9.error("consumer trying to write before we are ready for more data", void 0, {
2857
+ F: __dxlog_file10,
2858
+ L: 166,
2859
+ S: this,
2860
+ C: (f, a) => f(...a)
2861
+ });
2862
+ }
2863
+ this._streamDataFlushedCallback = callback;
2864
+ } else {
2865
+ callback();
2866
+ }
3227
2867
  }
3228
- _disconnectStreams() {
3229
- if (this._piped) {
3230
- this._params.stream.unpipe?.(this._peer)?.unpipe?.(this._params.stream);
2868
+ _safeCloseChannel(channel) {
2869
+ try {
2870
+ channel.close();
2871
+ } catch (error) {
2872
+ log9.catch(error, void 0, {
2873
+ F: __dxlog_file10,
2874
+ L: 178,
2875
+ S: this,
2876
+ C: (f, a) => f(...a)
2877
+ });
3231
2878
  }
3232
2879
  }
2880
+ onSignal(signal) {
2881
+ return this._connection.onSignal(signal);
2882
+ }
2883
+ async getDetails() {
2884
+ return describeSelectedRemoteCandidate(this._connection.currentConnection);
2885
+ }
2886
+ async getStats() {
2887
+ return createRtcTransportStats(this._connection.currentConnection, this._options.topic);
2888
+ }
3233
2889
  };
3234
- _ts_decorate6([
3235
- synchronized5
3236
- ], SimplePeerTransport.prototype, "open", null);
3237
- _ts_decorate6([
3238
- synchronized5
3239
- ], SimplePeerTransport.prototype, "close", null);
3240
- _ts_decorate6([
3241
- synchronized5
3242
- ], SimplePeerTransport.prototype, "onSignal", null);
3243
2890
 
3244
- // packages/core/mesh/network-manager/src/transport/simplepeer-transport-service.ts
3245
- import { Duplex } from "@dxos/node-std/stream";
3246
- import { Stream } from "@dxos/codec-protobuf";
3247
- import { invariant as invariant12 } from "@dxos/invariant";
3248
- import { PublicKey as PublicKey11 } from "@dxos/keys";
3249
- import { log as log13 } from "@dxos/log";
3250
- import { ConnectionState as ConnectionState3 } from "@dxos/protocols/proto/dxos/mesh/bridge";
3251
- import { ComplexMap as ComplexMap8 } from "@dxos/util";
3252
- var __dxlog_file14 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/transport/simplepeer-transport-service.ts";
3253
- var SimplePeerTransportService = class {
3254
- constructor(_webrtcConfig, _iceProvider) {
3255
- this._webrtcConfig = _webrtcConfig;
3256
- this._iceProvider = _iceProvider;
3257
- this.transports = new ComplexMap8(PublicKey11.hash);
3258
- }
3259
- open(request) {
3260
- const rpcStream = new Stream(({ ready, next, close }) => {
3261
- const duplex = new Duplex({
3262
- read: () => {
3263
- const callbacks = [
3264
- ...transportState.writeCallbacks
3265
- ];
3266
- transportState.writeCallbacks.length = 0;
3267
- for (const cb of callbacks) {
3268
- cb();
3269
- }
3270
- },
3271
- write: function(chunk, _, callback) {
3272
- next({
3273
- data: {
3274
- payload: chunk
3275
- }
3276
- });
3277
- callback();
3278
- }
3279
- });
3280
- const transport = new SimplePeerTransport({
3281
- initiator: request.initiator,
3282
- stream: duplex,
3283
- webrtcConfig: this._webrtcConfig,
3284
- sendSignal: async (signal) => {
3285
- next({
3286
- signal: {
3287
- payload: signal
3288
- }
3289
- });
3290
- },
3291
- iceProvider: this._iceProvider
3292
- });
3293
- void transport.open();
3294
- next({
3295
- connection: {
3296
- state: ConnectionState3.CONNECTING
3297
- }
3298
- });
3299
- transport.connected.on(() => {
3300
- next({
3301
- connection: {
3302
- state: ConnectionState3.CONNECTED
3303
- }
3304
- });
3305
- });
3306
- transport.errors.handle((err) => {
3307
- next({
3308
- connection: {
3309
- state: ConnectionState3.CLOSED,
3310
- error: err.toString()
3311
- }
3312
- });
3313
- close(err);
3314
- });
3315
- transport.closed.on(() => {
3316
- next({
3317
- connection: {
3318
- state: ConnectionState3.CLOSED
3319
- }
3320
- });
3321
- close();
3322
- });
3323
- const transportState = {
3324
- transport,
3325
- stream: duplex,
3326
- writeCallbacks: [],
3327
- state: "OPEN"
3328
- };
3329
- ready();
3330
- this.transports.set(request.proxyId, transportState);
3331
- });
3332
- return rpcStream;
2891
+ // packages/core/mesh/network-manager/src/transport/webrtc/utils.ts
2892
+ var chooseInitiatorPeer = (peer1Key, peer2Key) => peer1Key < peer2Key ? peer1Key : peer2Key;
2893
+ var areSdpEqual = (sdp1, sdp2) => {
2894
+ const sdp1Lines = deduplicatedSdpLines(sdp1);
2895
+ const sdp2Lines = deduplicatedSdpLines(sdp2);
2896
+ if (sdp1Lines.length !== sdp2Lines.length) {
2897
+ return false;
2898
+ }
2899
+ return sdp1Lines.every((line, idx) => line === sdp2Lines[idx]);
2900
+ };
2901
+ var deduplicatedSdpLines = (sdp) => {
2902
+ const deduplicatedLines = [];
2903
+ const seenLines = [];
2904
+ for (const line of sdp.split("\r\n")) {
2905
+ if (line.startsWith("m")) {
2906
+ seenLines.length = 0;
2907
+ }
2908
+ if (seenLines.includes(line)) {
2909
+ continue;
2910
+ }
2911
+ seenLines.push(line);
2912
+ deduplicatedLines.push(line);
3333
2913
  }
3334
- async sendSignal({ proxyId, signal }) {
3335
- invariant12(this.transports.has(proxyId), void 0, {
3336
- F: __dxlog_file14,
3337
- L: 124,
3338
- S: this,
3339
- A: [
3340
- "this.transports.has(proxyId)",
3341
- ""
3342
- ]
3343
- });
3344
- await this.transports.get(proxyId).transport.onSignal(signal);
2914
+ return deduplicatedLines;
2915
+ };
2916
+
2917
+ // packages/core/mesh/network-manager/src/transport/webrtc/rtc-peer-connection.ts
2918
+ function _ts_decorate6(decorators, target, key, desc) {
2919
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
2920
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
2921
+ 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;
2922
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
2923
+ }
2924
+ var __dxlog_file11 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/transport/webrtc/rtc-peer-connection.ts";
2925
+ var RtcPeerConnection = class {
2926
+ constructor(_factory, _options) {
2927
+ this._factory = _factory;
2928
+ this._options = _options;
2929
+ this._channelCreatedCallbacks = /* @__PURE__ */ new Map();
2930
+ this._transportChannels = /* @__PURE__ */ new Map();
2931
+ this._dataChannels = /* @__PURE__ */ new Map();
2932
+ this._readyForCandidates = new Trigger3();
2933
+ this._offerProcessingMutex = new Mutex2();
2934
+ this._initiator = chooseInitiatorPeer(_options.ownPeerKey, _options.remotePeerKey) === _options.ownPeerKey;
3345
2935
  }
3346
- async getDetails({ proxyId }) {
3347
- invariant12(this.transports.has(proxyId), void 0, {
3348
- F: __dxlog_file14,
3349
- L: 129,
3350
- S: this,
3351
- A: [
3352
- "this.transports.has(proxyId)",
3353
- ""
3354
- ]
3355
- });
3356
- return {
3357
- details: await this.transports.get(proxyId).transport.getDetails()
3358
- };
2936
+ get transportChannelCount() {
2937
+ return this._transportChannels.size;
3359
2938
  }
3360
- async getStats({ proxyId }) {
3361
- invariant12(this.transports.has(proxyId), void 0, {
3362
- F: __dxlog_file14,
3363
- L: 134,
3364
- S: this,
3365
- A: [
3366
- "this.transports.has(proxyId)",
3367
- ""
3368
- ]
3369
- });
3370
- return {
3371
- stats: await this.transports.get(proxyId).transport.getStats()
3372
- };
2939
+ get currentConnection() {
2940
+ return this._connection;
3373
2941
  }
3374
- async sendData({ proxyId, payload }) {
3375
- if (this.transports.get(proxyId)?.state !== "OPEN") {
3376
- log13.debug("transport is closed", void 0, {
3377
- F: __dxlog_file14,
3378
- L: 140,
2942
+ async createDataChannel(topic) {
2943
+ const connection = await this._openConnection();
2944
+ if (!this._transportChannels.has(topic)) {
2945
+ if (!this._transportChannels.size) {
2946
+ this._lockAndCloseConnection();
2947
+ }
2948
+ throw new Error("Transport closed while connection was being open");
2949
+ }
2950
+ if (this._initiator) {
2951
+ const channel = connection.createDataChannel(topic);
2952
+ this._dataChannels.set(topic, channel);
2953
+ return channel;
2954
+ } else {
2955
+ const existingChannel = this._dataChannels.get(topic);
2956
+ if (existingChannel) {
2957
+ return existingChannel;
2958
+ }
2959
+ log10("waiting for initiator-peer to open a data channel", void 0, {
2960
+ F: __dxlog_file11,
2961
+ L: 90,
3379
2962
  S: this,
3380
2963
  C: (f, a) => f(...a)
3381
2964
  });
3382
- }
3383
- invariant12(this.transports.has(proxyId), void 0, {
3384
- F: __dxlog_file14,
3385
- L: 142,
3386
- S: this,
3387
- A: [
3388
- "this.transports.has(proxyId)",
3389
- ""
3390
- ]
3391
- });
3392
- const state = this.transports.get(proxyId);
3393
- const bufferHasSpace = state.stream.push(payload);
3394
- if (!bufferHasSpace) {
3395
- await new Promise((resolve) => {
3396
- state.writeCallbacks.push(resolve);
2965
+ return new Promise((resolve, reject) => {
2966
+ this._channelCreatedCallbacks.set(topic, {
2967
+ resolve,
2968
+ reject
2969
+ });
3397
2970
  });
3398
2971
  }
3399
2972
  }
3400
- async close({ proxyId }) {
3401
- await this.transports.get(proxyId)?.transport.close();
3402
- await this.transports.get(proxyId)?.stream.end();
3403
- if (this.transports.get(proxyId)) {
3404
- this.transports.get(proxyId).state = "CLOSED";
3405
- }
3406
- log13("Closed.", void 0, {
3407
- F: __dxlog_file14,
3408
- L: 158,
2973
+ createTransportChannel(options) {
2974
+ const channel = new RtcTransportChannel(this, options);
2975
+ this._transportChannels.set(options.topic, channel);
2976
+ channel.closed.on(() => {
2977
+ this._transportChannels.delete(options.topic);
2978
+ if (this._transportChannels.size === 0) {
2979
+ this._lockAndCloseConnection();
2980
+ }
2981
+ });
2982
+ return channel;
2983
+ }
2984
+ async _openConnection() {
2985
+ if (this._connection) {
2986
+ return this._connection;
2987
+ }
2988
+ log10("initializing connection...", () => ({
2989
+ remotePeer: this._options.remotePeerKey
2990
+ }), {
2991
+ F: __dxlog_file11,
2992
+ L: 115,
2993
+ S: this,
2994
+ C: (f, a) => f(...a)
2995
+ });
2996
+ const config = await this._loadConnectionConfig();
2997
+ const connection = await this._factory.createConnection(config);
2998
+ const iceCandidateErrors = [];
2999
+ Object.assign(connection, {
3000
+ onnegotiationneeded: async () => {
3001
+ invariant10(this._initiator, void 0, {
3002
+ F: __dxlog_file11,
3003
+ L: 130,
3004
+ S: this,
3005
+ A: [
3006
+ "this._initiator",
3007
+ ""
3008
+ ]
3009
+ });
3010
+ if (connection !== this._connection) {
3011
+ this._onConnectionCallbackAfterClose("onnegotiationneeded", connection);
3012
+ return;
3013
+ }
3014
+ log10("onnegotiationneeded", void 0, {
3015
+ F: __dxlog_file11,
3016
+ L: 137,
3017
+ S: this,
3018
+ C: (f, a) => f(...a)
3019
+ });
3020
+ try {
3021
+ const offer = await connection.createOffer();
3022
+ await connection.setLocalDescription(offer);
3023
+ await this._sendDescription(connection, offer);
3024
+ } catch (err) {
3025
+ this._lockAndAbort(connection, err);
3026
+ }
3027
+ },
3028
+ // When ICE candidate identified (should be sent to remote peer) and when ICE gathering finalized.
3029
+ // https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/icecandidate_event
3030
+ onicecandidate: async (event) => {
3031
+ if (connection !== this._connection) {
3032
+ this._onConnectionCallbackAfterClose("onicecandidate", connection);
3033
+ return;
3034
+ }
3035
+ if (event.candidate) {
3036
+ log10("onicecandidate", {
3037
+ candidate: event.candidate.candidate
3038
+ }, {
3039
+ F: __dxlog_file11,
3040
+ L: 156,
3041
+ S: this,
3042
+ C: (f, a) => f(...a)
3043
+ });
3044
+ await this._sendIceCandidate(event.candidate);
3045
+ } else {
3046
+ log10("onicecandidate gathering complete", void 0, {
3047
+ F: __dxlog_file11,
3048
+ L: 159,
3049
+ S: this,
3050
+ C: (f, a) => f(...a)
3051
+ });
3052
+ }
3053
+ },
3054
+ // When error occurs while performing ICE negotiations through a STUN or TURN server.
3055
+ // It's ok for some candidates to fail if a working pair is eventually found.
3056
+ // https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/icecandidateerror_event
3057
+ onicecandidateerror: (event) => {
3058
+ const { url, errorCode, errorText } = event;
3059
+ iceCandidateErrors.push({
3060
+ url,
3061
+ errorCode,
3062
+ errorText
3063
+ });
3064
+ },
3065
+ // When possible error during ICE gathering.
3066
+ // https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/iceconnectionstatechange_event
3067
+ oniceconnectionstatechange: () => {
3068
+ if (connection !== this._connection) {
3069
+ this._onConnectionCallbackAfterClose("oniceconnectionstatechange", connection);
3070
+ return;
3071
+ }
3072
+ log10("oniceconnectionstatechange", {
3073
+ state: connection.iceConnectionState
3074
+ }, {
3075
+ F: __dxlog_file11,
3076
+ L: 179,
3077
+ S: this,
3078
+ C: (f, a) => f(...a)
3079
+ });
3080
+ if (connection.iceConnectionState === "failed") {
3081
+ this._lockAndAbort(connection, createIceFailureError(iceCandidateErrors));
3082
+ }
3083
+ },
3084
+ // When new track (or channel) is added.
3085
+ // State: { new, connecting, connected, disconnected, failed, closed }
3086
+ // https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/connectionstatechange_event
3087
+ onconnectionstatechange: () => {
3088
+ if (connection !== this._connection) {
3089
+ if (connection.connectionState !== "closed" && connection.connectionState !== "failed") {
3090
+ this._onConnectionCallbackAfterClose("onconnectionstatechange", connection);
3091
+ }
3092
+ return;
3093
+ }
3094
+ log10("onconnectionstatechange", {
3095
+ state: connection.connectionState
3096
+ }, {
3097
+ F: __dxlog_file11,
3098
+ L: 196,
3099
+ S: this,
3100
+ C: (f, a) => f(...a)
3101
+ });
3102
+ if (connection.connectionState === "failed") {
3103
+ this._lockAndAbort(connection, new Error("Connection failed."));
3104
+ }
3105
+ },
3106
+ onsignalingstatechange: () => {
3107
+ log10("onsignalingstatechange", {
3108
+ state: connection.signalingState
3109
+ }, {
3110
+ F: __dxlog_file11,
3111
+ L: 203,
3112
+ S: this,
3113
+ C: (f, a) => f(...a)
3114
+ });
3115
+ },
3116
+ // When channel is added to connection.
3117
+ // https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/datachannel_event
3118
+ ondatachannel: (event) => {
3119
+ invariant10(!this._initiator, "Initiator is expected to create data channels.", {
3120
+ F: __dxlog_file11,
3121
+ L: 209,
3122
+ S: this,
3123
+ A: [
3124
+ "!this._initiator",
3125
+ "'Initiator is expected to create data channels.'"
3126
+ ]
3127
+ });
3128
+ if (connection !== this._connection) {
3129
+ this._onConnectionCallbackAfterClose("ondatachannel", connection);
3130
+ return;
3131
+ }
3132
+ log10("ondatachannel", {
3133
+ label: event.channel.label
3134
+ }, {
3135
+ F: __dxlog_file11,
3136
+ L: 216,
3137
+ S: this,
3138
+ C: (f, a) => f(...a)
3139
+ });
3140
+ this._dataChannels.set(event.channel.label, event.channel);
3141
+ const pendingCallback = this._channelCreatedCallbacks.get(event.channel.label);
3142
+ if (pendingCallback) {
3143
+ this._channelCreatedCallbacks.delete(event.channel.label);
3144
+ pendingCallback.resolve(event.channel);
3145
+ }
3146
+ }
3147
+ });
3148
+ this._connection = connection;
3149
+ this._readyForCandidates.reset();
3150
+ await this._factory.initConnection(connection, {
3151
+ initiator: this._initiator
3152
+ });
3153
+ return this._connection;
3154
+ }
3155
+ _lockAndAbort(connection, error) {
3156
+ this._abortConnection(connection, error);
3157
+ }
3158
+ _abortConnection(connection, error) {
3159
+ if (connection !== this._connection) {
3160
+ log10.error("attempted to abort an inactive connection", {
3161
+ error
3162
+ }, {
3163
+ F: __dxlog_file11,
3164
+ L: 241,
3165
+ S: this,
3166
+ C: (f, a) => f(...a)
3167
+ });
3168
+ this._safeCloseConnection(connection);
3169
+ return;
3170
+ }
3171
+ for (const [topic, pendingCallback] of this._channelCreatedCallbacks.entries()) {
3172
+ pendingCallback.reject(error);
3173
+ this._transportChannels.delete(topic);
3174
+ }
3175
+ this._channelCreatedCallbacks.clear();
3176
+ for (const channel of this._transportChannels.values()) {
3177
+ channel.onConnectionError(error);
3178
+ }
3179
+ this._transportChannels.clear();
3180
+ this._safeCloseConnection();
3181
+ log10("connection aborted", {
3182
+ reason: error.message
3183
+ }, {
3184
+ F: __dxlog_file11,
3185
+ L: 255,
3186
+ S: this,
3187
+ C: (f, a) => f(...a)
3188
+ });
3189
+ }
3190
+ _lockAndCloseConnection() {
3191
+ invariant10(this._transportChannels.size === 0, void 0, {
3192
+ F: __dxlog_file11,
3193
+ L: 260,
3194
+ S: this,
3195
+ A: [
3196
+ "this._transportChannels.size === 0",
3197
+ ""
3198
+ ]
3199
+ });
3200
+ if (this._connection) {
3201
+ this._safeCloseConnection();
3202
+ log10("connection closed", void 0, {
3203
+ F: __dxlog_file11,
3204
+ L: 263,
3205
+ S: this,
3206
+ C: (f, a) => f(...a)
3207
+ });
3208
+ }
3209
+ }
3210
+ async onSignal(signal) {
3211
+ const connection = this._connection;
3212
+ if (!connection) {
3213
+ log10.warn("a signal ignored because the connection was closed", {
3214
+ type: signal.payload.data.type
3215
+ }, {
3216
+ F: __dxlog_file11,
3217
+ L: 271,
3218
+ S: this,
3219
+ C: (f, a) => f(...a)
3220
+ });
3221
+ return;
3222
+ }
3223
+ const data = signal.payload.data;
3224
+ switch (data.type) {
3225
+ case "offer": {
3226
+ await this._offerProcessingMutex.executeSynchronized(async () => {
3227
+ if (isRemoteDescriptionSet(connection, data)) {
3228
+ return;
3229
+ }
3230
+ if (connection.connectionState !== "new") {
3231
+ this._abortConnection(connection, new Error(`Received an offer in ${connection.connectionState}.`));
3232
+ return;
3233
+ }
3234
+ try {
3235
+ await connection.setRemoteDescription({
3236
+ type: data.type,
3237
+ sdp: data.sdp
3238
+ });
3239
+ const answer = await connection.createAnswer();
3240
+ await connection.setLocalDescription(answer);
3241
+ await this._sendDescription(connection, answer);
3242
+ this._onSessionNegotiated(connection);
3243
+ } catch (err) {
3244
+ this._abortConnection(connection, new Error("Error handling a remote offer.", {
3245
+ cause: err
3246
+ }));
3247
+ }
3248
+ });
3249
+ break;
3250
+ }
3251
+ case "answer":
3252
+ await this._offerProcessingMutex.executeSynchronized(async () => {
3253
+ try {
3254
+ if (isRemoteDescriptionSet(connection, data)) {
3255
+ return;
3256
+ }
3257
+ if (connection.signalingState !== "have-local-offer") {
3258
+ this._abortConnection(connection, new Error(`Unexpected answer from remote peer, signalingState was ${connection.signalingState}.`));
3259
+ return;
3260
+ }
3261
+ await connection.setRemoteDescription({
3262
+ type: data.type,
3263
+ sdp: data.sdp
3264
+ });
3265
+ this._onSessionNegotiated(connection);
3266
+ } catch (err) {
3267
+ this._abortConnection(connection, new Error("Error handling a remote answer.", {
3268
+ cause: err
3269
+ }));
3270
+ }
3271
+ });
3272
+ break;
3273
+ case "candidate":
3274
+ void this._processIceCandidate(connection, data.candidate);
3275
+ break;
3276
+ default:
3277
+ this._abortConnection(connection, new Error(`Unknown signal type ${data.type}.`));
3278
+ break;
3279
+ }
3280
+ log10("signal processed", void 0, {
3281
+ F: __dxlog_file11,
3282
+ L: 330,
3283
+ S: this,
3284
+ C: (f, a) => f(...a)
3285
+ });
3286
+ }
3287
+ async _processIceCandidate(connection, candidate) {
3288
+ try {
3289
+ await this._readyForCandidates.wait();
3290
+ if (connection === this._connection) {
3291
+ log10("adding ice candidate", {
3292
+ candidate
3293
+ }, {
3294
+ F: __dxlog_file11,
3295
+ L: 338,
3296
+ S: this,
3297
+ C: (f, a) => f(...a)
3298
+ });
3299
+ await connection.addIceCandidate(candidate);
3300
+ }
3301
+ } catch (err) {
3302
+ log10.catch(err, void 0, {
3303
+ F: __dxlog_file11,
3304
+ L: 342,
3305
+ S: this,
3306
+ C: (f, a) => f(...a)
3307
+ });
3308
+ }
3309
+ }
3310
+ _onSessionNegotiated(connection) {
3311
+ if (connection === this._connection) {
3312
+ log10("ready to process ice candidates", void 0, {
3313
+ F: __dxlog_file11,
3314
+ L: 348,
3315
+ S: this,
3316
+ C: (f, a) => f(...a)
3317
+ });
3318
+ this._readyForCandidates.wake();
3319
+ } else {
3320
+ log10.warn("session was negotiated after connection became inactive", void 0, {
3321
+ F: __dxlog_file11,
3322
+ L: 351,
3323
+ S: this,
3324
+ C: (f, a) => f(...a)
3325
+ });
3326
+ }
3327
+ }
3328
+ _onConnectionCallbackAfterClose(callback, connection) {
3329
+ log10.warn("callback invoked after a connection was destroyed, this is probably a bug", {
3330
+ callback,
3331
+ state: connection.connectionState
3332
+ }, {
3333
+ F: __dxlog_file11,
3334
+ L: 356,
3409
3335
  S: this,
3410
3336
  C: (f, a) => f(...a)
3411
3337
  });
3338
+ this._safeCloseConnection(connection);
3339
+ }
3340
+ _safeCloseConnection(connection = this._connection) {
3341
+ const resetFields = this._connection && connection === this._connection;
3342
+ try {
3343
+ connection?.close();
3344
+ } catch (err) {
3345
+ log10.catch(err, void 0, {
3346
+ F: __dxlog_file11,
3347
+ L: 368,
3348
+ S: this,
3349
+ C: (f, a) => f(...a)
3350
+ });
3351
+ }
3352
+ if (resetFields) {
3353
+ this._connection = void 0;
3354
+ this._dataChannels.clear();
3355
+ this._readyForCandidates.wake();
3356
+ void this._factory.onConnectionDestroyed().catch((err) => log10.catch(err, void 0, {
3357
+ F: __dxlog_file11,
3358
+ L: 374,
3359
+ S: this,
3360
+ C: (f, a) => f(...a)
3361
+ }));
3362
+ for (const [_, pendingCallback] of this._channelCreatedCallbacks.entries()) {
3363
+ pendingCallback.reject("Connection closed.");
3364
+ }
3365
+ this._channelCreatedCallbacks.clear();
3366
+ }
3367
+ }
3368
+ async _loadConnectionConfig() {
3369
+ const config = {
3370
+ ...this._options.webrtcConfig
3371
+ };
3372
+ try {
3373
+ const providedIceServers = await this._options.iceProvider?.getIceServers() ?? [];
3374
+ if (providedIceServers.length > 0) {
3375
+ config.iceServers = [
3376
+ ...config.iceServers ?? [],
3377
+ ...providedIceServers
3378
+ ];
3379
+ }
3380
+ } catch (error) {
3381
+ log10.catch(error, void 0, {
3382
+ F: __dxlog_file11,
3383
+ L: 390,
3384
+ S: this,
3385
+ C: (f, a) => f(...a)
3386
+ });
3387
+ }
3388
+ return config;
3389
+ }
3390
+ async _sendIceCandidate(candidate) {
3391
+ try {
3392
+ await this._options.sendSignal({
3393
+ payload: {
3394
+ data: {
3395
+ type: "candidate",
3396
+ candidate: {
3397
+ candidate: candidate.candidate,
3398
+ // These fields never seem to be not null, but connecting to Chrome doesn't work if they are.
3399
+ sdpMLineIndex: candidate.sdpMLineIndex ?? "0",
3400
+ sdpMid: candidate.sdpMid ?? "0"
3401
+ }
3402
+ }
3403
+ }
3404
+ });
3405
+ } catch (err) {
3406
+ log10.warn("signaling error", {
3407
+ err
3408
+ }, {
3409
+ F: __dxlog_file11,
3410
+ L: 411,
3411
+ S: this,
3412
+ C: (f, a) => f(...a)
3413
+ });
3414
+ }
3415
+ }
3416
+ async _sendDescription(connection, description) {
3417
+ if (connection !== this._connection) {
3418
+ return;
3419
+ }
3420
+ const data = {
3421
+ type: description.type,
3422
+ sdp: description.sdp
3423
+ };
3424
+ await this._options.sendSignal({
3425
+ payload: {
3426
+ data
3427
+ }
3428
+ });
3429
+ }
3430
+ get _connectionInfo() {
3431
+ const connectionInfo = this._connection && {
3432
+ connectionState: this._connection.connectionState,
3433
+ iceConnectionState: this._connection.iceConnectionState,
3434
+ iceGatheringState: this._connection.iceGatheringState,
3435
+ signalingState: this._connection.signalingState,
3436
+ remoteDescription: this._connection.remoteDescription,
3437
+ localDescription: this._connection.localDescription
3438
+ };
3439
+ return {
3440
+ ...connectionInfo,
3441
+ ts: Date.now(),
3442
+ remotePeerKey: this._options.remotePeerKey,
3443
+ channels: [
3444
+ ...this._transportChannels.keys()
3445
+ ].map((topic) => topic),
3446
+ config: this._connection?.getConfiguration()
3447
+ };
3448
+ }
3449
+ get _loggerContext() {
3450
+ return {
3451
+ ownPeerKey: this._options.ownPeerKey,
3452
+ remotePeerKey: this._options.remotePeerKey,
3453
+ initiator: this._initiator,
3454
+ channels: this._transportChannels.size
3455
+ };
3412
3456
  }
3413
3457
  };
3458
+ _ts_decorate6([
3459
+ synchronized5
3460
+ ], RtcPeerConnection.prototype, "_openConnection", null);
3461
+ _ts_decorate6([
3462
+ synchronized5
3463
+ ], RtcPeerConnection.prototype, "_lockAndAbort", null);
3464
+ _ts_decorate6([
3465
+ synchronized5
3466
+ ], RtcPeerConnection.prototype, "_lockAndCloseConnection", null);
3467
+ _ts_decorate6([
3468
+ synchronized5
3469
+ ], RtcPeerConnection.prototype, "onSignal", null);
3470
+ _ts_decorate6([
3471
+ trace4.info()
3472
+ ], RtcPeerConnection.prototype, "_connectionInfo", null);
3473
+ _ts_decorate6([
3474
+ logInfo4
3475
+ ], RtcPeerConnection.prototype, "_loggerContext", null);
3476
+ RtcPeerConnection = _ts_decorate6([
3477
+ trace4.resource()
3478
+ ], RtcPeerConnection);
3479
+ var isRemoteDescriptionSet = (connection, data) => {
3480
+ if (!connection.remoteDescription?.type || connection.remoteDescription?.type !== data.type) {
3481
+ return false;
3482
+ }
3483
+ return areSdpEqual(connection.remoteDescription.sdp, data.sdp);
3484
+ };
3485
+ var createIceFailureError = (details) => {
3486
+ const candidateErrors = details.map(({ url, errorCode, errorText }) => `${errorCode} ${url}: ${errorText}`);
3487
+ return new ConnectivityError3(`ICE failed:
3488
+ ${candidateErrors.join("\n")}`);
3489
+ };
3490
+
3491
+ // packages/core/mesh/network-manager/src/transport/webrtc/rtc-transport-factory.ts
3492
+ var createRtcTransportFactory = (webrtcConfig, iceProvider) => {
3493
+ const connectionFactory = getRtcConnectionFactory();
3494
+ return {
3495
+ createTransport: (options) => {
3496
+ const connection = new RtcPeerConnection(connectionFactory, {
3497
+ ownPeerKey: options.ownPeerKey,
3498
+ remotePeerKey: options.remotePeerKey,
3499
+ sendSignal: options.sendSignal,
3500
+ webrtcConfig,
3501
+ iceProvider
3502
+ });
3503
+ return connection.createTransportChannel(options);
3504
+ }
3505
+ };
3506
+ };
3414
3507
 
3415
- // packages/core/mesh/network-manager/src/transport/simplepeer-transport-proxy.ts
3508
+ // packages/core/mesh/network-manager/src/transport/webrtc/rtc-transport-proxy.ts
3416
3509
  import { Writable } from "@dxos/node-std/stream";
3417
- import { Event as Event9, scheduleTask as scheduleTask4 } from "@dxos/async";
3418
- import { Context as Context6 } from "@dxos/context";
3510
+ import { Event as Event8, scheduleTask as scheduleTask4 } from "@dxos/async";
3511
+ import { Resource as Resource2 } from "@dxos/context";
3419
3512
  import { ErrorStream as ErrorStream5 } from "@dxos/debug";
3420
- import { invariant as invariant13 } from "@dxos/invariant";
3421
- import { PublicKey as PublicKey12 } from "@dxos/keys";
3422
- import { log as log14 } from "@dxos/log";
3423
- import { ConnectionResetError as ConnectionResetError3, TimeoutError as TimeoutError3, ProtocolError as ProtocolError3, ConnectivityError as ConnectivityError3, UnknownProtocolError as UnknownProtocolError3 } from "@dxos/protocols";
3424
- import { ConnectionState as ConnectionState4 } from "@dxos/protocols/proto/dxos/mesh/bridge";
3513
+ import { invariant as invariant11 } from "@dxos/invariant";
3514
+ import { PublicKey as PublicKey10 } from "@dxos/keys";
3515
+ import { log as log11 } from "@dxos/log";
3516
+ import { ConnectionResetError as ConnectionResetError2, ConnectivityError as ConnectivityError4, TimeoutError as TimeoutError3 } from "@dxos/protocols";
3517
+ import { ConnectionState as ConnectionState3 } from "@dxos/protocols/proto/dxos/mesh/bridge";
3425
3518
  import { arrayToBuffer } from "@dxos/util";
3426
- var __dxlog_file15 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/transport/simplepeer-transport-proxy.ts";
3519
+ var __dxlog_file12 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/transport/webrtc/rtc-transport-proxy.ts";
3427
3520
  var RPC_TIMEOUT = 1e4;
3521
+ var CLOSE_RPC_TIMEOUT = 3e3;
3428
3522
  var RESP_MIN_THRESHOLD = 500;
3429
- var TIMEOUT_THRESHOLD = 10;
3430
- var SimplePeerTransportProxy = class {
3523
+ var RtcTransportProxy = class extends Resource2 {
3431
3524
  constructor(_options) {
3525
+ super();
3432
3526
  this._options = _options;
3433
- this._proxyId = PublicKey12.random();
3434
- this._ctx = new Context6(void 0, {
3435
- F: __dxlog_file15,
3436
- L: 37
3437
- });
3438
- this._timeoutCount = 0;
3439
- this.closed = new Event9();
3440
- this.connected = new Event9();
3527
+ this._proxyId = PublicKey10.random();
3528
+ this.closed = new Event8();
3529
+ this.connected = new Event8();
3441
3530
  this.errors = new ErrorStream5();
3442
- this._closed = false;
3443
- }
3444
- get isOpen() {
3445
- return !this._closed;
3446
3531
  }
3447
- async open() {
3448
- this._serviceStream = this._options.bridgeService.open({
3449
- proxyId: this._proxyId,
3450
- initiator: this._options.initiator
3451
- }, {
3452
- timeout: RPC_TIMEOUT
3453
- });
3454
- this._serviceStream.waitUntilReady().then(() => {
3455
- this._serviceStream.subscribe(async (event) => {
3456
- log14("SimplePeerTransportProxy: event", event, {
3457
- F: __dxlog_file15,
3532
+ async _open() {
3533
+ let stream;
3534
+ try {
3535
+ stream = this._options.bridgeService.open({
3536
+ proxyId: this._proxyId,
3537
+ remotePeerKey: this._options.remotePeerKey,
3538
+ ownPeerKey: this._options.ownPeerKey,
3539
+ topic: this._options.topic,
3540
+ initiator: this._options.initiator ?? false
3541
+ }, {
3542
+ timeout: RPC_TIMEOUT
3543
+ });
3544
+ } catch (error) {
3545
+ this.errors.raise(error);
3546
+ return;
3547
+ }
3548
+ this._serviceStream = stream;
3549
+ stream.waitUntilReady().then(() => {
3550
+ stream.subscribe(async (event) => {
3551
+ log11("rtc transport proxy event", event, {
3552
+ F: __dxlog_file12,
3458
3553
  L: 66,
3459
3554
  S: this,
3460
3555
  C: (f, a) => f(...a)
@@ -3466,20 +3561,34 @@ var SimplePeerTransportProxy = class {
3466
3561
  } else if (event.signal) {
3467
3562
  await this._handleSignal(event.signal);
3468
3563
  }
3564
+ }, (err) => {
3565
+ log11("rtc bridge stream closed", {
3566
+ err
3567
+ }, {
3568
+ F: __dxlog_file12,
3569
+ L: 76,
3570
+ S: this,
3571
+ C: (f, a) => f(...a)
3572
+ });
3573
+ if (err) {
3574
+ this._raiseIfOpen(err);
3575
+ } else {
3576
+ void this.close();
3577
+ }
3469
3578
  });
3470
- const proxyStream = new Writable({
3579
+ const connectorStream = new Writable({
3471
3580
  write: (chunk, _, callback) => {
3472
- const then = performance.now();
3581
+ const sendStartMs = Date.now();
3473
3582
  this._options.bridgeService.sendData({
3474
3583
  proxyId: this._proxyId,
3475
3584
  payload: chunk
3476
3585
  }, {
3477
3586
  timeout: RPC_TIMEOUT
3478
3587
  }).then(() => {
3479
- if (performance.now() - then > RESP_MIN_THRESHOLD) {
3480
- log14("slow response, delaying callback", void 0, {
3481
- F: __dxlog_file15,
3482
- L: 90,
3588
+ if (Date.now() - sendStartMs > RESP_MIN_THRESHOLD) {
3589
+ log11("slow response, delaying callback", void 0, {
3590
+ F: __dxlog_file12,
3591
+ L: 93,
3483
3592
  S: this,
3484
3593
  C: (f, a) => f(...a)
3485
3594
  });
@@ -3487,71 +3596,51 @@ var SimplePeerTransportProxy = class {
3487
3596
  } else {
3488
3597
  callback();
3489
3598
  }
3490
- this._timeoutCount = 0;
3491
3599
  }, (err) => {
3492
- if (err instanceof TimeoutError3 || err.constructor.name === "TimeoutError") {
3493
- if (this._timeoutCount++ > TIMEOUT_THRESHOLD) {
3494
- throw new TimeoutError3(`too many timeouts (${this._timeoutCount} > ${TIMEOUT_THRESHOLD}`);
3495
- } else {
3496
- log14("timeout error, but still invoking callback", void 0, {
3497
- F: __dxlog_file15,
3498
- L: 102,
3499
- S: this,
3500
- C: (f, a) => f(...a)
3501
- });
3502
- callback();
3503
- }
3504
- } else {
3505
- log14.catch(err, void 0, {
3506
- F: __dxlog_file15,
3507
- L: 106,
3508
- S: this,
3509
- C: (f, a) => f(...a)
3510
- });
3511
- }
3600
+ callback();
3601
+ this._raiseIfOpen(err);
3512
3602
  });
3513
3603
  }
3514
3604
  });
3515
- proxyStream.on("error", (err) => {
3516
- log14("proxystream error", {
3517
- err
3518
- }, {
3519
- F: __dxlog_file15,
3520
- L: 114,
3521
- S: this,
3522
- C: (f, a) => f(...a)
3523
- });
3605
+ connectorStream.on("error", (err) => {
3606
+ this._raiseIfOpen(err);
3524
3607
  });
3525
- this._options.stream.pipe(proxyStream);
3526
- }, (error) => log14.catch(error, void 0, {
3527
- F: __dxlog_file15,
3528
- L: 119,
3529
- S: this,
3530
- C: (f, a) => f(...a)
3531
- }));
3608
+ this._options.stream.pipe(connectorStream);
3609
+ }, (error) => {
3610
+ if (error) {
3611
+ this._raiseIfOpen(error);
3612
+ } else {
3613
+ void this.close();
3614
+ }
3615
+ });
3532
3616
  }
3533
- async close() {
3534
- await this._ctx.dispose();
3535
- if (this._closed) {
3536
- return;
3617
+ async _close() {
3618
+ try {
3619
+ await this._serviceStream?.close();
3620
+ this._serviceStream = void 0;
3621
+ } catch (err) {
3622
+ log11.catch(err, void 0, {
3623
+ F: __dxlog_file12,
3624
+ L: 128,
3625
+ S: this,
3626
+ C: (f, a) => f(...a)
3627
+ });
3537
3628
  }
3538
- await this._serviceStream.close();
3539
3629
  try {
3540
3630
  await this._options.bridgeService.close({
3541
3631
  proxyId: this._proxyId
3542
3632
  }, {
3543
- timeout: RPC_TIMEOUT
3633
+ timeout: CLOSE_RPC_TIMEOUT
3544
3634
  });
3545
3635
  } catch (err) {
3546
- log14.catch(err, void 0, {
3547
- F: __dxlog_file15,
3636
+ log11.catch(err, void 0, {
3637
+ F: __dxlog_file12,
3548
3638
  L: 134,
3549
3639
  S: this,
3550
3640
  C: (f, a) => f(...a)
3551
3641
  });
3552
3642
  }
3553
3643
  this.closed.emit();
3554
- this._closed = true;
3555
3644
  }
3556
3645
  async onSignal(signal) {
3557
3646
  this._options.bridgeService.sendSignal({
@@ -3559,581 +3648,347 @@ var SimplePeerTransportProxy = class {
3559
3648
  signal
3560
3649
  }, {
3561
3650
  timeout: RPC_TIMEOUT
3562
- }).catch((err) => this.errors.raise(decodeError(err)));
3651
+ }).catch((err) => this._raiseIfOpen(decodeError(err)));
3563
3652
  }
3564
3653
  async _handleConnection(connectionEvent) {
3565
3654
  if (connectionEvent.error) {
3566
3655
  this.errors.raise(decodeError(connectionEvent.error));
3656
+ return;
3567
3657
  }
3568
3658
  switch (connectionEvent.state) {
3569
- case ConnectionState4.CONNECTED: {
3659
+ case ConnectionState3.CONNECTED: {
3570
3660
  this.connected.emit();
3571
3661
  break;
3572
3662
  }
3573
- case ConnectionState4.CLOSED: {
3663
+ case ConnectionState3.CLOSED: {
3574
3664
  await this.close();
3575
3665
  break;
3576
3666
  }
3577
3667
  }
3578
3668
  }
3579
3669
  _handleData(dataEvent) {
3580
- this._options.stream.write(arrayToBuffer(dataEvent.payload));
3581
- }
3582
- async _handleSignal(signalEvent) {
3583
- await this._options.sendSignal(signalEvent.payload);
3584
- }
3585
- async getDetails() {
3586
- return (await this._options.bridgeService.getDetails({
3587
- proxyId: this._proxyId
3588
- }, {
3589
- timeout: RPC_TIMEOUT
3590
- })).details;
3591
- }
3592
- async getStats() {
3593
- return (await this._options.bridgeService.getStats({
3594
- proxyId: this._proxyId
3595
- }, {
3596
- timeout: RPC_TIMEOUT
3597
- })).stats;
3598
- }
3599
- /**
3600
- * Called when underlying proxy service becomes unavailable.
3601
- */
3602
- // TODO(burdon): Option on close method.
3603
- forceClose() {
3604
- void this._serviceStream.close();
3605
- this.closed.emit();
3606
- this._closed = true;
3607
- }
3608
- };
3609
- var SimplePeerTransportProxyFactory = class {
3610
- constructor() {
3611
- this._connections = /* @__PURE__ */ new Set();
3612
- }
3613
- /**
3614
- * Sets the current BridgeService to be used to open connections.
3615
- * Calling this method will close any existing connections.
3616
- */
3617
- setBridgeService(bridgeService) {
3618
- this._bridgeService = bridgeService;
3619
- for (const connection of this._connections) {
3620
- connection.forceClose();
3670
+ try {
3671
+ this._options.stream.write(arrayToBuffer(dataEvent.payload));
3672
+ } catch (error) {
3673
+ this._raiseIfOpen(error);
3621
3674
  }
3622
- return this;
3623
- }
3624
- createTransport(options) {
3625
- invariant13(this._bridgeService, "SimplePeerTransportProxyFactory is not ready to open connections", {
3626
- F: __dxlog_file15,
3627
- L: 218,
3628
- S: this,
3629
- A: [
3630
- "this._bridgeService",
3631
- "'SimplePeerTransportProxyFactory is not ready to open connections'"
3632
- ]
3633
- });
3634
- const transport = new SimplePeerTransportProxy({
3635
- ...options,
3636
- bridgeService: this._bridgeService
3637
- });
3638
- this._connections.add(transport);
3639
- transport.closed.on(() => this._connections.delete(transport));
3640
- return transport;
3641
- }
3642
- };
3643
- var decodeError = (err) => {
3644
- const message = typeof err === "string" ? err : err.message;
3645
- if (message.includes("CONNECTION_RESET")) {
3646
- return new ConnectionResetError3(message);
3647
- } else if (message.includes("TIMEOUT")) {
3648
- return new TimeoutError3(message);
3649
- } else if (message.includes("PROTOCOL_ERROR")) {
3650
- return new ProtocolError3(message);
3651
- } else if (message.includes("CONNECTIVITY_ERROR")) {
3652
- return new ConnectivityError3(message);
3653
- } else if (message.includes("UNKNOWN_PROTOCOL_ERROR")) {
3654
- return new UnknownProtocolError3(message);
3655
- } else {
3656
- return typeof err === "string" ? new Error(err) : err;
3657
- }
3658
- };
3659
-
3660
- // packages/core/mesh/network-manager/src/transport/libdatachannel-transport.ts
3661
- import { Duplex as Duplex2 } from "stream";
3662
- import { Event as Event10, Trigger as Trigger3, synchronized as synchronized6 } from "@dxos/async";
3663
- import { ErrorStream as ErrorStream6 } from "@dxos/debug";
3664
- import { invariant as invariant14 } from "@dxos/invariant";
3665
- import { log as log15 } from "@dxos/log";
3666
- function _ts_decorate7(decorators, target, key, desc) {
3667
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3668
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
3669
- 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;
3670
- return c > 3 && r && Object.defineProperty(target, key, r), r;
3671
- }
3672
- var __dxlog_file16 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/transport/libdatachannel-transport.ts";
3673
- var DATACHANNEL_LABEL = "dxos.mesh.transport";
3674
- var MAX_BUFFERED_AMOUNT = 64 * 1024;
3675
- var MAX_MESSAGE_SIZE = 64 * 1024;
3676
- var createLibDataChannelTransportFactory = (webrtcConfig, iceProvider) => {
3677
- return {
3678
- createTransport: (options) => new LibDataChannelTransport({
3679
- ...options,
3680
- webrtcConfig,
3681
- iceProvider
3682
- })
3683
- };
3684
- };
3685
- var LibDataChannelTransport = class _LibDataChannelTransport {
3686
- static {
3687
- this._instanceCount = 0;
3688
3675
  }
3689
- constructor(_options) {
3690
- this._options = _options;
3691
- this._closed = false;
3692
- this._connected = false;
3693
- this._writeCallback = null;
3694
- this._readyForCandidates = new Trigger3();
3695
- this.closed = new Event10();
3696
- this.connected = new Event10();
3697
- this.errors = new ErrorStream6();
3698
- }
3699
- get isOpen() {
3700
- return !!this._peer && !this._closed;
3701
- }
3702
- async open() {
3703
- if (this._closed) {
3704
- this.errors.raise(new Error("connection already closed"));
3705
- }
3706
- const { RTCPeerConnection } = (await importESM("node-datachannel/polyfill")).default;
3707
- const providedIceServers = await this._options.iceProvider?.getIceServers();
3708
- if (!this._options.webrtcConfig) {
3709
- this._options.webrtcConfig = {};
3710
- }
3711
- this._options.webrtcConfig.iceServers = [
3712
- ...this._options.webrtcConfig.iceServers ?? [],
3713
- ...providedIceServers ?? []
3714
- ];
3715
- this._peer = new RTCPeerConnection(this._options.webrtcConfig);
3716
- this._peer.onicecandidateerror = (event) => {
3717
- log15.error("peer.onicecandidateerror", {
3718
- event
3719
- }, {
3720
- F: __dxlog_file16,
3721
- L: 93,
3722
- S: this,
3723
- C: (f, a) => f(...a)
3724
- });
3725
- };
3726
- this._peer.onconnectionstatechange = (event) => {
3727
- log15.debug("peer.onconnectionstatechange", {
3728
- event,
3729
- peerConnectionState: this._peer?.connectionState,
3730
- transportConnectionState: this._connected
3731
- }, {
3732
- F: __dxlog_file16,
3733
- L: 97,
3734
- S: this,
3735
- C: (f, a) => f(...a)
3736
- });
3737
- };
3738
- this._peer.onicecandidate = async (event) => {
3739
- log15.debug("peer.onicecandidate", {
3740
- event
3741
- }, {
3742
- F: __dxlog_file16,
3743
- L: 107,
3744
- S: this,
3745
- C: (f, a) => f(...a)
3746
- });
3747
- if (event.candidate) {
3748
- try {
3749
- await this._options.sendSignal({
3750
- payload: {
3751
- data: {
3752
- type: "candidate",
3753
- candidate: {
3754
- candidate: event.candidate.candidate,
3755
- // These fields never seem to be not null, but connecting to Chrome doesn't work if they are.
3756
- sdpMLineIndex: event.candidate.sdpMLineIndex ?? 0,
3757
- sdpMid: event.candidate.sdpMid ?? 0
3758
- }
3759
- }
3760
- }
3761
- });
3762
- } catch (err) {
3763
- log15.info("signaling error", {
3764
- err
3765
- }, {
3766
- F: __dxlog_file16,
3767
- L: 124,
3768
- S: this,
3769
- C: (f, a) => f(...a)
3770
- });
3771
- }
3676
+ async _handleSignal(signalEvent) {
3677
+ try {
3678
+ await this._options.sendSignal(signalEvent.payload);
3679
+ } catch (error) {
3680
+ const type = signalEvent.payload.payload.data?.type;
3681
+ if (type === "offer" || type === "answer") {
3682
+ this._raiseIfOpen(new ConnectivityError4(`Session establishment failed: ${type} couldn't be sent.`));
3772
3683
  }
3773
- };
3774
- if (this._options.initiator) {
3775
- invariant14(this._peer, "not open", {
3776
- F: __dxlog_file16,
3777
- L: 130,
3778
- S: this,
3779
- A: [
3780
- "this._peer",
3781
- "'not open'"
3782
- ]
3783
- });
3784
- this._peer.createOffer().then(async (offer) => {
3785
- if (this._closed) {
3786
- return;
3787
- }
3788
- if (this._peer?.connectionState !== "connecting") {
3789
- log15.error("peer not connecting", {
3790
- peer: this._peer
3791
- }, {
3792
- F: __dxlog_file16,
3793
- L: 141,
3794
- S: this,
3795
- C: (f, a) => f(...a)
3796
- });
3797
- this.errors.raise(new Error("invalid state: peer is initiator, but other peer not in state connecting"));
3798
- }
3799
- log15.debug("creating offer", {
3800
- peer: this._peer,
3801
- offer
3802
- }, {
3803
- F: __dxlog_file16,
3804
- L: 145,
3805
- S: this,
3806
- C: (f, a) => f(...a)
3807
- });
3808
- await this._peer.setLocalDescription(offer);
3809
- await this._options.sendSignal({
3810
- payload: {
3811
- data: {
3812
- type: offer.type,
3813
- sdp: offer.sdp
3814
- }
3815
- }
3816
- });
3817
- }).catch((err) => {
3818
- this.errors.raise(err);
3819
- });
3820
- this._handleChannel(this._peer.createDataChannel(DATACHANNEL_LABEL));
3821
- log15.debug("created data channel", void 0, {
3822
- F: __dxlog_file16,
3823
- L: 155,
3824
- S: this,
3825
- C: (f, a) => f(...a)
3826
- });
3827
- this._peer.ondatachannel = () => {
3828
- this.errors.raise(new Error("unexpected ondatachannel event for initiator"));
3829
- };
3830
- } else {
3831
- this._peer.ondatachannel = (event) => {
3832
- log15.debug("peer.ondatachannel (non-initiator)", {
3833
- event
3834
- }, {
3835
- F: __dxlog_file16,
3836
- L: 161,
3837
- S: this,
3838
- C: (f, a) => f(...a)
3839
- });
3840
- if (event.channel.label !== DATACHANNEL_LABEL) {
3841
- this.errors.raise(new Error(`unexpected channel label ${event.channel.label}`));
3842
- }
3843
- this._handleChannel(event.channel);
3844
- };
3845
3684
  }
3846
- _LibDataChannelTransport._instanceCount++;
3847
3685
  }
3848
- async close() {
3849
- await this._close();
3850
- if (--_LibDataChannelTransport._instanceCount === 0) {
3851
- (await importESM("node-datachannel")).cleanup();
3686
+ async getDetails() {
3687
+ try {
3688
+ const response = await this._options.bridgeService.getDetails({
3689
+ proxyId: this._proxyId
3690
+ }, {
3691
+ timeout: RPC_TIMEOUT
3692
+ });
3693
+ return response.details;
3694
+ } catch (err) {
3695
+ return "bridge-svc unreachable";
3852
3696
  }
3853
3697
  }
3854
- async _close() {
3855
- if (this._closed) {
3856
- return;
3857
- }
3858
- await this._disconnectStreams();
3698
+ async getStats() {
3859
3699
  try {
3860
- this._peer?.close();
3700
+ const response = await this._options.bridgeService.getStats({
3701
+ proxyId: this._proxyId
3702
+ }, {
3703
+ timeout: RPC_TIMEOUT
3704
+ });
3705
+ return response.stats;
3861
3706
  } catch (err) {
3862
- this.errors.raise(err);
3707
+ return {
3708
+ bytesSent: 0,
3709
+ bytesReceived: 0,
3710
+ packetsSent: 0,
3711
+ packetsReceived: 0,
3712
+ rawStats: "bridge-svc unreachable"
3713
+ };
3863
3714
  }
3864
- this._peer = void 0;
3865
- this._closed = true;
3715
+ }
3716
+ _raiseIfOpen(error) {
3717
+ if (this.isOpen) {
3718
+ this.errors.raise(error);
3719
+ } else {
3720
+ log11.info("error swallowed because transport was closed", {
3721
+ message: error.message
3722
+ }, {
3723
+ F: __dxlog_file12,
3724
+ L: 215,
3725
+ S: this,
3726
+ C: (f, a) => f(...a)
3727
+ });
3728
+ }
3729
+ }
3730
+ /**
3731
+ * Called when underlying proxy service becomes unavailable.
3732
+ */
3733
+ forceClose() {
3734
+ void this._serviceStream?.close();
3866
3735
  this.closed.emit();
3867
3736
  }
3737
+ };
3738
+ var RtcTransportProxyFactory = class {
3739
+ constructor() {
3740
+ this._connections = /* @__PURE__ */ new Set();
3741
+ }
3868
3742
  /**
3869
- * Handle data channel events.
3743
+ * Sets the current BridgeService to be used to open connections.
3744
+ * Calling this method will close any existing connections.
3870
3745
  */
3871
- _handleChannel(dataChannel) {
3872
- this._channel = dataChannel;
3873
- this._channel.onopen = () => {
3874
- log15.debug("channel.onopen", void 0, {
3875
- F: __dxlog_file16,
3876
- L: 206,
3746
+ setBridgeService(bridgeService) {
3747
+ this._bridgeService = bridgeService;
3748
+ for (const connection of this._connections) {
3749
+ connection.forceClose();
3750
+ }
3751
+ return this;
3752
+ }
3753
+ createTransport(options) {
3754
+ invariant11(this._bridgeService, "RtcTransportProxyFactory is not ready to open connections", {
3755
+ F: __dxlog_file12,
3756
+ L: 245,
3757
+ S: this,
3758
+ A: [
3759
+ "this._bridgeService",
3760
+ "'RtcTransportProxyFactory is not ready to open connections'"
3761
+ ]
3762
+ });
3763
+ const transport = new RtcTransportProxy({
3764
+ ...options,
3765
+ bridgeService: this._bridgeService
3766
+ });
3767
+ this._connections.add(transport);
3768
+ transport.closed.on(() => this._connections.delete(transport));
3769
+ return transport;
3770
+ }
3771
+ };
3772
+ var decodeError = (err) => {
3773
+ const message = typeof err === "string" ? err : err.message;
3774
+ if (message.includes("CONNECTION_RESET")) {
3775
+ return new ConnectionResetError2(message);
3776
+ } else if (message.includes("TIMEOUT")) {
3777
+ return new TimeoutError3(message);
3778
+ } else if (message.includes("CONNECTIVITY_ERROR")) {
3779
+ return new ConnectivityError4(message);
3780
+ } else {
3781
+ return typeof err === "string" ? new Error(err) : err;
3782
+ }
3783
+ };
3784
+
3785
+ // packages/core/mesh/network-manager/src/transport/webrtc/rtc-transport-service.ts
3786
+ import { Duplex as Duplex2 } from "@dxos/node-std/stream";
3787
+ import { Stream } from "@dxos/codec-protobuf";
3788
+ import { invariant as invariant12 } from "@dxos/invariant";
3789
+ import { PublicKey as PublicKey11 } from "@dxos/keys";
3790
+ import { log as log12 } from "@dxos/log";
3791
+ import { ConnectionState as ConnectionState4 } from "@dxos/protocols/proto/dxos/mesh/bridge";
3792
+ import { ComplexMap as ComplexMap8 } from "@dxos/util";
3793
+ var __dxlog_file13 = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/transport/webrtc/rtc-transport-service.ts";
3794
+ var RtcTransportService = class {
3795
+ constructor(webrtcConfig, iceProvider, _transportFactory = createRtcTransportFactory(webrtcConfig, iceProvider)) {
3796
+ this._transportFactory = _transportFactory;
3797
+ this._openTransports = new ComplexMap8(PublicKey11.hash);
3798
+ }
3799
+ hasOpenTransports() {
3800
+ return this._openTransports.size > 0;
3801
+ }
3802
+ open(request) {
3803
+ const existingTransport = this._openTransports.get(request.proxyId);
3804
+ if (existingTransport) {
3805
+ log12.error("requesting a new transport bridge for an existing proxy", void 0, {
3806
+ F: __dxlog_file13,
3807
+ L: 53,
3877
3808
  S: this,
3878
3809
  C: (f, a) => f(...a)
3879
3810
  });
3880
- const duplex = new Duplex2({
3811
+ void this._safeCloseTransport(existingTransport);
3812
+ this._openTransports.delete(request.proxyId);
3813
+ }
3814
+ return new Stream(({ ready, next, close }) => {
3815
+ const pushNewState = createStateUpdater(next);
3816
+ const transportStream = new Duplex2({
3881
3817
  read: () => {
3818
+ const callbacks = [
3819
+ ...transportState.writeProcessedCallbacks
3820
+ ];
3821
+ transportState.writeProcessedCallbacks.length = 0;
3822
+ callbacks.forEach((cb) => cb());
3882
3823
  },
3883
- write: async (chunk, encoding, callback) => {
3884
- if (chunk.length > MAX_MESSAGE_SIZE) {
3885
- this.errors.raise(new Error(`message too large: ${chunk.length} > ${MAX_MESSAGE_SIZE}`));
3886
- }
3887
- try {
3888
- dataChannel.send(chunk);
3889
- } catch (err) {
3890
- this.errors.raise(err);
3891
- await this._close();
3892
- }
3893
- if (this._channel.bufferedAmount > MAX_BUFFERED_AMOUNT) {
3894
- if (this._writeCallback !== null) {
3895
- log15.error("consumer trying to write before we are ready for more data", void 0, {
3896
- F: __dxlog_file16,
3897
- L: 223,
3898
- S: this,
3899
- C: (f, a) => f(...a)
3900
- });
3824
+ write: function(chunk, _, callback) {
3825
+ next({
3826
+ data: {
3827
+ payload: chunk
3901
3828
  }
3902
- this._writeCallback = callback;
3903
- } else {
3904
- callback();
3905
- }
3829
+ });
3830
+ callback();
3906
3831
  }
3907
3832
  });
3908
- duplex.pipe(this._options.stream).pipe(duplex);
3909
- this._stream = duplex;
3910
- this._connected = true;
3911
- this.connected.emit();
3912
- };
3913
- this._channel.onclose = async (err) => {
3914
- log15.info("channel.onclose", {
3915
- err
3916
- }, {
3917
- F: __dxlog_file16,
3918
- L: 239,
3919
- S: this,
3920
- C: (f, a) => f(...a)
3833
+ const transport = this._transportFactory.createTransport({
3834
+ initiator: request.initiator,
3835
+ topic: request.topic,
3836
+ ownPeerKey: request.ownPeerKey,
3837
+ remotePeerKey: request.remotePeerKey,
3838
+ stream: transportStream,
3839
+ sendSignal: async (signal) => {
3840
+ next({
3841
+ signal: {
3842
+ payload: signal
3843
+ }
3844
+ });
3845
+ }
3921
3846
  });
3922
- await this._close();
3923
- };
3924
- this._channel.onerror = async (err) => {
3925
- this.errors.raise(new Error("channel error: " + err.toString()));
3926
- await this._close();
3927
- };
3928
- this._channel.onbufferedamountlow = () => {
3929
- const cb = this._writeCallback;
3930
- this._writeCallback = null;
3931
- cb?.();
3932
- };
3933
- this._channel.onmessage = (event) => {
3934
- let data = event.data;
3935
- if (data instanceof ArrayBuffer) {
3936
- data = Buffer2.from(data);
3937
- }
3938
- this._stream.push(data);
3939
- };
3847
+ const transportState = {
3848
+ proxyId: request.proxyId,
3849
+ transport,
3850
+ connectorStream: transportStream,
3851
+ writeProcessedCallbacks: []
3852
+ };
3853
+ pushNewState(ConnectionState4.CONNECTING);
3854
+ transport.connected.on(() => pushNewState(ConnectionState4.CONNECTED));
3855
+ transport.errors.handle(async (err) => {
3856
+ pushNewState(ConnectionState4.CLOSED, err);
3857
+ void this._safeCloseTransport(transportState);
3858
+ close(err);
3859
+ });
3860
+ transport.closed.on(async () => {
3861
+ pushNewState(ConnectionState4.CLOSED);
3862
+ void this._safeCloseTransport(transportState);
3863
+ close();
3864
+ });
3865
+ this._openTransports.set(request.proxyId, transportState);
3866
+ transport.open().catch(async (err) => {
3867
+ pushNewState(ConnectionState4.CLOSED, err);
3868
+ void this._safeCloseTransport(transportState);
3869
+ close(err);
3870
+ });
3871
+ ready();
3872
+ });
3940
3873
  }
3941
- async onSignal(signal) {
3942
- invariant14(this._peer, "not open", {
3943
- F: __dxlog_file16,
3944
- L: 265,
3874
+ async sendSignal({ proxyId, signal }) {
3875
+ const transport = this._openTransports.get(proxyId);
3876
+ invariant12(transport, void 0, {
3877
+ F: __dxlog_file13,
3878
+ L: 121,
3945
3879
  S: this,
3946
3880
  A: [
3947
- "this._peer",
3948
- "'not open'"
3881
+ "transport",
3882
+ ""
3949
3883
  ]
3950
3884
  });
3951
- try {
3952
- const data = signal.payload.data;
3953
- switch (data.type) {
3954
- case "offer": {
3955
- if (this._peer.connectionState !== "new") {
3956
- log15.error("received offer but peer not in state new", {
3957
- peer: this._peer
3958
- }, {
3959
- F: __dxlog_file16,
3960
- L: 272,
3961
- S: this,
3962
- C: (f, a) => f(...a)
3963
- });
3964
- this.errors.raise(new Error("invalid signalling state: received offer when peer is not in state new"));
3965
- break;
3966
- }
3967
- try {
3968
- await this._peer.setRemoteDescription({
3969
- type: data.type,
3970
- sdp: data.sdp
3971
- });
3972
- const answer = await this._peer.createAnswer();
3973
- await this._peer.setLocalDescription(answer);
3974
- await this._options.sendSignal({
3975
- payload: {
3976
- data: {
3977
- type: answer.type,
3978
- sdp: answer.sdp
3979
- }
3980
- }
3981
- });
3982
- this._readyForCandidates.wake();
3983
- } catch (err) {
3984
- log15.error("cannot handle offer from signalling server", {
3985
- err
3986
- }, {
3987
- F: __dxlog_file16,
3988
- L: 284,
3989
- S: this,
3990
- C: (f, a) => f(...a)
3991
- });
3992
- this.errors.raise(new Error("error handling offer"));
3993
- }
3994
- break;
3995
- }
3996
- case "answer":
3997
- try {
3998
- await this._peer.setRemoteDescription({
3999
- type: data.type,
4000
- sdp: data.sdp
4001
- });
4002
- this._readyForCandidates.wake();
4003
- } catch (err) {
4004
- log15.error("cannot handle answer from signalling server", {
4005
- err
4006
- }, {
4007
- F: __dxlog_file16,
4008
- L: 295,
4009
- S: this,
4010
- C: (f, a) => f(...a)
4011
- });
4012
- this.errors.raise(new Error("error handling answer"));
4013
- }
4014
- break;
4015
- case "candidate":
4016
- await this._readyForCandidates.wait();
4017
- await this._peer.addIceCandidate({
4018
- candidate: data.candidate.candidate
4019
- });
4020
- break;
4021
- default:
4022
- log15.error("unhandled signal type", {
4023
- type: data.type,
4024
- signal
4025
- }, {
4026
- F: __dxlog_file16,
4027
- L: 306,
4028
- S: this,
4029
- C: (f, a) => f(...a)
4030
- });
4031
- this.errors.raise(new Error(`unhandled signal type ${data.type}`));
4032
- }
4033
- } catch (err) {
4034
- log15.catch(err, void 0, {
4035
- F: __dxlog_file16,
4036
- L: 310,
4037
- S: this,
4038
- C: (f, a) => f(...a)
4039
- });
4040
- }
3885
+ await transport.transport.onSignal(signal);
4041
3886
  }
4042
- async getDetails() {
4043
- const stats = await this._getStats();
4044
- const rc = stats?.remoteCandidate;
4045
- if (!rc) {
4046
- return "unavailable";
4047
- }
4048
- if (rc.candidateType === "relay") {
4049
- return `${rc.ip}:${rc.port} relay for ${rc.relatedAddress}:${rc.relatedPort}`;
4050
- }
4051
- return `${rc.ip}:${rc.port} ${rc.candidateType}`;
4052
- }
4053
- async getStats() {
4054
- const stats = await this._getStats();
4055
- if (!stats) {
4056
- return {
4057
- bytesSent: 0,
4058
- bytesReceived: 0,
4059
- packetsSent: 0,
4060
- packetsReceived: 0,
4061
- rawStats: {}
4062
- };
4063
- }
3887
+ async getDetails({ proxyId }) {
3888
+ const transport = this._openTransports.get(proxyId);
3889
+ invariant12(transport, void 0, {
3890
+ F: __dxlog_file13,
3891
+ L: 128,
3892
+ S: this,
3893
+ A: [
3894
+ "transport",
3895
+ ""
3896
+ ]
3897
+ });
4064
3898
  return {
4065
- bytesSent: stats.transport.bytesSent,
4066
- bytesReceived: stats.transport.bytesReceived,
4067
- packetsSent: 0,
4068
- packetsReceived: 0,
4069
- rawStats: stats.raw
3899
+ details: await transport.transport.getDetails()
4070
3900
  };
4071
3901
  }
4072
- async _getStats() {
4073
- invariant14(this._peer, "not open", {
4074
- F: __dxlog_file16,
4075
- L: 350,
3902
+ async getStats({ proxyId }) {
3903
+ const transport = this._openTransports.get(proxyId);
3904
+ invariant12(transport, void 0, {
3905
+ F: __dxlog_file13,
3906
+ L: 135,
4076
3907
  S: this,
4077
3908
  A: [
4078
- "this._peer",
4079
- "'not open'"
3909
+ "transport",
3910
+ ""
4080
3911
  ]
4081
3912
  });
4082
- const stats = await this._peer.getStats();
4083
- const statsEntries = Array.from(stats.entries());
4084
- const transport = statsEntries.filter((s) => s[1].type === "transport")[0][1];
4085
- const candidatePair = statsEntries.filter((s) => s[0] === transport.selectedCandidatePairId);
4086
- let selectedCandidatePair;
4087
- let remoteCandidate;
4088
- if (candidatePair.length > 0) {
4089
- selectedCandidatePair = candidatePair[0][1];
4090
- remoteCandidate = statsEntries.filter((s) => s[0] === selectedCandidatePair.remoteCandidateId)[0][1];
4091
- }
4092
3913
  return {
4093
- transport,
4094
- selectedCandidatePair,
4095
- remoteCandidate,
4096
- raw: Object.fromEntries(stats)
3914
+ stats: await transport.transport.getStats()
4097
3915
  };
4098
3916
  }
4099
- async _disconnectStreams() {
4100
- this._options.stream.unpipe?.(this._stream)?.unpipe?.(this._options.stream);
4101
- }
4102
- };
4103
- _ts_decorate7([
4104
- synchronized6
4105
- ], LibDataChannelTransport.prototype, "_close", null);
4106
- var importESM = Function("path", "return import(path)");
4107
-
4108
- // packages/core/mesh/network-manager/src/transport/tcp-transport.browser.ts
4109
- import { Event as Event11 } from "@dxos/async";
4110
- import { ErrorStream as ErrorStream7 } from "@dxos/debug";
4111
- var TcpTransportFactory = {
4112
- createTransport: () => new TcpTransport()
4113
- };
4114
- var TcpTransport = class {
4115
- constructor() {
4116
- this.closed = new Event11();
4117
- this.connected = new Event11();
4118
- this.errors = new ErrorStream7();
4119
- }
4120
- get isOpen() {
4121
- return true;
4122
- }
4123
- async open() {
4124
- }
4125
- async close() {
4126
- }
4127
- async onSignal() {
4128
- throw new Error("Method not implemented.");
3917
+ async sendData({ proxyId, payload }) {
3918
+ const transport = this._openTransports.get(proxyId);
3919
+ invariant12(transport, void 0, {
3920
+ F: __dxlog_file13,
3921
+ L: 142,
3922
+ S: this,
3923
+ A: [
3924
+ "transport",
3925
+ ""
3926
+ ]
3927
+ });
3928
+ const bufferHasSpace = transport.connectorStream.push(payload);
3929
+ if (!bufferHasSpace) {
3930
+ await new Promise((resolve) => {
3931
+ transport.writeProcessedCallbacks.push(resolve);
3932
+ });
3933
+ }
4129
3934
  }
4130
- async getStats() {
4131
- throw new Error("Method not implemented.");
3935
+ async close({ proxyId }) {
3936
+ const transport = this._openTransports.get(proxyId);
3937
+ if (!transport) {
3938
+ return;
3939
+ }
3940
+ this._openTransports.delete(proxyId);
3941
+ await this._safeCloseTransport(transport);
4132
3942
  }
4133
- async getDetails() {
4134
- throw new Error("Method not implemented.");
3943
+ async _safeCloseTransport(transport) {
3944
+ if (this._openTransports.get(transport.proxyId) === transport) {
3945
+ this._openTransports.delete(transport.proxyId);
3946
+ }
3947
+ transport.writeProcessedCallbacks.forEach((cb) => cb());
3948
+ try {
3949
+ await transport.transport.close();
3950
+ } catch (error) {
3951
+ log12.warn("transport close error", {
3952
+ message: error?.message
3953
+ }, {
3954
+ F: __dxlog_file13,
3955
+ L: 172,
3956
+ S: this,
3957
+ C: (f, a) => f(...a)
3958
+ });
3959
+ }
3960
+ try {
3961
+ transport.connectorStream.end();
3962
+ } catch (error) {
3963
+ log12.warn("connectorStream close error", {
3964
+ message: error?.message
3965
+ }, {
3966
+ F: __dxlog_file13,
3967
+ L: 177,
3968
+ S: this,
3969
+ C: (f, a) => f(...a)
3970
+ });
3971
+ }
3972
+ log12("closed", void 0, {
3973
+ F: __dxlog_file13,
3974
+ L: 179,
3975
+ S: this,
3976
+ C: (f, a) => f(...a)
3977
+ });
4135
3978
  }
4136
3979
  };
3980
+ var createStateUpdater = (next) => {
3981
+ return (state, err) => {
3982
+ next({
3983
+ connection: {
3984
+ state,
3985
+ ...err ? {
3986
+ error: err.message
3987
+ } : void 0
3988
+ }
3989
+ });
3990
+ };
3991
+ };
4137
3992
 
4138
3993
  // packages/core/mesh/network-manager/src/wire-protocol.ts
4139
3994
  import { Teleport } from "@dxos/teleport";
@@ -4160,10 +4015,8 @@ var createTeleportProtocolFactory = (onConnection, defaultParams) => {
4160
4015
  };
4161
4016
 
4162
4017
  export {
4163
- process,
4164
4018
  ConnectionState,
4165
4019
  Connection,
4166
- createIceProvider,
4167
4020
  SwarmMessenger,
4168
4021
  Swarm,
4169
4022
  SwarmMapper,
@@ -4173,20 +4026,13 @@ export {
4173
4026
  ConnectionLog,
4174
4027
  SwarmNetworkManager,
4175
4028
  FullyConnectedTopology,
4176
- MMSTTopology,
4177
- StarTopology,
4178
4029
  MemoryTransportFactory,
4179
4030
  MemoryTransport,
4180
4031
  TransportKind,
4181
- createSimplePeerTransportFactory,
4182
- SimplePeerTransport,
4183
- SimplePeerTransportService,
4184
- SimplePeerTransportProxy,
4185
- SimplePeerTransportProxyFactory,
4186
- createLibDataChannelTransportFactory,
4187
- LibDataChannelTransport,
4188
- TcpTransportFactory,
4189
- TcpTransport,
4032
+ createRtcTransportFactory,
4033
+ RtcTransportProxy,
4034
+ RtcTransportProxyFactory,
4035
+ RtcTransportService,
4190
4036
  createTeleportProtocolFactory
4191
4037
  };
4192
- //# sourceMappingURL=chunk-XYSYUN63.mjs.map
4038
+ //# sourceMappingURL=chunk-V3IRGRVX.mjs.map