@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 277 lines 10 KB
Raw
1 import * as realtimeKit from "@distilled.cloud/cloudflare/realtime-kit";
2 import { createPhysicalName } from "alchemy/PhysicalName";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import * as Data from "effect/Data";
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.App" as const;
12 type TypeId = typeof TypeId;
13
14 export type AppProps = {
15 /**
16 * Human readable app name. App names are not unique on Cloudflare's side.
17 * If omitted, a unique name is generated from the app, stage, and logical
18 * ID.
19 *
20 * RealtimeKit currently ships no update API, so the name cannot be changed
21 * after creation — and no delete API either, so a name change cannot be
22 * modeled as a replacement (the old app could never be removed). Changing
23 * this property fails the deploy.
24 * @default ${app}-${stage}-${id}
25 */
26 name?: string;
27 };
28
29 export type AppAttributes = {
30 /**
31 * Server-generated app identifier (also called the organization id).
32 * Stable for the lifetime of the app.
33 */
34 appId: string;
35 /**
36 * The Cloudflare account the app belongs to.
37 */
38 accountId: string;
39 /**
40 * Human readable app name.
41 */
42 name: string;
43 /**
44 * When the app was created.
45 */
46 createdAt: string;
47 };
48
49 export type App = Resource<TypeId, AppProps, AppAttributes, never, Providers>;
50
51 /**
52 * A Cloudflare RealtimeKit app — the organizational container for RealtimeKit
53 * meetings, presets, and webhooks.
54 *
55 * RealtimeKit (the acquired Dyte platform) is in beta and must be enabled on
56 * the account. The API is create-only today: there is no update and no delete
57 * endpoint. Destroying the resource therefore only forgets the app from state
58 * (with a warning) — the app itself remains on the account until Cloudflare
59 * ships a delete API. Because of this, an existing app with the same name is
60 * adopted rather than duplicated.
61 * ### Creating an App
62 * **Example:** Basic app
63 * ```typescript
64 * const app = yield* Cloudflare.RealtimeKit.App("Meetings", {
65 * name: "my-meetings-app",
66 * });
67 * ```
68 *
69 * **Example:** Child resources
70 * ```typescript
71 * const app = yield* Cloudflare.RealtimeKit.App("Meetings", {});
72 *
73 * const webhook = yield* Cloudflare.RealtimeKit.Webhook("Events", {
74 * appId: app.appId,
75 * url: "https://example.com/webhook",
76 * events: ["meeting.started", "meeting.ended"],
77 * });
78 * ```
79 *
80 * @see https://developers.cloudflare.com/realtime/realtimekit/
81 *
82 * @resource
83 * @product Realtime Kit
84 * @category Media
85 */
86 export const App = Resource<App>(TypeId);
87
88 /**
89 * Returns true if the given value is a App resource.
90 */
91 export const isApp = (value: unknown): value is App =>
92 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
93
94 export const AppProvider = () =>
95 Provider.succeed(App, {
96 stables: ["appId", "accountId", "name", "createdAt"],
97 diff: Effect.fn(function* ({ olds, news, output }) {
98 const { accountId } = yield* yield* CloudflareEnvironment;
99 if ((output?.accountId ?? accountId) !== accountId) {
100 return { action: "replace" } as const;
101 }
102 // No update API and no delete API — a name change can neither be
103 // applied in place nor modeled as a replacement (the old app could
104 // never be removed). Reconcile fails loudly on a drifted name; diff
105 // lets the default update flow surface that error.
106 void olds;
107 void news;
108 return undefined;
109 }),
110 read: Effect.fn(function* ({ id, olds, output }) {
111 const { accountId } = yield* yield* CloudflareEnvironment;
112 const acct = output?.accountId ?? accountId;
113
114 if (output?.appId) {
115 const observed = yield* findById(acct, output.appId);
116 return observed ? toAttributes(observed, acct) : undefined;
117 }
118 // Cold read — recover from lost state by matching the deterministic
119 // physical name. App names are not unique; an exact match on our
120 // generated/explicit name is the best identity we have, and adoption
121 // is preferable to orphan-spam since apps cannot be deleted.
122 const name = yield* createAppName(id, olds?.name);
123 const match = yield* findByName(acct, name);
124 return match ? toAttributes(match, acct) : undefined;
125 }),
126 reconcile: Effect.fn(function* ({ id, news, output }) {
127 const { accountId } = yield* yield* CloudflareEnvironment;
128 const name = yield* createAppName(id, news.name);
129
130 // Observe — the appId cached on `output` is a hint, not a guarantee.
131 // Fall back to a name scan so an existing same-named app is adopted
132 // instead of duplicated (apps can never be deleted).
133 const observed = output?.appId
134 ? yield* findById(output.accountId ?? accountId, output.appId)
135 : yield* findByName(accountId, name);
136
137 if (!observed) {
138 // Ensure — greenfield: create. Names are not unique so there is no
139 // AlreadyExists race to tolerate.
140 const created = yield* realtimeKit.postApp({ accountId, name });
141 const app = created.data?.app;
142 return {
143 appId: app?.id ?? "",
144 accountId,
145 name: app?.name ?? name,
146 createdAt: app?.createdAt ?? "",
147 };
148 }
149
150 // Sync — RealtimeKit has no update API. The only mutable-looking prop
151 // is the name; fail loudly instead of silently ignoring drift.
152 if ((observed.name ?? "") !== name) {
153 return yield* new AppRenameNotSupported({
154 appId: observed.id ?? "",
155 currentName: observed.name ?? "",
156 desiredName: name,
157 message: `Cloudflare RealtimeKit apps cannot be renamed (no update API) or replaced (no delete API). App ${observed.id} is named "${observed.name}" but "${name}" was requested.`,
158 });
159 }
160 return toAttributes(observed, observed.accountId);
161 }),
162 // No delete API exists, so `delete` cannot actually remove the app — it
163 // would re-appear on every `nuke` scan. Skip it in account-wide teardown
164 // instead of falsely reporting it deleted.
165 nuke: { skip: true },
166 delete: Effect.fn(function* ({ output }) {
167 // RealtimeKit ships no delete API. Forget the app from state and warn —
168 // the app remains on the account until Cloudflare adds deletion.
169 yield* Effect.logWarning(
170 `Cloudflare RealtimeKit has no delete API — app "${output.name}" (${output.appId}) was removed from state but still exists on account ${output.accountId}.`,
171 );
172 }),
173 // Account-scoped collection: enumerate every RealtimeKit app on the
174 // account, exhaustively paginated, and hydrate each into the exact `read`
175 // Attributes shape. Unentitled accounts reject the list with the typed
176 // `Forbidden` (403) which propagates — the suite gates the live assertion
177 // behind an entitlement probe.
178 list: Effect.fn(function* () {
179 const { accountId } = yield* yield* CloudflareEnvironment;
180 const apps = yield* listAllApps(accountId);
181 return apps.map((app) => toAttributes({ ...app, accountId }, accountId));
182 }),
183 });
184
185 const LIST_PER_PAGE = 100;
186
187 /**
188 * Exhaustively enumerate every RealtimeKit app in the account. The list op is
189 * not generated as a paginated method, so fetch the first page, derive the
190 * page count from `paging.totalCount`, then fan out the remaining pages with
191 * bounded concurrency.
192 */
193 const listAllApps = (accountId: string) =>
194 Effect.gen(function* () {
195 const first = yield* realtimeKit.getApp({
196 accountId,
197 pageNo: 1,
198 perPage: LIST_PER_PAGE,
199 });
200 const apps = (first.data ?? []).filter((a): a is NonNullable<typeof a> => a !== null);
201 const total = first.paging?.totalCount ?? apps.length;
202 const pages = Math.ceil(total / LIST_PER_PAGE);
203 if (pages <= 1) return apps;
204 const rest = yield* Effect.forEach(
205 Array.from({ length: pages - 1 }, (_, i) => i + 2),
206 (pageNo) =>
207 realtimeKit
208 .getApp({ accountId, pageNo, perPage: LIST_PER_PAGE })
209 .pipe(
210 Effect.map((res) =>
211 (res.data ?? []).filter((a): a is NonNullable<typeof a> => a !== null),
212 ),
213 ),
214 { concurrency: 10 },
215 );
216 return [...apps, ...rest.flat()];
217 });
218
219 /**
220 * Error raised when a deploy attempts to rename a RealtimeKit app. The API
221 * has neither an update endpoint (to rename in place) nor a delete endpoint
222 * (to model the change as a replacement).
223 */
224 export class AppRenameNotSupported extends Data.TaggedError("AppRenameNotSupported")<{
225 readonly appId: string;
226 readonly currentName: string;
227 readonly desiredName: string;
228 readonly message: string;
229 }> {}
230
231 type ObservedApp = {
232 id?: string | null;
233 createdAt?: string | null;
234 name?: string | null;
235 accountId: string;
236 };
237
238 /**
239 * Find an app by id. The API only exposes a list endpoint, so scan it.
240 */
241 const findById = (accountId: string, appId: string) =>
242 realtimeKit.getApp({ accountId }).pipe(
243 Effect.map((list) =>
244 (list.data ?? [])
245 .filter((a): a is NonNullable<typeof a> => a !== null)
246 .map((a): ObservedApp => ({ ...a, accountId }))
247 .find((a) => a.id === appId),
248 ),
249 );
250
251 /**
252 * Find an app by exact name. If several apps carry the same name, pick the
253 * oldest for determinism.
254 */
255 const findByName = (accountId: string, name: string) =>
256 realtimeKit.getApp({ accountId }).pipe(
257 Effect.map((list) =>
258 (list.data ?? [])
259 .filter((a): a is NonNullable<typeof a> => a !== null)
260 .map((a): ObservedApp => ({ ...a, accountId }))
261 .filter((a) => a.name === name)
262 .sort((a, b) => (a.createdAt ?? "").localeCompare(b.createdAt ?? ""))
263 .at(0),
264 ),
265 );
266
267 const createAppName = (id: string, name: string | undefined) =>
268 Effect.gen(function* () {
269 return name ?? (yield* createPhysicalName({ id, lowercase: true }));
270 });
271
272 const toAttributes = (app: ObservedApp, accountId: string): AppAttributes => ({
273 appId: app.id ?? "",
274 accountId,
275 name: app.name ?? "",
276 createdAt: app.createdAt ?? "",
277 });