The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as Bundle from "alchemy/Bundle/Bundle"; |
| 2 | import { findCwdForBundle } from "alchemy/Bundle/TempRoot"; |
| 3 | import { Stack } from "alchemy/Stack"; |
| 4 | import * as Effect from "effect/Effect"; |
| 5 | import * as FileSystem from "effect/FileSystem"; |
| 6 | import * as Path from "effect/Path"; |
| 7 | import type * as rolldown from "rolldown"; |
| 8 | |
| 9 | /** |
| 10 | * The AWS-managed base image MicroVM Dockerfiles build on. The MicroVM build |
| 11 | * runs the Dockerfile server-side and snapshots the result with Firecracker. |
| 12 | */ |
| 13 | export const MICROVM_BASE_DOCKER_IMAGE = "public.ecr.aws/lambda/microvms:al2023-minimal"; |
| 14 | |
| 15 | /** The default port the in-VM HTTP server listens on. */ |
| 16 | export const DEFAULT_MICROVM_PORT = 8080; |
| 17 | |
| 18 | /** |
| 19 | * Build the final Dockerfile for an effectful MicroVM image. Starts from the |
| 20 | * user-provided base (or the managed MicroVM base), installs the JS runtime, |
| 21 | * copies the bundled program, and runs it as the entrypoint. Mirrors the |
| 22 | * Cloudflare Container `buildFinalDockerfile`, but targets the MicroVM base. |
| 23 | */ |
| 24 | export const buildMicrovmDockerfile = ( |
| 25 | userDockerfile: string | undefined, |
| 26 | runtime: "bun" | "node", |
| 27 | port: number, |
| 28 | options: { |
| 29 | /** The bundle ships `.map` files: copy them and have Node apply them. */ |
| 30 | readonly sourceMaps?: boolean; |
| 31 | } = {}, |
| 32 | ): string => { |
| 33 | const base = userDockerfile?.trim() ?? `FROM ${MICROVM_BASE_DOCKER_IMAGE}`; |
| 34 | const installRuntime = |
| 35 | runtime === "bun" |
| 36 | ? // `bun.sh/install` unpacks a zip, so the minimal MicroVM base needs |
| 37 | // `unzip` (and `tar`) present before the installer runs. |
| 38 | "RUN dnf install -y unzip tar && curl -fsSL https://bun.sh/install | bash && ln -s /root/.bun/bin/bun /usr/local/bin/bun && dnf clean all" |
| 39 | : // AL2023's default `nodejs` is Node 18, which lacks the global WebCrypto |
| 40 | // that AWS request signing needs; `nodejs24` also links `node`. |
| 41 | "RUN dnf install -y nodejs24 && dnf clean all"; |
| 42 | const runtimeBin = runtime === "bun" ? "bun" : "node"; |
| 43 | // Bun ignores external source maps, so only Node gets them. |
| 44 | const sourceMaps = options.sourceMaps === true && runtime === "node"; |
| 45 | const command = sourceMaps |
| 46 | ? `"${runtimeBin}", "--enable-source-maps", "/app/index.mjs"` |
| 47 | : `"${runtimeBin}", "/app/index.mjs"`; |
| 48 | return [ |
| 49 | base, |
| 50 | "", |
| 51 | installRuntime, |
| 52 | "WORKDIR /app", |
| 53 | // The entry (`index.mjs`) and every rolldown chunk are emitted with a |
| 54 | // `.mjs` extension, which Node always treats as ESM — so the entry's named |
| 55 | // imports of a chunk resolve without needing a `package.json` `"type"` |
| 56 | // marker (which would risk clobbering a user-provided base image's file). |
| 57 | "COPY *.mjs /app/", |
| 58 | ...(sourceMaps ? ["COPY *.map /app/"] : []), |
| 59 | `EXPOSE ${port}`, |
| 60 | `ENV PORT=${port}`, |
| 61 | `ENTRYPOINT [${command}]`, |
| 62 | "", |
| 63 | ].join("\n"); |
| 64 | }; |
| 65 | |
| 66 | /** |
| 67 | * Bundle an Effect-native MicroVM program with Rolldown and wrap it in a |
| 68 | * generated bootstrap that boots an HTTP server (the MicroVM endpoint). Returns |
| 69 | * every emitted file so the full set can be zipped into the code artifact. |
| 70 | * |
| 71 | * Mirrors `bundleContainerProgram`; the bootstrap provides AWS runtime services |
| 72 | * (FetchHttpClient + region from env) so in-VM HTTP capability bindings |
| 73 | * (e.g. S3 `*Http`) resolve against the MicroVM's execution role. |
| 74 | */ |
| 75 | export const bundleMicrovmProgram = Effect.fn(function* ({ |
| 76 | main, |
| 77 | runtime, |
| 78 | handler = "default", |
| 79 | isExternal = false, |
| 80 | external = [], |
| 81 | port, |
| 82 | build, |
| 83 | }: { |
| 84 | main: string; |
| 85 | runtime: "bun" | "node"; |
| 86 | handler?: string | undefined; |
| 87 | isExternal?: boolean; |
| 88 | external?: string[]; |
| 89 | port: number; |
| 90 | build?: Bundle.BundleConfig; |
| 91 | }) { |
| 92 | const fs = yield* FileSystem.FileSystem; |
| 93 | const stack = yield* Stack; |
| 94 | const virtualEntryPlugin = yield* Bundle.virtualEntryPlugin; |
| 95 | |
| 96 | const realMain = yield* fs.realPath(main); |
| 97 | const cwd = yield* findCwdForBundle(realMain); |
| 98 | |
| 99 | const buildBundle = Effect.fn(function* (entry: string, plugins?: rolldown.RolldownPluginOption) { |
| 100 | return yield* Bundle.build( |
| 101 | { |
| 102 | ...build?.input, |
| 103 | input: entry, |
| 104 | cwd, |
| 105 | external: [ |
| 106 | "@aws-sdk/*", |
| 107 | ...(runtime === "bun" ? ["bun", "bun:*"] : []), |
| 108 | ...external, |
| 109 | ...((build?.input?.external as string[] | undefined) ?? []), |
| 110 | ], |
| 111 | platform: "node", |
| 112 | resolve: { |
| 113 | conditionNames: |
| 114 | runtime === "bun" ? [...Bundle.BUN_CONDITION_NAMES] : [...Bundle.NODE_CONDITION_NAMES], |
| 115 | ...build?.input?.resolve, |
| 116 | }, |
| 117 | plugins: [build?.input?.plugins, plugins], |
| 118 | treeshake: true, |
| 119 | }, |
| 120 | { |
| 121 | ...build?.output, |
| 122 | format: "esm", |
| 123 | // Minified like Lambda Functions and Workers; `keepNames` keeps class |
| 124 | // and function names in stack traces and Effect spans. Node maps |
| 125 | // traces back through the source map; Bun ignores external maps. |
| 126 | sourcemap: build?.output?.sourcemap ?? runtime === "node", |
| 127 | minify: build?.output?.minify ?? true, |
| 128 | keepNames: build?.output?.keepNames ?? true, |
| 129 | entryFileNames: "index.mjs", |
| 130 | // Emit chunks as `.mjs` too so Node treats them as ESM unconditionally |
| 131 | // (no `package.json` `"type":"module"` needed in the image). |
| 132 | chunkFileNames: "[name]-[hash].mjs", |
| 133 | }, |
| 134 | build, |
| 135 | ); |
| 136 | }); |
| 137 | |
| 138 | const bundleOutput = isExternal |
| 139 | ? yield* buildBundle(realMain) |
| 140 | : yield* buildBundle( |
| 141 | realMain, |
| 142 | virtualEntryPlugin( |
| 143 | (importPath) => ` |
| 144 | import { bootstrap } from ${JSON.stringify( |
| 145 | runtime === "bun" |
| 146 | ? "@alchemy.run/aws/Bootstrap/MicrovmBun" |
| 147 | : "@alchemy.run/aws/Bootstrap/MicrovmNode", |
| 148 | )}; |
| 149 | import ${handler === "default" ? "entrypoint" : `{ ${handler} as entrypoint }`} from ${JSON.stringify(importPath)}; |
| 150 | |
| 151 | await bootstrap(entrypoint, ${JSON.stringify({ |
| 152 | port, |
| 153 | stack: { name: stack.name, stage: stack.stage }, |
| 154 | })}); |
| 155 | `, |
| 156 | ), |
| 157 | ); |
| 158 | |
| 159 | const files = bundleOutput.files.map((f) => ({ |
| 160 | path: f.path, |
| 161 | content: typeof f.content === "string" ? new TextEncoder().encode(f.content) : f.content, |
| 162 | })); |
| 163 | |
| 164 | return { files, hash: bundleOutput.hash }; |
| 165 | }); |
| 166 | |
| 167 | export interface ArtifactFile { |
| 168 | path: string; |
| 169 | content: string | Uint8Array; |
| 170 | } |
| 171 | |
| 172 | /** |
| 173 | * Zip a flat list of files into a deterministic (fixed mtime) archive. Used to |
| 174 | * package the MicroVM code artifact (Dockerfile + bundled program, or a build |
| 175 | * context) before uploading it to S3. |
| 176 | */ |
| 177 | export { zipFiles } from "alchemy/Util/zip"; |
| 178 | |
| 179 | /** |
| 180 | * Recursively read a build-context directory into a flat list of files |
| 181 | * (relative paths + bytes) for zipping into the code artifact. Used by the |
| 182 | * external (bring-your-own-Dockerfile) MicroVM mode. |
| 183 | */ |
| 184 | export const readContextDirectory = Effect.fn(function* (dir: string) { |
| 185 | const fs = yield* FileSystem.FileSystem; |
| 186 | const path = yield* Path.Path; |
| 187 | const root = yield* fs.realPath(dir); |
| 188 | |
| 189 | const walk = ( |
| 190 | current: string, |
| 191 | ): Effect.Effect<{ path: string; content: Uint8Array }[], any, never> => |
| 192 | Effect.gen(function* () { |
| 193 | const entries = yield* fs.readDirectory(current); |
| 194 | const out: { path: string; content: Uint8Array }[] = []; |
| 195 | for (const entry of entries) { |
| 196 | const abs = path.join(current, entry); |
| 197 | const info = yield* fs.stat(abs); |
| 198 | if (info.type === "Directory") { |
| 199 | out.push(...(yield* walk(abs))); |
| 200 | } else { |
| 201 | const content = yield* fs.readFile(abs); |
| 202 | out.push({ path: path.relative(root, abs), content }); |
| 203 | } |
| 204 | } |
| 205 | return out; |
| 206 | }); |
| 207 | |
| 208 | return yield* walk(root); |
| 209 | }); |