Debian Codegraph @

types/index.d.ts

raw symbols SCIP
1 /* eslint-disable @typescript-eslint/ban-types */
2 declare namespace Fig {
3 /**
4 * Templates are generators prebuilt by Fig.
5 * @remarks
6 * Here are the three templates:
7 * - filepaths: show folders and filepaths. Allow autoexecute on filepaths
8 * - folders: show folders only. Allow autoexecute on folders
9 * - history: show suggestions for all items in history matching this pattern
10 * - help: show subcommands. Only includes the 'siblings' of the nearest 'parent' subcommand
11 */
12 type TemplateStrings = "filepaths" | "folders" | "history" | "help";
13
14 /**
15 * A template which is a single TemplateString or an array of TemplateStrings
16 *
17 * @remarks
18 * Templates are generators prebuilt by Fig. Here are the three templates:
19 * - filepaths: show folders and filepaths. Allow autoexecute on filepaths
20 * - folders: show folders only. Allow autoexecute on folders
21 * - history: show suggestions for all items in history matching this pattern
22 * - help: show subcommands. Only includes the 'siblings' of the nearest 'parent' subcommand
23 *
24 * @example
25 * `cd` uses the "folders" template
26 * `ls` used ["filepaths", "folders"]. Why both? Because if I `ls` a directory, we want to enable a user to autoexecute on this directory. If we just did "filepaths" they couldn't autoexecute.
27 *
28 */
29 type Template = TemplateStrings | TemplateStrings[];
30
31 type HistoryContext = {
32 currentWorkingDirectory: string;
33 time: number;
34 exitCode: number;
35 shell: string;
36 };
37
38 type TemplateSuggestionContext =
39 | { templateType: "filepaths" }
40 | { templateType: "folders" }
41 | { templateType: "help" }
42 | ({ templateType: "history" } & Partial<HistoryContext>);
43
44 type TemplateSuggestion = Modify<
45 Suggestion,
46 { name?: string; context: TemplateSuggestionContext }
47 >;
48
49 /**
50 *
51 * The SpecLocation object defines well... the location of the completion spec we want to load.
52 * Specs can be "global" (ie hosted by Fig's cloud) or "local" (ie stored on your local machine)
53 *
54 * @remarks
55 * **The `SpecLocation` Object**
56 *
57 * The SpecLocation object defines well... the location of the completion spec we want to load.
58 * Specs can be "global" (ie hosted by Fig's cloud) or "local" (ie stored on your local machine).
59 *
60 * - Global `SpecLocation`:
61 * Load specs hosted in Fig's Cloud. Assume the current working directory is here: https://github.com/withfig/autocomplete/tree/master/src. Now set the value for the "name" prop to the relative location of your spec (without the .js file extension)
62 * ```js
63 * // e.g.
64 * { type: "global", name: "aws/s3" } // Loads up the aws s3 completion spec
65 * { type: "global", name: "python/http.server" } // Loads up the http.server completion spec
66 * ```
67 *
68 * - Local `SpecLocation`:
69 * Load specs saved on your local system / machine. Assume the current working directory is the user's current working directory.
70 * The `name` prop should take the name of the spec (without the .js file extension) e.g. my_cli_tool
71 * The `path` prop should take an absolute path OR a relative path (relative to the user's current working directory). The path should be to the directory that contains the `.fig` folder. Fig will then assume your spec is located in `.fig/autocomplete/build/`
72 * ```js
73 * // e.g.
74 * { type: "global", path: "node_modules/cowsay", name: "cowsay_cli" } // will look for `cwd/node_modules/cowsay/.fig/autocomplete/build/cowsay_cli.js`
75 * { type: "global", path: "~", name: "my_cli" } // will look for `~/.fig/autocomplete/build/my_cli.js`
76 * ```
77 * @irreplaceable
78 */
79 type SpecLocation =
80 | { type: "local"; path?: string; name: string }
81 | { type: "global"; name: string };
82
83 /**
84 * Dynamically load up another completion spec at runtime.
85 *
86 * See [`loadSpec` property in Subcommand Object](https://fig.io/docs/reference/subcommand#loadspec).
87 */
88 type LoadSpec =
89 | string
90 | Subcommand
91 | ((
92 token: string,
93 executeCommand: ExecuteCommandFunction
94 ) => Promise<SpecLocation | SpecLocation[] | Subcommand>);
95
96 /**
97 * The type of a suggestion object.
98 * @remarks
99 * The type determines:
100 * - the default icon Fig uses (e.g. a file or folder searches for the system icon, a subcommand has a specific icon etc)
101 * - whether we allow users to auto-execute a command
102 */
103 type SuggestionType =
104 | "folder"
105 | "file"
106 | "arg"
107 | "subcommand"
108 | "option"
109 | "special"
110 | "mixin"
111 | "shortcut";
112
113 /**
114 * A single object of type `T` or an array of objects of type `T`.
115 */
116 type SingleOrArray<T> = T | T[];
117
118 /**
119 * An async function that returns the version of a given CLI tool.
120 * @remarks
121 * This is used in completion specs that want to version themselves the same way CLI tools are versioned. See fig.io/docs
122 *
123 * @param executeCommand -an async function that allows you to execute a shell command on the user's system and get the output as a string.
124 * @returns The version of a CLI tool
125 *
126 * @example
127 * `1.0.22`
128 *
129 * @example
130 * `v26`
131 *
132 */
133 type GetVersionCommand = (executeCommand: ExecuteCommandFunction) => Promise<string>;
134
135 /**
136 * Context about a current shell session.
137 */
138 type ShellContext = {
139 /**
140 * The current directory the shell is in
141 */
142 currentWorkingDirectory: string;
143 /**
144 * Exported environment variables from the shell
145 */
146 environmentVariables: Record<string, string>;
147 /**
148 * The name of the current process
149 */
150 currentProcess: string;
151 /**
152 * @hidden
153 * @deprecated
154 */
155 sshPrefix: string;
156 };
157
158 type GeneratorContext = ShellContext & {
159 isDangerous?: boolean;
160 searchTerm: string;
161 };
162
163 /**
164 * A function which can have a `T` argument and a `R` result.
165 * @param param - A param of type `R`
166 * @returns Something of type `R`
167 */
168 type Function<T = void, R = void> = (param: T) => R;
169
170 /**
171 * A utility type to modify a property type
172 * @irreplaceable
173 */
174 type Modify<T, R> = Omit<T, keyof R> & R;
175
176 /**
177 * A `string` OR a `function` which can have a `T` argument and a `R` result.
178 * @param param - A param of type `R`
179 * @returns Something of type `R`
180 */
181 type StringOrFunction<T = void, R = void> = string | Function<T, R>;
182
183 /**
184 * @excluded
185 * @irreplaceable
186 */
187 type ArgDiff = Modify<Fig.Arg, { remove?: true }>;
188
189 /**
190 * @excluded
191 * @irreplaceable
192 */
193 type OptionDiff = Modify<
194 Fig.Option,
195 {
196 args?: ArgDiff | ArgDiff[];
197 remove?: true;
198 }
199 >;
200
201 /**
202 * @excluded
203 * @irreplaceable
204 */
205 type SubcommandDiff = Modify<
206 Fig.Subcommand,
207 {
208 subcommands?: SubcommandDiff[];
209 options?: OptionDiff[];
210 args?: ArgDiff | ArgDiff[];
211 remove?: true;
212 }
213 >;
214
215 /**
216 * @excluded
217 * @irreplaceable
218 */
219 type SpecDiff = Omit<SubcommandDiff, "name" | "remove">;
220
221 /**
222 * @excluded
223 * @irreplaceable
224 */
225 type VersionDiffMap = Record<string, SpecDiff>;
226
227 /**
228 * A spec object.
229 * Can be one of
230 * 1. A subcommand
231 * 2. A function that dynamically computes a subcommand
232 * 3. A function that returns the path to a versioned spec files (that exports a base subcommand and { versions: VersionDiffMap }
233 */
234 type Spec =
235 | Subcommand
236 | ((version?: string) => Subcommand)
237 | ((version?: string) => {
238 versionedSpecPath: string;
239 version?: string;
240 });
241
242 type ExecuteCommandInput = {
243 /**
244 * The command to execute
245 */
246 command: string;
247 /**
248 * The arguments to the command to be run
249 */
250 args: string[];
251 /**
252 * The directory to run the command in
253 */
254 cwd?: string;
255 /**
256 * The environment variables to set when executing the command, `undefined` will unset the variable if it set
257 */
258 env?: Record<string, string | undefined>;
259 /**
260 * Duration of timeout in milliseconds, if the command takes longer than the timeout a error will be thrown.
261 * @defaultValue 5000
262 */
263 timeout?: number;
264 };
265
266 /**
267 * The output of running a command
268 */
269 type ExecuteCommandOutput = {
270 /**
271 * The stdout (1) of running a command
272 */
273 stdout: string;
274 /**
275 * The stderr (2) of running a command
276 */
277 stderr: string;
278 /**
279 * The exit status of running a command
280 */
281 status: number;
282 };
283
284 /**
285 * An async function to execute a command
286 * @returns The output of the command
287 */
288 type ExecuteCommandFunction = (args: ExecuteCommandInput) => Promise<ExecuteCommandOutput>;
289
290 type CacheMaxAge = {
291 strategy: "max-age";
292 /**
293 * The time to live for the cache in milliseconds.
294 * @example
295 * 3600
296 */
297 ttl: number;
298 };
299
300 type CacheStaleWhileRevalidate = {
301 strategy?: "stale-while-revalidate";
302 /**
303 * The time to live for the cache in milliseconds.
304 * @example
305 * 3600
306 */
307 ttl?: number;
308 };
309
310 type Cache = (CacheMaxAge | CacheStaleWhileRevalidate) & {
311 /**
312 * Whether the cache should be based on the directory the user was currently in or not.
313 * @defaultValue false
314 */
315 cacheByDirectory?: boolean;
316
317 /**
318 * Hardcoded cache key that can be used to cache a single generator across
319 * multiple argument locations in a spec.
320 */
321 cacheKey?: string;
322 };
323
324 type TriggerOnChange = {
325 /** Trigger on any change to the token */
326 on: "change";
327 };
328
329 type TriggerOnThreshold = {
330 /** Trigger when the length of the token changes past a threshold */
331 on: "threshold";
332 length: number;
333 };
334
335 type TriggerOnMatch = {
336 /** Trigger when the index of a string changes */
337 on: "match";
338 string: string | string[];
339 };
340
341 type Trigger =
342 | string
343 | ((newToken: string, oldToken: string) => boolean)
344 | TriggerOnChange
345 | TriggerOnThreshold
346 | TriggerOnMatch;
347
348 /**
349 * The BaseSuggestion object is the root of the Suggestion, Subcommand, and Option objects.
350 * It is where key properties like description, icon, and displayName are found
351 * @excluded
352 */
353 interface BaseSuggestion {
354 /**
355 * The string that is displayed in the UI for a given suggestion.
356 * @defaultValue the name prop
357 *
358 * @example
359 * The npm CLI has a subcommand called `install`. If we wanted
360 * to display some custom text like `Install an NPM package 📦` we would set
361 * `name: "install"` and `displayName: "Install an NPM package 📦"`
362 */
363 displayName?: string;
364 /**
365 * The value that's inserted into the terminal when a user presses enter/tab or clicks on a menu item.
366 *
367 * @remarks
368 * You can use `\n` to insert a newline or `\b` to insert a backspace.
369 * You can also optionally specify {cursor} in the string and Fig will automatically place the cursor there after insert.
370 *
371 * @defaultValue The value of the name prop.
372 *
373 * @example
374 * For the `git commit` subcommand, the `-m` option has an insert value of `-m '{cursor}'`
375 */
376 insertValue?: string;
377 /**
378 * When the suggestion is inserted, replace the command with this string
379 *
380 * @remarks
381 * You can use `\n` to insert a newline or `\b` to insert a backspace.
382 * You can also optionally specify {cursor} in the string and Fig will automatically place the cursor there after insert.
383 * Note that currently the entire edit buffer will be replaced. Eventually, only the root command will be replaced, preserving pipes and continuations.
384 */
385 replaceValue?: string;
386 /**
387 * The text that gets rendered at the bottom of the autocomplete box (or the side if you hit ⌘i)
388 *
389 * @example
390 * "Your commit message"
391 */
392 description?: string;
393 /**
394 * The icon that is rendered is based on the type.
395 *
396 * @remarks
397 * Icons can be a 1 character string, a URL, or Fig's [icon protocol](https://fig.io/docs/reference/suggestion/icon-api) (fig://) which lets you generate
398 * colorful and fun systems icons.
399 *
400 * @defaultValue related to the type of the object (e.g. `Suggestion`, `Subcommand`, `Option`, `Arg`)
401 *
402 * @example
403 * `A`
404 * @example
405 * `😊`
406 * @example
407 * `https://www.herokucdn.com/favicon.ico`
408 * @example
409 * `fig://icon?type=file`
410 *
411 */
412 icon?: string;
413 /**
414 * Specifies whether the suggestion is "dangerous".
415 *
416 * @remarks
417 * If true, Fig will not enable its autoexecute functionality. Autoexecute means if a user selects a suggestion it will insert the text and run the command. We signal this by changing the icon to red.
418 * Setting `isDangerous` to `true` will make it harder for a user to accidentally run a dangerous command.
419 *
420 * @defaultValue false
421 *
422 * @example
423 * This is used in the `rm` spec. Why? Because we don't want users to accidentally delete their files so we make it just a little bit harder...
424 */
425 isDangerous?: boolean;
426 /**
427 * The number used to rank suggestions in autocomplete. Number must be from 0-100. Higher priorities rank higher.
428 *
429 * @defaultValue 50
430 * @remarks
431 * Fig ranks suggestions by recency. To do this, we check if a suggestion has been selected before. If yes and the suggestions has:
432 * - a priority between 50-75, the priority will be replaced with 75, then we will add the timestamp of when that suggestion was selected as a decimal.
433 * - a priority outside of 50-75, the priority will be increased by the timestamp of when that suggestion was selected as a decimal.
434 * If it has not been selected before, Fig will keep the same priority as was set in the completion spec
435 * If it was not set in the spec, it will default to 50.
436 *
437 * @example
438 * Let's say a user has previously selected a suggestion at unix timestamp 1634087677:
439 * - If completion spec did not set a priority (Fig treats this as priority 50), its priority would change to 75 + 0.1634087677 = 75.1634087677;
440 * - If completion spec set a priority of 49 or less, its priority would change to 49 + 0.1634087677 = 49.1634087677;
441 * - If completion spec set a priority of 76 or more, its priority would change to 76 + 0.1634087677 = 76.1634087677;
442 * - If a user had never selected a suggestion, then its priority would just stay as is (or if not set, default to 50).
443 *
444 * @example
445 * If you want your suggestions to always be:
446 * - at the top order, rank them 76 or above.
447 * - at the bottom, rank them 49 or below
448 */
449 priority?: number;
450 /**
451 * Specifies whether a suggestion should be hidden from results.
452 * @remarks
453 * Fig will only show it if the user exactly types the name.
454 * @defaultValue false
455 * @example
456 * The "-" suggestion is hidden in the `cd` spec. You will only see it if you type exactly `cd -`
457 */
458 hidden?: boolean;
459 /**
460 *
461 * Specifies whether a suggestion is deprecated.
462 * @remarks
463 * It is possible to specify a suggestion to replace the deprecated one.
464 * - The `description` of the deprecated object (e.g `deprecated: { description: 'The --no-ansi option has been deprecated in v2' }`) is used to provide infos about the deprecation.
465 * - `deprecated: true` and `deprecated: { }` behave the same and will just display the suggestion as deprecated.
466 * @example
467 * ```js
468 * deprecated: { insertValue: '--ansi never', description: 'The --no-ansi option has been deprecated in v2' }
469 * ```
470 */
471 deprecated?: boolean | Omit<BaseSuggestion, "deprecated">;
472
473 /**
474 * Specifies which component to use to render the preview window.
475 *
476 * @remarks This should be the path within the `src` directory to the component without the extension.
477 *
478 * @example 'ls/filepathPreview'
479 */
480 previewComponent?: string;
481
482 /**
483 * This is a way to pass data to the Autocomplete Engine that is not formalized in the spec, do not use this in specs as it may change at any time
484 *
485 * @ignore
486 */
487 _internal?: Record<string, unknown>;
488 }
489
490 /**
491 * Each item in Fig's autocomplete popup window is a Suggestion object. It is probably the most important object in Fig.
492 * Subcommand and Option objects compile down to Suggestion objects. Generators return Suggestion objects.
493 * The main things you can customize in your suggestion object is the text that's displayed, the icon, and what's inserted after being selected. In saying that, most of these have very sane defaults.
494 */
495 interface Suggestion extends BaseSuggestion {
496 /**
497 * The string Fig uses when filtering over a list of suggestions to check for a match.
498 * @remarks
499 * When a a user is typing in the terminal, the query term (the token they are currently typing) filters over all suggestions in a list by checking if the queryTerm matches the prefix of the name.
500 * The `displayName` prop also defaults to the value of name.
501 *
502 * The `name` props of suggestion, subcommand, option, and arg objects are all different. It's important to read them all carefully.
503 *
504 * @example
505 * If a user types git `c`, any Suggestion objects with a name prop that has a value starting with "c" will match.
506 *
507 */
508 name?: SingleOrArray<string>;
509 /**
510 * The type of a suggestion object.
511 * @remarks
512 * The type determines
513 * - the default icon Fig uses (e.g. a file or folder searches for the system icon, a subcommand has a specific icon etc)
514 * - whether we allow users to auto-execute a command
515 */
516 type?: SuggestionType;
517 }
518
519 /**
520 * The subcommand object represent the tree structure of a completion spec. We sometimes also call it the skeleton.
521 *
522 * A subcommand can nest options, arguments, and more subcommands (it's recursive)
523 */
524 interface Subcommand extends BaseSuggestion {
525 /**
526 * The name of the subcommand. Should exactly match the name defined by the CLI tool.
527 *
528 * @remarks
529 * If a subcommand has multiple aliases, they should be included as an array.
530 *
531 * Note that Fig's autocomplete engine requires this `name` to match the text typed by the user in the shell.
532 *
533 * To customize the title that is displayed to the user, use `displayName`.
534 *
535 *
536 * @example
537 * For `git checkout`, the subcommand `checkout` would have `name: "checkout"`
538 * @example
539 * For `npm install`, the subcommand `install` would have `name: ["install", "i"]` as these two values both represent the same subcommand.
540 */
541 name: SingleOrArray<string>;
542
543 /**
544 * An array of `Subcommand` objects representing all the subcommands that exist beneath the current command.
545 * *
546 * To support large CLI tools, `Subcommands` can be nested recursively.
547 *
548 * @example
549 * A CLI tool like `aws` is composed of many top-level subcommands (`s3`, `ec2`, `eks`...), each of which include child subcommands of their own.
550 */
551 subcommands?: Subcommand[];
552
553 /**
554 * Specifies whether the command requires a subcommand. This is false by default.
555 *
556 * A space will always be inserted after this command if `requiresSubcommand` is true.
557 * If the property is omitted, a space will be inserted if there is at least one required argument.
558 */
559 requiresSubcommand?: boolean;
560
561 /**
562 * An array of `Option` objects representing the options that are available on this subcommand.
563 *
564 * @example
565 * A command like `git commit` accepts various flags and options, such as `--message` and `--all`. These `Option` objects would be included in the `options` field.
566 */
567 options?: Option[];
568
569 /**
570 * An array of `Arg` objects representing the various parameters or "arguments" that can be passed to this subcommand.
571 *
572 */
573 args?: SingleOrArray<Arg>;
574 /**
575 * This option allows to enforce the suggestion filtering strategy for a specific subcommand.
576 * @remarks
577 * Users always want to have the most accurate results at the top of the suggestions list.
578 * For example we can enable fuzzy search on a subcommand that always requires fuzzy search to show the best suggestions.
579 * This property is also useful when subcommands or options have a prefix (e.g. the npm package scope) because enabling fuzzy search users can omit that part (see the second example below)
580 * @example
581 * yarn workspace [name] with fuzzy search is way more useful since we can omit the npm package scope
582 * @example
583 * fig settings <setting name> uses fuzzy search to prevent having to add the `autocomplete.` prefix to each searched setting
584 * ```typescript
585 * const figSpec: Fig.Spec {
586 * name: "fig",
587 * subcommands: [
588 * {
589 * name: "settings",
590 * filterStrategy: "fuzzy",
591 * subcommands: [
592 * {
593 * name: "autocomplete.theme", // if a user writes `fig settings theme` it gets the correct suggestions
594 * },
595 * // ... other settings
596 * ]
597 * },
598 * // ... other fig subcommands
599 * ]
600 * }
601 * ```
602 */
603 filterStrategy?: "fuzzy" | "prefix" | "default";
604 /**
605 * A list of Suggestion objects that are appended to the suggestions shown beneath a subcommand.
606 *
607 * @remarks
608 * You can use this field to suggest common workflows.
609 *
610 */
611 additionalSuggestions?: (string | Suggestion)[];
612 /**
613 * Dynamically load another completion spec at runtime.
614 *
615 * @param tokens - a tokenized array of the text the user has typed in the shell.
616 * @param executeCommand - an async function that can execute a shell command on behalf of the user. The output is a string.
617 * @returns A `SpecLocation` object or an array of `SpecLocation` objects.
618 *
619 * @remarks
620 * `loadSpec` can be invoked as string (recommended) or a function (advanced).
621 *
622 * The API tells the autocomplete engine where to look for a completion spec. If you pass a string, the engine will attempt to locate a matching spec that is hosted by Fig.
623 *
624 * @example
625 * Suppose you have an internal CLI tool that wraps `kubectl`. Instead of copying the `kubectl` completion spec, you can include the spec at runtime.
626 * ```typescript
627 * {
628 * name: "kube",
629 * description: "a wrapper around kubectl"
630 * loadSpec: "kubectl"
631 * }
632 * ```
633 * @example
634 * In the `aws` completion spec, `loadSpec` is used to optimize performance. The completion spec is split into multiple files, each of which can be loaded separately.
635 * ```typescript
636 * {
637 * name: "s3",
638 * loadSpec: "aws/s3"
639 * }
640 * ```
641 */
642 loadSpec?: LoadSpec;
643 /**
644 * Dynamically *generate* a `Subcommand` object a runtime. The generated `Subcommand` is merged with the current subcommand.
645 *
646 * @remarks
647 * This API is often used by CLI tools where the structure of the CLI tool is not *static*. For instance, if the tool can be extended by plugins or otherwise shows different subcommands or options depending on the environment.
648 *
649 * @param tokens - a tokenized array of the text the user has typed in the shell.
650 * @param executeCommand - an async function that can execute a shell command on behalf of the user. The output is a string.
651 * @returns a `Fig.Spec` object
652 *
653 * @example
654 * The `python` spec uses `generateSpec` to include the`django-admin` spec if `django manage.py` exists.
655 * ```typescript
656 * generateSpec: async (tokens, executeCommand) => {
657 * // Load the contents of manage.py
658 * const managePyContents = await executeCommand("cat manage.py");
659 * // Heuristic to determine if project uses django
660 * if (managePyContents.contains("django")) {
661 * return {
662 * name: "python",
663 * subcommands: [{ name: "manage.py", loadSpec: "django-admin" }],
664 * };
665 * }
666 * },
667 * ```
668 */
669 generateSpec?: (tokens: string[], executeCommand: ExecuteCommandFunction) => Promise<Spec>;
670
671 /**
672 * Generating a spec can be expensive, but due to current guarantees they are not cached.
673 * This function generates a cache key which is used to cache the result of generateSpec.
674 * If `undefined` is returned, the cache will not be used.
675 */
676 generateSpecCacheKey?: Function<{ tokens: string[] }, string | undefined> | string;
677
678 /**
679 * Configure how the autocomplete engine will map the raw tokens to a given completion spec.
680 *
681 * @param flagsArePosixNoncompliant - Indicates that flags with one hyphen may have *more* than one character. Enabling this directive, turns off support for option chaining.
682 * @param optionsMustPrecedeArguments - Options will not be suggested after any argument of the Subcommand has been typed.
683 * @param optionArgSeparators - Indicate that options which take arguments will require one of the specified separators between the 'verbose' option name and the argument.
684 *
685 * @example
686 * The `-work` option from the `go` spec is parsed as a single flag when `parserDirectives.flagsArePosixNoncompliant` is set to true. Normally, this would be chained and parsed as `-w -o -r -k` if `flagsArePosixNoncompliant` is not set to true.
687 */
688 parserDirectives?: {
689 flagsArePosixNoncompliant?: boolean;
690 optionsMustPrecedeArguments?: boolean;
691 optionArgSeparators?: SingleOrArray<string>;
692 };
693
694 /**
695 * Specifies whether or not to cache the result of loadSpec and generateSpec
696 *
697 * @remarks
698 * Caching is good because it reduces the time to completion on subsequent calls to a dynamic subcommand, but when the data does not outlive the cache this allows a mechanism for opting out of it.
699 */
700 cache?: boolean;
701 }
702
703 /**
704 * The option object represent CLI options (sometimes called flags).
705 *
706 * A option can have an argument. An option can NOT have subcommands or other option
707 */
708 interface Option extends BaseSuggestion {
709 /**
710 * The exact name of the subcommand as defined in the CLI tool.
711 *
712 * @remarks
713 * Fig's parser relies on your option name being exactly what the user would type. (e.g. if the user types `git "-m"`, you must have `name: "-m"` and not something like `name: "your message"` or even with an `=` sign like`name: "-m="`)
714 *
715 * If you want to customize what the text the popup says, use `displayName`.
716 *
717 * The name prop in an Option object compiles down to the name prop in a Suggestion object
718 *
719 * Final note: the name prop can be a string (most common) or an array of strings
720 *
721 *
722 * @example
723 * For `git commit -m` in the, message option nested beneath `commit` would have `name: ["-m", "--message"]`
724 * @example
725 * For `ls -l` the `-l` option would have `name: "-l"`
726 */
727 name: SingleOrArray<string>;
728
729 /**
730 * An array of arg objects or a single arg object
731 *
732 * @remarks
733 * If a subcommand takes an argument, please at least include an empty Arg Object. (e.g. `{ }`). Why? If you don't, Fig will assume the subcommand does not take an argument. When the user types their argument
734 * If the argument is optional, signal this by saying `isOptional: true`.
735 *
736 * @example
737 * `npm run` takes one mandatory argument. This can be represented by `args: { }`
738 * @example
739 * `git push` takes two optional arguments. This can be represented by: `args: [{ isOptional: true }, { isOptional: true }]`
740 * @example
741 * `git clone` takes one mandatory argument and one optional argument. This can be represented by: `args: [{ }, { isOptional: true }]`
742 */
743 args?: SingleOrArray<Arg>;
744 /**
745 *
746 * Signals whether an option is persistent, meaning that it will still be available
747 * as an option for all child subcommands.
748 *
749 * @remarks
750 * As of now there is no way to disable this
751 * persistence for certain children. Also see
752 * https://github.com/spf13/cobra/blob/master/user_guide.md#persistent-flags.
753 *
754 * @defaultValue false
755 *
756 * @example
757 * Say the `git` spec had an option at the top level with `{ name: "--help", isPersistent: true }`.
758 * Then the spec would recognize both `git --help` and `git commit --help`
759 * as a valid as we are passing the `--help` option to all `git` subcommands.
760 *
761 */
762 isPersistent?: boolean;
763 /**
764 * Signals whether an option is required.
765 *
766 * @defaultValue false (option is NOT required)
767 * @example
768 * The `-m` option of `git commit` is required
769 *
770 */
771 isRequired?: boolean;
772 /**
773 *
774 * Signals whether an equals sign is required to pass an argument to an option (e.g. `git commit --message="msg"`)
775 * @defaultValue false (does NOT require an equal)
776 *
777 * @example
778 * When `requiresEqual: true` the user MUST do `--opt=value` and cannot do `--opt value`
779 *
780 * @deprecated use `requiresSeparator` instead
781 *
782 */
783 requiresEquals?: boolean;
784 /**
785 *
786 * Signals whether one of the separators specified in parserDirectives is required to pass an argument to an option (e.g. `git commit --message[separator]"msg"`)
787 * If set to true this will automatically insert an equal after the option name.
788 * If set to a separator (string) this will automatically insert the separator specified after the option name.
789 * @defaultValue false (does NOT require a separator)
790 *
791 * @example
792 * When `requiresSeparator: true` the user MUST do `--opt=value` and cannot do `--opt value`
793 * @example
794 * When `requiresSeparator: ':'` the user MUST do `--opt:value` and cannot do `--opt value`
795 */
796 requiresSeparator?: boolean | string;
797 /**
798 *
799 * Signals whether an option can be passed multiple times.
800 *
801 * @defaultValue false (option is NOT repeatable)
802 *
803 * @remarks
804 * Passing `isRepeatable: true` will allow an option to be passed any number
805 * of times, while passing `isRepeatable: 2` will allow it to be passed
806 * twice, etc. Passing `isRepeatable: false` is the same as passing
807 * `isRepeatable: 1`.
808 *
809 * If you explicitly specify the isRepeatable option in a spec, this
810 * constraint will be enforced at the parser level, meaning after the option
811 * (say `-o`) has been passed the maximum number of times, Fig's parser will
812 * not recognize `-o` as an option if the user types it again.
813 *
814 * @example
815 * In `npm install` doesn't specify `isRepeatable` for `{ name: ["-D", "--save-dev"] }`.
816 * When the user types `npm install -D`, Fig will no longer suggest `-D`.
817 * If the user types `npm install -D -D`. Fig will still parse the second
818 * `-D` as an option.
819 *
820 * Suppose `npm install` explicitly specified `{ name: ["-D", "--save-dev"], isRepeatable: false }`.
821 * Now if the user types `npm install -D -D`, Fig will instead parse the second
822 * `-D` as the argument to the `install` subcommand instead of as an option.
823 *
824 * @example
825 * SSH has `{ name: "-v", isRepeatable: 3 }`. When the user types `ssh -vv`, Fig
826 * will still suggest `-v`, when the user types `ssh -vvv` Fig will stop
827 * suggesting `-v` as an option. Finally if the user types `ssh -vvvv` Fig's
828 * parser will recognize that this is not a valid string of chained options
829 * and will treat this as an argument to `ssh`.
830 *
831 */
832 isRepeatable?: boolean | number;
833 /**
834 *
835 * Signals whether an option is mutually exclusive with other options (ie if the user has this option, Fig should not show the options specified).
836 * @defaultValue false
837 *
838 * @remarks
839 * Options that are mutually exclusive with flags the user has already passed will not be shown in the suggestions list.
840 *
841 * @example
842 * You might see `[-a | --interactive | --patch]` in a man page. This means each of these options are mutually exclusive on each other.
843 * If we were defining the exclusive prop of the "-a" option, then we would have `exclusive: ["--interactive", "--patch"]`
844 *
845 */
846 exclusiveOn?: string[];
847 /**
848 *
849 *
850 * Signals whether an option depends on other options (ie if the user has this option, Fig should only show these options until they are all inserted).
851 *
852 * @defaultValue false
853 *
854 * @remarks
855 * If the user has an unmet dependency for a flag they've already typed, this dependency will have boosted priority in the suggestion list.
856 *
857 * @example
858 * In a tool like firebase, we may want to delete a specific extension. The command might be `firebase delete --project ABC --extension 123` This would mean we delete the 123 extension from the ABC project.
859 * In this case, `--extension` dependsOn `--project`
860 *
861 */
862 dependsOn?: string[];
863 }
864
865 /**
866 * The arg object represent CLI arguments (sometimes called positional arguments).
867 *
868 * An argument is different to a subcommand object and option object. It does not compile down to a suggestion object. Rather, it represents custom user input. If you want to generate suggestions for this custom user input, you should use the generator prop nested beneath an Arg object
869 */
870 interface Arg {
871 /**
872 * The name of an argument. This is different to the `name` prop for subcommands, options, and suggestion objects so please read carefully.
873 * This `name` prop signals a normal, human readable string. It usually signals to the user the type of argument they are inserting if there are no available suggestions.
874 * Unlike subcommands and options, Fig does NOT use this value for parsing. Therefore, it can be whatever you want.
875 *
876 * @example
877 * The name prop for the `git commit -m <msg>` arg object is "msg". But you could also make it "message" or "your message". It is only used for description purposes (you see it when you type the message), not for parsing!
878 */
879 name?: string;
880
881 /**
882 * The text that gets rendered at the bottom of the autocomplete box a) when the user is inputting an argument and there are no suggestions and b) for all generated suggestions for an argument
883 * Keep it short and direct!
884 *
885 * @example
886 * "Your commit message"
887 */
888 description?: string;
889
890 /**
891 * Specifies whether the suggestions generated for this argument are "dangerous".
892 *
893 * @remarks
894 * If true, Fig will not enable its autoexecute functionality. Autoexecute means if a user selects a suggestion it will insert the text and run the command. We signal this by changing the icon to red.
895 * Turning on isDangerous will make it harder for a user to accidentally run a dangerous command.
896 *
897 * @defaultValue false
898 *
899 * @example
900 * This is used for all arguments in the `rm` spec.
901 */
902 isDangerous?: boolean;
903
904 /**
905 * A list of Suggestion objects that are shown when a user is typing an argument.
906 *
907 * @remarks
908 * These suggestions are static meaning you know them beforehand and they are not generated at runtime. If you want to generate suggestions at runtime, use a generator
909 *
910 * @example
911 * For `git reset <branch or commit>`, a two common arguments to pass are "head" and "head^". Therefore, the spec suggests both of these by using the suggestion prop
912 */
913 suggestions?: (string | Suggestion)[];
914 /**
915 * A template which is a single TemplateString or an array of TemplateStrings
916 *
917 * @remarks
918 * Templates are generators prebuilt by Fig. Here are the three templates:
919 * - filepaths: show folders and filepaths. Allow autoexecute on filepaths
920 * - folders: show folders only. Allow autoexecute on folders
921 * - history: show suggestions for all items in history matching this pattern
922 * - help: show subcommands. Only includes the 'siblings' of the nearest 'parent' subcommand
923 *
924 * @example
925 * `cd` uses the "folders" template
926 * @example
927 * `ls` used ["filepaths", "folders"]. Why both? Because if I `ls` a directory, we want to enable a user to autoexecute on this directory. If we just did "filepaths" they couldn't autoexecute.
928 *
929 */
930 template?: Template;
931 /**
932 *
933 * Generators let you dynamically generate suggestions for arguments by running shell commands on a user's device.
934 *
935 * This takes a single generator or an array of generators
936 */
937 generators?: SingleOrArray<Generator>;
938 /**
939 * This option allows to enforce the suggestion filtering strategy for a specific argument suggestions.
940 * @remarks
941 * Users always want to have the most accurate results at the top of the suggestions list.
942 * For example we can enable fuzzy search on an argument that always requires fuzzy search to show the best suggestions.
943 * This property is also useful when argument suggestions have a prefix (e.g. the npm package scope) because enabling fuzzy search users can omit that part (see the second example below)
944 * @example
945 * npm uninstall [packages...] uses fuzzy search to allow searching for installed packages ignoring the package scope
946 * ```typescript
947 * const figSpec: Fig.Spec {
948 * name: "npm",
949 * subcommands: [
950 * {
951 * args: {
952 * name: "packages",
953 * filterStrategy: "fuzzy", // search in suggestions provided by the generator (in this case) using fuzzy search
954 * generators: generateNpmDeps,
955 * isVariadic: true,
956 * },
957 * },
958 * // ... other npm commands
959 * ],
960 * }
961 * ```
962 */
963 filterStrategy?: "fuzzy" | "prefix" | "default";
964 /**
965 * Provide a suggestion at the top of the list with the current token that is being typed by the user.
966 */
967 suggestCurrentToken?: boolean;
968 /**
969 * Specifies that the argument is variadic and therefore repeats infinitely.
970 *
971 * @remarks
972 * Man pages represent variadic arguments with an ellipsis e.g. `git add <pathspec...>`
973 *
974 * @example
975 * `echo` takes a variadic argument (`echo hello world ...`)
976 * @example
977 * `git add` also takes a variadic argument
978 */
979 isVariadic?: boolean;
980
981 /**
982 * Specifies whether options can interrupt variadic arguments. There is
983 * slightly different behavior when this is used on an option argument and
984 * on a subcommand argument:
985 *
986 * - When an option breaks a *variadic subcommand argument*, after the option
987 * and any arguments are parsed, the parser will continue parsing variadic
988 * arguments to the subcommand
989 * - When an option breaks a *variadic option argument*, after the breaking
990 * option and any arguments are parsed, the original variadic options
991 * arguments will be terminated. See the second examples below for details.
992 *
993 *
994 * @defaultValue true
995 *
996 * @example
997 * When true for git add's argument:
998 * `git add file1 -v file2` will interpret `-v` as an option NOT an
999 * argument, and will continue interpreting file2 as a variadic argument to
1000 * add after
1001 *
1002 * @example
1003 * When true for -T's argument, where -T is a variadic list of tags:
1004 * `cmd -T tag1 tag2 -p project tag3` will interpret `-p` as an option, but
1005 * will then terminate the list of tags. So tag3 is not parsed as an
1006 * argument to `-T`, but rather as a subcommand argument to `cmd` if `cmd`
1007 * takes any arguments.
1008 *
1009 * @example
1010 * When false:
1011 * `echo hello -n world` will treat -n as an argument NOT an option.
1012 * However, in `echo -n hello world` it will treat -n as an option as
1013 * variadic arguments haven't started yet
1014 *
1015 */
1016 optionsCanBreakVariadicArg?: boolean;
1017
1018 /**
1019 * `true` if an argument is optional (ie the CLI spec says it is not mandatory to include an argument, but you can if you want to).
1020 *
1021 * @remarks
1022 * NOTE: It is important you include this for our parsing. If you don't, Fig will assume the argument is mandatory. When we assume an argument is mandatory, we force the user to input the argument and hide all other suggestions.
1023 *
1024 * @example
1025 * `git push [remote] [branch]` takes two optional args.
1026 */
1027 isOptional?: boolean;
1028 /**
1029 * Syntactic sugar over the `loadSpec` prop.
1030 *
1031 * @remarks
1032 * Specifies that the argument is an entirely new command which Fig should start completing on from scratch.
1033 *
1034 * @example
1035 * `time` and `builtin` have only one argument and this argument has the `isCommand` property. If I type `time git`, Fig will load up the git completion spec because the isCommand property is set.
1036 */
1037 isCommand?: boolean;
1038 /**
1039 * The same as the `isCommand` prop, except Fig will look for a completion spec in the `.fig/autocomplete/build` folder in the user's current working directory.
1040 *
1041 * @remarks
1042 * See our docs for more on building completion specs for local scripts [Fig for Teams](https://fig.io/docs/)
1043 * @example
1044 * `python` take one argument which is a `.py` file. If I have a `main.py` file on my desktop and my current working directory is my desktop, if I type `python main.py[space]` Fig will look for a completion spec in `~/Desktop/.fig/autocomplete/build/main.py.js`
1045 */
1046 isScript?: boolean;
1047 /**
1048 * The same as the `isCommand` prop, except you specify a string to prepend to what the user inputs and fig will load the completion spec accordingly.
1049 * @remarks
1050 * If isModule: "python/", Fig would load up the `python/USER_INPUT.js` completion spec from the `~/.fig/autocomplete` folder.
1051 * @example
1052 * For `python -m`, the user can input a specific module such as http.server. Each module is effectively a mini CLI tool that should have its own completions. Therefore the argument object for -m has `isModule: "python/"`. Whatever the modules user inputs, Fig will look under the `~/.fig/autocomplete/python/` directory for completion spec.
1053 *
1054 * @deprecated use `loadSpec` instead
1055 */
1056 isModule?: string;
1057
1058 /**
1059 * This will debounce every keystroke event for this particular arg.
1060 * @remarks
1061 * If there are no keystroke events after 100ms, Fig will execute all the generators in this arg and return the suggestions.
1062 *
1063 * @example
1064 * `npm install` and `pip install` send debounced network requests after inactive typing from users.
1065 */
1066 debounce?: boolean;
1067 /**
1068 * The default value for an optional argument.
1069 *
1070 * @remarks
1071 * Note: This is currently not used anywhere in Fig's autocomplete popup, but will be soon.
1072 *
1073 */
1074 default?: string;
1075 /**
1076 * See [`loadSpec` in Subcommand Object](https://fig.io/docs/reference/subcommand#loadspec).
1077 *
1078 * @remarks
1079 * There is a very high chance you want to use one of the following:
1080 * 1. `isCommand` (See [Arg Object](https://fig.io/docs/reference/arg#iscommand))
1081 * 2. `isScript` (See [Arg Object](https://fig.io/docs/reference/arg#isscript))
1082 *
1083 */
1084 loadSpec?: LoadSpec;
1085
1086 /**
1087 * The `arg.parserDirective.alias` prop defines whether Fig's tokenizer should expand out an alias into separate tokens then offer completions accordingly.
1088 *
1089 * @remarks
1090 * This is similar to how Fig is able to offer autocomplete for user defined shell aliases, but occurs at the completion spec level.
1091 *
1092 * @param token - The token that the user has just typed that is an alias for something else
1093 * @param executeCommand -an async function that allows you to execute a shell command on the user's system and get the output as a string.
1094 * @returns The expansion of the alias that Fig's bash parser will reparse as if it were typed out in full, rather than the alias.
1095 *
1096 * If for some reason you know exactly what it will be, you may also just pass in the expanded alias, not a function that returns the expanded alias.
1097 *
1098 * @example
1099 * git takes git aliases. These aliases are defined in a user's gitconfig file. Let's say a user has an alias for `p=push`, then if a user typed `git p[space]`, this function would take the `p` token, return `push` and then offer suggestions as if the user had typed `git push[space]`
1100 *
1101 * @example
1102 * `npm run <script>` also takes an arg called "script". This arg is technically an alias for another shell command that is specified in the package.json.
1103 * If the user typed `npm run start[space]`, the package.json had script `start=node index.js`, then Fig would start offering suggestions for as if you had just typed `node index.js[space]`
1104 *
1105 * Note: In both cases, the alias function is only used to expand a given alias NOT to generate the list of aliases. To generate a list of aliases, scripts etc, use a generator.
1106 */
1107 parserDirectives?: {
1108 alias?: string | ((token: string, exec: ExecuteCommandFunction) => Promise<string>);
1109 };
1110 }
1111
1112 /**
1113 * The generator object is used to generate suggestions for an arg object. To do this, it runs a defined shell command on the user's device, gets the output, and returns a list of Suggestion objects.
1114 *
1115 */
1116 interface Generator {
1117 /**
1118 * A template which is a single `TemplateString` or an array of `TemplateStrings`.
1119 *
1120 * @remarks
1121 * Templates are generators prebuilt by Fig. Here are the three templates:
1122 * - filepaths: show folders and filepaths. Allow autoexecute on filepaths
1123 * - folders: show folders only. Allow autoexecute on folders
1124 * - history: show suggestions for all items in history matching this pattern
1125 * - help: show subcommands. Only includes the 'siblings' of the nearest 'parent' subcommand
1126 *
1127 * @example
1128 * `cd` uses the "folders" template
1129 * @example
1130 * `ls` uses ["filepaths", "folders"]. Why both? Because if I `ls` a directory, we want to enable a user to autoexecute on this directory. If we just did "filepaths" they couldn't autoexecute.
1131 *
1132 */
1133 template?: Template;
1134 /**
1135 *
1136 * A function to filter and modify suggestions returned by a template
1137 *
1138 * @param templateSuggestions - the array of suggestion objects returned by the given template.
1139 * @returns An array of `Suggestion` objects.
1140 *
1141 * @example
1142 * The python spec has an arg object which has a template for "filepaths". However, we don't want to suggest non `.py` files. Therefore, we take the output of the template, filter out all files that don't end in `.py`, keep all folders that end with `/` and return the list of suggestions.
1143 */
1144 filterTemplateSuggestions?: Function<TemplateSuggestion[], Suggestion[]>;
1145 /**
1146 *
1147 * The command you wish to run on the user's device at their shell session's current working directory.
1148 *
1149 * @remarks
1150 * You can either specify
1151 * 1. a command and args to be executed (like `["ls"]` or `["git", "branch"]`)
1152 * 2. a function to generate the command and args to be executed. The function takes in an array of tokens of the user input and should output a array of string (command and args). You use a function when the script you run is dependent upon one of the tokens the user has already input (for instance an app name, a Kubernetes token etc.)
1153 * After executing the script, the stdout output will be passed to one of `splitOn` or `postProcess` for further processing to produce suggestion objects.
1154 *
1155 * @example
1156 * `git checkout <branch>` takes one argument which is a git branch. Its arg object has a generator with a `script: ["git", "branch"]"`. The stdout output of this shell command is then passed into the postProcess function to generate the final suggestions.
1157 */
1158 script?:
1159 | string[]
1160 | Function<string[], string[]>
1161 | ExecuteCommandInput
1162 | Function<string[], ExecuteCommandInput>;
1163 /**
1164 * Set the execution timeout of the command specified in the `script` prop.
1165 * @defaultValue 5000
1166 */
1167 scriptTimeout?: number;
1168 /**
1169 *
1170 * Process the string output from the `script` prop and return a list of suggestions
1171 *
1172 * @param out - The output of the script that was executed on the user's device
1173 * @param tokens - a tokenized array of what the user has typed
1174 * @returns An array of `Suggestion` objects.
1175 *
1176 */
1177 postProcess?: (out: string, tokens: string[]) => Suggestion[];
1178 /**
1179 * Syntactic sugar for `postProcess` function
1180 *
1181 * @remarks
1182 * This takes in the text output of `script`, splits it on the string you provide here, and then automatically generates an array of suggestion objects for each item.
1183 *
1184 * @example
1185 * Specify `\n` and Fig will split on new lines, and turn each line into a suggestion object with `name` prop equal to the value on the line.
1186 */
1187 splitOn?: string;
1188 /**
1189 *
1190 * A function run on every keystroke that determines whether Fig should invalidate its cached list of suggestions and instead regenerate its list of suggestions.
1191 *
1192 * @remarks
1193 * A note on how Fig works: Suggestions vs Filtered Suggestions
1194 * Suggestions: Whenever you type a space indicating the start of a new token, Fig will regenerate a new list of suggestions e.g. `git[space]` will generate a list of suggestions for every subcommand, option, and arg
1195 * Filtered Suggestions: When you type within the same token (e.g. `git c` -> `git ch`), Fig takes the token you are currently typing in and uses it to filter over the list of suggestions you have cached. e.g. `git c`. The list of suggestions is the same as before, but the filtered suggestions are now `commit`, `clean`, `clone`, and `checkout`.
1196 *
1197 * **Why don't we recalculate suggestions on each keystroke?**
1198 * 1. It's expensive
1199 * 2. We don't need to. The caching works nicely
1200 *
1201 * **So what does the trigger do?**
1202 * The trigger function is run on every keystroke and tells us whether or not we should invalidate the cache and regenerate a list of suggestions.
1203 * The trigger function is almost always used with a `custom` generator and the `getQueryTerm` function to make the autocomplete experience really good (it's how suggestions for `cd` work)
1204 * It is especially beneficial when you want to generate suggestions for an argument contained inside a single string that is not separated by a space.
1205 *
1206 * **What is important to remember?**
1207 * This function looks at the CHANGE in a token, not the current state of the token. If my token goes from `desktop` to `desktop/`, should I regenerate suggestions? Remember, users can paste text so theoretically any change is possible. It is totally valid for oldToken to be an empty string and newToken to be a 50 character string!
1208 *
1209 *
1210 * @param newToken - The new token that was just typed by the user e.g. "desktop/""
1211 * @param oldToken - The old token that was there before e.g. "desktop"
1212 * @returns A boolean of whether or not we should regenerate suggestions
1213 *
1214 * @defaultValue
1215 * `false`
1216 * It means that the function returns false ie we do not regenerate suggestion on each keystroke and instead, keep our cached list of suggestions while the user is editing the current token.
1217 *
1218 * @example
1219 * `chmod`: If I type `chmod u` we should generate suggestions for `u+x`, `u+r`, `u-w` etc. Whereas if I typed `chmod 7` we should generate suggestions for `755` or `777` etc.
1220 * The suggestion we generate depends on the new information we have. The oldToken was an empty string, the new token could be a `7` or a `u` etc...
1221 *
1222 * All this function's job is to say whether or not we should generate new suggestions. It does not specify how to create these new suggestions. This is the job of the `script` or `custom` props. Annoyingly, you may have to implement some of the same parsing logic again. However, because this is javascript, just create a function so you don't have to repeat yourself :)
1223 *
1224 * Note: yes, we could have generate a list of suggestions at the start for every single permutation of 777 or u+x etc, however, there are so many and this is just not performant!
1225 *
1226 * @example
1227 * `cd`: Let's say a user has "cd desktop" currently typed then the user types a "/" so the changes to "cd ~/desktop/".
1228 * The old token is "~/desktop", new token is "desktop/". This is a perfect time for us to generate a new list of suggestions. We previously had all the folders in my ~ directory as suggestions, but after the total number of `/` in the tokens changed, we should trigger a new set of suggestions to be generated. This new set of suggestions should then generate suggestions for the desktop directory, not the ~ directory.
1229 */
1230 trigger?: Trigger;
1231 /**
1232 * A function that takes the token that the user has typed and determines which part of it should be used to filter over all the suggestions.
1233 *
1234 * @param token - The full token the user is currently typing
1235 * @returns The query term that Fig will use to filter over suggestions
1236 *
1237 * @remarks
1238 * Read the note above on how triggers work. Triggers and query term may seem similar but are actually different.
1239 *
1240 * The `trigger` function defines when to regenerate new suggestions.
1241 * The `query` term defines what characters we should use to filter over these suggestions.
1242 * The `getQueryTerm` function defines the queryTerm
1243 *
1244 * @example
1245 * `cd` has a `getQueryTerm` function that takes the token the user has typed and returns everything after the last "/".
1246 * if the user types cd `~/desktop/a`, the list of suggestions will be all the folders on the user's desktop. We want to filter over these folders with the query term `"a"` not `~/desktop/a`
1247 *
1248 */
1249 getQueryTerm?: StringOrFunction<string, string>;
1250 /**
1251 * An async function that is similar to the function version of `script`, however, it gives you full control.
1252 *
1253 * @remarks
1254 * This function is effectively `script` and `postProcess` combined. It is very useful in combination with `trigger` and `getQueryTerm` to generate suggestions as the user is typing inside a token. Read the description of `trigger` for more.
1255 *
1256 * @param tokens - a tokenized array of what the user has typed
1257 * @param executeCommand - an async function that allows you to execute a shell command on the user's system and get the output as a string.
1258 * @param shellContext - an object containing a user's currentWorkingDirectory, currentProcess, and if relevant, the sshPrefix string that can be used if the user is in an SSH session.
1259 *
1260 * @returns An array of suggestion objects
1261 *
1262 * @example
1263 * In `cd` the custom function will combine the current working directory with everything up to the last `"/"` in the last token. It will then run `ls` at this path and generate a list of suggestions accordingly.
1264 * e.g. if the user was currently in their home directory and typed "cd desktop/abcdef", then the custom function would return a list of directories at the `~/desktop` directory
1265 * if the user was currently in their home directory and typed "cd desktop/my_folder/second_folder/aaaaa", then the custom function would return a list of directories at the `~/desktop/my_folder/second_folder` directory
1266 * if the user was currently in their home directory and typed "cd /usr/bin/", then the custom function would return a list of directories at the `/usr/bin/` directory
1267 *
1268 * @example
1269 * ```ts
1270 * const generator: Fig.Generator = {
1271 * custom: async (tokens, executeCommand) => {
1272 * const out = await executeCommand("ls");
1273 * return out.split("\n").map((elm) => ({ name: elm }));
1274 * },
1275 * };
1276 * ```
1277 */
1278 custom?: (
1279 tokens: string[],
1280 executeCommand: ExecuteCommandFunction,
1281 generatorContext: GeneratorContext
1282 ) => Promise<Suggestion[]>;
1283 /**
1284 *
1285 * Cache the response of generators for a specific period time and optionally by directory the commands were executed in.
1286 *
1287 * @remarks
1288 * For commands that take a long time to run, Fig gives you the option to cache their response. You can cache the response globally or just by the directory they were run in.
1289 * We currently have two cache strategies:
1290 * - `stale-while-revalidate` (default): when cache becomes stale fig will return the stale data while fetching the updated one. This strategy accepts a `ttl` (time to live) to configure how long it takes for the cache to become stale.
1291 * - `max-age`: will show a loading indicator when cache is stale. You need to specify a `ttl` for how long it takes for the cache to become stale.
1292 * You can also optionally turn on the ability to just cache by directory (`cacheByDirectory: true`)
1293 *
1294 * @example
1295 * The kubernetes spec makes use of this.
1296 *
1297 */
1298 cache?: Cache;
1299 }
1300 }