@decentnetwork/beagle 0.1.132 → 0.1.138

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- window.__DK_UI_VERSION="0.1.131";
1
+ window.__DK_UI_VERSION="0.1.138";
2
2
  "use strict";
3
3
  (() => {
4
4
  // packages/beagle-ui/dist/beagle-ui.js
@@ -5189,6 +5189,44 @@ ${peer.address}`
5189
5189
  justifyContent: "center"
5190
5190
  } }, /* @__PURE__ */ React.createElement(Icon, { name: app.icon, size: 19, color: "var(--accent)", stroke: 1.8 })), /* @__PURE__ */ React.createElement("div", { style: { flex: 1, minWidth: 0 } }, /* @__PURE__ */ React.createElement("div", { style: { fontFamily: "var(--ui)", fontSize: 14, fontWeight: 600, color: "var(--text)" } }, pickText(app.name, t && t.lang, app.id)), /* @__PURE__ */ React.createElement("div", { style: { fontFamily: "var(--ui)", fontSize: 12.5, color: "var(--faint)", marginTop: 2 } }, pickText(app.blurb, t && t.lang, "")), /* @__PURE__ */ React.createElement("div", { style: { fontFamily: "var(--mono)", fontSize: 11, color: "var(--dim)", marginTop: 3 } }, app.host ? zh ? "\u672C\u673A\u5E94\u7528" : "runs in this app" : String(app.origin || "").replace(/^https?:\/\//, ""))), /* @__PURE__ */ React.createElement(Btn, { tone: "accent", size: "sm", onClick: busy ? void 0 : () => open(app) }, busy === app.id ? zh ? "\u6253\u5F00\u4E2D\u2026" : "opening\u2026" : zh ? "\u6253\u5F00" : "Open")))));
5191
5191
  }
5192
+ var CLAIM_SUPPRESS_MS = 5 * 6e4;
5193
+ function newPageId() {
5194
+ return "p" + Math.random().toString(36).slice(2, 10) + Date.now().toString(36).slice(-4);
5195
+ }
5196
+ var norm = (id) => String(id || "").trim().toLowerCase();
5197
+ function silencedFor(rec, myPage) {
5198
+ if (!rec)
5199
+ return false;
5200
+ if (rec.state === "ended")
5201
+ return true;
5202
+ if (rec.state === "claimed")
5203
+ return !(rec.claim && rec.claim.page === myPage);
5204
+ return false;
5205
+ }
5206
+ function applyCallsTable(table, myPage, suppressed, now) {
5207
+ const stop = [];
5208
+ const ended = [];
5209
+ for (const rec of Array.isArray(table) ? table : []) {
5210
+ if (!rec || !rec.callId)
5211
+ continue;
5212
+ const id = norm(rec.callId);
5213
+ if (rec.state === "ended")
5214
+ ended.push(id);
5215
+ if (!silencedFor(rec, myPage))
5216
+ continue;
5217
+ if (!suppressed.has(id))
5218
+ suppressed.set(id, now);
5219
+ stop.push(id);
5220
+ }
5221
+ return { stop, ended };
5222
+ }
5223
+ function isSuppressed(suppressed, callId, now) {
5224
+ const at = suppressed.get(norm(callId));
5225
+ return !!at && now - at < CLAIM_SUPPRESS_MS;
5226
+ }
5227
+ function sameCall(a, b) {
5228
+ return !!a && !!b && norm(a) === norm(b);
5229
+ }
5192
5230
  var DK_FALLBACK_ICE_SERVERS = [
5193
5231
  { urls: "stun:stun.l.google.com:19302" },
5194
5232
  { urls: "turn:tokyo.fi.chat:3478", username: "allcom", credential: "allcompass" },
@@ -5296,6 +5334,9 @@ ${peer.address}`
5296
5334
  function dkRtcSignalBus() {
5297
5335
  if (window.__dkRtcSignalBus)
5298
5336
  return window.__dkRtcSignalBus;
5337
+ const pageId = window.__dkPageId || (window.__dkPageId = newPageId());
5338
+ let callsVersion = null;
5339
+ let callsTable = [];
5299
5340
  const PW = window.PeerWebRTC;
5300
5341
  const handlers = /* @__PURE__ */ new Map();
5301
5342
  const pendingCalls = [];
@@ -5326,12 +5367,18 @@ ${peer.address}`
5326
5367
  while (!stopped) {
5327
5368
  let signals = [];
5328
5369
  try {
5329
- const u = cursor == null ? "/api/call-poll" : "/api/call-poll?since=" + cursor;
5370
+ const u = cursor == null ? "/api/call-poll" : "/api/call-poll?since=" + cursor + (callsVersion == null ? "" : "&cv=" + callsVersion);
5330
5371
  const r = await fetch(u, { headers: { "cache-control": "no-cache" } });
5331
5372
  const d = await r.json();
5332
5373
  signals = d && d.signals || [];
5333
5374
  if (d && typeof d.cursor === "number")
5334
5375
  cursor = d.cursor;
5376
+ if (d && Array.isArray(d.calls)) {
5377
+ callsTable = d.calls;
5378
+ if (typeof d.callsVersion === "number")
5379
+ callsVersion = d.callsVersion;
5380
+ emit("calls", null, callsTable);
5381
+ }
5335
5382
  } catch (e) {
5336
5383
  await new Promise((res) => setTimeout(res, 1e3));
5337
5384
  continue;
@@ -5367,6 +5414,12 @@ ${peer.address}`
5367
5414
  handlers.set(kind, /* @__PURE__ */ new Set());
5368
5415
  handlers.get(kind).add(cb);
5369
5416
  this.start();
5417
+ if (kind === "calls" && callsTable.length) {
5418
+ try {
5419
+ cb(null, callsTable);
5420
+ } catch (e) {
5421
+ }
5422
+ }
5370
5423
  if (kind === "call" && pendingCalls.length) {
5371
5424
  const queued = pendingCalls.splice(0);
5372
5425
  console.log("[rtc] flushing " + queued.length + " buffered call signal(s)");
@@ -5383,16 +5436,54 @@ ${peer.address}`
5383
5436
  return (_a = handlers.get(kind)) == null ? void 0 : _a.delete(cb);
5384
5437
  };
5385
5438
  },
5439
+ pageId,
5440
+ calls() {
5441
+ return callsTable;
5442
+ },
5386
5443
  async send(userid, data) {
5387
- const body = JSON.stringify({ userid, data: typeof data === "string" ? data : JSON.stringify(data) });
5444
+ const body = JSON.stringify({ userid, data: typeof data === "string" ? data : JSON.stringify(data), page: pageId });
5388
5445
  const r = await fetch("/api/call-signal", {
5389
5446
  method: "POST",
5390
5447
  headers: { "content-type": "application/json" },
5391
5448
  body
5392
5449
  });
5393
5450
  const d = await r.json().catch(() => ({ ok: r.ok }));
5394
- if (!d.ok)
5395
- throw new Error(d.error || "call-signal send failed");
5451
+ if (!d.ok) {
5452
+ const err = new Error(d.error || "call-signal send failed");
5453
+ if (d.answeredElsewhere)
5454
+ err.answeredElsewhere = true;
5455
+ throw err;
5456
+ }
5457
+ },
5458
+ // Claim an incoming call on the server before answering or declining it.
5459
+ // `won: false` = another page or client already has it. A server that
5460
+ // does not know the route (an older host) or does not answer within
5461
+ // 1.5 s counts as won — /api/call-signal still refuses a second answer.
5462
+ async claim(callId, peerId, action) {
5463
+ const ctl = typeof AbortController === "function" ? new AbortController() : null;
5464
+ const t = setTimeout(() => {
5465
+ try {
5466
+ if (ctl)
5467
+ ctl.abort();
5468
+ } catch (e) {
5469
+ }
5470
+ }, 1500);
5471
+ try {
5472
+ const r = await fetch("/api/call-claim", {
5473
+ method: "POST",
5474
+ headers: { "content-type": "application/json" },
5475
+ body: JSON.stringify({ callId, peerId, action, page: pageId }),
5476
+ signal: ctl ? ctl.signal : void 0
5477
+ });
5478
+ const d = await r.json().catch(() => null);
5479
+ if (!d || d.ok !== true || typeof d.won !== "boolean")
5480
+ return { won: true, unknown: true };
5481
+ return { won: d.won, call: d.call };
5482
+ } catch (e) {
5483
+ return { won: true, unknown: true };
5484
+ } finally {
5485
+ clearTimeout(t);
5486
+ }
5396
5487
  },
5397
5488
  stop() {
5398
5489
  stopped = true;
@@ -5423,7 +5514,7 @@ ${peer.address}`
5423
5514
  };
5424
5515
  }
5425
5516
  Object.assign(window, { dkRtcSignalBus, makeDaemonSignaling });
5426
- var CALL_END_STATES = /* @__PURE__ */ new Set(["noAnswer", "unreachable", "failed", "busy", "declined"]);
5517
+ var CALL_END_STATES = /* @__PURE__ */ new Set(["noAnswer", "unreachable", "failed", "busy", "declined", "elsewhere"]);
5427
5518
  var CALL_END_LINGER_MS = 3500;
5428
5519
  var EN = {
5429
5520
  calling: "calling\u2026",
@@ -5434,7 +5525,8 @@ ${peer.address}`
5434
5525
  cantReach: "Can't reach {name}",
5435
5526
  callFailed: "Call failed",
5436
5527
  busy: "Busy",
5437
- declined: "Declined"
5528
+ declined: "Declined",
5529
+ answeredElsewhere: "Answered elsewhere"
5438
5530
  };
5439
5531
  function str(T, key) {
5440
5532
  return T && T[key] || EN[key];
@@ -5460,6 +5552,8 @@ ${peer.address}`
5460
5552
  return str(T, "busy");
5461
5553
  case "declined":
5462
5554
  return str(T, "declined");
5555
+ case "elsewhere":
5556
+ return str(T, "answeredElsewhere");
5463
5557
  default:
5464
5558
  return state || "";
5465
5559
  }
@@ -5547,16 +5641,26 @@ ${peer.address}`
5547
5641
  return;
5548
5642
  }
5549
5643
  engine.on("incomingCall", (info) => {
5550
- const claimedAt = claimedCalls.current.get(String(info.callId).toLowerCase());
5551
- if (claimedAt && Date.now() - claimedAt < 5 * 6e4) {
5644
+ const pre = preAccepted.current.get(String(info.callId).toLowerCase());
5645
+ if (pre) {
5646
+ preAccepted.current.delete(String(info.callId).toLowerCase());
5647
+ setIncoming((i) => i && sameCall(i.callId, info.callId) ? null : i);
5648
+ engine.accept(info.callId).catch((e) => {
5649
+ console.warn("[call] accept after ring failed:", e && e.message || e);
5650
+ endWithReason((a) => sameCall(a.callId, info.callId), "failed");
5651
+ });
5652
+ return;
5653
+ }
5654
+ if (isSuppressed(claimedCalls.current, info.callId, Date.now())) {
5552
5655
  try {
5553
5656
  engine.discard && engine.discard(info.callId);
5554
5657
  } catch (e) {
5555
5658
  }
5556
5659
  return;
5557
5660
  }
5661
+ const wasRinging = incomingRef.current && sameCall(incomingRef.current.callId, info.callId);
5558
5662
  setIncoming(info);
5559
- if (onCallLogRef.current)
5663
+ if (!wasRinging && onCallLogRef.current)
5560
5664
  onCallLogRef.current(info.peerId, !!info.video, "incoming");
5561
5665
  });
5562
5666
  engine.on("stateChanged", (info, state) => setActive((a) => a && !a.ended && a.callId === info.callId ? { ...a, state } : a));
@@ -5664,6 +5768,81 @@ ${peer.address}`
5664
5768
  claimBus.current = null;
5665
5769
  };
5666
5770
  }, []);
5771
+ const preAccepted = React.useRef(/* @__PURE__ */ new Map());
5772
+ const silence = React.useCallback((callId) => {
5773
+ const inc = incomingRef.current;
5774
+ if (inc && sameCall(inc.callId, callId))
5775
+ setIncoming(null);
5776
+ const a = activeRef.current;
5777
+ if (a && sameCall(a.callId, callId))
5778
+ return;
5779
+ try {
5780
+ engineRef.current && engineRef.current.discard && engineRef.current.discard(callId);
5781
+ } catch (e) {
5782
+ }
5783
+ }, []);
5784
+ React.useEffect(() => {
5785
+ const bus = dkRtcSignalBus();
5786
+ const offCalls = bus.on("calls", (_u, table) => {
5787
+ const { stop, ended } = applyCallsTable(table, bus.pageId, claimedCalls.current, Date.now());
5788
+ for (const id of stop)
5789
+ silence(id);
5790
+ for (const id of ended) {
5791
+ if (preAccepted.current.has(id)) {
5792
+ preAccepted.current.delete(id);
5793
+ setActive((a) => a && sameCall(a.callId, id) && a.state === "connecting" ? null : a);
5794
+ }
5795
+ }
5796
+ });
5797
+ const offRing = bus.on("call-ring", (userid, env) => {
5798
+ if (!env || !env.callId || !userid)
5799
+ return;
5800
+ if (isSuppressed(claimedCalls.current, env.callId, Date.now()))
5801
+ return;
5802
+ if (preAccepted.current.has(String(env.callId).toLowerCase()))
5803
+ return;
5804
+ const a = activeRef.current;
5805
+ if (a && sameCall(a.callId, env.callId))
5806
+ return;
5807
+ const inc = incomingRef.current;
5808
+ if (inc && sameCall(inc.callId, env.callId))
5809
+ return;
5810
+ setIncoming({ callId: env.callId, peerId: userid, video: !!env.video, audio: true, ringOnly: true, callName: env.callName || env.name });
5811
+ if (onCallLogRef.current)
5812
+ onCallLogRef.current(userid, !!env.video, "incoming");
5813
+ try {
5814
+ bus.send(userid, window.PeerWebRTC.encodeSignal({ type: "event", event: "ringing", callId: env.callId })).catch(() => {
5815
+ });
5816
+ } catch (e) {
5817
+ }
5818
+ });
5819
+ const offStop = bus.on("call-ring-stop", (_u, env) => {
5820
+ if (!env || !env.callId)
5821
+ return;
5822
+ const id = String(env.callId).toLowerCase();
5823
+ if (env.reason === "answered" && preAccepted.current.has(id))
5824
+ return;
5825
+ if (!claimedCalls.current.has(id))
5826
+ claimedCalls.current.set(id, Date.now());
5827
+ silence(env.callId);
5828
+ if (env.reason !== "answered" && preAccepted.current.has(id)) {
5829
+ preAccepted.current.delete(id);
5830
+ setActive((a) => a && sameCall(a.callId, id) && a.state === "connecting" ? null : a);
5831
+ }
5832
+ });
5833
+ return () => {
5834
+ offCalls();
5835
+ offRing();
5836
+ offStop();
5837
+ };
5838
+ }, [silence]);
5839
+ const showElsewhere = React.useCallback((inc) => {
5840
+ silence(inc.callId);
5841
+ claimedCalls.current.set(String(inc.callId).toLowerCase(), Date.now());
5842
+ setActive({ callId: inc.callId, peerId: inc.peerId, video: inc.video, direction: "incoming", state: "elsewhere", ended: true });
5843
+ clearTimeout(lingerTimer.current);
5844
+ lingerTimer.current = setTimeout(() => setActive((a) => a && a.ended ? null : a), CALL_END_LINGER_MS);
5845
+ }, [silence]);
5667
5846
  const broadcastClaim = React.useCallback((inc, action) => {
5668
5847
  try {
5669
5848
  if (claimBus.current)
@@ -5678,29 +5857,66 @@ ${peer.address}`
5678
5857
  broadcastClaim(pending, "accepted");
5679
5858
  setIncoming(null);
5680
5859
  setActive({ callId: pending.callId, peerId: pending.peerId, video: pending.video, direction: "incoming", state: "connecting" });
5681
- waitEngine().then((eng) => {
5682
- if (!eng)
5683
- throw new Error("Calls unavailable (engine not ready)");
5684
- return eng.accept(pending.callId);
5860
+ const bus = dkRtcSignalBus();
5861
+ bus.claim(pending.callId, pending.peerId, "accepted").then((c) => {
5862
+ if (!c.won) {
5863
+ showElsewhere(pending);
5864
+ return null;
5865
+ }
5866
+ if (pending.ringOnly) {
5867
+ preAccepted.current.set(String(pending.callId).toLowerCase(), Date.now());
5868
+ return bus.send(pending.peerId, window.PeerWebRTC.encodeSignal({ type: "action", action: "accept", callId: pending.callId }));
5869
+ }
5870
+ return waitEngine().then((eng) => {
5871
+ if (!eng)
5872
+ throw new Error("Calls unavailable (engine not ready)");
5873
+ return eng.accept(pending.callId);
5874
+ });
5685
5875
  }).catch((e) => {
5876
+ if (e && e.answeredElsewhere) {
5877
+ showElsewhere(pending);
5878
+ return;
5879
+ }
5686
5880
  console.warn("[call] accept failed:", e && e.message || e);
5687
5881
  endWithReason((a) => a.callId === pending.callId, "failed");
5688
5882
  });
5689
- }, [waitEngine, endWithReason]);
5883
+ }, [waitEngine, endWithReason, broadcastClaim, showElsewhere]);
5690
5884
  const reject = React.useCallback(() => {
5691
- const eng = engineRef.current;
5692
5885
  const inc = incomingRef.current;
5693
- if (inc)
5694
- broadcastClaim(inc, "rejected");
5695
- if (eng && inc)
5696
- eng.reject(inc.callId);
5697
5886
  setIncoming(null);
5698
- }, [broadcastClaim]);
5887
+ if (!inc)
5888
+ return;
5889
+ broadcastClaim(inc, "rejected");
5890
+ const bus = dkRtcSignalBus();
5891
+ bus.claim(inc.callId, inc.peerId, "rejected").then((c) => {
5892
+ if (!c.won) {
5893
+ silence(inc.callId);
5894
+ return;
5895
+ }
5896
+ if (inc.ringOnly) {
5897
+ bus.send(inc.peerId, window.PeerWebRTC.encodeSignal({ type: "action", action: "reject", callId: inc.callId })).catch(() => {
5898
+ });
5899
+ return;
5900
+ }
5901
+ const eng = engineRef.current;
5902
+ if (eng)
5903
+ eng.reject(inc.callId);
5904
+ });
5905
+ }, [broadcastClaim, silence]);
5699
5906
  const hangup = React.useCallback(() => {
5700
5907
  const eng = engineRef.current;
5701
5908
  const a = activeRef.current;
5702
5909
  clearTimeout(lingerTimer.current);
5703
- if (eng && a && a.callId && !a.ended)
5910
+ const preId = a && a.callId ? String(a.callId).toLowerCase() : "";
5911
+ if (preId && preAccepted.current.has(preId) && !a.ended) {
5912
+ preAccepted.current.delete(preId);
5913
+ claimedCalls.current.set(preId, Date.now());
5914
+ try {
5915
+ dkRtcSignalBus().send(a.peerId, window.PeerWebRTC.encodeSignal({ type: "bye", reason: "normal", callId: a.callId })).catch(() => {
5916
+ });
5917
+ } catch (e) {
5918
+ }
5919
+ } else if (eng && a && a.callId && !a.ended)
5704
5920
  eng.hangup(a.callId);
5705
5921
  setActive(null);
5706
5922
  setLocalStream(null);
@@ -7127,6 +7343,7 @@ ${peer.address}`
7127
7343
  callFailed: "Call failed",
7128
7344
  busy: "Busy",
7129
7345
  declined: "Declined",
7346
+ answeredElsewhere: "Answered elsewhere",
7130
7347
  joinGroup: "Join group",
7131
7348
  cardIsFriend: "Already in your chats.",
7132
7349
  cardNoEns: "No beagles.eth name registered.",
@@ -7354,6 +7571,7 @@ ${peer.address}`
7354
7571
  callFailed: "\u901A\u8BDD\u5931\u8D25",
7355
7572
  busy: "\u5BF9\u65B9\u5FD9",
7356
7573
  declined: "\u5BF9\u65B9\u5DF2\u62D2\u7EDD",
7574
+ answeredElsewhere: "\u5DF2\u5728\u5176\u4ED6\u8BBE\u5907\u63A5\u542C",
7357
7575
  joinGroup: "\u52A0\u5165\u7FA4",
7358
7576
  cardIsFriend: "\u5DF2\u5728\u4F60\u7684\u4F1A\u8BDD\u91CC\u3002",
7359
7577
  cardNoEns: "\u5BF9\u65B9\u8FD8\u6CA1\u6709\u6CE8\u518C beagles.eth \u540D\u5B57\u3002",