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

main
ts 314 lines 11.4 KB
Raw
1 import assert from "node:assert";
2 import { createRequire } from "node:module";
3 import path from "node:path";
4 import { getCloudflarePreset, nonPrefixedNodeModules } from "@cloudflare/unenv-preset";
5 import { defineEnv } from "unenv";
6 import { createPlugin } from "../factory.ts";
7 import { isSkippedEnvironment } from "../options.ts";
8 import type { BasePluginOptions } from "../options.ts";
9 import { hasNodejsAls, hasNodejsCompat, toPosixPath } from "../utils.ts";
10
11 const ASYNC_HOOKS_REGEXP = /^(node:)?async_hooks$/;
12 const NODE_BUILTIN_MODULES_REGEXP = new RegExp(`^(${nonPrefixedNodeModules.join("|")}|node:.+)$`);
13
14 export const nodejsAlsPlugin = createPlugin("nodejs-als", (options) => {
15 if (!hasNodejsAls(options.compatibilityFlags)) return;
16 return {
17 rolldown: {
18 resolveId: {
19 filter: { id: ASYNC_HOOKS_REGEXP },
20 handler(id) {
21 return { id, external: true };
22 },
23 },
24 },
25 vite: {
26 enforce: "pre",
27 configEnvironment(name) {
28 if (name === "client") return;
29 return {
30 resolve: {
31 builtins: ["async_hooks", "node:async_hooks"],
32 },
33 optimizeDeps: {
34 exclude: ["async_hooks", "node:async_hooks"],
35 },
36 };
37 },
38 },
39 };
40 });
41
42 export interface UnenvApi {
43 polyfill: ReadonlyArray<string>;
44 inject: { [injectedName: string]: string };
45 }
46
47 export const getUnenv = (options: BasePluginOptions) =>
48 defineEnv({
49 presets: [
50 getCloudflarePreset({
51 compatibilityDate: options.compatibilityDate,
52 compatibilityFlags: options.compatibilityFlags,
53 }),
54 ],
55 }).env;
56
57 export const nodejsUnenvPlugin = createPlugin<"nodejs-unenv", UnenvApi>(
58 "nodejs-unenv",
59 (options) => {
60 if (!hasNodejsCompat(options.compatibilityFlags, options.compatibilityDate)) return;
61 const { alias, inject, polyfill, external } = getUnenv(options);
62 const entries = new Set(Object.values(alias));
63 for (const globalInject of Object.values(inject)) {
64 if (typeof globalInject === "string") {
65 entries.add(globalInject);
66 } else {
67 entries.add(globalInject[0]);
68 }
69 }
70 polyfill.forEach((module) => entries.add(module));
71 external.forEach((module) => entries.delete(module));
72 const require = createRequire(import.meta.url);
73 // `unresolved` is the polyfill's bare specifier: the key it is
74 // pre-bundled under, shared by every import that aliases to it.
75 const resolveNodejsImport = (id: string) => {
76 if (alias[id] && !external.includes(alias[id])) {
77 return { unresolved: alias[id], resolved: require.resolve(alias[id]) };
78 }
79 if (entries.has(id)) {
80 return { unresolved: id, resolved: require.resolve(id) };
81 }
82 };
83 const RESOLVE_ID_FILTER = {
84 id: [NODE_BUILTIN_MODULES_REGEXP, /^unenv\//, /^@cloudflare\/unenv-preset\//],
85 };
86 return {
87 shared: {
88 api: {
89 // Virtual entries have no package directory for bare-import resolution.
90 polyfill: polyfill.map((id) => toPosixPath(require.resolve(id))),
91 inject: Object.fromEntries(
92 Object.entries(inject).map(([injectedName, moduleSpecifier]) => {
93 assert(
94 typeof moduleSpecifier === "string",
95 `expected moduleSpecifier to be a string`,
96 );
97 return [injectedName, toPosixPath(require.resolve(moduleSpecifier))];
98 }),
99 ),
100 },
101 },
102 rolldown: {
103 resolveId: {
104 filter: RESOLVE_ID_FILTER,
105 handler(source, importer, options) {
106 const result = resolveNodejsImport(source);
107 if (!result) return;
108 return this.resolve(result.resolved, importer, options);
109 },
110 },
111 },
112 vite: {
113 enforce: "pre",
114 async configEnvironment(name) {
115 if (name === "client") return;
116 const { esmExternalRequirePlugin } = await import("vite");
117 return {
118 resolve: {
119 builtins: [...external],
120 },
121 ...(this.meta.rolldownVersion
122 ? {
123 build: {
124 rolldownOptions: {
125 plugins: [
126 esmExternalRequirePlugin({
127 external: [...external],
128 skipDuplicateCheck: true,
129 }),
130 ],
131 },
132 },
133 }
134 : {}),
135 // (Node.js built-ins are excluded from pre-bundling for every
136 // Worker environment by the options plugin.)
137 optimizeDeps: this.meta.rolldownVersion
138 ? {
139 rolldownOptions: {
140 plugins: [
141 // In Vite 8, `require` calls are not automatically replaced when
142 // the format is ESM and `platform` is `neutral`.
143 esmExternalRequirePlugin({
144 external: [NODE_BUILTIN_MODULES_REGEXP],
145 skipDuplicateCheck: true,
146 }),
147 ],
148 },
149 }
150 : {},
151 };
152 },
153 async configureServer(server) {
154 await Promise.all(
155 Object.values(server.environments).flatMap(async (environment) => {
156 // Framework-owned Node-side environments (e.g. Astro's `astro`
157 // and `prerender`) must be left untouched — this is a
158 // server-level hook, so `applyToEnvironment` cannot gate it.
159 if (isSkippedEnvironment(options, environment.name)) return;
160 const depsOptimizer = environment.depsOptimizer;
161 if (!depsOptimizer) return;
162 // Environments using Vite's no-discovery ("explicit") optimizer
163 // throw on `registerMissingImport` by design; pre-bundling the
164 // unenv polyfills is best-effort, so skip them.
165 if (!supportsMissingImportRegistration(environment)) return;
166 await depsOptimizer.init();
167 return Array.from(entries).map((entry) => {
168 const result = resolveNodejsImport(entry);
169 if (!result) return;
170 const registration = depsOptimizer.registerMissingImport(
171 result.unresolved,
172 result.resolved,
173 );
174 return registration?.processing;
175 });
176 }),
177 );
178 },
179 resolveId: {
180 filter: RESOLVE_ID_FILTER,
181 handler(source, importer, options) {
182 const result = resolveNodejsImport(source);
183 if (!result) return;
184 if (
185 this.environment.mode === "dev" &&
186 this.environment.depsOptimizer &&
187 supportsMissingImportRegistration(this.environment)
188 ) {
189 // We are in dev mode (rather than build).
190 // So let's pre-bundle this polyfill entry-point using the dependency optimizer.
191 const { id } = this.environment.depsOptimizer.registerMissingImport(
192 result.unresolved,
193 result.resolved,
194 );
195 // We use the unresolved path to the polyfill and let the dependency optimizer's
196 // resolver find the resolved path to the bundled version.
197 return this.resolve(id, importer, options);
198 }
199 return this.resolve(result.resolved, importer, options);
200 },
201 },
202 },
203 };
204 },
205 );
206
207 /**
208 * Vite's no-discovery ("explicit") dependency optimizer throws on
209 * `registerMissingImport` by design, and third-party environments may not
210 * implement it at all. Feature-detect before registering polyfill entries.
211 */
212 const supportsMissingImportRegistration = (environment: {
213 config: { optimizeDeps?: { noDiscovery?: boolean } };
214 depsOptimizer?: { registerMissingImport?: unknown } | undefined;
215 }): boolean =>
216 environment.config.optimizeDeps?.noDiscovery !== true &&
217 typeof environment.depsOptimizer?.registerMissingImport === "function";
218
219 export const nodejsImportWarningPlugin = createPlugin("nodejs-import-warning", (options) => {
220 if (hasNodejsCompat(options.compatibilityFlags, options.compatibilityDate)) return;
221 const imports = new Map<string, Set<string>>();
222 let root = process.cwd();
223 // In dev there is no `buildEnd` until the server closes, so, as
224 // `@cloudflare/vite-plugin` does, warn once imports go quiet.
225 const devImports = new Map<string, Set<string>>();
226 let devTimer: ReturnType<typeof setTimeout> | undefined;
227 const warnInDev = (environment: {
228 name: string;
229 logger: { warn: (message: string, options?: { timestamp?: boolean }) => void };
230 }) => {
231 if (devTimer) clearTimeout(devTimer);
232 devTimer = setTimeout(() => {
233 devTimer = undefined;
234 if (devImports.size === 0) return;
235 let message = `Unexpected Node.js imports for environment "${environment.name}". Do you need to enable the "nodejs_compat" compatibility flag? Refer to https://developers.cloudflare.com/workers/runtime-apis/nodejs/ for more details.\n`;
236 for (const [id, importers] of devImports) {
237 for (const importer of importers) {
238 message += ` - "${id}" imported from "${toPosixPath(path.relative(root, importer))}"\n`;
239 }
240 }
241 devImports.clear();
242 environment.logger.warn(message, { timestamp: true });
243 }, 500);
244 };
245 return {
246 rolldown: {
247 options(options) {
248 if (options.cwd) {
249 root = options.cwd;
250 }
251 },
252 },
253 vite: {
254 enforce: "pre",
255 configResolved(config) {
256 root = config.root;
257 },
258 },
259 shared: {
260 buildStart() {
261 imports.clear();
262 },
263 resolveId: {
264 filter: { id: NODE_BUILTIN_MODULES_REGEXP },
265 async handler(id, importer) {
266 if (hasNodejsAls(options.compatibilityFlags) && ASYNC_HOOKS_REGEXP.test(id)) return;
267 if (importer) {
268 if (!imports.has(id)) {
269 imports.set(id, new Set());
270 }
271 imports.get(id)?.add(importer);
272 const environment = (
273 this as {
274 environment?: {
275 name: string;
276 mode: string;
277 logger: Parameters<typeof warnInDev>[0]["logger"];
278 };
279 }
280 ).environment;
281 if (environment?.mode === "dev") {
282 if (!devImports.has(id)) devImports.set(id, new Set());
283 devImports.get(id)?.add(importer);
284 warnInDev(environment);
285 }
286 }
287 return { id, external: true };
288 },
289 },
290 buildEnd() {
291 const filteredImports: Array<{ id: string; importer: string }> = [];
292 for (const [id, importers] of imports.entries()) {
293 for (const importer of importers) {
294 if (this.getModuleInfo(importer)) {
295 filteredImports.push({ id, importer });
296 }
297 }
298 }
299 if (filteredImports.length > 0) {
300 const message = [
301 "Unexpected Node.js imports. ",
302 'Do you need to enable the "nodejs_compat" compatibility flag? ',
303 "Refer to https://developers.cloudflare.com/workers/runtime-apis/nodejs/ for more details.\n",
304 ...filteredImports.map(
305 ({ id, importer }) =>
306 ` - "${id}" imported from "${toPosixPath(path.relative(root, importer))}"\n`,
307 ),
308 ].join("");
309 this.warn(message);
310 }
311 },
312 },
313 };
314 });