@reactor-team/js-sdk 3.0.2 → 3.2.0

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
@@ -23,6 +23,16 @@ Full reference and guides live at **[docs.reactor.inc](https://docs.reactor.inc)
23
23
  npm install @reactor-team/js-sdk
24
24
  ```
25
25
 
26
+ No bundler configuration needed: the WebAssembly binding the SDK runs on
27
+ ships inside its own JavaScript module, fetched the first time a `Reactor`
28
+ connects rather than when the SDK is imported. Each release is
29
+ checked against Vite 6, 7 and 8 and Next.js 15 and 16 (webpack and
30
+ Turbopack), in both dev and production builds, except Next.js 15 with
31
+ Turbopack, checked in dev only since its production build is still beta.
32
+
33
+ If your page sets a Content Security Policy, its `script-src` needs
34
+ `'wasm-unsafe-eval'` for the binding to compile.
35
+
26
36
  ## Quickstart
27
37
 
28
38
  ```ts
@@ -30,7 +40,7 @@ import { Reactor } from "@reactor-team/js-sdk";
30
40
 
31
41
  const reactor = new Reactor({
32
42
  modelName: "my-model",
33
- jwt: () => fetchToken(), // or a plain string; omit for an unauthenticated local runtime
43
+ jwt: fetchToken, // your resolver, or a plain string; omit for an unauthenticated local runtime
34
44
  });
35
45
 
36
46
  reactor.on("statusChanged", (status) => {
@@ -78,6 +88,45 @@ const { jwt } = await result.json();
78
88
  See [Authentication](https://docs.reactor.inc/authentication) for the full request shape,
79
89
  including `max_session_duration_seconds` and other constraints.
80
90
 
91
+ ### Refreshing a token mid-session
92
+
93
+ A scoped token reaches only the sessions it created or was bound to. When a session outlives
94
+ its token, a fresh token minted the same way cannot reach it: uploads, reconnects, the session
95
+ delete and clip reads all return `403`. So the SDK tells the resolver what each request is for:
96
+
97
+ ```ts
98
+ async function fetchToken({ sessionId }: JwtRequestContext = {}): Promise<string> {
99
+ // ask your backend for a token, and pass sessionId along when it is set
100
+ }
101
+ ```
102
+
103
+ `sessionId` is set for every request that targets an existing session and unset for session
104
+ creation. Keep returning the token that created the session until shortly before it expires.
105
+ Then mint a replacement bound to that session, which lets it act on the session and create
106
+ nothing else:
107
+
108
+ ```ts
109
+ body: JSON.stringify({
110
+ authorization_details: [
111
+ {
112
+ type: "session",
113
+ resources: { models: { match: ["my-model"] }, sessions: { bind: [sessionId] } },
114
+ },
115
+ ],
116
+ }),
117
+ ```
118
+
119
+ Reactor only binds a session the API key owns, so the question your backend must answer is
120
+ whether *this* browser may hold a token for *that* session. The simplest answer is to create the
121
+ session on the backend and hand the browser `{ jwt, sessionId }` to adopt with
122
+ `connect(jwt, { sessionId })`: the backend then knows the owner. When the browser creates the
123
+ session itself, have it register the session id as soon as the SDK first names it to the
124
+ resolver, which is right after creation, with the token that created it; check that token
125
+ against `GET /sessions/{id}` (Reactor answers only for a token bound to it), and remember the
126
+ session for that browser. Registering only after `connect()` returns is too late when a slow
127
+ model keeps the connect open past the token's expiry. The bundled examples do exactly that in
128
+ `examples/shared/token-server.ts`.
129
+
81
130
  ## Events
82
131
 
83
132
  `on(event, handler)` / `off(event, handler)` / `once(event, handler)`. The ones you'll reach
@@ -109,9 +158,14 @@ matching `schemaReceived`/`capabilitiesReceived` events. See
109
158
 
110
159
  ```ts
111
160
  const clip = await reactor.requestClip(10); // last 10 seconds
112
- await reactor.downloadClipAsFile(clip, "clip.mp4", { jwt: await fetchToken() });
161
+ await reactor.downloadClipAsFile(clip, "clip.mp4", { jwt: reactor.getJwtResolver() });
113
162
  ```
114
163
 
164
+ `jwt` takes a token or a resolver. A resolver is called before every poll of the manifest with
165
+ `{ sessionId: clip.sessionId }`, so a clip that takes a while to become ready still downloads
166
+ after the token that created the session has expired. The same goes for `getJwt` on
167
+ `<ClipPlayer>`, `<ClipDownloadButton>` and `useClipDownload`.
168
+
115
169
  `requestClip()`/`requestRecording()`/`downloadClipAsFile()` live directly on `Reactor`, and the
116
170
  same three are bound on the React store. For a preview or download button instead, drop in
117
171
  `<ClipPlayer>`/`<ClipDownloadButton>`:
@@ -119,8 +173,8 @@ same three are bound on the React store. For a preview or download button instea
119
173
  ```tsx
120
174
  import { ClipPlayer, ClipDownloadButton } from "@reactor-team/js-sdk";
121
175
 
122
- <ClipPlayer clip={clip} getJwt={() => fetchToken()} />
123
- <ClipDownloadButton clip={clip} getJwt={() => fetchToken()} filename="clip.mp4" />
176
+ <ClipPlayer clip={clip} getJwt={fetchToken} />
177
+ <ClipDownloadButton clip={clip} getJwt={fetchToken} filename="clip.mp4" />
124
178
  ```
125
179
 
126
180
  Full API, playback details, and the `useClipDownload` hook: [Recordings](https://docs.reactor.inc/concepts/recordings).
@@ -160,16 +214,13 @@ try {
160
214
  ## React
161
215
 
162
216
  ```tsx
163
- import { useCallback } from "react";
164
217
  import { ReactorProvider, ReactorView, useReactor } from "@reactor-team/js-sdk";
165
218
 
166
219
  function App() {
167
- // Stable across renders — see the note on ReactorProvider below for why
168
- // this matters.
169
- const jwt = useCallback(() => fetchToken(), []);
170
-
220
+ // A module-level fetchToken is stable across renders — see the note on
221
+ // ReactorProvider below for why this matters.
171
222
  return (
172
- <ReactorProvider modelName="my-model" jwtToken={jwt}>
223
+ <ReactorProvider modelName="my-model" jwtToken={fetchToken}>
173
224
  <Status />
174
225
  </ReactorProvider>
175
226
  );
@@ -225,8 +276,9 @@ you want to stay model-agnostic. See [Typed model SDKs](https://docs.reactor.inc
225
276
  ```bash
226
277
  mise run install:js # npm install
227
278
  mise run lint:js # eslint + tsc --noEmit
228
- mise run build:js # tsup -> dist/, then copies reactor-wasm's pkg/ into dist/wasm
279
+ mise run build:js # tsup -> dist/, then copies reactor-wasm's pkg/ into dist/wasm, binary inlined
229
280
  mise run test:js # vitest — pure-JS unit tests against a mocked ReactorClient, no wasm build needed
281
+ mise run test:js:consumer-tests # the packed SDK in real Vite/Next.js apps, in a real browser — see consumer-tests/README.md
230
282
  ```
231
283
 
232
284
  `build:js` fails fast with a clear message if `crates/reactor-wasm/pkg`
package/dist/index.cjs CHANGED
@@ -129,7 +129,7 @@ var ReactorError = class extends Error {
129
129
  * compatibility — prefer `timestamp_ms`. */
130
130
  timestamp;
131
131
  constructor(message, options = {}) {
132
- super(message);
132
+ super(message, options.cause === void 0 ? void 0 : { cause: options.cause });
133
133
  this.name = "ReactorError";
134
134
  this.code = options.code ?? new.target.code;
135
135
  this.recoverable = options.recoverable ?? false;
@@ -230,7 +230,10 @@ function toReactorError(cause) {
230
230
  status: payload.status,
231
231
  operation: payload.operation,
232
232
  retry_after_ms: payload.retry_after_ms,
233
- timestamp_ms: payload.timestamp_ms
233
+ timestamp_ms: payload.timestamp_ms,
234
+ // A thrown JS error (a failed wasm load, say) keeps its stack and its own
235
+ // `cause` reachable; reactor-core's plain payload objects have neither.
236
+ cause: cause instanceof Error ? cause : void 0
234
237
  });
235
238
  }
236
239
 
@@ -379,14 +382,185 @@ function toPublicClip(clip) {
379
382
  }
380
383
 
381
384
  // src/internal/stats.ts
382
- var STATS_INTERVAL_MS = 2e3;
383
- function createRTCStatsExtractor() {
385
+ var LOCAL_STATS_INTERVAL_MS = 2e3;
386
+ var RUNTIME_REPORT_INTERVAL_MS = 5e3;
387
+ function pollPeerStats(client, intervalMs, onReport) {
388
+ let stopped = false;
389
+ let reading = false;
390
+ const handle = setInterval(() => {
391
+ if (reading) {
392
+ return;
393
+ }
394
+ const peerConnection = client.getPeerConnection();
395
+ if (!peerConnection) {
396
+ return;
397
+ }
398
+ reading = true;
399
+ void peerConnection.getStats().then(
400
+ (report) => {
401
+ if (stopped) {
402
+ return;
403
+ }
404
+ try {
405
+ onReport(report);
406
+ } catch (error) {
407
+ console.error("[Reactor] stats report handler threw:", error);
408
+ }
409
+ },
410
+ () => {
411
+ }
412
+ ).finally(() => {
413
+ reading = false;
414
+ });
415
+ }, intervalMs);
416
+ return () => {
417
+ stopped = true;
418
+ clearInterval(handle);
419
+ };
420
+ }
421
+ function roundMs(ms) {
422
+ return Math.round(ms * 1e3) / 1e3;
423
+ }
424
+ function secondsToMs(seconds) {
425
+ return roundMs(seconds * 1e3);
426
+ }
427
+ var WIRE_CODECS = {
428
+ video: /* @__PURE__ */ new Set(["vp8", "vp9", "av1", "h264", "h265"]),
429
+ audio: /* @__PURE__ */ new Set(["opus"])
430
+ };
431
+ function createTrackStatsExtractor() {
432
+ const lastBytes = /* @__PURE__ */ new Map();
433
+ return (report, tracks, pausedTracks) => {
434
+ const reportWithLookup = report;
435
+ const stats = [];
436
+ const seenStreams = /* @__PURE__ */ new Set();
437
+ const remoteInbound = /* @__PURE__ */ new Map();
438
+ report.forEach((stat) => {
439
+ if (stat.type === "remote-inbound-rtp" && stat.localId !== void 0) {
440
+ remoteInbound.set(stat.localId, stat);
441
+ }
442
+ });
443
+ report.forEach((stat) => {
444
+ const inbound = stat.type === "inbound-rtp";
445
+ if (!inbound && stat.type !== "outbound-rtp" || stat.mid === void 0) {
446
+ return;
447
+ }
448
+ const direction = inbound ? "recvonly" : "sendonly";
449
+ const streamKey = `${direction}:${stat.mid}`;
450
+ if (seenStreams.has(streamKey)) {
451
+ return;
452
+ }
453
+ const track = tracks.find((entry) => entry.mid === stat.mid && entry.direction === direction);
454
+ const codecStat = stat.codecId !== void 0 ? reportWithLookup.get(stat.codecId) : void 0;
455
+ const codec = codecStat?.mimeType?.split("/")[1]?.toLowerCase();
456
+ if (track === void 0 || codec === void 0 || !WIRE_CODECS[track.kind].has(codec)) {
457
+ return;
458
+ }
459
+ seenStreams.add(streamKey);
460
+ const metrics = {};
461
+ const put = (key, value) => {
462
+ if (value !== void 0) {
463
+ metrics[key] = value;
464
+ }
465
+ };
466
+ const bytes = inbound ? stat.bytesReceived : stat.bytesSent;
467
+ if (bytes !== void 0) {
468
+ const previous = lastBytes.get(stat.id);
469
+ if (previous !== void 0 && stat.timestamp > previous.timestamp && bytes >= previous.bytes) {
470
+ put("bitrate_bps", Math.round((bytes - previous.bytes) * 8 * 1e3 / (stat.timestamp - previous.timestamp)));
471
+ }
472
+ lastBytes.set(stat.id, { bytes, timestamp: stat.timestamp });
473
+ }
474
+ const keyframeRequests = stat.firCount !== void 0 || stat.pliCount !== void 0 ? (stat.firCount ?? 0) + (stat.pliCount ?? 0) : void 0;
475
+ if (inbound) {
476
+ put("packets_received", stat.packetsReceived);
477
+ put("packets_lost", stat.packetsLost);
478
+ put("jitter_ms", stat.jitter !== void 0 ? secondsToMs(stat.jitter) : void 0);
479
+ put("nack_count", stat.nackCount);
480
+ if (track.kind === "video") {
481
+ put("frames_per_second", stat.framesPerSecond);
482
+ put("frames_decoded", stat.framesDecoded);
483
+ put("frames_dropped", stat.framesDropped);
484
+ put("frame_width", stat.frameWidth);
485
+ put("frame_height", stat.frameHeight);
486
+ put("keyframe_requests", keyframeRequests);
487
+ } else {
488
+ put("concealed_samples", stat.concealedSamples);
489
+ put("total_samples_received", stat.totalSamplesReceived);
490
+ }
491
+ } else {
492
+ const remote = remoteInbound.get(stat.id);
493
+ put("packets_sent", stat.packetsSent);
494
+ put("retransmitted_packets_sent", stat.retransmittedPacketsSent);
495
+ put("nack_count", stat.nackCount);
496
+ put("packets_lost", remote?.packetsLost);
497
+ put("jitter_ms", remote?.jitter !== void 0 ? secondsToMs(remote.jitter) : void 0);
498
+ put("round_trip_time_ms", remote?.roundTripTime !== void 0 ? secondsToMs(remote.roundTripTime) : void 0);
499
+ if (track.kind === "video") {
500
+ put("frames_per_second", stat.framesPerSecond);
501
+ put("frames_encoded", stat.framesEncoded);
502
+ put("frame_width", stat.frameWidth);
503
+ put("frame_height", stat.frameHeight);
504
+ put("keyframe_requests", keyframeRequests);
505
+ }
506
+ }
507
+ stats.push({
508
+ timestamp: Date.now(),
509
+ trackName: track.name,
510
+ kind: track.kind,
511
+ direction,
512
+ codec,
513
+ paused: pausedTracks.includes(track.name),
514
+ metrics
515
+ });
516
+ });
517
+ return stats;
518
+ };
519
+ }
520
+ function toClientConnectionStat(report, timeToConnectMs) {
521
+ const pair = activeCandidatePair(report);
522
+ const metrics = {};
523
+ if (pair?.availableOutgoingBitrate !== void 0) {
524
+ metrics.available_outgoing_bitrate_bps = pair.availableOutgoingBitrate;
525
+ }
526
+ if (pair?.availableIncomingBitrate !== void 0) {
527
+ metrics.available_incoming_bitrate_bps = pair.availableIncomingBitrate;
528
+ }
529
+ if (pair?.currentRoundTripTime !== void 0) {
530
+ metrics.connection_rtt_ms = secondsToMs(pair.currentRoundTripTime);
531
+ }
532
+ if (timeToConnectMs !== void 0) {
533
+ metrics.time_to_connect_ms = roundMs(timeToConnectMs);
534
+ }
535
+ return { timestamp: Date.now(), metrics };
536
+ }
537
+ function activeCandidatePair(report) {
538
+ let namedByTransport;
539
+ let flaggedSelected;
540
+ let firstNominated;
541
+ report.forEach((stat) => {
542
+ if (stat.type === "transport" && stat.selectedCandidatePairId) {
543
+ namedByTransport ??= stat.selectedCandidatePairId;
544
+ }
545
+ if (stat.type === "candidate-pair" && stat.state === "succeeded") {
546
+ if (stat.selected) {
547
+ flaggedSelected ??= stat;
548
+ }
549
+ if (stat.nominated) {
550
+ firstNominated ??= stat;
551
+ }
552
+ }
553
+ });
554
+ const named = namedByTransport !== void 0 ? report.get(namedByTransport) : void 0;
555
+ const namedSucceeded = named?.state === "succeeded" ? named : void 0;
556
+ return namedSucceeded ?? flaggedSelected ?? firstNominated;
557
+ }
558
+ function createConnectionStatsExtractor() {
384
559
  let lastBytesReceived;
385
560
  let lastBytesSent;
386
561
  let lastCandPairTimestamp;
387
562
  let lastCandPairId;
388
563
  return (report) => {
389
- let candPairId;
390
564
  let rtt;
391
565
  let availableOutgoingBitrate;
392
566
  let availableIncomingBitrate;
@@ -397,40 +571,35 @@ function createRTCStatsExtractor() {
397
571
  let jitter;
398
572
  let packetLossRatio;
399
573
  let candidateType;
400
- const reportWithLookup = report;
401
- report.forEach((stat) => {
402
- if (candPairId === void 0 && stat.type === "candidate-pair" && stat.state === "succeeded" && stat.nominated) {
403
- candPairId = stat.id;
404
- if (stat.currentRoundTripTime !== void 0) {
405
- rtt = stat.currentRoundTripTime * 1e3;
406
- }
407
- if (stat.availableOutgoingBitrate !== void 0) {
408
- availableOutgoingBitrate = stat.availableOutgoingBitrate;
409
- }
410
- if (stat.availableIncomingBitrate !== void 0) {
411
- availableIncomingBitrate = stat.availableIncomingBitrate;
412
- }
413
- const localCandidate = stat.localCandidateId !== void 0 ? reportWithLookup.get(stat.localCandidateId) : void 0;
414
- if (localCandidate?.candidateType) {
415
- candidateType = localCandidate.candidateType;
416
- }
417
- const samePair = lastCandPairId === candPairId;
418
- const timeDiff = samePair && lastCandPairTimestamp !== void 0 ? stat.timestamp - lastCandPairTimestamp : 0;
419
- if (stat.bytesReceived !== void 0) {
420
- if (samePair && lastBytesReceived !== void 0 && timeDiff > 0) {
421
- incomingBitrate = (stat.bytesReceived - lastBytesReceived) * 8 / timeDiff * 1e3;
422
- }
423
- lastBytesReceived = stat.bytesReceived;
574
+ const pair = activeCandidatePair(report);
575
+ if (pair !== void 0) {
576
+ if (pair.currentRoundTripTime !== void 0) {
577
+ rtt = pair.currentRoundTripTime * 1e3;
578
+ }
579
+ availableOutgoingBitrate = pair.availableOutgoingBitrate;
580
+ availableIncomingBitrate = pair.availableIncomingBitrate;
581
+ const localCandidate = pair.localCandidateId !== void 0 ? report.get(pair.localCandidateId) : void 0;
582
+ if (localCandidate?.candidateType) {
583
+ candidateType = localCandidate.candidateType;
584
+ }
585
+ const samePair = lastCandPairId === pair.id;
586
+ const timeDiff = samePair && lastCandPairTimestamp !== void 0 ? pair.timestamp - lastCandPairTimestamp : 0;
587
+ if (pair.bytesReceived !== void 0) {
588
+ if (samePair && lastBytesReceived !== void 0 && timeDiff > 0) {
589
+ incomingBitrate = (pair.bytesReceived - lastBytesReceived) * 8 / timeDiff * 1e3;
424
590
  }
425
- if (stat.bytesSent !== void 0) {
426
- if (samePair && lastBytesSent !== void 0 && timeDiff > 0) {
427
- outgoingBitrate = (stat.bytesSent - lastBytesSent) * 8 / timeDiff * 1e3;
428
- }
429
- lastBytesSent = stat.bytesSent;
591
+ lastBytesReceived = pair.bytesReceived;
592
+ }
593
+ if (pair.bytesSent !== void 0) {
594
+ if (samePair && lastBytesSent !== void 0 && timeDiff > 0) {
595
+ outgoingBitrate = (pair.bytesSent - lastBytesSent) * 8 / timeDiff * 1e3;
430
596
  }
431
- lastCandPairTimestamp = stat.timestamp;
432
- lastCandPairId = candPairId;
597
+ lastBytesSent = pair.bytesSent;
433
598
  }
599
+ lastCandPairTimestamp = pair.timestamp;
600
+ lastCandPairId = pair.id;
601
+ }
602
+ report.forEach((stat) => {
434
603
  if (videoInboundRtpId === void 0 && stat.type === "inbound-rtp" && stat.kind === "video") {
435
604
  videoInboundRtpId = stat.id;
436
605
  if (stat.framesPerSecond !== void 0) {
@@ -465,27 +634,27 @@ function loadReactorWasm() {
465
634
  if (!modulePromise) {
466
635
  modulePromise = importWasmModule().catch((cause) => {
467
636
  modulePromise = null;
468
- throw new Error(
469
- "reactor-wasm failed to load. Run `mise run build:wasm` (or, from a published install, reinstall the package) and try again.",
470
- { cause }
471
- );
637
+ throw new Error(`reactor-wasm failed to load: ${describeCause(cause)}`, { cause });
472
638
  });
473
639
  }
474
640
  return modulePromise;
475
641
  }
476
642
  async function importWasmModule() {
477
- const module2 = await import(
478
- /* @vite-ignore */
479
- "./wasm/reactor_wasm.js"
480
- );
643
+ const module2 = await import("./wasm/reactor_wasm.js");
481
644
  await module2.default();
482
645
  return module2;
483
646
  }
647
+ function describeCause(cause) {
648
+ if (cause instanceof Error) {
649
+ return cause.message ? `${cause.name}: ${cause.message}` : cause.name;
650
+ }
651
+ return String(cause);
652
+ }
484
653
 
485
654
  // package.json
486
655
  var package_default = {
487
656
  name: "@reactor-team/js-sdk",
488
- version: "3.0.2",
657
+ version: "3.2.0",
489
658
  description: "Connect your JavaScript/TypeScript app to a live Reactor model in the browser.",
490
659
  license: "Apache-2.0",
491
660
  repository: {
@@ -545,6 +714,11 @@ var package_default = {
545
714
  }
546
715
  };
547
716
 
717
+ // src/internal/jwt-resolver.ts
718
+ async function resolveJwtSource(source, context) {
719
+ return typeof source === "function" ? source(context) : source;
720
+ }
721
+
548
722
  // src/recording.ts
549
723
  var RecordingError = class extends Error {
550
724
  constructor(code, reason) {
@@ -564,15 +738,16 @@ async function fetchPlaylist(playlistUrl, options = {}) {
564
738
  const startedPollingAt = Date.now();
565
739
  const deadlineMs = hasDeadline ? Math.max(options.predictedReadyAtMs ?? startedPollingAt, startedPollingAt) + options.slackMs : void 0;
566
740
  const maxRetries = typeof options.maxRetries === "number" ? options.maxRetries : void 0;
567
- const init = {};
568
- if (options.signal) {
569
- init.signal = options.signal;
570
- }
571
- if (options.jwt) {
572
- init.headers = { Authorization: `Bearer ${options.jwt}` };
573
- }
574
741
  let attempt = 0;
575
742
  while (true) {
743
+ const init = {};
744
+ if (options.signal) {
745
+ init.signal = options.signal;
746
+ }
747
+ const jwt = await resolveManifestJwt(options);
748
+ if (jwt) {
749
+ init.headers = { Authorization: `Bearer ${jwt}` };
750
+ }
576
751
  let response;
577
752
  try {
578
753
  response = await fetch(playlistUrl, init);
@@ -675,7 +850,10 @@ function absolutizeManifestUrls(manifestBody, playlistUrl) {
675
850
  return out.join(eol);
676
851
  }
677
852
  async function downloadClipAsFile(clip, filename = "reactor-clip.mp4", options = {}) {
678
- const playlistOptions = { predictedReadyAtMs: clip.predictedReadyAtMs };
853
+ const playlistOptions = {
854
+ predictedReadyAtMs: clip.predictedReadyAtMs,
855
+ sessionId: clip.sessionId
856
+ };
679
857
  if (options.signal) {
680
858
  playlistOptions.signal = options.signal;
681
859
  }
@@ -913,6 +1091,27 @@ function parseRetryAfter(header, fallbackMs) {
913
1091
  }
914
1092
  return fallbackMs;
915
1093
  }
1094
+ async function resolveManifestJwt(options) {
1095
+ if (options.jwt === void 0) {
1096
+ return void 0;
1097
+ }
1098
+ const context = options.sessionId === void 0 ? {} : { sessionId: options.sessionId };
1099
+ return abortable(resolveJwtSource(options.jwt, context), options.signal);
1100
+ }
1101
+ function abortable(promise, signal) {
1102
+ if (!signal) {
1103
+ return promise;
1104
+ }
1105
+ return new Promise((resolve, reject) => {
1106
+ const onAbort = () => reject(new DOMException("Aborted", "AbortError"));
1107
+ if (signal.aborted) {
1108
+ onAbort();
1109
+ } else {
1110
+ signal.addEventListener("abort", onAbort, { once: true });
1111
+ }
1112
+ void promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort));
1113
+ });
1114
+ }
916
1115
  function sleep(ms, signal) {
917
1116
  return new Promise((resolve, reject) => {
918
1117
  if (signal?.aborted) {
@@ -961,11 +1160,14 @@ var Reactor = class {
961
1160
  capabilities;
962
1161
  stats;
963
1162
  connectionTimings;
964
- statsPollHandle;
965
- /** Bumped on every `startStatsPolling()`/`stopStatsPolling()` call — lets an
966
- * in-flight `getStats()` recognize it's stale once it resolves, even if
967
- * `this.client` hasn't changed in the meantime. */
968
- statsPollGeneration = 0;
1163
+ /** The stop functions of the running stats pollers — see `pollPeerStats()`. */
1164
+ stopStatsPollers = [];
1165
+ /** Whether this connection has already reported its time to connect —
1166
+ * a one-time fact, sent on the first client-stats report that carries it
1167
+ * and omitted on every one after. Set only once a batch actually went out
1168
+ * with it, so a batch sent before the timings exist doesn't use it up.
1169
+ * Reset per `startStatsPolling()` call, i.e. per connect()/reconnect(). */
1170
+ hasSentConnectTime = false;
969
1171
  /** Set on the "connecting" status transition, cleared once `connectionTimings`
970
1172
  * is finalized on "ready" — see `handleStatusChanged()`. */
971
1173
  connectStartTime;
@@ -1494,7 +1696,7 @@ var Reactor = class {
1494
1696
  getLastError() {
1495
1697
  return this._lastError;
1496
1698
  }
1497
- /** The most recent WebRTC connection stats, polled every `STATS_INTERVAL_MS`
1699
+ /** The most recent WebRTC connection stats, polled every `LOCAL_STATS_INTERVAL_MS`
1498
1700
  * while "ready" — see `statsUpdate`. `undefined` before the first sample. */
1499
1701
  getStats() {
1500
1702
  return this.stats;
@@ -1644,31 +1846,57 @@ var Reactor = class {
1644
1846
  this.stopStatsPolling();
1645
1847
  }
1646
1848
  }
1849
+ /** Starts both stats pollers: the local one updates `getStats()` and emits
1850
+ * `statsUpdate`, the runtime one sends a client-stats batch. Each owns the
1851
+ * extractor it computes bitrates with, so a bitrate covers its own
1852
+ * poller's interval. */
1647
1853
  startStatsPolling(client) {
1648
1854
  this.stopStatsPolling();
1649
- const generation = ++this.statsPollGeneration;
1650
- const extractStats = createRTCStatsExtractor();
1651
- this.statsPollHandle = setInterval(() => {
1652
- const peerConnection = client.getPeerConnection();
1653
- if (!peerConnection) {
1654
- return;
1655
- }
1656
- peerConnection.getStats().then((report) => {
1657
- if (generation !== this.statsPollGeneration) {
1658
- return;
1659
- }
1660
- this.stats = { ...extractStats(report), connectionTimings: this.connectionTimings };
1855
+ const extractConnectionStats = createConnectionStatsExtractor();
1856
+ const extractTrackStats = createTrackStatsExtractor();
1857
+ this.hasSentConnectTime = false;
1858
+ this.stopStatsPollers = [
1859
+ pollPeerStats(client, LOCAL_STATS_INTERVAL_MS, (report) => {
1860
+ this.stats = { ...extractConnectionStats(report), connectionTimings: this.connectionTimings };
1661
1861
  this.emitter.emit("statsUpdate", this.stats);
1662
- }).catch(() => {
1663
- });
1664
- }, STATS_INTERVAL_MS);
1862
+ }),
1863
+ pollPeerStats(client, RUNTIME_REPORT_INTERVAL_MS, (report) => {
1864
+ this.reportClientStats(client, report, extractTrackStats);
1865
+ })
1866
+ ];
1867
+ }
1868
+ /** Report one quality batch to the runtime: a reading per negotiated
1869
+ * track — audio and video, sent and received — see
1870
+ * `createTrackStatsExtractor`, and the connection-wide reading — see
1871
+ * `toClientConnectionStat`. The connection reading goes even while no
1872
+ * track has one yet (none negotiated onto a named track, or no codec
1873
+ * reported yet), so the runtime gets the bandwidth estimate, the
1874
+ * round-trip time and the time to connect without waiting on the tracks.
1875
+ * Skipped only when there is nothing at all to say; one is due again in
1876
+ * `RUNTIME_REPORT_INTERVAL_MS`. The time to connect goes on the first batch
1877
+ * actually sent for this connection — see `hasSentConnectTime`.
1878
+ * `sendClientStats` throws synchronously on a closing connection; caught
1879
+ * here for the same reason `getStats()`'s rejection is above. */
1880
+ reportClientStats(client, report, extractTrackStats) {
1881
+ const trackStats = extractTrackStats(report, this.trackMapping(), this.pausedTracks());
1882
+ const timeToConnectMs = this.hasSentConnectTime ? void 0 : this.connectionTimings?.totalMs;
1883
+ const connectionStat = toClientConnectionStat(report, timeToConnectMs);
1884
+ if (trackStats.length === 0 && Object.keys(connectionStat.metrics).length === 0) {
1885
+ return;
1886
+ }
1887
+ try {
1888
+ client.sendClientStats(trackStats, connectionStat);
1889
+ if (timeToConnectMs !== void 0) {
1890
+ this.hasSentConnectTime = true;
1891
+ }
1892
+ } catch {
1893
+ }
1665
1894
  }
1666
1895
  stopStatsPolling() {
1667
- this.statsPollGeneration += 1;
1668
- if (this.statsPollHandle !== void 0) {
1669
- clearInterval(this.statsPollHandle);
1670
- this.statsPollHandle = void 0;
1896
+ for (const stop of this.stopStatsPollers) {
1897
+ stop();
1671
1898
  }
1899
+ this.stopStatsPollers = [];
1672
1900
  this.stats = void 0;
1673
1901
  }
1674
1902
  /** Called on every `disconnect()` and on `[Symbol.dispose]`. Leaves
@@ -2348,11 +2576,6 @@ function describeMediaError(error) {
2348
2576
  return error?.message ? `${message} (${error.message})` : message;
2349
2577
  }
2350
2578
 
2351
- // src/internal/jwt-resolver.ts
2352
- async function resolveJwtSource(source) {
2353
- return typeof source === "function" ? source() : source;
2354
- }
2355
-
2356
2579
  // src/react/ClipPlayer.tsx
2357
2580
  var import_jsx_runtime4 = require("react/jsx-runtime");
2358
2581
  function ClipPlayer({
@@ -2402,21 +2625,17 @@ function ClipPlayer({
2402
2625
  const setup = async () => {
2403
2626
  try {
2404
2627
  setPhase({ kind: "waiting" });
2405
- const explicit = getJwtRef.current;
2406
- const fallback = storeRef.current?.getState().internal.reactor.getJwtResolver();
2407
- const jwt = explicit ? await explicit() : fallback !== void 0 ? await resolveJwtSource(fallback) : void 0;
2408
- if (cancelled) {
2409
- return;
2410
- }
2628
+ const source = () => getJwtRef.current ?? storeRef.current?.getState().internal.reactor.getJwtResolver();
2411
2629
  const playlistOptions = {
2412
2630
  predictedReadyAtMs: clip.predictedReadyAtMs,
2631
+ sessionId: clip.sessionId,
2413
2632
  signal: abort.signal
2414
2633
  };
2415
2634
  if (slackMsRef.current !== void 0) {
2416
2635
  playlistOptions.slackMs = slackMsRef.current;
2417
2636
  }
2418
- if (jwt !== void 0) {
2419
- playlistOptions.jwt = jwt;
2637
+ if (source() !== void 0) {
2638
+ playlistOptions.jwt = (context) => resolveJwtSource(source() ?? "", context);
2420
2639
  }
2421
2640
  const body = await fetchPlaylist(clip.playlistUrl, playlistOptions);
2422
2641
  if (cancelled) {
@@ -2562,15 +2781,13 @@ function useClipDownload(clip, options = {}) {
2562
2781
  abortRef.current = abort;
2563
2782
  setState({ kind: "downloading", fetched: 0, total: 0 });
2564
2783
  try {
2565
- const explicit = getJwtRef.current;
2566
- const fallback = storeRef.current?.getState().internal.reactor.getJwtResolver();
2567
- const jwt = explicit ? await explicit() : fallback !== void 0 ? await resolveJwtSource(fallback) : void 0;
2784
+ const source = () => getJwtRef.current ?? storeRef.current?.getState().internal.reactor.getJwtResolver();
2568
2785
  const downloadOptions = {
2569
2786
  signal: abort.signal,
2570
2787
  onProgress: ({ fetched, total }) => setState({ kind: "downloading", fetched, total })
2571
2788
  };
2572
- if (jwt !== void 0) {
2573
- downloadOptions.jwt = jwt;
2789
+ if (source() !== void 0) {
2790
+ downloadOptions.jwt = (context) => resolveJwtSource(source() ?? "", context);
2574
2791
  }
2575
2792
  const blob = await downloadClipAsFile(clipRef.current, filenameRef.current, downloadOptions);
2576
2793
  setState({ kind: "idle" });