@reactor-team/js-sdk 2.12.4 → 3.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +211 -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 -1078
- package/dist/index.js +1644 -4103
- 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 +35 -53
- package/LICENSE +0 -201
- package/NOTICE +0 -5
- package/dist/index.d.mts +0 -1360
- package/dist/index.mjs +0 -4805
- package/dist/index.mjs.map +0 -1
package/dist/index.mjs
DELETED
|
@@ -1,4805 +0,0 @@
|
|
|
1
|
-
var __defProp = Object.defineProperty;
|
|
2
|
-
var __defProps = Object.defineProperties;
|
|
3
|
-
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
|
|
4
|
-
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
|
|
5
|
-
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
-
var __propIsEnum = Object.prototype.propertyIsEnumerable;
|
|
7
|
-
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
8
|
-
var __spreadValues = (a, b) => {
|
|
9
|
-
for (var prop in b || (b = {}))
|
|
10
|
-
if (__hasOwnProp.call(b, prop))
|
|
11
|
-
__defNormalProp(a, prop, b[prop]);
|
|
12
|
-
if (__getOwnPropSymbols)
|
|
13
|
-
for (var prop of __getOwnPropSymbols(b)) {
|
|
14
|
-
if (__propIsEnum.call(b, prop))
|
|
15
|
-
__defNormalProp(a, prop, b[prop]);
|
|
16
|
-
}
|
|
17
|
-
return a;
|
|
18
|
-
};
|
|
19
|
-
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
|
|
20
|
-
var __objRest = (source, exclude) => {
|
|
21
|
-
var target = {};
|
|
22
|
-
for (var prop in source)
|
|
23
|
-
if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
|
|
24
|
-
target[prop] = source[prop];
|
|
25
|
-
if (source != null && __getOwnPropSymbols)
|
|
26
|
-
for (var prop of __getOwnPropSymbols(source)) {
|
|
27
|
-
if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
|
|
28
|
-
target[prop] = source[prop];
|
|
29
|
-
}
|
|
30
|
-
return target;
|
|
31
|
-
};
|
|
32
|
-
var __async = (__this, __arguments, generator) => {
|
|
33
|
-
return new Promise((resolve, reject) => {
|
|
34
|
-
var fulfilled = (value) => {
|
|
35
|
-
try {
|
|
36
|
-
step(generator.next(value));
|
|
37
|
-
} catch (e) {
|
|
38
|
-
reject(e);
|
|
39
|
-
}
|
|
40
|
-
};
|
|
41
|
-
var rejected = (value) => {
|
|
42
|
-
try {
|
|
43
|
-
step(generator.throw(value));
|
|
44
|
-
} catch (e) {
|
|
45
|
-
reject(e);
|
|
46
|
-
}
|
|
47
|
-
};
|
|
48
|
-
var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
|
|
49
|
-
step((generator = generator.apply(__this, __arguments)).next());
|
|
50
|
-
});
|
|
51
|
-
};
|
|
52
|
-
|
|
53
|
-
// src/core/FileRef.ts
|
|
54
|
-
var FileRef = class {
|
|
55
|
-
constructor(uploadId, name, mimeType, size) {
|
|
56
|
-
this.uploadId = uploadId;
|
|
57
|
-
this.name = name;
|
|
58
|
-
this.mimeType = mimeType;
|
|
59
|
-
this.size = size;
|
|
60
|
-
/** @internal Marker so sendCommand can detect FileRef values. */
|
|
61
|
-
this.__isFileRef = true;
|
|
62
|
-
}
|
|
63
|
-
};
|
|
64
|
-
|
|
65
|
-
// src/types.ts
|
|
66
|
-
var ConflictError = class extends Error {
|
|
67
|
-
constructor(message) {
|
|
68
|
-
super(message);
|
|
69
|
-
}
|
|
70
|
-
};
|
|
71
|
-
var AbortError = class extends Error {
|
|
72
|
-
constructor(message) {
|
|
73
|
-
super(message);
|
|
74
|
-
}
|
|
75
|
-
};
|
|
76
|
-
function isAbortError(error) {
|
|
77
|
-
return error instanceof AbortError || error instanceof Error && error.name === "AbortError";
|
|
78
|
-
}
|
|
79
|
-
var SessionLostError = class extends Error {
|
|
80
|
-
constructor(message) {
|
|
81
|
-
super(message);
|
|
82
|
-
}
|
|
83
|
-
};
|
|
84
|
-
function isSessionLostError(error) {
|
|
85
|
-
return error instanceof SessionLostError;
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
// src/core/auth.ts
|
|
89
|
-
function normalizeJwtSource(source) {
|
|
90
|
-
if (typeof source === "function") {
|
|
91
|
-
return source;
|
|
92
|
-
}
|
|
93
|
-
return () => source;
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
// src/core/types.ts
|
|
97
|
-
import { z } from "zod";
|
|
98
|
-
|
|
99
|
-
// package.json
|
|
100
|
-
var package_default = {
|
|
101
|
-
name: "@reactor-team/js-sdk",
|
|
102
|
-
version: "2.12.4",
|
|
103
|
-
description: "Reactor JavaScript frontend SDK \u2014 connect React and TypeScript apps to real-time AI video models on Reactor.",
|
|
104
|
-
license: "Apache-2.0",
|
|
105
|
-
repository: {
|
|
106
|
-
type: "git",
|
|
107
|
-
url: "https://github.com/reactor-team/js-sdk.git"
|
|
108
|
-
},
|
|
109
|
-
keywords: [
|
|
110
|
-
"reactor",
|
|
111
|
-
"sdk",
|
|
112
|
-
"frontend",
|
|
113
|
-
"react",
|
|
114
|
-
"webrtc",
|
|
115
|
-
"real-time",
|
|
116
|
-
"video",
|
|
117
|
-
"ai"
|
|
118
|
-
],
|
|
119
|
-
author: "Reactor Technologies, Inc.",
|
|
120
|
-
main: "dist/index.js",
|
|
121
|
-
module: "dist/index.mjs",
|
|
122
|
-
types: "dist/index.d.ts",
|
|
123
|
-
exports: {
|
|
124
|
-
".": {
|
|
125
|
-
types: "./dist/index.d.ts",
|
|
126
|
-
import: "./dist/index.mjs",
|
|
127
|
-
require: "./dist/index.js"
|
|
128
|
-
}
|
|
129
|
-
},
|
|
130
|
-
sideEffects: false,
|
|
131
|
-
engines: {
|
|
132
|
-
node: ">=18"
|
|
133
|
-
},
|
|
134
|
-
files: [
|
|
135
|
-
"dist",
|
|
136
|
-
"README.md",
|
|
137
|
-
"LICENSE",
|
|
138
|
-
"NOTICE"
|
|
139
|
-
],
|
|
140
|
-
scripts: {
|
|
141
|
-
prepack: "cp ../../LICENSE ../../NOTICE .",
|
|
142
|
-
postpack: "rm -f LICENSE NOTICE",
|
|
143
|
-
build: "tsup",
|
|
144
|
-
dev: "tsup --watch",
|
|
145
|
-
test: "vitest run",
|
|
146
|
-
"test:watch": "vitest",
|
|
147
|
-
"test:unit": "vitest run __tests__/unit",
|
|
148
|
-
"test:integration": "vitest run __tests__/integration",
|
|
149
|
-
format: "prettier --write .",
|
|
150
|
-
"format:check": "prettier --check ."
|
|
151
|
-
},
|
|
152
|
-
reactor: {
|
|
153
|
-
apiVersion: 1,
|
|
154
|
-
webrtcVersion: "1.0"
|
|
155
|
-
},
|
|
156
|
-
packageManager: "pnpm@10.12.1",
|
|
157
|
-
dependencies: {
|
|
158
|
-
awaitqueue: "^3.3.0",
|
|
159
|
-
"hls.js": "^1.6.0",
|
|
160
|
-
mp4box: "^2.3.0",
|
|
161
|
-
"sdp-transform": "^3.0.0",
|
|
162
|
-
zod: "^4.4.3"
|
|
163
|
-
},
|
|
164
|
-
peerDependencies: {
|
|
165
|
-
react: "^17.0.0 || ^18.0.0 || ^19.0.0",
|
|
166
|
-
zustand: "^5.0.6"
|
|
167
|
-
},
|
|
168
|
-
devDependencies: {
|
|
169
|
-
"@roamhq/wrtc": "^0.10.0",
|
|
170
|
-
"@types/node": "^25",
|
|
171
|
-
"@types/react": "^19.2.15",
|
|
172
|
-
"@types/sdp-transform": "^2.15.0",
|
|
173
|
-
prettier: "^3.8.4",
|
|
174
|
-
tsup: "^8.5.0",
|
|
175
|
-
typescript: "^6.0.3",
|
|
176
|
-
vitest: "^4.1.7"
|
|
177
|
-
}
|
|
178
|
-
};
|
|
179
|
-
|
|
180
|
-
// src/core/types.ts
|
|
181
|
-
var REACTOR_SDK_VERSION = package_default.version;
|
|
182
|
-
var REACTOR_API_VERSION = package_default.reactor.apiVersion;
|
|
183
|
-
var REACTOR_WEBRTC_VERSION = package_default.reactor.webrtcVersion;
|
|
184
|
-
var REACTOR_SDK_TYPE = "js";
|
|
185
|
-
var API_VERSION_HEADER = "Reactor-API-Version";
|
|
186
|
-
var API_ACCEPT_VERSION_HEADER = "Reactor-API-Accept-Version";
|
|
187
|
-
var WEBRTC_VERSION_HEADER = "Reactor-WebRTC-Version";
|
|
188
|
-
var VERSION_ERROR_CODES = {
|
|
189
|
-
426: "CLIENT_VERSION_TOO_OLD",
|
|
190
|
-
501: "SERVER_VERSION_TOO_OLD"
|
|
191
|
-
};
|
|
192
|
-
var ClientInfoSchema = z.object({
|
|
193
|
-
sdk_version: z.string(),
|
|
194
|
-
sdk_type: z.literal("js")
|
|
195
|
-
});
|
|
196
|
-
var TransportDeclarationSchema = z.object({
|
|
197
|
-
protocol: z.string(),
|
|
198
|
-
version: z.string()
|
|
199
|
-
});
|
|
200
|
-
var TrackCapabilitySchema = z.object({
|
|
201
|
-
name: z.string(),
|
|
202
|
-
kind: z.enum(["video", "audio"]),
|
|
203
|
-
direction: z.enum(["recvonly", "sendonly"])
|
|
204
|
-
});
|
|
205
|
-
var TrackMappingEntrySchema = TrackCapabilitySchema.extend({
|
|
206
|
-
mid: z.string()
|
|
207
|
-
});
|
|
208
|
-
var CreateSessionRequestSchema = z.object({
|
|
209
|
-
model: z.object({ name: z.string() }),
|
|
210
|
-
client_info: ClientInfoSchema,
|
|
211
|
-
supported_transports: z.array(TransportDeclarationSchema),
|
|
212
|
-
extra_args: z.record(z.string(), z.any()).optional()
|
|
213
|
-
});
|
|
214
|
-
var CommandCapabilitySchema = z.object({
|
|
215
|
-
name: z.string(),
|
|
216
|
-
description: z.string(),
|
|
217
|
-
schema: z.record(z.string(), z.any()).optional()
|
|
218
|
-
});
|
|
219
|
-
var CapabilitiesSchema = z.object({
|
|
220
|
-
protocol_version: z.string(),
|
|
221
|
-
tracks: z.array(TrackCapabilitySchema),
|
|
222
|
-
commands: z.array(CommandCapabilitySchema).optional(),
|
|
223
|
-
emission_fps: z.number().nullable().optional()
|
|
224
|
-
});
|
|
225
|
-
var SessionInfoResponseSchema = z.object({
|
|
226
|
-
session_id: z.string(),
|
|
227
|
-
state: z.string(),
|
|
228
|
-
cluster: z.string()
|
|
229
|
-
});
|
|
230
|
-
var CreateSessionResponseSchema = SessionInfoResponseSchema.extend({
|
|
231
|
-
model: z.object({ name: z.string(), version: z.string().optional() }),
|
|
232
|
-
server_info: z.object({ server_version: z.string() })
|
|
233
|
-
});
|
|
234
|
-
var SessionResponseSchema = CreateSessionResponseSchema.extend({
|
|
235
|
-
selected_transport: TransportDeclarationSchema.optional(),
|
|
236
|
-
capabilities: CapabilitiesSchema.optional()
|
|
237
|
-
});
|
|
238
|
-
var TerminateSessionRequestSchema = z.object({
|
|
239
|
-
reason: z.string().optional()
|
|
240
|
-
});
|
|
241
|
-
var CreateUploadRequestSchema = z.object({
|
|
242
|
-
name: z.string(),
|
|
243
|
-
size: z.number().int().positive(),
|
|
244
|
-
mime_type: z.string()
|
|
245
|
-
});
|
|
246
|
-
var CreateUploadResponseSchema = z.object({
|
|
247
|
-
presigned_id: z.string(),
|
|
248
|
-
presigned_url: z.string(),
|
|
249
|
-
path: z.string()
|
|
250
|
-
});
|
|
251
|
-
var IceServerCredentialsSchema = z.object({
|
|
252
|
-
username: z.string(),
|
|
253
|
-
password: z.string()
|
|
254
|
-
});
|
|
255
|
-
var IceServerSchema = z.object({
|
|
256
|
-
uris: z.array(z.string()),
|
|
257
|
-
credentials: IceServerCredentialsSchema.optional()
|
|
258
|
-
});
|
|
259
|
-
var IceServersResponseSchema = z.object({
|
|
260
|
-
ice_servers: z.array(IceServerSchema)
|
|
261
|
-
});
|
|
262
|
-
var WebRTCSdpOfferRequestSchema = z.object({
|
|
263
|
-
sdp_offer: z.string(),
|
|
264
|
-
client_info: ClientInfoSchema.optional(),
|
|
265
|
-
track_mapping: z.array(TrackMappingEntrySchema)
|
|
266
|
-
});
|
|
267
|
-
var WebRTCSdpOfferResponseSchema = z.object({
|
|
268
|
-
connection_id: z.number().optional()
|
|
269
|
-
});
|
|
270
|
-
var WebRTCSdpAnswerResponseSchema = z.object({
|
|
271
|
-
sdp_answer: z.string(),
|
|
272
|
-
connection_id: z.number().optional()
|
|
273
|
-
});
|
|
274
|
-
var IceCandidateSchema = z.object({
|
|
275
|
-
candidate: z.string(),
|
|
276
|
-
sdp_mid: z.string().optional(),
|
|
277
|
-
sdp_mline_index: z.number().optional()
|
|
278
|
-
});
|
|
279
|
-
var IceCandidatesRequestSchema = z.object({
|
|
280
|
-
candidates: z.array(IceCandidateSchema),
|
|
281
|
-
is_final: z.boolean(),
|
|
282
|
-
client_info: ClientInfoSchema.optional()
|
|
283
|
-
});
|
|
284
|
-
|
|
285
|
-
// src/core/CoordinatorClient.ts
|
|
286
|
-
var SESSION_POLL_INITIAL_BACKOFF_MS = 200;
|
|
287
|
-
var SESSION_POLL_MAX_BACKOFF_MS = 1e4;
|
|
288
|
-
var SESSION_POLL_BACKOFF_MULTIPLIER = 2;
|
|
289
|
-
var SESSION_POLL_DEFAULT_MAX_ATTEMPTS = 20;
|
|
290
|
-
var CoordinatorClient = class {
|
|
291
|
-
constructor(options) {
|
|
292
|
-
this.baseUrl = options.baseUrl;
|
|
293
|
-
this.resolveJwt = normalizeJwtSource(options.jwtToken);
|
|
294
|
-
this.model = options.model;
|
|
295
|
-
this.abortController = new AbortController();
|
|
296
|
-
}
|
|
297
|
-
/**
|
|
298
|
-
* Aborts any in-flight HTTP requests.
|
|
299
|
-
* A fresh AbortController is created so the client remains reusable.
|
|
300
|
-
*/
|
|
301
|
-
abort() {
|
|
302
|
-
this.abortController.abort();
|
|
303
|
-
this.abortController = new AbortController();
|
|
304
|
-
}
|
|
305
|
-
/**
|
|
306
|
-
* The current abort signal, passed to every fetch() call.
|
|
307
|
-
* Protected so subclasses can forward it to their own fetch calls.
|
|
308
|
-
*/
|
|
309
|
-
get signal() {
|
|
310
|
-
return this.abortController.signal;
|
|
311
|
-
}
|
|
312
|
-
/**
|
|
313
|
-
* Returns authorization + versioning headers for all coordinator
|
|
314
|
-
* requests. Async so the JWT resolver can fetch a fresh token if
|
|
315
|
-
* needed; an empty token suppresses the `Authorization` header.
|
|
316
|
-
*/
|
|
317
|
-
getHeaders() {
|
|
318
|
-
return __async(this, null, function* () {
|
|
319
|
-
const headers = {
|
|
320
|
-
[API_VERSION_HEADER]: String(REACTOR_API_VERSION),
|
|
321
|
-
[API_ACCEPT_VERSION_HEADER]: String(REACTOR_API_VERSION)
|
|
322
|
-
};
|
|
323
|
-
const jwt = yield this.resolveJwt();
|
|
324
|
-
if (jwt) {
|
|
325
|
-
headers.Authorization = `Bearer ${jwt}`;
|
|
326
|
-
}
|
|
327
|
-
return headers;
|
|
328
|
-
});
|
|
329
|
-
}
|
|
330
|
-
/**
|
|
331
|
-
* Checks an HTTP response for version mismatch errors (426, 501).
|
|
332
|
-
* Logs a clear message and throws with a descriptive error code.
|
|
333
|
-
*/
|
|
334
|
-
checkVersionMismatch(response) {
|
|
335
|
-
return __async(this, null, function* () {
|
|
336
|
-
if (response.status === 426) {
|
|
337
|
-
const msg = `Client API version (${REACTOR_API_VERSION}) is too old. Server requires a newer version. Please upgrade @reactor-team/js-sdk.`;
|
|
338
|
-
console.error(`[Reactor]`, msg);
|
|
339
|
-
throw new Error(`${VERSION_ERROR_CODES[426]}: ${msg}`);
|
|
340
|
-
}
|
|
341
|
-
if (response.status === 501) {
|
|
342
|
-
const msg = `Server does not support API version ${REACTOR_API_VERSION}. The server may need to be updated.`;
|
|
343
|
-
console.error(`[Reactor]`, msg);
|
|
344
|
-
throw new Error(`${VERSION_ERROR_CODES[501]}: ${msg}`);
|
|
345
|
-
}
|
|
346
|
-
});
|
|
347
|
-
}
|
|
348
|
-
sleep(ms) {
|
|
349
|
-
return new Promise((resolve, reject) => {
|
|
350
|
-
const { signal } = this;
|
|
351
|
-
if (signal.aborted) {
|
|
352
|
-
reject(new AbortError("Sleep aborted"));
|
|
353
|
-
return;
|
|
354
|
-
}
|
|
355
|
-
const timer = setTimeout(() => {
|
|
356
|
-
signal.removeEventListener("abort", onAbort);
|
|
357
|
-
resolve();
|
|
358
|
-
}, ms);
|
|
359
|
-
const onAbort = () => {
|
|
360
|
-
clearTimeout(timer);
|
|
361
|
-
reject(new AbortError("Sleep aborted"));
|
|
362
|
-
};
|
|
363
|
-
signal.addEventListener("abort", onAbort, { once: true });
|
|
364
|
-
});
|
|
365
|
-
}
|
|
366
|
-
/**
|
|
367
|
-
* Creates a new session with the coordinator.
|
|
368
|
-
* No SDP is sent — transport signaling is decoupled from session creation.
|
|
369
|
-
*
|
|
370
|
-
* The POST response is a slim acknowledgment (session_id, model name, status).
|
|
371
|
-
* Capabilities and transport details are populated later once the Runtime
|
|
372
|
-
* accepts the session — use {@link pollSessionReady} to wait for them.
|
|
373
|
-
*/
|
|
374
|
-
createSession(extraArgs) {
|
|
375
|
-
return __async(this, null, function* () {
|
|
376
|
-
console.debug("[CoordinatorClient] Creating session...");
|
|
377
|
-
const requestBody = __spreadValues({
|
|
378
|
-
model: { name: this.model },
|
|
379
|
-
client_info: {
|
|
380
|
-
sdk_version: REACTOR_SDK_VERSION,
|
|
381
|
-
sdk_type: REACTOR_SDK_TYPE
|
|
382
|
-
},
|
|
383
|
-
supported_transports: [
|
|
384
|
-
{ protocol: "webrtc", version: REACTOR_WEBRTC_VERSION }
|
|
385
|
-
]
|
|
386
|
-
}, extraArgs ? { extra_args: extraArgs } : {});
|
|
387
|
-
const response = yield fetch(`${this.baseUrl}/sessions`, {
|
|
388
|
-
method: "POST",
|
|
389
|
-
headers: __spreadProps(__spreadValues({}, yield this.getHeaders()), {
|
|
390
|
-
"Content-Type": "application/json"
|
|
391
|
-
}),
|
|
392
|
-
body: JSON.stringify(requestBody),
|
|
393
|
-
signal: this.signal
|
|
394
|
-
});
|
|
395
|
-
yield this.checkVersionMismatch(response);
|
|
396
|
-
if (!response.ok) {
|
|
397
|
-
const errorText = yield response.text();
|
|
398
|
-
throw new Error(
|
|
399
|
-
`Failed to create session: ${response.status} ${errorText}`
|
|
400
|
-
);
|
|
401
|
-
}
|
|
402
|
-
const data = yield response.json();
|
|
403
|
-
const parsed = CreateSessionResponseSchema.parse(data);
|
|
404
|
-
this.currentSessionId = parsed.session_id;
|
|
405
|
-
console.debug(
|
|
406
|
-
"[CoordinatorClient] Session created:",
|
|
407
|
-
this.currentSessionId,
|
|
408
|
-
"state:",
|
|
409
|
-
parsed.state
|
|
410
|
-
);
|
|
411
|
-
return parsed;
|
|
412
|
-
});
|
|
413
|
-
}
|
|
414
|
-
/**
|
|
415
|
-
* Attaches to a session created elsewhere (e.g. by a backend) instead of
|
|
416
|
-
* creating one via {@link createSession}. After this, {@link pollSessionReady}
|
|
417
|
-
* and {@link getSession} operate on the adopted id. The session must be owned
|
|
418
|
-
* by the account behind this client's JWT.
|
|
419
|
-
*/
|
|
420
|
-
adoptSession(sessionId) {
|
|
421
|
-
return __async(this, null, function* () {
|
|
422
|
-
this.currentSessionId = sessionId;
|
|
423
|
-
console.debug("[CoordinatorClient] Adopted existing session:", sessionId);
|
|
424
|
-
});
|
|
425
|
-
}
|
|
426
|
-
/**
|
|
427
|
-
* Polls GET /sessions/{id} until the Runtime has accepted the session
|
|
428
|
-
* and populated capabilities and selected_transport.
|
|
429
|
-
*/
|
|
430
|
-
pollSessionReady(opts) {
|
|
431
|
-
return __async(this, null, function* () {
|
|
432
|
-
var _a;
|
|
433
|
-
if (!this.currentSessionId) {
|
|
434
|
-
throw new Error("No active session. Call createSession() first.");
|
|
435
|
-
}
|
|
436
|
-
const maxAttempts = (_a = opts == null ? void 0 : opts.maxAttempts) != null ? _a : SESSION_POLL_DEFAULT_MAX_ATTEMPTS;
|
|
437
|
-
let backoffMs = SESSION_POLL_INITIAL_BACKOFF_MS;
|
|
438
|
-
let attempt = 0;
|
|
439
|
-
console.debug(
|
|
440
|
-
"[CoordinatorClient] Polling session until capabilities are available..."
|
|
441
|
-
);
|
|
442
|
-
while (true) {
|
|
443
|
-
if (this.signal.aborted) {
|
|
444
|
-
throw new AbortError("Session polling aborted");
|
|
445
|
-
}
|
|
446
|
-
if (attempt >= maxAttempts) {
|
|
447
|
-
throw new Error(
|
|
448
|
-
`Session polling exceeded maximum attempts (${maxAttempts}). The model may be unavailable or overloaded.`
|
|
449
|
-
);
|
|
450
|
-
}
|
|
451
|
-
attempt++;
|
|
452
|
-
const response = yield fetch(
|
|
453
|
-
`${this.baseUrl}/sessions/${this.currentSessionId}`,
|
|
454
|
-
{
|
|
455
|
-
method: "GET",
|
|
456
|
-
headers: yield this.getHeaders(),
|
|
457
|
-
signal: this.signal
|
|
458
|
-
}
|
|
459
|
-
);
|
|
460
|
-
yield this.checkVersionMismatch(response);
|
|
461
|
-
if (!response.ok) {
|
|
462
|
-
const errorText = yield response.text();
|
|
463
|
-
throw new Error(
|
|
464
|
-
`Failed to poll session: ${response.status} ${errorText}`
|
|
465
|
-
);
|
|
466
|
-
}
|
|
467
|
-
const data = yield response.json();
|
|
468
|
-
const partial = SessionResponseSchema.parse(data);
|
|
469
|
-
const terminalStates = [
|
|
470
|
-
"CLOSED" /* CLOSED */,
|
|
471
|
-
"INACTIVE" /* INACTIVE */
|
|
472
|
-
];
|
|
473
|
-
if (terminalStates.includes(partial.state)) {
|
|
474
|
-
throw new Error(
|
|
475
|
-
`Session entered terminal state "${partial.state}" while waiting for capabilities`
|
|
476
|
-
);
|
|
477
|
-
}
|
|
478
|
-
if (partial.capabilities && partial.selected_transport) {
|
|
479
|
-
console.debug(
|
|
480
|
-
`[CoordinatorClient] Session ready after ${attempt} poll(s), transport: ${partial.selected_transport.protocol}, tracks: ${partial.capabilities.tracks.length}`
|
|
481
|
-
);
|
|
482
|
-
return partial;
|
|
483
|
-
}
|
|
484
|
-
console.debug(
|
|
485
|
-
`[CoordinatorClient] Session poll ${attempt}/${maxAttempts} \u2014 state: ${partial.state}, waiting ${backoffMs}ms...`
|
|
486
|
-
);
|
|
487
|
-
yield this.sleep(backoffMs);
|
|
488
|
-
backoffMs = Math.min(
|
|
489
|
-
backoffMs * SESSION_POLL_BACKOFF_MULTIPLIER,
|
|
490
|
-
SESSION_POLL_MAX_BACKOFF_MS
|
|
491
|
-
);
|
|
492
|
-
}
|
|
493
|
-
});
|
|
494
|
-
}
|
|
495
|
-
/**
|
|
496
|
-
* Gets session details from the coordinator.
|
|
497
|
-
* Fields like selected_transport and capabilities are only present
|
|
498
|
-
* after the Runtime accepts the session.
|
|
499
|
-
*/
|
|
500
|
-
getSession() {
|
|
501
|
-
return __async(this, null, function* () {
|
|
502
|
-
if (!this.currentSessionId) {
|
|
503
|
-
throw new Error("No active session. Call createSession() first.");
|
|
504
|
-
}
|
|
505
|
-
const response = yield fetch(
|
|
506
|
-
`${this.baseUrl}/sessions/${this.currentSessionId}`,
|
|
507
|
-
{
|
|
508
|
-
method: "GET",
|
|
509
|
-
headers: yield this.getHeaders(),
|
|
510
|
-
signal: this.signal
|
|
511
|
-
}
|
|
512
|
-
);
|
|
513
|
-
yield this.checkVersionMismatch(response);
|
|
514
|
-
if (!response.ok) {
|
|
515
|
-
const errorText = yield response.text();
|
|
516
|
-
throw new Error(`Failed to get session: ${response.status} ${errorText}`);
|
|
517
|
-
}
|
|
518
|
-
const data = yield response.json();
|
|
519
|
-
return SessionResponseSchema.parse(data);
|
|
520
|
-
});
|
|
521
|
-
}
|
|
522
|
-
/**
|
|
523
|
-
* Gets lightweight session status (session_id, cluster, status).
|
|
524
|
-
*/
|
|
525
|
-
getSessionInfo() {
|
|
526
|
-
return __async(this, null, function* () {
|
|
527
|
-
if (!this.currentSessionId) {
|
|
528
|
-
throw new Error("No active session. Call createSession() first.");
|
|
529
|
-
}
|
|
530
|
-
const response = yield fetch(
|
|
531
|
-
`${this.baseUrl}/sessions/${this.currentSessionId}/info`,
|
|
532
|
-
{
|
|
533
|
-
method: "GET",
|
|
534
|
-
headers: yield this.getHeaders(),
|
|
535
|
-
signal: this.signal
|
|
536
|
-
}
|
|
537
|
-
);
|
|
538
|
-
yield this.checkVersionMismatch(response);
|
|
539
|
-
if (!response.ok) {
|
|
540
|
-
const errorText = yield response.text();
|
|
541
|
-
throw new Error(
|
|
542
|
-
`Failed to get session info: ${response.status} ${errorText}`
|
|
543
|
-
);
|
|
544
|
-
}
|
|
545
|
-
const data = yield response.json();
|
|
546
|
-
return SessionInfoResponseSchema.parse(data);
|
|
547
|
-
});
|
|
548
|
-
}
|
|
549
|
-
/**
|
|
550
|
-
* Restarts an inactive session with a different compute unit.
|
|
551
|
-
* The session ID is preserved but a new transport must be established.
|
|
552
|
-
*/
|
|
553
|
-
restartSession() {
|
|
554
|
-
return __async(this, null, function* () {
|
|
555
|
-
if (!this.currentSessionId) {
|
|
556
|
-
throw new Error("No active session. Call createSession() first.");
|
|
557
|
-
}
|
|
558
|
-
console.debug(
|
|
559
|
-
"[CoordinatorClient] Restarting session:",
|
|
560
|
-
this.currentSessionId
|
|
561
|
-
);
|
|
562
|
-
const response = yield fetch(
|
|
563
|
-
`${this.baseUrl}/sessions/${this.currentSessionId}`,
|
|
564
|
-
{
|
|
565
|
-
method: "PUT",
|
|
566
|
-
headers: yield this.getHeaders(),
|
|
567
|
-
signal: this.signal
|
|
568
|
-
}
|
|
569
|
-
);
|
|
570
|
-
yield this.checkVersionMismatch(response);
|
|
571
|
-
if (!response.ok) {
|
|
572
|
-
const errorText = yield response.text();
|
|
573
|
-
throw new Error(
|
|
574
|
-
`Failed to restart session: ${response.status} ${errorText}`
|
|
575
|
-
);
|
|
576
|
-
}
|
|
577
|
-
});
|
|
578
|
-
}
|
|
579
|
-
/**
|
|
580
|
-
* Terminates the current session by sending a DELETE request.
|
|
581
|
-
* No-op if no session has been created yet.
|
|
582
|
-
* @param reason Optional termination reason
|
|
583
|
-
*/
|
|
584
|
-
terminateSession(reason) {
|
|
585
|
-
return __async(this, null, function* () {
|
|
586
|
-
if (!this.currentSessionId) {
|
|
587
|
-
return;
|
|
588
|
-
}
|
|
589
|
-
console.debug(
|
|
590
|
-
"[CoordinatorClient] Terminating session:",
|
|
591
|
-
this.currentSessionId
|
|
592
|
-
);
|
|
593
|
-
const body = reason ? { reason } : void 0;
|
|
594
|
-
const response = yield fetch(
|
|
595
|
-
`${this.baseUrl}/sessions/${this.currentSessionId}`,
|
|
596
|
-
__spreadProps(__spreadValues({
|
|
597
|
-
method: "DELETE",
|
|
598
|
-
headers: __spreadValues(__spreadValues({}, yield this.getHeaders()), body ? { "Content-Type": "application/json" } : {})
|
|
599
|
-
}, body ? { body: JSON.stringify(body) } : {}), {
|
|
600
|
-
signal: this.signal
|
|
601
|
-
})
|
|
602
|
-
);
|
|
603
|
-
if (response.ok) {
|
|
604
|
-
this.currentSessionId = void 0;
|
|
605
|
-
return;
|
|
606
|
-
}
|
|
607
|
-
if (response.status === 404) {
|
|
608
|
-
console.debug(
|
|
609
|
-
"[CoordinatorClient] Session not found on server, clearing local state:",
|
|
610
|
-
this.currentSessionId
|
|
611
|
-
);
|
|
612
|
-
this.currentSessionId = void 0;
|
|
613
|
-
return;
|
|
614
|
-
}
|
|
615
|
-
const errorText = yield response.text();
|
|
616
|
-
throw new Error(
|
|
617
|
-
`Failed to terminate session: ${response.status} ${errorText}`
|
|
618
|
-
);
|
|
619
|
-
});
|
|
620
|
-
}
|
|
621
|
-
/**
|
|
622
|
-
* Allocates an upload slot for a file.
|
|
623
|
-
* Returns a presigned PUT URL the caller can use to upload the file
|
|
624
|
-
* directly to the object store (production) or local runtime (local dev).
|
|
625
|
-
*/
|
|
626
|
-
createUpload(sessionId, request) {
|
|
627
|
-
return __async(this, null, function* () {
|
|
628
|
-
console.debug("[CoordinatorClient] Creating upload slot...", {
|
|
629
|
-
sessionId,
|
|
630
|
-
name: request.name,
|
|
631
|
-
size: request.size
|
|
632
|
-
});
|
|
633
|
-
const response = yield fetch(
|
|
634
|
-
`${this.baseUrl}/sessions/${sessionId}/uploads`,
|
|
635
|
-
{
|
|
636
|
-
method: "POST",
|
|
637
|
-
headers: __spreadProps(__spreadValues({}, yield this.getHeaders()), {
|
|
638
|
-
"Content-Type": "application/json"
|
|
639
|
-
}),
|
|
640
|
-
body: JSON.stringify(request),
|
|
641
|
-
signal: this.signal
|
|
642
|
-
}
|
|
643
|
-
);
|
|
644
|
-
yield this.checkVersionMismatch(response);
|
|
645
|
-
if (!response.ok) {
|
|
646
|
-
const errorText = yield response.text();
|
|
647
|
-
throw new Error(
|
|
648
|
-
`Failed to create upload slot: ${response.status} ${errorText}`
|
|
649
|
-
);
|
|
650
|
-
}
|
|
651
|
-
const data = yield response.json();
|
|
652
|
-
return CreateUploadResponseSchema.parse(data);
|
|
653
|
-
});
|
|
654
|
-
}
|
|
655
|
-
getSessionId() {
|
|
656
|
-
return this.currentSessionId;
|
|
657
|
-
}
|
|
658
|
-
};
|
|
659
|
-
|
|
660
|
-
// src/core/LocalCoordinatorClient.ts
|
|
661
|
-
var LocalCoordinatorClient = class extends CoordinatorClient {
|
|
662
|
-
constructor(baseUrl, model) {
|
|
663
|
-
super({
|
|
664
|
-
baseUrl,
|
|
665
|
-
jwtToken: "local",
|
|
666
|
-
model
|
|
667
|
-
});
|
|
668
|
-
}
|
|
669
|
-
// Local runtime endpoints are auth-free; skip the Authorization header.
|
|
670
|
-
getHeaders() {
|
|
671
|
-
return __async(this, null, function* () {
|
|
672
|
-
return {
|
|
673
|
-
[API_VERSION_HEADER]: String(REACTOR_API_VERSION),
|
|
674
|
-
[API_ACCEPT_VERSION_HEADER]: String(REACTOR_API_VERSION)
|
|
675
|
-
};
|
|
676
|
-
});
|
|
677
|
-
}
|
|
678
|
-
/**
|
|
679
|
-
* Starts a session on the local runtime.
|
|
680
|
-
*
|
|
681
|
-
* Unlike the production coordinator, the local runtime returns the full
|
|
682
|
-
* response (capabilities, selected_transport) immediately — no polling needed.
|
|
683
|
-
*/
|
|
684
|
-
createSession(extraArgs) {
|
|
685
|
-
return __async(this, null, function* () {
|
|
686
|
-
var _a, _b;
|
|
687
|
-
console.debug("[LocalCoordinatorClient] Starting session...");
|
|
688
|
-
const response = yield fetch(`${this.baseUrl}/start_session`, {
|
|
689
|
-
method: "POST",
|
|
690
|
-
headers: __spreadProps(__spreadValues({}, yield this.getHeaders()), {
|
|
691
|
-
"Content-Type": "application/json"
|
|
692
|
-
}),
|
|
693
|
-
body: JSON.stringify(__spreadValues({}, extraArgs ? { extra_args: extraArgs } : {})),
|
|
694
|
-
signal: this.signal
|
|
695
|
-
});
|
|
696
|
-
if (!response.ok) {
|
|
697
|
-
const errorText = yield response.text();
|
|
698
|
-
if (response.status === 400) {
|
|
699
|
-
throw new SessionLostError(
|
|
700
|
-
`Failed to start session: ${response.status} ${errorText}`
|
|
701
|
-
);
|
|
702
|
-
}
|
|
703
|
-
throw new Error(
|
|
704
|
-
`Failed to start session: ${response.status} ${errorText}`
|
|
705
|
-
);
|
|
706
|
-
}
|
|
707
|
-
const data = yield response.json();
|
|
708
|
-
const session = SessionResponseSchema.parse(data);
|
|
709
|
-
this.cachedSessionResponse = session;
|
|
710
|
-
this.currentSessionId = session.session_id;
|
|
711
|
-
console.debug(
|
|
712
|
-
"[LocalCoordinatorClient] Session started:",
|
|
713
|
-
this.currentSessionId,
|
|
714
|
-
"transport:",
|
|
715
|
-
(_a = session.selected_transport) == null ? void 0 : _a.protocol,
|
|
716
|
-
"tracks:",
|
|
717
|
-
(_b = session.capabilities) == null ? void 0 : _b.tracks.length
|
|
718
|
-
);
|
|
719
|
-
return CreateSessionResponseSchema.parse(data);
|
|
720
|
-
});
|
|
721
|
-
}
|
|
722
|
-
/**
|
|
723
|
-
* Adopts the local session for `connect({ sessionId })`: records the id and
|
|
724
|
-
* reads the session descriptor, caching it so {@link pollSessionReady}
|
|
725
|
-
* returns immediately. No `start_session` is issued.
|
|
726
|
-
*
|
|
727
|
-
* The local runtime hosts a single session (always id `"local"`), so the
|
|
728
|
-
* lookup ignores the specific id. This is a pure read of session info — it
|
|
729
|
-
* does not start or otherwise advance the session.
|
|
730
|
-
*/
|
|
731
|
-
adoptSession(sessionId) {
|
|
732
|
-
return __async(this, null, function* () {
|
|
733
|
-
this.currentSessionId = sessionId;
|
|
734
|
-
this.cachedSessionResponse = yield this.getSession();
|
|
735
|
-
console.debug(
|
|
736
|
-
"[LocalCoordinatorClient] Adopted existing session:",
|
|
737
|
-
sessionId
|
|
738
|
-
);
|
|
739
|
-
});
|
|
740
|
-
}
|
|
741
|
-
/**
|
|
742
|
-
* Reads the local session descriptor (model, capabilities, transport,
|
|
743
|
-
* state) via the runtime's read-only `GET /session`.
|
|
744
|
-
*
|
|
745
|
-
* The local runtime exposes a single session, so — unlike the Coordinator's
|
|
746
|
-
* id-addressed `GET /sessions/{id}` — there is no id in the path. Read-only:
|
|
747
|
-
* it does not start or advance the session.
|
|
748
|
-
*/
|
|
749
|
-
getSession() {
|
|
750
|
-
return __async(this, null, function* () {
|
|
751
|
-
const response = yield fetch(`${this.baseUrl}/session`, {
|
|
752
|
-
method: "GET",
|
|
753
|
-
headers: yield this.getHeaders(),
|
|
754
|
-
signal: this.signal
|
|
755
|
-
});
|
|
756
|
-
if (!response.ok) {
|
|
757
|
-
const errorText = yield response.text();
|
|
758
|
-
throw new Error(`Failed to get session: ${response.status} ${errorText}`);
|
|
759
|
-
}
|
|
760
|
-
const data = yield response.json();
|
|
761
|
-
return SessionResponseSchema.parse(data);
|
|
762
|
-
});
|
|
763
|
-
}
|
|
764
|
-
/**
|
|
765
|
-
* Returns the cached full session response immediately.
|
|
766
|
-
* The local runtime already provided everything in start_session.
|
|
767
|
-
*/
|
|
768
|
-
pollSessionReady() {
|
|
769
|
-
return __async(this, null, function* () {
|
|
770
|
-
if (!this.cachedSessionResponse) {
|
|
771
|
-
throw new Error(
|
|
772
|
-
"No cached session response. Call createSession() first."
|
|
773
|
-
);
|
|
774
|
-
}
|
|
775
|
-
return this.cachedSessionResponse;
|
|
776
|
-
});
|
|
777
|
-
}
|
|
778
|
-
/**
|
|
779
|
-
* Stops the session on the local runtime.
|
|
780
|
-
*/
|
|
781
|
-
terminateSession() {
|
|
782
|
-
return __async(this, null, function* () {
|
|
783
|
-
if (!this.currentSessionId) {
|
|
784
|
-
return;
|
|
785
|
-
}
|
|
786
|
-
console.debug(
|
|
787
|
-
"[LocalCoordinatorClient] Stopping session:",
|
|
788
|
-
this.currentSessionId
|
|
789
|
-
);
|
|
790
|
-
try {
|
|
791
|
-
yield fetch(`${this.baseUrl}/stop_session`, {
|
|
792
|
-
method: "POST",
|
|
793
|
-
headers: yield this.getHeaders(),
|
|
794
|
-
signal: this.signal
|
|
795
|
-
});
|
|
796
|
-
} catch (error) {
|
|
797
|
-
console.error("[LocalCoordinatorClient] Error stopping session:", error);
|
|
798
|
-
}
|
|
799
|
-
this.currentSessionId = void 0;
|
|
800
|
-
this.cachedSessionResponse = void 0;
|
|
801
|
-
});
|
|
802
|
-
}
|
|
803
|
-
};
|
|
804
|
-
|
|
805
|
-
// src/core/WebRTCTransportClient.ts
|
|
806
|
-
import { AwaitQueue } from "awaitqueue";
|
|
807
|
-
|
|
808
|
-
// src/utils/sdp.ts
|
|
809
|
-
import { parse, parsePayloads } from "sdp-transform";
|
|
810
|
-
function sdpLineSeparator(sdp) {
|
|
811
|
-
return sdp.includes("\r\n") ? "\r\n" : "\n";
|
|
812
|
-
}
|
|
813
|
-
function splitSdpLines(sdp) {
|
|
814
|
-
return sdp.split(/\r?\n/);
|
|
815
|
-
}
|
|
816
|
-
function joinSdpLines(lines, sep) {
|
|
817
|
-
return lines.join(sep);
|
|
818
|
-
}
|
|
819
|
-
var DYNAMIC_PT_MIN = 96;
|
|
820
|
-
var DYNAMIC_PT_MAX = 127;
|
|
821
|
-
function isSanitizedVideoCodecRtpmapEncoding(name) {
|
|
822
|
-
const u = name.toUpperCase();
|
|
823
|
-
if (/^(H265|HEVC|HEV1|HVC1)/.test(u)) return true;
|
|
824
|
-
if (/^VP8(\/|$)/.test(u)) return true;
|
|
825
|
-
if (/^VP9(\/|$)/.test(u)) return true;
|
|
826
|
-
if (/^H264(\/|$)/.test(u)) return true;
|
|
827
|
-
return false;
|
|
828
|
-
}
|
|
829
|
-
function isOpusRtpmapEncoding(name) {
|
|
830
|
-
return /^OPUS(\/|$)/i.test(name);
|
|
831
|
-
}
|
|
832
|
-
function mediaMLinePayloadTypes(media) {
|
|
833
|
-
var _a;
|
|
834
|
-
return parsePayloads(String((_a = media.payloads) != null ? _a : ""));
|
|
835
|
-
}
|
|
836
|
-
function collectRtpmap(media) {
|
|
837
|
-
var _a;
|
|
838
|
-
const rtpmap = /* @__PURE__ */ new Map();
|
|
839
|
-
for (const r of (_a = media.rtp) != null ? _a : []) {
|
|
840
|
-
rtpmap.set(Number(r.payload), String(r.codec));
|
|
841
|
-
}
|
|
842
|
-
return rtpmap;
|
|
843
|
-
}
|
|
844
|
-
function collectSanitizedCodecPayloadSet(media) {
|
|
845
|
-
const rtpmap = collectRtpmap(media);
|
|
846
|
-
const tracked = /* @__PURE__ */ new Set();
|
|
847
|
-
if (media.type === "video") {
|
|
848
|
-
for (const [pt, enc] of rtpmap) {
|
|
849
|
-
if (isSanitizedVideoCodecRtpmapEncoding(enc)) tracked.add(pt);
|
|
850
|
-
}
|
|
851
|
-
} else if (media.type === "audio") {
|
|
852
|
-
for (const [pt, enc] of rtpmap) {
|
|
853
|
-
if (isOpusRtpmapEncoding(enc)) tracked.add(pt);
|
|
854
|
-
}
|
|
855
|
-
}
|
|
856
|
-
return tracked.size > 0 ? tracked : null;
|
|
857
|
-
}
|
|
858
|
-
function codecRelocationPriority(enc) {
|
|
859
|
-
const u = (enc != null ? enc : "").toUpperCase();
|
|
860
|
-
if (/^(H265|HEVC|HEV1|HVC1)/.test(u)) return 0;
|
|
861
|
-
if (/^H264(\/|$)/.test(u)) return 1;
|
|
862
|
-
if (/^VP9(\/|$)/.test(u)) return 2;
|
|
863
|
-
if (/^VP8(\/|$)/.test(u)) return 3;
|
|
864
|
-
if (/^OPUS(\/|$)/.test(u)) return 4;
|
|
865
|
-
return 5;
|
|
866
|
-
}
|
|
867
|
-
function sortedRelocate(relocate, rtpmap) {
|
|
868
|
-
return [...relocate].sort(
|
|
869
|
-
(a, b) => codecRelocationPriority(rtpmap.get(a)) - codecRelocationPriority(rtpmap.get(b))
|
|
870
|
-
);
|
|
871
|
-
}
|
|
872
|
-
function remapFmtpConfigForPayloadMap(config, remap) {
|
|
873
|
-
let s = config;
|
|
874
|
-
const pairs = [...remap.entries()].sort((a, b) => b[0] - a[0]);
|
|
875
|
-
for (const [oldP, newP] of pairs) {
|
|
876
|
-
if (oldP === newP) continue;
|
|
877
|
-
s = s.replace(new RegExp(`apt=${oldP}([^0-9]|$)`, "g"), `apt=${newP}$1`);
|
|
878
|
-
}
|
|
879
|
-
return s;
|
|
880
|
-
}
|
|
881
|
-
function computeCodecRemapForMedia(media, forbidden) {
|
|
882
|
-
const remap = /* @__PURE__ */ new Map();
|
|
883
|
-
if (media.type !== "video" && media.type !== "audio") {
|
|
884
|
-
return remap;
|
|
885
|
-
}
|
|
886
|
-
const tracked = collectSanitizedCodecPayloadSet(media);
|
|
887
|
-
if (!tracked) {
|
|
888
|
-
return remap;
|
|
889
|
-
}
|
|
890
|
-
const relocate = [...tracked].filter(
|
|
891
|
-
(p) => p < DYNAMIC_PT_MIN || p > DYNAMIC_PT_MAX || forbidden.has(p)
|
|
892
|
-
);
|
|
893
|
-
if (relocate.length === 0) {
|
|
894
|
-
return remap;
|
|
895
|
-
}
|
|
896
|
-
const rtpmap = collectRtpmap(media);
|
|
897
|
-
const ordered = sortedRelocate(relocate, rtpmap);
|
|
898
|
-
const usedPts = new Set(forbidden);
|
|
899
|
-
for (const p of mediaMLinePayloadTypes(media)) {
|
|
900
|
-
if (p >= DYNAMIC_PT_MIN && p <= DYNAMIC_PT_MAX) usedPts.add(p);
|
|
901
|
-
}
|
|
902
|
-
let candidate = DYNAMIC_PT_MIN;
|
|
903
|
-
for (const oldPt of ordered) {
|
|
904
|
-
while (candidate <= DYNAMIC_PT_MAX && usedPts.has(candidate)) candidate++;
|
|
905
|
-
if (candidate > DYNAMIC_PT_MAX) break;
|
|
906
|
-
remap.set(oldPt, candidate);
|
|
907
|
-
usedPts.add(candidate);
|
|
908
|
-
candidate++;
|
|
909
|
-
}
|
|
910
|
-
return remap;
|
|
911
|
-
}
|
|
912
|
-
function rewriteRtpSavpfMPayloads(mLine, mapPt) {
|
|
913
|
-
if (!/\bRTP\/SAVPF\b/.test(mLine)) {
|
|
914
|
-
return mLine;
|
|
915
|
-
}
|
|
916
|
-
const tokens = mLine.split(/\s+/);
|
|
917
|
-
if (tokens.length < 4) {
|
|
918
|
-
return mLine;
|
|
919
|
-
}
|
|
920
|
-
const head = tokens.slice(0, 3).join(" ");
|
|
921
|
-
const tail = tokens.slice(3).map((t) => /^\d+$/.test(t) ? String(mapPt(Number(t))) : t);
|
|
922
|
-
return `${head} ${tail.join(" ")}`;
|
|
923
|
-
}
|
|
924
|
-
function payloadTypesFromSavpfMLine(mLine) {
|
|
925
|
-
const m = /\bRTP\/SAVPF\s+(.+)$/i.exec(mLine);
|
|
926
|
-
return m ? parsePayloads(m[1].trim()) : [];
|
|
927
|
-
}
|
|
928
|
-
function payloadTypeFromPtBoundAttributeLine(line) {
|
|
929
|
-
if (line.startsWith("a=rtpmap:")) {
|
|
930
|
-
const x = /^a=rtpmap:(\d+)/i.exec(line);
|
|
931
|
-
return x ? Number(x[1]) : null;
|
|
932
|
-
}
|
|
933
|
-
if (line.startsWith("a=fmtp:")) {
|
|
934
|
-
const x = /^a=fmtp:(\d+)/i.exec(line);
|
|
935
|
-
return x ? Number(x[1]) : null;
|
|
936
|
-
}
|
|
937
|
-
if (line.startsWith("a=rtcp-fb:")) {
|
|
938
|
-
const x = /^a=rtcp-fb:(\*|(\d+))/i.exec(line);
|
|
939
|
-
if (!x || x[1] === "*") return null;
|
|
940
|
-
return Number(x[2]);
|
|
941
|
-
}
|
|
942
|
-
if (line.startsWith("a=rtcp-fb-trr-int:")) {
|
|
943
|
-
const x = /^a=rtcp-fb-trr-int:(\*|(\d+))/i.exec(line);
|
|
944
|
-
if (!x || x[1] === "*") return null;
|
|
945
|
-
return Number(x[2]);
|
|
946
|
-
}
|
|
947
|
-
if (line.startsWith("a=imageattrs:")) {
|
|
948
|
-
const x = /^a=imageattrs:(\*|(\d+))/i.exec(line);
|
|
949
|
-
if (!x || x[1] === "*") return null;
|
|
950
|
-
return Number(x[2]);
|
|
951
|
-
}
|
|
952
|
-
return null;
|
|
953
|
-
}
|
|
954
|
-
function isPtBoundCodecAttributeLine(line) {
|
|
955
|
-
return payloadTypeFromPtBoundAttributeLine(line) !== null;
|
|
956
|
-
}
|
|
957
|
-
function reorderSingleRtpSavpfSection(sec) {
|
|
958
|
-
const mLine = sec[0];
|
|
959
|
-
if (!/\bRTP\/SAVPF\b/.test(mLine)) {
|
|
960
|
-
return sec;
|
|
961
|
-
}
|
|
962
|
-
const body = sec.slice(1);
|
|
963
|
-
let first = -1;
|
|
964
|
-
let last = -1;
|
|
965
|
-
for (let j = 0; j < body.length; j++) {
|
|
966
|
-
if (isPtBoundCodecAttributeLine(body[j])) {
|
|
967
|
-
if (first === -1) first = j;
|
|
968
|
-
last = j;
|
|
969
|
-
}
|
|
970
|
-
}
|
|
971
|
-
if (first === -1) {
|
|
972
|
-
return sec;
|
|
973
|
-
}
|
|
974
|
-
const prefix = body.slice(0, first);
|
|
975
|
-
const codecLines = body.slice(first, last + 1);
|
|
976
|
-
const suffix = body.slice(last + 1);
|
|
977
|
-
const mPts = payloadTypesFromSavpfMLine(mLine);
|
|
978
|
-
const buckets = /* @__PURE__ */ new Map();
|
|
979
|
-
for (const line of codecLines) {
|
|
980
|
-
const pt = payloadTypeFromPtBoundAttributeLine(line);
|
|
981
|
-
if (pt === null) continue;
|
|
982
|
-
const arr = buckets.get(pt);
|
|
983
|
-
if (arr) arr.push(line);
|
|
984
|
-
else buckets.set(pt, [line]);
|
|
985
|
-
}
|
|
986
|
-
const seenOrder = [];
|
|
987
|
-
for (const line of codecLines) {
|
|
988
|
-
const pt = payloadTypeFromPtBoundAttributeLine(line);
|
|
989
|
-
if (pt !== null && !seenOrder.includes(pt)) seenOrder.push(pt);
|
|
990
|
-
}
|
|
991
|
-
const outCodec = [];
|
|
992
|
-
for (const pt of mPts) {
|
|
993
|
-
const arr = buckets.get(pt);
|
|
994
|
-
if (!arr) continue;
|
|
995
|
-
outCodec.push(...arr);
|
|
996
|
-
buckets.delete(pt);
|
|
997
|
-
}
|
|
998
|
-
for (const pt of seenOrder) {
|
|
999
|
-
const arr = buckets.get(pt);
|
|
1000
|
-
if (!arr) continue;
|
|
1001
|
-
outCodec.push(...arr);
|
|
1002
|
-
buckets.delete(pt);
|
|
1003
|
-
}
|
|
1004
|
-
for (const arr of buckets.values()) {
|
|
1005
|
-
outCodec.push(...arr);
|
|
1006
|
-
}
|
|
1007
|
-
return [mLine, ...prefix, ...outCodec, ...suffix];
|
|
1008
|
-
}
|
|
1009
|
-
function reorderCodecAttributes(sdp) {
|
|
1010
|
-
const sep = sdpLineSeparator(sdp);
|
|
1011
|
-
const lines = splitSdpLines(sdp);
|
|
1012
|
-
const out = [];
|
|
1013
|
-
let i = 0;
|
|
1014
|
-
while (i < lines.length) {
|
|
1015
|
-
const line = lines[i];
|
|
1016
|
-
if (!line.startsWith("m=")) {
|
|
1017
|
-
out.push(line);
|
|
1018
|
-
i++;
|
|
1019
|
-
continue;
|
|
1020
|
-
}
|
|
1021
|
-
const mLine = line;
|
|
1022
|
-
i++;
|
|
1023
|
-
const rest = [];
|
|
1024
|
-
while (i < lines.length && !lines[i].startsWith("m=")) {
|
|
1025
|
-
rest.push(lines[i]);
|
|
1026
|
-
i++;
|
|
1027
|
-
}
|
|
1028
|
-
out.push(...reorderSingleRtpSavpfSection([mLine, ...rest]));
|
|
1029
|
-
}
|
|
1030
|
-
return joinSdpLines(out, sep);
|
|
1031
|
-
}
|
|
1032
|
-
function applyRemapToMediaAttributeLine(line, remap) {
|
|
1033
|
-
var _a, _b, _c, _d, _e, _f, _g, _h;
|
|
1034
|
-
if (!line.startsWith("a=")) {
|
|
1035
|
-
return line;
|
|
1036
|
-
}
|
|
1037
|
-
if (line.startsWith("a=rtpmap:")) {
|
|
1038
|
-
const m = /^a=rtpmap:(\d+)/.exec(line);
|
|
1039
|
-
if (!m) return line;
|
|
1040
|
-
const pt = Number(m[1]);
|
|
1041
|
-
const np = (_a = remap.get(pt)) != null ? _a : pt;
|
|
1042
|
-
return np === pt ? line : line.replace(/^a=rtpmap:\d+/, `a=rtpmap:${np}`);
|
|
1043
|
-
}
|
|
1044
|
-
if (line.startsWith("a=fmtp:")) {
|
|
1045
|
-
const m = /^a=fmtp:(\d+)\s(.*)$/.exec(line);
|
|
1046
|
-
if (!m) return line;
|
|
1047
|
-
const pt = Number(m[1]);
|
|
1048
|
-
const np = (_b = remap.get(pt)) != null ? _b : pt;
|
|
1049
|
-
const cfg = remapFmtpConfigForPayloadMap(m[2], remap);
|
|
1050
|
-
return `a=fmtp:${np} ${cfg}`;
|
|
1051
|
-
}
|
|
1052
|
-
if (line.startsWith("a=rtcp-fb:")) {
|
|
1053
|
-
const m = /^a=rtcp-fb:(\*|\d+)(\s.*)?$/.exec(line);
|
|
1054
|
-
if (!m || m[1] === "*") return line;
|
|
1055
|
-
const pt = Number(m[1]);
|
|
1056
|
-
const np = (_c = remap.get(pt)) != null ? _c : pt;
|
|
1057
|
-
return np === pt ? line : `a=rtcp-fb:${np}${(_d = m[2]) != null ? _d : ""}`;
|
|
1058
|
-
}
|
|
1059
|
-
if (line.startsWith("a=rtcp-fb-trr-int:")) {
|
|
1060
|
-
const m = /^a=rtcp-fb-trr-int:(\*|\d+)(\s.*)?$/.exec(line);
|
|
1061
|
-
if (!m || m[1] === "*") return line;
|
|
1062
|
-
const pt = Number(m[1]);
|
|
1063
|
-
const np = (_e = remap.get(pt)) != null ? _e : pt;
|
|
1064
|
-
return np === pt ? line : `a=rtcp-fb-trr-int:${np}${(_f = m[2]) != null ? _f : ""}`;
|
|
1065
|
-
}
|
|
1066
|
-
if (line.startsWith("a=imageattrs:")) {
|
|
1067
|
-
const m = /^a=imageattrs:(\*|\d+)(\s.*)?$/.exec(line);
|
|
1068
|
-
if (!m || m[1] === "*") return line;
|
|
1069
|
-
const pt = Number(m[1]);
|
|
1070
|
-
const np = (_g = remap.get(pt)) != null ? _g : pt;
|
|
1071
|
-
return np === pt ? line : `a=imageattrs:${np}${(_h = m[2]) != null ? _h : ""}`;
|
|
1072
|
-
}
|
|
1073
|
-
return line;
|
|
1074
|
-
}
|
|
1075
|
-
function stripTelephoneEventsPreserveOrder(sdp) {
|
|
1076
|
-
const session = parse(sdp);
|
|
1077
|
-
const telPerSection = session.media.map((media) => {
|
|
1078
|
-
var _a;
|
|
1079
|
-
const tel = /* @__PURE__ */ new Set();
|
|
1080
|
-
for (const r of (_a = media.rtp) != null ? _a : []) {
|
|
1081
|
-
if (/^telephone-event$/i.test(String(r.codec))) {
|
|
1082
|
-
tel.add(Number(r.payload));
|
|
1083
|
-
}
|
|
1084
|
-
}
|
|
1085
|
-
return tel;
|
|
1086
|
-
});
|
|
1087
|
-
if (!telPerSection.some((s) => s.size > 0)) {
|
|
1088
|
-
return sdp;
|
|
1089
|
-
}
|
|
1090
|
-
const sep = sdpLineSeparator(sdp);
|
|
1091
|
-
const lines = splitSdpLines(sdp);
|
|
1092
|
-
let secIdx = -1;
|
|
1093
|
-
const out = [];
|
|
1094
|
-
for (const line of lines) {
|
|
1095
|
-
if (line.startsWith("m=")) {
|
|
1096
|
-
secIdx++;
|
|
1097
|
-
const drop = telPerSection[secIdx];
|
|
1098
|
-
if (!drop || drop.size === 0 || !/\bRTP\/SAVPF\b/.test(line)) {
|
|
1099
|
-
out.push(line);
|
|
1100
|
-
continue;
|
|
1101
|
-
}
|
|
1102
|
-
const tokens = line.split(/\s+/);
|
|
1103
|
-
const head = tokens.slice(0, 3).join(" ");
|
|
1104
|
-
const nums = tokens.slice(3).filter((t) => /^\d+$/.test(t)).map(Number).filter((p) => !drop.has(p));
|
|
1105
|
-
out.push(`${head} ${nums.join(" ")}`);
|
|
1106
|
-
continue;
|
|
1107
|
-
}
|
|
1108
|
-
if (secIdx >= 0) {
|
|
1109
|
-
const drop = telPerSection[secIdx];
|
|
1110
|
-
if (drop && drop.size > 0) {
|
|
1111
|
-
const rtp = /^a=rtpmap:(\d+)\s/i.exec(line);
|
|
1112
|
-
if (rtp && drop.has(Number(rtp[1]))) continue;
|
|
1113
|
-
const fmtp = /^a=fmtp:(\d+)\s/i.exec(line);
|
|
1114
|
-
if (fmtp && drop.has(Number(fmtp[1]))) continue;
|
|
1115
|
-
const rfb = /^a=rtcp-fb:(\d+)\s/i.exec(line);
|
|
1116
|
-
if (rfb && drop.has(Number(rfb[1]))) continue;
|
|
1117
|
-
const trr = /^a=rtcp-fb-trr-int:(\d+)\s/i.exec(line);
|
|
1118
|
-
if (trr && drop.has(Number(trr[1]))) continue;
|
|
1119
|
-
}
|
|
1120
|
-
}
|
|
1121
|
-
out.push(line);
|
|
1122
|
-
}
|
|
1123
|
-
return joinSdpLines(out, sep);
|
|
1124
|
-
}
|
|
1125
|
-
function transformOfferSdpCodecDynamicPts(sdp) {
|
|
1126
|
-
var _a;
|
|
1127
|
-
const session = parse(sdp);
|
|
1128
|
-
if (!session.media.some((m) => collectSanitizedCodecPayloadSet(m) !== null)) {
|
|
1129
|
-
return sdp;
|
|
1130
|
-
}
|
|
1131
|
-
const remaps = [];
|
|
1132
|
-
const forbidden = /* @__PURE__ */ new Set();
|
|
1133
|
-
for (const media of session.media) {
|
|
1134
|
-
const R = computeCodecRemapForMedia(media, forbidden);
|
|
1135
|
-
remaps.push(R);
|
|
1136
|
-
for (const p of mediaMLinePayloadTypes(media)) {
|
|
1137
|
-
forbidden.add((_a = R.get(p)) != null ? _a : p);
|
|
1138
|
-
}
|
|
1139
|
-
}
|
|
1140
|
-
const sep = sdpLineSeparator(sdp);
|
|
1141
|
-
const lines = splitSdpLines(sdp);
|
|
1142
|
-
let secIdx = -1;
|
|
1143
|
-
const out = [];
|
|
1144
|
-
for (let line of lines) {
|
|
1145
|
-
if (line.startsWith("m=")) {
|
|
1146
|
-
secIdx++;
|
|
1147
|
-
const R2 = remaps[secIdx];
|
|
1148
|
-
if (R2.size > 0 && /\bRTP\/SAVPF\b/.test(line)) {
|
|
1149
|
-
line = rewriteRtpSavpfMPayloads(line, (p) => {
|
|
1150
|
-
var _a2;
|
|
1151
|
-
return (_a2 = R2.get(p)) != null ? _a2 : p;
|
|
1152
|
-
});
|
|
1153
|
-
}
|
|
1154
|
-
out.push(line);
|
|
1155
|
-
continue;
|
|
1156
|
-
}
|
|
1157
|
-
const R = secIdx >= 0 ? remaps[secIdx] : null;
|
|
1158
|
-
if (!R || R.size === 0) {
|
|
1159
|
-
out.push(line);
|
|
1160
|
-
continue;
|
|
1161
|
-
}
|
|
1162
|
-
out.push(applyRemapToMediaAttributeLine(line, R));
|
|
1163
|
-
}
|
|
1164
|
-
return joinSdpLines(out, sep);
|
|
1165
|
-
}
|
|
1166
|
-
function sanitize(sdp) {
|
|
1167
|
-
const stripped = stripTelephoneEventsPreserveOrder(sdp);
|
|
1168
|
-
const remapped = transformOfferSdpCodecDynamicPts(stripped);
|
|
1169
|
-
return reorderCodecAttributes(remapped);
|
|
1170
|
-
}
|
|
1171
|
-
|
|
1172
|
-
// src/utils/webrtc.ts
|
|
1173
|
-
var DEFAULT_DATA_CHANNEL_LABEL = "data";
|
|
1174
|
-
var FORCE_RELAY_MODE = false;
|
|
1175
|
-
var DEFAULT_MAX_MESSAGE_BYTES = 256 * 1024;
|
|
1176
|
-
function createPeerConnection(config) {
|
|
1177
|
-
return new RTCPeerConnection({
|
|
1178
|
-
iceServers: config.iceServers,
|
|
1179
|
-
iceTransportPolicy: FORCE_RELAY_MODE ? "relay" : "all"
|
|
1180
|
-
});
|
|
1181
|
-
}
|
|
1182
|
-
function createDataChannel(pc, label) {
|
|
1183
|
-
return pc.createDataChannel(label != null ? label : DEFAULT_DATA_CHANNEL_LABEL);
|
|
1184
|
-
}
|
|
1185
|
-
function createOffer(pc) {
|
|
1186
|
-
return __async(this, null, function* () {
|
|
1187
|
-
var _a;
|
|
1188
|
-
const initial = yield pc.createOffer();
|
|
1189
|
-
const sdp = sanitize((_a = initial.sdp) != null ? _a : "");
|
|
1190
|
-
yield pc.setLocalDescription(
|
|
1191
|
-
new RTCSessionDescription({ type: initial.type, sdp })
|
|
1192
|
-
);
|
|
1193
|
-
const localDescription = pc.localDescription;
|
|
1194
|
-
if (!localDescription) {
|
|
1195
|
-
throw new Error("Failed to create local description");
|
|
1196
|
-
}
|
|
1197
|
-
return localDescription.sdp;
|
|
1198
|
-
});
|
|
1199
|
-
}
|
|
1200
|
-
function setRemoteDescription(pc, sdp) {
|
|
1201
|
-
return __async(this, null, function* () {
|
|
1202
|
-
const sessionDescription = new RTCSessionDescription({
|
|
1203
|
-
sdp,
|
|
1204
|
-
type: "answer"
|
|
1205
|
-
});
|
|
1206
|
-
yield pc.setRemoteDescription(sessionDescription);
|
|
1207
|
-
});
|
|
1208
|
-
}
|
|
1209
|
-
function transformIceServers(response) {
|
|
1210
|
-
return response.ice_servers.map((server) => {
|
|
1211
|
-
const rtcServer = {
|
|
1212
|
-
urls: server.uris
|
|
1213
|
-
};
|
|
1214
|
-
if (server.credentials) {
|
|
1215
|
-
rtcServer.username = server.credentials.username;
|
|
1216
|
-
rtcServer.credential = server.credentials.password;
|
|
1217
|
-
}
|
|
1218
|
-
return rtcServer;
|
|
1219
|
-
});
|
|
1220
|
-
}
|
|
1221
|
-
function sendMessage(channel, command, data, scope = "application", maxBytes = DEFAULT_MAX_MESSAGE_BYTES, uploads) {
|
|
1222
|
-
if (channel.readyState !== "open") {
|
|
1223
|
-
throw new Error(`Data channel not open: ${channel.readyState}`);
|
|
1224
|
-
}
|
|
1225
|
-
const jsonData = typeof data === "string" ? JSON.parse(data) : data;
|
|
1226
|
-
const inner = { type: command, data: jsonData };
|
|
1227
|
-
if (uploads && Object.keys(uploads).length > 0) {
|
|
1228
|
-
inner.uploads = uploads;
|
|
1229
|
-
}
|
|
1230
|
-
const payload = { scope, data: inner };
|
|
1231
|
-
const serialized = JSON.stringify(payload);
|
|
1232
|
-
const byteLength = new TextEncoder().encode(serialized).byteLength;
|
|
1233
|
-
if (byteLength > maxBytes) {
|
|
1234
|
-
throw new Error(
|
|
1235
|
-
`Data channel message too large: ${byteLength} bytes exceeds limit of ${maxBytes} bytes (command: "${command}")`
|
|
1236
|
-
);
|
|
1237
|
-
}
|
|
1238
|
-
channel.send(serialized);
|
|
1239
|
-
}
|
|
1240
|
-
function parseMessage(data) {
|
|
1241
|
-
if (typeof data === "string") {
|
|
1242
|
-
try {
|
|
1243
|
-
return JSON.parse(data);
|
|
1244
|
-
} catch (e) {
|
|
1245
|
-
return data;
|
|
1246
|
-
}
|
|
1247
|
-
}
|
|
1248
|
-
return data;
|
|
1249
|
-
}
|
|
1250
|
-
function complementDirection(direction) {
|
|
1251
|
-
if (direction === "sendonly") return "recvonly";
|
|
1252
|
-
if (direction === "recvonly") return "sendonly";
|
|
1253
|
-
return direction;
|
|
1254
|
-
}
|
|
1255
|
-
function replaceSdpDirectionForMid(sdp, mid, direction) {
|
|
1256
|
-
const [session, ...mediaSections] = sdp.split(/(?=\r\nm=)/);
|
|
1257
|
-
const updated = mediaSections.map((section) => {
|
|
1258
|
-
if (!section.includes(`\r
|
|
1259
|
-
a=mid:${mid}\r
|
|
1260
|
-
`)) return section;
|
|
1261
|
-
return section.replace(
|
|
1262
|
-
/\r\na=(sendonly|recvonly|sendrecv|inactive)\r\n/,
|
|
1263
|
-
`\r
|
|
1264
|
-
a=${direction}\r
|
|
1265
|
-
`
|
|
1266
|
-
);
|
|
1267
|
-
});
|
|
1268
|
-
return session + updated.join("");
|
|
1269
|
-
}
|
|
1270
|
-
function closePeerConnection(pc) {
|
|
1271
|
-
pc.close();
|
|
1272
|
-
}
|
|
1273
|
-
function createRTCStatsExtractor() {
|
|
1274
|
-
let lastBytesReceived;
|
|
1275
|
-
let lastBytesSent;
|
|
1276
|
-
let lastCandPairTimestamp;
|
|
1277
|
-
return (report) => {
|
|
1278
|
-
let candPairId;
|
|
1279
|
-
let rtt;
|
|
1280
|
-
let availableOutgoingBitrate;
|
|
1281
|
-
let availableIncomingBitrate;
|
|
1282
|
-
let incomingBitrate;
|
|
1283
|
-
let outgoingBitrate;
|
|
1284
|
-
let videoInboundRtpId;
|
|
1285
|
-
let framesPerSecond;
|
|
1286
|
-
let jitter;
|
|
1287
|
-
let packetLossRatio;
|
|
1288
|
-
let candidateType;
|
|
1289
|
-
report.forEach((stat) => {
|
|
1290
|
-
if (candPairId === void 0 && stat.type === "candidate-pair" && stat.state === "succeeded" && stat.nominated) {
|
|
1291
|
-
candPairId = stat.id;
|
|
1292
|
-
if (stat.currentRoundTripTime !== void 0) {
|
|
1293
|
-
rtt = stat.currentRoundTripTime * 1e3;
|
|
1294
|
-
}
|
|
1295
|
-
if (stat.availableOutgoingBitrate !== void 0) {
|
|
1296
|
-
availableOutgoingBitrate = stat.availableOutgoingBitrate;
|
|
1297
|
-
}
|
|
1298
|
-
if (stat.availableIncomingBitrate != void 0) {
|
|
1299
|
-
availableIncomingBitrate = stat.availableIncomingBitrate;
|
|
1300
|
-
}
|
|
1301
|
-
const localCandidate = report.get(stat.localCandidateId);
|
|
1302
|
-
if (localCandidate == null ? void 0 : localCandidate.candidateType) {
|
|
1303
|
-
candidateType = localCandidate.candidateType;
|
|
1304
|
-
}
|
|
1305
|
-
const timeDiff = lastCandPairTimestamp !== void 0 ? stat.timestamp - lastCandPairTimestamp : 0;
|
|
1306
|
-
if (stat.bytesReceived !== void 0) {
|
|
1307
|
-
if (lastBytesReceived !== void 0 && timeDiff > 0) {
|
|
1308
|
-
incomingBitrate = (stat.bytesReceived - lastBytesReceived) * 8 / timeDiff * 1e3;
|
|
1309
|
-
}
|
|
1310
|
-
lastBytesReceived = stat.bytesReceived;
|
|
1311
|
-
}
|
|
1312
|
-
if (stat.bytesSent !== void 0) {
|
|
1313
|
-
if (lastBytesSent !== void 0 && timeDiff > 0) {
|
|
1314
|
-
outgoingBitrate = (stat.bytesSent - lastBytesSent) * 8 / timeDiff * 1e3;
|
|
1315
|
-
}
|
|
1316
|
-
lastBytesSent = stat.bytesSent;
|
|
1317
|
-
}
|
|
1318
|
-
lastCandPairTimestamp = stat.timestamp;
|
|
1319
|
-
}
|
|
1320
|
-
if (videoInboundRtpId === void 0 && stat.type === "inbound-rtp" && stat.kind === "video") {
|
|
1321
|
-
videoInboundRtpId = stat.id;
|
|
1322
|
-
if (stat.framesPerSecond !== void 0) {
|
|
1323
|
-
framesPerSecond = stat.framesPerSecond;
|
|
1324
|
-
}
|
|
1325
|
-
if (stat.jitter !== void 0) {
|
|
1326
|
-
jitter = stat.jitter;
|
|
1327
|
-
}
|
|
1328
|
-
if (stat.packetsReceived !== void 0 && stat.packetsLost !== void 0 && stat.packetsReceived + stat.packetsLost > 0) {
|
|
1329
|
-
packetLossRatio = stat.packetsLost / (stat.packetsReceived + stat.packetsLost);
|
|
1330
|
-
}
|
|
1331
|
-
}
|
|
1332
|
-
});
|
|
1333
|
-
return {
|
|
1334
|
-
rtt,
|
|
1335
|
-
candidateType,
|
|
1336
|
-
availableIncomingBitrate,
|
|
1337
|
-
availableOutgoingBitrate,
|
|
1338
|
-
incomingBitrate,
|
|
1339
|
-
outgoingBitrate,
|
|
1340
|
-
framesPerSecond,
|
|
1341
|
-
packetLossRatio,
|
|
1342
|
-
jitter,
|
|
1343
|
-
timestamp: Date.now()
|
|
1344
|
-
};
|
|
1345
|
-
};
|
|
1346
|
-
}
|
|
1347
|
-
|
|
1348
|
-
// src/core/WebRTCTransportClient.ts
|
|
1349
|
-
var PING_INTERVAL_MS = 5e3;
|
|
1350
|
-
var STATS_INTERVAL_MS = 2e3;
|
|
1351
|
-
var INITIAL_BACKOFF_MS = 200;
|
|
1352
|
-
var MAX_BACKOFF_MS = 15e3;
|
|
1353
|
-
var BACKOFF_MULTIPLIER = 2;
|
|
1354
|
-
var DEFAULT_MAX_POLL_ATTEMPTS = 6;
|
|
1355
|
-
var MIN_CONNECTION_ID = 1e3;
|
|
1356
|
-
var MAX_CONNECTION_ID = 9999;
|
|
1357
|
-
var ICE_CANDIDATE_BATCH_WINDOW_MS = 25;
|
|
1358
|
-
var WebRTCTransportClient = class {
|
|
1359
|
-
constructor(config) {
|
|
1360
|
-
this.eventListeners = /* @__PURE__ */ new Map();
|
|
1361
|
-
this.status = "disconnected";
|
|
1362
|
-
this.transceiverMap = /* @__PURE__ */ new Map();
|
|
1363
|
-
this.publishedTracks = /* @__PURE__ */ new Map();
|
|
1364
|
-
// Serializes all SDP renegotiations (pause/resume direction changes) and gates
|
|
1365
|
-
// them behind the connection-ready task. Reset on each prepare() call.
|
|
1366
|
-
this.peerConnectionQueue = new AwaitQueue();
|
|
1367
|
-
this.pendingControlRequests = /* @__PURE__ */ new Map();
|
|
1368
|
-
this.controlRequestCounter = 0;
|
|
1369
|
-
this.peerConnected = false;
|
|
1370
|
-
this.dataChannelOpen = false;
|
|
1371
|
-
this.controlChannelOpen = false;
|
|
1372
|
-
// Trickle ICE batching
|
|
1373
|
-
this.pendingIceCandidates = [];
|
|
1374
|
-
var _a, _b;
|
|
1375
|
-
this.baseUrl = config.baseUrl;
|
|
1376
|
-
this.sessionId = config.sessionId;
|
|
1377
|
-
this.resolveJwt = normalizeJwtSource(config.jwtToken);
|
|
1378
|
-
this.webrtcVersion = (_a = config.webrtcVersion) != null ? _a : REACTOR_WEBRTC_VERSION;
|
|
1379
|
-
this.maxPollAttempts = (_b = config.maxPollAttempts) != null ? _b : DEFAULT_MAX_POLL_ATTEMPTS;
|
|
1380
|
-
this.abortController = new AbortController();
|
|
1381
|
-
}
|
|
1382
|
-
// ─────────────────────────────────────────────────────────────────────────
|
|
1383
|
-
// Event Emitter
|
|
1384
|
-
// ─────────────────────────────────────────────────────────────────────────
|
|
1385
|
-
on(event, handler) {
|
|
1386
|
-
if (!this.eventListeners.has(event)) {
|
|
1387
|
-
this.eventListeners.set(event, /* @__PURE__ */ new Set());
|
|
1388
|
-
}
|
|
1389
|
-
this.eventListeners.get(event).add(handler);
|
|
1390
|
-
}
|
|
1391
|
-
off(event, handler) {
|
|
1392
|
-
var _a;
|
|
1393
|
-
(_a = this.eventListeners.get(event)) == null ? void 0 : _a.delete(handler);
|
|
1394
|
-
}
|
|
1395
|
-
emit(event, ...args) {
|
|
1396
|
-
var _a;
|
|
1397
|
-
(_a = this.eventListeners.get(event)) == null ? void 0 : _a.forEach((handler) => handler(...args));
|
|
1398
|
-
}
|
|
1399
|
-
// ─────────────────────────────────────────────────────────────────────────
|
|
1400
|
-
// HTTP Helpers
|
|
1401
|
-
// ─────────────────────────────────────────────────────────────────────────
|
|
1402
|
-
get signal() {
|
|
1403
|
-
return this.abortController.signal;
|
|
1404
|
-
}
|
|
1405
|
-
get transportBaseUrl() {
|
|
1406
|
-
return `${this.baseUrl}/sessions/${this.sessionId}/transport/webrtc`;
|
|
1407
|
-
}
|
|
1408
|
-
// Async so the JWT resolver can fetch a fresh token if needed; an
|
|
1409
|
-
// empty token suppresses the `Authorization` header.
|
|
1410
|
-
getHeaders() {
|
|
1411
|
-
return __async(this, null, function* () {
|
|
1412
|
-
const headers = {
|
|
1413
|
-
[WEBRTC_VERSION_HEADER]: this.webrtcVersion
|
|
1414
|
-
};
|
|
1415
|
-
const jwt = yield this.resolveJwt();
|
|
1416
|
-
if (jwt) {
|
|
1417
|
-
headers.Authorization = `Bearer ${jwt}`;
|
|
1418
|
-
}
|
|
1419
|
-
return headers;
|
|
1420
|
-
});
|
|
1421
|
-
}
|
|
1422
|
-
checkVersionMismatch(response) {
|
|
1423
|
-
return __async(this, null, function* () {
|
|
1424
|
-
if (response.status === 426) {
|
|
1425
|
-
const msg = `Client WebRTC version (${this.webrtcVersion}) is too old. Server requires a newer version. Please upgrade @reactor-team/js-sdk.`;
|
|
1426
|
-
console.error(`[WebRTCTransport]`, msg);
|
|
1427
|
-
throw new Error(`${VERSION_ERROR_CODES[426]}: ${msg}`);
|
|
1428
|
-
}
|
|
1429
|
-
if (response.status === 501) {
|
|
1430
|
-
const msg = `Server does not support WebRTC version ${this.webrtcVersion}. The server may need to be updated.`;
|
|
1431
|
-
console.error(`[WebRTCTransport]`, msg);
|
|
1432
|
-
throw new Error(`${VERSION_ERROR_CODES[501]}: ${msg}`);
|
|
1433
|
-
}
|
|
1434
|
-
});
|
|
1435
|
-
}
|
|
1436
|
-
sleep(ms) {
|
|
1437
|
-
return new Promise((resolve, reject) => {
|
|
1438
|
-
const { signal } = this;
|
|
1439
|
-
if (signal.aborted) {
|
|
1440
|
-
reject(new AbortError("Sleep aborted"));
|
|
1441
|
-
return;
|
|
1442
|
-
}
|
|
1443
|
-
const timer = setTimeout(() => {
|
|
1444
|
-
signal.removeEventListener("abort", onAbort);
|
|
1445
|
-
resolve();
|
|
1446
|
-
}, ms);
|
|
1447
|
-
const onAbort = () => {
|
|
1448
|
-
clearTimeout(timer);
|
|
1449
|
-
reject(new AbortError("Sleep aborted"));
|
|
1450
|
-
};
|
|
1451
|
-
signal.addEventListener("abort", onAbort, { once: true });
|
|
1452
|
-
});
|
|
1453
|
-
}
|
|
1454
|
-
// ─────────────────────────────────────────────────────────────────────────
|
|
1455
|
-
// Transport Signaling (HTTP)
|
|
1456
|
-
// ─────────────────────────────────────────────────────────────────────────
|
|
1457
|
-
fetchIceServers() {
|
|
1458
|
-
return __async(this, null, function* () {
|
|
1459
|
-
console.debug("[WebRTCTransport] Fetching ICE servers...");
|
|
1460
|
-
const response = yield fetch(`${this.transportBaseUrl}/ice_servers`, {
|
|
1461
|
-
method: "GET",
|
|
1462
|
-
headers: yield this.getHeaders(),
|
|
1463
|
-
signal: this.signal
|
|
1464
|
-
});
|
|
1465
|
-
yield this.checkVersionMismatch(response);
|
|
1466
|
-
if (!response.ok) {
|
|
1467
|
-
throw new Error(`Failed to fetch ICE servers: ${response.status}`);
|
|
1468
|
-
}
|
|
1469
|
-
const data = yield response.json();
|
|
1470
|
-
const parsed = IceServersResponseSchema.parse(data);
|
|
1471
|
-
const iceServers = transformIceServers(parsed);
|
|
1472
|
-
console.debug("[WebRTCTransport] Received ICE servers:", iceServers.length);
|
|
1473
|
-
return iceServers;
|
|
1474
|
-
});
|
|
1475
|
-
}
|
|
1476
|
-
registerConnection() {
|
|
1477
|
-
return __async(this, null, function* () {
|
|
1478
|
-
console.debug("[WebRTCTransport] Registering connection...");
|
|
1479
|
-
const response = yield fetch(`${this.transportBaseUrl}/connections`, {
|
|
1480
|
-
method: "POST",
|
|
1481
|
-
headers: yield this.getHeaders(),
|
|
1482
|
-
signal: this.signal
|
|
1483
|
-
});
|
|
1484
|
-
yield this.checkVersionMismatch(response);
|
|
1485
|
-
if (response.status !== 201) {
|
|
1486
|
-
const errorText = yield response.text();
|
|
1487
|
-
if (response.status === 400) {
|
|
1488
|
-
throw new SessionLostError(
|
|
1489
|
-
`Failed to register connection: ${response.status} ${errorText}`
|
|
1490
|
-
);
|
|
1491
|
-
}
|
|
1492
|
-
throw new Error(
|
|
1493
|
-
`Failed to register connection: ${response.status} ${errorText}`
|
|
1494
|
-
);
|
|
1495
|
-
}
|
|
1496
|
-
const data = yield response.json();
|
|
1497
|
-
const connectionId = data.connection_id;
|
|
1498
|
-
console.debug(
|
|
1499
|
-
`[WebRTCTransport] Connection registered: id=${connectionId}`
|
|
1500
|
-
);
|
|
1501
|
-
return connectionId;
|
|
1502
|
-
});
|
|
1503
|
-
}
|
|
1504
|
-
sendSdpOffer(connectionId, sdpOffer, trackMapping, reconnect = false) {
|
|
1505
|
-
return __async(this, null, function* () {
|
|
1506
|
-
const method = reconnect ? "PUT" : "POST";
|
|
1507
|
-
console.debug(
|
|
1508
|
-
`[WebRTCTransport] Sending SDP offer (${method}) connection=${connectionId}`
|
|
1509
|
-
);
|
|
1510
|
-
const requestBody = {
|
|
1511
|
-
sdp_offer: sdpOffer,
|
|
1512
|
-
client_info: {
|
|
1513
|
-
sdk_version: REACTOR_SDK_VERSION,
|
|
1514
|
-
sdk_type: REACTOR_SDK_TYPE
|
|
1515
|
-
},
|
|
1516
|
-
track_mapping: trackMapping
|
|
1517
|
-
};
|
|
1518
|
-
const response = yield fetch(
|
|
1519
|
-
`${this.transportBaseUrl}/connections/${connectionId}/sdp_params`,
|
|
1520
|
-
{
|
|
1521
|
-
method,
|
|
1522
|
-
headers: __spreadProps(__spreadValues({}, yield this.getHeaders()), {
|
|
1523
|
-
"Content-Type": "application/json"
|
|
1524
|
-
}),
|
|
1525
|
-
body: JSON.stringify(requestBody),
|
|
1526
|
-
signal: this.signal
|
|
1527
|
-
}
|
|
1528
|
-
);
|
|
1529
|
-
yield this.checkVersionMismatch(response);
|
|
1530
|
-
if (response.status !== 202) {
|
|
1531
|
-
const errorText = yield response.text();
|
|
1532
|
-
if (response.status === 404) {
|
|
1533
|
-
throw new Error(
|
|
1534
|
-
`[WebRTCTransport] Connection ${connectionId} not found or already closed (404). A supplied connectionId must reference a connection registered under this session (POST .../connections) that is still open. ${errorText}`
|
|
1535
|
-
);
|
|
1536
|
-
}
|
|
1537
|
-
if (response.status === 400) {
|
|
1538
|
-
throw new SessionLostError(
|
|
1539
|
-
`[WebRTCTransport] Connection ${connectionId} rejected (400): ${errorText}`
|
|
1540
|
-
);
|
|
1541
|
-
}
|
|
1542
|
-
throw new Error(
|
|
1543
|
-
`Failed to send SDP offer: ${response.status} ${errorText}`
|
|
1544
|
-
);
|
|
1545
|
-
}
|
|
1546
|
-
console.debug("[WebRTCTransport] SDP offer accepted (202)");
|
|
1547
|
-
});
|
|
1548
|
-
}
|
|
1549
|
-
sendIceCandidates(candidates, is_final) {
|
|
1550
|
-
return __async(this, null, function* () {
|
|
1551
|
-
if (this.connectionId === void 0) {
|
|
1552
|
-
console.warn(
|
|
1553
|
-
"[WebRTCTransport] ICE candidates dropped: no active connection"
|
|
1554
|
-
);
|
|
1555
|
-
return;
|
|
1556
|
-
}
|
|
1557
|
-
console.debug(
|
|
1558
|
-
`[WebRTCTransport] Sending ICE candidates (count=${candidates.length}, is_final=${is_final})`
|
|
1559
|
-
);
|
|
1560
|
-
const requestBody = {
|
|
1561
|
-
candidates,
|
|
1562
|
-
is_final,
|
|
1563
|
-
client_info: {
|
|
1564
|
-
sdk_version: REACTOR_SDK_VERSION,
|
|
1565
|
-
sdk_type: REACTOR_SDK_TYPE
|
|
1566
|
-
}
|
|
1567
|
-
};
|
|
1568
|
-
const response = yield fetch(
|
|
1569
|
-
`${this.transportBaseUrl}/connections/${this.connectionId}/ice_candidates`,
|
|
1570
|
-
{
|
|
1571
|
-
method: "POST",
|
|
1572
|
-
headers: __spreadProps(__spreadValues({}, yield this.getHeaders()), {
|
|
1573
|
-
"Content-Type": "application/json"
|
|
1574
|
-
}),
|
|
1575
|
-
body: JSON.stringify(requestBody),
|
|
1576
|
-
signal: this.signal
|
|
1577
|
-
}
|
|
1578
|
-
);
|
|
1579
|
-
yield this.checkVersionMismatch(response);
|
|
1580
|
-
if (response.status !== 202) {
|
|
1581
|
-
const errorText = yield response.text();
|
|
1582
|
-
throw new Error(
|
|
1583
|
-
`Failed to send ICE candidates: ${response.status} ${errorText}`
|
|
1584
|
-
);
|
|
1585
|
-
}
|
|
1586
|
-
console.debug("[WebRTCTransport] ICE candidates accepted (202)");
|
|
1587
|
-
});
|
|
1588
|
-
}
|
|
1589
|
-
/**
|
|
1590
|
-
* Drain the pending ICE candidates buffer and POST them as a single
|
|
1591
|
-
* batch. Called either by the debounce timer (collected candidates so
|
|
1592
|
-
* far) or directly by the gathering-complete handler (with
|
|
1593
|
-
* ``isFinal=true``).
|
|
1594
|
-
*
|
|
1595
|
-
* Errors are logged at debug level — trickle ICE is fire-and-forget,
|
|
1596
|
-
* and the connection can still succeed even if some candidate batches
|
|
1597
|
-
* are lost (host/srflx candidates from the other side are usually
|
|
1598
|
-
* sufficient).
|
|
1599
|
-
*/
|
|
1600
|
-
flushPendingIceCandidates(isFinal) {
|
|
1601
|
-
if (this.iceCandidateFlushTimer !== void 0) {
|
|
1602
|
-
clearTimeout(this.iceCandidateFlushTimer);
|
|
1603
|
-
this.iceCandidateFlushTimer = void 0;
|
|
1604
|
-
}
|
|
1605
|
-
if (this.connectionId === void 0) {
|
|
1606
|
-
console.debug(
|
|
1607
|
-
"[WebRTCTransportClient] skipping ICE candidate flush because the connection is not established yet"
|
|
1608
|
-
);
|
|
1609
|
-
return;
|
|
1610
|
-
}
|
|
1611
|
-
const batch = this.pendingIceCandidates;
|
|
1612
|
-
this.pendingIceCandidates = [];
|
|
1613
|
-
if (batch.length === 0 && !isFinal) {
|
|
1614
|
-
return;
|
|
1615
|
-
}
|
|
1616
|
-
this.sendIceCandidates(batch, isFinal).catch((err) => {
|
|
1617
|
-
console.debug("[WebRTCTransport] ICE candidate flush failed:", err);
|
|
1618
|
-
});
|
|
1619
|
-
}
|
|
1620
|
-
cancelPendingIceCandidates() {
|
|
1621
|
-
if (this.iceCandidateFlushTimer !== void 0) {
|
|
1622
|
-
clearTimeout(this.iceCandidateFlushTimer);
|
|
1623
|
-
this.iceCandidateFlushTimer = void 0;
|
|
1624
|
-
}
|
|
1625
|
-
this.pendingIceCandidates = [];
|
|
1626
|
-
}
|
|
1627
|
-
pollSdpAnswer(connectionId) {
|
|
1628
|
-
return __async(this, null, function* () {
|
|
1629
|
-
console.debug("[WebRTCTransport] Polling for SDP answer...");
|
|
1630
|
-
const pollUrl = `${this.transportBaseUrl}/connections/${connectionId}/sdp_params`;
|
|
1631
|
-
const pollStart = performance.now();
|
|
1632
|
-
let backoffMs = INITIAL_BACKOFF_MS;
|
|
1633
|
-
let attempt = 0;
|
|
1634
|
-
while (true) {
|
|
1635
|
-
if (this.signal.aborted) {
|
|
1636
|
-
throw new AbortError("SDP polling aborted");
|
|
1637
|
-
}
|
|
1638
|
-
if (attempt >= this.maxPollAttempts) {
|
|
1639
|
-
throw new Error(
|
|
1640
|
-
`SDP polling exceeded maximum attempts (${this.maxPollAttempts})`
|
|
1641
|
-
);
|
|
1642
|
-
}
|
|
1643
|
-
attempt++;
|
|
1644
|
-
console.debug(
|
|
1645
|
-
`[WebRTCTransport] SDP poll attempt ${attempt}/${this.maxPollAttempts}`
|
|
1646
|
-
);
|
|
1647
|
-
const response = yield fetch(pollUrl, {
|
|
1648
|
-
method: "GET",
|
|
1649
|
-
headers: yield this.getHeaders(),
|
|
1650
|
-
signal: this.signal
|
|
1651
|
-
});
|
|
1652
|
-
yield this.checkVersionMismatch(response);
|
|
1653
|
-
if (response.status === 200) {
|
|
1654
|
-
const data = yield response.json();
|
|
1655
|
-
const parsed = WebRTCSdpAnswerResponseSchema.parse(data);
|
|
1656
|
-
this.sdpPollingMs = performance.now() - pollStart;
|
|
1657
|
-
this.sdpPollingAttempts = attempt;
|
|
1658
|
-
console.debug(
|
|
1659
|
-
`[WebRTCTransport] Received SDP answer via polling (${attempt} attempt(s), ${this.sdpPollingMs.toFixed(0)}ms)`
|
|
1660
|
-
);
|
|
1661
|
-
return parsed;
|
|
1662
|
-
}
|
|
1663
|
-
if (response.status === 202) {
|
|
1664
|
-
console.debug(
|
|
1665
|
-
`[WebRTCTransport] SDP answer pending, retrying in ${backoffMs}ms...`
|
|
1666
|
-
);
|
|
1667
|
-
yield this.sleep(backoffMs);
|
|
1668
|
-
backoffMs = Math.min(backoffMs * BACKOFF_MULTIPLIER, MAX_BACKOFF_MS);
|
|
1669
|
-
continue;
|
|
1670
|
-
}
|
|
1671
|
-
const errorText = yield response.text();
|
|
1672
|
-
throw new Error(
|
|
1673
|
-
`Failed to poll SDP answer: ${response.status} ${errorText}`
|
|
1674
|
-
);
|
|
1675
|
-
}
|
|
1676
|
-
});
|
|
1677
|
-
}
|
|
1678
|
-
// ─────────────────────────────────────────────────────────────────────────
|
|
1679
|
-
// Connection Lifecycle
|
|
1680
|
-
// ─────────────────────────────────────────────────────────────────────────
|
|
1681
|
-
warmup() {
|
|
1682
|
-
return __async(this, null, function* () {
|
|
1683
|
-
if (!this.cachedIceServers) {
|
|
1684
|
-
this.cachedIceServers = this.fetchIceServers();
|
|
1685
|
-
this.cachedIceServers.catch(() => {
|
|
1686
|
-
});
|
|
1687
|
-
}
|
|
1688
|
-
yield this.cachedIceServers;
|
|
1689
|
-
});
|
|
1690
|
-
}
|
|
1691
|
-
prepare(tracks) {
|
|
1692
|
-
return __async(this, null, function* () {
|
|
1693
|
-
this.setStatus("connecting");
|
|
1694
|
-
this.resetTransportTimings();
|
|
1695
|
-
this.stopPing();
|
|
1696
|
-
this.stopStatsPolling();
|
|
1697
|
-
this.cancelPendingIceCandidates();
|
|
1698
|
-
if (this.dataChannel) {
|
|
1699
|
-
this.dataChannel.close();
|
|
1700
|
-
this.dataChannel = void 0;
|
|
1701
|
-
}
|
|
1702
|
-
if (this.controlChannel) {
|
|
1703
|
-
this.controlChannel.close();
|
|
1704
|
-
this.controlChannel = void 0;
|
|
1705
|
-
}
|
|
1706
|
-
if (this.peerConnection) {
|
|
1707
|
-
closePeerConnection(this.peerConnection);
|
|
1708
|
-
this.peerConnection = void 0;
|
|
1709
|
-
}
|
|
1710
|
-
this.peerConnected = false;
|
|
1711
|
-
this.dataChannelOpen = false;
|
|
1712
|
-
this.controlChannelOpen = false;
|
|
1713
|
-
this.peerConnectionQueue.stop();
|
|
1714
|
-
this.peerConnectionQueue = new AwaitQueue();
|
|
1715
|
-
this.peerConnectionQueue.push(
|
|
1716
|
-
() => new Promise((resolve) => {
|
|
1717
|
-
this.readyGateResolve = resolve;
|
|
1718
|
-
})
|
|
1719
|
-
).catch(() => {
|
|
1720
|
-
});
|
|
1721
|
-
const iceServers = this.cachedIceServers ? yield this.cachedIceServers : yield this.fetchIceServers();
|
|
1722
|
-
this.cachedIceServers = void 0;
|
|
1723
|
-
this.peerConnection = createPeerConnection({ iceServers });
|
|
1724
|
-
this.setupPeerConnectionHandlers();
|
|
1725
|
-
this.controlChannel = createDataChannel(
|
|
1726
|
-
this.peerConnection,
|
|
1727
|
-
"control"
|
|
1728
|
-
);
|
|
1729
|
-
this.setupControlChannelHandlers();
|
|
1730
|
-
this.dataChannel = createDataChannel(this.peerConnection);
|
|
1731
|
-
this.setupDataChannelHandlers();
|
|
1732
|
-
this.transceiverMap.clear();
|
|
1733
|
-
for (const track of tracks) {
|
|
1734
|
-
const transceiver = this.peerConnection.addTransceiver(track.kind, {
|
|
1735
|
-
direction: track.direction
|
|
1736
|
-
});
|
|
1737
|
-
this.transceiverMap.set(track.name, {
|
|
1738
|
-
name: track.name,
|
|
1739
|
-
kind: track.kind,
|
|
1740
|
-
direction: track.direction,
|
|
1741
|
-
transceiver
|
|
1742
|
-
});
|
|
1743
|
-
console.debug(
|
|
1744
|
-
`[WebRTCTransport] Transceiver added: "${track.name}" (${track.kind}, ${track.direction})`
|
|
1745
|
-
);
|
|
1746
|
-
}
|
|
1747
|
-
this.pendingSdpOffer = yield createOffer(this.peerConnection);
|
|
1748
|
-
this.pendingTrackMapping = this.buildTrackMapping(tracks);
|
|
1749
|
-
console.debug("[WebRTCTransport] SDP offer prepared");
|
|
1750
|
-
});
|
|
1751
|
-
}
|
|
1752
|
-
connect(reconnect = false, connectionId) {
|
|
1753
|
-
return __async(this, null, function* () {
|
|
1754
|
-
if (!this.pendingSdpOffer || !this.pendingTrackMapping) {
|
|
1755
|
-
throw new Error(
|
|
1756
|
-
"[WebRTCTransport] No prepared connection. Call prepare() first."
|
|
1757
|
-
);
|
|
1758
|
-
}
|
|
1759
|
-
const sdpOffer = this.pendingSdpOffer;
|
|
1760
|
-
const trackMapping = this.pendingTrackMapping;
|
|
1761
|
-
this.pendingSdpOffer = void 0;
|
|
1762
|
-
this.pendingTrackMapping = void 0;
|
|
1763
|
-
if (connectionId !== void 0) {
|
|
1764
|
-
if (!Number.isInteger(connectionId) || connectionId <= MIN_CONNECTION_ID || connectionId > MAX_CONNECTION_ID) {
|
|
1765
|
-
throw new Error(
|
|
1766
|
-
`[WebRTCTransport] Invalid connectionId ${connectionId}: must be an integer in (${MIN_CONNECTION_ID}, ${MAX_CONNECTION_ID}]`
|
|
1767
|
-
);
|
|
1768
|
-
}
|
|
1769
|
-
this.connectionId = connectionId;
|
|
1770
|
-
} else if (!reconnect || this.connectionId === void 0) {
|
|
1771
|
-
this.connectionId = yield this.registerConnection();
|
|
1772
|
-
}
|
|
1773
|
-
yield this.sendSdpOffer(
|
|
1774
|
-
this.connectionId,
|
|
1775
|
-
sdpOffer,
|
|
1776
|
-
trackMapping,
|
|
1777
|
-
reconnect
|
|
1778
|
-
);
|
|
1779
|
-
if (this.pendingIceCandidates.length > 0) {
|
|
1780
|
-
this.flushPendingIceCandidates(
|
|
1781
|
-
this.peerConnection !== void 0 && this.peerConnection.iceGatheringState === "complete"
|
|
1782
|
-
);
|
|
1783
|
-
}
|
|
1784
|
-
const answerResponse = yield this.pollSdpAnswer(this.connectionId);
|
|
1785
|
-
this.iceStartTime = performance.now();
|
|
1786
|
-
yield setRemoteDescription(
|
|
1787
|
-
this.peerConnection,
|
|
1788
|
-
answerResponse.sdp_answer
|
|
1789
|
-
);
|
|
1790
|
-
console.debug("[WebRTCTransport] Remote description set");
|
|
1791
|
-
});
|
|
1792
|
-
}
|
|
1793
|
-
disconnect() {
|
|
1794
|
-
return __async(this, null, function* () {
|
|
1795
|
-
this.stopPing();
|
|
1796
|
-
this.stopStatsPolling();
|
|
1797
|
-
this.cancelPendingIceCandidates();
|
|
1798
|
-
for (const name of Array.from(this.publishedTracks.keys())) {
|
|
1799
|
-
yield this.unpublishTrack(name);
|
|
1800
|
-
}
|
|
1801
|
-
if (this.dataChannel) {
|
|
1802
|
-
this.dataChannel.close();
|
|
1803
|
-
this.dataChannel = void 0;
|
|
1804
|
-
}
|
|
1805
|
-
if (this.controlChannel) {
|
|
1806
|
-
this.controlChannel.close();
|
|
1807
|
-
this.controlChannel = void 0;
|
|
1808
|
-
}
|
|
1809
|
-
if (this.peerConnection) {
|
|
1810
|
-
closePeerConnection(this.peerConnection);
|
|
1811
|
-
this.peerConnection = void 0;
|
|
1812
|
-
}
|
|
1813
|
-
for (const [, pending] of this.pendingControlRequests) {
|
|
1814
|
-
clearTimeout(pending.timeout);
|
|
1815
|
-
pending.reject(
|
|
1816
|
-
new Error("[WebRTCTransport] Disconnected while waiting for response")
|
|
1817
|
-
);
|
|
1818
|
-
}
|
|
1819
|
-
this.pendingControlRequests.clear();
|
|
1820
|
-
this.readyGateResolve = void 0;
|
|
1821
|
-
this.peerConnectionQueue.stop();
|
|
1822
|
-
this.connectionId = void 0;
|
|
1823
|
-
this.transceiverMap.clear();
|
|
1824
|
-
this.peerConnected = false;
|
|
1825
|
-
this.dataChannelOpen = false;
|
|
1826
|
-
this.controlChannelOpen = false;
|
|
1827
|
-
this.resetTransportTimings();
|
|
1828
|
-
this.setStatus("disconnected");
|
|
1829
|
-
console.debug("[WebRTCTransport] Disconnected");
|
|
1830
|
-
});
|
|
1831
|
-
}
|
|
1832
|
-
abort() {
|
|
1833
|
-
this.abortController.abort();
|
|
1834
|
-
this.abortController = new AbortController();
|
|
1835
|
-
}
|
|
1836
|
-
getStatus() {
|
|
1837
|
-
return this.status;
|
|
1838
|
-
}
|
|
1839
|
-
// ─────────────────────────────────────────────────────────────────────────
|
|
1840
|
-
// Track Mapping
|
|
1841
|
-
// ─────────────────────────────────────────────────────────────────────────
|
|
1842
|
-
/**
|
|
1843
|
-
* Builds the track_mapping array from capabilities + transceiver MIDs.
|
|
1844
|
-
* Must be called after createOffer + setLocalDescription so that
|
|
1845
|
-
* transceiver.mid is assigned.
|
|
1846
|
-
*/
|
|
1847
|
-
buildTrackMapping(tracks) {
|
|
1848
|
-
return tracks.map((track) => {
|
|
1849
|
-
var _a;
|
|
1850
|
-
const entry = this.transceiverMap.get(track.name);
|
|
1851
|
-
const mid = (_a = entry == null ? void 0 : entry.transceiver) == null ? void 0 : _a.mid;
|
|
1852
|
-
if (mid == null) {
|
|
1853
|
-
throw new Error(
|
|
1854
|
-
`Cannot build track mapping: transceiver "${track.name}" has no MID. Was createOffer() called?`
|
|
1855
|
-
);
|
|
1856
|
-
}
|
|
1857
|
-
return {
|
|
1858
|
-
mid,
|
|
1859
|
-
name: track.name,
|
|
1860
|
-
kind: track.kind,
|
|
1861
|
-
direction: track.direction
|
|
1862
|
-
};
|
|
1863
|
-
});
|
|
1864
|
-
}
|
|
1865
|
-
// ─────────────────────────────────────────────────────────────────────────
|
|
1866
|
-
// Messaging
|
|
1867
|
-
// ─────────────────────────────────────────────────────────────────────────
|
|
1868
|
-
get maxMessageBytes() {
|
|
1869
|
-
var _a, _b, _c;
|
|
1870
|
-
return (_c = (_b = (_a = this.peerConnection) == null ? void 0 : _a.sctp) == null ? void 0 : _b.maxMessageSize) != null ? _c : void 0;
|
|
1871
|
-
}
|
|
1872
|
-
sendCommand(command, data, scope = "application", uploads) {
|
|
1873
|
-
if (!this.dataChannel) {
|
|
1874
|
-
throw new Error("[WebRTCTransport] Data channel not available");
|
|
1875
|
-
}
|
|
1876
|
-
try {
|
|
1877
|
-
sendMessage(
|
|
1878
|
-
this.dataChannel,
|
|
1879
|
-
command,
|
|
1880
|
-
data,
|
|
1881
|
-
scope,
|
|
1882
|
-
this.maxMessageBytes,
|
|
1883
|
-
uploads
|
|
1884
|
-
);
|
|
1885
|
-
} catch (error) {
|
|
1886
|
-
console.warn("[WebRTCTransport] Failed to send message:", error);
|
|
1887
|
-
}
|
|
1888
|
-
}
|
|
1889
|
-
sendControlMessage(command, data, reqId) {
|
|
1890
|
-
if (!this.controlChannel) {
|
|
1891
|
-
console.warn("[WebRTCTransport] Control channel not available");
|
|
1892
|
-
return;
|
|
1893
|
-
}
|
|
1894
|
-
try {
|
|
1895
|
-
if (this.controlChannel.readyState !== "open") {
|
|
1896
|
-
throw new Error(
|
|
1897
|
-
`Control channel not open: ${this.controlChannel.readyState}`
|
|
1898
|
-
);
|
|
1899
|
-
}
|
|
1900
|
-
this.controlChannel.send(
|
|
1901
|
-
JSON.stringify({ type: "notification", event: command, data })
|
|
1902
|
-
);
|
|
1903
|
-
} catch (error) {
|
|
1904
|
-
console.warn("[WebRTCTransport] Failed to send control message:", error);
|
|
1905
|
-
}
|
|
1906
|
-
}
|
|
1907
|
-
sendControlRequest(method, data, timeoutMs = 1e4) {
|
|
1908
|
-
return new Promise((resolve, reject) => {
|
|
1909
|
-
const requestId = `ctrl_${++this.controlRequestCounter}`;
|
|
1910
|
-
const timeout = setTimeout(() => {
|
|
1911
|
-
this.pendingControlRequests.delete(requestId);
|
|
1912
|
-
reject(new Error(`[WebRTCTransport] Request "${method}" timed out`));
|
|
1913
|
-
}, timeoutMs);
|
|
1914
|
-
this.pendingControlRequests.set(requestId, { resolve, reject, timeout });
|
|
1915
|
-
try {
|
|
1916
|
-
if (!this.controlChannel || this.controlChannel.readyState !== "open") {
|
|
1917
|
-
throw new Error("Control channel not available");
|
|
1918
|
-
}
|
|
1919
|
-
this.controlChannel.send(
|
|
1920
|
-
JSON.stringify({
|
|
1921
|
-
type: "request",
|
|
1922
|
-
method,
|
|
1923
|
-
request_id: requestId,
|
|
1924
|
-
data
|
|
1925
|
-
})
|
|
1926
|
-
);
|
|
1927
|
-
} catch (error) {
|
|
1928
|
-
clearTimeout(timeout);
|
|
1929
|
-
this.pendingControlRequests.delete(requestId);
|
|
1930
|
-
reject(error);
|
|
1931
|
-
}
|
|
1932
|
-
});
|
|
1933
|
-
}
|
|
1934
|
-
pauseTrack(name) {
|
|
1935
|
-
this.peerConnectionQueue.push(() => __async(this, null, function* () {
|
|
1936
|
-
var _a;
|
|
1937
|
-
const entry = this.transceiverMap.get(name);
|
|
1938
|
-
if ((_a = entry == null ? void 0 : entry.transceiver) == null ? void 0 : _a.mid) {
|
|
1939
|
-
entry.transceiver.direction = "inactive";
|
|
1940
|
-
yield this.applyDirectionLocally(entry.transceiver.mid, "inactive");
|
|
1941
|
-
}
|
|
1942
|
-
this.sendControlMessage("pause_track", { name });
|
|
1943
|
-
})).catch((e) => {
|
|
1944
|
-
console.warn("[WebRTCTransport] Failed to pause track:", e);
|
|
1945
|
-
});
|
|
1946
|
-
}
|
|
1947
|
-
resumeTrack(name) {
|
|
1948
|
-
this.peerConnectionQueue.push(() => __async(this, null, function* () {
|
|
1949
|
-
var _a;
|
|
1950
|
-
const entry = this.transceiverMap.get(name);
|
|
1951
|
-
if ((_a = entry == null ? void 0 : entry.transceiver) == null ? void 0 : _a.mid) {
|
|
1952
|
-
entry.transceiver.direction = entry.direction;
|
|
1953
|
-
yield this.applyDirectionLocally(
|
|
1954
|
-
entry.transceiver.mid,
|
|
1955
|
-
entry.direction
|
|
1956
|
-
);
|
|
1957
|
-
}
|
|
1958
|
-
this.sendControlMessage("resume_track", { name });
|
|
1959
|
-
})).catch((e) => {
|
|
1960
|
-
console.warn("[WebRTCTransport] Failed to resume track:", e);
|
|
1961
|
-
});
|
|
1962
|
-
}
|
|
1963
|
-
applyDirectionLocally(mid, localDirection) {
|
|
1964
|
-
return __async(this, null, function* () {
|
|
1965
|
-
var _a, _b;
|
|
1966
|
-
const pc = this.peerConnection;
|
|
1967
|
-
if (!pc) return;
|
|
1968
|
-
const tx = pc.getTransceivers().find((t) => t.mid === mid);
|
|
1969
|
-
if (tx && tx.currentDirection === localDirection) return;
|
|
1970
|
-
if (pc.signalingState !== "stable") return;
|
|
1971
|
-
const localSdp = (_a = pc.localDescription) == null ? void 0 : _a.sdp;
|
|
1972
|
-
const remoteSdp = (_b = pc.remoteDescription) == null ? void 0 : _b.sdp;
|
|
1973
|
-
if (!localSdp || !remoteSdp) return;
|
|
1974
|
-
const modifiedLocal = replaceSdpDirectionForMid(
|
|
1975
|
-
localSdp,
|
|
1976
|
-
mid,
|
|
1977
|
-
localDirection
|
|
1978
|
-
);
|
|
1979
|
-
const modifiedRemote = replaceSdpDirectionForMid(
|
|
1980
|
-
remoteSdp,
|
|
1981
|
-
mid,
|
|
1982
|
-
complementDirection(localDirection)
|
|
1983
|
-
);
|
|
1984
|
-
try {
|
|
1985
|
-
yield pc.setLocalDescription(
|
|
1986
|
-
new RTCSessionDescription({ type: "offer", sdp: modifiedLocal })
|
|
1987
|
-
);
|
|
1988
|
-
yield pc.setRemoteDescription(
|
|
1989
|
-
new RTCSessionDescription({ type: "answer", sdp: modifiedRemote })
|
|
1990
|
-
);
|
|
1991
|
-
} catch (e) {
|
|
1992
|
-
if (pc.signalingState === "have-local-offer") {
|
|
1993
|
-
try {
|
|
1994
|
-
yield pc.setLocalDescription({ type: "rollback" });
|
|
1995
|
-
} catch (e2) {
|
|
1996
|
-
}
|
|
1997
|
-
}
|
|
1998
|
-
throw e;
|
|
1999
|
-
}
|
|
2000
|
-
});
|
|
2001
|
-
}
|
|
2002
|
-
// ─────────────────────────────────────────────────────────────────────────
|
|
2003
|
-
// Track Publishing
|
|
2004
|
-
// ─────────────────────────────────────────────────────────────────────────
|
|
2005
|
-
publishTrack(name, track) {
|
|
2006
|
-
return __async(this, null, function* () {
|
|
2007
|
-
if (!this.peerConnection) {
|
|
2008
|
-
throw new Error(
|
|
2009
|
-
`[WebRTCTransport] Cannot publish track "${name}" - not initialized`
|
|
2010
|
-
);
|
|
2011
|
-
}
|
|
2012
|
-
if (this.status !== "connected") {
|
|
2013
|
-
throw new Error(
|
|
2014
|
-
`[WebRTCTransport] Cannot publish track "${name}" - not connected`
|
|
2015
|
-
);
|
|
2016
|
-
}
|
|
2017
|
-
const entry = this.transceiverMap.get(name);
|
|
2018
|
-
if (!entry || !entry.transceiver) {
|
|
2019
|
-
throw new Error(
|
|
2020
|
-
`[WebRTCTransport] Cannot publish track "${name}" - no transceiver (was it declared in capabilities?)`
|
|
2021
|
-
);
|
|
2022
|
-
}
|
|
2023
|
-
if (entry.direction === "recvonly") {
|
|
2024
|
-
throw new Error(
|
|
2025
|
-
`[WebRTCTransport] Cannot publish track "${name}" - transceiver is recvonly`
|
|
2026
|
-
);
|
|
2027
|
-
}
|
|
2028
|
-
yield this.sendControlRequest("publish_track", { name });
|
|
2029
|
-
yield entry.transceiver.sender.replaceTrack(track);
|
|
2030
|
-
this.publishedTracks.set(name, track);
|
|
2031
|
-
console.debug(`[WebRTCTransport] Track "${name}" published successfully`);
|
|
2032
|
-
});
|
|
2033
|
-
}
|
|
2034
|
-
unpublishTrack(name) {
|
|
2035
|
-
return __async(this, null, function* () {
|
|
2036
|
-
const entry = this.transceiverMap.get(name);
|
|
2037
|
-
if (!(entry == null ? void 0 : entry.transceiver) || !this.publishedTracks.has(name)) return;
|
|
2038
|
-
try {
|
|
2039
|
-
yield entry.transceiver.sender.replaceTrack(null);
|
|
2040
|
-
this.sendControlMessage("unpublish_track", { name });
|
|
2041
|
-
console.debug(
|
|
2042
|
-
`[WebRTCTransport] Track "${name}" unpublished successfully`
|
|
2043
|
-
);
|
|
2044
|
-
} catch (error) {
|
|
2045
|
-
console.error(
|
|
2046
|
-
`[WebRTCTransport] Failed to unpublish track "${name}":`,
|
|
2047
|
-
error
|
|
2048
|
-
);
|
|
2049
|
-
throw error;
|
|
2050
|
-
} finally {
|
|
2051
|
-
this.publishedTracks.delete(name);
|
|
2052
|
-
}
|
|
2053
|
-
});
|
|
2054
|
-
}
|
|
2055
|
-
// ─────────────────────────────────────────────────────────────────────────
|
|
2056
|
-
// Stats
|
|
2057
|
-
// ─────────────────────────────────────────────────────────────────────────
|
|
2058
|
-
getStats() {
|
|
2059
|
-
return this.stats;
|
|
2060
|
-
}
|
|
2061
|
-
getTransportTimings() {
|
|
2062
|
-
var _a, _b;
|
|
2063
|
-
if (this.iceNegotiationMs == null || this.dataChannelMs == null) {
|
|
2064
|
-
return void 0;
|
|
2065
|
-
}
|
|
2066
|
-
return {
|
|
2067
|
-
protocol: "webrtc",
|
|
2068
|
-
sdpPollingMs: (_a = this.sdpPollingMs) != null ? _a : 0,
|
|
2069
|
-
sdpPollingAttempts: (_b = this.sdpPollingAttempts) != null ? _b : 0,
|
|
2070
|
-
iceNegotiationMs: this.iceNegotiationMs,
|
|
2071
|
-
dataChannelMs: this.dataChannelMs
|
|
2072
|
-
};
|
|
2073
|
-
}
|
|
2074
|
-
resetTransportTimings() {
|
|
2075
|
-
this.iceStartTime = void 0;
|
|
2076
|
-
this.iceNegotiationMs = void 0;
|
|
2077
|
-
this.dataChannelMs = void 0;
|
|
2078
|
-
this.sdpPollingMs = void 0;
|
|
2079
|
-
this.sdpPollingAttempts = void 0;
|
|
2080
|
-
}
|
|
2081
|
-
startStatsPolling() {
|
|
2082
|
-
this.stopStatsPolling();
|
|
2083
|
-
const statsExtractor = createRTCStatsExtractor();
|
|
2084
|
-
this.statsInterval = setInterval(() => __async(this, null, function* () {
|
|
2085
|
-
if (!this.peerConnection) return;
|
|
2086
|
-
try {
|
|
2087
|
-
const report = yield this.peerConnection.getStats();
|
|
2088
|
-
this.stats = statsExtractor(report);
|
|
2089
|
-
this.emit("statsUpdate", this.stats);
|
|
2090
|
-
} catch (e) {
|
|
2091
|
-
}
|
|
2092
|
-
}), STATS_INTERVAL_MS);
|
|
2093
|
-
}
|
|
2094
|
-
stopStatsPolling() {
|
|
2095
|
-
if (this.statsInterval !== void 0) {
|
|
2096
|
-
clearInterval(this.statsInterval);
|
|
2097
|
-
this.statsInterval = void 0;
|
|
2098
|
-
}
|
|
2099
|
-
this.stats = void 0;
|
|
2100
|
-
}
|
|
2101
|
-
// ─────────────────────────────────────────────────────────────────────────
|
|
2102
|
-
// Ping (Client Liveness)
|
|
2103
|
-
// ─────────────────────────────────────────────────────────────────────────
|
|
2104
|
-
startPing() {
|
|
2105
|
-
this.stopPing();
|
|
2106
|
-
this.pingInterval = setInterval(() => {
|
|
2107
|
-
var _a;
|
|
2108
|
-
if (((_a = this.dataChannel) == null ? void 0 : _a.readyState) === "open") {
|
|
2109
|
-
try {
|
|
2110
|
-
sendMessage(this.dataChannel, "ping", {}, "runtime");
|
|
2111
|
-
} catch (e) {
|
|
2112
|
-
}
|
|
2113
|
-
}
|
|
2114
|
-
}, PING_INTERVAL_MS);
|
|
2115
|
-
}
|
|
2116
|
-
stopPing() {
|
|
2117
|
-
if (this.pingInterval !== void 0) {
|
|
2118
|
-
clearInterval(this.pingInterval);
|
|
2119
|
-
this.pingInterval = void 0;
|
|
2120
|
-
}
|
|
2121
|
-
}
|
|
2122
|
-
// ─────────────────────────────────────────────────────────────────────────
|
|
2123
|
-
// Internal Helpers
|
|
2124
|
-
// ─────────────────────────────────────────────────────────────────────────
|
|
2125
|
-
checkFullyConnected() {
|
|
2126
|
-
if (this.peerConnected && this.dataChannelOpen && this.controlChannelOpen) {
|
|
2127
|
-
this.setStatus("connected");
|
|
2128
|
-
this.startStatsPolling();
|
|
2129
|
-
this.readyGateResolve();
|
|
2130
|
-
this.readyGateResolve = void 0;
|
|
2131
|
-
}
|
|
2132
|
-
}
|
|
2133
|
-
setStatus(newStatus) {
|
|
2134
|
-
if (this.status !== newStatus) {
|
|
2135
|
-
this.status = newStatus;
|
|
2136
|
-
this.emit("statusChanged", newStatus);
|
|
2137
|
-
}
|
|
2138
|
-
}
|
|
2139
|
-
setupPeerConnectionHandlers() {
|
|
2140
|
-
if (!this.peerConnection) return;
|
|
2141
|
-
this.peerConnection.onconnectionstatechange = () => {
|
|
2142
|
-
var _a;
|
|
2143
|
-
const state = (_a = this.peerConnection) == null ? void 0 : _a.connectionState;
|
|
2144
|
-
console.debug("[WebRTCTransport] Connection state:", state);
|
|
2145
|
-
if (state) {
|
|
2146
|
-
switch (state) {
|
|
2147
|
-
case "connected":
|
|
2148
|
-
if (this.iceStartTime != null && this.iceNegotiationMs == null) {
|
|
2149
|
-
this.iceNegotiationMs = performance.now() - this.iceStartTime;
|
|
2150
|
-
}
|
|
2151
|
-
this.peerConnected = true;
|
|
2152
|
-
this.checkFullyConnected();
|
|
2153
|
-
break;
|
|
2154
|
-
case "disconnected":
|
|
2155
|
-
case "closed":
|
|
2156
|
-
this.peerConnected = false;
|
|
2157
|
-
this.setStatus("disconnected");
|
|
2158
|
-
break;
|
|
2159
|
-
case "failed":
|
|
2160
|
-
this.peerConnected = false;
|
|
2161
|
-
this.setStatus("error");
|
|
2162
|
-
break;
|
|
2163
|
-
}
|
|
2164
|
-
}
|
|
2165
|
-
};
|
|
2166
|
-
this.peerConnection.ontrack = (event) => {
|
|
2167
|
-
var _a, _b;
|
|
2168
|
-
let trackName;
|
|
2169
|
-
for (const [name, entry] of this.transceiverMap) {
|
|
2170
|
-
if (entry.transceiver === event.transceiver) {
|
|
2171
|
-
trackName = name;
|
|
2172
|
-
break;
|
|
2173
|
-
}
|
|
2174
|
-
}
|
|
2175
|
-
trackName != null ? trackName : trackName = (_a = event.transceiver.mid) != null ? _a : `unknown-${event.track.id}`;
|
|
2176
|
-
console.debug(
|
|
2177
|
-
`[WebRTCTransport] Track received: "${trackName}" (${event.track.kind}, mid=${event.transceiver.mid})`
|
|
2178
|
-
);
|
|
2179
|
-
const stream = (_b = event.streams[0]) != null ? _b : new MediaStream([event.track]);
|
|
2180
|
-
this.emit("trackReceived", trackName, event.track, stream);
|
|
2181
|
-
};
|
|
2182
|
-
this.peerConnection.onicecandidate = (event) => {
|
|
2183
|
-
var _a, _b;
|
|
2184
|
-
if (event.candidate) {
|
|
2185
|
-
this.pendingIceCandidates.push({
|
|
2186
|
-
candidate: event.candidate.candidate,
|
|
2187
|
-
sdp_mid: (_a = event.candidate.sdpMid) != null ? _a : void 0,
|
|
2188
|
-
sdp_mline_index: (_b = event.candidate.sdpMLineIndex) != null ? _b : void 0
|
|
2189
|
-
});
|
|
2190
|
-
if (this.iceCandidateFlushTimer === void 0) {
|
|
2191
|
-
this.iceCandidateFlushTimer = setTimeout(
|
|
2192
|
-
() => this.flushPendingIceCandidates(false),
|
|
2193
|
-
ICE_CANDIDATE_BATCH_WINDOW_MS
|
|
2194
|
-
);
|
|
2195
|
-
}
|
|
2196
|
-
} else {
|
|
2197
|
-
this.flushPendingIceCandidates(true);
|
|
2198
|
-
}
|
|
2199
|
-
};
|
|
2200
|
-
this.peerConnection.onicecandidateerror = (event) => {
|
|
2201
|
-
console.debug("[WebRTCTransport] ICE candidate error:", event);
|
|
2202
|
-
};
|
|
2203
|
-
this.peerConnection.ondatachannel = (event) => {
|
|
2204
|
-
console.debug("[WebRTCTransport] Data channel received from remote");
|
|
2205
|
-
this.dataChannel = event.channel;
|
|
2206
|
-
this.setupDataChannelHandlers();
|
|
2207
|
-
};
|
|
2208
|
-
}
|
|
2209
|
-
setupDataChannelHandlers() {
|
|
2210
|
-
if (!this.dataChannel) return;
|
|
2211
|
-
this.dataChannel.onopen = () => {
|
|
2212
|
-
console.debug("[WebRTCTransport] Data channel open");
|
|
2213
|
-
if (this.iceStartTime != null && this.dataChannelMs == null) {
|
|
2214
|
-
this.dataChannelMs = performance.now() - this.iceStartTime;
|
|
2215
|
-
}
|
|
2216
|
-
this.dataChannelOpen = true;
|
|
2217
|
-
this.startPing();
|
|
2218
|
-
this.checkFullyConnected();
|
|
2219
|
-
};
|
|
2220
|
-
this.dataChannel.onclose = () => {
|
|
2221
|
-
console.debug("[WebRTCTransport] Data channel closed");
|
|
2222
|
-
this.dataChannelOpen = false;
|
|
2223
|
-
this.stopPing();
|
|
2224
|
-
};
|
|
2225
|
-
this.dataChannel.onerror = (error) => {
|
|
2226
|
-
console.error("[WebRTCTransport] Data channel error:", error);
|
|
2227
|
-
};
|
|
2228
|
-
this.dataChannel.onmessage = (event) => {
|
|
2229
|
-
const rawData = parseMessage(event.data);
|
|
2230
|
-
console.debug("[WebRTCTransport] Received message:", rawData);
|
|
2231
|
-
try {
|
|
2232
|
-
if ((rawData == null ? void 0 : rawData.scope) === "application" && (rawData == null ? void 0 : rawData.data) !== void 0) {
|
|
2233
|
-
this.emit("message", rawData.data, "application");
|
|
2234
|
-
} else if ((rawData == null ? void 0 : rawData.scope) === "runtime" && (rawData == null ? void 0 : rawData.data) !== void 0) {
|
|
2235
|
-
this.emit("message", rawData.data, "runtime");
|
|
2236
|
-
} else {
|
|
2237
|
-
console.warn(
|
|
2238
|
-
"[WebRTCTransport] Received message without envelope, treating as application"
|
|
2239
|
-
);
|
|
2240
|
-
this.emit("message", rawData, "application");
|
|
2241
|
-
}
|
|
2242
|
-
} catch (error) {
|
|
2243
|
-
console.error(
|
|
2244
|
-
"[WebRTCTransport] Failed to parse/validate message:",
|
|
2245
|
-
error
|
|
2246
|
-
);
|
|
2247
|
-
}
|
|
2248
|
-
};
|
|
2249
|
-
}
|
|
2250
|
-
setupControlChannelHandlers() {
|
|
2251
|
-
if (!this.controlChannel) return;
|
|
2252
|
-
this.controlChannel.onopen = () => {
|
|
2253
|
-
console.debug("[WebRTCTransport] Control channel open");
|
|
2254
|
-
this.controlChannelOpen = true;
|
|
2255
|
-
this.checkFullyConnected();
|
|
2256
|
-
};
|
|
2257
|
-
this.controlChannel.onclose = () => {
|
|
2258
|
-
console.debug("[WebRTCTransport] Control channel closed");
|
|
2259
|
-
this.controlChannelOpen = false;
|
|
2260
|
-
};
|
|
2261
|
-
this.controlChannel.onerror = (error) => {
|
|
2262
|
-
console.error("[WebRTCTransport] Control channel error:", error);
|
|
2263
|
-
};
|
|
2264
|
-
this.controlChannel.onmessage = (event) => {
|
|
2265
|
-
var _a, _b;
|
|
2266
|
-
const raw = parseMessage(event.data);
|
|
2267
|
-
if ((raw == null ? void 0 : raw.type) === "response") {
|
|
2268
|
-
const requestId = raw == null ? void 0 : raw.request_id;
|
|
2269
|
-
if (requestId) {
|
|
2270
|
-
const pending = this.pendingControlRequests.get(requestId);
|
|
2271
|
-
if (pending) {
|
|
2272
|
-
clearTimeout(pending.timeout);
|
|
2273
|
-
this.pendingControlRequests.delete(requestId);
|
|
2274
|
-
if (raw == null ? void 0 : raw.error) {
|
|
2275
|
-
pending.reject(
|
|
2276
|
-
new Error(
|
|
2277
|
-
`[WebRTCTransport] ${(_a = raw.method) != null ? _a : "request"} failed: ${(_b = raw.error.message) != null ? _b : "unknown error"}`
|
|
2278
|
-
)
|
|
2279
|
-
);
|
|
2280
|
-
} else {
|
|
2281
|
-
pending.resolve();
|
|
2282
|
-
}
|
|
2283
|
-
}
|
|
2284
|
-
}
|
|
2285
|
-
return;
|
|
2286
|
-
}
|
|
2287
|
-
console.debug("[WebRTCTransport] Received control message:", raw);
|
|
2288
|
-
};
|
|
2289
|
-
}
|
|
2290
|
-
};
|
|
2291
|
-
|
|
2292
|
-
// src/core/Reactor.ts
|
|
2293
|
-
import { z as z3 } from "zod";
|
|
2294
|
-
|
|
2295
|
-
// src/utils/recording.ts
|
|
2296
|
-
import { z as z2 } from "zod";
|
|
2297
|
-
var RuntimeRecordingMessageType = {
|
|
2298
|
-
REQUEST_CLIP: "requestClip",
|
|
2299
|
-
REQUEST_RECORDING: "requestRecording",
|
|
2300
|
-
CLIP_READY: "clipReady",
|
|
2301
|
-
CLIP_FAILED: "clipFailed"
|
|
2302
|
-
};
|
|
2303
|
-
var RecordingError = class extends Error {
|
|
2304
|
-
constructor(code, reason) {
|
|
2305
|
-
super(`${code}: ${reason}`);
|
|
2306
|
-
this.code = code;
|
|
2307
|
-
this.reason = reason;
|
|
2308
|
-
this.name = "RecordingError";
|
|
2309
|
-
}
|
|
2310
|
-
};
|
|
2311
|
-
var ClipReadyPayloadSchema = z2.object({
|
|
2312
|
-
session_id: z2.string(),
|
|
2313
|
-
kind: z2.enum(["snap", "recording"]),
|
|
2314
|
-
start_marker: z2.number(),
|
|
2315
|
-
end_marker: z2.number(),
|
|
2316
|
-
now_marker: z2.number(),
|
|
2317
|
-
predicted_ready_at_ms: z2.number(),
|
|
2318
|
-
playlist_url: z2.string()
|
|
2319
|
-
}).passthrough();
|
|
2320
|
-
var ClipFailedPayloadSchema = z2.object({
|
|
2321
|
-
reason: z2.string().default("unknown")
|
|
2322
|
-
}).passthrough();
|
|
2323
|
-
function clipFromPayload(payload, options = {}) {
|
|
2324
|
-
const playlistUrl = options.coordinatorBaseUrl ? rewriteUrlHost(payload.playlist_url, options.coordinatorBaseUrl) : payload.playlist_url;
|
|
2325
|
-
return {
|
|
2326
|
-
sessionId: payload.session_id,
|
|
2327
|
-
kind: payload.kind,
|
|
2328
|
-
startMarker: payload.start_marker,
|
|
2329
|
-
endMarker: payload.end_marker,
|
|
2330
|
-
nowMarker: payload.now_marker,
|
|
2331
|
-
predictedReadyAtMs: payload.predicted_ready_at_ms,
|
|
2332
|
-
playlistUrl
|
|
2333
|
-
};
|
|
2334
|
-
}
|
|
2335
|
-
function rewriteUrlHost(target, base) {
|
|
2336
|
-
try {
|
|
2337
|
-
if (!/^[a-z][a-z0-9+.-]*:/i.test(target)) {
|
|
2338
|
-
return new URL(target, base).toString();
|
|
2339
|
-
}
|
|
2340
|
-
const baseUrl = new URL(base);
|
|
2341
|
-
const parsed = new URL(target);
|
|
2342
|
-
parsed.protocol = baseUrl.protocol;
|
|
2343
|
-
parsed.hostname = baseUrl.hostname;
|
|
2344
|
-
parsed.port = baseUrl.port;
|
|
2345
|
-
return parsed.toString();
|
|
2346
|
-
} catch (e) {
|
|
2347
|
-
return target;
|
|
2348
|
-
}
|
|
2349
|
-
}
|
|
2350
|
-
var DEFAULT_PLAYLIST_POLL_SLACK_MS = 15e3;
|
|
2351
|
-
function fetchPlaylist(_0) {
|
|
2352
|
-
return __async(this, arguments, function* (playlistUrl, options = {}) {
|
|
2353
|
-
var _a, _b, _c, _d;
|
|
2354
|
-
const minDelay = Math.max(0, (_a = options.minRetryDelayMs) != null ? _a : 200);
|
|
2355
|
-
const maxDelay = Math.max(minDelay, (_b = options.maxRetryDelayMs) != null ? _b : 2e3);
|
|
2356
|
-
const hasDeadline = typeof options.slackMs === "number" && Number.isFinite(options.slackMs);
|
|
2357
|
-
const startedPollingAt = Date.now();
|
|
2358
|
-
const deadlineMs = hasDeadline ? Math.max(
|
|
2359
|
-
(_c = options.predictedReadyAtMs) != null ? _c : startedPollingAt,
|
|
2360
|
-
startedPollingAt
|
|
2361
|
-
) + options.slackMs : void 0;
|
|
2362
|
-
const maxRetries = typeof options.maxRetries === "number" ? options.maxRetries : void 0;
|
|
2363
|
-
const headers = options.jwt ? { Authorization: `Bearer ${options.jwt}` } : void 0;
|
|
2364
|
-
let attempt = 0;
|
|
2365
|
-
let lastStatus = 0;
|
|
2366
|
-
while (true) {
|
|
2367
|
-
let response;
|
|
2368
|
-
try {
|
|
2369
|
-
response = yield fetch(playlistUrl, {
|
|
2370
|
-
signal: options.signal,
|
|
2371
|
-
headers
|
|
2372
|
-
});
|
|
2373
|
-
} catch (error) {
|
|
2374
|
-
throw new RecordingError(
|
|
2375
|
-
"PLAYLIST_FETCH_FAILED",
|
|
2376
|
-
`Network error fetching playlist: ${error.message}`
|
|
2377
|
-
);
|
|
2378
|
-
}
|
|
2379
|
-
lastStatus = response.status;
|
|
2380
|
-
if (response.status === 202) {
|
|
2381
|
-
if (deadlineMs !== void 0 && Date.now() >= deadlineMs) {
|
|
2382
|
-
throw new RecordingError(
|
|
2383
|
-
"CLIP_NOT_READY",
|
|
2384
|
-
`Boundary chunk still pending after ${options.slackMs}ms grace (predicted ready ${new Date(
|
|
2385
|
-
(_d = options.predictedReadyAtMs) != null ? _d : startedPollingAt
|
|
2386
|
-
).toISOString()}). Runtime may have crashed mid-clip.`
|
|
2387
|
-
);
|
|
2388
|
-
}
|
|
2389
|
-
if (maxRetries !== void 0 && attempt >= maxRetries) {
|
|
2390
|
-
throw new RecordingError(
|
|
2391
|
-
"CLIP_NOT_READY",
|
|
2392
|
-
`Manifest still pending after ${attempt + 1} attempts (last status ${lastStatus})`
|
|
2393
|
-
);
|
|
2394
|
-
}
|
|
2395
|
-
const headerDelay = parseRetryAfter(
|
|
2396
|
-
response.headers.get("Retry-After"),
|
|
2397
|
-
minDelay
|
|
2398
|
-
);
|
|
2399
|
-
const delay = Math.min(maxDelay, Math.max(minDelay, headerDelay));
|
|
2400
|
-
const clampedDelay = deadlineMs !== void 0 ? Math.min(delay, Math.max(0, deadlineMs - Date.now())) : delay;
|
|
2401
|
-
yield sleep(clampedDelay, options.signal);
|
|
2402
|
-
attempt++;
|
|
2403
|
-
continue;
|
|
2404
|
-
}
|
|
2405
|
-
if (response.status === 200) {
|
|
2406
|
-
return yield response.text();
|
|
2407
|
-
}
|
|
2408
|
-
if (response.status === 410) {
|
|
2409
|
-
throw new RecordingError(
|
|
2410
|
-
"CLIP_GONE",
|
|
2411
|
-
"Clip is no longer available (chunks aged out or session unknown)"
|
|
2412
|
-
);
|
|
2413
|
-
}
|
|
2414
|
-
if (response.status === 404) {
|
|
2415
|
-
throw new RecordingError(
|
|
2416
|
-
"CLIP_GONE",
|
|
2417
|
-
"Session not found for clip playlist"
|
|
2418
|
-
);
|
|
2419
|
-
}
|
|
2420
|
-
throw new RecordingError(
|
|
2421
|
-
"PLAYLIST_FETCH_FAILED",
|
|
2422
|
-
`Manifest endpoint returned HTTP ${response.status}`
|
|
2423
|
-
);
|
|
2424
|
-
}
|
|
2425
|
-
});
|
|
2426
|
-
}
|
|
2427
|
-
function parsePlaylist(manifestBody, playlistUrl) {
|
|
2428
|
-
let initUrl;
|
|
2429
|
-
const segments = [];
|
|
2430
|
-
const lines = manifestBody.split(/\r?\n/);
|
|
2431
|
-
for (const line of lines) {
|
|
2432
|
-
const trimmed = line.trim();
|
|
2433
|
-
if (!trimmed) continue;
|
|
2434
|
-
if (trimmed.startsWith("#EXT-X-MAP")) {
|
|
2435
|
-
const match = trimmed.match(/URI="([^"]+)"/);
|
|
2436
|
-
if (match) {
|
|
2437
|
-
initUrl = resolveAgainst(match[1], playlistUrl);
|
|
2438
|
-
}
|
|
2439
|
-
continue;
|
|
2440
|
-
}
|
|
2441
|
-
if (trimmed.startsWith("#")) {
|
|
2442
|
-
continue;
|
|
2443
|
-
}
|
|
2444
|
-
segments.push(resolveAgainst(trimmed, playlistUrl));
|
|
2445
|
-
}
|
|
2446
|
-
if (!initUrl) {
|
|
2447
|
-
throw new RecordingError(
|
|
2448
|
-
"INVALID_PLAYLIST",
|
|
2449
|
-
"Playlist is missing an #EXT-X-MAP init segment URI"
|
|
2450
|
-
);
|
|
2451
|
-
}
|
|
2452
|
-
if (segments.length === 0) {
|
|
2453
|
-
throw new RecordingError(
|
|
2454
|
-
"INVALID_PLAYLIST",
|
|
2455
|
-
"Playlist contains no media segments"
|
|
2456
|
-
);
|
|
2457
|
-
}
|
|
2458
|
-
return { initUrl, segmentUrls: segments };
|
|
2459
|
-
}
|
|
2460
|
-
function createPlayableManifestUrl(manifestBody, playlistUrl) {
|
|
2461
|
-
if (typeof Blob === "undefined" || typeof URL === "undefined" || typeof URL.createObjectURL !== "function") {
|
|
2462
|
-
throw new RecordingError(
|
|
2463
|
-
"INVALID_PLAYLIST",
|
|
2464
|
-
"createPlayableManifestUrl requires a browser environment with URL.createObjectURL"
|
|
2465
|
-
);
|
|
2466
|
-
}
|
|
2467
|
-
const rewritten = absolutizeManifestUrls(manifestBody, playlistUrl);
|
|
2468
|
-
const blob = new Blob([rewritten], {
|
|
2469
|
-
type: "application/vnd.apple.mpegurl"
|
|
2470
|
-
});
|
|
2471
|
-
return URL.createObjectURL(blob);
|
|
2472
|
-
}
|
|
2473
|
-
function absolutizeManifestUrls(manifestBody, playlistUrl) {
|
|
2474
|
-
const eol = manifestBody.includes("\r\n") ? "\r\n" : "\n";
|
|
2475
|
-
const lines = manifestBody.split(/\r?\n/);
|
|
2476
|
-
const out = [];
|
|
2477
|
-
for (const line of lines) {
|
|
2478
|
-
if (line.startsWith("#EXT-X-MAP")) {
|
|
2479
|
-
out.push(
|
|
2480
|
-
line.replace(
|
|
2481
|
-
/URI="([^"]+)"/,
|
|
2482
|
-
(_, uri) => `URI="${resolveAgainst(uri, playlistUrl)}"`
|
|
2483
|
-
)
|
|
2484
|
-
);
|
|
2485
|
-
continue;
|
|
2486
|
-
}
|
|
2487
|
-
const trimmed = line.trim();
|
|
2488
|
-
if (!trimmed || trimmed.startsWith("#")) {
|
|
2489
|
-
out.push(line);
|
|
2490
|
-
continue;
|
|
2491
|
-
}
|
|
2492
|
-
out.push(resolveAgainst(trimmed, playlistUrl));
|
|
2493
|
-
}
|
|
2494
|
-
return out.join(eol);
|
|
2495
|
-
}
|
|
2496
|
-
function downloadClipAsFile(_0) {
|
|
2497
|
-
return __async(this, arguments, function* (clip, filename = "reactor-clip.mp4", options = {}) {
|
|
2498
|
-
const manifestBody = yield fetchPlaylist(clip.playlistUrl, {
|
|
2499
|
-
predictedReadyAtMs: clip.predictedReadyAtMs,
|
|
2500
|
-
signal: options.signal,
|
|
2501
|
-
jwt: options.jwt
|
|
2502
|
-
});
|
|
2503
|
-
const blob = yield assembleClipBlob(manifestBody, clip.playlistUrl, options);
|
|
2504
|
-
if (filename === null) {
|
|
2505
|
-
return blob;
|
|
2506
|
-
}
|
|
2507
|
-
if (typeof document === "undefined" || typeof URL.createObjectURL !== "function") {
|
|
2508
|
-
throw new RecordingError(
|
|
2509
|
-
"DOWNLOAD_UNSUPPORTED",
|
|
2510
|
-
"downloadClipAsFile requires a DOM environment; pass filename=null to skip the download trigger"
|
|
2511
|
-
);
|
|
2512
|
-
}
|
|
2513
|
-
triggerBrowserDownload(blob, filename);
|
|
2514
|
-
return blob;
|
|
2515
|
-
});
|
|
2516
|
-
}
|
|
2517
|
-
function assembleClipBlob(_0, _1) {
|
|
2518
|
-
return __async(this, arguments, function* (manifestBody, playlistUrl, options = {}) {
|
|
2519
|
-
var _a;
|
|
2520
|
-
const { initUrl, segmentUrls } = parsePlaylist(manifestBody, playlistUrl);
|
|
2521
|
-
const orderedUrls = [initUrl, ...segmentUrls];
|
|
2522
|
-
const parts = [];
|
|
2523
|
-
let bytes = 0;
|
|
2524
|
-
for (let i = 0; i < orderedUrls.length; i++) {
|
|
2525
|
-
const url = orderedUrls[i];
|
|
2526
|
-
let response;
|
|
2527
|
-
try {
|
|
2528
|
-
response = yield fetch(url, { signal: options.signal });
|
|
2529
|
-
} catch (error) {
|
|
2530
|
-
throw new RecordingError(
|
|
2531
|
-
"CHUNK_FETCH_FAILED",
|
|
2532
|
-
`Network error fetching chunk ${i}: ${error.message}`
|
|
2533
|
-
);
|
|
2534
|
-
}
|
|
2535
|
-
if (!response.ok) {
|
|
2536
|
-
throw new RecordingError(
|
|
2537
|
-
"CHUNK_FETCH_FAILED",
|
|
2538
|
-
`Chunk ${i} returned HTTP ${response.status}`
|
|
2539
|
-
);
|
|
2540
|
-
}
|
|
2541
|
-
const data = new Uint8Array(yield response.arrayBuffer());
|
|
2542
|
-
parts.push(data);
|
|
2543
|
-
bytes += data.byteLength;
|
|
2544
|
-
(_a = options.onProgress) == null ? void 0 : _a.call(options, {
|
|
2545
|
-
fetched: i + 1,
|
|
2546
|
-
total: orderedUrls.length,
|
|
2547
|
-
bytes
|
|
2548
|
-
});
|
|
2549
|
-
}
|
|
2550
|
-
const finalBytes = yield maybeRemux(parts);
|
|
2551
|
-
return new Blob([finalBytes], { type: "video/mp4" });
|
|
2552
|
-
});
|
|
2553
|
-
}
|
|
2554
|
-
function maybeRemux(parts) {
|
|
2555
|
-
return __async(this, null, function* () {
|
|
2556
|
-
const input = concatUint8Arrays(parts);
|
|
2557
|
-
try {
|
|
2558
|
-
const MP4Box = yield loadMp4Box();
|
|
2559
|
-
return yield remuxFragmentedToFlat(input, MP4Box);
|
|
2560
|
-
} catch (error) {
|
|
2561
|
-
console.warn(
|
|
2562
|
-
"[Reactor] Clip remux failed, returning fragmented MP4 instead.",
|
|
2563
|
-
error
|
|
2564
|
-
);
|
|
2565
|
-
return input;
|
|
2566
|
-
}
|
|
2567
|
-
});
|
|
2568
|
-
}
|
|
2569
|
-
var __remuxInternals = {
|
|
2570
|
-
loadMp4Box: () => import("mp4box")
|
|
2571
|
-
};
|
|
2572
|
-
function loadMp4Box() {
|
|
2573
|
-
return __remuxInternals.loadMp4Box();
|
|
2574
|
-
}
|
|
2575
|
-
function remuxFragmentedToFlat(input, MP4Box) {
|
|
2576
|
-
return __async(this, null, function* () {
|
|
2577
|
-
return new Promise((resolve, reject) => {
|
|
2578
|
-
const inFile = MP4Box.createFile();
|
|
2579
|
-
const outFile = MP4Box.createFile();
|
|
2580
|
-
outFile.init({ brands: ["isom", "mp42", "avc1", "iso2"] });
|
|
2581
|
-
const inToOutTrack = /* @__PURE__ */ new Map();
|
|
2582
|
-
const trackBaselineDts = /* @__PURE__ */ new Map();
|
|
2583
|
-
let settled = false;
|
|
2584
|
-
const fail = (err) => {
|
|
2585
|
-
if (settled) return;
|
|
2586
|
-
settled = true;
|
|
2587
|
-
reject(err);
|
|
2588
|
-
};
|
|
2589
|
-
inFile.onError = (_module, message) => {
|
|
2590
|
-
fail(new Error(message));
|
|
2591
|
-
};
|
|
2592
|
-
inFile.onReady = (info) => {
|
|
2593
|
-
if (!info.tracks.length) {
|
|
2594
|
-
fail(new Error("no tracks in input"));
|
|
2595
|
-
return;
|
|
2596
|
-
}
|
|
2597
|
-
for (const track of info.tracks) {
|
|
2598
|
-
inFile.setExtractionOptions(track.id, null, { nbSamples: 1e3 });
|
|
2599
|
-
}
|
|
2600
|
-
inFile.start();
|
|
2601
|
-
};
|
|
2602
|
-
inFile.onSamples = (id, _user, samples) => {
|
|
2603
|
-
if (settled || samples.length === 0) return;
|
|
2604
|
-
let outId = inToOutTrack.get(id);
|
|
2605
|
-
let baseline = trackBaselineDts.get(id);
|
|
2606
|
-
if (outId === void 0) {
|
|
2607
|
-
const firstSample = samples[0];
|
|
2608
|
-
const sampleEntry = firstSample.description;
|
|
2609
|
-
const inputTrack = trackInfoById(inFile, id);
|
|
2610
|
-
outId = outFile.addTrack({
|
|
2611
|
-
type: sampleEntry.type,
|
|
2612
|
-
timescale: firstSample.timescale,
|
|
2613
|
-
width: inputTrack == null ? void 0 : inputTrack.track_width,
|
|
2614
|
-
height: inputTrack == null ? void 0 : inputTrack.track_height,
|
|
2615
|
-
language: inputTrack == null ? void 0 : inputTrack.language,
|
|
2616
|
-
hdlr: (inputTrack == null ? void 0 : inputTrack.video) ? "vide" : (inputTrack == null ? void 0 : inputTrack.audio) ? "soun" : void 0,
|
|
2617
|
-
// `boxes` is typed as `Box[]` but `description_boxes`
|
|
2618
|
-
// wants the narrower `BoxKind[]` union — at runtime they
|
|
2619
|
-
// are the same concrete instances, just typed loosely.
|
|
2620
|
-
description_boxes: sampleEntry.boxes
|
|
2621
|
-
});
|
|
2622
|
-
baseline = firstSample.dts;
|
|
2623
|
-
inToOutTrack.set(id, outId);
|
|
2624
|
-
trackBaselineDts.set(id, baseline);
|
|
2625
|
-
}
|
|
2626
|
-
const dtsShift = baseline;
|
|
2627
|
-
for (const sample of samples) {
|
|
2628
|
-
if (!sample.data) continue;
|
|
2629
|
-
outFile.addSample(outId, sample.data, {
|
|
2630
|
-
duration: sample.duration,
|
|
2631
|
-
dts: sample.dts - dtsShift,
|
|
2632
|
-
cts: sample.cts - dtsShift,
|
|
2633
|
-
is_sync: sample.is_sync
|
|
2634
|
-
});
|
|
2635
|
-
}
|
|
2636
|
-
};
|
|
2637
|
-
let buf;
|
|
2638
|
-
try {
|
|
2639
|
-
buf = MP4Box.MP4BoxBuffer.fromArrayBuffer(
|
|
2640
|
-
input.buffer.slice(
|
|
2641
|
-
input.byteOffset,
|
|
2642
|
-
input.byteOffset + input.byteLength
|
|
2643
|
-
),
|
|
2644
|
-
0
|
|
2645
|
-
);
|
|
2646
|
-
} catch (error) {
|
|
2647
|
-
fail(error);
|
|
2648
|
-
return;
|
|
2649
|
-
}
|
|
2650
|
-
try {
|
|
2651
|
-
inFile.appendBuffer(buf);
|
|
2652
|
-
inFile.flush();
|
|
2653
|
-
} catch (error) {
|
|
2654
|
-
fail(error);
|
|
2655
|
-
return;
|
|
2656
|
-
}
|
|
2657
|
-
if (settled) return;
|
|
2658
|
-
if (inToOutTrack.size === 0) {
|
|
2659
|
-
fail(new Error("no samples extracted from input"));
|
|
2660
|
-
return;
|
|
2661
|
-
}
|
|
2662
|
-
let output;
|
|
2663
|
-
try {
|
|
2664
|
-
const stream = outFile.getBuffer();
|
|
2665
|
-
output = new Uint8Array(
|
|
2666
|
-
stream.buffer.slice(0, stream.byteLength)
|
|
2667
|
-
);
|
|
2668
|
-
} catch (error) {
|
|
2669
|
-
fail(error);
|
|
2670
|
-
return;
|
|
2671
|
-
}
|
|
2672
|
-
settled = true;
|
|
2673
|
-
resolve(output);
|
|
2674
|
-
});
|
|
2675
|
-
});
|
|
2676
|
-
}
|
|
2677
|
-
function trackInfoById(file, id) {
|
|
2678
|
-
const info = file.getInfo();
|
|
2679
|
-
return info.tracks.find((t) => t.id === id);
|
|
2680
|
-
}
|
|
2681
|
-
function concatUint8Arrays(parts) {
|
|
2682
|
-
if (parts.length === 1) return parts[0];
|
|
2683
|
-
let total = 0;
|
|
2684
|
-
for (const p of parts) total += p.byteLength;
|
|
2685
|
-
const out = new Uint8Array(total);
|
|
2686
|
-
let offset = 0;
|
|
2687
|
-
for (const p of parts) {
|
|
2688
|
-
out.set(p, offset);
|
|
2689
|
-
offset += p.byteLength;
|
|
2690
|
-
}
|
|
2691
|
-
return out;
|
|
2692
|
-
}
|
|
2693
|
-
function resolveAgainst(target, base) {
|
|
2694
|
-
try {
|
|
2695
|
-
return new URL(target, base).toString();
|
|
2696
|
-
} catch (e) {
|
|
2697
|
-
return target;
|
|
2698
|
-
}
|
|
2699
|
-
}
|
|
2700
|
-
function parseRetryAfter(header, fallbackMs) {
|
|
2701
|
-
if (!header) return fallbackMs;
|
|
2702
|
-
const seconds = Number(header);
|
|
2703
|
-
if (Number.isFinite(seconds) && seconds >= 0) {
|
|
2704
|
-
return seconds * 1e3;
|
|
2705
|
-
}
|
|
2706
|
-
const dateMs = Date.parse(header);
|
|
2707
|
-
if (!Number.isNaN(dateMs)) {
|
|
2708
|
-
return Math.max(0, dateMs - Date.now());
|
|
2709
|
-
}
|
|
2710
|
-
return fallbackMs;
|
|
2711
|
-
}
|
|
2712
|
-
function sleep(ms, signal) {
|
|
2713
|
-
return new Promise((resolve, reject) => {
|
|
2714
|
-
if (signal == null ? void 0 : signal.aborted) {
|
|
2715
|
-
reject(new DOMException("Aborted", "AbortError"));
|
|
2716
|
-
return;
|
|
2717
|
-
}
|
|
2718
|
-
const timer = setTimeout(() => {
|
|
2719
|
-
signal == null ? void 0 : signal.removeEventListener("abort", onAbort);
|
|
2720
|
-
resolve();
|
|
2721
|
-
}, ms);
|
|
2722
|
-
const onAbort = () => {
|
|
2723
|
-
clearTimeout(timer);
|
|
2724
|
-
reject(new DOMException("Aborted", "AbortError"));
|
|
2725
|
-
};
|
|
2726
|
-
signal == null ? void 0 : signal.addEventListener("abort", onAbort, { once: true });
|
|
2727
|
-
});
|
|
2728
|
-
}
|
|
2729
|
-
function triggerBrowserDownload(blob, filename) {
|
|
2730
|
-
const objectUrl = URL.createObjectURL(blob);
|
|
2731
|
-
try {
|
|
2732
|
-
const a = document.createElement("a");
|
|
2733
|
-
a.href = objectUrl;
|
|
2734
|
-
a.download = filename;
|
|
2735
|
-
a.style.display = "none";
|
|
2736
|
-
document.body.appendChild(a);
|
|
2737
|
-
a.click();
|
|
2738
|
-
a.remove();
|
|
2739
|
-
} finally {
|
|
2740
|
-
URL.revokeObjectURL(objectUrl);
|
|
2741
|
-
}
|
|
2742
|
-
}
|
|
2743
|
-
|
|
2744
|
-
// src/core/RecordingClient.ts
|
|
2745
|
-
var DEFAULT_CLIP_REQUEST_TIMEOUT_MS = 1e4;
|
|
2746
|
-
var RecordingClient = class {
|
|
2747
|
-
constructor(host, options = {}) {
|
|
2748
|
-
this.host = host;
|
|
2749
|
-
// FIFO queue: the runtime processes requests in receipt order and
|
|
2750
|
-
// `clipFailed` carries no discriminator, so FIFO matching is the
|
|
2751
|
-
// simplest correct correlator.
|
|
2752
|
-
this.pendingClipRequests = [];
|
|
2753
|
-
/** Cleanup handles for the host event subscriptions. */
|
|
2754
|
-
this.unsubscribers = [];
|
|
2755
|
-
var _a;
|
|
2756
|
-
this.requestTimeoutMs = (_a = options.requestTimeoutMs) != null ? _a : DEFAULT_CLIP_REQUEST_TIMEOUT_MS;
|
|
2757
|
-
this.unsubscribers.push(
|
|
2758
|
-
this.host.onRuntimeMessage((message) => this.onRuntimeMessage(message))
|
|
2759
|
-
);
|
|
2760
|
-
this.unsubscribers.push(
|
|
2761
|
-
this.host.onStatusChanged((status) => this.onStatusChanged(status))
|
|
2762
|
-
);
|
|
2763
|
-
}
|
|
2764
|
-
/**
|
|
2765
|
-
* Request a clip covering the last `durationSeconds` of the live
|
|
2766
|
-
* session. See {@link Reactor.requestClip}.
|
|
2767
|
-
*/
|
|
2768
|
-
requestClip(durationSeconds) {
|
|
2769
|
-
return __async(this, null, function* () {
|
|
2770
|
-
if (typeof durationSeconds !== "number" || !Number.isFinite(durationSeconds) || durationSeconds <= 0) {
|
|
2771
|
-
throw new RecordingError(
|
|
2772
|
-
"INVALID_DURATION",
|
|
2773
|
-
"durationSeconds must be a positive finite number"
|
|
2774
|
-
);
|
|
2775
|
-
}
|
|
2776
|
-
const status = this.host.getStatus();
|
|
2777
|
-
if (status !== "ready") {
|
|
2778
|
-
throw new RecordingError(
|
|
2779
|
-
"DISCONNECTED",
|
|
2780
|
-
`Cannot request clip while status is "${status}"`
|
|
2781
|
-
);
|
|
2782
|
-
}
|
|
2783
|
-
return this.dispatchClipRequest(RuntimeRecordingMessageType.REQUEST_CLIP, {
|
|
2784
|
-
duration_seconds: durationSeconds
|
|
2785
|
-
});
|
|
2786
|
-
});
|
|
2787
|
-
}
|
|
2788
|
-
/**
|
|
2789
|
-
* Request a clip covering the entire session up to "now". See
|
|
2790
|
-
* {@link Reactor.requestRecording}.
|
|
2791
|
-
*/
|
|
2792
|
-
requestRecording() {
|
|
2793
|
-
return __async(this, null, function* () {
|
|
2794
|
-
const status = this.host.getStatus();
|
|
2795
|
-
if (status !== "ready") {
|
|
2796
|
-
throw new RecordingError(
|
|
2797
|
-
"DISCONNECTED",
|
|
2798
|
-
`Cannot request recording while status is "${status}"`
|
|
2799
|
-
);
|
|
2800
|
-
}
|
|
2801
|
-
return this.dispatchClipRequest(
|
|
2802
|
-
RuntimeRecordingMessageType.REQUEST_RECORDING,
|
|
2803
|
-
{}
|
|
2804
|
-
);
|
|
2805
|
-
});
|
|
2806
|
-
}
|
|
2807
|
-
/**
|
|
2808
|
-
* Poll `/clips` and return the raw manifest body. Same polling
|
|
2809
|
-
* semantics as the bare {@link fetchPlaylist} helper; the caller is
|
|
2810
|
-
* responsible for supplying the Coordinator JWT via `options.jwt`
|
|
2811
|
-
* (origin-scoped to `clip.playlistUrl`). In local mode against the
|
|
2812
|
-
* HttpRuntime, `options.jwt` should be omitted.
|
|
2813
|
-
*/
|
|
2814
|
-
fetchPlaylist(_0) {
|
|
2815
|
-
return __async(this, arguments, function* (clip, options = {}) {
|
|
2816
|
-
return fetchPlaylist(clip.playlistUrl, __spreadValues({
|
|
2817
|
-
predictedReadyAtMs: clip.predictedReadyAtMs
|
|
2818
|
-
}, options));
|
|
2819
|
-
});
|
|
2820
|
-
}
|
|
2821
|
-
/**
|
|
2822
|
-
* Fetch the manifest and return a `blob:` URL suitable for
|
|
2823
|
-
* `<video src>` / `hls.js`. The player reads the manifest from
|
|
2824
|
-
* browser memory; chunk URLs inside are presigned S3 GETs.
|
|
2825
|
-
*
|
|
2826
|
-
* Caller owns the returned URL — revoke it via `URL.revokeObjectURL`
|
|
2827
|
-
* when playback tears down. Pass `options.jwt` for production
|
|
2828
|
-
* `/clips` (the Coordinator hop) — see {@link FetchPlaylistOptions}.
|
|
2829
|
-
*/
|
|
2830
|
-
getPlayableManifestUrl(_0) {
|
|
2831
|
-
return __async(this, arguments, function* (clip, options = {}) {
|
|
2832
|
-
const body = yield this.fetchPlaylist(clip, options);
|
|
2833
|
-
return createPlayableManifestUrl(body, clip.playlistUrl);
|
|
2834
|
-
});
|
|
2835
|
-
}
|
|
2836
|
-
/**
|
|
2837
|
-
* Thin delegation to {@link downloadClipAsFile}. Caller must pass
|
|
2838
|
-
* `options.jwt` in production — see {@link DownloadClipOptions}.
|
|
2839
|
-
*/
|
|
2840
|
-
downloadClipAsFile(clip, filename = "reactor-clip.mp4", options) {
|
|
2841
|
-
return __async(this, null, function* () {
|
|
2842
|
-
return downloadClipAsFile(clip, filename, options);
|
|
2843
|
-
});
|
|
2844
|
-
}
|
|
2845
|
-
/**
|
|
2846
|
-
* Drop every pending request and unsubscribe from host events.
|
|
2847
|
-
* Safe to call multiple times; further `requestClip` /
|
|
2848
|
-
* `requestRecording` calls after `destroy()` will hang waiting for
|
|
2849
|
-
* a response that will never arrive — host should not call into
|
|
2850
|
-
* the client after destroy.
|
|
2851
|
-
*/
|
|
2852
|
-
destroy() {
|
|
2853
|
-
this.rejectPending("RecordingClient destroyed");
|
|
2854
|
-
while (this.unsubscribers.length > 0) {
|
|
2855
|
-
const off = this.unsubscribers.pop();
|
|
2856
|
-
try {
|
|
2857
|
-
off == null ? void 0 : off();
|
|
2858
|
-
} catch (e) {
|
|
2859
|
-
}
|
|
2860
|
-
}
|
|
2861
|
-
}
|
|
2862
|
-
/**
|
|
2863
|
-
* Register a pending FIFO entry, send the runtime message via
|
|
2864
|
-
* the host, and resolve when the next `clipReady` / `clipFailed`
|
|
2865
|
-
* arrives.
|
|
2866
|
-
*/
|
|
2867
|
-
dispatchClipRequest(messageType, payload) {
|
|
2868
|
-
return new Promise((resolve, reject) => {
|
|
2869
|
-
const pending = { resolve, reject };
|
|
2870
|
-
pending.timeoutHandle = setTimeout(() => {
|
|
2871
|
-
const idx = this.pendingClipRequests.indexOf(pending);
|
|
2872
|
-
if (idx === -1) return;
|
|
2873
|
-
this.pendingClipRequests.splice(idx, 1);
|
|
2874
|
-
reject(
|
|
2875
|
-
new RecordingError(
|
|
2876
|
-
"REQUEST_TIMEOUT",
|
|
2877
|
-
`No clipReady/clipFailed within ${this.requestTimeoutMs}ms`
|
|
2878
|
-
)
|
|
2879
|
-
);
|
|
2880
|
-
}, this.requestTimeoutMs);
|
|
2881
|
-
this.pendingClipRequests.push(pending);
|
|
2882
|
-
try {
|
|
2883
|
-
void this.host.sendRuntimeCommand(messageType, payload);
|
|
2884
|
-
} catch (error) {
|
|
2885
|
-
const idx = this.pendingClipRequests.indexOf(pending);
|
|
2886
|
-
if (idx !== -1) this.pendingClipRequests.splice(idx, 1);
|
|
2887
|
-
if (pending.timeoutHandle) clearTimeout(pending.timeoutHandle);
|
|
2888
|
-
reject(
|
|
2889
|
-
new RecordingError(
|
|
2890
|
-
"INTERNAL_ERROR",
|
|
2891
|
-
`Failed to send ${messageType}: ${error.message}`
|
|
2892
|
-
)
|
|
2893
|
-
);
|
|
2894
|
-
}
|
|
2895
|
-
});
|
|
2896
|
-
}
|
|
2897
|
-
/**
|
|
2898
|
-
* Match inbound `clipReady` / `clipFailed` to the next pending
|
|
2899
|
-
* request FIFO; ignore every other runtime message type.
|
|
2900
|
-
*/
|
|
2901
|
-
onRuntimeMessage(message) {
|
|
2902
|
-
var _a;
|
|
2903
|
-
if (!message || typeof message !== "object") return;
|
|
2904
|
-
const msg = message;
|
|
2905
|
-
const type = msg.type;
|
|
2906
|
-
if (type !== RuntimeRecordingMessageType.CLIP_READY && type !== RuntimeRecordingMessageType.CLIP_FAILED) {
|
|
2907
|
-
return;
|
|
2908
|
-
}
|
|
2909
|
-
const pending = this.pendingClipRequests.shift();
|
|
2910
|
-
if (!pending) {
|
|
2911
|
-
console.warn("[Reactor] Received", type, "with no pending request");
|
|
2912
|
-
return;
|
|
2913
|
-
}
|
|
2914
|
-
if (pending.timeoutHandle) clearTimeout(pending.timeoutHandle);
|
|
2915
|
-
if (type === RuntimeRecordingMessageType.CLIP_READY) {
|
|
2916
|
-
const parsed = ClipReadyPayloadSchema.safeParse(msg.data);
|
|
2917
|
-
if (!parsed.success) {
|
|
2918
|
-
pending.reject(
|
|
2919
|
-
new RecordingError(
|
|
2920
|
-
"INTERNAL_ERROR",
|
|
2921
|
-
`Malformed clipReady payload: ${parsed.error.message}`
|
|
2922
|
-
)
|
|
2923
|
-
);
|
|
2924
|
-
return;
|
|
2925
|
-
}
|
|
2926
|
-
pending.resolve(
|
|
2927
|
-
clipFromPayload(parsed.data, {
|
|
2928
|
-
coordinatorBaseUrl: this.host.getCoordinatorBaseUrl()
|
|
2929
|
-
})
|
|
2930
|
-
);
|
|
2931
|
-
return;
|
|
2932
|
-
}
|
|
2933
|
-
const parsedFail = ClipFailedPayloadSchema.safeParse((_a = msg.data) != null ? _a : {});
|
|
2934
|
-
const reason = parsedFail.success ? parsedFail.data.reason : "unknown";
|
|
2935
|
-
pending.reject(
|
|
2936
|
-
new RecordingError(
|
|
2937
|
-
reason === "recorder disabled" || reason === "recorder disabled or encoder crashed" ? "RECORDER_DISABLED" : "INTERNAL_ERROR",
|
|
2938
|
-
reason
|
|
2939
|
-
)
|
|
2940
|
-
);
|
|
2941
|
-
}
|
|
2942
|
-
onStatusChanged(status) {
|
|
2943
|
-
if (status === "disconnected") {
|
|
2944
|
-
this.rejectPending("Reactor disconnected");
|
|
2945
|
-
}
|
|
2946
|
-
}
|
|
2947
|
-
/** Reject every in-flight request with a typed disconnect error. */
|
|
2948
|
-
rejectPending(reason) {
|
|
2949
|
-
if (this.pendingClipRequests.length === 0) return;
|
|
2950
|
-
const pending = this.pendingClipRequests;
|
|
2951
|
-
this.pendingClipRequests = [];
|
|
2952
|
-
for (const entry of pending) {
|
|
2953
|
-
if (entry.timeoutHandle) clearTimeout(entry.timeoutHandle);
|
|
2954
|
-
entry.reject(new RecordingError("DISCONNECTED", reason));
|
|
2955
|
-
}
|
|
2956
|
-
}
|
|
2957
|
-
};
|
|
2958
|
-
|
|
2959
|
-
// src/core/Reactor.ts
|
|
2960
|
-
var LOCAL_COORDINATOR_URL = "http://localhost:8080";
|
|
2961
|
-
var DEFAULT_BASE_URL = "https://api.reactor.inc";
|
|
2962
|
-
var TrackHintSchema = z3.object({
|
|
2963
|
-
name: z3.string(),
|
|
2964
|
-
kind: z3.enum(["video", "audio"]),
|
|
2965
|
-
direction: z3.enum(["recvonly", "sendonly"])
|
|
2966
|
-
});
|
|
2967
|
-
var OptionsSchema = z3.object({
|
|
2968
|
-
apiUrl: z3.string().default(DEFAULT_BASE_URL),
|
|
2969
|
-
modelName: z3.string(),
|
|
2970
|
-
local: z3.boolean().default(false),
|
|
2971
|
-
modelTracks: z3.array(TrackHintSchema).optional()
|
|
2972
|
-
});
|
|
2973
|
-
var Reactor = class {
|
|
2974
|
-
constructor(options) {
|
|
2975
|
-
this.status = "disconnected";
|
|
2976
|
-
/**
|
|
2977
|
-
* True only when the active session was created by THIS connect flow
|
|
2978
|
-
* (via `createSession()`). False when the session was adopted via
|
|
2979
|
-
* `connect({ sessionId })`. We must never DELETE a session we did not
|
|
2980
|
-
* create — another client (or the backend that created it) owns its
|
|
2981
|
-
* lifecycle, so on disconnect/teardown/error an adopting client tears
|
|
2982
|
-
* down its own transport but leaves the session alive.
|
|
2983
|
-
*/
|
|
2984
|
-
this.createdSession = false;
|
|
2985
|
-
this.retryingSessionLoss = false;
|
|
2986
|
-
this.tracks = [];
|
|
2987
|
-
this.autoResumeTracks = false;
|
|
2988
|
-
this.eventListeners = /* @__PURE__ */ new Map();
|
|
2989
|
-
const validatedOptions = OptionsSchema.parse(options);
|
|
2990
|
-
this.coordinatorUrl = validatedOptions.apiUrl;
|
|
2991
|
-
this.model = validatedOptions.modelName;
|
|
2992
|
-
this.local = validatedOptions.local;
|
|
2993
|
-
if (this.local && options.apiUrl === void 0) {
|
|
2994
|
-
this.coordinatorUrl = LOCAL_COORDINATOR_URL;
|
|
2995
|
-
}
|
|
2996
|
-
if (validatedOptions.modelTracks) {
|
|
2997
|
-
this.presetTracks = validatedOptions.modelTracks;
|
|
2998
|
-
}
|
|
2999
|
-
this.recording = new RecordingClient({
|
|
3000
|
-
onRuntimeMessage: (handler) => {
|
|
3001
|
-
this.on("runtimeMessage", handler);
|
|
3002
|
-
return () => this.off("runtimeMessage", handler);
|
|
3003
|
-
},
|
|
3004
|
-
onStatusChanged: (handler) => {
|
|
3005
|
-
this.on("statusChanged", handler);
|
|
3006
|
-
return () => this.off("statusChanged", handler);
|
|
3007
|
-
},
|
|
3008
|
-
sendRuntimeCommand: (command, data) => this.sendCommand(command, data, "runtime"),
|
|
3009
|
-
getStatus: () => this.status,
|
|
3010
|
-
getCoordinatorBaseUrl: () => this.coordinatorUrl
|
|
3011
|
-
});
|
|
3012
|
-
}
|
|
3013
|
-
/**
|
|
3014
|
-
* Returns the JWT resolver supplied to the most recent
|
|
3015
|
-
* {@link connect} call, or `undefined` if none was set (pre-connect
|
|
3016
|
-
* or local mode). Used by clip surfaces as a fallback when their
|
|
3017
|
-
* own `getJwt` prop is omitted.
|
|
3018
|
-
*/
|
|
3019
|
-
getJwtResolver() {
|
|
3020
|
-
return this.jwtResolver;
|
|
3021
|
-
}
|
|
3022
|
-
on(event, handler) {
|
|
3023
|
-
if (!this.eventListeners.has(event)) {
|
|
3024
|
-
this.eventListeners.set(event, /* @__PURE__ */ new Set());
|
|
3025
|
-
}
|
|
3026
|
-
this.eventListeners.get(event).add(handler);
|
|
3027
|
-
}
|
|
3028
|
-
off(event, handler) {
|
|
3029
|
-
var _a;
|
|
3030
|
-
(_a = this.eventListeners.get(event)) == null ? void 0 : _a.delete(handler);
|
|
3031
|
-
}
|
|
3032
|
-
emit(event, ...args) {
|
|
3033
|
-
var _a;
|
|
3034
|
-
(_a = this.eventListeners.get(event)) == null ? void 0 : _a.forEach((handler) => handler(...args));
|
|
3035
|
-
}
|
|
3036
|
-
/**
|
|
3037
|
-
* Sends a command to the model via the data channel.
|
|
3038
|
-
*
|
|
3039
|
-
* When any value in `data` is a {@link FileRef}, it is automatically
|
|
3040
|
-
* extracted and serialized into a separate `uploads` section on the
|
|
3041
|
-
* wire, keyed by the parameter name. Scalar values remain in `data`.
|
|
3042
|
-
*/
|
|
3043
|
-
sendCommand(command, data, scope = "application") {
|
|
3044
|
-
return __async(this, null, function* () {
|
|
3045
|
-
var _a;
|
|
3046
|
-
if (this.status !== "ready") {
|
|
3047
|
-
this.createError(
|
|
3048
|
-
"NOT_READY",
|
|
3049
|
-
`Cannot send command "${command}" while status is "${this.status}". Must be "ready".`,
|
|
3050
|
-
"api",
|
|
3051
|
-
true
|
|
3052
|
-
);
|
|
3053
|
-
return;
|
|
3054
|
-
}
|
|
3055
|
-
try {
|
|
3056
|
-
let uploads;
|
|
3057
|
-
if (data && typeof data === "object" && !Array.isArray(data)) {
|
|
3058
|
-
const scalarData = {};
|
|
3059
|
-
const extractedUploads = {};
|
|
3060
|
-
for (const [key, value] of Object.entries(data)) {
|
|
3061
|
-
if (value instanceof FileRef) {
|
|
3062
|
-
extractedUploads[key] = {
|
|
3063
|
-
upload_id: value.uploadId,
|
|
3064
|
-
name: value.name,
|
|
3065
|
-
mime_type: value.mimeType,
|
|
3066
|
-
size: value.size
|
|
3067
|
-
};
|
|
3068
|
-
} else {
|
|
3069
|
-
scalarData[key] = value;
|
|
3070
|
-
}
|
|
3071
|
-
}
|
|
3072
|
-
if (Object.keys(extractedUploads).length > 0) {
|
|
3073
|
-
uploads = extractedUploads;
|
|
3074
|
-
data = scalarData;
|
|
3075
|
-
}
|
|
3076
|
-
}
|
|
3077
|
-
(_a = this.transportClient) == null ? void 0 : _a.sendCommand(command, data, scope, uploads);
|
|
3078
|
-
} catch (error) {
|
|
3079
|
-
console.error("[Reactor] Failed to send message:", error);
|
|
3080
|
-
this.createError(
|
|
3081
|
-
"MESSAGE_SEND_FAILED",
|
|
3082
|
-
`Failed to send message: ${error}`,
|
|
3083
|
-
"gpu",
|
|
3084
|
-
true
|
|
3085
|
-
);
|
|
3086
|
-
}
|
|
3087
|
-
});
|
|
3088
|
-
}
|
|
3089
|
-
/**
|
|
3090
|
-
* Uploads a file to the session's object store and returns a {@link FileRef}.
|
|
3091
|
-
*
|
|
3092
|
-
* Flow:
|
|
3093
|
-
* 1. POST /sessions/{id}/uploads → allocate presigned PUT URL
|
|
3094
|
-
* 2. PUT file bytes to the presigned URL
|
|
3095
|
-
* 3. Send `fileUploaded` notification on the runtime data channel
|
|
3096
|
-
* (fires `@file_uploaded` on the model if registered)
|
|
3097
|
-
* 4. Return a `FileRef` to pass into {@link sendCommand}
|
|
3098
|
-
*
|
|
3099
|
-
* In local mode, the presigned URL returned by the runtime is rewritten
|
|
3100
|
-
* to use the SDK-configured base URL (scheme + host), so port-forwarded
|
|
3101
|
-
* setups work correctly (REA-1573).
|
|
3102
|
-
*/
|
|
3103
|
-
uploadFile(file, options) {
|
|
3104
|
-
return __async(this, null, function* () {
|
|
3105
|
-
var _a;
|
|
3106
|
-
if (this.status !== "ready") {
|
|
3107
|
-
throw new Error(
|
|
3108
|
-
`Cannot upload file, status is "${this.status}". Must be "ready".`
|
|
3109
|
-
);
|
|
3110
|
-
}
|
|
3111
|
-
if (!this.coordinatorClient || !this.sessionId) {
|
|
3112
|
-
throw new Error("No active session. Call connect() first.");
|
|
3113
|
-
}
|
|
3114
|
-
const name = (_a = options == null ? void 0 : options.name) != null ? _a : file instanceof File ? file.name : "upload";
|
|
3115
|
-
const mimeType = file.type || "application/octet-stream";
|
|
3116
|
-
const size = file.size;
|
|
3117
|
-
if (size <= 0) {
|
|
3118
|
-
throw new Error("File is empty");
|
|
3119
|
-
}
|
|
3120
|
-
const slot = yield this.coordinatorClient.createUpload(this.sessionId, {
|
|
3121
|
-
name,
|
|
3122
|
-
size,
|
|
3123
|
-
mime_type: mimeType
|
|
3124
|
-
});
|
|
3125
|
-
let presignedUrl = slot.presigned_url;
|
|
3126
|
-
if (this.local) {
|
|
3127
|
-
const target = new URL(this.coordinatorUrl);
|
|
3128
|
-
const parsed = new URL(presignedUrl);
|
|
3129
|
-
parsed.protocol = target.protocol;
|
|
3130
|
-
parsed.hostname = target.hostname;
|
|
3131
|
-
parsed.port = target.port;
|
|
3132
|
-
presignedUrl = parsed.toString();
|
|
3133
|
-
}
|
|
3134
|
-
const putResponse = yield fetch(presignedUrl, {
|
|
3135
|
-
method: "PUT",
|
|
3136
|
-
body: file,
|
|
3137
|
-
headers: {
|
|
3138
|
-
"Content-Length": String(size)
|
|
3139
|
-
}
|
|
3140
|
-
});
|
|
3141
|
-
if (!putResponse.ok) {
|
|
3142
|
-
throw new Error(
|
|
3143
|
-
`File upload failed: ${putResponse.status} ${putResponse.statusText}`
|
|
3144
|
-
);
|
|
3145
|
-
}
|
|
3146
|
-
yield this.sendCommand(
|
|
3147
|
-
"fileUploaded",
|
|
3148
|
-
{
|
|
3149
|
-
upload_id: slot.presigned_id,
|
|
3150
|
-
name,
|
|
3151
|
-
mime_type: mimeType,
|
|
3152
|
-
size
|
|
3153
|
-
},
|
|
3154
|
-
"runtime"
|
|
3155
|
-
);
|
|
3156
|
-
console.debug("[Reactor] File uploaded:", {
|
|
3157
|
-
uploadId: slot.presigned_id,
|
|
3158
|
-
name,
|
|
3159
|
-
mimeType,
|
|
3160
|
-
size
|
|
3161
|
-
});
|
|
3162
|
-
return new FileRef(slot.presigned_id, name, mimeType, size);
|
|
3163
|
-
});
|
|
3164
|
-
}
|
|
3165
|
-
/**
|
|
3166
|
-
* Request a clip covering the last `durationSeconds` of the live
|
|
3167
|
-
* session. Capped server-side at `recording.clip_max_seconds`
|
|
3168
|
-
* (default 5 minutes). Resolves with a {@link Clip} whose
|
|
3169
|
-
* `playlistUrl` can be handed to any HLS-capable player.
|
|
3170
|
-
*
|
|
3171
|
-
* @throws {RecordingError} on invalid input, transport failure,
|
|
3172
|
-
* timeout, runtime-side `clipFailed`, or disconnect mid-request.
|
|
3173
|
-
*/
|
|
3174
|
-
requestClip(durationSeconds) {
|
|
3175
|
-
return __async(this, null, function* () {
|
|
3176
|
-
return this.recording.requestClip(durationSeconds);
|
|
3177
|
-
});
|
|
3178
|
-
}
|
|
3179
|
-
/**
|
|
3180
|
-
* Request a clip covering the entire session up to "now". Same
|
|
3181
|
-
* mechanics as {@link requestClip} with `start = 0`; only the
|
|
3182
|
-
* resolved {@link Clip.kind} discriminator differs.
|
|
3183
|
-
*/
|
|
3184
|
-
requestRecording() {
|
|
3185
|
-
return __async(this, null, function* () {
|
|
3186
|
-
return this.recording.requestRecording();
|
|
3187
|
-
});
|
|
3188
|
-
}
|
|
3189
|
-
/**
|
|
3190
|
-
* Stream the chunks referenced by `clip.playlistUrl` and trigger a
|
|
3191
|
-
* native browser download of the assembled fragmented-MP4 Blob.
|
|
3192
|
-
* Pass `filename: null` to skip the download trigger and receive
|
|
3193
|
-
* the Blob (useful for non-DOM consumers and tests).
|
|
3194
|
-
*/
|
|
3195
|
-
downloadClipAsFile(clip, filename = "reactor-clip.mp4", options) {
|
|
3196
|
-
return __async(this, null, function* () {
|
|
3197
|
-
return this.recording.downloadClipAsFile(clip, filename, options);
|
|
3198
|
-
});
|
|
3199
|
-
}
|
|
3200
|
-
/**
|
|
3201
|
-
* Publishes a MediaStreamTrack to a named sendonly track.
|
|
3202
|
-
* The transceiver is already set up from capabilities — this just
|
|
3203
|
-
* calls replaceTrack() on the sender.
|
|
3204
|
-
*/
|
|
3205
|
-
publishTrack(name, track) {
|
|
3206
|
-
return __async(this, null, function* () {
|
|
3207
|
-
var _a;
|
|
3208
|
-
if (process.env.NODE_ENV !== "development" && this.status !== "ready") {
|
|
3209
|
-
console.warn(
|
|
3210
|
-
`[Reactor] Cannot publish track "${name}", status is ${this.status}`
|
|
3211
|
-
);
|
|
3212
|
-
return;
|
|
3213
|
-
}
|
|
3214
|
-
try {
|
|
3215
|
-
yield (_a = this.transportClient) == null ? void 0 : _a.publishTrack(name, track);
|
|
3216
|
-
} catch (error) {
|
|
3217
|
-
console.error(`[Reactor] Failed to publish track "${name}":`, error);
|
|
3218
|
-
this.createError(
|
|
3219
|
-
"TRACK_PUBLISH_FAILED",
|
|
3220
|
-
`Failed to publish track "${name}": ${error}`,
|
|
3221
|
-
"gpu",
|
|
3222
|
-
true
|
|
3223
|
-
);
|
|
3224
|
-
throw error;
|
|
3225
|
-
}
|
|
3226
|
-
});
|
|
3227
|
-
}
|
|
3228
|
-
unpublishTrack(name) {
|
|
3229
|
-
return __async(this, null, function* () {
|
|
3230
|
-
var _a;
|
|
3231
|
-
try {
|
|
3232
|
-
yield (_a = this.transportClient) == null ? void 0 : _a.unpublishTrack(name);
|
|
3233
|
-
} catch (error) {
|
|
3234
|
-
console.error(`[Reactor] Failed to unpublish track "${name}":`, error);
|
|
3235
|
-
this.createError(
|
|
3236
|
-
"TRACK_UNPUBLISH_FAILED",
|
|
3237
|
-
`Failed to unpublish track "${name}": ${error}`,
|
|
3238
|
-
"gpu",
|
|
3239
|
-
true
|
|
3240
|
-
);
|
|
3241
|
-
}
|
|
3242
|
-
});
|
|
3243
|
-
}
|
|
3244
|
-
pauseTrack(name) {
|
|
3245
|
-
var _a;
|
|
3246
|
-
(_a = this.transportClient) == null ? void 0 : _a.pauseTrack(name);
|
|
3247
|
-
}
|
|
3248
|
-
resumeTrack(name) {
|
|
3249
|
-
var _a;
|
|
3250
|
-
(_a = this.transportClient) == null ? void 0 : _a.resumeTrack(name);
|
|
3251
|
-
}
|
|
3252
|
-
/** Whether `name` is a track this client receives rather than sends. */
|
|
3253
|
-
isRecvonly(name) {
|
|
3254
|
-
return this.tracks.some(
|
|
3255
|
-
(track) => track.name === name && track.direction === "recvonly"
|
|
3256
|
-
);
|
|
3257
|
-
}
|
|
3258
|
-
/**
|
|
3259
|
-
* Reconnects to an existing session with a fresh transport.
|
|
3260
|
-
*/
|
|
3261
|
-
reconnect(options) {
|
|
3262
|
-
return __async(this, null, function* () {
|
|
3263
|
-
if (!this.sessionId || !this.coordinatorClient) {
|
|
3264
|
-
console.warn("[Reactor] No active session to reconnect to.");
|
|
3265
|
-
return;
|
|
3266
|
-
}
|
|
3267
|
-
if (this.status === "ready") {
|
|
3268
|
-
console.warn("[Reactor] Already connected, no need to reconnect.");
|
|
3269
|
-
return;
|
|
3270
|
-
}
|
|
3271
|
-
if (this.tracks.length === 0) {
|
|
3272
|
-
console.warn("[Reactor] No tracks available for reconnect.");
|
|
3273
|
-
return;
|
|
3274
|
-
}
|
|
3275
|
-
this.setStatus("connecting");
|
|
3276
|
-
try {
|
|
3277
|
-
if (!this.transportClient) {
|
|
3278
|
-
this.transportClient = new WebRTCTransportClient({
|
|
3279
|
-
baseUrl: this.coordinatorUrl,
|
|
3280
|
-
sessionId: this.sessionId,
|
|
3281
|
-
jwtToken: this.local ? "local" : "",
|
|
3282
|
-
maxPollAttempts: options == null ? void 0 : options.maxAttempts
|
|
3283
|
-
});
|
|
3284
|
-
this.setupTransportHandlers();
|
|
3285
|
-
}
|
|
3286
|
-
yield this.transportClient.prepare(this.tracks);
|
|
3287
|
-
yield this.transportClient.connect(true);
|
|
3288
|
-
} catch (error) {
|
|
3289
|
-
if (isAbortError(error)) return;
|
|
3290
|
-
console.error("[Reactor] Failed to reconnect:", error);
|
|
3291
|
-
this.disconnect(true);
|
|
3292
|
-
this.createError(
|
|
3293
|
-
"RECONNECTION_FAILED",
|
|
3294
|
-
`Failed to reconnect: ${error}`,
|
|
3295
|
-
"api",
|
|
3296
|
-
true
|
|
3297
|
-
);
|
|
3298
|
-
}
|
|
3299
|
-
});
|
|
3300
|
-
}
|
|
3301
|
-
/**
|
|
3302
|
-
* Connects to the coordinator, creates a session, then establishes
|
|
3303
|
-
* the transport using server-declared capabilities. `jwtToken` may
|
|
3304
|
-
* be a static string or a {@link JwtSource} resolver; pass a
|
|
3305
|
-
* resolver when the token is short-lived so each Coordinator HTTP
|
|
3306
|
-
* hop sees a fresh value.
|
|
3307
|
-
*
|
|
3308
|
-
* Pass `options.sessionId` to attach to a session that already exists
|
|
3309
|
-
* (e.g. one created by a backend) instead of creating a new one — session
|
|
3310
|
-
* creation is skipped and the transport is brought up against that id. The
|
|
3311
|
-
* `jwtToken` must be valid for the account that owns the session. Works in
|
|
3312
|
-
* local mode too (it looks the session up by id rather than starting one).
|
|
3313
|
-
*/
|
|
3314
|
-
connect(jwtToken, options) {
|
|
3315
|
-
return __async(this, null, function* () {
|
|
3316
|
-
var _a, _b, _c, _d;
|
|
3317
|
-
console.debug("[Reactor] Connecting, status:", this.status);
|
|
3318
|
-
if (jwtToken == void 0 && !this.local) {
|
|
3319
|
-
throw new Error("No authentication provided and not in local mode");
|
|
3320
|
-
}
|
|
3321
|
-
if (this.status !== "disconnected") {
|
|
3322
|
-
throw new Error("Already connected or connecting");
|
|
3323
|
-
}
|
|
3324
|
-
this.setStatus("connecting");
|
|
3325
|
-
this.connectStartTime = performance.now();
|
|
3326
|
-
if (!this.local && jwtToken !== void 0) {
|
|
3327
|
-
this.jwtResolver = normalizeJwtSource(jwtToken);
|
|
3328
|
-
}
|
|
3329
|
-
try {
|
|
3330
|
-
this.coordinatorClient = this.local ? new LocalCoordinatorClient(this.coordinatorUrl, this.model) : new CoordinatorClient({
|
|
3331
|
-
baseUrl: this.coordinatorUrl,
|
|
3332
|
-
jwtToken,
|
|
3333
|
-
model: this.model
|
|
3334
|
-
});
|
|
3335
|
-
let sessionCreationMs = 0;
|
|
3336
|
-
let sessionId;
|
|
3337
|
-
if (options == null ? void 0 : options.sessionId) {
|
|
3338
|
-
yield this.coordinatorClient.adoptSession(options.sessionId);
|
|
3339
|
-
sessionId = options.sessionId;
|
|
3340
|
-
this.createdSession = false;
|
|
3341
|
-
console.debug("[Reactor] Attaching to existing session:", sessionId);
|
|
3342
|
-
} else {
|
|
3343
|
-
const tSession = performance.now();
|
|
3344
|
-
const initialResponse = yield this.coordinatorClient.createSession();
|
|
3345
|
-
sessionCreationMs = performance.now() - tSession;
|
|
3346
|
-
sessionId = initialResponse.session_id;
|
|
3347
|
-
this.createdSession = true;
|
|
3348
|
-
console.debug(
|
|
3349
|
-
"[Reactor] Session created:",
|
|
3350
|
-
sessionId,
|
|
3351
|
-
"state:",
|
|
3352
|
-
initialResponse.state
|
|
3353
|
-
);
|
|
3354
|
-
}
|
|
3355
|
-
this.setSessionId(sessionId);
|
|
3356
|
-
this.setStatus("waiting");
|
|
3357
|
-
this.transportClient = new WebRTCTransportClient({
|
|
3358
|
-
baseUrl: this.coordinatorUrl,
|
|
3359
|
-
sessionId,
|
|
3360
|
-
jwtToken: this.local ? "local" : jwtToken,
|
|
3361
|
-
webrtcVersion: REACTOR_WEBRTC_VERSION,
|
|
3362
|
-
maxPollAttempts: options == null ? void 0 : options.maxAttempts
|
|
3363
|
-
});
|
|
3364
|
-
this.setupTransportHandlers();
|
|
3365
|
-
let sessionPollingMs;
|
|
3366
|
-
let transportConnectingMs;
|
|
3367
|
-
this.autoResumeTracks = (_a = options == null ? void 0 : options.autoResumeTracks) != null ? _a : true;
|
|
3368
|
-
if (this.presetTracks) {
|
|
3369
|
-
this.tracks = this.presetTracks;
|
|
3370
|
-
const tParallel = performance.now();
|
|
3371
|
-
const [sessionResponse] = yield Promise.all([
|
|
3372
|
-
this.coordinatorClient.pollSessionReady(),
|
|
3373
|
-
this.transportClient.prepare(this.tracks)
|
|
3374
|
-
]);
|
|
3375
|
-
sessionPollingMs = performance.now() - tParallel;
|
|
3376
|
-
this.sessionResponse = sessionResponse;
|
|
3377
|
-
const tConnect = performance.now();
|
|
3378
|
-
yield this.transportClient.connect(false, options == null ? void 0 : options.connectionId);
|
|
3379
|
-
transportConnectingMs = performance.now() - tConnect;
|
|
3380
|
-
} else {
|
|
3381
|
-
this.transportClient.warmup();
|
|
3382
|
-
const tPoll = performance.now();
|
|
3383
|
-
const sessionResponse = yield this.coordinatorClient.pollSessionReady();
|
|
3384
|
-
sessionPollingMs = performance.now() - tPoll;
|
|
3385
|
-
this.sessionResponse = sessionResponse;
|
|
3386
|
-
this.tracks = sessionResponse.capabilities.tracks;
|
|
3387
|
-
const protocol = sessionResponse.selected_transport.protocol;
|
|
3388
|
-
if (protocol !== "webrtc") {
|
|
3389
|
-
throw new Error(`Unsupported transport protocol: ${protocol}`);
|
|
3390
|
-
}
|
|
3391
|
-
const tTransport = performance.now();
|
|
3392
|
-
yield this.transportClient.prepare(this.tracks);
|
|
3393
|
-
yield this.transportClient.connect(false, options == null ? void 0 : options.connectionId);
|
|
3394
|
-
transportConnectingMs = performance.now() - tTransport;
|
|
3395
|
-
}
|
|
3396
|
-
console.debug("[Reactor] Session ready, tracks:", this.tracks.length);
|
|
3397
|
-
this.connectionTimings = {
|
|
3398
|
-
sessionCreationMs: sessionCreationMs + sessionPollingMs,
|
|
3399
|
-
transportConnectingMs,
|
|
3400
|
-
totalMs: 0
|
|
3401
|
-
};
|
|
3402
|
-
} catch (error) {
|
|
3403
|
-
if (isAbortError(error)) return;
|
|
3404
|
-
if (!(options == null ? void 0 : options.sessionId) && !this.retryingSessionLoss && isSessionLostError(error)) {
|
|
3405
|
-
this.retryingSessionLoss = true;
|
|
3406
|
-
(_b = this.coordinatorClient) == null ? void 0 : _b.abort();
|
|
3407
|
-
(_c = this.transportClient) == null ? void 0 : _c.abort();
|
|
3408
|
-
(_d = this.transportClient) == null ? void 0 : _d.disconnect();
|
|
3409
|
-
this.setStatus("disconnected");
|
|
3410
|
-
try {
|
|
3411
|
-
yield this.connect(jwtToken, options);
|
|
3412
|
-
return;
|
|
3413
|
-
} finally {
|
|
3414
|
-
this.retryingSessionLoss = false;
|
|
3415
|
-
}
|
|
3416
|
-
}
|
|
3417
|
-
console.error("[Reactor] Connection failed:", error);
|
|
3418
|
-
this.createError(
|
|
3419
|
-
"CONNECTION_FAILED",
|
|
3420
|
-
`Connection failed: ${error}`,
|
|
3421
|
-
"api",
|
|
3422
|
-
true
|
|
3423
|
-
);
|
|
3424
|
-
try {
|
|
3425
|
-
yield this.disconnect(false);
|
|
3426
|
-
} catch (disconnectError) {
|
|
3427
|
-
console.error(
|
|
3428
|
-
"[Reactor] Failed to clean up after connection failure:",
|
|
3429
|
-
disconnectError
|
|
3430
|
-
);
|
|
3431
|
-
}
|
|
3432
|
-
throw error;
|
|
3433
|
-
}
|
|
3434
|
-
});
|
|
3435
|
-
}
|
|
3436
|
-
/**
|
|
3437
|
-
* Sets up event handlers for the transport client.
|
|
3438
|
-
* Each handler captures the client reference to ignore stale events.
|
|
3439
|
-
*/
|
|
3440
|
-
setupTransportHandlers() {
|
|
3441
|
-
if (!this.transportClient) return;
|
|
3442
|
-
const client = this.transportClient;
|
|
3443
|
-
client.on("message", (message, scope) => {
|
|
3444
|
-
if (this.transportClient !== client) return;
|
|
3445
|
-
if (scope === "application") {
|
|
3446
|
-
this.emit("message", message);
|
|
3447
|
-
} else if (scope === "runtime") {
|
|
3448
|
-
if (message && typeof message === "object" && message.type === "modelSchema" && message.data) {
|
|
3449
|
-
this.schema = message.data;
|
|
3450
|
-
this.emit("schemaReceived", this.schema);
|
|
3451
|
-
}
|
|
3452
|
-
this.emit("runtimeMessage", message);
|
|
3453
|
-
}
|
|
3454
|
-
});
|
|
3455
|
-
client.on("statusChanged", (status) => {
|
|
3456
|
-
if (this.transportClient !== client) return;
|
|
3457
|
-
switch (status) {
|
|
3458
|
-
case "connected":
|
|
3459
|
-
this.finalizeConnectionTimings();
|
|
3460
|
-
if (this.autoResumeTracks) {
|
|
3461
|
-
for (const track of this.tracks) {
|
|
3462
|
-
if (track.direction === "recvonly") {
|
|
3463
|
-
this.resumeTrack(track.name);
|
|
3464
|
-
}
|
|
3465
|
-
}
|
|
3466
|
-
}
|
|
3467
|
-
this.setStatus("ready");
|
|
3468
|
-
void this.sendCommand("requestSchema", {}, "runtime");
|
|
3469
|
-
break;
|
|
3470
|
-
case "disconnected":
|
|
3471
|
-
this.disconnect(true);
|
|
3472
|
-
break;
|
|
3473
|
-
case "error":
|
|
3474
|
-
this.createError(
|
|
3475
|
-
"GPU_CONNECTION_ERROR",
|
|
3476
|
-
"Transport connection failed",
|
|
3477
|
-
"gpu",
|
|
3478
|
-
true
|
|
3479
|
-
);
|
|
3480
|
-
this.disconnect();
|
|
3481
|
-
break;
|
|
3482
|
-
}
|
|
3483
|
-
});
|
|
3484
|
-
client.on(
|
|
3485
|
-
"trackReceived",
|
|
3486
|
-
(name, track, stream) => {
|
|
3487
|
-
if (this.transportClient !== client) return;
|
|
3488
|
-
this.emit("trackReceived", name, track, stream);
|
|
3489
|
-
if (this.autoResumeTracks && this.isRecvonly(name)) {
|
|
3490
|
-
this.resumeTrack(name);
|
|
3491
|
-
}
|
|
3492
|
-
}
|
|
3493
|
-
);
|
|
3494
|
-
client.on("statsUpdate", (stats) => {
|
|
3495
|
-
if (this.transportClient !== client) return;
|
|
3496
|
-
this.emit("statsUpdate", __spreadProps(__spreadValues({}, stats), {
|
|
3497
|
-
connectionTimings: this.connectionTimings
|
|
3498
|
-
}));
|
|
3499
|
-
});
|
|
3500
|
-
}
|
|
3501
|
-
/**
|
|
3502
|
-
* Disconnects from both the transport and the coordinator.
|
|
3503
|
-
*/
|
|
3504
|
-
disconnect(recoverable = false) {
|
|
3505
|
-
return __async(this, null, function* () {
|
|
3506
|
-
var _a, _b;
|
|
3507
|
-
if (this.status === "disconnected" && !this.sessionId) {
|
|
3508
|
-
console.warn("[Reactor] Already disconnected");
|
|
3509
|
-
return;
|
|
3510
|
-
}
|
|
3511
|
-
(_a = this.coordinatorClient) == null ? void 0 : _a.abort();
|
|
3512
|
-
(_b = this.transportClient) == null ? void 0 : _b.abort();
|
|
3513
|
-
if (this.coordinatorClient && !recoverable) {
|
|
3514
|
-
if (this.createdSession) {
|
|
3515
|
-
try {
|
|
3516
|
-
yield this.coordinatorClient.terminateSession();
|
|
3517
|
-
} catch (error) {
|
|
3518
|
-
console.error("[Reactor] Error terminating session:", error);
|
|
3519
|
-
}
|
|
3520
|
-
} else {
|
|
3521
|
-
console.debug(
|
|
3522
|
-
"[Reactor] Adopted session (not the creator) \u2014 skipping DELETE, leaving it alive"
|
|
3523
|
-
);
|
|
3524
|
-
}
|
|
3525
|
-
this.coordinatorClient = void 0;
|
|
3526
|
-
}
|
|
3527
|
-
if (this.transportClient) {
|
|
3528
|
-
try {
|
|
3529
|
-
yield this.transportClient.disconnect();
|
|
3530
|
-
} catch (error) {
|
|
3531
|
-
console.error("[Reactor] Error disconnecting transport:", error);
|
|
3532
|
-
}
|
|
3533
|
-
if (!recoverable) {
|
|
3534
|
-
this.transportClient = void 0;
|
|
3535
|
-
}
|
|
3536
|
-
}
|
|
3537
|
-
this.setStatus("disconnected");
|
|
3538
|
-
this.resetConnectionTimings();
|
|
3539
|
-
if (!recoverable) {
|
|
3540
|
-
this.setSessionExpiration(void 0);
|
|
3541
|
-
this.setSessionId(void 0);
|
|
3542
|
-
this.schema = void 0;
|
|
3543
|
-
this.tracks = [];
|
|
3544
|
-
this.sessionResponse = void 0;
|
|
3545
|
-
this.createdSession = false;
|
|
3546
|
-
}
|
|
3547
|
-
});
|
|
3548
|
-
}
|
|
3549
|
-
// ─────────────────────────────────────────────────────────────────────────
|
|
3550
|
-
// Getters
|
|
3551
|
-
// ─────────────────────────────────────────────────────────────────────────
|
|
3552
|
-
getSessionId() {
|
|
3553
|
-
return this.sessionId;
|
|
3554
|
-
}
|
|
3555
|
-
getStatus() {
|
|
3556
|
-
return this.status;
|
|
3557
|
-
}
|
|
3558
|
-
getState() {
|
|
3559
|
-
return {
|
|
3560
|
-
status: this.status,
|
|
3561
|
-
lastError: this.lastError
|
|
3562
|
-
};
|
|
3563
|
-
}
|
|
3564
|
-
getLastError() {
|
|
3565
|
-
return this.lastError;
|
|
3566
|
-
}
|
|
3567
|
-
/**
|
|
3568
|
-
* The model's OpenAPI schema (events, outbound messages, tracks),
|
|
3569
|
-
* received over the runtime channel shortly after the session becomes
|
|
3570
|
-
* ready. `undefined` until the `schemaReceived` event has fired.
|
|
3571
|
-
*/
|
|
3572
|
-
getSchema() {
|
|
3573
|
-
return this.schema;
|
|
3574
|
-
}
|
|
3575
|
-
getSessionInfo() {
|
|
3576
|
-
return this.sessionResponse;
|
|
3577
|
-
}
|
|
3578
|
-
getStats() {
|
|
3579
|
-
var _a;
|
|
3580
|
-
const stats = (_a = this.transportClient) == null ? void 0 : _a.getStats();
|
|
3581
|
-
if (!stats) return void 0;
|
|
3582
|
-
return __spreadProps(__spreadValues({}, stats), { connectionTimings: this.connectionTimings });
|
|
3583
|
-
}
|
|
3584
|
-
/** Timing breakdown from the most recent connect() handshake. */
|
|
3585
|
-
getConnectionTimings() {
|
|
3586
|
-
return this.connectionTimings;
|
|
3587
|
-
}
|
|
3588
|
-
// ─────────────────────────────────────────────────────────────────────────
|
|
3589
|
-
// Private State Management
|
|
3590
|
-
// ─────────────────────────────────────────────────────────────────────────
|
|
3591
|
-
setSessionId(newSessionId) {
|
|
3592
|
-
console.debug(
|
|
3593
|
-
"[Reactor] Setting session ID:",
|
|
3594
|
-
newSessionId,
|
|
3595
|
-
"from",
|
|
3596
|
-
this.sessionId
|
|
3597
|
-
);
|
|
3598
|
-
if (this.sessionId !== newSessionId) {
|
|
3599
|
-
this.sessionId = newSessionId;
|
|
3600
|
-
this.emit("sessionIdChanged", newSessionId);
|
|
3601
|
-
}
|
|
3602
|
-
}
|
|
3603
|
-
setStatus(newStatus) {
|
|
3604
|
-
console.debug("[Reactor] Setting status:", newStatus, "from", this.status);
|
|
3605
|
-
if (this.status !== newStatus) {
|
|
3606
|
-
this.status = newStatus;
|
|
3607
|
-
this.emit("statusChanged", newStatus);
|
|
3608
|
-
}
|
|
3609
|
-
}
|
|
3610
|
-
setSessionExpiration(newSessionExpiration) {
|
|
3611
|
-
console.debug(
|
|
3612
|
-
"[Reactor] Setting session expiration:",
|
|
3613
|
-
newSessionExpiration
|
|
3614
|
-
);
|
|
3615
|
-
if (this.sessionExpiration !== newSessionExpiration) {
|
|
3616
|
-
this.sessionExpiration = newSessionExpiration;
|
|
3617
|
-
this.emit("sessionExpirationChanged", newSessionExpiration);
|
|
3618
|
-
}
|
|
3619
|
-
}
|
|
3620
|
-
resetConnectionTimings() {
|
|
3621
|
-
this.connectStartTime = void 0;
|
|
3622
|
-
this.connectionTimings = void 0;
|
|
3623
|
-
}
|
|
3624
|
-
finalizeConnectionTimings() {
|
|
3625
|
-
if (!this.connectionTimings || this.connectStartTime == null) return;
|
|
3626
|
-
this.connectionTimings.totalMs = performance.now() - this.connectStartTime;
|
|
3627
|
-
this.connectStartTime = void 0;
|
|
3628
|
-
console.debug("[Reactor] Connection timings:", this.connectionTimings);
|
|
3629
|
-
}
|
|
3630
|
-
createError(code, message, component, recoverable, retryAfter) {
|
|
3631
|
-
this.lastError = {
|
|
3632
|
-
code,
|
|
3633
|
-
message,
|
|
3634
|
-
timestamp: Date.now(),
|
|
3635
|
-
recoverable,
|
|
3636
|
-
component,
|
|
3637
|
-
retryAfter
|
|
3638
|
-
};
|
|
3639
|
-
this.emit("error", this.lastError);
|
|
3640
|
-
}
|
|
3641
|
-
};
|
|
3642
|
-
|
|
3643
|
-
// src/react/ReactorProvider.tsx
|
|
3644
|
-
import {
|
|
3645
|
-
useContext,
|
|
3646
|
-
useEffect,
|
|
3647
|
-
useMemo,
|
|
3648
|
-
useRef,
|
|
3649
|
-
useState
|
|
3650
|
-
} from "react";
|
|
3651
|
-
|
|
3652
|
-
// src/core/store.ts
|
|
3653
|
-
import { create } from "zustand/react";
|
|
3654
|
-
import { createContext } from "react";
|
|
3655
|
-
var ReactorContext = createContext(
|
|
3656
|
-
void 0
|
|
3657
|
-
);
|
|
3658
|
-
var defaultInitState = {
|
|
3659
|
-
status: "disconnected",
|
|
3660
|
-
tracks: {},
|
|
3661
|
-
lastError: void 0,
|
|
3662
|
-
sessionExpiration: void 0,
|
|
3663
|
-
jwtToken: void 0,
|
|
3664
|
-
sessionId: void 0,
|
|
3665
|
-
connectOptions: void 0
|
|
3666
|
-
};
|
|
3667
|
-
var initReactorStore = (props) => {
|
|
3668
|
-
return __spreadValues(__spreadValues({}, defaultInitState), props);
|
|
3669
|
-
};
|
|
3670
|
-
var createReactorStore = (initProps, publicState = defaultInitState) => {
|
|
3671
|
-
console.debug("[ReactorStore] Creating store", {
|
|
3672
|
-
apiUrl: initProps.apiUrl,
|
|
3673
|
-
jwtToken: initProps.jwtToken,
|
|
3674
|
-
initialState: publicState
|
|
3675
|
-
});
|
|
3676
|
-
return create()((set, get) => {
|
|
3677
|
-
const reactor = new Reactor(initProps);
|
|
3678
|
-
console.debug("[ReactorStore] Setting up event listeners");
|
|
3679
|
-
reactor.on("statusChanged", (newStatus) => {
|
|
3680
|
-
console.debug("[ReactorStore] Status changed", {
|
|
3681
|
-
oldStatus: get().status,
|
|
3682
|
-
newStatus
|
|
3683
|
-
});
|
|
3684
|
-
if (newStatus === "disconnected") {
|
|
3685
|
-
set({ status: newStatus, tracks: {} });
|
|
3686
|
-
} else {
|
|
3687
|
-
set({ status: newStatus });
|
|
3688
|
-
}
|
|
3689
|
-
});
|
|
3690
|
-
reactor.on(
|
|
3691
|
-
"sessionExpirationChanged",
|
|
3692
|
-
(newSessionExpiration) => {
|
|
3693
|
-
console.debug("[ReactorStore] Session expiration changed", {
|
|
3694
|
-
oldSessionExpiration: get().sessionExpiration,
|
|
3695
|
-
newSessionExpiration
|
|
3696
|
-
});
|
|
3697
|
-
set({ sessionExpiration: newSessionExpiration });
|
|
3698
|
-
}
|
|
3699
|
-
);
|
|
3700
|
-
reactor.on("trackReceived", (name, track) => {
|
|
3701
|
-
console.debug("[ReactorStore] Track received", {
|
|
3702
|
-
name,
|
|
3703
|
-
kind: track.kind,
|
|
3704
|
-
id: track.id
|
|
3705
|
-
});
|
|
3706
|
-
set({ tracks: __spreadProps(__spreadValues({}, get().tracks), { [name]: track }) });
|
|
3707
|
-
});
|
|
3708
|
-
reactor.on("error", (error) => {
|
|
3709
|
-
console.debug("[ReactorStore] Error occurred", error);
|
|
3710
|
-
set({ lastError: error });
|
|
3711
|
-
});
|
|
3712
|
-
reactor.on("sessionIdChanged", (newSessionId) => {
|
|
3713
|
-
console.debug("[ReactorStore] Session ID changed", {
|
|
3714
|
-
oldSessionId: get().sessionId,
|
|
3715
|
-
newSessionId
|
|
3716
|
-
});
|
|
3717
|
-
set({ sessionId: newSessionId });
|
|
3718
|
-
});
|
|
3719
|
-
return __spreadProps(__spreadValues({}, publicState), {
|
|
3720
|
-
jwtToken: initProps.jwtToken,
|
|
3721
|
-
connectOptions: initProps.connectOptions,
|
|
3722
|
-
internal: { reactor },
|
|
3723
|
-
// actions
|
|
3724
|
-
onMessage: (handler) => {
|
|
3725
|
-
console.debug("[ReactorStore] Registering message handler");
|
|
3726
|
-
get().internal.reactor.on("message", handler);
|
|
3727
|
-
return () => {
|
|
3728
|
-
console.debug("[ReactorStore] Cleaning up message handler");
|
|
3729
|
-
get().internal.reactor.off("message", handler);
|
|
3730
|
-
};
|
|
3731
|
-
},
|
|
3732
|
-
sendCommand: (command, data, scope) => __async(null, null, function* () {
|
|
3733
|
-
console.debug("[ReactorStore] Sending command", {
|
|
3734
|
-
command,
|
|
3735
|
-
data,
|
|
3736
|
-
scope
|
|
3737
|
-
});
|
|
3738
|
-
try {
|
|
3739
|
-
yield get().internal.reactor.sendCommand(command, data, scope);
|
|
3740
|
-
console.debug("[ReactorStore] Command sent successfully");
|
|
3741
|
-
} catch (error) {
|
|
3742
|
-
console.error("[ReactorStore] Failed to send command:", error);
|
|
3743
|
-
throw error;
|
|
3744
|
-
}
|
|
3745
|
-
}),
|
|
3746
|
-
connect: (jwtToken, options) => __async(null, null, function* () {
|
|
3747
|
-
if (jwtToken === void 0) {
|
|
3748
|
-
jwtToken = get().jwtToken;
|
|
3749
|
-
}
|
|
3750
|
-
const resolvedOptions = __spreadValues(__spreadValues({}, get().connectOptions), options);
|
|
3751
|
-
console.debug("[ReactorStore] Connect called.");
|
|
3752
|
-
try {
|
|
3753
|
-
yield get().internal.reactor.connect(jwtToken, resolvedOptions);
|
|
3754
|
-
console.debug("[ReactorStore] Connect completed successfully");
|
|
3755
|
-
} catch (error) {
|
|
3756
|
-
console.error("[ReactorStore] Connect failed:", error);
|
|
3757
|
-
throw error;
|
|
3758
|
-
}
|
|
3759
|
-
}),
|
|
3760
|
-
disconnect: (recoverable = false) => __async(null, null, function* () {
|
|
3761
|
-
console.debug("[ReactorStore] Disconnect called", {
|
|
3762
|
-
currentStatus: get().status
|
|
3763
|
-
});
|
|
3764
|
-
try {
|
|
3765
|
-
yield get().internal.reactor.disconnect(recoverable);
|
|
3766
|
-
console.debug("[ReactorStore] Disconnect completed successfully");
|
|
3767
|
-
} catch (error) {
|
|
3768
|
-
console.error("[ReactorStore] Disconnect failed:", error);
|
|
3769
|
-
throw error;
|
|
3770
|
-
}
|
|
3771
|
-
}),
|
|
3772
|
-
publish: (name, track) => __async(null, null, function* () {
|
|
3773
|
-
console.debug(`[ReactorStore] Publishing track "${name}"`);
|
|
3774
|
-
try {
|
|
3775
|
-
yield get().internal.reactor.publishTrack(name, track);
|
|
3776
|
-
console.debug(
|
|
3777
|
-
`[ReactorStore] Track "${name}" published successfully`
|
|
3778
|
-
);
|
|
3779
|
-
} catch (error) {
|
|
3780
|
-
console.error(
|
|
3781
|
-
`[ReactorStore] Failed to publish track "${name}":`,
|
|
3782
|
-
error
|
|
3783
|
-
);
|
|
3784
|
-
throw error;
|
|
3785
|
-
}
|
|
3786
|
-
}),
|
|
3787
|
-
unpublish: (name) => __async(null, null, function* () {
|
|
3788
|
-
console.debug(`[ReactorStore] Unpublishing track "${name}"`);
|
|
3789
|
-
try {
|
|
3790
|
-
yield get().internal.reactor.unpublishTrack(name);
|
|
3791
|
-
console.debug(
|
|
3792
|
-
`[ReactorStore] Track "${name}" unpublished successfully`
|
|
3793
|
-
);
|
|
3794
|
-
} catch (error) {
|
|
3795
|
-
console.error(
|
|
3796
|
-
`[ReactorStore] Failed to unpublish track "${name}":`,
|
|
3797
|
-
error
|
|
3798
|
-
);
|
|
3799
|
-
throw error;
|
|
3800
|
-
}
|
|
3801
|
-
}),
|
|
3802
|
-
pauseTrack: (name) => get().internal.reactor.pauseTrack(name),
|
|
3803
|
-
resumeTrack: (name) => get().internal.reactor.resumeTrack(name),
|
|
3804
|
-
reconnect: (options) => __async(null, null, function* () {
|
|
3805
|
-
console.debug("[ReactorStore] Reconnecting");
|
|
3806
|
-
try {
|
|
3807
|
-
yield get().internal.reactor.reconnect(options);
|
|
3808
|
-
console.debug("[ReactorStore] Reconnect completed successfully");
|
|
3809
|
-
} catch (error) {
|
|
3810
|
-
console.error("[ReactorStore] Failed to reconnect:", error);
|
|
3811
|
-
throw error;
|
|
3812
|
-
}
|
|
3813
|
-
}),
|
|
3814
|
-
uploadFile: (file, options) => __async(null, null, function* () {
|
|
3815
|
-
console.debug("[ReactorStore] Uploading file");
|
|
3816
|
-
try {
|
|
3817
|
-
const result = yield get().internal.reactor.uploadFile(file, options);
|
|
3818
|
-
console.debug("[ReactorStore] File uploaded successfully", result);
|
|
3819
|
-
return result;
|
|
3820
|
-
} catch (error) {
|
|
3821
|
-
console.error("[ReactorStore] Failed to upload file:", error);
|
|
3822
|
-
throw error;
|
|
3823
|
-
}
|
|
3824
|
-
}),
|
|
3825
|
-
requestClip: (durationSeconds) => get().internal.reactor.requestClip(durationSeconds),
|
|
3826
|
-
requestRecording: () => get().internal.reactor.requestRecording(),
|
|
3827
|
-
downloadClipAsFile: (clip, filename, options) => get().internal.reactor.downloadClipAsFile(clip, filename, options)
|
|
3828
|
-
});
|
|
3829
|
-
});
|
|
3830
|
-
};
|
|
3831
|
-
|
|
3832
|
-
// src/react/ReactorProvider.tsx
|
|
3833
|
-
import { useStore } from "zustand";
|
|
3834
|
-
import { jsx } from "react/jsx-runtime";
|
|
3835
|
-
function ReactorProvider(_a) {
|
|
3836
|
-
var _b = _a, {
|
|
3837
|
-
children,
|
|
3838
|
-
connectOptions,
|
|
3839
|
-
jwtToken,
|
|
3840
|
-
getJwt
|
|
3841
|
-
} = _b, props = __objRest(_b, [
|
|
3842
|
-
"children",
|
|
3843
|
-
"connectOptions",
|
|
3844
|
-
"jwtToken",
|
|
3845
|
-
"getJwt"
|
|
3846
|
-
]);
|
|
3847
|
-
const getJwtRef = useRef(getJwt);
|
|
3848
|
-
useEffect(() => {
|
|
3849
|
-
getJwtRef.current = getJwt;
|
|
3850
|
-
});
|
|
3851
|
-
const hasGetJwt = getJwt !== void 0;
|
|
3852
|
-
const stableGetJwt = useMemo(() => {
|
|
3853
|
-
if (!hasGetJwt) return void 0;
|
|
3854
|
-
return () => __async(null, null, function* () {
|
|
3855
|
-
const r = getJwtRef.current;
|
|
3856
|
-
return r ? yield r() : "";
|
|
3857
|
-
});
|
|
3858
|
-
}, [hasGetJwt]);
|
|
3859
|
-
const jwtSource = stableGetJwt != null ? stableGetJwt : jwtToken;
|
|
3860
|
-
const storeRef = useRef(void 0);
|
|
3861
|
-
const firstRender = useRef(true);
|
|
3862
|
-
const [_storeVersion, setStoreVersion] = useState(0);
|
|
3863
|
-
const _a2 = connectOptions != null ? connectOptions : {}, { autoConnect = false } = _a2, pollingOptions = __objRest(_a2, ["autoConnect"]);
|
|
3864
|
-
if (storeRef.current === void 0) {
|
|
3865
|
-
console.debug("[ReactorProvider] Creating new reactor store");
|
|
3866
|
-
storeRef.current = createReactorStore(
|
|
3867
|
-
initReactorStore(__spreadProps(__spreadValues({}, props), {
|
|
3868
|
-
jwtToken: jwtSource,
|
|
3869
|
-
connectOptions: pollingOptions
|
|
3870
|
-
}))
|
|
3871
|
-
);
|
|
3872
|
-
console.debug("[ReactorProvider] Reactor store created successfully");
|
|
3873
|
-
}
|
|
3874
|
-
const { apiUrl, modelName, local } = props;
|
|
3875
|
-
const maxAttempts = pollingOptions.maxAttempts;
|
|
3876
|
-
const { autoResumeTracks } = pollingOptions;
|
|
3877
|
-
useEffect(() => {
|
|
3878
|
-
var _a3;
|
|
3879
|
-
(_a3 = storeRef.current) == null ? void 0 : _a3.setState({ connectOptions: pollingOptions });
|
|
3880
|
-
}, [autoResumeTracks, maxAttempts]);
|
|
3881
|
-
useEffect(() => {
|
|
3882
|
-
const handleBeforeUnload = () => {
|
|
3883
|
-
var _a3;
|
|
3884
|
-
(_a3 = storeRef.current) == null ? void 0 : _a3.getState().internal.reactor.disconnect(false);
|
|
3885
|
-
};
|
|
3886
|
-
window.addEventListener("beforeunload", handleBeforeUnload);
|
|
3887
|
-
return () => window.removeEventListener("beforeunload", handleBeforeUnload);
|
|
3888
|
-
}, []);
|
|
3889
|
-
useEffect(() => {
|
|
3890
|
-
if (firstRender.current) {
|
|
3891
|
-
firstRender.current = false;
|
|
3892
|
-
const current2 = storeRef.current;
|
|
3893
|
-
if (autoConnect && current2.getState().status === "disconnected" && jwtSource) {
|
|
3894
|
-
console.debug(
|
|
3895
|
-
"[ReactorProvider] Starting autoconnect in first render..."
|
|
3896
|
-
);
|
|
3897
|
-
current2.getState().connect(jwtSource, pollingOptions).then(() => {
|
|
3898
|
-
console.debug(
|
|
3899
|
-
"[ReactorProvider] Autoconnect successful in first render"
|
|
3900
|
-
);
|
|
3901
|
-
}).catch((error) => {
|
|
3902
|
-
console.error(
|
|
3903
|
-
"[ReactorProvider] Failed to autoconnect in first render:",
|
|
3904
|
-
error
|
|
3905
|
-
);
|
|
3906
|
-
});
|
|
3907
|
-
}
|
|
3908
|
-
return () => {
|
|
3909
|
-
console.debug(
|
|
3910
|
-
"[ReactorProvider] Disconnecting in cleanup for first render"
|
|
3911
|
-
);
|
|
3912
|
-
current2.getState().disconnect().then(() => {
|
|
3913
|
-
console.debug(
|
|
3914
|
-
"[ReactorProvider] Disconnect completed successfully in cleanup for first render"
|
|
3915
|
-
);
|
|
3916
|
-
}).catch((error) => {
|
|
3917
|
-
console.error(
|
|
3918
|
-
"[ReactorProvider] Failed to disconnect in cleanup for first render:",
|
|
3919
|
-
error
|
|
3920
|
-
);
|
|
3921
|
-
});
|
|
3922
|
-
};
|
|
3923
|
-
}
|
|
3924
|
-
console.debug("[ReactorProvider] Updating reactor store");
|
|
3925
|
-
storeRef.current = createReactorStore(
|
|
3926
|
-
initReactorStore({
|
|
3927
|
-
apiUrl,
|
|
3928
|
-
modelName,
|
|
3929
|
-
local,
|
|
3930
|
-
jwtToken: jwtSource,
|
|
3931
|
-
connectOptions: pollingOptions
|
|
3932
|
-
})
|
|
3933
|
-
);
|
|
3934
|
-
const current = storeRef.current;
|
|
3935
|
-
setStoreVersion((v) => v + 1);
|
|
3936
|
-
console.debug(
|
|
3937
|
-
"[ReactorProvider] Reactor store updated successfully, and increased version"
|
|
3938
|
-
);
|
|
3939
|
-
if (autoConnect && current.getState().status === "disconnected" && jwtSource) {
|
|
3940
|
-
console.debug("[ReactorProvider] Starting autoconnect...");
|
|
3941
|
-
current.getState().connect(jwtSource, pollingOptions).then(() => {
|
|
3942
|
-
console.debug("[ReactorProvider] Autoconnect successful");
|
|
3943
|
-
}).catch((error) => {
|
|
3944
|
-
console.error("[ReactorProvider] Failed to autoconnect:", error);
|
|
3945
|
-
});
|
|
3946
|
-
}
|
|
3947
|
-
return () => {
|
|
3948
|
-
console.debug("[ReactorProvider] Disconnecting in cleanup");
|
|
3949
|
-
current.getState().disconnect().then(() => {
|
|
3950
|
-
console.debug(
|
|
3951
|
-
"[ReactorProvider] Disconnect completed successfully in cleanup"
|
|
3952
|
-
);
|
|
3953
|
-
}).catch((error) => {
|
|
3954
|
-
console.error("[ReactorProvider] Failed to disconnect:", error);
|
|
3955
|
-
});
|
|
3956
|
-
};
|
|
3957
|
-
}, [apiUrl, modelName, local, jwtSource]);
|
|
3958
|
-
return /* @__PURE__ */ jsx(ReactorContext.Provider, { value: storeRef.current, children });
|
|
3959
|
-
}
|
|
3960
|
-
function useReactorStore(selector) {
|
|
3961
|
-
const ctx = useContext(ReactorContext);
|
|
3962
|
-
if (!ctx) {
|
|
3963
|
-
throw new Error("useReactor must be used within a ReactorProvider");
|
|
3964
|
-
}
|
|
3965
|
-
return useStore(ctx, selector);
|
|
3966
|
-
}
|
|
3967
|
-
|
|
3968
|
-
// src/react/hooks.ts
|
|
3969
|
-
import { useShallow } from "zustand/shallow";
|
|
3970
|
-
import { useEffect as useEffect2, useRef as useRef2, useState as useState2 } from "react";
|
|
3971
|
-
function useReactor(selector) {
|
|
3972
|
-
return useReactorStore(useShallow(selector));
|
|
3973
|
-
}
|
|
3974
|
-
function useReactorMessage(handler) {
|
|
3975
|
-
const reactor = useReactor((state) => state.internal.reactor);
|
|
3976
|
-
const handlerRef = useRef2(handler);
|
|
3977
|
-
useEffect2(() => {
|
|
3978
|
-
handlerRef.current = handler;
|
|
3979
|
-
}, [handler]);
|
|
3980
|
-
useEffect2(() => {
|
|
3981
|
-
const stableHandler = (message) => {
|
|
3982
|
-
handlerRef.current(message);
|
|
3983
|
-
};
|
|
3984
|
-
reactor.on("message", stableHandler);
|
|
3985
|
-
return () => {
|
|
3986
|
-
reactor.off("message", stableHandler);
|
|
3987
|
-
};
|
|
3988
|
-
}, [reactor]);
|
|
3989
|
-
}
|
|
3990
|
-
function useReactorInternalMessage(handler) {
|
|
3991
|
-
const reactor = useReactor((state) => state.internal.reactor);
|
|
3992
|
-
const handlerRef = useRef2(handler);
|
|
3993
|
-
useEffect2(() => {
|
|
3994
|
-
handlerRef.current = handler;
|
|
3995
|
-
}, [handler]);
|
|
3996
|
-
useEffect2(() => {
|
|
3997
|
-
const stableHandler = (message) => {
|
|
3998
|
-
handlerRef.current(message);
|
|
3999
|
-
};
|
|
4000
|
-
reactor.on("runtimeMessage", stableHandler);
|
|
4001
|
-
return () => {
|
|
4002
|
-
reactor.off("runtimeMessage", stableHandler);
|
|
4003
|
-
};
|
|
4004
|
-
}, [reactor]);
|
|
4005
|
-
}
|
|
4006
|
-
function useStats() {
|
|
4007
|
-
const reactor = useReactor((state) => state.internal.reactor);
|
|
4008
|
-
const [stats, setStats] = useState2(void 0);
|
|
4009
|
-
useEffect2(() => {
|
|
4010
|
-
const handler = (newStats) => {
|
|
4011
|
-
setStats(newStats);
|
|
4012
|
-
};
|
|
4013
|
-
reactor.on("statsUpdate", handler);
|
|
4014
|
-
return () => {
|
|
4015
|
-
reactor.off("statsUpdate", handler);
|
|
4016
|
-
setStats(void 0);
|
|
4017
|
-
};
|
|
4018
|
-
}, [reactor]);
|
|
4019
|
-
return stats;
|
|
4020
|
-
}
|
|
4021
|
-
|
|
4022
|
-
// src/react/ReactorView.tsx
|
|
4023
|
-
import { useEffect as useEffect3, useMemo as useMemo2, useRef as useRef3 } from "react";
|
|
4024
|
-
import { jsx as jsx2 } from "react/jsx-runtime";
|
|
4025
|
-
function ReactorView({
|
|
4026
|
-
track = "main_video",
|
|
4027
|
-
audioTrack,
|
|
4028
|
-
width,
|
|
4029
|
-
height,
|
|
4030
|
-
className,
|
|
4031
|
-
style,
|
|
4032
|
-
videoObjectFit = "contain",
|
|
4033
|
-
muted = audioTrack === void 0
|
|
4034
|
-
}) {
|
|
4035
|
-
const { videoMediaTrack, audioMediaTrack } = useReactor((state) => {
|
|
4036
|
-
var _a, _b;
|
|
4037
|
-
return {
|
|
4038
|
-
videoMediaTrack: (_a = state.tracks[track]) != null ? _a : null,
|
|
4039
|
-
audioMediaTrack: audioTrack ? (_b = state.tracks[audioTrack]) != null ? _b : null : null
|
|
4040
|
-
};
|
|
4041
|
-
});
|
|
4042
|
-
const videoRef = useRef3(null);
|
|
4043
|
-
const mediaStream = useMemo2(() => {
|
|
4044
|
-
const tracks = [];
|
|
4045
|
-
if (videoMediaTrack) tracks.push(videoMediaTrack);
|
|
4046
|
-
if (audioMediaTrack) tracks.push(audioMediaTrack);
|
|
4047
|
-
if (tracks.length === 0) return null;
|
|
4048
|
-
return new MediaStream(tracks);
|
|
4049
|
-
}, [videoMediaTrack, audioMediaTrack]);
|
|
4050
|
-
useEffect3(() => {
|
|
4051
|
-
console.debug("[ReactorView] Media track effect triggered", {
|
|
4052
|
-
track,
|
|
4053
|
-
hasVideoElement: !!videoRef.current,
|
|
4054
|
-
hasVideoTrack: !!videoMediaTrack,
|
|
4055
|
-
hasAudioTrack: !!audioMediaTrack
|
|
4056
|
-
});
|
|
4057
|
-
const el = videoRef.current;
|
|
4058
|
-
if (!el || !mediaStream) {
|
|
4059
|
-
console.debug("[ReactorView] No tracks or element to attach");
|
|
4060
|
-
return;
|
|
4061
|
-
}
|
|
4062
|
-
const attach = (reset) => {
|
|
4063
|
-
try {
|
|
4064
|
-
if (reset) el.srcObject = null;
|
|
4065
|
-
el.srcObject = mediaStream;
|
|
4066
|
-
el.play().catch((e) => {
|
|
4067
|
-
console.warn("[ReactorView] Auto-play failed:", e);
|
|
4068
|
-
});
|
|
4069
|
-
} catch (error) {
|
|
4070
|
-
console.error("[ReactorView] Failed to attach media stream:", error);
|
|
4071
|
-
}
|
|
4072
|
-
};
|
|
4073
|
-
console.debug("[ReactorView] Attaching media stream to element");
|
|
4074
|
-
attach(false);
|
|
4075
|
-
const onUnmute = () => {
|
|
4076
|
-
console.debug(
|
|
4077
|
-
"[ReactorView] Track unmuted \u2014 re-attaching to render incoming media"
|
|
4078
|
-
);
|
|
4079
|
-
attach(true);
|
|
4080
|
-
};
|
|
4081
|
-
const tracks = mediaStream.getTracks();
|
|
4082
|
-
for (const t of tracks) t.addEventListener("unmute", onUnmute);
|
|
4083
|
-
return () => {
|
|
4084
|
-
console.debug("[ReactorView] Detaching media stream from element");
|
|
4085
|
-
for (const t of tracks) t.removeEventListener("unmute", onUnmute);
|
|
4086
|
-
if (videoRef.current) {
|
|
4087
|
-
videoRef.current.srcObject = null;
|
|
4088
|
-
}
|
|
4089
|
-
};
|
|
4090
|
-
}, [mediaStream]);
|
|
4091
|
-
return /* @__PURE__ */ jsx2(
|
|
4092
|
-
"div",
|
|
4093
|
-
{
|
|
4094
|
-
style: __spreadValues(__spreadValues(__spreadValues({
|
|
4095
|
-
position: "relative",
|
|
4096
|
-
background: "#000"
|
|
4097
|
-
}, width && { width }), height && { height }), style),
|
|
4098
|
-
className,
|
|
4099
|
-
children: /* @__PURE__ */ jsx2(
|
|
4100
|
-
"video",
|
|
4101
|
-
{
|
|
4102
|
-
ref: videoRef,
|
|
4103
|
-
style: {
|
|
4104
|
-
width: "100%",
|
|
4105
|
-
height: "100%",
|
|
4106
|
-
objectFit: videoObjectFit,
|
|
4107
|
-
display: videoMediaTrack ? "block" : "none"
|
|
4108
|
-
},
|
|
4109
|
-
muted,
|
|
4110
|
-
playsInline: true
|
|
4111
|
-
}
|
|
4112
|
-
)
|
|
4113
|
-
}
|
|
4114
|
-
);
|
|
4115
|
-
}
|
|
4116
|
-
|
|
4117
|
-
// src/react/WebcamStream.tsx
|
|
4118
|
-
import { useEffect as useEffect4, useRef as useRef4, useState as useState3 } from "react";
|
|
4119
|
-
import { jsx as jsx3, jsxs } from "react/jsx-runtime";
|
|
4120
|
-
function WebcamStream({
|
|
4121
|
-
track,
|
|
4122
|
-
audio = false,
|
|
4123
|
-
audioTrack,
|
|
4124
|
-
className,
|
|
4125
|
-
style,
|
|
4126
|
-
videoConstraints = {
|
|
4127
|
-
width: { ideal: 1280 },
|
|
4128
|
-
height: { ideal: 720 }
|
|
4129
|
-
},
|
|
4130
|
-
showWebcam = true,
|
|
4131
|
-
videoObjectFit = "contain",
|
|
4132
|
-
onPermissionDenied,
|
|
4133
|
-
onPublished,
|
|
4134
|
-
onError
|
|
4135
|
-
}) {
|
|
4136
|
-
const [stream, setStream] = useState3(null);
|
|
4137
|
-
const [isPublishing, setIsPublishing] = useState3(false);
|
|
4138
|
-
const [permissionDenied, setPermissionDenied] = useState3(false);
|
|
4139
|
-
const { status, publish, unpublish, reactor } = useReactor((state) => ({
|
|
4140
|
-
status: state.status,
|
|
4141
|
-
publish: state.publish,
|
|
4142
|
-
unpublish: state.unpublish,
|
|
4143
|
-
reactor: state.internal.reactor
|
|
4144
|
-
}));
|
|
4145
|
-
const videoRef = useRef4(null);
|
|
4146
|
-
const onPermissionDeniedRef = useRef4(onPermissionDenied);
|
|
4147
|
-
const onPublishedRef = useRef4(onPublished);
|
|
4148
|
-
const onErrorRef = useRef4(onError);
|
|
4149
|
-
useEffect4(() => {
|
|
4150
|
-
onPermissionDeniedRef.current = onPermissionDenied;
|
|
4151
|
-
onPublishedRef.current = onPublished;
|
|
4152
|
-
onErrorRef.current = onError;
|
|
4153
|
-
});
|
|
4154
|
-
const audioRequested = audio !== false && audio !== void 0;
|
|
4155
|
-
const audioEnabled = audioRequested && !!audioTrack;
|
|
4156
|
-
if (audioRequested && !audioTrack) {
|
|
4157
|
-
console.warn(
|
|
4158
|
-
"[WebcamStream] `audio` was set but `audioTrack` is missing; capturing video-only."
|
|
4159
|
-
);
|
|
4160
|
-
}
|
|
4161
|
-
const startWebcam = () => __async(null, null, function* () {
|
|
4162
|
-
var _a, _b;
|
|
4163
|
-
console.debug("[WebcamPublisher] Starting webcam");
|
|
4164
|
-
try {
|
|
4165
|
-
const mediaStream = yield navigator.mediaDevices.getUserMedia({
|
|
4166
|
-
video: videoConstraints,
|
|
4167
|
-
audio: audioEnabled ? audio === true ? true : audio : false
|
|
4168
|
-
});
|
|
4169
|
-
console.debug("[WebcamPublisher] Webcam started successfully");
|
|
4170
|
-
setStream(mediaStream);
|
|
4171
|
-
setPermissionDenied(false);
|
|
4172
|
-
} catch (err) {
|
|
4173
|
-
console.error("[WebcamPublisher] Failed to start webcam:", err);
|
|
4174
|
-
if (err instanceof DOMException && (err.name === "NotAllowedError" || err.name === "PermissionDeniedError")) {
|
|
4175
|
-
console.debug("[WebcamPublisher] Camera permission denied");
|
|
4176
|
-
setPermissionDenied(true);
|
|
4177
|
-
(_a = onPermissionDeniedRef.current) == null ? void 0 : _a.call(onPermissionDeniedRef);
|
|
4178
|
-
} else {
|
|
4179
|
-
(_b = onErrorRef.current) == null ? void 0 : _b.call(
|
|
4180
|
-
onErrorRef,
|
|
4181
|
-
err instanceof Error ? err : new Error(String(err))
|
|
4182
|
-
);
|
|
4183
|
-
}
|
|
4184
|
-
}
|
|
4185
|
-
});
|
|
4186
|
-
const stopWebcam = () => __async(null, null, function* () {
|
|
4187
|
-
var _a;
|
|
4188
|
-
console.debug("[WebcamPublisher] Stopping webcam");
|
|
4189
|
-
const unpublishTasks = [unpublish(track)];
|
|
4190
|
-
if (audioEnabled && audioTrack) {
|
|
4191
|
-
unpublishTasks.push(unpublish(audioTrack));
|
|
4192
|
-
}
|
|
4193
|
-
const results = yield Promise.allSettled(unpublishTasks);
|
|
4194
|
-
for (const r of results) {
|
|
4195
|
-
if (r.status === "rejected") {
|
|
4196
|
-
console.error(
|
|
4197
|
-
"[WebcamPublisher] Error unpublishing before stop:",
|
|
4198
|
-
r.reason
|
|
4199
|
-
);
|
|
4200
|
-
(_a = onErrorRef.current) == null ? void 0 : _a.call(
|
|
4201
|
-
onErrorRef,
|
|
4202
|
-
r.reason instanceof Error ? r.reason : new Error(String(r.reason))
|
|
4203
|
-
);
|
|
4204
|
-
}
|
|
4205
|
-
}
|
|
4206
|
-
setIsPublishing(false);
|
|
4207
|
-
stream == null ? void 0 : stream.getTracks().forEach((t) => {
|
|
4208
|
-
t.stop();
|
|
4209
|
-
console.debug("[WebcamPublisher] Stopped track:", t.kind);
|
|
4210
|
-
});
|
|
4211
|
-
setStream(null);
|
|
4212
|
-
console.debug("[WebcamPublisher] Webcam stopped");
|
|
4213
|
-
});
|
|
4214
|
-
useEffect4(() => {
|
|
4215
|
-
console.debug("[WebcamPublisher] Stream effect triggered", {
|
|
4216
|
-
hasVideoElement: !!videoRef.current,
|
|
4217
|
-
hasStream: !!stream
|
|
4218
|
-
});
|
|
4219
|
-
if (!videoRef.current) {
|
|
4220
|
-
return;
|
|
4221
|
-
}
|
|
4222
|
-
if (stream) {
|
|
4223
|
-
console.debug("[WebcamPublisher] Attaching stream to video element");
|
|
4224
|
-
videoRef.current.srcObject = stream;
|
|
4225
|
-
console.debug("[WebcamPublisher] Stream attached successfully");
|
|
4226
|
-
} else {
|
|
4227
|
-
console.debug("[WebcamPublisher] Clearing video element");
|
|
4228
|
-
videoRef.current.srcObject = null;
|
|
4229
|
-
}
|
|
4230
|
-
}, [stream]);
|
|
4231
|
-
useEffect4(() => {
|
|
4232
|
-
if (!stream) {
|
|
4233
|
-
return;
|
|
4234
|
-
}
|
|
4235
|
-
if (status === "ready" && !isPublishing) {
|
|
4236
|
-
console.debug(
|
|
4237
|
-
"[WebcamPublisher] Reactor ready, auto-publishing webcam stream"
|
|
4238
|
-
);
|
|
4239
|
-
const videoMediaTrack = stream.getVideoTracks()[0];
|
|
4240
|
-
const audioMediaTrack = audioEnabled && audioTrack ? stream.getAudioTracks()[0] : null;
|
|
4241
|
-
const tasks = [];
|
|
4242
|
-
if (videoMediaTrack) tasks.push(publish(track, videoMediaTrack));
|
|
4243
|
-
if (audioMediaTrack && audioTrack)
|
|
4244
|
-
tasks.push(publish(audioTrack, audioMediaTrack));
|
|
4245
|
-
if (tasks.length === 0) return;
|
|
4246
|
-
Promise.all(tasks).then(() => {
|
|
4247
|
-
var _a;
|
|
4248
|
-
console.debug("[WebcamPublisher] Auto-publish successful");
|
|
4249
|
-
setIsPublishing(true);
|
|
4250
|
-
(_a = onPublishedRef.current) == null ? void 0 : _a.call(onPublishedRef);
|
|
4251
|
-
}).catch((err) => {
|
|
4252
|
-
var _a;
|
|
4253
|
-
console.error("[WebcamPublisher] Auto-publish failed:", err);
|
|
4254
|
-
(_a = onErrorRef.current) == null ? void 0 : _a.call(
|
|
4255
|
-
onErrorRef,
|
|
4256
|
-
err instanceof Error ? err : new Error(String(err))
|
|
4257
|
-
);
|
|
4258
|
-
});
|
|
4259
|
-
} else if (status !== "ready" && isPublishing) {
|
|
4260
|
-
console.debug("[WebcamPublisher] Reactor not ready, auto-unpublishing");
|
|
4261
|
-
const tasks = [unpublish(track)];
|
|
4262
|
-
if (audioEnabled && audioTrack) tasks.push(unpublish(audioTrack));
|
|
4263
|
-
Promise.allSettled(tasks).then((results) => {
|
|
4264
|
-
var _a;
|
|
4265
|
-
for (const r of results) {
|
|
4266
|
-
if (r.status === "rejected") {
|
|
4267
|
-
console.error("[WebcamPublisher] Auto-unpublish failed:", r.reason);
|
|
4268
|
-
(_a = onErrorRef.current) == null ? void 0 : _a.call(
|
|
4269
|
-
onErrorRef,
|
|
4270
|
-
r.reason instanceof Error ? r.reason : new Error(String(r.reason))
|
|
4271
|
-
);
|
|
4272
|
-
}
|
|
4273
|
-
}
|
|
4274
|
-
setIsPublishing(false);
|
|
4275
|
-
});
|
|
4276
|
-
}
|
|
4277
|
-
}, [
|
|
4278
|
-
status,
|
|
4279
|
-
stream,
|
|
4280
|
-
isPublishing,
|
|
4281
|
-
publish,
|
|
4282
|
-
unpublish,
|
|
4283
|
-
track,
|
|
4284
|
-
audioEnabled,
|
|
4285
|
-
audioTrack
|
|
4286
|
-
]);
|
|
4287
|
-
useEffect4(() => {
|
|
4288
|
-
const handleError = (error) => {
|
|
4289
|
-
console.debug("[WebcamPublisher] Received error event:", error);
|
|
4290
|
-
if (error.code === "TRACK_PUBLISH_FAILED") {
|
|
4291
|
-
console.debug(
|
|
4292
|
-
"[WebcamPublisher] Track publish failed, resetting isPublishing state"
|
|
4293
|
-
);
|
|
4294
|
-
setIsPublishing(false);
|
|
4295
|
-
}
|
|
4296
|
-
};
|
|
4297
|
-
reactor.on("error", handleError);
|
|
4298
|
-
return () => {
|
|
4299
|
-
reactor.off("error", handleError);
|
|
4300
|
-
};
|
|
4301
|
-
}, [reactor]);
|
|
4302
|
-
useEffect4(() => {
|
|
4303
|
-
if (status !== "ready") {
|
|
4304
|
-
console.debug(
|
|
4305
|
-
"[WebcamPublisher] Status changed to",
|
|
4306
|
-
status,
|
|
4307
|
-
"- resetting isPublishing state"
|
|
4308
|
-
);
|
|
4309
|
-
setIsPublishing(false);
|
|
4310
|
-
}
|
|
4311
|
-
}, [status, isPublishing]);
|
|
4312
|
-
useEffect4(() => {
|
|
4313
|
-
console.debug("[WebcamPublisher] Auto-starting webcam");
|
|
4314
|
-
startWebcam();
|
|
4315
|
-
return () => {
|
|
4316
|
-
console.debug("[WebcamPublisher] Cleanup on unmount");
|
|
4317
|
-
stopWebcam();
|
|
4318
|
-
};
|
|
4319
|
-
}, []);
|
|
4320
|
-
const showPlaceholder = !stream;
|
|
4321
|
-
return /* @__PURE__ */ jsxs(
|
|
4322
|
-
"div",
|
|
4323
|
-
{
|
|
4324
|
-
style: __spreadValues({
|
|
4325
|
-
display: showWebcam ? "block" : "none",
|
|
4326
|
-
position: "relative",
|
|
4327
|
-
background: "#000"
|
|
4328
|
-
}, style),
|
|
4329
|
-
className,
|
|
4330
|
-
children: [
|
|
4331
|
-
/* @__PURE__ */ jsx3(
|
|
4332
|
-
"video",
|
|
4333
|
-
{
|
|
4334
|
-
ref: videoRef,
|
|
4335
|
-
style: {
|
|
4336
|
-
width: "100%",
|
|
4337
|
-
height: "100%",
|
|
4338
|
-
objectFit: videoObjectFit,
|
|
4339
|
-
display: showPlaceholder ? "none" : "block"
|
|
4340
|
-
},
|
|
4341
|
-
muted: true,
|
|
4342
|
-
playsInline: true,
|
|
4343
|
-
autoPlay: true
|
|
4344
|
-
}
|
|
4345
|
-
),
|
|
4346
|
-
showPlaceholder && /* @__PURE__ */ jsx3(
|
|
4347
|
-
"div",
|
|
4348
|
-
{
|
|
4349
|
-
style: {
|
|
4350
|
-
position: "absolute",
|
|
4351
|
-
top: 0,
|
|
4352
|
-
left: 0,
|
|
4353
|
-
width: "100%",
|
|
4354
|
-
height: "100%",
|
|
4355
|
-
color: "#fff",
|
|
4356
|
-
display: "flex",
|
|
4357
|
-
alignItems: "center",
|
|
4358
|
-
justifyContent: "center",
|
|
4359
|
-
fontSize: "16px",
|
|
4360
|
-
fontFamily: "monospace",
|
|
4361
|
-
textAlign: "center",
|
|
4362
|
-
padding: "20px",
|
|
4363
|
-
boxSizing: "border-box",
|
|
4364
|
-
flexDirection: "column",
|
|
4365
|
-
gap: "12px"
|
|
4366
|
-
},
|
|
4367
|
-
children: permissionDenied ? /* @__PURE__ */ jsxs("div", { style: { fontSize: "12px", fontFamily: "monospace" }, children: [
|
|
4368
|
-
"Camera access denied.",
|
|
4369
|
-
/* @__PURE__ */ jsx3("br", {}),
|
|
4370
|
-
"Please allow access in your browser settings."
|
|
4371
|
-
] }) : /* @__PURE__ */ jsx3("div", { style: { fontSize: "12px", fontFamily: "monospace" }, children: "Starting camera..." })
|
|
4372
|
-
}
|
|
4373
|
-
)
|
|
4374
|
-
]
|
|
4375
|
-
}
|
|
4376
|
-
);
|
|
4377
|
-
}
|
|
4378
|
-
|
|
4379
|
-
// src/react/ClipPlayer.tsx
|
|
4380
|
-
import { useContext as useContext2, useEffect as useEffect5, useRef as useRef5, useState as useState4 } from "react";
|
|
4381
|
-
|
|
4382
|
-
// src/utils/clipPlayback.ts
|
|
4383
|
-
function attachClipPlayback(video, source, {
|
|
4384
|
-
autoPlay,
|
|
4385
|
-
onReady,
|
|
4386
|
-
onError,
|
|
4387
|
-
loadHls = () => import("hls.js").then(
|
|
4388
|
-
(mod) => mod.default
|
|
4389
|
-
)
|
|
4390
|
-
}) {
|
|
4391
|
-
let destroyed = false;
|
|
4392
|
-
let failed = false;
|
|
4393
|
-
let ready = false;
|
|
4394
|
-
let hls = null;
|
|
4395
|
-
let mp4Url = null;
|
|
4396
|
-
const fail = (error) => {
|
|
4397
|
-
if (destroyed || failed) return;
|
|
4398
|
-
failed = true;
|
|
4399
|
-
onError(error);
|
|
4400
|
-
};
|
|
4401
|
-
const handleLoadedMetadata = () => {
|
|
4402
|
-
if (destroyed || failed || ready) return;
|
|
4403
|
-
ready = true;
|
|
4404
|
-
onReady();
|
|
4405
|
-
if (autoPlay) {
|
|
4406
|
-
video.play().catch(() => {
|
|
4407
|
-
});
|
|
4408
|
-
}
|
|
4409
|
-
};
|
|
4410
|
-
const handleElementError = () => {
|
|
4411
|
-
fail(new Error(describeMediaError(video.error)));
|
|
4412
|
-
};
|
|
4413
|
-
video.addEventListener("loadedmetadata", handleLoadedMetadata);
|
|
4414
|
-
video.addEventListener("error", handleElementError);
|
|
4415
|
-
const handle = {
|
|
4416
|
-
destroy: () => {
|
|
4417
|
-
destroyed = true;
|
|
4418
|
-
video.removeEventListener("loadedmetadata", handleLoadedMetadata);
|
|
4419
|
-
video.removeEventListener("error", handleElementError);
|
|
4420
|
-
hls == null ? void 0 : hls.destroy();
|
|
4421
|
-
hls = null;
|
|
4422
|
-
if (mp4Url) {
|
|
4423
|
-
URL.revokeObjectURL(mp4Url);
|
|
4424
|
-
mp4Url = null;
|
|
4425
|
-
}
|
|
4426
|
-
}
|
|
4427
|
-
};
|
|
4428
|
-
const selectPath = () => __async(null, null, function* () {
|
|
4429
|
-
const HlsCtor = hasMediaSource() ? yield loadHls().catch(() => null) : null;
|
|
4430
|
-
if (destroyed) return;
|
|
4431
|
-
if (HlsCtor == null ? void 0 : HlsCtor.isSupported()) {
|
|
4432
|
-
const instance = new HlsCtor();
|
|
4433
|
-
instance.loadSource(source.manifestUrl);
|
|
4434
|
-
instance.attachMedia(video);
|
|
4435
|
-
instance.on(HlsCtor.Events.ERROR, (_evt, data) => {
|
|
4436
|
-
var _a;
|
|
4437
|
-
if (destroyed) return;
|
|
4438
|
-
if (data.fatal) {
|
|
4439
|
-
fail(new Error(`Playback error: ${(_a = data.details) != null ? _a : "unknown"}`));
|
|
4440
|
-
return;
|
|
4441
|
-
}
|
|
4442
|
-
console.warn("[Reactor.ClipPlayer] hls.js non-fatal error", data);
|
|
4443
|
-
});
|
|
4444
|
-
hls = instance;
|
|
4445
|
-
return;
|
|
4446
|
-
}
|
|
4447
|
-
const blob = yield source.assembleMp4();
|
|
4448
|
-
if (destroyed) return;
|
|
4449
|
-
mp4Url = URL.createObjectURL(blob);
|
|
4450
|
-
video.src = mp4Url;
|
|
4451
|
-
});
|
|
4452
|
-
selectPath().catch((err) => {
|
|
4453
|
-
fail(err instanceof Error ? err : new Error(String(err)));
|
|
4454
|
-
});
|
|
4455
|
-
return handle;
|
|
4456
|
-
}
|
|
4457
|
-
function hasMediaSource() {
|
|
4458
|
-
var _a, _b;
|
|
4459
|
-
const scope = globalThis;
|
|
4460
|
-
return Boolean(
|
|
4461
|
-
(_b = (_a = scope.ManagedMediaSource) != null ? _a : scope.MediaSource) != null ? _b : scope.WebKitMediaSource
|
|
4462
|
-
);
|
|
4463
|
-
}
|
|
4464
|
-
var MEDIA_ERROR_MESSAGES = {
|
|
4465
|
-
1: "Playback was aborted.",
|
|
4466
|
-
2: "A network error interrupted playback.",
|
|
4467
|
-
3: "This clip could not be decoded.",
|
|
4468
|
-
4: "This browser cannot play this clip. Use Download instead."
|
|
4469
|
-
};
|
|
4470
|
-
function describeMediaError(error) {
|
|
4471
|
-
var _a;
|
|
4472
|
-
const message = (_a = error && MEDIA_ERROR_MESSAGES[error.code]) != null ? _a : "This clip failed to play in this browser. Use Download instead.";
|
|
4473
|
-
return (error == null ? void 0 : error.message) ? `${message} (${error.message})` : message;
|
|
4474
|
-
}
|
|
4475
|
-
|
|
4476
|
-
// src/react/ClipPlayer.tsx
|
|
4477
|
-
import { jsx as jsx4, jsxs as jsxs2 } from "react/jsx-runtime";
|
|
4478
|
-
function ClipPlayer({
|
|
4479
|
-
clip,
|
|
4480
|
-
getJwt,
|
|
4481
|
-
slackMs,
|
|
4482
|
-
autoPlay = true,
|
|
4483
|
-
muted = true,
|
|
4484
|
-
className,
|
|
4485
|
-
style,
|
|
4486
|
-
onError
|
|
4487
|
-
}) {
|
|
4488
|
-
const videoRef = useRef5(null);
|
|
4489
|
-
const [phase, setPhase] = useState4({ kind: "waiting" });
|
|
4490
|
-
const store = useContext2(ReactorContext);
|
|
4491
|
-
const getJwtRef = useRef5(getJwt);
|
|
4492
|
-
const autoPlayRef = useRef5(autoPlay);
|
|
4493
|
-
const slackMsRef = useRef5(slackMs);
|
|
4494
|
-
const onErrorRef = useRef5(onError);
|
|
4495
|
-
const storeRef = useRef5(store);
|
|
4496
|
-
useEffect5(() => {
|
|
4497
|
-
getJwtRef.current = getJwt;
|
|
4498
|
-
autoPlayRef.current = autoPlay;
|
|
4499
|
-
slackMsRef.current = slackMs;
|
|
4500
|
-
onErrorRef.current = onError;
|
|
4501
|
-
storeRef.current = store;
|
|
4502
|
-
});
|
|
4503
|
-
useEffect5(() => {
|
|
4504
|
-
var _a;
|
|
4505
|
-
if (phase.kind === "error") {
|
|
4506
|
-
(_a = onErrorRef.current) == null ? void 0 : _a.call(onErrorRef, phase.error);
|
|
4507
|
-
}
|
|
4508
|
-
}, [phase]);
|
|
4509
|
-
useEffect5(() => {
|
|
4510
|
-
const video = videoRef.current;
|
|
4511
|
-
if (!video) return;
|
|
4512
|
-
const abort = new AbortController();
|
|
4513
|
-
let cancelled = false;
|
|
4514
|
-
let playback = null;
|
|
4515
|
-
let manifestBlobUrl = null;
|
|
4516
|
-
const fail = (error) => {
|
|
4517
|
-
if (cancelled) return;
|
|
4518
|
-
const message = error instanceof RecordingError ? `${error.code}: ${error.reason}` : error.message;
|
|
4519
|
-
setPhase({ kind: "error", message, error });
|
|
4520
|
-
};
|
|
4521
|
-
const setup = () => __async(null, null, function* () {
|
|
4522
|
-
var _a;
|
|
4523
|
-
try {
|
|
4524
|
-
setPhase({ kind: "waiting" });
|
|
4525
|
-
const explicit = getJwtRef.current;
|
|
4526
|
-
const fallback = (_a = storeRef.current) == null ? void 0 : _a.getState().internal.reactor.getJwtResolver();
|
|
4527
|
-
const resolver = explicit != null ? explicit : fallback;
|
|
4528
|
-
const jwt = resolver ? yield resolver() : void 0;
|
|
4529
|
-
if (cancelled) return;
|
|
4530
|
-
const body = yield fetchPlaylist(clip.playlistUrl, {
|
|
4531
|
-
predictedReadyAtMs: clip.predictedReadyAtMs,
|
|
4532
|
-
slackMs: slackMsRef.current,
|
|
4533
|
-
jwt,
|
|
4534
|
-
signal: abort.signal
|
|
4535
|
-
});
|
|
4536
|
-
if (cancelled) return;
|
|
4537
|
-
setPhase({ kind: "loading" });
|
|
4538
|
-
manifestBlobUrl = createPlayableManifestUrl(body, clip.playlistUrl);
|
|
4539
|
-
playback = attachClipPlayback(
|
|
4540
|
-
video,
|
|
4541
|
-
{
|
|
4542
|
-
manifestUrl: manifestBlobUrl,
|
|
4543
|
-
assembleMp4: () => assembleClipBlob(body, clip.playlistUrl, {
|
|
4544
|
-
signal: abort.signal
|
|
4545
|
-
})
|
|
4546
|
-
},
|
|
4547
|
-
{
|
|
4548
|
-
autoPlay: autoPlayRef.current,
|
|
4549
|
-
onReady: () => {
|
|
4550
|
-
if (!cancelled) setPhase({ kind: "ready" });
|
|
4551
|
-
},
|
|
4552
|
-
onError: fail
|
|
4553
|
-
}
|
|
4554
|
-
);
|
|
4555
|
-
} catch (err) {
|
|
4556
|
-
if (cancelled) return;
|
|
4557
|
-
if (err instanceof DOMException && err.name === "AbortError") {
|
|
4558
|
-
return;
|
|
4559
|
-
}
|
|
4560
|
-
fail(err instanceof Error ? err : new Error(String(err)));
|
|
4561
|
-
}
|
|
4562
|
-
});
|
|
4563
|
-
setup();
|
|
4564
|
-
return () => {
|
|
4565
|
-
cancelled = true;
|
|
4566
|
-
abort.abort();
|
|
4567
|
-
playback == null ? void 0 : playback.destroy();
|
|
4568
|
-
video.pause();
|
|
4569
|
-
video.removeAttribute("src");
|
|
4570
|
-
video.load();
|
|
4571
|
-
if (manifestBlobUrl) URL.revokeObjectURL(manifestBlobUrl);
|
|
4572
|
-
};
|
|
4573
|
-
}, [clip]);
|
|
4574
|
-
const overlayText = phase.kind === "waiting" ? "Waiting for clip\u2026" : phase.kind === "loading" ? "Loading player\u2026" : null;
|
|
4575
|
-
return /* @__PURE__ */ jsxs2(
|
|
4576
|
-
"div",
|
|
4577
|
-
{
|
|
4578
|
-
className,
|
|
4579
|
-
style: __spreadValues({
|
|
4580
|
-
position: "relative",
|
|
4581
|
-
background: "#000",
|
|
4582
|
-
width: "100%",
|
|
4583
|
-
display: "flex",
|
|
4584
|
-
alignItems: "center",
|
|
4585
|
-
justifyContent: "center"
|
|
4586
|
-
}, style),
|
|
4587
|
-
children: [
|
|
4588
|
-
/* @__PURE__ */ jsx4(
|
|
4589
|
-
"video",
|
|
4590
|
-
{
|
|
4591
|
-
ref: videoRef,
|
|
4592
|
-
controls: true,
|
|
4593
|
-
playsInline: true,
|
|
4594
|
-
muted,
|
|
4595
|
-
style: {
|
|
4596
|
-
display: "block",
|
|
4597
|
-
width: "100%",
|
|
4598
|
-
height: "auto",
|
|
4599
|
-
maxHeight: "100%"
|
|
4600
|
-
}
|
|
4601
|
-
}
|
|
4602
|
-
),
|
|
4603
|
-
overlayText && /* @__PURE__ */ jsx4(
|
|
4604
|
-
"div",
|
|
4605
|
-
{
|
|
4606
|
-
style: {
|
|
4607
|
-
position: "absolute",
|
|
4608
|
-
inset: 0,
|
|
4609
|
-
display: "flex",
|
|
4610
|
-
alignItems: "center",
|
|
4611
|
-
justifyContent: "center",
|
|
4612
|
-
color: "rgba(255,255,255,0.6)",
|
|
4613
|
-
font: "11px ui-monospace, SFMono-Regular, Menlo, monospace",
|
|
4614
|
-
letterSpacing: "0.1em",
|
|
4615
|
-
textTransform: "uppercase",
|
|
4616
|
-
pointerEvents: "none"
|
|
4617
|
-
},
|
|
4618
|
-
children: overlayText
|
|
4619
|
-
}
|
|
4620
|
-
),
|
|
4621
|
-
phase.kind === "error" && /* @__PURE__ */ jsx4(
|
|
4622
|
-
"div",
|
|
4623
|
-
{
|
|
4624
|
-
style: {
|
|
4625
|
-
position: "absolute",
|
|
4626
|
-
inset: 0,
|
|
4627
|
-
display: "flex",
|
|
4628
|
-
alignItems: "center",
|
|
4629
|
-
justifyContent: "center",
|
|
4630
|
-
padding: 24,
|
|
4631
|
-
background: "rgba(0,0,0,0.8)",
|
|
4632
|
-
color: "#ef4444",
|
|
4633
|
-
font: "11px ui-monospace, SFMono-Regular, Menlo, monospace",
|
|
4634
|
-
textAlign: "center"
|
|
4635
|
-
},
|
|
4636
|
-
children: phase.message
|
|
4637
|
-
}
|
|
4638
|
-
)
|
|
4639
|
-
]
|
|
4640
|
-
}
|
|
4641
|
-
);
|
|
4642
|
-
}
|
|
4643
|
-
|
|
4644
|
-
// src/react/ClipDownloadButton.tsx
|
|
4645
|
-
import { useEffect as useEffect7, useRef as useRef7 } from "react";
|
|
4646
|
-
|
|
4647
|
-
// src/react/useClipDownload.ts
|
|
4648
|
-
import { useCallback, useContext as useContext3, useEffect as useEffect6, useRef as useRef6, useState as useState5 } from "react";
|
|
4649
|
-
function useClipDownload(clip, options = {}) {
|
|
4650
|
-
var _a;
|
|
4651
|
-
const [state, setState] = useState5({ kind: "idle" });
|
|
4652
|
-
const store = useContext3(ReactorContext);
|
|
4653
|
-
const clipRef = useRef6(clip);
|
|
4654
|
-
const filenameRef = useRef6(
|
|
4655
|
-
(_a = options.filename) != null ? _a : "reactor-clip.mp4"
|
|
4656
|
-
);
|
|
4657
|
-
const getJwtRef = useRef6(options.getJwt);
|
|
4658
|
-
useEffect6(() => {
|
|
4659
|
-
clipRef.current = clip;
|
|
4660
|
-
filenameRef.current = options.filename === void 0 ? "reactor-clip.mp4" : options.filename;
|
|
4661
|
-
getJwtRef.current = options.getJwt;
|
|
4662
|
-
});
|
|
4663
|
-
const inFlightRef = useRef6(false);
|
|
4664
|
-
const abortRef = useRef6(null);
|
|
4665
|
-
useEffect6(() => () => {
|
|
4666
|
-
var _a2;
|
|
4667
|
-
return (_a2 = abortRef.current) == null ? void 0 : _a2.abort();
|
|
4668
|
-
}, []);
|
|
4669
|
-
const download = useCallback(() => __async(null, null, function* () {
|
|
4670
|
-
if (inFlightRef.current) return void 0;
|
|
4671
|
-
inFlightRef.current = true;
|
|
4672
|
-
const abort = new AbortController();
|
|
4673
|
-
abortRef.current = abort;
|
|
4674
|
-
setState({ kind: "downloading", fetched: 0, total: 0 });
|
|
4675
|
-
try {
|
|
4676
|
-
const explicit = getJwtRef.current;
|
|
4677
|
-
const fallback = store == null ? void 0 : store.getState().internal.reactor.getJwtResolver();
|
|
4678
|
-
const resolver = explicit != null ? explicit : fallback;
|
|
4679
|
-
const jwt = resolver ? yield resolver() : void 0;
|
|
4680
|
-
const blob = yield downloadClipAsFile(
|
|
4681
|
-
clipRef.current,
|
|
4682
|
-
filenameRef.current,
|
|
4683
|
-
{
|
|
4684
|
-
jwt,
|
|
4685
|
-
signal: abort.signal,
|
|
4686
|
-
onProgress: ({ fetched, total }) => setState({ kind: "downloading", fetched, total })
|
|
4687
|
-
}
|
|
4688
|
-
);
|
|
4689
|
-
setState({ kind: "idle" });
|
|
4690
|
-
return blob;
|
|
4691
|
-
} catch (err) {
|
|
4692
|
-
if (err instanceof DOMException && err.name === "AbortError") {
|
|
4693
|
-
return void 0;
|
|
4694
|
-
}
|
|
4695
|
-
const message = err instanceof RecordingError ? `${err.code}: ${err.reason}` : err instanceof Error ? err.message : String(err);
|
|
4696
|
-
setState({ kind: "error", message });
|
|
4697
|
-
return void 0;
|
|
4698
|
-
} finally {
|
|
4699
|
-
inFlightRef.current = false;
|
|
4700
|
-
}
|
|
4701
|
-
}), [store]);
|
|
4702
|
-
const reset = useCallback(() => setState({ kind: "idle" }), []);
|
|
4703
|
-
return { state, download, reset };
|
|
4704
|
-
}
|
|
4705
|
-
|
|
4706
|
-
// src/react/ClipDownloadButton.tsx
|
|
4707
|
-
import { jsx as jsx5 } from "react/jsx-runtime";
|
|
4708
|
-
function ClipDownloadButton({
|
|
4709
|
-
clip,
|
|
4710
|
-
getJwt,
|
|
4711
|
-
filename = "reactor-clip.mp4",
|
|
4712
|
-
children,
|
|
4713
|
-
className,
|
|
4714
|
-
style,
|
|
4715
|
-
disabled,
|
|
4716
|
-
onSuccess,
|
|
4717
|
-
onError
|
|
4718
|
-
}) {
|
|
4719
|
-
const { state, download } = useClipDownload(clip, { filename, getJwt });
|
|
4720
|
-
const downloading = state.kind === "downloading";
|
|
4721
|
-
const isDisabled = downloading || !!disabled;
|
|
4722
|
-
const onSuccessRef = useRef7(onSuccess);
|
|
4723
|
-
const onErrorRef = useRef7(onError);
|
|
4724
|
-
useEffect7(() => {
|
|
4725
|
-
onSuccessRef.current = onSuccess;
|
|
4726
|
-
onErrorRef.current = onError;
|
|
4727
|
-
});
|
|
4728
|
-
useEffect7(() => {
|
|
4729
|
-
var _a;
|
|
4730
|
-
if (state.kind === "error") {
|
|
4731
|
-
(_a = onErrorRef.current) == null ? void 0 : _a.call(onErrorRef, new Error(state.message));
|
|
4732
|
-
}
|
|
4733
|
-
}, [state]);
|
|
4734
|
-
const content = typeof children === "function" ? children(state) : children !== void 0 ? children : defaultLabel(state);
|
|
4735
|
-
return /* @__PURE__ */ jsx5(
|
|
4736
|
-
"button",
|
|
4737
|
-
{
|
|
4738
|
-
type: "button",
|
|
4739
|
-
onClick: () => {
|
|
4740
|
-
void download().then((blob) => {
|
|
4741
|
-
var _a;
|
|
4742
|
-
if (blob) (_a = onSuccessRef.current) == null ? void 0 : _a.call(onSuccessRef, blob);
|
|
4743
|
-
});
|
|
4744
|
-
},
|
|
4745
|
-
disabled: isDisabled,
|
|
4746
|
-
title: state.kind === "error" ? state.message : void 0,
|
|
4747
|
-
className,
|
|
4748
|
-
style: __spreadValues({
|
|
4749
|
-
padding: "5px 12px",
|
|
4750
|
-
borderRadius: 4,
|
|
4751
|
-
border: "1px solid rgba(255,255,255,0.15)",
|
|
4752
|
-
background: "rgba(255,255,255,0.05)",
|
|
4753
|
-
color: "#fff",
|
|
4754
|
-
font: "11px ui-monospace, SFMono-Regular, Menlo, monospace",
|
|
4755
|
-
cursor: isDisabled ? "default" : "pointer",
|
|
4756
|
-
opacity: isDisabled ? 0.6 : 1,
|
|
4757
|
-
transition: "background-color 120ms ease"
|
|
4758
|
-
}, style),
|
|
4759
|
-
children: content
|
|
4760
|
-
}
|
|
4761
|
-
);
|
|
4762
|
-
}
|
|
4763
|
-
function defaultLabel(state) {
|
|
4764
|
-
if (state.kind === "downloading") {
|
|
4765
|
-
if (state.total > 0) {
|
|
4766
|
-
return `Downloading ${state.fetched}/${state.total}\u2026`;
|
|
4767
|
-
}
|
|
4768
|
-
return "Downloading\u2026";
|
|
4769
|
-
}
|
|
4770
|
-
return "Download";
|
|
4771
|
-
}
|
|
4772
|
-
export {
|
|
4773
|
-
AbortError,
|
|
4774
|
-
ClipDownloadButton,
|
|
4775
|
-
ClipPlayer,
|
|
4776
|
-
ConflictError,
|
|
4777
|
-
DEFAULT_BASE_URL,
|
|
4778
|
-
DEFAULT_CLIP_REQUEST_TIMEOUT_MS,
|
|
4779
|
-
DEFAULT_PLAYLIST_POLL_SLACK_MS,
|
|
4780
|
-
FileRef,
|
|
4781
|
-
Reactor,
|
|
4782
|
-
ReactorProvider,
|
|
4783
|
-
ReactorView,
|
|
4784
|
-
RecordingClient,
|
|
4785
|
-
RecordingError,
|
|
4786
|
-
RuntimeRecordingMessageType,
|
|
4787
|
-
SessionLostError,
|
|
4788
|
-
WebcamStream,
|
|
4789
|
-
clipFromPayload,
|
|
4790
|
-
createPlayableManifestUrl,
|
|
4791
|
-
downloadClipAsFile,
|
|
4792
|
-
fetchPlaylist,
|
|
4793
|
-
isAbortError,
|
|
4794
|
-
isSessionLostError,
|
|
4795
|
-
normalizeJwtSource,
|
|
4796
|
-
parsePlaylist,
|
|
4797
|
-
rewriteUrlHost,
|
|
4798
|
-
useClipDownload,
|
|
4799
|
-
useReactor,
|
|
4800
|
-
useReactorInternalMessage,
|
|
4801
|
-
useReactorMessage,
|
|
4802
|
-
useReactorStore,
|
|
4803
|
-
useStats
|
|
4804
|
-
};
|
|
4805
|
-
//# sourceMappingURL=index.mjs.map
|