mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-11-22 08:03:40 +00:00
* chore(deps): bump fast-xml-parser and @aws-sdk/xml-builder Bumps [fast-xml-parser](https://github.com/NaturalIntelligence/fast-xml-parser) and [@aws-sdk/xml-builder](https://github.com/aws/aws-sdk-js-v3/tree/HEAD/packages-internal/xml-builder). These dependencies needed to be updated together. Updates `fast-xml-parser` from 5.3.4 to 5.5.8 - [Release notes](https://github.com/NaturalIntelligence/fast-xml-parser/releases) - [Changelog](https://github.com/NaturalIntelligence/fast-xml-parser/blob/master/CHANGELOG.md) - [Commits](https://github.com/NaturalIntelligence/fast-xml-parser/compare/v5.3.4...v5.5.8) Updates `@aws-sdk/xml-builder` from 3.972.4 to 3.972.18 - [Release notes](https://github.com/aws/aws-sdk-js-v3/releases) - [Changelog](https://github.com/aws/aws-sdk-js-v3/blob/main/packages-internal/xml-builder/CHANGELOG.md) - [Commits](https://github.com/aws/aws-sdk-js-v3/commits/HEAD/packages-internal/xml-builder) --- updated-dependencies: - dependency-name: fast-xml-parser dependency-version: 5.5.8 dependency-type: indirect - dependency-name: "@aws-sdk/xml-builder" dependency-version: 3.972.18 dependency-type: indirect ... Signed-off-by: dependabot[bot] <support@github.com> * chore(deps-dev): bump follow-redirects from 1.15.11 to 1.16.0 Bumps [follow-redirects](https://github.com/follow-redirects/follow-redirects) from 1.15.11 to 1.16.0. - [Release notes](https://github.com/follow-redirects/follow-redirects/releases) - [Commits](https://github.com/follow-redirects/follow-redirects/compare/v1.15.11...v1.16.0) --- updated-dependencies: - dependency-name: follow-redirects dependency-version: 1.16.0 dependency-type: indirect ... Signed-off-by: dependabot[bot] <support@github.com> * chore(deps): bump hono from 4.12.7 to 4.12.14 Bumps [hono](https://github.com/honojs/hono) from 4.12.7 to 4.12.14. - [Release notes](https://github.com/honojs/hono/releases) - [Commits](https://github.com/honojs/hono/compare/v4.12.7...v4.12.14) --- updated-dependencies: - dependency-name: hono dependency-version: 4.12.14 dependency-type: indirect ... Signed-off-by: dependabot[bot] <support@github.com> * chore(deps-dev): bump vite from 7.3.1 to 7.3.2 Bumps [vite](https://github.com/vitejs/vite/tree/HEAD/packages/vite) from 7.3.1 to 7.3.2. - [Release notes](https://github.com/vitejs/vite/releases) - [Changelog](https://github.com/vitejs/vite/blob/v7.3.2/packages/vite/CHANGELOG.md) - [Commits](https://github.com/vitejs/vite/commits/v7.3.2/packages/vite) --- updated-dependencies: - dependency-name: vite dependency-version: 7.3.2 dependency-type: direct:development ... Signed-off-by: dependabot[bot] <support@github.com> * chore(deps-dev): bump flatted from 3.3.3 to 3.4.2 Bumps [flatted](https://github.com/WebReflection/flatted) from 3.3.3 to 3.4.2. - [Commits](https://github.com/WebReflection/flatted/compare/v3.3.3...v3.4.2) --- updated-dependencies: - dependency-name: flatted dependency-version: 3.4.2 dependency-type: indirect ... Signed-off-by: dependabot[bot] <support@github.com> * chore(deps-dev): bump minimatch from 3.1.2 to 3.1.5 Bumps [minimatch](https://github.com/isaacs/minimatch) from 3.1.2 to 3.1.5. - [Changelog](https://github.com/isaacs/minimatch/blob/main/changelog.md) - [Commits](https://github.com/isaacs/minimatch/compare/v3.1.2...v3.1.5) --- updated-dependencies: - dependency-name: minimatch dependency-version: 3.1.5 dependency-type: indirect ... Signed-off-by: dependabot[bot] <support@github.com> * chore(deps-dev): bump lodash from 4.17.23 to 4.18.1 Bumps [lodash](https://github.com/lodash/lodash) from 4.17.23 to 4.18.1. - [Release notes](https://github.com/lodash/lodash/releases) - [Commits](https://github.com/lodash/lodash/compare/4.17.23...4.18.1) --- updated-dependencies: - dependency-name: lodash dependency-version: 4.18.1 dependency-type: indirect ... Signed-off-by: dependabot[bot] <support@github.com> * chore(deps): bump @hono/node-server from 1.19.11 to 1.19.14 Bumps [@hono/node-server](https://github.com/honojs/node-server) from 1.19.11 to 1.19.14. - [Release notes](https://github.com/honojs/node-server/releases) - [Commits](https://github.com/honojs/node-server/compare/v1.19.11...v1.19.14) --- updated-dependencies: - dependency-name: "@hono/node-server" dependency-version: 1.19.14 dependency-type: indirect ... Signed-off-by: dependabot[bot] <support@github.com> * chore(deps): bump rollup from 4.57.1 to 4.60.2 Bumps [rollup](https://github.com/rollup/rollup) from 4.57.1 to 4.60.2. - [Release notes](https://github.com/rollup/rollup/releases) - [Changelog](https://github.com/rollup/rollup/blob/master/CHANGELOG.md) - [Commits](https://github.com/rollup/rollup/compare/v4.57.1...v4.60.2) --- updated-dependencies: - dependency-name: rollup dependency-version: 4.60.2 dependency-type: indirect ... Signed-off-by: dependabot[bot] <support@github.com> * chore(deps-dev): bump electron from 40.1.0 to 40.8.5 Bumps [electron](https://github.com/electron/electron) from 40.1.0 to 40.8.5. - [Release notes](https://github.com/electron/electron/releases) - [Commits](https://github.com/electron/electron/compare/v40.1.0...v40.8.5) --- updated-dependencies: - dependency-name: electron dependency-version: 40.8.5 dependency-type: direct:development ... Signed-off-by: dependabot[bot] <support@github.com> * chore(deps): bump path-to-regexp from 8.3.0 to 8.4.2 Bumps [path-to-regexp](https://github.com/pillarjs/path-to-regexp) from 8.3.0 to 8.4.2. - [Release notes](https://github.com/pillarjs/path-to-regexp/releases) - [Changelog](https://github.com/pillarjs/path-to-regexp/blob/master/History.md) - [Commits](https://github.com/pillarjs/path-to-regexp/compare/v8.3.0...v8.4.2) --- updated-dependencies: - dependency-name: path-to-regexp dependency-version: 8.4.2 dependency-type: indirect ... Signed-off-by: dependabot[bot] <support@github.com> * chore(deps-dev): bump picomatch from 2.3.1 to 2.3.2 Bumps [picomatch](https://github.com/micromatch/picomatch) from 2.3.1 to 2.3.2. - [Release notes](https://github.com/micromatch/picomatch/releases) - [Changelog](https://github.com/micromatch/picomatch/blob/master/CHANGELOG.md) - [Commits](https://github.com/micromatch/picomatch/compare/2.3.1...2.3.2) --- updated-dependencies: - dependency-name: picomatch dependency-version: 2.3.2 dependency-type: indirect ... Signed-off-by: dependabot[bot] <support@github.com> * chore(deps): bump yaml from 2.8.2 to 2.8.3 Bumps [yaml](https://github.com/eemeli/yaml) from 2.8.2 to 2.8.3. - [Release notes](https://github.com/eemeli/yaml/releases) - [Commits](https://github.com/eemeli/yaml/compare/v2.8.2...v2.8.3) --- updated-dependencies: - dependency-name: yaml dependency-version: 2.8.3 dependency-type: indirect ... Signed-off-by: dependabot[bot] <support@github.com> * chore(deps-dev): bump @xmldom/xmldom from 0.8.11 to 0.8.13 Bumps [@xmldom/xmldom](https://github.com/xmldom/xmldom) from 0.8.11 to 0.8.13. - [Release notes](https://github.com/xmldom/xmldom/releases) - [Changelog](https://github.com/xmldom/xmldom/blob/master/CHANGELOG.md) - [Commits](https://github.com/xmldom/xmldom/compare/0.8.11...0.8.13) --- updated-dependencies: - dependency-name: "@xmldom/xmldom" dependency-version: 0.8.13 dependency-type: indirect ... Signed-off-by: dependabot[bot] <support@github.com> * chore(deps-dev): bump brace-expansion from 1.1.12 to 1.1.14 Bumps [brace-expansion](https://github.com/juliangruber/brace-expansion) from 1.1.12 to 1.1.14. - [Release notes](https://github.com/juliangruber/brace-expansion/releases) - [Commits](https://github.com/juliangruber/brace-expansion/compare/v1.1.12...v1.1.14) --- updated-dependencies: - dependency-name: brace-expansion dependency-version: 1.1.14 dependency-type: indirect ... Signed-off-by: dependabot[bot] <support@github.com> * chore(deps-dev): bump tar from 7.5.7 to 7.5.13 Bumps [tar](https://github.com/isaacs/node-tar) from 7.5.7 to 7.5.13. - [Release notes](https://github.com/isaacs/node-tar/releases) - [Changelog](https://github.com/isaacs/node-tar/blob/main/CHANGELOG.md) - [Commits](https://github.com/isaacs/node-tar/compare/v7.5.7...v7.5.13) --- updated-dependencies: - dependency-name: tar dependency-version: 7.5.13 dependency-type: indirect ... Signed-off-by: dependabot[bot] <support@github.com> * Security Fixes Security fixes: Added input validation for uncontrolled command lines. Added Proper Shell Escaping for useTerminalAutocomplete Fixed 4 race condition alerts by atomic stat+read(s) without following symlinks. Misc: Use Crypto randomness instead of Math.random() (Not a security issue but convenient) * Fix OS quirk fallbacks * Review fix - use lstat before open to skip FIFO/devices early to prevent blocks - SFTP skip UUID tag could be dubiously long * allow symlinks alongside regular files. * Use acutal target size for reading * Fix Destructed import / fix to use full shellEscape charset - Destructed import - Guard now matches full shellEscape charset * Supress Codex complaints Replaced manual fd.read with fs.promises.readFile(fd) to ensure complete file reads to EOF. --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
628 lines
18 KiB
TypeScript
628 lines
18 KiB
TypeScript
/**
|
|
* Context-aware completion engine.
|
|
* Combines multiple data sources:
|
|
* 1. Command history (highest priority)
|
|
* 2. @withfig/autocomplete specs (subcommands, options, args)
|
|
* 3. Fuzzy history matching (fallback)
|
|
*
|
|
* Parses the current command line to determine context (command, subcommand,
|
|
* option, or argument position) and provides appropriate suggestions.
|
|
*/
|
|
|
|
import {
|
|
queryHistory,
|
|
queryRecentHistoryByCommand,
|
|
fuzzyQueryHistory,
|
|
type HistoryQueryOptions,
|
|
} from "./commandHistoryStore";
|
|
import {
|
|
loadSpec,
|
|
hasSpec,
|
|
getAvailableSpecs,
|
|
normalizeCommandName,
|
|
resolveNames,
|
|
type FigSpec,
|
|
type FigSubcommand,
|
|
type FigOption,
|
|
} from "./figSpecLoader";
|
|
import {
|
|
shouldDoPathCompletion,
|
|
getPathSuggestions,
|
|
resolvePathComponents,
|
|
} from "./remotePathCompleter";
|
|
|
|
/** Source indicator for where a suggestion came from */
|
|
export type SuggestionSource = "history" | "command" | "subcommand" | "option" | "arg" | "path";
|
|
|
|
export interface CompletionSuggestion {
|
|
/** The text to insert */
|
|
text: string;
|
|
/** Display text (may differ from insert text) */
|
|
displayText: string;
|
|
/** Optional description */
|
|
description?: string;
|
|
/** Source of this suggestion */
|
|
source: SuggestionSource;
|
|
/** Relevance score (higher = more relevant) */
|
|
score: number;
|
|
/** For history entries: execution frequency */
|
|
frequency?: number;
|
|
/** For path suggestions: file type */
|
|
fileType?: "file" | "directory" | "symlink";
|
|
}
|
|
|
|
export interface CompletionContext {
|
|
/** Full command line text */
|
|
commandLine: string;
|
|
/** Current word being typed */
|
|
currentWord: string;
|
|
/** Index of the current word in the parsed tokens */
|
|
wordIndex: number;
|
|
/** Parsed command tokens */
|
|
tokens: string[];
|
|
/** The base command name (first token) */
|
|
commandName: string;
|
|
/** Whether the current position is after a recognized option that expects an argument */
|
|
isOptionArg: boolean;
|
|
}
|
|
|
|
export function shellEscape(name: string): string {
|
|
if (!name) return name;
|
|
if (/[\\$'"|!<>;#~` ]/.test(name)) {
|
|
return `'${name.replace(/'/g, "'\\''")}'`;
|
|
}
|
|
return name;
|
|
}
|
|
|
|
/**
|
|
* Parse a command line string into tokens, handling quoting.
|
|
*/
|
|
function tokenize(input: string): string[] {
|
|
const tokens: string[] = [];
|
|
let current = "";
|
|
let inSingleQuote = false;
|
|
let inDoubleQuote = false;
|
|
let escaped = false;
|
|
|
|
for (let i = 0; i < input.length; i++) {
|
|
const ch = input[i];
|
|
|
|
if (escaped) {
|
|
current += ch;
|
|
escaped = false;
|
|
continue;
|
|
}
|
|
|
|
if (ch === "\\") {
|
|
escaped = true;
|
|
current += ch;
|
|
continue;
|
|
}
|
|
|
|
if (ch === "'" && !inDoubleQuote) {
|
|
inSingleQuote = !inSingleQuote;
|
|
current += ch;
|
|
continue;
|
|
}
|
|
|
|
if (ch === '"' && !inSingleQuote) {
|
|
inDoubleQuote = !inDoubleQuote;
|
|
current += ch;
|
|
continue;
|
|
}
|
|
|
|
if (ch === " " && !inSingleQuote && !inDoubleQuote) {
|
|
if (current.length > 0) {
|
|
tokens.push(current);
|
|
current = "";
|
|
}
|
|
continue;
|
|
}
|
|
|
|
current += ch;
|
|
}
|
|
|
|
// Always include the last token (even if empty, to indicate trailing space)
|
|
tokens.push(current);
|
|
|
|
return tokens;
|
|
}
|
|
|
|
/**
|
|
* Parse the current command line into a CompletionContext.
|
|
*/
|
|
export function parseCommandLine(input: string): CompletionContext {
|
|
const tokens = tokenize(input);
|
|
const wordIndex = tokens.length - 1;
|
|
const currentWord = tokens[wordIndex] || "";
|
|
const commandName = tokens.length > 0 ? normalizeCommandName(tokens[0]) : "";
|
|
|
|
return {
|
|
commandLine: input,
|
|
currentWord,
|
|
wordIndex,
|
|
tokens,
|
|
commandName,
|
|
isOptionArg: false,
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Main completion function. Returns sorted suggestions from all sources.
|
|
* Ghost text should use completions[0].text instead of a separate query.
|
|
*/
|
|
export async function getCompletions(
|
|
input: string,
|
|
options: {
|
|
hostId?: string;
|
|
os?: "linux" | "windows" | "macos";
|
|
maxResults?: number;
|
|
/** Session ID for remote path completion */
|
|
sessionId?: string;
|
|
/** Connection protocol (ssh, local, telnet, serial) */
|
|
protocol?: string;
|
|
/** Current working directory (from OSC 7) */
|
|
cwd?: string;
|
|
} = {},
|
|
): Promise<CompletionSuggestion[]> {
|
|
const { hostId, maxResults = 15 } = options;
|
|
|
|
if (!input || input.trim().length === 0) return [];
|
|
|
|
const ctx = parseCommandLine(input);
|
|
const suggestions: CompletionSuggestion[] = [];
|
|
const seenSuggestionTexts = new Set<string>();
|
|
const pathCheck = ctx.commandName && ctx.wordIndex >= 1
|
|
? shouldDoPathCompletion(ctx, undefined)
|
|
: { shouldComplete: false, foldersOnly: false };
|
|
const preferPathSuggestions = pathCheck.shouldComplete;
|
|
const resultLimit = preferPathSuggestions ? Math.max(maxResults, 24) : maxResults;
|
|
|
|
// 1. History suggestions (full command line prefix match)
|
|
// Cap history to leave room for spec suggestions in the popup
|
|
const historyOpts: HistoryQueryOptions = {
|
|
hostId,
|
|
limit: preferPathSuggestions ? 0 : 5,
|
|
};
|
|
|
|
const historyMatches = queryHistory(input, historyOpts);
|
|
for (const entry of historyMatches) {
|
|
const suggestion = {
|
|
text: entry.command,
|
|
displayText: entry.command,
|
|
source: "history",
|
|
score: 1000 + entry.frequency,
|
|
frequency: entry.frequency,
|
|
} satisfies CompletionSuggestion;
|
|
suggestions.push(suggestion);
|
|
seenSuggestionTexts.add(suggestion.text);
|
|
}
|
|
|
|
if (preferPathSuggestions && ctx.commandName) {
|
|
// When path completion is active (file-related commands like cat, vim, cd),
|
|
// recent history is still useful but should rank below actual path matches
|
|
// from the current directory.
|
|
const recentHistory = queryRecentHistoryByCommand({
|
|
commandName: ctx.commandName,
|
|
excludeCommand: input,
|
|
argumentPrefix: normalizeHistoryPathPrefix(ctx.currentWord),
|
|
hostId,
|
|
limit: 5,
|
|
});
|
|
for (let index = 0; index < recentHistory.length; index++) {
|
|
const entry = recentHistory[index];
|
|
if (seenSuggestionTexts.has(entry.command)) continue;
|
|
const suggestion = {
|
|
text: entry.command,
|
|
displayText: entry.command,
|
|
source: "history",
|
|
score: 720 - index,
|
|
frequency: entry.frequency,
|
|
} satisfies CompletionSuggestion;
|
|
suggestions.push(suggestion);
|
|
seenSuggestionTexts.add(suggestion.text);
|
|
}
|
|
}
|
|
|
|
const canQueryPaths = options.protocol === "local" || options.sessionId !== undefined;
|
|
|
|
const specPromise = ctx.commandName && ctx.wordIndex >= 0
|
|
? getSpecSuggestions(ctx)
|
|
: Promise.resolve([]);
|
|
const pathPromise = canQueryPaths && pathCheck.shouldComplete
|
|
? getPathSuggestions(ctx, {
|
|
sessionId: options.sessionId,
|
|
protocol: options.protocol,
|
|
cwd: options.cwd,
|
|
foldersOnly: pathCheck.foldersOnly,
|
|
})
|
|
: Promise.resolve([]);
|
|
|
|
const [specSugs, pathEntries] = await Promise.all([specPromise, pathPromise]);
|
|
|
|
for (const suggestion of specSugs) {
|
|
suggestions.push(suggestion);
|
|
seenSuggestionTexts.add(suggestion.text);
|
|
}
|
|
|
|
if (pathEntries.length > 0) {
|
|
const { pathPrefix, quoteSuffix } = resolvePathComponents(ctx.currentWord, options.cwd);
|
|
const isQuotedPath = ctx.currentWord.startsWith('"') || ctx.currentWord.startsWith("'");
|
|
for (const entry of pathEntries) {
|
|
const insertName = isQuotedPath || !/[\\$'"|!<>;#~` ]/.test(entry.name)
|
|
? entry.name
|
|
: shellEscape(entry.name);
|
|
const suffix = entry.type === "directory" ? "/" : "";
|
|
const fullPath = pathPrefix + insertName + suffix + quoteSuffix;
|
|
const suggestion = {
|
|
text: rebuildCommand(ctx.tokens, ctx.wordIndex, fullPath),
|
|
displayText: entry.name + suffix,
|
|
source: "path",
|
|
score: 750,
|
|
fileType: entry.type,
|
|
} satisfies CompletionSuggestion;
|
|
suggestions.push(suggestion);
|
|
seenSuggestionTexts.add(suggestion.text);
|
|
}
|
|
}
|
|
|
|
// 3. Fuzzy history fallback (if prefix match yields few results)
|
|
if (!preferPathSuggestions && suggestions.length < 3 && input.length >= 2) {
|
|
const fuzzyMatches = fuzzyQueryHistory(input, {
|
|
...historyOpts,
|
|
limit: 5,
|
|
});
|
|
for (const entry of fuzzyMatches) {
|
|
if (seenSuggestionTexts.has(entry.command)) continue;
|
|
const suggestion = {
|
|
text: entry.command,
|
|
displayText: entry.command,
|
|
source: "history",
|
|
score: 500 + entry.frequency,
|
|
frequency: entry.frequency,
|
|
} satisfies CompletionSuggestion;
|
|
suggestions.push(suggestion);
|
|
seenSuggestionTexts.add(suggestion.text);
|
|
}
|
|
}
|
|
|
|
// Sort by score descending
|
|
suggestions.sort((a, b) => b.score - a.score);
|
|
|
|
// Deduplicate
|
|
const seen = new Set<string>();
|
|
const unique: CompletionSuggestion[] = [];
|
|
for (const s of suggestions) {
|
|
if (seen.has(s.text)) continue;
|
|
seen.add(s.text);
|
|
unique.push(s);
|
|
if (unique.length >= resultLimit) break;
|
|
}
|
|
|
|
return unique;
|
|
}
|
|
|
|
function normalizeHistoryPathPrefix(token: string): string {
|
|
return token
|
|
.trim()
|
|
.replace(/^['"]/, "")
|
|
.replace(/['"]$/, "")
|
|
.replace(/\\ /g, " ");
|
|
}
|
|
|
|
/**
|
|
* Get suggestions from Fig spec + return resolved args (for path detection reuse).
|
|
*/
|
|
async function getSpecSuggestions(ctx: CompletionContext): Promise<CompletionSuggestion[]> {
|
|
const suggestions: CompletionSuggestion[] = [];
|
|
|
|
const specAvailable = await hasSpec(ctx.commandName);
|
|
if (!specAvailable) {
|
|
if (ctx.wordIndex === 0 && ctx.currentWord.length >= 1) {
|
|
return await getCommandNameSuggestions(ctx.currentWord);
|
|
}
|
|
return [];
|
|
}
|
|
|
|
const spec = await loadSpec(ctx.commandName);
|
|
if (!spec) return [];
|
|
|
|
// If we're still typing the command name (partial match, not yet complete)
|
|
if (ctx.wordIndex === 0) {
|
|
const typedLower = ctx.currentWord.toLowerCase();
|
|
const specNames = resolveNames(spec.name);
|
|
const isExactMatch = specNames.some((n) => n.toLowerCase() === typedLower);
|
|
if (!isExactMatch) return [];
|
|
|
|
// Show subcommands as preview (user typed full command but no space yet)
|
|
if (spec.subcommands) {
|
|
for (const sub of spec.subcommands) {
|
|
const names = resolveNames(sub.name);
|
|
suggestions.push({
|
|
text: ctx.currentWord + " " + names[0],
|
|
displayText: names[0],
|
|
description: sub.description,
|
|
source: "subcommand",
|
|
score: 800,
|
|
});
|
|
if (suggestions.length >= 10) break;
|
|
}
|
|
}
|
|
return suggestions;
|
|
}
|
|
|
|
// Navigate the spec tree based on typed tokens
|
|
let resolved = resolveSpecContext(spec, ctx.tokens.slice(1, ctx.wordIndex));
|
|
const currentToken = ctx.currentWord;
|
|
|
|
// Check if currentToken exactly matches a subcommand — if so, navigate into it
|
|
// and show its children as preview (e.g., "git commit" shows commit's options)
|
|
if (currentToken && resolved.subcommands) {
|
|
const exactMatch = resolved.subcommands.find((s) => {
|
|
const names = resolveNames(s.name);
|
|
return names.includes(currentToken);
|
|
});
|
|
if (exactMatch) {
|
|
// Navigate into the matched subcommand and show its children
|
|
const childResolved = resolveSpecContext(spec, ctx.tokens.slice(1, ctx.wordIndex + 1));
|
|
|
|
// Show child subcommands
|
|
if (childResolved.subcommands) {
|
|
for (const sub of childResolved.subcommands) {
|
|
const names = resolveNames(sub.name);
|
|
suggestions.push({
|
|
text: ctx.commandLine + " " + names[0],
|
|
displayText: names[0],
|
|
description: sub.description,
|
|
source: "subcommand",
|
|
score: 800,
|
|
});
|
|
if (suggestions.length >= 10) break;
|
|
}
|
|
}
|
|
// Show child options
|
|
appendOptionPreviewSuggestions(
|
|
suggestions,
|
|
ctx.commandLine,
|
|
childResolved.options?.length ? childResolved.options : childResolved.fallbackOptions,
|
|
15,
|
|
);
|
|
return suggestions;
|
|
}
|
|
}
|
|
|
|
// Suggest subcommands (prefix match, excluding exact matches)
|
|
if (resolved.subcommands) {
|
|
for (const sub of resolved.subcommands) {
|
|
const names = resolveNames(sub.name);
|
|
for (const name of names) {
|
|
if (name.startsWith(currentToken) && name !== currentToken) {
|
|
suggestions.push({
|
|
text: rebuildCommand(ctx.tokens, ctx.wordIndex, name),
|
|
displayText: name,
|
|
description: sub.description,
|
|
source: "subcommand",
|
|
score: 800,
|
|
});
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// Suggest options
|
|
const hasDirectOptionSuggestions = appendOptionSuggestions(
|
|
suggestions,
|
|
ctx,
|
|
currentToken,
|
|
resolved.options,
|
|
);
|
|
if (!hasDirectOptionSuggestions) {
|
|
appendOptionSuggestions(suggestions, ctx, currentToken, resolved.fallbackOptions);
|
|
}
|
|
|
|
// Suggest argument values from suggestions in the spec
|
|
if (resolved.args) {
|
|
const args = Array.isArray(resolved.args) ? resolved.args : [resolved.args];
|
|
for (const arg of args) {
|
|
if (arg.suggestions) {
|
|
for (const sug of arg.suggestions) {
|
|
const sugName = typeof sug === "string" ? sug : (Array.isArray(sug.name) ? sug.name[0] : sug.name);
|
|
const sugDesc = typeof sug === "string" ? undefined : sug.description;
|
|
if (sugName.startsWith(currentToken) && sugName !== currentToken) {
|
|
suggestions.push({
|
|
text: rebuildCommand(ctx.tokens, ctx.wordIndex, sugName),
|
|
displayText: sugName,
|
|
description: sugDesc,
|
|
source: "arg",
|
|
score: 600,
|
|
});
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
return suggestions;
|
|
}
|
|
|
|
/**
|
|
* Get command name suggestions by matching against available specs.
|
|
* Uses the already-imported getAvailableSpecs directly (no dynamic self-import).
|
|
*/
|
|
async function getCommandNameSuggestions(prefix: string): Promise<CompletionSuggestion[]> {
|
|
const specs = await getAvailableSpecs();
|
|
const lower = prefix.toLowerCase();
|
|
const suggestions: CompletionSuggestion[] = [];
|
|
|
|
for (const name of specs) {
|
|
// Skip sub-path specs like "aws/s3", "dotnet/dotnet-build" — not direct shell commands
|
|
if (name.includes("/")) continue;
|
|
if (name.startsWith(lower) && name !== lower) {
|
|
suggestions.push({
|
|
text: name,
|
|
displayText: name,
|
|
source: "command",
|
|
score: 600,
|
|
});
|
|
if (suggestions.length >= 10) break;
|
|
}
|
|
}
|
|
|
|
return suggestions;
|
|
}
|
|
|
|
interface ResolvedContext {
|
|
subcommands?: FigSubcommand[];
|
|
options?: FigOption[];
|
|
fallbackOptions?: FigOption[];
|
|
args?: FigSubcommand["args"];
|
|
}
|
|
|
|
/**
|
|
* Walk the spec tree following the typed tokens to find the current context.
|
|
* Handles options with arguments (e.g., --name value) by skipping the value token.
|
|
*/
|
|
function resolveSpecContext(spec: FigSpec, consumedTokens: string[]): ResolvedContext {
|
|
let current: FigSubcommand = spec;
|
|
let inheritedOptions: FigOption[] = [];
|
|
let skipNext = false;
|
|
let lastOptionArgs: FigSubcommand["args"] | undefined;
|
|
|
|
for (const token of consumedTokens) {
|
|
// Skip this token if it's the argument value of a previous option
|
|
if (skipNext) {
|
|
skipNext = false;
|
|
lastOptionArgs = undefined;
|
|
continue;
|
|
}
|
|
|
|
// Handle option flags
|
|
if (token.startsWith("-")) {
|
|
// Check if this option expects an argument
|
|
const opt = [...(current.options ?? []), ...inheritedOptions].find((candidate) => {
|
|
const names = resolveNames(candidate.name);
|
|
return names.includes(token);
|
|
});
|
|
if (opt?.args) {
|
|
// This option expects an argument — the next token is its value
|
|
const args = Array.isArray(opt.args) ? opt.args : [opt.args];
|
|
if (args.length > 0 && !args[0].isOptional) {
|
|
skipNext = true;
|
|
lastOptionArgs = opt.args; // Track for the case where next token is currentWord
|
|
}
|
|
}
|
|
continue;
|
|
}
|
|
|
|
// Try to find a matching subcommand
|
|
if (current.subcommands) {
|
|
const sub = current.subcommands.find((s) => {
|
|
const names = resolveNames(s.name);
|
|
return names.includes(token);
|
|
});
|
|
if (sub) {
|
|
inheritedOptions = mergeOptionLists(inheritedOptions, current.options);
|
|
current = sub;
|
|
continue;
|
|
}
|
|
}
|
|
|
|
// If no subcommand matched, we're at the args level
|
|
break;
|
|
}
|
|
|
|
// If skipNext is still true, the currentWord is an option's arg value
|
|
// (e.g., "git archive --format |" — currentWord is the format value)
|
|
// Return the option's args instead of the subcommand's args.
|
|
if (skipNext && lastOptionArgs) {
|
|
return {
|
|
subcommands: undefined,
|
|
options: undefined,
|
|
fallbackOptions: inheritedOptions.length > 0 ? inheritedOptions : undefined,
|
|
args: lastOptionArgs,
|
|
};
|
|
}
|
|
|
|
return {
|
|
subcommands: current.subcommands,
|
|
options: current.options ? [...current.options] : undefined,
|
|
fallbackOptions: inheritedOptions.length > 0 ? inheritedOptions : undefined,
|
|
args: current.args,
|
|
};
|
|
}
|
|
|
|
function mergeOptionLists(
|
|
left: FigOption[] | undefined,
|
|
right: FigOption[] | undefined,
|
|
): FigOption[] {
|
|
const merged: FigOption[] = [];
|
|
const seen = new Set<string>();
|
|
|
|
for (const option of [...(left ?? []), ...(right ?? [])]) {
|
|
const key = resolveNames(option.name).sort().join("\0");
|
|
if (seen.has(key)) continue;
|
|
seen.add(key);
|
|
merged.push(option);
|
|
}
|
|
|
|
return merged;
|
|
}
|
|
|
|
function appendOptionSuggestions(
|
|
suggestions: CompletionSuggestion[],
|
|
ctx: CompletionContext,
|
|
currentToken: string,
|
|
options: FigOption[] | undefined,
|
|
): boolean {
|
|
if (!options || options.length === 0) return false;
|
|
|
|
let added = false;
|
|
for (const opt of options) {
|
|
const names = resolveNames(opt.name);
|
|
for (const name of names) {
|
|
if (name.startsWith(currentToken) && name !== currentToken) {
|
|
suggestions.push({
|
|
text: rebuildCommand(ctx.tokens, ctx.wordIndex, name),
|
|
displayText: name,
|
|
description: opt.description,
|
|
source: "option",
|
|
score: 700,
|
|
});
|
|
added = true;
|
|
}
|
|
}
|
|
}
|
|
|
|
return added;
|
|
}
|
|
|
|
function appendOptionPreviewSuggestions(
|
|
suggestions: CompletionSuggestion[],
|
|
commandLine: string,
|
|
options: FigOption[] | undefined,
|
|
limit: number,
|
|
): void {
|
|
if (!options || options.length === 0 || suggestions.length >= limit) return;
|
|
|
|
for (const opt of options) {
|
|
const names = resolveNames(opt.name);
|
|
suggestions.push({
|
|
text: commandLine + " " + names[0],
|
|
displayText: names[0],
|
|
description: opt.description,
|
|
source: "option",
|
|
score: 700,
|
|
});
|
|
if (suggestions.length >= limit) break;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Rebuild the full command text with a replacement at a specific token index.
|
|
*/
|
|
function rebuildCommand(tokens: string[], replaceIndex: number, replacement: string): string {
|
|
const rebuilt = [...tokens];
|
|
rebuilt[replaceIndex] = replacement;
|
|
return rebuilt.join(" ");
|
|
}
|