@devries-cameron20 / t3code Mirror · read-only
Fork 0

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, 04:45 UTC

main
ts 355 lines 12 KB
Raw
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.Webhook" as const;
12 type TypeId = typeof TypeId;
13
14 /**
15 * Event that can trigger a RealtimeKit webhook.
16 */
17 export type WebhookEvent =
18 | "meeting.started"
19 | "meeting.ended"
20 | "meeting.participantJoined"
21 | "meeting.participantLeft"
22 | "meeting.chatSynced"
23 | "recording.statusUpdate"
24 | "livestreaming.statusUpdate"
25 | "meeting.transcript"
26 | "meeting.summary";
27
28 export type WebhookProps = {
29 /**
30 * The RealtimeKit app the webhook belongs to. Changing the app triggers a
31 * replacement.
32 */
33 appId: string;
34 /**
35 * Human readable webhook name. If omitted, a unique name is generated from
36 * the app, stage, and logical ID.
37 * @default ${app}-${stage}-${id}
38 */
39 name?: string;
40 /**
41 * URL this webhook will send events to. Often a deployed Worker URL.
42 */
43 url: string;
44 /**
45 * Events that trigger this webhook.
46 */
47 events: WebhookEvent[];
48 /**
49 * Whether the webhook is active.
50 * @default true
51 */
52 enabled?: boolean;
53 };
54
55 export type WebhookAttributes = {
56 /**
57 * Server-generated webhook identifier. Stable across updates.
58 */
59 webhookId: string;
60 /**
61 * The Cloudflare account the webhook belongs to.
62 */
63 accountId: string;
64 /**
65 * The RealtimeKit app the webhook belongs to.
66 */
67 appId: string;
68 /**
69 * Human readable webhook name.
70 */
71 name: string;
72 /**
73 * URL the webhook sends events to.
74 */
75 url: string;
76 /**
77 * Events that trigger this webhook.
78 */
79 events: WebhookEvent[];
80 /**
81 * Whether the webhook is active.
82 */
83 enabled: boolean;
84 /**
85 * When the webhook was created.
86 */
87 createdAt: string;
88 /**
89 * When the webhook was last modified.
90 */
91 updatedAt: string;
92 };
93
94 export type Webhook = Resource<TypeId, WebhookProps, WebhookAttributes, never, Providers>;
95
96 /**
97 * A Cloudflare RealtimeKit webhook — receives meeting, recording,
98 * livestream, transcript, and summary events for a RealtimeKit app.
99 *
100 * Name, URL, events, and enablement are all mutable in place; only moving
101 * the webhook to a different app forces a replacement.
102 * ### Creating a Webhook
103 * **Example:** Meeting lifecycle events
104 * ```typescript
105 * const app = yield* Cloudflare.RealtimeKit.App("Meetings", {});
106 *
107 * const webhook = yield* Cloudflare.RealtimeKit.Webhook("Lifecycle", {
108 * appId: app.appId,
109 * url: "https://example.com/webhook",
110 * events: ["meeting.started", "meeting.ended"],
111 * });
112 * ```
113 *
114 * **Example:** Recording events to a Worker
115 * ```typescript
116 * const webhook = yield* Cloudflare.RealtimeKit.Webhook("Recordings", {
117 * appId: app.appId,
118 * url: worker.url,
119 * events: ["recording.statusUpdate"],
120 * });
121 * ```
122 *
123 * ### Updating a Webhook
124 * **Example:** Pause delivery without deleting
125 * ```typescript
126 * const webhook = yield* Cloudflare.RealtimeKit.Webhook("Lifecycle", {
127 * appId: app.appId,
128 * url: "https://example.com/webhook",
129 * events: ["meeting.started", "meeting.ended"],
130 * enabled: false,
131 * });
132 * ```
133 *
134 * @see https://developers.cloudflare.com/realtime/realtimekit/
135 *
136 * @resource
137 * @product Realtime Kit
138 * @category Media
139 */
140 export const Webhook = Resource<Webhook>(TypeId);
141
142 /**
143 * Returns true if the given value is a Webhook resource.
144 */
145 export const isWebhook = (value: unknown): value is Webhook =>
146 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
147
148 export const WebhookProvider = () =>
149 Provider.succeed(Webhook, {
150 stables: ["webhookId", "accountId", "appId", "createdAt"],
151 diff: Effect.fn(function* ({ olds, news, output }) {
152 if (!isResolved(news)) return undefined;
153 const { accountId } = yield* yield* CloudflareEnvironment;
154 if ((output?.accountId ?? accountId) !== accountId) {
155 return { action: "replace" } as const;
156 }
157 // The app is a path parameter — a webhook cannot move between apps in
158 // place. By diff time both sides are resolved strings.
159 const oldAppId = output?.appId ?? olds?.appId;
160 if (
161 typeof oldAppId === "string" &&
162 typeof news.appId === "string" &&
163 oldAppId !== news.appId
164 ) {
165 return { action: "replace" } as const;
166 }
167 return undefined;
168 }),
169 read: Effect.fn(function* ({ id, olds, output }) {
170 const { accountId } = yield* yield* CloudflareEnvironment;
171 const acct = output?.accountId ?? accountId;
172 const appId = output?.appId ?? (olds?.appId as string | undefined);
173 if (appId === undefined) return undefined;
174
175 if (output?.webhookId) {
176 const observed = yield* getWebhook(acct, appId, output.webhookId);
177 return observed ? toAttributes(observed, acct, appId) : undefined;
178 }
179 // Cold read — recover from lost state by matching the deterministic
180 // physical name. Names are not unique on Cloudflare's side; an exact
181 // match on our generated/explicit name is the best identity we have.
182 const name = yield* createWebhookName(id, olds?.name);
183 const match = yield* findByName(acct, appId, name);
184 return match ? toAttributes(match, acct, appId) : undefined;
185 }),
186 reconcile: Effect.fn(function* ({ id, news, output }) {
187 const { accountId } = yield* yield* CloudflareEnvironment;
188 const appId = news.appId as string;
189 const name = yield* createWebhookName(id, news.name);
190 const desired = {
191 name,
192 url: news.url as string,
193 events: [...news.events],
194 enabled: news.enabled ?? true,
195 };
196
197 // Observe — the webhookId cached on `output` is a hint, not a
198 // guarantee: a missing webhook falls through and we recreate.
199 const observed = output?.webhookId
200 ? yield* getWebhook(output.accountId ?? accountId, appId, output.webhookId)
201 : undefined;
202
203 if (!observed) {
204 // Ensure — greenfield (or out-of-band delete): create with the full
205 // desired body. The API rejects a duplicate name in the same app
206 // with a 409 (`RealtimeKitWebhookExists`); this happens when a prior
207 // run leaked a same-named webhook (lost state) or when a retried
208 // create races a 500 that actually persisted. Adopt the existing
209 // webhook by name and converge it to the desired body instead of
210 // leaking / failing.
211 const created = yield* realtimeKit
212 .createWebhookWebhook({ accountId, appId, ...desired })
213 .pipe(Effect.catchTag("RealtimeKitWebhookExists", () => Effect.undefined));
214 if (created) {
215 return toAttributes(created.data, accountId, appId);
216 }
217 const existing = yield* findByName(accountId, appId, name);
218 if (!existing) {
219 // Conflict reported but the webhook isn't visible yet — let the
220 // engine retry the reconcile rather than silently succeeding.
221 return yield* realtimeKit
222 .createWebhookWebhook({ accountId, appId, ...desired })
223 .pipe(Effect.map((res) => toAttributes(res.data, accountId, appId)));
224 }
225 yield* realtimeKit.replaceWebhookWebhook({
226 accountId,
227 appId,
228 webhookId: existing.id,
229 ...desired,
230 });
231 const adopted = yield* realtimeKit.getWebhookByIdWebhook({
232 accountId,
233 appId,
234 webhookId: existing.id,
235 });
236 return toAttributes(adopted.data, accountId, appId);
237 }
238
239 // Sync — diff observed cloud state against desired; the update API is
240 // a PUT that takes the full body, so send everything, but skip the
241 // call entirely on a no-op.
242 const observedShape = {
243 name: observed.name,
244 url: observed.url,
245 events: [...observed.events].sort(),
246 enabled: observed.enabled,
247 };
248 const desiredShape = { ...desired, events: [...desired.events].sort() };
249 if (JSON.stringify(observedShape) === JSON.stringify(desiredShape)) {
250 return toAttributes(observed, accountId, appId);
251 }
252 yield* realtimeKit.replaceWebhookWebhook({
253 accountId,
254 appId,
255 webhookId: observed.id,
256 ...desired,
257 });
258 // The PUT response is a partial echo — re-read for fresh attributes.
259 const fresh = yield* realtimeKit.getWebhookByIdWebhook({
260 accountId,
261 appId,
262 webhookId: observed.id,
263 });
264 return toAttributes(fresh.data, accountId, appId);
265 }),
266 delete: Effect.fn(function* ({ output }) {
267 yield* realtimeKit
268 .deleteWebhookWebhook({
269 accountId: output.accountId,
270 appId: output.appId,
271 webhookId: output.webhookId,
272 })
273 .pipe(Effect.catchTag("RealtimeKitWebhookNotFound", () => Effect.void));
274 }),
275 // Webhooks are keyed by {accountId, appId, webhookId} with no account-wide
276 // enumeration API, so fan out: enumerate every RealtimeKit app in the
277 // account, then list each app's webhooks and flatten. The apps endpoint
278 // 403s (`Forbidden`) when RealtimeKit isn't enabled on the account — an
279 // unentitled account simply has no webhooks. Neither endpoint paginates.
280 list: Effect.fn(function* () {
281 const { accountId } = yield* yield* CloudflareEnvironment;
282 const appIds = yield* realtimeKit.getApp({ accountId }).pipe(
283 Effect.map((apps) =>
284 (apps.data ?? [])
285 .map((app) => app?.id)
286 .filter((id): id is string => typeof id === "string"),
287 ),
288 Effect.catchTag("Forbidden", () => Effect.succeed([] as string[])),
289 );
290 const perApp = yield* Effect.forEach(
291 appIds,
292 (appId) =>
293 realtimeKit.getWebhooksWebhook({ accountId, appId }).pipe(
294 Effect.map((res) => res.data.map((webhook) => toAttributes(webhook, accountId, appId))),
295 // An app with no webhooks 404s (`RealtimeKitWebhookNotFound`).
296 Effect.catchTag("RealtimeKitWebhookNotFound", () =>
297 Effect.succeed([] as WebhookAttributes[]),
298 ),
299 ),
300 { concurrency: 10 },
301 );
302 return perApp.flat();
303 }),
304 });
305
306 type ObservedWebhook = realtimeKit.GetWebhookByIdWebhookResponse["data"];
307
308 /**
309 * Read a webhook by id, mapping "gone" (`RealtimeKitWebhookNotFound`,
310 * HTTP 404) to `undefined`.
311 */
312 const getWebhook = (accountId: string, appId: string, webhookId: string) =>
313 realtimeKit.getWebhookByIdWebhook({ accountId, appId, webhookId }).pipe(
314 Effect.map((res) => res.data),
315 Effect.catchTag("RealtimeKitWebhookNotFound", () => Effect.undefined),
316 );
317
318 /**
319 * Find a webhook by exact name. The list endpoint 404s
320 * (`RealtimeKitWebhookNotFound`) when the app has no webhooks at all —
321 * treat that as an empty list. If several webhooks carry the same name,
322 * pick the oldest for determinism.
323 */
324 const findByName = (accountId: string, appId: string, name: string) =>
325 realtimeKit.getWebhooksWebhook({ accountId, appId }).pipe(
326 Effect.map((list) =>
327 [...list.data]
328 .filter((w) => w.name === name)
329 .sort((a, b) => a.createdAt.localeCompare(b.createdAt))
330 .at(0),
331 ),
332 Effect.catchTag("RealtimeKitWebhookNotFound", () => Effect.undefined),
333 );
334
335 const createWebhookName = (id: string, name: string | undefined) =>
336 Effect.gen(function* () {
337 return name ?? (yield* createPhysicalName({ id, lowercase: true }));
338 });
339
340 const toAttributes = (
341 webhook: ObservedWebhook,
342 accountId: string,
343 appId: string,
344 ): WebhookAttributes => ({
345 webhookId: webhook.id,
346 accountId,
347 appId,
348 name: webhook.name,
349 url: webhook.url,
350 // Distilled widens generated string enums to open unions (`string & {}`).
351 events: [...webhook.events] as WebhookEvent[],
352 enabled: webhook.enabled,
353 createdAt: webhook.createdAt,
354 updatedAt: webhook.updatedAt,
355 });