@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.
@@ -0,0 +1,1234 @@
1
+ import * as react from 'react';
2
+ import { ReactNode, CSSProperties, VideoHTMLAttributes } from 'react';
3
+
4
+ /**
5
+ * Every Reactor failure carries `code`, `recoverable`, `status`, `operation`,
6
+ * `retry_after_ms` and `timestamp_ms` — `reactor-core`'s canonical shape,
7
+ * shared by every SDK on it. `timestamp`/`retryAfter` are kept alongside
8
+ * under their previous names for compatibility — see their own doc comments
9
+ * below — rather than dropped, since this package's public API may only
10
+ * grow.
11
+ *
12
+ * There is **one class**, not two: the `error` event payload and a rejected
13
+ * call's error are the same shape and the same instance type.
14
+ *
15
+ * `ReactorError` is the base of a typed hierarchy keyed by `code` —
16
+ * `reactor-core`'s own per-failure-kind classification — so `instanceof
17
+ * UnauthorizedError` and `code === 'UNAUTHORIZED'` are equivalent, one just
18
+ * typed. Codes are open-ended (the platform can send its own), so an
19
+ * unrecognized one falls back to the base class itself rather than
20
+ * throwing.
21
+ */
22
+ /** Fields a `ReactorError` constructor accepts, all optional — an
23
+ * unrecognized code still constructs cleanly on the base class, and a
24
+ * purely local failure (no payload at all) still constructs cleanly too. */
25
+ interface ReactorErrorOptions {
26
+ code?: string | undefined;
27
+ recoverable?: boolean | undefined;
28
+ status?: number | undefined;
29
+ operation?: string | undefined;
30
+ retry_after_ms?: number | undefined;
31
+ timestamp_ms?: number | undefined;
32
+ }
33
+ declare class ReactorError extends Error {
34
+ /** The code this class stands for. `ReactorError` itself is the fallback,
35
+ * so it claims none and takes whatever the payload reported. */
36
+ static readonly code: string;
37
+ /** `reactor-core`'s own canonical code for this failure — the same value
38
+ * used to pick this instance's class (see the typed subclasses below for
39
+ * the vocabulary). Open-ended: an unrecognized code still constructs the
40
+ * base class, with `code` set to whatever was reported. */
41
+ readonly code: string;
42
+ /** Whether the same call could succeed later. */
43
+ readonly recoverable: boolean;
44
+ /** The HTTP status, when the failure came from one. */
45
+ readonly status: number | undefined;
46
+ /** Which call failed, e.g. "connect", "sendCommand". */
47
+ readonly operation: string | undefined;
48
+ /** Backoff hint the platform sent. */
49
+ readonly retry_after_ms: number | undefined;
50
+ /** When `reactor-core` reported this failure. For a purely local one (no
51
+ * payload at all — see {@link ReactorErrorOptions}), this is synthesized
52
+ * as the construction time instead, since there's nothing to report —
53
+ * not a value read off the wire. */
54
+ readonly timestamp_ms: number;
55
+ /** Same value as `retry_after_ms`, under its previous name. Kept for
56
+ * compatibility — prefer `retry_after_ms`. */
57
+ readonly retryAfter: number | undefined;
58
+ /** Same value as `timestamp_ms`, under its previous name. Kept for
59
+ * compatibility — prefer `timestamp_ms`. */
60
+ readonly timestamp: number;
61
+ constructor(message: string, options?: ReactorErrorOptions);
62
+ }
63
+ /** The request never got a reply — DNS, TLS, a refused socket. */
64
+ declare class NetworkError extends ReactorError {
65
+ static readonly code = "NETWORK_ERROR";
66
+ }
67
+ /** 401 or 403: the token is missing, expired, or not scoped for this call. */
68
+ declare class UnauthorizedError extends ReactorError {
69
+ static readonly code = "UNAUTHORIZED";
70
+ }
71
+ /** 404: no such model, session or upload. */
72
+ declare class NotFoundError extends ReactorError {
73
+ static readonly code = "NOT_FOUND";
74
+ }
75
+ /** 409: the session is in a state that does not allow this — usually a
76
+ * session left orphaned by a previous run that went away without
77
+ * disconnecting. */
78
+ declare class ConflictError extends ReactorError {
79
+ static readonly code = "CONFLICT";
80
+ }
81
+ /** 429: too many requests. `retry_after_ms` carries the server's
82
+ * `Retry-After` when it sent one; `undefined` means back off on your own
83
+ * terms rather than retrying immediately. */
84
+ declare class RateLimitedError extends ReactorError {
85
+ static readonly code = "RATE_LIMITED";
86
+ }
87
+ /** A 4xx other than the ones above: the request itself was wrong. */
88
+ declare class BadRequestError extends ReactorError {
89
+ static readonly code = "BAD_REQUEST";
90
+ }
91
+ /** 5xx: the coordinator failed, and the same request may work later. */
92
+ declare class ServerError extends ReactorError {
93
+ static readonly code = "SERVER_ERROR";
94
+ }
95
+ /** This client and the platform disagree on the protocol — upgrade the SDK. */
96
+ declare class VersionMismatchError extends ReactorError {
97
+ static readonly code = "VERSION_MISMATCH";
98
+ }
99
+ /** A reply arrived and could not be understood. */
100
+ declare class DecodeError extends ReactorError {
101
+ static readonly code = "DECODE_FAILED";
102
+ }
103
+ /** The operation is not allowed from the state the client is in — most often
104
+ * a call that needs a live session, made before `connect()` or after the
105
+ * status left `"ready"`. */
106
+ declare class InvalidStateError extends ReactorError {
107
+ static readonly code = "INVALID_STATE";
108
+ }
109
+ /** The session reached a state it cannot leave. Start a new one. */
110
+ declare class SessionTerminalError extends ReactorError {
111
+ static readonly code = "SESSION_TERMINAL";
112
+ }
113
+ /** The payload exceeds what the data channel accepts — send large content
114
+ * with `uploadFile()` and pass the `FileRef` instead of embedding it
115
+ * inline in a command. */
116
+ declare class MessageTooLargeError extends ReactorError {
117
+ static readonly code = "MESSAGE_TOO_LARGE";
118
+ }
119
+ /** The media transport failed. */
120
+ declare class TransportError extends ReactorError {
121
+ static readonly code = "TRANSPORT_ERROR";
122
+ }
123
+ /** The connection went away, either dropped mid-request or lost after being
124
+ * established. `reconnect()` is the way back. */
125
+ declare class DisconnectedError extends ReactorError {
126
+ static readonly code = "DISCONNECTED";
127
+ }
128
+ /** The operation was sent and nothing came back in time. */
129
+ declare class RequestTimeoutError extends ReactorError {
130
+ static readonly code = "REQUEST_TIMEOUT";
131
+ }
132
+ /** The operation was abandoned before it finished. */
133
+ declare class AbortedError extends ReactorError {
134
+ static readonly code = "ABORTED";
135
+ }
136
+ /**
137
+ * A `requestClip()`/`requestRecording()` call failed because the model's
138
+ * recorder is disabled or has crashed.
139
+ *
140
+ * Unlike every other code here, `RECORDER_DISABLED` isn't platform-sent —
141
+ * `reactor-core` produces it by matching known reason strings on an
142
+ * otherwise free-text `ClipFailed` message, as a stopgap until that message
143
+ * carries a structured reason (tracked as REA-5403). Treat it as best-effort:
144
+ * a clip failure for the same underlying reason may still arrive as the
145
+ * base `ReactorError` (`code: "INTERNAL_ERROR"`) if the reason text ever
146
+ * changes upstream.
147
+ *
148
+ * `recoverable` is `false`: the recorder being disabled or crashed isn't
149
+ * something retrying the same `requestClip()`/`requestRecording()` call can
150
+ * fix — it needs an operator to re-enable or restart the recorder on the
151
+ * model side first.
152
+ */
153
+ declare class RecorderDisabledError extends ReactorError {
154
+ static readonly code = "RECORDER_DISABLED";
155
+ }
156
+
157
+ /**
158
+ * Reference to a file uploaded via `Reactor.uploadFile()`. Pass it back as a
159
+ * top-level value in `sendCommand()`'s `data` and it's extracted and sent as
160
+ * a separate upload reference rather than embedded in the JSON payload —
161
+ * see `extractFileRefs()`.
162
+ */
163
+ declare class FileRef {
164
+ readonly uploadId: string;
165
+ readonly name: string;
166
+ readonly mimeType: string;
167
+ readonly size: number;
168
+ constructor(uploadId: string, name: string, mimeType: string, size: number);
169
+ }
170
+ /**
171
+ * Structural check for anything shaped like a `FileRef`, for callers who'd
172
+ * rather duck-type than rely on `instanceof` (e.g. across two copies of this
173
+ * package bundled into the same page). `extractFileRefs()` uses this too,
174
+ * for the same reason.
175
+ */
176
+ declare function isFileRef(value: unknown): value is FileRef;
177
+
178
+ /**
179
+ * The `reactor-wasm` contract, mirrored by hand.
180
+ *
181
+ * `crates/reactor-wasm` generates the real `reactor_wasm.d.ts` at
182
+ * `mise run build:wasm` time (see `crates/reactor-wasm/src/types.rs` and
183
+ * `client.rs`), but that output isn't committed — the JS SDK depends on a
184
+ * build step, not a checked-in file. This file re-states that same contract
185
+ * so `sdks/js` type-checks on a fresh checkout too, before anyone has run the
186
+ * wasm build. Node resolution always prefers a real, installed module over an
187
+ * ambient ad-hoc declaration, so once `reactor_wasm.js`/`.d.ts` exist next to
188
+ * this at runtime, they're what actually loads — this file only fills the gap
189
+ * until then.
190
+ *
191
+ * Keep in sync with the two files above. Field naming follows the wire, not
192
+ * JavaScript: payloads that come out of the core keep snake_case
193
+ * (`protocol_version`, `retry_after_ms`, `playlist_url`, ...); only the
194
+ * options this crate defines itself are camelCase.
195
+ */
196
+ type ReactorStatus = 'disconnected' | 'connecting' | 'waiting' | 'ready';
197
+ type TrackKind = 'audio' | 'video';
198
+ type TrackDirection = 'recvonly' | 'sendonly';
199
+ interface ClientOptions {
200
+ modelName: string;
201
+ apiUrl?: string;
202
+ local?: boolean;
203
+ sdkType?: string;
204
+ sdkVersion?: string;
205
+ autoResumeTracks?: boolean;
206
+ extraArgs?: Record<string, unknown>;
207
+ heartbeatIntervalMs?: number;
208
+ readyTimeoutMs?: number;
209
+ controlRequestTimeoutMs?: number;
210
+ clipRequestTimeoutMs?: number;
211
+ maxSessionAttempts?: number;
212
+ maxSdpAttempts?: number;
213
+ sdpBackoffInitialMs?: number;
214
+ sdpBackoffMaxMs?: number;
215
+ sdpBackoffMultiplier?: number;
216
+ modelTracks?: TrackCapability[];
217
+ logLevel?: 'off' | 'error' | 'warn' | 'info' | 'debug' | 'trace';
218
+ }
219
+ interface ConnectOptions {
220
+ sessionId?: string;
221
+ connectionId?: number;
222
+ autoResumeTracks?: boolean;
223
+ maxAttempts?: number;
224
+ }
225
+ /** A token, or a resolver called before every authenticated request.
226
+ * Returning "" sends no Authorization header. */
227
+ type JwtSource = string | (() => string | Promise<string>);
228
+ interface TrackCapability {
229
+ name: string;
230
+ kind: TrackKind;
231
+ direction: TrackDirection;
232
+ }
233
+ interface TrackMappingEntry extends TrackCapability {
234
+ mid: string;
235
+ }
236
+ interface CommandCapability$1 {
237
+ name: string;
238
+ description?: string;
239
+ schema?: unknown;
240
+ }
241
+ interface Capabilities$1 {
242
+ protocol_version: string;
243
+ tracks: TrackCapability[];
244
+ commands?: CommandCapability$1[];
245
+ emission_fps?: number;
246
+ }
247
+ interface SessionInfo {
248
+ session_id: string;
249
+ state: string;
250
+ model?: {
251
+ name: string;
252
+ version?: string;
253
+ };
254
+ cluster?: string;
255
+ server_info?: {
256
+ server_version: string;
257
+ };
258
+ selected_transport?: {
259
+ protocol: string;
260
+ version: string;
261
+ };
262
+ capabilities?: Capabilities$1;
263
+ [key: string]: unknown;
264
+ }
265
+ interface ReactorMessage {
266
+ type: string;
267
+ data: unknown;
268
+ }
269
+
270
+ /** The session resource, as the coordinator reports it — see
271
+ * `Reactor.getSessionInfo()`. */
272
+ type SessionResponse = SessionInfo;
273
+ /**
274
+ * Scope tag for `sendCommand()`. This SDK has no generic runtime-scope
275
+ * channel — see `Reactor`'s private `sendRuntimeScopedCommand()` for what
276
+ * `"runtime"` actually does here (routes a couple of recognized commands to
277
+ * their direct equivalents, warns and falls through to a normal send for
278
+ * anything else).
279
+ */
280
+ type MessageScope = 'application' | 'runtime';
281
+ /** Any object, except a function. */
282
+ type NotFunction<T> = T extends (...args: never[]) => unknown ? never : T;
283
+ /** One command the model declares in its capabilities. */
284
+ interface CommandCapability {
285
+ name: string;
286
+ description?: string;
287
+ schema?: unknown;
288
+ }
289
+ /**
290
+ * The runtime's declared capabilities for the session — negotiated tracks,
291
+ * and the command set when the model exposes one. Pushed once available (no
292
+ * explicit request needed) — see `Reactor.getCapabilities()`/
293
+ * `capabilitiesReceived`.
294
+ *
295
+ * camelCase — the wasm binding's own wire shape is snake_case
296
+ * (`protocol_version`, `emission_fps`), translated at the boundary in
297
+ * `internal/capabilities.ts` rather than exposed directly here.
298
+ */
299
+ interface Capabilities {
300
+ protocolVersion: string;
301
+ tracks: TrackCapability[];
302
+ commands?: CommandCapability[];
303
+ emissionFps?: number;
304
+ }
305
+ /** One OpenAPI operation (the `post` of an event/webhook path item). */
306
+ interface ModelSchemaOperation {
307
+ operationId?: string;
308
+ summary?: string;
309
+ description?: string;
310
+ requestBody?: {
311
+ required?: boolean;
312
+ content?: Record<string, {
313
+ schema?: Record<string, unknown>;
314
+ }>;
315
+ };
316
+ responses?: Record<string, unknown>;
317
+ [key: string]: unknown;
318
+ }
319
+ /** An OpenAPI path item; the runtime only populates `post`. */
320
+ interface ModelSchemaPathItem {
321
+ post?: ModelSchemaOperation;
322
+ [key: string]: unknown;
323
+ }
324
+ /**
325
+ * The model's OpenAPI 3.1 schema, returned by `requestSchema()`/cached by
326
+ * `getSchema()`. A pass-through of the runtime's document, not a shape this
327
+ * SDK reshapes: client-triggerable events live under `paths` as
328
+ * `POST /events/<name>` operations, outbound model messages under
329
+ * `webhooks`, and media tracks under `x-reactor.tracks`. Read the parts you
330
+ * need.
331
+ */
332
+ interface ModelSchema {
333
+ openapi: string;
334
+ info: {
335
+ title: string;
336
+ version: string;
337
+ description?: string;
338
+ };
339
+ paths?: Record<string, ModelSchemaPathItem>;
340
+ webhooks?: Record<string, ModelSchemaPathItem>;
341
+ 'x-reactor'?: {
342
+ tracks?: Array<{
343
+ name: string;
344
+ kind: string;
345
+ direction: string;
346
+ }>;
347
+ };
348
+ components?: Record<string, unknown>;
349
+ [key: string]: unknown;
350
+ }
351
+ /**
352
+ * Severity tier of a content-moderation event delivered as the inner
353
+ * payload of a `runtimeMessage` with `type === "moderation"`. `"warn"`
354
+ * continues the session (informational only); `"terminate"` ends it shortly
355
+ * after the message is dispatched.
356
+ */
357
+ type ModerationAction = 'warn' | 'terminate';
358
+ /**
359
+ * Inner payload of a `runtimeMessage` with `type === "moderation"`. Surfaces
360
+ * a content-moderation outcome to the client app on any moderatable input
361
+ * (free-text fields, file uploads) the configured policy flags — subscribe
362
+ * via `reactor.on("runtimeMessage", ...)` and filter on `type`.
363
+ */
364
+ interface ModerationEvent {
365
+ action: ModerationAction;
366
+ /** Modality of the flagged input. `"text"` for string fields, `"image"`
367
+ * for file-upload payloads with an image MIME type. */
368
+ input_kind: 'text' | 'image';
369
+ /** Name of the inbound command/event whose payload was flagged. */
370
+ command: string;
371
+ /** Category labels that flagged (e.g. `["sexual"]`, `["violence/graphic"]`). */
372
+ categories: string[];
373
+ /** Short human-readable summary suitable for UI rendering. */
374
+ message: string;
375
+ }
376
+ /**
377
+ * `Reactor` construction options. Only `modelName` is required.
378
+ *
379
+ * Everything but `jwt` passes straight through to the wasm binding's
380
+ * `ClientOptions` — see `crates/reactor-wasm/src/types.rs` for what each
381
+ * field does. `jwt` lives here instead because the binding takes it as a
382
+ * second constructor argument, not a field; `Reactor` accepts one options
383
+ * object and splits it internally.
384
+ */
385
+ interface ReactorOptions extends ClientOptions {
386
+ /** A token, or a resolver called before every authenticated request.
387
+ * Omit for an unauthenticated local runtime. Replaceable later by passing
388
+ * a new one to `connect()`. */
389
+ jwt?: JwtSource;
390
+ }
391
+ /**
392
+ * Timing breakdown of the `connect()` handshake, recorded once per connection
393
+ * and included in every subsequent `ConnectionStats` update. All durations
394
+ * are in milliseconds (from `performance.now()`).
395
+ *
396
+ * `sessionCreationMs` covers session creation/adoption (the binding's
397
+ * `"connecting"` phase); `transportConnectingMs` covers the session-ready
398
+ * wait and transport handshake together (the `"waiting"` phase) — that
399
+ * handshake happens entirely inside `reactor-core`, so this can only split
400
+ * on the phase boundaries the binding's status events expose, not on the
401
+ * finer steps within each one.
402
+ */
403
+ interface ConnectionTimings {
404
+ sessionCreationMs: number;
405
+ transportConnectingMs: number;
406
+ /** End-to-end: connect() invocation → status "ready". */
407
+ totalMs: number;
408
+ }
409
+ interface ConnectionStats {
410
+ /** ICE candidate-pair round-trip time in milliseconds */
411
+ rtt?: number | undefined;
412
+ /** ICE candidate type: "host", "srflx", "prflx", or "relay" (TURN) */
413
+ candidateType?: string | undefined;
414
+ /** Estimated available incoming bitrate in bits/second */
415
+ availableIncomingBitrate?: number | undefined;
416
+ /** Estimated available outgoing bitrate in bits/second */
417
+ availableOutgoingBitrate?: number | undefined;
418
+ /** Real-time incoming bitrate in bits/second */
419
+ incomingBitrate?: number | undefined;
420
+ /** Real-time outgoing bitrate in bits/second */
421
+ outgoingBitrate?: number | undefined;
422
+ /** Received video frames per second */
423
+ framesPerSecond?: number | undefined;
424
+ /** Ratio of packets lost (0-1) */
425
+ packetLossRatio?: number | undefined;
426
+ /** Network jitter in seconds (from inbound-rtp) */
427
+ jitter?: number | undefined;
428
+ /** Timing breakdown of the initial connection handshake (set once, persisted until disconnect) */
429
+ connectionTimings?: ConnectionTimings | undefined;
430
+ timestamp: number;
431
+ }
432
+ /** Discriminator on a {@link Clip}. `"snap"` from `requestClip()`, `"recording"` from `requestRecording()`. */
433
+ type ClipKind = 'snap' | 'recording';
434
+ /**
435
+ * A finished (or soon-available) clip, from `requestClip()` / `requestRecording()`.
436
+ *
437
+ * The runtime returns immediately on every request — it does not block until
438
+ * the in-progress chunk finalizes. `predictedReadyAtMs` is the runtime's own
439
+ * estimate of when `playlistUrl` becomes fetchable; `fetchPlaylist()` and
440
+ * `downloadClipAsFile()` poll past it until the manifest is actually ready.
441
+ */
442
+ interface Clip {
443
+ sessionId: string;
444
+ kind: ClipKind;
445
+ /** Session-relative seconds since recorder start. */
446
+ startMarker: number;
447
+ endMarker: number;
448
+ nowMarker: number;
449
+ /** Unix epoch in milliseconds. */
450
+ predictedReadyAtMs: number;
451
+ /** Absolute HLS manifest URL — short-lived; re-issuing the request produces a fresh one. */
452
+ playlistUrl: string;
453
+ }
454
+ interface ReactorEventMap {
455
+ statusChanged: (status: ReactorStatus) => void;
456
+ sessionIdChanged: (sessionId: string | undefined) => void;
457
+ error: (error: ReactorError) => void;
458
+ /** Application-scope payload from the model. */
459
+ message: (message: ReactorMessage) => void;
460
+ /** Platform-scope payload, same name as the Python SDK's `runtime_message`. */
461
+ runtimeMessage: (message: ReactorMessage) => void;
462
+ /** The model's command schema, fired once the auto-request on `"ready"`
463
+ * lands — see `getSchema()`. */
464
+ schemaReceived: (schema: ModelSchema) => void;
465
+ /** The runtime's declared capabilities, fired once available — see
466
+ * `getCapabilities()`. */
467
+ capabilitiesReceived: (capabilities: Capabilities) => void;
468
+ /** Fired when the model side of a track's media becomes available.
469
+ * `Reactor` resolves the wasm binding's raw `(name, mid)` through
470
+ * `getTrackByName`/`getStreamByName` before emitting, so callers don't
471
+ * need an extra step. `reactor-core` only ever dispatches this once the
472
+ * track is already resolvable (it drops the underlying event entirely
473
+ * otherwise), so `track`/`stream` are always real values here, never
474
+ * `undefined`; `mid` rides along as an extra escape hatch for callers
475
+ * that want the binding's own identifier (e.g. for
476
+ * `getTrackByMid`/`getStreamByMid`). */
477
+ trackReceived: (name: string, track: MediaStreamTrack, stream: MediaStream, mid: string | undefined) => void;
478
+ /** Fired every `STATS_INTERVAL_MS` while the session is "ready" — see
479
+ * `getStats()`. */
480
+ statsUpdate: (stats: ConnectionStats) => void;
481
+ }
482
+ type ReactorEventName = keyof ReactorEventMap;
483
+
484
+ /**
485
+ * Browser-side primitives for turning a `Clip` (from `requestClip()` /
486
+ * `requestRecording()`) into playable or downloadable media.
487
+ *
488
+ * `Clip.playlistUrl` names an HLS media playlist — `#EXT-X-VERSION:7`
489
+ * fragmented MP4, an `#EXT-X-MAP` init segment followed by `.m4s` media
490
+ * fragments — that the caller fetches and assembles; Reactor itself doesn't
491
+ * host clips. This module owns fetching and parsing that playlist
492
+ * (`fetchPlaylist` / `parsePlaylist`), wrapping it for a `<video>` element or
493
+ * `hls.js` (`createPlayableManifestUrl`), and assembling the referenced
494
+ * chunks into a flat, downloadable MP4 (`downloadClipAsFile`).
495
+ */
496
+
497
+ /**
498
+ * Error thrown when a clip's playlist or chunks can't be fetched, parsed, or
499
+ * assembled into a file. Scoped to this module — a failure in
500
+ * `requestClip()` / `requestRecording()` themselves surfaces as a
501
+ * `ReactorError`, since those go through `reactor-core`'s own error channel.
502
+ *
503
+ * `code` is a stable, machine-readable identifier; `reason` is the raw
504
+ * string behind it (an HTTP status, a parse complaint, …).
505
+ */
506
+ declare class RecordingError extends Error {
507
+ readonly code: 'CLIP_GONE' | 'CLIP_NOT_READY' | 'PLAYLIST_FETCH_FAILED' | 'CHUNK_FETCH_FAILED' | 'INVALID_PLAYLIST' | 'DOWNLOAD_UNSUPPORTED';
508
+ readonly reason: string;
509
+ constructor(code: 'CLIP_GONE' | 'CLIP_NOT_READY' | 'PLAYLIST_FETCH_FAILED' | 'CHUNK_FETCH_FAILED' | 'INVALID_PLAYLIST' | 'DOWNLOAD_UNSUPPORTED', reason: string);
510
+ }
511
+ /** Segments referenced by an HLS manifest, in playback order. */
512
+ interface ParsedPlaylist {
513
+ initUrl: string;
514
+ segmentUrls: string[];
515
+ }
516
+ /**
517
+ * Suggested grace period for callers that opt into a bounded wait by passing
518
+ * it as `FetchPlaylistOptions.slackMs`. Not a default — `fetchPlaylist()`
519
+ * polls indefinitely unless a bound is supplied.
520
+ */
521
+ declare const DEFAULT_PLAYLIST_POLL_SLACK_MS = 15000;
522
+ interface FetchPlaylistOptions {
523
+ /**
524
+ * Unix epoch (ms) when the runtime predicts the boundary chunk will be
525
+ * servable — pass `clip.predictedReadyAtMs`. On its own this doesn't stop
526
+ * polling; it only anchors the optional `slackMs` deadline.
527
+ */
528
+ predictedReadyAtMs?: number;
529
+ /**
530
+ * Opt-in grace period that turns polling into a bounded wait: a stuck
531
+ * `202` produces `CLIP_NOT_READY` once `max(predictedReadyAtMs, pollStart)
532
+ * + slackMs` passes. Omit (the default) to poll indefinitely until the
533
+ * manifest is ready or the caller aborts via `signal`.
534
+ */
535
+ slackMs?: number;
536
+ /** Hard cap on the per-poll wait. `Retry-After` is honored but clamped. Default 2000 ms. */
537
+ maxRetryDelayMs?: number;
538
+ /** Floor on the per-poll wait so a cheap network doesn't hot-loop. Default 200 ms. */
539
+ minRetryDelayMs?: number;
540
+ /**
541
+ * Opt-in cap on the number of `202` responses tolerated before
542
+ * `CLIP_NOT_READY`. Omit (the default) to poll indefinitely.
543
+ */
544
+ maxRetries?: number;
545
+ /**
546
+ * Aborts in-flight fetches and the inter-poll sleep — the primary way to
547
+ * end an unbounded wait (a timeout, a user cancel, a component unmount).
548
+ */
549
+ signal?: AbortSignal;
550
+ /**
551
+ * Coordinator JWT, attached as `Authorization: Bearer <jwt>` on the
552
+ * manifest GET. Omit in local mode (HttpRuntime).
553
+ */
554
+ jwt?: string;
555
+ }
556
+ /**
557
+ * Fetch `playlistUrl`, polling on `202 Accepted` — returned while the
558
+ * boundary chunk is still uploading.
559
+ *
560
+ * - `200` → the manifest body.
561
+ * - `410` / `404` → `CLIP_GONE`.
562
+ * - other → `PLAYLIST_FETCH_FAILED` (no retry).
563
+ * - `202` past an opt-in `slackMs` deadline or `maxRetries` cap → `CLIP_NOT_READY`.
564
+ * - aborted `signal` → rejects with the fetch/sleep `AbortError`.
565
+ */
566
+ declare function fetchPlaylist(playlistUrl: string, options?: FetchPlaylistOptions): Promise<string>;
567
+ /**
568
+ * Parse an HLS `.m3u8` body into the init segment URL plus the ordered media
569
+ * segment URLs, resolving relative URLs against `playlistUrl` itself.
570
+ */
571
+ declare function parsePlaylist(manifestBody: string, playlistUrl: string): ParsedPlaylist;
572
+ /**
573
+ * Wrap an HLS manifest body in a `blob:` URL suitable for `<video src>` or
574
+ * `hls.js`. Bypasses "the player can't set an Authorization header": the
575
+ * manifest is served from memory, and its chunk URLs are already-signed S3
576
+ * GETs. Path-only chunk URLs in the body are absolutized against
577
+ * `playlistUrl` first — without that, the browser would resolve them against
578
+ * the `blob:` URL's own origin instead of the runtime's.
579
+ *
580
+ * Caller owns the returned URL — revoke it via `URL.revokeObjectURL` when
581
+ * playback tears down. Browser-only; throws `INVALID_PLAYLIST` outside a DOM
582
+ * environment.
583
+ */
584
+ declare function createPlayableManifestUrl(manifestBody: string, playlistUrl: string): string;
585
+ interface DownloadClipOptions {
586
+ /** Coordinator JWT for the manifest GET. The chunks it references are S3
587
+ * presigned URLs, fetched unauthenticated. */
588
+ jwt?: string;
589
+ /** Cancels both the playlist poll and any in-flight chunk fetches. */
590
+ signal?: AbortSignal;
591
+ /** Called after each chunk completes — useful for progress UI. */
592
+ onProgress?: (info: {
593
+ fetched: number;
594
+ total: number;
595
+ bytes: number;
596
+ }) => void;
597
+ }
598
+ /**
599
+ * Fetch the chunks `clip.playlistUrl` references, remux them into a flat
600
+ * MP4, and (when `filename` is non-null) trigger a browser `<a download>`.
601
+ * Pass `filename: null` to skip the download trigger and just get the Blob.
602
+ *
603
+ * See {@link assembleClipBlob} for the remux and memory-bound caveats.
604
+ */
605
+ declare function downloadClipAsFile(clip: Clip, filename?: string | null, options?: DownloadClipOptions): Promise<Blob>;
606
+
607
+ /**
608
+ * A live connection to a Reactor model.
609
+ */
610
+ declare class Reactor implements Disposable {
611
+ private readonly clientOptions;
612
+ private jwt;
613
+ private client;
614
+ private clientPromise;
615
+ private disposed;
616
+ private _lastError;
617
+ private schema;
618
+ /** Bumped on every `refreshSchema()` call — lets a call detect it's been
619
+ * superseded by a newer one even when `client` itself hasn't changed
620
+ * (e.g. two "ready" transitions on the same reused client). */
621
+ private schemaRefreshId;
622
+ private capabilities;
623
+ private stats;
624
+ private connectionTimings;
625
+ private statsPollHandle;
626
+ /** Bumped on every `startStatsPolling()`/`stopStatsPolling()` call — lets an
627
+ * in-flight `getStats()` recognize it's stale once it resolves, even if
628
+ * `this.client` hasn't changed in the meantime. */
629
+ private statsPollGeneration;
630
+ /** Set on the "connecting" status transition, cleared once `connectionTimings`
631
+ * is finalized on "ready" — see `handleStatusChanged()`. */
632
+ private connectStartTime;
633
+ private waitingStartTime;
634
+ private readonly emitter;
635
+ /** Serializes connect()/reconnect()/disconnect() (and the free() inside
636
+ * disconnect()/[Symbol.dispose]) against each other. Calling into the
637
+ * client concurrently with one of these (e.g. a user clicking Disconnect
638
+ * mid-connect) races its internal state and can throw ("attempted to
639
+ * take ownership of Rust value while it was borrowed") or corrupt it
640
+ * outright. */
641
+ private readonly queue;
642
+ constructor(options: ReactorOptions);
643
+ /**
644
+ * `jwt`, when given, replaces whatever `new Reactor({ jwt })` was given —
645
+ * including on a client that's still around from a recoverable
646
+ * `disconnect(true)`.
647
+ *
648
+ * Throws if already connected or connecting; call `disconnect()` first.
649
+ */
650
+ connect(jwt?: JwtSource, options?: ConnectOptions): Promise<void>;
651
+ /**
652
+ * Ends the connection. By default (`recoverable = false`) this also frees
653
+ * the wasm resource graph — the pump/dispatcher/heartbeat tasks and the
654
+ * peer connection — in one step. Pass `recoverable: true` to keep the
655
+ * wasm client alive so a later `connect()`/`reconnect()` doesn't have to
656
+ * reload wasm and reconstruct it from scratch.
657
+ *
658
+ * Note this only governs the *local* resource graph — the binding's own
659
+ * `disconnect()` always ends the session server-side regardless of this
660
+ * flag, so `recoverable` isn't a way to keep the session itself alive.
661
+ *
662
+ * Queued behind any in-flight `connect()`/`reconnect()` — see `queue`'s
663
+ * docs for why calling into the client concurrently with one of those is
664
+ * unsafe.
665
+ */
666
+ disconnect(recoverable?: boolean): Promise<void>;
667
+ /**
668
+ * Only `options.maxAttempts` has an effect here — the rest of
669
+ * `ConnectOptions` (session adoption, connection id, auto-resume) only
670
+ * makes sense when establishing a session in the first place, same as v2's
671
+ * `reconnect()` always ignored them.
672
+ */
673
+ reconnect(options?: ConnectOptions): Promise<void>;
674
+ /**
675
+ * Sends a command to the model and resolves with its correlated reply.
676
+ *
677
+ * `undefined` means the handler acknowledged the command but sent no
678
+ * reply body. The binding's own typed signature promises `undefined` for
679
+ * that case, but its serializer (serde_wasm_bindgen's `json_compatible`
680
+ * mode) actually hands back `null` — normalized here so callers can rely
681
+ * on the documented type instead of the binding's serialization quirk.
682
+ *
683
+ * A `FileRef` (from `uploadFile`) may be passed as a top-level value in
684
+ * `data` alongside regular parameters — it is extracted and sent as a
685
+ * separate upload reference rather than embedded in the JSON payload.
686
+ *
687
+ * Unlike every other method here, this never rejects — a failure (the
688
+ * session isn't `"ready"`, the send itself fails, …) is reported through
689
+ * `getLastError()`/the `error` event instead, resolving with `undefined`.
690
+ * This is a JS-only compatibility shim, kept because callers routinely
691
+ * fire-and-forget `sendCommand(...)` without `await`/`catch`, and a
692
+ * rejection nobody handles is an unhandled-rejection warning at best. It
693
+ * is deliberately not applied to `publishTrack`/`uploadFile`/etc., which
694
+ * throw normally.
695
+ *
696
+ * `scope` is forwarded to `sendRuntimeScopedCommand()` — see there for
697
+ * what `"runtime"` actually does.
698
+ *
699
+ * `data` accepts any object, except a function.
700
+ */
701
+ sendCommand<T extends object = Record<string, unknown>>(command: string, data?: NotFunction<T>, scope?: MessageScope): Promise<ReactorMessage | undefined>;
702
+ /**
703
+ * Handles `sendCommand(command, data, "runtime")` — this SDK has no
704
+ * generic runtime-scope channel. `reactor-core`'s `send_command` is a
705
+ * single channel; `requestSchema`/clip requests/heartbeat are each their
706
+ * own dedicated RPC instead of a scoped envelope, so there's nothing
707
+ * generic to route a scope through at the wire level.
708
+ *
709
+ * `requestSchema` and `requestCapabilities` route to their direct
710
+ * equivalents below, neither of which returns a `ReactorMessage` the way a
711
+ * normal `sendCommand()` reply would, so both resolve `undefined`; the
712
+ * actual data surfaces through `getSchema()`/`schemaReceived` and
713
+ * `getCapabilities()`/`capabilitiesReceived` as it already does. Anything
714
+ * else has no runtime-scope destination to route to — rather than silently
715
+ * doing nothing, it falls through as a normal application-scope send, with
716
+ * a console warning.
717
+ */
718
+ private sendRuntimeScopedCommand;
719
+ /** Requests the model's command schema directly. Most callers don't need
720
+ * this — it's already fetched once and cached as soon as the session
721
+ * reaches `"ready"`; use `getSchema()` for that. Resolves `undefined`
722
+ * when the model doesn't expose a schema — the binding replies with a
723
+ * wire `null` in that case rather than omitting the field. */
724
+ requestSchema(): Promise<ModelSchema | undefined>;
725
+ /** The model's command schema (an OpenAPI document), cached from the
726
+ * `requestSchema()` call fired automatically on `"ready"`. `undefined`
727
+ * until that reply has landed. */
728
+ getSchema(): ModelSchema | undefined;
729
+ /** The runtime's declared capabilities (negotiated tracks, and the
730
+ * command set when the model exposes one) — pushed once available, no
731
+ * explicit request needed. `undefined` until `capabilitiesReceived`
732
+ * fires. */
733
+ getCapabilities(): Capabilities | undefined;
734
+ /** The session resource, as the coordinator reports it — id, state,
735
+ * model, cluster, server info, and (once negotiated) `capabilities`.
736
+ * A live read straight off the wasm client, not cached — reflects
737
+ * whatever's current. `undefined` before a client exists. */
738
+ getSessionInfo(): SessionResponse | undefined;
739
+ /**
740
+ * Publishes a local `MediaStreamTrack` under `name` — the counterpart to a
741
+ * `sendonly` track the model declares. Awaitable. Queued behind
742
+ * connect()/disconnect()/reconnect() (unlike `sendCommand()`): a track
743
+ * operation awaits its own control round-trip, and a concurrent
744
+ * disconnect() freeing the wasm client mid-await would otherwise resume
745
+ * into a freed client — the same class of use-after-free `queue` exists to
746
+ * prevent for connect/disconnect/reconnect themselves.
747
+ */
748
+ publishTrack(name: string, track: MediaStreamTrack): Promise<void>;
749
+ /**
750
+ * Unlike every other track method, this doesn't reject — a failure is
751
+ * reported through the `error` event instead, since this is commonly the
752
+ * last call in a `finally` block, and raising there would replace
753
+ * whatever exception was already propagating.
754
+ */
755
+ unpublishTrack(name: string): Promise<void>;
756
+ /**
757
+ * Stops a received track: the receiver goes inactive and the runtime stops
758
+ * producing it. Awaitable, and queued behind connect()/disconnect()/
759
+ * reconnect() for the same reason as `publishTrack()`.
760
+ */
761
+ pauseTrack(name: string): Promise<void>;
762
+ /** Resumes a track previously stopped with `pauseTrack()`. */
763
+ resumeTrack(name: string): Promise<void>;
764
+ /**
765
+ * Requests a clip covering the last `durationSeconds` of the session.
766
+ * `reactor-core` correlates the reply itself (and enforces `"ready"`), so
767
+ * this is a thin delegation, same as `requestSchema()`. See
768
+ * `downloadClipAsFile()` to turn the result into a file.
769
+ */
770
+ requestClip(durationSeconds: number): Promise<Clip>;
771
+ /** Requests a clip covering the entire session up to now. See `requestClip()`. */
772
+ requestRecording(): Promise<Clip>;
773
+ /** Thin delegation to the standalone `downloadClipAsFile()` — see its own doc comment. */
774
+ downloadClipAsFile(clip: Clip, filename?: string | null, options?: DownloadClipOptions): Promise<Blob>;
775
+ /**
776
+ * Uploads a file to the session's object store, resolving with a
777
+ * `FileRef` to pass as a top-level value in a `sendCommand()`'s `data`
778
+ * (see `extractFileRefs`). The binding itself takes `(file, name?)`
779
+ * positionally and already applies the right defaulting — a bare
780
+ * `Blob`'s name falls back to `"upload"`, and an empty/missing mime type
781
+ * to `"application/octet-stream"` — so there's nothing to wrap here.
782
+ *
783
+ * Queued behind connect()/disconnect()/reconnect(), same as the track
784
+ * ops: this awaits its own round-trip, and a concurrent disconnect()
785
+ * freeing the wasm client mid-upload would otherwise resume into a freed
786
+ * client — the same use-after-free class of race the queue exists to
787
+ * prevent.
788
+ */
789
+ uploadFile(file: File | Blob, options?: {
790
+ name?: string;
791
+ }): Promise<FileRef>;
792
+ /** All tracks the model declared, whether or not media has arrived for —
793
+ * or been published to — them yet. Empty before a client exists. */
794
+ tracks(): TrackCapability[];
795
+ /** Same as `tracks()`, plus each entry's negotiated `mid` — the id
796
+ * `trackReceived`'s `mid` argument and the `getXByMid` escape hatches key
797
+ * on. Only populated once SDP negotiation has assigned mids. */
798
+ trackMapping(): TrackMappingEntry[];
799
+ pausedTracks(): string[];
800
+ /** Drops to the raw `RTCPeerConnection` for anything this class doesn't
801
+ * wrap directly. `undefined` before a client exists. */
802
+ getPeerConnection(): RTCPeerConnection | undefined;
803
+ getTrackByMid(mid: string): MediaStreamTrack | undefined;
804
+ getStreamByMid(mid: string): MediaStream | undefined;
805
+ getTrackByName(name: string): MediaStreamTrack | undefined;
806
+ getStreamByName(name: string): MediaStream | undefined;
807
+ /**
808
+ * Supports `using reactor = new Reactor(...)`: releases the wasm resource
809
+ * graph and drops every registered event handler for good. Unlike a plain
810
+ * `disconnect()`, this instance is unusable afterward — construct a new
811
+ * `Reactor` instead of trying to `connect()` again.
812
+ */
813
+ [Symbol.dispose](): void;
814
+ /** The wasm binding's own terser `status()` name can be added alongside
815
+ * this later if it turns out to be worth it. */
816
+ getStatus(): ReactorStatus;
817
+ /** See `getStatus()`. */
818
+ getSessionId(): string | undefined;
819
+ /** The `jwt` this instance was constructed (or last `connect()`ed) with —
820
+ * lets a component composed inside a `ReactorProvider` (e.g. `ClipPlayer`)
821
+ * authenticate its own requests without the caller repeating the resolver. */
822
+ getJwtResolver(): JwtSource | undefined;
823
+ /** The most recent `ReactorError`, from either an `error` event or a
824
+ * rejected call — whichever landed last. `undefined` until the first
825
+ * failure. */
826
+ getLastError(): ReactorError | undefined;
827
+ /** The most recent WebRTC connection stats, polled every `STATS_INTERVAL_MS`
828
+ * while "ready" — see `statsUpdate`. `undefined` before the first sample. */
829
+ getStats(): ConnectionStats | undefined;
830
+ /** Timing breakdown from the most recent `connect()`/`reconnect()`
831
+ * handshake — see `ConnectionTimings`. */
832
+ getConnectionTimings(): ConnectionTimings | undefined;
833
+ on<Name extends keyof ReactorEventMap>(event: Name, handler: ReactorEventMap[Name]): void;
834
+ off<Name extends keyof ReactorEventMap>(event: Name, handler: ReactorEventMap[Name]): void;
835
+ once<Name extends keyof ReactorEventMap>(event: Name, handler: ReactorEventMap[Name]): void;
836
+ private getOrCreateClient;
837
+ private createClient;
838
+ /** Fired once per `"ready"` transition — see `getSchema()`. `getSchema()`
839
+ * isn't guaranteed populated by the time a `statusChanged` "ready" handler
840
+ * runs (this fetch is async and dispatched separately), so callers that
841
+ * need the schema as soon as it lands should listen for `schemaReceived`
842
+ * instead of reading `getSchema()` synchronously off `statusChanged`.
843
+ *
844
+ * Guards against a stale reply: if `disconnect()`/a later `connect()`
845
+ * replaces `client` before this resolves, or a newer `refreshSchema()`
846
+ * call for the same client wins the race, the result is discarded rather
847
+ * than clobbering `this.schema` (or emitting `schema`) with old data.
848
+ *
849
+ * A rejection here (e.g. the session drops mid-request) surfaces like any
850
+ * other binding failure, through the same `error` event as `onError`. */
851
+ private refreshSchema;
852
+ /** The binding replies with a wire `null` (not an omitted field) when the
853
+ * model doesn't expose a schema — normalized to `undefined` so callers
854
+ * get the same "no schema" sentinel `getSchema()` already uses instead
855
+ * of a document they could otherwise dereference. */
856
+ private normalizeSchema;
857
+ /** Frees the wasm resource graph, if one exists, and clears the cached
858
+ * schema. Reusable — unlike `[Symbol.dispose]`, this doesn't set the
859
+ * permanent `disposed` flag, so a later `connect()`/`reconnect()` lazily
860
+ * builds a fresh client.
861
+ *
862
+ * Only called from within `disconnect()`'s queued task, so `client.free()`
863
+ * is safe to call directly here — the queue already guarantees no other
864
+ * operation is running concurrently against it. */
865
+ private freeClient;
866
+ /** Tracks `connectionTimings` off the binding's own "connecting" → "waiting"
867
+ * → "ready" status sequence (see `ReactorStatus`), and starts/stops stats
868
+ * polling around the "ready" window. */
869
+ private handleStatusChanged;
870
+ private startStatsPolling;
871
+ private stopStatsPolling;
872
+ /** Called on every `disconnect()` and on `[Symbol.dispose]`. Leaves
873
+ * `client`/`schema` alone — that's `freeClient()`'s job, run separately
874
+ * when `disconnect()` isn't recoverable. `capabilities` is cleared here
875
+ * regardless, though: unlike the schema, it isn't re-fetched on demand,
876
+ * so a recoverable disconnect that skips `freeClient()` would otherwise
877
+ * leave `getCapabilities()` returning the previous session's stale
878
+ * tracks/commands until a new `capabilitiesReceived` lands. */
879
+ private resetConnectionState;
880
+ /** Wraps `cause` and records it as the most recent failure, for a call
881
+ * that's about to throw rather than emit — see `getLastError()`'s doc
882
+ * comment. */
883
+ private captureError;
884
+ /** Wraps `cause`, records it as the most recent failure, and fires the
885
+ * `error` event — the one place recording and emitting happen together,
886
+ * so `getLastError()` never drifts from what listeners were told. */
887
+ private emitError;
888
+ private assertNotDisposed;
889
+ }
890
+
891
+ /** Lazy resolver for a Coordinator/runtime bearer token, called immediately
892
+ * before each authenticated request — see `JwtSource`. */
893
+ type JwtResolver = () => string | Promise<string>;
894
+ /**
895
+ * Wraps a `JwtSource` into a `JwtResolver`: a static string becomes a
896
+ * resolver that always returns it, a resolver passes through unchanged.
897
+ * Useful for feeding a source that may be either form (e.g. a
898
+ * `ReactorProvider`'s `jwtToken`) into a `getJwt` prop that expects a
899
+ * resolver.
900
+ */
901
+ declare function normalizeJwtSource(source: JwtSource): JwtResolver;
902
+
903
+ /** State kept reactive for `useReactor` selectors. Stats/schema/capabilities
904
+ * aren't mirrored here — reach them through the `internal.reactor` escape
905
+ * hatch. */
906
+ interface ReactorState {
907
+ status: ReactorStatus;
908
+ sessionId: string | undefined;
909
+ lastError: ReactorError | undefined;
910
+ /** Most recent app-scope `message` payload; `runtimeMessage` isn't mirrored
911
+ * here — subscribe on `internal.reactor` for that. */
912
+ lastMessage: ReactorMessage | undefined;
913
+ /** Media tracks received from the model, keyed by track name. Reset to
914
+ * `{}` on every "disconnected" status transition — a fresh connection
915
+ * invalidates whatever arrived under the previous one. Append-only within
916
+ * a session: a track pausing/unpublishing mid-session doesn't remove its
917
+ * entry, so a stale `MediaStreamTrack` can linger until the next
918
+ * disconnect. Matches v2's identical behavior (`core/store.ts`). */
919
+ tracks: Record<string, MediaStreamTrack>;
920
+ /** The `jwt` the store was created with — see `createReactorStore`'s
921
+ * `options.jwt`. Set once at creation, not resynced afterward. */
922
+ jwtToken: JwtSource | undefined;
923
+ /** The `defaultConnectOptions` the store was created with — set once at
924
+ * creation, not resynced afterward. Lets a component read the
925
+ * provider-level defaults (e.g. `autoResumeTracks`) without threading
926
+ * them through props of its own. */
927
+ connectOptions: ConnectOptions | undefined;
928
+ }
929
+ interface ReactorActions {
930
+ connect: (jwt?: JwtSource, options?: ConnectOptions) => Promise<void>;
931
+ disconnect: (recoverable?: boolean) => Promise<void>;
932
+ reconnect: (options?: ConnectOptions) => Promise<void>;
933
+ sendCommand: <T extends object = Record<string, unknown>>(command: string, data?: NotFunction<T>, scope?: MessageScope) => Promise<ReactorMessage | undefined>;
934
+ publish: (name: string, track: MediaStreamTrack) => Promise<void>;
935
+ unpublish: (name: string) => Promise<void>;
936
+ pauseTrack: (name: string) => Promise<void>;
937
+ resumeTrack: (name: string) => Promise<void>;
938
+ uploadFile: (file: File | Blob, options?: {
939
+ name?: string;
940
+ }) => Promise<FileRef>;
941
+ requestClip: (durationSeconds: number) => Promise<Clip>;
942
+ requestRecording: () => Promise<Clip>;
943
+ downloadClipAsFile: (clip: Clip, filename?: string | null, options?: DownloadClipOptions) => Promise<Blob>;
944
+ }
945
+ interface ReactorInternal {
946
+ /** Escape hatch: the underlying `Reactor` instance, for anything the
947
+ * selector state / action bindings above don't cover. */
948
+ reactor: Reactor;
949
+ }
950
+ type ReactorStore = ReactorState & ReactorActions & {
951
+ internal: ReactorInternal;
952
+ };
953
+
954
+ /** `connectOptions` for the provider — adds `autoConnect` to the core
955
+ * `ConnectOptions`. Live, same as every other `ReactorProviderProps` field —
956
+ * see `ReactorProvider`'s doc comment. */
957
+ interface ReactorConnectOptions extends ConnectOptions {
958
+ /** Connect automatically once a Reactor is built — initial mount, or any
959
+ * later rebuild. Default `false`. */
960
+ autoConnect?: boolean;
961
+ }
962
+ interface ReactorProviderProps {
963
+ apiUrl?: string | undefined;
964
+ modelName: string;
965
+ local?: boolean | undefined;
966
+ /** Media tracks to declare up front, so the transport can prepare the SDP
967
+ * offer in parallel with session polling instead of waiting to discover
968
+ * them from the model's schema. */
969
+ modelTracks?: TrackCapability[] | undefined;
970
+ /** Static token, or a resolver called before every authenticated request
971
+ * — see `JwtSource`. Required for `autoConnect` against a non-local
972
+ * runtime; can also be supplied later via an explicit `connect()` call
973
+ * instead. */
974
+ jwtToken?: JwtSource | undefined;
975
+ connectOptions?: ReactorConnectOptions | undefined;
976
+ children?: ReactNode;
977
+ }
978
+ /**
979
+ * Owns a `Reactor` instance and exposes it to `useReactor` below.
980
+ *
981
+ * `apiUrl`/`modelName`/`local`/`modelTracks`/`jwtToken`/`connectOptions`
982
+ * (including `autoConnect`) are live: changing any of them tears down the
983
+ * current `Reactor` (`disconnect()` then `[Symbol.dispose]()`) and builds a
984
+ * fresh one — the same way `useLiveKitRoom` rebuilds its `Room` when its
985
+ * construction `options` change. `Reactor` has no equivalent of LiveKit's
986
+ * `token`/`serverUrl` split (reconnecting the *same* instance with new
987
+ * credentials) or its live `connect` boolean (toggling the same `Room`'s
988
+ * connection without rebuilding it) — its constructor bundles everything, so
989
+ * any change, `autoConnect` included, means a fresh instance rather than
990
+ * reconnecting/disconnecting the existing one. Pass a stable `jwtToken`
991
+ * (e.g. via `useCallback` for a resolver) and stable `modelTracks`/
992
+ * `connectOptions` references if you don't want an unrelated parent render to
993
+ * rebuild the connection — object/array props are compared by reference
994
+ * (`modelTracks`/`connectOptions` via a `JSON.stringify` snapshot, same as
995
+ * `useLiveKitRoom` does for its own `options`).
996
+ *
997
+ * Unmounting tears down the same way — see `Reactor.disconnect()`/
998
+ * `[Symbol.dispose]()` for what that frees.
999
+ */
1000
+ declare function ReactorProvider({ apiUrl, modelName, local, modelTracks, jwtToken, connectOptions, children, }: ReactorProviderProps): react.JSX.Element;
1001
+
1002
+ /** Reads from the nearest `ReactorProvider`'s store, with a shallow-equality
1003
+ * check on the selector's result — so a selector returning a fresh object
1004
+ * each call doesn't cause a re-render on every unrelated store update. */
1005
+ declare function useReactor<T>(selector: (state: ReactorStore) => T): T;
1006
+ /** Subscribes to app-scope `message` payloads sent by the model via
1007
+ * `get_ctx().send()`. `handler` is kept in a ref so identity churn on
1008
+ * every render doesn't retrigger the subscription effect. */
1009
+ declare function useReactorMessage(handler: (message: ReactorMessage) => void): void;
1010
+ /** Subscribes to platform-scope `runtimeMessage` payloads (moderation,
1011
+ * clip/recording lifecycle, ...) — see `useReactorMessage` for app-scope
1012
+ * payloads instead. */
1013
+ declare function useReactorInternalMessage(handler: (message: ReactorMessage) => void): void;
1014
+ /** The most recent `statsUpdate` sample; `undefined` until the first one
1015
+ * arrives, and reset back to `undefined` on unmount or reactor change. */
1016
+ declare function useStats(): ConnectionStats | undefined;
1017
+
1018
+ interface ReactorViewProps {
1019
+ /** Name of the recvonly video track to render. Must match a track name
1020
+ * declared in the model's capabilities. Defaults to `"main_video"`. */
1021
+ track?: string;
1022
+ /** Name of a recvonly audio track to mix into the same `<video>` element
1023
+ * alongside `track`. */
1024
+ audioTrack?: string;
1025
+ width?: number;
1026
+ height?: number;
1027
+ className?: string;
1028
+ style?: CSSProperties;
1029
+ videoObjectFit?: NonNullable<VideoHTMLAttributes<HTMLVideoElement>['style']>['objectFit'];
1030
+ /** Defaults to `true` when no `audioTrack` is set (keeps the element within
1031
+ * browser autoplay policies), `false` otherwise. Pass an explicit value to
1032
+ * override either default. */
1033
+ muted?: boolean;
1034
+ }
1035
+ declare function ReactorView({ track, audioTrack, width, height, className, style, videoObjectFit, muted, }: ReactorViewProps): react.JSX.Element;
1036
+
1037
+ interface WebcamStreamProps {
1038
+ /** Name of the sendonly video track to publish the webcam to. Must match a
1039
+ * track name declared in the model's capabilities. */
1040
+ track: string;
1041
+ /** Capture and publish the microphone alongside the webcam. `true` for
1042
+ * default constraints, or explicit `MediaTrackConstraints`. Requires
1043
+ * `audioTrack`. Defaults to `false`. */
1044
+ audio?: boolean | MediaTrackConstraints;
1045
+ /** Name of the sendonly audio track to publish the mic to. Ignored unless
1046
+ * `audio` is set. */
1047
+ audioTrack?: string;
1048
+ className?: string;
1049
+ style?: CSSProperties;
1050
+ /** Read once, at mount — changing this after mount doesn't re-request
1051
+ * `getUserMedia`. Matches v2. */
1052
+ videoConstraints?: MediaTrackConstraints;
1053
+ showWebcam?: boolean;
1054
+ videoObjectFit?: NonNullable<VideoHTMLAttributes<HTMLVideoElement>['style']>['objectFit'];
1055
+ /** Fires once `getUserMedia` is rejected with `NotAllowedError` or
1056
+ * `PermissionDeniedError`. */
1057
+ onPermissionDenied?: () => void;
1058
+ /** Fires after the local media has been published (video, and audio when
1059
+ * `audio` is enabled). Re-fires after a reconnect. */
1060
+ onPublished?: () => void;
1061
+ /** Fires on non-permission `getUserMedia` failures and on publish/unpublish
1062
+ * rejections. Permission denials route to `onPermissionDenied` instead. */
1063
+ onError?: (error: Error) => void;
1064
+ }
1065
+ declare function WebcamStream({ track, audio, audioTrack, className, style, videoConstraints, showWebcam, videoObjectFit, onPermissionDenied, onPublished, onError, }: WebcamStreamProps): react.JSX.Element;
1066
+
1067
+ /**
1068
+ * Video preview for a captured {@link Clip}. Streams the clip with `hls.js`
1069
+ * wherever Media Source Extensions exist — every current browser, iOS
1070
+ * Safari 17.1 and later included. `hls.js` is dynamically imported, so
1071
+ * bundlers give it a chunk of its own that an app importing this component
1072
+ * fetches on first play, and one that never renders a player drops
1073
+ * entirely. Where Media Source Extensions don't exist — iOS before 17.1 —
1074
+ * the clip is assembled into a single MP4 and played from memory instead.
1075
+ * Failures surface in an inline error overlay; the chunks remain
1076
+ * downloadable via {@link useClipDownload}/`ClipDownloadButton` either way.
1077
+ *
1078
+ * Preview only — this component doesn't render a download UI. Compose it
1079
+ * with `ClipDownloadButton`, or build a custom download surface around
1080
+ * `useClipDownload`.
1081
+ *
1082
+ * Unlike `ReactorView`/`WebcamStream`, this doesn't require a
1083
+ * `ReactorProvider` in the tree — it operates on the `Clip` value alone, so
1084
+ * it stays usable after `reactor.disconnect()` and works with clips loaded
1085
+ * from fixtures or any other source. When a `ReactorProvider` is mounted
1086
+ * above, an omitted `getJwt` inherits the provider's resolver.
1087
+ */
1088
+ interface ClipPlayerProps {
1089
+ /** The captured clip to play. Re-fetches the manifest and re-attaches the
1090
+ * player when this changes by reference. */
1091
+ clip: Clip;
1092
+ /**
1093
+ * Lazy resolver for the Coordinator JWT used on the manifest GET, called
1094
+ * at request time so token refreshes are picked up automatically.
1095
+ *
1096
+ * Required outside a `ReactorProvider` in production; optional inside one
1097
+ * (inherits the provider's resolver). Omit in local-dev mode (HttpRuntime)
1098
+ * — the manifest endpoint there is auth-free.
1099
+ */
1100
+ getJwt?: () => string | Promise<string>;
1101
+ /**
1102
+ * Opt into a bounded wait: give up polling the manifest with
1103
+ * `CLIP_NOT_READY` once `max(clip.predictedReadyAtMs, pollStart) + slackMs`
1104
+ * passes. Unset by default — the player polls indefinitely until the clip
1105
+ * is ready, stopping only when it unmounts or `clip` changes. Forwarded
1106
+ * directly to `fetchPlaylist()`'s `slackMs` option.
1107
+ */
1108
+ slackMs?: number;
1109
+ /** Play automatically once the manifest is attached. Default `true`. */
1110
+ autoPlay?: boolean;
1111
+ /** Start muted. Default `true` — browser autoplay policies block
1112
+ * audio-bearing video from playing without a user gesture; the user can
1113
+ * unmute via the native controls. */
1114
+ muted?: boolean;
1115
+ className?: string;
1116
+ style?: CSSProperties;
1117
+ /** Fires when the player enters its inline error state. A `RecordingError`
1118
+ * for manifest-fetch failures, a plain `Error` for hls.js/element playback
1119
+ * failures. */
1120
+ onError?: (error: Error) => void;
1121
+ }
1122
+ declare function ClipPlayer({ clip, getJwt, slackMs, autoPlay, muted, className, style, onError, }: ClipPlayerProps): react.JSX.Element;
1123
+
1124
+ /**
1125
+ * State machine for an in-progress clip download.
1126
+ *
1127
+ * - `idle`: no download in flight (initial state, and what the hook returns
1128
+ * to after a successful save).
1129
+ * - `downloading`: chunks are being fetched. `fetched`/`total` count the
1130
+ * chunks (init segment + media segments) — useful for a progress bar.
1131
+ * `total` is 0 until the manifest is parsed and the chunk count is known.
1132
+ * - `error`: most recent attempt failed; `message` is suitable for
1133
+ * surfacing inline. `RecordingError`s are formatted as `"<CODE>: <reason>"`.
1134
+ */
1135
+ type ClipDownloadState = {
1136
+ kind: 'idle';
1137
+ } | {
1138
+ kind: 'downloading';
1139
+ fetched: number;
1140
+ total: number;
1141
+ } | {
1142
+ kind: 'error';
1143
+ message: string;
1144
+ };
1145
+ interface UseClipDownloadOptions {
1146
+ /** Filename used when the browser save dialog opens. Pass `null` to skip
1147
+ * the `<a download>` trigger entirely — the returned Blob is still
1148
+ * resolved so the caller can `URL.createObjectURL` it or re-upload it.
1149
+ * Default `"reactor-clip.mp4"`. */
1150
+ filename?: string | null;
1151
+ /**
1152
+ * Lazy resolver for the Coordinator JWT used on the manifest GET. Called
1153
+ * on every {@link UseClipDownloadResult.download} invocation, so token
1154
+ * refreshes are picked up automatically.
1155
+ *
1156
+ * Optional inside a `ReactorProvider` (inherits the provider's resolver)
1157
+ * and in local-dev mode.
1158
+ */
1159
+ getJwt?: () => string | Promise<string>;
1160
+ }
1161
+ interface UseClipDownloadResult {
1162
+ /** Current state of the most recent download attempt. */
1163
+ state: ClipDownloadState;
1164
+ /**
1165
+ * Trigger a download. Resolves with the assembled fragmented-MP4 Blob, or
1166
+ * `undefined` if a download was already in flight (a no-op in that case)
1167
+ * or the attempt failed. Errors are surfaced via {@link state} rather than
1168
+ * a rejection — check `state.kind === "error"` to drive failure UI.
1169
+ */
1170
+ download: () => Promise<Blob | undefined>;
1171
+ /** Reset to `idle`. Does *not* cancel an in-flight download. */
1172
+ reset: () => void;
1173
+ }
1174
+ /**
1175
+ * Headless download primitive for a {@link Clip}. Wraps `downloadClipAsFile`
1176
+ * in a React state machine so the consumer can render any button they want,
1177
+ * anywhere they want, and still get progress + error feedback. Used
1178
+ * internally by `ClipDownloadButton` — reach for this hook directly when you
1179
+ * need custom placement or styling.
1180
+ *
1181
+ * `download`/`reset` are stable callback identities across renders, so
1182
+ * they're safe to pass through memoized children without forcing re-renders.
1183
+ */
1184
+ declare function useClipDownload(clip: Clip, options?: UseClipDownloadOptions): UseClipDownloadResult;
1185
+
1186
+ /**
1187
+ * Standalone download button for a captured {@link Clip}. Drops anywhere in
1188
+ * your UI — modal headers, list rows, hover menus, floating action buttons
1189
+ * — and is responsible for nothing more than triggering a download and
1190
+ * reflecting its state. Wraps `useClipDownload` internally; for completely
1191
+ * custom UIs (progress bars, menu items, post-download blob handling) call
1192
+ * that hook directly.
1193
+ *
1194
+ * Styling is intentionally minimal — override via `className`/`style`, or
1195
+ * replace the inner content with the `children` render-prop. No CSS file is
1196
+ * shipped; every default style is inline so it loses to anything the
1197
+ * consumer provides.
1198
+ */
1199
+ interface ClipDownloadButtonProps {
1200
+ /** The clip to download. */
1201
+ clip: Clip;
1202
+ /** Lazy JWT resolver. Optional inside a `ReactorProvider` (inherits the
1203
+ * provider's resolver) and in local-dev mode. See `ClipPlayerProps.getJwt`. */
1204
+ getJwt?: () => string | Promise<string>;
1205
+ /** Filename for the saved MP4. Default `"reactor-clip.mp4"`. */
1206
+ filename?: string;
1207
+ /**
1208
+ * Inner content of the button. Three forms:
1209
+ *
1210
+ * - Omitted — renders a default label that follows the state
1211
+ * (`"Download"` / `"Downloading 3/8…"` / etc.).
1212
+ * - `ReactNode` — static label, no state-driven text.
1213
+ * - `(state) => ReactNode` — state-aware render function, for custom
1214
+ * progress strings, spinners, etc.
1215
+ */
1216
+ children?: ReactNode | ((state: ClipDownloadState) => ReactNode);
1217
+ /** Forwarded to the underlying `<button>`. */
1218
+ className?: string;
1219
+ /** Forwarded to the underlying `<button>` — merges after the defaults so
1220
+ * each property overrides. */
1221
+ style?: CSSProperties;
1222
+ /** Forwarded to the underlying `<button>`. ORed with the internal
1223
+ * "downloading" state. */
1224
+ disabled?: boolean;
1225
+ /** Fires when the download completes with the assembled MP4 Blob. */
1226
+ onSuccess?: (blob: Blob) => void;
1227
+ /** Fires when the download fails. Message mirrors the in-button state —
1228
+ * `"<CODE>: <reason>"` for `RecordingError`s, the plain error message
1229
+ * otherwise. */
1230
+ onError?: (error: Error) => void;
1231
+ }
1232
+ declare function ClipDownloadButton({ clip, getJwt, filename, children, className, style, disabled, onSuccess, onError, }: ClipDownloadButtonProps): react.JSX.Element;
1233
+
1234
+ export { AbortedError, BadRequestError, type Capabilities, type Clip, ClipDownloadButton, type ClipDownloadButtonProps, type ClipDownloadState, type ClipKind, ClipPlayer, type ClipPlayerProps, type CommandCapability, ConflictError, type ConnectOptions, type ConnectionStats, type ConnectionTimings, DEFAULT_PLAYLIST_POLL_SLACK_MS, DecodeError, DisconnectedError, type DownloadClipOptions, type FetchPlaylistOptions, FileRef, InvalidStateError, type JwtResolver, type JwtSource, type MessageScope, MessageTooLargeError, type ModelSchema, type ModelSchemaOperation, type ModelSchemaPathItem, type ModerationAction, type ModerationEvent, NetworkError, NotFoundError, RateLimitedError, Reactor, type ReactorActions, type ReactorConnectOptions, ReactorError, type ReactorEventMap, type ReactorEventName, type ReactorMessage, type ReactorOptions, ReactorProvider, type ReactorProviderProps, type ReactorState, type ReactorStatus, type ReactorStore, ReactorView, type ReactorViewProps, RecorderDisabledError, RecordingError, RequestTimeoutError, ServerError, type SessionResponse, SessionTerminalError, type TrackCapability, type TrackDirection, type TrackKind, type TrackMappingEntry, TransportError, UnauthorizedError, type UseClipDownloadOptions, type UseClipDownloadResult, VersionMismatchError, WebcamStream, type WebcamStreamProps, createPlayableManifestUrl, downloadClipAsFile, fetchPlaylist, isFileRef, normalizeJwtSource, parsePlaylist, useClipDownload, useReactor, useReactorInternalMessage, useReactorMessage, useStats };