@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 320 lines 12.5 KB
Raw
1 import * as NodeFs from "node:fs/promises";
2 import * as NodePath from "node:path";
3 import { fileURLToPath } from "node:url";
4 import type { BindingHooks, Module } from "@alchemy.run/cloudflare-runtime/core";
5 import { DEFAULT_COMPATIBILITY_DATE } from "@alchemy.run/cloudflare-runtime/core/internal/constants";
6 import * as Runtime from "@alchemy.run/cloudflare-runtime/core/Runtime";
7 import * as RuntimeServices from "@alchemy.run/cloudflare-runtime/core/RuntimeServices";
8 import { hasNodejsAls, hasNodejsCompat } from "@alchemy.run/cloudflare-runtime/rolldown/utils";
9 // Alchemy modifications are licensed under Apache-2.0.
10 // This file includes third-party code; see /THIRD_PARTY_LICENSES.md.
11 /**
12 * Wrangler-free workerd prerenderer: the build-side driver of the
13 * `__astro_*` prerender protocol, ported from `@astrojs/cloudflare` v14.4.2
14 * (`src/prerenderer.ts`).
15 *
16 * Upstream boots a Vite preview server wrapped around
17 * `@cloudflare/vite-plugin` to host the built `prerender` environment. We
18 * skip the preview-server indirection entirely: the built output under
19 * `dist/server/.prerender/` is loaded from disk into workerd via
20 * `cloudflare-runtime`'s `Runtime.start`, with the same bindings, assets
21 * directory, and compatibility settings as the entry worker — so prerendered
22 * pages render in the same runtime that serves them in production
23 * (top-level `cloudflare:*` imports included).
24 *
25 * Protocol (served by the vendored runtime handler when
26 * `virtual:astro-cloudflare:config`'s `isPrerender` is true):
27 * - `POST /__astro_static_paths` → all paths to prerender (serialized routes)
28 * - `POST /__astro_prerender` → renders one page, framed with its render
29 * metadata (`runtime/utils/prerender-response.ts`); a failure is signalled
30 * via the `x-astro-prerender-error` response header
31 *
32 * This module is heavyweight (Effect + cloudflare-runtime); the integration
33 * imports it lazily inside the `astro:build:start` hook so `astro dev` and
34 * node-mode builds never load it.
35 */
36 import type { CloudflareVitePluginOptions } from "@alchemy.run/cloudflare-runtime/vite";
37 import * as Credentials from "@distilled.cloud/cloudflare/Credentials";
38 import type { AstroConfig, AstroPrerenderer, StaticPathsResult } from "astro";
39 import { deserializeRouteData, serializeRouteData } from "astro/app/manifest";
40 import type * as Context from "effect/Context";
41 import * as Effect from "effect/Effect";
42 import * as Exit from "effect/Exit";
43 import * as FetchHttpClient from "effect/http/FetchHttpClient";
44 import * as Layer from "effect/Layer";
45 import * as Scope from "effect/Scope";
46 import { PlatformServices } from "../Platform.ts";
47 import { readFramedPrerenderResponse } from "./prerender-response.ts";
48 import type { PrerenderRequest, StaticPathsResponse } from "./runtime/prerender-types.ts";
49 import { PRERENDER_ENDPOINT, STATIC_PATHS_ENDPOINT } from "./runtime/utils/prerender-constants.ts";
50
51 /** The subdirectory of the server output dir that hosts the prerender build. */
52 const PRERENDER_OUTPUT_SUBDIR = "./.prerender/";
53
54 /** Astro core's entry chunk name pattern for the prerender environment. */
55 const PRERENDER_ENTRY_PATTERN = /^prerender-entry\..*\.mjs$/;
56
57 export interface WorkerdPrerendererOptions {
58 /** `config.build.server` — the prerender build lives in `.prerender/` inside it. */
59 readonly serverDir: URL;
60 /** `config.build.client` — served as the worker's assets directory. */
61 readonly clientDir: URL;
62 /** `config.trailingSlash` — needed to serialize route data for the protocol. */
63 readonly trailingSlash: AstroConfig["trailingSlash"];
64 /**
65 * The integration's `@alchemy.run/cloudflare-runtime/vite` options: the
66 * prerender worker reuses the entry worker's name, bindings, assets
67 * options, compatibility settings, and (optionally) runtime context.
68 */
69 readonly vite?: CloudflareVitePluginOptions | undefined;
70 }
71
72 /**
73 * Creates the workerd prerenderer registered via `setPrerenderer` in the
74 * `astro:build:start` hook when `prerenderEnvironment` is `"workerd"`.
75 */
76 export function createWorkerdPrerenderer(options: WorkerdPrerendererOptions): AstroPrerenderer {
77 const { serverDir, clientDir, trailingSlash, vite } = options;
78 let scope: Scope.Closeable | undefined;
79 let serverUrl: string | undefined;
80
81 const origin = (): string => {
82 if (serverUrl === undefined) {
83 throw new Error(
84 "The workerd prerender server is not running. " +
85 "This is a bug in @alchemy.run/frontend-frameworks/astro — `setup()` must run before the prerender protocol is driven.",
86 );
87 }
88 return serverUrl;
89 };
90
91 return {
92 name: "@alchemy.run/frontend-frameworks/astro:workerd-prerenderer",
93
94 async setup() {
95 const prerenderDir = fileURLToPath(new URL(PRERENDER_OUTPUT_SUBDIR, serverDir));
96 const clientDirPath = fileURLToPath(clientDir);
97 // The assets manifest is read from the client dir; make sure it exists
98 // even for all-prerendered sites where the client build emitted nothing.
99 await NodeFs.mkdir(clientDirPath, { recursive: true });
100 const modules = await collectOutputModules(prerenderDir);
101
102 scope = Scope.makeUnsafe();
103 const context = vite?.context ?? (await buildDefaultContext(scope));
104 const worker = vite?.worker;
105
106 const compatibilityDate = vite?.compatibilityDate ?? DEFAULT_COMPATIBILITY_DATE;
107 const program = Effect.gen(function* () {
108 const runtime = yield* Runtime.Runtime;
109 return yield* runtime.start({
110 ...worker,
111 // Suffixed so the prerender instance never collides with a
112 // concurrently running dev server in the local dev registry.
113 name: worker?.name !== undefined ? `${worker.name}-prerender` : "astro-prerender",
114 compatibilityDate,
115 // The render scope installed per prerender request imports
116 // `node:async_hooks`, so make sure AsyncLocalStorage is available
117 // even when the user's flags don't enable it (upstream does the same).
118 compatibilityFlags: withAsyncLocalStorage(
119 vite?.compatibilityFlags ?? [],
120 compatibilityDate,
121 ),
122 bindings: (worker?.bindings ?? []) as BindingHooks,
123 modules,
124 assets: {
125 ...worker?.assets,
126 directory: worker?.assets?.directory ?? clientDirPath,
127 },
128 });
129 });
130
131 const url = await program.pipe(
132 Effect.provide(context as Context.Context<RuntimeServices.RuntimeServices>),
133 Scope.provide(scope),
134 Effect.runPromise,
135 );
136 serverUrl = url.origin;
137 },
138
139 async getStaticPaths(): Promise<StaticPathsResult> {
140 const response = await fetch(`${origin()}${STATIC_PATHS_ENDPOINT}`, {
141 method: "POST",
142 headers: { "Content-Type": "application/json" },
143 });
144
145 if (!response.ok) {
146 const body = await response.text();
147 const details = body ? `\n${body}` : "";
148 throw new Error(
149 `Failed to get static paths from the workerd prerender server (${response.status}: ${response.statusText}).${details}`,
150 );
151 }
152
153 const data = (await response.json()) as StaticPathsResponse;
154 const paths = data.paths.map(({ pathname, route, cacheKey }) => ({
155 pathname,
156 route: deserializeRouteData(route),
157 cacheKey,
158 }));
159 return { paths, metadata: data.metadata };
160 },
161
162 async render(request, { routeData }) {
163 const body: PrerenderRequest = {
164 url: request.url,
165 routeData: serializeRouteData(routeData, trailingSlash),
166 };
167
168 const response = await fetch(`${origin()}${PRERENDER_ENDPOINT}`, {
169 method: "POST",
170 headers: { "Content-Type": "application/json" },
171 body: JSON.stringify(body),
172 redirect: "manual",
173 });
174
175 // Only the header marks a failure: pages may intentionally return
176 // non-2xx responses while prerendering (e.g. a custom 404 page).
177 const prerenderError = response.headers.get("x-astro-prerender-error");
178 if (prerenderError) {
179 throw new Error(`Failed to prerender ${request.url}: ${prerenderError}`);
180 }
181
182 return readFramedPrerenderResponse(response);
183 },
184
185 async teardown() {
186 serverUrl = undefined;
187 if (scope === undefined) return;
188 const closing = scope;
189 scope = undefined;
190 await Effect.runPromiseExit(Scope.closeUnsafe(closing, Exit.void) ?? Effect.void);
191 },
192 };
193 }
194
195 /**
196 * Loads the prerender environment's build output from disk as workerd
197 * modules. Module names are output-relative POSIX paths, so the bundle's
198 * relative chunk imports (`./chunks/*.mjs`) resolve natively in workerd; the
199 * entry chunk (astro core names it `prerender-entry.[hash].mjs`) is listed
200 * first, which makes it the worker's main module.
201 */
202 export const collectOutputModules = async (outputDir: string): Promise<Array<Module>> => {
203 let entries: Array<{
204 parentPath: string;
205 name: string;
206 isFile: () => boolean;
207 }>;
208 try {
209 entries = await NodeFs.readdir(outputDir, {
210 recursive: true,
211 withFileTypes: true,
212 });
213 } catch (cause) {
214 throw new Error(
215 `Failed to read the prerender build output at "${outputDir}". ` +
216 "The workerd prerenderer requires the `prerender` environment to have been built first.",
217 { cause },
218 );
219 }
220 const modules: Array<Module> = [];
221 for (const entry of entries) {
222 if (!entry.isFile()) continue;
223 const absolute = NodePath.join(entry.parentPath, entry.name);
224 const relative = NodePath.relative(outputDir, absolute);
225 const module = await moduleForFile(absolute, relative);
226 if (module !== undefined) modules.push(module);
227 }
228 // Deterministic order, entry first.
229 modules.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
230 const entryIndex = modules.findIndex((module) => PRERENDER_ENTRY_PATTERN.test(module.name));
231 if (entryIndex === -1) {
232 throw new Error(
233 `No prerender entry chunk (prerender-entry.*.mjs) found in "${outputDir}". ` +
234 "This is a bug in @alchemy.run/frontend-frameworks/astro — the prerender environment should have built the worker server entrypoint.",
235 );
236 }
237 const [entryModule] = modules.splice(entryIndex, 1);
238 modules.unshift(entryModule);
239 return modules;
240 };
241
242 const TEXT_EXTENSIONS = new Set([".css", ".html", ".svg", ".txt", ".xml"]);
243
244 const moduleForFile = async (absolute: string, relative: string): Promise<Module | undefined> => {
245 const extension = NodePath.extname(relative).toLowerCase();
246 if (extension === ".map") return undefined;
247 const name = relative.split(NodePath.sep).join("/");
248 switch (extension) {
249 case ".js":
250 case ".mjs":
251 return {
252 name,
253 type: "ESModule",
254 content: await NodeFs.readFile(absolute, "utf8"),
255 };
256 case ".cjs":
257 return {
258 name,
259 type: "CommonJsModule",
260 content: await NodeFs.readFile(absolute, "utf8"),
261 };
262 case ".json":
263 return {
264 name,
265 type: "Json",
266 content: await NodeFs.readFile(absolute, "utf8"),
267 };
268 case ".wasm":
269 return {
270 name,
271 type: "Wasm",
272 content: new Uint8Array(await NodeFs.readFile(absolute)),
273 };
274 default:
275 return TEXT_EXTENSIONS.has(extension)
276 ? {
277 name,
278 type: "Text",
279 content: await NodeFs.readFile(absolute, "utf8"),
280 }
281 : {
282 name,
283 type: "Data",
284 content: new Uint8Array(await NodeFs.readFile(absolute)),
285 };
286 }
287 };
288
289 /**
290 * The default runtime context, mirroring the Cloudflare vite plugin's dev
291 * server (`createDefaultContext`): the full `layerRuntime` stack, so local
292 * AND remote bindings behave identically to `astro dev`. Built into the
293 * prerenderer's scope so `teardown()` disposes everything (including the
294 * workerd process).
295 */
296 const buildDefaultContext = (
297 scope: Scope.Scope,
298 ): Promise<Context.Context<RuntimeServices.RuntimeServices>> =>
299 RuntimeServices.layerRuntime({
300 api: {
301 accountId: process.env.CLOUDFLARE_ACCOUNT_ID!,
302 },
303 }).pipe(
304 Layer.provideMerge(PlatformServices),
305 Layer.provide(Layer.merge(Credentials.fromEnv(), FetchHttpClient.layer)),
306 Layer.buildWithScope(scope),
307 Effect.runPromise,
308 );
309
310 /**
311 * Adds `nodejs_als` unless Node compat already provides AsyncLocalStorage,
312 * either through a flag or because the compatibility date turns it on.
313 */
314 export const withAsyncLocalStorage = (
315 flags: ReadonlyArray<string>,
316 compatibilityDate: string,
317 ): Array<string> =>
318 hasNodejsCompat(flags, compatibilityDate) || hasNodejsAls(flags)
319 ? [...flags]
320 : [...flags, "nodejs_als"];