@neta-art/cohub-cli 10.23.0 → 10.25.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 +18 -5
- package/bin/cohub.js +4 -1
- package/dist/board-gpu/page.js +1566 -71230
- package/dist/bootstrap.js +67 -27
- package/dist/build.json +1 -1
- package/dist/{board-kernel/FilterPipe.js → chunks/Geometry.js} +10447 -10469
- package/dist/chunks/about.js +102 -0
- package/dist/chunks/app-realtime.js +2216 -0
- package/dist/chunks/app-realtime2.js +2 -0
- package/dist/chunks/app-ref.js +88 -0
- package/dist/chunks/apps.js +1423 -0
- package/dist/chunks/auth.js +175 -0
- package/dist/chunks/avatar.js +146 -0
- package/dist/chunks/board-export-resources.js +232 -0
- package/dist/chunks/board-export.js +874 -0
- package/dist/chunks/board-export2.js +2 -0
- package/dist/{board-kernel.js → chunks/board-kernel.js} +18032 -28512
- package/dist/chunks/board-kernel2.js +4 -0
- package/dist/chunks/board-profile.js +69 -0
- package/dist/chunks/board-simulate.js +315 -0
- package/dist/chunks/board-time.js +34 -0
- package/dist/chunks/boards.js +1943 -0
- package/dist/{board-kernel → chunks}/browserAll.js +9 -8
- package/dist/chunks/channels.js +64 -0
- package/dist/chunks/client.js +12606 -0
- package/dist/chunks/command-input.js +17 -0
- package/dist/chunks/commander.js +2962 -0
- package/dist/chunks/cron-jobs.js +163 -0
- package/dist/chunks/daemon.js +545 -0
- package/dist/chunks/daemon2.js +2 -0
- package/dist/chunks/desktop.js +172 -0
- package/dist/chunks/endpoint-options.js +26 -0
- package/dist/chunks/env-proxy.js +35 -0
- package/dist/chunks/environment.js +154 -0
- package/dist/chunks/feedback.js +120 -0
- package/dist/chunks/generations.js +379 -0
- package/dist/chunks/host.js +9 -0
- package/dist/chunks/http-put.js +131 -0
- package/dist/chunks/id.js +2416 -0
- package/dist/{board-kernel → chunks}/init.js +1 -1
- package/dist/chunks/install.js +11959 -0
- package/dist/chunks/launch.js +374 -0
- package/dist/chunks/local-media.js +47 -0
- package/dist/chunks/me.js +134 -0
- package/dist/chunks/media.js +315 -0
- package/dist/chunks/models.js +242 -0
- package/dist/chunks/operands.js +46 -0
- package/dist/chunks/package-paths.js +13 -0
- package/dist/chunks/policy.js +221 -0
- package/dist/chunks/preferences.js +29 -0
- package/dist/chunks/profile.js +64 -0
- package/dist/chunks/prompts.js +41 -0
- package/dist/chunks/public.js +2 -0
- package/dist/chunks/public2.js +244 -0
- package/dist/chunks/references.js +197 -0
- package/dist/chunks/referrals.js +90 -0
- package/dist/chunks/rolldown-runtime.js +26 -0
- package/dist/chunks/rooms-connect.js +2 -0
- package/dist/chunks/rooms-connect2.js +151 -0
- package/dist/chunks/rooms-rtc.js +309 -0
- package/dist/chunks/rooms.js +211 -0
- package/dist/chunks/run.js +220 -0
- package/dist/chunks/runtime.js +638 -0
- package/dist/chunks/runtime2.js +286 -0
- package/dist/chunks/runtimes.js +48 -0
- package/dist/chunks/safe-remote-image.js +198 -0
- package/dist/chunks/schemas.js +6017 -0
- package/dist/chunks/search.js +113 -0
- package/dist/chunks/self-update.js +238 -0
- package/dist/chunks/serve.js +1246 -0
- package/dist/chunks/session-status.js +24 -0
- package/dist/chunks/skills.js +35 -0
- package/dist/chunks/spaces.js +5080 -0
- package/dist/chunks/src.js +405 -0
- package/dist/chunks/supervisor.js +2511 -0
- package/dist/chunks/supervisor2.js +2 -0
- package/dist/chunks/tasks.js +82 -0
- package/dist/chunks/themes.js +2898 -0
- package/dist/chunks/version.js +2 -0
- package/dist/chunks/version2.js +22 -0
- package/dist/chunks/version3.js +18 -0
- package/dist/chunks/web.js +7 -0
- package/dist/{board-kernel → chunks}/webworkerAll.js +1 -1
- package/dist/runtime/native/pi-extension.js +174 -166
- package/dist/runtime/worker.js +27 -16
- package/package.json +8 -9
- package/dist/about.d.ts +0 -2
- package/dist/about.js +0 -71
- package/dist/app-download.d.ts +0 -11
- package/dist/app-download.js +0 -252
- package/dist/app-ref.d.ts +0 -5
- package/dist/app-ref.js +0 -8
- package/dist/app-target.d.ts +0 -26
- package/dist/app-target.js +0 -55
- package/dist/auth.d.ts +0 -45
- package/dist/auth.js +0 -307
- package/dist/avatar.d.ts +0 -55
- package/dist/avatar.js +0 -104
- package/dist/board-command-support.d.ts +0 -6
- package/dist/board-command-support.js +0 -88
- package/dist/board-export-resources.d.ts +0 -12
- package/dist/board-export-resources.js +0 -51
- package/dist/board-export.d.ts +0 -110
- package/dist/board-export.js +0 -592
- package/dist/board-fonts.d.ts +0 -11
- package/dist/board-fonts.js +0 -10
- package/dist/board-gpu/daemon.d.ts +0 -11
- package/dist/board-gpu/daemon.js +0 -295
- package/dist/board-gpu/index.d.ts +0 -33
- package/dist/board-gpu/index.js +0 -189
- package/dist/board-gpu/protocol.d.ts +0 -77
- package/dist/board-gpu/protocol.js +0 -1
- package/dist/board-kernel.d.ts +0 -5
- package/dist/board-media-export.d.ts +0 -17
- package/dist/board-media-export.js +0 -164
- package/dist/board-media.d.ts +0 -5
- package/dist/board-media.js +0 -66
- package/dist/board-profile.d.ts +0 -21
- package/dist/board-profile.js +0 -67
- package/dist/board-simulate.d.ts +0 -67
- package/dist/board-simulate.js +0 -259
- package/dist/board-time.d.ts +0 -3
- package/dist/board-time.js +0 -34
- package/dist/bootstrap.d.ts +0 -2
- package/dist/client.d.ts +0 -5
- package/dist/client.js +0 -24
- package/dist/command-input.d.ts +0 -4
- package/dist/command-input.js +0 -16
- package/dist/commands/app-commerce.d.ts +0 -2
- package/dist/commands/app-commerce.js +0 -228
- package/dist/commands/app-domains.d.ts +0 -2
- package/dist/commands/app-domains.js +0 -133
- package/dist/commands/apps.d.ts +0 -4
- package/dist/commands/apps.js +0 -827
- package/dist/commands/auth.d.ts +0 -2
- package/dist/commands/auth.js +0 -186
- package/dist/commands/boards/authoring.d.ts +0 -2
- package/dist/commands/boards/authoring.js +0 -166
- package/dist/commands/boards/examples.d.ts +0 -10
- package/dist/commands/boards/examples.js +0 -118
- package/dist/commands/boards.d.ts +0 -13
- package/dist/commands/boards.js +0 -836
- package/dist/commands/channels.d.ts +0 -2
- package/dist/commands/channels.js +0 -74
- package/dist/commands/cron-jobs.d.ts +0 -2
- package/dist/commands/cron-jobs.js +0 -155
- package/dist/commands/decision.d.ts +0 -4
- package/dist/commands/decision.js +0 -113
- package/dist/commands/desktop.d.ts +0 -10
- package/dist/commands/desktop.js +0 -233
- package/dist/commands/feedback.d.ts +0 -2
- package/dist/commands/feedback.js +0 -131
- package/dist/commands/generations.d.ts +0 -2
- package/dist/commands/generations.js +0 -427
- package/dist/commands/host.d.ts +0 -2
- package/dist/commands/host.js +0 -11
- package/dist/commands/me.d.ts +0 -2
- package/dist/commands/me.js +0 -118
- package/dist/commands/models.d.ts +0 -28
- package/dist/commands/models.js +0 -271
- package/dist/commands/profile.d.ts +0 -2
- package/dist/commands/profile.js +0 -81
- package/dist/commands/prompts.d.ts +0 -2
- package/dist/commands/prompts.js +0 -37
- package/dist/commands/public.d.ts +0 -20
- package/dist/commands/public.js +0 -291
- package/dist/commands/references.d.ts +0 -2
- package/dist/commands/references.js +0 -193
- package/dist/commands/referrals.d.ts +0 -2
- package/dist/commands/referrals.js +0 -88
- package/dist/commands/rooms-connect.d.ts +0 -17
- package/dist/commands/rooms-connect.js +0 -140
- package/dist/commands/rooms-rtc-binary.d.ts +0 -2
- package/dist/commands/rooms-rtc-binary.js +0 -107
- package/dist/commands/rooms-rtc.d.ts +0 -21
- package/dist/commands/rooms-rtc.js +0 -171
- package/dist/commands/rooms.d.ts +0 -3
- package/dist/commands/rooms.js +0 -277
- package/dist/commands/run.d.ts +0 -13
- package/dist/commands/run.js +0 -246
- package/dist/commands/runtime.d.ts +0 -3
- package/dist/commands/runtime.js +0 -320
- package/dist/commands/sandboxd-binary.d.ts +0 -11
- package/dist/commands/sandboxd-binary.js +0 -238
- package/dist/commands/search.d.ts +0 -2
- package/dist/commands/search.js +0 -114
- package/dist/commands/session-access.d.ts +0 -2
- package/dist/commands/session-access.js +0 -70
- package/dist/commands/skills.d.ts +0 -2
- package/dist/commands/skills.js +0 -34
- package/dist/commands/space-activity.d.ts +0 -26
- package/dist/commands/space-activity.js +0 -147
- package/dist/commands/space-commerce.d.ts +0 -2
- package/dist/commands/space-commerce.js +0 -514
- package/dist/commands/space-displays.d.ts +0 -2
- package/dist/commands/space-displays.js +0 -620
- package/dist/commands/space-files.d.ts +0 -5
- package/dist/commands/space-files.js +0 -215
- package/dist/commands/space-invitations.d.ts +0 -29
- package/dist/commands/space-invitations.js +0 -189
- package/dist/commands/space-turns.d.ts +0 -49
- package/dist/commands/space-turns.js +0 -205
- package/dist/commands/space-wallet.d.ts +0 -2
- package/dist/commands/space-wallet.js +0 -64
- package/dist/commands/space-webhooks.d.ts +0 -7
- package/dist/commands/space-webhooks.js +0 -73
- package/dist/commands/spaces.d.ts +0 -25
- package/dist/commands/spaces.js +0 -2139
- package/dist/commands/tasks.d.ts +0 -8
- package/dist/commands/tasks.js +0 -80
- package/dist/commands/version.d.ts +0 -2
- package/dist/commands/version.js +0 -21
- package/dist/endpoint-options.d.ts +0 -4
- package/dist/endpoint-options.js +0 -26
- package/dist/env-proxy.d.ts +0 -5
- package/dist/env-proxy.js +0 -20
- package/dist/help-path.d.ts +0 -18
- package/dist/help-path.js +0 -223
- package/dist/host/auth.d.ts +0 -20
- package/dist/host/auth.js +0 -119
- package/dist/host/login-env.d.ts +0 -1
- package/dist/host/login-env.js +0 -31
- package/dist/host/runtime.d.ts +0 -35
- package/dist/host/runtime.js +0 -395
- package/dist/host/runtimes.d.ts +0 -9
- package/dist/host/runtimes.js +0 -42
- package/dist/host/serve.d.ts +0 -2
- package/dist/host/serve.js +0 -117
- package/dist/host/workspaces.d.ts +0 -2
- package/dist/host/workspaces.js +0 -18
- package/dist/http-put.d.ts +0 -25
- package/dist/http-put.js +0 -132
- package/dist/index.d.ts +0 -2
- package/dist/index.js +0 -129
- package/dist/launcher.d.ts +0 -4
- package/dist/launcher.js +0 -38
- package/dist/local-media.d.ts +0 -2
- package/dist/local-media.js +0 -30
- package/dist/network-error.d.ts +0 -3
- package/dist/network-error.js +0 -22
- package/dist/output.d.ts +0 -46
- package/dist/output.js +0 -244
- package/dist/runtime/archive-store.d.ts +0 -54
- package/dist/runtime/archive-store.js +0 -379
- package/dist/runtime/cli-path.d.ts +0 -5
- package/dist/runtime/cli-path.js +0 -27
- package/dist/runtime/codex-usage.d.ts +0 -7
- package/dist/runtime/codex-usage.js +0 -11
- package/dist/runtime/connection.d.ts +0 -42
- package/dist/runtime/connection.js +0 -789
- package/dist/runtime/diagnostics.d.ts +0 -107
- package/dist/runtime/diagnostics.js +0 -392
- package/dist/runtime/harnesses/chained-projection.d.ts +0 -40
- package/dist/runtime/harnesses/chained-projection.js +0 -95
- package/dist/runtime/harnesses/chained-transcript.d.ts +0 -24
- package/dist/runtime/harnesses/chained-transcript.js +0 -62
- package/dist/runtime/harnesses/claude-approval.d.ts +0 -34
- package/dist/runtime/harnesses/claude-approval.js +0 -124
- package/dist/runtime/harnesses/claude-transcript.d.ts +0 -8
- package/dist/runtime/harnesses/claude-transcript.js +0 -138
- package/dist/runtime/harnesses/claude.d.ts +0 -8
- package/dist/runtime/harnesses/claude.js +0 -225
- package/dist/runtime/harnesses/codex-approval.d.ts +0 -25
- package/dist/runtime/harnesses/codex-approval.js +0 -69
- package/dist/runtime/harnesses/codex.d.ts +0 -4
- package/dist/runtime/harnesses/codex.js +0 -269
- package/dist/runtime/harnesses/cursor-transcript.d.ts +0 -37
- package/dist/runtime/harnesses/cursor-transcript.js +0 -183
- package/dist/runtime/harnesses/cursor.d.ts +0 -24
- package/dist/runtime/harnesses/cursor.js +0 -620
- package/dist/runtime/harnesses/index.d.ts +0 -16
- package/dist/runtime/harnesses/index.js +0 -73
- package/dist/runtime/harnesses/pi.d.ts +0 -4
- package/dist/runtime/harnesses/pi.js +0 -247
- package/dist/runtime/harnesses/process.d.ts +0 -31
- package/dist/runtime/harnesses/process.js +0 -75
- package/dist/runtime/harnesses/stream-json.d.ts +0 -48
- package/dist/runtime/harnesses/stream-json.js +0 -336
- package/dist/runtime/harnesses/types.d.ts +0 -117
- package/dist/runtime/harnesses/types.js +0 -1
- package/dist/runtime/harnesses/workbuddy-transcript.d.ts +0 -8
- package/dist/runtime/harnesses/workbuddy-transcript.js +0 -127
- package/dist/runtime/harnesses/workbuddy.d.ts +0 -21
- package/dist/runtime/harnesses/workbuddy.js +0 -123
- package/dist/runtime/instance.d.ts +0 -20
- package/dist/runtime/instance.js +0 -247
- package/dist/runtime/json-rpc.d.ts +0 -53
- package/dist/runtime/json-rpc.js +0 -212
- package/dist/runtime/launch.d.ts +0 -25
- package/dist/runtime/launch.js +0 -247
- package/dist/runtime/local-workspace.d.ts +0 -15
- package/dist/runtime/local-workspace.js +0 -52
- package/dist/runtime/model-catalog.d.ts +0 -12
- package/dist/runtime/model-catalog.js +0 -84
- package/dist/runtime/native/adapters.d.ts +0 -15
- package/dist/runtime/native/adapters.js +0 -11
- package/dist/runtime/native/approvals.d.ts +0 -18
- package/dist/runtime/native/approvals.js +0 -54
- package/dist/runtime/native/archive.d.ts +0 -19
- package/dist/runtime/native/archive.js +0 -142
- package/dist/runtime/native/attach.d.ts +0 -36
- package/dist/runtime/native/attach.js +0 -128
- package/dist/runtime/native/codex-link.d.ts +0 -60
- package/dist/runtime/native/codex-link.js +0 -322
- package/dist/runtime/native/config.d.ts +0 -16
- package/dist/runtime/native/config.js +0 -24
- package/dist/runtime/native/daemon.d.ts +0 -92
- package/dist/runtime/native/daemon.js +0 -380
- package/dist/runtime/native/execution.d.ts +0 -26
- package/dist/runtime/native/execution.js +0 -34
- package/dist/runtime/native/identity.d.ts +0 -9
- package/dist/runtime/native/identity.js +0 -15
- package/dist/runtime/native/ingest.d.ts +0 -263
- package/dist/runtime/native/ingest.js +0 -884
- package/dist/runtime/native/install.d.ts +0 -9
- package/dist/runtime/native/install.js +0 -113
- package/dist/runtime/native/paths.d.ts +0 -2
- package/dist/runtime/native/paths.js +0 -7
- package/dist/runtime/native/pi-extension.d.ts +0 -36
- package/dist/runtime/native/pi-link.d.ts +0 -69
- package/dist/runtime/native/pi-link.js +0 -269
- package/dist/runtime/native/results.d.ts +0 -41
- package/dist/runtime/native/results.js +0 -128
- package/dist/runtime/native/sessions.d.ts +0 -45
- package/dist/runtime/native/sessions.js +0 -87
- package/dist/runtime/native/transcript.d.ts +0 -89
- package/dist/runtime/native/transcript.js +0 -656
- package/dist/runtime/native/translate.d.ts +0 -46
- package/dist/runtime/native/translate.js +0 -299
- package/dist/runtime/native/transport.d.ts +0 -7
- package/dist/runtime/native/transport.js +0 -16
- package/dist/runtime/native/version.d.ts +0 -5
- package/dist/runtime/native/version.js +0 -21
- package/dist/runtime/preferences.d.ts +0 -7
- package/dist/runtime/preferences.js +0 -22
- package/dist/runtime/presentation.d.ts +0 -32
- package/dist/runtime/presentation.js +0 -124
- package/dist/runtime/process-group.d.ts +0 -5
- package/dist/runtime/process-group.js +0 -161
- package/dist/runtime/projection-store.d.ts +0 -27
- package/dist/runtime/projection-store.js +0 -30
- package/dist/runtime/space-binding.d.ts +0 -48
- package/dist/runtime/space-binding.js +0 -342
- package/dist/runtime/supervisor.d.ts +0 -19
- package/dist/runtime/supervisor.js +0 -441
- package/dist/runtime/turn-projection.d.ts +0 -41
- package/dist/runtime/turn-projection.js +0 -120
- package/dist/runtime/worker.d.ts +0 -1
- package/dist/safe-remote-image.d.ts +0 -36
- package/dist/safe-remote-image.js +0 -191
- package/dist/self-update.d.ts +0 -7
- package/dist/self-update.js +0 -202
- package/dist/session-status.d.ts +0 -6
- package/dist/session-status.js +0 -16
- package/dist/space-files/limit.d.ts +0 -2
- package/dist/space-files/limit.js +0 -16
- package/dist/space-files/operands.d.ts +0 -17
- package/dist/space-files/operands.js +0 -33
- package/dist/space-files/transfer.d.ts +0 -53
- package/dist/space-files/transfer.js +0 -297
- package/dist/space-files/upload.d.ts +0 -17
- package/dist/space-files/upload.js +0 -76
- package/dist/space.d.ts +0 -44
- package/dist/space.js +0 -192
- package/dist/version.d.ts +0 -2
- package/dist/version.js +0 -17
- package/dist/web.d.ts +0 -1
- package/dist/web.js +0 -4
- /package/dist/{board-kernel → chunks}/lexer.js +0 -0
|
@@ -0,0 +1,2216 @@
|
|
|
1
|
+
import { _ as union, a as array, h as string, n as _enum, p as object, s as boolean } from "./schemas.js";
|
|
2
|
+
import { a as resolveApiBaseUrl, n as decodeJwtPayload } from "./environment.js";
|
|
3
|
+
//#region ../protocol/src/realtime/types.ts
|
|
4
|
+
const WS_COMPACT_STREAM_CAPABILITY = "session.compact_stream.v1";
|
|
5
|
+
const WS_ROOM_SUBSCRIPTION_CAPABILITY = "realtime.rooms.v1";
|
|
6
|
+
const WS_BOARD_AWARENESS_CAPABILITY = "board.awareness.v1";
|
|
7
|
+
const WS_REALTIME_ROOM_CAPABILITY = "realtime.room.v1";
|
|
8
|
+
const WS_REALTIME_ROOM_HISTORY_CAPABILITY = "realtime.room.history.v1";
|
|
9
|
+
const REALTIME_DOMAINS = [
|
|
10
|
+
"system",
|
|
11
|
+
"session",
|
|
12
|
+
"space",
|
|
13
|
+
"label",
|
|
14
|
+
"room",
|
|
15
|
+
"ui",
|
|
16
|
+
"desktop"
|
|
17
|
+
];
|
|
18
|
+
const isRealtimeDomain = (value) => typeof value === "string" && REALTIME_DOMAINS.some((domain) => domain === value);
|
|
19
|
+
/** Accepted room event names. Shared so a client can reject one before sending. */
|
|
20
|
+
const REALTIME_ROOM_EVENT_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/;
|
|
21
|
+
const getRealtimeSpaceRoom = (spaceId) => `space:${spaceId}`;
|
|
22
|
+
const getRealtimeBoardRoom = (boardId) => `board:${boardId}`;
|
|
23
|
+
const parseRealtimeRoom = (room) => {
|
|
24
|
+
const trimmed = room.trim();
|
|
25
|
+
const separatorIndex = trimmed.indexOf(":");
|
|
26
|
+
if (separatorIndex <= 0) return null;
|
|
27
|
+
const kind = trimmed.slice(0, separatorIndex);
|
|
28
|
+
const id = trimmed.slice(separatorIndex + 1).trim();
|
|
29
|
+
if (!id) return null;
|
|
30
|
+
if (kind !== "space" && kind !== "user" && kind !== "board" && kind !== "room") return null;
|
|
31
|
+
return {
|
|
32
|
+
kind,
|
|
33
|
+
id
|
|
34
|
+
};
|
|
35
|
+
};
|
|
36
|
+
const normalizeRealtimeRooms = (rooms) => {
|
|
37
|
+
const normalized = /* @__PURE__ */ new Set();
|
|
38
|
+
for (const room of rooms) {
|
|
39
|
+
const parsed = typeof room === "string" ? parseRealtimeRoom(room) : null;
|
|
40
|
+
if (!parsed) continue;
|
|
41
|
+
normalized.add(`${parsed.kind}:${parsed.id}`);
|
|
42
|
+
}
|
|
43
|
+
return [...normalized];
|
|
44
|
+
};
|
|
45
|
+
const getNonEmptyString = (value) => typeof value === "string" && value.trim() ? value : null;
|
|
46
|
+
const getSessionTurnPatchStreamKey = (input, options = {}) => {
|
|
47
|
+
const turnId = getNonEmptyString(input.turnId);
|
|
48
|
+
const messageKey = getNonEmptyString(input.messageId) ?? getNonEmptyString(input.sourceMessageId) ?? getNonEmptyString(input.anchorUserMessageId) ?? (typeof input.messageOrdinal === "number" && Number.isFinite(input.messageOrdinal) ? `ordinal:${input.messageOrdinal}` : null);
|
|
49
|
+
if (turnId && messageKey) return `${turnId}:${messageKey}`;
|
|
50
|
+
const streamKey = messageKey ?? turnId;
|
|
51
|
+
if (streamKey) return streamKey;
|
|
52
|
+
return options.includeSessionFallback ? getNonEmptyString(input.sessionId) : null;
|
|
53
|
+
};
|
|
54
|
+
//#endregion
|
|
55
|
+
//#region ../protocol/src/identifiers.ts
|
|
56
|
+
const UUID_SHAPE_PATTERN = "[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}";
|
|
57
|
+
const UUID_PATTERN = "[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}";
|
|
58
|
+
const UUID_OR_SHORT_UUID_PATTERN = `^(?:${UUID_PATTERN}|[0-9a-fA-F]{32})$`;
|
|
59
|
+
const UUID_SHAPE_REGEX = new RegExp(`^${UUID_SHAPE_PATTERN}$`);
|
|
60
|
+
new RegExp(`^${UUID_PATTERN}$`);
|
|
61
|
+
new RegExp(UUID_OR_SHORT_UUID_PATTERN);
|
|
62
|
+
function isUuidLike(value) {
|
|
63
|
+
return typeof value === "string" && UUID_SHAPE_REGEX.test(value);
|
|
64
|
+
}
|
|
65
|
+
//#endregion
|
|
66
|
+
//#region ../protocol/src/provenance.ts
|
|
67
|
+
/** Request provenance via X-Cohub-Source-* headers. Never used for authorization. */
|
|
68
|
+
const COHUB_SOURCE_HEADER = {
|
|
69
|
+
space: "X-Cohub-Source-Space",
|
|
70
|
+
session: "X-Cohub-Source-Session",
|
|
71
|
+
turn: "X-Cohub-Source-Turn",
|
|
72
|
+
toolCall: "X-Cohub-Source-Tool-Call",
|
|
73
|
+
client: "X-Cohub-Source-Client",
|
|
74
|
+
sandboxVersion: "X-Cohub-Source-Sandbox",
|
|
75
|
+
via: "X-Cohub-Source-Via"
|
|
76
|
+
};
|
|
77
|
+
const isRequestSourceUuid = (value) => isUuidLike(value);
|
|
78
|
+
/** Opaque, url-safe client instance id. */
|
|
79
|
+
const CLIENT_ID_RE = /^[A-Za-z0-9_-]{8,64}$/;
|
|
80
|
+
const isRequestSourceClientId = (value) => typeof value === "string" && CLIENT_ID_RE.test(value);
|
|
81
|
+
/** Remove C0 controls and DEL without a control-char regex (biome-friendly). */
|
|
82
|
+
const stripControlChars = (value) => {
|
|
83
|
+
let out = "";
|
|
84
|
+
for (let i = 0; i < value.length; i += 1) {
|
|
85
|
+
const code = value.charCodeAt(i);
|
|
86
|
+
if (code >= 32 && code !== 127) out += value[i];
|
|
87
|
+
}
|
|
88
|
+
return out;
|
|
89
|
+
};
|
|
90
|
+
const asNonEmpty = (value) => {
|
|
91
|
+
if (typeof value !== "string") return void 0;
|
|
92
|
+
const trimmed = stripControlChars(value).trim();
|
|
93
|
+
return trimmed.length > 0 ? trimmed : void 0;
|
|
94
|
+
};
|
|
95
|
+
const asUuid = (value) => {
|
|
96
|
+
const trimmed = asNonEmpty(value);
|
|
97
|
+
return trimmed && isRequestSourceUuid(trimmed) ? trimmed : void 0;
|
|
98
|
+
};
|
|
99
|
+
const asVia = (value) => {
|
|
100
|
+
const cleaned = asNonEmpty(value);
|
|
101
|
+
if (!cleaned) return void 0;
|
|
102
|
+
return cleaned.slice(0, 64);
|
|
103
|
+
};
|
|
104
|
+
const asClientId = (value) => {
|
|
105
|
+
const cleaned = asNonEmpty(value);
|
|
106
|
+
return cleaned && isRequestSourceClientId(cleaned) ? cleaned : void 0;
|
|
107
|
+
};
|
|
108
|
+
const asSandboxVersion = (value) => asNonEmpty(value)?.slice(0, 128);
|
|
109
|
+
const isRequestSourceEmpty = (source) => {
|
|
110
|
+
if (!source) return true;
|
|
111
|
+
return !source.spaceId && !source.sessionId && !source.turnId && !source.toolCallId && !source.clientId && !source.sandboxVersion && !source.via;
|
|
112
|
+
};
|
|
113
|
+
/** Drop invalid UUIDs; via-only is valid. */
|
|
114
|
+
const normalizeRequestSource = (input) => {
|
|
115
|
+
if (!input || typeof input !== "object" || Array.isArray(input)) return null;
|
|
116
|
+
const record = input;
|
|
117
|
+
const spaceId = asUuid(record.spaceId);
|
|
118
|
+
const sessionId = asUuid(record.sessionId);
|
|
119
|
+
const turnId = asUuid(record.turnId);
|
|
120
|
+
const toolCallId = asNonEmpty(record.toolCallId);
|
|
121
|
+
const validToolCallId = toolCallId && toolCallId.length <= 255 ? toolCallId : void 0;
|
|
122
|
+
const clientId = asClientId(record.clientId);
|
|
123
|
+
const sandboxVersion = asSandboxVersion(record.sandboxVersion);
|
|
124
|
+
const via = asVia(record.via);
|
|
125
|
+
const source = {
|
|
126
|
+
...spaceId ? { spaceId } : {},
|
|
127
|
+
...sessionId ? { sessionId } : {},
|
|
128
|
+
...turnId ? { turnId } : {},
|
|
129
|
+
...validToolCallId ? { toolCallId: validToolCallId } : {},
|
|
130
|
+
...clientId ? { clientId } : {},
|
|
131
|
+
...sandboxVersion ? { sandboxVersion } : {},
|
|
132
|
+
...via ? { via } : {}
|
|
133
|
+
};
|
|
134
|
+
return isRequestSourceEmpty(source) ? null : source;
|
|
135
|
+
};
|
|
136
|
+
const requestSourceToHeaders = (source) => {
|
|
137
|
+
const normalized = normalizeRequestSource(source);
|
|
138
|
+
if (!normalized) return {};
|
|
139
|
+
const headers = {};
|
|
140
|
+
if (normalized.spaceId) headers[COHUB_SOURCE_HEADER.space] = normalized.spaceId;
|
|
141
|
+
if (normalized.sessionId) headers[COHUB_SOURCE_HEADER.session] = normalized.sessionId;
|
|
142
|
+
if (normalized.turnId) headers[COHUB_SOURCE_HEADER.turn] = normalized.turnId;
|
|
143
|
+
if (normalized.toolCallId) headers[COHUB_SOURCE_HEADER.toolCall] = normalized.toolCallId;
|
|
144
|
+
if (normalized.clientId) headers[COHUB_SOURCE_HEADER.client] = normalized.clientId;
|
|
145
|
+
if (normalized.sandboxVersion) headers[COHUB_SOURCE_HEADER.sandboxVersion] = normalized.sandboxVersion;
|
|
146
|
+
if (normalized.via) headers[COHUB_SOURCE_HEADER.via] = normalized.via;
|
|
147
|
+
return headers;
|
|
148
|
+
};
|
|
149
|
+
/** Read COHUB_* env into a RequestSource. */
|
|
150
|
+
const readRequestSourceFromEnv = (env = {}, defaults) => normalizeRequestSource({
|
|
151
|
+
spaceId: env.COHUB_SPACE_ID,
|
|
152
|
+
sessionId: env.COHUB_SESSION_ID,
|
|
153
|
+
turnId: env.COHUB_TURN_ID,
|
|
154
|
+
toolCallId: env.COHUB_TOOL_CALL_ID,
|
|
155
|
+
clientId: env.COHUB_SOURCE_CLIENT_ID,
|
|
156
|
+
sandboxVersion: asNonEmpty(env.COHUB_SANDBOX_VERSION) ?? env.IMAGE_VERSION,
|
|
157
|
+
via: env.COHUB_SOURCE_VIA ?? defaults?.via
|
|
158
|
+
});
|
|
159
|
+
Object.values(COHUB_SOURCE_HEADER);
|
|
160
|
+
//#endregion
|
|
161
|
+
//#region ../sdk/src/revalidation-cache.ts
|
|
162
|
+
const MAX_ENTRY_CHARS = 262144;
|
|
163
|
+
const MAX_TOTAL_CHARS = 8388608;
|
|
164
|
+
const entries = /* @__PURE__ */ new Map();
|
|
165
|
+
let totalChars = 0;
|
|
166
|
+
const runtime = globalThis;
|
|
167
|
+
const revalidationEnabled = runtime.window === void 0 && Boolean(runtime.process?.versions?.node);
|
|
168
|
+
function remove(key) {
|
|
169
|
+
const entry = entries.get(key);
|
|
170
|
+
if (!entry) return;
|
|
171
|
+
entries.delete(key);
|
|
172
|
+
totalChars -= entry.body.length;
|
|
173
|
+
}
|
|
174
|
+
function readRevalidationEntry(key) {
|
|
175
|
+
const entry = entries.get(key);
|
|
176
|
+
if (!entry) return void 0;
|
|
177
|
+
entries.delete(key);
|
|
178
|
+
entries.set(key, entry);
|
|
179
|
+
return entry;
|
|
180
|
+
}
|
|
181
|
+
function writeRevalidationEntry(key, etag, body) {
|
|
182
|
+
remove(key);
|
|
183
|
+
if (!etag || body.length > MAX_ENTRY_CHARS) return;
|
|
184
|
+
entries.set(key, {
|
|
185
|
+
etag,
|
|
186
|
+
body
|
|
187
|
+
});
|
|
188
|
+
totalChars += body.length;
|
|
189
|
+
for (const oldest of entries.keys()) {
|
|
190
|
+
if (totalChars <= MAX_TOTAL_CHARS) break;
|
|
191
|
+
remove(oldest);
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
//#endregion
|
|
195
|
+
//#region ../sdk/src/transport.ts
|
|
196
|
+
const responseBodyForError = async (response) => {
|
|
197
|
+
return (response.headers.get("content-type") ?? "").includes("application/json") ? await response.json().catch(() => null) : await response.text().catch(() => response.statusText);
|
|
198
|
+
};
|
|
199
|
+
const isFailure = (response) => !response.ok && response.status !== 304;
|
|
200
|
+
const messageFromErrorBody = (body, fallback) => {
|
|
201
|
+
if (typeof body === "string") return body.trim() || fallback;
|
|
202
|
+
if (body && typeof body === "object") {
|
|
203
|
+
const errorBody = body;
|
|
204
|
+
if (typeof errorBody.message === "string" && errorBody.message.trim()) return errorBody.message;
|
|
205
|
+
}
|
|
206
|
+
return fallback;
|
|
207
|
+
};
|
|
208
|
+
function errorCodeFromBody(body) {
|
|
209
|
+
if (!body || typeof body !== "object") return null;
|
|
210
|
+
const errorBody = body;
|
|
211
|
+
if (typeof errorBody.code === "string" && errorBody.code.trim()) return errorBody.code;
|
|
212
|
+
return null;
|
|
213
|
+
}
|
|
214
|
+
function cleanTraceHeader(value) {
|
|
215
|
+
if (!value) return null;
|
|
216
|
+
const cleaned = value.replace(/[\r\n\t\0]/g, "").trim();
|
|
217
|
+
return cleaned ? cleaned.slice(0, 256) : null;
|
|
218
|
+
}
|
|
219
|
+
function traceContextFromResponse(response) {
|
|
220
|
+
return {
|
|
221
|
+
requestId: cleanTraceHeader(response.headers.get("x-request-id")),
|
|
222
|
+
traceId: cleanTraceHeader(response.headers.get("x-trace-id")),
|
|
223
|
+
spanId: cleanTraceHeader(response.headers.get("x-span-id")),
|
|
224
|
+
traceparent: cleanTraceHeader(response.headers.get("traceparent"))
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
/**
|
|
228
|
+
* Access tokens must be a single HTTP header token.
|
|
229
|
+
* Newlines / control chars (from corrupted storage or clipboard paste) make
|
|
230
|
+
* `Headers#set` throw TypeError — Safari: "The string did not match the expected pattern."
|
|
231
|
+
*/
|
|
232
|
+
function sanitizeAccessToken(token) {
|
|
233
|
+
if (typeof token !== "string") return null;
|
|
234
|
+
const cleaned = token.replace(/[\r\n\t\0]/g, "").trim();
|
|
235
|
+
return cleaned.length > 0 ? cleaned : null;
|
|
236
|
+
}
|
|
237
|
+
/** Join API base + path without double slashes; prefer URL when base is absolute. */
|
|
238
|
+
function joinApiUrl(baseUrl, path) {
|
|
239
|
+
const base = baseUrl.trim().replace(/\/+$/, "");
|
|
240
|
+
const normalizedPath = path.startsWith("/") ? path : `/${path}`;
|
|
241
|
+
if (!base) return normalizedPath;
|
|
242
|
+
if (/^https?:\/\//i.test(base)) try {
|
|
243
|
+
return new URL(`.${normalizedPath}`, `${base}/`).href;
|
|
244
|
+
} catch {}
|
|
245
|
+
return `${base}${normalizedPath}`;
|
|
246
|
+
}
|
|
247
|
+
function isBrowserRequestConstructionError(error) {
|
|
248
|
+
if (!(error instanceof TypeError)) return false;
|
|
249
|
+
const message = error.message || "";
|
|
250
|
+
return message === "The string did not match the expected pattern." || /invalid header value|Failed to construct|is an invalid header/i.test(message);
|
|
251
|
+
}
|
|
252
|
+
var HttpError = class extends Error {
|
|
253
|
+
status;
|
|
254
|
+
body;
|
|
255
|
+
code;
|
|
256
|
+
/** The configured unauthorized callback already handled this 401. */
|
|
257
|
+
unauthorizedHandled;
|
|
258
|
+
/** Auth state observed before the rejected request resolved its token. */
|
|
259
|
+
authSessionVersion;
|
|
260
|
+
/** Safe identifiers returned by the rejected API response. */
|
|
261
|
+
traceContext;
|
|
262
|
+
constructor(message, status, body, options) {
|
|
263
|
+
super(message);
|
|
264
|
+
this.name = "HttpError";
|
|
265
|
+
this.status = status;
|
|
266
|
+
this.body = body;
|
|
267
|
+
this.code = errorCodeFromBody(body);
|
|
268
|
+
this.unauthorizedHandled = Boolean(options?.unauthorizedHandled);
|
|
269
|
+
this.authSessionVersion = options?.authSessionVersion;
|
|
270
|
+
this.traceContext = options?.traceContext;
|
|
271
|
+
}
|
|
272
|
+
};
|
|
273
|
+
const rejectedTokenByError = /* @__PURE__ */ new WeakMap();
|
|
274
|
+
var HttpTransport = class {
|
|
275
|
+
baseUrl;
|
|
276
|
+
fetcher;
|
|
277
|
+
getAccessToken;
|
|
278
|
+
getAuthSessionVersion;
|
|
279
|
+
onUnauthorized;
|
|
280
|
+
requestSource;
|
|
281
|
+
scopedToken = null;
|
|
282
|
+
refreshInFlight = null;
|
|
283
|
+
constructor(options = {}) {
|
|
284
|
+
this.baseUrl = resolveApiBaseUrl(options);
|
|
285
|
+
this.fetcher = options.fetch ?? fetch;
|
|
286
|
+
this.getAccessToken = options.getAccessToken;
|
|
287
|
+
this.getAuthSessionVersion = options.getAuthSessionVersion;
|
|
288
|
+
this.onUnauthorized = options.onUnauthorized;
|
|
289
|
+
this.requestSource = options.requestSource;
|
|
290
|
+
}
|
|
291
|
+
async credential() {
|
|
292
|
+
return sanitizeAccessToken(this.getAccessToken ? await this.getAccessToken() : null);
|
|
293
|
+
}
|
|
294
|
+
async cacheScope() {
|
|
295
|
+
let token;
|
|
296
|
+
try {
|
|
297
|
+
token = await this.credential();
|
|
298
|
+
} catch {
|
|
299
|
+
return null;
|
|
300
|
+
}
|
|
301
|
+
if (!token) return "anonymous";
|
|
302
|
+
if (this.scopedToken?.token !== token) {
|
|
303
|
+
const uuid = decodeJwtPayload(token)?.talesofai_uuid;
|
|
304
|
+
this.scopedToken = {
|
|
305
|
+
token,
|
|
306
|
+
scope: typeof uuid === "string" && uuid ? `user:${uuid}` : null
|
|
307
|
+
};
|
|
308
|
+
}
|
|
309
|
+
return this.scopedToken.scope;
|
|
310
|
+
}
|
|
311
|
+
resolveRequestSource() {
|
|
312
|
+
if (!this.requestSource) return null;
|
|
313
|
+
if (typeof this.requestSource === "function") return this.requestSource() ?? null;
|
|
314
|
+
return this.requestSource;
|
|
315
|
+
}
|
|
316
|
+
applyRequestSourceHeaders(headers) {
|
|
317
|
+
const sourceHeaders = requestSourceToHeaders(this.resolveRequestSource());
|
|
318
|
+
for (const [name, value] of Object.entries(sourceHeaders)) if (!headers.has(name)) headers.set(name, value);
|
|
319
|
+
}
|
|
320
|
+
readAuthSessionVersion() {
|
|
321
|
+
try {
|
|
322
|
+
return this.getAuthSessionVersion?.();
|
|
323
|
+
} catch {
|
|
324
|
+
return;
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
async withAuthorization(init, tokenOverride) {
|
|
328
|
+
const { fetch: _fetch, skipUnauthorizedHandler: _skip, accessToken, ...requestInit } = init ?? {};
|
|
329
|
+
const headers = new Headers(requestInit.headers);
|
|
330
|
+
let authSessionVersion = this.readAuthSessionVersion();
|
|
331
|
+
const pinned = tokenOverride !== void 0 ? tokenOverride : accessToken;
|
|
332
|
+
const token = sanitizeAccessToken(pinned !== void 0 ? pinned : this.getAccessToken ? await this.getAccessToken() : null);
|
|
333
|
+
if (token) {
|
|
334
|
+
const resolvedVersion = this.readAuthSessionVersion();
|
|
335
|
+
if (resolvedVersion !== void 0) authSessionVersion = resolvedVersion;
|
|
336
|
+
}
|
|
337
|
+
if (token) headers.set("Authorization", `Bearer ${token}`);
|
|
338
|
+
else headers.delete("Authorization");
|
|
339
|
+
this.applyRequestSourceHeaders(headers);
|
|
340
|
+
return {
|
|
341
|
+
requestInit: {
|
|
342
|
+
...requestInit,
|
|
343
|
+
headers
|
|
344
|
+
},
|
|
345
|
+
token,
|
|
346
|
+
authSessionVersion
|
|
347
|
+
};
|
|
348
|
+
}
|
|
349
|
+
async refreshAccessToken(rejectedToken) {
|
|
350
|
+
if (!this.getAccessToken) return null;
|
|
351
|
+
const inFlight = this.refreshInFlight;
|
|
352
|
+
if (inFlight) {
|
|
353
|
+
const resolved = await inFlight.promise;
|
|
354
|
+
if (inFlight.rejectedToken === rejectedToken) return resolved;
|
|
355
|
+
return this.refreshAccessToken(rejectedToken);
|
|
356
|
+
}
|
|
357
|
+
const getAccessToken = this.getAccessToken;
|
|
358
|
+
const task = (async () => {
|
|
359
|
+
try {
|
|
360
|
+
const currentToken = sanitizeAccessToken(await getAccessToken());
|
|
361
|
+
if (currentToken && currentToken !== rejectedToken) return currentToken;
|
|
362
|
+
} catch {}
|
|
363
|
+
try {
|
|
364
|
+
return sanitizeAccessToken(await getAccessToken({
|
|
365
|
+
forceRefresh: true,
|
|
366
|
+
rejectedToken
|
|
367
|
+
}));
|
|
368
|
+
} catch {
|
|
369
|
+
return null;
|
|
370
|
+
}
|
|
371
|
+
})();
|
|
372
|
+
const entry = {
|
|
373
|
+
rejectedToken,
|
|
374
|
+
promise: task
|
|
375
|
+
};
|
|
376
|
+
this.refreshInFlight = entry;
|
|
377
|
+
try {
|
|
378
|
+
return await task;
|
|
379
|
+
} finally {
|
|
380
|
+
if (this.refreshInFlight === entry) this.refreshInFlight = null;
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
async send(path, init) {
|
|
384
|
+
const fetcher = init?.fetch ?? this.fetcher;
|
|
385
|
+
const url = joinApiUrl(this.baseUrl, path);
|
|
386
|
+
const pinned = init?.accessToken !== void 0;
|
|
387
|
+
const skipUnauthorizedHandler = Boolean(init?.skipUnauthorizedHandler) || pinned;
|
|
388
|
+
let response;
|
|
389
|
+
let rejectedToken = null;
|
|
390
|
+
let rejectedAuthSessionVersion;
|
|
391
|
+
try {
|
|
392
|
+
const authorized = await this.withAuthorization(init);
|
|
393
|
+
rejectedToken = authorized.token;
|
|
394
|
+
rejectedAuthSessionVersion = authorized.authSessionVersion;
|
|
395
|
+
response = await fetcher(url, authorized.requestInit);
|
|
396
|
+
} catch (error) {
|
|
397
|
+
if (isBrowserRequestConstructionError(error)) throw new Error("Could not send request. Your session may be invalid — try refreshing or signing in again.", { cause: error });
|
|
398
|
+
throw error;
|
|
399
|
+
}
|
|
400
|
+
if (response.status === 401 && this.getAccessToken && !pinned) {
|
|
401
|
+
const refreshedToken = await this.refreshAccessToken(rejectedToken);
|
|
402
|
+
if (refreshedToken) {
|
|
403
|
+
let retryResponse;
|
|
404
|
+
try {
|
|
405
|
+
const authorizedRetry = await this.withAuthorization(init, refreshedToken);
|
|
406
|
+
rejectedToken = authorizedRetry.token;
|
|
407
|
+
rejectedAuthSessionVersion = authorizedRetry.authSessionVersion;
|
|
408
|
+
retryResponse = await fetcher(url, authorizedRetry.requestInit);
|
|
409
|
+
} catch (error) {
|
|
410
|
+
if (isBrowserRequestConstructionError(error)) throw new Error("Could not send request. Your session may be invalid — try refreshing or signing in again.", { cause: error });
|
|
411
|
+
throw error;
|
|
412
|
+
}
|
|
413
|
+
if (retryResponse.status !== 401) {
|
|
414
|
+
if (isFailure(retryResponse)) {
|
|
415
|
+
const body = await responseBodyForError(retryResponse);
|
|
416
|
+
throw new HttpError(messageFromErrorBody(body, retryResponse.statusText), retryResponse.status, body);
|
|
417
|
+
}
|
|
418
|
+
return retryResponse;
|
|
419
|
+
}
|
|
420
|
+
response = retryResponse;
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
if (response.status === 401) {
|
|
424
|
+
const traceContext = traceContextFromResponse(response);
|
|
425
|
+
let unauthorizedHandled = false;
|
|
426
|
+
if (!skipUnauthorizedHandler && this.onUnauthorized) {
|
|
427
|
+
await this.onUnauthorized({
|
|
428
|
+
matchesRejectedToken: (candidate) => sanitizeAccessToken(candidate) === rejectedToken,
|
|
429
|
+
authSessionVersion: rejectedAuthSessionVersion,
|
|
430
|
+
traceContext
|
|
431
|
+
});
|
|
432
|
+
unauthorizedHandled = true;
|
|
433
|
+
}
|
|
434
|
+
const error = new HttpError("unauthorized", 401, null, {
|
|
435
|
+
unauthorizedHandled,
|
|
436
|
+
authSessionVersion: rejectedAuthSessionVersion,
|
|
437
|
+
traceContext
|
|
438
|
+
});
|
|
439
|
+
rejectedTokenByError.set(error, rejectedToken);
|
|
440
|
+
throw error;
|
|
441
|
+
}
|
|
442
|
+
if (isFailure(response)) {
|
|
443
|
+
const body = await responseBodyForError(response);
|
|
444
|
+
throw new HttpError(messageFromErrorBody(body, response.statusText), response.status, body);
|
|
445
|
+
}
|
|
446
|
+
return response;
|
|
447
|
+
}
|
|
448
|
+
async request(path, init) {
|
|
449
|
+
const response = await this.send(path, init);
|
|
450
|
+
if (response.status === 204) return null;
|
|
451
|
+
return response.json();
|
|
452
|
+
}
|
|
453
|
+
async requestRevalidated(path, init) {
|
|
454
|
+
if (!revalidationEnabled) return this.request(path, init);
|
|
455
|
+
const key = joinApiUrl(this.baseUrl, path);
|
|
456
|
+
const cached = readRevalidationEntry(key);
|
|
457
|
+
const headers = new Headers(init?.headers);
|
|
458
|
+
if (cached) headers.set("If-None-Match", cached.etag);
|
|
459
|
+
const response = await this.send(path, {
|
|
460
|
+
...init,
|
|
461
|
+
headers
|
|
462
|
+
});
|
|
463
|
+
if (response.status === 304 && cached) return JSON.parse(cached.body);
|
|
464
|
+
const body = await response.text();
|
|
465
|
+
writeRevalidationEntry(key, response.headers.get("etag"), body);
|
|
466
|
+
return JSON.parse(body);
|
|
467
|
+
}
|
|
468
|
+
async raw(path, init) {
|
|
469
|
+
const response = await this.send(path, init);
|
|
470
|
+
return {
|
|
471
|
+
response,
|
|
472
|
+
blob: () => response.blob(),
|
|
473
|
+
arrayBuffer: () => response.arrayBuffer(),
|
|
474
|
+
text: () => response.text(),
|
|
475
|
+
json: () => response.json()
|
|
476
|
+
};
|
|
477
|
+
}
|
|
478
|
+
async blob(path, init) {
|
|
479
|
+
return (await this.raw(path, init)).blob();
|
|
480
|
+
}
|
|
481
|
+
};
|
|
482
|
+
//#endregion
|
|
483
|
+
//#region ../sdk/src/rtc/index.ts
|
|
484
|
+
const ICE_REFRESH_MARGIN_MS = 3e5;
|
|
485
|
+
var IceServerCache = class {
|
|
486
|
+
load;
|
|
487
|
+
cached = null;
|
|
488
|
+
constructor(load) {
|
|
489
|
+
this.load = load;
|
|
490
|
+
}
|
|
491
|
+
async get(signal) {
|
|
492
|
+
if (this.cached && this.cached.refreshAt > Date.now()) return this.cached.value;
|
|
493
|
+
const value = await this.load(signal);
|
|
494
|
+
this.cached = {
|
|
495
|
+
value,
|
|
496
|
+
refreshAt: Date.parse(value.expiresAt) - ICE_REFRESH_MARGIN_MS
|
|
497
|
+
};
|
|
498
|
+
return value;
|
|
499
|
+
}
|
|
500
|
+
};
|
|
501
|
+
function waitForIceGathering(pc, timeoutMs, signal) {
|
|
502
|
+
if (pc.iceGatheringState === "complete") return Promise.resolve();
|
|
503
|
+
if (signal?.aborted) return Promise.reject(signal.reason ?? new DOMException("Aborted", "AbortError"));
|
|
504
|
+
return new Promise((resolve, reject) => {
|
|
505
|
+
const cleanup = () => {
|
|
506
|
+
clearTimeout(timer);
|
|
507
|
+
pc.removeEventListener("icegatheringstatechange", check);
|
|
508
|
+
signal?.removeEventListener("abort", abort);
|
|
509
|
+
};
|
|
510
|
+
const done = () => {
|
|
511
|
+
cleanup();
|
|
512
|
+
resolve();
|
|
513
|
+
};
|
|
514
|
+
const check = () => {
|
|
515
|
+
if (pc.iceGatheringState === "complete") done();
|
|
516
|
+
};
|
|
517
|
+
const abort = () => {
|
|
518
|
+
cleanup();
|
|
519
|
+
reject(signal?.reason ?? new DOMException("Aborted", "AbortError"));
|
|
520
|
+
};
|
|
521
|
+
const timer = setTimeout(done, timeoutMs);
|
|
522
|
+
pc.addEventListener("icegatheringstatechange", check);
|
|
523
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
524
|
+
});
|
|
525
|
+
}
|
|
526
|
+
const statNumber = (value) => typeof value === "number" && Number.isFinite(value) ? value : null;
|
|
527
|
+
function readRtcTransportStats(report) {
|
|
528
|
+
const stats = {
|
|
529
|
+
path: null,
|
|
530
|
+
relayProtocol: null,
|
|
531
|
+
rttMs: null
|
|
532
|
+
};
|
|
533
|
+
report.forEach((entry) => {
|
|
534
|
+
if (entry.type !== "candidate-pair" || !entry.nominated || entry.state !== "succeeded") return;
|
|
535
|
+
const local = report.get(String(entry.localCandidateId));
|
|
536
|
+
const remote = report.get(String(entry.remoteCandidateId));
|
|
537
|
+
stats.path = local?.candidateType === "relay" || remote?.candidateType === "relay" ? "relay" : "direct";
|
|
538
|
+
if (local?.candidateType === "relay" && typeof local.relayProtocol === "string") stats.relayProtocol = local.relayProtocol;
|
|
539
|
+
const rtt = statNumber(entry.currentRoundTripTime);
|
|
540
|
+
if (rtt !== null) stats.rttMs = Math.round(rtt * 1e3);
|
|
541
|
+
});
|
|
542
|
+
return stats;
|
|
543
|
+
}
|
|
544
|
+
object({
|
|
545
|
+
urls: union([string().min(1).max(512), array(string().min(1).max(512)).min(1).max(16)]),
|
|
546
|
+
username: string().max(512).optional(),
|
|
547
|
+
credential: string().max(512).optional()
|
|
548
|
+
});
|
|
549
|
+
const sessionDescriptionSchema = object({
|
|
550
|
+
type: _enum(["offer", "answer"]),
|
|
551
|
+
sdp: string().min(1).max(65536)
|
|
552
|
+
});
|
|
553
|
+
const APP_RTC_DELIVERIES = ["reliable", "latest"];
|
|
554
|
+
const APP_RTC_PUBLICATION_KINDS = [
|
|
555
|
+
"data",
|
|
556
|
+
"audio",
|
|
557
|
+
"video"
|
|
558
|
+
];
|
|
559
|
+
const APP_RTC_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/;
|
|
560
|
+
const isAppRtcName = (value) => typeof value === "string" && APP_RTC_NAME_PATTERN.test(value) && !value.toLowerCase().startsWith("cohub.");
|
|
561
|
+
const APP_RTC_LIMITS = {
|
|
562
|
+
channelsPerMember: 16,
|
|
563
|
+
tracksPerMember: 4,
|
|
564
|
+
dataSubscriptions: 512,
|
|
565
|
+
mediaSubscriptions: 16,
|
|
566
|
+
messageBytes: 65536,
|
|
567
|
+
operationsPerSecond: 10,
|
|
568
|
+
opensPerSecond: 2,
|
|
569
|
+
batch: 64
|
|
570
|
+
};
|
|
571
|
+
const APP_RTC_QUALITIES = [
|
|
572
|
+
"high",
|
|
573
|
+
"medium",
|
|
574
|
+
"low"
|
|
575
|
+
];
|
|
576
|
+
const APP_RTC_SIMULCAST_LAYERS = [
|
|
577
|
+
{
|
|
578
|
+
rid: "f",
|
|
579
|
+
quality: "high",
|
|
580
|
+
scaleResolutionDownBy: 1
|
|
581
|
+
},
|
|
582
|
+
{
|
|
583
|
+
rid: "h",
|
|
584
|
+
quality: "medium",
|
|
585
|
+
scaleResolutionDownBy: 2
|
|
586
|
+
},
|
|
587
|
+
{
|
|
588
|
+
rid: "q",
|
|
589
|
+
quality: "low",
|
|
590
|
+
scaleResolutionDownBy: 4
|
|
591
|
+
}
|
|
592
|
+
];
|
|
593
|
+
object({
|
|
594
|
+
id: string().min(1).max(32),
|
|
595
|
+
name: string().regex(APP_RTC_NAME_PATTERN),
|
|
596
|
+
kind: _enum(APP_RTC_PUBLICATION_KINDS),
|
|
597
|
+
delivery: _enum(APP_RTC_DELIVERIES).optional(),
|
|
598
|
+
simulcast: boolean().optional()
|
|
599
|
+
});
|
|
600
|
+
const nameSchema = string().refine(isAppRtcName, "invalid name");
|
|
601
|
+
const participantIdSchema = string().uuid();
|
|
602
|
+
object({
|
|
603
|
+
ticket: string().min(1).max(4096),
|
|
604
|
+
participantId: participantIdSchema
|
|
605
|
+
});
|
|
606
|
+
object({ answer: sessionDescriptionSchema.refine((value) => value.type === "answer", "expected an answer") });
|
|
607
|
+
union([object({ channels: array(object({
|
|
608
|
+
name: nameSchema,
|
|
609
|
+
delivery: _enum(APP_RTC_DELIVERIES)
|
|
610
|
+
})).min(1).max(APP_RTC_LIMITS.channelsPerMember) }), object({
|
|
611
|
+
offer: sessionDescriptionSchema.refine((value) => value.type === "offer", "expected an offer"),
|
|
612
|
+
tracks: array(object({
|
|
613
|
+
name: nameSchema,
|
|
614
|
+
kind: _enum(["audio", "video"]),
|
|
615
|
+
mid: string().min(1).max(32),
|
|
616
|
+
simulcast: boolean().optional()
|
|
617
|
+
})).min(1).max(APP_RTC_LIMITS.tracksPerMember)
|
|
618
|
+
})]);
|
|
619
|
+
object({
|
|
620
|
+
ids: array(string().min(1).max(32)).min(1).max(APP_RTC_LIMITS.channelsPerMember + APP_RTC_LIMITS.tracksPerMember),
|
|
621
|
+
offer: sessionDescriptionSchema.refine((value) => value.type === "offer", "expected an offer").optional()
|
|
622
|
+
});
|
|
623
|
+
const subscriptionRefSchema = object({
|
|
624
|
+
participantId: participantIdSchema,
|
|
625
|
+
publicationId: string().min(1).max(32)
|
|
626
|
+
});
|
|
627
|
+
const qualitySchema = _enum(APP_RTC_QUALITIES);
|
|
628
|
+
object({
|
|
629
|
+
kind: _enum(["data", "media"]),
|
|
630
|
+
items: array(subscriptionRefSchema.extend({ quality: qualitySchema.optional() })).min(1).max(APP_RTC_LIMITS.batch)
|
|
631
|
+
});
|
|
632
|
+
object({ items: array(subscriptionRefSchema.extend({
|
|
633
|
+
mid: string().min(1).max(32),
|
|
634
|
+
quality: qualitySchema.optional()
|
|
635
|
+
})).min(1).max(APP_RTC_LIMITS.mediaSubscriptions) });
|
|
636
|
+
object({
|
|
637
|
+
items: array(subscriptionRefSchema).min(1).max(APP_RTC_LIMITS.batch),
|
|
638
|
+
offer: sessionDescriptionSchema.refine((value) => value.type === "offer", "expected an offer").optional()
|
|
639
|
+
});
|
|
640
|
+
//#endregion
|
|
641
|
+
//#region ../sdk/src/apis/app-room-rtc.ts
|
|
642
|
+
var AppRtcError = class extends Error {
|
|
643
|
+
code;
|
|
644
|
+
constructor(code, message) {
|
|
645
|
+
super(message);
|
|
646
|
+
this.code = code;
|
|
647
|
+
this.name = "AppRtcError";
|
|
648
|
+
}
|
|
649
|
+
};
|
|
650
|
+
const SERVER_CODES = /* @__PURE__ */ new Set([
|
|
651
|
+
"RTC_UNAVAILABLE",
|
|
652
|
+
"RTC_FORBIDDEN",
|
|
653
|
+
"RTC_LIMIT_EXCEEDED",
|
|
654
|
+
"RTC_RATE_LIMITED",
|
|
655
|
+
"ROOM_NOT_FOUND",
|
|
656
|
+
"ROOM_EXPIRED"
|
|
657
|
+
]);
|
|
658
|
+
const toAppRtcError = (error) => {
|
|
659
|
+
if (error instanceof AppRtcError) return error;
|
|
660
|
+
if (error instanceof HttpError && SERVER_CODES.has(error.code)) return new AppRtcError(error.code, error.message);
|
|
661
|
+
return new AppRtcError("RTC_FAILED", error instanceof Error ? error.message : String(error));
|
|
662
|
+
};
|
|
663
|
+
const HEADER_BYTES = 5;
|
|
664
|
+
const FLAG_BINARY = 1;
|
|
665
|
+
const encoder = new TextEncoder();
|
|
666
|
+
const decoder = new TextDecoder();
|
|
667
|
+
function encodeAppRtcFrame(data, sequence) {
|
|
668
|
+
let payload;
|
|
669
|
+
let flags = 0;
|
|
670
|
+
if (data instanceof ArrayBuffer) {
|
|
671
|
+
payload = new Uint8Array(data);
|
|
672
|
+
flags = FLAG_BINARY;
|
|
673
|
+
} else if (ArrayBuffer.isView(data)) {
|
|
674
|
+
payload = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
|
|
675
|
+
flags = FLAG_BINARY;
|
|
676
|
+
} else {
|
|
677
|
+
const json = JSON.stringify(data);
|
|
678
|
+
if (json === void 0) throw new TypeError("RTC message is not serializable");
|
|
679
|
+
payload = encoder.encode(json);
|
|
680
|
+
}
|
|
681
|
+
if (payload.byteLength > APP_RTC_LIMITS.messageBytes) throw new RangeError(`RTC message exceeds ${APP_RTC_LIMITS.messageBytes} bytes`);
|
|
682
|
+
const frame = new Uint8Array(HEADER_BYTES + payload.byteLength);
|
|
683
|
+
frame[0] = flags;
|
|
684
|
+
new DataView(frame.buffer).setUint32(1, sequence >>> 0);
|
|
685
|
+
frame.set(payload, HEADER_BYTES);
|
|
686
|
+
return frame;
|
|
687
|
+
}
|
|
688
|
+
function decodeAppRtcFrame(frame) {
|
|
689
|
+
if (frame.byteLength < HEADER_BYTES) return null;
|
|
690
|
+
const view = new DataView(frame);
|
|
691
|
+
const flags = view.getUint8(0);
|
|
692
|
+
const sequence = view.getUint32(1);
|
|
693
|
+
const payload = new Uint8Array(frame, HEADER_BYTES);
|
|
694
|
+
if (flags & FLAG_BINARY) return {
|
|
695
|
+
data: payload.slice().buffer,
|
|
696
|
+
sequence
|
|
697
|
+
};
|
|
698
|
+
try {
|
|
699
|
+
return {
|
|
700
|
+
data: JSON.parse(decoder.decode(payload)),
|
|
701
|
+
sequence
|
|
702
|
+
};
|
|
703
|
+
} catch {
|
|
704
|
+
return null;
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
const isNewerSequence = (next, last) => last === null || next !== last && next - last >>> 0 < 2147483648;
|
|
708
|
+
const publicationsKey = (members) => members.map((member) => `${member.participantId}:${member.publications?.map((item) => item.id).join(",") ?? ""}`).join(";");
|
|
709
|
+
const GATHER_TIMEOUT_MS = 2e3;
|
|
710
|
+
const CONNECT_TIMEOUT_MS = 15e3;
|
|
711
|
+
const PENDING_RELIABLE_FRAMES = 256;
|
|
712
|
+
const LATEST_BACKLOG_BYTES = 65536;
|
|
713
|
+
const RECONNECT_DELAYS_MS = [
|
|
714
|
+
500,
|
|
715
|
+
1e3,
|
|
716
|
+
2e3,
|
|
717
|
+
5e3,
|
|
718
|
+
1e4,
|
|
719
|
+
3e4
|
|
720
|
+
];
|
|
721
|
+
const RATE_LIMIT_RETRY_MS = 1e3;
|
|
722
|
+
var ConnectionReplacedError = class extends Error {
|
|
723
|
+
constructor() {
|
|
724
|
+
super("RTC connection was replaced");
|
|
725
|
+
this.name = "ConnectionReplacedError";
|
|
726
|
+
}
|
|
727
|
+
};
|
|
728
|
+
const policyOf = (delivery) => delivery === "latest" ? {
|
|
729
|
+
ordered: false,
|
|
730
|
+
maxRetransmits: 0
|
|
731
|
+
} : { ordered: true };
|
|
732
|
+
const isSessionLost = (error) => error instanceof HttpError && (error.code === "RTC_STALE" || error.code === "RTC_SESSION_NOT_FOUND");
|
|
733
|
+
const isRoomGone = (error) => error instanceof HttpError && (error.code === "ROOM_NOT_FOUND" || error.code === "ROOM_EXPIRED");
|
|
734
|
+
const chunk = (items, size) => {
|
|
735
|
+
const chunks = [];
|
|
736
|
+
for (let index = 0; index < items.length; index += size) chunks.push(items.slice(index, index + size));
|
|
737
|
+
return chunks;
|
|
738
|
+
};
|
|
739
|
+
const mediaKey = (participantId, publicationId) => `${participantId}:${publicationId}`;
|
|
740
|
+
var AppRtcChannel = class {
|
|
741
|
+
rtc;
|
|
742
|
+
name;
|
|
743
|
+
delivery;
|
|
744
|
+
handlers = /* @__PURE__ */ new Set();
|
|
745
|
+
peerHandlers = /* @__PURE__ */ new Set();
|
|
746
|
+
openPeers = /* @__PURE__ */ new Set();
|
|
747
|
+
publication = null;
|
|
748
|
+
pending = [];
|
|
749
|
+
offFlush = null;
|
|
750
|
+
sequence = 0;
|
|
751
|
+
closed = false;
|
|
752
|
+
constructor(rtc, name, delivery) {
|
|
753
|
+
this.rtc = rtc;
|
|
754
|
+
this.name = name;
|
|
755
|
+
this.delivery = delivery;
|
|
756
|
+
}
|
|
757
|
+
get peers() {
|
|
758
|
+
return [...this.openPeers];
|
|
759
|
+
}
|
|
760
|
+
send(data) {
|
|
761
|
+
if (this.closed || this.rtc.state === "closed") return false;
|
|
762
|
+
this.sequence = this.sequence + 1 >>> 0;
|
|
763
|
+
const frame = encodeAppRtcFrame(data, this.sequence);
|
|
764
|
+
const channel = this.publication?.channel;
|
|
765
|
+
if (channel?.readyState === "open" && this.pending.length === 0) return this.write(channel, frame);
|
|
766
|
+
if (this.delivery === "latest") this.pending = [frame];
|
|
767
|
+
else if (this.pending.length >= PENDING_RELIABLE_FRAMES) return false;
|
|
768
|
+
else this.pending.push(frame);
|
|
769
|
+
return true;
|
|
770
|
+
}
|
|
771
|
+
onMessage(handler) {
|
|
772
|
+
this.handlers.add(handler);
|
|
773
|
+
return () => this.handlers.delete(handler);
|
|
774
|
+
}
|
|
775
|
+
/** Reports when this client starts or stops receiving a peer's channel. */
|
|
776
|
+
onPeer(handler) {
|
|
777
|
+
this.peerHandlers.add(handler);
|
|
778
|
+
return () => this.peerHandlers.delete(handler);
|
|
779
|
+
}
|
|
780
|
+
close() {
|
|
781
|
+
if (this.closed) return;
|
|
782
|
+
this.closed = true;
|
|
783
|
+
this.handlers.clear();
|
|
784
|
+
this.peerHandlers.clear();
|
|
785
|
+
this.openPeers.clear();
|
|
786
|
+
this.pending = [];
|
|
787
|
+
this.offFlush?.();
|
|
788
|
+
this.offFlush = null;
|
|
789
|
+
this.rtc.closeChannel(this);
|
|
790
|
+
}
|
|
791
|
+
/** @internal */
|
|
792
|
+
get isOpen() {
|
|
793
|
+
return !this.closed;
|
|
794
|
+
}
|
|
795
|
+
/** @internal */
|
|
796
|
+
get publicationId() {
|
|
797
|
+
return this.publication?.id ?? null;
|
|
798
|
+
}
|
|
799
|
+
/** @internal */
|
|
800
|
+
attach(id, channel) {
|
|
801
|
+
this.offFlush?.();
|
|
802
|
+
this.publication = {
|
|
803
|
+
id,
|
|
804
|
+
channel
|
|
805
|
+
};
|
|
806
|
+
channel.binaryType = "arraybuffer";
|
|
807
|
+
channel.bufferedAmountLowThreshold = LATEST_BACKLOG_BYTES;
|
|
808
|
+
const flush = () => {
|
|
809
|
+
let sent = 0;
|
|
810
|
+
while (sent < this.pending.length) {
|
|
811
|
+
const frame = this.pending[sent];
|
|
812
|
+
if (!frame || !this.write(channel, frame)) break;
|
|
813
|
+
sent++;
|
|
814
|
+
}
|
|
815
|
+
this.pending = this.pending.slice(sent);
|
|
816
|
+
};
|
|
817
|
+
channel.addEventListener("open", flush);
|
|
818
|
+
channel.addEventListener("bufferedamountlow", flush);
|
|
819
|
+
this.offFlush = () => {
|
|
820
|
+
channel.removeEventListener("open", flush);
|
|
821
|
+
channel.removeEventListener("bufferedamountlow", flush);
|
|
822
|
+
};
|
|
823
|
+
if (channel.readyState === "open") flush();
|
|
824
|
+
}
|
|
825
|
+
/** @internal */
|
|
826
|
+
detach() {
|
|
827
|
+
this.offFlush?.();
|
|
828
|
+
this.offFlush = null;
|
|
829
|
+
this.publication = null;
|
|
830
|
+
}
|
|
831
|
+
/** @internal */
|
|
832
|
+
fail() {
|
|
833
|
+
this.close();
|
|
834
|
+
}
|
|
835
|
+
/** @internal */
|
|
836
|
+
deliver(from, data) {
|
|
837
|
+
for (const handler of this.handlers) handler({
|
|
838
|
+
from,
|
|
839
|
+
data
|
|
840
|
+
});
|
|
841
|
+
}
|
|
842
|
+
/** @internal */
|
|
843
|
+
setPeer(participantId, open) {
|
|
844
|
+
if (open ? this.openPeers.has(participantId) : !this.openPeers.delete(participantId)) return;
|
|
845
|
+
if (open) this.openPeers.add(participantId);
|
|
846
|
+
for (const handler of this.peerHandlers) handler({
|
|
847
|
+
participantId,
|
|
848
|
+
open
|
|
849
|
+
});
|
|
850
|
+
}
|
|
851
|
+
write(channel, frame) {
|
|
852
|
+
if (channel.bufferedAmount > (this.delivery === "latest" ? LATEST_BACKLOG_BYTES : 4194304)) return false;
|
|
853
|
+
try {
|
|
854
|
+
channel.send(frame);
|
|
855
|
+
return true;
|
|
856
|
+
} catch {
|
|
857
|
+
return false;
|
|
858
|
+
}
|
|
859
|
+
}
|
|
860
|
+
};
|
|
861
|
+
var AppRoomRtc = class {
|
|
862
|
+
host;
|
|
863
|
+
_state = "connecting";
|
|
864
|
+
pc = null;
|
|
865
|
+
sessionId = null;
|
|
866
|
+
queue = Promise.resolve();
|
|
867
|
+
releasePending = Promise.resolve();
|
|
868
|
+
reconcileQueued = false;
|
|
869
|
+
reconcileFailures = 0;
|
|
870
|
+
reconnectAttempt = 0;
|
|
871
|
+
reconnectTimer = null;
|
|
872
|
+
generation = 0;
|
|
873
|
+
filter = null;
|
|
874
|
+
channels = /* @__PURE__ */ new Map();
|
|
875
|
+
channelsToPublish = /* @__PURE__ */ new Set();
|
|
876
|
+
remoteData = /* @__PURE__ */ new Map();
|
|
877
|
+
localTracks = /* @__PURE__ */ new Map();
|
|
878
|
+
remoteMedia = /* @__PURE__ */ new Map();
|
|
879
|
+
mediaByMid = /* @__PURE__ */ new Map();
|
|
880
|
+
stateHandlers = /* @__PURE__ */ new Set();
|
|
881
|
+
trackHandlers = /* @__PURE__ */ new Set();
|
|
882
|
+
offMembers;
|
|
883
|
+
constructor(host) {
|
|
884
|
+
this.host = host;
|
|
885
|
+
let published = "";
|
|
886
|
+
this.offMembers = host.onMembersChanged((members) => {
|
|
887
|
+
const next = publicationsKey(members);
|
|
888
|
+
if (next === published) return;
|
|
889
|
+
published = next;
|
|
890
|
+
this.scheduleReconcile();
|
|
891
|
+
});
|
|
892
|
+
}
|
|
893
|
+
get state() {
|
|
894
|
+
return this._state;
|
|
895
|
+
}
|
|
896
|
+
get tracks() {
|
|
897
|
+
const tracks = [];
|
|
898
|
+
for (const [key, item] of this.remoteMedia) {
|
|
899
|
+
if (!item.track) continue;
|
|
900
|
+
tracks.push({
|
|
901
|
+
participantId: item.participantId,
|
|
902
|
+
name: item.name,
|
|
903
|
+
kind: item.kind,
|
|
904
|
+
track: item.track,
|
|
905
|
+
quality: item.quality ?? null,
|
|
906
|
+
setQuality: (quality) => this.setQuality(key, quality)
|
|
907
|
+
});
|
|
908
|
+
}
|
|
909
|
+
return tracks;
|
|
910
|
+
}
|
|
911
|
+
get candidates() {
|
|
912
|
+
return this.mediaCandidates().map(({ candidate }) => candidate);
|
|
913
|
+
}
|
|
914
|
+
onStateChange(handler) {
|
|
915
|
+
this.stateHandlers.add(handler);
|
|
916
|
+
return () => this.stateHandlers.delete(handler);
|
|
917
|
+
}
|
|
918
|
+
onTracksChanged(handler) {
|
|
919
|
+
this.trackHandlers.add(handler);
|
|
920
|
+
return () => this.trackHandlers.delete(handler);
|
|
921
|
+
}
|
|
922
|
+
select(filter) {
|
|
923
|
+
this.filter = filter;
|
|
924
|
+
this.scheduleReconcile();
|
|
925
|
+
}
|
|
926
|
+
channel(name, options = {}) {
|
|
927
|
+
if (!isAppRtcName(name)) throw new AppRtcError("RTC_FAILED", `invalid RTC channel name: ${name}`);
|
|
928
|
+
const delivery = options.delivery ?? "reliable";
|
|
929
|
+
const existing = this.channels.get(name);
|
|
930
|
+
if (existing?.isOpen) {
|
|
931
|
+
if (existing.delivery !== delivery) throw new AppRtcError("RTC_FAILED", `RTC channel ${name} is already open with ${existing.delivery} delivery`);
|
|
932
|
+
return existing;
|
|
933
|
+
}
|
|
934
|
+
if (this._state === "closed") throw new AppRtcError("RTC_CLOSED", "RTC connection is closed");
|
|
935
|
+
const channel = new AppRtcChannel(this, name, delivery);
|
|
936
|
+
this.channels.set(name, channel);
|
|
937
|
+
this.publishChannel(channel);
|
|
938
|
+
this.scheduleReconcile();
|
|
939
|
+
return channel;
|
|
940
|
+
}
|
|
941
|
+
async publish(tracks) {
|
|
942
|
+
if (this._state === "closed") throw new AppRtcError("RTC_CLOSED", "RTC connection is closed");
|
|
943
|
+
const inputs = Object.entries(tracks);
|
|
944
|
+
for (const [name] of inputs) {
|
|
945
|
+
if (!isAppRtcName(name)) throw new AppRtcError("RTC_FAILED", `invalid RTC track name: ${name}`);
|
|
946
|
+
if (this.localTracks.has(name)) throw new AppRtcError("RTC_FAILED", `RTC track ${name} is already published`);
|
|
947
|
+
}
|
|
948
|
+
if (this.localTracks.size + inputs.length > APP_RTC_LIMITS.tracksPerMember) throw new AppRtcError("RTC_LIMIT_EXCEEDED", `at most ${APP_RTC_LIMITS.tracksPerMember} tracks per member`);
|
|
949
|
+
const entries = inputs.map(([name, input]) => {
|
|
950
|
+
const { track, simulcast } = "track" in input ? input : {
|
|
951
|
+
track: input,
|
|
952
|
+
simulcast: false
|
|
953
|
+
};
|
|
954
|
+
const kind = track.kind === "audio" ? "audio" : "video";
|
|
955
|
+
return this.localEntry(name, kind, track, simulcast === true && kind === "video");
|
|
956
|
+
});
|
|
957
|
+
for (const entry of entries) this.localTracks.set(entry.name, entry);
|
|
958
|
+
try {
|
|
959
|
+
await this.enqueue(() => this.publishTracks(entries.map((entry) => entry.name)));
|
|
960
|
+
} catch (error) {
|
|
961
|
+
if (!(error instanceof ConnectionReplacedError)) {
|
|
962
|
+
for (const entry of entries) this.dropLocal(entry);
|
|
963
|
+
throw toAppRtcError(error);
|
|
964
|
+
}
|
|
965
|
+
}
|
|
966
|
+
return Object.fromEntries(entries.map((entry) => [entry.name, this.localHandle(entry)]));
|
|
967
|
+
}
|
|
968
|
+
async stats() {
|
|
969
|
+
return this.pc ? readRtcTransportStats(await this.pc.getStats()) : {
|
|
970
|
+
path: null,
|
|
971
|
+
relayProtocol: null,
|
|
972
|
+
rttMs: null
|
|
973
|
+
};
|
|
974
|
+
}
|
|
975
|
+
close() {
|
|
976
|
+
if (this._state === "closed") return;
|
|
977
|
+
this.setState("closed");
|
|
978
|
+
this.offMembers();
|
|
979
|
+
if (this.reconnectTimer) clearTimeout(this.reconnectTimer);
|
|
980
|
+
for (const channel of this.channels.values()) channel.close();
|
|
981
|
+
for (const entry of this.localTracks.values()) entry.track.removeEventListener("ended", entry.onEnded);
|
|
982
|
+
this.teardown(true);
|
|
983
|
+
}
|
|
984
|
+
async shutdown() {
|
|
985
|
+
this.close();
|
|
986
|
+
await this.releasePending;
|
|
987
|
+
}
|
|
988
|
+
/** @internal */
|
|
989
|
+
async start() {
|
|
990
|
+
try {
|
|
991
|
+
await this.connect();
|
|
992
|
+
} catch (error) {
|
|
993
|
+
throw toAppRtcError(error);
|
|
994
|
+
}
|
|
995
|
+
}
|
|
996
|
+
/** @internal */
|
|
997
|
+
async verify() {
|
|
998
|
+
if (this._state === "closed" || !this.sessionId) return;
|
|
999
|
+
try {
|
|
1000
|
+
await this.request("GET", `/${this.sessionId}`);
|
|
1001
|
+
} catch (error) {
|
|
1002
|
+
if (isSessionLost(error)) this.reconnect();
|
|
1003
|
+
}
|
|
1004
|
+
}
|
|
1005
|
+
/** @internal */
|
|
1006
|
+
closeChannel(channel) {
|
|
1007
|
+
if (this.channels.get(channel.name) === channel) this.channels.delete(channel.name);
|
|
1008
|
+
const id = channel.publicationId;
|
|
1009
|
+
channel.detach();
|
|
1010
|
+
if (id) this.enqueue(() => this.unpublishData([id])).catch(() => void 0);
|
|
1011
|
+
this.scheduleReconcile();
|
|
1012
|
+
}
|
|
1013
|
+
localEntry(name, kind, track, simulcast) {
|
|
1014
|
+
const entry = {
|
|
1015
|
+
name,
|
|
1016
|
+
kind,
|
|
1017
|
+
track,
|
|
1018
|
+
simulcast,
|
|
1019
|
+
transceiver: null,
|
|
1020
|
+
id: null,
|
|
1021
|
+
ended: /* @__PURE__ */ new Set(),
|
|
1022
|
+
onEnded: () => void 0
|
|
1023
|
+
};
|
|
1024
|
+
entry.onEnded = () => {
|
|
1025
|
+
if (this.localTracks.get(name) !== entry) return;
|
|
1026
|
+
for (const handler of entry.ended) handler();
|
|
1027
|
+
this.stopLocal(entry).catch(() => void 0);
|
|
1028
|
+
};
|
|
1029
|
+
track.addEventListener("ended", entry.onEnded);
|
|
1030
|
+
return entry;
|
|
1031
|
+
}
|
|
1032
|
+
localHandle(entry) {
|
|
1033
|
+
return {
|
|
1034
|
+
name: entry.name,
|
|
1035
|
+
kind: entry.kind,
|
|
1036
|
+
simulcast: entry.simulcast,
|
|
1037
|
+
get track() {
|
|
1038
|
+
return entry.track;
|
|
1039
|
+
},
|
|
1040
|
+
replace: async (track) => {
|
|
1041
|
+
if (track.kind !== entry.kind) throw new AppRtcError("RTC_FAILED", `replace ${entry.name} with another ${entry.kind} track`);
|
|
1042
|
+
if (this.localTracks.get(entry.name) !== entry) throw new AppRtcError("RTC_CLOSED", `RTC track ${entry.name} has stopped`);
|
|
1043
|
+
entry.track.removeEventListener("ended", entry.onEnded);
|
|
1044
|
+
entry.track = track;
|
|
1045
|
+
track.addEventListener("ended", entry.onEnded);
|
|
1046
|
+
await entry.transceiver?.sender.replaceTrack(track);
|
|
1047
|
+
},
|
|
1048
|
+
onEnded: (handler) => {
|
|
1049
|
+
entry.ended.add(handler);
|
|
1050
|
+
return () => entry.ended.delete(handler);
|
|
1051
|
+
},
|
|
1052
|
+
stop: () => this.stopLocal(entry)
|
|
1053
|
+
};
|
|
1054
|
+
}
|
|
1055
|
+
dropLocal(entry) {
|
|
1056
|
+
entry.track.removeEventListener("ended", entry.onEnded);
|
|
1057
|
+
if (this.localTracks.get(entry.name) === entry) this.localTracks.delete(entry.name);
|
|
1058
|
+
}
|
|
1059
|
+
stopLocal(entry) {
|
|
1060
|
+
if (this.localTracks.get(entry.name) !== entry) return Promise.resolve();
|
|
1061
|
+
this.dropLocal(entry);
|
|
1062
|
+
return this.enqueue(() => this.unpublishTrack(entry)).catch((error) => {
|
|
1063
|
+
if (error instanceof ConnectionReplacedError) return;
|
|
1064
|
+
throw toAppRtcError(error);
|
|
1065
|
+
});
|
|
1066
|
+
}
|
|
1067
|
+
async publishTracks(names) {
|
|
1068
|
+
const pc = this.requirePc();
|
|
1069
|
+
const entries = names.flatMap((name) => {
|
|
1070
|
+
const entry = this.localTracks.get(name);
|
|
1071
|
+
return entry && !entry.id ? [entry] : [];
|
|
1072
|
+
});
|
|
1073
|
+
if (entries.length === 0) return;
|
|
1074
|
+
for (const entry of entries) entry.transceiver = pc.addTransceiver(entry.track, {
|
|
1075
|
+
direction: "sendonly",
|
|
1076
|
+
...entry.simulcast ? { sendEncodings: APP_RTC_SIMULCAST_LAYERS.map(({ rid, scaleResolutionDownBy }) => ({
|
|
1077
|
+
rid,
|
|
1078
|
+
scaleResolutionDownBy
|
|
1079
|
+
})) } : {}
|
|
1080
|
+
});
|
|
1081
|
+
const offer = await this.localOffer(pc);
|
|
1082
|
+
let result;
|
|
1083
|
+
try {
|
|
1084
|
+
result = await this.request("POST", `/${this.sessionId}/publish`, {
|
|
1085
|
+
offer,
|
|
1086
|
+
tracks: entries.map((entry) => ({
|
|
1087
|
+
name: entry.name,
|
|
1088
|
+
kind: entry.kind,
|
|
1089
|
+
mid: entry.transceiver?.mid ?? "",
|
|
1090
|
+
...entry.simulcast ? { simulcast: true } : {}
|
|
1091
|
+
}))
|
|
1092
|
+
});
|
|
1093
|
+
} catch (error) {
|
|
1094
|
+
if (error instanceof ConnectionReplacedError) throw error;
|
|
1095
|
+
await this.settleOffer(pc, void 0).catch(() => void 0);
|
|
1096
|
+
for (const entry of entries) {
|
|
1097
|
+
entry.transceiver?.stop();
|
|
1098
|
+
entry.transceiver = null;
|
|
1099
|
+
}
|
|
1100
|
+
throw error;
|
|
1101
|
+
}
|
|
1102
|
+
await this.settleOffer(pc, result.answer);
|
|
1103
|
+
for (const publication of result.publications) {
|
|
1104
|
+
const entry = entries.find((candidate) => candidate.name === publication.name);
|
|
1105
|
+
if (entry) entry.id = publication.id;
|
|
1106
|
+
}
|
|
1107
|
+
}
|
|
1108
|
+
async unpublishTrack(entry) {
|
|
1109
|
+
if (!entry.id || !entry.transceiver || !this.pc) return;
|
|
1110
|
+
const id = entry.id;
|
|
1111
|
+
entry.transceiver.stop();
|
|
1112
|
+
await this.offerExchange(this.pc, (offer) => this.request("POST", `/${this.sessionId}/unpublish`, {
|
|
1113
|
+
ids: [id],
|
|
1114
|
+
offer
|
|
1115
|
+
}));
|
|
1116
|
+
entry.id = null;
|
|
1117
|
+
}
|
|
1118
|
+
publishChannel(channel) {
|
|
1119
|
+
this.channelsToPublish.add(channel);
|
|
1120
|
+
if (this.channelsToPublish.size > 1 || !this.pc) return;
|
|
1121
|
+
this.enqueue(async () => {
|
|
1122
|
+
const batch = [...this.channelsToPublish];
|
|
1123
|
+
this.channelsToPublish.clear();
|
|
1124
|
+
try {
|
|
1125
|
+
await this.publishChannels(batch);
|
|
1126
|
+
} catch (error) {
|
|
1127
|
+
if (isSessionLost(error) || error instanceof ConnectionReplacedError) throw error;
|
|
1128
|
+
if (error instanceof HttpError && error.code === "RTC_RATE_LIMITED") {
|
|
1129
|
+
setTimeout(() => {
|
|
1130
|
+
for (const item of batch) if (item.isOpen) this.publishChannel(item);
|
|
1131
|
+
}, RATE_LIMIT_RETRY_MS);
|
|
1132
|
+
return;
|
|
1133
|
+
}
|
|
1134
|
+
for (const item of batch) item.fail();
|
|
1135
|
+
console.warn("[Cohub AppRtc] failed to publish channels", error);
|
|
1136
|
+
}
|
|
1137
|
+
}).catch(() => void 0);
|
|
1138
|
+
}
|
|
1139
|
+
async connect() {
|
|
1140
|
+
const generation = ++this.generation;
|
|
1141
|
+
const opened = await this.send("POST", "", {
|
|
1142
|
+
ticket: this.host.ticket,
|
|
1143
|
+
participantId: this.host.participantId()
|
|
1144
|
+
});
|
|
1145
|
+
if (generation !== this.generation || this._state === "closed") {
|
|
1146
|
+
this.send("DELETE", `/${opened.sessionId}`).catch(() => void 0);
|
|
1147
|
+
return;
|
|
1148
|
+
}
|
|
1149
|
+
this.sessionId = opened.sessionId;
|
|
1150
|
+
const configuration = {
|
|
1151
|
+
iceServers: opened.iceServers,
|
|
1152
|
+
bundlePolicy: "max-bundle"
|
|
1153
|
+
};
|
|
1154
|
+
let pc;
|
|
1155
|
+
try {
|
|
1156
|
+
pc = this.host.createPeerConnection?.(configuration) ?? new RTCPeerConnection(configuration);
|
|
1157
|
+
} catch (error) {
|
|
1158
|
+
await this.shutdown();
|
|
1159
|
+
throw error;
|
|
1160
|
+
}
|
|
1161
|
+
this.pc = pc;
|
|
1162
|
+
pc.addEventListener("connectionstatechange", () => {
|
|
1163
|
+
if (this.pc !== pc) return;
|
|
1164
|
+
if (pc.connectionState === "connected") {
|
|
1165
|
+
this.reconnectAttempt = 0;
|
|
1166
|
+
this.setState("connected");
|
|
1167
|
+
} else if (pc.connectionState === "failed") this.reconnect();
|
|
1168
|
+
});
|
|
1169
|
+
pc.addEventListener("track", (event) => this.onTrack(event));
|
|
1170
|
+
const ready = (async () => {
|
|
1171
|
+
await this.answerOffer(opened.offer);
|
|
1172
|
+
await this.connected(pc);
|
|
1173
|
+
})();
|
|
1174
|
+
this.queue = ready.catch(() => void 0);
|
|
1175
|
+
try {
|
|
1176
|
+
await ready;
|
|
1177
|
+
} catch (error) {
|
|
1178
|
+
if (generation === this.generation) this.reconnect();
|
|
1179
|
+
throw error;
|
|
1180
|
+
}
|
|
1181
|
+
this.channelsToPublish.clear();
|
|
1182
|
+
const republish = [...this.channels.values()].filter((channel) => channel.isOpen);
|
|
1183
|
+
const tracks = [...this.localTracks.keys()];
|
|
1184
|
+
await Promise.all([republish.length ? this.enqueue(() => this.publishChannels(republish)).catch((error) => {
|
|
1185
|
+
if (error instanceof ConnectionReplacedError || isSessionLost(error)) return;
|
|
1186
|
+
for (const channel of republish) channel.fail();
|
|
1187
|
+
console.warn("[Cohub AppRtc] failed to publish channels on the new connection", error);
|
|
1188
|
+
}) : null, tracks.length ? this.enqueue(() => this.publishTracks(tracks)).catch((error) => {
|
|
1189
|
+
if (error instanceof ConnectionReplacedError || isSessionLost(error)) return;
|
|
1190
|
+
console.warn("[Cohub AppRtc] failed to publish tracks on the new connection", error);
|
|
1191
|
+
}) : null]);
|
|
1192
|
+
this.scheduleReconcile();
|
|
1193
|
+
}
|
|
1194
|
+
connected(pc) {
|
|
1195
|
+
if (pc.connectionState === "connected") return Promise.resolve();
|
|
1196
|
+
return new Promise((resolve, reject) => {
|
|
1197
|
+
const timer = setTimeout(() => done(/* @__PURE__ */ new Error("RTC connection timed out")), CONNECT_TIMEOUT_MS);
|
|
1198
|
+
const done = (error) => {
|
|
1199
|
+
clearTimeout(timer);
|
|
1200
|
+
pc.removeEventListener("connectionstatechange", check);
|
|
1201
|
+
if (error) reject(error);
|
|
1202
|
+
else resolve();
|
|
1203
|
+
};
|
|
1204
|
+
const check = () => {
|
|
1205
|
+
if (pc.connectionState === "connected") done();
|
|
1206
|
+
else if (pc.connectionState === "failed" || pc.connectionState === "closed") done(/* @__PURE__ */ new Error("RTC connection failed"));
|
|
1207
|
+
};
|
|
1208
|
+
pc.addEventListener("connectionstatechange", check);
|
|
1209
|
+
});
|
|
1210
|
+
}
|
|
1211
|
+
reconnect() {
|
|
1212
|
+
if (this._state === "closed" || this.reconnectTimer) return;
|
|
1213
|
+
this.setState(this._state === "connecting" ? "connecting" : "reconnecting");
|
|
1214
|
+
this.teardown(true);
|
|
1215
|
+
const delay = RECONNECT_DELAYS_MS[Math.min(this.reconnectAttempt, RECONNECT_DELAYS_MS.length - 1)] ?? 3e4;
|
|
1216
|
+
this.reconnectAttempt += 1;
|
|
1217
|
+
this.reconnectTimer = setTimeout(() => {
|
|
1218
|
+
this.reconnectTimer = null;
|
|
1219
|
+
this.connect().catch((error) => {
|
|
1220
|
+
if (isRoomGone(error) || error instanceof HttpError && (error.status === 403 || error.status === 503)) this.close();
|
|
1221
|
+
else this.reconnect();
|
|
1222
|
+
});
|
|
1223
|
+
}, delay);
|
|
1224
|
+
}
|
|
1225
|
+
teardown(release) {
|
|
1226
|
+
this.generation += 1;
|
|
1227
|
+
const sessionId = this.sessionId;
|
|
1228
|
+
this.sessionId = null;
|
|
1229
|
+
this.queue = Promise.resolve();
|
|
1230
|
+
for (const channel of this.channels.values()) channel.detach();
|
|
1231
|
+
for (const item of this.remoteData.values()) this.dropRemoteData(item);
|
|
1232
|
+
this.remoteData.clear();
|
|
1233
|
+
for (const item of this.localTracks.values()) {
|
|
1234
|
+
item.transceiver = null;
|
|
1235
|
+
item.id = null;
|
|
1236
|
+
}
|
|
1237
|
+
const hadTracks = this.remoteMedia.size > 0;
|
|
1238
|
+
this.remoteMedia.clear();
|
|
1239
|
+
this.mediaByMid.clear();
|
|
1240
|
+
this.pc?.close();
|
|
1241
|
+
this.pc = null;
|
|
1242
|
+
if (hadTracks) this.notifyTracks();
|
|
1243
|
+
if (release && sessionId) {
|
|
1244
|
+
this.releasePending = Promise.allSettled([this.releasePending, this.send("DELETE", `/${sessionId}`)]).then((results) => {
|
|
1245
|
+
const failed = results.find((result) => result.status === "rejected");
|
|
1246
|
+
if (failed?.status === "rejected") throw failed.reason;
|
|
1247
|
+
});
|
|
1248
|
+
this.releasePending.catch(() => void 0);
|
|
1249
|
+
}
|
|
1250
|
+
}
|
|
1251
|
+
enqueue(operation) {
|
|
1252
|
+
const generation = this.generation;
|
|
1253
|
+
const run = async () => {
|
|
1254
|
+
if (generation !== this.generation || !this.pc || !this.sessionId) throw new ConnectionReplacedError();
|
|
1255
|
+
try {
|
|
1256
|
+
return await operation();
|
|
1257
|
+
} catch (error) {
|
|
1258
|
+
if (isSessionLost(error)) this.reconnect();
|
|
1259
|
+
throw error;
|
|
1260
|
+
}
|
|
1261
|
+
};
|
|
1262
|
+
const next = this.queue.then(run, run);
|
|
1263
|
+
this.queue = next.catch(() => void 0);
|
|
1264
|
+
return next;
|
|
1265
|
+
}
|
|
1266
|
+
async publishChannels(channels) {
|
|
1267
|
+
const pc = this.requirePc();
|
|
1268
|
+
const open = channels.filter((channel) => channel.isOpen && !channel.publicationId);
|
|
1269
|
+
if (open.length === 0) return;
|
|
1270
|
+
const result = await this.request("POST", `/${this.sessionId}/publish`, { channels: open.map((channel) => ({
|
|
1271
|
+
name: channel.name,
|
|
1272
|
+
delivery: channel.delivery
|
|
1273
|
+
})) });
|
|
1274
|
+
for (const publication of result.publications) {
|
|
1275
|
+
const channel = open.find((item) => item.name === publication.name);
|
|
1276
|
+
const id = result.channelIds?.[publication.id];
|
|
1277
|
+
if (!channel || id === void 0) continue;
|
|
1278
|
+
const dataChannel = pc.createDataChannel(publication.name, {
|
|
1279
|
+
negotiated: true,
|
|
1280
|
+
id,
|
|
1281
|
+
...policyOf(channel.delivery)
|
|
1282
|
+
});
|
|
1283
|
+
channel.attach(publication.id, dataChannel);
|
|
1284
|
+
if (!channel.isOpen) await this.unpublishData([publication.id]);
|
|
1285
|
+
}
|
|
1286
|
+
}
|
|
1287
|
+
async unpublishData(ids) {
|
|
1288
|
+
await this.request("POST", `/${this.sessionId}/unpublish`, { ids });
|
|
1289
|
+
}
|
|
1290
|
+
async settleOffer(pc, answer) {
|
|
1291
|
+
if (answer) await pc.setRemoteDescription(answer);
|
|
1292
|
+
else if (pc.signalingState === "have-local-offer") await pc.setLocalDescription({ type: "rollback" });
|
|
1293
|
+
}
|
|
1294
|
+
async offerExchange(pc, send) {
|
|
1295
|
+
const offer = await this.localOffer(pc);
|
|
1296
|
+
let answer;
|
|
1297
|
+
try {
|
|
1298
|
+
({answer} = await send(offer));
|
|
1299
|
+
} catch (error) {
|
|
1300
|
+
if (!(error instanceof ConnectionReplacedError)) await this.settleOffer(pc, void 0).catch(() => void 0);
|
|
1301
|
+
throw error;
|
|
1302
|
+
}
|
|
1303
|
+
await this.settleOffer(pc, answer);
|
|
1304
|
+
}
|
|
1305
|
+
scheduleReconcile() {
|
|
1306
|
+
if (this.reconcileQueued || !this.pc || this._state === "closed") return;
|
|
1307
|
+
this.reconcileQueued = true;
|
|
1308
|
+
this.enqueue(async () => {
|
|
1309
|
+
this.reconcileQueued = false;
|
|
1310
|
+
await this.reconcile();
|
|
1311
|
+
this.reconcileFailures = 0;
|
|
1312
|
+
}).catch((error) => {
|
|
1313
|
+
this.reconcileQueued = false;
|
|
1314
|
+
if (isSessionLost(error) || error instanceof ConnectionReplacedError) return;
|
|
1315
|
+
console.warn("[Cohub AppRtc] failed to update subscriptions", error);
|
|
1316
|
+
if (error instanceof HttpError && error.code === "RTC_LIMIT_EXCEEDED") return;
|
|
1317
|
+
const delay = RECONNECT_DELAYS_MS[Math.min(this.reconcileFailures, RECONNECT_DELAYS_MS.length - 1)] ?? 3e4;
|
|
1318
|
+
this.reconcileFailures += 1;
|
|
1319
|
+
const generation = this.generation;
|
|
1320
|
+
setTimeout(() => {
|
|
1321
|
+
if (generation === this.generation) this.scheduleReconcile();
|
|
1322
|
+
}, delay);
|
|
1323
|
+
});
|
|
1324
|
+
}
|
|
1325
|
+
mediaCandidates() {
|
|
1326
|
+
const self = this.host.participantId();
|
|
1327
|
+
const candidates = [];
|
|
1328
|
+
for (const member of this.host.members()) {
|
|
1329
|
+
if (member.participantId === self) continue;
|
|
1330
|
+
for (const publication of member.publications ?? []) {
|
|
1331
|
+
if (publication.kind === "data") continue;
|
|
1332
|
+
candidates.push({
|
|
1333
|
+
publication,
|
|
1334
|
+
candidate: {
|
|
1335
|
+
participantId: member.participantId,
|
|
1336
|
+
name: publication.name,
|
|
1337
|
+
kind: publication.kind,
|
|
1338
|
+
simulcast: publication.simulcast === true,
|
|
1339
|
+
subscribed: this.remoteMedia.has(mediaKey(member.participantId, publication.id))
|
|
1340
|
+
}
|
|
1341
|
+
});
|
|
1342
|
+
}
|
|
1343
|
+
}
|
|
1344
|
+
return candidates;
|
|
1345
|
+
}
|
|
1346
|
+
async reconcile() {
|
|
1347
|
+
const self = this.host.participantId();
|
|
1348
|
+
const wantedData = /* @__PURE__ */ new Map();
|
|
1349
|
+
for (const member of this.host.members()) {
|
|
1350
|
+
if (member.participantId === self) continue;
|
|
1351
|
+
for (const publication of member.publications ?? []) {
|
|
1352
|
+
if (publication.kind !== "data") continue;
|
|
1353
|
+
const channel = this.channels.get(publication.name);
|
|
1354
|
+
if (channel?.isOpen && channel.delivery === (publication.delivery ?? "reliable")) wantedData.set(mediaKey(member.participantId, publication.id), {
|
|
1355
|
+
participantId: member.participantId,
|
|
1356
|
+
publicationId: publication.id,
|
|
1357
|
+
name: publication.name,
|
|
1358
|
+
delivery: channel.delivery
|
|
1359
|
+
});
|
|
1360
|
+
}
|
|
1361
|
+
}
|
|
1362
|
+
const wantedMedia = /* @__PURE__ */ new Map();
|
|
1363
|
+
for (const { candidate, publication } of this.mediaCandidates()) {
|
|
1364
|
+
if (wantedMedia.size >= APP_RTC_LIMITS.mediaSubscriptions) break;
|
|
1365
|
+
if (this.filter && !this.filter(candidate)) continue;
|
|
1366
|
+
const key = mediaKey(candidate.participantId, publication.id);
|
|
1367
|
+
const quality = this.remoteMedia.get(key)?.quality ?? (candidate.simulcast ? "high" : void 0);
|
|
1368
|
+
wantedMedia.set(key, {
|
|
1369
|
+
participantId: candidate.participantId,
|
|
1370
|
+
publicationId: publication.id,
|
|
1371
|
+
name: candidate.name,
|
|
1372
|
+
kind: candidate.kind,
|
|
1373
|
+
...quality ? { quality } : {}
|
|
1374
|
+
});
|
|
1375
|
+
}
|
|
1376
|
+
await this.reconcileData(wantedData);
|
|
1377
|
+
await this.reconcileMedia(wantedMedia);
|
|
1378
|
+
if ([...wantedData.keys()].some((key) => !this.remoteData.has(key)) || [...wantedMedia.keys()].some((key) => !this.remoteMedia.has(key))) throw new AppRtcError("RTC_FAILED", "Some RTC subscriptions could not be established");
|
|
1379
|
+
}
|
|
1380
|
+
dropRemoteData(item) {
|
|
1381
|
+
item.channel.close();
|
|
1382
|
+
this.channels.get(item.name)?.setPeer(item.participantId, false);
|
|
1383
|
+
}
|
|
1384
|
+
async reconcileData(wanted) {
|
|
1385
|
+
const pc = this.requirePc();
|
|
1386
|
+
const stale = [...this.remoteData].filter(([key]) => !wanted.has(key));
|
|
1387
|
+
for (const batch of chunk(stale, APP_RTC_LIMITS.batch)) {
|
|
1388
|
+
await this.request("POST", `/${this.sessionId}/unsubscribe`, { items: batch.map(([, item]) => ({
|
|
1389
|
+
participantId: item.participantId,
|
|
1390
|
+
publicationId: item.publicationId
|
|
1391
|
+
})) });
|
|
1392
|
+
for (const [key, item] of batch) {
|
|
1393
|
+
this.dropRemoteData(item);
|
|
1394
|
+
this.remoteData.delete(key);
|
|
1395
|
+
}
|
|
1396
|
+
}
|
|
1397
|
+
const missing = [...wanted].filter(([key]) => !this.remoteData.has(key)).map(([, item]) => item);
|
|
1398
|
+
for (const batch of chunk(missing, APP_RTC_LIMITS.batch)) {
|
|
1399
|
+
const result = await this.request("POST", `/${this.sessionId}/subscribe`, {
|
|
1400
|
+
kind: "data",
|
|
1401
|
+
items: batch.map(({ participantId, publicationId }) => ({
|
|
1402
|
+
participantId,
|
|
1403
|
+
publicationId
|
|
1404
|
+
}))
|
|
1405
|
+
});
|
|
1406
|
+
for (const subscription of result.subscriptions) {
|
|
1407
|
+
const item = batch.find((entry) => entry.participantId === subscription.participantId && entry.publicationId === subscription.publicationId);
|
|
1408
|
+
if (!item || subscription.channelId === void 0) continue;
|
|
1409
|
+
const channel = pc.createDataChannel(item.name, {
|
|
1410
|
+
negotiated: true,
|
|
1411
|
+
id: subscription.channelId,
|
|
1412
|
+
...policyOf(item.delivery)
|
|
1413
|
+
});
|
|
1414
|
+
channel.binaryType = "arraybuffer";
|
|
1415
|
+
const remote = {
|
|
1416
|
+
name: item.name,
|
|
1417
|
+
participantId: item.participantId,
|
|
1418
|
+
publicationId: item.publicationId,
|
|
1419
|
+
channel,
|
|
1420
|
+
last: null
|
|
1421
|
+
};
|
|
1422
|
+
channel.addEventListener("message", (event) => this.onData(remote, event.data));
|
|
1423
|
+
channel.addEventListener("open", () => {
|
|
1424
|
+
if (this.remoteData.get(mediaKey(remote.participantId, remote.publicationId)) === remote) this.channels.get(remote.name)?.setPeer(remote.participantId, true);
|
|
1425
|
+
});
|
|
1426
|
+
this.remoteData.set(mediaKey(item.participantId, item.publicationId), remote);
|
|
1427
|
+
}
|
|
1428
|
+
}
|
|
1429
|
+
}
|
|
1430
|
+
async reconcileMedia(wanted) {
|
|
1431
|
+
const stale = [...this.remoteMedia].filter(([key]) => !wanted.has(key));
|
|
1432
|
+
const missing = [...wanted].filter(([key]) => !this.remoteMedia.has(key)).map(([, item]) => item);
|
|
1433
|
+
const moves = [];
|
|
1434
|
+
for (const to of [...missing]) {
|
|
1435
|
+
const index = stale.findIndex(([, receiver]) => receiver.kind === to.kind);
|
|
1436
|
+
const found = index >= 0 ? stale.splice(index, 1)[0] : void 0;
|
|
1437
|
+
if (!found) continue;
|
|
1438
|
+
moves.push({
|
|
1439
|
+
from: found[0],
|
|
1440
|
+
receiver: found[1],
|
|
1441
|
+
to
|
|
1442
|
+
});
|
|
1443
|
+
missing.splice(missing.indexOf(to), 1);
|
|
1444
|
+
}
|
|
1445
|
+
if (moves.length) {
|
|
1446
|
+
const moved = await this.retarget(moves.map(({ receiver, to }) => ({
|
|
1447
|
+
...to,
|
|
1448
|
+
mid: receiver.mid
|
|
1449
|
+
})));
|
|
1450
|
+
for (const { from, receiver, to } of moves) if (moved.has(receiver.mid)) {
|
|
1451
|
+
this.remoteMedia.delete(from);
|
|
1452
|
+
this.remoteMedia.set(mediaKey(to.participantId, to.publicationId), {
|
|
1453
|
+
...to,
|
|
1454
|
+
mid: receiver.mid,
|
|
1455
|
+
track: receiver.track
|
|
1456
|
+
});
|
|
1457
|
+
this.mediaByMid.set(receiver.mid, mediaKey(to.participantId, to.publicationId));
|
|
1458
|
+
} else {
|
|
1459
|
+
stale.push([from, receiver]);
|
|
1460
|
+
missing.push(to);
|
|
1461
|
+
}
|
|
1462
|
+
if (moved.size) this.notifyTracks();
|
|
1463
|
+
}
|
|
1464
|
+
await this.unsubscribeMedia(stale);
|
|
1465
|
+
await this.subscribeMedia(missing);
|
|
1466
|
+
}
|
|
1467
|
+
async retarget(items) {
|
|
1468
|
+
try {
|
|
1469
|
+
const result = await this.request("PATCH", `/${this.sessionId}/media`, { items: items.map(({ participantId, publicationId, mid, quality }) => ({
|
|
1470
|
+
participantId,
|
|
1471
|
+
publicationId,
|
|
1472
|
+
mid,
|
|
1473
|
+
...quality ? { quality } : {}
|
|
1474
|
+
})) });
|
|
1475
|
+
if (result.offer) await this.answerOffer(result.offer);
|
|
1476
|
+
return new Set(result.updated.map((item) => item.mid));
|
|
1477
|
+
} catch (error) {
|
|
1478
|
+
if (error instanceof ConnectionReplacedError || isSessionLost(error)) throw error;
|
|
1479
|
+
return /* @__PURE__ */ new Set();
|
|
1480
|
+
}
|
|
1481
|
+
}
|
|
1482
|
+
async setQuality(key, quality) {
|
|
1483
|
+
await this.enqueue(async () => {
|
|
1484
|
+
const item = this.remoteMedia.get(key);
|
|
1485
|
+
if (!item || item.quality === void 0 || item.quality === quality) return;
|
|
1486
|
+
if ((await this.retarget([{
|
|
1487
|
+
...item,
|
|
1488
|
+
quality
|
|
1489
|
+
}])).has(item.mid)) {
|
|
1490
|
+
item.quality = quality;
|
|
1491
|
+
this.notifyTracks();
|
|
1492
|
+
}
|
|
1493
|
+
}).catch((error) => {
|
|
1494
|
+
if (error instanceof ConnectionReplacedError) return;
|
|
1495
|
+
throw toAppRtcError(error);
|
|
1496
|
+
});
|
|
1497
|
+
}
|
|
1498
|
+
async unsubscribeMedia(stale) {
|
|
1499
|
+
if (stale.length === 0) return;
|
|
1500
|
+
const pc = this.requirePc();
|
|
1501
|
+
for (const [, item] of stale) {
|
|
1502
|
+
pc.getTransceivers().find((transceiver) => transceiver.mid === item.mid)?.stop();
|
|
1503
|
+
item.track = null;
|
|
1504
|
+
}
|
|
1505
|
+
this.notifyTracks();
|
|
1506
|
+
await this.offerExchange(pc, (offer) => this.request("POST", `/${this.sessionId}/unsubscribe`, {
|
|
1507
|
+
items: stale.map(([, item]) => ({
|
|
1508
|
+
participantId: item.participantId,
|
|
1509
|
+
publicationId: item.publicationId
|
|
1510
|
+
})),
|
|
1511
|
+
offer
|
|
1512
|
+
}));
|
|
1513
|
+
for (const [key, item] of stale) {
|
|
1514
|
+
this.remoteMedia.delete(key);
|
|
1515
|
+
this.mediaByMid.delete(item.mid);
|
|
1516
|
+
}
|
|
1517
|
+
}
|
|
1518
|
+
async subscribeMedia(missing) {
|
|
1519
|
+
if (missing.length === 0) return;
|
|
1520
|
+
const result = await this.request("POST", `/${this.sessionId}/subscribe`, {
|
|
1521
|
+
kind: "media",
|
|
1522
|
+
items: missing.map(({ participantId, publicationId, quality }) => ({
|
|
1523
|
+
participantId,
|
|
1524
|
+
publicationId,
|
|
1525
|
+
...quality ? { quality } : {}
|
|
1526
|
+
}))
|
|
1527
|
+
});
|
|
1528
|
+
for (const subscription of result.subscriptions) {
|
|
1529
|
+
const item = missing.find((entry) => entry.participantId === subscription.participantId && entry.publicationId === subscription.publicationId);
|
|
1530
|
+
if (!item || !subscription.mid) continue;
|
|
1531
|
+
const key = mediaKey(item.participantId, item.publicationId);
|
|
1532
|
+
this.remoteMedia.set(key, {
|
|
1533
|
+
...item,
|
|
1534
|
+
mid: subscription.mid,
|
|
1535
|
+
track: null
|
|
1536
|
+
});
|
|
1537
|
+
this.mediaByMid.set(subscription.mid, key);
|
|
1538
|
+
}
|
|
1539
|
+
if (!result.offer) return;
|
|
1540
|
+
try {
|
|
1541
|
+
await this.answerOffer(result.offer);
|
|
1542
|
+
} catch (error) {
|
|
1543
|
+
if (!(error instanceof ConnectionReplacedError)) this.reconnect();
|
|
1544
|
+
throw error;
|
|
1545
|
+
}
|
|
1546
|
+
}
|
|
1547
|
+
async answerOffer(offer) {
|
|
1548
|
+
const pc = this.requirePc();
|
|
1549
|
+
await pc.setRemoteDescription(offer);
|
|
1550
|
+
await pc.setLocalDescription(await pc.createAnswer());
|
|
1551
|
+
await waitForIceGathering(pc, GATHER_TIMEOUT_MS);
|
|
1552
|
+
const answer = pc.localDescription;
|
|
1553
|
+
if (!answer) throw new Error("the browser produced no answer");
|
|
1554
|
+
await this.request("PUT", `/${this.sessionId}`, { answer: {
|
|
1555
|
+
type: "answer",
|
|
1556
|
+
sdp: answer.sdp
|
|
1557
|
+
} });
|
|
1558
|
+
}
|
|
1559
|
+
async localOffer(pc) {
|
|
1560
|
+
await pc.setLocalDescription(await pc.createOffer());
|
|
1561
|
+
await waitForIceGathering(pc, GATHER_TIMEOUT_MS);
|
|
1562
|
+
const offer = pc.localDescription;
|
|
1563
|
+
if (!offer) throw new Error("the browser produced no offer");
|
|
1564
|
+
return {
|
|
1565
|
+
type: "offer",
|
|
1566
|
+
sdp: offer.sdp
|
|
1567
|
+
};
|
|
1568
|
+
}
|
|
1569
|
+
async request(method, path, body) {
|
|
1570
|
+
const generation = this.generation;
|
|
1571
|
+
const settled = await this.send(method, path, body).then((value) => ({ value }), (error) => ({ error }));
|
|
1572
|
+
if (generation !== this.generation) throw new ConnectionReplacedError();
|
|
1573
|
+
if ("error" in settled) throw settled.error;
|
|
1574
|
+
return settled.value;
|
|
1575
|
+
}
|
|
1576
|
+
send(method, path, body) {
|
|
1577
|
+
const url = `${this.host.hosted ? `/api/rooms/${encodeURIComponent(this.host.roomId)}/rtc` : `/api/apps/${encodeURIComponent(this.host.appId)}/realtime/rooms/${encodeURIComponent(this.host.roomId)}/rtc`}${path}`;
|
|
1578
|
+
return this.host.transport.request(url, {
|
|
1579
|
+
method,
|
|
1580
|
+
...body === void 0 ? {} : {
|
|
1581
|
+
headers: { "Content-Type": "application/json" },
|
|
1582
|
+
body: JSON.stringify(body)
|
|
1583
|
+
}
|
|
1584
|
+
});
|
|
1585
|
+
}
|
|
1586
|
+
requirePc() {
|
|
1587
|
+
if (!this.pc || !this.sessionId) throw new ConnectionReplacedError();
|
|
1588
|
+
return this.pc;
|
|
1589
|
+
}
|
|
1590
|
+
onData(remote, raw) {
|
|
1591
|
+
if (!(raw instanceof ArrayBuffer)) return;
|
|
1592
|
+
const frame = decodeAppRtcFrame(raw);
|
|
1593
|
+
if (!frame) return;
|
|
1594
|
+
const channel = this.channels.get(remote.name);
|
|
1595
|
+
if (!channel?.isOpen) return;
|
|
1596
|
+
if (channel.delivery === "latest") {
|
|
1597
|
+
if (!isNewerSequence(frame.sequence, remote.last)) return;
|
|
1598
|
+
remote.last = frame.sequence;
|
|
1599
|
+
}
|
|
1600
|
+
channel.deliver(remote.participantId, frame.data);
|
|
1601
|
+
}
|
|
1602
|
+
onTrack(event) {
|
|
1603
|
+
const mid = event.transceiver.mid;
|
|
1604
|
+
const key = mid ? this.mediaByMid.get(mid) : void 0;
|
|
1605
|
+
const item = key ? this.remoteMedia.get(key) : void 0;
|
|
1606
|
+
if (!item || !mid) return;
|
|
1607
|
+
item.track = event.track;
|
|
1608
|
+
event.track.addEventListener("ended", () => {
|
|
1609
|
+
const current = this.mediaByMid.get(mid);
|
|
1610
|
+
const owner = current ? this.remoteMedia.get(current) : void 0;
|
|
1611
|
+
if (owner?.track === event.track) {
|
|
1612
|
+
owner.track = null;
|
|
1613
|
+
this.notifyTracks();
|
|
1614
|
+
}
|
|
1615
|
+
});
|
|
1616
|
+
this.notifyTracks();
|
|
1617
|
+
}
|
|
1618
|
+
notifyTracks() {
|
|
1619
|
+
const tracks = this.tracks;
|
|
1620
|
+
for (const handler of this.trackHandlers) handler(tracks);
|
|
1621
|
+
}
|
|
1622
|
+
setState(state) {
|
|
1623
|
+
if (this._state === state) return;
|
|
1624
|
+
this._state = state;
|
|
1625
|
+
for (const handler of this.stateHandlers) handler(state);
|
|
1626
|
+
}
|
|
1627
|
+
};
|
|
1628
|
+
//#endregion
|
|
1629
|
+
//#region ../sdk/src/apis/app-realtime.ts
|
|
1630
|
+
const randomId = () => globalThis.crypto?.randomUUID?.() ?? `${Date.now()}-${Math.random().toString(36).slice(2)}`;
|
|
1631
|
+
const textEncoder = new TextEncoder();
|
|
1632
|
+
const byteLength = (text) => textEncoder.encode(text).byteLength;
|
|
1633
|
+
/**
|
|
1634
|
+
* Ceiling on deltas held during a join, so a stalled handshake cannot buffer without
|
|
1635
|
+
* limit. Dropping the tail needs no extra signal: the gap detection below reports it.
|
|
1636
|
+
*/
|
|
1637
|
+
const APP_ROOM_MAX_JOIN_BUFFER = 512;
|
|
1638
|
+
/** Room events that mutate state, so they must not be applied before the join snapshot. */
|
|
1639
|
+
const APP_ROOM_DELTA_EVENTS = /* @__PURE__ */ new Set([
|
|
1640
|
+
"realtime.room.event",
|
|
1641
|
+
"realtime.room.member.joined",
|
|
1642
|
+
"realtime.room.member.left",
|
|
1643
|
+
"realtime.room.presence.updated",
|
|
1644
|
+
"realtime.room.publications.updated"
|
|
1645
|
+
]);
|
|
1646
|
+
const APP_ROOM_MEMBER_EVENTS = /* @__PURE__ */ new Set([
|
|
1647
|
+
"realtime.room.member.joined",
|
|
1648
|
+
"realtime.room.member.left",
|
|
1649
|
+
"realtime.room.presence.updated",
|
|
1650
|
+
"realtime.room.publications.updated"
|
|
1651
|
+
]);
|
|
1652
|
+
const requestError = (event) => {
|
|
1653
|
+
const payload = event.payload;
|
|
1654
|
+
return new Error(typeof payload.message === "string" ? payload.message : typeof payload.code === "string" ? payload.code : "room request failed");
|
|
1655
|
+
};
|
|
1656
|
+
const isRoomEvent = (event, roomId) => {
|
|
1657
|
+
if (event.domain !== "room") return false;
|
|
1658
|
+
return event.payload.roomId === roomId || event.rooms?.includes(`room:${roomId}`);
|
|
1659
|
+
};
|
|
1660
|
+
var AppRoom = class {
|
|
1661
|
+
websocket;
|
|
1662
|
+
admission;
|
|
1663
|
+
appContext;
|
|
1664
|
+
id;
|
|
1665
|
+
code;
|
|
1666
|
+
createdAt;
|
|
1667
|
+
expiresAt;
|
|
1668
|
+
maxParticipants;
|
|
1669
|
+
seatPerUser;
|
|
1670
|
+
/** Opaque, stable identity of this viewer inside the room. */
|
|
1671
|
+
userKey;
|
|
1672
|
+
_participantId;
|
|
1673
|
+
_state = "connecting";
|
|
1674
|
+
_members = [];
|
|
1675
|
+
joinBuffer = null;
|
|
1676
|
+
lastSequence = 0;
|
|
1677
|
+
hasJoined = false;
|
|
1678
|
+
explicitLeave = false;
|
|
1679
|
+
expiryTimer = null;
|
|
1680
|
+
pending = /* @__PURE__ */ new Map();
|
|
1681
|
+
handlers = /* @__PURE__ */ new Map();
|
|
1682
|
+
allHandlers = /* @__PURE__ */ new Set();
|
|
1683
|
+
stateHandlers = /* @__PURE__ */ new Set();
|
|
1684
|
+
membersHandlers = /* @__PURE__ */ new Set();
|
|
1685
|
+
outOfSyncHandlers = /* @__PURE__ */ new Set();
|
|
1686
|
+
sendErrorHandlers = /* @__PURE__ */ new Set();
|
|
1687
|
+
offEvent;
|
|
1688
|
+
offOpen;
|
|
1689
|
+
offClose;
|
|
1690
|
+
offReconnecting;
|
|
1691
|
+
instanceId = randomId().replace(/[^A-Za-z0-9_-]/g, "");
|
|
1692
|
+
rtcConnection = null;
|
|
1693
|
+
constructor(websocket, admission, appContext) {
|
|
1694
|
+
this.websocket = websocket;
|
|
1695
|
+
this.admission = admission;
|
|
1696
|
+
this.appContext = appContext;
|
|
1697
|
+
this.id = admission.room.id;
|
|
1698
|
+
this.code = admission.room.code;
|
|
1699
|
+
this.createdAt = admission.room.createdAt;
|
|
1700
|
+
this.expiresAt = admission.room.expiresAt;
|
|
1701
|
+
this.maxParticipants = admission.room.maxParticipants;
|
|
1702
|
+
this.seatPerUser = admission.room.seatPerUser === true;
|
|
1703
|
+
this.userKey = admission.userKey;
|
|
1704
|
+
this._participantId = admission.participantId;
|
|
1705
|
+
this.offEvent = websocket.on("event", (event) => this.handleEvent(event));
|
|
1706
|
+
this.offOpen = websocket.on("open", () => {
|
|
1707
|
+
if (!this.hasJoined || this.explicitLeave || this._state === "expired" || this._state === "closed") return;
|
|
1708
|
+
this.rejoin();
|
|
1709
|
+
});
|
|
1710
|
+
this.offReconnecting = websocket.on("reconnecting", () => {
|
|
1711
|
+
if (this.hasJoined && !this.explicitLeave) this.setState("reconnecting");
|
|
1712
|
+
});
|
|
1713
|
+
this.offClose = websocket.on("close", ({ willReconnect }) => {
|
|
1714
|
+
this.rejectPending(/* @__PURE__ */ new Error("room connection closed"));
|
|
1715
|
+
if (this.explicitLeave || !willReconnect) {
|
|
1716
|
+
if (this._state !== "expired") this.setState("closed");
|
|
1717
|
+
this.hasJoined = false;
|
|
1718
|
+
this.dispose();
|
|
1719
|
+
} else if (this.hasJoined) this.setState("reconnecting");
|
|
1720
|
+
});
|
|
1721
|
+
const delay = Math.max(0, Date.parse(this.expiresAt) - Date.now());
|
|
1722
|
+
this.expiryTimer = setTimeout(() => this.expire(), Math.min(delay, 2147e6));
|
|
1723
|
+
}
|
|
1724
|
+
get state() {
|
|
1725
|
+
return this._state;
|
|
1726
|
+
}
|
|
1727
|
+
/**
|
|
1728
|
+
* Identity of this connection inside the room. A `seatPerUser` join can take over a
|
|
1729
|
+
* seat the viewer already holds, so this may differ from the id issued at admission.
|
|
1730
|
+
*/
|
|
1731
|
+
get participantId() {
|
|
1732
|
+
return this._participantId;
|
|
1733
|
+
}
|
|
1734
|
+
get members() {
|
|
1735
|
+
return this._members.slice();
|
|
1736
|
+
}
|
|
1737
|
+
get sequence() {
|
|
1738
|
+
return this.lastSequence;
|
|
1739
|
+
}
|
|
1740
|
+
async connect(options = {}) {
|
|
1741
|
+
if (this.explicitLeave || this.state === "closed" || this.state === "expired") throw new Error("room is closed");
|
|
1742
|
+
if (this.hasJoined) return this;
|
|
1743
|
+
if (options.after !== void 0 && (!Number.isSafeInteger(options.after) || options.after < 0)) throw new Error("after must be a non-negative safe integer");
|
|
1744
|
+
this.lastSequence = options.after ?? 0;
|
|
1745
|
+
await this.joinOverWebsocket(false, options.after);
|
|
1746
|
+
return this;
|
|
1747
|
+
}
|
|
1748
|
+
subscribe(type, handler) {
|
|
1749
|
+
const handlers = this.handlers.get(type) ?? /* @__PURE__ */ new Set();
|
|
1750
|
+
handlers.add(handler);
|
|
1751
|
+
this.handlers.set(type, handlers);
|
|
1752
|
+
return () => handlers.delete(handler);
|
|
1753
|
+
}
|
|
1754
|
+
subscribeAll(handler) {
|
|
1755
|
+
this.allHandlers.add(handler);
|
|
1756
|
+
return () => this.allHandlers.delete(handler);
|
|
1757
|
+
}
|
|
1758
|
+
onStateChange(handler) {
|
|
1759
|
+
this.stateHandlers.add(handler);
|
|
1760
|
+
return () => this.stateHandlers.delete(handler);
|
|
1761
|
+
}
|
|
1762
|
+
onMembersChanged(handler) {
|
|
1763
|
+
this.membersHandlers.add(handler);
|
|
1764
|
+
return () => this.membersHandlers.delete(handler);
|
|
1765
|
+
}
|
|
1766
|
+
onOutOfSync(handler) {
|
|
1767
|
+
this.outOfSyncHandlers.add(handler);
|
|
1768
|
+
return () => this.outOfSyncHandlers.delete(handler);
|
|
1769
|
+
}
|
|
1770
|
+
/** Reports failures of {@link send}, which has no ack to reject. */
|
|
1771
|
+
onSendError(handler) {
|
|
1772
|
+
this.sendErrorHandlers.add(handler);
|
|
1773
|
+
return () => this.sendErrorHandlers.delete(handler);
|
|
1774
|
+
}
|
|
1775
|
+
/**
|
|
1776
|
+
* Publishes without waiting for the server ack, for high-frequency traffic such as
|
|
1777
|
+
* input frames. Awaiting {@link publish} instead caps a loop at `1000 / rtt` events
|
|
1778
|
+
* per second. Ordering still holds, but failures surface through
|
|
1779
|
+
* {@link onSendError} rather than a rejected promise, and calls are ignored while
|
|
1780
|
+
* the room is not joined; watch {@link onStateChange} to know when it resumes.
|
|
1781
|
+
*/
|
|
1782
|
+
send(type, data) {
|
|
1783
|
+
if (this._state !== "joined" || !this.hasJoined) return;
|
|
1784
|
+
const failure = this.validateSend(type, data);
|
|
1785
|
+
if (failure) {
|
|
1786
|
+
for (const handler of this.sendErrorHandlers) handler(failure);
|
|
1787
|
+
return;
|
|
1788
|
+
}
|
|
1789
|
+
this.websocket.publishRealtimeRoom({
|
|
1790
|
+
roomId: this.id,
|
|
1791
|
+
event: type,
|
|
1792
|
+
data
|
|
1793
|
+
}).catch((error) => {
|
|
1794
|
+
const reason = error instanceof Error ? error : new Error(String(error));
|
|
1795
|
+
for (const handler of this.sendErrorHandlers) handler(reason);
|
|
1796
|
+
});
|
|
1797
|
+
}
|
|
1798
|
+
validateSend(type, data) {
|
|
1799
|
+
if (!REALTIME_ROOM_EVENT_NAME_PATTERN.test(type)) return /* @__PURE__ */ new Error(`invalid room event name: ${type}`);
|
|
1800
|
+
let encoded;
|
|
1801
|
+
try {
|
|
1802
|
+
encoded = JSON.stringify(data);
|
|
1803
|
+
} catch {
|
|
1804
|
+
return /* @__PURE__ */ new Error("room event data is not serializable");
|
|
1805
|
+
}
|
|
1806
|
+
if (encoded === void 0) return /* @__PURE__ */ new Error("room event data is not serializable");
|
|
1807
|
+
if (byteLength(encoded) > 16384) return /* @__PURE__ */ new Error("room event payload is too large");
|
|
1808
|
+
return null;
|
|
1809
|
+
}
|
|
1810
|
+
async publish(type, data, options) {
|
|
1811
|
+
this.assertJoined();
|
|
1812
|
+
const failure = this.validateSend(type, data);
|
|
1813
|
+
if (failure) throw failure;
|
|
1814
|
+
const requestId = randomId();
|
|
1815
|
+
const response = await this.request(requestId, /* @__PURE__ */ new Set(["realtime.room.request.ok"]), () => this.websocket.publishRealtimeRoom({
|
|
1816
|
+
roomId: this.id,
|
|
1817
|
+
event: type,
|
|
1818
|
+
data,
|
|
1819
|
+
clientEventId: options?.clientEventId,
|
|
1820
|
+
requestId
|
|
1821
|
+
}));
|
|
1822
|
+
const payload = response.payload;
|
|
1823
|
+
return {
|
|
1824
|
+
eventId: typeof payload.eventId === "string" ? payload.eventId : response.id,
|
|
1825
|
+
sequence: typeof payload.sequence === "number" ? payload.sequence : 0,
|
|
1826
|
+
clientEventId: typeof payload.clientEventId === "string" ? payload.clientEventId : null
|
|
1827
|
+
};
|
|
1828
|
+
}
|
|
1829
|
+
/** Published events after `after`, oldest first; without it, the newest ones. */
|
|
1830
|
+
async history(input = {}) {
|
|
1831
|
+
this.assertJoined();
|
|
1832
|
+
if (!this.websocket.supportsCapability("realtime.room.history.v1")) throw new Error("Room history is not supported by the Gateway");
|
|
1833
|
+
const requestId = randomId();
|
|
1834
|
+
const response = await this.request(requestId, /* @__PURE__ */ new Set(["realtime.room.history"]), () => this.websocket.readRealtimeRoomHistory({
|
|
1835
|
+
roomId: this.id,
|
|
1836
|
+
...input,
|
|
1837
|
+
requestId
|
|
1838
|
+
}));
|
|
1839
|
+
return this.toHistory(response.payload);
|
|
1840
|
+
}
|
|
1841
|
+
/** An invite for someone outside the App, e.g. an Agent: `cohub rooms join <invite>`. */
|
|
1842
|
+
async invite(input = {}) {
|
|
1843
|
+
this.assertJoined();
|
|
1844
|
+
const context = this.appContext;
|
|
1845
|
+
if (!context) throw new Error("Invites are only available inside a published App or hosted Room");
|
|
1846
|
+
if (context.hosted) return context.transport.request(`/api/rooms/${encodeURIComponent(this.id)}/invites`, {
|
|
1847
|
+
method: "POST",
|
|
1848
|
+
headers: { "Content-Type": "application/json" },
|
|
1849
|
+
body: JSON.stringify(input)
|
|
1850
|
+
});
|
|
1851
|
+
return context.transport.request(`/api/apps/${encodeURIComponent(context.appId)}/realtime/rooms/${encodeURIComponent(this.id)}/invites`, {
|
|
1852
|
+
method: "POST",
|
|
1853
|
+
headers: { "Content-Type": "application/json" },
|
|
1854
|
+
body: JSON.stringify({
|
|
1855
|
+
ticket: this.admission.ticket,
|
|
1856
|
+
...input
|
|
1857
|
+
})
|
|
1858
|
+
});
|
|
1859
|
+
}
|
|
1860
|
+
rtcFactory;
|
|
1861
|
+
rtc(options) {
|
|
1862
|
+
if (options?.createPeerConnection) this.rtcFactory = options.createPeerConnection;
|
|
1863
|
+
this.assertJoined();
|
|
1864
|
+
if (this.rtcConnection) {
|
|
1865
|
+
const current = this.rtcConnection;
|
|
1866
|
+
return current.then((rtc) => {
|
|
1867
|
+
if (rtc.state !== "closed") return rtc;
|
|
1868
|
+
return (this.rtcConnection === current ? this.openRtc() : this.rtcConnection) ?? this.openRtc();
|
|
1869
|
+
});
|
|
1870
|
+
}
|
|
1871
|
+
return this.openRtc();
|
|
1872
|
+
}
|
|
1873
|
+
openRtc() {
|
|
1874
|
+
this.assertJoined();
|
|
1875
|
+
const context = this.appContext;
|
|
1876
|
+
if (!context) return Promise.reject(new AppRtcError("RTC_UNSUPPORTED", "RTC requires room context"));
|
|
1877
|
+
if (!this.rtcFactory && typeof RTCPeerConnection === "undefined") return Promise.reject(new AppRtcError("RTC_UNSUPPORTED", "RTC needs a WebRTC adapter"));
|
|
1878
|
+
if (!this.websocket.supportsCapability("realtime.room.rtc.v1")) return Promise.reject(new AppRtcError("RTC_UNSUPPORTED", "RTC is not supported by the Gateway"));
|
|
1879
|
+
const rtc = new AppRoomRtc({
|
|
1880
|
+
roomId: this.id,
|
|
1881
|
+
appId: context.appId,
|
|
1882
|
+
ticket: this.admission.ticket,
|
|
1883
|
+
transport: context.transport,
|
|
1884
|
+
hosted: context.hosted,
|
|
1885
|
+
createPeerConnection: this.rtcFactory,
|
|
1886
|
+
participantId: () => this._participantId,
|
|
1887
|
+
members: () => this._members,
|
|
1888
|
+
onMembersChanged: (handler) => this.onMembersChanged(handler)
|
|
1889
|
+
});
|
|
1890
|
+
const opening = rtc.start().then(() => rtc, (error) => {
|
|
1891
|
+
rtc.close();
|
|
1892
|
+
if (this.rtcConnection === opening) this.rtcConnection = null;
|
|
1893
|
+
throw error;
|
|
1894
|
+
});
|
|
1895
|
+
this.rtcConnection = opening;
|
|
1896
|
+
return opening;
|
|
1897
|
+
}
|
|
1898
|
+
async setPresence(presence) {
|
|
1899
|
+
this.assertJoined();
|
|
1900
|
+
const requestId = randomId();
|
|
1901
|
+
await this.request(requestId, /* @__PURE__ */ new Set(["realtime.room.request.ok"]), () => this.websocket.updateRealtimeRoomPresence({
|
|
1902
|
+
roomId: this.id,
|
|
1903
|
+
presence,
|
|
1904
|
+
requestId
|
|
1905
|
+
}));
|
|
1906
|
+
}
|
|
1907
|
+
async disconnect() {
|
|
1908
|
+
if (this.explicitLeave || this._state === "closed" || this._state === "expired") return;
|
|
1909
|
+
this.explicitLeave = true;
|
|
1910
|
+
try {
|
|
1911
|
+
if (this.hasJoined && this.websocket.state === "open") {
|
|
1912
|
+
const requestId = randomId();
|
|
1913
|
+
await this.request(requestId, /* @__PURE__ */ new Set(["realtime.room.request.ok"]), () => this.appContext?.hosted ? this.websocket.detachRealtimeRoom({
|
|
1914
|
+
roomId: this.id,
|
|
1915
|
+
requestId
|
|
1916
|
+
}) : this.websocket.leaveRealtimeRoom({
|
|
1917
|
+
roomId: this.id,
|
|
1918
|
+
requestId
|
|
1919
|
+
}));
|
|
1920
|
+
}
|
|
1921
|
+
} finally {
|
|
1922
|
+
this.hasJoined = false;
|
|
1923
|
+
this.setState("closed");
|
|
1924
|
+
this.dispose();
|
|
1925
|
+
}
|
|
1926
|
+
}
|
|
1927
|
+
async leave() {
|
|
1928
|
+
if (!this.appContext?.hosted) return this.disconnect();
|
|
1929
|
+
if (this.explicitLeave || this.state === "closed" || this.state === "expired") return;
|
|
1930
|
+
await this.appContext.transport.request(`/api/rooms/${encodeURIComponent(this.id)}/seat`, { method: "DELETE" });
|
|
1931
|
+
this.explicitLeave = true;
|
|
1932
|
+
this.hasJoined = false;
|
|
1933
|
+
this.rejectPending(/* @__PURE__ */ new Error("room left"));
|
|
1934
|
+
this.setState("closed");
|
|
1935
|
+
this.dispose();
|
|
1936
|
+
}
|
|
1937
|
+
async rejoin() {
|
|
1938
|
+
if (this.explicitLeave || this._state === "expired" || this._state === "closed") return;
|
|
1939
|
+
try {
|
|
1940
|
+
await this.joinOverWebsocket(true);
|
|
1941
|
+
} catch (error) {
|
|
1942
|
+
if (this.state === "expired") return;
|
|
1943
|
+
this.setState("closed");
|
|
1944
|
+
this.dispose();
|
|
1945
|
+
console.warn("[Cohub AppRoom] failed to rejoin room", error);
|
|
1946
|
+
}
|
|
1947
|
+
}
|
|
1948
|
+
async joinOverWebsocket(isReconnect, initialAfter) {
|
|
1949
|
+
if (!this.websocket.supportsCapability("realtime.room.v1") && this.websocket.state === "open") throw new Error("Realtime rooms are not supported by the Gateway");
|
|
1950
|
+
this.setState(isReconnect ? "reconnecting" : "connecting");
|
|
1951
|
+
const requestId = randomId();
|
|
1952
|
+
const after = isReconnect && this.websocket.supportsCapability("realtime.room.history.v1") ? this.lastSequence : initialAfter;
|
|
1953
|
+
let missed = null;
|
|
1954
|
+
this.joinBuffer = [];
|
|
1955
|
+
try {
|
|
1956
|
+
if (this.appContext?.hosted && isReconnect) {
|
|
1957
|
+
const admission = await this.appContext.transport.request(`/api/rooms/${encodeURIComponent(this.id)}/connect`, { method: "POST" });
|
|
1958
|
+
if (admission.participantId !== this.participantId) throw new Error("room seat changed during reconnect");
|
|
1959
|
+
this.admission.ticket = admission.ticket;
|
|
1960
|
+
}
|
|
1961
|
+
const payload = (await this.request(requestId, /* @__PURE__ */ new Set(["realtime.room.joined"]), () => this.websocket.joinRealtimeRoom({
|
|
1962
|
+
roomId: this.id,
|
|
1963
|
+
ticket: this.admission.ticket,
|
|
1964
|
+
instanceId: this.instanceId,
|
|
1965
|
+
after,
|
|
1966
|
+
requestId
|
|
1967
|
+
}))).payload;
|
|
1968
|
+
if (typeof payload.participantId !== "string" || !Array.isArray(payload.members)) throw new Error("invalid room join response");
|
|
1969
|
+
this._participantId = payload.participantId;
|
|
1970
|
+
this._members = payload.members;
|
|
1971
|
+
const sequence = typeof payload.sequence === "number" ? payload.sequence : 0;
|
|
1972
|
+
if (after !== void 0 && sequence > after) missed = await this.catchUp(payload.missed, after, sequence);
|
|
1973
|
+
this.lastSequence = sequence;
|
|
1974
|
+
} catch (error) {
|
|
1975
|
+
this.joinBuffer = null;
|
|
1976
|
+
throw error;
|
|
1977
|
+
}
|
|
1978
|
+
if (this.explicitLeave || this._state === "closed" || this._state === "expired") throw new Error("room is closed");
|
|
1979
|
+
this.hasJoined = true;
|
|
1980
|
+
this.setState("joined");
|
|
1981
|
+
this.notifyMembers();
|
|
1982
|
+
if (missed) {
|
|
1983
|
+
const { lost } = missed;
|
|
1984
|
+
if (lost) for (const handler of this.outOfSyncHandlers) handler(lost[0], lost[1]);
|
|
1985
|
+
for (const event of missed.events) this.emit(event);
|
|
1986
|
+
}
|
|
1987
|
+
const buffered = this.joinBuffer ?? [];
|
|
1988
|
+
this.joinBuffer = null;
|
|
1989
|
+
for (const item of buffered) {
|
|
1990
|
+
const sequence = item.payload.sequence;
|
|
1991
|
+
if (typeof sequence === "number" && sequence <= this.lastSequence) continue;
|
|
1992
|
+
this.handleEvent(item);
|
|
1993
|
+
}
|
|
1994
|
+
if (isReconnect) this.rtcConnection?.then((rtc) => rtc.verify()).catch(() => void 0);
|
|
1995
|
+
}
|
|
1996
|
+
request(requestId, expected, send) {
|
|
1997
|
+
return new Promise((resolve, reject) => {
|
|
1998
|
+
const timer = setTimeout(() => {
|
|
1999
|
+
this.pending.delete(requestId);
|
|
2000
|
+
reject(/* @__PURE__ */ new Error("room request timed out"));
|
|
2001
|
+
}, 2e4);
|
|
2002
|
+
this.pending.set(requestId, {
|
|
2003
|
+
expected,
|
|
2004
|
+
resolve,
|
|
2005
|
+
reject,
|
|
2006
|
+
timer
|
|
2007
|
+
});
|
|
2008
|
+
send().catch((error) => {
|
|
2009
|
+
this.pending.delete(requestId);
|
|
2010
|
+
clearTimeout(timer);
|
|
2011
|
+
reject(error instanceof Error ? error : new Error(String(error)));
|
|
2012
|
+
});
|
|
2013
|
+
});
|
|
2014
|
+
}
|
|
2015
|
+
/** Detaches the entry awaiting this requestId, so the caller can settle it. */
|
|
2016
|
+
takePending(requestId) {
|
|
2017
|
+
const pending = requestId ? this.pending.get(requestId) : void 0;
|
|
2018
|
+
if (!pending || !requestId) return null;
|
|
2019
|
+
this.pending.delete(requestId);
|
|
2020
|
+
clearTimeout(pending.timer);
|
|
2021
|
+
return pending;
|
|
2022
|
+
}
|
|
2023
|
+
handleEvent(event) {
|
|
2024
|
+
if (!isRoomEvent(event, this.id)) {
|
|
2025
|
+
if (event.type === "system.request.error") this.takePending(event.requestId)?.reject(requestError(event));
|
|
2026
|
+
return;
|
|
2027
|
+
}
|
|
2028
|
+
if (event.type === "realtime.room.request.error") {
|
|
2029
|
+
const failure = requestError(event);
|
|
2030
|
+
if (event.requestId) {
|
|
2031
|
+
this.takePending(event.requestId)?.reject(failure);
|
|
2032
|
+
return;
|
|
2033
|
+
}
|
|
2034
|
+
for (const handler of this.sendErrorHandlers) handler(failure);
|
|
2035
|
+
return;
|
|
2036
|
+
}
|
|
2037
|
+
const awaiting = event.requestId ? this.pending.get(event.requestId) : void 0;
|
|
2038
|
+
if (awaiting?.expected.has(event.type)) {
|
|
2039
|
+
this.takePending(event.requestId);
|
|
2040
|
+
awaiting.resolve(event);
|
|
2041
|
+
}
|
|
2042
|
+
if (this.joinBuffer && APP_ROOM_DELTA_EVENTS.has(event.type)) {
|
|
2043
|
+
if (this.joinBuffer.length < APP_ROOM_MAX_JOIN_BUFFER) this.joinBuffer.push(event);
|
|
2044
|
+
return;
|
|
2045
|
+
}
|
|
2046
|
+
const payload = event.payload;
|
|
2047
|
+
if (APP_ROOM_DELTA_EVENTS.has(event.type) && typeof payload.sequence === "number") this.observeSequence(payload.sequence);
|
|
2048
|
+
if (APP_ROOM_MEMBER_EVENTS.has(event.type)) {
|
|
2049
|
+
const member = payload.member;
|
|
2050
|
+
if (member?.participantId) {
|
|
2051
|
+
const members = new Map(this._members.map((item) => [item.participantId, item]));
|
|
2052
|
+
if (event.type === "realtime.room.member.left") members.delete(member.participantId);
|
|
2053
|
+
else members.set(member.participantId, member);
|
|
2054
|
+
this._members = [...members.values()];
|
|
2055
|
+
this.notifyMembers();
|
|
2056
|
+
}
|
|
2057
|
+
return;
|
|
2058
|
+
}
|
|
2059
|
+
if (event.type === "realtime.room.closed") {
|
|
2060
|
+
this.hasJoined = false;
|
|
2061
|
+
if (payload.reason === "expired") this.setState("expired");
|
|
2062
|
+
else this.setState("closed");
|
|
2063
|
+
this.rejectPending(/* @__PURE__ */ new Error(`room closed: ${typeof payload.reason === "string" ? payload.reason : "unknown"}`));
|
|
2064
|
+
this.dispose();
|
|
2065
|
+
return;
|
|
2066
|
+
}
|
|
2067
|
+
if (event.type !== "realtime.room.event") return;
|
|
2068
|
+
const { id, timestamp, payload: roomPayload } = event;
|
|
2069
|
+
this.emit({
|
|
2070
|
+
id,
|
|
2071
|
+
timestamp,
|
|
2072
|
+
roomId: roomPayload.roomId,
|
|
2073
|
+
sequence: roomPayload.sequence,
|
|
2074
|
+
type: roomPayload.event,
|
|
2075
|
+
data: roomPayload.data,
|
|
2076
|
+
clientEventId: roomPayload.clientEventId,
|
|
2077
|
+
sender: roomPayload.sender,
|
|
2078
|
+
self: roomPayload.sender.participantId === this.participantId
|
|
2079
|
+
});
|
|
2080
|
+
}
|
|
2081
|
+
async catchUp(first, after, sequence) {
|
|
2082
|
+
if (!first) return {
|
|
2083
|
+
events: [],
|
|
2084
|
+
lost: [after + 1, sequence]
|
|
2085
|
+
};
|
|
2086
|
+
const events = this.toHistory(first).events;
|
|
2087
|
+
const { truncated } = first;
|
|
2088
|
+
let { cursor } = first;
|
|
2089
|
+
while (cursor < sequence) {
|
|
2090
|
+
const requestId = randomId();
|
|
2091
|
+
const page = (await this.request(requestId, /* @__PURE__ */ new Set(["realtime.room.history"]), () => this.websocket.readRealtimeRoomHistory({
|
|
2092
|
+
roomId: this.id,
|
|
2093
|
+
after: cursor,
|
|
2094
|
+
requestId
|
|
2095
|
+
})).catch(() => null))?.payload;
|
|
2096
|
+
if (!page || page.cursor <= cursor) break;
|
|
2097
|
+
events.push(...this.toHistory(page).events);
|
|
2098
|
+
cursor = page.cursor;
|
|
2099
|
+
}
|
|
2100
|
+
const kept = events.filter((event) => event.sequence <= sequence);
|
|
2101
|
+
const lost = truncated ? [after + 1, kept[0]?.sequence ?? sequence] : cursor < sequence ? [cursor + 1, sequence] : null;
|
|
2102
|
+
return {
|
|
2103
|
+
events: kept,
|
|
2104
|
+
lost: lost && lost[1] > lost[0] ? lost : null
|
|
2105
|
+
};
|
|
2106
|
+
}
|
|
2107
|
+
emit(item) {
|
|
2108
|
+
this.handlers.get(item.type)?.forEach((handler) => {
|
|
2109
|
+
handler(item);
|
|
2110
|
+
});
|
|
2111
|
+
this.allHandlers.forEach((handler) => {
|
|
2112
|
+
handler(item);
|
|
2113
|
+
});
|
|
2114
|
+
}
|
|
2115
|
+
toHistory(history) {
|
|
2116
|
+
return {
|
|
2117
|
+
events: history.events.map((event) => ({
|
|
2118
|
+
...event,
|
|
2119
|
+
data: event.data,
|
|
2120
|
+
roomId: this.id,
|
|
2121
|
+
self: event.sender.participantId === this.participantId
|
|
2122
|
+
})),
|
|
2123
|
+
cursor: history.cursor,
|
|
2124
|
+
truncated: history.truncated
|
|
2125
|
+
};
|
|
2126
|
+
}
|
|
2127
|
+
observeSequence(sequence) {
|
|
2128
|
+
if (this.lastSequence > 0 && sequence > this.lastSequence + 1) for (const handler of this.outOfSyncHandlers) handler(this.lastSequence + 1, sequence);
|
|
2129
|
+
if (sequence > this.lastSequence) this.lastSequence = sequence;
|
|
2130
|
+
}
|
|
2131
|
+
assertJoined() {
|
|
2132
|
+
if (this._state !== "joined" || !this.hasJoined) throw new Error("room is not joined");
|
|
2133
|
+
}
|
|
2134
|
+
setState(state) {
|
|
2135
|
+
if (this._state === state) return;
|
|
2136
|
+
this._state = state;
|
|
2137
|
+
for (const handler of this.stateHandlers) handler(state);
|
|
2138
|
+
}
|
|
2139
|
+
notifyMembers() {
|
|
2140
|
+
const members = this.members;
|
|
2141
|
+
for (const handler of this.membersHandlers) handler(members);
|
|
2142
|
+
}
|
|
2143
|
+
rejectPending(error) {
|
|
2144
|
+
for (const [requestId, pending] of this.pending) {
|
|
2145
|
+
this.pending.delete(requestId);
|
|
2146
|
+
clearTimeout(pending.timer);
|
|
2147
|
+
pending.reject(error);
|
|
2148
|
+
}
|
|
2149
|
+
}
|
|
2150
|
+
expire() {
|
|
2151
|
+
if (this.explicitLeave || this._state === "closed" || this._state === "expired") return;
|
|
2152
|
+
this.hasJoined = false;
|
|
2153
|
+
this.setState("expired");
|
|
2154
|
+
this.rejectPending(/* @__PURE__ */ new Error("room expired"));
|
|
2155
|
+
this.dispose();
|
|
2156
|
+
}
|
|
2157
|
+
dispose() {
|
|
2158
|
+
const rtc = this.rtcConnection;
|
|
2159
|
+
this.rtcConnection = null;
|
|
2160
|
+
rtc?.then((connection) => connection.close()).catch(() => void 0);
|
|
2161
|
+
this.offEvent();
|
|
2162
|
+
this.offOpen();
|
|
2163
|
+
this.offClose();
|
|
2164
|
+
this.offReconnecting();
|
|
2165
|
+
if (this.expiryTimer) clearTimeout(this.expiryTimer);
|
|
2166
|
+
this.expiryTimer = null;
|
|
2167
|
+
}
|
|
2168
|
+
};
|
|
2169
|
+
var AppRealtimeApi = class {
|
|
2170
|
+
transport;
|
|
2171
|
+
websocket;
|
|
2172
|
+
getContext;
|
|
2173
|
+
constructor(transport, websocket, getContext) {
|
|
2174
|
+
this.transport = transport;
|
|
2175
|
+
this.websocket = websocket;
|
|
2176
|
+
this.getContext = getContext;
|
|
2177
|
+
}
|
|
2178
|
+
async createRoom(input = {}) {
|
|
2179
|
+
const appId = await this.requireAppId();
|
|
2180
|
+
const admission = await this.transport.request(`/api/apps/${encodeURIComponent(appId)}/realtime/rooms`, {
|
|
2181
|
+
method: "POST",
|
|
2182
|
+
headers: { "Content-Type": "application/json" },
|
|
2183
|
+
body: JSON.stringify(input)
|
|
2184
|
+
});
|
|
2185
|
+
return this.openRoom(appId, admission);
|
|
2186
|
+
}
|
|
2187
|
+
async joinRoom(input) {
|
|
2188
|
+
const appId = await this.requireAppId();
|
|
2189
|
+
const admission = await this.transport.request(`/api/apps/${encodeURIComponent(appId)}/realtime/rooms/join`, {
|
|
2190
|
+
method: "POST",
|
|
2191
|
+
headers: { "Content-Type": "application/json" },
|
|
2192
|
+
body: JSON.stringify(input)
|
|
2193
|
+
});
|
|
2194
|
+
return this.openRoom(appId, admission);
|
|
2195
|
+
}
|
|
2196
|
+
async requireAppId() {
|
|
2197
|
+
const context = await this.getContext();
|
|
2198
|
+
if (!context?.app?.id) throw new Error("App context is unavailable — not running inside a published app runtime.");
|
|
2199
|
+
return context.app.id;
|
|
2200
|
+
}
|
|
2201
|
+
async openRoom(appId, admission) {
|
|
2202
|
+
const room = new AppRoom(this.websocket, admission, {
|
|
2203
|
+
transport: this.transport,
|
|
2204
|
+
appId
|
|
2205
|
+
});
|
|
2206
|
+
try {
|
|
2207
|
+
await room.connect();
|
|
2208
|
+
return room;
|
|
2209
|
+
} catch (error) {
|
|
2210
|
+
await room.leave().catch(() => void 0);
|
|
2211
|
+
throw error;
|
|
2212
|
+
}
|
|
2213
|
+
}
|
|
2214
|
+
};
|
|
2215
|
+
//#endregion
|
|
2216
|
+
export { normalizeRealtimeRooms as C, isRealtimeDomain as S, WS_REALTIME_ROOM_HISTORY_CAPABILITY as _, statNumber as a, getRealtimeSpaceRoom as b, HttpTransport as c, normalizeRequestSource as d, readRequestSourceFromEnv as f, WS_REALTIME_ROOM_CAPABILITY as g, WS_COMPACT_STREAM_CAPABILITY as h, readRtcTransportStats as i, joinApiUrl as l, WS_BOARD_AWARENESS_CAPABILITY as m, AppRoom as n, waitForIceGathering as o, isUuidLike as p, IceServerCache as r, HttpError as s, AppRealtimeApi as t, sanitizeAccessToken as u, WS_ROOM_SUBSCRIPTION_CAPABILITY as v, getSessionTurnPatchStreamKey as x, getRealtimeBoardRoom as y };
|