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

main
ts 116 lines 4.48 KB
Raw
1 import {
2 EXPORT_TYPES_MODULE_ID,
3 exportTypesModuleSource,
4 RESOLVED_EXPORT_TYPES_MODULE_ID,
5 WORKER_EXPORT_TYPES_EVENT,
6 } from "../export-types.ts";
7 import { createPlugin } from "../factory.ts";
8 import { resolvePluginApi } from "../utils.ts";
9 import type { UnenvApi } from "./nodejs-compat.ts";
10
11 // The export-types module is the one virtual module that is imported by
12 // specifier (both from the Worker entry and, in dev, by the module runner), so
13 // the filter has to match it before it has been resolved to its `\0` id.
14 const VIRTUAL_MODULE_REGEXP = /^\0?distilled:.*$/;
15
16 export const WORKER_ENTRY_PREFIX = "\0distilled:worker-entry:" as const;
17 const USER_ENTRY_PREFIX = "\0distilled:user-entry:" as const;
18 const INJECT_PREFIX = "\0distilled:inject:" as const;
19 const NODEJS_UNENV_PLUGIN_NAME = "distilled-cloudflare:nodejs-unenv";
20
21 /**
22 * The id of the generated Worker entry that wraps the user entry `id`.
23 *
24 * Entry ids are embedded into the specifier and round-tripped through
25 * Rolldown/Vite id handling, which expects POSIX-style separators. On Windows
26 * the input is an absolute path with `\` separators (e.g. `D:\app\entry.ts`),
27 * which would corrupt the virtual id and break resolution. Normalizing to
28 * forward slashes is a no-op on POSIX, where ids already use `/`.
29 */
30 export const workerEntryId = (id: string) =>
31 `${WORKER_ENTRY_PREFIX}${id.replace(/\\/g, "/")}` as const;
32
33 export const virtualModulesPlugin = createPlugin("virtual-modules", (options) => {
34 let unenvApi: UnenvApi | undefined;
35 const inject = () => {
36 if (!unenvApi) return [];
37 return [
38 ...unenvApi.polyfill.map((module) => `import "${module}";`),
39 ...Object.keys(unenvApi.inject).map(
40 (injectedName) => `import "${INJECT_PREFIX}${injectedName}";`,
41 ),
42 ];
43 };
44 return {
45 vite: {
46 enforce: "pre",
47 // Vite's dev server starts the build without the plugin list, so the
48 // Worker entry would skip the polyfills and injected globals.
49 configResolved(config) {
50 unenvApi = resolvePluginApi<UnenvApi>(config.plugins, NODEJS_UNENV_PLUGIN_NAME);
51 },
52 },
53 shared: {
54 buildStart({ plugins }) {
55 unenvApi = resolvePluginApi<UnenvApi>(plugins ?? [], NODEJS_UNENV_PLUGIN_NAME) ?? unenvApi;
56 },
57 resolveId: {
58 filter: { id: VIRTUAL_MODULE_REGEXP },
59 handler(id) {
60 if (id === EXPORT_TYPES_MODULE_ID || id === RESOLVED_EXPORT_TYPES_MODULE_ID) {
61 return { id: RESOLVED_EXPORT_TYPES_MODULE_ID };
62 }
63 if (id.startsWith(WORKER_ENTRY_PREFIX) || id.startsWith(INJECT_PREFIX)) {
64 return { id };
65 }
66 if (id.startsWith(USER_ENTRY_PREFIX)) {
67 return this.resolve(id.slice(USER_ENTRY_PREFIX.length), undefined, {
68 isEntry: true,
69 kind: "import-statement",
70 });
71 }
72 },
73 },
74 load: {
75 filter: { id: VIRTUAL_MODULE_REGEXP },
76 handler(id) {
77 if (id.startsWith(WORKER_ENTRY_PREFIX)) {
78 const userEntryId = id.replace(WORKER_ENTRY_PREFIX, USER_ENTRY_PREFIX);
79
80 return [
81 ...inject(),
82 ...(options.exports
83 ? [`export { ${options.exports.join(", ")} } from "${userEntryId}";`]
84 : [
85 `import * as userEntry from "${userEntryId}";`,
86 `export * from "${userEntryId}";`,
87 `export default userEntry.default ?? {};`,
88 ]),
89 "if (import.meta.hot) {",
90 ` const { getExportTypes } = await import("${EXPORT_TYPES_MODULE_ID}");`,
91 " import.meta.hot.accept((module) => {",
92 " const exportTypes = getExportTypes(module);",
93 ` import.meta.hot.send("${WORKER_EXPORT_TYPES_EVENT}", exportTypes);`,
94 " });",
95 "}",
96 ].join("\n");
97 }
98 if (id === RESOLVED_EXPORT_TYPES_MODULE_ID) {
99 return exportTypesModuleSource;
100 }
101 if (id.startsWith(INJECT_PREFIX)) {
102 const injectedName = id.slice(INJECT_PREFIX.length);
103 const moduleSpecifier = unenvApi?.inject[injectedName];
104 if (!moduleSpecifier) {
105 throw new Error(`Expected module specifier for "${injectedName}" to be defined`);
106 }
107 return [
108 `import ${injectedName} from "${moduleSpecifier}";`,
109 `globalThis.${injectedName} = ${injectedName};`,
110 ].join("\n");
111 }
112 },
113 },
114 },
115 };
116 });