@reactor-team/js-sdk 2.12.4 → 3.0.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.mts DELETED
@@ -1,1360 +0,0 @@
1
- import { z } from 'zod';
2
- import * as react_jsx_runtime from 'react/jsx-runtime';
3
- import React, { ReactNode } from 'react';
4
-
5
- /**
6
- * Internal types for the Reactor SDK.
7
- *
8
- * All Zod schemas and derived TypeScript types live here.
9
- * Version constants are sourced from package.json via resolveJsonModule.
10
- */
11
-
12
- declare const TrackCapabilitySchema: z.ZodObject<{
13
- name: z.ZodString;
14
- kind: z.ZodEnum<{
15
- video: "video";
16
- audio: "audio";
17
- }>;
18
- direction: z.ZodEnum<{
19
- recvonly: "recvonly";
20
- sendonly: "sendonly";
21
- }>;
22
- }, z.core.$strip>;
23
- declare const CommandCapabilitySchema: z.ZodObject<{
24
- name: z.ZodString;
25
- description: z.ZodString;
26
- schema: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
27
- }, z.core.$strip>;
28
- declare const CapabilitiesSchema: z.ZodObject<{
29
- protocol_version: z.ZodString;
30
- tracks: z.ZodArray<z.ZodObject<{
31
- name: z.ZodString;
32
- kind: z.ZodEnum<{
33
- video: "video";
34
- audio: "audio";
35
- }>;
36
- direction: z.ZodEnum<{
37
- recvonly: "recvonly";
38
- sendonly: "sendonly";
39
- }>;
40
- }, z.core.$strip>>;
41
- commands: z.ZodOptional<z.ZodArray<z.ZodObject<{
42
- name: z.ZodString;
43
- description: z.ZodString;
44
- schema: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
45
- }, z.core.$strip>>>;
46
- emission_fps: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
47
- }, z.core.$strip>;
48
- declare const SessionResponseSchema: z.ZodObject<{
49
- session_id: z.ZodString;
50
- state: z.ZodString;
51
- cluster: z.ZodString;
52
- model: z.ZodObject<{
53
- name: z.ZodString;
54
- version: z.ZodOptional<z.ZodString>;
55
- }, z.core.$strip>;
56
- server_info: z.ZodObject<{
57
- server_version: z.ZodString;
58
- }, z.core.$strip>;
59
- selected_transport: z.ZodOptional<z.ZodObject<{
60
- protocol: z.ZodString;
61
- version: z.ZodString;
62
- }, z.core.$strip>>;
63
- capabilities: z.ZodOptional<z.ZodObject<{
64
- protocol_version: z.ZodString;
65
- tracks: z.ZodArray<z.ZodObject<{
66
- name: z.ZodString;
67
- kind: z.ZodEnum<{
68
- video: "video";
69
- audio: "audio";
70
- }>;
71
- direction: z.ZodEnum<{
72
- recvonly: "recvonly";
73
- sendonly: "sendonly";
74
- }>;
75
- }, z.core.$strip>>;
76
- commands: z.ZodOptional<z.ZodArray<z.ZodObject<{
77
- name: z.ZodString;
78
- description: z.ZodString;
79
- schema: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
80
- }, z.core.$strip>>>;
81
- emission_fps: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
82
- }, z.core.$strip>>;
83
- }, z.core.$strip>;
84
- type TrackCapability = z.infer<typeof TrackCapabilitySchema>;
85
- type CommandCapability = z.infer<typeof CommandCapabilitySchema>;
86
- type SessionResponse = z.infer<typeof SessionResponseSchema>;
87
- type Capabilities = z.infer<typeof CapabilitiesSchema>;
88
- /** One OpenAPI operation (the `post` of an event/webhook path item). */
89
- interface ModelSchemaOperation {
90
- operationId?: string;
91
- summary?: string;
92
- description?: string;
93
- requestBody?: {
94
- required?: boolean;
95
- content?: Record<string, {
96
- schema?: Record<string, unknown>;
97
- }>;
98
- };
99
- responses?: Record<string, unknown>;
100
- [key: string]: unknown;
101
- }
102
- /** An OpenAPI path item; the runtime only populates `post`. */
103
- interface ModelSchemaPathItem {
104
- post?: ModelSchemaOperation;
105
- [key: string]: unknown;
106
- }
107
- /**
108
- * The model's OpenAPI 3.1 schema, returned by the runtime in response to a
109
- * `requestSchema` runtime-channel command. This is a pass-through of the
110
- * runtime's document, not a shape the SDK reshapes: client-triggerable
111
- * events live under `paths` as `POST /events/<name>` operations, outbound
112
- * model messages under `webhooks`, and media tracks under `x-reactor.tracks`.
113
- * Read the parts you need.
114
- */
115
- interface ModelSchema {
116
- openapi: string;
117
- info: {
118
- title: string;
119
- version: string;
120
- description?: string;
121
- };
122
- paths?: Record<string, ModelSchemaPathItem>;
123
- webhooks?: Record<string, ModelSchemaPathItem>;
124
- "x-reactor"?: {
125
- tracks?: Array<{
126
- name: string;
127
- kind: string;
128
- direction: string;
129
- }>;
130
- };
131
- components?: Record<string, unknown>;
132
- [key: string]: unknown;
133
- }
134
-
135
- /**
136
- * Reference to an uploaded file, returned by {@link Reactor.uploadFile}.
137
- *
138
- * Pass a `FileRef` as a value in {@link Reactor.sendCommand} and it will
139
- * be serialized into the `uploads` section of the wire envelope, separate
140
- * from scalar arguments. The runtime resolves each reference to bytes
141
- * before dispatching the event to the model handler.
142
- */
143
- declare class FileRef {
144
- readonly uploadId: string;
145
- readonly name: string;
146
- readonly mimeType: string;
147
- readonly size: number;
148
- constructor(uploadId: string, name: string, mimeType: string, size: number);
149
- }
150
-
151
- type ReactorStatus = "disconnected" | "connecting" | "waiting" | "ready";
152
- /**
153
- * The message scope identifies the envelope layer a data channel message belongs to.
154
- * - "application": model-defined commands (client->runtime) and model-emitted payloads (runtime->client).
155
- * - "runtime": platform-level control messages (e.g., capabilities exchange).
156
- */
157
- type MessageScope = "application" | "runtime";
158
-
159
- interface ReactorError {
160
- code: string;
161
- message: string;
162
- timestamp: number;
163
- recoverable: boolean;
164
- component: "api" | "gpu";
165
- retryAfter?: number;
166
- }
167
- declare class ConflictError extends Error {
168
- constructor(message: string);
169
- }
170
- declare class AbortError extends Error {
171
- constructor(message: string);
172
- }
173
- /** Matches both our custom AbortError and the native DOMException thrown by fetch(). */
174
- declare function isAbortError(error: unknown): boolean;
175
- declare class SessionLostError extends Error {
176
- constructor(message: string);
177
- }
178
- declare function isSessionLostError(error: unknown): boolean;
179
- interface ReactorState$1 {
180
- status: ReactorStatus;
181
- lastError?: ReactorError;
182
- }
183
- /**
184
- * Options for configuring the connect polling behavior.
185
- */
186
- interface ConnectOptions {
187
- /** Maximum number of SDP polling attempts before giving up. Default: 6. */
188
- maxAttempts?: number;
189
- /**
190
- * When true (default), sends `resume_track` for every recvonly track
191
- * immediately after the connection is established, causing the backend to
192
- * begin streaming those tracks — this preserves the pre-multi-connection
193
- * behaviour where output tracks flow automatically on connect. Set to false
194
- * to keep recvonly tracks paused on connect and resume them individually via
195
- * `resumeTrack()` (e.g. multi-connection apps that only subscribe to a
196
- * subset of peers).
197
- *
198
- * A track that arrives after that is resumed on its own, so one track
199
- * appearing never disturbs another the caller has paused.
200
- */
201
- autoResumeTracks?: boolean;
202
- /**
203
- * Attach to a session that already exists (e.g. one created by a backend)
204
- * instead of creating a new one. When set, `connect()` skips `POST /sessions`
205
- * and brings up the transport directly against this id. The JWT passed to
206
- * `connect()` must be valid for the account that owns the session.
207
- */
208
- sessionId?: string;
209
- /**
210
- * Use a specific WebRTC connection id instead of minting one. When omitted
211
- * (default), the transport registers a fresh connection (`POST .../connections`)
212
- * and the server mints the id. When set, the transport skips registration and
213
- * sends its SDP offer directly to that connection — so the id must already have
214
- * been registered under this session (e.g. a backend called `POST .../connections`
215
- * and handed the id to this client) and must still be open.
216
- *
217
- * `connect()` rejects if the id is invalid (out of the server's accepted range)
218
- * or if no open connection with that id exists for the session.
219
- */
220
- connectionId?: number;
221
- }
222
- /**
223
- * Transport-agnostic timing breakdown of the connect() handshake, recorded
224
- * once per connection and included in every subsequent {@link ConnectionStats}
225
- * update. All durations are in milliseconds (from `performance.now()`).
226
- *
227
- * For transport-specific timings (e.g. ICE negotiation, data channel open),
228
- * see the relevant transport stats type (e.g. {@link WebRTCTransportTimings}).
229
- */
230
- interface ConnectionTimings {
231
- /** POST /sessions round-trip time */
232
- sessionCreationMs: number;
233
- /** Total time spent in transport.connect() (signaling, negotiation, etc.) */
234
- transportConnectingMs: number;
235
- /** End-to-end: connect() invocation → status "ready" */
236
- totalMs: number;
237
- }
238
- interface ConnectionStats {
239
- /** ICE candidate-pair round-trip time in milliseconds */
240
- rtt?: number;
241
- /** ICE candidate type: "host", "srflx", "prflx", or "relay" (TURN) */
242
- candidateType?: string;
243
- /** Estimated available incoming bitrate in bits/second */
244
- availableIncomingBitrate?: number;
245
- /** Estimated available outgoing bitrate in bits/second */
246
- availableOutgoingBitrate?: number;
247
- /** Real-time Incoming bitrate in bits/second */
248
- incomingBitrate?: number;
249
- /** Real-time Outgoing bitrate in bits/second */
250
- outgoingBitrate?: number;
251
- /** Received video frames per second */
252
- framesPerSecond?: number;
253
- /** Ratio of packets lost (0-1) */
254
- packetLossRatio?: number;
255
- /** Network jitter in seconds (from inbound-rtp) */
256
- jitter?: number;
257
- /** Timing breakdown of the initial connection handshake (set once, persisted until disconnect) */
258
- connectionTimings?: ConnectionTimings;
259
- timestamp: number;
260
- }
261
- type ReactorEvent = "statusChanged" | "sessionIdChanged" | "message" | "runtimeMessage" | "trackReceived" | "error" | "sessionExpirationChanged" | "schemaReceived" | "statsUpdate";
262
- /**
263
- * Severity tier of a content moderation event delivered as the inner
264
- * payload of a `runtimeMessage` with `type === "moderation"`.
265
- *
266
- * - `"warn"`: the input scored above the warn threshold but below the
267
- * terminate threshold. The session continues; this is informational
268
- * only.
269
- * - `"terminate"`: the input crossed the terminate threshold. The
270
- * session will be ended shortly after this message is dispatched.
271
- */
272
- type ModerationAction = "warn" | "terminate";
273
- /**
274
- * Inner payload of a `runtimeMessage` with `type === "moderation"`.
275
- *
276
- * Surfaces a content-moderation outcome to the client app. Fires on
277
- * any moderatable input (free-text fields, file uploads) that the
278
- * configured moderation policy flags. Apps receive it by subscribing
279
- * to the existing `runtimeMessage` event and filtering on `type`:
280
- *
281
- * reactor.on("runtimeMessage", (m) => {
282
- * if (m?.type === "moderation") {
283
- * const payload = m.data as ModerationEvent;
284
- * // ...render banner, log, etc.
285
- * }
286
- * });
287
- */
288
- interface ModerationEvent {
289
- /** Severity tier — `"warn"` continues the session, `"terminate"` ends it. */
290
- action: ModerationAction;
291
- /**
292
- * Modality of the flagged input. `"text"` for string fields,
293
- * `"image"` for `UploadedFile` payloads with an image MIME type.
294
- */
295
- input_kind: "text" | "image";
296
- /**
297
- * Name of the inbound command/event whose payload was flagged
298
- * (e.g. `"set_prompt"`, `"set_image"`, `"fileUploaded"`).
299
- */
300
- command: string;
301
- /** Category labels that flagged (e.g. `["sexual"]`, `["violence/graphic"]`). */
302
- categories: string[];
303
- /** Short human-readable summary suitable for UI rendering. */
304
- message: string;
305
- }
306
-
307
- /**
308
- * Lazy resolver for the Coordinator bearer token. The SDK calls this
309
- * immediately before each authenticated HTTP request, so short-lived
310
- * tokens (Clerk session JWTs, etc.) are refreshed transparently.
311
- * Returning `""` suppresses the `Authorization` header entirely.
312
- */
313
- type JwtResolver = () => string | Promise<string>;
314
- /** Static token, or a {@link JwtResolver} invoked per request. */
315
- type JwtSource = string | JwtResolver;
316
- /** Wrap a {@link JwtSource} into a {@link JwtResolver}. */
317
- declare function normalizeJwtSource(source: JwtSource): JwtResolver;
318
-
319
- /**
320
- * Stateless primitives for the Reactor recording feature.
321
- *
322
- * This module owns:
323
- * - Public-facing {@link Clip} type, {@link RecordingError} class, and
324
- * the `RuntimeRecordingMessageType` enum.
325
- * - Wire schemas (`ClipReadyPayloadSchema`, `ClipFailedPayloadSchema`)
326
- * plus `clipFromPayload` to convert snake_case wire payloads into
327
- * camelCase `Clip` objects.
328
- * - HTTP helpers `fetchPlaylist` (deadline-driven polling) and
329
- * `parsePlaylist` (HLS `.m3u8` parser).
330
- * - The `downloadClipAsFile` helper that streams the referenced
331
- * fMP4 chunks, remuxes them into a flat social-media-ready MP4
332
- * via `mp4box` (PTS=0, faststart, `major_brand=isom`), and
333
- * returns a Blob for browser download.
334
- *
335
- * Stateful pieces (FIFO promise correlator, in-flight request
336
- * lifecycle, integration with Reactor's event bus) live in the
337
- * `RecordingClient` class in `core/RecordingClient.ts`.
338
- *
339
- * Wire contract is documented end-to-end in the *Video Recording
340
- * Feature* Notion page; the runtime side ships in
341
- * `reactor_runtime/recording/`.
342
- */
343
-
344
- /**
345
- * Names of the runtime-scoped messages used by the recording feature.
346
- * Outbound names are sent via `Reactor.sendCommand(name, …, "runtime")`;
347
- * inbound names appear as `message.type` on `runtimeMessage` events.
348
- */
349
- declare const RuntimeRecordingMessageType: {
350
- readonly REQUEST_CLIP: "requestClip";
351
- readonly REQUEST_RECORDING: "requestRecording";
352
- readonly CLIP_READY: "clipReady";
353
- readonly CLIP_FAILED: "clipFailed";
354
- };
355
- /** Discriminator on a {@link Clip}. `"snap"` from `requestClip`, `"recording"` from `requestRecording`. */
356
- type ClipKind = "snap" | "recording";
357
- /**
358
- * Resolved outcome of a {@link Reactor.requestClip} / {@link Reactor.requestRecording} call.
359
- *
360
- * The runtime returns immediately on every request — it does *not*
361
- * block until the in-progress chunk has been finalised. The response
362
- * is a *promise*: `endMarker` reflects wall-clock at request time
363
- * and may point inside a chunk ffmpeg is still writing. The
364
- * `/clips` manifest endpoint returns `202 Retry-After` while that
365
- * chunk is in flight; the SDK polls until `200`.
366
- *
367
- * - `startMarker` / `endMarker` / `nowMarker` are session-relative
368
- * seconds since recorder start.
369
- * - `predictedReadyAtMs` is a **Unix epoch in milliseconds** — the
370
- * runtime's estimate of when the boundary chunk will be servable
371
- * by `/clips`. Compare against `Date.now()` to drive a "ready in
372
- * Ns" indicator. It is only an estimate: the SDK polls `/clips`
373
- * until the manifest is actually ready and does not give up when
374
- * this epoch passes (see {@link fetchPlaylist} for the polling and
375
- * cancellation model).
376
- * - `playlistUrl` is short-lived in production (the embedded chunk
377
- * URLs are presigned for a few minutes). Re-issuing the request
378
- * produces a fresh URL with fresh presigning.
379
- */
380
- interface Clip {
381
- sessionId: string;
382
- kind: ClipKind;
383
- startMarker: number;
384
- endMarker: number;
385
- nowMarker: number;
386
- predictedReadyAtMs: number;
387
- playlistUrl: string;
388
- }
389
- /**
390
- * Error thrown when a recording request cannot be served.
391
- *
392
- * `code` is a stable, machine-readable identifier; `reason` is the
393
- * raw string the runtime / manifest endpoint returned (passed through
394
- * verbatim from `clipFailed.reason`, the `/clips` HTTP body, or the
395
- * SDK's pre-flight check).
396
- */
397
- declare class RecordingError extends Error {
398
- 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";
399
- readonly reason: string;
400
- 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);
401
- }
402
- /** `clipReady.data` payload as serialised by `ClipResult.to_dict()`. */
403
- declare const ClipReadyPayloadSchema: z.ZodObject<{
404
- session_id: z.ZodString;
405
- kind: z.ZodEnum<{
406
- snap: "snap";
407
- recording: "recording";
408
- }>;
409
- start_marker: z.ZodNumber;
410
- end_marker: z.ZodNumber;
411
- now_marker: z.ZodNumber;
412
- predicted_ready_at_ms: z.ZodNumber;
413
- playlist_url: z.ZodString;
414
- }, z.core.$loose>;
415
- type ClipReadyPayload = z.infer<typeof ClipReadyPayloadSchema>;
416
- /** `clipFailed.data` payload — short reason string from the runtime. */
417
- declare const ClipFailedPayloadSchema: z.ZodObject<{
418
- reason: z.ZodDefault<z.ZodString>;
419
- }, z.core.$loose>;
420
- type ClipFailedPayload = z.infer<typeof ClipFailedPayloadSchema>;
421
- /** Options for {@link clipFromPayload}. */
422
- interface ParseClipOptions {
423
- /**
424
- * Coordinator base URL. When set, resolves `payload.playlist_url`
425
- * against this base — used to convert the runtime's path-only
426
- * playlist URL (``/clips?session_id=…``) into an absolute URL the
427
- * browser/SDK can fetch. Also handles the legacy case where an
428
- * older runtime emits an absolute URL bound to its own
429
- * ``0.0.0.0`` listener: the host/port are rewritten onto the
430
- * coordinator.
431
- */
432
- coordinatorBaseUrl?: string;
433
- }
434
- /**
435
- * Convert a validated {@link ClipReadyPayload} into the public {@link Clip}.
436
- * Pure: no IO, no side effects.
437
- */
438
- declare function clipFromPayload(payload: ClipReadyPayload, options?: ParseClipOptions): Clip;
439
- /**
440
- * Resolve `target` against `base`, returning an absolute URL.
441
- *
442
- * Two cases:
443
- *
444
- * * **Path-only / relative target** (no scheme — e.g. the
445
- * runtime's current ``/clips?session_id=…`` shape): joined
446
- * against ``base`` via ``new URL(target, base)``, preserving
447
- * path, query, and fragment.
448
- * * **Absolute target** (``http://…`` / ``https://…``, e.g. a legacy
449
- * runtime emitting a URL bound to its own ``0.0.0.0`` listener):
450
- * scheme, hostname, and port are replaced with ``base``'s,
451
- * preserving path, query, and fragment.
452
- *
453
- * Returns the original ``target`` on any parse failure rather than
454
- * throwing — the SDK consumes the URL eagerly and shouldn't break
455
- * a session over a malformed clip envelope.
456
- */
457
- declare function rewriteUrlHost(target: string, base: string): string;
458
- /** Internal — segments referenced by an HLS manifest, in playback order. */
459
- interface ParsedPlaylist {
460
- initUrl: string;
461
- segmentUrls: string[];
462
- }
463
- /**
464
- * Suggested grace period for callers that opt into a *bounded* wait by
465
- * passing it as {@link FetchPlaylistOptions.slackMs}. It is **not** a
466
- * default: {@link fetchPlaylist} polls indefinitely unless a bound is
467
- * supplied. Provided so callers who do want the old ~15 s ceiling can
468
- * ask for it by name rather than hard-coding a magic number.
469
- */
470
- declare const DEFAULT_PLAYLIST_POLL_SLACK_MS = 15000;
471
- interface FetchPlaylistOptions {
472
- /**
473
- * Unix epoch (ms) when the runtime predicts the boundary chunk will
474
- * be servable. Pass `clip.predictedReadyAtMs` here. On its own it
475
- * does *not* stop polling — it only anchors the optional `slackMs`
476
- * deadline. Use it to drive a "ready in Ns" indicator.
477
- */
478
- predictedReadyAtMs?: number;
479
- /**
480
- * Opt-in grace period that turns polling into a *bounded* wait. When
481
- * set to a finite value, a stuck `202` produces `CLIP_NOT_READY` once
482
- * `max(predictedReadyAtMs, pollStart) + slackMs` passes. Omit (the
483
- * default) to poll indefinitely until the manifest is ready or the
484
- * caller aborts via `signal`. See {@link DEFAULT_PLAYLIST_POLL_SLACK_MS}
485
- * for a sensible value if you want the old ~15 s ceiling.
486
- */
487
- slackMs?: number;
488
- /**
489
- * Hard cap on the per-poll wait. The server's `Retry-After` header is
490
- * honored but clamped. Default 2000 ms keeps pending UI snappy.
491
- */
492
- maxRetryDelayMs?: number;
493
- /** Floor on the per-poll wait so we don't hot-loop on cheap networks. Default 200 ms. */
494
- minRetryDelayMs?: number;
495
- /**
496
- * Opt-in cap on the number of `202` responses tolerated before
497
- * `CLIP_NOT_READY`. Omit (the default) to poll indefinitely; set it
498
- * for a simple attempt-count ceiling when you don't have a
499
- * `predictedReadyAtMs` to anchor a `slackMs` deadline.
500
- */
501
- maxRetries?: number;
502
- /**
503
- * Aborts in-flight fetches and the inter-poll sleep. Because polling
504
- * is unbounded by default, this is the primary way a caller ends a
505
- * wait that is taking too long (a timeout, a user "cancel", a React
506
- * unmount).
507
- */
508
- signal?: AbortSignal;
509
- /**
510
- * Coordinator JWT. When set, attached as `Authorization: Bearer
511
- * <jwt>` on the manifest GET — the Coordinator hop. In local mode
512
- * (HttpRuntime), leave undefined.
513
- */
514
- jwt?: string;
515
- }
516
- /**
517
- * Fetch the playlist URL, polling on `202 Accepted` (which the manifest
518
- * endpoint returns while the boundary chunk is still uploading).
519
- *
520
- * Polling is **unbounded by default** — it keeps retrying on `202`
521
- * until the manifest is ready or the caller aborts via `signal`. This
522
- * matches the reality that a clip's boundary chunk can take arbitrarily
523
- * long to land (a paused model closes no chunks; a long recording's
524
- * final chunk is large). Callers own the give-up policy: pass `signal`
525
- * to cancel, or opt into a ceiling with `slackMs` / `maxRetries`.
526
- *
527
- * - `200` → returns the manifest body.
528
- * - `410` / `404` → throws `CLIP_GONE`.
529
- * - `5xx`/other → throws `PLAYLIST_FETCH_FAILED` (no retry).
530
- * - `202` past an opt-in `slackMs` deadline or `maxRetries` cap →
531
- * throws `CLIP_NOT_READY`.
532
- * - aborted `signal` → rejects with the fetch/`sleep` `AbortError`.
533
- */
534
- declare function fetchPlaylist(playlistUrl: string, options?: FetchPlaylistOptions): Promise<string>;
535
- /**
536
- * Parse an HLS `.m3u8` body into the init segment URL plus the ordered
537
- * list of media segment URLs. Resolves relative URLs against the
538
- * playlist URL itself.
539
- */
540
- declare function parsePlaylist(manifestBody: string, playlistUrl: string): ParsedPlaylist;
541
- /**
542
- * Wrap an HLS manifest body in a `blob:` URL suitable for `<video src>`
543
- * or `hls.js`. Bypasses the "player can't set Authorization headers"
544
- * problem: the manifest body is served from browser memory, and the
545
- * chunk URLs inside are already-signed S3 GETs.
546
- *
547
- * Path-only / relative chunk URLs in the body are absolutized against
548
- * ``playlistUrl`` first. Without this rewrite the browser would
549
- * resolve them against the ``blob:`` URL's effective base — the page's
550
- * origin — and a local-dev frontend on (e.g.) port 3000 would issue
551
- * chunk fetches against its own dev server instead of the
552
- * HttpRuntime's ``/clips/chunks/...`` endpoint on port 8080. In
553
- * production / kind-cluster mode the manifest already carries absolute
554
- * presigned S3 URLs and `resolveAgainst` is a no-op on them.
555
- *
556
- * Caller owns the returned URL — revoke it via `URL.revokeObjectURL`
557
- * when playback tears down. Browser-only; throws `INVALID_PLAYLIST`
558
- * outside a DOM environment.
559
- */
560
- declare function createPlayableManifestUrl(manifestBody: string, playlistUrl: string): string;
561
- interface DownloadClipOptions {
562
- /**
563
- * Coordinator JWT. Attached on the manifest GET only; the chunks
564
- * referenced inside the manifest are S3 presigned URLs and are
565
- * fetched unauthenticated.
566
- */
567
- jwt?: string;
568
- /** Forwarded to every request. Cancels both the playlist poll and any in-flight chunk fetches. */
569
- signal?: AbortSignal;
570
- /** Called after each chunk completes — useful for progress UI. */
571
- onProgress?: (info: {
572
- fetched: number;
573
- total: number;
574
- bytes: number;
575
- }) => void;
576
- }
577
- /**
578
- * Stream the chunks referenced by `clip.playlistUrl`, remux the
579
- * assembled bytes into a flat social-media-ready MP4, and (when
580
- * `filename` is non-null) trigger a browser-native `<a download>`.
581
- * Pass `filename: null` to skip the download trigger and just
582
- * receive the Blob.
583
- *
584
- * The remux step rewrites the container only — H.264 NAL units and
585
- * AAC packets pass through unchanged — so `start_time=0`,
586
- * `+faststart`, and `major_brand=isom` come for free without any
587
- * re-encode cost. See {@link maybeRemux} for the fallback
588
- * semantics on the rare parse failure.
589
- */
590
- declare function downloadClipAsFile(clip: Clip, filename?: string | null, options?: DownloadClipOptions): Promise<Blob>;
591
-
592
- /**
593
- * Per-Reactor recording client. Owns the FIFO promise correlator for
594
- * inbound `clipReady` / `clipFailed` runtime messages and the
595
- * lifecycle hooks (subscribe on construct, reject pending requests
596
- * on disconnect). Reactor exposes thin delegations for the common
597
- * case; this class is exported for advanced consumers and isolated
598
- * testing.
599
- */
600
-
601
- /** Default per-request timeout for `clipReady` / `clipFailed`. */
602
- declare const DEFAULT_CLIP_REQUEST_TIMEOUT_MS = 10000;
603
- /** Slim adapter the {@link RecordingClient} requires from its host. */
604
- interface RecordingClientHost {
605
- /**
606
- * Subscribe to runtime-scoped messages on the data channel.
607
- * Returns an unsubscribe function. Mirrors the
608
- * `reactor.on("runtimeMessage", …)` pattern.
609
- */
610
- onRuntimeMessage: (handler: (message: unknown) => void) => () => void;
611
- /**
612
- * Subscribe to status changes (so the client can reject pending
613
- * requests on disconnect). Returns an unsubscribe function.
614
- */
615
- onStatusChanged: (handler: (status: ReactorStatus) => void) => () => void;
616
- /**
617
- * Send a runtime-scoped command on the data channel. The
618
- * `RecordingClient` uses this to fire `requestClip` /
619
- * `requestRecording`.
620
- */
621
- sendRuntimeCommand: (command: string, data: Record<string, unknown>) => Promise<void>;
622
- /** Current connection status — guards `requestClip` before it goes on the wire. */
623
- getStatus: () => ReactorStatus;
624
- /**
625
- * Coordinator base URL used to resolve `clip.playlistUrl` against.
626
- *
627
- * The runtime now emits a path-only ``playlist_url`` (e.g.
628
- * ``/clips?session_id=…``) so the SDK is the absolute-origin owner
629
- * for both local-dev (HttpRuntime on the SDK's ``apiUrl``) and
630
- * production (Coordinator on the SDK's ``apiUrl``). We always
631
- * resolve against the ``Reactor``'s coordinator URL — there is no
632
- * remote-vs-local divergence on the read path.
633
- *
634
- * For backwards-compat with older runtimes that emitted absolute
635
- * URLs (scheme + host bound to the runtime's own listener,
636
- * e.g. ``http://0.0.0.0:8080/clips?…``), the same URL is also used
637
- * to rewrite the host onto the coordinator — see
638
- * ``rewriteUrlHost`` in ``utils/recording.ts``.
639
- */
640
- getCoordinatorBaseUrl: () => string | undefined;
641
- }
642
- declare class RecordingClient {
643
- private readonly host;
644
- private pendingClipRequests;
645
- /** Timeout applied per request; configurable for tests. */
646
- private readonly requestTimeoutMs;
647
- /** Cleanup handles for the host event subscriptions. */
648
- private readonly unsubscribers;
649
- constructor(host: RecordingClientHost, options?: {
650
- requestTimeoutMs?: number;
651
- });
652
- /**
653
- * Request a clip covering the last `durationSeconds` of the live
654
- * session. See {@link Reactor.requestClip}.
655
- */
656
- requestClip(durationSeconds: number): Promise<Clip>;
657
- /**
658
- * Request a clip covering the entire session up to "now". See
659
- * {@link Reactor.requestRecording}.
660
- */
661
- requestRecording(): Promise<Clip>;
662
- /**
663
- * Poll `/clips` and return the raw manifest body. Same polling
664
- * semantics as the bare {@link fetchPlaylist} helper; the caller is
665
- * responsible for supplying the Coordinator JWT via `options.jwt`
666
- * (origin-scoped to `clip.playlistUrl`). In local mode against the
667
- * HttpRuntime, `options.jwt` should be omitted.
668
- */
669
- fetchPlaylist(clip: Clip, options?: FetchPlaylistOptions): Promise<string>;
670
- /**
671
- * Fetch the manifest and return a `blob:` URL suitable for
672
- * `<video src>` / `hls.js`. The player reads the manifest from
673
- * browser memory; chunk URLs inside are presigned S3 GETs.
674
- *
675
- * Caller owns the returned URL — revoke it via `URL.revokeObjectURL`
676
- * when playback tears down. Pass `options.jwt` for production
677
- * `/clips` (the Coordinator hop) — see {@link FetchPlaylistOptions}.
678
- */
679
- getPlayableManifestUrl(clip: Clip, options?: FetchPlaylistOptions): Promise<string>;
680
- /**
681
- * Thin delegation to {@link downloadClipAsFile}. Caller must pass
682
- * `options.jwt` in production — see {@link DownloadClipOptions}.
683
- */
684
- downloadClipAsFile(clip: Clip, filename?: string | null, options?: DownloadClipOptions): Promise<Blob>;
685
- /**
686
- * Drop every pending request and unsubscribe from host events.
687
- * Safe to call multiple times; further `requestClip` /
688
- * `requestRecording` calls after `destroy()` will hang waiting for
689
- * a response that will never arrive — host should not call into
690
- * the client after destroy.
691
- */
692
- destroy(): void;
693
- /**
694
- * Register a pending FIFO entry, send the runtime message via
695
- * the host, and resolve when the next `clipReady` / `clipFailed`
696
- * arrives.
697
- */
698
- private dispatchClipRequest;
699
- /**
700
- * Match inbound `clipReady` / `clipFailed` to the next pending
701
- * request FIFO; ignore every other runtime message type.
702
- */
703
- private onRuntimeMessage;
704
- private onStatusChanged;
705
- /** Reject every in-flight request with a typed disconnect error. */
706
- private rejectPending;
707
- }
708
-
709
- declare const DEFAULT_BASE_URL = "https://api.reactor.inc";
710
- declare const OptionsSchema: z.ZodObject<{
711
- apiUrl: z.ZodDefault<z.ZodString>;
712
- modelName: z.ZodString;
713
- local: z.ZodDefault<z.ZodBoolean>;
714
- modelTracks: z.ZodOptional<z.ZodArray<z.ZodObject<{
715
- name: z.ZodString;
716
- kind: z.ZodEnum<{
717
- video: "video";
718
- audio: "audio";
719
- }>;
720
- direction: z.ZodEnum<{
721
- recvonly: "recvonly";
722
- sendonly: "sendonly";
723
- }>;
724
- }, z.core.$strip>>>;
725
- }, z.core.$strip>;
726
- type Options = z.input<typeof OptionsSchema>;
727
-
728
- type EventHandler = (...args: any[]) => void;
729
- declare class Reactor {
730
- private coordinatorClient;
731
- private transportClient;
732
- private status;
733
- private coordinatorUrl;
734
- private lastError?;
735
- private model;
736
- private sessionExpiration?;
737
- private local;
738
- private sessionId?;
739
- /**
740
- * True only when the active session was created by THIS connect flow
741
- * (via `createSession()`). False when the session was adopted via
742
- * `connect({ sessionId })`. We must never DELETE a session we did not
743
- * create — another client (or the backend that created it) owns its
744
- * lifecycle, so on disconnect/teardown/error an adopting client tears
745
- * down its own transport but leaves the session alive.
746
- */
747
- private createdSession;
748
- private retryingSessionLoss;
749
- private connectStartTime?;
750
- private connectionTimings?;
751
- private schema?;
752
- private tracks;
753
- private presetTracks?;
754
- private autoResumeTracks;
755
- private sessionResponse?;
756
- private jwtResolver?;
757
- /** Per-Reactor recording client. See {@link RecordingClient}. */
758
- readonly recording: RecordingClient;
759
- constructor(options: Options);
760
- private eventListeners;
761
- /**
762
- * Returns the JWT resolver supplied to the most recent
763
- * {@link connect} call, or `undefined` if none was set (pre-connect
764
- * or local mode). Used by clip surfaces as a fallback when their
765
- * own `getJwt` prop is omitted.
766
- */
767
- getJwtResolver(): JwtResolver | undefined;
768
- on(event: ReactorEvent, handler: EventHandler): void;
769
- off(event: ReactorEvent, handler: EventHandler): void;
770
- emit(event: ReactorEvent, ...args: any[]): void;
771
- /**
772
- * Sends a command to the model via the data channel.
773
- *
774
- * When any value in `data` is a {@link FileRef}, it is automatically
775
- * extracted and serialized into a separate `uploads` section on the
776
- * wire, keyed by the parameter name. Scalar values remain in `data`.
777
- */
778
- sendCommand(command: string, data: any, scope?: MessageScope): Promise<void>;
779
- /**
780
- * Uploads a file to the session's object store and returns a {@link FileRef}.
781
- *
782
- * Flow:
783
- * 1. POST /sessions/{id}/uploads → allocate presigned PUT URL
784
- * 2. PUT file bytes to the presigned URL
785
- * 3. Send `fileUploaded` notification on the runtime data channel
786
- * (fires `@file_uploaded` on the model if registered)
787
- * 4. Return a `FileRef` to pass into {@link sendCommand}
788
- *
789
- * In local mode, the presigned URL returned by the runtime is rewritten
790
- * to use the SDK-configured base URL (scheme + host), so port-forwarded
791
- * setups work correctly (REA-1573).
792
- */
793
- uploadFile(file: File | Blob, options?: {
794
- name?: string;
795
- }): Promise<FileRef>;
796
- /**
797
- * Request a clip covering the last `durationSeconds` of the live
798
- * session. Capped server-side at `recording.clip_max_seconds`
799
- * (default 5 minutes). Resolves with a {@link Clip} whose
800
- * `playlistUrl` can be handed to any HLS-capable player.
801
- *
802
- * @throws {RecordingError} on invalid input, transport failure,
803
- * timeout, runtime-side `clipFailed`, or disconnect mid-request.
804
- */
805
- requestClip(durationSeconds: number): Promise<Clip>;
806
- /**
807
- * Request a clip covering the entire session up to "now". Same
808
- * mechanics as {@link requestClip} with `start = 0`; only the
809
- * resolved {@link Clip.kind} discriminator differs.
810
- */
811
- requestRecording(): Promise<Clip>;
812
- /**
813
- * Stream the chunks referenced by `clip.playlistUrl` and trigger a
814
- * native browser download of the assembled fragmented-MP4 Blob.
815
- * Pass `filename: null` to skip the download trigger and receive
816
- * the Blob (useful for non-DOM consumers and tests).
817
- */
818
- downloadClipAsFile(clip: Clip, filename?: string | null, options?: DownloadClipOptions): Promise<Blob>;
819
- /**
820
- * Publishes a MediaStreamTrack to a named sendonly track.
821
- * The transceiver is already set up from capabilities — this just
822
- * calls replaceTrack() on the sender.
823
- */
824
- publishTrack(name: string, track: MediaStreamTrack): Promise<void>;
825
- unpublishTrack(name: string): Promise<void>;
826
- pauseTrack(name: string): void;
827
- resumeTrack(name: string): void;
828
- /** Whether `name` is a track this client receives rather than sends. */
829
- private isRecvonly;
830
- /**
831
- * Reconnects to an existing session with a fresh transport.
832
- */
833
- reconnect(options?: ConnectOptions): Promise<void>;
834
- /**
835
- * Connects to the coordinator, creates a session, then establishes
836
- * the transport using server-declared capabilities. `jwtToken` may
837
- * be a static string or a {@link JwtSource} resolver; pass a
838
- * resolver when the token is short-lived so each Coordinator HTTP
839
- * hop sees a fresh value.
840
- *
841
- * Pass `options.sessionId` to attach to a session that already exists
842
- * (e.g. one created by a backend) instead of creating a new one — session
843
- * creation is skipped and the transport is brought up against that id. The
844
- * `jwtToken` must be valid for the account that owns the session. Works in
845
- * local mode too (it looks the session up by id rather than starting one).
846
- */
847
- connect(jwtToken?: JwtSource, options?: ConnectOptions): Promise<void>;
848
- /**
849
- * Sets up event handlers for the transport client.
850
- * Each handler captures the client reference to ignore stale events.
851
- */
852
- private setupTransportHandlers;
853
- /**
854
- * Disconnects from both the transport and the coordinator.
855
- */
856
- disconnect(recoverable?: boolean): Promise<void>;
857
- getSessionId(): string | undefined;
858
- getStatus(): ReactorStatus;
859
- getState(): ReactorState$1;
860
- getLastError(): ReactorError | undefined;
861
- /**
862
- * The model's OpenAPI schema (events, outbound messages, tracks),
863
- * received over the runtime channel shortly after the session becomes
864
- * ready. `undefined` until the `schemaReceived` event has fired.
865
- */
866
- getSchema(): ModelSchema | undefined;
867
- getSessionInfo(): SessionResponse | undefined;
868
- getStats(): ConnectionStats | undefined;
869
- /** Timing breakdown from the most recent connect() handshake. */
870
- getConnectionTimings(): ConnectionTimings | undefined;
871
- private setSessionId;
872
- private setStatus;
873
- private setSessionExpiration;
874
- private resetConnectionTimings;
875
- private finalizeConnectionTimings;
876
- private createError;
877
- }
878
-
879
- interface ReactorState {
880
- status: ReactorStatus;
881
- /**
882
- * Media tracks received from the model, keyed by track name.
883
- *
884
- * Each entry maps a recvonly track name (e.g. `"main_video"`,
885
- * `"main_audio"`) to the live `MediaStreamTrack` delivered by the model.
886
- */
887
- tracks: Record<string, MediaStreamTrack>;
888
- lastError?: ReactorError;
889
- sessionId?: string;
890
- sessionExpiration?: number;
891
- /** Token source for Coordinator HTTP calls — see {@link JwtSource}. */
892
- jwtToken?: JwtSource;
893
- /**
894
- * Default connect options set by the provider. Applied as base values
895
- * whenever `connect()` is called without explicit options, so that
896
- * provider-level settings like `autoResumeTracks` are honoured for
897
- * both autoConnect and manual connect calls.
898
- */
899
- connectOptions?: ConnectOptions;
900
- }
901
- interface ReactorActions {
902
- sendCommand(command: string, data: any, scope?: MessageScope): Promise<void>;
903
- /**
904
- * Connect the underlying {@link Reactor}. `options` is forwarded verbatim —
905
- * pass `options.sessionId` to attach to an existing session instead of
906
- * creating one (see {@link ConnectOptions}).
907
- */
908
- connect(jwtToken?: JwtSource, options?: ConnectOptions): Promise<void>;
909
- disconnect(recoverable?: boolean): Promise<void>;
910
- publish(name: string, track: MediaStreamTrack): Promise<void>;
911
- unpublish(name: string): Promise<void>;
912
- /**
913
- * Ask the runtime to stop processing a recvonly track. Top-level
914
- * alias for `internal.reactor.pauseTrack(…)` — lifted onto the store
915
- * so consumers don't have to reach through `internal.reactor`. See
916
- * {@link Reactor.pauseTrack}.
917
- */
918
- pauseTrack(name: string): void;
919
- /**
920
- * Ask the runtime to resume a previously paused recvonly track.
921
- * Top-level alias for `internal.reactor.resumeTrack(…)`. See
922
- * {@link Reactor.resumeTrack}.
923
- */
924
- resumeTrack(name: string): void;
925
- reconnect(options?: ConnectOptions): Promise<void>;
926
- uploadFile(file: File | Blob, options?: {
927
- name?: string;
928
- }): Promise<FileRef>;
929
- /**
930
- * Capture the trailing `durationSeconds` of the live session as a
931
- * clip. Top-level alias for `internal.reactor.requestClip(…)` —
932
- * lifted onto the store so consumers don't have to reach through
933
- * `internal.reactor` for the common case. See
934
- * {@link Reactor.requestClip}.
935
- */
936
- requestClip(durationSeconds: number): Promise<Clip>;
937
- /**
938
- * Capture the entire session up to "now" as a clip. Top-level
939
- * alias for `internal.reactor.requestRecording()`. See
940
- * {@link Reactor.requestRecording}.
941
- */
942
- requestRecording(): Promise<Clip>;
943
- /**
944
- * Stream the chunks referenced by `clip.playlistUrl` and trigger a
945
- * native browser download of the assembled MP4. Top-level alias
946
- * for `internal.reactor.downloadClipAsFile(…)`. See
947
- * {@link Reactor.downloadClipAsFile}.
948
- */
949
- downloadClipAsFile(clip: Clip, filename?: string | null, options?: DownloadClipOptions): Promise<Blob>;
950
- }
951
- interface ReactorInternalState {
952
- reactor: Reactor;
953
- }
954
- type ReactorStore = ReactorState & ReactorActions & {
955
- internal: ReactorInternalState;
956
- };
957
- interface ReactorInitializationProps extends Options {
958
- /** Token source for the underlying {@link Reactor} — see {@link JwtSource}. */
959
- jwtToken?: JwtSource;
960
- /** Default connect options applied when `connect()` is called without explicit options. */
961
- connectOptions?: ConnectOptions;
962
- }
963
-
964
- /**
965
- * Options for the React provider's connect behavior.
966
- * Extends the core ConnectOptions with autoConnect for the React lifecycle.
967
- */
968
- interface ReactorConnectOptions extends ConnectOptions {
969
- /** Whether to automatically connect when the provider mounts. Default: false. */
970
- autoConnect?: boolean;
971
- }
972
- interface ReactorProviderProps extends Omit<ReactorInitializationProps, "jwtToken"> {
973
- connectOptions?: ReactorConnectOptions;
974
- /**
975
- * Static JWT token. Use when you hold a long-lived SDK JWT (e.g.
976
- * minted via `/tokens`). For short-lived tokens use {@link getJwt}.
977
- */
978
- jwtToken?: string;
979
- /**
980
- * Lazy JWT resolver invoked immediately before each Coordinator
981
- * HTTP request. Preferred for short-lived tokens. Wins over
982
- * {@link jwtToken} when both are provided.
983
- */
984
- getJwt?: JwtResolver;
985
- children?: ReactNode;
986
- }
987
- declare function ReactorProvider({ children, connectOptions, jwtToken, getJwt, ...props }: ReactorProviderProps): react_jsx_runtime.JSX.Element;
988
- declare function useReactorStore<T = ReactorStore>(selector: (state: ReactorStore) => T): T;
989
-
990
- interface ReactorViewProps {
991
- /**
992
- * The name of the recvonly track to render.
993
- * Must match a track name declared in the server capabilities.
994
- * Check the model's documentation for available track names.
995
- * Defaults to `"main_video"`.
996
- */
997
- track?: string;
998
- /**
999
- * Optional name of a recvonly audio track to play alongside the video
1000
- * (e.g. `"main_audio"`). The audio is mixed into the same `<video>` element.
1001
- * Check the model's documentation for available track names.
1002
- */
1003
- audioTrack?: string;
1004
- width?: number;
1005
- height?: number;
1006
- className?: string;
1007
- style?: React.CSSProperties;
1008
- videoObjectFit?: NonNullable<React.VideoHTMLAttributes<HTMLVideoElement>["style"]>["objectFit"];
1009
- /**
1010
- * Controls whether inbound audio plays. Default is `true`
1011
- * (muted) when no `audioTrack` is set — keeps the underlying
1012
- * `<video>` element within browser autoplay policies; `false`
1013
- * when an `audioTrack` is set. Pass an explicit value to
1014
- * override either default.
1015
- */
1016
- muted?: boolean;
1017
- }
1018
- declare function ReactorView({ track, audioTrack, width, height, className, style, videoObjectFit, muted, }: ReactorViewProps): react_jsx_runtime.JSX.Element;
1019
-
1020
- interface WebcamStreamProps {
1021
- /**
1022
- * The name of the sendonly **video** track to publish the webcam to.
1023
- * Must match a track name declared in the server capabilities.
1024
- * Check the model's documentation for available track names.
1025
- */
1026
- track: string;
1027
- /**
1028
- * Capture and publish the microphone alongside the webcam. Pass
1029
- * `true` for default constraints, or an explicit
1030
- * `MediaTrackConstraints` to control sample rate / device / echo
1031
- * cancellation. Requires {@link audioTrack} so the SDK knows
1032
- * which sendonly track to publish the mic to. Default `false`.
1033
- */
1034
- audio?: boolean | MediaTrackConstraints;
1035
- /**
1036
- * The name of the sendonly **audio** track to publish the mic to.
1037
- * Ignored when {@link audio} is `false` (the default); required
1038
- * otherwise.
1039
- */
1040
- audioTrack?: string;
1041
- className?: string;
1042
- style?: React.CSSProperties;
1043
- videoConstraints?: MediaTrackConstraints;
1044
- showWebcam?: boolean;
1045
- videoObjectFit?: NonNullable<React.VideoHTMLAttributes<HTMLVideoElement>["style"]>["objectFit"];
1046
- /**
1047
- * Fires once `getUserMedia` is rejected with `NotAllowedError`
1048
- * or `PermissionDeniedError`.
1049
- */
1050
- onPermissionDenied?: () => void;
1051
- /**
1052
- * Fires after the local media stream has been published (both
1053
- * video and audio when {@link audio} is enabled). Re-fires
1054
- * after a reconnect.
1055
- */
1056
- onPublished?: () => void;
1057
- /**
1058
- * Fires on non-permission `getUserMedia` failures and on
1059
- * publish / unpublish rejections. Permission denials route to
1060
- * {@link onPermissionDenied} instead.
1061
- */
1062
- onError?: (error: Error) => void;
1063
- }
1064
- declare function WebcamStream({ track, audio, audioTrack, className, style, videoConstraints, showWebcam, videoObjectFit, onPermissionDenied, onPublished, onError, }: WebcamStreamProps): react_jsx_runtime.JSX.Element;
1065
-
1066
- /**
1067
- * Video preview for a captured {@link Clip}.
1068
- *
1069
- * Plays into a ``<video controls>`` element, streaming the clip with
1070
- * ``hls.js`` wherever Media Source Extensions exist — every current
1071
- * browser, iOS Safari 17.1 and later included. ``hls.js`` is
1072
- * dynamically imported, so bundlers give it a chunk of its own that
1073
- * an app importing this component fetches on first play and one that
1074
- * never renders a player drops entirely. On iOS before 17.1 the clip
1075
- * is assembled into a single MP4 and played from memory instead: the
1076
- * whole clip is fetched before it starts, and it plays. Failures
1077
- * surface in an inline error overlay, and the same clip stays
1078
- * downloadable via {@link useClipDownload} /
1079
- * {@link ClipDownloadButton}.
1080
- *
1081
- * **Preview only.** This component intentionally does *not* render a
1082
- * download UI. Compose it with {@link ClipDownloadButton} or build
1083
- * your own download surface around {@link useClipDownload} — the
1084
- * separation keeps both pieces independently extendible and avoids
1085
- * baking layout decisions into the SDK.
1086
- *
1087
- * Unlike {@link ReactorView} / {@link WebcamStream} this component
1088
- * **does not require a ``ReactorProvider``** in the tree. It
1089
- * operates on the ``Clip`` value alone, so it stays usable after
1090
- * ``reactor.disconnect()`` and works with clips loaded from
1091
- * fixtures, server logs, or any other source. When a
1092
- * ``ReactorProvider`` is mounted above, an omitted ``getJwt``
1093
- * inherits the provider's resolver.
1094
- *
1095
- * @example Compose with the download button (explicit `getJwt`):
1096
- * ```tsx
1097
- * <div>
1098
- * <ClipPlayer clip={clip} getJwt={() => jwt} />
1099
- * <ClipDownloadButton clip={clip} getJwt={() => jwt} />
1100
- * </div>
1101
- * ```
1102
- *
1103
- * @example Local dev (HttpRuntime, no auth on /clips):
1104
- * ```tsx
1105
- * <ClipPlayer clip={clip} />
1106
- * ```
1107
- */
1108
- interface ClipPlayerProps {
1109
- /**
1110
- * The captured clip to play. When this prop changes by reference
1111
- * the player re-fetches the manifest and re-attaches the player.
1112
- */
1113
- clip: Clip;
1114
- /**
1115
- * Lazy resolver for the Coordinator JWT used on the ``/clips``
1116
- * manifest GET. Called at request time so token refreshes are
1117
- * picked up automatically.
1118
- *
1119
- * - **Production:** required outside a ``<ReactorProvider>``;
1120
- * optional inside one (inherits the provider's resolver).
1121
- * - **Local-dev (HttpRuntime):** omit — ``/clips`` is auth-free.
1122
- *
1123
- * Chunk URLs inside the manifest are presigned (prod) or
1124
- * unauthenticated (local) and are fetched without
1125
- * ``Authorization`` in either case.
1126
- */
1127
- getJwt?: () => string | Promise<string>;
1128
- /**
1129
- * Opt into a *bounded* wait: give up polling the ``/clips`` manifest
1130
- * endpoint with ``CLIP_NOT_READY`` once
1131
- * ``max(clip.predictedReadyAtMs, pollStart) + slackMs`` passes. By
1132
- * default this is **unset** — the player polls indefinitely until the
1133
- * clip is ready, and stops only when it unmounts or ``clip`` changes
1134
- * (both abort the in-flight poll). Set a value when you want a hard
1135
- * ceiling (e.g. ``120_000`` for a two-minute cap). Forwarded
1136
- * directly to {@link fetchPlaylist}'s ``slackMs`` option — see that
1137
- * helper for the polling semantics.
1138
- */
1139
- slackMs?: number;
1140
- /** Play automatically once the manifest is attached. Default ``true``. */
1141
- autoPlay?: boolean;
1142
- /**
1143
- * Start muted. Default ``true`` because browser autoplay policies
1144
- * block audio-bearing video from playing without a user gesture;
1145
- * the user can unmute via the native ``<video controls>``.
1146
- */
1147
- muted?: boolean;
1148
- className?: string;
1149
- style?: React.CSSProperties;
1150
- /**
1151
- * Fires when the player enters its inline error state. Receives
1152
- * the originating error: a ``RecordingError`` for manifest-fetch
1153
- * failures, a plain ``Error`` for hls.js / native playback or
1154
- * missing-peer-dep cases.
1155
- */
1156
- onError?: (error: Error) => void;
1157
- }
1158
- declare function ClipPlayer({ clip, getJwt, slackMs, autoPlay, muted, className, style, onError, }: ClipPlayerProps): react_jsx_runtime.JSX.Element;
1159
-
1160
- /**
1161
- * State machine for an in-progress clip download.
1162
- *
1163
- * - ``idle``: no download in flight (initial state, and what the hook
1164
- * returns to after a successful save).
1165
- * - ``downloading``: chunks are being fetched. ``fetched`` and
1166
- * ``total`` count the number of chunks (init segment + media
1167
- * segments) — useful for a progress bar. ``total`` is 0 until the
1168
- * manifest is parsed and the chunk count is known.
1169
- * - ``error``: most recent attempt failed; the ``message`` is suitable
1170
- * for surfacing inline. ``RecordingError`` instances are formatted
1171
- * as ``"<CODE>: <reason>"`` for grep-ability.
1172
- */
1173
- type ClipDownloadState = {
1174
- kind: "idle";
1175
- } | {
1176
- kind: "downloading";
1177
- fetched: number;
1178
- total: number;
1179
- } | {
1180
- kind: "error";
1181
- message: string;
1182
- };
1183
- interface UseClipDownloadOptions {
1184
- /**
1185
- * Filename used when the browser save dialog opens. Pass ``null``
1186
- * to skip the ``<a download>`` trigger entirely — the returned
1187
- * Blob is still resolved so the caller can ``URL.createObjectURL``
1188
- * it or re-upload it. Default ``"reactor-clip.mp4"``.
1189
- */
1190
- filename?: string | null;
1191
- /**
1192
- * Lazy resolver for the Coordinator JWT used on the ``/clips``
1193
- * manifest GET. Called on every {@link download} invocation, so
1194
- * token refreshes are picked up automatically.
1195
- *
1196
- * Optional inside a ``<ReactorProvider>`` (inherits the provider's
1197
- * resolver) and in local-dev mode. See
1198
- * {@link ClipPlayerProps.getJwt}.
1199
- */
1200
- getJwt?: () => string | Promise<string>;
1201
- }
1202
- interface UseClipDownloadResult {
1203
- /** Current state of the most recent download attempt. */
1204
- state: ClipDownloadState;
1205
- /**
1206
- * Trigger a download. Resolves with the assembled fragmented-MP4
1207
- * Blob, or ``undefined`` if a download was already in flight (the
1208
- * call is a no-op in that case — guarding against double-click is
1209
- * the hook's responsibility, not the caller's).
1210
- *
1211
- * Errors are caught and surfaced via {@link state} — the returned
1212
- * Promise still resolves to ``undefined`` rather than rejecting,
1213
- * because the typical caller is a click handler that doesn't await.
1214
- * Use ``state.kind === "error"`` to drive failure UI.
1215
- */
1216
- download: () => Promise<Blob | undefined>;
1217
- /** Reset to ``idle``. Does *not* cancel an in-flight download. */
1218
- reset: () => void;
1219
- }
1220
- /**
1221
- * Headless download primitive for a {@link Clip}.
1222
- *
1223
- * Wraps {@link downloadClipAsFile} in a React state machine so the
1224
- * consumer can render any button they want, anywhere they want, and
1225
- * still get progress + error feedback. Used internally by
1226
- * {@link ClipPlayer}'s built-in download button — when you need
1227
- * custom placement or styling, set ``showDownloadButton={false}`` on
1228
- * the player and call this hook directly.
1229
- *
1230
- * Stable callback identity: ``download`` and ``reset`` are the same
1231
- * function reference across renders, so they're safe to pass through
1232
- * memoized children without forcing re-renders.
1233
- *
1234
- * @example Render a download button anywhere in your tree:
1235
- * ```tsx
1236
- * function ClipCard({ clip }: { clip: Clip }) {
1237
- * const jwt = useReactor((s) => s.jwtToken);
1238
- * const { state, download } = useClipDownload(clip, {
1239
- * filename: `snap-${clip.sessionId}.mp4`,
1240
- * getJwt: jwt ? () => jwt : undefined,
1241
- * });
1242
- * return (
1243
- * <button onClick={download} disabled={state.kind === "downloading"}>
1244
- * {state.kind === "downloading"
1245
- * ? `${state.fetched}/${state.total}`
1246
- * : state.kind === "error"
1247
- * ? "Retry"
1248
- * : "Download"}
1249
- * </button>
1250
- * );
1251
- * }
1252
- * ```
1253
- */
1254
- declare function useClipDownload(clip: Clip, options?: UseClipDownloadOptions): UseClipDownloadResult;
1255
-
1256
- /**
1257
- * Standalone download button for a captured {@link Clip}.
1258
- *
1259
- * Drops anywhere in your UI — modal headers, list rows, hover menus,
1260
- * floating action buttons — and is responsible for nothing more than
1261
- * triggering a download and reflecting its state. Internally wraps
1262
- * {@link useClipDownload}; for completely custom UIs (progress bars,
1263
- * menu items, post-download blob handling) call that hook directly.
1264
- *
1265
- * Styling is intentionally minimal. Override via ``className``,
1266
- * ``style``, or replace the inner content with the ``children``
1267
- * render-prop. No CSS file is shipped — every default style is
1268
- * inline so it loses to anything the consumer provides.
1269
- *
1270
- * @example Default label, state-aware:
1271
- * ```tsx
1272
- * <ClipDownloadButton clip={clip} getJwt={() => jwt} />
1273
- * ```
1274
- *
1275
- * @example Custom label that follows the state:
1276
- * ```tsx
1277
- * <ClipDownloadButton clip={clip} getJwt={() => jwt}>
1278
- * {(s) => (s.kind === "downloading" ? `${s.fetched}/${s.total}` : "Save MP4")}
1279
- * </ClipDownloadButton>
1280
- * ```
1281
- *
1282
- * @example Static label:
1283
- * ```tsx
1284
- * <ClipDownloadButton clip={clip} getJwt={() => jwt}>Save</ClipDownloadButton>
1285
- * ```
1286
- */
1287
- interface ClipDownloadButtonProps {
1288
- /** The clip to download. */
1289
- clip: Clip;
1290
- /**
1291
- * Lazy JWT resolver. Optional inside a ``<ReactorProvider>``
1292
- * (inherits the provider's resolver) and in local-dev mode. See
1293
- * {@link ClipPlayerProps.getJwt}.
1294
- */
1295
- getJwt?: () => string | Promise<string>;
1296
- /** Filename for the saved MP4. Default ``"reactor-clip.mp4"``. */
1297
- filename?: string;
1298
- /**
1299
- * Inner content of the button. Three forms:
1300
- *
1301
- * - **Omitted** — renders a sensible default label that follows
1302
- * the state (``"Download"`` / ``"Downloading 3/8…"`` / etc.).
1303
- * - **`ReactNode`** — static label. No state-driven text.
1304
- * - **`(state) => ReactNode`** — state-aware render function;
1305
- * use for custom progress strings, spinners, etc.
1306
- */
1307
- children?: React.ReactNode | ((state: ClipDownloadState) => React.ReactNode);
1308
- /** Forwarded to the underlying ``<button>``. */
1309
- className?: string;
1310
- /** Forwarded to the underlying ``<button>`` — merges *after* the defaults so each property overrides. */
1311
- style?: React.CSSProperties;
1312
- /** Forwarded to the underlying ``<button>``. ORed with the internal "downloading" state. */
1313
- disabled?: boolean;
1314
- /**
1315
- * Fires when the download completes with the assembled MP4 ``Blob``.
1316
- */
1317
- onSuccess?: (blob: Blob) => void;
1318
- /**
1319
- * Fires when the download fails. Message mirrors the in-button
1320
- * state — ``"<CODE>: <reason>"`` for ``RecordingError``s, the
1321
- * plain error message otherwise.
1322
- */
1323
- onError?: (error: Error) => void;
1324
- }
1325
- declare function ClipDownloadButton({ clip, getJwt, filename, children, className, style, disabled, onSuccess, onError, }: ClipDownloadButtonProps): react_jsx_runtime.JSX.Element;
1326
-
1327
- /**
1328
- * Generic hook for accessing selected parts of the Reactor store.
1329
- *
1330
- * @param selector - A function that selects part of the store state.
1331
- * @returns The selected slice from the store.
1332
- */
1333
- declare function useReactor<T>(selector: (state: ReactorStore) => T): T;
1334
- /**
1335
- * Hook for receiving model application messages.
1336
- *
1337
- * Only fires for messages sent by the model via `get_ctx().send()`.
1338
- * Internal platform-level messages (e.g. capabilities) are NOT delivered here.
1339
- *
1340
- * @param handler - Callback invoked with each application message payload.
1341
- */
1342
- declare function useReactorMessage(handler: (message: any) => void): void;
1343
- /**
1344
- * Hook for receiving internal platform-level (runtime) messages.
1345
- *
1346
- * This is intended for advanced use cases that need access to the runtime
1347
- * control layer, such as capabilities negotiation. Model application messages
1348
- * sent via `get_ctx().send()` are NOT delivered through this hook — use
1349
- * {@link useReactorMessage} for those.
1350
- *
1351
- * @param handler - Callback invoked with each runtime message payload.
1352
- */
1353
- declare function useReactorInternalMessage(handler: (message: any) => void): void;
1354
- /**
1355
- * Hook that returns the current connection stats (RTT, etc.).
1356
- * Updates every ~2s while connected. Returns undefined when disconnected.
1357
- */
1358
- declare function useStats(): ConnectionStats | undefined;
1359
-
1360
- 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 ModelSchema, type ModelSchemaOperation, type ModelSchemaPathItem, type ModerationAction, type ModerationEvent, type Options, type ParseClipOptions, Reactor, type ReactorConnectOptions, type ReactorError, type ReactorEvent, ReactorProvider, type ReactorState$1 as ReactorState, type ReactorStatus, type ReactorStore, ReactorView, type ReactorViewProps, RecordingClient, type RecordingClientHost, RecordingError, RuntimeRecordingMessageType, SessionLostError, type SessionResponse, type TrackCapability, type UseClipDownloadOptions, type UseClipDownloadResult, WebcamStream, type WebcamStreamProps, clipFromPayload, createPlayableManifestUrl, downloadClipAsFile, fetchPlaylist, isAbortError, isSessionLostError, normalizeJwtSource, parsePlaylist, rewriteUrlHost, useClipDownload, useReactor, useReactorInternalMessage, useReactorMessage, useReactorStore, useStats };