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

main
ts 177 lines 6.53 KB
Raw
1 import type * as vite from "vite";
2 import { assert, describe, expect, it, vi } from "vitest";
3 import { parseViteEnvironments, type BasePluginOptions } from "../options.ts";
4 import {
5 cloudflareExternalsPlugin,
6 nodejsUnenvPlugin,
7 optionsPlugin,
8 virtualModulesPlugin,
9 } from "../plugins/index.ts";
10
11 const applyToEnvironment = (plugin: vite.Plugin | null, name: string) => {
12 assert(plugin, "plugin is not defined");
13 assert(
14 typeof plugin.applyToEnvironment === "function",
15 "plugin.applyToEnvironment is not a function",
16 );
17 return plugin.applyToEnvironment.call(
18 plugin as never,
19 { name } as unknown as Parameters<typeof plugin.applyToEnvironment>[0],
20 );
21 };
22
23 const callConfigEnvironment = (plugin: vite.Plugin | null, name: string) => {
24 assert(plugin, "plugin is not defined");
25 const hook = plugin.configEnvironment;
26 assert(hook, "plugin.configEnvironment is not defined");
27 const handler = typeof hook === "function" ? hook : hook.handler;
28 return handler.call(
29 { meta: {} } as never,
30 name,
31 {} as never,
32 { command: "serve", mode: "development" } as never,
33 );
34 };
35
36 describe("skipEnvironments", () => {
37 const options: BasePluginOptions = {
38 compatibilityDate: "2025-07-01",
39 compatibilityFlags: ["nodejs_compat"],
40 skipEnvironments: ["prerender", "astro"],
41 };
42
43 it("excludes skipped environments (and client) from every per-environment plugin", () => {
44 for (const factory of [
45 optionsPlugin,
46 cloudflareExternalsPlugin,
47 nodejsUnenvPlugin,
48 virtualModulesPlugin,
49 ]) {
50 const plugin = factory.vite(options);
51 expect(applyToEnvironment(plugin, "ssr")).toBe(true);
52 expect(applyToEnvironment(plugin, "client")).toBe(false);
53 expect(applyToEnvironment(plugin, "prerender")).toBe(false);
54 expect(applyToEnvironment(plugin, "astro")).toBe(false);
55 }
56 });
57
58 it("gates configEnvironment away from skipped environments", async () => {
59 const plugin = nodejsUnenvPlugin.vite(options);
60 expect(await callConfigEnvironment(plugin, "prerender")).toBeUndefined();
61 expect(await callConfigEnvironment(plugin, "astro")).toBeUndefined();
62 const ssr = await callConfigEnvironment(plugin, "ssr");
63 expect(ssr).toBeDefined();
64 expect((ssr as { resolve?: { builtins?: unknown } }).resolve?.builtins).toBeDefined();
65 });
66
67 it("keeps the client environment's special configEnvironment handling", async () => {
68 const plugin = cloudflareExternalsPlugin.vite(options);
69 expect(await callConfigEnvironment(plugin, "prerender")).toBeUndefined();
70 const client = (await callConfigEnvironment(plugin, "client")) as {
71 optimizeDeps?: { exclude?: Array<string> };
72 };
73 expect(client?.optimizeDeps?.exclude).toContain("cloudflare:workers");
74 });
75
76 it("rejects worker environments listed in skipEnvironments", () => {
77 expect(() => parseViteEnvironments({ skipEnvironments: ["ssr"] })).toThrowError(
78 /cannot be both a worker environment/,
79 );
80 expect(() =>
81 parseViteEnvironments({
82 viteEnvironments: { entry: "rsc", children: ["ssr"] },
83 skipEnvironments: ["ssr"],
84 }),
85 ).toThrowError(/cannot be both a worker environment/);
86 expect(() =>
87 parseViteEnvironments({
88 viteEnvironments: { entry: "rsc", children: ["ssr"] },
89 skipEnvironments: ["prerender"],
90 }),
91 ).not.toThrow();
92 });
93
94 it("tolerates environments whose optimizer does not support registerMissingImport", async () => {
95 const plugin = nodejsUnenvPlugin.vite(options);
96 assert(plugin, "plugin is not defined");
97 const configureServer = plugin.configureServer;
98 assert(typeof configureServer === "function", "configureServer is not a function");
99
100 const registered: Array<string> = [];
101 const makeEnvironment = (
102 name: string,
103 { noDiscovery = false, throws = false }: { noDiscovery?: boolean; throws?: boolean } = {},
104 ) => ({
105 name,
106 config: { optimizeDeps: { noDiscovery } },
107 depsOptimizer: {
108 init: async () => {},
109 registerMissingImport: (id: string) => {
110 if (throws) {
111 throw new Error(`registerMissingImport is not supported in dev ${name}`);
112 }
113 registered.push(`${name}:${id}`);
114 return { id, processing: Promise.resolve() };
115 },
116 },
117 });
118 const server = {
119 environments: {
120 ssr: makeEnvironment("ssr"),
121 // Vite's no-discovery ("explicit") optimizer throws by design.
122 prerender: makeEnvironment("prerender", {
123 noDiscovery: true,
124 throws: true,
125 }),
126 // Skipped environments must not be touched even if their optimizer
127 // looks usable.
128 astro: makeEnvironment("astro", { throws: true }),
129 client: makeEnvironment("client", { throws: true }),
130 // Environments without an optimizer are skipped.
131 bare: {
132 name: "bare",
133 config: { optimizeDeps: {} },
134 depsOptimizer: undefined,
135 },
136 },
137 };
138
139 await expect(configureServer.call(plugin as never, server as never)).resolves.not.toThrow();
140 expect(registered.length).toBeGreaterThan(0);
141 expect(registered.every((entry) => entry.startsWith("ssr:"))).toBe(true);
142 });
143
144 it("skips the dependency optimizer in resolveId when discovery is disabled", async () => {
145 const plugin = nodejsUnenvPlugin.vite(options);
146 assert(plugin, "plugin is not defined");
147 const hook = plugin.resolveId;
148 assert(hook && typeof hook === "object" && "handler" in hook, "resolveId is not a hook");
149 const registerMissingImport = vi.fn(() => {
150 throw new Error("registerMissingImport is not supported in dev prerender");
151 });
152 const resolve = vi.fn(async (id: string) => ({ id }));
153 const context = {
154 environment: {
155 mode: "dev",
156 config: { optimizeDeps: { noDiscovery: true } },
157 depsOptimizer: { registerMissingImport },
158 },
159 resolve,
160 };
161 // `node:child_process` is polyfilled by unenv (workerd cannot spawn
162 // processes), so the plugin resolves it rather than externalizing it.
163 await (
164 hook.handler as unknown as (
165 this: typeof context,
166 source: string,
167 importer: string | undefined,
168 options: object,
169 ) => Promise<unknown>
170 ).call(context, "node:child_process", undefined, {});
171 expect(registerMissingImport).not.toHaveBeenCalled();
172 // Falls back to resolving the polyfill directly instead of pre-bundling it.
173 expect(resolve).toHaveBeenCalledTimes(1);
174 const [resolvedPath] = resolve.mock.calls[0] ?? [];
175 expect(resolvedPath).not.toBe("node:child_process");
176 });
177 });