@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 81 lines 2.83 KB
Raw
1 import { ConfigError } from "effect/Config";
2 import * as ConfigProvider from "effect/ConfigProvider";
3 import * as Data from "effect/Data";
4 import * as Effect from "effect/Effect";
5 import { FileSystem } from "effect/FileSystem";
6 import { envKeys, logLoadedKeys } from "./Log.ts";
7 import { resolveSecretsOption, type SecretsLayer, type SecretsOption } from "./Provider.ts";
8
9 export interface DotEnvOptions {
10 /**
11 * File or ordered files to load. Later files override earlier files.
12 * Every explicitly supplied path must exist; an empty array loads no files.
13 * @default ".env"
14 */
15 path?: string | readonly string[];
16 /**
17 * Expand `${VAR}` references within the file.
18 * @default false
19 */
20 expandVariables?: boolean;
21 }
22
23 /** A `secrets` entry that loads dotenv files. */
24 export class DotEnvProvider extends Data.TaggedClass("alchemy/SecretProvider::DotEnv")<{
25 readonly layer: SecretsLayer;
26 }> {}
27
28 /**
29 * Add dotenv files to Effect's ConfigProvider without touching `process.env`.
30 *
31 * Keys missing from every file fall back to the previous provider; an empty
32 * value in a file is a real value and overrides it. With no explicit `path`,
33 * a missing `.env` is silently ignored.
34 *
35 * Options may be a callback so a stack can pick files by stage:
36 *
37 * ```ts
38 * secrets: [Secrets.DotEnv(({ stage }) => ({ path: [".env", `.env.${stage}`] }))]
39 * ```
40 */
41 export const DotEnv = (options: SecretsOption<DotEnvOptions> = {}) =>
42 new DotEnvProvider({
43 layer: ConfigProvider.layerAdd(
44 Effect.gen(function* () {
45 const resolved = yield* resolveSecretsOption(options);
46 const fs = yield* FileSystem;
47
48 // The implicit default `.env` may be absent; a file named
49 // explicitly must exist.
50 const explicit = resolved.path !== undefined;
51 const path = resolved.path ?? ".env";
52 const paths = typeof path === "string" ? [path] : path;
53
54 let loaded = ConfigProvider.fromEnv({ env: {} });
55 for (const path of paths) {
56 const file = yield* Effect.gen(function* () {
57 if (!explicit && !(yield* fs.exists(path))) return undefined;
58 return yield* ConfigProvider.fromDotEnv({
59 path,
60 expandVariables: resolved.expandVariables,
61 preserveEmptyStrings: true,
62 });
63 }).pipe(
64 Effect.mapError(
65 (cause) =>
66 new ConfigError(
67 new ConfigProvider.SourceError({
68 message: `Failed to read dotenv file ${path}`,
69 cause,
70 }),
71 ),
72 ),
73 );
74 if (file !== undefined) loaded = ConfigProvider.orElse(file, loaded);
75 }
76 yield* logLoadedKeys(`dotenv (${paths.join(", ") || "no files"})`, yield* envKeys(loaded));
77 return loaded;
78 }),
79 { asPrimary: true },
80 ),
81 });