@wirecat/drive-cli 0.44.0 → 0.45.1

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