The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 06:00 UTC
| 1 | import * as realtimeKit from "@distilled.cloud/cloudflare/realtime-kit"; |
| 2 | import { isResolved } from "alchemy/Diff"; |
| 3 | import { createPhysicalName } from "alchemy/PhysicalName"; |
| 4 | import * as Provider from "alchemy/Provider"; |
| 5 | import { Resource } from "alchemy/Resource"; |
| 6 | import * as Effect from "effect/Effect"; |
| 7 | import * as Predicate from "effect/Predicate"; |
| 8 | import { CloudflareEnvironment } from "../CloudflareEnvironment.ts"; |
| 9 | import type { Providers } from "../Providers.ts"; |
| 10 | |
| 11 | const TypeId = "Cloudflare.RealtimeKit.Preset" as const; |
| 12 | type TypeId = typeof TypeId; |
| 13 | |
| 14 | /** |
| 15 | * Media quality tier for video / screenshare streams. |
| 16 | */ |
| 17 | export type MediaQuality = "hd" | "vga" | "qvga"; |
| 18 | |
| 19 | /** |
| 20 | * Meeting layout the preset applies to. |
| 21 | */ |
| 22 | export type ViewType = "GROUP_CALL" | "WEBINAR" | "AUDIO_ROOM"; |
| 23 | |
| 24 | /** |
| 25 | * Whether a participant may produce a media kind. |
| 26 | */ |
| 27 | export type CanProduce = "ALLOWED" | "NOT_ALLOWED" | "CAN_REQUEST"; |
| 28 | |
| 29 | /** |
| 30 | * What a participant joining with this preset records as. |
| 31 | */ |
| 32 | export type RecorderType = "RECORDER" | "LIVESTREAMER" | "NONE"; |
| 33 | |
| 34 | /** |
| 35 | * Waiting-room behavior for participants joining with this preset. |
| 36 | */ |
| 37 | export type WaitingRoomType = "SKIP" | "ON_PRIVILEGED_USER_ENTRY" | "SKIP_ON_ACCEPT"; |
| 38 | |
| 39 | /** |
| 40 | * Media configuration of a preset (stream counts, quality, frame rates). |
| 41 | */ |
| 42 | export type PresetConfig = { |
| 43 | /** |
| 44 | * Maximum number of simultaneous screenshares. |
| 45 | */ |
| 46 | maxScreenshareCount: number; |
| 47 | /** |
| 48 | * Maximum simultaneous video streams per device class. |
| 49 | */ |
| 50 | maxVideoStreams: { desktop: number; mobile: number }; |
| 51 | /** |
| 52 | * Quality / frame-rate settings for each media kind. |
| 53 | */ |
| 54 | media: { |
| 55 | screenshare: { frameRate: number; quality: MediaQuality }; |
| 56 | video: { frameRate: number; quality: MediaQuality }; |
| 57 | audio?: { enableHighBitrate?: boolean; enableStereo?: boolean }; |
| 58 | }; |
| 59 | /** |
| 60 | * Meeting layout this preset applies to. |
| 61 | */ |
| 62 | viewType: ViewType; |
| 63 | }; |
| 64 | |
| 65 | /** |
| 66 | * UI design tokens of a preset (colors, logo, spacing). |
| 67 | */ |
| 68 | /** Corner rounding of UI elements. */ |
| 69 | export type BorderRadius = "sharp" | "rounded" | "extra-rounded" | "circular"; |
| 70 | |
| 71 | /** Border width of UI elements. */ |
| 72 | export type BorderWidth = "none" | "thin" | "fat"; |
| 73 | |
| 74 | /** Base color theme of the meeting UI. */ |
| 75 | export type Theme = "darkest" | "dark" | "light"; |
| 76 | |
| 77 | export type PresetUi = { |
| 78 | designTokens: { |
| 79 | borderRadius: BorderRadius; |
| 80 | borderWidth: BorderWidth; |
| 81 | colors: { |
| 82 | background: { |
| 83 | "600": string; |
| 84 | "700": string; |
| 85 | "800": string; |
| 86 | "900": string; |
| 87 | "1000": string; |
| 88 | }; |
| 89 | brand: { |
| 90 | "300": string; |
| 91 | "400": string; |
| 92 | "500": string; |
| 93 | "600": string; |
| 94 | "700": string; |
| 95 | }; |
| 96 | danger: string; |
| 97 | success: string; |
| 98 | text: string; |
| 99 | textOnBrand: string; |
| 100 | videoBg: string; |
| 101 | warning: string; |
| 102 | }; |
| 103 | logo: string; |
| 104 | spacingBase: number; |
| 105 | theme: Theme; |
| 106 | }; |
| 107 | /** |
| 108 | * Raw UI-kit config diff applied on top of the design tokens. Required by |
| 109 | * the live API (defaulted to `{}` when omitted). |
| 110 | * @default {} |
| 111 | */ |
| 112 | configDiff?: unknown; |
| 113 | }; |
| 114 | |
| 115 | /** |
| 116 | * Participant permissions granted by a preset. |
| 117 | */ |
| 118 | export type PresetPermissions = { |
| 119 | acceptWaitingRequests: boolean; |
| 120 | canAcceptProductionRequests: boolean; |
| 121 | canChangeParticipantPermissions: boolean; |
| 122 | canEditDisplayName: boolean; |
| 123 | canLivestream: boolean; |
| 124 | canRecord: boolean; |
| 125 | canSpotlight: boolean; |
| 126 | chat: { |
| 127 | private: { |
| 128 | canReceive: boolean; |
| 129 | canSend: boolean; |
| 130 | files: boolean; |
| 131 | text: boolean; |
| 132 | }; |
| 133 | public: { canSend: boolean; files: boolean; text: boolean }; |
| 134 | }; |
| 135 | connectedMeetings: { |
| 136 | canAlterConnectedMeetings: boolean; |
| 137 | canSwitchConnectedMeetings: boolean; |
| 138 | canSwitchToParentMeeting: boolean; |
| 139 | }; |
| 140 | disableParticipantAudio: boolean; |
| 141 | disableParticipantScreensharing: boolean; |
| 142 | disableParticipantVideo: boolean; |
| 143 | hiddenParticipant: boolean; |
| 144 | kickParticipant: boolean; |
| 145 | media: { |
| 146 | audio: { canProduce: CanProduce }; |
| 147 | screenshare: { canProduce: CanProduce }; |
| 148 | video: { canProduce: CanProduce }; |
| 149 | }; |
| 150 | pinParticipant: boolean; |
| 151 | plugins: { |
| 152 | canClose: boolean; |
| 153 | canEditConfig: boolean; |
| 154 | canStart: boolean; |
| 155 | /** |
| 156 | * Per-plugin access config keyed by plugin UUID. |
| 157 | * @default {} |
| 158 | */ |
| 159 | config?: unknown; |
| 160 | }; |
| 161 | polls: { canCreate: boolean; canView: boolean; canVote: boolean }; |
| 162 | recorderType: RecorderType; |
| 163 | showParticipantList: boolean; |
| 164 | waitingRoomType: WaitingRoomType; |
| 165 | isRecorder?: boolean; |
| 166 | }; |
| 167 | |
| 168 | export type PresetProps = { |
| 169 | /** |
| 170 | * The RealtimeKit app the preset belongs to. Changing the app triggers a |
| 171 | * replacement. |
| 172 | */ |
| 173 | appId: string; |
| 174 | /** |
| 175 | * Human readable preset name (e.g. `host`, `guest`). If omitted, a unique |
| 176 | * name is generated from the app, stage, and logical ID. |
| 177 | * @default ${app}-${stage}-${id} |
| 178 | */ |
| 179 | name?: string; |
| 180 | /** |
| 181 | * Media configuration (stream counts, quality, frame rates). |
| 182 | * @default a group-call config (hd video at 30fps, hd screenshare at 5fps, 9 desktop / 4 mobile streams) |
| 183 | */ |
| 184 | config?: PresetConfig; |
| 185 | /** |
| 186 | * UI design tokens. |
| 187 | * @default RealtimeKit's dark theme defaults |
| 188 | */ |
| 189 | ui?: PresetUi; |
| 190 | /** |
| 191 | * Participant permissions. The API requires the full object on create, so |
| 192 | * unspecified permissions fall back to conservative attendee defaults |
| 193 | * (chat and polls allowed, no recording / livestreaming / moderation). |
| 194 | * @default conservative attendee defaults |
| 195 | */ |
| 196 | permissions?: PresetPermissions; |
| 197 | }; |
| 198 | |
| 199 | export type PresetAttributes = { |
| 200 | /** |
| 201 | * Server-generated preset identifier. Stable across updates. |
| 202 | */ |
| 203 | presetId: string; |
| 204 | /** |
| 205 | * The Cloudflare account the preset belongs to. |
| 206 | */ |
| 207 | accountId: string; |
| 208 | /** |
| 209 | * The RealtimeKit app the preset belongs to. |
| 210 | */ |
| 211 | appId: string; |
| 212 | /** |
| 213 | * Human readable preset name. |
| 214 | */ |
| 215 | name: string; |
| 216 | /** |
| 217 | * Media configuration as stored by Cloudflare. |
| 218 | */ |
| 219 | config: PresetConfig; |
| 220 | /** |
| 221 | * UI design tokens as stored by Cloudflare. |
| 222 | */ |
| 223 | ui: PresetUi; |
| 224 | /** |
| 225 | * Participant permissions as stored by Cloudflare. |
| 226 | */ |
| 227 | permissions: PresetPermissions | undefined; |
| 228 | }; |
| 229 | |
| 230 | export type Preset = Resource<TypeId, PresetProps, PresetAttributes, never, Providers>; |
| 231 | |
| 232 | /** |
| 233 | * A Cloudflare RealtimeKit preset — a named participant role (e.g. `host`, |
| 234 | * `guest`) bundling permissions, media quality, and UI design tokens for a |
| 235 | * RealtimeKit app. |
| 236 | * |
| 237 | * Name, config, UI, and permissions are all mutable in place; only moving |
| 238 | * the preset to a different app forces a replacement. The create API |
| 239 | * requires the full config / UI / permissions objects, so the resource fills |
| 240 | * unspecified sections with sensible defaults. |
| 241 | * ### Creating a Preset |
| 242 | * **Example:** Default group-call preset |
| 243 | * ```typescript |
| 244 | * const app = yield* Cloudflare.RealtimeKit.App("Meetings", {}); |
| 245 | * |
| 246 | * const guest = yield* Cloudflare.RealtimeKit.Preset("Guest", { |
| 247 | * appId: app.appId, |
| 248 | * name: "guest", |
| 249 | * }); |
| 250 | * ``` |
| 251 | * |
| 252 | * **Example:** Host preset with moderation permissions |
| 253 | * ```typescript |
| 254 | * const host = yield* Cloudflare.RealtimeKit.Preset("Host", { |
| 255 | * appId: app.appId, |
| 256 | * name: "host", |
| 257 | * permissions: { |
| 258 | * ...Cloudflare.RealtimeKit.defaultRealtimeKitPresetPermissions(), |
| 259 | * canRecord: true, |
| 260 | * kickParticipant: true, |
| 261 | * pinParticipant: true, |
| 262 | * acceptWaitingRequests: true, |
| 263 | * }, |
| 264 | * }); |
| 265 | * ``` |
| 266 | * |
| 267 | * ### Updating a Preset |
| 268 | * **Example:** Switch to a webinar layout |
| 269 | * ```typescript |
| 270 | * const preset = yield* Cloudflare.RealtimeKit.Preset("Guest", { |
| 271 | * appId: app.appId, |
| 272 | * name: "guest", |
| 273 | * config: { |
| 274 | * ...Cloudflare.RealtimeKit.defaultRealtimeKitPresetConfig(), |
| 275 | * viewType: "WEBINAR", |
| 276 | * }, |
| 277 | * }); |
| 278 | * ``` |
| 279 | * |
| 280 | * @see https://developers.cloudflare.com/realtime/realtimekit/ |
| 281 | * |
| 282 | * @resource |
| 283 | * @product Realtime Kit |
| 284 | * @category Media |
| 285 | */ |
| 286 | export const Preset = Resource<Preset>(TypeId); |
| 287 | |
| 288 | /** |
| 289 | * Returns true if the given value is a Preset resource. |
| 290 | */ |
| 291 | export const isPreset = (value: unknown): value is Preset => |
| 292 | Predicate.hasProperty(value, "Type") && value.Type === TypeId; |
| 293 | |
| 294 | /** |
| 295 | * The default media configuration used when `config` is omitted: a group |
| 296 | * call with hd video at 30fps, hd screenshare at 5fps, and 9 desktop / |
| 297 | * 4 mobile video streams. |
| 298 | */ |
| 299 | export const defaultRealtimeKitPresetConfig = (): PresetConfig => ({ |
| 300 | maxScreenshareCount: 1, |
| 301 | maxVideoStreams: { desktop: 9, mobile: 4 }, |
| 302 | media: { |
| 303 | screenshare: { frameRate: 5, quality: "hd" }, |
| 304 | video: { frameRate: 30, quality: "hd" }, |
| 305 | }, |
| 306 | viewType: "GROUP_CALL", |
| 307 | }); |
| 308 | |
| 309 | /** |
| 310 | * The default UI design tokens used when `ui` is omitted: RealtimeKit's |
| 311 | * dark theme. |
| 312 | */ |
| 313 | export const defaultRealtimeKitPresetUi = (): PresetUi => ({ |
| 314 | designTokens: { |
| 315 | borderRadius: "rounded", |
| 316 | borderWidth: "thin", |
| 317 | colors: { |
| 318 | background: { |
| 319 | "600": "#1f2937", |
| 320 | "700": "#1a232e", |
| 321 | "800": "#141d26", |
| 322 | "900": "#10171e", |
| 323 | "1000": "#0b1116", |
| 324 | }, |
| 325 | brand: { |
| 326 | "300": "#93c5fd", |
| 327 | "400": "#60a5fa", |
| 328 | "500": "#3b82f6", |
| 329 | "600": "#2563eb", |
| 330 | "700": "#1d4ed8", |
| 331 | }, |
| 332 | danger: "#ff2d2d", |
| 333 | success: "#62a504", |
| 334 | text: "#ffffff", |
| 335 | textOnBrand: "#ffffff", |
| 336 | videoBg: "#191919", |
| 337 | warning: "#ffc107", |
| 338 | }, |
| 339 | logo: "", |
| 340 | spacingBase: 4, |
| 341 | theme: "dark", |
| 342 | }, |
| 343 | configDiff: {}, |
| 344 | }); |
| 345 | |
| 346 | /** |
| 347 | * The default permissions used when `permissions` is omitted: a conservative |
| 348 | * attendee role — chat, polls, and media production allowed; recording, |
| 349 | * livestreaming, and moderation denied. |
| 350 | */ |
| 351 | export const defaultRealtimeKitPresetPermissions = (): PresetPermissions => ({ |
| 352 | acceptWaitingRequests: false, |
| 353 | canAcceptProductionRequests: false, |
| 354 | canChangeParticipantPermissions: false, |
| 355 | canEditDisplayName: false, |
| 356 | canLivestream: false, |
| 357 | canRecord: false, |
| 358 | canSpotlight: false, |
| 359 | chat: { |
| 360 | private: { canReceive: true, canSend: true, files: true, text: true }, |
| 361 | public: { canSend: true, files: true, text: true }, |
| 362 | }, |
| 363 | connectedMeetings: { |
| 364 | canAlterConnectedMeetings: false, |
| 365 | canSwitchConnectedMeetings: false, |
| 366 | canSwitchToParentMeeting: false, |
| 367 | }, |
| 368 | disableParticipantAudio: false, |
| 369 | disableParticipantScreensharing: false, |
| 370 | disableParticipantVideo: false, |
| 371 | hiddenParticipant: false, |
| 372 | kickParticipant: false, |
| 373 | media: { |
| 374 | audio: { canProduce: "ALLOWED" }, |
| 375 | screenshare: { canProduce: "ALLOWED" }, |
| 376 | video: { canProduce: "ALLOWED" }, |
| 377 | }, |
| 378 | pinParticipant: false, |
| 379 | plugins: { |
| 380 | canClose: true, |
| 381 | canEditConfig: true, |
| 382 | canStart: true, |
| 383 | config: {}, |
| 384 | }, |
| 385 | polls: { canCreate: true, canView: true, canVote: true }, |
| 386 | recorderType: "NONE", |
| 387 | showParticipantList: true, |
| 388 | waitingRoomType: "SKIP", |
| 389 | }); |
| 390 | |
| 391 | export const PresetProvider = () => |
| 392 | Provider.succeed(Preset, { |
| 393 | stables: ["presetId", "accountId", "appId"], |
| 394 | diff: Effect.fn(function* ({ olds, news, output }) { |
| 395 | if (!isResolved(news)) return undefined; |
| 396 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 397 | if ((output?.accountId ?? accountId) !== accountId) { |
| 398 | return { action: "replace" } as const; |
| 399 | } |
| 400 | // The app is a path parameter — a preset cannot move between apps in |
| 401 | // place. By diff time both sides are resolved strings. |
| 402 | const oldAppId = output?.appId ?? olds?.appId; |
| 403 | if ( |
| 404 | typeof oldAppId === "string" && |
| 405 | typeof news.appId === "string" && |
| 406 | oldAppId !== news.appId |
| 407 | ) { |
| 408 | return { action: "replace" } as const; |
| 409 | } |
| 410 | return undefined; |
| 411 | }), |
| 412 | read: Effect.fn(function* ({ id, olds, output }) { |
| 413 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 414 | const acct = output?.accountId ?? accountId; |
| 415 | const appId = output?.appId ?? (olds?.appId as string | undefined); |
| 416 | if (appId === undefined) return undefined; |
| 417 | |
| 418 | if (output?.presetId) { |
| 419 | const observed = yield* getPreset(acct, appId, output.presetId); |
| 420 | return observed ? toAttributes(observed, acct, appId) : undefined; |
| 421 | } |
| 422 | // Cold read — recover from lost state by matching the deterministic |
| 423 | // physical name. Names are not unique on Cloudflare's side; an exact |
| 424 | // match on our generated/explicit name is the best identity we have. |
| 425 | const name = yield* createPresetName(id, olds?.name); |
| 426 | const match = yield* findByName(acct, appId, name); |
| 427 | if (match?.id) { |
| 428 | const observed = yield* getPreset(acct, appId, match.id); |
| 429 | return observed ? toAttributes(observed, acct, appId) : undefined; |
| 430 | } |
| 431 | return undefined; |
| 432 | }), |
| 433 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 434 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 435 | const appId = news.appId as string; |
| 436 | const name = yield* createPresetName(id, news.name); |
| 437 | const desired = { |
| 438 | name, |
| 439 | config: news.config ?? defaultRealtimeKitPresetConfig(), |
| 440 | ui: withUiDefaults(news.ui), |
| 441 | permissions: withPermissionsDefaults(news.permissions), |
| 442 | }; |
| 443 | |
| 444 | // Observe — the presetId cached on `output` is a hint, not a |
| 445 | // guarantee: a missing preset falls through and we recreate. |
| 446 | const observed = output?.presetId |
| 447 | ? yield* getPreset(output.accountId ?? accountId, appId, output.presetId) |
| 448 | : undefined; |
| 449 | |
| 450 | if (!observed) { |
| 451 | // Ensure — greenfield (or out-of-band delete): create with the full |
| 452 | // desired body. The API rejects a duplicate name in the same app |
| 453 | // with a 409 (`RealtimeKitPresetExists`); this happens when a prior |
| 454 | // run leaked a same-named preset (lost state) or when a retried |
| 455 | // create races a 500 that actually persisted. Adopt the existing |
| 456 | // preset by name and converge it to the desired body instead of |
| 457 | // leaking / failing. |
| 458 | const created = yield* realtimeKit |
| 459 | .createPreset({ accountId, appId, ...desired }) |
| 460 | .pipe(Effect.catchTag("RealtimeKitPresetExists", () => Effect.undefined)); |
| 461 | if (created) { |
| 462 | return toAttributes(created.data, accountId, appId); |
| 463 | } |
| 464 | const existing = yield* findByName(accountId, appId, name); |
| 465 | if (!existing?.id) { |
| 466 | // Conflict reported but the preset isn't visible yet — let the |
| 467 | // engine retry the reconcile rather than silently succeeding. |
| 468 | return yield* realtimeKit |
| 469 | .createPreset({ accountId, appId, ...desired }) |
| 470 | .pipe(Effect.map((res) => toAttributes(res.data, accountId, appId))); |
| 471 | } |
| 472 | yield* realtimeKit.patchPreset({ |
| 473 | accountId, |
| 474 | appId, |
| 475 | presetId: existing.id, |
| 476 | ...desired, |
| 477 | }); |
| 478 | const adopted = yield* realtimeKit.getPresetByIdPreset({ |
| 479 | accountId, |
| 480 | appId, |
| 481 | presetId: existing.id, |
| 482 | }); |
| 483 | return toAttributes(adopted.data, accountId, appId); |
| 484 | } |
| 485 | |
| 486 | // Sync — diff what the user asked for against observed cloud state. |
| 487 | // The API fills/echoes extra server-side fields (e.g. `simulcast`), |
| 488 | // so compare only the desired keys against the observed echo. |
| 489 | if (subsetEquals(desired, observed)) { |
| 490 | return toAttributes(observed, accountId, appId); |
| 491 | } |
| 492 | yield* realtimeKit.patchPreset({ |
| 493 | accountId, |
| 494 | appId, |
| 495 | presetId: observed.id, |
| 496 | ...desired, |
| 497 | }); |
| 498 | // The PATCH response omits the preset id — re-read for fresh state. |
| 499 | const fresh = yield* realtimeKit.getPresetByIdPreset({ |
| 500 | accountId, |
| 501 | appId, |
| 502 | presetId: observed.id, |
| 503 | }); |
| 504 | return toAttributes(fresh.data, accountId, appId); |
| 505 | }), |
| 506 | delete: Effect.fn(function* ({ output }) { |
| 507 | yield* realtimeKit |
| 508 | .deletePreset({ |
| 509 | accountId: output.accountId, |
| 510 | appId: output.appId, |
| 511 | presetId: output.presetId, |
| 512 | }) |
| 513 | .pipe(Effect.catchTag("RealtimeKitPresetNotFound", () => Effect.void)); |
| 514 | }), |
| 515 | // Presets are sub-resources of a RealtimeKit app. There is no |
| 516 | // account-wide preset enumeration API, so fan out: list every app in the |
| 517 | // account, then list every preset within each app. The per-app preset |
| 518 | // list returns only a slim `{ id, name }` shape, so each row is hydrated |
| 519 | // via `getPresetByIdPreset` into the full `read` Attributes shape. |
| 520 | list: Effect.fn(function* () { |
| 521 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 522 | const apps = yield* listAllApps(accountId); |
| 523 | const rows = yield* Effect.forEach( |
| 524 | apps, |
| 525 | (app) => |
| 526 | Effect.gen(function* () { |
| 527 | const appId = app.id; |
| 528 | if (!appId) return []; |
| 529 | const presets = yield* listAllPresets(accountId, appId); |
| 530 | const hydrated = yield* Effect.forEach( |
| 531 | presets, |
| 532 | (preset) => |
| 533 | preset.id |
| 534 | ? getPreset(accountId, appId, preset.id).pipe( |
| 535 | Effect.map((observed) => |
| 536 | observed ? toAttributes(observed, accountId, appId) : undefined, |
| 537 | ), |
| 538 | ) |
| 539 | : Effect.undefined, |
| 540 | { concurrency: 10 }, |
| 541 | ); |
| 542 | return hydrated.filter((row): row is PresetAttributes => row !== undefined); |
| 543 | }), |
| 544 | { concurrency: 10 }, |
| 545 | ); |
| 546 | return rows.flat(); |
| 547 | }), |
| 548 | }); |
| 549 | |
| 550 | const LIST_PER_PAGE = 100; |
| 551 | |
| 552 | /** |
| 553 | * Exhaustively enumerate every RealtimeKit app in the account. The list op is |
| 554 | * not generated as a paginated method, so fetch the first page, derive the |
| 555 | * page count from `paging.totalCount`, then fan out the remaining pages. |
| 556 | */ |
| 557 | const listAllApps = (accountId: string) => |
| 558 | Effect.gen(function* () { |
| 559 | const first = yield* realtimeKit.getApp({ |
| 560 | accountId, |
| 561 | pageNo: 1, |
| 562 | perPage: LIST_PER_PAGE, |
| 563 | }); |
| 564 | const apps = (first.data ?? []).filter((a): a is NonNullable<typeof a> => a !== null); |
| 565 | const total = first.paging?.totalCount ?? apps.length; |
| 566 | const pages = Math.ceil(total / LIST_PER_PAGE); |
| 567 | if (pages <= 1) return apps; |
| 568 | const rest = yield* Effect.forEach( |
| 569 | Array.from({ length: pages - 1 }, (_, i) => i + 2), |
| 570 | (pageNo) => |
| 571 | realtimeKit |
| 572 | .getApp({ accountId, pageNo, perPage: LIST_PER_PAGE }) |
| 573 | .pipe( |
| 574 | Effect.map((res) => |
| 575 | (res.data ?? []).filter((a): a is NonNullable<typeof a> => a !== null), |
| 576 | ), |
| 577 | ), |
| 578 | { concurrency: 10 }, |
| 579 | ); |
| 580 | return [...apps, ...rest.flat()]; |
| 581 | }); |
| 582 | |
| 583 | /** |
| 584 | * Exhaustively enumerate every preset within a single app, paginating off |
| 585 | * `paging.totalCount` the same way as {@link listAllApps}. |
| 586 | */ |
| 587 | const listAllPresets = (accountId: string, appId: string) => |
| 588 | Effect.gen(function* () { |
| 589 | const first = yield* realtimeKit.getPreset({ |
| 590 | accountId, |
| 591 | appId, |
| 592 | pageNo: 1, |
| 593 | perPage: LIST_PER_PAGE, |
| 594 | }); |
| 595 | const presets = [...first.data]; |
| 596 | const total = first.paging?.totalCount ?? presets.length; |
| 597 | const pages = Math.ceil(total / LIST_PER_PAGE); |
| 598 | if (pages <= 1) return presets; |
| 599 | const rest = yield* Effect.forEach( |
| 600 | Array.from({ length: pages - 1 }, (_, i) => i + 2), |
| 601 | (pageNo) => |
| 602 | realtimeKit |
| 603 | .getPreset({ accountId, appId, pageNo, perPage: LIST_PER_PAGE }) |
| 604 | .pipe(Effect.map((res) => [...res.data])), |
| 605 | { concurrency: 10 }, |
| 606 | ); |
| 607 | return [...presets, ...rest.flat()]; |
| 608 | }); |
| 609 | |
| 610 | type ObservedPreset = realtimeKit.GetPresetByIdPresetResponse["data"]; |
| 611 | |
| 612 | /** |
| 613 | * Read a preset by id, mapping "gone" (`RealtimeKitPresetNotFound`, |
| 614 | * HTTP 404) to `undefined`. |
| 615 | */ |
| 616 | const getPreset = (accountId: string, appId: string, presetId: string) => |
| 617 | realtimeKit.getPresetByIdPreset({ accountId, appId, presetId }).pipe( |
| 618 | Effect.map((res) => res.data), |
| 619 | Effect.catchTag("RealtimeKitPresetNotFound", () => Effect.undefined), |
| 620 | ); |
| 621 | |
| 622 | /** |
| 623 | * Find a preset by exact name in the app's preset list. If several presets |
| 624 | * carry the same name, pick the oldest for determinism. |
| 625 | */ |
| 626 | const findByName = (accountId: string, appId: string, name: string) => |
| 627 | realtimeKit.getPreset({ accountId, appId, perPage: 100 }).pipe( |
| 628 | Effect.map((list) => |
| 629 | [...list.data] |
| 630 | .filter((p) => p.name === name) |
| 631 | .sort((a, b) => (a.createdAt ?? "").localeCompare(b.createdAt ?? "")) |
| 632 | .at(0), |
| 633 | ), |
| 634 | ); |
| 635 | |
| 636 | const createPresetName = (id: string, name: string | undefined) => |
| 637 | Effect.gen(function* () { |
| 638 | return name ?? (yield* createPhysicalName({ id, lowercase: true })); |
| 639 | }); |
| 640 | |
| 641 | const withUiDefaults = (ui: PresetUi | undefined): PresetUi & { configDiff: unknown } => { |
| 642 | const base = ui ?? defaultRealtimeKitPresetUi(); |
| 643 | // `config_diff` is required by the API even though it's incidental — |
| 644 | // default it so users don't have to care. |
| 645 | return { ...base, configDiff: base.configDiff ?? {} }; |
| 646 | }; |
| 647 | |
| 648 | /** |
| 649 | * Fill `plugins.config` (required by the create API even though it's |
| 650 | * incidental) so users don't have to care. The return type intentionally |
| 651 | * stays inferred: `CreatePresetRequest` requires `plugins.config` to be |
| 652 | * present, and annotating `PresetPermissions` (where it is |
| 653 | * optional) would erase the guarantee the literal provides. |
| 654 | */ |
| 655 | const withPermissionsDefaults = (permissions: PresetPermissions | undefined) => { |
| 656 | const base = permissions ?? defaultRealtimeKitPresetPermissions(); |
| 657 | return { |
| 658 | ...base, |
| 659 | plugins: { |
| 660 | ...base.plugins, |
| 661 | config: (base.plugins.config ?? {}) as unknown, |
| 662 | }, |
| 663 | }; |
| 664 | }; |
| 665 | |
| 666 | /** |
| 667 | * Deep "is `desired` a subset of `observed`" comparison. The RealtimeKit |
| 668 | * API echoes extra server-computed fields (e.g. `simulcast`) alongside what |
| 669 | * we sent, so a strict deep-equal would always report drift. |
| 670 | */ |
| 671 | const subsetEquals = (desired: unknown, observed: unknown): boolean => { |
| 672 | if ( |
| 673 | typeof desired === "object" && |
| 674 | desired !== null && |
| 675 | typeof observed === "object" && |
| 676 | observed !== null && |
| 677 | !Array.isArray(desired) && |
| 678 | !Array.isArray(observed) |
| 679 | ) { |
| 680 | return Object.entries(desired as Record<string, unknown>).every( |
| 681 | ([key, value]) => |
| 682 | value === undefined || subsetEquals(value, (observed as Record<string, unknown>)[key]), |
| 683 | ); |
| 684 | } |
| 685 | if (Array.isArray(desired) && Array.isArray(observed)) { |
| 686 | return ( |
| 687 | desired.length === observed.length && |
| 688 | desired.every((value, i) => subsetEquals(value, observed[i])) |
| 689 | ); |
| 690 | } |
| 691 | return desired === observed; |
| 692 | }; |
| 693 | |
| 694 | const toAttributes = ( |
| 695 | preset: ObservedPreset, |
| 696 | accountId: string, |
| 697 | appId: string, |
| 698 | ): PresetAttributes => ({ |
| 699 | presetId: preset.id, |
| 700 | accountId, |
| 701 | appId, |
| 702 | name: preset.name, |
| 703 | // Distilled widens generated string enums to open unions (`string & {}`) |
| 704 | // and marks echoes readonly — re-shape into our prop types. |
| 705 | config: { |
| 706 | maxScreenshareCount: preset.config.maxScreenshareCount, |
| 707 | maxVideoStreams: { |
| 708 | desktop: preset.config.maxVideoStreams.desktop, |
| 709 | mobile: preset.config.maxVideoStreams.mobile, |
| 710 | }, |
| 711 | media: { |
| 712 | screenshare: { |
| 713 | frameRate: preset.config.media.screenshare.frameRate, |
| 714 | quality: preset.config.media.screenshare.quality as MediaQuality, |
| 715 | }, |
| 716 | video: { |
| 717 | frameRate: preset.config.media.video.frameRate, |
| 718 | quality: preset.config.media.video.quality as MediaQuality, |
| 719 | }, |
| 720 | ...(preset.config.media.audio |
| 721 | ? { |
| 722 | audio: { |
| 723 | ...(preset.config.media.audio.enableHighBitrate != null |
| 724 | ? { |
| 725 | enableHighBitrate: preset.config.media.audio.enableHighBitrate, |
| 726 | } |
| 727 | : {}), |
| 728 | ...(preset.config.media.audio.enableStereo != null |
| 729 | ? { enableStereo: preset.config.media.audio.enableStereo } |
| 730 | : {}), |
| 731 | }, |
| 732 | } |
| 733 | : {}), |
| 734 | }, |
| 735 | viewType: preset.config.viewType as ViewType, |
| 736 | }, |
| 737 | ui: { |
| 738 | designTokens: { |
| 739 | borderRadius: preset.ui.designTokens.borderRadius as BorderRadius, |
| 740 | borderWidth: preset.ui.designTokens.borderWidth as BorderWidth, |
| 741 | colors: { |
| 742 | background: { ...preset.ui.designTokens.colors.background }, |
| 743 | brand: { ...preset.ui.designTokens.colors.brand }, |
| 744 | danger: preset.ui.designTokens.colors.danger, |
| 745 | success: preset.ui.designTokens.colors.success, |
| 746 | text: preset.ui.designTokens.colors.text, |
| 747 | textOnBrand: preset.ui.designTokens.colors.textOnBrand, |
| 748 | videoBg: preset.ui.designTokens.colors.videoBg, |
| 749 | warning: preset.ui.designTokens.colors.warning, |
| 750 | }, |
| 751 | logo: preset.ui.designTokens.logo ?? "", |
| 752 | spacingBase: preset.ui.designTokens.spacingBase, |
| 753 | theme: preset.ui.designTokens.theme as Theme, |
| 754 | }, |
| 755 | configDiff: preset.ui.configDiff ?? {}, |
| 756 | }, |
| 757 | permissions: preset.permissions |
| 758 | ? { |
| 759 | acceptWaitingRequests: preset.permissions.acceptWaitingRequests, |
| 760 | canAcceptProductionRequests: preset.permissions.canAcceptProductionRequests, |
| 761 | canChangeParticipantPermissions: preset.permissions.canChangeParticipantPermissions, |
| 762 | canEditDisplayName: preset.permissions.canEditDisplayName, |
| 763 | canLivestream: preset.permissions.canLivestream, |
| 764 | canRecord: preset.permissions.canRecord, |
| 765 | canSpotlight: preset.permissions.canSpotlight, |
| 766 | chat: { |
| 767 | private: { ...preset.permissions.chat.private }, |
| 768 | public: { ...preset.permissions.chat.public }, |
| 769 | }, |
| 770 | connectedMeetings: { ...preset.permissions.connectedMeetings }, |
| 771 | disableParticipantAudio: preset.permissions.disableParticipantAudio, |
| 772 | disableParticipantScreensharing: preset.permissions.disableParticipantScreensharing, |
| 773 | disableParticipantVideo: preset.permissions.disableParticipantVideo, |
| 774 | hiddenParticipant: preset.permissions.hiddenParticipant, |
| 775 | kickParticipant: preset.permissions.kickParticipant, |
| 776 | media: { |
| 777 | audio: { |
| 778 | canProduce: preset.permissions.media.audio.canProduce as CanProduce, |
| 779 | }, |
| 780 | screenshare: { |
| 781 | canProduce: preset.permissions.media.screenshare.canProduce as CanProduce, |
| 782 | }, |
| 783 | video: { |
| 784 | canProduce: preset.permissions.media.video.canProduce as CanProduce, |
| 785 | }, |
| 786 | }, |
| 787 | pinParticipant: preset.permissions.pinParticipant, |
| 788 | plugins: { |
| 789 | canClose: preset.permissions.plugins.canClose, |
| 790 | canEditConfig: preset.permissions.plugins.canEditConfig, |
| 791 | canStart: preset.permissions.plugins.canStart, |
| 792 | config: preset.permissions.plugins.config ?? {}, |
| 793 | }, |
| 794 | polls: { ...preset.permissions.polls }, |
| 795 | recorderType: preset.permissions.recorderType as RecorderType, |
| 796 | showParticipantList: preset.permissions.showParticipantList, |
| 797 | waitingRoomType: preset.permissions.waitingRoomType as WaitingRoomType, |
| 798 | ...(preset.permissions.isRecorder != null |
| 799 | ? { isRecorder: preset.permissions.isRecorder } |
| 800 | : {}), |
| 801 | } |
| 802 | : undefined, |
| 803 | }); |