@bemoje/cli 4.0.0 → 5.0.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/lib/index.cjs CHANGED
@@ -118,9 +118,7 @@ __name(valuesOf, "valuesOf");
118
118
 
119
119
  // src/lib/helpers/findCommand.ts
120
120
  function findCommand(cmd, nameOrAlias) {
121
- return cmd.commands[nameOrAlias] ?? valuesOf(cmd.commands).find((c) => {
122
- return c.aliases.includes(nameOrAlias);
123
- });
121
+ return cmd.commands[nameOrAlias] ?? valuesOf(cmd.commands).find((c) => c.aliases.includes(nameOrAlias));
124
122
  }
125
123
  __name(findCommand, "findCommand");
126
124
 
@@ -352,13 +350,9 @@ var Help = class {
352
350
  * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
353
351
  */
354
352
  visibleCommands() {
355
- const res = Object.values(this.cmd.commands).filter((c) => {
356
- return !c.hidden;
357
- });
353
+ const res = Object.values(this.cmd.commands).filter((c) => !c.hidden);
358
354
  if (this.sortSubcommands) {
359
- res.sort((a, b) => {
360
- return a.name.localeCompare(b.name);
361
- });
355
+ res.sort((a, b) => a.name.localeCompare(b.name));
362
356
  }
363
357
  return res;
364
358
  }
@@ -366,18 +360,17 @@ var Help = class {
366
360
  * Compare options for sort.
367
361
  */
368
362
  compareOptions(a, b) {
369
- const getSortKey = /* @__PURE__ */ __name((option) => {
370
- return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
371
- }, "getSortKey");
363
+ const getSortKey = /* @__PURE__ */ __name((option) => (
364
+ // WYSIWYG for order displayed in help. Short used for comparison if present. No special handling for negated.
365
+ option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "")
366
+ ), "getSortKey");
372
367
  return getSortKey(a).localeCompare(getSortKey(b));
373
368
  }
374
369
  /**
375
370
  * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
376
371
  */
377
372
  visibleOptions() {
378
- const res = this.cmd.options.filter((option) => {
379
- return !option.hidden;
380
- });
373
+ const res = this.cmd.options.filter((option) => !option.hidden);
381
374
  if (this.sortOptions) {
382
375
  res.sort(this.compareOptions);
383
376
  }
@@ -393,9 +386,7 @@ var Help = class {
393
386
  * Get the command term to show in the list of subcommands.
394
387
  */
395
388
  subcommandTerm(sub) {
396
- const args = sub.arguments.map((arg) => {
397
- return arg.usage;
398
- }).join(" ");
389
+ const args = sub.arguments.map((arg) => arg.usage).join(" ");
399
390
  return (sub.aliases[0] ? `${sub.aliases[0].padEnd(this.longestSubcommandAliasLength(), " ")} | ` : "") + sub.name + (sub.options.length ? ` ${this.usageDisplayOptionsAs}` : "") + // simplistic check for non-help option
400
391
  (args ? ` ${args}` : "");
401
392
  }
@@ -415,33 +406,25 @@ var Help = class {
415
406
  * Get the longest subcommand primary alias length.
416
407
  */
417
408
  longestSubcommandAliasLength() {
418
- return Math.max(0, ...this.visibleCommands().map((c) => {
419
- return c.aliases[0]?.length || 0;
420
- }));
409
+ return Math.max(0, ...this.visibleCommands().map((c) => c.aliases[0]?.length || 0));
421
410
  }
422
411
  /**
423
412
  * Get the longest subcommand term length.
424
413
  */
425
414
  longestSubcommandTermLength() {
426
- return this.visibleCommands().reduce((max, command) => {
427
- return Math.max(max, this.displayWidth(this.styleSubcommandTerm(this.subcommandTerm(command))));
428
- }, 0);
415
+ return this.visibleCommands().reduce((max, command) => Math.max(max, this.displayWidth(this.styleSubcommandTerm(this.subcommandTerm(command)))), 0);
429
416
  }
430
417
  /**
431
418
  * Get the longest option term length.
432
419
  */
433
420
  longestOptionTermLength() {
434
- return this.visibleOptions().reduce((max, option) => {
435
- return Math.max(max, this.displayWidth(this.styleOptionTerm(this.optionTerm(option))));
436
- }, 0);
421
+ return this.visibleOptions().reduce((max, option) => Math.max(max, this.displayWidth(this.styleOptionTerm(this.optionTerm(option)))), 0);
437
422
  }
438
423
  /**
439
424
  * Get the longest argument term length.
440
425
  */
441
426
  longestArgumentTermLength() {
442
- return this.visibleArguments().reduce((max, argument) => {
443
- return Math.max(max, this.displayWidth(this.styleArgumentTerm(this.argumentTerm(argument))));
444
- }, 0);
427
+ return this.visibleArguments().reduce((max, argument) => Math.max(max, this.displayWidth(this.styleArgumentTerm(this.argumentTerm(argument)))), 0);
445
428
  }
446
429
  /**
447
430
  * Get the command usage to be displayed at the top of the built-in help.
@@ -458,9 +441,7 @@ var Help = class {
458
441
  ...this.cmd.options.length ? [
459
442
  this.usageDisplayOptionsAs
460
443
  ] : [],
461
- ...this.cmd.arguments.map((arg) => {
462
- return arg.required ? arg.variadic ? `<${arg.name}...>` : `<${arg.name}>` : arg.variadic ? `[${arg.name}...]` : `[${arg.name}]`;
463
- })
444
+ ...this.cmd.arguments.map((arg) => arg.required ? arg.variadic ? `<${arg.name}...>` : `<${arg.name}>` : arg.variadic ? `[${arg.name}...]` : `[${arg.name}]`)
464
445
  ].join(" ")}`.trim();
465
446
  }
466
447
  /**
@@ -786,26 +767,16 @@ ${itemIndentStr}`);
786
767
  ""
787
768
  ]);
788
769
  }
789
- const argumentList = this.visibleArguments().map((argument) => {
790
- return this.formatItem(this.styleArgumentTerm(this.argumentTerm(argument)), this.padWidth(), this.styleArgumentDescription(this.argumentDescription(argument)));
791
- });
770
+ const argumentList = this.visibleArguments().map((argument) => this.formatItem(this.styleArgumentTerm(this.argumentTerm(argument)), this.padWidth(), this.styleArgumentDescription(this.argumentDescription(argument))));
792
771
  output = output.concat(this.formatItemList("Arguments:", argumentList));
793
- const optionGroups = this.groupItems(this.cmd.options, this.visibleOptions(), (option) => {
794
- return option.group ?? "Options:";
795
- });
772
+ const optionGroups = this.groupItems(this.cmd.options, this.visibleOptions(), (option) => option.group ?? "Options:");
796
773
  optionGroups.forEach((options, group) => {
797
- const optionList = options.map((option) => {
798
- return this.formatItem(this.styleOptionTerm(this.optionTerm(option)), this.padWidth(), this.styleOptionDescription(this.optionDescription(option)));
799
- });
774
+ const optionList = options.map((option) => this.formatItem(this.styleOptionTerm(this.optionTerm(option)), this.padWidth(), this.styleOptionDescription(this.optionDescription(option))));
800
775
  output = output.concat(this.formatItemList(group, optionList));
801
776
  });
802
- const commandGroups = this.groupItems(Object.values(this.cmd.commands), this.visibleCommands(), (sub) => {
803
- return sub.group || "Commands:";
804
- });
777
+ const commandGroups = this.groupItems(Object.values(this.cmd.commands), this.visibleCommands(), (sub) => sub.group || "Commands:");
805
778
  commandGroups.forEach((commands, group) => {
806
- const commandList = commands.map((sub) => {
807
- return this.formatItem(this.styleSubcommandTerm(this.subcommandTerm(sub)), this.padWidth(), this.styleSubcommandDescription(this.subcommandDescription(sub)));
808
- });
779
+ const commandList = commands.map((sub) => this.formatItem(this.styleSubcommandTerm(this.subcommandTerm(sub)), this.padWidth(), this.styleSubcommandDescription(this.subcommandDescription(sub))));
809
780
  output = output.concat(this.formatItemList(group, commandList));
810
781
  });
811
782
  return output.join("\n");
@@ -860,39 +831,275 @@ _ts_decorate([
860
831
  _ts_metadata("design:returntype", Number)
861
832
  ], Help.prototype, "padWidth", null);
862
833
 
834
+ // src/lib/internal/isOptionLike.ts
835
+ function isOptionLike(word) {
836
+ return word.startsWith("-") && word !== "-" && !/^-(\d+\.?\d*|\.\d+)$/.test(word);
837
+ }
838
+ __name(isOptionLike, "isOptionLike");
839
+
840
+ // src/lib/internal/checkOptionValues.ts
841
+ function checkOptionValues(argv, options) {
842
+ const out = [];
843
+ const report = {
844
+ errors: [],
845
+ invalid: /* @__PURE__ */ new Set()
846
+ };
847
+ for (let i = 0; i < argv.length; i++) {
848
+ const word = argv[i];
849
+ if (word === "--") {
850
+ out.push(...argv.slice(i));
851
+ break;
852
+ }
853
+ const { keep, read } = word.startsWith("--") ? checkLong(word, argv[i + 1], options, report) : isOptionLike(word) ? checkShort(word, argv[i + 1], options, report) : {
854
+ keep: [
855
+ word
856
+ ],
857
+ read: 1
858
+ };
859
+ out.push(...keep);
860
+ i += read - 1;
861
+ }
862
+ return {
863
+ argv: out,
864
+ ...report
865
+ };
866
+ }
867
+ __name(checkOptionValues, "checkOptionValues");
868
+ function needsValue(def) {
869
+ return def.type === "string" && !(def.variadic && !def.required);
870
+ }
871
+ __name(needsValue, "needsValue");
872
+ function isNoValue(next) {
873
+ return next === void 0 || isOptionLike(next);
874
+ }
875
+ __name(isNoValue, "isNoValue");
876
+ function reportMissingValue(def, report) {
877
+ report.errors.push(`Option --${def.long} requires a value`);
878
+ report.invalid.add(def.name);
879
+ }
880
+ __name(reportMissingValue, "reportMissingValue");
881
+ function checkLong(word, next, options, report) {
882
+ const eq = word.indexOf("=");
883
+ const name = eq === -1 ? word.slice(2) : word.slice(2, eq);
884
+ const def = options.find((o) => o.name === name);
885
+ const negated = !def && name.startsWith("no-") ? options.find((o) => o.name === name.slice(3)) : void 0;
886
+ if (def?.type === "boolean" && eq !== -1) {
887
+ report.errors.push(`Option --${def.long} does not take a value: --${def.long}${word.slice(eq)}`);
888
+ report.invalid.add(def.name);
889
+ return {
890
+ keep: [],
891
+ read: 1
892
+ };
893
+ }
894
+ if (negated?.type === "string") {
895
+ report.errors.push(`Option --${negated.long} takes a value and cannot be negated: --no-${negated.long}`);
896
+ report.invalid.add(negated.name);
897
+ return {
898
+ keep: [],
899
+ read: 1
900
+ };
901
+ }
902
+ if (def?.type !== "string" || eq !== -1) {
903
+ return {
904
+ keep: [
905
+ word
906
+ ],
907
+ read: 1
908
+ };
909
+ }
910
+ if (!isNoValue(next)) {
911
+ return {
912
+ keep: [
913
+ word,
914
+ next
915
+ ],
916
+ read: 2
917
+ };
918
+ }
919
+ if (needsValue(def)) {
920
+ reportMissingValue(def, report);
921
+ return {
922
+ keep: [],
923
+ read: 1
924
+ };
925
+ }
926
+ return {
927
+ keep: [
928
+ word
929
+ ],
930
+ read: 1
931
+ };
932
+ }
933
+ __name(checkLong, "checkLong");
934
+ function checkShort(word, next, options, report) {
935
+ for (let j = 1; j < word.length; j++) {
936
+ const def = options.find((o) => o.short === word[j]);
937
+ if (def?.type !== "string") {
938
+ continue;
939
+ }
940
+ const before = j > 1 ? [
941
+ word.slice(0, j)
942
+ ] : [];
943
+ if (j < word.length - 1) {
944
+ return word[j + 1] === "=" ? {
945
+ keep: [
946
+ ...before,
947
+ `--${def.name}${word.slice(j + 1)}`
948
+ ],
949
+ read: 1
950
+ } : {
951
+ keep: [
952
+ word
953
+ ],
954
+ read: 1
955
+ };
956
+ }
957
+ if (!isNoValue(next)) {
958
+ return {
959
+ keep: [
960
+ word,
961
+ next
962
+ ],
963
+ read: 2
964
+ };
965
+ }
966
+ if (needsValue(def)) {
967
+ reportMissingValue(def, report);
968
+ return {
969
+ keep: before,
970
+ read: 1
971
+ };
972
+ }
973
+ break;
974
+ }
975
+ return {
976
+ keep: [
977
+ word
978
+ ],
979
+ read: 1
980
+ };
981
+ }
982
+ __name(checkShort, "checkShort");
983
+
863
984
  // src/lib/internal/collectVariadicOptionValues.ts
864
985
  function collectVariadicOptionValues(parsed, options) {
986
+ const taken = /* @__PURE__ */ new Set();
987
+ const collected = /* @__PURE__ */ new Map();
865
988
  for (let i = 0; i < parsed.tokens.length; i++) {
866
989
  const token = parsed.tokens[i];
867
990
  if (token.kind !== "option") {
868
991
  continue;
869
992
  }
870
- const def = options.find((o) => {
871
- return o.name === token.name;
872
- });
993
+ const def = options.find((o) => o.name === token.name);
873
994
  if (!def?.variadic || def.type !== "string") {
874
995
  continue;
875
996
  }
876
- const values = [
877
- token.value
878
- ];
997
+ const values = collected.get(token.name) ?? [];
998
+ collected.set(token.name, values);
999
+ if (token.value !== void 0) {
1000
+ values.push(token.value);
1001
+ }
879
1002
  let j = i + 1;
880
1003
  while (j < parsed.tokens.length && parsed.tokens[j].kind === "positional") {
881
- const positionalToken = parsed.tokens[j];
882
- values.push(positionalToken.value);
883
- const posIndex = parsed.positionals.indexOf(positionalToken.value);
884
- if (posIndex !== -1) {
885
- parsed.positionals.splice(posIndex, 1);
886
- }
1004
+ values.push(parsed.tokens[j].value);
1005
+ taken.add(j);
887
1006
  j++;
888
1007
  }
889
- Reflect.set(parsed.values, token.name, values.filter((v) => {
890
- return v !== void 0;
891
- }));
1008
+ }
1009
+ if (taken.size) {
1010
+ parsed.positionals = parsed.tokens.filter((token, index) => token.kind === "positional" && !taken.has(index)).map((token) => token.value);
1011
+ }
1012
+ for (const [name, values] of collected) {
1013
+ Reflect.set(parsed.values, name, values);
892
1014
  }
893
1015
  }
894
1016
  __name(collectVariadicOptionValues, "collectVariadicOptionValues");
895
1017
 
1018
+ // src/lib/internal/createOption.ts
1019
+ function createOption(flags, opts = {}) {
1020
+ const ins = {};
1021
+ const { short, long, name, argName } = parseOptionFlags(flags);
1022
+ ins.flags = flags;
1023
+ ins.short = short;
1024
+ ins.long = long;
1025
+ ins.name = name;
1026
+ ins.description = "";
1027
+ if (argName) {
1028
+ ins.type = "string";
1029
+ ins.argName = argName;
1030
+ if (flags.endsWith(">")) {
1031
+ if (flags.endsWith("...>")) {
1032
+ ins.required = true;
1033
+ ins.variadic = true;
1034
+ } else {
1035
+ ins.required = true;
1036
+ }
1037
+ } else if (flags.endsWith("]") && flags.endsWith("...]")) {
1038
+ ins.variadic = true;
1039
+ ins.defaultValue = opts.defaultValue ?? [];
1040
+ }
1041
+ } else {
1042
+ ins.type = "boolean";
1043
+ }
1044
+ for (const [key, value] of Object.entries(opts)) {
1045
+ if (value !== void 0) {
1046
+ Reflect.set(ins, key, value);
1047
+ }
1048
+ }
1049
+ if (ins.env && ins.defaultValue === void 0 && typeof process.env[ins.env] === "string") {
1050
+ ins.required = false;
1051
+ ins.flags = ins.flags.replace("<", "[").replace(">", "]");
1052
+ if (ins.type === "boolean") {
1053
+ ins.defaultValue = /^(t(rue)?|y(es)?|1)$/i.test(process.env[ins.env]);
1054
+ } else if (ins.variadic) {
1055
+ ins.defaultValue = process.env[ins.env].replace(/\[]/, "").split(",").map((v) => v.trim());
1056
+ } else {
1057
+ ins.defaultValue = process.env[ins.env];
1058
+ }
1059
+ }
1060
+ return ins;
1061
+ }
1062
+ __name(createOption, "createOption");
1063
+
1064
+ // src/lib/internal/findSubcommandIndex.ts
1065
+ function findSubcommandIndex(cmd, argv) {
1066
+ const takesNext = /* @__PURE__ */ __name((next) => next !== void 0 && !isOptionLike(next) ? 1 : 0, "takesNext");
1067
+ for (let i = 0; i < argv.length; i++) {
1068
+ const word = argv[i];
1069
+ if (word === "--") {
1070
+ return -1;
1071
+ }
1072
+ if (!isOptionLike(word)) {
1073
+ return findCommand(cmd, word) ? i : -1;
1074
+ }
1075
+ if (word.startsWith("--")) {
1076
+ const name = word.slice(2);
1077
+ const def = cmd.options.find((o) => o.long === name || o.name === name);
1078
+ if (def?.type === "string") {
1079
+ if (def.variadic) {
1080
+ return -1;
1081
+ }
1082
+ i += takesNext(argv[i + 1]);
1083
+ }
1084
+ continue;
1085
+ }
1086
+ for (let j = 1; j < word.length; j++) {
1087
+ const def = cmd.options.find((o) => o.short === word[j]);
1088
+ if (def?.type === "string") {
1089
+ if (j === word.length - 1) {
1090
+ if (def.variadic) {
1091
+ return -1;
1092
+ }
1093
+ i += takesNext(argv[i + 1]);
1094
+ }
1095
+ break;
1096
+ }
1097
+ }
1098
+ }
1099
+ return -1;
1100
+ }
1101
+ __name(findSubcommandIndex, "findSubcommandIndex");
1102
+
896
1103
  // src/lib/internal/mergeOptionDefaults.ts
897
1104
  function mergeOptionDefaults(values, options) {
898
1105
  for (const option of options) {
@@ -905,21 +1112,22 @@ __name(mergeOptionDefaults, "mergeOptionDefaults");
905
1112
 
906
1113
  // src/lib/internal/normalizeArgv.ts
907
1114
  function normalizeArgv(argv, options) {
1115
+ const end = argv.includes("--") ? argv.indexOf("--") : argv.length;
1116
+ const head = argv.slice(0, end);
908
1117
  for (const o of options) {
909
1118
  if (o.long === o.name) {
910
1119
  continue;
911
1120
  }
912
- argv = argv.map((a) => {
913
- if (a === `--${o.long}`) {
914
- return `--${o.name}`;
915
- }
916
- if (a === `--no-${o.long}`) {
917
- return `--no-${o.name}`;
1121
+ for (let i = 0; i < head.length; i++) {
1122
+ const a = head[i];
1123
+ if (a === `--${o.long}` || a.startsWith(`--${o.long}=`)) {
1124
+ head[i] = `--${o.name}${a.slice(2 + o.long.length)}`;
1125
+ } else if (a === `--no-${o.long}`) {
1126
+ head[i] = `--no-${o.name}`;
918
1127
  }
919
- return a;
920
- });
1128
+ }
921
1129
  }
922
- return argv;
1130
+ return head.concat(argv.slice(end));
923
1131
  }
924
1132
  __name(normalizeArgv, "normalizeArgv");
925
1133
  function resolveArguments(positionals, args) {
@@ -976,47 +1184,29 @@ function createLogger(name) {
976
1184
  const cyanArgs = createColoredArgs(C__default.default.cyan);
977
1185
  const yellowArgs = createColoredArgs(C__default.default.yellow);
978
1186
  return {
979
- start: /* @__PURE__ */ __name((...args) => {
980
- return console.info(...START, ...args);
981
- }, "start"),
982
- done: /* @__PURE__ */ __name((...args) => {
983
- return console.info(...DONE, ...args);
984
- }, "done"),
985
- info: /* @__PURE__ */ __name((...args) => {
986
- return console.info(...INFO, ...grayArgs(args));
987
- }, "info"),
988
- log: /* @__PURE__ */ __name((...args) => {
989
- return console.log(...NAME ? [
990
- NAME,
991
- ...args
992
- ] : args);
993
- }, "log"),
994
- warn: /* @__PURE__ */ __name((...args) => {
995
- return console.warn(...WARN, ...yellowArgs(args));
996
- }, "warn"),
997
- debug: /* @__PURE__ */ __name((...args) => {
998
- return console.debug(...DEBUG, ...cyanArgs(args));
999
- }, "debug"),
1000
- error: /* @__PURE__ */ __name((...args) => {
1001
- return args.forEach((arg) => {
1002
- return console.error(...ERROR, arg);
1003
- });
1004
- }, "error")
1187
+ start: /* @__PURE__ */ __name((...args) => console.info(...START, ...args), "start"),
1188
+ done: /* @__PURE__ */ __name((...args) => console.info(...DONE, ...args), "done"),
1189
+ info: /* @__PURE__ */ __name((...args) => console.info(...INFO, ...grayArgs(args)), "info"),
1190
+ log: /* @__PURE__ */ __name((...args) => console.log(...NAME ? [
1191
+ NAME,
1192
+ ...args
1193
+ ] : args), "log"),
1194
+ warn: /* @__PURE__ */ __name((...args) => console.warn(...WARN, ...yellowArgs(args)), "warn"),
1195
+ debug: /* @__PURE__ */ __name((...args) => console.debug(...DEBUG, ...cyanArgs(args)), "debug"),
1196
+ error: /* @__PURE__ */ __name((...args) => args.forEach((arg) => console.error(...ERROR, arg)), "error")
1005
1197
  };
1006
1198
  }
1007
1199
  __name(createLogger, "createLogger");
1008
1200
  function createColoredArgs(colorFn) {
1009
- return (args) => {
1010
- return args.map((arg) => {
1011
- if (predicate.isString(arg)) {
1012
- return arg === C__default.default.stripColor(arg) ? colorFn(arg) : arg;
1013
- } else if (predicate.isPrimitive(arg)) {
1014
- return colorFn(String(arg));
1015
- } else {
1016
- return arg;
1017
- }
1018
- });
1019
- };
1201
+ return (args) => args.map((arg) => {
1202
+ if (predicate.isString(arg)) {
1203
+ return arg === C__default.default.stripColor(arg) ? colorFn(arg) : arg;
1204
+ } else if (predicate.isPrimitive(arg)) {
1205
+ return colorFn(String(arg));
1206
+ } else {
1207
+ return arg;
1208
+ }
1209
+ });
1020
1210
  }
1021
1211
  __name(createColoredArgs, "createColoredArgs");
1022
1212
  function timer(arg, task) {
@@ -1033,9 +1223,7 @@ function timer(arg, task) {
1033
1223
  if (!types.isPromise(retval)) {
1034
1224
  return done(retval);
1035
1225
  }
1036
- return retval.then((result) => {
1037
- return done(result);
1038
- });
1226
+ return retval.then((result) => done(result));
1039
1227
  function done(retval2) {
1040
1228
  if (process.exitCode) {
1041
1229
  return retval2;
@@ -1049,7 +1237,7 @@ function timer(arg, task) {
1049
1237
  __name(timer, "timer");
1050
1238
 
1051
1239
  // src/lib/internal/validateParsed.ts
1052
- function validateParsed(args, optionValues, argDefs, optionDefs) {
1240
+ function validateParsed(args, optionValues, argDefs, optionDefs, rawNames = {}, invalid = /* @__PURE__ */ new Set()) {
1053
1241
  return argDefs.map((def, index) => {
1054
1242
  const value = args[index];
1055
1243
  if (def.required && (def.variadic ? Array.isArray(value) && value.length === 0 : value === void 0)) {
@@ -1057,34 +1245,25 @@ function validateParsed(args, optionValues, argDefs, optionDefs) {
1057
1245
  }
1058
1246
  if (def.choices && value !== void 0 && ![
1059
1247
  value
1060
- ].flat().every((v) => {
1061
- return def.choices.includes(v);
1062
- })) {
1063
- return `Invalid argument [${index}] ${def.usage}: Got \`${value}\`. Accepted values: [${def.choices.map((c) => {
1064
- return `\`${c}\``;
1065
- }).join(",")}]`;
1248
+ ].flat().every((v) => def.choices.includes(v))) {
1249
+ return `Invalid argument [${index}] ${def.usage}: Got \`${value}\`. Accepted values: [${def.choices.map((c) => `\`${c}\``).join(",")}]`;
1066
1250
  }
1067
1251
  }).concat(entriesOf(optionValues).map(([key, value]) => {
1068
- const def = optionDefs.find((o) => {
1069
- return o.name === key;
1070
- });
1252
+ const def = optionDefs.find((o) => o.name === key);
1071
1253
  if (!def) {
1072
- return `Unknown option --${key}`;
1254
+ return `Unknown option ${rawNames[key] ?? `--${key}`}`;
1073
1255
  }
1074
1256
  if (def.choices && value !== void 0 && !(def.variadic ? value : [
1075
1257
  value
1076
- ]).every((v) => {
1077
- return def.choices.includes(v);
1078
- })) {
1079
- return `Invalid option value ${def.flags}: Got \`${value}\`. Accepted values: [${def.choices.map((c) => {
1080
- return `\`${c}\``;
1081
- }).join(",")}]`;
1082
- }
1083
- })).filter((s) => {
1084
- return s !== void 0;
1085
- }).reduce((acc, curr) => {
1086
- return (acc ?? []).concat(curr);
1087
- }, void 0);
1258
+ ]).every((v) => def.choices.includes(v))) {
1259
+ return `Invalid option value ${def.flags}: Got \`${value}\`. Accepted values: [${def.choices.map((c) => `\`${c}\``).join(",")}]`;
1260
+ }
1261
+ })).concat(optionDefs.map((def) => {
1262
+ const value = optionValues[def.name];
1263
+ if (def.required && !invalid.has(def.name) && (value === void 0 || Array.isArray(value) && !value.length)) {
1264
+ return `Missing option ${def.flags}`;
1265
+ }
1266
+ })).filter((s) => s !== void 0).reduce((acc, curr) => (acc ?? []).concat(curr), void 0);
1088
1267
  }
1089
1268
  __name(validateParsed, "validateParsed");
1090
1269
 
@@ -1100,6 +1279,7 @@ function _ts_metadata2(k, v) {
1100
1279
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
1101
1280
  }
1102
1281
  __name(_ts_metadata2, "_ts_metadata");
1282
+ var builtinOptions = /* @__PURE__ */ new WeakSet();
1103
1283
  var Command = class _Command {
1104
1284
  static {
1105
1285
  __name(this, "Command");
@@ -1143,21 +1323,17 @@ var Command = class _Command {
1143
1323
  enumerable: false
1144
1324
  });
1145
1325
  if (!parent) {
1146
- this.addOption("-D, --debug", {
1147
- description: "Display debug information"
1148
- }).addOptionHook("debug", ({ cmd, ...data }) => {
1149
- console.debug(util.inspect(cmd, {
1150
- depth: 1,
1326
+ this.addBuiltinOption("-D, --debug", "Display debug information", ({ cmd, ...data }) => {
1327
+ data.logger.debug(util.inspect(cmd, {
1328
+ depth: 3,
1151
1329
  colors: true
1152
1330
  }));
1153
- console.debug(util.inspect(data, {
1154
- depth: 3,
1331
+ data.logger.debug(util.inspect(data, {
1332
+ depth: 1,
1155
1333
  colors: true
1156
1334
  }));
1157
1335
  });
1158
- this.addOption("-h, --help", {
1159
- description: "Display help information"
1160
- }).addOptionHook("help", ({ cmd }) => {
1336
+ this.addBuiltinOption("-h, --help", "Display help information", ({ cmd }) => {
1161
1337
  console.log(cmd.renderHelp());
1162
1338
  process.exitCode = 0;
1163
1339
  });
@@ -1189,23 +1365,17 @@ var Command = class _Command {
1189
1365
  }
1190
1366
  /** adds aliases to existing ones */
1191
1367
  addAliases(...aliases) {
1192
- const taken = this.parent ? valuesOf(this.parent.commands).flatMap((c) => {
1193
- return [
1194
- c.name,
1195
- ...c.aliases
1196
- ];
1197
- }) : [];
1198
- array.uniq(aliases.flat()).filter((a) => {
1199
- return !this.aliases.includes(a) && a !== this.name;
1200
- }).forEach((a) => {
1368
+ const taken = this.parent ? valuesOf(this.parent.commands).flatMap((c) => [
1369
+ c.name,
1370
+ ...c.aliases
1371
+ ]) : [];
1372
+ array.uniq(aliases.flat()).filter((a) => !this.aliases.includes(a) && a !== this.name).forEach((a) => {
1201
1373
  if (taken.includes(a)) {
1202
1374
  throw new Error(`Alias "${a}" is already used by a sibling command: ${findCommand(this.parent, a)?.name}`);
1203
1375
  }
1204
1376
  this.aliases.push(a);
1205
1377
  });
1206
- this.aliases.sort((a, b) => {
1207
- return a.length - b.length;
1208
- });
1378
+ this.aliases.sort((a, b) => a.length - b.length);
1209
1379
  return this;
1210
1380
  }
1211
1381
  /** sets the command version */
@@ -1214,12 +1384,8 @@ var Command = class _Command {
1214
1384
  if (findOption(this, "version")) {
1215
1385
  return this;
1216
1386
  }
1217
- return this.addOption("-V, --version", {
1218
- description: "Display semver version"
1219
- }).addOptionHook("version", ({ cmd }) => {
1220
- console.log(getCommandAndAncestors(cmd).find((c) => {
1221
- return c.version;
1222
- })?.version);
1387
+ return this.addBuiltinOption("-V, --version", "Display semver version", ({ cmd }) => {
1388
+ console.log(getCommandAndAncestors(cmd).find((c) => c.version)?.version);
1223
1389
  process.exitCode = 0;
1224
1390
  });
1225
1391
  }
@@ -1252,32 +1418,20 @@ var Command = class _Command {
1252
1418
  const sub = this.createSubcommand(name);
1253
1419
  const inherit = this.options;
1254
1420
  sub.options.push(...inherit);
1255
- const inheritHooks = this.hooks.filter((t) => {
1256
- return inherit.some((i) => {
1257
- return i.name === t.name;
1258
- });
1259
- });
1421
+ const inheritHooks = this.hooks.filter((t) => inherit.some((i) => i.name === t.name));
1260
1422
  sub.hooks.push(...inheritHooks);
1261
- const taken = valuesOf(this.commands).flatMap((c) => {
1262
- return [
1263
- c.name,
1264
- ...c.aliases
1265
- ];
1266
- });
1423
+ const taken = valuesOf(this.commands).flatMap((c) => [
1424
+ c.name,
1425
+ ...c.aliases
1426
+ ]);
1267
1427
  if (taken.includes(name)) {
1268
- throw new Error(`Command name "${getCommandAndAncestors(sub).map((c) => {
1269
- return c.name;
1270
- })}" is already used by this command or its aliases: ${taken.join(", ")}`);
1428
+ throw new Error(`Command name "${getCommandAndAncestors(sub).map((c) => c.name)}" is already used by this command or its aliases: ${taken.join(", ")}`);
1271
1429
  }
1272
1430
  const kebab = string.kebabCase(name);
1273
1431
  const words = kebab.split("-");
1274
- const initials = words.map((s) => {
1275
- return s[0];
1276
- }).join("");
1432
+ const initials = words.map((s) => s[0]).join("");
1277
1433
  if (taken.includes(initials)) {
1278
- const initials2 = words.map((s) => {
1279
- return s[0] + s[1];
1280
- }).join("");
1434
+ const initials2 = words.map((s) => s[0] + s[1]).join("");
1281
1435
  if (!taken.includes(initials2)) {
1282
1436
  sub.addAliases(initials2);
1283
1437
  }
@@ -1328,59 +1482,46 @@ var Command = class _Command {
1328
1482
  * adds command-line option with type inference. Parses format: `-s, --long [<value>|[value]|<value...>|[value...]]`
1329
1483
  */
1330
1484
  addOption(flags, opts = {}) {
1331
- const ins = {};
1332
- const { short, long, name, argName } = parseOptionFlags(flags);
1485
+ const ins = createOption(flags, opts);
1333
1486
  for (const opt of this.options) {
1334
- if (opt.long === long) {
1335
- throw new Error(`Option long name, --${long} already in use by: ${opt.flags}`);
1336
- }
1337
- if (opt.short === short) {
1338
- throw new Error(`Option short name, -${short} already in use by: ${opt.flags}`);
1339
- }
1340
- }
1341
- ins.flags = flags;
1342
- ins.short = short;
1343
- ins.long = long;
1344
- ins.name = name;
1345
- ins.description = "";
1346
- if (argName) {
1347
- ins.type = "string";
1348
- ins.argName = argName;
1349
- if (flags.endsWith(">")) {
1350
- if (flags.endsWith("...>")) {
1351
- ins.required = true;
1352
- ins.variadic = true;
1353
- } else {
1354
- ins.required = true;
1487
+ const builtin = builtinOptions.has(opt);
1488
+ if (opt.long === ins.long) {
1489
+ if (!builtin) {
1490
+ throw new Error(`Option long name, --${ins.long} already in use by: ${opt.flags}`);
1355
1491
  }
1356
- } else if (flags.endsWith("]") && flags.endsWith("...]")) {
1357
- ins.variadic = true;
1358
- ins.defaultValue = opts.defaultValue ?? [];
1492
+ this.options = this.options.filter((o) => o !== opt);
1493
+ this.hooks = this.hooks.filter((h) => h.name !== opt.name);
1494
+ continue;
1359
1495
  }
1360
- } else {
1361
- ins.type = "boolean";
1362
- }
1363
- for (const [key, value] of Object.entries(opts)) {
1364
- if (value !== void 0) {
1365
- Reflect.set(ins, key, value);
1366
- }
1367
- }
1368
- if (ins.env && ins.defaultValue === void 0 && typeof process.env[ins.env] === "string") {
1369
- ins.required = false;
1370
- ins.flags = ins.flags.replace("<", "[").replace(">", "]");
1371
- if (ins.type === "boolean") {
1372
- ins.defaultValue = /^(t(rue)?|y(es)?|1)$/i.test(process.env[ins.env]);
1373
- } else if (ins.variadic) {
1374
- ins.defaultValue = process.env[ins.env].replace(/\[]/, "").split(",").map((v) => {
1375
- return v.trim();
1376
- });
1377
- } else {
1378
- ins.defaultValue = process.env[ins.env];
1496
+ if (opt.short === ins.short) {
1497
+ if (!builtin) {
1498
+ throw new Error(`Option short name, -${ins.short} already in use by: ${opt.flags}`);
1499
+ }
1500
+ const longOnly = {
1501
+ ...opt,
1502
+ short: void 0,
1503
+ flags: `--${opt.long}`
1504
+ };
1505
+ builtinOptions.add(longOnly);
1506
+ this.options = this.options.map((o) => o === opt ? longOnly : o);
1379
1507
  }
1380
1508
  }
1381
1509
  this.options.push(ins);
1382
1510
  return this;
1383
1511
  }
1512
+ /** adds a built-in option with its hook; it goes without its short flag when an option already has that */
1513
+ addBuiltinOption(flags, description, action) {
1514
+ const ins = createOption(flags, {
1515
+ description
1516
+ });
1517
+ if (this.options.some((o) => o.short === ins.short)) {
1518
+ ins.short = void 0;
1519
+ ins.flags = `--${ins.long}`;
1520
+ }
1521
+ builtinOptions.add(ins);
1522
+ this.options.push(ins);
1523
+ return this.addOptionHook(ins.name, action);
1524
+ }
1384
1525
  /**
1385
1526
  * register an action to be invoked when an option is set to true or string value.
1386
1527
  *
@@ -1390,38 +1531,41 @@ var Command = class _Command {
1390
1531
  */
1391
1532
  addOptionHook(optionName, action) {
1392
1533
  const def = findOption(this, optionName);
1534
+ if (!def) {
1535
+ throw new Error(`Cannot add a hook for option "${String(optionName)}": ${this.name} has no such option`);
1536
+ }
1393
1537
  if (!def.group && /process\.exitCode ?= ?.+;?\s*}$/.test(action.toString())) {
1394
1538
  def.group = "Command Options";
1395
1539
  }
1396
1540
  this.hooks.push({
1397
1541
  name: optionName,
1398
- predicate: setName(`has${string.upperFirst(optionName)}`, ({ opts }) => {
1399
- return opts[optionName] !== void 0 && opts[optionName] !== false && !(Array.isArray(opts[optionName]) && opts[optionName].length === 0);
1400
- }),
1542
+ predicate: setName(`has${string.upperFirst(optionName)}`, ({ opts }) => opts[optionName] !== void 0 && opts[optionName] !== false && !(Array.isArray(opts[optionName]) && opts[optionName].length === 0)),
1401
1543
  action: setName(optionName, action)
1402
1544
  });
1403
1545
  return this;
1404
1546
  }
1405
1547
  /** parses command-line arguments with subcommand support and type-safe validation. */
1406
1548
  parseArgv(argv = process.argv.slice(2)) {
1407
- const sub = findCommand(this, argv[0]);
1408
- if (sub) {
1409
- return sub.parseArgv(argv.slice(1));
1549
+ const subIndex = findSubcommandIndex(this, argv);
1550
+ if (subIndex !== -1) {
1551
+ const sub = findCommand(this, argv[subIndex]);
1552
+ return sub.parseArgv(argv.filter((_, i) => i !== subIndex));
1410
1553
  }
1411
1554
  argv = normalizeArgv(argv, this.options);
1555
+ const checked = checkOptionValues(argv, this.options);
1412
1556
  const parsed = util.parseArgs({
1413
- args: argv,
1414
- options: Object.fromEntries(this.options.map((o) => {
1415
- return [
1416
- o.name,
1417
- {
1418
- type: o.type,
1419
- short: o.short,
1420
- default: o.defaultValue,
1421
- multiple: !!o.variadic
1422
- }
1423
- ];
1424
- })),
1557
+ args: checked.argv,
1558
+ options: Object.fromEntries(this.options.map((o) => [
1559
+ o.name,
1560
+ {
1561
+ type: o.type,
1562
+ default: o.defaultValue,
1563
+ multiple: !!o.variadic,
1564
+ ...o.short ? {
1565
+ short: o.short
1566
+ } : {}
1567
+ }
1568
+ ])),
1425
1569
  allowPositionals: true,
1426
1570
  tokens: true,
1427
1571
  strict: false,
@@ -1429,17 +1573,22 @@ var Command = class _Command {
1429
1573
  });
1430
1574
  collectVariadicOptionValues(parsed, this.options);
1431
1575
  mergeOptionDefaults(parsed.values, this.options);
1432
- parsed.values = objSortKeys(parsed.values, (a, b) => {
1433
- return a[1] === false ? 1 : b[1] === false ? -1 : a[1] === true ? 1 : b[1] === true ? -1 : 0;
1434
- });
1576
+ parsed.values = objSortKeys(parsed.values, (a, b) => a[1] === false ? 1 : b[1] === false ? -1 : a[1] === true ? 1 : b[1] === true ? -1 : 0);
1435
1577
  const args = resolveArguments(parsed.positionals, this.arguments);
1436
- const opts = filterObject(parsed.values, (value) => {
1437
- return value !== void 0;
1438
- });
1439
- const errors = validateParsed(args, parsed.values, this.arguments, this.options);
1440
- const path = getCommandAncestors(this).map((c) => {
1441
- return c.name;
1442
- });
1578
+ const opts = filterObject(parsed.values, (value) => value !== void 0);
1579
+ const rawNames = Object.fromEntries(parsed.tokens.flatMap((t) => t.kind === "option" ? [
1580
+ [
1581
+ t.name,
1582
+ t.rawName
1583
+ ]
1584
+ ] : []));
1585
+ const unexpected = this.arguments.some((a) => a.variadic) ? [] : parsed.positionals.slice(this.arguments.length);
1586
+ const errorList = checked.errors.concat(validateParsed(args, parsed.values, this.arguments, this.options, rawNames, checked.invalid) ?? []).concat(
1587
+ // a command with subcommands has no arguments of its own: the words after an unknown name were meant for it
1588
+ Object.keys(this.commands).length ? unexpected.slice(0, 1).map((word) => `Unknown command \`${word}\``) : unexpected.map((word) => `Unexpected argument \`${word}\``)
1589
+ );
1590
+ const errors = errorList.length ? errorList : void 0;
1591
+ const path = getCommandAncestors(this).map((c) => c.name);
1443
1592
  const data = {
1444
1593
  path,
1445
1594
  name: this.name,
@@ -1449,42 +1598,43 @@ var Command = class _Command {
1449
1598
  errors,
1450
1599
  cmd: this
1451
1600
  };
1452
- const hooks = this.hooks.filter((t) => {
1453
- return t.predicate(data);
1454
- });
1455
- const execute = /* @__PURE__ */ __name(async () => {
1601
+ const hooks = this.hooks.filter((t) => t.predicate(data));
1602
+ const execute = /* @__PURE__ */ __name(async () => await timer([
1603
+ [
1604
+ ...path,
1605
+ this.name
1606
+ ].join(" "),
1607
+ this.summary || this.description
1608
+ ], async (logger) => {
1456
1609
  for (const hook of hooks) {
1457
- await hook.action(data);
1610
+ await hook.action({
1611
+ ...data,
1612
+ get logger() {
1613
+ return logger;
1614
+ }
1615
+ });
1458
1616
  if (process.exitCode !== void 0) {
1459
1617
  return;
1460
1618
  }
1461
1619
  }
1462
- await timer([
1463
- [
1464
- ...path,
1465
- this.name
1466
- ].join(" "),
1467
- this.description
1468
- ], async (logger) => {
1469
- if (errors) {
1470
- errors.forEach((msg) => {
1471
- return logger.error(C__default.default.red(msg));
1472
- });
1473
- process.exitCode = 1;
1474
- return;
1475
- }
1476
- if (this.action) {
1477
- return await this.action(...args, opts, {
1478
- ...data,
1479
- args,
1480
- opts,
1481
- cmd: this,
1482
- logger
1483
- });
1484
- }
1485
- console.log(this.renderHelp());
1486
- });
1487
- }, "execute");
1620
+ if (errors) {
1621
+ errors.forEach((msg) => logger.error(C__default.default.red(msg)));
1622
+ process.exitCode = 1;
1623
+ return;
1624
+ }
1625
+ if (this.action) {
1626
+ return await this.action(...args, opts, {
1627
+ ...data,
1628
+ args,
1629
+ opts,
1630
+ cmd: this,
1631
+ get logger() {
1632
+ return logger;
1633
+ }
1634
+ });
1635
+ }
1636
+ console.log(this.renderHelp());
1637
+ }), "execute");
1488
1638
  return {
1489
1639
  ...data,
1490
1640
  hooks,
@@ -1493,11 +1643,13 @@ var Command = class _Command {
1493
1643
  }
1494
1644
  /**
1495
1645
  * sets the main action handler for this command, which is executed after any matching option hooks when the command is invoked.
1496
- * The handler receives parsed arguments and options with correct typings.
1646
+ * The handler receives parsed arguments and options with correct typings. It may return a value (or a promise of one):
1647
+ * `execute()` of the parse result gives it back, typed.
1497
1648
  */
1498
1649
  setAction(fn) {
1499
- this.action = setName(this.name, fn);
1500
- return this;
1650
+ const typed = this;
1651
+ typed.action = setName(this.name, fn);
1652
+ return typed;
1501
1653
  }
1502
1654
  /** returns a new Command instance. Override this method in subclasses. */
1503
1655
  createSubcommand(name) {