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

main
ts 163 lines 6.29 KB
Raw
1 import * as NodeFsPromises from "node:fs/promises";
2 import * as NodeOs from "node:os";
3 import * as NodePath from "node:path";
4 import { WORKER_ENTRY_PREFIX } from "@alchemy.run/cloudflare-runtime/rolldown/plugins";
5 import type * as ViteModule from "vite";
6 import { afterEach, describe, expect, it } from "vitest";
7 import { makeIntegrationPluginOptions, SERVER_ENTRYPOINT } from "../cloudflare.ts";
8 import { createWorkerdPrerenderEnvironmentPlugin } from "../prerender-environment.ts";
9 import { collectOutputModules, withAsyncLocalStorage } from "../prerenderer.ts";
10
11 describe("makeIntegrationPluginOptions (workerd prerendering)", () => {
12 it("promotes prerender to a child worker environment during a workerd build", () => {
13 const options = makeIntegrationPluginOptions(undefined, {
14 prerenderEnvironment: "workerd",
15 command: "build",
16 });
17 expect(options.viteEnvironments).toEqual({
18 entry: "ssr",
19 children: ["prerender"],
20 });
21 expect(options.skipEnvironments).toEqual(["astro"]);
22 });
23
24 it("filters a user-supplied prerender skip during a workerd build", () => {
25 const options = makeIntegrationPluginOptions(
26 { skipEnvironments: ["custom", "prerender"] },
27 { prerenderEnvironment: "workerd", command: "build" },
28 );
29 expect(options.viteEnvironments).toEqual({
30 entry: "ssr",
31 children: ["prerender"],
32 });
33 expect(options.skipEnvironments).toEqual(["astro", "custom"]);
34 });
35
36 it("keeps prerender skipped in dev and in node mode", () => {
37 for (const args of [
38 { prerenderEnvironment: "workerd", command: "dev" },
39 { prerenderEnvironment: "workerd", command: "sync" },
40 { prerenderEnvironment: "node", command: "build" },
41 ] as const) {
42 const options = makeIntegrationPluginOptions(undefined, args);
43 expect(options.viteEnvironments).toEqual({ entry: "ssr" });
44 expect(options.skipEnvironments).toEqual(["astro", "prerender"]);
45 }
46 });
47 });
48
49 describe("createWorkerdPrerenderEnvironmentPlugin", () => {
50 const configEnvironment = (plugin: ViteModule.Plugin, name: string): unknown => {
51 const hook = plugin.configEnvironment;
52 const handler = typeof hook === "function" ? hook : hook?.handler;
53 if (!handler) throw new Error("configEnvironment hook missing");
54 return handler.call(undefined as never, name, {} as never, {} as never);
55 };
56
57 it("assigns the worker-wrapped server entrypoint as the prerender build input", () => {
58 const plugin = createWorkerdPrerenderEnvironmentPlugin(SERVER_ENTRYPOINT);
59 expect(plugin.apply).toBe("build");
60 expect(configEnvironment(plugin, "prerender")).toEqual({
61 build: {
62 rolldownOptions: {
63 input: `${WORKER_ENTRY_PREFIX}${SERVER_ENTRYPOINT}`,
64 },
65 },
66 });
67 });
68
69 it("leaves every other environment untouched", () => {
70 const plugin = createWorkerdPrerenderEnvironmentPlugin(SERVER_ENTRYPOINT);
71 for (const name of ["ssr", "client", "astro"]) {
72 expect(configEnvironment(plugin, name)).toBeUndefined();
73 }
74 });
75 });
76
77 describe("collectOutputModules", () => {
78 let dir: string | undefined;
79
80 const makeOutputDir = async (files: Record<string, string | Uint8Array>): Promise<string> => {
81 dir = await NodeFsPromises.mkdtemp(NodePath.join(NodeOs.tmpdir(), "astro-prerender-test-"));
82 for (const [relative, content] of Object.entries(files)) {
83 const absolute = NodePath.join(dir, relative);
84 await NodeFsPromises.mkdir(NodePath.dirname(absolute), {
85 recursive: true,
86 });
87 await NodeFsPromises.writeFile(absolute, content);
88 }
89 return dir;
90 };
91
92 afterEach(async () => {
93 if (dir !== undefined) {
94 await NodeFsPromises.rm(dir, { recursive: true, force: true });
95 dir = undefined;
96 }
97 });
98
99 it("loads the output with the prerender entry chunk first", async () => {
100 const output = await makeOutputDir({
101 "prerender-entry.C3POR2D2.mjs": "export default {};",
102 "chunks/page_abc.mjs": "export const page = 1;",
103 "chunks/zzz_last.mjs": "export const z = 1;",
104 "chunks/page_abc.mjs.map": "{}",
105 "_astro/styles.css": "body {}",
106 "manifest.json": "{}",
107 "data.bin": new Uint8Array([1, 2, 3]),
108 });
109 const modules = await collectOutputModules(output);
110 expect(modules[0]).toMatchObject({
111 name: "prerender-entry.C3POR2D2.mjs",
112 type: "ESModule",
113 });
114 const byName = new Map(modules.map((module) => [module.name, module]));
115 expect(byName.get("chunks/page_abc.mjs")).toMatchObject({
116 type: "ESModule",
117 });
118 expect(byName.get("_astro/styles.css")).toMatchObject({ type: "Text" });
119 expect(byName.get("manifest.json")).toMatchObject({ type: "Json" });
120 expect(byName.get("data.bin")).toMatchObject({ type: "Data" });
121 // Sourcemaps are never shipped to workerd.
122 expect(byName.has("chunks/page_abc.mjs.map")).toBe(false);
123 // Deterministic ordering after the entry.
124 expect(modules.map((module) => module.name).slice(1)).toEqual(
125 [...byName.keys()].filter((name) => !name.startsWith("prerender-entry.")).sort(),
126 );
127 });
128
129 it("fails with a clear error when the entry chunk is missing", async () => {
130 const output = await makeOutputDir({
131 "chunks/page_abc.mjs": "export const page = 1;",
132 });
133 await expect(collectOutputModules(output)).rejects.toThrow(/prerender-entry/);
134 });
135
136 it("fails with a clear error when the output directory does not exist", async () => {
137 await expect(collectOutputModules("/nonexistent/prerender-output")).rejects.toThrow(
138 /prerender build output/,
139 );
140 });
141 });
142
143 describe("withAsyncLocalStorage", () => {
144 it("adds nodejs_als before Node compat is on by default", () => {
145 expect(withAsyncLocalStorage([], "2026-03-10")).toEqual(["nodejs_als"]);
146 });
147
148 it("leaves flags alone when the compatibility date turns Node compat on", () => {
149 expect(withAsyncLocalStorage([], "2026-08-31")).toEqual([]);
150 });
151
152 it("leaves flags alone when a flag already provides AsyncLocalStorage", () => {
153 expect(withAsyncLocalStorage(["nodejs_compat"], "2026-03-10")).toEqual(["nodejs_compat"]);
154 expect(withAsyncLocalStorage(["nodejs_als"], "2026-03-10")).toEqual(["nodejs_als"]);
155 });
156
157 it("adds nodejs_als when Node compat is opted out", () => {
158 expect(withAsyncLocalStorage(["no_nodejs_compat"], "2026-08-31")).toEqual([
159 "no_nodejs_compat",
160 "nodejs_als",
161 ]);
162 });
163 });