@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, 06:00 UTC

main
ts 436 lines 15.2 KB
Raw
1 import { AlchemyContext } from "alchemy/AlchemyContext";
2 import * as Command from "alchemy/Command";
3 import type { Input, InputProps } from "alchemy/Input";
4 import * as Namespace from "alchemy/Namespace";
5 import * as Output from "alchemy/Output";
6 import { renamedFrom } from "alchemy/Rename";
7 import { effectClass, isYieldableEffectLike, type YieldableEffectLike } from "alchemy/Util/effect";
8 import { asEffect } from "alchemy/Util/types";
9 import * as Effect from "effect/Effect";
10 import { cast } from "effect/Function";
11 import * as Redacted from "effect/Redacted";
12 import type { Providers } from "../Providers.ts";
13 import type { AssetsConfig } from "../Workers/Assets.ts";
14 import {
15 Worker,
16 type NormalizedBindings,
17 type WorkerAssetsConfig,
18 type WorkerBindingProps,
19 type WorkerProps,
20 } from "../Workers/Worker.ts";
21 import { isContainerDecl } from "../Workers/WorkerAsyncBindings.ts";
22
23 export interface StaticSiteProps<Bindings extends WorkerBindingProps = {}>
24 extends
25 Omit<WorkerProps<Bindings, WorkerAssetsConfig>, "assets" | "dev">,
26 Omit<Command.BuildProps, "env"> {
27 /**
28 * Optional configuration for static asset routing behavior.
29 * Supports `runWorkerFirst`, `htmlHandling`, `notFoundHandling`, etc.
30 */
31
32 assets?: AssetsConfig;
33 /**
34 * Local dev configuration, in one of two forms.
35 *
36 * With `command`, `alchemy dev` skips the build and spawns `command` as a
37 * long-lived child process tied to the stack's scope. Alchemy does not
38 * proxy or interpret the process — the dev server's own URL (e.g.
39 * `http://localhost:5173`) is what you open in the browser.
40 *
41 * Without `command`, `alchemy dev` runs the build and a local Worker
42 * serves the output; `port`, `strictPort` and `host` configure that
43 * Worker.
44 *
45 * @example
46 * ```typescript
47 * Cloudflare.Website.StaticSite("App", {
48 * command: "npm run build",
49 * outdir: "dist",
50 * main: "./src/worker.ts",
51 * dev: { command: "npm run dev" },
52 * });
53 * ```
54 *
55 * @example
56 * ```typescript
57 * Cloudflare.Website.StaticSite("App", {
58 * command: "npm run build",
59 * outdir: "dist",
60 * dev: { port: 4321, strictPort: true },
61 * });
62 * ```
63 */
64 dev?: StaticSiteDevCommand | StaticSiteDevWorker;
65 }
66
67 /**
68 * `StaticSite` dev form that serves the site from an external dev server.
69 */
70 export interface StaticSiteDevCommand {
71 /**
72 * Shell command to run as the local dev server (e.g. `npm run dev`).
73 */
74 command: string;
75 /**
76 * Working directory for {@link command}. Defaults to
77 * {@link Command.BuildProps.cwd} (the build command's `cwd`), or
78 * `process.cwd()` if neither is set.
79 */
80 cwd?: string;
81 /**
82 * Environment variables for {@link command}, merged on top of
83 * `process.env`. When set, these replace the top-level `env` for the
84 * dev process; otherwise the top-level `env` is passed through.
85 * `Redacted` values stay out of logs and state, so put secrets here
86 * rather than interpolating them into {@link command}.
87 */
88 env?: Record<string, string | Redacted.Redacted<string>>;
89 /**
90 * Override for the `url` output if alchemy fails to detect it from the stdout of the dev command
91 */
92 url?: string;
93 port?: never;
94 strictPort?: never;
95 host?: never;
96 }
97
98 /**
99 * `StaticSite` dev form that builds the site and serves it from a local
100 * Worker.
101 */
102 export interface StaticSiteDevWorker {
103 /**
104 * Port the local Worker listens on. If the port is unavailable, the next
105 * free port is used unless {@link strictPort} is `true`.
106 * @default 1337
107 */
108 port?: number;
109 /**
110 * When `true`, fail instead of falling back to another port if
111 * {@link port} is already in use.
112 * @default false
113 */
114 strictPort?: boolean;
115 /**
116 * Host the local Worker binds to.
117 * @default "localhost"
118 */
119 host?: string;
120 command?: never;
121 cwd?: never;
122 env?: never;
123 url?: never;
124 }
125
126 type StaticSiteWorker<Bindings extends WorkerBindingProps> = Worker<{
127 [binding in keyof NormalizedBindings<Bindings, WorkerAssetsConfig>]: NormalizedBindings<
128 Bindings,
129 WorkerAssetsConfig
130 >[binding];
131 }>;
132
133 /**
134 * A Cloudflare Worker that serves static assets built by a shell command.
135 *
136 * `StaticSite` runs a build command (e.g. `npm run build`), content-hashes
137 * the output directory, and deploys the result as a Cloudflare Worker with
138 * static assets. Use this when your site has its own build step that
139 * produces a directory of files — Hugo, Zola, Eleventy, or any custom
140 * pipeline.
141 *
142 * For Vite-based projects, prefer `Cloudflare.Website.Vite` which handles
143 * building automatically.
144 *
145 *
146 * ### Basic Usage
147 * Point `command` at your build script and `outdir` at where it writes
148 * output. Alchemy runs the command, hashes the output, and deploys it as
149 * an assets-only Worker — no Worker code is uploaded, and Cloudflare's
150 * asset layer serves every request itself.
151 *
152 * **Example:** Deploying a Hugo site
153 * ```typescript
154 * const site = yield* Cloudflare.Website.StaticSite("Blog", {
155 * command: "hugo --minify",
156 * outdir: "public",
157 * });
158 * ```
159 *
160 * Provide `main` to put your own Worker in front of the assets instead.
161 * The Worker receives an `ASSETS` binding it can delegate to:
162 *
163 * ```typescript
164 * // src/worker.ts
165 * export default {
166 * fetch: (request: Request, env: { ASSETS: Fetcher }) =>
167 * env.ASSETS.fetch(request),
168 * };
169 * ```
170 *
171 * **Example:** Custom Worker in front of the assets
172 * ```typescript
173 * const site = yield* Cloudflare.Website.StaticSite("Blog", {
174 * command: "hugo --minify",
175 * outdir: "public",
176 * main: "./src/worker.ts",
177 * });
178 * ```
179 *
180 * ### Asset Configuration
181 * Use `assets` to control how Cloudflare handles routing for
182 * your static files — HTML handling, not-found behavior, etc.
183 *
184 * **Example:** SPA-style routing
185 * ```typescript
186 * const site = yield* Cloudflare.Website.StaticSite("App", {
187 * command: "npm run build",
188 * outdir: "dist",
189 * main: "./src/worker.ts",
190 * assets: {
191 * htmlHandling: "auto-trailing-slash",
192 * notFoundHandling: "single-page-application",
193 * },
194 * });
195 * ```
196 *
197 * ### Building from a Subdirectory
198 * Set `cwd` to run the build command in a subdirectory (e.g. a
199 * monorepo package). `outdir` is resolved relative to `cwd`.
200 *
201 * **Example:** Building a frontend in a monorepo
202 * ```typescript
203 * const site = yield* Cloudflare.Website.StaticSite("Web", {
204 * cwd: "apps/web",
205 * command: "npm run build",
206 * outdir: "dist",
207 * main: "apps/web/worker.ts",
208 * });
209 * ```
210 *
211 * ### Custom Rebuild Scope
212 * By default, all non-gitignored files are hashed to decide whether
213 * the build should re-run. Use `memo` to narrow the scope.
214 *
215 * **Example:** Narrowing the memo scope
216 * ```typescript
217 * const site = yield* Cloudflare.Website.StaticSite("Docs", {
218 * command: "npm run build",
219 * outdir: "dist",
220 * main: "./src/worker.ts",
221 * memo: {
222 * include: ["content/**", "templates/**", "config.toml"],
223 * },
224 * });
225 * ```
226 *
227 * **Example:** Rebuilding when a sibling workspace package changes
228 * The default scope only hashes files under `cwd` (plus the nearest
229 * lockfile), so edits to a sibling workspace package the app imports do
230 * not retrigger the build on their own. Add the sibling's sources with a
231 * `../` include glob — and keep `lockfile: true`, since providing
232 * `include` otherwise drops the lockfile from the hash:
233 * ```typescript
234 * const site = yield* Cloudflare.Website.StaticSite("Web", {
235 * cwd: "apps/web",
236 * command: "npm run build",
237 * outdir: "dist",
238 * main: "./src/worker.ts",
239 * memo: {
240 * include: ["**\/*", "../../packages/env/src/**"],
241 * lockfile: true,
242 * },
243 * });
244 * ```
245 *
246 * ### Class Form
247 * Calling `StaticSite` with no arguments returns a constructor you can
248 * `extend` to declare the Worker as a named class. The class is both
249 * an `Effect` you can `yield*` to deploy and a type you can reference
250 * elsewhere — useful when other resources need to bind to this Worker.
251 *
252 * **Example:** Declaring a Worker class
253 * ```typescript
254 * class Blog extends Cloudflare.Website.StaticSite<Blog>()("Blog", {
255 * command: "hugo --minify",
256 * outdir: "public",
257 * main: "./src/worker.ts",
258 * }) {}
259 *
260 * const site = yield* Blog;
261 * ```
262 *
263 * @resource
264 * @product Website
265 * @category Workers & Compute
266 */
267 export const StaticSite: {
268 <Self>(): {
269 <const Bindings extends WorkerBindingProps = {}, Req = never>(
270 id: string,
271 propsEff:
272 | InputProps<StaticSiteProps<Bindings>, "dev">
273 | Effect.Effect<InputProps<StaticSiteProps<Bindings>, "dev">, never, Req>,
274 ): Effect.Effect<Self, never, Req | Providers> & {
275 new (): StaticSiteWorker<Bindings>;
276 };
277 };
278 <const Bindings extends WorkerBindingProps = {}, Req = never>(
279 id: string,
280 propsEff:
281 | InputProps<StaticSiteProps<Bindings>, "dev">
282 | Effect.Effect<InputProps<StaticSiteProps<Bindings>, "dev">, never, Req>,
283 ): Effect.Effect<StaticSiteWorker<Bindings>, never, Req | Providers>;
284 } = ((id?: any, propsEff?: any) =>
285 id === undefined
286 ? (id: string, propsEff: any) => effectClass(makeStaticSite(id, propsEff))
287 : makeStaticSite(id, propsEff)) as any;
288
289 const makeStaticSite = <const Bindings extends WorkerBindingProps = {}, Req = never>(
290 id: string,
291 propsEff:
292 | InputProps<StaticSiteProps<Bindings>, "dev">
293 | Effect.Effect<InputProps<StaticSiteProps<Bindings>, "dev">, never, Req>,
294 ) =>
295 Effect.gen(function* () {
296 const ctx = yield* AlchemyContext;
297 const props = yield* asEffect(propsEff);
298
299 // `Dev` and `Build` carry constant logical ids, so they are namespaced
300 // under `id` to keep two sites on one stack from colliding. Nothing
301 // else is: the site's own `props` — and the resources its `env`
302 // bindings declare — must resolve in the CALLER's namespace. Pushing
303 // the namespace around the whole body instead re-declares a shared
304 // resource referenced from `env` as a second copy under `<id>/`.
305 // `Vite` already passes `id` straight through to `Worker`.
306
307 // In dev mode with a dev.command, declare a DevCommand resource so
308 // the sidecar owns the process lifecycle (survives user-code HMR),
309 // skip the build, and tell Worker not to start a local instance.
310 const devCommand = props.dev?.command !== undefined ? props.dev : undefined;
311 const dev =
312 ctx.dev && devCommand
313 ? yield* Command.Dev("Dev", {
314 command: devCommand.command,
315 cwd: devCommand.cwd ?? (typeof props.cwd === "string" ? props.cwd : undefined),
316 env: yield* serializeEnv(devCommand.env ?? props.env),
317 }).pipe(
318 Namespace.push(id),
319 Effect.map((d) =>
320 Output.map(d.url, (url) => ({
321 url: url ?? devCommand.url,
322 })),
323 ),
324 )
325 : undefined;
326
327 const build = dev
328 ? undefined
329 : yield* Command.Build("Build", {
330 command: props.command,
331 cwd: props.cwd,
332 memo: props.memo,
333 outdir: props.outdir,
334 env: yield* serializeEnv(props.env),
335 }).pipe(Namespace.push(id));
336
337 // Pure-static sites (neither `main` nor `script`) deploy as
338 // assets-only Workers: no script is uploaded and Cloudflare's asset
339 // layer serves every request itself.
340 //
341 // The Worker's FQN was `<id>/Worker` before #1053 flattened it to
342 // `<id>`; `renamedFrom` migrates the pre-existing state row to the new
343 // FQN instead of letting the engine plan a create+delete replacement
344 // (a new physical name, a torn-down workers.dev URL, and a
345 // custom-domain handover that crashes the deploy).
346 return yield* Worker<Bindings, WorkerAssetsConfig, Req>(id, {
347 ...props,
348 assets: build
349 ? cast({
350 directory: build.outdir,
351 hash: build.hash.output,
352 // oxlint-disable-next-line typescript/no-misused-spread -- assets is a plain config object in practice; a top-level Output/Effect would be dropped (pre-existing)
353 ...props.assets,
354 })
355 : undefined,
356 // Opt out of the local Worker in dev when the external DevCommand
357 // is serving the content. The Worker resource still exists in
358 // state with a stub Attributes shape.
359 dev: dev
360 ? { mode: "external", url: dev.url }
361 : props.dev && !devCommand
362 ? {
363 port: props.dev.port,
364 strictPort: props.dev.strictPort,
365 host: props.dev.host,
366 }
367 : undefined,
368 script: props.script,
369 }).pipe(renamedFrom(`${id}/Worker`));
370 });
371
372 /**
373 * Serialize the site's `env` for the build/dev subprocess. The same record
374 * doubles as the Worker's binding props, so entries may be plain strings,
375 * `Redacted` secrets, `effect/Config` values, `Output` references, or
376 * binding Effects:
377 *
378 * - strings and `Redacted` values pass through unchanged
379 * - `Config` (and any other runnable Effect) is resolved here, at stack
380 * construction — passing it through unresolved would hand the subprocess
381 * the JSON-serialized `Config` object (`{"_id":"Config"}`) instead of its
382 * value (#796)
383 * - `Output` references resolve at reconcile; the resolved value is
384 * serialized the same way inline values are (an `Output<object>` must
385 * reach the subprocess as JSON, not `[object Object]`)
386 * - binding Effects (`~alchemy/Kind`-marked, e.g. a `WorkerLoader`) and
387 * `Cloudflare.Container` declarations have no env-var representation and
388 * are dropped
389 * - remaining plain values (`null`, numbers, JSON objects) are stringified
390 */
391 const serializeEnv = Effect.fn(function* (
392 env: Input<WorkerBindingProps | Record<string, string | Redacted.Redacted<string>> | undefined>,
393 ) {
394 const entries: [string, unknown][] = [];
395 for (const [k, v] of Object.entries(env ?? {})) {
396 if (v === undefined) continue;
397 if (typeof v === "string" || Redacted.isRedacted(v)) {
398 entries.push([k, v]);
399 } else if (Output.isOutput(v)) {
400 entries.push([k, Output.map(v, serializeEnvValue)]);
401 } else if (isContainerDecl(v)) {
402 // A `Cloudflare.Container` declaration is Effect-shaped but is a
403 // binding (DO namespace + ContainerApplication) — yielding it would
404 // resolve the started-instance tag, which only exists inside a
405 // Durable Object (#997). Deploy-time only, nothing to expose to the
406 // build subprocess.
407 continue;
408 } else if (isYieldableEffectLike(v)) {
409 const resolved = serializeEnvValue(
410 yield* asEffect(v as YieldableEffectLike<unknown, unknown, never>).pipe(Effect.orDie),
411 );
412 if (resolved === undefined) continue;
413 entries.push([k, resolved]);
414 } else if (v !== null && typeof v === "object" && "~alchemy/Kind" in v) {
415 // A binding Effect (e.g. WorkerLoader) — deploy-time only, nothing to
416 // expose to the build subprocess.
417 continue;
418 } else {
419 entries.push([k, JSON.stringify(v)]);
420 }
421 }
422 return Object.fromEntries(entries) as Record<string, string | Redacted.Redacted<string>>;
423 });
424
425 /**
426 * Serialize one resolved env value for the build/dev subprocess: strings and
427 * `Redacted` pass through, everything else becomes JSON.
428 */
429 const serializeEnvValue = (value: unknown): string | Redacted.Redacted<string> | undefined =>
430 value === undefined
431 ? undefined
432 : typeof value === "string"
433 ? value
434 : Redacted.isRedacted(value)
435 ? (value as Redacted.Redacted<string>)
436 : JSON.stringify(value);