The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import type * as rolldown from "rolldown"; |
| 2 | |
| 3 | /** |
| 4 | * Drop the chunks no entry reaches, with their source maps, before the bundle |
| 5 | * is returned or written. |
| 6 | * |
| 7 | * Rolldown decides a dynamic chunk is live when the statement holding its |
| 8 | * `import()` is included, and a cycle can keep that true on its own: Vite's |
| 9 | * `node.js` sets up `createCachedImport(() => import("./build.js"))` at |
| 10 | * module level, and `build.js` imports `node.js` back. So a Worker that only |
| 11 | * reaches `import("vite")` through deploy-time code tree-shaking removes |
| 12 | * still got ~1 MB of chunks (Vite, rolldown, esbuild, postcss, …) that |
| 13 | * nothing loads, and every output file is uploaded. |
| 14 | * |
| 15 | * `dynamicImports` is computed before constant inlining, so it can list an |
| 16 | * `import()` the final code no longer contains: only dynamic imports the |
| 17 | * importer's code still references are followed. |
| 18 | */ |
| 19 | export const unreachableChunksPlugin = (): rolldown.Plugin => ({ |
| 20 | name: "alchemy:unreachable-chunks", |
| 21 | generateBundle(_options, bundle) { |
| 22 | const chunks = Object.values(bundle).filter( |
| 23 | (file): file is rolldown.OutputChunk => file.type === "chunk", |
| 24 | ); |
| 25 | const live = new Set<string>(); |
| 26 | const queue = chunks.filter((chunk) => chunk.isEntry).map((chunk) => chunk.fileName); |
| 27 | while (queue.length > 0) { |
| 28 | const fileName = queue.pop()!; |
| 29 | if (live.has(fileName)) continue; |
| 30 | live.add(fileName); |
| 31 | const chunk = bundle[fileName] as rolldown.OutputChunk; |
| 32 | for (const dependency of chunk.imports) { |
| 33 | if (bundle[dependency]?.type === "chunk") queue.push(dependency); |
| 34 | } |
| 35 | for (const dependency of chunk.dynamicImports) { |
| 36 | if ( |
| 37 | bundle[dependency]?.type === "chunk" && |
| 38 | chunk.code.includes(dependency.split("/").pop()!) |
| 39 | ) { |
| 40 | queue.push(dependency); |
| 41 | } |
| 42 | } |
| 43 | } |
| 44 | for (const chunk of chunks) { |
| 45 | if (live.has(chunk.fileName)) continue; |
| 46 | delete bundle[chunk.fileName]; |
| 47 | if (chunk.sourcemapFileName !== null) delete bundle[chunk.sourcemapFileName]; |
| 48 | } |
| 49 | }, |
| 50 | }); |