@gunshi/bone 1.0.0-beta.2 → 1.0.0-rc.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +0 -6
- package/lib/index.d.ts +407 -63
- package/lib/index.js +627 -265
- package/package.json +32 -38
package/lib/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
// ../../node_modules/.pnpm/args-tokens@1.3.0/node_modules/args-tokens/lib/parser.js
|
|
2
2
|
/**
|
|
3
3
|
* forked from `nodejs/node` (`pkgjs/parseargs`)
|
|
4
4
|
* repository url: https://github.com/nodejs/node (https://github.com/pkgjs/parseargs)
|
|
@@ -200,8 +200,7 @@ function isLongOptionAndValue(arg) {
|
|
|
200
200
|
function hasLongOptionPrefix(arg) {
|
|
201
201
|
return arg.startsWith(LONG_OPTION_PREFIX) && arg.length > 2;
|
|
202
202
|
}
|
|
203
|
-
|
|
204
|
-
//#region ../../node_modules/.pnpm/args-tokens@1.0.0-beta.1/node_modules/args-tokens/lib/utils.js
|
|
203
|
+
// ../../node_modules/.pnpm/args-tokens@1.3.0/node_modules/args-tokens/lib/utils.js
|
|
205
204
|
/**
|
|
206
205
|
* Entry point of utils.
|
|
207
206
|
*
|
|
@@ -231,8 +230,7 @@ function kebabnize(str) {
|
|
|
231
230
|
function formatChoices(choices) {
|
|
232
231
|
return choices.map((value) => JSON.stringify(value)).join(", ");
|
|
233
232
|
}
|
|
234
|
-
|
|
235
|
-
//#region ../../node_modules/.pnpm/args-tokens@1.0.0-beta.1/node_modules/args-tokens/lib/resolver-CAlgxe_R.js
|
|
233
|
+
// ../../node_modules/.pnpm/args-tokens@1.3.0/node_modules/args-tokens/lib/resolver-DWmHKGSL.js
|
|
236
234
|
/**
|
|
237
235
|
* Internal definitions shared by the modules of `args-tokens`.
|
|
238
236
|
*
|
|
@@ -268,9 +266,16 @@ const PURE_PARSE = Symbol.for("args-tokens.pureParse");
|
|
|
268
266
|
* Each code identifies a validation failure category and is also suitable as an
|
|
269
267
|
* i18n resource key for localized rendering.
|
|
270
268
|
*
|
|
271
|
-
*
|
|
269
|
+
* A value that breaks a constraint of the options of a combinator is reported with a code of its
|
|
270
|
+
* own: `tooSmall` and `tooLarge` for `min` and `max` of `number()`, `integer()` and `float()`,
|
|
271
|
+
* `tooShort` and `tooLong` for `minLength` and `maxLength` of `string()`, and `patternMismatch` for
|
|
272
|
+
* its `pattern`. What a `parse` function of your own throws is reported as `customParse`.
|
|
273
|
+
*
|
|
274
|
+
* {@link resolveArgs} and `parse()` do not report `unknownOption` or `unexpectedPositional`: a caller
|
|
275
|
+
* that knows what a command takes, such as a CLI framework, reports them. An option that is not in the
|
|
272
276
|
* schema takes the argument after it as its value, unless that argument is an option, and the value
|
|
273
|
-
* is dropped: with no `foo` in the schema, `--foo bar` gives no positional argument.
|
|
277
|
+
* is dropped: with no `foo` in the schema, `--foo bar` gives no positional argument. A positional
|
|
278
|
+
* argument that the schema does not take stays in `positionals`, as the other positional arguments do.
|
|
274
279
|
*/
|
|
275
280
|
const ArgsValidationErrorKeys = {
|
|
276
281
|
requiredOption: "err:arg:required-option",
|
|
@@ -282,7 +287,13 @@ const ArgsValidationErrorKeys = {
|
|
|
282
287
|
unexpectedValue: "err:arg:unexpected-value",
|
|
283
288
|
missingValue: "err:arg:missing-value",
|
|
284
289
|
conflict: "err:arg:conflict",
|
|
285
|
-
invalidDefault: "err:arg:invalid-default"
|
|
290
|
+
invalidDefault: "err:arg:invalid-default",
|
|
291
|
+
unexpectedPositional: "err:arg:unexpected-positional",
|
|
292
|
+
tooSmall: "err:arg:too-small",
|
|
293
|
+
tooLarge: "err:arg:too-large",
|
|
294
|
+
tooShort: "err:arg:too-short",
|
|
295
|
+
tooLong: "err:arg:too-long",
|
|
296
|
+
patternMismatch: "err:arg:pattern-mismatch"
|
|
286
297
|
};
|
|
287
298
|
/**
|
|
288
299
|
* Brand that marks {@link ArgsValidationError} instances.
|
|
@@ -718,7 +729,7 @@ function parseSchemaValue(value, rawArg, option, schema) {
|
|
|
718
729
|
}
|
|
719
730
|
}
|
|
720
731
|
function createRequireError(rawArg, option, schema) {
|
|
721
|
-
return new ArgResolveError(schema.type === "positional" ? `Positional argument '${option}' is required` : `
|
|
732
|
+
return new ArgResolveError(schema.type === "positional" ? `Positional argument '${option}' is required` : `Option ${createOptionDisplayName(option, schema)} is required`, option, "required", schema, {
|
|
722
733
|
code: schema.type === "positional" ? ArgsValidationErrorKeys.requiredPositional : ArgsValidationErrorKeys.requiredOption,
|
|
723
734
|
values: schema.type === "positional" ? {
|
|
724
735
|
displayName: createArgumentDisplayName(option, schema),
|
|
@@ -840,7 +851,7 @@ function isNumeric(str) {
|
|
|
840
851
|
return str.trim() !== "" && !isNaN(str);
|
|
841
852
|
}
|
|
842
853
|
function createTypeError(rawArg, option, schema, actual, expected = schema.type) {
|
|
843
|
-
return new ArgResolveError(`
|
|
854
|
+
return new ArgResolveError(`Invalid value for ${createOptionDisplayName(option, schema)}: expected ${expected}`, option, "type", schema, {
|
|
844
855
|
code: ArgsValidationErrorKeys.invalidType,
|
|
845
856
|
values: {
|
|
846
857
|
displayName: createOptionDisplayName(option, schema),
|
|
@@ -870,7 +881,7 @@ function createMissingValueError(rawArg, option, schema, next) {
|
|
|
870
881
|
const suggestion = next === void 0 || !acceptsSuggestedValue(schema, next) ? void 0 : `--${option}=${next}`;
|
|
871
882
|
const hint = suggestion === void 0 ? "" : ` (to pass '${next}' as its value, write '${suggestion}')`;
|
|
872
883
|
const choices = schema.choices ?? [];
|
|
873
|
-
return new ArgResolveError(`
|
|
884
|
+
return new ArgResolveError(`Option ${displayName} requires a value${hint}`, option, "type", schema, {
|
|
874
885
|
code: ArgsValidationErrorKeys.missingValue,
|
|
875
886
|
values: {
|
|
876
887
|
displayName,
|
|
@@ -989,7 +1000,7 @@ function hasPureParseBrand(parse) {
|
|
|
989
1000
|
function createUnexpectedValueError(rawArg, option, schema, token) {
|
|
990
1001
|
const rawName = token.rawName;
|
|
991
1002
|
const displayName = `'${rawName}'`;
|
|
992
|
-
return new ArgResolveError(`
|
|
1003
|
+
return new ArgResolveError(`Option ${displayName} does not take a value`, option, "type", schema, {
|
|
993
1004
|
code: ArgsValidationErrorKeys.unexpectedValue,
|
|
994
1005
|
values: {
|
|
995
1006
|
displayName,
|
|
@@ -1001,7 +1012,7 @@ function createUnexpectedValueError(rawArg, option, schema, token) {
|
|
|
1001
1012
|
}
|
|
1002
1013
|
function createChoiceError(rawArg, option, schema, actual) {
|
|
1003
1014
|
const choices = schema.choices ?? [];
|
|
1004
|
-
return new ArgResolveError(`
|
|
1015
|
+
return new ArgResolveError(`Invalid value for ${createOptionDisplayName(option, schema)}: expected one of ${formatChoices(choices)}`, option, "type", schema, {
|
|
1005
1016
|
code: ArgsValidationErrorKeys.invalidChoice,
|
|
1006
1017
|
values: {
|
|
1007
1018
|
displayName: createOptionDisplayName(option, schema),
|
|
@@ -1027,7 +1038,7 @@ function createChoiceError(rawArg, option, schema, actual) {
|
|
|
1027
1038
|
function createDefaultChoiceError(rawArg, option, schema) {
|
|
1028
1039
|
const choices = schema.choices ?? [];
|
|
1029
1040
|
const displayName = createOptionDisplayName(option, schema);
|
|
1030
|
-
return new ArgResolveError(`
|
|
1041
|
+
return new ArgResolveError(`Invalid default for ${displayName}: ${typeof schema.default === "string" ? JSON.stringify(schema.default) : String(schema.default)} is not one of ${formatChoices(choices)}`, option, "type", schema, {
|
|
1031
1042
|
code: ArgsValidationErrorKeys.invalidDefault,
|
|
1032
1043
|
values: {
|
|
1033
1044
|
displayName,
|
|
@@ -1043,10 +1054,11 @@ function createCustomParseError(error, rawArg, option, schema, value) {
|
|
|
1043
1054
|
const reused = reuseValidationError(error, rawArg, option, schema, value);
|
|
1044
1055
|
if (reused) return reused;
|
|
1045
1056
|
const reason = getErrorReason(error);
|
|
1046
|
-
|
|
1057
|
+
const displayName = createArgumentDisplayName(option, schema);
|
|
1058
|
+
return new ArgsValidationError(`Invalid value for ${displayName}: ${reason}`, {
|
|
1047
1059
|
code: ArgsValidationErrorKeys.customParse,
|
|
1048
1060
|
values: {
|
|
1049
|
-
displayName
|
|
1061
|
+
displayName,
|
|
1050
1062
|
name: rawArg,
|
|
1051
1063
|
reason
|
|
1052
1064
|
},
|
|
@@ -1056,6 +1068,11 @@ function createCustomParseError(error, rawArg, option, schema, value) {
|
|
|
1056
1068
|
/**
|
|
1057
1069
|
* Reuse an {@link ArgsValidationError} thrown from a custom `parse` function, filling in missing values.
|
|
1058
1070
|
*
|
|
1071
|
+
* An error with no `displayName` in its `values`, such as one thrown by the combinators, gets the
|
|
1072
|
+
* argument before its message, as a custom parse error does:
|
|
1073
|
+
* `Invalid value for '--port': Expected an integer, got 'abc'`. An error that names its argument keeps
|
|
1074
|
+
* its message.
|
|
1075
|
+
*
|
|
1059
1076
|
* @param error - The value thrown from `parse`
|
|
1060
1077
|
* @param rawArg - The argument key in the schema
|
|
1061
1078
|
* @param option - The option name used on the command line
|
|
@@ -1075,9 +1092,13 @@ function reuseValidationError(error, rawArg, option, schema, value) {
|
|
|
1075
1092
|
}
|
|
1076
1093
|
function augmentValidationError(error, rawArg, option, schema, value) {
|
|
1077
1094
|
const values = error.values;
|
|
1095
|
+
const named = values.displayName != null;
|
|
1078
1096
|
values.name ??= rawArg;
|
|
1079
1097
|
values.displayName ??= createArgumentDisplayName(option, schema);
|
|
1080
1098
|
if ((error.code === ArgsValidationErrorKeys.invalidType || error.code === ArgsValidationErrorKeys.invalidChoice) && values.actual == null) values.actual = value;
|
|
1099
|
+
if (!named) try {
|
|
1100
|
+
error.message = `Invalid value for ${String(values.displayName)}: ${error.message}`;
|
|
1101
|
+
} catch {}
|
|
1081
1102
|
}
|
|
1082
1103
|
function getErrorReason(error) {
|
|
1083
1104
|
return error instanceof Error ? error.message : String(error);
|
|
@@ -1092,8 +1113,8 @@ function createOptionDisplayName(option, schema) {
|
|
|
1092
1113
|
* Create the error for two arguments that conflict.
|
|
1093
1114
|
*
|
|
1094
1115
|
* An option is shown as it was written, such as `'-p'` or `'--no-color'`, and a positional argument
|
|
1095
|
-
* by its name, such as `'file'`, as in the message. The message
|
|
1096
|
-
*
|
|
1116
|
+
* by its name, such as `'file'`, as in the message. The message names first the argument whose
|
|
1117
|
+
* `conflicts` names the other one.
|
|
1097
1118
|
*
|
|
1098
1119
|
* @param rawArg - The argument key of the argument whose `conflicts` names the other one
|
|
1099
1120
|
* @param option - The name of that argument used on the command line
|
|
@@ -1107,7 +1128,7 @@ function createOptionDisplayName(option, schema) {
|
|
|
1107
1128
|
function createConflictError(rawArg, option, schema, actualName, conflictingArg, conflictingActualName) {
|
|
1108
1129
|
const displayName = `'${actualName}'`;
|
|
1109
1130
|
const conflictDisplayName = `'${conflictingActualName}'`;
|
|
1110
|
-
return new ArgResolveError(`${
|
|
1131
|
+
return new ArgResolveError(`${displayName} conflicts with ${conflictDisplayName}`, option, "conflict", schema, {
|
|
1111
1132
|
code: ArgsValidationErrorKeys.conflict,
|
|
1112
1133
|
values: {
|
|
1113
1134
|
displayName,
|
|
@@ -1133,8 +1154,7 @@ function checkConflicts(args, explicit, toKebab, actualInputNames) {
|
|
|
1133
1154
|
}
|
|
1134
1155
|
return [];
|
|
1135
1156
|
}
|
|
1136
|
-
|
|
1137
|
-
//#region ../../node_modules/.pnpm/args-tokens@1.0.0-beta.1/node_modules/args-tokens/lib/index.js
|
|
1157
|
+
// ../../node_modules/.pnpm/args-tokens@1.3.0/node_modules/args-tokens/lib/index.js
|
|
1138
1158
|
/**
|
|
1139
1159
|
* @author kazuya kawaguchi (a.k.a. kazupon)
|
|
1140
1160
|
* @license MIT
|
|
@@ -1143,8 +1163,7 @@ function checkConflicts(args, explicit, toKebab, actualInputNames) {
|
|
|
1143
1163
|
* @author kazuya kawaguchi (a.k.a. kazupon)
|
|
1144
1164
|
* @license MIT
|
|
1145
1165
|
*/
|
|
1146
|
-
|
|
1147
|
-
//#region ../gunshi/src/constants.ts
|
|
1166
|
+
// ../gunshi/src/constants.ts
|
|
1148
1167
|
/**
|
|
1149
1168
|
* @author kazuya kawaguchi (a.k.a. kazupon)
|
|
1150
1169
|
* @license MIT
|
|
@@ -1165,20 +1184,266 @@ const CLI_OPTIONS_DEFAULT = {
|
|
|
1165
1184
|
middleMargin: 10,
|
|
1166
1185
|
usageOptionType: false,
|
|
1167
1186
|
usageOptionValue: true,
|
|
1168
|
-
strict:
|
|
1187
|
+
strict: true,
|
|
1188
|
+
strictPositionals: false,
|
|
1189
|
+
helpHint: true,
|
|
1190
|
+
validationErrorExitCode: 1,
|
|
1169
1191
|
renderHeader: void 0,
|
|
1170
1192
|
renderUsage: void 0,
|
|
1171
1193
|
renderValidationErrors: void 0,
|
|
1172
1194
|
plugins: void 0,
|
|
1173
1195
|
fallbackToEntry: false
|
|
1174
1196
|
};
|
|
1175
|
-
|
|
1176
|
-
|
|
1197
|
+
// ../gunshi/src/error.ts
|
|
1198
|
+
/**
|
|
1199
|
+
* @author kazuya kawaguchi (a.k.a. kazupon)
|
|
1200
|
+
* @license MIT
|
|
1201
|
+
*/
|
|
1202
|
+
/**
|
|
1203
|
+
* Command not found error resource keys.
|
|
1204
|
+
*/
|
|
1205
|
+
const CommandNotFoundErrorKeys = { notFound: "err:cmd:not-found" };
|
|
1206
|
+
/**
|
|
1207
|
+
* Command resolution error resource keys.
|
|
1208
|
+
*
|
|
1209
|
+
* These errors describe an ambiguity or inconsistency while choosing a command from arguments.
|
|
1210
|
+
* They are kept separate from {@link CommandNotFoundError} so consumers can distinguish a typo
|
|
1211
|
+
* from an input whose command interpretation is not unique.
|
|
1212
|
+
*/
|
|
1213
|
+
const CommandResolutionErrorKeys = {
|
|
1214
|
+
ambiguous: "err:cmd:ambiguous",
|
|
1215
|
+
inconsistentOptions: "err:cmd:inconsistent-options",
|
|
1216
|
+
lazySchemaMismatch: "err:cmd:lazy-schema-mismatch"
|
|
1217
|
+
};
|
|
1218
|
+
/**
|
|
1219
|
+
* Brand that marks {@link CommandNotFoundError} instances.
|
|
1220
|
+
*
|
|
1221
|
+
* The brand is looked up in the global symbol registry with `Symbol.for`, so it stays
|
|
1222
|
+
* identical across bundled copies of gunshi (`gunshi`, `@gunshi/plugin`, `@gunshi/bone`)
|
|
1223
|
+
* and across realms. It lets {@link isCommandNotFoundError} recognize errors created by
|
|
1224
|
+
* another copy, where `instanceof` cannot match.
|
|
1225
|
+
*/
|
|
1226
|
+
const COMMAND_NOT_FOUND_ERROR_BRAND = Symbol.for("gunshi.CommandNotFoundError");
|
|
1227
|
+
const COMMAND_RESOLUTION_ERROR_BRAND = Symbol.for("gunshi.CommandResolutionError");
|
|
1228
|
+
/**
|
|
1229
|
+
* Error raised when a command cannot be resolved.
|
|
1230
|
+
*
|
|
1231
|
+
* Each instance carries a non-enumerable brand keyed by
|
|
1232
|
+
* `Symbol.for('gunshi.CommandNotFoundError')`, so that {@link isCommandNotFoundError}
|
|
1233
|
+
* recognizes it even when it was created by another bundled copy of gunshi.
|
|
1234
|
+
*/
|
|
1235
|
+
var CommandNotFoundError = class extends Error {
|
|
1236
|
+
code;
|
|
1237
|
+
values;
|
|
1238
|
+
commandName;
|
|
1239
|
+
candidates;
|
|
1240
|
+
commandPath;
|
|
1241
|
+
/**
|
|
1242
|
+
* Create a command-not-found error.
|
|
1243
|
+
*
|
|
1244
|
+
* @param message - Fallback error message
|
|
1245
|
+
* @param options - Command-not-found metadata
|
|
1246
|
+
*/
|
|
1247
|
+
constructor(message, options) {
|
|
1248
|
+
super(message, { cause: options.cause });
|
|
1249
|
+
this.name = "CommandNotFoundError";
|
|
1250
|
+
this.code = options.code;
|
|
1251
|
+
this.values = options.values || {};
|
|
1252
|
+
this.commandName = options.commandName;
|
|
1253
|
+
this.candidates = options.candidates || [];
|
|
1254
|
+
this.commandPath = options.commandPath || [];
|
|
1255
|
+
Object.defineProperty(this, COMMAND_NOT_FOUND_ERROR_BRAND, {
|
|
1256
|
+
value: true,
|
|
1257
|
+
enumerable: false,
|
|
1258
|
+
writable: false,
|
|
1259
|
+
configurable: false
|
|
1260
|
+
});
|
|
1261
|
+
}
|
|
1262
|
+
};
|
|
1263
|
+
/**
|
|
1264
|
+
* Error raised when command routing cannot produce one consistent command.
|
|
1265
|
+
*
|
|
1266
|
+
* The own registry brand is the cross-bundle contract. Unlike the legacy command-not-found
|
|
1267
|
+
* guard, the new guard deliberately has no name-based fallback because this error type is new and
|
|
1268
|
+
* must not classify arbitrary errors from older versions.
|
|
1269
|
+
*/
|
|
1270
|
+
var CommandResolutionError = class extends Error {
|
|
1271
|
+
code;
|
|
1272
|
+
values;
|
|
1273
|
+
commandPath;
|
|
1274
|
+
candidatePaths;
|
|
1275
|
+
/**
|
|
1276
|
+
* Create a command resolution error with structured routing metadata.
|
|
1277
|
+
*
|
|
1278
|
+
* @param message - Human-readable fallback message
|
|
1279
|
+
* @param options - Error code and command-routing metadata
|
|
1280
|
+
*/
|
|
1281
|
+
constructor(message, options = {}) {
|
|
1282
|
+
super(message, { cause: options.cause });
|
|
1283
|
+
this.name = "CommandResolutionError";
|
|
1284
|
+
this.code = options.code;
|
|
1285
|
+
this.values = options.values || {};
|
|
1286
|
+
this.commandPath = options.commandPath || [];
|
|
1287
|
+
this.candidatePaths = options.candidatePaths || [];
|
|
1288
|
+
Object.defineProperty(this, COMMAND_RESOLUTION_ERROR_BRAND, {
|
|
1289
|
+
value: true,
|
|
1290
|
+
enumerable: false,
|
|
1291
|
+
writable: false,
|
|
1292
|
+
configurable: false
|
|
1293
|
+
});
|
|
1294
|
+
}
|
|
1295
|
+
};
|
|
1296
|
+
/**
|
|
1297
|
+
* Check whether an error is a {@link CommandNotFoundError}.
|
|
1298
|
+
*
|
|
1299
|
+
* `instanceof` alone is not enough: `@gunshi/plugin` is bundled with its own copy of this
|
|
1300
|
+
* class (`noExternal: ['gunshi/plugin']`), so an error thrown by `gunshi` is never an instance
|
|
1301
|
+
* of the class a plugin imports. Errors from another copy are recognized through the
|
|
1302
|
+
* `Symbol.for('gunshi.CommandNotFoundError')` brand, which does not depend on `error.name`.
|
|
1303
|
+
*
|
|
1304
|
+
* @param error - An unknown error
|
|
1305
|
+
* @returns `true` if the error is a {@link CommandNotFoundError}
|
|
1306
|
+
*/
|
|
1307
|
+
function isCommandNotFoundError(error) {
|
|
1308
|
+
if (error instanceof CommandNotFoundError) return true;
|
|
1309
|
+
if (!isRecord(error) || !hasCommandNotFoundErrorShape(error)) return false;
|
|
1310
|
+
if (Object.hasOwn(error, COMMAND_NOT_FOUND_ERROR_BRAND) && error[COMMAND_NOT_FOUND_ERROR_BRAND] === true) return true;
|
|
1311
|
+
return error instanceof Error && error.name === "CommandNotFoundError";
|
|
1312
|
+
}
|
|
1313
|
+
/**
|
|
1314
|
+
* Check whether an error is a {@link CommandResolutionError}.
|
|
1315
|
+
*
|
|
1316
|
+
* @param error - An unknown error
|
|
1317
|
+
* @returns `true` when the error has the command-resolution brand and shape
|
|
1318
|
+
*/
|
|
1319
|
+
function isCommandResolutionError(error) {
|
|
1320
|
+
if (error instanceof CommandResolutionError) return true;
|
|
1321
|
+
if (!isRecord(error) || !hasCommandResolutionErrorShape(error)) return false;
|
|
1322
|
+
return Object.hasOwn(error, COMMAND_RESOLUTION_ERROR_BRAND) && error[COMMAND_RESOLUTION_ERROR_BRAND] === true;
|
|
1323
|
+
}
|
|
1324
|
+
/**
|
|
1325
|
+
* Check whether an error is an {@link ArgsValidationError}.
|
|
1326
|
+
*
|
|
1327
|
+
* Prefer this over the `args-tokens` guard of the same name. Both recognize errors from another
|
|
1328
|
+
* bundled copy through the `Symbol.for('args-tokens.ArgsValidationError')` brand that
|
|
1329
|
+
* `args-tokens` 0.29.0 or later sets, including subclasses such as `ArgResolveError` that
|
|
1330
|
+
* override `name` with the argument name. This guard additionally:
|
|
1331
|
+
*
|
|
1332
|
+
* - recognizes direct `ArgsValidationError` instances from copies bundling `args-tokens`
|
|
1333
|
+
* older than 0.29.0, which do not set the brand
|
|
1334
|
+
* - checks that `code` and `values` of an error from another copy have the expected types
|
|
1335
|
+
*
|
|
1336
|
+
* The guard narrows only to {@link ArgsValidationError}: across copies,
|
|
1337
|
+
* `instanceof ArgResolveError` still fails, so do not rely on `type` or `schema` for such errors.
|
|
1338
|
+
*
|
|
1339
|
+
* @param error - An unknown error
|
|
1340
|
+
* @returns `true` if the error is an {@link ArgsValidationError}
|
|
1341
|
+
*/
|
|
1342
|
+
function isArgsValidationError(error) {
|
|
1343
|
+
if (error instanceof ArgsValidationError) return true;
|
|
1344
|
+
if (!isRecord(error) || !hasArgsValidationErrorShape(error)) return false;
|
|
1345
|
+
if (isArgsValidationError$1(error)) return true;
|
|
1346
|
+
return error instanceof Error && error.name === "ArgsValidationError";
|
|
1347
|
+
}
|
|
1348
|
+
function isRecord(value) {
|
|
1349
|
+
return typeof value === "object" && value !== null;
|
|
1350
|
+
}
|
|
1351
|
+
function isStringArray(value) {
|
|
1352
|
+
return Array.isArray(value) && value.every((item) => typeof item === "string");
|
|
1353
|
+
}
|
|
1354
|
+
/**
|
|
1355
|
+
* Check whether `code` is an own or inherited property that is a string or `undefined`.
|
|
1356
|
+
*
|
|
1357
|
+
* Constructors always assign `code`, even when the option is omitted.
|
|
1358
|
+
*
|
|
1359
|
+
* @param error - An error from another copy
|
|
1360
|
+
* @returns `true` if `code` has the expected type
|
|
1361
|
+
*/
|
|
1362
|
+
function hasOptionalStringCode(error) {
|
|
1363
|
+
return "code" in error && (error.code === void 0 || typeof error.code === "string");
|
|
1364
|
+
}
|
|
1365
|
+
function hasCommandNotFoundErrorShape(error) {
|
|
1366
|
+
return hasOptionalStringCode(error) && isRecord(error.values) && typeof error.commandName === "string" && isStringArray(error.candidates) && isStringArray(error.commandPath);
|
|
1367
|
+
}
|
|
1368
|
+
function hasCommandResolutionErrorShape(error) {
|
|
1369
|
+
return hasOptionalStringCode(error) && isRecord(error.values) && isStringArray(error.commandPath) && Array.isArray(error.candidatePaths) && error.candidatePaths.every((path) => isStringArray(path));
|
|
1370
|
+
}
|
|
1371
|
+
function hasArgsValidationErrorShape(error) {
|
|
1372
|
+
return hasOptionalStringCode(error) && isRecord(error.values);
|
|
1373
|
+
}
|
|
1374
|
+
/**
|
|
1375
|
+
* Check whether a value is an exit code of a failure: an integer from 1 to 255.
|
|
1376
|
+
*
|
|
1377
|
+
* @param value - The value to check
|
|
1378
|
+
* @returns `true` if the value is an exit code of a failure
|
|
1379
|
+
*/
|
|
1380
|
+
function isFailureExitCode(value) {
|
|
1381
|
+
return Number.isInteger(value) && value >= 1 && value <= 255;
|
|
1382
|
+
}
|
|
1383
|
+
/**
|
|
1384
|
+
* Check whether validation errors must stop the command before it runs: an unknown command, a command
|
|
1385
|
+
* line that cannot be resolved, an unknown option (unless `strict` is `false`), or a positional argument
|
|
1386
|
+
* that the command does not take, of `strictPositionals`. The global options plugin reports them before
|
|
1387
|
+
* `--help` and `--version`, except an unknown option and a positional argument that the command does not
|
|
1388
|
+
* take: `--help` and `--version` are answered before them, as they are before the other validation errors.
|
|
1389
|
+
*
|
|
1390
|
+
* @param error - An aggregate validation error
|
|
1391
|
+
* @returns `true` if the validation error must be handled with priority
|
|
1392
|
+
*/
|
|
1393
|
+
function hasPriorityValidationError(error) {
|
|
1394
|
+
return error?.errors.some((error) => isCommandNotFoundError(error) || isCommandResolutionError(error) || isArgsValidationError(error) && (error.code === ArgsValidationErrorKeys.unknownOption || error.code === ArgsValidationErrorKeys.unexpectedPositional)) ?? false;
|
|
1395
|
+
}
|
|
1396
|
+
// ../gunshi/src/utils.ts
|
|
1177
1397
|
/**
|
|
1178
1398
|
* @author kazuya kawaguchi (a.k.a. kazupon)
|
|
1179
1399
|
* @license MIT
|
|
1180
1400
|
*/
|
|
1181
1401
|
/**
|
|
1402
|
+
* Check whether an argument schema is the `json` argument of `jsonArgs`, by its mark.
|
|
1403
|
+
*
|
|
1404
|
+
* @param schema - An argument schema
|
|
1405
|
+
* @returns `true` if the schema has the mark of `jsonArgs`
|
|
1406
|
+
*/
|
|
1407
|
+
function isJsonArg(schema) {
|
|
1408
|
+
return typeof schema === "object" && schema !== null && schema["~gunshi.json-arg"] === true;
|
|
1409
|
+
}
|
|
1410
|
+
/**
|
|
1411
|
+
* Resolve whether `--json` asks a command for JSON.
|
|
1412
|
+
*
|
|
1413
|
+
* A command that spreads `jsonArgs` is asked for JSON when the resolved value of its `json` is `true`:
|
|
1414
|
+
* with `--json`, or with a short name that the command gives it, but not with `--json=false`, nor with
|
|
1415
|
+
* `--json` after `--`. The raw tokens are read only when they are given, and only when there is no
|
|
1416
|
+
* value to read: when the command has no `json` argument, and when the core could not resolve the
|
|
1417
|
+
* command and left the values empty. A `json` argument without the mark belongs to the command, and
|
|
1418
|
+
* `--json` is never taken for a request then.
|
|
1419
|
+
*
|
|
1420
|
+
* @param args - The arguments of the command, the global options included
|
|
1421
|
+
* @param values - The resolved values of the arguments
|
|
1422
|
+
* @param tokens - The raw tokens of the arguments, to find a `--json` that no argument declares
|
|
1423
|
+
* @returns How the command is asked for JSON, or `undefined` when it is not
|
|
1424
|
+
*/
|
|
1425
|
+
function resolveJsonRequest(args, values, tokens) {
|
|
1426
|
+
const schema = Object.hasOwn(args, "json") ? args.json : void 0;
|
|
1427
|
+
if (schema === void 0) return tokens !== void 0 && hasJsonOption(tokens) ? "undeclared" : void 0;
|
|
1428
|
+
if (!isJsonArg(schema)) return;
|
|
1429
|
+
if (values.json !== void 0) return values.json === true ? "declared" : void 0;
|
|
1430
|
+
return tokens !== void 0 && hasJsonOption(tokens) ? "declared" : void 0;
|
|
1431
|
+
}
|
|
1432
|
+
/**
|
|
1433
|
+
* Check whether the raw tokens have a `--json` that asks for JSON: `--json` or `--json=true`, before
|
|
1434
|
+
* `--`. Without a declaration, a short name of `--json` is not known.
|
|
1435
|
+
*
|
|
1436
|
+
* @param tokens - The raw tokens of the arguments
|
|
1437
|
+
* @returns `true` if a `--json` asks for JSON
|
|
1438
|
+
*/
|
|
1439
|
+
function hasJsonOption(tokens) {
|
|
1440
|
+
for (const token of tokens) {
|
|
1441
|
+
if (token.kind === "option-terminator") return false;
|
|
1442
|
+
if (token.kind === "option" && token.rawName === "--json" && (token.value === void 0 || token.value === "true")) return true;
|
|
1443
|
+
}
|
|
1444
|
+
return false;
|
|
1445
|
+
}
|
|
1446
|
+
/**
|
|
1182
1447
|
* Check if the given command is a {@link LazyCommand}.
|
|
1183
1448
|
*
|
|
1184
1449
|
* @param cmd - A command to check
|
|
@@ -1195,6 +1460,8 @@ function isLazyCommand(cmd) {
|
|
|
1195
1460
|
*
|
|
1196
1461
|
* If the loader returns a command, the properties of the loaded command take precedence,
|
|
1197
1462
|
* and the properties that it does not define fall back to the definition that is given to `lazy`.
|
|
1463
|
+
* `run` comes from the loader only, as the definition has none. A loaded command without `run` is resolved
|
|
1464
|
+
* without it, as any command without `run`, which the CLI fails with when it runs, unless it has sub-commands.
|
|
1198
1465
|
*
|
|
1199
1466
|
* @param cmd - A {@link Commandable} or {@link LazyCommand} to resolve
|
|
1200
1467
|
* @param name - Optional name of the command, if not provided, it will use the name from the command itself.
|
|
@@ -1210,6 +1477,8 @@ async function resolveLazyCommand(cmd, name, needRunResolving = false) {
|
|
|
1210
1477
|
args: cmd.args,
|
|
1211
1478
|
examples: cmd.examples,
|
|
1212
1479
|
internal: cmd.internal,
|
|
1480
|
+
aliases: cmd.aliases,
|
|
1481
|
+
deprecated: cmd.deprecated,
|
|
1213
1482
|
entry: cmd.entry,
|
|
1214
1483
|
toKebab: cmd.toKebab,
|
|
1215
1484
|
rendering: cmd.rendering,
|
|
@@ -1218,14 +1487,20 @@ async function resolveLazyCommand(cmd, name, needRunResolving = false) {
|
|
|
1218
1487
|
if ("resource" in cmd && cmd.resource) baseCommand.resource = cmd.resource;
|
|
1219
1488
|
command = Object.assign(create(), baseCommand);
|
|
1220
1489
|
if (needRunResolving) {
|
|
1490
|
+
/**
|
|
1491
|
+
* NOTE(kazupon): the error names the command, by its `commandName` or the name that it is given with.
|
|
1492
|
+
* The lazy command is the loader function, so its `name` is the name of the function, such as
|
|
1493
|
+
* `buildLoader` of a loader in a const.
|
|
1494
|
+
*/
|
|
1495
|
+
const commandName = cmd.commandName || name || "(anonymous)";
|
|
1221
1496
|
const loaded = await cmd();
|
|
1222
1497
|
if (typeof loaded === "function") command.run = loaded;
|
|
1223
|
-
else if (typeof loaded === "object") {
|
|
1224
|
-
if (loaded.run == null) throw new TypeError(`'run' is required in command: ${cmd.name || name}`);
|
|
1498
|
+
else if (typeof loaded === "object" && loaded !== null) {
|
|
1225
1499
|
/**
|
|
1226
1500
|
* NOTE(kazupon): the loaded command wins, and the definition that is given to `lazy` is the fallback
|
|
1227
1501
|
* for what the loaded command does not define. A loader that returns `{ run }` keeps the whole definition,
|
|
1228
|
-
* like a loader that returns the runner itself.
|
|
1502
|
+
* like a loader that returns the runner itself. A loaded command without `run` is a command without `run`
|
|
1503
|
+
* (#885): the CLI fails with it where it would run, as with any other, or prints the usage of a group.
|
|
1229
1504
|
*/
|
|
1230
1505
|
command.run = loaded.run;
|
|
1231
1506
|
command.name = loaded.name ?? cmd.commandName;
|
|
@@ -1233,12 +1508,19 @@ async function resolveLazyCommand(cmd, name, needRunResolving = false) {
|
|
|
1233
1508
|
command.args = loaded.args ?? cmd.args;
|
|
1234
1509
|
command.examples = loaded.examples ?? cmd.examples;
|
|
1235
1510
|
command.internal = loaded.internal ?? cmd.internal;
|
|
1511
|
+
command.aliases = loaded.aliases ?? cmd.aliases;
|
|
1512
|
+
command.deprecated = loaded.deprecated ?? cmd.deprecated;
|
|
1236
1513
|
command.entry = loaded.entry ?? cmd.entry;
|
|
1237
1514
|
command.toKebab = loaded.toKebab ?? cmd.toKebab;
|
|
1238
1515
|
command.rendering = loaded.rendering ?? cmd.rendering;
|
|
1239
1516
|
command.subCommands = loaded.subCommands || cmd.subCommands;
|
|
1240
1517
|
if ("resource" in loaded && loaded.resource) command.resource = loaded.resource;
|
|
1241
|
-
} else
|
|
1518
|
+
} else
|
|
1519
|
+
/**
|
|
1520
|
+
* NOTE(kazupon): `null` comes here too, though `typeof null` is `'object'` (#883): a loader may return it
|
|
1521
|
+
* for a module that is not found, and it is neither a command nor a runner, as `undefined` is not.
|
|
1522
|
+
*/
|
|
1523
|
+
throw new TypeError(`Cannot resolve command: ${commandName}`);
|
|
1242
1524
|
}
|
|
1243
1525
|
} else command = Object.assign(create(), cmd);
|
|
1244
1526
|
if (command.name == null && name) command.name = name;
|
|
@@ -1264,13 +1546,27 @@ function log(...args) {
|
|
|
1264
1546
|
/**
|
|
1265
1547
|
* Get the sub-commands of a command as a normalized Map.
|
|
1266
1548
|
*
|
|
1549
|
+
* An array of sub-commands is keyed by the names of the commands (`commandName` for a lazy command).
|
|
1550
|
+
*
|
|
1267
1551
|
* @param cmd - A command or lazy command
|
|
1268
1552
|
* @returns A Map of sub-commands, or undefined if the command has no sub-commands.
|
|
1553
|
+
* @throws {TypeError} If a command in an array has no name, or two commands in an array have the same name.
|
|
1269
1554
|
*/
|
|
1270
1555
|
function getCommandSubCommands(cmd) {
|
|
1271
1556
|
const subCommands = isLazyCommand(cmd) ? cmd.subCommands : typeof cmd === "object" ? cmd.subCommands : void 0;
|
|
1272
1557
|
if (!subCommands) return;
|
|
1273
1558
|
if (subCommands instanceof Map) return subCommands.size > 0 ? subCommands : void 0;
|
|
1559
|
+
if (Array.isArray(subCommands)) {
|
|
1560
|
+
if (subCommands.length === 0) return;
|
|
1561
|
+
const map = /* @__PURE__ */ new Map();
|
|
1562
|
+
for (const sub of subCommands) {
|
|
1563
|
+
const name = isLazyCommand(sub) ? sub.commandName : sub?.name;
|
|
1564
|
+
if (typeof name !== "string" || name === "") throw new TypeError(`Sub-command name must be a non-empty string in an array of 'subCommands'`);
|
|
1565
|
+
if (map.has(name)) throw new TypeError(`Sub-command '${name}' is given twice in an array of 'subCommands'`);
|
|
1566
|
+
map.set(name, sub);
|
|
1567
|
+
}
|
|
1568
|
+
return map;
|
|
1569
|
+
}
|
|
1274
1570
|
if (typeof subCommands === "object") {
|
|
1275
1571
|
const entries = Object.entries(subCommands);
|
|
1276
1572
|
if (entries.length === 0) return;
|
|
@@ -1295,8 +1591,7 @@ function deepFreeze(obj, ignores = []) {
|
|
|
1295
1591
|
}
|
|
1296
1592
|
return Object.freeze(obj);
|
|
1297
1593
|
}
|
|
1298
|
-
|
|
1299
|
-
//#region ../gunshi/src/context.ts
|
|
1594
|
+
// ../gunshi/src/context.ts
|
|
1300
1595
|
/**
|
|
1301
1596
|
* The entry for gunshi context.
|
|
1302
1597
|
* This module is exported for the purpose of testing the command.
|
|
@@ -1331,6 +1626,11 @@ async function createCommandContext({ args = {}, explicit = {}, values = {}, pos
|
|
|
1331
1626
|
*/
|
|
1332
1627
|
const env = Object.assign(create(), CLI_OPTIONS_DEFAULT, cliOptions);
|
|
1333
1628
|
/**
|
|
1629
|
+
* NOTE(kazupon): the exit code of the validation errors is an exit code of a failure, as the `exitCode`
|
|
1630
|
+
* of a `CommandError` is: any other value is replaced with `1`.
|
|
1631
|
+
*/
|
|
1632
|
+
if (!isFailureExitCode(env.validationErrorExitCode)) env.validationErrorExitCode = 1;
|
|
1633
|
+
/**
|
|
1334
1634
|
* apply Command definition's rendering option with highest priority
|
|
1335
1635
|
*/
|
|
1336
1636
|
if (command.rendering) {
|
|
@@ -1342,6 +1642,14 @@ async function createCommandContext({ args = {}, explicit = {}, values = {}, pos
|
|
|
1342
1642
|
/**
|
|
1343
1643
|
* create the command context
|
|
1344
1644
|
*/
|
|
1645
|
+
/**
|
|
1646
|
+
* NOTE(kazupon): a command that spreads `jsonArgs` and is asked for JSON prints its result as JSON, so
|
|
1647
|
+
* the human output of `ctx.log` is silenced, as it is with `usageSilent`. The hooks and the decorators
|
|
1648
|
+
* get the same context, so their `ctx.log` is silenced too. Only the resolved value of the `json`
|
|
1649
|
+
* argument counts here, not the raw tokens: a command that does not support `--json` keeps its output,
|
|
1650
|
+
* and the global options plugin reports the `--json` given to it.
|
|
1651
|
+
*/
|
|
1652
|
+
const silent = cliOptions.usageSilent || resolveJsonRequest(_args, values) === "declared";
|
|
1345
1653
|
const core = Object.assign(create(), {
|
|
1346
1654
|
name: getCommandName(command),
|
|
1347
1655
|
description: command.description,
|
|
@@ -1357,7 +1665,7 @@ async function createCommandContext({ args = {}, explicit = {}, values = {}, pos
|
|
|
1357
1665
|
_: argv,
|
|
1358
1666
|
tokens,
|
|
1359
1667
|
toKebab: command.toKebab,
|
|
1360
|
-
log:
|
|
1668
|
+
log: silent ? NOOP : log,
|
|
1361
1669
|
validationError
|
|
1362
1670
|
});
|
|
1363
1671
|
/**
|
|
@@ -1383,8 +1691,7 @@ function getCommandName(cmd) {
|
|
|
1383
1691
|
else if (typeof cmd === "object") return cmd.name || "(anonymous)";
|
|
1384
1692
|
else return ANONYMOUS_COMMAND_NAME;
|
|
1385
1693
|
}
|
|
1386
|
-
|
|
1387
|
-
//#region ../gunshi/src/decorators.ts
|
|
1694
|
+
// ../gunshi/src/decorators.ts
|
|
1388
1695
|
/**
|
|
1389
1696
|
* @author kazuya kawaguchi (a.k.a. kazupon)
|
|
1390
1697
|
* @license MIT
|
|
@@ -1451,195 +1758,7 @@ function createDecorators() {
|
|
|
1451
1758
|
}
|
|
1452
1759
|
});
|
|
1453
1760
|
}
|
|
1454
|
-
|
|
1455
|
-
//#region ../gunshi/src/error.ts
|
|
1456
|
-
/**
|
|
1457
|
-
* @author kazuya kawaguchi (a.k.a. kazupon)
|
|
1458
|
-
* @license MIT
|
|
1459
|
-
*/
|
|
1460
|
-
/**
|
|
1461
|
-
* Command not found error resource keys.
|
|
1462
|
-
*/
|
|
1463
|
-
const CommandNotFoundErrorKeys = { notFound: "err:cmd:not-found" };
|
|
1464
|
-
/**
|
|
1465
|
-
* Command resolution error resource keys.
|
|
1466
|
-
*
|
|
1467
|
-
* These errors describe an ambiguity or inconsistency while choosing a command from arguments.
|
|
1468
|
-
* They are kept separate from {@link CommandNotFoundError} so consumers can distinguish a typo
|
|
1469
|
-
* from an input whose command interpretation is not unique.
|
|
1470
|
-
*/
|
|
1471
|
-
const CommandResolutionErrorKeys = {
|
|
1472
|
-
ambiguous: "err:cmd:ambiguous",
|
|
1473
|
-
inconsistentOptions: "err:cmd:inconsistent-options",
|
|
1474
|
-
lazySchemaMismatch: "err:cmd:lazy-schema-mismatch"
|
|
1475
|
-
};
|
|
1476
|
-
/**
|
|
1477
|
-
* Brand that marks {@link CommandNotFoundError} instances.
|
|
1478
|
-
*
|
|
1479
|
-
* The brand is looked up in the global symbol registry with `Symbol.for`, so it stays
|
|
1480
|
-
* identical across bundled copies of gunshi (`gunshi`, `@gunshi/plugin`, `@gunshi/bone`)
|
|
1481
|
-
* and across realms. It lets {@link isCommandNotFoundError} recognize errors created by
|
|
1482
|
-
* another copy, where `instanceof` cannot match.
|
|
1483
|
-
*/
|
|
1484
|
-
const COMMAND_NOT_FOUND_ERROR_BRAND = Symbol.for("gunshi.CommandNotFoundError");
|
|
1485
|
-
const COMMAND_RESOLUTION_ERROR_BRAND = Symbol.for("gunshi.CommandResolutionError");
|
|
1486
|
-
/**
|
|
1487
|
-
* Error raised when a command cannot be resolved.
|
|
1488
|
-
*
|
|
1489
|
-
* Each instance carries a non-enumerable brand keyed by
|
|
1490
|
-
* `Symbol.for('gunshi.CommandNotFoundError')`, so that {@link isCommandNotFoundError}
|
|
1491
|
-
* recognizes it even when it was created by another bundled copy of gunshi.
|
|
1492
|
-
*/
|
|
1493
|
-
var CommandNotFoundError = class extends Error {
|
|
1494
|
-
code;
|
|
1495
|
-
values;
|
|
1496
|
-
commandName;
|
|
1497
|
-
candidates;
|
|
1498
|
-
commandPath;
|
|
1499
|
-
/**
|
|
1500
|
-
* Create a command-not-found error.
|
|
1501
|
-
*
|
|
1502
|
-
* @param message - Fallback error message
|
|
1503
|
-
* @param options - Command-not-found metadata
|
|
1504
|
-
*/
|
|
1505
|
-
constructor(message, options) {
|
|
1506
|
-
super(message, { cause: options.cause });
|
|
1507
|
-
this.name = "CommandNotFoundError";
|
|
1508
|
-
this.code = options.code;
|
|
1509
|
-
this.values = options.values || {};
|
|
1510
|
-
this.commandName = options.commandName;
|
|
1511
|
-
this.candidates = options.candidates || [];
|
|
1512
|
-
this.commandPath = options.commandPath || [];
|
|
1513
|
-
Object.defineProperty(this, COMMAND_NOT_FOUND_ERROR_BRAND, {
|
|
1514
|
-
value: true,
|
|
1515
|
-
enumerable: false,
|
|
1516
|
-
writable: false,
|
|
1517
|
-
configurable: false
|
|
1518
|
-
});
|
|
1519
|
-
}
|
|
1520
|
-
};
|
|
1521
|
-
/**
|
|
1522
|
-
* Error raised when command routing cannot produce one consistent command.
|
|
1523
|
-
*
|
|
1524
|
-
* The own registry brand is the cross-bundle contract. Unlike the legacy command-not-found
|
|
1525
|
-
* guard, the new guard deliberately has no name-based fallback because this error type is new and
|
|
1526
|
-
* must not classify arbitrary errors from older versions.
|
|
1527
|
-
*/
|
|
1528
|
-
var CommandResolutionError = class extends Error {
|
|
1529
|
-
code;
|
|
1530
|
-
values;
|
|
1531
|
-
commandPath;
|
|
1532
|
-
candidatePaths;
|
|
1533
|
-
/**
|
|
1534
|
-
* Create a command resolution error with structured routing metadata.
|
|
1535
|
-
*
|
|
1536
|
-
* @param message - Human-readable fallback message
|
|
1537
|
-
* @param options - Error code and command-routing metadata
|
|
1538
|
-
*/
|
|
1539
|
-
constructor(message, options = {}) {
|
|
1540
|
-
super(message, { cause: options.cause });
|
|
1541
|
-
this.name = "CommandResolutionError";
|
|
1542
|
-
this.code = options.code;
|
|
1543
|
-
this.values = options.values || {};
|
|
1544
|
-
this.commandPath = options.commandPath || [];
|
|
1545
|
-
this.candidatePaths = options.candidatePaths || [];
|
|
1546
|
-
Object.defineProperty(this, COMMAND_RESOLUTION_ERROR_BRAND, {
|
|
1547
|
-
value: true,
|
|
1548
|
-
enumerable: false,
|
|
1549
|
-
writable: false,
|
|
1550
|
-
configurable: false
|
|
1551
|
-
});
|
|
1552
|
-
}
|
|
1553
|
-
};
|
|
1554
|
-
/**
|
|
1555
|
-
* Check whether an error is a {@link CommandNotFoundError}.
|
|
1556
|
-
*
|
|
1557
|
-
* `instanceof` alone is not enough: `@gunshi/plugin` is bundled with its own copy of this
|
|
1558
|
-
* class (`noExternal: ['gunshi/plugin']`), so an error thrown by `gunshi` is never an instance
|
|
1559
|
-
* of the class a plugin imports. Errors from another copy are recognized through the
|
|
1560
|
-
* `Symbol.for('gunshi.CommandNotFoundError')` brand, which does not depend on `error.name`.
|
|
1561
|
-
*
|
|
1562
|
-
* @param error - An unknown error
|
|
1563
|
-
* @returns `true` if the error is a {@link CommandNotFoundError}
|
|
1564
|
-
*/
|
|
1565
|
-
function isCommandNotFoundError(error) {
|
|
1566
|
-
if (error instanceof CommandNotFoundError) return true;
|
|
1567
|
-
if (!isRecord(error) || !hasCommandNotFoundErrorShape(error)) return false;
|
|
1568
|
-
if (Object.hasOwn(error, COMMAND_NOT_FOUND_ERROR_BRAND) && error[COMMAND_NOT_FOUND_ERROR_BRAND] === true) return true;
|
|
1569
|
-
return error instanceof Error && error.name === "CommandNotFoundError";
|
|
1570
|
-
}
|
|
1571
|
-
/**
|
|
1572
|
-
* Check whether an error is a {@link CommandResolutionError}.
|
|
1573
|
-
*
|
|
1574
|
-
* @param error - An unknown error
|
|
1575
|
-
* @returns `true` when the error has the command-resolution brand and shape
|
|
1576
|
-
*/
|
|
1577
|
-
function isCommandResolutionError(error) {
|
|
1578
|
-
if (error instanceof CommandResolutionError) return true;
|
|
1579
|
-
if (!isRecord(error) || !hasCommandResolutionErrorShape(error)) return false;
|
|
1580
|
-
return Object.hasOwn(error, COMMAND_RESOLUTION_ERROR_BRAND) && error[COMMAND_RESOLUTION_ERROR_BRAND] === true;
|
|
1581
|
-
}
|
|
1582
|
-
/**
|
|
1583
|
-
* Check whether an error is an {@link ArgsValidationError}.
|
|
1584
|
-
*
|
|
1585
|
-
* Prefer this over the `args-tokens` guard of the same name. Both recognize errors from another
|
|
1586
|
-
* bundled copy through the `Symbol.for('args-tokens.ArgsValidationError')` brand that
|
|
1587
|
-
* `args-tokens` 0.29.0 or later sets, including subclasses such as `ArgResolveError` that
|
|
1588
|
-
* override `name` with the argument name. This guard additionally:
|
|
1589
|
-
*
|
|
1590
|
-
* - recognizes direct `ArgsValidationError` instances from copies bundling `args-tokens`
|
|
1591
|
-
* older than 0.29.0, which do not set the brand
|
|
1592
|
-
* - checks that `code` and `values` of an error from another copy have the expected types
|
|
1593
|
-
*
|
|
1594
|
-
* The guard narrows only to {@link ArgsValidationError}: across copies,
|
|
1595
|
-
* `instanceof ArgResolveError` still fails, so do not rely on `type` or `schema` for such errors.
|
|
1596
|
-
*
|
|
1597
|
-
* @param error - An unknown error
|
|
1598
|
-
* @returns `true` if the error is an {@link ArgsValidationError}
|
|
1599
|
-
*/
|
|
1600
|
-
function isArgsValidationError(error) {
|
|
1601
|
-
if (error instanceof ArgsValidationError) return true;
|
|
1602
|
-
if (!isRecord(error) || !hasArgsValidationErrorShape(error)) return false;
|
|
1603
|
-
if (isArgsValidationError$1(error)) return true;
|
|
1604
|
-
return error instanceof Error && error.name === "ArgsValidationError";
|
|
1605
|
-
}
|
|
1606
|
-
function isRecord(value) {
|
|
1607
|
-
return typeof value === "object" && value !== null;
|
|
1608
|
-
}
|
|
1609
|
-
function isStringArray(value) {
|
|
1610
|
-
return Array.isArray(value) && value.every((item) => typeof item === "string");
|
|
1611
|
-
}
|
|
1612
|
-
/**
|
|
1613
|
-
* Check whether `code` is an own or inherited property that is a string or `undefined`.
|
|
1614
|
-
*
|
|
1615
|
-
* Constructors always assign `code`, even when the option is omitted.
|
|
1616
|
-
*
|
|
1617
|
-
* @param error - An error from another copy
|
|
1618
|
-
* @returns `true` if `code` has the expected type
|
|
1619
|
-
*/
|
|
1620
|
-
function hasOptionalStringCode(error) {
|
|
1621
|
-
return "code" in error && (error.code === void 0 || typeof error.code === "string");
|
|
1622
|
-
}
|
|
1623
|
-
function hasCommandNotFoundErrorShape(error) {
|
|
1624
|
-
return hasOptionalStringCode(error) && isRecord(error.values) && typeof error.commandName === "string" && isStringArray(error.candidates) && isStringArray(error.commandPath);
|
|
1625
|
-
}
|
|
1626
|
-
function hasCommandResolutionErrorShape(error) {
|
|
1627
|
-
return hasOptionalStringCode(error) && isRecord(error.values) && isStringArray(error.commandPath) && Array.isArray(error.candidatePaths) && error.candidatePaths.every((path) => isStringArray(path));
|
|
1628
|
-
}
|
|
1629
|
-
function hasArgsValidationErrorShape(error) {
|
|
1630
|
-
return hasOptionalStringCode(error) && isRecord(error.values);
|
|
1631
|
-
}
|
|
1632
|
-
/**
|
|
1633
|
-
* Check whether validation errors should be handled before version, help, or command execution.
|
|
1634
|
-
*
|
|
1635
|
-
* @param error - An aggregate validation error
|
|
1636
|
-
* @returns `true` if the validation error must be handled with priority
|
|
1637
|
-
*/
|
|
1638
|
-
function hasPriorityValidationError(error) {
|
|
1639
|
-
return error?.errors.some((error) => isCommandNotFoundError(error) || isCommandResolutionError(error) || isArgsValidationError(error) && error.code === ArgsValidationErrorKeys.unknownOption) ?? false;
|
|
1640
|
-
}
|
|
1641
|
-
//#endregion
|
|
1642
|
-
//#region ../gunshi/src/plugin/context.ts
|
|
1761
|
+
// ../gunshi/src/plugin/context.ts
|
|
1643
1762
|
/**
|
|
1644
1763
|
* @author kazuya kawaguchi (a.k.a. kazupon)
|
|
1645
1764
|
* @license MIT
|
|
@@ -1722,8 +1841,7 @@ function createPluginContext(decorators, initialSubCommands) {
|
|
|
1722
1841
|
function findGlobalOptionByShort(globalOptions, short) {
|
|
1723
1842
|
for (const [name, schema] of globalOptions) if (schema.short === short) return name;
|
|
1724
1843
|
}
|
|
1725
|
-
|
|
1726
|
-
//#region ../gunshi/src/plugin/dependency.ts
|
|
1844
|
+
// ../gunshi/src/plugin/dependency.ts
|
|
1727
1845
|
/**
|
|
1728
1846
|
* @author kazuya kawaguchi (a.k.a. kazupon)
|
|
1729
1847
|
* @license MIT
|
|
@@ -1764,8 +1882,7 @@ function resolveDependencies(plugins) {
|
|
|
1764
1882
|
for (const plugin of plugins) visit(plugin);
|
|
1765
1883
|
return sorted;
|
|
1766
1884
|
}
|
|
1767
|
-
|
|
1768
|
-
//#region ../gunshi/src/cli/args.ts
|
|
1885
|
+
// ../gunshi/src/cli/args.ts
|
|
1769
1886
|
/**
|
|
1770
1887
|
* @author kazuya kawaguchi (a.k.a. kazupon)
|
|
1771
1888
|
* @license MIT
|
|
@@ -1805,8 +1922,7 @@ function resolveGlobalOptions(globalOptions, args) {
|
|
|
1805
1922
|
} : schema;
|
|
1806
1923
|
return resolved;
|
|
1807
1924
|
}
|
|
1808
|
-
|
|
1809
|
-
//#region ../gunshi/src/cli/core.ts
|
|
1925
|
+
// ../gunshi/src/cli/core.ts
|
|
1810
1926
|
/**
|
|
1811
1927
|
* @author kazuya kawaguchi (a.k.a. kazupon)
|
|
1812
1928
|
* @license MIT
|
|
@@ -1839,8 +1955,11 @@ async function cliCore(argv, entry, options, plugins, usageOnly = false) {
|
|
|
1839
1955
|
* NOTE(kazupon): a CLI whose user declares no sub-commands has no command tree of its own,
|
|
1840
1956
|
* so a positional argument must not become a command name just because a plugin added a command.
|
|
1841
1957
|
* The user can still opt out with an explicit `fallbackToEntry: false`.
|
|
1958
|
+
* An entry command without `run` has nothing to run with the argument: the commands that the plugins
|
|
1959
|
+
* add are the commands of the CLI, so an argument that is not one of them is reported, as when the
|
|
1960
|
+
* user declares them (#874). A lazy entry command and a runner given to `cli()` have something to run.
|
|
1842
1961
|
*/
|
|
1843
|
-
if (initialSubCommands.size === 0 && cliOptions.subCommands.size > 0 && options.fallbackToEntry === void 0) cliOptions.fallbackToEntry = true;
|
|
1962
|
+
if (initialSubCommands.size === 0 && cliOptions.subCommands.size > 0 && options.fallbackToEntry === void 0 && (typeof entry === "function" || entry.run != null)) cliOptions.fallbackToEntry = true;
|
|
1844
1963
|
const tokens = parseArgs(argv);
|
|
1845
1964
|
const selection = resolveCommandSelection(tokens, entry, cliOptions, pluginContext.globalOptions);
|
|
1846
1965
|
const resolved = selection.context;
|
|
@@ -1866,8 +1985,24 @@ async function cliCore(argv, entry, options, plugins, usageOnly = false) {
|
|
|
1866
1985
|
}
|
|
1867
1986
|
const routingOptions = Object.assign(create(), cliOptions, { subCommands: new Map(cliOptions.subCommands) });
|
|
1868
1987
|
if (targetLevelSubCommands) cliOptions.subCommands = targetLevelSubCommands;
|
|
1869
|
-
|
|
1870
|
-
|
|
1988
|
+
/**
|
|
1989
|
+
* NOTE(kazupon): a lazy command is loaded before the arguments are parsed, so that the arguments of the
|
|
1990
|
+
* loaded command are used. An error of the loading, such as one that the loader throws, is thrown where the
|
|
1991
|
+
* command would run, after the decorators, as an error of `run` is (#885): the global options plugin prints a
|
|
1992
|
+
* `CommandError` with its exit code, and the failure as JSON with `--json`, and `onErrorCommand` sees it.
|
|
1993
|
+
* Until then, the definition given to `lazy` stands for the command, so that its arguments are parsed, and
|
|
1994
|
+
* `--help` prints its usage.
|
|
1995
|
+
*/
|
|
1996
|
+
let resolvedCommand;
|
|
1997
|
+
let loadFailure;
|
|
1998
|
+
if (isLazyCommand(targetCommand)) try {
|
|
1999
|
+
resolvedCommand = await resolveLazyCommand(targetCommand, targetCommandName, true);
|
|
2000
|
+
} catch (error) {
|
|
2001
|
+
loadFailure = { error };
|
|
2002
|
+
resolvedCommand = await resolveLazyCommand(targetCommand, targetCommandName);
|
|
2003
|
+
}
|
|
2004
|
+
else resolvedCommand = targetCommand;
|
|
2005
|
+
if (selection.error == null && isLazyCommand(targetCommand) && loadFailure === void 0) {
|
|
1871
2006
|
const loaded = resolveCommandTreeFromPositionals(getRoutingPositionals(tokens, pluginContext.globalOptions, resolvedCommand), entry, routingOptions);
|
|
1872
2007
|
if (!sameCommandPath(loaded.commandPath, targetCommandPath)) additionalValidationErrors.push(createLazySchemaMismatchError(targetCommandPath, loaded.commandPath));
|
|
1873
2008
|
}
|
|
@@ -1891,8 +2026,15 @@ async function cliCore(argv, entry, options, plugins, usageOnly = false) {
|
|
|
1891
2026
|
toKebab: resolvedCommand.toKebab,
|
|
1892
2027
|
skipPositional
|
|
1893
2028
|
});
|
|
1894
|
-
const validationError = mergeValidationErrors(error, [
|
|
1895
|
-
|
|
2029
|
+
const validationError = mergeValidationErrors(error, [
|
|
2030
|
+
...additionalValidationErrors,
|
|
2031
|
+
...cliOptions.strict && !diagnostic ? createUnknownOptionErrors(findUnknownOptions(args, tokens, {
|
|
2032
|
+
toKebab: resolvedCommand.toKebab,
|
|
2033
|
+
suggestedValues: findSuggestedValues(args, argv, tokens, error, { toKebab: resolvedCommand.toKebab })
|
|
2034
|
+
})) : [],
|
|
2035
|
+
...cliOptions.strictPositionals && !diagnostic && additionalValidationErrors.length === 0 ? createUnexpectedPositionalErrors(findUnexpectedPositionals(args, positionals, skipPositional)) : []
|
|
2036
|
+
]);
|
|
2037
|
+
const commandContext = await createCommandContext({
|
|
1896
2038
|
args,
|
|
1897
2039
|
explicit,
|
|
1898
2040
|
values,
|
|
@@ -1907,7 +2049,138 @@ async function cliCore(argv, entry, options, plugins, usageOnly = false) {
|
|
|
1907
2049
|
extensions: getPluginExtensions(resolvedPlugins),
|
|
1908
2050
|
validationError,
|
|
1909
2051
|
cliOptions
|
|
1910
|
-
})
|
|
2052
|
+
});
|
|
2053
|
+
markDeprecatedCommands(commandContext, collectDeprecatedCommands(routingOptions.subCommands, targetCommandPath, resolvedCommand));
|
|
2054
|
+
const reported = trackReported(commandContext);
|
|
2055
|
+
let fallbackRunner = NOOP;
|
|
2056
|
+
if (loadFailure !== void 0) {
|
|
2057
|
+
const { error } = loadFailure;
|
|
2058
|
+
fallbackRunner = () => {
|
|
2059
|
+
throw error;
|
|
2060
|
+
};
|
|
2061
|
+
} else if (resolvedCommand.run == null) {
|
|
2062
|
+
markWithoutRun(commandContext);
|
|
2063
|
+
if (!(targetDepth === 0 ? routingOptions.subCommands.size > 0 : (getCommandSubCommands(resolvedCommand)?.size ?? 0) > 0)) {
|
|
2064
|
+
const commandName = resolvedCommand.name || targetCommandName || "(anonymous)";
|
|
2065
|
+
fallbackRunner = () => {
|
|
2066
|
+
throw new TypeError(`'run' is required in command: ${commandName}`);
|
|
2067
|
+
};
|
|
2068
|
+
}
|
|
2069
|
+
}
|
|
2070
|
+
try {
|
|
2071
|
+
return await executeCommand(resolvedCommand, commandContext, decorators.commandDecorators, fallbackRunner);
|
|
2072
|
+
} catch (error) {
|
|
2073
|
+
/**
|
|
2074
|
+
* NOTE(kazupon): a plugin that has reported the validation errors to the user marks them, as the
|
|
2075
|
+
* global options plugin does after it prints them to stderr and sets the exit code. They have been
|
|
2076
|
+
* dealt with, and `onErrorCommand` has seen them in `executeCommand`, so `cli()` ends without
|
|
2077
|
+
* rejecting. Errors that nobody reported, such as when the app renders the validation errors itself
|
|
2078
|
+
* or an error thrown by a command, reject as before.
|
|
2079
|
+
*/
|
|
2080
|
+
if (error != null && typeof error === "object" && reported.has(error)) return;
|
|
2081
|
+
throw error;
|
|
2082
|
+
}
|
|
2083
|
+
}
|
|
2084
|
+
/**
|
|
2085
|
+
* The key of the registry that maps the command context of a run to the set of the errors that a plugin
|
|
2086
|
+
* has reported to the user during the run. The global options plugin uses the same registered symbol,
|
|
2087
|
+
* since `gunshi` and the plugins bundle their own copies.
|
|
2088
|
+
*/
|
|
2089
|
+
const REPORTED = Symbol.for("gunshi.reported");
|
|
2090
|
+
/**
|
|
2091
|
+
* Prepare the set of the errors that a plugin reports to the user during a run. The set belongs to the
|
|
2092
|
+
* command context of the run, so a report counts for this run only: not for a nested `cli()` in a hook,
|
|
2093
|
+
* nor for a later run in which the same error is thrown again.
|
|
2094
|
+
*
|
|
2095
|
+
* @param ctx - The command context of the run
|
|
2096
|
+
* @returns The set of the errors that have been reported during the run
|
|
2097
|
+
*/
|
|
2098
|
+
function trackReported(ctx) {
|
|
2099
|
+
const registry = globalThis;
|
|
2100
|
+
const reported = /* @__PURE__ */ new WeakSet();
|
|
2101
|
+
(registry[REPORTED] ??= /* @__PURE__ */ new WeakMap()).set(ctx, reported);
|
|
2102
|
+
return reported;
|
|
2103
|
+
}
|
|
2104
|
+
/**
|
|
2105
|
+
* The key of the registry of the command contexts whose command has no `run`. The global options plugin
|
|
2106
|
+
* and the usage renderer plugin read it with `isWithoutRun` of `@gunshi/shared`, by the same registered
|
|
2107
|
+
* symbol, since `gunshi` and the plugins bundle their own copies. Neither is in the public API.
|
|
2108
|
+
*/
|
|
2109
|
+
const WITHOUT_RUN = Symbol.for("gunshi.withoutRun");
|
|
2110
|
+
/**
|
|
2111
|
+
* Mark the command context of a run whose command has no `run`.
|
|
2112
|
+
*
|
|
2113
|
+
* NOTE(kazupon): the global options plugin prints the usage of a command that has sub-commands and no
|
|
2114
|
+
* `run`, when it runs without a sub-command, as `--help` does. The plugin cannot tell it from the context,
|
|
2115
|
+
* nor from the runner that it decorates, which the core always wraps, so the core tells it. The command
|
|
2116
|
+
* is checked once it is loaded, so a lazy command whose loader returns a command without `run` is marked
|
|
2117
|
+
* too. The registry is weak, and holds the context of this run only: a nested `cli()` in a hook has a
|
|
2118
|
+
* context of its own.
|
|
2119
|
+
*
|
|
2120
|
+
* @param ctx - The command context of the run
|
|
2121
|
+
*/
|
|
2122
|
+
function markWithoutRun(ctx) {
|
|
2123
|
+
const registry = globalThis;
|
|
2124
|
+
(registry[WITHOUT_RUN] ??= /* @__PURE__ */ new WeakSet()).add(ctx);
|
|
2125
|
+
}
|
|
2126
|
+
/**
|
|
2127
|
+
* The key of the registry of the deprecated commands on the path of a run. The global options plugin and the
|
|
2128
|
+
* usage renderer plugin read it with `getDeprecatedCommands` of `@gunshi/shared`, by the same registered
|
|
2129
|
+
* symbol, since `gunshi` and the plugins bundle their own copies. Neither is in the public API.
|
|
2130
|
+
*/
|
|
2131
|
+
const DEPRECATED_COMMANDS = Symbol.for("gunshi.deprecatedCommands");
|
|
2132
|
+
/**
|
|
2133
|
+
* Check whether the `deprecated` of a command or an argument marks it as deprecated.
|
|
2134
|
+
*
|
|
2135
|
+
* @param deprecated - The `deprecated` of a command or an argument
|
|
2136
|
+
* @returns `true` for `true` or a text
|
|
2137
|
+
*/
|
|
2138
|
+
function isDeprecated(deprecated) {
|
|
2139
|
+
return deprecated === true || typeof deprecated === "string";
|
|
2140
|
+
}
|
|
2141
|
+
/**
|
|
2142
|
+
* Collect the deprecated commands on the path of a run, root first.
|
|
2143
|
+
*
|
|
2144
|
+
* NOTE(kazupon): the command that runs is the loaded one, whose `deprecated` wins over the one of the definition
|
|
2145
|
+
* given to `lazy`. The commands above it are the definitions of the tree, as the routing found them. The entry
|
|
2146
|
+
* command is not on the path.
|
|
2147
|
+
*
|
|
2148
|
+
* @param root - The sub-commands at the top level
|
|
2149
|
+
* @param commandPath - The names of the commands on the path
|
|
2150
|
+
* @param resolvedCommand - The command that runs
|
|
2151
|
+
* @returns The deprecated commands, with their paths
|
|
2152
|
+
*/
|
|
2153
|
+
function collectDeprecatedCommands(root, commandPath, resolvedCommand) {
|
|
2154
|
+
const marks = [];
|
|
2155
|
+
let level = root;
|
|
2156
|
+
for (const [index, name] of commandPath.entries()) {
|
|
2157
|
+
const last = index === commandPath.length - 1;
|
|
2158
|
+
const declared = level?.get(name);
|
|
2159
|
+
const command = last ? resolvedCommand : declared;
|
|
2160
|
+
if (command == null) break;
|
|
2161
|
+
if (isDeprecated(command.deprecated)) marks.push({
|
|
2162
|
+
commandPath: commandPath.slice(0, index + 1),
|
|
2163
|
+
deprecated: command.deprecated
|
|
2164
|
+
});
|
|
2165
|
+
level = declared == null ? void 0 : getCommandSubCommands(declared);
|
|
2166
|
+
}
|
|
2167
|
+
return marks;
|
|
2168
|
+
}
|
|
2169
|
+
/**
|
|
2170
|
+
* Mark the command context of a run with the deprecated commands on its path.
|
|
2171
|
+
*
|
|
2172
|
+
* NOTE(kazupon): the context has the command that runs, and not the commands above it, such as the old name of a
|
|
2173
|
+
* renamed group, so the core, which walks the path, tells the plugins which of them are deprecated. The global
|
|
2174
|
+
* options plugin warns of them, and the usage renderer plugin says so in the help. The registry is weak, and
|
|
2175
|
+
* holds the context of this run only.
|
|
2176
|
+
*
|
|
2177
|
+
* @param ctx - The command context of the run
|
|
2178
|
+
* @param marks - The deprecated commands on the path
|
|
2179
|
+
*/
|
|
2180
|
+
function markDeprecatedCommands(ctx, marks) {
|
|
2181
|
+
if (marks.length === 0) return;
|
|
2182
|
+
const registry = globalThis;
|
|
2183
|
+
(registry[DEPRECATED_COMMANDS] ??= /* @__PURE__ */ new WeakMap()).set(ctx, marks);
|
|
1911
2184
|
}
|
|
1912
2185
|
/**
|
|
1913
2186
|
* Create the decorator that renders the usage of the command instead of running it.
|
|
@@ -1997,20 +2270,23 @@ function findUnknownOptions(args, tokens, options) {
|
|
|
1997
2270
|
knownLongOptions.add(optionName);
|
|
1998
2271
|
/**
|
|
1999
2272
|
* NOTE(kazupon): a hidden option is still accepted, so it stays a known option. It is left out
|
|
2000
|
-
* of the candidates, which are what `@gunshi/plugin-suggestion` offers as "Did you mean".
|
|
2273
|
+
* of the candidates, which are what `@gunshi/plugin-suggestion` offers as "Did you mean". So is a
|
|
2274
|
+
* deprecated option, which the help leaves out too, and so is the negated form of either.
|
|
2001
2275
|
*/
|
|
2002
|
-
|
|
2276
|
+
const offered = !schema.hidden && !isDeprecated(schema.deprecated);
|
|
2277
|
+
if (offered) addLongOptionCandidate(optionName);
|
|
2003
2278
|
if (schema.short) knownShortOptions.add(schema.short);
|
|
2004
2279
|
if (schema.type === "boolean" && schema.negatable) {
|
|
2005
2280
|
const negatableOptionName = `${NEGATABLE_OPTION_PREFIX}${optionName}`;
|
|
2006
2281
|
knownNegatableOptions.add(negatableOptionName);
|
|
2007
|
-
if (
|
|
2282
|
+
if (offered) addLongOptionCandidate(negatableOptionName);
|
|
2008
2283
|
}
|
|
2009
2284
|
}
|
|
2010
2285
|
const unknownOptions = [];
|
|
2011
2286
|
for (const token of tokens) {
|
|
2012
2287
|
if (token.kind === "option-terminator") break;
|
|
2013
2288
|
if (token.kind !== "option" || !token.name || !token.rawName) continue;
|
|
2289
|
+
if (options.suggestedValues?.has(token.index)) continue;
|
|
2014
2290
|
const isLongOption = token.rawName.startsWith("--");
|
|
2015
2291
|
if (isLongOption) {
|
|
2016
2292
|
if (knownLongOptions.has(token.name) || knownNegatableOptions.has(token.name)) continue;
|
|
@@ -2023,6 +2299,38 @@ function findUnknownOptions(args, tokens, options) {
|
|
|
2023
2299
|
}
|
|
2024
2300
|
return unknownOptions;
|
|
2025
2301
|
}
|
|
2302
|
+
/**
|
|
2303
|
+
* Find the arguments that the errors of a missing value suggest as the values of their options, such as `-5` in
|
|
2304
|
+
* `--port -5`: args-tokens reads `-5` as an option, and its error says to write `--port=-5`. Such an argument is
|
|
2305
|
+
* not reported as an unknown option too.
|
|
2306
|
+
*
|
|
2307
|
+
* NOTE(kazupon): args-tokens suggests the argument right after an option that is given without a value, when the
|
|
2308
|
+
* tokens of that argument are options that are not all declared and the option may take it as a value, and gives
|
|
2309
|
+
* it in `values.next` of the error. An error without `next` suggests nothing, and its next argument is reported as
|
|
2310
|
+
* before. The same argument elsewhere on the command line is reported too.
|
|
2311
|
+
*
|
|
2312
|
+
* @param args - The arguments of the command
|
|
2313
|
+
* @param argv - The command line arguments, which the indexes of the tokens point into
|
|
2314
|
+
* @param tokens - The tokens of the command line arguments
|
|
2315
|
+
* @param error - The argument validation errors of args-tokens
|
|
2316
|
+
* @param options - How the option names are written
|
|
2317
|
+
* @returns The indexes of the suggested arguments
|
|
2318
|
+
*/
|
|
2319
|
+
function findSuggestedValues(args, argv, tokens, error, options) {
|
|
2320
|
+
const indexes = /* @__PURE__ */ new Set();
|
|
2321
|
+
for (const cause of error?.errors ?? []) {
|
|
2322
|
+
if (!isArgsValidationError$1(cause) || cause.code !== ArgsValidationErrorKeys.missingValue) continue;
|
|
2323
|
+
const { name, next } = cause.values;
|
|
2324
|
+
if (typeof name !== "string" || typeof next !== "string" || !Object.hasOwn(args, name)) continue;
|
|
2325
|
+
const schema = args[name];
|
|
2326
|
+
const optionName = resolveOptionName(name, schema, options);
|
|
2327
|
+
for (const token of tokens) {
|
|
2328
|
+
if (token.kind !== "option" || !token.rawName || token.value !== void 0) continue;
|
|
2329
|
+
if ((token.rawName.startsWith("--") ? token.name === optionName : token.name === schema.short) && argv[token.index + 1] === next) indexes.add(token.index + 1);
|
|
2330
|
+
}
|
|
2331
|
+
}
|
|
2332
|
+
return indexes;
|
|
2333
|
+
}
|
|
2026
2334
|
function resolveOptionName(name, schema, options) {
|
|
2027
2335
|
return options.toKebab || schema.toKebab ? kebabnize(name) : name;
|
|
2028
2336
|
}
|
|
@@ -2038,11 +2346,34 @@ function createUnknownOptionErrors(unknownOptions) {
|
|
|
2038
2346
|
});
|
|
2039
2347
|
});
|
|
2040
2348
|
}
|
|
2349
|
+
/**
|
|
2350
|
+
* Find the positional arguments that the command does not take: the ones after its command path that its
|
|
2351
|
+
* positional arguments do not take. A positional argument with `multiple` takes all of them.
|
|
2352
|
+
*
|
|
2353
|
+
* NOTE(kazupon): args-tokens gives the positional arguments after the command path to the positional
|
|
2354
|
+
* arguments of the command in the order they are declared, so the declared ones take the first of them,
|
|
2355
|
+
* as many as they are, an optional one included, and the rest are left over.
|
|
2356
|
+
*
|
|
2357
|
+
* @param args - The arguments of the command
|
|
2358
|
+
* @param positionals - The positional arguments, the command path included
|
|
2359
|
+
* @param skipPositional - The index of the last command name in `positionals`
|
|
2360
|
+
* @returns The positional arguments that are left over
|
|
2361
|
+
*/
|
|
2362
|
+
function findUnexpectedPositionals(args, positionals, skipPositional) {
|
|
2363
|
+
const declared = Object.values(args).filter((schema) => schema.type === "positional");
|
|
2364
|
+
if (declared.some((schema) => schema.multiple)) return [];
|
|
2365
|
+
return positionals.slice(skipPositional + 1 + declared.length);
|
|
2366
|
+
}
|
|
2367
|
+
function createUnexpectedPositionalErrors(positionals) {
|
|
2368
|
+
return positionals.map((rawName) => new ArgsValidationError(`Unexpected positional argument: ${rawName}`, {
|
|
2369
|
+
code: ArgsValidationErrorKeys.unexpectedPositional,
|
|
2370
|
+
values: { rawName }
|
|
2371
|
+
}));
|
|
2372
|
+
}
|
|
2041
2373
|
function mergeValidationErrors(error, additionalErrors) {
|
|
2042
2374
|
if (additionalErrors.length === 0) return error;
|
|
2043
2375
|
return new AggregateError(error ? [...error.errors, ...additionalErrors] : additionalErrors, error?.message || additionalErrors[0]?.message);
|
|
2044
2376
|
}
|
|
2045
|
-
const isObject = (val) => val !== null && typeof val === "object";
|
|
2046
2377
|
/**
|
|
2047
2378
|
* Create the entry command that sub-commands and plugins can see.
|
|
2048
2379
|
* The user-provided entry is copied, so that marking it with `entry: true` does not mutate it.
|
|
@@ -2060,10 +2391,13 @@ function createEntryCommand(entryCmd) {
|
|
|
2060
2391
|
};
|
|
2061
2392
|
}
|
|
2062
2393
|
function createInitialSubCommands(options, entryCommand) {
|
|
2063
|
-
const
|
|
2064
|
-
|
|
2065
|
-
|
|
2066
|
-
|
|
2394
|
+
const subCommands = new Map(getCommandSubCommands({ subCommands: options.subCommands }) ?? []);
|
|
2395
|
+
/**
|
|
2396
|
+
* NOTE(kazupon): `subCommands` works for any command definition, the entry included.
|
|
2397
|
+
* Without sub-commands in the options, the sub-commands of the entry are the top-level ones.
|
|
2398
|
+
*/
|
|
2399
|
+
if (!(subCommands.size > 0) && entryCommand) for (const [name, cmd] of getCommandSubCommands(entryCommand) ?? []) subCommands.set(name, cmd);
|
|
2400
|
+
if (subCommands.size > 0 && entryCommand) subCommands.set(resolveEntryName(entryCommand), entryCommand);
|
|
2067
2401
|
return subCommands;
|
|
2068
2402
|
}
|
|
2069
2403
|
function normalizeCliOptions(options, decorators, pluginContext, entryCommand) {
|
|
@@ -2140,8 +2474,8 @@ function resolveCommandTreeFromPositionals(positionals, entry, options) {
|
|
|
2140
2474
|
let depth = 0;
|
|
2141
2475
|
for (let i = 0; i < positionals.length; i++) {
|
|
2142
2476
|
const token = positionals[i];
|
|
2143
|
-
const
|
|
2144
|
-
if (
|
|
2477
|
+
const found = findSubCommand(currentSubCommands, token);
|
|
2478
|
+
if (found == null) {
|
|
2145
2479
|
if (depth === 0) {
|
|
2146
2480
|
if (options.fallbackToEntry) return resolveAsEntry();
|
|
2147
2481
|
const parent = resolveAsEntry();
|
|
@@ -2173,12 +2507,13 @@ function resolveCommandTreeFromPositionals(positionals, entry, options) {
|
|
|
2173
2507
|
parentSubCommands: currentSubCommands
|
|
2174
2508
|
};
|
|
2175
2509
|
}
|
|
2510
|
+
const [key, cmd] = found;
|
|
2176
2511
|
let resolved = cmd;
|
|
2177
|
-
if (typeof cmd === "function" && cmd.commandName == null) resolved = Object.assign((...args) => cmd(...args), cmd, { commandName:
|
|
2178
|
-
else if (typeof cmd === "object" && cmd.name == null) resolved = Object.assign(create(), cmd, { name:
|
|
2512
|
+
if (typeof cmd === "function" && cmd.commandName == null) resolved = Object.assign((...args) => cmd(...args), cmd, { commandName: key });
|
|
2513
|
+
else if (typeof cmd === "object" && cmd.name == null) resolved = Object.assign(create(), cmd, { name: key });
|
|
2179
2514
|
resolvedCommand = resolved;
|
|
2180
|
-
resolvedName =
|
|
2181
|
-
commandPath.push(
|
|
2515
|
+
resolvedName = key;
|
|
2516
|
+
commandPath.push(key);
|
|
2182
2517
|
depth++;
|
|
2183
2518
|
const nestedSubCommands = getCommandSubCommands(cmd);
|
|
2184
2519
|
if (nestedSubCommands && nestedSubCommands.size > 0) currentSubCommands = nestedSubCommands;
|
|
@@ -2265,9 +2600,9 @@ function collectRoutingCandidates(rawPositionals, root) {
|
|
|
2265
2600
|
const seen = /* @__PURE__ */ new Set();
|
|
2266
2601
|
function collect(commands, offset, parentPath) {
|
|
2267
2602
|
for (let index = offset; index < rawPositionals.length; index++) {
|
|
2268
|
-
const
|
|
2269
|
-
|
|
2270
|
-
|
|
2603
|
+
const found = findSubCommand(commands, rawPositionals[index]);
|
|
2604
|
+
if (found == null) continue;
|
|
2605
|
+
const [name, command] = found;
|
|
2271
2606
|
const path = [...parentPath, name];
|
|
2272
2607
|
const key = JSON.stringify(path);
|
|
2273
2608
|
const normalized = normalizeCommandReference(command, name);
|
|
@@ -2285,6 +2620,30 @@ function collectRoutingCandidates(rawPositionals, root) {
|
|
|
2285
2620
|
collect(root, 0, []);
|
|
2286
2621
|
return candidates;
|
|
2287
2622
|
}
|
|
2623
|
+
/**
|
|
2624
|
+
* Find the sub-command that a word of the command line names: the sub-command whose name is the word, or else the
|
|
2625
|
+
* one that has the word among its {@linkcode Command.aliases | aliases}.
|
|
2626
|
+
*
|
|
2627
|
+
* NOTE(kazupon): a name wins over an alias, so that an alias never hides a sub-command. A lazy command has the
|
|
2628
|
+
* aliases of its definition, as it is not loaded yet. Two sub-commands that give the same alias are a mistake in
|
|
2629
|
+
* their definitions, which is thrown as a `TypeError`, as a name given twice in an array of `subCommands` is.
|
|
2630
|
+
*
|
|
2631
|
+
* @param commands - The sub-commands of a level, by their names
|
|
2632
|
+
* @param word - The word of the command line
|
|
2633
|
+
* @returns The name of the sub-command and the sub-command, or `undefined` when no sub-command is named so
|
|
2634
|
+
*/
|
|
2635
|
+
function findSubCommand(commands, word) {
|
|
2636
|
+
const command = commands.get(word);
|
|
2637
|
+
if (command != null) return [word, command];
|
|
2638
|
+
let found;
|
|
2639
|
+
for (const [name, candidate] of commands) {
|
|
2640
|
+
const aliases = candidate.aliases;
|
|
2641
|
+
if (!Array.isArray(aliases) || !aliases.includes(word)) continue;
|
|
2642
|
+
if (found) throw new TypeError(`Alias '${word}' is given to more than one command: '${found[0]}' and '${name}'`);
|
|
2643
|
+
found = [name, candidate];
|
|
2644
|
+
}
|
|
2645
|
+
return found;
|
|
2646
|
+
}
|
|
2288
2647
|
function normalizeCommandReference(command, name) {
|
|
2289
2648
|
if (typeof command === "function" && command.commandName == null) return Object.assign((...args) => command(...args), command, { commandName: name });
|
|
2290
2649
|
if (typeof command === "object" && command.name == null) return Object.assign(create(), command, { name });
|
|
@@ -2454,7 +2813,13 @@ function createCommandNotFoundError(resolved) {
|
|
|
2454
2813
|
code: CommandNotFoundErrorKeys.notFound,
|
|
2455
2814
|
values: { commandName },
|
|
2456
2815
|
commandName,
|
|
2457
|
-
|
|
2816
|
+
/**
|
|
2817
|
+
* NOTE(kazupon): the candidates are what `@gunshi/plugin-suggestion` offers as "Did you mean". An internal
|
|
2818
|
+
* command is left out of them, as the help, shell completion and the help as JSON leave it out: it still
|
|
2819
|
+
* runs when it is typed, but nothing shows it to the user. So is a deprecated command, whose replacement is
|
|
2820
|
+
* what to offer.
|
|
2821
|
+
*/
|
|
2822
|
+
candidates: [...resolved.parentSubCommands || []].filter(([, command]) => !command.internal && !isDeprecated(command.deprecated)).map(([name]) => name),
|
|
2458
2823
|
commandPath: resolved.parentCommandPath || []
|
|
2459
2824
|
});
|
|
2460
2825
|
}
|
|
@@ -2470,8 +2835,8 @@ function getPluginExtensions(plugins) {
|
|
|
2470
2835
|
}
|
|
2471
2836
|
return extensions;
|
|
2472
2837
|
}
|
|
2473
|
-
async function executeCommand(cmd, ctx, decorators) {
|
|
2474
|
-
const commandRunner = cmd.run ||
|
|
2838
|
+
async function executeCommand(cmd, ctx, decorators, fallbackRunner = NOOP) {
|
|
2839
|
+
const commandRunner = cmd.run || fallbackRunner;
|
|
2475
2840
|
const baseRunner = (ctx) => {
|
|
2476
2841
|
if (hasPriorityValidationError(ctx.validationError)) throw ctx.validationError;
|
|
2477
2842
|
return commandRunner(ctx);
|
|
@@ -2480,7 +2845,7 @@ async function executeCommand(cmd, ctx, decorators) {
|
|
|
2480
2845
|
try {
|
|
2481
2846
|
if (ctx.env.onBeforeCommand) await ctx.env.onBeforeCommand(ctx);
|
|
2482
2847
|
const result = await decoratedRunner(ctx);
|
|
2483
|
-
if (ctx.env.onAfterCommand) await ctx.env.onAfterCommand(ctx, result);
|
|
2848
|
+
if (ctx.env.onAfterCommand) await ctx.env.onAfterCommand(ctx, typeof result === "string" ? result : void 0);
|
|
2484
2849
|
return typeof result === "string" ? result : void 0;
|
|
2485
2850
|
} catch (error) {
|
|
2486
2851
|
if (ctx.env.onErrorCommand) try {
|
|
@@ -2491,14 +2856,14 @@ async function executeCommand(cmd, ctx, decorators) {
|
|
|
2491
2856
|
throw error;
|
|
2492
2857
|
}
|
|
2493
2858
|
}
|
|
2494
|
-
|
|
2495
|
-
//#region ../gunshi/src/cli/bone.ts
|
|
2859
|
+
// ../gunshi/src/cli/bone.ts
|
|
2496
2860
|
/**
|
|
2497
2861
|
* @author kazuya kawaguchi (a.k.a. kazupon)
|
|
2498
2862
|
* @license MIT
|
|
2499
2863
|
*/
|
|
2500
2864
|
/**
|
|
2501
|
-
* Run the command.
|
|
2865
|
+
* Run the command, without the built-in plugins: `--help` and `--version` print nothing, unless you add the plugins.
|
|
2866
|
+
* To have them, use `cli` from `gunshi`.
|
|
2502
2867
|
*
|
|
2503
2868
|
* @typeParam G - A type extending {@linkcode GunshiParams} to specify the shape of command and cli options.
|
|
2504
2869
|
*
|
|
@@ -2510,17 +2875,14 @@ async function executeCommand(cmd, ctx, decorators) {
|
|
|
2510
2875
|
async function cli(args, entry, options = {}) {
|
|
2511
2876
|
return cliCore(args, entry, options, []);
|
|
2512
2877
|
}
|
|
2513
|
-
|
|
2514
|
-
//#region ../gunshi/src/bone.ts
|
|
2878
|
+
// ../gunshi/src/bone.ts
|
|
2515
2879
|
/**
|
|
2516
2880
|
* @author kazuya kawaguchi (a.k.a. kazupon)
|
|
2517
2881
|
* @license MIT
|
|
2518
2882
|
*/
|
|
2519
|
-
|
|
2520
|
-
//#region src/index.ts
|
|
2883
|
+
// src/index.ts
|
|
2521
2884
|
/**
|
|
2522
2885
|
* @author kazuya kawaguchi (a.k.a. kazupon)
|
|
2523
2886
|
* @license MIT
|
|
2524
2887
|
*/
|
|
2525
|
-
//#endregion
|
|
2526
2888
|
export { cli };
|