@gunshi/bone 1.0.0-rc.5 → 1.0.0-rc.7

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.
Files changed (3) hide show
  1. package/lib/index.d.ts +263 -43
  2. package/lib/index.js +501 -246
  3. package/package.json +32 -33
package/lib/index.js CHANGED
@@ -1,4 +1,4 @@
1
- //#region ../../node_modules/.pnpm/args-tokens@1.0.2/node_modules/args-tokens/lib/parser.js
1
+ // ../../node_modules/.pnpm/args-tokens@1.2.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
- //#endregion
204
- //#region ../../node_modules/.pnpm/args-tokens@1.0.2/node_modules/args-tokens/lib/utils.js
203
+ // ../../node_modules/.pnpm/args-tokens@1.2.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
- //#endregion
235
- //#region ../../node_modules/.pnpm/args-tokens@1.0.2/node_modules/args-tokens/lib/resolver-Cx5Pw6-S.js
233
+ // ../../node_modules/.pnpm/args-tokens@1.2.0/node_modules/args-tokens/lib/resolver-DT0CiD5Y.js
236
234
  /**
237
235
  * Internal definitions shared by the modules of `args-tokens`.
238
236
  *
@@ -268,9 +266,11 @@ 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
- * {@link resolveArgs} and `parse()` do not report `unknownOption`. An option that is not in the
269
+ * {@link resolveArgs} and `parse()` do not report `unknownOption` or `unexpectedPositional`: a caller
270
+ * that knows what a command takes, such as a CLI framework, reports them. An option that is not in the
272
271
  * 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.
272
+ * is dropped: with no `foo` in the schema, `--foo bar` gives no positional argument. A positional
273
+ * argument that the schema does not take stays in `positionals`, as the other positional arguments do.
274
274
  */
275
275
  const ArgsValidationErrorKeys = {
276
276
  requiredOption: "err:arg:required-option",
@@ -282,7 +282,8 @@ const ArgsValidationErrorKeys = {
282
282
  unexpectedValue: "err:arg:unexpected-value",
283
283
  missingValue: "err:arg:missing-value",
284
284
  conflict: "err:arg:conflict",
285
- invalidDefault: "err:arg:invalid-default"
285
+ invalidDefault: "err:arg:invalid-default",
286
+ unexpectedPositional: "err:arg:unexpected-positional"
286
287
  };
287
288
  /**
288
289
  * Brand that marks {@link ArgsValidationError} instances.
@@ -1143,8 +1144,7 @@ function checkConflicts(args, explicit, toKebab, actualInputNames) {
1143
1144
  }
1144
1145
  return [];
1145
1146
  }
1146
- //#endregion
1147
- //#region ../../node_modules/.pnpm/args-tokens@1.0.2/node_modules/args-tokens/lib/index.js
1147
+ // ../../node_modules/.pnpm/args-tokens@1.2.0/node_modules/args-tokens/lib/index.js
1148
1148
  /**
1149
1149
  * @author kazuya kawaguchi (a.k.a. kazupon)
1150
1150
  * @license MIT
@@ -1153,8 +1153,7 @@ function checkConflicts(args, explicit, toKebab, actualInputNames) {
1153
1153
  * @author kazuya kawaguchi (a.k.a. kazupon)
1154
1154
  * @license MIT
1155
1155
  */
1156
- //#endregion
1157
- //#region ../gunshi/src/constants.ts
1156
+ // ../gunshi/src/constants.ts
1158
1157
  /**
1159
1158
  * @author kazuya kawaguchi (a.k.a. kazupon)
1160
1159
  * @license MIT
@@ -1176,19 +1175,265 @@ const CLI_OPTIONS_DEFAULT = {
1176
1175
  usageOptionType: false,
1177
1176
  usageOptionValue: true,
1178
1177
  strict: false,
1178
+ strictPositionals: false,
1179
+ helpHint: true,
1180
+ validationErrorExitCode: 1,
1179
1181
  renderHeader: void 0,
1180
1182
  renderUsage: void 0,
1181
1183
  renderValidationErrors: void 0,
1182
1184
  plugins: void 0,
1183
1185
  fallbackToEntry: false
1184
1186
  };
1185
- //#endregion
1186
- //#region ../gunshi/src/utils.ts
1187
+ // ../gunshi/src/error.ts
1187
1188
  /**
1188
1189
  * @author kazuya kawaguchi (a.k.a. kazupon)
1189
1190
  * @license MIT
1190
1191
  */
1191
1192
  /**
1193
+ * Command not found error resource keys.
1194
+ */
1195
+ const CommandNotFoundErrorKeys = { notFound: "err:cmd:not-found" };
1196
+ /**
1197
+ * Command resolution error resource keys.
1198
+ *
1199
+ * These errors describe an ambiguity or inconsistency while choosing a command from arguments.
1200
+ * They are kept separate from {@link CommandNotFoundError} so consumers can distinguish a typo
1201
+ * from an input whose command interpretation is not unique.
1202
+ */
1203
+ const CommandResolutionErrorKeys = {
1204
+ ambiguous: "err:cmd:ambiguous",
1205
+ inconsistentOptions: "err:cmd:inconsistent-options",
1206
+ lazySchemaMismatch: "err:cmd:lazy-schema-mismatch"
1207
+ };
1208
+ /**
1209
+ * Brand that marks {@link CommandNotFoundError} instances.
1210
+ *
1211
+ * The brand is looked up in the global symbol registry with `Symbol.for`, so it stays
1212
+ * identical across bundled copies of gunshi (`gunshi`, `@gunshi/plugin`, `@gunshi/bone`)
1213
+ * and across realms. It lets {@link isCommandNotFoundError} recognize errors created by
1214
+ * another copy, where `instanceof` cannot match.
1215
+ */
1216
+ const COMMAND_NOT_FOUND_ERROR_BRAND = Symbol.for("gunshi.CommandNotFoundError");
1217
+ const COMMAND_RESOLUTION_ERROR_BRAND = Symbol.for("gunshi.CommandResolutionError");
1218
+ /**
1219
+ * Error raised when a command cannot be resolved.
1220
+ *
1221
+ * Each instance carries a non-enumerable brand keyed by
1222
+ * `Symbol.for('gunshi.CommandNotFoundError')`, so that {@link isCommandNotFoundError}
1223
+ * recognizes it even when it was created by another bundled copy of gunshi.
1224
+ */
1225
+ var CommandNotFoundError = class extends Error {
1226
+ code;
1227
+ values;
1228
+ commandName;
1229
+ candidates;
1230
+ commandPath;
1231
+ /**
1232
+ * Create a command-not-found error.
1233
+ *
1234
+ * @param message - Fallback error message
1235
+ * @param options - Command-not-found metadata
1236
+ */
1237
+ constructor(message, options) {
1238
+ super(message, { cause: options.cause });
1239
+ this.name = "CommandNotFoundError";
1240
+ this.code = options.code;
1241
+ this.values = options.values || {};
1242
+ this.commandName = options.commandName;
1243
+ this.candidates = options.candidates || [];
1244
+ this.commandPath = options.commandPath || [];
1245
+ Object.defineProperty(this, COMMAND_NOT_FOUND_ERROR_BRAND, {
1246
+ value: true,
1247
+ enumerable: false,
1248
+ writable: false,
1249
+ configurable: false
1250
+ });
1251
+ }
1252
+ };
1253
+ /**
1254
+ * Error raised when command routing cannot produce one consistent command.
1255
+ *
1256
+ * The own registry brand is the cross-bundle contract. Unlike the legacy command-not-found
1257
+ * guard, the new guard deliberately has no name-based fallback because this error type is new and
1258
+ * must not classify arbitrary errors from older versions.
1259
+ */
1260
+ var CommandResolutionError = class extends Error {
1261
+ code;
1262
+ values;
1263
+ commandPath;
1264
+ candidatePaths;
1265
+ /**
1266
+ * Create a command resolution error with structured routing metadata.
1267
+ *
1268
+ * @param message - Human-readable fallback message
1269
+ * @param options - Error code and command-routing metadata
1270
+ */
1271
+ constructor(message, options = {}) {
1272
+ super(message, { cause: options.cause });
1273
+ this.name = "CommandResolutionError";
1274
+ this.code = options.code;
1275
+ this.values = options.values || {};
1276
+ this.commandPath = options.commandPath || [];
1277
+ this.candidatePaths = options.candidatePaths || [];
1278
+ Object.defineProperty(this, COMMAND_RESOLUTION_ERROR_BRAND, {
1279
+ value: true,
1280
+ enumerable: false,
1281
+ writable: false,
1282
+ configurable: false
1283
+ });
1284
+ }
1285
+ };
1286
+ /**
1287
+ * Check whether an error is a {@link CommandNotFoundError}.
1288
+ *
1289
+ * `instanceof` alone is not enough: `@gunshi/plugin` is bundled with its own copy of this
1290
+ * class (`noExternal: ['gunshi/plugin']`), so an error thrown by `gunshi` is never an instance
1291
+ * of the class a plugin imports. Errors from another copy are recognized through the
1292
+ * `Symbol.for('gunshi.CommandNotFoundError')` brand, which does not depend on `error.name`.
1293
+ *
1294
+ * @param error - An unknown error
1295
+ * @returns `true` if the error is a {@link CommandNotFoundError}
1296
+ */
1297
+ function isCommandNotFoundError(error) {
1298
+ if (error instanceof CommandNotFoundError) return true;
1299
+ if (!isRecord(error) || !hasCommandNotFoundErrorShape(error)) return false;
1300
+ if (Object.hasOwn(error, COMMAND_NOT_FOUND_ERROR_BRAND) && error[COMMAND_NOT_FOUND_ERROR_BRAND] === true) return true;
1301
+ return error instanceof Error && error.name === "CommandNotFoundError";
1302
+ }
1303
+ /**
1304
+ * Check whether an error is a {@link CommandResolutionError}.
1305
+ *
1306
+ * @param error - An unknown error
1307
+ * @returns `true` when the error has the command-resolution brand and shape
1308
+ */
1309
+ function isCommandResolutionError(error) {
1310
+ if (error instanceof CommandResolutionError) return true;
1311
+ if (!isRecord(error) || !hasCommandResolutionErrorShape(error)) return false;
1312
+ return Object.hasOwn(error, COMMAND_RESOLUTION_ERROR_BRAND) && error[COMMAND_RESOLUTION_ERROR_BRAND] === true;
1313
+ }
1314
+ /**
1315
+ * Check whether an error is an {@link ArgsValidationError}.
1316
+ *
1317
+ * Prefer this over the `args-tokens` guard of the same name. Both recognize errors from another
1318
+ * bundled copy through the `Symbol.for('args-tokens.ArgsValidationError')` brand that
1319
+ * `args-tokens` 0.29.0 or later sets, including subclasses such as `ArgResolveError` that
1320
+ * override `name` with the argument name. This guard additionally:
1321
+ *
1322
+ * - recognizes direct `ArgsValidationError` instances from copies bundling `args-tokens`
1323
+ * older than 0.29.0, which do not set the brand
1324
+ * - checks that `code` and `values` of an error from another copy have the expected types
1325
+ *
1326
+ * The guard narrows only to {@link ArgsValidationError}: across copies,
1327
+ * `instanceof ArgResolveError` still fails, so do not rely on `type` or `schema` for such errors.
1328
+ *
1329
+ * @param error - An unknown error
1330
+ * @returns `true` if the error is an {@link ArgsValidationError}
1331
+ */
1332
+ function isArgsValidationError(error) {
1333
+ if (error instanceof ArgsValidationError) return true;
1334
+ if (!isRecord(error) || !hasArgsValidationErrorShape(error)) return false;
1335
+ if (isArgsValidationError$1(error)) return true;
1336
+ return error instanceof Error && error.name === "ArgsValidationError";
1337
+ }
1338
+ function isRecord(value) {
1339
+ return typeof value === "object" && value !== null;
1340
+ }
1341
+ function isStringArray(value) {
1342
+ return Array.isArray(value) && value.every((item) => typeof item === "string");
1343
+ }
1344
+ /**
1345
+ * Check whether `code` is an own or inherited property that is a string or `undefined`.
1346
+ *
1347
+ * Constructors always assign `code`, even when the option is omitted.
1348
+ *
1349
+ * @param error - An error from another copy
1350
+ * @returns `true` if `code` has the expected type
1351
+ */
1352
+ function hasOptionalStringCode(error) {
1353
+ return "code" in error && (error.code === void 0 || typeof error.code === "string");
1354
+ }
1355
+ function hasCommandNotFoundErrorShape(error) {
1356
+ return hasOptionalStringCode(error) && isRecord(error.values) && typeof error.commandName === "string" && isStringArray(error.candidates) && isStringArray(error.commandPath);
1357
+ }
1358
+ function hasCommandResolutionErrorShape(error) {
1359
+ return hasOptionalStringCode(error) && isRecord(error.values) && isStringArray(error.commandPath) && Array.isArray(error.candidatePaths) && error.candidatePaths.every((path) => isStringArray(path));
1360
+ }
1361
+ function hasArgsValidationErrorShape(error) {
1362
+ return hasOptionalStringCode(error) && isRecord(error.values);
1363
+ }
1364
+ /**
1365
+ * Check whether a value is an exit code of a failure: an integer from 1 to 255.
1366
+ *
1367
+ * @param value - The value to check
1368
+ * @returns `true` if the value is an exit code of a failure
1369
+ */
1370
+ function isFailureExitCode(value) {
1371
+ return Number.isInteger(value) && value >= 1 && value <= 255;
1372
+ }
1373
+ /**
1374
+ * Check whether validation errors must stop the command before it runs: an unknown command, a command
1375
+ * line that cannot be resolved, an unknown option of `strict`, or a positional argument that the command
1376
+ * does not take, of `strictPositionals`. The global options plugin reports them before `--help` and
1377
+ * `--version`, except an unknown option and a positional argument that the command does not take:
1378
+ * `--help` and `--version` are answered before them, as they are before the other validation errors.
1379
+ *
1380
+ * @param error - An aggregate validation error
1381
+ * @returns `true` if the validation error must be handled with priority
1382
+ */
1383
+ function hasPriorityValidationError(error) {
1384
+ return error?.errors.some((error) => isCommandNotFoundError(error) || isCommandResolutionError(error) || isArgsValidationError(error) && (error.code === ArgsValidationErrorKeys.unknownOption || error.code === ArgsValidationErrorKeys.unexpectedPositional)) ?? false;
1385
+ }
1386
+ // ../gunshi/src/utils.ts
1387
+ /**
1388
+ * @author kazuya kawaguchi (a.k.a. kazupon)
1389
+ * @license MIT
1390
+ */
1391
+ /**
1392
+ * Check whether an argument schema is the `json` argument of `jsonArgs`, by its mark.
1393
+ *
1394
+ * @param schema - An argument schema
1395
+ * @returns `true` if the schema has the mark of `jsonArgs`
1396
+ */
1397
+ function isJsonArg(schema) {
1398
+ return typeof schema === "object" && schema !== null && schema["~gunshi.json-arg"] === true;
1399
+ }
1400
+ /**
1401
+ * Resolve whether `--json` asks a command for JSON.
1402
+ *
1403
+ * A command that spreads `jsonArgs` is asked for JSON when the resolved value of its `json` is `true`:
1404
+ * with `--json`, or with a short name that the command gives it, but not with `--json=false`, nor with
1405
+ * `--json` after `--`. The raw tokens are read only when they are given, and only when there is no
1406
+ * value to read: when the command has no `json` argument, and when the core could not resolve the
1407
+ * command and left the values empty. A `json` argument without the mark belongs to the command, and
1408
+ * `--json` is never taken for a request then.
1409
+ *
1410
+ * @param args - The arguments of the command, the global options included
1411
+ * @param values - The resolved values of the arguments
1412
+ * @param tokens - The raw tokens of the arguments, to find a `--json` that no argument declares
1413
+ * @returns How the command is asked for JSON, or `undefined` when it is not
1414
+ */
1415
+ function resolveJsonRequest(args, values, tokens) {
1416
+ const schema = Object.hasOwn(args, "json") ? args.json : void 0;
1417
+ if (schema === void 0) return tokens !== void 0 && hasJsonOption(tokens) ? "undeclared" : void 0;
1418
+ if (!isJsonArg(schema)) return;
1419
+ if (values.json !== void 0) return values.json === true ? "declared" : void 0;
1420
+ return tokens !== void 0 && hasJsonOption(tokens) ? "declared" : void 0;
1421
+ }
1422
+ /**
1423
+ * Check whether the raw tokens have a `--json` that asks for JSON: `--json` or `--json=true`, before
1424
+ * `--`. Without a declaration, a short name of `--json` is not known.
1425
+ *
1426
+ * @param tokens - The raw tokens of the arguments
1427
+ * @returns `true` if a `--json` asks for JSON
1428
+ */
1429
+ function hasJsonOption(tokens) {
1430
+ for (const token of tokens) {
1431
+ if (token.kind === "option-terminator") return false;
1432
+ if (token.kind === "option" && token.rawName === "--json" && (token.value === void 0 || token.value === "true")) return true;
1433
+ }
1434
+ return false;
1435
+ }
1436
+ /**
1192
1437
  * Check if the given command is a {@link LazyCommand}.
1193
1438
  *
1194
1439
  * @param cmd - A command to check
@@ -1205,6 +1450,8 @@ function isLazyCommand(cmd) {
1205
1450
  *
1206
1451
  * If the loader returns a command, the properties of the loaded command take precedence,
1207
1452
  * and the properties that it does not define fall back to the definition that is given to `lazy`.
1453
+ * `run` comes from the loader only, as the definition has none. A loaded command without `run` is resolved
1454
+ * without it, as any command without `run`, which the CLI fails with when it runs, unless it has sub-commands.
1208
1455
  *
1209
1456
  * @param cmd - A {@link Commandable} or {@link LazyCommand} to resolve
1210
1457
  * @param name - Optional name of the command, if not provided, it will use the name from the command itself.
@@ -1220,6 +1467,8 @@ async function resolveLazyCommand(cmd, name, needRunResolving = false) {
1220
1467
  args: cmd.args,
1221
1468
  examples: cmd.examples,
1222
1469
  internal: cmd.internal,
1470
+ aliases: cmd.aliases,
1471
+ deprecated: cmd.deprecated,
1223
1472
  entry: cmd.entry,
1224
1473
  toKebab: cmd.toKebab,
1225
1474
  rendering: cmd.rendering,
@@ -1228,14 +1477,20 @@ async function resolveLazyCommand(cmd, name, needRunResolving = false) {
1228
1477
  if ("resource" in cmd && cmd.resource) baseCommand.resource = cmd.resource;
1229
1478
  command = Object.assign(create(), baseCommand);
1230
1479
  if (needRunResolving) {
1480
+ /**
1481
+ * NOTE(kazupon): the error names the command, by its `commandName` or the name that it is given with.
1482
+ * The lazy command is the loader function, so its `name` is the name of the function, such as
1483
+ * `buildLoader` of a loader in a const.
1484
+ */
1485
+ const commandName = cmd.commandName || name || "(anonymous)";
1231
1486
  const loaded = await cmd();
1232
1487
  if (typeof loaded === "function") command.run = loaded;
1233
- else if (typeof loaded === "object") {
1234
- if (loaded.run == null) throw new TypeError(`'run' is required in command: ${cmd.name || name}`);
1488
+ else if (typeof loaded === "object" && loaded !== null) {
1235
1489
  /**
1236
1490
  * NOTE(kazupon): the loaded command wins, and the definition that is given to `lazy` is the fallback
1237
1491
  * for what the loaded command does not define. A loader that returns `{ run }` keeps the whole definition,
1238
- * like a loader that returns the runner itself.
1492
+ * like a loader that returns the runner itself. A loaded command without `run` is a command without `run`
1493
+ * (#885): the CLI fails with it where it would run, as with any other, or prints the usage of a group.
1239
1494
  */
1240
1495
  command.run = loaded.run;
1241
1496
  command.name = loaded.name ?? cmd.commandName;
@@ -1243,12 +1498,19 @@ async function resolveLazyCommand(cmd, name, needRunResolving = false) {
1243
1498
  command.args = loaded.args ?? cmd.args;
1244
1499
  command.examples = loaded.examples ?? cmd.examples;
1245
1500
  command.internal = loaded.internal ?? cmd.internal;
1501
+ command.aliases = loaded.aliases ?? cmd.aliases;
1502
+ command.deprecated = loaded.deprecated ?? cmd.deprecated;
1246
1503
  command.entry = loaded.entry ?? cmd.entry;
1247
1504
  command.toKebab = loaded.toKebab ?? cmd.toKebab;
1248
1505
  command.rendering = loaded.rendering ?? cmd.rendering;
1249
1506
  command.subCommands = loaded.subCommands || cmd.subCommands;
1250
1507
  if ("resource" in loaded && loaded.resource) command.resource = loaded.resource;
1251
- } else throw new TypeError(`Cannot resolve command: ${cmd.name || name}`);
1508
+ } else
1509
+ /**
1510
+ * NOTE(kazupon): `null` comes here too, though `typeof null` is `'object'` (#883): a loader may return it
1511
+ * for a module that is not found, and it is neither a command nor a runner, as `undefined` is not.
1512
+ */
1513
+ throw new TypeError(`Cannot resolve command: ${commandName}`);
1252
1514
  }
1253
1515
  } else command = Object.assign(create(), cmd);
1254
1516
  if (command.name == null && name) command.name = name;
@@ -1319,8 +1581,7 @@ function deepFreeze(obj, ignores = []) {
1319
1581
  }
1320
1582
  return Object.freeze(obj);
1321
1583
  }
1322
- //#endregion
1323
- //#region ../gunshi/src/context.ts
1584
+ // ../gunshi/src/context.ts
1324
1585
  /**
1325
1586
  * The entry for gunshi context.
1326
1587
  * This module is exported for the purpose of testing the command.
@@ -1355,6 +1616,11 @@ async function createCommandContext({ args = {}, explicit = {}, values = {}, pos
1355
1616
  */
1356
1617
  const env = Object.assign(create(), CLI_OPTIONS_DEFAULT, cliOptions);
1357
1618
  /**
1619
+ * NOTE(kazupon): the exit code of the validation errors is an exit code of a failure, as the `exitCode`
1620
+ * of a `CommandError` is: any other value is replaced with `1`.
1621
+ */
1622
+ if (!isFailureExitCode(env.validationErrorExitCode)) env.validationErrorExitCode = 1;
1623
+ /**
1358
1624
  * apply Command definition's rendering option with highest priority
1359
1625
  */
1360
1626
  if (command.rendering) {
@@ -1366,6 +1632,14 @@ async function createCommandContext({ args = {}, explicit = {}, values = {}, pos
1366
1632
  /**
1367
1633
  * create the command context
1368
1634
  */
1635
+ /**
1636
+ * NOTE(kazupon): a command that spreads `jsonArgs` and is asked for JSON prints its result as JSON, so
1637
+ * the human output of `ctx.log` is silenced, as it is with `usageSilent`. The hooks and the decorators
1638
+ * get the same context, so their `ctx.log` is silenced too. Only the resolved value of the `json`
1639
+ * argument counts here, not the raw tokens: a command that does not support `--json` keeps its output,
1640
+ * and the global options plugin reports the `--json` given to it.
1641
+ */
1642
+ const silent = cliOptions.usageSilent || resolveJsonRequest(_args, values) === "declared";
1369
1643
  const core = Object.assign(create(), {
1370
1644
  name: getCommandName(command),
1371
1645
  description: command.description,
@@ -1381,7 +1655,7 @@ async function createCommandContext({ args = {}, explicit = {}, values = {}, pos
1381
1655
  _: argv,
1382
1656
  tokens,
1383
1657
  toKebab: command.toKebab,
1384
- log: cliOptions.usageSilent ? NOOP : log,
1658
+ log: silent ? NOOP : log,
1385
1659
  validationError
1386
1660
  });
1387
1661
  /**
@@ -1407,8 +1681,7 @@ function getCommandName(cmd) {
1407
1681
  else if (typeof cmd === "object") return cmd.name || "(anonymous)";
1408
1682
  else return ANONYMOUS_COMMAND_NAME;
1409
1683
  }
1410
- //#endregion
1411
- //#region ../gunshi/src/decorators.ts
1684
+ // ../gunshi/src/decorators.ts
1412
1685
  /**
1413
1686
  * @author kazuya kawaguchi (a.k.a. kazupon)
1414
1687
  * @license MIT
@@ -1475,195 +1748,7 @@ function createDecorators() {
1475
1748
  }
1476
1749
  });
1477
1750
  }
1478
- //#endregion
1479
- //#region ../gunshi/src/error.ts
1480
- /**
1481
- * @author kazuya kawaguchi (a.k.a. kazupon)
1482
- * @license MIT
1483
- */
1484
- /**
1485
- * Command not found error resource keys.
1486
- */
1487
- const CommandNotFoundErrorKeys = { notFound: "err:cmd:not-found" };
1488
- /**
1489
- * Command resolution error resource keys.
1490
- *
1491
- * These errors describe an ambiguity or inconsistency while choosing a command from arguments.
1492
- * They are kept separate from {@link CommandNotFoundError} so consumers can distinguish a typo
1493
- * from an input whose command interpretation is not unique.
1494
- */
1495
- const CommandResolutionErrorKeys = {
1496
- ambiguous: "err:cmd:ambiguous",
1497
- inconsistentOptions: "err:cmd:inconsistent-options",
1498
- lazySchemaMismatch: "err:cmd:lazy-schema-mismatch"
1499
- };
1500
- /**
1501
- * Brand that marks {@link CommandNotFoundError} instances.
1502
- *
1503
- * The brand is looked up in the global symbol registry with `Symbol.for`, so it stays
1504
- * identical across bundled copies of gunshi (`gunshi`, `@gunshi/plugin`, `@gunshi/bone`)
1505
- * and across realms. It lets {@link isCommandNotFoundError} recognize errors created by
1506
- * another copy, where `instanceof` cannot match.
1507
- */
1508
- const COMMAND_NOT_FOUND_ERROR_BRAND = Symbol.for("gunshi.CommandNotFoundError");
1509
- const COMMAND_RESOLUTION_ERROR_BRAND = Symbol.for("gunshi.CommandResolutionError");
1510
- /**
1511
- * Error raised when a command cannot be resolved.
1512
- *
1513
- * Each instance carries a non-enumerable brand keyed by
1514
- * `Symbol.for('gunshi.CommandNotFoundError')`, so that {@link isCommandNotFoundError}
1515
- * recognizes it even when it was created by another bundled copy of gunshi.
1516
- */
1517
- var CommandNotFoundError = class extends Error {
1518
- code;
1519
- values;
1520
- commandName;
1521
- candidates;
1522
- commandPath;
1523
- /**
1524
- * Create a command-not-found error.
1525
- *
1526
- * @param message - Fallback error message
1527
- * @param options - Command-not-found metadata
1528
- */
1529
- constructor(message, options) {
1530
- super(message, { cause: options.cause });
1531
- this.name = "CommandNotFoundError";
1532
- this.code = options.code;
1533
- this.values = options.values || {};
1534
- this.commandName = options.commandName;
1535
- this.candidates = options.candidates || [];
1536
- this.commandPath = options.commandPath || [];
1537
- Object.defineProperty(this, COMMAND_NOT_FOUND_ERROR_BRAND, {
1538
- value: true,
1539
- enumerable: false,
1540
- writable: false,
1541
- configurable: false
1542
- });
1543
- }
1544
- };
1545
- /**
1546
- * Error raised when command routing cannot produce one consistent command.
1547
- *
1548
- * The own registry brand is the cross-bundle contract. Unlike the legacy command-not-found
1549
- * guard, the new guard deliberately has no name-based fallback because this error type is new and
1550
- * must not classify arbitrary errors from older versions.
1551
- */
1552
- var CommandResolutionError = class extends Error {
1553
- code;
1554
- values;
1555
- commandPath;
1556
- candidatePaths;
1557
- /**
1558
- * Create a command resolution error with structured routing metadata.
1559
- *
1560
- * @param message - Human-readable fallback message
1561
- * @param options - Error code and command-routing metadata
1562
- */
1563
- constructor(message, options = {}) {
1564
- super(message, { cause: options.cause });
1565
- this.name = "CommandResolutionError";
1566
- this.code = options.code;
1567
- this.values = options.values || {};
1568
- this.commandPath = options.commandPath || [];
1569
- this.candidatePaths = options.candidatePaths || [];
1570
- Object.defineProperty(this, COMMAND_RESOLUTION_ERROR_BRAND, {
1571
- value: true,
1572
- enumerable: false,
1573
- writable: false,
1574
- configurable: false
1575
- });
1576
- }
1577
- };
1578
- /**
1579
- * Check whether an error is a {@link CommandNotFoundError}.
1580
- *
1581
- * `instanceof` alone is not enough: `@gunshi/plugin` is bundled with its own copy of this
1582
- * class (`noExternal: ['gunshi/plugin']`), so an error thrown by `gunshi` is never an instance
1583
- * of the class a plugin imports. Errors from another copy are recognized through the
1584
- * `Symbol.for('gunshi.CommandNotFoundError')` brand, which does not depend on `error.name`.
1585
- *
1586
- * @param error - An unknown error
1587
- * @returns `true` if the error is a {@link CommandNotFoundError}
1588
- */
1589
- function isCommandNotFoundError(error) {
1590
- if (error instanceof CommandNotFoundError) return true;
1591
- if (!isRecord(error) || !hasCommandNotFoundErrorShape(error)) return false;
1592
- if (Object.hasOwn(error, COMMAND_NOT_FOUND_ERROR_BRAND) && error[COMMAND_NOT_FOUND_ERROR_BRAND] === true) return true;
1593
- return error instanceof Error && error.name === "CommandNotFoundError";
1594
- }
1595
- /**
1596
- * Check whether an error is a {@link CommandResolutionError}.
1597
- *
1598
- * @param error - An unknown error
1599
- * @returns `true` when the error has the command-resolution brand and shape
1600
- */
1601
- function isCommandResolutionError(error) {
1602
- if (error instanceof CommandResolutionError) return true;
1603
- if (!isRecord(error) || !hasCommandResolutionErrorShape(error)) return false;
1604
- return Object.hasOwn(error, COMMAND_RESOLUTION_ERROR_BRAND) && error[COMMAND_RESOLUTION_ERROR_BRAND] === true;
1605
- }
1606
- /**
1607
- * Check whether an error is an {@link ArgsValidationError}.
1608
- *
1609
- * Prefer this over the `args-tokens` guard of the same name. Both recognize errors from another
1610
- * bundled copy through the `Symbol.for('args-tokens.ArgsValidationError')` brand that
1611
- * `args-tokens` 0.29.0 or later sets, including subclasses such as `ArgResolveError` that
1612
- * override `name` with the argument name. This guard additionally:
1613
- *
1614
- * - recognizes direct `ArgsValidationError` instances from copies bundling `args-tokens`
1615
- * older than 0.29.0, which do not set the brand
1616
- * - checks that `code` and `values` of an error from another copy have the expected types
1617
- *
1618
- * The guard narrows only to {@link ArgsValidationError}: across copies,
1619
- * `instanceof ArgResolveError` still fails, so do not rely on `type` or `schema` for such errors.
1620
- *
1621
- * @param error - An unknown error
1622
- * @returns `true` if the error is an {@link ArgsValidationError}
1623
- */
1624
- function isArgsValidationError(error) {
1625
- if (error instanceof ArgsValidationError) return true;
1626
- if (!isRecord(error) || !hasArgsValidationErrorShape(error)) return false;
1627
- if (isArgsValidationError$1(error)) return true;
1628
- return error instanceof Error && error.name === "ArgsValidationError";
1629
- }
1630
- function isRecord(value) {
1631
- return typeof value === "object" && value !== null;
1632
- }
1633
- function isStringArray(value) {
1634
- return Array.isArray(value) && value.every((item) => typeof item === "string");
1635
- }
1636
- /**
1637
- * Check whether `code` is an own or inherited property that is a string or `undefined`.
1638
- *
1639
- * Constructors always assign `code`, even when the option is omitted.
1640
- *
1641
- * @param error - An error from another copy
1642
- * @returns `true` if `code` has the expected type
1643
- */
1644
- function hasOptionalStringCode(error) {
1645
- return "code" in error && (error.code === void 0 || typeof error.code === "string");
1646
- }
1647
- function hasCommandNotFoundErrorShape(error) {
1648
- return hasOptionalStringCode(error) && isRecord(error.values) && typeof error.commandName === "string" && isStringArray(error.candidates) && isStringArray(error.commandPath);
1649
- }
1650
- function hasCommandResolutionErrorShape(error) {
1651
- return hasOptionalStringCode(error) && isRecord(error.values) && isStringArray(error.commandPath) && Array.isArray(error.candidatePaths) && error.candidatePaths.every((path) => isStringArray(path));
1652
- }
1653
- function hasArgsValidationErrorShape(error) {
1654
- return hasOptionalStringCode(error) && isRecord(error.values);
1655
- }
1656
- /**
1657
- * Check whether validation errors should be handled before version, help, or command execution.
1658
- *
1659
- * @param error - An aggregate validation error
1660
- * @returns `true` if the validation error must be handled with priority
1661
- */
1662
- function hasPriorityValidationError(error) {
1663
- return error?.errors.some((error) => isCommandNotFoundError(error) || isCommandResolutionError(error) || isArgsValidationError(error) && error.code === ArgsValidationErrorKeys.unknownOption) ?? false;
1664
- }
1665
- //#endregion
1666
- //#region ../gunshi/src/plugin/context.ts
1751
+ // ../gunshi/src/plugin/context.ts
1667
1752
  /**
1668
1753
  * @author kazuya kawaguchi (a.k.a. kazupon)
1669
1754
  * @license MIT
@@ -1746,8 +1831,7 @@ function createPluginContext(decorators, initialSubCommands) {
1746
1831
  function findGlobalOptionByShort(globalOptions, short) {
1747
1832
  for (const [name, schema] of globalOptions) if (schema.short === short) return name;
1748
1833
  }
1749
- //#endregion
1750
- //#region ../gunshi/src/plugin/dependency.ts
1834
+ // ../gunshi/src/plugin/dependency.ts
1751
1835
  /**
1752
1836
  * @author kazuya kawaguchi (a.k.a. kazupon)
1753
1837
  * @license MIT
@@ -1788,8 +1872,7 @@ function resolveDependencies(plugins) {
1788
1872
  for (const plugin of plugins) visit(plugin);
1789
1873
  return sorted;
1790
1874
  }
1791
- //#endregion
1792
- //#region ../gunshi/src/cli/args.ts
1875
+ // ../gunshi/src/cli/args.ts
1793
1876
  /**
1794
1877
  * @author kazuya kawaguchi (a.k.a. kazupon)
1795
1878
  * @license MIT
@@ -1829,8 +1912,7 @@ function resolveGlobalOptions(globalOptions, args) {
1829
1912
  } : schema;
1830
1913
  return resolved;
1831
1914
  }
1832
- //#endregion
1833
- //#region ../gunshi/src/cli/core.ts
1915
+ // ../gunshi/src/cli/core.ts
1834
1916
  /**
1835
1917
  * @author kazuya kawaguchi (a.k.a. kazupon)
1836
1918
  * @license MIT
@@ -1863,8 +1945,11 @@ async function cliCore(argv, entry, options, plugins, usageOnly = false) {
1863
1945
  * NOTE(kazupon): a CLI whose user declares no sub-commands has no command tree of its own,
1864
1946
  * so a positional argument must not become a command name just because a plugin added a command.
1865
1947
  * The user can still opt out with an explicit `fallbackToEntry: false`.
1948
+ * An entry command without `run` has nothing to run with the argument: the commands that the plugins
1949
+ * add are the commands of the CLI, so an argument that is not one of them is reported, as when the
1950
+ * user declares them (#874). A lazy entry command and a runner given to `cli()` have something to run.
1866
1951
  */
1867
- if (initialSubCommands.size === 0 && cliOptions.subCommands.size > 0 && options.fallbackToEntry === void 0) cliOptions.fallbackToEntry = true;
1952
+ if (initialSubCommands.size === 0 && cliOptions.subCommands.size > 0 && options.fallbackToEntry === void 0 && (typeof entry === "function" || entry.run != null)) cliOptions.fallbackToEntry = true;
1868
1953
  const tokens = parseArgs(argv);
1869
1954
  const selection = resolveCommandSelection(tokens, entry, cliOptions, pluginContext.globalOptions);
1870
1955
  const resolved = selection.context;
@@ -1890,8 +1975,24 @@ async function cliCore(argv, entry, options, plugins, usageOnly = false) {
1890
1975
  }
1891
1976
  const routingOptions = Object.assign(create(), cliOptions, { subCommands: new Map(cliOptions.subCommands) });
1892
1977
  if (targetLevelSubCommands) cliOptions.subCommands = targetLevelSubCommands;
1893
- const resolvedCommand = isLazyCommand(targetCommand) ? await resolveLazyCommand(targetCommand, targetCommandName, true) : targetCommand;
1894
- if (selection.error == null && isLazyCommand(targetCommand)) {
1978
+ /**
1979
+ * NOTE(kazupon): a lazy command is loaded before the arguments are parsed, so that the arguments of the
1980
+ * loaded command are used. An error of the loading, such as one that the loader throws, is thrown where the
1981
+ * command would run, after the decorators, as an error of `run` is (#885): the global options plugin prints a
1982
+ * `CommandError` with its exit code, and the failure as JSON with `--json`, and `onErrorCommand` sees it.
1983
+ * Until then, the definition given to `lazy` stands for the command, so that its arguments are parsed, and
1984
+ * `--help` prints its usage.
1985
+ */
1986
+ let resolvedCommand;
1987
+ let loadFailure;
1988
+ if (isLazyCommand(targetCommand)) try {
1989
+ resolvedCommand = await resolveLazyCommand(targetCommand, targetCommandName, true);
1990
+ } catch (error) {
1991
+ loadFailure = { error };
1992
+ resolvedCommand = await resolveLazyCommand(targetCommand, targetCommandName);
1993
+ }
1994
+ else resolvedCommand = targetCommand;
1995
+ if (selection.error == null && isLazyCommand(targetCommand) && loadFailure === void 0) {
1895
1996
  const loaded = resolveCommandTreeFromPositionals(getRoutingPositionals(tokens, pluginContext.globalOptions, resolvedCommand), entry, routingOptions);
1896
1997
  if (!sameCommandPath(loaded.commandPath, targetCommandPath)) additionalValidationErrors.push(createLazySchemaMismatchError(targetCommandPath, loaded.commandPath));
1897
1998
  }
@@ -1915,7 +2016,11 @@ async function cliCore(argv, entry, options, plugins, usageOnly = false) {
1915
2016
  toKebab: resolvedCommand.toKebab,
1916
2017
  skipPositional
1917
2018
  });
1918
- const validationError = mergeValidationErrors(error, [...additionalValidationErrors, ...cliOptions.strict && !diagnostic ? createUnknownOptionErrors(findUnknownOptions(args, tokens, { toKebab: resolvedCommand.toKebab })) : []]);
2019
+ const validationError = mergeValidationErrors(error, [
2020
+ ...additionalValidationErrors,
2021
+ ...cliOptions.strict && !diagnostic ? createUnknownOptionErrors(findUnknownOptions(args, tokens, { toKebab: resolvedCommand.toKebab })) : [],
2022
+ ...cliOptions.strictPositionals && !diagnostic && additionalValidationErrors.length === 0 ? createUnexpectedPositionalErrors(findUnexpectedPositionals(args, positionals, skipPositional)) : []
2023
+ ]);
1919
2024
  const commandContext = await createCommandContext({
1920
2025
  args,
1921
2026
  explicit,
@@ -1932,9 +2037,25 @@ async function cliCore(argv, entry, options, plugins, usageOnly = false) {
1932
2037
  validationError,
1933
2038
  cliOptions
1934
2039
  });
2040
+ markDeprecatedCommands(commandContext, collectDeprecatedCommands(routingOptions.subCommands, targetCommandPath, resolvedCommand));
1935
2041
  const reported = trackReported(commandContext);
2042
+ let fallbackRunner = NOOP;
2043
+ if (loadFailure !== void 0) {
2044
+ const { error } = loadFailure;
2045
+ fallbackRunner = () => {
2046
+ throw error;
2047
+ };
2048
+ } else if (resolvedCommand.run == null) {
2049
+ markWithoutRun(commandContext);
2050
+ if (!(targetDepth === 0 ? routingOptions.subCommands.size > 0 : (getCommandSubCommands(resolvedCommand)?.size ?? 0) > 0)) {
2051
+ const commandName = resolvedCommand.name || targetCommandName || "(anonymous)";
2052
+ fallbackRunner = () => {
2053
+ throw new TypeError(`'run' is required in command: ${commandName}`);
2054
+ };
2055
+ }
2056
+ }
1936
2057
  try {
1937
- return await executeCommand(resolvedCommand, commandContext, decorators.commandDecorators);
2058
+ return await executeCommand(resolvedCommand, commandContext, decorators.commandDecorators, fallbackRunner);
1938
2059
  } catch (error) {
1939
2060
  /**
1940
2061
  * NOTE(kazupon): a plugin that has reported the validation errors to the user marks them, as the
@@ -1968,6 +2089,87 @@ function trackReported(ctx) {
1968
2089
  return reported;
1969
2090
  }
1970
2091
  /**
2092
+ * The key of the registry of the command contexts whose command has no `run`. The global options plugin
2093
+ * and the usage renderer plugin read it with `isWithoutRun` of `@gunshi/shared`, by the same registered
2094
+ * symbol, since `gunshi` and the plugins bundle their own copies. Neither is in the public API.
2095
+ */
2096
+ const WITHOUT_RUN = Symbol.for("gunshi.withoutRun");
2097
+ /**
2098
+ * Mark the command context of a run whose command has no `run`.
2099
+ *
2100
+ * NOTE(kazupon): the global options plugin prints the usage of a command that has sub-commands and no
2101
+ * `run`, when it runs without a sub-command, as `--help` does. The plugin cannot tell it from the context,
2102
+ * nor from the runner that it decorates, which the core always wraps, so the core tells it. The command
2103
+ * is checked once it is loaded, so a lazy command whose loader returns a command without `run` is marked
2104
+ * too. The registry is weak, and holds the context of this run only: a nested `cli()` in a hook has a
2105
+ * context of its own.
2106
+ *
2107
+ * @param ctx - The command context of the run
2108
+ */
2109
+ function markWithoutRun(ctx) {
2110
+ const registry = globalThis;
2111
+ (registry[WITHOUT_RUN] ??= /* @__PURE__ */ new WeakSet()).add(ctx);
2112
+ }
2113
+ /**
2114
+ * The key of the registry of the deprecated commands on the path of a run. The global options plugin and the
2115
+ * usage renderer plugin read it with `getDeprecatedCommands` of `@gunshi/shared`, by the same registered
2116
+ * symbol, since `gunshi` and the plugins bundle their own copies. Neither is in the public API.
2117
+ */
2118
+ const DEPRECATED_COMMANDS = Symbol.for("gunshi.deprecatedCommands");
2119
+ /**
2120
+ * Check whether the `deprecated` of a command or an argument marks it as deprecated.
2121
+ *
2122
+ * @param deprecated - The `deprecated` of a command or an argument
2123
+ * @returns `true` for `true` or a text
2124
+ */
2125
+ function isDeprecated(deprecated) {
2126
+ return deprecated === true || typeof deprecated === "string";
2127
+ }
2128
+ /**
2129
+ * Collect the deprecated commands on the path of a run, root first.
2130
+ *
2131
+ * NOTE(kazupon): the command that runs is the loaded one, whose `deprecated` wins over the one of the definition
2132
+ * given to `lazy`. The commands above it are the definitions of the tree, as the routing found them. The entry
2133
+ * command is not on the path.
2134
+ *
2135
+ * @param root - The sub-commands at the top level
2136
+ * @param commandPath - The names of the commands on the path
2137
+ * @param resolvedCommand - The command that runs
2138
+ * @returns The deprecated commands, with their paths
2139
+ */
2140
+ function collectDeprecatedCommands(root, commandPath, resolvedCommand) {
2141
+ const marks = [];
2142
+ let level = root;
2143
+ for (const [index, name] of commandPath.entries()) {
2144
+ const last = index === commandPath.length - 1;
2145
+ const declared = level?.get(name);
2146
+ const command = last ? resolvedCommand : declared;
2147
+ if (command == null) break;
2148
+ if (isDeprecated(command.deprecated)) marks.push({
2149
+ commandPath: commandPath.slice(0, index + 1),
2150
+ deprecated: command.deprecated
2151
+ });
2152
+ level = declared == null ? void 0 : getCommandSubCommands(declared);
2153
+ }
2154
+ return marks;
2155
+ }
2156
+ /**
2157
+ * Mark the command context of a run with the deprecated commands on its path.
2158
+ *
2159
+ * NOTE(kazupon): the context has the command that runs, and not the commands above it, such as the old name of a
2160
+ * renamed group, so the core, which walks the path, tells the plugins which of them are deprecated. The global
2161
+ * options plugin warns of them, and the usage renderer plugin says so in the help. The registry is weak, and
2162
+ * holds the context of this run only.
2163
+ *
2164
+ * @param ctx - The command context of the run
2165
+ * @param marks - The deprecated commands on the path
2166
+ */
2167
+ function markDeprecatedCommands(ctx, marks) {
2168
+ if (marks.length === 0) return;
2169
+ const registry = globalThis;
2170
+ (registry[DEPRECATED_COMMANDS] ??= /* @__PURE__ */ new WeakMap()).set(ctx, marks);
2171
+ }
2172
+ /**
1971
2173
  * Create the decorator that renders the usage of the command instead of running it.
1972
2174
  *
1973
2175
  * NOTE(kazupon): `generate()` of `gunshi/generator` asks the core for a usage. It used to ask by
@@ -2055,14 +2257,16 @@ function findUnknownOptions(args, tokens, options) {
2055
2257
  knownLongOptions.add(optionName);
2056
2258
  /**
2057
2259
  * NOTE(kazupon): a hidden option is still accepted, so it stays a known option. It is left out
2058
- * of the candidates, which are what `@gunshi/plugin-suggestion` offers as "Did you mean".
2260
+ * of the candidates, which are what `@gunshi/plugin-suggestion` offers as "Did you mean". So is a
2261
+ * deprecated option, which the help leaves out too, and so is the negated form of either.
2059
2262
  */
2060
- if (!schema.hidden) addLongOptionCandidate(optionName);
2263
+ const offered = !schema.hidden && !isDeprecated(schema.deprecated);
2264
+ if (offered) addLongOptionCandidate(optionName);
2061
2265
  if (schema.short) knownShortOptions.add(schema.short);
2062
2266
  if (schema.type === "boolean" && schema.negatable) {
2063
2267
  const negatableOptionName = `${NEGATABLE_OPTION_PREFIX}${optionName}`;
2064
2268
  knownNegatableOptions.add(negatableOptionName);
2065
- if (!schema.hidden) addLongOptionCandidate(negatableOptionName);
2269
+ if (offered) addLongOptionCandidate(negatableOptionName);
2066
2270
  }
2067
2271
  }
2068
2272
  const unknownOptions = [];
@@ -2096,6 +2300,30 @@ function createUnknownOptionErrors(unknownOptions) {
2096
2300
  });
2097
2301
  });
2098
2302
  }
2303
+ /**
2304
+ * Find the positional arguments that the command does not take: the ones after its command path that its
2305
+ * positional arguments do not take. A positional argument with `multiple` takes all of them.
2306
+ *
2307
+ * NOTE(kazupon): args-tokens gives the positional arguments after the command path to the positional
2308
+ * arguments of the command in the order they are declared, so the declared ones take the first of them,
2309
+ * as many as they are, an optional one included, and the rest are left over.
2310
+ *
2311
+ * @param args - The arguments of the command
2312
+ * @param positionals - The positional arguments, the command path included
2313
+ * @param skipPositional - The index of the last command name in `positionals`
2314
+ * @returns The positional arguments that are left over
2315
+ */
2316
+ function findUnexpectedPositionals(args, positionals, skipPositional) {
2317
+ const declared = Object.values(args).filter((schema) => schema.type === "positional");
2318
+ if (declared.some((schema) => schema.multiple)) return [];
2319
+ return positionals.slice(skipPositional + 1 + declared.length);
2320
+ }
2321
+ function createUnexpectedPositionalErrors(positionals) {
2322
+ return positionals.map((rawName) => new ArgsValidationError(`Unexpected positional argument: ${rawName}`, {
2323
+ code: ArgsValidationErrorKeys.unexpectedPositional,
2324
+ values: { rawName }
2325
+ }));
2326
+ }
2099
2327
  function mergeValidationErrors(error, additionalErrors) {
2100
2328
  if (additionalErrors.length === 0) return error;
2101
2329
  return new AggregateError(error ? [...error.errors, ...additionalErrors] : additionalErrors, error?.message || additionalErrors[0]?.message);
@@ -2200,8 +2428,8 @@ function resolveCommandTreeFromPositionals(positionals, entry, options) {
2200
2428
  let depth = 0;
2201
2429
  for (let i = 0; i < positionals.length; i++) {
2202
2430
  const token = positionals[i];
2203
- const cmd = currentSubCommands.get(token);
2204
- if (cmd == null) {
2431
+ const found = findSubCommand(currentSubCommands, token);
2432
+ if (found == null) {
2205
2433
  if (depth === 0) {
2206
2434
  if (options.fallbackToEntry) return resolveAsEntry();
2207
2435
  const parent = resolveAsEntry();
@@ -2233,12 +2461,13 @@ function resolveCommandTreeFromPositionals(positionals, entry, options) {
2233
2461
  parentSubCommands: currentSubCommands
2234
2462
  };
2235
2463
  }
2464
+ const [key, cmd] = found;
2236
2465
  let resolved = cmd;
2237
- if (typeof cmd === "function" && cmd.commandName == null) resolved = Object.assign((...args) => cmd(...args), cmd, { commandName: token });
2238
- else if (typeof cmd === "object" && cmd.name == null) resolved = Object.assign(create(), cmd, { name: token });
2466
+ if (typeof cmd === "function" && cmd.commandName == null) resolved = Object.assign((...args) => cmd(...args), cmd, { commandName: key });
2467
+ else if (typeof cmd === "object" && cmd.name == null) resolved = Object.assign(create(), cmd, { name: key });
2239
2468
  resolvedCommand = resolved;
2240
- resolvedName = token;
2241
- commandPath.push(token);
2469
+ resolvedName = key;
2470
+ commandPath.push(key);
2242
2471
  depth++;
2243
2472
  const nestedSubCommands = getCommandSubCommands(cmd);
2244
2473
  if (nestedSubCommands && nestedSubCommands.size > 0) currentSubCommands = nestedSubCommands;
@@ -2325,9 +2554,9 @@ function collectRoutingCandidates(rawPositionals, root) {
2325
2554
  const seen = /* @__PURE__ */ new Set();
2326
2555
  function collect(commands, offset, parentPath) {
2327
2556
  for (let index = offset; index < rawPositionals.length; index++) {
2328
- const name = rawPositionals[index];
2329
- const command = commands.get(name);
2330
- if (command == null) continue;
2557
+ const found = findSubCommand(commands, rawPositionals[index]);
2558
+ if (found == null) continue;
2559
+ const [name, command] = found;
2331
2560
  const path = [...parentPath, name];
2332
2561
  const key = JSON.stringify(path);
2333
2562
  const normalized = normalizeCommandReference(command, name);
@@ -2345,6 +2574,30 @@ function collectRoutingCandidates(rawPositionals, root) {
2345
2574
  collect(root, 0, []);
2346
2575
  return candidates;
2347
2576
  }
2577
+ /**
2578
+ * Find the sub-command that a word of the command line names: the sub-command whose name is the word, or else the
2579
+ * one that has the word among its {@linkcode Command.aliases | aliases}.
2580
+ *
2581
+ * NOTE(kazupon): a name wins over an alias, so that an alias never hides a sub-command. A lazy command has the
2582
+ * aliases of its definition, as it is not loaded yet. Two sub-commands that give the same alias are a mistake in
2583
+ * their definitions, which is thrown as a `TypeError`, as a name given twice in an array of `subCommands` is.
2584
+ *
2585
+ * @param commands - The sub-commands of a level, by their names
2586
+ * @param word - The word of the command line
2587
+ * @returns The name of the sub-command and the sub-command, or `undefined` when no sub-command is named so
2588
+ */
2589
+ function findSubCommand(commands, word) {
2590
+ const command = commands.get(word);
2591
+ if (command != null) return [word, command];
2592
+ let found;
2593
+ for (const [name, candidate] of commands) {
2594
+ const aliases = candidate.aliases;
2595
+ if (!Array.isArray(aliases) || !aliases.includes(word)) continue;
2596
+ if (found) throw new TypeError(`Alias '${word}' is given to more than one command: '${found[0]}' and '${name}'`);
2597
+ found = [name, candidate];
2598
+ }
2599
+ return found;
2600
+ }
2348
2601
  function normalizeCommandReference(command, name) {
2349
2602
  if (typeof command === "function" && command.commandName == null) return Object.assign((...args) => command(...args), command, { commandName: name });
2350
2603
  if (typeof command === "object" && command.name == null) return Object.assign(create(), command, { name });
@@ -2514,7 +2767,13 @@ function createCommandNotFoundError(resolved) {
2514
2767
  code: CommandNotFoundErrorKeys.notFound,
2515
2768
  values: { commandName },
2516
2769
  commandName,
2517
- candidates: [...resolved.parentSubCommands?.keys() || []],
2770
+ /**
2771
+ * NOTE(kazupon): the candidates are what `@gunshi/plugin-suggestion` offers as "Did you mean". An internal
2772
+ * command is left out of them, as the help, shell completion and the help as JSON leave it out: it still
2773
+ * runs when it is typed, but nothing shows it to the user. So is a deprecated command, whose replacement is
2774
+ * what to offer.
2775
+ */
2776
+ candidates: [...resolved.parentSubCommands || []].filter(([, command]) => !command.internal && !isDeprecated(command.deprecated)).map(([name]) => name),
2518
2777
  commandPath: resolved.parentCommandPath || []
2519
2778
  });
2520
2779
  }
@@ -2530,8 +2789,8 @@ function getPluginExtensions(plugins) {
2530
2789
  }
2531
2790
  return extensions;
2532
2791
  }
2533
- async function executeCommand(cmd, ctx, decorators) {
2534
- const commandRunner = cmd.run || NOOP;
2792
+ async function executeCommand(cmd, ctx, decorators, fallbackRunner = NOOP) {
2793
+ const commandRunner = cmd.run || fallbackRunner;
2535
2794
  const baseRunner = (ctx) => {
2536
2795
  if (hasPriorityValidationError(ctx.validationError)) throw ctx.validationError;
2537
2796
  return commandRunner(ctx);
@@ -2540,7 +2799,7 @@ async function executeCommand(cmd, ctx, decorators) {
2540
2799
  try {
2541
2800
  if (ctx.env.onBeforeCommand) await ctx.env.onBeforeCommand(ctx);
2542
2801
  const result = await decoratedRunner(ctx);
2543
- if (ctx.env.onAfterCommand) await ctx.env.onAfterCommand(ctx, result);
2802
+ if (ctx.env.onAfterCommand) await ctx.env.onAfterCommand(ctx, typeof result === "string" ? result : void 0);
2544
2803
  return typeof result === "string" ? result : void 0;
2545
2804
  } catch (error) {
2546
2805
  if (ctx.env.onErrorCommand) try {
@@ -2551,8 +2810,7 @@ async function executeCommand(cmd, ctx, decorators) {
2551
2810
  throw error;
2552
2811
  }
2553
2812
  }
2554
- //#endregion
2555
- //#region ../gunshi/src/cli/bone.ts
2813
+ // ../gunshi/src/cli/bone.ts
2556
2814
  /**
2557
2815
  * @author kazuya kawaguchi (a.k.a. kazupon)
2558
2816
  * @license MIT
@@ -2571,17 +2829,14 @@ async function executeCommand(cmd, ctx, decorators) {
2571
2829
  async function cli(args, entry, options = {}) {
2572
2830
  return cliCore(args, entry, options, []);
2573
2831
  }
2574
- //#endregion
2575
- //#region ../gunshi/src/bone.ts
2832
+ // ../gunshi/src/bone.ts
2576
2833
  /**
2577
2834
  * @author kazuya kawaguchi (a.k.a. kazupon)
2578
2835
  * @license MIT
2579
2836
  */
2580
- //#endregion
2581
- //#region src/index.ts
2837
+ // src/index.ts
2582
2838
  /**
2583
2839
  * @author kazuya kawaguchi (a.k.a. kazupon)
2584
2840
  * @license MIT
2585
2841
  */
2586
- //#endregion
2587
2842
  export { cli };