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

import { fileURLToPath } from "node:url";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import type * as Scope from "effect/Scope";
import { runBuildChild } from "../core/BuildChild.ts";
/**
 * `@alchemy.run/frontend-frameworks/vinext/aws` — vinext on AWS Lambda.
 *
 * AWS uses Vinext's Vite build in Node (no Cloudflare Vite
 * plugin) plus a finishing pass that wraps the App Router RSC entry
 * (`dist/server/index.js`) as a streaming Lambda handler via
 * `@alchemy.run/frontend-frameworks/aws-lambda`. Static assets in
 * `dist/client` are uploaded to S3 by `AWS.Website.Vinext`.
 *
 * - **`build`** runs vinext's Vite build in a disposable child, then writes
 *   `dist/server/serve-aws-lambda.mjs` exporting `handler`, or with
 *   `server: "web-function"` `dist/server/serve-node.mjs`, a Node HTTP
 *   server on `AWS_LAMBDA_HTTP_ENDPOINT` for a Lambda Web Function.
 * - **`dev`** runs the real `vinext dev` CLI (plain Node), scoped.
 *
 * This is **not** OpenNext and **not** `Cloudflare.Website.Vinext`.
 * App Router only — Pages Router has no single fetch handler to wrap.
 *
 * Composites should load this module as both the framework specifier and
 * the deploy target (same shape as `nextjs/aws`).
 */
import * as FrameworkCore from "../core/index.ts";
import { DeployTargetError, makeDeployTarget, type DeployTarget } from "../core/index.ts";
import { resolveProjectPackageDirectory } from "../core/Loader.ts";
import { makeNodeServeEntrySource, NODE_SERVE_ENTRY_FILE_NAME } from "../core/NodeServe.ts";
import {
  awaitVinextDevReady,
  collectVinextDist,
  failFramework,
  pickEphemeralPort,
  pinServeModule,
  resolveVinextCli,
  runVinextBuild,
  spawnVinextDev,
  VINEXT_RSC_ENTRY,
} from "./cli.ts";

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

/** Options for the vinext AWS framework module / deploy target. */
export interface VinextAwsOptions {
  readonly root?: string | undefined;
  /**
   * The deploy target module specifier the caller resolved this module as.
   * This module IS the AWS target — accepted and ignored.
   */
  readonly target?: string | undefined;
  /**
   * Whether the emitted Lambda handler streams its response
   * (`awslambda.streamifyResponse`, requires a Function URL with
   * `invokeMode: RESPONSE_STREAM`).
   * @default true
   */
  readonly streaming?: boolean | undefined;
  /**
   * What runs the server. `"web-function"` writes
   * `dist/server/serve-node.mjs`, a Node HTTP server on
   * `AWS_LAMBDA_HTTP_ENDPOINT` for a Lambda Web Function; `"function"`
   * writes the Lambda handler.
   * @default "function"
   */
  readonly server?: "web-function" | "function" | undefined;
}

export interface VinextAwsTargetConfig {
  readonly root?: string | undefined;
  readonly streaming?: boolean | undefined;
  readonly server?: "web-function" | "function" | undefined;
}

export interface VinextAwsTarget extends DeployTarget<VinextAwsTargetConfig> {}

/** The Lambda entry the finishing pass writes into `dist/server`. */
export const SERVE_ENTRY_NAME = "server/serve-aws-lambda.mjs";

/** The Web Function entry the finishing pass writes into `dist/server`. */
export const WEB_SERVE_ENTRY_NAME = `server/${NODE_SERVE_ENTRY_FILE_NAME}`;

/** vinext's App Router fetch handler, as both entries call it. */
const FETCH_HANDLER_SOURCE = `import rsc from "./index.js";

const fetchHandler = (request) => {
  const ctx = {
    hostRuntime: "node",
    waitUntil(promise) {
      Promise.resolve(promise).catch(() => {});
    },
    passThroughOnException() {},
  };
  if (typeof rsc === "function") return rsc(request, ctx);
  return rsc.fetch(request, process.env, ctx);
};`;

/**
 * The generated Web Function entry: a Node HTTP server around vinext's App
 * Router fetch handler. Assets are served from S3, so there is no static
 * directory.
 */
export const makeWebEntrySource = (): string =>
  makeNodeServeEntrySource({
    handler: { kind: "fetch", imports: FETCH_HANDLER_SOURCE, expr: "fetchHandler" },
  });

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

/**
 * The generated Lambda entry: imports vinext's App Router fetch handler
 * and exports it wrapped for the Lambda Node.js runtime.
 */
export const makeLambdaEntrySource = (streaming: boolean): string => {
  const wrap = streaming ? "toLambdaHandler" : "toBufferedLambdaHandler";
  return `// Generated by @alchemy.run/frontend-frameworks/vinext/aws — do not edit.
import { ${wrap} } from "./${LAMBDA_ADAPTER_FILE_NAME}";
${FETCH_HANDLER_SOURCE}

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

const resolveLambdaAdapterPath = Effect.try({
  try: () => fileURLToPath(import.meta.resolve("@alchemy.run/frontend-frameworks/aws-lambda")),
  catch: (cause) =>
    failFramework(
      'Failed to resolve "@alchemy.run/frontend-frameworks/aws-lambda" — is the package built (its exports map serves dist/)?',
    )(cause),
});

export interface VinextAwsBuildChildConfig {
  readonly rootDir: string;
  readonly config: VinextAwsTargetConfig;
}

export const buildInChild = (config: VinextAwsBuildChildConfig) =>
  Effect.gen(function* () {
    const fs = yield* FileSystem.FileSystem;
    const path = yield* Path.Path;
    const root = config.rootDir;
    yield* runVinextBuild({ root, cache: "s3" });
    const dist = yield* collectVinextDist(root);
    if (!dist.hasRsc) {
      return yield* failFramework(
        `The vinext AWS target requires an App Router build (${VINEXT_RSC_ENTRY}). Pages Router is supported on Node containers, not Lambda.`,
      )(undefined);
    }
    const adapterPath = yield* resolveLambdaAdapterPath;
    const adapterSource = yield* fs
      .readFileString(adapterPath)
      .pipe(Effect.mapError(failFramework("Failed to read the aws-lambda adapter module")));
    yield* fs
      .writeFileString(
        path.join(dist.serverDir, LAMBDA_ADAPTER_FILE_NAME),
        adapterSource.replace(/^\/\/# sourceMappingURL=.*$/m, ""),
      )
      .pipe(
        Effect.mapError(failFramework("Failed to write the aws-lambda adapter into dist/server")),
      );
    const output =
      config.config.server === "web-function"
        ? yield* pinServeModule(dist, WEB_SERVE_ENTRY_NAME, makeWebEntrySource())
        : yield* pinServeModule(
            dist,
            SERVE_ENTRY_NAME,
            makeLambdaEntrySource(config.config.streaming !== false),
          );
    // Preserve vinext's separate RSC/SSR module graphs and package its externals.
    const vinextRoot = yield* resolveProjectPackageDirectory(root, "vinext").pipe(
      Effect.flatMap((directory) => fs.realPath(directory)),
    );
    const standaloneUrl = yield* path.toFileUrl(path.join(vinextRoot, "dist/build/standalone.js"));
    const standalone = yield* Effect.tryPromise({
      try: () =>
        import(/* @vite-ignore */ standaloneUrl.href) as Promise<{
          emitStandaloneOutput(options: {
            root: string;
            outDir: string;
            vinextPackageRoot: string;
          }): { standaloneDir: string };
        }>,
      catch: failFramework(
        "Failed to load vinext standalone packaging; install vinext 1.0.1 or newer",
      ),
    });
    const packaged = yield* Effect.try({
      try: () =>
        standalone.emitStandaloneOutput({
          root,
          outDir: dist.distDirectory!,
          vinextPackageRoot: vinextRoot,
        }),
      catch: failFramework("Failed to package vinext Lambda runtime dependencies"),
    });
    yield* fs.rename(
      path.join(packaged.standaloneDir, "node_modules"),
      path.join(dist.serverDir, "node_modules"),
    );
    yield* fs.remove(packaged.standaloneDir, { recursive: true });
    yield* fs.writeFileString(path.join(dist.serverDir, "package.json"), '{"type":"module"}');
    return output;
  });

const makeAwsChildTarget = (config: VinextAwsTargetConfig = {}): VinextAwsTarget =>
  makeDeployTarget({
    platform: "aws",
    config,
    bundle: {
      conditions: ["node", "import", "module"],
      external: ["@aws-sdk/"],
    },
  });

/**
 * Create the AWS Lambda {@link VinextAwsTarget}. See the module doc.
 */
export const makeAwsTarget = (config: VinextAwsTargetConfig = {}): VinextAwsTarget => ({
  ...makeAwsChildTarget(config),
  build: (context) =>
    runBuildChild({
      runtime: "node",
      module: import.meta.url,
      rootDir: context.root,
      env: context.env,
      framework: "vinext",
      config: {
        rootDir: context.root,
        config,
      } satisfies VinextAwsBuildChildConfig,
    }).pipe(Effect.mapError((error) => failTarget(error.message, error.cause))),
});

export const target = makeAwsTarget;

export default makeAwsTarget;

export interface VinextAwsService {
  readonly build: (options?: FrameworkCore.FrameworkBuildOptions) => Effect.Effect<
    {
      readonly distDirectory: string;
      readonly clientDirectory: string | undefined;
      readonly serverModules: Array<{ readonly name: string }>;
    },
    FrameworkCore.FrameworkError
  >;
  readonly dev: (
    options?: FrameworkCore.FrameworkDevOptions,
  ) => Effect.Effect<FrameworkCore.FrameworkDevServer, FrameworkCore.FrameworkError, Scope.Scope>;
}

/**
 * Build the vinext-on-AWS framework service. See the module doc for the
 * `build`/`dev` semantics.
 */
export const make: (
  options?: VinextAwsOptions,
) => Effect.Effect<VinextAwsService, never, FileSystem.FileSystem | Path.Path> = Effect.fnUntraced(
  function* (options?: VinextAwsOptions) {
    const fs = yield* FileSystem.FileSystem;
    const path = yield* Path.Path;
    const resolveRoot = (override: string | undefined) =>
      Effect.sync(() => path.resolve(override ?? options?.root ?? process.cwd()));

    const build: VinextAwsService["build"] = Effect.fn(function* (
      buildOptions?: FrameworkCore.FrameworkBuildOptions,
    ) {
      const root = yield* resolveRoot(buildOptions?.root);
      const awsTarget = makeAwsTarget({
        root,
        streaming: options?.streaming,
        server: options?.server,
      });
      const output = yield* awsTarget.build!({
        root,
        framework: "vinext",
        env: buildOptions?.env,
      }).pipe(
        Effect.provideService(FileSystem.FileSystem, fs),
        Effect.provideService(Path.Path, path),
        Effect.mapError((error) => failFramework(error.message)(error.cause)),
      );
      return {
        distDirectory: output.distDirectory ?? path.join(root, "dist"),
        clientDirectory: output.clientDirectory,
        serverModules: (output.serverModules ?? []).map((module_) => ({
          name: module_.name,
        })),
      };
    });

    const dev: VinextAwsService["dev"] = Effect.fn(function* (
      devOptions?: FrameworkCore.FrameworkDevOptions,
    ) {
      const root = yield* resolveRoot(devOptions?.root);
      const port = devOptions?.port ?? (yield* pickEphemeralPort);
      const cli = yield* resolveVinextCli(root);
      const host = devOptions?.host ?? "127.0.0.1";
      const child = yield* spawnVinextDev({ root, cli, port, host });
      const url = `http://${host}:${port}`;
      yield* awaitVinextDevReady({ url, child });
      return { url };
    });

    return { build, dev };
  },
);