@reactor-team/js-sdk 2.9.3 → 2.10.1

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,14 +77,38 @@ 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.9.3",
87
- description: "Reactor JavaScript frontend SDK",
94
+ version: "2.10.1",
95
+ description: "Reactor JavaScript frontend SDK \u2014 connect React and TypeScript apps to real-time AI video models on Reactor.",
96
+ license: "Apache-2.0",
97
+ repository: {
98
+ type: "git",
99
+ url: "https://github.com/reactor-team/js-sdk.git"
100
+ },
101
+ keywords: [
102
+ "reactor",
103
+ "sdk",
104
+ "frontend",
105
+ "react",
106
+ "webrtc",
107
+ "real-time",
108
+ "video",
109
+ "ai"
110
+ ],
111
+ author: "Reactor Technologies, Inc.",
88
112
  main: "dist/index.js",
89
113
  module: "dist/index.mjs",
90
114
  types: "dist/index.d.ts",
@@ -95,11 +119,19 @@ var package_default = {
95
119
  require: "./dist/index.js"
96
120
  }
97
121
  },
122
+ sideEffects: false,
123
+ engines: {
124
+ node: ">=18"
125
+ },
98
126
  files: [
99
127
  "dist",
100
- "README.md"
128
+ "README.md",
129
+ "LICENSE",
130
+ "NOTICE"
101
131
  ],
102
132
  scripts: {
133
+ prepack: "cp ../../LICENSE ../../NOTICE .",
134
+ postpack: "rm -f LICENSE NOTICE",
103
135
  build: "tsup",
104
136
  dev: "tsup --watch",
105
137
  test: "vitest run",
@@ -109,46 +141,35 @@ var package_default = {
109
141
  format: "prettier --write .",
110
142
  "format:check": "prettier --check ."
111
143
  },
112
- keywords: [
113
- "reactor",
114
- "frontend",
115
- "sdk"
116
- ],
117
- author: "Reactor Technologies, Inc.",
118
144
  reactor: {
119
145
  apiVersion: 1,
120
146
  webrtcVersion: "1.0"
121
147
  },
122
- license: "MIT",
123
- repository: {
124
- type: "git",
125
- url: "https://github.com/reactor-team/js-sdk.git"
126
- },
127
148
  packageManager: "pnpm@10.12.1",
128
- devDependencies: {
129
- "@roamhq/wrtc": "^0.8.0",
130
- "@types/inquirer": "^9.0.9",
131
- "@types/node": "^20",
132
- "@types/react": "^18.2.8",
133
- "@types/sdp-transform": "^2.15.0",
134
- "@types/ws": "^8.18.1",
135
- prettier: "^3.6.2",
136
- tsup: "^8.5.0",
137
- typescript: "^5.8.3",
138
- vitest: "^3.0.0"
139
- },
140
149
  dependencies: {
141
- "@bufbuild/protobuf": "^2.0.0",
142
- chalk: "^5.3.0",
143
- inquirer: "^9.3.0",
150
+ mp4box: "^2.3.0",
144
151
  "sdp-transform": "^3.0.0",
145
- "simple-git": "^3.24.0",
146
- ws: "^8.18.3",
147
- zod: "^4.0.5"
152
+ zod: "^4.4.3"
148
153
  },
149
154
  peerDependencies: {
155
+ "hls.js": "^1.6.0",
150
156
  react: "^17.0.0 || ^18.0.0 || ^19.0.0",
151
157
  zustand: "^5.0.6"
158
+ },
159
+ peerDependenciesMeta: {
160
+ "hls.js": {
161
+ optional: true
162
+ }
163
+ },
164
+ devDependencies: {
165
+ "@roamhq/wrtc": "^0.8.0",
166
+ "@types/node": "^25",
167
+ "@types/react": "^19.2.15",
168
+ "hls.js": "^1.6.0",
169
+ prettier: "^3.6.2",
170
+ tsup: "^8.5.0",
171
+ typescript: "^5.8.3",
172
+ vitest: "^4.1.7"
152
173
  }
153
174
  };
154
175
 
@@ -251,7 +272,7 @@ var SESSION_POLL_DEFAULT_MAX_ATTEMPTS = 20;
251
272
  var CoordinatorClient = class {
252
273
  constructor(options) {
253
274
  this.baseUrl = options.baseUrl;
254
- this.jwtToken = options.jwtToken;
275
+ this.resolveJwt = normalizeJwtSource(options.jwtToken);
255
276
  this.model = options.model;
256
277
  this.abortController = new AbortController();
257
278
  }
@@ -271,14 +292,22 @@ var CoordinatorClient = class {
271
292
  return this.abortController.signal;
272
293
  }
273
294
  /**
274
- * Returns authorization + versioning headers for all coordinator requests.
295
+ * Returns authorization + versioning headers for all coordinator
296
+ * requests. Async so the JWT resolver can fetch a fresh token if
297
+ * needed; an empty token suppresses the `Authorization` header.
275
298
  */
276
299
  getHeaders() {
277
- return {
278
- Authorization: `Bearer ${this.jwtToken}`,
279
- [API_VERSION_HEADER]: String(REACTOR_API_VERSION),
280
- [API_ACCEPT_VERSION_HEADER]: String(REACTOR_API_VERSION)
281
- };
300
+ return __async(this, null, function* () {
301
+ const headers = {
302
+ [API_VERSION_HEADER]: String(REACTOR_API_VERSION),
303
+ [API_ACCEPT_VERSION_HEADER]: String(REACTOR_API_VERSION)
304
+ };
305
+ const jwt = yield this.resolveJwt();
306
+ if (jwt) {
307
+ headers.Authorization = `Bearer ${jwt}`;
308
+ }
309
+ return headers;
310
+ });
282
311
  }
283
312
  /**
284
313
  * Checks an HTTP response for version mismatch errors (426, 501).
@@ -339,7 +368,7 @@ var CoordinatorClient = class {
339
368
  }, extraArgs ? { extra_args: extraArgs } : {});
340
369
  const response = yield fetch(`${this.baseUrl}/sessions`, {
341
370
  method: "POST",
342
- headers: __spreadProps(__spreadValues({}, this.getHeaders()), {
371
+ headers: __spreadProps(__spreadValues({}, yield this.getHeaders()), {
343
372
  "Content-Type": "application/json"
344
373
  }),
345
374
  body: JSON.stringify(requestBody),
@@ -394,7 +423,7 @@ var CoordinatorClient = class {
394
423
  `${this.baseUrl}/sessions/${this.currentSessionId}`,
395
424
  {
396
425
  method: "GET",
397
- headers: this.getHeaders(),
426
+ headers: yield this.getHeaders(),
398
427
  signal: this.signal
399
428
  }
400
429
  );
@@ -447,7 +476,7 @@ var CoordinatorClient = class {
447
476
  `${this.baseUrl}/sessions/${this.currentSessionId}`,
448
477
  {
449
478
  method: "GET",
450
- headers: this.getHeaders(),
479
+ headers: yield this.getHeaders(),
451
480
  signal: this.signal
452
481
  }
453
482
  );
@@ -472,7 +501,7 @@ var CoordinatorClient = class {
472
501
  `${this.baseUrl}/sessions/${this.currentSessionId}/info`,
473
502
  {
474
503
  method: "GET",
475
- headers: this.getHeaders(),
504
+ headers: yield this.getHeaders(),
476
505
  signal: this.signal
477
506
  }
478
507
  );
@@ -504,7 +533,7 @@ var CoordinatorClient = class {
504
533
  `${this.baseUrl}/sessions/${this.currentSessionId}`,
505
534
  {
506
535
  method: "PUT",
507
- headers: this.getHeaders(),
536
+ headers: yield this.getHeaders(),
508
537
  signal: this.signal
509
538
  }
510
539
  );
@@ -536,7 +565,7 @@ var CoordinatorClient = class {
536
565
  `${this.baseUrl}/sessions/${this.currentSessionId}`,
537
566
  __spreadProps(__spreadValues({
538
567
  method: "DELETE",
539
- headers: __spreadValues(__spreadValues({}, this.getHeaders()), body ? { "Content-Type": "application/json" } : {})
568
+ headers: __spreadValues(__spreadValues({}, yield this.getHeaders()), body ? { "Content-Type": "application/json" } : {})
540
569
  }, body ? { body: JSON.stringify(body) } : {}), {
541
570
  signal: this.signal
542
571
  })
@@ -575,7 +604,7 @@ var CoordinatorClient = class {
575
604
  `${this.baseUrl}/sessions/${sessionId}/uploads`,
576
605
  {
577
606
  method: "POST",
578
- headers: __spreadProps(__spreadValues({}, this.getHeaders()), {
607
+ headers: __spreadProps(__spreadValues({}, yield this.getHeaders()), {
579
608
  "Content-Type": "application/json"
580
609
  }),
581
610
  body: JSON.stringify(request),
@@ -607,11 +636,14 @@ var LocalCoordinatorClient = class extends CoordinatorClient {
607
636
  model
608
637
  });
609
638
  }
639
+ // Local runtime endpoints are auth-free; skip the Authorization header.
610
640
  getHeaders() {
611
- return {
612
- [API_VERSION_HEADER]: String(REACTOR_API_VERSION),
613
- [API_ACCEPT_VERSION_HEADER]: String(REACTOR_API_VERSION)
614
- };
641
+ return __async(this, null, function* () {
642
+ return {
643
+ [API_VERSION_HEADER]: String(REACTOR_API_VERSION),
644
+ [API_ACCEPT_VERSION_HEADER]: String(REACTOR_API_VERSION)
645
+ };
646
+ });
615
647
  }
616
648
  /**
617
649
  * Starts a session on the local runtime.
@@ -625,7 +657,7 @@ var LocalCoordinatorClient = class extends CoordinatorClient {
625
657
  console.debug("[LocalCoordinatorClient] Starting session...");
626
658
  const response = yield fetch(`${this.baseUrl}/start_session`, {
627
659
  method: "POST",
628
- headers: __spreadProps(__spreadValues({}, this.getHeaders()), {
660
+ headers: __spreadProps(__spreadValues({}, yield this.getHeaders()), {
629
661
  "Content-Type": "application/json"
630
662
  }),
631
663
  body: JSON.stringify(__spreadValues({}, extraArgs ? { extra_args: extraArgs } : {})),
@@ -681,7 +713,7 @@ var LocalCoordinatorClient = class extends CoordinatorClient {
681
713
  try {
682
714
  yield fetch(`${this.baseUrl}/stop_session`, {
683
715
  method: "POST",
684
- headers: this.getHeaders(),
716
+ headers: yield this.getHeaders(),
685
717
  signal: this.signal
686
718
  });
687
719
  } catch (error) {
@@ -1261,7 +1293,7 @@ var WebRTCTransportClient = class {
1261
1293
  var _a, _b;
1262
1294
  this.baseUrl = config.baseUrl;
1263
1295
  this.sessionId = config.sessionId;
1264
- this.jwtToken = config.jwtToken;
1296
+ this.resolveJwt = normalizeJwtSource(config.jwtToken);
1265
1297
  this.webrtcVersion = (_a = config.webrtcVersion) != null ? _a : REACTOR_WEBRTC_VERSION;
1266
1298
  this.maxPollAttempts = (_b = config.maxPollAttempts) != null ? _b : DEFAULT_MAX_POLL_ATTEMPTS;
1267
1299
  this.abortController = new AbortController();
@@ -1292,11 +1324,19 @@ var WebRTCTransportClient = class {
1292
1324
  get transportBaseUrl() {
1293
1325
  return `${this.baseUrl}/sessions/${this.sessionId}/transport/webrtc`;
1294
1326
  }
1327
+ // Async so the JWT resolver can fetch a fresh token if needed; an
1328
+ // empty token suppresses the `Authorization` header.
1295
1329
  getHeaders() {
1296
- return {
1297
- Authorization: `Bearer ${this.jwtToken}`,
1298
- [WEBRTC_VERSION_HEADER]: this.webrtcVersion
1299
- };
1330
+ return __async(this, null, function* () {
1331
+ const headers = {
1332
+ [WEBRTC_VERSION_HEADER]: this.webrtcVersion
1333
+ };
1334
+ const jwt = yield this.resolveJwt();
1335
+ if (jwt) {
1336
+ headers.Authorization = `Bearer ${jwt}`;
1337
+ }
1338
+ return headers;
1339
+ });
1300
1340
  }
1301
1341
  checkVersionMismatch(response) {
1302
1342
  return __async(this, null, function* () {
@@ -1338,7 +1378,7 @@ var WebRTCTransportClient = class {
1338
1378
  console.debug("[WebRTCTransport] Fetching ICE servers...");
1339
1379
  const response = yield fetch(`${this.transportBaseUrl}/ice_servers`, {
1340
1380
  method: "GET",
1341
- headers: this.getHeaders(),
1381
+ headers: yield this.getHeaders(),
1342
1382
  signal: this.signal
1343
1383
  });
1344
1384
  yield this.checkVersionMismatch(response);
@@ -1368,7 +1408,7 @@ var WebRTCTransportClient = class {
1368
1408
  };
1369
1409
  const response = yield fetch(`${this.transportBaseUrl}/sdp_params`, {
1370
1410
  method,
1371
- headers: __spreadProps(__spreadValues({}, this.getHeaders()), {
1411
+ headers: __spreadProps(__spreadValues({}, yield this.getHeaders()), {
1372
1412
  "Content-Type": "application/json"
1373
1413
  }),
1374
1414
  body: JSON.stringify(requestBody),
@@ -1405,7 +1445,7 @@ var WebRTCTransportClient = class {
1405
1445
  );
1406
1446
  const response = yield fetch(`${this.transportBaseUrl}/sdp_params`, {
1407
1447
  method: "GET",
1408
- headers: this.getHeaders(),
1448
+ headers: yield this.getHeaders(),
1409
1449
  signal: this.signal
1410
1450
  });
1411
1451
  yield this.checkVersionMismatch(response);
@@ -1825,19 +1865,682 @@ var WebRTCTransportClient = class {
1825
1865
  };
1826
1866
 
1827
1867
  // src/core/Reactor.ts
1868
+ import { z as z3 } from "zod";
1869
+
1870
+ // src/utils/recording.ts
1828
1871
  import { z as z2 } from "zod";
1872
+ var RuntimeRecordingMessageType = {
1873
+ REQUEST_CLIP: "requestClip",
1874
+ REQUEST_RECORDING: "requestRecording",
1875
+ CLIP_READY: "clipReady",
1876
+ CLIP_FAILED: "clipFailed"
1877
+ };
1878
+ var RecordingError = class extends Error {
1879
+ constructor(code, reason) {
1880
+ super(`${code}: ${reason}`);
1881
+ this.code = code;
1882
+ this.reason = reason;
1883
+ this.name = "RecordingError";
1884
+ }
1885
+ };
1886
+ var ClipReadyPayloadSchema = z2.object({
1887
+ session_id: z2.string(),
1888
+ kind: z2.enum(["snap", "recording"]),
1889
+ start_marker: z2.number(),
1890
+ end_marker: z2.number(),
1891
+ now_marker: z2.number(),
1892
+ predicted_ready_at_ms: z2.number(),
1893
+ playlist_url: z2.string()
1894
+ }).passthrough();
1895
+ var ClipFailedPayloadSchema = z2.object({
1896
+ reason: z2.string().default("unknown")
1897
+ }).passthrough();
1898
+ function clipFromPayload(payload, options = {}) {
1899
+ const playlistUrl = options.coordinatorBaseUrl ? rewriteUrlHost(payload.playlist_url, options.coordinatorBaseUrl) : payload.playlist_url;
1900
+ return {
1901
+ sessionId: payload.session_id,
1902
+ kind: payload.kind,
1903
+ startMarker: payload.start_marker,
1904
+ endMarker: payload.end_marker,
1905
+ nowMarker: payload.now_marker,
1906
+ predictedReadyAtMs: payload.predicted_ready_at_ms,
1907
+ playlistUrl
1908
+ };
1909
+ }
1910
+ function rewriteUrlHost(target, base) {
1911
+ try {
1912
+ if (!/^[a-z][a-z0-9+.-]*:/i.test(target)) {
1913
+ return new URL(target, base).toString();
1914
+ }
1915
+ const baseUrl = new URL(base);
1916
+ const parsed = new URL(target);
1917
+ parsed.protocol = baseUrl.protocol;
1918
+ parsed.hostname = baseUrl.hostname;
1919
+ parsed.port = baseUrl.port;
1920
+ return parsed.toString();
1921
+ } catch (e) {
1922
+ return target;
1923
+ }
1924
+ }
1925
+ var DEFAULT_PLAYLIST_POLL_SLACK_MS = 15e3;
1926
+ function fetchPlaylist(_0) {
1927
+ return __async(this, arguments, function* (playlistUrl, options = {}) {
1928
+ var _a, _b, _c, _d;
1929
+ const slackMs = (_a = options.slackMs) != null ? _a : DEFAULT_PLAYLIST_POLL_SLACK_MS;
1930
+ const minDelay = Math.max(0, (_b = options.minRetryDelayMs) != null ? _b : 200);
1931
+ const maxDelay = Math.max(minDelay, (_c = options.maxRetryDelayMs) != null ? _c : 2e3);
1932
+ const fallbackMaxRetries = (_d = options.maxRetries) != null ? _d : 5;
1933
+ const hasDeadline = typeof options.predictedReadyAtMs === "number";
1934
+ const startedPollingAt = Date.now();
1935
+ const deadlineMs = hasDeadline ? Math.max(options.predictedReadyAtMs, startedPollingAt) + slackMs : void 0;
1936
+ const headers = options.jwt ? { Authorization: `Bearer ${options.jwt}` } : void 0;
1937
+ let attempt = 0;
1938
+ let lastStatus = 0;
1939
+ while (true) {
1940
+ let response;
1941
+ try {
1942
+ response = yield fetch(playlistUrl, {
1943
+ signal: options.signal,
1944
+ headers
1945
+ });
1946
+ } catch (error) {
1947
+ throw new RecordingError(
1948
+ "PLAYLIST_FETCH_FAILED",
1949
+ `Network error fetching playlist: ${error.message}`
1950
+ );
1951
+ }
1952
+ lastStatus = response.status;
1953
+ if (response.status === 202) {
1954
+ if (hasDeadline) {
1955
+ if (Date.now() >= deadlineMs) {
1956
+ throw new RecordingError(
1957
+ "CLIP_NOT_READY",
1958
+ `Boundary chunk still pending after ${slackMs}ms grace (predicted ready ${new Date(
1959
+ options.predictedReadyAtMs
1960
+ ).toISOString()}). Runtime may have crashed mid-clip.`
1961
+ );
1962
+ }
1963
+ } else if (attempt >= fallbackMaxRetries) {
1964
+ throw new RecordingError(
1965
+ "CLIP_NOT_READY",
1966
+ `Manifest still pending after ${attempt + 1} attempts (last status ${lastStatus})`
1967
+ );
1968
+ }
1969
+ const headerDelay = parseRetryAfter(
1970
+ response.headers.get("Retry-After"),
1971
+ minDelay
1972
+ );
1973
+ const delay = Math.min(maxDelay, Math.max(minDelay, headerDelay));
1974
+ const clampedDelay = hasDeadline ? Math.min(delay, Math.max(0, deadlineMs - Date.now())) : delay;
1975
+ yield sleep(clampedDelay, options.signal);
1976
+ attempt++;
1977
+ continue;
1978
+ }
1979
+ if (response.status === 200) {
1980
+ return yield response.text();
1981
+ }
1982
+ if (response.status === 410) {
1983
+ throw new RecordingError(
1984
+ "CLIP_GONE",
1985
+ "Clip is no longer available (chunks aged out or session unknown)"
1986
+ );
1987
+ }
1988
+ if (response.status === 404) {
1989
+ throw new RecordingError(
1990
+ "CLIP_GONE",
1991
+ "Session not found for clip playlist"
1992
+ );
1993
+ }
1994
+ throw new RecordingError(
1995
+ "PLAYLIST_FETCH_FAILED",
1996
+ `Manifest endpoint returned HTTP ${response.status}`
1997
+ );
1998
+ }
1999
+ });
2000
+ }
2001
+ function parsePlaylist(manifestBody, playlistUrl) {
2002
+ let initUrl;
2003
+ const segments = [];
2004
+ const lines = manifestBody.split(/\r?\n/);
2005
+ for (const line of lines) {
2006
+ const trimmed = line.trim();
2007
+ if (!trimmed) continue;
2008
+ if (trimmed.startsWith("#EXT-X-MAP")) {
2009
+ const match = trimmed.match(/URI="([^"]+)"/);
2010
+ if (match) {
2011
+ initUrl = resolveAgainst(match[1], playlistUrl);
2012
+ }
2013
+ continue;
2014
+ }
2015
+ if (trimmed.startsWith("#")) {
2016
+ continue;
2017
+ }
2018
+ segments.push(resolveAgainst(trimmed, playlistUrl));
2019
+ }
2020
+ if (!initUrl) {
2021
+ throw new RecordingError(
2022
+ "INVALID_PLAYLIST",
2023
+ "Playlist is missing an #EXT-X-MAP init segment URI"
2024
+ );
2025
+ }
2026
+ if (segments.length === 0) {
2027
+ throw new RecordingError(
2028
+ "INVALID_PLAYLIST",
2029
+ "Playlist contains no media segments"
2030
+ );
2031
+ }
2032
+ return { initUrl, segmentUrls: segments };
2033
+ }
2034
+ function createPlayableManifestUrl(manifestBody, playlistUrl) {
2035
+ if (typeof Blob === "undefined" || typeof URL === "undefined" || typeof URL.createObjectURL !== "function") {
2036
+ throw new RecordingError(
2037
+ "INVALID_PLAYLIST",
2038
+ "createPlayableManifestUrl requires a browser environment with URL.createObjectURL"
2039
+ );
2040
+ }
2041
+ const rewritten = absolutizeManifestUrls(manifestBody, playlistUrl);
2042
+ const blob = new Blob([rewritten], {
2043
+ type: "application/vnd.apple.mpegurl"
2044
+ });
2045
+ return URL.createObjectURL(blob);
2046
+ }
2047
+ function absolutizeManifestUrls(manifestBody, playlistUrl) {
2048
+ const eol = manifestBody.includes("\r\n") ? "\r\n" : "\n";
2049
+ const lines = manifestBody.split(/\r?\n/);
2050
+ const out = [];
2051
+ for (const line of lines) {
2052
+ if (line.startsWith("#EXT-X-MAP")) {
2053
+ out.push(
2054
+ line.replace(
2055
+ /URI="([^"]+)"/,
2056
+ (_, uri) => `URI="${resolveAgainst(uri, playlistUrl)}"`
2057
+ )
2058
+ );
2059
+ continue;
2060
+ }
2061
+ const trimmed = line.trim();
2062
+ if (!trimmed || trimmed.startsWith("#")) {
2063
+ out.push(line);
2064
+ continue;
2065
+ }
2066
+ out.push(resolveAgainst(trimmed, playlistUrl));
2067
+ }
2068
+ return out.join(eol);
2069
+ }
2070
+ function downloadClipAsFile(_0) {
2071
+ return __async(this, arguments, function* (clip, filename = "reactor-clip.mp4", options = {}) {
2072
+ var _a;
2073
+ const manifestBody = yield fetchPlaylist(clip.playlistUrl, {
2074
+ predictedReadyAtMs: clip.predictedReadyAtMs,
2075
+ signal: options.signal,
2076
+ jwt: options.jwt
2077
+ });
2078
+ const { initUrl, segmentUrls } = parsePlaylist(
2079
+ manifestBody,
2080
+ clip.playlistUrl
2081
+ );
2082
+ const orderedUrls = [initUrl, ...segmentUrls];
2083
+ const parts = [];
2084
+ let bytes = 0;
2085
+ for (let i = 0; i < orderedUrls.length; i++) {
2086
+ const url = orderedUrls[i];
2087
+ let response;
2088
+ try {
2089
+ response = yield fetch(url, { signal: options.signal });
2090
+ } catch (error) {
2091
+ throw new RecordingError(
2092
+ "CHUNK_FETCH_FAILED",
2093
+ `Network error fetching chunk ${i}: ${error.message}`
2094
+ );
2095
+ }
2096
+ if (!response.ok) {
2097
+ throw new RecordingError(
2098
+ "CHUNK_FETCH_FAILED",
2099
+ `Chunk ${i} returned HTTP ${response.status}`
2100
+ );
2101
+ }
2102
+ const data = new Uint8Array(yield response.arrayBuffer());
2103
+ parts.push(data);
2104
+ bytes += data.byteLength;
2105
+ (_a = options.onProgress) == null ? void 0 : _a.call(options, {
2106
+ fetched: i + 1,
2107
+ total: orderedUrls.length,
2108
+ bytes
2109
+ });
2110
+ }
2111
+ const finalBytes = yield maybeRemux(parts);
2112
+ const blob = new Blob([finalBytes], { type: "video/mp4" });
2113
+ if (filename === null) {
2114
+ return blob;
2115
+ }
2116
+ if (typeof document === "undefined" || typeof URL.createObjectURL !== "function") {
2117
+ throw new RecordingError(
2118
+ "DOWNLOAD_UNSUPPORTED",
2119
+ "downloadClipAsFile requires a DOM environment; pass filename=null to skip the download trigger"
2120
+ );
2121
+ }
2122
+ triggerBrowserDownload(blob, filename);
2123
+ return blob;
2124
+ });
2125
+ }
2126
+ function maybeRemux(parts) {
2127
+ return __async(this, null, function* () {
2128
+ const input = concatUint8Arrays(parts);
2129
+ try {
2130
+ const MP4Box = yield loadMp4Box();
2131
+ return yield remuxFragmentedToFlat(input, MP4Box);
2132
+ } catch (error) {
2133
+ console.warn(
2134
+ "[Reactor] Clip remux failed, returning fragmented MP4 instead.",
2135
+ error
2136
+ );
2137
+ return input;
2138
+ }
2139
+ });
2140
+ }
2141
+ var __remuxInternals = {
2142
+ loadMp4Box: () => import("mp4box")
2143
+ };
2144
+ function loadMp4Box() {
2145
+ return __remuxInternals.loadMp4Box();
2146
+ }
2147
+ function remuxFragmentedToFlat(input, MP4Box) {
2148
+ return __async(this, null, function* () {
2149
+ return new Promise((resolve, reject) => {
2150
+ const inFile = MP4Box.createFile();
2151
+ const outFile = MP4Box.createFile();
2152
+ outFile.init({ brands: ["isom", "mp42", "avc1", "iso2"] });
2153
+ const inToOutTrack = /* @__PURE__ */ new Map();
2154
+ const trackBaselineDts = /* @__PURE__ */ new Map();
2155
+ let settled = false;
2156
+ const fail = (err) => {
2157
+ if (settled) return;
2158
+ settled = true;
2159
+ reject(err);
2160
+ };
2161
+ inFile.onError = (_module, message) => {
2162
+ fail(new Error(message));
2163
+ };
2164
+ inFile.onReady = (info) => {
2165
+ if (!info.tracks.length) {
2166
+ fail(new Error("no tracks in input"));
2167
+ return;
2168
+ }
2169
+ for (const track of info.tracks) {
2170
+ inFile.setExtractionOptions(track.id, null, { nbSamples: 1e3 });
2171
+ }
2172
+ inFile.start();
2173
+ };
2174
+ inFile.onSamples = (id, _user, samples) => {
2175
+ if (settled || samples.length === 0) return;
2176
+ let outId = inToOutTrack.get(id);
2177
+ let baseline = trackBaselineDts.get(id);
2178
+ if (outId === void 0) {
2179
+ const firstSample = samples[0];
2180
+ const sampleEntry = firstSample.description;
2181
+ const inputTrack = trackInfoById(inFile, id);
2182
+ outId = outFile.addTrack({
2183
+ type: sampleEntry.type,
2184
+ timescale: firstSample.timescale,
2185
+ width: inputTrack == null ? void 0 : inputTrack.track_width,
2186
+ height: inputTrack == null ? void 0 : inputTrack.track_height,
2187
+ language: inputTrack == null ? void 0 : inputTrack.language,
2188
+ hdlr: (inputTrack == null ? void 0 : inputTrack.video) ? "vide" : (inputTrack == null ? void 0 : inputTrack.audio) ? "soun" : void 0,
2189
+ // `boxes` is typed as `Box[]` but `description_boxes`
2190
+ // wants the narrower `BoxKind[]` union — at runtime they
2191
+ // are the same concrete instances, just typed loosely.
2192
+ description_boxes: sampleEntry.boxes
2193
+ });
2194
+ baseline = firstSample.dts;
2195
+ inToOutTrack.set(id, outId);
2196
+ trackBaselineDts.set(id, baseline);
2197
+ }
2198
+ const dtsShift = baseline;
2199
+ for (const sample of samples) {
2200
+ if (!sample.data) continue;
2201
+ outFile.addSample(outId, sample.data, {
2202
+ duration: sample.duration,
2203
+ dts: sample.dts - dtsShift,
2204
+ cts: sample.cts - dtsShift,
2205
+ is_sync: sample.is_sync
2206
+ });
2207
+ }
2208
+ };
2209
+ let buf;
2210
+ try {
2211
+ buf = MP4Box.MP4BoxBuffer.fromArrayBuffer(
2212
+ input.buffer.slice(
2213
+ input.byteOffset,
2214
+ input.byteOffset + input.byteLength
2215
+ ),
2216
+ 0
2217
+ );
2218
+ } catch (error) {
2219
+ fail(error);
2220
+ return;
2221
+ }
2222
+ try {
2223
+ inFile.appendBuffer(buf);
2224
+ inFile.flush();
2225
+ } catch (error) {
2226
+ fail(error);
2227
+ return;
2228
+ }
2229
+ if (settled) return;
2230
+ if (inToOutTrack.size === 0) {
2231
+ fail(new Error("no samples extracted from input"));
2232
+ return;
2233
+ }
2234
+ let output;
2235
+ try {
2236
+ const stream = outFile.getBuffer();
2237
+ output = new Uint8Array(
2238
+ stream.buffer.slice(0, stream.byteLength)
2239
+ );
2240
+ } catch (error) {
2241
+ fail(error);
2242
+ return;
2243
+ }
2244
+ settled = true;
2245
+ resolve(output);
2246
+ });
2247
+ });
2248
+ }
2249
+ function trackInfoById(file, id) {
2250
+ const info = file.getInfo();
2251
+ return info.tracks.find((t) => t.id === id);
2252
+ }
2253
+ function concatUint8Arrays(parts) {
2254
+ if (parts.length === 1) return parts[0];
2255
+ let total = 0;
2256
+ for (const p of parts) total += p.byteLength;
2257
+ const out = new Uint8Array(total);
2258
+ let offset = 0;
2259
+ for (const p of parts) {
2260
+ out.set(p, offset);
2261
+ offset += p.byteLength;
2262
+ }
2263
+ return out;
2264
+ }
2265
+ function resolveAgainst(target, base) {
2266
+ try {
2267
+ return new URL(target, base).toString();
2268
+ } catch (e) {
2269
+ return target;
2270
+ }
2271
+ }
2272
+ function parseRetryAfter(header, fallbackMs) {
2273
+ if (!header) return fallbackMs;
2274
+ const seconds = Number(header);
2275
+ if (Number.isFinite(seconds) && seconds >= 0) {
2276
+ return seconds * 1e3;
2277
+ }
2278
+ const dateMs = Date.parse(header);
2279
+ if (!Number.isNaN(dateMs)) {
2280
+ return Math.max(0, dateMs - Date.now());
2281
+ }
2282
+ return fallbackMs;
2283
+ }
2284
+ function sleep(ms, signal) {
2285
+ return new Promise((resolve, reject) => {
2286
+ if (signal == null ? void 0 : signal.aborted) {
2287
+ reject(new DOMException("Aborted", "AbortError"));
2288
+ return;
2289
+ }
2290
+ const timer = setTimeout(() => {
2291
+ signal == null ? void 0 : signal.removeEventListener("abort", onAbort);
2292
+ resolve();
2293
+ }, ms);
2294
+ const onAbort = () => {
2295
+ clearTimeout(timer);
2296
+ reject(new DOMException("Aborted", "AbortError"));
2297
+ };
2298
+ signal == null ? void 0 : signal.addEventListener("abort", onAbort, { once: true });
2299
+ });
2300
+ }
2301
+ function triggerBrowserDownload(blob, filename) {
2302
+ const objectUrl = URL.createObjectURL(blob);
2303
+ try {
2304
+ const a = document.createElement("a");
2305
+ a.href = objectUrl;
2306
+ a.download = filename;
2307
+ a.style.display = "none";
2308
+ document.body.appendChild(a);
2309
+ a.click();
2310
+ a.remove();
2311
+ } finally {
2312
+ URL.revokeObjectURL(objectUrl);
2313
+ }
2314
+ }
2315
+
2316
+ // src/core/RecordingClient.ts
2317
+ var DEFAULT_CLIP_REQUEST_TIMEOUT_MS = 1e4;
2318
+ var RecordingClient = class {
2319
+ constructor(host, options = {}) {
2320
+ this.host = host;
2321
+ // FIFO queue: the runtime processes requests in receipt order and
2322
+ // `clipFailed` carries no discriminator, so FIFO matching is the
2323
+ // simplest correct correlator.
2324
+ this.pendingClipRequests = [];
2325
+ /** Cleanup handles for the host event subscriptions. */
2326
+ this.unsubscribers = [];
2327
+ var _a;
2328
+ this.requestTimeoutMs = (_a = options.requestTimeoutMs) != null ? _a : DEFAULT_CLIP_REQUEST_TIMEOUT_MS;
2329
+ this.unsubscribers.push(
2330
+ this.host.onRuntimeMessage((message) => this.onRuntimeMessage(message))
2331
+ );
2332
+ this.unsubscribers.push(
2333
+ this.host.onStatusChanged((status) => this.onStatusChanged(status))
2334
+ );
2335
+ }
2336
+ /**
2337
+ * Request a clip covering the last `durationSeconds` of the live
2338
+ * session. See {@link Reactor.requestClip}.
2339
+ */
2340
+ requestClip(durationSeconds) {
2341
+ return __async(this, null, function* () {
2342
+ if (typeof durationSeconds !== "number" || !Number.isFinite(durationSeconds) || durationSeconds <= 0) {
2343
+ throw new RecordingError(
2344
+ "INVALID_DURATION",
2345
+ "durationSeconds must be a positive finite number"
2346
+ );
2347
+ }
2348
+ const status = this.host.getStatus();
2349
+ if (status !== "ready") {
2350
+ throw new RecordingError(
2351
+ "DISCONNECTED",
2352
+ `Cannot request clip while status is "${status}"`
2353
+ );
2354
+ }
2355
+ return this.dispatchClipRequest(RuntimeRecordingMessageType.REQUEST_CLIP, {
2356
+ duration_seconds: durationSeconds
2357
+ });
2358
+ });
2359
+ }
2360
+ /**
2361
+ * Request a clip covering the entire session up to "now". See
2362
+ * {@link Reactor.requestRecording}.
2363
+ */
2364
+ requestRecording() {
2365
+ return __async(this, null, function* () {
2366
+ const status = this.host.getStatus();
2367
+ if (status !== "ready") {
2368
+ throw new RecordingError(
2369
+ "DISCONNECTED",
2370
+ `Cannot request recording while status is "${status}"`
2371
+ );
2372
+ }
2373
+ return this.dispatchClipRequest(
2374
+ RuntimeRecordingMessageType.REQUEST_RECORDING,
2375
+ {}
2376
+ );
2377
+ });
2378
+ }
2379
+ /**
2380
+ * Poll `/clips` and return the raw manifest body. Same polling
2381
+ * semantics as the bare {@link fetchPlaylist} helper; the caller is
2382
+ * responsible for supplying the Coordinator JWT via `options.jwt`
2383
+ * (origin-scoped to `clip.playlistUrl`). In local mode against the
2384
+ * HttpRuntime, `options.jwt` should be omitted.
2385
+ */
2386
+ fetchPlaylist(_0) {
2387
+ return __async(this, arguments, function* (clip, options = {}) {
2388
+ return fetchPlaylist(clip.playlistUrl, __spreadValues({
2389
+ predictedReadyAtMs: clip.predictedReadyAtMs
2390
+ }, options));
2391
+ });
2392
+ }
2393
+ /**
2394
+ * Fetch the manifest and return a `blob:` URL suitable for
2395
+ * `<video src>` / `hls.js`. The player reads the manifest from
2396
+ * browser memory; chunk URLs inside are presigned S3 GETs.
2397
+ *
2398
+ * Caller owns the returned URL — revoke it via `URL.revokeObjectURL`
2399
+ * when playback tears down. Pass `options.jwt` for production
2400
+ * `/clips` (the Coordinator hop) — see {@link FetchPlaylistOptions}.
2401
+ */
2402
+ getPlayableManifestUrl(_0) {
2403
+ return __async(this, arguments, function* (clip, options = {}) {
2404
+ const body = yield this.fetchPlaylist(clip, options);
2405
+ return createPlayableManifestUrl(body, clip.playlistUrl);
2406
+ });
2407
+ }
2408
+ /**
2409
+ * Thin delegation to {@link downloadClipAsFile}. Caller must pass
2410
+ * `options.jwt` in production — see {@link DownloadClipOptions}.
2411
+ */
2412
+ downloadClipAsFile(clip, filename = "reactor-clip.mp4", options) {
2413
+ return __async(this, null, function* () {
2414
+ return downloadClipAsFile(clip, filename, options);
2415
+ });
2416
+ }
2417
+ /**
2418
+ * Drop every pending request and unsubscribe from host events.
2419
+ * Safe to call multiple times; further `requestClip` /
2420
+ * `requestRecording` calls after `destroy()` will hang waiting for
2421
+ * a response that will never arrive — host should not call into
2422
+ * the client after destroy.
2423
+ */
2424
+ destroy() {
2425
+ this.rejectPending("RecordingClient destroyed");
2426
+ while (this.unsubscribers.length > 0) {
2427
+ const off = this.unsubscribers.pop();
2428
+ try {
2429
+ off == null ? void 0 : off();
2430
+ } catch (e) {
2431
+ }
2432
+ }
2433
+ }
2434
+ /**
2435
+ * Register a pending FIFO entry, send the runtime message via
2436
+ * the host, and resolve when the next `clipReady` / `clipFailed`
2437
+ * arrives.
2438
+ */
2439
+ dispatchClipRequest(messageType, payload) {
2440
+ return new Promise((resolve, reject) => {
2441
+ const pending = { resolve, reject };
2442
+ pending.timeoutHandle = setTimeout(() => {
2443
+ const idx = this.pendingClipRequests.indexOf(pending);
2444
+ if (idx === -1) return;
2445
+ this.pendingClipRequests.splice(idx, 1);
2446
+ reject(
2447
+ new RecordingError(
2448
+ "REQUEST_TIMEOUT",
2449
+ `No clipReady/clipFailed within ${this.requestTimeoutMs}ms`
2450
+ )
2451
+ );
2452
+ }, this.requestTimeoutMs);
2453
+ this.pendingClipRequests.push(pending);
2454
+ try {
2455
+ void this.host.sendRuntimeCommand(messageType, payload);
2456
+ } catch (error) {
2457
+ const idx = this.pendingClipRequests.indexOf(pending);
2458
+ if (idx !== -1) this.pendingClipRequests.splice(idx, 1);
2459
+ if (pending.timeoutHandle) clearTimeout(pending.timeoutHandle);
2460
+ reject(
2461
+ new RecordingError(
2462
+ "INTERNAL_ERROR",
2463
+ `Failed to send ${messageType}: ${error.message}`
2464
+ )
2465
+ );
2466
+ }
2467
+ });
2468
+ }
2469
+ /**
2470
+ * Match inbound `clipReady` / `clipFailed` to the next pending
2471
+ * request FIFO; ignore every other runtime message type.
2472
+ */
2473
+ onRuntimeMessage(message) {
2474
+ var _a;
2475
+ if (!message || typeof message !== "object") return;
2476
+ const msg = message;
2477
+ const type = msg.type;
2478
+ if (type !== RuntimeRecordingMessageType.CLIP_READY && type !== RuntimeRecordingMessageType.CLIP_FAILED) {
2479
+ return;
2480
+ }
2481
+ const pending = this.pendingClipRequests.shift();
2482
+ if (!pending) {
2483
+ console.warn("[Reactor] Received", type, "with no pending request");
2484
+ return;
2485
+ }
2486
+ if (pending.timeoutHandle) clearTimeout(pending.timeoutHandle);
2487
+ if (type === RuntimeRecordingMessageType.CLIP_READY) {
2488
+ const parsed = ClipReadyPayloadSchema.safeParse(msg.data);
2489
+ if (!parsed.success) {
2490
+ pending.reject(
2491
+ new RecordingError(
2492
+ "INTERNAL_ERROR",
2493
+ `Malformed clipReady payload: ${parsed.error.message}`
2494
+ )
2495
+ );
2496
+ return;
2497
+ }
2498
+ pending.resolve(
2499
+ clipFromPayload(parsed.data, {
2500
+ coordinatorBaseUrl: this.host.getCoordinatorBaseUrl()
2501
+ })
2502
+ );
2503
+ return;
2504
+ }
2505
+ const parsedFail = ClipFailedPayloadSchema.safeParse((_a = msg.data) != null ? _a : {});
2506
+ const reason = parsedFail.success ? parsedFail.data.reason : "unknown";
2507
+ pending.reject(
2508
+ new RecordingError(
2509
+ reason === "recorder disabled" || reason === "recorder disabled or encoder crashed" ? "RECORDER_DISABLED" : "INTERNAL_ERROR",
2510
+ reason
2511
+ )
2512
+ );
2513
+ }
2514
+ onStatusChanged(status) {
2515
+ if (status === "disconnected") {
2516
+ this.rejectPending("Reactor disconnected");
2517
+ }
2518
+ }
2519
+ /** Reject every in-flight request with a typed disconnect error. */
2520
+ rejectPending(reason) {
2521
+ if (this.pendingClipRequests.length === 0) return;
2522
+ const pending = this.pendingClipRequests;
2523
+ this.pendingClipRequests = [];
2524
+ for (const entry of pending) {
2525
+ if (entry.timeoutHandle) clearTimeout(entry.timeoutHandle);
2526
+ entry.reject(new RecordingError("DISCONNECTED", reason));
2527
+ }
2528
+ }
2529
+ };
2530
+
2531
+ // src/core/Reactor.ts
1829
2532
  var LOCAL_COORDINATOR_URL = "http://localhost:8080";
1830
2533
  var DEFAULT_BASE_URL = "https://api.reactor.inc";
1831
- var TrackHintSchema = z2.object({
1832
- name: z2.string(),
1833
- kind: z2.enum(["video", "audio"]),
1834
- direction: z2.enum(["recvonly", "sendonly"])
2534
+ var TrackHintSchema = z3.object({
2535
+ name: z3.string(),
2536
+ kind: z3.enum(["video", "audio"]),
2537
+ direction: z3.enum(["recvonly", "sendonly"])
1835
2538
  });
1836
- var OptionsSchema = z2.object({
1837
- apiUrl: z2.string().default(DEFAULT_BASE_URL),
1838
- modelName: z2.string(),
1839
- local: z2.boolean().default(false),
1840
- modelTracks: z2.array(TrackHintSchema).optional()
2539
+ var OptionsSchema = z3.object({
2540
+ apiUrl: z3.string().default(DEFAULT_BASE_URL),
2541
+ modelName: z3.string(),
2542
+ local: z3.boolean().default(false),
2543
+ modelTracks: z3.array(TrackHintSchema).optional()
1841
2544
  });
1842
2545
  var Reactor = class {
1843
2546
  constructor(options) {
@@ -1854,6 +2557,28 @@ var Reactor = class {
1854
2557
  if (validatedOptions.modelTracks) {
1855
2558
  this.presetTracks = validatedOptions.modelTracks;
1856
2559
  }
2560
+ this.recording = new RecordingClient({
2561
+ onRuntimeMessage: (handler) => {
2562
+ this.on("runtimeMessage", handler);
2563
+ return () => this.off("runtimeMessage", handler);
2564
+ },
2565
+ onStatusChanged: (handler) => {
2566
+ this.on("statusChanged", handler);
2567
+ return () => this.off("statusChanged", handler);
2568
+ },
2569
+ sendRuntimeCommand: (command, data) => this.sendCommand(command, data, "runtime"),
2570
+ getStatus: () => this.status,
2571
+ getCoordinatorBaseUrl: () => this.coordinatorUrl
2572
+ });
2573
+ }
2574
+ /**
2575
+ * Returns the JWT resolver supplied to the most recent
2576
+ * {@link connect} call, or `undefined` if none was set (pre-connect
2577
+ * or local mode). Used by clip surfaces as a fallback when their
2578
+ * own `getJwt` prop is omitted.
2579
+ */
2580
+ getJwtResolver() {
2581
+ return this.jwtResolver;
1857
2582
  }
1858
2583
  on(event, handler) {
1859
2584
  if (!this.eventListeners.has(event)) {
@@ -1994,6 +2719,41 @@ var Reactor = class {
1994
2719
  return new FileRef(slot.presigned_id, name, mimeType, size);
1995
2720
  });
1996
2721
  }
2722
+ /**
2723
+ * Request a clip covering the last `durationSeconds` of the live
2724
+ * session. Capped server-side at `recording.clip_max_seconds`
2725
+ * (default 5 minutes). Resolves with a {@link Clip} whose
2726
+ * `playlistUrl` can be handed to any HLS-capable player.
2727
+ *
2728
+ * @throws {RecordingError} on invalid input, transport failure,
2729
+ * timeout, runtime-side `clipFailed`, or disconnect mid-request.
2730
+ */
2731
+ requestClip(durationSeconds) {
2732
+ return __async(this, null, function* () {
2733
+ return this.recording.requestClip(durationSeconds);
2734
+ });
2735
+ }
2736
+ /**
2737
+ * Request a clip covering the entire session up to "now". Same
2738
+ * mechanics as {@link requestClip} with `start = 0`; only the
2739
+ * resolved {@link Clip.kind} discriminator differs.
2740
+ */
2741
+ requestRecording() {
2742
+ return __async(this, null, function* () {
2743
+ return this.recording.requestRecording();
2744
+ });
2745
+ }
2746
+ /**
2747
+ * Stream the chunks referenced by `clip.playlistUrl` and trigger a
2748
+ * native browser download of the assembled fragmented-MP4 Blob.
2749
+ * Pass `filename: null` to skip the download trigger and receive
2750
+ * the Blob (useful for non-DOM consumers and tests).
2751
+ */
2752
+ downloadClipAsFile(clip, filename = "reactor-clip.mp4", options) {
2753
+ return __async(this, null, function* () {
2754
+ return this.recording.downloadClipAsFile(clip, filename, options);
2755
+ });
2756
+ }
1997
2757
  /**
1998
2758
  * Publishes a MediaStreamTrack to a named sendonly track.
1999
2759
  * The transceiver is already set up from capabilities — this just
@@ -2082,7 +2842,10 @@ var Reactor = class {
2082
2842
  }
2083
2843
  /**
2084
2844
  * Connects to the coordinator, creates a session, then establishes
2085
- * the transport using server-declared capabilities.
2845
+ * the transport using server-declared capabilities. `jwtToken` may
2846
+ * be a static string or a {@link JwtSource} resolver; pass a
2847
+ * resolver when the token is short-lived so each Coordinator HTTP
2848
+ * hop sees a fresh value.
2086
2849
  */
2087
2850
  connect(jwtToken, options) {
2088
2851
  return __async(this, null, function* () {
@@ -2095,6 +2858,9 @@ var Reactor = class {
2095
2858
  }
2096
2859
  this.setStatus("connecting");
2097
2860
  this.connectStartTime = performance.now();
2861
+ if (!this.local && jwtToken !== void 0) {
2862
+ this.jwtResolver = normalizeJwtSource(jwtToken);
2863
+ }
2098
2864
  try {
2099
2865
  this.coordinatorClient = this.local ? new LocalCoordinatorClient(this.coordinatorUrl, this.model) : new CoordinatorClient({
2100
2866
  baseUrl: this.coordinatorUrl,
@@ -2358,7 +3124,13 @@ var Reactor = class {
2358
3124
  };
2359
3125
 
2360
3126
  // src/react/ReactorProvider.tsx
2361
- import { useContext, useEffect, useRef, useState } from "react";
3127
+ import {
3128
+ useContext,
3129
+ useEffect,
3130
+ useMemo,
3131
+ useRef,
3132
+ useState
3133
+ } from "react";
2362
3134
 
2363
3135
  // src/core/store.ts
2364
3136
  import { create } from "zustand/react";
@@ -2539,12 +3311,27 @@ function ReactorProvider(_a) {
2539
3311
  var _b = _a, {
2540
3312
  children,
2541
3313
  connectOptions,
2542
- jwtToken
3314
+ jwtToken,
3315
+ getJwt
2543
3316
  } = _b, props = __objRest(_b, [
2544
3317
  "children",
2545
3318
  "connectOptions",
2546
- "jwtToken"
3319
+ "jwtToken",
3320
+ "getJwt"
2547
3321
  ]);
3322
+ const getJwtRef = useRef(getJwt);
3323
+ useEffect(() => {
3324
+ getJwtRef.current = getJwt;
3325
+ });
3326
+ const hasGetJwt = getJwt !== void 0;
3327
+ const stableGetJwt = useMemo(() => {
3328
+ if (!hasGetJwt) return void 0;
3329
+ return () => __async(null, null, function* () {
3330
+ const r = getJwtRef.current;
3331
+ return r ? yield r() : "";
3332
+ });
3333
+ }, [hasGetJwt]);
3334
+ const jwtSource = stableGetJwt != null ? stableGetJwt : jwtToken;
2548
3335
  const storeRef = useRef(void 0);
2549
3336
  const firstRender = useRef(true);
2550
3337
  const [_storeVersion, setStoreVersion] = useState(0);
@@ -2552,7 +3339,7 @@ function ReactorProvider(_a) {
2552
3339
  console.debug("[ReactorProvider] Creating new reactor store");
2553
3340
  storeRef.current = createReactorStore(
2554
3341
  initReactorStore(__spreadProps(__spreadValues({}, props), {
2555
- jwtToken
3342
+ jwtToken: jwtSource
2556
3343
  }))
2557
3344
  );
2558
3345
  console.debug("[ReactorProvider] Reactor store created successfully");
@@ -2577,11 +3364,11 @@ function ReactorProvider(_a) {
2577
3364
  if (firstRender.current) {
2578
3365
  firstRender.current = false;
2579
3366
  const current2 = storeRef.current;
2580
- if (autoConnect && current2.getState().status === "disconnected" && jwtToken) {
3367
+ if (autoConnect && current2.getState().status === "disconnected" && jwtSource) {
2581
3368
  console.debug(
2582
3369
  "[ReactorProvider] Starting autoconnect in first render..."
2583
3370
  );
2584
- current2.getState().connect(jwtToken, pollingOptions).then(() => {
3371
+ current2.getState().connect(jwtSource, pollingOptions).then(() => {
2585
3372
  console.debug(
2586
3373
  "[ReactorProvider] Autoconnect successful in first render"
2587
3374
  );
@@ -2614,7 +3401,7 @@ function ReactorProvider(_a) {
2614
3401
  apiUrl,
2615
3402
  modelName,
2616
3403
  local,
2617
- jwtToken
3404
+ jwtToken: jwtSource
2618
3405
  })
2619
3406
  );
2620
3407
  const current = storeRef.current;
@@ -2622,9 +3409,9 @@ function ReactorProvider(_a) {
2622
3409
  console.debug(
2623
3410
  "[ReactorProvider] Reactor store updated successfully, and increased version"
2624
3411
  );
2625
- if (autoConnect && current.getState().status === "disconnected" && jwtToken) {
3412
+ if (autoConnect && current.getState().status === "disconnected" && jwtSource) {
2626
3413
  console.debug("[ReactorProvider] Starting autoconnect...");
2627
- current.getState().connect(jwtToken, pollingOptions).then(() => {
3414
+ current.getState().connect(jwtSource, pollingOptions).then(() => {
2628
3415
  console.debug("[ReactorProvider] Autoconnect successful");
2629
3416
  }).catch((error) => {
2630
3417
  console.error("[ReactorProvider] Failed to autoconnect:", error);
@@ -2640,7 +3427,7 @@ function ReactorProvider(_a) {
2640
3427
  console.error("[ReactorProvider] Failed to disconnect:", error);
2641
3428
  });
2642
3429
  };
2643
- }, [apiUrl, modelName, autoConnect, local, jwtToken, maxAttempts]);
3430
+ }, [apiUrl, modelName, autoConnect, local, jwtSource, maxAttempts]);
2644
3431
  return /* @__PURE__ */ jsx(ReactorContext.Provider, { value: storeRef.current, children });
2645
3432
  }
2646
3433
  function useReactorStore(selector) {
@@ -2706,7 +3493,7 @@ function useStats() {
2706
3493
  }
2707
3494
 
2708
3495
  // src/react/ReactorView.tsx
2709
- import { useEffect as useEffect3, useMemo, useRef as useRef3 } from "react";
3496
+ import { useEffect as useEffect3, useMemo as useMemo2, useRef as useRef3 } from "react";
2710
3497
  import { jsx as jsx2 } from "react/jsx-runtime";
2711
3498
  function ReactorView({
2712
3499
  track = "main_video",
@@ -2726,7 +3513,7 @@ function ReactorView({
2726
3513
  };
2727
3514
  });
2728
3515
  const videoRef = useRef3(null);
2729
- const mediaStream = useMemo(() => {
3516
+ const mediaStream = useMemo2(() => {
2730
3517
  const tracks = [];
2731
3518
  if (videoMediaTrack) tracks.push(videoMediaTrack);
2732
3519
  if (audioMediaTrack) tracks.push(audioMediaTrack);
@@ -3547,17 +4334,323 @@ function WebcamStream({
3547
4334
  }
3548
4335
  );
3549
4336
  }
4337
+
4338
+ // src/react/ClipPlayer.tsx
4339
+ import { useContext as useContext2, useEffect as useEffect5, useRef as useRef6, useState as useState5 } from "react";
4340
+ import { jsx as jsx5, jsxs as jsxs3 } from "react/jsx-runtime";
4341
+ function ClipPlayer({
4342
+ clip,
4343
+ getJwt,
4344
+ slackMs,
4345
+ autoPlay = true,
4346
+ muted = true,
4347
+ className,
4348
+ style
4349
+ }) {
4350
+ const videoRef = useRef6(null);
4351
+ const [phase, setPhase] = useState5({ kind: "waiting" });
4352
+ const store = useContext2(ReactorContext);
4353
+ const getJwtRef = useRef6(getJwt);
4354
+ const autoPlayRef = useRef6(autoPlay);
4355
+ const slackMsRef = useRef6(slackMs);
4356
+ const storeRef = useRef6(store);
4357
+ useEffect5(() => {
4358
+ getJwtRef.current = getJwt;
4359
+ autoPlayRef.current = autoPlay;
4360
+ slackMsRef.current = slackMs;
4361
+ storeRef.current = store;
4362
+ });
4363
+ useEffect5(() => {
4364
+ const video = videoRef.current;
4365
+ if (!video) return;
4366
+ const abort = new AbortController();
4367
+ let cancelled = false;
4368
+ let hlsInstance = null;
4369
+ let manifestBlobUrl = null;
4370
+ const fail = (message) => {
4371
+ if (cancelled) return;
4372
+ setPhase({ kind: "error", message });
4373
+ };
4374
+ const attachPlayer = (manifestUrl) => __async(null, null, function* () {
4375
+ const canPlayNative = video.canPlayType("application/vnd.apple.mpegurl") !== "";
4376
+ if (canPlayNative) {
4377
+ video.src = manifestUrl;
4378
+ if (autoPlayRef.current) {
4379
+ video.play().catch(() => {
4380
+ });
4381
+ }
4382
+ if (!cancelled) setPhase({ kind: "ready" });
4383
+ return;
4384
+ }
4385
+ let HlsCtor;
4386
+ try {
4387
+ const mod = yield import("hls.js");
4388
+ HlsCtor = mod.default;
4389
+ } catch (e) {
4390
+ fail(
4391
+ "HLS playback unavailable in this browser. Install `hls.js` as a peer dependency, or use Download."
4392
+ );
4393
+ return;
4394
+ }
4395
+ if (cancelled) return;
4396
+ if (!HlsCtor.isSupported()) {
4397
+ fail("This browser cannot play HLS clips. Use Download instead.");
4398
+ return;
4399
+ }
4400
+ const hls = new HlsCtor();
4401
+ hls.loadSource(manifestUrl);
4402
+ hls.attachMedia(video);
4403
+ hls.on(HlsCtor.Events.MANIFEST_PARSED, () => {
4404
+ if (cancelled) return;
4405
+ setPhase({ kind: "ready" });
4406
+ if (autoPlayRef.current) {
4407
+ video.play().catch(() => {
4408
+ });
4409
+ }
4410
+ });
4411
+ hls.on(HlsCtor.Events.ERROR, (_evt, data) => {
4412
+ var _a;
4413
+ if (cancelled) return;
4414
+ if (data.fatal) {
4415
+ fail(`Playback error: ${(_a = data.details) != null ? _a : "unknown"}`);
4416
+ return;
4417
+ }
4418
+ console.warn("[Reactor.ClipPlayer] hls.js non-fatal error", data);
4419
+ });
4420
+ hlsInstance = hls;
4421
+ });
4422
+ const setup = () => __async(null, null, function* () {
4423
+ var _a;
4424
+ try {
4425
+ setPhase({ kind: "waiting" });
4426
+ const explicit = getJwtRef.current;
4427
+ const fallback = (_a = storeRef.current) == null ? void 0 : _a.getState().internal.reactor.getJwtResolver();
4428
+ const resolver = explicit != null ? explicit : fallback;
4429
+ const jwt = resolver ? yield resolver() : void 0;
4430
+ if (cancelled) return;
4431
+ const body = yield fetchPlaylist(clip.playlistUrl, {
4432
+ predictedReadyAtMs: clip.predictedReadyAtMs,
4433
+ slackMs: slackMsRef.current,
4434
+ jwt,
4435
+ signal: abort.signal
4436
+ });
4437
+ if (cancelled) return;
4438
+ setPhase({ kind: "loading" });
4439
+ manifestBlobUrl = createPlayableManifestUrl(body, clip.playlistUrl);
4440
+ yield attachPlayer(manifestBlobUrl);
4441
+ } catch (err) {
4442
+ if (cancelled) return;
4443
+ if (err instanceof DOMException && err.name === "AbortError") {
4444
+ return;
4445
+ }
4446
+ const message = err instanceof RecordingError ? `${err.code}: ${err.reason}` : err instanceof Error ? err.message : String(err);
4447
+ fail(message);
4448
+ }
4449
+ });
4450
+ setup();
4451
+ return () => {
4452
+ cancelled = true;
4453
+ abort.abort();
4454
+ hlsInstance == null ? void 0 : hlsInstance.destroy();
4455
+ video.pause();
4456
+ video.removeAttribute("src");
4457
+ video.load();
4458
+ if (manifestBlobUrl) URL.revokeObjectURL(manifestBlobUrl);
4459
+ };
4460
+ }, [clip]);
4461
+ const overlayText = phase.kind === "waiting" ? "Waiting for clip\u2026" : phase.kind === "loading" ? "Loading player\u2026" : null;
4462
+ return /* @__PURE__ */ jsxs3(
4463
+ "div",
4464
+ {
4465
+ className,
4466
+ style: __spreadValues({
4467
+ position: "relative",
4468
+ background: "#000",
4469
+ width: "100%",
4470
+ display: "flex",
4471
+ alignItems: "center",
4472
+ justifyContent: "center"
4473
+ }, style),
4474
+ children: [
4475
+ /* @__PURE__ */ jsx5(
4476
+ "video",
4477
+ {
4478
+ ref: videoRef,
4479
+ controls: true,
4480
+ playsInline: true,
4481
+ muted,
4482
+ style: {
4483
+ display: "block",
4484
+ width: "100%",
4485
+ height: "auto",
4486
+ maxHeight: "100%"
4487
+ }
4488
+ }
4489
+ ),
4490
+ overlayText && /* @__PURE__ */ jsx5(
4491
+ "div",
4492
+ {
4493
+ style: {
4494
+ position: "absolute",
4495
+ inset: 0,
4496
+ display: "flex",
4497
+ alignItems: "center",
4498
+ justifyContent: "center",
4499
+ color: "rgba(255,255,255,0.6)",
4500
+ font: "11px ui-monospace, SFMono-Regular, Menlo, monospace",
4501
+ letterSpacing: "0.1em",
4502
+ textTransform: "uppercase",
4503
+ pointerEvents: "none"
4504
+ },
4505
+ children: overlayText
4506
+ }
4507
+ ),
4508
+ phase.kind === "error" && /* @__PURE__ */ jsx5(
4509
+ "div",
4510
+ {
4511
+ style: {
4512
+ position: "absolute",
4513
+ inset: 0,
4514
+ display: "flex",
4515
+ alignItems: "center",
4516
+ justifyContent: "center",
4517
+ padding: 24,
4518
+ background: "rgba(0,0,0,0.8)",
4519
+ color: "#ef4444",
4520
+ font: "11px ui-monospace, SFMono-Regular, Menlo, monospace",
4521
+ textAlign: "center"
4522
+ },
4523
+ children: phase.message
4524
+ }
4525
+ )
4526
+ ]
4527
+ }
4528
+ );
4529
+ }
4530
+
4531
+ // src/react/useClipDownload.ts
4532
+ import { useCallback as useCallback2, useContext as useContext3, useEffect as useEffect6, useRef as useRef7, useState as useState6 } from "react";
4533
+ function useClipDownload(clip, options = {}) {
4534
+ var _a;
4535
+ const [state, setState] = useState6({ kind: "idle" });
4536
+ const store = useContext3(ReactorContext);
4537
+ const clipRef = useRef7(clip);
4538
+ const filenameRef = useRef7(
4539
+ (_a = options.filename) != null ? _a : "reactor-clip.mp4"
4540
+ );
4541
+ const getJwtRef = useRef7(options.getJwt);
4542
+ useEffect6(() => {
4543
+ clipRef.current = clip;
4544
+ filenameRef.current = options.filename === void 0 ? "reactor-clip.mp4" : options.filename;
4545
+ getJwtRef.current = options.getJwt;
4546
+ });
4547
+ const inFlightRef = useRef7(false);
4548
+ const download = useCallback2(() => __async(null, null, function* () {
4549
+ if (inFlightRef.current) return void 0;
4550
+ inFlightRef.current = true;
4551
+ setState({ kind: "downloading", fetched: 0, total: 0 });
4552
+ try {
4553
+ const explicit = getJwtRef.current;
4554
+ const fallback = store == null ? void 0 : store.getState().internal.reactor.getJwtResolver();
4555
+ const resolver = explicit != null ? explicit : fallback;
4556
+ const jwt = resolver ? yield resolver() : void 0;
4557
+ const blob = yield downloadClipAsFile(
4558
+ clipRef.current,
4559
+ filenameRef.current,
4560
+ {
4561
+ jwt,
4562
+ onProgress: ({ fetched, total }) => setState({ kind: "downloading", fetched, total })
4563
+ }
4564
+ );
4565
+ setState({ kind: "idle" });
4566
+ return blob;
4567
+ } catch (err) {
4568
+ const message = err instanceof RecordingError ? `${err.code}: ${err.reason}` : err instanceof Error ? err.message : String(err);
4569
+ setState({ kind: "error", message });
4570
+ return void 0;
4571
+ } finally {
4572
+ inFlightRef.current = false;
4573
+ }
4574
+ }), [store]);
4575
+ const reset = useCallback2(() => setState({ kind: "idle" }), []);
4576
+ return { state, download, reset };
4577
+ }
4578
+
4579
+ // src/react/ClipDownloadButton.tsx
4580
+ import { jsx as jsx6 } from "react/jsx-runtime";
4581
+ function ClipDownloadButton({
4582
+ clip,
4583
+ getJwt,
4584
+ filename = "reactor-clip.mp4",
4585
+ children,
4586
+ className,
4587
+ style,
4588
+ disabled
4589
+ }) {
4590
+ const { state, download } = useClipDownload(clip, { filename, getJwt });
4591
+ const downloading = state.kind === "downloading";
4592
+ const isDisabled = downloading || !!disabled;
4593
+ const content = typeof children === "function" ? children(state) : children !== void 0 ? children : defaultLabel(state);
4594
+ return /* @__PURE__ */ jsx6(
4595
+ "button",
4596
+ {
4597
+ type: "button",
4598
+ onClick: () => {
4599
+ void download();
4600
+ },
4601
+ disabled: isDisabled,
4602
+ title: state.kind === "error" ? state.message : void 0,
4603
+ className,
4604
+ style: __spreadValues({
4605
+ padding: "5px 12px",
4606
+ borderRadius: 4,
4607
+ border: "1px solid rgba(255,255,255,0.15)",
4608
+ background: "rgba(255,255,255,0.05)",
4609
+ color: "#fff",
4610
+ font: "11px ui-monospace, SFMono-Regular, Menlo, monospace",
4611
+ cursor: isDisabled ? "default" : "pointer",
4612
+ opacity: isDisabled ? 0.6 : 1,
4613
+ transition: "background-color 120ms ease"
4614
+ }, style),
4615
+ children: content
4616
+ }
4617
+ );
4618
+ }
4619
+ function defaultLabel(state) {
4620
+ if (state.kind === "downloading") {
4621
+ if (state.total > 0) {
4622
+ return `Downloading ${state.fetched}/${state.total}\u2026`;
4623
+ }
4624
+ return "Downloading\u2026";
4625
+ }
4626
+ return "Download";
4627
+ }
3550
4628
  export {
3551
4629
  AbortError,
4630
+ ClipDownloadButton,
4631
+ ClipPlayer,
3552
4632
  ConflictError,
3553
4633
  DEFAULT_BASE_URL,
4634
+ DEFAULT_CLIP_REQUEST_TIMEOUT_MS,
4635
+ DEFAULT_PLAYLIST_POLL_SLACK_MS,
3554
4636
  FileRef,
3555
4637
  Reactor,
3556
4638
  ReactorController,
3557
4639
  ReactorProvider,
3558
4640
  ReactorView,
4641
+ RecordingClient,
4642
+ RecordingError,
4643
+ RuntimeRecordingMessageType,
3559
4644
  WebcamStream,
4645
+ clipFromPayload,
4646
+ createPlayableManifestUrl,
4647
+ downloadClipAsFile,
4648
+ fetchPlaylist,
3560
4649
  isAbortError,
4650
+ normalizeJwtSource,
4651
+ parsePlaylist,
4652
+ rewriteUrlHost,
4653
+ useClipDownload,
3561
4654
  useReactor,
3562
4655
  useReactorInternalMessage,
3563
4656
  useReactorMessage,