Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
| 1 | import { ConfigProvider, Effect, FileSystem, PlatformError, Predicate } from 'effect'; |
| 2 | import { JSONParse, JSONParseError } from 'src/effects/json'; |
| 3 | |
| 4 | /** |
| 5 | * Lazy version of an `effect/ConfigProvider` that reads config values from a |
| 6 | * JSON file. The file is not read until the returned provider is first |
| 7 | * consulted for a config value, and the parsed provider is cached for |
| 8 | * subsequent lookups within the same process. |
| 9 | * |
| 10 | * A missing file is treated as "no config here" (every path lookup resolves |
| 11 | * to `undefined`, matching `ConfigProvider`'s not-found contract) rather than |
| 12 | * a hard failure — callers can still fall back to other providers or |
| 13 | * `Config.withDefault`. Any other read/parse failure surfaces as a |
| 14 | * `ConfigProvider.SourceError`. |
| 15 | */ |
| 16 | export const configProviderFromLazyJson = ( |
| 17 | filePath: string |
| 18 | ): Effect.Effect<ConfigProvider.ConfigProvider, never, FileSystem.FileSystem> => |
| 19 | Effect.gen(function* () { |
| 20 | const fs = yield* FileSystem.FileSystem; |
| 21 | |
| 22 | const isNotFound = (error: PlatformError.PlatformError): boolean => |
| 23 | Predicate.isTagged(error.reason, 'NotFound'); |
| 24 | |
| 25 | // Memoize the built provider so the file is read (and parsed) at most |
| 26 | // once per process, no matter how many config paths are looked up. |
| 27 | let cached: ConfigProvider.ConfigProvider | undefined; |
| 28 | |
| 29 | const loadRootProvider: Effect.Effect< |
| 30 | ConfigProvider.ConfigProvider | undefined, |
| 31 | ConfigProvider.SourceError |
| 32 | > = Effect.gen(function* () { |
| 33 | if (cached) { |
| 34 | return cached; |
| 35 | } |
| 36 | |
| 37 | const content = yield* fs.readFileString(filePath, 'utf-8').pipe( |
| 38 | Effect.map((text): string | undefined => text), |
| 39 | Effect.catchIf(isNotFound, () => Effect.succeed(undefined)), |
| 40 | Effect.mapError( |
| 41 | error => |
| 42 | new ConfigProvider.SourceError({ |
| 43 | message: error.message, |
| 44 | cause: error, |
| 45 | }) |
| 46 | ) |
| 47 | ); |
| 48 | |
| 49 | if (content === undefined) { |
| 50 | return undefined; |
| 51 | } |
| 52 | |
| 53 | const json = yield* JSONParse(content).pipe( |
| 54 | Effect.mapError( |
| 55 | (error: JSONParseError) => |
| 56 | new ConfigProvider.SourceError({ message: error.message, cause: error }) |
| 57 | ) |
| 58 | ); |
| 59 | |
| 60 | cached = ConfigProvider.fromUnknown(json); |
| 61 | return cached; |
| 62 | }); |
| 63 | |
| 64 | return ConfigProvider.make(path => |
| 65 | Effect.flatMap(loadRootProvider, provider => |
| 66 | provider ? provider.load(path) : Effect.succeed(undefined) |
| 67 | ) |
| 68 | ); |
| 69 | }); |