@reactor-team/js-sdk 2.12.1 → 2.12.3

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.mjs CHANGED
@@ -76,6 +76,14 @@ var AbortError = class extends Error {
76
76
  function isAbortError(error) {
77
77
  return error instanceof AbortError || error instanceof Error && error.name === "AbortError";
78
78
  }
79
+ var SessionLostError = class extends Error {
80
+ constructor(message) {
81
+ super(message);
82
+ }
83
+ };
84
+ function isSessionLostError(error) {
85
+ return error instanceof SessionLostError;
86
+ }
79
87
 
80
88
  // src/core/auth.ts
81
89
  function normalizeJwtSource(source) {
@@ -91,7 +99,7 @@ import { z } from "zod";
91
99
  // package.json
92
100
  var package_default = {
93
101
  name: "@reactor-team/js-sdk",
94
- version: "2.12.1",
102
+ version: "2.12.3",
95
103
  description: "Reactor JavaScript frontend SDK \u2014 connect React and TypeScript apps to real-time AI video models on Reactor.",
96
104
  license: "Apache-2.0",
97
105
  repository: {
@@ -693,6 +701,11 @@ var LocalCoordinatorClient = class extends CoordinatorClient {
693
701
  });
694
702
  if (!response.ok) {
695
703
  const errorText = yield response.text();
704
+ if (response.status === 400) {
705
+ throw new SessionLostError(
706
+ `Failed to start session: ${response.status} ${errorText}`
707
+ );
708
+ }
696
709
  throw new Error(
697
710
  `Failed to start session: ${response.status} ${errorText}`
698
711
  );
@@ -1477,6 +1490,11 @@ var WebRTCTransportClient = class {
1477
1490
  yield this.checkVersionMismatch(response);
1478
1491
  if (response.status !== 201) {
1479
1492
  const errorText = yield response.text();
1493
+ if (response.status === 400) {
1494
+ throw new SessionLostError(
1495
+ `Failed to register connection: ${response.status} ${errorText}`
1496
+ );
1497
+ }
1480
1498
  throw new Error(
1481
1499
  `Failed to register connection: ${response.status} ${errorText}`
1482
1500
  );
@@ -1523,7 +1541,7 @@ var WebRTCTransportClient = class {
1523
1541
  );
1524
1542
  }
1525
1543
  if (response.status === 400) {
1526
- throw new Error(
1544
+ throw new SessionLostError(
1527
1545
  `[WebRTCTransport] Connection ${connectionId} rejected (400): ${errorText}`
1528
1546
  );
1529
1547
  }
@@ -1537,7 +1555,7 @@ var WebRTCTransportClient = class {
1537
1555
  sendIceCandidates(candidates, is_final) {
1538
1556
  return __async(this, null, function* () {
1539
1557
  if (this.connectionId === void 0) {
1540
- console.debug(
1558
+ console.warn(
1541
1559
  "[WebRTCTransport] ICE candidates dropped: no active connection"
1542
1560
  );
1543
1561
  return;
@@ -1590,6 +1608,12 @@ var WebRTCTransportClient = class {
1590
1608
  clearTimeout(this.iceCandidateFlushTimer);
1591
1609
  this.iceCandidateFlushTimer = void 0;
1592
1610
  }
1611
+ if (this.connectionId === void 0) {
1612
+ console.debug(
1613
+ "[WebRTCTransportClient] skipping ICE candidate flush because the connection is not established yet"
1614
+ );
1615
+ return;
1616
+ }
1593
1617
  const batch = this.pendingIceCandidates;
1594
1618
  this.pendingIceCandidates = [];
1595
1619
  if (batch.length === 0 && !isFinal) {
@@ -1758,6 +1782,11 @@ var WebRTCTransportClient = class {
1758
1782
  trackMapping,
1759
1783
  reconnect
1760
1784
  );
1785
+ if (this.pendingIceCandidates.length > 0) {
1786
+ this.flushPendingIceCandidates(
1787
+ this.peerConnection !== void 0 && this.peerConnection.iceGatheringState === "complete"
1788
+ );
1789
+ }
1761
1790
  const answerResponse = yield this.pollSdpAnswer(this.connectionId);
1762
1791
  this.iceStartTime = performance.now();
1763
1792
  yield setRemoteDescription(
@@ -2328,13 +2357,15 @@ var DEFAULT_PLAYLIST_POLL_SLACK_MS = 15e3;
2328
2357
  function fetchPlaylist(_0) {
2329
2358
  return __async(this, arguments, function* (playlistUrl, options = {}) {
2330
2359
  var _a, _b, _c, _d;
2331
- const slackMs = (_a = options.slackMs) != null ? _a : DEFAULT_PLAYLIST_POLL_SLACK_MS;
2332
- const minDelay = Math.max(0, (_b = options.minRetryDelayMs) != null ? _b : 200);
2333
- const maxDelay = Math.max(minDelay, (_c = options.maxRetryDelayMs) != null ? _c : 2e3);
2334
- const fallbackMaxRetries = (_d = options.maxRetries) != null ? _d : 5;
2335
- const hasDeadline = typeof options.predictedReadyAtMs === "number";
2360
+ const minDelay = Math.max(0, (_a = options.minRetryDelayMs) != null ? _a : 200);
2361
+ const maxDelay = Math.max(minDelay, (_b = options.maxRetryDelayMs) != null ? _b : 2e3);
2362
+ const hasDeadline = typeof options.slackMs === "number" && Number.isFinite(options.slackMs);
2336
2363
  const startedPollingAt = Date.now();
2337
- const deadlineMs = hasDeadline ? Math.max(options.predictedReadyAtMs, startedPollingAt) + slackMs : void 0;
2364
+ const deadlineMs = hasDeadline ? Math.max(
2365
+ (_c = options.predictedReadyAtMs) != null ? _c : startedPollingAt,
2366
+ startedPollingAt
2367
+ ) + options.slackMs : void 0;
2368
+ const maxRetries = typeof options.maxRetries === "number" ? options.maxRetries : void 0;
2338
2369
  const headers = options.jwt ? { Authorization: `Bearer ${options.jwt}` } : void 0;
2339
2370
  let attempt = 0;
2340
2371
  let lastStatus = 0;
@@ -2353,16 +2384,15 @@ function fetchPlaylist(_0) {
2353
2384
  }
2354
2385
  lastStatus = response.status;
2355
2386
  if (response.status === 202) {
2356
- if (hasDeadline) {
2357
- if (Date.now() >= deadlineMs) {
2358
- throw new RecordingError(
2359
- "CLIP_NOT_READY",
2360
- `Boundary chunk still pending after ${slackMs}ms grace (predicted ready ${new Date(
2361
- options.predictedReadyAtMs
2362
- ).toISOString()}). Runtime may have crashed mid-clip.`
2363
- );
2364
- }
2365
- } else if (attempt >= fallbackMaxRetries) {
2387
+ if (deadlineMs !== void 0 && Date.now() >= deadlineMs) {
2388
+ throw new RecordingError(
2389
+ "CLIP_NOT_READY",
2390
+ `Boundary chunk still pending after ${options.slackMs}ms grace (predicted ready ${new Date(
2391
+ (_d = options.predictedReadyAtMs) != null ? _d : startedPollingAt
2392
+ ).toISOString()}). Runtime may have crashed mid-clip.`
2393
+ );
2394
+ }
2395
+ if (maxRetries !== void 0 && attempt >= maxRetries) {
2366
2396
  throw new RecordingError(
2367
2397
  "CLIP_NOT_READY",
2368
2398
  `Manifest still pending after ${attempt + 1} attempts (last status ${lastStatus})`
@@ -2373,7 +2403,7 @@ function fetchPlaylist(_0) {
2373
2403
  minDelay
2374
2404
  );
2375
2405
  const delay = Math.min(maxDelay, Math.max(minDelay, headerDelay));
2376
- const clampedDelay = hasDeadline ? Math.min(delay, Math.max(0, deadlineMs - Date.now())) : delay;
2406
+ const clampedDelay = deadlineMs !== void 0 ? Math.min(delay, Math.max(0, deadlineMs - Date.now())) : delay;
2377
2407
  yield sleep(clampedDelay, options.signal);
2378
2408
  attempt++;
2379
2409
  continue;
@@ -2956,6 +2986,7 @@ var Reactor = class {
2956
2986
  * down its own transport but leaves the session alive.
2957
2987
  */
2958
2988
  this.createdSession = false;
2989
+ this.retryingSessionLoss = false;
2959
2990
  this.tracks = [];
2960
2991
  this.autoResumeTracks = false;
2961
2992
  this.eventListeners = /* @__PURE__ */ new Map();
@@ -3222,6 +3253,12 @@ var Reactor = class {
3222
3253
  var _a;
3223
3254
  (_a = this.transportClient) == null ? void 0 : _a.resumeTrack(name);
3224
3255
  }
3256
+ /** Whether `name` is a track this client receives rather than sends. */
3257
+ isRecvonly(name) {
3258
+ return this.tracks.some(
3259
+ (track) => track.name === name && track.direction === "recvonly"
3260
+ );
3261
+ }
3225
3262
  /**
3226
3263
  * Reconnects to an existing session with a fresh transport.
3227
3264
  */
@@ -3280,7 +3317,7 @@ var Reactor = class {
3280
3317
  */
3281
3318
  connect(jwtToken, options) {
3282
3319
  return __async(this, null, function* () {
3283
- var _a;
3320
+ var _a, _b, _c, _d;
3284
3321
  console.debug("[Reactor] Connecting, status:", this.status);
3285
3322
  if (jwtToken == void 0 && !this.local) {
3286
3323
  throw new Error("No authentication provided and not in local mode");
@@ -3368,6 +3405,19 @@ var Reactor = class {
3368
3405
  };
3369
3406
  } catch (error) {
3370
3407
  if (isAbortError(error)) return;
3408
+ if (!(options == null ? void 0 : options.sessionId) && !this.retryingSessionLoss && isSessionLostError(error)) {
3409
+ this.retryingSessionLoss = true;
3410
+ (_b = this.coordinatorClient) == null ? void 0 : _b.abort();
3411
+ (_c = this.transportClient) == null ? void 0 : _c.abort();
3412
+ (_d = this.transportClient) == null ? void 0 : _d.disconnect();
3413
+ this.setStatus("disconnected");
3414
+ try {
3415
+ yield this.connect(jwtToken, options);
3416
+ return;
3417
+ } finally {
3418
+ this.retryingSessionLoss = false;
3419
+ }
3420
+ }
3371
3421
  console.error("[Reactor] Connection failed:", error);
3372
3422
  this.createError(
3373
3423
  "CONNECTION_FAILED",
@@ -3440,12 +3490,8 @@ var Reactor = class {
3440
3490
  (name, track, stream) => {
3441
3491
  if (this.transportClient !== client) return;
3442
3492
  this.emit("trackReceived", name, track, stream);
3443
- if (this.autoResumeTracks) {
3444
- for (const track2 of this.tracks) {
3445
- if (track2.direction === "recvonly") {
3446
- this.resumeTrack(track2.name);
3447
- }
3448
- }
3493
+ if (this.autoResumeTracks && this.isRecvonly(name)) {
3494
+ this.resumeTrack(name);
3449
3495
  }
3450
3496
  }
3451
3497
  );
@@ -4560,9 +4606,16 @@ function useClipDownload(clip, options = {}) {
4560
4606
  getJwtRef.current = options.getJwt;
4561
4607
  });
4562
4608
  const inFlightRef = useRef6(false);
4609
+ const abortRef = useRef6(null);
4610
+ useEffect6(() => () => {
4611
+ var _a2;
4612
+ return (_a2 = abortRef.current) == null ? void 0 : _a2.abort();
4613
+ }, []);
4563
4614
  const download = useCallback(() => __async(null, null, function* () {
4564
4615
  if (inFlightRef.current) return void 0;
4565
4616
  inFlightRef.current = true;
4617
+ const abort = new AbortController();
4618
+ abortRef.current = abort;
4566
4619
  setState({ kind: "downloading", fetched: 0, total: 0 });
4567
4620
  try {
4568
4621
  const explicit = getJwtRef.current;
@@ -4574,12 +4627,16 @@ function useClipDownload(clip, options = {}) {
4574
4627
  filenameRef.current,
4575
4628
  {
4576
4629
  jwt,
4630
+ signal: abort.signal,
4577
4631
  onProgress: ({ fetched, total }) => setState({ kind: "downloading", fetched, total })
4578
4632
  }
4579
4633
  );
4580
4634
  setState({ kind: "idle" });
4581
4635
  return blob;
4582
4636
  } catch (err) {
4637
+ if (err instanceof DOMException && err.name === "AbortError") {
4638
+ return void 0;
4639
+ }
4583
4640
  const message = err instanceof RecordingError ? `${err.code}: ${err.reason}` : err instanceof Error ? err.message : String(err);
4584
4641
  setState({ kind: "error", message });
4585
4642
  return void 0;
@@ -4672,12 +4729,14 @@ export {
4672
4729
  RecordingClient,
4673
4730
  RecordingError,
4674
4731
  RuntimeRecordingMessageType,
4732
+ SessionLostError,
4675
4733
  WebcamStream,
4676
4734
  clipFromPayload,
4677
4735
  createPlayableManifestUrl,
4678
4736
  downloadClipAsFile,
4679
4737
  fetchPlaylist,
4680
4738
  isAbortError,
4739
+ isSessionLostError,
4681
4740
  normalizeJwtSource,
4682
4741
  parsePlaylist,
4683
4742
  rewriteUrlHost,