@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, 06:00 UTC

main
ts 513 lines 18.8 KB
Raw
1 import { relativeWorkerMain } from "@alchemy.run/cloudflare/Workers/Worker";
2 import {
3 encodeDurableObjectTags,
4 getDurableObjectTagMap,
5 normalizeStateDomains,
6 orderObservedWorkerRoutes,
7 resolveWorkerDomain,
8 resolveWorkerDomainZone,
9 resolveWorkersDev,
10 shouldRecreateWorkerDomainAttachment,
11 shouldObserveWorkerCrons,
12 shouldObserveWorkerDomains,
13 shouldObserveWorkerRoutes,
14 stateCustomDomains,
15 stateWorkerDomain,
16 } from "@alchemy.run/cloudflare/Workers/WorkerProvider";
17 import { describe, expect, test } from "@alchemy.run/test";
18 import { deepEqual } from "alchemy/Diff";
19 import * as Effect from "effect/Effect";
20 import * as Result from "effect/Result";
21
22 describe(
23 "WorkerProvider",
24 { tags: ["unit", "provider:cloudflare", "provider:cloudflare:worker", "local"] },
25 () => {
26 describe("normalizeStateDomains", () => {
27 // Worker state has gone through three generations: <= beta.44 stored each
28 // custom domain as a `{ id, hostname, zoneId }` object; beta.45 – beta.57
29 // stored `https://<hostname>` URL strings (with the workers.dev URL mixed
30 // in); the current format stores bare hostnames aligned with `allUrls`.
31 // The diff path reads all three without throwing (#546).
32 test("coerces legacy domain objects to hostnames", () => {
33 expect(
34 normalizeStateDomains([{ id: "abc", hostname: "metrics.example.com", zoneId: "z1" }]),
35 ).toEqual(["metrics.example.com"]);
36 });
37
38 test("coerces legacy https:// URL strings to hostnames", () => {
39 expect(
40 normalizeStateDomains(["https://app.example.com", "https://my-worker.acct.workers.dev"]),
41 ).toEqual(["app.example.com", "my-worker.acct.workers.dev"]);
42 });
43
44 test("leaves current-format hostnames untouched", () => {
45 expect(normalizeStateDomains(["app.example.com", "localhost"])).toEqual([
46 "app.example.com",
47 "localhost",
48 ]);
49 });
50
51 test("drops entries that fit no state generation", () => {
52 expect(
53 normalizeStateDomains([
54 "https://keep.example.com",
55 { id: "no-hostname" },
56 { hostname: 123 },
57 null,
58 42,
59 "",
60 ]),
61 ).toEqual(["keep.example.com"]);
62 });
63
64 test("returns an empty array for undefined state", () => {
65 expect(normalizeStateDomains(undefined)).toEqual([]);
66 });
67 });
68
69 describe("stateCustomDomains", () => {
70 test("excludes workers.dev, preview, and local-dev entries", () => {
71 expect(
72 stateCustomDomains([
73 "my-worker.acct.workers.dev",
74 "0a1b2c3d-my-worker.acct.workers.dev",
75 "localhost",
76 "192.168.0.12",
77 "app.example.com",
78 ]),
79 ).toEqual(["app.example.com"]);
80 });
81
82 test("reads legacy URL-string state", () => {
83 expect(
84 stateCustomDomains(["https://app.example.com", "https://my-worker.acct.workers.dev"]),
85 ).toEqual(["app.example.com"]);
86 });
87 });
88
89 describe("resolveWorkerDomain", () => {
90 const resolve = (domain: Parameters<typeof resolveWorkerDomain>[0]) =>
91 Effect.runSync(resolveWorkerDomain(domain));
92
93 test("string shorthand resolves to { name }", () => {
94 expect(resolve("app.example.com")).toEqual({
95 name: "app.example.com",
96 aliases: [],
97 redirects: [],
98 });
99 });
100
101 test("previews: true is preserved", () => {
102 expect(resolve({ name: "app.example.com", previews: true })).toEqual({
103 name: "app.example.com",
104 aliases: [],
105 redirects: [],
106 previews: true,
107 });
108 });
109
110 test("object form dedupes and punycodes hostnames", () => {
111 expect(
112 resolve({
113 name: "📦.example.com",
114 aliases: ["www.example.com", "www.example.com"],
115 redirects: ["old.example.com"],
116 }),
117 ).toEqual({
118 name: "xn--cu8h.example.com",
119 aliases: ["www.example.com"],
120 redirects: ["old.example.com"],
121 });
122 });
123
124 test("undefined and null resolve to no domain", () => {
125 expect(resolve(undefined)).toBeUndefined();
126 expect(resolve(null)).toBeUndefined();
127 });
128
129 // Pre-redesign props stored `domain: string[]` — persisted `olds` can
130 // still hand that shape to read's classification. `domains[0]` was the
131 // primary hostname back then, so it maps to `name`; the rest to
132 // aliases. A legacy empty array was the explicit detach-all.
133 test("legacy string[] maps to name + aliases", () => {
134 expect(resolve(["app.example.com", "www.example.com"])).toEqual({
135 name: "app.example.com",
136 aliases: ["www.example.com"],
137 redirects: [],
138 });
139 expect(resolve([])).toBeUndefined();
140 });
141
142 test("a hostname in more than one role is a typed error", () => {
143 const result = Effect.runSync(
144 Effect.result(
145 resolveWorkerDomain({ name: "app.example.com", aliases: ["app.example.com"] }),
146 ),
147 );
148 expect(Result.isFailure(result)).toBe(true);
149 if (Result.isFailure(result)) {
150 expect(result.failure._tag).toEqual("WorkerDomainConfigError");
151 }
152 });
153
154 test("carries zoneId / zone / zoneName pins", () => {
155 const zoneId = "0123456789abcdef0123456789abcdef";
156 expect(resolve({ name: "app.example.com", zoneId })).toEqual({
157 name: "app.example.com",
158 aliases: [],
159 redirects: [],
160 zone: zoneId,
161 });
162 expect(resolve({ name: "app.example.com", zoneName: "example.com" })).toEqual({
163 name: "app.example.com",
164 aliases: [],
165 redirects: [],
166 zone: "example.com",
167 });
168 expect(
169 resolveWorkerDomainZone({ zoneId, zoneName: "ignored.com", zone: "also-ignored.com" }),
170 ).toEqual(zoneId);
171 });
172
173 test("recreates an existing attachment only for a changed explicit zone", () => {
174 expect(shouldRecreateWorkerDomainAttachment("live-zone", undefined)).toBe(false);
175 expect(shouldRecreateWorkerDomainAttachment("live-zone", "live-zone")).toBe(false);
176 expect(shouldRecreateWorkerDomainAttachment("live-zone", "desired-zone")).toBe(true);
177 });
178 });
179
180 describe("stateWorkerDomain", () => {
181 test("passes the current-format domain attribute through", () => {
182 expect(
183 stateWorkerDomain({
184 domain: {
185 name: "app.example.com",
186 aliases: ["www.example.com"],
187 redirects: ["old.example.com"],
188 },
189 }),
190 ).toEqual({
191 name: "app.example.com",
192 aliases: ["www.example.com"],
193 redirects: ["old.example.com"],
194 });
195 expect(
196 stateWorkerDomain({
197 domain: {
198 name: "app.example.com",
199 aliases: [],
200 redirects: [],
201 zoneId: "0123456789abcdef0123456789abcdef",
202 },
203 }),
204 ).toEqual({
205 name: "app.example.com",
206 aliases: [],
207 redirects: [],
208 zone: "0123456789abcdef0123456789abcdef",
209 });
210 expect(
211 stateWorkerDomain({
212 domain: {
213 name: "app.example.com",
214 aliases: [],
215 redirects: [],
216 zoneId: 42,
217 zoneName: "example.com",
218 },
219 }),
220 ).toEqual({ name: "app.example.com", aliases: [], redirects: [], zone: "example.com" });
221 });
222
223 test("derives name + aliases from legacy URL-string domains state", () => {
224 expect(
225 stateWorkerDomain({
226 domains: [
227 "https://app.example.com",
228 "https://www.example.com",
229 "https://my-worker.acct.workers.dev",
230 ],
231 }),
232 ).toEqual({ name: "app.example.com", aliases: ["www.example.com"], redirects: [] });
233 });
234
235 test("derives from <= beta.44 domain objects", () => {
236 expect(
237 stateWorkerDomain({ domains: [{ id: "abc", hostname: "app.example.com", zoneId: "z" }] }),
238 ).toEqual({ name: "app.example.com", aliases: [], redirects: [] });
239 });
240
241 test("workers.dev-only and empty state resolve to no domain", () => {
242 expect(
243 stateWorkerDomain({ domains: ["https://my-worker.acct.workers.dev"] }),
244 ).toBeUndefined();
245 expect(stateWorkerDomain({})).toBeUndefined();
246 expect(stateWorkerDomain(undefined)).toBeUndefined();
247 });
248 });
249
250 describe("resolveWorkersDev", () => {
251 test("defaults to the full workers.dev behavior", () => {
252 expect(resolveWorkersDev(undefined)).toEqual({ enabled: true, previewsEnabled: true });
253 expect(resolveWorkersDev(true)).toEqual({ enabled: true, previewsEnabled: true });
254 });
255
256 test("false disables both toggles", () => {
257 expect(resolveWorkersDev(false)).toEqual({ enabled: false, previewsEnabled: false });
258 });
259
260 test("object form fills unset toggles with true", () => {
261 expect(resolveWorkersDev({})).toEqual({ enabled: true, previewsEnabled: true });
262 expect(resolveWorkersDev({ enabled: false })).toEqual({
263 enabled: false,
264 previewsEnabled: true,
265 });
266 expect(resolveWorkersDev({ previewsEnabled: false })).toEqual({
267 enabled: true,
268 previewsEnabled: false,
269 });
270 expect(resolveWorkersDev({ enabled: false, previewsEnabled: true })).toEqual({
271 enabled: false,
272 previewsEnabled: true,
273 });
274 });
275 });
276
277 // Cloudflare allows at most 10 tags per worker and 1024 bytes per tag, so
278 // the DO logical-id→class mapping is packed into `alchemy:dos:` tags
279 // instead of one `alchemy:do:` tag per binding (#811).
280 describe("durable object tags", () => {
281 test("packs all mappings into a single tag", () => {
282 expect(
283 encodeDurableObjectTags([
284 { logicalId: "Counter", className: "Counter" },
285 { logicalId: "Meter", className: "MeterV2" },
286 ]),
287 ).toEqual(["alchemy:dos:Counter;Meter=MeterV2"]);
288 });
289
290 test("elides the class name when it equals the logical id", () => {
291 expect(encodeDurableObjectTags([{ logicalId: "A", className: "A" }])).toEqual([
292 "alchemy:dos:A",
293 ]);
294 });
295
296 test("output is deterministic regardless of input order", () => {
297 const forward = encodeDurableObjectTags([
298 { logicalId: "A", className: "A1" },
299 { logicalId: "B", className: "B1" },
300 ]);
301 const reverse = encodeDurableObjectTags([
302 { logicalId: "B", className: "B1" },
303 { logicalId: "A", className: "A1" },
304 ]);
305 expect(forward).toEqual(reverse);
306 });
307
308 test("round-trips through the parser", () => {
309 const mappings = Array.from({ length: 25 }, (_, i) => ({
310 logicalId: `binding-${i}`,
311 className: `ClassName${i}`,
312 }));
313 expect(getDurableObjectTagMap(encodeDurableObjectTags(mappings))).toEqual(
314 Object.fromEntries(mappings.map(({ logicalId, className }) => [logicalId, className])),
315 );
316 });
317
318 test("escapes separators and Cloudflare-forbidden characters", () => {
319 const mappings = [
320 { logicalId: "a;b", className: "C1" },
321 { logicalId: "a=b", className: "C2" },
322 { logicalId: "a,b&c", className: "C3" },
323 { logicalId: "a:b", className: "C4" },
324 ];
325 const tags = encodeDurableObjectTags(mappings);
326 for (const tag of tags) {
327 expect(tag).not.toContain(",");
328 expect(tag).not.toContain("&");
329 }
330 expect(getDurableObjectTagMap(tags)).toEqual({
331 "a;b": "C1",
332 "a=b": "C2",
333 "a,b&c": "C3",
334 "a:b": "C4",
335 });
336 });
337
338 test("splits into multiple tags at the 1024-byte limit", () => {
339 const mappings = Array.from({ length: 100 }, (_, i) => ({
340 logicalId: `some-durable-object-binding-${i}`,
341 className: `SomeDurableObjectClassName${i}`,
342 }));
343 const tags = encodeDurableObjectTags(mappings);
344 expect(tags.length).toBeGreaterThan(1);
345 for (const tag of tags) {
346 expect(tag.length).toBeLessThanOrEqual(1024);
347 expect(tag.startsWith("alchemy:dos:")).toBe(true);
348 }
349 expect(getDurableObjectTagMap(tags)).toEqual(
350 Object.fromEntries(mappings.map(({ logicalId, className }) => [logicalId, className])),
351 );
352 });
353
354 test("unicode identifiers stay within the byte limit", () => {
355 const mappings = Array.from({ length: 40 }, (_, i) => ({
356 logicalId: `对象-${i}`,
357 className: `Class_${i}`,
358 }));
359 const tags = encodeDurableObjectTags(mappings);
360 const encoder = new TextEncoder();
361 for (const tag of tags) {
362 expect(encoder.encode(tag).length).toBeLessThanOrEqual(1024);
363 }
364 expect(getDurableObjectTagMap(tags)).toEqual(
365 Object.fromEntries(mappings.map(({ logicalId, className }) => [logicalId, className])),
366 );
367 });
368
369 test("parses legacy per-DO alchemy:do: tags", () => {
370 expect(
371 getDurableObjectTagMap([
372 "alchemy:stack:app",
373 "alchemy:do:Counter:CounterV2",
374 "alchemy:do:Meter:Meter",
375 "user-tag",
376 ]),
377 ).toEqual({ Counter: "CounterV2", Meter: "Meter" });
378 });
379
380 test("packed entries win over legacy entries for the same logical id", () => {
381 expect(
382 getDurableObjectTagMap(["alchemy:do:Counter:OldClass", "alchemy:dos:Counter=NewClass"]),
383 ).toEqual({ Counter: "NewClass" });
384 });
385
386 test("returns an empty map when no DO tags are present", () => {
387 expect(getDurableObjectTagMap(["alchemy:stack:app", "user"])).toEqual({});
388 });
389 });
390
391 // Worker read used to always fan out listDomains + account-wide route
392 // discovery + getScriptSchedule, even for a plain workers.dev Worker. That
393 // stampeded GET /accounts/{id}/workers/subdomain neighbors into 429/code 971
394 // (#926). These helpers gate those observations on whether Alchemy manages
395 // the surface.
396 describe("shouldObserveWorkerDomains", () => {
397 test("skips when neither props nor state manage custom domains", () => {
398 expect(
399 shouldObserveWorkerDomains({}, { domains: ["https://my-worker.acct.workers.dev"] }),
400 ).toBe(false);
401 expect(shouldObserveWorkerDomains(undefined, undefined)).toBe(false);
402 });
403
404 test("observes when domain prop is present, including null", () => {
405 expect(shouldObserveWorkerDomains({ domain: null }, undefined)).toBe(true);
406 expect(shouldObserveWorkerDomains({ domain: "app.example.com" }, undefined)).toBe(true);
407 });
408
409 test("observes when prior state has non-workers.dev domains", () => {
410 expect(
411 shouldObserveWorkerDomains(
412 {},
413 { domains: ["https://app.example.com", "https://my-worker.acct.workers.dev"] },
414 ),
415 ).toBe(true);
416 });
417 });
418
419 describe("shouldObserveWorkerRoutes", () => {
420 test("skips when neither props nor state manage routes", () => {
421 expect(shouldObserveWorkerRoutes({}, { routes: [] })).toBe(false);
422 expect(shouldObserveWorkerRoutes(undefined, undefined)).toBe(false);
423 });
424
425 test("observes when routes prop is present, including empty array", () => {
426 expect(shouldObserveWorkerRoutes({ routes: [] }, undefined)).toBe(true);
427 expect(
428 shouldObserveWorkerRoutes({ routes: [{ pattern: "example.com/*" }] }, undefined),
429 ).toBe(true);
430 });
431
432 test("observes when prior state has routes", () => {
433 expect(
434 shouldObserveWorkerRoutes(
435 {},
436 { routes: [{ id: "r1", pattern: "example.com/*", zoneId: "z1" }] },
437 ),
438 ).toBe(true);
439 });
440 });
441
442 describe("orderObservedWorkerRoutes", () => {
443 const auth = { id: "r1", pattern: "example.com/auth/*", zoneId: "z1" };
444 const api = { id: "r2", pattern: "example.com/api/*", zoneId: "z1" };
445 const docs = { id: "r3", pattern: "docs.example.com/*", zoneId: "z2" };
446
447 test("matches state order when Cloudflare lists routes in another order", () => {
448 const persisted = [auth, api, docs];
449 const listed = [docs, api, auth];
450 expect(deepEqual(listed, persisted)).toBe(false);
451 expect(deepEqual(orderObservedWorkerRoutes(listed, persisted), persisted)).toBe(true);
452 });
453
454 test("appends routes missing from state in listing order", () => {
455 const extra = { id: "r4", pattern: "example.com/x/*", zoneId: "z1" };
456 expect(orderObservedWorkerRoutes([extra, docs, auth], [auth, api])).toEqual([
457 auth,
458 extra,
459 docs,
460 ]);
461 });
462
463 test("keys routes by zone and pattern", () => {
464 const sameInZ2 = { id: "r5", pattern: auth.pattern, zoneId: "z2" };
465 expect(orderObservedWorkerRoutes([sameInZ2, auth], [auth, sameInZ2])).toEqual([
466 auth,
467 sameInZ2,
468 ]);
469 });
470 });
471
472 describe("shouldObserveWorkerCrons", () => {
473 test("skips when neither props nor state manage crons", () => {
474 expect(shouldObserveWorkerCrons({}, { crons: [] })).toBe(false);
475 expect(shouldObserveWorkerCrons(undefined, undefined)).toBe(false);
476 });
477
478 test("observes when crons prop is present, including empty array", () => {
479 expect(shouldObserveWorkerCrons({ crons: [] }, undefined)).toBe(true);
480 expect(shouldObserveWorkerCrons({ crons: ["0 * * * *"] }, undefined)).toBe(true);
481 });
482
483 test("observes when prior state has crons (e.g. Effect-native cron())", () => {
484 expect(shouldObserveWorkerCrons({}, { crons: ["0 * * * *"] })).toBe(true);
485 });
486 });
487
488 // The live drift-repair test in Worker.test.ts covers a moved checkout
489 // end to end; these pin the path edge cases it doesn't exercise.
490 describe("relativeWorkerMain", () => {
491 test("relativizes a file URL or absolute path inside cwd", () => {
492 expect(relativeWorkerMain("file:///repo/apps/api/src/index.ts", "/repo")).toEqual(
493 "apps/api/src/index.ts",
494 );
495 expect(relativeWorkerMain("/repo/src/worker.ts", "/repo")).toEqual("src/worker.ts");
496 });
497
498 test("keeps relative paths and paths outside cwd", () => {
499 expect(relativeWorkerMain("./src/worker.ts", "/repo")).toEqual("./src/worker.ts");
500 expect(relativeWorkerMain("/other/worker.ts", "/repo")).toEqual("/other/worker.ts");
501 expect(relativeWorkerMain("file:///other/worker.ts", "/repo")).toEqual(
502 "file:///other/worker.ts",
503 );
504 });
505
506 test("decodes escaped characters in file URLs", () => {
507 expect(relativeWorkerMain("file:///my%20repo/src/worker.ts", "/my repo")).toEqual(
508 "src/worker.ts",
509 );
510 });
511 });
512 },
513 );