easyclaw-link 1.0.0 → 1.2.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/dist/index.js CHANGED
@@ -1,27 +1,3148 @@
1
1
  #!/usr/bin/env node
2
2
  "use strict";
3
- Object.defineProperty(exports, "__esModule", { value: true });
4
- const commander_1 = require("commander");
5
- const login_1 = require("./commands/login");
6
- const publish_1 = require("./commands/publish");
7
- const list_1 = require("./commands/list");
8
- const program = new commander_1.Command();
9
- program
10
- .name("easyclaw")
11
- .description("EasyClaw CLI - Publish and manage skills on easyclaw.link")
12
- .version("1.0.0");
13
- program
14
- .command("login")
15
- .description("登录 EasyClaw 平台,保存 API Key")
16
- .action(login_1.loginAction);
17
- program
18
- .command("publish [dir]")
19
- .description("发布或更新技能到 EasyClaw 平台")
20
- .option("--id <id>", "指定技能 ID 进行更新")
21
- .action(publish_1.publishAction);
22
- program
23
- .command("list")
24
- .description("查看我发布的所有技能")
25
- .action(list_1.listAction);
26
- program.parse();
27
- //# sourceMappingURL=index.js.map
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 __commonJS = (cb, mod) => function __require() {
10
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+
29
+ // node_modules/commander/lib/error.js
30
+ var require_error = __commonJS({
31
+ "node_modules/commander/lib/error.js"(exports2) {
32
+ var CommanderError2 = class extends Error {
33
+ /**
34
+ * Constructs the CommanderError class
35
+ * @param {number} exitCode suggested exit code which could be used with process.exit
36
+ * @param {string} code an id string representing the error
37
+ * @param {string} message human-readable description of the error
38
+ * @constructor
39
+ */
40
+ constructor(exitCode, code, message) {
41
+ super(message);
42
+ Error.captureStackTrace(this, this.constructor);
43
+ this.name = this.constructor.name;
44
+ this.code = code;
45
+ this.exitCode = exitCode;
46
+ this.nestedError = void 0;
47
+ }
48
+ };
49
+ var InvalidArgumentError2 = class extends CommanderError2 {
50
+ /**
51
+ * Constructs the InvalidArgumentError class
52
+ * @param {string} [message] explanation of why argument is invalid
53
+ * @constructor
54
+ */
55
+ constructor(message) {
56
+ super(1, "commander.invalidArgument", message);
57
+ Error.captureStackTrace(this, this.constructor);
58
+ this.name = this.constructor.name;
59
+ }
60
+ };
61
+ exports2.CommanderError = CommanderError2;
62
+ exports2.InvalidArgumentError = InvalidArgumentError2;
63
+ }
64
+ });
65
+
66
+ // node_modules/commander/lib/argument.js
67
+ var require_argument = __commonJS({
68
+ "node_modules/commander/lib/argument.js"(exports2) {
69
+ var { InvalidArgumentError: InvalidArgumentError2 } = require_error();
70
+ var Argument2 = class {
71
+ /**
72
+ * Initialize a new command argument with the given name and description.
73
+ * The default is that the argument is required, and you can explicitly
74
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
75
+ *
76
+ * @param {string} name
77
+ * @param {string} [description]
78
+ */
79
+ constructor(name, description) {
80
+ this.description = description || "";
81
+ this.variadic = false;
82
+ this.parseArg = void 0;
83
+ this.defaultValue = void 0;
84
+ this.defaultValueDescription = void 0;
85
+ this.argChoices = void 0;
86
+ switch (name[0]) {
87
+ case "<":
88
+ this.required = true;
89
+ this._name = name.slice(1, -1);
90
+ break;
91
+ case "[":
92
+ this.required = false;
93
+ this._name = name.slice(1, -1);
94
+ break;
95
+ default:
96
+ this.required = true;
97
+ this._name = name;
98
+ break;
99
+ }
100
+ if (this._name.length > 3 && this._name.slice(-3) === "...") {
101
+ this.variadic = true;
102
+ this._name = this._name.slice(0, -3);
103
+ }
104
+ }
105
+ /**
106
+ * Return argument name.
107
+ *
108
+ * @return {string}
109
+ */
110
+ name() {
111
+ return this._name;
112
+ }
113
+ /**
114
+ * @api private
115
+ */
116
+ _concatValue(value, previous) {
117
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
118
+ return [value];
119
+ }
120
+ return previous.concat(value);
121
+ }
122
+ /**
123
+ * Set the default value, and optionally supply the description to be displayed in the help.
124
+ *
125
+ * @param {*} value
126
+ * @param {string} [description]
127
+ * @return {Argument}
128
+ */
129
+ default(value, description) {
130
+ this.defaultValue = value;
131
+ this.defaultValueDescription = description;
132
+ return this;
133
+ }
134
+ /**
135
+ * Set the custom handler for processing CLI command arguments into argument values.
136
+ *
137
+ * @param {Function} [fn]
138
+ * @return {Argument}
139
+ */
140
+ argParser(fn) {
141
+ this.parseArg = fn;
142
+ return this;
143
+ }
144
+ /**
145
+ * Only allow argument value to be one of choices.
146
+ *
147
+ * @param {string[]} values
148
+ * @return {Argument}
149
+ */
150
+ choices(values) {
151
+ this.argChoices = values.slice();
152
+ this.parseArg = (arg, previous) => {
153
+ if (!this.argChoices.includes(arg)) {
154
+ throw new InvalidArgumentError2(`Allowed choices are ${this.argChoices.join(", ")}.`);
155
+ }
156
+ if (this.variadic) {
157
+ return this._concatValue(arg, previous);
158
+ }
159
+ return arg;
160
+ };
161
+ return this;
162
+ }
163
+ /**
164
+ * Make argument required.
165
+ */
166
+ argRequired() {
167
+ this.required = true;
168
+ return this;
169
+ }
170
+ /**
171
+ * Make argument optional.
172
+ */
173
+ argOptional() {
174
+ this.required = false;
175
+ return this;
176
+ }
177
+ };
178
+ function humanReadableArgName(arg) {
179
+ const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
180
+ return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
181
+ }
182
+ exports2.Argument = Argument2;
183
+ exports2.humanReadableArgName = humanReadableArgName;
184
+ }
185
+ });
186
+
187
+ // node_modules/commander/lib/help.js
188
+ var require_help = __commonJS({
189
+ "node_modules/commander/lib/help.js"(exports2) {
190
+ var { humanReadableArgName } = require_argument();
191
+ var Help2 = class {
192
+ constructor() {
193
+ this.helpWidth = void 0;
194
+ this.sortSubcommands = false;
195
+ this.sortOptions = false;
196
+ this.showGlobalOptions = false;
197
+ }
198
+ /**
199
+ * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
200
+ *
201
+ * @param {Command} cmd
202
+ * @returns {Command[]}
203
+ */
204
+ visibleCommands(cmd) {
205
+ const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
206
+ if (cmd._hasImplicitHelpCommand()) {
207
+ const [, helpName, helpArgs] = cmd._helpCommandnameAndArgs.match(/([^ ]+) *(.*)/);
208
+ const helpCommand = cmd.createCommand(helpName).helpOption(false);
209
+ helpCommand.description(cmd._helpCommandDescription);
210
+ if (helpArgs)
211
+ helpCommand.arguments(helpArgs);
212
+ visibleCommands.push(helpCommand);
213
+ }
214
+ if (this.sortSubcommands) {
215
+ visibleCommands.sort((a, b) => {
216
+ return a.name().localeCompare(b.name());
217
+ });
218
+ }
219
+ return visibleCommands;
220
+ }
221
+ /**
222
+ * Compare options for sort.
223
+ *
224
+ * @param {Option} a
225
+ * @param {Option} b
226
+ * @returns number
227
+ */
228
+ compareOptions(a, b) {
229
+ const getSortKey = (option) => {
230
+ return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
231
+ };
232
+ return getSortKey(a).localeCompare(getSortKey(b));
233
+ }
234
+ /**
235
+ * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
236
+ *
237
+ * @param {Command} cmd
238
+ * @returns {Option[]}
239
+ */
240
+ visibleOptions(cmd) {
241
+ const visibleOptions = cmd.options.filter((option) => !option.hidden);
242
+ const showShortHelpFlag = cmd._hasHelpOption && cmd._helpShortFlag && !cmd._findOption(cmd._helpShortFlag);
243
+ const showLongHelpFlag = cmd._hasHelpOption && !cmd._findOption(cmd._helpLongFlag);
244
+ if (showShortHelpFlag || showLongHelpFlag) {
245
+ let helpOption;
246
+ if (!showShortHelpFlag) {
247
+ helpOption = cmd.createOption(cmd._helpLongFlag, cmd._helpDescription);
248
+ } else if (!showLongHelpFlag) {
249
+ helpOption = cmd.createOption(cmd._helpShortFlag, cmd._helpDescription);
250
+ } else {
251
+ helpOption = cmd.createOption(cmd._helpFlags, cmd._helpDescription);
252
+ }
253
+ visibleOptions.push(helpOption);
254
+ }
255
+ if (this.sortOptions) {
256
+ visibleOptions.sort(this.compareOptions);
257
+ }
258
+ return visibleOptions;
259
+ }
260
+ /**
261
+ * Get an array of the visible global options. (Not including help.)
262
+ *
263
+ * @param {Command} cmd
264
+ * @returns {Option[]}
265
+ */
266
+ visibleGlobalOptions(cmd) {
267
+ if (!this.showGlobalOptions)
268
+ return [];
269
+ const globalOptions = [];
270
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
271
+ const visibleOptions = ancestorCmd.options.filter((option) => !option.hidden);
272
+ globalOptions.push(...visibleOptions);
273
+ }
274
+ if (this.sortOptions) {
275
+ globalOptions.sort(this.compareOptions);
276
+ }
277
+ return globalOptions;
278
+ }
279
+ /**
280
+ * Get an array of the arguments if any have a description.
281
+ *
282
+ * @param {Command} cmd
283
+ * @returns {Argument[]}
284
+ */
285
+ visibleArguments(cmd) {
286
+ if (cmd._argsDescription) {
287
+ cmd.registeredArguments.forEach((argument) => {
288
+ argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
289
+ });
290
+ }
291
+ if (cmd.registeredArguments.find((argument) => argument.description)) {
292
+ return cmd.registeredArguments;
293
+ }
294
+ return [];
295
+ }
296
+ /**
297
+ * Get the command term to show in the list of subcommands.
298
+ *
299
+ * @param {Command} cmd
300
+ * @returns {string}
301
+ */
302
+ subcommandTerm(cmd) {
303
+ const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
304
+ return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + // simplistic check for non-help option
305
+ (args ? " " + args : "");
306
+ }
307
+ /**
308
+ * Get the option term to show in the list of options.
309
+ *
310
+ * @param {Option} option
311
+ * @returns {string}
312
+ */
313
+ optionTerm(option) {
314
+ return option.flags;
315
+ }
316
+ /**
317
+ * Get the argument term to show in the list of arguments.
318
+ *
319
+ * @param {Argument} argument
320
+ * @returns {string}
321
+ */
322
+ argumentTerm(argument) {
323
+ return argument.name();
324
+ }
325
+ /**
326
+ * Get the longest command term length.
327
+ *
328
+ * @param {Command} cmd
329
+ * @param {Help} helper
330
+ * @returns {number}
331
+ */
332
+ longestSubcommandTermLength(cmd, helper) {
333
+ return helper.visibleCommands(cmd).reduce((max, command) => {
334
+ return Math.max(max, helper.subcommandTerm(command).length);
335
+ }, 0);
336
+ }
337
+ /**
338
+ * Get the longest option term length.
339
+ *
340
+ * @param {Command} cmd
341
+ * @param {Help} helper
342
+ * @returns {number}
343
+ */
344
+ longestOptionTermLength(cmd, helper) {
345
+ return helper.visibleOptions(cmd).reduce((max, option) => {
346
+ return Math.max(max, helper.optionTerm(option).length);
347
+ }, 0);
348
+ }
349
+ /**
350
+ * Get the longest global option term length.
351
+ *
352
+ * @param {Command} cmd
353
+ * @param {Help} helper
354
+ * @returns {number}
355
+ */
356
+ longestGlobalOptionTermLength(cmd, helper) {
357
+ return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
358
+ return Math.max(max, helper.optionTerm(option).length);
359
+ }, 0);
360
+ }
361
+ /**
362
+ * Get the longest argument term length.
363
+ *
364
+ * @param {Command} cmd
365
+ * @param {Help} helper
366
+ * @returns {number}
367
+ */
368
+ longestArgumentTermLength(cmd, helper) {
369
+ return helper.visibleArguments(cmd).reduce((max, argument) => {
370
+ return Math.max(max, helper.argumentTerm(argument).length);
371
+ }, 0);
372
+ }
373
+ /**
374
+ * Get the command usage to be displayed at the top of the built-in help.
375
+ *
376
+ * @param {Command} cmd
377
+ * @returns {string}
378
+ */
379
+ commandUsage(cmd) {
380
+ let cmdName = cmd._name;
381
+ if (cmd._aliases[0]) {
382
+ cmdName = cmdName + "|" + cmd._aliases[0];
383
+ }
384
+ let ancestorCmdNames = "";
385
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
386
+ ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
387
+ }
388
+ return ancestorCmdNames + cmdName + " " + cmd.usage();
389
+ }
390
+ /**
391
+ * Get the description for the command.
392
+ *
393
+ * @param {Command} cmd
394
+ * @returns {string}
395
+ */
396
+ commandDescription(cmd) {
397
+ return cmd.description();
398
+ }
399
+ /**
400
+ * Get the subcommand summary to show in the list of subcommands.
401
+ * (Fallback to description for backwards compatibility.)
402
+ *
403
+ * @param {Command} cmd
404
+ * @returns {string}
405
+ */
406
+ subcommandDescription(cmd) {
407
+ return cmd.summary() || cmd.description();
408
+ }
409
+ /**
410
+ * Get the option description to show in the list of options.
411
+ *
412
+ * @param {Option} option
413
+ * @return {string}
414
+ */
415
+ optionDescription(option) {
416
+ const extraInfo = [];
417
+ if (option.argChoices) {
418
+ extraInfo.push(
419
+ // use stringify to match the display of the default value
420
+ `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
421
+ );
422
+ }
423
+ if (option.defaultValue !== void 0) {
424
+ const showDefault = option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean";
425
+ if (showDefault) {
426
+ extraInfo.push(`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`);
427
+ }
428
+ }
429
+ if (option.presetArg !== void 0 && option.optional) {
430
+ extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
431
+ }
432
+ if (option.envVar !== void 0) {
433
+ extraInfo.push(`env: ${option.envVar}`);
434
+ }
435
+ if (extraInfo.length > 0) {
436
+ return `${option.description} (${extraInfo.join(", ")})`;
437
+ }
438
+ return option.description;
439
+ }
440
+ /**
441
+ * Get the argument description to show in the list of arguments.
442
+ *
443
+ * @param {Argument} argument
444
+ * @return {string}
445
+ */
446
+ argumentDescription(argument) {
447
+ const extraInfo = [];
448
+ if (argument.argChoices) {
449
+ extraInfo.push(
450
+ // use stringify to match the display of the default value
451
+ `choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
452
+ );
453
+ }
454
+ if (argument.defaultValue !== void 0) {
455
+ extraInfo.push(`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`);
456
+ }
457
+ if (extraInfo.length > 0) {
458
+ const extraDescripton = `(${extraInfo.join(", ")})`;
459
+ if (argument.description) {
460
+ return `${argument.description} ${extraDescripton}`;
461
+ }
462
+ return extraDescripton;
463
+ }
464
+ return argument.description;
465
+ }
466
+ /**
467
+ * Generate the built-in help text.
468
+ *
469
+ * @param {Command} cmd
470
+ * @param {Help} helper
471
+ * @returns {string}
472
+ */
473
+ formatHelp(cmd, helper) {
474
+ const termWidth = helper.padWidth(cmd, helper);
475
+ const helpWidth = helper.helpWidth || 80;
476
+ const itemIndentWidth = 2;
477
+ const itemSeparatorWidth = 2;
478
+ function formatItem(term, description) {
479
+ if (description) {
480
+ const fullText = `${term.padEnd(termWidth + itemSeparatorWidth)}${description}`;
481
+ return helper.wrap(fullText, helpWidth - itemIndentWidth, termWidth + itemSeparatorWidth);
482
+ }
483
+ return term;
484
+ }
485
+ function formatList(textArray) {
486
+ return textArray.join("\n").replace(/^/gm, " ".repeat(itemIndentWidth));
487
+ }
488
+ let output = [`Usage: ${helper.commandUsage(cmd)}`, ""];
489
+ const commandDescription = helper.commandDescription(cmd);
490
+ if (commandDescription.length > 0) {
491
+ output = output.concat([helper.wrap(commandDescription, helpWidth, 0), ""]);
492
+ }
493
+ const argumentList = helper.visibleArguments(cmd).map((argument) => {
494
+ return formatItem(helper.argumentTerm(argument), helper.argumentDescription(argument));
495
+ });
496
+ if (argumentList.length > 0) {
497
+ output = output.concat(["Arguments:", formatList(argumentList), ""]);
498
+ }
499
+ const optionList = helper.visibleOptions(cmd).map((option) => {
500
+ return formatItem(helper.optionTerm(option), helper.optionDescription(option));
501
+ });
502
+ if (optionList.length > 0) {
503
+ output = output.concat(["Options:", formatList(optionList), ""]);
504
+ }
505
+ if (this.showGlobalOptions) {
506
+ const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
507
+ return formatItem(helper.optionTerm(option), helper.optionDescription(option));
508
+ });
509
+ if (globalOptionList.length > 0) {
510
+ output = output.concat(["Global Options:", formatList(globalOptionList), ""]);
511
+ }
512
+ }
513
+ const commandList = helper.visibleCommands(cmd).map((cmd2) => {
514
+ return formatItem(helper.subcommandTerm(cmd2), helper.subcommandDescription(cmd2));
515
+ });
516
+ if (commandList.length > 0) {
517
+ output = output.concat(["Commands:", formatList(commandList), ""]);
518
+ }
519
+ return output.join("\n");
520
+ }
521
+ /**
522
+ * Calculate the pad width from the maximum term length.
523
+ *
524
+ * @param {Command} cmd
525
+ * @param {Help} helper
526
+ * @returns {number}
527
+ */
528
+ padWidth(cmd, helper) {
529
+ return Math.max(
530
+ helper.longestOptionTermLength(cmd, helper),
531
+ helper.longestGlobalOptionTermLength(cmd, helper),
532
+ helper.longestSubcommandTermLength(cmd, helper),
533
+ helper.longestArgumentTermLength(cmd, helper)
534
+ );
535
+ }
536
+ /**
537
+ * Wrap the given string to width characters per line, with lines after the first indented.
538
+ * Do not wrap if insufficient room for wrapping (minColumnWidth), or string is manually formatted.
539
+ *
540
+ * @param {string} str
541
+ * @param {number} width
542
+ * @param {number} indent
543
+ * @param {number} [minColumnWidth=40]
544
+ * @return {string}
545
+ *
546
+ */
547
+ wrap(str, width, indent, minColumnWidth = 40) {
548
+ const indents = " \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF";
549
+ const manualIndent = new RegExp(`[\\n][${indents}]+`);
550
+ if (str.match(manualIndent))
551
+ return str;
552
+ const columnWidth = width - indent;
553
+ if (columnWidth < minColumnWidth)
554
+ return str;
555
+ const leadingStr = str.slice(0, indent);
556
+ const columnText = str.slice(indent).replace("\r\n", "\n");
557
+ const indentString = " ".repeat(indent);
558
+ const zeroWidthSpace = "\u200B";
559
+ const breaks = `\\s${zeroWidthSpace}`;
560
+ const regex = new RegExp(`
561
+ |.{1,${columnWidth - 1}}([${breaks}]|$)|[^${breaks}]+?([${breaks}]|$)`, "g");
562
+ const lines = columnText.match(regex) || [];
563
+ return leadingStr + lines.map((line, i) => {
564
+ if (line === "\n")
565
+ return "";
566
+ return (i > 0 ? indentString : "") + line.trimEnd();
567
+ }).join("\n");
568
+ }
569
+ };
570
+ exports2.Help = Help2;
571
+ }
572
+ });
573
+
574
+ // node_modules/commander/lib/option.js
575
+ var require_option = __commonJS({
576
+ "node_modules/commander/lib/option.js"(exports2) {
577
+ var { InvalidArgumentError: InvalidArgumentError2 } = require_error();
578
+ var Option2 = class {
579
+ /**
580
+ * Initialize a new `Option` with the given `flags` and `description`.
581
+ *
582
+ * @param {string} flags
583
+ * @param {string} [description]
584
+ */
585
+ constructor(flags, description) {
586
+ this.flags = flags;
587
+ this.description = description || "";
588
+ this.required = flags.includes("<");
589
+ this.optional = flags.includes("[");
590
+ this.variadic = /\w\.\.\.[>\]]$/.test(flags);
591
+ this.mandatory = false;
592
+ const optionFlags = splitOptionFlags(flags);
593
+ this.short = optionFlags.shortFlag;
594
+ this.long = optionFlags.longFlag;
595
+ this.negate = false;
596
+ if (this.long) {
597
+ this.negate = this.long.startsWith("--no-");
598
+ }
599
+ this.defaultValue = void 0;
600
+ this.defaultValueDescription = void 0;
601
+ this.presetArg = void 0;
602
+ this.envVar = void 0;
603
+ this.parseArg = void 0;
604
+ this.hidden = false;
605
+ this.argChoices = void 0;
606
+ this.conflictsWith = [];
607
+ this.implied = void 0;
608
+ }
609
+ /**
610
+ * Set the default value, and optionally supply the description to be displayed in the help.
611
+ *
612
+ * @param {*} value
613
+ * @param {string} [description]
614
+ * @return {Option}
615
+ */
616
+ default(value, description) {
617
+ this.defaultValue = value;
618
+ this.defaultValueDescription = description;
619
+ return this;
620
+ }
621
+ /**
622
+ * Preset to use when option used without option-argument, especially optional but also boolean and negated.
623
+ * The custom processing (parseArg) is called.
624
+ *
625
+ * @example
626
+ * new Option('--color').default('GREYSCALE').preset('RGB');
627
+ * new Option('--donate [amount]').preset('20').argParser(parseFloat);
628
+ *
629
+ * @param {*} arg
630
+ * @return {Option}
631
+ */
632
+ preset(arg) {
633
+ this.presetArg = arg;
634
+ return this;
635
+ }
636
+ /**
637
+ * Add option name(s) that conflict with this option.
638
+ * An error will be displayed if conflicting options are found during parsing.
639
+ *
640
+ * @example
641
+ * new Option('--rgb').conflicts('cmyk');
642
+ * new Option('--js').conflicts(['ts', 'jsx']);
643
+ *
644
+ * @param {string | string[]} names
645
+ * @return {Option}
646
+ */
647
+ conflicts(names) {
648
+ this.conflictsWith = this.conflictsWith.concat(names);
649
+ return this;
650
+ }
651
+ /**
652
+ * Specify implied option values for when this option is set and the implied options are not.
653
+ *
654
+ * The custom processing (parseArg) is not called on the implied values.
655
+ *
656
+ * @example
657
+ * program
658
+ * .addOption(new Option('--log', 'write logging information to file'))
659
+ * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
660
+ *
661
+ * @param {Object} impliedOptionValues
662
+ * @return {Option}
663
+ */
664
+ implies(impliedOptionValues) {
665
+ let newImplied = impliedOptionValues;
666
+ if (typeof impliedOptionValues === "string") {
667
+ newImplied = { [impliedOptionValues]: true };
668
+ }
669
+ this.implied = Object.assign(this.implied || {}, newImplied);
670
+ return this;
671
+ }
672
+ /**
673
+ * Set environment variable to check for option value.
674
+ *
675
+ * An environment variable is only used if when processed the current option value is
676
+ * undefined, or the source of the current value is 'default' or 'config' or 'env'.
677
+ *
678
+ * @param {string} name
679
+ * @return {Option}
680
+ */
681
+ env(name) {
682
+ this.envVar = name;
683
+ return this;
684
+ }
685
+ /**
686
+ * Set the custom handler for processing CLI option arguments into option values.
687
+ *
688
+ * @param {Function} [fn]
689
+ * @return {Option}
690
+ */
691
+ argParser(fn) {
692
+ this.parseArg = fn;
693
+ return this;
694
+ }
695
+ /**
696
+ * Whether the option is mandatory and must have a value after parsing.
697
+ *
698
+ * @param {boolean} [mandatory=true]
699
+ * @return {Option}
700
+ */
701
+ makeOptionMandatory(mandatory = true) {
702
+ this.mandatory = !!mandatory;
703
+ return this;
704
+ }
705
+ /**
706
+ * Hide option in help.
707
+ *
708
+ * @param {boolean} [hide=true]
709
+ * @return {Option}
710
+ */
711
+ hideHelp(hide = true) {
712
+ this.hidden = !!hide;
713
+ return this;
714
+ }
715
+ /**
716
+ * @api private
717
+ */
718
+ _concatValue(value, previous) {
719
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
720
+ return [value];
721
+ }
722
+ return previous.concat(value);
723
+ }
724
+ /**
725
+ * Only allow option value to be one of choices.
726
+ *
727
+ * @param {string[]} values
728
+ * @return {Option}
729
+ */
730
+ choices(values) {
731
+ this.argChoices = values.slice();
732
+ this.parseArg = (arg, previous) => {
733
+ if (!this.argChoices.includes(arg)) {
734
+ throw new InvalidArgumentError2(`Allowed choices are ${this.argChoices.join(", ")}.`);
735
+ }
736
+ if (this.variadic) {
737
+ return this._concatValue(arg, previous);
738
+ }
739
+ return arg;
740
+ };
741
+ return this;
742
+ }
743
+ /**
744
+ * Return option name.
745
+ *
746
+ * @return {string}
747
+ */
748
+ name() {
749
+ if (this.long) {
750
+ return this.long.replace(/^--/, "");
751
+ }
752
+ return this.short.replace(/^-/, "");
753
+ }
754
+ /**
755
+ * Return option name, in a camelcase format that can be used
756
+ * as a object attribute key.
757
+ *
758
+ * @return {string}
759
+ * @api private
760
+ */
761
+ attributeName() {
762
+ return camelcase(this.name().replace(/^no-/, ""));
763
+ }
764
+ /**
765
+ * Check if `arg` matches the short or long flag.
766
+ *
767
+ * @param {string} arg
768
+ * @return {boolean}
769
+ * @api private
770
+ */
771
+ is(arg) {
772
+ return this.short === arg || this.long === arg;
773
+ }
774
+ /**
775
+ * Return whether a boolean option.
776
+ *
777
+ * Options are one of boolean, negated, required argument, or optional argument.
778
+ *
779
+ * @return {boolean}
780
+ * @api private
781
+ */
782
+ isBoolean() {
783
+ return !this.required && !this.optional && !this.negate;
784
+ }
785
+ };
786
+ var DualOptions = class {
787
+ /**
788
+ * @param {Option[]} options
789
+ */
790
+ constructor(options) {
791
+ this.positiveOptions = /* @__PURE__ */ new Map();
792
+ this.negativeOptions = /* @__PURE__ */ new Map();
793
+ this.dualOptions = /* @__PURE__ */ new Set();
794
+ options.forEach((option) => {
795
+ if (option.negate) {
796
+ this.negativeOptions.set(option.attributeName(), option);
797
+ } else {
798
+ this.positiveOptions.set(option.attributeName(), option);
799
+ }
800
+ });
801
+ this.negativeOptions.forEach((value, key) => {
802
+ if (this.positiveOptions.has(key)) {
803
+ this.dualOptions.add(key);
804
+ }
805
+ });
806
+ }
807
+ /**
808
+ * Did the value come from the option, and not from possible matching dual option?
809
+ *
810
+ * @param {*} value
811
+ * @param {Option} option
812
+ * @returns {boolean}
813
+ */
814
+ valueFromOption(value, option) {
815
+ const optionKey = option.attributeName();
816
+ if (!this.dualOptions.has(optionKey))
817
+ return true;
818
+ const preset = this.negativeOptions.get(optionKey).presetArg;
819
+ const negativeValue = preset !== void 0 ? preset : false;
820
+ return option.negate === (negativeValue === value);
821
+ }
822
+ };
823
+ function camelcase(str) {
824
+ return str.split("-").reduce((str2, word) => {
825
+ return str2 + word[0].toUpperCase() + word.slice(1);
826
+ });
827
+ }
828
+ function splitOptionFlags(flags) {
829
+ let shortFlag;
830
+ let longFlag;
831
+ const flagParts = flags.split(/[ |,]+/);
832
+ if (flagParts.length > 1 && !/^[[<]/.test(flagParts[1]))
833
+ shortFlag = flagParts.shift();
834
+ longFlag = flagParts.shift();
835
+ if (!shortFlag && /^-[^-]$/.test(longFlag)) {
836
+ shortFlag = longFlag;
837
+ longFlag = void 0;
838
+ }
839
+ return { shortFlag, longFlag };
840
+ }
841
+ exports2.Option = Option2;
842
+ exports2.splitOptionFlags = splitOptionFlags;
843
+ exports2.DualOptions = DualOptions;
844
+ }
845
+ });
846
+
847
+ // node_modules/commander/lib/suggestSimilar.js
848
+ var require_suggestSimilar = __commonJS({
849
+ "node_modules/commander/lib/suggestSimilar.js"(exports2) {
850
+ var maxDistance = 3;
851
+ function editDistance(a, b) {
852
+ if (Math.abs(a.length - b.length) > maxDistance)
853
+ return Math.max(a.length, b.length);
854
+ const d = [];
855
+ for (let i = 0; i <= a.length; i++) {
856
+ d[i] = [i];
857
+ }
858
+ for (let j = 0; j <= b.length; j++) {
859
+ d[0][j] = j;
860
+ }
861
+ for (let j = 1; j <= b.length; j++) {
862
+ for (let i = 1; i <= a.length; i++) {
863
+ let cost = 1;
864
+ if (a[i - 1] === b[j - 1]) {
865
+ cost = 0;
866
+ } else {
867
+ cost = 1;
868
+ }
869
+ d[i][j] = Math.min(
870
+ d[i - 1][j] + 1,
871
+ // deletion
872
+ d[i][j - 1] + 1,
873
+ // insertion
874
+ d[i - 1][j - 1] + cost
875
+ // substitution
876
+ );
877
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
878
+ d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
879
+ }
880
+ }
881
+ }
882
+ return d[a.length][b.length];
883
+ }
884
+ function suggestSimilar(word, candidates) {
885
+ if (!candidates || candidates.length === 0)
886
+ return "";
887
+ candidates = Array.from(new Set(candidates));
888
+ const searchingOptions = word.startsWith("--");
889
+ if (searchingOptions) {
890
+ word = word.slice(2);
891
+ candidates = candidates.map((candidate) => candidate.slice(2));
892
+ }
893
+ let similar = [];
894
+ let bestDistance = maxDistance;
895
+ const minSimilarity = 0.4;
896
+ candidates.forEach((candidate) => {
897
+ if (candidate.length <= 1)
898
+ return;
899
+ const distance = editDistance(word, candidate);
900
+ const length = Math.max(word.length, candidate.length);
901
+ const similarity = (length - distance) / length;
902
+ if (similarity > minSimilarity) {
903
+ if (distance < bestDistance) {
904
+ bestDistance = distance;
905
+ similar = [candidate];
906
+ } else if (distance === bestDistance) {
907
+ similar.push(candidate);
908
+ }
909
+ }
910
+ });
911
+ similar.sort((a, b) => a.localeCompare(b));
912
+ if (searchingOptions) {
913
+ similar = similar.map((candidate) => `--${candidate}`);
914
+ }
915
+ if (similar.length > 1) {
916
+ return `
917
+ (Did you mean one of ${similar.join(", ")}?)`;
918
+ }
919
+ if (similar.length === 1) {
920
+ return `
921
+ (Did you mean ${similar[0]}?)`;
922
+ }
923
+ return "";
924
+ }
925
+ exports2.suggestSimilar = suggestSimilar;
926
+ }
927
+ });
928
+
929
+ // node_modules/commander/lib/command.js
930
+ var require_command = __commonJS({
931
+ "node_modules/commander/lib/command.js"(exports2) {
932
+ var EventEmitter = require("events").EventEmitter;
933
+ var childProcess = require("child_process");
934
+ var path4 = require("path");
935
+ var fs4 = require("fs");
936
+ var process2 = require("process");
937
+ var { Argument: Argument2, humanReadableArgName } = require_argument();
938
+ var { CommanderError: CommanderError2 } = require_error();
939
+ var { Help: Help2 } = require_help();
940
+ var { Option: Option2, splitOptionFlags, DualOptions } = require_option();
941
+ var { suggestSimilar } = require_suggestSimilar();
942
+ var Command2 = class _Command extends EventEmitter {
943
+ /**
944
+ * Initialize a new `Command`.
945
+ *
946
+ * @param {string} [name]
947
+ */
948
+ constructor(name) {
949
+ super();
950
+ this.commands = [];
951
+ this.options = [];
952
+ this.parent = null;
953
+ this._allowUnknownOption = false;
954
+ this._allowExcessArguments = true;
955
+ this.registeredArguments = [];
956
+ this._args = this.registeredArguments;
957
+ this.args = [];
958
+ this.rawArgs = [];
959
+ this.processedArgs = [];
960
+ this._scriptPath = null;
961
+ this._name = name || "";
962
+ this._optionValues = {};
963
+ this._optionValueSources = {};
964
+ this._storeOptionsAsProperties = false;
965
+ this._actionHandler = null;
966
+ this._executableHandler = false;
967
+ this._executableFile = null;
968
+ this._executableDir = null;
969
+ this._defaultCommandName = null;
970
+ this._exitCallback = null;
971
+ this._aliases = [];
972
+ this._combineFlagAndOptionalValue = true;
973
+ this._description = "";
974
+ this._summary = "";
975
+ this._argsDescription = void 0;
976
+ this._enablePositionalOptions = false;
977
+ this._passThroughOptions = false;
978
+ this._lifeCycleHooks = {};
979
+ this._showHelpAfterError = false;
980
+ this._showSuggestionAfterError = true;
981
+ this._outputConfiguration = {
982
+ writeOut: (str) => process2.stdout.write(str),
983
+ writeErr: (str) => process2.stderr.write(str),
984
+ getOutHelpWidth: () => process2.stdout.isTTY ? process2.stdout.columns : void 0,
985
+ getErrHelpWidth: () => process2.stderr.isTTY ? process2.stderr.columns : void 0,
986
+ outputError: (str, write) => write(str)
987
+ };
988
+ this._hidden = false;
989
+ this._hasHelpOption = true;
990
+ this._helpFlags = "-h, --help";
991
+ this._helpDescription = "display help for command";
992
+ this._helpShortFlag = "-h";
993
+ this._helpLongFlag = "--help";
994
+ this._addImplicitHelpCommand = void 0;
995
+ this._helpCommandName = "help";
996
+ this._helpCommandnameAndArgs = "help [command]";
997
+ this._helpCommandDescription = "display help for command";
998
+ this._helpConfiguration = {};
999
+ }
1000
+ /**
1001
+ * Copy settings that are useful to have in common across root command and subcommands.
1002
+ *
1003
+ * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
1004
+ *
1005
+ * @param {Command} sourceCommand
1006
+ * @return {Command} `this` command for chaining
1007
+ */
1008
+ copyInheritedSettings(sourceCommand) {
1009
+ this._outputConfiguration = sourceCommand._outputConfiguration;
1010
+ this._hasHelpOption = sourceCommand._hasHelpOption;
1011
+ this._helpFlags = sourceCommand._helpFlags;
1012
+ this._helpDescription = sourceCommand._helpDescription;
1013
+ this._helpShortFlag = sourceCommand._helpShortFlag;
1014
+ this._helpLongFlag = sourceCommand._helpLongFlag;
1015
+ this._helpCommandName = sourceCommand._helpCommandName;
1016
+ this._helpCommandnameAndArgs = sourceCommand._helpCommandnameAndArgs;
1017
+ this._helpCommandDescription = sourceCommand._helpCommandDescription;
1018
+ this._helpConfiguration = sourceCommand._helpConfiguration;
1019
+ this._exitCallback = sourceCommand._exitCallback;
1020
+ this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
1021
+ this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
1022
+ this._allowExcessArguments = sourceCommand._allowExcessArguments;
1023
+ this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
1024
+ this._showHelpAfterError = sourceCommand._showHelpAfterError;
1025
+ this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
1026
+ return this;
1027
+ }
1028
+ /**
1029
+ * @returns {Command[]}
1030
+ * @api private
1031
+ */
1032
+ _getCommandAndAncestors() {
1033
+ const result = [];
1034
+ for (let command = this; command; command = command.parent) {
1035
+ result.push(command);
1036
+ }
1037
+ return result;
1038
+ }
1039
+ /**
1040
+ * Define a command.
1041
+ *
1042
+ * There are two styles of command: pay attention to where to put the description.
1043
+ *
1044
+ * @example
1045
+ * // Command implemented using action handler (description is supplied separately to `.command`)
1046
+ * program
1047
+ * .command('clone <source> [destination]')
1048
+ * .description('clone a repository into a newly created directory')
1049
+ * .action((source, destination) => {
1050
+ * console.log('clone command called');
1051
+ * });
1052
+ *
1053
+ * // Command implemented using separate executable file (description is second parameter to `.command`)
1054
+ * program
1055
+ * .command('start <service>', 'start named service')
1056
+ * .command('stop [service]', 'stop named service, or all if no name supplied');
1057
+ *
1058
+ * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
1059
+ * @param {Object|string} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
1060
+ * @param {Object} [execOpts] - configuration options (for executable)
1061
+ * @return {Command} returns new command for action handler, or `this` for executable command
1062
+ */
1063
+ command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
1064
+ let desc = actionOptsOrExecDesc;
1065
+ let opts = execOpts;
1066
+ if (typeof desc === "object" && desc !== null) {
1067
+ opts = desc;
1068
+ desc = null;
1069
+ }
1070
+ opts = opts || {};
1071
+ const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
1072
+ const cmd = this.createCommand(name);
1073
+ if (desc) {
1074
+ cmd.description(desc);
1075
+ cmd._executableHandler = true;
1076
+ }
1077
+ if (opts.isDefault)
1078
+ this._defaultCommandName = cmd._name;
1079
+ cmd._hidden = !!(opts.noHelp || opts.hidden);
1080
+ cmd._executableFile = opts.executableFile || null;
1081
+ if (args)
1082
+ cmd.arguments(args);
1083
+ this.commands.push(cmd);
1084
+ cmd.parent = this;
1085
+ cmd.copyInheritedSettings(this);
1086
+ if (desc)
1087
+ return this;
1088
+ return cmd;
1089
+ }
1090
+ /**
1091
+ * Factory routine to create a new unattached command.
1092
+ *
1093
+ * See .command() for creating an attached subcommand, which uses this routine to
1094
+ * create the command. You can override createCommand to customise subcommands.
1095
+ *
1096
+ * @param {string} [name]
1097
+ * @return {Command} new command
1098
+ */
1099
+ createCommand(name) {
1100
+ return new _Command(name);
1101
+ }
1102
+ /**
1103
+ * You can customise the help with a subclass of Help by overriding createHelp,
1104
+ * or by overriding Help properties using configureHelp().
1105
+ *
1106
+ * @return {Help}
1107
+ */
1108
+ createHelp() {
1109
+ return Object.assign(new Help2(), this.configureHelp());
1110
+ }
1111
+ /**
1112
+ * You can customise the help by overriding Help properties using configureHelp(),
1113
+ * or with a subclass of Help by overriding createHelp().
1114
+ *
1115
+ * @param {Object} [configuration] - configuration options
1116
+ * @return {Command|Object} `this` command for chaining, or stored configuration
1117
+ */
1118
+ configureHelp(configuration) {
1119
+ if (configuration === void 0)
1120
+ return this._helpConfiguration;
1121
+ this._helpConfiguration = configuration;
1122
+ return this;
1123
+ }
1124
+ /**
1125
+ * The default output goes to stdout and stderr. You can customise this for special
1126
+ * applications. You can also customise the display of errors by overriding outputError.
1127
+ *
1128
+ * The configuration properties are all functions:
1129
+ *
1130
+ * // functions to change where being written, stdout and stderr
1131
+ * writeOut(str)
1132
+ * writeErr(str)
1133
+ * // matching functions to specify width for wrapping help
1134
+ * getOutHelpWidth()
1135
+ * getErrHelpWidth()
1136
+ * // functions based on what is being written out
1137
+ * outputError(str, write) // used for displaying errors, and not used for displaying help
1138
+ *
1139
+ * @param {Object} [configuration] - configuration options
1140
+ * @return {Command|Object} `this` command for chaining, or stored configuration
1141
+ */
1142
+ configureOutput(configuration) {
1143
+ if (configuration === void 0)
1144
+ return this._outputConfiguration;
1145
+ Object.assign(this._outputConfiguration, configuration);
1146
+ return this;
1147
+ }
1148
+ /**
1149
+ * Display the help or a custom message after an error occurs.
1150
+ *
1151
+ * @param {boolean|string} [displayHelp]
1152
+ * @return {Command} `this` command for chaining
1153
+ */
1154
+ showHelpAfterError(displayHelp = true) {
1155
+ if (typeof displayHelp !== "string")
1156
+ displayHelp = !!displayHelp;
1157
+ this._showHelpAfterError = displayHelp;
1158
+ return this;
1159
+ }
1160
+ /**
1161
+ * Display suggestion of similar commands for unknown commands, or options for unknown options.
1162
+ *
1163
+ * @param {boolean} [displaySuggestion]
1164
+ * @return {Command} `this` command for chaining
1165
+ */
1166
+ showSuggestionAfterError(displaySuggestion = true) {
1167
+ this._showSuggestionAfterError = !!displaySuggestion;
1168
+ return this;
1169
+ }
1170
+ /**
1171
+ * Add a prepared subcommand.
1172
+ *
1173
+ * See .command() for creating an attached subcommand which inherits settings from its parent.
1174
+ *
1175
+ * @param {Command} cmd - new subcommand
1176
+ * @param {Object} [opts] - configuration options
1177
+ * @return {Command} `this` command for chaining
1178
+ */
1179
+ addCommand(cmd, opts) {
1180
+ if (!cmd._name) {
1181
+ throw new Error(`Command passed to .addCommand() must have a name
1182
+ - specify the name in Command constructor or using .name()`);
1183
+ }
1184
+ opts = opts || {};
1185
+ if (opts.isDefault)
1186
+ this._defaultCommandName = cmd._name;
1187
+ if (opts.noHelp || opts.hidden)
1188
+ cmd._hidden = true;
1189
+ this.commands.push(cmd);
1190
+ cmd.parent = this;
1191
+ return this;
1192
+ }
1193
+ /**
1194
+ * Factory routine to create a new unattached argument.
1195
+ *
1196
+ * See .argument() for creating an attached argument, which uses this routine to
1197
+ * create the argument. You can override createArgument to return a custom argument.
1198
+ *
1199
+ * @param {string} name
1200
+ * @param {string} [description]
1201
+ * @return {Argument} new argument
1202
+ */
1203
+ createArgument(name, description) {
1204
+ return new Argument2(name, description);
1205
+ }
1206
+ /**
1207
+ * Define argument syntax for command.
1208
+ *
1209
+ * The default is that the argument is required, and you can explicitly
1210
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
1211
+ *
1212
+ * @example
1213
+ * program.argument('<input-file>');
1214
+ * program.argument('[output-file]');
1215
+ *
1216
+ * @param {string} name
1217
+ * @param {string} [description]
1218
+ * @param {Function|*} [fn] - custom argument processing function
1219
+ * @param {*} [defaultValue]
1220
+ * @return {Command} `this` command for chaining
1221
+ */
1222
+ argument(name, description, fn, defaultValue) {
1223
+ const argument = this.createArgument(name, description);
1224
+ if (typeof fn === "function") {
1225
+ argument.default(defaultValue).argParser(fn);
1226
+ } else {
1227
+ argument.default(fn);
1228
+ }
1229
+ this.addArgument(argument);
1230
+ return this;
1231
+ }
1232
+ /**
1233
+ * Define argument syntax for command, adding multiple at once (without descriptions).
1234
+ *
1235
+ * See also .argument().
1236
+ *
1237
+ * @example
1238
+ * program.arguments('<cmd> [env]');
1239
+ *
1240
+ * @param {string} names
1241
+ * @return {Command} `this` command for chaining
1242
+ */
1243
+ arguments(names) {
1244
+ names.trim().split(/ +/).forEach((detail) => {
1245
+ this.argument(detail);
1246
+ });
1247
+ return this;
1248
+ }
1249
+ /**
1250
+ * Define argument syntax for command, adding a prepared argument.
1251
+ *
1252
+ * @param {Argument} argument
1253
+ * @return {Command} `this` command for chaining
1254
+ */
1255
+ addArgument(argument) {
1256
+ const previousArgument = this.registeredArguments.slice(-1)[0];
1257
+ if (previousArgument && previousArgument.variadic) {
1258
+ throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);
1259
+ }
1260
+ if (argument.required && argument.defaultValue !== void 0 && argument.parseArg === void 0) {
1261
+ throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);
1262
+ }
1263
+ this.registeredArguments.push(argument);
1264
+ return this;
1265
+ }
1266
+ /**
1267
+ * Override default decision whether to add implicit help command.
1268
+ *
1269
+ * addHelpCommand() // force on
1270
+ * addHelpCommand(false); // force off
1271
+ * addHelpCommand('help [cmd]', 'display help for [cmd]'); // force on with custom details
1272
+ *
1273
+ * @return {Command} `this` command for chaining
1274
+ */
1275
+ addHelpCommand(enableOrNameAndArgs, description) {
1276
+ if (enableOrNameAndArgs === false) {
1277
+ this._addImplicitHelpCommand = false;
1278
+ } else {
1279
+ this._addImplicitHelpCommand = true;
1280
+ if (typeof enableOrNameAndArgs === "string") {
1281
+ this._helpCommandName = enableOrNameAndArgs.split(" ")[0];
1282
+ this._helpCommandnameAndArgs = enableOrNameAndArgs;
1283
+ }
1284
+ this._helpCommandDescription = description || this._helpCommandDescription;
1285
+ }
1286
+ return this;
1287
+ }
1288
+ /**
1289
+ * @return {boolean}
1290
+ * @api private
1291
+ */
1292
+ _hasImplicitHelpCommand() {
1293
+ if (this._addImplicitHelpCommand === void 0) {
1294
+ return this.commands.length && !this._actionHandler && !this._findCommand("help");
1295
+ }
1296
+ return this._addImplicitHelpCommand;
1297
+ }
1298
+ /**
1299
+ * Add hook for life cycle event.
1300
+ *
1301
+ * @param {string} event
1302
+ * @param {Function} listener
1303
+ * @return {Command} `this` command for chaining
1304
+ */
1305
+ hook(event, listener) {
1306
+ const allowedValues = ["preSubcommand", "preAction", "postAction"];
1307
+ if (!allowedValues.includes(event)) {
1308
+ throw new Error(`Unexpected value for event passed to hook : '${event}'.
1309
+ Expecting one of '${allowedValues.join("', '")}'`);
1310
+ }
1311
+ if (this._lifeCycleHooks[event]) {
1312
+ this._lifeCycleHooks[event].push(listener);
1313
+ } else {
1314
+ this._lifeCycleHooks[event] = [listener];
1315
+ }
1316
+ return this;
1317
+ }
1318
+ /**
1319
+ * Register callback to use as replacement for calling process.exit.
1320
+ *
1321
+ * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
1322
+ * @return {Command} `this` command for chaining
1323
+ */
1324
+ exitOverride(fn) {
1325
+ if (fn) {
1326
+ this._exitCallback = fn;
1327
+ } else {
1328
+ this._exitCallback = (err) => {
1329
+ if (err.code !== "commander.executeSubCommandAsync") {
1330
+ throw err;
1331
+ } else {
1332
+ }
1333
+ };
1334
+ }
1335
+ return this;
1336
+ }
1337
+ /**
1338
+ * Call process.exit, and _exitCallback if defined.
1339
+ *
1340
+ * @param {number} exitCode exit code for using with process.exit
1341
+ * @param {string} code an id string representing the error
1342
+ * @param {string} message human-readable description of the error
1343
+ * @return never
1344
+ * @api private
1345
+ */
1346
+ _exit(exitCode, code, message) {
1347
+ if (this._exitCallback) {
1348
+ this._exitCallback(new CommanderError2(exitCode, code, message));
1349
+ }
1350
+ process2.exit(exitCode);
1351
+ }
1352
+ /**
1353
+ * Register callback `fn` for the command.
1354
+ *
1355
+ * @example
1356
+ * program
1357
+ * .command('serve')
1358
+ * .description('start service')
1359
+ * .action(function() {
1360
+ * // do work here
1361
+ * });
1362
+ *
1363
+ * @param {Function} fn
1364
+ * @return {Command} `this` command for chaining
1365
+ */
1366
+ action(fn) {
1367
+ const listener = (args) => {
1368
+ const expectedArgsCount = this.registeredArguments.length;
1369
+ const actionArgs = args.slice(0, expectedArgsCount);
1370
+ if (this._storeOptionsAsProperties) {
1371
+ actionArgs[expectedArgsCount] = this;
1372
+ } else {
1373
+ actionArgs[expectedArgsCount] = this.opts();
1374
+ }
1375
+ actionArgs.push(this);
1376
+ return fn.apply(this, actionArgs);
1377
+ };
1378
+ this._actionHandler = listener;
1379
+ return this;
1380
+ }
1381
+ /**
1382
+ * Factory routine to create a new unattached option.
1383
+ *
1384
+ * See .option() for creating an attached option, which uses this routine to
1385
+ * create the option. You can override createOption to return a custom option.
1386
+ *
1387
+ * @param {string} flags
1388
+ * @param {string} [description]
1389
+ * @return {Option} new option
1390
+ */
1391
+ createOption(flags, description) {
1392
+ return new Option2(flags, description);
1393
+ }
1394
+ /**
1395
+ * Wrap parseArgs to catch 'commander.invalidArgument'.
1396
+ *
1397
+ * @param {Option | Argument} target
1398
+ * @param {string} value
1399
+ * @param {*} previous
1400
+ * @param {string} invalidArgumentMessage
1401
+ * @api private
1402
+ */
1403
+ _callParseArg(target, value, previous, invalidArgumentMessage) {
1404
+ try {
1405
+ return target.parseArg(value, previous);
1406
+ } catch (err) {
1407
+ if (err.code === "commander.invalidArgument") {
1408
+ const message = `${invalidArgumentMessage} ${err.message}`;
1409
+ this.error(message, { exitCode: err.exitCode, code: err.code });
1410
+ }
1411
+ throw err;
1412
+ }
1413
+ }
1414
+ /**
1415
+ * Add an option.
1416
+ *
1417
+ * @param {Option} option
1418
+ * @return {Command} `this` command for chaining
1419
+ */
1420
+ addOption(option) {
1421
+ const oname = option.name();
1422
+ const name = option.attributeName();
1423
+ if (option.negate) {
1424
+ const positiveLongFlag = option.long.replace(/^--no-/, "--");
1425
+ if (!this._findOption(positiveLongFlag)) {
1426
+ this.setOptionValueWithSource(name, option.defaultValue === void 0 ? true : option.defaultValue, "default");
1427
+ }
1428
+ } else if (option.defaultValue !== void 0) {
1429
+ this.setOptionValueWithSource(name, option.defaultValue, "default");
1430
+ }
1431
+ this.options.push(option);
1432
+ const handleOptionValue = (val, invalidValueMessage, valueSource) => {
1433
+ if (val == null && option.presetArg !== void 0) {
1434
+ val = option.presetArg;
1435
+ }
1436
+ const oldValue = this.getOptionValue(name);
1437
+ if (val !== null && option.parseArg) {
1438
+ val = this._callParseArg(option, val, oldValue, invalidValueMessage);
1439
+ } else if (val !== null && option.variadic) {
1440
+ val = option._concatValue(val, oldValue);
1441
+ }
1442
+ if (val == null) {
1443
+ if (option.negate) {
1444
+ val = false;
1445
+ } else if (option.isBoolean() || option.optional) {
1446
+ val = true;
1447
+ } else {
1448
+ val = "";
1449
+ }
1450
+ }
1451
+ this.setOptionValueWithSource(name, val, valueSource);
1452
+ };
1453
+ this.on("option:" + oname, (val) => {
1454
+ const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
1455
+ handleOptionValue(val, invalidValueMessage, "cli");
1456
+ });
1457
+ if (option.envVar) {
1458
+ this.on("optionEnv:" + oname, (val) => {
1459
+ const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
1460
+ handleOptionValue(val, invalidValueMessage, "env");
1461
+ });
1462
+ }
1463
+ return this;
1464
+ }
1465
+ /**
1466
+ * Internal implementation shared by .option() and .requiredOption()
1467
+ *
1468
+ * @api private
1469
+ */
1470
+ _optionEx(config, flags, description, fn, defaultValue) {
1471
+ if (typeof flags === "object" && flags instanceof Option2) {
1472
+ throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");
1473
+ }
1474
+ const option = this.createOption(flags, description);
1475
+ option.makeOptionMandatory(!!config.mandatory);
1476
+ if (typeof fn === "function") {
1477
+ option.default(defaultValue).argParser(fn);
1478
+ } else if (fn instanceof RegExp) {
1479
+ const regex = fn;
1480
+ fn = (val, def) => {
1481
+ const m = regex.exec(val);
1482
+ return m ? m[0] : def;
1483
+ };
1484
+ option.default(defaultValue).argParser(fn);
1485
+ } else {
1486
+ option.default(fn);
1487
+ }
1488
+ return this.addOption(option);
1489
+ }
1490
+ /**
1491
+ * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
1492
+ *
1493
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
1494
+ * option-argument is indicated by `<>` and an optional option-argument by `[]`.
1495
+ *
1496
+ * See the README for more details, and see also addOption() and requiredOption().
1497
+ *
1498
+ * @example
1499
+ * program
1500
+ * .option('-p, --pepper', 'add pepper')
1501
+ * .option('-p, --pizza-type <TYPE>', 'type of pizza') // required option-argument
1502
+ * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
1503
+ * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
1504
+ *
1505
+ * @param {string} flags
1506
+ * @param {string} [description]
1507
+ * @param {Function|*} [parseArg] - custom option processing function or default value
1508
+ * @param {*} [defaultValue]
1509
+ * @return {Command} `this` command for chaining
1510
+ */
1511
+ option(flags, description, parseArg, defaultValue) {
1512
+ return this._optionEx({}, flags, description, parseArg, defaultValue);
1513
+ }
1514
+ /**
1515
+ * Add a required option which must have a value after parsing. This usually means
1516
+ * the option must be specified on the command line. (Otherwise the same as .option().)
1517
+ *
1518
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
1519
+ *
1520
+ * @param {string} flags
1521
+ * @param {string} [description]
1522
+ * @param {Function|*} [parseArg] - custom option processing function or default value
1523
+ * @param {*} [defaultValue]
1524
+ * @return {Command} `this` command for chaining
1525
+ */
1526
+ requiredOption(flags, description, parseArg, defaultValue) {
1527
+ return this._optionEx({ mandatory: true }, flags, description, parseArg, defaultValue);
1528
+ }
1529
+ /**
1530
+ * Alter parsing of short flags with optional values.
1531
+ *
1532
+ * @example
1533
+ * // for `.option('-f,--flag [value]'):
1534
+ * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
1535
+ * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
1536
+ *
1537
+ * @param {Boolean} [combine=true] - if `true` or omitted, an optional value can be specified directly after the flag.
1538
+ */
1539
+ combineFlagAndOptionalValue(combine = true) {
1540
+ this._combineFlagAndOptionalValue = !!combine;
1541
+ return this;
1542
+ }
1543
+ /**
1544
+ * Allow unknown options on the command line.
1545
+ *
1546
+ * @param {Boolean} [allowUnknown=true] - if `true` or omitted, no error will be thrown
1547
+ * for unknown options.
1548
+ */
1549
+ allowUnknownOption(allowUnknown = true) {
1550
+ this._allowUnknownOption = !!allowUnknown;
1551
+ return this;
1552
+ }
1553
+ /**
1554
+ * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
1555
+ *
1556
+ * @param {Boolean} [allowExcess=true] - if `true` or omitted, no error will be thrown
1557
+ * for excess arguments.
1558
+ */
1559
+ allowExcessArguments(allowExcess = true) {
1560
+ this._allowExcessArguments = !!allowExcess;
1561
+ return this;
1562
+ }
1563
+ /**
1564
+ * Enable positional options. Positional means global options are specified before subcommands which lets
1565
+ * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
1566
+ * The default behaviour is non-positional and global options may appear anywhere on the command line.
1567
+ *
1568
+ * @param {Boolean} [positional=true]
1569
+ */
1570
+ enablePositionalOptions(positional = true) {
1571
+ this._enablePositionalOptions = !!positional;
1572
+ return this;
1573
+ }
1574
+ /**
1575
+ * Pass through options that come after command-arguments rather than treat them as command-options,
1576
+ * so actual command-options come before command-arguments. Turning this on for a subcommand requires
1577
+ * positional options to have been enabled on the program (parent commands).
1578
+ * The default behaviour is non-positional and options may appear before or after command-arguments.
1579
+ *
1580
+ * @param {Boolean} [passThrough=true]
1581
+ * for unknown options.
1582
+ */
1583
+ passThroughOptions(passThrough = true) {
1584
+ this._passThroughOptions = !!passThrough;
1585
+ if (!!this.parent && passThrough && !this.parent._enablePositionalOptions) {
1586
+ throw new Error("passThroughOptions can not be used without turning on enablePositionalOptions for parent command(s)");
1587
+ }
1588
+ return this;
1589
+ }
1590
+ /**
1591
+ * Whether to store option values as properties on command object,
1592
+ * or store separately (specify false). In both cases the option values can be accessed using .opts().
1593
+ *
1594
+ * @param {boolean} [storeAsProperties=true]
1595
+ * @return {Command} `this` command for chaining
1596
+ */
1597
+ storeOptionsAsProperties(storeAsProperties = true) {
1598
+ if (this.options.length) {
1599
+ throw new Error("call .storeOptionsAsProperties() before adding options");
1600
+ }
1601
+ this._storeOptionsAsProperties = !!storeAsProperties;
1602
+ return this;
1603
+ }
1604
+ /**
1605
+ * Retrieve option value.
1606
+ *
1607
+ * @param {string} key
1608
+ * @return {Object} value
1609
+ */
1610
+ getOptionValue(key) {
1611
+ if (this._storeOptionsAsProperties) {
1612
+ return this[key];
1613
+ }
1614
+ return this._optionValues[key];
1615
+ }
1616
+ /**
1617
+ * Store option value.
1618
+ *
1619
+ * @param {string} key
1620
+ * @param {Object} value
1621
+ * @return {Command} `this` command for chaining
1622
+ */
1623
+ setOptionValue(key, value) {
1624
+ return this.setOptionValueWithSource(key, value, void 0);
1625
+ }
1626
+ /**
1627
+ * Store option value and where the value came from.
1628
+ *
1629
+ * @param {string} key
1630
+ * @param {Object} value
1631
+ * @param {string} source - expected values are default/config/env/cli/implied
1632
+ * @return {Command} `this` command for chaining
1633
+ */
1634
+ setOptionValueWithSource(key, value, source) {
1635
+ if (this._storeOptionsAsProperties) {
1636
+ this[key] = value;
1637
+ } else {
1638
+ this._optionValues[key] = value;
1639
+ }
1640
+ this._optionValueSources[key] = source;
1641
+ return this;
1642
+ }
1643
+ /**
1644
+ * Get source of option value.
1645
+ * Expected values are default | config | env | cli | implied
1646
+ *
1647
+ * @param {string} key
1648
+ * @return {string}
1649
+ */
1650
+ getOptionValueSource(key) {
1651
+ return this._optionValueSources[key];
1652
+ }
1653
+ /**
1654
+ * Get source of option value. See also .optsWithGlobals().
1655
+ * Expected values are default | config | env | cli | implied
1656
+ *
1657
+ * @param {string} key
1658
+ * @return {string}
1659
+ */
1660
+ getOptionValueSourceWithGlobals(key) {
1661
+ let source;
1662
+ this._getCommandAndAncestors().forEach((cmd) => {
1663
+ if (cmd.getOptionValueSource(key) !== void 0) {
1664
+ source = cmd.getOptionValueSource(key);
1665
+ }
1666
+ });
1667
+ return source;
1668
+ }
1669
+ /**
1670
+ * Get user arguments from implied or explicit arguments.
1671
+ * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
1672
+ *
1673
+ * @api private
1674
+ */
1675
+ _prepareUserArgs(argv, parseOptions) {
1676
+ if (argv !== void 0 && !Array.isArray(argv)) {
1677
+ throw new Error("first parameter to parse must be array or undefined");
1678
+ }
1679
+ parseOptions = parseOptions || {};
1680
+ if (argv === void 0) {
1681
+ argv = process2.argv;
1682
+ if (process2.versions && process2.versions.electron) {
1683
+ parseOptions.from = "electron";
1684
+ }
1685
+ }
1686
+ this.rawArgs = argv.slice();
1687
+ let userArgs;
1688
+ switch (parseOptions.from) {
1689
+ case void 0:
1690
+ case "node":
1691
+ this._scriptPath = argv[1];
1692
+ userArgs = argv.slice(2);
1693
+ break;
1694
+ case "electron":
1695
+ if (process2.defaultApp) {
1696
+ this._scriptPath = argv[1];
1697
+ userArgs = argv.slice(2);
1698
+ } else {
1699
+ userArgs = argv.slice(1);
1700
+ }
1701
+ break;
1702
+ case "user":
1703
+ userArgs = argv.slice(0);
1704
+ break;
1705
+ default:
1706
+ throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);
1707
+ }
1708
+ if (!this._name && this._scriptPath)
1709
+ this.nameFromFilename(this._scriptPath);
1710
+ this._name = this._name || "program";
1711
+ return userArgs;
1712
+ }
1713
+ /**
1714
+ * Parse `argv`, setting options and invoking commands when defined.
1715
+ *
1716
+ * The default expectation is that the arguments are from node and have the application as argv[0]
1717
+ * and the script being run in argv[1], with user parameters after that.
1718
+ *
1719
+ * @example
1720
+ * program.parse(process.argv);
1721
+ * program.parse(); // implicitly use process.argv and auto-detect node vs electron conventions
1722
+ * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
1723
+ *
1724
+ * @param {string[]} [argv] - optional, defaults to process.argv
1725
+ * @param {Object} [parseOptions] - optionally specify style of options with from: node/user/electron
1726
+ * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
1727
+ * @return {Command} `this` command for chaining
1728
+ */
1729
+ parse(argv, parseOptions) {
1730
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1731
+ this._parseCommand([], userArgs);
1732
+ return this;
1733
+ }
1734
+ /**
1735
+ * Parse `argv`, setting options and invoking commands when defined.
1736
+ *
1737
+ * Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise.
1738
+ *
1739
+ * The default expectation is that the arguments are from node and have the application as argv[0]
1740
+ * and the script being run in argv[1], with user parameters after that.
1741
+ *
1742
+ * @example
1743
+ * await program.parseAsync(process.argv);
1744
+ * await program.parseAsync(); // implicitly use process.argv and auto-detect node vs electron conventions
1745
+ * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
1746
+ *
1747
+ * @param {string[]} [argv]
1748
+ * @param {Object} [parseOptions]
1749
+ * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
1750
+ * @return {Promise}
1751
+ */
1752
+ async parseAsync(argv, parseOptions) {
1753
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1754
+ await this._parseCommand([], userArgs);
1755
+ return this;
1756
+ }
1757
+ /**
1758
+ * Execute a sub-command executable.
1759
+ *
1760
+ * @api private
1761
+ */
1762
+ _executeSubCommand(subcommand, args) {
1763
+ args = args.slice();
1764
+ let launchWithNode = false;
1765
+ const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
1766
+ function findFile(baseDir, baseName) {
1767
+ const localBin = path4.resolve(baseDir, baseName);
1768
+ if (fs4.existsSync(localBin))
1769
+ return localBin;
1770
+ if (sourceExt.includes(path4.extname(baseName)))
1771
+ return void 0;
1772
+ const foundExt = sourceExt.find((ext) => fs4.existsSync(`${localBin}${ext}`));
1773
+ if (foundExt)
1774
+ return `${localBin}${foundExt}`;
1775
+ return void 0;
1776
+ }
1777
+ this._checkForMissingMandatoryOptions();
1778
+ this._checkForConflictingOptions();
1779
+ let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
1780
+ let executableDir = this._executableDir || "";
1781
+ if (this._scriptPath) {
1782
+ let resolvedScriptPath;
1783
+ try {
1784
+ resolvedScriptPath = fs4.realpathSync(this._scriptPath);
1785
+ } catch (err) {
1786
+ resolvedScriptPath = this._scriptPath;
1787
+ }
1788
+ executableDir = path4.resolve(path4.dirname(resolvedScriptPath), executableDir);
1789
+ }
1790
+ if (executableDir) {
1791
+ let localFile = findFile(executableDir, executableFile);
1792
+ if (!localFile && !subcommand._executableFile && this._scriptPath) {
1793
+ const legacyName = path4.basename(this._scriptPath, path4.extname(this._scriptPath));
1794
+ if (legacyName !== this._name) {
1795
+ localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);
1796
+ }
1797
+ }
1798
+ executableFile = localFile || executableFile;
1799
+ }
1800
+ launchWithNode = sourceExt.includes(path4.extname(executableFile));
1801
+ let proc;
1802
+ if (process2.platform !== "win32") {
1803
+ if (launchWithNode) {
1804
+ args.unshift(executableFile);
1805
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
1806
+ proc = childProcess.spawn(process2.argv[0], args, { stdio: "inherit" });
1807
+ } else {
1808
+ proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
1809
+ }
1810
+ } else {
1811
+ args.unshift(executableFile);
1812
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
1813
+ proc = childProcess.spawn(process2.execPath, args, { stdio: "inherit" });
1814
+ }
1815
+ if (!proc.killed) {
1816
+ const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
1817
+ signals.forEach((signal) => {
1818
+ process2.on(signal, () => {
1819
+ if (proc.killed === false && proc.exitCode === null) {
1820
+ proc.kill(signal);
1821
+ }
1822
+ });
1823
+ });
1824
+ }
1825
+ const exitCallback = this._exitCallback;
1826
+ if (!exitCallback) {
1827
+ proc.on("close", process2.exit.bind(process2));
1828
+ } else {
1829
+ proc.on("close", () => {
1830
+ exitCallback(new CommanderError2(process2.exitCode || 0, "commander.executeSubCommandAsync", "(close)"));
1831
+ });
1832
+ }
1833
+ proc.on("error", (err) => {
1834
+ if (err.code === "ENOENT") {
1835
+ 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";
1836
+ const executableMissing = `'${executableFile}' does not exist
1837
+ - if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
1838
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
1839
+ - ${executableDirMessage}`;
1840
+ throw new Error(executableMissing);
1841
+ } else if (err.code === "EACCES") {
1842
+ throw new Error(`'${executableFile}' not executable`);
1843
+ }
1844
+ if (!exitCallback) {
1845
+ process2.exit(1);
1846
+ } else {
1847
+ const wrappedError = new CommanderError2(1, "commander.executeSubCommandAsync", "(error)");
1848
+ wrappedError.nestedError = err;
1849
+ exitCallback(wrappedError);
1850
+ }
1851
+ });
1852
+ this.runningCommand = proc;
1853
+ }
1854
+ /**
1855
+ * @api private
1856
+ */
1857
+ _dispatchSubcommand(commandName, operands, unknown) {
1858
+ const subCommand = this._findCommand(commandName);
1859
+ if (!subCommand)
1860
+ this.help({ error: true });
1861
+ let promiseChain;
1862
+ promiseChain = this._chainOrCallSubCommandHook(promiseChain, subCommand, "preSubcommand");
1863
+ promiseChain = this._chainOrCall(promiseChain, () => {
1864
+ if (subCommand._executableHandler) {
1865
+ this._executeSubCommand(subCommand, operands.concat(unknown));
1866
+ } else {
1867
+ return subCommand._parseCommand(operands, unknown);
1868
+ }
1869
+ });
1870
+ return promiseChain;
1871
+ }
1872
+ /**
1873
+ * Invoke help directly if possible, or dispatch if necessary.
1874
+ * e.g. help foo
1875
+ *
1876
+ * @api private
1877
+ */
1878
+ _dispatchHelpCommand(subcommandName) {
1879
+ if (!subcommandName) {
1880
+ this.help();
1881
+ }
1882
+ const subCommand = this._findCommand(subcommandName);
1883
+ if (subCommand && !subCommand._executableHandler) {
1884
+ subCommand.help();
1885
+ }
1886
+ return this._dispatchSubcommand(subcommandName, [], [
1887
+ this._helpLongFlag || this._helpShortFlag
1888
+ ]);
1889
+ }
1890
+ /**
1891
+ * Check this.args against expected this.registeredArguments.
1892
+ *
1893
+ * @api private
1894
+ */
1895
+ _checkNumberOfArguments() {
1896
+ this.registeredArguments.forEach((arg, i) => {
1897
+ if (arg.required && this.args[i] == null) {
1898
+ this.missingArgument(arg.name());
1899
+ }
1900
+ });
1901
+ if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
1902
+ return;
1903
+ }
1904
+ if (this.args.length > this.registeredArguments.length) {
1905
+ this._excessArguments(this.args);
1906
+ }
1907
+ }
1908
+ /**
1909
+ * Process this.args using this.registeredArguments and save as this.processedArgs!
1910
+ *
1911
+ * @api private
1912
+ */
1913
+ _processArguments() {
1914
+ const myParseArg = (argument, value, previous) => {
1915
+ let parsedValue = value;
1916
+ if (value !== null && argument.parseArg) {
1917
+ const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
1918
+ parsedValue = this._callParseArg(argument, value, previous, invalidValueMessage);
1919
+ }
1920
+ return parsedValue;
1921
+ };
1922
+ this._checkNumberOfArguments();
1923
+ const processedArgs = [];
1924
+ this.registeredArguments.forEach((declaredArg, index) => {
1925
+ let value = declaredArg.defaultValue;
1926
+ if (declaredArg.variadic) {
1927
+ if (index < this.args.length) {
1928
+ value = this.args.slice(index);
1929
+ if (declaredArg.parseArg) {
1930
+ value = value.reduce((processed, v) => {
1931
+ return myParseArg(declaredArg, v, processed);
1932
+ }, declaredArg.defaultValue);
1933
+ }
1934
+ } else if (value === void 0) {
1935
+ value = [];
1936
+ }
1937
+ } else if (index < this.args.length) {
1938
+ value = this.args[index];
1939
+ if (declaredArg.parseArg) {
1940
+ value = myParseArg(declaredArg, value, declaredArg.defaultValue);
1941
+ }
1942
+ }
1943
+ processedArgs[index] = value;
1944
+ });
1945
+ this.processedArgs = processedArgs;
1946
+ }
1947
+ /**
1948
+ * Once we have a promise we chain, but call synchronously until then.
1949
+ *
1950
+ * @param {Promise|undefined} promise
1951
+ * @param {Function} fn
1952
+ * @return {Promise|undefined}
1953
+ * @api private
1954
+ */
1955
+ _chainOrCall(promise, fn) {
1956
+ if (promise && promise.then && typeof promise.then === "function") {
1957
+ return promise.then(() => fn());
1958
+ }
1959
+ return fn();
1960
+ }
1961
+ /**
1962
+ *
1963
+ * @param {Promise|undefined} promise
1964
+ * @param {string} event
1965
+ * @return {Promise|undefined}
1966
+ * @api private
1967
+ */
1968
+ _chainOrCallHooks(promise, event) {
1969
+ let result = promise;
1970
+ const hooks = [];
1971
+ this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== void 0).forEach((hookedCommand) => {
1972
+ hookedCommand._lifeCycleHooks[event].forEach((callback) => {
1973
+ hooks.push({ hookedCommand, callback });
1974
+ });
1975
+ });
1976
+ if (event === "postAction") {
1977
+ hooks.reverse();
1978
+ }
1979
+ hooks.forEach((hookDetail) => {
1980
+ result = this._chainOrCall(result, () => {
1981
+ return hookDetail.callback(hookDetail.hookedCommand, this);
1982
+ });
1983
+ });
1984
+ return result;
1985
+ }
1986
+ /**
1987
+ *
1988
+ * @param {Promise|undefined} promise
1989
+ * @param {Command} subCommand
1990
+ * @param {string} event
1991
+ * @return {Promise|undefined}
1992
+ * @api private
1993
+ */
1994
+ _chainOrCallSubCommandHook(promise, subCommand, event) {
1995
+ let result = promise;
1996
+ if (this._lifeCycleHooks[event] !== void 0) {
1997
+ this._lifeCycleHooks[event].forEach((hook) => {
1998
+ result = this._chainOrCall(result, () => {
1999
+ return hook(this, subCommand);
2000
+ });
2001
+ });
2002
+ }
2003
+ return result;
2004
+ }
2005
+ /**
2006
+ * Process arguments in context of this command.
2007
+ * Returns action result, in case it is a promise.
2008
+ *
2009
+ * @api private
2010
+ */
2011
+ _parseCommand(operands, unknown) {
2012
+ const parsed = this.parseOptions(unknown);
2013
+ this._parseOptionsEnv();
2014
+ this._parseOptionsImplied();
2015
+ operands = operands.concat(parsed.operands);
2016
+ unknown = parsed.unknown;
2017
+ this.args = operands.concat(unknown);
2018
+ if (operands && this._findCommand(operands[0])) {
2019
+ return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
2020
+ }
2021
+ if (this._hasImplicitHelpCommand() && operands[0] === this._helpCommandName) {
2022
+ return this._dispatchHelpCommand(operands[1]);
2023
+ }
2024
+ if (this._defaultCommandName) {
2025
+ outputHelpIfRequested(this, unknown);
2026
+ return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);
2027
+ }
2028
+ if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
2029
+ this.help({ error: true });
2030
+ }
2031
+ outputHelpIfRequested(this, parsed.unknown);
2032
+ this._checkForMissingMandatoryOptions();
2033
+ this._checkForConflictingOptions();
2034
+ const checkForUnknownOptions = () => {
2035
+ if (parsed.unknown.length > 0) {
2036
+ this.unknownOption(parsed.unknown[0]);
2037
+ }
2038
+ };
2039
+ const commandEvent = `command:${this.name()}`;
2040
+ if (this._actionHandler) {
2041
+ checkForUnknownOptions();
2042
+ this._processArguments();
2043
+ let promiseChain;
2044
+ promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
2045
+ promiseChain = this._chainOrCall(promiseChain, () => this._actionHandler(this.processedArgs));
2046
+ if (this.parent) {
2047
+ promiseChain = this._chainOrCall(promiseChain, () => {
2048
+ this.parent.emit(commandEvent, operands, unknown);
2049
+ });
2050
+ }
2051
+ promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
2052
+ return promiseChain;
2053
+ }
2054
+ if (this.parent && this.parent.listenerCount(commandEvent)) {
2055
+ checkForUnknownOptions();
2056
+ this._processArguments();
2057
+ this.parent.emit(commandEvent, operands, unknown);
2058
+ } else if (operands.length) {
2059
+ if (this._findCommand("*")) {
2060
+ return this._dispatchSubcommand("*", operands, unknown);
2061
+ }
2062
+ if (this.listenerCount("command:*")) {
2063
+ this.emit("command:*", operands, unknown);
2064
+ } else if (this.commands.length) {
2065
+ this.unknownCommand();
2066
+ } else {
2067
+ checkForUnknownOptions();
2068
+ this._processArguments();
2069
+ }
2070
+ } else if (this.commands.length) {
2071
+ checkForUnknownOptions();
2072
+ this.help({ error: true });
2073
+ } else {
2074
+ checkForUnknownOptions();
2075
+ this._processArguments();
2076
+ }
2077
+ }
2078
+ /**
2079
+ * Find matching command.
2080
+ *
2081
+ * @api private
2082
+ */
2083
+ _findCommand(name) {
2084
+ if (!name)
2085
+ return void 0;
2086
+ return this.commands.find((cmd) => cmd._name === name || cmd._aliases.includes(name));
2087
+ }
2088
+ /**
2089
+ * Return an option matching `arg` if any.
2090
+ *
2091
+ * @param {string} arg
2092
+ * @return {Option}
2093
+ * @api private
2094
+ */
2095
+ _findOption(arg) {
2096
+ return this.options.find((option) => option.is(arg));
2097
+ }
2098
+ /**
2099
+ * Display an error message if a mandatory option does not have a value.
2100
+ * Called after checking for help flags in leaf subcommand.
2101
+ *
2102
+ * @api private
2103
+ */
2104
+ _checkForMissingMandatoryOptions() {
2105
+ this._getCommandAndAncestors().forEach((cmd) => {
2106
+ cmd.options.forEach((anOption) => {
2107
+ if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === void 0) {
2108
+ cmd.missingMandatoryOptionValue(anOption);
2109
+ }
2110
+ });
2111
+ });
2112
+ }
2113
+ /**
2114
+ * Display an error message if conflicting options are used together in this.
2115
+ *
2116
+ * @api private
2117
+ */
2118
+ _checkForConflictingLocalOptions() {
2119
+ const definedNonDefaultOptions = this.options.filter(
2120
+ (option) => {
2121
+ const optionKey = option.attributeName();
2122
+ if (this.getOptionValue(optionKey) === void 0) {
2123
+ return false;
2124
+ }
2125
+ return this.getOptionValueSource(optionKey) !== "default";
2126
+ }
2127
+ );
2128
+ const optionsWithConflicting = definedNonDefaultOptions.filter(
2129
+ (option) => option.conflictsWith.length > 0
2130
+ );
2131
+ optionsWithConflicting.forEach((option) => {
2132
+ const conflictingAndDefined = definedNonDefaultOptions.find(
2133
+ (defined) => option.conflictsWith.includes(defined.attributeName())
2134
+ );
2135
+ if (conflictingAndDefined) {
2136
+ this._conflictingOption(option, conflictingAndDefined);
2137
+ }
2138
+ });
2139
+ }
2140
+ /**
2141
+ * Display an error message if conflicting options are used together.
2142
+ * Called after checking for help flags in leaf subcommand.
2143
+ *
2144
+ * @api private
2145
+ */
2146
+ _checkForConflictingOptions() {
2147
+ this._getCommandAndAncestors().forEach((cmd) => {
2148
+ cmd._checkForConflictingLocalOptions();
2149
+ });
2150
+ }
2151
+ /**
2152
+ * Parse options from `argv` removing known options,
2153
+ * and return argv split into operands and unknown arguments.
2154
+ *
2155
+ * Examples:
2156
+ *
2157
+ * argv => operands, unknown
2158
+ * --known kkk op => [op], []
2159
+ * op --known kkk => [op], []
2160
+ * sub --unknown uuu op => [sub], [--unknown uuu op]
2161
+ * sub -- --unknown uuu op => [sub --unknown uuu op], []
2162
+ *
2163
+ * @param {String[]} argv
2164
+ * @return {{operands: String[], unknown: String[]}}
2165
+ */
2166
+ parseOptions(argv) {
2167
+ const operands = [];
2168
+ const unknown = [];
2169
+ let dest = operands;
2170
+ const args = argv.slice();
2171
+ function maybeOption(arg) {
2172
+ return arg.length > 1 && arg[0] === "-";
2173
+ }
2174
+ let activeVariadicOption = null;
2175
+ while (args.length) {
2176
+ const arg = args.shift();
2177
+ if (arg === "--") {
2178
+ if (dest === unknown)
2179
+ dest.push(arg);
2180
+ dest.push(...args);
2181
+ break;
2182
+ }
2183
+ if (activeVariadicOption && !maybeOption(arg)) {
2184
+ this.emit(`option:${activeVariadicOption.name()}`, arg);
2185
+ continue;
2186
+ }
2187
+ activeVariadicOption = null;
2188
+ if (maybeOption(arg)) {
2189
+ const option = this._findOption(arg);
2190
+ if (option) {
2191
+ if (option.required) {
2192
+ const value = args.shift();
2193
+ if (value === void 0)
2194
+ this.optionMissingArgument(option);
2195
+ this.emit(`option:${option.name()}`, value);
2196
+ } else if (option.optional) {
2197
+ let value = null;
2198
+ if (args.length > 0 && !maybeOption(args[0])) {
2199
+ value = args.shift();
2200
+ }
2201
+ this.emit(`option:${option.name()}`, value);
2202
+ } else {
2203
+ this.emit(`option:${option.name()}`);
2204
+ }
2205
+ activeVariadicOption = option.variadic ? option : null;
2206
+ continue;
2207
+ }
2208
+ }
2209
+ if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
2210
+ const option = this._findOption(`-${arg[1]}`);
2211
+ if (option) {
2212
+ if (option.required || option.optional && this._combineFlagAndOptionalValue) {
2213
+ this.emit(`option:${option.name()}`, arg.slice(2));
2214
+ } else {
2215
+ this.emit(`option:${option.name()}`);
2216
+ args.unshift(`-${arg.slice(2)}`);
2217
+ }
2218
+ continue;
2219
+ }
2220
+ }
2221
+ if (/^--[^=]+=/.test(arg)) {
2222
+ const index = arg.indexOf("=");
2223
+ const option = this._findOption(arg.slice(0, index));
2224
+ if (option && (option.required || option.optional)) {
2225
+ this.emit(`option:${option.name()}`, arg.slice(index + 1));
2226
+ continue;
2227
+ }
2228
+ }
2229
+ if (maybeOption(arg)) {
2230
+ dest = unknown;
2231
+ }
2232
+ if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
2233
+ if (this._findCommand(arg)) {
2234
+ operands.push(arg);
2235
+ if (args.length > 0)
2236
+ unknown.push(...args);
2237
+ break;
2238
+ } else if (arg === this._helpCommandName && this._hasImplicitHelpCommand()) {
2239
+ operands.push(arg);
2240
+ if (args.length > 0)
2241
+ operands.push(...args);
2242
+ break;
2243
+ } else if (this._defaultCommandName) {
2244
+ unknown.push(arg);
2245
+ if (args.length > 0)
2246
+ unknown.push(...args);
2247
+ break;
2248
+ }
2249
+ }
2250
+ if (this._passThroughOptions) {
2251
+ dest.push(arg);
2252
+ if (args.length > 0)
2253
+ dest.push(...args);
2254
+ break;
2255
+ }
2256
+ dest.push(arg);
2257
+ }
2258
+ return { operands, unknown };
2259
+ }
2260
+ /**
2261
+ * Return an object containing local option values as key-value pairs.
2262
+ *
2263
+ * @return {Object}
2264
+ */
2265
+ opts() {
2266
+ if (this._storeOptionsAsProperties) {
2267
+ const result = {};
2268
+ const len = this.options.length;
2269
+ for (let i = 0; i < len; i++) {
2270
+ const key = this.options[i].attributeName();
2271
+ result[key] = key === this._versionOptionName ? this._version : this[key];
2272
+ }
2273
+ return result;
2274
+ }
2275
+ return this._optionValues;
2276
+ }
2277
+ /**
2278
+ * Return an object containing merged local and global option values as key-value pairs.
2279
+ *
2280
+ * @return {Object}
2281
+ */
2282
+ optsWithGlobals() {
2283
+ return this._getCommandAndAncestors().reduce(
2284
+ (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),
2285
+ {}
2286
+ );
2287
+ }
2288
+ /**
2289
+ * Display error message and exit (or call exitOverride).
2290
+ *
2291
+ * @param {string} message
2292
+ * @param {Object} [errorOptions]
2293
+ * @param {string} [errorOptions.code] - an id string representing the error
2294
+ * @param {number} [errorOptions.exitCode] - used with process.exit
2295
+ */
2296
+ error(message, errorOptions) {
2297
+ this._outputConfiguration.outputError(`${message}
2298
+ `, this._outputConfiguration.writeErr);
2299
+ if (typeof this._showHelpAfterError === "string") {
2300
+ this._outputConfiguration.writeErr(`${this._showHelpAfterError}
2301
+ `);
2302
+ } else if (this._showHelpAfterError) {
2303
+ this._outputConfiguration.writeErr("\n");
2304
+ this.outputHelp({ error: true });
2305
+ }
2306
+ const config = errorOptions || {};
2307
+ const exitCode = config.exitCode || 1;
2308
+ const code = config.code || "commander.error";
2309
+ this._exit(exitCode, code, message);
2310
+ }
2311
+ /**
2312
+ * Apply any option related environment variables, if option does
2313
+ * not have a value from cli or client code.
2314
+ *
2315
+ * @api private
2316
+ */
2317
+ _parseOptionsEnv() {
2318
+ this.options.forEach((option) => {
2319
+ if (option.envVar && option.envVar in process2.env) {
2320
+ const optionKey = option.attributeName();
2321
+ if (this.getOptionValue(optionKey) === void 0 || ["default", "config", "env"].includes(this.getOptionValueSource(optionKey))) {
2322
+ if (option.required || option.optional) {
2323
+ this.emit(`optionEnv:${option.name()}`, process2.env[option.envVar]);
2324
+ } else {
2325
+ this.emit(`optionEnv:${option.name()}`);
2326
+ }
2327
+ }
2328
+ }
2329
+ });
2330
+ }
2331
+ /**
2332
+ * Apply any implied option values, if option is undefined or default value.
2333
+ *
2334
+ * @api private
2335
+ */
2336
+ _parseOptionsImplied() {
2337
+ const dualHelper = new DualOptions(this.options);
2338
+ const hasCustomOptionValue = (optionKey) => {
2339
+ return this.getOptionValue(optionKey) !== void 0 && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
2340
+ };
2341
+ this.options.filter((option) => option.implied !== void 0 && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(this.getOptionValue(option.attributeName()), option)).forEach((option) => {
2342
+ Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
2343
+ this.setOptionValueWithSource(impliedKey, option.implied[impliedKey], "implied");
2344
+ });
2345
+ });
2346
+ }
2347
+ /**
2348
+ * Argument `name` is missing.
2349
+ *
2350
+ * @param {string} name
2351
+ * @api private
2352
+ */
2353
+ missingArgument(name) {
2354
+ const message = `error: missing required argument '${name}'`;
2355
+ this.error(message, { code: "commander.missingArgument" });
2356
+ }
2357
+ /**
2358
+ * `Option` is missing an argument.
2359
+ *
2360
+ * @param {Option} option
2361
+ * @api private
2362
+ */
2363
+ optionMissingArgument(option) {
2364
+ const message = `error: option '${option.flags}' argument missing`;
2365
+ this.error(message, { code: "commander.optionMissingArgument" });
2366
+ }
2367
+ /**
2368
+ * `Option` does not have a value, and is a mandatory option.
2369
+ *
2370
+ * @param {Option} option
2371
+ * @api private
2372
+ */
2373
+ missingMandatoryOptionValue(option) {
2374
+ const message = `error: required option '${option.flags}' not specified`;
2375
+ this.error(message, { code: "commander.missingMandatoryOptionValue" });
2376
+ }
2377
+ /**
2378
+ * `Option` conflicts with another option.
2379
+ *
2380
+ * @param {Option} option
2381
+ * @param {Option} conflictingOption
2382
+ * @api private
2383
+ */
2384
+ _conflictingOption(option, conflictingOption) {
2385
+ const findBestOptionFromValue = (option2) => {
2386
+ const optionKey = option2.attributeName();
2387
+ const optionValue = this.getOptionValue(optionKey);
2388
+ const negativeOption = this.options.find((target) => target.negate && optionKey === target.attributeName());
2389
+ const positiveOption = this.options.find((target) => !target.negate && optionKey === target.attributeName());
2390
+ if (negativeOption && (negativeOption.presetArg === void 0 && optionValue === false || negativeOption.presetArg !== void 0 && optionValue === negativeOption.presetArg)) {
2391
+ return negativeOption;
2392
+ }
2393
+ return positiveOption || option2;
2394
+ };
2395
+ const getErrorMessage = (option2) => {
2396
+ const bestOption = findBestOptionFromValue(option2);
2397
+ const optionKey = bestOption.attributeName();
2398
+ const source = this.getOptionValueSource(optionKey);
2399
+ if (source === "env") {
2400
+ return `environment variable '${bestOption.envVar}'`;
2401
+ }
2402
+ return `option '${bestOption.flags}'`;
2403
+ };
2404
+ const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
2405
+ this.error(message, { code: "commander.conflictingOption" });
2406
+ }
2407
+ /**
2408
+ * Unknown option `flag`.
2409
+ *
2410
+ * @param {string} flag
2411
+ * @api private
2412
+ */
2413
+ unknownOption(flag) {
2414
+ if (this._allowUnknownOption)
2415
+ return;
2416
+ let suggestion = "";
2417
+ if (flag.startsWith("--") && this._showSuggestionAfterError) {
2418
+ let candidateFlags = [];
2419
+ let command = this;
2420
+ do {
2421
+ const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
2422
+ candidateFlags = candidateFlags.concat(moreFlags);
2423
+ command = command.parent;
2424
+ } while (command && !command._enablePositionalOptions);
2425
+ suggestion = suggestSimilar(flag, candidateFlags);
2426
+ }
2427
+ const message = `error: unknown option '${flag}'${suggestion}`;
2428
+ this.error(message, { code: "commander.unknownOption" });
2429
+ }
2430
+ /**
2431
+ * Excess arguments, more than expected.
2432
+ *
2433
+ * @param {string[]} receivedArgs
2434
+ * @api private
2435
+ */
2436
+ _excessArguments(receivedArgs) {
2437
+ if (this._allowExcessArguments)
2438
+ return;
2439
+ const expected = this.registeredArguments.length;
2440
+ const s = expected === 1 ? "" : "s";
2441
+ const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
2442
+ const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
2443
+ this.error(message, { code: "commander.excessArguments" });
2444
+ }
2445
+ /**
2446
+ * Unknown command.
2447
+ *
2448
+ * @api private
2449
+ */
2450
+ unknownCommand() {
2451
+ const unknownName = this.args[0];
2452
+ let suggestion = "";
2453
+ if (this._showSuggestionAfterError) {
2454
+ const candidateNames = [];
2455
+ this.createHelp().visibleCommands(this).forEach((command) => {
2456
+ candidateNames.push(command.name());
2457
+ if (command.alias())
2458
+ candidateNames.push(command.alias());
2459
+ });
2460
+ suggestion = suggestSimilar(unknownName, candidateNames);
2461
+ }
2462
+ const message = `error: unknown command '${unknownName}'${suggestion}`;
2463
+ this.error(message, { code: "commander.unknownCommand" });
2464
+ }
2465
+ /**
2466
+ * Get or set the program version.
2467
+ *
2468
+ * This method auto-registers the "-V, --version" option which will print the version number.
2469
+ *
2470
+ * You can optionally supply the flags and description to override the defaults.
2471
+ *
2472
+ * @param {string} [str]
2473
+ * @param {string} [flags]
2474
+ * @param {string} [description]
2475
+ * @return {this | string | undefined} `this` command for chaining, or version string if no arguments
2476
+ */
2477
+ version(str, flags, description) {
2478
+ if (str === void 0)
2479
+ return this._version;
2480
+ this._version = str;
2481
+ flags = flags || "-V, --version";
2482
+ description = description || "output the version number";
2483
+ const versionOption = this.createOption(flags, description);
2484
+ this._versionOptionName = versionOption.attributeName();
2485
+ this.options.push(versionOption);
2486
+ this.on("option:" + versionOption.name(), () => {
2487
+ this._outputConfiguration.writeOut(`${str}
2488
+ `);
2489
+ this._exit(0, "commander.version", str);
2490
+ });
2491
+ return this;
2492
+ }
2493
+ /**
2494
+ * Set the description.
2495
+ *
2496
+ * @param {string} [str]
2497
+ * @param {Object} [argsDescription]
2498
+ * @return {string|Command}
2499
+ */
2500
+ description(str, argsDescription) {
2501
+ if (str === void 0 && argsDescription === void 0)
2502
+ return this._description;
2503
+ this._description = str;
2504
+ if (argsDescription) {
2505
+ this._argsDescription = argsDescription;
2506
+ }
2507
+ return this;
2508
+ }
2509
+ /**
2510
+ * Set the summary. Used when listed as subcommand of parent.
2511
+ *
2512
+ * @param {string} [str]
2513
+ * @return {string|Command}
2514
+ */
2515
+ summary(str) {
2516
+ if (str === void 0)
2517
+ return this._summary;
2518
+ this._summary = str;
2519
+ return this;
2520
+ }
2521
+ /**
2522
+ * Set an alias for the command.
2523
+ *
2524
+ * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
2525
+ *
2526
+ * @param {string} [alias]
2527
+ * @return {string|Command}
2528
+ */
2529
+ alias(alias) {
2530
+ if (alias === void 0)
2531
+ return this._aliases[0];
2532
+ let command = this;
2533
+ if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
2534
+ command = this.commands[this.commands.length - 1];
2535
+ }
2536
+ if (alias === command._name)
2537
+ throw new Error("Command alias can't be the same as its name");
2538
+ command._aliases.push(alias);
2539
+ return this;
2540
+ }
2541
+ /**
2542
+ * Set aliases for the command.
2543
+ *
2544
+ * Only the first alias is shown in the auto-generated help.
2545
+ *
2546
+ * @param {string[]} [aliases]
2547
+ * @return {string[]|Command}
2548
+ */
2549
+ aliases(aliases) {
2550
+ if (aliases === void 0)
2551
+ return this._aliases;
2552
+ aliases.forEach((alias) => this.alias(alias));
2553
+ return this;
2554
+ }
2555
+ /**
2556
+ * Set / get the command usage `str`.
2557
+ *
2558
+ * @param {string} [str]
2559
+ * @return {String|Command}
2560
+ */
2561
+ usage(str) {
2562
+ if (str === void 0) {
2563
+ if (this._usage)
2564
+ return this._usage;
2565
+ const args = this.registeredArguments.map((arg) => {
2566
+ return humanReadableArgName(arg);
2567
+ });
2568
+ return [].concat(
2569
+ this.options.length || this._hasHelpOption ? "[options]" : [],
2570
+ this.commands.length ? "[command]" : [],
2571
+ this.registeredArguments.length ? args : []
2572
+ ).join(" ");
2573
+ }
2574
+ this._usage = str;
2575
+ return this;
2576
+ }
2577
+ /**
2578
+ * Get or set the name of the command.
2579
+ *
2580
+ * @param {string} [str]
2581
+ * @return {string|Command}
2582
+ */
2583
+ name(str) {
2584
+ if (str === void 0)
2585
+ return this._name;
2586
+ this._name = str;
2587
+ return this;
2588
+ }
2589
+ /**
2590
+ * Set the name of the command from script filename, such as process.argv[1],
2591
+ * or require.main.filename, or __filename.
2592
+ *
2593
+ * (Used internally and public although not documented in README.)
2594
+ *
2595
+ * @example
2596
+ * program.nameFromFilename(require.main.filename);
2597
+ *
2598
+ * @param {string} filename
2599
+ * @return {Command}
2600
+ */
2601
+ nameFromFilename(filename) {
2602
+ this._name = path4.basename(filename, path4.extname(filename));
2603
+ return this;
2604
+ }
2605
+ /**
2606
+ * Get or set the directory for searching for executable subcommands of this command.
2607
+ *
2608
+ * @example
2609
+ * program.executableDir(__dirname);
2610
+ * // or
2611
+ * program.executableDir('subcommands');
2612
+ *
2613
+ * @param {string} [path]
2614
+ * @return {string|null|Command}
2615
+ */
2616
+ executableDir(path5) {
2617
+ if (path5 === void 0)
2618
+ return this._executableDir;
2619
+ this._executableDir = path5;
2620
+ return this;
2621
+ }
2622
+ /**
2623
+ * Return program help documentation.
2624
+ *
2625
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
2626
+ * @return {string}
2627
+ */
2628
+ helpInformation(contextOptions) {
2629
+ const helper = this.createHelp();
2630
+ if (helper.helpWidth === void 0) {
2631
+ helper.helpWidth = contextOptions && contextOptions.error ? this._outputConfiguration.getErrHelpWidth() : this._outputConfiguration.getOutHelpWidth();
2632
+ }
2633
+ return helper.formatHelp(this, helper);
2634
+ }
2635
+ /**
2636
+ * @api private
2637
+ */
2638
+ _getHelpContext(contextOptions) {
2639
+ contextOptions = contextOptions || {};
2640
+ const context = { error: !!contextOptions.error };
2641
+ let write;
2642
+ if (context.error) {
2643
+ write = (arg) => this._outputConfiguration.writeErr(arg);
2644
+ } else {
2645
+ write = (arg) => this._outputConfiguration.writeOut(arg);
2646
+ }
2647
+ context.write = contextOptions.write || write;
2648
+ context.command = this;
2649
+ return context;
2650
+ }
2651
+ /**
2652
+ * Output help information for this command.
2653
+ *
2654
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
2655
+ *
2656
+ * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
2657
+ */
2658
+ outputHelp(contextOptions) {
2659
+ let deprecatedCallback;
2660
+ if (typeof contextOptions === "function") {
2661
+ deprecatedCallback = contextOptions;
2662
+ contextOptions = void 0;
2663
+ }
2664
+ const context = this._getHelpContext(contextOptions);
2665
+ this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", context));
2666
+ this.emit("beforeHelp", context);
2667
+ let helpInformation = this.helpInformation(context);
2668
+ if (deprecatedCallback) {
2669
+ helpInformation = deprecatedCallback(helpInformation);
2670
+ if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
2671
+ throw new Error("outputHelp callback must return a string or a Buffer");
2672
+ }
2673
+ }
2674
+ context.write(helpInformation);
2675
+ if (this._helpLongFlag) {
2676
+ this.emit(this._helpLongFlag);
2677
+ }
2678
+ this.emit("afterHelp", context);
2679
+ this._getCommandAndAncestors().forEach((command) => command.emit("afterAllHelp", context));
2680
+ }
2681
+ /**
2682
+ * You can pass in flags and a description to override the help
2683
+ * flags and help description for your command. Pass in false to
2684
+ * disable the built-in help option.
2685
+ *
2686
+ * @param {string | boolean} [flags]
2687
+ * @param {string} [description]
2688
+ * @return {Command} `this` command for chaining
2689
+ */
2690
+ helpOption(flags, description) {
2691
+ if (typeof flags === "boolean") {
2692
+ this._hasHelpOption = flags;
2693
+ return this;
2694
+ }
2695
+ this._helpFlags = flags || this._helpFlags;
2696
+ this._helpDescription = description || this._helpDescription;
2697
+ const helpFlags = splitOptionFlags(this._helpFlags);
2698
+ this._helpShortFlag = helpFlags.shortFlag;
2699
+ this._helpLongFlag = helpFlags.longFlag;
2700
+ return this;
2701
+ }
2702
+ /**
2703
+ * Output help information and exit.
2704
+ *
2705
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
2706
+ *
2707
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
2708
+ */
2709
+ help(contextOptions) {
2710
+ this.outputHelp(contextOptions);
2711
+ let exitCode = process2.exitCode || 0;
2712
+ if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
2713
+ exitCode = 1;
2714
+ }
2715
+ this._exit(exitCode, "commander.help", "(outputHelp)");
2716
+ }
2717
+ /**
2718
+ * Add additional text to be displayed with the built-in help.
2719
+ *
2720
+ * Position is 'before' or 'after' to affect just this command,
2721
+ * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
2722
+ *
2723
+ * @param {string} position - before or after built-in help
2724
+ * @param {string | Function} text - string to add, or a function returning a string
2725
+ * @return {Command} `this` command for chaining
2726
+ */
2727
+ addHelpText(position, text) {
2728
+ const allowedValues = ["beforeAll", "before", "after", "afterAll"];
2729
+ if (!allowedValues.includes(position)) {
2730
+ throw new Error(`Unexpected value for position to addHelpText.
2731
+ Expecting one of '${allowedValues.join("', '")}'`);
2732
+ }
2733
+ const helpEvent = `${position}Help`;
2734
+ this.on(helpEvent, (context) => {
2735
+ let helpStr;
2736
+ if (typeof text === "function") {
2737
+ helpStr = text({ error: context.error, command: context.command });
2738
+ } else {
2739
+ helpStr = text;
2740
+ }
2741
+ if (helpStr) {
2742
+ context.write(`${helpStr}
2743
+ `);
2744
+ }
2745
+ });
2746
+ return this;
2747
+ }
2748
+ };
2749
+ function outputHelpIfRequested(cmd, args) {
2750
+ const helpOption = cmd._hasHelpOption && args.find((arg) => arg === cmd._helpLongFlag || arg === cmd._helpShortFlag);
2751
+ if (helpOption) {
2752
+ cmd.outputHelp();
2753
+ cmd._exit(0, "commander.helpDisplayed", "(outputHelp)");
2754
+ }
2755
+ }
2756
+ function incrementNodeInspectorPort(args) {
2757
+ return args.map((arg) => {
2758
+ if (!arg.startsWith("--inspect")) {
2759
+ return arg;
2760
+ }
2761
+ let debugOption;
2762
+ let debugHost = "127.0.0.1";
2763
+ let debugPort = "9229";
2764
+ let match;
2765
+ if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
2766
+ debugOption = match[1];
2767
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
2768
+ debugOption = match[1];
2769
+ if (/^\d+$/.test(match[3])) {
2770
+ debugPort = match[3];
2771
+ } else {
2772
+ debugHost = match[3];
2773
+ }
2774
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
2775
+ debugOption = match[1];
2776
+ debugHost = match[3];
2777
+ debugPort = match[4];
2778
+ }
2779
+ if (debugOption && debugPort !== "0") {
2780
+ return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
2781
+ }
2782
+ return arg;
2783
+ });
2784
+ }
2785
+ exports2.Command = Command2;
2786
+ }
2787
+ });
2788
+
2789
+ // node_modules/commander/index.js
2790
+ var require_commander = __commonJS({
2791
+ "node_modules/commander/index.js"(exports2, module2) {
2792
+ var { Argument: Argument2 } = require_argument();
2793
+ var { Command: Command2 } = require_command();
2794
+ var { CommanderError: CommanderError2, InvalidArgumentError: InvalidArgumentError2 } = require_error();
2795
+ var { Help: Help2 } = require_help();
2796
+ var { Option: Option2 } = require_option();
2797
+ exports2 = module2.exports = new Command2();
2798
+ exports2.program = exports2;
2799
+ exports2.Command = Command2;
2800
+ exports2.Option = Option2;
2801
+ exports2.Argument = Argument2;
2802
+ exports2.Help = Help2;
2803
+ exports2.CommanderError = CommanderError2;
2804
+ exports2.InvalidArgumentError = InvalidArgumentError2;
2805
+ exports2.InvalidOptionArgumentError = InvalidArgumentError2;
2806
+ }
2807
+ });
2808
+
2809
+ // node_modules/commander/esm.mjs
2810
+ var import_index = __toESM(require_commander(), 1);
2811
+ var {
2812
+ program,
2813
+ createCommand,
2814
+ createArgument,
2815
+ createOption,
2816
+ CommanderError,
2817
+ InvalidArgumentError,
2818
+ InvalidOptionArgumentError,
2819
+ // deprecated old name
2820
+ Command,
2821
+ Argument,
2822
+ Option,
2823
+ Help
2824
+ } = import_index.default;
2825
+
2826
+ // src/commands/login.ts
2827
+ var readline = __toESM(require("readline"));
2828
+
2829
+ // src/config.ts
2830
+ var fs = __toESM(require("fs"));
2831
+ var path = __toESM(require("path"));
2832
+ var os = __toESM(require("os"));
2833
+ var CONFIG_DIR = path.join(os.homedir(), ".easyclaw-link");
2834
+ var CONFIG_FILE = path.join(CONFIG_DIR, "config.json");
2835
+ var BASE_URL = process.env.EASYCLAW_LINK_API || "https://easyclaw.link";
2836
+ function readConfig() {
2837
+ try {
2838
+ if (!fs.existsSync(CONFIG_FILE))
2839
+ return {};
2840
+ const raw = fs.readFileSync(CONFIG_FILE, "utf-8");
2841
+ return JSON.parse(raw);
2842
+ } catch {
2843
+ return {};
2844
+ }
2845
+ }
2846
+ function writeConfig(config) {
2847
+ if (!fs.existsSync(CONFIG_DIR)) {
2848
+ fs.mkdirSync(CONFIG_DIR, { recursive: true });
2849
+ }
2850
+ fs.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2), "utf-8");
2851
+ }
2852
+ function requireApiKey() {
2853
+ const cfg = readConfig();
2854
+ if (!cfg.apiKey) {
2855
+ console.error("\u274C \u672A\u767B\u5F55\uFF0C\u8BF7\u5148\u8FD0\u884C: npx easyclaw-link login");
2856
+ process.exit(1);
2857
+ }
2858
+ return cfg.apiKey;
2859
+ }
2860
+ async function fetchWithRetry(url, options, maxRetries = 3) {
2861
+ let lastErr;
2862
+ for (let i = 0; i < maxRetries; i++) {
2863
+ try {
2864
+ const res = await fetch(url, options);
2865
+ return res;
2866
+ } catch (err) {
2867
+ lastErr = err;
2868
+ if (i < maxRetries - 1) {
2869
+ const delay = 1e3 * Math.pow(2, i);
2870
+ console.error(`\u26A0\uFE0F \u7F51\u7EDC\u9519\u8BEF\uFF0C${delay / 1e3}s \u540E\u91CD\u8BD5 (${i + 1}/${maxRetries})...`);
2871
+ await new Promise((r) => setTimeout(r, delay));
2872
+ }
2873
+ }
2874
+ }
2875
+ throw lastErr;
2876
+ }
2877
+
2878
+ // src/commands/login.ts
2879
+ function prompt(question) {
2880
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
2881
+ return new Promise((resolve2) => {
2882
+ rl.question(question, (answer) => {
2883
+ rl.close();
2884
+ resolve2(answer.trim());
2885
+ });
2886
+ });
2887
+ }
2888
+ async function verifyApiKey(apiKey) {
2889
+ try {
2890
+ const res = await fetchWithRetry(
2891
+ `${BASE_URL}/api/assets?author=me`,
2892
+ { headers: { Authorization: `Bearer ${apiKey}` } }
2893
+ );
2894
+ return res.ok;
2895
+ } catch {
2896
+ return false;
2897
+ }
2898
+ }
2899
+ async function loginAction() {
2900
+ console.log("\u{1F511} \u767B\u5F55 EasyClaw Link \u5E73\u53F0\n");
2901
+ const apiKey = await prompt("\u8BF7\u8F93\u5165 API Key (eck_xxx): ");
2902
+ if (!apiKey || !apiKey.startsWith("eck_")) {
2903
+ console.error("\u274C API Key \u683C\u5F0F\u4E0D\u6B63\u786E\uFF08\u5E94\u4EE5 eck_ \u5F00\u5934\uFF09");
2904
+ process.exit(1);
2905
+ }
2906
+ console.log("\u23F3 \u9A8C\u8BC1 API Key...");
2907
+ const valid = await verifyApiKey(apiKey);
2908
+ if (!valid) {
2909
+ console.error("\u274C API Key \u65E0\u6548\uFF0C\u8BF7\u68C0\u67E5\u540E\u91CD\u8BD5");
2910
+ process.exit(1);
2911
+ }
2912
+ writeConfig({ apiKey });
2913
+ console.log("\u2705 \u767B\u5F55\u6210\u529F\uFF01API Key \u5DF2\u4FDD\u5B58\u5230 ~/.easyclaw-link/config.json");
2914
+ console.log("\n\u73B0\u5728\u53EF\u4EE5\u8FD0\u884C\uFF1A");
2915
+ console.log(" npx easyclaw-link publish . # \u53D1\u5E03\u6280\u80FD");
2916
+ console.log(" npx easyclaw-link list # \u67E5\u770B\u6280\u80FD\u5217\u8868");
2917
+ }
2918
+
2919
+ // src/commands/publish.ts
2920
+ var fs3 = __toESM(require("fs"));
2921
+ var path3 = __toESM(require("path"));
2922
+
2923
+ // src/validate.ts
2924
+ var fs2 = __toESM(require("fs"));
2925
+ var path2 = __toESM(require("path"));
2926
+ function validateSkillDir(dir) {
2927
+ const errors = [];
2928
+ const skillPath = path2.join(dir, "SKILL.md");
2929
+ if (!fs2.existsSync(skillPath)) {
2930
+ errors.push("\u7F3A\u5C11 SKILL.md \u6587\u4EF6");
2931
+ } else {
2932
+ const content = fs2.readFileSync(skillPath, "utf-8");
2933
+ const trimmed = content.trim();
2934
+ if (!trimmed) {
2935
+ errors.push("SKILL.md \u6587\u4EF6\u4E3A\u7A7A");
2936
+ } else {
2937
+ const lines = content.split("\n");
2938
+ const hasHeading = lines.some((line) => /^#{1,6}\s/.test(line));
2939
+ if (!hasHeading) {
2940
+ errors.push("SKILL.md \u7F3A\u5C11\u6807\u9898\u884C\uFF08\u9700\u8981\u4EE5 # \u5F00\u5934\u7684\u884C\uFF0C\u5982 # \u6280\u80FD\u540D\u79F0\uFF09");
2941
+ }
2942
+ }
2943
+ if (content.length > 5e4) {
2944
+ errors.push("SKILL.md \u8D85\u8FC7 50000 \u5B57\u7B26\u9650\u5236");
2945
+ }
2946
+ }
2947
+ return { valid: errors.length === 0, errors };
2948
+ }
2949
+
2950
+ // src/commands/publish.ts
2951
+ async function resolveId(apiKey, slug) {
2952
+ const PAGE_SIZE = 100;
2953
+ let offset = 0;
2954
+ while (true) {
2955
+ const res = await fetchWithRetry(
2956
+ `${BASE_URL}/api/assets?author=me&limit=${PAGE_SIZE}&offset=${offset}`,
2957
+ { headers: { Authorization: `Bearer ${apiKey}` } }
2958
+ );
2959
+ if (!res.ok) {
2960
+ console.error(`\u274C \u67E5\u8BE2\u6280\u80FD\u5217\u8868\u5931\u8D25 (${res.status})`);
2961
+ process.exit(1);
2962
+ }
2963
+ const { assets } = await res.json();
2964
+ if (!assets || assets.length === 0)
2965
+ break;
2966
+ const match = assets.find((a) => a.slug === slug);
2967
+ if (match)
2968
+ return match.id;
2969
+ if (assets.length < PAGE_SIZE)
2970
+ break;
2971
+ offset += PAGE_SIZE;
2972
+ }
2973
+ console.error(`\u274C \u672A\u627E\u5230 slug="${slug}" \u7684\u6280\u80FD\uFF0C\u8BF7\u7528 npx easyclaw-link list \u786E\u8BA4`);
2974
+ process.exit(1);
2975
+ }
2976
+ async function publishAction(dir, options) {
2977
+ const apiKey = requireApiKey();
2978
+ const targetDir = path3.resolve(dir || ".");
2979
+ const { valid, errors } = validateSkillDir(targetDir);
2980
+ if (!valid) {
2981
+ console.error("\u274C \u6821\u9A8C\u5931\u8D25\uFF1A");
2982
+ errors.forEach((e) => console.error(` \u2022 ${e}`));
2983
+ process.exit(1);
2984
+ }
2985
+ const content = fs3.readFileSync(path3.join(targetDir, "SKILL.md"), "utf-8");
2986
+ let pkgName;
2987
+ let pkgVersion;
2988
+ let pkgDescription;
2989
+ const pkgJsonPath = path3.join(targetDir, "package.json");
2990
+ if (fs3.existsSync(pkgJsonPath)) {
2991
+ try {
2992
+ const pkg = JSON.parse(fs3.readFileSync(pkgJsonPath, "utf-8"));
2993
+ pkgName = pkg.name;
2994
+ pkgVersion = pkg.version;
2995
+ pkgDescription = pkg.description;
2996
+ } catch {
2997
+ }
2998
+ }
2999
+ const title = pkgName || path3.basename(targetDir);
3000
+ const description = pkgDescription || title;
3001
+ let resolvedId = options.id;
3002
+ if (!resolvedId && options.slug) {
3003
+ const numId = await resolveId(apiKey, options.slug);
3004
+ resolvedId = String(numId);
3005
+ }
3006
+ if (resolvedId) {
3007
+ console.log(`\u23F3 \u66F4\u65B0\u6280\u80FD #${resolvedId}...`);
3008
+ const res = await fetchWithRetry(
3009
+ `${BASE_URL}/api/assets/${resolvedId}`,
3010
+ {
3011
+ method: "PATCH",
3012
+ headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },
3013
+ body: JSON.stringify({ content })
3014
+ }
3015
+ );
3016
+ if (!res.ok) {
3017
+ const body = await res.text();
3018
+ console.error(`\u274C \u66F4\u65B0\u5931\u8D25 (${res.status}): ${body}`);
3019
+ process.exit(1);
3020
+ }
3021
+ const { asset } = await res.json();
3022
+ console.log(`\u2705 \u6280\u80FD\u5DF2\u66F4\u65B0`);
3023
+ console.log(`\u{1F517} ${BASE_URL}/market/${asset?.id ?? resolvedId}`);
3024
+ } else {
3025
+ console.log(`\u23F3 \u53D1\u5E03\u65B0\u6280\u80FD: ${title}...`);
3026
+ const res = await fetchWithRetry(
3027
+ `${BASE_URL}/api/assets`,
3028
+ {
3029
+ method: "POST",
3030
+ headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },
3031
+ body: JSON.stringify({ title, content, description, category: "other" })
3032
+ }
3033
+ );
3034
+ if (!res.ok) {
3035
+ const body = await res.text();
3036
+ console.error(`\u274C \u53D1\u5E03\u5931\u8D25 (${res.status}): ${body}`);
3037
+ process.exit(1);
3038
+ }
3039
+ const { asset } = await res.json();
3040
+ console.log(`\u2705 \u6280\u80FD\u53D1\u5E03\u6210\u529F\uFF01`);
3041
+ console.log(`\u{1F517} ${BASE_URL}/market/${asset?.id}`);
3042
+ if (pkgVersion)
3043
+ console.log(`\u{1F4E6} \u7248\u672C: ${pkgVersion}`);
3044
+ }
3045
+ }
3046
+
3047
+ // src/commands/list.ts
3048
+ async function listAction() {
3049
+ const apiKey = requireApiKey();
3050
+ console.log("\u23F3 \u83B7\u53D6\u6280\u80FD\u5217\u8868...\n");
3051
+ const res = await fetchWithRetry(
3052
+ `${BASE_URL}/api/assets?author=me`,
3053
+ { headers: { Authorization: `Bearer ${apiKey}` } }
3054
+ );
3055
+ if (!res.ok) {
3056
+ const body = await res.text();
3057
+ console.error(`\u274C \u83B7\u53D6\u5931\u8D25 (${res.status}): ${body}`);
3058
+ process.exit(1);
3059
+ }
3060
+ const { assets } = await res.json();
3061
+ if (!assets || assets.length === 0) {
3062
+ console.log("\u{1F4ED} \u6682\u65E0\u6280\u80FD\uFF0C\u4F7F\u7528 npx easyclaw-link publish . \u53D1\u5E03\u4F60\u7684\u7B2C\u4E00\u4E2A\u6280\u80FD");
3063
+ return;
3064
+ }
3065
+ const idW = 6, titleW = 32, statusW = 10, callsW = 8, slugW = 24;
3066
+ const sep = "-".repeat(idW + titleW + statusW + callsW + slugW + 8);
3067
+ console.log(
3068
+ "ID".padEnd(idW) + " " + "Title".padEnd(titleW) + " " + "Status".padEnd(statusW) + " " + "Calls".padEnd(callsW) + " Slug"
3069
+ );
3070
+ console.log(sep);
3071
+ for (const a of assets) {
3072
+ const t = (a.title || "").slice(0, titleW - 1).padEnd(titleW);
3073
+ const s = (a.status || "").padEnd(statusW);
3074
+ const c = String(a.calls ?? 0).padEnd(callsW);
3075
+ const sl = (a.slug || "-").slice(0, slugW - 1);
3076
+ console.log(`${String(a.id).padEnd(idW)} ${t} ${s} ${c} ${sl}`);
3077
+ }
3078
+ console.log(`
3079
+ \u5171 ${assets.length} \u4E2A\u6280\u80FD`);
3080
+ }
3081
+
3082
+ // src/commands/whoami.ts
3083
+ async function whoamiAction() {
3084
+ const apiKey = requireApiKey();
3085
+ const res = await fetch(`${BASE_URL}/api/auth/me`, {
3086
+ headers: { Authorization: `Bearer ${apiKey}` }
3087
+ });
3088
+ if (!res.ok) {
3089
+ const body = await res.text();
3090
+ console.error(`\u274C \u8BF7\u6C42\u5931\u8D25 (${res.status}): ${body}`);
3091
+ process.exit(1);
3092
+ }
3093
+ const { user } = await res.json();
3094
+ if (!user) {
3095
+ console.error("\u274C \u672A\u767B\u5F55\u6216 API Key \u5DF2\u5931\u6548\uFF0C\u8BF7\u91CD\u65B0\u8FD0\u884C npx easyclaw-link login");
3096
+ process.exit(1);
3097
+ }
3098
+ console.log("\u{1F464} \u5F53\u524D\u767B\u5F55\u7528\u6237\n");
3099
+ console.log(`\u7528\u6237\u540D: ${user.username}`);
3100
+ console.log(`\u90AE\u7BB1: ${user.email}`);
3101
+ console.log(`\u89D2\u8272: ${user.role}`);
3102
+ console.log(`\u9F99\u867E\u5E01: ${user.credits} \u{1F99E}`);
3103
+ console.log(`\u58F0\u671B: ${user.reputation}`);
3104
+ console.log(`\u7B49\u7EA7: Lv.${user.level_num}`);
3105
+ }
3106
+
3107
+ // src/commands/credits.ts
3108
+ async function creditsAction() {
3109
+ const apiKey = requireApiKey();
3110
+ const res = await fetch(`${BASE_URL}/api/credits`, {
3111
+ headers: { Authorization: `Bearer ${apiKey}` }
3112
+ });
3113
+ if (!res.ok) {
3114
+ const body = await res.text();
3115
+ console.error(`\u274C \u8BF7\u6C42\u5931\u8D25 (${res.status}): ${body}`);
3116
+ process.exit(1);
3117
+ }
3118
+ const data = await res.json();
3119
+ console.log(`\u{1F4B0} \u9F99\u867E\u5E01\u4F59\u989D: ${data.credits} \u{1F99E}`);
3120
+ console.log(`\u2B50 \u58F0\u671B: ${data.reputation} ${data.level.badge} ${data.level.name}
3121
+ `);
3122
+ const recentTxs = data.transactions.slice(0, 10);
3123
+ if (recentTxs.length === 0) {
3124
+ console.log("\u{1F4ED} \u6682\u65E0\u6536\u652F\u8BB0\u5F55");
3125
+ return;
3126
+ }
3127
+ console.log("\u6700\u8FD1\u6536\u652F\u8BB0\u5F55:");
3128
+ console.log("-".repeat(64));
3129
+ for (const tx of recentTxs) {
3130
+ const sign = tx.amount >= 0 ? "+" : "";
3131
+ const amountStr = `${sign}${tx.amount}`.padStart(6);
3132
+ const date = new Date(tx.created_at).toLocaleDateString("zh-CN");
3133
+ const note = tx.note || tx.ref_type || tx.type;
3134
+ console.log(`${date} ${amountStr} \u{1F99E} ${note}`);
3135
+ }
3136
+ console.log(`
3137
+ \u5171 ${data.transactions.length} \u6761\u8BB0\u5F55\uFF0C\u663E\u793A\u6700\u8FD1 ${recentTxs.length} \u6761`);
3138
+ }
3139
+
3140
+ // src/index.ts
3141
+ var program2 = new Command();
3142
+ program2.name("easyclaw-link").description("EasyClaw Link CLI - Publish and manage skills on EasyClaw Link platform").version("0.1.0-alpha.2");
3143
+ program2.command("login").description("\u767B\u5F55 EasyClaw Link\uFF0C\u4FDD\u5B58 API Key").action(loginAction);
3144
+ program2.command("publish [dir]").description("\u53D1\u5E03\u6216\u66F4\u65B0\u6280\u80FD\u5230 EasyClaw Link \u5E73\u53F0").option("--id <id>", "\u66F4\u65B0\u6307\u5B9A ID \u7684\u6280\u80FD").option("--slug <slug>", "\u901A\u8FC7 slug \u66F4\u65B0\u5DF2\u6709\u6280\u80FD").action(publishAction);
3145
+ program2.command("list").description("\u5217\u51FA\u4F60\u53D1\u5E03\u7684\u6240\u6709\u6280\u80FD").action(listAction);
3146
+ program2.command("whoami").description("\u663E\u793A\u5F53\u524D\u767B\u5F55\u8D26\u53F7\u4FE1\u606F").action(whoamiAction);
3147
+ program2.command("credits").description("\u67E5\u770B\u9F99\u867E\u5E01\u4F59\u989D").action(creditsAction);
3148
+ program2.parse(process.argv);