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

main
ts 280 lines 9.82 KB
Raw
1 import * as snippets from "@distilled.cloud/cloudflare/snippets";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import { createPhysicalName } from "alchemy/PhysicalName";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import * as Effect from "effect/Effect";
8 import * as Predicate from "effect/Predicate";
9 import * as Schedule from "effect/Schedule";
10 import * as Stream from "effect/Stream";
11 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
12 import type { Providers } from "../Providers.ts";
13 import { listAllZones } from "../Zone/lookup.ts";
14
15 export interface SnippetProps {
16 /**
17 * Zone the snippet belongs to. Stable — changing the zone triggers
18 * replacement.
19 */
20 zoneId: string;
21 /**
22 * Name of the snippet. Snippet names may only contain letters, numbers,
23 * and underscores (`[a-zA-Z0-9_]`) — the name is the snippet's identity
24 * within the zone, so changing it triggers replacement.
25 *
26 * If omitted, a unique name is generated from the app, stage, and
27 * logical ID.
28 *
29 * @default ${app}_${id}_${stage}_${suffix}
30 */
31 name?: string;
32 /**
33 * JavaScript source code of the snippet (ES module). Snippets are
34 * lightweight Workers-like scripts with hard platform limits: no
35 * environment variables or bindings, 5ms CPU time, 2MB memory, and a
36 * 32KB compressed size limit (500KB on Enterprise).
37 *
38 * Mutable — updated in place via upload.
39 */
40 code: string;
41 /**
42 * Filename of the snippet's main module as referenced in the upload.
43 *
44 * @default "snippet.js"
45 */
46 mainModule?: string;
47 }
48
49 export interface SnippetAttributes {
50 /** Name identifying the snippet within the zone. */
51 name: string;
52 /** Zone that owns this snippet. */
53 zoneId: string;
54 /** Filename of the snippet's main module. */
55 mainModule: string;
56 /** ISO8601 creation timestamp. */
57 createdOn: string | undefined;
58 /** ISO8601 last-modified timestamp. */
59 modifiedOn: string | undefined;
60 }
61
62 export type Snippet = Resource<
63 "Cloudflare.Snippets.Snippet",
64 SnippetProps,
65 SnippetAttributes,
66 never,
67 Providers
68 >;
69
70 /**
71 * A Cloudflare Snippet — a lightweight JavaScript module that runs on
72 * Cloudflare's edge to modify HTTP traffic for a zone.
73 *
74 * Uploading a snippet does not activate it: traffic only flows through a
75 * snippet once a {@link SnippetRules} rule references it with a matching
76 * expression.
77 *
78 * Safety: snippets carry no ownership markers. When there is no prior
79 * state, `read` looks the snippet up by name and reports an existing match
80 * as `Unowned`, so the engine refuses to take it over unless `--adopt`
81 * (or `adopt(true)`) is set.
82 * ### Creating a Snippet
83 * **Example:** Add a response header
84 * ```typescript
85 * const snippet = yield* Cloudflare.Snippets.Snippet("HeaderSnippet", {
86 * zoneId: zone.zoneId,
87 * code: `
88 * export default {
89 * async fetch(request) {
90 * const response = await fetch(request);
91 * const headers = new Headers(response.headers);
92 * headers.set("x-snippet", "hello");
93 * return new Response(response.body, { ...response, headers });
94 * },
95 * };
96 * `,
97 * });
98 * ```
99 *
100 * ### Activating with Snippet Rules
101 * **Example:** Route traffic through the snippet
102 * ```typescript
103 * yield* Cloudflare.Snippets.SnippetRules("Rules", {
104 * zoneId: zone.zoneId,
105 * rules: [
106 * {
107 * snippetName: snippet.name,
108 * expression: 'http.request.uri.path wildcard "/api/*"',
109 * },
110 * ],
111 * });
112 * ```
113 *
114 * @resource
115 * @product Snippets
116 * @category Rules & Configuration
117 */
118 export const Snippet = Resource<Snippet>("Cloudflare.Snippets.Snippet");
119
120 export const isSnippet = (value: unknown): value is Snippet =>
121 Predicate.hasProperty(value, "Type") && value.Type === "Cloudflare.Snippets.Snippet";
122
123 const DEFAULT_MAIN_MODULE = "snippet.js";
124
125 export const SnippetProvider = () =>
126 Provider.succeed(Snippet, {
127 stables: ["name", "zoneId", "createdOn"],
128
129 list: Effect.fn(function* () {
130 const { accountId } = yield* yield* CloudflareEnvironment;
131 // Snippets live inside a zone with no account-wide enumeration
132 // API — fan out across every zone and list snippets per zone.
133 const zones = yield* listAllZones(accountId);
134 const rows = yield* Effect.forEach(
135 zones,
136 (zone) =>
137 snippets.listSnippets.pages({ zoneId: zone.id }).pipe(
138 Stream.runCollect,
139 Effect.map((chunk) =>
140 Array.from(chunk).flatMap((page) =>
141 (page.result ?? []).map((s): SnippetAttributes => ({
142 name: s.snippetName,
143 zoneId: zone.id,
144 // The list response carries no main module; snippets
145 // upload under the engine default and `read` falls
146 // back to it too, so report the same here.
147 mainModule: DEFAULT_MAIN_MODULE,
148 createdOn: s.createdOn,
149 modifiedOn: s.modifiedOn ?? undefined,
150 })),
151 ),
152 ),
153 // Plan-gated / partial-permission zones reject the route; skip.
154 Effect.catchTag("Forbidden", () => Effect.succeed([] as SnippetAttributes[])),
155 ),
156 { concurrency: 10 },
157 );
158 return rows.flat();
159 }),
160
161 diff: Effect.fn(function* ({ id, olds, news, output }) {
162 if (!isResolved(news)) return undefined;
163 const o = olds as SnippetProps;
164 const n = news as SnippetProps;
165
166 // Name is the snippet's identity within the zone.
167 const oldName = output?.name ?? (yield* createSnippetName(id, o.name as string));
168 // Auto-generated names are engine-owned: the deployed name stays
169 // authoritative even if the generator would name this id differently
170 // today. Only an explicit user-provided name can force a replace.
171 const name = n.name ?? oldName;
172 if (oldName !== name) {
173 return { action: "replace" } as const;
174 }
175 // zoneId is Input<string>; only compare once both are concrete.
176 const oldZoneId = output?.zoneId ?? (typeof o.zoneId === "string" ? o.zoneId : undefined);
177 if (typeof n.zoneId === "string" && oldZoneId !== undefined && oldZoneId !== n.zoneId) {
178 return { action: "replace" } as const;
179 }
180 }),
181
182 read: Effect.fn(function* ({ id, olds, output }) {
183 // Owned path: refresh from persisted identity.
184 if (output?.name && output.zoneId) {
185 const observed = yield* getSnippetOrUndefined(output.zoneId, output.name);
186 if (observed) {
187 return toAttributes(observed, output.zoneId, output.mainModule);
188 }
189 return undefined;
190 }
191 // Cold read: derive the deterministic name and look it up. Snippets
192 // carry no ownership markers, so an existing match is `Unowned` and
193 // takeover is gated behind the adopt policy.
194 const zoneId = output?.zoneId ?? (olds?.zoneId as string | undefined);
195 if (!zoneId) return undefined;
196 const name = output?.name ?? (yield* createSnippetName(id, olds?.name));
197 const observed = yield* getSnippetOrUndefined(zoneId, name);
198 if (observed) {
199 return Unowned(toAttributes(observed, zoneId, olds?.mainModule ?? DEFAULT_MAIN_MODULE));
200 }
201 return undefined;
202 }),
203
204 reconcile: Effect.fn(function* ({ id, news, output }) {
205 // Inputs have been resolved to concrete values by Plan.
206 const zoneId = (output?.zoneId ?? news.zoneId) as string;
207 const name = output?.name ?? (yield* createSnippetName(id, news.name));
208 const mainModule = news.mainModule ?? DEFAULT_MAIN_MODULE;
209
210 // `putSnippet` (PUT) is a true upsert — one call converges greenfield
211 // create, routine update, and adoption alike.
212 const file = yield* Effect.sync(
213 () =>
214 new File([news.code], mainModule, {
215 type: "application/javascript+module",
216 }),
217 );
218 const synced = yield* snippets.putSnippet({
219 zoneId,
220 snippetName: name,
221 metadata: { mainModule },
222 files: file,
223 });
224
225 return toAttributes(synced, zoneId, mainModule);
226 }),
227
228 delete: Effect.fn(function* ({ output }) {
229 yield* snippets
230 .deleteSnippet({
231 zoneId: output.zoneId,
232 snippetName: output.name,
233 })
234 // A snippet can only be deleted once no snippet rule references it.
235 // The engine deletes referencing `SnippetRules` first (dependency
236 // edge via `snippetName`), but the rule removal is eventually
237 // consistent — Cloudflare may still report `snippet is still used`
238 // for a short window. Bounded-retry that lag before giving up.
239 .pipe(
240 Effect.retry({
241 while: (e) => e._tag === "SnippetInUse",
242 schedule: Schedule.max([Schedule.exponential("1 second"), Schedule.recurs(8)]),
243 }),
244 Effect.catchTag("SnippetNotFound", () => Effect.void),
245 );
246 }),
247 });
248
249 /**
250 * Snippet names only allow letters, numbers, and underscores; physical
251 * names are generated with `_` separators and any residual hyphens (from
252 * the app/stage/id) are normalized to underscores.
253 */
254 const createSnippetName = (id: string, name: string | undefined) =>
255 Effect.gen(function* () {
256 if (name) return name;
257 const physical = yield* createPhysicalName({
258 id,
259 lowercase: true,
260 delimiter: "_",
261 });
262 return physical.replaceAll("-", "_");
263 });
264
265 const getSnippetOrUndefined = (zoneId: string, snippetName: string) =>
266 snippets
267 .getSnippet({ zoneId, snippetName })
268 .pipe(Effect.catchTag("SnippetNotFound", () => Effect.undefined));
269
270 const toAttributes = (
271 observed: snippets.GetSnippetResponse,
272 zoneId: string,
273 mainModule: string,
274 ): SnippetAttributes => ({
275 name: observed.snippetName,
276 zoneId,
277 mainModule,
278 createdOn: observed.createdOn,
279 modifiedOn: observed.modifiedOn ?? undefined,
280 });