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, 06:00 UTC
| 1 | import * as NodePath from "node:path"; |
| 2 | import * as Effect from "effect/Effect"; |
| 3 | import * as FileSystem from "effect/FileSystem"; |
| 4 | import * as Layer from "effect/Layer"; |
| 5 | import * as Path from "effect/Path"; |
| 6 | import * as Schedule from "effect/Schedule"; |
| 7 | import * as Semaphore from "effect/Semaphore"; |
| 8 | import type * as ViteModule from "vite"; |
| 9 | import type { Config as WakuConfig } from "waku/config"; |
| 10 | import type * as WakuVitePlugins from "waku/vite-plugins"; |
| 11 | import * as FrameworkCore from "../core/index.ts"; |
| 12 | import type { |
| 13 | BuildOutput, |
| 14 | DeployTarget, |
| 15 | DeployTargetBuildContext, |
| 16 | DeployTargetError, |
| 17 | DeployTargetInput, |
| 18 | DeployTargetServices, |
| 19 | } from "../core/index.ts"; |
| 20 | |
| 21 | type WakuVitePluginsModule = typeof WakuVitePlugins; |
| 22 | type ResolvedWakuConfig = ReturnType<WakuVitePluginsModule["unstable_resolveConfig"]>; |
| 23 | |
| 24 | /** |
| 25 | * Waku's rsc-environment worker entry, relative to the installed `waku` |
| 26 | * package directory. Its default export is the adapter's `ExportedHandler` |
| 27 | * (the same module waku wires as the rsc env's `index` input). The deep path |
| 28 | * is not in waku's exports map, so it is joined onto the resolved package |
| 29 | * directory. |
| 30 | * |
| 31 | * Deploy targets whose bundler plugin needs an explicit entry (e.g. the |
| 32 | * cloudflare target's `main`) pin it to this path: waku's rsc environment |
| 33 | * declares two rolldown inputs (`index` + `build`) while such plugins assert |
| 34 | * exactly one entry. |
| 35 | */ |
| 36 | export const WAKU_SERVER_ENTRY_PATH = "dist/lib/vite-entries/entry.server.js"; |
| 37 | |
| 38 | /** |
| 39 | * The server module that must become `serverModules[0]` when the app has no |
| 40 | * user worker entry: waku's own `index` input of the rsc environment |
| 41 | * (`dist/server/index.js`), whose default export is the adapter's |
| 42 | * `ExportedHandler`. The entry environment emits multiple entry chunks |
| 43 | * (`index`, `build`, and any wrapped worker entry), so entry selection is |
| 44 | * pinned to this name. When the deploy target carries a user entry |
| 45 | * (`target.entry`), the chunk built from the user's `main` is pinned instead |
| 46 | * (framework-core's `selectEntryByFacade`) and this module remains an |
| 47 | * ordinary chunk the user entry imports. |
| 48 | */ |
| 49 | export const WAKU_SERVER_ENTRY_MODULE = "server/index.js"; |
| 50 | |
| 51 | /** |
| 52 | * The stable importable specifier for waku's server handler — the module a |
| 53 | * USER worker entry wraps (the deploy-target user-entry seam; precedent: |
| 54 | * React Router's `virtual:react-router/server-build`). Resolves to waku's |
| 55 | * rsc server entry ({@link WAKU_SERVER_ENTRY_PATH}), whose default export is |
| 56 | * the adapter's `ExportedHandler`, in dev and build alike: |
| 57 | * |
| 58 | * ```ts |
| 59 | * // src/worker-entry.ts |
| 60 | * import wakuHandler from "virtual:waku/server-entry"; |
| 61 | * export class Counter extends DurableObject {} |
| 62 | * export default { |
| 63 | * fetch: (request, env, ctx) => wakuHandler.fetch(request, env, ctx), |
| 64 | * }; |
| 65 | * ``` |
| 66 | */ |
| 67 | export const WAKU_SERVER_ENTRY_ID = "virtual:waku/server-entry"; |
| 68 | |
| 69 | /** |
| 70 | * The vite plugin resolving {@link WAKU_SERVER_ENTRY_ID} to the project's |
| 71 | * installed waku server entry. Platform-neutral (the id maps to the same |
| 72 | * framework module for every deploy target) and always injected first in |
| 73 | * `vite.plugins`, so the id resolves for the dev module runner, the |
| 74 | * production build, and the SSG preview server alike. |
| 75 | */ |
| 76 | export const makeWakuServerEntryPlugin = (wakuDirectory: string): ViteModule.Plugin => ({ |
| 77 | name: "distilled-waku:server-entry", |
| 78 | resolveId(id) { |
| 79 | if (id === WAKU_SERVER_ENTRY_ID) { |
| 80 | return NodePath.join(wakuDirectory, WAKU_SERVER_ENTRY_PATH); |
| 81 | } |
| 82 | return undefined; |
| 83 | }, |
| 84 | }); |
| 85 | |
| 86 | /** |
| 87 | * The inputs a {@link WakuTarget} hook receives: enough to synthesize the |
| 88 | * target's bundler plugins and adapter selection for one waku pass. |
| 89 | */ |
| 90 | export interface WakuTargetContext { |
| 91 | /** Absolute project root. */ |
| 92 | readonly root: string; |
| 93 | /** Directory of the project's installed `waku` package. */ |
| 94 | readonly wakuDirectory: string; |
| 95 | /** Which waku pass the hook feeds: the production build or the HMR dev server. */ |
| 96 | readonly phase: "build" | "dev"; |
| 97 | } |
| 98 | |
| 99 | /** |
| 100 | * The waku-specific deploy-target contract: the generic |
| 101 | * `framework-core` {@link DeployTarget} seams plus the two |
| 102 | * hooks a target must implement to slot into waku's toolchain: |
| 103 | * |
| 104 | * - `adapter` — the absolute path of the waku server-entry adapter module the |
| 105 | * in-memory config selects via `unstable_adapter`. Always required: leaving |
| 106 | * `unstable_adapter` unset makes waku silently pick `waku/adapters/node`, |
| 107 | * which cannot run on a non-Node target runtime. |
| 108 | * - `vitePlugins` — vite plugins injected *first* inside waku's |
| 109 | * `config.vite.plugins` (waku's `extraPlugins` places user plugins first, |
| 110 | * ahead of waku's own environments plugin) — the position upstream |
| 111 | * documents for `@cloudflare/vite-plugin`, and the only one where a |
| 112 | * target's request-proxy middleware registers before waku's Node request |
| 113 | * bridge. |
| 114 | * |
| 115 | * The Cloudflare implementation ships at `@alchemy.run/frontend-frameworks/waku/cloudflare` |
| 116 | * (the default). A future target (e.g. AWS) is a new module implementing the |
| 117 | * same two hooks — no change to this package's orchestration. |
| 118 | */ |
| 119 | export interface WakuTarget<Config = unknown> extends DeployTarget<Config> { |
| 120 | /** Absolute path of the adapter module waku's config selects via `unstable_adapter`. */ |
| 121 | readonly adapter: (context: WakuTargetContext) => Effect.Effect<string, DeployTargetError>; |
| 122 | /** Vite plugins injected first inside waku's `vite.plugins` (dev + build). */ |
| 123 | readonly vitePlugins: ( |
| 124 | context: WakuTargetContext, |
| 125 | ) => Effect.Effect<ReadonlyArray<ViteModule.PluginOption>, DeployTargetError>; |
| 126 | /** |
| 127 | * Optional *wholesale* build takeover (see `DeployTarget.build`), with |
| 128 | * the waku-specific {@link WakuTargetBuildContext}. |
| 129 | */ |
| 130 | readonly build?: |
| 131 | | (( |
| 132 | context: WakuTargetBuildContext, |
| 133 | ) => Effect.Effect<BuildOutput, DeployTargetError, DeployTargetServices>) |
| 134 | | undefined; |
| 135 | } |
| 136 | |
| 137 | /** |
| 138 | * The context a waku target's wholesale `build` takeover receives: the |
| 139 | * generic build context plus the inline waku options the framework was |
| 140 | * constructed with ({@link WakuFrameworkOptions.waku}) — carried so |
| 141 | * wholesale targets that re-run the framework in a child process (the AWS |
| 142 | * target) can reconstruct it. Only JSON-serializable fields survive that |
| 143 | * process boundary. |
| 144 | */ |
| 145 | export interface WakuTargetBuildContext extends DeployTargetBuildContext { |
| 146 | readonly waku?: WakuConfig | undefined; |
| 147 | } |
| 148 | |
| 149 | /** |
| 150 | * Structural mirror of the e2e harness's target-scoped config carriage |
| 151 | * (`Options.TargetOptions`): a plain selection object whose `cloudflare.worker` |
| 152 | * carries the cloudflare target's configuration. Distinguished from a |
| 153 | * {@link DeployTargetInput} structurally (it is neither a |
| 154 | * string, a function, nor a `DeployTarget` value). |
| 155 | */ |
| 156 | export interface WakuHarnessTargetOptions { |
| 157 | /** Which platform target drives the integration. @default "cloudflare" */ |
| 158 | readonly name?: string | undefined; |
| 159 | readonly cloudflare?: { readonly worker?: unknown } | undefined; |
| 160 | } |
| 161 | |
| 162 | /** |
| 163 | * How the deploy target is passed to the waku integration: |
| 164 | * |
| 165 | * - a target value / factory / module-specifier string (a |
| 166 | * {@link DeployTargetInput}) — resolved with |
| 167 | * `resolveDeployTarget` |
| 168 | * - the e2e harness's target-scoped carriage |
| 169 | * ({@link WakuHarnessTargetOptions}) — selects the default cloudflare |
| 170 | * target module and hands it `cloudflare.worker` as its config |
| 171 | * - omitted — the default cloudflare target module with the deprecated |
| 172 | * `vite` alias as its config |
| 173 | */ |
| 174 | export type WakuTargetOption = DeployTargetInput<WakuTarget, unknown> | WakuHarnessTargetOptions; |
| 175 | |
| 176 | /** |
| 177 | * The module specifier of the default deploy target, loaded from the |
| 178 | * *project's* `node_modules` when no explicit target is passed. |
| 179 | */ |
| 180 | export const DEFAULT_TARGET_SPECIFIER = "@alchemy.run/frontend-frameworks/waku/cloudflare"; |
| 181 | |
| 182 | /** |
| 183 | * Options for the Waku `Framework` integration. |
| 184 | */ |
| 185 | export interface WakuFrameworkOptions { |
| 186 | /** |
| 187 | * The deploy target the build is produced for. Accepts a target value |
| 188 | * (build it by importing the target module, e.g. |
| 189 | * `@alchemy.run/frontend-frameworks/waku/cloudflare`, for full config type safety), a |
| 190 | * `(config) => target` factory, a module specifier string, or the e2e |
| 191 | * harness's target-scoped carriage. Defaults to the cloudflare target |
| 192 | * module ({@link DEFAULT_TARGET_SPECIFIER}). |
| 193 | */ |
| 194 | readonly target?: WakuTargetOption | undefined; |
| 195 | /** |
| 196 | * @deprecated Alias for the deploy target's configuration (the harness's |
| 197 | * pre-target `vite` field, carrying the cloudflare worker configuration). |
| 198 | * Prefer passing a fully-built target via {@link target}, or the harness's |
| 199 | * target-scoped `target.cloudflare.worker`. |
| 200 | */ |
| 201 | readonly vite?: unknown; |
| 202 | /** |
| 203 | * Extra waku config (`srcDir`, `distDir`, `vite`, ...) merged OVER the |
| 204 | * project's own `waku.config.ts`/`waku.config.js`, which is always loaded |
| 205 | * natively first (same semantics as waku's CLI — see |
| 206 | * {@link mergeUserWakuConfig}). `unstable_adapter` is owned by the deploy |
| 207 | * target and must not be set here or in the config file. |
| 208 | */ |
| 209 | readonly waku?: WakuConfig | undefined; |
| 210 | /** Project root. Defaults to the process working directory. */ |
| 211 | readonly root?: string | undefined; |
| 212 | /** |
| 213 | * Default dev-server port, used when `dev` is called without an explicit |
| 214 | * port (e.g. the e2e harness's Playwright dev fixture). Non-strict: if the |
| 215 | * port is taken, vite falls back to the next free one. A port passed to |
| 216 | * `dev` directly (`e2e dev --port N`) is strict and takes precedence. |
| 217 | */ |
| 218 | readonly port?: number | undefined; |
| 219 | } |
| 220 | |
| 221 | /** |
| 222 | * The config files waku's CLI probes for, in probe order (see waku's |
| 223 | * `lib/vite-rsc/loader.ts` `loadConfig`). Only the existence probe uses these |
| 224 | * names — the actual import goes through vite's resolver as `/waku.config`, |
| 225 | * exactly like upstream. |
| 226 | */ |
| 227 | export const WAKU_CONFIG_FILES = ["waku.config.ts", "waku.config.js"] as const; |
| 228 | |
| 229 | /** Strip `undefined`-valued keys so an inline options object with explicit |
| 230 | * `undefined` entries cannot clobber values from the user's config file. */ |
| 231 | const definedConfig = (config: WakuConfig | undefined): WakuConfig | undefined => { |
| 232 | if (config === undefined) { |
| 233 | return undefined; |
| 234 | } |
| 235 | const entries = Object.entries(config).filter(([, value]) => value !== undefined); |
| 236 | return entries.length === 0 ? undefined : (Object.fromEntries(entries) as WakuConfig); |
| 237 | }; |
| 238 | |
| 239 | /** Inputs for {@link mergeUserWakuConfig} (exported for testing). */ |
| 240 | export interface MergeUserWakuConfigInputs { |
| 241 | /** The natively loaded `waku.config.ts`/`waku.config.js` default export. */ |
| 242 | readonly file: WakuConfig | undefined; |
| 243 | /** The integration's inline waku options ({@link WakuFrameworkOptions.waku}). */ |
| 244 | readonly inline: WakuConfig | undefined; |
| 245 | /** vite's `mergeConfig` (from the project's vite installation). */ |
| 246 | readonly mergeViteConfig: ( |
| 247 | defaults: ViteModule.UserConfig, |
| 248 | overrides: ViteModule.UserConfig, |
| 249 | ) => ViteModule.UserConfig; |
| 250 | } |
| 251 | |
| 252 | /** |
| 253 | * Merge the project's natively loaded waku config file with the integration's |
| 254 | * inline waku options: the file is the base, inline options win per key |
| 255 | * (mirroring vite's file-config-vs-inline-config precedence), and the `vite` |
| 256 | * fields are combined with vite's own `mergeConfig` (arrays like `plugins` |
| 257 | * concatenate — file plugins first, inline plugins after). |
| 258 | */ |
| 259 | export const mergeUserWakuConfig = (inputs: MergeUserWakuConfigInputs): WakuConfig | undefined => { |
| 260 | const file = definedConfig(inputs.file); |
| 261 | const inline = definedConfig(inputs.inline); |
| 262 | if (file === undefined || inline === undefined) { |
| 263 | return file ?? inline; |
| 264 | } |
| 265 | const vite = |
| 266 | file.vite !== undefined && inline.vite !== undefined |
| 267 | ? inputs.mergeViteConfig(file.vite, inline.vite) |
| 268 | : (inline.vite ?? file.vite); |
| 269 | return { ...file, ...inline, ...(vite !== undefined ? { vite } : undefined) }; |
| 270 | }; |
| 271 | |
| 272 | const isDeployTargetInput = (value: unknown): value is DeployTargetInput<WakuTarget, unknown> => |
| 273 | typeof value === "string" || typeof value === "function" || FrameworkCore.isDeployTarget(value); |
| 274 | |
| 275 | /** The normalized `(input, config)` pair fed to `resolveDeployTarget`. */ |
| 276 | export interface WakuTargetInputSelection { |
| 277 | readonly input: DeployTargetInput<WakuTarget, unknown>; |
| 278 | readonly config: unknown; |
| 279 | } |
| 280 | |
| 281 | /** |
| 282 | * Normalize {@link WakuFrameworkOptions} into the `(input, config)` pair for |
| 283 | * `resolveDeployTarget`: |
| 284 | * |
| 285 | * - an explicit `DeployTargetInput` is used as-is, with the deprecated `vite` |
| 286 | * alias as the config a factory/specifier receives |
| 287 | * - the harness carriage (or no target at all) selects the default target |
| 288 | * module with `target.cloudflare.worker ?? vite` as its config |
| 289 | */ |
| 290 | export const selectWakuTargetInput = (options?: WakuFrameworkOptions): WakuTargetInputSelection => { |
| 291 | const raw = options?.target; |
| 292 | if (raw !== undefined && isDeployTargetInput(raw)) { |
| 293 | return { input: raw, config: options?.vite }; |
| 294 | } |
| 295 | return { |
| 296 | input: DEFAULT_TARGET_SPECIFIER, |
| 297 | config: raw?.cloudflare?.worker ?? options?.vite, |
| 298 | }; |
| 299 | }; |
| 300 | |
| 301 | /** Inputs for {@link makeWakuConfigInput} (exported for testing). */ |
| 302 | export interface WakuConfigInputs { |
| 303 | /** Absolute path of the adapter module (the target's `adapter` hook). */ |
| 304 | readonly adapterPath: string; |
| 305 | /** |
| 306 | * Deploy-target vite plugins injected first inside `vite.plugins` (the |
| 307 | * target's `vitePlugins` hook). The SSG preview server resolves the same |
| 308 | * config — upstream parity: waku's CLI reuses the loaded config's plugin |
| 309 | * instances for both `createBuilder` and `vite.preview` — so a target |
| 310 | * whose plugins implement `configurePreviewServer` (the cloudflare |
| 311 | * target's does) serves SSG through its own runtime. |
| 312 | */ |
| 313 | readonly plugins?: ReadonlyArray<ViteModule.PluginOption> | undefined; |
| 314 | /** |
| 315 | * The user's waku config — the natively loaded `waku.config.ts`/`.js` |
| 316 | * merged with the integration's inline waku options (see |
| 317 | * {@link mergeUserWakuConfig}). Its `vite` config is preserved; a user |
| 318 | * `unstable_adapter` is rejected by the caller before this point (the |
| 319 | * deploy target owns the adapter), so this function pins it |
| 320 | * unconditionally. |
| 321 | */ |
| 322 | readonly userConfig?: WakuConfig | undefined; |
| 323 | } |
| 324 | |
| 325 | const mergeWorkerEnvironment = ( |
| 326 | user: ViteModule.EnvironmentOptions | undefined, |
| 327 | optimizeDepsInclude: Array<string>, |
| 328 | ): ViteModule.EnvironmentOptions => ({ |
| 329 | ...user, |
| 330 | optimizeDeps: { |
| 331 | ...user?.optimizeDeps, |
| 332 | include: [...optimizeDepsInclude, ...(user?.optimizeDeps?.include ?? [])], |
| 333 | }, |
| 334 | build: { |
| 335 | ...user?.build, |
| 336 | rolldownOptions: { |
| 337 | platform: "neutral", |
| 338 | ...user?.build?.rolldownOptions, |
| 339 | }, |
| 340 | }, |
| 341 | }); |
| 342 | |
| 343 | /** |
| 344 | * Build the waku `Config` fed to waku's `unstable_resolveConfig`: the USER's |
| 345 | * config (their natively loaded `waku.config.*`, plus any inline waku |
| 346 | * options) with the deploy target's required fields merged over it: |
| 347 | * |
| 348 | * - `unstable_adapter` is pinned to the deploy target's adapter module. |
| 349 | * Leaving it unset would silently select `waku/adapters/node` (no |
| 350 | * `CLOUDFLARE` env var), which cannot run on a non-Node target runtime; |
| 351 | * a user-set adapter is rejected upstream of this function. |
| 352 | * - The target's vite plugins are injected INSIDE `vite.plugins` (waku's |
| 353 | * `extraPlugins` places user plugins first, ahead of waku's own |
| 354 | * environments plugin) — the position upstream documents for |
| 355 | * `@cloudflare/vite-plugin`, and the only one where the target's proxy |
| 356 | * middleware registers before waku's Node request bridge. |
| 357 | * - `waku` and `hono` are deduped so the adapter module (which lives outside |
| 358 | * the project) resolves the project's copies. |
| 359 | * - rsc/ssr get the documented `optimizeDeps.include` entries and |
| 360 | * `platform: "neutral"`. |
| 361 | */ |
| 362 | export const makeWakuConfigInput = (inputs: WakuConfigInputs): WakuConfig => { |
| 363 | const user = inputs.userConfig; |
| 364 | const userVite = user?.vite; |
| 365 | const environments = (userVite?.environments ?? {}) as Record< |
| 366 | string, |
| 367 | ViteModule.EnvironmentOptions | undefined |
| 368 | >; |
| 369 | return { |
| 370 | ...user, |
| 371 | unstable_adapter: inputs.adapterPath, |
| 372 | vite: { |
| 373 | ...userVite, |
| 374 | resolve: { |
| 375 | ...userVite?.resolve, |
| 376 | dedupe: [...new Set(["waku", "hono", ...(userVite?.resolve?.dedupe ?? [])])], |
| 377 | }, |
| 378 | environments: { |
| 379 | ...userVite?.environments, |
| 380 | rsc: mergeWorkerEnvironment(environments.rsc, ["hono/tiny"]), |
| 381 | ssr: mergeWorkerEnvironment(environments.ssr, ["waku > rsc-html-stream/server"]), |
| 382 | }, |
| 383 | plugins: [...(inputs.plugins ?? []), ...(userVite?.plugins ?? [])], |
| 384 | }, |
| 385 | }; |
| 386 | }; |
| 387 | |
| 388 | /** |
| 389 | * `NODE_ENV` as it was when this module first loaded. Waku's CLI sets |
| 390 | * `NODE_ENV` before loading anything (waku's environmentsPlugin bakes |
| 391 | * `process.env.NODE_ENV` into `define`), which we replicate — but a |
| 392 | * long-lived process may run both `build` and `dev` (e.g. a playwright worker |
| 393 | * driving the live and dev servers), and a plain `??=` would leak the first |
| 394 | * operation's value into the second. Capturing the initial value preserves an |
| 395 | * explicit user override while keeping the two operations independent. |
| 396 | */ |
| 397 | const INITIAL_NODE_ENV = process.env.NODE_ENV; |
| 398 | |
| 399 | /** |
| 400 | * Serializes cwd swaps across concurrent builds in one process (the same |
| 401 | * discipline as the source provider's dev-server startup lock). |
| 402 | */ |
| 403 | const cwdLock = Semaphore.makeUnsafe(1); |
| 404 | |
| 405 | /** |
| 406 | * Run `effect` with `process.cwd()` set to the project root, restoring the |
| 407 | * previous cwd afterwards. Waku's toolchain assumes cwd == root: the |
| 408 | * html-shell plugin declares a cwd-relative `index.html` client input (a |
| 409 | * root outside the cwd makes `vite:build-html` emit an invalid |
| 410 | * `../index.html` asset name) and reads the html shell with bare relative |
| 411 | * paths. A no-op when the cwd already is the root. |
| 412 | */ |
| 413 | const withRootCwd = <A, E, R>( |
| 414 | root: string, |
| 415 | effect: Effect.Effect<A, E, R>, |
| 416 | ): Effect.Effect<A, E, R> => |
| 417 | Effect.flatMap( |
| 418 | Effect.sync(() => process.cwd() === NodePath.resolve(root)), |
| 419 | (isRoot) => |
| 420 | isRoot |
| 421 | ? effect |
| 422 | : Semaphore.withPermits( |
| 423 | cwdLock, |
| 424 | 1, |
| 425 | )( |
| 426 | Effect.acquireUseRelease( |
| 427 | Effect.sync(() => { |
| 428 | const previous = process.cwd(); |
| 429 | process.chdir(root); |
| 430 | return previous; |
| 431 | }), |
| 432 | () => effect, |
| 433 | (previous) => Effect.sync(() => process.chdir(previous)), |
| 434 | ), |
| 435 | ), |
| 436 | ); |
| 437 | |
| 438 | const PREVIEW_SERVER_GLOBAL = "__WAKU_START_PREVIEW_SERVER__"; |
| 439 | |
| 440 | /** The shape waku's `unstable_startPreviewServer` expects the global to produce. */ |
| 441 | interface WakuPreviewServer { |
| 442 | readonly baseUrl: string; |
| 443 | readonly middlewares: { |
| 444 | readonly use: (fn: (req: unknown, res: unknown, next: (err?: unknown) => void) => void) => void; |
| 445 | }; |
| 446 | readonly close: () => Promise<void>; |
| 447 | } |
| 448 | |
| 449 | /** |
| 450 | * Replicates waku's `cmd-build.ts` `startPreviewServerImpl`: the SSG step of |
| 451 | * `builder.buildApp()` (the adapter's `build`) calls |
| 452 | * `unstable_startPreviewServer`, which throws unless this global is set. The |
| 453 | * preview server resolves the SAME waku config as the build — upstream |
| 454 | * parity: waku's CLI calls `combinedPlugins(config)` for both |
| 455 | * `createBuilder` and `vite.preview`, reusing the loaded config's plugin |
| 456 | * instances across the two servers. A deploy target whose vite plugins |
| 457 | * implement `configurePreviewServer` (the cloudflare target serves the |
| 458 | * freshly built worker through workerd) therefore hosts the SSG rendering on |
| 459 | * its own runtime; waku's adapter registers its Node fallback middleware |
| 460 | * behind it, which only fires for targets without a preview mode. |
| 461 | */ |
| 462 | const setPreviewServerGlobal = ( |
| 463 | vite: typeof ViteModule, |
| 464 | vitePlugins: WakuVitePluginsModule, |
| 465 | root: string, |
| 466 | previewConfig: ResolvedWakuConfig, |
| 467 | port: number, |
| 468 | ): void => { |
| 469 | (globalThis as Record<string, unknown>)[PREVIEW_SERVER_GLOBAL] = |
| 470 | async (): Promise<WakuPreviewServer> => { |
| 471 | const server = await vite.preview({ |
| 472 | configFile: false, |
| 473 | root, |
| 474 | plugins: [vitePlugins.unstable_combinedPlugins(previewConfig)], |
| 475 | // localhost can resolve to another build's listener on the other IP family. |
| 476 | preview: { host: "127.0.0.1", port }, |
| 477 | }); |
| 478 | const baseUrl = server.resolvedUrls?.local[0]; |
| 479 | if (!baseUrl) { |
| 480 | throw new Error("Could not determine the URL of the waku SSG preview server"); |
| 481 | } |
| 482 | return { |
| 483 | baseUrl, |
| 484 | middlewares: { |
| 485 | use: (fn) => server.middlewares.use(fn as never), |
| 486 | }, |
| 487 | close: () => server.close(), |
| 488 | }; |
| 489 | }; |
| 490 | }; |
| 491 | |
| 492 | const clearPreviewServerGlobal = (): void => { |
| 493 | delete (globalThis as Record<string, unknown>)[PREVIEW_SERVER_GLOBAL]; |
| 494 | }; |
| 495 | |
| 496 | interface ProjectModules { |
| 497 | readonly vite: typeof ViteModule; |
| 498 | readonly vitePlugins: WakuVitePluginsModule; |
| 499 | readonly wakuDirectory: string; |
| 500 | } |
| 501 | |
| 502 | /** |
| 503 | * The Waku implementation of framework-core's `Framework` service. |
| 504 | * |
| 505 | * - `build` replicates waku's `runBuild` (`vite.createBuilder` + |
| 506 | * `combinedPlugins` + the SSG preview-server global) and collects the |
| 507 | * `BuildOutput` with a post-`buildApp` disk re-read (waku writes |
| 508 | * `__waku_build_metadata.js` and prunes static-only chunks after the |
| 509 | * bundler finishes). The result is returned in-memory only, then passed |
| 510 | * through the deploy target's finishing pass (if any). |
| 511 | * - `dev` replicates waku's `runDev` with the deploy target's vite plugins |
| 512 | * injected inside waku's `config.vite.plugins`, so the rsc environment runs |
| 513 | * on the target's dev runtime (workerd for cloudflare) with in-memory |
| 514 | * bindings. |
| 515 | * |
| 516 | * Deploy-target resolution happens per operation: platform-specific halves |
| 517 | * (adapter module, bundler plugins) come exclusively from the resolved |
| 518 | * {@link WakuTarget} — this module contains no platform imports. |
| 519 | * |
| 520 | * Returns the service implementation as an Effect (the alchemy-side |
| 521 | * `FrameworkModule` contract); use {@link layer} for the `Layer` form the |
| 522 | * e2e harness consumes. |
| 523 | */ |
| 524 | export const make = ( |
| 525 | options?: WakuFrameworkOptions, |
| 526 | ): Effect.Effect<FrameworkCore.Framework["Service"], never, FileSystem.FileSystem | Path.Path> => |
| 527 | Effect.gen(function* () { |
| 528 | const fs = yield* FileSystem.FileSystem; |
| 529 | const path = yield* Path.Path; |
| 530 | |
| 531 | const fail = (message: string) => (cause: unknown) => |
| 532 | new FrameworkCore.FrameworkError({ framework: "waku", message, cause }); |
| 533 | |
| 534 | const resolveRoot = (override: string | undefined) => |
| 535 | Effect.sync(() => override ?? options?.root ?? process.cwd()); |
| 536 | |
| 537 | const resolveTarget: (root: string) => Effect.Effect<WakuTarget, FrameworkCore.FrameworkError> = |
| 538 | Effect.fn(function* (root: string) { |
| 539 | const { input, config } = selectWakuTargetInput(options); |
| 540 | return yield* FrameworkCore.resolveDeployTarget<WakuTarget, unknown>( |
| 541 | root, |
| 542 | input, |
| 543 | config, |
| 544 | ).pipe(Effect.mapError(fail("Failed to resolve the deploy target"))); |
| 545 | }); |
| 546 | |
| 547 | /** Run the target's waku hooks, validating they exist (a dynamically |
| 548 | * loaded module may satisfy `DeployTarget` without the waku hooks). */ |
| 549 | const useTargetHooks: ( |
| 550 | target: WakuTarget, |
| 551 | context: WakuTargetContext, |
| 552 | ) => Effect.Effect< |
| 553 | { |
| 554 | adapterPath: string; |
| 555 | plugins: ReadonlyArray<ViteModule.PluginOption>; |
| 556 | }, |
| 557 | FrameworkCore.FrameworkError |
| 558 | > = Effect.fn(function* (target: WakuTarget, context: WakuTargetContext) { |
| 559 | if (typeof target.adapter !== "function" || typeof target.vitePlugins !== "function") { |
| 560 | return yield* fail( |
| 561 | `Deploy target "${target.platform}" does not implement the waku target hooks ` + |
| 562 | "(adapter, vitePlugins) required to drive waku " + |
| 563 | context.phase, |
| 564 | )(undefined); |
| 565 | } |
| 566 | const [adapterPath, plugins] = yield* Effect.all( |
| 567 | [target.adapter(context), target.vitePlugins(context)], |
| 568 | { concurrency: "unbounded" }, |
| 569 | ).pipe(Effect.mapError(fail(`The deploy target failed preparing the waku ${context.phase}`))); |
| 570 | return { adapterPath, plugins }; |
| 571 | }); |
| 572 | |
| 573 | const loadProject: ( |
| 574 | root: string, |
| 575 | ) => Effect.Effect<ProjectModules, FrameworkCore.FrameworkError> = Effect.fn(function* ( |
| 576 | root: string, |
| 577 | ) { |
| 578 | const [vite, vitePlugins, wakuDirectory] = yield* Effect.all( |
| 579 | [ |
| 580 | FrameworkCore.loadProjectModule<typeof ViteModule>(root, "vite").pipe( |
| 581 | Effect.mapError(fail("Failed to load the project's vite")), |
| 582 | ), |
| 583 | FrameworkCore.loadProjectModule<WakuVitePluginsModule>(root, "waku/vite-plugins").pipe( |
| 584 | Effect.mapError(fail("Failed to load the project's waku/vite-plugins")), |
| 585 | ), |
| 586 | FrameworkCore.resolveProjectPackageDirectory(root, "waku").pipe( |
| 587 | Effect.mapError(fail("Failed to resolve the project's waku package directory")), |
| 588 | ), |
| 589 | ], |
| 590 | { concurrency: "unbounded" }, |
| 591 | ); |
| 592 | return { vite, vitePlugins, wakuDirectory }; |
| 593 | }); |
| 594 | |
| 595 | /** |
| 596 | * Load the project's `waku.config.ts`/`waku.config.js` exactly the way |
| 597 | * waku's own CLI does. Waku's loader (`lib/vite-rsc/loader.ts` |
| 598 | * `loadConfig`) is NOT exported, so its semantics are replicated: an |
| 599 | * existence probe for {@link WAKU_CONFIG_FILES} at the project root |
| 600 | * (waku probes the cwd — its CLI always runs from the project), |
| 601 | * followed by `vite.runnerImport("/waku.config")` with the project's |
| 602 | * own vite. `runnerImport`'s inline config pins `root` so the |
| 603 | * root-relative id resolves identically when root !== cwd. `NODE_ENV` |
| 604 | * is set before this runs, matching waku's CLI ordering (vite#20299). |
| 605 | * |
| 606 | * Deliberate divergences from the CLI (host-process concerns): |
| 607 | * - no `loadDotEnv()` — the CLI mutates `process.env` from |
| 608 | * `.env.local`/`.env`; here the host (alchemy/e2e) owns the process |
| 609 | * environment and worker env comes from bindings. |
| 610 | * - no dev-server restart on config-file change — the dev handle is a |
| 611 | * plain URL; edits to `waku.config.*` need a dev restart. |
| 612 | */ |
| 613 | const loadUserConfigFile: ( |
| 614 | project: ProjectModules, |
| 615 | root: string, |
| 616 | ) => Effect.Effect<WakuConfig | undefined, FrameworkCore.FrameworkError> = Effect.fn(function* ( |
| 617 | project: ProjectModules, |
| 618 | root: string, |
| 619 | ) { |
| 620 | const exists = yield* Effect.all( |
| 621 | WAKU_CONFIG_FILES.map((file) => fs.exists(path.join(root, file))), |
| 622 | { concurrency: "unbounded" }, |
| 623 | ).pipe(Effect.mapError(fail("Failed to probe for the project's waku.config file"))); |
| 624 | if (!exists.some(Boolean)) { |
| 625 | return undefined; |
| 626 | } |
| 627 | return yield* Effect.tryPromise({ |
| 628 | try: async () => { |
| 629 | const imported = await project.vite.runnerImport<{ |
| 630 | default: WakuConfig; |
| 631 | }>("/waku.config", { root }); |
| 632 | return imported.module.default; |
| 633 | }, |
| 634 | catch: fail("Failed to load the project's waku.config file"), |
| 635 | }); |
| 636 | }); |
| 637 | |
| 638 | const makeConfig: ( |
| 639 | project: ProjectModules, |
| 640 | root: string, |
| 641 | inputs: { |
| 642 | adapterPath: string; |
| 643 | plugins: ReadonlyArray<ViteModule.PluginOption>; |
| 644 | }, |
| 645 | ) => Effect.Effect<ResolvedWakuConfig, FrameworkCore.FrameworkError> = Effect.fn(function* ( |
| 646 | project: ProjectModules, |
| 647 | root: string, |
| 648 | inputs: { |
| 649 | adapterPath: string; |
| 650 | plugins: ReadonlyArray<ViteModule.PluginOption>; |
| 651 | }, |
| 652 | ) { |
| 653 | const fileConfig = yield* loadUserConfigFile(project, root); |
| 654 | const userConfig = mergeUserWakuConfig({ |
| 655 | file: fileConfig, |
| 656 | inline: options?.waku, |
| 657 | mergeViteConfig: project.vite.mergeConfig, |
| 658 | }); |
| 659 | if (userConfig?.unstable_adapter !== undefined) { |
| 660 | return yield* fail( |
| 661 | `The waku config sets unstable_adapter (${JSON.stringify(userConfig.unstable_adapter)}), ` + |
| 662 | "but the deploy target owns the server adapter " + |
| 663 | `(it injects ${JSON.stringify(inputs.adapterPath)}). ` + |
| 664 | "Remove unstable_adapter from waku.config.ts/waku.config.js (and from the " + |
| 665 | "integration's waku options); to change the deploy platform, pass a different " + |
| 666 | "deploy target to the integration instead.", |
| 667 | )(undefined); |
| 668 | } |
| 669 | return project.vitePlugins.unstable_resolveConfig( |
| 670 | makeWakuConfigInput({ |
| 671 | adapterPath: inputs.adapterPath, |
| 672 | // The server-entry resolver goes first so |
| 673 | // `virtual:waku/server-entry` (the wrappable-handler seam a user |
| 674 | // worker entry imports) resolves in dev, build, and the SSG |
| 675 | // preview server alike. |
| 676 | plugins: [makeWakuServerEntryPlugin(project.wakuDirectory), ...inputs.plugins], |
| 677 | userConfig, |
| 678 | }), |
| 679 | ); |
| 680 | }); |
| 681 | |
| 682 | const inProcess = FrameworkCore.Framework.of({ |
| 683 | build: Effect.fn(function* (buildOptions) { |
| 684 | const root = yield* resolveRoot(buildOptions?.root); |
| 685 | const target = yield* resolveTarget(root); |
| 686 | if (target.build !== undefined) { |
| 687 | // Wholesale build takeover: the target owns the entire pipeline. |
| 688 | // The inline waku options ride along so a child-process build can |
| 689 | // reconstruct the framework with the same options. |
| 690 | return yield* target |
| 691 | .build({ |
| 692 | root, |
| 693 | framework: "waku", |
| 694 | env: buildOptions?.env, |
| 695 | waku: options?.waku, |
| 696 | }) |
| 697 | .pipe( |
| 698 | Effect.provideService(FileSystem.FileSystem, fs), |
| 699 | Effect.provideService(Path.Path, path), |
| 700 | Effect.mapError(fail("The deploy target's build failed")), |
| 701 | ); |
| 702 | } |
| 703 | const project = yield* loadProject(root); |
| 704 | const hooks = yield* useTargetHooks(target, { |
| 705 | root, |
| 706 | wakuDirectory: project.wakuDirectory, |
| 707 | phase: "build", |
| 708 | }); |
| 709 | // waku's CLI sets this before loading anything; waku's |
| 710 | // environmentsPlugin bakes `process.env.NODE_ENV` into `define`. |
| 711 | yield* Effect.sync(() => { |
| 712 | process.env.NODE_ENV = INITIAL_NODE_ENV ?? "production"; |
| 713 | }); |
| 714 | const wakuConfig = yield* makeConfig(project, root, hooks); |
| 715 | const previewPort = yield* FrameworkCore.resolveViteDevPort(project.vite.version); |
| 716 | // Entry selection (the user-entry seam): when the deploy target |
| 717 | // carries a user worker entry, the chunk built from it must become |
| 718 | // `serverModules[0]` — waku's own `server/index.js` remains an |
| 719 | // ordinary chunk the user entry imports (via |
| 720 | // `virtual:waku/server-entry`). Without one, waku's own `index` |
| 721 | // entry chunk is pinned by name as before. |
| 722 | const userEntry = FrameworkCore.resolveDeployTargetEntry(target, { |
| 723 | root, |
| 724 | }); |
| 725 | const collector = yield* FrameworkCore.makeBuildOutputCollector({ |
| 726 | entryEnvironment: "rsc", |
| 727 | selectEntry: |
| 728 | userEntry !== undefined |
| 729 | ? FrameworkCore.selectEntryByFacade(userEntry) |
| 730 | : (chunk) => chunk.name === WAKU_SERVER_ENTRY_MODULE, |
| 731 | }).pipe(Effect.provideService(FileSystem.FileSystem, fs)); |
| 732 | // The whole build runs under the project root cwd: waku's |
| 733 | // html-shell plugin declares a cwd-relative `index.html` client |
| 734 | // input and reads the shell with bare relative paths (see |
| 735 | // withRootCwd). |
| 736 | yield* withRootCwd( |
| 737 | root, |
| 738 | Effect.tryPromise({ |
| 739 | try: async () => { |
| 740 | const builder = await project.vite.createBuilder( |
| 741 | { |
| 742 | configFile: false, |
| 743 | root, |
| 744 | // Warn-level: rolldown-vite's native progress reporter |
| 745 | // ("transforming...") writes straight to the fd, which |
| 746 | // corrupts hosting-process reporters (e.g. alchemy-test) |
| 747 | // that can only intercept JS-level writers. |
| 748 | logLevel: "warn", |
| 749 | plugins: [ |
| 750 | project.vitePlugins.unstable_combinedPlugins(wakuConfig), |
| 751 | collector.plugin, |
| 752 | ], |
| 753 | }, |
| 754 | null, |
| 755 | ); |
| 756 | setPreviewServerGlobal( |
| 757 | project.vite, |
| 758 | project.vitePlugins, |
| 759 | root, |
| 760 | wakuConfig, |
| 761 | previewPort, |
| 762 | ); |
| 763 | try { |
| 764 | await builder.buildApp(); |
| 765 | } finally { |
| 766 | clearPreviewServerGlobal(); |
| 767 | } |
| 768 | }, |
| 769 | catch: fail("Failed to build"), |
| 770 | }), |
| 771 | ); |
| 772 | // Disk re-read: waku writes `__waku_build_metadata.js` and prunes |
| 773 | // static-only server chunks during `buildApp` hooks, after the |
| 774 | // in-memory `writeBundle` capture. |
| 775 | const output = yield* collector |
| 776 | .collect({ fromDisk: true }) |
| 777 | .pipe(Effect.mapError((error) => fail(error.message)(error.cause))); |
| 778 | return yield* FrameworkCore.applyDeployTargetFinish(target, output, { |
| 779 | root, |
| 780 | framework: "waku", |
| 781 | }).pipe( |
| 782 | Effect.provideService(FileSystem.FileSystem, fs), |
| 783 | Effect.provideService(Path.Path, path), |
| 784 | Effect.mapError(fail("The deploy target's finishing pass failed")), |
| 785 | ); |
| 786 | }), |
| 787 | dev: Effect.fn(function* (devOptions) { |
| 788 | const root = yield* resolveRoot(devOptions?.root); |
| 789 | const target = yield* resolveTarget(root); |
| 790 | const project = yield* loadProject(root); |
| 791 | const hooks = yield* useTargetHooks(target, { |
| 792 | root, |
| 793 | wakuDirectory: project.wakuDirectory, |
| 794 | phase: "dev", |
| 795 | }); |
| 796 | yield* Effect.sync(() => { |
| 797 | process.env.NODE_ENV = INITIAL_NODE_ENV ?? "development"; |
| 798 | }); |
| 799 | const wakuConfig = yield* makeConfig(project, root, hooks); |
| 800 | // `port: 0` (true OS-assigned) on Vite >= 8.2.1, probed ephemeral |
| 801 | // port on older Vite — see `resolveViteDevPort`. strictPort stays |
| 802 | // off for allocated ports so a probe race just moves to the next |
| 803 | // ephemeral port. |
| 804 | const explicitPort = devOptions?.port || options?.port; |
| 805 | const port = yield* FrameworkCore.resolveViteDevPort(project.vite.version, explicitPort); |
| 806 | const host = devOptions?.host; |
| 807 | // The dev server *starts* under the project root cwd (waku |
| 808 | // resolves its html shell and relative inputs from the cwd at |
| 809 | // startup); the cwd is restored once the server is listening. |
| 810 | const server = yield* Effect.acquireRelease( |
| 811 | withRootCwd( |
| 812 | root, |
| 813 | Effect.tryPromise({ |
| 814 | try: async () => { |
| 815 | const server = await project.vite.createServer({ |
| 816 | configFile: false, |
| 817 | root, |
| 818 | plugins: [project.vitePlugins.unstable_combinedPlugins(wakuConfig)], |
| 819 | server: { |
| 820 | port, |
| 821 | strictPort: !!explicitPort, |
| 822 | ...(host !== undefined ? { host } : undefined), |
| 823 | }, |
| 824 | }); |
| 825 | return await server.listen(); |
| 826 | }, |
| 827 | catch: fail("Failed to start the waku dev server"), |
| 828 | }), |
| 829 | ), |
| 830 | (server) => Effect.promise(async () => await server.close()), |
| 831 | ); |
| 832 | const resolved = server.resolvedUrls?.local[0]; |
| 833 | if (resolved === undefined) { |
| 834 | return yield* fail("Could not determine the URL of the waku dev server")(undefined); |
| 835 | } |
| 836 | // Vite's `resolvedUrls.local[0]` is `http://host:port/` — strip |
| 837 | // the trailing slash so callers can concatenate paths (`${url}/`) |
| 838 | // without producing `//`, which waku's router does not match. |
| 839 | const url = resolved.replace(/\/+$/, ""); |
| 840 | // Bounded readiness probe: any HTTP response counts (waku's |
| 841 | // first RSC compile is lazy; we only need the listener to answer). |
| 842 | yield* Effect.tryPromise({ |
| 843 | try: async () => { |
| 844 | const response = await fetch(`${url}/`, { redirect: "manual" }); |
| 845 | await response.arrayBuffer().catch(() => {}); |
| 846 | }, |
| 847 | catch: fail("The waku dev server did not become reachable"), |
| 848 | }).pipe(Effect.retry({ schedule: Schedule.spaced("250 millis"), times: 40 })); |
| 849 | return { url }; |
| 850 | }), |
| 851 | }); |
| 852 | |
| 853 | // Waku's toolchain assumes `cwd === root` at dev startup (the html shell |
| 854 | // and relative inputs resolve from the cwd), so its startup window |
| 855 | // chdirs — which must not happen in a process hosting other sites' dev |
| 856 | // servers (the alchemy dev sidecar). Run the dev server in a dedicated |
| 857 | // child whose cwd IS the root instead (see core/DevChild.ts). Inside |
| 858 | // that child — or when the options cannot cross the process boundary |
| 859 | // (e.g. a deploy-target VALUE from the e2e harness) — the in-process |
| 860 | // path runs directly. |
| 861 | const dev: FrameworkCore.Framework["Service"]["dev"] = (devOptions) => { |
| 862 | if (FrameworkCore.isInsideDevChild() || !FrameworkCore.isJsonSerializable(options)) { |
| 863 | return inProcess.dev(devOptions); |
| 864 | } |
| 865 | const root = devOptions?.root ?? options?.root ?? process.cwd(); |
| 866 | const port = devOptions?.port ?? options?.port; |
| 867 | return FrameworkCore.runDevChild({ |
| 868 | framework: "waku", |
| 869 | module: "@alchemy.run/frontend-frameworks/waku", |
| 870 | callerUrl: import.meta.url, |
| 871 | rootDir: root, |
| 872 | makeOptions: { ...options, root }, |
| 873 | devOptions: { |
| 874 | root, |
| 875 | ...(port !== undefined ? { port } : {}), |
| 876 | ...(devOptions?.host !== undefined ? { host: devOptions.host } : {}), |
| 877 | }, |
| 878 | }); |
| 879 | }; |
| 880 | |
| 881 | return FrameworkCore.Framework.of({ build: inProcess.build, dev }); |
| 882 | }); |
| 883 | |
| 884 | /** |
| 885 | * The `Layer` form of {@link make} — the shape the e2e harness's framework |
| 886 | * factory contract expects (`(options) => Layer<Framework>`). |
| 887 | */ |
| 888 | export const layer = ( |
| 889 | options?: WakuFrameworkOptions, |
| 890 | ): Layer.Layer<FrameworkCore.Framework, never, FileSystem.FileSystem | Path.Path> => |
| 891 | Layer.effect(FrameworkCore.Framework, make(options)); |