@clerc/plugin-help 1.0.3 → 1.1.1

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 CHANGED
@@ -2,23 +2,9 @@
2
2
 
3
3
  [![NPM version](https://img.shields.io/npm/v/@clerc/plugin-help?color=a1b858&label=)](https://www.npmjs.com/package/@clerc/plugin-help)
4
4
 
5
- Clerc plugin to add help command to your cli.
5
+ ## Documenation
6
6
 
7
- ## 📦 Installation
8
-
9
- ```bash
10
- $ npm install @clerc/plugin-help
11
- $ yarn add @clerc/plugin-help
12
- $ pnpm add @clerc/plugin-help
13
- ```
14
-
15
- ## 🚀 Usage
16
-
17
- ```ts
18
- import { helpPlugin } from "@clerc/plugin-help";
19
-
20
- cli.use(helpPlugin());
21
- ```
7
+ Read the [documentation](https://clerc.so1ve.dev/official-plugins/plugin-help.html) for more details.
22
8
 
23
9
  ## 📝 License
24
10
 
@@ -7,9 +7,9 @@ interface Formatters {
7
7
  formatFlagDefault: <T>(value: FlagDefaultValue<T>) => string;
8
8
  }
9
9
  /**
10
- * A group definition as a tuple of [key, displayName].
11
- * The key is used in help options to assign items to groups.
12
- * The displayName is shown in the help output.
10
+ * A group definition as a tuple of [key, displayName]. The key is used in help
11
+ * options to assign items to groups. The displayName is shown in the help
12
+ * output.
13
13
  */
14
14
  type GroupDefinition = [key: string, name: string];
15
15
  /**
@@ -17,18 +17,15 @@ type GroupDefinition = [key: string, name: string];
17
17
  */
18
18
  interface GroupsOptions {
19
19
  /**
20
- * Groups for commands.
21
- * Each group is defined as `[key, name]`.
20
+ * Groups for commands. Each group is defined as `[key, name]`.
22
21
  */
23
22
  commands?: GroupDefinition[];
24
23
  /**
25
- * Groups for command-specific flags.
26
- * Each group is defined as `[key, name]`.
24
+ * Groups for command-specific flags. Each group is defined as `[key, name]`.
27
25
  */
28
26
  flags?: GroupDefinition[];
29
27
  /**
30
- * Groups for global flags.
31
- * Each group is defined as `[key, name]`.
28
+ * Groups for global flags. Each group is defined as `[key, name]`.
32
29
  */
33
30
  globalFlags?: GroupDefinition[];
34
31
  }
@@ -39,8 +36,8 @@ declare const defaultFormatters: Formatters;
39
36
  //#region src/index.d.ts
40
37
  interface HelpOptions {
41
38
  /**
42
- * The group this item belongs to.
43
- * The group must be defined in the `groups` option of `helpPlugin()`.
39
+ * The group this item belongs to. The group must be defined in the `groups`
40
+ * option of `helpPlugin()`.
44
41
  */
45
42
  group?: string;
46
43
  }
@@ -56,8 +53,8 @@ interface CommandHelpOptions extends HelpOptions {
56
53
  */
57
54
  notes?: string[];
58
55
  /**
59
- * Examples to show in the help output.
60
- * Each example is a tuple of `[command, description]`.
56
+ * Examples to show in the help output. Each example is a tuple of `[command,
57
+ * description]`.
61
58
  */
62
59
  examples?: [string, string][];
63
60
  }
@@ -99,8 +96,8 @@ interface HelpPluginOptions {
99
96
  */
100
97
  notes?: string[];
101
98
  /**
102
- * Examples to show in the help output.
103
- * Each example is a tuple of `[command, description]`.
99
+ * Examples to show in the help output. Each example is a tuple of `[command,
100
+ * description]`.
104
101
  */
105
102
  examples?: [string, string][];
106
103
  /**
@@ -116,10 +113,10 @@ interface HelpPluginOptions {
116
113
  */
117
114
  formatters?: Partial<Formatters>;
118
115
  /**
119
- * Group definitions for commands and flags.
120
- * Groups allow organizing commands and flags into logical sections in help output.
121
- * Each group is defined as `[key, name]` where `key` is the identifier used in help options
122
- * and `name` is the display name shown in help output.
116
+ * Group definitions for commands and flags. Groups allow organizing commands
117
+ * and flags into logical sections in help output. Each group is defined as
118
+ * `[key, name]` where `key` is the identifier used in help options and `name`
119
+ * is the display name shown in help output.
123
120
  */
124
121
  groups?: GroupsOptions;
125
122
  }
package/dist/index.mjs ADDED
@@ -0,0 +1,8 @@
1
+ import{DOUBLE_DASH as e,NoSuchCommandError as t,definePlugin as n,normalizeFlagValue as r,normalizeParameterValue as i,resolveCommand as a}from"@clerc/core";import{formatFlagName as o,formatVersion as s,isTruthy as c,objectIsEmpty as l,toArray as u}from"@clerc/utils";import*as d from"@uttr/tint";import f from"string-width";import p from"text-table";function m(e){if(typeof e==`function`)return e.display??e.name;let t=e[0];return`Array<${t.displayName??t.name}>`}function h(e){return typeof e==`function`&&`display`in e&&e.display?e.display:String(e)}function g(e){return e===``?`(root)`:e}const _={formatTypeValue:m,formatFlagDefault:h},v=`default`,y=e=>p(e,{stringLength:f}),b=e=>y(e).split(`
2
+ `),x=` `.repeat(2),S=e=>`${x}${e}`;function C(e){let t=new Map;if(e)for(let[n,r]of e)t.set(n,r);return t}function w(e,t,n,r){if(e&&e!==v&&!t.has(e))throw Error(`Unknown ${n} group "${e}" for "${r}". Available groups: ${[...t.keys()].join(`, `)||`(none)`}`)}var T=class{_command;get _commandGroups(){return C(this._getGroups().commands)}get _flagGroups(){return C(this._getGroups().flags)}get _globalFlagGroups(){return C(this._getGroups().globalFlags)}constructor(e,t,n,r,i,a){this._formatters=e,this._cli=t,this._globalFlags=n,this._getGroups=r,this._examples=i,this._notes=a}setCommand(e){e&&(this._command=e,this._examples=e?.help?.examples,this._notes=e?.help?.notes)}renderSections(e){return e.filter(c).map(e=>{let t=Array.isArray(e.body)?e.body.filter(e=>e!==void 0).join(`
3
+ `):e.body;return e.title?`${d.underline.bold(e.title)}\n${t.split(`
4
+ `).map(S).join(`
5
+ `)}`:t}).join(`
6
+
7
+ `)}render(){let e=[this.renderHeader(),this.renderUsage(),this.renderParameters(),this.renderCommandFlags(),this.renderGlobalFlags(),this.renderCommands(),this.renderExamples(),this.renderNotes()];return this.renderSections(e)}renderHeader(){let{_scriptName:e,_version:t,_description:n}=this._cli,r=this._command,i=r?r.description:n,a=`${!r||r.name===``?d.bold(e):d.dim(e)}${r?.name?` ${d.bold(r.name)}`:``}${r?``:` ${s(t)}`}`,o=r?.alias?`Alias${u(r.alias).length>1?`es`:``}: ${u(r.alias).map(e=>d.bold(e)).join(`, `)}`:void 0;return{body:[`${a}${i?` - ${i}`:``}`,o]}}renderUsage(){let{_scriptName:t}=this._cli,n=this._command,r=`$ ${t}`;if(n){if(n.name&&(r+=` ${n.name}`),n.parameters){let t=n.parameters.indexOf(e),i=t!==-1&&n.parameters.slice(t+1).some(e=>(typeof e==`string`?e:e.key).startsWith(`<`)),a=n.parameters.map(t=>{let n=typeof t==`string`?t:t.key;return t===e&&(n=i?e:`[${e}]`),n});r+=` ${a.join(` `)}`}}else this._cli._commands.size>0&&(!this._cli._commands.has(``)||this._cli._commands.size!==1)&&(r+=this._cli._commands.has(``)?` ${d.dim(`[command]`)}`:` ${d.dim(`<command>`)}`);return(n?.flags&&!l(n.flags)||!l(this._globalFlags))&&(r+=` ${d.dim(`[flags]`)}`),{title:`Usage`,body:[r]}}renderParameters(){let t=this._command;if(!(!t?.parameters||t.parameters.length===0))return{title:`Parameters`,body:b(t.parameters.filter(t=>t!==e).map(i).map(({key:e,type:t,description:n})=>{let r=t?this._formatters.formatTypeValue(t):`string`;return[d.bold(e),d.dim(r),n].filter(c)}))}}getSubcommands(e){let t=new Map;if(e===``)return t;let n=`${e} `;for(let[e,r]of this._cli._commands)if(e.startsWith(n)){let i=e.slice(n.length);t.set(i,r)}return t}buildGroupedCommandsBody(e,t){let n=new Map,r=[],i=[];for(let a of e.values()){if(a.__isAlias||a.help?.show===!1)continue;let e=a.help?.group;w(e,this._commandGroups,`command`,a.name);let o=[`${d.bold(g(a.name.slice(t.length)))}${a.alias?` (${u(a.alias).join(`, `)})`:``}`,a.description].filter(c);if(a.name===``)i=o;else if(e&&e!==v){let t=n.get(e)??[];t.push(o),n.set(e,t)}else r.push(o)}let a=[],o=[];i.length>0&&o.push(i),r.length>0&&o.push(...r),o.length>0&&a.push(...b(o));for(let[e,t]of this._commandGroups){let r=n.get(e);r&&r.length>0&&(a.length>0&&a.push(``),a.push(`${d.dim(t)}`),a.push(...b(r).map(S)))}return a}renderAvailableSubcommands(e){let t=this.getSubcommands(e);if(t.size===0)return null;let n=`${e} `,r=this.buildGroupedCommandsBody(t,n);if(r.length===0)return null;let i=[{body:`${this._cli._scriptName} ${d.bold(e)} not found`},{title:`Available Subcommands`,body:r}];return this.renderSections(i)}renderCommands(){let e=this._cli._commands,t,n=`Commands`,r=``;if(this._command){if(r=this._command.name?`${this._command.name} `:``,n=`Subcommands`,t=this.getSubcommands(this._command.name),t.size===0)return}else t=e;if(t.size===0)return;let i=this.buildGroupedCommandsBody(t,r);return{title:n,body:i}}renderFlagItem(e,t){t=r(t);let n=o(e);t.short&&(n+=`, ${o(t.short)}`);let i=this._formatters.formatTypeValue(t.type),a=t.default!==void 0&&d.dim(`[default: ${d.bold(this._formatters.formatFlagDefault(t.default))}]`);return[d.bold(n),d.dim(i),t.description,a].filter(c)}renderGroupedFlags(e,t,n){let r=new Map,i=[];for(let[a,o]of Object.entries(e)){let e=o.help?.group;w(e,t,n,a);let s=this.renderFlagItem(a,o);if(e&&e!==v){let t=r.get(e)??[];t.push(s),r.set(e,t)}else i.push(s)}let a=[];i.length>0&&a.push(...b(i));for(let[e,n]of t){let t=r.get(e);t&&t.length>0&&(a.length>0&&a.push(``),a.push(`${d.dim(n)}`),a.push(...b(t).map(S)))}return a}renderCommandFlags(){let e=this._command;if(!(!e?.flags||l(e.flags)))return{title:`Flags`,body:this.renderGroupedFlags(e.flags,this._flagGroups,`flag`)}}renderGlobalFlags(){if(!(!this._globalFlags||l(this._globalFlags)))return{title:`Global Flags`,body:this.renderGroupedFlags(this._globalFlags,this._globalFlagGroups,`global flag`)}}renderNotes(){if(this._notes?.length)return{title:`Notes`,body:this._notes}}renderExamples(){if(this._examples?.length)return{title:`Examples`,body:b(this._examples.map(([e,t])=>[e,`-`,t]))}}};function E(e,{groups:t}){e.store.help={addGroup:e=>{e.commands&&(t.commands=[...t.commands??[],...e.commands]),e.flags&&(t.flags=[...t.flags??[],...e.flags]),e.globalFlags&&(t.globalFlags=[...t.globalFlags??[],...e.globalFlags])}}}const D=({command:e=!0,flag:r=!0,showHelpWhenNoCommandSpecified:i=!0,notes:o,examples:s,header:l,footer:u,formatters:d,groups:f={}}={})=>n({setup:n=>{E(n,{groups:f});let p={..._,...d};function m(e){l&&console.log(l),console.log(e),u&&console.log(u)}let h=new T(p,n,n._globalFlags,()=>f,s,o);function g(e){let t=h.renderAvailableSubcommands(e);return t?(m(t),!0):!1}e&&n.command(`help`,`Show help`,{parameters:[`[command...]`],help:{notes:[`If no command is specified, show help for the CLI.`,`If a command is specified, show help for the command.`,r&&`-h is an alias for --help.`].filter(c),examples:[e&&[`$ ${n._scriptName} help`,`Show help`],e&&[`$ ${n._scriptName} help <command>`,`Show help for a specific command`],r&&[`$ ${n._scriptName} <command> --help`,`Show help for a specific command`]].filter(c)}}).on(`help`,e=>{let r=e.parameters.command,i;if(r.length>0&&([i]=a(n._commands,r),!i)){let e=r.join(` `);if(g(e))return;throw new t(e)}h.setCommand(i),m(h.render())}),r&&n.globalFlag(`help`,`Show help`,{short:`h`,type:Boolean,default:!1}),n.interceptor({enforce:`post`,handler:async(e,t)=>{if(e.flags.help){let n=e.command;if(!n&&e.rawParsed.parameters.length>0){if(g(e.rawParsed.parameters.join(` `)))return;await t()}h.setCommand(n),m(h.render())}else i&&!e.command&&e.rawParsed.parameters.length===0?(console.log(`No command specified. Showing help:
8
+ `),m(h.render())):await t()}})}});export{_ as defaultFormatters,D as helpPlugin};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@clerc/plugin-help",
3
- "version": "1.0.3",
3
+ "version": "1.1.1",
4
4
  "author": "Ray <i@mk1.io> (https://github.com/so1ve)",
5
5
  "type": "module",
6
6
  "description": "Clerc plugin help",
@@ -25,19 +25,12 @@
25
25
  "license": "MIT",
26
26
  "sideEffects": false,
27
27
  "exports": {
28
- ".": "./dist/index.js"
29
- },
30
- "main": "./dist/index.js",
31
- "module": "./dist/index.js",
32
- "types": "dist/index.d.ts",
33
- "typesVersions": {
34
- "*": {
35
- "*": [
36
- "./dist/*",
37
- "./dist/index.d.ts"
38
- ]
39
- }
28
+ ".": "./dist/index.mjs",
29
+ "./package.json": "./package.json"
40
30
  },
31
+ "main": "./dist/index.mjs",
32
+ "module": "./dist/index.mjs",
33
+ "types": "./dist/index.d.mts",
41
34
  "files": [
42
35
  "dist"
43
36
  ],
@@ -48,13 +41,13 @@
48
41
  "@uttr/tint": "^0.1.3",
49
42
  "string-width": "^8.1.0",
50
43
  "text-table": "^0.2.0",
51
- "@clerc/utils": "1.0.3"
44
+ "@clerc/utils": "1.1.1"
52
45
  },
53
46
  "devDependencies": {
54
47
  "@types/text-table": "^0.2.5",
55
48
  "kons": "^0.7.1",
56
- "@clerc/core": "1.0.3",
57
- "@clerc/parser": "1.0.3"
49
+ "@clerc/core": "1.1.1",
50
+ "@clerc/parser": "1.1.1"
58
51
  },
59
52
  "peerDependencies": {
60
53
  "@clerc/core": "*"
package/dist/index.js DELETED
@@ -1,370 +0,0 @@
1
- import { DOUBLE_DASH, NoSuchCommandError, definePlugin, normalizeFlagValue, normalizeParameterValue, resolveCommand } from "@clerc/core";
2
- import { formatFlagName, formatVersion, isTruthy, objectIsEmpty, toArray } from "@clerc/utils";
3
- import * as tint from "@uttr/tint";
4
- import stringWidth from "string-width";
5
- import textTable from "text-table";
6
-
7
- //#region src/utils.ts
8
- function formatTypeValue(type) {
9
- if (typeof type === "function") return type.display ?? type.name;
10
- const innerType = type[0];
11
- return `Array<${innerType.displayName ?? innerType.name}>`;
12
- }
13
- function formatFlagDefault(value) {
14
- if (typeof value === "function" && "display" in value && value.display) return value.display;
15
- return String(value);
16
- }
17
- function formatCommandName(name) {
18
- if (name === "") return "(root)";
19
- return name;
20
- }
21
-
22
- //#endregion
23
- //#region src/formatters.ts
24
- const defaultFormatters = {
25
- formatTypeValue,
26
- formatFlagDefault
27
- };
28
-
29
- //#endregion
30
- //#region src/renderer.ts
31
- const DEFAULT_GROUP_KEY = "default";
32
- const table = (items) => textTable(items, { stringLength: stringWidth });
33
- const splitTable = (items) => table(items).split("\n");
34
- const DELIMITER = "-";
35
- const INDENT = " ".repeat(2);
36
- const withIndent = (str) => `${INDENT}${str}`;
37
- function groupDefinitionsToMap(definitions) {
38
- const map = /* @__PURE__ */ new Map();
39
- if (definitions) for (const [key, name] of definitions) map.set(key, name);
40
- return map;
41
- }
42
- function validateGroup(group, groupMap, itemType, itemName) {
43
- if (group && group !== DEFAULT_GROUP_KEY && !groupMap.has(group)) throw new Error(`Unknown ${itemType} group "${group}" for "${itemName}". Available groups: ${[...groupMap.keys()].join(", ") || "(none)"}`);
44
- }
45
- var HelpRenderer = class {
46
- _command;
47
- get _commandGroups() {
48
- return groupDefinitionsToMap(this._getGroups().commands);
49
- }
50
- get _flagGroups() {
51
- return groupDefinitionsToMap(this._getGroups().flags);
52
- }
53
- get _globalFlagGroups() {
54
- return groupDefinitionsToMap(this._getGroups().globalFlags);
55
- }
56
- constructor(_formatters, _cli, _globalFlags, _getGroups, _examples, _notes) {
57
- this._formatters = _formatters;
58
- this._cli = _cli;
59
- this._globalFlags = _globalFlags;
60
- this._getGroups = _getGroups;
61
- this._examples = _examples;
62
- this._notes = _notes;
63
- }
64
- setCommand(command) {
65
- if (command) {
66
- this._command = command;
67
- this._examples = command?.help?.examples;
68
- this._notes = command?.help?.notes;
69
- }
70
- }
71
- renderSections(sections) {
72
- return sections.filter(isTruthy).map((section) => {
73
- const body = Array.isArray(section.body) ? section.body.filter((s) => s !== void 0).join("\n") : section.body;
74
- if (!section.title) return body;
75
- return `${tint.underline.bold(section.title)}\n${body.split("\n").map(withIndent).join("\n")}`;
76
- }).join("\n\n");
77
- }
78
- render() {
79
- const sections = [
80
- this.renderHeader(),
81
- this.renderUsage(),
82
- this.renderParameters(),
83
- this.renderCommandFlags(),
84
- this.renderGlobalFlags(),
85
- this.renderCommands(),
86
- this.renderExamples(),
87
- this.renderNotes()
88
- ];
89
- return this.renderSections(sections);
90
- }
91
- renderHeader() {
92
- const { _scriptName, _version, _description } = this._cli;
93
- const command = this._command;
94
- const description = command ? command.description : _description;
95
- const headerLine = `${!command || command.name === "" ? tint.bold(_scriptName) : tint.dim(_scriptName)}${command?.name ? ` ${tint.bold(command.name)}` : ""}${command ? "" : ` ${formatVersion(_version)}`}`;
96
- const alias = command?.alias ? `Alias${toArray(command.alias).length > 1 ? "es" : ""}: ${toArray(command.alias).map((a) => tint.bold(a)).join(", ")}` : void 0;
97
- return { body: [`${headerLine}${description ? ` ${DELIMITER} ${description}` : ""}`, alias] };
98
- }
99
- renderUsage() {
100
- const { _scriptName } = this._cli;
101
- const command = this._command;
102
- let usage = `$ ${_scriptName}`;
103
- if (command) {
104
- if (command.name) usage += ` ${command.name}`;
105
- if (command.parameters) {
106
- const doubleDashIndex = command.parameters.indexOf(DOUBLE_DASH);
107
- const hasRequiredAfterDoubleDash = doubleDashIndex !== -1 && command.parameters.slice(doubleDashIndex + 1).some((parameter) => {
108
- return (typeof parameter === "string" ? parameter : parameter.key).startsWith("<");
109
- });
110
- const items = command.parameters.map((parameter) => {
111
- let key = typeof parameter === "string" ? parameter : parameter.key;
112
- if (parameter === DOUBLE_DASH) key = hasRequiredAfterDoubleDash ? DOUBLE_DASH : `[${DOUBLE_DASH}]`;
113
- return key;
114
- });
115
- usage += ` ${items.join(" ")}`;
116
- }
117
- } else if (this._cli._commands.size > 0 && !(this._cli._commands.has("") && this._cli._commands.size === 1)) usage += this._cli._commands.has("") ? ` ${tint.dim("[command]")}` : ` ${tint.dim("<command>")}`;
118
- if (command?.flags && !objectIsEmpty(command.flags) || !objectIsEmpty(this._globalFlags)) usage += ` ${tint.dim("[flags]")}`;
119
- return {
120
- title: "Usage",
121
- body: [usage]
122
- };
123
- }
124
- renderParameters() {
125
- const command = this._command;
126
- if (!command?.parameters || command.parameters.length === 0) return;
127
- return {
128
- title: "Parameters",
129
- body: splitTable(command.parameters.filter((parameter) => parameter !== DOUBLE_DASH).map(normalizeParameterValue).map(({ key, type, description }) => {
130
- const formattedType = type ? this._formatters.formatTypeValue(type) : "string";
131
- return [
132
- tint.bold(key),
133
- tint.dim(formattedType),
134
- description
135
- ].filter(isTruthy);
136
- }))
137
- };
138
- }
139
- getSubcommands(parentCommandName) {
140
- const subcommands = /* @__PURE__ */ new Map();
141
- if (parentCommandName === "") return subcommands;
142
- const prefix = `${parentCommandName} `;
143
- for (const [name, command] of this._cli._commands) if (name.startsWith(prefix)) {
144
- const subcommandName = name.slice(prefix.length);
145
- subcommands.set(subcommandName, command);
146
- }
147
- return subcommands;
148
- }
149
- buildGroupedCommandsBody(commandsToShow, prefix) {
150
- const groupedCommands = /* @__PURE__ */ new Map();
151
- const defaultCommands = [];
152
- let rootCommand = [];
153
- for (const command of commandsToShow.values()) {
154
- if (command.__isAlias || command.help?.show === false) continue;
155
- const group = command.help?.group;
156
- validateGroup(group, this._commandGroups, "command", command.name);
157
- const item = [`${tint.bold(formatCommandName(command.name.slice(prefix.length)))}${command.alias ? ` (${toArray(command.alias).join(", ")})` : ""}`, command.description].filter(isTruthy);
158
- if (command.name === "") rootCommand = item;
159
- else if (group && group !== DEFAULT_GROUP_KEY) {
160
- const groupItems = groupedCommands.get(group) ?? [];
161
- groupItems.push(item);
162
- groupedCommands.set(group, groupItems);
163
- } else defaultCommands.push(item);
164
- }
165
- const body = [];
166
- const defaultGroup = [];
167
- if (rootCommand.length > 0) defaultGroup.push(rootCommand);
168
- if (defaultCommands.length > 0) defaultGroup.push(...defaultCommands);
169
- if (defaultGroup.length > 0) body.push(...splitTable(defaultGroup));
170
- for (const [key, name] of this._commandGroups) {
171
- const items = groupedCommands.get(key);
172
- if (items && items.length > 0) {
173
- if (body.length > 0) body.push("");
174
- body.push(`${tint.dim(name)}`);
175
- body.push(...splitTable(items).map(withIndent));
176
- }
177
- }
178
- return body;
179
- }
180
- renderAvailableSubcommands(parentCommandName) {
181
- const subcommands = this.getSubcommands(parentCommandName);
182
- if (subcommands.size === 0) return null;
183
- const prefix = `${parentCommandName} `;
184
- const body = this.buildGroupedCommandsBody(subcommands, prefix);
185
- if (body.length === 0) return null;
186
- const sections = [{ body: `${this._cli._scriptName} ${tint.bold(parentCommandName)} not found` }, {
187
- title: "Available Subcommands",
188
- body
189
- }];
190
- return this.renderSections(sections);
191
- }
192
- renderCommands() {
193
- const commands = this._cli._commands;
194
- let commandsToShow;
195
- let title = "Commands";
196
- let prefix = "";
197
- if (this._command) {
198
- prefix = this._command.name ? `${this._command.name} ` : "";
199
- title = "Subcommands";
200
- commandsToShow = this.getSubcommands(this._command.name);
201
- if (commandsToShow.size === 0) return;
202
- } else commandsToShow = commands;
203
- if (commandsToShow.size === 0) return;
204
- const body = this.buildGroupedCommandsBody(commandsToShow, prefix);
205
- return {
206
- title,
207
- body
208
- };
209
- }
210
- renderFlagItem(name, flag) {
211
- flag = normalizeFlagValue(flag);
212
- let flagName = formatFlagName(name);
213
- if (flag.short) flagName += `, ${formatFlagName(flag.short)}`;
214
- const type = this._formatters.formatTypeValue(flag.type);
215
- const default_ = flag.default !== void 0 && tint.dim(`[default: ${tint.bold(this._formatters.formatFlagDefault(flag.default))}]`);
216
- return [
217
- tint.bold(flagName),
218
- tint.dim(type),
219
- flag.description,
220
- default_
221
- ].filter(isTruthy);
222
- }
223
- renderGroupedFlags(flags, groupMap, itemType) {
224
- const groupedFlags = /* @__PURE__ */ new Map();
225
- const defaultFlags = [];
226
- for (const [name, flag] of Object.entries(flags)) {
227
- const group = flag.help?.group;
228
- validateGroup(group, groupMap, itemType, name);
229
- const item = this.renderFlagItem(name, flag);
230
- if (group && group !== DEFAULT_GROUP_KEY) {
231
- const groupItems = groupedFlags.get(group) ?? [];
232
- groupItems.push(item);
233
- groupedFlags.set(group, groupItems);
234
- } else defaultFlags.push(item);
235
- }
236
- const body = [];
237
- if (defaultFlags.length > 0) body.push(...splitTable(defaultFlags));
238
- for (const [key, name] of groupMap) {
239
- const items = groupedFlags.get(key);
240
- if (items && items.length > 0) {
241
- if (body.length > 0) body.push("");
242
- body.push(`${tint.dim(name)}`);
243
- body.push(...splitTable(items).map(withIndent));
244
- }
245
- }
246
- return body;
247
- }
248
- renderCommandFlags() {
249
- const command = this._command;
250
- if (!command?.flags || objectIsEmpty(command.flags)) return;
251
- return {
252
- title: "Flags",
253
- body: this.renderGroupedFlags(command.flags, this._flagGroups, "flag")
254
- };
255
- }
256
- renderGlobalFlags() {
257
- if (!this._globalFlags || objectIsEmpty(this._globalFlags)) return;
258
- return {
259
- title: "Global Flags",
260
- body: this.renderGroupedFlags(this._globalFlags, this._globalFlagGroups, "global flag")
261
- };
262
- }
263
- renderNotes() {
264
- if (!this._notes?.length) return;
265
- return {
266
- title: "Notes",
267
- body: this._notes
268
- };
269
- }
270
- renderExamples() {
271
- if (!this._examples?.length) return;
272
- return {
273
- title: "Examples",
274
- body: splitTable(this._examples.map(([command, description]) => {
275
- return [
276
- command,
277
- DELIMITER,
278
- description
279
- ];
280
- }))
281
- };
282
- }
283
- };
284
-
285
- //#endregion
286
- //#region src/store.ts
287
- function addStoreApi(cli, { groups }) {
288
- cli.store.help = { addGroup: (options) => {
289
- if (options.commands) groups.commands = [...groups.commands ?? [], ...options.commands];
290
- if (options.flags) groups.flags = [...groups.flags ?? [], ...options.flags];
291
- if (options.globalFlags) groups.globalFlags = [...groups.globalFlags ?? [], ...options.globalFlags];
292
- } };
293
- }
294
-
295
- //#endregion
296
- //#region src/index.ts
297
- const helpPlugin = ({ command = true, flag = true, showHelpWhenNoCommandSpecified = true, notes, examples, header, footer, formatters, groups = {} } = {}) => definePlugin({ setup: (cli) => {
298
- addStoreApi(cli, { groups });
299
- const mergedFormatters = {
300
- ...defaultFormatters,
301
- ...formatters
302
- };
303
- function printHelp(s) {
304
- if (header) console.log(header);
305
- console.log(s);
306
- if (footer) console.log(footer);
307
- }
308
- const renderer = new HelpRenderer(mergedFormatters, cli, cli._globalFlags, () => groups, examples, notes);
309
- function tryPrintSubcommandsHelp(commandName) {
310
- const subcommandsOutput = renderer.renderAvailableSubcommands(commandName);
311
- if (subcommandsOutput) {
312
- printHelp(subcommandsOutput);
313
- return true;
314
- }
315
- return false;
316
- }
317
- if (command) cli.command("help", "Show help", {
318
- parameters: ["[command...]"],
319
- help: {
320
- notes: [
321
- "If no command is specified, show help for the CLI.",
322
- "If a command is specified, show help for the command.",
323
- flag && "-h is an alias for --help."
324
- ].filter(isTruthy),
325
- examples: [
326
- command && [`$ ${cli._scriptName} help`, "Show help"],
327
- command && [`$ ${cli._scriptName} help <command>`, "Show help for a specific command"],
328
- flag && [`$ ${cli._scriptName} <command> --help`, "Show help for a specific command"]
329
- ].filter(isTruthy)
330
- }
331
- }).on("help", (ctx) => {
332
- const commandName = ctx.parameters.command;
333
- let command$1;
334
- if (commandName.length > 0) {
335
- [command$1] = resolveCommand(cli._commands, commandName);
336
- if (!command$1) {
337
- const parentCommandName = commandName.join(" ");
338
- if (tryPrintSubcommandsHelp(parentCommandName)) return;
339
- throw new NoSuchCommandError(parentCommandName);
340
- }
341
- }
342
- renderer.setCommand(command$1);
343
- printHelp(renderer.render());
344
- });
345
- if (flag) cli.globalFlag("help", "Show help", {
346
- short: "h",
347
- type: Boolean,
348
- default: false
349
- });
350
- cli.interceptor({
351
- enforce: "post",
352
- handler: async (ctx, next) => {
353
- if (ctx.flags.help) {
354
- const command$1 = ctx.command;
355
- if (!command$1 && ctx.rawParsed.parameters.length > 0) {
356
- if (tryPrintSubcommandsHelp(ctx.rawParsed.parameters.join(" "))) return;
357
- await next();
358
- }
359
- renderer.setCommand(command$1);
360
- printHelp(renderer.render());
361
- } else if (showHelpWhenNoCommandSpecified && !ctx.command && ctx.rawParsed.parameters.length === 0) {
362
- console.log("No command specified. Showing help:\n");
363
- printHelp(renderer.render());
364
- } else await next();
365
- }
366
- });
367
- } });
368
-
369
- //#endregion
370
- export { defaultFormatters, helpPlugin };