@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 229 lines 8.34 KB
Raw
1 import * as urlNormalization from "@distilled.cloud/cloudflare/url-normalization";
2 import * as Provider from "alchemy/Provider";
3 import { Resource } from "alchemy/Resource";
4 import * as Effect from "effect/Effect";
5 import * as Predicate from "effect/Predicate";
6 import * as Schedule from "effect/Schedule";
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.UrlNormalization.UrlNormalization" as const;
12 type TypeId = typeof TypeId;
13
14 /**
15 * Which URLs Cloudflare normalizes.
16 *
17 * - `"incoming"` — normalize the URLs used for rule matching only
18 * (Cloudflare's zone default).
19 * - `"both"` — additionally normalize the URLs forwarded to the origin.
20 * - `"none"` — disable URL normalization entirely.
21 */
22 export type UrlNormalizationScope = "incoming" | "both" | "none";
23
24 /**
25 * Which normalization algorithm Cloudflare applies.
26 *
27 * - `"cloudflare"` — RFC 3986 normalization plus Cloudflare's extra
28 * normalizations (e.g. collapsing `//` sequences). The zone default.
29 * - `"rfc3986"` — strict RFC 3986 normalization only.
30 */
31 export type Type = "cloudflare" | "rfc3986";
32
33 export interface Props {
34 /**
35 * Zone whose URL normalization is managed. Stable — changing the zone
36 * triggers a replacement (the old zone's URL normalization is reset to
37 * Cloudflare defaults as the old instance deletes).
38 */
39 zoneId: string;
40 /**
41 * The scope of the URL normalization: `"incoming"` normalizes URLs used
42 * for rule matching only, `"both"` also normalizes URLs sent to the
43 * origin, `"none"` disables normalization.
44 *
45 * Mutable — updated in place.
46 *
47 * @default "incoming"
48 */
49 scope?: UrlNormalizationScope;
50 /**
51 * The type of URL normalization performed by Cloudflare:
52 * `"cloudflare"` is RFC 3986 plus extra normalizations (e.g. `//`
53 * collapsing), `"rfc3986"` is strict RFC 3986 only.
54 *
55 * Mutable — updated in place.
56 *
57 * @default "cloudflare"
58 */
59 type?: Type;
60 }
61
62 export interface Attributes {
63 /** Zone whose URL normalization is managed. */
64 zoneId: string;
65 /** Observed scope of the URL normalization. */
66 scope: string;
67 /** Observed type of URL normalization performed by Cloudflare. */
68 type: string;
69 }
70
71 export type UrlNormalization = Resource<TypeId, Props, Attributes, never, Providers>;
72
73 /**
74 * The URL normalization configuration of a Cloudflare zone
75 * (`/zones/{zone_id}/url_normalization`) — a zone-scoped **singleton**
76 * controlling how Cloudflare normalizes incoming URLs before rule matching
77 * and before forwarding to the origin.
78 *
79 * The setting always exists on every zone (with Cloudflare defaults
80 * `scope: "incoming"`, `type: "cloudflare"`), so reconcile adopts the
81 * singleton and PUTs the desired `{ scope, type }` only when the observed
82 * configuration differs. Destroy issues the API's true reset operation
83 * (DELETE), returning the zone to Cloudflare defaults.
84 * ### Managing URL normalization
85 * **Example:** Normalize URLs sent to the origin too
86 * ```typescript
87 * yield* Cloudflare.UrlNormalization.UrlNormalization("UrlNormalization", {
88 * zoneId: zone.zoneId,
89 * scope: "both",
90 * });
91 * ```
92 *
93 * **Example:** Strict RFC 3986 normalization
94 * ```typescript
95 * yield* Cloudflare.UrlNormalization.UrlNormalization("UrlNormalization", {
96 * zoneId: zone.zoneId,
97 * scope: "incoming",
98 * type: "rfc3986",
99 * });
100 * ```
101 *
102 * **Example:** Disable URL normalization
103 * ```typescript
104 * yield* Cloudflare.UrlNormalization.UrlNormalization("UrlNormalization", {
105 * zoneId: zone.zoneId,
106 * scope: "none",
107 * });
108 * ```
109 *
110 * @see https://developers.cloudflare.com/rules/normalization/
111 *
112 * @resource
113 * @product URL Normalization
114 * @category Rules & Configuration
115 */
116 export const UrlNormalization = Resource<UrlNormalization>(TypeId, {
117 aliases: ["Cloudflare.UrlNormalization"],
118 });
119
120 /**
121 * Returns true if the given value is a UrlNormalization resource.
122 */
123 export const isUrlNormalization = (value: unknown): value is UrlNormalization =>
124 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
125
126 /** Cloudflare's zone default scope. */
127 const DEFAULT_SCOPE: UrlNormalizationScope = "incoming";
128 /** Cloudflare's zone default normalization type. */
129 const DEFAULT_TYPE: Type = "cloudflare";
130
131 export const UrlNormalizationProvider = () =>
132 Provider.succeed(UrlNormalization, {
133 nuke: { singleton: true },
134 stables: ["zoneId"],
135
136 list: Effect.fn(function* () {
137 const { accountId } = yield* yield* CloudflareEnvironment;
138 // No account-wide API for this zone singleton — enumerate every
139 // zone in the account and read its URL normalization (every zone
140 // has one).
141 const allZones = yield* listAllZones(accountId);
142 const rows = yield* Effect.forEach(
143 allZones.map((zone) => zone.id),
144 (zoneId) =>
145 urlNormalization.getUrlNormalization({ zoneId }).pipe(
146 // Cloudflare intermittently rejects a *valid* token with
147 // `Forbidden` (a transient edge auth failure). Retry with capped
148 // backoff rather than dropping the zone, so a genuinely accessible
149 // zone never falls out of the enumeration on a blip.
150 Effect.retry({
151 while: (e) => e._tag === "Forbidden",
152 schedule: Schedule.max([
153 Schedule.min([Schedule.exponential("500 millis"), Schedule.spaced("5 seconds")]),
154 Schedule.recurs(8),
155 ]),
156 }),
157 Effect.map((observed) => toAttributes(zoneId, observed)),
158 // Plan-gated or partial zones reject the route; skip them.
159 Effect.catchTag("InvalidRoute", () => Effect.undefined),
160 ),
161 { concurrency: 10 },
162 );
163 return rows.filter((row): row is Attributes => row !== undefined);
164 }),
165
166 diff: Effect.fn(function* ({ olds = {}, news, output }) {
167 const o = olds as Props;
168 const n = news as Props;
169 // zoneId is Input<string>; compare only once both sides are concrete.
170 const oldZoneId = output?.zoneId ?? (typeof o.zoneId === "string" ? o.zoneId : undefined);
171 if (oldZoneId !== undefined && typeof n.zoneId === "string" && oldZoneId !== n.zoneId) {
172 return { action: "replace" } as const;
173 }
174 return undefined;
175 }),
176
177 read: Effect.fn(function* ({ output, olds }) {
178 const zoneId = output?.zoneId ?? (olds?.zoneId as string | undefined);
179 if (!zoneId) return undefined;
180 // The setting is a singleton that always exists with Cloudflare
181 // defaults — there is nothing to "own", so a cold read adopts freely
182 // (never `Unowned`). A dead zone reads as gone.
183 const observed = yield* urlNormalization
184 .getUrlNormalization({ zoneId })
185 .pipe(Effect.catchTag("InvalidRoute", () => Effect.undefined));
186 if (observed === undefined) return undefined;
187 return toAttributes(zoneId, observed);
188 }),
189
190 reconcile: Effect.fn(function* ({ news }) {
191 // Inputs have been resolved to concrete strings by Plan.
192 const zoneId = news.zoneId as string;
193 const desiredScope = news.scope ?? DEFAULT_SCOPE;
194 const desiredType = news.type ?? DEFAULT_TYPE;
195
196 // 1. Observe — the singleton always exists on a live zone.
197 const observed = yield* urlNormalization.getUrlNormalization({ zoneId });
198
199 // 2. Sync — PUT is a full replace of { scope, type }; skip the API
200 // entirely when the observed configuration already matches.
201 if (observed.scope === desiredScope && observed.type === desiredType) {
202 return toAttributes(zoneId, observed);
203 }
204 const updated = yield* urlNormalization.putUrlNormalization({
205 zoneId,
206 scope: desiredScope,
207 type: desiredType,
208 });
209 return toAttributes(zoneId, updated);
210 }),
211
212 delete: Effect.fn(function* ({ output }) {
213 // True reset operation — returns the zone to Cloudflare defaults.
214 // Idempotent: resetting an already-default zone succeeds, and a dead
215 // zone is treated as already reset.
216 yield* urlNormalization
217 .deleteUrlNormalization({ zoneId: output.zoneId })
218 .pipe(Effect.catchTag("InvalidRoute", () => Effect.void));
219 }),
220 });
221
222 const toAttributes = (
223 zoneId: string,
224 observed: urlNormalization.GetUrlNormalizationResponse,
225 ): Attributes => ({
226 zoneId,
227 scope: observed.scope,
228 type: observed.type,
229 });