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