@cognite/cli 0.5.2 → 0.6.0-alpha.6

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.
@@ -0,0 +1,3589 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __typeError = (msg) => {
8
+ throw TypeError(msg);
9
+ };
10
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
11
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
12
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
13
+ }) : x)(function(x) {
14
+ if (typeof require !== "undefined") return require.apply(this, arguments);
15
+ throw Error('Dynamic require of "' + x + '" is not supported');
16
+ });
17
+ var __esm = (fn, res) => function __init() {
18
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
19
+ };
20
+ var __commonJS = (cb, mod) => function __require2() {
21
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
22
+ };
23
+ var __export = (target, all) => {
24
+ for (var name in all)
25
+ __defProp(target, name, { get: all[name], enumerable: true });
26
+ };
27
+ var __copyProps = (to, from, except, desc) => {
28
+ if (from && typeof from === "object" || typeof from === "function") {
29
+ for (let key of __getOwnPropNames(from))
30
+ if (!__hasOwnProp.call(to, key) && key !== except)
31
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
32
+ }
33
+ return to;
34
+ };
35
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
36
+ // If the importer is in node compatibility mode or this is not an ESM
37
+ // file that has been converted to a CommonJS file using a Babel-
38
+ // compatible transform (i.e. "__esModule" has not been set), then set
39
+ // "default" to the CommonJS "module.exports" for node compatibility.
40
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
41
+ mod
42
+ ));
43
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
44
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
45
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
46
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
47
+ var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
48
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
49
+ var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
50
+ var __privateWrapper = (obj, member, setter, getter) => ({
51
+ set _(value) {
52
+ __privateSet(obj, member, value, setter);
53
+ },
54
+ get _() {
55
+ return __privateGet(obj, member, getter);
56
+ }
57
+ });
58
+
59
+ // ../../node_modules/.pnpm/commander@14.0.3/node_modules/commander/lib/error.js
60
+ var require_error = __commonJS({
61
+ "../../node_modules/.pnpm/commander@14.0.3/node_modules/commander/lib/error.js"(exports) {
62
+ "use strict";
63
+ var CommanderError2 = class extends Error {
64
+ /**
65
+ * Constructs the CommanderError class
66
+ * @param {number} exitCode suggested exit code which could be used with process.exit
67
+ * @param {string} code an id string representing the error
68
+ * @param {string} message human-readable description of the error
69
+ */
70
+ constructor(exitCode, code, message) {
71
+ super(message);
72
+ Error.captureStackTrace(this, this.constructor);
73
+ this.name = this.constructor.name;
74
+ this.code = code;
75
+ this.exitCode = exitCode;
76
+ this.nestedError = void 0;
77
+ }
78
+ };
79
+ var InvalidArgumentError2 = class extends CommanderError2 {
80
+ /**
81
+ * Constructs the InvalidArgumentError class
82
+ * @param {string} [message] explanation of why argument is invalid
83
+ */
84
+ constructor(message) {
85
+ super(1, "commander.invalidArgument", message);
86
+ Error.captureStackTrace(this, this.constructor);
87
+ this.name = this.constructor.name;
88
+ }
89
+ };
90
+ exports.CommanderError = CommanderError2;
91
+ exports.InvalidArgumentError = InvalidArgumentError2;
92
+ }
93
+ });
94
+
95
+ // ../../node_modules/.pnpm/commander@14.0.3/node_modules/commander/lib/argument.js
96
+ var require_argument = __commonJS({
97
+ "../../node_modules/.pnpm/commander@14.0.3/node_modules/commander/lib/argument.js"(exports) {
98
+ "use strict";
99
+ var { InvalidArgumentError: InvalidArgumentError2 } = require_error();
100
+ var Argument2 = class {
101
+ /**
102
+ * Initialize a new command argument with the given name and description.
103
+ * The default is that the argument is required, and you can explicitly
104
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
105
+ *
106
+ * @param {string} name
107
+ * @param {string} [description]
108
+ */
109
+ constructor(name, description) {
110
+ this.description = description || "";
111
+ this.variadic = false;
112
+ this.parseArg = void 0;
113
+ this.defaultValue = void 0;
114
+ this.defaultValueDescription = void 0;
115
+ this.argChoices = void 0;
116
+ switch (name[0]) {
117
+ case "<":
118
+ this.required = true;
119
+ this._name = name.slice(1, -1);
120
+ break;
121
+ case "[":
122
+ this.required = false;
123
+ this._name = name.slice(1, -1);
124
+ break;
125
+ default:
126
+ this.required = true;
127
+ this._name = name;
128
+ break;
129
+ }
130
+ if (this._name.endsWith("...")) {
131
+ this.variadic = true;
132
+ this._name = this._name.slice(0, -3);
133
+ }
134
+ }
135
+ /**
136
+ * Return argument name.
137
+ *
138
+ * @return {string}
139
+ */
140
+ name() {
141
+ return this._name;
142
+ }
143
+ /**
144
+ * @package
145
+ */
146
+ _collectValue(value, previous) {
147
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
148
+ return [value];
149
+ }
150
+ previous.push(value);
151
+ return previous;
152
+ }
153
+ /**
154
+ * Set the default value, and optionally supply the description to be displayed in the help.
155
+ *
156
+ * @param {*} value
157
+ * @param {string} [description]
158
+ * @return {Argument}
159
+ */
160
+ default(value, description) {
161
+ this.defaultValue = value;
162
+ this.defaultValueDescription = description;
163
+ return this;
164
+ }
165
+ /**
166
+ * Set the custom handler for processing CLI command arguments into argument values.
167
+ *
168
+ * @param {Function} [fn]
169
+ * @return {Argument}
170
+ */
171
+ argParser(fn) {
172
+ this.parseArg = fn;
173
+ return this;
174
+ }
175
+ /**
176
+ * Only allow argument value to be one of choices.
177
+ *
178
+ * @param {string[]} values
179
+ * @return {Argument}
180
+ */
181
+ choices(values) {
182
+ this.argChoices = values.slice();
183
+ this.parseArg = (arg, previous) => {
184
+ if (!this.argChoices.includes(arg)) {
185
+ throw new InvalidArgumentError2(
186
+ `Allowed choices are ${this.argChoices.join(", ")}.`
187
+ );
188
+ }
189
+ if (this.variadic) {
190
+ return this._collectValue(arg, previous);
191
+ }
192
+ return arg;
193
+ };
194
+ return this;
195
+ }
196
+ /**
197
+ * Make argument required.
198
+ *
199
+ * @returns {Argument}
200
+ */
201
+ argRequired() {
202
+ this.required = true;
203
+ return this;
204
+ }
205
+ /**
206
+ * Make argument optional.
207
+ *
208
+ * @returns {Argument}
209
+ */
210
+ argOptional() {
211
+ this.required = false;
212
+ return this;
213
+ }
214
+ };
215
+ function humanReadableArgName(arg) {
216
+ const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
217
+ return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
218
+ }
219
+ exports.Argument = Argument2;
220
+ exports.humanReadableArgName = humanReadableArgName;
221
+ }
222
+ });
223
+
224
+ // ../../node_modules/.pnpm/commander@14.0.3/node_modules/commander/lib/help.js
225
+ var require_help = __commonJS({
226
+ "../../node_modules/.pnpm/commander@14.0.3/node_modules/commander/lib/help.js"(exports) {
227
+ "use strict";
228
+ var { humanReadableArgName } = require_argument();
229
+ var Help2 = class {
230
+ constructor() {
231
+ this.helpWidth = void 0;
232
+ this.minWidthToWrap = 40;
233
+ this.sortSubcommands = false;
234
+ this.sortOptions = false;
235
+ this.showGlobalOptions = false;
236
+ }
237
+ /**
238
+ * prepareContext is called by Commander after applying overrides from `Command.configureHelp()`
239
+ * and just before calling `formatHelp()`.
240
+ *
241
+ * Commander just uses the helpWidth and the rest is provided for optional use by more complex subclasses.
242
+ *
243
+ * @param {{ error?: boolean, helpWidth?: number, outputHasColors?: boolean }} contextOptions
244
+ */
245
+ prepareContext(contextOptions) {
246
+ this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;
247
+ }
248
+ /**
249
+ * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
250
+ *
251
+ * @param {Command} cmd
252
+ * @returns {Command[]}
253
+ */
254
+ visibleCommands(cmd) {
255
+ const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
256
+ const helpCommand = cmd._getHelpCommand();
257
+ if (helpCommand && !helpCommand._hidden) {
258
+ visibleCommands.push(helpCommand);
259
+ }
260
+ if (this.sortSubcommands) {
261
+ visibleCommands.sort((a, b) => {
262
+ return a.name().localeCompare(b.name());
263
+ });
264
+ }
265
+ return visibleCommands;
266
+ }
267
+ /**
268
+ * Compare options for sort.
269
+ *
270
+ * @param {Option} a
271
+ * @param {Option} b
272
+ * @returns {number}
273
+ */
274
+ compareOptions(a, b) {
275
+ const getSortKey = (option) => {
276
+ return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
277
+ };
278
+ return getSortKey(a).localeCompare(getSortKey(b));
279
+ }
280
+ /**
281
+ * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
282
+ *
283
+ * @param {Command} cmd
284
+ * @returns {Option[]}
285
+ */
286
+ visibleOptions(cmd) {
287
+ const visibleOptions = cmd.options.filter((option) => !option.hidden);
288
+ const helpOption = cmd._getHelpOption();
289
+ if (helpOption && !helpOption.hidden) {
290
+ const removeShort = helpOption.short && cmd._findOption(helpOption.short);
291
+ const removeLong = helpOption.long && cmd._findOption(helpOption.long);
292
+ if (!removeShort && !removeLong) {
293
+ visibleOptions.push(helpOption);
294
+ } else if (helpOption.long && !removeLong) {
295
+ visibleOptions.push(
296
+ cmd.createOption(helpOption.long, helpOption.description)
297
+ );
298
+ } else if (helpOption.short && !removeShort) {
299
+ visibleOptions.push(
300
+ cmd.createOption(helpOption.short, helpOption.description)
301
+ );
302
+ }
303
+ }
304
+ if (this.sortOptions) {
305
+ visibleOptions.sort(this.compareOptions);
306
+ }
307
+ return visibleOptions;
308
+ }
309
+ /**
310
+ * Get an array of the visible global options. (Not including help.)
311
+ *
312
+ * @param {Command} cmd
313
+ * @returns {Option[]}
314
+ */
315
+ visibleGlobalOptions(cmd) {
316
+ if (!this.showGlobalOptions) return [];
317
+ const globalOptions = [];
318
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
319
+ const visibleOptions = ancestorCmd.options.filter(
320
+ (option) => !option.hidden
321
+ );
322
+ globalOptions.push(...visibleOptions);
323
+ }
324
+ if (this.sortOptions) {
325
+ globalOptions.sort(this.compareOptions);
326
+ }
327
+ return globalOptions;
328
+ }
329
+ /**
330
+ * Get an array of the arguments if any have a description.
331
+ *
332
+ * @param {Command} cmd
333
+ * @returns {Argument[]}
334
+ */
335
+ visibleArguments(cmd) {
336
+ if (cmd._argsDescription) {
337
+ cmd.registeredArguments.forEach((argument) => {
338
+ argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
339
+ });
340
+ }
341
+ if (cmd.registeredArguments.find((argument) => argument.description)) {
342
+ return cmd.registeredArguments;
343
+ }
344
+ return [];
345
+ }
346
+ /**
347
+ * Get the command term to show in the list of subcommands.
348
+ *
349
+ * @param {Command} cmd
350
+ * @returns {string}
351
+ */
352
+ subcommandTerm(cmd) {
353
+ const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
354
+ return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + // simplistic check for non-help option
355
+ (args ? " " + args : "");
356
+ }
357
+ /**
358
+ * Get the option term to show in the list of options.
359
+ *
360
+ * @param {Option} option
361
+ * @returns {string}
362
+ */
363
+ optionTerm(option) {
364
+ return option.flags;
365
+ }
366
+ /**
367
+ * Get the argument term to show in the list of arguments.
368
+ *
369
+ * @param {Argument} argument
370
+ * @returns {string}
371
+ */
372
+ argumentTerm(argument) {
373
+ return argument.name();
374
+ }
375
+ /**
376
+ * Get the longest command term length.
377
+ *
378
+ * @param {Command} cmd
379
+ * @param {Help} helper
380
+ * @returns {number}
381
+ */
382
+ longestSubcommandTermLength(cmd, helper) {
383
+ return helper.visibleCommands(cmd).reduce((max, command) => {
384
+ return Math.max(
385
+ max,
386
+ this.displayWidth(
387
+ helper.styleSubcommandTerm(helper.subcommandTerm(command))
388
+ )
389
+ );
390
+ }, 0);
391
+ }
392
+ /**
393
+ * Get the longest option term length.
394
+ *
395
+ * @param {Command} cmd
396
+ * @param {Help} helper
397
+ * @returns {number}
398
+ */
399
+ longestOptionTermLength(cmd, helper) {
400
+ return helper.visibleOptions(cmd).reduce((max, option) => {
401
+ return Math.max(
402
+ max,
403
+ this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option)))
404
+ );
405
+ }, 0);
406
+ }
407
+ /**
408
+ * Get the longest global option term length.
409
+ *
410
+ * @param {Command} cmd
411
+ * @param {Help} helper
412
+ * @returns {number}
413
+ */
414
+ longestGlobalOptionTermLength(cmd, helper) {
415
+ return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
416
+ return Math.max(
417
+ max,
418
+ this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option)))
419
+ );
420
+ }, 0);
421
+ }
422
+ /**
423
+ * Get the longest argument term length.
424
+ *
425
+ * @param {Command} cmd
426
+ * @param {Help} helper
427
+ * @returns {number}
428
+ */
429
+ longestArgumentTermLength(cmd, helper) {
430
+ return helper.visibleArguments(cmd).reduce((max, argument) => {
431
+ return Math.max(
432
+ max,
433
+ this.displayWidth(
434
+ helper.styleArgumentTerm(helper.argumentTerm(argument))
435
+ )
436
+ );
437
+ }, 0);
438
+ }
439
+ /**
440
+ * Get the command usage to be displayed at the top of the built-in help.
441
+ *
442
+ * @param {Command} cmd
443
+ * @returns {string}
444
+ */
445
+ commandUsage(cmd) {
446
+ let cmdName = cmd._name;
447
+ if (cmd._aliases[0]) {
448
+ cmdName = cmdName + "|" + cmd._aliases[0];
449
+ }
450
+ let ancestorCmdNames = "";
451
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
452
+ ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
453
+ }
454
+ return ancestorCmdNames + cmdName + " " + cmd.usage();
455
+ }
456
+ /**
457
+ * Get the description for the command.
458
+ *
459
+ * @param {Command} cmd
460
+ * @returns {string}
461
+ */
462
+ commandDescription(cmd) {
463
+ return cmd.description();
464
+ }
465
+ /**
466
+ * Get the subcommand summary to show in the list of subcommands.
467
+ * (Fallback to description for backwards compatibility.)
468
+ *
469
+ * @param {Command} cmd
470
+ * @returns {string}
471
+ */
472
+ subcommandDescription(cmd) {
473
+ return cmd.summary() || cmd.description();
474
+ }
475
+ /**
476
+ * Get the option description to show in the list of options.
477
+ *
478
+ * @param {Option} option
479
+ * @return {string}
480
+ */
481
+ optionDescription(option) {
482
+ const extraInfo = [];
483
+ if (option.argChoices) {
484
+ extraInfo.push(
485
+ // use stringify to match the display of the default value
486
+ `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
487
+ );
488
+ }
489
+ if (option.defaultValue !== void 0) {
490
+ const showDefault = option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean";
491
+ if (showDefault) {
492
+ extraInfo.push(
493
+ `default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`
494
+ );
495
+ }
496
+ }
497
+ if (option.presetArg !== void 0 && option.optional) {
498
+ extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
499
+ }
500
+ if (option.envVar !== void 0) {
501
+ extraInfo.push(`env: ${option.envVar}`);
502
+ }
503
+ if (extraInfo.length > 0) {
504
+ const extraDescription = `(${extraInfo.join(", ")})`;
505
+ if (option.description) {
506
+ return `${option.description} ${extraDescription}`;
507
+ }
508
+ return extraDescription;
509
+ }
510
+ return option.description;
511
+ }
512
+ /**
513
+ * Get the argument description to show in the list of arguments.
514
+ *
515
+ * @param {Argument} argument
516
+ * @return {string}
517
+ */
518
+ argumentDescription(argument) {
519
+ const extraInfo = [];
520
+ if (argument.argChoices) {
521
+ extraInfo.push(
522
+ // use stringify to match the display of the default value
523
+ `choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
524
+ );
525
+ }
526
+ if (argument.defaultValue !== void 0) {
527
+ extraInfo.push(
528
+ `default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`
529
+ );
530
+ }
531
+ if (extraInfo.length > 0) {
532
+ const extraDescription = `(${extraInfo.join(", ")})`;
533
+ if (argument.description) {
534
+ return `${argument.description} ${extraDescription}`;
535
+ }
536
+ return extraDescription;
537
+ }
538
+ return argument.description;
539
+ }
540
+ /**
541
+ * Format a list of items, given a heading and an array of formatted items.
542
+ *
543
+ * @param {string} heading
544
+ * @param {string[]} items
545
+ * @param {Help} helper
546
+ * @returns string[]
547
+ */
548
+ formatItemList(heading, items, helper) {
549
+ if (items.length === 0) return [];
550
+ return [helper.styleTitle(heading), ...items, ""];
551
+ }
552
+ /**
553
+ * Group items by their help group heading.
554
+ *
555
+ * @param {Command[] | Option[]} unsortedItems
556
+ * @param {Command[] | Option[]} visibleItems
557
+ * @param {Function} getGroup
558
+ * @returns {Map<string, Command[] | Option[]>}
559
+ */
560
+ groupItems(unsortedItems, visibleItems, getGroup) {
561
+ const result = /* @__PURE__ */ new Map();
562
+ unsortedItems.forEach((item) => {
563
+ const group = getGroup(item);
564
+ if (!result.has(group)) result.set(group, []);
565
+ });
566
+ visibleItems.forEach((item) => {
567
+ const group = getGroup(item);
568
+ if (!result.has(group)) {
569
+ result.set(group, []);
570
+ }
571
+ result.get(group).push(item);
572
+ });
573
+ return result;
574
+ }
575
+ /**
576
+ * Generate the built-in help text.
577
+ *
578
+ * @param {Command} cmd
579
+ * @param {Help} helper
580
+ * @returns {string}
581
+ */
582
+ formatHelp(cmd, helper) {
583
+ const termWidth = helper.padWidth(cmd, helper);
584
+ const helpWidth = helper.helpWidth ?? 80;
585
+ function callFormatItem(term, description) {
586
+ return helper.formatItem(term, termWidth, description, helper);
587
+ }
588
+ let output = [
589
+ `${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`,
590
+ ""
591
+ ];
592
+ const commandDescription = helper.commandDescription(cmd);
593
+ if (commandDescription.length > 0) {
594
+ output = output.concat([
595
+ helper.boxWrap(
596
+ helper.styleCommandDescription(commandDescription),
597
+ helpWidth
598
+ ),
599
+ ""
600
+ ]);
601
+ }
602
+ const argumentList = helper.visibleArguments(cmd).map((argument) => {
603
+ return callFormatItem(
604
+ helper.styleArgumentTerm(helper.argumentTerm(argument)),
605
+ helper.styleArgumentDescription(helper.argumentDescription(argument))
606
+ );
607
+ });
608
+ output = output.concat(
609
+ this.formatItemList("Arguments:", argumentList, helper)
610
+ );
611
+ const optionGroups = this.groupItems(
612
+ cmd.options,
613
+ helper.visibleOptions(cmd),
614
+ (option) => option.helpGroupHeading ?? "Options:"
615
+ );
616
+ optionGroups.forEach((options, group) => {
617
+ const optionList = options.map((option) => {
618
+ return callFormatItem(
619
+ helper.styleOptionTerm(helper.optionTerm(option)),
620
+ helper.styleOptionDescription(helper.optionDescription(option))
621
+ );
622
+ });
623
+ output = output.concat(this.formatItemList(group, optionList, helper));
624
+ });
625
+ if (helper.showGlobalOptions) {
626
+ const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
627
+ return callFormatItem(
628
+ helper.styleOptionTerm(helper.optionTerm(option)),
629
+ helper.styleOptionDescription(helper.optionDescription(option))
630
+ );
631
+ });
632
+ output = output.concat(
633
+ this.formatItemList("Global Options:", globalOptionList, helper)
634
+ );
635
+ }
636
+ const commandGroups = this.groupItems(
637
+ cmd.commands,
638
+ helper.visibleCommands(cmd),
639
+ (sub) => sub.helpGroup() || "Commands:"
640
+ );
641
+ commandGroups.forEach((commands, group) => {
642
+ const commandList = commands.map((sub) => {
643
+ return callFormatItem(
644
+ helper.styleSubcommandTerm(helper.subcommandTerm(sub)),
645
+ helper.styleSubcommandDescription(helper.subcommandDescription(sub))
646
+ );
647
+ });
648
+ output = output.concat(this.formatItemList(group, commandList, helper));
649
+ });
650
+ return output.join("\n");
651
+ }
652
+ /**
653
+ * Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations.
654
+ *
655
+ * @param {string} str
656
+ * @returns {number}
657
+ */
658
+ displayWidth(str) {
659
+ return stripColor(str).length;
660
+ }
661
+ /**
662
+ * Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc.
663
+ *
664
+ * @param {string} str
665
+ * @returns {string}
666
+ */
667
+ styleTitle(str) {
668
+ return str;
669
+ }
670
+ styleUsage(str) {
671
+ return str.split(" ").map((word) => {
672
+ if (word === "[options]") return this.styleOptionText(word);
673
+ if (word === "[command]") return this.styleSubcommandText(word);
674
+ if (word[0] === "[" || word[0] === "<")
675
+ return this.styleArgumentText(word);
676
+ return this.styleCommandText(word);
677
+ }).join(" ");
678
+ }
679
+ styleCommandDescription(str) {
680
+ return this.styleDescriptionText(str);
681
+ }
682
+ styleOptionDescription(str) {
683
+ return this.styleDescriptionText(str);
684
+ }
685
+ styleSubcommandDescription(str) {
686
+ return this.styleDescriptionText(str);
687
+ }
688
+ styleArgumentDescription(str) {
689
+ return this.styleDescriptionText(str);
690
+ }
691
+ styleDescriptionText(str) {
692
+ return str;
693
+ }
694
+ styleOptionTerm(str) {
695
+ return this.styleOptionText(str);
696
+ }
697
+ styleSubcommandTerm(str) {
698
+ return str.split(" ").map((word) => {
699
+ if (word === "[options]") return this.styleOptionText(word);
700
+ if (word[0] === "[" || word[0] === "<")
701
+ return this.styleArgumentText(word);
702
+ return this.styleSubcommandText(word);
703
+ }).join(" ");
704
+ }
705
+ styleArgumentTerm(str) {
706
+ return this.styleArgumentText(str);
707
+ }
708
+ styleOptionText(str) {
709
+ return str;
710
+ }
711
+ styleArgumentText(str) {
712
+ return str;
713
+ }
714
+ styleSubcommandText(str) {
715
+ return str;
716
+ }
717
+ styleCommandText(str) {
718
+ return str;
719
+ }
720
+ /**
721
+ * Calculate the pad width from the maximum term length.
722
+ *
723
+ * @param {Command} cmd
724
+ * @param {Help} helper
725
+ * @returns {number}
726
+ */
727
+ padWidth(cmd, helper) {
728
+ return Math.max(
729
+ helper.longestOptionTermLength(cmd, helper),
730
+ helper.longestGlobalOptionTermLength(cmd, helper),
731
+ helper.longestSubcommandTermLength(cmd, helper),
732
+ helper.longestArgumentTermLength(cmd, helper)
733
+ );
734
+ }
735
+ /**
736
+ * Detect manually wrapped and indented strings by checking for line break followed by whitespace.
737
+ *
738
+ * @param {string} str
739
+ * @returns {boolean}
740
+ */
741
+ preformatted(str) {
742
+ return /\n[^\S\r\n]/.test(str);
743
+ }
744
+ /**
745
+ * Format the "item", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.
746
+ *
747
+ * So "TTT", 5, "DDD DDDD DD DDD" might be formatted for this.helpWidth=17 like so:
748
+ * TTT DDD DDDD
749
+ * DD DDD
750
+ *
751
+ * @param {string} term
752
+ * @param {number} termWidth
753
+ * @param {string} description
754
+ * @param {Help} helper
755
+ * @returns {string}
756
+ */
757
+ formatItem(term, termWidth, description, helper) {
758
+ const itemIndent = 2;
759
+ const itemIndentStr = " ".repeat(itemIndent);
760
+ if (!description) return itemIndentStr + term;
761
+ const paddedTerm = term.padEnd(
762
+ termWidth + term.length - helper.displayWidth(term)
763
+ );
764
+ const spacerWidth = 2;
765
+ const helpWidth = this.helpWidth ?? 80;
766
+ const remainingWidth = helpWidth - termWidth - spacerWidth - itemIndent;
767
+ let formattedDescription;
768
+ if (remainingWidth < this.minWidthToWrap || helper.preformatted(description)) {
769
+ formattedDescription = description;
770
+ } else {
771
+ const wrappedDescription = helper.boxWrap(description, remainingWidth);
772
+ formattedDescription = wrappedDescription.replace(
773
+ /\n/g,
774
+ "\n" + " ".repeat(termWidth + spacerWidth)
775
+ );
776
+ }
777
+ return itemIndentStr + paddedTerm + " ".repeat(spacerWidth) + formattedDescription.replace(/\n/g, `
778
+ ${itemIndentStr}`);
779
+ }
780
+ /**
781
+ * Wrap a string at whitespace, preserving existing line breaks.
782
+ * Wrapping is skipped if the width is less than `minWidthToWrap`.
783
+ *
784
+ * @param {string} str
785
+ * @param {number} width
786
+ * @returns {string}
787
+ */
788
+ boxWrap(str, width) {
789
+ if (width < this.minWidthToWrap) return str;
790
+ const rawLines = str.split(/\r\n|\n/);
791
+ const chunkPattern = /[\s]*[^\s]+/g;
792
+ const wrappedLines = [];
793
+ rawLines.forEach((line) => {
794
+ const chunks = line.match(chunkPattern);
795
+ if (chunks === null) {
796
+ wrappedLines.push("");
797
+ return;
798
+ }
799
+ let sumChunks = [chunks.shift()];
800
+ let sumWidth = this.displayWidth(sumChunks[0]);
801
+ chunks.forEach((chunk) => {
802
+ const visibleWidth = this.displayWidth(chunk);
803
+ if (sumWidth + visibleWidth <= width) {
804
+ sumChunks.push(chunk);
805
+ sumWidth += visibleWidth;
806
+ return;
807
+ }
808
+ wrappedLines.push(sumChunks.join(""));
809
+ const nextChunk = chunk.trimStart();
810
+ sumChunks = [nextChunk];
811
+ sumWidth = this.displayWidth(nextChunk);
812
+ });
813
+ wrappedLines.push(sumChunks.join(""));
814
+ });
815
+ return wrappedLines.join("\n");
816
+ }
817
+ };
818
+ function stripColor(str) {
819
+ const sgrPattern = /\x1b\[\d*(;\d*)*m/g;
820
+ return str.replace(sgrPattern, "");
821
+ }
822
+ exports.Help = Help2;
823
+ exports.stripColor = stripColor;
824
+ }
825
+ });
826
+
827
+ // ../../node_modules/.pnpm/commander@14.0.3/node_modules/commander/lib/option.js
828
+ var require_option = __commonJS({
829
+ "../../node_modules/.pnpm/commander@14.0.3/node_modules/commander/lib/option.js"(exports) {
830
+ "use strict";
831
+ var { InvalidArgumentError: InvalidArgumentError2 } = require_error();
832
+ var Option2 = class {
833
+ /**
834
+ * Initialize a new `Option` with the given `flags` and `description`.
835
+ *
836
+ * @param {string} flags
837
+ * @param {string} [description]
838
+ */
839
+ constructor(flags, description) {
840
+ this.flags = flags;
841
+ this.description = description || "";
842
+ this.required = flags.includes("<");
843
+ this.optional = flags.includes("[");
844
+ this.variadic = /\w\.\.\.[>\]]$/.test(flags);
845
+ this.mandatory = false;
846
+ const optionFlags = splitOptionFlags(flags);
847
+ this.short = optionFlags.shortFlag;
848
+ this.long = optionFlags.longFlag;
849
+ this.negate = false;
850
+ if (this.long) {
851
+ this.negate = this.long.startsWith("--no-");
852
+ }
853
+ this.defaultValue = void 0;
854
+ this.defaultValueDescription = void 0;
855
+ this.presetArg = void 0;
856
+ this.envVar = void 0;
857
+ this.parseArg = void 0;
858
+ this.hidden = false;
859
+ this.argChoices = void 0;
860
+ this.conflictsWith = [];
861
+ this.implied = void 0;
862
+ this.helpGroupHeading = void 0;
863
+ }
864
+ /**
865
+ * Set the default value, and optionally supply the description to be displayed in the help.
866
+ *
867
+ * @param {*} value
868
+ * @param {string} [description]
869
+ * @return {Option}
870
+ */
871
+ default(value, description) {
872
+ this.defaultValue = value;
873
+ this.defaultValueDescription = description;
874
+ return this;
875
+ }
876
+ /**
877
+ * Preset to use when option used without option-argument, especially optional but also boolean and negated.
878
+ * The custom processing (parseArg) is called.
879
+ *
880
+ * @example
881
+ * new Option('--color').default('GREYSCALE').preset('RGB');
882
+ * new Option('--donate [amount]').preset('20').argParser(parseFloat);
883
+ *
884
+ * @param {*} arg
885
+ * @return {Option}
886
+ */
887
+ preset(arg) {
888
+ this.presetArg = arg;
889
+ return this;
890
+ }
891
+ /**
892
+ * Add option name(s) that conflict with this option.
893
+ * An error will be displayed if conflicting options are found during parsing.
894
+ *
895
+ * @example
896
+ * new Option('--rgb').conflicts('cmyk');
897
+ * new Option('--js').conflicts(['ts', 'jsx']);
898
+ *
899
+ * @param {(string | string[])} names
900
+ * @return {Option}
901
+ */
902
+ conflicts(names) {
903
+ this.conflictsWith = this.conflictsWith.concat(names);
904
+ return this;
905
+ }
906
+ /**
907
+ * Specify implied option values for when this option is set and the implied options are not.
908
+ *
909
+ * The custom processing (parseArg) is not called on the implied values.
910
+ *
911
+ * @example
912
+ * program
913
+ * .addOption(new Option('--log', 'write logging information to file'))
914
+ * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
915
+ *
916
+ * @param {object} impliedOptionValues
917
+ * @return {Option}
918
+ */
919
+ implies(impliedOptionValues) {
920
+ let newImplied = impliedOptionValues;
921
+ if (typeof impliedOptionValues === "string") {
922
+ newImplied = { [impliedOptionValues]: true };
923
+ }
924
+ this.implied = Object.assign(this.implied || {}, newImplied);
925
+ return this;
926
+ }
927
+ /**
928
+ * Set environment variable to check for option value.
929
+ *
930
+ * An environment variable is only used if when processed the current option value is
931
+ * undefined, or the source of the current value is 'default' or 'config' or 'env'.
932
+ *
933
+ * @param {string} name
934
+ * @return {Option}
935
+ */
936
+ env(name) {
937
+ this.envVar = name;
938
+ return this;
939
+ }
940
+ /**
941
+ * Set the custom handler for processing CLI option arguments into option values.
942
+ *
943
+ * @param {Function} [fn]
944
+ * @return {Option}
945
+ */
946
+ argParser(fn) {
947
+ this.parseArg = fn;
948
+ return this;
949
+ }
950
+ /**
951
+ * Whether the option is mandatory and must have a value after parsing.
952
+ *
953
+ * @param {boolean} [mandatory=true]
954
+ * @return {Option}
955
+ */
956
+ makeOptionMandatory(mandatory = true) {
957
+ this.mandatory = !!mandatory;
958
+ return this;
959
+ }
960
+ /**
961
+ * Hide option in help.
962
+ *
963
+ * @param {boolean} [hide=true]
964
+ * @return {Option}
965
+ */
966
+ hideHelp(hide = true) {
967
+ this.hidden = !!hide;
968
+ return this;
969
+ }
970
+ /**
971
+ * @package
972
+ */
973
+ _collectValue(value, previous) {
974
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
975
+ return [value];
976
+ }
977
+ previous.push(value);
978
+ return previous;
979
+ }
980
+ /**
981
+ * Only allow option value to be one of choices.
982
+ *
983
+ * @param {string[]} values
984
+ * @return {Option}
985
+ */
986
+ choices(values) {
987
+ this.argChoices = values.slice();
988
+ this.parseArg = (arg, previous) => {
989
+ if (!this.argChoices.includes(arg)) {
990
+ throw new InvalidArgumentError2(
991
+ `Allowed choices are ${this.argChoices.join(", ")}.`
992
+ );
993
+ }
994
+ if (this.variadic) {
995
+ return this._collectValue(arg, previous);
996
+ }
997
+ return arg;
998
+ };
999
+ return this;
1000
+ }
1001
+ /**
1002
+ * Return option name.
1003
+ *
1004
+ * @return {string}
1005
+ */
1006
+ name() {
1007
+ if (this.long) {
1008
+ return this.long.replace(/^--/, "");
1009
+ }
1010
+ return this.short.replace(/^-/, "");
1011
+ }
1012
+ /**
1013
+ * Return option name, in a camelcase format that can be used
1014
+ * as an object attribute key.
1015
+ *
1016
+ * @return {string}
1017
+ */
1018
+ attributeName() {
1019
+ if (this.negate) {
1020
+ return camelcase(this.name().replace(/^no-/, ""));
1021
+ }
1022
+ return camelcase(this.name());
1023
+ }
1024
+ /**
1025
+ * Set the help group heading.
1026
+ *
1027
+ * @param {string} heading
1028
+ * @return {Option}
1029
+ */
1030
+ helpGroup(heading) {
1031
+ this.helpGroupHeading = heading;
1032
+ return this;
1033
+ }
1034
+ /**
1035
+ * Check if `arg` matches the short or long flag.
1036
+ *
1037
+ * @param {string} arg
1038
+ * @return {boolean}
1039
+ * @package
1040
+ */
1041
+ is(arg) {
1042
+ return this.short === arg || this.long === arg;
1043
+ }
1044
+ /**
1045
+ * Return whether a boolean option.
1046
+ *
1047
+ * Options are one of boolean, negated, required argument, or optional argument.
1048
+ *
1049
+ * @return {boolean}
1050
+ * @package
1051
+ */
1052
+ isBoolean() {
1053
+ return !this.required && !this.optional && !this.negate;
1054
+ }
1055
+ };
1056
+ var DualOptions = class {
1057
+ /**
1058
+ * @param {Option[]} options
1059
+ */
1060
+ constructor(options) {
1061
+ this.positiveOptions = /* @__PURE__ */ new Map();
1062
+ this.negativeOptions = /* @__PURE__ */ new Map();
1063
+ this.dualOptions = /* @__PURE__ */ new Set();
1064
+ options.forEach((option) => {
1065
+ if (option.negate) {
1066
+ this.negativeOptions.set(option.attributeName(), option);
1067
+ } else {
1068
+ this.positiveOptions.set(option.attributeName(), option);
1069
+ }
1070
+ });
1071
+ this.negativeOptions.forEach((value, key) => {
1072
+ if (this.positiveOptions.has(key)) {
1073
+ this.dualOptions.add(key);
1074
+ }
1075
+ });
1076
+ }
1077
+ /**
1078
+ * Did the value come from the option, and not from possible matching dual option?
1079
+ *
1080
+ * @param {*} value
1081
+ * @param {Option} option
1082
+ * @returns {boolean}
1083
+ */
1084
+ valueFromOption(value, option) {
1085
+ const optionKey = option.attributeName();
1086
+ if (!this.dualOptions.has(optionKey)) return true;
1087
+ const preset = this.negativeOptions.get(optionKey).presetArg;
1088
+ const negativeValue = preset !== void 0 ? preset : false;
1089
+ return option.negate === (negativeValue === value);
1090
+ }
1091
+ };
1092
+ function camelcase(str) {
1093
+ return str.split("-").reduce((str2, word) => {
1094
+ return str2 + word[0].toUpperCase() + word.slice(1);
1095
+ });
1096
+ }
1097
+ function splitOptionFlags(flags) {
1098
+ let shortFlag;
1099
+ let longFlag;
1100
+ const shortFlagExp = /^-[^-]$/;
1101
+ const longFlagExp = /^--[^-]/;
1102
+ const flagParts = flags.split(/[ |,]+/).concat("guard");
1103
+ if (shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();
1104
+ if (longFlagExp.test(flagParts[0])) longFlag = flagParts.shift();
1105
+ if (!shortFlag && shortFlagExp.test(flagParts[0]))
1106
+ shortFlag = flagParts.shift();
1107
+ if (!shortFlag && longFlagExp.test(flagParts[0])) {
1108
+ shortFlag = longFlag;
1109
+ longFlag = flagParts.shift();
1110
+ }
1111
+ if (flagParts[0].startsWith("-")) {
1112
+ const unsupportedFlag = flagParts[0];
1113
+ const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;
1114
+ if (/^-[^-][^-]/.test(unsupportedFlag))
1115
+ throw new Error(
1116
+ `${baseError}
1117
+ - a short flag is a single dash and a single character
1118
+ - either use a single dash and a single character (for a short flag)
1119
+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`
1120
+ );
1121
+ if (shortFlagExp.test(unsupportedFlag))
1122
+ throw new Error(`${baseError}
1123
+ - too many short flags`);
1124
+ if (longFlagExp.test(unsupportedFlag))
1125
+ throw new Error(`${baseError}
1126
+ - too many long flags`);
1127
+ throw new Error(`${baseError}
1128
+ - unrecognised flag format`);
1129
+ }
1130
+ if (shortFlag === void 0 && longFlag === void 0)
1131
+ throw new Error(
1132
+ `option creation failed due to no flags found in '${flags}'.`
1133
+ );
1134
+ return { shortFlag, longFlag };
1135
+ }
1136
+ exports.Option = Option2;
1137
+ exports.DualOptions = DualOptions;
1138
+ }
1139
+ });
1140
+
1141
+ // ../../node_modules/.pnpm/commander@14.0.3/node_modules/commander/lib/suggestSimilar.js
1142
+ var require_suggestSimilar = __commonJS({
1143
+ "../../node_modules/.pnpm/commander@14.0.3/node_modules/commander/lib/suggestSimilar.js"(exports) {
1144
+ "use strict";
1145
+ var maxDistance = 3;
1146
+ function editDistance(a, b) {
1147
+ if (Math.abs(a.length - b.length) > maxDistance)
1148
+ return Math.max(a.length, b.length);
1149
+ const d = [];
1150
+ for (let i = 0; i <= a.length; i++) {
1151
+ d[i] = [i];
1152
+ }
1153
+ for (let j = 0; j <= b.length; j++) {
1154
+ d[0][j] = j;
1155
+ }
1156
+ for (let j = 1; j <= b.length; j++) {
1157
+ for (let i = 1; i <= a.length; i++) {
1158
+ let cost = 1;
1159
+ if (a[i - 1] === b[j - 1]) {
1160
+ cost = 0;
1161
+ } else {
1162
+ cost = 1;
1163
+ }
1164
+ d[i][j] = Math.min(
1165
+ d[i - 1][j] + 1,
1166
+ // deletion
1167
+ d[i][j - 1] + 1,
1168
+ // insertion
1169
+ d[i - 1][j - 1] + cost
1170
+ // substitution
1171
+ );
1172
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
1173
+ d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
1174
+ }
1175
+ }
1176
+ }
1177
+ return d[a.length][b.length];
1178
+ }
1179
+ function suggestSimilar(word, candidates) {
1180
+ if (!candidates || candidates.length === 0) return "";
1181
+ candidates = Array.from(new Set(candidates));
1182
+ const searchingOptions = word.startsWith("--");
1183
+ if (searchingOptions) {
1184
+ word = word.slice(2);
1185
+ candidates = candidates.map((candidate) => candidate.slice(2));
1186
+ }
1187
+ let similar = [];
1188
+ let bestDistance = maxDistance;
1189
+ const minSimilarity = 0.4;
1190
+ candidates.forEach((candidate) => {
1191
+ if (candidate.length <= 1) return;
1192
+ const distance = editDistance(word, candidate);
1193
+ const length = Math.max(word.length, candidate.length);
1194
+ const similarity = (length - distance) / length;
1195
+ if (similarity > minSimilarity) {
1196
+ if (distance < bestDistance) {
1197
+ bestDistance = distance;
1198
+ similar = [candidate];
1199
+ } else if (distance === bestDistance) {
1200
+ similar.push(candidate);
1201
+ }
1202
+ }
1203
+ });
1204
+ similar.sort((a, b) => a.localeCompare(b));
1205
+ if (searchingOptions) {
1206
+ similar = similar.map((candidate) => `--${candidate}`);
1207
+ }
1208
+ if (similar.length > 1) {
1209
+ return `
1210
+ (Did you mean one of ${similar.join(", ")}?)`;
1211
+ }
1212
+ if (similar.length === 1) {
1213
+ return `
1214
+ (Did you mean ${similar[0]}?)`;
1215
+ }
1216
+ return "";
1217
+ }
1218
+ exports.suggestSimilar = suggestSimilar;
1219
+ }
1220
+ });
1221
+
1222
+ // ../../node_modules/.pnpm/commander@14.0.3/node_modules/commander/lib/command.js
1223
+ var require_command = __commonJS({
1224
+ "../../node_modules/.pnpm/commander@14.0.3/node_modules/commander/lib/command.js"(exports) {
1225
+ "use strict";
1226
+ var EventEmitter = __require("events").EventEmitter;
1227
+ var childProcess = __require("child_process");
1228
+ var path = __require("path");
1229
+ var fs = __require("fs");
1230
+ var process2 = __require("process");
1231
+ var { Argument: Argument2, humanReadableArgName } = require_argument();
1232
+ var { CommanderError: CommanderError2 } = require_error();
1233
+ var { Help: Help2, stripColor } = require_help();
1234
+ var { Option: Option2, DualOptions } = require_option();
1235
+ var { suggestSimilar } = require_suggestSimilar();
1236
+ var Command2 = class _Command extends EventEmitter {
1237
+ /**
1238
+ * Initialize a new `Command`.
1239
+ *
1240
+ * @param {string} [name]
1241
+ */
1242
+ constructor(name) {
1243
+ super();
1244
+ this.commands = [];
1245
+ this.options = [];
1246
+ this.parent = null;
1247
+ this._allowUnknownOption = false;
1248
+ this._allowExcessArguments = false;
1249
+ this.registeredArguments = [];
1250
+ this._args = this.registeredArguments;
1251
+ this.args = [];
1252
+ this.rawArgs = [];
1253
+ this.processedArgs = [];
1254
+ this._scriptPath = null;
1255
+ this._name = name || "";
1256
+ this._optionValues = {};
1257
+ this._optionValueSources = {};
1258
+ this._storeOptionsAsProperties = false;
1259
+ this._actionHandler = null;
1260
+ this._executableHandler = false;
1261
+ this._executableFile = null;
1262
+ this._executableDir = null;
1263
+ this._defaultCommandName = null;
1264
+ this._exitCallback = null;
1265
+ this._aliases = [];
1266
+ this._combineFlagAndOptionalValue = true;
1267
+ this._description = "";
1268
+ this._summary = "";
1269
+ this._argsDescription = void 0;
1270
+ this._enablePositionalOptions = false;
1271
+ this._passThroughOptions = false;
1272
+ this._lifeCycleHooks = {};
1273
+ this._showHelpAfterError = false;
1274
+ this._showSuggestionAfterError = true;
1275
+ this._savedState = null;
1276
+ this._outputConfiguration = {
1277
+ writeOut: (str) => process2.stdout.write(str),
1278
+ writeErr: (str) => process2.stderr.write(str),
1279
+ outputError: (str, write) => write(str),
1280
+ getOutHelpWidth: () => process2.stdout.isTTY ? process2.stdout.columns : void 0,
1281
+ getErrHelpWidth: () => process2.stderr.isTTY ? process2.stderr.columns : void 0,
1282
+ getOutHasColors: () => useColor() ?? (process2.stdout.isTTY && process2.stdout.hasColors?.()),
1283
+ getErrHasColors: () => useColor() ?? (process2.stderr.isTTY && process2.stderr.hasColors?.()),
1284
+ stripColor: (str) => stripColor(str)
1285
+ };
1286
+ this._hidden = false;
1287
+ this._helpOption = void 0;
1288
+ this._addImplicitHelpCommand = void 0;
1289
+ this._helpCommand = void 0;
1290
+ this._helpConfiguration = {};
1291
+ this._helpGroupHeading = void 0;
1292
+ this._defaultCommandGroup = void 0;
1293
+ this._defaultOptionGroup = void 0;
1294
+ }
1295
+ /**
1296
+ * Copy settings that are useful to have in common across root command and subcommands.
1297
+ *
1298
+ * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
1299
+ *
1300
+ * @param {Command} sourceCommand
1301
+ * @return {Command} `this` command for chaining
1302
+ */
1303
+ copyInheritedSettings(sourceCommand) {
1304
+ this._outputConfiguration = sourceCommand._outputConfiguration;
1305
+ this._helpOption = sourceCommand._helpOption;
1306
+ this._helpCommand = sourceCommand._helpCommand;
1307
+ this._helpConfiguration = sourceCommand._helpConfiguration;
1308
+ this._exitCallback = sourceCommand._exitCallback;
1309
+ this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
1310
+ this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
1311
+ this._allowExcessArguments = sourceCommand._allowExcessArguments;
1312
+ this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
1313
+ this._showHelpAfterError = sourceCommand._showHelpAfterError;
1314
+ this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
1315
+ return this;
1316
+ }
1317
+ /**
1318
+ * @returns {Command[]}
1319
+ * @private
1320
+ */
1321
+ _getCommandAndAncestors() {
1322
+ const result = [];
1323
+ for (let command = this; command; command = command.parent) {
1324
+ result.push(command);
1325
+ }
1326
+ return result;
1327
+ }
1328
+ /**
1329
+ * Define a command.
1330
+ *
1331
+ * There are two styles of command: pay attention to where to put the description.
1332
+ *
1333
+ * @example
1334
+ * // Command implemented using action handler (description is supplied separately to `.command`)
1335
+ * program
1336
+ * .command('clone <source> [destination]')
1337
+ * .description('clone a repository into a newly created directory')
1338
+ * .action((source, destination) => {
1339
+ * console.log('clone command called');
1340
+ * });
1341
+ *
1342
+ * // Command implemented using separate executable file (description is second parameter to `.command`)
1343
+ * program
1344
+ * .command('start <service>', 'start named service')
1345
+ * .command('stop [service]', 'stop named service, or all if no name supplied');
1346
+ *
1347
+ * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
1348
+ * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
1349
+ * @param {object} [execOpts] - configuration options (for executable)
1350
+ * @return {Command} returns new command for action handler, or `this` for executable command
1351
+ */
1352
+ command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
1353
+ let desc = actionOptsOrExecDesc;
1354
+ let opts = execOpts;
1355
+ if (typeof desc === "object" && desc !== null) {
1356
+ opts = desc;
1357
+ desc = null;
1358
+ }
1359
+ opts = opts || {};
1360
+ const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
1361
+ const cmd = this.createCommand(name);
1362
+ if (desc) {
1363
+ cmd.description(desc);
1364
+ cmd._executableHandler = true;
1365
+ }
1366
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
1367
+ cmd._hidden = !!(opts.noHelp || opts.hidden);
1368
+ cmd._executableFile = opts.executableFile || null;
1369
+ if (args) cmd.arguments(args);
1370
+ this._registerCommand(cmd);
1371
+ cmd.parent = this;
1372
+ cmd.copyInheritedSettings(this);
1373
+ if (desc) return this;
1374
+ return cmd;
1375
+ }
1376
+ /**
1377
+ * Factory routine to create a new unattached command.
1378
+ *
1379
+ * See .command() for creating an attached subcommand, which uses this routine to
1380
+ * create the command. You can override createCommand to customise subcommands.
1381
+ *
1382
+ * @param {string} [name]
1383
+ * @return {Command} new command
1384
+ */
1385
+ createCommand(name) {
1386
+ return new _Command(name);
1387
+ }
1388
+ /**
1389
+ * You can customise the help with a subclass of Help by overriding createHelp,
1390
+ * or by overriding Help properties using configureHelp().
1391
+ *
1392
+ * @return {Help}
1393
+ */
1394
+ createHelp() {
1395
+ return Object.assign(new Help2(), this.configureHelp());
1396
+ }
1397
+ /**
1398
+ * You can customise the help by overriding Help properties using configureHelp(),
1399
+ * or with a subclass of Help by overriding createHelp().
1400
+ *
1401
+ * @param {object} [configuration] - configuration options
1402
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
1403
+ */
1404
+ configureHelp(configuration) {
1405
+ if (configuration === void 0) return this._helpConfiguration;
1406
+ this._helpConfiguration = configuration;
1407
+ return this;
1408
+ }
1409
+ /**
1410
+ * The default output goes to stdout and stderr. You can customise this for special
1411
+ * applications. You can also customise the display of errors by overriding outputError.
1412
+ *
1413
+ * The configuration properties are all functions:
1414
+ *
1415
+ * // change how output being written, defaults to stdout and stderr
1416
+ * writeOut(str)
1417
+ * writeErr(str)
1418
+ * // change how output being written for errors, defaults to writeErr
1419
+ * outputError(str, write) // used for displaying errors and not used for displaying help
1420
+ * // specify width for wrapping help
1421
+ * getOutHelpWidth()
1422
+ * getErrHelpWidth()
1423
+ * // color support, currently only used with Help
1424
+ * getOutHasColors()
1425
+ * getErrHasColors()
1426
+ * stripColor() // used to remove ANSI escape codes if output does not have colors
1427
+ *
1428
+ * @param {object} [configuration] - configuration options
1429
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
1430
+ */
1431
+ configureOutput(configuration) {
1432
+ if (configuration === void 0) return this._outputConfiguration;
1433
+ this._outputConfiguration = {
1434
+ ...this._outputConfiguration,
1435
+ ...configuration
1436
+ };
1437
+ return this;
1438
+ }
1439
+ /**
1440
+ * Display the help or a custom message after an error occurs.
1441
+ *
1442
+ * @param {(boolean|string)} [displayHelp]
1443
+ * @return {Command} `this` command for chaining
1444
+ */
1445
+ showHelpAfterError(displayHelp = true) {
1446
+ if (typeof displayHelp !== "string") displayHelp = !!displayHelp;
1447
+ this._showHelpAfterError = displayHelp;
1448
+ return this;
1449
+ }
1450
+ /**
1451
+ * Display suggestion of similar commands for unknown commands, or options for unknown options.
1452
+ *
1453
+ * @param {boolean} [displaySuggestion]
1454
+ * @return {Command} `this` command for chaining
1455
+ */
1456
+ showSuggestionAfterError(displaySuggestion = true) {
1457
+ this._showSuggestionAfterError = !!displaySuggestion;
1458
+ return this;
1459
+ }
1460
+ /**
1461
+ * Add a prepared subcommand.
1462
+ *
1463
+ * See .command() for creating an attached subcommand which inherits settings from its parent.
1464
+ *
1465
+ * @param {Command} cmd - new subcommand
1466
+ * @param {object} [opts] - configuration options
1467
+ * @return {Command} `this` command for chaining
1468
+ */
1469
+ addCommand(cmd, opts) {
1470
+ if (!cmd._name) {
1471
+ throw new Error(`Command passed to .addCommand() must have a name
1472
+ - specify the name in Command constructor or using .name()`);
1473
+ }
1474
+ opts = opts || {};
1475
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
1476
+ if (opts.noHelp || opts.hidden) cmd._hidden = true;
1477
+ this._registerCommand(cmd);
1478
+ cmd.parent = this;
1479
+ cmd._checkForBrokenPassThrough();
1480
+ return this;
1481
+ }
1482
+ /**
1483
+ * Factory routine to create a new unattached argument.
1484
+ *
1485
+ * See .argument() for creating an attached argument, which uses this routine to
1486
+ * create the argument. You can override createArgument to return a custom argument.
1487
+ *
1488
+ * @param {string} name
1489
+ * @param {string} [description]
1490
+ * @return {Argument} new argument
1491
+ */
1492
+ createArgument(name, description) {
1493
+ return new Argument2(name, description);
1494
+ }
1495
+ /**
1496
+ * Define argument syntax for command.
1497
+ *
1498
+ * The default is that the argument is required, and you can explicitly
1499
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
1500
+ *
1501
+ * @example
1502
+ * program.argument('<input-file>');
1503
+ * program.argument('[output-file]');
1504
+ *
1505
+ * @param {string} name
1506
+ * @param {string} [description]
1507
+ * @param {(Function|*)} [parseArg] - custom argument processing function or default value
1508
+ * @param {*} [defaultValue]
1509
+ * @return {Command} `this` command for chaining
1510
+ */
1511
+ argument(name, description, parseArg, defaultValue) {
1512
+ const argument = this.createArgument(name, description);
1513
+ if (typeof parseArg === "function") {
1514
+ argument.default(defaultValue).argParser(parseArg);
1515
+ } else {
1516
+ argument.default(parseArg);
1517
+ }
1518
+ this.addArgument(argument);
1519
+ return this;
1520
+ }
1521
+ /**
1522
+ * Define argument syntax for command, adding multiple at once (without descriptions).
1523
+ *
1524
+ * See also .argument().
1525
+ *
1526
+ * @example
1527
+ * program.arguments('<cmd> [env]');
1528
+ *
1529
+ * @param {string} names
1530
+ * @return {Command} `this` command for chaining
1531
+ */
1532
+ arguments(names) {
1533
+ names.trim().split(/ +/).forEach((detail) => {
1534
+ this.argument(detail);
1535
+ });
1536
+ return this;
1537
+ }
1538
+ /**
1539
+ * Define argument syntax for command, adding a prepared argument.
1540
+ *
1541
+ * @param {Argument} argument
1542
+ * @return {Command} `this` command for chaining
1543
+ */
1544
+ addArgument(argument) {
1545
+ const previousArgument = this.registeredArguments.slice(-1)[0];
1546
+ if (previousArgument?.variadic) {
1547
+ throw new Error(
1548
+ `only the last argument can be variadic '${previousArgument.name()}'`
1549
+ );
1550
+ }
1551
+ if (argument.required && argument.defaultValue !== void 0 && argument.parseArg === void 0) {
1552
+ throw new Error(
1553
+ `a default value for a required argument is never used: '${argument.name()}'`
1554
+ );
1555
+ }
1556
+ this.registeredArguments.push(argument);
1557
+ return this;
1558
+ }
1559
+ /**
1560
+ * Customise or override default help command. By default a help command is automatically added if your command has subcommands.
1561
+ *
1562
+ * @example
1563
+ * program.helpCommand('help [cmd]');
1564
+ * program.helpCommand('help [cmd]', 'show help');
1565
+ * program.helpCommand(false); // suppress default help command
1566
+ * program.helpCommand(true); // add help command even if no subcommands
1567
+ *
1568
+ * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added
1569
+ * @param {string} [description] - custom description
1570
+ * @return {Command} `this` command for chaining
1571
+ */
1572
+ helpCommand(enableOrNameAndArgs, description) {
1573
+ if (typeof enableOrNameAndArgs === "boolean") {
1574
+ this._addImplicitHelpCommand = enableOrNameAndArgs;
1575
+ if (enableOrNameAndArgs && this._defaultCommandGroup) {
1576
+ this._initCommandGroup(this._getHelpCommand());
1577
+ }
1578
+ return this;
1579
+ }
1580
+ const nameAndArgs = enableOrNameAndArgs ?? "help [command]";
1581
+ const [, helpName, helpArgs] = nameAndArgs.match(/([^ ]+) *(.*)/);
1582
+ const helpDescription = description ?? "display help for command";
1583
+ const helpCommand = this.createCommand(helpName);
1584
+ helpCommand.helpOption(false);
1585
+ if (helpArgs) helpCommand.arguments(helpArgs);
1586
+ if (helpDescription) helpCommand.description(helpDescription);
1587
+ this._addImplicitHelpCommand = true;
1588
+ this._helpCommand = helpCommand;
1589
+ if (enableOrNameAndArgs || description) this._initCommandGroup(helpCommand);
1590
+ return this;
1591
+ }
1592
+ /**
1593
+ * Add prepared custom help command.
1594
+ *
1595
+ * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`
1596
+ * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only
1597
+ * @return {Command} `this` command for chaining
1598
+ */
1599
+ addHelpCommand(helpCommand, deprecatedDescription) {
1600
+ if (typeof helpCommand !== "object") {
1601
+ this.helpCommand(helpCommand, deprecatedDescription);
1602
+ return this;
1603
+ }
1604
+ this._addImplicitHelpCommand = true;
1605
+ this._helpCommand = helpCommand;
1606
+ this._initCommandGroup(helpCommand);
1607
+ return this;
1608
+ }
1609
+ /**
1610
+ * Lazy create help command.
1611
+ *
1612
+ * @return {(Command|null)}
1613
+ * @package
1614
+ */
1615
+ _getHelpCommand() {
1616
+ const hasImplicitHelpCommand = this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"));
1617
+ if (hasImplicitHelpCommand) {
1618
+ if (this._helpCommand === void 0) {
1619
+ this.helpCommand(void 0, void 0);
1620
+ }
1621
+ return this._helpCommand;
1622
+ }
1623
+ return null;
1624
+ }
1625
+ /**
1626
+ * Add hook for life cycle event.
1627
+ *
1628
+ * @param {string} event
1629
+ * @param {Function} listener
1630
+ * @return {Command} `this` command for chaining
1631
+ */
1632
+ hook(event, listener) {
1633
+ const allowedValues = ["preSubcommand", "preAction", "postAction"];
1634
+ if (!allowedValues.includes(event)) {
1635
+ throw new Error(`Unexpected value for event passed to hook : '${event}'.
1636
+ Expecting one of '${allowedValues.join("', '")}'`);
1637
+ }
1638
+ if (this._lifeCycleHooks[event]) {
1639
+ this._lifeCycleHooks[event].push(listener);
1640
+ } else {
1641
+ this._lifeCycleHooks[event] = [listener];
1642
+ }
1643
+ return this;
1644
+ }
1645
+ /**
1646
+ * Register callback to use as replacement for calling process.exit.
1647
+ *
1648
+ * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
1649
+ * @return {Command} `this` command for chaining
1650
+ */
1651
+ exitOverride(fn) {
1652
+ if (fn) {
1653
+ this._exitCallback = fn;
1654
+ } else {
1655
+ this._exitCallback = (err) => {
1656
+ if (err.code !== "commander.executeSubCommandAsync") {
1657
+ throw err;
1658
+ } else {
1659
+ }
1660
+ };
1661
+ }
1662
+ return this;
1663
+ }
1664
+ /**
1665
+ * Call process.exit, and _exitCallback if defined.
1666
+ *
1667
+ * @param {number} exitCode exit code for using with process.exit
1668
+ * @param {string} code an id string representing the error
1669
+ * @param {string} message human-readable description of the error
1670
+ * @return never
1671
+ * @private
1672
+ */
1673
+ _exit(exitCode, code, message) {
1674
+ if (this._exitCallback) {
1675
+ this._exitCallback(new CommanderError2(exitCode, code, message));
1676
+ }
1677
+ process2.exit(exitCode);
1678
+ }
1679
+ /**
1680
+ * Register callback `fn` for the command.
1681
+ *
1682
+ * @example
1683
+ * program
1684
+ * .command('serve')
1685
+ * .description('start service')
1686
+ * .action(function() {
1687
+ * // do work here
1688
+ * });
1689
+ *
1690
+ * @param {Function} fn
1691
+ * @return {Command} `this` command for chaining
1692
+ */
1693
+ action(fn) {
1694
+ const listener = (args) => {
1695
+ const expectedArgsCount = this.registeredArguments.length;
1696
+ const actionArgs = args.slice(0, expectedArgsCount);
1697
+ if (this._storeOptionsAsProperties) {
1698
+ actionArgs[expectedArgsCount] = this;
1699
+ } else {
1700
+ actionArgs[expectedArgsCount] = this.opts();
1701
+ }
1702
+ actionArgs.push(this);
1703
+ return fn.apply(this, actionArgs);
1704
+ };
1705
+ this._actionHandler = listener;
1706
+ return this;
1707
+ }
1708
+ /**
1709
+ * Factory routine to create a new unattached option.
1710
+ *
1711
+ * See .option() for creating an attached option, which uses this routine to
1712
+ * create the option. You can override createOption to return a custom option.
1713
+ *
1714
+ * @param {string} flags
1715
+ * @param {string} [description]
1716
+ * @return {Option} new option
1717
+ */
1718
+ createOption(flags, description) {
1719
+ return new Option2(flags, description);
1720
+ }
1721
+ /**
1722
+ * Wrap parseArgs to catch 'commander.invalidArgument'.
1723
+ *
1724
+ * @param {(Option | Argument)} target
1725
+ * @param {string} value
1726
+ * @param {*} previous
1727
+ * @param {string} invalidArgumentMessage
1728
+ * @private
1729
+ */
1730
+ _callParseArg(target, value, previous, invalidArgumentMessage) {
1731
+ try {
1732
+ return target.parseArg(value, previous);
1733
+ } catch (err) {
1734
+ if (err.code === "commander.invalidArgument") {
1735
+ const message = `${invalidArgumentMessage} ${err.message}`;
1736
+ this.error(message, { exitCode: err.exitCode, code: err.code });
1737
+ }
1738
+ throw err;
1739
+ }
1740
+ }
1741
+ /**
1742
+ * Check for option flag conflicts.
1743
+ * Register option if no conflicts found, or throw on conflict.
1744
+ *
1745
+ * @param {Option} option
1746
+ * @private
1747
+ */
1748
+ _registerOption(option) {
1749
+ const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
1750
+ if (matchingOption) {
1751
+ const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
1752
+ throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
1753
+ - already used by option '${matchingOption.flags}'`);
1754
+ }
1755
+ this._initOptionGroup(option);
1756
+ this.options.push(option);
1757
+ }
1758
+ /**
1759
+ * Check for command name and alias conflicts with existing commands.
1760
+ * Register command if no conflicts found, or throw on conflict.
1761
+ *
1762
+ * @param {Command} command
1763
+ * @private
1764
+ */
1765
+ _registerCommand(command) {
1766
+ const knownBy = (cmd) => {
1767
+ return [cmd.name()].concat(cmd.aliases());
1768
+ };
1769
+ const alreadyUsed = knownBy(command).find(
1770
+ (name) => this._findCommand(name)
1771
+ );
1772
+ if (alreadyUsed) {
1773
+ const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
1774
+ const newCmd = knownBy(command).join("|");
1775
+ throw new Error(
1776
+ `cannot add command '${newCmd}' as already have command '${existingCmd}'`
1777
+ );
1778
+ }
1779
+ this._initCommandGroup(command);
1780
+ this.commands.push(command);
1781
+ }
1782
+ /**
1783
+ * Add an option.
1784
+ *
1785
+ * @param {Option} option
1786
+ * @return {Command} `this` command for chaining
1787
+ */
1788
+ addOption(option) {
1789
+ this._registerOption(option);
1790
+ const oname = option.name();
1791
+ const name = option.attributeName();
1792
+ if (option.negate) {
1793
+ const positiveLongFlag = option.long.replace(/^--no-/, "--");
1794
+ if (!this._findOption(positiveLongFlag)) {
1795
+ this.setOptionValueWithSource(
1796
+ name,
1797
+ option.defaultValue === void 0 ? true : option.defaultValue,
1798
+ "default"
1799
+ );
1800
+ }
1801
+ } else if (option.defaultValue !== void 0) {
1802
+ this.setOptionValueWithSource(name, option.defaultValue, "default");
1803
+ }
1804
+ const handleOptionValue = (val, invalidValueMessage, valueSource) => {
1805
+ if (val == null && option.presetArg !== void 0) {
1806
+ val = option.presetArg;
1807
+ }
1808
+ const oldValue = this.getOptionValue(name);
1809
+ if (val !== null && option.parseArg) {
1810
+ val = this._callParseArg(option, val, oldValue, invalidValueMessage);
1811
+ } else if (val !== null && option.variadic) {
1812
+ val = option._collectValue(val, oldValue);
1813
+ }
1814
+ if (val == null) {
1815
+ if (option.negate) {
1816
+ val = false;
1817
+ } else if (option.isBoolean() || option.optional) {
1818
+ val = true;
1819
+ } else {
1820
+ val = "";
1821
+ }
1822
+ }
1823
+ this.setOptionValueWithSource(name, val, valueSource);
1824
+ };
1825
+ this.on("option:" + oname, (val) => {
1826
+ const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
1827
+ handleOptionValue(val, invalidValueMessage, "cli");
1828
+ });
1829
+ if (option.envVar) {
1830
+ this.on("optionEnv:" + oname, (val) => {
1831
+ const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
1832
+ handleOptionValue(val, invalidValueMessage, "env");
1833
+ });
1834
+ }
1835
+ return this;
1836
+ }
1837
+ /**
1838
+ * Internal implementation shared by .option() and .requiredOption()
1839
+ *
1840
+ * @return {Command} `this` command for chaining
1841
+ * @private
1842
+ */
1843
+ _optionEx(config, flags, description, fn, defaultValue) {
1844
+ if (typeof flags === "object" && flags instanceof Option2) {
1845
+ throw new Error(
1846
+ "To add an Option object use addOption() instead of option() or requiredOption()"
1847
+ );
1848
+ }
1849
+ const option = this.createOption(flags, description);
1850
+ option.makeOptionMandatory(!!config.mandatory);
1851
+ if (typeof fn === "function") {
1852
+ option.default(defaultValue).argParser(fn);
1853
+ } else if (fn instanceof RegExp) {
1854
+ const regex = fn;
1855
+ fn = (val, def) => {
1856
+ const m = regex.exec(val);
1857
+ return m ? m[0] : def;
1858
+ };
1859
+ option.default(defaultValue).argParser(fn);
1860
+ } else {
1861
+ option.default(fn);
1862
+ }
1863
+ return this.addOption(option);
1864
+ }
1865
+ /**
1866
+ * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
1867
+ *
1868
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
1869
+ * option-argument is indicated by `<>` and an optional option-argument by `[]`.
1870
+ *
1871
+ * See the README for more details, and see also addOption() and requiredOption().
1872
+ *
1873
+ * @example
1874
+ * program
1875
+ * .option('-p, --pepper', 'add pepper')
1876
+ * .option('--pt, --pizza-type <TYPE>', 'type of pizza') // required option-argument
1877
+ * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
1878
+ * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
1879
+ *
1880
+ * @param {string} flags
1881
+ * @param {string} [description]
1882
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
1883
+ * @param {*} [defaultValue]
1884
+ * @return {Command} `this` command for chaining
1885
+ */
1886
+ option(flags, description, parseArg, defaultValue) {
1887
+ return this._optionEx({}, flags, description, parseArg, defaultValue);
1888
+ }
1889
+ /**
1890
+ * Add a required option which must have a value after parsing. This usually means
1891
+ * the option must be specified on the command line. (Otherwise the same as .option().)
1892
+ *
1893
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
1894
+ *
1895
+ * @param {string} flags
1896
+ * @param {string} [description]
1897
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
1898
+ * @param {*} [defaultValue]
1899
+ * @return {Command} `this` command for chaining
1900
+ */
1901
+ requiredOption(flags, description, parseArg, defaultValue) {
1902
+ return this._optionEx(
1903
+ { mandatory: true },
1904
+ flags,
1905
+ description,
1906
+ parseArg,
1907
+ defaultValue
1908
+ );
1909
+ }
1910
+ /**
1911
+ * Alter parsing of short flags with optional values.
1912
+ *
1913
+ * @example
1914
+ * // for `.option('-f,--flag [value]'):
1915
+ * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
1916
+ * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
1917
+ *
1918
+ * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.
1919
+ * @return {Command} `this` command for chaining
1920
+ */
1921
+ combineFlagAndOptionalValue(combine = true) {
1922
+ this._combineFlagAndOptionalValue = !!combine;
1923
+ return this;
1924
+ }
1925
+ /**
1926
+ * Allow unknown options on the command line.
1927
+ *
1928
+ * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.
1929
+ * @return {Command} `this` command for chaining
1930
+ */
1931
+ allowUnknownOption(allowUnknown = true) {
1932
+ this._allowUnknownOption = !!allowUnknown;
1933
+ return this;
1934
+ }
1935
+ /**
1936
+ * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
1937
+ *
1938
+ * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.
1939
+ * @return {Command} `this` command for chaining
1940
+ */
1941
+ allowExcessArguments(allowExcess = true) {
1942
+ this._allowExcessArguments = !!allowExcess;
1943
+ return this;
1944
+ }
1945
+ /**
1946
+ * Enable positional options. Positional means global options are specified before subcommands which lets
1947
+ * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
1948
+ * The default behaviour is non-positional and global options may appear anywhere on the command line.
1949
+ *
1950
+ * @param {boolean} [positional]
1951
+ * @return {Command} `this` command for chaining
1952
+ */
1953
+ enablePositionalOptions(positional = true) {
1954
+ this._enablePositionalOptions = !!positional;
1955
+ return this;
1956
+ }
1957
+ /**
1958
+ * Pass through options that come after command-arguments rather than treat them as command-options,
1959
+ * so actual command-options come before command-arguments. Turning this on for a subcommand requires
1960
+ * positional options to have been enabled on the program (parent commands).
1961
+ * The default behaviour is non-positional and options may appear before or after command-arguments.
1962
+ *
1963
+ * @param {boolean} [passThrough] for unknown options.
1964
+ * @return {Command} `this` command for chaining
1965
+ */
1966
+ passThroughOptions(passThrough = true) {
1967
+ this._passThroughOptions = !!passThrough;
1968
+ this._checkForBrokenPassThrough();
1969
+ return this;
1970
+ }
1971
+ /**
1972
+ * @private
1973
+ */
1974
+ _checkForBrokenPassThrough() {
1975
+ if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {
1976
+ throw new Error(
1977
+ `passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`
1978
+ );
1979
+ }
1980
+ }
1981
+ /**
1982
+ * Whether to store option values as properties on command object,
1983
+ * or store separately (specify false). In both cases the option values can be accessed using .opts().
1984
+ *
1985
+ * @param {boolean} [storeAsProperties=true]
1986
+ * @return {Command} `this` command for chaining
1987
+ */
1988
+ storeOptionsAsProperties(storeAsProperties = true) {
1989
+ if (this.options.length) {
1990
+ throw new Error("call .storeOptionsAsProperties() before adding options");
1991
+ }
1992
+ if (Object.keys(this._optionValues).length) {
1993
+ throw new Error(
1994
+ "call .storeOptionsAsProperties() before setting option values"
1995
+ );
1996
+ }
1997
+ this._storeOptionsAsProperties = !!storeAsProperties;
1998
+ return this;
1999
+ }
2000
+ /**
2001
+ * Retrieve option value.
2002
+ *
2003
+ * @param {string} key
2004
+ * @return {object} value
2005
+ */
2006
+ getOptionValue(key) {
2007
+ if (this._storeOptionsAsProperties) {
2008
+ return this[key];
2009
+ }
2010
+ return this._optionValues[key];
2011
+ }
2012
+ /**
2013
+ * Store option value.
2014
+ *
2015
+ * @param {string} key
2016
+ * @param {object} value
2017
+ * @return {Command} `this` command for chaining
2018
+ */
2019
+ setOptionValue(key, value) {
2020
+ return this.setOptionValueWithSource(key, value, void 0);
2021
+ }
2022
+ /**
2023
+ * Store option value and where the value came from.
2024
+ *
2025
+ * @param {string} key
2026
+ * @param {object} value
2027
+ * @param {string} source - expected values are default/config/env/cli/implied
2028
+ * @return {Command} `this` command for chaining
2029
+ */
2030
+ setOptionValueWithSource(key, value, source) {
2031
+ if (this._storeOptionsAsProperties) {
2032
+ this[key] = value;
2033
+ } else {
2034
+ this._optionValues[key] = value;
2035
+ }
2036
+ this._optionValueSources[key] = source;
2037
+ return this;
2038
+ }
2039
+ /**
2040
+ * Get source of option value.
2041
+ * Expected values are default | config | env | cli | implied
2042
+ *
2043
+ * @param {string} key
2044
+ * @return {string}
2045
+ */
2046
+ getOptionValueSource(key) {
2047
+ return this._optionValueSources[key];
2048
+ }
2049
+ /**
2050
+ * Get source of option value. See also .optsWithGlobals().
2051
+ * Expected values are default | config | env | cli | implied
2052
+ *
2053
+ * @param {string} key
2054
+ * @return {string}
2055
+ */
2056
+ getOptionValueSourceWithGlobals(key) {
2057
+ let source;
2058
+ this._getCommandAndAncestors().forEach((cmd) => {
2059
+ if (cmd.getOptionValueSource(key) !== void 0) {
2060
+ source = cmd.getOptionValueSource(key);
2061
+ }
2062
+ });
2063
+ return source;
2064
+ }
2065
+ /**
2066
+ * Get user arguments from implied or explicit arguments.
2067
+ * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
2068
+ *
2069
+ * @private
2070
+ */
2071
+ _prepareUserArgs(argv, parseOptions) {
2072
+ if (argv !== void 0 && !Array.isArray(argv)) {
2073
+ throw new Error("first parameter to parse must be array or undefined");
2074
+ }
2075
+ parseOptions = parseOptions || {};
2076
+ if (argv === void 0 && parseOptions.from === void 0) {
2077
+ if (process2.versions?.electron) {
2078
+ parseOptions.from = "electron";
2079
+ }
2080
+ const execArgv = process2.execArgv ?? [];
2081
+ if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) {
2082
+ parseOptions.from = "eval";
2083
+ }
2084
+ }
2085
+ if (argv === void 0) {
2086
+ argv = process2.argv;
2087
+ }
2088
+ this.rawArgs = argv.slice();
2089
+ let userArgs;
2090
+ switch (parseOptions.from) {
2091
+ case void 0:
2092
+ case "node":
2093
+ this._scriptPath = argv[1];
2094
+ userArgs = argv.slice(2);
2095
+ break;
2096
+ case "electron":
2097
+ if (process2.defaultApp) {
2098
+ this._scriptPath = argv[1];
2099
+ userArgs = argv.slice(2);
2100
+ } else {
2101
+ userArgs = argv.slice(1);
2102
+ }
2103
+ break;
2104
+ case "user":
2105
+ userArgs = argv.slice(0);
2106
+ break;
2107
+ case "eval":
2108
+ userArgs = argv.slice(1);
2109
+ break;
2110
+ default:
2111
+ throw new Error(
2112
+ `unexpected parse option { from: '${parseOptions.from}' }`
2113
+ );
2114
+ }
2115
+ if (!this._name && this._scriptPath)
2116
+ this.nameFromFilename(this._scriptPath);
2117
+ this._name = this._name || "program";
2118
+ return userArgs;
2119
+ }
2120
+ /**
2121
+ * Parse `argv`, setting options and invoking commands when defined.
2122
+ *
2123
+ * Use parseAsync instead of parse if any of your action handlers are async.
2124
+ *
2125
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
2126
+ *
2127
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
2128
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
2129
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
2130
+ * - `'user'`: just user arguments
2131
+ *
2132
+ * @example
2133
+ * program.parse(); // parse process.argv and auto-detect electron and special node flags
2134
+ * program.parse(process.argv); // assume argv[0] is app and argv[1] is script
2135
+ * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
2136
+ *
2137
+ * @param {string[]} [argv] - optional, defaults to process.argv
2138
+ * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron
2139
+ * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
2140
+ * @return {Command} `this` command for chaining
2141
+ */
2142
+ parse(argv, parseOptions) {
2143
+ this._prepareForParse();
2144
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
2145
+ this._parseCommand([], userArgs);
2146
+ return this;
2147
+ }
2148
+ /**
2149
+ * Parse `argv`, setting options and invoking commands when defined.
2150
+ *
2151
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
2152
+ *
2153
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
2154
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
2155
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
2156
+ * - `'user'`: just user arguments
2157
+ *
2158
+ * @example
2159
+ * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags
2160
+ * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script
2161
+ * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
2162
+ *
2163
+ * @param {string[]} [argv]
2164
+ * @param {object} [parseOptions]
2165
+ * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
2166
+ * @return {Promise}
2167
+ */
2168
+ async parseAsync(argv, parseOptions) {
2169
+ this._prepareForParse();
2170
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
2171
+ await this._parseCommand([], userArgs);
2172
+ return this;
2173
+ }
2174
+ _prepareForParse() {
2175
+ if (this._savedState === null) {
2176
+ this.saveStateBeforeParse();
2177
+ } else {
2178
+ this.restoreStateBeforeParse();
2179
+ }
2180
+ }
2181
+ /**
2182
+ * Called the first time parse is called to save state and allow a restore before subsequent calls to parse.
2183
+ * Not usually called directly, but available for subclasses to save their custom state.
2184
+ *
2185
+ * This is called in a lazy way. Only commands used in parsing chain will have state saved.
2186
+ */
2187
+ saveStateBeforeParse() {
2188
+ this._savedState = {
2189
+ // name is stable if supplied by author, but may be unspecified for root command and deduced during parsing
2190
+ _name: this._name,
2191
+ // option values before parse have default values (including false for negated options)
2192
+ // shallow clones
2193
+ _optionValues: { ...this._optionValues },
2194
+ _optionValueSources: { ...this._optionValueSources }
2195
+ };
2196
+ }
2197
+ /**
2198
+ * Restore state before parse for calls after the first.
2199
+ * Not usually called directly, but available for subclasses to save their custom state.
2200
+ *
2201
+ * This is called in a lazy way. Only commands used in parsing chain will have state restored.
2202
+ */
2203
+ restoreStateBeforeParse() {
2204
+ if (this._storeOptionsAsProperties)
2205
+ throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
2206
+ - either make a new Command for each call to parse, or stop storing options as properties`);
2207
+ this._name = this._savedState._name;
2208
+ this._scriptPath = null;
2209
+ this.rawArgs = [];
2210
+ this._optionValues = { ...this._savedState._optionValues };
2211
+ this._optionValueSources = { ...this._savedState._optionValueSources };
2212
+ this.args = [];
2213
+ this.processedArgs = [];
2214
+ }
2215
+ /**
2216
+ * Throw if expected executable is missing. Add lots of help for author.
2217
+ *
2218
+ * @param {string} executableFile
2219
+ * @param {string} executableDir
2220
+ * @param {string} subcommandName
2221
+ */
2222
+ _checkForMissingExecutable(executableFile, executableDir, subcommandName) {
2223
+ if (fs.existsSync(executableFile)) return;
2224
+ const executableDirMessage = executableDir ? `searched for local subcommand relative to directory '${executableDir}'` : "no directory for search for local subcommand, use .executableDir() to supply a custom directory";
2225
+ const executableMissing = `'${executableFile}' does not exist
2226
+ - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
2227
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
2228
+ - ${executableDirMessage}`;
2229
+ throw new Error(executableMissing);
2230
+ }
2231
+ /**
2232
+ * Execute a sub-command executable.
2233
+ *
2234
+ * @private
2235
+ */
2236
+ _executeSubCommand(subcommand, args) {
2237
+ args = args.slice();
2238
+ let launchWithNode = false;
2239
+ const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
2240
+ function findFile(baseDir, baseName) {
2241
+ const localBin = path.resolve(baseDir, baseName);
2242
+ if (fs.existsSync(localBin)) return localBin;
2243
+ if (sourceExt.includes(path.extname(baseName))) return void 0;
2244
+ const foundExt = sourceExt.find(
2245
+ (ext) => fs.existsSync(`${localBin}${ext}`)
2246
+ );
2247
+ if (foundExt) return `${localBin}${foundExt}`;
2248
+ return void 0;
2249
+ }
2250
+ this._checkForMissingMandatoryOptions();
2251
+ this._checkForConflictingOptions();
2252
+ let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
2253
+ let executableDir = this._executableDir || "";
2254
+ if (this._scriptPath) {
2255
+ let resolvedScriptPath;
2256
+ try {
2257
+ resolvedScriptPath = fs.realpathSync(this._scriptPath);
2258
+ } catch {
2259
+ resolvedScriptPath = this._scriptPath;
2260
+ }
2261
+ executableDir = path.resolve(
2262
+ path.dirname(resolvedScriptPath),
2263
+ executableDir
2264
+ );
2265
+ }
2266
+ if (executableDir) {
2267
+ let localFile = findFile(executableDir, executableFile);
2268
+ if (!localFile && !subcommand._executableFile && this._scriptPath) {
2269
+ const legacyName = path.basename(
2270
+ this._scriptPath,
2271
+ path.extname(this._scriptPath)
2272
+ );
2273
+ if (legacyName !== this._name) {
2274
+ localFile = findFile(
2275
+ executableDir,
2276
+ `${legacyName}-${subcommand._name}`
2277
+ );
2278
+ }
2279
+ }
2280
+ executableFile = localFile || executableFile;
2281
+ }
2282
+ launchWithNode = sourceExt.includes(path.extname(executableFile));
2283
+ let proc;
2284
+ if (process2.platform !== "win32") {
2285
+ if (launchWithNode) {
2286
+ args.unshift(executableFile);
2287
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
2288
+ proc = childProcess.spawn(process2.argv[0], args, { stdio: "inherit" });
2289
+ } else {
2290
+ proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
2291
+ }
2292
+ } else {
2293
+ this._checkForMissingExecutable(
2294
+ executableFile,
2295
+ executableDir,
2296
+ subcommand._name
2297
+ );
2298
+ args.unshift(executableFile);
2299
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
2300
+ proc = childProcess.spawn(process2.execPath, args, { stdio: "inherit" });
2301
+ }
2302
+ if (!proc.killed) {
2303
+ const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
2304
+ signals.forEach((signal) => {
2305
+ process2.on(signal, () => {
2306
+ if (proc.killed === false && proc.exitCode === null) {
2307
+ proc.kill(signal);
2308
+ }
2309
+ });
2310
+ });
2311
+ }
2312
+ const exitCallback = this._exitCallback;
2313
+ proc.on("close", (code) => {
2314
+ code = code ?? 1;
2315
+ if (!exitCallback) {
2316
+ process2.exit(code);
2317
+ } else {
2318
+ exitCallback(
2319
+ new CommanderError2(
2320
+ code,
2321
+ "commander.executeSubCommandAsync",
2322
+ "(close)"
2323
+ )
2324
+ );
2325
+ }
2326
+ });
2327
+ proc.on("error", (err) => {
2328
+ if (err.code === "ENOENT") {
2329
+ this._checkForMissingExecutable(
2330
+ executableFile,
2331
+ executableDir,
2332
+ subcommand._name
2333
+ );
2334
+ } else if (err.code === "EACCES") {
2335
+ throw new Error(`'${executableFile}' not executable`);
2336
+ }
2337
+ if (!exitCallback) {
2338
+ process2.exit(1);
2339
+ } else {
2340
+ const wrappedError = new CommanderError2(
2341
+ 1,
2342
+ "commander.executeSubCommandAsync",
2343
+ "(error)"
2344
+ );
2345
+ wrappedError.nestedError = err;
2346
+ exitCallback(wrappedError);
2347
+ }
2348
+ });
2349
+ this.runningCommand = proc;
2350
+ }
2351
+ /**
2352
+ * @private
2353
+ */
2354
+ _dispatchSubcommand(commandName, operands, unknown) {
2355
+ const subCommand = this._findCommand(commandName);
2356
+ if (!subCommand) this.help({ error: true });
2357
+ subCommand._prepareForParse();
2358
+ let promiseChain;
2359
+ promiseChain = this._chainOrCallSubCommandHook(
2360
+ promiseChain,
2361
+ subCommand,
2362
+ "preSubcommand"
2363
+ );
2364
+ promiseChain = this._chainOrCall(promiseChain, () => {
2365
+ if (subCommand._executableHandler) {
2366
+ this._executeSubCommand(subCommand, operands.concat(unknown));
2367
+ } else {
2368
+ return subCommand._parseCommand(operands, unknown);
2369
+ }
2370
+ });
2371
+ return promiseChain;
2372
+ }
2373
+ /**
2374
+ * Invoke help directly if possible, or dispatch if necessary.
2375
+ * e.g. help foo
2376
+ *
2377
+ * @private
2378
+ */
2379
+ _dispatchHelpCommand(subcommandName) {
2380
+ if (!subcommandName) {
2381
+ this.help();
2382
+ }
2383
+ const subCommand = this._findCommand(subcommandName);
2384
+ if (subCommand && !subCommand._executableHandler) {
2385
+ subCommand.help();
2386
+ }
2387
+ return this._dispatchSubcommand(
2388
+ subcommandName,
2389
+ [],
2390
+ [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]
2391
+ );
2392
+ }
2393
+ /**
2394
+ * Check this.args against expected this.registeredArguments.
2395
+ *
2396
+ * @private
2397
+ */
2398
+ _checkNumberOfArguments() {
2399
+ this.registeredArguments.forEach((arg, i) => {
2400
+ if (arg.required && this.args[i] == null) {
2401
+ this.missingArgument(arg.name());
2402
+ }
2403
+ });
2404
+ if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
2405
+ return;
2406
+ }
2407
+ if (this.args.length > this.registeredArguments.length) {
2408
+ this._excessArguments(this.args);
2409
+ }
2410
+ }
2411
+ /**
2412
+ * Process this.args using this.registeredArguments and save as this.processedArgs!
2413
+ *
2414
+ * @private
2415
+ */
2416
+ _processArguments() {
2417
+ const myParseArg = (argument, value, previous) => {
2418
+ let parsedValue = value;
2419
+ if (value !== null && argument.parseArg) {
2420
+ const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
2421
+ parsedValue = this._callParseArg(
2422
+ argument,
2423
+ value,
2424
+ previous,
2425
+ invalidValueMessage
2426
+ );
2427
+ }
2428
+ return parsedValue;
2429
+ };
2430
+ this._checkNumberOfArguments();
2431
+ const processedArgs = [];
2432
+ this.registeredArguments.forEach((declaredArg, index) => {
2433
+ let value = declaredArg.defaultValue;
2434
+ if (declaredArg.variadic) {
2435
+ if (index < this.args.length) {
2436
+ value = this.args.slice(index);
2437
+ if (declaredArg.parseArg) {
2438
+ value = value.reduce((processed, v) => {
2439
+ return myParseArg(declaredArg, v, processed);
2440
+ }, declaredArg.defaultValue);
2441
+ }
2442
+ } else if (value === void 0) {
2443
+ value = [];
2444
+ }
2445
+ } else if (index < this.args.length) {
2446
+ value = this.args[index];
2447
+ if (declaredArg.parseArg) {
2448
+ value = myParseArg(declaredArg, value, declaredArg.defaultValue);
2449
+ }
2450
+ }
2451
+ processedArgs[index] = value;
2452
+ });
2453
+ this.processedArgs = processedArgs;
2454
+ }
2455
+ /**
2456
+ * Once we have a promise we chain, but call synchronously until then.
2457
+ *
2458
+ * @param {(Promise|undefined)} promise
2459
+ * @param {Function} fn
2460
+ * @return {(Promise|undefined)}
2461
+ * @private
2462
+ */
2463
+ _chainOrCall(promise, fn) {
2464
+ if (promise?.then && typeof promise.then === "function") {
2465
+ return promise.then(() => fn());
2466
+ }
2467
+ return fn();
2468
+ }
2469
+ /**
2470
+ *
2471
+ * @param {(Promise|undefined)} promise
2472
+ * @param {string} event
2473
+ * @return {(Promise|undefined)}
2474
+ * @private
2475
+ */
2476
+ _chainOrCallHooks(promise, event) {
2477
+ let result = promise;
2478
+ const hooks = [];
2479
+ this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== void 0).forEach((hookedCommand) => {
2480
+ hookedCommand._lifeCycleHooks[event].forEach((callback) => {
2481
+ hooks.push({ hookedCommand, callback });
2482
+ });
2483
+ });
2484
+ if (event === "postAction") {
2485
+ hooks.reverse();
2486
+ }
2487
+ hooks.forEach((hookDetail) => {
2488
+ result = this._chainOrCall(result, () => {
2489
+ return hookDetail.callback(hookDetail.hookedCommand, this);
2490
+ });
2491
+ });
2492
+ return result;
2493
+ }
2494
+ /**
2495
+ *
2496
+ * @param {(Promise|undefined)} promise
2497
+ * @param {Command} subCommand
2498
+ * @param {string} event
2499
+ * @return {(Promise|undefined)}
2500
+ * @private
2501
+ */
2502
+ _chainOrCallSubCommandHook(promise, subCommand, event) {
2503
+ let result = promise;
2504
+ if (this._lifeCycleHooks[event] !== void 0) {
2505
+ this._lifeCycleHooks[event].forEach((hook) => {
2506
+ result = this._chainOrCall(result, () => {
2507
+ return hook(this, subCommand);
2508
+ });
2509
+ });
2510
+ }
2511
+ return result;
2512
+ }
2513
+ /**
2514
+ * Process arguments in context of this command.
2515
+ * Returns action result, in case it is a promise.
2516
+ *
2517
+ * @private
2518
+ */
2519
+ _parseCommand(operands, unknown) {
2520
+ const parsed = this.parseOptions(unknown);
2521
+ this._parseOptionsEnv();
2522
+ this._parseOptionsImplied();
2523
+ operands = operands.concat(parsed.operands);
2524
+ unknown = parsed.unknown;
2525
+ this.args = operands.concat(unknown);
2526
+ if (operands && this._findCommand(operands[0])) {
2527
+ return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
2528
+ }
2529
+ if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) {
2530
+ return this._dispatchHelpCommand(operands[1]);
2531
+ }
2532
+ if (this._defaultCommandName) {
2533
+ this._outputHelpIfRequested(unknown);
2534
+ return this._dispatchSubcommand(
2535
+ this._defaultCommandName,
2536
+ operands,
2537
+ unknown
2538
+ );
2539
+ }
2540
+ if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
2541
+ this.help({ error: true });
2542
+ }
2543
+ this._outputHelpIfRequested(parsed.unknown);
2544
+ this._checkForMissingMandatoryOptions();
2545
+ this._checkForConflictingOptions();
2546
+ const checkForUnknownOptions = () => {
2547
+ if (parsed.unknown.length > 0) {
2548
+ this.unknownOption(parsed.unknown[0]);
2549
+ }
2550
+ };
2551
+ const commandEvent = `command:${this.name()}`;
2552
+ if (this._actionHandler) {
2553
+ checkForUnknownOptions();
2554
+ this._processArguments();
2555
+ let promiseChain;
2556
+ promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
2557
+ promiseChain = this._chainOrCall(
2558
+ promiseChain,
2559
+ () => this._actionHandler(this.processedArgs)
2560
+ );
2561
+ if (this.parent) {
2562
+ promiseChain = this._chainOrCall(promiseChain, () => {
2563
+ this.parent.emit(commandEvent, operands, unknown);
2564
+ });
2565
+ }
2566
+ promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
2567
+ return promiseChain;
2568
+ }
2569
+ if (this.parent?.listenerCount(commandEvent)) {
2570
+ checkForUnknownOptions();
2571
+ this._processArguments();
2572
+ this.parent.emit(commandEvent, operands, unknown);
2573
+ } else if (operands.length) {
2574
+ if (this._findCommand("*")) {
2575
+ return this._dispatchSubcommand("*", operands, unknown);
2576
+ }
2577
+ if (this.listenerCount("command:*")) {
2578
+ this.emit("command:*", operands, unknown);
2579
+ } else if (this.commands.length) {
2580
+ this.unknownCommand();
2581
+ } else {
2582
+ checkForUnknownOptions();
2583
+ this._processArguments();
2584
+ }
2585
+ } else if (this.commands.length) {
2586
+ checkForUnknownOptions();
2587
+ this.help({ error: true });
2588
+ } else {
2589
+ checkForUnknownOptions();
2590
+ this._processArguments();
2591
+ }
2592
+ }
2593
+ /**
2594
+ * Find matching command.
2595
+ *
2596
+ * @private
2597
+ * @return {Command | undefined}
2598
+ */
2599
+ _findCommand(name) {
2600
+ if (!name) return void 0;
2601
+ return this.commands.find(
2602
+ (cmd) => cmd._name === name || cmd._aliases.includes(name)
2603
+ );
2604
+ }
2605
+ /**
2606
+ * Return an option matching `arg` if any.
2607
+ *
2608
+ * @param {string} arg
2609
+ * @return {Option}
2610
+ * @package
2611
+ */
2612
+ _findOption(arg) {
2613
+ return this.options.find((option) => option.is(arg));
2614
+ }
2615
+ /**
2616
+ * Display an error message if a mandatory option does not have a value.
2617
+ * Called after checking for help flags in leaf subcommand.
2618
+ *
2619
+ * @private
2620
+ */
2621
+ _checkForMissingMandatoryOptions() {
2622
+ this._getCommandAndAncestors().forEach((cmd) => {
2623
+ cmd.options.forEach((anOption) => {
2624
+ if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === void 0) {
2625
+ cmd.missingMandatoryOptionValue(anOption);
2626
+ }
2627
+ });
2628
+ });
2629
+ }
2630
+ /**
2631
+ * Display an error message if conflicting options are used together in this.
2632
+ *
2633
+ * @private
2634
+ */
2635
+ _checkForConflictingLocalOptions() {
2636
+ const definedNonDefaultOptions = this.options.filter((option) => {
2637
+ const optionKey = option.attributeName();
2638
+ if (this.getOptionValue(optionKey) === void 0) {
2639
+ return false;
2640
+ }
2641
+ return this.getOptionValueSource(optionKey) !== "default";
2642
+ });
2643
+ const optionsWithConflicting = definedNonDefaultOptions.filter(
2644
+ (option) => option.conflictsWith.length > 0
2645
+ );
2646
+ optionsWithConflicting.forEach((option) => {
2647
+ const conflictingAndDefined = definedNonDefaultOptions.find(
2648
+ (defined) => option.conflictsWith.includes(defined.attributeName())
2649
+ );
2650
+ if (conflictingAndDefined) {
2651
+ this._conflictingOption(option, conflictingAndDefined);
2652
+ }
2653
+ });
2654
+ }
2655
+ /**
2656
+ * Display an error message if conflicting options are used together.
2657
+ * Called after checking for help flags in leaf subcommand.
2658
+ *
2659
+ * @private
2660
+ */
2661
+ _checkForConflictingOptions() {
2662
+ this._getCommandAndAncestors().forEach((cmd) => {
2663
+ cmd._checkForConflictingLocalOptions();
2664
+ });
2665
+ }
2666
+ /**
2667
+ * Parse options from `argv` removing known options,
2668
+ * and return argv split into operands and unknown arguments.
2669
+ *
2670
+ * Side effects: modifies command by storing options. Does not reset state if called again.
2671
+ *
2672
+ * Examples:
2673
+ *
2674
+ * argv => operands, unknown
2675
+ * --known kkk op => [op], []
2676
+ * op --known kkk => [op], []
2677
+ * sub --unknown uuu op => [sub], [--unknown uuu op]
2678
+ * sub -- --unknown uuu op => [sub --unknown uuu op], []
2679
+ *
2680
+ * @param {string[]} args
2681
+ * @return {{operands: string[], unknown: string[]}}
2682
+ */
2683
+ parseOptions(args) {
2684
+ const operands = [];
2685
+ const unknown = [];
2686
+ let dest = operands;
2687
+ function maybeOption(arg) {
2688
+ return arg.length > 1 && arg[0] === "-";
2689
+ }
2690
+ const negativeNumberArg = (arg) => {
2691
+ if (!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(arg)) return false;
2692
+ return !this._getCommandAndAncestors().some(
2693
+ (cmd) => cmd.options.map((opt) => opt.short).some((short) => /^-\d$/.test(short))
2694
+ );
2695
+ };
2696
+ let activeVariadicOption = null;
2697
+ let activeGroup = null;
2698
+ let i = 0;
2699
+ while (i < args.length || activeGroup) {
2700
+ const arg = activeGroup ?? args[i++];
2701
+ activeGroup = null;
2702
+ if (arg === "--") {
2703
+ if (dest === unknown) dest.push(arg);
2704
+ dest.push(...args.slice(i));
2705
+ break;
2706
+ }
2707
+ if (activeVariadicOption && (!maybeOption(arg) || negativeNumberArg(arg))) {
2708
+ this.emit(`option:${activeVariadicOption.name()}`, arg);
2709
+ continue;
2710
+ }
2711
+ activeVariadicOption = null;
2712
+ if (maybeOption(arg)) {
2713
+ const option = this._findOption(arg);
2714
+ if (option) {
2715
+ if (option.required) {
2716
+ const value = args[i++];
2717
+ if (value === void 0) this.optionMissingArgument(option);
2718
+ this.emit(`option:${option.name()}`, value);
2719
+ } else if (option.optional) {
2720
+ let value = null;
2721
+ if (i < args.length && (!maybeOption(args[i]) || negativeNumberArg(args[i]))) {
2722
+ value = args[i++];
2723
+ }
2724
+ this.emit(`option:${option.name()}`, value);
2725
+ } else {
2726
+ this.emit(`option:${option.name()}`);
2727
+ }
2728
+ activeVariadicOption = option.variadic ? option : null;
2729
+ continue;
2730
+ }
2731
+ }
2732
+ if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
2733
+ const option = this._findOption(`-${arg[1]}`);
2734
+ if (option) {
2735
+ if (option.required || option.optional && this._combineFlagAndOptionalValue) {
2736
+ this.emit(`option:${option.name()}`, arg.slice(2));
2737
+ } else {
2738
+ this.emit(`option:${option.name()}`);
2739
+ activeGroup = `-${arg.slice(2)}`;
2740
+ }
2741
+ continue;
2742
+ }
2743
+ }
2744
+ if (/^--[^=]+=/.test(arg)) {
2745
+ const index = arg.indexOf("=");
2746
+ const option = this._findOption(arg.slice(0, index));
2747
+ if (option && (option.required || option.optional)) {
2748
+ this.emit(`option:${option.name()}`, arg.slice(index + 1));
2749
+ continue;
2750
+ }
2751
+ }
2752
+ if (dest === operands && maybeOption(arg) && !(this.commands.length === 0 && negativeNumberArg(arg))) {
2753
+ dest = unknown;
2754
+ }
2755
+ if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
2756
+ if (this._findCommand(arg)) {
2757
+ operands.push(arg);
2758
+ unknown.push(...args.slice(i));
2759
+ break;
2760
+ } else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
2761
+ operands.push(arg, ...args.slice(i));
2762
+ break;
2763
+ } else if (this._defaultCommandName) {
2764
+ unknown.push(arg, ...args.slice(i));
2765
+ break;
2766
+ }
2767
+ }
2768
+ if (this._passThroughOptions) {
2769
+ dest.push(arg, ...args.slice(i));
2770
+ break;
2771
+ }
2772
+ dest.push(arg);
2773
+ }
2774
+ return { operands, unknown };
2775
+ }
2776
+ /**
2777
+ * Return an object containing local option values as key-value pairs.
2778
+ *
2779
+ * @return {object}
2780
+ */
2781
+ opts() {
2782
+ if (this._storeOptionsAsProperties) {
2783
+ const result = {};
2784
+ const len = this.options.length;
2785
+ for (let i = 0; i < len; i++) {
2786
+ const key = this.options[i].attributeName();
2787
+ result[key] = key === this._versionOptionName ? this._version : this[key];
2788
+ }
2789
+ return result;
2790
+ }
2791
+ return this._optionValues;
2792
+ }
2793
+ /**
2794
+ * Return an object containing merged local and global option values as key-value pairs.
2795
+ *
2796
+ * @return {object}
2797
+ */
2798
+ optsWithGlobals() {
2799
+ return this._getCommandAndAncestors().reduce(
2800
+ (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),
2801
+ {}
2802
+ );
2803
+ }
2804
+ /**
2805
+ * Display error message and exit (or call exitOverride).
2806
+ *
2807
+ * @param {string} message
2808
+ * @param {object} [errorOptions]
2809
+ * @param {string} [errorOptions.code] - an id string representing the error
2810
+ * @param {number} [errorOptions.exitCode] - used with process.exit
2811
+ */
2812
+ error(message, errorOptions) {
2813
+ this._outputConfiguration.outputError(
2814
+ `${message}
2815
+ `,
2816
+ this._outputConfiguration.writeErr
2817
+ );
2818
+ if (typeof this._showHelpAfterError === "string") {
2819
+ this._outputConfiguration.writeErr(`${this._showHelpAfterError}
2820
+ `);
2821
+ } else if (this._showHelpAfterError) {
2822
+ this._outputConfiguration.writeErr("\n");
2823
+ this.outputHelp({ error: true });
2824
+ }
2825
+ const config = errorOptions || {};
2826
+ const exitCode = config.exitCode || 1;
2827
+ const code = config.code || "commander.error";
2828
+ this._exit(exitCode, code, message);
2829
+ }
2830
+ /**
2831
+ * Apply any option related environment variables, if option does
2832
+ * not have a value from cli or client code.
2833
+ *
2834
+ * @private
2835
+ */
2836
+ _parseOptionsEnv() {
2837
+ this.options.forEach((option) => {
2838
+ if (option.envVar && option.envVar in process2.env) {
2839
+ const optionKey = option.attributeName();
2840
+ if (this.getOptionValue(optionKey) === void 0 || ["default", "config", "env"].includes(
2841
+ this.getOptionValueSource(optionKey)
2842
+ )) {
2843
+ if (option.required || option.optional) {
2844
+ this.emit(`optionEnv:${option.name()}`, process2.env[option.envVar]);
2845
+ } else {
2846
+ this.emit(`optionEnv:${option.name()}`);
2847
+ }
2848
+ }
2849
+ }
2850
+ });
2851
+ }
2852
+ /**
2853
+ * Apply any implied option values, if option is undefined or default value.
2854
+ *
2855
+ * @private
2856
+ */
2857
+ _parseOptionsImplied() {
2858
+ const dualHelper = new DualOptions(this.options);
2859
+ const hasCustomOptionValue = (optionKey) => {
2860
+ return this.getOptionValue(optionKey) !== void 0 && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
2861
+ };
2862
+ this.options.filter(
2863
+ (option) => option.implied !== void 0 && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(
2864
+ this.getOptionValue(option.attributeName()),
2865
+ option
2866
+ )
2867
+ ).forEach((option) => {
2868
+ Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
2869
+ this.setOptionValueWithSource(
2870
+ impliedKey,
2871
+ option.implied[impliedKey],
2872
+ "implied"
2873
+ );
2874
+ });
2875
+ });
2876
+ }
2877
+ /**
2878
+ * Argument `name` is missing.
2879
+ *
2880
+ * @param {string} name
2881
+ * @private
2882
+ */
2883
+ missingArgument(name) {
2884
+ const message = `error: missing required argument '${name}'`;
2885
+ this.error(message, { code: "commander.missingArgument" });
2886
+ }
2887
+ /**
2888
+ * `Option` is missing an argument.
2889
+ *
2890
+ * @param {Option} option
2891
+ * @private
2892
+ */
2893
+ optionMissingArgument(option) {
2894
+ const message = `error: option '${option.flags}' argument missing`;
2895
+ this.error(message, { code: "commander.optionMissingArgument" });
2896
+ }
2897
+ /**
2898
+ * `Option` does not have a value, and is a mandatory option.
2899
+ *
2900
+ * @param {Option} option
2901
+ * @private
2902
+ */
2903
+ missingMandatoryOptionValue(option) {
2904
+ const message = `error: required option '${option.flags}' not specified`;
2905
+ this.error(message, { code: "commander.missingMandatoryOptionValue" });
2906
+ }
2907
+ /**
2908
+ * `Option` conflicts with another option.
2909
+ *
2910
+ * @param {Option} option
2911
+ * @param {Option} conflictingOption
2912
+ * @private
2913
+ */
2914
+ _conflictingOption(option, conflictingOption) {
2915
+ const findBestOptionFromValue = (option2) => {
2916
+ const optionKey = option2.attributeName();
2917
+ const optionValue = this.getOptionValue(optionKey);
2918
+ const negativeOption = this.options.find(
2919
+ (target) => target.negate && optionKey === target.attributeName()
2920
+ );
2921
+ const positiveOption = this.options.find(
2922
+ (target) => !target.negate && optionKey === target.attributeName()
2923
+ );
2924
+ if (negativeOption && (negativeOption.presetArg === void 0 && optionValue === false || negativeOption.presetArg !== void 0 && optionValue === negativeOption.presetArg)) {
2925
+ return negativeOption;
2926
+ }
2927
+ return positiveOption || option2;
2928
+ };
2929
+ const getErrorMessage = (option2) => {
2930
+ const bestOption = findBestOptionFromValue(option2);
2931
+ const optionKey = bestOption.attributeName();
2932
+ const source = this.getOptionValueSource(optionKey);
2933
+ if (source === "env") {
2934
+ return `environment variable '${bestOption.envVar}'`;
2935
+ }
2936
+ return `option '${bestOption.flags}'`;
2937
+ };
2938
+ const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
2939
+ this.error(message, { code: "commander.conflictingOption" });
2940
+ }
2941
+ /**
2942
+ * Unknown option `flag`.
2943
+ *
2944
+ * @param {string} flag
2945
+ * @private
2946
+ */
2947
+ unknownOption(flag) {
2948
+ if (this._allowUnknownOption) return;
2949
+ let suggestion = "";
2950
+ if (flag.startsWith("--") && this._showSuggestionAfterError) {
2951
+ let candidateFlags = [];
2952
+ let command = this;
2953
+ do {
2954
+ const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
2955
+ candidateFlags = candidateFlags.concat(moreFlags);
2956
+ command = command.parent;
2957
+ } while (command && !command._enablePositionalOptions);
2958
+ suggestion = suggestSimilar(flag, candidateFlags);
2959
+ }
2960
+ const message = `error: unknown option '${flag}'${suggestion}`;
2961
+ this.error(message, { code: "commander.unknownOption" });
2962
+ }
2963
+ /**
2964
+ * Excess arguments, more than expected.
2965
+ *
2966
+ * @param {string[]} receivedArgs
2967
+ * @private
2968
+ */
2969
+ _excessArguments(receivedArgs) {
2970
+ if (this._allowExcessArguments) return;
2971
+ const expected = this.registeredArguments.length;
2972
+ const s = expected === 1 ? "" : "s";
2973
+ const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
2974
+ const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
2975
+ this.error(message, { code: "commander.excessArguments" });
2976
+ }
2977
+ /**
2978
+ * Unknown command.
2979
+ *
2980
+ * @private
2981
+ */
2982
+ unknownCommand() {
2983
+ const unknownName = this.args[0];
2984
+ let suggestion = "";
2985
+ if (this._showSuggestionAfterError) {
2986
+ const candidateNames = [];
2987
+ this.createHelp().visibleCommands(this).forEach((command) => {
2988
+ candidateNames.push(command.name());
2989
+ if (command.alias()) candidateNames.push(command.alias());
2990
+ });
2991
+ suggestion = suggestSimilar(unknownName, candidateNames);
2992
+ }
2993
+ const message = `error: unknown command '${unknownName}'${suggestion}`;
2994
+ this.error(message, { code: "commander.unknownCommand" });
2995
+ }
2996
+ /**
2997
+ * Get or set the program version.
2998
+ *
2999
+ * This method auto-registers the "-V, --version" option which will print the version number.
3000
+ *
3001
+ * You can optionally supply the flags and description to override the defaults.
3002
+ *
3003
+ * @param {string} [str]
3004
+ * @param {string} [flags]
3005
+ * @param {string} [description]
3006
+ * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments
3007
+ */
3008
+ version(str, flags, description) {
3009
+ if (str === void 0) return this._version;
3010
+ this._version = str;
3011
+ flags = flags || "-V, --version";
3012
+ description = description || "output the version number";
3013
+ const versionOption = this.createOption(flags, description);
3014
+ this._versionOptionName = versionOption.attributeName();
3015
+ this._registerOption(versionOption);
3016
+ this.on("option:" + versionOption.name(), () => {
3017
+ this._outputConfiguration.writeOut(`${str}
3018
+ `);
3019
+ this._exit(0, "commander.version", str);
3020
+ });
3021
+ return this;
3022
+ }
3023
+ /**
3024
+ * Set the description.
3025
+ *
3026
+ * @param {string} [str]
3027
+ * @param {object} [argsDescription]
3028
+ * @return {(string|Command)}
3029
+ */
3030
+ description(str, argsDescription) {
3031
+ if (str === void 0 && argsDescription === void 0)
3032
+ return this._description;
3033
+ this._description = str;
3034
+ if (argsDescription) {
3035
+ this._argsDescription = argsDescription;
3036
+ }
3037
+ return this;
3038
+ }
3039
+ /**
3040
+ * Set the summary. Used when listed as subcommand of parent.
3041
+ *
3042
+ * @param {string} [str]
3043
+ * @return {(string|Command)}
3044
+ */
3045
+ summary(str) {
3046
+ if (str === void 0) return this._summary;
3047
+ this._summary = str;
3048
+ return this;
3049
+ }
3050
+ /**
3051
+ * Set an alias for the command.
3052
+ *
3053
+ * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
3054
+ *
3055
+ * @param {string} [alias]
3056
+ * @return {(string|Command)}
3057
+ */
3058
+ alias(alias) {
3059
+ if (alias === void 0) return this._aliases[0];
3060
+ let command = this;
3061
+ if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
3062
+ command = this.commands[this.commands.length - 1];
3063
+ }
3064
+ if (alias === command._name)
3065
+ throw new Error("Command alias can't be the same as its name");
3066
+ const matchingCommand = this.parent?._findCommand(alias);
3067
+ if (matchingCommand) {
3068
+ const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
3069
+ throw new Error(
3070
+ `cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`
3071
+ );
3072
+ }
3073
+ command._aliases.push(alias);
3074
+ return this;
3075
+ }
3076
+ /**
3077
+ * Set aliases for the command.
3078
+ *
3079
+ * Only the first alias is shown in the auto-generated help.
3080
+ *
3081
+ * @param {string[]} [aliases]
3082
+ * @return {(string[]|Command)}
3083
+ */
3084
+ aliases(aliases) {
3085
+ if (aliases === void 0) return this._aliases;
3086
+ aliases.forEach((alias) => this.alias(alias));
3087
+ return this;
3088
+ }
3089
+ /**
3090
+ * Set / get the command usage `str`.
3091
+ *
3092
+ * @param {string} [str]
3093
+ * @return {(string|Command)}
3094
+ */
3095
+ usage(str) {
3096
+ if (str === void 0) {
3097
+ if (this._usage) return this._usage;
3098
+ const args = this.registeredArguments.map((arg) => {
3099
+ return humanReadableArgName(arg);
3100
+ });
3101
+ return [].concat(
3102
+ this.options.length || this._helpOption !== null ? "[options]" : [],
3103
+ this.commands.length ? "[command]" : [],
3104
+ this.registeredArguments.length ? args : []
3105
+ ).join(" ");
3106
+ }
3107
+ this._usage = str;
3108
+ return this;
3109
+ }
3110
+ /**
3111
+ * Get or set the name of the command.
3112
+ *
3113
+ * @param {string} [str]
3114
+ * @return {(string|Command)}
3115
+ */
3116
+ name(str) {
3117
+ if (str === void 0) return this._name;
3118
+ this._name = str;
3119
+ return this;
3120
+ }
3121
+ /**
3122
+ * Set/get the help group heading for this subcommand in parent command's help.
3123
+ *
3124
+ * @param {string} [heading]
3125
+ * @return {Command | string}
3126
+ */
3127
+ helpGroup(heading) {
3128
+ if (heading === void 0) return this._helpGroupHeading ?? "";
3129
+ this._helpGroupHeading = heading;
3130
+ return this;
3131
+ }
3132
+ /**
3133
+ * Set/get the default help group heading for subcommands added to this command.
3134
+ * (This does not override a group set directly on the subcommand using .helpGroup().)
3135
+ *
3136
+ * @example
3137
+ * program.commandsGroup('Development Commands:);
3138
+ * program.command('watch')...
3139
+ * program.command('lint')...
3140
+ * ...
3141
+ *
3142
+ * @param {string} [heading]
3143
+ * @returns {Command | string}
3144
+ */
3145
+ commandsGroup(heading) {
3146
+ if (heading === void 0) return this._defaultCommandGroup ?? "";
3147
+ this._defaultCommandGroup = heading;
3148
+ return this;
3149
+ }
3150
+ /**
3151
+ * Set/get the default help group heading for options added to this command.
3152
+ * (This does not override a group set directly on the option using .helpGroup().)
3153
+ *
3154
+ * @example
3155
+ * program
3156
+ * .optionsGroup('Development Options:')
3157
+ * .option('-d, --debug', 'output extra debugging')
3158
+ * .option('-p, --profile', 'output profiling information')
3159
+ *
3160
+ * @param {string} [heading]
3161
+ * @returns {Command | string}
3162
+ */
3163
+ optionsGroup(heading) {
3164
+ if (heading === void 0) return this._defaultOptionGroup ?? "";
3165
+ this._defaultOptionGroup = heading;
3166
+ return this;
3167
+ }
3168
+ /**
3169
+ * @param {Option} option
3170
+ * @private
3171
+ */
3172
+ _initOptionGroup(option) {
3173
+ if (this._defaultOptionGroup && !option.helpGroupHeading)
3174
+ option.helpGroup(this._defaultOptionGroup);
3175
+ }
3176
+ /**
3177
+ * @param {Command} cmd
3178
+ * @private
3179
+ */
3180
+ _initCommandGroup(cmd) {
3181
+ if (this._defaultCommandGroup && !cmd.helpGroup())
3182
+ cmd.helpGroup(this._defaultCommandGroup);
3183
+ }
3184
+ /**
3185
+ * Set the name of the command from script filename, such as process.argv[1],
3186
+ * or require.main.filename, or __filename.
3187
+ *
3188
+ * (Used internally and public although not documented in README.)
3189
+ *
3190
+ * @example
3191
+ * program.nameFromFilename(require.main.filename);
3192
+ *
3193
+ * @param {string} filename
3194
+ * @return {Command}
3195
+ */
3196
+ nameFromFilename(filename) {
3197
+ this._name = path.basename(filename, path.extname(filename));
3198
+ return this;
3199
+ }
3200
+ /**
3201
+ * Get or set the directory for searching for executable subcommands of this command.
3202
+ *
3203
+ * @example
3204
+ * program.executableDir(__dirname);
3205
+ * // or
3206
+ * program.executableDir('subcommands');
3207
+ *
3208
+ * @param {string} [path]
3209
+ * @return {(string|null|Command)}
3210
+ */
3211
+ executableDir(path2) {
3212
+ if (path2 === void 0) return this._executableDir;
3213
+ this._executableDir = path2;
3214
+ return this;
3215
+ }
3216
+ /**
3217
+ * Return program help documentation.
3218
+ *
3219
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
3220
+ * @return {string}
3221
+ */
3222
+ helpInformation(contextOptions) {
3223
+ const helper = this.createHelp();
3224
+ const context = this._getOutputContext(contextOptions);
3225
+ helper.prepareContext({
3226
+ error: context.error,
3227
+ helpWidth: context.helpWidth,
3228
+ outputHasColors: context.hasColors
3229
+ });
3230
+ const text = helper.formatHelp(this, helper);
3231
+ if (context.hasColors) return text;
3232
+ return this._outputConfiguration.stripColor(text);
3233
+ }
3234
+ /**
3235
+ * @typedef HelpContext
3236
+ * @type {object}
3237
+ * @property {boolean} error
3238
+ * @property {number} helpWidth
3239
+ * @property {boolean} hasColors
3240
+ * @property {function} write - includes stripColor if needed
3241
+ *
3242
+ * @returns {HelpContext}
3243
+ * @private
3244
+ */
3245
+ _getOutputContext(contextOptions) {
3246
+ contextOptions = contextOptions || {};
3247
+ const error = !!contextOptions.error;
3248
+ let baseWrite;
3249
+ let hasColors;
3250
+ let helpWidth;
3251
+ if (error) {
3252
+ baseWrite = (str) => this._outputConfiguration.writeErr(str);
3253
+ hasColors = this._outputConfiguration.getErrHasColors();
3254
+ helpWidth = this._outputConfiguration.getErrHelpWidth();
3255
+ } else {
3256
+ baseWrite = (str) => this._outputConfiguration.writeOut(str);
3257
+ hasColors = this._outputConfiguration.getOutHasColors();
3258
+ helpWidth = this._outputConfiguration.getOutHelpWidth();
3259
+ }
3260
+ const write = (str) => {
3261
+ if (!hasColors) str = this._outputConfiguration.stripColor(str);
3262
+ return baseWrite(str);
3263
+ };
3264
+ return { error, write, hasColors, helpWidth };
3265
+ }
3266
+ /**
3267
+ * Output help information for this command.
3268
+ *
3269
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
3270
+ *
3271
+ * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
3272
+ */
3273
+ outputHelp(contextOptions) {
3274
+ let deprecatedCallback;
3275
+ if (typeof contextOptions === "function") {
3276
+ deprecatedCallback = contextOptions;
3277
+ contextOptions = void 0;
3278
+ }
3279
+ const outputContext = this._getOutputContext(contextOptions);
3280
+ const eventContext = {
3281
+ error: outputContext.error,
3282
+ write: outputContext.write,
3283
+ command: this
3284
+ };
3285
+ this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", eventContext));
3286
+ this.emit("beforeHelp", eventContext);
3287
+ let helpInformation = this.helpInformation({ error: outputContext.error });
3288
+ if (deprecatedCallback) {
3289
+ helpInformation = deprecatedCallback(helpInformation);
3290
+ if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
3291
+ throw new Error("outputHelp callback must return a string or a Buffer");
3292
+ }
3293
+ }
3294
+ outputContext.write(helpInformation);
3295
+ if (this._getHelpOption()?.long) {
3296
+ this.emit(this._getHelpOption().long);
3297
+ }
3298
+ this.emit("afterHelp", eventContext);
3299
+ this._getCommandAndAncestors().forEach(
3300
+ (command) => command.emit("afterAllHelp", eventContext)
3301
+ );
3302
+ }
3303
+ /**
3304
+ * You can pass in flags and a description to customise the built-in help option.
3305
+ * Pass in false to disable the built-in help option.
3306
+ *
3307
+ * @example
3308
+ * program.helpOption('-?, --help' 'show help'); // customise
3309
+ * program.helpOption(false); // disable
3310
+ *
3311
+ * @param {(string | boolean)} flags
3312
+ * @param {string} [description]
3313
+ * @return {Command} `this` command for chaining
3314
+ */
3315
+ helpOption(flags, description) {
3316
+ if (typeof flags === "boolean") {
3317
+ if (flags) {
3318
+ if (this._helpOption === null) this._helpOption = void 0;
3319
+ if (this._defaultOptionGroup) {
3320
+ this._initOptionGroup(this._getHelpOption());
3321
+ }
3322
+ } else {
3323
+ this._helpOption = null;
3324
+ }
3325
+ return this;
3326
+ }
3327
+ this._helpOption = this.createOption(
3328
+ flags ?? "-h, --help",
3329
+ description ?? "display help for command"
3330
+ );
3331
+ if (flags || description) this._initOptionGroup(this._helpOption);
3332
+ return this;
3333
+ }
3334
+ /**
3335
+ * Lazy create help option.
3336
+ * Returns null if has been disabled with .helpOption(false).
3337
+ *
3338
+ * @returns {(Option | null)} the help option
3339
+ * @package
3340
+ */
3341
+ _getHelpOption() {
3342
+ if (this._helpOption === void 0) {
3343
+ this.helpOption(void 0, void 0);
3344
+ }
3345
+ return this._helpOption;
3346
+ }
3347
+ /**
3348
+ * Supply your own option to use for the built-in help option.
3349
+ * This is an alternative to using helpOption() to customise the flags and description etc.
3350
+ *
3351
+ * @param {Option} option
3352
+ * @return {Command} `this` command for chaining
3353
+ */
3354
+ addHelpOption(option) {
3355
+ this._helpOption = option;
3356
+ this._initOptionGroup(option);
3357
+ return this;
3358
+ }
3359
+ /**
3360
+ * Output help information and exit.
3361
+ *
3362
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
3363
+ *
3364
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
3365
+ */
3366
+ help(contextOptions) {
3367
+ this.outputHelp(contextOptions);
3368
+ let exitCode = Number(process2.exitCode ?? 0);
3369
+ if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
3370
+ exitCode = 1;
3371
+ }
3372
+ this._exit(exitCode, "commander.help", "(outputHelp)");
3373
+ }
3374
+ /**
3375
+ * // Do a little typing to coordinate emit and listener for the help text events.
3376
+ * @typedef HelpTextEventContext
3377
+ * @type {object}
3378
+ * @property {boolean} error
3379
+ * @property {Command} command
3380
+ * @property {function} write
3381
+ */
3382
+ /**
3383
+ * Add additional text to be displayed with the built-in help.
3384
+ *
3385
+ * Position is 'before' or 'after' to affect just this command,
3386
+ * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
3387
+ *
3388
+ * @param {string} position - before or after built-in help
3389
+ * @param {(string | Function)} text - string to add, or a function returning a string
3390
+ * @return {Command} `this` command for chaining
3391
+ */
3392
+ addHelpText(position, text) {
3393
+ const allowedValues = ["beforeAll", "before", "after", "afterAll"];
3394
+ if (!allowedValues.includes(position)) {
3395
+ throw new Error(`Unexpected value for position to addHelpText.
3396
+ Expecting one of '${allowedValues.join("', '")}'`);
3397
+ }
3398
+ const helpEvent = `${position}Help`;
3399
+ this.on(helpEvent, (context) => {
3400
+ let helpStr;
3401
+ if (typeof text === "function") {
3402
+ helpStr = text({ error: context.error, command: context.command });
3403
+ } else {
3404
+ helpStr = text;
3405
+ }
3406
+ if (helpStr) {
3407
+ context.write(`${helpStr}
3408
+ `);
3409
+ }
3410
+ });
3411
+ return this;
3412
+ }
3413
+ /**
3414
+ * Output help information if help flags specified
3415
+ *
3416
+ * @param {Array} args - array of options to search for help flags
3417
+ * @private
3418
+ */
3419
+ _outputHelpIfRequested(args) {
3420
+ const helpOption = this._getHelpOption();
3421
+ const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
3422
+ if (helpRequested) {
3423
+ this.outputHelp();
3424
+ this._exit(0, "commander.helpDisplayed", "(outputHelp)");
3425
+ }
3426
+ }
3427
+ };
3428
+ function incrementNodeInspectorPort(args) {
3429
+ return args.map((arg) => {
3430
+ if (!arg.startsWith("--inspect")) {
3431
+ return arg;
3432
+ }
3433
+ let debugOption;
3434
+ let debugHost = "127.0.0.1";
3435
+ let debugPort = "9229";
3436
+ let match;
3437
+ if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
3438
+ debugOption = match[1];
3439
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
3440
+ debugOption = match[1];
3441
+ if (/^\d+$/.test(match[3])) {
3442
+ debugPort = match[3];
3443
+ } else {
3444
+ debugHost = match[3];
3445
+ }
3446
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
3447
+ debugOption = match[1];
3448
+ debugHost = match[3];
3449
+ debugPort = match[4];
3450
+ }
3451
+ if (debugOption && debugPort !== "0") {
3452
+ return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
3453
+ }
3454
+ return arg;
3455
+ });
3456
+ }
3457
+ function useColor() {
3458
+ if (process2.env.NO_COLOR || process2.env.FORCE_COLOR === "0" || process2.env.FORCE_COLOR === "false")
3459
+ return false;
3460
+ if (process2.env.FORCE_COLOR || process2.env.CLICOLOR_FORCE !== void 0)
3461
+ return true;
3462
+ return void 0;
3463
+ }
3464
+ exports.Command = Command2;
3465
+ exports.useColor = useColor;
3466
+ }
3467
+ });
3468
+
3469
+ // ../../node_modules/.pnpm/commander@14.0.3/node_modules/commander/index.js
3470
+ var require_commander = __commonJS({
3471
+ "../../node_modules/.pnpm/commander@14.0.3/node_modules/commander/index.js"(exports) {
3472
+ "use strict";
3473
+ var { Argument: Argument2 } = require_argument();
3474
+ var { Command: Command2 } = require_command();
3475
+ var { CommanderError: CommanderError2, InvalidArgumentError: InvalidArgumentError2 } = require_error();
3476
+ var { Help: Help2 } = require_help();
3477
+ var { Option: Option2 } = require_option();
3478
+ exports.program = new Command2();
3479
+ exports.createCommand = (name) => new Command2(name);
3480
+ exports.createOption = (flags, description) => new Option2(flags, description);
3481
+ exports.createArgument = (name, description) => new Argument2(name, description);
3482
+ exports.Command = Command2;
3483
+ exports.Option = Option2;
3484
+ exports.Argument = Argument2;
3485
+ exports.Help = Help2;
3486
+ exports.CommanderError = CommanderError2;
3487
+ exports.InvalidArgumentError = InvalidArgumentError2;
3488
+ exports.InvalidOptionArgumentError = InvalidArgumentError2;
3489
+ }
3490
+ });
3491
+
3492
+ // ../dune/cli/commands/skills.ts
3493
+ import { execFileSync } from "child_process";
3494
+ import { createRequire } from "module";
3495
+
3496
+ // ../../node_modules/.pnpm/commander@14.0.3/node_modules/commander/esm.mjs
3497
+ var import_index = __toESM(require_commander(), 1);
3498
+ var {
3499
+ program,
3500
+ createCommand,
3501
+ createArgument,
3502
+ createOption,
3503
+ CommanderError,
3504
+ InvalidArgumentError,
3505
+ InvalidOptionArgumentError,
3506
+ // deprecated old name
3507
+ Command,
3508
+ Argument,
3509
+ Option,
3510
+ Help
3511
+ } = import_index.default;
3512
+
3513
+ // ../dune/cli/commands/skills.ts
3514
+ var SKILL_SOURCE = "cognitedata/builder-skills";
3515
+ var SUPPORTED_AGENTS = ["claude-code", "cursor"];
3516
+ var AGENT_FLAGS = SUPPORTED_AGENTS.flatMap((agent) => ["-a", agent]);
3517
+ var SKILLS_BIN = createRequire(import.meta.url).resolve("skills/bin/cli.mjs");
3518
+ function execSkillsCli(args, options = {}) {
3519
+ execFileSync(process.execPath, [SKILLS_BIN, ...args], {
3520
+ stdio: "inherit",
3521
+ cwd: process.cwd(),
3522
+ ...options
3523
+ });
3524
+ }
3525
+ function pullAllArgs() {
3526
+ return ["add", SKILL_SOURCE, ...AGENT_FLAGS, "--skill", "*", "-y"];
3527
+ }
3528
+ function validateSource(value) {
3529
+ if (!/^[\w.-]+\/[\w.-]+$/.test(value)) {
3530
+ throw new InvalidArgumentError(
3531
+ "Expected owner/repo format (e.g., cognitedata/builder-skills)"
3532
+ );
3533
+ }
3534
+ return value;
3535
+ }
3536
+ function buildPullArgs(options) {
3537
+ const args = ["add", options.source, ...AGENT_FLAGS];
3538
+ if (options.skill) {
3539
+ args.push("--skill", options.skill);
3540
+ } else if (!options.interactive) {
3541
+ args.push("--skill", "*", "-y");
3542
+ }
3543
+ if (options.global) {
3544
+ args.push("--global");
3545
+ }
3546
+ return args;
3547
+ }
3548
+ function handlePull(options) {
3549
+ console.log(`\u{1F504} Pulling skills from ${options.source}...`);
3550
+ execSkillsCli(buildPullArgs(options));
3551
+ console.log("\n\u2705 Skills pulled successfully");
3552
+ }
3553
+ function registerSkillsCommand(parent) {
3554
+ const skills = parent.command("skills").summary("Manage AI agent skills for your Dune app").description(`Manage AI agent skills for your Dune app.
3555
+ Supports: ${SUPPORTED_AGENTS.join(", ")}`).addHelpText("after", `
3556
+ Examples:
3557
+ npx @cognite/dune skills pull Pull all skills
3558
+ npx @cognite/dune skills pull --skill create-client-tool Pull a specific skill
3559
+ npx @cognite/dune skills list List installed skills`);
3560
+ skills.command("pull").description("Pull all skills into your project").option(
3561
+ "--source <owner/repo>",
3562
+ "Skills repository",
3563
+ validateSource,
3564
+ SKILL_SOURCE
3565
+ ).option("--skill <name>", "Pull a specific skill by name").option("-i, --interactive", "Interactively select which skills to install", false).option("--global", "Install skills globally", false).action(handlePull);
3566
+ skills.command("list").description("List installed skills").action(() => {
3567
+ execSkillsCli(["list"]);
3568
+ });
3569
+ }
3570
+
3571
+ export {
3572
+ __require,
3573
+ __esm,
3574
+ __commonJS,
3575
+ __export,
3576
+ __toESM,
3577
+ __toCommonJS,
3578
+ __publicField,
3579
+ __privateGet,
3580
+ __privateAdd,
3581
+ __privateSet,
3582
+ __privateMethod,
3583
+ __privateWrapper,
3584
+ Command,
3585
+ execSkillsCli,
3586
+ pullAllArgs,
3587
+ buildPullArgs,
3588
+ registerSkillsCommand
3589
+ };