The best way to control Claude Code, Codex and more from any computer or phone

main
ts 273 lines 9.67 KB
Raw
1 import * as customNameservers from "@distilled.cloud/cloudflare/custom-nameservers";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
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 { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
10 import type { Providers } from "../Providers.ts";
11
12 const TypeId = "Cloudflare.CustomNameserver.CustomNameserver" as const;
13 type TypeId = typeof TypeId;
14
15 /**
16 * Verification status of an account custom nameserver. Deprecated by
17 * Cloudflare but still returned by the API.
18 */
19 export type Status = "moved" | "pending" | "verified";
20
21 /**
22 * A glue record (A/AAAA) that must be registered at the domain registrar
23 * for the custom nameserver to resolve.
24 */
25 export interface Record {
26 /**
27 * The record type of the glue record.
28 */
29 type: "A" | "AAAA" | undefined;
30 /**
31 * The IP address of the glue record.
32 */
33 value: string | undefined;
34 }
35
36 export interface Props {
37 /**
38 * The FQDN of the nameserver (e.g. `ns1.yourbrand.com`). Must be a
39 * subdomain of a zone active on the same account.
40 *
41 * Immutable — this is the nameserver's identity; changing it triggers a
42 * replacement.
43 */
44 nsName: string;
45 /**
46 * The number of the nameserver set this nameserver belongs to (1–5).
47 *
48 * Immutable — there is no update API; changing it triggers a replacement.
49 * @default 1
50 */
51 nsSet?: number;
52 }
53
54 export interface Attributes {
55 /**
56 * The FQDN of the nameserver. Also the identifier used to delete it.
57 */
58 nsName: string;
59 /**
60 * The Cloudflare account the nameserver belongs to.
61 */
62 accountId: string;
63 /**
64 * The number of the nameserver set this nameserver belongs to.
65 */
66 nsSet: number | undefined;
67 /**
68 * Verification status of the nameserver (deprecated by Cloudflare but
69 * still returned).
70 */
71 status: Status;
72 /**
73 * A/AAAA glue records to register at the domain registrar so the
74 * nameserver resolves.
75 */
76 dnsRecords: Record[];
77 /**
78 * The zone (on this account) that `nsName` belongs to.
79 */
80 zoneTag: string;
81 }
82
83 export type CustomNameserver = Resource<TypeId, Props, Attributes, never, Providers>;
84
85 /**
86 * An account-level custom (vanity) nameserver — e.g. `ns1.yourbrand.com` —
87 * that zones on the account can use instead of their assigned
88 * `*.ns.cloudflare.com` names.
89 *
90 * The nameserver's identity is its `nsName` (FQDN) within the account.
91 * There is no update API: both `nsName` and `nsSet` are immutable, so
92 * changing either triggers a replacement. After creation, Cloudflare
93 * returns the A/AAAA glue records (`dnsRecords`) that must be registered
94 * at the domain registrar.
95 *
96 * Requires the account custom nameservers entitlement (Business/Enterprise
97 * or a paid add-on); on unentitled accounts every API call fails with the
98 * typed `CustomNameserversNotEnabled` error.
99 *
100 * Safety: custom nameservers carry no ownership markers. When there is no
101 * prior state, `read` scans the account for an existing nameserver with
102 * the same `nsName` and reports it as `Unowned`, so the engine refuses to
103 * take it over unless `--adopt` (or `adopt(true)`) is set.
104 * ### Creating a custom nameserver
105 * **Example:** Vanity nameserver on the default set
106 * ```typescript
107 * const ns1 = yield* Cloudflare.CustomNameserver.CustomNameserver("Ns1", {
108 * nsName: "ns1.yourbrand.com",
109 * });
110 *
111 * // Glue records to register at your registrar:
112 * const glue = ns1.dnsRecords; // [{ type: "A", value: "..." }, ...]
113 * ```
114 *
115 * **Example:** Nameserver on a specific set
116 * ```typescript
117 * yield* Cloudflare.CustomNameserver.CustomNameserver("Ns2", {
118 * nsName: "ns2.yourbrand.com",
119 * nsSet: 2,
120 * });
121 * ```
122 *
123 * @see https://developers.cloudflare.com/dns/nameservers/custom-nameservers/account-custom-nameservers/
124 *
125 * @resource
126 * @product Custom Nameservers
127 * @category Domains & DNS
128 */
129 export const CustomNameserver = Resource<CustomNameserver>(TypeId, {
130 aliases: ["Cloudflare.CustomNameserver"],
131 });
132
133 /**
134 * Returns true if the given value is a CustomNameserver resource.
135 */
136 export const isCustomNameserver = (value: unknown): value is CustomNameserver =>
137 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
138
139 export const CustomNameserverProvider = () =>
140 Provider.succeed(CustomNameserver, {
141 stables: ["nsName", "accountId", "nsSet", "zoneTag"],
142
143 list: Effect.fn(function* () {
144 const { accountId } = yield* yield* CloudflareEnvironment;
145 // Account collection: `getCustomNameserver` is a paginated list
146 // endpoint despite its name. Enumerate every page and hydrate each
147 // nameserver into the exact `read` Attributes shape.
148 return yield* customNameservers.getCustomNameserver.pages({ accountId }).pipe(
149 Stream.runCollect,
150 Effect.map((chunk) =>
151 Array.from(chunk).flatMap((page) => page.result.map((ns) => toAttributes(ns, accountId))),
152 ),
153 // Unentitled accounts have no custom nameservers at all — the
154 // collection endpoint rejects with a typed entitlement error.
155 // Treat that as an empty collection rather than failing `list`.
156 Effect.catchTag("CustomNameserversNotEnabled", () => Effect.succeed([] as Attributes[])),
157 );
158 }),
159
160 diff: Effect.fn(function* ({ olds, news }) {
161 if (!isResolved(news)) return undefined;
162 // No prior props to compare against — let the engine decide.
163 if (olds?.nsName === undefined) return undefined;
164 // There is no update API: both the FQDN and the set number are
165 // immutable, so any change is a replacement.
166 if (olds.nsName !== news.nsName) {
167 return { action: "replace" } as const;
168 }
169 if ((olds.nsSet ?? 1) !== (news.nsSet ?? 1)) {
170 return { action: "replace" } as const;
171 }
172 return undefined;
173 }),
174
175 read: Effect.fn(function* ({ output, olds }) {
176 const { accountId } = yield* yield* CloudflareEnvironment;
177 const acct = output?.accountId ?? accountId;
178 const nsName = output?.nsName ?? olds?.nsName;
179 if (nsName === undefined) return undefined;
180
181 const observed = yield* findByName(acct, nsName);
182 if (!observed) return undefined;
183
184 // Owned path: we created this nameserver — refresh its attributes.
185 if (output?.nsName) return toAttributes(observed, acct);
186
187 // Adoption path: a nameserver with this FQDN already exists on the
188 // account. Custom nameservers carry no ownership markers, so brand
189 // it `Unowned` — the engine refuses to take over unless `adopt` is
190 // set.
191 return Unowned(toAttributes(observed, acct));
192 }),
193
194 reconcile: Effect.fn(function* ({ news, output }) {
195 const { accountId } = yield* yield* CloudflareEnvironment;
196
197 // 1. Observe — `nsName` is the nameserver's identity within the
198 // account; the cached `output` is at most a hint. The list is
199 // authoritative: a missing nameserver falls through to create.
200 const observed = yield* findByName(output?.accountId ?? accountId, news.nsName);
201 if (observed) {
202 // 2. Sync — nothing is mutable (no update API); `diff` already
203 // replaces on nsName/nsSet changes, so observed state is final.
204 return toAttributes(observed, output?.accountId ?? accountId);
205 }
206
207 // 3. Ensure — create when missing. A concurrent create surfaces as
208 // `CustomNameserverAlreadyExists`: converge by re-listing for
209 // the nameserver that won the race.
210 const created = yield* customNameservers
211 .createCustomNameserver({
212 accountId,
213 nsName: news.nsName,
214 nsSet: news.nsSet,
215 })
216 .pipe(
217 Effect.catchTag("CustomNameserverAlreadyExists", (error) =>
218 findByName(accountId, news.nsName).pipe(
219 Effect.flatMap((existing) =>
220 existing ? Effect.succeed(existing) : Effect.fail(error),
221 ),
222 ),
223 ),
224 );
225 return toAttributes(created, accountId);
226 }),
227
228 delete: Effect.fn(function* ({ output }) {
229 // Observe first — DELETE for an already-gone nameserver may not
230 // return a decodable envelope, and a second destroy must be a
231 // no-op either way.
232 const observed = yield* findByName(output.accountId, output.nsName);
233 if (!observed) return;
234 yield* customNameservers
235 .deleteCustomNameserver({
236 accountId: output.accountId,
237 customNsId: output.nsName,
238 })
239 .pipe(Effect.catchTag("CustomNameserverNotFound", () => Effect.void));
240 }),
241 });
242
243 type ObservedNameserver = customNameservers.GetCustomNameserverResponse["result"][number];
244
245 /**
246 * Find a custom nameserver by exact FQDN on the account. The FQDN is the
247 * nameserver's identity — Cloudflare rejects duplicates — so at most one
248 * can match. `getCustomNameserver` is a list endpoint despite its name.
249 */
250 const findByName = (accountId: string, nsName: string) =>
251 customNameservers
252 .getCustomNameserver({ accountId })
253 .pipe(
254 Effect.map((page) =>
255 page.result.find((ns): ns is ObservedNameserver => ns.nsName === nsName),
256 ),
257 );
258
259 const toAttributes = (
260 ns: ObservedNameserver | customNameservers.CreateCustomNameserverResponse,
261 accountId: string,
262 ): Attributes => ({
263 nsName: ns.nsName,
264 accountId,
265 nsSet: ns.nsSet ?? undefined,
266 // Distilled widens generated string enums to open unions (`string & {}`).
267 status: ns.status as Status,
268 dnsRecords: ns.dnsRecords.map((record) => ({
269 type: (record.type ?? undefined) as "A" | "AAAA" | undefined,
270 value: record.value ?? undefined,
271 })),
272 zoneTag: ns.zoneTag,
273 });