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

main
ts 311 lines 11.1 KB
Raw
1 import type { MemoOptions } from "alchemy/Command/Memo";
2 import type { InputProps } from "alchemy/Input";
3 import { effectClass } from "alchemy/Util/effect";
4 import * as Effect from "effect/Effect";
5 import type { Providers } from "../Providers.ts";
6 import type { AssetsConfig } from "../Workers/Assets.ts";
7 import {
8 Worker,
9 type NormalizedBindings,
10 type WorkerAssetsConfig,
11 type WorkerBindingProps,
12 type WorkerProps,
13 } from "../Workers/Worker.ts";
14
15 /**
16 * The specifier of the Waku source-provider module. The package must be
17 * installed in the user's project — `loadSource` fails with a
18 * `SourceProviderError` naming it otherwise.
19 */
20 const WAKU_SOURCE_PROVIDER = "@alchemy.run/frontend-frameworks/waku/source";
21
22 export interface WakuProps<Bindings extends WorkerBindingProps = {}> extends Omit<
23 WorkerProps<Bindings>,
24 "vite" | "main" | "assets" | "source" | "script" | "bundle" | "rules"
25 > {
26 /**
27 * Overrides the module that becomes the deployed Worker entry. Relative
28 * paths resolve from {@link rootDir}.
29 *
30 * By default Waku's own RSC server entry is deployed. Point `main` at a
31 * custom module when the deployed Worker must export more than Waku's
32 * fetch handler — e.g. Durable Object classes or additional handlers.
33 * The custom entry wraps Waku's handler by importing it from
34 * `virtual:waku/server-entry` and re-exports the extras:
35 *
36 * ```typescript
37 * // src/worker-entry.ts
38 * import wakuHandler from "virtual:waku/server-entry";
39 * export class Counter extends DurableObject {}
40 * export default {
41 * fetch: (request, env, ctx) => wakuHandler.fetch(request, env, ctx),
42 * };
43 * ```
44 */
45 main?: string;
46 /**
47 * Root directory of the Waku project. Defaults to the process working
48 * directory.
49 */
50 rootDir?: string;
51 /**
52 * Controls which files feed the content hash that decides whether a
53 * rebuild is needed. By default every non-gitignored file under
54 * {@link rootDir} is hashed, plus the nearest package-manager lockfile.
55 * Provide `include`/`exclude` globs to narrow the scope.
56 */
57 memo?: MemoOptions;
58 /**
59 * Optional configuration for static asset routing behavior.
60 * Supports `runWorkerFirst`, `htmlHandling`, `notFoundHandling`, etc.
61 *
62 * Waku links SSG pages without trailing slashes (`/about`), so
63 * `htmlHandling` defaults to `"drop-trailing-slash"` — the prerendered
64 * `about/index.html` serves directly at `/about` instead of 307-redirecting
65 * to `/about/`. Set `htmlHandling` explicitly to override.
66 *
67 * @default { htmlHandling: "drop-trailing-slash" }
68 */
69 assets?: AssetsConfig;
70 /**
71 * Waku config overrides merged over the project's `waku.config.*`
72 * (per-key; deploy-time values win). For values that vary by stage or
73 * come from other resources — static config belongs in `waku.config.*`.
74 */
75 waku?: {
76 /**
77 * Waku `srcDir` (relative to {@link rootDir}).
78 * @default "src"
79 */
80 srcDir?: string;
81 /**
82 * Waku `distDir` (relative to {@link rootDir}). If `waku.config.*`
83 * customizes `distDir`, mirror it here (or add it to `memo.exclude`)
84 * so the build output stays excluded from the rebuild-deciding input
85 * hash.
86 * @default "dist"
87 */
88 distDir?: string;
89 /**
90 * Waku `basePath`.
91 * @default "/"
92 */
93 basePath?: string;
94 };
95 }
96
97 // These options are inspected while constructing the Worker. Resolve them in
98 // the outer props Effect; pass-through properties can remain deferred Inputs.
99 type WakuInput<Bindings extends WorkerBindingProps> = InputProps<
100 WakuProps<Bindings>,
101 "compatibility" | "assets" | "waku"
102 >;
103
104 /**
105 * A Cloudflare Worker deployed from a [Waku](https://waku.gg) project.
106 *
107 * `Waku` builds the project programmatically — no `waku.config.ts` edits,
108 * no Wrangler configuration, and no build command required. A project's
109 * `waku.config.*` loads natively (same as waku's CLI) and is where all
110 * Waku configuration (`srcDir`, `distDir`, `basePath`, ...) lives; the
111 * `waku` prop overrides it per key at deploy time.
112 * `unstable_adapter` is owned by Alchemy and must not be set. Note that a
113 * standalone `vite.config.ts` is NOT loaded (same as waku's CLI) — Vite
114 * config belongs in `waku.config.*`'s `vite` field. The RSC server
115 * bundle deploys as the Worker script and the client output (including
116 * SSG-prerendered pages) deploys as static assets.
117 *
118 * Requires the `@alchemy.run/frontend-frameworks` package to be installed in
119 * your project; the integration is loaded from its `/waku` export. Input files
120 * are content-hashed
121 * (respecting `.gitignore` by default) so unchanged projects skip the
122 * build and deploy entirely.
123 *
124 * Waku's server runtime uses `AsyncLocalStorage`, so the `nodejs_als`
125 * compatibility flag is enabled automatically when your compatibility
126 * flags include neither `nodejs_als` nor `nodejs_compat`. SSG pages are
127 * served at their extensionless URLs (`/about`) via the default
128 * `drop-trailing-slash` asset handling.
129 *
130 *
131 * ### Deploying a Waku Site
132 * A single call builds the project and deploys the RSC server bundle plus
133 * the client assets — no configuration required.
134 *
135 * **Example:** Waku site
136 * ```typescript
137 * const site = yield* Cloudflare.Website.Waku("Site");
138 * ```
139 *
140 * **Example:** Waku project in a subdirectory
141 * ```typescript
142 * const site = yield* Cloudflare.Website.Waku("Site", {
143 * rootDir: "apps/web",
144 * });
145 * ```
146 *
147 * ### Waku Config Overrides
148 * Waku configuration lives in your `waku.config.*`. The `waku` prop
149 * overrides it per key at deploy time — for values that vary by stage
150 * or come from other resources.
151 *
152 * **Example:** Stage-dependent base path
153 * ```typescript
154 * const site = yield* Cloudflare.Website.Waku("Site", {
155 * waku: {
156 * basePath: "/docs/",
157 * },
158 * });
159 * ```
160 *
161 * ### Bindings
162 * Pass resources through `env` like any other Worker. Server components
163 * and API routes read them from the `cloudflare:workers` env at request
164 * time. Prefer a guarded dynamic import in page modules — Waku's SSG step
165 * renders static pages in Node, where a top-level
166 * `import { env } from "cloudflare:workers"` cannot resolve.
167 *
168 * **Example:** Binding an R2 bucket
169 * ```typescript
170 * const bucket = yield* Cloudflare.R2.Bucket("Uploads");
171 *
172 * const site = yield* Cloudflare.Website.Waku("Site", {
173 * env: {
174 * UPLOADS: bucket,
175 * },
176 * });
177 * ```
178 *
179 * ### Custom Worker Entry
180 * By default the deployed Worker entry is Waku's own RSC server entry.
181 * When the Worker must export more than Waku's fetch handler — Durable
182 * Object classes, additional handlers — point `main` at your own module
183 * that wraps Waku's handler (imported from `virtual:waku/server-entry`)
184 * and re-exports the extras.
185 *
186 * **Example:** Custom entry hosting a Durable Object
187 * ```typescript
188 * // src/worker-entry.ts
189 * // import wakuHandler from "virtual:waku/server-entry";
190 * // export class Counter extends DurableObject { ... }
191 * // export default { fetch: (req, env, ctx) => wakuHandler.fetch(req, env, ctx) };
192 *
193 * const site = yield* Cloudflare.Website.Waku("Site", {
194 * main: "src/worker-entry.ts",
195 * env: {
196 * COUNTER: Cloudflare.DurableObject("Counter", {
197 * className: "Counter",
198 * }),
199 * },
200 * });
201 * ```
202 *
203 * ### Custom Rebuild Scope
204 * By default, every non-gitignored file is hashed to decide whether a
205 * rebuild is needed. Use `memo` to narrow the scope when your project has
206 * large directories that don't affect the build output.
207 *
208 * **Example:** Narrowing the memo scope
209 * ```typescript
210 * const site = yield* Cloudflare.Website.Waku("Site", {
211 * memo: {
212 * include: ["src/**", "public/**", "package.json"],
213 * },
214 * });
215 * ```
216 *
217 * ### Class Form
218 * Calling `Waku` with no arguments returns a constructor you can `extend`
219 * to declare the Worker as a named class. The class is both an `Effect`
220 * you can `yield*` to deploy and a type you can reference elsewhere —
221 * useful when other resources need to bind to this Worker.
222 *
223 * **Example:** Declaring a Waku Worker class
224 * ```typescript
225 * class Site extends Cloudflare.Website.Waku<Site>()("Site") {}
226 *
227 * const site = yield* Site;
228 * ```
229 *
230 * @resource
231 * @product Website
232 * @category Workers & Compute
233 */
234 export const Waku: {
235 <Self>(): {
236 <const Bindings extends WorkerBindingProps = {}, Req = never>(
237 id: string,
238 propsEff?: WakuInput<Bindings> | Effect.Effect<WakuInput<Bindings>, never, Req>,
239 ): Effect.Effect<Self, never, Req | Providers> & {
240 new (): Worker<{
241 [binding in keyof NormalizedBindings<Bindings, WorkerAssetsConfig>]: NormalizedBindings<
242 Bindings,
243 WorkerAssetsConfig
244 >[binding];
245 }>;
246 };
247 };
248 <const Bindings extends WorkerBindingProps = {}, Req = never>(
249 id: string,
250 propsEff?: WakuInput<Bindings> | Effect.Effect<WakuInput<Bindings>, never, Req>,
251 ): Effect.Effect<
252 Worker<{
253 [binding in keyof NormalizedBindings<Bindings, WorkerAssetsConfig>]: NormalizedBindings<
254 Bindings,
255 WorkerAssetsConfig
256 >[binding];
257 }>,
258 never,
259 Req | Providers
260 >;
261 } = (<const Bindings extends WorkerBindingProps = {}, Req = never>(
262 id?: string,
263 propsEff?: WakuInput<Bindings> | Effect.Effect<WakuInput<Bindings>, never, Req>,
264 ) =>
265 id === undefined
266 ? <const Bindings extends WorkerBindingProps = {}, Req = never>(
267 id: string,
268 propsEff?: WakuInput<Bindings> | Effect.Effect<WakuInput<Bindings>, never, Req>,
269 ) => effectClass(Waku(id, propsEff))
270 : Worker(
271 id,
272 Effect.map(Effect.isEffect(propsEff) ? propsEff : Effect.succeed(propsEff), (props) => ({
273 ...props,
274 compatibility: {
275 ...props?.compatibility,
276 // Waku's server runtime needs AsyncLocalStorage — default to
277 // nodejs_als when the user hasn't enabled it (or the broader
278 // nodejs_compat) themselves.
279 flags:
280 props?.compatibility?.flags?.includes("nodejs_als") ||
281 props?.compatibility?.flags?.includes("nodejs_compat")
282 ? props.compatibility!.flags
283 : [...(props?.compatibility?.flags ?? []), "nodejs_als"],
284 },
285 // Waku links SSG pages without trailing slashes; serve
286 // `about/index.html` at `/about` directly instead of redirecting.
287 assets: {
288 htmlHandling: "drop-trailing-slash" as const,
289 ...props?.assets,
290 },
291 main: undefined!,
292 source: {
293 provider: WAKU_SOURCE_PROVIDER,
294 devMode: "server",
295 rootDir: props?.rootDir,
296 options: {
297 rootDir: props?.rootDir,
298 // Custom worker entry (wraps waku's handler via
299 // `virtual:waku/server-entry`); resolved against `rootDir`
300 // by the source provider.
301 main: props?.main,
302 // Deploy-time waku config overrides, merged over the
303 // project's `waku.config.*` by the source provider.
304 srcDir: props?.waku?.srcDir,
305 distDir: props?.waku?.distDir,
306 basePath: props?.waku?.basePath,
307 memo: props?.memo,
308 },
309 },
310 })),
311 )) as any;