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

main
ts 238 lines 7.29 KB
Raw
1 import { AlchemyContext } from "alchemy/AlchemyContext";
2 import * as Command from "alchemy/Command";
3 import type { MemoOptions } from "alchemy/Command/Memo";
4 import * as Namespace from "alchemy/Namespace";
5 import * as Output from "alchemy/Output";
6 import { ProviderModePolicy } from "alchemy/ProviderMode";
7 import { initialCwd } from "alchemy/Util/Node";
8 import { loadFrontendCore } from "alchemy/Website/FrontendCore";
9 import * as Effect from "effect/Effect";
10 import * as Path from "effect/Path";
11 import type * as Redacted from "effect/Redacted";
12 import { Service } from "../Service.ts";
13 import {
14 DEFAULT_WEBSITE_PORT,
15 publishWebsiteDomain,
16 requireWebsiteDomainZone,
17 resolveWebsiteServer,
18 unwrapEnv,
19 websiteDomainName,
20 websiteUrl,
21 type FrameworkSiteProps,
22 type Website,
23 } from "./FrameworkSite.ts";
24
25 export interface StaticSiteProps extends Pick<
26 FrameworkSiteProps,
27 "domain" | "zone" | "server" | "tags" | "env"
28 > {
29 /**
30 * Shell command that produces the site (e.g. `hugo --minify`).
31 */
32 command: string;
33 /**
34 * Directory the command writes, relative to {@link cwd}.
35 */
36 outdir: string;
37 /**
38 * Working directory for {@link command}.
39 * @default process.cwd()
40 */
41 cwd?: string;
42 /**
43 * Controls which files are hashed to decide whether the build re-runs.
44 * @default true
45 */
46 memo?: MemoOptions | boolean;
47 /**
48 * Answer misses with the index page (200) instead of a 404 so
49 * client-side routes deep-link correctly. Mutually exclusive with
50 * {@link errorPage}.
51 */
52 spa?: boolean;
53 /**
54 * Serve this page with a real `404` status for requests that match no
55 * file. Mutually exclusive with {@link spa}.
56 */
57 errorPage?: string;
58 /**
59 * Local dev configuration. When `alchemy dev` runs, the build command
60 * is skipped and `command` is spawned as a long-lived child. Without
61 * `dev`, the site is still built and served locally (no cloud Service).
62 */
63 dev?: {
64 /**
65 * Shell command to run as the local dev server (e.g. `npm run dev`).
66 */
67 command: string;
68 /**
69 * Working directory for {@link command}. Defaults to
70 * {@link StaticSiteProps.cwd}.
71 */
72 cwd?: string;
73 /**
74 * Environment variables for {@link command}, merged on top of
75 * `process.env`.
76 */
77 env?: Record<string, string | Redacted.Redacted<string>>;
78 /**
79 * Override for the `url` output if alchemy fails to detect it from
80 * stdout of the dev command.
81 */
82 url?: string;
83 };
84 }
85
86 /**
87 * A Hetzner Service that serves static assets built by a shell command.
88 *
89 * `StaticSite` runs a build command (e.g. `npm run build`), packs the
90 * output directory into the unit archive, and deploys a tiny static-file
91 * server (`GET` assets, `/health`, optional SPA / 404-page). Use this
92 * when your site has its own build step — Hugo, Zola, Eleventy, or any
93 * custom pipeline.
94 *
95 * For Vite-based projects, prefer {@link Vite | Hetzner.Website.Vite}.
96 *
97 * `Dev` and `Build` carry constant logical ids, so they are namespaced
98 * under `id`. The Service stays in the caller's namespace (same as
99 * Cloudflare.Website.StaticSite).
100 *
101 *
102 * ### Basic Usage
103 * **Example:** Deploying a Hugo site
104 * ```typescript
105 * const site = yield* Hetzner.Website.StaticSite("Blog", {
106 * command: "hugo --minify",
107 * outdir: "public",
108 * });
109 * ```
110 *
111 * **Example:** SPA-style routing
112 * ```typescript
113 * const site = yield* Hetzner.Website.StaticSite("App", {
114 * command: "npm run build",
115 * outdir: "dist",
116 * spa: true,
117 * });
118 * ```
119 *
120 * ### Building from a Subdirectory
121 * **Example:** Building a frontend in a monorepo
122 * ```typescript
123 * const site = yield* Hetzner.Website.StaticSite("Web", {
124 * cwd: "apps/web",
125 * command: "npm run build",
126 * outdir: "dist",
127 * });
128 * ```
129 *
130 * ### Local Development
131 * **Example:** External Dev Server
132 * ```typescript
133 * const site = yield* Hetzner.Website.StaticSite("App", {
134 * command: "npm run build",
135 * outdir: "dist",
136 * dev: { command: "npm run dev" },
137 * });
138 * ```
139 *
140 * @resource
141 * @product Website
142 */
143 export const StaticSite = (id: string, props: StaticSiteProps) =>
144 Effect.gen(function* () {
145 const ctx = yield* AlchemyContext;
146 const remoted = yield* ProviderModePolicy;
147 const isLocal = ctx.dev && remoted !== true;
148 const port = DEFAULT_WEBSITE_PORT;
149
150 if (props.spa && props.errorPage) {
151 return yield* Effect.die(
152 `Cannot provide both "spa" and "errorPage". A SPA answers misses with the index page (200); "errorPage" answers them with a real 404.`,
153 );
154 }
155 yield* requireWebsiteDomainZone("Hetzner.Website.StaticSite", props);
156
157 if (isLocal && props.dev) {
158 const dev = yield* Command.Dev("Dev", {
159 command: props.dev.command,
160 cwd: props.dev.cwd ?? props.cwd,
161 env: props.dev.env ?? props.env,
162 }).pipe(Namespace.push(id));
163 const url = Output.map((detected: string | undefined) => detected ?? props.dev?.url)(dev.url);
164 return { url, server: undefined, service: undefined } satisfies Website;
165 }
166
167 const build = yield* Command.Build("Build", {
168 command: props.command,
169 cwd: props.cwd,
170 memo: props.memo,
171 outdir: props.outdir,
172 env: props.env,
173 }).pipe(Namespace.push(id));
174
175 const path = yield* Path.Path;
176 const cwd = path.resolve(initialCwd, props.cwd ?? ".");
177 const outdir = path.resolve(cwd, props.outdir);
178 const { NODE_SERVE_ENTRY_FILE_NAME, relativeClientDirExpression, writeNodeServeEntry } =
179 yield* loadFrontendCore;
180 const servePath = path.join(path.dirname(outdir), NODE_SERVE_ENTRY_FILE_NAME);
181 yield* writeNodeServeEntry({
182 output: { clientDirectory: outdir, serverModules: [], externalWorkspaces: new Set<string>() },
183 servePath,
184 serveModuleName: NODE_SERVE_ENTRY_FILE_NAME,
185 clientDirExpression: relativeClientDirExpression(servePath, outdir),
186 notFoundHandling:
187 props.errorPage !== undefined ? "404-page" : props.spa === true ? "spa" : "none",
188 printUrl: isLocal,
189 defaultPort: port,
190 platform: "node",
191 });
192
193 if (isLocal) {
194 const bun = yield* Effect.sync(() => process.execPath);
195 const dev = yield* Command.Dev("Dev", {
196 command: `${bun} ${servePath}`,
197 cwd: path.dirname(servePath),
198 env: {
199 ...unwrapEnv(props.env),
200 ALCHEMY_BUILD_HASH: build.hash.output as unknown as string,
201 PORT: "0",
202 HOST: "127.0.0.1",
203 },
204 }).pipe(Namespace.push(id));
205 return { url: dev.url, server: undefined, service: undefined } satisfies Website;
206 }
207
208 const server =
209 props.server !== undefined
210 ? yield* resolveWebsiteServer(props)
211 : yield* resolveWebsiteServer(props).pipe(Namespace.push(id));
212 const service = yield* Service(id, {
213 server,
214 main: servePath,
215 extraFiles: [{ source: outdir, destination: path.basename(outdir) }],
216 port,
217 env: { ...unwrapEnv(props.env), PORT: String(port) },
218 // Generated static-file server is a complete bun/node program.
219 isExternal: true,
220 });
221
222 yield* publishWebsiteDomain({
223 domain: props.domain,
224 zone: props.zone,
225 server,
226 tags: props.tags,
227 });
228
229 return {
230 url: websiteUrl({
231 domain: websiteDomainName(props.domain),
232 service,
233 port,
234 }),
235 server,
236 service,
237 } satisfies Website;
238 }).pipe(Effect.orDie);