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 accounts from "@distilled.cloud/cloudflare/accounts"; |
| 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 * as Stream from "effect/Stream"; |
| 9 | import type { Providers } from "../Providers.ts"; |
| 10 | |
| 11 | const TypeId = "Cloudflare.Account.Account" as const; |
| 12 | type TypeId = typeof TypeId; |
| 13 | |
| 14 | /** |
| 15 | * The kind of Cloudflare account. Cannot be changed after creation. |
| 16 | */ |
| 17 | export type AccountType = "standard" | "enterprise"; |
| 18 | |
| 19 | export interface AccountProps { |
| 20 | /** |
| 21 | * Account name (display name). Mutable in place. If omitted, a unique |
| 22 | * name is generated from the app, stage, and logical ID. |
| 23 | * @default ${app}-${stage}-${id} |
| 24 | */ |
| 25 | name?: string; |
| 26 | /** |
| 27 | * The kind of account to create. Cannot be changed after creation — |
| 28 | * Cloudflare rejects type changes (`UpdateAccountTypeNotSupported`), so |
| 29 | * updating this property triggers a replacement. |
| 30 | * @default "standard" |
| 31 | */ |
| 32 | type?: AccountType; |
| 33 | /** |
| 34 | * Tenant unit to create the account under. Only meaningful for tenant / |
| 35 | * partner credentials; defaults to the tenant's root unit. Create-only — |
| 36 | * updating this property triggers a replacement. |
| 37 | * |
| 38 | * @see https://developers.cloudflare.com/tenant/how-to/manage-accounts/ |
| 39 | */ |
| 40 | unit?: { |
| 41 | /** |
| 42 | * The id of the tenant unit to create the account on. |
| 43 | */ |
| 44 | id?: string; |
| 45 | }; |
| 46 | /** |
| 47 | * Abuse contact email address for the account |
| 48 | * (`settings.abuse_contact_email`). Mutable in place. When omitted, the |
| 49 | * setting is left unmanaged (an existing value is not cleared). |
| 50 | */ |
| 51 | abuseContactEmail?: string; |
| 52 | /** |
| 53 | * Whether membership in this account requires that two-factor |
| 54 | * authentication is enabled (`settings.enforce_twofactor`). Mutable in |
| 55 | * place. When omitted, the setting is left unmanaged. |
| 56 | * @default false |
| 57 | */ |
| 58 | enforceTwofactor?: boolean; |
| 59 | } |
| 60 | |
| 61 | export interface AccountAttributes { |
| 62 | /** |
| 63 | * Account identifier tag assigned by Cloudflare. |
| 64 | */ |
| 65 | accountId: string; |
| 66 | /** |
| 67 | * Account name (display name). |
| 68 | */ |
| 69 | name: string; |
| 70 | /** |
| 71 | * The kind of account. |
| 72 | */ |
| 73 | type: AccountType; |
| 74 | /** |
| 75 | * Timestamp for the creation of the account. |
| 76 | */ |
| 77 | createdOn: string | undefined; |
| 78 | /** |
| 79 | * Id of the tenant organization the account is managed by, if any. |
| 80 | */ |
| 81 | parentOrgId: string | undefined; |
| 82 | /** |
| 83 | * Name of the tenant organization the account is managed by, if any. |
| 84 | */ |
| 85 | parentOrgName: string | undefined; |
| 86 | /** |
| 87 | * Abuse contact email address configured on the account, if any. |
| 88 | */ |
| 89 | abuseContactEmail: string | undefined; |
| 90 | /** |
| 91 | * Whether membership in the account requires two-factor authentication. |
| 92 | */ |
| 93 | enforceTwofactor: boolean; |
| 94 | } |
| 95 | |
| 96 | export type Account = Resource<TypeId, AccountProps, AccountAttributes, never, Providers>; |
| 97 | |
| 98 | /** |
| 99 | * A Cloudflare account (subaccount), for tenant / partner platforms that |
| 100 | * provision an account per customer. |
| 101 | * |
| 102 | * Creating accounts (`POST /accounts`) is restricted to credentials with the |
| 103 | * tenant entitlement — a standard user receives the typed |
| 104 | * `AccountCreationForbidden` error (Cloudflare error code 1002). The `name` |
| 105 | * and account settings are mutable in place; `type` and the tenant `unit` |
| 106 | * are create-only and trigger a replacement. Deleting the resource queues |
| 107 | * the account for deletion (also tenant-gated). |
| 108 | * |
| 109 | * The account's physical identity is the Cloudflare-assigned `accountId`. |
| 110 | * Account names are not unique, so there is no find-by-name fallback: if |
| 111 | * state is lost, the account is treated as missing rather than guessed at. |
| 112 | * ### Creating an account |
| 113 | * **Example:** Standard subaccount with a generated name |
| 114 | * ```typescript |
| 115 | * const account = yield* Cloudflare.Account.Account("CustomerAccount", {}); |
| 116 | * ``` |
| 117 | * |
| 118 | * **Example:** Subaccount on a specific tenant unit |
| 119 | * ```typescript |
| 120 | * const account = yield* Cloudflare.Account.Account("CustomerAccount", { |
| 121 | * name: "Customer: ACME Inc", |
| 122 | * unit: { id: tenantUnitId }, |
| 123 | * }); |
| 124 | * ``` |
| 125 | * |
| 126 | * ### Account settings |
| 127 | * **Example:** Enforce two-factor authentication for all members |
| 128 | * ```typescript |
| 129 | * const account = yield* Cloudflare.Account.Account("CustomerAccount", { |
| 130 | * name: "Customer: ACME Inc", |
| 131 | * enforceTwofactor: true, |
| 132 | * abuseContactEmail: "abuse@acme.example", |
| 133 | * }); |
| 134 | * ``` |
| 135 | * |
| 136 | * @see https://developers.cloudflare.com/tenant/how-to/manage-accounts/ |
| 137 | * |
| 138 | * @resource |
| 139 | * @product Accounts |
| 140 | * @category Account & Identity |
| 141 | */ |
| 142 | export const Account = Resource<Account>(TypeId, { |
| 143 | aliases: ["Cloudflare.Account"], |
| 144 | }); |
| 145 | |
| 146 | /** |
| 147 | * Returns true if the given value is an Account resource. |
| 148 | */ |
| 149 | export const isAccount = (value: unknown): value is Account => |
| 150 | Predicate.hasProperty(value, "Type") && value.Type === TypeId; |
| 151 | |
| 152 | export const AccountProvider = () => |
| 153 | Provider.succeed(Account, { |
| 154 | stables: ["accountId", "type", "createdOn", "parentOrgId", "parentOrgName"], |
| 155 | |
| 156 | diff: Effect.fn(function* ({ olds, news, output }) { |
| 157 | if (!isResolved(news)) return undefined; |
| 158 | // The account type cannot be changed after creation — Cloudflare |
| 159 | // rejects it with `UpdateAccountTypeNotSupported`. |
| 160 | const oldType = output?.type ?? olds?.type ?? "standard"; |
| 161 | if ((news.type ?? "standard") !== oldType) { |
| 162 | return { action: "replace" } as const; |
| 163 | } |
| 164 | // The tenant unit is a create-only placement decision. |
| 165 | if ((olds?.unit?.id ?? undefined) !== (news.unit?.id ?? undefined)) { |
| 166 | return { action: "replace" } as const; |
| 167 | } |
| 168 | return undefined; |
| 169 | }), |
| 170 | |
| 171 | list: () => |
| 172 | // `listAccounts` (GET /accounts) enumerates every account the API |
| 173 | // token can access — no scope input required. The list items carry |
| 174 | // the full account shape (settings + managedBy), so each maps |
| 175 | // directly to the same `Attributes` `read` produces with no |
| 176 | // per-item hydration. Paginate exhaustively. |
| 177 | accounts.listAccounts.pages({}).pipe( |
| 178 | Stream.runCollect, |
| 179 | Effect.map((chunk) => |
| 180 | Array.from(chunk).flatMap((page) => |
| 181 | (page.result ?? []).map((account) => toAttributes(account)), |
| 182 | ), |
| 183 | ), |
| 184 | ), |
| 185 | |
| 186 | read: Effect.fn(function* ({ output }) { |
| 187 | // The physical identity is the Cloudflare-assigned account id — |
| 188 | // names are not unique, so there is no cold find-by-name fallback. |
| 189 | if (!output?.accountId) return undefined; |
| 190 | const observed = yield* getAccount(output.accountId); |
| 191 | return observed ? toAttributes(observed) : undefined; |
| 192 | }), |
| 193 | |
| 194 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 195 | const name = news.name ?? (yield* createPhysicalName({ id, lowercase: true })); |
| 196 | |
| 197 | // 1. Observe — the account id cached on `output` is a hint, not a |
| 198 | // guarantee: a deleted account falls through to create. |
| 199 | let observed = output?.accountId ? yield* getAccount(output.accountId) : undefined; |
| 200 | |
| 201 | // 2. Ensure — create when missing. Names are not unique on |
| 202 | // Cloudflare's side, so there is no AlreadyExists race to |
| 203 | // tolerate. Requires the tenant entitlement: a standard user |
| 204 | // surfaces the typed `AccountCreationForbidden` (code 1002). |
| 205 | if (!observed) { |
| 206 | observed = yield* accounts.createAccount({ |
| 207 | name, |
| 208 | type: news.type, |
| 209 | unit: news.unit, |
| 210 | }); |
| 211 | } |
| 212 | |
| 213 | // 3. Sync — diff observed cloud state against desired; skip the PUT |
| 214 | // entirely on a no-op. Settings props left undefined are |
| 215 | // unmanaged: the observed value is kept as-is. |
| 216 | const settings = observed.settings ?? undefined; |
| 217 | const nameDirty = observed.name !== name; |
| 218 | const abuseDirty = |
| 219 | news.abuseContactEmail !== undefined && |
| 220 | (settings?.abuseContactEmail ?? undefined) !== news.abuseContactEmail; |
| 221 | const twofactorDirty = |
| 222 | news.enforceTwofactor !== undefined && |
| 223 | (settings?.enforceTwofactor ?? false) !== news.enforceTwofactor; |
| 224 | |
| 225 | if (nameDirty || abuseDirty || twofactorDirty) { |
| 226 | observed = yield* accounts.updateAccount({ |
| 227 | accountId: observed.id, |
| 228 | id: observed.id, |
| 229 | name, |
| 230 | settings: |
| 231 | abuseDirty || twofactorDirty |
| 232 | ? { |
| 233 | abuseContactEmail: news.abuseContactEmail, |
| 234 | enforceTwofactor: news.enforceTwofactor, |
| 235 | } |
| 236 | : undefined, |
| 237 | }); |
| 238 | } |
| 239 | |
| 240 | return toAttributes(observed); |
| 241 | }), |
| 242 | |
| 243 | delete: Effect.fn(function* ({ output }) { |
| 244 | // Account deletion is queued / asynchronous on Cloudflare's side — |
| 245 | // a successful DELETE means "pending deletion", which is success for |
| 246 | // us. An already-gone (or already-pending) account surfaces as |
| 247 | // `InvalidRoute` (code 7003): that's success too. |
| 248 | yield* accounts |
| 249 | .deleteAccount({ accountId: output.accountId }) |
| 250 | .pipe(Effect.catchTag("InvalidRoute", () => Effect.void)); |
| 251 | }), |
| 252 | }); |
| 253 | |
| 254 | type ObservedAccount = |
| 255 | | accounts.GetAccountResponse |
| 256 | | accounts.CreateAccountResponse |
| 257 | | accounts.UpdateAccountResponse |
| 258 | | accounts.ListAccountsResponse["result"][number]; |
| 259 | |
| 260 | /** |
| 261 | * Read an account by id, mapping "gone" to `undefined`. A missing (or |
| 262 | * deletion-pending) account surfaces as `InvalidRoute` (Cloudflare error |
| 263 | * code 7003). |
| 264 | */ |
| 265 | const getAccount = (accountId: string) => |
| 266 | accounts.getAccount({ accountId }).pipe( |
| 267 | Effect.map((account): ObservedAccount | undefined => account), |
| 268 | Effect.catchTag("InvalidRoute", () => Effect.undefined), |
| 269 | ); |
| 270 | |
| 271 | const toAttributes = (account: ObservedAccount): AccountAttributes => ({ |
| 272 | accountId: account.id, |
| 273 | name: account.name, |
| 274 | // Distilled widens generated string enums to open unions (`string & {}`). |
| 275 | type: account.type as AccountType, |
| 276 | createdOn: account.createdOn ?? undefined, |
| 277 | parentOrgId: account.managedBy?.parentOrgId ?? undefined, |
| 278 | parentOrgName: account.managedBy?.parentOrgName ?? undefined, |
| 279 | abuseContactEmail: account.settings?.abuseContactEmail ?? undefined, |
| 280 | enforceTwofactor: account.settings?.enforceTwofactor ?? false, |
| 281 | }); |