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

main
ts 743 lines 28.3 KB
Raw
1 import * as NodeCrypto from "node:crypto";
2 import { createRequire } from "node:module";
3 /**
4 * The alchemy Worker source-provider entry for Next.js
5 * (`@alchemy.run/frontend-frameworks/nextjs/source`).
6 *
7 * The default export implements alchemy's `WorkerSourceModule` contract
8 * (`packages/cloudflare/src/Workers/Source.ts`) **structurally** —
9 * this package deliberately does not import alchemy types. The shapes
10 * mirrored here are:
11 *
12 * - `WorkerSourceModule` — `{ make(options) => Effect<SourceProvider> }`
13 * - `SourceProvider` — `{ ownsAssets, build(ctx), hash(ctx, previous), dev(ctx) }`
14 * - `SourceBuildOutput` — `{ bundle: { files, hash }, assets: AssetReadResult, hash }`
15 * - `AssetReadResult` — the manifest shape alchemy's asset uploader consumes
16 * (per-file hash = sha256 hex truncated to 32 chars, the Workers Assets
17 * API's content-address format)
18 *
19 * `build()` wraps this package's `Framework` service (the OpenNext-based,
20 * wrangler-free pipeline in `Nextjs.ts`): server modules become the worker
21 * bundle (entry first), `.open-next/assets` becomes the static-assets
22 * manifest, and the project tree is content-hashed for rebuild-free diffs.
23 * `hash()` never builds — it recomputes the input-tree hash (including this
24 * package's version, so an adapter upgrade busts the memo). `dev()` is v1
25 * preview parity: the built worker served under cloudflare-runtime (workerd);
26 * ISR revalidation writes are a documented no-op (read-only static-assets
27 * incremental cache).
28 */
29 import type { BindingHooks, RuntimeWorker } from "@alchemy.run/cloudflare-runtime/core";
30 import * as Data from "effect/Data";
31 import * as Effect from "effect/Effect";
32 import * as FileSystem from "effect/FileSystem";
33 import * as Path from "effect/Path";
34 import type { PlatformError } from "effect/PlatformError";
35 import type * as Scope from "effect/Scope";
36 import { resolveBuildEnv, runBuildChild } from "../core/BuildChild.ts";
37 import * as FrameworkCore from "../core/index.ts";
38 import * as Nextjs from "./Nextjs.ts";
39 import * as Runner from "./Runner.ts";
40
41 const packageVersion: string = createRequire(import.meta.url)("../../package.json").version;
42
43 const PROVIDER = "@alchemy.run/frontend-frameworks/nextjs/source";
44
45 // ─────────────────────────────────────────────────────────────────────
46 // Structural mirrors of alchemy's Source.ts contract
47 // ─────────────────────────────────────────────────────────────────────
48
49 /**
50 * Structural mirror of alchemy's `Cloudflare.Workers.SourceProviderError`
51 * (same `_tag`, so alchemy-side `Effect.catchTag` handles it as its own).
52 */
53 export class SourceProviderError extends Data.TaggedError(
54 "Cloudflare.Workers.SourceProviderError",
55 )<{
56 readonly provider: string;
57 readonly message: string;
58 readonly cause?: unknown;
59 }> {}
60
61 /** Mirror of alchemy's `SourceHash` (the Worker `hash` attribute slots). */
62 export interface SourceHash {
63 readonly bundle: string | undefined;
64 readonly assets: string | undefined;
65 readonly input: string | undefined;
66 readonly additionalWorkspaces: Array<string> | undefined;
67 }
68
69 /** Mirror of alchemy's `Bundle.BundleFile`. */
70 export interface SourceBundleFile {
71 readonly path: string;
72 readonly content: string | Uint8Array;
73 readonly hash: string;
74 }
75
76 /** Mirror of alchemy's `AssetReadResult` (Workers Assets manifest shape). */
77 export interface SourceAssets {
78 directory: string;
79 config: Record<string, unknown> | undefined;
80 manifest: Record<string, { hash: string; size: number }>;
81 _headers: string | undefined;
82 _redirects: string | undefined;
83 hash: string;
84 }
85
86 /** Mirror of alchemy's `SourceBuildOutput`. */
87 export interface SourceBuildOutput {
88 readonly bundle: { readonly files: Array<SourceBundleFile>; readonly hash: string } | undefined;
89 readonly assets: SourceAssets | undefined;
90 readonly hash: SourceHash;
91 }
92
93 /** The subset of alchemy's `SourceContext` this provider consumes. */
94 export interface SourceContext {
95 readonly dotAlchemy?: string;
96 readonly id: string;
97 readonly workerName: string;
98 readonly compatibility: {
99 readonly date: string;
100 readonly flags: Array<string>;
101 };
102 readonly env?: Record<string, unknown> | undefined;
103 readonly assets?: string | Record<string, unknown> | undefined;
104 }
105
106 type WorkerWiring = Omit<
107 RuntimeWorker<BindingHooks>,
108 "compatibilityDate" | "compatibilityFlags" | "modules"
109 >;
110
111 /** The subset of alchemy's `DevContext` this provider consumes. */
112 export interface DevContext extends SourceContext {
113 readonly worker: {
114 readonly bindings: NonNullable<WorkerWiring["bindings"]>;
115 readonly durableObjectNamespaces: NonNullable<WorkerWiring["durableObjectNamespaces"]>;
116 readonly hyperdrives: NonNullable<WorkerWiring["hyperdrives"]>;
117 readonly queueConsumers: Effect.Effect<NonNullable<WorkerWiring["queueConsumers"]>>;
118 readonly assets: WorkerWiring["assets"] | undefined;
119 /**
120 * The Worker's other runtime settings (crons, Workflows, tail consumers,
121 * Cache API, `request.cf`, zone, Access), spread whole into the runtime
122 * Worker.
123 */
124 readonly options: Pick<
125 RuntimeWorker,
126 "workflows" | "crons" | "tails" | "streamingTails" | "cache" | "cf" | "zone" | "access"
127 >;
128 };
129 /**
130 * The host's runtime stack (a `Context.Context<RuntimeServices>`) — the
131 * dev binding proxy is hosted in it instead of the credential-free
132 * internal layer, so `Alchemy.remote()` bindings resolve in dev.
133 */
134 readonly runtimeContext: unknown;
135 }
136
137 export type SourceDevHandle = {
138 readonly mode: "server";
139 readonly url: URL;
140 readonly serviceBinding?: "http";
141 };
142
143 export type SourceError = SourceProviderError | PlatformError;
144
145 export type SourceServices = FileSystem.FileSystem | Path.Path;
146
147 /** Mirror of alchemy's `SourceProvider` (the arms this module implements). */
148 export interface SourceProvider {
149 readonly ownsAssets: boolean;
150 readonly build: (
151 ctx: SourceContext,
152 ) => Effect.Effect<SourceBuildOutput, SourceError, SourceServices>;
153 readonly hash: (
154 ctx: SourceContext,
155 previous: SourceHash | undefined,
156 ) => Effect.Effect<Partial<SourceHash>, SourceError, SourceServices>;
157 readonly dev: (
158 ctx: DevContext,
159 ) => Effect.Effect<SourceDevHandle, SourceError, SourceServices | Scope.Scope>;
160 }
161
162 // ─────────────────────────────────────────────────────────────────────
163 // Options
164 // ─────────────────────────────────────────────────────────────────────
165
166 /**
167 * Controls which project files are content-hashed to decide whether the
168 * OpenNext build needs to re-run. Mirrors the semantics of alchemy's
169 * `MemoOptions` (`Command/Memo.ts`) with a built-in glob matcher:
170 * `**` crosses directory boundaries, `*`/`?` stay within a segment.
171 */
172 export interface NextjsMemoOptions {
173 /** Glob patterns of files to hash, relative to the project root. @default all files */
174 readonly include?: Array<string> | undefined;
175 /** Glob patterns to exclude from hashing. Build outputs (`.next`, `.open-next`, `dist`) and `node_modules` are always excluded. */
176 readonly exclude?: Array<string> | undefined;
177 /**
178 * Include the nearest package-manager lockfile in the hash, even when it
179 * lives above the project root (e.g. a monorepo root).
180 * @default true when both `include` and `exclude` are unset; false otherwise
181 */
182 readonly lockfile?: boolean | undefined;
183 }
184
185 /**
186 * The JSON-serializable options of the `@alchemy.run/frontend-frameworks/nextjs/source`
187 * descriptor (`WorkerProps.source.options`). Must stay JSON-stable — the
188 * descriptor persists in state and participates in the Worker metadata hash.
189 */
190 export interface NextjsSourceOptions {
191 /** The Next.js project root. Defaults to the process working directory. */
192 readonly root?: string | undefined;
193 /** Rebuild-scope configuration (which files bust the build memo). */
194 readonly memo?: NextjsMemoOptions | undefined;
195 /** Optional explicit config; otherwise discover `open-next.config.ts`, falling back to generated defaults. */
196 readonly configPath?: string | undefined;
197 /** Resource-selected cache adapters. Defaults to the read-only static-assets cache. */
198 readonly cache?: "static-assets" | "kv" | undefined;
199 /**
200 * The command the OpenNext pipeline runs to build the Next.js app.
201 * Takes precedence over an explicitly supplied OpenNext config.
202 * @default "npx next build"
203 */
204 readonly buildCommand?: string | undefined;
205 /** Skip the internal `next build` (reuse an existing `.next`). */
206 readonly skipNextBuild?: boolean | undefined;
207 /** Minify the OpenNext bundling steps and the final bundle pass. */
208 readonly minify?: boolean | undefined;
209 /** Enable OpenNext debug logging (and verbose workerd output in dev). */
210 readonly debug?: boolean | undefined;
211 /** Dev-server behavior (JSON-stable; does not affect the build). */
212 readonly dev?:
213 | {
214 /**
215 * - `"preview"` (default): build the OpenNext worker and serve it
216 * under `cloudflare-runtime` (workerd) — production parity, no HMR.
217 * - `"hmr"`: run the real `next dev` (Turbopack HMR) in Node with the
218 * worker's bindings proxied from `cloudflare-runtime` onto
219 * OpenNext's `getCloudflareContext()` contract. App code runs in
220 * Node, not workerd — CF-specific runtime behavior and ISR/caching
221 * semantics still need `"preview"`.
222 * @default "preview"
223 */
224 readonly mode?: "preview" | "hmr" | undefined;
225 }
226 | undefined;
227 }
228
229 // ─────────────────────────────────────────────────────────────────────
230 // Hashing helpers (mirroring alchemy's Memo.ts / Assets.ts semantics)
231 // ─────────────────────────────────────────────────────────────────────
232
233 const sha256Hex = (input: string | Uint8Array): Effect.Effect<string> =>
234 Effect.sync(() => NodeCrypto.createHash("sha256").update(input).digest("hex"));
235
236 /** JSON.stringify with recursively sorted object keys (stable across runs). */
237 const stableStringify = (value: unknown): string => {
238 const stable = (v: unknown): unknown => {
239 if (Array.isArray(v)) return v.map(stable);
240 if (v !== null && typeof v === "object") {
241 return Object.fromEntries(
242 Object.entries(v as Record<string, unknown>)
243 .filter(([, entry]) => entry !== undefined)
244 .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
245 .map(([k, entry]) => [k, stable(entry)]),
246 );
247 }
248 return v;
249 };
250 return JSON.stringify(stable(value ?? null));
251 };
252
253 /**
254 * Compile a glob to a RegExp: `**` crosses `/` boundaries, `*` and `?` stay
255 * within a path segment. Enough for memo scoping (`app/**`, `package.json`);
256 * not a full gitignore engine.
257 */
258 const globToRegExp = (glob: string): RegExp => {
259 let out = "";
260 for (let i = 0; i < glob.length; i++) {
261 const ch = glob[i]!;
262 if (ch === "*") {
263 if (glob[i + 1] === "*") {
264 // `**/` also matches zero directories.
265 if (glob[i + 2] === "/") {
266 out += "(?:.*/)?";
267 i += 2;
268 } else {
269 out += ".*";
270 i += 1;
271 }
272 } else {
273 out += "[^/]*";
274 }
275 } else if (ch === "?") {
276 out += "[^/]";
277 } else if ("\\^$.|+()[]{}".includes(ch)) {
278 out += `\\${ch}`;
279 } else {
280 out += ch;
281 }
282 }
283 return new RegExp(`^${out}$`);
284 };
285
286 /**
287 * Directories that are never inputs: VCS metadata and this integration's own
288 * build outputs. Pruning them is load-bearing — `build()` writes `.next`,
289 * `.open-next`, and `dist` into the project root, so hashing them would make
290 * every deploy dirty its own memo.
291 */
292 const ALWAYS_PRUNED = new Set([
293 "node_modules",
294 ".git",
295 ".next",
296 ".open-next",
297 "dist",
298 ".turbo",
299 ".vercel",
300 ".alchemy",
301 ".wrangler",
302 ]);
303
304 const ALWAYS_IGNORED_FILES = new Set([".DS_Store"]);
305
306 /** Recursively list files under `root` (relative, `/`-separated), pruning `prune`d directories. */
307 const listProjectFiles = Effect.fn(function* (
308 root: string,
309 prune: ReadonlySet<string>,
310 dotAlchemy?: string,
311 ) {
312 const fs = yield* FileSystem.FileSystem;
313 const path = yield* Path.Path;
314 const runtimeDirectory =
315 dotAlchemy === undefined ? undefined : path.resolve(process.cwd(), dotAlchemy);
316 const out: Array<string> = [];
317 const walk = (relative: string): Effect.Effect<void, PlatformError, never> =>
318 Effect.gen(function* () {
319 const absolute = relative === "" ? root : path.join(root, relative);
320 const entries = yield* fs.readDirectory(absolute);
321 for (const entry of entries) {
322 const rel = relative === "" ? entry : `${relative}/${entry}`;
323 if (runtimeDirectory !== undefined) {
324 const runtimeRelative = path.relative(runtimeDirectory, path.join(root, rel));
325 if (
326 runtimeRelative === "" ||
327 (!path.isAbsolute(runtimeRelative) &&
328 runtimeRelative !== ".." &&
329 !runtimeRelative.startsWith(`..${path.sep}`))
330 )
331 continue;
332 }
333 const info = yield* fs.stat(path.join(root, rel));
334 if (info.type === "Directory") {
335 if (!prune.has(entry)) {
336 yield* walk(rel);
337 }
338 } else if (info.type === "File" && !ALWAYS_IGNORED_FILES.has(entry)) {
339 out.push(rel);
340 }
341 }
342 });
343 yield* walk("");
344 return out.sort();
345 });
346
347 const findUp = Effect.fn(function* (start: string, filenames: Array<string>) {
348 const fs = yield* FileSystem.FileSystem;
349 const path = yield* Path.Path;
350 let dir = start;
351 for (;;) {
352 for (const filename of filenames) {
353 const candidate = path.join(dir, filename);
354 if (yield* fs.exists(candidate).pipe(Effect.orElseSucceed(() => false))) {
355 return candidate;
356 }
357 }
358 const parent = path.dirname(dir);
359 if (parent === dir) return undefined;
360 dir = parent;
361 }
362 });
363
364 /**
365 * Content-hash the project's input tree. Deterministic for an unchanged tree
366 * and machine-independent for identical bytes: only root-relative paths are
367 * hashed, never absolute ones. The material additionally covers this
368 * package's version and the build-affecting options, so an adapter upgrade
369 * or an options change busts the memo without any file edit.
370 */
371 const hashInputTree = Effect.fn(function* (
372 root: string,
373 options: NextjsSourceOptions,
374 dotAlchemy?: string,
375 ) {
376 const fs = yield* FileSystem.FileSystem;
377 const memo = options.memo ?? {};
378 const include = (memo.include ?? ["**/*"]).map(globToRegExp);
379 const exclude = (memo.exclude ?? []).map(globToRegExp);
380 const files = (yield* listProjectFiles(root, ALWAYS_PRUNED, dotAlchemy)).filter(
381 (file) => include.some((re) => re.test(file)) && !exclude.some((re) => re.test(file)),
382 );
383 const path = yield* Path.Path;
384 const entries = yield* Effect.forEach(
385 files,
386 (file) =>
387 fs.readFile(path.join(root, file)).pipe(
388 Effect.flatMap(sha256Hex),
389 Effect.map((hash) => `${file}:${hash}`),
390 ),
391 { concurrency: 16 },
392 );
393 // Mirror alchemy's Memo.ts default: the nearest lockfile participates
394 // only when the memo scope wasn't explicitly narrowed.
395 const includeLockfile = memo.lockfile ?? !(memo.include || memo.exclude);
396 let lockfileHash: string | undefined;
397 if (includeLockfile) {
398 const lockfile = yield* findUp(root, [
399 "bun.lock",
400 "bun.lockb",
401 "package-lock.json",
402 "pnpm-lock.yaml",
403 "yarn.lock",
404 ]);
405 if (lockfile !== undefined) {
406 lockfileHash = yield* fs.readFile(lockfile).pipe(Effect.flatMap(sha256Hex));
407 }
408 }
409 const configPath = yield* Runner.resolveConfigPath({
410 appDir: root,
411 configPath: options.configPath,
412 }).pipe(Effect.mapError(frameworkError));
413 const configHash =
414 configPath === undefined
415 ? undefined
416 : yield* fs.readFile(configPath).pipe(Effect.flatMap(sha256Hex));
417 return yield* sha256Hex(
418 stableStringify({
419 version: packageVersion,
420 config: {
421 path:
422 configPath === undefined
423 ? undefined
424 : path.relative(root, configPath).replaceAll("\\", "/"),
425 hash: configHash,
426 },
427 options: {
428 configPath: options.configPath,
429 cache: options.cache,
430 buildCommand: options.buildCommand,
431 skipNextBuild: options.skipNextBuild,
432 minify: options.minify,
433 },
434 files: entries,
435 lockfile: lockfileHash,
436 }),
437 );
438 });
439
440 // ─────────────────────────────────────────────────────────────────────
441 // Assets (mirror of alchemy's readAssets manifest semantics)
442 // ─────────────────────────────────────────────────────────────────────
443
444 const MAX_ASSET_SIZE = 1024 * 1024 * 25; // 25MB (Workers Assets limit)
445 const MAX_ASSET_COUNT = 20_000;
446
447 const maybeReadString = Effect.fn(function* (file: string) {
448 const fs = yield* FileSystem.FileSystem;
449 return yield* fs.readFileString(file).pipe(Effect.orElseSucceed(() => undefined));
450 });
451
452 /**
453 * Read the client directory into the Workers Assets manifest shape alchemy's
454 * uploader consumes: keys are `/`-prefixed paths, per-file hash is the sha256
455 * hex digest truncated to 32 chars (the API's content-address format), and
456 * the aggregate `hash` covers config + manifest + `_headers`/`_redirects`.
457 */
458 const readClientAssets = Effect.fn(function* (
459 directory: string,
460 config: Record<string, unknown> | undefined,
461 ) {
462 const fs = yield* FileSystem.FileSystem;
463 const path = yield* Path.Path;
464 const [files, _headers, _redirects] = yield* Effect.all([
465 // The client directory is a build product (`.open-next/assets`): every
466 // file in it is servable, so nothing is pruned (mirroring readAssets).
467 listProjectFiles(directory, new Set<string>()),
468 maybeReadString(path.join(directory, "_headers")),
469 maybeReadString(path.join(directory, "_redirects")),
470 ]);
471 const ignore = yield* maybeReadString(path.join(directory, ".assetsignore"));
472 const ignored = (ignore ?? "")
473 .split("\n")
474 .map((line) => line.trim())
475 .filter((line) => line.length > 0 && !line.startsWith("#"))
476 .map(globToRegExp);
477 const manifest: Record<string, { hash: string; size: number }> = {};
478 let count = 0;
479 yield* Effect.forEach(
480 files,
481 Effect.fn(function* (name) {
482 if (
483 name === ".assetsignore" ||
484 name === "_headers" ||
485 name === "_redirects" ||
486 ignored.some((re) => re.test(name))
487 ) {
488 return;
489 }
490 const file = path.join(directory, name);
491 const stat = yield* fs.stat(file);
492 const size = Number(stat.size);
493 if (size > MAX_ASSET_SIZE) {
494 return yield* new SourceProviderError({
495 provider: PROVIDER,
496 message: `Asset ${name} is too large (${(size / 1024 / 1024).toFixed(1)} MB; the Workers Assets limit is 25 MB)`,
497 });
498 }
499 count++;
500 if (count > MAX_ASSET_COUNT) {
501 return yield* new SourceProviderError({
502 provider: PROVIDER,
503 message: `Too many assets in ${directory} (the Workers Assets limit is ${MAX_ASSET_COUNT})`,
504 });
505 }
506 const hash = (yield* fs.readFile(file).pipe(Effect.flatMap(sha256Hex))).slice(0, 32);
507 manifest[`/${name}`] = { hash, size };
508 }),
509 { concurrency: 16 },
510 );
511 const sortedManifest = Object.fromEntries(
512 Object.entries(manifest).sort(([a], [b]) => a.localeCompare(b)),
513 );
514 // Like alchemy's readAssets, `directory` is deliberately excluded from the
515 // hash material: identical bytes at a different absolute path must produce
516 // the same hash.
517 const hash = yield* sha256Hex(
518 stableStringify({ config, manifest: sortedManifest, _headers, _redirects }),
519 );
520 return {
521 directory,
522 config,
523 manifest: sortedManifest,
524 _headers,
525 _redirects,
526 hash,
527 } satisfies SourceAssets;
528 });
529
530 // ─────────────────────────────────────────────────────────────────────
531 // The provider
532 // ─────────────────────────────────────────────────────────────────────
533
534 const assetsConfigOf = (ctx: SourceContext): Record<string, unknown> | undefined =>
535 ctx.assets !== undefined && typeof ctx.assets !== "string"
536 ? (ctx.assets as Record<string, unknown>)
537 : undefined;
538
539 const frameworkError = (cause: { readonly message: string }): SourceProviderError =>
540 new SourceProviderError({
541 provider: PROVIDER,
542 message: cause.message,
543 cause,
544 });
545
546 /** Run `use` against a freshly-built `Framework` service for `options`. */
547 const withFramework = <A, E, R>(
548 options: Nextjs.NextjsFrameworkOptions,
549 use: (framework: FrameworkCore.Framework["Service"]) => Effect.Effect<A, E, R>,
550 ) =>
551 Effect.gen(function* () {
552 const framework = yield* FrameworkCore.Framework;
553 return yield* use(framework);
554 }).pipe(Effect.provide(Nextjs.make(options)));
555
556 /**
557 * The production build runs in a disposable child process with
558 * `cwd = project root` (see `core/BuildChild.ts`). The OpenNext pipeline
559 * itself already runs in its own child (`runner.mjs`, nested inside this
560 * one), but the surrounding steps — `open-next.config.ts` handling, the
561 * final bundle pass, cache population — execute framework/user code that
562 * must not run in the engine process either. The shared `core/BuildChildRunner`
563 * entry imports this module in the child and calls the exported
564 * {@link buildInChild}.
565 */
566 export interface NextjsBuildChildConfig {
567 readonly rootDir: string;
568 readonly compatibilityDate: string;
569 readonly compatibilityFlags: Array<string>;
570 readonly configPath: string | undefined;
571 readonly cache: "static-assets" | "kv" | undefined;
572 readonly buildCommand: string | undefined;
573 readonly skipNextBuild: boolean | undefined;
574 readonly minify: boolean | undefined;
575 readonly debug: boolean | undefined;
576 }
577
578 export const buildInChild = (config: NextjsBuildChildConfig) =>
579 withFramework(
580 {
581 root: config.rootDir,
582 vite: {
583 compatibilityDate: config.compatibilityDate,
584 compatibilityFlags: config.compatibilityFlags,
585 },
586 nextjs: {
587 configPath: config.configPath,
588 cache: config.cache,
589 buildCommand: config.buildCommand,
590 skipNextBuild: config.skipNextBuild,
591 minify: config.minify,
592 debug: config.debug,
593 },
594 },
595 (framework) => framework.build({ root: config.rootDir }),
596 );
597
598 const makeProvider = (options: NextjsSourceOptions): SourceProvider => {
599 const frameworkOptions = (ctx: SourceContext): Nextjs.NextjsFrameworkOptions => ({
600 root: options.root,
601 vite: {
602 compatibilityDate: ctx.compatibility.date,
603 compatibilityFlags: ctx.compatibility.flags,
604 },
605 nextjs: {
606 configPath: options.configPath,
607 cache: options.cache,
608 buildCommand: options.buildCommand,
609 skipNextBuild: options.skipNextBuild,
610 minify: options.minify,
611 debug: options.debug,
612 },
613 dev: options.dev,
614 });
615
616 const resolveRoot = Effect.fn(function* () {
617 const path = yield* Path.Path;
618 return path.resolve(options.root ?? (yield* Effect.sync(() => process.cwd())));
619 });
620
621 return {
622 ownsAssets: true,
623
624 build: Effect.fn(function* (ctx) {
625 const root = yield* resolveRoot();
626 const output = yield* runBuildChild({
627 module: import.meta.url,
628 rootDir: root,
629 framework: "nextjs",
630 env: resolveBuildEnv(ctx.env),
631 config: {
632 rootDir: root,
633 compatibilityDate: ctx.compatibility.date,
634 compatibilityFlags: ctx.compatibility.flags,
635 configPath: options.configPath,
636 cache: options.cache,
637 buildCommand: options.buildCommand,
638 skipNextBuild: options.skipNextBuild,
639 minify: options.minify,
640 debug: options.debug,
641 } satisfies NextjsBuildChildConfig,
642 }).pipe(Effect.mapError(frameworkError));
643 if (output.serverModules === undefined || output.serverModules.length === 0) {
644 return yield* new SourceProviderError({
645 provider: PROVIDER,
646 message: "The OpenNext build produced no server modules",
647 });
648 }
649 const files = output.serverModules.map((file): SourceBundleFile => ({
650 path: file.name,
651 content: file.content,
652 hash: file.hash,
653 }));
654 const bundleHash = yield* sha256Hex(
655 stableStringify(files.map(({ path, hash }) => ({ path, hash }))),
656 );
657 const [assets, input] = yield* Effect.all([
658 output.clientDirectory !== undefined
659 ? readClientAssets(output.clientDirectory, assetsConfigOf(ctx))
660 : Effect.undefined,
661 hashInputTree(root, options, ctx.dotAlchemy),
662 ]);
663 return {
664 bundle: { files, hash: bundleHash },
665 assets,
666 hash: {
667 bundle: bundleHash,
668 assets: assets?.hash,
669 input,
670 additionalWorkspaces: undefined,
671 },
672 } satisfies SourceBuildOutput;
673 }),
674
675 // Rebuild-free: the input-tree hash is the change signal (like the vite
676 // source). `previous` is never consulted — state can be stale/foreign.
677 hash: Effect.fn(function* (ctx, _previous) {
678 const root = yield* resolveRoot();
679 return { input: yield* hashInputTree(root, options, ctx.dotAlchemy) };
680 }),
681
682 // Default ("preview"): always build on dev start (OpenNext memoizes
683 // where possible) and serve the built worker under cloudflare-runtime
684 // (workerd) with the alchemy-managed binding wiring. No HMR; ISR
685 // revalidation writes are a no-op.
686 // With `options.dev.mode: "hmr"`, the Framework instead runs the real
687 // `next dev` (Turbopack HMR) in Node — the alchemy-managed bindings are
688 // proxied through cloudflare-runtime's platform proxy onto OpenNext's
689 // getCloudflareContext() contract.
690 dev: Effect.fn(function* (ctx) {
691 const root = yield* resolveRoot();
692 const queueConsumers = yield* ctx.worker.queueConsumers;
693 const devOptions: Nextjs.NextjsFrameworkOptions = {
694 ...frameworkOptions(ctx),
695 // The host's runtime stack (includes remote-bindings support) — the
696 // dev binding proxy is hosted in it instead of the credential-free
697 // internal layer, so `Alchemy.remote()` bindings resolve in dev.
698 services: ctx.runtimeContext,
699 vite: {
700 compatibilityDate: ctx.compatibility.date,
701 compatibilityFlags: ctx.compatibility.flags,
702 worker: {
703 ...ctx.worker.options,
704 name: ctx.workerName,
705 bindings: ctx.worker.bindings,
706 durableObjectNamespaces: ctx.worker.durableObjectNamespaces,
707 hyperdrives: ctx.worker.hyperdrives,
708 queueConsumers,
709 assets: ctx.worker.assets,
710 },
711 },
712 };
713 const server = yield* withFramework(devOptions, (framework) => framework.dev({ root })).pipe(
714 Effect.mapError(frameworkError),
715 );
716 return {
717 mode: "server",
718 url: new URL(server.url),
719 serviceBinding: options.dev?.mode === "hmr" ? "http" : undefined,
720 } satisfies SourceDevHandle;
721 }),
722 };
723 };
724
725 /**
726 * The `WorkerSourceModule` implementation: validate the descriptor options
727 * and hand back the provider.
728 */
729 const make = (
730 options: unknown,
731 ): Effect.Effect<SourceProvider, SourceProviderError, SourceServices> => {
732 if (options !== undefined && (typeof options !== "object" || Array.isArray(options))) {
733 return Effect.fail(
734 new SourceProviderError({
735 provider: PROVIDER,
736 message: "Invalid source options: expected a plain JSON object (NextjsSourceOptions)",
737 }),
738 );
739 }
740 return Effect.succeed(makeProvider((options ?? {}) as NextjsSourceOptions));
741 };
742
743 export default { make };