@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 676 lines 27.3 KB
Raw
1 import * as Effect from "effect/Effect";
2 import * as FileSystem from "effect/FileSystem";
3 import * as Layer from "effect/Layer";
4 import * as Path from "effect/Path";
5 import * as Schedule from "effect/Schedule";
6 import type * as Scope from "effect/Scope";
7 import * as FrameworkCore from "../core/index.ts";
8 import {
9 Framework,
10 FrameworkError,
11 type DeployTarget,
12 type DeployTargetError,
13 type DeployTargetInput,
14 } from "../core/index.ts";
15 import {
16 enforceNitroConfig,
17 findPresetConflict,
18 makeNuxtOverrides,
19 presetConflictMessage,
20 type NitroConfigSlice,
21 type NuxtConfigLayer,
22 } from "./UserConfig.ts";
23
24 /**
25 * The structural slice of the project's `@nuxt/kit` module this package
26 * drives. Typed structurally so the package carries no dependency on
27 * `@nuxt/kit` — the *project's* install is always the one loaded.
28 */
29 export interface NuxtKitModule {
30 readonly loadNuxt: (options: {
31 readonly cwd: string;
32 readonly dev?: boolean;
33 readonly ready?: boolean;
34 readonly overrides?: Record<string, unknown>;
35 }) => Promise<NuxtInstance>;
36 readonly buildNuxt: (nuxt: NuxtInstance) => Promise<unknown>;
37 }
38
39 /** The structural slice of a loaded Nuxt instance this package reads. */
40 export interface NuxtInstance {
41 readonly options: {
42 readonly _layers?: ReadonlyArray<NuxtConfigLayer> | undefined;
43 readonly [key: string]: unknown;
44 };
45 readonly hook: (name: string, fn: (...args: Array<never>) => unknown) => unknown;
46 readonly ready: () => Promise<void>;
47 readonly close: () => Promise<void>;
48 /**
49 * The dev middleware server (nitro's dev server; present after `ready()`
50 * when loaded with `dev: true`). `listen` is listhen-backed: it binds a
51 * real HTTP listener serving the dev app.
52 */
53 readonly server?:
54 | {
55 readonly listen: (
56 port: number,
57 opts?: { readonly hostname?: string },
58 ) => Promise<NuxtDevListener>;
59 }
60 | undefined;
61 }
62
63 /** The structural slice of the listhen listener `nuxt.server.listen` returns. */
64 export interface NuxtDevListener {
65 readonly url?: string | undefined;
66 readonly close?: (() => Promise<void>) | undefined;
67 }
68
69 /** The structural slice of a Nitro instance (`nitro:init` hook payload). */
70 interface NitroInstanceSlice {
71 readonly options: {
72 entry?: string;
73 readonly output: {
74 readonly dir: string;
75 readonly serverDir: string;
76 readonly publicDir: string;
77 };
78 };
79 }
80
81 /** Inputs the framework passes when consulting the target's nitro hook. */
82 export interface NuxtNitroContext {
83 /** Absolute project root. */
84 readonly root: string;
85 /**
86 * Absolute path of the USER's worker entry (the generic user-entry seam,
87 * `target.entry` resolved against the root), when one is configured. The
88 * target maps it onto nitro's entry/exports seam — the user module wraps
89 * nitro's emitted handler and adds its own exports (Durable Objects, ...).
90 */
91 readonly entry?: string | undefined;
92 }
93
94 /**
95 * The configuration this package assembles from {@link NuxtOptions} and hands
96 * to a deploy-target factory. The target treats it as its
97 * `DeployTarget.config`; the framework half never inspects a resolved
98 * target's config.
99 */
100 export interface NuxtTargetConfig {
101 /** Compatibility date the target carries for serve/deploy. */
102 readonly compatibilityDate?: string | undefined;
103 /** Compatibility flags the target carries for serve/deploy. */
104 readonly compatibilityFlags?: Array<string> | undefined;
105 /**
106 * The USER's worker entry (the custom-entry carriage): a module that wraps
107 * nitro's emitted entry and adds its own exports (Durable Object classes,
108 * ...). Relative paths resolve against the project root.
109 */
110 readonly main?: string | undefined;
111 /**
112 * Whether the server build includes Node.js compatibility (nitro's hybrid
113 * workerd node-compat). The deployed worker must enable the
114 * `nodejs_compat` compatibility flag when this is on.
115 * @default true (applied by the Cloudflare target)
116 */
117 readonly nodeCompat?: boolean | undefined;
118 /**
119 * The nuxt config overrides the framework half was constructed with
120 * ({@link NuxtOptions.nuxt}). Carried on the target config so wholesale
121 * targets that re-run the framework in a child process (the AWS target —
122 * `loadNuxt` executes user config/modules that may mutate the process)
123 * can reconstruct the framework with the same options.
124 */
125 readonly nuxt?: Record<string, unknown> | undefined;
126 }
127
128 /** Inputs the framework passes when asking the target for its dev platform. */
129 export interface NuxtDevPlatformContext {
130 /** Absolute project root. */
131 readonly root: string;
132 /**
133 * Literal env overrides for the dev platform — a same-named literal wins
134 * over any platform-served value.
135 */
136 readonly env?: Record<string, unknown> | undefined;
137 /**
138 * Target-specific binding specs the dev platform should serve (opaque to
139 * the framework half — the Cloudflare target takes `cloudflare-runtime`
140 * binding hooks and serves them through its platform proxy).
141 */
142 readonly bindings?: ReadonlyArray<unknown> | undefined;
143 /**
144 * Pre-built runtime-services context for the dev platform's proxy (opaque
145 * to the framework half — see `NuxtOptions.dev.services`).
146 */
147 readonly services?: unknown;
148 /**
149 * Overrides for the dev platform's workerd process (opaque to the
150 * framework half — see `NuxtOptions.dev.workerd`).
151 */
152 readonly workerd?: unknown;
153 }
154
155 /**
156 * What a target's dev platform contributes to the dev server: extra nitro
157 * plugins and `runtimeConfig` to inject through the `loadNuxt` overrides
158 * (the Cloudflare target injects its `event.context.cloudflare` bridge
159 * plugin plus the platform-proxy connect info).
160 */
161 export interface NuxtDevPlatform {
162 /** Absolute paths of nitro plugins to inject into the dev server. */
163 readonly nitroPlugins?: ReadonlyArray<string> | undefined;
164 /** `runtimeConfig` injected over the integration overrides. */
165 readonly runtimeConfig?: Record<string, unknown> | undefined;
166 }
167
168 /**
169 * A deploy target for Nuxt: the generic `DeployTarget` seams plus the
170 * framework-specific hooks nitro-driven builds and dev servers need — the
171 * nitro deployment preset to build with, a last-word pass over the resolved
172 * nitro config, and the dev-platform seam.
173 */
174 export interface NuxtTarget extends DeployTarget<NuxtTargetConfig> {
175 /** The nitro deployment preset this target builds with (e.g. `"cloudflare_module"`). */
176 readonly nitroPreset: string;
177 /**
178 * Last-word mutation of the resolved nitro config, run from the
179 * `nitro:config` hook after the user's config, layers, and modules have
180 * all contributed (e.g. the Cloudflare target forces
181 * `cloudflare.deployConfig: false` and wires the user entry).
182 */
183 readonly configureNitro?:
184 | ((nitroConfig: NitroConfigSlice, context: NuxtNitroContext) => void)
185 | undefined;
186 /**
187 * The target's dev-platform story: acquire whatever serves the platform
188 * environment in dev (scoped — closing the Scope tears it down AFTER the
189 * dev server closes) and return the injection the dev server needs. When
190 * absent, `dev` runs the plain framework dev server with no platform
191 * bridge.
192 */
193 readonly devPlatform?:
194 | ((
195 context: NuxtDevPlatformContext,
196 ) => Effect.Effect<NuxtDevPlatform, DeployTargetError, Scope.Scope>)
197 | undefined;
198 }
199
200 /**
201 * How a deploy target is passed to this package: a `NuxtTarget` value, a
202 * factory `(config) => NuxtTarget`, or a module specifier resolved from the
203 * *project's* `node_modules` (default-export — or named export `target` — a
204 * value or factory).
205 */
206 export type NuxtTargetInput = DeployTargetInput<NuxtTarget, NuxtTargetConfig>;
207
208 /**
209 * The default deploy target: this package's own Cloudflare Workers target
210 * module (`src/cloudflare.ts`), loaded from the project's dependency tree.
211 */
212 export const DEFAULT_TARGET_SPECIFIER = "@alchemy.run/frontend-frameworks/nuxt/cloudflare";
213
214 export interface NuxtOptions {
215 /**
216 * Project root (the directory containing `nuxt.config.ts`).
217 * @default process.cwd()
218 */
219 readonly root?: string | undefined;
220 /**
221 * The deploy target the build is produced for. Accepts a target value, a
222 * `(config) => target` factory, or a module specifier string.
223 * @default "@alchemy.run/frontend-frameworks/nuxt/cloudflare"
224 */
225 readonly target?: NuxtTargetInput | undefined;
226 /** Compatibility date forwarded to the target via its config. */
227 readonly compatibilityDate?: string | undefined;
228 /**
229 * Compatibility flags forwarded to the target via its config. Nitro's
230 * workerd build uses hybrid Node.js compatibility, so on workerd-style
231 * targets `nodejs_compat` is effectively required.
232 * @default ["nodejs_compat"] (applied by the Cloudflare target)
233 */
234 readonly compatibilityFlags?: Array<string> | undefined;
235 /**
236 * The USER's worker entry (the custom-entry carriage — see
237 * {@link NuxtTargetConfig.main}). Relative paths resolve against the root.
238 */
239 readonly main?: string | undefined;
240 /**
241 * Nuxt config overrides merged over the project's own `nuxt.config.ts`
242 * (highest-priority c12 layer; integration wins). The user's file remains
243 * authoritative for everything not named here; `nitro.preset` is always
244 * owned by the deploy target.
245 */
246 readonly nuxt?: Record<string, unknown> | undefined;
247 readonly dev?:
248 | {
249 /** Default dev-server port (overridden by `FrameworkDevOptions.port`). */
250 readonly port?: number | undefined;
251 /**
252 * Literal values exposed on the dev platform env
253 * (`event.context.cloudflare.env` on the Cloudflare target).
254 * Applied on top of the values served for {@link bindings} — a
255 * same-named literal always wins.
256 */
257 readonly env?: Record<string, unknown> | undefined;
258 /**
259 * Target-specific binding specs the dev platform should serve.
260 * Opaque to the framework half; the Cloudflare target accepts
261 * `cloudflare-runtime` binding hooks (`Text.local`,
262 * `KvNamespace.local`, …) and serves them into nitro's dev SSR
263 * worker thread through a workerd-backed platform proxy.
264 */
265 readonly bindings?: ReadonlyArray<unknown> | undefined;
266 /**
267 * A pre-built runtime-services context the dev platform should host
268 * its proxy in (opaque to the framework half; the Cloudflare target
269 * takes a `cloudflare-runtime` `Context<RuntimeServices>`). Embedders
270 * that already run a runtime stack — alchemy's dev sidecar — pass it
271 * so remote()-lowered bindings resolve; without it the platform is
272 * local-only.
273 */
274 readonly services?: unknown;
275 /**
276 * Overrides for the dev platform's workerd process (opaque to the
277 * framework half; the Cloudflare target takes `cloudflare-runtime`
278 * `WorkerdOptions`).
279 */
280 readonly workerd?: unknown;
281 }
282 | undefined;
283 }
284
285 const fail = (message: string, cause?: unknown) =>
286 new FrameworkError({ framework: "nuxt", message, cause });
287
288 /**
289 * The specifier the project's Nuxt kit is loaded from. `@nuxt/kit` itself is
290 * not directly resolvable from a project root under isolated installs (it's
291 * nuxt's own dependency), but nuxt's universally-present `./kit` subpath
292 * (`nuxt/kit.js`, a plain `export * from "@nuxt/kit"`) is — and it resolves
293 * the project's own kit instance.
294 */
295 export const NUXT_KIT_SPECIFIER = "nuxt/kit";
296
297 /**
298 * Build the `Framework` service implementation for a Nuxt project.
299 *
300 * - `build` resolves the deploy target, then either delegates wholesale
301 * (`target.build`) or drives the PROJECT's `@nuxt/kit` programmatically:
302 * `loadNuxt({ cwd, dev: false, ready: false, overrides })` — the project's
303 * `nuxt.config.ts` loads natively through c12 — hooks are registered
304 * BEFORE `nuxt.ready()` (with `ready: true` they'd fire inside `loadNuxt`
305 * and be missed), then `buildNuxt`. The nitro preset is the target's
306 * (`nitro:config` gets the last word); a user-configured foreign preset
307 * fails with an actionable error. The `BuildOutput` is read from nitro's
308 * `.output`: `serverModules` entry-first from `.output/server`,
309 * `clientDirectory` = `.output/public`, both taken from the resolved
310 * nitro output options (`nitro:init`).
311 * - `dev` runs Nuxt's own dev server programmatically (`loadNuxt({ dev:
312 * true, ready: false })` → hooks → `ready()` → `nuxt.server.listen` →
313 * `buildNuxt`, the same flow `nuxi dev` drives), scoped — closing the
314 * Scope closes the listener, the Nuxt instance, and then the target's
315 * dev platform. The target's `devPlatform` seam contributes nitro
316 * plugins + `runtimeConfig` (the Cloudflare target injects its
317 * `event.context.cloudflare` bridge served through cloudflare-runtime's
318 * platform proxy — SSR runs in nitro's Node worker THREAD, wrangler-free).
319 *
320 * This module is target-agnostic: everything Cloudflare-specific lives in
321 * `@alchemy.run/frontend-frameworks/nuxt/cloudflare`.
322 */
323 export const make: (
324 options?: NuxtOptions,
325 ) => Effect.Effect<Framework["Service"], never, FileSystem.FileSystem | Path.Path> =
326 Effect.fnUntraced(function* (options?: NuxtOptions) {
327 const fs = yield* FileSystem.FileSystem;
328 const path = yield* Path.Path;
329 const baseRoot = options?.root ?? (yield* Effect.sync(() => process.cwd()));
330
331 const targetConfig: NuxtTargetConfig = {
332 compatibilityDate: options?.compatibilityDate,
333 compatibilityFlags: options?.compatibilityFlags,
334 main: options?.main,
335 nuxt: options?.nuxt,
336 };
337
338 const resolveTarget = (root: string) =>
339 FrameworkCore.resolveDeployTarget<NuxtTarget, NuxtTargetConfig>(
340 root,
341 options?.target ?? DEFAULT_TARGET_SPECIFIER,
342 targetConfig,
343 ).pipe(Effect.mapError((error) => fail(error.message, error.cause)));
344
345 const requireNitroPreset = (target: NuxtTarget) =>
346 typeof target.nitroPreset === "string" && target.nitroPreset.length > 0
347 ? Effect.succeed(target)
348 : Effect.fail(
349 fail(
350 `The resolved "${target.platform}" deploy target does not declare the nitro ` +
351 "preset hook (`nitroPreset`) and has no wholesale `build`",
352 ),
353 );
354
355 const loadNuxtKit = (root: string) =>
356 FrameworkCore.loadProjectModule<NuxtKitModule>(root, NUXT_KIT_SPECIFIER).pipe(
357 Effect.mapError((error) => fail("Failed to load the project's Nuxt kit", error.cause)),
358 );
359
360 const build: Framework["Service"]["build"] = Effect.fn(function* (buildOptions) {
361 const root = buildOptions?.root ?? baseRoot;
362 const target = yield* resolveTarget(root);
363 const targetContext = { root, framework: "nuxt", env: buildOptions?.env };
364
365 // Wholesale build takeover (targets that own the entire pipeline).
366 if (target.build !== undefined) {
367 return yield* target.build(targetContext).pipe(
368 Effect.mapError((error) => fail(error.message, error.cause)),
369 Effect.provideService(FileSystem.FileSystem, fs),
370 Effect.provideService(Path.Path, path),
371 );
372 }
373
374 yield* requireNitroPreset(target);
375 const entry = FrameworkCore.resolveDeployTargetEntry(target, { root });
376 const kit = yield* loadNuxtKit(root);
377
378 // The user's nuxt.config.ts loads natively; our injection rides the
379 // highest-priority overrides layer. `ready: false` so hooks registered
380 // below actually fire (ready: true runs them inside loadNuxt).
381 const nuxt = yield* Effect.tryPromise({
382 try: async () =>
383 await kit.loadNuxt({
384 cwd: root,
385 dev: false,
386 ready: false,
387 overrides: makeNuxtOverrides({
388 nitroPreset: target.nitroPreset,
389 nuxtConfig: options?.nuxt,
390 }),
391 }),
392 catch: (error) => fail("Failed to load the Nuxt project", error),
393 });
394
395 const buildResult = yield* Effect.gen(function* () {
396 // Conflict policy: the overrides layer shadows a user-set preset in
397 // the merged options, so the user's raw value is read from the
398 // project's own config layers and rejected with an actionable error
399 // instead of being silently replaced.
400 const conflict = findPresetConflict(nuxt.options._layers, target.nitroPreset);
401 if (conflict !== undefined) {
402 return yield* fail(presetConflictMessage(conflict, target.nitroPreset));
403 }
404
405 // Registered BEFORE nuxt.ready(): nitro:config fires while ready()
406 // initializes nitro.
407 let outputDirs: NitroInstanceSlice["options"]["output"] | undefined;
408 yield* Effect.sync(() => {
409 nuxt.hook("nitro:config", (nitroConfig: NitroConfigSlice) => {
410 enforceNitroConfig(nitroConfig, {
411 preset: target.nitroPreset,
412 configure: (config) => target.configureNitro?.(config, { root, entry }),
413 });
414 });
415 nuxt.hook("nitro:init", (nitro: NitroInstanceSlice) => {
416 outputDirs = nitro.options.output;
417 // The user-entry seam: nitro bundles `options.entry` as THE
418 // worker entry, so the user module's exports (default handler +
419 // Durable Objects, ...) are the worker's exports. Set on the
420 // INSTANCE options — not the nitro config — because nitro's
421 // prerenderer clones `options._config` for its Node-preset
422 // sub-build, and a workerd-flavored user entry (importing
423 // `cloudflare:` modules) must not leak into that clone.
424 if (entry !== undefined) {
425 nitro.options.entry = entry;
426 }
427 });
428 });
429
430 yield* Effect.tryPromise({
431 try: async () => {
432 await nuxt.ready();
433 await kit.buildNuxt(nuxt);
434 },
435 catch: (error) => fail("Failed to build", error),
436 });
437
438 const output = outputDirs ?? {
439 dir: path.resolve(root, ".output"),
440 serverDir: path.resolve(root, ".output", "server"),
441 publicDir: path.resolve(root, ".output", "public"),
442 };
443 return output;
444 }).pipe(
445 Effect.ensuring(
446 Effect.promise(async () => {
447 try {
448 await nuxt.close();
449 } catch {
450 // teardown is best-effort
451 }
452 }),
453 ),
454 );
455
456 const output = yield* readNitroOutput(buildResult).pipe(
457 Effect.provideService(FileSystem.FileSystem, fs),
458 );
459
460 // The finishing-pass seam (none needed for cloudflare_module — the
461 // output is already workerd ESM — but the contract is honored for
462 // targets that do post-process).
463 return yield* FrameworkCore.applyDeployTargetFinish(target, output, {
464 ...targetContext,
465 entry: path.join(buildResult.serverDir, "index.mjs"),
466 }).pipe(
467 Effect.mapError((error) => fail(error.message, error.cause)),
468 Effect.provideService(FileSystem.FileSystem, fs),
469 Effect.provideService(Path.Path, path),
470 );
471 });
472
473 const devInProcess: Framework["Service"]["dev"] = Effect.fn(function* (devOptions) {
474 const root = devOptions?.root ?? baseRoot;
475 const target = yield* resolveTarget(root);
476 // Resolve the project's kit before anything expensive: a root without
477 // a Nuxt install fails fast, without spawning the dev platform.
478 const kit = yield* loadNuxtKit(root);
479
480 // The dev platform is acquired BEFORE the server so its finalizer
481 // runs LAST (finalizers are LIFO): the platform (e.g. the Cloudflare
482 // target's platform-proxy workerd instance) outlives the last
483 // in-flight request of the closing dev server.
484 const platform =
485 target.devPlatform !== undefined
486 ? yield* target
487 .devPlatform({
488 root,
489 env: options?.dev?.env,
490 bindings: options?.dev?.bindings,
491 services: options?.dev?.services,
492 workerd: options?.dev?.workerd,
493 })
494 .pipe(Effect.mapError((error) => fail(error.message, error.cause)))
495 : undefined;
496
497 // The user's nuxt.config.ts loads natively; the dev injection rides
498 // the overrides layer. No nitro preset here — nitro's dev flow runs
499 // its own Node dev preset (the SSR worker thread); the deploy preset
500 // only matters for `build`. Telemetry/devtools are disabled: this
501 // dev server runs headless under alchemy / the e2e harness.
502 //
503 // Injected plugins live under node_modules (this package's dist), so
504 // their directories must be forced into `nitro.externals.inline`:
505 // nitro's externals pass would otherwise keep the plugin external and
506 // node would resolve its `nitropack/runtime` import against the raw
507 // package, whose `#nitro-internal-virtual/*` imports only exist
508 // inside the dev bundle.
509 const nitroPlugins = platform?.nitroPlugins;
510 const nuxt = yield* Effect.tryPromise({
511 try: async () =>
512 await kit.loadNuxt({
513 cwd: root,
514 dev: true,
515 ready: false,
516 overrides: makeNuxtOverrides({
517 nuxtConfig: { telemetry: false, devtools: { enabled: false }, ...options?.nuxt },
518 nitroPlugins,
519 nitroExternalsInline: nitroPlugins?.map((plugin) => path.dirname(plugin)),
520 runtimeConfig: platform?.runtimeConfig,
521 }),
522 }),
523 catch: (error) => fail("Failed to load the Nuxt project", error),
524 });
525 yield* Effect.addFinalizer(() =>
526 Effect.promise(async () => {
527 try {
528 await nuxt.close();
529 } catch {
530 // teardown is best-effort
531 }
532 }),
533 );
534
535 yield* Effect.tryPromise({
536 try: () => nuxt.ready(),
537 catch: (error) => fail("Failed to initialize the Nuxt dev server", error),
538 });
539
540 const server = nuxt.server;
541 if (server === undefined || typeof server.listen !== "function") {
542 return yield* fail("The loaded Nuxt instance exposes no dev server (`nuxt.server.listen`)");
543 }
544 // `nuxt.server.listen` is listhen-backed. listhen hunts upward from
545 // 3000 when NO port is given — colliding with (or IPv6-shadowing)
546 // user-facing `alchemy dev` proxy ports — while an explicit `port: 0`
547 // resolves to get-port-please's `getRandomPort`, the same
548 // probe-and-release `findEphemeralPort` does. Probe explicitly for
549 // uniformity with the Vite-based frameworks (see DevPort's TODO).
550 const port =
551 (devOptions?.port ?? options?.dev?.port) || (yield* FrameworkCore.findEphemeralPort());
552 const host = devOptions?.host;
553 const listener = yield* Effect.acquireRelease(
554 Effect.tryPromise({
555 // Nitro's dev-server `listen` is listhen-backed; the second
556 // argument merges into listhen's options (older versions ignore
557 // it, degrading to the default host).
558 try: () => server.listen(port, host !== undefined ? { hostname: host } : undefined),
559 catch: (error) => fail("Failed to start the dev server listener", error),
560 }),
561 (listener) =>
562 Effect.promise(async () => {
563 try {
564 await listener.close?.();
565 } catch {
566 // teardown is best-effort
567 }
568 }),
569 );
570 const url = listener.url;
571 if (url === undefined) {
572 return yield* fail("Could not determine the dev server URL");
573 }
574
575 // The initial dev build — same flow as `nuxi dev` (which awaits
576 // buildNuxt after wiring its listener); the promise resolves once
577 // the dev bundles are ready, watchers keep running in background.
578 yield* Effect.tryPromise({
579 try: () => kit.buildNuxt(nuxt),
580 catch: (error) => fail("Failed to build the dev server", error),
581 });
582
583 // Bounded readiness probe: any HTTP response counts (vite serves
584 // lazily; we only need the listener to answer).
585 yield* Effect.tryPromise({
586 try: async () => {
587 const response = await fetch(url, { redirect: "manual" });
588 await response.arrayBuffer().catch(() => {});
589 },
590 catch: (error) => fail("The dev server did not become reachable", error),
591 }).pipe(Effect.retry({ schedule: Schedule.spaced("250 millis"), times: 40 }));
592
593 return { url };
594 });
595
596 // Nuxt's kit/module caches and Nitro dev runtime are shared within a
597 // process. Concurrent projects can report readiness while serving a
598 // different project's build, so give each dev server its own process.
599 const dev: Framework["Service"]["dev"] = (devOptions) => {
600 if (FrameworkCore.isInsideDevChild() || !FrameworkCore.isJsonSerializable(options)) {
601 return devInProcess(devOptions);
602 }
603 const root = devOptions?.root ?? baseRoot;
604 const port = devOptions?.port ?? options?.dev?.port;
605 return FrameworkCore.runDevChild({
606 framework: "nuxt",
607 module: "@alchemy.run/frontend-frameworks/nuxt",
608 callerUrl: import.meta.url,
609 rootDir: root,
610 makeOptions: { ...options, root },
611 devOptions: {
612 root,
613 ...(port !== undefined ? { port } : {}),
614 ...(devOptions?.host !== undefined ? { host: devOptions.host } : {}),
615 },
616 });
617 };
618
619 return Framework.of({ build, dev });
620 });
621
622 /** The nitro server entry's module name within the `BuildOutput` (POSIX). */
623 export const SERVER_ENTRY_NAME = "server/index.mjs";
624
625 /** The resolved nitro output directories (`nitro.options.output`). */
626 export interface NitroOutputDirs {
627 /** Root output directory (`.output`). */
628 readonly dir: string;
629 /** Server bundle directory (`.output/server`). */
630 readonly serverDir: string;
631 /** Static assets directory (`.output/public`, prerendered pages included). */
632 readonly publicDir: string;
633 }
634
635 /**
636 * Map nitro's on-disk `.output` onto the `BuildOutput` contract:
637 * `serverModules` entry-first from the server directory (POSIX names,
638 * sha256-hashed), `clientDirectory` = the public directory. The
639 * `cloudflare_module` output is already self-contained workerd ESM — no
640 * finishing pass, and no external workspace roots (nitro inlines workspace
641 * imports into the server chunks).
642 */
643 export const readNitroOutput = (
644 dirs: NitroOutputDirs,
645 ): Effect.Effect<FrameworkCore.BuildOutput, FrameworkError, FileSystem.FileSystem> =>
646 Effect.gen(function* () {
647 const modules = yield* FrameworkCore.readServerModulesFromDisk({
648 directory: dirs.serverDir,
649 prefix: "server",
650 }).pipe(Effect.mapError((error) => fail(error.message, error.cause)));
651 if (modules.length === 0) {
652 return yield* fail(`The Nuxt build produced no server modules in ${dirs.serverDir}`);
653 }
654 const serverModules = FrameworkCore.sortServerModules(modules, SERVER_ENTRY_NAME);
655 if (serverModules[0]?.name !== SERVER_ENTRY_NAME) {
656 return yield* fail(
657 `The Nuxt build produced no "${SERVER_ENTRY_NAME}" entry in ${dirs.serverDir}`,
658 );
659 }
660 return {
661 distDirectory: dirs.dir,
662 clientDirectory: dirs.publicDir,
663 serverModules,
664 externalWorkspaces: new Set<string>(),
665 } satisfies FrameworkCore.BuildOutput;
666 });
667
668 /**
669 * A `Layer` providing framework-core's `Framework` service for a Nuxt
670 * project — the fully-typed entrypoint for `e2e.config.ts` (harness form 4)
671 * and alchemy's `Website.Nuxt` composite.
672 */
673 export const layer = (
674 options?: NuxtOptions,
675 ): Layer.Layer<Framework, never, FileSystem.FileSystem | Path.Path> =>
676 Layer.effect(Framework, make(options));