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

main
ts 564 lines 19.2 KB
Raw
1 import { AlchemyContext } from "alchemy/AlchemyContext";
2 import type { MemoOptions } from "alchemy/Command/Memo";
3 import type { InputProps } from "alchemy/Input";
4 import type { Input } from "alchemy/Input";
5 import * as Namespace from "alchemy/Namespace";
6 import * as Output from "alchemy/Output";
7 import { ProviderModePolicy } from "alchemy/ProviderMode";
8 import { Server, type ServerDevProps } from "alchemy/Website/Server";
9 import * as Duration from "effect/Duration";
10 import * as Effect from "effect/Effect";
11 import { Table } from "../DynamoDB/Table.ts";
12 import type { PolicyStatement } from "../IAM/Policy.ts";
13 import { EventSourceMapping } from "../Lambda/EventSourceMapping.ts";
14 import { Function as LambdaFunction } from "../Lambda/Function.ts";
15 import { WebFunction } from "../Lambda/WebFunction.ts";
16 import { Bucket } from "../S3/Bucket.ts";
17 import { Queue } from "../SQS/Queue.ts";
18 import { AssetDeployment } from "./AssetDeployment.ts";
19 import { asRouterDomain, registerDevRouterRoute } from "./DevRouterRoute.ts";
20 import {
21 checkWebsiteRegions,
22 siteEndpoint,
23 type FunctionServerProps,
24 type WebFunctionServerProps,
25 } from "./FrameworkSite.ts";
26 import {
27 normalizeWebsiteDomain,
28 type WebsiteAssetsConfig,
29 type WebsiteDomainProps,
30 type WebsiteEdgeProps,
31 type WebsiteInvalidationProps,
32 } from "./shared.ts";
33 import { makeKvSite, type StaticSiteProps } from "./StaticSite.ts";
34
35 /**
36 * The framework-integration module that drives the `@opennextjs/aws` build
37 * (it is its own deploy target — the module IS the AWS pipeline).
38 */
39 export const NEXTJS_AWS_FRAMEWORK_SPECIFIER = "@alchemy.run/frontend-frameworks/nextjs/aws";
40
41 /** The S3 key prefix of the Next.js cache (both server forms). */
42 export const NEXTJS_CACHE_PREFIX = "_cache";
43
44 /** Props shared by both server forms of {@link Nextjs}. */
45 export interface NextjsBaseProps {
46 /**
47 * Project root directory (the directory containing `next.config.ts`).
48 * @default "."
49 */
50 rootDir?: string;
51 /**
52 * Controls which files are hashed to decide whether the build re-runs.
53 * @default true
54 */
55 memo?: MemoOptions | boolean;
56 /**
57 * Options for the local dev server that runs this site under
58 * `alchemy dev`.
59 */
60 dev?: ServerDevProps;
61 /**
62 * Maximum server request duration.
63 * @default 30 seconds
64 */
65 timeout?: Duration.Duration;
66 /**
67 * Environment variables for the SSR server (Lambda environment).
68 * Values accept `Output`s (e.g. `API_URL: api.url`).
69 */
70 env?: Record<string, any>;
71 /**
72 * Static asset upload configuration.
73 */
74 assets?: WebsiteAssetsConfig;
75 /**
76 * Optional custom domain. A string is shorthand for `{ name }`; `null`
77 * explicitly clears a previously set domain. Set `domain.router` to
78 * serve the site through an existing `AWS.Website.Router` instead of a
79 * standalone CloudFront distribution.
80 */
81 domain?: string | WebsiteDomainProps | null;
82 /**
83 * Serve the site at its CloudFront default domain
84 * (`https://dxxxx.cloudfront.net`). `false` 301s default-domain requests
85 * to `https://<domain.name>` at the edge and excludes the default domain
86 * from the `urls` output. Requires `domain`; not applicable when
87 * `domain.router` is set.
88 * @default true
89 */
90 cloudfrontUrl?: boolean;
91 /**
92 * Additional CloudFront Function customizations.
93 */
94 edge?: WebsiteEdgeProps;
95 /**
96 * Optional deterministic S3 bucket name for the asset bucket.
97 */
98 bucketName?: string;
99 /**
100 * Whether to delete uploaded objects when the bucket is destroyed.
101 * @default false
102 */
103 forceDestroy?: boolean;
104 /**
105 * CloudFront invalidation behavior.
106 * @default { paths: "all", wait: false }
107 */
108 invalidation?: false | WebsiteInvalidationProps;
109 /**
110 * User-defined tags applied to created resources.
111 */
112 tags?: Record<string, string>;
113 }
114
115 /**
116 * The server and the image optimizer on Lambda Functions behind Function
117 * URLs: for servers that need more than 2 GB of memory or x86_64, or
118 * Regions without Web Functions.
119 */
120 export interface NextjsFunctionServerProps extends FunctionServerProps {
121 /**
122 * Image optimization (Lambda) configuration.
123 */
124 imageOptimization?: {
125 /**
126 * Memory allocated to the image optimization function, in MB.
127 * @default 1536
128 */
129 memorySize?: number;
130 };
131 }
132
133 /**
134 * Props for {@link Nextjs}. By default Next runs as its standalone server on
135 * a Lambda Web Function; set `server: "function"` for the OpenNext topology
136 * on Lambda Functions.
137 */
138 export type NextjsProps = NextjsBaseProps & (WebFunctionServerProps | NextjsFunctionServerProps);
139
140 /**
141 * Deploy a Next.js application to AWS: Next's own standalone server on a
142 * Lambda Web Function, static assets in S3 behind CloudFront's KV-manifest
143 * edge router, and an S3 bucket for the cache. The server runs the way it
144 * does under `next start` (SSR, middleware, ISR revalidation and
145 * `/_next/image` in-process), and an S3 `cacheHandler` shares ISR pages,
146 * the fetch cache and optimized images across environments.
147 *
148 * The build runs through `@alchemy.run/frontend-frameworks/nextjs/aws`,
149 * which must be installed in your project. It runs `next build` with
150 * standalone output; your `next.config.*` is used as-is.
151 *
152 * With `server: "function"` the site uses the OpenNext (`@opennextjs/aws`)
153 * topology instead: the server and an image optimizer on Lambda Functions
154 * behind streaming Function URLs, and ISR revalidation through an SQS FIFO
155 * queue, a consumer Lambda, and a DynamoDB tag table. Install
156 * `@opennextjs/aws` for it; when the project has no `open-next.config.ts`,
157 * a minimal streaming default is generated.
158 *
159 * During `alchemy dev` the site is Next's own dev server (`next dev`) and
160 * no cloud resources are declared; `Alchemy.remote()` opts back into the
161 * full live deployment.
162 *
163 * ### Creating Next.js Sites
164 * **Example:** Basic Next.js App
165 * ```typescript
166 * const site = yield* AWS.Website.Nextjs("Web", {
167 * rootDir: "./app",
168 * });
169 * ```
170 *
171 * **Example:** Custom Domain
172 * ```typescript
173 * const site = yield* AWS.Website.Nextjs("Web", {
174 * rootDir: "./app",
175 * domain: {
176 * name: "app.example.com",
177 * hostedZoneId: zone.hostedZoneId,
178 * },
179 * });
180 * ```
181 *
182 * ### Server Configuration
183 * **Example:** Tune The Server Function
184 * ```typescript
185 * const site = yield* AWS.Website.Nextjs("Web", {
186 * rootDir: "./app",
187 * memorySize: 2048,
188 * env: {
189 * API_BASE: api.url,
190 * },
191 * });
192 * ```
193 *
194 * @resource
195 */
196
197 export const Nextjs = Effect.fn("AWS.Website.Nextjs")(
198 function* (id: string, propsIn: InputProps<NextjsProps, "server"> = {}) {
199 const props = propsIn as NextjsProps;
200 yield* checkWebsiteRegions(`AWS.Website.Nextjs "${id}"`, props);
201 const ctx = yield* AlchemyContext;
202 const remoted = yield* ProviderModePolicy;
203 // Mirrors the other Website composites: during `alchemy dev` the site
204 // is `next dev` (native HMR) and no cloud resources are declared;
205 // `Alchemy.remote()` opts back into the full live deployment.
206 const isLocal = ctx.dev && remoted !== true;
207 const onWebFunction = (props.server ?? "web-function") === "web-function";
208
209 const build = yield* Server("Build", {
210 framework: NEXTJS_AWS_FRAMEWORK_SPECIFIER,
211 target: NEXTJS_AWS_FRAMEWORK_SPECIFIER,
212 options: { server: onWebFunction ? "web-function" : "function" },
213 root: props.rootDir,
214 env: props.env,
215 memo: props.memo,
216 dev: props.dev,
217 });
218
219 if (isLocal) {
220 // Router-attached sites register with the Router in dev exactly as they
221 // do live — same resource types and ids — with `next dev` standing in
222 // for the S3 + Lambda origins.
223 const routerDomain = asRouterDomain(normalizeWebsiteDomain(props.domain));
224 const kvNamespace = routerDomain
225 ? yield* registerDevRouterRoute(routerDomain, build.url)
226 : undefined;
227 return {
228 bucket: undefined,
229 build,
230 cacheBucket: undefined,
231 cacheFiles: undefined,
232 distribution: undefined,
233 files: undefined,
234 imageFunction: undefined,
235 imageUrl: undefined,
236 invalidation: undefined,
237 kvNamespace,
238 revalidationFunction: undefined,
239 revalidationQueue: undefined,
240 server: undefined,
241 serverUrl: undefined,
242 tagCacheTable: undefined,
243 url: build.url,
244 urls: [build.url],
245 };
246 }
247
248 // `.open-next/<relative>` derived from the build's dist directory.
249 const fromDist = (relative: string) =>
250 Output.map((dir: string | undefined) => {
251 if (!dir) {
252 throw new Error("The Next.js build produced no .open-next directory.");
253 }
254 return `${dir}/${relative}`;
255 })(build.distDir as any) as Input<string>;
256
257 // The CDN-facing asset bucket (site assets + public files + originals
258 // for the image optimizer).
259 const bucket =
260 props.assets?.bucket ??
261 (yield* Bucket("Bucket", {
262 bucketName: props.bucketName,
263 forceDestroy: props.forceDestroy,
264 tags: props.tags,
265 }));
266
267 // The ISR/fetch cache lives in its OWN bucket, deliberately separate
268 // from the site bucket: the site bucket carries the CloudFront read
269 // policy (bound to the distribution's ARN), so a server -> site-bucket
270 // reference would close a dependency cycle
271 // (server -> bucket -> distribution -> server) and force the CloudFront
272 // origin to rendezvous on the Lambda's precreate stub, which has no
273 // Function URL yet. A dedicated cache bucket keeps the graph acyclic.
274 const cacheBucket = yield* Bucket("CacheBucket", {
275 forceDestroy: props.forceDestroy,
276 tags: props.tags,
277 });
278
279 // The cache handler's S3 access, on whichever server runs.
280 const cachePolicy = [
281 {
282 Effect: "Allow",
283 Action: ["s3:GetObject", "s3:PutObject"],
284 Resource: [Output.interpolate`${cacheBucket.bucketArn}/*` as any],
285 },
286 {
287 // A missing key answers 404 (not 403) only with ListBucket.
288 Effect: "Allow",
289 Action: ["s3:ListBucket"],
290 Resource: [cacheBucket.bucketArn as any],
291 },
292 ] satisfies PolicyStatement[];
293
294 if (props.server !== "function") {
295 // Next's standalone server: SSR, middleware, ISR revalidation and
296 // `/_next/image` run in-process; the S3 cache handler shares the
297 // cache across environments.
298 const server = yield* WebFunction("WebServer", {
299 main: build.serverEntry as unknown as string,
300 bundle: false,
301 authType: "ApplicationManaged",
302 timeout: props.timeout ?? Duration.seconds(30),
303 maxConcurrencyPerEnvironment: props.maxConcurrencyPerEnvironment,
304 maxEnvironments: props.maxEnvironments,
305 env: {
306 CACHE_BUCKET_NAME: cacheBucket.bucketName,
307 CACHE_BUCKET_KEY_PREFIX: NEXTJS_CACHE_PREFIX,
308 ...props.env,
309 },
310 });
311 yield* server.bind`Allow(${server}, AWS.Website.Nextjs.Cache(${cacheBucket}))`({
312 policyStatements: cachePolicy,
313 });
314 const endpoint = yield* siteEndpoint("ServerEndpoint", server, props);
315 const site = yield* makeKvSite(
316 id,
317 {
318 path: build.clientDir as unknown as string,
319 assets: props.assets,
320 domain: props.domain,
321 cloudfrontUrl: props.cloudfrontUrl,
322 edge: props.edge,
323 bucketName: props.bucketName,
324 forceDestroy: props.forceDestroy,
325 invalidation: props.invalidation,
326 tags: props.tags,
327 },
328 { serverHost: endpoint.domainName },
329 );
330 return {
331 ...site,
332 build,
333 cacheBucket,
334 cacheFiles: undefined,
335 imageFunction: undefined,
336 imageUrl: undefined,
337 revalidationFunction: undefined,
338 revalidationQueue: undefined,
339 server,
340 serverUrl: endpoint.url,
341 tagCacheTable: undefined,
342 };
343 }
344 const fnProps = props;
345
346 // ISR revalidation queue: OpenNext's `sqs` queue override sends
347 // explicitly-deduplicated messages to a FIFO queue.
348 const revalidationQueue = yield* Queue("RevalidationQueue", {
349 fifo: true,
350 // Lambda requires the queue's visibility timeout to cover the
351 // consumer function's timeout (30s) with headroom.
352 visibilityTimeout: "2 minutes",
353 tags: props.tags,
354 });
355
356 // Tag cache (`revalidateTag` / `revalidatePath`): the schema OpenNext's
357 // `dynamodb` tag-cache override queries — `tag`/`path` primary key plus
358 // the `revalidate` GSI on `path`/`revalidatedAt`.
359 const tagCacheTable = yield* Table("TagCache", {
360 partitionKey: "tag",
361 sortKey: "path",
362 attributes: { tag: "S", path: "S", revalidatedAt: "N" },
363 globalSecondaryIndexes: [
364 {
365 indexName: "revalidate",
366 partitionKey: "path",
367 sortKey: "revalidatedAt",
368 projection: { ProjectionType: "ALL" },
369 },
370 ],
371 billingMode: "PAY_PER_REQUEST",
372 tags: props.tags,
373 });
374
375 const server = yield* LambdaFunction("Server", {
376 // The framework module derives the entry from open-next.output.json
377 // (origins.default.bundle + handler), so this tracks the manifest.
378 main: build.serverEntry as unknown as string,
379 handler: "handler",
380 isExternal: true,
381 // OpenNext's server-functions/default is a complete deployment unit
382 // (entry + traced .next output + its own node_modules) — ship as-is.
383 bundle: false,
384 runtime: fnProps?.runtime ?? "nodejs24.x",
385 architecture: fnProps?.architecture,
386 memorySize: fnProps?.memorySize ?? 1024,
387 timeout: props.timeout ?? Duration.seconds(30),
388 env: {
389 // The env names OpenNext's s3/sqs/dynamodb overrides read. Regions
390 // are omitted: the SDK falls back to the Lambda runtime's own
391 // AWS_REGION, and every resource here is same-region.
392 CACHE_BUCKET_NAME: cacheBucket.bucketName,
393 CACHE_BUCKET_KEY_PREFIX: NEXTJS_CACHE_PREFIX,
394 REVALIDATION_QUEUE_URL: revalidationQueue.queueUrl,
395 CACHE_DYNAMO_TABLE: tagCacheTable.tableName,
396 ...props.env,
397 },
398 functionUrl: {
399 authType: "NONE",
400 // The default server is built with the aws-lambda-streaming
401 // wrapper (the framework module enforces it).
402 invokeMode: "RESPONSE_STREAM",
403 },
404 });
405
406 yield* server.bind`Allow(${server}, AWS.Website.Nextjs.Cache(${cacheBucket}))`({
407 policyStatements: [
408 {
409 Effect: "Allow",
410 Action: ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"],
411 Resource: [Output.interpolate`${cacheBucket.bucketArn}/*` as any],
412 },
413 {
414 Effect: "Allow",
415 Action: ["s3:ListBucket"],
416 Resource: [cacheBucket.bucketArn as any],
417 },
418 {
419 Effect: "Allow",
420 Action: ["sqs:SendMessage"],
421 Resource: [revalidationQueue.queueArn as any],
422 },
423 {
424 Effect: "Allow",
425 Action: [
426 "dynamodb:GetItem",
427 "dynamodb:PutItem",
428 "dynamodb:DeleteItem",
429 "dynamodb:Query",
430 "dynamodb:Scan",
431 "dynamodb:BatchGetItem",
432 "dynamodb:BatchWriteItem",
433 "dynamodb:UpdateItem",
434 ],
435 Resource: [
436 tagCacheTable.tableArn as any,
437 Output.interpolate`${tagCacheTable.tableArn}/index/*` as any,
438 ],
439 },
440 ] satisfies PolicyStatement[],
441 });
442
443 // ISR revalidation consumer: drains the FIFO queue and HEAD-requests
444 // stale pages with the prerender revalidate header.
445 const revalidationFunction = yield* LambdaFunction("Revalidation", {
446 main: fromDist("revalidation-function/index.mjs"),
447 handler: "handler",
448 isExternal: true,
449 bundle: false,
450 runtime: "nodejs24.x",
451 memorySize: 512,
452 timeout: Duration.seconds(30),
453 functionUrl: false,
454 });
455
456 yield* revalidationFunction.bind`Allow(${revalidationFunction}, AWS.SQS.Consume(${revalidationQueue}))`(
457 {
458 policyStatements: [
459 {
460 Effect: "Allow",
461 Action: [
462 "sqs:ReceiveMessage",
463 "sqs:DeleteMessage",
464 "sqs:GetQueueAttributes",
465 "sqs:GetQueueUrl",
466 "sqs:ChangeMessageVisibility",
467 ],
468 Resource: [revalidationQueue.queueArn as any],
469 },
470 ] satisfies PolicyStatement[],
471 },
472 );
473
474 yield* EventSourceMapping("RevalidationEventSource", {
475 functionName: revalidationFunction.functionName,
476 eventSourceArn: revalidationQueue.queueArn,
477 batchSize: 5,
478 });
479
480 // Image optimization: OpenNext installs sharp's linux-arm64 binaries
481 // into the bundle, so the function architecture is always arm64. Its
482 // s3 image loader reads originals from the asset bucket.
483 const imageFunction = yield* LambdaFunction("ImageOptimization", {
484 main: fromDist("image-optimization-function/index.mjs"),
485 handler: "handler",
486 isExternal: true,
487 bundle: false,
488 runtime: "nodejs24.x",
489 architecture: "arm64",
490 memorySize: fnProps?.imageOptimization?.memorySize ?? 1536,
491 timeout: Duration.seconds(25),
492 env: {
493 BUCKET_NAME: bucket.bucketName,
494 },
495 functionUrl: {
496 authType: "NONE",
497 // The image optimizer is buffered (streaming: false in the
498 // OpenNext output manifest).
499 invokeMode: "BUFFERED",
500 },
501 });
502
503 yield* imageFunction.bind`Allow(${imageFunction}, AWS.S3.GetObject(${bucket}))`({
504 policyStatements: [
505 {
506 Effect: "Allow",
507 Action: ["s3:GetObject"],
508 Resource: [Output.interpolate`${bucket.bucketArn}/*` as any],
509 },
510 ] satisfies PolicyStatement[],
511 });
512
513 const urlHost = (url: string | undefined) => {
514 if (!url) {
515 throw new Error("A Next.js Lambda function did not produce a Function URL.");
516 }
517 return new URL(url).hostname;
518 };
519 const serverHost = Output.map(urlHost)(server.functionUrl as any) as Input<string>;
520 const imageHost = Output.map(urlHost)(imageFunction.functionUrl as any) as Input<string>;
521
522 const siteProps: StaticSiteProps = {
523 path: build.clientDir as unknown as string,
524 assets: props.assets,
525 domain: props.domain,
526 cloudfrontUrl: props.cloudfrontUrl,
527 edge: props.edge,
528 bucketName: props.bucketName,
529 forceDestroy: props.forceDestroy,
530 invalidation: props.invalidation,
531 tags: props.tags,
532 };
533
534 const site = yield* makeKvSite(id, siteProps, {
535 serverHost,
536 image: { route: "/_next/image", host: imageHost },
537 });
538
539 // Seed the ISR/fetch cache: `.open-next/cache/<buildId>/...` uploaded
540 // under `_cache/` (matching CACHE_BUCKET_KEY_PREFIX). Old builds' seeds
541 // are left in place so a rolling deploy never breaks in-flight ISR.
542 const cacheFiles = yield* AssetDeployment("CacheFiles", {
543 bucket: cacheBucket,
544 sourcePath: fromDist("cache") as unknown as string,
545 prefix: NEXTJS_CACHE_PREFIX,
546 purge: false,
547 });
548
549 return {
550 ...site,
551 build,
552 cacheBucket,
553 cacheFiles,
554 imageFunction,
555 imageUrl: imageFunction.functionUrl,
556 revalidationFunction,
557 revalidationQueue,
558 server,
559 serverUrl: server.functionUrl,
560 tagCacheTable,
561 };
562 },
563 (effect, id: string, _props?: NextjsProps) => effect.pipe(Namespace.push(id)),
564 );