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

main
ts 192 lines 7.77 KB
Raw
1 import * as NodePath from "node:path";
2 import { fileURLToPath } from "node:url";
3 import * as Effect from "effect/Effect";
4 import type * as Scope from "effect/Scope";
5 /**
6 * Cloudflare dev transport — HOST half.
7 *
8 * Runs in the alchemy / e2e-harness process: opens `cloudflare-runtime`'s
9 * platform proxy (a local workerd instance hosting the configured binding
10 * hooks behind the internal proxy worker) and produces the
11 * {@link NuxtDevPlatform} the framework half injects into `loadNuxt`
12 * overrides — the dev-only nitro plugin (`./plugin.ts`) plus the
13 * `runtimeConfig` connect info. The proxy's entire client state is
14 * `connectInfo: { url, token }` — two plain strings — which is what lets
15 * the nitro dev SSR worker THREAD reconstruct the platform over HTTP
16 * (`platform-proxy/connect`) with live-shared binding state.
17 */
18 import { DeployTargetError } from "../../core/index.ts";
19 import type { NuxtDevPlatform, NuxtDevPlatformContext } from "../Nuxt.ts";
20 import { RUNTIME_CONFIG_KEY, type DevConnectInfo } from "./shared.ts";
21
22 /**
23 * The runtime-free client subpath of `cloudflare-runtime` the dev plugin is
24 * built on. Resolved HOST-side (this package depends on
25 * `cloudflare-runtime`) to an absolute path the dev worker imports
26 * directly — the worker itself cannot resolve the bare specifier when
27 * `cloudflare-runtime` is only a transitive dependency of the project.
28 */
29 export const CLIENT_MODULE_SPECIFIER =
30 "@alchemy.run/cloudflare-runtime/core/platform-proxy/connect";
31
32 /** Resolve the absolute path of the shipped dev-only nitro plugin. */
33 export const resolveDevPluginPath = (): string => {
34 const packageJson = fileURLToPath(
35 import.meta.resolve("@alchemy.run/frontend-frameworks/package.json"),
36 );
37 return NodePath.join(NodePath.dirname(packageJson), "dist", "nuxt", "dev", "plugin.js");
38 };
39
40 /** Resolve {@link CLIENT_MODULE_SPECIFIER} to an absolute file path. */
41 export const resolveClientModulePath = (): string =>
42 fileURLToPath(import.meta.resolve(CLIENT_MODULE_SPECIFIER));
43
44 /** What the dev platform needs back from an opened proxy. */
45 export interface DevProxyHandle {
46 /** Base URL of the proxy workerd instance. */
47 readonly url: string;
48 /** The instance's auth token. */
49 readonly token: string;
50 /** Tear the proxy down. Safe to call multiple times. */
51 readonly dispose: () => Promise<void>;
52 }
53
54 export interface OpenDevProxyOptions {
55 readonly name: string;
56 readonly compatibilityDate?: string | undefined;
57 readonly compatibilityFlags?: ReadonlyArray<string> | undefined;
58 /** `cloudflare-runtime` binding hooks (opaque through the framework half). */
59 readonly bindings: ReadonlyArray<unknown>;
60 /**
61 * Pre-built `Context<RuntimeServices>` to host the proxy in (opaque
62 * through the framework half). Enables remote()-lowered bindings, which
63 * the proxy's internal local-only layer cannot serve.
64 */
65 readonly services?: unknown;
66 /** `cloudflare-runtime` `WorkerdOptions` for the proxy's workerd process. */
67 readonly workerd?: unknown;
68 /** Static assets served to an `Assets.local` binding. */
69 readonly assets?: { readonly directory: string } | undefined;
70 }
71
72 /** How the platform proxy is opened. A test seam; the default is {@link openPlatformProxy}. */
73 export type OpenDevProxy = (options: OpenDevProxyOptions) => Promise<DevProxyHandle>;
74
75 /**
76 * The default opener: `cloudflare-runtime`'s `getPlatformProxy` (imported
77 * lazily so production builds never load the runtime machinery). The
78 * instance's `connectInfo` carries everything the dev plugin needs.
79 */
80 export const openPlatformProxy: OpenDevProxy = async (options) => {
81 const { getPlatformProxy } = await import("@alchemy.run/cloudflare-runtime/core/platform-proxy");
82 const proxy = await getPlatformProxy({
83 name: options.name,
84 ...(options.compatibilityDate !== undefined
85 ? { compatibilityDate: options.compatibilityDate }
86 : undefined),
87 ...(options.compatibilityFlags !== undefined
88 ? { compatibilityFlags: [...options.compatibilityFlags] }
89 : undefined),
90 bindings: options.bindings as Parameters<typeof getPlatformProxy>[0]["bindings"],
91 ...(options.assets !== undefined ? { assets: { ...options.assets } } : undefined),
92 ...(options.services !== undefined
93 ? {
94 services: options.services as Parameters<typeof getPlatformProxy>[0]["services"],
95 }
96 : undefined),
97 ...(options.workerd !== undefined
98 ? { workerd: options.workerd as Parameters<typeof getPlatformProxy>[0]["workerd"] }
99 : undefined),
100 });
101 return {
102 url: proxy.connectInfo.url,
103 token: proxy.connectInfo.token,
104 dispose: proxy.dispose,
105 };
106 };
107
108 export interface CloudflareDevPlatformOptions {
109 /** Name of the proxy workerd service. @default "nuxt-dev-platform-proxy" */
110 readonly name?: string | undefined;
111 /** Compatibility date for the binding-proxy workerd instance. */
112 readonly compatibilityDate?: string | undefined;
113 /** Compatibility flags for the binding-proxy workerd instance. */
114 readonly compatibilityFlags?: ReadonlyArray<string> | undefined;
115 /** Override how the proxy is opened. A test seam. */
116 readonly openProxy?: OpenDevProxy | undefined;
117 }
118
119 /**
120 * Literal env values for the plugin: strings pass through; everything else
121 * (resource bindings) is delivered through the proxy itself.
122 */
123 const literalEnv = (
124 env: Record<string, unknown> | undefined,
125 ): Record<string, string> | undefined => {
126 const out: Record<string, string> = {};
127 for (const [key, value] of Object.entries(env ?? {})) {
128 if (typeof value === "string") {
129 out[key] = value;
130 }
131 }
132 return Object.keys(out).length > 0 ? out : undefined;
133 };
134
135 /**
136 * The Cloudflare target's dev platform: open the proxy (scoped — closing
137 * the Scope disposes the workerd instance) and hand the framework half the
138 * nitro plugin + `runtimeConfig` connect info to inject.
139 */
140 export const makeCloudflareDevPlatform =
141 (options: CloudflareDevPlatformOptions = {}) =>
142 (
143 context: NuxtDevPlatformContext,
144 ): Effect.Effect<NuxtDevPlatform, DeployTargetError, Scope.Scope> =>
145 Effect.gen(function* () {
146 const open = options.openProxy ?? openPlatformProxy;
147 const proxy = yield* Effect.acquireRelease(
148 Effect.tryPromise({
149 try: () =>
150 open({
151 name: options.name ?? "nuxt-dev-platform-proxy",
152 compatibilityDate: options.compatibilityDate,
153 compatibilityFlags: options.compatibilityFlags,
154 bindings: context.bindings ?? [],
155 services: context.services,
156 workerd: context.workerd,
157 // Nuxt's public directory: what the deployed Worker's `ASSETS`
158 // serves besides the client build.
159 assets: { directory: NodePath.join(context.root, "public") },
160 }),
161 catch: (cause) =>
162 new DeployTargetError({
163 platform: "cloudflare",
164 message: "Failed to open the dev platform proxy",
165 cause,
166 }),
167 }),
168 (handle) => Effect.promise(() => handle.dispose().catch(() => {})),
169 );
170 const clientModule = yield* Effect.try({
171 try: resolveClientModulePath,
172 catch: (cause) =>
173 new DeployTargetError({
174 platform: "cloudflare",
175 message:
176 `Failed to resolve "${CLIENT_MODULE_SPECIFIER}" — the Nuxt dev bridge ` +
177 "requires @alchemy.run/cloudflare-runtime/core (a dependency of this package)",
178 cause,
179 }),
180 });
181 const env = literalEnv(context.env);
182 const connectInfo: DevConnectInfo = {
183 url: proxy.url,
184 token: proxy.token,
185 clientModule,
186 ...(env !== undefined ? { env } : {}),
187 };
188 return {
189 nitroPlugins: [resolveDevPluginPath()],
190 runtimeConfig: { [RUNTIME_CONFIG_KEY]: connectInfo },
191 } satisfies NuxtDevPlatform;
192 });