sailfork / t3code-github / .repos/ alchemy-effect/ packages/ alchemy/ src/ Cli/ commands/ flags.ts

import * as Argument from "effect/cli/Argument";
import * as CliError from "effect/cli/CliError";
import * as Flag from "effect/cli/Flag";
import * as Clock from "effect/Clock";
import * as Config from "effect/Config";
import * as ConfigProvider from "effect/ConfigProvider";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import { loadConfigProvider } from "../../Util/ConfigProvider.ts";
import { UserInputError } from "./errors.ts";

export const USER = Config.String("USER").pipe(
  Config.orElse(() => Config.String("USERNAME")),
  Config.withDefault("unknown"),
);

/**
 * `live_$USER`, `dev_$USER`, or `test_$USER` (falls back to `*_unknown`).
 * Characters a stage can't hold (`first.last`, `John Smith`) become `-`, so
 * the default always passes the `--stage` pattern and works in physical names.
 */
export const userStage = (kind: "live" | "dev" | "test") =>
  USER.pipe(
    Effect.map((user) => {
      const safe = user.replace(/[^a-z0-9_-]+/gi, "-").replace(/^-+|-+$/g, "");
      return `${kind}_${safe || "unknown"}`;
    }),
    Effect.orElseSucceed(() => `${kind}_unknown`),
  );

export const ALCHEMY_STAGE = Config.String("ALCHEMY_STAGE").pipe(
  Config.option,
  Effect.map(Option.getOrUndefined),
);

const STAGE_NAME_PATTERN = /^[a-z0-9]+([-_a-z0-9]+)*$/i;

const makeStageFlag = (kind: "live" | "dev") =>
  Flag.String("stage").pipe(
    Flag.withSchema(Schema.String.check(Schema.isPattern(/^[a-z0-9]+([-_a-z0-9]+)*$/gi))),
    Flag.withDescription(
      kind === "live"
        ? "Stage to deploy to. Defaults to $ALCHEMY_STAGE or live_${USER}"
        : "Stage to use for dev. Defaults to $ALCHEMY_STAGE or dev_${USER}",
    ),
    Flag.optional,
    Flag.map(Option.getOrUndefined),
  );

/** `--stage` for deploy / destroy / plan / logs / drift. Default: `live_$USER`. */
export const stage = makeStageFlag("live");

/** `--stage` for `alchemy dev`. Default: `dev_$USER`. */
export const devStage = makeStageFlag("dev");

/**
 * Resolve the target stage after the command's dotenv provider is known.
 * `--stage` wins; otherwise `$ALCHEMY_STAGE` from process env / `--env-file`
 * / `.env`; otherwise `live_$USER` or `dev_$USER`.
 *
 * `$STAGE` is not consulted. Use `$ALCHEMY_STAGE` so stage selection
 * matches `$ALCHEMY_PROFILE`.
 */
export const resolveStage = Effect.fn(function* (
  kind: "live" | "dev",
  override: string | undefined,
  envFile: Option.Option<string>,
) {
  if (override) return override;
  const provider = yield* loadConfigProvider(envFile);
  const configured = yield* ALCHEMY_STAGE.pipe(
    Effect.provideService(ConfigProvider.ConfigProvider, provider),
    Effect.orElseSucceed(() => undefined),
  );
  if (configured !== undefined && configured !== "") {
    if (!STAGE_NAME_PATTERN.test(configured)) {
      return yield* new UserInputError({
        message: `Invalid $ALCHEMY_STAGE '${configured}'. Must match [a-z0-9]+([-_a-z0-9]+)*.`,
      });
    }
    return configured;
  }
  return yield* userStage(kind);
});

// `Flag.File` accepts regular files only. Also accept a character device, so
// `--env-file /dev/null` reads as an empty env file.
export const envFile = Flag.Path("env-file", { typeName: "file" }).pipe(
  Flag.mapEffect((path) =>
    Effect.gen(function* () {
      const fs = yield* FileSystem.FileSystem;
      // A missing path fails later, when the file is read.
      const type = yield* fs.stat(path).pipe(
        Effect.map((info) => info.type),
        Effect.option,
      );
      if (Option.isSome(type) && type.value !== "File" && type.value !== "CharacterDevice") {
        return yield* CliError.InvalidValue.make({
          option: "env-file",
          value: path,
          expected: "a file or /dev/null",
          kind: "flag",
        });
      }
      return path;
    }),
  ),
  Flag.optional,
  Flag.withDescription("File to load environment variables from, defaults to .env"),
);

export const dryRun = Flag.Boolean("dry-run").pipe(
  Flag.withDescription("Dry run the deployment, do not actually deploy"),
  Flag.withDefault(false),
);

export const yes = Flag.Boolean("yes").pipe(
  Flag.withAlias("y"),
  Flag.withDescription("Yes to all prompts"),
  Flag.withDefault(false),
);

export const force = Flag.Boolean("force").pipe(
  Flag.withDescription("Force updates for resources that would otherwise no-op"),
  Flag.withDefault(false),
);

/** One pattern per occurrence; commas and whitespace are preserved. */
const selectionFlag = (name: "include" | "exclude", description: string) =>
  Flag.String(name).pipe(
    Flag.withDescription(description),
    Flag.atLeast(0),
    Flag.map((values) => (values.length === 0 ? undefined : values)),
  );

export const include = selectionFlag(
  "include",
  "Include exact FQNs, unique logical IDs, or FQN globs and their dependencies (repeatable, one pattern per flag). Quote globs: --include 'App/**'. Other rows and stack outputs are preserved; the whole declaration still runs.",
);

export const exclude = selectionFlag(
  "exclude",
  "Exclude exact FQNs, unique logical IDs, or FQN globs (repeatable, one pattern per flag). Quote globs: --exclude 'App/Legacy/**'. Required excluded dependencies fail planning, even when unchanged.",
);

export const validateSelectionOptions = (options: {
  readonly include?: ReadonlyArray<string>;
  readonly exclude?: ReadonlyArray<string>;
  readonly destroy?: boolean;
  readonly detectDrift?: boolean;
}) =>
  (options.include !== undefined || options.exclude !== undefined) &&
  (options.destroy || options.detectDrift)
    ? Effect.fail(
        new UserInputError({
          message: "--include/--exclude cannot be combined with destroy or --detect-drift.",
        }),
      )
    : Effect.void;

export const config = Flag.File("config", { mustExist: true }).pipe(
  Flag.withDescription("Alchemy entrypoint file (default: alchemy.run.ts)"),
  Flag.withAlias("c"),
  Flag.withDefault("alchemy.run.ts"),
);

export const optionalConfig = Flag.File("config", { mustExist: true }).pipe(
  Flag.withDescription("Alchemy entrypoint file (default: alchemy.run.ts)"),
  Flag.withAlias("c"),
  Flag.optional,
  Flag.map(Option.getOrUndefined),
);

export const configPath = Argument.File("config", { mustExist: true }).pipe(
  Argument.withDescription("Alchemy entrypoint file (default: alchemy.run.ts)"),
  Argument.optional,
  Argument.map(Option.getOrUndefined),
);

export const resolveConfig = <
  A extends {
    readonly config: string | undefined;
    readonly configPath: string | undefined;
  },
>(
  args: A,
) =>
  Effect.gen(function* () {
    if (args.config !== undefined && args.configPath !== undefined) {
      return yield* new UserInputError({
        message: "Pass the config path either positionally or with --config, not both.",
      });
    }
    return {
      ...args,
      main: args.config ?? args.configPath ?? "alchemy.run.ts",
    };
  });

export const resolveStackArgs =
  (kind: "live" | "dev") =>
  <
    A extends {
      readonly config: string | undefined;
      readonly configPath: string | undefined;
      readonly stage: string | undefined;
      readonly envFile: Option.Option<string>;
    },
  >(
    args: A,
  ) =>
    Effect.gen(function* () {
      const resolved = yield* resolveConfig(args);
      const stage = yield* resolveStage(kind, args.stage, args.envFile);
      return { ...resolved, stage };
    });

export const profile = Flag.String("profile").pipe(
  Flag.withDescription("Auth profile to use. Defaults to $ALCHEMY_PROFILE or 'default'."),
  Flag.optional,
  Flag.map(Option.getOrUndefined),
);

export const parseSince = (value: string) =>
  Effect.gen(function* () {
    const match = value.match(/^(\d+)([smhd])$/);
    if (match) {
      const amount = match[1];
      const unit = match[2];
      if (amount === undefined || unit === undefined) {
        return yield* new UserInputError({
          message: `Invalid --since value: '${value}'.`,
        });
      }
      const num = parseInt(amount, 10);
      const duration =
        unit === "s"
          ? Duration.seconds(num)
          : unit === "m"
            ? Duration.minutes(num)
            : unit === "h"
              ? Duration.hours(num)
              : Duration.days(num);
      const now = yield* Clock.currentTimeMillis;
      return new Date(now - Duration.toMillis(duration));
    }
    const parsed = new Date(value);
    if (isNaN(parsed.getTime())) {
      return yield* new UserInputError({
        message: `Invalid --since value: '${value}'. Use a duration (e.g. '1h', '30m') or ISO date.`,
      });
    }
    return parsed;
  });