@bemoje/cli 1.0.3 → 1.0.4

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.
@@ -28,4 +28,4 @@ __reExport(src_exports, require("./lib/renderHelp"), module.exports);
28
28
  ...require("./lib/Help"),
29
29
  ...require("./lib/renderHelp")
30
30
  });
31
- //# sourceMappingURL=index.js.map
31
+ //# sourceMappingURL=index.cjs.map
@@ -450,4 +450,4 @@ class Command {
450
450
  0 && (module.exports = {
451
451
  Command
452
452
  });
453
- //# sourceMappingURL=Command.js.map
453
+ //# sourceMappingURL=Command.cjs.map
@@ -127,4 +127,4 @@ let CommandHelpAdapter = _CommandHelpAdapter;
127
127
  0 && (module.exports = {
128
128
  CommandHelpAdapter
129
129
  });
130
- //# sourceMappingURL=CommandHelpAdapter.js.map
130
+ //# sourceMappingURL=CommandHelpAdapter.cjs.map
@@ -117,4 +117,4 @@ let CommanderHelpAdapter = _CommanderHelpAdapter;
117
117
  0 && (module.exports = {
118
118
  CommanderHelpAdapter
119
119
  });
120
- //# sourceMappingURL=CommanderHelpAdapter.js.map
120
+ //# sourceMappingURL=CommanderHelpAdapter.cjs.map
@@ -487,4 +487,4 @@ function humanReadableArgName(arg) {
487
487
  0 && (module.exports = {
488
488
  Help
489
489
  });
490
- //# sourceMappingURL=Help.js.map
490
+ //# sourceMappingURL=Help.cjs.map
@@ -38,4 +38,4 @@ function lazyProp(target, key, descriptor) {
38
38
  };
39
39
  return descriptor;
40
40
  }
41
- //# sourceMappingURL=lazyProp.js.map
41
+ //# sourceMappingURL=lazyProp.cjs.map
@@ -30,4 +30,4 @@ function renderHelp(cmd, help = new import_Help.Help()) {
30
30
  0 && (module.exports = {
31
31
  renderHelp
32
32
  });
33
- //# sourceMappingURL=renderHelp.js.map
33
+ //# sourceMappingURL=renderHelp.cjs.map
package/esm/index.mjs ADDED
@@ -0,0 +1,6 @@
1
+ export * from "./lib/Command";
2
+ export * from "./lib/CommandHelpAdapter";
3
+ export * from "./lib/CommanderHelpAdapter";
4
+ export * from "./lib/Help";
5
+ export * from "./lib/renderHelp";
6
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1,429 @@
1
+ import { parseArgs } from "node:util";
2
+ import { CommandHelpAdapter } from "./CommandHelpAdapter";
3
+ class Command {
4
+ /** Command name used for invocation */
5
+ name;
6
+ /** Optional version string */
7
+ version;
8
+ /** Alternative names for this command */
9
+ aliases;
10
+ /** Brief single-line description */
11
+ summary;
12
+ /** Full command description */
13
+ description;
14
+ /** Whether command should be hidden from help */
15
+ hidden;
16
+ /** Group name for organizing commands in help */
17
+ group;
18
+ /** Parent command if this is a subcommand */
19
+ parent;
20
+ /** Child subcommands */
21
+ commands;
22
+ /** Positional arguments */
23
+ arguments;
24
+ /** Named options/flags */
25
+ options;
26
+ /** Help system configuration */
27
+ helpConfiguration;
28
+ constructor(name = "", parent = null) {
29
+ this.name = name;
30
+ this.parent = parent;
31
+ this.aliases = [];
32
+ this.description = "";
33
+ this.commands = [];
34
+ this.arguments = [];
35
+ this.options = [];
36
+ this.helpConfiguration = { showGlobalOptions: true, sortOptions: true, sortSubcommands: true };
37
+ Object.defineProperty(this, "parent", { enumerable: false });
38
+ }
39
+ /** Updates multiple command properties at once */
40
+ setState(state) {
41
+ Object.assign(this, state);
42
+ if (state.commands) {
43
+ state.commands = state.commands.map((cmd) => new Command(cmd.name, this).setState(cmd));
44
+ }
45
+ return this;
46
+ }
47
+ /** Serializes command to JSON, maintaining compatibility with previous state-based structure */
48
+ toJSON() {
49
+ const result = {
50
+ name: this.name,
51
+ version: this.version,
52
+ aliases: this.aliases,
53
+ summary: this.summary,
54
+ description: this.description,
55
+ hidden: this.hidden,
56
+ group: this.group,
57
+ commands: this.commands,
58
+ arguments: this.arguments,
59
+ options: this.options,
60
+ helpConfiguration: this.helpConfiguration
61
+ };
62
+ Object.defineProperty(result, "parent", {
63
+ value: this.parent,
64
+ writable: true,
65
+ enumerable: false,
66
+ configurable: true
67
+ });
68
+ return result;
69
+ }
70
+ /** Sets the command name */
71
+ setName(name) {
72
+ this.name = name;
73
+ }
74
+ /** Sets command aliases, flattening nested arrays */
75
+ setAliases(...aliases) {
76
+ this.aliases = aliases.flat();
77
+ return this;
78
+ }
79
+ /** Adds aliases to existing ones */
80
+ addAliases(...aliases) {
81
+ this.aliases.push(...aliases.flat());
82
+ return this;
83
+ }
84
+ /** Sets the command version */
85
+ setVersion(version) {
86
+ this.version = version;
87
+ return this;
88
+ }
89
+ /** Sets the command summary */
90
+ setSummary(summary) {
91
+ this.summary = summary;
92
+ return this;
93
+ }
94
+ /** Sets command description, joining multiple lines */
95
+ setDescription(...lines) {
96
+ this.description = lines.join("\n");
97
+ return this;
98
+ }
99
+ /** Sets whether command is hidden from help */
100
+ setHidden(hidden = true) {
101
+ this.hidden = hidden;
102
+ return this;
103
+ }
104
+ /** Sets the command group for help organization */
105
+ setGroup(group) {
106
+ this.group = group;
107
+ return this;
108
+ }
109
+ /** Sets the parent command */
110
+ setParent(parent) {
111
+ this.parent = parent;
112
+ return this;
113
+ }
114
+ /** Extends existing help configuration with new settings */
115
+ extendHelpConfiguration(config) {
116
+ this.helpConfiguration = { ...this.helpConfiguration, ...config };
117
+ return this;
118
+ }
119
+ /** Sets help configuration, using defaults if not provided */
120
+ setHelpConfiguration(config) {
121
+ this.helpConfiguration = config ? { ...config } : { showGlobalOptions: true, sortOptions: true, sortSubcommands: true };
122
+ return this;
123
+ }
124
+ /** Creates and adds a subcommand */
125
+ subcommand(name) {
126
+ const sub = new Command(name, this);
127
+ this.commands.push(sub);
128
+ return sub;
129
+ }
130
+ /**
131
+ * Adds positional argument with type inference and CLI ordering validation.
132
+ */
133
+ argument(usage, description, options = {}) {
134
+ const match = usage.match(/^<(.*?)>$|^\[(.*?)\]$/);
135
+ if (!match) throw new Error(`Invalid argument format: ${usage}`);
136
+ const nameMatch = match[1] || match[2];
137
+ const name = nameMatch.replace(/\.\.\.$/, "");
138
+ this.assertArgumentNameNotInUse(name);
139
+ if (usage.startsWith("<")) {
140
+ if (nameMatch.endsWith("...")) {
141
+ this.assertNoMultipleVariadicArguments();
142
+ this.arguments.push({
143
+ name,
144
+ description,
145
+ required: true,
146
+ multiple: true,
147
+ ...options
148
+ });
149
+ } else {
150
+ this.assertNoOptionalOrVariadicArguments();
151
+ this.arguments.push({
152
+ name,
153
+ description,
154
+ required: true,
155
+ multiple: false,
156
+ ...options
157
+ });
158
+ }
159
+ } else if (usage.startsWith("[")) {
160
+ if (nameMatch.endsWith("...")) {
161
+ this.assertNoMultipleVariadicArguments();
162
+ this.arguments.push({
163
+ name,
164
+ description,
165
+ required: false,
166
+ multiple: true,
167
+ defaultValue: options.defaultValue ?? [],
168
+ ...options
169
+ });
170
+ } else {
171
+ this.assertNoVariadicArgument();
172
+ this.arguments.push({
173
+ name,
174
+ description,
175
+ required: false,
176
+ multiple: false,
177
+ ...options
178
+ });
179
+ }
180
+ }
181
+ return this;
182
+ }
183
+ /**
184
+ * Adds command-line option with type inference. Parses format: `-s, --long [<value>|[value]|<value...>|[value...]]`
185
+ */
186
+ option(usage, description, opts = {}) {
187
+ const match = usage.match(/^-(.+?), --([a-zA-Z][\w-]*)(?:\s*(<(.+?)>|\[(.+?)\]))?$/);
188
+ if (!match) throw new Error(`Invalid option format: ${usage}`);
189
+ const short = match[1];
190
+ this.assertOptionShortNameIsValid(short);
191
+ this.assertOptionShortNameNotInUse(short);
192
+ const name = match[2];
193
+ const argName = (match[4] || match[5])?.replace(/\.\.\.$/, "");
194
+ this.assertOptionNameNotInUse(name);
195
+ if (!argName) {
196
+ this.options.push({
197
+ type: "boolean",
198
+ short,
199
+ name,
200
+ description,
201
+ required: false,
202
+ multiple: false,
203
+ ...opts
204
+ });
205
+ } else if (usage.endsWith(">")) {
206
+ if (usage.endsWith("...>")) {
207
+ this.options.push({
208
+ type: "string",
209
+ short,
210
+ name,
211
+ argName,
212
+ description,
213
+ required: true,
214
+ multiple: true,
215
+ ...opts
216
+ });
217
+ } else {
218
+ this.options.push({
219
+ type: "string",
220
+ short,
221
+ name,
222
+ argName,
223
+ description,
224
+ required: true,
225
+ multiple: false,
226
+ ...opts
227
+ });
228
+ }
229
+ } else if (usage.endsWith("]")) {
230
+ if (usage.endsWith("...]")) {
231
+ this.options.push({
232
+ type: "string",
233
+ short,
234
+ name,
235
+ argName,
236
+ description,
237
+ required: false,
238
+ multiple: true,
239
+ defaultValue: opts.defaultValue ?? [],
240
+ ...opts
241
+ });
242
+ } else {
243
+ this.options.push({
244
+ type: "string",
245
+ short,
246
+ name,
247
+ argName,
248
+ description,
249
+ required: false,
250
+ multiple: false,
251
+ ...opts
252
+ });
253
+ }
254
+ }
255
+ return this;
256
+ }
257
+ /**
258
+ * Parses command-line arguments with subcommand support and type-safe validation.
259
+ *
260
+ * @example
261
+ * ```typescript
262
+ * const result = cmd.parse(['input.txt', '-v', '--format', 'json'])
263
+ * // { arguments: ['input.txt'], options: { verbose: true, format: 'json' } }
264
+ * ```
265
+ */
266
+ parse(argv = process.argv.slice(2), globalOptions = []) {
267
+ const maybeSubArg = parseArgs({
268
+ args: argv,
269
+ allowPositionals: true,
270
+ tokens: false,
271
+ strict: false,
272
+ allowNegative: true
273
+ }).positionals[0];
274
+ const sub = this.findCommand(maybeSubArg);
275
+ if (sub) {
276
+ return sub.parse(
277
+ argv?.filter((a) => a !== maybeSubArg),
278
+ [...globalOptions, ...this.options]
279
+ );
280
+ }
281
+ const parsed = parseArgs({
282
+ args: argv,
283
+ options: Object.fromEntries(
284
+ [...globalOptions, ...this.options].map((o) => {
285
+ return [o.name, o];
286
+ })
287
+ ),
288
+ allowPositionals: true,
289
+ tokens: true,
290
+ strict: true,
291
+ allowNegative: true
292
+ });
293
+ for (let i = 0; i < parsed.tokens.length; i++) {
294
+ const token = parsed.tokens[i];
295
+ if (token.kind === "option") {
296
+ const optionDescriptor = this.options.find((o) => o.name === token.name);
297
+ if (optionDescriptor && optionDescriptor.multiple && optionDescriptor.type === "string") {
298
+ const values = [token.value];
299
+ let j = i + 1;
300
+ while (j < parsed.tokens.length && parsed.tokens[j].kind === "positional") {
301
+ const positionalToken = parsed.tokens[j];
302
+ if (positionalToken.kind === "positional") {
303
+ values.push(positionalToken.value);
304
+ const posIndex = parsed.positionals.indexOf(positionalToken.value);
305
+ if (posIndex !== -1) {
306
+ parsed.positionals.splice(posIndex, 1);
307
+ }
308
+ }
309
+ j++;
310
+ }
311
+ Reflect.set(
312
+ parsed.values,
313
+ token.name,
314
+ values.filter((v) => v !== void 0)
315
+ );
316
+ }
317
+ }
318
+ }
319
+ const parsedArguments = this.arguments.map((arg, index) => {
320
+ if (arg.multiple) {
321
+ const remainingArgs = parsed.positionals.slice(index);
322
+ return remainingArgs.length > 0 ? remainingArgs : arg.defaultValue ?? [];
323
+ } else {
324
+ return parsed.positionals[index] ?? arg.defaultValue;
325
+ }
326
+ });
327
+ for (const option of this.options) {
328
+ if (!(option.name in parsed.values) && "defaultValue" in option) {
329
+ Reflect.set(parsed.values, option.name, option.defaultValue);
330
+ }
331
+ }
332
+ const self = this;
333
+ return {
334
+ get command() {
335
+ return self;
336
+ },
337
+ arguments: parsedArguments,
338
+ options: { ...parsed.values }
339
+ };
340
+ }
341
+ /** Validates CLI argument ordering */
342
+ assertNoOptionalOrVariadicArguments() {
343
+ if (this.arguments.some((arg) => !arg.required)) {
344
+ throw new Error("Cannot add required argument after optional or variadic arguments");
345
+ }
346
+ }
347
+ /** Validates optional args don't follow variadic args */
348
+ assertNoVariadicArgument() {
349
+ if (this.arguments.some((arg) => arg.multiple)) {
350
+ throw new Error("Cannot add optional argument after variadic argument");
351
+ }
352
+ }
353
+ /** Ensures only one variadic argument per command */
354
+ assertNoMultipleVariadicArguments() {
355
+ if (this.arguments.some((arg) => arg.multiple)) {
356
+ throw new Error("Cannot add more than one variadic argument");
357
+ }
358
+ }
359
+ /** Ensures unique argument names across arguments and options */
360
+ assertArgumentNameNotInUse(name) {
361
+ if (this.arguments.some((arg) => arg.name === name)) {
362
+ throw new Error(`Argument name already in use: ${name}`);
363
+ }
364
+ if (this.options.some((opt) => opt.name === name)) {
365
+ throw new Error(`Argument name already in use: ${name}`);
366
+ }
367
+ }
368
+ /** Validates option short names are single alphanumeric characters */
369
+ assertOptionShortNameIsValid(short) {
370
+ const isSingleAlphaNumericChar = /^[a-zA-Z0-9]$/.test(short);
371
+ if (!isSingleAlphaNumericChar) {
372
+ throw new Error(`Expected short name to be a single alpha-numeric character. Got: ${short}`);
373
+ }
374
+ }
375
+ /** Validates option short names are unique across command hierarchy */
376
+ assertOptionShortNameNotInUse(short) {
377
+ for (const opt of this.options) {
378
+ if (opt.short === short) {
379
+ throw new Error(`Option short name already in use: -${short}`);
380
+ }
381
+ }
382
+ this.parent?.assertOptionShortNameNotInUse(short);
383
+ }
384
+ /** Validates option names are unique across command hierarchy */
385
+ assertOptionNameNotInUse(name) {
386
+ if (this.options.some((opt) => opt.name === name)) {
387
+ throw new Error(`Option name already in use: --${name}`);
388
+ }
389
+ this.parent?.assertOptionNameNotInUse(name);
390
+ }
391
+ /** Returns command and all ancestor commands in hierarchy */
392
+ getCommandAndAncestors() {
393
+ const result = [];
394
+ let command = this;
395
+ for (; command; command = command.parent) {
396
+ result.push(command);
397
+ }
398
+ return result;
399
+ }
400
+ /** Returns all ancestor commands excluding this command */
401
+ getAncestors() {
402
+ return this.getCommandAndAncestors().slice(1);
403
+ }
404
+ /** Returns all options from this command and ancestors */
405
+ getOptionsInclAncestors() {
406
+ return this.getCommandAndAncestors().flatMap((cmd) => cmd.options);
407
+ }
408
+ /** Finds subcommand by name or alias */
409
+ findCommand(name) {
410
+ if (!name) return void 0;
411
+ return this.commands.find((cmd) => cmd.name === name || cmd.aliases.includes(name));
412
+ }
413
+ /** Finds option by short or long name */
414
+ findOption(arg) {
415
+ return this.options.find((option) => option.short === arg || option.name === arg);
416
+ }
417
+ /** Returns a view that is compliant with the CommandHelp interface */
418
+ createHelpAdapter() {
419
+ return new CommandHelpAdapter(this);
420
+ }
421
+ /** Renders formatted help text using provided help definition */
422
+ renderHelp(help) {
423
+ return this.createHelpAdapter().renderHelp(help);
424
+ }
425
+ }
426
+ export {
427
+ Command
428
+ };
429
+ //# sourceMappingURL=Command.mjs.map
@@ -0,0 +1,98 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __decorateClass = (decorators, target, key, kind) => {
4
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
5
+ for (var i = decorators.length - 1, decorator; i >= 0; i--)
6
+ if (decorator = decorators[i])
7
+ result = (kind ? decorator(target, key, result) : decorator(result)) || result;
8
+ if (kind && result) __defProp(target, key, result);
9
+ return result;
10
+ };
11
+ import lazyProp from "./internal/lazyProp";
12
+ import { Help } from "./Help";
13
+ import { renderHelp } from "./renderHelp";
14
+ const _CommandHelpAdapter = class _CommandHelpAdapter {
15
+ constructor(cmd) {
16
+ this.cmd = cmd;
17
+ }
18
+ renderHelp(help = new Help()) {
19
+ return renderHelp(this, help);
20
+ }
21
+ get name() {
22
+ return this.cmd.name;
23
+ }
24
+ get aliases() {
25
+ return this.cmd.aliases;
26
+ }
27
+ get summary() {
28
+ return this.cmd.summary ?? (this.cmd.description.includes("\n") ? this.cmd.description.split("\n")[0] : void 0);
29
+ }
30
+ get description() {
31
+ return this.cmd.description;
32
+ }
33
+ get hidden() {
34
+ return this.cmd.hidden;
35
+ }
36
+ get usage() {
37
+ return [
38
+ ...this.cmd.options.length ? ["[options]"] : [],
39
+ ...this.cmd.commands.length ? ["[command]"] : [],
40
+ ...this.cmd.arguments.map((arg) => this.renderArgumentFlags(arg))
41
+ ].join(" ");
42
+ }
43
+ get group() {
44
+ return this.cmd.group;
45
+ }
46
+ get commands() {
47
+ return this.cmd.commands.map((c) => new _CommandHelpAdapter(c));
48
+ }
49
+ get options() {
50
+ return this.cmd.options.map((opt) => ({
51
+ ...opt,
52
+ flags: this.renderOptionFlags(opt),
53
+ long: opt.name,
54
+ optional: !opt.required,
55
+ negate: false,
56
+ variadic: opt.multiple
57
+ }));
58
+ }
59
+ get arguments() {
60
+ return this.cmd.arguments.map((arg) => ({
61
+ ...arg,
62
+ variadic: arg.multiple
63
+ }));
64
+ }
65
+ get parent() {
66
+ return this.cmd.parent ? new _CommandHelpAdapter(this.cmd.parent) : null;
67
+ }
68
+ get helpConfiguration() {
69
+ return { ...this.cmd.helpConfiguration };
70
+ }
71
+ renderArgumentFlags(arg) {
72
+ return arg.required ? arg.multiple ? `<${arg.name}...>` : `<${arg.name}>` : arg.multiple ? `[${arg.name}...]` : `[${arg.name}]`;
73
+ }
74
+ renderOptionFlags(opt) {
75
+ const flags = `-${opt.short}, --${opt.name}`;
76
+ return opt.type === "boolean" ? flags : opt.required ? opt.multiple ? flags + ` <${opt.argName}...>` : flags + ` <${opt.argName}>` : opt.multiple ? flags + ` [${opt.argName}...]` : flags + ` [${opt.argName}]`;
77
+ }
78
+ };
79
+ __decorateClass([
80
+ lazyProp
81
+ ], _CommandHelpAdapter.prototype, "usage", 1);
82
+ __decorateClass([
83
+ lazyProp
84
+ ], _CommandHelpAdapter.prototype, "commands", 1);
85
+ __decorateClass([
86
+ lazyProp
87
+ ], _CommandHelpAdapter.prototype, "arguments", 1);
88
+ __decorateClass([
89
+ lazyProp
90
+ ], _CommandHelpAdapter.prototype, "parent", 1);
91
+ __decorateClass([
92
+ lazyProp
93
+ ], _CommandHelpAdapter.prototype, "helpConfiguration", 1);
94
+ let CommandHelpAdapter = _CommandHelpAdapter;
95
+ export {
96
+ CommandHelpAdapter
97
+ };
98
+ //# sourceMappingURL=CommandHelpAdapter.mjs.map
@@ -0,0 +1,88 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __decorateClass = (decorators, target, key, kind) => {
4
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
5
+ for (var i = decorators.length - 1, decorator; i >= 0; i--)
6
+ if (decorator = decorators[i])
7
+ result = (kind ? decorator(target, key, result) : decorator(result)) || result;
8
+ if (kind && result) __defProp(target, key, result);
9
+ return result;
10
+ };
11
+ import { Help } from "./Help";
12
+ import lazyProp from "./internal/lazyProp";
13
+ import { renderHelp } from "./renderHelp";
14
+ const _CommanderHelpAdapter = class _CommanderHelpAdapter {
15
+ constructor(cmd) {
16
+ this.cmd = cmd;
17
+ }
18
+ renderHelp(help = new Help()) {
19
+ return renderHelp(this, help);
20
+ }
21
+ get name() {
22
+ return this.cmd.name();
23
+ }
24
+ get aliases() {
25
+ return this.cmd.aliases();
26
+ }
27
+ get summary() {
28
+ const cmdSummary = this.cmd.summary();
29
+ return cmdSummary && cmdSummary.trim() !== "" ? cmdSummary : this.cmd.description().includes("\n") ? this.cmd.description().split("\n")[0] : void 0;
30
+ }
31
+ get description() {
32
+ return this.cmd.description();
33
+ }
34
+ get hidden() {
35
+ return Reflect.get(this.cmd, "_hidden");
36
+ }
37
+ get usage() {
38
+ return this.cmd.usage();
39
+ }
40
+ get group() {
41
+ return this.cmd.helpGroup();
42
+ }
43
+ get commands() {
44
+ return this.cmd.commands.map((c) => new _CommanderHelpAdapter(c));
45
+ }
46
+ get options() {
47
+ return this.cmd.options.map((opt) => ({
48
+ ...opt,
49
+ short: opt.short ?? opt.attributeName()[0],
50
+ long: opt.long ?? opt.attributeName()
51
+ }));
52
+ }
53
+ get arguments() {
54
+ return this.cmd.registeredArguments.map((arg) => ({
55
+ ...arg,
56
+ name: arg.name()
57
+ }));
58
+ }
59
+ get parent() {
60
+ return this.cmd.parent ? new _CommanderHelpAdapter(this.cmd.parent) : null;
61
+ }
62
+ get helpConfiguration() {
63
+ return { ...this.cmd.configureHelp() };
64
+ }
65
+ };
66
+ __decorateClass([
67
+ lazyProp
68
+ ], _CommanderHelpAdapter.prototype, "summary", 1);
69
+ __decorateClass([
70
+ lazyProp
71
+ ], _CommanderHelpAdapter.prototype, "commands", 1);
72
+ __decorateClass([
73
+ lazyProp
74
+ ], _CommanderHelpAdapter.prototype, "options", 1);
75
+ __decorateClass([
76
+ lazyProp
77
+ ], _CommanderHelpAdapter.prototype, "arguments", 1);
78
+ __decorateClass([
79
+ lazyProp
80
+ ], _CommanderHelpAdapter.prototype, "parent", 1);
81
+ __decorateClass([
82
+ lazyProp
83
+ ], _CommanderHelpAdapter.prototype, "helpConfiguration", 1);
84
+ let CommanderHelpAdapter = _CommanderHelpAdapter;
85
+ export {
86
+ CommanderHelpAdapter
87
+ };
88
+ //# sourceMappingURL=CommanderHelpAdapter.mjs.map
@@ -0,0 +1,466 @@
1
+ class Help {
2
+ /** output helpWidth, long lines are wrapped to fit */
3
+ helpWidth = process.stdout.isTTY ? process.stdout.columns : 80;
4
+ minWidthToWrap = 40;
5
+ sortSubcommands;
6
+ sortOptions;
7
+ showGlobalOptions;
8
+ /**
9
+ * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
10
+ */
11
+ visibleCommands(cmd) {
12
+ const visibleCommands = cmd.commands.filter((cmd2) => !cmd2.hidden);
13
+ if (this.sortSubcommands) {
14
+ visibleCommands.sort((a, b) => {
15
+ return a.name.localeCompare(b.name);
16
+ });
17
+ }
18
+ return visibleCommands;
19
+ }
20
+ /**
21
+ * Compare options for sort.
22
+ */
23
+ compareOptions(a, b) {
24
+ const getSortKey = (option) => {
25
+ return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
26
+ };
27
+ return getSortKey(a).localeCompare(getSortKey(b));
28
+ }
29
+ /**
30
+ * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
31
+ */
32
+ visibleOptions(cmd) {
33
+ const visibleOptions = cmd.options.filter((option) => !option.hidden);
34
+ if (this.sortOptions) {
35
+ visibleOptions.sort(this.compareOptions);
36
+ }
37
+ return visibleOptions;
38
+ }
39
+ /**
40
+ * Get an array of the visible global options. (Not including help.)
41
+ */
42
+ visibleGlobalOptions(cmd) {
43
+ if (!this.showGlobalOptions) return [];
44
+ const globalOptions = [];
45
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
46
+ const visibleOptions = ancestorCmd.options.filter((option) => !option.hidden);
47
+ globalOptions.push(...visibleOptions);
48
+ }
49
+ if (this.sortOptions) {
50
+ globalOptions.sort(this.compareOptions);
51
+ }
52
+ return globalOptions;
53
+ }
54
+ /**
55
+ * Get an array of the arguments if any have a description.
56
+ */
57
+ visibleArguments(cmd) {
58
+ if (cmd.arguments.find((argument) => argument.description)) {
59
+ return [...cmd.arguments];
60
+ }
61
+ return [];
62
+ }
63
+ /**
64
+ * Get the command term to show in the list of subcommands.
65
+ */
66
+ subcommandTerm(cmd) {
67
+ const args = cmd.arguments.map((arg) => humanReadableArgName(arg)).join(" ");
68
+ return cmd.name + (cmd.aliases[0] ? "|" + cmd.aliases[0] : "") + (cmd.options.length ? " [options]" : "") + // simplistic check for non-help option
69
+ (args ? " " + args : "");
70
+ }
71
+ /**
72
+ * Get the option term to show in the list of options.
73
+ */
74
+ optionTerm(option) {
75
+ return option.flags;
76
+ }
77
+ /**
78
+ * Get the argument term to show in the list of arguments.
79
+ */
80
+ argumentTerm(argument) {
81
+ return argument.name;
82
+ }
83
+ /**
84
+ * Get the longest command term length.
85
+ */
86
+ longestSubcommandTermLength(cmd, helper) {
87
+ return helper.visibleCommands(cmd).reduce((max, command) => {
88
+ return Math.max(max, this.displayWidth(helper.styleSubcommandTerm(helper.subcommandTerm(command))));
89
+ }, 0);
90
+ }
91
+ /**
92
+ * Get the longest option term length.
93
+ */
94
+ longestOptionTermLength(cmd, helper) {
95
+ return helper.visibleOptions(cmd).reduce((max, option) => {
96
+ return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
97
+ }, 0);
98
+ }
99
+ /**
100
+ * Get the longest global option term length.
101
+ */
102
+ longestGlobalOptionTermLength(cmd, helper) {
103
+ return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
104
+ return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
105
+ }, 0);
106
+ }
107
+ /**
108
+ * Get the longest argument term length.
109
+ */
110
+ longestArgumentTermLength(cmd, helper) {
111
+ return helper.visibleArguments(cmd).reduce((max, argument) => {
112
+ return Math.max(max, this.displayWidth(helper.styleArgumentTerm(helper.argumentTerm(argument))));
113
+ }, 0);
114
+ }
115
+ /**
116
+ * Get the command usage to be displayed at the top of the built-in help.
117
+ */
118
+ commandUsage(cmd) {
119
+ let cmdName = cmd.name;
120
+ if (cmd.aliases[0]) {
121
+ cmdName = cmdName + "|" + cmd.aliases[0];
122
+ }
123
+ let ancestorCmdNames = "";
124
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
125
+ ancestorCmdNames = ancestorCmd.name + " " + ancestorCmdNames;
126
+ }
127
+ return ancestorCmdNames + cmdName + " " + cmd.usage;
128
+ }
129
+ /**
130
+ * Get the description for the command.
131
+ */
132
+ commandDescription(cmd) {
133
+ return cmd.description;
134
+ }
135
+ /**
136
+ * Get the subcommand summary to show in the list of subcommands.
137
+ * (Fallback to description for backwards compatibility.)
138
+ */
139
+ subcommandDescription(cmd) {
140
+ return cmd.summary || cmd.description;
141
+ }
142
+ /**
143
+ * Get the option description to show in the list of options.
144
+ */
145
+ optionDescription(option) {
146
+ const extraInfo = [];
147
+ if (option.choices) {
148
+ extraInfo.push(
149
+ // use stringify to match the display of the default value
150
+ `choices: ${option.choices.map((choice) => String(choice)).join(", ")}`
151
+ );
152
+ }
153
+ if (option.defaultValue !== void 0) {
154
+ const boolean = !option.required && !option.optional && !option.negate;
155
+ const showDefault = option.required || option.optional || boolean && typeof option.defaultValue === "boolean";
156
+ if (showDefault) {
157
+ extraInfo.push(`default: ${option.defaultValueDescription || String(option.defaultValue)}`);
158
+ }
159
+ }
160
+ if (option.env !== void 0) {
161
+ extraInfo.push(`env: ${option.env}`);
162
+ }
163
+ if (extraInfo.length > 0) {
164
+ const extraDescription = `(${extraInfo.join(", ")})`;
165
+ if (option.description) {
166
+ return `${option.description} ${extraDescription}`;
167
+ }
168
+ return extraDescription;
169
+ }
170
+ return option.description;
171
+ }
172
+ /**
173
+ * Get the argument description to show in the list of arguments.
174
+ */
175
+ argumentDescription(argument) {
176
+ const extraInfo = [];
177
+ if (argument.choices) {
178
+ extraInfo.push(
179
+ // use stringify to match the display of the default value
180
+ `choices: ${argument.choices.map((choice) => String(choice)).join(", ")}`
181
+ );
182
+ }
183
+ if (argument.defaultValue !== void 0) {
184
+ extraInfo.push(`default: ${argument.defaultValueDescription || String(argument.defaultValue)}`);
185
+ }
186
+ if (extraInfo.length > 0) {
187
+ const extraDescription = `(${extraInfo.join(", ")})`;
188
+ if (argument.description) {
189
+ return `${argument.description} ${extraDescription}`;
190
+ }
191
+ return extraDescription;
192
+ }
193
+ return argument.description;
194
+ }
195
+ /**
196
+ * Format a list of items, given a heading and an array of formatted items.
197
+ */
198
+ formatItemList(heading, items, helper) {
199
+ if (items.length === 0) return [];
200
+ return [helper.styleTitle(heading), ...items, ""];
201
+ }
202
+ /**
203
+ * Group items by their help group heading.
204
+ */
205
+ groupItems(unsortedItems, visibleItems, getGroup) {
206
+ const result = /* @__PURE__ */ new Map();
207
+ unsortedItems.forEach((item) => {
208
+ const group = getGroup(item);
209
+ if (!result.has(group)) result.set(group, []);
210
+ });
211
+ visibleItems.forEach((item) => {
212
+ const group = getGroup(item);
213
+ if (!result.has(group)) {
214
+ result.set(group, []);
215
+ }
216
+ result.get(group).push(item);
217
+ });
218
+ return result;
219
+ }
220
+ /**
221
+ * Generate the built-in help text.
222
+ */
223
+ formatHelp(cmd, helper) {
224
+ const termWidth = helper.padWidth(cmd, helper);
225
+ const helpWidth = helper.helpWidth;
226
+ function callFormatItem(term, description) {
227
+ return helper.formatItem(term, termWidth, description, helper);
228
+ }
229
+ let output = [`${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`, ""];
230
+ const commandDescription = helper.commandDescription(cmd);
231
+ if (commandDescription.length > 0) {
232
+ output = output.concat([helper.boxWrap(helper.styleCommandDescription(commandDescription), helpWidth), ""]);
233
+ }
234
+ const argumentList = helper.visibleArguments(cmd).map((argument) => {
235
+ return callFormatItem(
236
+ helper.styleArgumentTerm(helper.argumentTerm(argument)),
237
+ helper.styleArgumentDescription(helper.argumentDescription(argument))
238
+ );
239
+ });
240
+ output = output.concat(this.formatItemList("Arguments:", argumentList, helper));
241
+ const optionGroups = this.groupItems(
242
+ cmd.options,
243
+ helper.visibleOptions(cmd),
244
+ (option) => option.group ?? "Options:"
245
+ );
246
+ optionGroups.forEach((options, group) => {
247
+ const optionList = options.map((option) => {
248
+ return callFormatItem(
249
+ helper.styleOptionTerm(helper.optionTerm(option)),
250
+ helper.styleOptionDescription(helper.optionDescription(option))
251
+ );
252
+ });
253
+ output = output.concat(this.formatItemList(group, optionList, helper));
254
+ });
255
+ if (helper.showGlobalOptions) {
256
+ const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
257
+ return callFormatItem(
258
+ helper.styleOptionTerm(helper.optionTerm(option)),
259
+ helper.styleOptionDescription(helper.optionDescription(option))
260
+ );
261
+ });
262
+ output = output.concat(this.formatItemList("Global Options:", globalOptionList, helper));
263
+ }
264
+ const commandGroups = this.groupItems(
265
+ cmd.commands,
266
+ helper.visibleCommands(cmd),
267
+ (sub) => sub.group || "Commands:"
268
+ );
269
+ commandGroups.forEach((commands, group) => {
270
+ const commandList = commands.map((sub) => {
271
+ return callFormatItem(
272
+ helper.styleSubcommandTerm(helper.subcommandTerm(sub)),
273
+ helper.styleSubcommandDescription(helper.subcommandDescription(sub))
274
+ );
275
+ });
276
+ output = output.concat(this.formatItemList(group, commandList, helper));
277
+ });
278
+ return output.join("\n");
279
+ }
280
+ /**
281
+ * Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations.
282
+ */
283
+ displayWidth(str) {
284
+ return stripColor(str).length;
285
+ }
286
+ /**
287
+ * Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc.
288
+ */
289
+ styleTitle(str) {
290
+ return str;
291
+ }
292
+ /**
293
+ * Style the usage line for displaying in the help. Applies specific styling to different parts like options, commands, and arguments.
294
+ */
295
+ styleUsage(str) {
296
+ return str.split(" ").map((word) => {
297
+ if (word === "[options]") return this.styleOptionText(word);
298
+ if (word === "[command]") return this.styleSubcommandText(word);
299
+ if (word[0] === "[" || word[0] === "<") return this.styleArgumentText(word);
300
+ return this.styleCommandText(word);
301
+ }).join(" ");
302
+ }
303
+ /**
304
+ * Style command descriptions for display in help output.
305
+ */
306
+ styleCommandDescription(str) {
307
+ return this.styleDescriptionText(str);
308
+ }
309
+ /**
310
+ * Style option descriptions for display in help output.
311
+ */
312
+ styleOptionDescription(str) {
313
+ return this.styleDescriptionText(str);
314
+ }
315
+ /**
316
+ * Style subcommand descriptions for display in help output.
317
+ */
318
+ styleSubcommandDescription(str) {
319
+ return this.styleDescriptionText(str);
320
+ }
321
+ /**
322
+ * Style argument descriptions for display in help output.
323
+ */
324
+ styleArgumentDescription(str) {
325
+ return this.styleDescriptionText(str);
326
+ }
327
+ /**
328
+ * Base style used by descriptions. Override in subclass to apply custom formatting.
329
+ */
330
+ styleDescriptionText(str) {
331
+ return str;
332
+ }
333
+ /**
334
+ * Style option terms (flags) for display in help output.
335
+ */
336
+ styleOptionTerm(str) {
337
+ return this.styleOptionText(str);
338
+ }
339
+ /**
340
+ * Style subcommand terms for display in help output. Applies specific styling to different parts like options and arguments.
341
+ */
342
+ styleSubcommandTerm(str) {
343
+ return str.split(" ").map((word) => {
344
+ if (word === "[options]") return this.styleOptionText(word);
345
+ if (word[0] === "[" || word[0] === "<") return this.styleArgumentText(word);
346
+ return this.styleSubcommandText(word);
347
+ }).join(" ");
348
+ }
349
+ /**
350
+ * Style argument terms for display in help output.
351
+ */
352
+ styleArgumentTerm(str) {
353
+ return this.styleArgumentText(str);
354
+ }
355
+ /**
356
+ * Base style used in terms and usage for options. Override in subclass to apply custom formatting.
357
+ */
358
+ styleOptionText(str) {
359
+ return str;
360
+ }
361
+ /**
362
+ * Base style used in terms and usage for arguments. Override in subclass to apply custom formatting.
363
+ */
364
+ styleArgumentText(str) {
365
+ return str;
366
+ }
367
+ /**
368
+ * Base style used in terms and usage for subcommands. Override in subclass to apply custom formatting.
369
+ */
370
+ styleSubcommandText(str) {
371
+ return str;
372
+ }
373
+ /**
374
+ * Base style used in terms and usage for commands. Override in subclass to apply custom formatting.
375
+ */
376
+ styleCommandText(str) {
377
+ return str;
378
+ }
379
+ /**
380
+ * Calculate the pad width from the maximum term length.
381
+ */
382
+ padWidth(cmd, helper) {
383
+ return Math.max(
384
+ helper.longestOptionTermLength(cmd, helper),
385
+ helper.longestGlobalOptionTermLength(cmd, helper),
386
+ helper.longestSubcommandTermLength(cmd, helper),
387
+ helper.longestArgumentTermLength(cmd, helper)
388
+ );
389
+ }
390
+ /**
391
+ * Detect manually wrapped and indented strings by checking for line break followed by whitespace.
392
+ */
393
+ preformatted(str) {
394
+ return /\n[^\S\r\n]/.test(str);
395
+ }
396
+ /**
397
+ * Format the "item", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.
398
+ *
399
+ * So "TTT", 5, "DDD DDDD DD DDD" might be formatted for this.helpWidth=17 like so:
400
+ * TTT DDD DDDD
401
+ * DD DDD
402
+ */
403
+ formatItem(term, termWidth, description, helper) {
404
+ const itemIndent = 2;
405
+ const itemIndentStr = " ".repeat(itemIndent);
406
+ if (!description) return itemIndentStr + term;
407
+ const paddedTerm = term.padEnd(termWidth + term.length - helper.displayWidth(term));
408
+ const spacerWidth = 2;
409
+ const helpWidth = this.helpWidth;
410
+ const remainingWidth = helpWidth - termWidth - spacerWidth - itemIndent;
411
+ let formattedDescription;
412
+ if (remainingWidth < this.minWidthToWrap || helper.preformatted(description)) {
413
+ formattedDescription = description;
414
+ } else {
415
+ const wrappedDescription = helper.boxWrap(description, remainingWidth);
416
+ formattedDescription = wrappedDescription.replace(/\n/g, "\n" + " ".repeat(termWidth + spacerWidth));
417
+ }
418
+ return itemIndentStr + paddedTerm + " ".repeat(spacerWidth) + formattedDescription.replace(/\n/g, `
419
+ ${itemIndentStr}`);
420
+ }
421
+ /**
422
+ * Wrap a string at whitespace, preserving existing line breaks.
423
+ * Wrapping is skipped if the width is less than `minWidthToWrap`.
424
+ */
425
+ boxWrap(str, width) {
426
+ if (width < this.minWidthToWrap) return str;
427
+ const rawLines = str.split(/\r\n|\n/);
428
+ const chunkPattern = /[\s]*[^\s]+/g;
429
+ const wrappedLines = [];
430
+ rawLines.forEach((line) => {
431
+ const chunks = line.match(chunkPattern);
432
+ if (chunks === null) {
433
+ wrappedLines.push("");
434
+ return;
435
+ }
436
+ let sumChunks = [chunks.shift()];
437
+ let sumWidth = this.displayWidth(sumChunks[0]);
438
+ chunks.forEach((chunk) => {
439
+ const visibleWidth = this.displayWidth(chunk);
440
+ if (sumWidth + visibleWidth <= width) {
441
+ sumChunks.push(chunk);
442
+ sumWidth += visibleWidth;
443
+ return;
444
+ }
445
+ wrappedLines.push(sumChunks.join(""));
446
+ const nextChunk = chunk.trimStart();
447
+ sumChunks = [nextChunk];
448
+ sumWidth = this.displayWidth(nextChunk);
449
+ });
450
+ wrappedLines.push(sumChunks.join(""));
451
+ });
452
+ return wrappedLines.join("\n");
453
+ }
454
+ }
455
+ function stripColor(str) {
456
+ const sgrPattern = /\x1b\[\d*(;\d*)*m/g;
457
+ return str.replace(sgrPattern, "");
458
+ }
459
+ function humanReadableArgName(arg) {
460
+ const nameOutput = arg.name + (arg.variadic === true ? "..." : "");
461
+ return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
462
+ }
463
+ export {
464
+ Help
465
+ };
466
+ //# sourceMappingURL=Help.mjs.map
@@ -0,0 +1,21 @@
1
+ function lazyProp(target, key, descriptor) {
2
+ const orig = descriptor.get;
3
+ if (typeof orig !== "function") {
4
+ throw new Error('"get" not a function');
5
+ }
6
+ descriptor.get = function() {
7
+ const value = orig.call(this);
8
+ Object.defineProperty(this, key, {
9
+ enumerable: false,
10
+ writable: false,
11
+ configurable: true,
12
+ value
13
+ });
14
+ return value;
15
+ };
16
+ return descriptor;
17
+ }
18
+ export {
19
+ lazyProp as default
20
+ };
21
+ //# sourceMappingURL=lazyProp.mjs.map
@@ -0,0 +1,9 @@
1
+ import { Help } from "./Help";
2
+ function renderHelp(cmd, help = new Help()) {
3
+ const helper = Object.assign(help, cmd.helpConfiguration);
4
+ return helper.formatHelp(cmd, helper);
5
+ }
6
+ export {
7
+ renderHelp
8
+ };
9
+ //# sourceMappingURL=renderHelp.mjs.map
package/package.json CHANGED
@@ -1,19 +1,13 @@
1
1
  {
2
2
  "name": "@bemoje/cli",
3
3
  "description": "A type-safe CLI builder focused on command composition and help generation without execution coupling. Parse arguments, generate help, and integrate with existing CLI frameworks through a clean, fluent API.",
4
- "version": "1.0.3",
4
+ "version": "1.0.4",
5
5
  "private": false,
6
6
  "sideEffects": false,
7
- "type": "commonjs",
8
- "module": "./index.js",
9
- "main": "./index.js",
10
- "exports": {
11
- ".": "./index.js",
12
- "./*": "./lib/*.js",
13
- "./package.json": "./package.json",
14
- "./index.d.ts": "./index.d.ts"
15
- },
16
- "typings": "./index.d.ts",
7
+ "type": "module",
8
+ "module": "./esm/index.mjs",
9
+ "main": "./cjs/index.cjs",
10
+ "typings": "./typings/index.d.ts",
17
11
  "dependencies": {},
18
12
  "devDependencies": {
19
13
  "commander": "^14.0.0"
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes