@gunshi/bone 1.0.0-rc.6 → 1.0.0-rc.8

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 +295 -36
  2. package/lib/index.js +456 -244
  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.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
- //#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.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
- //#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.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
- * {@link resolveArgs} and `parse()` do not report `unknownOption`. An option that is not in the
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.
@@ -1143,8 +1154,7 @@ function checkConflicts(args, explicit, toKebab, actualInputNames) {
1143
1154
  }
1144
1155
  return [];
1145
1156
  }
1146
- //#endregion
1147
- //#region ../../node_modules/.pnpm/args-tokens@1.0.2/node_modules/args-tokens/lib/index.js
1157
+ // ../../node_modules/.pnpm/args-tokens@1.3.0/node_modules/args-tokens/lib/index.js
1148
1158
  /**
1149
1159
  * @author kazuya kawaguchi (a.k.a. kazupon)
1150
1160
  * @license MIT
@@ -1153,8 +1163,7 @@ function checkConflicts(args, explicit, toKebab, actualInputNames) {
1153
1163
  * @author kazuya kawaguchi (a.k.a. kazupon)
1154
1164
  * @license MIT
1155
1165
  */
1156
- //#endregion
1157
- //#region ../gunshi/src/constants.ts
1166
+ // ../gunshi/src/constants.ts
1158
1167
  /**
1159
1168
  * @author kazuya kawaguchi (a.k.a. kazupon)
1160
1169
  * @license MIT
@@ -1176,14 +1185,215 @@ const CLI_OPTIONS_DEFAULT = {
1176
1185
  usageOptionType: false,
1177
1186
  usageOptionValue: true,
1178
1187
  strict: false,
1188
+ strictPositionals: false,
1189
+ helpHint: true,
1190
+ validationErrorExitCode: 1,
1179
1191
  renderHeader: void 0,
1180
1192
  renderUsage: void 0,
1181
1193
  renderValidationErrors: void 0,
1182
1194
  plugins: void 0,
1183
1195
  fallbackToEntry: false
1184
1196
  };
1185
- //#endregion
1186
- //#region ../gunshi/src/utils.ts
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 of `strict`, or a positional argument that the command
1386
+ * does not take, of `strictPositionals`. The global options plugin reports them before `--help` and
1387
+ * `--version`, except an unknown option and a positional argument that the command does not take:
1388
+ * `--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
1187
1397
  /**
1188
1398
  * @author kazuya kawaguchi (a.k.a. kazupon)
1189
1399
  * @license MIT
@@ -1250,6 +1460,8 @@ function isLazyCommand(cmd) {
1250
1460
  *
1251
1461
  * If the loader returns a command, the properties of the loaded command take precedence,
1252
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.
1253
1465
  *
1254
1466
  * @param cmd - A {@link Commandable} or {@link LazyCommand} to resolve
1255
1467
  * @param name - Optional name of the command, if not provided, it will use the name from the command itself.
@@ -1265,6 +1477,8 @@ async function resolveLazyCommand(cmd, name, needRunResolving = false) {
1265
1477
  args: cmd.args,
1266
1478
  examples: cmd.examples,
1267
1479
  internal: cmd.internal,
1480
+ aliases: cmd.aliases,
1481
+ deprecated: cmd.deprecated,
1268
1482
  entry: cmd.entry,
1269
1483
  toKebab: cmd.toKebab,
1270
1484
  rendering: cmd.rendering,
@@ -1273,14 +1487,20 @@ async function resolveLazyCommand(cmd, name, needRunResolving = false) {
1273
1487
  if ("resource" in cmd && cmd.resource) baseCommand.resource = cmd.resource;
1274
1488
  command = Object.assign(create(), baseCommand);
1275
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)";
1276
1496
  const loaded = await cmd();
1277
1497
  if (typeof loaded === "function") command.run = loaded;
1278
- else if (typeof loaded === "object") {
1279
- if (loaded.run == null) throw new TypeError(`'run' is required in command: ${cmd.name || name}`);
1498
+ else if (typeof loaded === "object" && loaded !== null) {
1280
1499
  /**
1281
1500
  * NOTE(kazupon): the loaded command wins, and the definition that is given to `lazy` is the fallback
1282
1501
  * for what the loaded command does not define. A loader that returns `{ run }` keeps the whole definition,
1283
- * 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.
1284
1504
  */
1285
1505
  command.run = loaded.run;
1286
1506
  command.name = loaded.name ?? cmd.commandName;
@@ -1288,12 +1508,19 @@ async function resolveLazyCommand(cmd, name, needRunResolving = false) {
1288
1508
  command.args = loaded.args ?? cmd.args;
1289
1509
  command.examples = loaded.examples ?? cmd.examples;
1290
1510
  command.internal = loaded.internal ?? cmd.internal;
1511
+ command.aliases = loaded.aliases ?? cmd.aliases;
1512
+ command.deprecated = loaded.deprecated ?? cmd.deprecated;
1291
1513
  command.entry = loaded.entry ?? cmd.entry;
1292
1514
  command.toKebab = loaded.toKebab ?? cmd.toKebab;
1293
1515
  command.rendering = loaded.rendering ?? cmd.rendering;
1294
1516
  command.subCommands = loaded.subCommands || cmd.subCommands;
1295
1517
  if ("resource" in loaded && loaded.resource) command.resource = loaded.resource;
1296
- } else throw new TypeError(`Cannot resolve command: ${cmd.name || name}`);
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}`);
1297
1524
  }
1298
1525
  } else command = Object.assign(create(), cmd);
1299
1526
  if (command.name == null && name) command.name = name;
@@ -1364,8 +1591,7 @@ function deepFreeze(obj, ignores = []) {
1364
1591
  }
1365
1592
  return Object.freeze(obj);
1366
1593
  }
1367
- //#endregion
1368
- //#region ../gunshi/src/context.ts
1594
+ // ../gunshi/src/context.ts
1369
1595
  /**
1370
1596
  * The entry for gunshi context.
1371
1597
  * This module is exported for the purpose of testing the command.
@@ -1400,6 +1626,11 @@ async function createCommandContext({ args = {}, explicit = {}, values = {}, pos
1400
1626
  */
1401
1627
  const env = Object.assign(create(), CLI_OPTIONS_DEFAULT, cliOptions);
1402
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
+ /**
1403
1634
  * apply Command definition's rendering option with highest priority
1404
1635
  */
1405
1636
  if (command.rendering) {
@@ -1460,8 +1691,7 @@ function getCommandName(cmd) {
1460
1691
  else if (typeof cmd === "object") return cmd.name || "(anonymous)";
1461
1692
  else return ANONYMOUS_COMMAND_NAME;
1462
1693
  }
1463
- //#endregion
1464
- //#region ../gunshi/src/decorators.ts
1694
+ // ../gunshi/src/decorators.ts
1465
1695
  /**
1466
1696
  * @author kazuya kawaguchi (a.k.a. kazupon)
1467
1697
  * @license MIT
@@ -1528,195 +1758,7 @@ function createDecorators() {
1528
1758
  }
1529
1759
  });
1530
1760
  }
1531
- //#endregion
1532
- //#region ../gunshi/src/error.ts
1533
- /**
1534
- * @author kazuya kawaguchi (a.k.a. kazupon)
1535
- * @license MIT
1536
- */
1537
- /**
1538
- * Command not found error resource keys.
1539
- */
1540
- const CommandNotFoundErrorKeys = { notFound: "err:cmd:not-found" };
1541
- /**
1542
- * Command resolution error resource keys.
1543
- *
1544
- * These errors describe an ambiguity or inconsistency while choosing a command from arguments.
1545
- * They are kept separate from {@link CommandNotFoundError} so consumers can distinguish a typo
1546
- * from an input whose command interpretation is not unique.
1547
- */
1548
- const CommandResolutionErrorKeys = {
1549
- ambiguous: "err:cmd:ambiguous",
1550
- inconsistentOptions: "err:cmd:inconsistent-options",
1551
- lazySchemaMismatch: "err:cmd:lazy-schema-mismatch"
1552
- };
1553
- /**
1554
- * Brand that marks {@link CommandNotFoundError} instances.
1555
- *
1556
- * The brand is looked up in the global symbol registry with `Symbol.for`, so it stays
1557
- * identical across bundled copies of gunshi (`gunshi`, `@gunshi/plugin`, `@gunshi/bone`)
1558
- * and across realms. It lets {@link isCommandNotFoundError} recognize errors created by
1559
- * another copy, where `instanceof` cannot match.
1560
- */
1561
- const COMMAND_NOT_FOUND_ERROR_BRAND = Symbol.for("gunshi.CommandNotFoundError");
1562
- const COMMAND_RESOLUTION_ERROR_BRAND = Symbol.for("gunshi.CommandResolutionError");
1563
- /**
1564
- * Error raised when a command cannot be resolved.
1565
- *
1566
- * Each instance carries a non-enumerable brand keyed by
1567
- * `Symbol.for('gunshi.CommandNotFoundError')`, so that {@link isCommandNotFoundError}
1568
- * recognizes it even when it was created by another bundled copy of gunshi.
1569
- */
1570
- var CommandNotFoundError = class extends Error {
1571
- code;
1572
- values;
1573
- commandName;
1574
- candidates;
1575
- commandPath;
1576
- /**
1577
- * Create a command-not-found error.
1578
- *
1579
- * @param message - Fallback error message
1580
- * @param options - Command-not-found metadata
1581
- */
1582
- constructor(message, options) {
1583
- super(message, { cause: options.cause });
1584
- this.name = "CommandNotFoundError";
1585
- this.code = options.code;
1586
- this.values = options.values || {};
1587
- this.commandName = options.commandName;
1588
- this.candidates = options.candidates || [];
1589
- this.commandPath = options.commandPath || [];
1590
- Object.defineProperty(this, COMMAND_NOT_FOUND_ERROR_BRAND, {
1591
- value: true,
1592
- enumerable: false,
1593
- writable: false,
1594
- configurable: false
1595
- });
1596
- }
1597
- };
1598
- /**
1599
- * Error raised when command routing cannot produce one consistent command.
1600
- *
1601
- * The own registry brand is the cross-bundle contract. Unlike the legacy command-not-found
1602
- * guard, the new guard deliberately has no name-based fallback because this error type is new and
1603
- * must not classify arbitrary errors from older versions.
1604
- */
1605
- var CommandResolutionError = class extends Error {
1606
- code;
1607
- values;
1608
- commandPath;
1609
- candidatePaths;
1610
- /**
1611
- * Create a command resolution error with structured routing metadata.
1612
- *
1613
- * @param message - Human-readable fallback message
1614
- * @param options - Error code and command-routing metadata
1615
- */
1616
- constructor(message, options = {}) {
1617
- super(message, { cause: options.cause });
1618
- this.name = "CommandResolutionError";
1619
- this.code = options.code;
1620
- this.values = options.values || {};
1621
- this.commandPath = options.commandPath || [];
1622
- this.candidatePaths = options.candidatePaths || [];
1623
- Object.defineProperty(this, COMMAND_RESOLUTION_ERROR_BRAND, {
1624
- value: true,
1625
- enumerable: false,
1626
- writable: false,
1627
- configurable: false
1628
- });
1629
- }
1630
- };
1631
- /**
1632
- * Check whether an error is a {@link CommandNotFoundError}.
1633
- *
1634
- * `instanceof` alone is not enough: `@gunshi/plugin` is bundled with its own copy of this
1635
- * class (`noExternal: ['gunshi/plugin']`), so an error thrown by `gunshi` is never an instance
1636
- * of the class a plugin imports. Errors from another copy are recognized through the
1637
- * `Symbol.for('gunshi.CommandNotFoundError')` brand, which does not depend on `error.name`.
1638
- *
1639
- * @param error - An unknown error
1640
- * @returns `true` if the error is a {@link CommandNotFoundError}
1641
- */
1642
- function isCommandNotFoundError(error) {
1643
- if (error instanceof CommandNotFoundError) return true;
1644
- if (!isRecord(error) || !hasCommandNotFoundErrorShape(error)) return false;
1645
- if (Object.hasOwn(error, COMMAND_NOT_FOUND_ERROR_BRAND) && error[COMMAND_NOT_FOUND_ERROR_BRAND] === true) return true;
1646
- return error instanceof Error && error.name === "CommandNotFoundError";
1647
- }
1648
- /**
1649
- * Check whether an error is a {@link CommandResolutionError}.
1650
- *
1651
- * @param error - An unknown error
1652
- * @returns `true` when the error has the command-resolution brand and shape
1653
- */
1654
- function isCommandResolutionError(error) {
1655
- if (error instanceof CommandResolutionError) return true;
1656
- if (!isRecord(error) || !hasCommandResolutionErrorShape(error)) return false;
1657
- return Object.hasOwn(error, COMMAND_RESOLUTION_ERROR_BRAND) && error[COMMAND_RESOLUTION_ERROR_BRAND] === true;
1658
- }
1659
- /**
1660
- * Check whether an error is an {@link ArgsValidationError}.
1661
- *
1662
- * Prefer this over the `args-tokens` guard of the same name. Both recognize errors from another
1663
- * bundled copy through the `Symbol.for('args-tokens.ArgsValidationError')` brand that
1664
- * `args-tokens` 0.29.0 or later sets, including subclasses such as `ArgResolveError` that
1665
- * override `name` with the argument name. This guard additionally:
1666
- *
1667
- * - recognizes direct `ArgsValidationError` instances from copies bundling `args-tokens`
1668
- * older than 0.29.0, which do not set the brand
1669
- * - checks that `code` and `values` of an error from another copy have the expected types
1670
- *
1671
- * The guard narrows only to {@link ArgsValidationError}: across copies,
1672
- * `instanceof ArgResolveError` still fails, so do not rely on `type` or `schema` for such errors.
1673
- *
1674
- * @param error - An unknown error
1675
- * @returns `true` if the error is an {@link ArgsValidationError}
1676
- */
1677
- function isArgsValidationError(error) {
1678
- if (error instanceof ArgsValidationError) return true;
1679
- if (!isRecord(error) || !hasArgsValidationErrorShape(error)) return false;
1680
- if (isArgsValidationError$1(error)) return true;
1681
- return error instanceof Error && error.name === "ArgsValidationError";
1682
- }
1683
- function isRecord(value) {
1684
- return typeof value === "object" && value !== null;
1685
- }
1686
- function isStringArray(value) {
1687
- return Array.isArray(value) && value.every((item) => typeof item === "string");
1688
- }
1689
- /**
1690
- * Check whether `code` is an own or inherited property that is a string or `undefined`.
1691
- *
1692
- * Constructors always assign `code`, even when the option is omitted.
1693
- *
1694
- * @param error - An error from another copy
1695
- * @returns `true` if `code` has the expected type
1696
- */
1697
- function hasOptionalStringCode(error) {
1698
- return "code" in error && (error.code === void 0 || typeof error.code === "string");
1699
- }
1700
- function hasCommandNotFoundErrorShape(error) {
1701
- return hasOptionalStringCode(error) && isRecord(error.values) && typeof error.commandName === "string" && isStringArray(error.candidates) && isStringArray(error.commandPath);
1702
- }
1703
- function hasCommandResolutionErrorShape(error) {
1704
- return hasOptionalStringCode(error) && isRecord(error.values) && isStringArray(error.commandPath) && Array.isArray(error.candidatePaths) && error.candidatePaths.every((path) => isStringArray(path));
1705
- }
1706
- function hasArgsValidationErrorShape(error) {
1707
- return hasOptionalStringCode(error) && isRecord(error.values);
1708
- }
1709
- /**
1710
- * Check whether validation errors should be handled before version, help, or command execution.
1711
- *
1712
- * @param error - An aggregate validation error
1713
- * @returns `true` if the validation error must be handled with priority
1714
- */
1715
- function hasPriorityValidationError(error) {
1716
- return error?.errors.some((error) => isCommandNotFoundError(error) || isCommandResolutionError(error) || isArgsValidationError(error) && error.code === ArgsValidationErrorKeys.unknownOption) ?? false;
1717
- }
1718
- //#endregion
1719
- //#region ../gunshi/src/plugin/context.ts
1761
+ // ../gunshi/src/plugin/context.ts
1720
1762
  /**
1721
1763
  * @author kazuya kawaguchi (a.k.a. kazupon)
1722
1764
  * @license MIT
@@ -1799,8 +1841,7 @@ function createPluginContext(decorators, initialSubCommands) {
1799
1841
  function findGlobalOptionByShort(globalOptions, short) {
1800
1842
  for (const [name, schema] of globalOptions) if (schema.short === short) return name;
1801
1843
  }
1802
- //#endregion
1803
- //#region ../gunshi/src/plugin/dependency.ts
1844
+ // ../gunshi/src/plugin/dependency.ts
1804
1845
  /**
1805
1846
  * @author kazuya kawaguchi (a.k.a. kazupon)
1806
1847
  * @license MIT
@@ -1841,8 +1882,7 @@ function resolveDependencies(plugins) {
1841
1882
  for (const plugin of plugins) visit(plugin);
1842
1883
  return sorted;
1843
1884
  }
1844
- //#endregion
1845
- //#region ../gunshi/src/cli/args.ts
1885
+ // ../gunshi/src/cli/args.ts
1846
1886
  /**
1847
1887
  * @author kazuya kawaguchi (a.k.a. kazupon)
1848
1888
  * @license MIT
@@ -1882,8 +1922,7 @@ function resolveGlobalOptions(globalOptions, args) {
1882
1922
  } : schema;
1883
1923
  return resolved;
1884
1924
  }
1885
- //#endregion
1886
- //#region ../gunshi/src/cli/core.ts
1925
+ // ../gunshi/src/cli/core.ts
1887
1926
  /**
1888
1927
  * @author kazuya kawaguchi (a.k.a. kazupon)
1889
1928
  * @license MIT
@@ -1916,8 +1955,11 @@ async function cliCore(argv, entry, options, plugins, usageOnly = false) {
1916
1955
  * NOTE(kazupon): a CLI whose user declares no sub-commands has no command tree of its own,
1917
1956
  * so a positional argument must not become a command name just because a plugin added a command.
1918
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.
1919
1961
  */
1920
- 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;
1921
1963
  const tokens = parseArgs(argv);
1922
1964
  const selection = resolveCommandSelection(tokens, entry, cliOptions, pluginContext.globalOptions);
1923
1965
  const resolved = selection.context;
@@ -1943,8 +1985,24 @@ async function cliCore(argv, entry, options, plugins, usageOnly = false) {
1943
1985
  }
1944
1986
  const routingOptions = Object.assign(create(), cliOptions, { subCommands: new Map(cliOptions.subCommands) });
1945
1987
  if (targetLevelSubCommands) cliOptions.subCommands = targetLevelSubCommands;
1946
- const resolvedCommand = isLazyCommand(targetCommand) ? await resolveLazyCommand(targetCommand, targetCommandName, true) : targetCommand;
1947
- if (selection.error == null && isLazyCommand(targetCommand)) {
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) {
1948
2006
  const loaded = resolveCommandTreeFromPositionals(getRoutingPositionals(tokens, pluginContext.globalOptions, resolvedCommand), entry, routingOptions);
1949
2007
  if (!sameCommandPath(loaded.commandPath, targetCommandPath)) additionalValidationErrors.push(createLazySchemaMismatchError(targetCommandPath, loaded.commandPath));
1950
2008
  }
@@ -1968,7 +2026,11 @@ async function cliCore(argv, entry, options, plugins, usageOnly = false) {
1968
2026
  toKebab: resolvedCommand.toKebab,
1969
2027
  skipPositional
1970
2028
  });
1971
- const validationError = mergeValidationErrors(error, [...additionalValidationErrors, ...cliOptions.strict && !diagnostic ? createUnknownOptionErrors(findUnknownOptions(args, tokens, { toKebab: resolvedCommand.toKebab })) : []]);
2029
+ const validationError = mergeValidationErrors(error, [
2030
+ ...additionalValidationErrors,
2031
+ ...cliOptions.strict && !diagnostic ? createUnknownOptionErrors(findUnknownOptions(args, tokens, { toKebab: resolvedCommand.toKebab })) : [],
2032
+ ...cliOptions.strictPositionals && !diagnostic && additionalValidationErrors.length === 0 ? createUnexpectedPositionalErrors(findUnexpectedPositionals(args, positionals, skipPositional)) : []
2033
+ ]);
1972
2034
  const commandContext = await createCommandContext({
1973
2035
  args,
1974
2036
  explicit,
@@ -1985,9 +2047,25 @@ async function cliCore(argv, entry, options, plugins, usageOnly = false) {
1985
2047
  validationError,
1986
2048
  cliOptions
1987
2049
  });
2050
+ markDeprecatedCommands(commandContext, collectDeprecatedCommands(routingOptions.subCommands, targetCommandPath, resolvedCommand));
1988
2051
  const reported = trackReported(commandContext);
2052
+ let fallbackRunner = NOOP;
2053
+ if (loadFailure !== void 0) {
2054
+ const { error } = loadFailure;
2055
+ fallbackRunner = () => {
2056
+ throw error;
2057
+ };
2058
+ } else if (resolvedCommand.run == null) {
2059
+ markWithoutRun(commandContext);
2060
+ if (!(targetDepth === 0 ? routingOptions.subCommands.size > 0 : (getCommandSubCommands(resolvedCommand)?.size ?? 0) > 0)) {
2061
+ const commandName = resolvedCommand.name || targetCommandName || "(anonymous)";
2062
+ fallbackRunner = () => {
2063
+ throw new TypeError(`'run' is required in command: ${commandName}`);
2064
+ };
2065
+ }
2066
+ }
1989
2067
  try {
1990
- return await executeCommand(resolvedCommand, commandContext, decorators.commandDecorators);
2068
+ return await executeCommand(resolvedCommand, commandContext, decorators.commandDecorators, fallbackRunner);
1991
2069
  } catch (error) {
1992
2070
  /**
1993
2071
  * NOTE(kazupon): a plugin that has reported the validation errors to the user marks them, as the
@@ -2021,6 +2099,87 @@ function trackReported(ctx) {
2021
2099
  return reported;
2022
2100
  }
2023
2101
  /**
2102
+ * The key of the registry of the command contexts whose command has no `run`. The global options plugin
2103
+ * and the usage renderer plugin read it with `isWithoutRun` of `@gunshi/shared`, by the same registered
2104
+ * symbol, since `gunshi` and the plugins bundle their own copies. Neither is in the public API.
2105
+ */
2106
+ const WITHOUT_RUN = Symbol.for("gunshi.withoutRun");
2107
+ /**
2108
+ * Mark the command context of a run whose command has no `run`.
2109
+ *
2110
+ * NOTE(kazupon): the global options plugin prints the usage of a command that has sub-commands and no
2111
+ * `run`, when it runs without a sub-command, as `--help` does. The plugin cannot tell it from the context,
2112
+ * nor from the runner that it decorates, which the core always wraps, so the core tells it. The command
2113
+ * is checked once it is loaded, so a lazy command whose loader returns a command without `run` is marked
2114
+ * too. The registry is weak, and holds the context of this run only: a nested `cli()` in a hook has a
2115
+ * context of its own.
2116
+ *
2117
+ * @param ctx - The command context of the run
2118
+ */
2119
+ function markWithoutRun(ctx) {
2120
+ const registry = globalThis;
2121
+ (registry[WITHOUT_RUN] ??= /* @__PURE__ */ new WeakSet()).add(ctx);
2122
+ }
2123
+ /**
2124
+ * The key of the registry of the deprecated commands on the path of a run. The global options plugin and the
2125
+ * usage renderer plugin read it with `getDeprecatedCommands` of `@gunshi/shared`, by the same registered
2126
+ * symbol, since `gunshi` and the plugins bundle their own copies. Neither is in the public API.
2127
+ */
2128
+ const DEPRECATED_COMMANDS = Symbol.for("gunshi.deprecatedCommands");
2129
+ /**
2130
+ * Check whether the `deprecated` of a command or an argument marks it as deprecated.
2131
+ *
2132
+ * @param deprecated - The `deprecated` of a command or an argument
2133
+ * @returns `true` for `true` or a text
2134
+ */
2135
+ function isDeprecated(deprecated) {
2136
+ return deprecated === true || typeof deprecated === "string";
2137
+ }
2138
+ /**
2139
+ * Collect the deprecated commands on the path of a run, root first.
2140
+ *
2141
+ * NOTE(kazupon): the command that runs is the loaded one, whose `deprecated` wins over the one of the definition
2142
+ * given to `lazy`. The commands above it are the definitions of the tree, as the routing found them. The entry
2143
+ * command is not on the path.
2144
+ *
2145
+ * @param root - The sub-commands at the top level
2146
+ * @param commandPath - The names of the commands on the path
2147
+ * @param resolvedCommand - The command that runs
2148
+ * @returns The deprecated commands, with their paths
2149
+ */
2150
+ function collectDeprecatedCommands(root, commandPath, resolvedCommand) {
2151
+ const marks = [];
2152
+ let level = root;
2153
+ for (const [index, name] of commandPath.entries()) {
2154
+ const last = index === commandPath.length - 1;
2155
+ const declared = level?.get(name);
2156
+ const command = last ? resolvedCommand : declared;
2157
+ if (command == null) break;
2158
+ if (isDeprecated(command.deprecated)) marks.push({
2159
+ commandPath: commandPath.slice(0, index + 1),
2160
+ deprecated: command.deprecated
2161
+ });
2162
+ level = declared == null ? void 0 : getCommandSubCommands(declared);
2163
+ }
2164
+ return marks;
2165
+ }
2166
+ /**
2167
+ * Mark the command context of a run with the deprecated commands on its path.
2168
+ *
2169
+ * NOTE(kazupon): the context has the command that runs, and not the commands above it, such as the old name of a
2170
+ * renamed group, so the core, which walks the path, tells the plugins which of them are deprecated. The global
2171
+ * options plugin warns of them, and the usage renderer plugin says so in the help. The registry is weak, and
2172
+ * holds the context of this run only.
2173
+ *
2174
+ * @param ctx - The command context of the run
2175
+ * @param marks - The deprecated commands on the path
2176
+ */
2177
+ function markDeprecatedCommands(ctx, marks) {
2178
+ if (marks.length === 0) return;
2179
+ const registry = globalThis;
2180
+ (registry[DEPRECATED_COMMANDS] ??= /* @__PURE__ */ new WeakMap()).set(ctx, marks);
2181
+ }
2182
+ /**
2024
2183
  * Create the decorator that renders the usage of the command instead of running it.
2025
2184
  *
2026
2185
  * NOTE(kazupon): `generate()` of `gunshi/generator` asks the core for a usage. It used to ask by
@@ -2108,14 +2267,16 @@ function findUnknownOptions(args, tokens, options) {
2108
2267
  knownLongOptions.add(optionName);
2109
2268
  /**
2110
2269
  * NOTE(kazupon): a hidden option is still accepted, so it stays a known option. It is left out
2111
- * of the candidates, which are what `@gunshi/plugin-suggestion` offers as "Did you mean".
2270
+ * of the candidates, which are what `@gunshi/plugin-suggestion` offers as "Did you mean". So is a
2271
+ * deprecated option, which the help leaves out too, and so is the negated form of either.
2112
2272
  */
2113
- if (!schema.hidden) addLongOptionCandidate(optionName);
2273
+ const offered = !schema.hidden && !isDeprecated(schema.deprecated);
2274
+ if (offered) addLongOptionCandidate(optionName);
2114
2275
  if (schema.short) knownShortOptions.add(schema.short);
2115
2276
  if (schema.type === "boolean" && schema.negatable) {
2116
2277
  const negatableOptionName = `${NEGATABLE_OPTION_PREFIX}${optionName}`;
2117
2278
  knownNegatableOptions.add(negatableOptionName);
2118
- if (!schema.hidden) addLongOptionCandidate(negatableOptionName);
2279
+ if (offered) addLongOptionCandidate(negatableOptionName);
2119
2280
  }
2120
2281
  }
2121
2282
  const unknownOptions = [];
@@ -2149,6 +2310,30 @@ function createUnknownOptionErrors(unknownOptions) {
2149
2310
  });
2150
2311
  });
2151
2312
  }
2313
+ /**
2314
+ * Find the positional arguments that the command does not take: the ones after its command path that its
2315
+ * positional arguments do not take. A positional argument with `multiple` takes all of them.
2316
+ *
2317
+ * NOTE(kazupon): args-tokens gives the positional arguments after the command path to the positional
2318
+ * arguments of the command in the order they are declared, so the declared ones take the first of them,
2319
+ * as many as they are, an optional one included, and the rest are left over.
2320
+ *
2321
+ * @param args - The arguments of the command
2322
+ * @param positionals - The positional arguments, the command path included
2323
+ * @param skipPositional - The index of the last command name in `positionals`
2324
+ * @returns The positional arguments that are left over
2325
+ */
2326
+ function findUnexpectedPositionals(args, positionals, skipPositional) {
2327
+ const declared = Object.values(args).filter((schema) => schema.type === "positional");
2328
+ if (declared.some((schema) => schema.multiple)) return [];
2329
+ return positionals.slice(skipPositional + 1 + declared.length);
2330
+ }
2331
+ function createUnexpectedPositionalErrors(positionals) {
2332
+ return positionals.map((rawName) => new ArgsValidationError(`Unexpected positional argument: ${rawName}`, {
2333
+ code: ArgsValidationErrorKeys.unexpectedPositional,
2334
+ values: { rawName }
2335
+ }));
2336
+ }
2152
2337
  function mergeValidationErrors(error, additionalErrors) {
2153
2338
  if (additionalErrors.length === 0) return error;
2154
2339
  return new AggregateError(error ? [...error.errors, ...additionalErrors] : additionalErrors, error?.message || additionalErrors[0]?.message);
@@ -2253,8 +2438,8 @@ function resolveCommandTreeFromPositionals(positionals, entry, options) {
2253
2438
  let depth = 0;
2254
2439
  for (let i = 0; i < positionals.length; i++) {
2255
2440
  const token = positionals[i];
2256
- const cmd = currentSubCommands.get(token);
2257
- if (cmd == null) {
2441
+ const found = findSubCommand(currentSubCommands, token);
2442
+ if (found == null) {
2258
2443
  if (depth === 0) {
2259
2444
  if (options.fallbackToEntry) return resolveAsEntry();
2260
2445
  const parent = resolveAsEntry();
@@ -2286,12 +2471,13 @@ function resolveCommandTreeFromPositionals(positionals, entry, options) {
2286
2471
  parentSubCommands: currentSubCommands
2287
2472
  };
2288
2473
  }
2474
+ const [key, cmd] = found;
2289
2475
  let resolved = cmd;
2290
- if (typeof cmd === "function" && cmd.commandName == null) resolved = Object.assign((...args) => cmd(...args), cmd, { commandName: token });
2291
- else if (typeof cmd === "object" && cmd.name == null) resolved = Object.assign(create(), cmd, { name: token });
2476
+ if (typeof cmd === "function" && cmd.commandName == null) resolved = Object.assign((...args) => cmd(...args), cmd, { commandName: key });
2477
+ else if (typeof cmd === "object" && cmd.name == null) resolved = Object.assign(create(), cmd, { name: key });
2292
2478
  resolvedCommand = resolved;
2293
- resolvedName = token;
2294
- commandPath.push(token);
2479
+ resolvedName = key;
2480
+ commandPath.push(key);
2295
2481
  depth++;
2296
2482
  const nestedSubCommands = getCommandSubCommands(cmd);
2297
2483
  if (nestedSubCommands && nestedSubCommands.size > 0) currentSubCommands = nestedSubCommands;
@@ -2378,9 +2564,9 @@ function collectRoutingCandidates(rawPositionals, root) {
2378
2564
  const seen = /* @__PURE__ */ new Set();
2379
2565
  function collect(commands, offset, parentPath) {
2380
2566
  for (let index = offset; index < rawPositionals.length; index++) {
2381
- const name = rawPositionals[index];
2382
- const command = commands.get(name);
2383
- if (command == null) continue;
2567
+ const found = findSubCommand(commands, rawPositionals[index]);
2568
+ if (found == null) continue;
2569
+ const [name, command] = found;
2384
2570
  const path = [...parentPath, name];
2385
2571
  const key = JSON.stringify(path);
2386
2572
  const normalized = normalizeCommandReference(command, name);
@@ -2398,6 +2584,30 @@ function collectRoutingCandidates(rawPositionals, root) {
2398
2584
  collect(root, 0, []);
2399
2585
  return candidates;
2400
2586
  }
2587
+ /**
2588
+ * Find the sub-command that a word of the command line names: the sub-command whose name is the word, or else the
2589
+ * one that has the word among its {@linkcode Command.aliases | aliases}.
2590
+ *
2591
+ * NOTE(kazupon): a name wins over an alias, so that an alias never hides a sub-command. A lazy command has the
2592
+ * aliases of its definition, as it is not loaded yet. Two sub-commands that give the same alias are a mistake in
2593
+ * their definitions, which is thrown as a `TypeError`, as a name given twice in an array of `subCommands` is.
2594
+ *
2595
+ * @param commands - The sub-commands of a level, by their names
2596
+ * @param word - The word of the command line
2597
+ * @returns The name of the sub-command and the sub-command, or `undefined` when no sub-command is named so
2598
+ */
2599
+ function findSubCommand(commands, word) {
2600
+ const command = commands.get(word);
2601
+ if (command != null) return [word, command];
2602
+ let found;
2603
+ for (const [name, candidate] of commands) {
2604
+ const aliases = candidate.aliases;
2605
+ if (!Array.isArray(aliases) || !aliases.includes(word)) continue;
2606
+ if (found) throw new TypeError(`Alias '${word}' is given to more than one command: '${found[0]}' and '${name}'`);
2607
+ found = [name, candidate];
2608
+ }
2609
+ return found;
2610
+ }
2401
2611
  function normalizeCommandReference(command, name) {
2402
2612
  if (typeof command === "function" && command.commandName == null) return Object.assign((...args) => command(...args), command, { commandName: name });
2403
2613
  if (typeof command === "object" && command.name == null) return Object.assign(create(), command, { name });
@@ -2567,7 +2777,13 @@ function createCommandNotFoundError(resolved) {
2567
2777
  code: CommandNotFoundErrorKeys.notFound,
2568
2778
  values: { commandName },
2569
2779
  commandName,
2570
- candidates: [...resolved.parentSubCommands?.keys() || []],
2780
+ /**
2781
+ * NOTE(kazupon): the candidates are what `@gunshi/plugin-suggestion` offers as "Did you mean". An internal
2782
+ * command is left out of them, as the help, shell completion and the help as JSON leave it out: it still
2783
+ * runs when it is typed, but nothing shows it to the user. So is a deprecated command, whose replacement is
2784
+ * what to offer.
2785
+ */
2786
+ candidates: [...resolved.parentSubCommands || []].filter(([, command]) => !command.internal && !isDeprecated(command.deprecated)).map(([name]) => name),
2571
2787
  commandPath: resolved.parentCommandPath || []
2572
2788
  });
2573
2789
  }
@@ -2583,8 +2799,8 @@ function getPluginExtensions(plugins) {
2583
2799
  }
2584
2800
  return extensions;
2585
2801
  }
2586
- async function executeCommand(cmd, ctx, decorators) {
2587
- const commandRunner = cmd.run || NOOP;
2802
+ async function executeCommand(cmd, ctx, decorators, fallbackRunner = NOOP) {
2803
+ const commandRunner = cmd.run || fallbackRunner;
2588
2804
  const baseRunner = (ctx) => {
2589
2805
  if (hasPriorityValidationError(ctx.validationError)) throw ctx.validationError;
2590
2806
  return commandRunner(ctx);
@@ -2604,8 +2820,7 @@ async function executeCommand(cmd, ctx, decorators) {
2604
2820
  throw error;
2605
2821
  }
2606
2822
  }
2607
- //#endregion
2608
- //#region ../gunshi/src/cli/bone.ts
2823
+ // ../gunshi/src/cli/bone.ts
2609
2824
  /**
2610
2825
  * @author kazuya kawaguchi (a.k.a. kazupon)
2611
2826
  * @license MIT
@@ -2624,17 +2839,14 @@ async function executeCommand(cmd, ctx, decorators) {
2624
2839
  async function cli(args, entry, options = {}) {
2625
2840
  return cliCore(args, entry, options, []);
2626
2841
  }
2627
- //#endregion
2628
- //#region ../gunshi/src/bone.ts
2842
+ // ../gunshi/src/bone.ts
2629
2843
  /**
2630
2844
  * @author kazuya kawaguchi (a.k.a. kazupon)
2631
2845
  * @license MIT
2632
2846
  */
2633
- //#endregion
2634
- //#region src/index.ts
2847
+ // src/index.ts
2635
2848
  /**
2636
2849
  * @author kazuya kawaguchi (a.k.a. kazupon)
2637
2850
  * @license MIT
2638
2851
  */
2639
- //#endregion
2640
2852
  export { cli };