@gunshi/plugin-suggestion 0.35.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 kazuya kawaguchi
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
6
+ this software and associated documentation files (the "Software"), to deal in
7
+ the Software without restriction, including without limitation the rights to
8
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9
+ the Software, and to permit persons to whom the Software is furnished to do so,
10
+ subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
17
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19
+ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20
+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,93 @@
1
+ # @gunshi/plugin-suggestion
2
+
3
+ Suggestion plugin for Gunshi.
4
+
5
+ This plugin adds a short hint to validation errors when a user enters an unknown long option or an unknown command.
6
+ It uses Levenshtein distance by default and works with Gunshi's structured validation errors.
7
+
8
+ ## Installation
9
+
10
+ ```sh
11
+ npm install @gunshi/plugin-suggestion
12
+ ```
13
+
14
+ ## Usage
15
+
16
+ ```ts
17
+ import { cli, define } from 'gunshi'
18
+ import { suggestion } from '@gunshi/plugin-suggestion'
19
+
20
+ const command = define({
21
+ name: 'app',
22
+ toKebab: true,
23
+ args: {
24
+ allowReload: {
25
+ type: 'boolean',
26
+ description: 'Allow reload'
27
+ }
28
+ },
29
+ run: () => {}
30
+ })
31
+
32
+ await cli(process.argv.slice(2), command, {
33
+ strict: true,
34
+ plugins: [suggestion()]
35
+ })
36
+ ```
37
+
38
+ When the user enters an unknown long option, the validation message includes a hint:
39
+
40
+ ```txt
41
+ Unknown option: --alow-reload
42
+ Did you mean --allow-reload?
43
+ ```
44
+
45
+ When the user enters an unknown command, the plugin suggests a command from the same command level:
46
+
47
+ ```txt
48
+ Command not found: rn
49
+ Did you mean run?
50
+ ```
51
+
52
+ ## Options
53
+
54
+ ```ts
55
+ suggestion({
56
+ maxDistance: 2,
57
+ maxSuggestions: 1,
58
+ includeOptions: true,
59
+ includeCommands: true,
60
+ distance: customDistance,
61
+ normalize: value => value.toLowerCase()
62
+ })
63
+ ```
64
+
65
+ - `maxDistance`: maximum distance allowed for a candidate.
66
+ - `maxSuggestions`: maximum number of suggestions per validation error.
67
+ - `includeOptions`: enables unknown long option suggestions.
68
+ - `includeCommands`: enables command not found suggestions.
69
+ - `distance`: custom distance function. Lower values are better matches.
70
+ - `normalize`: normalizes typed input and candidates before scoring.
71
+
72
+ ## Internationalization
73
+
74
+ The plugin can be combined with `@gunshi/plugin-i18n`.
75
+ The suggestion hint uses the built-in resource key `err:suggestion:did-you-mean`.
76
+
77
+ ```ts
78
+ import i18n from '@gunshi/plugin-i18n'
79
+ import { suggestion } from '@gunshi/plugin-suggestion'
80
+
81
+ await cli(argv, command, {
82
+ strict: true,
83
+ plugins: [i18n({ locale: 'ja-JP' }), suggestion()]
84
+ })
85
+ ```
86
+
87
+ Without i18n, the plugin falls back to `Did you mean {$name}?`.
88
+
89
+ ## Design notes
90
+
91
+ The plugin does not detect unknown options or unknown commands by itself.
92
+ Gunshi core creates structured validation errors and provides candidate metadata.
93
+ This plugin only decorates validation error rendering and appends suggestion hints.
package/lib/index.d.ts ADDED
@@ -0,0 +1,126 @@
1
+ import { PluginWithoutExtension } from "@gunshi/plugin";
2
+
3
+ //#region src/index.d.ts
4
+
5
+ /**
6
+ * The unique identifier for suggestion plugin.
7
+ */
8
+ declare const pluginId: "g:suggestion";
9
+ /**
10
+ * Type representing the unique identifier for suggestion plugin.
11
+ */
12
+ type PluginId = typeof pluginId;
13
+ /**
14
+ * Suggestion error resource keys.
15
+ */
16
+ declare const SuggestionErrorKeys: {
17
+ readonly didYouMean: "err:suggestion:did-you-mean";
18
+ };
19
+ /**
20
+ * Suggestion error resource key type.
21
+ */
22
+ type SuggestionErrorCode = (typeof SuggestionErrorKeys)[keyof typeof SuggestionErrorKeys];
23
+ /**
24
+ * Distance function for scoring candidate names.
25
+ *
26
+ * Lower values are treated as better matches.
27
+ */
28
+ type DistanceFunction = (input: string, candidate: string) => number;
29
+ /**
30
+ * Suggestion function returned by {@link defineSuggestNames}.
31
+ */
32
+ type SuggestNames = (typed: string, candidates: readonly string[]) => string[];
33
+ /**
34
+ * Suggestion plugin options.
35
+ */
36
+ interface SuggestionOptions {
37
+ /**
38
+ * Maximum distance allowed for a candidate.
39
+ *
40
+ * @default 2
41
+ */
42
+ maxDistance?: number;
43
+ /**
44
+ * Maximum number of suggestions to render for one error.
45
+ *
46
+ * @default 1
47
+ */
48
+ maxSuggestions?: number;
49
+ /**
50
+ * Whether to suggest known long options for unknown option errors.
51
+ *
52
+ * @default true
53
+ */
54
+ includeOptions?: boolean;
55
+ /**
56
+ * Whether to suggest known commands for command-not-found errors.
57
+ *
58
+ * @default true
59
+ */
60
+ includeCommands?: boolean;
61
+ /**
62
+ * Distance function used for ranking candidates.
63
+ *
64
+ * @default levenshtein
65
+ */
66
+ distance?: DistanceFunction;
67
+ /**
68
+ * Normalize typed input and candidates before distance calculation.
69
+ *
70
+ * @default value => value
71
+ */
72
+ normalize?: (value: string) => string;
73
+ }
74
+ /**
75
+ * Resolved suggestion plugin options.
76
+ */
77
+ interface ResolvedSuggestionOptions {
78
+ /**
79
+ * Maximum distance allowed for a candidate.
80
+ */
81
+ maxDistance: number;
82
+ /**
83
+ * Maximum number of suggestions to render for one error.
84
+ */
85
+ maxSuggestions: number;
86
+ /**
87
+ * Whether to suggest known long options for unknown option errors.
88
+ */
89
+ includeOptions: boolean;
90
+ /**
91
+ * Whether to suggest known commands for command-not-found errors.
92
+ */
93
+ includeCommands: boolean;
94
+ /**
95
+ * Distance function used for ranking candidates.
96
+ */
97
+ distance: DistanceFunction;
98
+ /**
99
+ * Normalize typed input and candidates before distance calculation.
100
+ */
101
+ normalize: (value: string) => string;
102
+ }
103
+ /**
104
+ * Calculate the Levenshtein distance between two strings.
105
+ *
106
+ * @param input - Input string
107
+ * @param candidate - Candidate string
108
+ * @returns Edit distance between the two strings
109
+ */
110
+ declare function levenshtein(input: string, candidate: string): number;
111
+ /**
112
+ * Create a suggestion function with resolved options captured in a closure.
113
+ *
114
+ * @param options - Resolved suggestion options
115
+ * @returns A function that suggests candidate names
116
+ */
117
+ declare function defineSuggestNames(options: ResolvedSuggestionOptions): SuggestNames;
118
+ /**
119
+ * Suggestion plugin.
120
+ *
121
+ * @param options - Suggestion plugin options
122
+ * @returns A defined plugin as suggestion
123
+ */
124
+ declare function suggestion(options?: SuggestionOptions): PluginWithoutExtension;
125
+ //#endregion
126
+ export { DistanceFunction, PluginId, ResolvedSuggestionOptions, SuggestNames, SuggestionErrorCode, SuggestionErrorKeys, SuggestionOptions, defineSuggestNames, levenshtein, pluginId, suggestion };
package/lib/index.js ADDED
@@ -0,0 +1,152 @@
1
+ import { ArgsValidationErrorKeys, isArgsValidationError, isCommandNotFoundError, plugin } from "@gunshi/plugin";
2
+ //#region src/index.ts
3
+ /**
4
+ * The entry point of suggestion plugin.
5
+ *
6
+ * @example
7
+ * ```js
8
+ * import { cli } from 'gunshi'
9
+ * import { suggestion } from '@gunshi/plugin-suggestion'
10
+ *
11
+ * await cli(process.argv.slice(2), command, {
12
+ * strict: true,
13
+ * plugins: [
14
+ * suggestion()
15
+ * ]
16
+ * })
17
+ * ```
18
+ *
19
+ * @module
20
+ */
21
+ /**
22
+ * @author kazuya kawaguchi (a.k.a. kazupon)
23
+ * @license MIT
24
+ */
25
+ /**
26
+ * The unique identifier for suggestion plugin.
27
+ */
28
+ const pluginId = "g:suggestion";
29
+ /**
30
+ * Suggestion error resource keys.
31
+ */
32
+ const SuggestionErrorKeys = { didYouMean: "err:suggestion:did-you-mean" };
33
+ const i18nPluginId = "g:i18n";
34
+ const dependencies = [{
35
+ id: i18nPluginId,
36
+ optional: true
37
+ }];
38
+ /**
39
+ * Calculate the Levenshtein distance between two strings.
40
+ *
41
+ * @param input - Input string
42
+ * @param candidate - Candidate string
43
+ * @returns Edit distance between the two strings
44
+ */
45
+ function levenshtein(input, candidate) {
46
+ if (input === candidate) return 0;
47
+ if (input.length === 0) return candidate.length;
48
+ if (candidate.length === 0) return input.length;
49
+ let previous = Array.from({ length: candidate.length + 1 }, (_, index) => index);
50
+ let current = Array.from({ length: candidate.length + 1 }, () => 0);
51
+ for (let i = 1; i <= input.length; i++) {
52
+ current[0] = i;
53
+ for (let j = 1; j <= candidate.length; j++) {
54
+ const cost = input[i - 1] === candidate[j - 1] ? 0 : 1;
55
+ current[j] = Math.min(previous[j] + 1, current[j - 1] + 1, previous[j - 1] + cost);
56
+ }
57
+ [previous, current] = [current, previous];
58
+ }
59
+ return previous[candidate.length];
60
+ }
61
+ /**
62
+ * Create a suggestion function with resolved options captured in a closure.
63
+ *
64
+ * @param options - Resolved suggestion options
65
+ * @returns A function that suggests candidate names
66
+ */
67
+ function defineSuggestNames(options) {
68
+ return function suggestNames(typed, candidates) {
69
+ const normalizedTyped = options.normalize(normalizeSuggestionName(typed));
70
+ return candidates.map((candidate, index) => ({
71
+ candidate,
72
+ index,
73
+ distance: options.distance(normalizedTyped, options.normalize(normalizeSuggestionName(candidate)))
74
+ })).filter((item) => item.distance <= options.maxDistance).sort((a, b) => a.distance - b.distance || a.index - b.index).slice(0, options.maxSuggestions).map((item) => item.candidate);
75
+ };
76
+ }
77
+ /**
78
+ * Suggestion plugin.
79
+ *
80
+ * @param options - Suggestion plugin options
81
+ * @returns A defined plugin as suggestion
82
+ */
83
+ function suggestion(options = {}) {
84
+ const resolved = resolveSuggestionOptions(options);
85
+ const suggestNames = defineSuggestNames(resolved);
86
+ return plugin({
87
+ id: pluginId,
88
+ name: "suggestion",
89
+ dependencies,
90
+ setup(ctx) {
91
+ ctx.decorateValidationErrorsRenderer(async (baseRenderer, cmdCtx, error) => {
92
+ const message = await baseRenderer(cmdCtx, error);
93
+ const hints = [];
94
+ const seen = /* @__PURE__ */ new Set();
95
+ for (const err of error.errors) {
96
+ if (resolved.includeOptions) await collectSuggestions(hints, seen, cmdCtx, getUnknownOptionSuggestionInput(err), suggestNames);
97
+ if (resolved.includeCommands) await collectSuggestions(hints, seen, cmdCtx, getCommandSuggestionInput(err), suggestNames);
98
+ }
99
+ return [message, ...hints].filter(Boolean).join("\n");
100
+ });
101
+ }
102
+ });
103
+ }
104
+ function resolveSuggestionOptions(options) {
105
+ return {
106
+ maxDistance: options.maxDistance ?? 2,
107
+ maxSuggestions: options.maxSuggestions ?? 1,
108
+ includeOptions: options.includeOptions ?? true,
109
+ includeCommands: options.includeCommands ?? true,
110
+ distance: options.distance ?? levenshtein,
111
+ normalize: options.normalize ?? ((value) => value)
112
+ };
113
+ }
114
+ async function collectSuggestions(hints, seen, ctx, input, suggestNames) {
115
+ if (!input) return;
116
+ const suggestions = suggestNames(input.name, input.candidates);
117
+ for (const name of suggestions) {
118
+ const hint = localizeSuggestion(ctx, name);
119
+ if (!seen.has(hint)) {
120
+ seen.add(hint);
121
+ hints.push(hint);
122
+ }
123
+ }
124
+ }
125
+ function getUnknownOptionSuggestionInput(error) {
126
+ if (!isArgsValidationError(error) || error.code !== ArgsValidationErrorKeys.unknownOption) return;
127
+ const values = error.values;
128
+ if (typeof values.rawName !== "string" || !values.rawName.startsWith("--")) return;
129
+ if (typeof values.name !== "string" || !Array.isArray(values.candidates)) return;
130
+ const candidates = values.candidates.filter((candidate) => {
131
+ return typeof candidate === "string" && candidate.startsWith("--");
132
+ });
133
+ return candidates.length > 0 ? {
134
+ name: values.name,
135
+ candidates
136
+ } : void 0;
137
+ }
138
+ function getCommandSuggestionInput(error) {
139
+ if (!isCommandNotFoundError(error) || error.candidates.length === 0) return;
140
+ return {
141
+ name: error.commandName,
142
+ candidates: error.candidates
143
+ };
144
+ }
145
+ function localizeSuggestion(ctx, name) {
146
+ return (ctx.extensions?.[i18nPluginId])?.translate?.(SuggestionErrorKeys.didYouMean, { name }) || `Did you mean ${name}?`;
147
+ }
148
+ function normalizeSuggestionName(value) {
149
+ return value.startsWith("--") ? value.slice(2) : value;
150
+ }
151
+ //#endregion
152
+ export { SuggestionErrorKeys, defineSuggestNames, levenshtein, pluginId, suggestion };
package/package.json ADDED
@@ -0,0 +1,76 @@
1
+ {
2
+ "name": "@gunshi/plugin-suggestion",
3
+ "description": "suggestion plugin for gunshi",
4
+ "version": "0.35.2",
5
+ "author": {
6
+ "name": "kazuya kawaguchi",
7
+ "email": "kawakazu80@gmail.com"
8
+ },
9
+ "license": "MIT",
10
+ "funding": "https://github.com/sponsors/kazupon",
11
+ "bugs": {
12
+ "url": "https://github.com/kazupon/gunshi/issues"
13
+ },
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://github.com/kazupon/gunshi.git",
17
+ "directory": "packages/plugin-suggestion"
18
+ },
19
+ "keywords": [
20
+ "gunshi",
21
+ "suggestion",
22
+ "plugin",
23
+ "cli"
24
+ ],
25
+ "publishConfig": {
26
+ "access": "public"
27
+ },
28
+ "engines": {
29
+ "node": ">= 22"
30
+ },
31
+ "type": "module",
32
+ "files": [
33
+ "lib"
34
+ ],
35
+ "module": "lib/index.js",
36
+ "exports": {
37
+ ".": {
38
+ "types": "./lib/index.d.ts",
39
+ "import": "./lib/index.js",
40
+ "require": "./lib/index.js",
41
+ "default": "./lib/index.js"
42
+ },
43
+ "./package.json": "./package.json"
44
+ },
45
+ "types": "lib/index.d.ts",
46
+ "typesVersions": {
47
+ "*": {
48
+ "*": [
49
+ "./lib/*",
50
+ "./*"
51
+ ]
52
+ }
53
+ },
54
+ "dependencies": {
55
+ "@gunshi/plugin": "0.35.2"
56
+ },
57
+ "peerDependencies": {
58
+ "@gunshi/plugin-i18n": "0.35.2"
59
+ },
60
+ "devDependencies": {
61
+ "deno": "^2.7.14",
62
+ "jsr": "^0.14.3",
63
+ "jsr-exports-lint": "^0.4.2",
64
+ "publint": "^0.3.20",
65
+ "tsdown": "0.21.0",
66
+ "@gunshi/resources": "0.35.2",
67
+ "gunshi": "0.35.2",
68
+ "@gunshi/plugin-i18n": "0.35.2"
69
+ },
70
+ "scripts": {
71
+ "build": "tsdown",
72
+ "build:docs": "tsx ../../scripts/api-references.ts",
73
+ "lint:jsr": "jsr publish --dry-run --allow-dirty",
74
+ "typecheck:deno": "deno check --import-map=../../importmap.json ./src"
75
+ }
76
+ }