@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 348 lines 13.4 KB
Raw
1 import * as NodeFs from "node:fs";
2 import * as NodeHttp from "node:http";
3 import { createRequire } from "node:module";
4 import type * as NodeNet from "node:net";
5 import type * as NodeVm from "node:vm";
6 // Alchemy modifications are licensed under Apache-2.0.
7 // This file includes third-party code; see /THIRD_PARTY_LICENSES.md.
8 /**
9 * Next.js dev v2 — real `next dev` (Turbopack HMR) with Cloudflare bindings,
10 * wrangler-free.
11 *
12 * {@link start} runs the documented custom-server API programmatically
13 * (`next({ dev: true, dir, hostname, port })` + `prepare()` +
14 * `getRequestHandler()` attached to an http.Server we own), so the caller
15 * controls the port/URL and shutdown is a clean `app.close()` — no CLI fork,
16 * no signal handlers, no `process.exit` choreography.
17 *
18 * Before the dev server starts, a `cloudflare-runtime` platform proxy
19 * ({@link PlatformProxy.open}) is opened with the worker's binding hooks and
20 * the resulting `{ env, cf, ctx }` is planted on
21 * `globalThis[Symbol.for("__cloudflare-context__")]` — the exact contract
22 * `@opennextjs/cloudflare`'s `getCloudflareContext()` reads (see upstream
23 * `src/api/cloudflare-context.ts`). `vm.runInContext` is additionally patched
24 * so Next's edge-runtime sandbox (middleware, edge routes) sees the same
25 * context, mirroring OpenNext's `monkeyPatchVmModuleEdgeContext`. App code
26 * therefore works without calling `initOpenNextCloudflareForDev()` and
27 * without wrangler.
28 *
29 * Fidelity notes (documented in the package README): app code runs in Node
30 * (or Next's edge-runtime VM), not workerd — bindings round-trip through the
31 * proxy, but CF-specific runtime behavior (workerd APIs and limits, ISR/cache
32 * semantics of the built worker) still needs the preview mode.
33 */
34 import type {
35 BindingHooks,
36 WorkerdLogging,
37 WorkerdOptions,
38 } from "@alchemy.run/cloudflare-runtime/core";
39 import * as PlatformProxy from "@alchemy.run/cloudflare-runtime/core/platform-proxy/PlatformProxy";
40 import type * as Runtime from "@alchemy.run/cloudflare-runtime/core/Runtime";
41 import * as Effect from "effect/Effect";
42 import type * as Scope from "effect/Scope";
43 import * as FrameworkCore from "../core/index.ts";
44
45 /** The symbol OpenNext uses to store/read the Cloudflare context. Must stay
46 * in sync with `@opennextjs/cloudflare`'s `cloudflareContextSymbol`. */
47 export const CLOUDFLARE_CONTEXT_SYMBOL: unique symbol = Symbol.for("__cloudflare-context__");
48
49 /** The shape `getCloudflareContext()` expects (upstream `CloudflareContext`). */
50 export interface CloudflareContextShape {
51 readonly env: Record<string, unknown>;
52 readonly cf: Record<string, unknown> | undefined;
53 readonly ctx: unknown;
54 }
55
56 export interface DevServerOptions {
57 /** The Next.js project root (the directory containing `next.config.*`). */
58 readonly root: string;
59 /** @default "localhost" */
60 readonly hostname?: string | undefined;
61 /** Port to listen on. Defaults to an ephemeral port. */
62 readonly port?: number | undefined;
63 /**
64 * Bindings to expose through `getCloudflareContext().env` — the same hook
65 * shapes `Runtime.start` accepts (`Text.local`, `KvNamespace.local`, …).
66 */
67 readonly bindings?: BindingHooks | undefined;
68 /** Compatibility date for the binding-proxy worker. */
69 readonly compatibilityDate?: string | undefined;
70 /** Compatibility flags for the binding-proxy worker. */
71 readonly compatibilityFlags?: ReadonlyArray<string> | undefined;
72 /** Name of the binding-proxy workerd service. @default "nextjs-dev-platform-proxy" */
73 readonly proxyName?: string | undefined;
74 readonly logging?: WorkerdLogging | undefined;
75 /** Overrides for the binding proxy's `workerd` process. */
76 readonly workerd?: WorkerdOptions | undefined;
77 }
78
79 export interface DevServerInstance {
80 /** The local URL the dev server is listening on. */
81 readonly url: URL;
82 }
83
84 const fail = (message: string) => (cause: unknown) =>
85 new FrameworkCore.FrameworkError({ framework: "nextjs", message, cause });
86
87 // ---------------------------------------------------------------------------
88 // Cloudflare-context planting (OpenNext contract)
89 // ---------------------------------------------------------------------------
90
91 type GlobalWithContext = typeof globalThis & {
92 [CLOUDFLARE_CONTEXT_SYMBOL]?: CloudflareContextShape | undefined;
93 };
94
95 /**
96 * The context currently planted by an open dev server. The `vm.runInContext`
97 * patch consults this mutable reference so the (process-global, one-time)
98 * patch always reflects the latest scope: cleared on release, re-set by the
99 * next `start`.
100 */
101 let currentContext: CloudflareContextShape | undefined;
102 let vmPatched = false;
103
104 /**
105 * Mirror of OpenNext's `monkeyPatchVmModuleEdgeContext`: Next dev evaluates
106 * edge functions (middleware, edge routes) with `vm.runInContext`, whose
107 * sandbox does not inherit `globalThis` symbols — inject the context into
108 * every contextified object so `getCloudflareContext()` works there too.
109 * Patched once per process; a cleared {@link currentContext} makes it a
110 * pass-through.
111 */
112 const patchVmRunInContext = (): void => {
113 if (vmPatched) return;
114 vmPatched = true;
115 // The ESM namespace of "node:vm" is frozen; patch the (shared, mutable)
116 // CJS exports object — the one Next's sandbox `require`s.
117 const vm = createRequire(import.meta.url)("vm") as typeof NodeVm;
118 const original = vm.runInContext.bind(vm);
119 const patched: typeof vm.runInContext = (code, contextifiedObject, options) => {
120 if (currentContext !== undefined) {
121 const runtimeContext = contextifiedObject as GlobalWithContext;
122 runtimeContext[CLOUDFLARE_CONTEXT_SYMBOL] ??= currentContext;
123 }
124 return original(code, contextifiedObject, options);
125 };
126 vm.runInContext = patched;
127 };
128
129 /**
130 * Plant `{ env, cf, ctx }` on the global symbol (and arm the vm patch) for
131 * the lifetime of the surrounding scope; the previous value is restored on
132 * release.
133 */
134 const plantCloudflareContext = (
135 context: CloudflareContextShape,
136 ): Effect.Effect<void, never, Scope.Scope> =>
137 Effect.acquireRelease(
138 Effect.sync(() => {
139 const global = globalThis as GlobalWithContext;
140 const previous = global[CLOUDFLARE_CONTEXT_SYMBOL];
141 global[CLOUDFLARE_CONTEXT_SYMBOL] = context;
142 currentContext = context;
143 patchVmRunInContext();
144 return previous;
145 }),
146 (previous) =>
147 Effect.sync(() => {
148 (globalThis as GlobalWithContext)[CLOUDFLARE_CONTEXT_SYMBOL] = previous;
149 currentContext = previous;
150 }),
151 ).pipe(Effect.asVoid);
152
153 // ---------------------------------------------------------------------------
154 // Loading `next` from the project root
155 // ---------------------------------------------------------------------------
156
157 type RequestHandler = (
158 req: NodeHttp.IncomingMessage,
159 res: NodeHttp.ServerResponse,
160 ) => Promise<void>;
161
162 /** The subset of `NextCustomServer` (the public custom-server API) we drive. */
163 interface NextDevApp {
164 prepare(): Promise<void>;
165 getRequestHandler(): RequestHandler;
166 close(): Promise<void>;
167 }
168
169 type CreateNextServer = (options: {
170 dev: boolean;
171 dir: string;
172 hostname: string;
173 port: number;
174 }) => NextDevApp;
175
176 /**
177 * Resolve the *project's* `next` (public entry, `dist/server/next.js`) — the
178 * fixture/app's installed copy is the one driven, never a hoisted sibling.
179 * The entry is CJS; unwrap the ESM-interop `default` nesting to the
180 * `createServer` function.
181 */
182 const loadNext = (root: string): Effect.Effect<CreateNextServer, FrameworkCore.FrameworkError> =>
183 FrameworkCore.loadProjectModule<Record<string, unknown>>(root, "next").pipe(
184 Effect.mapError((error) => fail(`Failed to load "next" from ${root}`)(error.cause)),
185 Effect.flatMap((module_) => {
186 let candidate: unknown = module_;
187 for (let i = 0; i < 3 && typeof candidate !== "function"; i++) {
188 candidate = (candidate as Record<string, unknown> | undefined)?.default;
189 }
190 return typeof candidate === "function"
191 ? Effect.succeed(candidate as CreateNextServer)
192 : Effect.fail(
193 fail(`The "next" package resolved from ${root} has no callable default export`)(
194 undefined,
195 ),
196 );
197 }),
198 );
199
200 // ---------------------------------------------------------------------------
201 // The http server (caller-owned port/URL)
202 // ---------------------------------------------------------------------------
203
204 interface HttpServerHandle {
205 readonly server: NodeHttp.Server;
206 readonly port: number;
207 readonly setHandler: (handler: RequestHandler) => void;
208 }
209
210 /**
211 * Listen before Next starts: the actual port must be known when the app is
212 * created (`port` seeds Turbopack's HMR/asset URLs), so the server binds
213 * first (503 until the handler is wired) and the ephemeral port feeds
214 * `next({ port })`. The HMR websocket upgrade is auto-wired by
215 * `getRequestHandler()` through `req.socket.server` on the first request.
216 */
217 const acquireHttpServer = (
218 hostname: string,
219 port: number | undefined,
220 ): Effect.Effect<HttpServerHandle, FrameworkCore.FrameworkError, Scope.Scope> =>
221 Effect.acquireRelease(
222 Effect.callback<
223 HttpServerHandle & { readonly sockets: Set<NodeNet.Socket> },
224 FrameworkCore.FrameworkError
225 >((resume) => {
226 let handler:
227 | ((req: NodeHttp.IncomingMessage, res: NodeHttp.ServerResponse) => Promise<void>)
228 | undefined;
229 const sockets = new Set<NodeNet.Socket>();
230 const server = NodeHttp.createServer((req, res) => {
231 if (handler !== undefined) {
232 void handler(req, res);
233 } else {
234 res.statusCode = 503;
235 res.end("Next.js dev server is starting");
236 }
237 });
238 server.on("connection", (socket) => {
239 sockets.add(socket);
240 socket.on("close", () => sockets.delete(socket));
241 });
242 server.once("error", (cause) =>
243 resume(Effect.fail(fail(`Failed to listen on ${hostname}:${port ?? 0}`)(cause))),
244 );
245 server.listen(port ?? 0, hostname, () => {
246 const address = server.address();
247 if (address === null || typeof address === "string") {
248 resume(Effect.fail(fail("The dev server has no TCP address")(address)));
249 return;
250 }
251 resume(
252 Effect.succeed({
253 server,
254 sockets,
255 port: address.port,
256 setHandler: (h) => {
257 handler = h;
258 },
259 }),
260 );
261 });
262 }),
263 ({ server, sockets }) =>
264 Effect.callback<void>((resume) => {
265 // Destroy live (keep-alive / HMR websocket) sockets so close() never
266 // hangs on an idle connection.
267 for (const socket of sockets) socket.destroy();
268 server.close(() => resume(Effect.void));
269 }),
270 );
271
272 // ---------------------------------------------------------------------------
273 // start
274 // ---------------------------------------------------------------------------
275
276 /**
277 * Start `next dev` with Cloudflare bindings. Scoped: closing the Scope stops
278 * the Next.js app (Turbopack), the http server, and the binding proxy, and
279 * restores the global Cloudflare context.
280 *
281 * Requires `Runtime.Runtime` (from `RuntimeServices.layerRuntime`) for the
282 * binding-proxy workerd instance.
283 */
284 export const start = Effect.fn("Nextjs.DevServer.start")(function* (options: DevServerOptions) {
285 const hostname = options.hostname ?? "localhost";
286 // Resolve symlinks in the project root (macOS /tmp, /var/folders):
287 // Turbopack's watcher reports events under the real path, so a symlinked
288 // root never receives HMR invalidations.
289 const root = yield* Effect.sync(() => {
290 try {
291 return NodeFs.realpathSync.native(options.root);
292 } catch {
293 return options.root;
294 }
295 });
296
297 // 1. Open the platform proxy hosting the worker's bindings.
298 const proxy = yield* PlatformProxy.open({
299 name: options.proxyName ?? "nextjs-dev-platform-proxy",
300 ...(options.compatibilityDate !== undefined
301 ? { compatibilityDate: options.compatibilityDate }
302 : {}),
303 ...(options.compatibilityFlags !== undefined
304 ? { compatibilityFlags: [...options.compatibilityFlags] }
305 : {}),
306 bindings: options.bindings ?? [],
307 ...(options.logging !== undefined ? { logging: options.logging } : {}),
308 ...(options.workerd !== undefined ? { workerd: options.workerd } : {}),
309 }).pipe(Effect.mapError(fail("Failed to start the binding proxy for next dev")));
310
311 // 2. Plant the OpenNext cloudflare-context contract before any app code
312 // (next.config, instrumentation, routes) can call getCloudflareContext.
313 yield* plantCloudflareContext({
314 env: proxy.env,
315 cf: proxy.cf,
316 ctx: proxy.ctx,
317 });
318
319 // 3. Bind our http server first so the real port can seed `next({ port })`.
320 const http = yield* acquireHttpServer(hostname, options.port);
321
322 // 4. The public programmatic dev API: next({ dev: true }) + prepare().
323 const createNext = yield* loadNext(root);
324 const app = yield* Effect.acquireRelease(
325 Effect.tryPromise({
326 try: async () => {
327 const app = createNext({
328 dev: true,
329 dir: root,
330 hostname,
331 port: http.port,
332 });
333 await app.prepare();
334 return app;
335 },
336 catch: fail("Failed to start the Next.js dev server"),
337 }),
338 (app) => Effect.promise(() => app.close().catch(() => undefined)),
339 );
340 http.setHandler(app.getRequestHandler());
341
342 const urlHost = hostname === "0.0.0.0" || hostname === "::" ? "127.0.0.1" : hostname;
343 return {
344 url: new URL(`http://${urlHost}:${http.port}`),
345 } satisfies DevServerInstance;
346 }) as (
347 options: DevServerOptions,
348 ) => Effect.Effect<DevServerInstance, FrameworkCore.FrameworkError, Runtime.Runtime | Scope.Scope>;