@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, 06:00 UTC

main
ts 240 lines 9.45 KB
Raw
1 import { fileURLToPath } from "node:url";
2 /**
3 * `@alchemy.run/frontend-frameworks/waku/aws` — the AWS Lambda deploy target for
4 * the Waku integration.
5 *
6 * Waku's AWS story is a plain-Node waku build with this package's forked
7 * aws-lambda adapter selected via `unstable_adapter`: `dist/server` is the
8 * self-contained server bundle and `dist/public` holds the static assets
9 * (SSG pages included) for the CDN. What this target owns:
10 *
11 * - **`adapter`** — this package's fork of waku's aws-lambda adapter
12 * (`@alchemy.run/frontend-frameworks/waku/aws-adapter`): behavior-identical to
13 * upstream except the Lambda wrapper is this package's own streaming
14 * adapter (`@alchemy.run/frontend-frameworks/aws-lambda`) instead of
15 * `hono/aws-lambda`, and the serve entry is written by this target's
16 * finishing pass instead of upstream's build enhancer.
17 * - **`vitePlugins`** — none: a plain-Node waku build needs no bundler
18 * plugin (there is no workerd runtime to host dev/build environments in).
19 * - **`finish`** — writes the Lambda serve entry
20 * (`dist/server/serve-aws-lambda.mjs`, importing the built server chunk's
21 * `INTERNAL_runFetch` and wrapping it via the adapter's handler-wrapper
22 * global — no bare imports, so the shipped directory needs no
23 * `node_modules`) plus a `package.json` marking the directory ESM, and
24 * pins the serve entry as `serverModules[0]`.
25 * - **`entry`** — surfaces `config.main` as the generic user-entry carriage.
26 * - **`bundle`** — Node resolve conditions and the `@aws-sdk/` externals
27 * (the Lambda Node.js runtime ships SDK v3) for callers that post-process
28 * server code.
29 */
30 import * as Effect from "effect/Effect";
31 import * as FileSystem from "effect/FileSystem";
32 import * as Path from "effect/Path";
33 import type { Config as WakuConfig } from "waku/config";
34 import { runBuildChild } from "../core/BuildChild.ts";
35 import {
36 DeployTargetError,
37 makeDeployTarget,
38 toOutputFile,
39 type BuildOutput,
40 } from "../core/index.ts";
41 import { AWS_LAMBDA_HANDLE_GLOBAL } from "./aws-shared.ts";
42 import { make, type WakuTarget, type WakuTargetBuildContext } from "./Waku.ts";
43
44 export type { WakuTarget, WakuTargetContext } from "./Waku.ts";
45
46 /** The serve entry the finishing pass writes into `dist/server`. */
47 export const SERVE_ENTRY_NAME = "serve-aws-lambda.mjs";
48
49 /** Configuration accepted by the AWS deploy target. */
50 export interface WakuAwsTargetConfig {
51 /**
52 * The user's own server entry module (the deploy-target user-entry seam):
53 * a module that wraps waku's handler (imported from
54 * `virtual:waku/server-entry`) and re-exports extras. Absolute, or
55 * relative to the project root.
56 */
57 readonly main?: string | undefined;
58 /**
59 * Whether the emitted Lambda handler streams its response
60 * (`awslambda.streamifyResponse`, requires a Function URL with
61 * `invokeMode: RESPONSE_STREAM`). Set `false` for the buffered
62 * payload-v2 handler (`invokeMode: BUFFERED` / API Gateway HTTP APIs).
63 * @default true
64 */
65 readonly streaming?: boolean | undefined;
66 }
67
68 /**
69 * The content of the generated Lambda serve entry: imports the built server
70 * chunk (whose module evaluation runs the adapter setup and publishes the
71 * handler-wrapper global), then exports the wrapped `handler`.
72 */
73 export const makeServeEntrySource = (streaming: boolean): string =>
74 `// Generated by @alchemy.run/frontend-frameworks/waku/aws — the Lambda entry.
75 import { INTERNAL_runFetch } from "./index.js";
76
77 const handle = globalThis.${AWS_LAMBDA_HANDLE_GLOBAL};
78 if (typeof handle !== "function") {
79 throw new Error(
80 "The waku AWS adapter did not register its Lambda handler wrapper — " +
81 "the server bundle was not built with @alchemy.run/frontend-frameworks/waku/aws-adapter.",
82 );
83 }
84
85 export const handler = handle(
86 (req, ...args) => INTERNAL_runFetch(process.env, req, ...args),
87 { streaming: ${streaming} },
88 );
89 `;
90
91 /**
92 * The adapter-driven target — the shape the framework's regular
93 * build/finish pipeline consumes. Used directly in the build child (where
94 * `cwd === root` holds); {@link makeWakuAwsTarget} wraps it with the
95 * wholesale `build` hook that spawns the child.
96 */
97 const makeAwsAdapterTarget = (
98 config?: WakuAwsTargetConfig,
99 ): WakuTarget<WakuAwsTargetConfig | undefined> =>
100 makeDeployTarget({
101 platform: "aws",
102 config,
103 entry: config?.main !== undefined ? { main: config.main } : undefined,
104 bundle: {
105 conditions: ["node", "import", "module"],
106 external: ["@aws-sdk/"],
107 },
108 adapter: () =>
109 Effect.try({
110 try: () =>
111 fileURLToPath(import.meta.resolve("@alchemy.run/frontend-frameworks/waku/aws-adapter")),
112 catch: (cause) =>
113 new DeployTargetError({
114 platform: "aws",
115 message:
116 "Failed to resolve the @alchemy.run/frontend-frameworks/waku AWS adapter module",
117 cause,
118 }),
119 }),
120 vitePlugins: () => Effect.sync(() => []),
121 finish: (output, _context) =>
122 Effect.gen(function* () {
123 const fs = yield* FileSystem.FileSystem;
124 const path = yield* Path.Path;
125 const fail = (message: string) => (cause?: unknown) =>
126 new DeployTargetError({ platform: "aws", message, cause });
127
128 if (output.distDirectory === undefined) {
129 return yield* fail("The waku build produced no dist directory")(undefined);
130 }
131 const serverDir = path.join(output.distDirectory, "server");
132 const serverIndex = path.join(serverDir, "index.js");
133 const hasServerIndex = yield* fs
134 .exists(serverIndex)
135 .pipe(Effect.mapError(fail("Failed to probe the built server entry")));
136 if (!hasServerIndex) {
137 return yield* fail(`The waku build produced no server entry at ${serverIndex}`)(
138 undefined,
139 );
140 }
141
142 const serveSource = makeServeEntrySource(config?.streaming ?? true);
143 // `dist/server` ships to Lambda as-is (no project package.json in the
144 // archive), so the directory must carry its own ESM marker for
145 // `./index.js` to parse as a module.
146 yield* Effect.all(
147 [
148 fs.writeFileString(path.join(serverDir, SERVE_ENTRY_NAME), serveSource),
149 fs.writeFileString(
150 path.join(serverDir, "package.json"),
151 `${JSON.stringify({ type: "module" }, null, 2)}\n`,
152 ),
153 ],
154 { concurrency: "unbounded" },
155 ).pipe(Effect.mapError(fail("Failed to write the Lambda serve entry")));
156
157 const serveModule = yield* toOutputFile(`server/${SERVE_ENTRY_NAME}`, serveSource);
158 // The serve entry becomes `serverModules[0]` — the module alchemy's
159 // Server resource deploys as the Lambda `main`.
160 const serverModules = [
161 serveModule,
162 ...(output.serverModules ?? []).filter((module_) => module_.name !== serveModule.name),
163 ];
164 return { ...output, serverModules } satisfies BuildOutput;
165 }),
166 });
167
168 /**
169 * Waku assumes `process.cwd()` is the project root in several places (the
170 * html-shell plugin's `index.html` input resolves against the cwd, and
171 * rolldown resolves relative inputs from the cwd), so the framework build
172 * chdirs to the root — which must never happen in the engine process (many
173 * deploys share one event loop). This target's wholesale `build` therefore
174 * runs the framework in a disposable child process whose working directory
175 * IS the project root (see `core/BuildChild.ts`); the framework's own
176 * chdir is a no-op there. The shared `core/BuildChildRunner` entry imports
177 * this module in the child and calls the exported {@link buildInChild}.
178 */
179 export interface WakuAwsBuildChildConfig {
180 readonly rootDir: string;
181 /** The (JSON-serializable) target config the parent was created with. */
182 readonly config: WakuAwsTargetConfig | undefined;
183 /**
184 * The inline waku options the framework was constructed with
185 * (`WakuFrameworkOptions.waku`, carried through the build context). Only
186 * JSON-serializable fields cross the process boundary.
187 */
188 readonly waku: WakuConfig | undefined;
189 }
190
191 export const buildInChild = (config: WakuAwsBuildChildConfig) =>
192 Effect.gen(function* () {
193 const framework = yield* make({
194 root: config.rootDir,
195 // The adapter-only target: no wholesale `build` hook, so the child
196 // runs the regular waku build + finish pipeline (no recursion).
197 target: makeAwsAdapterTarget(config.config),
198 waku: config.waku,
199 });
200 return yield* framework.build({ root: config.rootDir });
201 });
202
203 /**
204 * Build the AWS Lambda {@link WakuTarget}. See the module doc for the seams.
205 */
206 export const makeWakuAwsTarget = (
207 config?: WakuAwsTargetConfig,
208 ): WakuTarget<WakuAwsTargetConfig | undefined> => ({
209 ...makeAwsAdapterTarget(config),
210 build: (context: WakuTargetBuildContext) =>
211 runBuildChild({
212 runtime: "node",
213 module: import.meta.url,
214 rootDir: context.root,
215 env: context.env,
216 framework: "waku",
217 config: {
218 rootDir: context.root,
219 config,
220 waku: context.waku,
221 } satisfies WakuAwsBuildChildConfig,
222 }).pipe(
223 Effect.mapError(
224 (error) =>
225 new DeployTargetError({
226 platform: "aws",
227 message: error.message,
228 cause: error.cause,
229 }),
230 ),
231 ),
232 });
233
234 /**
235 * The deploy-target module contract (`resolveDeployTarget` accepts the
236 * default export — or the named `target` export — as a value or factory).
237 */
238 export const target = makeWakuAwsTarget;
239
240 export default makeWakuAwsTarget;