The best way to control Claude Code, Codex and more from any computer or phone

main
ts 257 lines 8.56 KB
Raw
1 import * as Argument from "effect/cli/Argument";
2 import * as CliError from "effect/cli/CliError";
3 import * as Flag from "effect/cli/Flag";
4 import * as Clock from "effect/Clock";
5 import * as Config from "effect/Config";
6 import * as ConfigProvider from "effect/ConfigProvider";
7 import * as Duration from "effect/Duration";
8 import * as Effect from "effect/Effect";
9 import * as FileSystem from "effect/FileSystem";
10 import * as Option from "effect/Option";
11 import * as Schema from "effect/Schema";
12 import { loadConfigProvider } from "../../Util/ConfigProvider.ts";
13 import { UserInputError } from "./errors.ts";
14
15 export const USER = Config.String("USER").pipe(
16 Config.orElse(() => Config.String("USERNAME")),
17 Config.withDefault("unknown"),
18 );
19
20 /**
21 * `live_$USER`, `dev_$USER`, or `test_$USER` (falls back to `*_unknown`).
22 * Characters a stage can't hold (`first.last`, `John Smith`) become `-`, so
23 * the default always passes the `--stage` pattern and works in physical names.
24 */
25 export const userStage = (kind: "live" | "dev" | "test") =>
26 USER.pipe(
27 Effect.map((user) => {
28 const safe = user.replace(/[^a-z0-9_-]+/gi, "-").replace(/^-+|-+$/g, "");
29 return `${kind}_${safe || "unknown"}`;
30 }),
31 Effect.orElseSucceed(() => `${kind}_unknown`),
32 );
33
34 export const ALCHEMY_STAGE = Config.String("ALCHEMY_STAGE").pipe(
35 Config.option,
36 Effect.map(Option.getOrUndefined),
37 );
38
39 const STAGE_NAME_PATTERN = /^[a-z0-9]+([-_a-z0-9]+)*$/i;
40
41 const makeStageFlag = (kind: "live" | "dev") =>
42 Flag.String("stage").pipe(
43 Flag.withSchema(Schema.String.check(Schema.isPattern(/^[a-z0-9]+([-_a-z0-9]+)*$/gi))),
44 Flag.withDescription(
45 kind === "live"
46 ? "Stage to deploy to. Defaults to $ALCHEMY_STAGE or live_${USER}"
47 : "Stage to use for dev. Defaults to $ALCHEMY_STAGE or dev_${USER}",
48 ),
49 Flag.optional,
50 Flag.map(Option.getOrUndefined),
51 );
52
53 /** `--stage` for deploy / destroy / plan / logs / drift. Default: `live_$USER`. */
54 export const stage = makeStageFlag("live");
55
56 /** `--stage` for `alchemy dev`. Default: `dev_$USER`. */
57 export const devStage = makeStageFlag("dev");
58
59 /**
60 * Resolve the target stage after the command's dotenv provider is known.
61 * `--stage` wins; otherwise `$ALCHEMY_STAGE` from process env / `--env-file`
62 * / `.env`; otherwise `live_$USER` or `dev_$USER`.
63 *
64 * `$STAGE` is not consulted. Use `$ALCHEMY_STAGE` so stage selection
65 * matches `$ALCHEMY_PROFILE`.
66 */
67 export const resolveStage = Effect.fn(function* (
68 kind: "live" | "dev",
69 override: string | undefined,
70 envFile: Option.Option<string>,
71 ) {
72 if (override) return override;
73 const provider = yield* loadConfigProvider(envFile);
74 const configured = yield* ALCHEMY_STAGE.pipe(
75 Effect.provideService(ConfigProvider.ConfigProvider, provider),
76 Effect.orElseSucceed(() => undefined),
77 );
78 if (configured !== undefined && configured !== "") {
79 if (!STAGE_NAME_PATTERN.test(configured)) {
80 return yield* new UserInputError({
81 message: `Invalid $ALCHEMY_STAGE '${configured}'. Must match [a-z0-9]+([-_a-z0-9]+)*.`,
82 });
83 }
84 return configured;
85 }
86 return yield* userStage(kind);
87 });
88
89 // `Flag.File` accepts regular files only. Also accept a character device, so
90 // `--env-file /dev/null` reads as an empty env file.
91 export const envFile = Flag.Path("env-file", { typeName: "file" }).pipe(
92 Flag.mapEffect((path) =>
93 Effect.gen(function* () {
94 const fs = yield* FileSystem.FileSystem;
95 // A missing path fails later, when the file is read.
96 const type = yield* fs.stat(path).pipe(
97 Effect.map((info) => info.type),
98 Effect.option,
99 );
100 if (Option.isSome(type) && type.value !== "File" && type.value !== "CharacterDevice") {
101 return yield* CliError.InvalidValue.make({
102 option: "env-file",
103 value: path,
104 expected: "a file or /dev/null",
105 kind: "flag",
106 });
107 }
108 return path;
109 }),
110 ),
111 Flag.optional,
112 Flag.withDescription("File to load environment variables from, defaults to .env"),
113 );
114
115 export const dryRun = Flag.Boolean("dry-run").pipe(
116 Flag.withDescription("Dry run the deployment, do not actually deploy"),
117 Flag.withDefault(false),
118 );
119
120 export const yes = Flag.Boolean("yes").pipe(
121 Flag.withAlias("y"),
122 Flag.withDescription("Yes to all prompts"),
123 Flag.withDefault(false),
124 );
125
126 export const force = Flag.Boolean("force").pipe(
127 Flag.withDescription("Force updates for resources that would otherwise no-op"),
128 Flag.withDefault(false),
129 );
130
131 /** One pattern per occurrence; commas and whitespace are preserved. */
132 const selectionFlag = (name: "include" | "exclude", description: string) =>
133 Flag.String(name).pipe(
134 Flag.withDescription(description),
135 Flag.atLeast(0),
136 Flag.map((values) => (values.length === 0 ? undefined : values)),
137 );
138
139 export const include = selectionFlag(
140 "include",
141 "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.",
142 );
143
144 export const exclude = selectionFlag(
145 "exclude",
146 "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.",
147 );
148
149 export const validateSelectionOptions = (options: {
150 readonly include?: ReadonlyArray<string>;
151 readonly exclude?: ReadonlyArray<string>;
152 readonly destroy?: boolean;
153 readonly detectDrift?: boolean;
154 }) =>
155 (options.include !== undefined || options.exclude !== undefined) &&
156 (options.destroy || options.detectDrift)
157 ? Effect.fail(
158 new UserInputError({
159 message: "--include/--exclude cannot be combined with destroy or --detect-drift.",
160 }),
161 )
162 : Effect.void;
163
164 export const config = Flag.File("config", { mustExist: true }).pipe(
165 Flag.withDescription("Alchemy entrypoint file (default: alchemy.run.ts)"),
166 Flag.withAlias("c"),
167 Flag.withDefault("alchemy.run.ts"),
168 );
169
170 export const optionalConfig = Flag.File("config", { mustExist: true }).pipe(
171 Flag.withDescription("Alchemy entrypoint file (default: alchemy.run.ts)"),
172 Flag.withAlias("c"),
173 Flag.optional,
174 Flag.map(Option.getOrUndefined),
175 );
176
177 export const configPath = Argument.File("config", { mustExist: true }).pipe(
178 Argument.withDescription("Alchemy entrypoint file (default: alchemy.run.ts)"),
179 Argument.optional,
180 Argument.map(Option.getOrUndefined),
181 );
182
183 export const resolveConfig = <
184 A extends {
185 readonly config: string | undefined;
186 readonly configPath: string | undefined;
187 },
188 >(
189 args: A,
190 ) =>
191 Effect.gen(function* () {
192 if (args.config !== undefined && args.configPath !== undefined) {
193 return yield* new UserInputError({
194 message: "Pass the config path either positionally or with --config, not both.",
195 });
196 }
197 return {
198 ...args,
199 main: args.config ?? args.configPath ?? "alchemy.run.ts",
200 };
201 });
202
203 export const resolveStackArgs =
204 (kind: "live" | "dev") =>
205 <
206 A extends {
207 readonly config: string | undefined;
208 readonly configPath: string | undefined;
209 readonly stage: string | undefined;
210 readonly envFile: Option.Option<string>;
211 },
212 >(
213 args: A,
214 ) =>
215 Effect.gen(function* () {
216 const resolved = yield* resolveConfig(args);
217 const stage = yield* resolveStage(kind, args.stage, args.envFile);
218 return { ...resolved, stage };
219 });
220
221 export const profile = Flag.String("profile").pipe(
222 Flag.withDescription("Auth profile to use. Defaults to $ALCHEMY_PROFILE or 'default'."),
223 Flag.optional,
224 Flag.map(Option.getOrUndefined),
225 );
226
227 export const parseSince = (value: string) =>
228 Effect.gen(function* () {
229 const match = value.match(/^(\d+)([smhd])$/);
230 if (match) {
231 const amount = match[1];
232 const unit = match[2];
233 if (amount === undefined || unit === undefined) {
234 return yield* new UserInputError({
235 message: `Invalid --since value: '${value}'.`,
236 });
237 }
238 const num = parseInt(amount, 10);
239 const duration =
240 unit === "s"
241 ? Duration.seconds(num)
242 : unit === "m"
243 ? Duration.minutes(num)
244 : unit === "h"
245 ? Duration.hours(num)
246 : Duration.days(num);
247 const now = yield* Clock.currentTimeMillis;
248 return new Date(now - Duration.toMillis(duration));
249 }
250 const parsed = new Date(value);
251 if (isNaN(parsed.getTime())) {
252 return yield* new UserInputError({
253 message: `Invalid --since value: '${value}'. Use a duration (e.g. '1h', '30m') or ISO date.`,
254 });
255 }
256 return parsed;
257 });