pingcode-cli-unofficial 1.8.2 → 1.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,13 +1,3141 @@
1
1
  #!/usr/bin/env node
2
+ import { createRequire as __cr } from "node:module"; const require = __cr(import.meta.url);
3
+ var __create = Object.create;
2
4
  var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
6
  var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
10
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
11
+ }) : x)(function(x) {
12
+ if (typeof require !== "undefined") return require.apply(this, arguments);
13
+ throw Error('Dynamic require of "' + x + '" is not supported');
14
+ });
4
15
  var __esm = (fn, res) => function __init() {
5
16
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
6
17
  };
18
+ var __commonJS = (cb, mod) => function __require2() {
19
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
20
+ };
7
21
  var __export = (target, all) => {
8
22
  for (var name in all)
9
23
  __defProp(target, name, { get: all[name], enumerable: true });
10
24
  };
25
+ var __copyProps = (to, from, except, desc) => {
26
+ if (from && typeof from === "object" || typeof from === "function") {
27
+ for (let key of __getOwnPropNames(from))
28
+ if (!__hasOwnProp.call(to, key) && key !== except)
29
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
30
+ }
31
+ return to;
32
+ };
33
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
34
+ // If the importer is in node compatibility mode or this is not an ESM
35
+ // file that has been converted to a CommonJS file using a Babel-
36
+ // compatible transform (i.e. "__esModule" has not been set), then set
37
+ // "default" to the CommonJS "module.exports" for node compatibility.
38
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
39
+ mod
40
+ ));
41
+
42
+ // node_modules/commander/lib/error.js
43
+ var require_error = __commonJS({
44
+ "node_modules/commander/lib/error.js"(exports) {
45
+ "use strict";
46
+ var CommanderError2 = class extends Error {
47
+ /**
48
+ * Constructs the CommanderError class
49
+ * @param {number} exitCode suggested exit code which could be used with process.exit
50
+ * @param {string} code an id string representing the error
51
+ * @param {string} message human-readable description of the error
52
+ */
53
+ constructor(exitCode, code, message) {
54
+ super(message);
55
+ Error.captureStackTrace(this, this.constructor);
56
+ this.name = this.constructor.name;
57
+ this.code = code;
58
+ this.exitCode = exitCode;
59
+ this.nestedError = void 0;
60
+ }
61
+ };
62
+ var InvalidArgumentError2 = class extends CommanderError2 {
63
+ /**
64
+ * Constructs the InvalidArgumentError class
65
+ * @param {string} [message] explanation of why argument is invalid
66
+ */
67
+ constructor(message) {
68
+ super(1, "commander.invalidArgument", message);
69
+ Error.captureStackTrace(this, this.constructor);
70
+ this.name = this.constructor.name;
71
+ }
72
+ };
73
+ exports.CommanderError = CommanderError2;
74
+ exports.InvalidArgumentError = InvalidArgumentError2;
75
+ }
76
+ });
77
+
78
+ // node_modules/commander/lib/argument.js
79
+ var require_argument = __commonJS({
80
+ "node_modules/commander/lib/argument.js"(exports) {
81
+ "use strict";
82
+ var { InvalidArgumentError: InvalidArgumentError2 } = require_error();
83
+ var Argument2 = class {
84
+ /**
85
+ * Initialize a new command argument with the given name and description.
86
+ * The default is that the argument is required, and you can explicitly
87
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
88
+ *
89
+ * @param {string} name
90
+ * @param {string} [description]
91
+ */
92
+ constructor(name, description) {
93
+ this.description = description || "";
94
+ this.variadic = false;
95
+ this.parseArg = void 0;
96
+ this.defaultValue = void 0;
97
+ this.defaultValueDescription = void 0;
98
+ this.argChoices = void 0;
99
+ switch (name[0]) {
100
+ case "<":
101
+ this.required = true;
102
+ this._name = name.slice(1, -1);
103
+ break;
104
+ case "[":
105
+ this.required = false;
106
+ this._name = name.slice(1, -1);
107
+ break;
108
+ default:
109
+ this.required = true;
110
+ this._name = name;
111
+ break;
112
+ }
113
+ if (this._name.length > 3 && this._name.slice(-3) === "...") {
114
+ this.variadic = true;
115
+ this._name = this._name.slice(0, -3);
116
+ }
117
+ }
118
+ /**
119
+ * Return argument name.
120
+ *
121
+ * @return {string}
122
+ */
123
+ name() {
124
+ return this._name;
125
+ }
126
+ /**
127
+ * @package
128
+ */
129
+ _concatValue(value, previous) {
130
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
131
+ return [value];
132
+ }
133
+ return previous.concat(value);
134
+ }
135
+ /**
136
+ * Set the default value, and optionally supply the description to be displayed in the help.
137
+ *
138
+ * @param {*} value
139
+ * @param {string} [description]
140
+ * @return {Argument}
141
+ */
142
+ default(value, description) {
143
+ this.defaultValue = value;
144
+ this.defaultValueDescription = description;
145
+ return this;
146
+ }
147
+ /**
148
+ * Set the custom handler for processing CLI command arguments into argument values.
149
+ *
150
+ * @param {Function} [fn]
151
+ * @return {Argument}
152
+ */
153
+ argParser(fn) {
154
+ this.parseArg = fn;
155
+ return this;
156
+ }
157
+ /**
158
+ * Only allow argument value to be one of choices.
159
+ *
160
+ * @param {string[]} values
161
+ * @return {Argument}
162
+ */
163
+ choices(values) {
164
+ this.argChoices = values.slice();
165
+ this.parseArg = (arg, previous) => {
166
+ if (!this.argChoices.includes(arg)) {
167
+ throw new InvalidArgumentError2(
168
+ `Allowed choices are ${this.argChoices.join(", ")}.`
169
+ );
170
+ }
171
+ if (this.variadic) {
172
+ return this._concatValue(arg, previous);
173
+ }
174
+ return arg;
175
+ };
176
+ return this;
177
+ }
178
+ /**
179
+ * Make argument required.
180
+ *
181
+ * @returns {Argument}
182
+ */
183
+ argRequired() {
184
+ this.required = true;
185
+ return this;
186
+ }
187
+ /**
188
+ * Make argument optional.
189
+ *
190
+ * @returns {Argument}
191
+ */
192
+ argOptional() {
193
+ this.required = false;
194
+ return this;
195
+ }
196
+ };
197
+ function humanReadableArgName(arg) {
198
+ const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
199
+ return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
200
+ }
201
+ exports.Argument = Argument2;
202
+ exports.humanReadableArgName = humanReadableArgName;
203
+ }
204
+ });
205
+
206
+ // node_modules/commander/lib/help.js
207
+ var require_help = __commonJS({
208
+ "node_modules/commander/lib/help.js"(exports) {
209
+ "use strict";
210
+ var { humanReadableArgName } = require_argument();
211
+ var Help2 = class {
212
+ constructor() {
213
+ this.helpWidth = void 0;
214
+ this.sortSubcommands = false;
215
+ this.sortOptions = false;
216
+ this.showGlobalOptions = false;
217
+ }
218
+ /**
219
+ * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
220
+ *
221
+ * @param {Command} cmd
222
+ * @returns {Command[]}
223
+ */
224
+ visibleCommands(cmd) {
225
+ const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
226
+ const helpCommand = cmd._getHelpCommand();
227
+ if (helpCommand && !helpCommand._hidden) {
228
+ visibleCommands.push(helpCommand);
229
+ }
230
+ if (this.sortSubcommands) {
231
+ visibleCommands.sort((a, b) => {
232
+ return a.name().localeCompare(b.name());
233
+ });
234
+ }
235
+ return visibleCommands;
236
+ }
237
+ /**
238
+ * Compare options for sort.
239
+ *
240
+ * @param {Option} a
241
+ * @param {Option} b
242
+ * @returns {number}
243
+ */
244
+ compareOptions(a, b) {
245
+ const getSortKey = (option) => {
246
+ return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
247
+ };
248
+ return getSortKey(a).localeCompare(getSortKey(b));
249
+ }
250
+ /**
251
+ * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
252
+ *
253
+ * @param {Command} cmd
254
+ * @returns {Option[]}
255
+ */
256
+ visibleOptions(cmd) {
257
+ const visibleOptions = cmd.options.filter((option) => !option.hidden);
258
+ const helpOption = cmd._getHelpOption();
259
+ if (helpOption && !helpOption.hidden) {
260
+ const removeShort = helpOption.short && cmd._findOption(helpOption.short);
261
+ const removeLong = helpOption.long && cmd._findOption(helpOption.long);
262
+ if (!removeShort && !removeLong) {
263
+ visibleOptions.push(helpOption);
264
+ } else if (helpOption.long && !removeLong) {
265
+ visibleOptions.push(
266
+ cmd.createOption(helpOption.long, helpOption.description)
267
+ );
268
+ } else if (helpOption.short && !removeShort) {
269
+ visibleOptions.push(
270
+ cmd.createOption(helpOption.short, helpOption.description)
271
+ );
272
+ }
273
+ }
274
+ if (this.sortOptions) {
275
+ visibleOptions.sort(this.compareOptions);
276
+ }
277
+ return visibleOptions;
278
+ }
279
+ /**
280
+ * Get an array of the visible global options. (Not including help.)
281
+ *
282
+ * @param {Command} cmd
283
+ * @returns {Option[]}
284
+ */
285
+ visibleGlobalOptions(cmd) {
286
+ if (!this.showGlobalOptions) return [];
287
+ const globalOptions = [];
288
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
289
+ const visibleOptions = ancestorCmd.options.filter(
290
+ (option) => !option.hidden
291
+ );
292
+ globalOptions.push(...visibleOptions);
293
+ }
294
+ if (this.sortOptions) {
295
+ globalOptions.sort(this.compareOptions);
296
+ }
297
+ return globalOptions;
298
+ }
299
+ /**
300
+ * Get an array of the arguments if any have a description.
301
+ *
302
+ * @param {Command} cmd
303
+ * @returns {Argument[]}
304
+ */
305
+ visibleArguments(cmd) {
306
+ if (cmd._argsDescription) {
307
+ cmd.registeredArguments.forEach((argument) => {
308
+ argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
309
+ });
310
+ }
311
+ if (cmd.registeredArguments.find((argument) => argument.description)) {
312
+ return cmd.registeredArguments;
313
+ }
314
+ return [];
315
+ }
316
+ /**
317
+ * Get the command term to show in the list of subcommands.
318
+ *
319
+ * @param {Command} cmd
320
+ * @returns {string}
321
+ */
322
+ subcommandTerm(cmd) {
323
+ const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
324
+ return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + // simplistic check for non-help option
325
+ (args ? " " + args : "");
326
+ }
327
+ /**
328
+ * Get the option term to show in the list of options.
329
+ *
330
+ * @param {Option} option
331
+ * @returns {string}
332
+ */
333
+ optionTerm(option) {
334
+ return option.flags;
335
+ }
336
+ /**
337
+ * Get the argument term to show in the list of arguments.
338
+ *
339
+ * @param {Argument} argument
340
+ * @returns {string}
341
+ */
342
+ argumentTerm(argument) {
343
+ return argument.name();
344
+ }
345
+ /**
346
+ * Get the longest command term length.
347
+ *
348
+ * @param {Command} cmd
349
+ * @param {Help} helper
350
+ * @returns {number}
351
+ */
352
+ longestSubcommandTermLength(cmd, helper) {
353
+ return helper.visibleCommands(cmd).reduce((max, command) => {
354
+ return Math.max(max, helper.subcommandTerm(command).length);
355
+ }, 0);
356
+ }
357
+ /**
358
+ * Get the longest option term length.
359
+ *
360
+ * @param {Command} cmd
361
+ * @param {Help} helper
362
+ * @returns {number}
363
+ */
364
+ longestOptionTermLength(cmd, helper) {
365
+ return helper.visibleOptions(cmd).reduce((max, option) => {
366
+ return Math.max(max, helper.optionTerm(option).length);
367
+ }, 0);
368
+ }
369
+ /**
370
+ * Get the longest global option term length.
371
+ *
372
+ * @param {Command} cmd
373
+ * @param {Help} helper
374
+ * @returns {number}
375
+ */
376
+ longestGlobalOptionTermLength(cmd, helper) {
377
+ return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
378
+ return Math.max(max, helper.optionTerm(option).length);
379
+ }, 0);
380
+ }
381
+ /**
382
+ * Get the longest argument term length.
383
+ *
384
+ * @param {Command} cmd
385
+ * @param {Help} helper
386
+ * @returns {number}
387
+ */
388
+ longestArgumentTermLength(cmd, helper) {
389
+ return helper.visibleArguments(cmd).reduce((max, argument) => {
390
+ return Math.max(max, helper.argumentTerm(argument).length);
391
+ }, 0);
392
+ }
393
+ /**
394
+ * Get the command usage to be displayed at the top of the built-in help.
395
+ *
396
+ * @param {Command} cmd
397
+ * @returns {string}
398
+ */
399
+ commandUsage(cmd) {
400
+ let cmdName = cmd._name;
401
+ if (cmd._aliases[0]) {
402
+ cmdName = cmdName + "|" + cmd._aliases[0];
403
+ }
404
+ let ancestorCmdNames = "";
405
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
406
+ ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
407
+ }
408
+ return ancestorCmdNames + cmdName + " " + cmd.usage();
409
+ }
410
+ /**
411
+ * Get the description for the command.
412
+ *
413
+ * @param {Command} cmd
414
+ * @returns {string}
415
+ */
416
+ commandDescription(cmd) {
417
+ return cmd.description();
418
+ }
419
+ /**
420
+ * Get the subcommand summary to show in the list of subcommands.
421
+ * (Fallback to description for backwards compatibility.)
422
+ *
423
+ * @param {Command} cmd
424
+ * @returns {string}
425
+ */
426
+ subcommandDescription(cmd) {
427
+ return cmd.summary() || cmd.description();
428
+ }
429
+ /**
430
+ * Get the option description to show in the list of options.
431
+ *
432
+ * @param {Option} option
433
+ * @return {string}
434
+ */
435
+ optionDescription(option) {
436
+ const extraInfo = [];
437
+ if (option.argChoices) {
438
+ extraInfo.push(
439
+ // use stringify to match the display of the default value
440
+ `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
441
+ );
442
+ }
443
+ if (option.defaultValue !== void 0) {
444
+ const showDefault = option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean";
445
+ if (showDefault) {
446
+ extraInfo.push(
447
+ `default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`
448
+ );
449
+ }
450
+ }
451
+ if (option.presetArg !== void 0 && option.optional) {
452
+ extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
453
+ }
454
+ if (option.envVar !== void 0) {
455
+ extraInfo.push(`env: ${option.envVar}`);
456
+ }
457
+ if (extraInfo.length > 0) {
458
+ return `${option.description} (${extraInfo.join(", ")})`;
459
+ }
460
+ return option.description;
461
+ }
462
+ /**
463
+ * Get the argument description to show in the list of arguments.
464
+ *
465
+ * @param {Argument} argument
466
+ * @return {string}
467
+ */
468
+ argumentDescription(argument) {
469
+ const extraInfo = [];
470
+ if (argument.argChoices) {
471
+ extraInfo.push(
472
+ // use stringify to match the display of the default value
473
+ `choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
474
+ );
475
+ }
476
+ if (argument.defaultValue !== void 0) {
477
+ extraInfo.push(
478
+ `default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`
479
+ );
480
+ }
481
+ if (extraInfo.length > 0) {
482
+ const extraDescripton = `(${extraInfo.join(", ")})`;
483
+ if (argument.description) {
484
+ return `${argument.description} ${extraDescripton}`;
485
+ }
486
+ return extraDescripton;
487
+ }
488
+ return argument.description;
489
+ }
490
+ /**
491
+ * Generate the built-in help text.
492
+ *
493
+ * @param {Command} cmd
494
+ * @param {Help} helper
495
+ * @returns {string}
496
+ */
497
+ formatHelp(cmd, helper) {
498
+ const termWidth = helper.padWidth(cmd, helper);
499
+ const helpWidth = helper.helpWidth || 80;
500
+ const itemIndentWidth = 2;
501
+ const itemSeparatorWidth = 2;
502
+ function formatItem(term, description) {
503
+ if (description) {
504
+ const fullText = `${term.padEnd(termWidth + itemSeparatorWidth)}${description}`;
505
+ return helper.wrap(
506
+ fullText,
507
+ helpWidth - itemIndentWidth,
508
+ termWidth + itemSeparatorWidth
509
+ );
510
+ }
511
+ return term;
512
+ }
513
+ function formatList(textArray) {
514
+ return textArray.join("\n").replace(/^/gm, " ".repeat(itemIndentWidth));
515
+ }
516
+ let output = [`Usage: ${helper.commandUsage(cmd)}`, ""];
517
+ const commandDescription = helper.commandDescription(cmd);
518
+ if (commandDescription.length > 0) {
519
+ output = output.concat([
520
+ helper.wrap(commandDescription, helpWidth, 0),
521
+ ""
522
+ ]);
523
+ }
524
+ const argumentList = helper.visibleArguments(cmd).map((argument) => {
525
+ return formatItem(
526
+ helper.argumentTerm(argument),
527
+ helper.argumentDescription(argument)
528
+ );
529
+ });
530
+ if (argumentList.length > 0) {
531
+ output = output.concat(["Arguments:", formatList(argumentList), ""]);
532
+ }
533
+ const optionList = helper.visibleOptions(cmd).map((option) => {
534
+ return formatItem(
535
+ helper.optionTerm(option),
536
+ helper.optionDescription(option)
537
+ );
538
+ });
539
+ if (optionList.length > 0) {
540
+ output = output.concat(["Options:", formatList(optionList), ""]);
541
+ }
542
+ if (this.showGlobalOptions) {
543
+ const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
544
+ return formatItem(
545
+ helper.optionTerm(option),
546
+ helper.optionDescription(option)
547
+ );
548
+ });
549
+ if (globalOptionList.length > 0) {
550
+ output = output.concat([
551
+ "Global Options:",
552
+ formatList(globalOptionList),
553
+ ""
554
+ ]);
555
+ }
556
+ }
557
+ const commandList = helper.visibleCommands(cmd).map((cmd2) => {
558
+ return formatItem(
559
+ helper.subcommandTerm(cmd2),
560
+ helper.subcommandDescription(cmd2)
561
+ );
562
+ });
563
+ if (commandList.length > 0) {
564
+ output = output.concat(["Commands:", formatList(commandList), ""]);
565
+ }
566
+ return output.join("\n");
567
+ }
568
+ /**
569
+ * Calculate the pad width from the maximum term length.
570
+ *
571
+ * @param {Command} cmd
572
+ * @param {Help} helper
573
+ * @returns {number}
574
+ */
575
+ padWidth(cmd, helper) {
576
+ return Math.max(
577
+ helper.longestOptionTermLength(cmd, helper),
578
+ helper.longestGlobalOptionTermLength(cmd, helper),
579
+ helper.longestSubcommandTermLength(cmd, helper),
580
+ helper.longestArgumentTermLength(cmd, helper)
581
+ );
582
+ }
583
+ /**
584
+ * Wrap the given string to width characters per line, with lines after the first indented.
585
+ * Do not wrap if insufficient room for wrapping (minColumnWidth), or string is manually formatted.
586
+ *
587
+ * @param {string} str
588
+ * @param {number} width
589
+ * @param {number} indent
590
+ * @param {number} [minColumnWidth=40]
591
+ * @return {string}
592
+ *
593
+ */
594
+ wrap(str2, width, indent, minColumnWidth = 40) {
595
+ const indents = " \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF";
596
+ const manualIndent = new RegExp(`[\\n][${indents}]+`);
597
+ if (str2.match(manualIndent)) return str2;
598
+ const columnWidth = width - indent;
599
+ if (columnWidth < minColumnWidth) return str2;
600
+ const leadingStr = str2.slice(0, indent);
601
+ const columnText = str2.slice(indent).replace("\r\n", "\n");
602
+ const indentString = " ".repeat(indent);
603
+ const zeroWidthSpace = "\u200B";
604
+ const breaks = `\\s${zeroWidthSpace}`;
605
+ const regex = new RegExp(
606
+ `
607
+ |.{1,${columnWidth - 1}}([${breaks}]|$)|[^${breaks}]+?([${breaks}]|$)`,
608
+ "g"
609
+ );
610
+ const lines = columnText.match(regex) || [];
611
+ return leadingStr + lines.map((line, i) => {
612
+ if (line === "\n") return "";
613
+ return (i > 0 ? indentString : "") + line.trimEnd();
614
+ }).join("\n");
615
+ }
616
+ };
617
+ exports.Help = Help2;
618
+ }
619
+ });
620
+
621
+ // node_modules/commander/lib/option.js
622
+ var require_option = __commonJS({
623
+ "node_modules/commander/lib/option.js"(exports) {
624
+ "use strict";
625
+ var { InvalidArgumentError: InvalidArgumentError2 } = require_error();
626
+ var Option2 = class {
627
+ /**
628
+ * Initialize a new `Option` with the given `flags` and `description`.
629
+ *
630
+ * @param {string} flags
631
+ * @param {string} [description]
632
+ */
633
+ constructor(flags, description) {
634
+ this.flags = flags;
635
+ this.description = description || "";
636
+ this.required = flags.includes("<");
637
+ this.optional = flags.includes("[");
638
+ this.variadic = /\w\.\.\.[>\]]$/.test(flags);
639
+ this.mandatory = false;
640
+ const optionFlags = splitOptionFlags(flags);
641
+ this.short = optionFlags.shortFlag;
642
+ this.long = optionFlags.longFlag;
643
+ this.negate = false;
644
+ if (this.long) {
645
+ this.negate = this.long.startsWith("--no-");
646
+ }
647
+ this.defaultValue = void 0;
648
+ this.defaultValueDescription = void 0;
649
+ this.presetArg = void 0;
650
+ this.envVar = void 0;
651
+ this.parseArg = void 0;
652
+ this.hidden = false;
653
+ this.argChoices = void 0;
654
+ this.conflictsWith = [];
655
+ this.implied = void 0;
656
+ }
657
+ /**
658
+ * Set the default value, and optionally supply the description to be displayed in the help.
659
+ *
660
+ * @param {*} value
661
+ * @param {string} [description]
662
+ * @return {Option}
663
+ */
664
+ default(value, description) {
665
+ this.defaultValue = value;
666
+ this.defaultValueDescription = description;
667
+ return this;
668
+ }
669
+ /**
670
+ * Preset to use when option used without option-argument, especially optional but also boolean and negated.
671
+ * The custom processing (parseArg) is called.
672
+ *
673
+ * @example
674
+ * new Option('--color').default('GREYSCALE').preset('RGB');
675
+ * new Option('--donate [amount]').preset('20').argParser(parseFloat);
676
+ *
677
+ * @param {*} arg
678
+ * @return {Option}
679
+ */
680
+ preset(arg) {
681
+ this.presetArg = arg;
682
+ return this;
683
+ }
684
+ /**
685
+ * Add option name(s) that conflict with this option.
686
+ * An error will be displayed if conflicting options are found during parsing.
687
+ *
688
+ * @example
689
+ * new Option('--rgb').conflicts('cmyk');
690
+ * new Option('--js').conflicts(['ts', 'jsx']);
691
+ *
692
+ * @param {(string | string[])} names
693
+ * @return {Option}
694
+ */
695
+ conflicts(names) {
696
+ this.conflictsWith = this.conflictsWith.concat(names);
697
+ return this;
698
+ }
699
+ /**
700
+ * Specify implied option values for when this option is set and the implied options are not.
701
+ *
702
+ * The custom processing (parseArg) is not called on the implied values.
703
+ *
704
+ * @example
705
+ * program
706
+ * .addOption(new Option('--log', 'write logging information to file'))
707
+ * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
708
+ *
709
+ * @param {object} impliedOptionValues
710
+ * @return {Option}
711
+ */
712
+ implies(impliedOptionValues) {
713
+ let newImplied = impliedOptionValues;
714
+ if (typeof impliedOptionValues === "string") {
715
+ newImplied = { [impliedOptionValues]: true };
716
+ }
717
+ this.implied = Object.assign(this.implied || {}, newImplied);
718
+ return this;
719
+ }
720
+ /**
721
+ * Set environment variable to check for option value.
722
+ *
723
+ * An environment variable is only used if when processed the current option value is
724
+ * undefined, or the source of the current value is 'default' or 'config' or 'env'.
725
+ *
726
+ * @param {string} name
727
+ * @return {Option}
728
+ */
729
+ env(name) {
730
+ this.envVar = name;
731
+ return this;
732
+ }
733
+ /**
734
+ * Set the custom handler for processing CLI option arguments into option values.
735
+ *
736
+ * @param {Function} [fn]
737
+ * @return {Option}
738
+ */
739
+ argParser(fn) {
740
+ this.parseArg = fn;
741
+ return this;
742
+ }
743
+ /**
744
+ * Whether the option is mandatory and must have a value after parsing.
745
+ *
746
+ * @param {boolean} [mandatory=true]
747
+ * @return {Option}
748
+ */
749
+ makeOptionMandatory(mandatory = true) {
750
+ this.mandatory = !!mandatory;
751
+ return this;
752
+ }
753
+ /**
754
+ * Hide option in help.
755
+ *
756
+ * @param {boolean} [hide=true]
757
+ * @return {Option}
758
+ */
759
+ hideHelp(hide = true) {
760
+ this.hidden = !!hide;
761
+ return this;
762
+ }
763
+ /**
764
+ * @package
765
+ */
766
+ _concatValue(value, previous) {
767
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
768
+ return [value];
769
+ }
770
+ return previous.concat(value);
771
+ }
772
+ /**
773
+ * Only allow option value to be one of choices.
774
+ *
775
+ * @param {string[]} values
776
+ * @return {Option}
777
+ */
778
+ choices(values) {
779
+ this.argChoices = values.slice();
780
+ this.parseArg = (arg, previous) => {
781
+ if (!this.argChoices.includes(arg)) {
782
+ throw new InvalidArgumentError2(
783
+ `Allowed choices are ${this.argChoices.join(", ")}.`
784
+ );
785
+ }
786
+ if (this.variadic) {
787
+ return this._concatValue(arg, previous);
788
+ }
789
+ return arg;
790
+ };
791
+ return this;
792
+ }
793
+ /**
794
+ * Return option name.
795
+ *
796
+ * @return {string}
797
+ */
798
+ name() {
799
+ if (this.long) {
800
+ return this.long.replace(/^--/, "");
801
+ }
802
+ return this.short.replace(/^-/, "");
803
+ }
804
+ /**
805
+ * Return option name, in a camelcase format that can be used
806
+ * as a object attribute key.
807
+ *
808
+ * @return {string}
809
+ */
810
+ attributeName() {
811
+ return camelcase(this.name().replace(/^no-/, ""));
812
+ }
813
+ /**
814
+ * Check if `arg` matches the short or long flag.
815
+ *
816
+ * @param {string} arg
817
+ * @return {boolean}
818
+ * @package
819
+ */
820
+ is(arg) {
821
+ return this.short === arg || this.long === arg;
822
+ }
823
+ /**
824
+ * Return whether a boolean option.
825
+ *
826
+ * Options are one of boolean, negated, required argument, or optional argument.
827
+ *
828
+ * @return {boolean}
829
+ * @package
830
+ */
831
+ isBoolean() {
832
+ return !this.required && !this.optional && !this.negate;
833
+ }
834
+ };
835
+ var DualOptions = class {
836
+ /**
837
+ * @param {Option[]} options
838
+ */
839
+ constructor(options) {
840
+ this.positiveOptions = /* @__PURE__ */ new Map();
841
+ this.negativeOptions = /* @__PURE__ */ new Map();
842
+ this.dualOptions = /* @__PURE__ */ new Set();
843
+ options.forEach((option) => {
844
+ if (option.negate) {
845
+ this.negativeOptions.set(option.attributeName(), option);
846
+ } else {
847
+ this.positiveOptions.set(option.attributeName(), option);
848
+ }
849
+ });
850
+ this.negativeOptions.forEach((value, key) => {
851
+ if (this.positiveOptions.has(key)) {
852
+ this.dualOptions.add(key);
853
+ }
854
+ });
855
+ }
856
+ /**
857
+ * Did the value come from the option, and not from possible matching dual option?
858
+ *
859
+ * @param {*} value
860
+ * @param {Option} option
861
+ * @returns {boolean}
862
+ */
863
+ valueFromOption(value, option) {
864
+ const optionKey = option.attributeName();
865
+ if (!this.dualOptions.has(optionKey)) return true;
866
+ const preset = this.negativeOptions.get(optionKey).presetArg;
867
+ const negativeValue = preset !== void 0 ? preset : false;
868
+ return option.negate === (negativeValue === value);
869
+ }
870
+ };
871
+ function camelcase(str2) {
872
+ return str2.split("-").reduce((str3, word) => {
873
+ return str3 + word[0].toUpperCase() + word.slice(1);
874
+ });
875
+ }
876
+ function splitOptionFlags(flags) {
877
+ let shortFlag;
878
+ let longFlag;
879
+ const flagParts = flags.split(/[ |,]+/);
880
+ if (flagParts.length > 1 && !/^[[<]/.test(flagParts[1]))
881
+ shortFlag = flagParts.shift();
882
+ longFlag = flagParts.shift();
883
+ if (!shortFlag && /^-[^-]$/.test(longFlag)) {
884
+ shortFlag = longFlag;
885
+ longFlag = void 0;
886
+ }
887
+ return { shortFlag, longFlag };
888
+ }
889
+ exports.Option = Option2;
890
+ exports.DualOptions = DualOptions;
891
+ }
892
+ });
893
+
894
+ // node_modules/commander/lib/suggestSimilar.js
895
+ var require_suggestSimilar = __commonJS({
896
+ "node_modules/commander/lib/suggestSimilar.js"(exports) {
897
+ "use strict";
898
+ var maxDistance = 3;
899
+ function editDistance2(a, b) {
900
+ if (Math.abs(a.length - b.length) > maxDistance)
901
+ return Math.max(a.length, b.length);
902
+ const d = [];
903
+ for (let i = 0; i <= a.length; i++) {
904
+ d[i] = [i];
905
+ }
906
+ for (let j = 0; j <= b.length; j++) {
907
+ d[0][j] = j;
908
+ }
909
+ for (let j = 1; j <= b.length; j++) {
910
+ for (let i = 1; i <= a.length; i++) {
911
+ let cost = 1;
912
+ if (a[i - 1] === b[j - 1]) {
913
+ cost = 0;
914
+ } else {
915
+ cost = 1;
916
+ }
917
+ d[i][j] = Math.min(
918
+ d[i - 1][j] + 1,
919
+ // deletion
920
+ d[i][j - 1] + 1,
921
+ // insertion
922
+ d[i - 1][j - 1] + cost
923
+ // substitution
924
+ );
925
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
926
+ d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
927
+ }
928
+ }
929
+ }
930
+ return d[a.length][b.length];
931
+ }
932
+ function suggestSimilar(word, candidates) {
933
+ if (!candidates || candidates.length === 0) return "";
934
+ candidates = Array.from(new Set(candidates));
935
+ const searchingOptions = word.startsWith("--");
936
+ if (searchingOptions) {
937
+ word = word.slice(2);
938
+ candidates = candidates.map((candidate) => candidate.slice(2));
939
+ }
940
+ let similar = [];
941
+ let bestDistance = maxDistance;
942
+ const minSimilarity = 0.4;
943
+ candidates.forEach((candidate) => {
944
+ if (candidate.length <= 1) return;
945
+ const distance = editDistance2(word, candidate);
946
+ const length = Math.max(word.length, candidate.length);
947
+ const similarity = (length - distance) / length;
948
+ if (similarity > minSimilarity) {
949
+ if (distance < bestDistance) {
950
+ bestDistance = distance;
951
+ similar = [candidate];
952
+ } else if (distance === bestDistance) {
953
+ similar.push(candidate);
954
+ }
955
+ }
956
+ });
957
+ similar.sort((a, b) => a.localeCompare(b));
958
+ if (searchingOptions) {
959
+ similar = similar.map((candidate) => `--${candidate}`);
960
+ }
961
+ if (similar.length > 1) {
962
+ return `
963
+ (Did you mean one of ${similar.join(", ")}?)`;
964
+ }
965
+ if (similar.length === 1) {
966
+ return `
967
+ (Did you mean ${similar[0]}?)`;
968
+ }
969
+ return "";
970
+ }
971
+ exports.suggestSimilar = suggestSimilar;
972
+ }
973
+ });
974
+
975
+ // node_modules/commander/lib/command.js
976
+ var require_command = __commonJS({
977
+ "node_modules/commander/lib/command.js"(exports) {
978
+ "use strict";
979
+ var EventEmitter = __require("events").EventEmitter;
980
+ var childProcess = __require("child_process");
981
+ var path9 = __require("path");
982
+ var fs = __require("fs");
983
+ var process2 = __require("process");
984
+ var { Argument: Argument2, humanReadableArgName } = require_argument();
985
+ var { CommanderError: CommanderError2 } = require_error();
986
+ var { Help: Help2 } = require_help();
987
+ var { Option: Option2, DualOptions } = require_option();
988
+ var { suggestSimilar } = require_suggestSimilar();
989
+ var Command2 = class _Command extends EventEmitter {
990
+ /**
991
+ * Initialize a new `Command`.
992
+ *
993
+ * @param {string} [name]
994
+ */
995
+ constructor(name) {
996
+ super();
997
+ this.commands = [];
998
+ this.options = [];
999
+ this.parent = null;
1000
+ this._allowUnknownOption = false;
1001
+ this._allowExcessArguments = true;
1002
+ this.registeredArguments = [];
1003
+ this._args = this.registeredArguments;
1004
+ this.args = [];
1005
+ this.rawArgs = [];
1006
+ this.processedArgs = [];
1007
+ this._scriptPath = null;
1008
+ this._name = name || "";
1009
+ this._optionValues = {};
1010
+ this._optionValueSources = {};
1011
+ this._storeOptionsAsProperties = false;
1012
+ this._actionHandler = null;
1013
+ this._executableHandler = false;
1014
+ this._executableFile = null;
1015
+ this._executableDir = null;
1016
+ this._defaultCommandName = null;
1017
+ this._exitCallback = null;
1018
+ this._aliases = [];
1019
+ this._combineFlagAndOptionalValue = true;
1020
+ this._description = "";
1021
+ this._summary = "";
1022
+ this._argsDescription = void 0;
1023
+ this._enablePositionalOptions = false;
1024
+ this._passThroughOptions = false;
1025
+ this._lifeCycleHooks = {};
1026
+ this._showHelpAfterError = false;
1027
+ this._showSuggestionAfterError = true;
1028
+ this._outputConfiguration = {
1029
+ writeOut: (str2) => process2.stdout.write(str2),
1030
+ writeErr: (str2) => process2.stderr.write(str2),
1031
+ getOutHelpWidth: () => process2.stdout.isTTY ? process2.stdout.columns : void 0,
1032
+ getErrHelpWidth: () => process2.stderr.isTTY ? process2.stderr.columns : void 0,
1033
+ outputError: (str2, write) => write(str2)
1034
+ };
1035
+ this._hidden = false;
1036
+ this._helpOption = void 0;
1037
+ this._addImplicitHelpCommand = void 0;
1038
+ this._helpCommand = void 0;
1039
+ this._helpConfiguration = {};
1040
+ }
1041
+ /**
1042
+ * Copy settings that are useful to have in common across root command and subcommands.
1043
+ *
1044
+ * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
1045
+ *
1046
+ * @param {Command} sourceCommand
1047
+ * @return {Command} `this` command for chaining
1048
+ */
1049
+ copyInheritedSettings(sourceCommand) {
1050
+ this._outputConfiguration = sourceCommand._outputConfiguration;
1051
+ this._helpOption = sourceCommand._helpOption;
1052
+ this._helpCommand = sourceCommand._helpCommand;
1053
+ this._helpConfiguration = sourceCommand._helpConfiguration;
1054
+ this._exitCallback = sourceCommand._exitCallback;
1055
+ this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
1056
+ this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
1057
+ this._allowExcessArguments = sourceCommand._allowExcessArguments;
1058
+ this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
1059
+ this._showHelpAfterError = sourceCommand._showHelpAfterError;
1060
+ this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
1061
+ return this;
1062
+ }
1063
+ /**
1064
+ * @returns {Command[]}
1065
+ * @private
1066
+ */
1067
+ _getCommandAndAncestors() {
1068
+ const result = [];
1069
+ for (let command = this; command; command = command.parent) {
1070
+ result.push(command);
1071
+ }
1072
+ return result;
1073
+ }
1074
+ /**
1075
+ * Define a command.
1076
+ *
1077
+ * There are two styles of command: pay attention to where to put the description.
1078
+ *
1079
+ * @example
1080
+ * // Command implemented using action handler (description is supplied separately to `.command`)
1081
+ * program
1082
+ * .command('clone <source> [destination]')
1083
+ * .description('clone a repository into a newly created directory')
1084
+ * .action((source, destination) => {
1085
+ * console.log('clone command called');
1086
+ * });
1087
+ *
1088
+ * // Command implemented using separate executable file (description is second parameter to `.command`)
1089
+ * program
1090
+ * .command('start <service>', 'start named service')
1091
+ * .command('stop [service]', 'stop named service, or all if no name supplied');
1092
+ *
1093
+ * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
1094
+ * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
1095
+ * @param {object} [execOpts] - configuration options (for executable)
1096
+ * @return {Command} returns new command for action handler, or `this` for executable command
1097
+ */
1098
+ command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
1099
+ let desc = actionOptsOrExecDesc;
1100
+ let opts = execOpts;
1101
+ if (typeof desc === "object" && desc !== null) {
1102
+ opts = desc;
1103
+ desc = null;
1104
+ }
1105
+ opts = opts || {};
1106
+ const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
1107
+ const cmd = this.createCommand(name);
1108
+ if (desc) {
1109
+ cmd.description(desc);
1110
+ cmd._executableHandler = true;
1111
+ }
1112
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
1113
+ cmd._hidden = !!(opts.noHelp || opts.hidden);
1114
+ cmd._executableFile = opts.executableFile || null;
1115
+ if (args) cmd.arguments(args);
1116
+ this._registerCommand(cmd);
1117
+ cmd.parent = this;
1118
+ cmd.copyInheritedSettings(this);
1119
+ if (desc) return this;
1120
+ return cmd;
1121
+ }
1122
+ /**
1123
+ * Factory routine to create a new unattached command.
1124
+ *
1125
+ * See .command() for creating an attached subcommand, which uses this routine to
1126
+ * create the command. You can override createCommand to customise subcommands.
1127
+ *
1128
+ * @param {string} [name]
1129
+ * @return {Command} new command
1130
+ */
1131
+ createCommand(name) {
1132
+ return new _Command(name);
1133
+ }
1134
+ /**
1135
+ * You can customise the help with a subclass of Help by overriding createHelp,
1136
+ * or by overriding Help properties using configureHelp().
1137
+ *
1138
+ * @return {Help}
1139
+ */
1140
+ createHelp() {
1141
+ return Object.assign(new Help2(), this.configureHelp());
1142
+ }
1143
+ /**
1144
+ * You can customise the help by overriding Help properties using configureHelp(),
1145
+ * or with a subclass of Help by overriding createHelp().
1146
+ *
1147
+ * @param {object} [configuration] - configuration options
1148
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
1149
+ */
1150
+ configureHelp(configuration) {
1151
+ if (configuration === void 0) return this._helpConfiguration;
1152
+ this._helpConfiguration = configuration;
1153
+ return this;
1154
+ }
1155
+ /**
1156
+ * The default output goes to stdout and stderr. You can customise this for special
1157
+ * applications. You can also customise the display of errors by overriding outputError.
1158
+ *
1159
+ * The configuration properties are all functions:
1160
+ *
1161
+ * // functions to change where being written, stdout and stderr
1162
+ * writeOut(str)
1163
+ * writeErr(str)
1164
+ * // matching functions to specify width for wrapping help
1165
+ * getOutHelpWidth()
1166
+ * getErrHelpWidth()
1167
+ * // functions based on what is being written out
1168
+ * outputError(str, write) // used for displaying errors, and not used for displaying help
1169
+ *
1170
+ * @param {object} [configuration] - configuration options
1171
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
1172
+ */
1173
+ configureOutput(configuration) {
1174
+ if (configuration === void 0) return this._outputConfiguration;
1175
+ Object.assign(this._outputConfiguration, configuration);
1176
+ return this;
1177
+ }
1178
+ /**
1179
+ * Display the help or a custom message after an error occurs.
1180
+ *
1181
+ * @param {(boolean|string)} [displayHelp]
1182
+ * @return {Command} `this` command for chaining
1183
+ */
1184
+ showHelpAfterError(displayHelp = true) {
1185
+ if (typeof displayHelp !== "string") displayHelp = !!displayHelp;
1186
+ this._showHelpAfterError = displayHelp;
1187
+ return this;
1188
+ }
1189
+ /**
1190
+ * Display suggestion of similar commands for unknown commands, or options for unknown options.
1191
+ *
1192
+ * @param {boolean} [displaySuggestion]
1193
+ * @return {Command} `this` command for chaining
1194
+ */
1195
+ showSuggestionAfterError(displaySuggestion = true) {
1196
+ this._showSuggestionAfterError = !!displaySuggestion;
1197
+ return this;
1198
+ }
1199
+ /**
1200
+ * Add a prepared subcommand.
1201
+ *
1202
+ * See .command() for creating an attached subcommand which inherits settings from its parent.
1203
+ *
1204
+ * @param {Command} cmd - new subcommand
1205
+ * @param {object} [opts] - configuration options
1206
+ * @return {Command} `this` command for chaining
1207
+ */
1208
+ addCommand(cmd, opts) {
1209
+ if (!cmd._name) {
1210
+ throw new Error(`Command passed to .addCommand() must have a name
1211
+ - specify the name in Command constructor or using .name()`);
1212
+ }
1213
+ opts = opts || {};
1214
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
1215
+ if (opts.noHelp || opts.hidden) cmd._hidden = true;
1216
+ this._registerCommand(cmd);
1217
+ cmd.parent = this;
1218
+ cmd._checkForBrokenPassThrough();
1219
+ return this;
1220
+ }
1221
+ /**
1222
+ * Factory routine to create a new unattached argument.
1223
+ *
1224
+ * See .argument() for creating an attached argument, which uses this routine to
1225
+ * create the argument. You can override createArgument to return a custom argument.
1226
+ *
1227
+ * @param {string} name
1228
+ * @param {string} [description]
1229
+ * @return {Argument} new argument
1230
+ */
1231
+ createArgument(name, description) {
1232
+ return new Argument2(name, description);
1233
+ }
1234
+ /**
1235
+ * Define argument syntax for command.
1236
+ *
1237
+ * The default is that the argument is required, and you can explicitly
1238
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
1239
+ *
1240
+ * @example
1241
+ * program.argument('<input-file>');
1242
+ * program.argument('[output-file]');
1243
+ *
1244
+ * @param {string} name
1245
+ * @param {string} [description]
1246
+ * @param {(Function|*)} [fn] - custom argument processing function
1247
+ * @param {*} [defaultValue]
1248
+ * @return {Command} `this` command for chaining
1249
+ */
1250
+ argument(name, description, fn, defaultValue) {
1251
+ const argument = this.createArgument(name, description);
1252
+ if (typeof fn === "function") {
1253
+ argument.default(defaultValue).argParser(fn);
1254
+ } else {
1255
+ argument.default(fn);
1256
+ }
1257
+ this.addArgument(argument);
1258
+ return this;
1259
+ }
1260
+ /**
1261
+ * Define argument syntax for command, adding multiple at once (without descriptions).
1262
+ *
1263
+ * See also .argument().
1264
+ *
1265
+ * @example
1266
+ * program.arguments('<cmd> [env]');
1267
+ *
1268
+ * @param {string} names
1269
+ * @return {Command} `this` command for chaining
1270
+ */
1271
+ arguments(names) {
1272
+ names.trim().split(/ +/).forEach((detail) => {
1273
+ this.argument(detail);
1274
+ });
1275
+ return this;
1276
+ }
1277
+ /**
1278
+ * Define argument syntax for command, adding a prepared argument.
1279
+ *
1280
+ * @param {Argument} argument
1281
+ * @return {Command} `this` command for chaining
1282
+ */
1283
+ addArgument(argument) {
1284
+ const previousArgument = this.registeredArguments.slice(-1)[0];
1285
+ if (previousArgument && previousArgument.variadic) {
1286
+ throw new Error(
1287
+ `only the last argument can be variadic '${previousArgument.name()}'`
1288
+ );
1289
+ }
1290
+ if (argument.required && argument.defaultValue !== void 0 && argument.parseArg === void 0) {
1291
+ throw new Error(
1292
+ `a default value for a required argument is never used: '${argument.name()}'`
1293
+ );
1294
+ }
1295
+ this.registeredArguments.push(argument);
1296
+ return this;
1297
+ }
1298
+ /**
1299
+ * Customise or override default help command. By default a help command is automatically added if your command has subcommands.
1300
+ *
1301
+ * @example
1302
+ * program.helpCommand('help [cmd]');
1303
+ * program.helpCommand('help [cmd]', 'show help');
1304
+ * program.helpCommand(false); // suppress default help command
1305
+ * program.helpCommand(true); // add help command even if no subcommands
1306
+ *
1307
+ * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added
1308
+ * @param {string} [description] - custom description
1309
+ * @return {Command} `this` command for chaining
1310
+ */
1311
+ helpCommand(enableOrNameAndArgs, description) {
1312
+ if (typeof enableOrNameAndArgs === "boolean") {
1313
+ this._addImplicitHelpCommand = enableOrNameAndArgs;
1314
+ return this;
1315
+ }
1316
+ enableOrNameAndArgs = enableOrNameAndArgs ?? "help [command]";
1317
+ const [, helpName, helpArgs] = enableOrNameAndArgs.match(/([^ ]+) *(.*)/);
1318
+ const helpDescription = description ?? "display help for command";
1319
+ const helpCommand = this.createCommand(helpName);
1320
+ helpCommand.helpOption(false);
1321
+ if (helpArgs) helpCommand.arguments(helpArgs);
1322
+ if (helpDescription) helpCommand.description(helpDescription);
1323
+ this._addImplicitHelpCommand = true;
1324
+ this._helpCommand = helpCommand;
1325
+ return this;
1326
+ }
1327
+ /**
1328
+ * Add prepared custom help command.
1329
+ *
1330
+ * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`
1331
+ * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only
1332
+ * @return {Command} `this` command for chaining
1333
+ */
1334
+ addHelpCommand(helpCommand, deprecatedDescription) {
1335
+ if (typeof helpCommand !== "object") {
1336
+ this.helpCommand(helpCommand, deprecatedDescription);
1337
+ return this;
1338
+ }
1339
+ this._addImplicitHelpCommand = true;
1340
+ this._helpCommand = helpCommand;
1341
+ return this;
1342
+ }
1343
+ /**
1344
+ * Lazy create help command.
1345
+ *
1346
+ * @return {(Command|null)}
1347
+ * @package
1348
+ */
1349
+ _getHelpCommand() {
1350
+ const hasImplicitHelpCommand = this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"));
1351
+ if (hasImplicitHelpCommand) {
1352
+ if (this._helpCommand === void 0) {
1353
+ this.helpCommand(void 0, void 0);
1354
+ }
1355
+ return this._helpCommand;
1356
+ }
1357
+ return null;
1358
+ }
1359
+ /**
1360
+ * Add hook for life cycle event.
1361
+ *
1362
+ * @param {string} event
1363
+ * @param {Function} listener
1364
+ * @return {Command} `this` command for chaining
1365
+ */
1366
+ hook(event, listener) {
1367
+ const allowedValues = ["preSubcommand", "preAction", "postAction"];
1368
+ if (!allowedValues.includes(event)) {
1369
+ throw new Error(`Unexpected value for event passed to hook : '${event}'.
1370
+ Expecting one of '${allowedValues.join("', '")}'`);
1371
+ }
1372
+ if (this._lifeCycleHooks[event]) {
1373
+ this._lifeCycleHooks[event].push(listener);
1374
+ } else {
1375
+ this._lifeCycleHooks[event] = [listener];
1376
+ }
1377
+ return this;
1378
+ }
1379
+ /**
1380
+ * Register callback to use as replacement for calling process.exit.
1381
+ *
1382
+ * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
1383
+ * @return {Command} `this` command for chaining
1384
+ */
1385
+ exitOverride(fn) {
1386
+ if (fn) {
1387
+ this._exitCallback = fn;
1388
+ } else {
1389
+ this._exitCallback = (err) => {
1390
+ if (err.code !== "commander.executeSubCommandAsync") {
1391
+ throw err;
1392
+ } else {
1393
+ }
1394
+ };
1395
+ }
1396
+ return this;
1397
+ }
1398
+ /**
1399
+ * Call process.exit, and _exitCallback if defined.
1400
+ *
1401
+ * @param {number} exitCode exit code for using with process.exit
1402
+ * @param {string} code an id string representing the error
1403
+ * @param {string} message human-readable description of the error
1404
+ * @return never
1405
+ * @private
1406
+ */
1407
+ _exit(exitCode, code, message) {
1408
+ if (this._exitCallback) {
1409
+ this._exitCallback(new CommanderError2(exitCode, code, message));
1410
+ }
1411
+ process2.exit(exitCode);
1412
+ }
1413
+ /**
1414
+ * Register callback `fn` for the command.
1415
+ *
1416
+ * @example
1417
+ * program
1418
+ * .command('serve')
1419
+ * .description('start service')
1420
+ * .action(function() {
1421
+ * // do work here
1422
+ * });
1423
+ *
1424
+ * @param {Function} fn
1425
+ * @return {Command} `this` command for chaining
1426
+ */
1427
+ action(fn) {
1428
+ const listener = (args) => {
1429
+ const expectedArgsCount = this.registeredArguments.length;
1430
+ const actionArgs = args.slice(0, expectedArgsCount);
1431
+ if (this._storeOptionsAsProperties) {
1432
+ actionArgs[expectedArgsCount] = this;
1433
+ } else {
1434
+ actionArgs[expectedArgsCount] = this.opts();
1435
+ }
1436
+ actionArgs.push(this);
1437
+ return fn.apply(this, actionArgs);
1438
+ };
1439
+ this._actionHandler = listener;
1440
+ return this;
1441
+ }
1442
+ /**
1443
+ * Factory routine to create a new unattached option.
1444
+ *
1445
+ * See .option() for creating an attached option, which uses this routine to
1446
+ * create the option. You can override createOption to return a custom option.
1447
+ *
1448
+ * @param {string} flags
1449
+ * @param {string} [description]
1450
+ * @return {Option} new option
1451
+ */
1452
+ createOption(flags, description) {
1453
+ return new Option2(flags, description);
1454
+ }
1455
+ /**
1456
+ * Wrap parseArgs to catch 'commander.invalidArgument'.
1457
+ *
1458
+ * @param {(Option | Argument)} target
1459
+ * @param {string} value
1460
+ * @param {*} previous
1461
+ * @param {string} invalidArgumentMessage
1462
+ * @private
1463
+ */
1464
+ _callParseArg(target, value, previous, invalidArgumentMessage) {
1465
+ try {
1466
+ return target.parseArg(value, previous);
1467
+ } catch (err) {
1468
+ if (err.code === "commander.invalidArgument") {
1469
+ const message = `${invalidArgumentMessage} ${err.message}`;
1470
+ this.error(message, { exitCode: err.exitCode, code: err.code });
1471
+ }
1472
+ throw err;
1473
+ }
1474
+ }
1475
+ /**
1476
+ * Check for option flag conflicts.
1477
+ * Register option if no conflicts found, or throw on conflict.
1478
+ *
1479
+ * @param {Option} option
1480
+ * @private
1481
+ */
1482
+ _registerOption(option) {
1483
+ const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
1484
+ if (matchingOption) {
1485
+ const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
1486
+ throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
1487
+ - already used by option '${matchingOption.flags}'`);
1488
+ }
1489
+ this.options.push(option);
1490
+ }
1491
+ /**
1492
+ * Check for command name and alias conflicts with existing commands.
1493
+ * Register command if no conflicts found, or throw on conflict.
1494
+ *
1495
+ * @param {Command} command
1496
+ * @private
1497
+ */
1498
+ _registerCommand(command) {
1499
+ const knownBy = (cmd) => {
1500
+ return [cmd.name()].concat(cmd.aliases());
1501
+ };
1502
+ const alreadyUsed = knownBy(command).find(
1503
+ (name) => this._findCommand(name)
1504
+ );
1505
+ if (alreadyUsed) {
1506
+ const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
1507
+ const newCmd = knownBy(command).join("|");
1508
+ throw new Error(
1509
+ `cannot add command '${newCmd}' as already have command '${existingCmd}'`
1510
+ );
1511
+ }
1512
+ this.commands.push(command);
1513
+ }
1514
+ /**
1515
+ * Add an option.
1516
+ *
1517
+ * @param {Option} option
1518
+ * @return {Command} `this` command for chaining
1519
+ */
1520
+ addOption(option) {
1521
+ this._registerOption(option);
1522
+ const oname = option.name();
1523
+ const name = option.attributeName();
1524
+ if (option.negate) {
1525
+ const positiveLongFlag = option.long.replace(/^--no-/, "--");
1526
+ if (!this._findOption(positiveLongFlag)) {
1527
+ this.setOptionValueWithSource(
1528
+ name,
1529
+ option.defaultValue === void 0 ? true : option.defaultValue,
1530
+ "default"
1531
+ );
1532
+ }
1533
+ } else if (option.defaultValue !== void 0) {
1534
+ this.setOptionValueWithSource(name, option.defaultValue, "default");
1535
+ }
1536
+ const handleOptionValue = (val, invalidValueMessage, valueSource) => {
1537
+ if (val == null && option.presetArg !== void 0) {
1538
+ val = option.presetArg;
1539
+ }
1540
+ const oldValue = this.getOptionValue(name);
1541
+ if (val !== null && option.parseArg) {
1542
+ val = this._callParseArg(option, val, oldValue, invalidValueMessage);
1543
+ } else if (val !== null && option.variadic) {
1544
+ val = option._concatValue(val, oldValue);
1545
+ }
1546
+ if (val == null) {
1547
+ if (option.negate) {
1548
+ val = false;
1549
+ } else if (option.isBoolean() || option.optional) {
1550
+ val = true;
1551
+ } else {
1552
+ val = "";
1553
+ }
1554
+ }
1555
+ this.setOptionValueWithSource(name, val, valueSource);
1556
+ };
1557
+ this.on("option:" + oname, (val) => {
1558
+ const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
1559
+ handleOptionValue(val, invalidValueMessage, "cli");
1560
+ });
1561
+ if (option.envVar) {
1562
+ this.on("optionEnv:" + oname, (val) => {
1563
+ const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
1564
+ handleOptionValue(val, invalidValueMessage, "env");
1565
+ });
1566
+ }
1567
+ return this;
1568
+ }
1569
+ /**
1570
+ * Internal implementation shared by .option() and .requiredOption()
1571
+ *
1572
+ * @return {Command} `this` command for chaining
1573
+ * @private
1574
+ */
1575
+ _optionEx(config, flags, description, fn, defaultValue) {
1576
+ if (typeof flags === "object" && flags instanceof Option2) {
1577
+ throw new Error(
1578
+ "To add an Option object use addOption() instead of option() or requiredOption()"
1579
+ );
1580
+ }
1581
+ const option = this.createOption(flags, description);
1582
+ option.makeOptionMandatory(!!config.mandatory);
1583
+ if (typeof fn === "function") {
1584
+ option.default(defaultValue).argParser(fn);
1585
+ } else if (fn instanceof RegExp) {
1586
+ const regex = fn;
1587
+ fn = (val, def) => {
1588
+ const m = regex.exec(val);
1589
+ return m ? m[0] : def;
1590
+ };
1591
+ option.default(defaultValue).argParser(fn);
1592
+ } else {
1593
+ option.default(fn);
1594
+ }
1595
+ return this.addOption(option);
1596
+ }
1597
+ /**
1598
+ * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
1599
+ *
1600
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
1601
+ * option-argument is indicated by `<>` and an optional option-argument by `[]`.
1602
+ *
1603
+ * See the README for more details, and see also addOption() and requiredOption().
1604
+ *
1605
+ * @example
1606
+ * program
1607
+ * .option('-p, --pepper', 'add pepper')
1608
+ * .option('-p, --pizza-type <TYPE>', 'type of pizza') // required option-argument
1609
+ * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
1610
+ * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
1611
+ *
1612
+ * @param {string} flags
1613
+ * @param {string} [description]
1614
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
1615
+ * @param {*} [defaultValue]
1616
+ * @return {Command} `this` command for chaining
1617
+ */
1618
+ option(flags, description, parseArg, defaultValue) {
1619
+ return this._optionEx({}, flags, description, parseArg, defaultValue);
1620
+ }
1621
+ /**
1622
+ * Add a required option which must have a value after parsing. This usually means
1623
+ * the option must be specified on the command line. (Otherwise the same as .option().)
1624
+ *
1625
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
1626
+ *
1627
+ * @param {string} flags
1628
+ * @param {string} [description]
1629
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
1630
+ * @param {*} [defaultValue]
1631
+ * @return {Command} `this` command for chaining
1632
+ */
1633
+ requiredOption(flags, description, parseArg, defaultValue) {
1634
+ return this._optionEx(
1635
+ { mandatory: true },
1636
+ flags,
1637
+ description,
1638
+ parseArg,
1639
+ defaultValue
1640
+ );
1641
+ }
1642
+ /**
1643
+ * Alter parsing of short flags with optional values.
1644
+ *
1645
+ * @example
1646
+ * // for `.option('-f,--flag [value]'):
1647
+ * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
1648
+ * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
1649
+ *
1650
+ * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.
1651
+ * @return {Command} `this` command for chaining
1652
+ */
1653
+ combineFlagAndOptionalValue(combine = true) {
1654
+ this._combineFlagAndOptionalValue = !!combine;
1655
+ return this;
1656
+ }
1657
+ /**
1658
+ * Allow unknown options on the command line.
1659
+ *
1660
+ * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.
1661
+ * @return {Command} `this` command for chaining
1662
+ */
1663
+ allowUnknownOption(allowUnknown = true) {
1664
+ this._allowUnknownOption = !!allowUnknown;
1665
+ return this;
1666
+ }
1667
+ /**
1668
+ * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
1669
+ *
1670
+ * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.
1671
+ * @return {Command} `this` command for chaining
1672
+ */
1673
+ allowExcessArguments(allowExcess = true) {
1674
+ this._allowExcessArguments = !!allowExcess;
1675
+ return this;
1676
+ }
1677
+ /**
1678
+ * Enable positional options. Positional means global options are specified before subcommands which lets
1679
+ * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
1680
+ * The default behaviour is non-positional and global options may appear anywhere on the command line.
1681
+ *
1682
+ * @param {boolean} [positional]
1683
+ * @return {Command} `this` command for chaining
1684
+ */
1685
+ enablePositionalOptions(positional = true) {
1686
+ this._enablePositionalOptions = !!positional;
1687
+ return this;
1688
+ }
1689
+ /**
1690
+ * Pass through options that come after command-arguments rather than treat them as command-options,
1691
+ * so actual command-options come before command-arguments. Turning this on for a subcommand requires
1692
+ * positional options to have been enabled on the program (parent commands).
1693
+ * The default behaviour is non-positional and options may appear before or after command-arguments.
1694
+ *
1695
+ * @param {boolean} [passThrough] for unknown options.
1696
+ * @return {Command} `this` command for chaining
1697
+ */
1698
+ passThroughOptions(passThrough3 = true) {
1699
+ this._passThroughOptions = !!passThrough3;
1700
+ this._checkForBrokenPassThrough();
1701
+ return this;
1702
+ }
1703
+ /**
1704
+ * @private
1705
+ */
1706
+ _checkForBrokenPassThrough() {
1707
+ if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {
1708
+ throw new Error(
1709
+ `passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`
1710
+ );
1711
+ }
1712
+ }
1713
+ /**
1714
+ * Whether to store option values as properties on command object,
1715
+ * or store separately (specify false). In both cases the option values can be accessed using .opts().
1716
+ *
1717
+ * @param {boolean} [storeAsProperties=true]
1718
+ * @return {Command} `this` command for chaining
1719
+ */
1720
+ storeOptionsAsProperties(storeAsProperties = true) {
1721
+ if (this.options.length) {
1722
+ throw new Error("call .storeOptionsAsProperties() before adding options");
1723
+ }
1724
+ if (Object.keys(this._optionValues).length) {
1725
+ throw new Error(
1726
+ "call .storeOptionsAsProperties() before setting option values"
1727
+ );
1728
+ }
1729
+ this._storeOptionsAsProperties = !!storeAsProperties;
1730
+ return this;
1731
+ }
1732
+ /**
1733
+ * Retrieve option value.
1734
+ *
1735
+ * @param {string} key
1736
+ * @return {object} value
1737
+ */
1738
+ getOptionValue(key) {
1739
+ if (this._storeOptionsAsProperties) {
1740
+ return this[key];
1741
+ }
1742
+ return this._optionValues[key];
1743
+ }
1744
+ /**
1745
+ * Store option value.
1746
+ *
1747
+ * @param {string} key
1748
+ * @param {object} value
1749
+ * @return {Command} `this` command for chaining
1750
+ */
1751
+ setOptionValue(key, value) {
1752
+ return this.setOptionValueWithSource(key, value, void 0);
1753
+ }
1754
+ /**
1755
+ * Store option value and where the value came from.
1756
+ *
1757
+ * @param {string} key
1758
+ * @param {object} value
1759
+ * @param {string} source - expected values are default/config/env/cli/implied
1760
+ * @return {Command} `this` command for chaining
1761
+ */
1762
+ setOptionValueWithSource(key, value, source) {
1763
+ if (this._storeOptionsAsProperties) {
1764
+ this[key] = value;
1765
+ } else {
1766
+ this._optionValues[key] = value;
1767
+ }
1768
+ this._optionValueSources[key] = source;
1769
+ return this;
1770
+ }
1771
+ /**
1772
+ * Get source of option value.
1773
+ * Expected values are default | config | env | cli | implied
1774
+ *
1775
+ * @param {string} key
1776
+ * @return {string}
1777
+ */
1778
+ getOptionValueSource(key) {
1779
+ return this._optionValueSources[key];
1780
+ }
1781
+ /**
1782
+ * Get source of option value. See also .optsWithGlobals().
1783
+ * Expected values are default | config | env | cli | implied
1784
+ *
1785
+ * @param {string} key
1786
+ * @return {string}
1787
+ */
1788
+ getOptionValueSourceWithGlobals(key) {
1789
+ let source;
1790
+ this._getCommandAndAncestors().forEach((cmd) => {
1791
+ if (cmd.getOptionValueSource(key) !== void 0) {
1792
+ source = cmd.getOptionValueSource(key);
1793
+ }
1794
+ });
1795
+ return source;
1796
+ }
1797
+ /**
1798
+ * Get user arguments from implied or explicit arguments.
1799
+ * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
1800
+ *
1801
+ * @private
1802
+ */
1803
+ _prepareUserArgs(argv, parseOptions) {
1804
+ if (argv !== void 0 && !Array.isArray(argv)) {
1805
+ throw new Error("first parameter to parse must be array or undefined");
1806
+ }
1807
+ parseOptions = parseOptions || {};
1808
+ if (argv === void 0 && parseOptions.from === void 0) {
1809
+ if (process2.versions?.electron) {
1810
+ parseOptions.from = "electron";
1811
+ }
1812
+ const execArgv = process2.execArgv ?? [];
1813
+ if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) {
1814
+ parseOptions.from = "eval";
1815
+ }
1816
+ }
1817
+ if (argv === void 0) {
1818
+ argv = process2.argv;
1819
+ }
1820
+ this.rawArgs = argv.slice();
1821
+ let userArgs;
1822
+ switch (parseOptions.from) {
1823
+ case void 0:
1824
+ case "node":
1825
+ this._scriptPath = argv[1];
1826
+ userArgs = argv.slice(2);
1827
+ break;
1828
+ case "electron":
1829
+ if (process2.defaultApp) {
1830
+ this._scriptPath = argv[1];
1831
+ userArgs = argv.slice(2);
1832
+ } else {
1833
+ userArgs = argv.slice(1);
1834
+ }
1835
+ break;
1836
+ case "user":
1837
+ userArgs = argv.slice(0);
1838
+ break;
1839
+ case "eval":
1840
+ userArgs = argv.slice(1);
1841
+ break;
1842
+ default:
1843
+ throw new Error(
1844
+ `unexpected parse option { from: '${parseOptions.from}' }`
1845
+ );
1846
+ }
1847
+ if (!this._name && this._scriptPath)
1848
+ this.nameFromFilename(this._scriptPath);
1849
+ this._name = this._name || "program";
1850
+ return userArgs;
1851
+ }
1852
+ /**
1853
+ * Parse `argv`, setting options and invoking commands when defined.
1854
+ *
1855
+ * Use parseAsync instead of parse if any of your action handlers are async.
1856
+ *
1857
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
1858
+ *
1859
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
1860
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
1861
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
1862
+ * - `'user'`: just user arguments
1863
+ *
1864
+ * @example
1865
+ * program.parse(); // parse process.argv and auto-detect electron and special node flags
1866
+ * program.parse(process.argv); // assume argv[0] is app and argv[1] is script
1867
+ * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
1868
+ *
1869
+ * @param {string[]} [argv] - optional, defaults to process.argv
1870
+ * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron
1871
+ * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
1872
+ * @return {Command} `this` command for chaining
1873
+ */
1874
+ parse(argv, parseOptions) {
1875
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1876
+ this._parseCommand([], userArgs);
1877
+ return this;
1878
+ }
1879
+ /**
1880
+ * Parse `argv`, setting options and invoking commands when defined.
1881
+ *
1882
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
1883
+ *
1884
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
1885
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
1886
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
1887
+ * - `'user'`: just user arguments
1888
+ *
1889
+ * @example
1890
+ * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags
1891
+ * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script
1892
+ * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
1893
+ *
1894
+ * @param {string[]} [argv]
1895
+ * @param {object} [parseOptions]
1896
+ * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
1897
+ * @return {Promise}
1898
+ */
1899
+ async parseAsync(argv, parseOptions) {
1900
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1901
+ await this._parseCommand([], userArgs);
1902
+ return this;
1903
+ }
1904
+ /**
1905
+ * Execute a sub-command executable.
1906
+ *
1907
+ * @private
1908
+ */
1909
+ _executeSubCommand(subcommand, args) {
1910
+ args = args.slice();
1911
+ let launchWithNode = false;
1912
+ const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
1913
+ function findFile(baseDir, baseName) {
1914
+ const localBin = path9.resolve(baseDir, baseName);
1915
+ if (fs.existsSync(localBin)) return localBin;
1916
+ if (sourceExt.includes(path9.extname(baseName))) return void 0;
1917
+ const foundExt = sourceExt.find(
1918
+ (ext) => fs.existsSync(`${localBin}${ext}`)
1919
+ );
1920
+ if (foundExt) return `${localBin}${foundExt}`;
1921
+ return void 0;
1922
+ }
1923
+ this._checkForMissingMandatoryOptions();
1924
+ this._checkForConflictingOptions();
1925
+ let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
1926
+ let executableDir = this._executableDir || "";
1927
+ if (this._scriptPath) {
1928
+ let resolvedScriptPath;
1929
+ try {
1930
+ resolvedScriptPath = fs.realpathSync(this._scriptPath);
1931
+ } catch (err) {
1932
+ resolvedScriptPath = this._scriptPath;
1933
+ }
1934
+ executableDir = path9.resolve(
1935
+ path9.dirname(resolvedScriptPath),
1936
+ executableDir
1937
+ );
1938
+ }
1939
+ if (executableDir) {
1940
+ let localFile = findFile(executableDir, executableFile);
1941
+ if (!localFile && !subcommand._executableFile && this._scriptPath) {
1942
+ const legacyName = path9.basename(
1943
+ this._scriptPath,
1944
+ path9.extname(this._scriptPath)
1945
+ );
1946
+ if (legacyName !== this._name) {
1947
+ localFile = findFile(
1948
+ executableDir,
1949
+ `${legacyName}-${subcommand._name}`
1950
+ );
1951
+ }
1952
+ }
1953
+ executableFile = localFile || executableFile;
1954
+ }
1955
+ launchWithNode = sourceExt.includes(path9.extname(executableFile));
1956
+ let proc;
1957
+ if (process2.platform !== "win32") {
1958
+ if (launchWithNode) {
1959
+ args.unshift(executableFile);
1960
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
1961
+ proc = childProcess.spawn(process2.argv[0], args, { stdio: "inherit" });
1962
+ } else {
1963
+ proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
1964
+ }
1965
+ } else {
1966
+ args.unshift(executableFile);
1967
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
1968
+ proc = childProcess.spawn(process2.execPath, args, { stdio: "inherit" });
1969
+ }
1970
+ if (!proc.killed) {
1971
+ const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
1972
+ signals.forEach((signal) => {
1973
+ process2.on(signal, () => {
1974
+ if (proc.killed === false && proc.exitCode === null) {
1975
+ proc.kill(signal);
1976
+ }
1977
+ });
1978
+ });
1979
+ }
1980
+ const exitCallback = this._exitCallback;
1981
+ proc.on("close", (code) => {
1982
+ code = code ?? 1;
1983
+ if (!exitCallback) {
1984
+ process2.exit(code);
1985
+ } else {
1986
+ exitCallback(
1987
+ new CommanderError2(
1988
+ code,
1989
+ "commander.executeSubCommandAsync",
1990
+ "(close)"
1991
+ )
1992
+ );
1993
+ }
1994
+ });
1995
+ proc.on("error", (err) => {
1996
+ if (err.code === "ENOENT") {
1997
+ 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";
1998
+ const executableMissing = `'${executableFile}' does not exist
1999
+ - if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
2000
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
2001
+ - ${executableDirMessage}`;
2002
+ throw new Error(executableMissing);
2003
+ } else if (err.code === "EACCES") {
2004
+ throw new Error(`'${executableFile}' not executable`);
2005
+ }
2006
+ if (!exitCallback) {
2007
+ process2.exit(1);
2008
+ } else {
2009
+ const wrappedError = new CommanderError2(
2010
+ 1,
2011
+ "commander.executeSubCommandAsync",
2012
+ "(error)"
2013
+ );
2014
+ wrappedError.nestedError = err;
2015
+ exitCallback(wrappedError);
2016
+ }
2017
+ });
2018
+ this.runningCommand = proc;
2019
+ }
2020
+ /**
2021
+ * @private
2022
+ */
2023
+ _dispatchSubcommand(commandName, operands, unknown) {
2024
+ const subCommand = this._findCommand(commandName);
2025
+ if (!subCommand) this.help({ error: true });
2026
+ let promiseChain;
2027
+ promiseChain = this._chainOrCallSubCommandHook(
2028
+ promiseChain,
2029
+ subCommand,
2030
+ "preSubcommand"
2031
+ );
2032
+ promiseChain = this._chainOrCall(promiseChain, () => {
2033
+ if (subCommand._executableHandler) {
2034
+ this._executeSubCommand(subCommand, operands.concat(unknown));
2035
+ } else {
2036
+ return subCommand._parseCommand(operands, unknown);
2037
+ }
2038
+ });
2039
+ return promiseChain;
2040
+ }
2041
+ /**
2042
+ * Invoke help directly if possible, or dispatch if necessary.
2043
+ * e.g. help foo
2044
+ *
2045
+ * @private
2046
+ */
2047
+ _dispatchHelpCommand(subcommandName) {
2048
+ if (!subcommandName) {
2049
+ this.help();
2050
+ }
2051
+ const subCommand = this._findCommand(subcommandName);
2052
+ if (subCommand && !subCommand._executableHandler) {
2053
+ subCommand.help();
2054
+ }
2055
+ return this._dispatchSubcommand(
2056
+ subcommandName,
2057
+ [],
2058
+ [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]
2059
+ );
2060
+ }
2061
+ /**
2062
+ * Check this.args against expected this.registeredArguments.
2063
+ *
2064
+ * @private
2065
+ */
2066
+ _checkNumberOfArguments() {
2067
+ this.registeredArguments.forEach((arg, i) => {
2068
+ if (arg.required && this.args[i] == null) {
2069
+ this.missingArgument(arg.name());
2070
+ }
2071
+ });
2072
+ if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
2073
+ return;
2074
+ }
2075
+ if (this.args.length > this.registeredArguments.length) {
2076
+ this._excessArguments(this.args);
2077
+ }
2078
+ }
2079
+ /**
2080
+ * Process this.args using this.registeredArguments and save as this.processedArgs!
2081
+ *
2082
+ * @private
2083
+ */
2084
+ _processArguments() {
2085
+ const myParseArg = (argument, value, previous) => {
2086
+ let parsedValue = value;
2087
+ if (value !== null && argument.parseArg) {
2088
+ const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
2089
+ parsedValue = this._callParseArg(
2090
+ argument,
2091
+ value,
2092
+ previous,
2093
+ invalidValueMessage
2094
+ );
2095
+ }
2096
+ return parsedValue;
2097
+ };
2098
+ this._checkNumberOfArguments();
2099
+ const processedArgs = [];
2100
+ this.registeredArguments.forEach((declaredArg, index) => {
2101
+ let value = declaredArg.defaultValue;
2102
+ if (declaredArg.variadic) {
2103
+ if (index < this.args.length) {
2104
+ value = this.args.slice(index);
2105
+ if (declaredArg.parseArg) {
2106
+ value = value.reduce((processed, v) => {
2107
+ return myParseArg(declaredArg, v, processed);
2108
+ }, declaredArg.defaultValue);
2109
+ }
2110
+ } else if (value === void 0) {
2111
+ value = [];
2112
+ }
2113
+ } else if (index < this.args.length) {
2114
+ value = this.args[index];
2115
+ if (declaredArg.parseArg) {
2116
+ value = myParseArg(declaredArg, value, declaredArg.defaultValue);
2117
+ }
2118
+ }
2119
+ processedArgs[index] = value;
2120
+ });
2121
+ this.processedArgs = processedArgs;
2122
+ }
2123
+ /**
2124
+ * Once we have a promise we chain, but call synchronously until then.
2125
+ *
2126
+ * @param {(Promise|undefined)} promise
2127
+ * @param {Function} fn
2128
+ * @return {(Promise|undefined)}
2129
+ * @private
2130
+ */
2131
+ _chainOrCall(promise, fn) {
2132
+ if (promise && promise.then && typeof promise.then === "function") {
2133
+ return promise.then(() => fn());
2134
+ }
2135
+ return fn();
2136
+ }
2137
+ /**
2138
+ *
2139
+ * @param {(Promise|undefined)} promise
2140
+ * @param {string} event
2141
+ * @return {(Promise|undefined)}
2142
+ * @private
2143
+ */
2144
+ _chainOrCallHooks(promise, event) {
2145
+ let result = promise;
2146
+ const hooks = [];
2147
+ this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== void 0).forEach((hookedCommand) => {
2148
+ hookedCommand._lifeCycleHooks[event].forEach((callback) => {
2149
+ hooks.push({ hookedCommand, callback });
2150
+ });
2151
+ });
2152
+ if (event === "postAction") {
2153
+ hooks.reverse();
2154
+ }
2155
+ hooks.forEach((hookDetail) => {
2156
+ result = this._chainOrCall(result, () => {
2157
+ return hookDetail.callback(hookDetail.hookedCommand, this);
2158
+ });
2159
+ });
2160
+ return result;
2161
+ }
2162
+ /**
2163
+ *
2164
+ * @param {(Promise|undefined)} promise
2165
+ * @param {Command} subCommand
2166
+ * @param {string} event
2167
+ * @return {(Promise|undefined)}
2168
+ * @private
2169
+ */
2170
+ _chainOrCallSubCommandHook(promise, subCommand, event) {
2171
+ let result = promise;
2172
+ if (this._lifeCycleHooks[event] !== void 0) {
2173
+ this._lifeCycleHooks[event].forEach((hook) => {
2174
+ result = this._chainOrCall(result, () => {
2175
+ return hook(this, subCommand);
2176
+ });
2177
+ });
2178
+ }
2179
+ return result;
2180
+ }
2181
+ /**
2182
+ * Process arguments in context of this command.
2183
+ * Returns action result, in case it is a promise.
2184
+ *
2185
+ * @private
2186
+ */
2187
+ _parseCommand(operands, unknown) {
2188
+ const parsed = this.parseOptions(unknown);
2189
+ this._parseOptionsEnv();
2190
+ this._parseOptionsImplied();
2191
+ operands = operands.concat(parsed.operands);
2192
+ unknown = parsed.unknown;
2193
+ this.args = operands.concat(unknown);
2194
+ if (operands && this._findCommand(operands[0])) {
2195
+ return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
2196
+ }
2197
+ if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) {
2198
+ return this._dispatchHelpCommand(operands[1]);
2199
+ }
2200
+ if (this._defaultCommandName) {
2201
+ this._outputHelpIfRequested(unknown);
2202
+ return this._dispatchSubcommand(
2203
+ this._defaultCommandName,
2204
+ operands,
2205
+ unknown
2206
+ );
2207
+ }
2208
+ if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
2209
+ this.help({ error: true });
2210
+ }
2211
+ this._outputHelpIfRequested(parsed.unknown);
2212
+ this._checkForMissingMandatoryOptions();
2213
+ this._checkForConflictingOptions();
2214
+ const checkForUnknownOptions = () => {
2215
+ if (parsed.unknown.length > 0) {
2216
+ this.unknownOption(parsed.unknown[0]);
2217
+ }
2218
+ };
2219
+ const commandEvent = `command:${this.name()}`;
2220
+ if (this._actionHandler) {
2221
+ checkForUnknownOptions();
2222
+ this._processArguments();
2223
+ let promiseChain;
2224
+ promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
2225
+ promiseChain = this._chainOrCall(
2226
+ promiseChain,
2227
+ () => this._actionHandler(this.processedArgs)
2228
+ );
2229
+ if (this.parent) {
2230
+ promiseChain = this._chainOrCall(promiseChain, () => {
2231
+ this.parent.emit(commandEvent, operands, unknown);
2232
+ });
2233
+ }
2234
+ promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
2235
+ return promiseChain;
2236
+ }
2237
+ if (this.parent && this.parent.listenerCount(commandEvent)) {
2238
+ checkForUnknownOptions();
2239
+ this._processArguments();
2240
+ this.parent.emit(commandEvent, operands, unknown);
2241
+ } else if (operands.length) {
2242
+ if (this._findCommand("*")) {
2243
+ return this._dispatchSubcommand("*", operands, unknown);
2244
+ }
2245
+ if (this.listenerCount("command:*")) {
2246
+ this.emit("command:*", operands, unknown);
2247
+ } else if (this.commands.length) {
2248
+ this.unknownCommand();
2249
+ } else {
2250
+ checkForUnknownOptions();
2251
+ this._processArguments();
2252
+ }
2253
+ } else if (this.commands.length) {
2254
+ checkForUnknownOptions();
2255
+ this.help({ error: true });
2256
+ } else {
2257
+ checkForUnknownOptions();
2258
+ this._processArguments();
2259
+ }
2260
+ }
2261
+ /**
2262
+ * Find matching command.
2263
+ *
2264
+ * @private
2265
+ * @return {Command | undefined}
2266
+ */
2267
+ _findCommand(name) {
2268
+ if (!name) return void 0;
2269
+ return this.commands.find(
2270
+ (cmd) => cmd._name === name || cmd._aliases.includes(name)
2271
+ );
2272
+ }
2273
+ /**
2274
+ * Return an option matching `arg` if any.
2275
+ *
2276
+ * @param {string} arg
2277
+ * @return {Option}
2278
+ * @package
2279
+ */
2280
+ _findOption(arg) {
2281
+ return this.options.find((option) => option.is(arg));
2282
+ }
2283
+ /**
2284
+ * Display an error message if a mandatory option does not have a value.
2285
+ * Called after checking for help flags in leaf subcommand.
2286
+ *
2287
+ * @private
2288
+ */
2289
+ _checkForMissingMandatoryOptions() {
2290
+ this._getCommandAndAncestors().forEach((cmd) => {
2291
+ cmd.options.forEach((anOption) => {
2292
+ if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === void 0) {
2293
+ cmd.missingMandatoryOptionValue(anOption);
2294
+ }
2295
+ });
2296
+ });
2297
+ }
2298
+ /**
2299
+ * Display an error message if conflicting options are used together in this.
2300
+ *
2301
+ * @private
2302
+ */
2303
+ _checkForConflictingLocalOptions() {
2304
+ const definedNonDefaultOptions = this.options.filter((option) => {
2305
+ const optionKey = option.attributeName();
2306
+ if (this.getOptionValue(optionKey) === void 0) {
2307
+ return false;
2308
+ }
2309
+ return this.getOptionValueSource(optionKey) !== "default";
2310
+ });
2311
+ const optionsWithConflicting = definedNonDefaultOptions.filter(
2312
+ (option) => option.conflictsWith.length > 0
2313
+ );
2314
+ optionsWithConflicting.forEach((option) => {
2315
+ const conflictingAndDefined = definedNonDefaultOptions.find(
2316
+ (defined) => option.conflictsWith.includes(defined.attributeName())
2317
+ );
2318
+ if (conflictingAndDefined) {
2319
+ this._conflictingOption(option, conflictingAndDefined);
2320
+ }
2321
+ });
2322
+ }
2323
+ /**
2324
+ * Display an error message if conflicting options are used together.
2325
+ * Called after checking for help flags in leaf subcommand.
2326
+ *
2327
+ * @private
2328
+ */
2329
+ _checkForConflictingOptions() {
2330
+ this._getCommandAndAncestors().forEach((cmd) => {
2331
+ cmd._checkForConflictingLocalOptions();
2332
+ });
2333
+ }
2334
+ /**
2335
+ * Parse options from `argv` removing known options,
2336
+ * and return argv split into operands and unknown arguments.
2337
+ *
2338
+ * Examples:
2339
+ *
2340
+ * argv => operands, unknown
2341
+ * --known kkk op => [op], []
2342
+ * op --known kkk => [op], []
2343
+ * sub --unknown uuu op => [sub], [--unknown uuu op]
2344
+ * sub -- --unknown uuu op => [sub --unknown uuu op], []
2345
+ *
2346
+ * @param {string[]} argv
2347
+ * @return {{operands: string[], unknown: string[]}}
2348
+ */
2349
+ parseOptions(argv) {
2350
+ const operands = [];
2351
+ const unknown = [];
2352
+ let dest = operands;
2353
+ const args = argv.slice();
2354
+ function maybeOption(arg) {
2355
+ return arg.length > 1 && arg[0] === "-";
2356
+ }
2357
+ let activeVariadicOption = null;
2358
+ while (args.length) {
2359
+ const arg = args.shift();
2360
+ if (arg === "--") {
2361
+ if (dest === unknown) dest.push(arg);
2362
+ dest.push(...args);
2363
+ break;
2364
+ }
2365
+ if (activeVariadicOption && !maybeOption(arg)) {
2366
+ this.emit(`option:${activeVariadicOption.name()}`, arg);
2367
+ continue;
2368
+ }
2369
+ activeVariadicOption = null;
2370
+ if (maybeOption(arg)) {
2371
+ const option = this._findOption(arg);
2372
+ if (option) {
2373
+ if (option.required) {
2374
+ const value = args.shift();
2375
+ if (value === void 0) this.optionMissingArgument(option);
2376
+ this.emit(`option:${option.name()}`, value);
2377
+ } else if (option.optional) {
2378
+ let value = null;
2379
+ if (args.length > 0 && !maybeOption(args[0])) {
2380
+ value = args.shift();
2381
+ }
2382
+ this.emit(`option:${option.name()}`, value);
2383
+ } else {
2384
+ this.emit(`option:${option.name()}`);
2385
+ }
2386
+ activeVariadicOption = option.variadic ? option : null;
2387
+ continue;
2388
+ }
2389
+ }
2390
+ if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
2391
+ const option = this._findOption(`-${arg[1]}`);
2392
+ if (option) {
2393
+ if (option.required || option.optional && this._combineFlagAndOptionalValue) {
2394
+ this.emit(`option:${option.name()}`, arg.slice(2));
2395
+ } else {
2396
+ this.emit(`option:${option.name()}`);
2397
+ args.unshift(`-${arg.slice(2)}`);
2398
+ }
2399
+ continue;
2400
+ }
2401
+ }
2402
+ if (/^--[^=]+=/.test(arg)) {
2403
+ const index = arg.indexOf("=");
2404
+ const option = this._findOption(arg.slice(0, index));
2405
+ if (option && (option.required || option.optional)) {
2406
+ this.emit(`option:${option.name()}`, arg.slice(index + 1));
2407
+ continue;
2408
+ }
2409
+ }
2410
+ if (maybeOption(arg)) {
2411
+ dest = unknown;
2412
+ }
2413
+ if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
2414
+ if (this._findCommand(arg)) {
2415
+ operands.push(arg);
2416
+ if (args.length > 0) unknown.push(...args);
2417
+ break;
2418
+ } else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
2419
+ operands.push(arg);
2420
+ if (args.length > 0) operands.push(...args);
2421
+ break;
2422
+ } else if (this._defaultCommandName) {
2423
+ unknown.push(arg);
2424
+ if (args.length > 0) unknown.push(...args);
2425
+ break;
2426
+ }
2427
+ }
2428
+ if (this._passThroughOptions) {
2429
+ dest.push(arg);
2430
+ if (args.length > 0) dest.push(...args);
2431
+ break;
2432
+ }
2433
+ dest.push(arg);
2434
+ }
2435
+ return { operands, unknown };
2436
+ }
2437
+ /**
2438
+ * Return an object containing local option values as key-value pairs.
2439
+ *
2440
+ * @return {object}
2441
+ */
2442
+ opts() {
2443
+ if (this._storeOptionsAsProperties) {
2444
+ const result = {};
2445
+ const len = this.options.length;
2446
+ for (let i = 0; i < len; i++) {
2447
+ const key = this.options[i].attributeName();
2448
+ result[key] = key === this._versionOptionName ? this._version : this[key];
2449
+ }
2450
+ return result;
2451
+ }
2452
+ return this._optionValues;
2453
+ }
2454
+ /**
2455
+ * Return an object containing merged local and global option values as key-value pairs.
2456
+ *
2457
+ * @return {object}
2458
+ */
2459
+ optsWithGlobals() {
2460
+ return this._getCommandAndAncestors().reduce(
2461
+ (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),
2462
+ {}
2463
+ );
2464
+ }
2465
+ /**
2466
+ * Display error message and exit (or call exitOverride).
2467
+ *
2468
+ * @param {string} message
2469
+ * @param {object} [errorOptions]
2470
+ * @param {string} [errorOptions.code] - an id string representing the error
2471
+ * @param {number} [errorOptions.exitCode] - used with process.exit
2472
+ */
2473
+ error(message, errorOptions) {
2474
+ this._outputConfiguration.outputError(
2475
+ `${message}
2476
+ `,
2477
+ this._outputConfiguration.writeErr
2478
+ );
2479
+ if (typeof this._showHelpAfterError === "string") {
2480
+ this._outputConfiguration.writeErr(`${this._showHelpAfterError}
2481
+ `);
2482
+ } else if (this._showHelpAfterError) {
2483
+ this._outputConfiguration.writeErr("\n");
2484
+ this.outputHelp({ error: true });
2485
+ }
2486
+ const config = errorOptions || {};
2487
+ const exitCode = config.exitCode || 1;
2488
+ const code = config.code || "commander.error";
2489
+ this._exit(exitCode, code, message);
2490
+ }
2491
+ /**
2492
+ * Apply any option related environment variables, if option does
2493
+ * not have a value from cli or client code.
2494
+ *
2495
+ * @private
2496
+ */
2497
+ _parseOptionsEnv() {
2498
+ this.options.forEach((option) => {
2499
+ if (option.envVar && option.envVar in process2.env) {
2500
+ const optionKey = option.attributeName();
2501
+ if (this.getOptionValue(optionKey) === void 0 || ["default", "config", "env"].includes(
2502
+ this.getOptionValueSource(optionKey)
2503
+ )) {
2504
+ if (option.required || option.optional) {
2505
+ this.emit(`optionEnv:${option.name()}`, process2.env[option.envVar]);
2506
+ } else {
2507
+ this.emit(`optionEnv:${option.name()}`);
2508
+ }
2509
+ }
2510
+ }
2511
+ });
2512
+ }
2513
+ /**
2514
+ * Apply any implied option values, if option is undefined or default value.
2515
+ *
2516
+ * @private
2517
+ */
2518
+ _parseOptionsImplied() {
2519
+ const dualHelper = new DualOptions(this.options);
2520
+ const hasCustomOptionValue = (optionKey) => {
2521
+ return this.getOptionValue(optionKey) !== void 0 && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
2522
+ };
2523
+ this.options.filter(
2524
+ (option) => option.implied !== void 0 && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(
2525
+ this.getOptionValue(option.attributeName()),
2526
+ option
2527
+ )
2528
+ ).forEach((option) => {
2529
+ Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
2530
+ this.setOptionValueWithSource(
2531
+ impliedKey,
2532
+ option.implied[impliedKey],
2533
+ "implied"
2534
+ );
2535
+ });
2536
+ });
2537
+ }
2538
+ /**
2539
+ * Argument `name` is missing.
2540
+ *
2541
+ * @param {string} name
2542
+ * @private
2543
+ */
2544
+ missingArgument(name) {
2545
+ const message = `error: missing required argument '${name}'`;
2546
+ this.error(message, { code: "commander.missingArgument" });
2547
+ }
2548
+ /**
2549
+ * `Option` is missing an argument.
2550
+ *
2551
+ * @param {Option} option
2552
+ * @private
2553
+ */
2554
+ optionMissingArgument(option) {
2555
+ const message = `error: option '${option.flags}' argument missing`;
2556
+ this.error(message, { code: "commander.optionMissingArgument" });
2557
+ }
2558
+ /**
2559
+ * `Option` does not have a value, and is a mandatory option.
2560
+ *
2561
+ * @param {Option} option
2562
+ * @private
2563
+ */
2564
+ missingMandatoryOptionValue(option) {
2565
+ const message = `error: required option '${option.flags}' not specified`;
2566
+ this.error(message, { code: "commander.missingMandatoryOptionValue" });
2567
+ }
2568
+ /**
2569
+ * `Option` conflicts with another option.
2570
+ *
2571
+ * @param {Option} option
2572
+ * @param {Option} conflictingOption
2573
+ * @private
2574
+ */
2575
+ _conflictingOption(option, conflictingOption) {
2576
+ const findBestOptionFromValue = (option2) => {
2577
+ const optionKey = option2.attributeName();
2578
+ const optionValue = this.getOptionValue(optionKey);
2579
+ const negativeOption = this.options.find(
2580
+ (target) => target.negate && optionKey === target.attributeName()
2581
+ );
2582
+ const positiveOption = this.options.find(
2583
+ (target) => !target.negate && optionKey === target.attributeName()
2584
+ );
2585
+ if (negativeOption && (negativeOption.presetArg === void 0 && optionValue === false || negativeOption.presetArg !== void 0 && optionValue === negativeOption.presetArg)) {
2586
+ return negativeOption;
2587
+ }
2588
+ return positiveOption || option2;
2589
+ };
2590
+ const getErrorMessage = (option2) => {
2591
+ const bestOption = findBestOptionFromValue(option2);
2592
+ const optionKey = bestOption.attributeName();
2593
+ const source = this.getOptionValueSource(optionKey);
2594
+ if (source === "env") {
2595
+ return `environment variable '${bestOption.envVar}'`;
2596
+ }
2597
+ return `option '${bestOption.flags}'`;
2598
+ };
2599
+ const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
2600
+ this.error(message, { code: "commander.conflictingOption" });
2601
+ }
2602
+ /**
2603
+ * Unknown option `flag`.
2604
+ *
2605
+ * @param {string} flag
2606
+ * @private
2607
+ */
2608
+ unknownOption(flag) {
2609
+ if (this._allowUnknownOption) return;
2610
+ let suggestion = "";
2611
+ if (flag.startsWith("--") && this._showSuggestionAfterError) {
2612
+ let candidateFlags = [];
2613
+ let command = this;
2614
+ do {
2615
+ const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
2616
+ candidateFlags = candidateFlags.concat(moreFlags);
2617
+ command = command.parent;
2618
+ } while (command && !command._enablePositionalOptions);
2619
+ suggestion = suggestSimilar(flag, candidateFlags);
2620
+ }
2621
+ const message = `error: unknown option '${flag}'${suggestion}`;
2622
+ this.error(message, { code: "commander.unknownOption" });
2623
+ }
2624
+ /**
2625
+ * Excess arguments, more than expected.
2626
+ *
2627
+ * @param {string[]} receivedArgs
2628
+ * @private
2629
+ */
2630
+ _excessArguments(receivedArgs) {
2631
+ if (this._allowExcessArguments) return;
2632
+ const expected = this.registeredArguments.length;
2633
+ const s = expected === 1 ? "" : "s";
2634
+ const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
2635
+ const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
2636
+ this.error(message, { code: "commander.excessArguments" });
2637
+ }
2638
+ /**
2639
+ * Unknown command.
2640
+ *
2641
+ * @private
2642
+ */
2643
+ unknownCommand() {
2644
+ const unknownName = this.args[0];
2645
+ let suggestion = "";
2646
+ if (this._showSuggestionAfterError) {
2647
+ const candidateNames = [];
2648
+ this.createHelp().visibleCommands(this).forEach((command) => {
2649
+ candidateNames.push(command.name());
2650
+ if (command.alias()) candidateNames.push(command.alias());
2651
+ });
2652
+ suggestion = suggestSimilar(unknownName, candidateNames);
2653
+ }
2654
+ const message = `error: unknown command '${unknownName}'${suggestion}`;
2655
+ this.error(message, { code: "commander.unknownCommand" });
2656
+ }
2657
+ /**
2658
+ * Get or set the program version.
2659
+ *
2660
+ * This method auto-registers the "-V, --version" option which will print the version number.
2661
+ *
2662
+ * You can optionally supply the flags and description to override the defaults.
2663
+ *
2664
+ * @param {string} [str]
2665
+ * @param {string} [flags]
2666
+ * @param {string} [description]
2667
+ * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments
2668
+ */
2669
+ version(str2, flags, description) {
2670
+ if (str2 === void 0) return this._version;
2671
+ this._version = str2;
2672
+ flags = flags || "-V, --version";
2673
+ description = description || "output the version number";
2674
+ const versionOption = this.createOption(flags, description);
2675
+ this._versionOptionName = versionOption.attributeName();
2676
+ this._registerOption(versionOption);
2677
+ this.on("option:" + versionOption.name(), () => {
2678
+ this._outputConfiguration.writeOut(`${str2}
2679
+ `);
2680
+ this._exit(0, "commander.version", str2);
2681
+ });
2682
+ return this;
2683
+ }
2684
+ /**
2685
+ * Set the description.
2686
+ *
2687
+ * @param {string} [str]
2688
+ * @param {object} [argsDescription]
2689
+ * @return {(string|Command)}
2690
+ */
2691
+ description(str2, argsDescription) {
2692
+ if (str2 === void 0 && argsDescription === void 0)
2693
+ return this._description;
2694
+ this._description = str2;
2695
+ if (argsDescription) {
2696
+ this._argsDescription = argsDescription;
2697
+ }
2698
+ return this;
2699
+ }
2700
+ /**
2701
+ * Set the summary. Used when listed as subcommand of parent.
2702
+ *
2703
+ * @param {string} [str]
2704
+ * @return {(string|Command)}
2705
+ */
2706
+ summary(str2) {
2707
+ if (str2 === void 0) return this._summary;
2708
+ this._summary = str2;
2709
+ return this;
2710
+ }
2711
+ /**
2712
+ * Set an alias for the command.
2713
+ *
2714
+ * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
2715
+ *
2716
+ * @param {string} [alias]
2717
+ * @return {(string|Command)}
2718
+ */
2719
+ alias(alias) {
2720
+ if (alias === void 0) return this._aliases[0];
2721
+ let command = this;
2722
+ if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
2723
+ command = this.commands[this.commands.length - 1];
2724
+ }
2725
+ if (alias === command._name)
2726
+ throw new Error("Command alias can't be the same as its name");
2727
+ const matchingCommand = this.parent?._findCommand(alias);
2728
+ if (matchingCommand) {
2729
+ const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
2730
+ throw new Error(
2731
+ `cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`
2732
+ );
2733
+ }
2734
+ command._aliases.push(alias);
2735
+ return this;
2736
+ }
2737
+ /**
2738
+ * Set aliases for the command.
2739
+ *
2740
+ * Only the first alias is shown in the auto-generated help.
2741
+ *
2742
+ * @param {string[]} [aliases]
2743
+ * @return {(string[]|Command)}
2744
+ */
2745
+ aliases(aliases) {
2746
+ if (aliases === void 0) return this._aliases;
2747
+ aliases.forEach((alias) => this.alias(alias));
2748
+ return this;
2749
+ }
2750
+ /**
2751
+ * Set / get the command usage `str`.
2752
+ *
2753
+ * @param {string} [str]
2754
+ * @return {(string|Command)}
2755
+ */
2756
+ usage(str2) {
2757
+ if (str2 === void 0) {
2758
+ if (this._usage) return this._usage;
2759
+ const args = this.registeredArguments.map((arg) => {
2760
+ return humanReadableArgName(arg);
2761
+ });
2762
+ return [].concat(
2763
+ this.options.length || this._helpOption !== null ? "[options]" : [],
2764
+ this.commands.length ? "[command]" : [],
2765
+ this.registeredArguments.length ? args : []
2766
+ ).join(" ");
2767
+ }
2768
+ this._usage = str2;
2769
+ return this;
2770
+ }
2771
+ /**
2772
+ * Get or set the name of the command.
2773
+ *
2774
+ * @param {string} [str]
2775
+ * @return {(string|Command)}
2776
+ */
2777
+ name(str2) {
2778
+ if (str2 === void 0) return this._name;
2779
+ this._name = str2;
2780
+ return this;
2781
+ }
2782
+ /**
2783
+ * Set the name of the command from script filename, such as process.argv[1],
2784
+ * or require.main.filename, or __filename.
2785
+ *
2786
+ * (Used internally and public although not documented in README.)
2787
+ *
2788
+ * @example
2789
+ * program.nameFromFilename(require.main.filename);
2790
+ *
2791
+ * @param {string} filename
2792
+ * @return {Command}
2793
+ */
2794
+ nameFromFilename(filename) {
2795
+ this._name = path9.basename(filename, path9.extname(filename));
2796
+ return this;
2797
+ }
2798
+ /**
2799
+ * Get or set the directory for searching for executable subcommands of this command.
2800
+ *
2801
+ * @example
2802
+ * program.executableDir(__dirname);
2803
+ * // or
2804
+ * program.executableDir('subcommands');
2805
+ *
2806
+ * @param {string} [path]
2807
+ * @return {(string|null|Command)}
2808
+ */
2809
+ executableDir(path10) {
2810
+ if (path10 === void 0) return this._executableDir;
2811
+ this._executableDir = path10;
2812
+ return this;
2813
+ }
2814
+ /**
2815
+ * Return program help documentation.
2816
+ *
2817
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
2818
+ * @return {string}
2819
+ */
2820
+ helpInformation(contextOptions) {
2821
+ const helper = this.createHelp();
2822
+ if (helper.helpWidth === void 0) {
2823
+ helper.helpWidth = contextOptions && contextOptions.error ? this._outputConfiguration.getErrHelpWidth() : this._outputConfiguration.getOutHelpWidth();
2824
+ }
2825
+ return helper.formatHelp(this, helper);
2826
+ }
2827
+ /**
2828
+ * @private
2829
+ */
2830
+ _getHelpContext(contextOptions) {
2831
+ contextOptions = contextOptions || {};
2832
+ const context = { error: !!contextOptions.error };
2833
+ let write;
2834
+ if (context.error) {
2835
+ write = (arg) => this._outputConfiguration.writeErr(arg);
2836
+ } else {
2837
+ write = (arg) => this._outputConfiguration.writeOut(arg);
2838
+ }
2839
+ context.write = contextOptions.write || write;
2840
+ context.command = this;
2841
+ return context;
2842
+ }
2843
+ /**
2844
+ * Output help information for this command.
2845
+ *
2846
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
2847
+ *
2848
+ * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
2849
+ */
2850
+ outputHelp(contextOptions) {
2851
+ let deprecatedCallback;
2852
+ if (typeof contextOptions === "function") {
2853
+ deprecatedCallback = contextOptions;
2854
+ contextOptions = void 0;
2855
+ }
2856
+ const context = this._getHelpContext(contextOptions);
2857
+ this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", context));
2858
+ this.emit("beforeHelp", context);
2859
+ let helpInformation = this.helpInformation(context);
2860
+ if (deprecatedCallback) {
2861
+ helpInformation = deprecatedCallback(helpInformation);
2862
+ if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
2863
+ throw new Error("outputHelp callback must return a string or a Buffer");
2864
+ }
2865
+ }
2866
+ context.write(helpInformation);
2867
+ if (this._getHelpOption()?.long) {
2868
+ this.emit(this._getHelpOption().long);
2869
+ }
2870
+ this.emit("afterHelp", context);
2871
+ this._getCommandAndAncestors().forEach(
2872
+ (command) => command.emit("afterAllHelp", context)
2873
+ );
2874
+ }
2875
+ /**
2876
+ * You can pass in flags and a description to customise the built-in help option.
2877
+ * Pass in false to disable the built-in help option.
2878
+ *
2879
+ * @example
2880
+ * program.helpOption('-?, --help' 'show help'); // customise
2881
+ * program.helpOption(false); // disable
2882
+ *
2883
+ * @param {(string | boolean)} flags
2884
+ * @param {string} [description]
2885
+ * @return {Command} `this` command for chaining
2886
+ */
2887
+ helpOption(flags, description) {
2888
+ if (typeof flags === "boolean") {
2889
+ if (flags) {
2890
+ this._helpOption = this._helpOption ?? void 0;
2891
+ } else {
2892
+ this._helpOption = null;
2893
+ }
2894
+ return this;
2895
+ }
2896
+ flags = flags ?? "-h, --help";
2897
+ description = description ?? "display help for command";
2898
+ this._helpOption = this.createOption(flags, description);
2899
+ return this;
2900
+ }
2901
+ /**
2902
+ * Lazy create help option.
2903
+ * Returns null if has been disabled with .helpOption(false).
2904
+ *
2905
+ * @returns {(Option | null)} the help option
2906
+ * @package
2907
+ */
2908
+ _getHelpOption() {
2909
+ if (this._helpOption === void 0) {
2910
+ this.helpOption(void 0, void 0);
2911
+ }
2912
+ return this._helpOption;
2913
+ }
2914
+ /**
2915
+ * Supply your own option to use for the built-in help option.
2916
+ * This is an alternative to using helpOption() to customise the flags and description etc.
2917
+ *
2918
+ * @param {Option} option
2919
+ * @return {Command} `this` command for chaining
2920
+ */
2921
+ addHelpOption(option) {
2922
+ this._helpOption = option;
2923
+ return this;
2924
+ }
2925
+ /**
2926
+ * Output help information and exit.
2927
+ *
2928
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
2929
+ *
2930
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
2931
+ */
2932
+ help(contextOptions) {
2933
+ this.outputHelp(contextOptions);
2934
+ let exitCode = process2.exitCode || 0;
2935
+ if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
2936
+ exitCode = 1;
2937
+ }
2938
+ this._exit(exitCode, "commander.help", "(outputHelp)");
2939
+ }
2940
+ /**
2941
+ * Add additional text to be displayed with the built-in help.
2942
+ *
2943
+ * Position is 'before' or 'after' to affect just this command,
2944
+ * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
2945
+ *
2946
+ * @param {string} position - before or after built-in help
2947
+ * @param {(string | Function)} text - string to add, or a function returning a string
2948
+ * @return {Command} `this` command for chaining
2949
+ */
2950
+ addHelpText(position, text) {
2951
+ const allowedValues = ["beforeAll", "before", "after", "afterAll"];
2952
+ if (!allowedValues.includes(position)) {
2953
+ throw new Error(`Unexpected value for position to addHelpText.
2954
+ Expecting one of '${allowedValues.join("', '")}'`);
2955
+ }
2956
+ const helpEvent = `${position}Help`;
2957
+ this.on(helpEvent, (context) => {
2958
+ let helpStr;
2959
+ if (typeof text === "function") {
2960
+ helpStr = text({ error: context.error, command: context.command });
2961
+ } else {
2962
+ helpStr = text;
2963
+ }
2964
+ if (helpStr) {
2965
+ context.write(`${helpStr}
2966
+ `);
2967
+ }
2968
+ });
2969
+ return this;
2970
+ }
2971
+ /**
2972
+ * Output help information if help flags specified
2973
+ *
2974
+ * @param {Array} args - array of options to search for help flags
2975
+ * @private
2976
+ */
2977
+ _outputHelpIfRequested(args) {
2978
+ const helpOption = this._getHelpOption();
2979
+ const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
2980
+ if (helpRequested) {
2981
+ this.outputHelp();
2982
+ this._exit(0, "commander.helpDisplayed", "(outputHelp)");
2983
+ }
2984
+ }
2985
+ };
2986
+ function incrementNodeInspectorPort(args) {
2987
+ return args.map((arg) => {
2988
+ if (!arg.startsWith("--inspect")) {
2989
+ return arg;
2990
+ }
2991
+ let debugOption;
2992
+ let debugHost = "127.0.0.1";
2993
+ let debugPort = "9229";
2994
+ let match;
2995
+ if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
2996
+ debugOption = match[1];
2997
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
2998
+ debugOption = match[1];
2999
+ if (/^\d+$/.test(match[3])) {
3000
+ debugPort = match[3];
3001
+ } else {
3002
+ debugHost = match[3];
3003
+ }
3004
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
3005
+ debugOption = match[1];
3006
+ debugHost = match[3];
3007
+ debugPort = match[4];
3008
+ }
3009
+ if (debugOption && debugPort !== "0") {
3010
+ return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
3011
+ }
3012
+ return arg;
3013
+ });
3014
+ }
3015
+ exports.Command = Command2;
3016
+ }
3017
+ });
3018
+
3019
+ // node_modules/commander/index.js
3020
+ var require_commander = __commonJS({
3021
+ "node_modules/commander/index.js"(exports) {
3022
+ "use strict";
3023
+ var { Argument: Argument2 } = require_argument();
3024
+ var { Command: Command2 } = require_command();
3025
+ var { CommanderError: CommanderError2, InvalidArgumentError: InvalidArgumentError2 } = require_error();
3026
+ var { Help: Help2 } = require_help();
3027
+ var { Option: Option2 } = require_option();
3028
+ exports.program = new Command2();
3029
+ exports.createCommand = (name) => new Command2(name);
3030
+ exports.createOption = (flags, description) => new Option2(flags, description);
3031
+ exports.createArgument = (name, description) => new Argument2(name, description);
3032
+ exports.Command = Command2;
3033
+ exports.Option = Option2;
3034
+ exports.Argument = Argument2;
3035
+ exports.Help = Help2;
3036
+ exports.CommanderError = CommanderError2;
3037
+ exports.InvalidArgumentError = InvalidArgumentError2;
3038
+ exports.InvalidOptionArgumentError = InvalidArgumentError2;
3039
+ }
3040
+ });
3041
+
3042
+ // node_modules/commander/esm.mjs
3043
+ var import_index, program, createCommand, createArgument, createOption, CommanderError, InvalidArgumentError, InvalidOptionArgumentError, Command, Argument, Option, Help;
3044
+ var init_esm = __esm({
3045
+ "node_modules/commander/esm.mjs"() {
3046
+ "use strict";
3047
+ import_index = __toESM(require_commander(), 1);
3048
+ ({
3049
+ program,
3050
+ createCommand,
3051
+ createArgument,
3052
+ createOption,
3053
+ CommanderError,
3054
+ InvalidArgumentError,
3055
+ InvalidOptionArgumentError,
3056
+ Command: (
3057
+ // deprecated old name
3058
+ Command
3059
+ ),
3060
+ Argument,
3061
+ Option,
3062
+ Help
3063
+ } = import_index.default);
3064
+ }
3065
+ });
3066
+
3067
+ // node_modules/picocolors/picocolors.js
3068
+ var require_picocolors = __commonJS({
3069
+ "node_modules/picocolors/picocolors.js"(exports, module) {
3070
+ "use strict";
3071
+ var p = process || {};
3072
+ var argv = p.argv || [];
3073
+ var env = p.env || {};
3074
+ var isColorSupported = !(!!env.NO_COLOR || argv.includes("--no-color")) && (!!env.FORCE_COLOR || argv.includes("--color") || p.platform === "win32" || (p.stdout || {}).isTTY && env.TERM !== "dumb" || !!env.CI);
3075
+ var formatter = (open, close, replace = open) => (input) => {
3076
+ let string = "" + input, index = string.indexOf(close, open.length);
3077
+ return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close;
3078
+ };
3079
+ var replaceClose = (string, close, replace, index) => {
3080
+ let result = "", cursor = 0;
3081
+ do {
3082
+ result += string.substring(cursor, index) + replace;
3083
+ cursor = index + close.length;
3084
+ index = string.indexOf(close, cursor);
3085
+ } while (~index);
3086
+ return result + string.substring(cursor);
3087
+ };
3088
+ var createColors = (enabled = isColorSupported) => {
3089
+ let f = enabled ? formatter : () => String;
3090
+ return {
3091
+ isColorSupported: enabled,
3092
+ reset: f("\x1B[0m", "\x1B[0m"),
3093
+ bold: f("\x1B[1m", "\x1B[22m", "\x1B[22m\x1B[1m"),
3094
+ dim: f("\x1B[2m", "\x1B[22m", "\x1B[22m\x1B[2m"),
3095
+ italic: f("\x1B[3m", "\x1B[23m"),
3096
+ underline: f("\x1B[4m", "\x1B[24m"),
3097
+ inverse: f("\x1B[7m", "\x1B[27m"),
3098
+ hidden: f("\x1B[8m", "\x1B[28m"),
3099
+ strikethrough: f("\x1B[9m", "\x1B[29m"),
3100
+ black: f("\x1B[30m", "\x1B[39m"),
3101
+ red: f("\x1B[31m", "\x1B[39m"),
3102
+ green: f("\x1B[32m", "\x1B[39m"),
3103
+ yellow: f("\x1B[33m", "\x1B[39m"),
3104
+ blue: f("\x1B[34m", "\x1B[39m"),
3105
+ magenta: f("\x1B[35m", "\x1B[39m"),
3106
+ cyan: f("\x1B[36m", "\x1B[39m"),
3107
+ white: f("\x1B[37m", "\x1B[39m"),
3108
+ gray: f("\x1B[90m", "\x1B[39m"),
3109
+ bgBlack: f("\x1B[40m", "\x1B[49m"),
3110
+ bgRed: f("\x1B[41m", "\x1B[49m"),
3111
+ bgGreen: f("\x1B[42m", "\x1B[49m"),
3112
+ bgYellow: f("\x1B[43m", "\x1B[49m"),
3113
+ bgBlue: f("\x1B[44m", "\x1B[49m"),
3114
+ bgMagenta: f("\x1B[45m", "\x1B[49m"),
3115
+ bgCyan: f("\x1B[46m", "\x1B[49m"),
3116
+ bgWhite: f("\x1B[47m", "\x1B[49m"),
3117
+ blackBright: f("\x1B[90m", "\x1B[39m"),
3118
+ redBright: f("\x1B[91m", "\x1B[39m"),
3119
+ greenBright: f("\x1B[92m", "\x1B[39m"),
3120
+ yellowBright: f("\x1B[93m", "\x1B[39m"),
3121
+ blueBright: f("\x1B[94m", "\x1B[39m"),
3122
+ magentaBright: f("\x1B[95m", "\x1B[39m"),
3123
+ cyanBright: f("\x1B[96m", "\x1B[39m"),
3124
+ whiteBright: f("\x1B[97m", "\x1B[39m"),
3125
+ bgBlackBright: f("\x1B[100m", "\x1B[49m"),
3126
+ bgRedBright: f("\x1B[101m", "\x1B[49m"),
3127
+ bgGreenBright: f("\x1B[102m", "\x1B[49m"),
3128
+ bgYellowBright: f("\x1B[103m", "\x1B[49m"),
3129
+ bgBlueBright: f("\x1B[104m", "\x1B[49m"),
3130
+ bgMagentaBright: f("\x1B[105m", "\x1B[49m"),
3131
+ bgCyanBright: f("\x1B[106m", "\x1B[49m"),
3132
+ bgWhiteBright: f("\x1B[107m", "\x1B[49m")
3133
+ };
3134
+ };
3135
+ module.exports = createColors();
3136
+ module.exports.createColors = createColors;
3137
+ }
3138
+ });
11
3139
 
12
3140
  // src/core/errors.ts
13
3141
  function exitCodeFor(error) {
@@ -137,7 +3265,6 @@ var init_redact = __esm({
137
3265
  });
138
3266
 
139
3267
  // src/cli/output.ts
140
- import pc from "picocolors";
141
3268
  function writeOut(text) {
142
3269
  stdoutWriter(text);
143
3270
  }
@@ -269,10 +3396,11 @@ function printDryRun(plan, mode) {
269
3396
  errLine(JSON.stringify(plan.body, null, 2));
270
3397
  }
271
3398
  }
272
- var FALLBACK_WIDTH, defaultStdout, defaultStderr, stdoutWriter, stderrWriter, paint, GAP, MIN_COLUMN_WIDTH;
3399
+ var import_picocolors, FALLBACK_WIDTH, defaultStdout, defaultStderr, stdoutWriter, stderrWriter, paint, GAP, MIN_COLUMN_WIDTH;
273
3400
  var init_output = __esm({
274
3401
  "src/cli/output.ts"() {
275
3402
  "use strict";
3403
+ import_picocolors = __toESM(require_picocolors(), 1);
276
3404
  init_errors();
277
3405
  init_redact();
278
3406
  FALLBACK_WIDTH = 120;
@@ -281,11 +3409,11 @@ var init_output = __esm({
281
3409
  stdoutWriter = defaultStdout;
282
3410
  stderrWriter = defaultStderr;
283
3411
  paint = {
284
- dim: (text) => isColorEnabled() ? pc.dim(text) : text,
285
- bold: (text) => isColorEnabled() ? pc.bold(text) : text,
286
- red: (text) => isColorEnabled() ? pc.red(text) : text,
287
- yellow: (text) => isColorEnabled() ? pc.yellow(text) : text,
288
- green: (text) => isColorEnabled() ? pc.green(text) : text
3412
+ dim: (text) => isColorEnabled() ? import_picocolors.default.dim(text) : text,
3413
+ bold: (text) => isColorEnabled() ? import_picocolors.default.bold(text) : text,
3414
+ red: (text) => isColorEnabled() ? import_picocolors.default.red(text) : text,
3415
+ yellow: (text) => isColorEnabled() ? import_picocolors.default.yellow(text) : text,
3416
+ green: (text) => isColorEnabled() ? import_picocolors.default.green(text) : text
289
3417
  };
290
3418
  GAP = " ";
291
3419
  MIN_COLUMN_WIDTH = 6;
@@ -297,7 +3425,7 @@ var VERSION;
297
3425
  var init_version = __esm({
298
3426
  "src/version.ts"() {
299
3427
  "use strict";
300
- VERSION = "1.8.2";
3428
+ VERSION = "1.9.0";
301
3429
  }
302
3430
  });
303
3431
 
@@ -654,7 +3782,6 @@ var init_context = __esm({
654
3782
  });
655
3783
 
656
3784
  // src/cli/globals.ts
657
- import { Option } from "commander";
658
3785
  function addGlobalOptions(command, options = {}) {
659
3786
  for (const spec of GLOBAL_FLAGS) {
660
3787
  const option = new Option(spec.flags, spec.description);
@@ -743,6 +3870,7 @@ var GLOBAL_FLAGS;
743
3870
  var init_globals = __esm({
744
3871
  "src/cli/globals.ts"() {
745
3872
  "use strict";
3873
+ init_esm();
746
3874
  init_config();
747
3875
  init_context();
748
3876
  init_logger();
@@ -1347,9 +4475,9 @@ var init_catalog = __esm({
1347
4475
  function isMutating(method) {
1348
4476
  return MUTATING.has(method.toUpperCase());
1349
4477
  }
1350
- function buildUrl(apiBase, path8, query) {
4478
+ function buildUrl(apiBase, path9, query) {
1351
4479
  const base = apiBase.replace(/\/+$/, "");
1352
- const relative = path8.startsWith("/") ? path8 : `/${path8}`;
4480
+ const relative = path9.startsWith("/") ? path9 : `/${path9}`;
1353
4481
  const url = new URL(`${base}${relative}`);
1354
4482
  if (query !== void 0) {
1355
4483
  for (const [key, value] of Object.entries(query)) {
@@ -2173,12 +5301,12 @@ function normalizeEnvelope(raw, requested) {
2173
5301
  values
2174
5302
  };
2175
5303
  }
2176
- async function fetchPage(ctx, path8, query = {}, page = {}) {
5304
+ async function fetchPage(ctx, path9, query = {}, page = {}) {
2177
5305
  const pageIndex = validatePageIndex(page.pageIndex ?? 0);
2178
5306
  const pageSize = validatePageSize(page.pageSize ?? DEFAULT_PAGE_SIZE);
2179
5307
  const raw = await request(ctx, {
2180
5308
  method: "GET",
2181
- path: path8,
5309
+ path: path9,
2182
5310
  query: { ...query, page_index: pageIndex, page_size: pageSize }
2183
5311
  });
2184
5312
  return normalizeEnvelope(raw, { pageIndex, pageSize });
@@ -2211,8 +5339,8 @@ async function* walkPages(ctx, fetchOne, options, label) {
2211
5339
  pageIndex += 1;
2212
5340
  }
2213
5341
  }
2214
- async function* paginate(ctx, path8, query = {}, options = {}) {
2215
- yield* walkPages(ctx, (page) => fetchPage(ctx, path8, query, page), options, "GET-list");
5342
+ async function* paginate(ctx, path9, query = {}, options = {}) {
5343
+ yield* walkPages(ctx, (page) => fetchPage(ctx, path9, query, page), options, "GET-list");
2216
5344
  }
2217
5345
  function asReadContext(ctx) {
2218
5346
  return ctx.dryRun ? { ...ctx, dryRun: false } : ctx;
@@ -2228,20 +5356,20 @@ function buildSearchBody(payload, page) {
2228
5356
  body.page_size = page.pageSize;
2229
5357
  return { mode: "query", payload: body };
2230
5358
  }
2231
- async function fetchSearchPage(ctx, path8, payload = {}, page = {}) {
5359
+ async function fetchSearchPage(ctx, path9, payload = {}, page = {}) {
2232
5360
  const pageIndex = validatePageIndex(page.pageIndex ?? 0);
2233
5361
  const pageSize = validatePageSize(page.pageSize ?? DEFAULT_PAGE_SIZE);
2234
5362
  const raw = await request(asReadContext(ctx), {
2235
5363
  method: "POST",
2236
- path: path8,
5364
+ path: path9,
2237
5365
  body: buildSearchBody(payload, { pageIndex, pageSize })
2238
5366
  });
2239
5367
  return normalizeEnvelope(raw, { pageIndex, pageSize });
2240
5368
  }
2241
- async function* searchPaginate(ctx, path8, payload = {}, options = {}) {
5369
+ async function* searchPaginate(ctx, path9, payload = {}, options = {}) {
2242
5370
  yield* walkPages(
2243
5371
  ctx,
2244
- (page) => fetchSearchPage(ctx, path8, payload, page),
5372
+ (page) => fetchSearchPage(ctx, path9, payload, page),
2245
5373
  options,
2246
5374
  "search"
2247
5375
  );
@@ -3959,9 +7087,9 @@ async function loadSuiteTree(ctx, path_, query) {
3959
7087
  }
3960
7088
  const candidates = [];
3961
7089
  for (const [id, node] of nodes) {
3962
- const path8 = suitePath(nodes, id);
3963
- const candidate = { id, name: node.name, path: path8 };
3964
- if (path8 !== void 0 && path8 !== node.name) candidate.aliases = [path8];
7090
+ const path9 = suitePath(nodes, id);
7091
+ const candidate = { id, name: node.name, path: path9 };
7092
+ if (path9 !== void 0 && path9 !== node.name) candidate.aliases = [path9];
3965
7093
  candidates.push(candidate);
3966
7094
  }
3967
7095
  return candidates;
@@ -4662,8 +7790,8 @@ var init_common = __esm({
4662
7790
  });
4663
7791
 
4664
7792
  // src/cli/commands/api.ts
4665
- function registerApiCommands(program) {
4666
- const api = program.command("api").description("\u901A\u7528\u9003\u751F\u8231: call any documented v1 endpoint directly (catalog-checked passthrough)");
7793
+ function registerApiCommands(program2) {
7794
+ const api = program2.command("api").description("\u901A\u7528\u9003\u751F\u8231: call any documented v1 endpoint directly (catalog-checked passthrough)");
4667
7795
  api.addHelpText(
4668
7796
  "after",
4669
7797
  "\nstdout is the API response, verbatim JSON \u2014 so --json is a no-op on the five verbs\n(it does apply to `api list` / `api describe`, which render the local catalog).\nThe path is checked against the endpoint catalog before anything is sent, so an\nunknown path, a wrong method, a missing required field or a user-token-only\nendpoint fails with exit 2 and no request.\nStart with `pingcode api list --search <text>` and `pingcode api describe <id>`.\n"
@@ -4733,29 +7861,29 @@ endpoints; a wiki page and a code branch are the two with no recovery path at al
4733
7861
  }
4734
7862
  }
4735
7863
  async function runVerb(method, pathArgument, flags, self) {
4736
- const { candidates, path: path8 } = resolveEntry2(method, pathArgument);
7864
+ const { candidates, path: path9 } = resolveEntry2(method, pathArgument);
4737
7865
  const { ctx } = contextFor(self);
4738
7866
  refuseUserTokenEndpoint(ctx, candidates);
4739
7867
  const query = parseQueryFlags(flags.query);
4740
- refuseUnconfirmedDelete(method, path8, query, flags);
7868
+ refuseUnconfirmedDelete(method, path9, query, flags);
4741
7869
  const body = await readBodyFlags(flags);
4742
7870
  const entry = chooseEntry(candidates, query, body);
4743
7871
  const paging = readPagingFor(entry, flags);
4744
7872
  try {
4745
- await send(ctx, entry, path8, query, body, paging);
7873
+ await send(ctx, entry, path9, query, body, paging);
4746
7874
  } catch (error) {
4747
7875
  if (error instanceof PermissionError) errLine(paint.dim(declaredScopeLine(entry)));
4748
7876
  throw error;
4749
7877
  }
4750
7878
  }
4751
- async function send(ctx, entry, path8, query, body, paging) {
7879
+ async function send(ctx, entry, path9, query, body, paging) {
4752
7880
  if (entry.paged === "search") {
4753
- await sendSearch(ctx, path8, body, paging);
7881
+ await sendSearch(ctx, path9, body, paging);
4754
7882
  return;
4755
7883
  }
4756
7884
  if (entry.paged === "query" && paging.all) {
4757
7885
  const values = await collect(
4758
- paginate(ctx, path8, query, {
7886
+ paginate(ctx, path9, query, {
4759
7887
  pageSize: paging.pageSize,
4760
7888
  startPage: paging.pageIndex,
4761
7889
  limit: paging.limit
@@ -4766,17 +7894,17 @@ async function send(ctx, entry, path8, query, body, paging) {
4766
7894
  }
4767
7895
  const raw = await request(ctx, {
4768
7896
  method: entry.method,
4769
- path: path8,
7897
+ path: path9,
4770
7898
  query: paging.requested ? { ...query, page_index: paging.pageIndex, page_size: paging.pageSize } : query,
4771
7899
  ...body === void 0 ? {} : { body }
4772
7900
  });
4773
7901
  printResponse(raw);
4774
7902
  }
4775
- async function sendSearch(ctx, path8, body, paging) {
7903
+ async function sendSearch(ctx, path9, body, paging) {
4776
7904
  const payload = searchPayloadOf(body);
4777
7905
  if (paging.all) {
4778
7906
  const values = await collect(
4779
- searchPaginate(ctx, path8, payload, {
7907
+ searchPaginate(ctx, path9, payload, {
4780
7908
  pageSize: paging.pageSize,
4781
7909
  startPage: paging.pageIndex,
4782
7910
  limit: paging.limit
@@ -4785,7 +7913,7 @@ async function sendSearch(ctx, path8, body, paging) {
4785
7913
  printJson({ values, count: values.length, all: true });
4786
7914
  return;
4787
7915
  }
4788
- const page = await fetchSearchPage(ctx, path8, payload, {
7916
+ const page = await fetchSearchPage(ctx, path9, payload, {
4789
7917
  pageIndex: paging.pageIndex,
4790
7918
  pageSize: paging.pageSize
4791
7919
  });
@@ -4819,8 +7947,8 @@ function resolveEntry2(method, pathArgument) {
4819
7947
  hint: `drop everything from "?" and pass the parameters as --query key=value (repeatable), so they are serialised the same way every other command does it`
4820
7948
  });
4821
7949
  }
4822
- const path8 = normalizePath(raw);
4823
- const unfilled = unfilledPathParams(path8);
7950
+ const path9 = normalizePath(raw);
7951
+ const unfilled = unfilledPathParams(path9);
4824
7952
  if (unfilled.length > 0) {
4825
7953
  throw new UsageError(
4826
7954
  `the path still contains the placeholder${unfilled.length > 1 ? "s" : ""} ${unfilled.map((name) => `{${name}}`).join(", ")}`,
@@ -4829,32 +7957,32 @@ function resolveEntry2(method, pathArgument) {
4829
7957
  }
4830
7958
  );
4831
7959
  }
4832
- const onPath = matchPath(path8);
4833
- if (onPath.length === 0) throw unknownPath(path8);
7960
+ const onPath = matchPath(path9);
7961
+ if (onPath.length === 0) throw unknownPath(path9);
4834
7962
  const candidates = onPath.filter((candidate) => candidate.method === method);
4835
7963
  if (candidates.length === 0) {
4836
- const supported = methodsFor(path8);
4837
- throw new UsageError(`${method} ${path8} is not a documented endpoint`, {
7964
+ const supported = methodsFor(path9);
7965
+ throw new UsageError(`${method} ${path9} is not a documented endpoint`, {
4838
7966
  hint: `that path supports ${supported.join(", ")} \u2014 this API is missing several symmetric operations on purpose (there is no project delete, no sprint delete, and nothing in \u4EA7\u54C1\u7BA1\u7406 can be deleted at all)`
4839
7967
  });
4840
7968
  }
4841
- return { candidates, path: path8 };
7969
+ return { candidates, path: path9 };
4842
7970
  }
4843
- function unknownPath(path8) {
4844
- if (segmentsOf2(path8).includes("authorize")) {
7971
+ function unknownPath(path9) {
7972
+ if (segmentsOf2(path9).includes("authorize")) {
4845
7973
  return new UsageError(
4846
- `${path8} is the browser authorization page of the OAuth2 authorization-code flow, not a REST endpoint: it renders HTML for a human to click and redirects, it returns no JSON, and it is not under /v1`,
7974
+ `${path9} is the browser authorization page of the OAuth2 authorization-code flow, not a REST endpoint: it renders HTML for a human to click and redirects, it returns no JSON, and it is not under /v1`,
4847
7975
  { hint: AUTHORIZE_HINT }
4848
7976
  );
4849
7977
  }
4850
- const suggestions = nearestPaths(path8);
4851
- const hint = suggestions.length === 0 ? `no documented path has ${segmentsOf2(path8).length} segments like this one \u2014 search the catalog with \`pingcode api list --search <text>\`` : `did you mean ${suggestions.join(" , ")} ? \u2014 or search with \`pingcode api list --search <text>\``;
4852
- return new UsageError(`${path8} is not in the endpoint catalog (459 documented v1 endpoints)`, {
7978
+ const suggestions = nearestPaths(path9);
7979
+ const hint = suggestions.length === 0 ? `no documented path has ${segmentsOf2(path9).length} segments like this one \u2014 search the catalog with \`pingcode api list --search <text>\`` : `did you mean ${suggestions.join(" , ")} ? \u2014 or search with \`pingcode api list --search <text>\``;
7980
+ return new UsageError(`${path9} is not in the endpoint catalog (459 documented v1 endpoints)`, {
4853
7981
  hint
4854
7982
  });
4855
7983
  }
4856
- function nearestPaths(path8) {
4857
- const actual = segmentsOf2(path8);
7984
+ function nearestPaths(path9) {
7985
+ const actual = segmentsOf2(path9);
4858
7986
  const scored = /* @__PURE__ */ new Map();
4859
7987
  for (const entry of CATALOG2) {
4860
7988
  const template = segmentsOf2(entry.path);
@@ -4883,8 +8011,8 @@ function editDistance(a, b) {
4883
8011
  }
4884
8012
  return previous[b.length] ?? Math.max(a.length, b.length);
4885
8013
  }
4886
- function segmentsOf2(path8) {
4887
- return path8.split("/").filter((segment) => segment !== "");
8014
+ function segmentsOf2(path9) {
8015
+ return path9.split("/").filter((segment) => segment !== "");
4888
8016
  }
4889
8017
  function isPlaceholder2(segment) {
4890
8018
  return segment.startsWith("{") && segment.endsWith("}");
@@ -4901,9 +8029,9 @@ function refuseUserTokenEndpoint(ctx, candidates) {
4901
8029
  }
4902
8030
  );
4903
8031
  }
4904
- function refuseUnconfirmedDelete(method, path8, query, flags) {
8032
+ function refuseUnconfirmedDelete(method, path9, query, flags) {
4905
8033
  if (method !== "DELETE" || flags.yes === true) return;
4906
- throw new UsageError(`refusing to send DELETE ${path8}${displayQuery(query)} without --yes`, {
8034
+ throw new UsageError(`refusing to send DELETE ${path9}${displayQuery(query)} without --yes`, {
4907
8035
  hint: "re-run with --yes to send it, or with --yes --dry-run to print the full request plan without sending anything"
4908
8036
  });
4909
8037
  }
@@ -5065,22 +8193,22 @@ function registerDescribe(api) {
5065
8193
  "\nAn id is exact; a method + path is matched through the same wildcard rules the\nexecutor uses. GET /v1/auth/token is the one path three entries share (the three\ngrants), so address those by id.\n--json prints the catalog entry verbatim.\n"
5066
8194
  );
5067
8195
  addGlobalOptions(command, { hidden: true }).action(
5068
- (idOrMethod, path8, _flags, self) => {
8196
+ (idOrMethod, path9, _flags, self) => {
5069
8197
  const { ctx } = contextFor(self);
5070
- const entry = lookupForDescribe(idOrMethod, path8);
8198
+ const entry = lookupForDescribe(idOrMethod, path9);
5071
8199
  printEntry(entry, modeOf(ctx));
5072
8200
  }
5073
8201
  );
5074
8202
  }
5075
- function lookupForDescribe(idOrMethod, path8) {
5076
- if (path8 !== void 0) {
8203
+ function lookupForDescribe(idOrMethod, path9) {
8204
+ if (path9 !== void 0) {
5077
8205
  const method = idOrMethod.trim().toUpperCase();
5078
8206
  if (!METHODS.includes(method)) {
5079
8207
  throw new UsageError(`"${idOrMethod}" is not an HTTP method`, {
5080
8208
  hint: `the methods are ${METHODS.join(", ")} \u2014 or pass a single catalog id instead`
5081
8209
  });
5082
8210
  }
5083
- const normalized = normalizePath(path8.trim());
8211
+ const normalized = normalizePath(path9.trim());
5084
8212
  const matches = matchPath(normalized).filter((entry2) => entry2.method === method);
5085
8213
  const entry = matches[0];
5086
8214
  if (entry === void 0) {
@@ -5257,26 +8385,26 @@ function parseRefList(raw) {
5257
8385
  function parseProperties(raw) {
5258
8386
  return typeof raw === "object" && raw !== null && !Array.isArray(raw) ? raw : void 0;
5259
8387
  }
5260
- async function fetchPageOf(ctx, path8, query, page, parse) {
5261
- const raw = await fetchPage(ctx, path8, query, page);
8388
+ async function fetchPageOf(ctx, path9, query, page, parse) {
8389
+ const raw = await fetchPage(ctx, path9, query, page);
5262
8390
  return { ...raw, values: raw.values.map(parse) };
5263
8391
  }
5264
- async function* iterateOf(ctx, path8, query, options, parse) {
5265
- for await (const raw of paginate(ctx, path8, query, options)) {
8392
+ async function* iterateOf(ctx, path9, query, options, parse) {
8393
+ for await (const raw of paginate(ctx, path9, query, options)) {
5266
8394
  yield parse(raw);
5267
8395
  }
5268
8396
  }
5269
- async function listAllOf(ctx, path8, query, parse, options = {}) {
8397
+ async function listAllOf(ctx, path9, query, parse, options = {}) {
5270
8398
  return await collect(
5271
- iterateOf(ctx, path8, query, { pageSize: 100, limit: 1e3, ...options }, parse)
8399
+ iterateOf(ctx, path9, query, { pageSize: 100, limit: 1e3, ...options }, parse)
5272
8400
  );
5273
8401
  }
5274
- async function fetchSearchPageOf(ctx, path8, payload, page, parse) {
5275
- const raw = await fetchSearchPage(ctx, path8, payload, page);
8402
+ async function fetchSearchPageOf(ctx, path9, payload, page, parse) {
8403
+ const raw = await fetchSearchPage(ctx, path9, payload, page);
5276
8404
  return { ...raw, values: raw.values.map(parse) };
5277
8405
  }
5278
- async function* iterateSearchOf(ctx, path8, payload, options, parse) {
5279
- for await (const raw of searchPaginate(ctx, path8, payload, options)) {
8406
+ async function* iterateSearchOf(ctx, path9, payload, options, parse) {
8407
+ for await (const raw of searchPaginate(ctx, path9, payload, options)) {
5280
8408
  yield parse(raw);
5281
8409
  }
5282
8410
  }
@@ -6829,8 +9957,8 @@ var init_oauth = __esm({
6829
9957
 
6830
9958
  // src/cli/commands/auth.ts
6831
9959
  import { createInterface } from "readline/promises";
6832
- function registerAuthCommands(program) {
6833
- const auth = program.command("auth").description("authenticate against PingCode (enterprise app or user token)");
9960
+ function registerAuthCommands(program2) {
9961
+ const auth = program2.command("auth").description("authenticate against PingCode (enterprise app or user token)");
6834
9962
  addGlobalOptions(
6835
9963
  auth.command("login").description("acquire a token (user token by default) and verify it").option("--client-id <id>", "app client id (or PINGCODE_CLIENT_ID)").option("--client-secret <secret>", "app client secret (or PINGCODE_CLIENT_SECRET)").option("--save", "also store the client id/secret in the config file (mode 0600)").option(
6836
9964
  "--mode <mode>",
@@ -7324,8 +10452,8 @@ var init_workItems = __esm({
7324
10452
  function durationCell(duration) {
7325
10453
  return duration === void 0 ? "" : `${duration}s`;
7326
10454
  }
7327
- function registerBuildCommands(program) {
7328
- const group = program.command("build").description(
10455
+ function registerBuildCommands(program2) {
10456
+ const group = program2.command("build").description(
7329
10457
  "\u6784\u5EFA\u4E0E\u90E8\u7F72 build: CI build records \u6784\u5EFA\u8BB0\u5F55 written back onto work items (\u4F01\u4E1A\u4EE4\u724C only, scopes pcp:read:devops:build / pcp:write:devops:build)"
7330
10458
  ).addHelpText(
7331
10459
  "after",
@@ -9109,8 +12237,8 @@ var init_ticket = __esm({
9109
12237
  });
9110
12238
 
9111
12239
  // src/cli/commands/product.ts
9112
- function registerProductCommands(program) {
9113
- const product = program.command("product").description("\u4EA7\u54C1\u7BA1\u7406 ship: products, ideas \u9700\u6C42, tickets \u5DE5\u5355 (scope pcp:read:ship:product)").addHelpText(
12240
+ function registerProductCommands(program2) {
12241
+ const product = program2.command("product").description("\u4EA7\u54C1\u7BA1\u7406 ship: products, ideas \u9700\u6C42, tickets \u5DE5\u5355 (scope pcp:read:ship:product)").addHelpText(
9114
12242
  "after",
9115
12243
  "\nPERMANENT: nothing in this group can be deleted. ship publishes 8 DELETEs and every\none of them removes a configuration or membership row \u2014 a scheme entry, a product\nmember, a suite, a tag, an external user, a state flow \u2014 never a product, a\nrequirement or a ticket. So a requirement or ticket you create here is forever, and\n`--dry-run` is worth the extra call. There is no archive either.\n"
9116
12244
  );
@@ -9808,13 +12936,13 @@ var init_projectMember = __esm({
9808
12936
 
9809
12937
  // src/cli/commands/_shared/bulkEntries.ts
9810
12938
  async function readBulkEntries(source, options) {
9811
- const path8 = source.file?.trim() ?? "";
9812
- if (path8 === "") {
12939
+ const path9 = source.file?.trim() ?? "";
12940
+ if (path9 === "") {
9813
12941
  throw new UsageError("--file <path|-> is required", {
9814
12942
  hint: "pass a JSON array of entries, or - to read it from stdin. Each entry needs name, start and end; project and assignee may be shared with --project / --assignee"
9815
12943
  });
9816
12944
  }
9817
- const document = path8 === "-" ? await readJsonStdin() : parseJsonDocument(await readTextFile(path8, "--file"), `--file ${path8}`);
12945
+ const document = path9 === "-" ? await readJsonStdin() : parseJsonDocument(await readTextFile(path9, "--file"), `--file ${path9}`);
9818
12946
  const list = unwrap(document, options.wrapperKey);
9819
12947
  if (list.length === 0) {
9820
12948
  throw new UsageError("--file contained no entries", {
@@ -11560,8 +14688,8 @@ var init_workItem = __esm({
11560
14688
  });
11561
14689
 
11562
14690
  // src/cli/commands/project.ts
11563
- function registerProjectCommands(program) {
11564
- const project = program.command("project").description("\u9879\u76EE\u7BA1\u7406 pjm: projects and work items (scope pcp:read:pjm:project)");
14691
+ function registerProjectCommands(program2) {
14692
+ const project = program2.command("project").description("\u9879\u76EE\u7BA1\u7406 pjm: projects and work items (scope pcp:read:pjm:project)");
11565
14693
  addGlobalOptions(
11566
14694
  addPagingOptions(
11567
14695
  project.command("list").description("list projects").option("--keywords <text>", "fuzzy search over project names").option("--type <type>", "scrum | kanban | waterfall | hybrid").option("--include-archived", "include archived projects")
@@ -12342,8 +15470,8 @@ var init_deploy = __esm({
12342
15470
  });
12343
15471
 
12344
15472
  // src/cli/commands/release/index.ts
12345
- function registerReleaseCommands(program) {
12346
- const release = program.command("release").description(
15473
+ function registerReleaseCommands(program2) {
15474
+ const release = program2.command("release").description(
12347
15475
  "\u6784\u5EFA\u4E0E\u90E8\u7F72 release: deploy targets \u73AF\u5883 and deployment records \u90E8\u7F72 (\u4F01\u4E1A\u4EE4\u724C only, scopes pcp:read:devops:deploy / pcp:write:devops:deploy)"
12348
15476
  ).addHelpText(
12349
15477
  "after",
@@ -12361,8 +15489,8 @@ var init_release2 = __esm({
12361
15489
  });
12362
15490
 
12363
15491
  // src/cli/commands/resolve.ts
12364
- function registerResolveCommands(program) {
12365
- const resolve = program.command("resolve").description("name \u2192 id: resolve a name, alias or id for any of the CLI's lookup kinds");
15492
+ function registerResolveCommands(program2) {
15493
+ const resolve = program2.command("resolve").description("name \u2192 id: resolve a name, alias or id for any of the CLI's lookup kinds");
12366
15494
  resolve.addHelpText(
12367
15495
  "after",
12368
15496
  '\nEvery lookup follows the same rules as the refined commands, because it is the same\nengine: an id is passed through untouched, a name must match **exactly** (case-\ninsensitively) and exactly once, and the answer is cached for 24h under\n(host, client_id, parent, kind) \u2014 bypass it with --no-cache.\nStart with `pingcode resolve list`, which prints every kind and the parent it needs.\n--parent takes an **id**, so the group composes with itself as well as with `api`:\n pingcode resolve ship-idea-state \u5DF2\u8BC4\u5BA1 \\\n --parent "$(pingcode resolve ship-product \u667A\u80FD\u5BA2\u670D --json | jq -r .id)"\n pingcode api GET /v1/ship/idea/states \\\n --query product_id=$(pingcode resolve ship-product "\u667A\u80FD\u5BA2\u670D" --json | jq -r .id)\nKinds that a name cannot address at all (ticket state plans and their flows) are\nabsent on purpose: nothing names them, so there is nothing to resolve.\n'
@@ -14313,8 +17441,8 @@ var init_review = __esm({
14313
17441
  });
14314
17442
 
14315
17443
  // src/cli/commands/scm/index.ts
14316
- function registerScmCommands(program) {
14317
- const scm = program.command("scm").description(
17444
+ function registerScmCommands(program2) {
17445
+ const scm = program2.command("scm").description(
14318
17446
  "\u6E90\u7801\u7BA1\u7406 scm: the DevOps write-back surface for code hosting data (\u4F01\u4E1A\u4EE4\u724C only, scopes pcp:read:devops:code / pcp:write:devops:code)"
14319
17447
  );
14320
17448
  registerPlatformCommands(scm);
@@ -14486,21 +17614,9 @@ function skillTargets(env = process.env) {
14486
17614
  }
14487
17615
  ];
14488
17616
  }
14489
- function installDir(env = process.env) {
14490
- if (process.platform === "win32") {
14491
- const base = env["LOCALAPPDATA"];
14492
- const root3 = base !== void 0 && base !== "" ? base : path4.join(os2.homedir(), "AppData", "Local");
14493
- return path4.join(root3, APP_NAME);
14494
- }
14495
- const xdg = env["XDG_DATA_HOME"];
14496
- const root2 = xdg !== void 0 && xdg !== "" ? xdg : path4.join(os2.homedir(), ".local", "share");
14497
- return path4.join(root2, APP_NAME);
14498
- }
14499
- var APP_NAME;
14500
17617
  var init_paths = __esm({
14501
17618
  "src/core/paths.ts"() {
14502
17619
  "use strict";
14503
- APP_NAME = "pingcode-cli";
14504
17620
  }
14505
17621
  });
14506
17622
 
@@ -14511,18 +17627,21 @@ import {
14511
17627
  mkdirSync as mkdirSync3,
14512
17628
  readFileSync as readFileSync3,
14513
17629
  readdirSync,
14514
- renameSync as renameSync2,
14515
17630
  rmSync as rmSync3,
14516
17631
  statSync as statSync2,
14517
17632
  utimesSync,
14518
17633
  writeFileSync as writeFileSync3
14519
17634
  } from "fs";
14520
17635
  import { execFileSync } from "child_process";
14521
- import os3 from "os";
14522
17636
  import path5 from "path";
14523
- import { gunzipSync } from "zlib";
17637
+ import { fileURLToPath } from "url";
14524
17638
  function defaultExec(file, args) {
14525
- return execFileSync(file, args, { encoding: "utf8" });
17639
+ const isWindowsBatch = /\.(cmd|bat)$/i.test(file);
17640
+ return execFileSync(file, args, {
17641
+ encoding: "utf8",
17642
+ stdio: ["inherit", "pipe", "pipe"],
17643
+ ...isWindowsBatch ? { shell: true } : {}
17644
+ });
14526
17645
  }
14527
17646
  function defaultFetch(input, init) {
14528
17647
  return init === void 0 ? globalThis.fetch(input) : globalThis.fetch(input, init);
@@ -14583,174 +17702,69 @@ async function fetchLatestInfo(fetchFn = defaultFetch) {
14583
17702
  }
14584
17703
  return { version: latest, tarballUrl };
14585
17704
  }
14586
- async function downloadTarball(url, fetchFn = defaultFetch) {
14587
- let response;
14588
- try {
14589
- response = await fetchFn(url, { signal: AbortSignal.timeout(NETWORK_TIMEOUT_MS) });
14590
- } catch (error) {
14591
- throw new TransportError(`failed to download tarball: ${errorMessage2(error)}`, {
14592
- cause: error
14593
- });
14594
- }
14595
- if (!response.ok) {
17705
+ function resolveNpm() {
17706
+ const binDir = path5.dirname(process.execPath);
17707
+ const candidates = process.platform === "win32" ? [path5.join(binDir, "npm.cmd"), path5.join(binDir, "npm")] : [path5.join(binDir, "npm")];
17708
+ return candidates.find(existsSync2);
17709
+ }
17710
+ async function installViaNpm(exec, version) {
17711
+ const npm = resolveNpm();
17712
+ if (npm === void 0) {
14596
17713
  throw new TransportError(
14597
- `tarball download returned HTTP ${response.status}`,
14598
- { status: response.status }
17714
+ `cannot update: no npm binary found next to the node running this command (tried ${path5.join(path5.dirname(process.execPath), "npm")})`,
17715
+ { hint: `install Node.js, then re-run this command` }
14599
17716
  );
14600
17717
  }
14601
- if (response.body === null) {
14602
- throw new TransportError("tarball download returned empty body");
14603
- }
14604
- const chunks = [];
14605
- const reader = response.body.getReader();
14606
- const MAX_SIZE = 50 * 1024 * 1024;
14607
- let total = 0;
14608
- while (true) {
14609
- const { done, value } = await reader.read();
14610
- if (done) break;
14611
- total += value.length;
14612
- if (total > MAX_SIZE) {
14613
- throw new TransportError(`tarball exceeds maximum size of ${MAX_SIZE} bytes`);
14614
- }
14615
- chunks.push(value);
14616
- }
14617
- return Buffer.concat(chunks);
14618
- }
14619
- function extractTarball(buffer, destDir) {
14620
- const gzipped = gunzipSync(buffer);
14621
- return extractTar(gzipped, destDir);
14622
- }
14623
- function extractTar(tarBuffer, destDir) {
14624
- const resolvedDest = path5.resolve(destDir);
14625
- mkdirSync3(resolvedDest, { recursive: true });
14626
- const extracted = [];
14627
- let offset = 0;
14628
- while (offset < tarBuffer.length) {
14629
- if (offset + 512 > tarBuffer.length) break;
14630
- const headerBlock = tarBuffer.subarray(offset, offset + 512);
14631
- if (headerBlock.every((b) => b === 0)) {
14632
- break;
14633
- }
14634
- const name = readTarString(headerBlock, 0, 100);
14635
- const typeflag = tarBuffer[offset + 156];
14636
- const size = readTarNumber(headerBlock, 124, 12);
14637
- offset += 512;
14638
- const dataBlocks = Math.ceil(size / 512);
14639
- const dataOffset = offset;
14640
- if (typeflag === "5".charCodeAt(0)) {
14641
- const cleanName = stripPackagePrefix(name);
14642
- if (cleanName) {
14643
- const dest = path5.resolve(resolvedDest, cleanName);
14644
- if (dest.startsWith(resolvedDest + path5.sep) || dest === resolvedDest) {
14645
- mkdirSync3(dest, { recursive: true });
14646
- }
14647
- }
14648
- } else if (typeflag === "0".charCodeAt(0) || typeflag === 0) {
14649
- const cleanName = stripPackagePrefix(name);
14650
- if (cleanName) {
14651
- const data = tarBuffer.subarray(dataOffset, dataOffset + size);
14652
- const dest = path5.resolve(resolvedDest, cleanName);
14653
- if (dest.startsWith(resolvedDest + path5.sep)) {
14654
- mkdirSync3(path5.dirname(dest), { recursive: true });
14655
- writeFileSync3(dest, data);
14656
- extracted.push(cleanName);
14657
- }
14658
- }
14659
- }
14660
- offset += dataBlocks * 512;
14661
- }
14662
- return extracted;
14663
- }
14664
- function stripPackagePrefix(name) {
14665
- if (name.startsWith("package/")) {
14666
- return name.slice("package/".length);
14667
- }
14668
- return name;
14669
- }
14670
- function readTarString(buf, start, maxLen) {
14671
- const end = buf.indexOf(0, start);
14672
- const actualEnd = end < 0 ? start + maxLen : end;
14673
- return buf.subarray(start, actualEnd).toString("utf8").trim();
14674
- }
14675
- function readTarNumber(buf, start, maxLen) {
14676
- const str2 = readTarString(buf, start, maxLen);
14677
- if (str2.charCodeAt(0) === 128) {
14678
- return 0;
14679
- }
14680
- return parseInt(str2, 8) || 0;
14681
- }
14682
- async function atomicReplace(current, staging) {
14683
- const backup = `${current}.backup`;
14684
- if (existsSync2(backup)) {
14685
- rmSync3(backup, { recursive: true, force: true });
14686
- }
14687
- const isNested = staging.startsWith(`${current}${path5.sep}`);
14688
- const incoming = isNested ? `${current}.incoming` : staging;
14689
- if (isNested) {
14690
- if (existsSync2(incoming)) rmSync3(incoming, { recursive: true, force: true });
14691
- try {
14692
- renameSync2(staging, incoming);
14693
- } catch (error) {
14694
- throw new TransportError(
14695
- `failed to move staging aside: ${errorMessage2(error)}`,
14696
- { cause: error }
14697
- );
14698
- }
14699
- }
14700
- if (existsSync2(current)) {
14701
- try {
14702
- renameSync2(current, backup);
14703
- } catch (error) {
14704
- if (isNested && existsSync2(incoming)) {
14705
- try {
14706
- renameSync2(incoming, staging);
14707
- } catch {
14708
- }
14709
- }
14710
- throw new TransportError(
14711
- `failed to back up current install: ${errorMessage2(error)}`,
14712
- { cause: error }
14713
- );
14714
- }
14715
- }
17718
+ const spec = `${PACKAGE_NAME2}@${version}`;
17719
+ let output;
14716
17720
  try {
14717
- renameSync2(incoming, current);
17721
+ output = exec(npm, ["install", "--global", spec]);
14718
17722
  } catch (error) {
14719
- try {
14720
- if (existsSync2(backup)) renameSync2(backup, current);
14721
- } catch (restoreError) {
14722
- throw new TransportError(
14723
- `CRITICAL: update failed AND backup restore failed. Restore manually: mv "${backup}" "${current}". Original error: ${errorMessage2(error)}. Restore error: ${errorMessage2(restoreError)}`,
14724
- { cause: error }
14725
- );
14726
- }
17723
+ const detail = npmOutputOf(error);
14727
17724
  throw new TransportError(
14728
- `failed to install update (backup restored): ${errorMessage2(error)}`,
17725
+ `npm install --global ${spec} failed (exit ${exitStatusOf(error)}): ${errorMessage2(error)}`,
14729
17726
  {
14730
- hint: `if needed, restore manually: mv "${backup}" "${current}"`,
17727
+ hint: detail === "" ? `npm printed nothing; try running manually: ${npm} install --global ${spec}` : detail,
14731
17728
  cause: error
14732
17729
  }
14733
17730
  );
14734
17731
  }
17732
+ const trimmed = output.trim();
17733
+ if (trimmed !== "") {
17734
+ process.stderr.write(`${output.endsWith("\n") ? output : `${output}
17735
+ `}`);
17736
+ }
17737
+ const installed = readInstalledVersion();
17738
+ if (installed !== version) {
17739
+ throw new TransportError(
17740
+ `npm install --global ${spec} exited 0 but the installed version is ${installed ?? "unreadable"}, expected ${version}`,
17741
+ { hint: `verify with: ${npm} list --global --depth=0 ${PACKAGE_NAME2}` }
17742
+ );
17743
+ }
17744
+ }
17745
+ function readInstalledVersion() {
14735
17746
  try {
14736
- rmSync3(backup, { recursive: true, force: true });
17747
+ const raw = readFileSync3(fileURLToPath(new URL("../../package.json", import.meta.url)), "utf8");
17748
+ const parsed = JSON.parse(raw);
17749
+ if (typeof parsed !== "object" || parsed === null) return void 0;
17750
+ const version = parsed.version;
17751
+ return typeof version === "string" ? version : void 0;
14737
17752
  } catch {
17753
+ return void 0;
14738
17754
  }
14739
17755
  }
14740
- function cleanStaging(stagingDir) {
14741
- if (existsSync2(stagingDir)) {
14742
- rmSync3(stagingDir, { recursive: true, force: true });
17756
+ function exitStatusOf(error) {
17757
+ if (typeof error === "object" && error !== null && "status" in error) {
17758
+ const status = error.status;
17759
+ if (typeof status === "number") return String(status);
17760
+ if (typeof status === "string" && status !== "") return status;
14743
17761
  }
17762
+ return "unknown";
14744
17763
  }
14745
- function validateStaging(stagingDir) {
14746
- const bin = path5.join(stagingDir, "dist", "bin", "pingcode.js");
14747
- return existsSync2(bin);
14748
- }
14749
- function writeBufferToFile(destPath, buffer) {
14750
- writeFileSync3(destPath, buffer);
14751
- }
14752
- function ensureDir(dirPath) {
14753
- mkdirSync3(dirPath, { recursive: true });
17764
+ function npmOutputOf(error) {
17765
+ if (typeof error !== "object" || error === null) return "";
17766
+ const e = error;
17767
+ return [e.stderr, e.stdout].filter((part) => part !== void 0 && part !== null).map((part) => String(part).trim()).filter((part) => part !== "").join("\n");
14754
17768
  }
14755
17769
  function removeFile(filePath) {
14756
17770
  try {
@@ -14761,6 +17775,9 @@ function removeFile(filePath) {
14761
17775
  function dirExists(dirPath) {
14762
17776
  return existsSync2(dirPath);
14763
17777
  }
17778
+ function packageSkillDir() {
17779
+ return fileURLToPath(new URL("../../skills/pingcode", import.meta.url));
17780
+ }
14764
17781
  async function syncSkills(sourceDir, targets) {
14765
17782
  const written = [];
14766
17783
  const payload = [];
@@ -14789,20 +17806,6 @@ async function syncSkills(sourceDir, targets) {
14789
17806
  }
14790
17807
  return written;
14791
17808
  }
14792
- function verifyInstall(dir, exec) {
14793
- const bin = path5.join(dir, "dist", "bin", "pingcode.js");
14794
- try {
14795
- return exec("node", [bin, "--version"]).trim();
14796
- } catch (error) {
14797
- throw new TransportError(
14798
- `failed to verify new installation: ${errorMessage2(error)}`,
14799
- {
14800
- hint: `try running manually: node "${bin}" --version`,
14801
- cause: error
14802
- }
14803
- );
14804
- }
14805
- }
14806
17809
  function acquireLock(dir) {
14807
17810
  const lockPath = path5.join(dir, LOCK_FILENAME);
14808
17811
  try {
@@ -14876,7 +17879,6 @@ function removeHint(dir) {
14876
17879
  removeFile(path5.join(dir, HINT_FILENAME));
14877
17880
  }
14878
17881
  async function runAutoUpdate(env = process.env, fetchFn = defaultFetch, exec = defaultExec) {
14879
- const dir = installDir(env);
14880
17882
  const stateDir = configDir(env);
14881
17883
  try {
14882
17884
  touchCooldown(stateDir);
@@ -14902,45 +17904,16 @@ async function runAutoUpdate(env = process.env, fetchFn = defaultFetch, exec = d
14902
17904
  return { status: "up-to-date" };
14903
17905
  }
14904
17906
  const newVersion = info.version;
14905
- const tarballBuffer = await downloadTarball(info.tarballUrl, fetchFn);
14906
- const stagingDir = path5.join(dir, ".staging");
14907
- const tmpTarball = path5.join(os3.tmpdir(), `pingcode-cli-${newVersion}.tgz`);
17907
+ await installViaNpm(exec, newVersion);
17908
+ const skillSource = packageSkillDir();
17909
+ if (dirExists(skillSource)) {
17910
+ await syncSkills(skillSource, skillTargets(env));
17911
+ }
14908
17912
  try {
14909
- writeFileSync3(tmpTarball, tarballBuffer);
14910
- cleanStaging(stagingDir);
14911
- mkdirSync3(stagingDir, { recursive: true });
14912
- extractTarball(tarballBuffer, stagingDir);
14913
- if (!validateStaging(stagingDir)) {
14914
- cleanStaging(stagingDir);
14915
- throw new TransportError("invalid tarball: dist/bin/pingcode.js not found");
14916
- }
14917
- await atomicReplace(dir, stagingDir);
14918
- try {
14919
- exec("npm", ["install", "--production", "--prefix", dir]);
14920
- } catch (error) {
14921
- const backup = `${dir}.backup`;
14922
- try {
14923
- atomicReplace(dir, backup);
14924
- } catch {
14925
- }
14926
- throw new TransportError(
14927
- `failed to install dependencies: ${errorMessage2(error)}`,
14928
- { cause: error }
14929
- );
14930
- }
14931
- const skillSource = path5.join(dir, "skills", "pingcode");
14932
- if (dirExists(skillSource)) {
14933
- await syncSkills(skillSource, skillTargets(env));
14934
- }
14935
- verifyInstall(dir, exec);
14936
- try {
14937
- removeHint(stateDir);
14938
- } catch {
14939
- }
14940
- return { status: "updated", version: newVersion };
14941
- } finally {
14942
- removeFile(tmpTarball);
17913
+ removeHint(stateDir);
17914
+ } catch {
14943
17915
  }
17916
+ return { status: "updated", version: newVersion };
14944
17917
  } catch (error) {
14945
17918
  if (info !== void 0) {
14946
17919
  try {
@@ -14975,10 +17948,9 @@ var init_update = __esm({
14975
17948
 
14976
17949
  // src/cli/commands/selfUpdate.ts
14977
17950
  import { execFileSync as execFileSync2 } from "child_process";
14978
- import os4 from "os";
14979
17951
  import path6 from "path";
14980
- function registerSelfUpdateCommands(program) {
14981
- const cmd = program.command("self-update").description("update the CLI to the latest npm-published version").option("--check-only", "check for updates without downloading").option("--force", "force update even if already up to date");
17952
+ function registerSelfUpdateCommands(program2) {
17953
+ const cmd = program2.command("self-update").description("update the CLI to the latest npm-published version").option("--check-only", "check for updates without installing").option("--force", "force update even if already up to date");
14982
17954
  addGlobalOptions(cmd).action(async (flags, command) => {
14983
17955
  await runSelfUpdate(flags, command);
14984
17956
  });
@@ -15027,61 +17999,45 @@ async function runSelfUpdate(flags, command) {
15027
17999
  }
15028
18000
  const oldVersion = VERSION;
15029
18001
  const newVersion = info.version;
15030
- const tarballBuffer = await downloadTarball(info.tarballUrl);
15031
- const tarballName = path6.basename(new URL(info.tarballUrl).pathname);
15032
- const install = installDir();
15033
- const stagingDir = path6.join(install, ".staging");
15034
18002
  if (ctx.dryRun) {
15035
18003
  printDryRunPlan({
15036
18004
  oldVersion,
15037
18005
  newVersion,
15038
- assetName: tarballName,
18006
+ assetName: path6.basename(new URL(info.tarballUrl).pathname),
15039
18007
  downloadUrl: info.tarballUrl,
15040
- install,
15041
- stagingDir,
15042
18008
  json: mode.json
15043
18009
  });
15044
18010
  return;
15045
18011
  }
15046
- errLine(paint.dim(`Downloading ${tarballName}...`));
15047
- errLine(paint.dim("Extracting to staging..."));
15048
- const tmpTarball = path6.join(os4.tmpdir(), `pingcode-cli-${newVersion}.tgz`);
18012
+ errLine(paint.dim(`Installing v${newVersion}...`));
15049
18013
  try {
15050
- writeBufferToFile(tmpTarball, tarballBuffer);
15051
- cleanStaging(stagingDir);
15052
- ensureDir(stagingDir);
15053
- extractTarball(tarballBuffer, stagingDir);
15054
- if (!validateStaging(stagingDir)) {
15055
- cleanStaging(stagingDir);
15056
- throw new TransportError(
15057
- "invalid tarball: dist/bin/pingcode.js not found"
15058
- );
15059
- }
15060
- errLine(paint.dim(`Installing v${newVersion}...`));
15061
- await atomicReplace(install, stagingDir);
15062
- const skillSource = path6.join(install, "skills", "pingcode");
15063
- if (dirExists(skillSource)) {
15064
- errLine(paint.dim("Syncing skills..."));
15065
- await syncSkills(skillSource, skillTargets());
15066
- }
15067
- errLine(paint.dim("Verifying..."));
15068
- const verified = verifyInstall(
15069
- install,
15070
- (file, args) => String(execFileSync2(file, args, { encoding: "utf8" }))
15071
- );
15072
- if (mode.json) {
15073
- printJson({
15074
- status: "updated",
15075
- previous_version: oldVersion,
15076
- new_version: verified
15077
- });
15078
- } else {
15079
- errLine(paint.green(`updated v${oldVersion} \u2192 v${verified}`));
18014
+ await installViaNpm(cliExec, newVersion);
18015
+ } catch (error) {
18016
+ if (!mode.json) {
18017
+ errLine(paint.red(`update failed: ${errorMessageOf(error)}`));
18018
+ const hint = error instanceof TransportError ? error.hint : void 0;
18019
+ if (hint !== void 0 && hint !== "") errLine(paint.dim(` ${hint}`));
15080
18020
  }
15081
- } finally {
15082
- removeFile(tmpTarball);
18021
+ throw error;
18022
+ }
18023
+ const skillSource = packageSkillDir();
18024
+ if (dirExists(skillSource)) {
18025
+ errLine(paint.dim("Syncing skills..."));
18026
+ await syncSkills(skillSource, skillTargets());
18027
+ }
18028
+ if (mode.json) {
18029
+ printJson({
18030
+ status: "updated",
18031
+ previous_version: oldVersion,
18032
+ new_version: newVersion
18033
+ });
18034
+ } else {
18035
+ errLine(paint.green(`updated v${oldVersion} \u2192 v${newVersion}`));
15083
18036
  }
15084
18037
  }
18038
+ function errorMessageOf(error) {
18039
+ return error instanceof Error ? error.message : String(error);
18040
+ }
15085
18041
  function printCheckResult(check, json) {
15086
18042
  if (json) {
15087
18043
  printJson({
@@ -15114,8 +18070,6 @@ function printDryRunPlan(plan) {
15114
18070
  target_version: plan.newVersion,
15115
18071
  asset: plan.assetName,
15116
18072
  download_url: plan.downloadUrl,
15117
- install_dir: plan.install,
15118
- staging_dir: plan.stagingDir,
15119
18073
  skill_targets: skillTargets().map((t) => t.dir)
15120
18074
  });
15121
18075
  return;
@@ -15124,10 +18078,9 @@ function printDryRunPlan(plan) {
15124
18078
  errLine(` current: v${plan.oldVersion}`);
15125
18079
  errLine(` target: v${plan.newVersion}`);
15126
18080
  errLine(` asset: ${plan.assetName}`);
15127
- errLine(` install: ${plan.install}`);
15128
- errLine(` staging: ${plan.stagingDir}`);
15129
18081
  errLine(` skills: ${skillTargets().map((t) => t.dir).join(", ")}`);
15130
18082
  }
18083
+ var cliExec;
15131
18084
  var init_selfUpdate = __esm({
15132
18085
  "src/cli/commands/selfUpdate.ts"() {
15133
18086
  "use strict";
@@ -15135,17 +18088,17 @@ var init_selfUpdate = __esm({
15135
18088
  init_update_check();
15136
18089
  init_update();
15137
18090
  init_errors();
15138
- init_update();
15139
18091
  init_common();
15140
18092
  init_output();
15141
18093
  init_globals();
15142
18094
  init_paths();
18095
+ cliExec = (file, args) => execFileSync2(file, args, { encoding: "utf8" });
15143
18096
  }
15144
18097
  });
15145
18098
 
15146
18099
  // src/cli/commands/settings.ts
15147
- function registerSettingsCommands(program) {
15148
- const settings = program.command("settings").description("\u540E\u53F0\u8BBE\u7F6E: organisation-wide directory data");
18100
+ function registerSettingsCommands(program2) {
18101
+ const settings = program2.command("settings").description("\u540E\u53F0\u8BBE\u7F6E: organisation-wide directory data");
15149
18102
  addGlobalOptions(
15150
18103
  addPagingOptions(
15151
18104
  settings.command("users").description("organisation members (scope pcp:read:global:team)").option("--keywords <text>", "fuzzy search over name and username")
@@ -15308,8 +18261,12 @@ var init_skill_ops = __esm({
15308
18261
  });
15309
18262
 
15310
18263
  // src/cli/commands/skill.ts
15311
- function registerSkillCommands(program) {
15312
- const skill = program.command("skill").description("manage the pingcode skill across agent targets");
18264
+ import path8 from "path";
18265
+ function packageSkillRoot() {
18266
+ return path8.dirname(path8.dirname(packageSkillDir()));
18267
+ }
18268
+ function registerSkillCommands(program2) {
18269
+ const skill = program2.command("skill").description("manage the pingcode skill across agent targets");
15313
18270
  skill.command("list").description("show where the skill is installed").action(async (flags) => {
15314
18271
  await runList18(flags);
15315
18272
  });
@@ -15370,7 +18327,7 @@ async function runInstall(flags) {
15370
18327
  const { ctx } = contextFor(command);
15371
18328
  const mode = modeOf(ctx);
15372
18329
  const targets = resolveTargets(flags);
15373
- const sourceRoot = installDir();
18330
+ const sourceRoot = packageSkillRoot();
15374
18331
  const results = installSkill(sourceRoot, targets, flags.force ?? false);
15375
18332
  renderResults(results, mode);
15376
18333
  }
@@ -15387,7 +18344,7 @@ async function runUpdate16(flags) {
15387
18344
  const { ctx } = contextFor(command);
15388
18345
  const mode = modeOf(ctx);
15389
18346
  const targets = resolveTargets(flags);
15390
- const sourceRoot = installDir();
18347
+ const sourceRoot = packageSkillRoot();
15391
18348
  const results = installSkill(sourceRoot, targets, true);
15392
18349
  renderResults(results, mode);
15393
18350
  }
@@ -15446,6 +18403,7 @@ var init_skill = __esm({
15446
18403
  "src/cli/commands/skill.ts"() {
15447
18404
  "use strict";
15448
18405
  init_paths();
18406
+ init_update();
15449
18407
  init_skill_ops();
15450
18408
  init_globals();
15451
18409
  init_output();
@@ -15923,11 +18881,11 @@ var init_libraries = __esm({
15923
18881
 
15924
18882
  // src/cli/commands/testhub/entries.ts
15925
18883
  async function readEntryFile(source, schema, hint) {
15926
- const path8 = source.file?.trim() ?? "";
15927
- if (path8 === "") {
18884
+ const path9 = source.file?.trim() ?? "";
18885
+ if (path9 === "") {
15928
18886
  throw new UsageError("--file <path|-> is required", { hint });
15929
18887
  }
15930
- const document = path8 === "-" ? await readJsonStdin() : parseJsonDocument(await readTextFile(path8, "--file"), `--file ${path8}`);
18888
+ const document = path9 === "-" ? await readJsonStdin() : parseJsonDocument(await readTextFile(path9, "--file"), `--file ${path9}`);
15931
18889
  const list = unwrap2(document, schema.wrapperKey);
15932
18890
  if (list.length === 0) {
15933
18891
  throw new UsageError("--file contained no entries", {
@@ -16750,7 +19708,6 @@ var init_cases = __esm({
16750
19708
  });
16751
19709
 
16752
19710
  // src/cli/commands/testhub/meta.ts
16753
- import { Option as Option2 } from "commander";
16754
19711
  function registerTesthubMetaCommands(parent) {
16755
19712
  const meta = parent.command("meta").description(
16756
19713
  "ids you need before writing: case states, types, importance levels, run results, plan types, plan states, case fields, modules"
@@ -16887,12 +19844,13 @@ function withComputedPaths(rows) {
16887
19844
  return rows.map((row) => ({ ...row, computed_path: walk(row) }));
16888
19845
  }
16889
19846
  function libraryTrap(flags) {
16890
- return new Option2(flags, "not accepted: importance levels are organisation-wide").hideHelp();
19847
+ return new Option(flags, "not accepted: importance levels are organisation-wide").hideHelp();
16891
19848
  }
16892
19849
  var CASE_STATE_COLUMNS, CASE_TYPE_COLUMNS, IMPORTANT_LEVEL_COLUMNS, RUN_STATUS_COLUMNS, PLAN_TYPE_COLUMNS, PLAN_STATE_COLUMNS, CASE_PROPERTY_COLUMNS, SUITE_COLUMNS;
16893
19850
  var init_meta2 = __esm({
16894
19851
  "src/cli/commands/testhub/meta.ts"() {
16895
19852
  "use strict";
19853
+ init_esm();
16896
19854
  init_testhub2();
16897
19855
  init_errors();
16898
19856
  init_metadata();
@@ -17947,8 +20905,8 @@ var init_runs = __esm({
17947
20905
  });
17948
20906
 
17949
20907
  // src/cli/commands/testhub/index.ts
17950
- function registerTesthubCommands(program) {
17951
- const testhub = program.command("testhub").description(
20908
+ function registerTesthubCommands(program2) {
20909
+ const testhub = program2.command("testhub").description(
17952
20910
  "\u6D4B\u8BD5\u7BA1\u7406 testhub: libraries \u6D4B\u8BD5\u5E93, cases \u7528\u4F8B, plans \u6D4B\u8BD5\u8BA1\u5212, runs \u6267\u884C\u7528\u4F8B (scopes pcp:read:testhub:testcase / :testplan / :configuration)"
17953
20911
  );
17954
20912
  registerLibraryCommands(testhub);
@@ -18008,22 +20966,22 @@ __export(program_exports, {
18008
20966
  HELP_WIDTH: () => HELP_WIDTH,
18009
20967
  buildProgram: () => buildProgram
18010
20968
  });
18011
- import { Command } from "commander";
18012
20969
  function buildProgram() {
18013
- const program = new Command();
18014
- program.name("pingcode").description("Command-line client for the PingCode Open API").version(VERSION, "--version", "output the CLI version").configureHelp({ helpWidth: HELP_WIDTH }).showHelpAfterError().allowExcessArguments(false).exitOverride();
18015
- addGlobalOptions(program);
18016
- program.addHelpText(
20970
+ const program2 = new Command();
20971
+ program2.name("pingcode").description("Command-line client for the PingCode Open API").version(VERSION, "--version", "output the CLI version").configureHelp({ helpWidth: HELP_WIDTH }).showHelpAfterError().allowExcessArguments(false).exitOverride();
20972
+ addGlobalOptions(program2);
20973
+ program2.addHelpText(
18017
20974
  "after",
18018
20975
  "\nGlobal flags may be given before or after the subcommand.\nAgents: prefer --json (stdout is JSON only) and run --dry-run before any write.\n"
18019
20976
  );
18020
- for (const [, register] of GROUPS) register(program);
18021
- return program;
20977
+ for (const [, register] of GROUPS) register(program2);
20978
+ return program2;
18022
20979
  }
18023
20980
  var HELP_WIDTH;
18024
20981
  var init_program = __esm({
18025
20982
  "src/cli/program.ts"() {
18026
20983
  "use strict";
20984
+ init_esm();
18027
20985
  init_version();
18028
20986
  init_globals();
18029
20987
  init_registry2();
@@ -18032,6 +20990,7 @@ var init_program = __esm({
18032
20990
  });
18033
20991
 
18034
20992
  // src/bin/pingcode.ts
20993
+ init_esm();
18035
20994
  init_output();
18036
20995
  init_program();
18037
20996
  init_errors();
@@ -18040,7 +20999,6 @@ init_update_check();
18040
20999
  init_update();
18041
21000
  init_version();
18042
21001
  import { spawn as spawn2 } from "child_process";
18043
- import { CommanderError } from "commander";
18044
21002
  function notifyUpdateCheck(jsonMode) {
18045
21003
  if (jsonMode) return;
18046
21004
  if (process.env[ENV_NO_UPDATE_CHECK] === "1") return;
@@ -18063,22 +21021,22 @@ function notifyUpdateCheck(jsonMode) {
18063
21021
  child.unref();
18064
21022
  }
18065
21023
  }
18066
- function detectJsonMode(program, argv) {
21024
+ function detectJsonMode(program2, argv) {
18067
21025
  try {
18068
- if (program.opts().json === true) return true;
21026
+ if (program2.opts().json === true) return true;
18069
21027
  } catch {
18070
21028
  }
18071
21029
  return argv.includes("--json");
18072
21030
  }
18073
21031
  async function main(argv) {
18074
- const program = buildProgram();
21032
+ const program2 = buildProgram();
18075
21033
  const jsonMode = argv.includes("--json");
18076
21034
  notifyUpdateCheck(jsonMode);
18077
21035
  try {
18078
- await program.parseAsync(argv);
21036
+ await program2.parseAsync(argv);
18079
21037
  return 0;
18080
21038
  } catch (error) {
18081
- const mode = { json: detectJsonMode(program, argv) };
21039
+ const mode = { json: detectJsonMode(program2, argv) };
18082
21040
  if (error instanceof DryRunHalt) {
18083
21041
  printDryRun(error.plan, mode);
18084
21042
  return 0;