@furious.luke/argus-js 0.2.1 → 0.3.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/README.md CHANGED
@@ -44,6 +44,10 @@ const publisher = new Publisher({
44
44
  callbacks: {
45
45
  onConnected: () => console.log("streaming live"),
46
46
  onConnectionStateChange: (state) => console.log("state:", state),
47
+ onRecoveryStateChange: (event) => console.log("media recovery:", event),
48
+ // Show a button or prompt. From its click handler, call captureScreen()
49
+ // and then publisher.replaceStream(newStream).
50
+ onRecoveryRequired: (event) => console.warn("screen share must be restarted", event),
47
51
  onError: (err) => console.error("publish error:", err),
48
52
  },
49
53
  });
@@ -93,6 +97,7 @@ publisher.stop(); // stops all tracks and tears down the peer connection
93
97
  | `gatewayURLs` | `string[]` | **Required.** The `gateway_urls` from the join response. All are raced simultaneously; the fastest to accept wins. |
94
98
  | `token` | `string` | **Required.** The short-lived join token from the join response. |
95
99
  | `iceServers` | `RTCIceServer[]` | Optional extra ICE servers (e.g. your own STUN). TURN is supplied automatically by the winning gateway. |
100
+ | `signalingReconnectTimeoutMs` | `number` | How long to retry a dropped signaling socket against the selected regional gateway. Defaults to 20 seconds. |
96
101
  | `callbacks` | `PublisherCallbacks` | Optional lifecycle callbacks (see below). |
97
102
 
98
103
  ### Methods & properties
@@ -102,7 +107,7 @@ publisher.stop(); // stops all tracks and tears down the peer connection
102
107
  | `start(stream)` | Races the gateways, completes the handshake, and sends the SDP offer. Resolves once the offer is sent — use `onConnected` to know when media is actually flowing. |
103
108
  | `replaceStream(stream)` | Replaces the published tracks and renegotiates in place. |
104
109
  | `stop()` | Stops all local tracks and closes the peer connection. |
105
- | `frameReadToken` | The read token from the gateway's `ready` message, or `null` before connecting. Hand this to your server to fetch frames. |
110
+ | `frameReadToken` | The one-hour read token from the gateway's `ready` message, or `null` before connecting. The publisher uses it internally to resume signaling; hand it to your server to fetch frames. |
106
111
  | `peerConnection` | The underlying `RTCPeerConnection`, or `null` if not started. |
107
112
  | `isConnected` | `true` when the peer connection state is `"connected"`. |
108
113
 
@@ -112,7 +117,9 @@ publisher.stop(); // stops all tracks and tears down the peer connection
112
117
  | --- | --- |
113
118
  | `onConnected()` | The peer connection reached `"connected"` — media is flowing. |
114
119
  | `onConnectionStateChange(state)` | The `RTCPeerConnectionState` changed. |
115
- | `onError(error)` | A fatal error occurred (signaling error, gateway failure, or closed socket). |
120
+ | `onRecoveryStateChange(event)` | Argus detected stalled media and the publisher started, escalated, completed, or failed automatic recovery. |
121
+ | `onRecoveryRequired(event)` | Automatic recovery could not restore media, or capture ended and the host must ask the user for a new screen share. |
122
+ | `onError(error)` | A fatal error occurred (signaling error, initial gateway failure, or signaling resume timed out). |
116
123
 
117
124
  ## How `start()` works
118
125
 
@@ -120,6 +127,28 @@ publisher.stop(); // stops all tracks and tears down the peer connection
120
127
  2. **TURN + read token.** The winning gateway's `ready` message carries per-session TURN credentials (merged into the ICE configuration) and the read token exposed as `frameReadToken`.
121
128
  3. **WebRTC.** A peer connection is created, tracks are added, and an offer is sent. Remote ICE candidates that arrive before the SDP answer are buffered and flushed once the answer is applied.
122
129
 
130
+ After this initial race, the publisher is pinned to the selected regional
131
+ gateway. If signaling drops, it reconnects to that same gateway with the
132
+ one-hour read token and waits for `resumed`; it does not race regions, rebuild
133
+ the peer connection, or repeat the `ready` handshake. If the retry deadline
134
+ expires, the publisher closes the stream and calls `onError`.
135
+
136
+ ## Automatic media recovery
137
+
138
+ Argus measures freshness from complete encoded samples received by the media
139
+ server, not from pixel changes. An unchanged screen therefore remains healthy.
140
+ If samples stop for 15 seconds, the media server tells the publisher that the
141
+ track has stalled and stops serving its retained frame as current. The publisher
142
+ first detaches and reattaches the live sender and renegotiates. If samples do not
143
+ resume within four seconds, it performs an ICE restart and waits another eight
144
+ seconds. These fixed timings deliberately are not application configuration.
145
+
146
+ `onRecoveryStateChange` reports the recovery transitions. If both automatic
147
+ steps fail, `onRecoveryRequired` is called and the host can acquire a replacement
148
+ stream and pass it to `replaceStream`. A browser cannot silently reacquire a
149
+ screen share after the user or operating system ends it, so `capture_ended`
150
+ always requires host UI and a fresh `captureScreen()` call.
151
+
123
152
  ## Browser support
124
153
 
125
154
  Requires a browser with WebRTC (`RTCPeerConnection`) and `WebSocket` — all current evergreen browsers. There is no Node.js runtime support; this is a browser-only package.
package/dist/index.cjs CHANGED
@@ -73,6 +73,12 @@ function parseSignal(data) {
73
73
  }
74
74
 
75
75
  // src/publisher.ts
76
+ var defaultSignalingReconnectTimeoutMs = 2e4;
77
+ var signalingResumeAttemptTimeoutMs = 3e3;
78
+ var signalingResumeMaxBackoffMs = 3e3;
79
+ var senderRestartPauseMs = 100;
80
+ var senderRecoveryWaitMs = 4e3;
81
+ var iceRecoveryWaitMs = 8e3;
76
82
  var Publisher = class {
77
83
  opts;
78
84
  sig = null;
@@ -81,10 +87,20 @@ var Publisher = class {
81
87
  pendingRemoteCandidates = [];
82
88
  localStream = null;
83
89
  readToken = null;
90
+ selectedGatewayURL = null;
91
+ stopped = true;
92
+ reconnecting = false;
93
+ reconnectGeneration = 0;
94
+ resumeSocket = null;
95
+ recoveryGeneration = 0;
96
+ recoveringMedia = false;
97
+ recoveryRequired = false;
98
+ recoveryAction = null;
99
+ trackEndHandlers = /* @__PURE__ */ new Map();
84
100
  constructor(opts) {
85
101
  this.opts = opts;
86
102
  }
87
- /** The read token received from the gateway after connecting, for fetching frames. */
103
+ /** The read token used for frame fetches and signaling resume in the selected region. */
88
104
  get frameReadToken() {
89
105
  return this.readToken;
90
106
  }
@@ -95,8 +111,12 @@ var Publisher = class {
95
111
  * use onConnected for that).
96
112
  */
97
113
  async start(stream) {
114
+ this.stopped = false;
115
+ this.recoveryRequired = false;
98
116
  this.localStream = stream;
99
- const { ws, readyInfo } = await this.raceGateways();
117
+ this.watchStreamTracks(stream);
118
+ const { ws, readyInfo, gatewayURL } = await this.raceGateways();
119
+ this.selectedGatewayURL = gatewayURL;
100
120
  if (readyInfo.read_token) {
101
121
  this.readToken = readyInfo.read_token;
102
122
  }
@@ -131,17 +151,17 @@ var Publisher = class {
131
151
  const offer = await this.pc.createOffer();
132
152
  await this.pc.setLocalDescription(offer);
133
153
  await this.gatherComplete();
134
- this.sig = SignalingChannel.wrap(ws);
135
- this.sig.onMessage = (msg) => this.handleSignal(msg);
136
- this.sig.onClose = () => this.opts.callbacks?.onError?.(new Error("signaling closed"));
137
- this.sig.onError = (err) => this.opts.callbacks?.onError?.(err);
154
+ const signaling = this.installSignaling(ws);
138
155
  const local = this.pc.localDescription;
139
156
  if (!local) throw new Error("local description missing after gather");
140
- this.sig.send({ type: "offer", sdp: local.sdp, sdp_type: "offer" });
157
+ signaling.send({ type: "offer", sdp: local.sdp, sdp_type: "offer" });
141
158
  }
142
159
  /** Replaces the currently published stream with a new one. */
143
160
  async replaceStream(stream) {
144
161
  if (!this.pc) throw new Error("publisher not started");
162
+ this.cancelMediaRecovery();
163
+ this.recoveryRequired = false;
164
+ this.unwatchStreamTracks();
145
165
  const senders = this.pc.getSenders();
146
166
  for (const sender of senders) {
147
167
  if (sender.track) {
@@ -152,21 +172,20 @@ var Publisher = class {
152
172
  this.pc.addTrack(track, stream);
153
173
  }
154
174
  this.localStream = stream;
155
- const offer = await this.pc.createOffer();
156
- await this.pc.setLocalDescription(offer);
157
- await this.gatherComplete();
158
- const local = this.pc.localDescription;
159
- if (!local) throw new Error("local description missing");
160
- this.sig?.send({
161
- type: "offer",
162
- sdp: local.sdp,
163
- sdp_type: "offer"
164
- });
175
+ this.watchStreamTracks(stream);
176
+ await this.renegotiate(false);
165
177
  }
166
178
  /** Stops publishing and tears down the peer connection. */
167
179
  stop() {
180
+ this.stopped = true;
181
+ this.cancelMediaRecovery();
182
+ this.reconnectGeneration++;
183
+ this.reconnecting = false;
184
+ this.resumeSocket?.close();
185
+ this.resumeSocket = null;
168
186
  this.sig?.close();
169
187
  this.sig = null;
188
+ this.unwatchStreamTracks();
170
189
  this.localStream?.getTracks().forEach((t) => t.stop());
171
190
  this.localStream = null;
172
191
  this.pc?.close();
@@ -174,6 +193,7 @@ var Publisher = class {
174
193
  this.hasAnswer = false;
175
194
  this.pendingRemoteCandidates = [];
176
195
  this.readToken = null;
196
+ this.selectedGatewayURL = null;
177
197
  }
178
198
  /** Returns the current RTCPeerConnection, or null if not started. */
179
199
  get peerConnection() {
@@ -228,7 +248,7 @@ var Publisher = class {
228
248
  } else if (accepted && msg.type === "ready") {
229
249
  settled = true;
230
250
  closeAll(ws);
231
- resolve({ ws, readyInfo: msg });
251
+ resolve({ ws, readyInfo: msg, gatewayURL });
232
252
  }
233
253
  } catch {
234
254
  }
@@ -238,6 +258,113 @@ var Publisher = class {
238
258
  }
239
259
  });
240
260
  }
261
+ installSignaling(ws) {
262
+ const channel = SignalingChannel.wrap(ws);
263
+ this.sig = channel;
264
+ channel.onMessage = (msg) => this.handleSignal(msg);
265
+ channel.onClose = () => {
266
+ if (this.sig !== channel || this.stopped) return;
267
+ this.sig = null;
268
+ void this.resumeSignaling();
269
+ };
270
+ channel.onError = () => {
271
+ };
272
+ return channel;
273
+ }
274
+ async resumeSignaling() {
275
+ if (this.reconnecting || this.stopped) return;
276
+ if (!this.selectedGatewayURL || !this.readToken) {
277
+ this.terminateWithError(new Error("signaling closed and cannot be resumed"));
278
+ return;
279
+ }
280
+ this.reconnecting = true;
281
+ const generation = ++this.reconnectGeneration;
282
+ const timeout = this.opts.signalingReconnectTimeoutMs ?? defaultSignalingReconnectTimeoutMs;
283
+ const deadline = Date.now() + Math.max(0, timeout);
284
+ let backoffMs = 0;
285
+ while (!this.stopped && generation === this.reconnectGeneration && Date.now() <= deadline) {
286
+ if (backoffMs > 0) {
287
+ const waitMs = Math.min(backoffMs, Math.max(0, deadline - Date.now()));
288
+ if (waitMs === 0) break;
289
+ await this.wait(waitMs);
290
+ if (this.stopped || generation !== this.reconnectGeneration) return;
291
+ }
292
+ const remaining = deadline - Date.now();
293
+ if (remaining < 0) break;
294
+ try {
295
+ const ws = await this.openResumeSocket(Math.min(signalingResumeAttemptTimeoutMs, Math.max(1, remaining)));
296
+ if (this.stopped || generation !== this.reconnectGeneration) {
297
+ ws.close();
298
+ return;
299
+ }
300
+ this.resumeSocket = null;
301
+ this.reconnecting = false;
302
+ this.installSignaling(ws);
303
+ return;
304
+ } catch {
305
+ backoffMs = backoffMs === 0 ? 250 : Math.min(backoffMs * 2, signalingResumeMaxBackoffMs);
306
+ }
307
+ }
308
+ if (!this.stopped && generation === this.reconnectGeneration) {
309
+ this.reconnecting = false;
310
+ this.terminateWithError(new Error("unable to resume signaling with the selected gateway"));
311
+ }
312
+ }
313
+ openResumeSocket(timeoutMs) {
314
+ return new Promise((resolve, reject) => {
315
+ const u = new URL(this.selectedGatewayURL);
316
+ u.searchParams.set("token", this.readToken);
317
+ const ws = new WebSocket(u.toString());
318
+ this.resumeSocket = ws;
319
+ let settled = false;
320
+ const timer = setTimeout(() => fail(), timeoutMs);
321
+ const fail = () => {
322
+ if (settled) return;
323
+ settled = true;
324
+ clearTimeout(timer);
325
+ if (this.resumeSocket === ws) this.resumeSocket = null;
326
+ ws.onmessage = null;
327
+ ws.onerror = null;
328
+ ws.onclose = null;
329
+ ws.close();
330
+ reject(new Error("signaling resume attempt failed"));
331
+ };
332
+ ws.onmessage = (ev) => {
333
+ try {
334
+ const msg = JSON.parse(ev.data);
335
+ if (msg.type !== "resumed" || settled) return;
336
+ settled = true;
337
+ clearTimeout(timer);
338
+ resolve(ws);
339
+ } catch {
340
+ }
341
+ };
342
+ ws.onerror = fail;
343
+ ws.onclose = fail;
344
+ });
345
+ }
346
+ wait(ms) {
347
+ return new Promise((resolve) => setTimeout(resolve, ms));
348
+ }
349
+ terminateWithError(err) {
350
+ this.stopped = true;
351
+ this.cancelMediaRecovery();
352
+ this.reconnectGeneration++;
353
+ this.resumeSocket?.close();
354
+ this.resumeSocket = null;
355
+ this.sig?.close();
356
+ this.sig = null;
357
+ this.pc?.close();
358
+ this.pc = null;
359
+ this.unwatchStreamTracks();
360
+ this.localStream?.getTracks().forEach((track) => track.stop());
361
+ this.localStream = null;
362
+ this.hasAnswer = false;
363
+ this.pendingRemoteCandidates = [];
364
+ this.readToken = null;
365
+ this.selectedGatewayURL = null;
366
+ this.opts.callbacks?.onError?.(err);
367
+ }
241
368
  handleSignal(msg) {
242
369
  switch (msg.type) {
243
370
  case "answer": {
@@ -277,11 +404,123 @@ var Publisher = class {
277
404
  case "connection_state": {
278
405
  break;
279
406
  }
407
+ case "media_stall":
408
+ case "media_track_ended": {
409
+ void this.beginMediaRecovery(msg.track);
410
+ break;
411
+ }
412
+ case "media_resumed": {
413
+ this.completeMediaRecovery(msg.track);
414
+ break;
415
+ }
280
416
  case "error": {
281
417
  this.opts.callbacks?.onError?.(new Error(msg.error));
282
418
  break;
283
419
  }
420
+ case "resumed":
421
+ break;
422
+ }
423
+ }
424
+ async beginMediaRecovery(trackType) {
425
+ if (this.stopped || this.recoveringMedia || this.recoveryRequired) return;
426
+ const tracks = this.localStream?.getVideoTracks() ?? [];
427
+ const liveTracks = tracks.filter((track) => track.readyState !== "ended");
428
+ if (liveTracks.length === 0) {
429
+ this.failMediaRecovery(trackType, "capture_ended");
430
+ return;
431
+ }
432
+ this.recoveringMedia = true;
433
+ const generation = ++this.recoveryGeneration;
434
+ this.recoveryAction = "sender_restart";
435
+ this.emitRecoveryTransition({ state: "recovering", track: trackType, action: "sender_restart" });
436
+ this.sendRecoveryDiagnostic("recovery_started", trackType, "sender_restart");
437
+ await this.restartSenders(liveTracks, generation);
438
+ if (!this.isCurrentRecovery(generation)) return;
439
+ await this.wait(senderRecoveryWaitMs);
440
+ if (!this.isCurrentRecovery(generation)) return;
441
+ this.recoveryAction = "ice_restart";
442
+ this.emitRecoveryTransition({ state: "recovering", track: trackType, action: "ice_restart" });
443
+ this.sendRecoveryDiagnostic("recovery_retry", trackType, "ice_restart");
444
+ try {
445
+ await this.renegotiate(true);
446
+ } catch {
447
+ }
448
+ await this.wait(iceRecoveryWaitMs);
449
+ if (!this.isCurrentRecovery(generation)) return;
450
+ this.failMediaRecovery(trackType, "automatic_recovery_failed");
451
+ }
452
+ async restartSenders(tracks, generation) {
453
+ const live = new Set(tracks);
454
+ const senders = this.pc?.getSenders().filter(
455
+ (sender) => sender.track && live.has(sender.track)
456
+ ) ?? [];
457
+ if (senders.length === 0) return;
458
+ const originals = senders.map((sender) => ({ sender, track: sender.track }));
459
+ try {
460
+ await Promise.all(originals.map(({ sender }) => sender.replaceTrack(null)));
461
+ await this.wait(senderRestartPauseMs);
462
+ if (!this.isCurrentRecovery(generation)) return;
463
+ await Promise.all(originals.map(({ sender, track }) => sender.replaceTrack(track)));
464
+ await this.renegotiate(false);
465
+ } catch {
466
+ }
467
+ }
468
+ async renegotiate(iceRestart) {
469
+ const pc = this.pc;
470
+ const signaling = this.sig;
471
+ if (!pc || !signaling) throw new Error("publisher signaling is unavailable");
472
+ if (iceRestart) pc.restartIce?.();
473
+ const offer = await pc.createOffer(iceRestart ? { iceRestart: true } : void 0);
474
+ await pc.setLocalDescription(offer);
475
+ await this.gatherComplete();
476
+ const local = pc.localDescription;
477
+ if (!local) throw new Error("local description missing");
478
+ this.hasAnswer = false;
479
+ this.pendingRemoteCandidates = [];
480
+ signaling.send({ type: "offer", sdp: local.sdp, sdp_type: "offer" });
481
+ }
482
+ completeMediaRecovery(trackType) {
483
+ if (!this.recoveringMedia) return;
484
+ const action = this.recoveryAction ?? void 0;
485
+ this.cancelMediaRecovery();
486
+ this.emitRecoveryTransition({ state: "recovered", track: trackType, action });
487
+ }
488
+ failMediaRecovery(trackType, reason) {
489
+ if (this.stopped || this.recoveryRequired) return;
490
+ this.recoveryRequired = true;
491
+ const action = this.recoveryAction ?? void 0;
492
+ this.cancelMediaRecovery();
493
+ const event = { state: "failed", track: trackType, action, reason };
494
+ this.emitRecoveryTransition(event);
495
+ this.opts.callbacks?.onRecoveryRequired?.(event);
496
+ this.sendRecoveryDiagnostic("recovery_failed", trackType, action, reason);
497
+ }
498
+ cancelMediaRecovery() {
499
+ this.recoveryGeneration++;
500
+ this.recoveringMedia = false;
501
+ this.recoveryAction = null;
502
+ }
503
+ isCurrentRecovery(generation) {
504
+ return !this.stopped && this.recoveringMedia && generation === this.recoveryGeneration;
505
+ }
506
+ emitRecoveryTransition(event) {
507
+ this.opts.callbacks?.onRecoveryStateChange?.(event);
508
+ }
509
+ sendRecoveryDiagnostic(event, track, action, reason) {
510
+ this.sig?.send({ type: "recovery_event", event, track, action, reason });
511
+ }
512
+ watchStreamTracks(stream) {
513
+ for (const track of stream.getVideoTracks()) {
514
+ const handler = () => this.failMediaRecovery("screen", "capture_ended");
515
+ track.addEventListener("ended", handler);
516
+ this.trackEndHandlers.set(track, handler);
517
+ }
518
+ }
519
+ unwatchStreamTracks() {
520
+ for (const [track, handler] of this.trackEndHandlers) {
521
+ track.removeEventListener("ended", handler);
284
522
  }
523
+ this.trackEndHandlers.clear();
285
524
  }
286
525
  /** Waits for ICE gathering to reach the "complete" state. */
287
526
  gatherComplete() {
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/signaling.ts","../src/publisher.ts","../src/capture.ts"],"sourcesContent":["export { Publisher } from \"./publisher\";\nexport type {\n SignalMessage,\n PublisherCallbacks,\n PublisherOptions,\n GatewayReadyInfo,\n} from \"./types\";\nexport { captureCamera, captureScreen } from \"./capture\";\nexport type {\n CaptureCameraOptions,\n CaptureScreenOptions,\n} from \"./capture\";\n","import type { SignalMessage } from \"./types\";\n\n/**\n * Wraps an open WebSocket to the Argus gateway and handles the JSON message\n * envelope: incoming text frames are parsed into {@link SignalMessage}s and\n * outgoing messages are serialised.\n *\n * This is an internal helper. The {@link Publisher} opens the socket itself\n * (racing all candidate gateways) and hands the winner here, so this class only\n * ever adopts an already-open socket rather than dialing one.\n *\n * @internal\n */\nexport class SignalingChannel {\n private ws: WebSocket;\n\n /** Fired for every incoming JSON message. */\n onMessage: ((msg: SignalMessage) => void) | null = null;\n /** Fired when the underlying WebSocket closes. */\n onClose: (() => void) | null = null;\n /** Fired when an error occurs on the WebSocket. */\n onError: ((err: Error) => void) | null = null;\n\n private constructor(ws: WebSocket) {\n this.ws = ws;\n }\n\n /**\n * Adopts an already-open WebSocket (e.g. the winner of a gateway race),\n * routing its events through the channel's callbacks. Any handlers previously\n * attached to the socket are replaced.\n */\n static wrap(ws: WebSocket): SignalingChannel {\n const ch = new SignalingChannel(ws);\n ws.onmessage = (ev: MessageEvent) => {\n const msg = parseSignal(ev.data);\n if (msg) ch.onMessage?.(msg);\n };\n ws.onerror = () => ch.onError?.(new Error(\"WebSocket error\"));\n ws.onclose = () => ch.onClose?.();\n return ch;\n }\n\n /** Sends a JSON message if the socket is open; a no-op otherwise. */\n send(msg: SignalMessage): void {\n if (this.ws.readyState === WebSocket.OPEN) {\n this.ws.send(JSON.stringify(msg));\n }\n }\n\n /** Closes the underlying WebSocket. */\n close(): void {\n this.ws.close();\n }\n}\n\n/** Parses a WebSocket text frame into a SignalMessage, or null if malformed. */\nfunction parseSignal(data: unknown): SignalMessage | null {\n try {\n return JSON.parse(data as string) as SignalMessage;\n } catch {\n return null;\n }\n}\n","import { SignalingChannel } from \"./signaling\";\nimport type { GatewayReadyInfo, PublisherOptions, SignalMessage } from \"./types\";\n\n/**\n * Publisher streams a browser {@link MediaStream} to an Argus media server over\n * WebRTC. Given the `gateway_urls` and `token` from a join-token response, it\n * races the candidate gateways to the fastest one, completes the two-phase\n * signaling handshake, and manages the peer connection — offer/answer exchange,\n * ICE candidate trickling, and track (re)negotiation.\n *\n * After {@link Publisher.start} resolves, {@link Publisher.frameReadToken} holds\n * the token your application server needs to fetch frames for this stream.\n *\n * @example Publish the default camera:\n * ```ts\n * const pub = new Publisher({\n * gatewayURLs: joinResp.gateway_urls,\n * token: joinResp.token,\n * callbacks: { onConnected: () => console.log(\"live!\") },\n * });\n *\n * const stream = await navigator.mediaDevices.getUserMedia({ video: true });\n * await pub.start(stream);\n * ```\n */\nexport class Publisher {\n private opts: PublisherOptions;\n private sig: SignalingChannel | null = null;\n private pc: RTCPeerConnection | null = null;\n private hasAnswer = false;\n private pendingRemoteCandidates: RTCIceCandidateInit[] = [];\n private localStream: MediaStream | null = null;\n private readToken: string | null = null;\n\n constructor(opts: PublisherOptions) {\n this.opts = opts;\n }\n\n /** The read token received from the gateway after connecting, for fetching frames. */\n get frameReadToken(): string | null { return this.readToken; }\n\n /**\n * Starts the publisher: races all gateways to find the fastest, completes\n * the two-phase handshake, creates the peer connection, and sends the SDP\n * offer. Resolves when the offer has been sent (not when ICE completes —\n * use onConnected for that).\n */\n async start(stream: MediaStream): Promise<void> {\n this.localStream = stream;\n\n // Race all gateways; returns winning WebSocket + TURN/read-token info\n const { ws, readyInfo } = await this.raceGateways();\n\n // Store read token for caller\n if (readyInfo.read_token) {\n this.readToken = readyInfo.read_token;\n }\n\n // Build ICE servers: extra servers from opts + TURN from gateway. The\n // gateway supplies multi-transport turn_urls (UDP + TCP) so relay can fall\n // back to TCP on UDP-blocking networks. A single credential is valid for\n // every transport.\n const iceServers: RTCIceServer[] = [...(this.opts.iceServers ?? [])];\n if (readyInfo.turn_urls && readyInfo.turn_urls.length > 0) {\n iceServers.push({\n urls: readyInfo.turn_urls,\n username: readyInfo.turn_username,\n credential: readyInfo.turn_credential,\n });\n }\n\n this.pc = new RTCPeerConnection({ iceServers });\n\n this.pc.onicecandidate = (ev) => {\n if (!ev.candidate || !this.sig) return;\n const c = ev.candidate;\n this.sig.send({\n type: \"ice_candidate\",\n candidate: c.candidate,\n sdp_mid: c.sdpMid ?? undefined,\n sdp_mline_index: c.sdpMLineIndex ?? undefined,\n username_fragment: c.usernameFragment ?? undefined,\n });\n };\n\n this.pc.onconnectionstatechange = () => {\n const state = this.pc?.connectionState;\n if (state) this.opts.callbacks?.onConnectionStateChange?.(state);\n if (state === \"connected\") this.opts.callbacks?.onConnected?.();\n };\n\n for (const track of stream.getTracks()) {\n this.pc.addTrack(track, stream);\n }\n\n const offer = await this.pc.createOffer();\n await this.pc.setLocalDescription(offer);\n await this.gatherComplete();\n\n // Wrap winning WebSocket in SignalingChannel\n this.sig = SignalingChannel.wrap(ws);\n this.sig.onMessage = (msg) => this.handleSignal(msg);\n this.sig.onClose = () => this.opts.callbacks?.onError?.(new Error(\"signaling closed\"));\n this.sig.onError = (err) => this.opts.callbacks?.onError?.(err);\n\n const local = this.pc.localDescription;\n if (!local) throw new Error(\"local description missing after gather\");\n this.sig.send({ type: \"offer\", sdp: local.sdp, sdp_type: \"offer\" });\n }\n\n /** Replaces the currently published stream with a new one. */\n async replaceStream(stream: MediaStream): Promise<void> {\n if (!this.pc) throw new Error(\"publisher not started\");\n\n // Remove old tracks.\n const senders = this.pc.getSenders();\n for (const sender of senders) {\n if (sender.track) {\n this.pc.removeTrack(sender);\n }\n }\n\n // Add new tracks.\n for (const track of stream.getTracks()) {\n this.pc.addTrack(track, stream);\n }\n this.localStream = stream;\n\n // Renegotiate.\n const offer = await this.pc.createOffer();\n await this.pc.setLocalDescription(offer);\n await this.gatherComplete();\n\n const local = this.pc.localDescription;\n if (!local) throw new Error(\"local description missing\");\n this.sig?.send({\n type: \"offer\",\n sdp: local.sdp,\n sdp_type: \"offer\",\n });\n }\n\n /** Stops publishing and tears down the peer connection. */\n stop(): void {\n this.sig?.close();\n this.sig = null;\n\n this.localStream?.getTracks().forEach((t) => t.stop());\n this.localStream = null;\n\n this.pc?.close();\n this.pc = null;\n this.hasAnswer = false;\n this.pendingRemoteCandidates = [];\n this.readToken = null;\n }\n\n /** Returns the current RTCPeerConnection, or null if not started. */\n get peerConnection(): RTCPeerConnection | null {\n return this.pc;\n }\n\n /** Returns true if the peer connection is in the \"connected\" state. */\n get isConnected(): boolean {\n return this.pc?.connectionState === \"connected\";\n }\n\n // -------------------------------------------------------------------------\n // Private helpers\n // -------------------------------------------------------------------------\n\n private raceGateways(): Promise<{ ws: WebSocket; readyInfo: GatewayReadyInfo }> {\n return new Promise((resolve, reject) => {\n const { gatewayURLs, token } = this.opts;\n if (gatewayURLs.length === 0) {\n reject(new Error(\"no gateway URLs provided\"));\n return;\n }\n\n const sockets: WebSocket[] = [];\n let settled = false;\n\n const closeAll = (except?: WebSocket) => {\n for (const s of sockets) {\n if (s !== except) {\n s.onmessage = null;\n s.onerror = null;\n s.onclose = null;\n s.close();\n }\n }\n };\n\n const checkAllFailed = () => {\n if (settled) return;\n if (sockets.every(s => s.readyState === WebSocket.CLOSED || s.readyState === WebSocket.CLOSING)) {\n settled = true;\n reject(new Error(\"all gateways failed to connect\"));\n }\n };\n\n for (const gatewayURL of gatewayURLs) {\n const u = new URL(gatewayURL);\n u.searchParams.set(\"token\", token);\n const ws = new WebSocket(u.toString());\n sockets.push(ws);\n\n let accepted = false;\n\n ws.onmessage = (ev: MessageEvent) => {\n if (settled) return;\n try {\n const msg = JSON.parse(ev.data as string);\n if (!accepted && msg.type === \"accepted\") {\n accepted = true;\n ws.send(JSON.stringify({ type: \"proceed\" }));\n } else if (accepted && msg.type === \"ready\") {\n settled = true;\n closeAll(ws);\n resolve({ ws, readyInfo: msg as GatewayReadyInfo });\n }\n } catch {\n /* ignore malformed */\n }\n };\n\n ws.onerror = () => checkAllFailed();\n ws.onclose = () => checkAllFailed();\n }\n });\n }\n\n private handleSignal(msg: SignalMessage): void {\n switch (msg.type) {\n case \"answer\": {\n if (!this.pc) return;\n this.pc\n .setRemoteDescription(\n new RTCSessionDescription({ type: \"answer\", sdp: msg.sdp }),\n )\n .then(() => {\n this.hasAnswer = true;\n // Flush any ICE candidates that arrived before the answer.\n for (const init of this.pendingRemoteCandidates) {\n this.pc?.addIceCandidate(init).catch(() => {\n /* ignore stale candidates */\n });\n }\n this.pendingRemoteCandidates = [];\n })\n .catch((err) => {\n this.opts.callbacks?.onError?.(\n new Error(`failed to set remote description: ${err}`),\n );\n });\n break;\n }\n\n case \"ice_candidate\": {\n if (!this.pc) return;\n const init: RTCIceCandidateInit = {\n candidate: msg.candidate,\n sdpMid: msg.sdp_mid ?? null,\n sdpMLineIndex: msg.sdp_mline_index ?? null,\n usernameFragment: msg.username_fragment ?? null,\n };\n if (this.hasAnswer) {\n this.pc.addIceCandidate(init).catch(() => {\n /* ignore stale candidates */\n });\n } else {\n this.pendingRemoteCandidates.push(init);\n }\n break;\n }\n\n case \"connection_state\": {\n // The server echoes the peer connection state; the onconnectionstatechange\n // handler above already covers this, but callers can also react via\n // onConnectionStateChange.\n break;\n }\n\n case \"error\": {\n this.opts.callbacks?.onError?.(new Error(msg.error));\n break;\n }\n }\n }\n\n /** Waits for ICE gathering to reach the \"complete\" state. */\n private gatherComplete(): Promise<void> {\n return new Promise((resolve) => {\n const pc = this.pc;\n if (!pc) {\n resolve();\n return;\n }\n if (pc.iceGatheringState === \"complete\") {\n resolve();\n return;\n }\n const handler = () => {\n if (pc.iceGatheringState === \"complete\") {\n pc.removeEventListener(\"icegatheringstatechange\", handler);\n resolve();\n }\n };\n pc.addEventListener(\"icegatheringstatechange\", handler);\n });\n }\n}\n","/**\n * Options for {@link captureCamera}.\n *\n * These are merged shallowly over the library defaults: any field you provide\n * replaces the default for that field entirely (e.g. passing `video` overrides\n * the default video constraints rather than merging into them). Omit a field to\n * keep its default.\n */\nexport interface CaptureCameraOptions {\n /**\n * Video constraints, or `true`/`false`. Defaults to a modest resolution and\n * frame rate (see {@link captureCamera}). Set `false` to disable video.\n */\n video?: MediaTrackConstraints | boolean;\n /**\n * Audio constraints, or `true`/`false`. Defaults to `false` — Argus is a\n * video-frame streaming system, so audio is off unless you ask for it.\n */\n audio?: MediaTrackConstraints | boolean;\n /**\n * The `MediaDevices` instance to capture from. Defaults to the global\n * `navigator.mediaDevices`. Pass another window's `navigator.mediaDevices`\n * (e.g. a Document Picture-in-Picture window's) so the browser's permission\n * prompt and transient-activation check are anchored to that window rather\n * than the one holding the global `navigator`.\n */\n mediaDevices?: MediaDevices;\n}\n\n/**\n * Options for {@link captureScreen}.\n *\n * These are merged shallowly over the library defaults: any field you provide\n * replaces the default for that field entirely. Omit a field to keep its\n * default.\n */\nexport interface CaptureScreenOptions {\n /**\n * Video constraints, or `true`. Defaults to a capped width and a low frame\n * rate (see {@link captureScreen}).\n */\n video?: MediaTrackConstraints | boolean;\n /**\n * Audio constraints, or `true`/`false`. Defaults to `false` — screen shares\n * rarely need audio for a video-frame streaming system.\n */\n audio?: MediaTrackConstraints | boolean;\n /**\n * The `MediaDevices` instance to capture from. Defaults to the global\n * `navigator.mediaDevices`. Pass another window's `navigator.mediaDevices`\n * (e.g. a Document Picture-in-Picture window's) so the screen picker and its\n * transient-activation check are anchored to that window rather than the one\n * holding the global `navigator`.\n */\n mediaDevices?: MediaDevices;\n}\n\n/**\n * Captures the user's camera via `navigator.mediaDevices.getUserMedia`,\n * applying sensible defaults for a video-frame streaming system.\n *\n * Defaults:\n * - `video`: `{ width: { ideal: 1280 }, height: { ideal: 720 }, frameRate: { ideal: 30 } }`\n * — a modest resolution that keeps upload bandwidth reasonable. Cameras are\n * rarely the 4k bandwidth problem that screen capture is, so this is an\n * `ideal` (a hint) rather than a hard cap.\n * - `audio`: `false` — this is a video-frame streaming system.\n *\n * Any option you pass replaces the corresponding default outright (shallow\n * merge), so pass a full `video` constraints object if you want to tweak it.\n *\n * @example\n * ```ts\n * const stream = await captureCamera();\n * await publisher.start(stream);\n * ```\n *\n * @example Front camera with audio:\n * ```ts\n * const stream = await captureCamera({\n * video: { facingMode: \"user\" },\n * audio: true,\n * });\n * ```\n */\nexport async function captureCamera(\n opts: CaptureCameraOptions = {},\n): Promise<MediaStream> {\n const constraints: MediaStreamConstraints = {\n video: opts.video ?? {\n width: { ideal: 1280 },\n height: { ideal: 720 },\n frameRate: { ideal: 30 },\n },\n audio: opts.audio ?? false,\n };\n const mediaDevices = opts.mediaDevices ?? navigator.mediaDevices;\n return mediaDevices.getUserMedia(constraints);\n}\n\n/**\n * Captures a screen / window / tab via\n * `navigator.mediaDevices.getDisplayMedia`, applying sensible defaults tuned to\n * avoid the HiDPI/Retina bandwidth trap.\n *\n * Defaults:\n * - `video`: `{ width: { max: 1920 }, frameRate: { ideal: 5, max: 10 } }`.\n * The `width` is a **`max`, not an `ideal`**: on a 2x-Retina display the\n * browser would otherwise capture at native resolution (often 3456px+ /\n * effectively 4k), wasting upload bandwidth and downstream decode cost for no\n * visible benefit. Capping the max roughly halves a 2x-Retina share while\n * leaving smaller displays untouched. Screen content is mostly static, so the\n * low frame rate saves further bandwidth.\n * - `audio`: `false`.\n *\n * IMPORTANT — do NOT add `resizeMode: \"none\"` here. That value forbids the\n * browser from downscaling the source, which turns the `width: { max: 1920 }`\n * cap into a no-op on exactly the Retina displays it targets. By omitting\n * `resizeMode` we let the user agent scale to satisfy the constraint (its\n * default behaviour), which is the entire point of this helper. It is tempting\n * to add `resizeMode: \"none\"` back for \"sharpness\" — don't.\n *\n * Any option you pass replaces the corresponding default outright (shallow\n * merge), so pass a full `video` constraints object if you want to tweak it.\n *\n * @example\n * ```ts\n * const stream = await captureScreen();\n * await publisher.start(stream);\n * ```\n */\nexport async function captureScreen(\n opts: CaptureScreenOptions = {},\n): Promise<MediaStream> {\n const constraints: MediaStreamConstraints = {\n video: opts.video ?? {\n width: { max: 1920 },\n frameRate: { ideal: 5, max: 10 },\n },\n audio: opts.audio ?? false,\n };\n const mediaDevices = opts.mediaDevices ?? navigator.mediaDevices;\n return mediaDevices.getDisplayMedia(constraints);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACaO,IAAM,mBAAN,MAAM,kBAAiB;AAAA,EACpB;AAAA;AAAA,EAGR,YAAmD;AAAA;AAAA,EAEnD,UAA+B;AAAA;AAAA,EAE/B,UAAyC;AAAA,EAEjC,YAAY,IAAe;AACjC,SAAK,KAAK;AAAA,EACZ;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,OAAO,KAAK,IAAiC;AAC3C,UAAM,KAAK,IAAI,kBAAiB,EAAE;AAClC,OAAG,YAAY,CAAC,OAAqB;AACnC,YAAM,MAAM,YAAY,GAAG,IAAI;AAC/B,UAAI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xD,CAAC;AAAA,EACH;AACF;;;AClOA,eAAsB,cACpB,OAA6B,CAAC,GACR;AACtB,QAAM,cAAsC;AAAA,IAC1C,OAAO,KAAK,SAAS;AAAA,MACnB,OAAO,EAAE,OAAO,KAAK;AAAA,MACrB,QAAQ,EAAE,OAAO,IAAI;AAAA,MACrB,WAAW,EAAE,OAAO,GAAG;AAAA,IACzB;AAAA,IACA,OAAO,KAAK,SAAS;AAAA,EACvB;AACA,QAAM,eAAe,KAAK,gBAAgB,UAAU;AACpD,SAAO,aAAa,aAAa,WAAW;AAC9C;AAiCA,eAAsB,cACpB,OAA6B,CAAC,GACR;AACtB,QAAM,cAAsC;AAAA,IAC1C,OAAO,KAAK,SAAS;AAAA,MACnB,OAAO,EAAE,KAAK,KAAK;AAAA,MACnB,WAAW,EAAE,OAAO,GAAG,KAAK,GAAG;AAAA,IACjC;AAAA,IACA,OAAO,KAAK,SAAS;AAAA,EACvB;AACA,QAAM,eAAe,KAAK,gBAAgB,UAAU;AACpD,SAAO,aAAa,gBAAgB,WAAW;AACjD;","names":[]}
1
+ {"version":3,"sources":["../src/index.ts","../src/signaling.ts","../src/publisher.ts","../src/capture.ts"],"sourcesContent":["export { Publisher } from \"./publisher\";\nexport type {\n SignalMessage,\n PublisherCallbacks,\n PublisherOptions,\n GatewayReadyInfo,\n PublisherRecoveryEvent,\n PublisherRecoveryState,\n PublisherRecoveryAction,\n PublisherRecoveryFailureReason,\n} from \"./types\";\nexport { captureCamera, captureScreen } from \"./capture\";\nexport type {\n CaptureCameraOptions,\n CaptureScreenOptions,\n} from \"./capture\";\n","import type { SignalMessage } from \"./types\";\n\n/**\n * Wraps an open WebSocket to the Argus gateway and handles the JSON message\n * envelope: incoming text frames are parsed into {@link SignalMessage}s and\n * outgoing messages are serialised.\n *\n * This is an internal helper. The {@link Publisher} opens the socket itself\n * (racing all candidate gateways) and hands the winner here, so this class only\n * ever adopts an already-open socket rather than dialing one.\n *\n * @internal\n */\nexport class SignalingChannel {\n private ws: WebSocket;\n\n /** Fired for every incoming JSON message. */\n onMessage: ((msg: SignalMessage) => void) | null = null;\n /** Fired when the underlying WebSocket closes. */\n onClose: (() => void) | null = null;\n /** Fired when an error occurs on the WebSocket. */\n onError: ((err: Error) => void) | null = null;\n\n private constructor(ws: WebSocket) {\n this.ws = ws;\n }\n\n /**\n * Adopts an already-open WebSocket (e.g. the winner of a gateway race),\n * routing its events through the channel's callbacks. Any handlers previously\n * attached to the socket are replaced.\n */\n static wrap(ws: WebSocket): SignalingChannel {\n const ch = new SignalingChannel(ws);\n ws.onmessage = (ev: MessageEvent) => {\n const msg = parseSignal(ev.data);\n if (msg) ch.onMessage?.(msg);\n };\n ws.onerror = () => ch.onError?.(new Error(\"WebSocket error\"));\n ws.onclose = () => ch.onClose?.();\n return ch;\n }\n\n /** Sends a JSON message if the socket is open; a no-op otherwise. */\n send(msg: SignalMessage): void {\n if (this.ws.readyState === WebSocket.OPEN) {\n this.ws.send(JSON.stringify(msg));\n }\n }\n\n /** Closes the underlying WebSocket. */\n close(): void {\n this.ws.close();\n }\n}\n\n/** Parses a WebSocket text frame into a SignalMessage, or null if malformed. */\nfunction parseSignal(data: unknown): SignalMessage | null {\n try {\n return JSON.parse(data as string) as SignalMessage;\n } catch {\n return null;\n }\n}\n","import { SignalingChannel } from \"./signaling\";\nimport type {\n GatewayReadyInfo,\n PublisherOptions,\n PublisherRecoveryAction,\n PublisherRecoveryEvent,\n SignalMessage,\n} from \"./types\";\n\nconst defaultSignalingReconnectTimeoutMs = 20_000;\nconst signalingResumeAttemptTimeoutMs = 3_000;\nconst signalingResumeMaxBackoffMs = 3_000;\nconst senderRestartPauseMs = 100;\nconst senderRecoveryWaitMs = 4_000;\nconst iceRecoveryWaitMs = 8_000;\n\n/**\n * Publisher streams a browser {@link MediaStream} to an Argus media server over\n * WebRTC. Given the `gateway_urls` and `token` from a join-token response, it\n * races the candidate gateways to the fastest one, completes the two-phase\n * signaling handshake, and manages the peer connection — offer/answer exchange,\n * ICE candidate trickling, and track (re)negotiation.\n *\n * After {@link Publisher.start} resolves, {@link Publisher.frameReadToken} holds\n * the token your application server needs to fetch frames for this stream.\n *\n * @example Publish the default camera:\n * ```ts\n * const pub = new Publisher({\n * gatewayURLs: joinResp.gateway_urls,\n * token: joinResp.token,\n * callbacks: { onConnected: () => console.log(\"live!\") },\n * });\n *\n * const stream = await navigator.mediaDevices.getUserMedia({ video: true });\n * await pub.start(stream);\n * ```\n */\nexport class Publisher {\n private opts: PublisherOptions;\n private sig: SignalingChannel | null = null;\n private pc: RTCPeerConnection | null = null;\n private hasAnswer = false;\n private pendingRemoteCandidates: RTCIceCandidateInit[] = [];\n private localStream: MediaStream | null = null;\n private readToken: string | null = null;\n private selectedGatewayURL: string | null = null;\n private stopped = true;\n private reconnecting = false;\n private reconnectGeneration = 0;\n private resumeSocket: WebSocket | null = null;\n private recoveryGeneration = 0;\n private recoveringMedia = false;\n private recoveryRequired = false;\n private recoveryAction: PublisherRecoveryAction | null = null;\n private trackEndHandlers = new Map<MediaStreamTrack, EventListener>();\n\n constructor(opts: PublisherOptions) {\n this.opts = opts;\n }\n\n /** The read token used for frame fetches and signaling resume in the selected region. */\n get frameReadToken(): string | null { return this.readToken; }\n\n /**\n * Starts the publisher: races all gateways to find the fastest, completes\n * the two-phase handshake, creates the peer connection, and sends the SDP\n * offer. Resolves when the offer has been sent (not when ICE completes —\n * use onConnected for that).\n */\n async start(stream: MediaStream): Promise<void> {\n this.stopped = false;\n this.recoveryRequired = false;\n this.localStream = stream;\n this.watchStreamTracks(stream);\n\n // Race all gateways; returns winning WebSocket + TURN/read-token info\n const { ws, readyInfo, gatewayURL } = await this.raceGateways();\n this.selectedGatewayURL = gatewayURL;\n\n // Store read token for caller\n if (readyInfo.read_token) {\n this.readToken = readyInfo.read_token;\n }\n\n // Build ICE servers: extra servers from opts + TURN from gateway. The\n // gateway supplies multi-transport turn_urls (UDP + TCP) so relay can fall\n // back to TCP on UDP-blocking networks. A single credential is valid for\n // every transport.\n const iceServers: RTCIceServer[] = [...(this.opts.iceServers ?? [])];\n if (readyInfo.turn_urls && readyInfo.turn_urls.length > 0) {\n iceServers.push({\n urls: readyInfo.turn_urls,\n username: readyInfo.turn_username,\n credential: readyInfo.turn_credential,\n });\n }\n\n this.pc = new RTCPeerConnection({ iceServers });\n\n this.pc.onicecandidate = (ev) => {\n if (!ev.candidate || !this.sig) return;\n const c = ev.candidate;\n this.sig.send({\n type: \"ice_candidate\",\n candidate: c.candidate,\n sdp_mid: c.sdpMid ?? undefined,\n sdp_mline_index: c.sdpMLineIndex ?? undefined,\n username_fragment: c.usernameFragment ?? undefined,\n });\n };\n\n this.pc.onconnectionstatechange = () => {\n const state = this.pc?.connectionState;\n if (state) this.opts.callbacks?.onConnectionStateChange?.(state);\n if (state === \"connected\") this.opts.callbacks?.onConnected?.();\n };\n\n for (const track of stream.getTracks()) {\n this.pc.addTrack(track, stream);\n }\n\n const offer = await this.pc.createOffer();\n await this.pc.setLocalDescription(offer);\n await this.gatherComplete();\n\n // Wrap winning WebSocket in SignalingChannel\n const signaling = this.installSignaling(ws);\n\n const local = this.pc.localDescription;\n if (!local) throw new Error(\"local description missing after gather\");\n signaling.send({ type: \"offer\", sdp: local.sdp, sdp_type: \"offer\" });\n }\n\n /** Replaces the currently published stream with a new one. */\n async replaceStream(stream: MediaStream): Promise<void> {\n if (!this.pc) throw new Error(\"publisher not started\");\n\n this.cancelMediaRecovery();\n this.recoveryRequired = false;\n this.unwatchStreamTracks();\n\n // Remove old tracks.\n const senders = this.pc.getSenders();\n for (const sender of senders) {\n if (sender.track) {\n this.pc.removeTrack(sender);\n }\n }\n\n // Add new tracks.\n for (const track of stream.getTracks()) {\n this.pc.addTrack(track, stream);\n }\n this.localStream = stream;\n this.watchStreamTracks(stream);\n\n await this.renegotiate(false);\n }\n\n /** Stops publishing and tears down the peer connection. */\n stop(): void {\n this.stopped = true;\n this.cancelMediaRecovery();\n this.reconnectGeneration++;\n this.reconnecting = false;\n this.resumeSocket?.close();\n this.resumeSocket = null;\n this.sig?.close();\n this.sig = null;\n\n this.unwatchStreamTracks();\n this.localStream?.getTracks().forEach((t) => t.stop());\n this.localStream = null;\n\n this.pc?.close();\n this.pc = null;\n this.hasAnswer = false;\n this.pendingRemoteCandidates = [];\n this.readToken = null;\n this.selectedGatewayURL = null;\n }\n\n /** Returns the current RTCPeerConnection, or null if not started. */\n get peerConnection(): RTCPeerConnection | null {\n return this.pc;\n }\n\n /** Returns true if the peer connection is in the \"connected\" state. */\n get isConnected(): boolean {\n return this.pc?.connectionState === \"connected\";\n }\n\n // -------------------------------------------------------------------------\n // Private helpers\n // -------------------------------------------------------------------------\n\n private raceGateways(): Promise<{ ws: WebSocket; readyInfo: GatewayReadyInfo; gatewayURL: string }> {\n return new Promise((resolve, reject) => {\n const { gatewayURLs, token } = this.opts;\n if (gatewayURLs.length === 0) {\n reject(new Error(\"no gateway URLs provided\"));\n return;\n }\n\n const sockets: WebSocket[] = [];\n let settled = false;\n\n const closeAll = (except?: WebSocket) => {\n for (const s of sockets) {\n if (s !== except) {\n s.onmessage = null;\n s.onerror = null;\n s.onclose = null;\n s.close();\n }\n }\n };\n\n const checkAllFailed = () => {\n if (settled) return;\n if (sockets.every(s => s.readyState === WebSocket.CLOSED || s.readyState === WebSocket.CLOSING)) {\n settled = true;\n reject(new Error(\"all gateways failed to connect\"));\n }\n };\n\n for (const gatewayURL of gatewayURLs) {\n const u = new URL(gatewayURL);\n u.searchParams.set(\"token\", token);\n const ws = new WebSocket(u.toString());\n sockets.push(ws);\n\n let accepted = false;\n\n ws.onmessage = (ev: MessageEvent) => {\n if (settled) return;\n try {\n const msg = JSON.parse(ev.data as string);\n if (!accepted && msg.type === \"accepted\") {\n accepted = true;\n ws.send(JSON.stringify({ type: \"proceed\" }));\n } else if (accepted && msg.type === \"ready\") {\n settled = true;\n closeAll(ws);\n resolve({ ws, readyInfo: msg as GatewayReadyInfo, gatewayURL });\n }\n } catch {\n /* ignore malformed */\n }\n };\n\n ws.onerror = () => checkAllFailed();\n ws.onclose = () => checkAllFailed();\n }\n });\n }\n\n private installSignaling(ws: WebSocket): SignalingChannel {\n const channel = SignalingChannel.wrap(ws);\n this.sig = channel;\n channel.onMessage = (msg) => this.handleSignal(msg);\n channel.onClose = () => {\n if (this.sig !== channel || this.stopped) return;\n this.sig = null;\n void this.resumeSignaling();\n };\n // Browsers normally follow an error event with close. Recovery begins from\n // close so a single transport failure cannot start two retry loops.\n channel.onError = () => {};\n return channel;\n }\n\n private async resumeSignaling(): Promise<void> {\n if (this.reconnecting || this.stopped) return;\n if (!this.selectedGatewayURL || !this.readToken) {\n this.terminateWithError(new Error(\"signaling closed and cannot be resumed\"));\n return;\n }\n\n this.reconnecting = true;\n const generation = ++this.reconnectGeneration;\n const timeout = this.opts.signalingReconnectTimeoutMs ?? defaultSignalingReconnectTimeoutMs;\n const deadline = Date.now() + Math.max(0, timeout);\n let backoffMs = 0;\n\n while (!this.stopped && generation === this.reconnectGeneration && Date.now() <= deadline) {\n if (backoffMs > 0) {\n const waitMs = Math.min(backoffMs, Math.max(0, deadline - Date.now()));\n if (waitMs === 0) break;\n await this.wait(waitMs);\n if (this.stopped || generation !== this.reconnectGeneration) return;\n }\n\n const remaining = deadline - Date.now();\n if (remaining < 0) break;\n try {\n const ws = await this.openResumeSocket(Math.min(signalingResumeAttemptTimeoutMs, Math.max(1, remaining)));\n if (this.stopped || generation !== this.reconnectGeneration) {\n ws.close();\n return;\n }\n this.resumeSocket = null;\n this.reconnecting = false;\n this.installSignaling(ws);\n return;\n } catch {\n backoffMs = backoffMs === 0 ? 250 : Math.min(backoffMs * 2, signalingResumeMaxBackoffMs);\n }\n }\n\n if (!this.stopped && generation === this.reconnectGeneration) {\n this.reconnecting = false;\n this.terminateWithError(new Error(\"unable to resume signaling with the selected gateway\"));\n }\n }\n\n private openResumeSocket(timeoutMs: number): Promise<WebSocket> {\n return new Promise((resolve, reject) => {\n const u = new URL(this.selectedGatewayURL!);\n u.searchParams.set(\"token\", this.readToken!);\n const ws = new WebSocket(u.toString());\n this.resumeSocket = ws;\n let settled = false;\n const timer = setTimeout(() => fail(), timeoutMs);\n\n const fail = () => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n if (this.resumeSocket === ws) this.resumeSocket = null;\n ws.onmessage = null;\n ws.onerror = null;\n ws.onclose = null;\n ws.close();\n reject(new Error(\"signaling resume attempt failed\"));\n };\n\n ws.onmessage = (ev: MessageEvent) => {\n try {\n const msg = JSON.parse(ev.data as string);\n if (msg.type !== \"resumed\" || settled) return;\n settled = true;\n clearTimeout(timer);\n resolve(ws);\n } catch {\n // Ignore malformed messages while waiting for the resume acknowledgement.\n }\n };\n ws.onerror = fail;\n ws.onclose = fail;\n });\n }\n\n private wait(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n\n private terminateWithError(err: Error): void {\n this.stopped = true;\n this.cancelMediaRecovery();\n this.reconnectGeneration++;\n this.resumeSocket?.close();\n this.resumeSocket = null;\n this.sig?.close();\n this.sig = null;\n this.pc?.close();\n this.pc = null;\n this.unwatchStreamTracks();\n this.localStream?.getTracks().forEach((track) => track.stop());\n this.localStream = null;\n this.hasAnswer = false;\n this.pendingRemoteCandidates = [];\n this.readToken = null;\n this.selectedGatewayURL = null;\n this.opts.callbacks?.onError?.(err);\n }\n\n private handleSignal(msg: SignalMessage): void {\n switch (msg.type) {\n case \"answer\": {\n if (!this.pc) return;\n this.pc\n .setRemoteDescription(\n new RTCSessionDescription({ type: \"answer\", sdp: msg.sdp }),\n )\n .then(() => {\n this.hasAnswer = true;\n // Flush any ICE candidates that arrived before the answer.\n for (const init of this.pendingRemoteCandidates) {\n this.pc?.addIceCandidate(init).catch(() => {\n /* ignore stale candidates */\n });\n }\n this.pendingRemoteCandidates = [];\n })\n .catch((err) => {\n this.opts.callbacks?.onError?.(\n new Error(`failed to set remote description: ${err}`),\n );\n });\n break;\n }\n\n case \"ice_candidate\": {\n if (!this.pc) return;\n const init: RTCIceCandidateInit = {\n candidate: msg.candidate,\n sdpMid: msg.sdp_mid ?? null,\n sdpMLineIndex: msg.sdp_mline_index ?? null,\n usernameFragment: msg.username_fragment ?? null,\n };\n if (this.hasAnswer) {\n this.pc.addIceCandidate(init).catch(() => {\n /* ignore stale candidates */\n });\n } else {\n this.pendingRemoteCandidates.push(init);\n }\n break;\n }\n\n case \"connection_state\": {\n // The server echoes the peer connection state; the onconnectionstatechange\n // handler above already covers this, but callers can also react via\n // onConnectionStateChange.\n break;\n }\n\n case \"media_stall\":\n case \"media_track_ended\": {\n void this.beginMediaRecovery(msg.track);\n break;\n }\n\n case \"media_resumed\": {\n this.completeMediaRecovery(msg.track);\n break;\n }\n\n case \"error\": {\n this.opts.callbacks?.onError?.(new Error(msg.error));\n break;\n }\n\n case \"resumed\":\n break;\n }\n }\n\n private async beginMediaRecovery(trackType: string): Promise<void> {\n if (this.stopped || this.recoveringMedia || this.recoveryRequired) return;\n\n const tracks = this.localStream?.getVideoTracks() ?? [];\n const liveTracks = tracks.filter((track) => track.readyState !== \"ended\");\n if (liveTracks.length === 0) {\n this.failMediaRecovery(trackType, \"capture_ended\");\n return;\n }\n\n this.recoveringMedia = true;\n const generation = ++this.recoveryGeneration;\n this.recoveryAction = \"sender_restart\";\n this.emitRecoveryTransition({ state: \"recovering\", track: trackType, action: \"sender_restart\" });\n this.sendRecoveryDiagnostic(\"recovery_started\", trackType, \"sender_restart\");\n\n await this.restartSenders(liveTracks, generation);\n if (!this.isCurrentRecovery(generation)) return;\n\n await this.wait(senderRecoveryWaitMs);\n if (!this.isCurrentRecovery(generation)) return;\n\n this.recoveryAction = \"ice_restart\";\n this.emitRecoveryTransition({ state: \"recovering\", track: trackType, action: \"ice_restart\" });\n this.sendRecoveryDiagnostic(\"recovery_retry\", trackType, \"ice_restart\");\n try {\n await this.renegotiate(true);\n } catch {\n // The fixed recovery window below still gives signaling-resume a chance.\n // If media does not recover, the host receives onRecoveryRequired.\n }\n\n await this.wait(iceRecoveryWaitMs);\n if (!this.isCurrentRecovery(generation)) return;\n this.failMediaRecovery(trackType, \"automatic_recovery_failed\");\n }\n\n private async restartSenders(tracks: MediaStreamTrack[], generation: number): Promise<void> {\n const live = new Set(tracks);\n const senders = this.pc?.getSenders().filter(\n (sender) => sender.track && live.has(sender.track),\n ) ?? [];\n if (senders.length === 0) return;\n\n const originals = senders.map((sender) => ({ sender, track: sender.track! }));\n try {\n await Promise.all(originals.map(({ sender }) => sender.replaceTrack(null)));\n await this.wait(senderRestartPauseMs);\n if (!this.isCurrentRecovery(generation)) return;\n await Promise.all(originals.map(({ sender, track }) => sender.replaceTrack(track)));\n await this.renegotiate(false);\n } catch {\n // ICE restart is the second stage and may still recover a sender reset or\n // renegotiation failure, so do not fail the stream at this stage.\n }\n }\n\n private async renegotiate(iceRestart: boolean): Promise<void> {\n const pc = this.pc;\n const signaling = this.sig;\n if (!pc || !signaling) throw new Error(\"publisher signaling is unavailable\");\n\n if (iceRestart) pc.restartIce?.();\n const offer = await pc.createOffer(iceRestart ? { iceRestart: true } : undefined);\n await pc.setLocalDescription(offer);\n await this.gatherComplete();\n\n const local = pc.localDescription;\n if (!local) throw new Error(\"local description missing\");\n this.hasAnswer = false;\n this.pendingRemoteCandidates = [];\n signaling.send({ type: \"offer\", sdp: local.sdp, sdp_type: \"offer\" });\n }\n\n private completeMediaRecovery(trackType: string): void {\n if (!this.recoveringMedia) return;\n const action = this.recoveryAction ?? undefined;\n this.cancelMediaRecovery();\n this.emitRecoveryTransition({ state: \"recovered\", track: trackType, action });\n }\n\n private failMediaRecovery(\n trackType: string,\n reason: \"capture_ended\" | \"automatic_recovery_failed\",\n ): void {\n if (this.stopped || this.recoveryRequired) return;\n this.recoveryRequired = true;\n const action = this.recoveryAction ?? undefined;\n this.cancelMediaRecovery();\n const event: PublisherRecoveryEvent = { state: \"failed\", track: trackType, action, reason };\n this.emitRecoveryTransition(event);\n this.opts.callbacks?.onRecoveryRequired?.(event);\n this.sendRecoveryDiagnostic(\"recovery_failed\", trackType, action, reason);\n }\n\n private cancelMediaRecovery(): void {\n this.recoveryGeneration++;\n this.recoveringMedia = false;\n this.recoveryAction = null;\n }\n\n private isCurrentRecovery(generation: number): boolean {\n return !this.stopped && this.recoveringMedia && generation === this.recoveryGeneration;\n }\n\n private emitRecoveryTransition(event: PublisherRecoveryEvent): void {\n this.opts.callbacks?.onRecoveryStateChange?.(event);\n }\n\n private sendRecoveryDiagnostic(\n event: \"recovery_started\" | \"recovery_retry\" | \"recovery_failed\",\n track: string,\n action?: PublisherRecoveryAction,\n reason?: \"capture_ended\" | \"automatic_recovery_failed\",\n ): void {\n this.sig?.send({ type: \"recovery_event\", event, track, action, reason });\n }\n\n private watchStreamTracks(stream: MediaStream): void {\n for (const track of stream.getVideoTracks()) {\n const handler: EventListener = () => this.failMediaRecovery(\"screen\", \"capture_ended\");\n track.addEventListener(\"ended\", handler);\n this.trackEndHandlers.set(track, handler);\n }\n }\n\n private unwatchStreamTracks(): void {\n for (const [track, handler] of this.trackEndHandlers) {\n track.removeEventListener(\"ended\", handler);\n }\n this.trackEndHandlers.clear();\n }\n\n /** Waits for ICE gathering to reach the \"complete\" state. */\n private gatherComplete(): Promise<void> {\n return new Promise((resolve) => {\n const pc = this.pc;\n if (!pc) {\n resolve();\n return;\n }\n if (pc.iceGatheringState === \"complete\") {\n resolve();\n return;\n }\n const handler = () => {\n if (pc.iceGatheringState === \"complete\") {\n pc.removeEventListener(\"icegatheringstatechange\", handler);\n resolve();\n }\n };\n pc.addEventListener(\"icegatheringstatechange\", handler);\n });\n }\n}\n","/**\n * Options for {@link captureCamera}.\n *\n * These are merged shallowly over the library defaults: any field you provide\n * replaces the default for that field entirely (e.g. passing `video` overrides\n * the default video constraints rather than merging into them). Omit a field to\n * keep its default.\n */\nexport interface CaptureCameraOptions {\n /**\n * Video constraints, or `true`/`false`. Defaults to a modest resolution and\n * frame rate (see {@link captureCamera}). Set `false` to disable video.\n */\n video?: MediaTrackConstraints | boolean;\n /**\n * Audio constraints, or `true`/`false`. Defaults to `false` — Argus is a\n * video-frame streaming system, so audio is off unless you ask for it.\n */\n audio?: MediaTrackConstraints | boolean;\n /**\n * The `MediaDevices` instance to capture from. Defaults to the global\n * `navigator.mediaDevices`. Pass another window's `navigator.mediaDevices`\n * (e.g. a Document Picture-in-Picture window's) so the browser's permission\n * prompt and transient-activation check are anchored to that window rather\n * than the one holding the global `navigator`.\n */\n mediaDevices?: MediaDevices;\n}\n\n/**\n * Options for {@link captureScreen}.\n *\n * These are merged shallowly over the library defaults: any field you provide\n * replaces the default for that field entirely. Omit a field to keep its\n * default.\n */\nexport interface CaptureScreenOptions {\n /**\n * Video constraints, or `true`. Defaults to a capped width and a low frame\n * rate (see {@link captureScreen}).\n */\n video?: MediaTrackConstraints | boolean;\n /**\n * Audio constraints, or `true`/`false`. Defaults to `false` — screen shares\n * rarely need audio for a video-frame streaming system.\n */\n audio?: MediaTrackConstraints | boolean;\n /**\n * The `MediaDevices` instance to capture from. Defaults to the global\n * `navigator.mediaDevices`. Pass another window's `navigator.mediaDevices`\n * (e.g. a Document Picture-in-Picture window's) so the screen picker and its\n * transient-activation check are anchored to that window rather than the one\n * holding the global `navigator`.\n */\n mediaDevices?: MediaDevices;\n}\n\n/**\n * Captures the user's camera via `navigator.mediaDevices.getUserMedia`,\n * applying sensible defaults for a video-frame streaming system.\n *\n * Defaults:\n * - `video`: `{ width: { ideal: 1280 }, height: { ideal: 720 }, frameRate: { ideal: 30 } }`\n * — a modest resolution that keeps upload bandwidth reasonable. Cameras are\n * rarely the 4k bandwidth problem that screen capture is, so this is an\n * `ideal` (a hint) rather than a hard cap.\n * - `audio`: `false` — this is a video-frame streaming system.\n *\n * Any option you pass replaces the corresponding default outright (shallow\n * merge), so pass a full `video` constraints object if you want to tweak it.\n *\n * @example\n * ```ts\n * const stream = await captureCamera();\n * await publisher.start(stream);\n * ```\n *\n * @example Front camera with audio:\n * ```ts\n * const stream = await captureCamera({\n * video: { facingMode: \"user\" },\n * audio: true,\n * });\n * ```\n */\nexport async function captureCamera(\n opts: CaptureCameraOptions = {},\n): Promise<MediaStream> {\n const constraints: MediaStreamConstraints = {\n video: opts.video ?? {\n width: { ideal: 1280 },\n height: { ideal: 720 },\n frameRate: { ideal: 30 },\n },\n audio: opts.audio ?? false,\n };\n const mediaDevices = opts.mediaDevices ?? navigator.mediaDevices;\n return mediaDevices.getUserMedia(constraints);\n}\n\n/**\n * Captures a screen / window / tab via\n * `navigator.mediaDevices.getDisplayMedia`, applying sensible defaults tuned to\n * avoid the HiDPI/Retina bandwidth trap.\n *\n * Defaults:\n * - `video`: `{ width: { max: 1920 }, frameRate: { ideal: 5, max: 10 } }`.\n * The `width` is a **`max`, not an `ideal`**: on a 2x-Retina display the\n * browser would otherwise capture at native resolution (often 3456px+ /\n * effectively 4k), wasting upload bandwidth and downstream decode cost for no\n * visible benefit. Capping the max roughly halves a 2x-Retina share while\n * leaving smaller displays untouched. Screen content is mostly static, so the\n * low frame rate saves further bandwidth.\n * - `audio`: `false`.\n *\n * IMPORTANT — do NOT add `resizeMode: \"none\"` here. That value forbids the\n * browser from downscaling the source, which turns the `width: { max: 1920 }`\n * cap into a no-op on exactly the Retina displays it targets. By omitting\n * `resizeMode` we let the user agent scale to satisfy the constraint (its\n * default behaviour), which is the entire point of this helper. It is tempting\n * to add `resizeMode: \"none\"` back for \"sharpness\" — don't.\n *\n * Any option you pass replaces the corresponding default outright (shallow\n * merge), so pass a full `video` constraints object if you want to tweak it.\n *\n * @example\n * ```ts\n * const stream = await captureScreen();\n * await publisher.start(stream);\n * ```\n */\nexport async function captureScreen(\n opts: CaptureScreenOptions = {},\n): Promise<MediaStream> {\n const constraints: MediaStreamConstraints = {\n video: opts.video ?? {\n width: { max: 1920 },\n frameRate: { ideal: 5, max: 10 },\n },\n audio: opts.audio ?? false,\n };\n const mediaDevices = opts.mediaDevices ?? navigator.mediaDevices;\n return mediaDevices.getDisplayMedia(constraints);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;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