@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/dist/index.js CHANGED
@@ -56,7 +56,7 @@ var ReactorError = class extends Error {
56
56
  * compatibility — prefer `timestamp_ms`. */
57
57
  timestamp;
58
58
  constructor(message, options = {}) {
59
- super(message);
59
+ super(message, options.cause === void 0 ? void 0 : { cause: options.cause });
60
60
  this.name = "ReactorError";
61
61
  this.code = options.code ?? new.target.code;
62
62
  this.recoverable = options.recoverable ?? false;
@@ -157,7 +157,10 @@ function toReactorError(cause) {
157
157
  status: payload.status,
158
158
  operation: payload.operation,
159
159
  retry_after_ms: payload.retry_after_ms,
160
- timestamp_ms: payload.timestamp_ms
160
+ timestamp_ms: payload.timestamp_ms,
161
+ // A thrown JS error (a failed wasm load, say) keeps its stack and its own
162
+ // `cause` reachable; reactor-core's plain payload objects have neither.
163
+ cause: cause instanceof Error ? cause : void 0
161
164
  });
162
165
  }
163
166
 
@@ -306,14 +309,185 @@ function toPublicClip(clip) {
306
309
  }
307
310
 
308
311
  // src/internal/stats.ts
309
- var STATS_INTERVAL_MS = 2e3;
310
- function createRTCStatsExtractor() {
312
+ var LOCAL_STATS_INTERVAL_MS = 2e3;
313
+ var RUNTIME_REPORT_INTERVAL_MS = 5e3;
314
+ function pollPeerStats(client, intervalMs, onReport) {
315
+ let stopped = false;
316
+ let reading = false;
317
+ const handle = setInterval(() => {
318
+ if (reading) {
319
+ return;
320
+ }
321
+ const peerConnection = client.getPeerConnection();
322
+ if (!peerConnection) {
323
+ return;
324
+ }
325
+ reading = true;
326
+ void peerConnection.getStats().then(
327
+ (report) => {
328
+ if (stopped) {
329
+ return;
330
+ }
331
+ try {
332
+ onReport(report);
333
+ } catch (error) {
334
+ console.error("[Reactor] stats report handler threw:", error);
335
+ }
336
+ },
337
+ () => {
338
+ }
339
+ ).finally(() => {
340
+ reading = false;
341
+ });
342
+ }, intervalMs);
343
+ return () => {
344
+ stopped = true;
345
+ clearInterval(handle);
346
+ };
347
+ }
348
+ function roundMs(ms) {
349
+ return Math.round(ms * 1e3) / 1e3;
350
+ }
351
+ function secondsToMs(seconds) {
352
+ return roundMs(seconds * 1e3);
353
+ }
354
+ var WIRE_CODECS = {
355
+ video: /* @__PURE__ */ new Set(["vp8", "vp9", "av1", "h264", "h265"]),
356
+ audio: /* @__PURE__ */ new Set(["opus"])
357
+ };
358
+ function createTrackStatsExtractor() {
359
+ const lastBytes = /* @__PURE__ */ new Map();
360
+ return (report, tracks, pausedTracks) => {
361
+ const reportWithLookup = report;
362
+ const stats = [];
363
+ const seenStreams = /* @__PURE__ */ new Set();
364
+ const remoteInbound = /* @__PURE__ */ new Map();
365
+ report.forEach((stat) => {
366
+ if (stat.type === "remote-inbound-rtp" && stat.localId !== void 0) {
367
+ remoteInbound.set(stat.localId, stat);
368
+ }
369
+ });
370
+ report.forEach((stat) => {
371
+ const inbound = stat.type === "inbound-rtp";
372
+ if (!inbound && stat.type !== "outbound-rtp" || stat.mid === void 0) {
373
+ return;
374
+ }
375
+ const direction = inbound ? "recvonly" : "sendonly";
376
+ const streamKey = `${direction}:${stat.mid}`;
377
+ if (seenStreams.has(streamKey)) {
378
+ return;
379
+ }
380
+ const track = tracks.find((entry) => entry.mid === stat.mid && entry.direction === direction);
381
+ const codecStat = stat.codecId !== void 0 ? reportWithLookup.get(stat.codecId) : void 0;
382
+ const codec = codecStat?.mimeType?.split("/")[1]?.toLowerCase();
383
+ if (track === void 0 || codec === void 0 || !WIRE_CODECS[track.kind].has(codec)) {
384
+ return;
385
+ }
386
+ seenStreams.add(streamKey);
387
+ const metrics = {};
388
+ const put = (key, value) => {
389
+ if (value !== void 0) {
390
+ metrics[key] = value;
391
+ }
392
+ };
393
+ const bytes = inbound ? stat.bytesReceived : stat.bytesSent;
394
+ if (bytes !== void 0) {
395
+ const previous = lastBytes.get(stat.id);
396
+ if (previous !== void 0 && stat.timestamp > previous.timestamp && bytes >= previous.bytes) {
397
+ put("bitrate_bps", Math.round((bytes - previous.bytes) * 8 * 1e3 / (stat.timestamp - previous.timestamp)));
398
+ }
399
+ lastBytes.set(stat.id, { bytes, timestamp: stat.timestamp });
400
+ }
401
+ const keyframeRequests = stat.firCount !== void 0 || stat.pliCount !== void 0 ? (stat.firCount ?? 0) + (stat.pliCount ?? 0) : void 0;
402
+ if (inbound) {
403
+ put("packets_received", stat.packetsReceived);
404
+ put("packets_lost", stat.packetsLost);
405
+ put("jitter_ms", stat.jitter !== void 0 ? secondsToMs(stat.jitter) : void 0);
406
+ put("nack_count", stat.nackCount);
407
+ if (track.kind === "video") {
408
+ put("frames_per_second", stat.framesPerSecond);
409
+ put("frames_decoded", stat.framesDecoded);
410
+ put("frames_dropped", stat.framesDropped);
411
+ put("frame_width", stat.frameWidth);
412
+ put("frame_height", stat.frameHeight);
413
+ put("keyframe_requests", keyframeRequests);
414
+ } else {
415
+ put("concealed_samples", stat.concealedSamples);
416
+ put("total_samples_received", stat.totalSamplesReceived);
417
+ }
418
+ } else {
419
+ const remote = remoteInbound.get(stat.id);
420
+ put("packets_sent", stat.packetsSent);
421
+ put("retransmitted_packets_sent", stat.retransmittedPacketsSent);
422
+ put("nack_count", stat.nackCount);
423
+ put("packets_lost", remote?.packetsLost);
424
+ put("jitter_ms", remote?.jitter !== void 0 ? secondsToMs(remote.jitter) : void 0);
425
+ put("round_trip_time_ms", remote?.roundTripTime !== void 0 ? secondsToMs(remote.roundTripTime) : void 0);
426
+ if (track.kind === "video") {
427
+ put("frames_per_second", stat.framesPerSecond);
428
+ put("frames_encoded", stat.framesEncoded);
429
+ put("frame_width", stat.frameWidth);
430
+ put("frame_height", stat.frameHeight);
431
+ put("keyframe_requests", keyframeRequests);
432
+ }
433
+ }
434
+ stats.push({
435
+ timestamp: Date.now(),
436
+ trackName: track.name,
437
+ kind: track.kind,
438
+ direction,
439
+ codec,
440
+ paused: pausedTracks.includes(track.name),
441
+ metrics
442
+ });
443
+ });
444
+ return stats;
445
+ };
446
+ }
447
+ function toClientConnectionStat(report, timeToConnectMs) {
448
+ const pair = activeCandidatePair(report);
449
+ const metrics = {};
450
+ if (pair?.availableOutgoingBitrate !== void 0) {
451
+ metrics.available_outgoing_bitrate_bps = pair.availableOutgoingBitrate;
452
+ }
453
+ if (pair?.availableIncomingBitrate !== void 0) {
454
+ metrics.available_incoming_bitrate_bps = pair.availableIncomingBitrate;
455
+ }
456
+ if (pair?.currentRoundTripTime !== void 0) {
457
+ metrics.connection_rtt_ms = secondsToMs(pair.currentRoundTripTime);
458
+ }
459
+ if (timeToConnectMs !== void 0) {
460
+ metrics.time_to_connect_ms = roundMs(timeToConnectMs);
461
+ }
462
+ return { timestamp: Date.now(), metrics };
463
+ }
464
+ function activeCandidatePair(report) {
465
+ let namedByTransport;
466
+ let flaggedSelected;
467
+ let firstNominated;
468
+ report.forEach((stat) => {
469
+ if (stat.type === "transport" && stat.selectedCandidatePairId) {
470
+ namedByTransport ??= stat.selectedCandidatePairId;
471
+ }
472
+ if (stat.type === "candidate-pair" && stat.state === "succeeded") {
473
+ if (stat.selected) {
474
+ flaggedSelected ??= stat;
475
+ }
476
+ if (stat.nominated) {
477
+ firstNominated ??= stat;
478
+ }
479
+ }
480
+ });
481
+ const named = namedByTransport !== void 0 ? report.get(namedByTransport) : void 0;
482
+ const namedSucceeded = named?.state === "succeeded" ? named : void 0;
483
+ return namedSucceeded ?? flaggedSelected ?? firstNominated;
484
+ }
485
+ function createConnectionStatsExtractor() {
311
486
  let lastBytesReceived;
312
487
  let lastBytesSent;
313
488
  let lastCandPairTimestamp;
314
489
  let lastCandPairId;
315
490
  return (report) => {
316
- let candPairId;
317
491
  let rtt;
318
492
  let availableOutgoingBitrate;
319
493
  let availableIncomingBitrate;
@@ -324,40 +498,35 @@ function createRTCStatsExtractor() {
324
498
  let jitter;
325
499
  let packetLossRatio;
326
500
  let candidateType;
327
- const reportWithLookup = report;
328
- report.forEach((stat) => {
329
- if (candPairId === void 0 && stat.type === "candidate-pair" && stat.state === "succeeded" && stat.nominated) {
330
- candPairId = stat.id;
331
- if (stat.currentRoundTripTime !== void 0) {
332
- rtt = stat.currentRoundTripTime * 1e3;
333
- }
334
- if (stat.availableOutgoingBitrate !== void 0) {
335
- availableOutgoingBitrate = stat.availableOutgoingBitrate;
336
- }
337
- if (stat.availableIncomingBitrate !== void 0) {
338
- availableIncomingBitrate = stat.availableIncomingBitrate;
339
- }
340
- const localCandidate = stat.localCandidateId !== void 0 ? reportWithLookup.get(stat.localCandidateId) : void 0;
341
- if (localCandidate?.candidateType) {
342
- candidateType = localCandidate.candidateType;
343
- }
344
- const samePair = lastCandPairId === candPairId;
345
- const timeDiff = samePair && lastCandPairTimestamp !== void 0 ? stat.timestamp - lastCandPairTimestamp : 0;
346
- if (stat.bytesReceived !== void 0) {
347
- if (samePair && lastBytesReceived !== void 0 && timeDiff > 0) {
348
- incomingBitrate = (stat.bytesReceived - lastBytesReceived) * 8 / timeDiff * 1e3;
349
- }
350
- lastBytesReceived = stat.bytesReceived;
501
+ const pair = activeCandidatePair(report);
502
+ if (pair !== void 0) {
503
+ if (pair.currentRoundTripTime !== void 0) {
504
+ rtt = pair.currentRoundTripTime * 1e3;
505
+ }
506
+ availableOutgoingBitrate = pair.availableOutgoingBitrate;
507
+ availableIncomingBitrate = pair.availableIncomingBitrate;
508
+ const localCandidate = pair.localCandidateId !== void 0 ? report.get(pair.localCandidateId) : void 0;
509
+ if (localCandidate?.candidateType) {
510
+ candidateType = localCandidate.candidateType;
511
+ }
512
+ const samePair = lastCandPairId === pair.id;
513
+ const timeDiff = samePair && lastCandPairTimestamp !== void 0 ? pair.timestamp - lastCandPairTimestamp : 0;
514
+ if (pair.bytesReceived !== void 0) {
515
+ if (samePair && lastBytesReceived !== void 0 && timeDiff > 0) {
516
+ incomingBitrate = (pair.bytesReceived - lastBytesReceived) * 8 / timeDiff * 1e3;
351
517
  }
352
- if (stat.bytesSent !== void 0) {
353
- if (samePair && lastBytesSent !== void 0 && timeDiff > 0) {
354
- outgoingBitrate = (stat.bytesSent - lastBytesSent) * 8 / timeDiff * 1e3;
355
- }
356
- lastBytesSent = stat.bytesSent;
518
+ lastBytesReceived = pair.bytesReceived;
519
+ }
520
+ if (pair.bytesSent !== void 0) {
521
+ if (samePair && lastBytesSent !== void 0 && timeDiff > 0) {
522
+ outgoingBitrate = (pair.bytesSent - lastBytesSent) * 8 / timeDiff * 1e3;
357
523
  }
358
- lastCandPairTimestamp = stat.timestamp;
359
- lastCandPairId = candPairId;
524
+ lastBytesSent = pair.bytesSent;
360
525
  }
526
+ lastCandPairTimestamp = pair.timestamp;
527
+ lastCandPairId = pair.id;
528
+ }
529
+ report.forEach((stat) => {
361
530
  if (videoInboundRtpId === void 0 && stat.type === "inbound-rtp" && stat.kind === "video") {
362
531
  videoInboundRtpId = stat.id;
363
532
  if (stat.framesPerSecond !== void 0) {
@@ -392,27 +561,27 @@ function loadReactorWasm() {
392
561
  if (!modulePromise) {
393
562
  modulePromise = importWasmModule().catch((cause) => {
394
563
  modulePromise = null;
395
- throw new Error(
396
- "reactor-wasm failed to load. Run `mise run build:wasm` (or, from a published install, reinstall the package) and try again.",
397
- { cause }
398
- );
564
+ throw new Error(`reactor-wasm failed to load: ${describeCause(cause)}`, { cause });
399
565
  });
400
566
  }
401
567
  return modulePromise;
402
568
  }
403
569
  async function importWasmModule() {
404
- const module = await import(
405
- /* @vite-ignore */
406
- "./wasm/reactor_wasm.js"
407
- );
570
+ const module = await import("./wasm/reactor_wasm.js");
408
571
  await module.default();
409
572
  return module;
410
573
  }
574
+ function describeCause(cause) {
575
+ if (cause instanceof Error) {
576
+ return cause.message ? `${cause.name}: ${cause.message}` : cause.name;
577
+ }
578
+ return String(cause);
579
+ }
411
580
 
412
581
  // package.json
413
582
  var package_default = {
414
583
  name: "@reactor-team/js-sdk",
415
- version: "3.0.2",
584
+ version: "3.2.0",
416
585
  description: "Connect your JavaScript/TypeScript app to a live Reactor model in the browser.",
417
586
  license: "Apache-2.0",
418
587
  repository: {
@@ -472,6 +641,11 @@ var package_default = {
472
641
  }
473
642
  };
474
643
 
644
+ // src/internal/jwt-resolver.ts
645
+ async function resolveJwtSource(source, context) {
646
+ return typeof source === "function" ? source(context) : source;
647
+ }
648
+
475
649
  // src/recording.ts
476
650
  var RecordingError = class extends Error {
477
651
  constructor(code, reason) {
@@ -491,15 +665,16 @@ async function fetchPlaylist(playlistUrl, options = {}) {
491
665
  const startedPollingAt = Date.now();
492
666
  const deadlineMs = hasDeadline ? Math.max(options.predictedReadyAtMs ?? startedPollingAt, startedPollingAt) + options.slackMs : void 0;
493
667
  const maxRetries = typeof options.maxRetries === "number" ? options.maxRetries : void 0;
494
- const init = {};
495
- if (options.signal) {
496
- init.signal = options.signal;
497
- }
498
- if (options.jwt) {
499
- init.headers = { Authorization: `Bearer ${options.jwt}` };
500
- }
501
668
  let attempt = 0;
502
669
  while (true) {
670
+ const init = {};
671
+ if (options.signal) {
672
+ init.signal = options.signal;
673
+ }
674
+ const jwt = await resolveManifestJwt(options);
675
+ if (jwt) {
676
+ init.headers = { Authorization: `Bearer ${jwt}` };
677
+ }
503
678
  let response;
504
679
  try {
505
680
  response = await fetch(playlistUrl, init);
@@ -602,7 +777,10 @@ function absolutizeManifestUrls(manifestBody, playlistUrl) {
602
777
  return out.join(eol);
603
778
  }
604
779
  async function downloadClipAsFile(clip, filename = "reactor-clip.mp4", options = {}) {
605
- const playlistOptions = { predictedReadyAtMs: clip.predictedReadyAtMs };
780
+ const playlistOptions = {
781
+ predictedReadyAtMs: clip.predictedReadyAtMs,
782
+ sessionId: clip.sessionId
783
+ };
606
784
  if (options.signal) {
607
785
  playlistOptions.signal = options.signal;
608
786
  }
@@ -840,6 +1018,27 @@ function parseRetryAfter(header, fallbackMs) {
840
1018
  }
841
1019
  return fallbackMs;
842
1020
  }
1021
+ async function resolveManifestJwt(options) {
1022
+ if (options.jwt === void 0) {
1023
+ return void 0;
1024
+ }
1025
+ const context = options.sessionId === void 0 ? {} : { sessionId: options.sessionId };
1026
+ return abortable(resolveJwtSource(options.jwt, context), options.signal);
1027
+ }
1028
+ function abortable(promise, signal) {
1029
+ if (!signal) {
1030
+ return promise;
1031
+ }
1032
+ return new Promise((resolve, reject) => {
1033
+ const onAbort = () => reject(new DOMException("Aborted", "AbortError"));
1034
+ if (signal.aborted) {
1035
+ onAbort();
1036
+ } else {
1037
+ signal.addEventListener("abort", onAbort, { once: true });
1038
+ }
1039
+ void promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort));
1040
+ });
1041
+ }
843
1042
  function sleep(ms, signal) {
844
1043
  return new Promise((resolve, reject) => {
845
1044
  if (signal?.aborted) {
@@ -888,11 +1087,14 @@ var Reactor = class {
888
1087
  capabilities;
889
1088
  stats;
890
1089
  connectionTimings;
891
- statsPollHandle;
892
- /** Bumped on every `startStatsPolling()`/`stopStatsPolling()` call — lets an
893
- * in-flight `getStats()` recognize it's stale once it resolves, even if
894
- * `this.client` hasn't changed in the meantime. */
895
- statsPollGeneration = 0;
1090
+ /** The stop functions of the running stats pollers — see `pollPeerStats()`. */
1091
+ stopStatsPollers = [];
1092
+ /** Whether this connection has already reported its time to connect —
1093
+ * a one-time fact, sent on the first client-stats report that carries it
1094
+ * and omitted on every one after. Set only once a batch actually went out
1095
+ * with it, so a batch sent before the timings exist doesn't use it up.
1096
+ * Reset per `startStatsPolling()` call, i.e. per connect()/reconnect(). */
1097
+ hasSentConnectTime = false;
896
1098
  /** Set on the "connecting" status transition, cleared once `connectionTimings`
897
1099
  * is finalized on "ready" — see `handleStatusChanged()`. */
898
1100
  connectStartTime;
@@ -1421,7 +1623,7 @@ var Reactor = class {
1421
1623
  getLastError() {
1422
1624
  return this._lastError;
1423
1625
  }
1424
- /** The most recent WebRTC connection stats, polled every `STATS_INTERVAL_MS`
1626
+ /** The most recent WebRTC connection stats, polled every `LOCAL_STATS_INTERVAL_MS`
1425
1627
  * while "ready" — see `statsUpdate`. `undefined` before the first sample. */
1426
1628
  getStats() {
1427
1629
  return this.stats;
@@ -1571,31 +1773,57 @@ var Reactor = class {
1571
1773
  this.stopStatsPolling();
1572
1774
  }
1573
1775
  }
1776
+ /** Starts both stats pollers: the local one updates `getStats()` and emits
1777
+ * `statsUpdate`, the runtime one sends a client-stats batch. Each owns the
1778
+ * extractor it computes bitrates with, so a bitrate covers its own
1779
+ * poller's interval. */
1574
1780
  startStatsPolling(client) {
1575
1781
  this.stopStatsPolling();
1576
- const generation = ++this.statsPollGeneration;
1577
- const extractStats = createRTCStatsExtractor();
1578
- this.statsPollHandle = setInterval(() => {
1579
- const peerConnection = client.getPeerConnection();
1580
- if (!peerConnection) {
1581
- return;
1582
- }
1583
- peerConnection.getStats().then((report) => {
1584
- if (generation !== this.statsPollGeneration) {
1585
- return;
1586
- }
1587
- this.stats = { ...extractStats(report), connectionTimings: this.connectionTimings };
1782
+ const extractConnectionStats = createConnectionStatsExtractor();
1783
+ const extractTrackStats = createTrackStatsExtractor();
1784
+ this.hasSentConnectTime = false;
1785
+ this.stopStatsPollers = [
1786
+ pollPeerStats(client, LOCAL_STATS_INTERVAL_MS, (report) => {
1787
+ this.stats = { ...extractConnectionStats(report), connectionTimings: this.connectionTimings };
1588
1788
  this.emitter.emit("statsUpdate", this.stats);
1589
- }).catch(() => {
1590
- });
1591
- }, STATS_INTERVAL_MS);
1789
+ }),
1790
+ pollPeerStats(client, RUNTIME_REPORT_INTERVAL_MS, (report) => {
1791
+ this.reportClientStats(client, report, extractTrackStats);
1792
+ })
1793
+ ];
1794
+ }
1795
+ /** Report one quality batch to the runtime: a reading per negotiated
1796
+ * track — audio and video, sent and received — see
1797
+ * `createTrackStatsExtractor`, and the connection-wide reading — see
1798
+ * `toClientConnectionStat`. The connection reading goes even while no
1799
+ * track has one yet (none negotiated onto a named track, or no codec
1800
+ * reported yet), so the runtime gets the bandwidth estimate, the
1801
+ * round-trip time and the time to connect without waiting on the tracks.
1802
+ * Skipped only when there is nothing at all to say; one is due again in
1803
+ * `RUNTIME_REPORT_INTERVAL_MS`. The time to connect goes on the first batch
1804
+ * actually sent for this connection — see `hasSentConnectTime`.
1805
+ * `sendClientStats` throws synchronously on a closing connection; caught
1806
+ * here for the same reason `getStats()`'s rejection is above. */
1807
+ reportClientStats(client, report, extractTrackStats) {
1808
+ const trackStats = extractTrackStats(report, this.trackMapping(), this.pausedTracks());
1809
+ const timeToConnectMs = this.hasSentConnectTime ? void 0 : this.connectionTimings?.totalMs;
1810
+ const connectionStat = toClientConnectionStat(report, timeToConnectMs);
1811
+ if (trackStats.length === 0 && Object.keys(connectionStat.metrics).length === 0) {
1812
+ return;
1813
+ }
1814
+ try {
1815
+ client.sendClientStats(trackStats, connectionStat);
1816
+ if (timeToConnectMs !== void 0) {
1817
+ this.hasSentConnectTime = true;
1818
+ }
1819
+ } catch {
1820
+ }
1592
1821
  }
1593
1822
  stopStatsPolling() {
1594
- this.statsPollGeneration += 1;
1595
- if (this.statsPollHandle !== void 0) {
1596
- clearInterval(this.statsPollHandle);
1597
- this.statsPollHandle = void 0;
1823
+ for (const stop of this.stopStatsPollers) {
1824
+ stop();
1598
1825
  }
1826
+ this.stopStatsPollers = [];
1599
1827
  this.stats = void 0;
1600
1828
  }
1601
1829
  /** Called on every `disconnect()` and on `[Symbol.dispose]`. Leaves
@@ -2275,11 +2503,6 @@ function describeMediaError(error) {
2275
2503
  return error?.message ? `${message} (${error.message})` : message;
2276
2504
  }
2277
2505
 
2278
- // src/internal/jwt-resolver.ts
2279
- async function resolveJwtSource(source) {
2280
- return typeof source === "function" ? source() : source;
2281
- }
2282
-
2283
2506
  // src/react/ClipPlayer.tsx
2284
2507
  import { jsx as jsx4, jsxs as jsxs2 } from "react/jsx-runtime";
2285
2508
  function ClipPlayer({
@@ -2329,21 +2552,17 @@ function ClipPlayer({
2329
2552
  const setup = async () => {
2330
2553
  try {
2331
2554
  setPhase({ kind: "waiting" });
2332
- const explicit = getJwtRef.current;
2333
- const fallback = storeRef.current?.getState().internal.reactor.getJwtResolver();
2334
- const jwt = explicit ? await explicit() : fallback !== void 0 ? await resolveJwtSource(fallback) : void 0;
2335
- if (cancelled) {
2336
- return;
2337
- }
2555
+ const source = () => getJwtRef.current ?? storeRef.current?.getState().internal.reactor.getJwtResolver();
2338
2556
  const playlistOptions = {
2339
2557
  predictedReadyAtMs: clip.predictedReadyAtMs,
2558
+ sessionId: clip.sessionId,
2340
2559
  signal: abort.signal
2341
2560
  };
2342
2561
  if (slackMsRef.current !== void 0) {
2343
2562
  playlistOptions.slackMs = slackMsRef.current;
2344
2563
  }
2345
- if (jwt !== void 0) {
2346
- playlistOptions.jwt = jwt;
2564
+ if (source() !== void 0) {
2565
+ playlistOptions.jwt = (context) => resolveJwtSource(source() ?? "", context);
2347
2566
  }
2348
2567
  const body = await fetchPlaylist(clip.playlistUrl, playlistOptions);
2349
2568
  if (cancelled) {
@@ -2489,15 +2708,13 @@ function useClipDownload(clip, options = {}) {
2489
2708
  abortRef.current = abort;
2490
2709
  setState({ kind: "downloading", fetched: 0, total: 0 });
2491
2710
  try {
2492
- const explicit = getJwtRef.current;
2493
- const fallback = storeRef.current?.getState().internal.reactor.getJwtResolver();
2494
- const jwt = explicit ? await explicit() : fallback !== void 0 ? await resolveJwtSource(fallback) : void 0;
2711
+ const source = () => getJwtRef.current ?? storeRef.current?.getState().internal.reactor.getJwtResolver();
2495
2712
  const downloadOptions = {
2496
2713
  signal: abort.signal,
2497
2714
  onProgress: ({ fetched, total }) => setState({ kind: "downloading", fetched, total })
2498
2715
  };
2499
- if (jwt !== void 0) {
2500
- downloadOptions.jwt = jwt;
2716
+ if (source() !== void 0) {
2717
+ downloadOptions.jwt = (context) => resolveJwtSource(source() ?? "", context);
2501
2718
  }
2502
2719
  const blob = await downloadClipAsFile(clipRef.current, filenameRef.current, downloadOptions);
2503
2720
  setState({ kind: "idle" });