@reactor-team/js-sdk 2.9.3 → 2.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -178,6 +178,368 @@ interface ConnectionStats {
178
178
  }
179
179
  type ReactorEvent = "statusChanged" | "sessionIdChanged" | "message" | "runtimeMessage" | "trackReceived" | "error" | "sessionExpirationChanged" | "capabilitiesReceived" | "statsUpdate";
180
180
 
181
+ /**
182
+ * Stateless primitives for the Reactor recording feature.
183
+ *
184
+ * This module owns:
185
+ * - Public-facing {@link Clip} type, {@link RecordingError} class, and
186
+ * the `RuntimeRecordingMessageType` enum.
187
+ * - Wire schemas (`ClipReadyPayloadSchema`, `ClipFailedPayloadSchema`)
188
+ * plus `clipFromPayload` to convert snake_case wire payloads into
189
+ * camelCase `Clip` objects.
190
+ * - HTTP helpers `fetchPlaylist` (deadline-driven polling) and
191
+ * `parsePlaylist` (HLS `.m3u8` parser).
192
+ * - The `downloadClipAsFile` helper that streams the referenced
193
+ * fMP4 chunks and byte-concatenates them into a fragmented-MP4
194
+ * Blob for browser download.
195
+ *
196
+ * Stateful pieces (FIFO promise correlator, in-flight request
197
+ * lifecycle, integration with Reactor's event bus) live in the
198
+ * `RecordingClient` class in `core/RecordingClient.ts`.
199
+ *
200
+ * Wire contract is documented end-to-end in the *Video Recording
201
+ * Feature* Notion page; the runtime side ships in
202
+ * `reactor_runtime/recording/`.
203
+ */
204
+
205
+ /**
206
+ * Names of the runtime-scoped messages used by the recording feature.
207
+ * Outbound names are sent via `Reactor.sendCommand(name, …, "runtime")`;
208
+ * inbound names appear as `message.type` on `runtimeMessage` events.
209
+ */
210
+ declare const RuntimeRecordingMessageType: {
211
+ readonly REQUEST_CLIP: "requestClip";
212
+ readonly REQUEST_RECORDING: "requestRecording";
213
+ readonly CLIP_READY: "clipReady";
214
+ readonly CLIP_FAILED: "clipFailed";
215
+ };
216
+ /** Discriminator on a {@link Clip}. `"snap"` from `requestClip`, `"recording"` from `requestRecording`. */
217
+ type ClipKind = "snap" | "recording";
218
+ /**
219
+ * Resolved outcome of a {@link Reactor.requestClip} / {@link Reactor.requestRecording} call.
220
+ *
221
+ * The runtime returns immediately on every request — it does *not*
222
+ * block until the in-progress chunk has been finalised. The response
223
+ * is a *promise*: `endMarker` reflects wall-clock at request time
224
+ * and may point inside a chunk ffmpeg is still writing. The
225
+ * `/clips` manifest endpoint returns `202 Retry-After` while that
226
+ * chunk is in flight; the SDK polls until `200`.
227
+ *
228
+ * - `startMarker` / `endMarker` / `nowMarker` are session-relative
229
+ * seconds since recorder start.
230
+ * - `predictedReadyAtMs` is a **Unix epoch in milliseconds** — the
231
+ * runtime's estimate of when the boundary chunk will be servable
232
+ * by `/clips`. Compare against `Date.now()` to drive a "ready in
233
+ * Ns" indicator. The SDK uses this as the polling deadline: past
234
+ * `predictedReadyAtMs + slackMs` and still 202, the SDK fails with
235
+ * `CLIP_NOT_READY` on the assumption the runtime crashed.
236
+ * - `playlistUrl` is short-lived in production (the embedded chunk
237
+ * URLs are presigned for a few minutes). Re-issuing the request
238
+ * produces a fresh URL with fresh presigning.
239
+ */
240
+ interface Clip {
241
+ sessionId: string;
242
+ kind: ClipKind;
243
+ startMarker: number;
244
+ endMarker: number;
245
+ nowMarker: number;
246
+ predictedReadyAtMs: number;
247
+ playlistUrl: string;
248
+ }
249
+ /**
250
+ * Error thrown when a recording request cannot be served.
251
+ *
252
+ * `code` is a stable, machine-readable identifier; `reason` is the
253
+ * raw string the runtime / manifest endpoint returned (passed through
254
+ * verbatim from `clipFailed.reason`, the `/clips` HTTP body, or the
255
+ * SDK's pre-flight check).
256
+ */
257
+ declare class RecordingError extends Error {
258
+ readonly code: "RECORDER_DISABLED" | "INVALID_DURATION" | "REQUEST_TIMEOUT" | "DISCONNECTED" | "CLIP_GONE" | "CLIP_NOT_READY" | "PLAYLIST_FETCH_FAILED" | "CHUNK_FETCH_FAILED" | "INVALID_PLAYLIST" | "DOWNLOAD_UNSUPPORTED" | "INTERNAL_ERROR";
259
+ readonly reason: string;
260
+ constructor(code: "RECORDER_DISABLED" | "INVALID_DURATION" | "REQUEST_TIMEOUT" | "DISCONNECTED" | "CLIP_GONE" | "CLIP_NOT_READY" | "PLAYLIST_FETCH_FAILED" | "CHUNK_FETCH_FAILED" | "INVALID_PLAYLIST" | "DOWNLOAD_UNSUPPORTED" | "INTERNAL_ERROR", reason: string);
261
+ }
262
+ /** `clipReady.data` payload as serialised by `ClipResult.to_dict()`. */
263
+ declare const ClipReadyPayloadSchema: z.ZodObject<{
264
+ session_id: z.ZodString;
265
+ kind: z.ZodEnum<{
266
+ snap: "snap";
267
+ recording: "recording";
268
+ }>;
269
+ start_marker: z.ZodNumber;
270
+ end_marker: z.ZodNumber;
271
+ now_marker: z.ZodNumber;
272
+ predicted_ready_at_ms: z.ZodNumber;
273
+ playlist_url: z.ZodString;
274
+ }, z.core.$loose>;
275
+ type ClipReadyPayload = z.infer<typeof ClipReadyPayloadSchema>;
276
+ /** `clipFailed.data` payload — short reason string from the runtime. */
277
+ declare const ClipFailedPayloadSchema: z.ZodObject<{
278
+ reason: z.ZodDefault<z.ZodString>;
279
+ }, z.core.$loose>;
280
+ type ClipFailedPayload = z.infer<typeof ClipFailedPayloadSchema>;
281
+ /** Options for {@link clipFromPayload}. */
282
+ interface ParseClipOptions {
283
+ /**
284
+ * Coordinator base URL. When set, resolves `payload.playlist_url`
285
+ * against this base — used to convert the runtime's path-only
286
+ * playlist URL (``/clips?session_id=…``) into an absolute URL the
287
+ * browser/SDK can fetch. Also handles the legacy case where an
288
+ * older runtime emits an absolute URL bound to its own
289
+ * ``0.0.0.0`` listener: the host/port are rewritten onto the
290
+ * coordinator.
291
+ */
292
+ coordinatorBaseUrl?: string;
293
+ }
294
+ /**
295
+ * Convert a validated {@link ClipReadyPayload} into the public {@link Clip}.
296
+ * Pure: no IO, no side effects.
297
+ */
298
+ declare function clipFromPayload(payload: ClipReadyPayload, options?: ParseClipOptions): Clip;
299
+ /**
300
+ * Resolve `target` against `base`, returning an absolute URL.
301
+ *
302
+ * Two cases:
303
+ *
304
+ * * **Path-only / relative target** (no scheme — e.g. the
305
+ * runtime's current ``/clips?session_id=…`` shape): joined
306
+ * against ``base`` via ``new URL(target, base)``, preserving
307
+ * path, query, and fragment.
308
+ * * **Absolute target** (``http://…`` / ``https://…``, e.g. a legacy
309
+ * runtime emitting a URL bound to its own ``0.0.0.0`` listener):
310
+ * scheme, hostname, and port are replaced with ``base``'s,
311
+ * preserving path, query, and fragment.
312
+ *
313
+ * Returns the original ``target`` on any parse failure rather than
314
+ * throwing — the SDK consumes the URL eagerly and shouldn't break
315
+ * a session over a malformed clip envelope.
316
+ */
317
+ declare function rewriteUrlHost(target: string, base: string): string;
318
+ /** Internal — segments referenced by an HLS manifest, in playback order. */
319
+ interface ParsedPlaylist {
320
+ initUrl: string;
321
+ segmentUrls: string[];
322
+ }
323
+ /**
324
+ * Default grace period after `predictedReadyAtMs` before
325
+ * {@link fetchPlaylist} gives up. Applied from
326
+ * `max(predictedReadyAtMs, pollStart)` so late clicks still get the
327
+ * full window.
328
+ */
329
+ declare const DEFAULT_PLAYLIST_POLL_SLACK_MS = 15000;
330
+ interface FetchPlaylistOptions {
331
+ /**
332
+ * Unix epoch (ms) when the runtime predicts the boundary chunk will
333
+ * be servable. Pass `clip.predictedReadyAtMs` here. When set, polling
334
+ * continues until `predictedReadyAtMs + slackMs`; once past, a
335
+ * stuck `202` produces `CLIP_NOT_READY` (assume runtime crashed).
336
+ */
337
+ predictedReadyAtMs?: number;
338
+ /** Grace period after `predictedReadyAtMs`. Default {@link DEFAULT_PLAYLIST_POLL_SLACK_MS}. */
339
+ slackMs?: number;
340
+ /**
341
+ * Hard cap on the per-poll wait. The server's `Retry-After` header is
342
+ * honored but clamped. Default 2000 ms keeps pending UI snappy.
343
+ */
344
+ maxRetryDelayMs?: number;
345
+ /** Floor on the per-poll wait so we don't hot-loop on cheap networks. Default 200 ms. */
346
+ minRetryDelayMs?: number;
347
+ /**
348
+ * Fallback retry count used when `predictedReadyAtMs` is omitted
349
+ * (e.g. someone calls `fetchPlaylist` directly with a saved URL,
350
+ * outside of a fresh `Clip`). Default 5.
351
+ */
352
+ maxRetries?: number;
353
+ /** Aborts in-flight fetches and the inter-poll sleep. */
354
+ signal?: AbortSignal;
355
+ /**
356
+ * Coordinator JWT. When set, attached as `Authorization: Bearer
357
+ * <jwt>` on the manifest GET — the Coordinator hop. In local mode
358
+ * (HttpRuntime), leave undefined.
359
+ */
360
+ jwt?: string;
361
+ }
362
+ /**
363
+ * Fetch the playlist URL, polling on `202 Accepted` (which the manifest
364
+ * endpoint returns while the boundary chunk is still uploading).
365
+ *
366
+ * Polling deadline is driven by `predictedReadyAtMs + slackMs` when a
367
+ * `Clip` was just minted by the runtime; without that field the
368
+ * function falls back to `maxRetries` attempts. Either way:
369
+ * - `200` → returns the manifest body.
370
+ * - `410` / `404` → throws `CLIP_GONE`.
371
+ * - `5xx`/other → throws `PLAYLIST_FETCH_FAILED` (no retry).
372
+ * - Past the deadline / retries with stuck `202` → throws
373
+ * `CLIP_NOT_READY` (the runtime probably crashed mid-chunk).
374
+ */
375
+ declare function fetchPlaylist(playlistUrl: string, options?: FetchPlaylistOptions): Promise<string>;
376
+ /**
377
+ * Parse an HLS `.m3u8` body into the init segment URL plus the ordered
378
+ * list of media segment URLs. Resolves relative URLs against the
379
+ * playlist URL itself.
380
+ */
381
+ declare function parsePlaylist(manifestBody: string, playlistUrl: string): ParsedPlaylist;
382
+ /**
383
+ * Wrap an HLS manifest body in a `blob:` URL suitable for `<video src>`
384
+ * or `hls.js`. Bypasses the "player can't set Authorization headers"
385
+ * problem: the manifest body is served from browser memory, and the
386
+ * chunk URLs inside are already-signed S3 GETs.
387
+ *
388
+ * Path-only / relative chunk URLs in the body are absolutized against
389
+ * ``playlistUrl`` first. Without this rewrite the browser would
390
+ * resolve them against the ``blob:`` URL's effective base — the page's
391
+ * origin — and a local-dev frontend on (e.g.) port 3000 would issue
392
+ * chunk fetches against its own dev server instead of the
393
+ * HttpRuntime's ``/clips/chunks/...`` endpoint on port 8080. In
394
+ * production / kind-cluster mode the manifest already carries absolute
395
+ * presigned S3 URLs and `resolveAgainst` is a no-op on them.
396
+ *
397
+ * Caller owns the returned URL — revoke it via `URL.revokeObjectURL`
398
+ * when playback tears down. Browser-only; throws `INVALID_PLAYLIST`
399
+ * outside a DOM environment.
400
+ */
401
+ declare function createPlayableManifestUrl(manifestBody: string, playlistUrl: string): string;
402
+ interface DownloadClipOptions {
403
+ /**
404
+ * Coordinator JWT. Attached on the manifest GET only; the chunks
405
+ * referenced inside the manifest are S3 presigned URLs and are
406
+ * fetched unauthenticated.
407
+ */
408
+ jwt?: string;
409
+ /** Forwarded to every request. Cancels both the playlist poll and any in-flight chunk fetches. */
410
+ signal?: AbortSignal;
411
+ /** Called after each chunk completes — useful for progress UI. */
412
+ onProgress?: (info: {
413
+ fetched: number;
414
+ total: number;
415
+ bytes: number;
416
+ }) => void;
417
+ }
418
+ /**
419
+ * Stream the chunks referenced by `clip.playlistUrl`, byte-concatenate
420
+ * them into a fragmented-MP4 Blob, and (when `filename` is non-null)
421
+ * trigger a browser-native `<a download>`. Pass `filename: null` to
422
+ * skip the download trigger and just receive the Blob.
423
+ */
424
+ declare function downloadClipAsFile(clip: Clip, filename?: string | null, options?: DownloadClipOptions): Promise<Blob>;
425
+
426
+ /**
427
+ * Per-Reactor recording client. Owns the FIFO promise correlator for
428
+ * inbound `clipReady` / `clipFailed` runtime messages and the
429
+ * lifecycle hooks (subscribe on construct, reject pending requests
430
+ * on disconnect). Reactor exposes thin delegations for the common
431
+ * case; this class is exported for advanced consumers and isolated
432
+ * testing.
433
+ */
434
+
435
+ /** Default per-request timeout for `clipReady` / `clipFailed`. */
436
+ declare const DEFAULT_CLIP_REQUEST_TIMEOUT_MS = 10000;
437
+ /** Slim adapter the {@link RecordingClient} requires from its host. */
438
+ interface RecordingClientHost {
439
+ /**
440
+ * Subscribe to runtime-scoped messages on the data channel.
441
+ * Returns an unsubscribe function. Mirrors the
442
+ * `reactor.on("runtimeMessage", …)` pattern.
443
+ */
444
+ onRuntimeMessage: (handler: (message: unknown) => void) => () => void;
445
+ /**
446
+ * Subscribe to status changes (so the client can reject pending
447
+ * requests on disconnect). Returns an unsubscribe function.
448
+ */
449
+ onStatusChanged: (handler: (status: ReactorStatus) => void) => () => void;
450
+ /**
451
+ * Send a runtime-scoped command on the data channel. The
452
+ * `RecordingClient` uses this to fire `requestClip` /
453
+ * `requestRecording`.
454
+ */
455
+ sendRuntimeCommand: (command: string, data: Record<string, unknown>) => Promise<void>;
456
+ /** Current connection status — guards `requestClip` before it goes on the wire. */
457
+ getStatus: () => ReactorStatus;
458
+ /**
459
+ * Coordinator base URL used to resolve `clip.playlistUrl` against.
460
+ *
461
+ * The runtime now emits a path-only ``playlist_url`` (e.g.
462
+ * ``/clips?session_id=…``) so the SDK is the absolute-origin owner
463
+ * for both local-dev (HttpRuntime on the SDK's ``apiUrl``) and
464
+ * production (Coordinator on the SDK's ``apiUrl``). We always
465
+ * resolve against the ``Reactor``'s coordinator URL — there is no
466
+ * remote-vs-local divergence on the read path.
467
+ *
468
+ * For backwards-compat with older runtimes that emitted absolute
469
+ * URLs (scheme + host bound to the runtime's own listener,
470
+ * e.g. ``http://0.0.0.0:8080/clips?…``), the same URL is also used
471
+ * to rewrite the host onto the coordinator — see
472
+ * ``rewriteUrlHost`` in ``utils/recording.ts``.
473
+ */
474
+ getCoordinatorBaseUrl: () => string | undefined;
475
+ }
476
+ declare class RecordingClient {
477
+ private readonly host;
478
+ private pendingClipRequests;
479
+ /** Timeout applied per request; configurable for tests. */
480
+ private readonly requestTimeoutMs;
481
+ /** Cleanup handles for the host event subscriptions. */
482
+ private readonly unsubscribers;
483
+ constructor(host: RecordingClientHost, options?: {
484
+ requestTimeoutMs?: number;
485
+ });
486
+ /**
487
+ * Request a clip covering the last `durationSeconds` of the live
488
+ * session. See {@link Reactor.requestClip}.
489
+ */
490
+ requestClip(durationSeconds: number): Promise<Clip>;
491
+ /**
492
+ * Request a clip covering the entire session up to "now". See
493
+ * {@link Reactor.requestRecording}.
494
+ */
495
+ requestRecording(): Promise<Clip>;
496
+ /**
497
+ * Poll `/clips` and return the raw manifest body. Same polling
498
+ * semantics as the bare {@link fetchPlaylist} helper; the caller is
499
+ * responsible for supplying the Coordinator JWT via `options.jwt`
500
+ * (origin-scoped to `clip.playlistUrl`). In local mode against the
501
+ * HttpRuntime, `options.jwt` should be omitted.
502
+ */
503
+ fetchPlaylist(clip: Clip, options?: FetchPlaylistOptions): Promise<string>;
504
+ /**
505
+ * Fetch the manifest and return a `blob:` URL suitable for
506
+ * `<video src>` / `hls.js`. The player reads the manifest from
507
+ * browser memory; chunk URLs inside are presigned S3 GETs.
508
+ *
509
+ * Caller owns the returned URL — revoke it via `URL.revokeObjectURL`
510
+ * when playback tears down. Pass `options.jwt` for production
511
+ * `/clips` (the Coordinator hop) — see {@link FetchPlaylistOptions}.
512
+ */
513
+ getPlayableManifestUrl(clip: Clip, options?: FetchPlaylistOptions): Promise<string>;
514
+ /**
515
+ * Thin delegation to {@link downloadClipAsFile}. Caller must pass
516
+ * `options.jwt` in production — see {@link DownloadClipOptions}.
517
+ */
518
+ downloadClipAsFile(clip: Clip, filename?: string | null, options?: DownloadClipOptions): Promise<Blob>;
519
+ /**
520
+ * Drop every pending request and unsubscribe from host events.
521
+ * Safe to call multiple times; further `requestClip` /
522
+ * `requestRecording` calls after `destroy()` will hang waiting for
523
+ * a response that will never arrive — host should not call into
524
+ * the client after destroy.
525
+ */
526
+ destroy(): void;
527
+ /**
528
+ * Register a pending FIFO entry, send the runtime message via
529
+ * the host, and resolve when the next `clipReady` / `clipFailed`
530
+ * arrives.
531
+ */
532
+ private dispatchClipRequest;
533
+ /**
534
+ * Match inbound `clipReady` / `clipFailed` to the next pending
535
+ * request FIFO; ignore every other runtime message type.
536
+ */
537
+ private onRuntimeMessage;
538
+ private onStatusChanged;
539
+ /** Reject every in-flight request with a typed disconnect error. */
540
+ private rejectPending;
541
+ }
542
+
181
543
  declare const DEFAULT_BASE_URL = "https://api.reactor.inc";
182
544
  declare const OptionsSchema: z.ZodObject<{
183
545
  apiUrl: z.ZodDefault<z.ZodString>;
@@ -214,6 +576,8 @@ declare class Reactor {
214
576
  private tracks;
215
577
  private presetTracks?;
216
578
  private sessionResponse?;
579
+ /** Per-Reactor recording client. See {@link RecordingClient}. */
580
+ readonly recording: RecordingClient;
217
581
  constructor(options: Options);
218
582
  private eventListeners;
219
583
  on(event: ReactorEvent, handler: EventHandler): void;
@@ -244,6 +608,29 @@ declare class Reactor {
244
608
  uploadFile(file: File | Blob, options?: {
245
609
  name?: string;
246
610
  }): Promise<FileRef>;
611
+ /**
612
+ * Request a clip covering the last `durationSeconds` of the live
613
+ * session. Capped server-side at `recording.clip_max_seconds`
614
+ * (default 5 minutes). Resolves with a {@link Clip} whose
615
+ * `playlistUrl` can be handed to any HLS-capable player.
616
+ *
617
+ * @throws {RecordingError} on invalid input, transport failure,
618
+ * timeout, runtime-side `clipFailed`, or disconnect mid-request.
619
+ */
620
+ requestClip(durationSeconds: number): Promise<Clip>;
621
+ /**
622
+ * Request a clip covering the entire session up to "now". Same
623
+ * mechanics as {@link requestClip} with `start = 0`; only the
624
+ * resolved {@link Clip.kind} discriminator differs.
625
+ */
626
+ requestRecording(): Promise<Clip>;
627
+ /**
628
+ * Stream the chunks referenced by `clip.playlistUrl` and trigger a
629
+ * native browser download of the assembled fragmented-MP4 Blob.
630
+ * Pass `filename: null` to skip the download trigger and receive
631
+ * the Blob (useful for non-DOM consumers and tests).
632
+ */
633
+ downloadClipAsFile(clip: Clip, filename?: string | null, options?: DownloadClipOptions): Promise<Blob>;
247
634
  /**
248
635
  * Publishes a MediaStreamTrack to a named sendonly track.
249
636
  * The transceiver is already set up from capabilities — this just
@@ -380,6 +767,247 @@ interface WebcamStreamProps {
380
767
  }
381
768
  declare function WebcamStream({ track, className, style, videoConstraints, showWebcam, videoObjectFit, }: WebcamStreamProps): react_jsx_runtime.JSX.Element;
382
769
 
770
+ /**
771
+ * Video preview for a captured {@link Clip}.
772
+ *
773
+ * Renders an HLS manifest through the browser's native
774
+ * ``<video controls>`` element. On Safari / iOS the manifest is
775
+ * attached directly (native HLS support). On Chrome / Firefox / Edge
776
+ * ``hls.js`` is dynamically imported — declared as an **optional peer
777
+ * dependency** so consumers who don't use this component aren't billed
778
+ * the ~80 KB. If ``hls.js`` isn't installed and native HLS isn't
779
+ * available the player surfaces an inline error overlay; the
780
+ * underlying chunks remain downloadable via {@link useClipDownload} /
781
+ * {@link ClipDownloadButton} (which don't depend on hls.js at all).
782
+ *
783
+ * **Preview only.** This component intentionally does *not* render a
784
+ * download UI. Compose it with {@link ClipDownloadButton} or build
785
+ * your own download surface around {@link useClipDownload} — the
786
+ * separation keeps both pieces independently extendible and avoids
787
+ * baking layout decisions into the SDK.
788
+ *
789
+ * Unlike {@link ReactorView} / {@link WebcamStream} this component
790
+ * **does not require a ``ReactorProvider``** in the tree. It
791
+ * operates on the ``Clip`` value alone, so it stays usable after
792
+ * ``reactor.disconnect()`` and works with clips loaded from
793
+ * fixtures, server logs, or any other source.
794
+ *
795
+ * @example Compose with the download button:
796
+ * ```tsx
797
+ * <div>
798
+ * <ClipPlayer clip={clip} getJwt={() => jwt} />
799
+ * <ClipDownloadButton clip={clip} getJwt={() => jwt} />
800
+ * </div>
801
+ * ```
802
+ *
803
+ * @example Local dev (HttpRuntime, no auth on /clips):
804
+ * ```tsx
805
+ * <ClipPlayer clip={clip} />
806
+ * ```
807
+ */
808
+ interface ClipPlayerProps {
809
+ /**
810
+ * The captured clip to play. When this prop changes by reference
811
+ * the player re-fetches the manifest and re-attaches the player.
812
+ */
813
+ clip: Clip;
814
+ /**
815
+ * Lazy resolver for the Coordinator JWT used on the ``/clips``
816
+ * manifest GET.
817
+ *
818
+ * - **Production / Coordinator:** required. Should return the
819
+ * same JWT your app already passes to ``ReactorProvider`` /
820
+ * ``reactor.connect()``. Called at request time (not at render
821
+ * time) so token refreshes are picked up automatically.
822
+ * - **Local-dev / HttpRuntime:** omit — the local ``/clips``
823
+ * endpoint serves manifests without auth.
824
+ *
825
+ * The chunks referenced *inside* the manifest are S3 presigned
826
+ * GETs (prod) or unauthenticated runtime URLs (local), and are
827
+ * fetched without an ``Authorization`` header in either case.
828
+ */
829
+ getJwt?: () => string | Promise<string>;
830
+ /**
831
+ * Override the grace period beyond ``clip.predictedReadyAtMs``
832
+ * before the SDK gives up polling the ``/clips`` manifest endpoint
833
+ * with ``CLIP_NOT_READY``. Defaults to
834
+ * {@link DEFAULT_PLAYLIST_POLL_SLACK_MS} (15 s) — enough for snap
835
+ * clips, but long-running session recordings may legitimately need
836
+ * a minute or more for the final boundary chunk to finish encoding
837
+ * + uploading, in which case pass a larger value (e.g. ``120_000``
838
+ * for two-minute grace). Forwarded directly to
839
+ * {@link fetchPlaylist}'s ``slackMs`` option — see that helper for
840
+ * the polling semantics.
841
+ */
842
+ slackMs?: number;
843
+ /** Play automatically once the manifest is attached. Default ``true``. */
844
+ autoPlay?: boolean;
845
+ /**
846
+ * Start muted. Default ``true`` because browser autoplay policies
847
+ * block audio-bearing video from playing without a user gesture;
848
+ * the user can unmute via the native ``<video controls>``.
849
+ */
850
+ muted?: boolean;
851
+ className?: string;
852
+ style?: React.CSSProperties;
853
+ }
854
+ declare function ClipPlayer({ clip, getJwt, slackMs, autoPlay, muted, className, style, }: ClipPlayerProps): react_jsx_runtime.JSX.Element;
855
+
856
+ /**
857
+ * State machine for an in-progress clip download.
858
+ *
859
+ * - ``idle``: no download in flight (initial state, and what the hook
860
+ * returns to after a successful save).
861
+ * - ``downloading``: chunks are being fetched. ``fetched`` and
862
+ * ``total`` count the number of chunks (init segment + media
863
+ * segments) — useful for a progress bar. ``total`` is 0 until the
864
+ * manifest is parsed and the chunk count is known.
865
+ * - ``error``: most recent attempt failed; the ``message`` is suitable
866
+ * for surfacing inline. ``RecordingError`` instances are formatted
867
+ * as ``"<CODE>: <reason>"`` for grep-ability.
868
+ */
869
+ type ClipDownloadState = {
870
+ kind: "idle";
871
+ } | {
872
+ kind: "downloading";
873
+ fetched: number;
874
+ total: number;
875
+ } | {
876
+ kind: "error";
877
+ message: string;
878
+ };
879
+ interface UseClipDownloadOptions {
880
+ /**
881
+ * Filename used when the browser save dialog opens. Pass ``null``
882
+ * to skip the ``<a download>`` trigger entirely — the returned
883
+ * Blob is still resolved so the caller can ``URL.createObjectURL``
884
+ * it or re-upload it. Default ``"reactor-clip.mp4"``.
885
+ */
886
+ filename?: string | null;
887
+ /**
888
+ * Lazy resolver for the Coordinator JWT used on the ``/clips``
889
+ * manifest GET. Called on every {@link download} invocation, so
890
+ * token refreshes are picked up automatically. Omit in local-dev
891
+ * mode (HttpRuntime has no auth on ``/clips``). See
892
+ * {@link ClipPlayerProps.getJwt} for the production / local
893
+ * distinction.
894
+ */
895
+ getJwt?: () => string | Promise<string>;
896
+ }
897
+ interface UseClipDownloadResult {
898
+ /** Current state of the most recent download attempt. */
899
+ state: ClipDownloadState;
900
+ /**
901
+ * Trigger a download. Resolves with the assembled fragmented-MP4
902
+ * Blob, or ``undefined`` if a download was already in flight (the
903
+ * call is a no-op in that case — guarding against double-click is
904
+ * the hook's responsibility, not the caller's).
905
+ *
906
+ * Errors are caught and surfaced via {@link state} — the returned
907
+ * Promise still resolves to ``undefined`` rather than rejecting,
908
+ * because the typical caller is a click handler that doesn't await.
909
+ * Use ``state.kind === "error"`` to drive failure UI.
910
+ */
911
+ download: () => Promise<Blob | undefined>;
912
+ /** Reset to ``idle``. Does *not* cancel an in-flight download. */
913
+ reset: () => void;
914
+ }
915
+ /**
916
+ * Headless download primitive for a {@link Clip}.
917
+ *
918
+ * Wraps {@link downloadClipAsFile} in a React state machine so the
919
+ * consumer can render any button they want, anywhere they want, and
920
+ * still get progress + error feedback. Used internally by
921
+ * {@link ClipPlayer}'s built-in download button — when you need
922
+ * custom placement or styling, set ``showDownloadButton={false}`` on
923
+ * the player and call this hook directly.
924
+ *
925
+ * Stable callback identity: ``download`` and ``reset`` are the same
926
+ * function reference across renders, so they're safe to pass through
927
+ * memoized children without forcing re-renders.
928
+ *
929
+ * @example Render a download button anywhere in your tree:
930
+ * ```tsx
931
+ * function ClipCard({ clip }: { clip: Clip }) {
932
+ * const jwt = useReactor((s) => s.jwtToken);
933
+ * const { state, download } = useClipDownload(clip, {
934
+ * filename: `snap-${clip.sessionId}.mp4`,
935
+ * getJwt: jwt ? () => jwt : undefined,
936
+ * });
937
+ * return (
938
+ * <button onClick={download} disabled={state.kind === "downloading"}>
939
+ * {state.kind === "downloading"
940
+ * ? `${state.fetched}/${state.total}`
941
+ * : state.kind === "error"
942
+ * ? "Retry"
943
+ * : "Download"}
944
+ * </button>
945
+ * );
946
+ * }
947
+ * ```
948
+ */
949
+ declare function useClipDownload(clip: Clip, options?: UseClipDownloadOptions): UseClipDownloadResult;
950
+
951
+ /**
952
+ * Standalone download button for a captured {@link Clip}.
953
+ *
954
+ * Drops anywhere in your UI — modal headers, list rows, hover menus,
955
+ * floating action buttons — and is responsible for nothing more than
956
+ * triggering a download and reflecting its state. Internally wraps
957
+ * {@link useClipDownload}; for completely custom UIs (progress bars,
958
+ * menu items, post-download blob handling) call that hook directly.
959
+ *
960
+ * Styling is intentionally minimal. Override via ``className``,
961
+ * ``style``, or replace the inner content with the ``children``
962
+ * render-prop. No CSS file is shipped — every default style is
963
+ * inline so it loses to anything the consumer provides.
964
+ *
965
+ * @example Default label, state-aware:
966
+ * ```tsx
967
+ * <ClipDownloadButton clip={clip} getJwt={() => jwt} />
968
+ * ```
969
+ *
970
+ * @example Custom label that follows the state:
971
+ * ```tsx
972
+ * <ClipDownloadButton clip={clip} getJwt={() => jwt}>
973
+ * {(s) => (s.kind === "downloading" ? `${s.fetched}/${s.total}` : "Save MP4")}
974
+ * </ClipDownloadButton>
975
+ * ```
976
+ *
977
+ * @example Static label:
978
+ * ```tsx
979
+ * <ClipDownloadButton clip={clip} getJwt={() => jwt}>Save</ClipDownloadButton>
980
+ * ```
981
+ */
982
+ interface ClipDownloadButtonProps {
983
+ /** The clip to download. */
984
+ clip: Clip;
985
+ /**
986
+ * Lazy JWT resolver. See {@link ClipPlayerProps.getJwt} for the
987
+ * production / local-dev distinction. Omit in local-dev mode.
988
+ */
989
+ getJwt?: () => string | Promise<string>;
990
+ /** Filename for the saved MP4. Default ``"reactor-clip.mp4"``. */
991
+ filename?: string;
992
+ /**
993
+ * Inner content of the button. Three forms:
994
+ *
995
+ * - **Omitted** — renders a sensible default label that follows
996
+ * the state (``"Download"`` / ``"Downloading 3/8…"`` / etc.).
997
+ * - **`ReactNode`** — static label. No state-driven text.
998
+ * - **`(state) => ReactNode`** — state-aware render function;
999
+ * use for custom progress strings, spinners, etc.
1000
+ */
1001
+ children?: React.ReactNode | ((state: ClipDownloadState) => React.ReactNode);
1002
+ /** Forwarded to the underlying ``<button>``. */
1003
+ className?: string;
1004
+ /** Forwarded to the underlying ``<button>`` — merges *after* the defaults so each property overrides. */
1005
+ style?: React.CSSProperties;
1006
+ /** Forwarded to the underlying ``<button>``. ORed with the internal "downloading" state. */
1007
+ disabled?: boolean;
1008
+ }
1009
+ declare function ClipDownloadButton({ clip, getJwt, filename, children, className, style, disabled, }: ClipDownloadButtonProps): react_jsx_runtime.JSX.Element;
1010
+
383
1011
  /**
384
1012
  * Generic hook for accessing selected parts of the Reactor store.
385
1013
  *
@@ -413,4 +1041,4 @@ declare function useReactorInternalMessage(handler: (message: any) => void): voi
413
1041
  */
414
1042
  declare function useStats(): ConnectionStats | undefined;
415
1043
 
416
- export { AbortError, type Capabilities, type CommandCapability, ConflictError, type ConnectOptions, type ConnectionStats, type ConnectionTimings, DEFAULT_BASE_URL, FileRef, type MessageScope, type Options, Reactor, type ReactorConnectOptions, ReactorController, type ReactorControllerProps, type ReactorError, type ReactorEvent, ReactorProvider, type ReactorState$1 as ReactorState, type ReactorStatus, type ReactorStore, ReactorView, type ReactorViewProps, type SessionResponse, type TrackCapability, WebcamStream, type WebcamStreamProps, isAbortError, useReactor, useReactorInternalMessage, useReactorMessage, useReactorStore, useStats };
1044
+ 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 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, parsePlaylist, rewriteUrlHost, useClipDownload, useReactor, useReactorInternalMessage, useReactorMessage, useReactorStore, useStats };