zod-args-parser 1.0.0
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.
- package/README.md +215 -0
- package/lib/commonjs/help.js +1 -0
- package/lib/commonjs/help.js.map +1 -0
- package/lib/commonjs/index.js +1 -0
- package/lib/commonjs/index.js.map +1 -0
- package/lib/commonjs/parser.js +1 -0
- package/lib/commonjs/parser.js.map +1 -0
- package/lib/commonjs/types.js +1 -0
- package/lib/commonjs/types.js.map +1 -0
- package/lib/commonjs/utils.js +1 -0
- package/lib/commonjs/utils.js.map +1 -0
- package/lib/module/help.js +1 -0
- package/lib/module/help.js.map +1 -0
- package/lib/module/index.js +1 -0
- package/lib/module/index.js.map +1 -0
- package/lib/module/parser.js +1 -0
- package/lib/module/parser.js.map +1 -0
- package/lib/module/types.js +1 -0
- package/lib/module/types.js.map +1 -0
- package/lib/module/utils.js +1 -0
- package/lib/module/utils.js.map +1 -0
- package/lib/typescript/help.d.ts +9 -0
- package/lib/typescript/help.d.ts.map +1 -0
- package/lib/typescript/index.d.ts +8 -0
- package/lib/typescript/index.d.ts.map +1 -0
- package/lib/typescript/parser.d.ts +6 -0
- package/lib/typescript/parser.d.ts.map +1 -0
- package/lib/typescript/types.d.ts +256 -0
- package/lib/typescript/types.d.ts.map +1 -0
- package/lib/typescript/utils.d.ts +38 -0
- package/lib/typescript/utils.d.ts.map +1 -0
- package/package.json +50 -0
- package/src/help.ts +340 -0
- package/src/index.ts +22 -0
- package/src/parser.ts +299 -0
- package/src/types.ts +286 -0
- package/src/utils.ts +154 -0
package/README.md
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
# zod-args-parser
|
|
2
|
+
|
|
3
|
+
A strictly typed command-line arguments parser powered by Zod.
|
|
4
|
+
|
|
5
|
+
## Features
|
|
6
|
+
|
|
7
|
+
- **Strict typing for subcommands, options, and arguments**.
|
|
8
|
+
- **Flag coupling support**: e.g., `-rf` to combine `-r` and `-f` flags.
|
|
9
|
+
- **Flexible option value formatting**: Supports both `--input-dir path` and `--input-dir=path` styles.
|
|
10
|
+
- **Help message generation**: Built-in methods to generate help text for the CLI and each subcommand.
|
|
11
|
+
|
|
12
|
+
## Installation
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
npm install zod-args-parser
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
## Usage
|
|
19
|
+
|
|
20
|
+
```ts
|
|
21
|
+
import { createCli, createSubcommand, safeParse } from "zod-args-parser";
|
|
22
|
+
|
|
23
|
+
// Create a CLI schema
|
|
24
|
+
// This will be used when no subcommands are provided
|
|
25
|
+
const cliProgram = createCli({
|
|
26
|
+
cliName: "my-cli",
|
|
27
|
+
description: "A description for my CLI",
|
|
28
|
+
example: "example of how to use my cli\nmy-cli --help",
|
|
29
|
+
options: [
|
|
30
|
+
{
|
|
31
|
+
name: "help",
|
|
32
|
+
description: "Show this help message",
|
|
33
|
+
aliases: ["h"],
|
|
34
|
+
type: z.boolean(),
|
|
35
|
+
},
|
|
36
|
+
],
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
// Execute this function when the CLI is run
|
|
40
|
+
cliProgram.setAction(results => {
|
|
41
|
+
const { help } = results;
|
|
42
|
+
if (help) results.printCliHelp();
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
// Create a subcommand schema
|
|
46
|
+
const helpCommandSchema = createSubcommand({
|
|
47
|
+
name: "help",
|
|
48
|
+
placeholder: "<command>",
|
|
49
|
+
description: "Print help message for command",
|
|
50
|
+
arguments: [
|
|
51
|
+
{
|
|
52
|
+
name: "command",
|
|
53
|
+
description: "Command to print help for",
|
|
54
|
+
type: z.enum(["build", "help", "init"]).optional(),
|
|
55
|
+
},
|
|
56
|
+
],
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
// Execute this function when the `help` subcommand is run
|
|
60
|
+
helpCommandSchema.setAction(results => {
|
|
61
|
+
const [command] = results.arguments;
|
|
62
|
+
if (command) results.printSubcommandHelp(command);
|
|
63
|
+
else results.printCliHelp();
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
const results = safeParse(
|
|
67
|
+
process.argv.slice(2),
|
|
68
|
+
cliProgram,
|
|
69
|
+
helpCommandSchema,
|
|
70
|
+
// Add more subcommands
|
|
71
|
+
);
|
|
72
|
+
|
|
73
|
+
// ! Error
|
|
74
|
+
if (!results.success) {
|
|
75
|
+
console.error(results.error.message);
|
|
76
|
+
console.log("\n`my-cli --help` for more information, or `my-cli help <command>` for command-specific help\n");
|
|
77
|
+
process.exit(1);
|
|
78
|
+
}
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
## Types Utility
|
|
82
|
+
|
|
83
|
+
```ts
|
|
84
|
+
import { createSubcommand } from "zod-args-parser";
|
|
85
|
+
import type { InferOptionsType, InferArgumentsType } from "zod-args-parser";
|
|
86
|
+
|
|
87
|
+
const subcommand = createSubcommand({
|
|
88
|
+
name: "subcommand",
|
|
89
|
+
options: [
|
|
90
|
+
{ name: "numberOption", type: z.coerce.number() },
|
|
91
|
+
{ name: "stringOption", type: z.string() },
|
|
92
|
+
{ name: "booleanOption", type: z.boolean() },
|
|
93
|
+
{ name: "optionalOption", type: z.boolean().optional() },
|
|
94
|
+
],
|
|
95
|
+
arguments: [
|
|
96
|
+
{ name: "stringArgument", type: z.string() },
|
|
97
|
+
{ name: "numberArgument", type: z.coerce.number() },
|
|
98
|
+
{ name: "booleanArgument", type: z.boolean() },
|
|
99
|
+
],
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
type Options = InferOptionsType<typeof subcommand>;
|
|
103
|
+
// { numberOption: number; stringOption: string; booleanOption: boolean; optionalOption?: boolean | undefined; }
|
|
104
|
+
|
|
105
|
+
type Arguments = InferArgumentsType<typeof subcommand>;
|
|
106
|
+
// [string, number, boolean]
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
## API
|
|
110
|
+
|
|
111
|
+
### `createSubcommand(input: Subcommand)`
|
|
112
|
+
|
|
113
|
+
Defines a subcommand with associated options and arguments.
|
|
114
|
+
|
|
115
|
+
- `name: string`
|
|
116
|
+
The name of the subcommand.
|
|
117
|
+
|
|
118
|
+
- `aliases?: string[]`
|
|
119
|
+
An array of aliases for the subcommand.
|
|
120
|
+
|
|
121
|
+
- `description?: string`
|
|
122
|
+
A description of the subcommand for the help message.
|
|
123
|
+
|
|
124
|
+
- `placeholder?: string`
|
|
125
|
+
A placeholder displayed in the help message alongside the subcommand name.
|
|
126
|
+
|
|
127
|
+
- `example?: string`
|
|
128
|
+
An example of subcommand usage for the help message.
|
|
129
|
+
|
|
130
|
+
- `allowPositional?: boolean`
|
|
131
|
+
Allows positional arguments for this subcommand.
|
|
132
|
+
Positional arguments are untyped (`string[]`) when enabled with the typed `arguments` any extra arguments, beyond the typed `arguments`, are parsed as positional and stored in the `positional` property.
|
|
133
|
+
|
|
134
|
+
- `options?: Option[]`
|
|
135
|
+
An array of options for the subcommand.
|
|
136
|
+
|
|
137
|
+
- `name: string`
|
|
138
|
+
The name of the option. Should be a valid variable name in JavaScript.
|
|
139
|
+
|
|
140
|
+
- `aliases?: string[]`
|
|
141
|
+
An array of aliases for the option.
|
|
142
|
+
|
|
143
|
+
- `type: ZodType`
|
|
144
|
+
Specifies the type of the option using Zod.
|
|
145
|
+
|
|
146
|
+
**Examples:**
|
|
147
|
+
|
|
148
|
+
- `type: z.boolean().default(false);`
|
|
149
|
+
- `type: z.coerce.number(); // coerces value to a number`
|
|
150
|
+
- `type: z.preprocess(parseStringToArrFn, z.array(z.coerce.number())); // array of numbers`
|
|
151
|
+
|
|
152
|
+
- `description?: string`
|
|
153
|
+
A description of the option for the help message.
|
|
154
|
+
|
|
155
|
+
- `placeholder?: string`
|
|
156
|
+
Placeholder text for the option in the help message.
|
|
157
|
+
|
|
158
|
+
- `example?: string`
|
|
159
|
+
An example of option usage for the help message.
|
|
160
|
+
|
|
161
|
+
- `arguments?: Argument[]`
|
|
162
|
+
An array of arguments for the subcommand.
|
|
163
|
+
|
|
164
|
+
- `name: string`
|
|
165
|
+
The name of the argument for display in the help message.
|
|
166
|
+
|
|
167
|
+
- `type: ZodType`
|
|
168
|
+
Specifies the type of the argument using Zod.
|
|
169
|
+
|
|
170
|
+
**Examples:**
|
|
171
|
+
|
|
172
|
+
- `type: z.boolean();`
|
|
173
|
+
- `type: z.coerce.number(); // coerces value to a number`
|
|
174
|
+
|
|
175
|
+
- `description?: string`
|
|
176
|
+
A description of the argument for the help message.
|
|
177
|
+
|
|
178
|
+
- `example?: string`
|
|
179
|
+
An example of argument usage for the help message.
|
|
180
|
+
|
|
181
|
+
### Results
|
|
182
|
+
|
|
183
|
+
- `subcommand: string | undefined`
|
|
184
|
+
The name of the executed subcommand.
|
|
185
|
+
If no subcommand is executed, this will be `undefined`.
|
|
186
|
+
|
|
187
|
+
- `arguments?: any[]`
|
|
188
|
+
An array representing defined arguments for the subcommand, e.g., `[string, number]`.
|
|
189
|
+
Only defined if the subcommand has specified `arguments`.
|
|
190
|
+
|
|
191
|
+
- `positional?: string[]`
|
|
192
|
+
Contains positional arguments as `string[]` if `allowPositional` is enabled for the subcommand.
|
|
193
|
+
|
|
194
|
+
- `printCliHelp(options?: PrintHelpOpt): void`
|
|
195
|
+
Prints the CLI help message.
|
|
196
|
+
Accepts an optional `options` object to disable colors or customize colors.
|
|
197
|
+
|
|
198
|
+
- `printSubcommandHelp(subcommand: string, options?: PrintHelpOpt): void`
|
|
199
|
+
Prints the help message for a specified subcommand.
|
|
200
|
+
|
|
201
|
+
- `[key: optionName]: optionType`
|
|
202
|
+
Represents options specified in the CLI or subcommand with their respective types.
|
|
203
|
+
|
|
204
|
+
### `parse(args: string[], cli: Cli, ...subcommands: Subcommand[]): UnSafeParseResult`
|
|
205
|
+
|
|
206
|
+
Parses the provided arguments and returns a `Results` object.
|
|
207
|
+
Throws an error if parsing fails.
|
|
208
|
+
|
|
209
|
+
### `safeParse(args: string[], cli: Cli, ...subcommands: Subcommand[]): SafeParseResult`
|
|
210
|
+
|
|
211
|
+
Parses the provided arguments and returns:
|
|
212
|
+
|
|
213
|
+
```ts
|
|
214
|
+
{ success: false, error: Error } | { success: true, data: ResultObj }
|
|
215
|
+
```
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.help=void 0;var _chalk=_interopRequireDefault(require("chalk"));var _utils=require("./utils.js");function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e};}const colors={title:_chalk.default.bold.blue,description:_chalk.default.white,default:_chalk.default.dim.italic,optional:_chalk.default.dim.italic,exampleTitle:_chalk.default.yellow,example:_chalk.default.dim.italic,command:_chalk.default.yellow,option:_chalk.default.cyan,argument:_chalk.default.green,placeholder:_chalk.default.hex("#FF9800"),punctuation:_chalk.default.white.dim};function printCliHelp(params){let printOptions=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};printOptions.colors??=true;const noColors=new Proxy(colors,{get:()=>{return function(){for(var _len=arguments.length,str=new Array(_len),_key=0;_key<_len;_key++){str[_key]=arguments[_key];}return 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=>{(0,_utils.print)(c.title(` ${title.toUpperCase()} `));};const cliName=cliOptions.cliName??"";const usage=cliOptions.usage??(0,_utils.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");(0,_utils.println)();(0,_utils.println)((0,_utils.indent)(2),usage,(0,_utils.ln)(1));if(cliOptions.description){printTitle("Description");(0,_utils.println)();(0,_utils.println)((0,_utils.indent)(2),c.description(cliOptions.description),(0,_utils.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");(0,_utils.println)();const normalizeExample=cliOptions.example.replace(/\n/g,"\n"+(0,_utils.indent)(3));(0,_utils.println)((0,_utils.indent)(2),c.example(normalizeExample),(0,_utils.ln)(1));}}function printSubcommandHelp(subcommand){let printOptions=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};let cliName=arguments.length>2&&arguments[2]!==undefined?arguments[2]:"";printOptions.colors??=true;const noColors=new Proxy(colors,{get:()=>{return function(){for(var _len2=arguments.length,str=new Array(_len2),_key2=0;_key2<_len2;_key2++){str[_key2]=arguments[_key2];}return str.join(" ");};}});const c=printOptions.colors?colors:noColors;if(printOptions.customColors){Object.assign(c,printOptions.customColors);}const printTitle=title=>{(0,_utils.print)(c.title(` ${title.toUpperCase()} `));};const usage=(0,_utils.concat)(c.punctuation("$"),cliName,c.command(subcommand.name),subcommand.options?.length?c.option("[options]"):"",subcommand.arguments?.length||subcommand.allowPositional?c.argument("<arguments>"):"");printTitle("Usage");(0,_utils.println)();(0,_utils.println)((0,_utils.indent)(2),usage,(0,_utils.ln)(1));if(subcommand.description){printTitle("Description");(0,_utils.println)();const normalizeDesc=subcommand.description.replace(/\n/g,"\n"+(0,_utils.indent)(3));(0,_utils.println)((0,_utils.indent)(2),c.description(normalizeDesc),(0,_utils.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");(0,_utils.println)();const normalizeExample=subcommand.example.replace(/\n/g,"\n"+(0,_utils.indent)(3));(0,_utils.println)((0,_utils.indent)(2),c.example(normalizeExample),(0,_utils.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=>(0,_utils.transformOptionToArg)(name)))).join(", ");const defaultValue=(0,_utils.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=(0,_utils.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;(0,_utils.print)(c.title(" OPTIONS "));(0,_utils.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"+(0,_utils.indent)(longest+7)+c.punctuation("└"));const coloredNames=names.split(/(,)/).map(name=>name===","?c.punctuation(name):c.option(name)).join("");(0,_utils.println)((0,_utils.indent)(2),coloredNames,c.placeholder(placeholder),(0,_utils.indent)(spacing),c.description(normalizeDesc),def?c.default(def):c.optional(optional));if(example){const normalizeExample=example.replace(/\n/g,"\n"+(0,_utils.indent)(longest+17));(0,_utils.println)((0,_utils.indent)(longest+6),c.punctuation("└")+c.exampleTitle("Example:"),c.example(normalizeExample));}}(0,_utils.println)();}function printPreparedCommands(commandsToPrint,c,longest){if(!commandsToPrint.length)return;(0,_utils.print)(c.title(" COMMANDS "));(0,_utils.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"+(0,_utils.indent)(longest+7));const coloredNames=names.split(/(,)/).map(name=>name===","?c.punctuation(name):c.command(name)).join("");(0,_utils.println)((0,_utils.indent)(2),coloredNames,c.placeholder(placeholder),(0,_utils.indent)(spacing),c.description(normalizeDesc));}(0,_utils.println)();}function printPreparedArguments(argsToPrint,c,longest){if(!argsToPrint.length)return;(0,_utils.print)(c.title(" ARGUMENTS "));(0,_utils.println)();for(const{names,description,example,optional,default:def}of argsToPrint){const spacing=longest+2-names.length;const normalizeDesc=description.replace(/\n/g,"\n"+(0,_utils.indent)(longest+6)+c.punctuation("└"));(0,_utils.println)((0,_utils.indent)(2),c.argument(names),(0,_utils.indent)(spacing),c.description(normalizeDesc),def?c.default(def):c.optional(optional));if(example){const normalizeExample=example.replace(/\n/g,"\n"+(0,_utils.indent)(longest+16));(0,_utils.println)((0,_utils.indent)(longest+5),c.punctuation("└")+c.exampleTitle("Example:"),c.example(normalizeExample));}}(0,_utils.println)();}const help=exports.help={printCliHelp,printSubcommandHelp};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"names":["_chalk","_interopRequireDefault","require","_utils","e","__esModule","default","colors","title","chalk","bold","blue","description","white","dim","italic","optional","exampleTitle","yellow","example","command","option","cyan","argument","green","placeholder","hex","punctuation","printCliHelp","params","printOptions","arguments","length","undefined","noColors","Proxy","get","_len","str","Array","_key","join","c","customColors","Object","assign","isFirstParamCli","cliOptions","shift","subcommands","printTitle","print","toUpperCase","cliName","usage","concat","options","allowPositional","println","indent","ln","longest","optionsToPrint","longestOptionIndent","prepareOptionsToPrint","commandsToPrint","longestSubcommandIndent","prepareCommandsToPrint","argsToPrint","longestArgIndent","prepareArgumentsToPrint","printPreparedOptions","printPreparedCommands","printPreparedArguments","normalizeExample","replace","printSubcommandHelp","subcommand","_len2","_key2","name","normalizeDesc","nameWithAliases","aliases","names","from","Set","map","transformOptionToArg","defaultValue","getDefaultValueFromSchema","type","push","JSON","stringify","isOptional","optLength","cmdLength","args","arg","def","spacing","coloredNames","split","help","exports"],"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\n/** Colors */\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.italic,\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 = 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));\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":"0FAAA,IAAAA,MAAA,CAAAC,sBAAA,CAAAC,OAAA,WACA,IAAAC,MAAA,CAAAD,OAAA,eAAiH,SAAAD,uBAAAG,CAAA,SAAAA,CAAA,EAAAA,CAAA,CAAAC,UAAA,CAAAD,CAAA,EAAAE,OAAA,CAAAF,CAAA,GAKjH,KAAM,CAAAG,MAA2D,CAAG,CAClEC,KAAK,CAAEC,cAAK,CAACC,IAAI,CAACC,IAAI,CACtBC,WAAW,CAAEH,cAAK,CAACI,KAAK,CACxBP,OAAO,CAAEG,cAAK,CAACK,GAAG,CAACC,MAAM,CACzBC,QAAQ,CAAEP,cAAK,CAACK,GAAG,CAACC,MAAM,CAC1BE,YAAY,CAAER,cAAK,CAACS,MAAM,CAC1BC,OAAO,CAAEV,cAAK,CAACK,GAAG,CAACC,MAAM,CACzBK,OAAO,CAAEX,cAAK,CAACS,MAAM,CACrBG,MAAM,CAAEZ,cAAK,CAACa,IAAI,CAClBC,QAAQ,CAAEd,cAAK,CAACe,KAAK,CACrBC,WAAW,CAAEhB,cAAK,CAACiB,GAAG,CAAC,SAAS,CAAC,CACjCC,WAAW,CAAElB,cAAK,CAACI,KAAK,CAACC,GAC3B,CAAC,CAWD,QAAS,CAAAc,YAAYA,CAACC,MAA8B,CAAmC,IAAjC,CAAAC,YAA0B,CAAAC,SAAA,CAAAC,MAAA,IAAAD,SAAA,MAAAE,SAAA,CAAAF,SAAA,IAAG,CAAC,CAAC,CACnFD,YAAY,CAACvB,MAAM,GAAK,IAAI,CAE5B,KAAM,CAAA2B,QAAQ,CAAG,GAAI,CAAAC,KAAK,CAAC5B,MAAM,CAAE,CACjC6B,GAAG,CAAEA,CAAA,GAAM,CACT,MAAO,oBAAAC,IAAA,CAAAN,SAA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ports,"__esModule",{value:true});exports.createCli=createCli;exports.createSubcommand=createSubcommand;Object.defineProperty(exports,"parse",{enumerable:true,get:function(){return _parser.parse;}});exports.printSubcommandHelp=exports.printCliHelp=void 0;Object.defineProperty(exports,"safeParse",{enumerable:true,get:function(){return _parser.safeParse;}});var _help=require("./help.js");var _parser=require("./parser.js");function createSubcommand(input){return Object.assign(input,{setAction:action=>input.action=action});}function createCli(input){return Object.assign(input,{setAction:action=>input.action=action});}const{printCliHelp,printSubcommandHelp}=_help.help;exports.printSubcommandHelp=printSubcommandHelp;exports.printCliHelp=printCliHelp;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"names":["_help","require","_parser","createSubcommand","input","Object","assign","setAction","action","createCli","printCliHelp","printSubcommandHelp","help","exports"],"sourceRoot":"../../src","sources":["index.ts"],"sourcesContent":["import { help } from \"./help.js\";\nimport { parse, safeParse } from \"./parser.js\";\n\nimport type { ActionFn, Cli, Prettify, Subcommand, UnSafeParseResult } from \"./types.js\";\n\nfunction createSubcommand<const T extends Subcommand>(input: T & Subcommand): Prettify<T & ActionFn<T>> {\n return Object.assign(input, {\n setAction: (action: (res: UnSafeParseResult<[T]>) => void) => (input.action = action),\n });\n}\n\nfunction createCli<const T extends Cli>(input: T & Cli): Prettify<T & ActionFn<T>> {\n return Object.assign(input, {\n setAction: (action: (res: UnSafeParseResult<[T]>) => void) => (input.action = action),\n });\n}\n\nconst { printCliHelp, printSubcommandHelp } = help;\n\nexport { createCli, createSubcommand, parse, printCliHelp, printSubcommandHelp, safeParse };\n\nexport type * from \"./types.js\";\n"],"mappings":"0YAAA,IAAAA,KAAA,CAAAC,OAAA,cACA,IAAAC,OAAA,CAAAD,OAAA,gBAIA,QAAS,CAAAE,gBAAgBA,CAA6BC,KAAqB,CAA6B,CACtG,MAAO,CAAAC,MAAM,CAACC,MAAM,CAACF,KAAK,CAAE,CAC1BG,SAAS,CAAGC,MAA6C,EAAMJ,KAAK,CAACI,MAAM,CAAGA,MAChF,CAAC,CAAC,CACJ,CAEA,QAAS,CAAAC,SAASA,CAAsBL,KAAc,CAA6B,CACjF,MAAO,CAAAC,MAAM,CAACC,MAAM,CAACF,KAAK,CAAE,CAC1BG,SAAS,CAAGC,MAA6C,EAAMJ,KAAK,CAACI,MAAM,CAAGA,MAChF,CAAC,CAAC,CACJ,CAEA,KAAM,CAAEE,YAAY,CAAEC,mBAAoB,CAAC,CAAGC,UAAI,CAACC,OAAA,CAAAF,mBAAA,CAAAA,mBAAA,CAAAE,OAAA,CAAAH,YAAA,CAAAA,YAAA","ignoreList":[]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.parse=parse;exports.safeParse=safeParse;var _help=require("./help.js");var _utils=require("./utils.js");function parse(argsv){for(var _len=arguments.length,params=new Array(_len>1?_len-1:0),_key=1;_key<_len;_key++){params[_key-1]=arguments[_key];}const cliOptions="cliName"in params[0]?params[0]:{};const subcommandArr=params;const allSubcommands=new Set(subcommandArr.flatMap(c=>[c.name,...(c.aliases||[])]));argsv=(0,_utils.decoupleFlags)(argsv);const results={subcommand:undefined,printCliHelp(opt){_help.help.printCliHelp(params,opt);},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.help.printSubcommandHelp(subcommand,opt,cliOptions.cliName);}};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=subcommandArr.find(c=>c.name===results.subcommand);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((0,_utils.isOptionArg)(argument)){if((0,_utils.isFlagArg)(argument)&&argWithEquals){throw new Error(`Flag arguments cannot be assigned using "=": "${arg}"`);}const subcommandProps=subcommandArr.find(c=>c.name===results.subcommand);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=(0,_utils.transformArg)(argument);if(optionName in results)throw new Error(`Duplicate option: "${argument}"`);const isNegative=argument.startsWith("--no-");const option=subcommandProps.options.find(o=>{if(o.name===optionName)return true;if(isNegative&&(0,_utils.noName)(o.name)===optionName)return true;if(!o.aliases)return false;if(o.aliases.includes(optionName))return true;if(isNegative&&o.aliases.map(_utils.noName).includes(optionName))return true;return false;});if(!option){throw new Error(`Unknown option: "${argument}"`);}const isTypeBoolean=(0,_utils.isBooleanSchema)(option.type);const nextArg=argsv[i+1];let optionValue=argWithEquals?argValue:nextArg;if(isTypeBoolean){if(argWithEquals){const parsedBoolean=(0,_utils.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&&(0,_utils.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=subcommandArr.find(c=>c.name===results.subcommand);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=(0,_utils.isBooleanSchema)(argType);if(isTypeBoolean)argValue=(0,_utils.stringToBoolean)(argValue);const res=argType.safeParse(argValue);if(!res.success){throw new Error(`The ${(0,_utils.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=subcommandArr.find(c=>c.name===results.subcommand);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: ${(0,_utils.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 ${(0,_utils.getOrdinalPlacement)(i)} argument is required: "${subcommandProps.arguments[i].name}"`);}}}if(subcommandProps?.action){subcommandProps.action(results);}return results;}function safeParse(argsv){for(var _len2=arguments.length,params=new Array(_len2>1?_len2-1:0),_key2=1;_key2<_len2;_key2++){params[_key2-1]=arguments[_key2];}const cliOptions="cliName"in params[0]?params[0]:{};const subcommandArr=params;const printCliHelp=opt=>_help.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.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};}}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"names":["_help","require","_utils","parse","argsv","_len","arguments","length","params","Array","_key","cliOptions","subcommandArr","allSubcommands","Set","flatMap","c","name","aliases","decoupleFlags","results","subcommand","undefined","printCliHelp","opt","help","printSubcommandHelp","subcommandStr","find","console","error","cliName","addRawArg","optionName","rawArg","_info","Object","create","addRawValue","rawValue","addSource","source","fillOption","value","assign","i","arg","has","subcommandProps","allowPositional","positional","argAndValue","split","filter","Boolean","argWithEquals","includes","argument","argValue","isOptionArg","isFlagArg","Error","options","msg","transformArg","isNegative","startsWith","option","o","noName","map","isTypeBoolean","isBooleanSchema","type","nextArg","optionValue","parsedBoolean","stringToBoolean","res","safeParse","success","errors","message","data","rawVal","currentArgCount","argType","getOrdinalPlacement","push","isOptional","hasDefault","_def","defaultValue","transformOptionToArg","subcommandArgCount","argumentType","action","_len2","_key2","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 SafeParseResult,\n Subcommand,\n UnSafeParseResult,\n} from \"./types.js\";\n\nexport function parse<T extends Subcommand[]>(argsv: string[], ...params: T): UnSafeParseResult<T>;\nexport function parse<T extends Subcommand[], U extends Cli>(\n argsv: string[],\n ...params: [U, ...T]\n): UnSafeParseResult<[...T, NoSubcommand & U]>;\n\nexport function parse<T extends Subcommand[], U extends Cli>(argsv: string[], ...params: [U, ...T]) {\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 => 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\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 = subcommandArr.find(c => c.name === results.subcommand);\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 = subcommandArr.find(c => c.name === results.subcommand);\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 if (optionName in results) throw new Error(`Duplicate option: \"${argument}\"`);\n\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 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 = subcommandArr.find(c => c.name === results.subcommand);\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 = subcommandArr.find(c => c.name === results.subcommand);\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[]>(argsv: string[], ...params: T): SafeParseResult<T>;\nexport function safeParse<T extends Subcommand[], U extends Cli>(\n argsv: string[],\n ...params: [U, ...T]\n): SafeParseResult<[...T, NoSubcommand & U]>;\n\nexport function safeParse<T extends Subcommand[], U extends Cli>(argsv: string[], ...params: [U, ...T]) {\n const cliOptions = (\"cliName\" in params[0] ? params[0] : {}) as U;\n const subcommandArr = params as Subcommand[];\n\n const printCliHelp = (opt?: PrintHelpOpt) => help.printCliHelp(params, opt);\n const printSubcommandHelp = (subcommandStr: NonNullable<T[number][\"name\"]>, opt?: PrintHelpOpt) => {\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 error\n delete data.printCliHelp;\n // @ts-expect-error error\n delete data.printSubcommandHelp;\n\n return {\n success: true,\n data: data as Omit<typeof data, \"printCliHelp\" | \"printSubcommandHelp\">,\n printCliHelp,\n printSubcommandHelp,\n };\n } catch (e) {\n return { success: false, error: e as Error, printCliHelp, printSubcommandHelp };\n }\n}\n"],"mappings":"sHAAA,IAAAA,KAAA,CAAAC,OAAA,cACA,IAAAC,MAAA,CAAAD,OAAA,eA4BO,QAAS,CAAAE,KAAKA,CAAwCC,KAAe,CAAwB,SAAAC,IAAA,CAAAC,SAAA,CAAAC,MAAA,CAAnBC,MAAM,KAAAC,KAAA,CAAAJ,IAAA,GAAAA,IAAA,MAAAK,IAAA,GAAAA,IAAA,CAAAL,IAAA,CAAAK,IAAA,IAANF,MAAM,CAAAE,IAAA,IAAAJ,SAAA,CAAAI,IAAA,GACrF,KAAM,CAAAC,UAAU,CAAI,SAAS,EAAI,CAAAH,MAAM,CAAC,CAAC,CAAC,CAAGA,MAAM,CAAC,CAAC,CAAC,CAAG,CAAC,CAAO,CACjE,KAAM,CAAAI,aAAa,CAAGJ,MAAsB,CAC5C,KAAM,CAAAK,cAAc,CAAG,GAAI,CAAAC,GAAG,CAASF,aAAa,CAACG,OAAO,CAACC,CAAC,EAAI,CAACA,CAAC,CAACC,IAAI,CAAE,IAAID,CAAC,CAACE,OAAO,EAAI,EAAE,CAAC,CAAC,CAAC,CAAC,CAGlGd,KAAK,CAAG,GAAAe,oBAAa,EAACf,KAAK,CAAC,CAW5B,KAAM,CAAAgB,OAAkB,CAAG,CACzBC,UAAU,CAAEC,SAAS,CACrBC,YAAYA,CAACC,GAAG,CAAE,CAChBC,UAAI,CAACF,YAAY,CAACf,MAAM,CAAEgB,GAAG,CAAC,CAChC,CAAC,CACDE,mBAAmBA,CAACC,aAAa,CAAEH,GAAG,CAAE,CACtC,KAAM,CAAAH,UAAU,CAAGT,aAAa,CAACgB,IAAI,CAACZ,CAAC,EA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B,IAAI,CAACZ,CAAC,EAAIA,CAAC,CAACC,IAAI,GAAKU,aAAa,CAAC,CACpE,GAAI,CAACN,UAAU,CAAE,MAAO,CAAAQ,OAAO,CAACC,KAAK,CAAC,qCAAqCH,aAAa,wBAAwB,CAAC,CACjHF,UAAI,CAACC,mBAAmB,CAACL,UAAU,CAAEG,GAAG,CAAEb,UAAU,CAACoB,OAAO,CAAC,CAC/D,CAAC,CAED,GAAI,CACF,KAAM,CAAAoD,IAAI,CAAGhF,KAAK,CAACC,KAAK,CAAE,GAAGI,MAAM,CAAC,CAEpC,MAAO,CAAA2E,IAAI,CAAC5D,YAAY,CAExB,MAAO,CAAA4D,IAAI,CAACzD,mBAAmB,CAE/B,MAAO,CACLsD,OAAO,CAAE,IAAI,CACbG,IAAI,CAAEA,IAAiE,CACvE5D,YAAY,CACZG,mBACF,CAAC,CACH,CAAE,MAAOyE,CAAC,CAAE,CACV,MAAO,CAAEnB,OAAO,CAAE,KAAK,CAAElD,KAAK,CAAEqE,CAAU,CAAE5E,YAAY,CAAEG,mBAAoB,CAAC,CACjF,CACF","ignoreList":[]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"names":[],"sourceRoot":"../../src","sources":["types.ts"],"sourcesContent":["import type { z } from \"zod\";\n\nexport type Subcommand = {\n /**\n * - The subcommand name, use `kebab-case`.\n * - Make sure to not duplicate commands and aliases.\n *\n * @example\n * name: \"test\";\n * name: \"run-app\";\n */\n name: string;\n\n /**\n * - The action is executed with the result of the parsed arguments.\n * - To get typescript types use `setAction` instead of this.\n *\n * @example\n * const helpCommand = createSubcommand({ name: \"help\", options: [...] });\n * helpCommand.setAction(res => console.log(res));\n */\n action?: (results?: any) => void;\n\n /**\n * - The description of the subcommand.\n * - Used for generating the help message.\n */\n description?: string;\n\n /** - Used for generating the help message. */\n placeholder?: string;\n\n /**\n * - Provide an example to show to the user.\n * - Used for generating the help message.\n */\n example?: string;\n\n /**\n * - The aliases of the subcommand.\n * - Make sure to not duplicate aliases and commands.\n */\n aliases?: string[];\n\n /**\n * - Allows positional arguments for this subcommand.\n * - Unlike `arguments`, which are strictly typed, positional arguments are untyped and represented as a string array of\n * variable length.\n * - When enabled and `arguments` are provided, `arguments` will be parsed first. Any remaining arguments will be\n * considered positional arguments and added to the `positional` property in the result.\n */\n allowPositional?: boolean;\n\n /**\n * - The options of the command.\n * - Those options are specific to this subcommand.\n */\n options?: [Option, ...Option[]];\n\n /**\n * - Specifies a list of strictly typed arguments.\n * - The order is important; for example, the first argument will be validated against the first specified type.\n * - It is recommended to not use optional arguments as the parser will fill the arguments by order and can't determine\n * which arguments are optional.\n */\n arguments?: [Argument, ...Argument[]];\n};\n\nexport type Cli = Prettify<\n Omit<Subcommand, \"name\"> & {\n /** - The name of the CLI program. */\n cliName: string;\n\n /**\n * - The usage of the CLI program.\n * - Used for generating the help message.\n */\n usage?: string;\n }\n>;\n\nexport type Option = {\n /**\n * - The name of the option, use `CamelCase`.\n * - For example: the syntax for the option `rootPath` is `--root-path`.\n */\n name: string;\n\n /**\n * - The will be used to validate the user input.\n *\n * @example\n * type: z.boolean().default(false);\n * type: z.coerce.number(); // will be coerced to number by Zod\n * type: z.preprocess(parseStringToArrFn, z.array(z.coerce.number())); // array of numbers\n *\n * @see https://zod.dev/?id=types\n */\n type: z.ZodTypeAny;\n\n /**\n * - The description of the option.\n * - Used for generating the help message.\n */\n description?: string;\n\n /** - Used for generating the help message. */\n placeholder?: string;\n\n /**\n * - The example of using the option.\n * - Used for generating the help message.\n */\n example?: string;\n\n /**\n * - The aliases of the option, use `CamelCase`.\n * - Here you can specify short names or flags.\n * - Make sure to not duplicate aliases.\n */\n aliases?: [string, ...string[]];\n};\n\nexport type Argument = {\n /** - The name of the argument. */\n name: string;\n\n /**\n * - The will be used to validate the user input.\n *\n * @example\n * type: z.boolean();\n * type: z.coerce.number(); // will be coerced to number by Zod\n * type: z.preprocess(ParseStringToArrFn, z.array(z.coerce.number())); // array of numbers\n *\n * @see https://zod.dev/?id=types\n */\n type: z.ZodTypeAny;\n\n /**\n * - The description of the argument.\n * - Used for generating the help message.\n */\n description?: string;\n\n /**\n * - The example of using the argument.\n * - Used for generating the help message.\n */\n example?: string;\n};\n\nexport type ColorFnType = (...text: unknown[]) => string;\n\nexport type PrintHelpOpt = {\n /**\n * - **Optional** `boolean`\n * - Whether to print colors or not.\n * - Default: `true`\n */\n colors?: boolean;\n\n /**\n * - **Optional** `object`\n * - The colors to use for the help message.\n */\n customColors?: {\n title?: ColorFnType;\n description?: ColorFnType;\n default?: ColorFnType;\n optional?: ColorFnType;\n exampleTitle?: ColorFnType;\n example?: ColorFnType;\n command?: ColorFnType;\n option?: ColorFnType;\n argument?: ColorFnType;\n placeholder?: ColorFnType;\n punctuation?: ColorFnType;\n };\n};\n\nexport type _Info = {\n /**\n * - The raw argument as it was passed in\n * - For options that have a default value and are not passed in, the raw argument will be `undefined`\n */\n rawArg?: string;\n /**\n * - The raw value of the argument as it was passed in\n * - It will be empty string for `boolean` options. E.g. `--help` or `-h`\n * - For options that have a default value and are not passed in, the raw value will be `undefined`\n */\n rawValue?: string;\n /**\n * - The source value of the argument:\n * - `cli`: The argument was passed in by the user\n * - `default`: The argument was not passed in and has a default value\n */\n source: \"cli\" | \"default\";\n};\n\n/**\n * - Infer the options type from a subcommand.\n *\n * @example\n * const subcommand = createSubcommand({ name: \"build\", options: [...] });\n * type OptionsType = InferOptionsType<typeof subcommand>;\n */\nexport type InferOptionsType<T extends Partial<Subcommand>> = T[\"options\"] extends infer U extends Option[]\n ? ToOptional<{ [K in U[number][\"name\"]]: z.infer<Extract<U[number], { name: K }>[\"type\"]> }>\n : undefined;\n\n/**\n * - Infer the arguments type from a subcommand.\n *\n * @example\n * const subcommand = createSubcommand({ name: \"build\", arguments: [...] });\n * type ArgumentsType = InferArgumentsType<typeof subcommand>;\n */\nexport type InferArgumentsType<T extends Partial<Subcommand>> = T[\"arguments\"] extends infer U extends Argument[]\n ? { [K in keyof U]: U[K] extends { type: z.ZodTypeAny } ? z.infer<U[K][\"type\"]> : never }\n : undefined;\n\n/** `{ some props } & { other props }` => `{ some props, other props }` */\nexport type Prettify<T> = { [K in keyof T]: T[K] } & {};\n\n/** Allow string type for literal union and get auto completion */\nexport type LiteralUnion<T extends string> = T | (string & {});\n\n/** Extract the undefined properties from an object */\ntype UndefinedProperties<T> = { [P in keyof T]-?: undefined extends T[P] ? P : never }[keyof T];\n\n/** Make undefined properties optional? */\ntype ToOptional<T> = Prettify<\n Partial<Pick<T, UndefinedProperties<T>>> & Pick<T, Exclude<keyof T, UndefinedProperties<T>>>\n>;\n\nexport type OptionsArr2RecordType<T extends Option[] | undefined> = T extends Option[]\n ? ToOptional<{ [K in T[number][\"name\"]]: z.infer<Extract<T[number], { name: K }>[\"type\"]> }>\n : object;\n\nexport type ArgumentsArr2ArrType<T extends Argument[] | undefined> = T extends Argument[]\n ? { arguments: { [K in keyof T]: T[K] extends { type: z.ZodTypeAny } ? z.infer<T[K][\"type\"]> : never } }\n : object;\n\nexport type Positional<S extends Partial<Subcommand>> = S[\"allowPositional\"] extends true ? { positional: string[] } : object;\n\nexport type Info<T extends Option[] | undefined> = T extends Option[]\n ? {\n _info: ToOptional<{\n [K in T[number][\"name\"]]: Extract<T[number], { name: K }> extends infer U extends Option\n ? undefined extends z.infer<U[\"type\"]>\n ? undefined | Prettify<_Info & U> // if optional add undefined\n : Prettify<_Info & U>\n : never;\n }>;\n }\n : object;\n\nexport type NoSubcommand = { name: undefined };\n\nexport type ParseResult<S extends Partial<Subcommand>[]> = {\n [K in keyof S]: Prettify<\n { subcommand: S[K][\"name\"] } & Positional<S[K]> &\n Info<S[K][\"options\"]> &\n OptionsArr2RecordType<S[K][\"options\"]> &\n ArgumentsArr2ArrType<S[K][\"arguments\"]>\n >;\n}[number];\n\nexport type PrintMethods<N extends Subcommand[\"name\"] | undefined> = {\n printCliHelp: (options?: PrintHelpOpt) => void;\n printSubcommandHelp: (subcommand: LiteralUnion<NonNullable<N>>, options?: PrintHelpOpt) => void;\n};\n\nexport type UnSafeParseResult<S extends Partial<Subcommand>[]> = Prettify<\n ParseResult<S> & PrintMethods<S[number][\"name\"]>\n>;\n\nexport type SafeParseResult<S extends Partial<Subcommand>[]> = Prettify<\n ({ success: false; error: Error } | { success: true; data: ParseResult<S> }) & PrintMethods<S[number][\"name\"]>\n>;\n\nexport type ActionFn<T extends Subcommand | Cli> = {\n setAction: (actions: (res: UnSafeParseResult<[T]>) => void) => void;\n};\n"],"mappings":"","ignoreList":[]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.addIndentLn=addIndentLn;exports.concat=concat;exports.decoupleFlags=decoupleFlags;exports.getDefaultValueFromSchema=getDefaultValueFromSchema;exports.getOrdinalPlacement=getOrdinalPlacement;exports.indent=indent;exports.isBooleanSchema=isBooleanSchema;exports.isFlagArg=isFlagArg;exports.isOptionArg=isOptionArg;exports.ln=ln;exports.noName=noName;exports.print=print;exports.println=println;exports.stringToBoolean=stringToBoolean;exports.transformArg=transformArg;exports.transformOptionToArg=transformOptionToArg;var _nodeAssert=_interopRequireDefault(require("node:assert"));var _zod=require("zod");function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e};}function transformArg(name){(0,_nodeAssert.default)(name.startsWith("-"),`[transformArg] Invalid arg name: ${name}`);name=name.startsWith("--")?name.substring(2):name.substring(1);return name.replace(/-([a-z])/g,g=>g[1].toUpperCase());}function transformOptionToArg(name){name=name.replace(/^[A-Z]/g,g=>g.toLowerCase());if(name.length===1)return`-${name}`;return`--${name.replace(/[A-Z]/g,g=>"-"+g.toLowerCase())}`;}function isFlagArg(name){return /^-[a-z]$/.test(name);}function isOptionArg(name){if(typeof name!=="string")return false;return isFlagArg(name)||name.startsWith("--");}function noName(name){if(name.length===1)return name;return"no"+name.replace(/^[a-z]/,g=>g.toUpperCase());}function stringToBoolean(str){if(str.toLowerCase()==="true")return true;if(str.toLowerCase()==="false")return false;throw new Error(`[stringToBoolean] Invalid boolean value: "${str}"; Expected "true" or "false"`);}function getOrdinalPlacement(index){if(index<0)return"";const suffixes=["th","st","nd","rd"];const lastDigit=index%10;const lastTwoDigits=index%100;const suffix=lastDigit===1&&lastTwoDigits!==11?suffixes[1]:lastDigit===2&&lastTwoDigits!==12?suffixes[2]:lastDigit===3&&lastTwoDigits!==13?suffixes[3]:suffixes[0];return`${index+1}${suffix}`;}function isBooleanSchema(schema){let type=schema;while(type){if(type instanceof _zod.z.ZodBoolean){return true;}if(type instanceof _zod.z.ZodLiteral){return type.value===true||type.value===false;}type=type._def.innerType;}return false;}function getDefaultValueFromSchema(schema){let type=schema;while(type){if(type instanceof _zod.z.ZodDefault){const defaultValue=type._def.defaultValue();return defaultValue;}type=type._def.innerType;}return undefined;}function decoupleFlags(args){const flagsRe=/^-[a-z]{2,}$/i;const result=[];for(let i=0;i<args.length;i++){const arg=args[i];const isCoupled=flagsRe.test(arg);if(!isCoupled){result.push(arg);continue;}const decoupledArr=arg.substring(1).split("").map(c=>"-"+c);result.push(...decoupledArr);}return result;}function print(){for(var _len=arguments.length,messages=new Array(_len),_key=0;_key<_len;_key++){messages[_key]=arguments[_key];}return process.stdout.write(messages.join(" "));}function println(){for(var _len2=arguments.length,messages=new Array(_len2),_key2=0;_key2<_len2;_key2++){messages[_key2]=arguments[_key2];}messages=messages.filter(Boolean);return console.log(...messages);}function ln(count){return"\n".repeat(count);}function indent(count){return" ".repeat(count);}function addIndentLn(message){let indent=arguments.length>1&&arguments[1]!==undefined?arguments[1]:"";return message.replace(/\n/g,`\n${indent}`);}function concat(){for(var _len3=arguments.length,messages=new Array(_len3),_key3=0;_key3<_len3;_key3++){messages[_key3]=arguments[_key3];}messages=messages.filter(Boolean);return messages.join(" ");}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"names":["_nodeAssert","_interopRequireDefault","require","_zod","e","__esModule","default","transformArg","name","assert","startsWith","substring","replace","g","toUpperCase","transformOptionToArg","toLowerCase","length","isFlagArg","test","isOptionArg","noName","stringToBoolean","str","Error","getOrdinalPlacement","index","suffixes","lastDigit","lastTwoDigits","suffix","isBooleanSchema","schema","type","z","ZodBoolean","ZodLiteral","value","_def","innerType","getDefaultValueFromSchema","ZodDefault","defaultValue","undefined","decoupleFlags","args","flagsRe","result","i","arg","isCoupled","push","decoupledArr","split","map","c","print","_len","arguments","messages","Array","_key","process","stdout","write","join","println","_len2","_key2","filter","Boolean","console","log","ln","count","repeat","indent","addIndentLn","message","concat","_len3","_key3"],"sourceRoot":"../../src","sources":["utils.ts"],"sourcesContent":["import assert from \"node:assert\";\nimport { z } from \"zod\";\n\n/**\n * @param name - Should start with `'--'`\n * @returns - The transformed name E.g. `--input-dir` -> `InputDir`\n */\nexport function transformArg(name: string): string {\n assert(name.startsWith(\"-\"), `[transformArg] Invalid arg name: ${name}`);\n name = name.startsWith(\"--\") ? name.substring(2) : name.substring(1);\n return name.replace(/-([a-z])/g, g => g[1].toUpperCase());\n}\n\n/** - Reverse of `transformArg`. E.g. `InputDir` -> `--input-dir` , `i` -> `-i` */\nexport function transformOptionToArg(name: string): string {\n name = name.replace(/^[A-Z]/g, g => g.toLowerCase()); // first letter always lower case\n if (name.length === 1) return `-${name}`;\n return `--${name.replace(/[A-Z]/g, g => \"-\" + g.toLowerCase())}`;\n}\n\n/** - Check if an arg string is a short arg. E.g. `-i` -> `true` */\nexport function isFlagArg(name: string): boolean {\n return /^-[a-z]$/.test(name);\n}\n\n/** - Check if an arg string is an options arg. E.g. `--input-dir` -> `true` , `-i` -> `true` */\nexport function isOptionArg(name: string | boolean): boolean {\n if (typeof name !== \"string\") return false;\n return isFlagArg(name) || name.startsWith(\"--\");\n}\n\n/**\n * - Transform option name to no name. E.g. `include` -> `noInclude`\n * - For short name like `-i` it will be ignored\n */\nexport function noName(name: string): string {\n if (name.length === 1) return name;\n return \"no\" + name.replace(/^[a-z]/, g => g.toUpperCase());\n}\n\n/** - Convert string to boolean. E.g. `\"true\"` -> `true` , `\"false\"` -> `false` */\nexport function stringToBoolean(str: string): boolean {\n if (str.toLowerCase() === \"true\") return true;\n if (str.toLowerCase() === \"false\") return false;\n throw new Error(`[stringToBoolean] Invalid boolean value: \"${str}\"; Expected \"true\" or \"false\"`);\n}\n\nexport function getOrdinalPlacement(index: number): string {\n if (index < 0) return \"\";\n\n const suffixes = [\"th\", \"st\", \"nd\", \"rd\"];\n const lastDigit = index % 10;\n const lastTwoDigits = index % 100;\n\n const suffix =\n lastDigit === 1 && lastTwoDigits !== 11\n ? suffixes[1]\n : lastDigit === 2 && lastTwoDigits !== 12\n ? suffixes[2]\n : lastDigit === 3 && lastTwoDigits !== 13\n ? suffixes[3]\n : suffixes[0];\n\n return `${index + 1}${suffix}`;\n}\n\n/** - Check if a schema is a boolean */\nexport function isBooleanSchema(schema: z.ZodTypeAny): boolean {\n let type = schema;\n while (type) {\n if (type instanceof z.ZodBoolean) {\n return true;\n }\n\n if (type instanceof z.ZodLiteral) {\n return type.value === true || type.value === false;\n }\n\n type = type._def.innerType;\n }\n\n return false;\n}\n\nexport function getDefaultValueFromSchema(schema: z.ZodTypeAny): unknown | undefined {\n let type = schema;\n while (type) {\n if (type instanceof z.ZodDefault) {\n const defaultValue = type._def.defaultValue();\n return defaultValue;\n }\n\n type = type._def.innerType;\n }\n\n return undefined;\n}\n\n/** - Decouple flags E.g. `-rf` -> `-r, -f` */\nexport function decoupleFlags(args: string[]): string[] {\n const flagsRe = /^-[a-z]{2,}$/i;\n\n const result = [];\n for (let i = 0; i < args.length; i++) {\n const arg = args[i];\n const isCoupled = flagsRe.test(arg);\n\n if (!isCoupled) {\n result.push(arg);\n continue;\n }\n\n const decoupledArr = arg\n .substring(1)\n .split(\"\")\n .map(c => \"-\" + c);\n\n result.push(...decoupledArr);\n }\n\n return result;\n}\n\n/** Print */\nexport function print(...messages: string[]) {\n return process.stdout.write(messages.join(\" \"));\n}\n\n/** Print line */\nexport function println(...messages: string[]) {\n messages = messages.filter(Boolean);\n return console.log(...messages);\n}\n\n/** New line */\nexport function ln(count: number) {\n return \"\\n\".repeat(count);\n}\n\n/** Space */\nexport function indent(count: number) {\n return \" \".repeat(count);\n}\n\n/** Add indent before each new line */\nexport function addIndentLn(message: string, indent: string = \"\") {\n return message.replace(/\\n/g, `\\n${indent}`);\n}\n\n/** Concat strings */\nexport function concat(...messages: string[]) {\n messages = messages.filter(Boolean);\n return messages.join(\" \");\n}\n"],"mappings":"klBAAA,IAAAA,WAAA,CAAAC,sBAAA,CAAAC,OAAA,iBACA,IAAAC,IAAA,CAAAD,OAAA,QAAwB,SAAAD,uBAAAG,CAAA,SAAAA,CAAA,EAAAA,CAAA,CAAAC,UAAA,CAAAD,CAAA,EAAAE,OAAA,CAAAF,CAAA,GAMjB,QAAS,CAAAG,YAAYA,CAACC,IAAY,CAAU,CACjD,GAAAC,mBAAM,EAACD,IAAI,CAACE,UAAU,CAAC,GAAG,CAAC,CAAE,oCAAoCF,IAAI,EAAE,CAAC,CACxEA,IAAI,CAAGA,IAAI,CAACE,UAAU,CAAC,IAAI,CAAC,CAAGF,IAAI,CAACG,SAAS,CAAC,CAAC,CAAC,CAAGH,IAAI,CAACG,SAAS,CAAC,CAAC,CAAC,CACpE,MAAO,CAAAH,IAAI,CAACI,OAAO,CAAC,WAAW,CAAEC,CAAC,EAAIA,CAAC,CAAC,CAAC,CAAC,CAACC,WAAW,CAAC,CAAC,CAAC,CAC3D,CAGO,QAAS,CAAAC,oBAAoBA,CAACP,IAAY,CAAU,CACzDA,IAAI,CAAGA,IAAI,CAACI,OAAO,CAAC,SAAS,CAAEC,CAAC,EAAIA,CAAC,CAACG,WAAW,CAAC,CAAC,CAAC,CACpD,GAAIR,IAAI,CAACS,MAAM,GAAK,CAAC,CAAE,MAAO,IAAIT,IAAI,EAAE,CACxC,MAAO,KAAKA,IAAI,CAACI,OAAO,CAAC,QAAQ,CAAEC,CAAC,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jC,CAGO,QAAS,CAAAc,EAAEA,CAACC,KAAa,CAAE,CAChC,MAAO,IAAI,CAACC,MAAM,CAACD,KAAK,CAAC,CAC3B,CAGO,QAAS,CAAAE,MAAMA,CAACF,KAAa,CAAE,CACpC,MAAO,GAAG,CAACC,MAAM,CAACD,KAAK,CAAC,CAC1B,CAGO,QAAS,CAAAG,WAAWA,CAACC,OAAe,CAAuB,IAArB,CAAAF,MAAc,CAAAlB,SAAA,CAAAzC,MAAA,IAAAyC,SAAA,MAAAf,SAAA,CAAAe,SAAA,IAAG,EAAE,CAC9D,MAAO,CAAAoB,OAAO,CAAClE,OAAO,CAAC,KAAK,CAAE,KAAKgE,MAAM,EAAE,CAAC,CAC9C,CAGO,QAAS,CAAAG,MAAMA,CAAA,CAAwB,SAAAC,KAAA,CAAAtB,SAAA,CAAAzC,MAAA,CAApB0C,QAAQ,KAAAC,KAAA,CAAAoB,KAAA,EAAAC,KAAA,GAAAA,KAAA,CAAAD,KAAA,CAAAC,KAAA,IAARtB,QAAQ,CAAAsB,KAAA,EAAAvB,SAAA,CAAAuB,KAAA,GAChCtB,QAAQ,CAAGA,QAAQ,CAACU,MAAM,CAACC,OAAO,CAAC,CACnC,MAAO,CAAAX,QAAQ,CAACM,IAAI,CAAC,GAAG,CAAC,CAC3B","ignoreList":[]}
|
|
@@ -0,0 +1 @@
|
|
|
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.italic,command:chalk.yellow,option:chalk.cyan,argument:chalk.green,placeholder:chalk.hex("#FF9800"),punctuation:chalk.white.dim};function printCliHelp(params){let printOptions=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};printOptions.colors??=true;const noColors=new Proxy(colors,{get:()=>{return function(){for(var _len=arguments.length,str=new Array(_len),_key=0;_key<_len;_key++){str[_key]=arguments[_key];}return 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){let printOptions=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};let cliName=arguments.length>2&&arguments[2]!==undefined?arguments[2]:"";printOptions.colors??=true;const noColors=new Proxy(colors,{get:()=>{return function(){for(var _len2=arguments.length,str=new Array(_len2),_key2=0;_key2<_len2;_key2++){str[_key2]=arguments[_key2];}return 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=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));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};
|
|
@@ -0,0 +1 @@
|
|
|
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","arguments","length","undefined","noColors","Proxy","get","_len","str","Array","_key","join","c","customColors","Object","assign","isFirstParamCli","cliOptions","shift","subcommands","printTitle","toUpperCase","cliName","usage","options","allowPositional","longest","optionsToPrint","longestOptionIndent","prepareOptionsToPrint","commandsToPrint","longestSubcommandIndent","prepareCommandsToPrint","argsToPrint","longestArgIndent","prepareArgumentsToPrint","printPreparedOptions","printPreparedCommands","printPreparedArguments","normalizeExample","replace","printSubcommandHelp","subcommand","_len2","_key2","name","normalizeDesc","nameWithAliases","aliases","names","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\n/** Colors */\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.italic,\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 = 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));\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,KAAK,KAAM,OAAO,CACzB,OAASC,MAAM,CAAEC,yBAAyB,CAAEC,MAAM,CAAEC,EAAE,CAAEC,KAAK,CAAEC,OAAO,CAAEC,oBAAoB,KAAQ,YAAY,CAKhH,KAAM,CAAAC,MAA2D,CAAG,CAClEC,KAAK,CAAET,KAAK,CAACU,IAAI,CAACC,IAAI,CACtBC,WAAW,CAAEZ,KAAK,CAACa,KAAK,CACxBC,OAAO,CAAEd,KAAK,CAACe,GAAG,CAACC,MAAM,CACzBC,QAAQ,CAAEjB,KAAK,CAACe,GAAG,CAACC,MAAM,CAC1BE,YAAY,CAAElB,KAAK,CAACmB,MAAM,CAC1BC,OAAO,CAAEpB,KAAK,CAACe,GAAG,CAACC,MAAM,CACzBK,OAAO,CAAErB,KAAK,CAACmB,MAAM,CACrBG,MAAM,CAAEtB,KAAK,CAACuB,IAAI,CAClBC,QAAQ,CAAExB,KAAK,CAACyB,KAAK,CACrBC,WAAW,CAAE1B,KAAK,CAAC2B,GAAG,CAAC,SAAS,CAAC,CACjCC,WAAW,CAAE5B,KAAK,CAACa,KAAK,CAACE,GAC3B,CAAC,CAWD,QAAS,CAAAc,YAAYA,CAACC,MAA8B,CAAmC,IAAjC,CAAAC,YAA0B,CAAAC,SAAA,CAAAC,MAAA,IAAAD,SAAA,MAAAE,SAAA,CAAAF,SAAA,IAAG,CAAC,CAAC,CACnFD,YAAY,CAACvB,MAAM,GAAK,IAAI,CAE5B,KAAM,CAAA2B,QAAQ,CAAG,GAAI,CAAAC,KAAK,CAAC5B,MAAM,CAAE,CACjC6B,GAAG,CAAEA,CAAA,GAAM,CACT,MAAO,oBAAAC,IAAA,CAAAN,SAAA,CAAAC,MAAA,CAAIM,GAAG,KAAAC,K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AAC,CACTwC,CAAC,CAACnB,QAAQ,CAACwD,KAAK,CAAC,CACjB7E,MAAM,CAAC4F,OAAO,CAAC,CACfpD,CAAC,CAAC/B,WAAW,CAACiE,aAAa,CAAC,CAC5BiB,GAAG,CAAGnD,CAAC,CAAC7B,OAAO,CAACgF,GAAG,CAAC,CAAGnD,CAAC,CAAC1B,QAAQ,CAACA,QAAQ,CAC5C,CAAC,CAED,GAAIG,OAAO,CAAE,CACX,KAAM,CAAAkD,gBAAgB,CAAGlD,OAAO,CAACmD,OAAO,CAAC,KAAK,CAAE,IAAI,CAAGpE,MAAM,CAACsD,OAAO,CAAG,EAAE,CAAC,CAAC,CAC5EnD,OAAO,CAACH,MAAM,CAACsD,OAAO,CAAG,CAAC,CAAC,CAAEd,CAAC,CAACf,WAAW,CAAC,GAAG,CAAC,CAAGe,CAAC,CAACzB,YAAY,CAAC,UAAU,CAAC,CAAEyB,CAAC,CAACvB,OAAO,CAACkD,gBAAgB,CAAC,CAAC,CAC5G,CACF,CAEAhE,OAAO,CAAC,CAAC,CACX,CAEA,MAAO,MAAM,CAAA4F,IAAI,CAAG,CAClBrE,YAAY,CACZ2C,mBACF,CAAC","ignoreList":[]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{help}from"./help.js";import{parse,safeParse}from"./parser.js";function createSubcommand(input){return Object.assign(input,{setAction:action=>input.action=action});}function createCli(input){return Object.assign(input,{setAction:action=>input.action=action});}const{printCliHelp,printSubcommandHelp}=help;export{createCli,createSubcommand,parse,printCliHelp,printSubcommandHelp,safeParse};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"names":["help","parse","safeParse","createSubcommand","input","Object","assign","setAction","action","createCli","printCliHelp","printSubcommandHelp"],"sourceRoot":"../../src","sources":["index.ts"],"sourcesContent":["import { help } from \"./help.js\";\nimport { parse, safeParse } from \"./parser.js\";\n\nimport type { ActionFn, Cli, Prettify, Subcommand, UnSafeParseResult } from \"./types.js\";\n\nfunction createSubcommand<const T extends Subcommand>(input: T & Subcommand): Prettify<T & ActionFn<T>> {\n return Object.assign(input, {\n setAction: (action: (res: UnSafeParseResult<[T]>) => void) => (input.action = action),\n });\n}\n\nfunction createCli<const T extends Cli>(input: T & Cli): Prettify<T & ActionFn<T>> {\n return Object.assign(input, {\n setAction: (action: (res: UnSafeParseResult<[T]>) => void) => (input.action = action),\n });\n}\n\nconst { printCliHelp, printSubcommandHelp } = help;\n\nexport { createCli, createSubcommand, parse, printCliHelp, printSubcommandHelp, safeParse };\n\nexport type * from \"./types.js\";\n"],"mappings":"AAAA,OAASA,IAAI,KAAQ,WAAW,CAChC,OAASC,KAAK,CAAEC,SAAS,KAAQ,aAAa,CAI9C,QAAS,CAAAC,gBAAgBA,CAA6BC,KAAqB,CAA6B,CACtG,MAAO,CAAAC,MAAM,CAACC,MAAM,CAACF,KAAK,CAAE,CAC1BG,SAAS,CAAGC,MAA6C,EAAMJ,KAAK,CAACI,MAAM,CAAGA,MAChF,CAAC,CAAC,CACJ,CAEA,QAAS,CAAAC,SAASA,CAAsBL,KAAc,CAA6B,CACjF,MAAO,CAAAC,MAAM,CAACC,MAAM,CAACF,KAAK,CAAE,CAC1BG,SAAS,CAAGC,MAA6C,EAAMJ,KAAK,CAACI,MAAM,CAAGA,MAChF,CAAC,CAAC,CACJ,CAEA,KAAM,CAAEE,YAAY,CAAEC,mBAAoB,CAAC,CAAGX,IAAI,CAElD,OAASS,SAAS,CAAEN,gBAAgB,CAAEF,KAAK,CAAES,YAAY,CAAEC,mBAAmB,CAAET,SAAS","ignoreList":[]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{help}from"./help.js";import{decoupleFlags,getOrdinalPlacement,isBooleanSchema,isFlagArg,isOptionArg,noName,stringToBoolean,transformArg,transformOptionToArg}from"./utils.js";export function parse(argsv){for(var _len=arguments.length,params=new Array(_len>1?_len-1:0),_key=1;_key<_len;_key++){params[_key-1]=arguments[_key];}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=>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);}};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=subcommandArr.find(c=>c.name===results.subcommand);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=subcommandArr.find(c=>c.name===results.subcommand);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);if(optionName in results)throw new Error(`Duplicate option: "${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}"`);}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=subcommandArr.find(c=>c.name===results.subcommand);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=subcommandArr.find(c=>c.name===results.subcommand);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){for(var _len2=arguments.length,params=new Array(_len2>1?_len2-1:0),_key2=1;_key2<_len2;_key2++){params[_key2-1]=arguments[_key2];}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};}}
|