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

main
ts 322 lines 10.5 KB
Raw
1 import { AlchemyContext } from "alchemy/AlchemyContext";
2 import type { MemoOptions } from "alchemy/Command/Memo";
3 import * as Namespace from "alchemy/Namespace";
4 import * as Output from "alchemy/Output";
5 import { ProviderModePolicy } from "alchemy/ProviderMode";
6 import type { ExtraFile } from "alchemy/Util/extraFiles";
7 import { initialCwd } from "alchemy/Util/Node";
8 import {
9 staticConfigFromAssets,
10 type WebsiteAssetsProps,
11 type WebsiteNotFoundHandling,
12 } from "alchemy/Website/assets";
13 import { packSiteExtraFiles } from "alchemy/Website/packExtraFiles";
14 import { Server as FrameworkServer, type ServerDevProps } from "alchemy/Website/Server";
15 import * as Data from "effect/Data";
16 import * as Effect from "effect/Effect";
17 import * as FileSystem from "effect/FileSystem";
18 import * as Path from "effect/Path";
19 import * as Redacted from "effect/Redacted";
20 import {
21 Service,
22 type ResourceRequirements,
23 type RevisionScaling,
24 type ServiceProps,
25 } from "../Run/Service.ts";
26
27 export type { ServerDevProps, WebsiteAssetsProps, WebsiteNotFoundHandling };
28 export { staticConfigFromAssets };
29
30 /** Port the Node serve entry listens on (Cloud Run injects `PORT`). */
31 export const WEBSITE_PORT = 8080;
32
33 /** Process environment value for a hosted website. */
34 export type WebsiteEnvValue =
35 | string
36 | Redacted.Redacted<string>
37 | Output.Output<string | undefined>;
38
39 /**
40 * Cloud Run knobs shared by every GCP website composite (framework sites
41 * and `StaticSite`).
42 */
43 export interface WebsiteServiceProps {
44 /**
45 * Allow unauthenticated requests. `true` disables Cloud Run's invoker IAM
46 * check so anyone can load the site; `false` requires a Google-signed
47 * identity token on every request.
48 * @default true
49 */
50 public?: boolean;
51 /**
52 * Ingress (`INGRESS_TRAFFIC_ALL`, `INGRESS_TRAFFIC_INTERNAL_ONLY`,
53 * `INGRESS_TRAFFIC_INTERNAL_LOAD_BALANCER`).
54 * @default "INGRESS_TRAFFIC_ALL"
55 */
56 ingress?: ServiceProps["ingress"];
57 /**
58 * Revision scaling. Set `minInstanceCount: 1` to avoid cold starts.
59 */
60 scaling?: RevisionScaling;
61 /**
62 * CPU / memory for the server container, e.g.
63 * `{ limits: { cpu: "1", memory: "1Gi" } }`.
64 * @default Cloud Run's default (1 vCPU, 512Mi)
65 */
66 resources?: ResourceRequirements;
67 /**
68 * Request timeout (e.g. `"60s"`).
69 * @default "300s"
70 */
71 timeout?: string;
72 /**
73 * Max concurrent requests per instance.
74 * @default 80
75 */
76 maxInstanceRequestConcurrency?: number;
77 /**
78 * Runtime service account email. When omitted, Alchemy mints a
79 * dedicated service account with no roles (deleted on destroy).
80 */
81 serviceAccount?: string;
82 /**
83 * User labels applied to the Cloud Run service. Alchemy ownership labels
84 * are merged in automatically.
85 */
86 tags?: Record<string, string>;
87 }
88
89 /**
90 * Props shared by every GCP framework website composite.
91 */
92 export interface FrameworkSiteProps extends WebsiteServiceProps {
93 /**
94 * Project root directory (the directory containing `package.json`).
95 * @default "."
96 */
97 rootDir?: string;
98 /**
99 * Controls which files are hashed to decide whether the build re-runs.
100 * @default true
101 */
102 memo?: MemoOptions | boolean;
103 /**
104 * Process environment for the hosted server (Cloud Run container env
105 * vars). Accepts `Output`s (e.g. `VITE_API_URL: api.uri`). `Redacted`
106 * values are unwrapped into plain container env vars.
107 */
108 env?: Record<string, WebsiteEnvValue>;
109 /**
110 * Static-asset routing (`notFoundHandling`, `htmlHandling`). Client
111 * files are baked into the container image and served by the Node
112 * server.
113 */
114 assets?: WebsiteAssetsProps;
115 /**
116 * Options for the local dev server that runs this site under
117 * `alchemy dev`.
118 */
119 dev?: ServerDevProps;
120 }
121
122 /** Per-framework wiring for {@link makeFrameworkSite}. */
123 export interface FrameworkSiteConfig {
124 /** Display name used in error messages (e.g. `"SvelteKit"`). */
125 name: string;
126 /** Framework-integration module specifier. */
127 framework: string;
128 /** Node deploy-target module specifier. */
129 target: string;
130 /**
131 * Framework-specific build options forwarded to the integration (e.g.
132 * `{ kit }`, `{ nuxt }`, `{ astro }`). Must be JSON-serializable.
133 */
134 options?: Record<string, unknown> | undefined;
135 /**
136 * Assets-only routing hints (Vite SPA fallback). Accepted for parity
137 * with the other providers; the Node serve entry handles routing.
138 */
139 static?: { spa?: boolean; errorPage?: string } | undefined;
140 /**
141 * Vocs/Waku: serve `about/index.html` at `/about`.
142 * @default "none"
143 */
144 htmlHandling?: "none" | "drop-trailing-slash";
145 /**
146 * Packages installed into the image with `npm install` instead of
147 * bundling (Next.js needs `next`).
148 */
149 install?: string[] | undefined;
150 /**
151 * Ship `.next`, `public/`, and `next.config.*` from the app root instead
152 * of the build's dist directory (Next.js).
153 */
154 skipClientAssets?: boolean | undefined;
155 }
156
157 export interface FrameworkSite {
158 /**
159 * Public site URL. Local framework URL under `alchemy dev`; the Cloud
160 * Run service URL (`https://{service}-{hash}.{region}.run.app`) on
161 * deploy.
162 */
163 url: string | Output.Output<string | undefined> | undefined;
164 /** Hosting Cloud Run service. `undefined` during `alchemy dev`. */
165 service: Service | undefined;
166 }
167
168 export class FrameworkSiteError extends Data.TaggedError("FrameworkSiteError")<{
169 readonly framework: string;
170 readonly message: string;
171 readonly cause?: unknown;
172 }> {}
173
174 /** Unwrap `Redacted` values into plain container env vars. */
175 export const websiteEnv = (
176 env: Record<string, WebsiteEnvValue> | undefined,
177 ): Record<string, string | Output.Output<string | undefined>> | undefined => {
178 if (env === undefined) return undefined;
179 return Object.fromEntries(
180 Object.entries(env).map(([key, value]) => [
181 key,
182 Redacted.isRedacted(value) ? Redacted.value(value) : value,
183 ]),
184 );
185 };
186
187 /**
188 * Cloud Run service props for a website whose image is the unbundled Node
189 * program `main` plus `extraFiles`.
190 */
191 export const websiteServiceProps = (
192 props: WebsiteServiceProps & {
193 env?: Record<string, WebsiteEnvValue>;
194 },
195 program: {
196 main: string;
197 extraFiles: ReadonlyArray<ExtraFile>;
198 install?: string[] | undefined;
199 },
200 ): ServiceProps => ({
201 main: program.main,
202 // The Node serve entry is a complete program, not an Effect-native one.
203 isExternal: true,
204 extraFiles: program.extraFiles,
205 port: WEBSITE_PORT,
206 env: websiteEnv(props.env),
207 labels: props.tags,
208 ingress: props.ingress,
209 invokerIamDisabled: props.public ?? true,
210 template: {
211 timeout: props.timeout,
212 maxInstanceRequestConcurrency: props.maxInstanceRequestConcurrency,
213 scaling: props.scaling,
214 serviceAccount: props.serviceAccount,
215 containers: props.resources !== undefined ? [{ resources: props.resources }] : undefined,
216 },
217 build:
218 program.install !== undefined && program.install.length > 0
219 ? { install: program.install }
220 : undefined,
221 });
222
223 const runFrameworkSite = Effect.fn("GCP.Website.FrameworkSite")(function* (
224 _id: string,
225 props: FrameworkSiteProps,
226 config: FrameworkSiteConfig,
227 ) {
228 const ctx = yield* AlchemyContext;
229 const remoted = yield* ProviderModePolicy;
230 const isLocal = ctx.dev && remoted !== true;
231 const path = yield* Path.Path;
232 const fs = yield* FileSystem.FileSystem;
233
234 const build = yield* FrameworkServer("Build", {
235 framework: config.framework,
236 target: config.target,
237 root: props.rootDir,
238 env: websiteEnv(props.env),
239 options: config.options,
240 memo: props.memo,
241 dev: props.dev,
242 });
243
244 if (isLocal) {
245 return { url: build.url, service: undefined } satisfies FrameworkSite;
246 }
247
248 // The build runs at apply time (`Website.Server` is a resource), so its
249 // attributes are Outputs here — derive every deploy input lazily.
250 const buildOut = Output.mapEffect(
251 ([serverEntry, distDir]: [string | undefined, string | undefined]) =>
252 Effect.gen(function* () {
253 if (serverEntry === undefined || distDir === undefined) {
254 return yield* Effect.die(
255 new FrameworkSiteError({
256 framework: config.framework,
257 message: `The ${config.name} build produced no Node serve entry (serverModules[0]). The Node deploy target should write serve-node.mjs.`,
258 }),
259 );
260 }
261 const main = path.resolve(initialCwd, serverEntry);
262 if (!(yield* fs.exists(main).pipe(Effect.orElseSucceed(() => false)))) {
263 return yield* Effect.die(
264 new FrameworkSiteError({
265 framework: config.framework,
266 message: `The ${config.name} build produced no server entry at ${main}`,
267 }),
268 );
269 }
270 return { distDir: path.resolve(initialCwd, distDir), main };
271 }),
272 )(
273 Output.all(
274 build.serverEntry as unknown as Output.Output<string | undefined>,
275 build.distDir as unknown as Output.Output<string | undefined>,
276 ) as unknown as Output.Output<[string | undefined, string | undefined]>,
277 );
278 const main = Output.map(buildOut, (out) => out.main);
279
280 // Always an array: `extraFiles` selects the unbundled Node image mode.
281 const extraFiles = Output.mapEffect((out: { distDir: string; main: string }) =>
282 packSiteExtraFiles(out.distDir, config.skipClientAssets === true ? "next" : "client").pipe(
283 Effect.map((files) => files ?? []),
284 ),
285 )(buildOut);
286
287 const service = yield* Service(
288 "Service",
289 websiteServiceProps(props, {
290 main: main as unknown as string,
291 extraFiles: extraFiles as unknown as ExtraFile[],
292 install: config.install,
293 }),
294 );
295
296 return {
297 url: service.uri,
298 service,
299 } satisfies FrameworkSite;
300 });
301
302 /**
303 * Shared implementation behind the GCP framework website composites:
304 * `Website.Server` runs the framework toolchain (dev server / production
305 * build), then a live deploy bakes `serve-node.mjs` plus the build output
306 * into a Node image in Artifact Registry and runs it on a Cloud Run
307 * service.
308 *
309 * Callers pipe `Namespace.push(id)` themselves (the composites do).
310 *
311 * Composite-level tagged errors (`FrameworkSiteError`, filesystem) are
312 * defects — `Alchemy.Stack` only admits `ConfigError` on the user effect.
313 */
314 export const makeFrameworkSite = (
315 id: string,
316 props: FrameworkSiteProps,
317 config: FrameworkSiteConfig,
318 ) => runFrameworkSite(id, props, config).pipe(Effect.orDie);
319
320 /** Push {@link id} then run {@link makeFrameworkSite}. */
321 export const frameworkSite = (id: string, props: FrameworkSiteProps, config: FrameworkSiteConfig) =>
322 makeFrameworkSite(id, props, config).pipe(Namespace.push(id));