@reactor-team/js-sdk 2.10.0 → 2.11.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
@@ -100,6 +100,7 @@ __export(index_exports, {
100
100
  downloadClipAsFile: () => downloadClipAsFile,
101
101
  fetchPlaylist: () => fetchPlaylist,
102
102
  isAbortError: () => isAbortError,
103
+ normalizeJwtSource: () => normalizeJwtSource,
103
104
  parsePlaylist: () => parsePlaylist,
104
105
  rewriteUrlHost: () => rewriteUrlHost,
105
106
  useClipDownload: () => useClipDownload,
@@ -138,15 +139,23 @@ function isAbortError(error) {
138
139
  return error instanceof AbortError || error instanceof Error && error.name === "AbortError";
139
140
  }
140
141
 
142
+ // src/core/auth.ts
143
+ function normalizeJwtSource(source) {
144
+ if (typeof source === "function") {
145
+ return source;
146
+ }
147
+ return () => source;
148
+ }
149
+
141
150
  // src/core/types.ts
142
151
  var import_zod = require("zod");
143
152
 
144
153
  // package.json
145
154
  var package_default = {
146
155
  name: "@reactor-team/js-sdk",
147
- version: "2.10.0",
156
+ version: "2.11.0",
148
157
  description: "Reactor JavaScript frontend SDK \u2014 connect React and TypeScript apps to real-time AI video models on Reactor.",
149
- license: "MIT",
158
+ license: "Apache-2.0",
150
159
  repository: {
151
160
  type: "git",
152
161
  url: "https://github.com/reactor-team/js-sdk.git"
@@ -178,9 +187,13 @@ var package_default = {
178
187
  },
179
188
  files: [
180
189
  "dist",
181
- "README.md"
190
+ "README.md",
191
+ "LICENSE",
192
+ "NOTICE"
182
193
  ],
183
194
  scripts: {
195
+ prepack: "cp ../../LICENSE ../../NOTICE .",
196
+ postpack: "rm -f LICENSE NOTICE",
184
197
  build: "tsup",
185
198
  dev: "tsup --watch",
186
199
  test: "vitest run",
@@ -196,8 +209,9 @@ var package_default = {
196
209
  },
197
210
  packageManager: "pnpm@10.12.1",
198
211
  dependencies: {
212
+ mp4box: "^2.3.0",
199
213
  "sdp-transform": "^3.0.0",
200
- zod: "^4.0.5"
214
+ zod: "^4.4.3"
201
215
  },
202
216
  peerDependencies: {
203
217
  "hls.js": "^1.6.0",
@@ -211,13 +225,13 @@ var package_default = {
211
225
  },
212
226
  devDependencies: {
213
227
  "@roamhq/wrtc": "^0.8.0",
214
- "@types/node": "^20",
215
- "@types/react": "^18.2.8",
228
+ "@types/node": "^25",
229
+ "@types/react": "^19.2.15",
216
230
  "hls.js": "^1.6.0",
217
231
  prettier: "^3.6.2",
218
232
  tsup: "^8.5.0",
219
233
  typescript: "^5.8.3",
220
- vitest: "^3.0.0"
234
+ vitest: "^4.1.7"
221
235
  }
222
236
  };
223
237
 
@@ -311,6 +325,16 @@ var WebRTCSdpOfferRequestSchema = import_zod.z.object({
311
325
  var WebRTCSdpAnswerResponseSchema = import_zod.z.object({
312
326
  sdp_answer: import_zod.z.string()
313
327
  });
328
+ var IceCandidateSchema = import_zod.z.object({
329
+ candidate: import_zod.z.string(),
330
+ sdp_mid: import_zod.z.string().optional(),
331
+ sdp_mline_index: import_zod.z.number().optional()
332
+ });
333
+ var IceCandidatesRequestSchema = import_zod.z.object({
334
+ candidates: import_zod.z.array(IceCandidateSchema),
335
+ is_final: import_zod.z.boolean(),
336
+ client_info: ClientInfoSchema.optional()
337
+ });
314
338
 
315
339
  // src/core/CoordinatorClient.ts
316
340
  var SESSION_POLL_INITIAL_BACKOFF_MS = 200;
@@ -320,7 +344,7 @@ var SESSION_POLL_DEFAULT_MAX_ATTEMPTS = 20;
320
344
  var CoordinatorClient = class {
321
345
  constructor(options) {
322
346
  this.baseUrl = options.baseUrl;
323
- this.jwtToken = options.jwtToken;
347
+ this.resolveJwt = normalizeJwtSource(options.jwtToken);
324
348
  this.model = options.model;
325
349
  this.abortController = new AbortController();
326
350
  }
@@ -340,14 +364,22 @@ var CoordinatorClient = class {
340
364
  return this.abortController.signal;
341
365
  }
342
366
  /**
343
- * Returns authorization + versioning headers for all coordinator requests.
367
+ * Returns authorization + versioning headers for all coordinator
368
+ * requests. Async so the JWT resolver can fetch a fresh token if
369
+ * needed; an empty token suppresses the `Authorization` header.
344
370
  */
345
371
  getHeaders() {
346
- return {
347
- Authorization: `Bearer ${this.jwtToken}`,
348
- [API_VERSION_HEADER]: String(REACTOR_API_VERSION),
349
- [API_ACCEPT_VERSION_HEADER]: String(REACTOR_API_VERSION)
350
- };
372
+ return __async(this, null, function* () {
373
+ const headers = {
374
+ [API_VERSION_HEADER]: String(REACTOR_API_VERSION),
375
+ [API_ACCEPT_VERSION_HEADER]: String(REACTOR_API_VERSION)
376
+ };
377
+ const jwt = yield this.resolveJwt();
378
+ if (jwt) {
379
+ headers.Authorization = `Bearer ${jwt}`;
380
+ }
381
+ return headers;
382
+ });
351
383
  }
352
384
  /**
353
385
  * Checks an HTTP response for version mismatch errors (426, 501).
@@ -408,7 +440,7 @@ var CoordinatorClient = class {
408
440
  }, extraArgs ? { extra_args: extraArgs } : {});
409
441
  const response = yield fetch(`${this.baseUrl}/sessions`, {
410
442
  method: "POST",
411
- headers: __spreadProps(__spreadValues({}, this.getHeaders()), {
443
+ headers: __spreadProps(__spreadValues({}, yield this.getHeaders()), {
412
444
  "Content-Type": "application/json"
413
445
  }),
414
446
  body: JSON.stringify(requestBody),
@@ -463,7 +495,7 @@ var CoordinatorClient = class {
463
495
  `${this.baseUrl}/sessions/${this.currentSessionId}`,
464
496
  {
465
497
  method: "GET",
466
- headers: this.getHeaders(),
498
+ headers: yield this.getHeaders(),
467
499
  signal: this.signal
468
500
  }
469
501
  );
@@ -516,7 +548,7 @@ var CoordinatorClient = class {
516
548
  `${this.baseUrl}/sessions/${this.currentSessionId}`,
517
549
  {
518
550
  method: "GET",
519
- headers: this.getHeaders(),
551
+ headers: yield this.getHeaders(),
520
552
  signal: this.signal
521
553
  }
522
554
  );
@@ -541,7 +573,7 @@ var CoordinatorClient = class {
541
573
  `${this.baseUrl}/sessions/${this.currentSessionId}/info`,
542
574
  {
543
575
  method: "GET",
544
- headers: this.getHeaders(),
576
+ headers: yield this.getHeaders(),
545
577
  signal: this.signal
546
578
  }
547
579
  );
@@ -573,7 +605,7 @@ var CoordinatorClient = class {
573
605
  `${this.baseUrl}/sessions/${this.currentSessionId}`,
574
606
  {
575
607
  method: "PUT",
576
- headers: this.getHeaders(),
608
+ headers: yield this.getHeaders(),
577
609
  signal: this.signal
578
610
  }
579
611
  );
@@ -605,7 +637,7 @@ var CoordinatorClient = class {
605
637
  `${this.baseUrl}/sessions/${this.currentSessionId}`,
606
638
  __spreadProps(__spreadValues({
607
639
  method: "DELETE",
608
- headers: __spreadValues(__spreadValues({}, this.getHeaders()), body ? { "Content-Type": "application/json" } : {})
640
+ headers: __spreadValues(__spreadValues({}, yield this.getHeaders()), body ? { "Content-Type": "application/json" } : {})
609
641
  }, body ? { body: JSON.stringify(body) } : {}), {
610
642
  signal: this.signal
611
643
  })
@@ -644,7 +676,7 @@ var CoordinatorClient = class {
644
676
  `${this.baseUrl}/sessions/${sessionId}/uploads`,
645
677
  {
646
678
  method: "POST",
647
- headers: __spreadProps(__spreadValues({}, this.getHeaders()), {
679
+ headers: __spreadProps(__spreadValues({}, yield this.getHeaders()), {
648
680
  "Content-Type": "application/json"
649
681
  }),
650
682
  body: JSON.stringify(request),
@@ -676,11 +708,14 @@ var LocalCoordinatorClient = class extends CoordinatorClient {
676
708
  model
677
709
  });
678
710
  }
711
+ // Local runtime endpoints are auth-free; skip the Authorization header.
679
712
  getHeaders() {
680
- return {
681
- [API_VERSION_HEADER]: String(REACTOR_API_VERSION),
682
- [API_ACCEPT_VERSION_HEADER]: String(REACTOR_API_VERSION)
683
- };
713
+ return __async(this, null, function* () {
714
+ return {
715
+ [API_VERSION_HEADER]: String(REACTOR_API_VERSION),
716
+ [API_ACCEPT_VERSION_HEADER]: String(REACTOR_API_VERSION)
717
+ };
718
+ });
684
719
  }
685
720
  /**
686
721
  * Starts a session on the local runtime.
@@ -694,7 +729,7 @@ var LocalCoordinatorClient = class extends CoordinatorClient {
694
729
  console.debug("[LocalCoordinatorClient] Starting session...");
695
730
  const response = yield fetch(`${this.baseUrl}/start_session`, {
696
731
  method: "POST",
697
- headers: __spreadProps(__spreadValues({}, this.getHeaders()), {
732
+ headers: __spreadProps(__spreadValues({}, yield this.getHeaders()), {
698
733
  "Content-Type": "application/json"
699
734
  }),
700
735
  body: JSON.stringify(__spreadValues({}, extraArgs ? { extra_args: extraArgs } : {})),
@@ -750,7 +785,7 @@ var LocalCoordinatorClient = class extends CoordinatorClient {
750
785
  try {
751
786
  yield fetch(`${this.baseUrl}/stop_session`, {
752
787
  method: "POST",
753
- headers: this.getHeaders(),
788
+ headers: yield this.getHeaders(),
754
789
  signal: this.signal
755
790
  });
756
791
  } catch (error) {
@@ -1154,7 +1189,6 @@ function createOffer(pc) {
1154
1189
  yield pc.setLocalDescription(
1155
1190
  new RTCSessionDescription({ type: initial.type, sdp })
1156
1191
  );
1157
- yield waitForIceGathering(pc);
1158
1192
  const localDescription = pc.localDescription;
1159
1193
  if (!localDescription) {
1160
1194
  throw new Error("Failed to create local description");
@@ -1183,28 +1217,6 @@ function transformIceServers(response) {
1183
1217
  return rtcServer;
1184
1218
  });
1185
1219
  }
1186
- function waitForIceGathering(pc, timeoutMs = 5e3) {
1187
- return new Promise((resolve) => {
1188
- if (pc.iceGatheringState === "complete") {
1189
- resolve();
1190
- return;
1191
- }
1192
- const onGatheringStateChange = () => {
1193
- if (pc.iceGatheringState === "complete") {
1194
- pc.removeEventListener(
1195
- "icegatheringstatechange",
1196
- onGatheringStateChange
1197
- );
1198
- resolve();
1199
- }
1200
- };
1201
- pc.addEventListener("icegatheringstatechange", onGatheringStateChange);
1202
- setTimeout(() => {
1203
- pc.removeEventListener("icegatheringstatechange", onGatheringStateChange);
1204
- resolve();
1205
- }, timeoutMs);
1206
- });
1207
- }
1208
1220
  function sendMessage(channel, command, data, scope = "application", maxBytes = DEFAULT_MAX_MESSAGE_BYTES, uploads) {
1209
1221
  if (channel.readyState !== "open") {
1210
1222
  throw new Error(`Data channel not open: ${channel.readyState}`);
@@ -1319,6 +1331,7 @@ var INITIAL_BACKOFF_MS = 200;
1319
1331
  var MAX_BACKOFF_MS = 15e3;
1320
1332
  var BACKOFF_MULTIPLIER = 2;
1321
1333
  var DEFAULT_MAX_POLL_ATTEMPTS = 6;
1334
+ var ICE_CANDIDATE_BATCH_WINDOW_MS = 25;
1322
1335
  var WebRTCTransportClient = class {
1323
1336
  constructor(config) {
1324
1337
  this.eventListeners = /* @__PURE__ */ new Map();
@@ -1327,10 +1340,12 @@ var WebRTCTransportClient = class {
1327
1340
  this.publishedTracks = /* @__PURE__ */ new Map();
1328
1341
  this.peerConnected = false;
1329
1342
  this.dataChannelOpen = false;
1343
+ // Trickle ICE batching
1344
+ this.pendingIceCandidates = [];
1330
1345
  var _a, _b;
1331
1346
  this.baseUrl = config.baseUrl;
1332
1347
  this.sessionId = config.sessionId;
1333
- this.jwtToken = config.jwtToken;
1348
+ this.resolveJwt = normalizeJwtSource(config.jwtToken);
1334
1349
  this.webrtcVersion = (_a = config.webrtcVersion) != null ? _a : REACTOR_WEBRTC_VERSION;
1335
1350
  this.maxPollAttempts = (_b = config.maxPollAttempts) != null ? _b : DEFAULT_MAX_POLL_ATTEMPTS;
1336
1351
  this.abortController = new AbortController();
@@ -1361,11 +1376,19 @@ var WebRTCTransportClient = class {
1361
1376
  get transportBaseUrl() {
1362
1377
  return `${this.baseUrl}/sessions/${this.sessionId}/transport/webrtc`;
1363
1378
  }
1379
+ // Async so the JWT resolver can fetch a fresh token if needed; an
1380
+ // empty token suppresses the `Authorization` header.
1364
1381
  getHeaders() {
1365
- return {
1366
- Authorization: `Bearer ${this.jwtToken}`,
1367
- [WEBRTC_VERSION_HEADER]: this.webrtcVersion
1368
- };
1382
+ return __async(this, null, function* () {
1383
+ const headers = {
1384
+ [WEBRTC_VERSION_HEADER]: this.webrtcVersion
1385
+ };
1386
+ const jwt = yield this.resolveJwt();
1387
+ if (jwt) {
1388
+ headers.Authorization = `Bearer ${jwt}`;
1389
+ }
1390
+ return headers;
1391
+ });
1369
1392
  }
1370
1393
  checkVersionMismatch(response) {
1371
1394
  return __async(this, null, function* () {
@@ -1407,7 +1430,7 @@ var WebRTCTransportClient = class {
1407
1430
  console.debug("[WebRTCTransport] Fetching ICE servers...");
1408
1431
  const response = yield fetch(`${this.transportBaseUrl}/ice_servers`, {
1409
1432
  method: "GET",
1410
- headers: this.getHeaders(),
1433
+ headers: yield this.getHeaders(),
1411
1434
  signal: this.signal
1412
1435
  });
1413
1436
  yield this.checkVersionMismatch(response);
@@ -1437,7 +1460,7 @@ var WebRTCTransportClient = class {
1437
1460
  };
1438
1461
  const response = yield fetch(`${this.transportBaseUrl}/sdp_params`, {
1439
1462
  method,
1440
- headers: __spreadProps(__spreadValues({}, this.getHeaders()), {
1463
+ headers: __spreadProps(__spreadValues({}, yield this.getHeaders()), {
1441
1464
  "Content-Type": "application/json"
1442
1465
  }),
1443
1466
  body: JSON.stringify(requestBody),
@@ -1453,6 +1476,70 @@ var WebRTCTransportClient = class {
1453
1476
  console.debug("[WebRTCTransport] SDP offer accepted (202)");
1454
1477
  });
1455
1478
  }
1479
+ sendIceCandidates(candidates, is_final) {
1480
+ return __async(this, null, function* () {
1481
+ console.debug(
1482
+ `[WebRTCTransport] Sending ICE candidates (count=${candidates.length}, is_final=${is_final})`
1483
+ );
1484
+ const requestBody = {
1485
+ candidates,
1486
+ is_final,
1487
+ client_info: {
1488
+ sdk_version: REACTOR_SDK_VERSION,
1489
+ sdk_type: REACTOR_SDK_TYPE
1490
+ }
1491
+ };
1492
+ const response = yield fetch(`${this.transportBaseUrl}/ice_candidates`, {
1493
+ method: "POST",
1494
+ headers: __spreadProps(__spreadValues({}, yield this.getHeaders()), {
1495
+ "Content-Type": "application/json"
1496
+ }),
1497
+ body: JSON.stringify(requestBody),
1498
+ signal: this.signal
1499
+ });
1500
+ yield this.checkVersionMismatch(response);
1501
+ if (response.status !== 202) {
1502
+ const errorText = yield response.text();
1503
+ throw new Error(
1504
+ `Failed to send ICE candidates: ${response.status} ${errorText}`
1505
+ );
1506
+ }
1507
+ console.debug("[WebRTCTransport] ICE candidates accepted (202)");
1508
+ return;
1509
+ });
1510
+ }
1511
+ /**
1512
+ * Drain the pending ICE candidates buffer and POST them as a single
1513
+ * batch. Called either by the debounce timer (collected candidates so
1514
+ * far) or directly by the gathering-complete handler (with
1515
+ * ``isFinal=true``).
1516
+ *
1517
+ * Errors are logged at debug level — trickle ICE is fire-and-forget,
1518
+ * and the connection can still succeed even if some candidate batches
1519
+ * are lost (host/srflx candidates from the other side are usually
1520
+ * sufficient).
1521
+ */
1522
+ flushPendingIceCandidates(isFinal) {
1523
+ if (this.iceCandidateFlushTimer !== void 0) {
1524
+ clearTimeout(this.iceCandidateFlushTimer);
1525
+ this.iceCandidateFlushTimer = void 0;
1526
+ }
1527
+ const batch = this.pendingIceCandidates;
1528
+ this.pendingIceCandidates = [];
1529
+ if (batch.length === 0 && !isFinal) {
1530
+ return;
1531
+ }
1532
+ this.sendIceCandidates(batch, isFinal).catch((err) => {
1533
+ console.debug("[WebRTCTransport] ICE candidate flush failed:", err);
1534
+ });
1535
+ }
1536
+ cancelPendingIceCandidates() {
1537
+ if (this.iceCandidateFlushTimer !== void 0) {
1538
+ clearTimeout(this.iceCandidateFlushTimer);
1539
+ this.iceCandidateFlushTimer = void 0;
1540
+ }
1541
+ this.pendingIceCandidates = [];
1542
+ }
1456
1543
  pollSdpAnswer() {
1457
1544
  return __async(this, null, function* () {
1458
1545
  console.debug("[WebRTCTransport] Polling for SDP answer...");
@@ -1474,7 +1561,7 @@ var WebRTCTransportClient = class {
1474
1561
  );
1475
1562
  const response = yield fetch(`${this.transportBaseUrl}/sdp_params`, {
1476
1563
  method: "GET",
1477
- headers: this.getHeaders(),
1564
+ headers: yield this.getHeaders(),
1478
1565
  signal: this.signal
1479
1566
  });
1480
1567
  yield this.checkVersionMismatch(response);
@@ -1522,6 +1609,7 @@ var WebRTCTransportClient = class {
1522
1609
  this.resetTransportTimings();
1523
1610
  this.stopPing();
1524
1611
  this.stopStatsPolling();
1612
+ this.cancelPendingIceCandidates();
1525
1613
  if (this.dataChannel) {
1526
1614
  this.dataChannel.close();
1527
1615
  this.dataChannel = void 0;
@@ -1584,6 +1672,7 @@ var WebRTCTransportClient = class {
1584
1672
  return __async(this, null, function* () {
1585
1673
  this.stopPing();
1586
1674
  this.stopStatsPolling();
1675
+ this.cancelPendingIceCandidates();
1587
1676
  for (const name of Array.from(this.publishedTracks.keys())) {
1588
1677
  yield this.unpublishTrack(name);
1589
1678
  }
@@ -1837,8 +1926,21 @@ var WebRTCTransportClient = class {
1837
1926
  this.emit("trackReceived", trackName, event.track, stream);
1838
1927
  };
1839
1928
  this.peerConnection.onicecandidate = (event) => {
1929
+ var _a, _b;
1840
1930
  if (event.candidate) {
1841
- console.debug("[WebRTCTransport] ICE candidate:", event.candidate);
1931
+ this.pendingIceCandidates.push({
1932
+ candidate: event.candidate.candidate,
1933
+ sdp_mid: (_a = event.candidate.sdpMid) != null ? _a : void 0,
1934
+ sdp_mline_index: (_b = event.candidate.sdpMLineIndex) != null ? _b : void 0
1935
+ });
1936
+ if (this.iceCandidateFlushTimer === void 0) {
1937
+ this.iceCandidateFlushTimer = setTimeout(
1938
+ () => this.flushPendingIceCandidates(false),
1939
+ ICE_CANDIDATE_BATCH_WINDOW_MS
1940
+ );
1941
+ }
1942
+ } else {
1943
+ this.flushPendingIceCandidates(true);
1842
1944
  }
1843
1945
  };
1844
1946
  this.peerConnection.onicecandidateerror = (event) => {
@@ -2128,7 +2230,7 @@ function downloadClipAsFile(_0) {
2128
2230
  `Chunk ${i} returned HTTP ${response.status}`
2129
2231
  );
2130
2232
  }
2131
- const data = yield response.arrayBuffer();
2233
+ const data = new Uint8Array(yield response.arrayBuffer());
2132
2234
  parts.push(data);
2133
2235
  bytes += data.byteLength;
2134
2236
  (_a = options.onProgress) == null ? void 0 : _a.call(options, {
@@ -2137,7 +2239,8 @@ function downloadClipAsFile(_0) {
2137
2239
  bytes
2138
2240
  });
2139
2241
  }
2140
- const blob = new Blob(parts, { type: "video/mp4" });
2242
+ const finalBytes = yield maybeRemux(parts);
2243
+ const blob = new Blob([finalBytes], { type: "video/mp4" });
2141
2244
  if (filename === null) {
2142
2245
  return blob;
2143
2246
  }
@@ -2151,6 +2254,145 @@ function downloadClipAsFile(_0) {
2151
2254
  return blob;
2152
2255
  });
2153
2256
  }
2257
+ function maybeRemux(parts) {
2258
+ return __async(this, null, function* () {
2259
+ const input = concatUint8Arrays(parts);
2260
+ try {
2261
+ const MP4Box = yield loadMp4Box();
2262
+ return yield remuxFragmentedToFlat(input, MP4Box);
2263
+ } catch (error) {
2264
+ console.warn(
2265
+ "[Reactor] Clip remux failed, returning fragmented MP4 instead.",
2266
+ error
2267
+ );
2268
+ return input;
2269
+ }
2270
+ });
2271
+ }
2272
+ var __remuxInternals = {
2273
+ loadMp4Box: () => import("mp4box")
2274
+ };
2275
+ function loadMp4Box() {
2276
+ return __remuxInternals.loadMp4Box();
2277
+ }
2278
+ function remuxFragmentedToFlat(input, MP4Box) {
2279
+ return __async(this, null, function* () {
2280
+ return new Promise((resolve, reject) => {
2281
+ const inFile = MP4Box.createFile();
2282
+ const outFile = MP4Box.createFile();
2283
+ outFile.init({ brands: ["isom", "mp42", "avc1", "iso2"] });
2284
+ const inToOutTrack = /* @__PURE__ */ new Map();
2285
+ const trackBaselineDts = /* @__PURE__ */ new Map();
2286
+ let settled = false;
2287
+ const fail = (err) => {
2288
+ if (settled) return;
2289
+ settled = true;
2290
+ reject(err);
2291
+ };
2292
+ inFile.onError = (_module, message) => {
2293
+ fail(new Error(message));
2294
+ };
2295
+ inFile.onReady = (info) => {
2296
+ if (!info.tracks.length) {
2297
+ fail(new Error("no tracks in input"));
2298
+ return;
2299
+ }
2300
+ for (const track of info.tracks) {
2301
+ inFile.setExtractionOptions(track.id, null, { nbSamples: 1e3 });
2302
+ }
2303
+ inFile.start();
2304
+ };
2305
+ inFile.onSamples = (id, _user, samples) => {
2306
+ if (settled || samples.length === 0) return;
2307
+ let outId = inToOutTrack.get(id);
2308
+ let baseline = trackBaselineDts.get(id);
2309
+ if (outId === void 0) {
2310
+ const firstSample = samples[0];
2311
+ const sampleEntry = firstSample.description;
2312
+ const inputTrack = trackInfoById(inFile, id);
2313
+ outId = outFile.addTrack({
2314
+ type: sampleEntry.type,
2315
+ timescale: firstSample.timescale,
2316
+ width: inputTrack == null ? void 0 : inputTrack.track_width,
2317
+ height: inputTrack == null ? void 0 : inputTrack.track_height,
2318
+ language: inputTrack == null ? void 0 : inputTrack.language,
2319
+ hdlr: (inputTrack == null ? void 0 : inputTrack.video) ? "vide" : (inputTrack == null ? void 0 : inputTrack.audio) ? "soun" : void 0,
2320
+ // `boxes` is typed as `Box[]` but `description_boxes`
2321
+ // wants the narrower `BoxKind[]` union — at runtime they
2322
+ // are the same concrete instances, just typed loosely.
2323
+ description_boxes: sampleEntry.boxes
2324
+ });
2325
+ baseline = firstSample.dts;
2326
+ inToOutTrack.set(id, outId);
2327
+ trackBaselineDts.set(id, baseline);
2328
+ }
2329
+ const dtsShift = baseline;
2330
+ for (const sample of samples) {
2331
+ if (!sample.data) continue;
2332
+ outFile.addSample(outId, sample.data, {
2333
+ duration: sample.duration,
2334
+ dts: sample.dts - dtsShift,
2335
+ cts: sample.cts - dtsShift,
2336
+ is_sync: sample.is_sync
2337
+ });
2338
+ }
2339
+ };
2340
+ let buf;
2341
+ try {
2342
+ buf = MP4Box.MP4BoxBuffer.fromArrayBuffer(
2343
+ input.buffer.slice(
2344
+ input.byteOffset,
2345
+ input.byteOffset + input.byteLength
2346
+ ),
2347
+ 0
2348
+ );
2349
+ } catch (error) {
2350
+ fail(error);
2351
+ return;
2352
+ }
2353
+ try {
2354
+ inFile.appendBuffer(buf);
2355
+ inFile.flush();
2356
+ } catch (error) {
2357
+ fail(error);
2358
+ return;
2359
+ }
2360
+ if (settled) return;
2361
+ if (inToOutTrack.size === 0) {
2362
+ fail(new Error("no samples extracted from input"));
2363
+ return;
2364
+ }
2365
+ let output;
2366
+ try {
2367
+ const stream = outFile.getBuffer();
2368
+ output = new Uint8Array(
2369
+ stream.buffer.slice(0, stream.byteLength)
2370
+ );
2371
+ } catch (error) {
2372
+ fail(error);
2373
+ return;
2374
+ }
2375
+ settled = true;
2376
+ resolve(output);
2377
+ });
2378
+ });
2379
+ }
2380
+ function trackInfoById(file, id) {
2381
+ const info = file.getInfo();
2382
+ return info.tracks.find((t) => t.id === id);
2383
+ }
2384
+ function concatUint8Arrays(parts) {
2385
+ if (parts.length === 1) return parts[0];
2386
+ let total = 0;
2387
+ for (const p of parts) total += p.byteLength;
2388
+ const out = new Uint8Array(total);
2389
+ let offset = 0;
2390
+ for (const p of parts) {
2391
+ out.set(p, offset);
2392
+ offset += p.byteLength;
2393
+ }
2394
+ return out;
2395
+ }
2154
2396
  function resolveAgainst(target, base) {
2155
2397
  try {
2156
2398
  return new URL(target, base).toString();
@@ -2460,6 +2702,15 @@ var Reactor = class {
2460
2702
  getCoordinatorBaseUrl: () => this.coordinatorUrl
2461
2703
  });
2462
2704
  }
2705
+ /**
2706
+ * Returns the JWT resolver supplied to the most recent
2707
+ * {@link connect} call, or `undefined` if none was set (pre-connect
2708
+ * or local mode). Used by clip surfaces as a fallback when their
2709
+ * own `getJwt` prop is omitted.
2710
+ */
2711
+ getJwtResolver() {
2712
+ return this.jwtResolver;
2713
+ }
2463
2714
  on(event, handler) {
2464
2715
  if (!this.eventListeners.has(event)) {
2465
2716
  this.eventListeners.set(event, /* @__PURE__ */ new Set());
@@ -2722,7 +2973,10 @@ var Reactor = class {
2722
2973
  }
2723
2974
  /**
2724
2975
  * Connects to the coordinator, creates a session, then establishes
2725
- * the transport using server-declared capabilities.
2976
+ * the transport using server-declared capabilities. `jwtToken` may
2977
+ * be a static string or a {@link JwtSource} resolver; pass a
2978
+ * resolver when the token is short-lived so each Coordinator HTTP
2979
+ * hop sees a fresh value.
2726
2980
  */
2727
2981
  connect(jwtToken, options) {
2728
2982
  return __async(this, null, function* () {
@@ -2735,6 +2989,9 @@ var Reactor = class {
2735
2989
  }
2736
2990
  this.setStatus("connecting");
2737
2991
  this.connectStartTime = performance.now();
2992
+ if (!this.local && jwtToken !== void 0) {
2993
+ this.jwtResolver = normalizeJwtSource(jwtToken);
2994
+ }
2738
2995
  try {
2739
2996
  this.coordinatorClient = this.local ? new LocalCoordinatorClient(this.coordinatorUrl, this.model) : new CoordinatorClient({
2740
2997
  baseUrl: this.coordinatorUrl,
@@ -3179,12 +3436,27 @@ function ReactorProvider(_a) {
3179
3436
  var _b = _a, {
3180
3437
  children,
3181
3438
  connectOptions,
3182
- jwtToken
3439
+ jwtToken,
3440
+ getJwt
3183
3441
  } = _b, props = __objRest(_b, [
3184
3442
  "children",
3185
3443
  "connectOptions",
3186
- "jwtToken"
3444
+ "jwtToken",
3445
+ "getJwt"
3187
3446
  ]);
3447
+ const getJwtRef = (0, import_react3.useRef)(getJwt);
3448
+ (0, import_react3.useEffect)(() => {
3449
+ getJwtRef.current = getJwt;
3450
+ });
3451
+ const hasGetJwt = getJwt !== void 0;
3452
+ const stableGetJwt = (0, import_react3.useMemo)(() => {
3453
+ if (!hasGetJwt) return void 0;
3454
+ return () => __async(null, null, function* () {
3455
+ const r = getJwtRef.current;
3456
+ return r ? yield r() : "";
3457
+ });
3458
+ }, [hasGetJwt]);
3459
+ const jwtSource = stableGetJwt != null ? stableGetJwt : jwtToken;
3188
3460
  const storeRef = (0, import_react3.useRef)(void 0);
3189
3461
  const firstRender = (0, import_react3.useRef)(true);
3190
3462
  const [_storeVersion, setStoreVersion] = (0, import_react3.useState)(0);
@@ -3192,7 +3464,7 @@ function ReactorProvider(_a) {
3192
3464
  console.debug("[ReactorProvider] Creating new reactor store");
3193
3465
  storeRef.current = createReactorStore(
3194
3466
  initReactorStore(__spreadProps(__spreadValues({}, props), {
3195
- jwtToken
3467
+ jwtToken: jwtSource
3196
3468
  }))
3197
3469
  );
3198
3470
  console.debug("[ReactorProvider] Reactor store created successfully");
@@ -3217,11 +3489,11 @@ function ReactorProvider(_a) {
3217
3489
  if (firstRender.current) {
3218
3490
  firstRender.current = false;
3219
3491
  const current2 = storeRef.current;
3220
- if (autoConnect && current2.getState().status === "disconnected" && jwtToken) {
3492
+ if (autoConnect && current2.getState().status === "disconnected" && jwtSource) {
3221
3493
  console.debug(
3222
3494
  "[ReactorProvider] Starting autoconnect in first render..."
3223
3495
  );
3224
- current2.getState().connect(jwtToken, pollingOptions).then(() => {
3496
+ current2.getState().connect(jwtSource, pollingOptions).then(() => {
3225
3497
  console.debug(
3226
3498
  "[ReactorProvider] Autoconnect successful in first render"
3227
3499
  );
@@ -3254,7 +3526,7 @@ function ReactorProvider(_a) {
3254
3526
  apiUrl,
3255
3527
  modelName,
3256
3528
  local,
3257
- jwtToken
3529
+ jwtToken: jwtSource
3258
3530
  })
3259
3531
  );
3260
3532
  const current = storeRef.current;
@@ -3262,9 +3534,9 @@ function ReactorProvider(_a) {
3262
3534
  console.debug(
3263
3535
  "[ReactorProvider] Reactor store updated successfully, and increased version"
3264
3536
  );
3265
- if (autoConnect && current.getState().status === "disconnected" && jwtToken) {
3537
+ if (autoConnect && current.getState().status === "disconnected" && jwtSource) {
3266
3538
  console.debug("[ReactorProvider] Starting autoconnect...");
3267
- current.getState().connect(jwtToken, pollingOptions).then(() => {
3539
+ current.getState().connect(jwtSource, pollingOptions).then(() => {
3268
3540
  console.debug("[ReactorProvider] Autoconnect successful");
3269
3541
  }).catch((error) => {
3270
3542
  console.error("[ReactorProvider] Failed to autoconnect:", error);
@@ -3280,7 +3552,7 @@ function ReactorProvider(_a) {
3280
3552
  console.error("[ReactorProvider] Failed to disconnect:", error);
3281
3553
  });
3282
3554
  };
3283
- }, [apiUrl, modelName, autoConnect, local, jwtToken, maxAttempts]);
3555
+ }, [apiUrl, modelName, autoConnect, local, jwtSource, maxAttempts]);
3284
3556
  return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ReactorContext.Provider, { value: storeRef.current, children });
3285
3557
  }
3286
3558
  function useReactorStore(selector) {
@@ -4202,13 +4474,16 @@ function ClipPlayer({
4202
4474
  }) {
4203
4475
  const videoRef = (0, import_react8.useRef)(null);
4204
4476
  const [phase, setPhase] = (0, import_react8.useState)({ kind: "waiting" });
4477
+ const store = (0, import_react8.useContext)(ReactorContext);
4205
4478
  const getJwtRef = (0, import_react8.useRef)(getJwt);
4206
4479
  const autoPlayRef = (0, import_react8.useRef)(autoPlay);
4207
4480
  const slackMsRef = (0, import_react8.useRef)(slackMs);
4481
+ const storeRef = (0, import_react8.useRef)(store);
4208
4482
  (0, import_react8.useEffect)(() => {
4209
4483
  getJwtRef.current = getJwt;
4210
4484
  autoPlayRef.current = autoPlay;
4211
4485
  slackMsRef.current = slackMs;
4486
+ storeRef.current = store;
4212
4487
  });
4213
4488
  (0, import_react8.useEffect)(() => {
4214
4489
  const video = videoRef.current;
@@ -4270,9 +4545,13 @@ function ClipPlayer({
4270
4545
  hlsInstance = hls;
4271
4546
  });
4272
4547
  const setup = () => __async(null, null, function* () {
4548
+ var _a;
4273
4549
  try {
4274
4550
  setPhase({ kind: "waiting" });
4275
- const jwt = getJwtRef.current ? yield getJwtRef.current() : void 0;
4551
+ const explicit = getJwtRef.current;
4552
+ const fallback = (_a = storeRef.current) == null ? void 0 : _a.getState().internal.reactor.getJwtResolver();
4553
+ const resolver = explicit != null ? explicit : fallback;
4554
+ const jwt = resolver ? yield resolver() : void 0;
4276
4555
  if (cancelled) return;
4277
4556
  const body = yield fetchPlaylist(clip.playlistUrl, {
4278
4557
  predictedReadyAtMs: clip.predictedReadyAtMs,
@@ -4379,6 +4658,7 @@ var import_react9 = require("react");
4379
4658
  function useClipDownload(clip, options = {}) {
4380
4659
  var _a;
4381
4660
  const [state, setState] = (0, import_react9.useState)({ kind: "idle" });
4661
+ const store = (0, import_react9.useContext)(ReactorContext);
4382
4662
  const clipRef = (0, import_react9.useRef)(clip);
4383
4663
  const filenameRef = (0, import_react9.useRef)(
4384
4664
  (_a = options.filename) != null ? _a : "reactor-clip.mp4"
@@ -4395,7 +4675,10 @@ function useClipDownload(clip, options = {}) {
4395
4675
  inFlightRef.current = true;
4396
4676
  setState({ kind: "downloading", fetched: 0, total: 0 });
4397
4677
  try {
4398
- const jwt = getJwtRef.current ? yield getJwtRef.current() : void 0;
4678
+ const explicit = getJwtRef.current;
4679
+ const fallback = store == null ? void 0 : store.getState().internal.reactor.getJwtResolver();
4680
+ const resolver = explicit != null ? explicit : fallback;
4681
+ const jwt = resolver ? yield resolver() : void 0;
4399
4682
  const blob = yield downloadClipAsFile(
4400
4683
  clipRef.current,
4401
4684
  filenameRef.current,
@@ -4413,7 +4696,7 @@ function useClipDownload(clip, options = {}) {
4413
4696
  } finally {
4414
4697
  inFlightRef.current = false;
4415
4698
  }
4416
- }), []);
4699
+ }), [store]);
4417
4700
  const reset = (0, import_react9.useCallback)(() => setState({ kind: "idle" }), []);
4418
4701
  return { state, download, reset };
4419
4702
  }
@@ -4490,6 +4773,7 @@ function defaultLabel(state) {
4490
4773
  downloadClipAsFile,
4491
4774
  fetchPlaylist,
4492
4775
  isAbortError,
4776
+ normalizeJwtSource,
4493
4777
  parsePlaylist,
4494
4778
  rewriteUrlHost,
4495
4779
  useClipDownload,