zod-args-parser 1.0.13 → 1.0.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (152) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +12 -1
  3. package/lib/commonjs/autocomplete-scripts/bash-autocomplete-script.js +42 -0
  4. package/lib/commonjs/autocomplete-scripts/bash-autocomplete-script.js.map +1 -0
  5. package/lib/commonjs/autocomplete-scripts/powershell-autocomplete-script.js +31 -0
  6. package/lib/commonjs/autocomplete-scripts/powershell-autocomplete-script.js.map +1 -0
  7. package/lib/commonjs/autocomplete-scripts/zsh-autocomplete-script.js +41 -0
  8. package/lib/commonjs/autocomplete-scripts/zsh-autocomplete-script.js.map +1 -0
  9. package/lib/commonjs/help-message/colors.js +1 -0
  10. package/lib/commonjs/help-message/colors.js.map +1 -0
  11. package/lib/commonjs/help-message/print-arguments.js +1 -0
  12. package/lib/commonjs/help-message/print-arguments.js.map +1 -0
  13. package/lib/commonjs/help-message/print-help-message.js +1 -0
  14. package/lib/commonjs/help-message/print-help-message.js.map +1 -0
  15. package/lib/commonjs/help-message/print-options.js +1 -0
  16. package/lib/commonjs/help-message/print-options.js.map +1 -0
  17. package/lib/commonjs/help-message/print-subcommands.js +1 -0
  18. package/lib/commonjs/help-message/print-subcommands.js.map +1 -0
  19. package/lib/commonjs/help-message/utils.js +1 -0
  20. package/lib/commonjs/help-message/utils.js.map +1 -0
  21. package/lib/commonjs/index.js +1 -1
  22. package/lib/commonjs/index.js.map +1 -1
  23. package/lib/commonjs/markdown/generate-markdown.js +1 -0
  24. package/lib/commonjs/markdown/generate-markdown.js.map +1 -0
  25. package/lib/commonjs/metadata/get-arguments-metadata.js +1 -0
  26. package/lib/commonjs/metadata/get-arguments-metadata.js.map +1 -0
  27. package/lib/commonjs/metadata/get-cli-metadata.js +1 -0
  28. package/lib/commonjs/metadata/get-cli-metadata.js.map +1 -0
  29. package/lib/commonjs/metadata/get-options-metadata.js +1 -0
  30. package/lib/commonjs/metadata/get-options-metadata.js.map +1 -0
  31. package/lib/commonjs/metadata/get-subcommands-metadata.js +1 -0
  32. package/lib/commonjs/metadata/get-subcommands-metadata.js.map +1 -0
  33. package/lib/commonjs/parser/parse.js +1 -0
  34. package/lib/commonjs/parser/parse.js.map +1 -0
  35. package/lib/commonjs/parser/safe-parse.js +1 -0
  36. package/lib/commonjs/parser/safe-parse.js.map +1 -0
  37. package/lib/commonjs/utils.js +1 -1
  38. package/lib/commonjs/utils.js.map +1 -1
  39. package/lib/module/autocomplete-scripts/bash-autocomplete-script.js +42 -0
  40. package/lib/module/autocomplete-scripts/bash-autocomplete-script.js.map +1 -0
  41. package/lib/module/autocomplete-scripts/powershell-autocomplete-script.js +31 -0
  42. package/lib/module/autocomplete-scripts/powershell-autocomplete-script.js.map +1 -0
  43. package/lib/module/autocomplete-scripts/zsh-autocomplete-script.js +41 -0
  44. package/lib/module/autocomplete-scripts/zsh-autocomplete-script.js.map +1 -0
  45. package/lib/module/help-message/colors.js +1 -0
  46. package/lib/module/help-message/colors.js.map +1 -0
  47. package/lib/module/help-message/print-arguments.js +1 -0
  48. package/lib/module/help-message/print-arguments.js.map +1 -0
  49. package/lib/module/help-message/print-help-message.js +1 -0
  50. package/lib/module/help-message/print-help-message.js.map +1 -0
  51. package/lib/module/help-message/print-options.js +1 -0
  52. package/lib/module/help-message/print-options.js.map +1 -0
  53. package/lib/module/help-message/print-subcommands.js +1 -0
  54. package/lib/module/help-message/print-subcommands.js.map +1 -0
  55. package/lib/module/help-message/utils.js +1 -0
  56. package/lib/module/help-message/utils.js.map +1 -0
  57. package/lib/module/index.js +1 -1
  58. package/lib/module/index.js.map +1 -1
  59. package/lib/module/markdown/generate-markdown.js +1 -0
  60. package/lib/module/markdown/generate-markdown.js.map +1 -0
  61. package/lib/module/metadata/get-arguments-metadata.js +1 -0
  62. package/lib/module/metadata/get-arguments-metadata.js.map +1 -0
  63. package/lib/module/metadata/get-cli-metadata.js +1 -0
  64. package/lib/module/metadata/get-cli-metadata.js.map +1 -0
  65. package/lib/module/metadata/get-options-metadata.js +1 -0
  66. package/lib/module/metadata/get-options-metadata.js.map +1 -0
  67. package/lib/module/metadata/get-subcommands-metadata.js +1 -0
  68. package/lib/module/metadata/get-subcommands-metadata.js.map +1 -0
  69. package/lib/module/parser/parse.js +1 -0
  70. package/lib/module/parser/parse.js.map +1 -0
  71. package/lib/module/parser/safe-parse.js +1 -0
  72. package/lib/module/parser/safe-parse.js.map +1 -0
  73. package/lib/module/utils.js +1 -1
  74. package/lib/module/utils.js.map +1 -1
  75. package/lib/typescript/autocomplete-scripts/bash-autocomplete-script.d.ts +11 -0
  76. package/lib/typescript/autocomplete-scripts/bash-autocomplete-script.d.ts.map +1 -0
  77. package/lib/typescript/autocomplete-scripts/powershell-autocomplete-script.d.ts +14 -0
  78. package/lib/typescript/autocomplete-scripts/powershell-autocomplete-script.d.ts.map +1 -0
  79. package/lib/typescript/autocomplete-scripts/zsh-autocomplete-script.d.ts +11 -0
  80. package/lib/typescript/autocomplete-scripts/zsh-autocomplete-script.d.ts.map +1 -0
  81. package/lib/typescript/help-message/colors.d.ts +17 -0
  82. package/lib/typescript/help-message/colors.d.ts.map +1 -0
  83. package/lib/typescript/help-message/print-arguments.d.ts +4 -0
  84. package/lib/typescript/help-message/print-arguments.d.ts.map +1 -0
  85. package/lib/typescript/help-message/print-help-message.d.ts +4 -0
  86. package/lib/typescript/help-message/print-help-message.d.ts.map +1 -0
  87. package/lib/typescript/help-message/print-options.d.ts +4 -0
  88. package/lib/typescript/help-message/print-options.d.ts.map +1 -0
  89. package/lib/typescript/help-message/print-subcommands.d.ts +4 -0
  90. package/lib/typescript/help-message/print-subcommands.d.ts.map +1 -0
  91. package/lib/typescript/help-message/utils.d.ts +13 -0
  92. package/lib/typescript/help-message/utils.d.ts.map +1 -0
  93. package/lib/typescript/index.d.ts +11 -4
  94. package/lib/typescript/index.d.ts.map +1 -1
  95. package/lib/typescript/markdown/generate-markdown.d.ts +3 -0
  96. package/lib/typescript/markdown/generate-markdown.d.ts.map +1 -0
  97. package/lib/typescript/metadata/get-arguments-metadata.d.ts +3 -0
  98. package/lib/typescript/metadata/get-arguments-metadata.d.ts.map +1 -0
  99. package/lib/typescript/metadata/get-cli-metadata.d.ts +3 -0
  100. package/lib/typescript/metadata/get-cli-metadata.d.ts.map +1 -0
  101. package/lib/typescript/metadata/get-options-metadata.d.ts +3 -0
  102. package/lib/typescript/metadata/get-options-metadata.d.ts.map +1 -0
  103. package/lib/typescript/metadata/get-subcommands-metadata.d.ts +3 -0
  104. package/lib/typescript/metadata/get-subcommands-metadata.d.ts.map +1 -0
  105. package/lib/typescript/parser/parse.d.ts +3 -0
  106. package/lib/typescript/parser/parse.d.ts.map +1 -0
  107. package/lib/typescript/parser/safe-parse.d.ts +3 -0
  108. package/lib/typescript/parser/safe-parse.d.ts.map +1 -0
  109. package/lib/typescript/types.d.ts +80 -0
  110. package/lib/typescript/types.d.ts.map +1 -1
  111. package/lib/typescript/utils.d.ts +0 -12
  112. package/lib/typescript/utils.d.ts.map +1 -1
  113. package/package.json +22 -22
  114. package/src/autocomplete-scripts/bash-autocomplete-script.ts +81 -0
  115. package/src/autocomplete-scripts/powershell-autocomplete-script.ts +78 -0
  116. package/src/autocomplete-scripts/zsh-autocomplete-script.ts +69 -0
  117. package/src/help-message/colors.ts +24 -0
  118. package/src/help-message/print-arguments.ts +35 -0
  119. package/src/help-message/print-help-message.ts +126 -0
  120. package/src/help-message/print-options.ts +40 -0
  121. package/src/help-message/print-subcommands.ts +28 -0
  122. package/src/help-message/utils.ts +31 -0
  123. package/src/index.ts +13 -10
  124. package/src/markdown/generate-markdown.ts +172 -0
  125. package/src/metadata/get-arguments-metadata.ts +23 -0
  126. package/src/metadata/get-cli-metadata.ts +23 -0
  127. package/src/metadata/get-options-metadata.ts +30 -0
  128. package/src/metadata/get-subcommands-metadata.ts +29 -0
  129. package/src/{parser.ts → parser/parse.ts} +4 -54
  130. package/src/parser/safe-parse.ts +45 -0
  131. package/src/types.ts +116 -0
  132. package/src/utils.ts +0 -32
  133. package/lib/commonjs/autocomplete.js +0 -107
  134. package/lib/commonjs/autocomplete.js.map +0 -1
  135. package/lib/commonjs/help.js +0 -1
  136. package/lib/commonjs/help.js.map +0 -1
  137. package/lib/commonjs/parser.js +0 -1
  138. package/lib/commonjs/parser.js.map +0 -1
  139. package/lib/module/autocomplete.js +0 -107
  140. package/lib/module/autocomplete.js.map +0 -1
  141. package/lib/module/help.js +0 -1
  142. package/lib/module/help.js.map +0 -1
  143. package/lib/module/parser.js +0 -1
  144. package/lib/module/parser.js.map +0 -1
  145. package/lib/typescript/autocomplete.d.ts +0 -32
  146. package/lib/typescript/autocomplete.d.ts.map +0 -1
  147. package/lib/typescript/help.d.ts +0 -9
  148. package/lib/typescript/help.d.ts.map +0 -1
  149. package/lib/typescript/parser.d.ts +0 -4
  150. package/lib/typescript/parser.d.ts.map +0 -1
  151. package/src/autocomplete.ts +0 -217
  152. package/src/help.ts +0 -341
@@ -1,107 +0,0 @@
1
- import{transformOptionToArg}from"./utils.js";export function generateBashAutocompleteScript(...params){const[cli,...subcommands]=params;const mappedCommands=subcommands.reduce((acc,subcommand)=>{acc[subcommand.name]={options:subcommand.options?.map(option=>transformOptionToArg(option.name))??[],aliases:subcommand.aliases??[]};return acc;},{});let switchCase="";for(const[key,{options,aliases}]of Object.entries(mappedCommands)){switchCase+=` ${key}${aliases.length?"|":""}${aliases.join("|")})\n`;switchCase+=` opts="${options.join(" ")}"\n`;switchCase+=" ;;\n";}if(cli.options?.length){switchCase+=` "-"*)\n`;switchCase+=` opts="${cli.options.map(option=>transformOptionToArg(option.name)).join(" ")}"\n`;switchCase+=" ;;\n";}return`_${cli.cliName}_autocomplete() {
2
- local cur prev commands opts subcommand used_opts filtered_opts
3
-
4
- cur="\${COMP_WORDS[COMP_CWORD]}"
5
- prev="\${COMP_WORDS[COMP_CWORD-1]}"
6
- subcommand="\${COMP_WORDS[1]}"
7
-
8
- commands="${Object.keys(mappedCommands).join(" ")}"
9
-
10
- case "$subcommand" in
11
- ${switchCase}
12
- esac
13
-
14
- used_opts=""
15
- if [[ " \${commands[@]} " =~ " $subcommand " ]]; then
16
- for word in "\${COMP_WORDS[@]:2}"; do
17
- if [[ "$word" =~ ^- ]]; then
18
- used_opts+=" $word"
19
- fi
20
- done
21
- fi
22
-
23
- if [[ -n "$opts" ]]; then
24
- filtered_opts=""
25
- for opt in $opts; do
26
- if [[ ! " $used_opts " =~ " $opt " ]]; then
27
- filtered_opts+="$opt "
28
- fi
29
- done
30
- COMPREPLY=( $(compgen -W "$filtered_opts" -- "$cur") )
31
- return
32
- fi
33
-
34
- if [[ "\${COMP_CWORD}" -eq 1 ]]; then
35
- COMPREPLY=( $(compgen -W "$commands" -- "$cur") )
36
- fi
37
- }
38
-
39
- complete -F _${cli.cliName}_autocomplete ${cli.cliName}
40
- `;}export function generatePowerShellAutocompleteScript(...params){const[cli,...subcommands]=params;const mappedCommands=subcommands.reduce((acc,subcommand)=>{acc[subcommand.name]={options:subcommand.options?.map(option=>transformOptionToArg(option.name))??[],aliases:subcommand.aliases??[]};return acc;},{});const subcommandsStr=Object.keys(mappedCommands).map(key=>`'${key}'`).join(", ");const cliOptionsStr=cli.options?.map(option=>`'${transformOptionToArg(option.name)}'`).join(", ")||"";let switchCase="switch ($subcommand) {\n";for(const[key,{options,aliases}]of Object.entries(mappedCommands)){const optionsStr=options.map(option=>`'${option}'`).join(", ");switchCase+=` '${key}' { @(${optionsStr}) }\n`;aliases.forEach(a=>switchCase+=` '${a}' { @(${optionsStr}) }\n`);}switchCase+=` default { @(${cliOptionsStr}) }\n }`;let functionInfo="";if(cli.description){functionInfo=`<#\n.DESCRIPTION\n${cli.description}\n${cli.example?`\n.EXAMPLE\n${cli.example}`:""}\n#>`;}return`${functionInfo}
41
- function ${cli.cliName} {
42
- param(
43
- [Parameter(Position = 0, Mandatory = $false)]
44
- [string]$subcommand,
45
- [Parameter(Position = 1, ValueFromRemainingArguments = $true)]
46
- [string[]]$arguments
47
- )
48
- $scriptPath = (Get-Command '${cli.cliName}.ps1').Source
49
- if ($scriptPath) {
50
- $argumentList = @($subcommand) + ($arguments | Where-Object { $_ -notin '--', '--%' }) | Where-Object { $_ -ne '' }
51
- & $scriptPath @argumentList
52
- return
53
- }
54
- Write-Error "Could not find '${cli.cliName}.ps1' script"
55
- }
56
-
57
- Register-ArgumentCompleter -CommandName '${cli.cliName}' -ParameterName 'subcommand' -ScriptBlock {
58
- param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameters)
59
- $subcommands = @(${subcommandsStr}${subcommandsStr&&cliOptionsStr?", ":""}${cliOptionsStr})
60
- $subcommands | Where-Object { $_ -like "$wordToComplete*" }
61
- }
62
-
63
- Register-ArgumentCompleter -CommandName '${cli.cliName}' -ParameterName 'arguments' -ScriptBlock {
64
- param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameters)
65
- $subcommand = $commandAst.CommandElements[1].Value
66
- $arguments = ${switchCase}
67
- $arguments | Where-Object { $_ -like "$wordToComplete*" }
68
- }`;}export function generateZshAutocompleteScript(...params){const[cli,...subcommands]=params;const genArguments=options=>{return options?.map(option=>`'${transformOptionToArg(option.name)}[${option.description??""}]'`).join(" \\\n ");};const genSubCommand=subcommand=>{const options=subcommand.options;if(!options||options.length===0)return"";return`${subcommand.name})
69
- _arguments \\
70
- ${genArguments(options)} \\
71
- '*: :_files' \\
72
- && ret=0
73
- ;;`;};return`
74
- _${cli.cliName}_autocomplete() {
75
- local ret=1
76
-
77
- _arguments -C \\
78
- '1: :_${cli.cliName}_commands' \\
79
- '*:: :->subcmds' \\
80
- && ret=0
81
-
82
- case $state in
83
- subcmds)
84
- case "$words[1]" in
85
- ${subcommands.map(genSubCommand).filter(Boolean).join("\n ")}
86
- *)
87
- _arguments \\
88
- '*: :_files' \\
89
- && ret=0
90
- ;;
91
- esac
92
- ;;
93
- esac
94
-
95
- return $ret
96
- }
97
-
98
- _${cli.cliName}_commands() {
99
- local -a commands=(
100
- ${subcommands.map(subcommand=>`"${subcommand.name}:${subcommand.description??""}"`).join("\n ")}
101
- )
102
-
103
- _describe -t subcommands 'subcommand' commands
104
- }
105
-
106
- compdef _${cli.cliName}_autocomplete ${cli.cliName}
107
- `;}
@@ -1 +0,0 @@
1
- {"version":3,"names":["transformOptionToArg","generateBashAutocompleteScript","params","cli","subcommands","mappedCommands","reduce","acc","subcommand","name","options","map","option","aliases","switchCase","key","Object","entries","length","join","cliName","keys","generatePowerShellAutocompleteScript","subcommandsStr","cliOptionsStr","optionsStr","forEach","a","functionInfo","description","example","generateZshAutocompleteScript","genArguments","genSubCommand","filter","Boolean"],"sourceRoot":"../../src","sources":["autocomplete.ts"],"sourcesContent":["import { transformOptionToArg } from \"./utils.js\";\n\nimport type { Cli, Option, Subcommand } from \"./types.js\";\n\n/**\n * - Generate bash autocomplete script for your CLI\n * - The generated script should be added to your `.bash_profile` or `.bashrc` file:\n *\n * - Run: `nano $HOME/.bash_profile` or `nano $HOME/.bashrc`\n * - Add the following line: `source <generated script path>`\n * - Save and reopen bash to take effect\n */\nexport function generateBashAutocompleteScript(...params: [Cli, ...Subcommand[]]): string {\n const [cli, ...subcommands] = params;\n\n type MappedCommands = Record<string, { options: string[]; aliases: string[] }>;\n\n const mappedCommands = subcommands.reduce((acc: MappedCommands, subcommand) => {\n acc[subcommand.name] = {\n options: subcommand.options?.map(option => transformOptionToArg(option.name)) ?? [],\n aliases: subcommand.aliases ?? [],\n };\n return acc;\n }, {});\n\n let switchCase = \"\";\n for (const [key, { options, aliases }] of Object.entries(mappedCommands)) {\n switchCase += ` ${key}${aliases.length ? \"|\" : \"\"}${aliases.join(\"|\")})\\n`;\n switchCase += ` opts=\"${options.join(\" \")}\"\\n`;\n switchCase += \" ;;\\n\";\n }\n\n if (cli.options?.length) {\n switchCase += ` \"-\"*)\\n`;\n switchCase += ` opts=\"${cli.options.map(option => transformOptionToArg(option.name)).join(\" \")}\"\\n`;\n switchCase += \" ;;\\n\";\n }\n\n return `_${cli.cliName}_autocomplete() {\n local cur prev commands opts subcommand used_opts filtered_opts\n\n cur=\"\\${COMP_WORDS[COMP_CWORD]}\"\n prev=\"\\${COMP_WORDS[COMP_CWORD-1]}\"\n subcommand=\"\\${COMP_WORDS[1]}\"\n\n commands=\"${Object.keys(mappedCommands).join(\" \")}\"\n\n case \"$subcommand\" in\n${switchCase}\n esac\n\n used_opts=\"\"\n if [[ \" \\${commands[@]} \" =~ \" $subcommand \" ]]; then\n for word in \"\\${COMP_WORDS[@]:2}\"; do\n if [[ \"$word\" =~ ^- ]]; then\n used_opts+=\" $word\"\n fi\n done\n fi\n\n if [[ -n \"$opts\" ]]; then\n filtered_opts=\"\"\n for opt in $opts; do\n if [[ ! \" $used_opts \" =~ \" $opt \" ]]; then\n filtered_opts+=\"$opt \"\n fi\n done\n COMPREPLY=( $(compgen -W \"$filtered_opts\" -- \"$cur\") )\n return\n fi\n\n if [[ \"\\${COMP_CWORD}\" -eq 1 ]]; then\n COMPREPLY=( $(compgen -W \"$commands\" -- \"$cur\") )\n fi\n}\n\ncomplete -F _${cli.cliName}_autocomplete ${cli.cliName}\n`;\n}\n\n/**\n * - Generates a PowerShell autocomplete script for your CLI.\n * - The script assumes that your CLI is available as a `.ps1` file in the environment variable. For example:\n * `cliName.ps1`.\n * - This should return a path to your script: `(Get-Command <cliName>.ps1).Source`\n * - The generated script should be added to your `profile.ps1` file:\n *\n * - Run: `notepad $profile`\n * - Add the following line: `. \"<generated script path>\"`\n * - Save and reopen powershell to take effect\n */\nexport function generatePowerShellAutocompleteScript(...params: [Cli, ...Subcommand[]]): string {\n const [cli, ...subcommands] = params;\n\n type MappedCommands = Record<string, { options: string[]; aliases: string[] }>;\n\n const mappedCommands = subcommands.reduce((acc: MappedCommands, subcommand) => {\n acc[subcommand.name] = {\n options: subcommand.options?.map(option => transformOptionToArg(option.name)) ?? [],\n aliases: subcommand.aliases ?? [],\n };\n return acc;\n }, {});\n\n const subcommandsStr = Object.keys(mappedCommands)\n .map(key => `'${key}'`)\n .join(\", \");\n const cliOptionsStr = cli.options?.map(option => `'${transformOptionToArg(option.name)}'`).join(\", \") || \"\";\n\n let switchCase = \"switch ($subcommand) {\\n\";\n for (const [key, { options, aliases }] of Object.entries(mappedCommands)) {\n const optionsStr = options.map(option => `'${option}'`).join(\", \");\n switchCase += ` '${key}' { @(${optionsStr}) }\\n`;\n aliases.forEach(a => (switchCase += ` '${a}' { @(${optionsStr}) }\\n`));\n }\n switchCase += ` default { @(${cliOptionsStr}) }\\n }`;\n\n let functionInfo = \"\";\n if (cli.description) {\n functionInfo = `<#\\n.DESCRIPTION\\n${cli.description}\\n${cli.example ? `\\n.EXAMPLE\\n${cli.example}` : \"\"}\\n#>`;\n }\n\n return `${functionInfo}\nfunction ${cli.cliName} {\n param(\n [Parameter(Position = 0, Mandatory = $false)]\n [string]$subcommand,\n [Parameter(Position = 1, ValueFromRemainingArguments = $true)]\n [string[]]$arguments\n )\n $scriptPath = (Get-Command '${cli.cliName}.ps1').Source\n if ($scriptPath) {\n $argumentList = @($subcommand) + ($arguments | Where-Object { $_ -notin '--', '--%' }) | Where-Object { $_ -ne '' }\n & $scriptPath @argumentList\n return\n }\n Write-Error \"Could not find '${cli.cliName}.ps1' script\"\n}\n\nRegister-ArgumentCompleter -CommandName '${cli.cliName}' -ParameterName 'subcommand' -ScriptBlock {\n param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameters)\n $subcommands = @(${subcommandsStr}${subcommandsStr && cliOptionsStr ? \", \" : \"\"}${cliOptionsStr})\n $subcommands | Where-Object { $_ -like \"$wordToComplete*\" }\n}\n\nRegister-ArgumentCompleter -CommandName '${cli.cliName}' -ParameterName 'arguments' -ScriptBlock {\n param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameters)\n $subcommand = $commandAst.CommandElements[1].Value\n $arguments = ${switchCase}\n $arguments | Where-Object { $_ -like \"$wordToComplete*\" }\n}`;\n}\n\n/**\n * - Generates a ZSH autocomplete script for your CLI.\n * - The generated script should be added to your `~/.zshrc` or `~/.zsh_profile` file:\n *\n * - Run: `nano $HOME/.zshrc` or `nano $HOME/.zsh_profile`\n * - Add the following line: `source <generated script path>`\n * - Save and reopen zsh to take effect\n */\nexport function generateZshAutocompleteScript(...params: [Cli, ...Subcommand[]]): string {\n const [cli, ...subcommands] = params;\n\n const genArguments = (options: Option[]) => {\n return options\n ?.map(option => `'${transformOptionToArg(option.name)}[${option.description ?? \"\"}]'`)\n .join(\" \\\\\\n \");\n };\n\n const genSubCommand = (subcommand: Subcommand) => {\n const options = subcommand.options;\n if (!options || options.length === 0) return \"\";\n return `${subcommand.name})\n _arguments \\\\\n ${genArguments(options)} \\\\\n '*: :_files' \\\\\n && ret=0\n ;;`;\n };\n\n return `\n_${cli.cliName}_autocomplete() {\n local ret=1\n\n _arguments -C \\\\\n '1: :_${cli.cliName}_commands' \\\\\n '*:: :->subcmds' \\\\\n && ret=0\n\n case $state in\n subcmds)\n case \"$words[1]\" in\n ${subcommands.map(genSubCommand).filter(Boolean).join(\"\\n \")}\n *)\n _arguments \\\\\n '*: :_files' \\\\\n && ret=0\n ;;\n esac\n ;;\n esac\n\n return $ret\n}\n \n_${cli.cliName}_commands() {\n local -a commands=(\n ${subcommands.map(subcommand => `\"${subcommand.name}:${subcommand.description ?? \"\"}\"`).join(\"\\n \")}\n )\n\n _describe -t subcommands 'subcommand' commands\n}\n\ncompdef _${cli.cliName}_autocomplete ${cli.cliName}\n`;\n}\n"],"mappings":"AAAA,OAASA,oBAAoB,KAAQ,YAAY,CAYjD,MAAO,SAAS,CAAAC,8BAA8BA,CAAC,GAAGC,MAA8B,CAAU,CACxF,KAAM,CAACC,GAAG,CAAE,GAAGC,WAAW,CAAC,CAAGF,MAAM,CAIpC,KAAM,CAAAG,cAAc,CAAGD,WAAW,CAACE,MAAM,CAAC,CAACC,GAAmB,CAAEC,UAAU,GAAK,CAC7ED,GAAG,CAACC,UAAU,CAACC,IAA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CAED,KAAM,CAAAc,aAAa,CAAIzB,UAAsB,EAAK,CAChD,KAAM,CAAAE,OAAO,CAAGF,UAAU,CAACE,OAAO,CAClC,GAAI,CAACA,OAAO,EAAIA,OAAO,CAACQ,MAAM,GAAK,CAAC,CAAE,MAAO,EAAE,CAC/C,MAAO,GAAGV,UAAU,CAACC,IAAI;AAC7B;AACA,cAAcuB,YAAY,CAACtB,OAAO,CAAC;AACnC;AACA;AACA,aAAa,CACX,CAAC,CAED,MAAO;AACT,GAAGP,GAAG,CAACiB,OAAO;AACd;AACA;AACA;AACA,YAAYjB,GAAG,CAACiB,OAAO;AACvB;AACA;AACA;AACA;AACA;AACA;AACA,UAAUhB,WAAW,CAACO,GAAG,CAACsB,aAAa,CAAC,CAACC,MAAM,CAACC,OAAO,CAAC,CAAChB,IAAI,CAAC,YAAY,CAAC;AAC3E;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAAGhB,GAAG,CAACiB,OAAO;AACd;AACA,MAAMhB,WAAW,CAACO,GAAG,CAACH,UAAU,EAAI,IAAIA,UAAU,CAACC,IAAI,IAAID,UAAU,CAACqB,WAAW,EAAI,EAAE,GAAG,CAAC,CAACV,IAAI,CAAC,QAAQ,CAAC;AAC1G;AACA;AACA;AACA;AACA;AACA,WAAWhB,GAAG,CAACiB,OAAO,iBAAiBjB,GAAG,CAACiB,OAAO;AAClD,CAAC,CACD","ignoreList":[]}
@@ -1 +0,0 @@
1
- import chalk from"chalk";import{concat,getDefaultValueFromSchema,indent,ln,print,println,transformOptionToArg}from"./utils.js";const colors={title:chalk.bold.blue,description:chalk.white,default:chalk.dim.italic,optional:chalk.dim.italic,exampleTitle:chalk.yellow,example:chalk.dim,command:chalk.yellow,option:chalk.cyan,argument:chalk.green,placeholder:chalk.hex("#FF9800"),punctuation:chalk.white.dim};function printCliHelp(params,printOptions={}){printOptions.colors??=true;const noColors=new Proxy(colors,{get:()=>{return(...str)=>str.join(" ");}});const c=printOptions.colors?colors:noColors;if(printOptions.customColors){Object.assign(c,printOptions.customColors);}const isFirstParamCli="cliName"in params[0];const cliOptions=isFirstParamCli?params.shift():{};const subcommands=params;const printTitle=title=>{print(c.title(` ${title.toUpperCase()} `));};const cliName=cliOptions.cliName??"";const usage=cliOptions.usage??concat(c.punctuation("$"),cliName,subcommands.length?c.command("[command]"):"",cliOptions.options?.length?c.option("[options]"):"",cliOptions.arguments?.length||cliOptions.allowPositional?c.argument("<arguments>"):"");printTitle("Usage");println();println(indent(2),usage,ln(1));if(cliOptions.description){printTitle("Description");println();println(indent(2),c.description(cliOptions.description),ln(1));}let longest=0;const[optionsToPrint,longestOptionIndent]=prepareOptionsToPrint(cliOptions.options);if(longestOptionIndent>longest)longest=longestOptionIndent;const[commandsToPrint,longestSubcommandIndent]=prepareCommandsToPrint(subcommands);if(longestSubcommandIndent>longest)longest=longestSubcommandIndent;const[argsToPrint,longestArgIndent]=prepareArgumentsToPrint(cliOptions.arguments);if(longestArgIndent>longest)longest=longestArgIndent;printPreparedOptions(optionsToPrint,c,longest);printPreparedCommands(commandsToPrint,c,longest);printPreparedArguments(argsToPrint,c,longest);if(cliOptions.example){printTitle("Example");println();const normalizeExample=cliOptions.example.replace(/\n/g,"\n"+indent(3));println(indent(2),c.example(normalizeExample),ln(1));}}function printSubcommandHelp(subcommand,printOptions={},cliName=""){printOptions.colors??=true;const noColors=new Proxy(colors,{get:()=>{return(...str)=>str.join(" ");}});const c=printOptions.colors?colors:noColors;if(printOptions.customColors){Object.assign(c,printOptions.customColors);}const printTitle=title=>{print(c.title(` ${title.toUpperCase()} `));};const usage=subcommand.usage??concat(c.punctuation("$"),cliName,c.command(subcommand.name),subcommand.options?.length?c.option("[options]"):"",subcommand.arguments?.length||subcommand.allowPositional?c.argument("<arguments>"):"");printTitle("Usage");println();println(indent(2),usage,ln(1));if(subcommand.description){printTitle("Description");println();const normalizeDesc=subcommand.description.replace(/\n/g,"\n"+indent(3));println(indent(2),c.description(normalizeDesc),ln(1));}let longest=0;const[optionsToPrint,longestOptionIndent]=prepareOptionsToPrint(subcommand.options);if(longestOptionIndent>longest)longest=longestOptionIndent;const[argsToPrint,longestArgIndent]=prepareArgumentsToPrint(subcommand.arguments);if(longestArgIndent>longest)longest=longestArgIndent;printPreparedOptions(optionsToPrint,c,longest);printPreparedArguments(argsToPrint,c,longest);if(subcommand.example){printTitle("Example");println();const normalizeExample=subcommand.example.replace(/\n/g,"\n"+indent(3));println(indent(2),c.example(normalizeExample),ln(1));}}function prepareOptionsToPrint(options){if(!options||!options.length)return[[],0];const optionsToPrint=[];let longest=0;for(const option of options){const nameWithAliases=option.aliases?[...option.aliases,option.name]:[option.name];const names=Array.from(new Set(nameWithAliases.map(name=>transformOptionToArg(name)))).join(", ");const defaultValue=getDefaultValueFromSchema(option.type);const placeholder=option.placeholder??" ";optionsToPrint.push({names,placeholder,description:option.description??option.type.description??"",default:typeof defaultValue!=="undefined"?`(default: ${JSON.stringify(defaultValue)})`:"",optional:option.type.isOptional()?"[optional]":"",example:option.example??""});const optLength=names.length+placeholder.length;if(optLength>longest)longest=optLength;}return[optionsToPrint,longest];}function prepareCommandsToPrint(subcommands){if(!subcommands||!subcommands.length)return[[],0];const commandsToPrint=[];let longest=0;for(const subcommand of subcommands){const{name,aliases,description}=subcommand;const names=Array.from(new Set([...(aliases??[]),name])).join(", ");const placeholder=subcommand.placeholder??(subcommand.options?"[options]":subcommand.allowPositional?"<args>":" ");commandsToPrint.push({names,placeholder,description:description??""});const cmdLength=names.length+placeholder.length;if(cmdLength>longest)longest=cmdLength;}return[commandsToPrint,longest];}function prepareArgumentsToPrint(args){if(!args||!args.length)return[[],0];const argsToPrint=[];let longest=0;for(const arg of args){const defaultValue=getDefaultValueFromSchema(arg.type);argsToPrint.push({names:arg.name,description:arg.description??"",default:typeof defaultValue!=="undefined"?`(default: ${JSON.stringify(defaultValue)})`:"",optional:arg.type.isOptional()?"[optional]":"",example:arg.example??""});const cmdLength=arg.name.length;if(cmdLength>longest)longest=cmdLength;}return[argsToPrint,longest];}function printPreparedOptions(optionsToPrint,c,longest){if(!optionsToPrint.length)return;print(c.title(" OPTIONS "));println();for(const{names,placeholder,description,example,optional,default:def}of optionsToPrint){const optLength=names.length+(placeholder?.length??0);const spacing=longest+1-optLength;const normalizeDesc=description.replace(/\n/g,"\n"+indent(longest+7)+c.punctuation("└"));const coloredNames=names.split(/(,)/).map(name=>name===","?c.punctuation(name):c.option(name)).join("");println(indent(2),coloredNames,c.placeholder(placeholder),indent(spacing),c.description(normalizeDesc),def?c.default(def):c.optional(optional));if(example){const normalizeExample=example.replace(/\n/g,"\n"+indent(longest+17));println(indent(longest+6),c.punctuation("└")+c.exampleTitle("Example:"),c.example(normalizeExample));}}println();}function printPreparedCommands(commandsToPrint,c,longest){if(!commandsToPrint.length)return;print(c.title(" COMMANDS "));println();for(const{names,placeholder,description}of commandsToPrint){const optLength=names.length+(placeholder?.length??0);const spacing=longest+1-optLength;const normalizeDesc=description.replace(/\n/g,"\n"+indent(longest+7)+c.punctuation("└"));const coloredNames=names.split(/(,)/).map(name=>name===","?c.punctuation(name):c.command(name)).join("");println(indent(2),coloredNames,c.placeholder(placeholder),indent(spacing),c.description(normalizeDesc));}println();}function printPreparedArguments(argsToPrint,c,longest){if(!argsToPrint.length)return;print(c.title(" ARGUMENTS "));println();for(const{names,description,example,optional,default:def}of argsToPrint){const spacing=longest+2-names.length;const normalizeDesc=description.replace(/\n/g,"\n"+indent(longest+6)+c.punctuation("└"));println(indent(2),c.argument(names),indent(spacing),c.description(normalizeDesc),def?c.default(def):c.optional(optional));if(example){const normalizeExample=example.replace(/\n/g,"\n"+indent(longest+16));println(indent(longest+5),c.punctuation("└")+c.exampleTitle("Example:"),c.example(normalizeExample));}}println();}export const help={printCliHelp,printSubcommandHelp};
@@ -1 +0,0 @@
1
- {"version":3,"names":["chalk","concat","getDefaultValueFromSchema","indent","ln","print","println","transformOptionToArg","colors","title","bold","blue","description","white","default","dim","italic","optional","exampleTitle","yellow","example","command","option","cyan","argument","green","placeholder","hex","punctuation","printCliHelp","params","printOptions","noColors","Proxy","get","str","join","c","customColors","Object","assign","isFirstParamCli","cliOptions","shift","subcommands","printTitle","toUpperCase","cliName","usage","length","options","arguments","allowPositional","longest","optionsToPrint","longestOptionIndent","prepareOptionsToPrint","commandsToPrint","longestSubcommandIndent","prepareCommandsToPrint","argsToPrint","longestArgIndent","prepareArgumentsToPrint","printPreparedOptions","printPreparedCommands","printPreparedArguments","normalizeExample","replace","printSubcommandHelp","subcommand","name","normalizeDesc","nameWithAliases","aliases","names","Array","from","Set","map","defaultValue","type","push","JSON","stringify","isOptional","optLength","cmdLength","args","arg","def","spacing","coloredNames","split","help"],"sourceRoot":"../../src","sources":["help.ts"],"sourcesContent":["import chalk from \"chalk\";\nimport { concat, getDefaultValueFromSchema, indent, ln, print, println, transformOptionToArg } from \"./utils.js\";\n\nimport type { Argument, Cli, Option, PrintHelpOpt, Subcommand } from \"./types.js\";\n\nconst colors: NonNullable<Required<PrintHelpOpt[\"customColors\"]>> = {\n title: chalk.bold.blue,\n description: chalk.white,\n default: chalk.dim.italic,\n optional: chalk.dim.italic,\n exampleTitle: chalk.yellow,\n example: chalk.dim,\n command: chalk.yellow,\n option: chalk.cyan,\n argument: chalk.green,\n placeholder: chalk.hex(\"#FF9800\"),\n punctuation: chalk.white.dim,\n};\n\ntype PreparedToPrint = {\n names: string;\n description: string;\n placeholder?: string;\n example?: string;\n default?: string;\n optional?: string;\n};\n\nfunction printCliHelp(params: [Cli, ...Subcommand[]], printOptions: PrintHelpOpt = {}) {\n printOptions.colors ??= true;\n\n const noColors = new Proxy(colors, {\n get: () => {\n return (...str: string[]) => str.join(\" \");\n },\n });\n\n const c = printOptions.colors ? colors : noColors;\n\n if (printOptions.customColors) {\n Object.assign(c, printOptions.customColors);\n }\n\n const isFirstParamCli = \"cliName\" in params[0];\n const cliOptions = (isFirstParamCli ? params.shift() : {}) as Cli;\n const subcommands = params as Subcommand[];\n\n /** Print a styled title */\n const printTitle = (title: string) => {\n print(c.title(` ${title.toUpperCase()} `));\n };\n\n // Print CLI usage\n const cliName = cliOptions.cliName ?? \"\";\n const usage =\n cliOptions.usage ??\n concat(\n c.punctuation(\"$\"),\n cliName,\n subcommands.length ? c.command(\"[command]\") : \"\",\n cliOptions.options?.length ? c.option(\"[options]\") : \"\",\n cliOptions.arguments?.length || cliOptions.allowPositional ? c.argument(\"<arguments>\") : \"\",\n );\n printTitle(\"Usage\");\n println();\n println(indent(2), usage, ln(1));\n\n // Print CLI description\n if (cliOptions.description) {\n printTitle(\"Description\");\n println();\n println(indent(2), c.description(cliOptions.description), ln(1));\n }\n\n let longest = 0;\n\n // Prepare CLI options\n const [optionsToPrint, longestOptionIndent] = prepareOptionsToPrint(cliOptions.options);\n if (longestOptionIndent > longest) longest = longestOptionIndent;\n\n // Prepare CLI commands\n const [commandsToPrint, longestSubcommandIndent] = prepareCommandsToPrint(subcommands);\n if (longestSubcommandIndent > longest) longest = longestSubcommandIndent;\n\n // Prepare CLI arguments\n const [argsToPrint, longestArgIndent] = prepareArgumentsToPrint(cliOptions.arguments);\n if (longestArgIndent > longest) longest = longestArgIndent;\n\n // Print CLI options\n printPreparedOptions(optionsToPrint, c, longest);\n\n // Print CLI commands\n printPreparedCommands(commandsToPrint, c, longest);\n\n // Print CLI arguments\n printPreparedArguments(argsToPrint, c, longest);\n\n // Print CLI example\n if (cliOptions.example) {\n printTitle(\"Example\");\n println();\n const normalizeExample = cliOptions.example.replace(/\\n/g, \"\\n\" + indent(3));\n println(indent(2), c.example(normalizeExample), ln(1));\n }\n}\n\nfunction printSubcommandHelp(subcommand: Subcommand, printOptions: PrintHelpOpt = {}, cliName = \"\") {\n printOptions.colors ??= true;\n\n const noColors = new Proxy(colors, {\n get: () => {\n return (...str: string[]) => str.join(\" \");\n },\n });\n\n const c = printOptions.colors ? colors : noColors;\n\n if (printOptions.customColors) {\n Object.assign(c, printOptions.customColors);\n }\n\n /** Print a styled title */\n const printTitle = (title: string) => {\n print(c.title(` ${title.toUpperCase()} `));\n };\n\n // Print command usage\n const usage =\n subcommand.usage ??\n concat(\n c.punctuation(\"$\"),\n cliName,\n c.command(subcommand.name),\n subcommand.options?.length ? c.option(\"[options]\") : \"\",\n subcommand.arguments?.length || subcommand.allowPositional ? c.argument(\"<arguments>\") : \"\",\n );\n printTitle(\"Usage\");\n println();\n println(indent(2), usage, ln(1));\n\n // Print command description\n if (subcommand.description) {\n printTitle(\"Description\");\n println();\n const normalizeDesc = subcommand.description.replace(/\\n/g, \"\\n\" + indent(3));\n println(indent(2), c.description(normalizeDesc), ln(1));\n }\n\n let longest = 0;\n\n // Prepare command options\n const [optionsToPrint, longestOptionIndent] = prepareOptionsToPrint(subcommand.options);\n if (longestOptionIndent > longest) longest = longestOptionIndent;\n\n // Prepare command arguments\n const [argsToPrint, longestArgIndent] = prepareArgumentsToPrint(subcommand.arguments);\n if (longestArgIndent > longest) longest = longestArgIndent;\n\n // Print command options\n printPreparedOptions(optionsToPrint, c, longest);\n\n // Print command arguments\n printPreparedArguments(argsToPrint, c, longest);\n\n // Print command example\n if (subcommand.example) {\n printTitle(\"Example\");\n println();\n const normalizeExample = subcommand.example.replace(/\\n/g, \"\\n\" + indent(3));\n println(indent(2), c.example(normalizeExample), ln(1));\n }\n}\n\n// * Prepare\nfunction prepareOptionsToPrint(options: Option[] | undefined): [PreparedToPrint[], number] {\n if (!options || !options.length) return [[], 0];\n\n const optionsToPrint: PreparedToPrint[] = [];\n let longest = 0;\n\n for (const option of options) {\n const nameWithAliases = option.aliases ? [...option.aliases, option.name] : [option.name];\n const names = Array.from(new Set(nameWithAliases.map(name => transformOptionToArg(name)))).join(\", \");\n\n const defaultValue = getDefaultValueFromSchema(option.type);\n\n const placeholder = option.placeholder ?? \" \";\n optionsToPrint.push({\n names,\n placeholder,\n description: option.description ?? option.type.description ?? \"\",\n default: typeof defaultValue !== \"undefined\" ? `(default: ${JSON.stringify(defaultValue)})` : \"\",\n optional: option.type.isOptional() ? \"[optional]\" : \"\",\n example: option.example ?? \"\",\n });\n\n const optLength = names.length + placeholder.length;\n\n if (optLength > longest) longest = optLength;\n }\n\n return [optionsToPrint, longest];\n}\n\nfunction prepareCommandsToPrint(subcommands: Subcommand[] | undefined): [PreparedToPrint[], number] {\n if (!subcommands || !subcommands.length) return [[], 0];\n\n const commandsToPrint: PreparedToPrint[] = [];\n let longest = 0;\n\n for (const subcommand of subcommands) {\n const { name, aliases, description } = subcommand;\n const names = Array.from(new Set([...(aliases ?? []), name])).join(\", \");\n\n const placeholder =\n subcommand.placeholder ?? (subcommand.options ? \"[options]\" : subcommand.allowPositional ? \"<args>\" : \" \");\n\n commandsToPrint.push({ names, placeholder, description: description ?? \"\" });\n\n const cmdLength = names.length + placeholder.length;\n if (cmdLength > longest) longest = cmdLength;\n }\n\n return [commandsToPrint, longest];\n}\n\nfunction prepareArgumentsToPrint(args: Argument[] | undefined): [PreparedToPrint[], number] {\n if (!args || !args.length) return [[], 0];\n\n const argsToPrint: PreparedToPrint[] = [];\n let longest = 0;\n\n for (const arg of args) {\n const defaultValue = getDefaultValueFromSchema(arg.type);\n\n argsToPrint.push({\n names: arg.name,\n description: arg.description ?? \"\",\n default: typeof defaultValue !== \"undefined\" ? `(default: ${JSON.stringify(defaultValue)})` : \"\",\n optional: arg.type.isOptional() ? \"[optional]\" : \"\",\n example: arg.example ?? \"\",\n });\n\n const cmdLength = arg.name.length;\n if (cmdLength > longest) longest = cmdLength;\n }\n\n return [argsToPrint, longest];\n}\n\n// * Print\nfunction printPreparedOptions(optionsToPrint: PreparedToPrint[], c: typeof colors, longest: number) {\n if (!optionsToPrint.length) return;\n\n print(c.title(\" OPTIONS \"));\n\n println();\n\n for (const { names, placeholder, description, example, optional, default: def } of optionsToPrint) {\n const optLength = names.length + (placeholder?.length ?? 0);\n const spacing = longest + 1 - optLength;\n const normalizeDesc = description.replace(/\\n/g, \"\\n\" + indent(longest + 7) + c.punctuation(\"└\"));\n\n const coloredNames = names\n .split(/(,)/)\n .map(name => (name === \",\" ? c.punctuation(name) : c.option(name)))\n .join(\"\");\n\n println(\n indent(2),\n coloredNames,\n c.placeholder(placeholder),\n indent(spacing),\n c.description(normalizeDesc),\n def ? c.default(def) : c.optional(optional),\n );\n\n if (example) {\n const normalizeExample = example.replace(/\\n/g, \"\\n\" + indent(longest + 17));\n println(indent(longest + 6), c.punctuation(\"└\") + c.exampleTitle(\"Example:\"), c.example(normalizeExample));\n }\n }\n\n println();\n}\n\nfunction printPreparedCommands(commandsToPrint: PreparedToPrint[], c: typeof colors, longest: number) {\n if (!commandsToPrint.length) return;\n\n print(c.title(\" COMMANDS \"));\n\n println();\n\n for (const { names, placeholder, description } of commandsToPrint) {\n const optLength = names.length + (placeholder?.length ?? 0);\n const spacing = longest + 1 - optLength;\n const normalizeDesc = description.replace(/\\n/g, \"\\n\" + indent(longest + 7) + c.punctuation(\"└\"));\n\n const coloredNames = names\n .split(/(,)/)\n .map(name => (name === \",\" ? c.punctuation(name) : c.command(name)))\n .join(\"\");\n\n println(indent(2), coloredNames, c.placeholder(placeholder), indent(spacing), c.description(normalizeDesc));\n }\n\n println();\n}\n\nfunction printPreparedArguments(argsToPrint: PreparedToPrint[], c: typeof colors, longest: number) {\n if (!argsToPrint.length) return;\n\n print(c.title(\" ARGUMENTS \"));\n\n println();\n\n for (const { names, description, example, optional, default: def } of argsToPrint) {\n const spacing = longest + 2 - names.length;\n const normalizeDesc = description.replace(/\\n/g, \"\\n\" + indent(longest + 6) + c.punctuation(\"└\"));\n\n println(\n indent(2),\n c.argument(names),\n indent(spacing),\n c.description(normalizeDesc),\n def ? c.default(def) : c.optional(optional),\n );\n\n if (example) {\n const normalizeExample = example.replace(/\\n/g, \"\\n\" + indent(longest + 16));\n println(indent(longest + 5), c.punctuation(\"└\") + c.exampleTitle(\"Example:\"), c.example(normalizeExample));\n }\n }\n\n println();\n}\n\nexport const help = {\n printCliHelp,\n printSubcommandHelp,\n};\n"],"mappings":"AAAA,MAAO,CAAAA,KA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YAAY,CACZuC,mBACF,CAAC","ignoreList":[]}
@@ -1 +0,0 @@
1
- import{help}from"./help.js";import{decoupleFlags,getOrdinalPlacement,isBooleanSchema,isFlagArg,isOptionArg,noName,stringToBoolean,transformArg,transformOptionToArg}from"./utils.js";export function parse(argsv,...params){const cliOptions="cliName"in params[0]?params[0]:{};const subcommandArr=params;const allSubcommands=new Set(subcommandArr.flatMap(c=>[c.name,...(c.aliases||[])]));argsv=decoupleFlags(argsv);const results={subcommand:undefined,printCliHelp(opt){help.printCliHelp(params,opt);},printSubcommandHelp(subcommandStr,opt){const subcommand=subcommandArr.find(c=>{if(c.name===subcommandStr)return true;if(!subcommandStr)return false;if(!c.aliases?.length)return false;return c.aliases.includes(subcommandStr);});if(!subcommand)return console.error(`Cannot print help for subcommand "${subcommandStr}" as it does not exist`);help.printSubcommandHelp(subcommand,opt,cliOptions.cliName);}};const GetSubcommandProps=(cmd=results.subcommand)=>{return subcommandArr.find(c=>{if(c.name===cmd)return true;if(!cmd)return false;if(!c.aliases?.length)return false;return c.aliases.includes(cmd);});};const addRawArg=(optionName,rawArg)=>{if(!results._info)results._info={};if(!results._info[optionName])results._info[optionName]=Object.create({});results._info[optionName].rawArg=rawArg;};const addRawValue=(optionName,rawValue)=>{if(!results._info)results._info={};if(!results._info[optionName])results._info[optionName]=Object.create({});results._info[optionName].rawValue=rawValue;};const addSource=(optionName,source)=>{if(!results._info)results._info={};if(!results._info[optionName])results._info[optionName]=Object.create({});results._info[optionName].source=source;};const fillOption=(optionName,value)=>{if(!results._info)results._info={};if(!results._info[optionName])results._info[optionName]=Object.create({});Object.assign(results._info[optionName],value);};for(let i=0;i<argsv.length;i++){const arg=argsv[i];if(i===0){results.subcommand=allSubcommands.has(arg)?arg:undefined;const subcommandProps=GetSubcommandProps();if(subcommandProps?.allowPositional)results.positional=[];if(subcommandProps?.arguments?.length)results.arguments=[];if(results.subcommand)continue;}const argAndValue=arg.split("=").filter(Boolean);const argWithEquals=arg.includes("=");const argument=argAndValue[0];const argValue=argAndValue[1];if(isOptionArg(argument)){if(isFlagArg(argument)&&argWithEquals){throw new Error(`Flag arguments cannot be assigned using "=": "${arg}"`);}const subcommandProps=GetSubcommandProps();if(!subcommandProps)throw new Error(`Unknown subcommand: "${results.subcommand}"`);if(!subcommandProps.options){const msg=!results.subcommand?"options are not allowed here":`subcommand "${results.subcommand}" does not allow options`;throw new Error(`Error: ${msg}: "${argument}"`);}const optionName=transformArg(argument);const isNegative=argument.startsWith("--no-");const option=subcommandProps.options.find(o=>{if(o.name===optionName)return true;if(isNegative&&noName(o.name)===optionName)return true;if(!o.aliases)return false;if(o.aliases.includes(optionName))return true;if(isNegative&&o.aliases.map(noName).includes(optionName))return true;return false;});if(!option){throw new Error(`Unknown option: "${argument}"`);}if(option.name in results){throw new Error(`Duplicated option: "${argument}"`);}const isTypeBoolean=isBooleanSchema(option.type);const nextArg=argsv[i+1];let optionValue=argWithEquals?argValue:nextArg;if(isTypeBoolean){if(argWithEquals){const parsedBoolean=stringToBoolean(argValue);optionValue=isNegative?!parsedBoolean:parsedBoolean;}else{optionValue=!isNegative;}}if(typeof optionValue==="undefined"){throw new Error(`Expected a value for "${argument}" but got nothing`);}if(!argWithEquals&&isOptionArg(optionValue)){throw new Error(`Expected a value for "${argument}" but got an argument "${nextArg}"`);}const res=option.type.safeParse(optionValue);if(!res.success){throw new Error(`Invalid value "${optionValue}" for "${argument}": ${res.error.errors[0].message}`);}results[option.name]=res.data;addRawArg(option.name,argument);const rawVal=argWithEquals?argValue:isTypeBoolean?"":nextArg;addRawValue(option.name,rawVal);fillOption(option.name,option);if(!argWithEquals&&!isTypeBoolean)i++;continue;}const subcommandProps=GetSubcommandProps();if(subcommandProps?.arguments?.length){if(!results.arguments)results.arguments=[];const currentArgCount=results.arguments.length;if(currentArgCount<subcommandProps.arguments.length){const argType=subcommandProps.arguments[currentArgCount].type;let argValue=arg;const isTypeBoolean=isBooleanSchema(argType);if(isTypeBoolean)argValue=stringToBoolean(argValue);const res=argType.safeParse(argValue);if(!res.success){throw new Error(`The ${getOrdinalPlacement(currentArgCount)} argument "${arg}" is invalid: ${res.error.errors[0].message}`);}results.arguments.push(res.data);continue;}}if(subcommandProps?.allowPositional){if(!results.positional)results.positional=[];results.positional.push(arg);continue;}const msg=!results.subcommand?"here":`for subcommand "${results.subcommand}"`;throw new Error(`Unexpected argument "${arg}": positional arguments are not allowed ${msg}`);}const subcommandProps=GetSubcommandProps();if(subcommandProps?.options?.length){for(const option of subcommandProps.options){if(option.name in results){addSource(option.name,"cli");fillOption(option.name,option);continue;}if(option.type.isOptional()){const hasDefault=typeof option.type._def.defaultValue==="function";if(!hasDefault)continue;results[option.name]=option.type._def.defaultValue();addSource(option.name,"default");fillOption(option.name,option);continue;}throw new Error(`Missing required option: ${transformOptionToArg(option.name)}`);}}if(subcommandProps?.arguments?.length){const currentArgCount=results.arguments?.length??0;const subcommandArgCount=subcommandProps.arguments.length;if(currentArgCount<subcommandArgCount){for(let i=currentArgCount;i<subcommandArgCount;i++){const argumentType=subcommandProps.arguments[i].type;const hasDefault=typeof argumentType._def.defaultValue==="function";if(hasDefault&&results.arguments){results.arguments.push(argumentType._def.defaultValue());continue;}if(argumentType.isOptional())continue;throw new Error(`the ${getOrdinalPlacement(i)} argument is required: "${subcommandProps.arguments[i].name}"`);}}}if(subcommandProps?.action){subcommandProps.action(results);}return results;}export function safeParse(argsv,...params){const cliOptions="cliName"in params[0]?params[0]:{};const subcommandArr=params;const printCliHelp=opt=>help.printCliHelp(params,opt);const printSubcommandHelp=(subcommandStr,opt)=>{const subcommand=subcommandArr.find(c=>c.name===subcommandStr);if(!subcommand)return console.error(`Cannot print help for subcommand "${subcommandStr}" as it does not exist`);help.printSubcommandHelp(subcommand,opt,cliOptions.cliName);};try{const data=parse(argsv,...params);delete data.printCliHelp;delete data.printSubcommandHelp;return{success:true,data:data,printCliHelp,printSubcommandHelp};}catch(e){return{success:false,error:e,printCliHelp,printSubcommandHelp};}}
@@ -1 +0,0 @@
1
- {"version":3,"names":["help","decoupleFlags","getOrdinalPlacement","isBooleanSchema","isFlagArg","isOptionArg","noName","stringToBoolean","transformArg","transformOptionToArg","parse","argsv","params","cliOptions","subcommandArr","allSubcommands","Set","flatMap","c","name","aliases","results","subcommand","undefined","printCliHelp","opt","printSubcommandHelp","subcommandStr","find","length","includes","console","error","cliName","GetSubcommandProps","cmd","addRawArg","optionName","rawArg","_info","Object","create","addRawValue","rawValue","addSource","source","fillOption","value","assign","i","arg","has","subcommandProps","allowPositional","positional","arguments","argAndValue","split","filter","Boolean","argWithEquals","argument","argValue","Error","options","msg","isNegative","startsWith","option","o","map","isTypeBoolean","type","nextArg","optionValue","parsedBoolean","res","safeParse","success","errors","message","data","rawVal","currentArgCount","argType","push","isOptional","hasDefault","_def","defaultValue","subcommandArgCount","argumentType","action","e"],"sourceRoot":"../../src","sources":["parser.ts"],"sourcesContent":["import { help } from \"./help.js\";\nimport {\n decoupleFlags,\n getOrdinalPlacement,\n isBooleanSchema,\n isFlagArg,\n isOptionArg,\n noName,\n stringToBoolean,\n transformArg,\n transformOptionToArg,\n} from \"./utils.js\";\n\nimport type {\n Cli,\n NoSubcommand,\n Option,\n PrintHelpOpt,\n PrintMethods,\n SafeParseResult,\n Subcommand,\n UnSafeParseResult,\n} from \"./types.js\";\n\nexport function parse<T extends Subcommand[], U extends Cli>(\n argsv: string[],\n ...params: [U, ...T]\n): UnSafeParseResult<[...T, NoSubcommand & U]> {\n const cliOptions = (\"cliName\" in params[0] ? params[0] : {}) as U;\n const subcommandArr = params as unknown as T;\n const allSubcommands = new Set<string>(subcommandArr.flatMap(c => [c.name, ...(c.aliases || [])]));\n\n // decouple flags E.g. `-rf` -> `-r, -f`\n argsv = decoupleFlags(argsv);\n\n type ResultObj = Record<string, unknown> & {\n subcommand: string | undefined;\n positional?: string[];\n arguments?: unknown[];\n _info?: Record<string, { rawArg?: string; rawValue?: string; source: \"cli\" | \"default\" }>;\n printCliHelp: (options?: PrintHelpOpt) => void;\n printSubcommandHelp: (subcommand: any, options?: PrintHelpOpt) => void;\n };\n\n const results: ResultObj = {\n subcommand: undefined,\n printCliHelp(opt) {\n help.printCliHelp(params, opt);\n },\n printSubcommandHelp(subcommandStr, opt) {\n const subcommand = subcommandArr.find(c => {\n if (c.name === subcommandStr) return true;\n if (!subcommandStr) return false;\n if (!c.aliases?.length) return false;\n return c.aliases.includes(subcommandStr);\n });\n if (!subcommand) return console.error(`Cannot print help for subcommand \"${subcommandStr}\" as it does not exist`);\n help.printSubcommandHelp(subcommand, opt, cliOptions.cliName);\n },\n };\n\n /** - Get current subcommand props */\n const GetSubcommandProps = (cmd = results.subcommand) => {\n return subcommandArr.find(c => {\n if (c.name === cmd) return true;\n if (!cmd) return false;\n if (!c.aliases?.length) return false;\n return c.aliases.includes(cmd);\n });\n };\n\n const addRawArg = (optionName: string, rawArg: string) => {\n if (!results._info) results._info = {};\n if (!results._info[optionName]) results._info[optionName] = Object.create({});\n results._info[optionName].rawArg = rawArg;\n };\n\n const addRawValue = (optionName: string, rawValue: string) => {\n if (!results._info) results._info = {};\n if (!results._info[optionName]) results._info[optionName] = Object.create({});\n results._info[optionName].rawValue = rawValue;\n };\n\n const addSource = (optionName: string, source: \"cli\" | \"default\") => {\n if (!results._info) results._info = {};\n if (!results._info[optionName]) results._info[optionName] = Object.create({});\n results._info[optionName].source = source;\n };\n\n const fillOption = (optionName: string, value: Option) => {\n if (!results._info) results._info = {};\n if (!results._info[optionName]) results._info[optionName] = Object.create({});\n Object.assign(results._info[optionName], value);\n };\n\n for (let i = 0; i < argsv.length; i++) {\n const arg = argsv[i];\n\n // * subcommand\n if (i === 0) {\n results.subcommand = allSubcommands.has(arg) ? arg : undefined;\n\n // add positional and arguments array\n const subcommandProps = GetSubcommandProps();\n if (subcommandProps?.allowPositional) results.positional = [];\n if (subcommandProps?.arguments?.length) results.arguments = [];\n\n if (results.subcommand) continue;\n }\n\n // * option\n const argAndValue = arg.split(\"=\").filter(Boolean);\n const argWithEquals = arg.includes(\"=\");\n const argument = argAndValue[0];\n const argValue: string | undefined = argAndValue[1];\n\n if (isOptionArg(argument)) {\n if (isFlagArg(argument) && argWithEquals) {\n throw new Error(`Flag arguments cannot be assigned using \"=\": \"${arg}\"`);\n }\n\n const subcommandProps = GetSubcommandProps();\n if (!subcommandProps) throw new Error(`Unknown subcommand: \"${results.subcommand}\"`);\n\n if (!subcommandProps.options) {\n const msg = !results.subcommand\n ? \"options are not allowed here\"\n : `subcommand \"${results.subcommand}\" does not allow options`;\n throw new Error(`Error: ${msg}: \"${argument}\"`);\n }\n\n const optionName = transformArg(argument);\n const isNegative = argument.startsWith(\"--no-\");\n\n const option = subcommandProps.options.find(o => {\n if (o.name === optionName) return true;\n if (isNegative && noName(o.name) === optionName) return true;\n\n if (!o.aliases) return false;\n if (o.aliases.includes(optionName)) return true;\n if (isNegative && o.aliases.map(noName).includes(optionName)) return true;\n\n return false;\n });\n\n if (!option) {\n throw new Error(`Unknown option: \"${argument}\"`);\n }\n\n if (option.name in results) {\n throw new Error(`Duplicated option: \"${argument}\"`);\n }\n\n const isTypeBoolean = isBooleanSchema(option.type);\n const nextArg = argsv[i + 1];\n\n let optionValue: string | boolean = argWithEquals ? argValue : nextArg;\n\n if (isTypeBoolean) {\n if (argWithEquals) {\n const parsedBoolean = stringToBoolean(argValue);\n optionValue = isNegative ? !parsedBoolean : parsedBoolean;\n } else {\n optionValue = !isNegative;\n }\n }\n\n if (typeof optionValue === \"undefined\") {\n throw new Error(`Expected a value for \"${argument}\" but got nothing`);\n }\n\n if (!argWithEquals && isOptionArg(optionValue)) {\n throw new Error(`Expected a value for \"${argument}\" but got an argument \"${nextArg}\"`);\n }\n\n const res = option.type.safeParse(optionValue);\n if (!res.success) {\n throw new Error(`Invalid value \"${optionValue}\" for \"${argument}\": ${res.error.errors[0].message}`);\n }\n\n results[option.name] = res.data;\n addRawArg(option.name, argument);\n const rawVal = argWithEquals ? argValue : isTypeBoolean ? \"\" : nextArg;\n addRawValue(option.name, rawVal);\n fillOption(option.name, option);\n\n if (!argWithEquals && !isTypeBoolean) i++;\n continue;\n }\n\n const subcommandProps = GetSubcommandProps();\n\n // * arguments\n if (subcommandProps?.arguments?.length) {\n if (!results.arguments) results.arguments = [];\n\n const currentArgCount = results.arguments.length;\n\n if (currentArgCount < subcommandProps.arguments.length) {\n const argType = subcommandProps.arguments[currentArgCount].type;\n\n let argValue: string | boolean = arg;\n const isTypeBoolean = isBooleanSchema(argType);\n if (isTypeBoolean) argValue = stringToBoolean(argValue);\n\n const res = argType.safeParse(argValue);\n if (!res.success) {\n throw new Error(\n `The ${getOrdinalPlacement(currentArgCount)} argument \"${arg}\" is invalid: ${res.error.errors[0].message}`,\n );\n }\n\n results.arguments.push(res.data);\n continue;\n }\n }\n\n // * positional\n if (subcommandProps?.allowPositional) {\n if (!results.positional) results.positional = [];\n results.positional.push(arg);\n continue;\n }\n\n const msg = !results.subcommand ? \"here\" : `for subcommand \"${results.subcommand}\"`;\n throw new Error(`Unexpected argument \"${arg}\": positional arguments are not allowed ${msg}`);\n }\n\n // check for missing options - set defaults - add _source\n const subcommandProps = GetSubcommandProps();\n if (subcommandProps?.options?.length) {\n for (const option of subcommandProps.options) {\n if (option.name in results) {\n addSource(option.name, \"cli\");\n fillOption(option.name, option);\n continue;\n }\n\n if (option.type.isOptional()) {\n const hasDefault = typeof option.type._def.defaultValue === \"function\";\n if (!hasDefault) continue;\n results[option.name] = option.type._def.defaultValue();\n addSource(option.name, \"default\");\n fillOption(option.name, option);\n continue;\n }\n\n throw new Error(`Missing required option: ${transformOptionToArg(option.name)}`);\n }\n }\n\n // check for arguments - set defaults\n if (subcommandProps?.arguments?.length) {\n const currentArgCount = results.arguments?.length ?? 0;\n const subcommandArgCount = subcommandProps.arguments.length;\n\n // missing arguments\n if (currentArgCount < subcommandArgCount) {\n for (let i = currentArgCount; i < subcommandArgCount; i++) {\n const argumentType = subcommandProps.arguments[i].type;\n const hasDefault = typeof argumentType._def.defaultValue === \"function\";\n if (hasDefault && results.arguments) {\n results.arguments.push(argumentType._def.defaultValue());\n continue;\n }\n\n if (argumentType.isOptional()) continue;\n\n throw new Error(`the ${getOrdinalPlacement(i)} argument is required: \"${subcommandProps.arguments[i].name}\"`);\n }\n }\n }\n\n if (subcommandProps?.action) {\n subcommandProps.action(results);\n }\n\n return results as UnSafeParseResult<[...T, NoSubcommand & U]>;\n}\n\nexport function safeParse<T extends Subcommand[], U extends Cli>(\n argsv: string[],\n ...params: [U, ...T]\n): SafeParseResult<[...T, NoSubcommand & U]> {\n const cliOptions = (\"cliName\" in params[0] ? params[0] : {}) as U;\n const subcommandArr = params as Subcommand[];\n\n type PrintTypes = PrintMethods<T[number][\"name\"]>;\n type PrintCli = PrintTypes[\"printCliHelp\"];\n type PrintSubcommand = PrintTypes[\"printSubcommandHelp\"];\n\n const printCliHelp: PrintCli = opt => help.printCliHelp(params, opt);\n const printSubcommandHelp: PrintSubcommand = (subcommandStr, opt) => {\n const subcommand = subcommandArr.find(c => c.name === subcommandStr);\n if (!subcommand) return console.error(`Cannot print help for subcommand \"${subcommandStr}\" as it does not exist`);\n help.printSubcommandHelp(subcommand, opt, cliOptions.cliName);\n };\n\n try {\n const data = parse(argsv, ...params);\n // @ts-expect-error The operand of a 'delete' operator must be optional.\n delete data.printCliHelp;\n // @ts-expect-errorThe operand of a 'delete' operator must be optional.\n delete data.printSubcommandHelp;\n\n return {\n success: true,\n data: data as Omit<typeof data, \"printCliHelp\" | \"printSubcommandHelp\">,\n printCliHelp,\n printSubcommandHelp,\n } as SafeParseResult<[...T, NoSubcommand & U]>;\n } catch (e) {\n return {\n success: false,\n error: e as Error,\n printCliHelp,\n printSubcommandHelp,\n } as SafeParseResult<[...T, NoSubcommand & U]>;\n }\n}\n"],"mappings":"AAAA,OAASA,IAAI,KAAQ,WAAW,CAChC,OACEC,aAAa,CACbC,mBAAmB,CACnBC,eAAe,CACfC,SAAS,CACTC,WAAW,CACXC,MAAM,CACNC,eAAe,CACfC,YAAY,CACZC,o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,GAAGC,MAAM,CAAC,CAEpC,MAAO,CAAAqE,IAAI,CAACzD,YAAY,CAExB,MAAO,CAAAyD,IAAI,CAACvD,mBAAmB,CAE/B,MAAO,CACLoD,OAAO,CAAE,IAAI,CACbG,IAAI,CAAEA,IAAiE,CACvEzD,YAAY,CACZE,mBACF,CAAC,CACH,CAAE,MAAOmE,CAAC,CAAE,CACV,MAAO,CACLf,OAAO,CAAE,KAAK,CACd9C,KAAK,CAAE6D,CAAU,CACjBrE,YAAY,CACZE,mBACF,CAAC,CACH,CACF","ignoreList":[]}
@@ -1,32 +0,0 @@
1
- import type { Cli, Subcommand } from "./types.js";
2
- /**
3
- * - Generate bash autocomplete script for your CLI
4
- * - The generated script should be added to your `.bash_profile` or `.bashrc` file:
5
- *
6
- * - Run: `nano $HOME/.bash_profile` or `nano $HOME/.bashrc`
7
- * - Add the following line: `source <generated script path>`
8
- * - Save and reopen bash to take effect
9
- */
10
- export declare function generateBashAutocompleteScript(...params: [Cli, ...Subcommand[]]): string;
11
- /**
12
- * - Generates a PowerShell autocomplete script for your CLI.
13
- * - The script assumes that your CLI is available as a `.ps1` file in the environment variable. For example:
14
- * `cliName.ps1`.
15
- * - This should return a path to your script: `(Get-Command <cliName>.ps1).Source`
16
- * - The generated script should be added to your `profile.ps1` file:
17
- *
18
- * - Run: `notepad $profile`
19
- * - Add the following line: `. "<generated script path>"`
20
- * - Save and reopen powershell to take effect
21
- */
22
- export declare function generatePowerShellAutocompleteScript(...params: [Cli, ...Subcommand[]]): string;
23
- /**
24
- * - Generates a ZSH autocomplete script for your CLI.
25
- * - The generated script should be added to your `~/.zshrc` or `~/.zsh_profile` file:
26
- *
27
- * - Run: `nano $HOME/.zshrc` or `nano $HOME/.zsh_profile`
28
- * - Add the following line: `source <generated script path>`
29
- * - Save and reopen zsh to take effect
30
- */
31
- export declare function generateZshAutocompleteScript(...params: [Cli, ...Subcommand[]]): string;
32
- //# sourceMappingURL=autocomplete.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"autocomplete.d.ts","sourceRoot":"","sources":["../../src/autocomplete.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,GAAG,EAAU,UAAU,EAAE,MAAM,YAAY,CAAC;AAE1D;;;;;;;GAOG;AACH,wBAAgB,8BAA8B,CAAC,GAAG,MAAM,EAAE,CAAC,GAAG,EAAE,GAAG,UAAU,EAAE,CAAC,GAAG,MAAM,CAkExF;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,oCAAoC,CAAC,GAAG,MAAM,EAAE,CAAC,GAAG,EAAE,GAAG,UAAU,EAAE,CAAC,GAAG,MAAM,CA4D9F;AAED;;;;;;;GAOG;AACH,wBAAgB,6BAA6B,CAAC,GAAG,MAAM,EAAE,CAAC,GAAG,EAAE,GAAG,UAAU,EAAE,CAAC,GAAG,MAAM,CAuDvF"}
@@ -1,9 +0,0 @@
1
- import type { Cli, PrintHelpOpt, Subcommand } from "./types.js";
2
- declare function printCliHelp(params: [Cli, ...Subcommand[]], printOptions?: PrintHelpOpt): void;
3
- declare function printSubcommandHelp(subcommand: Subcommand, printOptions?: PrintHelpOpt, cliName?: string): void;
4
- export declare const help: {
5
- printCliHelp: typeof printCliHelp;
6
- printSubcommandHelp: typeof printSubcommandHelp;
7
- };
8
- export {};
9
- //# sourceMappingURL=help.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"help.d.ts","sourceRoot":"","sources":["../../src/help.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAY,GAAG,EAAU,YAAY,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAyBlF,iBAAS,YAAY,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,GAAG,UAAU,EAAE,CAAC,EAAE,YAAY,GAAE,YAAiB,QA4EpF;AAED,iBAAS,mBAAmB,CAAC,UAAU,EAAE,UAAU,EAAE,YAAY,GAAE,YAAiB,EAAE,OAAO,SAAK,QAiEjG;AAsKD,eAAO,MAAM,IAAI;;;CAGhB,CAAC"}
@@ -1,4 +0,0 @@
1
- import type { Cli, NoSubcommand, SafeParseResult, Subcommand, UnSafeParseResult } from "./types.js";
2
- export declare function parse<T extends Subcommand[], U extends Cli>(argsv: string[], ...params: [U, ...T]): UnSafeParseResult<[...T, NoSubcommand & U]>;
3
- export declare function safeParse<T extends Subcommand[], U extends Cli>(argsv: string[], ...params: [U, ...T]): SafeParseResult<[...T, NoSubcommand & U]>;
4
- //# sourceMappingURL=parser.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"parser.d.ts","sourceRoot":"","sources":["../../src/parser.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,EACV,GAAG,EACH,YAAY,EAIZ,eAAe,EACf,UAAU,EACV,iBAAiB,EAClB,MAAM,YAAY,CAAC;AAEpB,wBAAgB,KAAK,CAAC,CAAC,SAAS,UAAU,EAAE,EAAE,CAAC,SAAS,GAAG,EACzD,KAAK,EAAE,MAAM,EAAE,EACf,GAAG,MAAM,EAAE,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,GACnB,iBAAiB,CAAC,CAAC,GAAG,CAAC,EAAE,YAAY,GAAG,CAAC,CAAC,CAAC,CA2P7C;AAED,wBAAgB,SAAS,CAAC,CAAC,SAAS,UAAU,EAAE,EAAE,CAAC,SAAS,GAAG,EAC7D,KAAK,EAAE,MAAM,EAAE,EACf,GAAG,MAAM,EAAE,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,GACnB,eAAe,CAAC,CAAC,GAAG,CAAC,EAAE,YAAY,GAAG,CAAC,CAAC,CAAC,CAoC3C"}
@@ -1,217 +0,0 @@
1
- import { transformOptionToArg } from "./utils.js";
2
-
3
- import type { Cli, Option, Subcommand } from "./types.js";
4
-
5
- /**
6
- * - Generate bash autocomplete script for your CLI
7
- * - The generated script should be added to your `.bash_profile` or `.bashrc` file:
8
- *
9
- * - Run: `nano $HOME/.bash_profile` or `nano $HOME/.bashrc`
10
- * - Add the following line: `source <generated script path>`
11
- * - Save and reopen bash to take effect
12
- */
13
- export function generateBashAutocompleteScript(...params: [Cli, ...Subcommand[]]): string {
14
- const [cli, ...subcommands] = params;
15
-
16
- type MappedCommands = Record<string, { options: string[]; aliases: string[] }>;
17
-
18
- const mappedCommands = subcommands.reduce((acc: MappedCommands, subcommand) => {
19
- acc[subcommand.name] = {
20
- options: subcommand.options?.map(option => transformOptionToArg(option.name)) ?? [],
21
- aliases: subcommand.aliases ?? [],
22
- };
23
- return acc;
24
- }, {});
25
-
26
- let switchCase = "";
27
- for (const [key, { options, aliases }] of Object.entries(mappedCommands)) {
28
- switchCase += ` ${key}${aliases.length ? "|" : ""}${aliases.join("|")})\n`;
29
- switchCase += ` opts="${options.join(" ")}"\n`;
30
- switchCase += " ;;\n";
31
- }
32
-
33
- if (cli.options?.length) {
34
- switchCase += ` "-"*)\n`;
35
- switchCase += ` opts="${cli.options.map(option => transformOptionToArg(option.name)).join(" ")}"\n`;
36
- switchCase += " ;;\n";
37
- }
38
-
39
- return `_${cli.cliName}_autocomplete() {
40
- local cur prev commands opts subcommand used_opts filtered_opts
41
-
42
- cur="\${COMP_WORDS[COMP_CWORD]}"
43
- prev="\${COMP_WORDS[COMP_CWORD-1]}"
44
- subcommand="\${COMP_WORDS[1]}"
45
-
46
- commands="${Object.keys(mappedCommands).join(" ")}"
47
-
48
- case "$subcommand" in
49
- ${switchCase}
50
- esac
51
-
52
- used_opts=""
53
- if [[ " \${commands[@]} " =~ " $subcommand " ]]; then
54
- for word in "\${COMP_WORDS[@]:2}"; do
55
- if [[ "$word" =~ ^- ]]; then
56
- used_opts+=" $word"
57
- fi
58
- done
59
- fi
60
-
61
- if [[ -n "$opts" ]]; then
62
- filtered_opts=""
63
- for opt in $opts; do
64
- if [[ ! " $used_opts " =~ " $opt " ]]; then
65
- filtered_opts+="$opt "
66
- fi
67
- done
68
- COMPREPLY=( $(compgen -W "$filtered_opts" -- "$cur") )
69
- return
70
- fi
71
-
72
- if [[ "\${COMP_CWORD}" -eq 1 ]]; then
73
- COMPREPLY=( $(compgen -W "$commands" -- "$cur") )
74
- fi
75
- }
76
-
77
- complete -F _${cli.cliName}_autocomplete ${cli.cliName}
78
- `;
79
- }
80
-
81
- /**
82
- * - Generates a PowerShell autocomplete script for your CLI.
83
- * - The script assumes that your CLI is available as a `.ps1` file in the environment variable. For example:
84
- * `cliName.ps1`.
85
- * - This should return a path to your script: `(Get-Command <cliName>.ps1).Source`
86
- * - The generated script should be added to your `profile.ps1` file:
87
- *
88
- * - Run: `notepad $profile`
89
- * - Add the following line: `. "<generated script path>"`
90
- * - Save and reopen powershell to take effect
91
- */
92
- export function generatePowerShellAutocompleteScript(...params: [Cli, ...Subcommand[]]): string {
93
- const [cli, ...subcommands] = params;
94
-
95
- type MappedCommands = Record<string, { options: string[]; aliases: string[] }>;
96
-
97
- const mappedCommands = subcommands.reduce((acc: MappedCommands, subcommand) => {
98
- acc[subcommand.name] = {
99
- options: subcommand.options?.map(option => transformOptionToArg(option.name)) ?? [],
100
- aliases: subcommand.aliases ?? [],
101
- };
102
- return acc;
103
- }, {});
104
-
105
- const subcommandsStr = Object.keys(mappedCommands)
106
- .map(key => `'${key}'`)
107
- .join(", ");
108
- const cliOptionsStr = cli.options?.map(option => `'${transformOptionToArg(option.name)}'`).join(", ") || "";
109
-
110
- let switchCase = "switch ($subcommand) {\n";
111
- for (const [key, { options, aliases }] of Object.entries(mappedCommands)) {
112
- const optionsStr = options.map(option => `'${option}'`).join(", ");
113
- switchCase += ` '${key}' { @(${optionsStr}) }\n`;
114
- aliases.forEach(a => (switchCase += ` '${a}' { @(${optionsStr}) }\n`));
115
- }
116
- switchCase += ` default { @(${cliOptionsStr}) }\n }`;
117
-
118
- let functionInfo = "";
119
- if (cli.description) {
120
- functionInfo = `<#\n.DESCRIPTION\n${cli.description}\n${cli.example ? `\n.EXAMPLE\n${cli.example}` : ""}\n#>`;
121
- }
122
-
123
- return `${functionInfo}
124
- function ${cli.cliName} {
125
- param(
126
- [Parameter(Position = 0, Mandatory = $false)]
127
- [string]$subcommand,
128
- [Parameter(Position = 1, ValueFromRemainingArguments = $true)]
129
- [string[]]$arguments
130
- )
131
- $scriptPath = (Get-Command '${cli.cliName}.ps1').Source
132
- if ($scriptPath) {
133
- $argumentList = @($subcommand) + ($arguments | Where-Object { $_ -notin '--', '--%' }) | Where-Object { $_ -ne '' }
134
- & $scriptPath @argumentList
135
- return
136
- }
137
- Write-Error "Could not find '${cli.cliName}.ps1' script"
138
- }
139
-
140
- Register-ArgumentCompleter -CommandName '${cli.cliName}' -ParameterName 'subcommand' -ScriptBlock {
141
- param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameters)
142
- $subcommands = @(${subcommandsStr}${subcommandsStr && cliOptionsStr ? ", " : ""}${cliOptionsStr})
143
- $subcommands | Where-Object { $_ -like "$wordToComplete*" }
144
- }
145
-
146
- Register-ArgumentCompleter -CommandName '${cli.cliName}' -ParameterName 'arguments' -ScriptBlock {
147
- param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameters)
148
- $subcommand = $commandAst.CommandElements[1].Value
149
- $arguments = ${switchCase}
150
- $arguments | Where-Object { $_ -like "$wordToComplete*" }
151
- }`;
152
- }
153
-
154
- /**
155
- * - Generates a ZSH autocomplete script for your CLI.
156
- * - The generated script should be added to your `~/.zshrc` or `~/.zsh_profile` file:
157
- *
158
- * - Run: `nano $HOME/.zshrc` or `nano $HOME/.zsh_profile`
159
- * - Add the following line: `source <generated script path>`
160
- * - Save and reopen zsh to take effect
161
- */
162
- export function generateZshAutocompleteScript(...params: [Cli, ...Subcommand[]]): string {
163
- const [cli, ...subcommands] = params;
164
-
165
- const genArguments = (options: Option[]) => {
166
- return options
167
- ?.map(option => `'${transformOptionToArg(option.name)}[${option.description ?? ""}]'`)
168
- .join(" \\\n ");
169
- };
170
-
171
- const genSubCommand = (subcommand: Subcommand) => {
172
- const options = subcommand.options;
173
- if (!options || options.length === 0) return "";
174
- return `${subcommand.name})
175
- _arguments \\
176
- ${genArguments(options)} \\
177
- '*: :_files' \\
178
- && ret=0
179
- ;;`;
180
- };
181
-
182
- return `
183
- _${cli.cliName}_autocomplete() {
184
- local ret=1
185
-
186
- _arguments -C \\
187
- '1: :_${cli.cliName}_commands' \\
188
- '*:: :->subcmds' \\
189
- && ret=0
190
-
191
- case $state in
192
- subcmds)
193
- case "$words[1]" in
194
- ${subcommands.map(genSubCommand).filter(Boolean).join("\n ")}
195
- *)
196
- _arguments \\
197
- '*: :_files' \\
198
- && ret=0
199
- ;;
200
- esac
201
- ;;
202
- esac
203
-
204
- return $ret
205
- }
206
-
207
- _${cli.cliName}_commands() {
208
- local -a commands=(
209
- ${subcommands.map(subcommand => `"${subcommand.name}:${subcommand.description ?? ""}"`).join("\n ")}
210
- )
211
-
212
- _describe -t subcommands 'subcommand' commands
213
- }
214
-
215
- compdef _${cli.cliName}_autocomplete ${cli.cliName}
216
- `;
217
- }