@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 289 lines 10.1 KB
Raw
1 import * as NodeFs from "node:fs";
2 import * as NodeHttp from "node:http";
3 import type * as NodeNet from "node:net";
4 import * as Effect from "effect/Effect";
5 import { describe, expect, it, vi } from "vitest";
6 import {
7 makeCloudflareDevPlatform,
8 resolveClientModulePath,
9 resolveDevPluginPath,
10 type OpenDevProxy,
11 } from "../dev/host.ts";
12 import { RUNTIME_CONFIG_KEY, type DevConnectInfo } from "../dev/shared.ts";
13 import { fromHarnessOptions } from "../index.ts";
14
15 // The plugin runs inside nitro's dev SSR worker thread; in the test we stand
16 // in for nitro: `defineNitroPlugin` is identity and `useRuntimeConfig`
17 // serves whatever the test put in the holder.
18 const nitro = vi.hoisted(() => ({ config: {} as Record<string, unknown> }));
19 vi.mock("nitropack/runtime", () => ({
20 defineNitroPlugin: (plugin: unknown) => plugin,
21 useRuntimeConfig: () => nitro.config,
22 }));
23
24 // The protocol constants the fake proxy server speaks (the same public
25 // subpath the runtime-free client is built on).
26 const loadProtocol = () =>
27 import("@alchemy.run/cloudflare-runtime/core/platform-proxy/PlatformProxyProtocol");
28
29 const listen = (server: NodeHttp.Server): Promise<string> =>
30 new Promise((resolve) => {
31 server.listen(0, "127.0.0.1", () => {
32 const address = server.address() as NodeNet.AddressInfo;
33 resolve(`http://127.0.0.1:${address.port}/`);
34 });
35 });
36
37 const close = (server: NodeHttp.Server): Promise<void> =>
38 new Promise((resolve) => server.close(() => resolve()));
39
40 /** A fake platform-proxy: /env descriptor + a KV-ish /call implementation. */
41 const makeFakeProxy = async (token: string) => {
42 const protocol = await loadProtocol();
43 const store = new Map<string, string>();
44 const server = NodeHttp.createServer((request, response) => {
45 if (request.headers[protocol.HEADER_TOKEN] !== token) {
46 response.statusCode = 401;
47 response.end("unauthorized");
48 return;
49 }
50 if (request.url === protocol.PATH_ENV) {
51 response.setHeader("content-type", "application/json");
52 response.end(
53 JSON.stringify({
54 bindings: [
55 {
56 name: "TEXT",
57 kind: "value",
58 value: { $: "string", value: "hello" },
59 },
60 {
61 name: "OVERRIDDEN",
62 kind: "value",
63 value: { $: "string", value: "proxied" },
64 },
65 { name: "KV", kind: "stub" },
66 ],
67 }),
68 );
69 return;
70 }
71 if (request.url === protocol.PATH_CALL) {
72 let body = "";
73 request.on("data", (chunk: Buffer) => (body += chunk.toString()));
74 request.on("end", () => {
75 const call = JSON.parse(body) as {
76 binding: string;
77 chain: Array<{
78 method: string;
79 args: Array<{ $: string; value?: unknown }>;
80 }>;
81 };
82 const [segment] = call.chain;
83 let result: unknown = null;
84 if (segment?.method === "put") {
85 store.set(String(segment.args[0]?.value), String(segment.args[1]?.value));
86 result = undefined;
87 } else if (segment?.method === "get") {
88 result = store.get(String(segment.args[0]?.value)) ?? null;
89 }
90 response.setHeader(protocol.HEADER_RESULT, "json");
91 response.setHeader("content-type", "application/json");
92 response.end(JSON.stringify({ value: protocol.encodeValue(result) }));
93 });
94 return;
95 }
96 response.statusCode = 404;
97 response.end();
98 });
99 const url = await listen(server);
100 return { url, close: () => close(server) };
101 };
102
103 /** Load the shipped dev plugin fresh and hand it a captured nitroApp. */
104 const setupPlugin = async (config: Record<string, unknown>) => {
105 nitro.config = config;
106 vi.resetModules();
107 const { default: plugin } = (await import("../dev/plugin.ts")) as unknown as {
108 default: (app: unknown) => void;
109 };
110 const hooks = new Map<string, (event: unknown) => Promise<void>>();
111 plugin({
112 hooks: {
113 hook: (name: string, handler: (event: unknown) => Promise<void>) => {
114 hooks.set(name, handler);
115 },
116 },
117 });
118 return hooks;
119 };
120
121 const makeEvent = () => ({
122 context: {} as Record<string, unknown>,
123 node: {
124 req: {
125 url: "/api/test?x=1",
126 method: "GET",
127 headers: { host: "localhost:3000", accept: "application/json" },
128 },
129 },
130 });
131
132 describe("module resolution", () => {
133 it("resolves the shipped dev plugin next to the host module", () => {
134 const path = resolveDevPluginPath();
135 expect(path).toMatch(/dev[/\\]plugin\.(ts|js)$/);
136 expect(NodeFs.existsSync(path)).toBe(true);
137 });
138
139 it("resolves the runtime-free client module from this package's dependencies", () => {
140 const path = resolveClientModulePath();
141 expect(path).toMatch(/platform-proxy[/\\]connect\./);
142 expect(NodeFs.existsSync(path)).toBe(true);
143 });
144 });
145
146 describe("makeCloudflareDevPlatform", () => {
147 it("opens the proxy, injects the plugin + connect info, and disposes with the scope", async () => {
148 let disposed = 0;
149 let openedWith: Parameters<OpenDevProxy>[0] | undefined;
150 const openProxy: OpenDevProxy = async (options) => {
151 openedWith = options;
152 return {
153 url: "http://127.0.0.1:4321/",
154 token: "test-token",
155 dispose: async () => {
156 disposed += 1;
157 },
158 };
159 };
160 const bindings = [{ kind: "text" }];
161 const platform = await Effect.runPromise(
162 Effect.scoped(
163 Effect.gen(function* () {
164 const platform = yield* makeCloudflareDevPlatform({
165 openProxy,
166 compatibilityDate: "2026-03-10",
167 compatibilityFlags: ["nodejs_compat"],
168 })({
169 root: "/tmp/project",
170 env: { LITERAL: "value", SKIPPED: { not: "a string" } },
171 bindings,
172 });
173 // Still alive inside the scope.
174 expect(disposed).toBe(0);
175 return platform;
176 }),
177 ),
178 );
179 expect(disposed).toBe(1);
180 expect(openedWith?.name).toBe("nuxt-dev-platform-proxy");
181 expect(openedWith?.compatibilityDate).toBe("2026-03-10");
182 expect(openedWith?.bindings).toBe(bindings);
183 expect(platform.nitroPlugins).toEqual([resolveDevPluginPath()]);
184 const info = (platform.runtimeConfig as Record<string, DevConnectInfo>)[RUNTIME_CONFIG_KEY];
185 expect(info).toBeDefined();
186 expect(info?.url).toBe("http://127.0.0.1:4321/");
187 expect(info?.token).toBe("test-token");
188 expect(info?.clientModule).toBe(resolveClientModulePath());
189 // Literal env: strings only.
190 expect(info?.env).toEqual({ LITERAL: "value" });
191 });
192
193 it("maps the open failure onto DeployTargetError", async () => {
194 const openProxy: OpenDevProxy = async () => {
195 throw new Error("workerd exploded");
196 };
197 const result = await Effect.runPromise(
198 Effect.result(
199 Effect.scoped(makeCloudflareDevPlatform({ openProxy })({ root: "/tmp/project" })),
200 ),
201 );
202 expect(result._tag).toBe("Failure");
203 if (result._tag === "Failure") {
204 const failure = result.failure as { _tag: string; message: string };
205 expect(failure._tag).toBe("DeployTargetError");
206 expect(failure.message).toContain("Failed to open the dev platform proxy");
207 }
208 });
209 });
210
211 describe("dev plugin (worker half)", () => {
212 it("serves the cloudflare dev context through the runtime-free client", async () => {
213 const token = "plugin-token";
214 const proxy = await makeFakeProxy(token);
215 try {
216 const info: DevConnectInfo = {
217 url: proxy.url,
218 token,
219 clientModule: resolveClientModulePath(),
220 env: { OVERRIDDEN: "literal-wins" },
221 };
222 const hooks = await setupPlugin({ [RUNTIME_CONFIG_KEY]: info });
223 const onRequest = hooks.get("request");
224 expect(onRequest).toBeDefined();
225
226 const event = makeEvent();
227 await onRequest!(event);
228
229 const cf = event.context.cf as Record<string, unknown>;
230 expect(cf.country).toBe("US");
231 // waitUntil is detachable (h3 consumers call it bare).
232 const waitUntil = event.context.waitUntil as (promise: Promise<unknown>) => void;
233 waitUntil(Promise.resolve());
234
235 const cloudflare = event.context.cloudflare as {
236 request: Request | undefined;
237 env: Record<string, unknown>;
238 context: { waitUntil: (promise: Promise<unknown>) => void };
239 };
240 expect(cloudflare.request?.url).toBe("http://localhost:3000/api/test?x=1");
241 expect((cloudflare.request as { cf?: unknown } | undefined)?.cf).toBe(cf);
242 expect(cloudflare.env.TEXT).toBe("hello");
243 // Literal env overlay: a same-named literal wins over the proxied value.
244 expect(cloudflare.env.OVERRIDDEN).toBe("literal-wins");
245 const kv = cloudflare.env.KV as {
246 put: (key: string, value: string) => Promise<void>;
247 get: (key: string) => Promise<string | null>;
248 };
249 await kv.put("k", "v");
250 expect(await kv.get("k")).toBe("v");
251 expect(await kv.get("missing")).toBeNull();
252 } finally {
253 await proxy.close();
254 }
255 });
256
257 it("stays inert without connect info", async () => {
258 const hooks = await setupPlugin({});
259 expect(hooks.size).toBe(0);
260 });
261
262 it("fails descriptively when the proxy rejects the token, then retries", async () => {
263 const proxy = await makeFakeProxy("right-token");
264 try {
265 const info: DevConnectInfo = {
266 url: proxy.url,
267 token: "wrong-token",
268 clientModule: resolveClientModulePath(),
269 };
270 const hooks = await setupPlugin({ [RUNTIME_CONFIG_KEY]: info });
271 const onRequest = hooks.get("request");
272 await expect(onRequest!(makeEvent())).rejects.toThrow(/\/env request failed with status 401/);
273 // The failed connection was not cached: the next request retries.
274 await expect(onRequest!(makeEvent())).rejects.toThrow(/\/env request failed with status 401/);
275 } finally {
276 await proxy.close();
277 }
278 });
279 });
280
281 describe("fromHarnessOptions (dev)", () => {
282 it("passes the harness worker's binding hooks through to dev.bindings", () => {
283 const bindings = [{ hook: true }];
284 const options = fromHarnessOptions({
285 target: { cloudflare: { worker: { worker: { bindings } } } },
286 });
287 expect(options.dev?.bindings).toBe(bindings);
288 });
289 });