| 1 | import { makeArray } from "./utils"; |
| 2 | |
| 3 | export type SuggestionType = Fig.SuggestionType | "history" | "auto-execute"; |
| 4 | |
| 5 | type Override<T, S> = Omit<T, keyof S> & S; |
| 6 | export type Suggestion = Override<Fig.Suggestion, { type?: SuggestionType }>; |
| 7 | |
| 8 | export type Option<ArgT, OptionT> = OptionT & { |
| 9 | name: string[]; |
| 10 | args: ArgT[]; |
| 11 | }; |
| 12 | |
| 13 | export type Subcommand<ArgT, OptionT, SubcommandT> = SubcommandT & { |
| 14 | name: string[]; |
| 15 | subcommands: Record<string, Subcommand<ArgT, OptionT, SubcommandT>>; |
| 16 | options: Record<string, Option<ArgT, OptionT>>; |
| 17 | persistentOptions: Record<string, Option<ArgT, OptionT>>; |
| 18 | args: ArgT[]; |
| 19 | }; |
| 20 | |
| 21 | const makeNamedMap = <T extends { name: string[] }>(items: T[] | undefined): Record<string, T> => { |
| 22 | const nameMapping: Record<string, T> = {}; |
| 23 | if (!items) { |
| 24 | return nameMapping; |
| 25 | } |
| 26 | |
| 27 | for (let i = 0; i < items.length; i += 1) { |
| 28 | items[i].name.forEach((name) => { |
| 29 | nameMapping[name] = items[i]; |
| 30 | }); |
| 31 | } |
| 32 | return nameMapping; |
| 33 | }; |
| 34 | |
| 35 | export type Initializer<ArgT, OptionT, SubcommandT> = { |
| 36 | subcommand: (subcommand: Fig.Subcommand) => SubcommandT; |
| 37 | option: (option: Fig.Option) => OptionT; |
| 38 | arg: (arg: Fig.Arg) => ArgT; |
| 39 | }; |
| 40 | |
| 41 | function convertOption<ArgT, OptionT>( |
| 42 | option: Fig.Option, |
| 43 | initialize: Omit<Initializer<ArgT, OptionT, never>, "subcommand"> |
| 44 | ): Option<ArgT, OptionT> { |
| 45 | return { |
| 46 | ...initialize.option(option), |
| 47 | name: makeArray(option.name), |
| 48 | args: option.args ? makeArray(option.args).map(initialize.arg) : [], |
| 49 | }; |
| 50 | } |
| 51 | |
| 52 | export function convertSubcommand<ArgT, OptionT, SubcommandT>( |
| 53 | subcommand: Fig.Subcommand, |
| 54 | initialize: Initializer<ArgT, OptionT, SubcommandT> |
| 55 | ): Subcommand<ArgT, OptionT, SubcommandT> { |
| 56 | const { subcommands, options, args } = subcommand; |
| 57 | return { |
| 58 | ...initialize.subcommand(subcommand), |
| 59 | name: makeArray(subcommand.name), |
| 60 | subcommands: makeNamedMap(subcommands?.map((s) => convertSubcommand(s, initialize))), |
| 61 | options: makeNamedMap( |
| 62 | options |
| 63 | ?.filter((option) => !option.isPersistent) |
| 64 | ?.map((option) => convertOption(option, initialize)) |
| 65 | ), |
| 66 | persistentOptions: makeNamedMap( |
| 67 | options |
| 68 | ?.filter((option) => option.isPersistent) |
| 69 | ?.map((option) => convertOption(option, initialize)) |
| 70 | ), |
| 71 | args: args ? makeArray(args).map(initialize.arg) : [], |
| 72 | }; |
| 73 | } |