@unicitylabs/nostr-js-sdk 0.4.0 → 0.4.1

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.
@@ -9671,6 +9671,7 @@ class NostrClient {
9671
9671
  reconnectTimer: null,
9672
9672
  pingTimer: null,
9673
9673
  lastPongTime: Date.now(),
9674
+ unansweredPings: 0,
9674
9675
  wasConnected: existingRelay?.wasConnected ?? false,
9675
9676
  };
9676
9677
  socket.onopen = () => {
@@ -9698,10 +9699,11 @@ class NostrClient {
9698
9699
  socket.onmessage = (event) => {
9699
9700
  try {
9700
9701
  const data = extractMessageData(event);
9701
- // Update last pong time on any message (relay is alive)
9702
+ // Update last pong time and reset unanswered pings on any message (relay is alive)
9702
9703
  const r = this.relays.get(url);
9703
9704
  if (r) {
9704
9705
  r.lastPongTime = Date.now();
9706
+ r.unansweredPings = 0;
9705
9707
  }
9706
9708
  this.handleRelayMessage(url, data);
9707
9709
  }
@@ -9785,11 +9787,16 @@ class NostrClient {
9785
9787
  this.stopPingTimer(url);
9786
9788
  return;
9787
9789
  }
9788
- // Check if we've received any message recently
9789
9790
  const timeSinceLastPong = Date.now() - relay.lastPongTime;
9790
- if (timeSinceLastPong > this.pingIntervalMs * 2) {
9791
- // Connection is stale - force close and reconnect
9792
- console.warn(`Relay ${url} appears stale (no response for ${timeSinceLastPong}ms), reconnecting...`);
9791
+ if (timeSinceLastPong > this.pingIntervalMs * 2 && relay.unansweredPings >= 2) {
9792
+ // No inbound message for 2x the ping interval AND we've sent at least 2 pings
9793
+ // without any response the connection is truly stale.
9794
+ // The unanswered pings gate handles browser tab throttling: on the first tick
9795
+ // after waking, unansweredPings is 0, so we send a ping and wait. If the relay
9796
+ // is alive it responds (resetting the counter). If dead, subsequent ticks
9797
+ // increment the counter until it reaches the threshold, even under sustained
9798
+ // throttling where intervals are irregular.
9799
+ console.warn(`Relay ${url} appears stale (no response for ${timeSinceLastPong}ms, ${relay.unansweredPings} unanswered pings), reconnecting...`);
9793
9800
  this.stopPingTimer(url);
9794
9801
  try {
9795
9802
  relay.socket.close();
@@ -9810,6 +9817,7 @@ class NostrClient {
9810
9817
  // Then send the new ping request (limit:1 ensures relay sends EOSE)
9811
9818
  const pingMessage = JSON.stringify(['REQ', pingSubId, { limit: 1 }]);
9812
9819
  relay.socket.send(pingMessage);
9820
+ relay.unansweredPings++;
9813
9821
  }
9814
9822
  catch {
9815
9823
  // Send failed, connection likely dead