@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 270 lines 10.2 KB
Raw
1 import * as zones from "@distilled.cloud/cloudflare/zones";
2 import { isResolved } from "alchemy/Diff";
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 { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
8 import type { Providers } from "../Providers.ts";
9 import { listAllZones } from "../Zone/lookup.ts";
10
11 const TypeId = "Cloudflare.Zone.CustomNameservers" as const;
12 type TypeId = typeof TypeId;
13
14 export type CustomNameserversProps = {
15 /**
16 * Zone whose account-level custom nameserver usage is managed. Stable —
17 * changing the zone triggers a replacement (the old zone's configuration
18 * is restored to the value it had before Alchemy managed it).
19 */
20 zoneId: string;
21 /**
22 * Whether the zone uses account-level custom nameservers (ACNS) instead
23 * of the Cloudflare-assigned nameservers.
24 *
25 * Enabling requires an account-level custom nameserver set to already be
26 * configured (Business/Enterprise) — otherwise Cloudflare rejects the
27 * update with the typed `CustomNameserverSetNotFound` error.
28 *
29 * Mutable — applied in place.
30 */
31 enabled: boolean;
32 /**
33 * The number of the account custom nameserver set to assign to the zone.
34 * Only meaningful when `enabled` is `true`.
35 *
36 * Mutable — applied in place.
37 *
38 * @default 1 (Cloudflare's default nameserver set)
39 */
40 nsSet?: number;
41 };
42
43 export type CustomNameserversAttributes = {
44 /** Zone whose custom nameserver usage is managed. */
45 zoneId: string;
46 /** Whether the zone currently uses account-level custom nameservers. */
47 enabled: boolean;
48 /** The nameserver set currently assigned to the zone, if reported. */
49 nsSet: number | undefined;
50 /**
51 * Whether ACNS was enabled before Alchemy first touched the zone.
52 * Restored on destroy, so deleting the resource puts the zone back the
53 * way it was found.
54 */
55 initialEnabled: boolean;
56 /** The nameserver set assigned before Alchemy first touched the zone. */
57 initialNsSet: number | undefined;
58 };
59
60 export type CustomNameservers = Resource<
61 TypeId,
62 CustomNameserversProps,
63 CustomNameserversAttributes,
64 never,
65 Providers
66 >;
67
68 /**
69 * Controls whether a Cloudflare zone uses **account-level custom
70 * nameservers** (ACNS, `/zones/{zone_id}/custom_ns`).
71 *
72 * This configuration is a zone singleton — it always exists on every zone
73 * (disabled by default), so the resource never creates or deletes anything
74 * physical. Reconcile applies the desired `enabled`/`nsSet` when the
75 * observed configuration differs; destroy restores the configuration the
76 * zone had before Alchemy first managed it.
77 *
78 * Enabling requires an account custom nameserver set to be configured first
79 * (Business/Enterprise feature). Without one, Cloudflare rejects the update
80 * with the typed `CustomNameserverSetNotFound` error.
81 * ### Enabling account custom nameservers
82 * **Example:** Use the account's default nameserver set
83 * ```typescript
84 * yield* Cloudflare.Zone.CustomNameservers("CustomNs", {
85 * zoneId: zone.zoneId,
86 * enabled: true,
87 * });
88 * ```
89 *
90 * **Example:** Pin a specific nameserver set
91 * ```typescript
92 * yield* Cloudflare.Zone.CustomNameservers("CustomNs", {
93 * zoneId: zone.zoneId,
94 * enabled: true,
95 * nsSet: 2,
96 * });
97 * ```
98 *
99 * ### Disabling
100 * **Example:** Explicitly pin the zone to Cloudflare-assigned nameservers
101 * ```typescript
102 * yield* Cloudflare.Zone.CustomNameservers("CustomNs", {
103 * zoneId: zone.zoneId,
104 * enabled: false,
105 * });
106 * ```
107 *
108 * @see https://developers.cloudflare.com/api/resources/zones/subresources/custom_nameservers/
109 *
110 * @resource
111 * @product Zones
112 * @category Domains & DNS
113 */
114 export const CustomNameservers = Resource<CustomNameservers>(TypeId);
115
116 /**
117 * Returns true if the given value is a CustomNameservers resource.
118 */
119 export const isCustomNameservers = (value: unknown): value is CustomNameservers =>
120 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
121
122 export const CustomNameserversProvider = () =>
123 Provider.succeed(CustomNameservers, {
124 stables: ["zoneId", "initialEnabled", "initialNsSet"],
125
126 list: Effect.fn(function* () {
127 const { accountId } = yield* yield* CloudflareEnvironment;
128 // No account-wide API for this zone singleton — enumerate every
129 // zone in the account and read its custom-nameserver config.
130 const allZones = yield* listAllZones(accountId);
131 const rows = yield* Effect.forEach(
132 allZones.map((zone) => zone.id),
133 (zoneId) =>
134 zones.getCustomNameserver({ zoneId }).pipe(
135 Effect.map((observed) => {
136 // Only zones actively using account custom nameservers are
137 // worth enumerating — a disabled (default) toggle has
138 // nothing to restore on destroy.
139 if (!(observed.enabled ?? false)) return undefined;
140 return toAttributes(
141 zoneId,
142 observed,
143 observed.enabled ?? false,
144 observed.nsSet ?? undefined,
145 );
146 }),
147 // ACNS is a Business/Enterprise feature — plan-gated zones
148 // reject with `Forbidden`; zones deleted out-of-band 404 with
149 // `InvalidZoneIdentifier`. Skip both.
150 Effect.catchTag(["InvalidZoneIdentifier", "Forbidden"], () => Effect.undefined),
151 ),
152 { concurrency: 10 },
153 );
154 return rows.filter((row): row is CustomNameserversAttributes => row !== undefined);
155 }),
156
157 diff: Effect.fn(function* ({ olds, news, output }) {
158 // zoneId is the resource's identity; compare only once both sides
159 // are concrete (resolved) values.
160 if (!isResolved(news)) return undefined;
161 const oldZoneId =
162 output?.zoneId ?? (olds !== undefined && isResolved(olds) ? olds.zoneId : undefined);
163 if (oldZoneId !== undefined && oldZoneId !== news.zoneId) {
164 return { action: "replace" } as const;
165 }
166 return undefined;
167 }),
168
169 read: Effect.fn(function* ({ output, olds }) {
170 const zoneId = output?.zoneId ?? (olds?.zoneId as string | undefined);
171 if (!zoneId) return undefined;
172 const observed = yield* zones.getCustomNameserver({ zoneId }).pipe(
173 // Zone deleted out-of-band — the configuration is gone with it.
174 Effect.catchTag("InvalidZoneIdentifier", () => Effect.undefined),
175 );
176 if (observed === undefined) return undefined;
177 // The custom-NS toggle is a singleton that always exists (disabled
178 // by default) — there is nothing to "own", so a cold read adopts
179 // freely (never `Unowned`). The observed state at adoption time
180 // becomes the baseline restored on destroy.
181 const initialEnabled =
182 output !== undefined ? output.initialEnabled : (observed.enabled ?? false);
183 const initialNsSet =
184 output !== undefined ? output.initialNsSet : (observed.nsSet ?? undefined);
185 return toAttributes(zoneId, observed, initialEnabled, initialNsSet);
186 }),
187
188 reconcile: Effect.fn(function* ({ news, output }) {
189 // Inputs have been resolved to concrete strings by Plan.
190 const zoneId = news.zoneId as string;
191
192 // 1. Observe — the configuration always exists; read its live state.
193 const observed = yield* zones.getCustomNameserver({ zoneId });
194
195 // 2. Capture — the pre-management state, restored on destroy.
196 // `output` (including an adoption read) already carries it;
197 // otherwise this is our first touch and the observed state is
198 // the zone's original.
199 const initialEnabled =
200 output !== undefined ? output.initialEnabled : (observed.enabled ?? false);
201 const initialNsSet =
202 output !== undefined ? output.initialNsSet : (observed.nsSet ?? undefined);
203
204 // 3. Sync — apply only when the observed state differs.
205 const observedEnabled = observed.enabled ?? false;
206 const observedNsSet = observed.nsSet ?? undefined;
207 const inSync =
208 observedEnabled === news.enabled &&
209 (news.nsSet === undefined || observedNsSet === news.nsSet);
210 if (inSync) {
211 return toAttributes(zoneId, observed, initialEnabled, initialNsSet);
212 }
213 yield* zones.putCustomNameserver({
214 zoneId,
215 enabled: news.enabled,
216 ...(news.nsSet !== undefined ? { nsSet: news.nsSet } : {}),
217 });
218 // The PUT response does not reliably echo the resulting state —
219 // re-read so the attributes reflect the observed cloud state.
220 const final = yield* zones.getCustomNameserver({ zoneId });
221 return toAttributes(zoneId, final, initialEnabled, initialNsSet);
222 }),
223
224 delete: Effect.fn(function* ({ output }) {
225 const { zoneId, initialEnabled, initialNsSet } = output;
226 // Observe — if the zone itself is gone, so is the configuration.
227 const observed = yield* zones
228 .getCustomNameserver({ zoneId })
229 .pipe(Effect.catchTag("InvalidZoneIdentifier", () => Effect.undefined));
230 if (observed === undefined) return;
231 // Restore the pre-management state; skip the call when it already
232 // matches (idempotent re-delete after a crashed run).
233 const observedEnabled = observed.enabled ?? false;
234 const observedNsSet = observed.nsSet ?? undefined;
235 if (
236 observedEnabled === initialEnabled &&
237 (initialNsSet === undefined || observedNsSet === initialNsSet)
238 ) {
239 return;
240 }
241 yield* zones
242 .putCustomNameserver({
243 zoneId,
244 enabled: initialEnabled,
245 ...(initialNsSet !== undefined ? { nsSet: initialNsSet } : {}),
246 })
247 .pipe(
248 // Zone deleted out-of-band, or the account nameserver set the
249 // zone originally referenced no longer exists — nothing left to
250 // restore.
251 Effect.catchTag(
252 ["InvalidZoneIdentifier", "CustomNameserverSetNotFound"],
253 () => Effect.void,
254 ),
255 );
256 }),
257 });
258
259 const toAttributes = (
260 zoneId: string,
261 observed: zones.GetCustomNameserverResponse,
262 initialEnabled: boolean,
263 initialNsSet: number | undefined,
264 ): CustomNameserversAttributes => ({
265 zoneId,
266 enabled: observed.enabled ?? false,
267 nsSet: observed.nsSet ?? undefined,
268 initialEnabled,
269 initialNsSet,
270 });