@reactor-team/js-sdk 2.12.3 → 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/README.md +209 -172
- package/dist/index.cjs +2478 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +1234 -0
- package/dist/index.d.ts +952 -1076
- package/dist/index.js +1707 -4111
- package/dist/index.js.map +1 -1
- package/dist/wasm/README.md +151 -0
- package/dist/wasm/package.json +21 -0
- package/dist/wasm/reactor_wasm.d.ts +422 -0
- package/dist/wasm/reactor_wasm.js +1428 -0
- package/dist/wasm/reactor_wasm_bg.wasm +0 -0
- package/dist/wasm/reactor_wasm_bg.wasm.d.ts +53 -0
- package/package.json +36 -60
- package/LICENSE +0 -201
- package/NOTICE +0 -5
- package/dist/index.d.mts +0 -1358
- package/dist/index.mjs +0 -4750
- package/dist/index.mjs.map +0 -1
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,2478 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
"use strict";
|
|
3
|
+
var __create = Object.create;
|
|
4
|
+
var __defProp = Object.defineProperty;
|
|
5
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
6
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
7
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
8
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
9
|
+
var __export = (target, all) => {
|
|
10
|
+
for (var name in all)
|
|
11
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
12
|
+
};
|
|
13
|
+
var __copyProps = (to, from, except, desc) => {
|
|
14
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
15
|
+
for (let key of __getOwnPropNames(from))
|
|
16
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
17
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
18
|
+
}
|
|
19
|
+
return to;
|
|
20
|
+
};
|
|
21
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
22
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
23
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
24
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
25
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
26
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
27
|
+
mod
|
|
28
|
+
));
|
|
29
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
30
|
+
|
|
31
|
+
// src/index.ts
|
|
32
|
+
var index_exports = {};
|
|
33
|
+
__export(index_exports, {
|
|
34
|
+
AbortedError: () => AbortedError,
|
|
35
|
+
BadRequestError: () => BadRequestError,
|
|
36
|
+
ClipDownloadButton: () => ClipDownloadButton,
|
|
37
|
+
ClipPlayer: () => ClipPlayer,
|
|
38
|
+
ConflictError: () => ConflictError,
|
|
39
|
+
DEFAULT_PLAYLIST_POLL_SLACK_MS: () => DEFAULT_PLAYLIST_POLL_SLACK_MS,
|
|
40
|
+
DecodeError: () => DecodeError,
|
|
41
|
+
DisconnectedError: () => DisconnectedError,
|
|
42
|
+
FileRef: () => FileRef,
|
|
43
|
+
InvalidStateError: () => InvalidStateError,
|
|
44
|
+
MessageTooLargeError: () => MessageTooLargeError,
|
|
45
|
+
NetworkError: () => NetworkError,
|
|
46
|
+
NotFoundError: () => NotFoundError,
|
|
47
|
+
RateLimitedError: () => RateLimitedError,
|
|
48
|
+
Reactor: () => Reactor,
|
|
49
|
+
ReactorError: () => ReactorError,
|
|
50
|
+
ReactorProvider: () => ReactorProvider,
|
|
51
|
+
ReactorView: () => ReactorView,
|
|
52
|
+
RecorderDisabledError: () => RecorderDisabledError,
|
|
53
|
+
RecordingError: () => RecordingError,
|
|
54
|
+
RequestTimeoutError: () => RequestTimeoutError,
|
|
55
|
+
ServerError: () => ServerError,
|
|
56
|
+
SessionTerminalError: () => SessionTerminalError,
|
|
57
|
+
TransportError: () => TransportError,
|
|
58
|
+
UnauthorizedError: () => UnauthorizedError,
|
|
59
|
+
VersionMismatchError: () => VersionMismatchError,
|
|
60
|
+
WebcamStream: () => WebcamStream,
|
|
61
|
+
createPlayableManifestUrl: () => createPlayableManifestUrl,
|
|
62
|
+
downloadClipAsFile: () => downloadClipAsFile,
|
|
63
|
+
fetchPlaylist: () => fetchPlaylist,
|
|
64
|
+
isFileRef: () => isFileRef,
|
|
65
|
+
normalizeJwtSource: () => normalizeJwtSource,
|
|
66
|
+
parsePlaylist: () => parsePlaylist,
|
|
67
|
+
useClipDownload: () => useClipDownload,
|
|
68
|
+
useReactor: () => useReactor,
|
|
69
|
+
useReactorInternalMessage: () => useReactorInternalMessage,
|
|
70
|
+
useReactorMessage: () => useReactorMessage,
|
|
71
|
+
useStats: () => useStats
|
|
72
|
+
});
|
|
73
|
+
module.exports = __toCommonJS(index_exports);
|
|
74
|
+
|
|
75
|
+
// src/reactor.ts
|
|
76
|
+
var import_awaitqueue = require("awaitqueue");
|
|
77
|
+
|
|
78
|
+
// src/internal/capabilities.ts
|
|
79
|
+
function toPublicCapabilities(wire) {
|
|
80
|
+
const capabilities = {
|
|
81
|
+
protocolVersion: wire.protocol_version,
|
|
82
|
+
tracks: wire.tracks
|
|
83
|
+
};
|
|
84
|
+
if (wire.commands !== void 0) {
|
|
85
|
+
capabilities.commands = wire.commands;
|
|
86
|
+
}
|
|
87
|
+
if (wire.emission_fps !== void 0) {
|
|
88
|
+
capabilities.emissionFps = wire.emission_fps;
|
|
89
|
+
}
|
|
90
|
+
return capabilities;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// src/internal/debug-log.ts
|
|
94
|
+
var import_meta = {};
|
|
95
|
+
var isDev = typeof process !== "undefined" && process?.env?.NODE_ENV === "development" || import_meta.env?.DEV === true;
|
|
96
|
+
function debugLog(...args) {
|
|
97
|
+
if (isDev) {
|
|
98
|
+
console.debug(...args);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// src/errors.ts
|
|
103
|
+
var ReactorError = class extends Error {
|
|
104
|
+
/** The code this class stands for. `ReactorError` itself is the fallback,
|
|
105
|
+
* so it claims none and takes whatever the payload reported. */
|
|
106
|
+
static code = "INTERNAL_ERROR";
|
|
107
|
+
/** `reactor-core`'s own canonical code for this failure — the same value
|
|
108
|
+
* used to pick this instance's class (see the typed subclasses below for
|
|
109
|
+
* the vocabulary). Open-ended: an unrecognized code still constructs the
|
|
110
|
+
* base class, with `code` set to whatever was reported. */
|
|
111
|
+
code;
|
|
112
|
+
/** Whether the same call could succeed later. */
|
|
113
|
+
recoverable;
|
|
114
|
+
/** The HTTP status, when the failure came from one. */
|
|
115
|
+
status;
|
|
116
|
+
/** Which call failed, e.g. "connect", "sendCommand". */
|
|
117
|
+
operation;
|
|
118
|
+
/** Backoff hint the platform sent. */
|
|
119
|
+
retry_after_ms;
|
|
120
|
+
/** When `reactor-core` reported this failure. For a purely local one (no
|
|
121
|
+
* payload at all — see {@link ReactorErrorOptions}), this is synthesized
|
|
122
|
+
* as the construction time instead, since there's nothing to report —
|
|
123
|
+
* not a value read off the wire. */
|
|
124
|
+
timestamp_ms;
|
|
125
|
+
/** Same value as `retry_after_ms`, under its previous name. Kept for
|
|
126
|
+
* compatibility — prefer `retry_after_ms`. */
|
|
127
|
+
retryAfter;
|
|
128
|
+
/** Same value as `timestamp_ms`, under its previous name. Kept for
|
|
129
|
+
* compatibility — prefer `timestamp_ms`. */
|
|
130
|
+
timestamp;
|
|
131
|
+
constructor(message, options = {}) {
|
|
132
|
+
super(message);
|
|
133
|
+
this.name = "ReactorError";
|
|
134
|
+
this.code = options.code ?? new.target.code;
|
|
135
|
+
this.recoverable = options.recoverable ?? false;
|
|
136
|
+
this.status = options.status;
|
|
137
|
+
this.operation = options.operation;
|
|
138
|
+
this.retry_after_ms = options.retry_after_ms;
|
|
139
|
+
this.retryAfter = options.retry_after_ms;
|
|
140
|
+
this.timestamp_ms = options.timestamp_ms ?? Date.now();
|
|
141
|
+
this.timestamp = this.timestamp_ms;
|
|
142
|
+
}
|
|
143
|
+
};
|
|
144
|
+
var NetworkError = class extends ReactorError {
|
|
145
|
+
static code = "NETWORK_ERROR";
|
|
146
|
+
};
|
|
147
|
+
var UnauthorizedError = class extends ReactorError {
|
|
148
|
+
static code = "UNAUTHORIZED";
|
|
149
|
+
};
|
|
150
|
+
var NotFoundError = class extends ReactorError {
|
|
151
|
+
static code = "NOT_FOUND";
|
|
152
|
+
};
|
|
153
|
+
var ConflictError = class extends ReactorError {
|
|
154
|
+
static code = "CONFLICT";
|
|
155
|
+
};
|
|
156
|
+
var RateLimitedError = class extends ReactorError {
|
|
157
|
+
static code = "RATE_LIMITED";
|
|
158
|
+
};
|
|
159
|
+
var BadRequestError = class extends ReactorError {
|
|
160
|
+
static code = "BAD_REQUEST";
|
|
161
|
+
};
|
|
162
|
+
var ServerError = class extends ReactorError {
|
|
163
|
+
static code = "SERVER_ERROR";
|
|
164
|
+
};
|
|
165
|
+
var VersionMismatchError = class extends ReactorError {
|
|
166
|
+
static code = "VERSION_MISMATCH";
|
|
167
|
+
};
|
|
168
|
+
var DecodeError = class extends ReactorError {
|
|
169
|
+
static code = "DECODE_FAILED";
|
|
170
|
+
};
|
|
171
|
+
var InvalidStateError = class extends ReactorError {
|
|
172
|
+
static code = "INVALID_STATE";
|
|
173
|
+
};
|
|
174
|
+
var SessionTerminalError = class extends ReactorError {
|
|
175
|
+
static code = "SESSION_TERMINAL";
|
|
176
|
+
};
|
|
177
|
+
var MessageTooLargeError = class extends ReactorError {
|
|
178
|
+
static code = "MESSAGE_TOO_LARGE";
|
|
179
|
+
};
|
|
180
|
+
var TransportError = class extends ReactorError {
|
|
181
|
+
static code = "TRANSPORT_ERROR";
|
|
182
|
+
};
|
|
183
|
+
var DisconnectedError = class extends ReactorError {
|
|
184
|
+
static code = "DISCONNECTED";
|
|
185
|
+
};
|
|
186
|
+
var RequestTimeoutError = class extends ReactorError {
|
|
187
|
+
static code = "REQUEST_TIMEOUT";
|
|
188
|
+
};
|
|
189
|
+
var AbortedError = class extends ReactorError {
|
|
190
|
+
static code = "ABORTED";
|
|
191
|
+
};
|
|
192
|
+
var RecorderDisabledError = class extends ReactorError {
|
|
193
|
+
static code = "RECORDER_DISABLED";
|
|
194
|
+
};
|
|
195
|
+
var ERROR_CLASSES = [
|
|
196
|
+
NetworkError,
|
|
197
|
+
UnauthorizedError,
|
|
198
|
+
NotFoundError,
|
|
199
|
+
ConflictError,
|
|
200
|
+
RateLimitedError,
|
|
201
|
+
BadRequestError,
|
|
202
|
+
ServerError,
|
|
203
|
+
VersionMismatchError,
|
|
204
|
+
DecodeError,
|
|
205
|
+
InvalidStateError,
|
|
206
|
+
SessionTerminalError,
|
|
207
|
+
MessageTooLargeError,
|
|
208
|
+
TransportError,
|
|
209
|
+
DisconnectedError,
|
|
210
|
+
RequestTimeoutError,
|
|
211
|
+
AbortedError,
|
|
212
|
+
RecorderDisabledError
|
|
213
|
+
];
|
|
214
|
+
var BY_CODE = new Map(
|
|
215
|
+
ERROR_CLASSES.map((errorClass) => [errorClass.code, errorClass])
|
|
216
|
+
);
|
|
217
|
+
function errorForCode(code) {
|
|
218
|
+
return code && BY_CODE.get(code) || ReactorError;
|
|
219
|
+
}
|
|
220
|
+
function toReactorError(cause) {
|
|
221
|
+
if (cause instanceof ReactorError) {
|
|
222
|
+
return cause;
|
|
223
|
+
}
|
|
224
|
+
const payload = cause ?? {};
|
|
225
|
+
const message = typeof payload.message === "string" ? payload.message : String(cause);
|
|
226
|
+
const ErrorClass = errorForCode(payload.code);
|
|
227
|
+
return new ErrorClass(message, {
|
|
228
|
+
code: payload.code,
|
|
229
|
+
recoverable: payload.recoverable,
|
|
230
|
+
status: payload.status,
|
|
231
|
+
operation: payload.operation,
|
|
232
|
+
retry_after_ms: payload.retry_after_ms,
|
|
233
|
+
timestamp_ms: payload.timestamp_ms
|
|
234
|
+
});
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
// src/internal/emitter.ts
|
|
238
|
+
var Emitter = class {
|
|
239
|
+
listeners = /* @__PURE__ */ new Map();
|
|
240
|
+
on(event, handler) {
|
|
241
|
+
let handlers = this.listeners.get(event);
|
|
242
|
+
if (!handlers) {
|
|
243
|
+
handlers = /* @__PURE__ */ new Set();
|
|
244
|
+
this.listeners.set(event, handlers);
|
|
245
|
+
}
|
|
246
|
+
handlers.add(handler);
|
|
247
|
+
}
|
|
248
|
+
off(event, handler) {
|
|
249
|
+
this.listeners.get(event)?.delete(handler);
|
|
250
|
+
}
|
|
251
|
+
once(event, handler) {
|
|
252
|
+
const wrapped = ((...args) => {
|
|
253
|
+
this.off(event, wrapped);
|
|
254
|
+
handler(...args);
|
|
255
|
+
});
|
|
256
|
+
this.on(event, wrapped);
|
|
257
|
+
}
|
|
258
|
+
emit(event, ...args) {
|
|
259
|
+
const handlers = this.listeners.get(event);
|
|
260
|
+
if (!handlers) {
|
|
261
|
+
return;
|
|
262
|
+
}
|
|
263
|
+
for (const handler of [...handlers]) {
|
|
264
|
+
try {
|
|
265
|
+
handler(...args);
|
|
266
|
+
} catch (error) {
|
|
267
|
+
console.error(`[Emitter] handler for "${String(event)}" threw:`, error);
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
/** Drops every registered handler for every event. */
|
|
272
|
+
clear() {
|
|
273
|
+
this.listeners.clear();
|
|
274
|
+
}
|
|
275
|
+
};
|
|
276
|
+
|
|
277
|
+
// src/file-ref.ts
|
|
278
|
+
var FileRef = class {
|
|
279
|
+
constructor(uploadId, name, mimeType, size) {
|
|
280
|
+
this.uploadId = uploadId;
|
|
281
|
+
this.name = name;
|
|
282
|
+
this.mimeType = mimeType;
|
|
283
|
+
this.size = size;
|
|
284
|
+
}
|
|
285
|
+
uploadId;
|
|
286
|
+
name;
|
|
287
|
+
mimeType;
|
|
288
|
+
size;
|
|
289
|
+
};
|
|
290
|
+
function isFileRef(value) {
|
|
291
|
+
if (value instanceof FileRef) {
|
|
292
|
+
return true;
|
|
293
|
+
}
|
|
294
|
+
if (typeof value !== "object" || value === null) {
|
|
295
|
+
return false;
|
|
296
|
+
}
|
|
297
|
+
const candidate = value;
|
|
298
|
+
return typeof candidate.uploadId === "string" && typeof candidate.name === "string" && typeof candidate.mimeType === "string" && typeof candidate.size === "number";
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
// src/internal/file-ref.ts
|
|
302
|
+
function toWireFileRef(fileRef) {
|
|
303
|
+
return {
|
|
304
|
+
upload_id: fileRef.uploadId,
|
|
305
|
+
name: fileRef.name,
|
|
306
|
+
mime_type: fileRef.mimeType,
|
|
307
|
+
size: fileRef.size
|
|
308
|
+
};
|
|
309
|
+
}
|
|
310
|
+
function toPublicFileRef(fileRef) {
|
|
311
|
+
return new FileRef(fileRef.upload_id, fileRef.name, fileRef.mime_type, fileRef.size);
|
|
312
|
+
}
|
|
313
|
+
function extractFileRefs(data) {
|
|
314
|
+
if (!data) {
|
|
315
|
+
return { data, uploads: void 0 };
|
|
316
|
+
}
|
|
317
|
+
let uploads;
|
|
318
|
+
let scalars;
|
|
319
|
+
for (const [key, value] of Object.entries(data)) {
|
|
320
|
+
if (!isFileRef(value)) {
|
|
321
|
+
continue;
|
|
322
|
+
}
|
|
323
|
+
uploads ??= {};
|
|
324
|
+
scalars ??= { ...data };
|
|
325
|
+
uploads[key] = toWireFileRef(value);
|
|
326
|
+
delete scalars[key];
|
|
327
|
+
}
|
|
328
|
+
return { data: scalars ?? data, uploads };
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
// src/internal/recording.ts
|
|
332
|
+
function toPublicClip(clip) {
|
|
333
|
+
return {
|
|
334
|
+
sessionId: clip.session_id,
|
|
335
|
+
kind: clip.kind,
|
|
336
|
+
startMarker: clip.start_marker,
|
|
337
|
+
endMarker: clip.end_marker,
|
|
338
|
+
nowMarker: clip.now_marker,
|
|
339
|
+
predictedReadyAtMs: clip.predicted_ready_at_ms,
|
|
340
|
+
playlistUrl: clip.playlist_url
|
|
341
|
+
};
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
// src/internal/stats.ts
|
|
345
|
+
var STATS_INTERVAL_MS = 2e3;
|
|
346
|
+
function createRTCStatsExtractor() {
|
|
347
|
+
let lastBytesReceived;
|
|
348
|
+
let lastBytesSent;
|
|
349
|
+
let lastCandPairTimestamp;
|
|
350
|
+
let lastCandPairId;
|
|
351
|
+
return (report) => {
|
|
352
|
+
let candPairId;
|
|
353
|
+
let rtt;
|
|
354
|
+
let availableOutgoingBitrate;
|
|
355
|
+
let availableIncomingBitrate;
|
|
356
|
+
let incomingBitrate;
|
|
357
|
+
let outgoingBitrate;
|
|
358
|
+
let videoInboundRtpId;
|
|
359
|
+
let framesPerSecond;
|
|
360
|
+
let jitter;
|
|
361
|
+
let packetLossRatio;
|
|
362
|
+
let candidateType;
|
|
363
|
+
const reportWithLookup = report;
|
|
364
|
+
report.forEach((stat) => {
|
|
365
|
+
if (candPairId === void 0 && stat.type === "candidate-pair" && stat.state === "succeeded" && stat.nominated) {
|
|
366
|
+
candPairId = stat.id;
|
|
367
|
+
if (stat.currentRoundTripTime !== void 0) {
|
|
368
|
+
rtt = stat.currentRoundTripTime * 1e3;
|
|
369
|
+
}
|
|
370
|
+
if (stat.availableOutgoingBitrate !== void 0) {
|
|
371
|
+
availableOutgoingBitrate = stat.availableOutgoingBitrate;
|
|
372
|
+
}
|
|
373
|
+
if (stat.availableIncomingBitrate !== void 0) {
|
|
374
|
+
availableIncomingBitrate = stat.availableIncomingBitrate;
|
|
375
|
+
}
|
|
376
|
+
const localCandidate = stat.localCandidateId !== void 0 ? reportWithLookup.get(stat.localCandidateId) : void 0;
|
|
377
|
+
if (localCandidate?.candidateType) {
|
|
378
|
+
candidateType = localCandidate.candidateType;
|
|
379
|
+
}
|
|
380
|
+
const samePair = lastCandPairId === candPairId;
|
|
381
|
+
const timeDiff = samePair && lastCandPairTimestamp !== void 0 ? stat.timestamp - lastCandPairTimestamp : 0;
|
|
382
|
+
if (stat.bytesReceived !== void 0) {
|
|
383
|
+
if (samePair && lastBytesReceived !== void 0 && timeDiff > 0) {
|
|
384
|
+
incomingBitrate = (stat.bytesReceived - lastBytesReceived) * 8 / timeDiff * 1e3;
|
|
385
|
+
}
|
|
386
|
+
lastBytesReceived = stat.bytesReceived;
|
|
387
|
+
}
|
|
388
|
+
if (stat.bytesSent !== void 0) {
|
|
389
|
+
if (samePair && lastBytesSent !== void 0 && timeDiff > 0) {
|
|
390
|
+
outgoingBitrate = (stat.bytesSent - lastBytesSent) * 8 / timeDiff * 1e3;
|
|
391
|
+
}
|
|
392
|
+
lastBytesSent = stat.bytesSent;
|
|
393
|
+
}
|
|
394
|
+
lastCandPairTimestamp = stat.timestamp;
|
|
395
|
+
lastCandPairId = candPairId;
|
|
396
|
+
}
|
|
397
|
+
if (videoInboundRtpId === void 0 && stat.type === "inbound-rtp" && stat.kind === "video") {
|
|
398
|
+
videoInboundRtpId = stat.id;
|
|
399
|
+
if (stat.framesPerSecond !== void 0) {
|
|
400
|
+
framesPerSecond = stat.framesPerSecond;
|
|
401
|
+
}
|
|
402
|
+
if (stat.jitter !== void 0) {
|
|
403
|
+
jitter = stat.jitter;
|
|
404
|
+
}
|
|
405
|
+
if (stat.packetsReceived !== void 0 && stat.packetsLost !== void 0 && stat.packetsReceived + stat.packetsLost > 0) {
|
|
406
|
+
packetLossRatio = stat.packetsLost / (stat.packetsReceived + stat.packetsLost);
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
});
|
|
410
|
+
return {
|
|
411
|
+
rtt,
|
|
412
|
+
candidateType,
|
|
413
|
+
availableIncomingBitrate,
|
|
414
|
+
availableOutgoingBitrate,
|
|
415
|
+
incomingBitrate,
|
|
416
|
+
outgoingBitrate,
|
|
417
|
+
framesPerSecond,
|
|
418
|
+
packetLossRatio,
|
|
419
|
+
jitter,
|
|
420
|
+
timestamp: Date.now()
|
|
421
|
+
};
|
|
422
|
+
};
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
// src/internal/wasm.ts
|
|
426
|
+
var modulePromise = null;
|
|
427
|
+
function loadReactorWasm() {
|
|
428
|
+
if (!modulePromise) {
|
|
429
|
+
modulePromise = importWasmModule().catch((cause) => {
|
|
430
|
+
modulePromise = null;
|
|
431
|
+
throw new Error(
|
|
432
|
+
"reactor-wasm failed to load. Run `mise run build:wasm` (or, from a published install, reinstall the package) and try again.",
|
|
433
|
+
{ cause }
|
|
434
|
+
);
|
|
435
|
+
});
|
|
436
|
+
}
|
|
437
|
+
return modulePromise;
|
|
438
|
+
}
|
|
439
|
+
async function importWasmModule() {
|
|
440
|
+
const module2 = await import(
|
|
441
|
+
/* @vite-ignore */
|
|
442
|
+
"./wasm/reactor_wasm.js"
|
|
443
|
+
);
|
|
444
|
+
await module2.default();
|
|
445
|
+
return module2;
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
// src/recording.ts
|
|
449
|
+
var RecordingError = class extends Error {
|
|
450
|
+
constructor(code, reason) {
|
|
451
|
+
super(`${code}: ${reason}`);
|
|
452
|
+
this.code = code;
|
|
453
|
+
this.reason = reason;
|
|
454
|
+
this.name = "RecordingError";
|
|
455
|
+
}
|
|
456
|
+
code;
|
|
457
|
+
reason;
|
|
458
|
+
};
|
|
459
|
+
var DEFAULT_PLAYLIST_POLL_SLACK_MS = 15e3;
|
|
460
|
+
async function fetchPlaylist(playlistUrl, options = {}) {
|
|
461
|
+
const minDelay = Math.max(0, options.minRetryDelayMs ?? 200);
|
|
462
|
+
const maxDelay = Math.max(minDelay, options.maxRetryDelayMs ?? 2e3);
|
|
463
|
+
const hasDeadline = typeof options.slackMs === "number" && Number.isFinite(options.slackMs);
|
|
464
|
+
const startedPollingAt = Date.now();
|
|
465
|
+
const deadlineMs = hasDeadline ? Math.max(options.predictedReadyAtMs ?? startedPollingAt, startedPollingAt) + options.slackMs : void 0;
|
|
466
|
+
const maxRetries = typeof options.maxRetries === "number" ? options.maxRetries : void 0;
|
|
467
|
+
const init = {};
|
|
468
|
+
if (options.signal) {
|
|
469
|
+
init.signal = options.signal;
|
|
470
|
+
}
|
|
471
|
+
if (options.jwt) {
|
|
472
|
+
init.headers = { Authorization: `Bearer ${options.jwt}` };
|
|
473
|
+
}
|
|
474
|
+
let attempt = 0;
|
|
475
|
+
while (true) {
|
|
476
|
+
let response;
|
|
477
|
+
try {
|
|
478
|
+
response = await fetch(playlistUrl, init);
|
|
479
|
+
} catch (error) {
|
|
480
|
+
if (isAbortError(error)) {
|
|
481
|
+
throw error;
|
|
482
|
+
}
|
|
483
|
+
throw new RecordingError(
|
|
484
|
+
"PLAYLIST_FETCH_FAILED",
|
|
485
|
+
`Network error fetching playlist: ${error.message}`
|
|
486
|
+
);
|
|
487
|
+
}
|
|
488
|
+
if (response.status === 202) {
|
|
489
|
+
if (deadlineMs !== void 0 && Date.now() >= deadlineMs) {
|
|
490
|
+
throw new RecordingError(
|
|
491
|
+
"CLIP_NOT_READY",
|
|
492
|
+
`Boundary chunk still pending after ${options.slackMs}ms grace (predicted ready ${new Date(
|
|
493
|
+
options.predictedReadyAtMs ?? startedPollingAt
|
|
494
|
+
).toISOString()}). Runtime may have crashed mid-clip.`
|
|
495
|
+
);
|
|
496
|
+
}
|
|
497
|
+
if (maxRetries !== void 0 && attempt >= maxRetries) {
|
|
498
|
+
throw new RecordingError(
|
|
499
|
+
"CLIP_NOT_READY",
|
|
500
|
+
`Manifest still pending after ${attempt + 1} attempts (last status 202)`
|
|
501
|
+
);
|
|
502
|
+
}
|
|
503
|
+
const headerDelay = parseRetryAfter(response.headers.get("Retry-After"), minDelay);
|
|
504
|
+
const delay = Math.min(maxDelay, Math.max(minDelay, headerDelay));
|
|
505
|
+
const clampedDelay = deadlineMs !== void 0 ? Math.min(delay, Math.max(0, deadlineMs - Date.now())) : delay;
|
|
506
|
+
await sleep(clampedDelay, options.signal);
|
|
507
|
+
attempt++;
|
|
508
|
+
continue;
|
|
509
|
+
}
|
|
510
|
+
if (response.status === 200) {
|
|
511
|
+
return await response.text();
|
|
512
|
+
}
|
|
513
|
+
if (response.status === 410 || response.status === 404) {
|
|
514
|
+
throw new RecordingError("CLIP_GONE", "Clip is no longer available or session unknown");
|
|
515
|
+
}
|
|
516
|
+
throw new RecordingError("PLAYLIST_FETCH_FAILED", `Manifest endpoint returned HTTP ${response.status}`);
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
function parsePlaylist(manifestBody, playlistUrl) {
|
|
520
|
+
let initUrl;
|
|
521
|
+
const segments = [];
|
|
522
|
+
for (const rawLine of manifestBody.split(/\r?\n/)) {
|
|
523
|
+
const trimmed = rawLine.trim();
|
|
524
|
+
if (!trimmed) {
|
|
525
|
+
continue;
|
|
526
|
+
}
|
|
527
|
+
if (trimmed.startsWith("#EXT-X-MAP")) {
|
|
528
|
+
const match = trimmed.match(/URI="([^"]+)"/);
|
|
529
|
+
if (match?.[1]) {
|
|
530
|
+
initUrl = resolveAgainst(match[1], playlistUrl);
|
|
531
|
+
}
|
|
532
|
+
continue;
|
|
533
|
+
}
|
|
534
|
+
if (trimmed.startsWith("#")) {
|
|
535
|
+
continue;
|
|
536
|
+
}
|
|
537
|
+
segments.push(resolveAgainst(trimmed, playlistUrl));
|
|
538
|
+
}
|
|
539
|
+
if (!initUrl) {
|
|
540
|
+
throw new RecordingError("INVALID_PLAYLIST", "Playlist is missing an #EXT-X-MAP init segment URI");
|
|
541
|
+
}
|
|
542
|
+
if (segments.length === 0) {
|
|
543
|
+
throw new RecordingError("INVALID_PLAYLIST", "Playlist contains no media segments");
|
|
544
|
+
}
|
|
545
|
+
return { initUrl, segmentUrls: segments };
|
|
546
|
+
}
|
|
547
|
+
function createPlayableManifestUrl(manifestBody, playlistUrl) {
|
|
548
|
+
if (typeof Blob === "undefined" || typeof URL === "undefined" || typeof URL.createObjectURL !== "function") {
|
|
549
|
+
throw new RecordingError(
|
|
550
|
+
"INVALID_PLAYLIST",
|
|
551
|
+
"createPlayableManifestUrl requires a browser environment with URL.createObjectURL"
|
|
552
|
+
);
|
|
553
|
+
}
|
|
554
|
+
const rewritten = absolutizeManifestUrls(manifestBody, playlistUrl);
|
|
555
|
+
const blob = new Blob([rewritten], { type: "application/vnd.apple.mpegurl" });
|
|
556
|
+
return URL.createObjectURL(blob);
|
|
557
|
+
}
|
|
558
|
+
function absolutizeManifestUrls(manifestBody, playlistUrl) {
|
|
559
|
+
const eol = manifestBody.includes("\r\n") ? "\r\n" : "\n";
|
|
560
|
+
const out = [];
|
|
561
|
+
for (const line of manifestBody.split(/\r?\n/)) {
|
|
562
|
+
if (line.startsWith("#EXT-X-MAP")) {
|
|
563
|
+
out.push(
|
|
564
|
+
line.replace(/URI="([^"]+)"/, (_, uri) => `URI="${resolveAgainst(uri, playlistUrl)}"`)
|
|
565
|
+
);
|
|
566
|
+
continue;
|
|
567
|
+
}
|
|
568
|
+
const trimmed = line.trim();
|
|
569
|
+
if (!trimmed || trimmed.startsWith("#")) {
|
|
570
|
+
out.push(line);
|
|
571
|
+
continue;
|
|
572
|
+
}
|
|
573
|
+
out.push(resolveAgainst(trimmed, playlistUrl));
|
|
574
|
+
}
|
|
575
|
+
return out.join(eol);
|
|
576
|
+
}
|
|
577
|
+
async function downloadClipAsFile(clip, filename = "reactor-clip.mp4", options = {}) {
|
|
578
|
+
const playlistOptions = { predictedReadyAtMs: clip.predictedReadyAtMs };
|
|
579
|
+
if (options.signal) {
|
|
580
|
+
playlistOptions.signal = options.signal;
|
|
581
|
+
}
|
|
582
|
+
if (options.jwt) {
|
|
583
|
+
playlistOptions.jwt = options.jwt;
|
|
584
|
+
}
|
|
585
|
+
const manifestBody = await fetchPlaylist(clip.playlistUrl, playlistOptions);
|
|
586
|
+
const blob = await assembleClipBlob(manifestBody, clip.playlistUrl, options);
|
|
587
|
+
if (filename === null) {
|
|
588
|
+
return blob;
|
|
589
|
+
}
|
|
590
|
+
if (typeof document === "undefined" || typeof URL.createObjectURL !== "function") {
|
|
591
|
+
throw new RecordingError(
|
|
592
|
+
"DOWNLOAD_UNSUPPORTED",
|
|
593
|
+
"downloadClipAsFile requires a DOM environment; pass filename=null to skip the download trigger"
|
|
594
|
+
);
|
|
595
|
+
}
|
|
596
|
+
triggerBrowserDownload(blob, filename);
|
|
597
|
+
return blob;
|
|
598
|
+
}
|
|
599
|
+
async function assembleClipBlob(manifestBody, playlistUrl, options = {}) {
|
|
600
|
+
const { initUrl, segmentUrls } = parsePlaylist(manifestBody, playlistUrl);
|
|
601
|
+
const orderedUrls = [initUrl, ...segmentUrls];
|
|
602
|
+
const chunkInit = {};
|
|
603
|
+
if (options.signal) {
|
|
604
|
+
chunkInit.signal = options.signal;
|
|
605
|
+
}
|
|
606
|
+
const parts = [];
|
|
607
|
+
let bytes = 0;
|
|
608
|
+
for (const [i, url] of orderedUrls.entries()) {
|
|
609
|
+
let response;
|
|
610
|
+
try {
|
|
611
|
+
response = await fetch(url, chunkInit);
|
|
612
|
+
} catch (error) {
|
|
613
|
+
if (isAbortError(error)) {
|
|
614
|
+
throw error;
|
|
615
|
+
}
|
|
616
|
+
throw new RecordingError("CHUNK_FETCH_FAILED", `Network error fetching chunk ${i}: ${error.message}`);
|
|
617
|
+
}
|
|
618
|
+
if (!response.ok) {
|
|
619
|
+
throw new RecordingError("CHUNK_FETCH_FAILED", `Chunk ${i} returned HTTP ${response.status}`);
|
|
620
|
+
}
|
|
621
|
+
const data = new Uint8Array(await response.arrayBuffer());
|
|
622
|
+
parts.push(data);
|
|
623
|
+
bytes += data.byteLength;
|
|
624
|
+
options.onProgress?.({ fetched: i + 1, total: orderedUrls.length, bytes });
|
|
625
|
+
}
|
|
626
|
+
const finalBytes = await maybeRemux(parts);
|
|
627
|
+
return new Blob([finalBytes], { type: "video/mp4" });
|
|
628
|
+
}
|
|
629
|
+
async function maybeRemux(parts) {
|
|
630
|
+
const input = concatUint8Arrays(parts);
|
|
631
|
+
try {
|
|
632
|
+
const MP4Box = await loadMp4Box();
|
|
633
|
+
return await remuxFragmentedToFlat(input, MP4Box);
|
|
634
|
+
} catch (error) {
|
|
635
|
+
console.warn("[Reactor] Clip remux failed, returning fragmented MP4 instead.", error);
|
|
636
|
+
return input;
|
|
637
|
+
}
|
|
638
|
+
}
|
|
639
|
+
var __remuxInternals = {
|
|
640
|
+
loadMp4Box: () => import("mp4box")
|
|
641
|
+
};
|
|
642
|
+
function loadMp4Box() {
|
|
643
|
+
return __remuxInternals.loadMp4Box();
|
|
644
|
+
}
|
|
645
|
+
async function remuxFragmentedToFlat(input, MP4Box) {
|
|
646
|
+
return new Promise((resolve, reject) => {
|
|
647
|
+
const inFile = MP4Box.createFile();
|
|
648
|
+
const outFile = MP4Box.createFile();
|
|
649
|
+
outFile.init({ brands: ["isom", "mp42", "avc1", "iso2"] });
|
|
650
|
+
const pendingTracks = /* @__PURE__ */ new Map();
|
|
651
|
+
let settled = false;
|
|
652
|
+
const fail = (err) => {
|
|
653
|
+
if (settled) {
|
|
654
|
+
return;
|
|
655
|
+
}
|
|
656
|
+
settled = true;
|
|
657
|
+
reject(err);
|
|
658
|
+
};
|
|
659
|
+
inFile.onError = (_module, message) => {
|
|
660
|
+
fail(new Error(message));
|
|
661
|
+
};
|
|
662
|
+
inFile.onReady = (info) => {
|
|
663
|
+
if (!info.tracks.length) {
|
|
664
|
+
fail(new Error("no tracks in input"));
|
|
665
|
+
return;
|
|
666
|
+
}
|
|
667
|
+
for (const track of info.tracks) {
|
|
668
|
+
inFile.setExtractionOptions(track.id, null, { nbSamples: 1e3 });
|
|
669
|
+
}
|
|
670
|
+
inFile.start();
|
|
671
|
+
};
|
|
672
|
+
inFile.onSamples = (id, _user, samples) => {
|
|
673
|
+
if (settled || samples.length === 0) {
|
|
674
|
+
return;
|
|
675
|
+
}
|
|
676
|
+
let pending = pendingTracks.get(id);
|
|
677
|
+
if (!pending) {
|
|
678
|
+
const firstSample = samples[0];
|
|
679
|
+
if (!firstSample) {
|
|
680
|
+
return;
|
|
681
|
+
}
|
|
682
|
+
const sampleEntry = firstSample.description;
|
|
683
|
+
const inputTrack = trackInfoById(inFile, id);
|
|
684
|
+
const trackOptions = {
|
|
685
|
+
type: sampleEntry.type,
|
|
686
|
+
timescale: firstSample.timescale,
|
|
687
|
+
// `boxes` is typed as `Box[]` but `description_boxes` wants the
|
|
688
|
+
// narrower `BoxKind[]` union — at runtime they're the same
|
|
689
|
+
// concrete instances, just typed loosely.
|
|
690
|
+
description_boxes: sampleEntry.boxes
|
|
691
|
+
};
|
|
692
|
+
if (inputTrack?.track_width !== void 0) {
|
|
693
|
+
trackOptions.width = inputTrack.track_width;
|
|
694
|
+
}
|
|
695
|
+
if (inputTrack?.track_height !== void 0) {
|
|
696
|
+
trackOptions.height = inputTrack.track_height;
|
|
697
|
+
}
|
|
698
|
+
if (inputTrack?.language !== void 0) {
|
|
699
|
+
trackOptions.language = inputTrack.language;
|
|
700
|
+
}
|
|
701
|
+
if (inputTrack?.video) {
|
|
702
|
+
trackOptions.hdlr = "vide";
|
|
703
|
+
} else if (inputTrack?.audio) {
|
|
704
|
+
trackOptions.hdlr = "soun";
|
|
705
|
+
}
|
|
706
|
+
pending = { trackOptions, timescale: firstSample.timescale, firstDts: firstSample.dts, samples: [] };
|
|
707
|
+
pendingTracks.set(id, pending);
|
|
708
|
+
}
|
|
709
|
+
pending.samples.push(...samples);
|
|
710
|
+
};
|
|
711
|
+
let buf;
|
|
712
|
+
try {
|
|
713
|
+
buf = MP4Box.MP4BoxBuffer.fromArrayBuffer(
|
|
714
|
+
input.buffer.slice(input.byteOffset, input.byteOffset + input.byteLength),
|
|
715
|
+
0
|
|
716
|
+
);
|
|
717
|
+
} catch (error) {
|
|
718
|
+
fail(error);
|
|
719
|
+
return;
|
|
720
|
+
}
|
|
721
|
+
try {
|
|
722
|
+
inFile.appendBuffer(buf);
|
|
723
|
+
inFile.flush();
|
|
724
|
+
} catch (error) {
|
|
725
|
+
fail(error);
|
|
726
|
+
return;
|
|
727
|
+
}
|
|
728
|
+
if (settled) {
|
|
729
|
+
return;
|
|
730
|
+
}
|
|
731
|
+
if (pendingTracks.size === 0) {
|
|
732
|
+
fail(new Error("no samples extracted from input"));
|
|
733
|
+
return;
|
|
734
|
+
}
|
|
735
|
+
let originSeconds = Infinity;
|
|
736
|
+
for (const pending of pendingTracks.values()) {
|
|
737
|
+
originSeconds = Math.min(originSeconds, pending.firstDts / pending.timescale);
|
|
738
|
+
}
|
|
739
|
+
try {
|
|
740
|
+
for (const pending of pendingTracks.values()) {
|
|
741
|
+
const outId = outFile.addTrack(pending.trackOptions);
|
|
742
|
+
const dtsShift = Math.round(originSeconds * pending.timescale);
|
|
743
|
+
for (const sample of pending.samples) {
|
|
744
|
+
if (!sample.data) {
|
|
745
|
+
continue;
|
|
746
|
+
}
|
|
747
|
+
outFile.addSample(outId, sample.data, {
|
|
748
|
+
duration: sample.duration,
|
|
749
|
+
dts: sample.dts - dtsShift,
|
|
750
|
+
cts: sample.cts - dtsShift,
|
|
751
|
+
is_sync: sample.is_sync
|
|
752
|
+
});
|
|
753
|
+
}
|
|
754
|
+
}
|
|
755
|
+
} catch (error) {
|
|
756
|
+
fail(error);
|
|
757
|
+
return;
|
|
758
|
+
}
|
|
759
|
+
let output;
|
|
760
|
+
try {
|
|
761
|
+
const stream = outFile.getBuffer();
|
|
762
|
+
output = new Uint8Array(stream.buffer.slice(0, stream.byteLength));
|
|
763
|
+
} catch (error) {
|
|
764
|
+
fail(error);
|
|
765
|
+
return;
|
|
766
|
+
}
|
|
767
|
+
settled = true;
|
|
768
|
+
resolve(output);
|
|
769
|
+
});
|
|
770
|
+
}
|
|
771
|
+
function trackInfoById(file, id) {
|
|
772
|
+
const info = file.getInfo();
|
|
773
|
+
return info.tracks.find((t) => t.id === id);
|
|
774
|
+
}
|
|
775
|
+
function concatUint8Arrays(parts) {
|
|
776
|
+
const only = parts.length === 1 ? parts[0] : void 0;
|
|
777
|
+
if (only) {
|
|
778
|
+
return only;
|
|
779
|
+
}
|
|
780
|
+
let total = 0;
|
|
781
|
+
for (const p of parts) {
|
|
782
|
+
total += p.byteLength;
|
|
783
|
+
}
|
|
784
|
+
const out = new Uint8Array(total);
|
|
785
|
+
let offset = 0;
|
|
786
|
+
for (const p of parts) {
|
|
787
|
+
out.set(p, offset);
|
|
788
|
+
offset += p.byteLength;
|
|
789
|
+
}
|
|
790
|
+
return out;
|
|
791
|
+
}
|
|
792
|
+
function isAbortError(error) {
|
|
793
|
+
return error instanceof DOMException && error.name === "AbortError";
|
|
794
|
+
}
|
|
795
|
+
function resolveAgainst(target, base) {
|
|
796
|
+
try {
|
|
797
|
+
return new URL(target, base).toString();
|
|
798
|
+
} catch {
|
|
799
|
+
return target;
|
|
800
|
+
}
|
|
801
|
+
}
|
|
802
|
+
function parseRetryAfter(header, fallbackMs) {
|
|
803
|
+
if (!header) {
|
|
804
|
+
return fallbackMs;
|
|
805
|
+
}
|
|
806
|
+
const seconds = Number(header);
|
|
807
|
+
if (Number.isFinite(seconds) && seconds >= 0) {
|
|
808
|
+
return seconds * 1e3;
|
|
809
|
+
}
|
|
810
|
+
const dateMs = Date.parse(header);
|
|
811
|
+
if (!Number.isNaN(dateMs)) {
|
|
812
|
+
return Math.max(0, dateMs - Date.now());
|
|
813
|
+
}
|
|
814
|
+
return fallbackMs;
|
|
815
|
+
}
|
|
816
|
+
function sleep(ms, signal) {
|
|
817
|
+
return new Promise((resolve, reject) => {
|
|
818
|
+
if (signal?.aborted) {
|
|
819
|
+
reject(new DOMException("Aborted", "AbortError"));
|
|
820
|
+
return;
|
|
821
|
+
}
|
|
822
|
+
const timer = setTimeout(() => {
|
|
823
|
+
signal?.removeEventListener("abort", onAbort);
|
|
824
|
+
resolve();
|
|
825
|
+
}, ms);
|
|
826
|
+
const onAbort = () => {
|
|
827
|
+
clearTimeout(timer);
|
|
828
|
+
reject(new DOMException("Aborted", "AbortError"));
|
|
829
|
+
};
|
|
830
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
831
|
+
});
|
|
832
|
+
}
|
|
833
|
+
function triggerBrowserDownload(blob, filename) {
|
|
834
|
+
const objectUrl = URL.createObjectURL(blob);
|
|
835
|
+
try {
|
|
836
|
+
const a = document.createElement("a");
|
|
837
|
+
a.href = objectUrl;
|
|
838
|
+
a.download = filename;
|
|
839
|
+
a.style.display = "none";
|
|
840
|
+
document.body.appendChild(a);
|
|
841
|
+
a.click();
|
|
842
|
+
a.remove();
|
|
843
|
+
} finally {
|
|
844
|
+
URL.revokeObjectURL(objectUrl);
|
|
845
|
+
}
|
|
846
|
+
}
|
|
847
|
+
|
|
848
|
+
// src/reactor.ts
|
|
849
|
+
var Reactor = class {
|
|
850
|
+
clientOptions;
|
|
851
|
+
jwt;
|
|
852
|
+
client;
|
|
853
|
+
clientPromise;
|
|
854
|
+
disposed = false;
|
|
855
|
+
_lastError;
|
|
856
|
+
schema;
|
|
857
|
+
/** Bumped on every `refreshSchema()` call — lets a call detect it's been
|
|
858
|
+
* superseded by a newer one even when `client` itself hasn't changed
|
|
859
|
+
* (e.g. two "ready" transitions on the same reused client). */
|
|
860
|
+
schemaRefreshId = 0;
|
|
861
|
+
capabilities;
|
|
862
|
+
stats;
|
|
863
|
+
connectionTimings;
|
|
864
|
+
statsPollHandle;
|
|
865
|
+
/** Bumped on every `startStatsPolling()`/`stopStatsPolling()` call — lets an
|
|
866
|
+
* in-flight `getStats()` recognize it's stale once it resolves, even if
|
|
867
|
+
* `this.client` hasn't changed in the meantime. */
|
|
868
|
+
statsPollGeneration = 0;
|
|
869
|
+
/** Set on the "connecting" status transition, cleared once `connectionTimings`
|
|
870
|
+
* is finalized on "ready" — see `handleStatusChanged()`. */
|
|
871
|
+
connectStartTime;
|
|
872
|
+
waitingStartTime;
|
|
873
|
+
emitter = new Emitter();
|
|
874
|
+
/** Serializes connect()/reconnect()/disconnect() (and the free() inside
|
|
875
|
+
* disconnect()/[Symbol.dispose]) against each other. Calling into the
|
|
876
|
+
* client concurrently with one of these (e.g. a user clicking Disconnect
|
|
877
|
+
* mid-connect) races its internal state and can throw ("attempted to
|
|
878
|
+
* take ownership of Rust value while it was borrowed") or corrupt it
|
|
879
|
+
* outright. */
|
|
880
|
+
queue = new import_awaitqueue.AwaitQueue();
|
|
881
|
+
constructor(options) {
|
|
882
|
+
const { jwt, ...clientOptions } = options;
|
|
883
|
+
this.clientOptions = clientOptions;
|
|
884
|
+
this.jwt = jwt ?? null;
|
|
885
|
+
}
|
|
886
|
+
// ── Lifecycle ───────────────────────────────────────────────────────────
|
|
887
|
+
/**
|
|
888
|
+
* `jwt`, when given, replaces whatever `new Reactor({ jwt })` was given —
|
|
889
|
+
* including on a client that's still around from a recoverable
|
|
890
|
+
* `disconnect(true)`.
|
|
891
|
+
*
|
|
892
|
+
* Throws if already connected or connecting; call `disconnect()` first.
|
|
893
|
+
*/
|
|
894
|
+
async connect(jwt, options) {
|
|
895
|
+
this.assertNotDisposed();
|
|
896
|
+
try {
|
|
897
|
+
if (this.getStatus() !== "disconnected") {
|
|
898
|
+
throw new Error("Already connected or connecting.");
|
|
899
|
+
}
|
|
900
|
+
if (jwt !== void 0) {
|
|
901
|
+
this.jwt = jwt;
|
|
902
|
+
this.client?.setJwt(jwt);
|
|
903
|
+
}
|
|
904
|
+
await this.queue.push(async () => {
|
|
905
|
+
const client = await this.getOrCreateClient();
|
|
906
|
+
await client.connect(options);
|
|
907
|
+
}, "connect");
|
|
908
|
+
} catch (cause) {
|
|
909
|
+
throw this.captureError(cause);
|
|
910
|
+
}
|
|
911
|
+
}
|
|
912
|
+
/**
|
|
913
|
+
* Ends the connection. By default (`recoverable = false`) this also frees
|
|
914
|
+
* the wasm resource graph — the pump/dispatcher/heartbeat tasks and the
|
|
915
|
+
* peer connection — in one step. Pass `recoverable: true` to keep the
|
|
916
|
+
* wasm client alive so a later `connect()`/`reconnect()` doesn't have to
|
|
917
|
+
* reload wasm and reconstruct it from scratch.
|
|
918
|
+
*
|
|
919
|
+
* Note this only governs the *local* resource graph — the binding's own
|
|
920
|
+
* `disconnect()` always ends the session server-side regardless of this
|
|
921
|
+
* flag, so `recoverable` isn't a way to keep the session itself alive.
|
|
922
|
+
*
|
|
923
|
+
* Queued behind any in-flight `connect()`/`reconnect()` — see `queue`'s
|
|
924
|
+
* docs for why calling into the client concurrently with one of those is
|
|
925
|
+
* unsafe.
|
|
926
|
+
*/
|
|
927
|
+
async disconnect(recoverable = false) {
|
|
928
|
+
this.assertNotDisposed();
|
|
929
|
+
try {
|
|
930
|
+
await this.queue.push(async () => {
|
|
931
|
+
if (this.client) {
|
|
932
|
+
await this.client.disconnect();
|
|
933
|
+
}
|
|
934
|
+
this.resetConnectionState();
|
|
935
|
+
if (!recoverable) {
|
|
936
|
+
this.freeClient();
|
|
937
|
+
}
|
|
938
|
+
}, "disconnect");
|
|
939
|
+
} catch (cause) {
|
|
940
|
+
throw this.captureError(cause);
|
|
941
|
+
}
|
|
942
|
+
}
|
|
943
|
+
/**
|
|
944
|
+
* Only `options.maxAttempts` has an effect here — the rest of
|
|
945
|
+
* `ConnectOptions` (session adoption, connection id, auto-resume) only
|
|
946
|
+
* makes sense when establishing a session in the first place, same as v2's
|
|
947
|
+
* `reconnect()` always ignored them.
|
|
948
|
+
*/
|
|
949
|
+
async reconnect(options) {
|
|
950
|
+
this.assertNotDisposed();
|
|
951
|
+
try {
|
|
952
|
+
await this.queue.push(async () => {
|
|
953
|
+
const client = await this.getOrCreateClient();
|
|
954
|
+
await client.reconnect(options);
|
|
955
|
+
}, "reconnect");
|
|
956
|
+
} catch (cause) {
|
|
957
|
+
throw this.captureError(cause);
|
|
958
|
+
}
|
|
959
|
+
}
|
|
960
|
+
// ── Messaging ───────────────────────────────────────────────────────────
|
|
961
|
+
/**
|
|
962
|
+
* Sends a command to the model and resolves with its correlated reply.
|
|
963
|
+
*
|
|
964
|
+
* `undefined` means the handler acknowledged the command but sent no
|
|
965
|
+
* reply body. The binding's own typed signature promises `undefined` for
|
|
966
|
+
* that case, but its serializer (serde_wasm_bindgen's `json_compatible`
|
|
967
|
+
* mode) actually hands back `null` — normalized here so callers can rely
|
|
968
|
+
* on the documented type instead of the binding's serialization quirk.
|
|
969
|
+
*
|
|
970
|
+
* A `FileRef` (from `uploadFile`) may be passed as a top-level value in
|
|
971
|
+
* `data` alongside regular parameters — it is extracted and sent as a
|
|
972
|
+
* separate upload reference rather than embedded in the JSON payload.
|
|
973
|
+
*
|
|
974
|
+
* Unlike every other method here, this never rejects — a failure (the
|
|
975
|
+
* session isn't `"ready"`, the send itself fails, …) is reported through
|
|
976
|
+
* `getLastError()`/the `error` event instead, resolving with `undefined`.
|
|
977
|
+
* This is a JS-only compatibility shim, kept because callers routinely
|
|
978
|
+
* fire-and-forget `sendCommand(...)` without `await`/`catch`, and a
|
|
979
|
+
* rejection nobody handles is an unhandled-rejection warning at best. It
|
|
980
|
+
* is deliberately not applied to `publishTrack`/`uploadFile`/etc., which
|
|
981
|
+
* throw normally.
|
|
982
|
+
*
|
|
983
|
+
* `scope` is forwarded to `sendRuntimeScopedCommand()` — see there for
|
|
984
|
+
* what `"runtime"` actually does.
|
|
985
|
+
*
|
|
986
|
+
* `data` accepts any object, except a function.
|
|
987
|
+
*/
|
|
988
|
+
async sendCommand(command, data, scope) {
|
|
989
|
+
if (scope === "runtime") {
|
|
990
|
+
return this.sendRuntimeScopedCommand(command, data);
|
|
991
|
+
}
|
|
992
|
+
try {
|
|
993
|
+
this.assertNotDisposed();
|
|
994
|
+
const client = await this.getOrCreateClient();
|
|
995
|
+
const extracted = extractFileRefs(data);
|
|
996
|
+
const reply = await client.sendCommand(command, extracted.data, extracted.uploads);
|
|
997
|
+
return reply ?? void 0;
|
|
998
|
+
} catch (cause) {
|
|
999
|
+
this.emitError(cause);
|
|
1000
|
+
return void 0;
|
|
1001
|
+
}
|
|
1002
|
+
}
|
|
1003
|
+
/**
|
|
1004
|
+
* Handles `sendCommand(command, data, "runtime")` — this SDK has no
|
|
1005
|
+
* generic runtime-scope channel. `reactor-core`'s `send_command` is a
|
|
1006
|
+
* single channel; `requestSchema`/clip requests/heartbeat are each their
|
|
1007
|
+
* own dedicated RPC instead of a scoped envelope, so there's nothing
|
|
1008
|
+
* generic to route a scope through at the wire level.
|
|
1009
|
+
*
|
|
1010
|
+
* `requestSchema` and `requestCapabilities` route to their direct
|
|
1011
|
+
* equivalents below, neither of which returns a `ReactorMessage` the way a
|
|
1012
|
+
* normal `sendCommand()` reply would, so both resolve `undefined`; the
|
|
1013
|
+
* actual data surfaces through `getSchema()`/`schemaReceived` and
|
|
1014
|
+
* `getCapabilities()`/`capabilitiesReceived` as it already does. Anything
|
|
1015
|
+
* else has no runtime-scope destination to route to — rather than silently
|
|
1016
|
+
* doing nothing, it falls through as a normal application-scope send, with
|
|
1017
|
+
* a console warning.
|
|
1018
|
+
*/
|
|
1019
|
+
async sendRuntimeScopedCommand(command, data) {
|
|
1020
|
+
switch (command) {
|
|
1021
|
+
case "requestSchema":
|
|
1022
|
+
try {
|
|
1023
|
+
const client = await this.getOrCreateClient();
|
|
1024
|
+
await this.refreshSchema(client);
|
|
1025
|
+
} catch (cause) {
|
|
1026
|
+
this.emitError(cause);
|
|
1027
|
+
}
|
|
1028
|
+
return void 0;
|
|
1029
|
+
case "requestCapabilities":
|
|
1030
|
+
return void 0;
|
|
1031
|
+
default:
|
|
1032
|
+
console.warn(
|
|
1033
|
+
`[Reactor] sendCommand(${JSON.stringify(command)}, \u2026, "runtime") has no runtime-scope destination in this SDK \u2014 sending as a normal application-scope command instead.`
|
|
1034
|
+
);
|
|
1035
|
+
return this.sendCommand(command, data);
|
|
1036
|
+
}
|
|
1037
|
+
}
|
|
1038
|
+
/** Requests the model's command schema directly. Most callers don't need
|
|
1039
|
+
* this — it's already fetched once and cached as soon as the session
|
|
1040
|
+
* reaches `"ready"`; use `getSchema()` for that. Resolves `undefined`
|
|
1041
|
+
* when the model doesn't expose a schema — the binding replies with a
|
|
1042
|
+
* wire `null` in that case rather than omitting the field. */
|
|
1043
|
+
async requestSchema() {
|
|
1044
|
+
this.assertNotDisposed();
|
|
1045
|
+
try {
|
|
1046
|
+
const client = await this.getOrCreateClient();
|
|
1047
|
+
return this.normalizeSchema(await client.requestSchema());
|
|
1048
|
+
} catch (cause) {
|
|
1049
|
+
throw this.captureError(cause);
|
|
1050
|
+
}
|
|
1051
|
+
}
|
|
1052
|
+
/** The model's command schema (an OpenAPI document), cached from the
|
|
1053
|
+
* `requestSchema()` call fired automatically on `"ready"`. `undefined`
|
|
1054
|
+
* until that reply has landed. */
|
|
1055
|
+
getSchema() {
|
|
1056
|
+
return this.schema;
|
|
1057
|
+
}
|
|
1058
|
+
/** The runtime's declared capabilities (negotiated tracks, and the
|
|
1059
|
+
* command set when the model exposes one) — pushed once available, no
|
|
1060
|
+
* explicit request needed. `undefined` until `capabilitiesReceived`
|
|
1061
|
+
* fires. */
|
|
1062
|
+
getCapabilities() {
|
|
1063
|
+
return this.capabilities;
|
|
1064
|
+
}
|
|
1065
|
+
/** The session resource, as the coordinator reports it — id, state,
|
|
1066
|
+
* model, cluster, server info, and (once negotiated) `capabilities`.
|
|
1067
|
+
* A live read straight off the wasm client, not cached — reflects
|
|
1068
|
+
* whatever's current. `undefined` before a client exists. */
|
|
1069
|
+
getSessionInfo() {
|
|
1070
|
+
return this.client?.sessionInfo();
|
|
1071
|
+
}
|
|
1072
|
+
// ── Tracks ──────────────────────────────────────────────────────────────
|
|
1073
|
+
/**
|
|
1074
|
+
* Publishes a local `MediaStreamTrack` under `name` — the counterpart to a
|
|
1075
|
+
* `sendonly` track the model declares. Awaitable. Queued behind
|
|
1076
|
+
* connect()/disconnect()/reconnect() (unlike `sendCommand()`): a track
|
|
1077
|
+
* operation awaits its own control round-trip, and a concurrent
|
|
1078
|
+
* disconnect() freeing the wasm client mid-await would otherwise resume
|
|
1079
|
+
* into a freed client — the same class of use-after-free `queue` exists to
|
|
1080
|
+
* prevent for connect/disconnect/reconnect themselves.
|
|
1081
|
+
*/
|
|
1082
|
+
async publishTrack(name, track) {
|
|
1083
|
+
this.assertNotDisposed();
|
|
1084
|
+
try {
|
|
1085
|
+
await this.queue.push(async () => {
|
|
1086
|
+
const client = await this.getOrCreateClient();
|
|
1087
|
+
await client.publishTrack(name, track);
|
|
1088
|
+
}, "publishTrack");
|
|
1089
|
+
} catch (cause) {
|
|
1090
|
+
throw this.captureError(cause);
|
|
1091
|
+
}
|
|
1092
|
+
}
|
|
1093
|
+
/**
|
|
1094
|
+
* Unlike every other track method, this doesn't reject — a failure is
|
|
1095
|
+
* reported through the `error` event instead, since this is commonly the
|
|
1096
|
+
* last call in a `finally` block, and raising there would replace
|
|
1097
|
+
* whatever exception was already propagating.
|
|
1098
|
+
*/
|
|
1099
|
+
async unpublishTrack(name) {
|
|
1100
|
+
this.assertNotDisposed();
|
|
1101
|
+
try {
|
|
1102
|
+
await this.queue.push(async () => {
|
|
1103
|
+
const client = await this.getOrCreateClient();
|
|
1104
|
+
await client.unpublishTrack(name);
|
|
1105
|
+
}, "unpublishTrack");
|
|
1106
|
+
} catch (cause) {
|
|
1107
|
+
this.emitError(cause);
|
|
1108
|
+
}
|
|
1109
|
+
}
|
|
1110
|
+
/**
|
|
1111
|
+
* Stops a received track: the receiver goes inactive and the runtime stops
|
|
1112
|
+
* producing it. Awaitable, and queued behind connect()/disconnect()/
|
|
1113
|
+
* reconnect() for the same reason as `publishTrack()`.
|
|
1114
|
+
*/
|
|
1115
|
+
async pauseTrack(name) {
|
|
1116
|
+
this.assertNotDisposed();
|
|
1117
|
+
try {
|
|
1118
|
+
await this.queue.push(async () => {
|
|
1119
|
+
const client = await this.getOrCreateClient();
|
|
1120
|
+
await client.pauseTrack(name);
|
|
1121
|
+
}, "pauseTrack");
|
|
1122
|
+
} catch (cause) {
|
|
1123
|
+
throw this.captureError(cause);
|
|
1124
|
+
}
|
|
1125
|
+
}
|
|
1126
|
+
/** Resumes a track previously stopped with `pauseTrack()`. */
|
|
1127
|
+
async resumeTrack(name) {
|
|
1128
|
+
this.assertNotDisposed();
|
|
1129
|
+
try {
|
|
1130
|
+
await this.queue.push(async () => {
|
|
1131
|
+
const client = await this.getOrCreateClient();
|
|
1132
|
+
await client.resumeTrack(name);
|
|
1133
|
+
}, "resumeTrack");
|
|
1134
|
+
} catch (cause) {
|
|
1135
|
+
throw this.captureError(cause);
|
|
1136
|
+
}
|
|
1137
|
+
}
|
|
1138
|
+
// ── Recording ───────────────────────────────────────────────────────────
|
|
1139
|
+
/**
|
|
1140
|
+
* Requests a clip covering the last `durationSeconds` of the session.
|
|
1141
|
+
* `reactor-core` correlates the reply itself (and enforces `"ready"`), so
|
|
1142
|
+
* this is a thin delegation, same as `requestSchema()`. See
|
|
1143
|
+
* `downloadClipAsFile()` to turn the result into a file.
|
|
1144
|
+
*/
|
|
1145
|
+
async requestClip(durationSeconds) {
|
|
1146
|
+
this.assertNotDisposed();
|
|
1147
|
+
try {
|
|
1148
|
+
const client = await this.getOrCreateClient();
|
|
1149
|
+
return toPublicClip(await client.requestClip(durationSeconds));
|
|
1150
|
+
} catch (cause) {
|
|
1151
|
+
throw this.captureError(cause);
|
|
1152
|
+
}
|
|
1153
|
+
}
|
|
1154
|
+
/** Requests a clip covering the entire session up to now. See `requestClip()`. */
|
|
1155
|
+
async requestRecording() {
|
|
1156
|
+
this.assertNotDisposed();
|
|
1157
|
+
try {
|
|
1158
|
+
const client = await this.getOrCreateClient();
|
|
1159
|
+
return toPublicClip(await client.requestRecording());
|
|
1160
|
+
} catch (cause) {
|
|
1161
|
+
throw this.captureError(cause);
|
|
1162
|
+
}
|
|
1163
|
+
}
|
|
1164
|
+
/** Thin delegation to the standalone `downloadClipAsFile()` — see its own doc comment. */
|
|
1165
|
+
async downloadClipAsFile(clip, filename = "reactor-clip.mp4", options) {
|
|
1166
|
+
return downloadClipAsFile(clip, filename, options);
|
|
1167
|
+
}
|
|
1168
|
+
// ── Uploads ─────────────────────────────────────────────────────────────
|
|
1169
|
+
/**
|
|
1170
|
+
* Uploads a file to the session's object store, resolving with a
|
|
1171
|
+
* `FileRef` to pass as a top-level value in a `sendCommand()`'s `data`
|
|
1172
|
+
* (see `extractFileRefs`). The binding itself takes `(file, name?)`
|
|
1173
|
+
* positionally and already applies the right defaulting — a bare
|
|
1174
|
+
* `Blob`'s name falls back to `"upload"`, and an empty/missing mime type
|
|
1175
|
+
* to `"application/octet-stream"` — so there's nothing to wrap here.
|
|
1176
|
+
*
|
|
1177
|
+
* Queued behind connect()/disconnect()/reconnect(), same as the track
|
|
1178
|
+
* ops: this awaits its own round-trip, and a concurrent disconnect()
|
|
1179
|
+
* freeing the wasm client mid-upload would otherwise resume into a freed
|
|
1180
|
+
* client — the same use-after-free class of race the queue exists to
|
|
1181
|
+
* prevent.
|
|
1182
|
+
*/
|
|
1183
|
+
async uploadFile(file, options) {
|
|
1184
|
+
this.assertNotDisposed();
|
|
1185
|
+
try {
|
|
1186
|
+
const wireFileRef = await this.queue.push(async () => {
|
|
1187
|
+
const client = await this.getOrCreateClient();
|
|
1188
|
+
return client.uploadFile(file, options?.name);
|
|
1189
|
+
}, "uploadFile");
|
|
1190
|
+
return toPublicFileRef(wireFileRef);
|
|
1191
|
+
} catch (cause) {
|
|
1192
|
+
throw this.captureError(cause);
|
|
1193
|
+
}
|
|
1194
|
+
}
|
|
1195
|
+
/** All tracks the model declared, whether or not media has arrived for —
|
|
1196
|
+
* or been published to — them yet. Empty before a client exists. */
|
|
1197
|
+
tracks() {
|
|
1198
|
+
return this.client?.tracks() ?? [];
|
|
1199
|
+
}
|
|
1200
|
+
/** Same as `tracks()`, plus each entry's negotiated `mid` — the id
|
|
1201
|
+
* `trackReceived`'s `mid` argument and the `getXByMid` escape hatches key
|
|
1202
|
+
* on. Only populated once SDP negotiation has assigned mids. */
|
|
1203
|
+
trackMapping() {
|
|
1204
|
+
return this.client?.trackMapping() ?? [];
|
|
1205
|
+
}
|
|
1206
|
+
pausedTracks() {
|
|
1207
|
+
return this.client?.pausedTracks() ?? [];
|
|
1208
|
+
}
|
|
1209
|
+
// ── Escape hatches ──────────────────────────────────────────────────────
|
|
1210
|
+
/** Drops to the raw `RTCPeerConnection` for anything this class doesn't
|
|
1211
|
+
* wrap directly. `undefined` before a client exists. */
|
|
1212
|
+
getPeerConnection() {
|
|
1213
|
+
return this.client?.getPeerConnection();
|
|
1214
|
+
}
|
|
1215
|
+
getTrackByMid(mid) {
|
|
1216
|
+
return this.client?.getTrackByMid(mid);
|
|
1217
|
+
}
|
|
1218
|
+
getStreamByMid(mid) {
|
|
1219
|
+
return this.client?.getStreamByMid(mid);
|
|
1220
|
+
}
|
|
1221
|
+
getTrackByName(name) {
|
|
1222
|
+
return this.client?.getTrackByName(name);
|
|
1223
|
+
}
|
|
1224
|
+
getStreamByName(name) {
|
|
1225
|
+
return this.client?.getStreamByName(name);
|
|
1226
|
+
}
|
|
1227
|
+
/**
|
|
1228
|
+
* Supports `using reactor = new Reactor(...)`: releases the wasm resource
|
|
1229
|
+
* graph and drops every registered event handler for good. Unlike a plain
|
|
1230
|
+
* `disconnect()`, this instance is unusable afterward — construct a new
|
|
1231
|
+
* `Reactor` instead of trying to `connect()` again.
|
|
1232
|
+
*/
|
|
1233
|
+
[Symbol.dispose]() {
|
|
1234
|
+
if (this.disposed) {
|
|
1235
|
+
return;
|
|
1236
|
+
}
|
|
1237
|
+
this.disposed = true;
|
|
1238
|
+
const client = this.client;
|
|
1239
|
+
this.client = void 0;
|
|
1240
|
+
this.clientPromise = void 0;
|
|
1241
|
+
this.schema = void 0;
|
|
1242
|
+
this.capabilities = void 0;
|
|
1243
|
+
this.resetConnectionState();
|
|
1244
|
+
this.emitter.clear();
|
|
1245
|
+
if (client) {
|
|
1246
|
+
void this.queue.push(() => client.free(), "dispose").catch(() => {
|
|
1247
|
+
});
|
|
1248
|
+
}
|
|
1249
|
+
}
|
|
1250
|
+
// ── Introspection ───────────────────────────────────────────────────────
|
|
1251
|
+
/** The wasm binding's own terser `status()` name can be added alongside
|
|
1252
|
+
* this later if it turns out to be worth it. */
|
|
1253
|
+
getStatus() {
|
|
1254
|
+
return this.client?.status() ?? "disconnected";
|
|
1255
|
+
}
|
|
1256
|
+
/** See `getStatus()`. */
|
|
1257
|
+
getSessionId() {
|
|
1258
|
+
return this.client?.sessionId();
|
|
1259
|
+
}
|
|
1260
|
+
/** The `jwt` this instance was constructed (or last `connect()`ed) with —
|
|
1261
|
+
* lets a component composed inside a `ReactorProvider` (e.g. `ClipPlayer`)
|
|
1262
|
+
* authenticate its own requests without the caller repeating the resolver. */
|
|
1263
|
+
getJwtResolver() {
|
|
1264
|
+
return this.jwt ?? void 0;
|
|
1265
|
+
}
|
|
1266
|
+
/** The most recent `ReactorError`, from either an `error` event or a
|
|
1267
|
+
* rejected call — whichever landed last. `undefined` until the first
|
|
1268
|
+
* failure. */
|
|
1269
|
+
getLastError() {
|
|
1270
|
+
return this._lastError;
|
|
1271
|
+
}
|
|
1272
|
+
/** The most recent WebRTC connection stats, polled every `STATS_INTERVAL_MS`
|
|
1273
|
+
* while "ready" — see `statsUpdate`. `undefined` before the first sample. */
|
|
1274
|
+
getStats() {
|
|
1275
|
+
return this.stats;
|
|
1276
|
+
}
|
|
1277
|
+
/** Timing breakdown from the most recent `connect()`/`reconnect()`
|
|
1278
|
+
* handshake — see `ConnectionTimings`. */
|
|
1279
|
+
getConnectionTimings() {
|
|
1280
|
+
return this.connectionTimings;
|
|
1281
|
+
}
|
|
1282
|
+
// ── Events ──────────────────────────────────────────────────────────────
|
|
1283
|
+
on(event, handler) {
|
|
1284
|
+
this.emitter.on(event, handler);
|
|
1285
|
+
}
|
|
1286
|
+
off(event, handler) {
|
|
1287
|
+
this.emitter.off(event, handler);
|
|
1288
|
+
}
|
|
1289
|
+
once(event, handler) {
|
|
1290
|
+
this.emitter.once(event, handler);
|
|
1291
|
+
}
|
|
1292
|
+
// ── Internal ────────────────────────────────────────────────────────────
|
|
1293
|
+
getOrCreateClient() {
|
|
1294
|
+
if (!this.clientPromise) {
|
|
1295
|
+
this.clientPromise = this.createClient().catch((cause) => {
|
|
1296
|
+
this.clientPromise = void 0;
|
|
1297
|
+
throw cause;
|
|
1298
|
+
});
|
|
1299
|
+
}
|
|
1300
|
+
return this.clientPromise;
|
|
1301
|
+
}
|
|
1302
|
+
async createClient() {
|
|
1303
|
+
const { ReactorClient: WasmReactorClient } = await loadReactorWasm();
|
|
1304
|
+
if (this.disposed) {
|
|
1305
|
+
throw new Error("Reactor was disposed while connecting.");
|
|
1306
|
+
}
|
|
1307
|
+
const client = new WasmReactorClient(this.clientOptions, this.jwt);
|
|
1308
|
+
client.onStatusChanged((status) => {
|
|
1309
|
+
this.emitter.emit("statusChanged", status);
|
|
1310
|
+
this.handleStatusChanged(client, status);
|
|
1311
|
+
});
|
|
1312
|
+
client.onSessionIdChanged((sessionId) => this.emitter.emit("sessionIdChanged", sessionId));
|
|
1313
|
+
client.onError((error) => this.emitError(error));
|
|
1314
|
+
client.onMessage((message) => {
|
|
1315
|
+
debugLog("[Reactor] message:", message);
|
|
1316
|
+
this.emitter.emit("message", message);
|
|
1317
|
+
});
|
|
1318
|
+
client.onRuntimeMessage((message) => {
|
|
1319
|
+
debugLog("[Reactor] runtimeMessage:", message);
|
|
1320
|
+
this.emitter.emit("runtimeMessage", message);
|
|
1321
|
+
});
|
|
1322
|
+
client.onCapabilitiesReceived((capabilities) => {
|
|
1323
|
+
this.capabilities = toPublicCapabilities(capabilities);
|
|
1324
|
+
this.emitter.emit("capabilitiesReceived", this.capabilities);
|
|
1325
|
+
});
|
|
1326
|
+
client.onTrackReceived((name, mid) => {
|
|
1327
|
+
const track = client.getTrackByName(name);
|
|
1328
|
+
const stream = client.getStreamByName(name);
|
|
1329
|
+
if (!track || !stream) {
|
|
1330
|
+
return;
|
|
1331
|
+
}
|
|
1332
|
+
this.emitter.emit("trackReceived", name, track, stream, mid);
|
|
1333
|
+
});
|
|
1334
|
+
this.client = client;
|
|
1335
|
+
return client;
|
|
1336
|
+
}
|
|
1337
|
+
/** Fired once per `"ready"` transition — see `getSchema()`. `getSchema()`
|
|
1338
|
+
* isn't guaranteed populated by the time a `statusChanged` "ready" handler
|
|
1339
|
+
* runs (this fetch is async and dispatched separately), so callers that
|
|
1340
|
+
* need the schema as soon as it lands should listen for `schemaReceived`
|
|
1341
|
+
* instead of reading `getSchema()` synchronously off `statusChanged`.
|
|
1342
|
+
*
|
|
1343
|
+
* Guards against a stale reply: if `disconnect()`/a later `connect()`
|
|
1344
|
+
* replaces `client` before this resolves, or a newer `refreshSchema()`
|
|
1345
|
+
* call for the same client wins the race, the result is discarded rather
|
|
1346
|
+
* than clobbering `this.schema` (or emitting `schema`) with old data.
|
|
1347
|
+
*
|
|
1348
|
+
* A rejection here (e.g. the session drops mid-request) surfaces like any
|
|
1349
|
+
* other binding failure, through the same `error` event as `onError`. */
|
|
1350
|
+
async refreshSchema(client) {
|
|
1351
|
+
const refreshId = ++this.schemaRefreshId;
|
|
1352
|
+
try {
|
|
1353
|
+
const schema = this.normalizeSchema(await client.requestSchema());
|
|
1354
|
+
if (this.client !== client || refreshId !== this.schemaRefreshId) {
|
|
1355
|
+
return;
|
|
1356
|
+
}
|
|
1357
|
+
if (schema === void 0) {
|
|
1358
|
+
return;
|
|
1359
|
+
}
|
|
1360
|
+
this.schema = schema;
|
|
1361
|
+
this.emitter.emit("schemaReceived", this.schema);
|
|
1362
|
+
this.emitter.emit("runtimeMessage", { type: "modelSchema", data: this.schema });
|
|
1363
|
+
} catch (cause) {
|
|
1364
|
+
if (this.client !== client || refreshId !== this.schemaRefreshId) {
|
|
1365
|
+
return;
|
|
1366
|
+
}
|
|
1367
|
+
this.emitError(cause);
|
|
1368
|
+
}
|
|
1369
|
+
}
|
|
1370
|
+
/** The binding replies with a wire `null` (not an omitted field) when the
|
|
1371
|
+
* model doesn't expose a schema — normalized to `undefined` so callers
|
|
1372
|
+
* get the same "no schema" sentinel `getSchema()` already uses instead
|
|
1373
|
+
* of a document they could otherwise dereference. */
|
|
1374
|
+
normalizeSchema(schema) {
|
|
1375
|
+
return schema ?? void 0;
|
|
1376
|
+
}
|
|
1377
|
+
/** Frees the wasm resource graph, if one exists, and clears the cached
|
|
1378
|
+
* schema. Reusable — unlike `[Symbol.dispose]`, this doesn't set the
|
|
1379
|
+
* permanent `disposed` flag, so a later `connect()`/`reconnect()` lazily
|
|
1380
|
+
* builds a fresh client.
|
|
1381
|
+
*
|
|
1382
|
+
* Only called from within `disconnect()`'s queued task, so `client.free()`
|
|
1383
|
+
* is safe to call directly here — the queue already guarantees no other
|
|
1384
|
+
* operation is running concurrently against it. */
|
|
1385
|
+
freeClient() {
|
|
1386
|
+
this.client?.free();
|
|
1387
|
+
this.client = void 0;
|
|
1388
|
+
this.clientPromise = void 0;
|
|
1389
|
+
this.schema = void 0;
|
|
1390
|
+
this.capabilities = void 0;
|
|
1391
|
+
}
|
|
1392
|
+
/** Tracks `connectionTimings` off the binding's own "connecting" → "waiting"
|
|
1393
|
+
* → "ready" status sequence (see `ReactorStatus`), and starts/stops stats
|
|
1394
|
+
* polling around the "ready" window. */
|
|
1395
|
+
handleStatusChanged(client, status) {
|
|
1396
|
+
switch (status) {
|
|
1397
|
+
case "connecting":
|
|
1398
|
+
this.connectStartTime = performance.now();
|
|
1399
|
+
this.waitingStartTime = void 0;
|
|
1400
|
+
break;
|
|
1401
|
+
case "waiting":
|
|
1402
|
+
this.waitingStartTime = performance.now();
|
|
1403
|
+
break;
|
|
1404
|
+
case "ready": {
|
|
1405
|
+
const readyTime = performance.now();
|
|
1406
|
+
if (this.connectStartTime != null) {
|
|
1407
|
+
const waitingStartTime = this.waitingStartTime ?? readyTime;
|
|
1408
|
+
this.connectionTimings = {
|
|
1409
|
+
sessionCreationMs: waitingStartTime - this.connectStartTime,
|
|
1410
|
+
transportConnectingMs: readyTime - waitingStartTime,
|
|
1411
|
+
totalMs: readyTime - this.connectStartTime
|
|
1412
|
+
};
|
|
1413
|
+
}
|
|
1414
|
+
this.startStatsPolling(client);
|
|
1415
|
+
void this.refreshSchema(client);
|
|
1416
|
+
break;
|
|
1417
|
+
}
|
|
1418
|
+
default:
|
|
1419
|
+
this.stopStatsPolling();
|
|
1420
|
+
}
|
|
1421
|
+
}
|
|
1422
|
+
startStatsPolling(client) {
|
|
1423
|
+
this.stopStatsPolling();
|
|
1424
|
+
const generation = ++this.statsPollGeneration;
|
|
1425
|
+
const extractStats = createRTCStatsExtractor();
|
|
1426
|
+
this.statsPollHandle = setInterval(() => {
|
|
1427
|
+
const peerConnection = client.getPeerConnection();
|
|
1428
|
+
if (!peerConnection) {
|
|
1429
|
+
return;
|
|
1430
|
+
}
|
|
1431
|
+
peerConnection.getStats().then((report) => {
|
|
1432
|
+
if (generation !== this.statsPollGeneration) {
|
|
1433
|
+
return;
|
|
1434
|
+
}
|
|
1435
|
+
this.stats = { ...extractStats(report), connectionTimings: this.connectionTimings };
|
|
1436
|
+
this.emitter.emit("statsUpdate", this.stats);
|
|
1437
|
+
}).catch(() => {
|
|
1438
|
+
});
|
|
1439
|
+
}, STATS_INTERVAL_MS);
|
|
1440
|
+
}
|
|
1441
|
+
stopStatsPolling() {
|
|
1442
|
+
this.statsPollGeneration += 1;
|
|
1443
|
+
if (this.statsPollHandle !== void 0) {
|
|
1444
|
+
clearInterval(this.statsPollHandle);
|
|
1445
|
+
this.statsPollHandle = void 0;
|
|
1446
|
+
}
|
|
1447
|
+
this.stats = void 0;
|
|
1448
|
+
}
|
|
1449
|
+
/** Called on every `disconnect()` and on `[Symbol.dispose]`. Leaves
|
|
1450
|
+
* `client`/`schema` alone — that's `freeClient()`'s job, run separately
|
|
1451
|
+
* when `disconnect()` isn't recoverable. `capabilities` is cleared here
|
|
1452
|
+
* regardless, though: unlike the schema, it isn't re-fetched on demand,
|
|
1453
|
+
* so a recoverable disconnect that skips `freeClient()` would otherwise
|
|
1454
|
+
* leave `getCapabilities()` returning the previous session's stale
|
|
1455
|
+
* tracks/commands until a new `capabilitiesReceived` lands. */
|
|
1456
|
+
resetConnectionState() {
|
|
1457
|
+
this.stopStatsPolling();
|
|
1458
|
+
this.connectionTimings = void 0;
|
|
1459
|
+
this.connectStartTime = void 0;
|
|
1460
|
+
this.waitingStartTime = void 0;
|
|
1461
|
+
this.capabilities = void 0;
|
|
1462
|
+
}
|
|
1463
|
+
/** Wraps `cause` and records it as the most recent failure, for a call
|
|
1464
|
+
* that's about to throw rather than emit — see `getLastError()`'s doc
|
|
1465
|
+
* comment. */
|
|
1466
|
+
captureError(cause) {
|
|
1467
|
+
const error = toReactorError(cause);
|
|
1468
|
+
this._lastError = error;
|
|
1469
|
+
return error;
|
|
1470
|
+
}
|
|
1471
|
+
/** Wraps `cause`, records it as the most recent failure, and fires the
|
|
1472
|
+
* `error` event — the one place recording and emitting happen together,
|
|
1473
|
+
* so `getLastError()` never drifts from what listeners were told. */
|
|
1474
|
+
emitError(cause) {
|
|
1475
|
+
this.emitter.emit("error", this.captureError(cause));
|
|
1476
|
+
}
|
|
1477
|
+
assertNotDisposed() {
|
|
1478
|
+
if (this.disposed) {
|
|
1479
|
+
throw new Error("This Reactor was disposed and can't be used again \u2014 construct a new one.");
|
|
1480
|
+
}
|
|
1481
|
+
}
|
|
1482
|
+
};
|
|
1483
|
+
|
|
1484
|
+
// src/jwt.ts
|
|
1485
|
+
function normalizeJwtSource(source) {
|
|
1486
|
+
if (typeof source === "function") {
|
|
1487
|
+
return source;
|
|
1488
|
+
}
|
|
1489
|
+
return () => source;
|
|
1490
|
+
}
|
|
1491
|
+
|
|
1492
|
+
// src/react/ReactorProvider.tsx
|
|
1493
|
+
var import_react = require("react");
|
|
1494
|
+
|
|
1495
|
+
// src/react/store.ts
|
|
1496
|
+
var defaultReactorState = {
|
|
1497
|
+
status: "disconnected",
|
|
1498
|
+
sessionId: void 0,
|
|
1499
|
+
lastError: void 0,
|
|
1500
|
+
lastMessage: void 0,
|
|
1501
|
+
tracks: {},
|
|
1502
|
+
jwtToken: void 0,
|
|
1503
|
+
connectOptions: void 0
|
|
1504
|
+
};
|
|
1505
|
+
function createStore(build) {
|
|
1506
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
1507
|
+
let state;
|
|
1508
|
+
const set = (partial) => {
|
|
1509
|
+
state = { ...state, ...partial };
|
|
1510
|
+
listeners.forEach((listener) => listener());
|
|
1511
|
+
};
|
|
1512
|
+
const get = () => state;
|
|
1513
|
+
state = build(set, get);
|
|
1514
|
+
return {
|
|
1515
|
+
getState: get,
|
|
1516
|
+
subscribe: (listener) => {
|
|
1517
|
+
listeners.add(listener);
|
|
1518
|
+
return () => listeners.delete(listener);
|
|
1519
|
+
}
|
|
1520
|
+
};
|
|
1521
|
+
}
|
|
1522
|
+
function createReactorStore(options, defaultConnectOptions) {
|
|
1523
|
+
return createStore((set, get) => {
|
|
1524
|
+
const reactor = new Reactor(options);
|
|
1525
|
+
reactor.on("statusChanged", (status) => {
|
|
1526
|
+
set(status === "disconnected" ? { status, tracks: {} } : { status });
|
|
1527
|
+
});
|
|
1528
|
+
reactor.on("sessionIdChanged", (sessionId) => set({ sessionId }));
|
|
1529
|
+
reactor.on("error", (lastError) => set({ lastError }));
|
|
1530
|
+
reactor.on("message", (lastMessage) => set({ lastMessage }));
|
|
1531
|
+
reactor.on("trackReceived", (name, track) => set({ tracks: { ...get().tracks, [name]: track } }));
|
|
1532
|
+
return {
|
|
1533
|
+
...defaultReactorState,
|
|
1534
|
+
jwtToken: options.jwt,
|
|
1535
|
+
connectOptions: defaultConnectOptions,
|
|
1536
|
+
internal: { reactor },
|
|
1537
|
+
connect: (jwt, callOptions) => get().internal.reactor.connect(jwt, { ...defaultConnectOptions, ...callOptions }),
|
|
1538
|
+
disconnect: (recoverable) => get().internal.reactor.disconnect(recoverable),
|
|
1539
|
+
reconnect: (callOptions) => get().internal.reactor.reconnect({ ...defaultConnectOptions, ...callOptions }),
|
|
1540
|
+
sendCommand: (command, data, scope) => get().internal.reactor.sendCommand(command, data, scope),
|
|
1541
|
+
publish: (name, track) => get().internal.reactor.publishTrack(name, track),
|
|
1542
|
+
unpublish: (name) => get().internal.reactor.unpublishTrack(name),
|
|
1543
|
+
pauseTrack: (name) => get().internal.reactor.pauseTrack(name),
|
|
1544
|
+
resumeTrack: (name) => get().internal.reactor.resumeTrack(name),
|
|
1545
|
+
uploadFile: (file, options2) => get().internal.reactor.uploadFile(file, options2),
|
|
1546
|
+
requestClip: (durationSeconds) => get().internal.reactor.requestClip(durationSeconds),
|
|
1547
|
+
requestRecording: () => get().internal.reactor.requestRecording(),
|
|
1548
|
+
downloadClipAsFile: (clip, filename, options2) => get().internal.reactor.downloadClipAsFile(clip, filename, options2)
|
|
1549
|
+
};
|
|
1550
|
+
});
|
|
1551
|
+
}
|
|
1552
|
+
|
|
1553
|
+
// src/react/ReactorProvider.tsx
|
|
1554
|
+
var import_jsx_runtime = require("react/jsx-runtime");
|
|
1555
|
+
var ReactorContext = (0, import_react.createContext)(void 0);
|
|
1556
|
+
function buildStore({
|
|
1557
|
+
apiUrl,
|
|
1558
|
+
modelName,
|
|
1559
|
+
local,
|
|
1560
|
+
modelTracks,
|
|
1561
|
+
jwtToken,
|
|
1562
|
+
connectOptions
|
|
1563
|
+
}) {
|
|
1564
|
+
const options = { modelName };
|
|
1565
|
+
if (apiUrl !== void 0) {
|
|
1566
|
+
options.apiUrl = apiUrl;
|
|
1567
|
+
}
|
|
1568
|
+
if (local !== void 0) {
|
|
1569
|
+
options.local = local;
|
|
1570
|
+
}
|
|
1571
|
+
if (modelTracks !== void 0) {
|
|
1572
|
+
options.modelTracks = modelTracks;
|
|
1573
|
+
}
|
|
1574
|
+
if (jwtToken !== void 0) {
|
|
1575
|
+
options.jwt = jwtToken;
|
|
1576
|
+
}
|
|
1577
|
+
const { autoConnect, ...pollingOptions } = connectOptions ?? {};
|
|
1578
|
+
return createReactorStore(options, pollingOptions);
|
|
1579
|
+
}
|
|
1580
|
+
function ReactorProvider({
|
|
1581
|
+
apiUrl,
|
|
1582
|
+
modelName,
|
|
1583
|
+
local,
|
|
1584
|
+
modelTracks,
|
|
1585
|
+
jwtToken,
|
|
1586
|
+
connectOptions,
|
|
1587
|
+
children
|
|
1588
|
+
}) {
|
|
1589
|
+
const [store, setStore] = (0, import_react.useState)(
|
|
1590
|
+
() => buildStore({ apiUrl, modelName, local, modelTracks, jwtToken, connectOptions })
|
|
1591
|
+
);
|
|
1592
|
+
const isFirstRun = (0, import_react.useRef)(true);
|
|
1593
|
+
(0, import_react.useEffect)(() => {
|
|
1594
|
+
if (isFirstRun.current) {
|
|
1595
|
+
isFirstRun.current = false;
|
|
1596
|
+
return;
|
|
1597
|
+
}
|
|
1598
|
+
setStore(buildStore({ apiUrl, modelName, local, modelTracks, jwtToken, connectOptions }));
|
|
1599
|
+
}, [apiUrl, modelName, local, JSON.stringify(modelTracks), jwtToken, JSON.stringify(connectOptions)]);
|
|
1600
|
+
(0, import_react.useEffect)(() => {
|
|
1601
|
+
const { autoConnect = false, ...pollingOptions } = connectOptions ?? {};
|
|
1602
|
+
if (autoConnect && store.getState().status === "disconnected") {
|
|
1603
|
+
store.getState().connect(jwtToken, pollingOptions).catch((error) => {
|
|
1604
|
+
console.error("[Reactor.ReactorProvider] autoConnect failed:", error);
|
|
1605
|
+
});
|
|
1606
|
+
}
|
|
1607
|
+
}, [store]);
|
|
1608
|
+
(0, import_react.useEffect)(() => {
|
|
1609
|
+
return () => {
|
|
1610
|
+
const reactor = store.getState().internal.reactor;
|
|
1611
|
+
void reactor.disconnect().finally(() => reactor[Symbol.dispose]());
|
|
1612
|
+
};
|
|
1613
|
+
}, [store]);
|
|
1614
|
+
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ReactorContext.Provider, { value: store, children });
|
|
1615
|
+
}
|
|
1616
|
+
function useReactorStore(selector) {
|
|
1617
|
+
const store = (0, import_react.useContext)(ReactorContext);
|
|
1618
|
+
if (store === void 0) {
|
|
1619
|
+
throw new Error("useReactor must be used within a ReactorProvider");
|
|
1620
|
+
}
|
|
1621
|
+
const getSnapshot = () => selector(store.getState());
|
|
1622
|
+
return (0, import_react.useSyncExternalStore)(store.subscribe, getSnapshot, getSnapshot);
|
|
1623
|
+
}
|
|
1624
|
+
|
|
1625
|
+
// src/react/hooks.ts
|
|
1626
|
+
var import_react2 = require("react");
|
|
1627
|
+
function shallowEqual(a, b) {
|
|
1628
|
+
if (Object.is(a, b)) {
|
|
1629
|
+
return true;
|
|
1630
|
+
}
|
|
1631
|
+
if (typeof a !== "object" || a === null || typeof b !== "object" || b === null) {
|
|
1632
|
+
return false;
|
|
1633
|
+
}
|
|
1634
|
+
const keysA = Object.keys(a);
|
|
1635
|
+
const keysB = Object.keys(b);
|
|
1636
|
+
return keysA.length === keysB.length && keysA.every((key) => Object.is(a[key], b[key]));
|
|
1637
|
+
}
|
|
1638
|
+
function useShallowSelector(selector) {
|
|
1639
|
+
const cache = (0, import_react2.useRef)(void 0);
|
|
1640
|
+
return (state) => {
|
|
1641
|
+
const next = selector(state);
|
|
1642
|
+
if (cache.current && shallowEqual(cache.current.value, next)) {
|
|
1643
|
+
return cache.current.value;
|
|
1644
|
+
}
|
|
1645
|
+
cache.current = { value: next };
|
|
1646
|
+
return next;
|
|
1647
|
+
};
|
|
1648
|
+
}
|
|
1649
|
+
function useReactor(selector) {
|
|
1650
|
+
return useReactorStore(useShallowSelector(selector));
|
|
1651
|
+
}
|
|
1652
|
+
function useReactorMessage(handler) {
|
|
1653
|
+
const reactor = useReactor((state) => state.internal.reactor);
|
|
1654
|
+
const handlerRef = (0, import_react2.useRef)(handler);
|
|
1655
|
+
handlerRef.current = handler;
|
|
1656
|
+
(0, import_react2.useEffect)(() => {
|
|
1657
|
+
const listener = (message) => handlerRef.current(message);
|
|
1658
|
+
reactor.on("message", listener);
|
|
1659
|
+
return () => reactor.off("message", listener);
|
|
1660
|
+
}, [reactor]);
|
|
1661
|
+
}
|
|
1662
|
+
function useReactorInternalMessage(handler) {
|
|
1663
|
+
const reactor = useReactor((state) => state.internal.reactor);
|
|
1664
|
+
const handlerRef = (0, import_react2.useRef)(handler);
|
|
1665
|
+
handlerRef.current = handler;
|
|
1666
|
+
(0, import_react2.useEffect)(() => {
|
|
1667
|
+
const listener = (message) => handlerRef.current(message);
|
|
1668
|
+
reactor.on("runtimeMessage", listener);
|
|
1669
|
+
return () => reactor.off("runtimeMessage", listener);
|
|
1670
|
+
}, [reactor]);
|
|
1671
|
+
}
|
|
1672
|
+
function useStats() {
|
|
1673
|
+
const reactor = useReactor((state) => state.internal.reactor);
|
|
1674
|
+
const [stats, setStats] = (0, import_react2.useState)(void 0);
|
|
1675
|
+
(0, import_react2.useEffect)(() => {
|
|
1676
|
+
setStats(void 0);
|
|
1677
|
+
reactor.on("statsUpdate", setStats);
|
|
1678
|
+
return () => {
|
|
1679
|
+
reactor.off("statsUpdate", setStats);
|
|
1680
|
+
setStats(void 0);
|
|
1681
|
+
};
|
|
1682
|
+
}, [reactor]);
|
|
1683
|
+
return stats;
|
|
1684
|
+
}
|
|
1685
|
+
|
|
1686
|
+
// src/react/ReactorView.tsx
|
|
1687
|
+
var import_react3 = require("react");
|
|
1688
|
+
var import_jsx_runtime2 = require("react/jsx-runtime");
|
|
1689
|
+
function useReceivedTrack(name) {
|
|
1690
|
+
const reactor = useReactor((state) => state.internal.reactor);
|
|
1691
|
+
const [track, setTrack] = (0, import_react3.useState)(() => name ? reactor.getTrackByName(name) : void 0);
|
|
1692
|
+
(0, import_react3.useEffect)(() => {
|
|
1693
|
+
setTrack(name ? reactor.getTrackByName(name) : void 0);
|
|
1694
|
+
if (!name) {
|
|
1695
|
+
return;
|
|
1696
|
+
}
|
|
1697
|
+
const listener = (receivedName, receivedTrack) => {
|
|
1698
|
+
if (receivedName === name) {
|
|
1699
|
+
setTrack(receivedTrack);
|
|
1700
|
+
}
|
|
1701
|
+
};
|
|
1702
|
+
reactor.on("trackReceived", listener);
|
|
1703
|
+
return () => reactor.off("trackReceived", listener);
|
|
1704
|
+
}, [reactor, name]);
|
|
1705
|
+
return track;
|
|
1706
|
+
}
|
|
1707
|
+
function ReactorView({
|
|
1708
|
+
track = "main_video",
|
|
1709
|
+
audioTrack,
|
|
1710
|
+
width,
|
|
1711
|
+
height,
|
|
1712
|
+
className,
|
|
1713
|
+
style,
|
|
1714
|
+
videoObjectFit = "contain",
|
|
1715
|
+
muted = audioTrack === void 0
|
|
1716
|
+
}) {
|
|
1717
|
+
const videoMediaTrack = useReceivedTrack(track);
|
|
1718
|
+
const audioMediaTrack = useReceivedTrack(audioTrack);
|
|
1719
|
+
const videoRef = (0, import_react3.useRef)(null);
|
|
1720
|
+
const mediaStream = (0, import_react3.useMemo)(() => {
|
|
1721
|
+
const tracks = [];
|
|
1722
|
+
if (videoMediaTrack) {
|
|
1723
|
+
tracks.push(videoMediaTrack);
|
|
1724
|
+
}
|
|
1725
|
+
if (audioMediaTrack) {
|
|
1726
|
+
tracks.push(audioMediaTrack);
|
|
1727
|
+
}
|
|
1728
|
+
return tracks.length > 0 ? new MediaStream(tracks) : null;
|
|
1729
|
+
}, [videoMediaTrack, audioMediaTrack]);
|
|
1730
|
+
(0, import_react3.useEffect)(() => {
|
|
1731
|
+
const el = videoRef.current;
|
|
1732
|
+
if (!el || !mediaStream) {
|
|
1733
|
+
return;
|
|
1734
|
+
}
|
|
1735
|
+
const attach = (reset) => {
|
|
1736
|
+
if (reset) {
|
|
1737
|
+
el.srcObject = null;
|
|
1738
|
+
}
|
|
1739
|
+
el.srcObject = mediaStream;
|
|
1740
|
+
void el.play().catch(() => {
|
|
1741
|
+
});
|
|
1742
|
+
};
|
|
1743
|
+
attach(false);
|
|
1744
|
+
const onUnmute = () => attach(true);
|
|
1745
|
+
const tracks = mediaStream.getTracks();
|
|
1746
|
+
for (const t of tracks) {
|
|
1747
|
+
t.addEventListener("unmute", onUnmute);
|
|
1748
|
+
}
|
|
1749
|
+
return () => {
|
|
1750
|
+
for (const t of tracks) {
|
|
1751
|
+
t.removeEventListener("unmute", onUnmute);
|
|
1752
|
+
}
|
|
1753
|
+
el.srcObject = null;
|
|
1754
|
+
};
|
|
1755
|
+
}, [mediaStream]);
|
|
1756
|
+
return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
|
|
1757
|
+
"div",
|
|
1758
|
+
{
|
|
1759
|
+
style: {
|
|
1760
|
+
position: "relative",
|
|
1761
|
+
background: "#000",
|
|
1762
|
+
...width !== void 0 && { width },
|
|
1763
|
+
...height !== void 0 && { height },
|
|
1764
|
+
...style
|
|
1765
|
+
},
|
|
1766
|
+
className,
|
|
1767
|
+
children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
|
|
1768
|
+
"video",
|
|
1769
|
+
{
|
|
1770
|
+
ref: videoRef,
|
|
1771
|
+
style: {
|
|
1772
|
+
width: "100%",
|
|
1773
|
+
height: "100%",
|
|
1774
|
+
objectFit: videoObjectFit,
|
|
1775
|
+
display: videoMediaTrack ? "block" : "none"
|
|
1776
|
+
},
|
|
1777
|
+
muted,
|
|
1778
|
+
playsInline: true
|
|
1779
|
+
}
|
|
1780
|
+
)
|
|
1781
|
+
}
|
|
1782
|
+
);
|
|
1783
|
+
}
|
|
1784
|
+
|
|
1785
|
+
// src/react/WebcamStream.tsx
|
|
1786
|
+
var import_react4 = require("react");
|
|
1787
|
+
var import_jsx_runtime3 = require("react/jsx-runtime");
|
|
1788
|
+
var DEFAULT_VIDEO_CONSTRAINTS = {
|
|
1789
|
+
width: { ideal: 1280 },
|
|
1790
|
+
height: { ideal: 720 }
|
|
1791
|
+
};
|
|
1792
|
+
function WebcamStream({
|
|
1793
|
+
track,
|
|
1794
|
+
audio = false,
|
|
1795
|
+
audioTrack,
|
|
1796
|
+
className,
|
|
1797
|
+
style,
|
|
1798
|
+
videoConstraints = DEFAULT_VIDEO_CONSTRAINTS,
|
|
1799
|
+
showWebcam = true,
|
|
1800
|
+
videoObjectFit = "contain",
|
|
1801
|
+
onPermissionDenied,
|
|
1802
|
+
onPublished,
|
|
1803
|
+
onError
|
|
1804
|
+
}) {
|
|
1805
|
+
const [stream, setStream] = (0, import_react4.useState)(null);
|
|
1806
|
+
const [published, setPublished] = (0, import_react4.useState)(null);
|
|
1807
|
+
const [permissionDenied, setPermissionDenied] = (0, import_react4.useState)(false);
|
|
1808
|
+
const { status, publish, unpublish, reactor } = useReactor((state) => ({
|
|
1809
|
+
status: state.status,
|
|
1810
|
+
publish: state.publish,
|
|
1811
|
+
unpublish: state.unpublish,
|
|
1812
|
+
reactor: state.internal.reactor
|
|
1813
|
+
}));
|
|
1814
|
+
const videoRef = (0, import_react4.useRef)(null);
|
|
1815
|
+
const onPermissionDeniedRef = (0, import_react4.useRef)(onPermissionDenied);
|
|
1816
|
+
const onPublishedRef = (0, import_react4.useRef)(onPublished);
|
|
1817
|
+
const onErrorRef = (0, import_react4.useRef)(onError);
|
|
1818
|
+
onPermissionDeniedRef.current = onPermissionDenied;
|
|
1819
|
+
onPublishedRef.current = onPublished;
|
|
1820
|
+
onErrorRef.current = onError;
|
|
1821
|
+
const audioRequested = audio !== false;
|
|
1822
|
+
const audioEnabled = audioRequested && audioTrack !== void 0;
|
|
1823
|
+
const latestRef = (0, import_react4.useRef)({ published, unpublish, stream });
|
|
1824
|
+
latestRef.current = { published, unpublish, stream };
|
|
1825
|
+
(0, import_react4.useEffect)(() => {
|
|
1826
|
+
let cancelled = false;
|
|
1827
|
+
navigator.mediaDevices.getUserMedia({
|
|
1828
|
+
video: videoConstraints,
|
|
1829
|
+
audio: audioEnabled ? audio : false
|
|
1830
|
+
}).then((mediaStream) => {
|
|
1831
|
+
if (cancelled) {
|
|
1832
|
+
for (const t of mediaStream.getTracks()) {
|
|
1833
|
+
t.stop();
|
|
1834
|
+
}
|
|
1835
|
+
return;
|
|
1836
|
+
}
|
|
1837
|
+
setStream(mediaStream);
|
|
1838
|
+
setPermissionDenied(false);
|
|
1839
|
+
}).catch((err) => {
|
|
1840
|
+
if (cancelled) {
|
|
1841
|
+
return;
|
|
1842
|
+
}
|
|
1843
|
+
if (err instanceof DOMException && (err.name === "NotAllowedError" || err.name === "PermissionDeniedError")) {
|
|
1844
|
+
setPermissionDenied(true);
|
|
1845
|
+
onPermissionDeniedRef.current?.();
|
|
1846
|
+
} else {
|
|
1847
|
+
onErrorRef.current?.(err instanceof Error ? err : new Error(String(err)));
|
|
1848
|
+
}
|
|
1849
|
+
});
|
|
1850
|
+
return () => {
|
|
1851
|
+
cancelled = true;
|
|
1852
|
+
const current = latestRef.current;
|
|
1853
|
+
const tasks = [];
|
|
1854
|
+
if (current.published) {
|
|
1855
|
+
tasks.push(current.unpublish(current.published.video));
|
|
1856
|
+
if (current.published.audio) {
|
|
1857
|
+
tasks.push(current.unpublish(current.published.audio));
|
|
1858
|
+
}
|
|
1859
|
+
}
|
|
1860
|
+
if (tasks.length > 0) {
|
|
1861
|
+
void Promise.allSettled(tasks).then((results) => {
|
|
1862
|
+
for (const r of results) {
|
|
1863
|
+
if (r.status === "rejected") {
|
|
1864
|
+
onErrorRef.current?.(r.reason instanceof Error ? r.reason : new Error(String(r.reason)));
|
|
1865
|
+
}
|
|
1866
|
+
}
|
|
1867
|
+
});
|
|
1868
|
+
}
|
|
1869
|
+
current.stream?.getTracks().forEach((t) => t.stop());
|
|
1870
|
+
};
|
|
1871
|
+
}, []);
|
|
1872
|
+
(0, import_react4.useEffect)(() => {
|
|
1873
|
+
const el = videoRef.current;
|
|
1874
|
+
if (!el) {
|
|
1875
|
+
return;
|
|
1876
|
+
}
|
|
1877
|
+
el.srcObject = stream;
|
|
1878
|
+
}, [stream]);
|
|
1879
|
+
(0, import_react4.useEffect)(() => {
|
|
1880
|
+
if (!stream) {
|
|
1881
|
+
return;
|
|
1882
|
+
}
|
|
1883
|
+
let cancelled = false;
|
|
1884
|
+
const desiredAudio = audioEnabled ? audioTrack : void 0;
|
|
1885
|
+
const activeStream = stream;
|
|
1886
|
+
async function sync() {
|
|
1887
|
+
if (status === "ready") {
|
|
1888
|
+
if (published && published.video === track && published.audio === desiredAudio) {
|
|
1889
|
+
return;
|
|
1890
|
+
}
|
|
1891
|
+
if (published) {
|
|
1892
|
+
const rollback = [unpublish(published.video)];
|
|
1893
|
+
if (published.audio) {
|
|
1894
|
+
rollback.push(unpublish(published.audio));
|
|
1895
|
+
}
|
|
1896
|
+
await Promise.allSettled(rollback);
|
|
1897
|
+
if (cancelled) {
|
|
1898
|
+
return;
|
|
1899
|
+
}
|
|
1900
|
+
setPublished(null);
|
|
1901
|
+
}
|
|
1902
|
+
const videoMediaTrack = activeStream.getVideoTracks()[0];
|
|
1903
|
+
const audioMediaTrack = desiredAudio ? activeStream.getAudioTracks()[0] : void 0;
|
|
1904
|
+
const attempts = [];
|
|
1905
|
+
if (videoMediaTrack) {
|
|
1906
|
+
attempts.push({ name: track, task: publish(track, videoMediaTrack) });
|
|
1907
|
+
}
|
|
1908
|
+
if (audioMediaTrack && desiredAudio) {
|
|
1909
|
+
attempts.push({ name: desiredAudio, task: publish(desiredAudio, audioMediaTrack) });
|
|
1910
|
+
}
|
|
1911
|
+
if (attempts.length === 0) {
|
|
1912
|
+
return;
|
|
1913
|
+
}
|
|
1914
|
+
const results = await Promise.allSettled(attempts.map((a) => a.task));
|
|
1915
|
+
if (cancelled) {
|
|
1916
|
+
return;
|
|
1917
|
+
}
|
|
1918
|
+
const failureIndex = results.findIndex((r) => r.status === "rejected");
|
|
1919
|
+
if (failureIndex !== -1) {
|
|
1920
|
+
const succeeded = attempts.filter((_, i) => results[i]?.status === "fulfilled");
|
|
1921
|
+
await Promise.allSettled(succeeded.map((a) => unpublish(a.name)));
|
|
1922
|
+
if (cancelled) {
|
|
1923
|
+
return;
|
|
1924
|
+
}
|
|
1925
|
+
const failure = results[failureIndex];
|
|
1926
|
+
onErrorRef.current?.(failure.reason instanceof Error ? failure.reason : new Error(String(failure.reason)));
|
|
1927
|
+
return;
|
|
1928
|
+
}
|
|
1929
|
+
const newPublished = { video: track };
|
|
1930
|
+
if (audioMediaTrack && desiredAudio) {
|
|
1931
|
+
newPublished.audio = desiredAudio;
|
|
1932
|
+
}
|
|
1933
|
+
setPublished(newPublished);
|
|
1934
|
+
onPublishedRef.current?.();
|
|
1935
|
+
} else if (published) {
|
|
1936
|
+
const tasks = [unpublish(published.video)];
|
|
1937
|
+
if (published.audio) {
|
|
1938
|
+
tasks.push(unpublish(published.audio));
|
|
1939
|
+
}
|
|
1940
|
+
const results = await Promise.allSettled(tasks);
|
|
1941
|
+
if (cancelled) {
|
|
1942
|
+
return;
|
|
1943
|
+
}
|
|
1944
|
+
for (const r of results) {
|
|
1945
|
+
if (r.status === "rejected") {
|
|
1946
|
+
onErrorRef.current?.(r.reason instanceof Error ? r.reason : new Error(String(r.reason)));
|
|
1947
|
+
}
|
|
1948
|
+
}
|
|
1949
|
+
setPublished(null);
|
|
1950
|
+
}
|
|
1951
|
+
}
|
|
1952
|
+
void sync();
|
|
1953
|
+
return () => {
|
|
1954
|
+
cancelled = true;
|
|
1955
|
+
};
|
|
1956
|
+
}, [status, stream, published, publish, unpublish, track, audioEnabled, audioTrack]);
|
|
1957
|
+
(0, import_react4.useEffect)(() => {
|
|
1958
|
+
const handleError = (error) => {
|
|
1959
|
+
if (error.code === "TRACK_PUBLISH_FAILED") {
|
|
1960
|
+
setPublished(null);
|
|
1961
|
+
}
|
|
1962
|
+
};
|
|
1963
|
+
reactor.on("error", handleError);
|
|
1964
|
+
return () => reactor.off("error", handleError);
|
|
1965
|
+
}, [reactor]);
|
|
1966
|
+
const showPlaceholder = !stream;
|
|
1967
|
+
return /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(
|
|
1968
|
+
"div",
|
|
1969
|
+
{
|
|
1970
|
+
style: {
|
|
1971
|
+
display: showWebcam ? "block" : "none",
|
|
1972
|
+
position: "relative",
|
|
1973
|
+
background: "#000",
|
|
1974
|
+
...style
|
|
1975
|
+
},
|
|
1976
|
+
className,
|
|
1977
|
+
children: [
|
|
1978
|
+
/* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
|
|
1979
|
+
"video",
|
|
1980
|
+
{
|
|
1981
|
+
ref: videoRef,
|
|
1982
|
+
style: {
|
|
1983
|
+
width: "100%",
|
|
1984
|
+
height: "100%",
|
|
1985
|
+
objectFit: videoObjectFit,
|
|
1986
|
+
display: showPlaceholder ? "none" : "block"
|
|
1987
|
+
},
|
|
1988
|
+
muted: true,
|
|
1989
|
+
playsInline: true,
|
|
1990
|
+
autoPlay: true
|
|
1991
|
+
}
|
|
1992
|
+
),
|
|
1993
|
+
showPlaceholder && /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
|
|
1994
|
+
"div",
|
|
1995
|
+
{
|
|
1996
|
+
style: {
|
|
1997
|
+
position: "absolute",
|
|
1998
|
+
top: 0,
|
|
1999
|
+
left: 0,
|
|
2000
|
+
width: "100%",
|
|
2001
|
+
height: "100%",
|
|
2002
|
+
color: "#fff",
|
|
2003
|
+
display: "flex",
|
|
2004
|
+
alignItems: "center",
|
|
2005
|
+
justifyContent: "center",
|
|
2006
|
+
fontSize: "16px",
|
|
2007
|
+
fontFamily: "monospace",
|
|
2008
|
+
textAlign: "center",
|
|
2009
|
+
padding: "20px",
|
|
2010
|
+
boxSizing: "border-box",
|
|
2011
|
+
flexDirection: "column",
|
|
2012
|
+
gap: "12px"
|
|
2013
|
+
},
|
|
2014
|
+
children: permissionDenied ? /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { style: { fontSize: "12px", fontFamily: "monospace" }, children: [
|
|
2015
|
+
"Camera access denied.",
|
|
2016
|
+
/* @__PURE__ */ (0, import_jsx_runtime3.jsx)("br", {}),
|
|
2017
|
+
"Please allow access in your browser settings."
|
|
2018
|
+
] }) : /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { style: { fontSize: "12px", fontFamily: "monospace" }, children: "Starting camera..." })
|
|
2019
|
+
}
|
|
2020
|
+
)
|
|
2021
|
+
]
|
|
2022
|
+
}
|
|
2023
|
+
);
|
|
2024
|
+
}
|
|
2025
|
+
|
|
2026
|
+
// src/react/ClipPlayer.tsx
|
|
2027
|
+
var import_react5 = require("react");
|
|
2028
|
+
|
|
2029
|
+
// src/clip-playback.ts
|
|
2030
|
+
function attachClipPlayback(video, source, {
|
|
2031
|
+
autoPlay,
|
|
2032
|
+
onReady,
|
|
2033
|
+
onError,
|
|
2034
|
+
loadHls = () => import("hls.js").then((mod) => mod.default)
|
|
2035
|
+
}) {
|
|
2036
|
+
let destroyed = false;
|
|
2037
|
+
let failed = false;
|
|
2038
|
+
let ready = false;
|
|
2039
|
+
let hls = null;
|
|
2040
|
+
let mp4Url = null;
|
|
2041
|
+
const fail = (error) => {
|
|
2042
|
+
if (destroyed || failed) {
|
|
2043
|
+
return;
|
|
2044
|
+
}
|
|
2045
|
+
failed = true;
|
|
2046
|
+
onError(error);
|
|
2047
|
+
};
|
|
2048
|
+
const handleLoadedMetadata = () => {
|
|
2049
|
+
if (destroyed || failed || ready) {
|
|
2050
|
+
return;
|
|
2051
|
+
}
|
|
2052
|
+
ready = true;
|
|
2053
|
+
onReady();
|
|
2054
|
+
if (autoPlay) {
|
|
2055
|
+
video.play().catch(() => {
|
|
2056
|
+
});
|
|
2057
|
+
}
|
|
2058
|
+
};
|
|
2059
|
+
const handleElementError = () => {
|
|
2060
|
+
fail(new Error(describeMediaError(video.error)));
|
|
2061
|
+
};
|
|
2062
|
+
video.addEventListener("loadedmetadata", handleLoadedMetadata);
|
|
2063
|
+
video.addEventListener("error", handleElementError);
|
|
2064
|
+
const handle = {
|
|
2065
|
+
destroy: () => {
|
|
2066
|
+
destroyed = true;
|
|
2067
|
+
video.removeEventListener("loadedmetadata", handleLoadedMetadata);
|
|
2068
|
+
video.removeEventListener("error", handleElementError);
|
|
2069
|
+
hls?.destroy();
|
|
2070
|
+
hls = null;
|
|
2071
|
+
if (mp4Url) {
|
|
2072
|
+
URL.revokeObjectURL(mp4Url);
|
|
2073
|
+
mp4Url = null;
|
|
2074
|
+
}
|
|
2075
|
+
}
|
|
2076
|
+
};
|
|
2077
|
+
const selectPath = async () => {
|
|
2078
|
+
const HlsCtor = hasMediaSource() ? await loadHls().catch(() => null) : null;
|
|
2079
|
+
if (destroyed) {
|
|
2080
|
+
return;
|
|
2081
|
+
}
|
|
2082
|
+
if (HlsCtor?.isSupported()) {
|
|
2083
|
+
const instance = new HlsCtor();
|
|
2084
|
+
instance.loadSource(source.manifestUrl);
|
|
2085
|
+
instance.attachMedia(video);
|
|
2086
|
+
instance.on(HlsCtor.Events.ERROR, (_evt, data) => {
|
|
2087
|
+
if (destroyed) {
|
|
2088
|
+
return;
|
|
2089
|
+
}
|
|
2090
|
+
if (data.fatal) {
|
|
2091
|
+
fail(new Error(`Playback error: ${data.details ?? "unknown"}`));
|
|
2092
|
+
return;
|
|
2093
|
+
}
|
|
2094
|
+
console.warn("[Reactor.ClipPlayer] hls.js non-fatal error", data);
|
|
2095
|
+
});
|
|
2096
|
+
hls = instance;
|
|
2097
|
+
return;
|
|
2098
|
+
}
|
|
2099
|
+
const blob = await source.assembleMp4();
|
|
2100
|
+
if (destroyed) {
|
|
2101
|
+
return;
|
|
2102
|
+
}
|
|
2103
|
+
mp4Url = URL.createObjectURL(blob);
|
|
2104
|
+
video.src = mp4Url;
|
|
2105
|
+
};
|
|
2106
|
+
selectPath().catch((err) => {
|
|
2107
|
+
fail(err instanceof Error ? err : new Error(String(err)));
|
|
2108
|
+
});
|
|
2109
|
+
return handle;
|
|
2110
|
+
}
|
|
2111
|
+
function hasMediaSource() {
|
|
2112
|
+
const scope = globalThis;
|
|
2113
|
+
return Boolean(scope.ManagedMediaSource ?? scope.MediaSource ?? scope.WebKitMediaSource);
|
|
2114
|
+
}
|
|
2115
|
+
var MEDIA_ERROR_MESSAGES = {
|
|
2116
|
+
1: "Playback was aborted.",
|
|
2117
|
+
2: "A network error interrupted playback.",
|
|
2118
|
+
3: "This clip could not be decoded.",
|
|
2119
|
+
4: "This browser cannot play this clip. Use Download instead."
|
|
2120
|
+
};
|
|
2121
|
+
function describeMediaError(error) {
|
|
2122
|
+
const message = (error && MEDIA_ERROR_MESSAGES[error.code]) ?? "This clip failed to play in this browser. Use Download instead.";
|
|
2123
|
+
return error?.message ? `${message} (${error.message})` : message;
|
|
2124
|
+
}
|
|
2125
|
+
|
|
2126
|
+
// src/internal/jwt-resolver.ts
|
|
2127
|
+
async function resolveJwtSource(source) {
|
|
2128
|
+
return typeof source === "function" ? source() : source;
|
|
2129
|
+
}
|
|
2130
|
+
|
|
2131
|
+
// src/react/ClipPlayer.tsx
|
|
2132
|
+
var import_jsx_runtime4 = require("react/jsx-runtime");
|
|
2133
|
+
function ClipPlayer({
|
|
2134
|
+
clip,
|
|
2135
|
+
getJwt,
|
|
2136
|
+
slackMs,
|
|
2137
|
+
autoPlay = true,
|
|
2138
|
+
muted = true,
|
|
2139
|
+
className,
|
|
2140
|
+
style,
|
|
2141
|
+
onError
|
|
2142
|
+
}) {
|
|
2143
|
+
const videoRef = (0, import_react5.useRef)(null);
|
|
2144
|
+
const [phase, setPhase] = (0, import_react5.useState)({ kind: "waiting" });
|
|
2145
|
+
const store = (0, import_react5.useContext)(ReactorContext);
|
|
2146
|
+
const getJwtRef = (0, import_react5.useRef)(getJwt);
|
|
2147
|
+
const autoPlayRef = (0, import_react5.useRef)(autoPlay);
|
|
2148
|
+
const slackMsRef = (0, import_react5.useRef)(slackMs);
|
|
2149
|
+
const onErrorRef = (0, import_react5.useRef)(onError);
|
|
2150
|
+
const storeRef = (0, import_react5.useRef)(store);
|
|
2151
|
+
getJwtRef.current = getJwt;
|
|
2152
|
+
autoPlayRef.current = autoPlay;
|
|
2153
|
+
slackMsRef.current = slackMs;
|
|
2154
|
+
onErrorRef.current = onError;
|
|
2155
|
+
storeRef.current = store;
|
|
2156
|
+
(0, import_react5.useEffect)(() => {
|
|
2157
|
+
if (phase.kind === "error") {
|
|
2158
|
+
onErrorRef.current?.(phase.error);
|
|
2159
|
+
}
|
|
2160
|
+
}, [phase]);
|
|
2161
|
+
(0, import_react5.useEffect)(() => {
|
|
2162
|
+
const video = videoRef.current;
|
|
2163
|
+
if (!video) {
|
|
2164
|
+
return;
|
|
2165
|
+
}
|
|
2166
|
+
const abort = new AbortController();
|
|
2167
|
+
let cancelled = false;
|
|
2168
|
+
let playback = null;
|
|
2169
|
+
let manifestBlobUrl = null;
|
|
2170
|
+
const fail = (error) => {
|
|
2171
|
+
if (cancelled) {
|
|
2172
|
+
return;
|
|
2173
|
+
}
|
|
2174
|
+
const message = error instanceof RecordingError ? `${error.code}: ${error.reason}` : error.message;
|
|
2175
|
+
setPhase({ kind: "error", message, error });
|
|
2176
|
+
};
|
|
2177
|
+
const setup = async () => {
|
|
2178
|
+
try {
|
|
2179
|
+
setPhase({ kind: "waiting" });
|
|
2180
|
+
const explicit = getJwtRef.current;
|
|
2181
|
+
const fallback = storeRef.current?.getState().internal.reactor.getJwtResolver();
|
|
2182
|
+
const jwt = explicit ? await explicit() : fallback !== void 0 ? await resolveJwtSource(fallback) : void 0;
|
|
2183
|
+
if (cancelled) {
|
|
2184
|
+
return;
|
|
2185
|
+
}
|
|
2186
|
+
const playlistOptions = {
|
|
2187
|
+
predictedReadyAtMs: clip.predictedReadyAtMs,
|
|
2188
|
+
signal: abort.signal
|
|
2189
|
+
};
|
|
2190
|
+
if (slackMsRef.current !== void 0) {
|
|
2191
|
+
playlistOptions.slackMs = slackMsRef.current;
|
|
2192
|
+
}
|
|
2193
|
+
if (jwt !== void 0) {
|
|
2194
|
+
playlistOptions.jwt = jwt;
|
|
2195
|
+
}
|
|
2196
|
+
const body = await fetchPlaylist(clip.playlistUrl, playlistOptions);
|
|
2197
|
+
if (cancelled) {
|
|
2198
|
+
return;
|
|
2199
|
+
}
|
|
2200
|
+
setPhase({ kind: "loading" });
|
|
2201
|
+
manifestBlobUrl = createPlayableManifestUrl(body, clip.playlistUrl);
|
|
2202
|
+
playback = attachClipPlayback(
|
|
2203
|
+
video,
|
|
2204
|
+
{
|
|
2205
|
+
manifestUrl: manifestBlobUrl,
|
|
2206
|
+
assembleMp4: () => assembleClipBlob(body, clip.playlistUrl, { signal: abort.signal })
|
|
2207
|
+
},
|
|
2208
|
+
{
|
|
2209
|
+
autoPlay: autoPlayRef.current,
|
|
2210
|
+
onReady: () => {
|
|
2211
|
+
if (!cancelled) {
|
|
2212
|
+
setPhase({ kind: "ready" });
|
|
2213
|
+
}
|
|
2214
|
+
},
|
|
2215
|
+
onError: fail
|
|
2216
|
+
}
|
|
2217
|
+
);
|
|
2218
|
+
} catch (err) {
|
|
2219
|
+
if (cancelled) {
|
|
2220
|
+
return;
|
|
2221
|
+
}
|
|
2222
|
+
if (err instanceof DOMException && err.name === "AbortError") {
|
|
2223
|
+
return;
|
|
2224
|
+
}
|
|
2225
|
+
fail(err instanceof Error ? err : new Error(String(err)));
|
|
2226
|
+
}
|
|
2227
|
+
};
|
|
2228
|
+
void setup();
|
|
2229
|
+
return () => {
|
|
2230
|
+
cancelled = true;
|
|
2231
|
+
abort.abort();
|
|
2232
|
+
playback?.destroy();
|
|
2233
|
+
video.pause();
|
|
2234
|
+
video.removeAttribute("src");
|
|
2235
|
+
video.load();
|
|
2236
|
+
if (manifestBlobUrl) {
|
|
2237
|
+
URL.revokeObjectURL(manifestBlobUrl);
|
|
2238
|
+
}
|
|
2239
|
+
};
|
|
2240
|
+
}, [clip]);
|
|
2241
|
+
const overlayText = phase.kind === "waiting" ? "Waiting for clip\u2026" : phase.kind === "loading" ? "Loading player\u2026" : null;
|
|
2242
|
+
return /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(
|
|
2243
|
+
"div",
|
|
2244
|
+
{
|
|
2245
|
+
className,
|
|
2246
|
+
style: {
|
|
2247
|
+
position: "relative",
|
|
2248
|
+
background: "#000",
|
|
2249
|
+
width: "100%",
|
|
2250
|
+
display: "flex",
|
|
2251
|
+
alignItems: "center",
|
|
2252
|
+
justifyContent: "center",
|
|
2253
|
+
...style
|
|
2254
|
+
},
|
|
2255
|
+
children: [
|
|
2256
|
+
/* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
|
|
2257
|
+
"video",
|
|
2258
|
+
{
|
|
2259
|
+
ref: videoRef,
|
|
2260
|
+
controls: true,
|
|
2261
|
+
playsInline: true,
|
|
2262
|
+
muted,
|
|
2263
|
+
style: {
|
|
2264
|
+
display: "block",
|
|
2265
|
+
width: "100%",
|
|
2266
|
+
height: "auto",
|
|
2267
|
+
maxHeight: "100%"
|
|
2268
|
+
}
|
|
2269
|
+
}
|
|
2270
|
+
),
|
|
2271
|
+
overlayText && /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
|
|
2272
|
+
"div",
|
|
2273
|
+
{
|
|
2274
|
+
style: {
|
|
2275
|
+
position: "absolute",
|
|
2276
|
+
inset: 0,
|
|
2277
|
+
display: "flex",
|
|
2278
|
+
alignItems: "center",
|
|
2279
|
+
justifyContent: "center",
|
|
2280
|
+
color: "rgba(255,255,255,0.6)",
|
|
2281
|
+
font: "11px ui-monospace, SFMono-Regular, Menlo, monospace",
|
|
2282
|
+
letterSpacing: "0.1em",
|
|
2283
|
+
textTransform: "uppercase",
|
|
2284
|
+
pointerEvents: "none"
|
|
2285
|
+
},
|
|
2286
|
+
children: overlayText
|
|
2287
|
+
}
|
|
2288
|
+
),
|
|
2289
|
+
phase.kind === "error" && /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
|
|
2290
|
+
"div",
|
|
2291
|
+
{
|
|
2292
|
+
style: {
|
|
2293
|
+
position: "absolute",
|
|
2294
|
+
inset: 0,
|
|
2295
|
+
display: "flex",
|
|
2296
|
+
alignItems: "center",
|
|
2297
|
+
justifyContent: "center",
|
|
2298
|
+
padding: 24,
|
|
2299
|
+
background: "rgba(0,0,0,0.8)",
|
|
2300
|
+
color: "#ef4444",
|
|
2301
|
+
font: "11px ui-monospace, SFMono-Regular, Menlo, monospace",
|
|
2302
|
+
textAlign: "center"
|
|
2303
|
+
},
|
|
2304
|
+
children: phase.message
|
|
2305
|
+
}
|
|
2306
|
+
)
|
|
2307
|
+
]
|
|
2308
|
+
}
|
|
2309
|
+
);
|
|
2310
|
+
}
|
|
2311
|
+
|
|
2312
|
+
// src/react/ClipDownloadButton.tsx
|
|
2313
|
+
var import_react7 = require("react");
|
|
2314
|
+
|
|
2315
|
+
// src/react/useClipDownload.ts
|
|
2316
|
+
var import_react6 = require("react");
|
|
2317
|
+
function useClipDownload(clip, options = {}) {
|
|
2318
|
+
const [state, setState] = (0, import_react6.useState)({ kind: "idle" });
|
|
2319
|
+
const store = (0, import_react6.useContext)(ReactorContext);
|
|
2320
|
+
const clipRef = (0, import_react6.useRef)(clip);
|
|
2321
|
+
const filenameRef = (0, import_react6.useRef)(options.filename ?? "reactor-clip.mp4");
|
|
2322
|
+
const getJwtRef = (0, import_react6.useRef)(options.getJwt);
|
|
2323
|
+
const storeRef = (0, import_react6.useRef)(store);
|
|
2324
|
+
clipRef.current = clip;
|
|
2325
|
+
filenameRef.current = options.filename === void 0 ? "reactor-clip.mp4" : options.filename;
|
|
2326
|
+
getJwtRef.current = options.getJwt;
|
|
2327
|
+
storeRef.current = store;
|
|
2328
|
+
const inFlightRef = (0, import_react6.useRef)(false);
|
|
2329
|
+
const abortRef = (0, import_react6.useRef)(null);
|
|
2330
|
+
(0, import_react6.useEffect)(() => () => abortRef.current?.abort(), []);
|
|
2331
|
+
const download = (0, import_react6.useCallback)(async () => {
|
|
2332
|
+
if (inFlightRef.current) {
|
|
2333
|
+
return void 0;
|
|
2334
|
+
}
|
|
2335
|
+
inFlightRef.current = true;
|
|
2336
|
+
const abort = new AbortController();
|
|
2337
|
+
abortRef.current = abort;
|
|
2338
|
+
setState({ kind: "downloading", fetched: 0, total: 0 });
|
|
2339
|
+
try {
|
|
2340
|
+
const explicit = getJwtRef.current;
|
|
2341
|
+
const fallback = storeRef.current?.getState().internal.reactor.getJwtResolver();
|
|
2342
|
+
const jwt = explicit ? await explicit() : fallback !== void 0 ? await resolveJwtSource(fallback) : void 0;
|
|
2343
|
+
const downloadOptions = {
|
|
2344
|
+
signal: abort.signal,
|
|
2345
|
+
onProgress: ({ fetched, total }) => setState({ kind: "downloading", fetched, total })
|
|
2346
|
+
};
|
|
2347
|
+
if (jwt !== void 0) {
|
|
2348
|
+
downloadOptions.jwt = jwt;
|
|
2349
|
+
}
|
|
2350
|
+
const blob = await downloadClipAsFile(clipRef.current, filenameRef.current, downloadOptions);
|
|
2351
|
+
setState({ kind: "idle" });
|
|
2352
|
+
return blob;
|
|
2353
|
+
} catch (err) {
|
|
2354
|
+
if (err instanceof DOMException && err.name === "AbortError") {
|
|
2355
|
+
return void 0;
|
|
2356
|
+
}
|
|
2357
|
+
const message = err instanceof RecordingError ? `${err.code}: ${err.reason}` : err instanceof Error ? err.message : String(err);
|
|
2358
|
+
setState({ kind: "error", message });
|
|
2359
|
+
return void 0;
|
|
2360
|
+
} finally {
|
|
2361
|
+
inFlightRef.current = false;
|
|
2362
|
+
}
|
|
2363
|
+
}, []);
|
|
2364
|
+
const reset = (0, import_react6.useCallback)(() => setState({ kind: "idle" }), []);
|
|
2365
|
+
return { state, download, reset };
|
|
2366
|
+
}
|
|
2367
|
+
|
|
2368
|
+
// src/react/ClipDownloadButton.tsx
|
|
2369
|
+
var import_jsx_runtime5 = require("react/jsx-runtime");
|
|
2370
|
+
function ClipDownloadButton({
|
|
2371
|
+
clip,
|
|
2372
|
+
getJwt,
|
|
2373
|
+
filename = "reactor-clip.mp4",
|
|
2374
|
+
children,
|
|
2375
|
+
className,
|
|
2376
|
+
style,
|
|
2377
|
+
disabled,
|
|
2378
|
+
onSuccess,
|
|
2379
|
+
onError
|
|
2380
|
+
}) {
|
|
2381
|
+
const downloadOptions = { filename };
|
|
2382
|
+
if (getJwt !== void 0) {
|
|
2383
|
+
downloadOptions.getJwt = getJwt;
|
|
2384
|
+
}
|
|
2385
|
+
const { state, download } = useClipDownload(clip, downloadOptions);
|
|
2386
|
+
const downloading = state.kind === "downloading";
|
|
2387
|
+
const isDisabled = downloading || !!disabled;
|
|
2388
|
+
const onSuccessRef = (0, import_react7.useRef)(onSuccess);
|
|
2389
|
+
const onErrorRef = (0, import_react7.useRef)(onError);
|
|
2390
|
+
onSuccessRef.current = onSuccess;
|
|
2391
|
+
onErrorRef.current = onError;
|
|
2392
|
+
(0, import_react7.useEffect)(() => {
|
|
2393
|
+
if (state.kind === "error") {
|
|
2394
|
+
onErrorRef.current?.(new Error(state.message));
|
|
2395
|
+
}
|
|
2396
|
+
}, [state]);
|
|
2397
|
+
const content = typeof children === "function" ? children(state) : children !== void 0 ? children : defaultLabel(state);
|
|
2398
|
+
return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
|
|
2399
|
+
"button",
|
|
2400
|
+
{
|
|
2401
|
+
type: "button",
|
|
2402
|
+
onClick: () => {
|
|
2403
|
+
void download().then((blob) => {
|
|
2404
|
+
if (blob) {
|
|
2405
|
+
onSuccessRef.current?.(blob);
|
|
2406
|
+
}
|
|
2407
|
+
});
|
|
2408
|
+
},
|
|
2409
|
+
disabled: isDisabled,
|
|
2410
|
+
title: state.kind === "error" ? state.message : void 0,
|
|
2411
|
+
className,
|
|
2412
|
+
style: {
|
|
2413
|
+
padding: "5px 12px",
|
|
2414
|
+
borderRadius: 4,
|
|
2415
|
+
border: "1px solid rgba(255,255,255,0.15)",
|
|
2416
|
+
background: "rgba(255,255,255,0.05)",
|
|
2417
|
+
color: "#fff",
|
|
2418
|
+
font: "11px ui-monospace, SFMono-Regular, Menlo, monospace",
|
|
2419
|
+
cursor: isDisabled ? "default" : "pointer",
|
|
2420
|
+
opacity: isDisabled ? 0.6 : 1,
|
|
2421
|
+
transition: "background-color 120ms ease",
|
|
2422
|
+
...style
|
|
2423
|
+
},
|
|
2424
|
+
children: content
|
|
2425
|
+
}
|
|
2426
|
+
);
|
|
2427
|
+
}
|
|
2428
|
+
function defaultLabel(state) {
|
|
2429
|
+
if (state.kind === "downloading") {
|
|
2430
|
+
if (state.total > 0) {
|
|
2431
|
+
return `Downloading ${state.fetched}/${state.total}\u2026`;
|
|
2432
|
+
}
|
|
2433
|
+
return "Downloading\u2026";
|
|
2434
|
+
}
|
|
2435
|
+
return "Download";
|
|
2436
|
+
}
|
|
2437
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
2438
|
+
0 && (module.exports = {
|
|
2439
|
+
AbortedError,
|
|
2440
|
+
BadRequestError,
|
|
2441
|
+
ClipDownloadButton,
|
|
2442
|
+
ClipPlayer,
|
|
2443
|
+
ConflictError,
|
|
2444
|
+
DEFAULT_PLAYLIST_POLL_SLACK_MS,
|
|
2445
|
+
DecodeError,
|
|
2446
|
+
DisconnectedError,
|
|
2447
|
+
FileRef,
|
|
2448
|
+
InvalidStateError,
|
|
2449
|
+
MessageTooLargeError,
|
|
2450
|
+
NetworkError,
|
|
2451
|
+
NotFoundError,
|
|
2452
|
+
RateLimitedError,
|
|
2453
|
+
Reactor,
|
|
2454
|
+
ReactorError,
|
|
2455
|
+
ReactorProvider,
|
|
2456
|
+
ReactorView,
|
|
2457
|
+
RecorderDisabledError,
|
|
2458
|
+
RecordingError,
|
|
2459
|
+
RequestTimeoutError,
|
|
2460
|
+
ServerError,
|
|
2461
|
+
SessionTerminalError,
|
|
2462
|
+
TransportError,
|
|
2463
|
+
UnauthorizedError,
|
|
2464
|
+
VersionMismatchError,
|
|
2465
|
+
WebcamStream,
|
|
2466
|
+
createPlayableManifestUrl,
|
|
2467
|
+
downloadClipAsFile,
|
|
2468
|
+
fetchPlaylist,
|
|
2469
|
+
isFileRef,
|
|
2470
|
+
normalizeJwtSource,
|
|
2471
|
+
parsePlaylist,
|
|
2472
|
+
useClipDownload,
|
|
2473
|
+
useReactor,
|
|
2474
|
+
useReactorInternalMessage,
|
|
2475
|
+
useReactorMessage,
|
|
2476
|
+
useStats
|
|
2477
|
+
});
|
|
2478
|
+
//# sourceMappingURL=index.cjs.map
|