@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, 04:45 UTC

main
ts 73 lines 2.72 KB
Raw
1 import { splitFileAndPostfix } from "alchemy/Bundle/RawPlugin";
2 /**
3 * `import source from "./hasher.ts?worker"` — the target is bundled into
4 * one self-contained ES module (the same Cloudflare-flavored build the
5 * parent gets: workerd externals, node builtins, Alchemy defines) and
6 * imported as a **string**, ready to hand to a `WorkerLoader`
7 * (`modules: { "worker.js": source }`). Nested `?worker` imports inside
8 * the target work the same way.
9 *
10 * Bundling happens at build time, so the string is fixed per deploy; the
11 * dynamic worker it becomes is then instantiated at runtime as many times
12 * as the caller wants.
13 */
14 import type * as rolldown from "rolldown";
15
16 export const WORKER_MODULE_RE: RegExp = /(\?|&)worker(?:&|$)/;
17
18 export const workerModulePlugin = (options: {
19 /**
20 * The nested build's input options (plugins, externals, cwd) for a given
21 * entry; `input` is set by the plugin. Built lazily per import.
22 */
23 readonly nested: (entry: string) => Promise<rolldown.InputOptions>;
24 readonly loadRolldown: () => Promise<typeof import("rolldown")>;
25 }): rolldown.Plugin => ({
26 name: "alchemy:worker-module",
27 resolveId: {
28 filter: { id: WORKER_MODULE_RE },
29 async handler(source, importer) {
30 const [base, query] = splitFileAndPostfix(source);
31 const resolved = await this.resolve(base, importer, { skipSelf: true });
32 if (!resolved || resolved.external) return null;
33 return { id: resolved.id + query, moduleSideEffects: false };
34 },
35 },
36 load: {
37 filter: { id: WORKER_MODULE_RE },
38 async handler(id) {
39 const entry = id.replace(/[?#].*$/, "");
40 this.addWatchFile(entry);
41 const rolldownLib = await options.loadRolldown();
42 const input = await options.nested(entry);
43 const bundle = await rolldownLib.rolldown({ ...input, input: entry });
44 try {
45 const { output } = await bundle.generate({
46 format: "esm",
47 minify: true,
48 keepNames: true,
49 inlineDynamicImports: true,
50 sourcemap: false,
51 });
52 const chunk = output.find((item) => item.type === "chunk" && item.isEntry);
53 if (chunk === undefined || chunk.type !== "chunk") {
54 throw new Error(`worker module ${entry}: no entry chunk produced`);
55 }
56 for (const item of output) {
57 if (item.type === "chunk" && item !== chunk) {
58 throw new Error(
59 `worker module ${entry}: produced a second chunk (${item.fileName}); a dynamic worker is one module`,
60 );
61 }
62 }
63 return {
64 code: `export default ${JSON.stringify(chunk.code)};`,
65 map: { mappings: "" },
66 moduleType: "js",
67 };
68 } finally {
69 await bundle.close();
70 }
71 },
72 },
73 });