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