@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 236 lines 9.16 KB
Raw
1 import { fileURLToPath } from "node:url";
2 /**
3 * `@alchemy.run/frontend-frameworks/tanstack-start/aws` — the AWS Lambda
4 * deploy target for the TanStack Start integration.
5 *
6 * TanStack Start is pure Vite: `tanstackStart()` in the project's
7 * `vite.config.ts` builds a `client` environment into `<outDir>/client` and
8 * an `ssr` environment into `<outDir>/server`, whose entry module
9 * default-exports `{ fetch }` — a web-standard fetch handler. There is no
10 * adapter to select and no deployment preset; what this target owns is the
11 * Lambda packaging:
12 *
13 * - **`serverEntryFileName`** — `server.js`, the chunk the SSR environment
14 * emits for the resolved server entry; the finishing pass wraps it.
15 * - **`finish`** — emits the Lambda deployment surface next to the entry:
16 * a `package.json` (`type: "module"` — the Lambda Node.js runtime
17 * classifies `.js` by the nearest manifest, and `<outDir>/server` ships
18 * without one), a copy of this package's self-contained `aws-lambda` web
19 * adapter, and `index.mjs` exporting `handler` — the fetch handler wrapped
20 * with `awslambda.streamifyResponse` (or the buffered payload-v2 wrapper
21 * with `streaming: false`). The rewritten `BuildOutput` puts
22 * `server/index.mjs` first, so it becomes the deployed Lambda entry.
23 * - **`bundle`** — Node resolve conditions and the `@aws-sdk/` externals
24 * (the Lambda Node.js runtime ships SDK v3) for callers that post-process
25 * server code.
26 *
27 * No `devPlatform`: `dev` runs TanStack Start's own Vite dev server, which
28 * is already the AWS Lambda programming model (plain Node).
29 */
30 import * as Effect from "effect/Effect";
31 import * as FileSystem from "effect/FileSystem";
32 import * as Path from "effect/Path";
33 import { runBuildChild } from "../core/BuildChild.ts";
34 import {
35 DeployTargetError,
36 makeDeployTarget,
37 readServerModulesFromDisk,
38 sortServerModules,
39 type BuildOutput,
40 type DeployTargetFinishContext,
41 } from "../core/index.ts";
42 import {
43 DEFAULT_SERVER_ENTRY_FILE_NAME,
44 make,
45 type TanStackStartTarget,
46 type TanStackStartTargetConfig,
47 } from "./TanStackStart.ts";
48
49 /** The server entry file name the SSR environment emits. */
50 export const SERVER_ENTRY_FILE_NAME = DEFAULT_SERVER_ENTRY_FILE_NAME;
51
52 /** The Lambda entry module the finishing pass emits beside the server entry. */
53 export const LAMBDA_ENTRY_FILE_NAME = "index.mjs";
54
55 /** The on-disk copy of this package's `aws-lambda` web adapter runtime. */
56 export const LAMBDA_ADAPTER_FILE_NAME = "tanstack-start-aws-lambda.mjs";
57
58 /** AWS-specific knobs carried on the shared {@link TanStackStartTargetConfig}. */
59 export interface TanStackStartAwsTargetConfig extends TanStackStartTargetConfig {
60 /**
61 * Whether the emitted Lambda handler streams its response
62 * (`awslambda.streamifyResponse`, requires a Function URL with
63 * `invokeMode: RESPONSE_STREAM`). The buffered handler answers
64 * APIGW/Function-URL events with a complete response object.
65 * @default true
66 */
67 readonly streaming?: boolean | undefined;
68 }
69
70 const fail = (message: string, cause?: unknown) =>
71 new DeployTargetError({ platform: "aws", message, cause });
72
73 /**
74 * The generated Lambda entry: imports TanStack Start's server entry and
75 * exports its fetch handler wrapped for the Lambda Node.js runtime.
76 *
77 * The entry module default-exports `{ fetch }` (the shape
78 * `createServerEntry` produces). A project whose custom server entry
79 * default-exports the bare fetch function is accepted too.
80 */
81 export const generateLambdaEntry = (options: {
82 readonly streaming: boolean;
83 readonly serverEntryFileName: string;
84 }): string => {
85 const wrap = options.streaming ? "toLambdaHandler" : "toBufferedLambdaHandler";
86 return `// Auto-generated by @alchemy.run/frontend-frameworks/tanstack-start/aws — do not edit.
87 import * as serverEntry from "./${options.serverEntryFileName}";
88 import { ${wrap} } from "./${LAMBDA_ADAPTER_FILE_NAME}";
89
90 const entry = serverEntry.default ?? serverEntry;
91 const fetchHandler =
92 typeof entry === "function"
93 ? entry
94 : (request) => entry.fetch(request);
95
96 export const handler = ${wrap}(fetchHandler);
97 `;
98 };
99
100 /**
101 * Resolve this package's built, self-contained `aws-lambda` adapter module
102 * on disk (it has no imports of its own, so a byte copy deploys as-is).
103 */
104 const resolveLambdaAdapterPath = Effect.try({
105 try: () => fileURLToPath(import.meta.resolve("@alchemy.run/frontend-frameworks/aws-lambda")),
106 catch: (cause) =>
107 fail(
108 'Failed to resolve "@alchemy.run/frontend-frameworks/aws-lambda" — is the package built (its exports map serves dist/)?',
109 cause,
110 ),
111 });
112
113 const finish = (
114 config: TanStackStartAwsTargetConfig,
115 output: BuildOutput,
116 context: DeployTargetFinishContext,
117 ): Effect.Effect<BuildOutput, DeployTargetError, FileSystem.FileSystem | Path.Path> =>
118 Effect.gen(function* () {
119 const fs = yield* FileSystem.FileSystem;
120 const path = yield* Path.Path;
121 if (context.entry === undefined) {
122 return yield* fail("The TanStack Start build produced no on-disk server entry to finish");
123 }
124 const serverDir = path.dirname(context.entry);
125 const serverEntryFileName = path.basename(context.entry);
126
127 // The Lambda Node.js runtime classifies `.js` modules by the nearest
128 // package.json, and the server directory ships as the deployment root
129 // without one — the ESM entry and its chunks need the marker.
130 yield* fs.writeFileString(path.join(serverDir, "package.json"), '{"type":"module"}\n');
131
132 const adapterPath = yield* resolveLambdaAdapterPath;
133 const adapterSource = yield* fs.readFileString(adapterPath);
134 yield* fs.writeFileString(
135 path.join(serverDir, LAMBDA_ADAPTER_FILE_NAME),
136 // Drop the sourcemap pointer — the map is not copied into the bundle.
137 adapterSource.replace(/^\/\/# sourceMappingURL=.*$/m, ""),
138 );
139
140 yield* fs.writeFileString(
141 path.join(serverDir, LAMBDA_ENTRY_FILE_NAME),
142 generateLambdaEntry({
143 streaming: config.streaming !== false,
144 serverEntryFileName,
145 }),
146 );
147
148 // Re-read the server directory so the emitted files are part of the
149 // output, with the Lambda entry first.
150 const modules = yield* readServerModulesFromDisk({
151 directory: serverDir,
152 prefix: "server",
153 }).pipe(Effect.mapError((error) => fail(error.message, error.cause)));
154 return {
155 ...output,
156 serverModules: sortServerModules(modules, `server/${LAMBDA_ENTRY_FILE_NAME}`),
157 };
158 }).pipe(
159 Effect.catchTag("PlatformError", (error) =>
160 Effect.fail(fail("Failed to emit the Lambda entry", error)),
161 ),
162 );
163
164 /**
165 * The finish-only target — the shape the framework's regular build/finish
166 * pipeline consumes. Used directly in the build child (where `cwd === root`
167 * holds); {@link makeAwsTarget} wraps it with the wholesale `build` hook
168 * that spawns the child.
169 */
170 const makeAwsFinishTarget = (config: TanStackStartAwsTargetConfig = {}): TanStackStartTarget =>
171 makeDeployTarget({
172 platform: "aws",
173 config,
174 bundle: {
175 conditions: ["node", "import", "module"],
176 external: ["@aws-sdk/"],
177 },
178 serverEntryFileName: SERVER_ENTRY_FILE_NAME,
179 finish: (output, context) => finish(config, output, context),
180 });
181
182 /**
183 * A TanStack Start build loads and executes the project's `vite.config.*`
184 * (its `tanstackStart()` plugin crawls framework packages from
185 * `process.cwd()`, and user plugins may mutate `process.env` or
186 * `process.chdir`) — none of which may touch the engine process, where many
187 * deploys share one event loop. This target's wholesale `build` therefore
188 * runs the framework in a disposable child process whose working directory
189 * IS the project root (see `core/BuildChild.ts`). The shared
190 * `core/BuildChildRunner` entry imports this module in the child and calls
191 * the exported {@link buildInChild}.
192 */
193 export interface TanStackStartAwsBuildChildConfig {
194 readonly rootDir: string;
195 /** The (JSON-serializable) target config the parent was created with. */
196 readonly config: TanStackStartAwsTargetConfig;
197 }
198
199 export const buildInChild = (config: TanStackStartAwsBuildChildConfig) =>
200 Effect.gen(function* () {
201 const framework = yield* make({
202 root: config.rootDir,
203 // The finish-only target: no wholesale `build` hook, so the child
204 // runs the regular vite build + finish pipeline (no recursion).
205 target: makeAwsFinishTarget(config.config),
206 outDir: config.config.outDir,
207 });
208 return yield* framework.build({ root: config.rootDir });
209 });
210
211 /**
212 * Create the AWS Lambda {@link TanStackStartTarget}. See the module doc for
213 * the seams.
214 */
215 export const makeAwsTarget = (config: TanStackStartAwsTargetConfig = {}): TanStackStartTarget => ({
216 ...makeAwsFinishTarget(config),
217 build: (context) =>
218 runBuildChild({
219 module: import.meta.url,
220 rootDir: context.root,
221 env: context.env,
222 framework: "tanstack-start",
223 config: {
224 rootDir: context.root,
225 config,
226 } satisfies TanStackStartAwsBuildChildConfig,
227 }).pipe(Effect.mapError((error) => fail(error.message, error.cause))),
228 });
229
230 /**
231 * The deploy-target module contract (`resolveDeployTarget` accepts the
232 * default export — or the named `target` export — as a value or factory).
233 */
234 export const target = makeAwsTarget;
235
236 export default makeAwsTarget;