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

main
ts 361 lines 14.2 KB
Raw
1 import { DEFAULT_COMPATIBILITY_DATE } from "@alchemy.run/cloudflare-runtime/core/internal/constants";
2 import type { MemoOptions } from "alchemy/Command/Memo";
3 import type { InputProps } from "alchemy/Input";
4 import { effectClass } from "alchemy/Util/effect";
5 import * as Effect from "effect/Effect";
6 import type { Namespace } from "../KV/Namespace.ts";
7 import type { Providers } from "../Providers.ts";
8 import type { AssetsConfig } from "../Workers/Assets.ts";
9 import { DurableObject } from "../Workers/DurableObject.ts";
10 import {
11 Self,
12 Worker,
13 type NormalizedBindings,
14 type WorkerAssetsConfig,
15 type WorkerBindingProps,
16 type WorkerProps,
17 } from "../Workers/Worker.ts";
18
19 /**
20 * The module specifier of the Next.js source provider. Loaded with a
21 * dynamic `import()`, so `@alchemy.run/frontend-frameworks` must be installed
22 * in the deploying project. The provider is exposed through its `/nextjs`
23 * subpath.
24 */
25 const NEXTJS_SOURCE_PROVIDER = "@alchemy.run/frontend-frameworks/nextjs/source";
26
27 export interface NextjsProps<Bindings extends WorkerBindingProps = {}> extends Omit<
28 WorkerProps<Bindings>,
29 "vite" | "main" | "assets" | "script" | "bundle" | "source" | "rules" | "dev"
30 > {
31 /**
32 * The Next.js project root. Defaults to the process working directory.
33 */
34 rootDir?: string;
35 /**
36 * Controls which files are content-hashed to decide whether the OpenNext
37 * build needs to re-run. By default every project file outside build
38 * outputs (`.next`, `.open-next`, `dist`) and `node_modules` is hashed,
39 * plus the nearest package-manager lockfile. Narrow the scope with
40 * `include`/`exclude` globs when the default is too broad.
41 * `open-next.config.ts` itself is always hashed. When narrowing `include`,
42 * also include any helpers imported by that config.
43 */
44 memo?: MemoOptions;
45 /**
46 * Binds KV caches and the same-worker Durable Object revalidation queue.
47 * Without `open-next.config.ts`, Alchemy selects matching KV adapters;
48 * omitting `isr` instead selects the read-only static-assets cache.
49 * A native config controls adapter selection and must choose adapters
50 * matching these bindings. KV fills on demand; build-time cache entries
51 * are not uploaded to KV.
52 */
53 isr?: {
54 /** KV namespace storing rendered pages and fetch results. */
55 incrementalCache: Namespace;
56 /** KV namespace storing cache-tag invalidations. */
57 tagCache: Namespace;
58 };
59 /** Build controls, separate from the optional native `open-next.config.ts`. */
60 openNext?: {
61 /**
62 * Overrides the native config's `buildCommand` when set. If neither sets
63 * a command, defaults to `npx next build`.
64 */
65 buildCommand?: string;
66 /** Minify the generated Worker. Defaults to false. */
67 minify?: boolean;
68 /** Enable OpenNext build diagnostics. Defaults to false. */
69 debug?: boolean;
70 };
71 /**
72 * Local dev (`alchemy dev`) behavior.
73 */
74 dev?: {
75 /**
76 * - `"preview"` (default): build the OpenNext worker and serve it
77 * under workerd — production parity (workerd APIs, ISR/cache
78 * semantics), no HMR.
79 * - `"hmr"`: run the real `next dev` (Turbopack HMR) in Node with the
80 * Worker's bindings proxied onto OpenNext's `getCloudflareContext()`
81 * contract. App code runs in Node, not workerd — CF-specific
82 * runtime behavior still needs `"preview"`.
83 * @default "preview"
84 */
85 mode?: "preview" | "hmr";
86 /**
87 * Port for the local dev server. `0` picks an ephemeral port.
88 */
89 port?: number;
90 };
91 /**
92 * Optional configuration for static asset routing behavior.
93 * Defaults to `runWorkerFirst: true` with `htmlHandling`/`notFoundHandling`
94 * set to `"none"` — the OpenNext server owns routing and delegates to the
95 * `ASSETS` binding itself.
96 */
97 assets?: AssetsConfig;
98 }
99
100 // These options are inspected while constructing the Worker. Resolve them in
101 // the outer props Effect; pass-through properties can remain deferred Inputs.
102 type NextjsInput<Bindings extends WorkerBindingProps> = InputProps<
103 NextjsProps<Bindings>,
104 "dev" | "isr" | "env" | "compatibility" | "assets" | "openNext"
105 >;
106
107 /**
108 * A Cloudflare Worker deployed from a Next.js project.
109 *
110 * `Nextjs` builds the app with the wrangler-free OpenNext pipeline from
111 * [`@alchemy.run/frontend-frameworks/nextjs`](https://github.com/alchemy-run/alchemy/tree/main/packages/frontend-frameworks/src/nextjs):
112 * `next build` runs through `@opennextjs/cloudflare`, the resulting worker
113 * is bundled into a self-contained ES module set, and the static assets
114 * (including prerendered pages and the read-only incremental cache) deploy
115 * as Workers static assets. Input files are content-hashed so unchanged
116 * projects skip the build and deploy entirely.
117 *
118 * Both `@alchemy.run/frontend-frameworks` and its peer
119 * `@opennextjs/cloudflare` must be installed in the deploying project. The
120 * source provider is loaded from the package's `/nextjs` export with a dynamic
121 * `import()`.
122 *
123 * Local dev (`alchemy dev`) defaults to preview parity — the built worker
124 * served under workerd. Set `dev: { mode: "hmr" }` for the real `next dev`
125 * (Turbopack HMR) with the Worker's bindings proxied onto
126 * `getCloudflareContext()`.
127 *
128 * If `open-next.config.ts` exists in the project root, Alchemy loads it through
129 * OpenNext's native compiler without rewriting it. Otherwise, Alchemy generates
130 * temporary defaults: a read-only static-assets cache, or KV adapters when
131 * `isr` is set. Static-assets revalidation writes are a no-op.
132 * Native Next.js and Tailwind configuration files are left unchanged.
133 *
134 * Known limitations (upstream `@opennextjs/cloudflare`):
135 * - Edge-runtime routes/pages (`export const runtime = "edge"`) are not
136 * supported — the build fails with the offending route list; remove the
137 * directive (the node runtime runs on Workers). Middleware is fine.
138 * - `next/image` optimization requires a zone with Cloudflare Images;
139 * on `workers.dev`, use `unoptimized` (images serve as raw assets).
140 * - Partial Prerendering / `"use cache"` (`cacheComponents`) and
141 * Pages-Router `i18n` config are untested/out of scope for now. App
142 * Router i18n via middleware works (middleware is fully supported).
143 *
144 *
145 * ### Deploying a Next.js App
146 * A single call builds the app and deploys the Worker plus static assets.
147 * No `open-next.config.ts`, Wrangler config, or Alchemy plugin is required.
148 *
149 * **Example:** Basic Next.js site
150 * ```typescript
151 * const site = yield* Cloudflare.Website.Nextjs("Site");
152 * ```
153 *
154 * **Example:** Explicit project root
155 * ```typescript
156 * const site = yield* Cloudflare.Website.Nextjs("Site", {
157 * rootDir: "./apps/web",
158 * });
159 * ```
160 *
161 * ### Optional Native OpenNext Configuration
162 * The same `Cloudflare.Website.Nextjs("Site")` call works with or without a
163 * config file. To customize OpenNext, add `open-next.config.ts` under `rootDir`
164 * (the working directory by default). Imports and callbacks are preserved;
165 * the native `OpenNextConfig` is passed to OpenNext's compiler, subject to
166 * Cloudflare's adapter constraints rather than AWS runtime feature parity.
167 *
168 * **Example:** Native config with the read-only static-assets cache
169 * ```typescript
170 * // open-next.config.ts
171 * import { defineCloudflareConfig, type OpenNextConfig } from "@opennextjs/cloudflare";
172 * import staticAssetsIncrementalCache from "@opennextjs/cloudflare/overrides/incremental-cache/static-assets-incremental-cache";
173 *
174 * export default {
175 * ...defineCloudflareConfig({ incrementalCache: staticAssetsIncrementalCache }),
176 * buildCommand: "pnpm exec next build",
177 * } satisfies OpenNextConfig;
178 * ```
179 *
180 * ### Bindings
181 * Resources passed via `env` become Worker bindings, readable in route
182 * handlers and server components through OpenNext's
183 * `getCloudflareContext()`.
184 *
185 * **Example:** Binding an R2 bucket
186 * ```typescript
187 * const bucket = yield* Cloudflare.R2.Bucket("Uploads");
188 * const site = yield* Cloudflare.Website.Nextjs("Site", {
189 * env: {
190 * UPLOADS: bucket,
191 * },
192 * });
193 * ```
194 *
195 * ```typescript
196 * // app/api/upload/route.ts
197 * import { getCloudflareContext } from "@opennextjs/cloudflare";
198 *
199 * export async function PUT(request: Request) {
200 * const { env } = getCloudflareContext();
201 * await env.UPLOADS.put("key", await request.text());
202 * return Response.json({ ok: true });
203 * }
204 * ```
205 *
206 * ### Writable ISR
207 * Supply the cache namespaces on the resource. Alchemy binds them and adds
208 * the Durable Object queue for background regeneration. Without a native
209 * config, it also selects the matching adapters. With a native config, select
210 * `kv-incremental-cache`, `kv-next-tag-cache`, and `do-queue` there; `isr`
211 * does not override the file's adapter choices.
212 *
213 * **Example:** Binding the writable-ISR resources
214 * ```typescript
215 * const incCache = yield* Cloudflare.KV.Namespace("NextIncCache");
216 * const tagCache = yield* Cloudflare.KV.Namespace("NextTagCache");
217 *
218 * const site = yield* Cloudflare.Website.Nextjs("Site", {
219 * isr: { incrementalCache: incCache, tagCache },
220 * });
221 * ```
222 *
223 * ### Custom Rebuild Scope
224 * By default, every project file outside build outputs is hashed to decide
225 * whether a rebuild is needed. Use `memo` to narrow the scope when the
226 * project has large directories that don't affect the build output.
227 * `open-next.config.ts` itself is always hashed. Include any imported config
228 * helpers in a narrowed `memo.include` too (for example, `config/**`).
229 *
230 * **Example:** Narrowing the memo scope
231 * ```typescript
232 * const site = yield* Cloudflare.Website.Nextjs("Site", {
233 * memo: {
234 * include: ["app/**", "public/**", "package.json", "next.config.mjs", "config/**"],
235 * },
236 * });
237 * ```
238 *
239 * ### Build Configuration
240 * An explicit `openNext.buildCommand` overrides the native config's command.
241 * `openNext.minify` and `openNext.debug` remain resource-level build controls.
242 *
243 * **Example:** Customize the build
244 * ```typescript
245 * const site = yield* Cloudflare.Website.Nextjs("Site", {
246 * openNext: { buildCommand: "pnpm exec next build", minify: true },
247 * });
248 * ```
249 *
250 * ### Class Form
251 * Calling `Nextjs` with no arguments returns a constructor you can
252 * `extend` to declare the Worker as a named class. The class is both an
253 * `Effect` you can `yield*` to deploy and a type you can reference
254 * elsewhere — useful when other resources need to bind to this Worker.
255 *
256 * **Example:** Declaring a Worker class
257 * ```typescript
258 * class Site extends Cloudflare.Website.Nextjs<Site>()("Site", {
259 * rootDir: "./apps/web",
260 * }) {}
261 *
262 * const site = yield* Site;
263 * ```
264 *
265 * @resource
266 * @product Website
267 * @category Workers & Compute
268 */
269 export const Nextjs: {
270 <Self>(): {
271 <const Bindings extends WorkerBindingProps = {}, Req = never>(
272 id: string,
273 propsEff?: NextjsInput<Bindings> | Effect.Effect<NextjsInput<Bindings>, never, Req>,
274 ): Effect.Effect<Self, never, Req | Providers> & {
275 new (): Worker<{
276 [binding in keyof NormalizedBindings<Bindings, WorkerAssetsConfig>]: NormalizedBindings<
277 Bindings,
278 WorkerAssetsConfig
279 >[binding];
280 }>;
281 };
282 };
283 <const Bindings extends WorkerBindingProps = {}, Req = never>(
284 id: string,
285 propsEff?: NextjsInput<Bindings> | Effect.Effect<NextjsInput<Bindings>, never, Req>,
286 ): Effect.Effect<
287 Worker<{
288 [binding in keyof NormalizedBindings<Bindings, WorkerAssetsConfig>]: NormalizedBindings<
289 Bindings,
290 WorkerAssetsConfig
291 >[binding];
292 }>,
293 never,
294 Req | Providers
295 >;
296 } = (<const Bindings extends WorkerBindingProps = {}, Req = never>(
297 id?: string,
298 propsEff?: NextjsInput<Bindings> | Effect.Effect<NextjsInput<Bindings>, never, Req>,
299 ) =>
300 id === undefined
301 ? <const Bindings extends WorkerBindingProps = {}, Req = never>(
302 id: string,
303 propsEff?: NextjsInput<Bindings> | Effect.Effect<NextjsInput<Bindings>, never, Req>,
304 ) => effectClass(Nextjs(id, propsEff))
305 : Worker(
306 id,
307 Effect.map(Effect.isEffect(propsEff) ? propsEff : Effect.succeed(propsEff), (props) => ({
308 ...props,
309 // `dev.mode` is the integration's dev behavior (routed through
310 // the source options below); only `port` maps onto the Worker's
311 // own local-dev config.
312 dev: props?.dev?.port !== undefined ? { port: props.dev.port } : undefined,
313 // OpenNext's revalidation queues (memory-queue, do-queue) fetch
314 // the worker back through `WORKER_SELF_REFERENCE`. Always wire
315 // the self service binding — it's inert when unused, and its
316 // absence turns ISR revalidation into a silent no-op. An
317 // explicit user-provided `env.WORKER_SELF_REFERENCE` wins.
318 env: {
319 WORKER_SELF_REFERENCE: Self,
320 ...props?.env,
321 ...(props?.isr
322 ? {
323 NEXT_INC_CACHE_KV: props.isr.incrementalCache,
324 NEXT_TAG_CACHE_KV: props.isr.tagCache,
325 NEXT_CACHE_DO_QUEUE: DurableObject("NEXT_CACHE_DO_QUEUE", {
326 className: "DOQueueHandler",
327 }),
328 }
329 : {}),
330 },
331 // OpenNext requires Node.js APIs. The 2026-08-31 default date
332 // enables both nodejs_compat modes, so no redundant flag is sent.
333 compatibility: {
334 date: props?.compatibility?.date ?? DEFAULT_COMPATIBILITY_DATE,
335 flags: props?.compatibility?.flags,
336 },
337 // The OpenNext server owns routing: run the worker first and
338 // leave asset-path rewriting off. Users can still override.
339 assets: {
340 runWorkerFirst: true,
341 htmlHandling: "none" as const,
342 notFoundHandling: "none" as const,
343 ...props?.assets,
344 },
345 source: {
346 provider: NEXTJS_SOURCE_PROVIDER,
347 devMode: "server",
348 rootDir: props?.rootDir,
349 // `next dev` (Turbopack) cold-starts broken under bun (every
350 // route 404s until `.next` is warm) — pin the dev child to node.
351 runtime: "node",
352 options: {
353 root: props?.rootDir,
354 memo: props?.memo,
355 cache: props?.isr ? "kv" : "static-assets",
356 ...props?.openNext,
357 ...(props?.dev?.mode !== undefined ? { dev: { mode: props.dev.mode } } : {}),
358 },
359 },
360 })),
361 )) as any;