@reactor-team/js-sdk 2.11.0 → 2.11.2

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
@@ -153,7 +153,7 @@ var import_zod = require("zod");
153
153
  // package.json
154
154
  var package_default = {
155
155
  name: "@reactor-team/js-sdk",
156
- version: "2.11.0",
156
+ version: "2.11.2",
157
157
  description: "Reactor JavaScript frontend SDK \u2014 connect React and TypeScript apps to real-time AI video models on Reactor.",
158
158
  license: "Apache-2.0",
159
159
  repository: {
@@ -465,6 +465,18 @@ var CoordinatorClient = class {
465
465
  return parsed;
466
466
  });
467
467
  }
468
+ /**
469
+ * Attaches to a session created elsewhere (e.g. by a backend) instead of
470
+ * creating one via {@link createSession}. After this, {@link pollSessionReady}
471
+ * and {@link getSession} operate on the adopted id. The session must be owned
472
+ * by the account behind this client's JWT.
473
+ */
474
+ adoptSession(sessionId) {
475
+ return __async(this, null, function* () {
476
+ this.currentSessionId = sessionId;
477
+ console.debug("[CoordinatorClient] Adopted existing session:", sessionId);
478
+ });
479
+ }
468
480
  /**
469
481
  * Polls GET /sessions/{id} until the Runtime has accepted the session
470
482
  * and populated capabilities and selected_transport.
@@ -756,6 +768,48 @@ var LocalCoordinatorClient = class extends CoordinatorClient {
756
768
  return CreateSessionResponseSchema.parse(data);
757
769
  });
758
770
  }
771
+ /**
772
+ * Adopts the local session for `connect({ sessionId })`: records the id and
773
+ * reads the session descriptor, caching it so {@link pollSessionReady}
774
+ * returns immediately. No `start_session` is issued.
775
+ *
776
+ * The local runtime hosts a single session (always id `"local"`), so the
777
+ * lookup ignores the specific id. This is a pure read of session info — it
778
+ * does not start or otherwise advance the session.
779
+ */
780
+ adoptSession(sessionId) {
781
+ return __async(this, null, function* () {
782
+ this.currentSessionId = sessionId;
783
+ this.cachedSessionResponse = yield this.getSession();
784
+ console.debug(
785
+ "[LocalCoordinatorClient] Adopted existing session:",
786
+ sessionId
787
+ );
788
+ });
789
+ }
790
+ /**
791
+ * Reads the local session descriptor (model, capabilities, transport,
792
+ * state) via the runtime's read-only `GET /session`.
793
+ *
794
+ * The local runtime exposes a single session, so — unlike the Coordinator's
795
+ * id-addressed `GET /sessions/{id}` — there is no id in the path. Read-only:
796
+ * it does not start or advance the session.
797
+ */
798
+ getSession() {
799
+ return __async(this, null, function* () {
800
+ const response = yield fetch(`${this.baseUrl}/session`, {
801
+ method: "GET",
802
+ headers: yield this.getHeaders(),
803
+ signal: this.signal
804
+ });
805
+ if (!response.ok) {
806
+ const errorText = yield response.text();
807
+ throw new Error(`Failed to get session: ${response.status} ${errorText}`);
808
+ }
809
+ const data = yield response.json();
810
+ return SessionResponseSchema.parse(data);
811
+ });
812
+ }
759
813
  /**
760
814
  * Returns the cached full session response immediately.
761
815
  * The local runtime already provided everything in start_session.
@@ -2735,9 +2789,13 @@ var Reactor = class {
2735
2789
  sendCommand(command, data, scope = "application") {
2736
2790
  return __async(this, null, function* () {
2737
2791
  var _a;
2738
- if (process.env.NODE_ENV !== "development" && this.status !== "ready") {
2739
- const errorMessage = `Cannot send message, status is ${this.status}`;
2740
- console.warn("[Reactor]", errorMessage);
2792
+ if (this.status !== "ready") {
2793
+ this.createError(
2794
+ "NOT_READY",
2795
+ `Cannot send command "${command}" while status is "${this.status}". Must be "ready".`,
2796
+ "api",
2797
+ true
2798
+ );
2741
2799
  return;
2742
2800
  }
2743
2801
  try {
@@ -2977,6 +3035,12 @@ var Reactor = class {
2977
3035
  * be a static string or a {@link JwtSource} resolver; pass a
2978
3036
  * resolver when the token is short-lived so each Coordinator HTTP
2979
3037
  * hop sees a fresh value.
3038
+ *
3039
+ * Pass `options.sessionId` to attach to a session that already exists
3040
+ * (e.g. one created by a backend) instead of creating a new one — session
3041
+ * creation is skipped and the transport is brought up against that id. The
3042
+ * `jwtToken` must be valid for the account that owns the session. Works in
3043
+ * local mode too (it looks the session up by id rather than starting one).
2980
3044
  */
2981
3045
  connect(jwtToken, options) {
2982
3046
  return __async(this, null, function* () {
@@ -2998,20 +3062,29 @@ var Reactor = class {
2998
3062
  jwtToken,
2999
3063
  model: this.model
3000
3064
  });
3001
- const tSession = performance.now();
3002
- const initialResponse = yield this.coordinatorClient.createSession();
3003
- const sessionCreationMs = performance.now() - tSession;
3004
- this.setSessionId(initialResponse.session_id);
3005
- console.debug(
3006
- "[Reactor] Session created:",
3007
- initialResponse.session_id,
3008
- "state:",
3009
- initialResponse.state
3010
- );
3065
+ let sessionCreationMs = 0;
3066
+ let sessionId;
3067
+ if (options == null ? void 0 : options.sessionId) {
3068
+ yield this.coordinatorClient.adoptSession(options.sessionId);
3069
+ sessionId = options.sessionId;
3070
+ console.debug("[Reactor] Attaching to existing session:", sessionId);
3071
+ } else {
3072
+ const tSession = performance.now();
3073
+ const initialResponse = yield this.coordinatorClient.createSession();
3074
+ sessionCreationMs = performance.now() - tSession;
3075
+ sessionId = initialResponse.session_id;
3076
+ console.debug(
3077
+ "[Reactor] Session created:",
3078
+ sessionId,
3079
+ "state:",
3080
+ initialResponse.state
3081
+ );
3082
+ }
3083
+ this.setSessionId(sessionId);
3011
3084
  this.setStatus("waiting");
3012
3085
  this.transportClient = new WebRTCTransportClient({
3013
3086
  baseUrl: this.coordinatorUrl,
3014
- sessionId: initialResponse.session_id,
3087
+ sessionId,
3015
3088
  jwtToken: this.local ? "local" : jwtToken,
3016
3089
  webrtcVersion: REACTOR_WEBRTC_VERSION,
3017
3090
  maxPollAttempts: options == null ? void 0 : options.maxAttempts
@@ -3424,7 +3497,10 @@ var createReactorStore = (initProps, publicState = defaultInitState) => {
3424
3497
  console.error("[ReactorStore] Failed to upload file:", error);
3425
3498
  throw error;
3426
3499
  }
3427
- })
3500
+ }),
3501
+ requestClip: (durationSeconds) => get().internal.reactor.requestClip(durationSeconds),
3502
+ requestRecording: () => get().internal.reactor.requestRecording(),
3503
+ downloadClipAsFile: (clip, filename, options) => get().internal.reactor.downloadClipAsFile(clip, filename, options)
3428
3504
  });
3429
3505
  });
3430
3506
  };
@@ -3552,7 +3628,7 @@ function ReactorProvider(_a) {
3552
3628
  console.error("[ReactorProvider] Failed to disconnect:", error);
3553
3629
  });
3554
3630
  };
3555
- }, [apiUrl, modelName, autoConnect, local, jwtSource, maxAttempts]);
3631
+ }, [apiUrl, modelName, local, jwtSource]);
3556
3632
  return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ReactorContext.Provider, { value: storeRef.current, children });
3557
3633
  }
3558
3634
  function useReactorStore(selector) {
@@ -3628,7 +3704,7 @@ function ReactorView({
3628
3704
  className,
3629
3705
  style,
3630
3706
  videoObjectFit = "contain",
3631
- muted = true
3707
+ muted = audioTrack === void 0
3632
3708
  }) {
3633
3709
  const { videoMediaTrack, audioMediaTrack } = useReactor((state) => {
3634
3710
  var _a, _b;
@@ -4271,6 +4347,8 @@ var import_react7 = require("react");
4271
4347
  var import_jsx_runtime4 = require("react/jsx-runtime");
4272
4348
  function WebcamStream({
4273
4349
  track,
4350
+ audio = false,
4351
+ audioTrack,
4274
4352
  className,
4275
4353
  style,
4276
4354
  videoConstraints = {
@@ -4278,7 +4356,10 @@ function WebcamStream({
4278
4356
  height: { ideal: 720 }
4279
4357
  },
4280
4358
  showWebcam = true,
4281
- videoObjectFit = "contain"
4359
+ videoObjectFit = "contain",
4360
+ onPermissionDenied,
4361
+ onPublished,
4362
+ onError
4282
4363
  }) {
4283
4364
  const [stream, setStream] = (0, import_react7.useState)(null);
4284
4365
  const [isPublishing, setIsPublishing] = (0, import_react7.useState)(false);
@@ -4290,12 +4371,28 @@ function WebcamStream({
4290
4371
  reactor: state.internal.reactor
4291
4372
  }));
4292
4373
  const videoRef = (0, import_react7.useRef)(null);
4374
+ const onPermissionDeniedRef = (0, import_react7.useRef)(onPermissionDenied);
4375
+ const onPublishedRef = (0, import_react7.useRef)(onPublished);
4376
+ const onErrorRef = (0, import_react7.useRef)(onError);
4377
+ (0, import_react7.useEffect)(() => {
4378
+ onPermissionDeniedRef.current = onPermissionDenied;
4379
+ onPublishedRef.current = onPublished;
4380
+ onErrorRef.current = onError;
4381
+ });
4382
+ const audioRequested = audio !== false && audio !== void 0;
4383
+ const audioEnabled = audioRequested && !!audioTrack;
4384
+ if (audioRequested && !audioTrack) {
4385
+ console.warn(
4386
+ "[WebcamStream] `audio` was set but `audioTrack` is missing; capturing video-only."
4387
+ );
4388
+ }
4293
4389
  const startWebcam = () => __async(null, null, function* () {
4390
+ var _a, _b;
4294
4391
  console.debug("[WebcamPublisher] Starting webcam");
4295
4392
  try {
4296
4393
  const mediaStream = yield navigator.mediaDevices.getUserMedia({
4297
4394
  video: videoConstraints,
4298
- audio: false
4395
+ audio: audioEnabled ? audio === true ? true : audio : false
4299
4396
  });
4300
4397
  console.debug("[WebcamPublisher] Webcam started successfully");
4301
4398
  setStream(mediaStream);
@@ -4305,16 +4402,34 @@ function WebcamStream({
4305
4402
  if (err instanceof DOMException && (err.name === "NotAllowedError" || err.name === "PermissionDeniedError")) {
4306
4403
  console.debug("[WebcamPublisher] Camera permission denied");
4307
4404
  setPermissionDenied(true);
4405
+ (_a = onPermissionDeniedRef.current) == null ? void 0 : _a.call(onPermissionDeniedRef);
4406
+ } else {
4407
+ (_b = onErrorRef.current) == null ? void 0 : _b.call(
4408
+ onErrorRef,
4409
+ err instanceof Error ? err : new Error(String(err))
4410
+ );
4308
4411
  }
4309
4412
  }
4310
4413
  });
4311
4414
  const stopWebcam = () => __async(null, null, function* () {
4415
+ var _a;
4312
4416
  console.debug("[WebcamPublisher] Stopping webcam");
4313
- try {
4314
- yield unpublish(track);
4315
- console.debug("[WebcamPublisher] Unpublished before stopping");
4316
- } catch (err) {
4317
- console.error("[WebcamPublisher] Error unpublishing before stop:", err);
4417
+ const unpublishTasks = [unpublish(track)];
4418
+ if (audioEnabled && audioTrack) {
4419
+ unpublishTasks.push(unpublish(audioTrack));
4420
+ }
4421
+ const results = yield Promise.allSettled(unpublishTasks);
4422
+ for (const r of results) {
4423
+ if (r.status === "rejected") {
4424
+ console.error(
4425
+ "[WebcamPublisher] Error unpublishing before stop:",
4426
+ r.reason
4427
+ );
4428
+ (_a = onErrorRef.current) == null ? void 0 : _a.call(
4429
+ onErrorRef,
4430
+ r.reason instanceof Error ? r.reason : new Error(String(r.reason))
4431
+ );
4432
+ }
4318
4433
  }
4319
4434
  setIsPublishing(false);
4320
4435
  stream == null ? void 0 : stream.getTracks().forEach((t) => {
@@ -4349,25 +4464,54 @@ function WebcamStream({
4349
4464
  console.debug(
4350
4465
  "[WebcamPublisher] Reactor ready, auto-publishing webcam stream"
4351
4466
  );
4352
- const videoTrack = stream.getVideoTracks()[0];
4353
- if (videoTrack) {
4354
- publish(track, videoTrack).then(() => {
4355
- console.debug("[WebcamPublisher] Auto-publish successful");
4356
- setIsPublishing(true);
4357
- }).catch((err) => {
4358
- console.error("[WebcamPublisher] Auto-publish failed:", err);
4359
- });
4360
- }
4467
+ const videoMediaTrack = stream.getVideoTracks()[0];
4468
+ const audioMediaTrack = audioEnabled && audioTrack ? stream.getAudioTracks()[0] : null;
4469
+ const tasks = [];
4470
+ if (videoMediaTrack) tasks.push(publish(track, videoMediaTrack));
4471
+ if (audioMediaTrack && audioTrack)
4472
+ tasks.push(publish(audioTrack, audioMediaTrack));
4473
+ if (tasks.length === 0) return;
4474
+ Promise.all(tasks).then(() => {
4475
+ var _a;
4476
+ console.debug("[WebcamPublisher] Auto-publish successful");
4477
+ setIsPublishing(true);
4478
+ (_a = onPublishedRef.current) == null ? void 0 : _a.call(onPublishedRef);
4479
+ }).catch((err) => {
4480
+ var _a;
4481
+ console.error("[WebcamPublisher] Auto-publish failed:", err);
4482
+ (_a = onErrorRef.current) == null ? void 0 : _a.call(
4483
+ onErrorRef,
4484
+ err instanceof Error ? err : new Error(String(err))
4485
+ );
4486
+ });
4361
4487
  } else if (status !== "ready" && isPublishing) {
4362
4488
  console.debug("[WebcamPublisher] Reactor not ready, auto-unpublishing");
4363
- unpublish(track).then(() => {
4364
- console.debug("[WebcamPublisher] Auto-unpublish successful");
4489
+ const tasks = [unpublish(track)];
4490
+ if (audioEnabled && audioTrack) tasks.push(unpublish(audioTrack));
4491
+ Promise.allSettled(tasks).then((results) => {
4492
+ var _a;
4493
+ for (const r of results) {
4494
+ if (r.status === "rejected") {
4495
+ console.error("[WebcamPublisher] Auto-unpublish failed:", r.reason);
4496
+ (_a = onErrorRef.current) == null ? void 0 : _a.call(
4497
+ onErrorRef,
4498
+ r.reason instanceof Error ? r.reason : new Error(String(r.reason))
4499
+ );
4500
+ }
4501
+ }
4365
4502
  setIsPublishing(false);
4366
- }).catch((err) => {
4367
- console.error("[WebcamPublisher] Auto-unpublish failed:", err);
4368
4503
  });
4369
4504
  }
4370
- }, [status, stream, isPublishing, publish, unpublish, track]);
4505
+ }, [
4506
+ status,
4507
+ stream,
4508
+ isPublishing,
4509
+ publish,
4510
+ unpublish,
4511
+ track,
4512
+ audioEnabled,
4513
+ audioTrack
4514
+ ]);
4371
4515
  (0, import_react7.useEffect)(() => {
4372
4516
  const handleError = (error) => {
4373
4517
  console.debug("[WebcamPublisher] Received error event:", error);
@@ -4470,7 +4614,8 @@ function ClipPlayer({
4470
4614
  autoPlay = true,
4471
4615
  muted = true,
4472
4616
  className,
4473
- style
4617
+ style,
4618
+ onError
4474
4619
  }) {
4475
4620
  const videoRef = (0, import_react8.useRef)(null);
4476
4621
  const [phase, setPhase] = (0, import_react8.useState)({ kind: "waiting" });
@@ -4478,13 +4623,21 @@ function ClipPlayer({
4478
4623
  const getJwtRef = (0, import_react8.useRef)(getJwt);
4479
4624
  const autoPlayRef = (0, import_react8.useRef)(autoPlay);
4480
4625
  const slackMsRef = (0, import_react8.useRef)(slackMs);
4626
+ const onErrorRef = (0, import_react8.useRef)(onError);
4481
4627
  const storeRef = (0, import_react8.useRef)(store);
4482
4628
  (0, import_react8.useEffect)(() => {
4483
4629
  getJwtRef.current = getJwt;
4484
4630
  autoPlayRef.current = autoPlay;
4485
4631
  slackMsRef.current = slackMs;
4632
+ onErrorRef.current = onError;
4486
4633
  storeRef.current = store;
4487
4634
  });
4635
+ (0, import_react8.useEffect)(() => {
4636
+ var _a;
4637
+ if (phase.kind === "error") {
4638
+ (_a = onErrorRef.current) == null ? void 0 : _a.call(onErrorRef, phase.error);
4639
+ }
4640
+ }, [phase]);
4488
4641
  (0, import_react8.useEffect)(() => {
4489
4642
  const video = videoRef.current;
4490
4643
  if (!video) return;
@@ -4492,9 +4645,10 @@ function ClipPlayer({
4492
4645
  let cancelled = false;
4493
4646
  let hlsInstance = null;
4494
4647
  let manifestBlobUrl = null;
4495
- const fail = (message) => {
4648
+ const fail = (error) => {
4496
4649
  if (cancelled) return;
4497
- setPhase({ kind: "error", message });
4650
+ const message = error instanceof RecordingError ? `${error.code}: ${error.reason}` : error.message;
4651
+ setPhase({ kind: "error", message, error });
4498
4652
  };
4499
4653
  const attachPlayer = (manifestUrl) => __async(null, null, function* () {
4500
4654
  const canPlayNative = video.canPlayType("application/vnd.apple.mpegurl") !== "";
@@ -4513,13 +4667,17 @@ function ClipPlayer({
4513
4667
  HlsCtor = mod.default;
4514
4668
  } catch (e) {
4515
4669
  fail(
4516
- "HLS playback unavailable in this browser. Install `hls.js` as a peer dependency, or use Download."
4670
+ new Error(
4671
+ "HLS playback unavailable in this browser. Install `hls.js` as a peer dependency, or use Download."
4672
+ )
4517
4673
  );
4518
4674
  return;
4519
4675
  }
4520
4676
  if (cancelled) return;
4521
4677
  if (!HlsCtor.isSupported()) {
4522
- fail("This browser cannot play HLS clips. Use Download instead.");
4678
+ fail(
4679
+ new Error("This browser cannot play HLS clips. Use Download instead.")
4680
+ );
4523
4681
  return;
4524
4682
  }
4525
4683
  const hls = new HlsCtor();
@@ -4537,7 +4695,7 @@ function ClipPlayer({
4537
4695
  var _a;
4538
4696
  if (cancelled) return;
4539
4697
  if (data.fatal) {
4540
- fail(`Playback error: ${(_a = data.details) != null ? _a : "unknown"}`);
4698
+ fail(new Error(`Playback error: ${(_a = data.details) != null ? _a : "unknown"}`));
4541
4699
  return;
4542
4700
  }
4543
4701
  console.warn("[Reactor.ClipPlayer] hls.js non-fatal error", data);
@@ -4568,8 +4726,7 @@ function ClipPlayer({
4568
4726
  if (err instanceof DOMException && err.name === "AbortError") {
4569
4727
  return;
4570
4728
  }
4571
- const message = err instanceof RecordingError ? `${err.code}: ${err.reason}` : err instanceof Error ? err.message : String(err);
4572
- fail(message);
4729
+ fail(err instanceof Error ? err : new Error(String(err)));
4573
4730
  }
4574
4731
  });
4575
4732
  setup();
@@ -4653,6 +4810,9 @@ function ClipPlayer({
4653
4810
  );
4654
4811
  }
4655
4812
 
4813
+ // src/react/ClipDownloadButton.tsx
4814
+ var import_react10 = require("react");
4815
+
4656
4816
  // src/react/useClipDownload.ts
4657
4817
  var import_react9 = require("react");
4658
4818
  function useClipDownload(clip, options = {}) {
@@ -4710,18 +4870,35 @@ function ClipDownloadButton({
4710
4870
  children,
4711
4871
  className,
4712
4872
  style,
4713
- disabled
4873
+ disabled,
4874
+ onSuccess,
4875
+ onError
4714
4876
  }) {
4715
4877
  const { state, download } = useClipDownload(clip, { filename, getJwt });
4716
4878
  const downloading = state.kind === "downloading";
4717
4879
  const isDisabled = downloading || !!disabled;
4880
+ const onSuccessRef = (0, import_react10.useRef)(onSuccess);
4881
+ const onErrorRef = (0, import_react10.useRef)(onError);
4882
+ (0, import_react10.useEffect)(() => {
4883
+ onSuccessRef.current = onSuccess;
4884
+ onErrorRef.current = onError;
4885
+ });
4886
+ (0, import_react10.useEffect)(() => {
4887
+ var _a;
4888
+ if (state.kind === "error") {
4889
+ (_a = onErrorRef.current) == null ? void 0 : _a.call(onErrorRef, new Error(state.message));
4890
+ }
4891
+ }, [state]);
4718
4892
  const content = typeof children === "function" ? children(state) : children !== void 0 ? children : defaultLabel(state);
4719
4893
  return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
4720
4894
  "button",
4721
4895
  {
4722
4896
  type: "button",
4723
4897
  onClick: () => {
4724
- void download();
4898
+ void download().then((blob) => {
4899
+ var _a;
4900
+ if (blob) (_a = onSuccessRef.current) == null ? void 0 : _a.call(onSuccessRef, blob);
4901
+ });
4725
4902
  },
4726
4903
  disabled: isDisabled,
4727
4904
  title: state.kind === "error" ? state.message : void 0,