@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.js CHANGED
@@ -80,15 +80,30 @@ var __async = (__this, __arguments, generator) => {
80
80
  var index_exports = {};
81
81
  __export(index_exports, {
82
82
  AbortError: () => AbortError,
83
+ ClipDownloadButton: () => ClipDownloadButton,
84
+ ClipPlayer: () => ClipPlayer,
83
85
  ConflictError: () => ConflictError,
84
86
  DEFAULT_BASE_URL: () => DEFAULT_BASE_URL,
87
+ DEFAULT_CLIP_REQUEST_TIMEOUT_MS: () => DEFAULT_CLIP_REQUEST_TIMEOUT_MS,
88
+ DEFAULT_PLAYLIST_POLL_SLACK_MS: () => DEFAULT_PLAYLIST_POLL_SLACK_MS,
85
89
  FileRef: () => FileRef,
86
90
  Reactor: () => Reactor,
87
91
  ReactorController: () => ReactorController,
88
92
  ReactorProvider: () => ReactorProvider,
89
93
  ReactorView: () => ReactorView,
94
+ RecordingClient: () => RecordingClient,
95
+ RecordingError: () => RecordingError,
96
+ RuntimeRecordingMessageType: () => RuntimeRecordingMessageType,
90
97
  WebcamStream: () => WebcamStream,
98
+ clipFromPayload: () => clipFromPayload,
99
+ createPlayableManifestUrl: () => createPlayableManifestUrl,
100
+ downloadClipAsFile: () => downloadClipAsFile,
101
+ fetchPlaylist: () => fetchPlaylist,
91
102
  isAbortError: () => isAbortError,
103
+ normalizeJwtSource: () => normalizeJwtSource,
104
+ parsePlaylist: () => parsePlaylist,
105
+ rewriteUrlHost: () => rewriteUrlHost,
106
+ useClipDownload: () => useClipDownload,
92
107
  useReactor: () => useReactor,
93
108
  useReactorInternalMessage: () => useReactorInternalMessage,
94
109
  useReactorMessage: () => useReactorMessage,
@@ -124,14 +139,38 @@ function isAbortError(error) {
124
139
  return error instanceof AbortError || error instanceof Error && error.name === "AbortError";
125
140
  }
126
141
 
142
+ // src/core/auth.ts
143
+ function normalizeJwtSource(source) {
144
+ if (typeof source === "function") {
145
+ return source;
146
+ }
147
+ return () => source;
148
+ }
149
+
127
150
  // src/core/types.ts
128
151
  var import_zod = require("zod");
129
152
 
130
153
  // package.json
131
154
  var package_default = {
132
155
  name: "@reactor-team/js-sdk",
133
- version: "2.9.3",
134
- description: "Reactor JavaScript frontend SDK",
156
+ version: "2.10.1",
157
+ description: "Reactor JavaScript frontend SDK \u2014 connect React and TypeScript apps to real-time AI video models on Reactor.",
158
+ license: "Apache-2.0",
159
+ repository: {
160
+ type: "git",
161
+ url: "https://github.com/reactor-team/js-sdk.git"
162
+ },
163
+ keywords: [
164
+ "reactor",
165
+ "sdk",
166
+ "frontend",
167
+ "react",
168
+ "webrtc",
169
+ "real-time",
170
+ "video",
171
+ "ai"
172
+ ],
173
+ author: "Reactor Technologies, Inc.",
135
174
  main: "dist/index.js",
136
175
  module: "dist/index.mjs",
137
176
  types: "dist/index.d.ts",
@@ -142,11 +181,19 @@ var package_default = {
142
181
  require: "./dist/index.js"
143
182
  }
144
183
  },
184
+ sideEffects: false,
185
+ engines: {
186
+ node: ">=18"
187
+ },
145
188
  files: [
146
189
  "dist",
147
- "README.md"
190
+ "README.md",
191
+ "LICENSE",
192
+ "NOTICE"
148
193
  ],
149
194
  scripts: {
195
+ prepack: "cp ../../LICENSE ../../NOTICE .",
196
+ postpack: "rm -f LICENSE NOTICE",
150
197
  build: "tsup",
151
198
  dev: "tsup --watch",
152
199
  test: "vitest run",
@@ -156,46 +203,35 @@ var package_default = {
156
203
  format: "prettier --write .",
157
204
  "format:check": "prettier --check ."
158
205
  },
159
- keywords: [
160
- "reactor",
161
- "frontend",
162
- "sdk"
163
- ],
164
- author: "Reactor Technologies, Inc.",
165
206
  reactor: {
166
207
  apiVersion: 1,
167
208
  webrtcVersion: "1.0"
168
209
  },
169
- license: "MIT",
170
- repository: {
171
- type: "git",
172
- url: "https://github.com/reactor-team/js-sdk.git"
173
- },
174
210
  packageManager: "pnpm@10.12.1",
175
- devDependencies: {
176
- "@roamhq/wrtc": "^0.8.0",
177
- "@types/inquirer": "^9.0.9",
178
- "@types/node": "^20",
179
- "@types/react": "^18.2.8",
180
- "@types/sdp-transform": "^2.15.0",
181
- "@types/ws": "^8.18.1",
182
- prettier: "^3.6.2",
183
- tsup: "^8.5.0",
184
- typescript: "^5.8.3",
185
- vitest: "^3.0.0"
186
- },
187
211
  dependencies: {
188
- "@bufbuild/protobuf": "^2.0.0",
189
- chalk: "^5.3.0",
190
- inquirer: "^9.3.0",
212
+ mp4box: "^2.3.0",
191
213
  "sdp-transform": "^3.0.0",
192
- "simple-git": "^3.24.0",
193
- ws: "^8.18.3",
194
- zod: "^4.0.5"
214
+ zod: "^4.4.3"
195
215
  },
196
216
  peerDependencies: {
217
+ "hls.js": "^1.6.0",
197
218
  react: "^17.0.0 || ^18.0.0 || ^19.0.0",
198
219
  zustand: "^5.0.6"
220
+ },
221
+ peerDependenciesMeta: {
222
+ "hls.js": {
223
+ optional: true
224
+ }
225
+ },
226
+ devDependencies: {
227
+ "@roamhq/wrtc": "^0.8.0",
228
+ "@types/node": "^25",
229
+ "@types/react": "^19.2.15",
230
+ "hls.js": "^1.6.0",
231
+ prettier: "^3.6.2",
232
+ tsup: "^8.5.0",
233
+ typescript: "^5.8.3",
234
+ vitest: "^4.1.7"
199
235
  }
200
236
  };
201
237
 
@@ -298,7 +334,7 @@ var SESSION_POLL_DEFAULT_MAX_ATTEMPTS = 20;
298
334
  var CoordinatorClient = class {
299
335
  constructor(options) {
300
336
  this.baseUrl = options.baseUrl;
301
- this.jwtToken = options.jwtToken;
337
+ this.resolveJwt = normalizeJwtSource(options.jwtToken);
302
338
  this.model = options.model;
303
339
  this.abortController = new AbortController();
304
340
  }
@@ -318,14 +354,22 @@ var CoordinatorClient = class {
318
354
  return this.abortController.signal;
319
355
  }
320
356
  /**
321
- * Returns authorization + versioning headers for all coordinator requests.
357
+ * Returns authorization + versioning headers for all coordinator
358
+ * requests. Async so the JWT resolver can fetch a fresh token if
359
+ * needed; an empty token suppresses the `Authorization` header.
322
360
  */
323
361
  getHeaders() {
324
- return {
325
- Authorization: `Bearer ${this.jwtToken}`,
326
- [API_VERSION_HEADER]: String(REACTOR_API_VERSION),
327
- [API_ACCEPT_VERSION_HEADER]: String(REACTOR_API_VERSION)
328
- };
362
+ return __async(this, null, function* () {
363
+ const headers = {
364
+ [API_VERSION_HEADER]: String(REACTOR_API_VERSION),
365
+ [API_ACCEPT_VERSION_HEADER]: String(REACTOR_API_VERSION)
366
+ };
367
+ const jwt = yield this.resolveJwt();
368
+ if (jwt) {
369
+ headers.Authorization = `Bearer ${jwt}`;
370
+ }
371
+ return headers;
372
+ });
329
373
  }
330
374
  /**
331
375
  * Checks an HTTP response for version mismatch errors (426, 501).
@@ -386,7 +430,7 @@ var CoordinatorClient = class {
386
430
  }, extraArgs ? { extra_args: extraArgs } : {});
387
431
  const response = yield fetch(`${this.baseUrl}/sessions`, {
388
432
  method: "POST",
389
- headers: __spreadProps(__spreadValues({}, this.getHeaders()), {
433
+ headers: __spreadProps(__spreadValues({}, yield this.getHeaders()), {
390
434
  "Content-Type": "application/json"
391
435
  }),
392
436
  body: JSON.stringify(requestBody),
@@ -441,7 +485,7 @@ var CoordinatorClient = class {
441
485
  `${this.baseUrl}/sessions/${this.currentSessionId}`,
442
486
  {
443
487
  method: "GET",
444
- headers: this.getHeaders(),
488
+ headers: yield this.getHeaders(),
445
489
  signal: this.signal
446
490
  }
447
491
  );
@@ -494,7 +538,7 @@ var CoordinatorClient = class {
494
538
  `${this.baseUrl}/sessions/${this.currentSessionId}`,
495
539
  {
496
540
  method: "GET",
497
- headers: this.getHeaders(),
541
+ headers: yield this.getHeaders(),
498
542
  signal: this.signal
499
543
  }
500
544
  );
@@ -519,7 +563,7 @@ var CoordinatorClient = class {
519
563
  `${this.baseUrl}/sessions/${this.currentSessionId}/info`,
520
564
  {
521
565
  method: "GET",
522
- headers: this.getHeaders(),
566
+ headers: yield this.getHeaders(),
523
567
  signal: this.signal
524
568
  }
525
569
  );
@@ -551,7 +595,7 @@ var CoordinatorClient = class {
551
595
  `${this.baseUrl}/sessions/${this.currentSessionId}`,
552
596
  {
553
597
  method: "PUT",
554
- headers: this.getHeaders(),
598
+ headers: yield this.getHeaders(),
555
599
  signal: this.signal
556
600
  }
557
601
  );
@@ -583,7 +627,7 @@ var CoordinatorClient = class {
583
627
  `${this.baseUrl}/sessions/${this.currentSessionId}`,
584
628
  __spreadProps(__spreadValues({
585
629
  method: "DELETE",
586
- headers: __spreadValues(__spreadValues({}, this.getHeaders()), body ? { "Content-Type": "application/json" } : {})
630
+ headers: __spreadValues(__spreadValues({}, yield this.getHeaders()), body ? { "Content-Type": "application/json" } : {})
587
631
  }, body ? { body: JSON.stringify(body) } : {}), {
588
632
  signal: this.signal
589
633
  })
@@ -622,7 +666,7 @@ var CoordinatorClient = class {
622
666
  `${this.baseUrl}/sessions/${sessionId}/uploads`,
623
667
  {
624
668
  method: "POST",
625
- headers: __spreadProps(__spreadValues({}, this.getHeaders()), {
669
+ headers: __spreadProps(__spreadValues({}, yield this.getHeaders()), {
626
670
  "Content-Type": "application/json"
627
671
  }),
628
672
  body: JSON.stringify(request),
@@ -654,11 +698,14 @@ var LocalCoordinatorClient = class extends CoordinatorClient {
654
698
  model
655
699
  });
656
700
  }
701
+ // Local runtime endpoints are auth-free; skip the Authorization header.
657
702
  getHeaders() {
658
- return {
659
- [API_VERSION_HEADER]: String(REACTOR_API_VERSION),
660
- [API_ACCEPT_VERSION_HEADER]: String(REACTOR_API_VERSION)
661
- };
703
+ return __async(this, null, function* () {
704
+ return {
705
+ [API_VERSION_HEADER]: String(REACTOR_API_VERSION),
706
+ [API_ACCEPT_VERSION_HEADER]: String(REACTOR_API_VERSION)
707
+ };
708
+ });
662
709
  }
663
710
  /**
664
711
  * Starts a session on the local runtime.
@@ -672,7 +719,7 @@ var LocalCoordinatorClient = class extends CoordinatorClient {
672
719
  console.debug("[LocalCoordinatorClient] Starting session...");
673
720
  const response = yield fetch(`${this.baseUrl}/start_session`, {
674
721
  method: "POST",
675
- headers: __spreadProps(__spreadValues({}, this.getHeaders()), {
722
+ headers: __spreadProps(__spreadValues({}, yield this.getHeaders()), {
676
723
  "Content-Type": "application/json"
677
724
  }),
678
725
  body: JSON.stringify(__spreadValues({}, extraArgs ? { extra_args: extraArgs } : {})),
@@ -728,7 +775,7 @@ var LocalCoordinatorClient = class extends CoordinatorClient {
728
775
  try {
729
776
  yield fetch(`${this.baseUrl}/stop_session`, {
730
777
  method: "POST",
731
- headers: this.getHeaders(),
778
+ headers: yield this.getHeaders(),
732
779
  signal: this.signal
733
780
  });
734
781
  } catch (error) {
@@ -1308,7 +1355,7 @@ var WebRTCTransportClient = class {
1308
1355
  var _a, _b;
1309
1356
  this.baseUrl = config.baseUrl;
1310
1357
  this.sessionId = config.sessionId;
1311
- this.jwtToken = config.jwtToken;
1358
+ this.resolveJwt = normalizeJwtSource(config.jwtToken);
1312
1359
  this.webrtcVersion = (_a = config.webrtcVersion) != null ? _a : REACTOR_WEBRTC_VERSION;
1313
1360
  this.maxPollAttempts = (_b = config.maxPollAttempts) != null ? _b : DEFAULT_MAX_POLL_ATTEMPTS;
1314
1361
  this.abortController = new AbortController();
@@ -1339,11 +1386,19 @@ var WebRTCTransportClient = class {
1339
1386
  get transportBaseUrl() {
1340
1387
  return `${this.baseUrl}/sessions/${this.sessionId}/transport/webrtc`;
1341
1388
  }
1389
+ // Async so the JWT resolver can fetch a fresh token if needed; an
1390
+ // empty token suppresses the `Authorization` header.
1342
1391
  getHeaders() {
1343
- return {
1344
- Authorization: `Bearer ${this.jwtToken}`,
1345
- [WEBRTC_VERSION_HEADER]: this.webrtcVersion
1346
- };
1392
+ return __async(this, null, function* () {
1393
+ const headers = {
1394
+ [WEBRTC_VERSION_HEADER]: this.webrtcVersion
1395
+ };
1396
+ const jwt = yield this.resolveJwt();
1397
+ if (jwt) {
1398
+ headers.Authorization = `Bearer ${jwt}`;
1399
+ }
1400
+ return headers;
1401
+ });
1347
1402
  }
1348
1403
  checkVersionMismatch(response) {
1349
1404
  return __async(this, null, function* () {
@@ -1385,7 +1440,7 @@ var WebRTCTransportClient = class {
1385
1440
  console.debug("[WebRTCTransport] Fetching ICE servers...");
1386
1441
  const response = yield fetch(`${this.transportBaseUrl}/ice_servers`, {
1387
1442
  method: "GET",
1388
- headers: this.getHeaders(),
1443
+ headers: yield this.getHeaders(),
1389
1444
  signal: this.signal
1390
1445
  });
1391
1446
  yield this.checkVersionMismatch(response);
@@ -1415,7 +1470,7 @@ var WebRTCTransportClient = class {
1415
1470
  };
1416
1471
  const response = yield fetch(`${this.transportBaseUrl}/sdp_params`, {
1417
1472
  method,
1418
- headers: __spreadProps(__spreadValues({}, this.getHeaders()), {
1473
+ headers: __spreadProps(__spreadValues({}, yield this.getHeaders()), {
1419
1474
  "Content-Type": "application/json"
1420
1475
  }),
1421
1476
  body: JSON.stringify(requestBody),
@@ -1452,7 +1507,7 @@ var WebRTCTransportClient = class {
1452
1507
  );
1453
1508
  const response = yield fetch(`${this.transportBaseUrl}/sdp_params`, {
1454
1509
  method: "GET",
1455
- headers: this.getHeaders(),
1510
+ headers: yield this.getHeaders(),
1456
1511
  signal: this.signal
1457
1512
  });
1458
1513
  yield this.checkVersionMismatch(response);
@@ -1872,19 +1927,682 @@ var WebRTCTransportClient = class {
1872
1927
  };
1873
1928
 
1874
1929
  // src/core/Reactor.ts
1930
+ var import_zod3 = require("zod");
1931
+
1932
+ // src/utils/recording.ts
1875
1933
  var import_zod2 = require("zod");
1934
+ var RuntimeRecordingMessageType = {
1935
+ REQUEST_CLIP: "requestClip",
1936
+ REQUEST_RECORDING: "requestRecording",
1937
+ CLIP_READY: "clipReady",
1938
+ CLIP_FAILED: "clipFailed"
1939
+ };
1940
+ var RecordingError = class extends Error {
1941
+ constructor(code, reason) {
1942
+ super(`${code}: ${reason}`);
1943
+ this.code = code;
1944
+ this.reason = reason;
1945
+ this.name = "RecordingError";
1946
+ }
1947
+ };
1948
+ var ClipReadyPayloadSchema = import_zod2.z.object({
1949
+ session_id: import_zod2.z.string(),
1950
+ kind: import_zod2.z.enum(["snap", "recording"]),
1951
+ start_marker: import_zod2.z.number(),
1952
+ end_marker: import_zod2.z.number(),
1953
+ now_marker: import_zod2.z.number(),
1954
+ predicted_ready_at_ms: import_zod2.z.number(),
1955
+ playlist_url: import_zod2.z.string()
1956
+ }).passthrough();
1957
+ var ClipFailedPayloadSchema = import_zod2.z.object({
1958
+ reason: import_zod2.z.string().default("unknown")
1959
+ }).passthrough();
1960
+ function clipFromPayload(payload, options = {}) {
1961
+ const playlistUrl = options.coordinatorBaseUrl ? rewriteUrlHost(payload.playlist_url, options.coordinatorBaseUrl) : payload.playlist_url;
1962
+ return {
1963
+ sessionId: payload.session_id,
1964
+ kind: payload.kind,
1965
+ startMarker: payload.start_marker,
1966
+ endMarker: payload.end_marker,
1967
+ nowMarker: payload.now_marker,
1968
+ predictedReadyAtMs: payload.predicted_ready_at_ms,
1969
+ playlistUrl
1970
+ };
1971
+ }
1972
+ function rewriteUrlHost(target, base) {
1973
+ try {
1974
+ if (!/^[a-z][a-z0-9+.-]*:/i.test(target)) {
1975
+ return new URL(target, base).toString();
1976
+ }
1977
+ const baseUrl = new URL(base);
1978
+ const parsed = new URL(target);
1979
+ parsed.protocol = baseUrl.protocol;
1980
+ parsed.hostname = baseUrl.hostname;
1981
+ parsed.port = baseUrl.port;
1982
+ return parsed.toString();
1983
+ } catch (e) {
1984
+ return target;
1985
+ }
1986
+ }
1987
+ var DEFAULT_PLAYLIST_POLL_SLACK_MS = 15e3;
1988
+ function fetchPlaylist(_0) {
1989
+ return __async(this, arguments, function* (playlistUrl, options = {}) {
1990
+ var _a, _b, _c, _d;
1991
+ const slackMs = (_a = options.slackMs) != null ? _a : DEFAULT_PLAYLIST_POLL_SLACK_MS;
1992
+ const minDelay = Math.max(0, (_b = options.minRetryDelayMs) != null ? _b : 200);
1993
+ const maxDelay = Math.max(minDelay, (_c = options.maxRetryDelayMs) != null ? _c : 2e3);
1994
+ const fallbackMaxRetries = (_d = options.maxRetries) != null ? _d : 5;
1995
+ const hasDeadline = typeof options.predictedReadyAtMs === "number";
1996
+ const startedPollingAt = Date.now();
1997
+ const deadlineMs = hasDeadline ? Math.max(options.predictedReadyAtMs, startedPollingAt) + slackMs : void 0;
1998
+ const headers = options.jwt ? { Authorization: `Bearer ${options.jwt}` } : void 0;
1999
+ let attempt = 0;
2000
+ let lastStatus = 0;
2001
+ while (true) {
2002
+ let response;
2003
+ try {
2004
+ response = yield fetch(playlistUrl, {
2005
+ signal: options.signal,
2006
+ headers
2007
+ });
2008
+ } catch (error) {
2009
+ throw new RecordingError(
2010
+ "PLAYLIST_FETCH_FAILED",
2011
+ `Network error fetching playlist: ${error.message}`
2012
+ );
2013
+ }
2014
+ lastStatus = response.status;
2015
+ if (response.status === 202) {
2016
+ if (hasDeadline) {
2017
+ if (Date.now() >= deadlineMs) {
2018
+ throw new RecordingError(
2019
+ "CLIP_NOT_READY",
2020
+ `Boundary chunk still pending after ${slackMs}ms grace (predicted ready ${new Date(
2021
+ options.predictedReadyAtMs
2022
+ ).toISOString()}). Runtime may have crashed mid-clip.`
2023
+ );
2024
+ }
2025
+ } else if (attempt >= fallbackMaxRetries) {
2026
+ throw new RecordingError(
2027
+ "CLIP_NOT_READY",
2028
+ `Manifest still pending after ${attempt + 1} attempts (last status ${lastStatus})`
2029
+ );
2030
+ }
2031
+ const headerDelay = parseRetryAfter(
2032
+ response.headers.get("Retry-After"),
2033
+ minDelay
2034
+ );
2035
+ const delay = Math.min(maxDelay, Math.max(minDelay, headerDelay));
2036
+ const clampedDelay = hasDeadline ? Math.min(delay, Math.max(0, deadlineMs - Date.now())) : delay;
2037
+ yield sleep(clampedDelay, options.signal);
2038
+ attempt++;
2039
+ continue;
2040
+ }
2041
+ if (response.status === 200) {
2042
+ return yield response.text();
2043
+ }
2044
+ if (response.status === 410) {
2045
+ throw new RecordingError(
2046
+ "CLIP_GONE",
2047
+ "Clip is no longer available (chunks aged out or session unknown)"
2048
+ );
2049
+ }
2050
+ if (response.status === 404) {
2051
+ throw new RecordingError(
2052
+ "CLIP_GONE",
2053
+ "Session not found for clip playlist"
2054
+ );
2055
+ }
2056
+ throw new RecordingError(
2057
+ "PLAYLIST_FETCH_FAILED",
2058
+ `Manifest endpoint returned HTTP ${response.status}`
2059
+ );
2060
+ }
2061
+ });
2062
+ }
2063
+ function parsePlaylist(manifestBody, playlistUrl) {
2064
+ let initUrl;
2065
+ const segments = [];
2066
+ const lines = manifestBody.split(/\r?\n/);
2067
+ for (const line of lines) {
2068
+ const trimmed = line.trim();
2069
+ if (!trimmed) continue;
2070
+ if (trimmed.startsWith("#EXT-X-MAP")) {
2071
+ const match = trimmed.match(/URI="([^"]+)"/);
2072
+ if (match) {
2073
+ initUrl = resolveAgainst(match[1], playlistUrl);
2074
+ }
2075
+ continue;
2076
+ }
2077
+ if (trimmed.startsWith("#")) {
2078
+ continue;
2079
+ }
2080
+ segments.push(resolveAgainst(trimmed, playlistUrl));
2081
+ }
2082
+ if (!initUrl) {
2083
+ throw new RecordingError(
2084
+ "INVALID_PLAYLIST",
2085
+ "Playlist is missing an #EXT-X-MAP init segment URI"
2086
+ );
2087
+ }
2088
+ if (segments.length === 0) {
2089
+ throw new RecordingError(
2090
+ "INVALID_PLAYLIST",
2091
+ "Playlist contains no media segments"
2092
+ );
2093
+ }
2094
+ return { initUrl, segmentUrls: segments };
2095
+ }
2096
+ function createPlayableManifestUrl(manifestBody, playlistUrl) {
2097
+ if (typeof Blob === "undefined" || typeof URL === "undefined" || typeof URL.createObjectURL !== "function") {
2098
+ throw new RecordingError(
2099
+ "INVALID_PLAYLIST",
2100
+ "createPlayableManifestUrl requires a browser environment with URL.createObjectURL"
2101
+ );
2102
+ }
2103
+ const rewritten = absolutizeManifestUrls(manifestBody, playlistUrl);
2104
+ const blob = new Blob([rewritten], {
2105
+ type: "application/vnd.apple.mpegurl"
2106
+ });
2107
+ return URL.createObjectURL(blob);
2108
+ }
2109
+ function absolutizeManifestUrls(manifestBody, playlistUrl) {
2110
+ const eol = manifestBody.includes("\r\n") ? "\r\n" : "\n";
2111
+ const lines = manifestBody.split(/\r?\n/);
2112
+ const out = [];
2113
+ for (const line of lines) {
2114
+ if (line.startsWith("#EXT-X-MAP")) {
2115
+ out.push(
2116
+ line.replace(
2117
+ /URI="([^"]+)"/,
2118
+ (_, uri) => `URI="${resolveAgainst(uri, playlistUrl)}"`
2119
+ )
2120
+ );
2121
+ continue;
2122
+ }
2123
+ const trimmed = line.trim();
2124
+ if (!trimmed || trimmed.startsWith("#")) {
2125
+ out.push(line);
2126
+ continue;
2127
+ }
2128
+ out.push(resolveAgainst(trimmed, playlistUrl));
2129
+ }
2130
+ return out.join(eol);
2131
+ }
2132
+ function downloadClipAsFile(_0) {
2133
+ return __async(this, arguments, function* (clip, filename = "reactor-clip.mp4", options = {}) {
2134
+ var _a;
2135
+ const manifestBody = yield fetchPlaylist(clip.playlistUrl, {
2136
+ predictedReadyAtMs: clip.predictedReadyAtMs,
2137
+ signal: options.signal,
2138
+ jwt: options.jwt
2139
+ });
2140
+ const { initUrl, segmentUrls } = parsePlaylist(
2141
+ manifestBody,
2142
+ clip.playlistUrl
2143
+ );
2144
+ const orderedUrls = [initUrl, ...segmentUrls];
2145
+ const parts = [];
2146
+ let bytes = 0;
2147
+ for (let i = 0; i < orderedUrls.length; i++) {
2148
+ const url = orderedUrls[i];
2149
+ let response;
2150
+ try {
2151
+ response = yield fetch(url, { signal: options.signal });
2152
+ } catch (error) {
2153
+ throw new RecordingError(
2154
+ "CHUNK_FETCH_FAILED",
2155
+ `Network error fetching chunk ${i}: ${error.message}`
2156
+ );
2157
+ }
2158
+ if (!response.ok) {
2159
+ throw new RecordingError(
2160
+ "CHUNK_FETCH_FAILED",
2161
+ `Chunk ${i} returned HTTP ${response.status}`
2162
+ );
2163
+ }
2164
+ const data = new Uint8Array(yield response.arrayBuffer());
2165
+ parts.push(data);
2166
+ bytes += data.byteLength;
2167
+ (_a = options.onProgress) == null ? void 0 : _a.call(options, {
2168
+ fetched: i + 1,
2169
+ total: orderedUrls.length,
2170
+ bytes
2171
+ });
2172
+ }
2173
+ const finalBytes = yield maybeRemux(parts);
2174
+ const blob = new Blob([finalBytes], { type: "video/mp4" });
2175
+ if (filename === null) {
2176
+ return blob;
2177
+ }
2178
+ if (typeof document === "undefined" || typeof URL.createObjectURL !== "function") {
2179
+ throw new RecordingError(
2180
+ "DOWNLOAD_UNSUPPORTED",
2181
+ "downloadClipAsFile requires a DOM environment; pass filename=null to skip the download trigger"
2182
+ );
2183
+ }
2184
+ triggerBrowserDownload(blob, filename);
2185
+ return blob;
2186
+ });
2187
+ }
2188
+ function maybeRemux(parts) {
2189
+ return __async(this, null, function* () {
2190
+ const input = concatUint8Arrays(parts);
2191
+ try {
2192
+ const MP4Box = yield loadMp4Box();
2193
+ return yield remuxFragmentedToFlat(input, MP4Box);
2194
+ } catch (error) {
2195
+ console.warn(
2196
+ "[Reactor] Clip remux failed, returning fragmented MP4 instead.",
2197
+ error
2198
+ );
2199
+ return input;
2200
+ }
2201
+ });
2202
+ }
2203
+ var __remuxInternals = {
2204
+ loadMp4Box: () => import("mp4box")
2205
+ };
2206
+ function loadMp4Box() {
2207
+ return __remuxInternals.loadMp4Box();
2208
+ }
2209
+ function remuxFragmentedToFlat(input, MP4Box) {
2210
+ return __async(this, null, function* () {
2211
+ return new Promise((resolve, reject) => {
2212
+ const inFile = MP4Box.createFile();
2213
+ const outFile = MP4Box.createFile();
2214
+ outFile.init({ brands: ["isom", "mp42", "avc1", "iso2"] });
2215
+ const inToOutTrack = /* @__PURE__ */ new Map();
2216
+ const trackBaselineDts = /* @__PURE__ */ new Map();
2217
+ let settled = false;
2218
+ const fail = (err) => {
2219
+ if (settled) return;
2220
+ settled = true;
2221
+ reject(err);
2222
+ };
2223
+ inFile.onError = (_module, message) => {
2224
+ fail(new Error(message));
2225
+ };
2226
+ inFile.onReady = (info) => {
2227
+ if (!info.tracks.length) {
2228
+ fail(new Error("no tracks in input"));
2229
+ return;
2230
+ }
2231
+ for (const track of info.tracks) {
2232
+ inFile.setExtractionOptions(track.id, null, { nbSamples: 1e3 });
2233
+ }
2234
+ inFile.start();
2235
+ };
2236
+ inFile.onSamples = (id, _user, samples) => {
2237
+ if (settled || samples.length === 0) return;
2238
+ let outId = inToOutTrack.get(id);
2239
+ let baseline = trackBaselineDts.get(id);
2240
+ if (outId === void 0) {
2241
+ const firstSample = samples[0];
2242
+ const sampleEntry = firstSample.description;
2243
+ const inputTrack = trackInfoById(inFile, id);
2244
+ outId = outFile.addTrack({
2245
+ type: sampleEntry.type,
2246
+ timescale: firstSample.timescale,
2247
+ width: inputTrack == null ? void 0 : inputTrack.track_width,
2248
+ height: inputTrack == null ? void 0 : inputTrack.track_height,
2249
+ language: inputTrack == null ? void 0 : inputTrack.language,
2250
+ hdlr: (inputTrack == null ? void 0 : inputTrack.video) ? "vide" : (inputTrack == null ? void 0 : inputTrack.audio) ? "soun" : void 0,
2251
+ // `boxes` is typed as `Box[]` but `description_boxes`
2252
+ // wants the narrower `BoxKind[]` union — at runtime they
2253
+ // are the same concrete instances, just typed loosely.
2254
+ description_boxes: sampleEntry.boxes
2255
+ });
2256
+ baseline = firstSample.dts;
2257
+ inToOutTrack.set(id, outId);
2258
+ trackBaselineDts.set(id, baseline);
2259
+ }
2260
+ const dtsShift = baseline;
2261
+ for (const sample of samples) {
2262
+ if (!sample.data) continue;
2263
+ outFile.addSample(outId, sample.data, {
2264
+ duration: sample.duration,
2265
+ dts: sample.dts - dtsShift,
2266
+ cts: sample.cts - dtsShift,
2267
+ is_sync: sample.is_sync
2268
+ });
2269
+ }
2270
+ };
2271
+ let buf;
2272
+ try {
2273
+ buf = MP4Box.MP4BoxBuffer.fromArrayBuffer(
2274
+ input.buffer.slice(
2275
+ input.byteOffset,
2276
+ input.byteOffset + input.byteLength
2277
+ ),
2278
+ 0
2279
+ );
2280
+ } catch (error) {
2281
+ fail(error);
2282
+ return;
2283
+ }
2284
+ try {
2285
+ inFile.appendBuffer(buf);
2286
+ inFile.flush();
2287
+ } catch (error) {
2288
+ fail(error);
2289
+ return;
2290
+ }
2291
+ if (settled) return;
2292
+ if (inToOutTrack.size === 0) {
2293
+ fail(new Error("no samples extracted from input"));
2294
+ return;
2295
+ }
2296
+ let output;
2297
+ try {
2298
+ const stream = outFile.getBuffer();
2299
+ output = new Uint8Array(
2300
+ stream.buffer.slice(0, stream.byteLength)
2301
+ );
2302
+ } catch (error) {
2303
+ fail(error);
2304
+ return;
2305
+ }
2306
+ settled = true;
2307
+ resolve(output);
2308
+ });
2309
+ });
2310
+ }
2311
+ function trackInfoById(file, id) {
2312
+ const info = file.getInfo();
2313
+ return info.tracks.find((t) => t.id === id);
2314
+ }
2315
+ function concatUint8Arrays(parts) {
2316
+ if (parts.length === 1) return parts[0];
2317
+ let total = 0;
2318
+ for (const p of parts) total += p.byteLength;
2319
+ const out = new Uint8Array(total);
2320
+ let offset = 0;
2321
+ for (const p of parts) {
2322
+ out.set(p, offset);
2323
+ offset += p.byteLength;
2324
+ }
2325
+ return out;
2326
+ }
2327
+ function resolveAgainst(target, base) {
2328
+ try {
2329
+ return new URL(target, base).toString();
2330
+ } catch (e) {
2331
+ return target;
2332
+ }
2333
+ }
2334
+ function parseRetryAfter(header, fallbackMs) {
2335
+ if (!header) return fallbackMs;
2336
+ const seconds = Number(header);
2337
+ if (Number.isFinite(seconds) && seconds >= 0) {
2338
+ return seconds * 1e3;
2339
+ }
2340
+ const dateMs = Date.parse(header);
2341
+ if (!Number.isNaN(dateMs)) {
2342
+ return Math.max(0, dateMs - Date.now());
2343
+ }
2344
+ return fallbackMs;
2345
+ }
2346
+ function sleep(ms, signal) {
2347
+ return new Promise((resolve, reject) => {
2348
+ if (signal == null ? void 0 : signal.aborted) {
2349
+ reject(new DOMException("Aborted", "AbortError"));
2350
+ return;
2351
+ }
2352
+ const timer = setTimeout(() => {
2353
+ signal == null ? void 0 : signal.removeEventListener("abort", onAbort);
2354
+ resolve();
2355
+ }, ms);
2356
+ const onAbort = () => {
2357
+ clearTimeout(timer);
2358
+ reject(new DOMException("Aborted", "AbortError"));
2359
+ };
2360
+ signal == null ? void 0 : signal.addEventListener("abort", onAbort, { once: true });
2361
+ });
2362
+ }
2363
+ function triggerBrowserDownload(blob, filename) {
2364
+ const objectUrl = URL.createObjectURL(blob);
2365
+ try {
2366
+ const a = document.createElement("a");
2367
+ a.href = objectUrl;
2368
+ a.download = filename;
2369
+ a.style.display = "none";
2370
+ document.body.appendChild(a);
2371
+ a.click();
2372
+ a.remove();
2373
+ } finally {
2374
+ URL.revokeObjectURL(objectUrl);
2375
+ }
2376
+ }
2377
+
2378
+ // src/core/RecordingClient.ts
2379
+ var DEFAULT_CLIP_REQUEST_TIMEOUT_MS = 1e4;
2380
+ var RecordingClient = class {
2381
+ constructor(host, options = {}) {
2382
+ this.host = host;
2383
+ // FIFO queue: the runtime processes requests in receipt order and
2384
+ // `clipFailed` carries no discriminator, so FIFO matching is the
2385
+ // simplest correct correlator.
2386
+ this.pendingClipRequests = [];
2387
+ /** Cleanup handles for the host event subscriptions. */
2388
+ this.unsubscribers = [];
2389
+ var _a;
2390
+ this.requestTimeoutMs = (_a = options.requestTimeoutMs) != null ? _a : DEFAULT_CLIP_REQUEST_TIMEOUT_MS;
2391
+ this.unsubscribers.push(
2392
+ this.host.onRuntimeMessage((message) => this.onRuntimeMessage(message))
2393
+ );
2394
+ this.unsubscribers.push(
2395
+ this.host.onStatusChanged((status) => this.onStatusChanged(status))
2396
+ );
2397
+ }
2398
+ /**
2399
+ * Request a clip covering the last `durationSeconds` of the live
2400
+ * session. See {@link Reactor.requestClip}.
2401
+ */
2402
+ requestClip(durationSeconds) {
2403
+ return __async(this, null, function* () {
2404
+ if (typeof durationSeconds !== "number" || !Number.isFinite(durationSeconds) || durationSeconds <= 0) {
2405
+ throw new RecordingError(
2406
+ "INVALID_DURATION",
2407
+ "durationSeconds must be a positive finite number"
2408
+ );
2409
+ }
2410
+ const status = this.host.getStatus();
2411
+ if (status !== "ready") {
2412
+ throw new RecordingError(
2413
+ "DISCONNECTED",
2414
+ `Cannot request clip while status is "${status}"`
2415
+ );
2416
+ }
2417
+ return this.dispatchClipRequest(RuntimeRecordingMessageType.REQUEST_CLIP, {
2418
+ duration_seconds: durationSeconds
2419
+ });
2420
+ });
2421
+ }
2422
+ /**
2423
+ * Request a clip covering the entire session up to "now". See
2424
+ * {@link Reactor.requestRecording}.
2425
+ */
2426
+ requestRecording() {
2427
+ return __async(this, null, function* () {
2428
+ const status = this.host.getStatus();
2429
+ if (status !== "ready") {
2430
+ throw new RecordingError(
2431
+ "DISCONNECTED",
2432
+ `Cannot request recording while status is "${status}"`
2433
+ );
2434
+ }
2435
+ return this.dispatchClipRequest(
2436
+ RuntimeRecordingMessageType.REQUEST_RECORDING,
2437
+ {}
2438
+ );
2439
+ });
2440
+ }
2441
+ /**
2442
+ * Poll `/clips` and return the raw manifest body. Same polling
2443
+ * semantics as the bare {@link fetchPlaylist} helper; the caller is
2444
+ * responsible for supplying the Coordinator JWT via `options.jwt`
2445
+ * (origin-scoped to `clip.playlistUrl`). In local mode against the
2446
+ * HttpRuntime, `options.jwt` should be omitted.
2447
+ */
2448
+ fetchPlaylist(_0) {
2449
+ return __async(this, arguments, function* (clip, options = {}) {
2450
+ return fetchPlaylist(clip.playlistUrl, __spreadValues({
2451
+ predictedReadyAtMs: clip.predictedReadyAtMs
2452
+ }, options));
2453
+ });
2454
+ }
2455
+ /**
2456
+ * Fetch the manifest and return a `blob:` URL suitable for
2457
+ * `<video src>` / `hls.js`. The player reads the manifest from
2458
+ * browser memory; chunk URLs inside are presigned S3 GETs.
2459
+ *
2460
+ * Caller owns the returned URL — revoke it via `URL.revokeObjectURL`
2461
+ * when playback tears down. Pass `options.jwt` for production
2462
+ * `/clips` (the Coordinator hop) — see {@link FetchPlaylistOptions}.
2463
+ */
2464
+ getPlayableManifestUrl(_0) {
2465
+ return __async(this, arguments, function* (clip, options = {}) {
2466
+ const body = yield this.fetchPlaylist(clip, options);
2467
+ return createPlayableManifestUrl(body, clip.playlistUrl);
2468
+ });
2469
+ }
2470
+ /**
2471
+ * Thin delegation to {@link downloadClipAsFile}. Caller must pass
2472
+ * `options.jwt` in production — see {@link DownloadClipOptions}.
2473
+ */
2474
+ downloadClipAsFile(clip, filename = "reactor-clip.mp4", options) {
2475
+ return __async(this, null, function* () {
2476
+ return downloadClipAsFile(clip, filename, options);
2477
+ });
2478
+ }
2479
+ /**
2480
+ * Drop every pending request and unsubscribe from host events.
2481
+ * Safe to call multiple times; further `requestClip` /
2482
+ * `requestRecording` calls after `destroy()` will hang waiting for
2483
+ * a response that will never arrive — host should not call into
2484
+ * the client after destroy.
2485
+ */
2486
+ destroy() {
2487
+ this.rejectPending("RecordingClient destroyed");
2488
+ while (this.unsubscribers.length > 0) {
2489
+ const off = this.unsubscribers.pop();
2490
+ try {
2491
+ off == null ? void 0 : off();
2492
+ } catch (e) {
2493
+ }
2494
+ }
2495
+ }
2496
+ /**
2497
+ * Register a pending FIFO entry, send the runtime message via
2498
+ * the host, and resolve when the next `clipReady` / `clipFailed`
2499
+ * arrives.
2500
+ */
2501
+ dispatchClipRequest(messageType, payload) {
2502
+ return new Promise((resolve, reject) => {
2503
+ const pending = { resolve, reject };
2504
+ pending.timeoutHandle = setTimeout(() => {
2505
+ const idx = this.pendingClipRequests.indexOf(pending);
2506
+ if (idx === -1) return;
2507
+ this.pendingClipRequests.splice(idx, 1);
2508
+ reject(
2509
+ new RecordingError(
2510
+ "REQUEST_TIMEOUT",
2511
+ `No clipReady/clipFailed within ${this.requestTimeoutMs}ms`
2512
+ )
2513
+ );
2514
+ }, this.requestTimeoutMs);
2515
+ this.pendingClipRequests.push(pending);
2516
+ try {
2517
+ void this.host.sendRuntimeCommand(messageType, payload);
2518
+ } catch (error) {
2519
+ const idx = this.pendingClipRequests.indexOf(pending);
2520
+ if (idx !== -1) this.pendingClipRequests.splice(idx, 1);
2521
+ if (pending.timeoutHandle) clearTimeout(pending.timeoutHandle);
2522
+ reject(
2523
+ new RecordingError(
2524
+ "INTERNAL_ERROR",
2525
+ `Failed to send ${messageType}: ${error.message}`
2526
+ )
2527
+ );
2528
+ }
2529
+ });
2530
+ }
2531
+ /**
2532
+ * Match inbound `clipReady` / `clipFailed` to the next pending
2533
+ * request FIFO; ignore every other runtime message type.
2534
+ */
2535
+ onRuntimeMessage(message) {
2536
+ var _a;
2537
+ if (!message || typeof message !== "object") return;
2538
+ const msg = message;
2539
+ const type = msg.type;
2540
+ if (type !== RuntimeRecordingMessageType.CLIP_READY && type !== RuntimeRecordingMessageType.CLIP_FAILED) {
2541
+ return;
2542
+ }
2543
+ const pending = this.pendingClipRequests.shift();
2544
+ if (!pending) {
2545
+ console.warn("[Reactor] Received", type, "with no pending request");
2546
+ return;
2547
+ }
2548
+ if (pending.timeoutHandle) clearTimeout(pending.timeoutHandle);
2549
+ if (type === RuntimeRecordingMessageType.CLIP_READY) {
2550
+ const parsed = ClipReadyPayloadSchema.safeParse(msg.data);
2551
+ if (!parsed.success) {
2552
+ pending.reject(
2553
+ new RecordingError(
2554
+ "INTERNAL_ERROR",
2555
+ `Malformed clipReady payload: ${parsed.error.message}`
2556
+ )
2557
+ );
2558
+ return;
2559
+ }
2560
+ pending.resolve(
2561
+ clipFromPayload(parsed.data, {
2562
+ coordinatorBaseUrl: this.host.getCoordinatorBaseUrl()
2563
+ })
2564
+ );
2565
+ return;
2566
+ }
2567
+ const parsedFail = ClipFailedPayloadSchema.safeParse((_a = msg.data) != null ? _a : {});
2568
+ const reason = parsedFail.success ? parsedFail.data.reason : "unknown";
2569
+ pending.reject(
2570
+ new RecordingError(
2571
+ reason === "recorder disabled" || reason === "recorder disabled or encoder crashed" ? "RECORDER_DISABLED" : "INTERNAL_ERROR",
2572
+ reason
2573
+ )
2574
+ );
2575
+ }
2576
+ onStatusChanged(status) {
2577
+ if (status === "disconnected") {
2578
+ this.rejectPending("Reactor disconnected");
2579
+ }
2580
+ }
2581
+ /** Reject every in-flight request with a typed disconnect error. */
2582
+ rejectPending(reason) {
2583
+ if (this.pendingClipRequests.length === 0) return;
2584
+ const pending = this.pendingClipRequests;
2585
+ this.pendingClipRequests = [];
2586
+ for (const entry of pending) {
2587
+ if (entry.timeoutHandle) clearTimeout(entry.timeoutHandle);
2588
+ entry.reject(new RecordingError("DISCONNECTED", reason));
2589
+ }
2590
+ }
2591
+ };
2592
+
2593
+ // src/core/Reactor.ts
1876
2594
  var LOCAL_COORDINATOR_URL = "http://localhost:8080";
1877
2595
  var DEFAULT_BASE_URL = "https://api.reactor.inc";
1878
- var TrackHintSchema = import_zod2.z.object({
1879
- name: import_zod2.z.string(),
1880
- kind: import_zod2.z.enum(["video", "audio"]),
1881
- direction: import_zod2.z.enum(["recvonly", "sendonly"])
2596
+ var TrackHintSchema = import_zod3.z.object({
2597
+ name: import_zod3.z.string(),
2598
+ kind: import_zod3.z.enum(["video", "audio"]),
2599
+ direction: import_zod3.z.enum(["recvonly", "sendonly"])
1882
2600
  });
1883
- var OptionsSchema = import_zod2.z.object({
1884
- apiUrl: import_zod2.z.string().default(DEFAULT_BASE_URL),
1885
- modelName: import_zod2.z.string(),
1886
- local: import_zod2.z.boolean().default(false),
1887
- modelTracks: import_zod2.z.array(TrackHintSchema).optional()
2601
+ var OptionsSchema = import_zod3.z.object({
2602
+ apiUrl: import_zod3.z.string().default(DEFAULT_BASE_URL),
2603
+ modelName: import_zod3.z.string(),
2604
+ local: import_zod3.z.boolean().default(false),
2605
+ modelTracks: import_zod3.z.array(TrackHintSchema).optional()
1888
2606
  });
1889
2607
  var Reactor = class {
1890
2608
  constructor(options) {
@@ -1901,6 +2619,28 @@ var Reactor = class {
1901
2619
  if (validatedOptions.modelTracks) {
1902
2620
  this.presetTracks = validatedOptions.modelTracks;
1903
2621
  }
2622
+ this.recording = new RecordingClient({
2623
+ onRuntimeMessage: (handler) => {
2624
+ this.on("runtimeMessage", handler);
2625
+ return () => this.off("runtimeMessage", handler);
2626
+ },
2627
+ onStatusChanged: (handler) => {
2628
+ this.on("statusChanged", handler);
2629
+ return () => this.off("statusChanged", handler);
2630
+ },
2631
+ sendRuntimeCommand: (command, data) => this.sendCommand(command, data, "runtime"),
2632
+ getStatus: () => this.status,
2633
+ getCoordinatorBaseUrl: () => this.coordinatorUrl
2634
+ });
2635
+ }
2636
+ /**
2637
+ * Returns the JWT resolver supplied to the most recent
2638
+ * {@link connect} call, or `undefined` if none was set (pre-connect
2639
+ * or local mode). Used by clip surfaces as a fallback when their
2640
+ * own `getJwt` prop is omitted.
2641
+ */
2642
+ getJwtResolver() {
2643
+ return this.jwtResolver;
1904
2644
  }
1905
2645
  on(event, handler) {
1906
2646
  if (!this.eventListeners.has(event)) {
@@ -2041,6 +2781,41 @@ var Reactor = class {
2041
2781
  return new FileRef(slot.presigned_id, name, mimeType, size);
2042
2782
  });
2043
2783
  }
2784
+ /**
2785
+ * Request a clip covering the last `durationSeconds` of the live
2786
+ * session. Capped server-side at `recording.clip_max_seconds`
2787
+ * (default 5 minutes). Resolves with a {@link Clip} whose
2788
+ * `playlistUrl` can be handed to any HLS-capable player.
2789
+ *
2790
+ * @throws {RecordingError} on invalid input, transport failure,
2791
+ * timeout, runtime-side `clipFailed`, or disconnect mid-request.
2792
+ */
2793
+ requestClip(durationSeconds) {
2794
+ return __async(this, null, function* () {
2795
+ return this.recording.requestClip(durationSeconds);
2796
+ });
2797
+ }
2798
+ /**
2799
+ * Request a clip covering the entire session up to "now". Same
2800
+ * mechanics as {@link requestClip} with `start = 0`; only the
2801
+ * resolved {@link Clip.kind} discriminator differs.
2802
+ */
2803
+ requestRecording() {
2804
+ return __async(this, null, function* () {
2805
+ return this.recording.requestRecording();
2806
+ });
2807
+ }
2808
+ /**
2809
+ * Stream the chunks referenced by `clip.playlistUrl` and trigger a
2810
+ * native browser download of the assembled fragmented-MP4 Blob.
2811
+ * Pass `filename: null` to skip the download trigger and receive
2812
+ * the Blob (useful for non-DOM consumers and tests).
2813
+ */
2814
+ downloadClipAsFile(clip, filename = "reactor-clip.mp4", options) {
2815
+ return __async(this, null, function* () {
2816
+ return this.recording.downloadClipAsFile(clip, filename, options);
2817
+ });
2818
+ }
2044
2819
  /**
2045
2820
  * Publishes a MediaStreamTrack to a named sendonly track.
2046
2821
  * The transceiver is already set up from capabilities — this just
@@ -2129,7 +2904,10 @@ var Reactor = class {
2129
2904
  }
2130
2905
  /**
2131
2906
  * Connects to the coordinator, creates a session, then establishes
2132
- * the transport using server-declared capabilities.
2907
+ * the transport using server-declared capabilities. `jwtToken` may
2908
+ * be a static string or a {@link JwtSource} resolver; pass a
2909
+ * resolver when the token is short-lived so each Coordinator HTTP
2910
+ * hop sees a fresh value.
2133
2911
  */
2134
2912
  connect(jwtToken, options) {
2135
2913
  return __async(this, null, function* () {
@@ -2142,6 +2920,9 @@ var Reactor = class {
2142
2920
  }
2143
2921
  this.setStatus("connecting");
2144
2922
  this.connectStartTime = performance.now();
2923
+ if (!this.local && jwtToken !== void 0) {
2924
+ this.jwtResolver = normalizeJwtSource(jwtToken);
2925
+ }
2145
2926
  try {
2146
2927
  this.coordinatorClient = this.local ? new LocalCoordinatorClient(this.coordinatorUrl, this.model) : new CoordinatorClient({
2147
2928
  baseUrl: this.coordinatorUrl,
@@ -2586,12 +3367,27 @@ function ReactorProvider(_a) {
2586
3367
  var _b = _a, {
2587
3368
  children,
2588
3369
  connectOptions,
2589
- jwtToken
3370
+ jwtToken,
3371
+ getJwt
2590
3372
  } = _b, props = __objRest(_b, [
2591
3373
  "children",
2592
3374
  "connectOptions",
2593
- "jwtToken"
3375
+ "jwtToken",
3376
+ "getJwt"
2594
3377
  ]);
3378
+ const getJwtRef = (0, import_react3.useRef)(getJwt);
3379
+ (0, import_react3.useEffect)(() => {
3380
+ getJwtRef.current = getJwt;
3381
+ });
3382
+ const hasGetJwt = getJwt !== void 0;
3383
+ const stableGetJwt = (0, import_react3.useMemo)(() => {
3384
+ if (!hasGetJwt) return void 0;
3385
+ return () => __async(null, null, function* () {
3386
+ const r = getJwtRef.current;
3387
+ return r ? yield r() : "";
3388
+ });
3389
+ }, [hasGetJwt]);
3390
+ const jwtSource = stableGetJwt != null ? stableGetJwt : jwtToken;
2595
3391
  const storeRef = (0, import_react3.useRef)(void 0);
2596
3392
  const firstRender = (0, import_react3.useRef)(true);
2597
3393
  const [_storeVersion, setStoreVersion] = (0, import_react3.useState)(0);
@@ -2599,7 +3395,7 @@ function ReactorProvider(_a) {
2599
3395
  console.debug("[ReactorProvider] Creating new reactor store");
2600
3396
  storeRef.current = createReactorStore(
2601
3397
  initReactorStore(__spreadProps(__spreadValues({}, props), {
2602
- jwtToken
3398
+ jwtToken: jwtSource
2603
3399
  }))
2604
3400
  );
2605
3401
  console.debug("[ReactorProvider] Reactor store created successfully");
@@ -2624,11 +3420,11 @@ function ReactorProvider(_a) {
2624
3420
  if (firstRender.current) {
2625
3421
  firstRender.current = false;
2626
3422
  const current2 = storeRef.current;
2627
- if (autoConnect && current2.getState().status === "disconnected" && jwtToken) {
3423
+ if (autoConnect && current2.getState().status === "disconnected" && jwtSource) {
2628
3424
  console.debug(
2629
3425
  "[ReactorProvider] Starting autoconnect in first render..."
2630
3426
  );
2631
- current2.getState().connect(jwtToken, pollingOptions).then(() => {
3427
+ current2.getState().connect(jwtSource, pollingOptions).then(() => {
2632
3428
  console.debug(
2633
3429
  "[ReactorProvider] Autoconnect successful in first render"
2634
3430
  );
@@ -2661,7 +3457,7 @@ function ReactorProvider(_a) {
2661
3457
  apiUrl,
2662
3458
  modelName,
2663
3459
  local,
2664
- jwtToken
3460
+ jwtToken: jwtSource
2665
3461
  })
2666
3462
  );
2667
3463
  const current = storeRef.current;
@@ -2669,9 +3465,9 @@ function ReactorProvider(_a) {
2669
3465
  console.debug(
2670
3466
  "[ReactorProvider] Reactor store updated successfully, and increased version"
2671
3467
  );
2672
- if (autoConnect && current.getState().status === "disconnected" && jwtToken) {
3468
+ if (autoConnect && current.getState().status === "disconnected" && jwtSource) {
2673
3469
  console.debug("[ReactorProvider] Starting autoconnect...");
2674
- current.getState().connect(jwtToken, pollingOptions).then(() => {
3470
+ current.getState().connect(jwtSource, pollingOptions).then(() => {
2675
3471
  console.debug("[ReactorProvider] Autoconnect successful");
2676
3472
  }).catch((error) => {
2677
3473
  console.error("[ReactorProvider] Failed to autoconnect:", error);
@@ -2687,7 +3483,7 @@ function ReactorProvider(_a) {
2687
3483
  console.error("[ReactorProvider] Failed to disconnect:", error);
2688
3484
  });
2689
3485
  };
2690
- }, [apiUrl, modelName, autoConnect, local, jwtToken, maxAttempts]);
3486
+ }, [apiUrl, modelName, autoConnect, local, jwtSource, maxAttempts]);
2691
3487
  return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ReactorContext.Provider, { value: storeRef.current, children });
2692
3488
  }
2693
3489
  function useReactorStore(selector) {
@@ -3594,18 +4390,324 @@ function WebcamStream({
3594
4390
  }
3595
4391
  );
3596
4392
  }
4393
+
4394
+ // src/react/ClipPlayer.tsx
4395
+ var import_react8 = require("react");
4396
+ var import_jsx_runtime5 = require("react/jsx-runtime");
4397
+ function ClipPlayer({
4398
+ clip,
4399
+ getJwt,
4400
+ slackMs,
4401
+ autoPlay = true,
4402
+ muted = true,
4403
+ className,
4404
+ style
4405
+ }) {
4406
+ const videoRef = (0, import_react8.useRef)(null);
4407
+ const [phase, setPhase] = (0, import_react8.useState)({ kind: "waiting" });
4408
+ const store = (0, import_react8.useContext)(ReactorContext);
4409
+ const getJwtRef = (0, import_react8.useRef)(getJwt);
4410
+ const autoPlayRef = (0, import_react8.useRef)(autoPlay);
4411
+ const slackMsRef = (0, import_react8.useRef)(slackMs);
4412
+ const storeRef = (0, import_react8.useRef)(store);
4413
+ (0, import_react8.useEffect)(() => {
4414
+ getJwtRef.current = getJwt;
4415
+ autoPlayRef.current = autoPlay;
4416
+ slackMsRef.current = slackMs;
4417
+ storeRef.current = store;
4418
+ });
4419
+ (0, import_react8.useEffect)(() => {
4420
+ const video = videoRef.current;
4421
+ if (!video) return;
4422
+ const abort = new AbortController();
4423
+ let cancelled = false;
4424
+ let hlsInstance = null;
4425
+ let manifestBlobUrl = null;
4426
+ const fail = (message) => {
4427
+ if (cancelled) return;
4428
+ setPhase({ kind: "error", message });
4429
+ };
4430
+ const attachPlayer = (manifestUrl) => __async(null, null, function* () {
4431
+ const canPlayNative = video.canPlayType("application/vnd.apple.mpegurl") !== "";
4432
+ if (canPlayNative) {
4433
+ video.src = manifestUrl;
4434
+ if (autoPlayRef.current) {
4435
+ video.play().catch(() => {
4436
+ });
4437
+ }
4438
+ if (!cancelled) setPhase({ kind: "ready" });
4439
+ return;
4440
+ }
4441
+ let HlsCtor;
4442
+ try {
4443
+ const mod = yield import("hls.js");
4444
+ HlsCtor = mod.default;
4445
+ } catch (e) {
4446
+ fail(
4447
+ "HLS playback unavailable in this browser. Install `hls.js` as a peer dependency, or use Download."
4448
+ );
4449
+ return;
4450
+ }
4451
+ if (cancelled) return;
4452
+ if (!HlsCtor.isSupported()) {
4453
+ fail("This browser cannot play HLS clips. Use Download instead.");
4454
+ return;
4455
+ }
4456
+ const hls = new HlsCtor();
4457
+ hls.loadSource(manifestUrl);
4458
+ hls.attachMedia(video);
4459
+ hls.on(HlsCtor.Events.MANIFEST_PARSED, () => {
4460
+ if (cancelled) return;
4461
+ setPhase({ kind: "ready" });
4462
+ if (autoPlayRef.current) {
4463
+ video.play().catch(() => {
4464
+ });
4465
+ }
4466
+ });
4467
+ hls.on(HlsCtor.Events.ERROR, (_evt, data) => {
4468
+ var _a;
4469
+ if (cancelled) return;
4470
+ if (data.fatal) {
4471
+ fail(`Playback error: ${(_a = data.details) != null ? _a : "unknown"}`);
4472
+ return;
4473
+ }
4474
+ console.warn("[Reactor.ClipPlayer] hls.js non-fatal error", data);
4475
+ });
4476
+ hlsInstance = hls;
4477
+ });
4478
+ const setup = () => __async(null, null, function* () {
4479
+ var _a;
4480
+ try {
4481
+ setPhase({ kind: "waiting" });
4482
+ const explicit = getJwtRef.current;
4483
+ const fallback = (_a = storeRef.current) == null ? void 0 : _a.getState().internal.reactor.getJwtResolver();
4484
+ const resolver = explicit != null ? explicit : fallback;
4485
+ const jwt = resolver ? yield resolver() : void 0;
4486
+ if (cancelled) return;
4487
+ const body = yield fetchPlaylist(clip.playlistUrl, {
4488
+ predictedReadyAtMs: clip.predictedReadyAtMs,
4489
+ slackMs: slackMsRef.current,
4490
+ jwt,
4491
+ signal: abort.signal
4492
+ });
4493
+ if (cancelled) return;
4494
+ setPhase({ kind: "loading" });
4495
+ manifestBlobUrl = createPlayableManifestUrl(body, clip.playlistUrl);
4496
+ yield attachPlayer(manifestBlobUrl);
4497
+ } catch (err) {
4498
+ if (cancelled) return;
4499
+ if (err instanceof DOMException && err.name === "AbortError") {
4500
+ return;
4501
+ }
4502
+ const message = err instanceof RecordingError ? `${err.code}: ${err.reason}` : err instanceof Error ? err.message : String(err);
4503
+ fail(message);
4504
+ }
4505
+ });
4506
+ setup();
4507
+ return () => {
4508
+ cancelled = true;
4509
+ abort.abort();
4510
+ hlsInstance == null ? void 0 : hlsInstance.destroy();
4511
+ video.pause();
4512
+ video.removeAttribute("src");
4513
+ video.load();
4514
+ if (manifestBlobUrl) URL.revokeObjectURL(manifestBlobUrl);
4515
+ };
4516
+ }, [clip]);
4517
+ const overlayText = phase.kind === "waiting" ? "Waiting for clip\u2026" : phase.kind === "loading" ? "Loading player\u2026" : null;
4518
+ return /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(
4519
+ "div",
4520
+ {
4521
+ className,
4522
+ style: __spreadValues({
4523
+ position: "relative",
4524
+ background: "#000",
4525
+ width: "100%",
4526
+ display: "flex",
4527
+ alignItems: "center",
4528
+ justifyContent: "center"
4529
+ }, style),
4530
+ children: [
4531
+ /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
4532
+ "video",
4533
+ {
4534
+ ref: videoRef,
4535
+ controls: true,
4536
+ playsInline: true,
4537
+ muted,
4538
+ style: {
4539
+ display: "block",
4540
+ width: "100%",
4541
+ height: "auto",
4542
+ maxHeight: "100%"
4543
+ }
4544
+ }
4545
+ ),
4546
+ overlayText && /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
4547
+ "div",
4548
+ {
4549
+ style: {
4550
+ position: "absolute",
4551
+ inset: 0,
4552
+ display: "flex",
4553
+ alignItems: "center",
4554
+ justifyContent: "center",
4555
+ color: "rgba(255,255,255,0.6)",
4556
+ font: "11px ui-monospace, SFMono-Regular, Menlo, monospace",
4557
+ letterSpacing: "0.1em",
4558
+ textTransform: "uppercase",
4559
+ pointerEvents: "none"
4560
+ },
4561
+ children: overlayText
4562
+ }
4563
+ ),
4564
+ phase.kind === "error" && /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
4565
+ "div",
4566
+ {
4567
+ style: {
4568
+ position: "absolute",
4569
+ inset: 0,
4570
+ display: "flex",
4571
+ alignItems: "center",
4572
+ justifyContent: "center",
4573
+ padding: 24,
4574
+ background: "rgba(0,0,0,0.8)",
4575
+ color: "#ef4444",
4576
+ font: "11px ui-monospace, SFMono-Regular, Menlo, monospace",
4577
+ textAlign: "center"
4578
+ },
4579
+ children: phase.message
4580
+ }
4581
+ )
4582
+ ]
4583
+ }
4584
+ );
4585
+ }
4586
+
4587
+ // src/react/useClipDownload.ts
4588
+ var import_react9 = require("react");
4589
+ function useClipDownload(clip, options = {}) {
4590
+ var _a;
4591
+ const [state, setState] = (0, import_react9.useState)({ kind: "idle" });
4592
+ const store = (0, import_react9.useContext)(ReactorContext);
4593
+ const clipRef = (0, import_react9.useRef)(clip);
4594
+ const filenameRef = (0, import_react9.useRef)(
4595
+ (_a = options.filename) != null ? _a : "reactor-clip.mp4"
4596
+ );
4597
+ const getJwtRef = (0, import_react9.useRef)(options.getJwt);
4598
+ (0, import_react9.useEffect)(() => {
4599
+ clipRef.current = clip;
4600
+ filenameRef.current = options.filename === void 0 ? "reactor-clip.mp4" : options.filename;
4601
+ getJwtRef.current = options.getJwt;
4602
+ });
4603
+ const inFlightRef = (0, import_react9.useRef)(false);
4604
+ const download = (0, import_react9.useCallback)(() => __async(null, null, function* () {
4605
+ if (inFlightRef.current) return void 0;
4606
+ inFlightRef.current = true;
4607
+ setState({ kind: "downloading", fetched: 0, total: 0 });
4608
+ try {
4609
+ const explicit = getJwtRef.current;
4610
+ const fallback = store == null ? void 0 : store.getState().internal.reactor.getJwtResolver();
4611
+ const resolver = explicit != null ? explicit : fallback;
4612
+ const jwt = resolver ? yield resolver() : void 0;
4613
+ const blob = yield downloadClipAsFile(
4614
+ clipRef.current,
4615
+ filenameRef.current,
4616
+ {
4617
+ jwt,
4618
+ onProgress: ({ fetched, total }) => setState({ kind: "downloading", fetched, total })
4619
+ }
4620
+ );
4621
+ setState({ kind: "idle" });
4622
+ return blob;
4623
+ } catch (err) {
4624
+ const message = err instanceof RecordingError ? `${err.code}: ${err.reason}` : err instanceof Error ? err.message : String(err);
4625
+ setState({ kind: "error", message });
4626
+ return void 0;
4627
+ } finally {
4628
+ inFlightRef.current = false;
4629
+ }
4630
+ }), [store]);
4631
+ const reset = (0, import_react9.useCallback)(() => setState({ kind: "idle" }), []);
4632
+ return { state, download, reset };
4633
+ }
4634
+
4635
+ // src/react/ClipDownloadButton.tsx
4636
+ var import_jsx_runtime6 = require("react/jsx-runtime");
4637
+ function ClipDownloadButton({
4638
+ clip,
4639
+ getJwt,
4640
+ filename = "reactor-clip.mp4",
4641
+ children,
4642
+ className,
4643
+ style,
4644
+ disabled
4645
+ }) {
4646
+ const { state, download } = useClipDownload(clip, { filename, getJwt });
4647
+ const downloading = state.kind === "downloading";
4648
+ const isDisabled = downloading || !!disabled;
4649
+ const content = typeof children === "function" ? children(state) : children !== void 0 ? children : defaultLabel(state);
4650
+ return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
4651
+ "button",
4652
+ {
4653
+ type: "button",
4654
+ onClick: () => {
4655
+ void download();
4656
+ },
4657
+ disabled: isDisabled,
4658
+ title: state.kind === "error" ? state.message : void 0,
4659
+ className,
4660
+ style: __spreadValues({
4661
+ padding: "5px 12px",
4662
+ borderRadius: 4,
4663
+ border: "1px solid rgba(255,255,255,0.15)",
4664
+ background: "rgba(255,255,255,0.05)",
4665
+ color: "#fff",
4666
+ font: "11px ui-monospace, SFMono-Regular, Menlo, monospace",
4667
+ cursor: isDisabled ? "default" : "pointer",
4668
+ opacity: isDisabled ? 0.6 : 1,
4669
+ transition: "background-color 120ms ease"
4670
+ }, style),
4671
+ children: content
4672
+ }
4673
+ );
4674
+ }
4675
+ function defaultLabel(state) {
4676
+ if (state.kind === "downloading") {
4677
+ if (state.total > 0) {
4678
+ return `Downloading ${state.fetched}/${state.total}\u2026`;
4679
+ }
4680
+ return "Downloading\u2026";
4681
+ }
4682
+ return "Download";
4683
+ }
3597
4684
  // Annotate the CommonJS export names for ESM import in node:
3598
4685
  0 && (module.exports = {
3599
4686
  AbortError,
4687
+ ClipDownloadButton,
4688
+ ClipPlayer,
3600
4689
  ConflictError,
3601
4690
  DEFAULT_BASE_URL,
4691
+ DEFAULT_CLIP_REQUEST_TIMEOUT_MS,
4692
+ DEFAULT_PLAYLIST_POLL_SLACK_MS,
3602
4693
  FileRef,
3603
4694
  Reactor,
3604
4695
  ReactorController,
3605
4696
  ReactorProvider,
3606
4697
  ReactorView,
4698
+ RecordingClient,
4699
+ RecordingError,
4700
+ RuntimeRecordingMessageType,
3607
4701
  WebcamStream,
4702
+ clipFromPayload,
4703
+ createPlayableManifestUrl,
4704
+ downloadClipAsFile,
4705
+ fetchPlaylist,
3608
4706
  isAbortError,
4707
+ normalizeJwtSource,
4708
+ parsePlaylist,
4709
+ rewriteUrlHost,
4710
+ useClipDownload,
3609
4711
  useReactor,
3610
4712
  useReactorInternalMessage,
3611
4713
  useReactorMessage,