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

main
ts 341 lines 12.2 KB
Raw
1 import type { MemoOptions } from "alchemy/Command/Memo";
2 import type { InputProps } from "alchemy/Input";
3 import { effectClass } from "alchemy/Util/effect";
4 import * as Effect from "effect/Effect";
5 import type { Providers } from "../Providers.ts";
6 import type { AssetsConfig } from "../Workers/Assets.ts";
7 import {
8 Worker,
9 type NormalizedBindings,
10 type WorkerAssetsConfig,
11 type WorkerBindingProps,
12 type WorkerProps,
13 } from "../Workers/Worker.ts";
14
15 /**
16 * The specifier of the Nuxt source-provider module. The package must be
17 * installed in the user's project — `loadSource` fails with a
18 * `SourceProviderError` naming it otherwise.
19 */
20 const NUXT_SOURCE_PROVIDER = "@alchemy.run/frontend-frameworks/nuxt/source";
21
22 export interface NuxtProps<Bindings extends WorkerBindingProps = {}> extends Omit<
23 WorkerProps<Bindings>,
24 "vite" | "main" | "assets" | "source" | "script" | "bundle" | "rules"
25 > {
26 /**
27 * Nuxt project root (the directory containing `nuxt.config.ts`).
28 * Relative paths resolve from the process working directory.
29 * @default process.cwd()
30 */
31 rootDir?: string;
32 /**
33 * Overrides the module that becomes the deployed Worker entry (nitro's
34 * entry/exports seam). Relative paths resolve from {@link rootDir}.
35 *
36 * By default nitro's own `cloudflare_module` entry is deployed. Point
37 * `main` at a custom module when the deployed Worker must export more
38 * than the framework's fetch handler — e.g. Durable Object classes. The
39 * custom entry wraps nitro's handler by importing it from
40 * `nitropack/presets/cloudflare/runtime/cloudflare-module` and
41 * re-exports the extras:
42 *
43 * ```typescript
44 * // worker-entry.ts
45 * import nitroHandler from "nitropack/presets/cloudflare/runtime/cloudflare-module";
46 * export class Counter extends DurableObject {}
47 * export default nitroHandler;
48 * ```
49 */
50 main?: string;
51 /**
52 * Controls which files are content-hashed to decide whether a rebuild is
53 * needed. By default every non-gitignored file under `rootDir` (plus the
54 * nearest package-manager lockfile) is hashed; narrow the scope with
55 * `include`/`exclude` globs when the project sits in a large repository.
56 */
57 memo?: MemoOptions;
58 /**
59 * Optional configuration for static asset routing behavior.
60 * Supports `runWorkerFirst`, `htmlHandling`, `notFoundHandling`, etc.
61 */
62 assets?: AssetsConfig;
63 /**
64 * Nuxt config overrides merged over the project's own `nuxt.config.ts`
65 * (the highest-priority c12 layer — a value here wins over the file).
66 * Use it for deploy-time values the config file can't express, e.g.
67 * per-stage `runtimeConfig`; `nuxt.config.ts` remains the primary home
68 * for everything else.
69 *
70 * Must be JSON-serializable — no functions, plugins, or modules (the
71 * value persists in state and participates in the rebuild hash).
72 * `nitro.preset` is always owned by the deploy target and cannot be
73 * overridden here.
74 */
75 nuxt?: Record<string, unknown>;
76 }
77
78 /**
79 * A Cloudflare Worker deployed from a [Nuxt](https://nuxt.com) project.
80 *
81 * `Nuxt` builds the app programmatically through the project's own
82 * `@nuxt/kit` with nitro's `cloudflare_module` preset — the project's
83 * `nuxt.config.ts` loads natively, no `nitro.preset` edits, no Wrangler
84 * configuration, and no build command required. The nitro server bundle
85 * deploys as the Worker script; client assets and prerendered pages
86 * (`.output/public`) deploy as Worker static assets.
87 *
88 * Requires the `@alchemy.run/frontend-frameworks` package to be installed in
89 * your project; the integration is loaded from its `/nuxt` export. Input files
90 * are content-hashed
91 * (respecting `.gitignore` by default) so unchanged projects skip the
92 * build and deploy entirely.
93 *
94 * The server build uses nitro's hybrid workerd Node compatibility
95 * (`cloudflare.nodeCompat`), which relies on workerd's native `node:*`
96 * modules — the `nodejs_compat` compatibility flag is always included in
97 * the Worker's compatibility flags to match.
98 *
99 * On local dev: `alchemy dev` runs Nuxt's own dev server (nitro dev, SSR
100 * in a Node worker thread, full HMR) with the Worker's bindings served on
101 * `event.context.cloudflare` through cloudflare-runtime's platform proxy —
102 * wrangler-free. Literal `env` values overlay the proxied bindings;
103 * resource bindings (KV, R2, D1, ...) round-trip to the proxy's local
104 * workerd instance, so dev state is live and shared. Durable Objects
105 * declared via a custom `main` entry only exist in the production build
106 * and are not servable in dev yet.
107 *
108 *
109 * ### Deploying a Nuxt App
110 * A single call builds and deploys the app — server-rendered pages, API
111 * routes, prerendered pages, and client assets included.
112 *
113 * **Example:** Basic Nuxt site
114 * ```typescript
115 * const site = yield* Cloudflare.Website.Nuxt("Website");
116 * ```
117 *
118 * **Example:** Nuxt project in a subdirectory
119 * ```typescript
120 * const site = yield* Cloudflare.Website.Nuxt("Website", {
121 * rootDir: "apps/web",
122 * });
123 * ```
124 *
125 * ### Bindings
126 * Values passed via `env` are exposed to server routes and SSR through
127 * nitro's `cloudflare_module` runtime contract:
128 * `event.context.cloudflare.env` (plus `event.context.cf` and
129 * `event.context.cloudflare.context.waitUntil`).
130 *
131 * **Example:** Reading env from an API route
132 * ```typescript
133 * const site = yield* Cloudflare.Website.Nuxt("Website", {
134 * env: {
135 * API_KEY: Config.Redacted("API_KEY"),
136 * },
137 * });
138 *
139 * // server/api/hello.ts
140 * // export default defineEventHandler((event) => ({
141 * // hasKey: event.context.cloudflare?.env?.API_KEY !== undefined,
142 * // }));
143 * ```
144 *
145 * **Example:** Binding an R2 bucket
146 * ```typescript
147 * const bucket = yield* Cloudflare.R2.Bucket("Uploads");
148 *
149 * const site = yield* Cloudflare.Website.Nuxt("Website", {
150 * env: {
151 * UPLOADS: bucket,
152 * },
153 * });
154 * ```
155 *
156 * ### Prerendering
157 * Routes marked for prerendering in `routeRules` (or via
158 * `nitro.prerender`) render at build time into `.output/public` and are
159 * served as static assets — no Worker invocation. Configure them in
160 * your `nuxt.config.ts`, which loads natively:
161 *
162 * **Example:** Prerendering a route (nuxt.config.ts)
163 * ```typescript
164 * // nuxt.config.ts
165 * export default defineNuxtConfig({
166 * routeRules: {
167 * "/about": { prerender: true },
168 * },
169 * });
170 * ```
171 *
172 * ### Config Overrides
173 * `nuxt.config.ts` is the primary home for Nuxt configuration — it loads
174 * natively. The `nuxt` prop layers deploy-time overrides on top (the
175 * highest-priority c12 layer) for values the file can't express, like
176 * per-stage settings. The bag must be JSON-serializable — no functions,
177 * plugins, or modules — and `nitro.preset` stays owned by the deploy
178 * target.
179 *
180 * **Example:** Deploy-time config overrides
181 * ```typescript
182 * const site = yield* Cloudflare.Website.Nuxt("Website", {
183 * nuxt: {
184 * app: { baseURL: "/docs/" },
185 * runtimeConfig: {
186 * public: { apiBase: "https://api.example.com" },
187 * },
188 * },
189 * });
190 * ```
191 *
192 * ### Custom Worker Exports (Durable Objects)
193 * Nitro's entry module is the Worker's exports seam. Point `main` at your
194 * own module that re-exports nitro's runtime handler (imported from
195 * `nitropack/presets/cloudflare/runtime/cloudflare-module`) and adds
196 * extra exports — Durable Object classes must live on the deployed
197 * Worker for their namespace bindings to resolve. Every framework route
198 * keeps working through the re-exported handler.
199 *
200 * **Example:** Custom entry hosting a Durable Object
201 * ```typescript
202 * // worker-entry.ts
203 * // import nitroHandler from "nitropack/presets/cloudflare/runtime/cloudflare-module";
204 * // export class Counter extends DurableObject { ... }
205 * // export default nitroHandler;
206 *
207 * const site = yield* Cloudflare.Website.Nuxt("Website", {
208 * main: "worker-entry.ts",
209 * env: {
210 * COUNTER: Cloudflare.DurableObject("Counter", {
211 * className: "Counter",
212 * }),
213 * },
214 * });
215 * ```
216 *
217 * ### Dev
218 * `alchemy dev` runs Nuxt's own dev server (nitro dev, full HMR) with
219 * `event.context.cloudflare` served wrangler-free through
220 * cloudflare-runtime's platform proxy: resource bindings resolve against
221 * a local workerd instance, and literal `env` values overlay them.
222 *
223 * **Example:** Reading bindings in dev and production alike
224 * ```typescript
225 * // server/api/greeting.ts — identical code in dev and deployed
226 * // export default defineEventHandler((event) => ({
227 * // greeting: event.context.cloudflare?.env?.GREETING,
228 * // }));
229 * const site = yield* Cloudflare.Website.Nuxt("Website", {
230 * env: { GREETING: "hello" },
231 * });
232 * ```
233 *
234 * ### Custom Rebuild Scope
235 * By default, every non-gitignored file is hashed to decide whether a
236 * rebuild is needed. Use `memo` to narrow the scope when the project
237 * lives in a large repository.
238 *
239 * **Example:** Narrowing the memo scope
240 * ```typescript
241 * const site = yield* Cloudflare.Website.Nuxt("Website", {
242 * memo: {
243 * include: ["app/**", "server/**", "public/**", "nuxt.config.ts", "package.json"],
244 * },
245 * });
246 * ```
247 *
248 * ### Limitations
249 * Nitro's `isr` route rule (incremental static regeneration) is
250 * implemented only by the Vercel and Netlify presets — on Cloudflare it
251 * is silently ignored at build time, and the route renders on demand in
252 * the Worker like any other SSR route. Use `prerender` for build-time
253 * static routes, or `cache` route rules for runtime caching.
254 *
255 * ### Class Form
256 * Calling `Nuxt` with no arguments returns a constructor you can
257 * `extend` to declare the Worker as a named class. The class is both an
258 * `Effect` you can `yield*` to deploy and a type you can reference
259 * elsewhere — useful when other resources need to bind to this Worker.
260 *
261 * **Example:** Declaring a Worker class
262 * ```typescript
263 * class Website extends Cloudflare.Website.Nuxt<Website>()(
264 * "Website",
265 * ) {}
266 *
267 * const site = yield* Website;
268 * ```
269 *
270 * @resource
271 * @product Website
272 * @category Workers & Compute
273 */
274 export const Nuxt: {
275 <Self>(): {
276 <const Bindings extends WorkerBindingProps = {}, Req = never>(
277 id: string,
278 propsEff?:
279 | InputProps<NuxtProps<Bindings>>
280 | Effect.Effect<InputProps<NuxtProps<Bindings>>, never, Req>,
281 ): Effect.Effect<Self, never, Req | Providers> & {
282 new (): Worker<{
283 [binding in keyof NormalizedBindings<Bindings, WorkerAssetsConfig>]: NormalizedBindings<
284 Bindings,
285 WorkerAssetsConfig
286 >[binding];
287 }>;
288 };
289 };
290 <const Bindings extends WorkerBindingProps = {}, Req = never>(
291 id: string,
292 propsEff?:
293 | InputProps<NuxtProps<Bindings>>
294 | Effect.Effect<InputProps<NuxtProps<Bindings>>, never, Req>,
295 ): Effect.Effect<
296 Worker<{
297 [binding in keyof NormalizedBindings<Bindings, WorkerAssetsConfig>]: NormalizedBindings<
298 Bindings,
299 WorkerAssetsConfig
300 >[binding];
301 }>,
302 never,
303 Req | Providers
304 >;
305 } = (<const Bindings extends WorkerBindingProps = {}, Req = never>(
306 id?: string,
307 propsEff?:
308 | InputProps<NuxtProps<Bindings>>
309 | Effect.Effect<InputProps<NuxtProps<Bindings>>, never, Req>,
310 ) =>
311 id === undefined
312 ? <const Bindings extends WorkerBindingProps = {}, Req = never>(
313 id: string,
314 propsEff?:
315 | InputProps<NuxtProps<Bindings>>
316 | Effect.Effect<InputProps<NuxtProps<Bindings>>, never, Req>,
317 ) => effectClass(Nuxt(id, propsEff))
318 : Worker(
319 id,
320 Effect.map(Effect.isEffect(propsEff) ? propsEff : Effect.succeed(propsEff), (props) => ({
321 ...props,
322 // The server build uses nitro's hybrid workerd node-compat
323 // (`cloudflare.nodeCompat: true`), which relies on workerd's
324 // native `node:*` modules — `getCompatibility` already adds
325 // `nodejs_compat` to every non-python Worker.
326 // `main` is the source provider's user-entry seam (nitro's
327 // entry), not the Worker's own bundling entry.
328 main: undefined!,
329 source: {
330 provider: NUXT_SOURCE_PROVIDER,
331 devMode: "server",
332 rootDir: props?.rootDir,
333 options: {
334 rootDir: props?.rootDir,
335 main: props?.main,
336 memo: props?.memo,
337 nuxt: props?.nuxt,
338 },
339 },
340 })),
341 )) as any;