-
-
Notifications
You must be signed in to change notification settings - Fork 257
/
options.ts
2069 lines (1957 loc) · 68.7 KB
/
options.ts
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
import type * as FileSystem from "@effect/platform/FileSystem"
import type * as Path from "@effect/platform/Path"
import type * as Terminal from "@effect/platform/Terminal"
import * as Schema from "@effect/schema/Schema"
import * as TreeFormatter from "@effect/schema/TreeFormatter"
import * as Arr from "effect/Array"
import type * as Config from "effect/Config"
import * as Console from "effect/Console"
import * as Effect from "effect/Effect"
import * as Either from "effect/Either"
import { dual, pipe } from "effect/Function"
import * as HashMap from "effect/HashMap"
import * as Option from "effect/Option"
import * as Order from "effect/Order"
import { pipeArguments } from "effect/Pipeable"
import type * as Redacted from "effect/Redacted"
import * as Ref from "effect/Ref"
import type * as Secret from "effect/Secret"
import type * as CliConfig from "../CliConfig.js"
import type * as HelpDoc from "../HelpDoc.js"
import type * as Options from "../Options.js"
import type * as Primitive from "../Primitive.js"
import type * as Usage from "../Usage.js"
import type * as ValidationError from "../ValidationError.js"
import * as InternalAutoCorrect from "./autoCorrect.js"
import * as InternalCliConfig from "./cliConfig.js"
import * as InternalFiles from "./files.js"
import * as InternalHelpDoc from "./helpDoc.js"
import * as InternalSpan from "./helpDoc/span.js"
import * as InternalPrimitive from "./primitive.js"
import * as InternalListPrompt from "./prompt/list.js"
import * as InternalNumberPrompt from "./prompt/number.js"
import * as InternalSelectPrompt from "./prompt/select.js"
import * as InternalUsage from "./usage.js"
import * as InternalValidationError from "./validationError.js"
const OptionsSymbolKey = "@effect/cli/Options"
/** @internal */
export const OptionsTypeId: Options.OptionsTypeId = Symbol.for(
OptionsSymbolKey
) as Options.OptionsTypeId
/** @internal */
export type Op<Tag extends string, Body = {}> = Options.Options<never> & Body & {
readonly _tag: Tag
}
const proto = {
[OptionsTypeId]: {
_A: (_: never) => _
},
pipe() {
return pipeArguments(this, arguments)
}
}
/** @internal */
export type Instruction =
| Empty
| Single
| KeyValueMap
| Map
| Both
| OrElse
| WithFallbackConfig
| Variadic
| WithDefault
/** @internal */
export type ParseableInstruction = Single | KeyValueMap | Variadic
/** @internal */
export interface Empty extends Op<"Empty", {}> {}
/** @internal */
export interface Single extends
Op<"Single", {
readonly name: string
readonly fullName: string
readonly placeholder: string
readonly aliases: ReadonlyArray<string>
readonly primitiveType: Primitive.Primitive<unknown>
readonly description: HelpDoc.HelpDoc
readonly pseudoName: Option.Option<string>
}>
{}
/** @internal */
export interface KeyValueMap extends
Op<"KeyValueMap", {
readonly argumentOption: Single
}>
{}
/** @internal */
export interface Map extends
Op<"Map", {
readonly options: Options.Options<unknown>
readonly f: (a: unknown) => Effect.Effect<
unknown,
ValidationError.ValidationError,
FileSystem.FileSystem | Path.Path | Terminal.Terminal
>
}>
{}
/** @internal */
export interface Both extends
Op<"Both", {
readonly left: Options.Options<unknown>
readonly right: Options.Options<unknown>
}>
{}
/** @internal */
export interface OrElse extends
Op<"OrElse", {
readonly left: Options.Options<unknown>
readonly right: Options.Options<unknown>
}>
{}
/** @internal */
export interface WithFallbackConfig extends
Op<"WithFallbackConfig", {
readonly options: Options.Options<unknown>
readonly config: Config.Config<unknown>
}>
{}
/** @internal */
export interface Variadic extends
Op<"Variadic", {
readonly argumentOption: Single
readonly min: Option.Option<number>
readonly max: Option.Option<number>
}>
{}
/** @internal */
export interface WithDefault extends
Op<"WithDefault", {
readonly options: Options.Options<unknown>
readonly fallback: unknown
}>
{}
// =============================================================================
// Refinements
// =============================================================================
/** @internal */
export const isOptions = (u: unknown): u is Options.Options<unknown> =>
typeof u === "object" && u != null && OptionsTypeId in u
/** @internal */
export const isInstruction = <_>(self: Options.Options<_>): self is Instruction => self as any
/** @internal */
export const isEmpty = (self: Instruction): self is Empty => self._tag === "Empty"
/** @internal */
export const isSingle = (self: Instruction): self is Single => self._tag === "Single"
/** @internal */
export const isKeyValueMap = (self: Instruction): self is KeyValueMap => self._tag === "KeyValueMap"
/** @internal */
export const isMap = (self: Instruction): self is Map => self._tag === "Map"
/** @internal */
export const isBoth = (self: Instruction): self is Both => self._tag === "Both"
/** @internal */
export const isOrElse = (self: Instruction): self is OrElse => self._tag === "OrElse"
/** @internal */
export const isWithDefault = (self: Instruction): self is WithDefault => self._tag === "WithDefault"
/** @internal */
export const isWithFallbackConfig = (self: Instruction): self is WithFallbackConfig =>
self._tag === "WithFallbackConfig"
// =============================================================================
// Constructors
// =============================================================================
/** @internal */
export const all: <
const Arg extends Iterable<Options.Options<any>> | Record<string, Options.Options<any>>
>(arg: Arg) => Options.All.Return<Arg> = function() {
if (arguments.length === 1) {
if (isOptions(arguments[0])) {
return map(arguments[0], (x) => [x]) as any
} else if (Arr.isArray(arguments[0])) {
return allTupled(arguments[0] as Array<any>) as any
} else {
const entries = Object.entries(
arguments[0] as Readonly<{ [K: string]: Options.Options<any> }>
)
let result = map(entries[0][1], (value) => ({ [entries[0][0]]: value }))
if (entries.length === 1) {
return result as any
}
const rest = entries.slice(1)
for (const [key, options] of rest) {
result = map(makeBoth(result, options), ([record, value]) => ({
...record,
[key]: value
}))
}
return result as any
}
}
return allTupled(arguments[0]) as any
}
const defaultBooleanOptions = {
ifPresent: true,
negationNames: [],
aliases: []
}
/** @internal */
export const boolean = (
name: string,
options?: Options.Options.BooleanOptionsConfig
): Options.Options<boolean> => {
const { aliases, ifPresent, negationNames } = { ...defaultBooleanOptions, ...options }
const option = makeSingle(
name,
aliases,
InternalPrimitive.boolean(Option.some(ifPresent))
)
if (Arr.isNonEmptyReadonlyArray(negationNames)) {
const head = Arr.headNonEmpty(negationNames)
const tail = Arr.tailNonEmpty(negationNames)
const negationOption = makeSingle(
head,
tail,
InternalPrimitive.boolean(Option.some(!ifPresent))
)
return withDefault(
orElse(option, negationOption),
!ifPresent
)
}
return withDefault(option, !ifPresent)
}
/** @internal */
export const choice = <A extends string, C extends ReadonlyArray<A>>(
name: string,
choices: C
): Options.Options<C[number]> => {
const primitive = InternalPrimitive.choice(
Arr.map(choices, (choice) => [choice, choice])
)
return makeSingle(name, Arr.empty(), primitive)
}
/** @internal */
export const choiceWithValue = <const C extends ReadonlyArray<[string, any]>>(
name: string,
choices: C
): Options.Options<C[number][1]> => makeSingle(name, Arr.empty(), InternalPrimitive.choice(choices))
/** @internal */
export const date = (name: string): Options.Options<Date> => makeSingle(name, Arr.empty(), InternalPrimitive.date)
/** @internal */
export const directory = (
name: string,
config?: Options.Options.PathOptionsConfig
): Options.Options<string> =>
makeSingle(
name,
Arr.empty(),
InternalPrimitive.path("directory", config?.exists ?? "either")
)
/** @internal */
export const file = (
name: string,
config?: Options.Options.PathOptionsConfig
): Options.Options<string> =>
makeSingle(
name,
Arr.empty(),
InternalPrimitive.path("file", config?.exists ?? "either")
)
/** @internal */
export const fileContent = (
name: string
): Options.Options<readonly [path: string, content: Uint8Array]> =>
mapEffect(file(name, { exists: "yes" }), (path) =>
Effect.mapError(
InternalFiles.read(path),
(msg) => InternalValidationError.invalidValue(InternalHelpDoc.p(msg))
))
/** @internal */
export const fileParse = (
name: string,
format?: "json" | "yaml" | "ini" | "toml"
): Options.Options<unknown> =>
mapEffect(fileText(name), ([path, content]) =>
Effect.mapError(
InternalFiles.parse(path, content, format),
(error) => InternalValidationError.invalidValue(InternalHelpDoc.p(error))
))
/** @internal */
export const fileSchema = <I, A>(
name: string,
schema: Schema.Schema<A, I, FileSystem.FileSystem | Path.Path | Terminal.Terminal>,
format?: "json" | "yaml" | "ini" | "toml"
): Options.Options<A> => withSchema(fileParse(name, format), schema)
/** @internal */
export const fileText = (
name: string
): Options.Options<readonly [path: string, content: string]> =>
mapEffect(file(name, { exists: "yes" }), (path) =>
Effect.mapError(
InternalFiles.readString(path),
(error) => InternalValidationError.invalidValue(InternalHelpDoc.p(error))
))
/** @internal */
export const filterMap = dual<
<A, B>(
f: (a: A) => Option.Option<B>,
message: string
) => (self: Options.Options<A>) => Options.Options<B>,
<A, B>(
self: Options.Options<A>,
f: (a: A) => Option.Option<B>,
message: string
) => Options.Options<B>
>(3, (self, f, message) =>
mapEffect(self, (a) =>
Option.match(f(a), {
onNone: () => Either.left(InternalValidationError.invalidValue(InternalHelpDoc.p(message))),
onSome: Either.right
})))
/** @internal */
export const float = (name: string): Options.Options<number> => makeSingle(name, Arr.empty(), InternalPrimitive.float)
/** @internal */
export const integer = (name: string): Options.Options<number> =>
makeSingle(name, Arr.empty(), InternalPrimitive.integer)
/** @internal */
export const keyValueMap = (
option: string | Options.Options<string>
): Options.Options<HashMap.HashMap<string, string>> => {
if (typeof option === "string") {
const single = makeSingle(option, Arr.empty(), InternalPrimitive.text)
return makeKeyValueMap(single as Single)
}
if (!isSingle(option as Instruction)) {
throw new Error("InvalidArgumentException: only single options can be key/value maps")
} else {
return makeKeyValueMap(option as Single)
}
}
/** @internal */
export const none: Options.Options<void> = (() => {
const op = Object.create(proto)
op._tag = "Empty"
return op
})()
/** @internal */
export const redacted = (name: string): Options.Options<Redacted.Redacted> =>
makeSingle(name, Arr.empty(), InternalPrimitive.redacted)
/** @internal */
export const secret = (name: string): Options.Options<Secret.Secret> =>
makeSingle(name, Arr.empty(), InternalPrimitive.secret)
/** @internal */
export const text = (name: string): Options.Options<string> => makeSingle(name, Arr.empty(), InternalPrimitive.text)
// =============================================================================
// Combinators
// =============================================================================
/** @internal */
export const atLeast = dual<
{
(times: 0): <A>(self: Options.Options<A>) => Options.Options<Array<A>>
(
times: number
): <A>(self: Options.Options<A>) => Options.Options<Arr.NonEmptyArray<A>>
},
{
<A>(self: Options.Options<A>, times: 0): Options.Options<Array<A>>
<A>(
self: Options.Options<A>,
times: number
): Options.Options<Arr.NonEmptyArray<A>>
}
>(2, (self, times) => makeVariadic(self, Option.some(times), Option.none()) as any)
/** @internal */
export const atMost = dual<
(times: number) => <A>(self: Options.Options<A>) => Options.Options<Array<A>>,
<A>(self: Options.Options<A>, times: number) => Options.Options<Array<A>>
>(2, (self, times) => makeVariadic(self, Option.none(), Option.some(times)) as any)
/** @internal */
export const between = dual<
{
(min: 0, max: number): <A>(self: Options.Options<A>) => Options.Options<Array<A>>
(
min: number,
max: number
): <A>(self: Options.Options<A>) => Options.Options<Arr.NonEmptyArray<A>>
},
{
<A>(self: Options.Options<A>, min: 0, max: number): Options.Options<Array<A>>
<A>(
self: Options.Options<A>,
min: number,
max: number
): Options.Options<Arr.NonEmptyArray<A>>
}
>(3, (self, min, max) => makeVariadic(self, Option.some(min), Option.some(max)) as any)
/** @internal */
export const isBool = <A>(self: Options.Options<A>): boolean => isBoolInternal(self as Instruction)
/** @internal */
export const getHelp = <A>(self: Options.Options<A>): HelpDoc.HelpDoc => getHelpInternal(self as Instruction)
/** @internal */
export const getIdentifier = <A>(self: Options.Options<A>): Option.Option<string> =>
getIdentifierInternal(self as Instruction)
/** @internal */
export const getMinSize = <A>(self: Options.Options<A>): number => getMinSizeInternal(self as Instruction)
/** @internal */
export const getMaxSize = <A>(self: Options.Options<A>): number => getMaxSizeInternal(self as Instruction)
/** @internal */
export const getUsage = <A>(self: Options.Options<A>): Usage.Usage => getUsageInternal(self as Instruction)
/** @internal */
export const map = dual<
<A, B>(f: (a: A) => B) => (self: Options.Options<A>) => Options.Options<B>,
<A, B>(self: Options.Options<A>, f: (a: A) => B) => Options.Options<B>
>(2, (self, f) => makeMap(self, (a) => Either.right(f(a))))
/** @internal */
export const mapEffect = dual<
<A, B>(
f: (
a: A
) => Effect.Effect<B, ValidationError.ValidationError, FileSystem.FileSystem | Path.Path | Terminal.Terminal>
) => (self: Options.Options<A>) => Options.Options<B>,
<A, B>(
self: Options.Options<A>,
f: (
a: A
) => Effect.Effect<B, ValidationError.ValidationError, FileSystem.FileSystem | Path.Path | Terminal.Terminal>
) => Options.Options<B>
>(2, (self, f) => makeMap(self, f))
/** @internal */
export const mapTryCatch = dual<
<A, B>(
f: (a: A) => B,
onError: (e: unknown) => HelpDoc.HelpDoc
) => (self: Options.Options<A>) => Options.Options<B>,
<A, B>(
self: Options.Options<A>,
f: (a: A) => B,
onError: (e: unknown) => HelpDoc.HelpDoc
) => Options.Options<B>
>(3, (self, f, onError) =>
mapEffect(self, (a) => {
try {
return Either.right(f(a))
} catch (e) {
return Either.left(InternalValidationError.invalidValue(onError(e)))
}
}))
/** @internal */
export const optional = <A>(self: Options.Options<A>): Options.Options<Option.Option<A>> =>
withDefault(map(self, Option.some), Option.none())
/** @internal */
export const orElse = dual<
<B>(that: Options.Options<B>) => <A>(self: Options.Options<A>) => Options.Options<A | B>,
<A, B>(self: Options.Options<A>, that: Options.Options<B>) => Options.Options<A | B>
>(2, (self, that) => orElseEither(self, that).pipe(map(Either.merge)))
/** @internal */
export const orElseEither = dual<
<B>(
that: Options.Options<B>
) => <A>(self: Options.Options<A>) => Options.Options<Either.Either<B, A>>,
<A, B>(self: Options.Options<A>, that: Options.Options<B>) => Options.Options<Either.Either<B, A>>
>(2, (self, that) => makeOrElse(self, that))
/** @internal */
export const parse = dual<
(
args: HashMap.HashMap<string, ReadonlyArray<string>>,
config: CliConfig.CliConfig
) => <A>(
self: Options.Options<A>
) => Effect.Effect<A, ValidationError.ValidationError, FileSystem.FileSystem>,
<A>(
self: Options.Options<A>,
args: HashMap.HashMap<string, ReadonlyArray<string>>,
config: CliConfig.CliConfig
) => Effect.Effect<A, ValidationError.ValidationError, FileSystem.FileSystem>
>(3, (self, args, config) => parseInternal(self as Instruction, args, config) as any)
/** @internal */
export const processCommandLine = dual<
(
args: ReadonlyArray<string>,
config: CliConfig.CliConfig
) => <A>(
self: Options.Options<A>
) => Effect.Effect<
[Option.Option<ValidationError.ValidationError>, Array<string>, A],
ValidationError.ValidationError,
FileSystem.FileSystem | Path.Path | Terminal.Terminal
>,
<A>(
self: Options.Options<A>,
args: ReadonlyArray<string>,
config: CliConfig.CliConfig
) => Effect.Effect<
[Option.Option<ValidationError.ValidationError>, Array<string>, A],
ValidationError.ValidationError,
FileSystem.FileSystem | Path.Path | Terminal.Terminal
>
>(
3,
(self, args, config) =>
matchOptions(args, toParseableInstruction(self as Instruction), config).pipe(
Effect.flatMap(([error, commandArgs, matchedOptions]) =>
parseInternal(self as Instruction, matchedOptions, config).pipe(
Effect.catchAll((e) =>
Option.match(error, {
onNone: () => Effect.fail(e),
onSome: (err) => Effect.fail(err)
})
),
Effect.map((a) => [error, commandArgs as Array<string>, a as any])
)
)
)
)
/** @internal */
export const repeated = <A>(self: Options.Options<A>): Options.Options<Array<A>> =>
makeVariadic(self, Option.none(), Option.none())
/** @internal */
export const withAlias = dual<
(alias: string) => <A>(self: Options.Options<A>) => Options.Options<A>,
<A>(self: Options.Options<A>, alias: string) => Options.Options<A>
>(2, (self, alias) =>
modifySingle(self as Instruction, (single) => {
const aliases = Arr.append(single.aliases, alias)
return makeSingle(
single.name,
aliases,
single.primitiveType,
single.description,
single.pseudoName
) as Single
}))
/** @internal */
export const withDefault = dual<
<const B>(fallback: B) => <A>(self: Options.Options<A>) => Options.Options<A | B>,
<A, const B>(self: Options.Options<A>, fallback: B) => Options.Options<A | B>
>(2, (self, fallback) => makeWithDefault(self, fallback))
/** @internal */
export const withFallbackConfig: {
<B>(config: Config.Config<B>): <A>(self: Options.Options<A>) => Options.Options<B | A>
<A, B>(self: Options.Options<A>, config: Config.Config<B>): Options.Options<A | B>
} = dual<
<B>(config: Config.Config<B>) => <A>(self: Options.Options<A>) => Options.Options<A | B>,
<A, B>(self: Options.Options<A>, config: Config.Config<B>) => Options.Options<A | B>
>(2, (self, config) => {
if (isInstruction(self) && isWithDefault(self)) {
return makeWithDefault(
withFallbackConfig(self.options, config),
self.fallback as any
)
}
return makeWithFallbackConfig(self, config)
})
/** @internal */
export const withDescription = dual<
(description: string) => <A>(self: Options.Options<A>) => Options.Options<A>,
<A>(self: Options.Options<A>, description: string) => Options.Options<A>
>(2, (self, desc) =>
modifySingle(self as Instruction, (single) => {
const description = InternalHelpDoc.sequence(single.description, InternalHelpDoc.p(desc))
return makeSingle(
single.name,
single.aliases,
single.primitiveType,
description,
single.pseudoName
) as Single
}))
/** @internal */
export const withPseudoName = dual<
(pseudoName: string) => <A>(self: Options.Options<A>) => Options.Options<A>,
<A>(self: Options.Options<A>, pseudoName: string) => Options.Options<A>
>(2, (self, pseudoName) =>
modifySingle(self as Instruction, (single) =>
makeSingle(
single.name,
single.aliases,
single.primitiveType,
single.description,
Option.some(pseudoName)
) as Single))
/** @internal */
export const withSchema = dual<
<A, I extends A, B>(
schema: Schema.Schema<B, I, FileSystem.FileSystem | Path.Path | Terminal.Terminal>
) => (self: Options.Options<A>) => Options.Options<B>,
<A, I extends A, B>(
self: Options.Options<A>,
schema: Schema.Schema<B, I, FileSystem.FileSystem | Path.Path | Terminal.Terminal>
) => Options.Options<B>
>(2, (self, schema) => {
const decode = Schema.decode(schema)
return mapEffect(self, (_) =>
Effect.mapError(
decode(_ as any),
(error) => InternalValidationError.invalidValue(InternalHelpDoc.p(TreeFormatter.formatErrorSync(error)))
))
})
/** @internal */
export const wizard = dual<
(config: CliConfig.CliConfig) => <A>(self: Options.Options<A>) => Effect.Effect<
Array<string>,
Terminal.QuitException | ValidationError.ValidationError,
FileSystem.FileSystem | Path.Path | Terminal.Terminal
>,
<A>(self: Options.Options<A>, config: CliConfig.CliConfig) => Effect.Effect<
Array<string>,
Terminal.QuitException | ValidationError.ValidationError,
FileSystem.FileSystem | Path.Path | Terminal.Terminal
>
>(2, (self, config) => wizardInternal(self as Instruction, config))
// =============================================================================
// Internals
// =============================================================================
const allTupled = <const T extends ArrayLike<Options.Options<any>>>(arg: T): Options.Options<
{
[K in keyof T]: [T[K]] extends [Options.Options<infer A>] ? A : never
}
> => {
if (arg.length === 0) {
return none as any
}
if (arg.length === 1) {
return map(arg[0], (x) => [x]) as any
}
let result = map(arg[0], (x) => [x])
for (let i = 1; i < arg.length; i++) {
const curr = arg[i]
result = map(makeBoth(result, curr), ([a, b]) => [...a, b])
}
return result as any
}
const getHelpInternal = (self: Instruction): HelpDoc.HelpDoc => {
switch (self._tag) {
case "Empty": {
return InternalHelpDoc.empty
}
case "Single": {
return InternalHelpDoc.descriptionList(Arr.of([
InternalHelpDoc.getSpan(InternalUsage.getHelp(getUsageInternal(self))),
InternalHelpDoc.sequence(
InternalHelpDoc.p(InternalPrimitive.getHelp(self.primitiveType)),
self.description
)
]))
}
case "KeyValueMap": {
// Single options always have an identifier, so we can safely `getOrThrow`
const identifier = Option.getOrThrow(
getIdentifierInternal(self.argumentOption as Instruction)
)
return InternalHelpDoc.mapDescriptionList(
getHelpInternal(self.argumentOption as Instruction),
(span, oldBlock) => {
const header = InternalHelpDoc.p("This setting is a property argument which:")
const single = `${identifier} key1=value key2=value2`
const multiple = `${identifier} key1=value ${identifier} key2=value2`
const description = InternalHelpDoc.enumeration([
InternalHelpDoc.p(`May be specified a single time: '${single}'`),
InternalHelpDoc.p(`May be specified multiple times: '${multiple}'`)
])
const newBlock = pipe(
oldBlock,
InternalHelpDoc.sequence(header),
InternalHelpDoc.sequence(description)
)
return [span, newBlock]
}
)
}
case "Map": {
return getHelpInternal(self.options as Instruction)
}
case "Both":
case "OrElse": {
return InternalHelpDoc.sequence(
getHelpInternal(self.left as Instruction),
getHelpInternal(self.right as Instruction)
)
}
case "Variadic": {
const help = getHelpInternal(self.argumentOption as Instruction)
return InternalHelpDoc.mapDescriptionList(help, (oldSpan, oldBlock) => {
const min = getMinSizeInternal(self as Instruction)
const max = getMaxSizeInternal(self as Instruction)
const newSpan = InternalSpan.text(
Option.isSome(self.max) ? ` ${min} - ${max}` : min === 0 ? "..." : ` ${min}+`
)
const newBlock = InternalHelpDoc.p(
Option.isSome(self.max)
? `This option must be repeated at least ${min} times and may be repeated up to ${max} times.`
: min === 0
? "This option may be repeated zero or more times."
: `This option must be repeated at least ${min} times.`
)
return [InternalSpan.concat(oldSpan, newSpan), InternalHelpDoc.sequence(oldBlock, newBlock)]
})
}
case "WithDefault": {
return InternalHelpDoc.mapDescriptionList(
getHelpInternal(self.options as Instruction),
(span, block) => {
const optionalDescription = Option.isOption(self.fallback)
? Option.match(self.fallback, {
onNone: () => InternalHelpDoc.p("This setting is optional."),
onSome: () => InternalHelpDoc.p(`This setting is optional. Defaults to: ${self.fallback}`)
})
: InternalHelpDoc.p("This setting is optional.")
return [span, InternalHelpDoc.sequence(block, optionalDescription)]
}
)
}
case "WithFallbackConfig": {
return InternalHelpDoc.mapDescriptionList(
getHelpInternal(self.options as Instruction),
(span, block) => [
span,
InternalHelpDoc.sequence(
block,
InternalHelpDoc.p(
"This option can be set from environment variables."
)
)
]
)
}
}
}
const getIdentifierInternal = (self: Instruction): Option.Option<string> => {
switch (self._tag) {
case "Empty": {
return Option.none()
}
case "Single": {
return Option.some(self.fullName)
}
case "Both":
case "OrElse": {
const ids = Arr.getSomes([
getIdentifierInternal(self.left as Instruction),
getIdentifierInternal(self.right as Instruction)
])
return Arr.match(ids, {
onEmpty: () => Option.none(),
onNonEmpty: (ids) => Option.some(Arr.join(ids, ", "))
})
}
case "KeyValueMap":
case "Variadic": {
return getIdentifierInternal(self.argumentOption as Instruction)
}
case "Map":
case "WithFallbackConfig":
case "WithDefault": {
return getIdentifierInternal(self.options as Instruction)
}
}
}
const getMinSizeInternal = (self: Instruction): number => {
switch (self._tag) {
case "Empty":
case "WithDefault":
case "WithFallbackConfig": {
return 0
}
case "Single":
case "KeyValueMap": {
return 1
}
case "Map": {
return getMinSizeInternal(self.options as Instruction)
}
case "Both": {
const leftMinSize = getMinSizeInternal(self.left as Instruction)
const rightMinSize = getMinSizeInternal(self.right as Instruction)
return leftMinSize + rightMinSize
}
case "OrElse": {
const leftMinSize = getMinSizeInternal(self.left as Instruction)
const rightMinSize = getMinSizeInternal(self.right as Instruction)
return Math.min(leftMinSize, rightMinSize)
}
case "Variadic": {
const selfMinSize = Option.getOrElse(self.min, () => 0)
const argumentOptionMinSize = getMinSizeInternal(self.argumentOption as Instruction)
return selfMinSize * argumentOptionMinSize
}
}
}
const getMaxSizeInternal = (self: Instruction): number => {
switch (self._tag) {
case "Empty": {
return 0
}
case "Single": {
return 1
}
case "KeyValueMap": {
return Number.MAX_SAFE_INTEGER
}
case "Map":
case "WithDefault":
case "WithFallbackConfig": {
return getMaxSizeInternal(self.options as Instruction)
}
case "Both": {
const leftMaxSize = getMaxSizeInternal(self.left as Instruction)
const rightMaxSize = getMaxSizeInternal(self.right as Instruction)
return leftMaxSize + rightMaxSize
}
case "OrElse": {
const leftMin = getMaxSizeInternal(self.left as Instruction)
const rightMin = getMaxSizeInternal(self.right as Instruction)
return Math.min(leftMin, rightMin)
}
case "Variadic": {
const selfMaxSize = Option.getOrElse(self.max, () => Number.MAX_SAFE_INTEGER / 2)
const optionsMaxSize = getMaxSizeInternal(self.argumentOption as Instruction)
return Math.floor(selfMaxSize * optionsMaxSize)
}
}
}
const getUsageInternal = (self: Instruction): Usage.Usage => {
switch (self._tag) {
case "Empty": {
return InternalUsage.empty
}
case "Single": {
const acceptedValues = InternalPrimitive.isBool(self.primitiveType)
? Option.none()
: Option.orElse(
InternalPrimitive.getChoices(self.primitiveType),
() => Option.some(self.placeholder)
)
return InternalUsage.named(getNames(self), acceptedValues)
}
case "KeyValueMap": {
return getUsageInternal(self.argumentOption as Instruction)
}
case "Map": {
return getUsageInternal(self.options as Instruction)
}
case "Both": {
return InternalUsage.concat(
getUsageInternal(self.left as Instruction),
getUsageInternal(self.right as Instruction)
)
}
case "OrElse": {
return InternalUsage.alternation(
getUsageInternal(self.left as Instruction),
getUsageInternal(self.right as Instruction)
)
}
case "Variadic": {
return InternalUsage.repeated(getUsageInternal(self.argumentOption as Instruction))
}
case "WithDefault":
case "WithFallbackConfig": {
return InternalUsage.optional(getUsageInternal(self.options as Instruction))
}
}
}
const isBoolInternal = (self: Instruction): boolean => {
switch (self._tag) {
case "Single": {
return InternalPrimitive.isBool(self.primitiveType)
}
case "Map": {
return isBoolInternal(self.options as Instruction)
}
case "WithDefault": {
return isBoolInternal(self.options as Instruction)
}
default: {
return false
}
}
}
const makeBoth = <A, B>(
left: Options.Options<A>,
right: Options.Options<B>
): Options.Options<[A, B]> => {
const op = Object.create(proto)
op._tag = "Both"
op.left = left
op.right = right
return op
}
const makeFullName = (str: string): [boolean, string] => str.length === 1 ? [true, `-${str}`] : [false, `--${str}`]
const makeKeyValueMap = (
argumentOption: Single
): Options.Options<HashMap.HashMap<string, string>> => {
const op = Object.create(proto)
op._tag = "KeyValueMap"
op.argumentOption = argumentOption
return op
}
const makeMap = <A, B>(
options: Options.Options<A>,
f: (a: A) => Effect.Effect<B, ValidationError.ValidationError, FileSystem.FileSystem | Path.Path | Terminal.Terminal>
): Options.Options<B> => {
const op = Object.create(proto)
op._tag = "Map"
op.options = options
op.f = f
return op
}
const makeOrElse = <A, B>(
left: Options.Options<A>,
right: Options.Options<B>
): Options.Options<Either.Either<B, A>> => {
const op = Object.create(proto)
op._tag = "OrElse"
op.left = left
op.right = right
return op
}
const makeSingle = <A>(
name: string,
aliases: ReadonlyArray<string>,
primitiveType: Primitive.Primitive<A>,
description: HelpDoc.HelpDoc = InternalHelpDoc.empty,
pseudoName: Option.Option<string> = Option.none()
): Options.Options<A> => {
const op = Object.create(proto)