The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as emailSending from "@distilled.cloud/cloudflare/email-sending"; |
| 2 | import { Unowned } from "alchemy/AdoptPolicy"; |
| 3 | import * as Provider from "alchemy/Provider"; |
| 4 | import { Resource } from "alchemy/Resource"; |
| 5 | import * as Effect from "effect/Effect"; |
| 6 | import * as Option from "effect/Option"; |
| 7 | import * as Predicate from "effect/Predicate"; |
| 8 | import * as Schedule from "effect/Schedule"; |
| 9 | import * as Stream from "effect/Stream"; |
| 10 | import { CloudflareEnvironment } from "../CloudflareEnvironment.ts"; |
| 11 | import type { Providers } from "../Providers.ts"; |
| 12 | import { listAllZones } from "../Zone/lookup.ts"; |
| 13 | |
| 14 | const SendingSubdomainTypeId = "Cloudflare.Email.SendingSubdomain" as const; |
| 15 | type SendingSubdomainTypeId = typeof SendingSubdomainTypeId; |
| 16 | |
| 17 | export interface SendingSubdomainProps { |
| 18 | /** |
| 19 | * Zone the sending subdomain is registered on. The subdomain name must |
| 20 | * be within this zone. |
| 21 | * |
| 22 | * Stable — moving the subdomain to another zone triggers a replacement. |
| 23 | */ |
| 24 | zoneId: string; |
| 25 | /** |
| 26 | * The fully-qualified subdomain to send email from (e.g. |
| 27 | * `mail.example.com`). Must be within the zone. |
| 28 | * |
| 29 | * Stable — the Cloudflare API has no update operation for sending |
| 30 | * subdomains, so a rename is a delete + create. Declared as plain |
| 31 | * `string` (not `string`) so it is statically knowable in `diff`. |
| 32 | */ |
| 33 | name: string; |
| 34 | /** |
| 35 | * Whether Cloudflare keeps a preview of each sent message in the activity |
| 36 | * log (retained for about seven days). Subdomains onboarded on or after |
| 37 | * 2026-07-02 start with previews on. Omit to leave the setting as |
| 38 | * Cloudflare has it. |
| 39 | * |
| 40 | * @see https://developers.cloudflare.com/email-service/observability/logs/#message-preview |
| 41 | */ |
| 42 | previewEnabled?: boolean; |
| 43 | } |
| 44 | |
| 45 | export interface SendingSubdomainAttributes { |
| 46 | /** Cloudflare-assigned identifier of the sending subdomain. */ |
| 47 | subdomainId: string; |
| 48 | /** Zone the sending subdomain is registered on. */ |
| 49 | zoneId: string; |
| 50 | /** The subdomain domain name. */ |
| 51 | name: string; |
| 52 | /** |
| 53 | * Whether Email Sending is enabled on this subdomain. Flips to `true` |
| 54 | * once the auto-provisioned DNS records (DKIM/SPF/return-path) validate |
| 55 | * — usually immediate for zones on Cloudflare DNS. |
| 56 | */ |
| 57 | enabled: boolean; |
| 58 | /** The DKIM selector used for email signing. */ |
| 59 | dkimSelector: string | undefined; |
| 60 | /** The return-path domain used for bounce handling. */ |
| 61 | returnPathDomain: string | undefined; |
| 62 | /** Whether sent messages can be previewed in the activity log. */ |
| 63 | previewEnabled: boolean | undefined; |
| 64 | /** ISO8601 creation timestamp. */ |
| 65 | created: string | undefined; |
| 66 | /** ISO8601 last-modified timestamp. */ |
| 67 | modified: string | undefined; |
| 68 | } |
| 69 | |
| 70 | export type SendingSubdomain = Resource< |
| 71 | SendingSubdomainTypeId, |
| 72 | SendingSubdomainProps, |
| 73 | SendingSubdomainAttributes, |
| 74 | never, |
| 75 | Providers |
| 76 | >; |
| 77 | |
| 78 | /** |
| 79 | * Registers a Cloudflare Email Sending subdomain on a zone, enabling the |
| 80 | * account to send transactional email from addresses on that subdomain. |
| 81 | * |
| 82 | * Creating the subdomain provisions DKIM, SPF, and return-path |
| 83 | * configuration; for zones on Cloudflare DNS the required DNS records are |
| 84 | * created automatically and `enabled` flips to `true` once they validate |
| 85 | * (usually immediately). |
| 86 | * |
| 87 | * Changing `name` or `zoneId` triggers a replacement; `previewEnabled` is |
| 88 | * updated in place. |
| 89 | * |
| 90 | * Safety: sending subdomains carry no ownership markers. When there is no |
| 91 | * prior state, `read` scans the zone for an existing subdomain with the |
| 92 | * same name and reports it as `Unowned`, so the engine refuses to take it |
| 93 | * over unless `--adopt` (or `adopt(true)`) is set. |
| 94 | * ### Registering a sending subdomain |
| 95 | * **Example:** Send mail from `mail.example.com` |
| 96 | * ```typescript |
| 97 | * const sending = yield* Cloudflare.Email.SendingSubdomain("Mail", { |
| 98 | * zoneId: zone.zoneId, |
| 99 | * name: "mail.example.com", |
| 100 | * }); |
| 101 | * // sending.enabled — true once DNS records validated |
| 102 | * // sending.dkimSelector / sending.returnPathDomain — provisioned config |
| 103 | * ``` |
| 104 | * |
| 105 | * ### Message previews |
| 106 | * **Example:** Keep no copies of sent messages in the activity log |
| 107 | * ```typescript |
| 108 | * const sending = yield* Cloudflare.Email.SendingSubdomain("Mail", { |
| 109 | * zoneId: zone.zoneId, |
| 110 | * name: "mail.example.com", |
| 111 | * previewEnabled: false, |
| 112 | * }); |
| 113 | * ``` |
| 114 | * |
| 115 | * ### Externally-hosted zones |
| 116 | * **Example:** Look up the DNS records to create manually |
| 117 | * ```typescript |
| 118 | * import * as emailSending from "@distilled.cloud/cloudflare/email-sending"; |
| 119 | * |
| 120 | * // For zones not on Cloudflare DNS, fetch the expected records and add |
| 121 | * // them at your DNS host; `enabled` flips to true once they validate. |
| 122 | * const records = yield* emailSending.getSubdomainDns.items({ |
| 123 | * zoneId: sending.zoneId, |
| 124 | * subdomainId: sending.subdomainId, |
| 125 | * }).pipe(Stream.runCollect); |
| 126 | * ``` |
| 127 | * |
| 128 | * @see https://developers.cloudflare.com/email-sending/ |
| 129 | * |
| 130 | * @resource |
| 131 | * @product Email |
| 132 | * @category Email |
| 133 | */ |
| 134 | export const SendingSubdomain = Resource<SendingSubdomain>(SendingSubdomainTypeId, { |
| 135 | aliases: ["Cloudflare.EmailSendingSubdomain"], |
| 136 | }); |
| 137 | |
| 138 | /** |
| 139 | * Returns true if the given value is an SendingSubdomain resource. |
| 140 | */ |
| 141 | export const isSendingSubdomain = (value: unknown): value is SendingSubdomain => |
| 142 | Predicate.hasProperty(value, "Type") && value.Type === SendingSubdomainTypeId; |
| 143 | |
| 144 | export const SendingSubdomainProvider = () => |
| 145 | Provider.succeed(SendingSubdomain, { |
| 146 | // Only `previewEnabled` changes in place. |
| 147 | stables: ["subdomainId", "zoneId", "name", "dkimSelector", "returnPathDomain", "created"], |
| 148 | |
| 149 | list: Effect.fn(function* () { |
| 150 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 151 | // Sending subdomains are zone-scoped (`/zones/{id}/email/sending/ |
| 152 | // subdomains`) with no account-wide list — enumerate every zone and |
| 153 | // list its subdomains, then flatten. |
| 154 | const zones = yield* listAllZones(accountId); |
| 155 | const rows = yield* Effect.forEach( |
| 156 | zones, |
| 157 | (zone) => |
| 158 | emailSending.listSubdomains.pages({ zoneId: zone.id }).pipe( |
| 159 | Stream.runCollect, |
| 160 | Effect.map((chunk) => |
| 161 | Array.from(chunk).flatMap((page) => |
| 162 | (page.result ?? []).map((subdomain) => toAttributes(subdomain, zone.id)), |
| 163 | ), |
| 164 | ), |
| 165 | // Email Sending may be unavailable / plan-gated on a zone — |
| 166 | // skip those zones rather than fail the whole enumeration. |
| 167 | Effect.catchTag("Forbidden", () => Effect.succeed([])), |
| 168 | ), |
| 169 | { concurrency: 10 }, |
| 170 | ); |
| 171 | return rows.flat(); |
| 172 | }), |
| 173 | |
| 174 | diff: Effect.fn(function* ({ olds = {}, news }) { |
| 175 | const o = olds as SendingSubdomainProps; |
| 176 | const n = news as SendingSubdomainProps; |
| 177 | // `name` and `zoneId` are identity; `previewEnabled` updates in place. |
| 178 | if (o.name !== undefined && o.name !== n.name) { |
| 179 | return { action: "replace" } as const; |
| 180 | } |
| 181 | // zoneId is Input<string>; compare only once both are concrete. |
| 182 | if (typeof o.zoneId === "string" && typeof n.zoneId === "string" && o.zoneId !== n.zoneId) { |
| 183 | return { action: "replace" } as const; |
| 184 | } |
| 185 | return undefined; |
| 186 | }), |
| 187 | |
| 188 | read: Effect.fn(function* ({ output, olds }) { |
| 189 | const zoneId = output?.zoneId ?? (typeof olds?.zoneId === "string" ? olds.zoneId : undefined); |
| 190 | if (!zoneId) return undefined; |
| 191 | |
| 192 | // Owned path: refresh by our persisted subdomain id. |
| 193 | if (output?.subdomainId) { |
| 194 | const observed = yield* getSubdomain(zoneId, output.subdomainId); |
| 195 | if (observed) return toAttributes(observed, zoneId); |
| 196 | } |
| 197 | |
| 198 | // Adoption path: a subdomain with this name may already exist on the |
| 199 | // zone. Sending subdomains carry no ownership markers, so we cannot |
| 200 | // prove we created it — brand it `Unowned` so the engine refuses to |
| 201 | // take over unless `adopt` is set. |
| 202 | const name = output?.name ?? olds?.name; |
| 203 | if (name) { |
| 204 | const observed = yield* findByName(zoneId, name); |
| 205 | if (observed) return Unowned(toAttributes(observed, zoneId)); |
| 206 | } |
| 207 | return undefined; |
| 208 | }), |
| 209 | |
| 210 | reconcile: Effect.fn(function* ({ news, output }) { |
| 211 | // Inputs have been resolved to concrete strings by Plan. |
| 212 | const zoneId = news.zoneId as string; |
| 213 | |
| 214 | // 1. Observe — the subdomain id cached on `output` is a hint, not a |
| 215 | // guarantee: a missing subdomain falls through to the name scan |
| 216 | // and then to create. |
| 217 | let observed = output?.subdomainId |
| 218 | ? yield* getSubdomain(zoneId, output.subdomainId) |
| 219 | : undefined; |
| 220 | |
| 221 | // 2. Fall back to scanning the zone for a name match. Ownership has |
| 222 | // already been verified upstream — `read` reports existing |
| 223 | // subdomains as `Unowned` and the engine gates takeover behind |
| 224 | // the adopt policy before reconcile ever runs. |
| 225 | if (!observed) { |
| 226 | observed = yield* findByName(zoneId, news.name); |
| 227 | } |
| 228 | |
| 229 | // 3. Ensure — create when missing. A concurrent create surfaces as |
| 230 | // `SendingSubdomainAlreadyExists` (Cloudflare code 2040): |
| 231 | // converge by re-scanning for the subdomain that won the race. |
| 232 | if (!observed) { |
| 233 | observed = yield* emailSending |
| 234 | .createSubdomain({ zoneId, name: news.name }) |
| 235 | .pipe( |
| 236 | Effect.catchTag("SendingSubdomainAlreadyExists", (error) => |
| 237 | findByName(zoneId, news.name).pipe( |
| 238 | Effect.flatMap((existing) => |
| 239 | existing ? Effect.succeed(existing) : Effect.fail(error), |
| 240 | ), |
| 241 | ), |
| 242 | ), |
| 243 | ); |
| 244 | } |
| 245 | |
| 246 | // 4. Sync — converge `previewEnabled` when it is declared, then wait |
| 247 | // for DNS validation. Cloudflare auto-creates the records on CF-hosted |
| 248 | // zones but validation is eventually consistent: poll briefly |
| 249 | // for `enabled` to flip, and return the observed state either |
| 250 | // way (an externally-hosted zone stays disabled until the user |
| 251 | // adds the records — that is not a deploy failure). |
| 252 | const ensured = |
| 253 | news.previewEnabled !== undefined && observed.previewEnabled !== news.previewEnabled |
| 254 | ? yield* emailSending.editSubdomain({ |
| 255 | zoneId, |
| 256 | subdomainId: observed.tag, |
| 257 | previewEnabled: news.previewEnabled, |
| 258 | }) |
| 259 | : observed; |
| 260 | const final = ensured.enabled |
| 261 | ? ensured |
| 262 | : yield* getSubdomain(zoneId, ensured.tag).pipe( |
| 263 | Effect.map((latest) => latest ?? ensured), |
| 264 | Effect.repeat({ |
| 265 | schedule: Schedule.spaced("5 seconds"), |
| 266 | until: (latest) => latest.enabled, |
| 267 | times: 12, |
| 268 | }), |
| 269 | ); |
| 270 | |
| 271 | // 5. Return. |
| 272 | return toAttributes(final, zoneId); |
| 273 | }), |
| 274 | |
| 275 | delete: Effect.fn(function* ({ output }) { |
| 276 | // Idempotent — an already-gone subdomain answers with Cloudflare |
| 277 | // code 2033 (`SendingSubdomainNotFound`), which is success here. |
| 278 | yield* emailSending |
| 279 | .deleteSubdomain({ |
| 280 | zoneId: output.zoneId, |
| 281 | subdomainId: output.subdomainId, |
| 282 | }) |
| 283 | .pipe(Effect.catchTag("SendingSubdomainNotFound", () => Effect.void)); |
| 284 | }), |
| 285 | }); |
| 286 | |
| 287 | // --------------------------------------------------------------------------- |
| 288 | // API helpers |
| 289 | // --------------------------------------------------------------------------- |
| 290 | |
| 291 | type ObservedSubdomain = emailSending.GetSubdomainResponse; |
| 292 | |
| 293 | /** |
| 294 | * Read a sending subdomain by id, mapping "gone" (`SendingSubdomainNotFound`, |
| 295 | * Cloudflare error code 2033) to `undefined`. |
| 296 | */ |
| 297 | const getSubdomain = (zoneId: string, subdomainId: string) => |
| 298 | emailSending.getSubdomain({ zoneId, subdomainId }).pipe( |
| 299 | Effect.map((subdomain): ObservedSubdomain | undefined => subdomain), |
| 300 | Effect.catchTag("SendingSubdomainNotFound", () => Effect.undefined), |
| 301 | ); |
| 302 | |
| 303 | /** |
| 304 | * Find a sending subdomain by exact name within the zone. The name is the |
| 305 | * subdomain's identity — Cloudflare rejects duplicates with code 2040 — so |
| 306 | * at most one can match. |
| 307 | */ |
| 308 | const findByName = (zoneId: string, name: string) => |
| 309 | emailSending.listSubdomains.items({ zoneId }).pipe( |
| 310 | Stream.filter((subdomain) => subdomain.name === name), |
| 311 | Stream.runHead, |
| 312 | Effect.map(Option.getOrUndefined), |
| 313 | ); |
| 314 | |
| 315 | const toAttributes = ( |
| 316 | subdomain: ObservedSubdomain, |
| 317 | zoneId: string, |
| 318 | ): SendingSubdomainAttributes => ({ |
| 319 | subdomainId: subdomain.tag, |
| 320 | zoneId, |
| 321 | name: subdomain.name, |
| 322 | enabled: subdomain.enabled, |
| 323 | dkimSelector: subdomain.dkimSelector ?? undefined, |
| 324 | returnPathDomain: subdomain.returnPathDomain ?? undefined, |
| 325 | previewEnabled: subdomain.previewEnabled ?? undefined, |
| 326 | created: subdomain.created ?? undefined, |
| 327 | modified: subdomain.modified ?? undefined, |
| 328 | }); |