-
-
Notifications
You must be signed in to change notification settings - Fork 633
Expand file tree
/
Copy pathConfigProvider.ts
More file actions
1212 lines (1131 loc) · 35.7 KB
/
Copy pathConfigProvider.ts
File metadata and controls
1212 lines (1131 loc) · 35.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Data sources used by `Config` to load raw configuration values. A
* `ConfigProvider` reads paths from places such as environment variables,
* JavaScript objects, `.env` contents, or directories, and returns a uniform
* `Node` shape that config schemas can decode. The module also includes helpers
* for composing providers, changing paths, and installing providers through
* layers.
*
* @since 4.0.0
*/
import * as Context from "./Context.ts"
import * as Data from "./Data.ts"
import * as Effect from "./Effect.ts"
import * as FileSystem from "./FileSystem.ts"
import { format } from "./Formatter.ts"
import { dual, flow } from "./Function.ts"
import { PipeInspectableProto } from "./internal/core.ts"
import * as Layer from "./Layer.ts"
import * as Path_ from "./Path.ts"
import type { Pipeable } from "./Pipeable.ts"
import type { PlatformError } from "./PlatformError.ts"
import * as Predicate from "./Predicate.ts"
import type { Scope } from "./Scope.ts"
import * as Str from "./String.ts"
/**
* A discriminated union describing the shape of a configuration value at a
* given path.
*
* **When to use**
*
* Use when implementing a custom `ConfigProvider` by returning raw
* nodes from the `get` callback passed to {@link make}, or when inspecting raw
* provider output before schema parsing.
*
* **Details**
*
* `Value` is a terminal string leaf. `Record` is an object-like container
* whose immediate child keys are known and may carry an optional co-located
* `value`. `Array` is an indexed container with a known `length` and may also
* carry an optional co-located `value`.
*
* @see {@link makeValue} – construct a `Value` node
* @see {@link makeRecord} – construct a `Record` node
* @see {@link makeArray} – construct an `Array` node
*
* @category models
* @since 4.0.0
*/
export type Node =
/** A terminal string value */
| {
readonly _tag: "Value"
readonly value: string
}
/** An object; keys are unordered */
| {
readonly _tag: "Record"
readonly keys: ReadonlySet<string>
readonly value: string | undefined
}
/** An array-like container; length is the number of elements */
| {
readonly _tag: "Array"
readonly length: number
readonly value: string | undefined
}
/**
* Creates a `Value` node representing a terminal string leaf.
*
* **When to use**
*
* Use when building nodes inside a custom `ConfigProvider`'s `get`
* callback.
*
* **Details**
*
* The function returns a new plain object.
*
* **Example** (Creating a value node)
*
* ```ts
* import { ConfigProvider } from "effect"
*
* const node = ConfigProvider.makeValue("3000")
* // { _tag: "Value", value: "3000" }
* ```
*
* @see {@link makeRecord} – for object-like containers
* @see {@link makeArray} – for array-like containers
*
* @category constructors
* @since 4.0.0
*/
export function makeValue(value: string): Node {
return { _tag: "Value", value }
}
/**
* Creates a `Record` node representing an object-like container with known
* child keys.
*
* **When to use**
*
* Use when you need to describe a directory or JSON object inside a custom
* provider.
*
* **Details**
*
* The optional `value` allows a node to be both a container and a leaf at the
* same time (for example, an env var `A=x` that also has children `A_FOO` and
* `A_BAR`).
*
* **Example** (Creating a record node)
*
* ```ts
* import { ConfigProvider } from "effect"
*
* const node = ConfigProvider.makeRecord(new Set(["host", "port"]))
* // { _tag: "Record", keys: Set(["host", "port"]), value: undefined }
* ```
*
* @see {@link makeValue} – for terminal leaves
* @see {@link makeArray} – for array-like containers
*
* @category constructors
* @since 4.0.0
*/
export function makeRecord(keys: ReadonlySet<string>, value?: string): Node {
return { _tag: "Record", keys, value }
}
/**
* Creates an `Array` node representing an indexed container with a known
* length.
*
* **When to use**
*
* Use when you need to describe a JSON array or numerically indexed env vars
* inside a custom provider.
*
* **Details**
*
* The optional `value` allows a node to be both a container and a leaf at the
* same time.
*
* **Example** (Creating an array node)
*
* ```ts
* import { ConfigProvider } from "effect"
*
* const node = ConfigProvider.makeArray(3)
* // { _tag: "Array", length: 3, value: undefined }
* ```
*
* @see {@link makeValue} – for terminal leaves
* @see {@link makeRecord} – for object-like containers
*
* @category constructors
* @since 4.0.0
*/
export function makeArray(length: number, value?: string): Node {
return { _tag: "Array", length, value }
}
/**
* Typed error indicating that a configuration source could not be read.
*
* **When to use**
*
* Use when you need to report that a custom provider's underlying store is
* unreachable or produced an I/O error while reading configuration data.
*
* **Gotchas**
*
* Do not use `SourceError` for "key not found". That case is represented by
* returning `undefined` from `load`.
*
* **Example** (Failing with a SourceError)
*
* ```ts
* import { ConfigProvider, Effect } from "effect"
*
* const provider = ConfigProvider.make((_path) =>
* Effect.fail(
* new ConfigProvider.SourceError({ message: "connection refused" })
* )
* )
* ```
*
* @see {@link ConfigProvider} – the interface whose `load` may fail with this
* error
*
* @category models
* @since 4.0.0
*/
export class SourceError extends Data.TaggedError("SourceError")<{
readonly message: string
readonly cause?: unknown
}> {}
/**
* An ordered sequence of string or numeric segments that addresses a node in
* the configuration tree. String segments name object keys; numeric segments
* index into arrays.
*
* **When to use**
*
* Use to address raw configuration nodes when implementing or transforming a
* `ConfigProvider`.
*
* **Example** (A typical config path)
*
* ```ts
* import type { ConfigProvider } from "effect"
*
* const path: ConfigProvider.Path = ["database", "replicas", 0, "host"]
* ```
*
* @category models
* @since 4.0.0
*/
export type Path = ReadonlyArray<string | number>
/**
* The core interface for loading raw configuration data.
*
* **When to use**
*
* Use to type-annotate variables that hold a provider or to implement a
* custom provider via {@link make}.
*
* **Details**
*
* `load(path)` is the semantic lookup operation used by the `Config` module.
* It applies provider transformations and composition before consulting the
* underlying source. `undefined` means "not found" and `SourceError` means the
* source itself failed.
*
* @see {@link make} – construct a provider from a lookup function
* @see {@link orElse} – compose providers with fallback
*
* @category models
* @since 2.0.0
*/
export interface ConfigProvider extends Pipeable {
/**
* Returns the node found at `path`, or `undefined` if it does not exist.
* Fails with `SourceError` when the underlying source cannot be read.
*
* **When to use**
*
* Use to resolve a path through this provider's path transformations before
* reading the backing source.
*/
readonly load: (path: Path) => Effect.Effect<Node | undefined, SourceError>
/** @internal */
readonly state: ProviderState
}
/**
* Context reference for the active raw configuration provider, registered in the context with a
* default value of `fromEnv()`. Because it is a `Context.Reference`, it is
* available without explicit provision; `Config` schemas automatically resolve
* it.
*
* **When to use**
*
* Use to override the active raw configuration provider for an entire program,
* or retrieve the current provider inside an Effect.
*
* **Example** (Providing a custom provider)
*
* ```ts
* import { ConfigProvider, Effect } from "effect"
*
* const provider = ConfigProvider.fromUnknown({ port: 8080 })
*
* const program = Effect.gen(function*() {
* const current = yield* ConfigProvider.ConfigProvider
* return current
* }).pipe(
* Effect.provideService(ConfigProvider.ConfigProvider, provider)
* )
* ```
*
* @see {@link layer} – install a provider as a Layer
* @see {@link layerAdd} – add a fallback provider as a Layer
*
* @category services
* @since 2.0.0
*/
export const ConfigProvider: Context.Reference<ConfigProvider> = Context.Reference<ConfigProvider>(
"effect/ConfigProvider",
{ defaultValue: () => fromEnv() }
)
const Proto = {
...PipeInspectableProto,
toJSON(this: ConfigProvider) {
return {
_id: "ConfigProvider"
}
}
}
type SourceState = {
readonly _tag: "Source"
readonly get: (path: Path) => Effect.Effect<Node | undefined, SourceError>
readonly transform: (path: Path) => Path
}
type OrElseState = {
readonly _tag: "OrElse"
readonly first: ConfigProvider
readonly second: ConfigProvider
}
type ProviderState = SourceState | OrElseState
const identityPath = (path: Path): Path => path
function makeProvider(
state: ProviderState,
load: (path: Path) => Effect.Effect<Node | undefined, SourceError>
): ConfigProvider {
const self = Object.create(Proto)
self.state = state
self.load = load
return self
}
function makeSource(
get: (path: Path) => Effect.Effect<Node | undefined, SourceError>,
transform: (path: Path) => Path
): ConfigProvider {
const state: SourceState = {
_tag: "Source",
get,
transform
}
return makeProvider(state, (path) => state.get(state.transform(path)))
}
function makeOrElse(first: ConfigProvider, second: ConfigProvider): ConfigProvider {
const state: OrElseState = {
_tag: "OrElse",
first,
second
}
return makeProvider(state, (path) =>
Effect.flatMap(
state.first.load(path),
(node) => node ? Effect.succeed(node) : state.second.load(path)
))
}
/**
* Creates a `ConfigProvider` from a raw lookup function.
*
* **When to use**
*
* Use when implementing a provider backed by a custom store, such as a
* database, remote API, or in-memory map.
*
* **Details**
*
* The `get` callback receives a `Path` and must return
* `Effect<Node | undefined, SourceError>`. Return `undefined` when the path
* does not exist; fail with `SourceError` only for actual I/O errors.
*
* **Example** (Creating a simple in-memory provider)
*
* ```ts
* import { ConfigProvider, Effect } from "effect"
*
* const data: Record<string, string> = {
* host: "localhost",
* port: "5432"
* }
*
* const provider = ConfigProvider.make((path) => {
* const key = path.join(".")
* const value = data[key]
* return Effect.succeed(
* value !== undefined ? ConfigProvider.makeValue(value) : undefined
* )
* })
* ```
*
* @see {@link fromEnv} – pre-built provider for environment variables
* @see {@link fromUnknown} – pre-built provider for JSON objects
*
* @category constructors
* @since 2.0.0
*/
export function make(get: (path: Path) => Effect.Effect<Node | undefined, SourceError>): ConfigProvider {
return makeSource(get, identityPath)
}
/**
* Returns a provider that falls back to `that` when `self` returns `undefined`
* for a path.
*
* **When to use**
*
* Use to layer multiple config sources, such as env vars plus a defaults file,
* or provide partial overrides on top of a base config.
*
* **Details**
*
* Each provider keeps its own path transformations. If the combined provider
* is later transformed with {@link mapInput} or {@link nested}, the
* transformation is applied to both sides.
*
* **Gotchas**
*
* The fallback only runs when the path is not found (`undefined`). A
* `SourceError` from `self` is not caught; it propagates immediately.
*
* **Example** (Falling back to a default provider)
*
* ```ts
* import { ConfigProvider } from "effect"
*
* const envProvider = ConfigProvider.fromEnv({
* env: { HOST: "prod.example.com" }
* })
* const defaults = ConfigProvider.fromUnknown({ HOST: "localhost", PORT: "3000" })
*
* const combined = ConfigProvider.orElse(envProvider, defaults)
* ```
*
* @see {@link layerAdd} – install a fallback provider via a Layer
*
* @category combinators
* @since 2.0.0
*/
export const orElse: {
(that: ConfigProvider): (self: ConfigProvider) => ConfigProvider
(self: ConfigProvider, that: ConfigProvider): ConfigProvider
} = dual(
2,
(self: ConfigProvider, that: ConfigProvider): ConfigProvider => makeOrElse(self, that)
)
/**
* Transforms the path segments before they reach the underlying store.
*
* **When to use**
*
* Use when you need to rename, re-case, or otherwise transform config path
* segments before lookup.
*
* **Details**
*
* The function `f` receives the whole path produced by earlier provider
* transformations and must return a new path. Lookup path transformations
* compose in application order: the existing transformation runs first, then
* `f` runs. For providers composed with {@link orElse}, the transformation is
* applied to each operand.
*
* **Example** (Uppercasing path segments)
*
* ```ts
* import { ConfigProvider } from "effect"
*
* const provider = ConfigProvider.fromEnv({
* env: { APP_HOST: "localhost" }
* })
*
* const upper = ConfigProvider.mapInput(provider, (path) =>
* path.map((seg) =>
* typeof seg === "string" ? seg.toUpperCase() : seg
* )
* )
* ```
*
* @see {@link constantCase} – a preset that converts to `CONSTANT_CASE`
* @see {@link nested} – for prepending a prefix instead of transforming
*
* @category combinators
* @since 4.0.0
*/
export const mapInput: {
(f: (path: Path) => Path): (self: ConfigProvider) => ConfigProvider
(self: ConfigProvider, f: (path: Path) => Path): ConfigProvider
} = dual(
2,
(self: ConfigProvider, f: (path: Path) => Path): ConfigProvider => {
const state = self.state
switch (state._tag) {
case "Source":
return makeSource(state.get, flow(state.transform, f))
case "OrElse":
return makeOrElse(mapInput(state.first, f), mapInput(state.second, f))
}
}
)
/**
* Converts all string path segments to `CONSTANT_CASE` before lookup.
*
* **When to use**
*
* Use to bridge camelCase schema keys to `SCREAMING_SNAKE_CASE`
* environment variables.
*
* **Details**
*
* Numeric segments are left unchanged. String segments use `String.configCase`
* so numeric word groups such as `v2` are preserved for environment variable
* names. This is a specialization of {@link mapInput}.
*
* **Example** (Resolving camelCase keys to env vars)
*
* ```ts
* import { ConfigProvider } from "effect"
*
* const provider = ConfigProvider.fromEnv({
* env: { DATABASE_HOST: "localhost" }
* }).pipe(ConfigProvider.constantCase)
*
* // path ["databaseHost"] now resolves to env var DATABASE_HOST
* ```
*
* @see {@link mapInput} – for arbitrary path transformations
*
* @category combinators
* @since 2.0.0
*/
export const constantCase: (self: ConfigProvider) => ConfigProvider = mapInput((path) =>
path.map((seg) => typeof seg === "number" ? seg : Str.configCase(seg))
)
/**
* Scopes a provider so that all lookups are prefixed with the given path
* segments.
*
* **When to use**
*
* Use to namespace config under a prefix like `"app"` or `"database"`, or
* reuse the same provider shape for multiple sub-configs.
*
* **Details**
*
* Accepts a single string or a full `Path` array. For providers composed with
* {@link orElse}, the prefix is applied to each operand. Supports both
* data-last and data-first calling conventions.
*
* **Gotchas**
*
* Ordering matters when composing with {@link mapInput} or
* {@link constantCase}. Later provider transformations run after earlier ones:
* a later `nested` becomes the outer prefix, and a later `mapInput` sees the
* whole path produced by previous transformations.
*
* **Example** (Nesting under a prefix)
*
* ```ts
* import { ConfigProvider } from "effect"
*
* const provider = ConfigProvider.fromEnv({
* env: { APP_HOST: "localhost", APP_PORT: "3000" }
* })
*
* // Lookups for ["HOST"] now resolve to ["APP", "HOST"]
* const scoped = ConfigProvider.nested(provider, "APP")
* ```
*
* @see {@link mapInput} – for arbitrary path transformations
*
* @category combinators
* @since 2.0.0
*/
export const nested: {
(prefix: string | Path): (self: ConfigProvider) => ConfigProvider
(self: ConfigProvider, prefix: string | Path): ConfigProvider
} = dual(
2,
(self: ConfigProvider, prefix: string | Path): ConfigProvider => {
const path = typeof prefix === "string" ? [prefix] : prefix
const state = self.state
switch (state._tag) {
case "Source":
return makeSource(state.get, flow(state.transform, (input) => [...path, ...input]))
case "OrElse":
return makeOrElse(nested(state.first, path), nested(state.second, path))
}
}
)
/**
* Provides a layer that installs a `ConfigProvider` as the active provider for
* all downstream effects, replacing any previously installed provider.
*
* **When to use**
*
* Use to set the config source for an entire application or test suite.
*
* **Details**
*
* Accepts either a plain `ConfigProvider` or an `Effect` that produces one.
* When given an Effect, it is evaluated once when the layer is built.
*
* **Example** (Reading config from a JSON object)
*
* ```ts
* import { Config, ConfigProvider, Effect, Layer } from "effect"
*
* const TestLayer = ConfigProvider.layer(
* ConfigProvider.fromUnknown({ port: 8080 })
* )
*
* const program = Effect.gen(function*() {
* const port = yield* Config.number("port")
* return port
* })
*
* // Effect.runSync(Effect.provide(program, TestLayer)) // 8080
* ```
*
* @see {@link layerAdd} – add a provider without replacing the existing one
*
* @category layers
* @since 4.0.0
*/
export const layer = <E = never, R = never>(
self: ConfigProvider | Effect.Effect<ConfigProvider, E, R>
): Layer.Layer<never, E, Exclude<R, Scope>> =>
Effect.isEffect(self) ? Layer.effect(ConfigProvider)(self) : Layer.succeed(ConfigProvider)(self)
/**
* Creates a Layer that composes a new `ConfigProvider` with the currently
* active one, rather than replacing it.
*
* **When to use**
*
* Use to add defaults that should only apply when the primary provider has no
* value for a path, or override specific keys while keeping the rest from the
* existing provider by setting `asPrimary: true`.
*
* **Details**
*
* By default, the new provider acts as a fallback and is consulted only when
* the current provider returns `undefined`. Set `asPrimary: true` to make the
* new provider the primary source, with the existing one as fallback.
*
* **Example** (Adding default values)
*
* ```ts
* import { ConfigProvider } from "effect"
*
* const defaults = ConfigProvider.fromUnknown({
* HOST: "localhost",
* PORT: "3000"
* })
*
* // The current env provider is tried first; `defaults` is the fallback
* const DefaultsLayer = ConfigProvider.layerAdd(defaults)
* ```
*
* @see {@link layer} – replace the provider entirely
* @see {@link orElse} – compose providers without layers
*
* @category layers
* @since 4.0.0
*/
export const layerAdd = <E = never, R = never>(
self: ConfigProvider | Effect.Effect<ConfigProvider, E, R>,
options?: {
readonly asPrimary?: boolean | undefined
} | undefined
): Layer.Layer<never, E, Exclude<R, Scope>> =>
Layer.effect(ConfigProvider)(
Effect.gen(function*() {
const current = yield* ConfigProvider
const configProvider = Effect.isEffect(self) ? yield* self : self
return options?.asPrimary ? orElse(configProvider, current) : orElse(current, configProvider)
})
)
/**
* Creates a `ConfigProvider` backed by an in-memory JavaScript value
* (typically a parsed JSON object).
*
* **When to use**
*
* Use when you need deterministic config from an in-memory JavaScript value,
* such as in tests, embedded config, or parsed JSON.
*
* **Details**
*
* Path traversal follows standard JS rules: string segments index into object
* keys, numeric segments index into arrays. Returns `undefined` for any path
* that cannot be resolved. Never fails with `SourceError`.
*
* Primitive values (`number`, `boolean`, `bigint`) are stringified via
* `String(...)`.
*
* Literal empty strings are treated as missing values when loaded as values by
* default. Pass `{ preserveEmptyStrings: true }` to keep empty strings as
* explicit values.
*
* **Gotchas**
*
* Object keys and array lengths reflect the original input shape. A leaf value
* of `""` is treated as missing when that leaf is loaded, but the parent
* container still reports its original keys or length.
*
* **Example** (Providing config from a plain object)
*
* ```ts
* import { Config, ConfigProvider, Effect } from "effect"
*
* const provider = ConfigProvider.fromUnknown({
* database: {
* host: "localhost",
* port: 5432
* }
* })
*
* const host = Config.string("host").parse(
* provider.pipe(ConfigProvider.nested("database"))
* )
*
* // Effect.runSync(host) // "localhost"
* ```
*
* @see {@link fromEnv} – for environment variables
* @see {@link make} – for custom backing stores
*
* @category ConfigProviders
* @since 4.0.0
*/
export function fromUnknown(root: unknown, options?: {
readonly preserveEmptyStrings?: boolean | undefined
}): ConfigProvider {
const preserveEmptyStrings = options?.preserveEmptyStrings === true
return make((path) => Effect.succeed(nodeAtJson(root, path, preserveEmptyStrings)))
}
function nodeAtJson(root: unknown, path: Path, preserveEmptyStrings: boolean): Node | undefined {
let cur: unknown = root
for (const seg of path) {
if (cur === null || cur === undefined) return undefined
if (Array.isArray(cur)) {
if (typeof seg !== "number" || !Number.isInteger(seg) || seg < 0 || seg >= cur.length) return undefined
cur = cur[seg]
continue
}
if (Predicate.isObject(cur)) {
if (typeof seg !== "string") return undefined
if (!Object.hasOwn(cur, seg)) return undefined
cur = cur[seg]
continue
}
// cannot descend
return undefined
}
return describeUnknown(cur, preserveEmptyStrings)
}
function describeUnknown(u: unknown, preserveEmptyStrings: boolean): Node | undefined {
if (u === undefined || u === null) return undefined
if (typeof u === "string") return stringNode(u, preserveEmptyStrings)
if (typeof u === "number" || typeof u === "boolean" || typeof u === "bigint") {
return makeValue(String(u))
}
if (Array.isArray(u)) return makeArray(u.length)
if (Predicate.isObject(u)) {
return makeRecord(new Set(Object.keys(u)))
}
// unknown values
return makeValue(format(u))
}
function stringNode(value: string, preserveEmptyStrings: boolean): Node | undefined {
const normalized = emptyStringAsMissing(value, preserveEmptyStrings)
return normalized === undefined ? undefined : makeValue(normalized)
}
function emptyStringAsMissing(value: string | undefined, preserveEmptyStrings: boolean): string | undefined {
return value === "" && !preserveEmptyStrings ? undefined : value
}
/**
* Creates a `ConfigProvider` backed by environment variables.
*
* **When to use**
*
* Use to read configuration from `process.env`, which is the default when no
* provider is explicitly set, or pass a custom env record for testing or
* non-Node runtimes.
*
* **Details**
*
* Path segments are joined with `_` for direct lookup, and env var names are
* also split on `_` to build a trie for child key discovery. This means
* `DATABASE_HOST=localhost` is accessible at both path `["DATABASE_HOST"]`
* and `["DATABASE", "HOST"]`. If all immediate children of a trie node have
* purely numeric names, the node is reported as an `Array`; otherwise as a
* `Record`.
*
* The default environment merges `process.env` and `import.meta.env` (when
* available). Override by passing `{ env: { ... } }`.
*
* Literal empty strings are treated as missing values when loaded as values by
* default. Pass `{ preserveEmptyStrings: true }` to keep empty strings as
* explicit values. Child discovery still reflects the environment variable
* names present in the source.
*
* Never fails with `SourceError` — all lookups are synchronous.
*
* **Example** (Reading from a custom env record)
*
* ```ts
* import { Config, ConfigProvider, Effect } from "effect"
*
* const provider = ConfigProvider.fromEnv({
* env: {
* DATABASE_HOST: "localhost",
* DATABASE_PORT: "5432"
* }
* })
*
* const host = Config.string("HOST").parse(
* provider.pipe(ConfigProvider.nested("DATABASE"))
* )
*
* // Effect.runSync(host) // "localhost"
* ```
*
* @see {@link fromUnknown} – for JSON objects
* @see {@link constantCase} – bridge camelCase keys to SCREAMING_SNAKE_CASE
*
* @category ConfigProviders
* @since 2.0.0
*/
export function fromEnv(options?: {
readonly env?: Record<string, string> | undefined
readonly preserveEmptyStrings?: boolean | undefined
}): ConfigProvider {
const env: Record<string, string | undefined> = options?.env ?? {
...globalThis?.process?.env,
...(import.meta as any)?.env
}
const preserveEmptyStrings = options?.preserveEmptyStrings === true
const trie = buildEnvTrie(env)
return make((path) => Effect.succeed(nodeAtEnv(trie, env, path, preserveEmptyStrings)))
}
type EnvTrieNode = {
children?: Record<string, EnvTrieNode>
}
function buildEnvTrie(env: Record<string, string | undefined>): EnvTrieNode {
const trie: EnvTrieNode = {}
for (const [name, value] of Object.entries(env)) {
if (value === undefined) continue
// Split on "_" and keep empty segments (no special handling for "__")
const segments = name.split("_")
let node = trie
for (const seg of segments) {
const children = node.children ??= Object.create(null)
node = children[seg] ??= {}
}
}
return trie
}
const NUMERIC_INDEX = /^(0|[1-9][0-9]*)$/
function nodeAtEnv(
trie: EnvTrieNode,
env: Record<string, string | undefined>,
path: Path,
preserveEmptyStrings: boolean
): Node | undefined {
const key = path.map(String).join("_")
const leafValue = emptyStringAsMissing(Object.hasOwn(env, key) ? env[key] : undefined, preserveEmptyStrings)
const trieNode = trieNodeAt(trie, path)
const children = trieNode?.children ? Object.keys(trieNode.children) : []
if (children.length === 0) {
return leafValue === undefined ? undefined : makeValue(leafValue)
}
const allNumeric = children.every((k) => NUMERIC_INDEX.test(k))
if (allNumeric) {
const length = Math.max(...children.map((k) => parseInt(k, 10))) + 1
return makeArray(length, leafValue)
}
return makeRecord(new Set(children), leafValue)
}
function trieNodeAt(root: EnvTrieNode, path: Path): EnvTrieNode | undefined {
if (path.length === 0) return root
// Convert path segments to strings and navigate through the trie
let node: EnvTrieNode | undefined = root
for (const seg of path) {
node = node?.children?.[String(seg)]
if (!node) return undefined
}
return node
}
/**
* Creates a `ConfigProvider` by parsing the string contents of a `.env` file.
*
* **When to use**
*
* Use when you already have the `.env` contents as a string, such as contents
* fetched from a remote store or embedded in a test.
*
* **Details**
*
* Supports `export` prefixes, single/double/backtick quoting, inline comments,
* and escaped newlines. Variable expansion (for example, `${VAR}`) is disabled
* by default; enable with `{ expandVariables: true }`.
*
* Literal empty strings are treated as missing values when loaded as values by
* default. Pass `{ preserveEmptyStrings: true }` to keep empty strings as
* explicit values. Child discovery still reflects the keys present in the
* parsed `.env` source.
*
* Parsing is based on the `dotenv` / `dotenv-expand` algorithm.
*
* Internally delegates to {@link fromEnv} with the parsed key-value pairs.
*
* **Example** (Parsing .env contents)
*
* ```ts
* import { ConfigProvider } from "effect"
*
* const contents = `
* HOST=localhost
* PORT=3000
* # this is a comment
* `
*
* const provider = ConfigProvider.fromDotEnvContents(contents)
* ```
*
* @see {@link fromDotEnv} – loads a `.env` file from disk
* @see {@link fromEnv} – for raw environment variable access
*
* @category ConfigProviders
* @since 4.0.0
*/
export function fromDotEnvContents(lines: string, options?: {
readonly expandVariables?: boolean | undefined
readonly preserveEmptyStrings?: boolean | undefined
}): ConfigProvider {
let env = parseDotEnvContents(lines)
if (options?.expandVariables) {
env = dotEnvExpand(env)
}
return fromEnv({ env, preserveEmptyStrings: options?.preserveEmptyStrings })
}
const DOT_ENV_LINE =
/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg
function parseDotEnvContents(lines: string): Record<string, string> {
const obj: Record<string, string> = Object.create(null)
// Convert line breaks to same format
lines = lines.replace(/\r\n?/gm, "\n")
let match: RegExpExecArray | null
while ((match = DOT_ENV_LINE.exec(lines)) != null) {
const key = match[1]
// Default undefined or null to empty string
let value = match[2] || ""
// Remove whitespace
value = value.trim()
// Check if double quoted
const maybeQuote = value[0]
// Remove surrounding quotes