@dxos/shell 0.6.3-next.4424131 → 0.6.3-staging.75e3813

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 (42) hide show
  1. package/dist/bundle/browser-C2u-GX_T.mjs +7 -0
  2. package/dist/bundle/browser-C2u-GX_T.mjs.map +1 -0
  3. package/dist/bundle/index-BoJU28fu.mjs +1322 -0
  4. package/dist/bundle/index-BoJU28fu.mjs.map +1 -0
  5. package/dist/bundle/index-Ckc10jMw.mjs +92927 -0
  6. package/dist/bundle/index-Ckc10jMw.mjs.map +1 -0
  7. package/dist/bundle/index-DXRmq0_o.mjs +4593 -0
  8. package/dist/bundle/index-DXRmq0_o.mjs.map +1 -0
  9. package/dist/bundle/index-DvzmUghe.mjs +112 -0
  10. package/dist/bundle/index-DvzmUghe.mjs.map +1 -0
  11. package/dist/bundle/shell.mjs +10 -88396
  12. package/dist/bundle/shell.mjs.map +1 -1
  13. package/dist/bundle/shell.umd.js +133 -101
  14. package/dist/bundle/shell.umd.js.map +1 -1
  15. package/dist/bundle/style.css +1 -1
  16. package/dist/lib/browser/meta.json +1 -1
  17. package/dist/lib/browser/react.mjs +12 -8
  18. package/dist/lib/browser/react.mjs.map +3 -3
  19. package/dist/types/src/composites/Shell/Shell.d.ts +1 -1
  20. package/dist/types/src/composites/Shell/Shell.d.ts.map +1 -1
  21. package/dist/types/src/composites/Shell/Shell.js +28 -27
  22. package/dist/types/src/composites/Shell/Shell.js.map +1 -1
  23. package/dist/types/src/composites/Shell/ShellContext.d.ts +2 -1
  24. package/dist/types/src/composites/Shell/ShellContext.d.ts.map +1 -1
  25. package/dist/types/src/composites/Shell/ShellContext.js +13 -12
  26. package/dist/types/src/composites/Shell/ShellContext.js.map +1 -1
  27. package/dist/types/src/composites/Shell/memory-shell-runtime.d.ts +2 -1
  28. package/dist/types/src/composites/Shell/memory-shell-runtime.d.ts.map +1 -1
  29. package/dist/types/src/composites/Shell/memory-shell-runtime.js +2 -2
  30. package/dist/types/src/composites/Shell/memory-shell-runtime.js.map +1 -1
  31. package/dist/types/src/composites/Shell/run-shell.d.ts.map +1 -1
  32. package/dist/types/src/composites/Shell/run-shell.js +4 -3
  33. package/dist/types/src/composites/Shell/run-shell.js.map +1 -1
  34. package/dist/types/src/panels/IdentityPanel/useAgentHandlers.d.ts.map +1 -1
  35. package/dist/types/src/panels/IdentityPanel/useAgentHandlers.js +2 -1
  36. package/dist/types/src/panels/IdentityPanel/useAgentHandlers.js.map +1 -1
  37. package/package.json +24 -24
  38. package/src/composites/Shell/Shell.tsx +3 -3
  39. package/src/composites/Shell/ShellContext.tsx +2 -1
  40. package/src/composites/Shell/memory-shell-runtime.ts +2 -2
  41. package/src/composites/Shell/run-shell.tsx +2 -9
  42. package/src/panels/IdentityPanel/useAgentHandlers.ts +2 -1
@@ -0,0 +1,4593 @@
1
+ import { s as Et, b as ve, r as se, d as It, g as Lt, a as q, f as F, C as N, E as S, i as f, l as a, h as nt, j as rt, T as ee, k as Ae, P as m, m as W, n as Rt, o as Tt, c as Ft, p as At, e as X, q as O, t as ie, S as xt, u as ot, D as at, v as Nt, w as ct, x as Ot, y as ue, z as Pt } from "./index-Ckc10jMw.mjs";
2
+ import { schema as ce, TimeoutError as le, RpcClosedError as ht, trace as $, ConnectionResetError as dt, UnknownProtocolError as Ee, ConnectivityError as he, ProtocolError as lt, CancelledError as xe, SystemError as Dt } from "@dxos/protocols";
3
+ import { Messenger as kt } from "./index-BoJU28fu.mjs";
4
+ function H(t, e) {
5
+ if (t.length !== e.length) throw new Error("Inputs should have the same length");
6
+ for (var s = Buffer.allocUnsafe(t.length), i = 0; i < t.length; i++) s[i] = t[i] ^ e[i];
7
+ return s;
8
+ }
9
+ H.compare = function(e, s) {
10
+ if (e.length !== s.length) throw new Error("Inputs should have the same length");
11
+ for (var i = 0; i < e.length; i++)
12
+ if (e[i] !== s[i])
13
+ return e[i] < s[i] ? -1 : 1;
14
+ return 0;
15
+ };
16
+ H.gt = function(e, s) {
17
+ return H.compare(e, s) === 1;
18
+ };
19
+ H.lt = function(e, s) {
20
+ return H.compare(e, s) === -1;
21
+ };
22
+ H.eq = function(e, s) {
23
+ return H.compare(e, s) === 0;
24
+ };
25
+ var Ie = { exports: {} }, ge, ke;
26
+ function Mt() {
27
+ if (ke) return ge;
28
+ ke = 1;
29
+ var t = 1e3, e = t * 60, s = e * 60, i = s * 24, n = i * 7, r = i * 365.25;
30
+ ge = function(h, l) {
31
+ l = l || {};
32
+ var u = typeof h;
33
+ if (u === "string" && h.length > 0)
34
+ return o(h);
35
+ if (u === "number" && isFinite(h))
36
+ return l.long ? _(h) : c(h);
37
+ throw new Error(
38
+ "val is not a non-empty string or a valid number. val=" + JSON.stringify(h)
39
+ );
40
+ };
41
+ function o(h) {
42
+ if (h = String(h), !(h.length > 100)) {
43
+ var l = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
44
+ h
45
+ );
46
+ if (l) {
47
+ var u = parseFloat(l[1]), D = (l[2] || "ms").toLowerCase();
48
+ switch (D) {
49
+ case "years":
50
+ case "year":
51
+ case "yrs":
52
+ case "yr":
53
+ case "y":
54
+ return u * r;
55
+ case "weeks":
56
+ case "week":
57
+ case "w":
58
+ return u * n;
59
+ case "days":
60
+ case "day":
61
+ case "d":
62
+ return u * i;
63
+ case "hours":
64
+ case "hour":
65
+ case "hrs":
66
+ case "hr":
67
+ case "h":
68
+ return u * s;
69
+ case "minutes":
70
+ case "minute":
71
+ case "mins":
72
+ case "min":
73
+ case "m":
74
+ return u * e;
75
+ case "seconds":
76
+ case "second":
77
+ case "secs":
78
+ case "sec":
79
+ case "s":
80
+ return u * t;
81
+ case "milliseconds":
82
+ case "millisecond":
83
+ case "msecs":
84
+ case "msec":
85
+ case "ms":
86
+ return u;
87
+ default:
88
+ return;
89
+ }
90
+ }
91
+ }
92
+ }
93
+ function c(h) {
94
+ var l = Math.abs(h);
95
+ return l >= i ? Math.round(h / i) + "d" : l >= s ? Math.round(h / s) + "h" : l >= e ? Math.round(h / e) + "m" : l >= t ? Math.round(h / t) + "s" : h + "ms";
96
+ }
97
+ function _(h) {
98
+ var l = Math.abs(h);
99
+ return l >= i ? d(h, l, i, "day") : l >= s ? d(h, l, s, "hour") : l >= e ? d(h, l, e, "minute") : l >= t ? d(h, l, t, "second") : h + " ms";
100
+ }
101
+ function d(h, l, u, D) {
102
+ var ne = l >= u * 1.5;
103
+ return Math.round(h / u) + " " + D + (ne ? "s" : "");
104
+ }
105
+ return ge;
106
+ }
107
+ function Bt(t) {
108
+ s.debug = s, s.default = s, s.coerce = _, s.disable = r, s.enable = n, s.enabled = o, s.humanize = Mt(), s.destroy = d, Object.keys(t).forEach((h) => {
109
+ s[h] = t[h];
110
+ }), s.names = [], s.skips = [], s.formatters = {};
111
+ function e(h) {
112
+ let l = 0;
113
+ for (let u = 0; u < h.length; u++)
114
+ l = (l << 5) - l + h.charCodeAt(u), l |= 0;
115
+ return s.colors[Math.abs(l) % s.colors.length];
116
+ }
117
+ s.selectColor = e;
118
+ function s(h) {
119
+ let l, u = null, D, ne;
120
+ function x(...T) {
121
+ if (!x.enabled)
122
+ return;
123
+ const U = x, re = Number(/* @__PURE__ */ new Date()), St = re - (l || re);
124
+ U.diff = St, U.prev = l, U.curr = re, l = re, T[0] = s.coerce(T[0]), typeof T[0] != "string" && T.unshift("%O");
125
+ let oe = 0;
126
+ T[0] = T[0].replace(/%([a-zA-Z%])/g, (pe, bt) => {
127
+ if (pe === "%%")
128
+ return "%";
129
+ oe++;
130
+ const De = s.formatters[bt];
131
+ if (typeof De == "function") {
132
+ const vt = T[oe];
133
+ pe = De.call(U, vt), T.splice(oe, 1), oe--;
134
+ }
135
+ return pe;
136
+ }), s.formatArgs.call(U, T), (U.log || s.log).apply(U, T);
137
+ }
138
+ return x.namespace = h, x.useColors = s.useColors(), x.color = s.selectColor(h), x.extend = i, x.destroy = s.destroy, Object.defineProperty(x, "enabled", {
139
+ enumerable: !0,
140
+ configurable: !1,
141
+ get: () => u !== null ? u : (D !== s.namespaces && (D = s.namespaces, ne = s.enabled(h)), ne),
142
+ set: (T) => {
143
+ u = T;
144
+ }
145
+ }), typeof s.init == "function" && s.init(x), x;
146
+ }
147
+ function i(h, l) {
148
+ const u = s(this.namespace + (typeof l > "u" ? ":" : l) + h);
149
+ return u.log = this.log, u;
150
+ }
151
+ function n(h) {
152
+ s.save(h), s.namespaces = h, s.names = [], s.skips = [];
153
+ let l;
154
+ const u = (typeof h == "string" ? h : "").split(/[\s,]+/), D = u.length;
155
+ for (l = 0; l < D; l++)
156
+ u[l] && (h = u[l].replace(/\*/g, ".*?"), h[0] === "-" ? s.skips.push(new RegExp("^" + h.slice(1) + "$")) : s.names.push(new RegExp("^" + h + "$")));
157
+ }
158
+ function r() {
159
+ const h = [
160
+ ...s.names.map(c),
161
+ ...s.skips.map(c).map((l) => "-" + l)
162
+ ].join(",");
163
+ return s.enable(""), h;
164
+ }
165
+ function o(h) {
166
+ if (h[h.length - 1] === "*")
167
+ return !0;
168
+ let l, u;
169
+ for (l = 0, u = s.skips.length; l < u; l++)
170
+ if (s.skips[l].test(h))
171
+ return !1;
172
+ for (l = 0, u = s.names.length; l < u; l++)
173
+ if (s.names[l].test(h))
174
+ return !0;
175
+ return !1;
176
+ }
177
+ function c(h) {
178
+ return h.toString().substring(2, h.toString().length - 2).replace(/\.\*\?$/, "*");
179
+ }
180
+ function _(h) {
181
+ return h instanceof Error ? h.stack || h.message : h;
182
+ }
183
+ function d() {
184
+ console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");
185
+ }
186
+ return s.enable(s.load()), s;
187
+ }
188
+ var $t = Bt;
189
+ (function(t, e) {
190
+ e.formatArgs = i, e.save = n, e.load = r, e.useColors = s, e.storage = o(), e.destroy = /* @__PURE__ */ (() => {
191
+ let _ = !1;
192
+ return () => {
193
+ _ || (_ = !0, console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."));
194
+ };
195
+ })(), e.colors = [
196
+ "#0000CC",
197
+ "#0000FF",
198
+ "#0033CC",
199
+ "#0033FF",
200
+ "#0066CC",
201
+ "#0066FF",
202
+ "#0099CC",
203
+ "#0099FF",
204
+ "#00CC00",
205
+ "#00CC33",
206
+ "#00CC66",
207
+ "#00CC99",
208
+ "#00CCCC",
209
+ "#00CCFF",
210
+ "#3300CC",
211
+ "#3300FF",
212
+ "#3333CC",
213
+ "#3333FF",
214
+ "#3366CC",
215
+ "#3366FF",
216
+ "#3399CC",
217
+ "#3399FF",
218
+ "#33CC00",
219
+ "#33CC33",
220
+ "#33CC66",
221
+ "#33CC99",
222
+ "#33CCCC",
223
+ "#33CCFF",
224
+ "#6600CC",
225
+ "#6600FF",
226
+ "#6633CC",
227
+ "#6633FF",
228
+ "#66CC00",
229
+ "#66CC33",
230
+ "#9900CC",
231
+ "#9900FF",
232
+ "#9933CC",
233
+ "#9933FF",
234
+ "#99CC00",
235
+ "#99CC33",
236
+ "#CC0000",
237
+ "#CC0033",
238
+ "#CC0066",
239
+ "#CC0099",
240
+ "#CC00CC",
241
+ "#CC00FF",
242
+ "#CC3300",
243
+ "#CC3333",
244
+ "#CC3366",
245
+ "#CC3399",
246
+ "#CC33CC",
247
+ "#CC33FF",
248
+ "#CC6600",
249
+ "#CC6633",
250
+ "#CC9900",
251
+ "#CC9933",
252
+ "#CCCC00",
253
+ "#CCCC33",
254
+ "#FF0000",
255
+ "#FF0033",
256
+ "#FF0066",
257
+ "#FF0099",
258
+ "#FF00CC",
259
+ "#FF00FF",
260
+ "#FF3300",
261
+ "#FF3333",
262
+ "#FF3366",
263
+ "#FF3399",
264
+ "#FF33CC",
265
+ "#FF33FF",
266
+ "#FF6600",
267
+ "#FF6633",
268
+ "#FF9900",
269
+ "#FF9933",
270
+ "#FFCC00",
271
+ "#FFCC33"
272
+ ];
273
+ function s() {
274
+ return typeof window < "u" && window.process && (window.process.type === "renderer" || window.process.__nwjs) ? !0 : typeof navigator < "u" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/) ? !1 : typeof document < "u" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773
275
+ typeof window < "u" && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31?
276
+ // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
277
+ typeof navigator < "u" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker
278
+ typeof navigator < "u" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
279
+ }
280
+ function i(_) {
281
+ if (_[0] = (this.useColors ? "%c" : "") + this.namespace + (this.useColors ? " %c" : " ") + _[0] + (this.useColors ? "%c " : " ") + "+" + t.exports.humanize(this.diff), !this.useColors)
282
+ return;
283
+ const d = "color: " + this.color;
284
+ _.splice(1, 0, d, "color: inherit");
285
+ let h = 0, l = 0;
286
+ _[0].replace(/%[a-zA-Z%]/g, (u) => {
287
+ u !== "%%" && (h++, u === "%c" && (l = h));
288
+ }), _.splice(l, 0, d);
289
+ }
290
+ e.log = console.debug || console.log || (() => {
291
+ });
292
+ function n(_) {
293
+ try {
294
+ _ ? e.storage.setItem("debug", _) : e.storage.removeItem("debug");
295
+ } catch {
296
+ }
297
+ }
298
+ function r() {
299
+ let _;
300
+ try {
301
+ _ = e.storage.getItem("debug");
302
+ } catch {
303
+ }
304
+ return !_ && typeof process < "u" && "env" in process && (_ = process.env.DEBUG), _;
305
+ }
306
+ function o() {
307
+ try {
308
+ return localStorage;
309
+ } catch {
310
+ }
311
+ }
312
+ t.exports = $t(e);
313
+ const { formatters: c } = t.exports;
314
+ c.j = function(_) {
315
+ try {
316
+ return JSON.stringify(_);
317
+ } catch (d) {
318
+ return "[UnexpectedJSONParseError]: " + d.message;
319
+ }
320
+ };
321
+ })(Ie, Ie.exports);
322
+ var qt = Ie.exports, jt = function() {
323
+ if (typeof globalThis > "u") return null;
324
+ var e = {
325
+ RTCPeerConnection: globalThis.RTCPeerConnection || globalThis.mozRTCPeerConnection || globalThis.webkitRTCPeerConnection,
326
+ RTCSessionDescription: globalThis.RTCSessionDescription || globalThis.mozRTCSessionDescription || globalThis.webkitRTCSessionDescription,
327
+ RTCIceCandidate: globalThis.RTCIceCandidate || globalThis.mozRTCIceCandidate || globalThis.webkitRTCIceCandidate
328
+ };
329
+ return e.RTCPeerConnection ? e : null;
330
+ }, Le = { exports: {} }, me = 65536, Ut = 4294967295;
331
+ function Ht() {
332
+ throw new Error(`Secure random number generation is not supported by this browser.
333
+ Use Chrome, Firefox or Internet Explorer 11`);
334
+ }
335
+ var Gt = Et.Buffer, de = ve.crypto || ve.msCrypto;
336
+ de && de.getRandomValues ? Le.exports = zt : Le.exports = Ht;
337
+ function zt(t, e) {
338
+ if (t > Ut) throw new RangeError("requested too many random bytes");
339
+ var s = Gt.allocUnsafe(t);
340
+ if (t > 0)
341
+ if (t > me)
342
+ for (var i = 0; i < t; i += me)
343
+ de.getRandomValues(s.slice(i, i + me));
344
+ else
345
+ de.getRandomValues(s);
346
+ return typeof e == "function" ? process.nextTick(function() {
347
+ e(null, s);
348
+ }) : s;
349
+ }
350
+ var Yt = Le.exports;
351
+ /*! queue-microtask. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
352
+ let Me;
353
+ var Kt = typeof queueMicrotask == "function" ? queueMicrotask.bind(typeof window < "u" ? window : ve) : (t) => (Me || (Me = Promise.resolve())).then(t).catch((e) => setTimeout(() => {
354
+ throw e;
355
+ }, 0));
356
+ function Be(t, e) {
357
+ for (const s in e)
358
+ Object.defineProperty(t, s, {
359
+ value: e[s],
360
+ enumerable: !0,
361
+ configurable: !0
362
+ });
363
+ return t;
364
+ }
365
+ function Wt(t, e, s) {
366
+ if (!t || typeof t == "string")
367
+ throw new TypeError("Please pass an Error to err-code");
368
+ s || (s = {}), typeof e == "object" && (s = e, e = ""), e && (s.code = e);
369
+ try {
370
+ return Be(t, s);
371
+ } catch {
372
+ s.message = t.message, s.stack = t.stack;
373
+ const n = function() {
374
+ };
375
+ return n.prototype = Object.create(Object.getPrototypeOf(t)), Be(new n(), s);
376
+ }
377
+ }
378
+ var Xt = Wt;
379
+ /*! simple-peer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
380
+ const Vt = qt("simple-peer"), _t = jt, $e = Yt, Zt = se, Ce = Kt, g = Xt, { Buffer: Jt } = It, we = 64 * 1024, Qt = 5 * 1e3, es = 5 * 1e3;
381
+ function qe(t) {
382
+ return t.replace(/a=ice-options:trickle\s\n/g, "");
383
+ }
384
+ function ts(t) {
385
+ console.warn(t);
386
+ }
387
+ let _e = class Re extends Zt.Duplex {
388
+ constructor(e) {
389
+ if (e = Object.assign({
390
+ allowHalfOpen: !1
391
+ }, e), super(e), this._id = $e(4).toString("hex").slice(0, 7), this._debug("new peer %o", e), this.channelName = e.initiator ? e.channelName || $e(20).toString("hex") : null, this.initiator = e.initiator || !1, this.channelConfig = e.channelConfig || Re.channelConfig, this.channelNegotiated = this.channelConfig.negotiated, this.config = Object.assign({}, Re.config, e.config), this.offerOptions = e.offerOptions || {}, this.answerOptions = e.answerOptions || {}, this.sdpTransform = e.sdpTransform || ((s) => s), this.streams = e.streams || (e.stream ? [e.stream] : []), this.trickle = e.trickle !== void 0 ? e.trickle : !0, this.allowHalfTrickle = e.allowHalfTrickle !== void 0 ? e.allowHalfTrickle : !1, this.iceCompleteTimeout = e.iceCompleteTimeout || Qt, this.destroyed = !1, this.destroying = !1, this._connected = !1, this.remoteAddress = void 0, this.remoteFamily = void 0, this.remotePort = void 0, this.localAddress = void 0, this.localFamily = void 0, this.localPort = void 0, this._wrtc = e.wrtc && typeof e.wrtc == "object" ? e.wrtc : _t(), !this._wrtc)
392
+ throw g(typeof window > "u" ? new Error("No WebRTC support: Specify `opts.wrtc` option in this environment") : new Error("No WebRTC support: Not a supported browser"), "ERR_WEBRTC_SUPPORT");
393
+ this._pcReady = !1, this._channelReady = !1, this._iceComplete = !1, this._iceCompleteTimer = null, this._channel = null, this._pendingCandidates = [], this._isNegotiating = !1, this._firstNegotiation = !0, this._batchedNegotiation = !1, this._queuedNegotiation = !1, this._sendersAwaitingStable = [], this._senderMap = /* @__PURE__ */ new Map(), this._closingInterval = null, this._remoteTracks = [], this._remoteStreams = [], this._chunk = null, this._cb = null, this._interval = null;
394
+ try {
395
+ this._pc = new this._wrtc.RTCPeerConnection(this.config);
396
+ } catch (s) {
397
+ this.destroy(g(s, "ERR_PC_CONSTRUCTOR"));
398
+ return;
399
+ }
400
+ this._isReactNativeWebrtc = typeof this._pc._peerConnectionId == "number", this._pc.oniceconnectionstatechange = () => {
401
+ this._onIceStateChange();
402
+ }, this._pc.onicegatheringstatechange = () => {
403
+ this._onIceStateChange();
404
+ }, this._pc.onconnectionstatechange = () => {
405
+ this._onConnectionStateChange();
406
+ }, this._pc.onsignalingstatechange = () => {
407
+ this._onSignalingStateChange();
408
+ }, this._pc.onicecandidate = (s) => {
409
+ this._onIceCandidate(s);
410
+ }, typeof this._pc.peerIdentity == "object" && this._pc.peerIdentity.catch((s) => {
411
+ this.destroy(g(s, "ERR_PC_PEER_IDENTITY"));
412
+ }), this.initiator || this.channelNegotiated ? this._setupData({
413
+ channel: this._pc.createDataChannel(this.channelName, this.channelConfig)
414
+ }) : this._pc.ondatachannel = (s) => {
415
+ this._setupData(s);
416
+ }, this.streams && this.streams.forEach((s) => {
417
+ this.addStream(s);
418
+ }), this._pc.ontrack = (s) => {
419
+ this._onTrack(s);
420
+ }, this._debug("initial negotiation"), this._needsNegotiation(), this._onFinishBound = () => {
421
+ this._onFinish();
422
+ }, this.once("finish", this._onFinishBound);
423
+ }
424
+ get bufferSize() {
425
+ return this._channel && this._channel.bufferedAmount || 0;
426
+ }
427
+ // HACK: it's possible channel.readyState is "closing" before peer.destroy() fires
428
+ // https://bugs.chromium.org/p/chromium/issues/detail?id=882743
429
+ get connected() {
430
+ return this._connected && this._channel.readyState === "open";
431
+ }
432
+ address() {
433
+ return { port: this.localPort, family: this.localFamily, address: this.localAddress };
434
+ }
435
+ signal(e) {
436
+ if (!this.destroying) {
437
+ if (this.destroyed) throw g(new Error("cannot signal after peer is destroyed"), "ERR_DESTROYED");
438
+ if (typeof e == "string")
439
+ try {
440
+ e = JSON.parse(e);
441
+ } catch {
442
+ e = {};
443
+ }
444
+ this._debug("signal()"), e.renegotiate && this.initiator && (this._debug("got request to renegotiate"), this._needsNegotiation()), e.transceiverRequest && this.initiator && (this._debug("got request for transceiver"), this.addTransceiver(e.transceiverRequest.kind, e.transceiverRequest.init)), e.candidate && (this._pc.remoteDescription && this._pc.remoteDescription.type ? this._addIceCandidate(e.candidate) : this._pendingCandidates.push(e.candidate)), e.sdp && this._pc.setRemoteDescription(new this._wrtc.RTCSessionDescription(e)).then(() => {
445
+ this.destroyed || (this._pendingCandidates.forEach((s) => {
446
+ this._addIceCandidate(s);
447
+ }), this._pendingCandidates = [], this._pc.remoteDescription.type === "offer" && this._createAnswer());
448
+ }).catch((s) => {
449
+ this.destroy(g(s, "ERR_SET_REMOTE_DESCRIPTION"));
450
+ }), !e.sdp && !e.candidate && !e.renegotiate && !e.transceiverRequest && this.destroy(g(new Error("signal() called with invalid signal data"), "ERR_SIGNALING"));
451
+ }
452
+ }
453
+ _addIceCandidate(e) {
454
+ const s = new this._wrtc.RTCIceCandidate(e);
455
+ this._pc.addIceCandidate(s).catch((i) => {
456
+ !s.address || s.address.endsWith(".local") ? ts("Ignoring unsupported ICE candidate.") : this.destroy(g(i, "ERR_ADD_ICE_CANDIDATE"));
457
+ });
458
+ }
459
+ /**
460
+ * Send text/binary data to the remote peer.
461
+ * @param {ArrayBufferView|ArrayBuffer|Buffer|string|Blob} chunk
462
+ */
463
+ send(e) {
464
+ if (!this.destroying) {
465
+ if (this.destroyed) throw g(new Error("cannot send after peer is destroyed"), "ERR_DESTROYED");
466
+ this._channel.send(e);
467
+ }
468
+ }
469
+ /**
470
+ * Add a Transceiver to the connection.
471
+ * @param {String} kind
472
+ * @param {Object} init
473
+ */
474
+ addTransceiver(e, s) {
475
+ if (!this.destroying) {
476
+ if (this.destroyed) throw g(new Error("cannot addTransceiver after peer is destroyed"), "ERR_DESTROYED");
477
+ if (this._debug("addTransceiver()"), this.initiator)
478
+ try {
479
+ this._pc.addTransceiver(e, s), this._needsNegotiation();
480
+ } catch (i) {
481
+ this.destroy(g(i, "ERR_ADD_TRANSCEIVER"));
482
+ }
483
+ else
484
+ this.emit("signal", {
485
+ // request initiator to renegotiate
486
+ type: "transceiverRequest",
487
+ transceiverRequest: { kind: e, init: s }
488
+ });
489
+ }
490
+ }
491
+ /**
492
+ * Add a MediaStream to the connection.
493
+ * @param {MediaStream} stream
494
+ */
495
+ addStream(e) {
496
+ if (!this.destroying) {
497
+ if (this.destroyed) throw g(new Error("cannot addStream after peer is destroyed"), "ERR_DESTROYED");
498
+ this._debug("addStream()"), e.getTracks().forEach((s) => {
499
+ this.addTrack(s, e);
500
+ });
501
+ }
502
+ }
503
+ /**
504
+ * Add a MediaStreamTrack to the connection.
505
+ * @param {MediaStreamTrack} track
506
+ * @param {MediaStream} stream
507
+ */
508
+ addTrack(e, s) {
509
+ if (this.destroying) return;
510
+ if (this.destroyed) throw g(new Error("cannot addTrack after peer is destroyed"), "ERR_DESTROYED");
511
+ this._debug("addTrack()");
512
+ const i = this._senderMap.get(e) || /* @__PURE__ */ new Map();
513
+ let n = i.get(s);
514
+ if (!n)
515
+ n = this._pc.addTrack(e, s), i.set(s, n), this._senderMap.set(e, i), this._needsNegotiation();
516
+ else throw n.removed ? g(new Error("Track has been removed. You should enable/disable tracks that you want to re-add."), "ERR_SENDER_REMOVED") : g(new Error("Track has already been added to that stream."), "ERR_SENDER_ALREADY_ADDED");
517
+ }
518
+ /**
519
+ * Replace a MediaStreamTrack by another in the connection.
520
+ * @param {MediaStreamTrack} oldTrack
521
+ * @param {MediaStreamTrack} newTrack
522
+ * @param {MediaStream} stream
523
+ */
524
+ replaceTrack(e, s, i) {
525
+ if (this.destroying) return;
526
+ if (this.destroyed) throw g(new Error("cannot replaceTrack after peer is destroyed"), "ERR_DESTROYED");
527
+ this._debug("replaceTrack()");
528
+ const n = this._senderMap.get(e), r = n ? n.get(i) : null;
529
+ if (!r)
530
+ throw g(new Error("Cannot replace track that was never added."), "ERR_TRACK_NOT_ADDED");
531
+ s && this._senderMap.set(s, n), r.replaceTrack != null ? r.replaceTrack(s) : this.destroy(g(new Error("replaceTrack is not supported in this browser"), "ERR_UNSUPPORTED_REPLACETRACK"));
532
+ }
533
+ /**
534
+ * Remove a MediaStreamTrack from the connection.
535
+ * @param {MediaStreamTrack} track
536
+ * @param {MediaStream} stream
537
+ */
538
+ removeTrack(e, s) {
539
+ if (this.destroying) return;
540
+ if (this.destroyed) throw g(new Error("cannot removeTrack after peer is destroyed"), "ERR_DESTROYED");
541
+ this._debug("removeSender()");
542
+ const i = this._senderMap.get(e), n = i ? i.get(s) : null;
543
+ if (!n)
544
+ throw g(new Error("Cannot remove track that was never added."), "ERR_TRACK_NOT_ADDED");
545
+ try {
546
+ n.removed = !0, this._pc.removeTrack(n);
547
+ } catch (r) {
548
+ r.name === "NS_ERROR_UNEXPECTED" ? this._sendersAwaitingStable.push(n) : this.destroy(g(r, "ERR_REMOVE_TRACK"));
549
+ }
550
+ this._needsNegotiation();
551
+ }
552
+ /**
553
+ * Remove a MediaStream from the connection.
554
+ * @param {MediaStream} stream
555
+ */
556
+ removeStream(e) {
557
+ if (!this.destroying) {
558
+ if (this.destroyed) throw g(new Error("cannot removeStream after peer is destroyed"), "ERR_DESTROYED");
559
+ this._debug("removeSenders()"), e.getTracks().forEach((s) => {
560
+ this.removeTrack(s, e);
561
+ });
562
+ }
563
+ }
564
+ _needsNegotiation() {
565
+ this._debug("_needsNegotiation"), !this._batchedNegotiation && (this._batchedNegotiation = !0, Ce(() => {
566
+ this._batchedNegotiation = !1, this.initiator || !this._firstNegotiation ? (this._debug("starting batched negotiation"), this.negotiate()) : this._debug("non-initiator initial negotiation request discarded"), this._firstNegotiation = !1;
567
+ }));
568
+ }
569
+ negotiate() {
570
+ if (!this.destroying) {
571
+ if (this.destroyed) throw g(new Error("cannot negotiate after peer is destroyed"), "ERR_DESTROYED");
572
+ this.initiator ? this._isNegotiating ? (this._queuedNegotiation = !0, this._debug("already negotiating, queueing")) : (this._debug("start negotiation"), setTimeout(() => {
573
+ this._createOffer();
574
+ }, 0)) : this._isNegotiating ? (this._queuedNegotiation = !0, this._debug("already negotiating, queueing")) : (this._debug("requesting negotiation from initiator"), this.emit("signal", {
575
+ // request initiator to renegotiate
576
+ type: "renegotiate",
577
+ renegotiate: !0
578
+ })), this._isNegotiating = !0;
579
+ }
580
+ }
581
+ // TODO: Delete this method once readable-stream is updated to contain a default
582
+ // implementation of destroy() that automatically calls _destroy()
583
+ // See: https://github.com/nodejs/readable-stream/issues/283
584
+ destroy(e) {
585
+ this._destroy(e, () => {
586
+ });
587
+ }
588
+ _destroy(e, s) {
589
+ this.destroyed || this.destroying || (this.destroying = !0, this._debug("destroying (error: %s)", e && (e.message || e)), Ce(() => {
590
+ if (this.destroyed = !0, this.destroying = !1, this._debug("destroy (error: %s)", e && (e.message || e)), this.readable = this.writable = !1, this._readableState.ended || this.push(null), this._writableState.finished || this.end(), this._connected = !1, this._pcReady = !1, this._channelReady = !1, this._remoteTracks = null, this._remoteStreams = null, this._senderMap = null, clearInterval(this._closingInterval), this._closingInterval = null, clearInterval(this._interval), this._interval = null, this._chunk = null, this._cb = null, this._onFinishBound && this.removeListener("finish", this._onFinishBound), this._onFinishBound = null, this._channel) {
591
+ try {
592
+ this._channel.close();
593
+ } catch {
594
+ }
595
+ this._channel.onmessage = null, this._channel.onopen = null, this._channel.onclose = null, this._channel.onerror = null;
596
+ }
597
+ if (this._pc) {
598
+ try {
599
+ this._pc.close();
600
+ } catch {
601
+ }
602
+ this._pc.oniceconnectionstatechange = null, this._pc.onicegatheringstatechange = null, this._pc.onsignalingstatechange = null, this._pc.onicecandidate = null, this._pc.ontrack = null, this._pc.ondatachannel = null;
603
+ }
604
+ this._pc = null, this._channel = null, e && this.emit("error", e), this.emit("close"), s();
605
+ }));
606
+ }
607
+ _setupData(e) {
608
+ if (!e.channel)
609
+ return this.destroy(g(new Error("Data channel event is missing `channel` property"), "ERR_DATA_CHANNEL"));
610
+ this._channel = e.channel, this._channel.binaryType = "arraybuffer", typeof this._channel.bufferedAmountLowThreshold == "number" && (this._channel.bufferedAmountLowThreshold = we), this.channelName = this._channel.label, this._channel.onmessage = (i) => {
611
+ this._onChannelMessage(i);
612
+ }, this._channel.onbufferedamountlow = () => {
613
+ this._onChannelBufferedAmountLow();
614
+ }, this._channel.onopen = () => {
615
+ this._onChannelOpen();
616
+ }, this._channel.onclose = () => {
617
+ this._onChannelClose();
618
+ }, this._channel.onerror = (i) => {
619
+ const n = i.error instanceof Error ? i.error : new Error(`Datachannel error: ${i.message} ${i.filename}:${i.lineno}:${i.colno}`);
620
+ this.destroy(g(n, "ERR_DATA_CHANNEL"));
621
+ };
622
+ let s = !1;
623
+ this._closingInterval = setInterval(() => {
624
+ this._channel && this._channel.readyState === "closing" ? (s && this._onChannelClose(), s = !0) : s = !1;
625
+ }, es);
626
+ }
627
+ _read() {
628
+ }
629
+ _write(e, s, i) {
630
+ if (this.destroyed) return i(g(new Error("cannot write after peer is destroyed"), "ERR_DATA_CHANNEL"));
631
+ if (this._connected) {
632
+ try {
633
+ this.send(e);
634
+ } catch (n) {
635
+ return this.destroy(g(n, "ERR_DATA_CHANNEL"));
636
+ }
637
+ this._channel.bufferedAmount > we ? (this._debug("start backpressure: bufferedAmount %d", this._channel.bufferedAmount), this._cb = i) : i(null);
638
+ } else
639
+ this._debug("write before connect"), this._chunk = e, this._cb = i;
640
+ }
641
+ // When stream finishes writing, close socket. Half open connections are not
642
+ // supported.
643
+ _onFinish() {
644
+ if (this.destroyed) return;
645
+ const e = () => {
646
+ setTimeout(() => this.destroy(), 1e3);
647
+ };
648
+ this._connected ? e() : this.once("connect", e);
649
+ }
650
+ _startIceCompleteTimeout() {
651
+ this.destroyed || this._iceCompleteTimer || (this._debug("started iceComplete timeout"), this._iceCompleteTimer = setTimeout(() => {
652
+ this._iceComplete || (this._iceComplete = !0, this._debug("iceComplete timeout completed"), this.emit("iceTimeout"), this.emit("_iceComplete"));
653
+ }, this.iceCompleteTimeout));
654
+ }
655
+ _createOffer() {
656
+ this.destroyed || this._pc.createOffer(this.offerOptions).then((e) => {
657
+ if (this.destroyed) return;
658
+ !this.trickle && !this.allowHalfTrickle && (e.sdp = qe(e.sdp)), e.sdp = this.sdpTransform(e.sdp);
659
+ const s = () => {
660
+ if (this.destroyed) return;
661
+ const r = this._pc.localDescription || e;
662
+ this._debug("signal"), this.emit("signal", {
663
+ type: r.type,
664
+ sdp: r.sdp
665
+ });
666
+ }, i = () => {
667
+ this._debug("createOffer success"), !this.destroyed && (this.trickle || this._iceComplete ? s() : this.once("_iceComplete", s));
668
+ }, n = (r) => {
669
+ this.destroy(g(r, "ERR_SET_LOCAL_DESCRIPTION"));
670
+ };
671
+ this._pc.setLocalDescription(e).then(i).catch(n);
672
+ }).catch((e) => {
673
+ this.destroy(g(e, "ERR_CREATE_OFFER"));
674
+ });
675
+ }
676
+ _requestMissingTransceivers() {
677
+ this._pc.getTransceivers && this._pc.getTransceivers().forEach((e) => {
678
+ !e.mid && e.sender.track && !e.requested && (e.requested = !0, this.addTransceiver(e.sender.track.kind));
679
+ });
680
+ }
681
+ _createAnswer() {
682
+ this.destroyed || this._pc.createAnswer(this.answerOptions).then((e) => {
683
+ if (this.destroyed) return;
684
+ !this.trickle && !this.allowHalfTrickle && (e.sdp = qe(e.sdp)), e.sdp = this.sdpTransform(e.sdp);
685
+ const s = () => {
686
+ if (this.destroyed) return;
687
+ const r = this._pc.localDescription || e;
688
+ this._debug("signal"), this.emit("signal", {
689
+ type: r.type,
690
+ sdp: r.sdp
691
+ }), this.initiator || this._requestMissingTransceivers();
692
+ }, i = () => {
693
+ this.destroyed || (this.trickle || this._iceComplete ? s() : this.once("_iceComplete", s));
694
+ }, n = (r) => {
695
+ this.destroy(g(r, "ERR_SET_LOCAL_DESCRIPTION"));
696
+ };
697
+ this._pc.setLocalDescription(e).then(i).catch(n);
698
+ }).catch((e) => {
699
+ this.destroy(g(e, "ERR_CREATE_ANSWER"));
700
+ });
701
+ }
702
+ _onConnectionStateChange() {
703
+ this.destroyed || this._pc.connectionState === "failed" && this.destroy(g(new Error("Connection failed."), "ERR_CONNECTION_FAILURE"));
704
+ }
705
+ _onIceStateChange() {
706
+ if (this.destroyed) return;
707
+ const e = this._pc.iceConnectionState, s = this._pc.iceGatheringState;
708
+ this._debug(
709
+ "iceStateChange (connection: %s) (gathering: %s)",
710
+ e,
711
+ s
712
+ ), this.emit("iceStateChange", e, s), (e === "connected" || e === "completed") && (this._pcReady = !0, this._maybeReady()), e === "failed" && this.destroy(g(new Error("Ice connection failed."), "ERR_ICE_CONNECTION_FAILURE")), e === "closed" && this.destroy(g(new Error("Ice connection closed."), "ERR_ICE_CONNECTION_CLOSED"));
713
+ }
714
+ getStats(e) {
715
+ const s = (i) => (Object.prototype.toString.call(i.values) === "[object Array]" && i.values.forEach((n) => {
716
+ Object.assign(i, n);
717
+ }), i);
718
+ this._pc.getStats.length === 0 || this._isReactNativeWebrtc ? this._pc.getStats().then((i) => {
719
+ const n = [];
720
+ i.forEach((r) => {
721
+ n.push(s(r));
722
+ }), e(null, n);
723
+ }, (i) => e(i)) : this._pc.getStats.length > 0 ? this._pc.getStats((i) => {
724
+ if (this.destroyed) return;
725
+ const n = [];
726
+ i.result().forEach((r) => {
727
+ const o = {};
728
+ r.names().forEach((c) => {
729
+ o[c] = r.stat(c);
730
+ }), o.id = r.id, o.type = r.type, o.timestamp = r.timestamp, n.push(s(o));
731
+ }), e(null, n);
732
+ }, (i) => e(i)) : e(null, []);
733
+ }
734
+ _maybeReady() {
735
+ if (this._debug("maybeReady pc %s channel %s", this._pcReady, this._channelReady), this._connected || this._connecting || !this._pcReady || !this._channelReady) return;
736
+ this._connecting = !0;
737
+ const e = () => {
738
+ this.destroyed || this.getStats((s, i) => {
739
+ if (this.destroyed) return;
740
+ s && (i = []);
741
+ const n = {}, r = {}, o = {};
742
+ let c = !1;
743
+ i.forEach((d) => {
744
+ (d.type === "remotecandidate" || d.type === "remote-candidate") && (n[d.id] = d), (d.type === "localcandidate" || d.type === "local-candidate") && (r[d.id] = d), (d.type === "candidatepair" || d.type === "candidate-pair") && (o[d.id] = d);
745
+ });
746
+ const _ = (d) => {
747
+ c = !0;
748
+ let h = r[d.localCandidateId];
749
+ h && (h.ip || h.address) ? (this.localAddress = h.ip || h.address, this.localPort = Number(h.port)) : h && h.ipAddress ? (this.localAddress = h.ipAddress, this.localPort = Number(h.portNumber)) : typeof d.googLocalAddress == "string" && (h = d.googLocalAddress.split(":"), this.localAddress = h[0], this.localPort = Number(h[1])), this.localAddress && (this.localFamily = this.localAddress.includes(":") ? "IPv6" : "IPv4");
750
+ let l = n[d.remoteCandidateId];
751
+ l && (l.ip || l.address) ? (this.remoteAddress = l.ip || l.address, this.remotePort = Number(l.port)) : l && l.ipAddress ? (this.remoteAddress = l.ipAddress, this.remotePort = Number(l.portNumber)) : typeof d.googRemoteAddress == "string" && (l = d.googRemoteAddress.split(":"), this.remoteAddress = l[0], this.remotePort = Number(l[1])), this.remoteAddress && (this.remoteFamily = this.remoteAddress.includes(":") ? "IPv6" : "IPv4"), this._debug(
752
+ "connect local: %s:%s remote: %s:%s",
753
+ this.localAddress,
754
+ this.localPort,
755
+ this.remoteAddress,
756
+ this.remotePort
757
+ );
758
+ };
759
+ if (i.forEach((d) => {
760
+ d.type === "transport" && d.selectedCandidatePairId && _(o[d.selectedCandidatePairId]), (d.type === "googCandidatePair" && d.googActiveConnection === "true" || (d.type === "candidatepair" || d.type === "candidate-pair") && d.selected) && _(d);
761
+ }), !c && (!Object.keys(o).length || Object.keys(r).length)) {
762
+ setTimeout(e, 100);
763
+ return;
764
+ } else
765
+ this._connecting = !1, this._connected = !0;
766
+ if (this._chunk) {
767
+ try {
768
+ this.send(this._chunk);
769
+ } catch (h) {
770
+ return this.destroy(g(h, "ERR_DATA_CHANNEL"));
771
+ }
772
+ this._chunk = null, this._debug('sent chunk from "write before connect"');
773
+ const d = this._cb;
774
+ this._cb = null, d(null);
775
+ }
776
+ typeof this._channel.bufferedAmountLowThreshold != "number" && (this._interval = setInterval(() => this._onInterval(), 150), this._interval.unref && this._interval.unref()), this._debug("connect"), this.emit("connect");
777
+ });
778
+ };
779
+ e();
780
+ }
781
+ _onInterval() {
782
+ !this._cb || !this._channel || this._channel.bufferedAmount > we || this._onChannelBufferedAmountLow();
783
+ }
784
+ _onSignalingStateChange() {
785
+ this.destroyed || (this._pc.signalingState === "stable" && (this._isNegotiating = !1, this._debug("flushing sender queue", this._sendersAwaitingStable), this._sendersAwaitingStable.forEach((e) => {
786
+ this._pc.removeTrack(e), this._queuedNegotiation = !0;
787
+ }), this._sendersAwaitingStable = [], this._queuedNegotiation ? (this._debug("flushing negotiation queue"), this._queuedNegotiation = !1, this._needsNegotiation()) : (this._debug("negotiated"), this.emit("negotiated"))), this._debug("signalingStateChange %s", this._pc.signalingState), this.emit("signalingStateChange", this._pc.signalingState));
788
+ }
789
+ _onIceCandidate(e) {
790
+ this.destroyed || (e.candidate && this.trickle ? this.emit("signal", {
791
+ type: "candidate",
792
+ candidate: {
793
+ candidate: e.candidate.candidate,
794
+ sdpMLineIndex: e.candidate.sdpMLineIndex,
795
+ sdpMid: e.candidate.sdpMid
796
+ }
797
+ }) : !e.candidate && !this._iceComplete && (this._iceComplete = !0, this.emit("_iceComplete")), e.candidate && this._startIceCompleteTimeout());
798
+ }
799
+ _onChannelMessage(e) {
800
+ if (this.destroyed) return;
801
+ let s = e.data;
802
+ s instanceof ArrayBuffer && (s = Jt.from(s)), this.push(s);
803
+ }
804
+ _onChannelBufferedAmountLow() {
805
+ if (this.destroyed || !this._cb) return;
806
+ this._debug("ending backpressure: bufferedAmount %d", this._channel.bufferedAmount);
807
+ const e = this._cb;
808
+ this._cb = null, e(null);
809
+ }
810
+ _onChannelOpen() {
811
+ this._connected || this.destroyed || (this._debug("on channel open"), this._channelReady = !0, this._maybeReady());
812
+ }
813
+ _onChannelClose() {
814
+ this.destroyed || (this._debug("on channel close"), this.destroy());
815
+ }
816
+ _onTrack(e) {
817
+ this.destroyed || e.streams.forEach((s) => {
818
+ this._debug("on track"), this.emit("track", e.track, s), this._remoteTracks.push({
819
+ track: e.track,
820
+ stream: s
821
+ }), !this._remoteStreams.some((i) => i.id === s.id) && (this._remoteStreams.push(s), Ce(() => {
822
+ this._debug("on stream"), this.emit("stream", s);
823
+ }));
824
+ });
825
+ }
826
+ _debug() {
827
+ const e = [].slice.call(arguments);
828
+ e[0] = "[" + this._id + "] " + e[0], Vt.apply(null, e);
829
+ }
830
+ };
831
+ _e.WEBRTC_SUPPORT = !!_t();
832
+ _e.config = {
833
+ iceServers: [
834
+ {
835
+ urls: [
836
+ "stun:stun.l.google.com:19302",
837
+ "stun:global.stun.twilio.com:3478"
838
+ ]
839
+ }
840
+ ],
841
+ sdpSemantics: "unified-plan"
842
+ };
843
+ _e.channelConfig = {};
844
+ var ss = _e;
845
+ const je = /* @__PURE__ */ Lt(ss);
846
+ var is = process.env.NODE_ENV === "production", ye = "Invariant failed";
847
+ function ns(t, e) {
848
+ if (!t) {
849
+ if (is)
850
+ throw new Error(ye);
851
+ var s = typeof e == "function" ? e() : e, i = s ? "".concat(ye, ": ").concat(s) : ye;
852
+ throw new Error(i);
853
+ }
854
+ }
855
+ var K;
856
+ (function(t) {
857
+ t[t.INVALID = 0] = "INVALID", t[t.CONNECTING = 1] = "CONNECTING", t[t.CONNECTED = 2] = "CONNECTED", t[t.CLOSED = 3] = "CLOSED";
858
+ })(K || (K = {}));
859
+ var rs = R;
860
+ function R(t) {
861
+ if (t) return os(t);
862
+ }
863
+ function os(t) {
864
+ for (var e in R.prototype)
865
+ t[e] = R.prototype[e];
866
+ return t;
867
+ }
868
+ R.prototype.on = R.prototype.addEventListener = function(t, e) {
869
+ return this._callbacks = this._callbacks || {}, (this._callbacks[t] = this._callbacks[t] || []).push(e), this;
870
+ };
871
+ R.prototype.once = function(t, e) {
872
+ var s = this;
873
+ this._callbacks = this._callbacks || {};
874
+ function i() {
875
+ s.off(t, i), e.apply(this, arguments);
876
+ }
877
+ return i.fn = e, this.on(t, i), this;
878
+ };
879
+ R.prototype.off = R.prototype.removeListener = R.prototype.removeAllListeners = R.prototype.removeEventListener = function(t, e) {
880
+ if (this._callbacks = this._callbacks || {}, arguments.length == 0)
881
+ return this._callbacks = {}, this;
882
+ var s = this._callbacks[t];
883
+ if (!s) return this;
884
+ if (arguments.length == 1)
885
+ return delete this._callbacks[t], this;
886
+ for (var i, n = 0; n < s.length; n++)
887
+ if (i = s[n], i === e || i.fn === e) {
888
+ s.splice(n, 1);
889
+ break;
890
+ }
891
+ return this;
892
+ };
893
+ R.prototype.emit = function(t) {
894
+ this._callbacks = this._callbacks || {};
895
+ var e = [].slice.call(arguments, 1), s = this._callbacks[t];
896
+ if (s) {
897
+ s = s.slice(0);
898
+ for (var i = 0, n = s.length; i < n; ++i)
899
+ s[i].apply(this, e);
900
+ }
901
+ return this;
902
+ };
903
+ R.prototype.listeners = function(t) {
904
+ return this._callbacks = this._callbacks || {}, this._callbacks[t] || [];
905
+ };
906
+ R.prototype.hasListeners = function(t) {
907
+ return !!this.listeners(t).length;
908
+ };
909
+ var ft = rs;
910
+ function te() {
911
+ ft.call(this);
912
+ }
913
+ te.prototype = new ft();
914
+ var as = te;
915
+ te.Stream = te;
916
+ te.prototype.pipe = function(t, e) {
917
+ var s = this;
918
+ function i(h) {
919
+ t.writable && t.write(h) === !1 && s.pause && s.pause();
920
+ }
921
+ s.on("data", i);
922
+ function n() {
923
+ s.readable && s.resume && s.resume();
924
+ }
925
+ t.on("drain", n), !t._isStdio && (!e || e.end !== !1) && (s.on("end", o), s.on("close", c));
926
+ var r = !1;
927
+ function o() {
928
+ r || (r = !0, t.end());
929
+ }
930
+ function c() {
931
+ r || (r = !0, typeof t.destroy == "function" && t.destroy());
932
+ }
933
+ function _(h) {
934
+ if (d(), !this.hasListeners("error"))
935
+ throw h;
936
+ }
937
+ s.on("error", _), t.on("error", _);
938
+ function d() {
939
+ s.off("data", i), t.off("drain", n), s.off("end", o), s.off("close", c), s.off("error", _), t.off("error", _), s.off("end", d), s.off("close", d), t.off("end", d), t.off("close", d);
940
+ }
941
+ return s.on("end", d), s.on("close", d), t.on("end", d), t.on("close", d), t.emit("pipe", s), t;
942
+ };
943
+ var cs = Te, Ue = 128, hs = 127, ds = ~hs, ls = Math.pow(2, 31);
944
+ function Te(t, e, s) {
945
+ if (Number.MAX_SAFE_INTEGER && t > Number.MAX_SAFE_INTEGER)
946
+ throw Te.bytes = 0, new RangeError("Could not encode varint");
947
+ e = e || [], s = s || 0;
948
+ for (var i = s; t >= ls; )
949
+ e[s++] = t & 255 | Ue, t /= 128;
950
+ for (; t & ds; )
951
+ e[s++] = t & 255 | Ue, t >>>= 7;
952
+ return e[s] = t | 0, Te.bytes = s - i + 1, e;
953
+ }
954
+ var _s = Fe, fs = 128, He = 127;
955
+ function Fe(t, i) {
956
+ var s = 0, i = i || 0, n = 0, r = i, o, c = t.length;
957
+ do {
958
+ if (r >= c || n > 49)
959
+ throw Fe.bytes = 0, new RangeError("Could not decode varint");
960
+ o = t[r++], s += n < 28 ? (o & He) << n : (o & He) * Math.pow(2, n), n += 7;
961
+ } while (o >= fs);
962
+ return Fe.bytes = r - i, s;
963
+ }
964
+ var ps = Math.pow(2, 7), us = Math.pow(2, 14), gs = Math.pow(2, 21), ms = Math.pow(2, 28), Cs = Math.pow(2, 35), ws = Math.pow(2, 42), ys = Math.pow(2, 49), Ss = Math.pow(2, 56), bs = Math.pow(2, 63), vs = function(t) {
965
+ return t < ps ? 1 : t < us ? 2 : t < gs ? 3 : t < ms ? 4 : t < Cs ? 5 : t < ws ? 6 : t < ys ? 7 : t < Ss ? 8 : t < bs ? 9 : 10;
966
+ }, M = {
967
+ encode: cs,
968
+ decode: _s,
969
+ encodingLength: vs
970
+ }, V = "/home/runner/work/dxos/dxos/packages/core/mesh/teleport/src/control-extension.ts", Se = 1e4, Es = !1, Is = class {
971
+ constructor(t, e, s) {
972
+ this.opts = t, this.localPeerId = e, this.remotePeerId = s, this._ctx = new N({
973
+ onError: (i) => {
974
+ this._extensionContext.close(i);
975
+ }
976
+ }, {
977
+ F: V,
978
+ L: 30
979
+ }), this.onExtensionRegistered = new Tt();
980
+ }
981
+ async registerExtension(t) {
982
+ await this._rpc.rpc.Control.registerExtension({
983
+ name: t
984
+ });
985
+ }
986
+ async onOpen(t) {
987
+ this._extensionContext = t, this._rpc = Ft({
988
+ requested: {
989
+ Control: ce.getService("dxos.mesh.teleport.control.ControlService")
990
+ },
991
+ exposed: {
992
+ Control: ce.getService("dxos.mesh.teleport.control.ControlService")
993
+ },
994
+ handlers: {
995
+ Control: {
996
+ registerExtension: async (e) => {
997
+ this.onExtensionRegistered.call(e.name);
998
+ },
999
+ heartbeat: async (e) => ({
1000
+ requestTimestamp: e.requestTimestamp
1001
+ })
1002
+ }
1003
+ },
1004
+ port: await t.createPort("rpc", {
1005
+ contentType: 'application/x-protobuf; messageType="dxos.rpc.Message"'
1006
+ }),
1007
+ timeout: this.opts.heartbeatTimeout
1008
+ }), await this._rpc.open(), Ae(this._ctx, async () => {
1009
+ const e = /* @__PURE__ */ new Date();
1010
+ try {
1011
+ const s = await nt(this._rpc.rpc.Control.heartbeat({
1012
+ requestTimestamp: e
1013
+ }), this.opts.heartbeatTimeout), i = Date.now();
1014
+ s.requestTimestamp instanceof Date && i - s.requestTimestamp.getTime() > (Se < this.opts.heartbeatTimeout ? Se : this.opts.heartbeatTimeout / 2) && a.warn(`heartbeat RTT for Teleport > ${Se / 1e3}s`, {
1015
+ rtt: i - s.requestTimestamp.getTime(),
1016
+ localPeerId: this.localPeerId.truncate(),
1017
+ remotePeerId: this.remotePeerId.truncate()
1018
+ }, {
1019
+ F: V,
1020
+ L: 106,
1021
+ S: this,
1022
+ C: (n, r) => n(...r)
1023
+ });
1024
+ } catch (s) {
1025
+ const i = Date.now();
1026
+ if (s instanceof ht) {
1027
+ a("ignoring RpcClosedError in heartbeat", void 0, {
1028
+ F: V,
1029
+ L: 125,
1030
+ S: this,
1031
+ C: (n, r) => n(...r)
1032
+ }), this._extensionContext.close(s);
1033
+ return;
1034
+ }
1035
+ s instanceof At ? (a("timeout waiting for heartbeat response", {
1036
+ err: s,
1037
+ delay: i - e.getTime()
1038
+ }, {
1039
+ F: V,
1040
+ L: 130,
1041
+ S: this,
1042
+ C: (n, r) => n(...r)
1043
+ }), this.opts.onTimeout(s)) : (a.info("other error waiting for heartbeat response", {
1044
+ err: s,
1045
+ delay: i - e.getTime()
1046
+ }, {
1047
+ F: V,
1048
+ L: 133,
1049
+ S: this,
1050
+ C: (n, r) => n(...r)
1051
+ }), this.opts.onTimeout(s));
1052
+ }
1053
+ }, this.opts.heartbeatInterval);
1054
+ }
1055
+ async onClose(t) {
1056
+ await this._ctx.dispose(), await this._rpc.close();
1057
+ }
1058
+ async onAbort(t) {
1059
+ await this._ctx.dispose(), await this._rpc.abort();
1060
+ }
1061
+ }, ae = "/home/runner/work/dxos/dxos/packages/core/mesh/teleport/src/muxing/framer.ts", Q = 2, Ls = class {
1062
+ constructor() {
1063
+ this._messageCb = void 0, this._subscribeCb = void 0, this._buffer = void 0, this._sendCallbacks = [], this._bytesSent = 0, this._bytesReceived = 0, this._writable = !0, this.drain = new S(), this._stream = new se.Duplex({
1064
+ objectMode: !1,
1065
+ read: () => {
1066
+ this._processResponseQueue();
1067
+ },
1068
+ write: (t, e, s) => {
1069
+ f(!this._subscribeCb, "Internal Framer bug. Concurrent writes detected.", {
1070
+ F: ae,
1071
+ L: 40,
1072
+ S: this,
1073
+ A: [
1074
+ "!this._subscribeCb",
1075
+ "'Internal Framer bug. Concurrent writes detected.'"
1076
+ ]
1077
+ }), this._bytesReceived += t.length, this._buffer && this._buffer.length > 0 ? this._buffer = X.concat([
1078
+ this._buffer,
1079
+ t
1080
+ ]) : this._buffer = t, this._messageCb ? (this._popFrames(), s()) : this._subscribeCb = () => {
1081
+ this._popFrames(), this._subscribeCb = void 0, s();
1082
+ };
1083
+ }
1084
+ }), this.port = {
1085
+ send: (t) => new Promise((e) => {
1086
+ const s = Ts(t);
1087
+ this._bytesSent += s.length, this._writable = this._stream.push(s), this._writable ? e() : this._sendCallbacks.push(e);
1088
+ }),
1089
+ subscribe: (t) => {
1090
+ var e;
1091
+ return f(!this._messageCb, "Rpc port already has a message listener.", {
1092
+ F: ae,
1093
+ L: 79,
1094
+ S: this,
1095
+ A: [
1096
+ "!this._messageCb",
1097
+ "'Rpc port already has a message listener.'"
1098
+ ]
1099
+ }), this._messageCb = t, (e = this._subscribeCb) == null || e.call(this), () => {
1100
+ this._messageCb = void 0;
1101
+ };
1102
+ }
1103
+ };
1104
+ }
1105
+ get stream() {
1106
+ return this._stream;
1107
+ }
1108
+ get bytesSent() {
1109
+ return this._bytesSent;
1110
+ }
1111
+ get bytesReceived() {
1112
+ return this._bytesReceived;
1113
+ }
1114
+ get writable() {
1115
+ return this._writable;
1116
+ }
1117
+ _processResponseQueue() {
1118
+ const t = this._sendCallbacks;
1119
+ this._sendCallbacks = [], this._writable = !0, this.drain.emit(), t.forEach((e) => e());
1120
+ }
1121
+ /**
1122
+ * Attempts to pop frames from the buffer and call the message callback.
1123
+ */
1124
+ _popFrames() {
1125
+ let t = 0;
1126
+ for (; t < this._buffer.length; ) {
1127
+ const e = Rs(this._buffer, t);
1128
+ if (!e)
1129
+ break;
1130
+ t += e.bytesConsumed, this._messageCb(e.payload);
1131
+ }
1132
+ t < this._buffer.length ? this._buffer = this._buffer.subarray(t) : this._buffer = void 0;
1133
+ }
1134
+ destroy() {
1135
+ this._stream.readableLength > 0 && a("framer destroyed while there are still read bytes in the buffer.", void 0, {
1136
+ F: ae,
1137
+ L: 140,
1138
+ S: this,
1139
+ C: (t, e) => t(...e)
1140
+ }), this._stream.writableLength > 0 && a.warn("framer destroyed while there are still write bytes in the buffer.", void 0, {
1141
+ F: ae,
1142
+ L: 143,
1143
+ S: this,
1144
+ C: (t, e) => t(...e)
1145
+ }), this._stream.destroy();
1146
+ }
1147
+ }, Rs = (t, e) => {
1148
+ if (t.length < e + Q)
1149
+ return;
1150
+ const s = t.readUInt16BE(e), i = Q + s;
1151
+ return t.length < e + i ? void 0 : {
1152
+ payload: t.subarray(e + Q, e + i),
1153
+ bytesConsumed: i
1154
+ };
1155
+ }, Ts = (t) => {
1156
+ const e = X.allocUnsafe(Q + t.length);
1157
+ return e.writeUInt16BE(t.length, 0), e.set(t, Q), e;
1158
+ }, z = "/home/runner/work/dxos/dxos/packages/core/mesh/teleport/src/muxing/balancer.ts", Ge = 8192, Fs = class {
1159
+ constructor(t) {
1160
+ this._sysChannelId = t, this._lastCallerIndex = 0, this._channels = [], this._framer = new Ls(), this._sendBuffers = /* @__PURE__ */ new Map(), this._receiveBuffers = /* @__PURE__ */ new Map(), this._sending = !1, this.incomingData = new S(), this.stream = this._framer.stream, this._channels.push(t), this._framer.port.subscribe(this._processIncomingMessage.bind(this));
1161
+ }
1162
+ get bytesSent() {
1163
+ return this._framer.bytesSent;
1164
+ }
1165
+ get bytesReceived() {
1166
+ return this._framer.bytesReceived;
1167
+ }
1168
+ get buffersCount() {
1169
+ return this._sendBuffers.size;
1170
+ }
1171
+ addChannel(t) {
1172
+ this._channels.push(t);
1173
+ }
1174
+ pushData(t, e, s) {
1175
+ this._enqueueChunk(t, e, s), this._sendChunks().catch((i) => a.catch(i, void 0, {
1176
+ F: z,
1177
+ L: 75,
1178
+ S: this,
1179
+ C: (n, r) => n(...r)
1180
+ }));
1181
+ }
1182
+ destroy() {
1183
+ this._sendBuffers.size !== 0 && a.info("destroying balancer with pending calls", void 0, {
1184
+ F: z,
1185
+ L: 80,
1186
+ S: this,
1187
+ C: (t, e) => t(...e)
1188
+ }), this._sendBuffers.clear(), this._framer.destroy();
1189
+ }
1190
+ _processIncomingMessage(t) {
1191
+ const { channelId: e, dataLength: s, chunk: i } = xs(t, (n) => !this._receiveBuffers.has(n));
1192
+ if (!this._receiveBuffers.has(e))
1193
+ i.length < s ? this._receiveBuffers.set(e, {
1194
+ buffer: X.from(i),
1195
+ msgLength: s
1196
+ }) : this.incomingData.emit(i);
1197
+ else {
1198
+ const n = this._receiveBuffers.get(e);
1199
+ if (n.buffer = X.concat([
1200
+ n.buffer,
1201
+ i
1202
+ ]), n.buffer.length < n.msgLength)
1203
+ return;
1204
+ const r = n.buffer;
1205
+ this._receiveBuffers.delete(e), this.incomingData.emit(r);
1206
+ }
1207
+ }
1208
+ _getNextCallerId() {
1209
+ if (this._sendBuffers.has(this._sysChannelId))
1210
+ return this._sysChannelId;
1211
+ const t = this._lastCallerIndex;
1212
+ return this._lastCallerIndex = (this._lastCallerIndex + 1) % this._channels.length, this._channels[t];
1213
+ }
1214
+ _enqueueChunk(t, e, s) {
1215
+ if (!this._channels.includes(s))
1216
+ throw new Error(`Unknown channel ${s}`);
1217
+ this._sendBuffers.has(s) || this._sendBuffers.set(s, []);
1218
+ const i = this._sendBuffers.get(s), n = [];
1219
+ for (let r = 0; r < t.length; r += Ge)
1220
+ n.push(t.subarray(r, r + Ge));
1221
+ n.forEach((r, o) => {
1222
+ const c = As({
1223
+ chunk: r,
1224
+ channelId: s,
1225
+ dataLength: o === 0 ? t.length : void 0
1226
+ });
1227
+ i.push({
1228
+ msg: c,
1229
+ trigger: o === n.length - 1 ? e : void 0
1230
+ });
1231
+ });
1232
+ }
1233
+ // get the next chunk or null if there are no chunks remaining
1234
+ _getNextChunk() {
1235
+ let t;
1236
+ for (; this._sendBuffers.size > 0; ) {
1237
+ const e = this._getNextCallerId(), s = this._sendBuffers.get(e);
1238
+ if (s && (t = s.shift(), !!t))
1239
+ return s.length === 0 && this._sendBuffers.delete(e), t;
1240
+ }
1241
+ return null;
1242
+ }
1243
+ async _sendChunks() {
1244
+ var e, s;
1245
+ if (this._sending)
1246
+ return;
1247
+ this._sending = !0;
1248
+ let t;
1249
+ for (t = this._getNextChunk(); t; ) {
1250
+ this._framer.writable || (a("PAUSE for drain", void 0, {
1251
+ F: z,
1252
+ L: 179,
1253
+ S: this,
1254
+ C: (i, n) => i(...n)
1255
+ }), await this._framer.drain.waitForCount(1), a("RESUME for drain", void 0, {
1256
+ F: z,
1257
+ L: 181,
1258
+ S: this,
1259
+ C: (i, n) => i(...n)
1260
+ }));
1261
+ try {
1262
+ await this._framer.port.send(t.msg), (e = t.trigger) == null || e.wake();
1263
+ } catch (i) {
1264
+ a("Error sending chunk", {
1265
+ err: i
1266
+ }, {
1267
+ F: z,
1268
+ L: 187,
1269
+ S: this,
1270
+ C: (n, r) => n(...r)
1271
+ }), (s = t.trigger) == null || s.throw(i);
1272
+ }
1273
+ t = this._getNextChunk();
1274
+ }
1275
+ f(this._sendBuffers.size === 0, "sendBuffers not empty", {
1276
+ F: z,
1277
+ L: 192,
1278
+ S: this,
1279
+ A: [
1280
+ "this._sendBuffers.size === 0",
1281
+ "'sendBuffers not empty'"
1282
+ ]
1283
+ }), this._sending = !1;
1284
+ }
1285
+ }, As = ({ channelId: t, dataLength: e, chunk: s }) => {
1286
+ const i = M.encodingLength(t), n = e ? M.encodingLength(e) : 0, r = X.allocUnsafe(i + n + s.length);
1287
+ return M.encode(t, r), e && M.encode(e, r, i), r.set(s, i + n), r;
1288
+ }, xs = (t, e) => {
1289
+ const s = M.decode(t);
1290
+ let i, n = M.decode.bytes;
1291
+ e(s) && (i = M.decode(t, n), n += M.decode.bytes);
1292
+ const r = t.subarray(n);
1293
+ return {
1294
+ channelId: s,
1295
+ dataLength: i,
1296
+ chunk: r
1297
+ };
1298
+ };
1299
+ function Ns(t, e, s, i) {
1300
+ var n = arguments.length, r = n < 3 ? e : i === null ? i = Object.getOwnPropertyDescriptor(e, s) : i, o;
1301
+ if (typeof Reflect == "object" && typeof Reflect.decorate == "function")
1302
+ r = Reflect.decorate(t, e, s, i);
1303
+ else
1304
+ for (var c = t.length - 1; c >= 0; c--)
1305
+ (o = t[c]) && (r = (n < 3 ? o(r) : n > 3 ? o(e, s, r) : o(e, s)) || r);
1306
+ return n > 3 && r && Object.defineProperty(e, s, r), r;
1307
+ }
1308
+ var v = "/home/runner/work/dxos/dxos/packages/core/mesh/teleport/src/muxing/muxer.ts", ze = ce.getCodecForType("dxos.mesh.muxer.Command"), Os = 6e4, Ps = 5e3, Ds = 1e3, Ye = 1e6, Z = 0, ks = 3e3, pt = class {
1309
+ constructor() {
1310
+ this._balancer = new Fs(Z), this._channelsByLocalId = /* @__PURE__ */ new Map(), this._channelsByTag = /* @__PURE__ */ new Map(), this._ctx = new N(void 0, {
1311
+ F: v,
1312
+ L: 107
1313
+ }), this._nextId = 1, this._closing = !1, this._destroying = !1, this._disposed = !1, this._lastStats = void 0, this._lastChannelStats = /* @__PURE__ */ new Map(), this.afterClosed = new S(), this.statsUpdated = new S(), this.stream = this._balancer.stream, this._balancer.incomingData.on(async (t) => {
1314
+ await this._handleCommand(ze.decode(t));
1315
+ });
1316
+ }
1317
+ setSessionId(t) {
1318
+ this._sessionId = t;
1319
+ }
1320
+ get sessionIdString() {
1321
+ return this._sessionId ? this._sessionId.truncate() : "none";
1322
+ }
1323
+ /**
1324
+ * Creates a duplex Node.js-style stream.
1325
+ * The remote peer is expected to call `createStream` with the same tag.
1326
+ * The stream is immediately readable and writable.
1327
+ * NOTE: The data will be buffered until the stream is opened remotely with the same tag (may cause a memory leak).
1328
+ */
1329
+ async createStream(t, e = {}) {
1330
+ const s = this._getOrCreateStream({
1331
+ tag: t,
1332
+ contentType: e.contentType
1333
+ });
1334
+ f(!s.push, `Channel already open: ${t}`, {
1335
+ F: v,
1336
+ L: 151,
1337
+ S: this,
1338
+ A: [
1339
+ "!channel.push",
1340
+ "`Channel already open: ${tag}`"
1341
+ ]
1342
+ });
1343
+ const i = new se.Duplex({
1344
+ write: (n, r, o) => {
1345
+ this._sendData(s, n).then(() => o()).catch(o);
1346
+ },
1347
+ read: () => {
1348
+ }
1349
+ });
1350
+ s.push = (n) => {
1351
+ s.stats.bytesReceived += n.length, i.push(n);
1352
+ }, s.destroy = (n) => {
1353
+ n && i.listeners("error").length > 0 ? i.destroy(n) : i.destroy();
1354
+ };
1355
+ try {
1356
+ await this._sendCommand({
1357
+ openChannel: {
1358
+ id: s.id,
1359
+ tag: s.tag,
1360
+ contentType: s.contentType
1361
+ }
1362
+ }, Z);
1363
+ } catch (n) {
1364
+ throw this._destroyChannel(s, n), n;
1365
+ }
1366
+ return i;
1367
+ }
1368
+ /**
1369
+ * Creates an RPC port.
1370
+ * The remote peer is expected to call `createPort` with the same tag.
1371
+ * The port is immediately usable.
1372
+ * NOTE: The data will be buffered until the stream is opened remotely with the same tag (may cause a memory leak).
1373
+ */
1374
+ async createPort(t, e = {}) {
1375
+ const s = this._getOrCreateStream({
1376
+ tag: t,
1377
+ contentType: e.contentType
1378
+ });
1379
+ f(!s.push, `Channel already open: ${t}`, {
1380
+ F: v,
1381
+ L: 211,
1382
+ S: this,
1383
+ A: [
1384
+ "!channel.push",
1385
+ "`Channel already open: ${tag}`"
1386
+ ]
1387
+ });
1388
+ let i = [], n;
1389
+ s.push = (o) => {
1390
+ s.stats.bytesReceived += o.length, n ? n(o) : i.push(o);
1391
+ };
1392
+ const r = {
1393
+ send: async (o, c) => {
1394
+ await this._sendData(s, o, c);
1395
+ },
1396
+ subscribe: (o) => {
1397
+ f(!n, "Only one subscriber is allowed", {
1398
+ F: v,
1399
+ L: 233,
1400
+ S: this,
1401
+ A: [
1402
+ "!callback",
1403
+ "'Only one subscriber is allowed'"
1404
+ ]
1405
+ }), n = o;
1406
+ for (const c of i)
1407
+ o(c);
1408
+ i = [];
1409
+ }
1410
+ };
1411
+ try {
1412
+ await this._sendCommand({
1413
+ openChannel: {
1414
+ id: s.id,
1415
+ tag: s.tag,
1416
+ contentType: s.contentType
1417
+ }
1418
+ }, Z);
1419
+ } catch (o) {
1420
+ throw this._destroyChannel(s, o), o;
1421
+ }
1422
+ return r;
1423
+ }
1424
+ // initiate graceful close
1425
+ async close(t) {
1426
+ if (this._destroying) {
1427
+ a("already destroying, ignoring graceful close request", void 0, {
1428
+ F: v,
1429
+ L: 266,
1430
+ S: this,
1431
+ C: (e, s) => e(...s)
1432
+ });
1433
+ return;
1434
+ }
1435
+ if (this._closing) {
1436
+ a("already closing, ignoring graceful close request", void 0, {
1437
+ F: v,
1438
+ L: 270,
1439
+ S: this,
1440
+ C: (e, s) => e(...s)
1441
+ });
1442
+ return;
1443
+ }
1444
+ this._closing = !0, await this._sendCommand({
1445
+ close: {
1446
+ error: t == null ? void 0 : t.message
1447
+ }
1448
+ }, Z, Ps).catch(async (e) => {
1449
+ a("error sending close command", {
1450
+ err: e
1451
+ }, {
1452
+ F: v,
1453
+ L: 285,
1454
+ S: this,
1455
+ C: (s, i) => s(...i)
1456
+ }), await this._dispose(e);
1457
+ }), await nt(this._dispose(t), ks, new le("gracefully closing muxer"));
1458
+ }
1459
+ // force close without confirmation
1460
+ async destroy(t) {
1461
+ if (this._destroying) {
1462
+ a("already destroying, ignoring destroy request", void 0, {
1463
+ F: v,
1464
+ L: 298,
1465
+ S: this,
1466
+ C: (e, s) => e(...s)
1467
+ });
1468
+ return;
1469
+ }
1470
+ this._destroying = !0, this._ctx.dispose(), this._closing ? (a("destroy cancelling graceful close", void 0, {
1471
+ F: v,
1472
+ L: 304,
1473
+ S: this,
1474
+ C: (e, s) => e(...s)
1475
+ }), this._closing = !1) : await this._sendCommand({
1476
+ close: {
1477
+ error: t == null ? void 0 : t.message
1478
+ }
1479
+ }, Z).catch(async (e) => {
1480
+ a("error sending courtesy close command", {
1481
+ err: e
1482
+ }, {
1483
+ F: v,
1484
+ L: 317,
1485
+ S: this,
1486
+ C: (s, i) => s(...i)
1487
+ });
1488
+ }), this._dispose(t).catch((e) => {
1489
+ a("error disposing after destroy", {
1490
+ err: e
1491
+ }, {
1492
+ F: v,
1493
+ L: 322,
1494
+ S: this,
1495
+ C: (s, i) => s(...i)
1496
+ });
1497
+ });
1498
+ }
1499
+ // complete the termination, graceful or otherwise
1500
+ async _dispose(t) {
1501
+ var e;
1502
+ if (this._disposed) {
1503
+ a("already destroyed, ignoring dispose request", void 0, {
1504
+ F: v,
1505
+ L: 330,
1506
+ S: this,
1507
+ C: (s, i) => s(...i)
1508
+ });
1509
+ return;
1510
+ }
1511
+ this._ctx.dispose(), await this._balancer.destroy();
1512
+ for (const s of this._channelsByTag.values())
1513
+ (e = s.destroy) == null || e.call(s, t);
1514
+ this._disposed = !0, await this._emitStats(), this.afterClosed.emit(t), this._channelsByLocalId.clear(), this._channelsByTag.clear();
1515
+ }
1516
+ async _handleCommand(t) {
1517
+ if (this._disposed) {
1518
+ a.warn("Received command after disposed", {
1519
+ cmd: t
1520
+ }, {
1521
+ F: v,
1522
+ L: 353,
1523
+ S: this,
1524
+ C: (e, s) => e(...s)
1525
+ });
1526
+ return;
1527
+ }
1528
+ if (t.close) {
1529
+ this._closing ? a("received close from peer, already closing", void 0, {
1530
+ F: v,
1531
+ L: 362,
1532
+ S: this,
1533
+ C: (e, s) => e(...s)
1534
+ }) : (a("received peer close, initiating my own graceful close", void 0, {
1535
+ F: v,
1536
+ L: 359,
1537
+ S: this,
1538
+ C: (e, s) => e(...s)
1539
+ }), await this.close(new Error("received peer close")));
1540
+ return;
1541
+ }
1542
+ if (t.openChannel) {
1543
+ const e = this._getOrCreateStream({
1544
+ tag: t.openChannel.tag,
1545
+ contentType: t.openChannel.contentType
1546
+ });
1547
+ e.remoteId = t.openChannel.id;
1548
+ for (const s of e.buffer)
1549
+ await this._sendCommand({
1550
+ data: {
1551
+ channelId: e.remoteId,
1552
+ data: s
1553
+ }
1554
+ }, e.id);
1555
+ e.buffer = [];
1556
+ } else if (t.data) {
1557
+ const e = this._channelsByLocalId.get(t.data.channelId) ?? rt();
1558
+ if (!e.push) {
1559
+ a.warn("Received data for channel before it was opened", {
1560
+ tag: e.tag
1561
+ }, {
1562
+ F: v,
1563
+ L: 391,
1564
+ S: this,
1565
+ C: (s, i) => s(...i)
1566
+ });
1567
+ return;
1568
+ }
1569
+ e.push(t.data.data);
1570
+ }
1571
+ }
1572
+ async _sendCommand(t, e = -1, s = Os) {
1573
+ if (!this._disposed)
1574
+ try {
1575
+ const i = new ee();
1576
+ this._balancer.pushData(ze.encode(t), i, e), await i.wait({
1577
+ timeout: s
1578
+ });
1579
+ } catch (i) {
1580
+ await this.destroy(i);
1581
+ }
1582
+ }
1583
+ _getOrCreateStream(t) {
1584
+ this._channelsByTag.size === 0 && Ae(this._ctx, async () => this._emitStats(), Ds);
1585
+ let e = this._channelsByTag.get(t.tag);
1586
+ return e || (e = {
1587
+ id: this._nextId++,
1588
+ remoteId: null,
1589
+ tag: t.tag,
1590
+ contentType: t.contentType,
1591
+ buffer: [],
1592
+ push: null,
1593
+ destroy: null,
1594
+ stats: {
1595
+ bytesSent: 0,
1596
+ bytesReceived: 0
1597
+ }
1598
+ }, this._channelsByTag.set(e.tag, e), this._channelsByLocalId.set(e.id, e), this._balancer.addChannel(e.id)), e;
1599
+ }
1600
+ async _sendData(t, e, s) {
1601
+ if (e.length > Ye && a.warn("frame size exceeds maximum safe value", {
1602
+ size: e.length,
1603
+ threshold: Ye
1604
+ }, {
1605
+ F: v,
1606
+ L: 441,
1607
+ S: this,
1608
+ C: (i, n) => i(...n)
1609
+ }), t.stats.bytesSent += e.length, t.remoteId === null) {
1610
+ t.buffer.push(e);
1611
+ return;
1612
+ }
1613
+ await this._sendCommand({
1614
+ data: {
1615
+ channelId: t.remoteId,
1616
+ data: e
1617
+ }
1618
+ }, t.id, s);
1619
+ }
1620
+ _destroyChannel(t, e) {
1621
+ t.destroy && t.destroy(e), this._channelsByLocalId.delete(t.id), this._channelsByTag.delete(t.tag);
1622
+ }
1623
+ async _emitStats() {
1624
+ if (this._disposed || this._destroying) {
1625
+ if (!this._lastStats)
1626
+ return;
1627
+ const r = this._lastStats;
1628
+ this._lastStats = void 0, r.readBufferSize = 0, r.writeBufferSize = 0;
1629
+ for (const o of r.channels)
1630
+ o.writeBufferSize = 0;
1631
+ this.statsUpdated.emit(r), this._lastChannelStats.clear();
1632
+ return;
1633
+ }
1634
+ const t = this._balancer.bytesSent, e = this._balancer.bytesReceived, s = Date.now(), i = this._lastStats ? (s - this._lastStats.timestamp) / 1e3 : 0, n = (r, o) => o ? {
1635
+ bytesSentRate: i ? (r.bytesSent - o.bytesSent) / i : void 0,
1636
+ bytesReceivedRate: i ? (r.bytesReceived - o.bytesReceived) / i : void 0
1637
+ } : {};
1638
+ this._lastStats = {
1639
+ timestamp: s,
1640
+ channels: Array.from(this._channelsByTag.values()).map((r) => {
1641
+ const o = {
1642
+ id: r.id,
1643
+ tag: r.tag,
1644
+ contentType: r.contentType,
1645
+ writeBufferSize: r.buffer.length,
1646
+ bytesSent: r.stats.bytesSent,
1647
+ bytesReceived: r.stats.bytesReceived,
1648
+ ...n(r.stats, this._lastChannelStats.get(r.id))
1649
+ };
1650
+ return this._lastChannelStats.set(r.id, o), o;
1651
+ }),
1652
+ bytesSent: t,
1653
+ bytesReceived: e,
1654
+ ...n({
1655
+ bytesSent: t,
1656
+ bytesReceived: e
1657
+ }, this._lastStats),
1658
+ readBufferSize: this._balancer.stream.readableLength,
1659
+ writeBufferSize: this._balancer.stream.writableLength
1660
+ }, this.statsUpdated.emit(this._lastStats);
1661
+ }
1662
+ };
1663
+ Ns([
1664
+ q
1665
+ ], pt.prototype, "sessionIdString", null);
1666
+ function Ne(t, e, s, i) {
1667
+ var n = arguments.length, r = n < 3 ? e : i === null ? i = Object.getOwnPropertyDescriptor(e, s) : i, o;
1668
+ if (typeof Reflect == "object" && typeof Reflect.decorate == "function")
1669
+ r = Reflect.decorate(t, e, s, i);
1670
+ else
1671
+ for (var c = t.length - 1; c >= 0; c--)
1672
+ (o = t[c]) && (r = (n < 3 ? o(r) : n > 3 ? o(e, s, r) : o(e, s)) || r);
1673
+ return n > 3 && r && Object.defineProperty(e, s, r), r;
1674
+ }
1675
+ var y = "/home/runner/work/dxos/dxos/packages/core/mesh/teleport/src/teleport.ts", Ms = 1e4, Bs = 6e4, Oe = class {
1676
+ constructor({ initiator: t, localPeerId: e, remotePeerId: s, ...i }) {
1677
+ this._ctx = new N({
1678
+ onError: (n) => {
1679
+ this.destroy(n).catch(() => {
1680
+ a.error("Error during destroy", n, {
1681
+ F: y,
1682
+ L: 41,
1683
+ S: this,
1684
+ C: (r, o) => r(...o)
1685
+ });
1686
+ });
1687
+ }
1688
+ }, {
1689
+ F: y,
1690
+ L: 38
1691
+ }), this._muxer = new pt(), this._extensions = /* @__PURE__ */ new Map(), this._remoteExtensions = /* @__PURE__ */ new Set(), this._open = !1, this._destroying = !1, this._aborting = !1, f(typeof t == "boolean", void 0, {
1692
+ F: y,
1693
+ L: 62,
1694
+ S: this,
1695
+ A: [
1696
+ "typeof initiator === 'boolean'",
1697
+ ""
1698
+ ]
1699
+ }), f(m.isPublicKey(e), void 0, {
1700
+ F: y,
1701
+ L: 63,
1702
+ S: this,
1703
+ A: [
1704
+ "PublicKey.isPublicKey(localPeerId)",
1705
+ ""
1706
+ ]
1707
+ }), f(m.isPublicKey(s), void 0, {
1708
+ F: y,
1709
+ L: 64,
1710
+ S: this,
1711
+ A: [
1712
+ "PublicKey.isPublicKey(remotePeerId)",
1713
+ ""
1714
+ ]
1715
+ }), this.initiator = t, this.localPeerId = e, this.remotePeerId = s, this._control = new Is({
1716
+ heartbeatInterval: i.controlHeartbeatInterval ?? Ms,
1717
+ heartbeatTimeout: i.controlHeartbeatTimeout ?? Bs,
1718
+ onTimeout: () => {
1719
+ this._destroying || this._aborting || (a.info("abort teleport due to onTimeout in ControlExtension", void 0, {
1720
+ F: y,
1721
+ L: 77,
1722
+ S: this,
1723
+ C: (n, r) => n(...r)
1724
+ }), this.abort(new le("control extension")).catch((n) => a.catch(n, void 0, {
1725
+ F: y,
1726
+ L: 78,
1727
+ S: this,
1728
+ C: (r, o) => r(...o)
1729
+ })));
1730
+ }
1731
+ }, this.localPeerId, this.remotePeerId), this._control.onExtensionRegistered.set(async (n) => {
1732
+ if (a("remote extension", {
1733
+ name: n
1734
+ }, {
1735
+ F: y,
1736
+ L: 86,
1737
+ S: this,
1738
+ C: (r, o) => r(...o)
1739
+ }), f(!this._remoteExtensions.has(n), "Remote extension already exists", {
1740
+ F: y,
1741
+ L: 87,
1742
+ S: this,
1743
+ A: [
1744
+ "!this._remoteExtensions.has(name)",
1745
+ "'Remote extension already exists'"
1746
+ ]
1747
+ }), this._remoteExtensions.add(n), this._extensions.has(n))
1748
+ try {
1749
+ await this._openExtension(n);
1750
+ } catch (r) {
1751
+ await this.destroy(r);
1752
+ }
1753
+ }), this._muxer.stream.on("close", async () => {
1754
+ if (this._destroying || this._aborting) {
1755
+ a("destroy teleport due to muxer stream close, skipping due to already destroying/aborting", void 0, {
1756
+ F: y,
1757
+ L: 103,
1758
+ S: this,
1759
+ C: (n, r) => n(...r)
1760
+ });
1761
+ return;
1762
+ }
1763
+ await this.destroy();
1764
+ }), this._muxer.stream.on("error", async (n) => {
1765
+ await this.destroy(n);
1766
+ }), this._muxer.statsUpdated.on((n) => {
1767
+ a.trace("dxos.mesh.teleport.stats", {
1768
+ localPeerId: e,
1769
+ remotePeerId: s,
1770
+ bytesSent: n.bytesSent,
1771
+ bytesSentRate: n.bytesSentRate,
1772
+ bytesReceived: n.bytesReceived,
1773
+ bytesReceivedRate: n.bytesReceivedRate,
1774
+ channels: n.channels
1775
+ }, {
1776
+ F: y,
1777
+ L: 116,
1778
+ S: this,
1779
+ C: (r, o) => r(...o)
1780
+ });
1781
+ });
1782
+ }
1783
+ get isOpen() {
1784
+ return this._open;
1785
+ }
1786
+ get sessionIdString() {
1787
+ return this._sessionId ? this._sessionId.truncate() : "none";
1788
+ }
1789
+ get stream() {
1790
+ return this._muxer.stream;
1791
+ }
1792
+ get stats() {
1793
+ return this._muxer.statsUpdated;
1794
+ }
1795
+ /**
1796
+ * Blocks until the handshake is complete.
1797
+ */
1798
+ async open(t = m.random()) {
1799
+ this._sessionId = t, a("open", void 0, {
1800
+ F: y,
1801
+ L: 150,
1802
+ S: this,
1803
+ C: (e, s) => e(...s)
1804
+ }), this._setExtension("dxos.mesh.teleport.control", this._control), await this._openExtension("dxos.mesh.teleport.control"), this._open = !0, this._muxer.setSessionId(t);
1805
+ }
1806
+ async close(t) {
1807
+ await this.destroy(t);
1808
+ }
1809
+ async abort(t) {
1810
+ if (!(this._aborting || this._destroying) && (this._aborting = !0, this._open = !1, !this._ctx.disposed)) {
1811
+ await this._ctx.dispose();
1812
+ for (const e of this._extensions.values())
1813
+ try {
1814
+ await e.onAbort(t);
1815
+ } catch (s) {
1816
+ a.catch(s, void 0, {
1817
+ F: y,
1818
+ L: 180,
1819
+ S: this,
1820
+ C: (i, n) => i(...n)
1821
+ });
1822
+ }
1823
+ await this._muxer.destroy(t);
1824
+ }
1825
+ }
1826
+ async destroy(t) {
1827
+ if (!(this._destroying || this._aborting) && (a("destroying teleport...", {
1828
+ extensionsCount: this._extensions.size
1829
+ }, {
1830
+ F: y,
1831
+ L: 193,
1832
+ S: this,
1833
+ C: (e, s) => e(...s)
1834
+ }), this._destroying = !0, this._open = !1, !this._ctx.disposed)) {
1835
+ await this._ctx.dispose();
1836
+ for (const e of this._extensions.values())
1837
+ try {
1838
+ a("destroying extension", {
1839
+ name: e.constructor.name
1840
+ }, {
1841
+ F: y,
1842
+ L: 205,
1843
+ S: this,
1844
+ C: (s, i) => s(...i)
1845
+ }), await e.onClose(t), a("destroyed extension", {
1846
+ name: e.constructor.name
1847
+ }, {
1848
+ F: y,
1849
+ L: 207,
1850
+ S: this,
1851
+ C: (s, i) => s(...i)
1852
+ });
1853
+ } catch (s) {
1854
+ a.catch(s, void 0, {
1855
+ F: y,
1856
+ L: 209,
1857
+ S: this,
1858
+ C: (i, n) => i(...n)
1859
+ });
1860
+ }
1861
+ await this._muxer.close(), a("teleport destroyed", void 0, {
1862
+ F: y,
1863
+ L: 214,
1864
+ S: this,
1865
+ C: (e, s) => e(...s)
1866
+ });
1867
+ }
1868
+ }
1869
+ addExtension(t, e) {
1870
+ if (!this._open)
1871
+ throw new Error("Not open");
1872
+ a("addExtension", {
1873
+ name: t
1874
+ }, {
1875
+ F: y,
1876
+ L: 222,
1877
+ S: this,
1878
+ C: (s, i) => s(...i)
1879
+ }), this._setExtension(t, e), W(this._ctx, async () => {
1880
+ try {
1881
+ await this._control.registerExtension(t);
1882
+ } catch (s) {
1883
+ if (s instanceof ht)
1884
+ return;
1885
+ throw s;
1886
+ }
1887
+ }), this._remoteExtensions.has(t) && W(this._ctx, async () => {
1888
+ await this._openExtension(t);
1889
+ });
1890
+ }
1891
+ _setExtension(t, e) {
1892
+ f(!t.includes("/"), "Invalid extension name", {
1893
+ F: y,
1894
+ L: 246,
1895
+ S: this,
1896
+ A: [
1897
+ "!extensionName.includes('/')",
1898
+ "'Invalid extension name'"
1899
+ ]
1900
+ }), f(!this._extensions.has(t), "Extension already exists", {
1901
+ F: y,
1902
+ L: 247,
1903
+ S: this,
1904
+ A: [
1905
+ "!this._extensions.has(extensionName)",
1906
+ "'Extension already exists'"
1907
+ ]
1908
+ }), this._extensions.set(t, e);
1909
+ }
1910
+ async _openExtension(t) {
1911
+ a("open extension", {
1912
+ extensionName: t
1913
+ }, {
1914
+ F: y,
1915
+ L: 252,
1916
+ S: this,
1917
+ C: (i, n) => i(...n)
1918
+ });
1919
+ const e = this._extensions.get(t) ?? rt(), s = {
1920
+ initiator: this.initiator,
1921
+ localPeerId: this.localPeerId,
1922
+ remotePeerId: this.remotePeerId,
1923
+ createPort: async (i, n) => (f(!i.includes("/"), "Invalid channel name", {
1924
+ F: y,
1925
+ L: 260,
1926
+ S: this,
1927
+ A: [
1928
+ "!channelName.includes('/')",
1929
+ "'Invalid channel name'"
1930
+ ]
1931
+ }), this._muxer.createPort(`${t}/${i}`, n)),
1932
+ createStream: async (i, n) => (f(!i.includes("/"), "Invalid channel name", {
1933
+ F: y,
1934
+ L: 264,
1935
+ S: this,
1936
+ A: [
1937
+ "!channelName.includes('/')",
1938
+ "'Invalid channel name'"
1939
+ ]
1940
+ }), this._muxer.createStream(`${t}/${i}`, n)),
1941
+ close: (i) => {
1942
+ Rt(this._ctx, async () => {
1943
+ await this.close(i);
1944
+ });
1945
+ }
1946
+ };
1947
+ await e.onOpen(s), a("extension opened", {
1948
+ extensionName: t
1949
+ }, {
1950
+ F: y,
1951
+ L: 275,
1952
+ S: this,
1953
+ C: (i, n) => i(...n)
1954
+ });
1955
+ }
1956
+ };
1957
+ Ne([
1958
+ q
1959
+ ], Oe.prototype, "sessionIdString", null);
1960
+ Ne([
1961
+ F
1962
+ ], Oe.prototype, "abort", null);
1963
+ Ne([
1964
+ F
1965
+ ], Oe.prototype, "destroy", null);
1966
+ var $s = /* @__PURE__ */ ((t) => typeof require < "u" ? require : typeof Proxy < "u" ? new Proxy(t, {
1967
+ get: (e, s) => (typeof require < "u" ? require : e)[s]
1968
+ }) : t)(function(t) {
1969
+ if (typeof require < "u")
1970
+ return require.apply(this, arguments);
1971
+ throw Error('Dynamic require of "' + t + '" is not supported');
1972
+ });
1973
+ function Pe(t, e, s, i) {
1974
+ var n = arguments.length, r = n < 3 ? e : i === null ? i = Object.getOwnPropertyDescriptor(e, s) : i, o;
1975
+ if (typeof Reflect == "object" && typeof Reflect.decorate == "function")
1976
+ r = Reflect.decorate(t, e, s, i);
1977
+ else
1978
+ for (var c = t.length - 1; c >= 0; c--)
1979
+ (o = t[c]) && (r = (n < 3 ? o(r) : n > 3 ? o(e, s, r) : o(e, s)) || r);
1980
+ return n > 3 && r && Object.defineProperty(e, s, r), r;
1981
+ }
1982
+ var p = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/swarm/connection.ts", qs = 10, be = 1e4, js = 5e3, Us = 300, P;
1983
+ (function(t) {
1984
+ t.CREATED = "CREATED", t.INITIAL = "INITIAL", t.CONNECTING = "CONNECTING", t.CONNECTED = "CONNECTED", t.CLOSING = "CLOSING", t.CLOSED = "CLOSED", t.ABORTING = "ABORTING", t.ABORTED = "ABORTED";
1985
+ })(P || (P = {}));
1986
+ var fe = class {
1987
+ constructor(t, e, s, i, n, r, o, c, _) {
1988
+ this.topic = t, this.ownId = e, this.remoteId = s, this.sessionId = i, this.initiator = n, this._signalMessaging = r, this._protocol = o, this._transportFactory = c, this._callbacks = _, this._ctx = new N(void 0, {
1989
+ F: p,
1990
+ L: 100
1991
+ }), this.connectedTimeoutContext = new N(void 0, {
1992
+ F: p,
1993
+ L: 101
1994
+ }), this._protocolClosed = new ee(), this._transportClosed = new ee(), this._state = "CREATED", this._incomingSignalBuffer = [], this._outgoingSignalBuffer = [], this.stateChanged = new S(), this.errors = new ie(), this._instanceId = m.random().toHex(), this.transportStats = new S(), this._signalSendTask = new at(this._ctx, async () => {
1995
+ await this._flushSignalBuffer();
1996
+ }), this._signallingDelay = qs, a.trace("dxos.mesh.connection.construct", {
1997
+ sessionId: this.sessionId,
1998
+ topic: this.topic,
1999
+ localPeerId: this.ownId,
2000
+ remotePeerId: this.remoteId,
2001
+ initiator: this.initiator
2002
+ }, {
2003
+ F: p,
2004
+ L: 137,
2005
+ S: this,
2006
+ C: (d, h) => d(...h)
2007
+ });
2008
+ }
2009
+ get sessionIdString() {
2010
+ return this.sessionId.truncate();
2011
+ }
2012
+ get state() {
2013
+ return this._state;
2014
+ }
2015
+ get transport() {
2016
+ return this._transport;
2017
+ }
2018
+ get protocol() {
2019
+ return this._protocol;
2020
+ }
2021
+ /**
2022
+ * Create an underlying transport and prepares it for the connection.
2023
+ */
2024
+ async openConnection() {
2025
+ f(this._state === "INITIAL", "Invalid state.", {
2026
+ F: p,
2027
+ L: 167,
2028
+ S: this,
2029
+ A: [
2030
+ "this._state === ConnectionState.INITIAL",
2031
+ "'Invalid state.'"
2032
+ ]
2033
+ }), a.trace("dxos.mesh.connection.open-connection", $.begin({
2034
+ id: this._instanceId
2035
+ }), {
2036
+ F: p,
2037
+ L: 168,
2038
+ S: this,
2039
+ C: (t, e) => t(...e)
2040
+ }), a.trace("dxos.mesh.connection.open", {
2041
+ sessionId: this.sessionId,
2042
+ topic: this.topic,
2043
+ localPeerId: this.ownId,
2044
+ remotePeerId: this.remoteId,
2045
+ initiator: this.initiator
2046
+ }, {
2047
+ F: p,
2048
+ L: 169,
2049
+ S: this,
2050
+ C: (t, e) => t(...e)
2051
+ }), this._changeState("CONNECTING"), this._protocol.open(this.sessionId).catch((t) => {
2052
+ this.errors.raise(t);
2053
+ }), this._protocol.stream.on("close", () => {
2054
+ a("protocol stream closed", void 0, {
2055
+ F: p,
2056
+ L: 186,
2057
+ S: this,
2058
+ C: (t, e) => t(...e)
2059
+ }), this._protocolClosed.wake(), this.close(new lt("protocol stream closed")).catch((t) => this.errors.raise(t));
2060
+ }), W(this.connectedTimeoutContext, async () => {
2061
+ a.info(`timeout waiting ${be / 1e3}s for transport to connect, aborting`, void 0, {
2062
+ F: p,
2063
+ L: 194,
2064
+ S: this,
2065
+ C: (t, e) => t(...e)
2066
+ }), await this.abort(new le(`${be / 1e3}s for transport to connect`)).catch((t) => this.errors.raise(t));
2067
+ }, be), f(!this._transport, void 0, {
2068
+ F: p,
2069
+ L: 202,
2070
+ S: this,
2071
+ A: [
2072
+ "!this._transport",
2073
+ ""
2074
+ ]
2075
+ }), this._transport = this._transportFactory.createTransport({
2076
+ initiator: this.initiator,
2077
+ stream: this._protocol.stream,
2078
+ sendSignal: async (t) => this._sendSignal(t),
2079
+ sessionId: this.sessionId
2080
+ }), await this._transport.open(), this._transport.connected.once(async () => {
2081
+ var t, e;
2082
+ this._changeState("CONNECTED"), await this.connectedTimeoutContext.dispose(), (e = (t = this._callbacks) == null ? void 0 : t.onConnected) == null || e.call(t), Ae(this._ctx, async () => this._emitTransportStats(), js);
2083
+ }), this._transport.closed.once(() => {
2084
+ this._transport = void 0, this._transportClosed.wake(), a("abort triggered by transport close", void 0, {
2085
+ F: p,
2086
+ L: 223,
2087
+ S: this,
2088
+ C: (t, e) => t(...e)
2089
+ }), this.abort().catch((t) => this.errors.raise(t));
2090
+ }), this._transport.errors.handle(async (t) => {
2091
+ a("transport error:", {
2092
+ err: t
2093
+ }, {
2094
+ F: p,
2095
+ L: 228,
2096
+ S: this,
2097
+ C: (e, s) => e(...s)
2098
+ }), this.closeReason || (this.closeReason = t == null ? void 0 : t.message), t instanceof dt ? (a.info("aborting due to transport ConnectionResetError", void 0, {
2099
+ F: p,
2100
+ L: 235,
2101
+ S: this,
2102
+ C: (e, s) => e(...s)
2103
+ }), this.abort().catch((e) => this.errors.raise(e))) : t instanceof he ? (a.info("aborting due to transport ConnectivityError", void 0, {
2104
+ F: p,
2105
+ L: 238,
2106
+ S: this,
2107
+ C: (e, s) => e(...s)
2108
+ }), this.abort().catch((e) => this.errors.raise(e))) : t instanceof Ee && a.warn("unsure what to do with UnknownProtocolError, will keep on truckin", {
2109
+ err: t
2110
+ }, {
2111
+ F: p,
2112
+ L: 241,
2113
+ S: this,
2114
+ C: (e, s) => e(...s)
2115
+ }), this._state !== "CLOSED" && this._state !== "CLOSING" && (await this.connectedTimeoutContext.dispose(), this.errors.raise(t));
2116
+ });
2117
+ for (const t of this._incomingSignalBuffer)
2118
+ this._transport.onSignal(t);
2119
+ this._incomingSignalBuffer = [], a.trace("dxos.mesh.connection.open-connection", $.end({
2120
+ id: this._instanceId
2121
+ }), {
2122
+ F: p,
2123
+ L: 257,
2124
+ S: this,
2125
+ C: (t, e) => t(...e)
2126
+ });
2127
+ }
2128
+ async abort(t) {
2129
+ var e, s;
2130
+ if (a("aborting...", {
2131
+ err: t
2132
+ }, {
2133
+ F: p,
2134
+ L: 264,
2135
+ S: this,
2136
+ C: (i, n) => i(...n)
2137
+ }), this._state === "CLOSED" || this._state === "ABORTED") {
2138
+ a(`abort ignored: already ${this._state}`, this.closeReason, {
2139
+ F: p,
2140
+ L: 266,
2141
+ S: this,
2142
+ C: (i, n) => i(...n)
2143
+ });
2144
+ return;
2145
+ }
2146
+ await this.connectedTimeoutContext.dispose(), this._changeState("ABORTING"), this.closeReason || (this.closeReason = t == null ? void 0 : t.message), await this._ctx.dispose();
2147
+ try {
2148
+ await this._closeProtocol({
2149
+ abort: !0
2150
+ });
2151
+ } catch (i) {
2152
+ a.catch(i, void 0, {
2153
+ F: p,
2154
+ L: 282,
2155
+ S: this,
2156
+ C: (n, r) => n(...r)
2157
+ });
2158
+ }
2159
+ try {
2160
+ await this._closeTransport();
2161
+ } catch (i) {
2162
+ a.catch(i, void 0, {
2163
+ F: p,
2164
+ L: 289,
2165
+ S: this,
2166
+ C: (n, r) => n(...r)
2167
+ });
2168
+ }
2169
+ try {
2170
+ (s = (e = this._callbacks) == null ? void 0 : e.onClosed) == null || s.call(e, t);
2171
+ } catch (i) {
2172
+ a.catch(i, void 0, {
2173
+ F: p,
2174
+ L: 295,
2175
+ S: this,
2176
+ C: (n, r) => n(...r)
2177
+ });
2178
+ }
2179
+ this._changeState("ABORTED");
2180
+ }
2181
+ async close(t) {
2182
+ var i, n;
2183
+ if (this.closeReason ? this.closeReason += `; ${t == null ? void 0 : t.message}` : this.closeReason = t == null ? void 0 : t.message, this._state === "CLOSED" || this._state === "ABORTING" || this._state === "ABORTED")
2184
+ return;
2185
+ const e = this._state;
2186
+ this._changeState("CLOSING"), await this.connectedTimeoutContext.dispose(), await this._ctx.dispose(), a("closing...", {
2187
+ peerId: this.ownId
2188
+ }, {
2189
+ F: p,
2190
+ L: 320,
2191
+ S: this,
2192
+ C: (r, o) => r(...o)
2193
+ });
2194
+ let s = !1;
2195
+ e !== "CONNECTED" && (a(`graceful close requested when we were in ${e} state? aborting`, void 0, {
2196
+ F: p,
2197
+ L: 324,
2198
+ S: this,
2199
+ C: (r, o) => r(...o)
2200
+ }), s = !0);
2201
+ try {
2202
+ await this._closeProtocol({
2203
+ abort: s
2204
+ });
2205
+ } catch (r) {
2206
+ a.catch(r, void 0, {
2207
+ F: p,
2208
+ L: 330,
2209
+ S: this,
2210
+ C: (o, c) => o(...c)
2211
+ });
2212
+ }
2213
+ try {
2214
+ await this._closeTransport();
2215
+ } catch (r) {
2216
+ a.catch(r, void 0, {
2217
+ F: p,
2218
+ L: 336,
2219
+ S: this,
2220
+ C: (o, c) => o(...c)
2221
+ });
2222
+ }
2223
+ a("closed", {
2224
+ peerId: this.ownId
2225
+ }, {
2226
+ F: p,
2227
+ L: 339,
2228
+ S: this,
2229
+ C: (r, o) => r(...o)
2230
+ }), this._changeState("CLOSED"), (n = (i = this._callbacks) == null ? void 0 : i.onClosed) == null || n.call(i, t);
2231
+ }
2232
+ async _closeProtocol(t) {
2233
+ a("closing protocol", t, {
2234
+ F: p,
2235
+ L: 345,
2236
+ S: this,
2237
+ C: (e, s) => e(...s)
2238
+ }), await Promise.race([
2239
+ t != null && t.abort ? this._protocol.abort() : this._protocol.close(),
2240
+ this._protocolClosed.wait()
2241
+ ]), a("protocol closed", t, {
2242
+ F: p,
2243
+ L: 347,
2244
+ S: this,
2245
+ C: (e, s) => e(...s)
2246
+ });
2247
+ }
2248
+ async _closeTransport() {
2249
+ var t;
2250
+ a("closing transport", void 0, {
2251
+ F: p,
2252
+ L: 351,
2253
+ S: this,
2254
+ C: (e, s) => e(...s)
2255
+ }), await Promise.race([
2256
+ (t = this._transport) == null ? void 0 : t.close(),
2257
+ this._transportClosed.wait()
2258
+ ]), a("transport closed", void 0, {
2259
+ F: p,
2260
+ L: 353,
2261
+ S: this,
2262
+ C: (e, s) => e(...s)
2263
+ });
2264
+ }
2265
+ _sendSignal(t) {
2266
+ this._outgoingSignalBuffer.push(t), this._signalSendTask.schedule();
2267
+ }
2268
+ async _flushSignalBuffer() {
2269
+ var t;
2270
+ if (this._outgoingSignalBuffer.length !== 0)
2271
+ try {
2272
+ await Nt(this._ctx, ct(this._signallingDelay)), this._signallingDelay = Math.min(this._signallingDelay * 2, Us);
2273
+ const e = [
2274
+ ...this._outgoingSignalBuffer
2275
+ ];
2276
+ this._outgoingSignalBuffer.length = 0, await this._signalMessaging.signal({
2277
+ author: this.ownId,
2278
+ recipient: this.remoteId,
2279
+ sessionId: this.sessionId,
2280
+ topic: this.topic,
2281
+ data: {
2282
+ signalBatch: {
2283
+ signals: e
2284
+ }
2285
+ }
2286
+ });
2287
+ } catch (e) {
2288
+ if (e instanceof xe || e instanceof Error && ((t = e.message) != null && t.includes("CANCELLED")))
2289
+ return;
2290
+ a.info("signal message failed to deliver", {
2291
+ err: e
2292
+ }, {
2293
+ F: p,
2294
+ L: 389,
2295
+ S: this,
2296
+ C: (s, i) => s(...i)
2297
+ }), await this.close(new he("signal message failed to deliver", e));
2298
+ }
2299
+ }
2300
+ /**
2301
+ * Receive a signal from the remote peer.
2302
+ */
2303
+ async signal(t) {
2304
+ var s, i;
2305
+ if (f(t.sessionId, void 0, {
2306
+ F: p,
2307
+ L: 398,
2308
+ S: this,
2309
+ A: [
2310
+ "msg.sessionId",
2311
+ ""
2312
+ ]
2313
+ }), !t.sessionId.equals(this.sessionId)) {
2314
+ a("dropping signal for incorrect session id", void 0, {
2315
+ F: p,
2316
+ L: 400,
2317
+ S: this,
2318
+ C: (n, r) => n(...r)
2319
+ });
2320
+ return;
2321
+ }
2322
+ f(t.data.signal || t.data.signalBatch, void 0, {
2323
+ F: p,
2324
+ L: 403,
2325
+ S: this,
2326
+ A: [
2327
+ "msg.data.signal || msg.data.signalBatch",
2328
+ ""
2329
+ ]
2330
+ }), f((s = t.author) == null ? void 0 : s.equals(this.remoteId), void 0, {
2331
+ F: p,
2332
+ L: 404,
2333
+ S: this,
2334
+ A: [
2335
+ "msg.author?.equals(this.remoteId)",
2336
+ ""
2337
+ ]
2338
+ }), f((i = t.recipient) == null ? void 0 : i.equals(this.ownId), void 0, {
2339
+ F: p,
2340
+ L: 405,
2341
+ S: this,
2342
+ A: [
2343
+ "msg.recipient?.equals(this.ownId)",
2344
+ ""
2345
+ ]
2346
+ });
2347
+ const e = t.data.signalBatch ? t.data.signalBatch.signals ?? [] : [
2348
+ t.data.signal
2349
+ ];
2350
+ for (const n of e)
2351
+ n && ([
2352
+ "CREATED",
2353
+ "INITIAL"
2354
+ ].includes(this.state) ? (a("buffered signal", {
2355
+ peerId: this.ownId,
2356
+ remoteId: this.remoteId,
2357
+ msg: t.data
2358
+ }, {
2359
+ F: p,
2360
+ L: 414,
2361
+ S: this,
2362
+ C: (r, o) => r(...o)
2363
+ }), this._incomingSignalBuffer.push(n)) : (f(this._transport, "Connection not ready to accept signals.", {
2364
+ F: p,
2365
+ L: 417,
2366
+ S: this,
2367
+ A: [
2368
+ "this._transport",
2369
+ "'Connection not ready to accept signals.'"
2370
+ ]
2371
+ }), a("received signal", {
2372
+ peerId: this.ownId,
2373
+ remoteId: this.remoteId,
2374
+ msg: t.data
2375
+ }, {
2376
+ F: p,
2377
+ L: 418,
2378
+ S: this,
2379
+ C: (r, o) => r(...o)
2380
+ }), await this._transport.onSignal(n)));
2381
+ }
2382
+ initiate() {
2383
+ this._changeState("INITIAL");
2384
+ }
2385
+ _changeState(t) {
2386
+ a("stateChanged", {
2387
+ from: this._state,
2388
+ to: t,
2389
+ peerId: this.ownId
2390
+ }, {
2391
+ F: p,
2392
+ L: 429,
2393
+ S: this,
2394
+ C: (e, s) => e(...s)
2395
+ }), f(t !== this._state, "Already in this state.", {
2396
+ F: p,
2397
+ L: 430,
2398
+ S: this,
2399
+ A: [
2400
+ "state !== this._state",
2401
+ "'Already in this state.'"
2402
+ ]
2403
+ }), this._state = t, this.stateChanged.emit(t);
2404
+ }
2405
+ async _emitTransportStats() {
2406
+ var e;
2407
+ const t = await ((e = this.transport) == null ? void 0 : e.getStats());
2408
+ t && this.transportStats.emit(t);
2409
+ }
2410
+ };
2411
+ Pe([
2412
+ q
2413
+ ], fe.prototype, "sessionIdString", null);
2414
+ Pe([
2415
+ F
2416
+ ], fe.prototype, "abort", null);
2417
+ Pe([
2418
+ F
2419
+ ], fe.prototype, "close", null);
2420
+ var E = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/signal/swarm-messenger.ts", Ke = ce.getCodecForType("dxos.mesh.swarm.SwarmMessage"), Hs = class {
2421
+ constructor({ sendMessage: t, onSignal: e, onOffer: s, topic: i }) {
2422
+ this._ctx = new N(void 0, {
2423
+ F: E,
2424
+ L: 33
2425
+ }), this._offerRecords = new O((n) => n.toHex()), this._sendMessage = t, this._onSignal = e, this._onOffer = s, this._topic = i;
2426
+ }
2427
+ async receiveMessage({ author: t, recipient: e, payload: s }) {
2428
+ var n, r, o, c;
2429
+ if (s.type_url !== "dxos.mesh.swarm.SwarmMessage")
2430
+ return;
2431
+ const i = Ke.decode(s.value);
2432
+ this._topic.equals(i.topic) && (a("received", {
2433
+ from: t,
2434
+ to: e,
2435
+ msg: i
2436
+ }, {
2437
+ F: E,
2438
+ L: 69,
2439
+ S: this,
2440
+ C: (_, d) => _(...d)
2441
+ }), (n = i.data) != null && n.offer ? await this._handleOffer({
2442
+ author: t,
2443
+ recipient: e,
2444
+ message: i
2445
+ }) : (r = i.data) != null && r.answer ? await this._resolveAnswers(i) : (o = i.data) != null && o.signal ? await this._handleSignal({
2446
+ author: t,
2447
+ recipient: e,
2448
+ message: i
2449
+ }) : (c = i.data) != null && c.signalBatch ? await this._handleSignal({
2450
+ author: t,
2451
+ recipient: e,
2452
+ message: i
2453
+ }) : a.warn("unknown message", {
2454
+ message: i
2455
+ }, {
2456
+ F: E,
2457
+ L: 80,
2458
+ S: this,
2459
+ C: (_, d) => _(...d)
2460
+ }));
2461
+ }
2462
+ async signal(t) {
2463
+ var e, s;
2464
+ f(((e = t.data) == null ? void 0 : e.signal) || ((s = t.data) == null ? void 0 : s.signalBatch), "Invalid message", {
2465
+ F: E,
2466
+ L: 85,
2467
+ S: this,
2468
+ A: [
2469
+ "message.data?.signal || message.data?.signalBatch",
2470
+ "'Invalid message'"
2471
+ ]
2472
+ }), await this._sendReliableMessage({
2473
+ author: t.author,
2474
+ recipient: t.recipient,
2475
+ message: t
2476
+ });
2477
+ }
2478
+ async offer(t) {
2479
+ const e = {
2480
+ ...t,
2481
+ messageId: m.random()
2482
+ };
2483
+ return new Promise((s, i) => {
2484
+ this._offerRecords.set(e.messageId, {
2485
+ resolve: s
2486
+ }), this._sendReliableMessage({
2487
+ author: t.author,
2488
+ recipient: t.recipient,
2489
+ message: e
2490
+ }).catch((n) => i(n));
2491
+ });
2492
+ }
2493
+ async _sendReliableMessage({ author: t, recipient: e, message: s }) {
2494
+ const i = {
2495
+ ...s,
2496
+ // Setting unique message_id if it not specified yet.
2497
+ messageId: s.messageId ?? m.random()
2498
+ };
2499
+ a("sending", {
2500
+ from: t,
2501
+ to: e,
2502
+ msg: i
2503
+ }, {
2504
+ F: E,
2505
+ L: 123,
2506
+ S: this,
2507
+ C: (n, r) => n(...r)
2508
+ }), await this._sendMessage({
2509
+ author: t,
2510
+ recipient: e,
2511
+ payload: {
2512
+ type_url: "dxos.mesh.swarm.SwarmMessage",
2513
+ value: Ke.encode(i)
2514
+ }
2515
+ });
2516
+ }
2517
+ async _resolveAnswers(t) {
2518
+ var s, i, n;
2519
+ f((i = (s = t.data) == null ? void 0 : s.answer) == null ? void 0 : i.offerMessageId, "No offerMessageId", {
2520
+ F: E,
2521
+ L: 135,
2522
+ S: this,
2523
+ A: [
2524
+ "message.data?.answer?.offerMessageId",
2525
+ "'No offerMessageId'"
2526
+ ]
2527
+ });
2528
+ const e = this._offerRecords.get(t.data.answer.offerMessageId);
2529
+ e && (this._offerRecords.delete(t.data.answer.offerMessageId), f((n = t.data) == null ? void 0 : n.answer, "No answer", {
2530
+ F: E,
2531
+ L: 139,
2532
+ S: this,
2533
+ A: [
2534
+ "message.data?.answer",
2535
+ "'No answer'"
2536
+ ]
2537
+ }), a("resolving", {
2538
+ answer: t.data.answer
2539
+ }, {
2540
+ F: E,
2541
+ L: 140,
2542
+ S: this,
2543
+ C: (r, o) => r(...o)
2544
+ }), e.resolve(t.data.answer));
2545
+ }
2546
+ async _handleOffer({ author: t, recipient: e, message: s }) {
2547
+ f(s.data.offer, "No offer", {
2548
+ F: E,
2549
+ L: 154,
2550
+ S: this,
2551
+ A: [
2552
+ "message.data.offer",
2553
+ "'No offer'"
2554
+ ]
2555
+ });
2556
+ const i = {
2557
+ author: t,
2558
+ recipient: e,
2559
+ ...s,
2560
+ data: {
2561
+ offer: s.data.offer
2562
+ }
2563
+ }, n = await this._onOffer(i);
2564
+ n.offerMessageId = s.messageId;
2565
+ try {
2566
+ await this._sendReliableMessage({
2567
+ author: e,
2568
+ recipient: t,
2569
+ message: {
2570
+ topic: s.topic,
2571
+ sessionId: s.sessionId,
2572
+ data: {
2573
+ answer: n
2574
+ }
2575
+ }
2576
+ });
2577
+ } catch (r) {
2578
+ r instanceof le ? a.info("timeout sending answer to offer", {
2579
+ err: r
2580
+ }, {
2581
+ F: E,
2582
+ L: 175,
2583
+ S: this,
2584
+ C: (o, c) => o(...c)
2585
+ }) : a.info("error sending answer to offer", {
2586
+ err: r
2587
+ }, {
2588
+ F: E,
2589
+ L: 177,
2590
+ S: this,
2591
+ C: (o, c) => o(...c)
2592
+ });
2593
+ }
2594
+ }
2595
+ async _handleSignal({ author: t, recipient: e, message: s }) {
2596
+ f(s.messageId, void 0, {
2597
+ F: E,
2598
+ L: 191,
2599
+ S: this,
2600
+ A: [
2601
+ "message.messageId",
2602
+ ""
2603
+ ]
2604
+ }), f(s.data.signal || s.data.signalBatch, "Invalid message", {
2605
+ F: E,
2606
+ L: 192,
2607
+ S: this,
2608
+ A: [
2609
+ "message.data.signal || message.data.signalBatch",
2610
+ "'Invalid message'"
2611
+ ]
2612
+ });
2613
+ const i = {
2614
+ author: t,
2615
+ recipient: e,
2616
+ ...s,
2617
+ data: {
2618
+ signal: s.data.signal,
2619
+ signalBatch: s.data.signalBatch
2620
+ }
2621
+ };
2622
+ await this._onSignal(i);
2623
+ }
2624
+ };
2625
+ function Gs(t, e, s, i) {
2626
+ var n = arguments.length, r = n < 3 ? e : i === null ? i = Object.getOwnPropertyDescriptor(e, s) : i, o;
2627
+ if (typeof Reflect == "object" && typeof Reflect.decorate == "function")
2628
+ r = Reflect.decorate(t, e, s, i);
2629
+ else
2630
+ for (var c = t.length - 1; c >= 0; c--)
2631
+ (o = t[c]) && (r = (n < 3 ? o(r) : n > 3 ? o(e, s, r) : o(e, s)) || r);
2632
+ return n > 3 && r && Object.defineProperty(e, s, r), r;
2633
+ }
2634
+ var w = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/swarm/peer.ts", We = class extends Dt {
2635
+ constructor() {
2636
+ super("Connection displaced by remote initiator.");
2637
+ }
2638
+ }, zs = 5e3, ut = class {
2639
+ constructor(t, e, s, i, n, r, o, c) {
2640
+ this.id = t, this.topic = e, this.localPeerId = s, this._signalMessaging = i, this._protocolProvider = n, this._transportFactory = r, this._connectionLimiter = o, this._callbacks = c, this._availableAfter = 0, this.availableToConnect = !0, this._ctx = new N(void 0, {
2641
+ F: w,
2642
+ L: 79
2643
+ }), this.advertizing = !1, this.initiating = !1, this.connectionDisplaced = new S();
2644
+ }
2645
+ /**
2646
+ * Respond to remote offer.
2647
+ */
2648
+ async onOffer(t) {
2649
+ var s;
2650
+ const e = t.author;
2651
+ if (this.connection && ![
2652
+ P.CREATED,
2653
+ P.INITIAL,
2654
+ P.CONNECTING
2655
+ ].includes(this.connection.state))
2656
+ return a.info(`received offer when connection already in ${this.connection.state} state`, void 0, {
2657
+ F: w,
2658
+ L: 114,
2659
+ S: this,
2660
+ C: (i, n) => i(...n)
2661
+ }), {
2662
+ accept: !1
2663
+ };
2664
+ if (this.connection || this.initiating)
2665
+ if (e.toHex() < this.localPeerId.toHex())
2666
+ a("close local connection", {
2667
+ localPeerId: this.id,
2668
+ topic: this.topic,
2669
+ remotePeerId: this.localPeerId,
2670
+ sessionId: (s = this.connection) == null ? void 0 : s.sessionId
2671
+ }, {
2672
+ F: w,
2673
+ L: 123,
2674
+ S: this,
2675
+ C: (i, n) => i(...n)
2676
+ }), this.connection && await this.closeConnection(new We());
2677
+ else
2678
+ return {
2679
+ accept: !1
2680
+ };
2681
+ if (await this._callbacks.onOffer(e) && !this.connection) {
2682
+ f(t.sessionId, void 0, {
2683
+ F: w,
2684
+ L: 143,
2685
+ S: this,
2686
+ A: [
2687
+ "message.sessionId",
2688
+ ""
2689
+ ]
2690
+ });
2691
+ const i = this._createConnection(!1, t.sessionId);
2692
+ try {
2693
+ await this._connectionLimiter.connecting(t.sessionId), i.initiate(), await i.openConnection();
2694
+ } catch (n) {
2695
+ n instanceof xe || a.info("connection error", {
2696
+ topic: this.topic,
2697
+ peerId: this.localPeerId,
2698
+ remoteId: this.id,
2699
+ err: n
2700
+ }, {
2701
+ F: w,
2702
+ L: 153,
2703
+ S: this,
2704
+ C: (r, o) => r(...o)
2705
+ }), await this.closeConnection(n);
2706
+ }
2707
+ return {
2708
+ accept: !0
2709
+ };
2710
+ }
2711
+ return {
2712
+ accept: !1
2713
+ };
2714
+ }
2715
+ /**
2716
+ * Initiate a connection to the remote peer.
2717
+ */
2718
+ async initiateConnection() {
2719
+ f(!this.initiating, "Initiation in progress.", {
2720
+ F: w,
2721
+ L: 170,
2722
+ S: this,
2723
+ A: [
2724
+ "!this.initiating",
2725
+ "'Initiation in progress.'"
2726
+ ]
2727
+ }), f(!this.connection, "Already connected.", {
2728
+ F: w,
2729
+ L: 171,
2730
+ S: this,
2731
+ A: [
2732
+ "!this.connection",
2733
+ "'Already connected.'"
2734
+ ]
2735
+ });
2736
+ const t = m.random();
2737
+ a("initiating...", {
2738
+ ownPeerId: this.localPeerId,
2739
+ topic: this.topic,
2740
+ remotePeerId: this.id,
2741
+ sessionId: t
2742
+ }, {
2743
+ F: w,
2744
+ L: 173,
2745
+ S: this,
2746
+ C: (i, n) => i(...n)
2747
+ });
2748
+ const e = this._createConnection(!0, t);
2749
+ this.initiating = !0;
2750
+ let s;
2751
+ try {
2752
+ if (await this._connectionLimiter.connecting(t), e.initiate(), s = await this._signalMessaging.offer({
2753
+ author: this.localPeerId,
2754
+ recipient: this.id,
2755
+ sessionId: t,
2756
+ topic: this.topic,
2757
+ data: {
2758
+ offer: {}
2759
+ }
2760
+ }), a("received", {
2761
+ answer: s,
2762
+ topic: this.topic,
2763
+ ownId: this.localPeerId,
2764
+ remoteId: this.id
2765
+ }, {
2766
+ F: w,
2767
+ L: 190,
2768
+ S: this,
2769
+ C: (i, n) => i(...n)
2770
+ }), e.state !== P.INITIAL) {
2771
+ a("ignoring response", void 0, {
2772
+ F: w,
2773
+ L: 192,
2774
+ S: this,
2775
+ C: (i, n) => i(...n)
2776
+ });
2777
+ return;
2778
+ }
2779
+ } catch (i) {
2780
+ throw a("initiation error: send offer", {
2781
+ err: i,
2782
+ topic: this.topic,
2783
+ peerId: this.localPeerId,
2784
+ remoteId: this.id
2785
+ }, {
2786
+ F: w,
2787
+ L: 196,
2788
+ S: this,
2789
+ C: (n, r) => n(...r)
2790
+ }), await e.abort(i), i;
2791
+ } finally {
2792
+ this.initiating = !1;
2793
+ }
2794
+ try {
2795
+ if (!s.accept) {
2796
+ this._callbacks.onRejected();
2797
+ return;
2798
+ }
2799
+ } catch (i) {
2800
+ throw a("initiation error: accept answer", {
2801
+ err: i,
2802
+ topic: this.topic,
2803
+ peerId: this.localPeerId,
2804
+ remoteId: this.id
2805
+ }, {
2806
+ F: w,
2807
+ L: 209,
2808
+ S: this,
2809
+ C: (n, r) => n(...r)
2810
+ }), await e.abort(i), i;
2811
+ } finally {
2812
+ this.initiating = !1;
2813
+ }
2814
+ try {
2815
+ a("opening connection as initiator", void 0, {
2816
+ F: w,
2817
+ L: 222,
2818
+ S: this,
2819
+ C: (i, n) => i(...n)
2820
+ }), await e.openConnection(), this._callbacks.onAccepted();
2821
+ } catch (i) {
2822
+ throw a("initiation error: open connection", {
2823
+ err: i,
2824
+ topic: this.topic,
2825
+ peerId: this.localPeerId,
2826
+ remoteId: this.id
2827
+ }, {
2828
+ F: w,
2829
+ L: 226,
2830
+ S: this,
2831
+ C: (n, r) => n(...r)
2832
+ }), a.warn("closing connection due to unhandled error on openConnection", {
2833
+ err: i
2834
+ }, {
2835
+ F: w,
2836
+ L: 233,
2837
+ S: this,
2838
+ C: (n, r) => n(...r)
2839
+ }), await this.closeConnection(i), i;
2840
+ } finally {
2841
+ this.initiating = !1;
2842
+ }
2843
+ }
2844
+ /**
2845
+ * Create new connection.
2846
+ * Either we're initiating a connection or creating one in response to an offer from the other peer.
2847
+ */
2848
+ _createConnection(t, e) {
2849
+ var i;
2850
+ a("creating connection", {
2851
+ topic: this.topic,
2852
+ peerId: this.localPeerId,
2853
+ remoteId: this.id,
2854
+ initiator: t,
2855
+ sessionId: e
2856
+ }, {
2857
+ F: w,
2858
+ L: 247,
2859
+ S: this,
2860
+ C: (n, r) => n(...r)
2861
+ }), f(!this.connection, "Already connected.", {
2862
+ F: w,
2863
+ L: 254,
2864
+ S: this,
2865
+ A: [
2866
+ "!this.connection",
2867
+ "'Already connected.'"
2868
+ ]
2869
+ });
2870
+ const s = new fe(
2871
+ this.topic,
2872
+ this.localPeerId,
2873
+ this.id,
2874
+ e,
2875
+ t,
2876
+ this._signalMessaging,
2877
+ // TODO(dmaretskyi): Init only when connection is established.
2878
+ this._protocolProvider({
2879
+ initiator: t,
2880
+ localPeerId: this.localPeerId,
2881
+ remotePeerId: this.id,
2882
+ topic: this.topic
2883
+ }),
2884
+ this._transportFactory,
2885
+ {
2886
+ onConnected: () => {
2887
+ this.availableToConnect = !0, this._lastConnectionTime = Date.now(), this._callbacks.onConnected(), this._connectionLimiter.doneConnecting(e), a.trace("dxos.mesh.connection.connected", {
2888
+ topic: this.topic,
2889
+ localPeerId: this.localPeerId,
2890
+ remotePeerId: this.id,
2891
+ sessionId: e,
2892
+ initiator: t
2893
+ }, {
2894
+ F: w,
2895
+ L: 273,
2896
+ S: this,
2897
+ C: (n, r) => n(...r)
2898
+ });
2899
+ },
2900
+ onClosed: (n) => {
2901
+ a("connection closed", {
2902
+ topic: this.topic,
2903
+ peerId: this.localPeerId,
2904
+ remoteId: this.id,
2905
+ initiator: t
2906
+ }, {
2907
+ F: w,
2908
+ L: 282,
2909
+ S: this,
2910
+ C: (r, o) => r(...o)
2911
+ }), this._connectionLimiter.doneConnecting(e), f(this.connection === s, "Connection mismatch (race condition).", {
2912
+ F: w,
2913
+ L: 287,
2914
+ S: this,
2915
+ A: [
2916
+ "this.connection === connection",
2917
+ "'Connection mismatch (race condition).'"
2918
+ ]
2919
+ }), a.trace("dxos.mesh.connection.closed", {
2920
+ topic: this.topic,
2921
+ localPeerId: this.localPeerId,
2922
+ remotePeerId: this.id,
2923
+ sessionId: e,
2924
+ initiator: t
2925
+ }, {
2926
+ F: w,
2927
+ L: 289,
2928
+ S: this,
2929
+ C: (r, o) => r(...o)
2930
+ }), n instanceof We ? this.connectionDisplaced.emit(this.connection) : (this._lastConnectionTime && this._lastConnectionTime + zs < Date.now() ? this._availableAfter = 0 : (this.availableToConnect = !1, this._availableAfter = Ys(this._availableAfter)), this._callbacks.onDisconnected(), W(this._connectionCtx, () => {
2931
+ this.availableToConnect = !0, this._callbacks.onPeerAvailable();
2932
+ }, this._availableAfter)), this.connection = void 0;
2933
+ }
2934
+ }
2935
+ );
2936
+ return this._callbacks.onInitiated(s), (i = this._connectionCtx) == null || i.dispose(), this._connectionCtx = this._ctx.derive(), s.errors.handle((n) => {
2937
+ a.info("connection error, closing", {
2938
+ topic: this.topic,
2939
+ peerId: this.localPeerId,
2940
+ remoteId: this.id,
2941
+ initiator: t,
2942
+ err: n
2943
+ }, {
2944
+ F: w,
2945
+ L: 329,
2946
+ S: this,
2947
+ C: (r, o) => r(...o)
2948
+ }), a.trace("dxos.mesh.connection.error", {
2949
+ topic: this.topic,
2950
+ localPeerId: this.localPeerId,
2951
+ remotePeerId: this.id,
2952
+ sessionId: e,
2953
+ initiator: t,
2954
+ err: n
2955
+ }, {
2956
+ F: w,
2957
+ L: 336,
2958
+ S: this,
2959
+ C: (r, o) => r(...o)
2960
+ }), this.closeConnection(n);
2961
+ }), this.connection = s, s;
2962
+ }
2963
+ async closeConnection(t) {
2964
+ if (!this.connection)
2965
+ return;
2966
+ const e = this.connection;
2967
+ a("closing...", {
2968
+ peerId: this.id,
2969
+ sessionId: e.sessionId
2970
+ }, {
2971
+ F: w,
2972
+ L: 361,
2973
+ S: this,
2974
+ C: (s, i) => s(...i)
2975
+ }), await e.close(t), a("closed", {
2976
+ peerId: this.id,
2977
+ sessionId: e.sessionId
2978
+ }, {
2979
+ F: w,
2980
+ L: 367,
2981
+ S: this,
2982
+ C: (s, i) => s(...i)
2983
+ });
2984
+ }
2985
+ async onSignal(t) {
2986
+ if (!this.connection) {
2987
+ a("dropping signal message for non-existent connection", {
2988
+ message: t
2989
+ }, {
2990
+ F: w,
2991
+ L: 372,
2992
+ S: this,
2993
+ C: (e, s) => e(...s)
2994
+ });
2995
+ return;
2996
+ }
2997
+ await this.connection.signal(t);
2998
+ }
2999
+ async safeDestroy(t) {
3000
+ var e;
3001
+ await this._ctx.dispose(), a("Destroying peer", {
3002
+ peerId: this.id,
3003
+ topic: this.topic
3004
+ }, {
3005
+ F: w,
3006
+ L: 382,
3007
+ S: this,
3008
+ C: (s, i) => s(...i)
3009
+ }), await ((e = this == null ? void 0 : this.connection) == null ? void 0 : e.close(t));
3010
+ }
3011
+ };
3012
+ Gs([
3013
+ F
3014
+ ], ut.prototype, "safeDestroy", null);
3015
+ var Ys = (t) => t === 0 ? 50 : t < 500 ? 500 : t < 1e3 ? 1e3 : t < 5e3 ? 5e3 : 1e4;
3016
+ function G(t, e, s, i) {
3017
+ var n = arguments.length, r = n < 3 ? e : i === null ? i = Object.getOwnPropertyDescriptor(e, s) : i, o;
3018
+ if (typeof Reflect == "object" && typeof Reflect.decorate == "function")
3019
+ r = Reflect.decorate(t, e, s, i);
3020
+ else
3021
+ for (var c = t.length - 1; c >= 0; c--)
3022
+ (o = t[c]) && (r = (n < 3 ? o(r) : n > 3 ? o(e, s, r) : o(e, s)) || r);
3023
+ return n > 3 && r && Object.defineProperty(e, s, r), r;
3024
+ }
3025
+ var C = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/swarm/swarm.ts", Ks = 100, Xe = (t) => Object.getPrototypeOf(t).constructor.name, j = class {
3026
+ // TODO(burdon): Swarm => Peer.create/destroy =< Connection.open/close
3027
+ // TODO(burdon): Pass in object.
3028
+ constructor(t, e, s, i, n, r, o, c, _ = Ks) {
3029
+ this._topic = t, this._ownPeerId = e, this._topology = s, this._protocolProvider = i, this._messenger = n, this._transportFactory = r, this._label = o, this._connectionLimiter = c, this._initiationDelay = _, this._ctx = new N(void 0, {
3030
+ F: C,
3031
+ L: 39
3032
+ }), this._listeningHandle = void 0, this._peers = new O(m.hash), this._instanceId = m.random().toHex(), this.connectionAdded = new S(), this.disconnected = new S(), this.connected = new S(), this.errors = new ie(), a.trace("dxos.mesh.swarm.constructor", $.begin({
3033
+ id: this._instanceId,
3034
+ data: {
3035
+ topic: this._topic.toHex(),
3036
+ peerId: this._ownPeerId.toHex()
3037
+ }
3038
+ }), {
3039
+ F: C,
3040
+ L: 89,
3041
+ S: this,
3042
+ C: (d, h) => d(...h)
3043
+ }), a("creating swarm", {
3044
+ peerId: e
3045
+ }, {
3046
+ F: C,
3047
+ L: 93,
3048
+ S: this,
3049
+ C: (d, h) => d(...h)
3050
+ }), s.init(this._getSwarmController()), this._swarmMessenger = new Hs({
3051
+ sendMessage: async (d) => await this._messenger.sendMessage(d),
3052
+ onSignal: async (d) => await this.onSignal(d),
3053
+ onOffer: async (d) => await this.onOffer(d),
3054
+ topic: this._topic
3055
+ }), a.trace("dxos.mesh.swarm.constructor", $.end({
3056
+ id: this._instanceId
3057
+ }), {
3058
+ F: C,
3059
+ L: 102,
3060
+ S: this,
3061
+ C: (d, h) => d(...h)
3062
+ });
3063
+ }
3064
+ get connections() {
3065
+ return Array.from(this._peers.values()).map((t) => t.connection).filter(Ot);
3066
+ }
3067
+ get ownPeerId() {
3068
+ return this._ownPeerId;
3069
+ }
3070
+ /**
3071
+ * Custom label assigned to this swarm. Used in devtools to display human-readable names for swarms.
3072
+ */
3073
+ get label() {
3074
+ return this._label;
3075
+ }
3076
+ get topic() {
3077
+ return this._topic;
3078
+ }
3079
+ async open() {
3080
+ f(!this._listeningHandle, void 0, {
3081
+ F: C,
3082
+ L: 129,
3083
+ S: this,
3084
+ A: [
3085
+ "!this._listeningHandle",
3086
+ ""
3087
+ ]
3088
+ }), this._listeningHandle = await this._messenger.listen({
3089
+ peerId: this._ownPeerId,
3090
+ payloadType: "dxos.mesh.swarm.SwarmMessage",
3091
+ onMessage: async (t) => {
3092
+ await this._swarmMessenger.receiveMessage(t).catch((e) => a.info("Error while receiving message", {
3093
+ err: e
3094
+ }, {
3095
+ F: C,
3096
+ L: 137,
3097
+ S: this,
3098
+ C: (s, i) => s(...i)
3099
+ }));
3100
+ }
3101
+ });
3102
+ }
3103
+ async destroy() {
3104
+ var t;
3105
+ a("destroying...", void 0, {
3106
+ F: C,
3107
+ L: 143,
3108
+ S: this,
3109
+ C: (e, s) => e(...s)
3110
+ }), await ((t = this._listeningHandle) == null ? void 0 : t.unsubscribe()), this._listeningHandle = void 0, await this._ctx.dispose(), await this._topology.destroy(), await Promise.all(Array.from(this._peers.keys()).map((e) => this._destroyPeer(e, "swarm destroyed"))), a("destroyed", void 0, {
3111
+ F: C,
3112
+ L: 150,
3113
+ S: this,
3114
+ C: (e, s) => e(...s)
3115
+ });
3116
+ }
3117
+ async setTopology(t) {
3118
+ f(!this._ctx.disposed, "Swarm is offline", {
3119
+ F: C,
3120
+ L: 154,
3121
+ S: this,
3122
+ A: [
3123
+ "!this._ctx.disposed",
3124
+ "'Swarm is offline'"
3125
+ ]
3126
+ }), t !== this._topology && (a("setting topology", {
3127
+ previous: Xe(this._topology),
3128
+ topology: Xe(t)
3129
+ }, {
3130
+ F: C,
3131
+ L: 158,
3132
+ S: this,
3133
+ C: (e, s) => e(...s)
3134
+ }), await this._topology.destroy(), this._topology = t, this._topology.init(this._getSwarmController()), this._topology.update());
3135
+ }
3136
+ onSwarmEvent(t) {
3137
+ var e;
3138
+ if (a("swarm event", {
3139
+ swarmEvent: t
3140
+ }, {
3141
+ F: C,
3142
+ L: 171,
3143
+ S: this,
3144
+ C: (s, i) => s(...i)
3145
+ }), this._ctx.disposed) {
3146
+ a("swarm event ignored for disposed swarm", void 0, {
3147
+ F: C,
3148
+ L: 174,
3149
+ S: this,
3150
+ C: (s, i) => s(...i)
3151
+ });
3152
+ return;
3153
+ }
3154
+ if (t.peerAvailable) {
3155
+ const s = m.from(t.peerAvailable.peer);
3156
+ if (!s.equals(this._ownPeerId)) {
3157
+ a("new peer", {
3158
+ peerId: s
3159
+ }, {
3160
+ F: C,
3161
+ L: 181,
3162
+ S: this,
3163
+ C: (n, r) => n(...r)
3164
+ });
3165
+ const i = this._getOrCreatePeer(s);
3166
+ i.advertizing = !0;
3167
+ }
3168
+ } else if (t.peerLeft) {
3169
+ const s = this._peers.get(m.from(t.peerLeft.peer));
3170
+ s ? (s.advertizing = !1, ((e = s.connection) == null ? void 0 : e.state) !== P.CONNECTED && this._destroyPeer(s.id, "peer left").catch((i) => a.catch(i, void 0, {
3171
+ F: C,
3172
+ L: 191,
3173
+ S: this,
3174
+ C: (n, r) => n(...r)
3175
+ }))) : a("received peerLeft but no peer found", {
3176
+ peer: t.peerLeft.peer
3177
+ }, {
3178
+ F: C,
3179
+ L: 194,
3180
+ S: this,
3181
+ C: (i, n) => i(...n)
3182
+ });
3183
+ }
3184
+ this._topology.update();
3185
+ }
3186
+ async onOffer(t) {
3187
+ var i, n;
3188
+ if (a("offer", {
3189
+ message: t
3190
+ }, {
3191
+ F: C,
3192
+ L: 203,
3193
+ S: this,
3194
+ C: (r, o) => r(...o)
3195
+ }), this._ctx.disposed)
3196
+ return a("ignored for disposed swarm", void 0, {
3197
+ F: C,
3198
+ L: 205,
3199
+ S: this,
3200
+ C: (r, o) => r(...o)
3201
+ }), {
3202
+ accept: !1
3203
+ };
3204
+ if (f(t.author, void 0, {
3205
+ F: C,
3206
+ L: 210,
3207
+ S: this,
3208
+ A: [
3209
+ "message.author",
3210
+ ""
3211
+ ]
3212
+ }), !((i = t.recipient) != null && i.equals(this._ownPeerId)))
3213
+ return a("rejecting offer with incorrect peerId", {
3214
+ message: t
3215
+ }, {
3216
+ F: C,
3217
+ L: 212,
3218
+ S: this,
3219
+ C: (r, o) => r(...o)
3220
+ }), {
3221
+ accept: !1
3222
+ };
3223
+ if (!((n = t.topic) != null && n.equals(this._topic)))
3224
+ return a("rejecting offer with incorrect topic", {
3225
+ message: t
3226
+ }, {
3227
+ F: C,
3228
+ L: 216,
3229
+ S: this,
3230
+ C: (r, o) => r(...o)
3231
+ }), {
3232
+ accept: !1
3233
+ };
3234
+ const s = await this._getOrCreatePeer(t.author).onOffer(t);
3235
+ return this._topology.update(), s;
3236
+ }
3237
+ async onSignal(t) {
3238
+ var s, i;
3239
+ if (a("signal", {
3240
+ message: t
3241
+ }, {
3242
+ F: C,
3243
+ L: 227,
3244
+ S: this,
3245
+ C: (n, r) => n(...r)
3246
+ }), this._ctx.disposed) {
3247
+ a.info("ignored for offline swarm", void 0, {
3248
+ F: C,
3249
+ L: 229,
3250
+ S: this,
3251
+ C: (n, r) => n(...r)
3252
+ });
3253
+ return;
3254
+ }
3255
+ f((s = t.recipient) == null ? void 0 : s.equals(this._ownPeerId), `Invalid signal peer id expected=${this.ownPeerId}, actual=${t.recipient}`, {
3256
+ F: C,
3257
+ L: 232,
3258
+ S: this,
3259
+ A: [
3260
+ "message.recipient?.equals(this._ownPeerId)",
3261
+ "`Invalid signal peer id expected=${this.ownPeerId}, actual=${message.recipient}`"
3262
+ ]
3263
+ }), f((i = t.topic) == null ? void 0 : i.equals(this._topic), void 0, {
3264
+ F: C,
3265
+ L: 236,
3266
+ S: this,
3267
+ A: [
3268
+ "message.topic?.equals(this._topic)",
3269
+ ""
3270
+ ]
3271
+ }), f(t.author, void 0, {
3272
+ F: C,
3273
+ L: 237,
3274
+ S: this,
3275
+ A: [
3276
+ "message.author",
3277
+ ""
3278
+ ]
3279
+ }), await this._getOrCreatePeer(t.author).onSignal(t);
3280
+ }
3281
+ // For debug purposes
3282
+ async goOffline() {
3283
+ await this._ctx.dispose(), await Promise.all([
3284
+ ...this._peers.keys()
3285
+ ].map((t) => this._destroyPeer(t, "goOffline")));
3286
+ }
3287
+ // For debug purposes
3288
+ async goOnline() {
3289
+ this._ctx = new N(void 0, {
3290
+ F: C,
3291
+ L: 253
3292
+ });
3293
+ }
3294
+ _getOrCreatePeer(t) {
3295
+ let e = this._peers.get(t);
3296
+ return e || (e = new ut(t, this._topic, this._ownPeerId, this._swarmMessenger, this._protocolProvider, this._transportFactory, this._connectionLimiter, {
3297
+ onInitiated: (s) => {
3298
+ this.connectionAdded.emit(s);
3299
+ },
3300
+ onConnected: () => {
3301
+ this.connected.emit(t);
3302
+ },
3303
+ onDisconnected: async () => {
3304
+ this._isUnregistered(e) || (e.advertizing || await this._destroyPeer(e.id, "peer disconnected"), this.disconnected.emit(t), this._topology.update());
3305
+ },
3306
+ onRejected: () => {
3307
+ this._isUnregistered(e) || (a("peer rejected connection", {
3308
+ peerId: t
3309
+ }, {
3310
+ F: C,
3311
+ L: 289,
3312
+ S: this,
3313
+ C: (s, i) => s(...i)
3314
+ }), this._destroyPeer(t, "peer rejected connection"));
3315
+ },
3316
+ onAccepted: () => {
3317
+ this._topology.update();
3318
+ },
3319
+ onOffer: (s) => this._topology.onOffer(s),
3320
+ onPeerAvailable: () => {
3321
+ this._topology.update();
3322
+ }
3323
+ }), this._peers.set(t, e)), e;
3324
+ }
3325
+ async _destroyPeer(t, e) {
3326
+ const s = this._peers.get(t);
3327
+ f(s, void 0, {
3328
+ F: C,
3329
+ L: 312,
3330
+ S: this,
3331
+ A: [
3332
+ "peer",
3333
+ ""
3334
+ ]
3335
+ }), this._peers.delete(t), await s.safeDestroy(new Error(e));
3336
+ }
3337
+ _getSwarmController() {
3338
+ return {
3339
+ getState: () => ({
3340
+ ownPeerId: this._ownPeerId,
3341
+ connected: Array.from(this._peers.values()).filter((t) => t.connection).map((t) => t.id),
3342
+ candidates: Array.from(this._peers.values()).filter((t) => !t.connection && t.advertizing && t.availableToConnect).map((t) => t.id),
3343
+ allPeers: Array.from(this._peers.values()).map((t) => t.id)
3344
+ }),
3345
+ connect: (t) => {
3346
+ this._ctx.disposed || W(this._ctx, async () => {
3347
+ try {
3348
+ await this._initiateConnection(t);
3349
+ } catch (e) {
3350
+ a("initiation error", e, {
3351
+ F: C,
3352
+ L: 339,
3353
+ S: this,
3354
+ C: (s, i) => s(...i)
3355
+ });
3356
+ }
3357
+ });
3358
+ },
3359
+ disconnect: async (t) => {
3360
+ this._ctx.disposed || W(this._ctx, async () => {
3361
+ await this._closeConnection(t), this._topology.update();
3362
+ });
3363
+ }
3364
+ };
3365
+ }
3366
+ /**
3367
+ * Creates a connection then sends message over signal network.
3368
+ */
3369
+ async _initiateConnection(t) {
3370
+ const e = this._ctx, s = this._getOrCreatePeer(t);
3371
+ if (t.toHex() < this._ownPeerId.toHex() && (a("initiation delay", {
3372
+ remoteId: t
3373
+ }, {
3374
+ F: C,
3375
+ L: 367,
3376
+ S: this,
3377
+ C: (i, n) => i(...n)
3378
+ }), await ct(this._initiationDelay)), !e.disposed) {
3379
+ if (this._isUnregistered(s))
3380
+ throw new Error("Peer left during initiation delay");
3381
+ s.connection || (a("initiating connection...", {
3382
+ remoteId: t
3383
+ }, {
3384
+ F: C,
3385
+ L: 383,
3386
+ S: this,
3387
+ C: (i, n) => i(...n)
3388
+ }), await s.initiateConnection(), this._topology.update(), a("initiated", {
3389
+ remoteId: t
3390
+ }, {
3391
+ F: C,
3392
+ L: 386,
3393
+ S: this,
3394
+ C: (i, n) => i(...n)
3395
+ }));
3396
+ }
3397
+ }
3398
+ async _closeConnection(t) {
3399
+ const e = this._peers.get(t);
3400
+ e && await e.closeConnection();
3401
+ }
3402
+ _isUnregistered(t) {
3403
+ return !t || this._peers.get(t.id) !== t;
3404
+ }
3405
+ };
3406
+ G([
3407
+ q
3408
+ ], j.prototype, "_instanceId", void 0);
3409
+ G([
3410
+ q
3411
+ ], j.prototype, "ownPeerId", null);
3412
+ G([
3413
+ q
3414
+ ], j.prototype, "topic", null);
3415
+ G([
3416
+ F
3417
+ ], j.prototype, "onSwarmEvent", null);
3418
+ G([
3419
+ F
3420
+ ], j.prototype, "onOffer", null);
3421
+ G([
3422
+ F
3423
+ ], j.prototype, "goOffline", null);
3424
+ G([
3425
+ F
3426
+ ], j.prototype, "goOnline", null);
3427
+ var Ve = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/swarm/swarm-mapper.ts", Ws = class {
3428
+ get peers() {
3429
+ return Array.from(this._peers.values());
3430
+ }
3431
+ constructor(t) {
3432
+ this._swarm = t, this._subscriptions = new Pt(), this._connectionSubscriptions = new O(m.hash), this._peers = new O(m.hash), this.mapUpdated = new S(), this._subscriptions.add(t.connectionAdded.on((e) => {
3433
+ this._update(), this._connectionSubscriptions.set(e.remoteId, e.stateChanged.on(() => {
3434
+ this._update();
3435
+ }));
3436
+ })), this._subscriptions.add(t.disconnected.on((e) => {
3437
+ var s;
3438
+ (s = this._connectionSubscriptions.get(e)) == null || s(), this._connectionSubscriptions.delete(e), this._update();
3439
+ })), this._update();
3440
+ }
3441
+ _update() {
3442
+ a("updating swarm", void 0, {
3443
+ F: Ve,
3444
+ L: 72,
3445
+ S: this,
3446
+ C: (t, e) => t(...e)
3447
+ }), this._peers.clear(), this._peers.set(this._swarm.ownPeerId, {
3448
+ id: this._swarm.ownPeerId,
3449
+ state: "ME",
3450
+ connections: []
3451
+ });
3452
+ for (const t of this._swarm.connections)
3453
+ this._peers.set(t.remoteId, {
3454
+ id: t.remoteId,
3455
+ state: t.state,
3456
+ connections: [
3457
+ this._swarm.ownPeerId
3458
+ ]
3459
+ });
3460
+ a("graph changed", {
3461
+ directConnections: this._swarm.connections.length,
3462
+ totalPeersInSwarm: this._peers.size
3463
+ }, {
3464
+ F: Ve,
3465
+ L: 113,
3466
+ S: this,
3467
+ C: (t, e) => t(...e)
3468
+ }), this.mapUpdated.emit(Array.from(this._peers.values()));
3469
+ }
3470
+ // TODO(burdon): Async open/close.
3471
+ destroy() {
3472
+ Array.from(this._connectionSubscriptions.values()).forEach((t) => t()), this._subscriptions.clear();
3473
+ }
3474
+ }, J = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/swarm/connection-limiter.ts", Xs = 50, Vs = class {
3475
+ constructor({ maxConcurrentInitConnections: t = Xs } = {}) {
3476
+ this._ctx = new N(void 0, {
3477
+ F: J,
3478
+ L: 23
3479
+ }), this._waitingPromises = new O(m.hash), this.resolveWaitingPromises = new at(this._ctx, async () => {
3480
+ Array.from(this._waitingPromises.values()).slice(0, this._maxConcurrentInitConnections).forEach(({ resolve: e }) => {
3481
+ e();
3482
+ });
3483
+ }), this._maxConcurrentInitConnections = t;
3484
+ }
3485
+ /**
3486
+ * @returns Promise that resolves in queue when connections amount with 'CONNECTING' state is below the limit.
3487
+ */
3488
+ async connecting(t) {
3489
+ f(!this._waitingPromises.has(t), "Peer is already waiting for connection", {
3490
+ F: J,
3491
+ L: 48,
3492
+ S: this,
3493
+ A: [
3494
+ "!this._waitingPromises.has(sessionId)",
3495
+ "'Peer is already waiting for connection'"
3496
+ ]
3497
+ }), a("waiting", {
3498
+ sessionId: t
3499
+ }, {
3500
+ F: J,
3501
+ L: 49,
3502
+ S: this,
3503
+ C: (e, s) => e(...s)
3504
+ }), await new Promise((e, s) => {
3505
+ this._waitingPromises.set(t, {
3506
+ resolve: e,
3507
+ reject: s
3508
+ }), this.resolveWaitingPromises.schedule();
3509
+ }), a("allow", {
3510
+ sessionId: t
3511
+ }, {
3512
+ F: J,
3513
+ L: 57,
3514
+ S: this,
3515
+ C: (e, s) => e(...s)
3516
+ });
3517
+ }
3518
+ /**
3519
+ * Rejects promise returned by `connecting` method.
3520
+ */
3521
+ doneConnecting(t) {
3522
+ a("done", {
3523
+ sessionId: t
3524
+ }, {
3525
+ F: J,
3526
+ L: 64,
3527
+ S: this,
3528
+ C: (e, s) => e(...s)
3529
+ }), this._waitingPromises.has(t) && (this._waitingPromises.get(t).reject(new xe()), this._waitingPromises.delete(t), this.resolveWaitingPromises.schedule());
3530
+ }
3531
+ }, Zs = 1e3 * 60 * 15, Ze;
3532
+ (function(t) {
3533
+ t.CONNECTION_STATE_CHANGED = "CONNECTION_STATE_CHANGED", t.PROTOCOL_ERROR = "PROTOCOL_ERROR", t.PROTOCOL_EXTENSIONS_INITIALIZED = "PROTOCOL_EXTENSIONS_INITIALIZED", t.PROTOCOL_EXTENSIONS_HANDSHAKE = "PROTOCOL_EXTENSIONS_HANDSHAKE", t.PROTOCOL_HANDSHAKE = "PROTOCOL_HANDSHAKE";
3534
+ })(Ze || (Ze = {}));
3535
+ var Js = class {
3536
+ constructor() {
3537
+ this._swarms = new O(m.hash), this.update = new S();
3538
+ }
3539
+ getSwarmInfo(t) {
3540
+ return this._swarms.get(t) ?? ot(new Error(`Swarm not found: ${t}`));
3541
+ }
3542
+ get swarms() {
3543
+ return Array.from(this._swarms.values());
3544
+ }
3545
+ joinedSwarm(t) {
3546
+ const e = {
3547
+ id: m.from(t._instanceId),
3548
+ topic: t.topic,
3549
+ isActive: !0,
3550
+ label: t.label,
3551
+ connections: []
3552
+ };
3553
+ this._swarms.set(m.from(t._instanceId), e), this.update.emit(), t.connectionAdded.on((s) => {
3554
+ var n, r, o;
3555
+ const i = {
3556
+ state: P.CREATED,
3557
+ closeReason: s.closeReason,
3558
+ remotePeerId: s.remoteId,
3559
+ sessionId: s.sessionId,
3560
+ transport: s.transport && Object.getPrototypeOf(s.transport).constructor.name,
3561
+ protocolExtensions: [],
3562
+ events: [],
3563
+ lastUpdate: /* @__PURE__ */ new Date()
3564
+ };
3565
+ e.connections.push(i), this.update.emit(), s.stateChanged.on(async (c) => {
3566
+ var _;
3567
+ if (i.state = c, i.closeReason = s.closeReason, i.lastUpdate = /* @__PURE__ */ new Date(), i.events.push({
3568
+ type: "CONNECTION_STATE_CHANGED",
3569
+ newState: c
3570
+ }), c === P.CONNECTED) {
3571
+ const d = await ((_ = s.transport) == null ? void 0 : _.getDetails());
3572
+ i.transportDetails = d;
3573
+ }
3574
+ this.update.emit();
3575
+ }), (r = (n = s.protocol) == null ? void 0 : n.stats) == null || r.on((c) => {
3576
+ i.readBufferSize = c.readBufferSize, i.writeBufferSize = c.writeBufferSize, i.streams = c.channels, i.lastUpdate = /* @__PURE__ */ new Date(), this.update.emit();
3577
+ }), (o = s.transportStats) == null || o.on((c) => {
3578
+ i.transportBytesSent = c.bytesSent, i.transportBytesReceived = c.bytesReceived, i.transportPacketsSent = c.packetsSent, i.transportPacketsReceived = c.packetsReceived;
3579
+ }), Qs(e);
3580
+ });
3581
+ }
3582
+ leftSwarm(t) {
3583
+ this.getSwarmInfo(m.from(t._instanceId)).isActive = !1, this.update.emit();
3584
+ }
3585
+ }, Qs = (t) => {
3586
+ var e;
3587
+ t.connections = (e = t.connections) == null ? void 0 : e.filter((s) => s.lastUpdate ? Date.now() - s.lastUpdate.getTime() < Zs : !0);
3588
+ };
3589
+ function gt(t, e, s, i) {
3590
+ var n = arguments.length, r = n < 3 ? e : i === null ? i = Object.getOwnPropertyDescriptor(e, s) : i, o;
3591
+ if (typeof Reflect == "object" && typeof Reflect.decorate == "function")
3592
+ r = Reflect.decorate(t, e, s, i);
3593
+ else
3594
+ for (var c = t.length - 1; c >= 0; c--)
3595
+ (o = t[c]) && (r = (n < 3 ? o(r) : n > 3 ? o(e, s, r) : o(e, s)) || r);
3596
+ return n > 3 && r && Object.defineProperty(e, s, r), r;
3597
+ }
3598
+ var I = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/network-manager.ts", mt = class {
3599
+ constructor({ transportFactory: t, signalManager: e, log: s }) {
3600
+ this._swarms = new O(m.hash), this._mappers = new O(m.hash), this._instanceId = m.random().toHex(), this._connectionState = ue.ONLINE, this.connectionStateChanged = new S(), this.topicsUpdated = new S(), this._transportFactory = t, this._signalManager = e, this._signalManager.swarmEvent.on(({ topic: i, swarmEvent: n }) => {
3601
+ var r;
3602
+ return (r = this._swarms.get(i)) == null ? void 0 : r.onSwarmEvent(n);
3603
+ }), this._messenger = new kt({
3604
+ signalManager: this._signalManager
3605
+ }), this._signalConnection = {
3606
+ join: (i) => this._signalManager.join(i),
3607
+ leave: (i) => this._signalManager.leave(i)
3608
+ }, this._connectionLimiter = new Vs(), s && (this._connectionLog = new Js());
3609
+ }
3610
+ // TODO(burdon): Remove access (Devtools only).
3611
+ get connectionLog() {
3612
+ return this._connectionLog;
3613
+ }
3614
+ get connectionState() {
3615
+ return this._connectionState;
3616
+ }
3617
+ // TODO(burdon): Reconcile with "discovery_key".
3618
+ get topics() {
3619
+ return Array.from(this._swarms.keys());
3620
+ }
3621
+ getSwarmMap(t) {
3622
+ return this._mappers.get(t);
3623
+ }
3624
+ getSwarm(t) {
3625
+ return this._swarms.get(t);
3626
+ }
3627
+ async open() {
3628
+ a.trace("dxos.mesh.network-manager.open", $.begin({
3629
+ id: this._instanceId
3630
+ }), {
3631
+ F: I,
3632
+ L: 126,
3633
+ S: this,
3634
+ C: (t, e) => t(...e)
3635
+ }), await this._messenger.open(), await this._signalManager.open(), a.trace("dxos.mesh.network-manager.open", $.end({
3636
+ id: this._instanceId
3637
+ }), {
3638
+ F: I,
3639
+ L: 129,
3640
+ S: this,
3641
+ C: (t, e) => t(...e)
3642
+ });
3643
+ }
3644
+ async close() {
3645
+ for (const t of this._swarms.keys())
3646
+ await this.leaveSwarm(t).catch((e) => {
3647
+ a(e, void 0, {
3648
+ F: I,
3649
+ L: 135,
3650
+ S: this,
3651
+ C: (s, i) => s(...i)
3652
+ });
3653
+ });
3654
+ await this._messenger.close(), await this._signalManager.close();
3655
+ }
3656
+ /**
3657
+ * Join the swarm.
3658
+ */
3659
+ async joinSwarm({ topic: t, peerId: e, topology: s, protocolProvider: i, label: n }) {
3660
+ var o;
3661
+ if (f(m.isPublicKey(t), void 0, {
3662
+ F: I,
3663
+ L: 154,
3664
+ S: this,
3665
+ A: [
3666
+ "PublicKey.isPublicKey(topic)",
3667
+ ""
3668
+ ]
3669
+ }), f(m.isPublicKey(e), void 0, {
3670
+ F: I,
3671
+ L: 155,
3672
+ S: this,
3673
+ A: [
3674
+ "PublicKey.isPublicKey(peerId)",
3675
+ ""
3676
+ ]
3677
+ }), f(s, void 0, {
3678
+ F: I,
3679
+ L: 156,
3680
+ S: this,
3681
+ A: [
3682
+ "topology",
3683
+ ""
3684
+ ]
3685
+ }), f(typeof i == "function", void 0, {
3686
+ F: I,
3687
+ L: 157,
3688
+ S: this,
3689
+ A: [
3690
+ "typeof protocol === 'function'",
3691
+ ""
3692
+ ]
3693
+ }), this._swarms.has(t))
3694
+ throw new Error(`Already connected to swarm: ${m.from(t)}`);
3695
+ a("joining", {
3696
+ topic: m.from(t),
3697
+ peerId: e,
3698
+ topology: s.toString()
3699
+ }, {
3700
+ F: I,
3701
+ L: 162,
3702
+ S: this,
3703
+ C: (c, _) => c(..._)
3704
+ });
3705
+ const r = new j(t, e, s, i, this._messenger, this._transportFactory, n, this._connectionLimiter);
3706
+ return r.errors.handle((c) => {
3707
+ a("swarm error", {
3708
+ error: c
3709
+ }, {
3710
+ F: I,
3711
+ L: 175,
3712
+ S: this,
3713
+ C: (_, d) => _(...d)
3714
+ });
3715
+ }), this._swarms.set(t, r), this._mappers.set(t, new Ws(r)), await r.open(), this._signalConnection.join({
3716
+ topic: t,
3717
+ peerId: e
3718
+ }).catch((c) => a.catch(c, void 0, {
3719
+ F: I,
3720
+ L: 184,
3721
+ S: this,
3722
+ C: (_, d) => _(...d)
3723
+ })), this.topicsUpdated.emit(), (o = this._connectionLog) == null || o.joinedSwarm(r), a("joined", {
3724
+ topic: m.from(t),
3725
+ count: this._swarms.size
3726
+ }, {
3727
+ F: I,
3728
+ L: 188,
3729
+ S: this,
3730
+ C: (c, _) => c(..._)
3731
+ }), {
3732
+ close: () => this.leaveSwarm(t)
3733
+ };
3734
+ }
3735
+ /**
3736
+ * Close the connection.
3737
+ */
3738
+ async leaveSwarm(t) {
3739
+ var i;
3740
+ if (!this._swarms.has(t))
3741
+ return;
3742
+ a("leaving", {
3743
+ topic: m.from(t)
3744
+ }, {
3745
+ F: I,
3746
+ L: 205,
3747
+ S: this,
3748
+ C: (n, r) => n(...r)
3749
+ });
3750
+ const e = this._swarms.get(t);
3751
+ await this._signalConnection.leave({
3752
+ topic: t,
3753
+ peerId: e.ownPeerId
3754
+ }), this._mappers.get(t).destroy(), this._mappers.delete(t), (i = this._connectionLog) == null || i.leftSwarm(e), await e.destroy(), this._swarms.delete(t), this.topicsUpdated.emit(), a("left", {
3755
+ topic: m.from(t),
3756
+ count: this._swarms.size
3757
+ }, {
3758
+ F: I,
3759
+ L: 219,
3760
+ S: this,
3761
+ C: (n, r) => n(...r)
3762
+ });
3763
+ }
3764
+ async setConnectionState(t) {
3765
+ if (t !== this._connectionState) {
3766
+ switch (t) {
3767
+ case ue.OFFLINE: {
3768
+ this._connectionState = t, await Promise.all([
3769
+ ...this._swarms.values()
3770
+ ].map((e) => e.goOffline())), await this._messenger.close(), await this._signalManager.close();
3771
+ break;
3772
+ }
3773
+ case ue.ONLINE: {
3774
+ this._connectionState = t, this._messenger.open(), await Promise.all([
3775
+ ...this._swarms.values()
3776
+ ].map((e) => e.goOnline())), await this._signalManager.open();
3777
+ break;
3778
+ }
3779
+ }
3780
+ this.connectionStateChanged.emit(this._connectionState);
3781
+ }
3782
+ }
3783
+ };
3784
+ gt([
3785
+ F
3786
+ ], mt.prototype, "joinSwarm", null);
3787
+ gt([
3788
+ F
3789
+ ], mt.prototype, "leaveSwarm", null);
3790
+ function Ct(t, e, s, i) {
3791
+ var n = arguments.length, r = n < 3 ? e : i === null ? i = Object.getOwnPropertyDescriptor(e, s) : i, o;
3792
+ if (typeof Reflect == "object" && typeof Reflect.decorate == "function")
3793
+ r = Reflect.decorate(t, e, s, i);
3794
+ else
3795
+ for (var c = t.length - 1; c >= 0; c--)
3796
+ (o = t[c]) && (r = (n < 3 ? o(r) : n > 3 ? o(e, s, r) : o(e, s)) || r);
3797
+ return n > 3 && r && Object.defineProperty(e, s, r), r;
3798
+ }
3799
+ var k = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/transport/memory-transport.ts", Je = 1, Qe = (t) => new se.Transform({
3800
+ objectMode: !0,
3801
+ transform: (e, s, i) => {
3802
+ setTimeout(() => i(null, e), t);
3803
+ }
3804
+ }), A, wt = (A = class {
3805
+ constructor(e) {
3806
+ this._options = e, this._instanceId = m.random(), this._remote = new ee(), this._outgoingDelay = Qe(Je), this._incomingDelay = Qe(Je), this._closed = !1, this.closed = new S(), this.connected = new S(), this.errors = new ie(), f(!A._connections.has(this._instanceId), "Duplicate memory connection", {
3807
+ F: k,
3808
+ L: 64,
3809
+ S: this,
3810
+ A: [
3811
+ "!MemoryTransport._connections.has(this._instanceId)",
3812
+ "'Duplicate memory connection'"
3813
+ ]
3814
+ }), A._connections.set(this._instanceId, this);
3815
+ }
3816
+ get isOpen() {
3817
+ return !this._closed;
3818
+ }
3819
+ async open() {
3820
+ if (a("opening...", void 0, {
3821
+ F: k,
3822
+ L: 74,
3823
+ S: this,
3824
+ C: (e, s) => e(...s)
3825
+ }), this._options.initiator) {
3826
+ a("sending signal", void 0, {
3827
+ F: k,
3828
+ L: 78,
3829
+ S: this,
3830
+ C: (e, s) => e(...s)
3831
+ });
3832
+ try {
3833
+ await this._options.sendSignal({
3834
+ payload: {
3835
+ transportId: this._instanceId.toHex()
3836
+ }
3837
+ });
3838
+ } catch (e) {
3839
+ this._closed || this.errors.raise(ei(e));
3840
+ }
3841
+ } else
3842
+ this._remote.wait({
3843
+ timeout: this._options.timeout ?? 1e3
3844
+ }).then((e) => {
3845
+ if (!this._closed) {
3846
+ if (this._remoteInstanceId = e, this._remoteConnection = A._connections.get(this._remoteInstanceId), !this._remoteConnection) {
3847
+ this._closed = !0, this.closed.emit();
3848
+ return;
3849
+ }
3850
+ f(!this._remoteConnection._remoteConnection, `Remote already connected: ${this._remoteInstanceId}`, {
3851
+ F: k,
3852
+ L: 104,
3853
+ S: this,
3854
+ A: [
3855
+ "!this._remoteConnection._remoteConnection",
3856
+ "`Remote already connected: ${this._remoteInstanceId}`"
3857
+ ]
3858
+ }), this._remoteConnection._remoteConnection = this, this._remoteConnection._remoteInstanceId = this._instanceId, a("connected", void 0, {
3859
+ F: k,
3860
+ L: 108,
3861
+ S: this,
3862
+ C: (s, i) => s(...i)
3863
+ }), this._options.stream.pipe(this._outgoingDelay).pipe(this._remoteConnection._options.stream).pipe(this._incomingDelay).pipe(this._options.stream), this.connected.emit(), this._remoteConnection.connected.emit();
3864
+ }
3865
+ }).catch((e) => {
3866
+ this._closed || this.errors.raise(e);
3867
+ });
3868
+ }
3869
+ async close() {
3870
+ a("closing...", void 0, {
3871
+ F: k,
3872
+ L: 129,
3873
+ S: this,
3874
+ C: (e, s) => e(...s)
3875
+ }), this._closed = !0, A._connections.delete(this._instanceId), this._remoteConnection && (this._remoteConnection._closed = !0, A._connections.delete(this._remoteInstanceId), this._options.stream.unpipe(this._incomingDelay), this._incomingDelay.unpipe(this._remoteConnection._options.stream), this._remoteConnection._options.stream.unpipe(this._outgoingDelay), this._outgoingDelay.unpipe(this._options.stream), this._options.stream.unpipe(this._outgoingDelay), this._remoteConnection.closed.emit(), this._remoteConnection._remoteConnection = void 0, this._remoteConnection = void 0), this.closed.emit(), a("closed", void 0, {
3876
+ F: k,
3877
+ L: 157,
3878
+ S: this,
3879
+ C: (e, s) => e(...s)
3880
+ });
3881
+ }
3882
+ async onSignal({ payload: e }) {
3883
+ if (a("received signal", {
3884
+ payload: e
3885
+ }, {
3886
+ F: k,
3887
+ L: 161,
3888
+ S: this,
3889
+ C: (i, n) => i(...n)
3890
+ }), !(e != null && e.transportId))
3891
+ return;
3892
+ const s = e.transportId;
3893
+ if (s) {
3894
+ const i = m.fromHex(s);
3895
+ this._remote.wake(i);
3896
+ }
3897
+ }
3898
+ async getDetails() {
3899
+ return this._instanceId.toHex();
3900
+ }
3901
+ async getStats() {
3902
+ return {
3903
+ bytesSent: 0,
3904
+ bytesReceived: 0,
3905
+ packetsSent: 0,
3906
+ packetsReceived: 0
3907
+ };
3908
+ }
3909
+ }, A._connections = new O(m.hash), A);
3910
+ Ct([
3911
+ q
3912
+ ], wt.prototype, "_instanceId", void 0);
3913
+ Ct([
3914
+ q
3915
+ ], wt.prototype, "_remoteInstanceId", void 0);
3916
+ var ei = (t) => t instanceof Error ? t : new Error(String(t)), et;
3917
+ (function(t) {
3918
+ t.SIMPLE_PEER = "SIMPLE_PEER", t.SIMPLE_PEER_PROXY = "SIMPLE_PEER_PROXY", t.LIBDATACHANNEL = "LIBDATACHANNEL", t.MEMORY = "MEMORY", t.TCP = "TCP";
3919
+ })(et || (et = {}));
3920
+ var yt = null;
3921
+ try {
3922
+ yt = $s("@koush/wrtc");
3923
+ } catch {
3924
+ }
3925
+ var L = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/transport/simplepeer-transport.ts", ti = class {
3926
+ get isOpen() {
3927
+ return this._piped && !this._closed;
3928
+ }
3929
+ /**
3930
+ * @params opts.config formatted as per https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/RTCPeerConnection
3931
+ */
3932
+ constructor(t) {
3933
+ this._params = t, this._closed = !1, this._piped = !1, this.closed = new S(), this.connected = new S(), this.errors = new ie(), this._instanceId = m.random().toHex(), a.trace("dxos.mesh.webrtc-transport.constructor", $.begin({
3934
+ id: this._instanceId
3935
+ }), {
3936
+ F: L,
3937
+ L: 50,
3938
+ S: this,
3939
+ C: (e, s) => e(...s)
3940
+ }), a("created connection", t, {
3941
+ F: L,
3942
+ L: 51,
3943
+ S: this,
3944
+ C: (e, s) => e(...s)
3945
+ }), this._peer = new je({
3946
+ channelName: "dxos.mesh.transport",
3947
+ initiator: this._params.initiator,
3948
+ wrtc: je.WEBRTC_SUPPORT ? void 0 : yt ?? ot(new Error("wrtc not available")),
3949
+ config: this._params.webrtcConfig
3950
+ }), this._peer.on("signal", async (e) => {
3951
+ a("signal", e, {
3952
+ F: L,
3953
+ L: 60,
3954
+ S: this,
3955
+ C: (s, i) => s(...i)
3956
+ }), await this._params.sendSignal({
3957
+ payload: {
3958
+ data: e
3959
+ }
3960
+ });
3961
+ }), this._peer.on("connect", () => {
3962
+ a("connected", void 0, {
3963
+ F: L,
3964
+ L: 65,
3965
+ S: this,
3966
+ C: (e, s) => e(...s)
3967
+ }), this._params.stream.pipe(this._peer).pipe(this._params.stream), this._piped = !0, this.connected.emit();
3968
+ }), this._peer.on("close", async () => {
3969
+ a("closed", void 0, {
3970
+ F: L,
3971
+ L: 72,
3972
+ S: this,
3973
+ C: (e, s) => e(...s)
3974
+ }), await this.close();
3975
+ }), this._peer.on("error", async (e) => {
3976
+ var s, i;
3977
+ if (typeof RTCError < "u" && e instanceof RTCError)
3978
+ e.errorDetail === "sctp-failure" ? this.errors.raise(new dt("sctp-failure from RTCError", e)) : (a.info("unknown RTCError", {
3979
+ err: e
3980
+ }, {
3981
+ F: L,
3982
+ L: 83,
3983
+ S: this,
3984
+ C: (n, r) => n(...r)
3985
+ }), this.errors.raise(new Ee("unknown RTCError", e)));
3986
+ else if ("code" in e)
3987
+ switch (a.info("simple-peer error", e, {
3988
+ F: L,
3989
+ L: 88,
3990
+ S: this,
3991
+ C: (n, r) => n(...r)
3992
+ }), e.code) {
3993
+ case "ERR_WEBRTC_SUPPORT":
3994
+ this.errors.raise(new lt("WebRTC not supported", e));
3995
+ break;
3996
+ case "ERR_SIGNALING":
3997
+ this.errors.raise(new he("signaling failure", e));
3998
+ break;
3999
+ case "ERR_ICE_CONNECTION_FAILURE":
4000
+ case "ERR_DATA_CHANNEL":
4001
+ case "ERR_CONNECTION_FAILURE":
4002
+ this.errors.raise(new he("unknown communication failure", e));
4003
+ break;
4004
+ case "ERR_CREATE_OFFER":
4005
+ case "ERR_CREATE_ANSWER":
4006
+ case "ERR_SET_LOCAL_DESCRIPTION":
4007
+ case "ERR_SET_REMOTE_DESCRIPTION":
4008
+ case "ERR_ADD_ICE_CANDIDATE":
4009
+ this.errors.raise(new Ee("unknown simple-peer library failure", e));
4010
+ break;
4011
+ default:
4012
+ this.errors.raise(new Error("unknown simple-peer error"));
4013
+ break;
4014
+ }
4015
+ else
4016
+ a.info("unknown peer connection error", e, {
4017
+ F: L,
4018
+ L: 114,
4019
+ S: this,
4020
+ C: (n, r) => n(...r)
4021
+ }), this.errors.raise(e);
4022
+ try {
4023
+ typeof ((i = (s = this._peer) == null ? void 0 : s._pc) == null ? void 0 : i.getStats) == "function" && this._peer._pc.getStats().then((n) => {
4024
+ a.info("report after webrtc error", {
4025
+ config: this._params.webrtcConfig,
4026
+ stats: Object.fromEntries(n.entries())
4027
+ }, {
4028
+ F: L,
4029
+ L: 122,
4030
+ S: this,
4031
+ C: (r, o) => r(...o)
4032
+ });
4033
+ });
4034
+ } catch (n) {
4035
+ a.catch(n, void 0, {
4036
+ F: L,
4037
+ L: 129,
4038
+ S: this,
4039
+ C: (r, o) => r(...o)
4040
+ });
4041
+ }
4042
+ await this.close();
4043
+ }), a.trace("dxos.mesh.webrtc-transport.constructor", $.end({
4044
+ id: this._instanceId
4045
+ }), {
4046
+ F: L,
4047
+ L: 135,
4048
+ S: this,
4049
+ C: (e, s) => e(...s)
4050
+ });
4051
+ }
4052
+ async getStats() {
4053
+ const t = await this._getStats();
4054
+ return t ? {
4055
+ bytesSent: t.transport.bytesSent,
4056
+ bytesReceived: t.transport.bytesReceived,
4057
+ packetsSent: t.transport.packetsSent,
4058
+ packetsReceived: t.transport.packetsReceived,
4059
+ rawStats: t.raw
4060
+ } : {
4061
+ bytesSent: 0,
4062
+ bytesReceived: 0,
4063
+ packetsSent: 0,
4064
+ packetsReceived: 0,
4065
+ rawStats: {}
4066
+ };
4067
+ }
4068
+ async _getStats() {
4069
+ var t, e;
4070
+ return typeof ((e = (t = this._peer) == null ? void 0 : t._pc) == null ? void 0 : e.getStats) != "function" ? null : await this._peer._pc.getStats().then((s) => {
4071
+ const i = Array.from(s.entries()), n = i.filter((_) => _[1].type === "transport")[0][1], r = i.filter((_) => _[0] === n.selectedCandidatePairId);
4072
+ let o, c;
4073
+ return r.length > 0 && (o = r[0][1], c = i.filter((_) => _[0] === o.remoteCandidateId)[0][1]), {
4074
+ datachannel: i.filter((_) => _[1].type === "data-channel")[0][1],
4075
+ transport: n,
4076
+ selectedCandidatePair: o,
4077
+ remoteCandidate: c,
4078
+ raw: Object.fromEntries(s.entries())
4079
+ };
4080
+ });
4081
+ }
4082
+ async getDetails() {
4083
+ const t = await this._getStats(), e = t == null ? void 0 : t.remoteCandidate;
4084
+ return e ? e.candidateType === "relay" ? `${e.ip}:${e.port}/${e.protocol} relay for ${e.relatedAddress}:${e.relatedPort}` : `${e.ip}:${e.port}/${e.protocol} ${e.candidateType}` : "unavailable";
4085
+ }
4086
+ async open() {
4087
+ }
4088
+ async close() {
4089
+ a("closing...", void 0, {
4090
+ F: L,
4091
+ L: 200,
4092
+ S: this,
4093
+ C: (t, e) => t(...e)
4094
+ }), !this._closed && (this._disconnectStreams(), this._peer.destroy(), this._closed = !0, this.closed.emit(), a("closed", void 0, {
4095
+ F: L,
4096
+ L: 208,
4097
+ S: this,
4098
+ C: (t, e) => t(...e)
4099
+ }));
4100
+ }
4101
+ async onSignal(t) {
4102
+ this._closed || (ns(t.payload.data, "Signal message must contain signal data."), this._peer.signal(t.payload.data));
4103
+ }
4104
+ _disconnectStreams() {
4105
+ var t, e, s, i;
4106
+ this._piped && ((i = (s = (e = (t = this._params.stream).unpipe) == null ? void 0 : e.call(t, this._peer)) == null ? void 0 : s.unpipe) == null || i.call(s, this._params.stream));
4107
+ }
4108
+ }, Y = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/transport/simplepeer-transport-service.ts", hi = class {
4109
+ constructor(t) {
4110
+ this._webrtcConfig = t, this.transports = new O(m.hash);
4111
+ }
4112
+ open(t) {
4113
+ return new xt(({ ready: s, next: i, close: n }) => {
4114
+ const r = new se.Duplex({
4115
+ read: () => {
4116
+ const _ = [
4117
+ ...c.writeCallbacks
4118
+ ];
4119
+ c.writeCallbacks.length = 0;
4120
+ for (const d of _)
4121
+ d();
4122
+ },
4123
+ write: function(_, d, h) {
4124
+ i({
4125
+ data: {
4126
+ payload: _
4127
+ }
4128
+ }), h();
4129
+ }
4130
+ }), o = new ti({
4131
+ initiator: t.initiator,
4132
+ stream: r,
4133
+ webrtcConfig: this._webrtcConfig,
4134
+ sendSignal: async (_) => {
4135
+ i({
4136
+ signal: {
4137
+ payload: _
4138
+ }
4139
+ });
4140
+ }
4141
+ });
4142
+ o.open(), i({
4143
+ connection: {
4144
+ state: K.CONNECTING
4145
+ }
4146
+ }), o.connected.on(() => {
4147
+ i({
4148
+ connection: {
4149
+ state: K.CONNECTED
4150
+ }
4151
+ });
4152
+ }), o.errors.handle((_) => {
4153
+ i({
4154
+ connection: {
4155
+ state: K.CLOSED,
4156
+ error: _.toString()
4157
+ }
4158
+ }), n(_);
4159
+ }), o.closed.on(() => {
4160
+ i({
4161
+ connection: {
4162
+ state: K.CLOSED
4163
+ }
4164
+ }), n();
4165
+ });
4166
+ const c = {
4167
+ transport: o,
4168
+ stream: r,
4169
+ writeCallbacks: [],
4170
+ state: "OPEN"
4171
+ };
4172
+ s(), this.transports.set(t.proxyId, c);
4173
+ });
4174
+ }
4175
+ async sendSignal({ proxyId: t, signal: e }) {
4176
+ f(this.transports.has(t), void 0, {
4177
+ F: Y,
4178
+ L: 119,
4179
+ S: this,
4180
+ A: [
4181
+ "this.transports.has(proxyId)",
4182
+ ""
4183
+ ]
4184
+ }), await this.transports.get(t).transport.onSignal(e);
4185
+ }
4186
+ async getDetails({ proxyId: t }) {
4187
+ return f(this.transports.has(t), void 0, {
4188
+ F: Y,
4189
+ L: 124,
4190
+ S: this,
4191
+ A: [
4192
+ "this.transports.has(proxyId)",
4193
+ ""
4194
+ ]
4195
+ }), {
4196
+ details: await this.transports.get(t).transport.getDetails()
4197
+ };
4198
+ }
4199
+ async getStats({ proxyId: t }) {
4200
+ return f(this.transports.has(t), void 0, {
4201
+ F: Y,
4202
+ L: 129,
4203
+ S: this,
4204
+ A: [
4205
+ "this.transports.has(proxyId)",
4206
+ ""
4207
+ ]
4208
+ }), {
4209
+ stats: await this.transports.get(t).transport.getStats()
4210
+ };
4211
+ }
4212
+ async sendData({ proxyId: t, payload: e }) {
4213
+ var n;
4214
+ ((n = this.transports.get(t)) == null ? void 0 : n.state) !== "OPEN" && a.debug("transport is closed", void 0, {
4215
+ F: Y,
4216
+ L: 135,
4217
+ S: this,
4218
+ C: (r, o) => r(...o)
4219
+ }), f(this.transports.has(t), void 0, {
4220
+ F: Y,
4221
+ L: 137,
4222
+ S: this,
4223
+ A: [
4224
+ "this.transports.has(proxyId)",
4225
+ ""
4226
+ ]
4227
+ });
4228
+ const s = this.transports.get(t);
4229
+ s.stream.push(e) || await new Promise((r) => {
4230
+ s.writeCallbacks.push(r);
4231
+ });
4232
+ }
4233
+ async close({ proxyId: t }) {
4234
+ var e, s;
4235
+ await ((e = this.transports.get(t)) == null ? void 0 : e.transport.close()), await ((s = this.transports.get(t)) == null ? void 0 : s.stream.end()), this.transports.get(t) && (this.transports.get(t).state = "CLOSED"), a("Closed.", void 0, {
4236
+ F: Y,
4237
+ L: 153,
4238
+ S: this,
4239
+ C: (i, n) => i(...n)
4240
+ });
4241
+ }
4242
+ };
4243
+ function si(t, e, s, i) {
4244
+ var n = arguments.length, r = n < 3 ? e : i === null ? i = Object.getOwnPropertyDescriptor(e, s) : i, o;
4245
+ if (typeof Reflect == "object" && typeof Reflect.decorate == "function")
4246
+ r = Reflect.decorate(t, e, s, i);
4247
+ else
4248
+ for (var c = t.length - 1; c >= 0; c--)
4249
+ (o = t[c]) && (r = (n < 3 ? o(r) : n > 3 ? o(e, s, r) : o(e, s)) || r);
4250
+ return n > 3 && r && Object.defineProperty(e, s, r), r;
4251
+ }
4252
+ var b = "/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/transport/libdatachannel-transport.ts", tt = "dxos.mesh.transport", ii = 64 * 1024, st = 64 * 1024, B, ni = (B = class {
4253
+ constructor(e) {
4254
+ this._options = e, this._closed = !1, this._connected = !1, this._writeCallback = null, this._readyForCandidates = new ee(), this.closed = new S(), this.connected = new S(), this.errors = new ie();
4255
+ }
4256
+ get isOpen() {
4257
+ return !!this._peer && !this._closed;
4258
+ }
4259
+ async open() {
4260
+ this._closed && this.errors.raise(new Error("connection already closed"));
4261
+ const { RTCPeerConnection: e } = (await it("node-datachannel/polyfill")).default;
4262
+ this._options.webrtcConfig ? this._options.webrtcConfig.iceServers = this._options.webrtcConfig.iceServers ?? [] : this._options.webrtcConfig = {
4263
+ iceServers: []
4264
+ }, this._peer = new e(this._options.webrtcConfig), this._peer.onicecandidateerror = (s) => {
4265
+ a.error("peer.onicecandidateerror", {
4266
+ event: s
4267
+ }, {
4268
+ F: b,
4269
+ L: 77,
4270
+ S: this,
4271
+ C: (i, n) => i(...n)
4272
+ });
4273
+ }, this._peer.onconnectionstatechange = (s) => {
4274
+ var i;
4275
+ a.debug("peer.onconnectionstatechange", {
4276
+ event: s,
4277
+ peerConnectionState: (i = this._peer) == null ? void 0 : i.connectionState,
4278
+ transportConnectionState: this._connected
4279
+ }, {
4280
+ F: b,
4281
+ L: 81,
4282
+ S: this,
4283
+ C: (n, r) => n(...r)
4284
+ });
4285
+ }, this._peer.onicecandidate = async (s) => {
4286
+ if (a.debug("peer.onicecandidate", {
4287
+ event: s
4288
+ }, {
4289
+ F: b,
4290
+ L: 91,
4291
+ S: this,
4292
+ C: (i, n) => i(...n)
4293
+ }), s.candidate)
4294
+ try {
4295
+ await this._options.sendSignal({
4296
+ payload: {
4297
+ data: {
4298
+ type: "candidate",
4299
+ candidate: {
4300
+ candidate: s.candidate.candidate,
4301
+ // These fields never seem to be not null, but connecting to Chrome doesn't work if they are.
4302
+ sdpMLineIndex: s.candidate.sdpMLineIndex ?? 0,
4303
+ sdpMid: s.candidate.sdpMid ?? 0
4304
+ }
4305
+ }
4306
+ }
4307
+ });
4308
+ } catch (i) {
4309
+ a.info("signaling error", {
4310
+ err: i
4311
+ }, {
4312
+ F: b,
4313
+ L: 108,
4314
+ S: this,
4315
+ C: (n, r) => n(...r)
4316
+ });
4317
+ }
4318
+ }, this._options.initiator ? (f(this._peer, "not open", {
4319
+ F: b,
4320
+ L: 114,
4321
+ S: this,
4322
+ A: [
4323
+ "this._peer",
4324
+ "'not open'"
4325
+ ]
4326
+ }), this._peer.createOffer().then(async (s) => {
4327
+ var i;
4328
+ this._closed || (((i = this._peer) == null ? void 0 : i.connectionState) !== "connecting" && (a.error("peer not connecting", {
4329
+ peer: this._peer
4330
+ }, {
4331
+ F: b,
4332
+ L: 125,
4333
+ S: this,
4334
+ C: (n, r) => n(...r)
4335
+ }), this.errors.raise(new Error("invalid state: peer is initiator, but other peer not in state connecting"))), a.debug("creating offer", {
4336
+ peer: this._peer,
4337
+ offer: s
4338
+ }, {
4339
+ F: b,
4340
+ L: 129,
4341
+ S: this,
4342
+ C: (n, r) => n(...r)
4343
+ }), await this._peer.setLocalDescription(s), await this._options.sendSignal({
4344
+ payload: {
4345
+ data: {
4346
+ type: s.type,
4347
+ sdp: s.sdp
4348
+ }
4349
+ }
4350
+ }));
4351
+ }).catch((s) => {
4352
+ this.errors.raise(s);
4353
+ }), this._handleChannel(this._peer.createDataChannel(tt)), a.debug("created data channel", void 0, {
4354
+ F: b,
4355
+ L: 139,
4356
+ S: this,
4357
+ C: (s, i) => s(...i)
4358
+ }), this._peer.ondatachannel = () => {
4359
+ this.errors.raise(new Error("unexpected ondatachannel event for initiator"));
4360
+ }) : this._peer.ondatachannel = (s) => {
4361
+ a.debug("peer.ondatachannel (non-initiator)", {
4362
+ event: s
4363
+ }, {
4364
+ F: b,
4365
+ L: 145,
4366
+ S: this,
4367
+ C: (i, n) => i(...n)
4368
+ }), s.channel.label !== tt && this.errors.raise(new Error(`unexpected channel label ${s.channel.label}`)), this._handleChannel(s.channel);
4369
+ }, B._instanceCount++;
4370
+ }
4371
+ async close() {
4372
+ await this._close(), --B._instanceCount === 0 && (await it("node-datachannel")).cleanup();
4373
+ }
4374
+ async _close() {
4375
+ var e;
4376
+ if (!this._closed) {
4377
+ await this._disconnectStreams();
4378
+ try {
4379
+ (e = this._peer) == null || e.close();
4380
+ } catch (s) {
4381
+ this.errors.raise(s);
4382
+ }
4383
+ this._peer = void 0, this._closed = !0, this.closed.emit();
4384
+ }
4385
+ }
4386
+ /**
4387
+ * Handle data channel events.
4388
+ */
4389
+ _handleChannel(e) {
4390
+ this._channel = e, this._channel.onopen = () => {
4391
+ a.debug("channel.onopen", void 0, {
4392
+ F: b,
4393
+ L: 190,
4394
+ S: this,
4395
+ C: (i, n) => i(...n)
4396
+ });
4397
+ const s = new as.Duplex({
4398
+ read: () => {
4399
+ },
4400
+ write: async (i, n, r) => {
4401
+ i.length > st && this.errors.raise(new Error(`message too large: ${i.length} > ${st}`));
4402
+ try {
4403
+ e.send(i);
4404
+ } catch (o) {
4405
+ this.errors.raise(o), await this._close();
4406
+ }
4407
+ this._channel.bufferedAmount > ii ? (this._writeCallback !== null && a.error("consumer trying to write before we are ready for more data", void 0, {
4408
+ F: b,
4409
+ L: 207,
4410
+ S: this,
4411
+ C: (o, c) => o(...c)
4412
+ }), this._writeCallback = r) : r();
4413
+ }
4414
+ });
4415
+ s.pipe(this._options.stream).pipe(s), this._stream = s, this._connected = !0, this.connected.emit();
4416
+ }, this._channel.onclose = async (s) => {
4417
+ a.info("channel.onclose", {
4418
+ err: s
4419
+ }, {
4420
+ F: b,
4421
+ L: 223,
4422
+ S: this,
4423
+ C: (i, n) => i(...n)
4424
+ }), await this._close();
4425
+ }, this._channel.onerror = async (s) => {
4426
+ this.errors.raise(new Error("channel error: " + s.toString())), await this._close();
4427
+ }, this._channel.onbufferedamountlow = () => {
4428
+ const s = this._writeCallback;
4429
+ this._writeCallback = null, s == null || s();
4430
+ }, this._channel.onmessage = (s) => {
4431
+ let i = s.data;
4432
+ i instanceof ArrayBuffer && (i = X.from(i)), this._stream.push(i);
4433
+ };
4434
+ }
4435
+ async onSignal(e) {
4436
+ f(this._peer, "not open", {
4437
+ F: b,
4438
+ L: 249,
4439
+ S: this,
4440
+ A: [
4441
+ "this._peer",
4442
+ "'not open'"
4443
+ ]
4444
+ });
4445
+ try {
4446
+ const s = e.payload.data;
4447
+ switch (s.type) {
4448
+ case "offer": {
4449
+ if (this._peer.connectionState !== "new") {
4450
+ a.error("received offer but peer not in state new", {
4451
+ peer: this._peer
4452
+ }, {
4453
+ F: b,
4454
+ L: 256,
4455
+ S: this,
4456
+ C: (i, n) => i(...n)
4457
+ }), this.errors.raise(new Error("invalid signalling state: received offer when peer is not in state new"));
4458
+ break;
4459
+ }
4460
+ try {
4461
+ await this._peer.setRemoteDescription({
4462
+ type: s.type,
4463
+ sdp: s.sdp
4464
+ });
4465
+ const i = await this._peer.createAnswer();
4466
+ await this._peer.setLocalDescription(i), await this._options.sendSignal({
4467
+ payload: {
4468
+ data: {
4469
+ type: i.type,
4470
+ sdp: i.sdp
4471
+ }
4472
+ }
4473
+ }), this._readyForCandidates.wake();
4474
+ } catch (i) {
4475
+ a.error("cannot handle offer from signalling server", {
4476
+ err: i
4477
+ }, {
4478
+ F: b,
4479
+ L: 268,
4480
+ S: this,
4481
+ C: (n, r) => n(...r)
4482
+ }), this.errors.raise(new Error("error handling offer"));
4483
+ }
4484
+ break;
4485
+ }
4486
+ case "answer":
4487
+ try {
4488
+ await this._peer.setRemoteDescription({
4489
+ type: s.type,
4490
+ sdp: s.sdp
4491
+ }), this._readyForCandidates.wake();
4492
+ } catch (i) {
4493
+ a.error("cannot handle answer from signalling server", {
4494
+ err: i
4495
+ }, {
4496
+ F: b,
4497
+ L: 279,
4498
+ S: this,
4499
+ C: (n, r) => n(...r)
4500
+ }), this.errors.raise(new Error("error handling answer"));
4501
+ }
4502
+ break;
4503
+ case "candidate":
4504
+ await this._readyForCandidates.wait(), await this._peer.addIceCandidate({
4505
+ candidate: s.candidate.candidate
4506
+ });
4507
+ break;
4508
+ default:
4509
+ a.error("unhandled signal type", {
4510
+ type: s.type,
4511
+ signal: e
4512
+ }, {
4513
+ F: b,
4514
+ L: 290,
4515
+ S: this,
4516
+ C: (i, n) => i(...n)
4517
+ }), this.errors.raise(new Error(`unhandled signal type ${s.type}`));
4518
+ }
4519
+ } catch (s) {
4520
+ a.catch(s, void 0, {
4521
+ F: b,
4522
+ L: 294,
4523
+ S: this,
4524
+ C: (i, n) => i(...n)
4525
+ });
4526
+ }
4527
+ }
4528
+ async getDetails() {
4529
+ const e = await this._getStats(), s = e == null ? void 0 : e.remoteCandidate;
4530
+ return s ? s.candidateType === "relay" ? `${s.ip}:${s.port} relay for ${s.relatedAddress}:${s.relatedPort}` : `${s.ip}:${s.port} ${s.candidateType}` : "unavailable";
4531
+ }
4532
+ async getStats() {
4533
+ const e = await this._getStats();
4534
+ return e ? {
4535
+ bytesSent: e.transport.bytesSent,
4536
+ bytesReceived: e.transport.bytesReceived,
4537
+ packetsSent: 0,
4538
+ packetsReceived: 0,
4539
+ rawStats: e.raw
4540
+ } : {
4541
+ bytesSent: 0,
4542
+ bytesReceived: 0,
4543
+ packetsSent: 0,
4544
+ packetsReceived: 0,
4545
+ rawStats: {}
4546
+ };
4547
+ }
4548
+ async _getStats() {
4549
+ f(this._peer, "not open", {
4550
+ F: b,
4551
+ L: 334,
4552
+ S: this,
4553
+ A: [
4554
+ "this._peer",
4555
+ "'not open'"
4556
+ ]
4557
+ });
4558
+ const e = await this._peer.getStats(), s = Array.from(e.entries()), i = s.filter((c) => c[1].type === "transport")[0][1], n = s.filter((c) => c[0] === i.selectedCandidatePairId);
4559
+ let r, o;
4560
+ return n.length > 0 && (r = n[0][1], o = s.filter((c) => c[0] === r.remoteCandidateId)[0][1]), {
4561
+ transport: i,
4562
+ selectedCandidatePair: r,
4563
+ remoteCandidate: o,
4564
+ raw: Object.fromEntries(e)
4565
+ };
4566
+ }
4567
+ async _disconnectStreams() {
4568
+ var e, s, i, n;
4569
+ (n = (i = (s = (e = this._options.stream).unpipe) == null ? void 0 : s.call(e, this._stream)) == null ? void 0 : i.unpipe) == null || n.call(i, this._options.stream);
4570
+ }
4571
+ }, B._instanceCount = 0, B);
4572
+ si([
4573
+ F
4574
+ ], ni.prototype, "_close", null);
4575
+ var it = Function("path", "return import(path)");
4576
+ export {
4577
+ fe as Connection,
4578
+ Vs as ConnectionLimiter,
4579
+ Js as ConnectionLog,
4580
+ P as ConnectionState,
4581
+ Ze as EventType,
4582
+ ni as LibDataChannelTransport,
4583
+ Xs as MAX_CONCURRENT_INITIATING_CONNECTIONS,
4584
+ wt as MemoryTransport,
4585
+ ti as SimplePeerTransport,
4586
+ hi as SimplePeerTransportService,
4587
+ j as Swarm,
4588
+ Ws as SwarmMapper,
4589
+ Hs as SwarmMessenger,
4590
+ mt as SwarmNetworkManager,
4591
+ et as TransportKind
4592
+ };
4593
+ //# sourceMappingURL=index-DXRmq0_o.mjs.map