@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 258 lines 9.31 KB
Raw
1 import type * as Context from "effect/Context";
2 import type * as vite from "vite";
3 import type { BindingHooks, RuntimeServices, RuntimeWorker } from "../core/index.ts";
4 import type { BasePluginOptions } from "../rolldown/options.ts";
5 import {
6 CLIENT_FALLBACK_ENTRY_ID,
7 additionalModulesPlugin,
8 cloudflareExternalsPlugin,
9 nodejsAlsPlugin,
10 nodejsImportWarningPlugin,
11 nodejsUnenvPlugin,
12 optionsPlugin,
13 virtualModulesPlugin,
14 wasmInitPlugin,
15 } from "../rolldown/plugins/index.ts";
16 import { dev } from "./dev-plugin.ts";
17 import { preview } from "./preview-plugin.ts";
18
19 export interface CloudflareVitePluginDevOptions {
20 /**
21 * Where the Worker request-proxy middleware registers relative to the
22 * `configureServer` post middlewares of other plugins.
23 *
24 * - `"post"` (default): append in plugin order. Required by frameworks whose
25 * own dev middlewares must see requests first (e.g. Astro's prerender
26 * handler and dev handler).
27 * - `"pre"`: insert directly after Vite's internal middlewares, ahead of the
28 * post middlewares other plugins registered. Use this when appending the
29 * Cloudflare plugin after a framework's config-file plugins and the
30 * framework registers its own Node request-bridge middleware that cannot
31 * handle the Worker environment (e.g. Waku's RSC bridge, which assumes a
32 * runnable Node environment).
33 *
34 * @default "post"
35 */
36 middlewareOrder?: "pre" | "post";
37 }
38
39 export interface CloudflareVitePluginOptions<
40 B extends BindingHooks = BindingHooks,
41 > extends BasePluginOptions {
42 worker?: Omit<RuntimeWorker<B>, "compatibilityDate" | "compatibilityFlags" | "modules">;
43 context?: Context.Context<RuntimeServices>;
44 dev?: CloudflareVitePluginDevOptions;
45 /**
46 * Named entrypoints the Worker binds to itself. workerd resolves those
47 * bindings at startup, before the entry module has been evaluated and its
48 * exports detected, so the dev Worker must export them from the start.
49 */
50 entrypoints?: ReadonlyArray<string>;
51 }
52
53 /**
54 * Official `@cloudflare/vite-plugin` root name. vinext / Next-on-Workers
55 * treat this exact name, or any `vite-plugin-cloudflare:*` prefix, as
56 * "Cloudflare Workers path".
57 */
58 export const OFFICIAL_CLOUDFLARE_VITE_PLUGIN_NAME = "vite-plugin-cloudflare";
59
60 /**
61 * Alchemy's presence marker. Matches vinext's
62 * `name.startsWith("vite-plugin-cloudflare:")` check without colliding
63 * with the official plugin's exact name.
64 */
65 export const ALCHEMY_CLOUDFLARE_VITE_PLUGIN_NAME = "vite-plugin-cloudflare:alchemy";
66
67 const officialCloudflareVitePluginPrefix = `${OFFICIAL_CLOUDFLARE_VITE_PLUGIN_NAME}:`;
68
69 const isOfficialCloudflareVitePlugin = (plugin: vite.Plugin): boolean =>
70 plugin.name === OFFICIAL_CLOUDFLARE_VITE_PLUGIN_NAME ||
71 (plugin.name.startsWith(officialCloudflareVitePluginPrefix) &&
72 plugin.name !== ALCHEMY_CLOUDFLARE_VITE_PLUGIN_NAME);
73
74 const noopHook = (): undefined => undefined;
75
76 /**
77 * Neutralize official `@cloudflare/vite-plugin` instances already in the
78 * Vite plugin list. Vite flattens `config.plugins` into `userPlugins`
79 * *before* `config()` hooks run, so splicing the array cannot unregister
80 * them — but those entries are the same objects. Replacing their hooks
81 * with no-ops (not `undefined`: `getSortedPluginsByHook("config")` has
82 * already captured them) stops the official stack from running alongside
83 * Alchemy's `distilled-cloudflare:*` plugins.
84 *
85 * Construction-time side effects inside `cloudflare()` still happen if
86 * the app called the official factory. `ALCHEMY_CLOUDFLARE_VITE_INJECTED`
87 * remains the way to skip that factory.
88 */
89 export const disableOfficialCloudflareVitePlugins = async (
90 plugins: ReadonlyArray<unknown> | undefined,
91 ): Promise<number> => {
92 let disabled = 0;
93 const visit = async (entry: unknown): Promise<void> => {
94 // Async plugin factories (e.g. RedwoodSDK's `redwood()`, which adds its
95 // own `cloudflare()`) leave promises here. Vite resolves the same
96 // promises, so their plugins are the same objects.
97 if (isPromiseLike(entry)) {
98 await visit(await entry);
99 return;
100 }
101 if (Array.isArray(entry)) {
102 for (const child of entry) await visit(child);
103 return;
104 }
105 if (entry === null || typeof entry !== "object" || !("name" in entry)) {
106 return;
107 }
108 const plugin = entry as vite.Plugin;
109 if (typeof plugin.name !== "string" || !isOfficialCloudflareVitePlugin(plugin)) {
110 return;
111 }
112 disableOfficialCloudflareVitePlugin(plugin);
113 disabled += 1;
114 };
115 for (const entry of plugins ?? []) await visit(entry);
116 return disabled;
117 };
118
119 const isPromiseLike = (value: unknown): value is PromiseLike<unknown> =>
120 typeof value === "object" &&
121 value !== null &&
122 "then" in value &&
123 typeof (value as { then: unknown }).then === "function";
124
125 const disableOfficialCloudflareVitePlugin = (plugin: vite.Plugin): void => {
126 const record = plugin as unknown as Record<string, unknown>;
127 // Its own `applyToEnvironment` reads the config its no-op `config` hook
128 // never resolved (`Expected resolvedPluginConfig to be defined`).
129 if ("applyToEnvironment" in record) record.applyToEnvironment = () => false;
130 // The root plugin's `config` only resolves the plugin's own config, which
131 // runs the user's `config` customizer: frameworks hand their Worker
132 // contributions through it and fail the build if it never runs (Flue's
133 // `cloudflare({ config: flueWorkerConfig() })`). It stays, in place, so it
134 // runs after the plugins listed before it, as it does under Wrangler. What
135 // it resolves feeds only the hooks disabled here.
136 const resolveConfig =
137 plugin.name === OFFICIAL_CLOUDFLARE_VITE_PLUGIN_NAME ? record.config : undefined;
138 if (typeof resolveConfig === "function") {
139 record.config = async function (this: unknown, ...args: Array<unknown>) {
140 try {
141 await resolveConfig.apply(this, args);
142 } catch {
143 // Its config (e.g. a missing `wrangler.jsonc`) doesn't apply under
144 // Alchemy, which configures the Worker itself.
145 }
146 };
147 }
148 for (const key of Object.keys(record)) {
149 if (
150 key === "name" ||
151 key === "enforce" ||
152 key === "apply" ||
153 key === "applyToEnvironment" ||
154 (key === "config" && typeof resolveConfig === "function")
155 ) {
156 continue;
157 }
158 const value = record[key];
159 if (typeof value === "function") {
160 record[key] = noopHook;
161 continue;
162 }
163 if (
164 value !== null &&
165 typeof value === "object" &&
166 "handler" in value &&
167 typeof (value as { handler: unknown }).handler === "function"
168 ) {
169 (value as { handler: typeof noopHook }).handler = noopHook;
170 }
171 }
172 };
173
174 /**
175 * Named so vinext takes the Workers path, and so a later `config()`
176 * reader cannot mistake us for the official plugin. `order: "pre"`
177 * runs before `vinext:config` scans `config.plugins`.
178 */
179 const alchemyCloudflareVitePlugin = (): vite.Plugin => ({
180 name: ALCHEMY_CLOUDFLARE_VITE_PLUGIN_NAME,
181 enforce: "pre",
182 config: {
183 order: "pre",
184 async handler(config) {
185 await disableOfficialCloudflareVitePlugins(config.plugins);
186 // Vite concatenates this with a user's own `server.fs.deny`, which
187 // would otherwise replace Vite's defaults and expose `.env`.
188 return { server: { fs: { deny: [...DENIED_FILES] } } };
189 },
190 },
191 });
192
193 /**
194 * Files the dev server never serves: `@cloudflare/vite-plugin`'s list
195 * (Vite's defaults, package-manager credentials, key stores, Wrangler's
196 * secrets and state) plus the stack file and Alchemy's state.
197 */
198 const DENIED_FILES = [
199 ".env",
200 ".env.*",
201 ".npmrc",
202 ".yarnrc",
203 ".yarnrc.yml",
204 "*.{crt,pem,key,pfx,p12,p8,jks}",
205 "**/.git/**",
206 ".dev.vars",
207 ".dev.vars.*",
208 "**/.cloudflare/**",
209 "**/.wrangler/**",
210 "**/.alchemy/**",
211 "alchemy.run.*",
212 ];
213
214 /**
215 * The empty entry the default build gives a client with no `index.html`, so
216 * its output still receives `public/` and the Worker's imported assets.
217 */
218 const clientFallbackPlugin = (): vite.Plugin => ({
219 name: "distilled-cloudflare:client-fallback",
220 applyToEnvironment: (environment) => environment.name === "client",
221 resolveId: {
222 filter: { id: /^virtual:cloudflare\/client-fallback-entry$/ },
223 handler: (id) => (id === CLIENT_FALLBACK_ENTRY_ID ? `\0${id}` : undefined),
224 },
225 load: {
226 filter: { id: /^\0virtual:cloudflare\/client-fallback-entry$/ },
227 handler: (id) => (id === `\0${CLIENT_FALLBACK_ENTRY_ID}` ? "" : undefined),
228 },
229 });
230
231 export default function cloudflareVitePlugin(
232 options: CloudflareVitePluginOptions = {},
233 ): vite.PluginOption {
234 return [
235 alchemyCloudflareVitePlugin(),
236 optionsPlugin.vite(options),
237 cloudflareExternalsPlugin.vite(options),
238 nodejsAlsPlugin.vite(options),
239 nodejsImportWarningPlugin.vite(options),
240 nodejsUnenvPlugin.vite(options),
241 virtualModulesPlugin.vite(options),
242 wasmInitPlugin.vite(options),
243 additionalModulesPlugin.vite(options),
244 clientFallbackPlugin(),
245 {
246 name: "distilled-cloudflare:rsc",
247 enforce: "pre",
248 config() {
249 return { rsc: { serverHandler: false } } as vite.UserConfig;
250 },
251 } as vite.Plugin,
252 ...dev(options),
253 preview(options),
254 // Some of the composed plugins are conditional (e.g. the nodejs-compat
255 // family) and resolve to `null`; filter them out so integrations that
256 // post-process the returned plugins don't have to handle sparse entries.
257 ].filter((plugin): plugin is vite.Plugin => plugin !== null);
258 }