The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import fs from "node:fs"; |
| 2 | import path from "node:path"; |
| 3 | import { nonPrefixedNodeModules } from "@cloudflare/unenv-preset"; |
| 4 | import type * as vite from "vite"; |
| 5 | import { createPlugin } from "../factory.ts"; |
| 6 | import { parseViteEnvironments, type BasePluginOptions } from "../options.ts"; |
| 7 | import { hasNodejsCompat } from "../utils.ts"; |
| 8 | import { workerEntryId } from "./virtual-modules.ts"; |
| 9 | |
| 10 | const DEFAULT_RESOLVE_CONDITION_NAMES = ["workerd", "worker", "module", "browser"]; |
| 11 | const DEFAULT_RESOLVE_MAIN_FIELDS = ["browser", "module", "jsnext:main", "jsnext", "main"]; |
| 12 | const DEFAULT_RESOLVE_EXTENSIONS = [ |
| 13 | ".mjs", |
| 14 | ".js", |
| 15 | ".mts", |
| 16 | ".ts", |
| 17 | ".jsx", |
| 18 | ".tsx", |
| 19 | ".json", |
| 20 | ".cjs", |
| 21 | ".cts", |
| 22 | ".ctx", |
| 23 | ]; |
| 24 | |
| 25 | // workerd runs `using` declarations natively, so Rolldown builds keep them. |
| 26 | // esbuild (Vite 6 and 7) has no `es2026`, so it gets `supported.using`. |
| 27 | const TARGET = "es2026"; |
| 28 | const ESBUILD_TARGET = "es2024"; |
| 29 | const CSS_TARGET = "es2024"; |
| 30 | const ESBUILD_SUPPORTED = { using: true }; |
| 31 | |
| 32 | export interface OptionsApi { |
| 33 | input: () => Record<string, string>; |
| 34 | } |
| 35 | |
| 36 | export const optionsPlugin = createPlugin<"options", OptionsApi>("options", (pluginOptions) => { |
| 37 | let input: Record<string, string> = {}; |
| 38 | // A framework's own `index` input in the Worker environment (Waku's server |
| 39 | // entry) merges over the Worker entry's, so once every config is merged the |
| 40 | // Worker entry takes `index` back and the framework's builds under its own |
| 41 | // name. |
| 42 | const restoreWorkerEntryInput = (config: vite.ResolvedConfig) => { |
| 43 | if (typeof pluginOptions.main !== "string" || input.index === undefined) return; |
| 44 | const workerEntry = workerEntryId(input.index); |
| 45 | const build = config.environments[parseViteEnvironments(pluginOptions)[0]]?.build; |
| 46 | for (const options of new Set([build?.rolldownOptions, build?.rollupOptions])) { |
| 47 | const current = options?.input; |
| 48 | if (!options || !current || typeof current !== "object" || Array.isArray(current)) continue; |
| 49 | const displaced = current.index; |
| 50 | if (displaced === undefined || displaced === workerEntry) continue; |
| 51 | options.input = { |
| 52 | ...current, |
| 53 | [path.parse(displaced).name || "framework"]: displaced, |
| 54 | index: workerEntry, |
| 55 | }; |
| 56 | } |
| 57 | }; |
| 58 | return { |
| 59 | shared: { |
| 60 | api: { |
| 61 | input: () => input, |
| 62 | }, |
| 63 | }, |
| 64 | rolldown: { |
| 65 | options(options) { |
| 66 | input = normalizeInput(pluginOptions.main ?? options.input ?? {}); |
| 67 | options.input = wrapInput(input); |
| 68 | options.preserveEntrySignatures ??= "strict"; |
| 69 | options.platform ??= "neutral"; |
| 70 | options.resolve ??= {}; |
| 71 | options.resolve.conditionNames ??= [...DEFAULT_RESOLVE_CONDITION_NAMES, "production"]; |
| 72 | options.resolve.mainFields ??= DEFAULT_RESOLVE_MAIN_FIELDS; |
| 73 | options.resolve.extensions ??= DEFAULT_RESOLVE_EXTENSIONS; |
| 74 | options.transform ??= {}; |
| 75 | options.transform.target ??= TARGET; |
| 76 | options.transform.define ??= {}; |
| 77 | Object.assign(options.transform.define, getDefine(pluginOptions, "production", "wrangler")); |
| 78 | return options; |
| 79 | }, |
| 80 | }, |
| 81 | vite: { |
| 82 | // On Vite 6 and 7, `vite:esbuild-transpile` lowers every chunk with the |
| 83 | // top-level `esbuild` options, which would also leave `using` in the |
| 84 | // client bundle. Each environment reads its own `esbuild` first, so |
| 85 | // the Worker environments get theirs. |
| 86 | configResolved(config) { |
| 87 | restoreWorkerEntryInput(config); |
| 88 | if (this.meta.rolldownVersion || config.esbuild === false) return; |
| 89 | const esbuild = { |
| 90 | ...config.esbuild, |
| 91 | supported: { ...config.esbuild.supported, ...ESBUILD_SUPPORTED }, |
| 92 | }; |
| 93 | for (const name of parseViteEnvironments(pluginOptions)) { |
| 94 | const environment = config.environments[name]; |
| 95 | if (environment) Object.assign(environment, { esbuild }); |
| 96 | } |
| 97 | }, |
| 98 | async config(userConfig) { |
| 99 | const vite = await import("vite"); |
| 100 | const isRolldown = "rolldownVersion" in this.meta; |
| 101 | const environmentNames = parseViteEnvironments(pluginOptions); |
| 102 | const root = path.resolve(userConfig.root ?? "."); |
| 103 | input = resolveInputPaths( |
| 104 | // `main` builds as `index`, `@cloudflare/vite-plugin`'s entry chunk |
| 105 | // name, which frameworks read back (RedwoodSDK links |
| 106 | // `<outDir>/index.js`). |
| 107 | typeof pluginOptions.main === "string" |
| 108 | ? { index: pluginOptions.main } |
| 109 | : normalizeInput( |
| 110 | pluginOptions.main ?? |
| 111 | defaultEnvironmentEntries(environmentNames[0], userConfig) ?? |
| 112 | {}, |
| 113 | ), |
| 114 | root, |
| 115 | ); |
| 116 | const rollupOptions: vite.Rollup.RollupOptions = { |
| 117 | input: wrapInput(input), |
| 118 | preserveEntrySignatures: "strict", |
| 119 | }; |
| 120 | const define = getDefine( |
| 121 | pluginOptions, |
| 122 | process.env.NODE_ENV || userConfig.mode || "production", |
| 123 | "vite", |
| 124 | ); |
| 125 | const makeEnvironment = ({ |
| 126 | name, |
| 127 | isEntry, |
| 128 | }: { |
| 129 | name: string; |
| 130 | isEntry: boolean; |
| 131 | }): vite.EnvironmentOptions => { |
| 132 | const entries = isEntry |
| 133 | ? (pluginOptions.main ?? defaultEnvironmentEntries(name, userConfig)) |
| 134 | : (defaultEnvironmentEntries(name, userConfig) ?? pluginOptions.main); |
| 135 | return { |
| 136 | // Bake `process.env.NODE_ENV` (and friends) into the worker build. |
| 137 | // workerd has no value for it at runtime, so without this libraries |
| 138 | // like React fall back to their development builds. Setting `define` |
| 139 | // at the environment level applies it even though `keepProcessEnv` |
| 140 | // stays `true` (so other `process.env` access is preserved at |
| 141 | // runtime for `nodejs_compat`). |
| 142 | define, |
| 143 | resolve: { |
| 144 | noExternal: true, |
| 145 | conditions: [...DEFAULT_RESOLVE_CONDITION_NAMES, "development|production"], |
| 146 | }, |
| 147 | optimizeDeps: { |
| 148 | noDiscovery: |
| 149 | userConfig.environments?.[name]?.optimizeDeps?.noDiscovery ?? |
| 150 | userConfig.optimizeDeps?.noDiscovery ?? |
| 151 | false, |
| 152 | ignoreOutdatedRequests: true, |
| 153 | entries: asArray(entries)?.map(vite.normalizePath), |
| 154 | // Node.js built-ins are never pre-bundled, with or without |
| 155 | // `nodejs_compat` (`cloudflare:*` modules: `cloudflare-externals`). |
| 156 | exclude: [ |
| 157 | ...nonPrefixedNodeModules, |
| 158 | ...nonPrefixedNodeModules.map((module) => `node:${module}`), |
| 159 | "node:sea", |
| 160 | "node:sqlite", |
| 161 | "node:test", |
| 162 | "node:test/reporters", |
| 163 | ], |
| 164 | ...(isRolldown |
| 165 | ? { |
| 166 | rolldownOptions: { |
| 167 | platform: "neutral", |
| 168 | resolve: { |
| 169 | conditionNames: [...DEFAULT_RESOLVE_CONDITION_NAMES, "development"], |
| 170 | mainFields: DEFAULT_RESOLVE_MAIN_FIELDS, |
| 171 | extensions: DEFAULT_RESOLVE_EXTENSIONS, |
| 172 | }, |
| 173 | transform: { |
| 174 | target: TARGET, |
| 175 | define, |
| 176 | }, |
| 177 | }, |
| 178 | } |
| 179 | : { |
| 180 | esbuildOptions: { |
| 181 | platform: "neutral", |
| 182 | conditions: [...DEFAULT_RESOLVE_CONDITION_NAMES, "development"], |
| 183 | resolveExtensions: DEFAULT_RESOLVE_EXTENSIONS, |
| 184 | mainFields: DEFAULT_RESOLVE_MAIN_FIELDS, |
| 185 | target: ESBUILD_TARGET, |
| 186 | supported: ESBUILD_SUPPORTED, |
| 187 | define, |
| 188 | }, |
| 189 | }), |
| 190 | }, |
| 191 | keepProcessEnv: true, |
| 192 | // The entry environment owns the Worker's build input and server |
| 193 | // output directory; children (e.g. `ssr`) keep their own build config |
| 194 | // from the framework plugin (`@vitejs/plugin-rsc`). |
| 195 | ...(isEntry |
| 196 | ? { |
| 197 | build: { |
| 198 | ssr: true, |
| 199 | target: isRolldown ? TARGET : ESBUILD_TARGET, |
| 200 | cssTarget: CSS_TARGET, |
| 201 | emitAssets: true, |
| 202 | manifest: true, |
| 203 | // Source maps upload with the Worker, for readable stack traces. |
| 204 | sourcemap: |
| 205 | userConfig.environments?.[name]?.build?.sourcemap ?? |
| 206 | userConfig.build?.sourcemap ?? |
| 207 | true, |
| 208 | copyPublicDir: false, |
| 209 | outDir: getOutputDirectory(userConfig, name), |
| 210 | ...(isRolldown |
| 211 | ? { |
| 212 | rolldownOptions: { |
| 213 | ...rollupOptions, |
| 214 | platform: "neutral", |
| 215 | resolve: { |
| 216 | mainFields: DEFAULT_RESOLVE_MAIN_FIELDS, |
| 217 | extensions: DEFAULT_RESOLVE_EXTENSIONS, |
| 218 | }, |
| 219 | }, |
| 220 | } |
| 221 | : { rollupOptions }), |
| 222 | }, |
| 223 | } |
| 224 | : {}), |
| 225 | }; |
| 226 | }; |
| 227 | // No Worker entry: an assets-only site. Declared `viteEnvironments` |
| 228 | // mean a framework plugin supplies the entry later (e.g. |
| 229 | // `@vitejs/plugin-rsc` in its own `config` hook). |
| 230 | const assetsOnly = |
| 231 | Object.keys(input).length === 0 && pluginOptions.viteEnvironments === undefined; |
| 232 | // `custom` as `@cloudflare/vite-plugin` sets it: Vite's own SPA/MPA |
| 233 | // HTML middleware never answers in dev, so every request it doesn't |
| 234 | // serve reaches the Worker's router, which applies the asset rules |
| 235 | // (`htmlHandling`, `notFoundHandling`, `runWorkerFirst`). |
| 236 | const appType = userConfig.appType ?? "custom"; |
| 237 | return { |
| 238 | appType, |
| 239 | builder: |
| 240 | // Vite merges plugin `config` results over the user config, so an |
| 241 | // unconditional default here would clobber a framework's own |
| 242 | // `buildApp` orchestrator (e.g. Astro's prerender -> ssr -> client |
| 243 | // pipeline). Only default it when the resolved user config doesn't |
| 244 | // already define one. |
| 245 | userConfig.builder?.buildApp !== undefined |
| 246 | ? undefined |
| 247 | : { |
| 248 | buildApp: (builder) => |
| 249 | // An assets-only site builds only its client. |
| 250 | buildApp(builder, assetsOnly ? [] : environmentNames, pluginOptions), |
| 251 | }, |
| 252 | // An assets-only site has no Worker environments, as with |
| 253 | // `@cloudflare/vite-plugin`: the client builds to Vite's own outDir. |
| 254 | environments: assetsOnly |
| 255 | ? undefined |
| 256 | : { |
| 257 | client: { |
| 258 | build: { |
| 259 | outDir: getOutputDirectory(userConfig, "client"), |
| 260 | }, |
| 261 | }, |
| 262 | ...Object.fromEntries( |
| 263 | environmentNames.map((name, index) => [ |
| 264 | name, |
| 265 | makeEnvironment({ name, isEntry: index === 0 }), |
| 266 | ]), |
| 267 | ), |
| 268 | }, |
| 269 | }; |
| 270 | }, |
| 271 | }, |
| 272 | }; |
| 273 | }); |
| 274 | |
| 275 | export const CLIENT_FALLBACK_ENTRY_ID = "virtual:cloudflare/client-fallback-entry"; |
| 276 | const CLIENT_FALLBACK_ENTRY_NAME = "__cloudflare_fallback_entry__"; |
| 277 | |
| 278 | /** |
| 279 | * `@cloudflare/vite-plugin`'s default build: the Worker environments, any |
| 280 | * other environment the app declares, then the client. A client with no |
| 281 | * entry still builds when it has `public/` files or the Worker imports |
| 282 | * assets, so its output holds every static asset; the Worker's imported |
| 283 | * assets then move into it. |
| 284 | */ |
| 285 | const buildApp = async ( |
| 286 | builder: vite.ViteBuilder, |
| 287 | environmentNames: ReadonlyArray<string>, |
| 288 | options: BasePluginOptions, |
| 289 | ) => { |
| 290 | const client = builder.environments.client; |
| 291 | const workerEnvironments = environmentNames.flatMap((name) => { |
| 292 | const environment = builder.environments[name]; |
| 293 | return environment ? [environment] : []; |
| 294 | }); |
| 295 | const others = Object.values(builder.environments).filter( |
| 296 | (environment) => |
| 297 | workerEnvironments.length > 0 && |
| 298 | environment !== client && |
| 299 | !environmentNames.includes(environment.name) && |
| 300 | // Framework-owned environments we were told to leave alone may have |
| 301 | // no build input; never drive them from the default orchestrator. |
| 302 | !options.skipEnvironments?.includes(environment.name), |
| 303 | ); |
| 304 | for (const environment of [...workerEnvironments, ...others]) { |
| 305 | if (!environment.isBuilt) await builder.build(environment); |
| 306 | } |
| 307 | if (!client || client.isBuilt) return; |
| 308 | const entry = workerEnvironments[0]; |
| 309 | const entryDirectory = entry |
| 310 | ? path.resolve(builder.config.root, entry.config.build.outDir) |
| 311 | : undefined; |
| 312 | const importedAssets = entryDirectory ? readImportedAssets(entryDirectory) : new Set<string>(); |
| 313 | if (!isEntrylessClientEnvironment(client)) { |
| 314 | await builder.build(client); |
| 315 | } else if (importedAssets.size > 0 || hasPublicAssets(builder.config)) { |
| 316 | client.config.build.rollupOptions = { |
| 317 | input: CLIENT_FALLBACK_ENTRY_ID, |
| 318 | logLevel: "silent", |
| 319 | output: { entryFileNames: CLIENT_FALLBACK_ENTRY_NAME }, |
| 320 | }; |
| 321 | await builder.build(client); |
| 322 | fs.rmSync( |
| 323 | path.resolve(builder.config.root, client.config.build.outDir, CLIENT_FALLBACK_ENTRY_NAME), |
| 324 | { force: true }, |
| 325 | ); |
| 326 | } else { |
| 327 | return; |
| 328 | } |
| 329 | if (!entryDirectory) return; |
| 330 | const clientDirectory = path.resolve(builder.config.root, client.config.build.outDir); |
| 331 | for (const asset of importedAssets) { |
| 332 | const source = path.join(entryDirectory, asset); |
| 333 | const destination = path.join(clientDirectory, asset); |
| 334 | if (!fs.existsSync(source)) continue; |
| 335 | if (fs.existsSync(destination)) { |
| 336 | fs.unlinkSync(source); |
| 337 | } else { |
| 338 | fs.mkdirSync(path.dirname(destination), { recursive: true }); |
| 339 | fs.renameSync(source, destination); |
| 340 | } |
| 341 | } |
| 342 | }; |
| 343 | |
| 344 | /** The assets the Worker's chunks import, from its build manifest. */ |
| 345 | const readImportedAssets = (directory: string): Set<string> => { |
| 346 | try { |
| 347 | const manifest = JSON.parse( |
| 348 | fs.readFileSync(path.join(directory, ".vite", "manifest.json"), "utf8"), |
| 349 | ) as Record<string, { assets?: Array<string> }>; |
| 350 | return new Set(Object.values(manifest).flatMap((chunk) => chunk.assets ?? [])); |
| 351 | } catch { |
| 352 | return new Set(); |
| 353 | } |
| 354 | }; |
| 355 | |
| 356 | const hasPublicAssets = ({ publicDir }: { publicDir: string | false }): boolean => { |
| 357 | if (!publicDir) return false; |
| 358 | try { |
| 359 | return fs.readdirSync(publicDir).length > 0; |
| 360 | } catch { |
| 361 | return false; |
| 362 | } |
| 363 | }; |
| 364 | |
| 365 | /** |
| 366 | * Vite always creates a default `client` environment, even for a pure Worker |
| 367 | * app that has no browser bundle. Building it makes Vite fall back to its |
| 368 | * default `index.html` entry, so the build fails on a file the app never |
| 369 | * referenced. Treat the environment as absent unless the app gave it an entry |
| 370 | * or serves an HTML shell. |
| 371 | */ |
| 372 | const isEntrylessClientEnvironment = (environment: { |
| 373 | name: string; |
| 374 | config: { root: string; build: { rollupOptions?: { input?: unknown } } }; |
| 375 | }): boolean => { |
| 376 | if (environment.name !== "client") return false; |
| 377 | const build = environment.config.build as { |
| 378 | rollupOptions?: { input?: unknown }; |
| 379 | rolldownOptions?: { input?: unknown }; |
| 380 | }; |
| 381 | if (build.rollupOptions?.input || build.rolldownOptions?.input) return false; |
| 382 | return !fs.existsSync(path.join(environment.config.root, "index.html")); |
| 383 | }; |
| 384 | |
| 385 | const defaultEnvironmentEntries = ( |
| 386 | environmentName: string, |
| 387 | userConfig: vite.UserConfig, |
| 388 | ): vite.Rolldown.InputOption | undefined => { |
| 389 | const environment = userConfig.environments?.[environmentName]; |
| 390 | return environment?.build?.rolldownOptions?.input ?? environment?.build?.rollupOptions?.input; |
| 391 | }; |
| 392 | |
| 393 | const asArray = ( |
| 394 | input: string | Array<string> | Record<string, string> | undefined, |
| 395 | ): Array<string> | undefined => { |
| 396 | if (!input) return; |
| 397 | if (typeof input === "string") return [input]; |
| 398 | if (Array.isArray(input) && input.length > 0) return input; |
| 399 | return Object.values(input); |
| 400 | }; |
| 401 | |
| 402 | const normalizeInput = ( |
| 403 | input: string | Array<string> | Record<string, string>, |
| 404 | ): Record<string, string> => { |
| 405 | if (typeof input === "string") { |
| 406 | return { [path.parse(input).name || "index"]: input }; |
| 407 | } else if (Array.isArray(input)) { |
| 408 | return Object.fromEntries(input.map((p) => [path.parse(p).name, p])); |
| 409 | } else { |
| 410 | return input; |
| 411 | } |
| 412 | }; |
| 413 | |
| 414 | /** |
| 415 | * Resolve path-like input entries against the Vite root. Worker entries are |
| 416 | * round-tripped through a synthetic `\0distilled:user-entry:` id and resolved |
| 417 | * with no importer, so a relative input (`./workers/app.ts`) would otherwise |
| 418 | * resolve against `process.cwd()` — the wrong base whenever the build runs |
| 419 | * outside the project root (e.g. from a monorepo infra package). A bare |
| 420 | * specifier that names a real file under the root (`workers/app.ts`) is |
| 421 | * treated as a path input, matching Vite's own input semantics; anything else |
| 422 | * (virtual modules, package specifiers) passes through and resolves via |
| 423 | * plugins. |
| 424 | */ |
| 425 | const resolveInputPaths = (input: Record<string, string>, root: string): Record<string, string> => |
| 426 | Object.fromEntries(Object.entries(input).map(([key, id]) => [key, resolveInputPath(id, root)])); |
| 427 | |
| 428 | const resolveInputPath = (id: string, root: string): string => { |
| 429 | if (path.isAbsolute(id)) return id; |
| 430 | if (id.startsWith("./") || id.startsWith("../")) return path.resolve(root, id); |
| 431 | const resolved = path.resolve(root, id); |
| 432 | return fs.existsSync(resolved) ? resolved : id; |
| 433 | }; |
| 434 | |
| 435 | const wrapInput = (input: Record<string, string>) => |
| 436 | Object.fromEntries(Object.entries(input).map(([key, id]) => [key, workerEntryId(id)])); |
| 437 | |
| 438 | // `bundler` names the reference whose defines to match: Wrangler's own |
| 439 | // bundler (plain Workers) or `@cloudflare/vite-plugin`, which leaves |
| 440 | // `navigator.userAgent` to workerd and `import.meta.hot` to Vite. |
| 441 | const getDefine = ( |
| 442 | options: BasePluginOptions, |
| 443 | nodeEnv: string, |
| 444 | bundler: "wrangler" | "vite", |
| 445 | ): Record<string, string> => ({ |
| 446 | "process.env.NODE_ENV": JSON.stringify(nodeEnv), |
| 447 | "global.process.env.NODE_ENV": JSON.stringify(nodeEnv), |
| 448 | "globalThis.process.env.NODE_ENV": JSON.stringify(nodeEnv), |
| 449 | ...(hasNodejsCompat(options.compatibilityFlags, options.compatibilityDate) |
| 450 | ? {} |
| 451 | : { |
| 452 | "process.env": "{}", |
| 453 | "global.process.env": "{}", |
| 454 | "globalThis.process.env": "{}", |
| 455 | }), |
| 456 | ...(bundler === "wrangler" && |
| 457 | options.compatibilityDate && |
| 458 | options.compatibilityDate >= "2022-03-21" |
| 459 | ? { |
| 460 | "navigator.userAgent": '"Cloudflare-Workers"', |
| 461 | } |
| 462 | : {}), |
| 463 | ...(bundler === "wrangler" && nodeEnv === "production" |
| 464 | ? { |
| 465 | "import.meta.hot": "false", |
| 466 | } |
| 467 | : {}), |
| 468 | }); |
| 469 | |
| 470 | const getOutputDirectory = (userConfig: vite.UserConfig, environmentName: string) => { |
| 471 | const rootOutputDirectory = userConfig.build?.outDir ?? "dist"; |
| 472 | |
| 473 | return ( |
| 474 | userConfig.environments?.[environmentName]?.build?.outDir ?? |
| 475 | path.join(rootOutputDirectory, environmentName) |
| 476 | ); |
| 477 | }; |