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

import { fileURLToPath } from "node:url";
/**
 * `@alchemy.run/frontend-frameworks/octane/aws` — the AWS Lambda deploy target
 * for the Octane integration.
 *
 * `AWS.Website.Octane` selects this target, which automatically wraps
 * Octane's default native Node output. No adapter is required in
 * `octane.config.ts`: the project's own `vite build` emits
 * `dist/server/entry.js`, a self-contained Node ESM bundle (only `node:`
 * externals) exporting a web-standard fetch `handler` that never boots a
 * listener when imported. What this target owns:
 *
 * - **`adapterName` / `adapterPackage`** — identify the optional legacy AWS
 *   marker adapter, still accepted for existing projects.
 * - **`serverEntryFileName`** — `entry.js`, Octane's emitted node entry;
 *   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 extensionless `.js` by the nearest manifest, and `dist/server`
 *   ships without one), a copy of this package's self-contained
 *   `aws-lambda` web adapter, and `index.mjs` exporting `handler` — the
 *   fetch handler wrapped with `awslambda.streamifyResponse` (or the
 *   buffered payload-v2 wrapper with `streaming: false`). The rewritten
 *   `BuildOutput` puts `server/index.mjs` first, so it becomes the deployed
 *   Lambda entry.
 * - **`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 Octane's own Vite dev server, which is
 * already the AWS Lambda programming model (plain Node; note Octane's dev
 * middleware supplies no request-scoped platform bindings — an upstream
 * limitation shared with the Cloudflare target).
 */
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 { make, type OctaneTarget, type OctaneTargetConfig } from "./Octane.ts";

/** The `adapter.name` the AWS marker adapter declares. */
export const ADAPTER_NAME = "aws";

/** The optional legacy AWS marker adapter module for existing configs. */
export const ADAPTER_PACKAGE = "@alchemy.run/frontend-frameworks/octane/aws-adapter";

/** Octane's emitted node server entry within the server output directory. */
export const SERVER_ENTRY_FILE_NAME = "entry.js";

/** The Lambda entry module the finishing pass emits beside `entry.js`. */
export const LAMBDA_ENTRY_FILE_NAME = "index.mjs";

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

/** AWS-specific knobs carried on the shared {@link OctaneTargetConfig}. */
export interface OctaneAwsTargetConfig extends OctaneTargetConfig {
  /**
   * 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;
}

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

/**
 * The generated Lambda entry: imports Octane's fetch handler from
 * `entry.js` and exports it wrapped for the Lambda Node.js runtime.
 */
const generateLambdaEntry = (streaming: boolean): string => {
  const wrap = streaming ? "toLambdaHandler" : "toBufferedLambdaHandler";
  return `// Auto-generated by ${ADAPTER_PACKAGE.replace("/aws-adapter", "/aws")} — do not edit.
import { handler as fetchHandler } from "./${SERVER_ENTRY_FILE_NAME}";
import { ${wrap} } from "./${LAMBDA_ADAPTER_FILE_NAME}";

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: OctaneAwsTargetConfig,
  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 Octane build produced no on-disk server entry to finish");
    }
    const serverDir = path.dirname(context.entry);

    // The Lambda Node.js runtime classifies `.js` modules by the nearest
    // package.json, and `dist/server` ships as the deployment root without
    // one — Octane's ESM `entry.js` needs the marker to load as ESM.
    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(config.streaming !== false),
    );

    // Re-read the server directory so the emitted files (and runtime inputs
    // like the SSR `index.html` the entry reads beside itself) 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 native Node output 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 makeAwsAdapterTarget = (config: OctaneAwsTargetConfig = {}): OctaneTarget =>
  makeDeployTarget({
    platform: "aws",
    config,
    bundle: {
      conditions: ["node", "import", "module"],
      external: ["@aws-sdk/"],
    },
    adapterName: ADAPTER_NAME,
    adapterPackage: ADAPTER_PACKAGE,
    serverEntryFileName: SERVER_ENTRY_FILE_NAME,
    finish: (output, context) => finish(config, output, context),
  });

/**
 * Octane's production build runs the project's own `vite build`, whose
 * natively-loaded `vite.config.*` / `octane.config.ts` execute user plugins
 * that may read the cwd, mutate `process.env`, or `process.chdir` — none of
 * which may touch the engine process (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 OctaneAwsBuildChildConfig {
  readonly rootDir: string;
  /** The (JSON-serializable) target config the parent was created with. */
  readonly config: OctaneAwsTargetConfig;
}

export const buildInChild = (config: OctaneAwsBuildChildConfig) =>
  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: makeAwsAdapterTarget(config.config),
      compatibilityDate: config.config.compatibilityDate,
      compatibilityFlags: config.config.compatibilityFlags,
    });
    return yield* framework.build({ root: config.rootDir });
  });

/**
 * Create the AWS Lambda {@link OctaneTarget}. See the module doc for the
 * seams.
 */
export const makeAwsTarget = (config: OctaneAwsTargetConfig = {}): OctaneTarget => ({
  ...makeAwsAdapterTarget(config),
  build: (context) =>
    runBuildChild({
      module: import.meta.url,
      rootDir: context.root,
      env: context.env,
      framework: "octane",
      config: {
        rootDir: context.root,
        config,
      } satisfies OctaneAwsBuildChildConfig,
    }).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;