@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, 06:00 UTC

main
ts 197 lines 6.81 KB
Raw
1 import * as calls from "@distilled.cloud/cloudflare/calls";
2 import { createPhysicalName } from "alchemy/PhysicalName";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import * as Effect from "effect/Effect";
6 import * as Predicate from "effect/Predicate";
7 import * as Redacted from "effect/Redacted";
8 import * as Stream from "effect/Stream";
9 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
10 import type { Providers } from "../Providers.ts";
11
12 const TypeId = "Cloudflare.Calls.App" as const;
13 type TypeId = typeof TypeId;
14
15 export type AppProps = {
16 /**
17 * A short description of the app, not shown to end users and not unique.
18 * Mutable in place. If omitted, a unique name is generated from the app,
19 * stage, and logical ID.
20 * @default ${app}-${stage}-${id}
21 */
22 name?: string;
23 };
24
25 export type AppAttributes = {
26 /**
27 * Cloudflare-generated unique identifier for the app. Used in client SDK
28 * session URLs (`https://rtc.live.cloudflare.com/v1/apps/{appId}/...`).
29 */
30 appId: string;
31 /**
32 * The Cloudflare account the app belongs to.
33 */
34 accountId: string;
35 /**
36 * App secret (bearer token) used to authenticate against the Realtime SFU
37 * HTTPS API. Returned only at creation time and never re-readable — Alchemy
38 * persists it in state and carries it forward across updates.
39 */
40 secret: Redacted.Redacted<string>;
41 /**
42 * A short description of the app.
43 */
44 name: string;
45 /**
46 * When the app was created.
47 */
48 created: string;
49 /**
50 * When the app was last modified.
51 */
52 modified: string;
53 };
54
55 export type App = Resource<TypeId, AppProps, AppAttributes, never, Providers>;
56
57 /**
58 * A Cloudflare Realtime (formerly "Calls") SFU application.
59 *
60 * An app is the unit of isolation for Cloudflare's WebRTC SFU: clients
61 * connect to sessions scoped to the app's auto-assigned `appId`, and your
62 * backend authenticates management calls with the create-only `secret`
63 * (a bearer token). The only configurable property is the human-readable
64 * `name`, which is mutable in place.
65 * ### Creating an App
66 * **Example:** App with a generated name
67 * ```typescript
68 * const app = yield* Cloudflare.Calls.App("realtime", {});
69 * ```
70 *
71 * **Example:** App with an explicit name
72 * ```typescript
73 * const app = yield* Cloudflare.Calls.App("realtime", {
74 * name: "my-realtime-app",
75 * });
76 * ```
77 *
78 * ### Using the credentials
79 * **Example:** Passing the appId and secret to a backend
80 * ```typescript
81 * // appId is public — it appears in client session URLs:
82 * const appId = app.appId;
83 *
84 * // The secret is redacted — use it server-side as a bearer token
85 * // against https://rtc.live.cloudflare.com/v1/apps/{appId}/...
86 * const secret = app.secret; // Redacted<string>
87 * ```
88 *
89 * @see https://developers.cloudflare.com/realtime/
90 *
91 * @resource
92 * @product Calls
93 * @category Media
94 */
95 export const App = Resource<App>(TypeId);
96
97 /**
98 * Returns true if the given value is a App resource.
99 */
100 export const isApp = (value: unknown): value is App =>
101 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
102
103 export const AppProvider = () =>
104 Provider.succeed(App, {
105 stables: ["appId", "accountId", "secret", "created"],
106 list: Effect.fn(function* () {
107 const { accountId } = yield* yield* CloudflareEnvironment;
108 // Account-scoped collection: enumerate every Calls app under the
109 // account, exhaustively paginating `result`. The create-only secret
110 // is never returned by the list endpoint, so — matching `read` for a
111 // resource without prior state — hydrate it as an empty Redacted.
112 return yield* calls.listSfus.pages({ accountId }).pipe(
113 Stream.runCollect,
114 Effect.map((chunk) =>
115 Array.from(chunk).flatMap((page) =>
116 (page.result ?? []).map((app) => toAttributes(app, accountId, Redacted.make(""))),
117 ),
118 ),
119 );
120 }),
121 diff: Effect.fn(function* ({ output }) {
122 const { accountId } = yield* yield* CloudflareEnvironment;
123 if (output !== undefined && output.accountId !== accountId) {
124 return { action: "replace" } as const;
125 }
126 return undefined;
127 }),
128 read: Effect.fn(function* ({ output }) {
129 // The app secret is returned only at creation time, so an app cannot
130 // be re-hydrated without prior state — no cold read / adoption path.
131 if (!output?.appId) return undefined;
132 const observed = yield* getApp(output.accountId, output.appId);
133 return observed ? toAttributes(observed, output.accountId, output.secret) : undefined;
134 }),
135 reconcile: Effect.fn(function* ({ id, news, output }) {
136 const { accountId } = yield* yield* CloudflareEnvironment;
137 const name = yield* createAppName(id, news.name);
138
139 // Observe — the appId cached on `output` is a hint, not a guarantee:
140 // a missing app (code 20007) falls through and we recreate.
141 const observed = output?.appId
142 ? yield* getApp(output.accountId ?? accountId, output.appId)
143 : undefined;
144
145 if (!observed || !output) {
146 // Ensure — greenfield (or out-of-band delete): create and capture
147 // the create-only secret. Names are not unique on Cloudflare's
148 // side, so there is no AlreadyExists race to tolerate.
149 const created = yield* calls.createSfu({ accountId, name });
150 return toAttributes(created, accountId, Redacted.make(created.secret ?? ""));
151 }
152
153 // Sync — the only mutable aspect is `name`; diff observed cloud
154 // state against desired and skip the PUT entirely on a no-op.
155 if (observed.name === name) {
156 return toAttributes(observed, output.accountId, output.secret);
157 }
158 const updated = yield* calls.updateSfu({
159 accountId: output.accountId,
160 appId: output.appId,
161 name,
162 });
163 return toAttributes(updated, output.accountId, output.secret);
164 }),
165 delete: Effect.fn(function* ({ output }) {
166 yield* calls
167 .deleteSfu({ accountId: output.accountId, appId: output.appId })
168 .pipe(Effect.catchTag("CallsAppNotFound", () => Effect.void));
169 }),
170 });
171
172 /**
173 * Read an app by id, mapping "gone" (`CallsAppNotFound`, Cloudflare error
174 * code 20007) to `undefined`.
175 */
176 const getApp = (accountId: string, appId: string) =>
177 calls
178 .getSfu({ accountId, appId })
179 .pipe(Effect.catchTag("CallsAppNotFound", () => Effect.undefined));
180
181 const createAppName = (id: string, name: string | undefined) =>
182 Effect.gen(function* () {
183 return name ?? (yield* createPhysicalName({ id, lowercase: true }));
184 });
185
186 const toAttributes = (
187 app: calls.GetSfuResponse | calls.CreateSfuResponse | calls.UpdateSfuResponse,
188 accountId: string,
189 secret: Redacted.Redacted<string>,
190 ): AppAttributes => ({
191 appId: app.uid ?? "",
192 accountId,
193 secret,
194 name: app.name ?? "",
195 created: app.created ?? "",
196 modified: app.modified ?? "",
197 });