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

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/node` — vinext on a Node
 * container (vinext's Vite build + vinext's production server).
 *
 * Unlike the Cloudflare integration (`./source`, Vite + the Alchemy
 * Cloudflare plugin + `vinext/server/fetch-handler`), this module does
 * **not** inject a Workers plugin. The container-optimal path is a
 * long-running Node process:
 *
 * - **`build`** runs Vinext's Vite build in a disposable child
 *   (cwd = project root), then writes a serve entry that calls
 *   `startProdServer` from `vinext/server/prod-server`, answers
 *   `GET /health`, and listens on `PORT` (default 3000).
 * - **`dev`** runs the real `vinext dev` CLI (plain Node), scoped.
 *
 * Composites should load this module as both the framework specifier and
 * the deploy target (same shape as `nextjs/node`).
 */
import * as FrameworkCore from "../core/index.ts";
import { DeployTargetError, makeDeployTarget, type DeployTarget } from "../core/index.ts";
import {
  NODE_BUNDLE_CONDITIONS,
  NODE_DEFAULT_PORT,
  NODE_SERVE_ENTRY_FILE_NAME,
} from "../core/NodeServe.ts";
import {
  awaitVinextDevReady,
  collectVinextDist,
  failFramework,
  pickEphemeralPort,
  pinServeModule,
  resolveVinextCli,
  runVinextBuild,
  spawnVinextDev,
} from "./cli.ts";

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

/** Options for the vinext Node framework module / deploy target. */
export interface VinextNodeOptions {
  readonly root?: string | undefined;
  /**
   * The deploy target module specifier the caller resolved this module as.
   * This module IS the Node target — accepted and ignored (parity with
   * `nextjs/node`).
   */
  readonly target?: string | undefined;
}

export interface VinextNodeTargetConfig {
  readonly root?: string | undefined;
}

export interface VinextNodeTarget extends DeployTarget<VinextNodeTargetConfig> {}

/** Serve-entry module name relative to `dist/`. */
export const SERVER_ENTRY_NAME = `server/${NODE_SERVE_ENTRY_FILE_NAME}`;

/**
 * Packages the Node image `npm install`s so `startProdServer` and the
 * RSC externals vinext leaves unbundled resolve at runtime.
 */
export const VINEXT_NODE_INSTALL = [
  "vinext",
  "react",
  "react-dom",
  "react-server-dom-webpack",
] as const;

/**
 * The generated vinext Node serve entry: starts vinext's official
 * production server and answers `GET /health` on the same listener.
 */
export const makeVinextServeEntrySource = (): string =>
  `// Generated by @alchemy.run/frontend-frameworks/vinext/node.
import * as path from "node:path";
import { fileURLToPath } from "node:url";
import { startProdServer } from "vinext/server/prod-server";

const dir = path.dirname(fileURLToPath(import.meta.url));
const PORT = Number.parseInt(process.env.PORT ?? "${String(NODE_DEFAULT_PORT)}", 10);
const HOST = process.env.HOST ?? "0.0.0.0";

const { server } = await startProdServer({
  port: PORT,
  host: HOST,
  outDir: path.resolve(dir, ".."),
});

const isHealth = (req) => {
  const urlPath = (req.url ?? "/").split("?")[0];
  return (req.method === "GET" || req.method === "HEAD") && urlPath === "/health";
};

const existing = server.listeners("request").slice();
server.removeAllListeners("request");
server.on("request", (req, res) => {
  if (isHealth(req)) {
    res.writeHead(200, { "content-type": "text/plain; charset=utf-8" });
    res.end("ok");
    return;
  }
  for (const listener of existing) listener.call(server, req, res);
});
`;

export interface VinextNodeBuildChildConfig {
  readonly rootDir: string;
  readonly config: VinextNodeTargetConfig;
}

export const buildInChild = (config: VinextNodeBuildChildConfig) =>
  Effect.gen(function* () {
    const root = config.rootDir;
    yield* runVinextBuild({ root, cache: "redis" });
    const dist = yield* collectVinextDist(root);
    return yield* pinServeModule(dist, SERVER_ENTRY_NAME, makeVinextServeEntrySource());
  });

const makeNodeChildTarget = (config: VinextNodeTargetConfig = {}): VinextNodeTarget =>
  makeDeployTarget({
    platform: "node",
    config,
    bundle: {
      conditions: [...NODE_BUNDLE_CONDITIONS],
    },
  });

/**
 * Create the Node {@link VinextNodeTarget}: run Vinext's Vite build in a
 * child process, then vinext's production serve entry.
 */
export const makeNodeTarget = (config: VinextNodeTargetConfig = {}): VinextNodeTarget => ({
  ...makeNodeChildTarget(config),
  build: (context) =>
    runBuildChild({
      runtime: "node",
      module: import.meta.url,
      rootDir: context.root,
      env: context.env,
      framework: "vinext",
      config: {
        rootDir: context.root,
        config,
      } satisfies VinextNodeBuildChildConfig,
    }).pipe(Effect.mapError((error) => failTarget(error.message, error.cause))),
});

export const target = makeNodeTarget;

export default makeNodeTarget;

export interface VinextNodeService {
  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-Node framework service. See the module doc for the
 * `build`/`dev` semantics.
 */
export const make: (
  options?: VinextNodeOptions,
) => Effect.Effect<VinextNodeService, never, FileSystem.FileSystem | Path.Path> = Effect.fnUntraced(
  function* (options?: VinextNodeOptions) {
    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: VinextNodeService["build"] = Effect.fn(function* (
      buildOptions?: FrameworkCore.FrameworkBuildOptions,
    ) {
      const root = yield* resolveRoot(buildOptions?.root);
      const nodeTarget = makeNodeTarget({ root });
      const output = yield* nodeTarget.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: VinextNodeService["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 };
  },
);