sailfork / t3code-github / .repos/ alchemy-effect/ packages/ frontend-frameworks/ src/ react-router/ aws.ts

import { fileURLToPath } from "node:url";
/**
 * `@alchemy.run/frontend-frameworks/react-router/aws` — the AWS Lambda
 * deploy target for the React Router v7 integration.
 *
 * React Router builds through Vite: `reactRouter()` in the project's
 * `vite.config.ts` builds a `client` environment into
 * `<buildDirectory>/client` and a server environment into
 * `<buildDirectory>/server`. Its server output is a `ServerBuild` MANIFEST
 * (`{ entry, routes, assets, ... }`) with no default export and nothing to
 * call, so the framework half makes the server build's rollup input a
 * wrapper that turns the manifest into a fetch handler with
 * `createRequestHandler` from `react-router` (see `serverEntrySource` in
 * `ReactRouter.ts` — it runs at build time because `react-router` itself
 * has to end up inside the emitted bundle). What this target owns is the
 * Lambda packaging on top of that fetch handler:
 *
 * - **`serverEntryFileName`** — `index.js`, the chunk the server pass emits
 *   (React Router's `serverBuildFile`); the finishing pass wraps it.
 * - **`finish`** — emits the Lambda deployment surface next to the entry:
 *   a `package.json` (`type: "module"` — the Lambda Node.js runtime
 *   classifies `.js` by the nearest manifest, and `<buildDirectory>/server`
 *   ships without one), a copy of this package's self-contained
 *   `aws-lambda` web adapter, and `lambda.mjs` exporting `handler` — the
 *   fetch handler wrapped with `awslambda.streamifyResponse` (or the
 *   buffered payload-v2 wrapper with `streaming: false`). The rewritten
 *   `BuildOutput` puts `server/lambda.mjs` first, so it becomes the
 *   deployed Lambda entry. (`lambda.mjs`, not `index.mjs`: React Router's
 *   server build already occupies `index.js`, and the Lambda runtime
 *   resolves a handler module extensionless.)
 * - **`bundle`** — Node resolve conditions and the `@aws-sdk/` externals
 *   (the Lambda Node.js runtime ships SDK v3) for callers that post-process
 *   server code.
 *
 * No `devPlatform`: `dev` runs React Router's own Vite dev server, which is
 * already the AWS Lambda programming model (plain Node).
 */
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import { runBuildChild } from "../core/BuildChild.ts";
import {
  DeployTargetError,
  makeDeployTarget,
  readServerModulesFromDisk,
  sortServerModules,
  type BuildOutput,
  type DeployTargetFinishContext,
} from "../core/index.ts";
import {
  DEFAULT_SERVER_BUILD_FILE,
  make,
  type ReactRouterTarget,
  type ReactRouterTargetConfig,
} from "./ReactRouter.ts";

/** The server entry file name React Router's server pass emits. */
export const SERVER_ENTRY_FILE_NAME = DEFAULT_SERVER_BUILD_FILE;

/**
 * The Lambda entry module the finishing pass emits beside the server entry.
 * Deliberately NOT `index.mjs`: the server build is `index.js`, and the
 * Lambda Node.js runtime resolves the handler module without an extension.
 */
export const LAMBDA_ENTRY_FILE_NAME = "lambda.mjs";

/** The on-disk copy of this package's `aws-lambda` web adapter runtime. */
export const LAMBDA_ADAPTER_FILE_NAME = "react-router-aws-lambda.mjs";

/** AWS-specific knobs carried on the shared {@link ReactRouterTargetConfig}. */
export interface ReactRouterAwsTargetConfig extends ReactRouterTargetConfig {
  /**
   * Whether the emitted Lambda handler streams its response
   * (`awslambda.streamifyResponse`, requires a Function URL with
   * `invokeMode: RESPONSE_STREAM`). The buffered handler answers
   * APIGW/Function-URL events with a complete response object.
   * @default true
   */
  readonly streaming?: boolean | undefined;
}

/** The AWS {@link ReactRouterTarget}, carrying the AWS-specific config. */
export interface ReactRouterAwsTarget extends ReactRouterTarget {
  readonly config: ReactRouterAwsTargetConfig;
}

const fail = (message: string, cause?: unknown) =>
  new DeployTargetError({ platform: "aws", message, cause });

/**
 * The generated Lambda entry: imports the server build's fetch handler and
 * exports it wrapped for the Lambda Node.js runtime.
 *
 * The entry module default-exports `{ fetch }` (the shape the integration's
 * virtual server entry produces). A project whose own entry default-exports
 * the bare fetch function is accepted too.
 */
export const generateLambdaEntry = (options: {
  readonly streaming: boolean;
  readonly serverEntryFileName: string;
}): string => {
  const wrap = options.streaming ? "toLambdaHandler" : "toBufferedLambdaHandler";
  return `// Auto-generated by @alchemy.run/frontend-frameworks/react-router/aws — do not edit.
import * as serverEntry from "./${options.serverEntryFileName}";
import { ${wrap} } from "./${LAMBDA_ADAPTER_FILE_NAME}";

const entry = serverEntry.default ?? serverEntry;
const fetchHandler =
  typeof entry === "function"
    ? entry
    : (request) => entry.fetch(request);

export const handler = ${wrap}(fetchHandler);
`;
};

/**
 * Resolve this package's built, self-contained `aws-lambda` adapter module
 * on disk (it has no imports of its own, so a byte copy deploys as-is).
 */
const resolveLambdaAdapterPath = Effect.try({
  try: () => fileURLToPath(import.meta.resolve("@alchemy.run/frontend-frameworks/aws-lambda")),
  catch: (cause) =>
    fail(
      'Failed to resolve "@alchemy.run/frontend-frameworks/aws-lambda" — is the package built (its exports map serves dist/)?',
      cause,
    ),
});

const finish = (
  config: ReactRouterAwsTargetConfig,
  output: BuildOutput,
  context: DeployTargetFinishContext,
): Effect.Effect<BuildOutput, DeployTargetError, FileSystem.FileSystem | Path.Path> =>
  Effect.gen(function* () {
    const fs = yield* FileSystem.FileSystem;
    const path = yield* Path.Path;
    if (context.entry === undefined) {
      return yield* fail("The React Router build produced no on-disk server entry to finish");
    }
    const serverDir = path.dirname(context.entry);
    const serverEntryFileName = path.basename(context.entry);

    // The Lambda Node.js runtime classifies `.js` modules by the nearest
    // package.json, and the server directory ships as the deployment root
    // without one — the ESM server build and its chunks need the marker.
    yield* fs.writeFileString(path.join(serverDir, "package.json"), '{"type":"module"}\n');

    const adapterPath = yield* resolveLambdaAdapterPath;
    const adapterSource = yield* fs.readFileString(adapterPath);
    yield* fs.writeFileString(
      path.join(serverDir, LAMBDA_ADAPTER_FILE_NAME),
      // Drop the sourcemap pointer — the map is not copied into the bundle.
      adapterSource.replace(/^\/\/# sourceMappingURL=.*$/m, ""),
    );

    yield* fs.writeFileString(
      path.join(serverDir, LAMBDA_ENTRY_FILE_NAME),
      generateLambdaEntry({
        streaming: config.streaming !== false,
        serverEntryFileName,
      }),
    );

    // Re-read the server directory so the emitted files are part of the
    // output, with the Lambda entry first.
    const modules = yield* readServerModulesFromDisk({
      directory: serverDir,
      prefix: "server",
    }).pipe(Effect.mapError((error) => fail(error.message, error.cause)));
    return {
      ...output,
      serverModules: sortServerModules(modules, `server/${LAMBDA_ENTRY_FILE_NAME}`),
    };
  }).pipe(
    Effect.catchTag("PlatformError", (error) =>
      Effect.fail(fail("Failed to emit the Lambda entry", error)),
    ),
  );

/**
 * The finish-only target — the shape the framework's regular build/finish
 * pipeline consumes. Used directly in the build child (where `cwd === root`
 * holds); {@link makeAwsTarget} wraps it with the wholesale `build` hook
 * that spawns the child.
 */
const makeAwsFinishTarget = (config: ReactRouterAwsTargetConfig = {}): ReactRouterAwsTarget =>
  makeDeployTarget({
    platform: "aws",
    config,
    bundle: {
      conditions: ["node", "import", "module"],
      external: ["@aws-sdk/"],
    },
    serverEntryFileName: SERVER_ENTRY_FILE_NAME,
    finish: (output, context) => finish(config, output, context),
  });

/**
 * A React Router build loads and executes the project's `vite.config.*` and
 * `react-router.config.ts` (user plugins may mutate `process.env` or
 * `process.chdir`, and React Router's config loader spins its own vite-node
 * server) — none of which may touch the engine process, where many deploys
 * share one event loop. This target's wholesale `build` therefore runs the
 * framework in a disposable child process whose working directory IS the
 * project root (see `core/BuildChild.ts`). The shared
 * `core/BuildChildRunner` entry imports this module in the child and calls
 * the exported {@link buildInChild}.
 */
export interface ReactRouterAwsBuildChildConfig {
  readonly rootDir: string;
  /** The (JSON-serializable) target config the parent was created with. */
  readonly config: ReactRouterAwsTargetConfig;
}

export const buildInChild = (config: ReactRouterAwsBuildChildConfig) =>
  Effect.gen(function* () {
    const framework = yield* make({
      root: config.rootDir,
      // The finish-only target: no wholesale `build` hook, so the child
      // runs the regular vite build + finish pipeline (no recursion).
      target: makeAwsFinishTarget(config.config),
      buildDirectory: config.config.buildDirectory,
    });
    return yield* framework.build({ root: config.rootDir });
  });

/**
 * Create the AWS Lambda {@link ReactRouterTarget}. See the module doc for
 * the seams.
 */
export const makeAwsTarget = (config: ReactRouterAwsTargetConfig = {}): ReactRouterAwsTarget => ({
  ...makeAwsFinishTarget(config),
  build: (context) =>
    runBuildChild({
      module: import.meta.url,
      rootDir: context.root,
      env: context.env,
      framework: "react-router",
      config: {
        rootDir: context.root,
        config,
      } satisfies ReactRouterAwsBuildChildConfig,
    }).pipe(Effect.mapError((error) => fail(error.message, error.cause))),
});

/**
 * The deploy-target module contract (`resolveDeployTarget` accepts the
 * default export — or the named `target` export — as a value or factory).
 */
export const target = makeAwsTarget;

export default makeAwsTarget;