@reactor-team/js-sdk 2.11.1 → 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.d.mts CHANGED
@@ -136,6 +136,13 @@ interface ReactorState$1 {
136
136
  interface ConnectOptions {
137
137
  /** Maximum number of SDP polling attempts before giving up. Default: 6. */
138
138
  maxAttempts?: number;
139
+ /**
140
+ * Attach to a session that already exists (e.g. one created by a backend)
141
+ * instead of creating a new one. When set, `connect()` skips `POST /sessions`
142
+ * and brings up the transport directly against this id. The JWT passed to
143
+ * `connect()` must be valid for the account that owns the session.
144
+ */
145
+ sessionId?: string;
139
146
  }
140
147
  /**
141
148
  * Transport-agnostic timing breakdown of the connect() handshake, recorded
@@ -177,6 +184,50 @@ interface ConnectionStats {
177
184
  timestamp: number;
178
185
  }
179
186
  type ReactorEvent = "statusChanged" | "sessionIdChanged" | "message" | "runtimeMessage" | "trackReceived" | "error" | "sessionExpirationChanged" | "capabilitiesReceived" | "statsUpdate";
187
+ /**
188
+ * Severity tier of a content moderation event delivered as the inner
189
+ * payload of a `runtimeMessage` with `type === "moderation"`.
190
+ *
191
+ * - `"warn"`: the input scored above the warn threshold but below the
192
+ * terminate threshold. The session continues; this is informational
193
+ * only.
194
+ * - `"terminate"`: the input crossed the terminate threshold. The
195
+ * session will be ended shortly after this message is dispatched.
196
+ */
197
+ type ModerationAction = "warn" | "terminate";
198
+ /**
199
+ * Inner payload of a `runtimeMessage` with `type === "moderation"`.
200
+ *
201
+ * Surfaces a content-moderation outcome to the client app. Fires on
202
+ * any moderatable input (free-text fields, file uploads) that the
203
+ * configured moderation policy flags. Apps receive it by subscribing
204
+ * to the existing `runtimeMessage` event and filtering on `type`:
205
+ *
206
+ * reactor.on("runtimeMessage", (m) => {
207
+ * if (m?.type === "moderation") {
208
+ * const payload = m.data as ModerationEvent;
209
+ * // ...render banner, log, etc.
210
+ * }
211
+ * });
212
+ */
213
+ interface ModerationEvent {
214
+ /** Severity tier — `"warn"` continues the session, `"terminate"` ends it. */
215
+ action: ModerationAction;
216
+ /**
217
+ * Modality of the flagged input. `"text"` for string fields,
218
+ * `"image"` for `UploadedFile` payloads with an image MIME type.
219
+ */
220
+ input_kind: "text" | "image";
221
+ /**
222
+ * Name of the inbound command/event whose payload was flagged
223
+ * (e.g. `"set_prompt"`, `"set_image"`, `"fileUploaded"`).
224
+ */
225
+ command: string;
226
+ /** Category labels that flagged (e.g. `["sexual"]`, `["violence/graphic"]`). */
227
+ categories: string[];
228
+ /** Short human-readable summary suitable for UI rendering. */
229
+ message: string;
230
+ }
180
231
 
181
232
  /**
182
233
  * Lazy resolver for the Coordinator bearer token. The SDK calls this
@@ -676,6 +727,12 @@ declare class Reactor {
676
727
  * be a static string or a {@link JwtSource} resolver; pass a
677
728
  * resolver when the token is short-lived so each Coordinator HTTP
678
729
  * hop sees a fresh value.
730
+ *
731
+ * Pass `options.sessionId` to attach to a session that already exists
732
+ * (e.g. one created by a backend) instead of creating a new one — session
733
+ * creation is skipped and the transport is brought up against that id. The
734
+ * `jwtToken` must be valid for the account that owns the session. Works in
735
+ * local mode too (it looks the session up by id rather than starting one).
679
736
  */
680
737
  connect(jwtToken?: JwtSource, options?: ConnectOptions): Promise<void>;
681
738
  /**
@@ -719,6 +776,11 @@ interface ReactorState {
719
776
  }
720
777
  interface ReactorActions {
721
778
  sendCommand(command: string, data: any, scope?: MessageScope): Promise<void>;
779
+ /**
780
+ * Connect the underlying {@link Reactor}. `options` is forwarded verbatim —
781
+ * pass `options.sessionId` to attach to an existing session instead of
782
+ * creating one (see {@link ConnectOptions}).
783
+ */
722
784
  connect(jwtToken?: JwtSource, options?: ConnectOptions): Promise<void>;
723
785
  disconnect(recoverable?: boolean): Promise<void>;
724
786
  publish(name: string, track: MediaStreamTrack): Promise<void>;
@@ -1161,4 +1223,4 @@ declare function useReactorInternalMessage(handler: (message: any) => void): voi
1161
1223
  */
1162
1224
  declare function useStats(): ConnectionStats | undefined;
1163
1225
 
1164
- export { AbortError, type Capabilities, type Clip, ClipDownloadButton, type ClipDownloadButtonProps, type ClipDownloadState, type ClipFailedPayload, type ClipKind, ClipPlayer, type ClipPlayerProps, type ClipReadyPayload, type CommandCapability, ConflictError, type ConnectOptions, type ConnectionStats, type ConnectionTimings, DEFAULT_BASE_URL, DEFAULT_CLIP_REQUEST_TIMEOUT_MS, DEFAULT_PLAYLIST_POLL_SLACK_MS, type DownloadClipOptions, type FetchPlaylistOptions, FileRef, type JwtResolver, type JwtSource, type MessageScope, type Options, type ParseClipOptions, Reactor, type ReactorConnectOptions, ReactorController, type ReactorControllerProps, type ReactorError, type ReactorEvent, ReactorProvider, type ReactorState$1 as ReactorState, type ReactorStatus, type ReactorStore, ReactorView, type ReactorViewProps, RecordingClient, type RecordingClientHost, RecordingError, RuntimeRecordingMessageType, type SessionResponse, type TrackCapability, type UseClipDownloadOptions, type UseClipDownloadResult, WebcamStream, type WebcamStreamProps, clipFromPayload, createPlayableManifestUrl, downloadClipAsFile, fetchPlaylist, isAbortError, normalizeJwtSource, parsePlaylist, rewriteUrlHost, useClipDownload, useReactor, useReactorInternalMessage, useReactorMessage, useReactorStore, useStats };
1226
+ export { AbortError, type Capabilities, type Clip, ClipDownloadButton, type ClipDownloadButtonProps, type ClipDownloadState, type ClipFailedPayload, type ClipKind, ClipPlayer, type ClipPlayerProps, type ClipReadyPayload, type CommandCapability, ConflictError, type ConnectOptions, type ConnectionStats, type ConnectionTimings, DEFAULT_BASE_URL, DEFAULT_CLIP_REQUEST_TIMEOUT_MS, DEFAULT_PLAYLIST_POLL_SLACK_MS, type DownloadClipOptions, type FetchPlaylistOptions, FileRef, type JwtResolver, type JwtSource, type MessageScope, type ModerationAction, type ModerationEvent, type Options, type ParseClipOptions, Reactor, type ReactorConnectOptions, ReactorController, type ReactorControllerProps, type ReactorError, type ReactorEvent, ReactorProvider, type ReactorState$1 as ReactorState, type ReactorStatus, type ReactorStore, ReactorView, type ReactorViewProps, RecordingClient, type RecordingClientHost, RecordingError, RuntimeRecordingMessageType, type SessionResponse, type TrackCapability, type UseClipDownloadOptions, type UseClipDownloadResult, WebcamStream, type WebcamStreamProps, clipFromPayload, createPlayableManifestUrl, downloadClipAsFile, fetchPlaylist, isAbortError, normalizeJwtSource, parsePlaylist, rewriteUrlHost, useClipDownload, useReactor, useReactorInternalMessage, useReactorMessage, useReactorStore, useStats };
package/dist/index.d.ts CHANGED
@@ -136,6 +136,13 @@ interface ReactorState$1 {
136
136
  interface ConnectOptions {
137
137
  /** Maximum number of SDP polling attempts before giving up. Default: 6. */
138
138
  maxAttempts?: number;
139
+ /**
140
+ * Attach to a session that already exists (e.g. one created by a backend)
141
+ * instead of creating a new one. When set, `connect()` skips `POST /sessions`
142
+ * and brings up the transport directly against this id. The JWT passed to
143
+ * `connect()` must be valid for the account that owns the session.
144
+ */
145
+ sessionId?: string;
139
146
  }
140
147
  /**
141
148
  * Transport-agnostic timing breakdown of the connect() handshake, recorded
@@ -177,6 +184,50 @@ interface ConnectionStats {
177
184
  timestamp: number;
178
185
  }
179
186
  type ReactorEvent = "statusChanged" | "sessionIdChanged" | "message" | "runtimeMessage" | "trackReceived" | "error" | "sessionExpirationChanged" | "capabilitiesReceived" | "statsUpdate";
187
+ /**
188
+ * Severity tier of a content moderation event delivered as the inner
189
+ * payload of a `runtimeMessage` with `type === "moderation"`.
190
+ *
191
+ * - `"warn"`: the input scored above the warn threshold but below the
192
+ * terminate threshold. The session continues; this is informational
193
+ * only.
194
+ * - `"terminate"`: the input crossed the terminate threshold. The
195
+ * session will be ended shortly after this message is dispatched.
196
+ */
197
+ type ModerationAction = "warn" | "terminate";
198
+ /**
199
+ * Inner payload of a `runtimeMessage` with `type === "moderation"`.
200
+ *
201
+ * Surfaces a content-moderation outcome to the client app. Fires on
202
+ * any moderatable input (free-text fields, file uploads) that the
203
+ * configured moderation policy flags. Apps receive it by subscribing
204
+ * to the existing `runtimeMessage` event and filtering on `type`:
205
+ *
206
+ * reactor.on("runtimeMessage", (m) => {
207
+ * if (m?.type === "moderation") {
208
+ * const payload = m.data as ModerationEvent;
209
+ * // ...render banner, log, etc.
210
+ * }
211
+ * });
212
+ */
213
+ interface ModerationEvent {
214
+ /** Severity tier — `"warn"` continues the session, `"terminate"` ends it. */
215
+ action: ModerationAction;
216
+ /**
217
+ * Modality of the flagged input. `"text"` for string fields,
218
+ * `"image"` for `UploadedFile` payloads with an image MIME type.
219
+ */
220
+ input_kind: "text" | "image";
221
+ /**
222
+ * Name of the inbound command/event whose payload was flagged
223
+ * (e.g. `"set_prompt"`, `"set_image"`, `"fileUploaded"`).
224
+ */
225
+ command: string;
226
+ /** Category labels that flagged (e.g. `["sexual"]`, `["violence/graphic"]`). */
227
+ categories: string[];
228
+ /** Short human-readable summary suitable for UI rendering. */
229
+ message: string;
230
+ }
180
231
 
181
232
  /**
182
233
  * Lazy resolver for the Coordinator bearer token. The SDK calls this
@@ -676,6 +727,12 @@ declare class Reactor {
676
727
  * be a static string or a {@link JwtSource} resolver; pass a
677
728
  * resolver when the token is short-lived so each Coordinator HTTP
678
729
  * hop sees a fresh value.
730
+ *
731
+ * Pass `options.sessionId` to attach to a session that already exists
732
+ * (e.g. one created by a backend) instead of creating a new one — session
733
+ * creation is skipped and the transport is brought up against that id. The
734
+ * `jwtToken` must be valid for the account that owns the session. Works in
735
+ * local mode too (it looks the session up by id rather than starting one).
679
736
  */
680
737
  connect(jwtToken?: JwtSource, options?: ConnectOptions): Promise<void>;
681
738
  /**
@@ -719,6 +776,11 @@ interface ReactorState {
719
776
  }
720
777
  interface ReactorActions {
721
778
  sendCommand(command: string, data: any, scope?: MessageScope): Promise<void>;
779
+ /**
780
+ * Connect the underlying {@link Reactor}. `options` is forwarded verbatim —
781
+ * pass `options.sessionId` to attach to an existing session instead of
782
+ * creating one (see {@link ConnectOptions}).
783
+ */
722
784
  connect(jwtToken?: JwtSource, options?: ConnectOptions): Promise<void>;
723
785
  disconnect(recoverable?: boolean): Promise<void>;
724
786
  publish(name: string, track: MediaStreamTrack): Promise<void>;
@@ -1161,4 +1223,4 @@ declare function useReactorInternalMessage(handler: (message: any) => void): voi
1161
1223
  */
1162
1224
  declare function useStats(): ConnectionStats | undefined;
1163
1225
 
1164
- export { AbortError, type Capabilities, type Clip, ClipDownloadButton, type ClipDownloadButtonProps, type ClipDownloadState, type ClipFailedPayload, type ClipKind, ClipPlayer, type ClipPlayerProps, type ClipReadyPayload, type CommandCapability, ConflictError, type ConnectOptions, type ConnectionStats, type ConnectionTimings, DEFAULT_BASE_URL, DEFAULT_CLIP_REQUEST_TIMEOUT_MS, DEFAULT_PLAYLIST_POLL_SLACK_MS, type DownloadClipOptions, type FetchPlaylistOptions, FileRef, type JwtResolver, type JwtSource, type MessageScope, type Options, type ParseClipOptions, Reactor, type ReactorConnectOptions, ReactorController, type ReactorControllerProps, type ReactorError, type ReactorEvent, ReactorProvider, type ReactorState$1 as ReactorState, type ReactorStatus, type ReactorStore, ReactorView, type ReactorViewProps, RecordingClient, type RecordingClientHost, RecordingError, RuntimeRecordingMessageType, type SessionResponse, type TrackCapability, type UseClipDownloadOptions, type UseClipDownloadResult, WebcamStream, type WebcamStreamProps, clipFromPayload, createPlayableManifestUrl, downloadClipAsFile, fetchPlaylist, isAbortError, normalizeJwtSource, parsePlaylist, rewriteUrlHost, useClipDownload, useReactor, useReactorInternalMessage, useReactorMessage, useReactorStore, useStats };
1226
+ export { AbortError, type Capabilities, type Clip, ClipDownloadButton, type ClipDownloadButtonProps, type ClipDownloadState, type ClipFailedPayload, type ClipKind, ClipPlayer, type ClipPlayerProps, type ClipReadyPayload, type CommandCapability, ConflictError, type ConnectOptions, type ConnectionStats, type ConnectionTimings, DEFAULT_BASE_URL, DEFAULT_CLIP_REQUEST_TIMEOUT_MS, DEFAULT_PLAYLIST_POLL_SLACK_MS, type DownloadClipOptions, type FetchPlaylistOptions, FileRef, type JwtResolver, type JwtSource, type MessageScope, type ModerationAction, type ModerationEvent, type Options, type ParseClipOptions, Reactor, type ReactorConnectOptions, ReactorController, type ReactorControllerProps, type ReactorError, type ReactorEvent, ReactorProvider, type ReactorState$1 as ReactorState, type ReactorStatus, type ReactorStore, ReactorView, type ReactorViewProps, RecordingClient, type RecordingClientHost, RecordingError, RuntimeRecordingMessageType, type SessionResponse, type TrackCapability, type UseClipDownloadOptions, type UseClipDownloadResult, WebcamStream, type WebcamStreamProps, clipFromPayload, createPlayableManifestUrl, downloadClipAsFile, fetchPlaylist, isAbortError, normalizeJwtSource, parsePlaylist, rewriteUrlHost, useClipDownload, useReactor, useReactorInternalMessage, useReactorMessage, useReactorStore, useStats };
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.1",
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.
@@ -2981,6 +3035,12 @@ var Reactor = class {
2981
3035
  * be a static string or a {@link JwtSource} resolver; pass a
2982
3036
  * resolver when the token is short-lived so each Coordinator HTTP
2983
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).
2984
3044
  */
2985
3045
  connect(jwtToken, options) {
2986
3046
  return __async(this, null, function* () {
@@ -3002,20 +3062,29 @@ var Reactor = class {
3002
3062
  jwtToken,
3003
3063
  model: this.model
3004
3064
  });
3005
- const tSession = performance.now();
3006
- const initialResponse = yield this.coordinatorClient.createSession();
3007
- const sessionCreationMs = performance.now() - tSession;
3008
- this.setSessionId(initialResponse.session_id);
3009
- console.debug(
3010
- "[Reactor] Session created:",
3011
- initialResponse.session_id,
3012
- "state:",
3013
- initialResponse.state
3014
- );
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);
3015
3084
  this.setStatus("waiting");
3016
3085
  this.transportClient = new WebRTCTransportClient({
3017
3086
  baseUrl: this.coordinatorUrl,
3018
- sessionId: initialResponse.session_id,
3087
+ sessionId,
3019
3088
  jwtToken: this.local ? "local" : jwtToken,
3020
3089
  webrtcVersion: REACTOR_WEBRTC_VERSION,
3021
3090
  maxPollAttempts: options == null ? void 0 : options.maxAttempts