reapp-protocol-cli 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +141 -0
- package/dist/reapp-cli.bundle.mjs +4340 -0
- package/package.json +40 -0
|
@@ -0,0 +1,4340 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import{createRequire as __cr}from'module';const require=__cr(import.meta.url);
|
|
3
|
+
var __create = Object.create;
|
|
4
|
+
var __defProp = Object.defineProperty;
|
|
5
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
6
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
7
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
8
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
9
|
+
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
|
|
10
|
+
get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
|
|
11
|
+
}) : x)(function(x) {
|
|
12
|
+
if (typeof require !== "undefined") return require.apply(this, arguments);
|
|
13
|
+
throw Error('Dynamic require of "' + x + '" is not supported');
|
|
14
|
+
});
|
|
15
|
+
var __commonJS = (cb, mod) => function __require2() {
|
|
16
|
+
try {
|
|
17
|
+
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
|
|
18
|
+
} catch (e) {
|
|
19
|
+
throw mod = 0, e;
|
|
20
|
+
}
|
|
21
|
+
};
|
|
22
|
+
var __export = (target, all) => {
|
|
23
|
+
for (var name in all)
|
|
24
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
25
|
+
};
|
|
26
|
+
var __copyProps = (to, from, except, desc) => {
|
|
27
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
28
|
+
for (let key of __getOwnPropNames(from))
|
|
29
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
30
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
31
|
+
}
|
|
32
|
+
return to;
|
|
33
|
+
};
|
|
34
|
+
var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
|
|
35
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
36
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
37
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
38
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
39
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
40
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
41
|
+
mod
|
|
42
|
+
));
|
|
43
|
+
|
|
44
|
+
// node_modules/commander/lib/error.js
|
|
45
|
+
var require_error = __commonJS({
|
|
46
|
+
"node_modules/commander/lib/error.js"(exports) {
|
|
47
|
+
var CommanderError2 = class extends Error {
|
|
48
|
+
/**
|
|
49
|
+
* Constructs the CommanderError class
|
|
50
|
+
* @param {number} exitCode suggested exit code which could be used with process.exit
|
|
51
|
+
* @param {string} code an id string representing the error
|
|
52
|
+
* @param {string} message human-readable description of the error
|
|
53
|
+
*/
|
|
54
|
+
constructor(exitCode, code, message) {
|
|
55
|
+
super(message);
|
|
56
|
+
Error.captureStackTrace(this, this.constructor);
|
|
57
|
+
this.name = this.constructor.name;
|
|
58
|
+
this.code = code;
|
|
59
|
+
this.exitCode = exitCode;
|
|
60
|
+
this.nestedError = void 0;
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
var InvalidArgumentError2 = class extends CommanderError2 {
|
|
64
|
+
/**
|
|
65
|
+
* Constructs the InvalidArgumentError class
|
|
66
|
+
* @param {string} [message] explanation of why argument is invalid
|
|
67
|
+
*/
|
|
68
|
+
constructor(message) {
|
|
69
|
+
super(1, "commander.invalidArgument", message);
|
|
70
|
+
Error.captureStackTrace(this, this.constructor);
|
|
71
|
+
this.name = this.constructor.name;
|
|
72
|
+
}
|
|
73
|
+
};
|
|
74
|
+
exports.CommanderError = CommanderError2;
|
|
75
|
+
exports.InvalidArgumentError = InvalidArgumentError2;
|
|
76
|
+
}
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
// node_modules/commander/lib/argument.js
|
|
80
|
+
var require_argument = __commonJS({
|
|
81
|
+
"node_modules/commander/lib/argument.js"(exports) {
|
|
82
|
+
var { InvalidArgumentError: InvalidArgumentError2 } = require_error();
|
|
83
|
+
var Argument2 = class {
|
|
84
|
+
/**
|
|
85
|
+
* Initialize a new command argument with the given name and description.
|
|
86
|
+
* The default is that the argument is required, and you can explicitly
|
|
87
|
+
* indicate this with <> around the name. Put [] around the name for an optional argument.
|
|
88
|
+
*
|
|
89
|
+
* @param {string} name
|
|
90
|
+
* @param {string} [description]
|
|
91
|
+
*/
|
|
92
|
+
constructor(name, description) {
|
|
93
|
+
this.description = description || "";
|
|
94
|
+
this.variadic = false;
|
|
95
|
+
this.parseArg = void 0;
|
|
96
|
+
this.defaultValue = void 0;
|
|
97
|
+
this.defaultValueDescription = void 0;
|
|
98
|
+
this.argChoices = void 0;
|
|
99
|
+
switch (name[0]) {
|
|
100
|
+
case "<":
|
|
101
|
+
this.required = true;
|
|
102
|
+
this._name = name.slice(1, -1);
|
|
103
|
+
break;
|
|
104
|
+
case "[":
|
|
105
|
+
this.required = false;
|
|
106
|
+
this._name = name.slice(1, -1);
|
|
107
|
+
break;
|
|
108
|
+
default:
|
|
109
|
+
this.required = true;
|
|
110
|
+
this._name = name;
|
|
111
|
+
break;
|
|
112
|
+
}
|
|
113
|
+
if (this._name.endsWith("...")) {
|
|
114
|
+
this.variadic = true;
|
|
115
|
+
this._name = this._name.slice(0, -3);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Return argument name.
|
|
120
|
+
*
|
|
121
|
+
* @return {string}
|
|
122
|
+
*/
|
|
123
|
+
name() {
|
|
124
|
+
return this._name;
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* @package
|
|
128
|
+
*/
|
|
129
|
+
_collectValue(value, previous) {
|
|
130
|
+
if (previous === this.defaultValue || !Array.isArray(previous)) {
|
|
131
|
+
return [value];
|
|
132
|
+
}
|
|
133
|
+
previous.push(value);
|
|
134
|
+
return previous;
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* Set the default value, and optionally supply the description to be displayed in the help.
|
|
138
|
+
*
|
|
139
|
+
* @param {*} value
|
|
140
|
+
* @param {string} [description]
|
|
141
|
+
* @return {Argument}
|
|
142
|
+
*/
|
|
143
|
+
default(value, description) {
|
|
144
|
+
this.defaultValue = value;
|
|
145
|
+
this.defaultValueDescription = description;
|
|
146
|
+
return this;
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* Set the custom handler for processing CLI command arguments into argument values.
|
|
150
|
+
*
|
|
151
|
+
* @param {Function} [fn]
|
|
152
|
+
* @return {Argument}
|
|
153
|
+
*/
|
|
154
|
+
argParser(fn) {
|
|
155
|
+
this.parseArg = fn;
|
|
156
|
+
return this;
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* Only allow argument value to be one of choices.
|
|
160
|
+
*
|
|
161
|
+
* @param {string[]} values
|
|
162
|
+
* @return {Argument}
|
|
163
|
+
*/
|
|
164
|
+
choices(values) {
|
|
165
|
+
this.argChoices = values.slice();
|
|
166
|
+
this.parseArg = (arg, previous) => {
|
|
167
|
+
if (!this.argChoices.includes(arg)) {
|
|
168
|
+
throw new InvalidArgumentError2(
|
|
169
|
+
`Allowed choices are ${this.argChoices.join(", ")}.`
|
|
170
|
+
);
|
|
171
|
+
}
|
|
172
|
+
if (this.variadic) {
|
|
173
|
+
return this._collectValue(arg, previous);
|
|
174
|
+
}
|
|
175
|
+
return arg;
|
|
176
|
+
};
|
|
177
|
+
return this;
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* Make argument required.
|
|
181
|
+
*
|
|
182
|
+
* @returns {Argument}
|
|
183
|
+
*/
|
|
184
|
+
argRequired() {
|
|
185
|
+
this.required = true;
|
|
186
|
+
return this;
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* Make argument optional.
|
|
190
|
+
*
|
|
191
|
+
* @returns {Argument}
|
|
192
|
+
*/
|
|
193
|
+
argOptional() {
|
|
194
|
+
this.required = false;
|
|
195
|
+
return this;
|
|
196
|
+
}
|
|
197
|
+
};
|
|
198
|
+
function humanReadableArgName(arg) {
|
|
199
|
+
const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
|
|
200
|
+
return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
|
|
201
|
+
}
|
|
202
|
+
exports.Argument = Argument2;
|
|
203
|
+
exports.humanReadableArgName = humanReadableArgName;
|
|
204
|
+
}
|
|
205
|
+
});
|
|
206
|
+
|
|
207
|
+
// node_modules/commander/lib/help.js
|
|
208
|
+
var require_help = __commonJS({
|
|
209
|
+
"node_modules/commander/lib/help.js"(exports) {
|
|
210
|
+
var { humanReadableArgName } = require_argument();
|
|
211
|
+
var Help2 = class {
|
|
212
|
+
constructor() {
|
|
213
|
+
this.helpWidth = void 0;
|
|
214
|
+
this.minWidthToWrap = 40;
|
|
215
|
+
this.sortSubcommands = false;
|
|
216
|
+
this.sortOptions = false;
|
|
217
|
+
this.showGlobalOptions = false;
|
|
218
|
+
}
|
|
219
|
+
/**
|
|
220
|
+
* prepareContext is called by Commander after applying overrides from `Command.configureHelp()`
|
|
221
|
+
* and just before calling `formatHelp()`.
|
|
222
|
+
*
|
|
223
|
+
* Commander just uses the helpWidth and the rest is provided for optional use by more complex subclasses.
|
|
224
|
+
*
|
|
225
|
+
* @param {{ error?: boolean, helpWidth?: number, outputHasColors?: boolean }} contextOptions
|
|
226
|
+
*/
|
|
227
|
+
prepareContext(contextOptions) {
|
|
228
|
+
this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;
|
|
229
|
+
}
|
|
230
|
+
/**
|
|
231
|
+
* Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
|
|
232
|
+
*
|
|
233
|
+
* @param {Command} cmd
|
|
234
|
+
* @returns {Command[]}
|
|
235
|
+
*/
|
|
236
|
+
visibleCommands(cmd) {
|
|
237
|
+
const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
|
|
238
|
+
const helpCommand = cmd._getHelpCommand();
|
|
239
|
+
if (helpCommand && !helpCommand._hidden) {
|
|
240
|
+
visibleCommands.push(helpCommand);
|
|
241
|
+
}
|
|
242
|
+
if (this.sortSubcommands) {
|
|
243
|
+
visibleCommands.sort((a, b) => {
|
|
244
|
+
return a.name().localeCompare(b.name());
|
|
245
|
+
});
|
|
246
|
+
}
|
|
247
|
+
return visibleCommands;
|
|
248
|
+
}
|
|
249
|
+
/**
|
|
250
|
+
* Compare options for sort.
|
|
251
|
+
*
|
|
252
|
+
* @param {Option} a
|
|
253
|
+
* @param {Option} b
|
|
254
|
+
* @returns {number}
|
|
255
|
+
*/
|
|
256
|
+
compareOptions(a, b) {
|
|
257
|
+
const getSortKey = (option) => {
|
|
258
|
+
return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
|
|
259
|
+
};
|
|
260
|
+
return getSortKey(a).localeCompare(getSortKey(b));
|
|
261
|
+
}
|
|
262
|
+
/**
|
|
263
|
+
* Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
|
|
264
|
+
*
|
|
265
|
+
* @param {Command} cmd
|
|
266
|
+
* @returns {Option[]}
|
|
267
|
+
*/
|
|
268
|
+
visibleOptions(cmd) {
|
|
269
|
+
const visibleOptions = cmd.options.filter((option) => !option.hidden);
|
|
270
|
+
const helpOption = cmd._getHelpOption();
|
|
271
|
+
if (helpOption && !helpOption.hidden) {
|
|
272
|
+
const removeShort = helpOption.short && cmd._findOption(helpOption.short);
|
|
273
|
+
const removeLong = helpOption.long && cmd._findOption(helpOption.long);
|
|
274
|
+
if (!removeShort && !removeLong) {
|
|
275
|
+
visibleOptions.push(helpOption);
|
|
276
|
+
} else if (helpOption.long && !removeLong) {
|
|
277
|
+
visibleOptions.push(
|
|
278
|
+
cmd.createOption(helpOption.long, helpOption.description)
|
|
279
|
+
);
|
|
280
|
+
} else if (helpOption.short && !removeShort) {
|
|
281
|
+
visibleOptions.push(
|
|
282
|
+
cmd.createOption(helpOption.short, helpOption.description)
|
|
283
|
+
);
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
if (this.sortOptions) {
|
|
287
|
+
visibleOptions.sort(this.compareOptions);
|
|
288
|
+
}
|
|
289
|
+
return visibleOptions;
|
|
290
|
+
}
|
|
291
|
+
/**
|
|
292
|
+
* Get an array of the visible global options. (Not including help.)
|
|
293
|
+
*
|
|
294
|
+
* @param {Command} cmd
|
|
295
|
+
* @returns {Option[]}
|
|
296
|
+
*/
|
|
297
|
+
visibleGlobalOptions(cmd) {
|
|
298
|
+
if (!this.showGlobalOptions) return [];
|
|
299
|
+
const globalOptions = [];
|
|
300
|
+
for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
|
|
301
|
+
const visibleOptions = ancestorCmd.options.filter(
|
|
302
|
+
(option) => !option.hidden
|
|
303
|
+
);
|
|
304
|
+
globalOptions.push(...visibleOptions);
|
|
305
|
+
}
|
|
306
|
+
if (this.sortOptions) {
|
|
307
|
+
globalOptions.sort(this.compareOptions);
|
|
308
|
+
}
|
|
309
|
+
return globalOptions;
|
|
310
|
+
}
|
|
311
|
+
/**
|
|
312
|
+
* Get an array of the arguments if any have a description.
|
|
313
|
+
*
|
|
314
|
+
* @param {Command} cmd
|
|
315
|
+
* @returns {Argument[]}
|
|
316
|
+
*/
|
|
317
|
+
visibleArguments(cmd) {
|
|
318
|
+
if (cmd._argsDescription) {
|
|
319
|
+
cmd.registeredArguments.forEach((argument) => {
|
|
320
|
+
argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
|
|
321
|
+
});
|
|
322
|
+
}
|
|
323
|
+
if (cmd.registeredArguments.find((argument) => argument.description)) {
|
|
324
|
+
return cmd.registeredArguments;
|
|
325
|
+
}
|
|
326
|
+
return [];
|
|
327
|
+
}
|
|
328
|
+
/**
|
|
329
|
+
* Get the command term to show in the list of subcommands.
|
|
330
|
+
*
|
|
331
|
+
* @param {Command} cmd
|
|
332
|
+
* @returns {string}
|
|
333
|
+
*/
|
|
334
|
+
subcommandTerm(cmd) {
|
|
335
|
+
const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
|
|
336
|
+
return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + // simplistic check for non-help option
|
|
337
|
+
(args ? " " + args : "");
|
|
338
|
+
}
|
|
339
|
+
/**
|
|
340
|
+
* Get the option term to show in the list of options.
|
|
341
|
+
*
|
|
342
|
+
* @param {Option} option
|
|
343
|
+
* @returns {string}
|
|
344
|
+
*/
|
|
345
|
+
optionTerm(option) {
|
|
346
|
+
return option.flags;
|
|
347
|
+
}
|
|
348
|
+
/**
|
|
349
|
+
* Get the argument term to show in the list of arguments.
|
|
350
|
+
*
|
|
351
|
+
* @param {Argument} argument
|
|
352
|
+
* @returns {string}
|
|
353
|
+
*/
|
|
354
|
+
argumentTerm(argument) {
|
|
355
|
+
return argument.name();
|
|
356
|
+
}
|
|
357
|
+
/**
|
|
358
|
+
* Get the longest command term length.
|
|
359
|
+
*
|
|
360
|
+
* @param {Command} cmd
|
|
361
|
+
* @param {Help} helper
|
|
362
|
+
* @returns {number}
|
|
363
|
+
*/
|
|
364
|
+
longestSubcommandTermLength(cmd, helper) {
|
|
365
|
+
return helper.visibleCommands(cmd).reduce((max, command) => {
|
|
366
|
+
return Math.max(
|
|
367
|
+
max,
|
|
368
|
+
this.displayWidth(
|
|
369
|
+
helper.styleSubcommandTerm(helper.subcommandTerm(command))
|
|
370
|
+
)
|
|
371
|
+
);
|
|
372
|
+
}, 0);
|
|
373
|
+
}
|
|
374
|
+
/**
|
|
375
|
+
* Get the longest option term length.
|
|
376
|
+
*
|
|
377
|
+
* @param {Command} cmd
|
|
378
|
+
* @param {Help} helper
|
|
379
|
+
* @returns {number}
|
|
380
|
+
*/
|
|
381
|
+
longestOptionTermLength(cmd, helper) {
|
|
382
|
+
return helper.visibleOptions(cmd).reduce((max, option) => {
|
|
383
|
+
return Math.max(
|
|
384
|
+
max,
|
|
385
|
+
this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option)))
|
|
386
|
+
);
|
|
387
|
+
}, 0);
|
|
388
|
+
}
|
|
389
|
+
/**
|
|
390
|
+
* Get the longest global option term length.
|
|
391
|
+
*
|
|
392
|
+
* @param {Command} cmd
|
|
393
|
+
* @param {Help} helper
|
|
394
|
+
* @returns {number}
|
|
395
|
+
*/
|
|
396
|
+
longestGlobalOptionTermLength(cmd, helper) {
|
|
397
|
+
return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
|
|
398
|
+
return Math.max(
|
|
399
|
+
max,
|
|
400
|
+
this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option)))
|
|
401
|
+
);
|
|
402
|
+
}, 0);
|
|
403
|
+
}
|
|
404
|
+
/**
|
|
405
|
+
* Get the longest argument term length.
|
|
406
|
+
*
|
|
407
|
+
* @param {Command} cmd
|
|
408
|
+
* @param {Help} helper
|
|
409
|
+
* @returns {number}
|
|
410
|
+
*/
|
|
411
|
+
longestArgumentTermLength(cmd, helper) {
|
|
412
|
+
return helper.visibleArguments(cmd).reduce((max, argument) => {
|
|
413
|
+
return Math.max(
|
|
414
|
+
max,
|
|
415
|
+
this.displayWidth(
|
|
416
|
+
helper.styleArgumentTerm(helper.argumentTerm(argument))
|
|
417
|
+
)
|
|
418
|
+
);
|
|
419
|
+
}, 0);
|
|
420
|
+
}
|
|
421
|
+
/**
|
|
422
|
+
* Get the command usage to be displayed at the top of the built-in help.
|
|
423
|
+
*
|
|
424
|
+
* @param {Command} cmd
|
|
425
|
+
* @returns {string}
|
|
426
|
+
*/
|
|
427
|
+
commandUsage(cmd) {
|
|
428
|
+
let cmdName = cmd._name;
|
|
429
|
+
if (cmd._aliases[0]) {
|
|
430
|
+
cmdName = cmdName + "|" + cmd._aliases[0];
|
|
431
|
+
}
|
|
432
|
+
let ancestorCmdNames = "";
|
|
433
|
+
for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
|
|
434
|
+
ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
|
|
435
|
+
}
|
|
436
|
+
return ancestorCmdNames + cmdName + " " + cmd.usage();
|
|
437
|
+
}
|
|
438
|
+
/**
|
|
439
|
+
* Get the description for the command.
|
|
440
|
+
*
|
|
441
|
+
* @param {Command} cmd
|
|
442
|
+
* @returns {string}
|
|
443
|
+
*/
|
|
444
|
+
commandDescription(cmd) {
|
|
445
|
+
return cmd.description();
|
|
446
|
+
}
|
|
447
|
+
/**
|
|
448
|
+
* Get the subcommand summary to show in the list of subcommands.
|
|
449
|
+
* (Fallback to description for backwards compatibility.)
|
|
450
|
+
*
|
|
451
|
+
* @param {Command} cmd
|
|
452
|
+
* @returns {string}
|
|
453
|
+
*/
|
|
454
|
+
subcommandDescription(cmd) {
|
|
455
|
+
return cmd.summary() || cmd.description();
|
|
456
|
+
}
|
|
457
|
+
/**
|
|
458
|
+
* Get the option description to show in the list of options.
|
|
459
|
+
*
|
|
460
|
+
* @param {Option} option
|
|
461
|
+
* @return {string}
|
|
462
|
+
*/
|
|
463
|
+
optionDescription(option) {
|
|
464
|
+
const extraInfo = [];
|
|
465
|
+
if (option.argChoices) {
|
|
466
|
+
extraInfo.push(
|
|
467
|
+
// use stringify to match the display of the default value
|
|
468
|
+
`choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
|
|
469
|
+
);
|
|
470
|
+
}
|
|
471
|
+
if (option.defaultValue !== void 0) {
|
|
472
|
+
const showDefault = option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean";
|
|
473
|
+
if (showDefault) {
|
|
474
|
+
extraInfo.push(
|
|
475
|
+
`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`
|
|
476
|
+
);
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
if (option.presetArg !== void 0 && option.optional) {
|
|
480
|
+
extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
|
|
481
|
+
}
|
|
482
|
+
if (option.envVar !== void 0) {
|
|
483
|
+
extraInfo.push(`env: ${option.envVar}`);
|
|
484
|
+
}
|
|
485
|
+
if (extraInfo.length > 0) {
|
|
486
|
+
const extraDescription = `(${extraInfo.join(", ")})`;
|
|
487
|
+
if (option.description) {
|
|
488
|
+
return `${option.description} ${extraDescription}`;
|
|
489
|
+
}
|
|
490
|
+
return extraDescription;
|
|
491
|
+
}
|
|
492
|
+
return option.description;
|
|
493
|
+
}
|
|
494
|
+
/**
|
|
495
|
+
* Get the argument description to show in the list of arguments.
|
|
496
|
+
*
|
|
497
|
+
* @param {Argument} argument
|
|
498
|
+
* @return {string}
|
|
499
|
+
*/
|
|
500
|
+
argumentDescription(argument) {
|
|
501
|
+
const extraInfo = [];
|
|
502
|
+
if (argument.argChoices) {
|
|
503
|
+
extraInfo.push(
|
|
504
|
+
// use stringify to match the display of the default value
|
|
505
|
+
`choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
|
|
506
|
+
);
|
|
507
|
+
}
|
|
508
|
+
if (argument.defaultValue !== void 0) {
|
|
509
|
+
extraInfo.push(
|
|
510
|
+
`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`
|
|
511
|
+
);
|
|
512
|
+
}
|
|
513
|
+
if (extraInfo.length > 0) {
|
|
514
|
+
const extraDescription = `(${extraInfo.join(", ")})`;
|
|
515
|
+
if (argument.description) {
|
|
516
|
+
return `${argument.description} ${extraDescription}`;
|
|
517
|
+
}
|
|
518
|
+
return extraDescription;
|
|
519
|
+
}
|
|
520
|
+
return argument.description;
|
|
521
|
+
}
|
|
522
|
+
/**
|
|
523
|
+
* Format a list of items, given a heading and an array of formatted items.
|
|
524
|
+
*
|
|
525
|
+
* @param {string} heading
|
|
526
|
+
* @param {string[]} items
|
|
527
|
+
* @param {Help} helper
|
|
528
|
+
* @returns string[]
|
|
529
|
+
*/
|
|
530
|
+
formatItemList(heading, items, helper) {
|
|
531
|
+
if (items.length === 0) return [];
|
|
532
|
+
return [helper.styleTitle(heading), ...items, ""];
|
|
533
|
+
}
|
|
534
|
+
/**
|
|
535
|
+
* Group items by their help group heading.
|
|
536
|
+
*
|
|
537
|
+
* @param {Command[] | Option[]} unsortedItems
|
|
538
|
+
* @param {Command[] | Option[]} visibleItems
|
|
539
|
+
* @param {Function} getGroup
|
|
540
|
+
* @returns {Map<string, Command[] | Option[]>}
|
|
541
|
+
*/
|
|
542
|
+
groupItems(unsortedItems, visibleItems, getGroup) {
|
|
543
|
+
const result = /* @__PURE__ */ new Map();
|
|
544
|
+
unsortedItems.forEach((item) => {
|
|
545
|
+
const group = getGroup(item);
|
|
546
|
+
if (!result.has(group)) result.set(group, []);
|
|
547
|
+
});
|
|
548
|
+
visibleItems.forEach((item) => {
|
|
549
|
+
const group = getGroup(item);
|
|
550
|
+
if (!result.has(group)) {
|
|
551
|
+
result.set(group, []);
|
|
552
|
+
}
|
|
553
|
+
result.get(group).push(item);
|
|
554
|
+
});
|
|
555
|
+
return result;
|
|
556
|
+
}
|
|
557
|
+
/**
|
|
558
|
+
* Generate the built-in help text.
|
|
559
|
+
*
|
|
560
|
+
* @param {Command} cmd
|
|
561
|
+
* @param {Help} helper
|
|
562
|
+
* @returns {string}
|
|
563
|
+
*/
|
|
564
|
+
formatHelp(cmd, helper) {
|
|
565
|
+
const termWidth = helper.padWidth(cmd, helper);
|
|
566
|
+
const helpWidth = helper.helpWidth ?? 80;
|
|
567
|
+
function callFormatItem(term, description) {
|
|
568
|
+
return helper.formatItem(term, termWidth, description, helper);
|
|
569
|
+
}
|
|
570
|
+
let output = [
|
|
571
|
+
`${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`,
|
|
572
|
+
""
|
|
573
|
+
];
|
|
574
|
+
const commandDescription = helper.commandDescription(cmd);
|
|
575
|
+
if (commandDescription.length > 0) {
|
|
576
|
+
output = output.concat([
|
|
577
|
+
helper.boxWrap(
|
|
578
|
+
helper.styleCommandDescription(commandDescription),
|
|
579
|
+
helpWidth
|
|
580
|
+
),
|
|
581
|
+
""
|
|
582
|
+
]);
|
|
583
|
+
}
|
|
584
|
+
const argumentList = helper.visibleArguments(cmd).map((argument) => {
|
|
585
|
+
return callFormatItem(
|
|
586
|
+
helper.styleArgumentTerm(helper.argumentTerm(argument)),
|
|
587
|
+
helper.styleArgumentDescription(helper.argumentDescription(argument))
|
|
588
|
+
);
|
|
589
|
+
});
|
|
590
|
+
output = output.concat(
|
|
591
|
+
this.formatItemList("Arguments:", argumentList, helper)
|
|
592
|
+
);
|
|
593
|
+
const optionGroups = this.groupItems(
|
|
594
|
+
cmd.options,
|
|
595
|
+
helper.visibleOptions(cmd),
|
|
596
|
+
(option) => option.helpGroupHeading ?? "Options:"
|
|
597
|
+
);
|
|
598
|
+
optionGroups.forEach((options, group) => {
|
|
599
|
+
const optionList = options.map((option) => {
|
|
600
|
+
return callFormatItem(
|
|
601
|
+
helper.styleOptionTerm(helper.optionTerm(option)),
|
|
602
|
+
helper.styleOptionDescription(helper.optionDescription(option))
|
|
603
|
+
);
|
|
604
|
+
});
|
|
605
|
+
output = output.concat(this.formatItemList(group, optionList, helper));
|
|
606
|
+
});
|
|
607
|
+
if (helper.showGlobalOptions) {
|
|
608
|
+
const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
|
|
609
|
+
return callFormatItem(
|
|
610
|
+
helper.styleOptionTerm(helper.optionTerm(option)),
|
|
611
|
+
helper.styleOptionDescription(helper.optionDescription(option))
|
|
612
|
+
);
|
|
613
|
+
});
|
|
614
|
+
output = output.concat(
|
|
615
|
+
this.formatItemList("Global Options:", globalOptionList, helper)
|
|
616
|
+
);
|
|
617
|
+
}
|
|
618
|
+
const commandGroups = this.groupItems(
|
|
619
|
+
cmd.commands,
|
|
620
|
+
helper.visibleCommands(cmd),
|
|
621
|
+
(sub) => sub.helpGroup() || "Commands:"
|
|
622
|
+
);
|
|
623
|
+
commandGroups.forEach((commands, group) => {
|
|
624
|
+
const commandList = commands.map((sub) => {
|
|
625
|
+
return callFormatItem(
|
|
626
|
+
helper.styleSubcommandTerm(helper.subcommandTerm(sub)),
|
|
627
|
+
helper.styleSubcommandDescription(helper.subcommandDescription(sub))
|
|
628
|
+
);
|
|
629
|
+
});
|
|
630
|
+
output = output.concat(this.formatItemList(group, commandList, helper));
|
|
631
|
+
});
|
|
632
|
+
return output.join("\n");
|
|
633
|
+
}
|
|
634
|
+
/**
|
|
635
|
+
* Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations.
|
|
636
|
+
*
|
|
637
|
+
* @param {string} str
|
|
638
|
+
* @returns {number}
|
|
639
|
+
*/
|
|
640
|
+
displayWidth(str) {
|
|
641
|
+
return stripColor(str).length;
|
|
642
|
+
}
|
|
643
|
+
/**
|
|
644
|
+
* Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc.
|
|
645
|
+
*
|
|
646
|
+
* @param {string} str
|
|
647
|
+
* @returns {string}
|
|
648
|
+
*/
|
|
649
|
+
styleTitle(str) {
|
|
650
|
+
return str;
|
|
651
|
+
}
|
|
652
|
+
styleUsage(str) {
|
|
653
|
+
return str.split(" ").map((word) => {
|
|
654
|
+
if (word === "[options]") return this.styleOptionText(word);
|
|
655
|
+
if (word === "[command]") return this.styleSubcommandText(word);
|
|
656
|
+
if (word[0] === "[" || word[0] === "<")
|
|
657
|
+
return this.styleArgumentText(word);
|
|
658
|
+
return this.styleCommandText(word);
|
|
659
|
+
}).join(" ");
|
|
660
|
+
}
|
|
661
|
+
styleCommandDescription(str) {
|
|
662
|
+
return this.styleDescriptionText(str);
|
|
663
|
+
}
|
|
664
|
+
styleOptionDescription(str) {
|
|
665
|
+
return this.styleDescriptionText(str);
|
|
666
|
+
}
|
|
667
|
+
styleSubcommandDescription(str) {
|
|
668
|
+
return this.styleDescriptionText(str);
|
|
669
|
+
}
|
|
670
|
+
styleArgumentDescription(str) {
|
|
671
|
+
return this.styleDescriptionText(str);
|
|
672
|
+
}
|
|
673
|
+
styleDescriptionText(str) {
|
|
674
|
+
return str;
|
|
675
|
+
}
|
|
676
|
+
styleOptionTerm(str) {
|
|
677
|
+
return this.styleOptionText(str);
|
|
678
|
+
}
|
|
679
|
+
styleSubcommandTerm(str) {
|
|
680
|
+
return str.split(" ").map((word) => {
|
|
681
|
+
if (word === "[options]") return this.styleOptionText(word);
|
|
682
|
+
if (word[0] === "[" || word[0] === "<")
|
|
683
|
+
return this.styleArgumentText(word);
|
|
684
|
+
return this.styleSubcommandText(word);
|
|
685
|
+
}).join(" ");
|
|
686
|
+
}
|
|
687
|
+
styleArgumentTerm(str) {
|
|
688
|
+
return this.styleArgumentText(str);
|
|
689
|
+
}
|
|
690
|
+
styleOptionText(str) {
|
|
691
|
+
return str;
|
|
692
|
+
}
|
|
693
|
+
styleArgumentText(str) {
|
|
694
|
+
return str;
|
|
695
|
+
}
|
|
696
|
+
styleSubcommandText(str) {
|
|
697
|
+
return str;
|
|
698
|
+
}
|
|
699
|
+
styleCommandText(str) {
|
|
700
|
+
return str;
|
|
701
|
+
}
|
|
702
|
+
/**
|
|
703
|
+
* Calculate the pad width from the maximum term length.
|
|
704
|
+
*
|
|
705
|
+
* @param {Command} cmd
|
|
706
|
+
* @param {Help} helper
|
|
707
|
+
* @returns {number}
|
|
708
|
+
*/
|
|
709
|
+
padWidth(cmd, helper) {
|
|
710
|
+
return Math.max(
|
|
711
|
+
helper.longestOptionTermLength(cmd, helper),
|
|
712
|
+
helper.longestGlobalOptionTermLength(cmd, helper),
|
|
713
|
+
helper.longestSubcommandTermLength(cmd, helper),
|
|
714
|
+
helper.longestArgumentTermLength(cmd, helper)
|
|
715
|
+
);
|
|
716
|
+
}
|
|
717
|
+
/**
|
|
718
|
+
* Detect manually wrapped and indented strings by checking for line break followed by whitespace.
|
|
719
|
+
*
|
|
720
|
+
* @param {string} str
|
|
721
|
+
* @returns {boolean}
|
|
722
|
+
*/
|
|
723
|
+
preformatted(str) {
|
|
724
|
+
return /\n[^\S\r\n]/.test(str);
|
|
725
|
+
}
|
|
726
|
+
/**
|
|
727
|
+
* Format the "item", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.
|
|
728
|
+
*
|
|
729
|
+
* So "TTT", 5, "DDD DDDD DD DDD" might be formatted for this.helpWidth=17 like so:
|
|
730
|
+
* TTT DDD DDDD
|
|
731
|
+
* DD DDD
|
|
732
|
+
*
|
|
733
|
+
* @param {string} term
|
|
734
|
+
* @param {number} termWidth
|
|
735
|
+
* @param {string} description
|
|
736
|
+
* @param {Help} helper
|
|
737
|
+
* @returns {string}
|
|
738
|
+
*/
|
|
739
|
+
formatItem(term, termWidth, description, helper) {
|
|
740
|
+
const itemIndent = 2;
|
|
741
|
+
const itemIndentStr = " ".repeat(itemIndent);
|
|
742
|
+
if (!description) return itemIndentStr + term;
|
|
743
|
+
const paddedTerm = term.padEnd(
|
|
744
|
+
termWidth + term.length - helper.displayWidth(term)
|
|
745
|
+
);
|
|
746
|
+
const spacerWidth = 2;
|
|
747
|
+
const helpWidth = this.helpWidth ?? 80;
|
|
748
|
+
const remainingWidth = helpWidth - termWidth - spacerWidth - itemIndent;
|
|
749
|
+
let formattedDescription;
|
|
750
|
+
if (remainingWidth < this.minWidthToWrap || helper.preformatted(description)) {
|
|
751
|
+
formattedDescription = description;
|
|
752
|
+
} else {
|
|
753
|
+
const wrappedDescription = helper.boxWrap(description, remainingWidth);
|
|
754
|
+
formattedDescription = wrappedDescription.replace(
|
|
755
|
+
/\n/g,
|
|
756
|
+
"\n" + " ".repeat(termWidth + spacerWidth)
|
|
757
|
+
);
|
|
758
|
+
}
|
|
759
|
+
return itemIndentStr + paddedTerm + " ".repeat(spacerWidth) + formattedDescription.replace(/\n/g, `
|
|
760
|
+
${itemIndentStr}`);
|
|
761
|
+
}
|
|
762
|
+
/**
|
|
763
|
+
* Wrap a string at whitespace, preserving existing line breaks.
|
|
764
|
+
* Wrapping is skipped if the width is less than `minWidthToWrap`.
|
|
765
|
+
*
|
|
766
|
+
* @param {string} str
|
|
767
|
+
* @param {number} width
|
|
768
|
+
* @returns {string}
|
|
769
|
+
*/
|
|
770
|
+
boxWrap(str, width) {
|
|
771
|
+
if (width < this.minWidthToWrap) return str;
|
|
772
|
+
const rawLines = str.split(/\r\n|\n/);
|
|
773
|
+
const chunkPattern = /[\s]*[^\s]+/g;
|
|
774
|
+
const wrappedLines = [];
|
|
775
|
+
rawLines.forEach((line2) => {
|
|
776
|
+
const chunks = line2.match(chunkPattern);
|
|
777
|
+
if (chunks === null) {
|
|
778
|
+
wrappedLines.push("");
|
|
779
|
+
return;
|
|
780
|
+
}
|
|
781
|
+
let sumChunks = [chunks.shift()];
|
|
782
|
+
let sumWidth = this.displayWidth(sumChunks[0]);
|
|
783
|
+
chunks.forEach((chunk) => {
|
|
784
|
+
const visibleWidth = this.displayWidth(chunk);
|
|
785
|
+
if (sumWidth + visibleWidth <= width) {
|
|
786
|
+
sumChunks.push(chunk);
|
|
787
|
+
sumWidth += visibleWidth;
|
|
788
|
+
return;
|
|
789
|
+
}
|
|
790
|
+
wrappedLines.push(sumChunks.join(""));
|
|
791
|
+
const nextChunk = chunk.trimStart();
|
|
792
|
+
sumChunks = [nextChunk];
|
|
793
|
+
sumWidth = this.displayWidth(nextChunk);
|
|
794
|
+
});
|
|
795
|
+
wrappedLines.push(sumChunks.join(""));
|
|
796
|
+
});
|
|
797
|
+
return wrappedLines.join("\n");
|
|
798
|
+
}
|
|
799
|
+
};
|
|
800
|
+
function stripColor(str) {
|
|
801
|
+
const sgrPattern = /\x1b\[\d*(;\d*)*m/g;
|
|
802
|
+
return str.replace(sgrPattern, "");
|
|
803
|
+
}
|
|
804
|
+
exports.Help = Help2;
|
|
805
|
+
exports.stripColor = stripColor;
|
|
806
|
+
}
|
|
807
|
+
});
|
|
808
|
+
|
|
809
|
+
// node_modules/commander/lib/option.js
|
|
810
|
+
var require_option = __commonJS({
|
|
811
|
+
"node_modules/commander/lib/option.js"(exports) {
|
|
812
|
+
var { InvalidArgumentError: InvalidArgumentError2 } = require_error();
|
|
813
|
+
var Option2 = class {
|
|
814
|
+
/**
|
|
815
|
+
* Initialize a new `Option` with the given `flags` and `description`.
|
|
816
|
+
*
|
|
817
|
+
* @param {string} flags
|
|
818
|
+
* @param {string} [description]
|
|
819
|
+
*/
|
|
820
|
+
constructor(flags, description) {
|
|
821
|
+
this.flags = flags;
|
|
822
|
+
this.description = description || "";
|
|
823
|
+
this.required = flags.includes("<");
|
|
824
|
+
this.optional = flags.includes("[");
|
|
825
|
+
this.variadic = /\w\.\.\.[>\]]$/.test(flags);
|
|
826
|
+
this.mandatory = false;
|
|
827
|
+
const optionFlags = splitOptionFlags(flags);
|
|
828
|
+
this.short = optionFlags.shortFlag;
|
|
829
|
+
this.long = optionFlags.longFlag;
|
|
830
|
+
this.negate = false;
|
|
831
|
+
if (this.long) {
|
|
832
|
+
this.negate = this.long.startsWith("--no-");
|
|
833
|
+
}
|
|
834
|
+
this.defaultValue = void 0;
|
|
835
|
+
this.defaultValueDescription = void 0;
|
|
836
|
+
this.presetArg = void 0;
|
|
837
|
+
this.envVar = void 0;
|
|
838
|
+
this.parseArg = void 0;
|
|
839
|
+
this.hidden = false;
|
|
840
|
+
this.argChoices = void 0;
|
|
841
|
+
this.conflictsWith = [];
|
|
842
|
+
this.implied = void 0;
|
|
843
|
+
this.helpGroupHeading = void 0;
|
|
844
|
+
}
|
|
845
|
+
/**
|
|
846
|
+
* Set the default value, and optionally supply the description to be displayed in the help.
|
|
847
|
+
*
|
|
848
|
+
* @param {*} value
|
|
849
|
+
* @param {string} [description]
|
|
850
|
+
* @return {Option}
|
|
851
|
+
*/
|
|
852
|
+
default(value, description) {
|
|
853
|
+
this.defaultValue = value;
|
|
854
|
+
this.defaultValueDescription = description;
|
|
855
|
+
return this;
|
|
856
|
+
}
|
|
857
|
+
/**
|
|
858
|
+
* Preset to use when option used without option-argument, especially optional but also boolean and negated.
|
|
859
|
+
* The custom processing (parseArg) is called.
|
|
860
|
+
*
|
|
861
|
+
* @example
|
|
862
|
+
* new Option('--color').default('GREYSCALE').preset('RGB');
|
|
863
|
+
* new Option('--donate [amount]').preset('20').argParser(parseFloat);
|
|
864
|
+
*
|
|
865
|
+
* @param {*} arg
|
|
866
|
+
* @return {Option}
|
|
867
|
+
*/
|
|
868
|
+
preset(arg) {
|
|
869
|
+
this.presetArg = arg;
|
|
870
|
+
return this;
|
|
871
|
+
}
|
|
872
|
+
/**
|
|
873
|
+
* Add option name(s) that conflict with this option.
|
|
874
|
+
* An error will be displayed if conflicting options are found during parsing.
|
|
875
|
+
*
|
|
876
|
+
* @example
|
|
877
|
+
* new Option('--rgb').conflicts('cmyk');
|
|
878
|
+
* new Option('--js').conflicts(['ts', 'jsx']);
|
|
879
|
+
*
|
|
880
|
+
* @param {(string | string[])} names
|
|
881
|
+
* @return {Option}
|
|
882
|
+
*/
|
|
883
|
+
conflicts(names) {
|
|
884
|
+
this.conflictsWith = this.conflictsWith.concat(names);
|
|
885
|
+
return this;
|
|
886
|
+
}
|
|
887
|
+
/**
|
|
888
|
+
* Specify implied option values for when this option is set and the implied options are not.
|
|
889
|
+
*
|
|
890
|
+
* The custom processing (parseArg) is not called on the implied values.
|
|
891
|
+
*
|
|
892
|
+
* @example
|
|
893
|
+
* program
|
|
894
|
+
* .addOption(new Option('--log', 'write logging information to file'))
|
|
895
|
+
* .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
|
|
896
|
+
*
|
|
897
|
+
* @param {object} impliedOptionValues
|
|
898
|
+
* @return {Option}
|
|
899
|
+
*/
|
|
900
|
+
implies(impliedOptionValues) {
|
|
901
|
+
let newImplied = impliedOptionValues;
|
|
902
|
+
if (typeof impliedOptionValues === "string") {
|
|
903
|
+
newImplied = { [impliedOptionValues]: true };
|
|
904
|
+
}
|
|
905
|
+
this.implied = Object.assign(this.implied || {}, newImplied);
|
|
906
|
+
return this;
|
|
907
|
+
}
|
|
908
|
+
/**
|
|
909
|
+
* Set environment variable to check for option value.
|
|
910
|
+
*
|
|
911
|
+
* An environment variable is only used if when processed the current option value is
|
|
912
|
+
* undefined, or the source of the current value is 'default' or 'config' or 'env'.
|
|
913
|
+
*
|
|
914
|
+
* @param {string} name
|
|
915
|
+
* @return {Option}
|
|
916
|
+
*/
|
|
917
|
+
env(name) {
|
|
918
|
+
this.envVar = name;
|
|
919
|
+
return this;
|
|
920
|
+
}
|
|
921
|
+
/**
|
|
922
|
+
* Set the custom handler for processing CLI option arguments into option values.
|
|
923
|
+
*
|
|
924
|
+
* @param {Function} [fn]
|
|
925
|
+
* @return {Option}
|
|
926
|
+
*/
|
|
927
|
+
argParser(fn) {
|
|
928
|
+
this.parseArg = fn;
|
|
929
|
+
return this;
|
|
930
|
+
}
|
|
931
|
+
/**
|
|
932
|
+
* Whether the option is mandatory and must have a value after parsing.
|
|
933
|
+
*
|
|
934
|
+
* @param {boolean} [mandatory=true]
|
|
935
|
+
* @return {Option}
|
|
936
|
+
*/
|
|
937
|
+
makeOptionMandatory(mandatory = true) {
|
|
938
|
+
this.mandatory = !!mandatory;
|
|
939
|
+
return this;
|
|
940
|
+
}
|
|
941
|
+
/**
|
|
942
|
+
* Hide option in help.
|
|
943
|
+
*
|
|
944
|
+
* @param {boolean} [hide=true]
|
|
945
|
+
* @return {Option}
|
|
946
|
+
*/
|
|
947
|
+
hideHelp(hide = true) {
|
|
948
|
+
this.hidden = !!hide;
|
|
949
|
+
return this;
|
|
950
|
+
}
|
|
951
|
+
/**
|
|
952
|
+
* @package
|
|
953
|
+
*/
|
|
954
|
+
_collectValue(value, previous) {
|
|
955
|
+
if (previous === this.defaultValue || !Array.isArray(previous)) {
|
|
956
|
+
return [value];
|
|
957
|
+
}
|
|
958
|
+
previous.push(value);
|
|
959
|
+
return previous;
|
|
960
|
+
}
|
|
961
|
+
/**
|
|
962
|
+
* Only allow option value to be one of choices.
|
|
963
|
+
*
|
|
964
|
+
* @param {string[]} values
|
|
965
|
+
* @return {Option}
|
|
966
|
+
*/
|
|
967
|
+
choices(values) {
|
|
968
|
+
this.argChoices = values.slice();
|
|
969
|
+
this.parseArg = (arg, previous) => {
|
|
970
|
+
if (!this.argChoices.includes(arg)) {
|
|
971
|
+
throw new InvalidArgumentError2(
|
|
972
|
+
`Allowed choices are ${this.argChoices.join(", ")}.`
|
|
973
|
+
);
|
|
974
|
+
}
|
|
975
|
+
if (this.variadic) {
|
|
976
|
+
return this._collectValue(arg, previous);
|
|
977
|
+
}
|
|
978
|
+
return arg;
|
|
979
|
+
};
|
|
980
|
+
return this;
|
|
981
|
+
}
|
|
982
|
+
/**
|
|
983
|
+
* Return option name.
|
|
984
|
+
*
|
|
985
|
+
* @return {string}
|
|
986
|
+
*/
|
|
987
|
+
name() {
|
|
988
|
+
if (this.long) {
|
|
989
|
+
return this.long.replace(/^--/, "");
|
|
990
|
+
}
|
|
991
|
+
return this.short.replace(/^-/, "");
|
|
992
|
+
}
|
|
993
|
+
/**
|
|
994
|
+
* Return option name, in a camelcase format that can be used
|
|
995
|
+
* as an object attribute key.
|
|
996
|
+
*
|
|
997
|
+
* @return {string}
|
|
998
|
+
*/
|
|
999
|
+
attributeName() {
|
|
1000
|
+
if (this.negate) {
|
|
1001
|
+
return camelcase(this.name().replace(/^no-/, ""));
|
|
1002
|
+
}
|
|
1003
|
+
return camelcase(this.name());
|
|
1004
|
+
}
|
|
1005
|
+
/**
|
|
1006
|
+
* Set the help group heading.
|
|
1007
|
+
*
|
|
1008
|
+
* @param {string} heading
|
|
1009
|
+
* @return {Option}
|
|
1010
|
+
*/
|
|
1011
|
+
helpGroup(heading) {
|
|
1012
|
+
this.helpGroupHeading = heading;
|
|
1013
|
+
return this;
|
|
1014
|
+
}
|
|
1015
|
+
/**
|
|
1016
|
+
* Check if `arg` matches the short or long flag.
|
|
1017
|
+
*
|
|
1018
|
+
* @param {string} arg
|
|
1019
|
+
* @return {boolean}
|
|
1020
|
+
* @package
|
|
1021
|
+
*/
|
|
1022
|
+
is(arg) {
|
|
1023
|
+
return this.short === arg || this.long === arg;
|
|
1024
|
+
}
|
|
1025
|
+
/**
|
|
1026
|
+
* Return whether a boolean option.
|
|
1027
|
+
*
|
|
1028
|
+
* Options are one of boolean, negated, required argument, or optional argument.
|
|
1029
|
+
*
|
|
1030
|
+
* @return {boolean}
|
|
1031
|
+
* @package
|
|
1032
|
+
*/
|
|
1033
|
+
isBoolean() {
|
|
1034
|
+
return !this.required && !this.optional && !this.negate;
|
|
1035
|
+
}
|
|
1036
|
+
};
|
|
1037
|
+
var DualOptions = class {
|
|
1038
|
+
/**
|
|
1039
|
+
* @param {Option[]} options
|
|
1040
|
+
*/
|
|
1041
|
+
constructor(options) {
|
|
1042
|
+
this.positiveOptions = /* @__PURE__ */ new Map();
|
|
1043
|
+
this.negativeOptions = /* @__PURE__ */ new Map();
|
|
1044
|
+
this.dualOptions = /* @__PURE__ */ new Set();
|
|
1045
|
+
options.forEach((option) => {
|
|
1046
|
+
if (option.negate) {
|
|
1047
|
+
this.negativeOptions.set(option.attributeName(), option);
|
|
1048
|
+
} else {
|
|
1049
|
+
this.positiveOptions.set(option.attributeName(), option);
|
|
1050
|
+
}
|
|
1051
|
+
});
|
|
1052
|
+
this.negativeOptions.forEach((value, key) => {
|
|
1053
|
+
if (this.positiveOptions.has(key)) {
|
|
1054
|
+
this.dualOptions.add(key);
|
|
1055
|
+
}
|
|
1056
|
+
});
|
|
1057
|
+
}
|
|
1058
|
+
/**
|
|
1059
|
+
* Did the value come from the option, and not from possible matching dual option?
|
|
1060
|
+
*
|
|
1061
|
+
* @param {*} value
|
|
1062
|
+
* @param {Option} option
|
|
1063
|
+
* @returns {boolean}
|
|
1064
|
+
*/
|
|
1065
|
+
valueFromOption(value, option) {
|
|
1066
|
+
const optionKey = option.attributeName();
|
|
1067
|
+
if (!this.dualOptions.has(optionKey)) return true;
|
|
1068
|
+
const preset = this.negativeOptions.get(optionKey).presetArg;
|
|
1069
|
+
const negativeValue = preset !== void 0 ? preset : false;
|
|
1070
|
+
return option.negate === (negativeValue === value);
|
|
1071
|
+
}
|
|
1072
|
+
};
|
|
1073
|
+
function camelcase(str) {
|
|
1074
|
+
return str.split("-").reduce((str2, word) => {
|
|
1075
|
+
return str2 + word[0].toUpperCase() + word.slice(1);
|
|
1076
|
+
});
|
|
1077
|
+
}
|
|
1078
|
+
function splitOptionFlags(flags) {
|
|
1079
|
+
let shortFlag;
|
|
1080
|
+
let longFlag;
|
|
1081
|
+
const shortFlagExp = /^-[^-]$/;
|
|
1082
|
+
const longFlagExp = /^--[^-]/;
|
|
1083
|
+
const flagParts = flags.split(/[ |,]+/).concat("guard");
|
|
1084
|
+
if (shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();
|
|
1085
|
+
if (longFlagExp.test(flagParts[0])) longFlag = flagParts.shift();
|
|
1086
|
+
if (!shortFlag && shortFlagExp.test(flagParts[0]))
|
|
1087
|
+
shortFlag = flagParts.shift();
|
|
1088
|
+
if (!shortFlag && longFlagExp.test(flagParts[0])) {
|
|
1089
|
+
shortFlag = longFlag;
|
|
1090
|
+
longFlag = flagParts.shift();
|
|
1091
|
+
}
|
|
1092
|
+
if (flagParts[0].startsWith("-")) {
|
|
1093
|
+
const unsupportedFlag = flagParts[0];
|
|
1094
|
+
const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;
|
|
1095
|
+
if (/^-[^-][^-]/.test(unsupportedFlag))
|
|
1096
|
+
throw new Error(
|
|
1097
|
+
`${baseError}
|
|
1098
|
+
- a short flag is a single dash and a single character
|
|
1099
|
+
- either use a single dash and a single character (for a short flag)
|
|
1100
|
+
- or use a double dash for a long option (and can have two, like '--ws, --workspace')`
|
|
1101
|
+
);
|
|
1102
|
+
if (shortFlagExp.test(unsupportedFlag))
|
|
1103
|
+
throw new Error(`${baseError}
|
|
1104
|
+
- too many short flags`);
|
|
1105
|
+
if (longFlagExp.test(unsupportedFlag))
|
|
1106
|
+
throw new Error(`${baseError}
|
|
1107
|
+
- too many long flags`);
|
|
1108
|
+
throw new Error(`${baseError}
|
|
1109
|
+
- unrecognised flag format`);
|
|
1110
|
+
}
|
|
1111
|
+
if (shortFlag === void 0 && longFlag === void 0)
|
|
1112
|
+
throw new Error(
|
|
1113
|
+
`option creation failed due to no flags found in '${flags}'.`
|
|
1114
|
+
);
|
|
1115
|
+
return { shortFlag, longFlag };
|
|
1116
|
+
}
|
|
1117
|
+
exports.Option = Option2;
|
|
1118
|
+
exports.DualOptions = DualOptions;
|
|
1119
|
+
}
|
|
1120
|
+
});
|
|
1121
|
+
|
|
1122
|
+
// node_modules/commander/lib/suggestSimilar.js
|
|
1123
|
+
var require_suggestSimilar = __commonJS({
|
|
1124
|
+
"node_modules/commander/lib/suggestSimilar.js"(exports) {
|
|
1125
|
+
var maxDistance = 3;
|
|
1126
|
+
function editDistance(a, b) {
|
|
1127
|
+
if (Math.abs(a.length - b.length) > maxDistance)
|
|
1128
|
+
return Math.max(a.length, b.length);
|
|
1129
|
+
const d = [];
|
|
1130
|
+
for (let i = 0; i <= a.length; i++) {
|
|
1131
|
+
d[i] = [i];
|
|
1132
|
+
}
|
|
1133
|
+
for (let j = 0; j <= b.length; j++) {
|
|
1134
|
+
d[0][j] = j;
|
|
1135
|
+
}
|
|
1136
|
+
for (let j = 1; j <= b.length; j++) {
|
|
1137
|
+
for (let i = 1; i <= a.length; i++) {
|
|
1138
|
+
let cost = 1;
|
|
1139
|
+
if (a[i - 1] === b[j - 1]) {
|
|
1140
|
+
cost = 0;
|
|
1141
|
+
} else {
|
|
1142
|
+
cost = 1;
|
|
1143
|
+
}
|
|
1144
|
+
d[i][j] = Math.min(
|
|
1145
|
+
d[i - 1][j] + 1,
|
|
1146
|
+
// deletion
|
|
1147
|
+
d[i][j - 1] + 1,
|
|
1148
|
+
// insertion
|
|
1149
|
+
d[i - 1][j - 1] + cost
|
|
1150
|
+
// substitution
|
|
1151
|
+
);
|
|
1152
|
+
if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
|
|
1153
|
+
d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
|
|
1154
|
+
}
|
|
1155
|
+
}
|
|
1156
|
+
}
|
|
1157
|
+
return d[a.length][b.length];
|
|
1158
|
+
}
|
|
1159
|
+
function suggestSimilar(word, candidates) {
|
|
1160
|
+
if (!candidates || candidates.length === 0) return "";
|
|
1161
|
+
candidates = Array.from(new Set(candidates));
|
|
1162
|
+
const searchingOptions = word.startsWith("--");
|
|
1163
|
+
if (searchingOptions) {
|
|
1164
|
+
word = word.slice(2);
|
|
1165
|
+
candidates = candidates.map((candidate) => candidate.slice(2));
|
|
1166
|
+
}
|
|
1167
|
+
let similar = [];
|
|
1168
|
+
let bestDistance = maxDistance;
|
|
1169
|
+
const minSimilarity = 0.4;
|
|
1170
|
+
candidates.forEach((candidate) => {
|
|
1171
|
+
if (candidate.length <= 1) return;
|
|
1172
|
+
const distance = editDistance(word, candidate);
|
|
1173
|
+
const length = Math.max(word.length, candidate.length);
|
|
1174
|
+
const similarity = (length - distance) / length;
|
|
1175
|
+
if (similarity > minSimilarity) {
|
|
1176
|
+
if (distance < bestDistance) {
|
|
1177
|
+
bestDistance = distance;
|
|
1178
|
+
similar = [candidate];
|
|
1179
|
+
} else if (distance === bestDistance) {
|
|
1180
|
+
similar.push(candidate);
|
|
1181
|
+
}
|
|
1182
|
+
}
|
|
1183
|
+
});
|
|
1184
|
+
similar.sort((a, b) => a.localeCompare(b));
|
|
1185
|
+
if (searchingOptions) {
|
|
1186
|
+
similar = similar.map((candidate) => `--${candidate}`);
|
|
1187
|
+
}
|
|
1188
|
+
if (similar.length > 1) {
|
|
1189
|
+
return `
|
|
1190
|
+
(Did you mean one of ${similar.join(", ")}?)`;
|
|
1191
|
+
}
|
|
1192
|
+
if (similar.length === 1) {
|
|
1193
|
+
return `
|
|
1194
|
+
(Did you mean ${similar[0]}?)`;
|
|
1195
|
+
}
|
|
1196
|
+
return "";
|
|
1197
|
+
}
|
|
1198
|
+
exports.suggestSimilar = suggestSimilar;
|
|
1199
|
+
}
|
|
1200
|
+
});
|
|
1201
|
+
|
|
1202
|
+
// node_modules/commander/lib/command.js
|
|
1203
|
+
var require_command = __commonJS({
|
|
1204
|
+
"node_modules/commander/lib/command.js"(exports) {
|
|
1205
|
+
var EventEmitter = __require("node:events").EventEmitter;
|
|
1206
|
+
var childProcess = __require("node:child_process");
|
|
1207
|
+
var path = __require("node:path");
|
|
1208
|
+
var fs = __require("node:fs");
|
|
1209
|
+
var process2 = __require("node:process");
|
|
1210
|
+
var { Argument: Argument2, humanReadableArgName } = require_argument();
|
|
1211
|
+
var { CommanderError: CommanderError2 } = require_error();
|
|
1212
|
+
var { Help: Help2, stripColor } = require_help();
|
|
1213
|
+
var { Option: Option2, DualOptions } = require_option();
|
|
1214
|
+
var { suggestSimilar } = require_suggestSimilar();
|
|
1215
|
+
var Command2 = class _Command extends EventEmitter {
|
|
1216
|
+
/**
|
|
1217
|
+
* Initialize a new `Command`.
|
|
1218
|
+
*
|
|
1219
|
+
* @param {string} [name]
|
|
1220
|
+
*/
|
|
1221
|
+
constructor(name) {
|
|
1222
|
+
super();
|
|
1223
|
+
this.commands = [];
|
|
1224
|
+
this.options = [];
|
|
1225
|
+
this.parent = null;
|
|
1226
|
+
this._allowUnknownOption = false;
|
|
1227
|
+
this._allowExcessArguments = false;
|
|
1228
|
+
this.registeredArguments = [];
|
|
1229
|
+
this._args = this.registeredArguments;
|
|
1230
|
+
this.args = [];
|
|
1231
|
+
this.rawArgs = [];
|
|
1232
|
+
this.processedArgs = [];
|
|
1233
|
+
this._scriptPath = null;
|
|
1234
|
+
this._name = name || "";
|
|
1235
|
+
this._optionValues = {};
|
|
1236
|
+
this._optionValueSources = {};
|
|
1237
|
+
this._storeOptionsAsProperties = false;
|
|
1238
|
+
this._actionHandler = null;
|
|
1239
|
+
this._executableHandler = false;
|
|
1240
|
+
this._executableFile = null;
|
|
1241
|
+
this._executableDir = null;
|
|
1242
|
+
this._defaultCommandName = null;
|
|
1243
|
+
this._exitCallback = null;
|
|
1244
|
+
this._aliases = [];
|
|
1245
|
+
this._combineFlagAndOptionalValue = true;
|
|
1246
|
+
this._description = "";
|
|
1247
|
+
this._summary = "";
|
|
1248
|
+
this._argsDescription = void 0;
|
|
1249
|
+
this._enablePositionalOptions = false;
|
|
1250
|
+
this._passThroughOptions = false;
|
|
1251
|
+
this._lifeCycleHooks = {};
|
|
1252
|
+
this._showHelpAfterError = false;
|
|
1253
|
+
this._showSuggestionAfterError = true;
|
|
1254
|
+
this._savedState = null;
|
|
1255
|
+
this._outputConfiguration = {
|
|
1256
|
+
writeOut: (str) => process2.stdout.write(str),
|
|
1257
|
+
writeErr: (str) => process2.stderr.write(str),
|
|
1258
|
+
outputError: (str, write) => write(str),
|
|
1259
|
+
getOutHelpWidth: () => process2.stdout.isTTY ? process2.stdout.columns : void 0,
|
|
1260
|
+
getErrHelpWidth: () => process2.stderr.isTTY ? process2.stderr.columns : void 0,
|
|
1261
|
+
getOutHasColors: () => useColor() ?? (process2.stdout.isTTY && process2.stdout.hasColors?.()),
|
|
1262
|
+
getErrHasColors: () => useColor() ?? (process2.stderr.isTTY && process2.stderr.hasColors?.()),
|
|
1263
|
+
stripColor: (str) => stripColor(str)
|
|
1264
|
+
};
|
|
1265
|
+
this._hidden = false;
|
|
1266
|
+
this._helpOption = void 0;
|
|
1267
|
+
this._addImplicitHelpCommand = void 0;
|
|
1268
|
+
this._helpCommand = void 0;
|
|
1269
|
+
this._helpConfiguration = {};
|
|
1270
|
+
this._helpGroupHeading = void 0;
|
|
1271
|
+
this._defaultCommandGroup = void 0;
|
|
1272
|
+
this._defaultOptionGroup = void 0;
|
|
1273
|
+
}
|
|
1274
|
+
/**
|
|
1275
|
+
* Copy settings that are useful to have in common across root command and subcommands.
|
|
1276
|
+
*
|
|
1277
|
+
* (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
|
|
1278
|
+
*
|
|
1279
|
+
* @param {Command} sourceCommand
|
|
1280
|
+
* @return {Command} `this` command for chaining
|
|
1281
|
+
*/
|
|
1282
|
+
copyInheritedSettings(sourceCommand) {
|
|
1283
|
+
this._outputConfiguration = sourceCommand._outputConfiguration;
|
|
1284
|
+
this._helpOption = sourceCommand._helpOption;
|
|
1285
|
+
this._helpCommand = sourceCommand._helpCommand;
|
|
1286
|
+
this._helpConfiguration = sourceCommand._helpConfiguration;
|
|
1287
|
+
this._exitCallback = sourceCommand._exitCallback;
|
|
1288
|
+
this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
|
|
1289
|
+
this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
|
|
1290
|
+
this._allowExcessArguments = sourceCommand._allowExcessArguments;
|
|
1291
|
+
this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
|
|
1292
|
+
this._showHelpAfterError = sourceCommand._showHelpAfterError;
|
|
1293
|
+
this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
|
|
1294
|
+
return this;
|
|
1295
|
+
}
|
|
1296
|
+
/**
|
|
1297
|
+
* @returns {Command[]}
|
|
1298
|
+
* @private
|
|
1299
|
+
*/
|
|
1300
|
+
_getCommandAndAncestors() {
|
|
1301
|
+
const result = [];
|
|
1302
|
+
for (let command = this; command; command = command.parent) {
|
|
1303
|
+
result.push(command);
|
|
1304
|
+
}
|
|
1305
|
+
return result;
|
|
1306
|
+
}
|
|
1307
|
+
/**
|
|
1308
|
+
* Define a command.
|
|
1309
|
+
*
|
|
1310
|
+
* There are two styles of command: pay attention to where to put the description.
|
|
1311
|
+
*
|
|
1312
|
+
* @example
|
|
1313
|
+
* // Command implemented using action handler (description is supplied separately to `.command`)
|
|
1314
|
+
* program
|
|
1315
|
+
* .command('clone <source> [destination]')
|
|
1316
|
+
* .description('clone a repository into a newly created directory')
|
|
1317
|
+
* .action((source, destination) => {
|
|
1318
|
+
* console.log('clone command called');
|
|
1319
|
+
* });
|
|
1320
|
+
*
|
|
1321
|
+
* // Command implemented using separate executable file (description is second parameter to `.command`)
|
|
1322
|
+
* program
|
|
1323
|
+
* .command('start <service>', 'start named service')
|
|
1324
|
+
* .command('stop [service]', 'stop named service, or all if no name supplied');
|
|
1325
|
+
*
|
|
1326
|
+
* @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
|
|
1327
|
+
* @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
|
|
1328
|
+
* @param {object} [execOpts] - configuration options (for executable)
|
|
1329
|
+
* @return {Command} returns new command for action handler, or `this` for executable command
|
|
1330
|
+
*/
|
|
1331
|
+
command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
|
|
1332
|
+
let desc = actionOptsOrExecDesc;
|
|
1333
|
+
let opts = execOpts;
|
|
1334
|
+
if (typeof desc === "object" && desc !== null) {
|
|
1335
|
+
opts = desc;
|
|
1336
|
+
desc = null;
|
|
1337
|
+
}
|
|
1338
|
+
opts = opts || {};
|
|
1339
|
+
const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
|
|
1340
|
+
const cmd = this.createCommand(name);
|
|
1341
|
+
if (desc) {
|
|
1342
|
+
cmd.description(desc);
|
|
1343
|
+
cmd._executableHandler = true;
|
|
1344
|
+
}
|
|
1345
|
+
if (opts.isDefault) this._defaultCommandName = cmd._name;
|
|
1346
|
+
cmd._hidden = !!(opts.noHelp || opts.hidden);
|
|
1347
|
+
cmd._executableFile = opts.executableFile || null;
|
|
1348
|
+
if (args) cmd.arguments(args);
|
|
1349
|
+
this._registerCommand(cmd);
|
|
1350
|
+
cmd.parent = this;
|
|
1351
|
+
cmd.copyInheritedSettings(this);
|
|
1352
|
+
if (desc) return this;
|
|
1353
|
+
return cmd;
|
|
1354
|
+
}
|
|
1355
|
+
/**
|
|
1356
|
+
* Factory routine to create a new unattached command.
|
|
1357
|
+
*
|
|
1358
|
+
* See .command() for creating an attached subcommand, which uses this routine to
|
|
1359
|
+
* create the command. You can override createCommand to customise subcommands.
|
|
1360
|
+
*
|
|
1361
|
+
* @param {string} [name]
|
|
1362
|
+
* @return {Command} new command
|
|
1363
|
+
*/
|
|
1364
|
+
createCommand(name) {
|
|
1365
|
+
return new _Command(name);
|
|
1366
|
+
}
|
|
1367
|
+
/**
|
|
1368
|
+
* You can customise the help with a subclass of Help by overriding createHelp,
|
|
1369
|
+
* or by overriding Help properties using configureHelp().
|
|
1370
|
+
*
|
|
1371
|
+
* @return {Help}
|
|
1372
|
+
*/
|
|
1373
|
+
createHelp() {
|
|
1374
|
+
return Object.assign(new Help2(), this.configureHelp());
|
|
1375
|
+
}
|
|
1376
|
+
/**
|
|
1377
|
+
* You can customise the help by overriding Help properties using configureHelp(),
|
|
1378
|
+
* or with a subclass of Help by overriding createHelp().
|
|
1379
|
+
*
|
|
1380
|
+
* @param {object} [configuration] - configuration options
|
|
1381
|
+
* @return {(Command | object)} `this` command for chaining, or stored configuration
|
|
1382
|
+
*/
|
|
1383
|
+
configureHelp(configuration) {
|
|
1384
|
+
if (configuration === void 0) return this._helpConfiguration;
|
|
1385
|
+
this._helpConfiguration = configuration;
|
|
1386
|
+
return this;
|
|
1387
|
+
}
|
|
1388
|
+
/**
|
|
1389
|
+
* The default output goes to stdout and stderr. You can customise this for special
|
|
1390
|
+
* applications. You can also customise the display of errors by overriding outputError.
|
|
1391
|
+
*
|
|
1392
|
+
* The configuration properties are all functions:
|
|
1393
|
+
*
|
|
1394
|
+
* // change how output being written, defaults to stdout and stderr
|
|
1395
|
+
* writeOut(str)
|
|
1396
|
+
* writeErr(str)
|
|
1397
|
+
* // change how output being written for errors, defaults to writeErr
|
|
1398
|
+
* outputError(str, write) // used for displaying errors and not used for displaying help
|
|
1399
|
+
* // specify width for wrapping help
|
|
1400
|
+
* getOutHelpWidth()
|
|
1401
|
+
* getErrHelpWidth()
|
|
1402
|
+
* // color support, currently only used with Help
|
|
1403
|
+
* getOutHasColors()
|
|
1404
|
+
* getErrHasColors()
|
|
1405
|
+
* stripColor() // used to remove ANSI escape codes if output does not have colors
|
|
1406
|
+
*
|
|
1407
|
+
* @param {object} [configuration] - configuration options
|
|
1408
|
+
* @return {(Command | object)} `this` command for chaining, or stored configuration
|
|
1409
|
+
*/
|
|
1410
|
+
configureOutput(configuration) {
|
|
1411
|
+
if (configuration === void 0) return this._outputConfiguration;
|
|
1412
|
+
this._outputConfiguration = {
|
|
1413
|
+
...this._outputConfiguration,
|
|
1414
|
+
...configuration
|
|
1415
|
+
};
|
|
1416
|
+
return this;
|
|
1417
|
+
}
|
|
1418
|
+
/**
|
|
1419
|
+
* Display the help or a custom message after an error occurs.
|
|
1420
|
+
*
|
|
1421
|
+
* @param {(boolean|string)} [displayHelp]
|
|
1422
|
+
* @return {Command} `this` command for chaining
|
|
1423
|
+
*/
|
|
1424
|
+
showHelpAfterError(displayHelp = true) {
|
|
1425
|
+
if (typeof displayHelp !== "string") displayHelp = !!displayHelp;
|
|
1426
|
+
this._showHelpAfterError = displayHelp;
|
|
1427
|
+
return this;
|
|
1428
|
+
}
|
|
1429
|
+
/**
|
|
1430
|
+
* Display suggestion of similar commands for unknown commands, or options for unknown options.
|
|
1431
|
+
*
|
|
1432
|
+
* @param {boolean} [displaySuggestion]
|
|
1433
|
+
* @return {Command} `this` command for chaining
|
|
1434
|
+
*/
|
|
1435
|
+
showSuggestionAfterError(displaySuggestion = true) {
|
|
1436
|
+
this._showSuggestionAfterError = !!displaySuggestion;
|
|
1437
|
+
return this;
|
|
1438
|
+
}
|
|
1439
|
+
/**
|
|
1440
|
+
* Add a prepared subcommand.
|
|
1441
|
+
*
|
|
1442
|
+
* See .command() for creating an attached subcommand which inherits settings from its parent.
|
|
1443
|
+
*
|
|
1444
|
+
* @param {Command} cmd - new subcommand
|
|
1445
|
+
* @param {object} [opts] - configuration options
|
|
1446
|
+
* @return {Command} `this` command for chaining
|
|
1447
|
+
*/
|
|
1448
|
+
addCommand(cmd, opts) {
|
|
1449
|
+
if (!cmd._name) {
|
|
1450
|
+
throw new Error(`Command passed to .addCommand() must have a name
|
|
1451
|
+
- specify the name in Command constructor or using .name()`);
|
|
1452
|
+
}
|
|
1453
|
+
opts = opts || {};
|
|
1454
|
+
if (opts.isDefault) this._defaultCommandName = cmd._name;
|
|
1455
|
+
if (opts.noHelp || opts.hidden) cmd._hidden = true;
|
|
1456
|
+
this._registerCommand(cmd);
|
|
1457
|
+
cmd.parent = this;
|
|
1458
|
+
cmd._checkForBrokenPassThrough();
|
|
1459
|
+
return this;
|
|
1460
|
+
}
|
|
1461
|
+
/**
|
|
1462
|
+
* Factory routine to create a new unattached argument.
|
|
1463
|
+
*
|
|
1464
|
+
* See .argument() for creating an attached argument, which uses this routine to
|
|
1465
|
+
* create the argument. You can override createArgument to return a custom argument.
|
|
1466
|
+
*
|
|
1467
|
+
* @param {string} name
|
|
1468
|
+
* @param {string} [description]
|
|
1469
|
+
* @return {Argument} new argument
|
|
1470
|
+
*/
|
|
1471
|
+
createArgument(name, description) {
|
|
1472
|
+
return new Argument2(name, description);
|
|
1473
|
+
}
|
|
1474
|
+
/**
|
|
1475
|
+
* Define argument syntax for command.
|
|
1476
|
+
*
|
|
1477
|
+
* The default is that the argument is required, and you can explicitly
|
|
1478
|
+
* indicate this with <> around the name. Put [] around the name for an optional argument.
|
|
1479
|
+
*
|
|
1480
|
+
* @example
|
|
1481
|
+
* program.argument('<input-file>');
|
|
1482
|
+
* program.argument('[output-file]');
|
|
1483
|
+
*
|
|
1484
|
+
* @param {string} name
|
|
1485
|
+
* @param {string} [description]
|
|
1486
|
+
* @param {(Function|*)} [parseArg] - custom argument processing function or default value
|
|
1487
|
+
* @param {*} [defaultValue]
|
|
1488
|
+
* @return {Command} `this` command for chaining
|
|
1489
|
+
*/
|
|
1490
|
+
argument(name, description, parseArg, defaultValue) {
|
|
1491
|
+
const argument = this.createArgument(name, description);
|
|
1492
|
+
if (typeof parseArg === "function") {
|
|
1493
|
+
argument.default(defaultValue).argParser(parseArg);
|
|
1494
|
+
} else {
|
|
1495
|
+
argument.default(parseArg);
|
|
1496
|
+
}
|
|
1497
|
+
this.addArgument(argument);
|
|
1498
|
+
return this;
|
|
1499
|
+
}
|
|
1500
|
+
/**
|
|
1501
|
+
* Define argument syntax for command, adding multiple at once (without descriptions).
|
|
1502
|
+
*
|
|
1503
|
+
* See also .argument().
|
|
1504
|
+
*
|
|
1505
|
+
* @example
|
|
1506
|
+
* program.arguments('<cmd> [env]');
|
|
1507
|
+
*
|
|
1508
|
+
* @param {string} names
|
|
1509
|
+
* @return {Command} `this` command for chaining
|
|
1510
|
+
*/
|
|
1511
|
+
arguments(names) {
|
|
1512
|
+
names.trim().split(/ +/).forEach((detail) => {
|
|
1513
|
+
this.argument(detail);
|
|
1514
|
+
});
|
|
1515
|
+
return this;
|
|
1516
|
+
}
|
|
1517
|
+
/**
|
|
1518
|
+
* Define argument syntax for command, adding a prepared argument.
|
|
1519
|
+
*
|
|
1520
|
+
* @param {Argument} argument
|
|
1521
|
+
* @return {Command} `this` command for chaining
|
|
1522
|
+
*/
|
|
1523
|
+
addArgument(argument) {
|
|
1524
|
+
const previousArgument = this.registeredArguments.slice(-1)[0];
|
|
1525
|
+
if (previousArgument?.variadic) {
|
|
1526
|
+
throw new Error(
|
|
1527
|
+
`only the last argument can be variadic '${previousArgument.name()}'`
|
|
1528
|
+
);
|
|
1529
|
+
}
|
|
1530
|
+
if (argument.required && argument.defaultValue !== void 0 && argument.parseArg === void 0) {
|
|
1531
|
+
throw new Error(
|
|
1532
|
+
`a default value for a required argument is never used: '${argument.name()}'`
|
|
1533
|
+
);
|
|
1534
|
+
}
|
|
1535
|
+
this.registeredArguments.push(argument);
|
|
1536
|
+
return this;
|
|
1537
|
+
}
|
|
1538
|
+
/**
|
|
1539
|
+
* Customise or override default help command. By default a help command is automatically added if your command has subcommands.
|
|
1540
|
+
*
|
|
1541
|
+
* @example
|
|
1542
|
+
* program.helpCommand('help [cmd]');
|
|
1543
|
+
* program.helpCommand('help [cmd]', 'show help');
|
|
1544
|
+
* program.helpCommand(false); // suppress default help command
|
|
1545
|
+
* program.helpCommand(true); // add help command even if no subcommands
|
|
1546
|
+
*
|
|
1547
|
+
* @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added
|
|
1548
|
+
* @param {string} [description] - custom description
|
|
1549
|
+
* @return {Command} `this` command for chaining
|
|
1550
|
+
*/
|
|
1551
|
+
helpCommand(enableOrNameAndArgs, description) {
|
|
1552
|
+
if (typeof enableOrNameAndArgs === "boolean") {
|
|
1553
|
+
this._addImplicitHelpCommand = enableOrNameAndArgs;
|
|
1554
|
+
if (enableOrNameAndArgs && this._defaultCommandGroup) {
|
|
1555
|
+
this._initCommandGroup(this._getHelpCommand());
|
|
1556
|
+
}
|
|
1557
|
+
return this;
|
|
1558
|
+
}
|
|
1559
|
+
const nameAndArgs = enableOrNameAndArgs ?? "help [command]";
|
|
1560
|
+
const [, helpName, helpArgs] = nameAndArgs.match(/([^ ]+) *(.*)/);
|
|
1561
|
+
const helpDescription = description ?? "display help for command";
|
|
1562
|
+
const helpCommand = this.createCommand(helpName);
|
|
1563
|
+
helpCommand.helpOption(false);
|
|
1564
|
+
if (helpArgs) helpCommand.arguments(helpArgs);
|
|
1565
|
+
if (helpDescription) helpCommand.description(helpDescription);
|
|
1566
|
+
this._addImplicitHelpCommand = true;
|
|
1567
|
+
this._helpCommand = helpCommand;
|
|
1568
|
+
if (enableOrNameAndArgs || description) this._initCommandGroup(helpCommand);
|
|
1569
|
+
return this;
|
|
1570
|
+
}
|
|
1571
|
+
/**
|
|
1572
|
+
* Add prepared custom help command.
|
|
1573
|
+
*
|
|
1574
|
+
* @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`
|
|
1575
|
+
* @param {string} [deprecatedDescription] - deprecated custom description used with custom name only
|
|
1576
|
+
* @return {Command} `this` command for chaining
|
|
1577
|
+
*/
|
|
1578
|
+
addHelpCommand(helpCommand, deprecatedDescription) {
|
|
1579
|
+
if (typeof helpCommand !== "object") {
|
|
1580
|
+
this.helpCommand(helpCommand, deprecatedDescription);
|
|
1581
|
+
return this;
|
|
1582
|
+
}
|
|
1583
|
+
this._addImplicitHelpCommand = true;
|
|
1584
|
+
this._helpCommand = helpCommand;
|
|
1585
|
+
this._initCommandGroup(helpCommand);
|
|
1586
|
+
return this;
|
|
1587
|
+
}
|
|
1588
|
+
/**
|
|
1589
|
+
* Lazy create help command.
|
|
1590
|
+
*
|
|
1591
|
+
* @return {(Command|null)}
|
|
1592
|
+
* @package
|
|
1593
|
+
*/
|
|
1594
|
+
_getHelpCommand() {
|
|
1595
|
+
const hasImplicitHelpCommand = this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"));
|
|
1596
|
+
if (hasImplicitHelpCommand) {
|
|
1597
|
+
if (this._helpCommand === void 0) {
|
|
1598
|
+
this.helpCommand(void 0, void 0);
|
|
1599
|
+
}
|
|
1600
|
+
return this._helpCommand;
|
|
1601
|
+
}
|
|
1602
|
+
return null;
|
|
1603
|
+
}
|
|
1604
|
+
/**
|
|
1605
|
+
* Add hook for life cycle event.
|
|
1606
|
+
*
|
|
1607
|
+
* @param {string} event
|
|
1608
|
+
* @param {Function} listener
|
|
1609
|
+
* @return {Command} `this` command for chaining
|
|
1610
|
+
*/
|
|
1611
|
+
hook(event, listener) {
|
|
1612
|
+
const allowedValues = ["preSubcommand", "preAction", "postAction"];
|
|
1613
|
+
if (!allowedValues.includes(event)) {
|
|
1614
|
+
throw new Error(`Unexpected value for event passed to hook : '${event}'.
|
|
1615
|
+
Expecting one of '${allowedValues.join("', '")}'`);
|
|
1616
|
+
}
|
|
1617
|
+
if (this._lifeCycleHooks[event]) {
|
|
1618
|
+
this._lifeCycleHooks[event].push(listener);
|
|
1619
|
+
} else {
|
|
1620
|
+
this._lifeCycleHooks[event] = [listener];
|
|
1621
|
+
}
|
|
1622
|
+
return this;
|
|
1623
|
+
}
|
|
1624
|
+
/**
|
|
1625
|
+
* Register callback to use as replacement for calling process.exit.
|
|
1626
|
+
*
|
|
1627
|
+
* @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
|
|
1628
|
+
* @return {Command} `this` command for chaining
|
|
1629
|
+
*/
|
|
1630
|
+
exitOverride(fn) {
|
|
1631
|
+
if (fn) {
|
|
1632
|
+
this._exitCallback = fn;
|
|
1633
|
+
} else {
|
|
1634
|
+
this._exitCallback = (err) => {
|
|
1635
|
+
if (err.code !== "commander.executeSubCommandAsync") {
|
|
1636
|
+
throw err;
|
|
1637
|
+
} else {
|
|
1638
|
+
}
|
|
1639
|
+
};
|
|
1640
|
+
}
|
|
1641
|
+
return this;
|
|
1642
|
+
}
|
|
1643
|
+
/**
|
|
1644
|
+
* Call process.exit, and _exitCallback if defined.
|
|
1645
|
+
*
|
|
1646
|
+
* @param {number} exitCode exit code for using with process.exit
|
|
1647
|
+
* @param {string} code an id string representing the error
|
|
1648
|
+
* @param {string} message human-readable description of the error
|
|
1649
|
+
* @return never
|
|
1650
|
+
* @private
|
|
1651
|
+
*/
|
|
1652
|
+
_exit(exitCode, code, message) {
|
|
1653
|
+
if (this._exitCallback) {
|
|
1654
|
+
this._exitCallback(new CommanderError2(exitCode, code, message));
|
|
1655
|
+
}
|
|
1656
|
+
process2.exit(exitCode);
|
|
1657
|
+
}
|
|
1658
|
+
/**
|
|
1659
|
+
* Register callback `fn` for the command.
|
|
1660
|
+
*
|
|
1661
|
+
* @example
|
|
1662
|
+
* program
|
|
1663
|
+
* .command('serve')
|
|
1664
|
+
* .description('start service')
|
|
1665
|
+
* .action(function() {
|
|
1666
|
+
* // do work here
|
|
1667
|
+
* });
|
|
1668
|
+
*
|
|
1669
|
+
* @param {Function} fn
|
|
1670
|
+
* @return {Command} `this` command for chaining
|
|
1671
|
+
*/
|
|
1672
|
+
action(fn) {
|
|
1673
|
+
const listener = (args) => {
|
|
1674
|
+
const expectedArgsCount = this.registeredArguments.length;
|
|
1675
|
+
const actionArgs = args.slice(0, expectedArgsCount);
|
|
1676
|
+
if (this._storeOptionsAsProperties) {
|
|
1677
|
+
actionArgs[expectedArgsCount] = this;
|
|
1678
|
+
} else {
|
|
1679
|
+
actionArgs[expectedArgsCount] = this.opts();
|
|
1680
|
+
}
|
|
1681
|
+
actionArgs.push(this);
|
|
1682
|
+
return fn.apply(this, actionArgs);
|
|
1683
|
+
};
|
|
1684
|
+
this._actionHandler = listener;
|
|
1685
|
+
return this;
|
|
1686
|
+
}
|
|
1687
|
+
/**
|
|
1688
|
+
* Factory routine to create a new unattached option.
|
|
1689
|
+
*
|
|
1690
|
+
* See .option() for creating an attached option, which uses this routine to
|
|
1691
|
+
* create the option. You can override createOption to return a custom option.
|
|
1692
|
+
*
|
|
1693
|
+
* @param {string} flags
|
|
1694
|
+
* @param {string} [description]
|
|
1695
|
+
* @return {Option} new option
|
|
1696
|
+
*/
|
|
1697
|
+
createOption(flags, description) {
|
|
1698
|
+
return new Option2(flags, description);
|
|
1699
|
+
}
|
|
1700
|
+
/**
|
|
1701
|
+
* Wrap parseArgs to catch 'commander.invalidArgument'.
|
|
1702
|
+
*
|
|
1703
|
+
* @param {(Option | Argument)} target
|
|
1704
|
+
* @param {string} value
|
|
1705
|
+
* @param {*} previous
|
|
1706
|
+
* @param {string} invalidArgumentMessage
|
|
1707
|
+
* @private
|
|
1708
|
+
*/
|
|
1709
|
+
_callParseArg(target, value, previous, invalidArgumentMessage) {
|
|
1710
|
+
try {
|
|
1711
|
+
return target.parseArg(value, previous);
|
|
1712
|
+
} catch (err) {
|
|
1713
|
+
if (err.code === "commander.invalidArgument") {
|
|
1714
|
+
const message = `${invalidArgumentMessage} ${err.message}`;
|
|
1715
|
+
this.error(message, { exitCode: err.exitCode, code: err.code });
|
|
1716
|
+
}
|
|
1717
|
+
throw err;
|
|
1718
|
+
}
|
|
1719
|
+
}
|
|
1720
|
+
/**
|
|
1721
|
+
* Check for option flag conflicts.
|
|
1722
|
+
* Register option if no conflicts found, or throw on conflict.
|
|
1723
|
+
*
|
|
1724
|
+
* @param {Option} option
|
|
1725
|
+
* @private
|
|
1726
|
+
*/
|
|
1727
|
+
_registerOption(option) {
|
|
1728
|
+
const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
|
|
1729
|
+
if (matchingOption) {
|
|
1730
|
+
const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
|
|
1731
|
+
throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
|
|
1732
|
+
- already used by option '${matchingOption.flags}'`);
|
|
1733
|
+
}
|
|
1734
|
+
this._initOptionGroup(option);
|
|
1735
|
+
this.options.push(option);
|
|
1736
|
+
}
|
|
1737
|
+
/**
|
|
1738
|
+
* Check for command name and alias conflicts with existing commands.
|
|
1739
|
+
* Register command if no conflicts found, or throw on conflict.
|
|
1740
|
+
*
|
|
1741
|
+
* @param {Command} command
|
|
1742
|
+
* @private
|
|
1743
|
+
*/
|
|
1744
|
+
_registerCommand(command) {
|
|
1745
|
+
const knownBy = (cmd) => {
|
|
1746
|
+
return [cmd.name()].concat(cmd.aliases());
|
|
1747
|
+
};
|
|
1748
|
+
const alreadyUsed = knownBy(command).find(
|
|
1749
|
+
(name) => this._findCommand(name)
|
|
1750
|
+
);
|
|
1751
|
+
if (alreadyUsed) {
|
|
1752
|
+
const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
|
|
1753
|
+
const newCmd = knownBy(command).join("|");
|
|
1754
|
+
throw new Error(
|
|
1755
|
+
`cannot add command '${newCmd}' as already have command '${existingCmd}'`
|
|
1756
|
+
);
|
|
1757
|
+
}
|
|
1758
|
+
this._initCommandGroup(command);
|
|
1759
|
+
this.commands.push(command);
|
|
1760
|
+
}
|
|
1761
|
+
/**
|
|
1762
|
+
* Add an option.
|
|
1763
|
+
*
|
|
1764
|
+
* @param {Option} option
|
|
1765
|
+
* @return {Command} `this` command for chaining
|
|
1766
|
+
*/
|
|
1767
|
+
addOption(option) {
|
|
1768
|
+
this._registerOption(option);
|
|
1769
|
+
const oname = option.name();
|
|
1770
|
+
const name = option.attributeName();
|
|
1771
|
+
if (option.negate) {
|
|
1772
|
+
const positiveLongFlag = option.long.replace(/^--no-/, "--");
|
|
1773
|
+
if (!this._findOption(positiveLongFlag)) {
|
|
1774
|
+
this.setOptionValueWithSource(
|
|
1775
|
+
name,
|
|
1776
|
+
option.defaultValue === void 0 ? true : option.defaultValue,
|
|
1777
|
+
"default"
|
|
1778
|
+
);
|
|
1779
|
+
}
|
|
1780
|
+
} else if (option.defaultValue !== void 0) {
|
|
1781
|
+
this.setOptionValueWithSource(name, option.defaultValue, "default");
|
|
1782
|
+
}
|
|
1783
|
+
const handleOptionValue = (val, invalidValueMessage, valueSource) => {
|
|
1784
|
+
if (val == null && option.presetArg !== void 0) {
|
|
1785
|
+
val = option.presetArg;
|
|
1786
|
+
}
|
|
1787
|
+
const oldValue = this.getOptionValue(name);
|
|
1788
|
+
if (val !== null && option.parseArg) {
|
|
1789
|
+
val = this._callParseArg(option, val, oldValue, invalidValueMessage);
|
|
1790
|
+
} else if (val !== null && option.variadic) {
|
|
1791
|
+
val = option._collectValue(val, oldValue);
|
|
1792
|
+
}
|
|
1793
|
+
if (val == null) {
|
|
1794
|
+
if (option.negate) {
|
|
1795
|
+
val = false;
|
|
1796
|
+
} else if (option.isBoolean() || option.optional) {
|
|
1797
|
+
val = true;
|
|
1798
|
+
} else {
|
|
1799
|
+
val = "";
|
|
1800
|
+
}
|
|
1801
|
+
}
|
|
1802
|
+
this.setOptionValueWithSource(name, val, valueSource);
|
|
1803
|
+
};
|
|
1804
|
+
this.on("option:" + oname, (val) => {
|
|
1805
|
+
const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
|
|
1806
|
+
handleOptionValue(val, invalidValueMessage, "cli");
|
|
1807
|
+
});
|
|
1808
|
+
if (option.envVar) {
|
|
1809
|
+
this.on("optionEnv:" + oname, (val) => {
|
|
1810
|
+
const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
|
|
1811
|
+
handleOptionValue(val, invalidValueMessage, "env");
|
|
1812
|
+
});
|
|
1813
|
+
}
|
|
1814
|
+
return this;
|
|
1815
|
+
}
|
|
1816
|
+
/**
|
|
1817
|
+
* Internal implementation shared by .option() and .requiredOption()
|
|
1818
|
+
*
|
|
1819
|
+
* @return {Command} `this` command for chaining
|
|
1820
|
+
* @private
|
|
1821
|
+
*/
|
|
1822
|
+
_optionEx(config, flags, description, fn, defaultValue) {
|
|
1823
|
+
if (typeof flags === "object" && flags instanceof Option2) {
|
|
1824
|
+
throw new Error(
|
|
1825
|
+
"To add an Option object use addOption() instead of option() or requiredOption()"
|
|
1826
|
+
);
|
|
1827
|
+
}
|
|
1828
|
+
const option = this.createOption(flags, description);
|
|
1829
|
+
option.makeOptionMandatory(!!config.mandatory);
|
|
1830
|
+
if (typeof fn === "function") {
|
|
1831
|
+
option.default(defaultValue).argParser(fn);
|
|
1832
|
+
} else if (fn instanceof RegExp) {
|
|
1833
|
+
const regex = fn;
|
|
1834
|
+
fn = (val, def) => {
|
|
1835
|
+
const m = regex.exec(val);
|
|
1836
|
+
return m ? m[0] : def;
|
|
1837
|
+
};
|
|
1838
|
+
option.default(defaultValue).argParser(fn);
|
|
1839
|
+
} else {
|
|
1840
|
+
option.default(fn);
|
|
1841
|
+
}
|
|
1842
|
+
return this.addOption(option);
|
|
1843
|
+
}
|
|
1844
|
+
/**
|
|
1845
|
+
* Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
|
|
1846
|
+
*
|
|
1847
|
+
* The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
|
|
1848
|
+
* option-argument is indicated by `<>` and an optional option-argument by `[]`.
|
|
1849
|
+
*
|
|
1850
|
+
* See the README for more details, and see also addOption() and requiredOption().
|
|
1851
|
+
*
|
|
1852
|
+
* @example
|
|
1853
|
+
* program
|
|
1854
|
+
* .option('-p, --pepper', 'add pepper')
|
|
1855
|
+
* .option('--pt, --pizza-type <TYPE>', 'type of pizza') // required option-argument
|
|
1856
|
+
* .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
|
|
1857
|
+
* .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
|
|
1858
|
+
*
|
|
1859
|
+
* @param {string} flags
|
|
1860
|
+
* @param {string} [description]
|
|
1861
|
+
* @param {(Function|*)} [parseArg] - custom option processing function or default value
|
|
1862
|
+
* @param {*} [defaultValue]
|
|
1863
|
+
* @return {Command} `this` command for chaining
|
|
1864
|
+
*/
|
|
1865
|
+
option(flags, description, parseArg, defaultValue) {
|
|
1866
|
+
return this._optionEx({}, flags, description, parseArg, defaultValue);
|
|
1867
|
+
}
|
|
1868
|
+
/**
|
|
1869
|
+
* Add a required option which must have a value after parsing. This usually means
|
|
1870
|
+
* the option must be specified on the command line. (Otherwise the same as .option().)
|
|
1871
|
+
*
|
|
1872
|
+
* The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
|
|
1873
|
+
*
|
|
1874
|
+
* @param {string} flags
|
|
1875
|
+
* @param {string} [description]
|
|
1876
|
+
* @param {(Function|*)} [parseArg] - custom option processing function or default value
|
|
1877
|
+
* @param {*} [defaultValue]
|
|
1878
|
+
* @return {Command} `this` command for chaining
|
|
1879
|
+
*/
|
|
1880
|
+
requiredOption(flags, description, parseArg, defaultValue) {
|
|
1881
|
+
return this._optionEx(
|
|
1882
|
+
{ mandatory: true },
|
|
1883
|
+
flags,
|
|
1884
|
+
description,
|
|
1885
|
+
parseArg,
|
|
1886
|
+
defaultValue
|
|
1887
|
+
);
|
|
1888
|
+
}
|
|
1889
|
+
/**
|
|
1890
|
+
* Alter parsing of short flags with optional values.
|
|
1891
|
+
*
|
|
1892
|
+
* @example
|
|
1893
|
+
* // for `.option('-f,--flag [value]'):
|
|
1894
|
+
* program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
|
|
1895
|
+
* program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
|
|
1896
|
+
*
|
|
1897
|
+
* @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.
|
|
1898
|
+
* @return {Command} `this` command for chaining
|
|
1899
|
+
*/
|
|
1900
|
+
combineFlagAndOptionalValue(combine = true) {
|
|
1901
|
+
this._combineFlagAndOptionalValue = !!combine;
|
|
1902
|
+
return this;
|
|
1903
|
+
}
|
|
1904
|
+
/**
|
|
1905
|
+
* Allow unknown options on the command line.
|
|
1906
|
+
*
|
|
1907
|
+
* @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.
|
|
1908
|
+
* @return {Command} `this` command for chaining
|
|
1909
|
+
*/
|
|
1910
|
+
allowUnknownOption(allowUnknown = true) {
|
|
1911
|
+
this._allowUnknownOption = !!allowUnknown;
|
|
1912
|
+
return this;
|
|
1913
|
+
}
|
|
1914
|
+
/**
|
|
1915
|
+
* Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
|
|
1916
|
+
*
|
|
1917
|
+
* @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.
|
|
1918
|
+
* @return {Command} `this` command for chaining
|
|
1919
|
+
*/
|
|
1920
|
+
allowExcessArguments(allowExcess = true) {
|
|
1921
|
+
this._allowExcessArguments = !!allowExcess;
|
|
1922
|
+
return this;
|
|
1923
|
+
}
|
|
1924
|
+
/**
|
|
1925
|
+
* Enable positional options. Positional means global options are specified before subcommands which lets
|
|
1926
|
+
* subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
|
|
1927
|
+
* The default behaviour is non-positional and global options may appear anywhere on the command line.
|
|
1928
|
+
*
|
|
1929
|
+
* @param {boolean} [positional]
|
|
1930
|
+
* @return {Command} `this` command for chaining
|
|
1931
|
+
*/
|
|
1932
|
+
enablePositionalOptions(positional = true) {
|
|
1933
|
+
this._enablePositionalOptions = !!positional;
|
|
1934
|
+
return this;
|
|
1935
|
+
}
|
|
1936
|
+
/**
|
|
1937
|
+
* Pass through options that come after command-arguments rather than treat them as command-options,
|
|
1938
|
+
* so actual command-options come before command-arguments. Turning this on for a subcommand requires
|
|
1939
|
+
* positional options to have been enabled on the program (parent commands).
|
|
1940
|
+
* The default behaviour is non-positional and options may appear before or after command-arguments.
|
|
1941
|
+
*
|
|
1942
|
+
* @param {boolean} [passThrough] for unknown options.
|
|
1943
|
+
* @return {Command} `this` command for chaining
|
|
1944
|
+
*/
|
|
1945
|
+
passThroughOptions(passThrough = true) {
|
|
1946
|
+
this._passThroughOptions = !!passThrough;
|
|
1947
|
+
this._checkForBrokenPassThrough();
|
|
1948
|
+
return this;
|
|
1949
|
+
}
|
|
1950
|
+
/**
|
|
1951
|
+
* @private
|
|
1952
|
+
*/
|
|
1953
|
+
_checkForBrokenPassThrough() {
|
|
1954
|
+
if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {
|
|
1955
|
+
throw new Error(
|
|
1956
|
+
`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`
|
|
1957
|
+
);
|
|
1958
|
+
}
|
|
1959
|
+
}
|
|
1960
|
+
/**
|
|
1961
|
+
* Whether to store option values as properties on command object,
|
|
1962
|
+
* or store separately (specify false). In both cases the option values can be accessed using .opts().
|
|
1963
|
+
*
|
|
1964
|
+
* @param {boolean} [storeAsProperties=true]
|
|
1965
|
+
* @return {Command} `this` command for chaining
|
|
1966
|
+
*/
|
|
1967
|
+
storeOptionsAsProperties(storeAsProperties = true) {
|
|
1968
|
+
if (this.options.length) {
|
|
1969
|
+
throw new Error("call .storeOptionsAsProperties() before adding options");
|
|
1970
|
+
}
|
|
1971
|
+
if (Object.keys(this._optionValues).length) {
|
|
1972
|
+
throw new Error(
|
|
1973
|
+
"call .storeOptionsAsProperties() before setting option values"
|
|
1974
|
+
);
|
|
1975
|
+
}
|
|
1976
|
+
this._storeOptionsAsProperties = !!storeAsProperties;
|
|
1977
|
+
return this;
|
|
1978
|
+
}
|
|
1979
|
+
/**
|
|
1980
|
+
* Retrieve option value.
|
|
1981
|
+
*
|
|
1982
|
+
* @param {string} key
|
|
1983
|
+
* @return {object} value
|
|
1984
|
+
*/
|
|
1985
|
+
getOptionValue(key) {
|
|
1986
|
+
if (this._storeOptionsAsProperties) {
|
|
1987
|
+
return this[key];
|
|
1988
|
+
}
|
|
1989
|
+
return this._optionValues[key];
|
|
1990
|
+
}
|
|
1991
|
+
/**
|
|
1992
|
+
* Store option value.
|
|
1993
|
+
*
|
|
1994
|
+
* @param {string} key
|
|
1995
|
+
* @param {object} value
|
|
1996
|
+
* @return {Command} `this` command for chaining
|
|
1997
|
+
*/
|
|
1998
|
+
setOptionValue(key, value) {
|
|
1999
|
+
return this.setOptionValueWithSource(key, value, void 0);
|
|
2000
|
+
}
|
|
2001
|
+
/**
|
|
2002
|
+
* Store option value and where the value came from.
|
|
2003
|
+
*
|
|
2004
|
+
* @param {string} key
|
|
2005
|
+
* @param {object} value
|
|
2006
|
+
* @param {string} source - expected values are default/config/env/cli/implied
|
|
2007
|
+
* @return {Command} `this` command for chaining
|
|
2008
|
+
*/
|
|
2009
|
+
setOptionValueWithSource(key, value, source) {
|
|
2010
|
+
if (this._storeOptionsAsProperties) {
|
|
2011
|
+
this[key] = value;
|
|
2012
|
+
} else {
|
|
2013
|
+
this._optionValues[key] = value;
|
|
2014
|
+
}
|
|
2015
|
+
this._optionValueSources[key] = source;
|
|
2016
|
+
return this;
|
|
2017
|
+
}
|
|
2018
|
+
/**
|
|
2019
|
+
* Get source of option value.
|
|
2020
|
+
* Expected values are default | config | env | cli | implied
|
|
2021
|
+
*
|
|
2022
|
+
* @param {string} key
|
|
2023
|
+
* @return {string}
|
|
2024
|
+
*/
|
|
2025
|
+
getOptionValueSource(key) {
|
|
2026
|
+
return this._optionValueSources[key];
|
|
2027
|
+
}
|
|
2028
|
+
/**
|
|
2029
|
+
* Get source of option value. See also .optsWithGlobals().
|
|
2030
|
+
* Expected values are default | config | env | cli | implied
|
|
2031
|
+
*
|
|
2032
|
+
* @param {string} key
|
|
2033
|
+
* @return {string}
|
|
2034
|
+
*/
|
|
2035
|
+
getOptionValueSourceWithGlobals(key) {
|
|
2036
|
+
let source;
|
|
2037
|
+
this._getCommandAndAncestors().forEach((cmd) => {
|
|
2038
|
+
if (cmd.getOptionValueSource(key) !== void 0) {
|
|
2039
|
+
source = cmd.getOptionValueSource(key);
|
|
2040
|
+
}
|
|
2041
|
+
});
|
|
2042
|
+
return source;
|
|
2043
|
+
}
|
|
2044
|
+
/**
|
|
2045
|
+
* Get user arguments from implied or explicit arguments.
|
|
2046
|
+
* Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
|
|
2047
|
+
*
|
|
2048
|
+
* @private
|
|
2049
|
+
*/
|
|
2050
|
+
_prepareUserArgs(argv, parseOptions) {
|
|
2051
|
+
if (argv !== void 0 && !Array.isArray(argv)) {
|
|
2052
|
+
throw new Error("first parameter to parse must be array or undefined");
|
|
2053
|
+
}
|
|
2054
|
+
parseOptions = parseOptions || {};
|
|
2055
|
+
if (argv === void 0 && parseOptions.from === void 0) {
|
|
2056
|
+
if (process2.versions?.electron) {
|
|
2057
|
+
parseOptions.from = "electron";
|
|
2058
|
+
}
|
|
2059
|
+
const execArgv = process2.execArgv ?? [];
|
|
2060
|
+
if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) {
|
|
2061
|
+
parseOptions.from = "eval";
|
|
2062
|
+
}
|
|
2063
|
+
}
|
|
2064
|
+
if (argv === void 0) {
|
|
2065
|
+
argv = process2.argv;
|
|
2066
|
+
}
|
|
2067
|
+
this.rawArgs = argv.slice();
|
|
2068
|
+
let userArgs;
|
|
2069
|
+
switch (parseOptions.from) {
|
|
2070
|
+
case void 0:
|
|
2071
|
+
case "node":
|
|
2072
|
+
this._scriptPath = argv[1];
|
|
2073
|
+
userArgs = argv.slice(2);
|
|
2074
|
+
break;
|
|
2075
|
+
case "electron":
|
|
2076
|
+
if (process2.defaultApp) {
|
|
2077
|
+
this._scriptPath = argv[1];
|
|
2078
|
+
userArgs = argv.slice(2);
|
|
2079
|
+
} else {
|
|
2080
|
+
userArgs = argv.slice(1);
|
|
2081
|
+
}
|
|
2082
|
+
break;
|
|
2083
|
+
case "user":
|
|
2084
|
+
userArgs = argv.slice(0);
|
|
2085
|
+
break;
|
|
2086
|
+
case "eval":
|
|
2087
|
+
userArgs = argv.slice(1);
|
|
2088
|
+
break;
|
|
2089
|
+
default:
|
|
2090
|
+
throw new Error(
|
|
2091
|
+
`unexpected parse option { from: '${parseOptions.from}' }`
|
|
2092
|
+
);
|
|
2093
|
+
}
|
|
2094
|
+
if (!this._name && this._scriptPath)
|
|
2095
|
+
this.nameFromFilename(this._scriptPath);
|
|
2096
|
+
this._name = this._name || "program";
|
|
2097
|
+
return userArgs;
|
|
2098
|
+
}
|
|
2099
|
+
/**
|
|
2100
|
+
* Parse `argv`, setting options and invoking commands when defined.
|
|
2101
|
+
*
|
|
2102
|
+
* Use parseAsync instead of parse if any of your action handlers are async.
|
|
2103
|
+
*
|
|
2104
|
+
* Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
|
|
2105
|
+
*
|
|
2106
|
+
* Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
|
|
2107
|
+
* - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
|
|
2108
|
+
* - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
|
|
2109
|
+
* - `'user'`: just user arguments
|
|
2110
|
+
*
|
|
2111
|
+
* @example
|
|
2112
|
+
* program.parse(); // parse process.argv and auto-detect electron and special node flags
|
|
2113
|
+
* program.parse(process.argv); // assume argv[0] is app and argv[1] is script
|
|
2114
|
+
* program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
|
|
2115
|
+
*
|
|
2116
|
+
* @param {string[]} [argv] - optional, defaults to process.argv
|
|
2117
|
+
* @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron
|
|
2118
|
+
* @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
|
|
2119
|
+
* @return {Command} `this` command for chaining
|
|
2120
|
+
*/
|
|
2121
|
+
parse(argv, parseOptions) {
|
|
2122
|
+
this._prepareForParse();
|
|
2123
|
+
const userArgs = this._prepareUserArgs(argv, parseOptions);
|
|
2124
|
+
this._parseCommand([], userArgs);
|
|
2125
|
+
return this;
|
|
2126
|
+
}
|
|
2127
|
+
/**
|
|
2128
|
+
* Parse `argv`, setting options and invoking commands when defined.
|
|
2129
|
+
*
|
|
2130
|
+
* Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
|
|
2131
|
+
*
|
|
2132
|
+
* Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
|
|
2133
|
+
* - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
|
|
2134
|
+
* - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
|
|
2135
|
+
* - `'user'`: just user arguments
|
|
2136
|
+
*
|
|
2137
|
+
* @example
|
|
2138
|
+
* await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags
|
|
2139
|
+
* await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script
|
|
2140
|
+
* await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
|
|
2141
|
+
*
|
|
2142
|
+
* @param {string[]} [argv]
|
|
2143
|
+
* @param {object} [parseOptions]
|
|
2144
|
+
* @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
|
|
2145
|
+
* @return {Promise}
|
|
2146
|
+
*/
|
|
2147
|
+
async parseAsync(argv, parseOptions) {
|
|
2148
|
+
this._prepareForParse();
|
|
2149
|
+
const userArgs = this._prepareUserArgs(argv, parseOptions);
|
|
2150
|
+
await this._parseCommand([], userArgs);
|
|
2151
|
+
return this;
|
|
2152
|
+
}
|
|
2153
|
+
_prepareForParse() {
|
|
2154
|
+
if (this._savedState === null) {
|
|
2155
|
+
this.saveStateBeforeParse();
|
|
2156
|
+
} else {
|
|
2157
|
+
this.restoreStateBeforeParse();
|
|
2158
|
+
}
|
|
2159
|
+
}
|
|
2160
|
+
/**
|
|
2161
|
+
* Called the first time parse is called to save state and allow a restore before subsequent calls to parse.
|
|
2162
|
+
* Not usually called directly, but available for subclasses to save their custom state.
|
|
2163
|
+
*
|
|
2164
|
+
* This is called in a lazy way. Only commands used in parsing chain will have state saved.
|
|
2165
|
+
*/
|
|
2166
|
+
saveStateBeforeParse() {
|
|
2167
|
+
this._savedState = {
|
|
2168
|
+
// name is stable if supplied by author, but may be unspecified for root command and deduced during parsing
|
|
2169
|
+
_name: this._name,
|
|
2170
|
+
// option values before parse have default values (including false for negated options)
|
|
2171
|
+
// shallow clones
|
|
2172
|
+
_optionValues: { ...this._optionValues },
|
|
2173
|
+
_optionValueSources: { ...this._optionValueSources }
|
|
2174
|
+
};
|
|
2175
|
+
}
|
|
2176
|
+
/**
|
|
2177
|
+
* Restore state before parse for calls after the first.
|
|
2178
|
+
* Not usually called directly, but available for subclasses to save their custom state.
|
|
2179
|
+
*
|
|
2180
|
+
* This is called in a lazy way. Only commands used in parsing chain will have state restored.
|
|
2181
|
+
*/
|
|
2182
|
+
restoreStateBeforeParse() {
|
|
2183
|
+
if (this._storeOptionsAsProperties)
|
|
2184
|
+
throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
|
|
2185
|
+
- either make a new Command for each call to parse, or stop storing options as properties`);
|
|
2186
|
+
this._name = this._savedState._name;
|
|
2187
|
+
this._scriptPath = null;
|
|
2188
|
+
this.rawArgs = [];
|
|
2189
|
+
this._optionValues = { ...this._savedState._optionValues };
|
|
2190
|
+
this._optionValueSources = { ...this._savedState._optionValueSources };
|
|
2191
|
+
this.args = [];
|
|
2192
|
+
this.processedArgs = [];
|
|
2193
|
+
}
|
|
2194
|
+
/**
|
|
2195
|
+
* Throw if expected executable is missing. Add lots of help for author.
|
|
2196
|
+
*
|
|
2197
|
+
* @param {string} executableFile
|
|
2198
|
+
* @param {string} executableDir
|
|
2199
|
+
* @param {string} subcommandName
|
|
2200
|
+
*/
|
|
2201
|
+
_checkForMissingExecutable(executableFile, executableDir, subcommandName) {
|
|
2202
|
+
if (fs.existsSync(executableFile)) return;
|
|
2203
|
+
const executableDirMessage = executableDir ? `searched for local subcommand relative to directory '${executableDir}'` : "no directory for search for local subcommand, use .executableDir() to supply a custom directory";
|
|
2204
|
+
const executableMissing = `'${executableFile}' does not exist
|
|
2205
|
+
- if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
2206
|
+
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
2207
|
+
- ${executableDirMessage}`;
|
|
2208
|
+
throw new Error(executableMissing);
|
|
2209
|
+
}
|
|
2210
|
+
/**
|
|
2211
|
+
* Execute a sub-command executable.
|
|
2212
|
+
*
|
|
2213
|
+
* @private
|
|
2214
|
+
*/
|
|
2215
|
+
_executeSubCommand(subcommand, args) {
|
|
2216
|
+
args = args.slice();
|
|
2217
|
+
let launchWithNode = false;
|
|
2218
|
+
const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
|
|
2219
|
+
function findFile(baseDir, baseName) {
|
|
2220
|
+
const localBin = path.resolve(baseDir, baseName);
|
|
2221
|
+
if (fs.existsSync(localBin)) return localBin;
|
|
2222
|
+
if (sourceExt.includes(path.extname(baseName))) return void 0;
|
|
2223
|
+
const foundExt = sourceExt.find(
|
|
2224
|
+
(ext) => fs.existsSync(`${localBin}${ext}`)
|
|
2225
|
+
);
|
|
2226
|
+
if (foundExt) return `${localBin}${foundExt}`;
|
|
2227
|
+
return void 0;
|
|
2228
|
+
}
|
|
2229
|
+
this._checkForMissingMandatoryOptions();
|
|
2230
|
+
this._checkForConflictingOptions();
|
|
2231
|
+
let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
|
|
2232
|
+
let executableDir = this._executableDir || "";
|
|
2233
|
+
if (this._scriptPath) {
|
|
2234
|
+
let resolvedScriptPath;
|
|
2235
|
+
try {
|
|
2236
|
+
resolvedScriptPath = fs.realpathSync(this._scriptPath);
|
|
2237
|
+
} catch {
|
|
2238
|
+
resolvedScriptPath = this._scriptPath;
|
|
2239
|
+
}
|
|
2240
|
+
executableDir = path.resolve(
|
|
2241
|
+
path.dirname(resolvedScriptPath),
|
|
2242
|
+
executableDir
|
|
2243
|
+
);
|
|
2244
|
+
}
|
|
2245
|
+
if (executableDir) {
|
|
2246
|
+
let localFile = findFile(executableDir, executableFile);
|
|
2247
|
+
if (!localFile && !subcommand._executableFile && this._scriptPath) {
|
|
2248
|
+
const legacyName = path.basename(
|
|
2249
|
+
this._scriptPath,
|
|
2250
|
+
path.extname(this._scriptPath)
|
|
2251
|
+
);
|
|
2252
|
+
if (legacyName !== this._name) {
|
|
2253
|
+
localFile = findFile(
|
|
2254
|
+
executableDir,
|
|
2255
|
+
`${legacyName}-${subcommand._name}`
|
|
2256
|
+
);
|
|
2257
|
+
}
|
|
2258
|
+
}
|
|
2259
|
+
executableFile = localFile || executableFile;
|
|
2260
|
+
}
|
|
2261
|
+
launchWithNode = sourceExt.includes(path.extname(executableFile));
|
|
2262
|
+
let proc;
|
|
2263
|
+
if (process2.platform !== "win32") {
|
|
2264
|
+
if (launchWithNode) {
|
|
2265
|
+
args.unshift(executableFile);
|
|
2266
|
+
args = incrementNodeInspectorPort(process2.execArgv).concat(args);
|
|
2267
|
+
proc = childProcess.spawn(process2.argv[0], args, { stdio: "inherit" });
|
|
2268
|
+
} else {
|
|
2269
|
+
proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
|
|
2270
|
+
}
|
|
2271
|
+
} else {
|
|
2272
|
+
this._checkForMissingExecutable(
|
|
2273
|
+
executableFile,
|
|
2274
|
+
executableDir,
|
|
2275
|
+
subcommand._name
|
|
2276
|
+
);
|
|
2277
|
+
args.unshift(executableFile);
|
|
2278
|
+
args = incrementNodeInspectorPort(process2.execArgv).concat(args);
|
|
2279
|
+
proc = childProcess.spawn(process2.execPath, args, { stdio: "inherit" });
|
|
2280
|
+
}
|
|
2281
|
+
if (!proc.killed) {
|
|
2282
|
+
const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
|
|
2283
|
+
signals.forEach((signal) => {
|
|
2284
|
+
process2.on(signal, () => {
|
|
2285
|
+
if (proc.killed === false && proc.exitCode === null) {
|
|
2286
|
+
proc.kill(signal);
|
|
2287
|
+
}
|
|
2288
|
+
});
|
|
2289
|
+
});
|
|
2290
|
+
}
|
|
2291
|
+
const exitCallback = this._exitCallback;
|
|
2292
|
+
proc.on("close", (code) => {
|
|
2293
|
+
code = code ?? 1;
|
|
2294
|
+
if (!exitCallback) {
|
|
2295
|
+
process2.exit(code);
|
|
2296
|
+
} else {
|
|
2297
|
+
exitCallback(
|
|
2298
|
+
new CommanderError2(
|
|
2299
|
+
code,
|
|
2300
|
+
"commander.executeSubCommandAsync",
|
|
2301
|
+
"(close)"
|
|
2302
|
+
)
|
|
2303
|
+
);
|
|
2304
|
+
}
|
|
2305
|
+
});
|
|
2306
|
+
proc.on("error", (err) => {
|
|
2307
|
+
if (err.code === "ENOENT") {
|
|
2308
|
+
this._checkForMissingExecutable(
|
|
2309
|
+
executableFile,
|
|
2310
|
+
executableDir,
|
|
2311
|
+
subcommand._name
|
|
2312
|
+
);
|
|
2313
|
+
} else if (err.code === "EACCES") {
|
|
2314
|
+
throw new Error(`'${executableFile}' not executable`);
|
|
2315
|
+
}
|
|
2316
|
+
if (!exitCallback) {
|
|
2317
|
+
process2.exit(1);
|
|
2318
|
+
} else {
|
|
2319
|
+
const wrappedError = new CommanderError2(
|
|
2320
|
+
1,
|
|
2321
|
+
"commander.executeSubCommandAsync",
|
|
2322
|
+
"(error)"
|
|
2323
|
+
);
|
|
2324
|
+
wrappedError.nestedError = err;
|
|
2325
|
+
exitCallback(wrappedError);
|
|
2326
|
+
}
|
|
2327
|
+
});
|
|
2328
|
+
this.runningCommand = proc;
|
|
2329
|
+
}
|
|
2330
|
+
/**
|
|
2331
|
+
* @private
|
|
2332
|
+
*/
|
|
2333
|
+
_dispatchSubcommand(commandName, operands, unknown) {
|
|
2334
|
+
const subCommand = this._findCommand(commandName);
|
|
2335
|
+
if (!subCommand) this.help({ error: true });
|
|
2336
|
+
subCommand._prepareForParse();
|
|
2337
|
+
let promiseChain;
|
|
2338
|
+
promiseChain = this._chainOrCallSubCommandHook(
|
|
2339
|
+
promiseChain,
|
|
2340
|
+
subCommand,
|
|
2341
|
+
"preSubcommand"
|
|
2342
|
+
);
|
|
2343
|
+
promiseChain = this._chainOrCall(promiseChain, () => {
|
|
2344
|
+
if (subCommand._executableHandler) {
|
|
2345
|
+
this._executeSubCommand(subCommand, operands.concat(unknown));
|
|
2346
|
+
} else {
|
|
2347
|
+
return subCommand._parseCommand(operands, unknown);
|
|
2348
|
+
}
|
|
2349
|
+
});
|
|
2350
|
+
return promiseChain;
|
|
2351
|
+
}
|
|
2352
|
+
/**
|
|
2353
|
+
* Invoke help directly if possible, or dispatch if necessary.
|
|
2354
|
+
* e.g. help foo
|
|
2355
|
+
*
|
|
2356
|
+
* @private
|
|
2357
|
+
*/
|
|
2358
|
+
_dispatchHelpCommand(subcommandName) {
|
|
2359
|
+
if (!subcommandName) {
|
|
2360
|
+
this.help();
|
|
2361
|
+
}
|
|
2362
|
+
const subCommand = this._findCommand(subcommandName);
|
|
2363
|
+
if (subCommand && !subCommand._executableHandler) {
|
|
2364
|
+
subCommand.help();
|
|
2365
|
+
}
|
|
2366
|
+
return this._dispatchSubcommand(
|
|
2367
|
+
subcommandName,
|
|
2368
|
+
[],
|
|
2369
|
+
[this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]
|
|
2370
|
+
);
|
|
2371
|
+
}
|
|
2372
|
+
/**
|
|
2373
|
+
* Check this.args against expected this.registeredArguments.
|
|
2374
|
+
*
|
|
2375
|
+
* @private
|
|
2376
|
+
*/
|
|
2377
|
+
_checkNumberOfArguments() {
|
|
2378
|
+
this.registeredArguments.forEach((arg, i) => {
|
|
2379
|
+
if (arg.required && this.args[i] == null) {
|
|
2380
|
+
this.missingArgument(arg.name());
|
|
2381
|
+
}
|
|
2382
|
+
});
|
|
2383
|
+
if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
|
|
2384
|
+
return;
|
|
2385
|
+
}
|
|
2386
|
+
if (this.args.length > this.registeredArguments.length) {
|
|
2387
|
+
this._excessArguments(this.args);
|
|
2388
|
+
}
|
|
2389
|
+
}
|
|
2390
|
+
/**
|
|
2391
|
+
* Process this.args using this.registeredArguments and save as this.processedArgs!
|
|
2392
|
+
*
|
|
2393
|
+
* @private
|
|
2394
|
+
*/
|
|
2395
|
+
_processArguments() {
|
|
2396
|
+
const myParseArg = (argument, value, previous) => {
|
|
2397
|
+
let parsedValue = value;
|
|
2398
|
+
if (value !== null && argument.parseArg) {
|
|
2399
|
+
const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
|
|
2400
|
+
parsedValue = this._callParseArg(
|
|
2401
|
+
argument,
|
|
2402
|
+
value,
|
|
2403
|
+
previous,
|
|
2404
|
+
invalidValueMessage
|
|
2405
|
+
);
|
|
2406
|
+
}
|
|
2407
|
+
return parsedValue;
|
|
2408
|
+
};
|
|
2409
|
+
this._checkNumberOfArguments();
|
|
2410
|
+
const processedArgs = [];
|
|
2411
|
+
this.registeredArguments.forEach((declaredArg, index) => {
|
|
2412
|
+
let value = declaredArg.defaultValue;
|
|
2413
|
+
if (declaredArg.variadic) {
|
|
2414
|
+
if (index < this.args.length) {
|
|
2415
|
+
value = this.args.slice(index);
|
|
2416
|
+
if (declaredArg.parseArg) {
|
|
2417
|
+
value = value.reduce((processed, v) => {
|
|
2418
|
+
return myParseArg(declaredArg, v, processed);
|
|
2419
|
+
}, declaredArg.defaultValue);
|
|
2420
|
+
}
|
|
2421
|
+
} else if (value === void 0) {
|
|
2422
|
+
value = [];
|
|
2423
|
+
}
|
|
2424
|
+
} else if (index < this.args.length) {
|
|
2425
|
+
value = this.args[index];
|
|
2426
|
+
if (declaredArg.parseArg) {
|
|
2427
|
+
value = myParseArg(declaredArg, value, declaredArg.defaultValue);
|
|
2428
|
+
}
|
|
2429
|
+
}
|
|
2430
|
+
processedArgs[index] = value;
|
|
2431
|
+
});
|
|
2432
|
+
this.processedArgs = processedArgs;
|
|
2433
|
+
}
|
|
2434
|
+
/**
|
|
2435
|
+
* Once we have a promise we chain, but call synchronously until then.
|
|
2436
|
+
*
|
|
2437
|
+
* @param {(Promise|undefined)} promise
|
|
2438
|
+
* @param {Function} fn
|
|
2439
|
+
* @return {(Promise|undefined)}
|
|
2440
|
+
* @private
|
|
2441
|
+
*/
|
|
2442
|
+
_chainOrCall(promise, fn) {
|
|
2443
|
+
if (promise?.then && typeof promise.then === "function") {
|
|
2444
|
+
return promise.then(() => fn());
|
|
2445
|
+
}
|
|
2446
|
+
return fn();
|
|
2447
|
+
}
|
|
2448
|
+
/**
|
|
2449
|
+
*
|
|
2450
|
+
* @param {(Promise|undefined)} promise
|
|
2451
|
+
* @param {string} event
|
|
2452
|
+
* @return {(Promise|undefined)}
|
|
2453
|
+
* @private
|
|
2454
|
+
*/
|
|
2455
|
+
_chainOrCallHooks(promise, event) {
|
|
2456
|
+
let result = promise;
|
|
2457
|
+
const hooks = [];
|
|
2458
|
+
this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== void 0).forEach((hookedCommand) => {
|
|
2459
|
+
hookedCommand._lifeCycleHooks[event].forEach((callback) => {
|
|
2460
|
+
hooks.push({ hookedCommand, callback });
|
|
2461
|
+
});
|
|
2462
|
+
});
|
|
2463
|
+
if (event === "postAction") {
|
|
2464
|
+
hooks.reverse();
|
|
2465
|
+
}
|
|
2466
|
+
hooks.forEach((hookDetail) => {
|
|
2467
|
+
result = this._chainOrCall(result, () => {
|
|
2468
|
+
return hookDetail.callback(hookDetail.hookedCommand, this);
|
|
2469
|
+
});
|
|
2470
|
+
});
|
|
2471
|
+
return result;
|
|
2472
|
+
}
|
|
2473
|
+
/**
|
|
2474
|
+
*
|
|
2475
|
+
* @param {(Promise|undefined)} promise
|
|
2476
|
+
* @param {Command} subCommand
|
|
2477
|
+
* @param {string} event
|
|
2478
|
+
* @return {(Promise|undefined)}
|
|
2479
|
+
* @private
|
|
2480
|
+
*/
|
|
2481
|
+
_chainOrCallSubCommandHook(promise, subCommand, event) {
|
|
2482
|
+
let result = promise;
|
|
2483
|
+
if (this._lifeCycleHooks[event] !== void 0) {
|
|
2484
|
+
this._lifeCycleHooks[event].forEach((hook) => {
|
|
2485
|
+
result = this._chainOrCall(result, () => {
|
|
2486
|
+
return hook(this, subCommand);
|
|
2487
|
+
});
|
|
2488
|
+
});
|
|
2489
|
+
}
|
|
2490
|
+
return result;
|
|
2491
|
+
}
|
|
2492
|
+
/**
|
|
2493
|
+
* Process arguments in context of this command.
|
|
2494
|
+
* Returns action result, in case it is a promise.
|
|
2495
|
+
*
|
|
2496
|
+
* @private
|
|
2497
|
+
*/
|
|
2498
|
+
_parseCommand(operands, unknown) {
|
|
2499
|
+
const parsed = this.parseOptions(unknown);
|
|
2500
|
+
this._parseOptionsEnv();
|
|
2501
|
+
this._parseOptionsImplied();
|
|
2502
|
+
operands = operands.concat(parsed.operands);
|
|
2503
|
+
unknown = parsed.unknown;
|
|
2504
|
+
this.args = operands.concat(unknown);
|
|
2505
|
+
if (operands && this._findCommand(operands[0])) {
|
|
2506
|
+
return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
|
|
2507
|
+
}
|
|
2508
|
+
if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) {
|
|
2509
|
+
return this._dispatchHelpCommand(operands[1]);
|
|
2510
|
+
}
|
|
2511
|
+
if (this._defaultCommandName) {
|
|
2512
|
+
this._outputHelpIfRequested(unknown);
|
|
2513
|
+
return this._dispatchSubcommand(
|
|
2514
|
+
this._defaultCommandName,
|
|
2515
|
+
operands,
|
|
2516
|
+
unknown
|
|
2517
|
+
);
|
|
2518
|
+
}
|
|
2519
|
+
if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
|
|
2520
|
+
this.help({ error: true });
|
|
2521
|
+
}
|
|
2522
|
+
this._outputHelpIfRequested(parsed.unknown);
|
|
2523
|
+
this._checkForMissingMandatoryOptions();
|
|
2524
|
+
this._checkForConflictingOptions();
|
|
2525
|
+
const checkForUnknownOptions = () => {
|
|
2526
|
+
if (parsed.unknown.length > 0) {
|
|
2527
|
+
this.unknownOption(parsed.unknown[0]);
|
|
2528
|
+
}
|
|
2529
|
+
};
|
|
2530
|
+
const commandEvent = `command:${this.name()}`;
|
|
2531
|
+
if (this._actionHandler) {
|
|
2532
|
+
checkForUnknownOptions();
|
|
2533
|
+
this._processArguments();
|
|
2534
|
+
let promiseChain;
|
|
2535
|
+
promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
|
|
2536
|
+
promiseChain = this._chainOrCall(
|
|
2537
|
+
promiseChain,
|
|
2538
|
+
() => this._actionHandler(this.processedArgs)
|
|
2539
|
+
);
|
|
2540
|
+
if (this.parent) {
|
|
2541
|
+
promiseChain = this._chainOrCall(promiseChain, () => {
|
|
2542
|
+
this.parent.emit(commandEvent, operands, unknown);
|
|
2543
|
+
});
|
|
2544
|
+
}
|
|
2545
|
+
promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
|
|
2546
|
+
return promiseChain;
|
|
2547
|
+
}
|
|
2548
|
+
if (this.parent?.listenerCount(commandEvent)) {
|
|
2549
|
+
checkForUnknownOptions();
|
|
2550
|
+
this._processArguments();
|
|
2551
|
+
this.parent.emit(commandEvent, operands, unknown);
|
|
2552
|
+
} else if (operands.length) {
|
|
2553
|
+
if (this._findCommand("*")) {
|
|
2554
|
+
return this._dispatchSubcommand("*", operands, unknown);
|
|
2555
|
+
}
|
|
2556
|
+
if (this.listenerCount("command:*")) {
|
|
2557
|
+
this.emit("command:*", operands, unknown);
|
|
2558
|
+
} else if (this.commands.length) {
|
|
2559
|
+
this.unknownCommand();
|
|
2560
|
+
} else {
|
|
2561
|
+
checkForUnknownOptions();
|
|
2562
|
+
this._processArguments();
|
|
2563
|
+
}
|
|
2564
|
+
} else if (this.commands.length) {
|
|
2565
|
+
checkForUnknownOptions();
|
|
2566
|
+
this.help({ error: true });
|
|
2567
|
+
} else {
|
|
2568
|
+
checkForUnknownOptions();
|
|
2569
|
+
this._processArguments();
|
|
2570
|
+
}
|
|
2571
|
+
}
|
|
2572
|
+
/**
|
|
2573
|
+
* Find matching command.
|
|
2574
|
+
*
|
|
2575
|
+
* @private
|
|
2576
|
+
* @return {Command | undefined}
|
|
2577
|
+
*/
|
|
2578
|
+
_findCommand(name) {
|
|
2579
|
+
if (!name) return void 0;
|
|
2580
|
+
return this.commands.find(
|
|
2581
|
+
(cmd) => cmd._name === name || cmd._aliases.includes(name)
|
|
2582
|
+
);
|
|
2583
|
+
}
|
|
2584
|
+
/**
|
|
2585
|
+
* Return an option matching `arg` if any.
|
|
2586
|
+
*
|
|
2587
|
+
* @param {string} arg
|
|
2588
|
+
* @return {Option}
|
|
2589
|
+
* @package
|
|
2590
|
+
*/
|
|
2591
|
+
_findOption(arg) {
|
|
2592
|
+
return this.options.find((option) => option.is(arg));
|
|
2593
|
+
}
|
|
2594
|
+
/**
|
|
2595
|
+
* Display an error message if a mandatory option does not have a value.
|
|
2596
|
+
* Called after checking for help flags in leaf subcommand.
|
|
2597
|
+
*
|
|
2598
|
+
* @private
|
|
2599
|
+
*/
|
|
2600
|
+
_checkForMissingMandatoryOptions() {
|
|
2601
|
+
this._getCommandAndAncestors().forEach((cmd) => {
|
|
2602
|
+
cmd.options.forEach((anOption) => {
|
|
2603
|
+
if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === void 0) {
|
|
2604
|
+
cmd.missingMandatoryOptionValue(anOption);
|
|
2605
|
+
}
|
|
2606
|
+
});
|
|
2607
|
+
});
|
|
2608
|
+
}
|
|
2609
|
+
/**
|
|
2610
|
+
* Display an error message if conflicting options are used together in this.
|
|
2611
|
+
*
|
|
2612
|
+
* @private
|
|
2613
|
+
*/
|
|
2614
|
+
_checkForConflictingLocalOptions() {
|
|
2615
|
+
const definedNonDefaultOptions = this.options.filter((option) => {
|
|
2616
|
+
const optionKey = option.attributeName();
|
|
2617
|
+
if (this.getOptionValue(optionKey) === void 0) {
|
|
2618
|
+
return false;
|
|
2619
|
+
}
|
|
2620
|
+
return this.getOptionValueSource(optionKey) !== "default";
|
|
2621
|
+
});
|
|
2622
|
+
const optionsWithConflicting = definedNonDefaultOptions.filter(
|
|
2623
|
+
(option) => option.conflictsWith.length > 0
|
|
2624
|
+
);
|
|
2625
|
+
optionsWithConflicting.forEach((option) => {
|
|
2626
|
+
const conflictingAndDefined = definedNonDefaultOptions.find(
|
|
2627
|
+
(defined) => option.conflictsWith.includes(defined.attributeName())
|
|
2628
|
+
);
|
|
2629
|
+
if (conflictingAndDefined) {
|
|
2630
|
+
this._conflictingOption(option, conflictingAndDefined);
|
|
2631
|
+
}
|
|
2632
|
+
});
|
|
2633
|
+
}
|
|
2634
|
+
/**
|
|
2635
|
+
* Display an error message if conflicting options are used together.
|
|
2636
|
+
* Called after checking for help flags in leaf subcommand.
|
|
2637
|
+
*
|
|
2638
|
+
* @private
|
|
2639
|
+
*/
|
|
2640
|
+
_checkForConflictingOptions() {
|
|
2641
|
+
this._getCommandAndAncestors().forEach((cmd) => {
|
|
2642
|
+
cmd._checkForConflictingLocalOptions();
|
|
2643
|
+
});
|
|
2644
|
+
}
|
|
2645
|
+
/**
|
|
2646
|
+
* Parse options from `argv` removing known options,
|
|
2647
|
+
* and return argv split into operands and unknown arguments.
|
|
2648
|
+
*
|
|
2649
|
+
* Side effects: modifies command by storing options. Does not reset state if called again.
|
|
2650
|
+
*
|
|
2651
|
+
* Examples:
|
|
2652
|
+
*
|
|
2653
|
+
* argv => operands, unknown
|
|
2654
|
+
* --known kkk op => [op], []
|
|
2655
|
+
* op --known kkk => [op], []
|
|
2656
|
+
* sub --unknown uuu op => [sub], [--unknown uuu op]
|
|
2657
|
+
* sub -- --unknown uuu op => [sub --unknown uuu op], []
|
|
2658
|
+
*
|
|
2659
|
+
* @param {string[]} args
|
|
2660
|
+
* @return {{operands: string[], unknown: string[]}}
|
|
2661
|
+
*/
|
|
2662
|
+
parseOptions(args) {
|
|
2663
|
+
const operands = [];
|
|
2664
|
+
const unknown = [];
|
|
2665
|
+
let dest = operands;
|
|
2666
|
+
function maybeOption(arg) {
|
|
2667
|
+
return arg.length > 1 && arg[0] === "-";
|
|
2668
|
+
}
|
|
2669
|
+
const negativeNumberArg = (arg) => {
|
|
2670
|
+
if (!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(arg)) return false;
|
|
2671
|
+
return !this._getCommandAndAncestors().some(
|
|
2672
|
+
(cmd) => cmd.options.map((opt) => opt.short).some((short5) => /^-\d$/.test(short5))
|
|
2673
|
+
);
|
|
2674
|
+
};
|
|
2675
|
+
let activeVariadicOption = null;
|
|
2676
|
+
let activeGroup = null;
|
|
2677
|
+
let i = 0;
|
|
2678
|
+
while (i < args.length || activeGroup) {
|
|
2679
|
+
const arg = activeGroup ?? args[i++];
|
|
2680
|
+
activeGroup = null;
|
|
2681
|
+
if (arg === "--") {
|
|
2682
|
+
if (dest === unknown) dest.push(arg);
|
|
2683
|
+
dest.push(...args.slice(i));
|
|
2684
|
+
break;
|
|
2685
|
+
}
|
|
2686
|
+
if (activeVariadicOption && (!maybeOption(arg) || negativeNumberArg(arg))) {
|
|
2687
|
+
this.emit(`option:${activeVariadicOption.name()}`, arg);
|
|
2688
|
+
continue;
|
|
2689
|
+
}
|
|
2690
|
+
activeVariadicOption = null;
|
|
2691
|
+
if (maybeOption(arg)) {
|
|
2692
|
+
const option = this._findOption(arg);
|
|
2693
|
+
if (option) {
|
|
2694
|
+
if (option.required) {
|
|
2695
|
+
const value = args[i++];
|
|
2696
|
+
if (value === void 0) this.optionMissingArgument(option);
|
|
2697
|
+
this.emit(`option:${option.name()}`, value);
|
|
2698
|
+
} else if (option.optional) {
|
|
2699
|
+
let value = null;
|
|
2700
|
+
if (i < args.length && (!maybeOption(args[i]) || negativeNumberArg(args[i]))) {
|
|
2701
|
+
value = args[i++];
|
|
2702
|
+
}
|
|
2703
|
+
this.emit(`option:${option.name()}`, value);
|
|
2704
|
+
} else {
|
|
2705
|
+
this.emit(`option:${option.name()}`);
|
|
2706
|
+
}
|
|
2707
|
+
activeVariadicOption = option.variadic ? option : null;
|
|
2708
|
+
continue;
|
|
2709
|
+
}
|
|
2710
|
+
}
|
|
2711
|
+
if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
|
|
2712
|
+
const option = this._findOption(`-${arg[1]}`);
|
|
2713
|
+
if (option) {
|
|
2714
|
+
if (option.required || option.optional && this._combineFlagAndOptionalValue) {
|
|
2715
|
+
this.emit(`option:${option.name()}`, arg.slice(2));
|
|
2716
|
+
} else {
|
|
2717
|
+
this.emit(`option:${option.name()}`);
|
|
2718
|
+
activeGroup = `-${arg.slice(2)}`;
|
|
2719
|
+
}
|
|
2720
|
+
continue;
|
|
2721
|
+
}
|
|
2722
|
+
}
|
|
2723
|
+
if (/^--[^=]+=/.test(arg)) {
|
|
2724
|
+
const index = arg.indexOf("=");
|
|
2725
|
+
const option = this._findOption(arg.slice(0, index));
|
|
2726
|
+
if (option && (option.required || option.optional)) {
|
|
2727
|
+
this.emit(`option:${option.name()}`, arg.slice(index + 1));
|
|
2728
|
+
continue;
|
|
2729
|
+
}
|
|
2730
|
+
}
|
|
2731
|
+
if (dest === operands && maybeOption(arg) && !(this.commands.length === 0 && negativeNumberArg(arg))) {
|
|
2732
|
+
dest = unknown;
|
|
2733
|
+
}
|
|
2734
|
+
if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
|
|
2735
|
+
if (this._findCommand(arg)) {
|
|
2736
|
+
operands.push(arg);
|
|
2737
|
+
unknown.push(...args.slice(i));
|
|
2738
|
+
break;
|
|
2739
|
+
} else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
|
|
2740
|
+
operands.push(arg, ...args.slice(i));
|
|
2741
|
+
break;
|
|
2742
|
+
} else if (this._defaultCommandName) {
|
|
2743
|
+
unknown.push(arg, ...args.slice(i));
|
|
2744
|
+
break;
|
|
2745
|
+
}
|
|
2746
|
+
}
|
|
2747
|
+
if (this._passThroughOptions) {
|
|
2748
|
+
dest.push(arg, ...args.slice(i));
|
|
2749
|
+
break;
|
|
2750
|
+
}
|
|
2751
|
+
dest.push(arg);
|
|
2752
|
+
}
|
|
2753
|
+
return { operands, unknown };
|
|
2754
|
+
}
|
|
2755
|
+
/**
|
|
2756
|
+
* Return an object containing local option values as key-value pairs.
|
|
2757
|
+
*
|
|
2758
|
+
* @return {object}
|
|
2759
|
+
*/
|
|
2760
|
+
opts() {
|
|
2761
|
+
if (this._storeOptionsAsProperties) {
|
|
2762
|
+
const result = {};
|
|
2763
|
+
const len = this.options.length;
|
|
2764
|
+
for (let i = 0; i < len; i++) {
|
|
2765
|
+
const key = this.options[i].attributeName();
|
|
2766
|
+
result[key] = key === this._versionOptionName ? this._version : this[key];
|
|
2767
|
+
}
|
|
2768
|
+
return result;
|
|
2769
|
+
}
|
|
2770
|
+
return this._optionValues;
|
|
2771
|
+
}
|
|
2772
|
+
/**
|
|
2773
|
+
* Return an object containing merged local and global option values as key-value pairs.
|
|
2774
|
+
*
|
|
2775
|
+
* @return {object}
|
|
2776
|
+
*/
|
|
2777
|
+
optsWithGlobals() {
|
|
2778
|
+
return this._getCommandAndAncestors().reduce(
|
|
2779
|
+
(combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),
|
|
2780
|
+
{}
|
|
2781
|
+
);
|
|
2782
|
+
}
|
|
2783
|
+
/**
|
|
2784
|
+
* Display error message and exit (or call exitOverride).
|
|
2785
|
+
*
|
|
2786
|
+
* @param {string} message
|
|
2787
|
+
* @param {object} [errorOptions]
|
|
2788
|
+
* @param {string} [errorOptions.code] - an id string representing the error
|
|
2789
|
+
* @param {number} [errorOptions.exitCode] - used with process.exit
|
|
2790
|
+
*/
|
|
2791
|
+
error(message, errorOptions) {
|
|
2792
|
+
this._outputConfiguration.outputError(
|
|
2793
|
+
`${message}
|
|
2794
|
+
`,
|
|
2795
|
+
this._outputConfiguration.writeErr
|
|
2796
|
+
);
|
|
2797
|
+
if (typeof this._showHelpAfterError === "string") {
|
|
2798
|
+
this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
2799
|
+
`);
|
|
2800
|
+
} else if (this._showHelpAfterError) {
|
|
2801
|
+
this._outputConfiguration.writeErr("\n");
|
|
2802
|
+
this.outputHelp({ error: true });
|
|
2803
|
+
}
|
|
2804
|
+
const config = errorOptions || {};
|
|
2805
|
+
const exitCode = config.exitCode || 1;
|
|
2806
|
+
const code = config.code || "commander.error";
|
|
2807
|
+
this._exit(exitCode, code, message);
|
|
2808
|
+
}
|
|
2809
|
+
/**
|
|
2810
|
+
* Apply any option related environment variables, if option does
|
|
2811
|
+
* not have a value from cli or client code.
|
|
2812
|
+
*
|
|
2813
|
+
* @private
|
|
2814
|
+
*/
|
|
2815
|
+
_parseOptionsEnv() {
|
|
2816
|
+
this.options.forEach((option) => {
|
|
2817
|
+
if (option.envVar && option.envVar in process2.env) {
|
|
2818
|
+
const optionKey = option.attributeName();
|
|
2819
|
+
if (this.getOptionValue(optionKey) === void 0 || ["default", "config", "env"].includes(
|
|
2820
|
+
this.getOptionValueSource(optionKey)
|
|
2821
|
+
)) {
|
|
2822
|
+
if (option.required || option.optional) {
|
|
2823
|
+
this.emit(`optionEnv:${option.name()}`, process2.env[option.envVar]);
|
|
2824
|
+
} else {
|
|
2825
|
+
this.emit(`optionEnv:${option.name()}`);
|
|
2826
|
+
}
|
|
2827
|
+
}
|
|
2828
|
+
}
|
|
2829
|
+
});
|
|
2830
|
+
}
|
|
2831
|
+
/**
|
|
2832
|
+
* Apply any implied option values, if option is undefined or default value.
|
|
2833
|
+
*
|
|
2834
|
+
* @private
|
|
2835
|
+
*/
|
|
2836
|
+
_parseOptionsImplied() {
|
|
2837
|
+
const dualHelper = new DualOptions(this.options);
|
|
2838
|
+
const hasCustomOptionValue = (optionKey) => {
|
|
2839
|
+
return this.getOptionValue(optionKey) !== void 0 && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
|
|
2840
|
+
};
|
|
2841
|
+
this.options.filter(
|
|
2842
|
+
(option) => option.implied !== void 0 && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(
|
|
2843
|
+
this.getOptionValue(option.attributeName()),
|
|
2844
|
+
option
|
|
2845
|
+
)
|
|
2846
|
+
).forEach((option) => {
|
|
2847
|
+
Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
|
|
2848
|
+
this.setOptionValueWithSource(
|
|
2849
|
+
impliedKey,
|
|
2850
|
+
option.implied[impliedKey],
|
|
2851
|
+
"implied"
|
|
2852
|
+
);
|
|
2853
|
+
});
|
|
2854
|
+
});
|
|
2855
|
+
}
|
|
2856
|
+
/**
|
|
2857
|
+
* Argument `name` is missing.
|
|
2858
|
+
*
|
|
2859
|
+
* @param {string} name
|
|
2860
|
+
* @private
|
|
2861
|
+
*/
|
|
2862
|
+
missingArgument(name) {
|
|
2863
|
+
const message = `error: missing required argument '${name}'`;
|
|
2864
|
+
this.error(message, { code: "commander.missingArgument" });
|
|
2865
|
+
}
|
|
2866
|
+
/**
|
|
2867
|
+
* `Option` is missing an argument.
|
|
2868
|
+
*
|
|
2869
|
+
* @param {Option} option
|
|
2870
|
+
* @private
|
|
2871
|
+
*/
|
|
2872
|
+
optionMissingArgument(option) {
|
|
2873
|
+
const message = `error: option '${option.flags}' argument missing`;
|
|
2874
|
+
this.error(message, { code: "commander.optionMissingArgument" });
|
|
2875
|
+
}
|
|
2876
|
+
/**
|
|
2877
|
+
* `Option` does not have a value, and is a mandatory option.
|
|
2878
|
+
*
|
|
2879
|
+
* @param {Option} option
|
|
2880
|
+
* @private
|
|
2881
|
+
*/
|
|
2882
|
+
missingMandatoryOptionValue(option) {
|
|
2883
|
+
const message = `error: required option '${option.flags}' not specified`;
|
|
2884
|
+
this.error(message, { code: "commander.missingMandatoryOptionValue" });
|
|
2885
|
+
}
|
|
2886
|
+
/**
|
|
2887
|
+
* `Option` conflicts with another option.
|
|
2888
|
+
*
|
|
2889
|
+
* @param {Option} option
|
|
2890
|
+
* @param {Option} conflictingOption
|
|
2891
|
+
* @private
|
|
2892
|
+
*/
|
|
2893
|
+
_conflictingOption(option, conflictingOption) {
|
|
2894
|
+
const findBestOptionFromValue = (option2) => {
|
|
2895
|
+
const optionKey = option2.attributeName();
|
|
2896
|
+
const optionValue = this.getOptionValue(optionKey);
|
|
2897
|
+
const negativeOption = this.options.find(
|
|
2898
|
+
(target) => target.negate && optionKey === target.attributeName()
|
|
2899
|
+
);
|
|
2900
|
+
const positiveOption = this.options.find(
|
|
2901
|
+
(target) => !target.negate && optionKey === target.attributeName()
|
|
2902
|
+
);
|
|
2903
|
+
if (negativeOption && (negativeOption.presetArg === void 0 && optionValue === false || negativeOption.presetArg !== void 0 && optionValue === negativeOption.presetArg)) {
|
|
2904
|
+
return negativeOption;
|
|
2905
|
+
}
|
|
2906
|
+
return positiveOption || option2;
|
|
2907
|
+
};
|
|
2908
|
+
const getErrorMessage = (option2) => {
|
|
2909
|
+
const bestOption = findBestOptionFromValue(option2);
|
|
2910
|
+
const optionKey = bestOption.attributeName();
|
|
2911
|
+
const source = this.getOptionValueSource(optionKey);
|
|
2912
|
+
if (source === "env") {
|
|
2913
|
+
return `environment variable '${bestOption.envVar}'`;
|
|
2914
|
+
}
|
|
2915
|
+
return `option '${bestOption.flags}'`;
|
|
2916
|
+
};
|
|
2917
|
+
const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
|
|
2918
|
+
this.error(message, { code: "commander.conflictingOption" });
|
|
2919
|
+
}
|
|
2920
|
+
/**
|
|
2921
|
+
* Unknown option `flag`.
|
|
2922
|
+
*
|
|
2923
|
+
* @param {string} flag
|
|
2924
|
+
* @private
|
|
2925
|
+
*/
|
|
2926
|
+
unknownOption(flag) {
|
|
2927
|
+
if (this._allowUnknownOption) return;
|
|
2928
|
+
let suggestion = "";
|
|
2929
|
+
if (flag.startsWith("--") && this._showSuggestionAfterError) {
|
|
2930
|
+
let candidateFlags = [];
|
|
2931
|
+
let command = this;
|
|
2932
|
+
do {
|
|
2933
|
+
const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
|
|
2934
|
+
candidateFlags = candidateFlags.concat(moreFlags);
|
|
2935
|
+
command = command.parent;
|
|
2936
|
+
} while (command && !command._enablePositionalOptions);
|
|
2937
|
+
suggestion = suggestSimilar(flag, candidateFlags);
|
|
2938
|
+
}
|
|
2939
|
+
const message = `error: unknown option '${flag}'${suggestion}`;
|
|
2940
|
+
this.error(message, { code: "commander.unknownOption" });
|
|
2941
|
+
}
|
|
2942
|
+
/**
|
|
2943
|
+
* Excess arguments, more than expected.
|
|
2944
|
+
*
|
|
2945
|
+
* @param {string[]} receivedArgs
|
|
2946
|
+
* @private
|
|
2947
|
+
*/
|
|
2948
|
+
_excessArguments(receivedArgs) {
|
|
2949
|
+
if (this._allowExcessArguments) return;
|
|
2950
|
+
const expected = this.registeredArguments.length;
|
|
2951
|
+
const s = expected === 1 ? "" : "s";
|
|
2952
|
+
const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
|
|
2953
|
+
const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
|
|
2954
|
+
this.error(message, { code: "commander.excessArguments" });
|
|
2955
|
+
}
|
|
2956
|
+
/**
|
|
2957
|
+
* Unknown command.
|
|
2958
|
+
*
|
|
2959
|
+
* @private
|
|
2960
|
+
*/
|
|
2961
|
+
unknownCommand() {
|
|
2962
|
+
const unknownName = this.args[0];
|
|
2963
|
+
let suggestion = "";
|
|
2964
|
+
if (this._showSuggestionAfterError) {
|
|
2965
|
+
const candidateNames = [];
|
|
2966
|
+
this.createHelp().visibleCommands(this).forEach((command) => {
|
|
2967
|
+
candidateNames.push(command.name());
|
|
2968
|
+
if (command.alias()) candidateNames.push(command.alias());
|
|
2969
|
+
});
|
|
2970
|
+
suggestion = suggestSimilar(unknownName, candidateNames);
|
|
2971
|
+
}
|
|
2972
|
+
const message = `error: unknown command '${unknownName}'${suggestion}`;
|
|
2973
|
+
this.error(message, { code: "commander.unknownCommand" });
|
|
2974
|
+
}
|
|
2975
|
+
/**
|
|
2976
|
+
* Get or set the program version.
|
|
2977
|
+
*
|
|
2978
|
+
* This method auto-registers the "-V, --version" option which will print the version number.
|
|
2979
|
+
*
|
|
2980
|
+
* You can optionally supply the flags and description to override the defaults.
|
|
2981
|
+
*
|
|
2982
|
+
* @param {string} [str]
|
|
2983
|
+
* @param {string} [flags]
|
|
2984
|
+
* @param {string} [description]
|
|
2985
|
+
* @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments
|
|
2986
|
+
*/
|
|
2987
|
+
version(str, flags, description) {
|
|
2988
|
+
if (str === void 0) return this._version;
|
|
2989
|
+
this._version = str;
|
|
2990
|
+
flags = flags || "-V, --version";
|
|
2991
|
+
description = description || "output the version number";
|
|
2992
|
+
const versionOption = this.createOption(flags, description);
|
|
2993
|
+
this._versionOptionName = versionOption.attributeName();
|
|
2994
|
+
this._registerOption(versionOption);
|
|
2995
|
+
this.on("option:" + versionOption.name(), () => {
|
|
2996
|
+
this._outputConfiguration.writeOut(`${str}
|
|
2997
|
+
`);
|
|
2998
|
+
this._exit(0, "commander.version", str);
|
|
2999
|
+
});
|
|
3000
|
+
return this;
|
|
3001
|
+
}
|
|
3002
|
+
/**
|
|
3003
|
+
* Set the description.
|
|
3004
|
+
*
|
|
3005
|
+
* @param {string} [str]
|
|
3006
|
+
* @param {object} [argsDescription]
|
|
3007
|
+
* @return {(string|Command)}
|
|
3008
|
+
*/
|
|
3009
|
+
description(str, argsDescription) {
|
|
3010
|
+
if (str === void 0 && argsDescription === void 0)
|
|
3011
|
+
return this._description;
|
|
3012
|
+
this._description = str;
|
|
3013
|
+
if (argsDescription) {
|
|
3014
|
+
this._argsDescription = argsDescription;
|
|
3015
|
+
}
|
|
3016
|
+
return this;
|
|
3017
|
+
}
|
|
3018
|
+
/**
|
|
3019
|
+
* Set the summary. Used when listed as subcommand of parent.
|
|
3020
|
+
*
|
|
3021
|
+
* @param {string} [str]
|
|
3022
|
+
* @return {(string|Command)}
|
|
3023
|
+
*/
|
|
3024
|
+
summary(str) {
|
|
3025
|
+
if (str === void 0) return this._summary;
|
|
3026
|
+
this._summary = str;
|
|
3027
|
+
return this;
|
|
3028
|
+
}
|
|
3029
|
+
/**
|
|
3030
|
+
* Set an alias for the command.
|
|
3031
|
+
*
|
|
3032
|
+
* You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
|
|
3033
|
+
*
|
|
3034
|
+
* @param {string} [alias]
|
|
3035
|
+
* @return {(string|Command)}
|
|
3036
|
+
*/
|
|
3037
|
+
alias(alias) {
|
|
3038
|
+
if (alias === void 0) return this._aliases[0];
|
|
3039
|
+
let command = this;
|
|
3040
|
+
if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
|
|
3041
|
+
command = this.commands[this.commands.length - 1];
|
|
3042
|
+
}
|
|
3043
|
+
if (alias === command._name)
|
|
3044
|
+
throw new Error("Command alias can't be the same as its name");
|
|
3045
|
+
const matchingCommand = this.parent?._findCommand(alias);
|
|
3046
|
+
if (matchingCommand) {
|
|
3047
|
+
const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
|
|
3048
|
+
throw new Error(
|
|
3049
|
+
`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`
|
|
3050
|
+
);
|
|
3051
|
+
}
|
|
3052
|
+
command._aliases.push(alias);
|
|
3053
|
+
return this;
|
|
3054
|
+
}
|
|
3055
|
+
/**
|
|
3056
|
+
* Set aliases for the command.
|
|
3057
|
+
*
|
|
3058
|
+
* Only the first alias is shown in the auto-generated help.
|
|
3059
|
+
*
|
|
3060
|
+
* @param {string[]} [aliases]
|
|
3061
|
+
* @return {(string[]|Command)}
|
|
3062
|
+
*/
|
|
3063
|
+
aliases(aliases) {
|
|
3064
|
+
if (aliases === void 0) return this._aliases;
|
|
3065
|
+
aliases.forEach((alias) => this.alias(alias));
|
|
3066
|
+
return this;
|
|
3067
|
+
}
|
|
3068
|
+
/**
|
|
3069
|
+
* Set / get the command usage `str`.
|
|
3070
|
+
*
|
|
3071
|
+
* @param {string} [str]
|
|
3072
|
+
* @return {(string|Command)}
|
|
3073
|
+
*/
|
|
3074
|
+
usage(str) {
|
|
3075
|
+
if (str === void 0) {
|
|
3076
|
+
if (this._usage) return this._usage;
|
|
3077
|
+
const args = this.registeredArguments.map((arg) => {
|
|
3078
|
+
return humanReadableArgName(arg);
|
|
3079
|
+
});
|
|
3080
|
+
return [].concat(
|
|
3081
|
+
this.options.length || this._helpOption !== null ? "[options]" : [],
|
|
3082
|
+
this.commands.length ? "[command]" : [],
|
|
3083
|
+
this.registeredArguments.length ? args : []
|
|
3084
|
+
).join(" ");
|
|
3085
|
+
}
|
|
3086
|
+
this._usage = str;
|
|
3087
|
+
return this;
|
|
3088
|
+
}
|
|
3089
|
+
/**
|
|
3090
|
+
* Get or set the name of the command.
|
|
3091
|
+
*
|
|
3092
|
+
* @param {string} [str]
|
|
3093
|
+
* @return {(string|Command)}
|
|
3094
|
+
*/
|
|
3095
|
+
name(str) {
|
|
3096
|
+
if (str === void 0) return this._name;
|
|
3097
|
+
this._name = str;
|
|
3098
|
+
return this;
|
|
3099
|
+
}
|
|
3100
|
+
/**
|
|
3101
|
+
* Set/get the help group heading for this subcommand in parent command's help.
|
|
3102
|
+
*
|
|
3103
|
+
* @param {string} [heading]
|
|
3104
|
+
* @return {Command | string}
|
|
3105
|
+
*/
|
|
3106
|
+
helpGroup(heading) {
|
|
3107
|
+
if (heading === void 0) return this._helpGroupHeading ?? "";
|
|
3108
|
+
this._helpGroupHeading = heading;
|
|
3109
|
+
return this;
|
|
3110
|
+
}
|
|
3111
|
+
/**
|
|
3112
|
+
* Set/get the default help group heading for subcommands added to this command.
|
|
3113
|
+
* (This does not override a group set directly on the subcommand using .helpGroup().)
|
|
3114
|
+
*
|
|
3115
|
+
* @example
|
|
3116
|
+
* program.commandsGroup('Development Commands:);
|
|
3117
|
+
* program.command('watch')...
|
|
3118
|
+
* program.command('lint')...
|
|
3119
|
+
* ...
|
|
3120
|
+
*
|
|
3121
|
+
* @param {string} [heading]
|
|
3122
|
+
* @returns {Command | string}
|
|
3123
|
+
*/
|
|
3124
|
+
commandsGroup(heading) {
|
|
3125
|
+
if (heading === void 0) return this._defaultCommandGroup ?? "";
|
|
3126
|
+
this._defaultCommandGroup = heading;
|
|
3127
|
+
return this;
|
|
3128
|
+
}
|
|
3129
|
+
/**
|
|
3130
|
+
* Set/get the default help group heading for options added to this command.
|
|
3131
|
+
* (This does not override a group set directly on the option using .helpGroup().)
|
|
3132
|
+
*
|
|
3133
|
+
* @example
|
|
3134
|
+
* program
|
|
3135
|
+
* .optionsGroup('Development Options:')
|
|
3136
|
+
* .option('-d, --debug', 'output extra debugging')
|
|
3137
|
+
* .option('-p, --profile', 'output profiling information')
|
|
3138
|
+
*
|
|
3139
|
+
* @param {string} [heading]
|
|
3140
|
+
* @returns {Command | string}
|
|
3141
|
+
*/
|
|
3142
|
+
optionsGroup(heading) {
|
|
3143
|
+
if (heading === void 0) return this._defaultOptionGroup ?? "";
|
|
3144
|
+
this._defaultOptionGroup = heading;
|
|
3145
|
+
return this;
|
|
3146
|
+
}
|
|
3147
|
+
/**
|
|
3148
|
+
* @param {Option} option
|
|
3149
|
+
* @private
|
|
3150
|
+
*/
|
|
3151
|
+
_initOptionGroup(option) {
|
|
3152
|
+
if (this._defaultOptionGroup && !option.helpGroupHeading)
|
|
3153
|
+
option.helpGroup(this._defaultOptionGroup);
|
|
3154
|
+
}
|
|
3155
|
+
/**
|
|
3156
|
+
* @param {Command} cmd
|
|
3157
|
+
* @private
|
|
3158
|
+
*/
|
|
3159
|
+
_initCommandGroup(cmd) {
|
|
3160
|
+
if (this._defaultCommandGroup && !cmd.helpGroup())
|
|
3161
|
+
cmd.helpGroup(this._defaultCommandGroup);
|
|
3162
|
+
}
|
|
3163
|
+
/**
|
|
3164
|
+
* Set the name of the command from script filename, such as process.argv[1],
|
|
3165
|
+
* or require.main.filename, or __filename.
|
|
3166
|
+
*
|
|
3167
|
+
* (Used internally and public although not documented in README.)
|
|
3168
|
+
*
|
|
3169
|
+
* @example
|
|
3170
|
+
* program.nameFromFilename(require.main.filename);
|
|
3171
|
+
*
|
|
3172
|
+
* @param {string} filename
|
|
3173
|
+
* @return {Command}
|
|
3174
|
+
*/
|
|
3175
|
+
nameFromFilename(filename) {
|
|
3176
|
+
this._name = path.basename(filename, path.extname(filename));
|
|
3177
|
+
return this;
|
|
3178
|
+
}
|
|
3179
|
+
/**
|
|
3180
|
+
* Get or set the directory for searching for executable subcommands of this command.
|
|
3181
|
+
*
|
|
3182
|
+
* @example
|
|
3183
|
+
* program.executableDir(__dirname);
|
|
3184
|
+
* // or
|
|
3185
|
+
* program.executableDir('subcommands');
|
|
3186
|
+
*
|
|
3187
|
+
* @param {string} [path]
|
|
3188
|
+
* @return {(string|null|Command)}
|
|
3189
|
+
*/
|
|
3190
|
+
executableDir(path2) {
|
|
3191
|
+
if (path2 === void 0) return this._executableDir;
|
|
3192
|
+
this._executableDir = path2;
|
|
3193
|
+
return this;
|
|
3194
|
+
}
|
|
3195
|
+
/**
|
|
3196
|
+
* Return program help documentation.
|
|
3197
|
+
*
|
|
3198
|
+
* @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
|
|
3199
|
+
* @return {string}
|
|
3200
|
+
*/
|
|
3201
|
+
helpInformation(contextOptions) {
|
|
3202
|
+
const helper = this.createHelp();
|
|
3203
|
+
const context = this._getOutputContext(contextOptions);
|
|
3204
|
+
helper.prepareContext({
|
|
3205
|
+
error: context.error,
|
|
3206
|
+
helpWidth: context.helpWidth,
|
|
3207
|
+
outputHasColors: context.hasColors
|
|
3208
|
+
});
|
|
3209
|
+
const text = helper.formatHelp(this, helper);
|
|
3210
|
+
if (context.hasColors) return text;
|
|
3211
|
+
return this._outputConfiguration.stripColor(text);
|
|
3212
|
+
}
|
|
3213
|
+
/**
|
|
3214
|
+
* @typedef HelpContext
|
|
3215
|
+
* @type {object}
|
|
3216
|
+
* @property {boolean} error
|
|
3217
|
+
* @property {number} helpWidth
|
|
3218
|
+
* @property {boolean} hasColors
|
|
3219
|
+
* @property {function} write - includes stripColor if needed
|
|
3220
|
+
*
|
|
3221
|
+
* @returns {HelpContext}
|
|
3222
|
+
* @private
|
|
3223
|
+
*/
|
|
3224
|
+
_getOutputContext(contextOptions) {
|
|
3225
|
+
contextOptions = contextOptions || {};
|
|
3226
|
+
const error = !!contextOptions.error;
|
|
3227
|
+
let baseWrite;
|
|
3228
|
+
let hasColors;
|
|
3229
|
+
let helpWidth;
|
|
3230
|
+
if (error) {
|
|
3231
|
+
baseWrite = (str) => this._outputConfiguration.writeErr(str);
|
|
3232
|
+
hasColors = this._outputConfiguration.getErrHasColors();
|
|
3233
|
+
helpWidth = this._outputConfiguration.getErrHelpWidth();
|
|
3234
|
+
} else {
|
|
3235
|
+
baseWrite = (str) => this._outputConfiguration.writeOut(str);
|
|
3236
|
+
hasColors = this._outputConfiguration.getOutHasColors();
|
|
3237
|
+
helpWidth = this._outputConfiguration.getOutHelpWidth();
|
|
3238
|
+
}
|
|
3239
|
+
const write = (str) => {
|
|
3240
|
+
if (!hasColors) str = this._outputConfiguration.stripColor(str);
|
|
3241
|
+
return baseWrite(str);
|
|
3242
|
+
};
|
|
3243
|
+
return { error, write, hasColors, helpWidth };
|
|
3244
|
+
}
|
|
3245
|
+
/**
|
|
3246
|
+
* Output help information for this command.
|
|
3247
|
+
*
|
|
3248
|
+
* Outputs built-in help, and custom text added using `.addHelpText()`.
|
|
3249
|
+
*
|
|
3250
|
+
* @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
|
|
3251
|
+
*/
|
|
3252
|
+
outputHelp(contextOptions) {
|
|
3253
|
+
let deprecatedCallback;
|
|
3254
|
+
if (typeof contextOptions === "function") {
|
|
3255
|
+
deprecatedCallback = contextOptions;
|
|
3256
|
+
contextOptions = void 0;
|
|
3257
|
+
}
|
|
3258
|
+
const outputContext = this._getOutputContext(contextOptions);
|
|
3259
|
+
const eventContext = {
|
|
3260
|
+
error: outputContext.error,
|
|
3261
|
+
write: outputContext.write,
|
|
3262
|
+
command: this
|
|
3263
|
+
};
|
|
3264
|
+
this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", eventContext));
|
|
3265
|
+
this.emit("beforeHelp", eventContext);
|
|
3266
|
+
let helpInformation = this.helpInformation({ error: outputContext.error });
|
|
3267
|
+
if (deprecatedCallback) {
|
|
3268
|
+
helpInformation = deprecatedCallback(helpInformation);
|
|
3269
|
+
if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
|
|
3270
|
+
throw new Error("outputHelp callback must return a string or a Buffer");
|
|
3271
|
+
}
|
|
3272
|
+
}
|
|
3273
|
+
outputContext.write(helpInformation);
|
|
3274
|
+
if (this._getHelpOption()?.long) {
|
|
3275
|
+
this.emit(this._getHelpOption().long);
|
|
3276
|
+
}
|
|
3277
|
+
this.emit("afterHelp", eventContext);
|
|
3278
|
+
this._getCommandAndAncestors().forEach(
|
|
3279
|
+
(command) => command.emit("afterAllHelp", eventContext)
|
|
3280
|
+
);
|
|
3281
|
+
}
|
|
3282
|
+
/**
|
|
3283
|
+
* You can pass in flags and a description to customise the built-in help option.
|
|
3284
|
+
* Pass in false to disable the built-in help option.
|
|
3285
|
+
*
|
|
3286
|
+
* @example
|
|
3287
|
+
* program.helpOption('-?, --help' 'show help'); // customise
|
|
3288
|
+
* program.helpOption(false); // disable
|
|
3289
|
+
*
|
|
3290
|
+
* @param {(string | boolean)} flags
|
|
3291
|
+
* @param {string} [description]
|
|
3292
|
+
* @return {Command} `this` command for chaining
|
|
3293
|
+
*/
|
|
3294
|
+
helpOption(flags, description) {
|
|
3295
|
+
if (typeof flags === "boolean") {
|
|
3296
|
+
if (flags) {
|
|
3297
|
+
if (this._helpOption === null) this._helpOption = void 0;
|
|
3298
|
+
if (this._defaultOptionGroup) {
|
|
3299
|
+
this._initOptionGroup(this._getHelpOption());
|
|
3300
|
+
}
|
|
3301
|
+
} else {
|
|
3302
|
+
this._helpOption = null;
|
|
3303
|
+
}
|
|
3304
|
+
return this;
|
|
3305
|
+
}
|
|
3306
|
+
this._helpOption = this.createOption(
|
|
3307
|
+
flags ?? "-h, --help",
|
|
3308
|
+
description ?? "display help for command"
|
|
3309
|
+
);
|
|
3310
|
+
if (flags || description) this._initOptionGroup(this._helpOption);
|
|
3311
|
+
return this;
|
|
3312
|
+
}
|
|
3313
|
+
/**
|
|
3314
|
+
* Lazy create help option.
|
|
3315
|
+
* Returns null if has been disabled with .helpOption(false).
|
|
3316
|
+
*
|
|
3317
|
+
* @returns {(Option | null)} the help option
|
|
3318
|
+
* @package
|
|
3319
|
+
*/
|
|
3320
|
+
_getHelpOption() {
|
|
3321
|
+
if (this._helpOption === void 0) {
|
|
3322
|
+
this.helpOption(void 0, void 0);
|
|
3323
|
+
}
|
|
3324
|
+
return this._helpOption;
|
|
3325
|
+
}
|
|
3326
|
+
/**
|
|
3327
|
+
* Supply your own option to use for the built-in help option.
|
|
3328
|
+
* This is an alternative to using helpOption() to customise the flags and description etc.
|
|
3329
|
+
*
|
|
3330
|
+
* @param {Option} option
|
|
3331
|
+
* @return {Command} `this` command for chaining
|
|
3332
|
+
*/
|
|
3333
|
+
addHelpOption(option) {
|
|
3334
|
+
this._helpOption = option;
|
|
3335
|
+
this._initOptionGroup(option);
|
|
3336
|
+
return this;
|
|
3337
|
+
}
|
|
3338
|
+
/**
|
|
3339
|
+
* Output help information and exit.
|
|
3340
|
+
*
|
|
3341
|
+
* Outputs built-in help, and custom text added using `.addHelpText()`.
|
|
3342
|
+
*
|
|
3343
|
+
* @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
|
|
3344
|
+
*/
|
|
3345
|
+
help(contextOptions) {
|
|
3346
|
+
this.outputHelp(contextOptions);
|
|
3347
|
+
let exitCode = Number(process2.exitCode ?? 0);
|
|
3348
|
+
if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
|
|
3349
|
+
exitCode = 1;
|
|
3350
|
+
}
|
|
3351
|
+
this._exit(exitCode, "commander.help", "(outputHelp)");
|
|
3352
|
+
}
|
|
3353
|
+
/**
|
|
3354
|
+
* // Do a little typing to coordinate emit and listener for the help text events.
|
|
3355
|
+
* @typedef HelpTextEventContext
|
|
3356
|
+
* @type {object}
|
|
3357
|
+
* @property {boolean} error
|
|
3358
|
+
* @property {Command} command
|
|
3359
|
+
* @property {function} write
|
|
3360
|
+
*/
|
|
3361
|
+
/**
|
|
3362
|
+
* Add additional text to be displayed with the built-in help.
|
|
3363
|
+
*
|
|
3364
|
+
* Position is 'before' or 'after' to affect just this command,
|
|
3365
|
+
* and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
|
|
3366
|
+
*
|
|
3367
|
+
* @param {string} position - before or after built-in help
|
|
3368
|
+
* @param {(string | Function)} text - string to add, or a function returning a string
|
|
3369
|
+
* @return {Command} `this` command for chaining
|
|
3370
|
+
*/
|
|
3371
|
+
addHelpText(position, text) {
|
|
3372
|
+
const allowedValues = ["beforeAll", "before", "after", "afterAll"];
|
|
3373
|
+
if (!allowedValues.includes(position)) {
|
|
3374
|
+
throw new Error(`Unexpected value for position to addHelpText.
|
|
3375
|
+
Expecting one of '${allowedValues.join("', '")}'`);
|
|
3376
|
+
}
|
|
3377
|
+
const helpEvent = `${position}Help`;
|
|
3378
|
+
this.on(helpEvent, (context) => {
|
|
3379
|
+
let helpStr;
|
|
3380
|
+
if (typeof text === "function") {
|
|
3381
|
+
helpStr = text({ error: context.error, command: context.command });
|
|
3382
|
+
} else {
|
|
3383
|
+
helpStr = text;
|
|
3384
|
+
}
|
|
3385
|
+
if (helpStr) {
|
|
3386
|
+
context.write(`${helpStr}
|
|
3387
|
+
`);
|
|
3388
|
+
}
|
|
3389
|
+
});
|
|
3390
|
+
return this;
|
|
3391
|
+
}
|
|
3392
|
+
/**
|
|
3393
|
+
* Output help information if help flags specified
|
|
3394
|
+
*
|
|
3395
|
+
* @param {Array} args - array of options to search for help flags
|
|
3396
|
+
* @private
|
|
3397
|
+
*/
|
|
3398
|
+
_outputHelpIfRequested(args) {
|
|
3399
|
+
const helpOption = this._getHelpOption();
|
|
3400
|
+
const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
|
|
3401
|
+
if (helpRequested) {
|
|
3402
|
+
this.outputHelp();
|
|
3403
|
+
this._exit(0, "commander.helpDisplayed", "(outputHelp)");
|
|
3404
|
+
}
|
|
3405
|
+
}
|
|
3406
|
+
};
|
|
3407
|
+
function incrementNodeInspectorPort(args) {
|
|
3408
|
+
return args.map((arg) => {
|
|
3409
|
+
if (!arg.startsWith("--inspect")) {
|
|
3410
|
+
return arg;
|
|
3411
|
+
}
|
|
3412
|
+
let debugOption;
|
|
3413
|
+
let debugHost = "127.0.0.1";
|
|
3414
|
+
let debugPort = "9229";
|
|
3415
|
+
let match;
|
|
3416
|
+
if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
|
|
3417
|
+
debugOption = match[1];
|
|
3418
|
+
} else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
|
|
3419
|
+
debugOption = match[1];
|
|
3420
|
+
if (/^\d+$/.test(match[3])) {
|
|
3421
|
+
debugPort = match[3];
|
|
3422
|
+
} else {
|
|
3423
|
+
debugHost = match[3];
|
|
3424
|
+
}
|
|
3425
|
+
} else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
|
|
3426
|
+
debugOption = match[1];
|
|
3427
|
+
debugHost = match[3];
|
|
3428
|
+
debugPort = match[4];
|
|
3429
|
+
}
|
|
3430
|
+
if (debugOption && debugPort !== "0") {
|
|
3431
|
+
return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
|
|
3432
|
+
}
|
|
3433
|
+
return arg;
|
|
3434
|
+
});
|
|
3435
|
+
}
|
|
3436
|
+
function useColor() {
|
|
3437
|
+
if (process2.env.NO_COLOR || process2.env.FORCE_COLOR === "0" || process2.env.FORCE_COLOR === "false")
|
|
3438
|
+
return false;
|
|
3439
|
+
if (process2.env.FORCE_COLOR || process2.env.CLICOLOR_FORCE !== void 0)
|
|
3440
|
+
return true;
|
|
3441
|
+
return void 0;
|
|
3442
|
+
}
|
|
3443
|
+
exports.Command = Command2;
|
|
3444
|
+
exports.useColor = useColor;
|
|
3445
|
+
}
|
|
3446
|
+
});
|
|
3447
|
+
|
|
3448
|
+
// node_modules/commander/index.js
|
|
3449
|
+
var require_commander = __commonJS({
|
|
3450
|
+
"node_modules/commander/index.js"(exports) {
|
|
3451
|
+
var { Argument: Argument2 } = require_argument();
|
|
3452
|
+
var { Command: Command2 } = require_command();
|
|
3453
|
+
var { CommanderError: CommanderError2, InvalidArgumentError: InvalidArgumentError2 } = require_error();
|
|
3454
|
+
var { Help: Help2 } = require_help();
|
|
3455
|
+
var { Option: Option2 } = require_option();
|
|
3456
|
+
exports.program = new Command2();
|
|
3457
|
+
exports.createCommand = (name) => new Command2(name);
|
|
3458
|
+
exports.createOption = (flags, description) => new Option2(flags, description);
|
|
3459
|
+
exports.createArgument = (name, description) => new Argument2(name, description);
|
|
3460
|
+
exports.Command = Command2;
|
|
3461
|
+
exports.Option = Option2;
|
|
3462
|
+
exports.Argument = Argument2;
|
|
3463
|
+
exports.Help = Help2;
|
|
3464
|
+
exports.CommanderError = CommanderError2;
|
|
3465
|
+
exports.InvalidArgumentError = InvalidArgumentError2;
|
|
3466
|
+
exports.InvalidOptionArgumentError = InvalidArgumentError2;
|
|
3467
|
+
}
|
|
3468
|
+
});
|
|
3469
|
+
|
|
3470
|
+
// node_modules/commander/esm.mjs
|
|
3471
|
+
var import_index = __toESM(require_commander(), 1);
|
|
3472
|
+
var {
|
|
3473
|
+
program,
|
|
3474
|
+
createCommand,
|
|
3475
|
+
createArgument,
|
|
3476
|
+
createOption,
|
|
3477
|
+
CommanderError,
|
|
3478
|
+
InvalidArgumentError,
|
|
3479
|
+
InvalidOptionArgumentError,
|
|
3480
|
+
// deprecated old name
|
|
3481
|
+
Command,
|
|
3482
|
+
Argument,
|
|
3483
|
+
Option,
|
|
3484
|
+
Help
|
|
3485
|
+
} = import_index.default;
|
|
3486
|
+
|
|
3487
|
+
// packages/cli/src/ui.ts
|
|
3488
|
+
var E = "\x1B[";
|
|
3489
|
+
var wrap = (open, s, close = "39") => `${E}${open}m${s}${E}${close}m`;
|
|
3490
|
+
var c = {
|
|
3491
|
+
reset: `${E}0m`,
|
|
3492
|
+
bold: (s) => `${E}1m${s}${E}22m`,
|
|
3493
|
+
dim: (s) => `${E}2m${s}${E}22m`,
|
|
3494
|
+
mint: (s) => wrap("38;5;121", s),
|
|
3495
|
+
emerald: (s) => wrap("38;5;48", s),
|
|
3496
|
+
green: (s) => wrap("38;5;42", s),
|
|
3497
|
+
teal: (s) => wrap("38;5;43", s),
|
|
3498
|
+
cyan: (s) => wrap("38;5;51", s),
|
|
3499
|
+
deep: (s) => wrap("38;5;30", s),
|
|
3500
|
+
gray: (s) => wrap("38;5;245", s),
|
|
3501
|
+
white: (s) => wrap("38;5;231", s),
|
|
3502
|
+
amber: (s) => wrap("38;5;215", s),
|
|
3503
|
+
red: (s) => wrap("38;5;203", s)
|
|
3504
|
+
};
|
|
3505
|
+
var TAGS = {
|
|
3506
|
+
INFO: c.cyan,
|
|
3507
|
+
OK: c.green,
|
|
3508
|
+
CHAIN: c.emerald,
|
|
3509
|
+
WARN: c.amber,
|
|
3510
|
+
ERR: c.red,
|
|
3511
|
+
STEP: c.gray
|
|
3512
|
+
};
|
|
3513
|
+
function line(tag, msg, extra) {
|
|
3514
|
+
const tail = extra ? " " + Object.entries(extra).map(([k, v]) => c.gray(k + "=") + c.white(String(v))).join(" ") : "";
|
|
3515
|
+
console.log(`${c.emerald("\u2B22")} ${c.bold(TAGS[tag](tag.padEnd(5)))} ${msg}${tail}`);
|
|
3516
|
+
}
|
|
3517
|
+
var log = {
|
|
3518
|
+
info: (m, x) => line("INFO", m, x),
|
|
3519
|
+
ok: (m, x) => line("OK", m, x),
|
|
3520
|
+
chain: (m, x) => line("CHAIN", m, x),
|
|
3521
|
+
warn: (m, x) => line("WARN", m, x),
|
|
3522
|
+
err: (m, x) => line("ERR", m, x),
|
|
3523
|
+
step: (m, x) => line("STEP", m, x)
|
|
3524
|
+
};
|
|
3525
|
+
var ART = [[["\u2588\u2588\u2588\u2588\u2588\u2588\u2557 ", "cyan"], ["\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557", "mint"], [" \u2588\u2588\u2588\u2588\u2588\u2557 ", "emerald"], ["\u2588\u2588\u2588\u2588\u2588\u2588\u2557 ", "teal"], ["\u2588\u2588\u2588\u2588\u2588\u2588\u2557 ", "green"]], [["\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557", "cyan"], ["\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D", "mint"], ["\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557", "emerald"], ["\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557", "teal"], ["\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557", "green"]], [["\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D", "cyan"], ["\u2588\u2588\u2588\u2588\u2588\u2557 ", "mint"], ["\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551", "emerald"], ["\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D", "teal"], ["\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D", "green"]], [["\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557", "cyan"], ["\u2588\u2588\u2554\u2550\u2550\u255D ", "mint"], ["\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551", "emerald"], ["\u2588\u2588\u2554\u2550\u2550\u2550\u255D ", "teal"], ["\u2588\u2588\u2554\u2550\u2550\u2550\u255D ", "green"]], [["\u2588\u2588\u2551 \u2588\u2588\u2551", "cyan"], ["\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557", "mint"], ["\u2588\u2588\u2551 \u2588\u2588\u2551", "emerald"], ["\u2588\u2588\u2551 ", "teal"], ["\u2588\u2588\u2551 ", "green"]], [["\u255A\u2550\u255D \u255A\u2550\u255D", "cyan"], ["\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D", "mint"], ["\u255A\u2550\u255D \u255A\u2550\u255D", "emerald"], ["\u255A\u2550\u255D ", "teal"], ["\u255A\u2550\u255D ", "green"]]];
|
|
3526
|
+
function banner() {
|
|
3527
|
+
const paint = (col, t) => c[col](t);
|
|
3528
|
+
const art = ART.map((row) => " " + row.map(([t, col]) => paint(col, t)).join("")).join("\n");
|
|
3529
|
+
const tag = " " + c.dim("agent payments") + c.emerald(" \xB7 ") + c.dim("enforced on-chain") + c.emerald(" \xB7 ") + c.dim("stellar testnet");
|
|
3530
|
+
return art + "\n" + tag;
|
|
3531
|
+
}
|
|
3532
|
+
|
|
3533
|
+
// packages/cli/src/config.ts
|
|
3534
|
+
import { readFileSync, writeFileSync, existsSync } from "node:fs";
|
|
3535
|
+
import { resolve } from "node:path";
|
|
3536
|
+
|
|
3537
|
+
// packages/stellar/dist/index.js
|
|
3538
|
+
var dist_exports = {};
|
|
3539
|
+
__export(dist_exports, {
|
|
3540
|
+
Client: () => Client,
|
|
3541
|
+
DEPLOYMENTS: () => DEPLOYMENTS,
|
|
3542
|
+
Errors: () => Errors,
|
|
3543
|
+
TESTNET: () => TESTNET,
|
|
3544
|
+
contract: () => contract,
|
|
3545
|
+
keypairSigner: () => keypairSigner,
|
|
3546
|
+
networks: () => networks,
|
|
3547
|
+
registryClient: () => registryClient,
|
|
3548
|
+
rpc: () => rpc,
|
|
3549
|
+
token: () => token_exports
|
|
3550
|
+
});
|
|
3551
|
+
|
|
3552
|
+
// packages/stellar/dist/deployments.js
|
|
3553
|
+
var DEPLOYMENTS = {
|
|
3554
|
+
testnet: {
|
|
3555
|
+
/** Deployed MandateRegistry contract id. */
|
|
3556
|
+
mandateRegistryId: "CBALARHTO5D7JLWHZ5KST4QNIRC64JI5H3DQDHMIUBSRLLOVS6FCWOQX",
|
|
3557
|
+
/** Native XLM Stellar Asset Contract — a real SEP-41 token. */
|
|
3558
|
+
nativeSac: "CDLZFC3SYJYDZT7K67VZ75HPJVIEUVNIXF47ZG2FB2RMQQVU2HHGCYSC"
|
|
3559
|
+
}
|
|
3560
|
+
};
|
|
3561
|
+
|
|
3562
|
+
// packages/stellar/dist/client.js
|
|
3563
|
+
var client_exports = {};
|
|
3564
|
+
__export(client_exports, {
|
|
3565
|
+
Client: () => Client,
|
|
3566
|
+
Errors: () => Errors,
|
|
3567
|
+
contract: () => contract,
|
|
3568
|
+
networks: () => networks,
|
|
3569
|
+
rpc: () => rpc
|
|
3570
|
+
});
|
|
3571
|
+
import { Buffer as Buffer2 } from "buffer";
|
|
3572
|
+
__reExport(client_exports, stellar_sdk_star);
|
|
3573
|
+
import { Client as ContractClient, Spec as ContractSpec } from "@stellar/stellar-sdk/contract";
|
|
3574
|
+
import * as stellar_sdk_star from "@stellar/stellar-sdk";
|
|
3575
|
+
import * as contract from "@stellar/stellar-sdk/contract";
|
|
3576
|
+
import * as rpc from "@stellar/stellar-sdk/rpc";
|
|
3577
|
+
if (typeof window !== "undefined") {
|
|
3578
|
+
window.Buffer = window.Buffer || Buffer2;
|
|
3579
|
+
}
|
|
3580
|
+
var networks = {
|
|
3581
|
+
testnet: {
|
|
3582
|
+
networkPassphrase: "Test SDF Network ; September 2015",
|
|
3583
|
+
contractId: DEPLOYMENTS.testnet.mandateRegistryId
|
|
3584
|
+
}
|
|
3585
|
+
};
|
|
3586
|
+
var Errors = {
|
|
3587
|
+
1: { message: "AlreadyExists" },
|
|
3588
|
+
2: { message: "NotFound" },
|
|
3589
|
+
4: { message: "MandateExpired" },
|
|
3590
|
+
5: { message: "MandateRevoked" },
|
|
3591
|
+
6: { message: "BudgetExceeded" },
|
|
3592
|
+
7: { message: "MerchantOutOfScope" },
|
|
3593
|
+
8: { message: "BadSequence" },
|
|
3594
|
+
9: { message: "InvalidAmount" },
|
|
3595
|
+
11: { message: "PoolNotFound" },
|
|
3596
|
+
12: { message: "PoolNotOpen" },
|
|
3597
|
+
13: { message: "ScheduleInvalid" },
|
|
3598
|
+
14: { message: "PoolMerchantMismatch" },
|
|
3599
|
+
15: { message: "PoolAssetMismatch" },
|
|
3600
|
+
16: { message: "DeadlinePassed" },
|
|
3601
|
+
/**
|
|
3602
|
+
* Reserved for outcome-style reporting; the abort branch is a success
|
|
3603
|
+
* (state flip + event), not an error.
|
|
3604
|
+
*/
|
|
3605
|
+
17: { message: "ThresholdNotMet" },
|
|
3606
|
+
18: { message: "PoolFull" },
|
|
3607
|
+
19: { message: "BadPoolState" },
|
|
3608
|
+
20: { message: "MandatePooled" },
|
|
3609
|
+
21: { message: "InsufficientFunds" },
|
|
3610
|
+
22: { message: "KindNotSupported" },
|
|
3611
|
+
25: { message: "NotPooled" },
|
|
3612
|
+
26: { message: "ExpiryBeforeDeadline" },
|
|
3613
|
+
27: { message: "BelowMinChild" },
|
|
3614
|
+
28: { message: "DuplicateMember" },
|
|
3615
|
+
29: { message: "DeadlineNotReached" },
|
|
3616
|
+
30: { message: "DeadlineTooFar" },
|
|
3617
|
+
31: { message: "MemberStillEligible" }
|
|
3618
|
+
};
|
|
3619
|
+
var Client = class extends ContractClient {
|
|
3620
|
+
options;
|
|
3621
|
+
static async deploy(options) {
|
|
3622
|
+
return ContractClient.deploy(null, options);
|
|
3623
|
+
}
|
|
3624
|
+
constructor(options) {
|
|
3625
|
+
super(new ContractSpec([
|
|
3626
|
+
"AAAAAAAAACVSZWFkLW9ubHkgYWNjZXNzb3IgZm9yIGEgc3RvcmVkIHBvb2wuAAAAAAAACGdldF9wb29sAAAAAQAAAAAAAAAHcG9vbF9pZAAAAAPuAAAAIAAAAAEAAAPpAAAH0AAAAAxDbGVhcmluZ1Bvb2wAAAAD",
|
|
3627
|
+
"AAAAAAAAAN9DbG9zZSB0aGUgZGVhZGxpbmUgYXVjdGlvbjogY2FwdHVyZSAoYWxsIGxlZ3MgaW4gdGhpcyBvbmUgdHJhbnNhY3Rpb24pCmlmIHRoZSB0aHJlc2hvbGQgcHJlZGljYXRlIGhvbGRzIHdpdGhpbiB0aGUgY2FwdHVyZSB3aW5kb3csIGVsc2UgYWJvcnQKYW5kIHJlbGVhc2UgZXZlcnkgY29tbWl0dGVkIGNoaWxkLiBDYWxsYWJsZSBieSBhbnlvbmUsIG5ldmVyIGJlZm9yZQp0aGUgZGVhZGxpbmUuAAAAAApjbGVhcl9wb29sAAAAAAABAAAAAAAAAAdwb29sX2lkAAAAA+4AAAAgAAAAAQAAA+kAAAPtAAAAAAAAAAM=",
|
|
3628
|
+
"AAAAAAAAAHNSZW1vdmUgYW4gb2JqZWN0aXZlbHktaW5lbGlnaWJsZSBtZW1iZXIgYW5kIGZyZWUgaXRzIHNsb3QuClBlcm1pc3Npb25sZXNzOyBjYW4gbmV2ZXIgZXZpY3QgYSBzdGlsbC1lbGlnaWJsZSBtZW1iZXIuAAAAAAtldmljdF9jaGlsZAAAAAACAAAAAAAAAAdwb29sX2lkAAAAA+4AAAAgAAAAAAAAAAptYW5kYXRlX2lkAAAAAAPuAAAAIAAAAAEAAAPpAAAD7QAAAAAAAAAD",
|
|
3629
|
+
"AAAAAAAAAD5SZWFkLW9ubHkgYWNjZXNzb3IgZm9yIHRoZSBzdG9yZWQgbWFuZGF0ZSAoYXVkaXQgLyBwcmVmbGlnaHQpLgAAAAAAC2dldF9tYW5kYXRlAAAAAAEAAAAAAAAACm1hbmRhdGVfaWQAAAAAA+4AAAAgAAAAAQAAA+kAAAfQAAAAB01hbmRhdGUAAAAAAw==",
|
|
3630
|
+
"AAAAAAAAAIBMaW5rIGEgcG9vbGVkIG1hbmRhdGUgaW50byBpdHMgcG9vbCBhcyBhIENvbW1pdHRlZCBtZW1iZXIuClBlcm1pc3Npb25sZXNzIChvYmplY3RpdmUgY2hlY2tzIG9ubHkpOyByZXZvY2FibGUgdW50aWwgdGhlIGRlYWRsaW5lLgAAAAxjb21taXRfY2hpbGQAAAABAAAAAAAAAAptYW5kYXRlX2lkAAAAAAPuAAAAIAAAAAEAAAPpAAAD7QAAAAAAAAAD",
|
|
3631
|
+
"AAAAAAAAAQxSZWdpc3RlciBhIGNsZWFyaW5nIHBvb2wuIFRoZSByZXR1cm5lZCBwb29sIGlkIGlzIGRlcml2ZWQgZnJvbSB0aGUKdGVybXMgKHNoYTI1NiBvZiB0aGVpciBYRFIpLCBzbyB0aGUgaWQgY29tbWl0cyB0byB0aGUgdGVybXMuCkF1dGhvcml6ZWQgYnkgYG9yaWdpbmF0b3JgIOKAlCB0aGUgbGFzdCBzcGVjaWFsIHNpZ25hdHVyZSB0aGUgcG9vbCBldmVyCnJlcXVpcmVzOiBldmVyeXRoaW5nIGFmdGVyIHRoaXMgaXMgcGVybWlzc2lvbmxlc3MgYW5kIGRldGVybWluaXN0aWMuAAAADXJlZ2lzdGVyX3Bvb2wAAAAAAAAJAAAAAAAAAApvcmlnaW5hdG9yAAAAAAATAAAAAAAAAAhtZXJjaGFudAAAABMAAAAAAAAABWFzc2V0AAAAAAAAEwAAAAAAAAAEa2luZAAAB9AAAAAMQ2xlYXJpbmdLaW5kAAAAAAAAAA10aHJlc2hvbGRfcXR5AAAAAAAACgAAAAAAAAAPdGhyZXNob2xkX3ZhbHVlAAAAAAoAAAAAAAAAD21pbl9jaGlsZF92YWx1ZQAAAAAKAAAAAAAAABFjbGVhcmluZ19kZWFkbGluZQAAAAAAAAYAAAAAAAAABW5vbmNlAAAAAAAD7gAAACAAAAABAAAD6QAAA+4AAAAgAAAAAw==",
|
|
3632
|
+
"AAAAAAAAAJVVc2VyIHdpdGhkcmF3cyBjb25zZW50OyBtYXJrcyB0aGUgbWFuZGF0ZSBSZXZva2VkLiBBdXRob3JpemVkIGJ5IHRoZQp1c2VyLiBBbHNvIGZyZWVzIHRoZSBwb29sIHNsb3Qgb2YgYSBDb21taXR0ZWQgY2hpbGQgKGl0cyBvbmUKcHJlLWRlYWRsaW5lIGV4aXQpLgAAAAAAAA5yZXZva2VfbWFuZGF0ZQAAAAAAAQAAAAAAAAAKbWFuZGF0ZV9pZAAAAAAD7gAAACAAAAABAAAD6QAAA+0AAAAAAAAAAw==",
|
|
3633
|
+
"AAAAAAAAAM1SZWFkLW9ubHk6IHRoZSBleGFjdCBvdXRjb21lIGBjbGVhcl9wb29sYCB3b3VsZCBleGVjdXRlIGFnYWluc3QgY3VycmVudApsZWRnZXIgc3RhdGUuIFNhbWUgYnVpbGRlciwgc2FtZSBjbGVhcmluZyBmdW5jdGlvbiDigJQgcmVjb21wdXRlIHRoaXMgdG8KdmVyaWZ5IHRoZSBvcmlnaW5hdG9yIGhhZCBubyBkaXNjcmV0aW9uIG92ZXIgdGhlIGFsbG9jYXRpb24uAAAAAAAADnNpbXVsYXRlX2NsZWFyAAAAAAABAAAAAAAAAAdwb29sX2lkAAAAA+4AAAAgAAAAAQAAA+kAAAfQAAAADENsZWFyT3V0Y29tZQAAAAM=",
|
|
3634
|
+
"AAAAAAAAAV1UaGUgc29sbyBtb25leSBwYXRoLiBBdG9taWM6IHJlcXVpcmVfYXV0aChhZ2VudCkg4oaSIHJlcGxheSBndWFyZAooYGV4cGVjdGVkX3NlcWAgPT0gY3VycmVudCBgc2VxYCwgZWxzZSBgQmFkU2VxdWVuY2VgKSDihpIgcmUtdmFsaWRhdGUg4oaSCmFkdmFuY2Ugc3BlbnQrc2VxIOKGkiBTRVAtNDEgdHJhbnNmZXJfZnJvbSh1c2VyIOKGkiBtZXJjaGFudCkuIFJldmVydHMgb24gYW55CmZhaWx1cmUuIGBleHBlY3RlZF9zZXFgIGlzIHRoZSBtYW5kYXRlJ3MgY3VycmVudCBzZXF1ZW5jZSAocmVhZCBmcm9tCmBnZXRfbWFuZGF0ZWApLCBwcmV2ZW50aW5nIGR1cGxpY2F0ZS9vdXQtb2Ytb3JkZXIgY29uc3VtcHRpb24uAAAAAAAAD2V4ZWN1dGVfcGF5bWVudAAAAAADAAAAAAAAAAptYW5kYXRlX2lkAAAAAAPuAAAAIAAAAAAAAAAGYW1vdW50AAAAAAALAAAAAAAAAAxleHBlY3RlZF9zZXEAAAAEAAAAAQAAA+kAAAPtAAAAAAAAAAM=",
|
|
3635
|
+
"AAAAAAAAAFdSZWFkLW9ubHk6IGN1cnJlbnQgbWVtYmVyIG1hbmRhdGUgaWRzIChjb21taXQgb3JkZXI7IGZyb3plbiBvbmNlIHRoZQpwb29sIGlzIHRlcm1pbmFsKS4AAAAAEGdldF9wb29sX21lbWJlcnMAAAABAAAAAAAAAAdwb29sX2lkAAAAA+4AAAAgAAAAAQAAA+kAAAPqAAAD7gAAACAAAAAD",
|
|
3636
|
+
"AAAAAAAAAbZTdG9yZSBhIHVzZXItc2lnbmVkIG1hbmRhdGUgZnJvbSBpdHMgYXV0aG9yaXplZCBwYXJhbWV0ZXJzLiBUaGUgY29udHJhY3QKc2V0cyBgc3BlbnQ9MCwgc2VxPTAsIHN0YXR1cz1BY3RpdmVgIGl0c2VsZi4gQXV0aG9yaXplZCBieSBgdXNlcmAuClJldHVybnMgdGhlIG1hbmRhdGUgaWQgKD0gYHZjX2hhc2hgLCB0aGUgc3RvcmFnZSBrZXkpLgoKYHBvb2xfaWQgPSBOb25lYCArIGVtcHR5IGBwcmljZV9zY2hlZHVsZWAgPT0gYSBzdGFuZGFsb25lIG1hbmRhdGUKKHRoZSBwcmUtY29tcG9zaXRlIGJlaGF2aW9yLCB1bmNoYW5nZWQpLiBgcG9vbF9pZCA9IFNvbWUoaWQpYCBiaW5kcyB0aGUKbWFuZGF0ZSB0byBhIGNsZWFyaW5nIHBvb2w7IHRoZSBzY2hlZHVsZSBpcyB0aGUgdXNlcidzIGF1dGhvcml6YXRpb24KZm9yIHRoZSBwb29sIHBhdGggKHNlZSBgcmVnaXN0cnlgKS4AAAAAABByZWdpc3Rlcl9tYW5kYXRlAAAACQAAAAAAAAAEdXNlcgAAABMAAAAAAAAABWFnZW50AAAAAAAAEwAAAAAAAAAIbWVyY2hhbnQAAAATAAAAAAAAAAVhc3NldAAAAAAAABMAAAAAAAAACm1heF9hbW91bnQAAAAAAAsAAAAAAAAABmV4cGlyeQAAAAAABgAAAAAAAAAHdmNfaGFzaAAAAAPuAAAAIAAAAAAAAAAHcG9vbF9pZAAAAAPoAAAD7gAAACAAAAAAAAAADnByaWNlX3NjaGVkdWxlAAAAAAPqAAAH0AAAAA1TY2hlZHVsZVBvaW50AAAAAAAAAQAAA+kAAAPuAAAAIAAAAAM=",
|
|
3637
|
+
"AAAAAAAAAURSZWFkLW9ubHkgcHJlZmxpZ2h0IOKAlCB3b3VsZCB0aGlzIHNwZW5kIGJlIHBlcm1pdHRlZCByaWdodCBub3c/IE11dGF0ZXMKbm90aGluZyBhbmQgcmVxdWlyZXMgbm8gYXV0aDsgdGhlIGF1dGhvcml0YXRpdmUgY29uc3VtZSBoYXBwZW5zIG9ubHkgaW4KYGV4ZWN1dGVfcGF5bWVudGAuIChJdCBpcyBhIGRyeS1ydW47IGl0IGNvbnN1bWVzIG5vdGhpbmcuKSBSZWZsZWN0cwpwb29sIHN0YXRlIHRvbzogYSBDb21taXR0ZWQvQ2FwdHVyZWQgY2hpbGQgcHJlZmxpZ2h0cyBgTWFuZGF0ZVBvb2xlZGAsCmV4YWN0bHkgd2hhdCBgZXhlY3V0ZV9wYXltZW50YCB3b3VsZCBkby4AAAAQdmFsaWRhdGVfbWFuZGF0ZQAAAAMAAAAAAAAACm1hbmRhdGVfaWQAAAAAA+4AAAAgAAAAAAAAAAZhbW91bnQAAAAAAAsAAAAAAAAACG1lcmNoYW50AAAAEwAAAAEAAAPpAAAD7QAAAAAAAAAD",
|
|
3638
|
+
"AAAABAAAAAAAAAAAAAAABUVycm9yAAAAAAAAGwAAAAAAAAANQWxyZWFkeUV4aXN0cwAAAAAAAAEAAAAAAAAACE5vdEZvdW5kAAAAAgAAAAAAAAAOTWFuZGF0ZUV4cGlyZWQAAAAAAAQAAAAAAAAADk1hbmRhdGVSZXZva2VkAAAAAAAFAAAAAAAAAA5CdWRnZXRFeGNlZWRlZAAAAAAABgAAAAAAAAASTWVyY2hhbnRPdXRPZlNjb3BlAAAAAAAHAAAAAAAAAAtCYWRTZXF1ZW5jZQAAAAAIAAAAAAAAAA1JbnZhbGlkQW1vdW50AAAAAAAACQAAAAAAAAAMUG9vbE5vdEZvdW5kAAAACwAAAAAAAAALUG9vbE5vdE9wZW4AAAAADAAAAAAAAAAPU2NoZWR1bGVJbnZhbGlkAAAAAA0AAAAAAAAAFFBvb2xNZXJjaGFudE1pc21hdGNoAAAADgAAAAAAAAARUG9vbEFzc2V0TWlzbWF0Y2gAAAAAAAAPAAAAAAAAAA5EZWFkbGluZVBhc3NlZAAAAAAAEAAAAGdSZXNlcnZlZCBmb3Igb3V0Y29tZS1zdHlsZSByZXBvcnRpbmc7IHRoZSBhYm9ydCBicmFuY2ggaXMgYSBzdWNjZXNzCihzdGF0ZSBmbGlwICsgZXZlbnQpLCBub3QgYW4gZXJyb3IuAAAAAA9UaHJlc2hvbGROb3RNZXQAAAAAEQAAAAAAAAAIUG9vbEZ1bGwAAAASAAAAAAAAAAxCYWRQb29sU3RhdGUAAAATAAAAAAAAAA1NYW5kYXRlUG9vbGVkAAAAAAAAFAAAAAAAAAARSW5zdWZmaWNpZW50RnVuZHMAAAAAAAAVAAAAAAAAABBLaW5kTm90U3VwcG9ydGVkAAAAFgAAAAAAAAAJTm90UG9vbGVkAAAAAAAAGQAAAAAAAAAURXhwaXJ5QmVmb3JlRGVhZGxpbmUAAAAaAAAAAAAAAA1CZWxvd01pbkNoaWxkAAAAAAAAGwAAAAAAAAAPRHVwbGljYXRlTWVtYmVyAAAAABwAAAAAAAAAEkRlYWRsaW5lTm90UmVhY2hlZAAAAAAAHQAAAAAAAAAORGVhZGxpbmVUb29GYXIAAAAAAB4AAAAAAAAAE01lbWJlclN0aWxsRWxpZ2libGUAAAAAHw==",
|
|
3639
|
+
"AAAAAgAAAAAAAAAAAAAABlN0YXR1cwAAAAAAAwAAAAAAAAAAAAAABkFjdGl2ZQAAAAAAAAAAAAAAAAAHUmV2b2tlZAAAAAAAAAAAAAAAAAlFeGhhdXN0ZWQAAAA=",
|
|
3640
|
+
"AAAAAQAAAAAAAAAAAAAAB01hbmRhdGUAAAAADQAAADdUaGUgT05MWSBwcmluY2lwYWwgcGVybWl0dGVkIHRvIGNhbGwgYGV4ZWN1dGVfcGF5bWVudGAuAAAAAAVhZ2VudAAAAAAAABMAAAArU0VQLTQxIC8gU0FDIGNvbnRyYWN0IGlkIChVU0RDIG9uIHRlc3RuZXQpLgAAAAAFYXNzZXQAAAAAAAATAAAAQUxlZGdlciBjbG9zZSB0aW1lc3RhbXAgKHNlY29uZHMpIGFmdGVyIHdoaWNoIHRoZSBtYW5kYXRlIGlzIGRlYWQuAAAAAAAABmV4cGlyeQAAAAAABgAAACdUb3RhbCBidWRnZXQgYXV0aG9yaXplZCBieSB0aGUgbWFuZGF0ZS4AAAAACm1heF9hbW91bnQAAAAAAAsAAABETVZQOiBzaW5nbGUgYWxsb3dlZCBwYXllZSAoc2NvcGUpLiBUMTogYFZlYzxBZGRyZXNzPmAgb3Igc2NvcGUtaGFzaC4AAAAIbWVyY2hhbnQAAAATAAAAOWBOb25lYCA9PSBzdGFuZGFsb25lOiBleGFjdGx5IHRoZSBwcmUtY29tcG9zaXRlIGJlaGF2aW9yLgAAAAAAAAdwb29sX2lkAAAAA+gAAAPuAAAAIAAAAAAAAAAKcG9vbF9zdGF0ZQAAAAAH0AAAAAlQb29sU3RhdGUAAAAAAAAoVGhlIGRlbWFuZCBjdXJ2ZTsgZW1wdHkgd2hlbiBzdGFuZGFsb25lLgAAAA5wcmljZV9zY2hlZHVsZQAAAAAD6gAAB9AAAAANU2NoZWR1bGVQb2ludAAAAAAAAD9Nb25vdG9uaWMgcGF5bWVudCBjb3VudGVyIChtYW5kYXRlLWxldmVsIGF1ZGl0IC8gcmVwbGF5IGd1YXJkKS4AAAAAA3NlcQAAAAAEAAAAO0N1bXVsYXRpdmUgY29uc3VtZWQ7IGludmFyaWFudDogYDAgPD0gc3BlbnQgPD0gbWF4X2Ftb3VudGAuAAAAAAVzcGVudAAAAAAAAAsAAAAAAAAABnN0YXR1cwAAAAAH0AAAAAZTdGF0dXMAAAAAAD1TaWduZXIgb2YgdGhlIEFQMiBJbnRlbnRNYW5kYXRlOyBncmFudHMgdGhlIFNFUC00MSBhbGxvd2FuY2UuAAAAAAAABHVzZXIAAAATAAAASUhhc2ggYmluZGluZyB0byB0aGUgb2ZmLWNoYWluIEFQMiBJbnRlbnRNYW5kYXRlIFZDOyBhbHNvIHRoZSBzdG9yYWdlIGtleS4AAAAAAAAHdmNfaGFzaAAAAAPuAAAAIA==",
|
|
3641
|
+
"AAAAAgAAAMNQb29sIGxpbmthZ2UgbGlmZWN5Y2xlLCBvcnRob2dvbmFsIHRvIGBTdGF0dXNgLiBgVW5saW5rZWRgIGFuZCBgUmVsZWFzZWRgCmNoaWxkcmVuIG1heSBzcGVuZCBvbiB0aGUgc29sbyBwYXRoICh0aGVpciBvd24gbGltaXRzIHN0aWxsIGFwcGx5KTsKYENvbW1pdHRlZGAgYW5kIGBDYXB0dXJlZGAgbWF5IG5vdCAoYE1hbmRhdGVQb29sZWRgKS4AAAAAAAAAAAlQb29sU3RhdGUAAAAAAAAEAAAAAAAAAAAAAAAIVW5saW5rZWQAAAAAAAAAAAAAAAlDb21taXR0ZWQAAAAAAAAAAAAAAAAAAAhDYXB0dXJlZAAAAAAAAAAAAAAACFJlbGVhc2Vk",
|
|
3642
|
+
"AAAAAQAAAAAAAAAAAAAADVNjaGVkdWxlUG9pbnQAAAAAAAACAAAAPlN0cmljdGx5IGRlc2NlbmRpbmcgYWNyb3NzIHRoZSBzY2hlZHVsZTsgZWFjaCBpbiAoMCwgTUFYX1FUWV0uAAAAAAAHbWF4X3F0eQAAAAAKAAAARFN0cmljdGx5IGFzY2VuZGluZyBhY3Jvc3MgdGhlIHNjaGVkdWxlOyBlYWNoIGluICgwLCBNQVhfVU5JVF9QUklDRV0uAAAACnVuaXRfcHJpY2UAAAAAAAs=",
|
|
3643
|
+
"AAAAAgAAAAAAAAAAAAAAB0RhdGFLZXkAAAAAAwAAAAEAAAAAAAAAB01hbmRhdGUAAAAAAQAAA+4AAAAgAAAAAQAAAAAAAAAEUG9vbAAAAAEAAAPuAAAAIAAAAAEAAAAAAAAAC1Bvb2xNZW1iZXJzAAAAAAEAAAPuAAAAIA==",
|
|
3644
|
+
"AAAAAQAAANNUaGUgcm93IGBwb29sLnJzYCBidWlsZHMgcGVyIGNvbW1pdHRlZCBjaGlsZCBhbmQgZmVlZHMgdG8gYGNsZWFyaW5nOjpjbGVhcmAuCkZlZWRpbmcgcGxhaW4gdmFsdWVzIChub3Qgc3RvcmFnZSBoYW5kbGVzKSBpcyB3aGF0IGtlZXBzIHRoZSBjbGVhcmluZwpmdW5jdGlvbiBwdXJlIGFuZCBtYWtlcyBzaW11bGF0ZSA9PSBjYXB0dXJlIGEgcHJvdmFibGUgZXF1YWxpdHkuAAAAAAAAAAAJQ2hpbGRWaWV3AAAAAAAABAAAAEJEZWNpZGVkIG9uY2UsIGJlZm9yZSBhbnkgcHJpY2UgZXhpc3RzIOKAlCBzZWUgcG9vbC5ycyBlbGlnaWJpbGl0eS4AAAAAAAhlbGlnaWJsZQAAAAEAAAAAAAAACm1hbmRhdGVfaWQAAAAAA+4AAAAgAAAAAAAAAAhzY2hlZHVsZQAAA+oAAAfQAAAADVNjaGVkdWxlUG9pbnQAAAAAAAAAAAAACndvcnN0X2Nhc2UAAAAAAAs=",
|
|
3645
|
+
"AAAAAQAAAAAAAAAAAAAACkFsbG9jYXRpb24AAAAAAAIAAAAAAAAACm1hbmRhdGVfaWQAAAAAA+4AAAAgAAAAAAAAAANxdHkAAAAACg==",
|
|
3646
|
+
"AAAAAgAAAAAAAAAAAAAAClBvb2xTdGF0dXMAAAAAAAMAAAAAAAAAAAAAAARPcGVuAAAAAAAAAAAAAAAHQ2xlYXJlZAAAAAAAAAAAAAAAAAdBYm9ydGVkAA==",
|
|
3647
|
+
"AAAAAgAAAAAAAAAAAAAADENsZWFyaW5nS2luZAAAAAMAAAAAAAAAAAAAAA5UaHJlc2hvbGRGbG9vcgAAAAAAAAAAAEZSZXNlcnZlZCBmb3IgU3RhZ2UgMjsgYHJlZ2lzdGVyX3Bvb2xgIHJlamVjdHMgd2l0aCBgS2luZE5vdFN1cHBvcnRlZGAuAAAAAAAMU3BlbmRDZWlsaW5nAAAAAAAAAEZSZXNlcnZlZCBmb3IgU3RhZ2UgMjsgYHJlZ2lzdGVyX3Bvb2xgIHJlamVjdHMgd2l0aCBgS2luZE5vdFN1cHBvcnRlZGAuAAAAAAAPQ2FwYWNpdHlDZWlsaW5nAA==",
|
|
3648
|
+
"AAAAAQAAAAAAAAAAAAAADENsZWFyaW5nUG9vbAAAAAsAAAAAAAAABWFzc2V0AAAAAAAAEwAAAEdVbml4IHNlY29uZHMuIENhcHR1cmUgaXMgYSBkZWFkbGluZSBhdWN0aW9uOiBuZXZlciBiZWZvcmUgdGhpcyBpbnN0YW50LgAAAAARY2xlYXJpbmdfZGVhZGxpbmUAAAAAAAAGAAAAvEZlZSByYXRlIGNhcHR1cmVkIGF0IGByZWdpc3Rlcl9wb29sYDsgY2FwdHVyZSBuZXZlciByZWFkcyBhIGxpdmUgcmF0ZS4KQWx3YXlzIDAgaW4gdGhpcyBkZXBsb3kgKHRoZSBmZWUga25vYiBzaGlwcyBpbiBpdHMgb3duIHBhc3MpOyB0aGUgZmllbGQKZXhpc3RzIHNvIHRoYXQgcGFzcyBpcyBub3QgYW5vdGhlciBBQkkgYnJlYWsuAAAADmZlZV9icHNfcGlubmVkAAAAAAAEAAAAAAAAAARraW5kAAAH0AAAAAxDbGVhcmluZ0tpbmQAAAA9TGl2ZSBDb21taXR0ZWQgbWVtYmVycyB3aGlsZSBPcGVuOyBmcm96ZW4gYXQgdGVybWluYWwgc3RhdHVzLgAAAAAAAAxtZW1iZXJfY291bnQAAAAEAAAAAAAAAAhtZXJjaGFudAAAABMAAABCRmxvb3Igb24gZWFjaCBjb21taXR0aW5nIGNoaWxkJ3Mgd29yc3RfY2FzZSAoYW50aS1kdXN0IHNxdWF0dGluZykuAAAAAAAPbWluX2NoaWxkX3ZhbHVlAAAAAAoAAACDU2lnbnMgYHJlZ2lzdGVyX3Bvb2xgOyBob2xkcyBOTyBsYXRlciBwb3dlciDigJQgY2xlYXJpbmcgaXMgcGVybWlzc2lvbmxlc3MKYW5kIGRldGVybWluaXN0aWMsIHdoaWNoIGlzIHRoZSB3aG9sZSBuby1za2ltIGd1YXJhbnRlZS4AAAAACm9yaWdpbmF0b3IAAAAAABMAAAAAAAAABnN0YXR1cwAAAAAH0AAAAApQb29sU3RhdHVzAAAAAABGVmVuZG9yIG1pbmltdW0gdW5pdHM7IHRoZSBwb29sIGZpcmVzIG9ubHkgaWYgYWdncmVnYXRlIHF0eSByZWFjaGVzIGl0LgAAAAAADXRocmVzaG9sZF9xdHkAAAAAAAAKAAAAQFZlbmRvciBtaW5pbXVtIG9yZGVyIHZhbHVlLCBjb21wYXJlZCBORVQgb2YgZmVlIHRvIHRoZSBtZXJjaGFudC4AAAAPdGhyZXNob2xkX3ZhbHVlAAAAAAo=",
|
|
3649
|
+
"AAAAAQAAAAAAAAAAAAAADENsZWFyT3V0Y29tZQAAAAcAAAAfbWFuZGF0ZV9pZCBvcmRlciwgcXR5ID4gMCBvbmx5LgAAAAALYWxsb2NhdGlvbnMAAAAD6gAAB9AAAAAKQWxsb2NhdGlvbgAAAAAALVRoZSBzaW5nbGUgdW5pZm9ybSBwcmljZSBwKjsgMCB3aGVuIGAhZmlyZXNgLgAAAAAAAA5jbGVhcmluZ19wcmljZQAAAAAACwAAAAAAAAAFZmlyZXMAAAAAAAABAAAAAAAAAAtncm9zc192YWx1ZQAAAAALAAAARGBncm9zc192YWx1ZSAtIHRvdGFsX2ZlZWA7IHRoZSBudW1iZXIgY29tcGFyZWQgdG8gYHRocmVzaG9sZF92YWx1ZWAuAAAACW5ldF92YWx1ZQAAAAAAAAsAAAAAAAAACXRvdGFsX2ZlZQAAAAAAAAsAAAAAAAAACXRvdGFsX3F0eQAAAAAAAAo="
|
|
3650
|
+
]), options);
|
|
3651
|
+
this.options = options;
|
|
3652
|
+
}
|
|
3653
|
+
fromJSON = {
|
|
3654
|
+
get_pool: this.txFromJSON,
|
|
3655
|
+
clear_pool: this.txFromJSON,
|
|
3656
|
+
evict_child: this.txFromJSON,
|
|
3657
|
+
get_mandate: this.txFromJSON,
|
|
3658
|
+
commit_child: this.txFromJSON,
|
|
3659
|
+
register_pool: this.txFromJSON,
|
|
3660
|
+
revoke_mandate: this.txFromJSON,
|
|
3661
|
+
simulate_clear: this.txFromJSON,
|
|
3662
|
+
execute_payment: this.txFromJSON,
|
|
3663
|
+
get_pool_members: this.txFromJSON,
|
|
3664
|
+
register_mandate: this.txFromJSON,
|
|
3665
|
+
validate_mandate: this.txFromJSON
|
|
3666
|
+
};
|
|
3667
|
+
};
|
|
3668
|
+
|
|
3669
|
+
// packages/stellar/dist/index.js
|
|
3670
|
+
__reExport(dist_exports, client_exports);
|
|
3671
|
+
|
|
3672
|
+
// packages/stellar/dist/config.js
|
|
3673
|
+
var TESTNET = {
|
|
3674
|
+
rpcUrl: "https://soroban-testnet.stellar.org",
|
|
3675
|
+
networkPassphrase: "Test SDF Network ; September 2015",
|
|
3676
|
+
mandateRegistryId: DEPLOYMENTS.testnet.mandateRegistryId,
|
|
3677
|
+
nativeSac: DEPLOYMENTS.testnet.nativeSac
|
|
3678
|
+
};
|
|
3679
|
+
|
|
3680
|
+
// packages/stellar/dist/signer.js
|
|
3681
|
+
import { Keypair } from "@stellar/stellar-sdk";
|
|
3682
|
+
import { basicNodeSigner } from "@stellar/stellar-sdk/contract";
|
|
3683
|
+
function keypairSigner(secretOrKeypair, networkPassphrase) {
|
|
3684
|
+
const keypair = typeof secretOrKeypair === "string" ? Keypair.fromSecret(secretOrKeypair) : secretOrKeypair;
|
|
3685
|
+
const node = basicNodeSigner(keypair, networkPassphrase);
|
|
3686
|
+
return {
|
|
3687
|
+
publicKey: keypair.publicKey(),
|
|
3688
|
+
keypair,
|
|
3689
|
+
signTransaction: node.signTransaction,
|
|
3690
|
+
signAuthEntry: node.signAuthEntry
|
|
3691
|
+
};
|
|
3692
|
+
}
|
|
3693
|
+
|
|
3694
|
+
// packages/stellar/dist/registry.js
|
|
3695
|
+
function registryClient(net, signer) {
|
|
3696
|
+
return new Client({
|
|
3697
|
+
contractId: net.mandateRegistryId,
|
|
3698
|
+
rpcUrl: net.rpcUrl,
|
|
3699
|
+
networkPassphrase: net.networkPassphrase,
|
|
3700
|
+
publicKey: signer.publicKey,
|
|
3701
|
+
signTransaction: signer.signTransaction,
|
|
3702
|
+
allowHttp: net.rpcUrl.startsWith("http://")
|
|
3703
|
+
});
|
|
3704
|
+
}
|
|
3705
|
+
|
|
3706
|
+
// packages/stellar/dist/token.js
|
|
3707
|
+
var token_exports = {};
|
|
3708
|
+
__export(token_exports, {
|
|
3709
|
+
approve: () => approve,
|
|
3710
|
+
balance: () => balance
|
|
3711
|
+
});
|
|
3712
|
+
import { Address, Contract, TransactionBuilder, nativeToScVal, scValToNative, rpc as rpc2 } from "@stellar/stellar-sdk";
|
|
3713
|
+
var INCLUSION_FEE = "100000";
|
|
3714
|
+
var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
3715
|
+
async function settle(server, hash2) {
|
|
3716
|
+
let res = await server.getTransaction(hash2);
|
|
3717
|
+
for (let i = 0; res.status === "NOT_FOUND" && i < 30; i += 1) {
|
|
3718
|
+
await sleep(1e3);
|
|
3719
|
+
res = await server.getTransaction(hash2);
|
|
3720
|
+
}
|
|
3721
|
+
if (res.status !== "SUCCESS") {
|
|
3722
|
+
throw new Error(`transaction ${hash2} did not succeed: ${res.status}`);
|
|
3723
|
+
}
|
|
3724
|
+
}
|
|
3725
|
+
async function approve(net, tokenId, owner, spender, amount, expirationLedger) {
|
|
3726
|
+
const server = new rpc2.Server(net.rpcUrl, { allowHttp: net.rpcUrl.startsWith("http://") });
|
|
3727
|
+
const source = await server.getAccount(owner.publicKey());
|
|
3728
|
+
const exp = expirationLedger ?? (await server.getLatestLedger()).sequence + 17280;
|
|
3729
|
+
const op = new Contract(tokenId).call("approve", new Address(owner.publicKey()).toScVal(), new Address(spender).toScVal(), nativeToScVal(amount, { type: "i128" }), nativeToScVal(exp, { type: "u32" }));
|
|
3730
|
+
const built = new TransactionBuilder(source, {
|
|
3731
|
+
fee: INCLUSION_FEE,
|
|
3732
|
+
networkPassphrase: net.networkPassphrase
|
|
3733
|
+
}).addOperation(op).setTimeout(60).build();
|
|
3734
|
+
const prepared = await server.prepareTransaction(built);
|
|
3735
|
+
prepared.sign(owner);
|
|
3736
|
+
const sent = await server.sendTransaction(prepared);
|
|
3737
|
+
if (sent.errorResult)
|
|
3738
|
+
throw new Error(`approve submit failed: ${sent.status}`);
|
|
3739
|
+
await settle(server, sent.hash);
|
|
3740
|
+
return sent.hash;
|
|
3741
|
+
}
|
|
3742
|
+
async function balance(net, tokenId, who) {
|
|
3743
|
+
const server = new rpc2.Server(net.rpcUrl, { allowHttp: net.rpcUrl.startsWith("http://") });
|
|
3744
|
+
const source = await server.getAccount(who).catch(() => null);
|
|
3745
|
+
const acct = source ?? await server.getAccount(who);
|
|
3746
|
+
const op = new Contract(tokenId).call("balance", new Address(who).toScVal());
|
|
3747
|
+
const tx = new TransactionBuilder(acct, {
|
|
3748
|
+
fee: INCLUSION_FEE,
|
|
3749
|
+
networkPassphrase: net.networkPassphrase
|
|
3750
|
+
}).addOperation(op).setTimeout(60).build();
|
|
3751
|
+
const sim = await server.simulateTransaction(tx);
|
|
3752
|
+
if (rpc2.Api.isSimulationError(sim))
|
|
3753
|
+
throw new Error(`balance sim failed: ${sim.error}`);
|
|
3754
|
+
return scValToNative(sim.result.retval);
|
|
3755
|
+
}
|
|
3756
|
+
|
|
3757
|
+
// packages/cli/src/config.ts
|
|
3758
|
+
var CONFIG_FILE = "reapp.config.json";
|
|
3759
|
+
function defaultConfig() {
|
|
3760
|
+
return {
|
|
3761
|
+
network: "testnet",
|
|
3762
|
+
contractId: TESTNET.mandateRegistryId,
|
|
3763
|
+
explorer: "https://stellar.expert/explorer/testnet",
|
|
3764
|
+
unlockPrice: "1.00",
|
|
3765
|
+
budget: "3.00"
|
|
3766
|
+
};
|
|
3767
|
+
}
|
|
3768
|
+
function networkConfig(config) {
|
|
3769
|
+
return { ...TESTNET, mandateRegistryId: config.contractId };
|
|
3770
|
+
}
|
|
3771
|
+
function configPath(cwd = process.cwd()) {
|
|
3772
|
+
return resolve(cwd, CONFIG_FILE);
|
|
3773
|
+
}
|
|
3774
|
+
function configExists(cwd) {
|
|
3775
|
+
return existsSync(configPath(cwd));
|
|
3776
|
+
}
|
|
3777
|
+
function loadConfig(cwd) {
|
|
3778
|
+
return JSON.parse(readFileSync(configPath(cwd), "utf8"));
|
|
3779
|
+
}
|
|
3780
|
+
function saveConfig(config, cwd) {
|
|
3781
|
+
const path = configPath(cwd);
|
|
3782
|
+
writeFileSync(path, JSON.stringify(config, null, 2) + "\n", "utf8");
|
|
3783
|
+
return path;
|
|
3784
|
+
}
|
|
3785
|
+
|
|
3786
|
+
// packages/cli/src/commands/init.ts
|
|
3787
|
+
function runInit(opts = {}) {
|
|
3788
|
+
console.log("\n" + banner() + "\n");
|
|
3789
|
+
if (configExists() && !opts.force) {
|
|
3790
|
+
log.warn(`${CONFIG_FILE} already exists`, { path: configPath() });
|
|
3791
|
+
log.info("re-run with --force to overwrite, or edit it directly");
|
|
3792
|
+
return;
|
|
3793
|
+
}
|
|
3794
|
+
const config = defaultConfig();
|
|
3795
|
+
const path = saveConfig(config);
|
|
3796
|
+
log.ok(`wrote ${CONFIG_FILE}`, { path });
|
|
3797
|
+
log.info("config", { network: config.network, contract: config.contractId });
|
|
3798
|
+
console.log(
|
|
3799
|
+
"\n" + c.bold("Next steps") + "\n" + c.gray(" 1. ") + c.white("reapp setup") + c.gray(" configure keys + fund testnet accounts") + "\n" + c.gray(" 2. ") + c.white("reapp mandate create") + c.gray(" register an AP2 mandate on-chain") + "\n" + c.gray(" 3. ") + c.white("reapp pay") + c.gray(" make an agent-signed payment") + "\n"
|
|
3800
|
+
);
|
|
3801
|
+
}
|
|
3802
|
+
|
|
3803
|
+
// packages/cli/src/commands/setup.ts
|
|
3804
|
+
import { Keypair as Keypair2, rpc as rpc3 } from "@stellar/stellar-sdk";
|
|
3805
|
+
|
|
3806
|
+
// packages/cli/src/secrets.ts
|
|
3807
|
+
import { readFileSync as readFileSync2, writeFileSync as writeFileSync2, existsSync as existsSync2, mkdirSync } from "node:fs";
|
|
3808
|
+
import { homedir } from "node:os";
|
|
3809
|
+
import { join } from "node:path";
|
|
3810
|
+
function reappHome() {
|
|
3811
|
+
return process.env.REAPP_HOME ?? join(homedir(), ".reapp");
|
|
3812
|
+
}
|
|
3813
|
+
function credentialsPath() {
|
|
3814
|
+
return join(reappHome(), "credentials.json");
|
|
3815
|
+
}
|
|
3816
|
+
function credentialsExist() {
|
|
3817
|
+
return existsSync2(credentialsPath());
|
|
3818
|
+
}
|
|
3819
|
+
function loadCredentials() {
|
|
3820
|
+
return JSON.parse(readFileSync2(credentialsPath(), "utf8"));
|
|
3821
|
+
}
|
|
3822
|
+
function saveCredentials(creds) {
|
|
3823
|
+
const home = reappHome();
|
|
3824
|
+
mkdirSync(home, { recursive: true, mode: 448 });
|
|
3825
|
+
const path = credentialsPath();
|
|
3826
|
+
writeFileSync2(path, JSON.stringify(creds, null, 2) + "\n", { mode: 384 });
|
|
3827
|
+
return path;
|
|
3828
|
+
}
|
|
3829
|
+
|
|
3830
|
+
// packages/cli/src/commands/setup.ts
|
|
3831
|
+
var short = (s) => s ? `${s.slice(0, 6)}\u2026${s.slice(-4)}` : "";
|
|
3832
|
+
var sleep2 = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
3833
|
+
async function fund(pub, server) {
|
|
3834
|
+
for (let round = 0; round < 4; round += 1) {
|
|
3835
|
+
await fetch(`https://friendbot.stellar.org/?addr=${pub}`).catch(() => void 0);
|
|
3836
|
+
for (let i = 0; i < 8; i += 1) {
|
|
3837
|
+
try {
|
|
3838
|
+
await server.getAccount(pub);
|
|
3839
|
+
return;
|
|
3840
|
+
} catch {
|
|
3841
|
+
await sleep2(1e3);
|
|
3842
|
+
}
|
|
3843
|
+
}
|
|
3844
|
+
}
|
|
3845
|
+
throw new Error(`friendbot could not fund ${short(pub)} after several attempts`);
|
|
3846
|
+
}
|
|
3847
|
+
async function runSetup(opts = {}) {
|
|
3848
|
+
if (!configExists()) {
|
|
3849
|
+
log.warn("no reapp.config.json here \u2014 run `reapp init` first");
|
|
3850
|
+
return;
|
|
3851
|
+
}
|
|
3852
|
+
if (credentialsExist() && !opts.force) {
|
|
3853
|
+
log.warn("credentials already exist", { path: credentialsPath() });
|
|
3854
|
+
log.info("re-run with --force to regenerate fresh testnet keys");
|
|
3855
|
+
return;
|
|
3856
|
+
}
|
|
3857
|
+
const config = configExists() ? loadConfig() : defaultConfig();
|
|
3858
|
+
const net = networkConfig(config);
|
|
3859
|
+
const server = new rpc3.Server(net.rpcUrl);
|
|
3860
|
+
const accountUrl = (pub) => `${config.explorer}/account/${pub}`;
|
|
3861
|
+
const user = Keypair2.random();
|
|
3862
|
+
const agent = Keypair2.random();
|
|
3863
|
+
const merchant = Keypair2.random();
|
|
3864
|
+
log.step("generated 3 fresh testnet keypairs", {
|
|
3865
|
+
user: short(user.publicKey()),
|
|
3866
|
+
agent: short(agent.publicKey()),
|
|
3867
|
+
merchant: short(merchant.publicKey())
|
|
3868
|
+
});
|
|
3869
|
+
log.step("funding via friendbot");
|
|
3870
|
+
await Promise.all([fund(user.publicKey(), server), fund(agent.publicKey(), server), fund(merchant.publicKey(), server)]);
|
|
3871
|
+
log.chain("accounts funded + visible on Soroban RPC");
|
|
3872
|
+
const creds = {
|
|
3873
|
+
network: config.network,
|
|
3874
|
+
userSecret: user.secret(),
|
|
3875
|
+
userPublic: user.publicKey(),
|
|
3876
|
+
agentSecret: agent.secret(),
|
|
3877
|
+
agentPublic: agent.publicKey(),
|
|
3878
|
+
merchantSecret: merchant.secret(),
|
|
3879
|
+
merchantPublic: merchant.publicKey()
|
|
3880
|
+
};
|
|
3881
|
+
const path = saveCredentials(creds);
|
|
3882
|
+
log.ok("wrote credentials (0600, outside the repo)", { path });
|
|
3883
|
+
console.log(
|
|
3884
|
+
"\n" + c.bold("Accounts") + "\n" + c.gray(" user ") + c.white(user.publicKey()) + c.dim(" " + accountUrl(user.publicKey())) + "\n" + c.gray(" agent ") + c.white(agent.publicKey()) + c.dim(" " + accountUrl(agent.publicKey())) + "\n" + c.gray(" merchant ") + c.white(merchant.publicKey()) + c.dim(" " + accountUrl(merchant.publicKey())) + "\n"
|
|
3885
|
+
);
|
|
3886
|
+
log.info("next", { run: "reapp mandate create" });
|
|
3887
|
+
}
|
|
3888
|
+
|
|
3889
|
+
// packages/sdk/dist/index.js
|
|
3890
|
+
import { Buffer as Buffer4 } from "buffer";
|
|
3891
|
+
import { Keypair as Keypair3, hash } from "@stellar/stellar-sdk";
|
|
3892
|
+
|
|
3893
|
+
// packages/sdk/dist/x402.js
|
|
3894
|
+
import { Buffer as Buffer3 } from "buffer";
|
|
3895
|
+
var X_PAYMENT_HEADER = "x-payment";
|
|
3896
|
+
async function parse402(res) {
|
|
3897
|
+
let body;
|
|
3898
|
+
try {
|
|
3899
|
+
body = await res.clone().json();
|
|
3900
|
+
} catch {
|
|
3901
|
+
throw new Error("x402: the 402 response body was not valid JSON");
|
|
3902
|
+
}
|
|
3903
|
+
const accepts = body?.accepts;
|
|
3904
|
+
const a = Array.isArray(accepts) ? accepts[0] : void 0;
|
|
3905
|
+
if (!a)
|
|
3906
|
+
throw new Error("x402: the 402 response carried no `accepts` payment requirement");
|
|
3907
|
+
const amount = String(a.maxAmountRequired ?? a.amount ?? "");
|
|
3908
|
+
const payTo = String(a.payTo ?? "");
|
|
3909
|
+
if (!amount)
|
|
3910
|
+
throw new Error("x402: the payment requirement is missing an amount");
|
|
3911
|
+
if (!payTo)
|
|
3912
|
+
throw new Error("x402: the payment requirement is missing `payTo` (the merchant)");
|
|
3913
|
+
const extra = a.extra ?? {};
|
|
3914
|
+
return {
|
|
3915
|
+
scheme: String(a.scheme ?? "reapp-soroban"),
|
|
3916
|
+
network: String(a.network ?? "stellar-testnet"),
|
|
3917
|
+
amount,
|
|
3918
|
+
asset: String(a.asset ?? ""),
|
|
3919
|
+
payTo,
|
|
3920
|
+
resource: String(a.resource ?? ""),
|
|
3921
|
+
contract: extra.contract ? String(extra.contract) : void 0
|
|
3922
|
+
};
|
|
3923
|
+
}
|
|
3924
|
+
function encodePaymentProof(p) {
|
|
3925
|
+
return Buffer3.from(JSON.stringify(p), "utf8").toString("base64");
|
|
3926
|
+
}
|
|
3927
|
+
|
|
3928
|
+
// packages/sdk/dist/index.js
|
|
3929
|
+
var DEFAULT_DECIMALS = 7;
|
|
3930
|
+
var PAYMENT_TIMEOUT_SECONDS = 60;
|
|
3931
|
+
var I128_MAX = 2n ** 127n - 1n;
|
|
3932
|
+
var MAX_EXPIRY = Number.MAX_SAFE_INTEGER;
|
|
3933
|
+
function toStroops(human, decimals = DEFAULT_DECIMALS) {
|
|
3934
|
+
const s = String(human).trim();
|
|
3935
|
+
if (!/^\d+(\.\d+)?$/.test(s)) {
|
|
3936
|
+
throw new Error(`Invalid amount ${JSON.stringify(human)}: expected a non-negative decimal like "5.00".`);
|
|
3937
|
+
}
|
|
3938
|
+
const dot = s.indexOf(".");
|
|
3939
|
+
const whole = dot === -1 ? s : s.slice(0, dot);
|
|
3940
|
+
const frac = dot === -1 ? "" : s.slice(dot + 1);
|
|
3941
|
+
if (frac.length > decimals) {
|
|
3942
|
+
throw new Error(`Amount ${JSON.stringify(human)} has more than ${decimals} decimal places.`);
|
|
3943
|
+
}
|
|
3944
|
+
const fracPadded = (frac + "0".repeat(decimals)).slice(0, decimals);
|
|
3945
|
+
const stroops = BigInt(whole) * 10n ** BigInt(decimals) + BigInt(fracPadded || "0");
|
|
3946
|
+
if (stroops > I128_MAX) {
|
|
3947
|
+
throw new Error(`Amount ${JSON.stringify(human)} is too large to fit the contract's i128 amount field.`);
|
|
3948
|
+
}
|
|
3949
|
+
return stroops;
|
|
3950
|
+
}
|
|
3951
|
+
var asKeypair = (s) => typeof s === "string" ? Keypair3.fromSecret(s) : s;
|
|
3952
|
+
var Agent = class {
|
|
3953
|
+
net;
|
|
3954
|
+
mandate;
|
|
3955
|
+
agentKeypair;
|
|
3956
|
+
constructor(net, mandate2, agentKeypair) {
|
|
3957
|
+
this.net = net;
|
|
3958
|
+
this.mandate = mandate2;
|
|
3959
|
+
this.agentKeypair = agentKeypair;
|
|
3960
|
+
}
|
|
3961
|
+
/** Execute a mandate-validated payment of `amount` (human, e.g. "1.00").
|
|
3962
|
+
* Reads the current sequence, then calls the contract's `execute_payment`
|
|
3963
|
+
* (agent-signed). Throws if the contract rejects it. Returns the tx hash. */
|
|
3964
|
+
async pay(amount) {
|
|
3965
|
+
const signer = keypairSigner(this.agentKeypair, this.net.networkPassphrase);
|
|
3966
|
+
const client = registryClient(this.net, signer);
|
|
3967
|
+
const current = (await client.get_mandate({ mandate_id: this.mandate.idBuffer })).result.unwrap();
|
|
3968
|
+
const at = await client.execute_payment({
|
|
3969
|
+
mandate_id: this.mandate.idBuffer,
|
|
3970
|
+
amount: toStroops(amount, this.mandate.decimals),
|
|
3971
|
+
expected_seq: current.seq
|
|
3972
|
+
}, { timeoutInSeconds: PAYMENT_TIMEOUT_SECONDS });
|
|
3973
|
+
const sent = await at.signAndSend();
|
|
3974
|
+
try {
|
|
3975
|
+
sent.result.unwrap();
|
|
3976
|
+
} catch (e) {
|
|
3977
|
+
throw new Error(`payment rejected by contract for mandate ${this.mandate.id}: ${e instanceof Error ? e.message : String(e)}`);
|
|
3978
|
+
}
|
|
3979
|
+
return sent.sendTransactionResponse?.hash ?? "";
|
|
3980
|
+
}
|
|
3981
|
+
/**
|
|
3982
|
+
* x402 round-trip. GET `url`; if the server answers 402 Payment Required, read
|
|
3983
|
+
* the payment requirement, settle it on-chain via `execute_payment` (the same
|
|
3984
|
+
* path as `pay`), and retry the request with an `X-PAYMENT` settlement proof.
|
|
3985
|
+
* Returns the final `Response`.
|
|
3986
|
+
*
|
|
3987
|
+
* The contract is the enforcer; `fetch` never bypasses it. The payment always
|
|
3988
|
+
* goes through `pay` -> `execute_payment`, so a revoked, expired, out-of-scope,
|
|
3989
|
+
* or over-budget request is rejected on-chain and `fetch` throws. The 402 body
|
|
3990
|
+
* is only a hint: the merchant independently verifies the on-chain payment
|
|
3991
|
+
* before serving the resource.
|
|
3992
|
+
*/
|
|
3993
|
+
async fetch(url, init) {
|
|
3994
|
+
const first = await fetch(url, init);
|
|
3995
|
+
if (first.status !== 402)
|
|
3996
|
+
return first;
|
|
3997
|
+
const required = await parse402(first);
|
|
3998
|
+
if (required.payTo !== this.mandate.merchant) {
|
|
3999
|
+
throw new Error(`x402: the 402 names merchant ${required.payTo}, not this mandate's merchant ${this.mandate.merchant}`);
|
|
4000
|
+
}
|
|
4001
|
+
if (required.asset && required.asset !== this.mandate.asset) {
|
|
4002
|
+
throw new Error(`x402: the 402 names a different asset than this mandate's`);
|
|
4003
|
+
}
|
|
4004
|
+
const txHash = await this.pay(required.amount);
|
|
4005
|
+
const headers = new Headers(init?.headers);
|
|
4006
|
+
headers.set(X_PAYMENT_HEADER, encodePaymentProof({
|
|
4007
|
+
scheme: required.scheme,
|
|
4008
|
+
network: required.network,
|
|
4009
|
+
txHash,
|
|
4010
|
+
mandateId: this.mandate.id,
|
|
4011
|
+
amount: required.amount
|
|
4012
|
+
}));
|
|
4013
|
+
return fetch(url, { ...init, method: init?.method ?? "GET", headers });
|
|
4014
|
+
}
|
|
4015
|
+
};
|
|
4016
|
+
var reapp = {
|
|
4017
|
+
testnet: TESTNET,
|
|
4018
|
+
/** Build an AP2-style IntentMandate and its canonical id (no chain calls). */
|
|
4019
|
+
createIntentMandate(input, net = TESTNET) {
|
|
4020
|
+
void net;
|
|
4021
|
+
if (!Number.isInteger(input.expiry) || input.expiry <= 0 || input.expiry > MAX_EXPIRY) {
|
|
4022
|
+
throw new Error(`expiry must be a positive integer of Unix seconds (got ${input.expiry}).`);
|
|
4023
|
+
}
|
|
4024
|
+
const decimals = input.decimals ?? DEFAULT_DECIMALS;
|
|
4025
|
+
const nonce = input.nonce ?? `${Date.now()}:${Math.random().toString(36).slice(2)}`;
|
|
4026
|
+
const maxAmount = String(input.maxAmount).trim();
|
|
4027
|
+
const canonical = JSON.stringify({
|
|
4028
|
+
user: input.user,
|
|
4029
|
+
agent: input.agent,
|
|
4030
|
+
merchant: input.merchant,
|
|
4031
|
+
asset: input.asset,
|
|
4032
|
+
maxAmount,
|
|
4033
|
+
expiry: input.expiry,
|
|
4034
|
+
nonce
|
|
4035
|
+
});
|
|
4036
|
+
const idBuffer = hash(Buffer4.from(canonical, "utf8"));
|
|
4037
|
+
return {
|
|
4038
|
+
id: idBuffer.toString("hex"),
|
|
4039
|
+
idBuffer,
|
|
4040
|
+
user: input.user,
|
|
4041
|
+
agent: input.agent,
|
|
4042
|
+
merchant: input.merchant,
|
|
4043
|
+
asset: input.asset,
|
|
4044
|
+
maxAmount: toStroops(maxAmount, decimals),
|
|
4045
|
+
expiry: input.expiry,
|
|
4046
|
+
decimals
|
|
4047
|
+
};
|
|
4048
|
+
},
|
|
4049
|
+
/** Register the mandate on-chain (user-signed). */
|
|
4050
|
+
async registerMandate(mandate2, opts, net = TESTNET) {
|
|
4051
|
+
const signer = keypairSigner(asKeypair(opts.signer), net.networkPassphrase);
|
|
4052
|
+
const client = registryClient(net, signer);
|
|
4053
|
+
const at = await client.register_mandate({
|
|
4054
|
+
user: mandate2.user,
|
|
4055
|
+
agent: mandate2.agent,
|
|
4056
|
+
merchant: mandate2.merchant,
|
|
4057
|
+
asset: mandate2.asset,
|
|
4058
|
+
max_amount: mandate2.maxAmount,
|
|
4059
|
+
expiry: BigInt(mandate2.expiry),
|
|
4060
|
+
vc_hash: mandate2.idBuffer,
|
|
4061
|
+
// Standalone mandate: no clearing-pool linkage (composite mandates are
|
|
4062
|
+
// registered with a pool id + price schedule via the pool surface).
|
|
4063
|
+
pool_id: void 0,
|
|
4064
|
+
price_schedule: []
|
|
4065
|
+
});
|
|
4066
|
+
const sent = await at.signAndSend();
|
|
4067
|
+
sent.result.unwrap();
|
|
4068
|
+
return sent.sendTransactionResponse?.hash ?? "";
|
|
4069
|
+
},
|
|
4070
|
+
/** Approve the contract for a SEP-41 allowance up to the mandate budget (user-signed). */
|
|
4071
|
+
async approveBudget(mandate2, opts, net = TESTNET) {
|
|
4072
|
+
return token_exports.approve(net, mandate2.asset, asKeypair(opts.signer), net.mandateRegistryId, mandate2.maxAmount);
|
|
4073
|
+
},
|
|
4074
|
+
/** Revoke the mandate (user-signed). After this, `pay` is rejected on-chain. */
|
|
4075
|
+
async revokeMandate(mandate2, opts, net = TESTNET) {
|
|
4076
|
+
const signer = keypairSigner(asKeypair(opts.signer), net.networkPassphrase);
|
|
4077
|
+
const client = registryClient(net, signer);
|
|
4078
|
+
const at = await client.revoke_mandate({ mandate_id: mandate2.idBuffer });
|
|
4079
|
+
const sent = await at.signAndSend();
|
|
4080
|
+
sent.result.unwrap();
|
|
4081
|
+
return sent.sendTransactionResponse?.hash ?? "";
|
|
4082
|
+
},
|
|
4083
|
+
/** Bind an agent to a registered mandate. */
|
|
4084
|
+
agent(opts, net = TESTNET) {
|
|
4085
|
+
return new Agent(net, opts.mandate, asKeypair(opts.signer));
|
|
4086
|
+
}
|
|
4087
|
+
};
|
|
4088
|
+
|
|
4089
|
+
// packages/cli/src/mandate-store.ts
|
|
4090
|
+
import { readFileSync as readFileSync3, writeFileSync as writeFileSync3, existsSync as existsSync3 } from "node:fs";
|
|
4091
|
+
import { join as join2 } from "node:path";
|
|
4092
|
+
function mandatePath() {
|
|
4093
|
+
return join2(reappHome(), "mandate.json");
|
|
4094
|
+
}
|
|
4095
|
+
function mandateExists() {
|
|
4096
|
+
return existsSync3(mandatePath());
|
|
4097
|
+
}
|
|
4098
|
+
function loadMandate() {
|
|
4099
|
+
return JSON.parse(readFileSync3(mandatePath(), "utf8"));
|
|
4100
|
+
}
|
|
4101
|
+
function saveMandate(m) {
|
|
4102
|
+
const path = mandatePath();
|
|
4103
|
+
writeFileSync3(path, JSON.stringify(m, null, 2) + "\n", { mode: 384 });
|
|
4104
|
+
return path;
|
|
4105
|
+
}
|
|
4106
|
+
|
|
4107
|
+
// packages/cli/src/commands/mandate.ts
|
|
4108
|
+
var short2 = (s) => s ? `${s.slice(0, 6)}\u2026${s.slice(-4)}` : "";
|
|
4109
|
+
async function runMandateCreate(opts = {}) {
|
|
4110
|
+
if (!configExists()) {
|
|
4111
|
+
log.warn("no reapp.config.json here \u2014 run `reapp init` first");
|
|
4112
|
+
return;
|
|
4113
|
+
}
|
|
4114
|
+
if (!credentialsExist()) {
|
|
4115
|
+
log.warn("no credentials \u2014 run `reapp setup` first");
|
|
4116
|
+
return;
|
|
4117
|
+
}
|
|
4118
|
+
if (mandateExists() && !opts.force) {
|
|
4119
|
+
log.warn("a mandate already exists \u2014 re-run with --force to replace it");
|
|
4120
|
+
return;
|
|
4121
|
+
}
|
|
4122
|
+
const config = loadConfig();
|
|
4123
|
+
const net = networkConfig(config);
|
|
4124
|
+
const creds = loadCredentials();
|
|
4125
|
+
const txUrl = (hash2) => `${config.explorer}/tx/${hash2}`;
|
|
4126
|
+
const budget = opts.budget ?? config.budget;
|
|
4127
|
+
const expirySecs = opts.expiry ? Number(opts.expiry) : 3600;
|
|
4128
|
+
if (!Number.isFinite(expirySecs) || expirySecs <= 0) {
|
|
4129
|
+
log.err("--expiry must be a positive number of seconds");
|
|
4130
|
+
return;
|
|
4131
|
+
}
|
|
4132
|
+
const inputs = {
|
|
4133
|
+
user: creds.userPublic,
|
|
4134
|
+
agent: creds.agentPublic,
|
|
4135
|
+
merchant: creds.merchantPublic,
|
|
4136
|
+
asset: reapp.testnet.nativeSac,
|
|
4137
|
+
maxAmount: budget,
|
|
4138
|
+
expiry: Math.floor(Date.now() / 1e3) + expirySecs,
|
|
4139
|
+
nonce: `${Date.now()}:${Math.random().toString(36).slice(2)}`
|
|
4140
|
+
};
|
|
4141
|
+
const mandate2 = reapp.createIntentMandate(inputs);
|
|
4142
|
+
log.step("authorizing mandate", {
|
|
4143
|
+
budget: `${budget} XLM`,
|
|
4144
|
+
merchant: short2(creds.merchantPublic),
|
|
4145
|
+
id: short2(mandate2.id)
|
|
4146
|
+
});
|
|
4147
|
+
const registerTx = await reapp.registerMandate(mandate2, { signer: creds.userSecret }, net);
|
|
4148
|
+
log.chain("register_mandate confirmed", { tx: short2(registerTx) });
|
|
4149
|
+
const approveTx = await reapp.approveBudget(mandate2, { signer: creds.userSecret }, net);
|
|
4150
|
+
log.chain("approveBudget confirmed (SEP-41 allowance to contract)", { tx: short2(approveTx) });
|
|
4151
|
+
const stored = { inputs, id: mandate2.id, registerTx, approveTx };
|
|
4152
|
+
const path = saveMandate(stored);
|
|
4153
|
+
log.ok("mandate saved", { path });
|
|
4154
|
+
console.log(
|
|
4155
|
+
"\n" + c.bold("Mandate") + "\n" + c.gray(" id ") + c.white(mandate2.id) + "\n" + c.gray(" budget ") + c.white(`${budget} XLM`) + "\n" + c.gray(" register ") + c.dim(txUrl(registerTx)) + "\n" + c.gray(" approve ") + c.dim(txUrl(approveTx)) + "\n"
|
|
4156
|
+
);
|
|
4157
|
+
log.info("next", { run: "reapp pay" });
|
|
4158
|
+
}
|
|
4159
|
+
|
|
4160
|
+
// packages/cli/src/commands/pay.ts
|
|
4161
|
+
var short3 = (s) => s ? `${s.slice(0, 6)}\u2026${s.slice(-4)}` : "";
|
|
4162
|
+
function rejectionSummary(reason) {
|
|
4163
|
+
const code = (reason.match(/Error\(Contract,\s*#(\d+)\)/) ?? [])[1];
|
|
4164
|
+
switch (code) {
|
|
4165
|
+
case "4":
|
|
4166
|
+
return "MandateExpired";
|
|
4167
|
+
case "5":
|
|
4168
|
+
return "MandateRevoked";
|
|
4169
|
+
case "6":
|
|
4170
|
+
return "BudgetExceeded";
|
|
4171
|
+
case "7":
|
|
4172
|
+
return "MerchantOutOfScope";
|
|
4173
|
+
case "8":
|
|
4174
|
+
return "BadSequence";
|
|
4175
|
+
case "9":
|
|
4176
|
+
return "InvalidAmount";
|
|
4177
|
+
default:
|
|
4178
|
+
return reason.split("\n")[0] ?? reason;
|
|
4179
|
+
}
|
|
4180
|
+
}
|
|
4181
|
+
async function runPay(amountArg) {
|
|
4182
|
+
if (!configExists()) {
|
|
4183
|
+
log.warn("no reapp.config.json here \u2014 run `reapp init` first");
|
|
4184
|
+
return;
|
|
4185
|
+
}
|
|
4186
|
+
if (!credentialsExist()) {
|
|
4187
|
+
log.warn("no credentials \u2014 run `reapp setup` first");
|
|
4188
|
+
return;
|
|
4189
|
+
}
|
|
4190
|
+
if (!mandateExists()) {
|
|
4191
|
+
log.warn("no mandate \u2014 run `reapp mandate create` first");
|
|
4192
|
+
return;
|
|
4193
|
+
}
|
|
4194
|
+
const config = loadConfig();
|
|
4195
|
+
const net = networkConfig(config);
|
|
4196
|
+
const creds = loadCredentials();
|
|
4197
|
+
const stored = loadMandate();
|
|
4198
|
+
const txUrl = (hash2) => `${config.explorer}/tx/${hash2}`;
|
|
4199
|
+
const amount = amountArg ?? config.unlockPrice;
|
|
4200
|
+
const mandate2 = reapp.createIntentMandate(stored.inputs);
|
|
4201
|
+
log.step("execute_payment (agent-signed)", { amount: `${amount} XLM`, mandate: short3(mandate2.id) });
|
|
4202
|
+
try {
|
|
4203
|
+
const hash2 = await reapp.agent({ mandate: mandate2, signer: creds.agentSecret }, net).pay(amount);
|
|
4204
|
+
log.chain("payment settled on-chain", { tx: short3(hash2) });
|
|
4205
|
+
console.log(
|
|
4206
|
+
"\n" + c.bold("Payment") + "\n" + c.gray(" amount ") + c.white(`${amount} XLM`) + "\n" + c.gray(" tx ") + c.dim(txUrl(hash2)) + "\n"
|
|
4207
|
+
);
|
|
4208
|
+
} catch (err) {
|
|
4209
|
+
const reason = err instanceof Error ? err.message : String(err);
|
|
4210
|
+
log.err("payment rejected by the contract", { reason: rejectionSummary(reason) });
|
|
4211
|
+
log.info("budget, expiry, and replay are enforced on-chain \u2014 the CLI cannot override them");
|
|
4212
|
+
process.exitCode = 1;
|
|
4213
|
+
}
|
|
4214
|
+
}
|
|
4215
|
+
|
|
4216
|
+
// packages/cli/src/commands/demo.ts
|
|
4217
|
+
import { Keypair as Keypair4, rpc as rpc4 } from "@stellar/stellar-sdk";
|
|
4218
|
+
var SOURCES = [
|
|
4219
|
+
{ name: "Market Data API", icon: "\u{1F4C8}" },
|
|
4220
|
+
{ name: "Academic Papers", icon: "\u{1F4DA}" },
|
|
4221
|
+
{ name: "News Archive", icon: "\u{1F4F0}" },
|
|
4222
|
+
{ name: "Patent Database", icon: "\u2697\uFE0F" },
|
|
4223
|
+
{ name: "Analyst Reports", icon: "\u{1F3E6}" }
|
|
4224
|
+
];
|
|
4225
|
+
var SOURCE_PRICE = "1.00";
|
|
4226
|
+
var BUDGET = "3.00";
|
|
4227
|
+
var short4 = (s) => s ? `${s.slice(0, 6)}\u2026${s.slice(-4)}` : "";
|
|
4228
|
+
var sleep3 = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
4229
|
+
async function fund2(pub) {
|
|
4230
|
+
const server = new rpc4.Server(TESTNET.rpcUrl);
|
|
4231
|
+
for (let round = 0; round < 4; round += 1) {
|
|
4232
|
+
await fetch(`https://friendbot.stellar.org/?addr=${pub}`).catch(() => void 0);
|
|
4233
|
+
for (let i = 0; i < 8; i += 1) {
|
|
4234
|
+
try {
|
|
4235
|
+
await server.getAccount(pub);
|
|
4236
|
+
return;
|
|
4237
|
+
} catch {
|
|
4238
|
+
}
|
|
4239
|
+
await sleep3(1e3);
|
|
4240
|
+
}
|
|
4241
|
+
}
|
|
4242
|
+
throw new Error(`friendbot could not fund ${pub} after several attempts`);
|
|
4243
|
+
}
|
|
4244
|
+
async function waitForSeq(client, idBuffer, target, tries = 20) {
|
|
4245
|
+
for (let i = 0; i < tries; i += 1) {
|
|
4246
|
+
try {
|
|
4247
|
+
const md = (await client.get_mandate({ mandate_id: idBuffer })).result.unwrap();
|
|
4248
|
+
if (Number(md.seq) >= target) return;
|
|
4249
|
+
} catch {
|
|
4250
|
+
}
|
|
4251
|
+
await sleep3(1e3);
|
|
4252
|
+
}
|
|
4253
|
+
}
|
|
4254
|
+
async function attemptPurchase(mandate2, agentSecret) {
|
|
4255
|
+
try {
|
|
4256
|
+
const hash2 = await reapp.agent({ mandate: mandate2, signer: agentSecret }).pay(SOURCE_PRICE);
|
|
4257
|
+
return { kind: "ok", hash: hash2 };
|
|
4258
|
+
} catch (e) {
|
|
4259
|
+
const msg = e instanceof Error ? e.message : String(e);
|
|
4260
|
+
const code = (msg.match(/Error\(Contract,\s*#(\d+)\)/) ?? [])[1];
|
|
4261
|
+
if (code === "6") return { kind: "blocked" };
|
|
4262
|
+
if (code === "8") return { kind: "retry" };
|
|
4263
|
+
return { kind: "error", msg: (msg.split("\n")[0] ?? msg).slice(0, 90) };
|
|
4264
|
+
}
|
|
4265
|
+
}
|
|
4266
|
+
async function runDemo(target = "research-agent") {
|
|
4267
|
+
if (target !== "research-agent") {
|
|
4268
|
+
log.warn(`unknown demo "${target}"`);
|
|
4269
|
+
log.info("available demos", { run: "reapp demo research-agent" });
|
|
4270
|
+
return;
|
|
4271
|
+
}
|
|
4272
|
+
console.log("\n" + banner() + "\n");
|
|
4273
|
+
log.info("research agent demo \u2014 the agent pays on-chain per source; the contract caps the budget");
|
|
4274
|
+
const user = Keypair4.random();
|
|
4275
|
+
const agent = Keypair4.random();
|
|
4276
|
+
const merchant = Keypair4.random();
|
|
4277
|
+
log.step("funding 3 ephemeral testnet accounts via friendbot");
|
|
4278
|
+
await Promise.all([fund2(user.publicKey()), fund2(agent.publicKey()), fund2(merchant.publicKey())]);
|
|
4279
|
+
log.chain("accounts funded", {
|
|
4280
|
+
user: short4(user.publicKey()),
|
|
4281
|
+
agent: short4(agent.publicKey()),
|
|
4282
|
+
merchant: short4(merchant.publicKey())
|
|
4283
|
+
});
|
|
4284
|
+
const inputs = {
|
|
4285
|
+
user: user.publicKey(),
|
|
4286
|
+
agent: agent.publicKey(),
|
|
4287
|
+
merchant: merchant.publicKey(),
|
|
4288
|
+
asset: reapp.testnet.nativeSac,
|
|
4289
|
+
maxAmount: BUDGET,
|
|
4290
|
+
expiry: Math.floor(Date.now() / 1e3) + 3600,
|
|
4291
|
+
nonce: `${Date.now()}:${Math.random().toString(36).slice(2)}`
|
|
4292
|
+
};
|
|
4293
|
+
const mandate2 = reapp.createIntentMandate(inputs);
|
|
4294
|
+
await reapp.registerMandate(mandate2, { signer: user.secret() });
|
|
4295
|
+
await reapp.approveBudget(mandate2, { signer: user.secret() });
|
|
4296
|
+
log.chain("mandate registered + allowance approved for contract", { budget: `${BUDGET} XLM`, id: short4(mandate2.id) });
|
|
4297
|
+
const rclient = registryClient(TESTNET, keypairSigner(agent, TESTNET.networkPassphrase));
|
|
4298
|
+
let purchased = 0;
|
|
4299
|
+
let seq = 0;
|
|
4300
|
+
outer: for (const s of SOURCES) {
|
|
4301
|
+
log.step(`agent buys ${s.icon} ${s.name}`, { price: `${SOURCE_PRICE} XLM` });
|
|
4302
|
+
for (let attempt = 0; attempt < 4; attempt += 1) {
|
|
4303
|
+
const r = await attemptPurchase(mandate2, agent.secret());
|
|
4304
|
+
if (r.kind === "ok") {
|
|
4305
|
+
purchased += 1;
|
|
4306
|
+
seq += 1;
|
|
4307
|
+
log.ok("purchased on-chain", { tx: short4(r.hash) });
|
|
4308
|
+
await waitForSeq(rclient, mandate2.idBuffer, seq);
|
|
4309
|
+
break;
|
|
4310
|
+
}
|
|
4311
|
+
if (r.kind === "blocked") {
|
|
4312
|
+
log.warn(`contract blocked the purchase \u2014 ${BUDGET} XLM budget exhausted`);
|
|
4313
|
+
break outer;
|
|
4314
|
+
}
|
|
4315
|
+
if (r.kind === "retry") {
|
|
4316
|
+
await waitForSeq(rclient, mandate2.idBuffer, seq);
|
|
4317
|
+
continue;
|
|
4318
|
+
}
|
|
4319
|
+
log.err("purchase failed", { reason: r.msg });
|
|
4320
|
+
break outer;
|
|
4321
|
+
}
|
|
4322
|
+
}
|
|
4323
|
+
console.log(
|
|
4324
|
+
"\n" + c.bold("Result") + "\n" + c.gray(" purchased ") + c.white(`${purchased} sources`) + c.gray(" for ") + c.white(`${purchased}.00 XLM`) + c.gray(" settled on-chain") + "\n" + c.gray(" enforced ") + c.white(`${BUDGET} XLM`) + c.gray(" budget cap \u2014 the contract rejected further purchases") + "\n" + c.gray(" the agent answers from what it could afford; a compromised agent or SDK cannot exceed the mandate.") + "\n"
|
|
4325
|
+
);
|
|
4326
|
+
}
|
|
4327
|
+
|
|
4328
|
+
// packages/cli/src/index.ts
|
|
4329
|
+
var program2 = new Command();
|
|
4330
|
+
program2.name("reapp").description("Agent payments on Stellar, enforced on-chain by the REAPP MandateRegistry.").version("0.1.0");
|
|
4331
|
+
program2.command("init").description("scaffold a project in the current directory (writes reapp.config.json)").option("-f, --force", "overwrite an existing reapp.config.json").action((opts) => runInit(opts));
|
|
4332
|
+
program2.command("setup").description("generate testnet burner keys and fund them via friendbot").option("-f, --force", "regenerate fresh keys, overwriting existing credentials").action((opts) => runSetup(opts));
|
|
4333
|
+
var mandate = program2.command("mandate").description("manage AP2 mandates");
|
|
4334
|
+
mandate.command("create").description("register an AP2 mandate on-chain and approve the SEP-41 allowance").option("-b, --budget <xlm>", "mandate cap in XLM (default: from reapp.config.json)").option("-e, --expiry <seconds>", "seconds until the mandate expires", "3600").option("-f, --force", "replace an existing stored mandate").action((opts) => runMandateCreate(opts));
|
|
4335
|
+
program2.command("pay").description("make an agent-signed payment against the active mandate (budget enforced on-chain)").argument("[amount]", "XLM amount to pay (default: unlockPrice from reapp.config.json)").action((amount) => runPay(amount));
|
|
4336
|
+
program2.command("demo").description("run a self-contained on-chain demo (ephemeral accounts, no setup needed)").argument("[target]", "which demo to run", "research-agent").action((target) => runDemo(target));
|
|
4337
|
+
program2.parseAsync(process.argv).catch((err) => {
|
|
4338
|
+
console.error(err instanceof Error ? err.message : err);
|
|
4339
|
+
process.exit(1);
|
|
4340
|
+
});
|