jsflow-sdk 1.0.0-rc.3 → 1.1.0-rc.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.
package/CHANGELOG.md CHANGED
@@ -6,42 +6,48 @@ All notable changes to `jsflow-sdk`. The format follows
6
6
  contract; metric names passed to `onMetric` are diagnostic and may change in
7
7
  any minor release.
8
8
 
9
- ## [1.0.0-rc.3] - 2026-11-18
9
+ ## [1.1.0-rc.1] - 2026-11-20
10
10
 
11
- The third release candidate for 1.0.0, under the npm tag `next` as before.
11
+ The first release candidate for 1.1.0, under the npm tag `next`
12
+ (`npm install jsflow-sdk@next`); `latest` stays 1.0.0. Additions only:
13
+ nothing in 1.0.0's API changes, and the wire version is still 2.
12
14
 
13
- ### Fixed
14
- - **Two peers no longer fail to link for 10 seconds or more when one joins
15
- through the other while the other is also trying to reach it.** A peer
16
- joining (or rejoining) a room through another member's waiting offer
17
- could, if that member also reached out to it at the same moment, send its
18
- reply to the wrong place, give up on the member's connection after 4
19
- seconds, and hold back from it for another 10. Both then waited without an
20
- error until their attempts timed out. It was most likely with a relay
21
- (TURN) configured, as in production, where a connection takes up to 1.5
22
- seconds to prepare. Nothing changes on the wire or in the API.
23
-
24
- ## [1.0.0-rc.2] - 2026-11-18
15
+ ### Added
25
16
 
26
- The second release candidate for 1.0.0, under the npm tag `next` as before.
17
+ - `JoinError.docs`: the link to the error's own entry on the errors page,
18
+ `https://jsflow.com/docs/reference/errors/#<code>`, the same link
19
+ `jsflow errors <code>` prints.
20
+ - `room.path(peer)`: how this peer reaches another now, `'direct'` or
21
+ `'relay'` over its own link (from the link's selected candidate pair),
22
+ `'mesh'` through other peers, or `null` if it is not reachable; and the
23
+ `'path'` event when that changes. Nothing is read until `path()` is called
24
+ or a `'path'` listener is added.
25
+ - `ErrorCode` includes `'unknown'`, the code a `JoinError` already carried
26
+ when a refused join's answer was not the service's JSON (a proxy's or
27
+ CDN's error page, for example); `status` says what happened.
27
28
 
28
29
  ### Fixed
29
- - **A reliable message is never delivered twice across a page reload.** If a
30
- receiver got a `sendReliable()` message, then reloaded (or restarted)
31
- before its acknowledgement reached the sender (for example while the
32
- sender's page was hidden), the sender's retransmission could reach the
33
- receiver's new page as well. The new page now drops it, and the sender
34
- gets `undelivered` for it, as for any message whose delivery it cannot
35
- confirm. Nothing changes on the wire.
36
30
 
37
- ## [1.0.0-rc.1] - 2026-11-18
38
-
39
- The release candidate for 1.0.0: everything listed under 1.0.0 below. Published under the npm tag `next`
40
- (`npm install jsflow-sdk@next`); `npm install jsflow-sdk` keeps the stable release.
41
-
42
- ## [1.0.0] - unreleased
43
-
44
- The first stable API, on wire version 2.
31
+ - **After the service restarts, members come back spread out instead of
32
+ all at once.** When a member's connection to the service drops, the SDK
33
+ now waits a random 0.5 to 5 seconds before reconnecting, and backs off up
34
+ to 15 seconds while the service stays down, instead of every member
35
+ retrying on the same fixed delays. A member whose network changes is back
36
+ about as fast as before.
37
+ - **A peer that joins while the member offering it a connection disappears
38
+ no longer waits several seconds for its first link.** The SDK's fallback
39
+ no longer picks a peer it is already trying to reach.
40
+ - **Two peers that reach each other in two ways at once no longer drop
41
+ their new connection.** When a joining peer's first reply arrived after
42
+ the connection it made another way was already up, the older reply could
43
+ close that connection, and the two stayed apart for about 12 seconds.
44
+
45
+ ## [1.0.0] - 2026-11-19
46
+
47
+ The first stable API, on wire version 2, under the npm tag `latest`
48
+ (`npm install jsflow-sdk`). The code is 1.0.0-rc.3's: since rc.3 only the
49
+ documentation comments in `jsflow.d.ts` changed (the spend cap is the
50
+ account's, and the examples fit 72 columns).
45
51
 
46
52
  ### Migrating from 0.1.x
47
53
 
@@ -143,3 +149,36 @@ The first stable API, on wire version 2.
143
149
  ### Removed
144
150
  - Lab-only options and methods (`lab`, `want`, `pool`, `target`, `max`,
145
151
  `room.lab()`).
152
+
153
+ ## [1.0.0-rc.3] - 2026-11-18
154
+
155
+ The third release candidate for 1.0.0, under the npm tag `next` as before.
156
+
157
+ ### Fixed
158
+ - **Two peers no longer fail to link for 10 seconds or more when one joins
159
+ through the other while the other is also trying to reach it.** A peer
160
+ joining (or rejoining) a room through another member's waiting offer
161
+ could, if that member also reached out to it at the same moment, send its
162
+ reply to the wrong place, give up on the member's connection after 4
163
+ seconds, and hold back from it for another 10. Both then waited without an
164
+ error until their attempts timed out. It was most likely with a relay
165
+ (TURN) configured, as in production, where a connection takes up to 1.5
166
+ seconds to prepare. Nothing changes on the wire or in the API.
167
+
168
+ ## [1.0.0-rc.2] - 2026-11-18
169
+
170
+ The second release candidate for 1.0.0, under the npm tag `next` as before.
171
+
172
+ ### Fixed
173
+ - **A reliable message is never delivered twice across a page reload.** If a
174
+ receiver got a `sendReliable()` message, then reloaded (or restarted)
175
+ before its acknowledgement reached the sender (for example while the
176
+ sender's page was hidden), the sender's retransmission could reach the
177
+ receiver's new page as well. The new page now drops it, and the sender
178
+ gets `undelivered` for it, as for any message whose delivery it cannot
179
+ confirm. Nothing changes on the wire.
180
+
181
+ ## [1.0.0-rc.1] - 2026-11-18
182
+
183
+ The release candidate for 1.0.0: everything listed under 1.0.0 above. Published under the npm tag `next`
184
+ (`npm install jsflow-sdk@next`); `npm install jsflow-sdk` keeps the stable release.
package/jsflow.d.ts CHANGED
@@ -4,7 +4,8 @@
4
4
  * The signalling service join() uses unless given another.
5
5
  * @since 1.0.0
6
6
  * @example
7
- * const room = await join({ app: 'pk_…', room: 'lobby' }); // uses SERVER
7
+ * // uses SERVER
8
+ * const room = await join({ app: 'pk_…', room: 'lobby' });
8
9
  */
9
10
  export const SERVER: string;
10
11
  /**
@@ -18,14 +19,16 @@ export const SDK_VERSION: string;
18
19
  * The wire version this SDK speaks. A room runs one: a peer of the other gets JoinError code 'wire'.
19
20
  * @since 1.0.0
20
21
  * @example
21
- * const roomName = `game-${id}-w${WIRE}`; // a room per wire version during an upgrade
22
+ * // a room per wire version during an upgrade
23
+ * const roomName = `game-${id}-w${WIRE}`;
22
24
  */
23
25
  export const WIRE: 2;
24
26
  /**
25
27
  * Bytes of app data per send() / broadcast() (1099 in 0.1.x).
26
28
  * @since 1.0.0
27
29
  * @example
28
- * if (bytes.length > MAX_DATAGRAM) await room.sendReliable(to, bytes); else room.send(to, bytes);
30
+ * if (bytes.length > MAX_DATAGRAM) await room.sendReliable(to, bytes);
31
+ * else room.send(to, bytes);
29
32
  */
30
33
  export const MAX_DATAGRAM: 1052;
31
34
  /**
@@ -47,7 +50,9 @@ export type Data = Uint8Array | ArrayBuffer | string;
47
50
  * A peer's id in the room: an integer the service assigns at each join.
48
51
  * @since 1.0.0
49
52
  * @example
50
- * room.on('peer', (id: PeerId, up) => console.log(id, up ? 'joined' : 'left'));
53
+ * room.on('peer', (id: PeerId, up) => {
54
+ * console.log(id, up ? 'joined' : 'left');
55
+ * });
51
56
  */
52
57
  export type PeerId = number;
53
58
  /**
@@ -61,10 +66,12 @@ export type Channel = number;
61
66
  /**
62
67
  * Where this peer is. 'away': its page is hidden (phones, desktop Safari) and it holds no slot;
63
68
  * 'superseded': a newer tab with the same id took over; 'evicted': the app's backend removed it;
64
- * 'suspended': the app's cost cap is reached (links kept, joins refused); 'left': leave() was called.
69
+ * 'suspended': the account's spend cap is reached (links kept, joins refused); 'left': leave() was called.
65
70
  * @since 1.0.0
66
71
  * @example
67
- * room.on('state', (s: State) => { if (s === 'suspended') showBanner('Paused: the app is over its plan'); });
72
+ * room.on('state', (s: State) => {
73
+ * if (s === 'suspended') showBanner('Paused: the app is over its plan');
74
+ * });
68
75
  */
69
76
  export type State =
70
77
  /** join() is connecting: the service admitted this peer, its first links are forming. */
@@ -77,7 +84,7 @@ export type State =
77
84
  | 'superseded'
78
85
  /** The app's backend removed this peer (see the 'evicted' event); it has stopped for good. */
79
86
  | 'evicted'
80
- /** The app's cost cap is reached: links are kept, but no new peer can join the app until the cap is raised (see the 'suspended' event). */
87
+ /** The account's spend cap is reached: links stay up, but new joins to the account's apps are refused ('quota') until an owner raises the cap or the next period starts (see the 'suspended' event). */
81
88
  | 'suspended'
82
89
  /** leave() was called. */
83
90
  | 'left';
@@ -86,7 +93,9 @@ export type State =
86
93
  * How a message was sent.
87
94
  * @since 1.0.0
88
95
  * @example
89
- * room.on('message', (from, data, info: MessageInfo) => { if (info.reliable) apply(text(data)); });
96
+ * room.on('message', (from, data, info: MessageInfo) => {
97
+ * if (info.reliable) apply(text(data));
98
+ * });
90
99
  */
91
100
  export interface MessageInfo {
92
101
  /** The channel it was sent on (0–13; 0 unless the sender chose another). */
@@ -101,7 +110,10 @@ export interface MessageInfo {
101
110
  * A region jsflow runs signalling and relays in: Stockholm (`eu-north-1`) or Ohio (`us-east-2`).
102
111
  * @since 1.0.0
103
112
  * @example
104
- * const room = await join({ app: 'pk_…', room: 'round-42', region: 'eu-north-1' }); // an EU-pinned app
113
+ * // an EU-pinned app
114
+ * const room = await join({
115
+ * app: 'pk_…', room: 'round-42', region: 'eu-north-1',
116
+ * });
105
117
  */
106
118
  export type Region = 'eu-north-1' | 'us-east-2';
107
119
 
@@ -109,7 +121,12 @@ export type Region = 'eu-north-1' | 'us-east-2';
109
121
  * What join() needs.
110
122
  * @since 1.0.0
111
123
  * @example
112
- * const opts: JoinOptions = { app: 'pk_…', room: 'round-42', ticket: () => fetch('/ticket', { method: 'POST' }).then((r) => r.text()) };
124
+ * const opts: JoinOptions = {
125
+ * app: 'pk_…',
126
+ * room: 'round-42',
127
+ * ticket: () =>
128
+ * fetch('/ticket', { method: 'POST' }).then((r) => r.text()),
129
+ * };
113
130
  */
114
131
  export interface JoinOptions {
115
132
  /** The app's publishable key ("pk_…"), from the dashboard. The page's origin must be one the app allows. */
@@ -166,9 +183,26 @@ export interface Room {
166
183
  peers(): PeerId[];
167
184
  /** A peer's user id from its join ticket, vouched for by the service; '' if it joined without one; null if not known yet. */
168
185
  user(peerId: PeerId): string | null;
186
+ /**
187
+ * How I reach a peer now: 'direct' over my own link to it, peer to peer; 'relay' over my own link
188
+ * through a TURN relay (either end relayed); 'mesh' through other peers (no link of my own to it,
189
+ * said once that has held for a second, so a peer leaving does not flash 'mesh'); null if it is not
190
+ * reachable. From the link's selected candidate pair, read only once path() or a
191
+ * 'path' listener asks: at once, about 1 s and 5 s after a link comes up, then every 10 s. Changes are
192
+ * reported by the 'path' event.
193
+ * @since 1.1.0
194
+ */
195
+ path(peer: PeerId): 'direct' | 'relay' | 'mesh' | null;
169
196
 
170
197
  /** A peer became reachable (`up` true) or unreachable (`up` false). peers() lists the reachable ones. */
171
198
  on(ev: 'peer', f: (id: PeerId, up: boolean) => void): this;
199
+ /**
200
+ * How I reach `peer` changed (see path()): for example 'relay' to 'direct' once ICE settles, 'mesh' to
201
+ * 'direct' when a link of my own comes up, null when it is no longer reachable. Listening starts the
202
+ * check, and fires once for each peer reachable then.
203
+ * @since 1.1.0
204
+ */
205
+ on(ev: 'path', f: (peer: PeerId, path: 'direct' | 'relay' | 'mesh' | null) => void): this;
172
206
  /** A message from `from`: its bytes (text() decodes UTF-8) and how it was sent. */
173
207
  on(ev: 'message', f: (from: PeerId, data: Uint8Array, info: MessageInfo) => void): this;
174
208
  /** This peer's state changed (the new value is also in room.state). */
@@ -182,7 +216,7 @@ export interface Room {
182
216
  on(ev: 'error', f: (e: Error) => void): this;
183
217
  /** The app's backend removed this peer; every other peer has cut it off. Joining again is refused (code 'blocked') until `until` (unix s). */
184
218
  on(ev: 'evicted', f: (info: { until: number }) => void): this;
185
- /** The app's cost cap is reached (the service said so in a signed notice at this peer's refresh). Links are kept; new joins to the app are refused (402 'quota') until the cap is raised; the state returns to 'connected' after a refresh without the notice. */
219
+ /** The account's spend cap is reached (the service said so in a signed notice at this peer's refresh). Links stay up, but new joins to the account's apps are refused (402 'quota') until an owner raises the cap or the next period starts; the state returns to 'connected' after a refresh without the notice. */
186
220
  on(ev: 'suspended', f: (info: { reason: 'quota' }) => void): this;
187
221
  /** Remove a listener added with on(): the same event name and the same function. */
188
222
  off(ev: string, f: (...a: any[]) => void): this;
@@ -251,6 +285,7 @@ export type ErrorCode =
251
285
  | 'too_many_rooms'
252
286
  | 'too_many_streams'
253
287
  | 'unauthorized'
288
+ | 'unknown'
254
289
  | 'unknown_app'
255
290
  | 'unsupported_browser'
256
291
  | 'want_not_allowed'
@@ -267,8 +302,14 @@ export type ErrorCode =
267
302
  * 'quota'. A network failure rejects with a TypeError instead.
268
303
  * @since 1.0.0
269
304
  * @example
270
- * try { await join(opts); }
271
- * catch (e) { if (e instanceof JoinError && e.code === 'ticket_expired') return join({ ...opts, ticket: await fresh() }); throw e; }
305
+ * try {
306
+ * await join(opts);
307
+ * } catch (e) {
308
+ * if (e instanceof JoinError && e.code === 'ticket_expired') {
309
+ * return join({ ...opts, ticket: await fresh() });
310
+ * }
311
+ * throw e;
312
+ * }
272
313
  */
273
314
  export class JoinError extends Error {
274
315
  /** Always 'JoinError', so it survives a structured clone or a log line where instanceof does not. */
@@ -279,13 +320,25 @@ export class JoinError extends Error {
279
320
  readonly code: ErrorCode;
280
321
  /** The service's answer: { err, message, ...details }, or null if it was not JSON. */
281
322
  readonly body: { err: string; message?: string; [k: string]: unknown } | null;
323
+ /**
324
+ * This code's entry on the errors page, what it means and what to do about it:
325
+ * https://jsflow.com/docs/reference/errors/#<code>. Log it with the error, or link it from a
326
+ * developer-facing message.
327
+ * @since 1.1.0
328
+ */
329
+ readonly docs: string;
282
330
  }
283
331
 
284
332
  /**
285
333
  * Join a room. Rejects with a JoinError if the service (or the SDK itself) refuses.
286
334
  * @since 1.0.0
287
335
  * @example
288
- * const room = await join({ app: 'pk_…', room: 'round-42', ticket: () => fetch('/ticket', { method: 'POST' }).then((r) => r.text()) });
336
+ * const room = await join({
337
+ * app: 'pk_…',
338
+ * room: 'round-42',
339
+ * ticket: () =>
340
+ * fetch('/ticket', { method: 'POST' }).then((r) => r.text()),
341
+ * });
289
342
  */
290
343
  export function join(opts: JoinOptions): Promise<Room>;
291
344
  /**
package/jsflow.js CHANGED
@@ -1,4 +1,4 @@
1
- // jsflow-sdk 1.0.0-rc.3. Licence: see LICENSE (https://jsflow.com). Built by client/build.js.
1
+ // jsflow-sdk 1.1.0-rc.1. Licence: see LICENSE (https://jsflow.com). Built by client/build.js.
2
2
 
3
3
  // core/link-main.js
4
4
  function linkKind(stats) {
@@ -49,7 +49,10 @@ function linkHost(worker, { iceServers = [], iceTransportPolicy, gatherCapMs = 1
49
49
  const dg = pc.createDataChannel("dg", { negotiated: true, id: 1, ordered: false, maxRetransmits: 0 });
50
50
  post({ op: "chans", peer, n, ctl, dg }, [ctl, dg]);
51
51
  const entry = { pc, n, peer };
52
- pc.onconnectionstatechange = () => post({ op: "pc", peer: entry.peer, n, s: pc.connectionState });
52
+ pc.onconnectionstatechange = () => {
53
+ post({ op: "pc", peer: entry.peer, n, s: pc.connectionState });
54
+ pathsSoon(pc.connectionState === "connected");
55
+ };
53
56
  pcs.set(peer, entry);
54
57
  return pc;
55
58
  }
@@ -86,7 +89,10 @@ function linkHost(worker, { iceServers = [], iceTransportPolicy, gatherCapMs = 1
86
89
  await pc.setRemoteDescription({ type: "offer", sdp: m.sdp });
87
90
  await pc.setLocalDescription(await pc.createAnswer());
88
91
  await gathered(pc, true);
89
- if (cur(m.peer, m.n)) post({ op: "sdp", peer: m.peer, n: m.n, kind: 5, sdp: pc.localDescription.sdp });
92
+ if (cur(m.peer, m.n)) {
93
+ post({ op: "sdp", peer: m.peer, n: m.n, kind: 5, sdp: pc.localDescription.sdp });
94
+ pathsSoon(true);
95
+ }
90
96
  } catch (err) {
91
97
  post({ op: "metric", name: "iceRestartFailed", value: String(err) });
92
98
  }
@@ -94,7 +100,10 @@ function linkHost(worker, { iceServers = [], iceTransportPolicy, gatherCapMs = 1
94
100
  const pc = cur(m.peer, m.n);
95
101
  if (pc?.connectionState === "connected") {
96
102
  try {
97
- if (pc.signalingState === "have-local-offer") await pc.setRemoteDescription({ type: "answer", sdp: m.sdp });
103
+ if (pc.signalingState === "have-local-offer") {
104
+ await pc.setRemoteDescription({ type: "answer", sdp: m.sdp });
105
+ pathsSoon(true);
106
+ }
98
107
  } catch (err) {
99
108
  post({ op: "metric", name: "iceRestartFailed", value: String(err) });
100
109
  }
@@ -108,12 +117,14 @@ function linkHost(worker, { iceServers = [], iceTransportPolicy, gatherCapMs = 1
108
117
  pcs.get(m.to)?.pc.close();
109
118
  x.peer = m.to;
110
119
  pcs.set(m.to, x);
120
+ pathsSoon();
111
121
  }
112
122
  } else if (m.op === "close") {
113
123
  const x = pcs.get(m.peer);
114
124
  if (x && (m.n === void 0 || x.n === m.n)) {
115
125
  pcs.delete(m.peer);
116
126
  x.pc.close();
127
+ pathsSoon();
117
128
  }
118
129
  }
119
130
  } catch (err) {
@@ -196,8 +207,67 @@ function linkHost(worker, { iceServers = [], iceTransportPolicy, gatherCapMs = 1
196
207
  }
197
208
  }
198
209
  }, 1e4);
199
- return { pcs, setIceServers, closeAll() {
210
+ let onPath = null, pathTimer = null, reading = false, again = false;
211
+ const own = /* @__PURE__ */ new Map();
212
+ async function readPaths() {
213
+ if (!onPath) return;
214
+ if (reading) {
215
+ again = true;
216
+ return;
217
+ }
218
+ reading = true;
219
+ try {
220
+ const live = /* @__PURE__ */ new Set();
221
+ for (const { pc, peer } of [...pcs.values()]) {
222
+ if (typeof peer !== "number") continue;
223
+ if (pc.connectionState === "disconnected" && own.has(peer)) {
224
+ live.add(peer);
225
+ continue;
226
+ }
227
+ if (pc.connectionState !== "connected") continue;
228
+ live.add(peer);
229
+ let k;
230
+ try {
231
+ k = linkKind(await pc.getStats());
232
+ } catch {
233
+ }
234
+ const p = k === "relay" ? "relay" : k ? "direct" : void 0;
235
+ if (p && own.get(peer) !== p && pcs.get(peer)?.pc === pc) {
236
+ own.set(peer, p);
237
+ onPath(peer, p);
238
+ }
239
+ }
240
+ for (const peer of [...own.keys()]) if (!live.has(peer)) {
241
+ own.delete(peer);
242
+ onPath(peer, null);
243
+ }
244
+ } finally {
245
+ reading = false;
246
+ if (again) {
247
+ again = false;
248
+ readPaths();
249
+ }
250
+ }
251
+ }
252
+ function pathsSoon(connected = false) {
253
+ if (!onPath) return;
254
+ setTimeout(readPaths, 0);
255
+ if (connected) {
256
+ setTimeout(readPaths, 1e3);
257
+ setTimeout(readPaths, 5e3);
258
+ }
259
+ }
260
+ function watchPaths(f) {
261
+ if (onPath) return;
262
+ onPath = f;
263
+ readPaths();
264
+ pathTimer = setInterval(readPaths, 1e4);
265
+ }
266
+ const ownPath = (peer) => own.get(peer) ?? (pcs.get(peer)?.pc.connectionState === "connected" ? "pending" : void 0);
267
+ return { pcs, setIceServers, watchPaths, ownPath, pathsSoon, closeAll() {
200
268
  clearInterval(kindsTimer);
269
+ clearInterval(pathTimer);
270
+ onPath = null;
201
271
  for (const { pc } of pcs.values()) pc.close();
202
272
  pcs.clear();
203
273
  } };
@@ -215,7 +285,7 @@ function ticketRegion(ticket) {
215
285
  return void 0;
216
286
  }
217
287
  }
218
- var SDK_VERSION = "1.0.0-rc.3";
288
+ var SDK_VERSION = "1.1.0-rc.1";
219
289
  var WIRE = 2;
220
290
  var MAX_DATAGRAM = 1052;
221
291
  var MAX_RELIABLE = 65536;
@@ -239,6 +309,7 @@ function startWorker(override) {
239
309
  if (/^https?:$/.test(here.protocol) && here.origin !== location.origin) return crossOriginWorker(here.href.replace(/[^/]*$/, "worker.js"));
240
310
  return new Worker(new URL("./worker.js", import.meta.url), { type: "module" });
241
311
  }
312
+ var ERRORS_PAGE = "https://jsflow.com/docs/reference/errors/";
242
313
  var JoinError = class extends Error {
243
314
  constructor(status, body) {
244
315
  super(`join: ${status} ${body?.err ?? ""}${body?.message ? `: ${body.message}` : ""}`);
@@ -246,8 +317,11 @@ var JoinError = class extends Error {
246
317
  this.status = status;
247
318
  this.code = body?.err ?? "unknown";
248
319
  this.body = body ?? null;
320
+ this.docs = `${ERRORS_PAGE}#${this.code}`;
249
321
  }
250
322
  };
323
+ var REOPEN = Object.freeze({ lo: 500, hi: 5e3, cap: 15e3 });
324
+ var reopenDelay = (n, r = Math.random(), { lo, hi, cap } = REOPEN) => n === 0 ? lo + r * (hi - lo) : r * Math.min(cap, hi * 2 ** (n - 1));
251
325
  function homeAllowed(server, home) {
252
326
  let s, h;
253
327
  try {
@@ -278,6 +352,8 @@ async function join(opts) {
278
352
  console.error(e);
279
353
  }
280
354
  };
355
+ const paths = /* @__PURE__ */ new Map();
356
+ let watching = false;
281
357
  const peers = /* @__PURE__ */ new Set(), waiting = /* @__PURE__ */ new Map(), users = /* @__PURE__ */ new Map();
282
358
  let state = "joining", es = null, mid = 0;
283
359
  const keysFrom = (w) => new Promise((ok) => {
@@ -377,19 +453,16 @@ async function join(opts) {
377
453
  if (m.type === "move") return moveTo(m.home, m.after);
378
454
  if (m.type !== "hb") worker.postMessage({ op: "sse", m });
379
455
  };
380
- let errs = 0;
381
456
  es.onopen = () => {
382
457
  errs = 0;
383
458
  };
384
459
  es.onerror = () => {
460
+ es.close();
385
461
  if (ended() || moving) return;
386
- if (es.readyState === EventSource.CLOSED) return void setTimeout(checkStream, 3e3);
387
- if (++errs >= 2) {
388
- es.close();
389
- setTimeout(checkStream, 1e3);
390
- }
462
+ setTimeout(checkStream, reopenDelay(errs++));
391
463
  };
392
464
  };
465
+ let errs = 0;
393
466
  let moving = false;
394
467
  const setHome = (h) => {
395
468
  home = h;
@@ -418,6 +491,7 @@ async function join(opts) {
418
491
  }
419
492
  if (r2 && r2.status < 500) failures = 0;
420
493
  else if (++failures >= 2 && await takeover()) failures = 0;
494
+ else if (!ended() && !moving) return void setTimeout(checkStream, reopenDelay(errs++));
421
495
  if (!ended() && !moving) openSse();
422
496
  };
423
497
  const takeover = async () => {
@@ -454,7 +528,8 @@ async function join(opts) {
454
528
  case "peer":
455
529
  if (m.up) peers.add(m.id);
456
530
  else peers.delete(m.id);
457
- return emit("peer", m.id, m.up);
531
+ emit("peer", m.id, m.up);
532
+ return repath(m.id);
458
533
  case "message":
459
534
  return emit("message", m.from, m.data, { channel: m.chan, broadcast: !!m.broadcast, reliable: !!m.reliable });
460
535
  case "state":
@@ -519,6 +594,42 @@ async function join(opts) {
519
594
  if (!e.persisted && state !== "left" && state !== "superseded") tellLeave();
520
595
  };
521
596
  addEventListener("pagehide", onPageHide);
597
+ const MESH_MS = 1e3, meshSince = /* @__PURE__ */ new Map(), meshCheck = /* @__PURE__ */ new Map();
598
+ const pathNow = (p) => {
599
+ const o = host.ownPath(p);
600
+ if (o === "direct" || o === "relay") {
601
+ meshSince.delete(p);
602
+ return o;
603
+ }
604
+ if (o === "pending") return paths.get(p) ?? null;
605
+ if (!peers.has(p) || ![...peers].some((q) => q !== p && host.ownPath(q))) {
606
+ meshSince.delete(p);
607
+ return null;
608
+ }
609
+ const now = Date.now();
610
+ if (!meshSince.has(p)) meshSince.set(p, now);
611
+ const left = MESH_MS - (now - meshSince.get(p));
612
+ if (left <= 0) return "mesh";
613
+ if (watching && !meshCheck.has(p)) meshCheck.set(p, setTimeout(() => {
614
+ meshCheck.delete(p);
615
+ repath(p);
616
+ }, left + 10));
617
+ return paths.get(p) ?? null;
618
+ };
619
+ function repath(p) {
620
+ if (!watching || ended()) return;
621
+ const v = pathNow(p);
622
+ if ((paths.get(p) ?? null) === v) return;
623
+ if (v === null) paths.delete(p);
624
+ else paths.set(p, v);
625
+ emit("path", p, v);
626
+ }
627
+ function watchPaths() {
628
+ if (watching) return;
629
+ watching = true;
630
+ host.watchPaths(repath);
631
+ for (const p of peers) repath(p);
632
+ }
522
633
  const live = () => {
523
634
  if (state === "left" || state === "superseded" || state === "evicted") throw new Error(`room is ${state}`);
524
635
  };
@@ -534,8 +645,14 @@ async function join(opts) {
534
645
  on(ev, f) {
535
646
  if (!handlers.has(ev)) handlers.set(ev, /* @__PURE__ */ new Set());
536
647
  handlers.get(ev).add(f);
648
+ if (ev === "path") watchPaths();
537
649
  return this;
538
650
  },
651
+ /** (1.1.0) How this peer reaches that one: 'direct' or 'relay' over its own link, 'mesh' through other peers, null if not reachable. */
652
+ path(peer) {
653
+ watchPaths();
654
+ return pathNow(peer);
655
+ },
539
656
  off(ev, f) {
540
657
  handlers.get(ev)?.delete(f);
541
658
  return this;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "jsflow-sdk",
3
- "version": "1.0.0-rc.3",
3
+ "version": "1.1.0-rc.1",
4
4
  "description": "jsflow: peer-to-peer rooms for the browser (WebRTC mesh, signalling and relays as a service).",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "type": "module",
package/sri.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
- "version": "1.0.0-rc.3",
3
- "jsflow.js": "sha384-R+KY9ySstq/BD2iK1rSeAi2cc7e/TvACrSegqTksn0hr1a4shMCRUy3Y8ZU2rz7R",
4
- "worker.js": "sha384-gHQ1l7u/ITLWPAt16wSLhVN9dZAYoh0DxJosUe9bt0Feft84eVIhrBHMT+BsZ8mS",
5
- "jsflow.d.ts": "sha384-ZQeEwggqNXnSnd25+7iK7oiLLI636vR16LRNPNflzbnxx/IsTmEsct592Eiq2mEg"
2
+ "version": "1.1.0-rc.1",
3
+ "jsflow.js": "sha384-O381tD0tzvsCNFFFCtgtr5WAGV31aWS3FZjHi33wT2Oh/yt4Wb9sI80Z6B+iJyOQ",
4
+ "worker.js": "sha384-0XqeO3D/M7TXSmGr37saYSJ0iek9R2Hr7GT8NX53S7FeB71xr06kszVbOB7gpoXt",
5
+ "jsflow.d.ts": "sha384-VM+jOFBiVG6Z3ElnDVldrvSTyha/lJh9kC8el+JL/77bYFOp6ScbTHFK2tCnFsN5"
6
6
  }
package/worker.js CHANGED
@@ -1,4 +1,4 @@
1
- // jsflow-sdk 1.0.0-rc.3. Licence: see LICENSE (https://jsflow.com). Built by client/build.js.
1
+ // jsflow-sdk 1.1.0-rc.1. Licence: see LICENSE (https://jsflow.com). Built by client/build.js.
2
2
 
3
3
  // core/header.js
4
4
  var VERSION = 2;
@@ -763,7 +763,7 @@ function meshNode(opts = {}) {
763
763
  for (const w of keep) route(w.raw, unpack(w.raw), w.from);
764
764
  }
765
765
  if (leaving) return;
766
- if (nbr.size === 0 && pending2.size === 0) return rescue(void 0, void 0, o.joinMinAgeMs);
766
+ if (nbr.size === 0 && pending2.size === 0) return rescue(incoming.size ? new Set(incoming.keys()) : void 0, void 0, o.joinMinAgeMs);
767
767
  const t = table();
768
768
  const reach = [...t.dist.keys()].filter((x) => x !== me);
769
769
  const away = [...lsdb].filter(([id, e]) => id !== me && e.links.size === 0).map(([id]) => id);
@@ -771,12 +771,12 @@ function meshNode(opts = {}) {
771
771
  if (lost.length && Math.min(me, ...reach) === me && env2.now() >= rescueAfter) {
772
772
  rescueAfter = env2.now() + rescueBackoff;
773
773
  rescueBackoff = Math.min(rescueBackoff * 2, 6e4);
774
- rescue(/* @__PURE__ */ new Set([me, ...reach, ...away]), void 0, o.islandCheckMs);
774
+ rescue(/* @__PURE__ */ new Set([me, ...reach, ...away, ...trying()]), void 0, o.islandCheckMs);
775
775
  } else if (!lost.length) rescueBackoff = 5e3;
776
776
  if (Math.min(me, ...reach) === me && env2.now() >= islandAt) {
777
777
  islandEvery = islandEvery ? Math.min(islandEvery * 2, 6e4) : o.islandFirstMs;
778
778
  islandAt = env2.now() + islandEvery * (0.8 + 0.4 * env2.rand());
779
- rescue(/* @__PURE__ */ new Set([me, ...reach, ...away]), (found) => {
779
+ rescue(/* @__PURE__ */ new Set([me, ...reach, ...away, ...trying()]), (found) => {
780
780
  if (found) {
781
781
  env2.metric("islandMerge", 1);
782
782
  islandEvery = 0;
@@ -802,6 +802,9 @@ function meshNode(opts = {}) {
802
802
  function busy(x) {
803
803
  return nbr.has(x) || pending2.has(x) || incoming.has(x);
804
804
  }
805
+ function trying() {
806
+ return [...pending2.keys(), ...incoming.keys()];
807
+ }
805
808
  function rescue(exclude, onDone, minAgeMs = 0) {
806
809
  if (cloudBusy) return;
807
810
  cloudBusy = true;
@@ -1285,6 +1288,7 @@ function workerEnv({ id, inc, cloud, post, pool = null, shim = null, onMetric =
1285
1288
  post({ op: "restart", peer: c.key, n: c.n });
1286
1289
  metric2("repark", { oid: c.oid, ageS: Math.round((performance.now() - c.at) / 1e3) });
1287
1290
  }
1291
+ const ANSWER_LATE_MS = 5e3;
1288
1292
  function adopt(m) {
1289
1293
  const c = [...parked.values()].find((x) => String(x.oid) === String(m.oid) && !x.refreshing), from = +m.from;
1290
1294
  if (!c) return metric2("orphanAnswer", { oid: m.oid, from });
@@ -1294,6 +1298,10 @@ function workerEnv({ id, inc, cloud, post, pool = null, shim = null, onMetric =
1294
1298
  return metric2("adoptRefused", { from });
1295
1299
  }
1296
1300
  const old = conns.get(from);
1301
+ if (old && performance.now() - old.t0 < ANSWER_LATE_MS) {
1302
+ post({ op: "close", peer: c.key, n: c.n });
1303
+ return metric2("adoptLate", { from, oid: m.oid, linkAgeMs: Math.round(performance.now() - old.t0), up: old.up });
1304
+ }
1297
1305
  if (old) {
1298
1306
  conns.delete(from);
1299
1307
  post({ op: "close", peer: from, n: old.n });