@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.mjs CHANGED
@@ -77,15 +77,23 @@ function isAbortError(error) {
77
77
  return error instanceof AbortError || error instanceof Error && error.name === "AbortError";
78
78
  }
79
79
 
80
+ // src/core/auth.ts
81
+ function normalizeJwtSource(source) {
82
+ if (typeof source === "function") {
83
+ return source;
84
+ }
85
+ return () => source;
86
+ }
87
+
80
88
  // src/core/types.ts
81
89
  import { z } from "zod";
82
90
 
83
91
  // package.json
84
92
  var package_default = {
85
93
  name: "@reactor-team/js-sdk",
86
- version: "2.10.0",
94
+ version: "2.11.0",
87
95
  description: "Reactor JavaScript frontend SDK \u2014 connect React and TypeScript apps to real-time AI video models on Reactor.",
88
- license: "MIT",
96
+ license: "Apache-2.0",
89
97
  repository: {
90
98
  type: "git",
91
99
  url: "https://github.com/reactor-team/js-sdk.git"
@@ -117,9 +125,13 @@ var package_default = {
117
125
  },
118
126
  files: [
119
127
  "dist",
120
- "README.md"
128
+ "README.md",
129
+ "LICENSE",
130
+ "NOTICE"
121
131
  ],
122
132
  scripts: {
133
+ prepack: "cp ../../LICENSE ../../NOTICE .",
134
+ postpack: "rm -f LICENSE NOTICE",
123
135
  build: "tsup",
124
136
  dev: "tsup --watch",
125
137
  test: "vitest run",
@@ -135,8 +147,9 @@ var package_default = {
135
147
  },
136
148
  packageManager: "pnpm@10.12.1",
137
149
  dependencies: {
150
+ mp4box: "^2.3.0",
138
151
  "sdp-transform": "^3.0.0",
139
- zod: "^4.0.5"
152
+ zod: "^4.4.3"
140
153
  },
141
154
  peerDependencies: {
142
155
  "hls.js": "^1.6.0",
@@ -150,13 +163,13 @@ var package_default = {
150
163
  },
151
164
  devDependencies: {
152
165
  "@roamhq/wrtc": "^0.8.0",
153
- "@types/node": "^20",
154
- "@types/react": "^18.2.8",
166
+ "@types/node": "^25",
167
+ "@types/react": "^19.2.15",
155
168
  "hls.js": "^1.6.0",
156
169
  prettier: "^3.6.2",
157
170
  tsup: "^8.5.0",
158
171
  typescript: "^5.8.3",
159
- vitest: "^3.0.0"
172
+ vitest: "^4.1.7"
160
173
  }
161
174
  };
162
175
 
@@ -250,6 +263,16 @@ var WebRTCSdpOfferRequestSchema = z.object({
250
263
  var WebRTCSdpAnswerResponseSchema = z.object({
251
264
  sdp_answer: z.string()
252
265
  });
266
+ var IceCandidateSchema = z.object({
267
+ candidate: z.string(),
268
+ sdp_mid: z.string().optional(),
269
+ sdp_mline_index: z.number().optional()
270
+ });
271
+ var IceCandidatesRequestSchema = z.object({
272
+ candidates: z.array(IceCandidateSchema),
273
+ is_final: z.boolean(),
274
+ client_info: ClientInfoSchema.optional()
275
+ });
253
276
 
254
277
  // src/core/CoordinatorClient.ts
255
278
  var SESSION_POLL_INITIAL_BACKOFF_MS = 200;
@@ -259,7 +282,7 @@ var SESSION_POLL_DEFAULT_MAX_ATTEMPTS = 20;
259
282
  var CoordinatorClient = class {
260
283
  constructor(options) {
261
284
  this.baseUrl = options.baseUrl;
262
- this.jwtToken = options.jwtToken;
285
+ this.resolveJwt = normalizeJwtSource(options.jwtToken);
263
286
  this.model = options.model;
264
287
  this.abortController = new AbortController();
265
288
  }
@@ -279,14 +302,22 @@ var CoordinatorClient = class {
279
302
  return this.abortController.signal;
280
303
  }
281
304
  /**
282
- * Returns authorization + versioning headers for all coordinator requests.
305
+ * Returns authorization + versioning headers for all coordinator
306
+ * requests. Async so the JWT resolver can fetch a fresh token if
307
+ * needed; an empty token suppresses the `Authorization` header.
283
308
  */
284
309
  getHeaders() {
285
- return {
286
- Authorization: `Bearer ${this.jwtToken}`,
287
- [API_VERSION_HEADER]: String(REACTOR_API_VERSION),
288
- [API_ACCEPT_VERSION_HEADER]: String(REACTOR_API_VERSION)
289
- };
310
+ return __async(this, null, function* () {
311
+ const headers = {
312
+ [API_VERSION_HEADER]: String(REACTOR_API_VERSION),
313
+ [API_ACCEPT_VERSION_HEADER]: String(REACTOR_API_VERSION)
314
+ };
315
+ const jwt = yield this.resolveJwt();
316
+ if (jwt) {
317
+ headers.Authorization = `Bearer ${jwt}`;
318
+ }
319
+ return headers;
320
+ });
290
321
  }
291
322
  /**
292
323
  * Checks an HTTP response for version mismatch errors (426, 501).
@@ -347,7 +378,7 @@ var CoordinatorClient = class {
347
378
  }, extraArgs ? { extra_args: extraArgs } : {});
348
379
  const response = yield fetch(`${this.baseUrl}/sessions`, {
349
380
  method: "POST",
350
- headers: __spreadProps(__spreadValues({}, this.getHeaders()), {
381
+ headers: __spreadProps(__spreadValues({}, yield this.getHeaders()), {
351
382
  "Content-Type": "application/json"
352
383
  }),
353
384
  body: JSON.stringify(requestBody),
@@ -402,7 +433,7 @@ var CoordinatorClient = class {
402
433
  `${this.baseUrl}/sessions/${this.currentSessionId}`,
403
434
  {
404
435
  method: "GET",
405
- headers: this.getHeaders(),
436
+ headers: yield this.getHeaders(),
406
437
  signal: this.signal
407
438
  }
408
439
  );
@@ -455,7 +486,7 @@ var CoordinatorClient = class {
455
486
  `${this.baseUrl}/sessions/${this.currentSessionId}`,
456
487
  {
457
488
  method: "GET",
458
- headers: this.getHeaders(),
489
+ headers: yield this.getHeaders(),
459
490
  signal: this.signal
460
491
  }
461
492
  );
@@ -480,7 +511,7 @@ var CoordinatorClient = class {
480
511
  `${this.baseUrl}/sessions/${this.currentSessionId}/info`,
481
512
  {
482
513
  method: "GET",
483
- headers: this.getHeaders(),
514
+ headers: yield this.getHeaders(),
484
515
  signal: this.signal
485
516
  }
486
517
  );
@@ -512,7 +543,7 @@ var CoordinatorClient = class {
512
543
  `${this.baseUrl}/sessions/${this.currentSessionId}`,
513
544
  {
514
545
  method: "PUT",
515
- headers: this.getHeaders(),
546
+ headers: yield this.getHeaders(),
516
547
  signal: this.signal
517
548
  }
518
549
  );
@@ -544,7 +575,7 @@ var CoordinatorClient = class {
544
575
  `${this.baseUrl}/sessions/${this.currentSessionId}`,
545
576
  __spreadProps(__spreadValues({
546
577
  method: "DELETE",
547
- headers: __spreadValues(__spreadValues({}, this.getHeaders()), body ? { "Content-Type": "application/json" } : {})
578
+ headers: __spreadValues(__spreadValues({}, yield this.getHeaders()), body ? { "Content-Type": "application/json" } : {})
548
579
  }, body ? { body: JSON.stringify(body) } : {}), {
549
580
  signal: this.signal
550
581
  })
@@ -583,7 +614,7 @@ var CoordinatorClient = class {
583
614
  `${this.baseUrl}/sessions/${sessionId}/uploads`,
584
615
  {
585
616
  method: "POST",
586
- headers: __spreadProps(__spreadValues({}, this.getHeaders()), {
617
+ headers: __spreadProps(__spreadValues({}, yield this.getHeaders()), {
587
618
  "Content-Type": "application/json"
588
619
  }),
589
620
  body: JSON.stringify(request),
@@ -615,11 +646,14 @@ var LocalCoordinatorClient = class extends CoordinatorClient {
615
646
  model
616
647
  });
617
648
  }
649
+ // Local runtime endpoints are auth-free; skip the Authorization header.
618
650
  getHeaders() {
619
- return {
620
- [API_VERSION_HEADER]: String(REACTOR_API_VERSION),
621
- [API_ACCEPT_VERSION_HEADER]: String(REACTOR_API_VERSION)
622
- };
651
+ return __async(this, null, function* () {
652
+ return {
653
+ [API_VERSION_HEADER]: String(REACTOR_API_VERSION),
654
+ [API_ACCEPT_VERSION_HEADER]: String(REACTOR_API_VERSION)
655
+ };
656
+ });
623
657
  }
624
658
  /**
625
659
  * Starts a session on the local runtime.
@@ -633,7 +667,7 @@ var LocalCoordinatorClient = class extends CoordinatorClient {
633
667
  console.debug("[LocalCoordinatorClient] Starting session...");
634
668
  const response = yield fetch(`${this.baseUrl}/start_session`, {
635
669
  method: "POST",
636
- headers: __spreadProps(__spreadValues({}, this.getHeaders()), {
670
+ headers: __spreadProps(__spreadValues({}, yield this.getHeaders()), {
637
671
  "Content-Type": "application/json"
638
672
  }),
639
673
  body: JSON.stringify(__spreadValues({}, extraArgs ? { extra_args: extraArgs } : {})),
@@ -689,7 +723,7 @@ var LocalCoordinatorClient = class extends CoordinatorClient {
689
723
  try {
690
724
  yield fetch(`${this.baseUrl}/stop_session`, {
691
725
  method: "POST",
692
- headers: this.getHeaders(),
726
+ headers: yield this.getHeaders(),
693
727
  signal: this.signal
694
728
  });
695
729
  } catch (error) {
@@ -1093,7 +1127,6 @@ function createOffer(pc) {
1093
1127
  yield pc.setLocalDescription(
1094
1128
  new RTCSessionDescription({ type: initial.type, sdp })
1095
1129
  );
1096
- yield waitForIceGathering(pc);
1097
1130
  const localDescription = pc.localDescription;
1098
1131
  if (!localDescription) {
1099
1132
  throw new Error("Failed to create local description");
@@ -1122,28 +1155,6 @@ function transformIceServers(response) {
1122
1155
  return rtcServer;
1123
1156
  });
1124
1157
  }
1125
- function waitForIceGathering(pc, timeoutMs = 5e3) {
1126
- return new Promise((resolve) => {
1127
- if (pc.iceGatheringState === "complete") {
1128
- resolve();
1129
- return;
1130
- }
1131
- const onGatheringStateChange = () => {
1132
- if (pc.iceGatheringState === "complete") {
1133
- pc.removeEventListener(
1134
- "icegatheringstatechange",
1135
- onGatheringStateChange
1136
- );
1137
- resolve();
1138
- }
1139
- };
1140
- pc.addEventListener("icegatheringstatechange", onGatheringStateChange);
1141
- setTimeout(() => {
1142
- pc.removeEventListener("icegatheringstatechange", onGatheringStateChange);
1143
- resolve();
1144
- }, timeoutMs);
1145
- });
1146
- }
1147
1158
  function sendMessage(channel, command, data, scope = "application", maxBytes = DEFAULT_MAX_MESSAGE_BYTES, uploads) {
1148
1159
  if (channel.readyState !== "open") {
1149
1160
  throw new Error(`Data channel not open: ${channel.readyState}`);
@@ -1258,6 +1269,7 @@ var INITIAL_BACKOFF_MS = 200;
1258
1269
  var MAX_BACKOFF_MS = 15e3;
1259
1270
  var BACKOFF_MULTIPLIER = 2;
1260
1271
  var DEFAULT_MAX_POLL_ATTEMPTS = 6;
1272
+ var ICE_CANDIDATE_BATCH_WINDOW_MS = 25;
1261
1273
  var WebRTCTransportClient = class {
1262
1274
  constructor(config) {
1263
1275
  this.eventListeners = /* @__PURE__ */ new Map();
@@ -1266,10 +1278,12 @@ var WebRTCTransportClient = class {
1266
1278
  this.publishedTracks = /* @__PURE__ */ new Map();
1267
1279
  this.peerConnected = false;
1268
1280
  this.dataChannelOpen = false;
1281
+ // Trickle ICE batching
1282
+ this.pendingIceCandidates = [];
1269
1283
  var _a, _b;
1270
1284
  this.baseUrl = config.baseUrl;
1271
1285
  this.sessionId = config.sessionId;
1272
- this.jwtToken = config.jwtToken;
1286
+ this.resolveJwt = normalizeJwtSource(config.jwtToken);
1273
1287
  this.webrtcVersion = (_a = config.webrtcVersion) != null ? _a : REACTOR_WEBRTC_VERSION;
1274
1288
  this.maxPollAttempts = (_b = config.maxPollAttempts) != null ? _b : DEFAULT_MAX_POLL_ATTEMPTS;
1275
1289
  this.abortController = new AbortController();
@@ -1300,11 +1314,19 @@ var WebRTCTransportClient = class {
1300
1314
  get transportBaseUrl() {
1301
1315
  return `${this.baseUrl}/sessions/${this.sessionId}/transport/webrtc`;
1302
1316
  }
1317
+ // Async so the JWT resolver can fetch a fresh token if needed; an
1318
+ // empty token suppresses the `Authorization` header.
1303
1319
  getHeaders() {
1304
- return {
1305
- Authorization: `Bearer ${this.jwtToken}`,
1306
- [WEBRTC_VERSION_HEADER]: this.webrtcVersion
1307
- };
1320
+ return __async(this, null, function* () {
1321
+ const headers = {
1322
+ [WEBRTC_VERSION_HEADER]: this.webrtcVersion
1323
+ };
1324
+ const jwt = yield this.resolveJwt();
1325
+ if (jwt) {
1326
+ headers.Authorization = `Bearer ${jwt}`;
1327
+ }
1328
+ return headers;
1329
+ });
1308
1330
  }
1309
1331
  checkVersionMismatch(response) {
1310
1332
  return __async(this, null, function* () {
@@ -1346,7 +1368,7 @@ var WebRTCTransportClient = class {
1346
1368
  console.debug("[WebRTCTransport] Fetching ICE servers...");
1347
1369
  const response = yield fetch(`${this.transportBaseUrl}/ice_servers`, {
1348
1370
  method: "GET",
1349
- headers: this.getHeaders(),
1371
+ headers: yield this.getHeaders(),
1350
1372
  signal: this.signal
1351
1373
  });
1352
1374
  yield this.checkVersionMismatch(response);
@@ -1376,7 +1398,7 @@ var WebRTCTransportClient = class {
1376
1398
  };
1377
1399
  const response = yield fetch(`${this.transportBaseUrl}/sdp_params`, {
1378
1400
  method,
1379
- headers: __spreadProps(__spreadValues({}, this.getHeaders()), {
1401
+ headers: __spreadProps(__spreadValues({}, yield this.getHeaders()), {
1380
1402
  "Content-Type": "application/json"
1381
1403
  }),
1382
1404
  body: JSON.stringify(requestBody),
@@ -1392,6 +1414,70 @@ var WebRTCTransportClient = class {
1392
1414
  console.debug("[WebRTCTransport] SDP offer accepted (202)");
1393
1415
  });
1394
1416
  }
1417
+ sendIceCandidates(candidates, is_final) {
1418
+ return __async(this, null, function* () {
1419
+ console.debug(
1420
+ `[WebRTCTransport] Sending ICE candidates (count=${candidates.length}, is_final=${is_final})`
1421
+ );
1422
+ const requestBody = {
1423
+ candidates,
1424
+ is_final,
1425
+ client_info: {
1426
+ sdk_version: REACTOR_SDK_VERSION,
1427
+ sdk_type: REACTOR_SDK_TYPE
1428
+ }
1429
+ };
1430
+ const response = yield fetch(`${this.transportBaseUrl}/ice_candidates`, {
1431
+ method: "POST",
1432
+ headers: __spreadProps(__spreadValues({}, yield this.getHeaders()), {
1433
+ "Content-Type": "application/json"
1434
+ }),
1435
+ body: JSON.stringify(requestBody),
1436
+ signal: this.signal
1437
+ });
1438
+ yield this.checkVersionMismatch(response);
1439
+ if (response.status !== 202) {
1440
+ const errorText = yield response.text();
1441
+ throw new Error(
1442
+ `Failed to send ICE candidates: ${response.status} ${errorText}`
1443
+ );
1444
+ }
1445
+ console.debug("[WebRTCTransport] ICE candidates accepted (202)");
1446
+ return;
1447
+ });
1448
+ }
1449
+ /**
1450
+ * Drain the pending ICE candidates buffer and POST them as a single
1451
+ * batch. Called either by the debounce timer (collected candidates so
1452
+ * far) or directly by the gathering-complete handler (with
1453
+ * ``isFinal=true``).
1454
+ *
1455
+ * Errors are logged at debug level — trickle ICE is fire-and-forget,
1456
+ * and the connection can still succeed even if some candidate batches
1457
+ * are lost (host/srflx candidates from the other side are usually
1458
+ * sufficient).
1459
+ */
1460
+ flushPendingIceCandidates(isFinal) {
1461
+ if (this.iceCandidateFlushTimer !== void 0) {
1462
+ clearTimeout(this.iceCandidateFlushTimer);
1463
+ this.iceCandidateFlushTimer = void 0;
1464
+ }
1465
+ const batch = this.pendingIceCandidates;
1466
+ this.pendingIceCandidates = [];
1467
+ if (batch.length === 0 && !isFinal) {
1468
+ return;
1469
+ }
1470
+ this.sendIceCandidates(batch, isFinal).catch((err) => {
1471
+ console.debug("[WebRTCTransport] ICE candidate flush failed:", err);
1472
+ });
1473
+ }
1474
+ cancelPendingIceCandidates() {
1475
+ if (this.iceCandidateFlushTimer !== void 0) {
1476
+ clearTimeout(this.iceCandidateFlushTimer);
1477
+ this.iceCandidateFlushTimer = void 0;
1478
+ }
1479
+ this.pendingIceCandidates = [];
1480
+ }
1395
1481
  pollSdpAnswer() {
1396
1482
  return __async(this, null, function* () {
1397
1483
  console.debug("[WebRTCTransport] Polling for SDP answer...");
@@ -1413,7 +1499,7 @@ var WebRTCTransportClient = class {
1413
1499
  );
1414
1500
  const response = yield fetch(`${this.transportBaseUrl}/sdp_params`, {
1415
1501
  method: "GET",
1416
- headers: this.getHeaders(),
1502
+ headers: yield this.getHeaders(),
1417
1503
  signal: this.signal
1418
1504
  });
1419
1505
  yield this.checkVersionMismatch(response);
@@ -1461,6 +1547,7 @@ var WebRTCTransportClient = class {
1461
1547
  this.resetTransportTimings();
1462
1548
  this.stopPing();
1463
1549
  this.stopStatsPolling();
1550
+ this.cancelPendingIceCandidates();
1464
1551
  if (this.dataChannel) {
1465
1552
  this.dataChannel.close();
1466
1553
  this.dataChannel = void 0;
@@ -1523,6 +1610,7 @@ var WebRTCTransportClient = class {
1523
1610
  return __async(this, null, function* () {
1524
1611
  this.stopPing();
1525
1612
  this.stopStatsPolling();
1613
+ this.cancelPendingIceCandidates();
1526
1614
  for (const name of Array.from(this.publishedTracks.keys())) {
1527
1615
  yield this.unpublishTrack(name);
1528
1616
  }
@@ -1776,8 +1864,21 @@ var WebRTCTransportClient = class {
1776
1864
  this.emit("trackReceived", trackName, event.track, stream);
1777
1865
  };
1778
1866
  this.peerConnection.onicecandidate = (event) => {
1867
+ var _a, _b;
1779
1868
  if (event.candidate) {
1780
- console.debug("[WebRTCTransport] ICE candidate:", event.candidate);
1869
+ this.pendingIceCandidates.push({
1870
+ candidate: event.candidate.candidate,
1871
+ sdp_mid: (_a = event.candidate.sdpMid) != null ? _a : void 0,
1872
+ sdp_mline_index: (_b = event.candidate.sdpMLineIndex) != null ? _b : void 0
1873
+ });
1874
+ if (this.iceCandidateFlushTimer === void 0) {
1875
+ this.iceCandidateFlushTimer = setTimeout(
1876
+ () => this.flushPendingIceCandidates(false),
1877
+ ICE_CANDIDATE_BATCH_WINDOW_MS
1878
+ );
1879
+ }
1880
+ } else {
1881
+ this.flushPendingIceCandidates(true);
1781
1882
  }
1782
1883
  };
1783
1884
  this.peerConnection.onicecandidateerror = (event) => {
@@ -2067,7 +2168,7 @@ function downloadClipAsFile(_0) {
2067
2168
  `Chunk ${i} returned HTTP ${response.status}`
2068
2169
  );
2069
2170
  }
2070
- const data = yield response.arrayBuffer();
2171
+ const data = new Uint8Array(yield response.arrayBuffer());
2071
2172
  parts.push(data);
2072
2173
  bytes += data.byteLength;
2073
2174
  (_a = options.onProgress) == null ? void 0 : _a.call(options, {
@@ -2076,7 +2177,8 @@ function downloadClipAsFile(_0) {
2076
2177
  bytes
2077
2178
  });
2078
2179
  }
2079
- const blob = new Blob(parts, { type: "video/mp4" });
2180
+ const finalBytes = yield maybeRemux(parts);
2181
+ const blob = new Blob([finalBytes], { type: "video/mp4" });
2080
2182
  if (filename === null) {
2081
2183
  return blob;
2082
2184
  }
@@ -2090,6 +2192,145 @@ function downloadClipAsFile(_0) {
2090
2192
  return blob;
2091
2193
  });
2092
2194
  }
2195
+ function maybeRemux(parts) {
2196
+ return __async(this, null, function* () {
2197
+ const input = concatUint8Arrays(parts);
2198
+ try {
2199
+ const MP4Box = yield loadMp4Box();
2200
+ return yield remuxFragmentedToFlat(input, MP4Box);
2201
+ } catch (error) {
2202
+ console.warn(
2203
+ "[Reactor] Clip remux failed, returning fragmented MP4 instead.",
2204
+ error
2205
+ );
2206
+ return input;
2207
+ }
2208
+ });
2209
+ }
2210
+ var __remuxInternals = {
2211
+ loadMp4Box: () => import("mp4box")
2212
+ };
2213
+ function loadMp4Box() {
2214
+ return __remuxInternals.loadMp4Box();
2215
+ }
2216
+ function remuxFragmentedToFlat(input, MP4Box) {
2217
+ return __async(this, null, function* () {
2218
+ return new Promise((resolve, reject) => {
2219
+ const inFile = MP4Box.createFile();
2220
+ const outFile = MP4Box.createFile();
2221
+ outFile.init({ brands: ["isom", "mp42", "avc1", "iso2"] });
2222
+ const inToOutTrack = /* @__PURE__ */ new Map();
2223
+ const trackBaselineDts = /* @__PURE__ */ new Map();
2224
+ let settled = false;
2225
+ const fail = (err) => {
2226
+ if (settled) return;
2227
+ settled = true;
2228
+ reject(err);
2229
+ };
2230
+ inFile.onError = (_module, message) => {
2231
+ fail(new Error(message));
2232
+ };
2233
+ inFile.onReady = (info) => {
2234
+ if (!info.tracks.length) {
2235
+ fail(new Error("no tracks in input"));
2236
+ return;
2237
+ }
2238
+ for (const track of info.tracks) {
2239
+ inFile.setExtractionOptions(track.id, null, { nbSamples: 1e3 });
2240
+ }
2241
+ inFile.start();
2242
+ };
2243
+ inFile.onSamples = (id, _user, samples) => {
2244
+ if (settled || samples.length === 0) return;
2245
+ let outId = inToOutTrack.get(id);
2246
+ let baseline = trackBaselineDts.get(id);
2247
+ if (outId === void 0) {
2248
+ const firstSample = samples[0];
2249
+ const sampleEntry = firstSample.description;
2250
+ const inputTrack = trackInfoById(inFile, id);
2251
+ outId = outFile.addTrack({
2252
+ type: sampleEntry.type,
2253
+ timescale: firstSample.timescale,
2254
+ width: inputTrack == null ? void 0 : inputTrack.track_width,
2255
+ height: inputTrack == null ? void 0 : inputTrack.track_height,
2256
+ language: inputTrack == null ? void 0 : inputTrack.language,
2257
+ hdlr: (inputTrack == null ? void 0 : inputTrack.video) ? "vide" : (inputTrack == null ? void 0 : inputTrack.audio) ? "soun" : void 0,
2258
+ // `boxes` is typed as `Box[]` but `description_boxes`
2259
+ // wants the narrower `BoxKind[]` union — at runtime they
2260
+ // are the same concrete instances, just typed loosely.
2261
+ description_boxes: sampleEntry.boxes
2262
+ });
2263
+ baseline = firstSample.dts;
2264
+ inToOutTrack.set(id, outId);
2265
+ trackBaselineDts.set(id, baseline);
2266
+ }
2267
+ const dtsShift = baseline;
2268
+ for (const sample of samples) {
2269
+ if (!sample.data) continue;
2270
+ outFile.addSample(outId, sample.data, {
2271
+ duration: sample.duration,
2272
+ dts: sample.dts - dtsShift,
2273
+ cts: sample.cts - dtsShift,
2274
+ is_sync: sample.is_sync
2275
+ });
2276
+ }
2277
+ };
2278
+ let buf;
2279
+ try {
2280
+ buf = MP4Box.MP4BoxBuffer.fromArrayBuffer(
2281
+ input.buffer.slice(
2282
+ input.byteOffset,
2283
+ input.byteOffset + input.byteLength
2284
+ ),
2285
+ 0
2286
+ );
2287
+ } catch (error) {
2288
+ fail(error);
2289
+ return;
2290
+ }
2291
+ try {
2292
+ inFile.appendBuffer(buf);
2293
+ inFile.flush();
2294
+ } catch (error) {
2295
+ fail(error);
2296
+ return;
2297
+ }
2298
+ if (settled) return;
2299
+ if (inToOutTrack.size === 0) {
2300
+ fail(new Error("no samples extracted from input"));
2301
+ return;
2302
+ }
2303
+ let output;
2304
+ try {
2305
+ const stream = outFile.getBuffer();
2306
+ output = new Uint8Array(
2307
+ stream.buffer.slice(0, stream.byteLength)
2308
+ );
2309
+ } catch (error) {
2310
+ fail(error);
2311
+ return;
2312
+ }
2313
+ settled = true;
2314
+ resolve(output);
2315
+ });
2316
+ });
2317
+ }
2318
+ function trackInfoById(file, id) {
2319
+ const info = file.getInfo();
2320
+ return info.tracks.find((t) => t.id === id);
2321
+ }
2322
+ function concatUint8Arrays(parts) {
2323
+ if (parts.length === 1) return parts[0];
2324
+ let total = 0;
2325
+ for (const p of parts) total += p.byteLength;
2326
+ const out = new Uint8Array(total);
2327
+ let offset = 0;
2328
+ for (const p of parts) {
2329
+ out.set(p, offset);
2330
+ offset += p.byteLength;
2331
+ }
2332
+ return out;
2333
+ }
2093
2334
  function resolveAgainst(target, base) {
2094
2335
  try {
2095
2336
  return new URL(target, base).toString();
@@ -2399,6 +2640,15 @@ var Reactor = class {
2399
2640
  getCoordinatorBaseUrl: () => this.coordinatorUrl
2400
2641
  });
2401
2642
  }
2643
+ /**
2644
+ * Returns the JWT resolver supplied to the most recent
2645
+ * {@link connect} call, or `undefined` if none was set (pre-connect
2646
+ * or local mode). Used by clip surfaces as a fallback when their
2647
+ * own `getJwt` prop is omitted.
2648
+ */
2649
+ getJwtResolver() {
2650
+ return this.jwtResolver;
2651
+ }
2402
2652
  on(event, handler) {
2403
2653
  if (!this.eventListeners.has(event)) {
2404
2654
  this.eventListeners.set(event, /* @__PURE__ */ new Set());
@@ -2661,7 +2911,10 @@ var Reactor = class {
2661
2911
  }
2662
2912
  /**
2663
2913
  * Connects to the coordinator, creates a session, then establishes
2664
- * the transport using server-declared capabilities.
2914
+ * the transport using server-declared capabilities. `jwtToken` may
2915
+ * be a static string or a {@link JwtSource} resolver; pass a
2916
+ * resolver when the token is short-lived so each Coordinator HTTP
2917
+ * hop sees a fresh value.
2665
2918
  */
2666
2919
  connect(jwtToken, options) {
2667
2920
  return __async(this, null, function* () {
@@ -2674,6 +2927,9 @@ var Reactor = class {
2674
2927
  }
2675
2928
  this.setStatus("connecting");
2676
2929
  this.connectStartTime = performance.now();
2930
+ if (!this.local && jwtToken !== void 0) {
2931
+ this.jwtResolver = normalizeJwtSource(jwtToken);
2932
+ }
2677
2933
  try {
2678
2934
  this.coordinatorClient = this.local ? new LocalCoordinatorClient(this.coordinatorUrl, this.model) : new CoordinatorClient({
2679
2935
  baseUrl: this.coordinatorUrl,
@@ -2937,7 +3193,13 @@ var Reactor = class {
2937
3193
  };
2938
3194
 
2939
3195
  // src/react/ReactorProvider.tsx
2940
- import { useContext, useEffect, useRef, useState } from "react";
3196
+ import {
3197
+ useContext,
3198
+ useEffect,
3199
+ useMemo,
3200
+ useRef,
3201
+ useState
3202
+ } from "react";
2941
3203
 
2942
3204
  // src/core/store.ts
2943
3205
  import { create } from "zustand/react";
@@ -3118,12 +3380,27 @@ function ReactorProvider(_a) {
3118
3380
  var _b = _a, {
3119
3381
  children,
3120
3382
  connectOptions,
3121
- jwtToken
3383
+ jwtToken,
3384
+ getJwt
3122
3385
  } = _b, props = __objRest(_b, [
3123
3386
  "children",
3124
3387
  "connectOptions",
3125
- "jwtToken"
3388
+ "jwtToken",
3389
+ "getJwt"
3126
3390
  ]);
3391
+ const getJwtRef = useRef(getJwt);
3392
+ useEffect(() => {
3393
+ getJwtRef.current = getJwt;
3394
+ });
3395
+ const hasGetJwt = getJwt !== void 0;
3396
+ const stableGetJwt = useMemo(() => {
3397
+ if (!hasGetJwt) return void 0;
3398
+ return () => __async(null, null, function* () {
3399
+ const r = getJwtRef.current;
3400
+ return r ? yield r() : "";
3401
+ });
3402
+ }, [hasGetJwt]);
3403
+ const jwtSource = stableGetJwt != null ? stableGetJwt : jwtToken;
3127
3404
  const storeRef = useRef(void 0);
3128
3405
  const firstRender = useRef(true);
3129
3406
  const [_storeVersion, setStoreVersion] = useState(0);
@@ -3131,7 +3408,7 @@ function ReactorProvider(_a) {
3131
3408
  console.debug("[ReactorProvider] Creating new reactor store");
3132
3409
  storeRef.current = createReactorStore(
3133
3410
  initReactorStore(__spreadProps(__spreadValues({}, props), {
3134
- jwtToken
3411
+ jwtToken: jwtSource
3135
3412
  }))
3136
3413
  );
3137
3414
  console.debug("[ReactorProvider] Reactor store created successfully");
@@ -3156,11 +3433,11 @@ function ReactorProvider(_a) {
3156
3433
  if (firstRender.current) {
3157
3434
  firstRender.current = false;
3158
3435
  const current2 = storeRef.current;
3159
- if (autoConnect && current2.getState().status === "disconnected" && jwtToken) {
3436
+ if (autoConnect && current2.getState().status === "disconnected" && jwtSource) {
3160
3437
  console.debug(
3161
3438
  "[ReactorProvider] Starting autoconnect in first render..."
3162
3439
  );
3163
- current2.getState().connect(jwtToken, pollingOptions).then(() => {
3440
+ current2.getState().connect(jwtSource, pollingOptions).then(() => {
3164
3441
  console.debug(
3165
3442
  "[ReactorProvider] Autoconnect successful in first render"
3166
3443
  );
@@ -3193,7 +3470,7 @@ function ReactorProvider(_a) {
3193
3470
  apiUrl,
3194
3471
  modelName,
3195
3472
  local,
3196
- jwtToken
3473
+ jwtToken: jwtSource
3197
3474
  })
3198
3475
  );
3199
3476
  const current = storeRef.current;
@@ -3201,9 +3478,9 @@ function ReactorProvider(_a) {
3201
3478
  console.debug(
3202
3479
  "[ReactorProvider] Reactor store updated successfully, and increased version"
3203
3480
  );
3204
- if (autoConnect && current.getState().status === "disconnected" && jwtToken) {
3481
+ if (autoConnect && current.getState().status === "disconnected" && jwtSource) {
3205
3482
  console.debug("[ReactorProvider] Starting autoconnect...");
3206
- current.getState().connect(jwtToken, pollingOptions).then(() => {
3483
+ current.getState().connect(jwtSource, pollingOptions).then(() => {
3207
3484
  console.debug("[ReactorProvider] Autoconnect successful");
3208
3485
  }).catch((error) => {
3209
3486
  console.error("[ReactorProvider] Failed to autoconnect:", error);
@@ -3219,7 +3496,7 @@ function ReactorProvider(_a) {
3219
3496
  console.error("[ReactorProvider] Failed to disconnect:", error);
3220
3497
  });
3221
3498
  };
3222
- }, [apiUrl, modelName, autoConnect, local, jwtToken, maxAttempts]);
3499
+ }, [apiUrl, modelName, autoConnect, local, jwtSource, maxAttempts]);
3223
3500
  return /* @__PURE__ */ jsx(ReactorContext.Provider, { value: storeRef.current, children });
3224
3501
  }
3225
3502
  function useReactorStore(selector) {
@@ -3285,7 +3562,7 @@ function useStats() {
3285
3562
  }
3286
3563
 
3287
3564
  // src/react/ReactorView.tsx
3288
- import { useEffect as useEffect3, useMemo, useRef as useRef3 } from "react";
3565
+ import { useEffect as useEffect3, useMemo as useMemo2, useRef as useRef3 } from "react";
3289
3566
  import { jsx as jsx2 } from "react/jsx-runtime";
3290
3567
  function ReactorView({
3291
3568
  track = "main_video",
@@ -3305,7 +3582,7 @@ function ReactorView({
3305
3582
  };
3306
3583
  });
3307
3584
  const videoRef = useRef3(null);
3308
- const mediaStream = useMemo(() => {
3585
+ const mediaStream = useMemo2(() => {
3309
3586
  const tracks = [];
3310
3587
  if (videoMediaTrack) tracks.push(videoMediaTrack);
3311
3588
  if (audioMediaTrack) tracks.push(audioMediaTrack);
@@ -4128,7 +4405,7 @@ function WebcamStream({
4128
4405
  }
4129
4406
 
4130
4407
  // src/react/ClipPlayer.tsx
4131
- import { useEffect as useEffect5, useRef as useRef6, useState as useState5 } from "react";
4408
+ import { useContext as useContext2, useEffect as useEffect5, useRef as useRef6, useState as useState5 } from "react";
4132
4409
  import { jsx as jsx5, jsxs as jsxs3 } from "react/jsx-runtime";
4133
4410
  function ClipPlayer({
4134
4411
  clip,
@@ -4141,13 +4418,16 @@ function ClipPlayer({
4141
4418
  }) {
4142
4419
  const videoRef = useRef6(null);
4143
4420
  const [phase, setPhase] = useState5({ kind: "waiting" });
4421
+ const store = useContext2(ReactorContext);
4144
4422
  const getJwtRef = useRef6(getJwt);
4145
4423
  const autoPlayRef = useRef6(autoPlay);
4146
4424
  const slackMsRef = useRef6(slackMs);
4425
+ const storeRef = useRef6(store);
4147
4426
  useEffect5(() => {
4148
4427
  getJwtRef.current = getJwt;
4149
4428
  autoPlayRef.current = autoPlay;
4150
4429
  slackMsRef.current = slackMs;
4430
+ storeRef.current = store;
4151
4431
  });
4152
4432
  useEffect5(() => {
4153
4433
  const video = videoRef.current;
@@ -4209,9 +4489,13 @@ function ClipPlayer({
4209
4489
  hlsInstance = hls;
4210
4490
  });
4211
4491
  const setup = () => __async(null, null, function* () {
4492
+ var _a;
4212
4493
  try {
4213
4494
  setPhase({ kind: "waiting" });
4214
- const jwt = getJwtRef.current ? yield getJwtRef.current() : void 0;
4495
+ const explicit = getJwtRef.current;
4496
+ const fallback = (_a = storeRef.current) == null ? void 0 : _a.getState().internal.reactor.getJwtResolver();
4497
+ const resolver = explicit != null ? explicit : fallback;
4498
+ const jwt = resolver ? yield resolver() : void 0;
4215
4499
  if (cancelled) return;
4216
4500
  const body = yield fetchPlaylist(clip.playlistUrl, {
4217
4501
  predictedReadyAtMs: clip.predictedReadyAtMs,
@@ -4314,10 +4598,11 @@ function ClipPlayer({
4314
4598
  }
4315
4599
 
4316
4600
  // src/react/useClipDownload.ts
4317
- import { useCallback as useCallback2, useEffect as useEffect6, useRef as useRef7, useState as useState6 } from "react";
4601
+ import { useCallback as useCallback2, useContext as useContext3, useEffect as useEffect6, useRef as useRef7, useState as useState6 } from "react";
4318
4602
  function useClipDownload(clip, options = {}) {
4319
4603
  var _a;
4320
4604
  const [state, setState] = useState6({ kind: "idle" });
4605
+ const store = useContext3(ReactorContext);
4321
4606
  const clipRef = useRef7(clip);
4322
4607
  const filenameRef = useRef7(
4323
4608
  (_a = options.filename) != null ? _a : "reactor-clip.mp4"
@@ -4334,7 +4619,10 @@ function useClipDownload(clip, options = {}) {
4334
4619
  inFlightRef.current = true;
4335
4620
  setState({ kind: "downloading", fetched: 0, total: 0 });
4336
4621
  try {
4337
- const jwt = getJwtRef.current ? yield getJwtRef.current() : void 0;
4622
+ const explicit = getJwtRef.current;
4623
+ const fallback = store == null ? void 0 : store.getState().internal.reactor.getJwtResolver();
4624
+ const resolver = explicit != null ? explicit : fallback;
4625
+ const jwt = resolver ? yield resolver() : void 0;
4338
4626
  const blob = yield downloadClipAsFile(
4339
4627
  clipRef.current,
4340
4628
  filenameRef.current,
@@ -4352,7 +4640,7 @@ function useClipDownload(clip, options = {}) {
4352
4640
  } finally {
4353
4641
  inFlightRef.current = false;
4354
4642
  }
4355
- }), []);
4643
+ }), [store]);
4356
4644
  const reset = useCallback2(() => setState({ kind: "idle" }), []);
4357
4645
  return { state, download, reset };
4358
4646
  }
@@ -4428,6 +4716,7 @@ export {
4428
4716
  downloadClipAsFile,
4429
4717
  fetchPlaylist,
4430
4718
  isAbortError,
4719
+ normalizeJwtSource,
4431
4720
  parsePlaylist,
4432
4721
  rewriteUrlHost,
4433
4722
  useClipDownload,