@kjanat/dreamcli 0.0.0 → 2.0.0
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/CHANGELOG.md +706 -0
- package/LICENSE +22 -0
- package/README.md +502 -0
- package/dist/core/cli/dispatch.d.mts +85 -0
- package/dist/core/cli/dispatch.mjs +1 -0
- package/dist/core/cli/index.d.mts +418 -0
- package/dist/core/cli/index.mjs +1 -0
- package/dist/core/cli/planner.d.mts +143 -0
- package/dist/core/cli/planner.mjs +1 -0
- package/dist/core/cli/plugin.d.mts +94 -0
- package/dist/core/cli/plugin.mjs +1 -0
- package/dist/core/cli/propagate.d.mts +39 -0
- package/dist/core/cli/propagate.mjs +1 -0
- package/dist/core/cli/root-help.d.mts +28 -0
- package/dist/core/cli/root-help.mjs +7 -0
- package/dist/core/cli/root-surface.d.mts +42 -0
- package/dist/core/cli/root-surface.mjs +1 -0
- package/dist/core/cli/runtime-preflight.d.mts +149 -0
- package/dist/core/cli/runtime-preflight.mjs +1 -0
- package/dist/core/completion/index.d.mts +46 -0
- package/dist/core/completion/index.mjs +1 -0
- package/dist/core/completion/shells/bash.d.mts +24 -0
- package/dist/core/completion/shells/bash.mjs +3 -0
- package/dist/core/completion/shells/fish.d.mts +20 -0
- package/dist/core/completion/shells/fish.mjs +2 -0
- package/dist/core/completion/shells/powershell.d.mts +14 -0
- package/dist/core/completion/shells/powershell.mjs +2 -0
- package/dist/core/completion/shells/shared.d.mts +139 -0
- package/dist/core/completion/shells/shared.mjs +1 -0
- package/dist/core/completion/shells/zsh.d.mts +24 -0
- package/dist/core/completion/shells/zsh.mjs +2 -0
- package/dist/core/config/index.d.mts +161 -0
- package/dist/core/config/index.mjs +1 -0
- package/dist/core/config/package-json.d.mts +68 -0
- package/dist/core/config/package-json.mjs +1 -0
- package/dist/core/errors/index.d.mts +126 -0
- package/dist/core/errors/index.mjs +1 -0
- package/dist/core/execution/index.d.mts +49 -0
- package/dist/core/execution/index.mjs +1 -0
- package/dist/core/help/index.d.mts +49 -0
- package/dist/core/help/index.mjs +8 -0
- package/dist/core/json-schema/index.d.mts +109 -0
- package/dist/core/json-schema/index.mjs +55 -0
- package/dist/core/json-schema/meta-descriptions.generated.d.mts +185 -0
- package/dist/core/json-schema/meta-descriptions.generated.mjs +28 -0
- package/dist/core/output/activity.d.mts +194 -0
- package/dist/core/output/activity.mjs +1 -0
- package/dist/core/output/contracts.d.mts +88 -0
- package/dist/core/output/contracts.mjs +1 -0
- package/dist/core/output/display-value.d.mts +19 -0
- package/dist/core/output/display-value.mjs +1 -0
- package/dist/core/output/index.d.mts +280 -0
- package/dist/core/output/index.mjs +2 -0
- package/dist/core/output/renderers.d.mts +46 -0
- package/dist/core/output/renderers.mjs +1 -0
- package/dist/core/output/writer.d.mts +40 -0
- package/dist/core/output/writer.mjs +1 -0
- package/dist/core/parse/index.d.mts +79 -0
- package/dist/core/parse/index.mjs +1 -0
- package/dist/core/prompt/index.d.mts +205 -0
- package/dist/core/prompt/index.mjs +6 -0
- package/dist/core/resolve/args.d.mts +8 -0
- package/dist/core/resolve/args.mjs +1 -0
- package/dist/core/resolve/coerce.d.mts +22 -0
- package/dist/core/resolve/coerce.mjs +1 -0
- package/dist/core/resolve/config.d.mts +10 -0
- package/dist/core/resolve/config.mjs +1 -0
- package/dist/core/resolve/contracts.d.mts +112 -0
- package/dist/core/resolve/errors.d.mts +11 -0
- package/dist/core/resolve/errors.mjs +2 -0
- package/dist/core/resolve/flags.d.mts +10 -0
- package/dist/core/resolve/flags.mjs +1 -0
- package/dist/core/resolve/index.d.mts +42 -0
- package/dist/core/resolve/index.mjs +1 -0
- package/dist/core/resolve/property.d.mts +47 -0
- package/dist/core/resolve/property.mjs +1 -0
- package/dist/core/schema/activity.d.mts +169 -0
- package/dist/core/schema/arg.d.mts +559 -0
- package/dist/core/schema/arg.mjs +1 -0
- package/dist/core/schema/command.d.mts +960 -0
- package/dist/core/schema/command.mjs +1 -0
- package/dist/core/schema/flag.d.mts +491 -0
- package/dist/core/schema/flag.mjs +1 -0
- package/dist/core/schema/index.d.mts +8 -0
- package/dist/core/schema/middleware.d.mts +122 -0
- package/dist/core/schema/middleware.mjs +1 -0
- package/dist/core/schema/prompt.d.mts +117 -0
- package/dist/core/schema/run.d.mts +171 -0
- package/dist/core/schema-dsl/runtime.d.mts +144 -0
- package/dist/core/schema-dsl/runtime.mjs +2 -0
- package/dist/core/schema-dsl/to-json-schema.d.mts +30 -0
- package/dist/core/schema-dsl/to-json-schema.mjs +1 -0
- package/dist/core/testkit/index.d.mts +54 -0
- package/dist/core/testkit/index.mjs +1 -0
- package/dist/index.d.mts +28 -0
- package/dist/index.mjs +1 -0
- package/dist/runtime/adapter.d.mts +212 -0
- package/dist/runtime/adapter.mjs +1 -0
- package/dist/runtime/auto.d.mts +26 -0
- package/dist/runtime/auto.mjs +1 -0
- package/dist/runtime/bun.d.mts +28 -0
- package/dist/runtime/bun.mjs +1 -0
- package/dist/runtime/deno.d.mts +76 -0
- package/dist/runtime/deno.mjs +2 -0
- package/dist/runtime/detect.d.mts +86 -0
- package/dist/runtime/detect.mjs +1 -0
- package/dist/runtime/index.d.mts +7 -0
- package/dist/runtime/node.d.mts +65 -0
- package/dist/runtime/node.mjs +2 -0
- package/dist/runtime/paths.d.mts +31 -0
- package/dist/runtime/paths.mjs +1 -0
- package/dist/runtime/support.d.mts +42 -0
- package/dist/runtime/support.mjs +1 -0
- package/dist/runtime.d.mts +7 -0
- package/dist/runtime.mjs +1 -0
- package/dist/testkit.d.mts +6 -0
- package/dist/testkit.mjs +1 -0
- package/dist/version.d.mts +16 -0
- package/dist/version.mjs +1 -0
- package/dreamcli.schema.json +338 -0
- package/examples/basic.ts +33 -0
- package/examples/gh/package.json +44 -0
- package/examples/gh/src/commands/auth.ts +66 -0
- package/examples/gh/src/commands/issue.ts +120 -0
- package/examples/gh/src/commands/pr.ts +125 -0
- package/examples/gh/src/data/issues.yaml +5 -0
- package/examples/gh/src/data/issues.yaml.d.ts +17 -0
- package/examples/gh/src/data/pull-requests.yaml +7 -0
- package/examples/gh/src/data/pull-requests.yaml.d.ts +18 -0
- package/examples/gh/src/docs.ts +11 -0
- package/examples/gh/src/lib/auth.ts +37 -0
- package/examples/gh/src/lib/utils.ts +17 -0
- package/examples/gh/src/main.test.ts +307 -0
- package/examples/gh/src/main.ts +40 -0
- package/examples/interactive.ts +66 -0
- package/examples/json-mode.ts +91 -0
- package/examples/middleware.ts +71 -0
- package/examples/multi-command.ts +66 -0
- package/examples/spinner-progress.ts +49 -0
- package/examples/testing.ts +147 -0
- package/package.json +149 -2
- package/src/core/cli/dispatch.ts +286 -0
- package/src/core/cli/index.ts +978 -0
- package/src/core/cli/planner.ts +413 -0
- package/src/core/cli/plugin.ts +117 -0
- package/src/core/cli/propagate.ts +97 -0
- package/src/core/cli/root-help.ts +269 -0
- package/src/core/cli/root-surface.ts +74 -0
- package/src/core/cli/runtime-preflight.ts +409 -0
- package/src/core/completion/index.ts +88 -0
- package/src/core/completion/shells/bash.ts +459 -0
- package/src/core/completion/shells/fish.ts +259 -0
- package/src/core/completion/shells/powershell.ts +405 -0
- package/src/core/completion/shells/shared.ts +283 -0
- package/src/core/completion/shells/zsh.ts +381 -0
- package/src/core/config/index.ts +407 -0
- package/src/core/config/package-json.ts +220 -0
- package/src/core/errors/index.ts +193 -0
- package/src/core/execution/index.ts +270 -0
- package/src/core/help/index.ts +557 -0
- package/src/core/json-schema/index.ts +891 -0
- package/src/core/json-schema/meta-descriptions.generated.ts +202 -0
- package/src/core/output/activity.ts +568 -0
- package/src/core/output/contracts.ts +194 -0
- package/src/core/output/display-value.ts +48 -0
- package/src/core/output/index.ts +669 -0
- package/src/core/output/renderers.ts +125 -0
- package/src/core/output/writer.ts +46 -0
- package/src/core/parse/index.ts +661 -0
- package/src/core/prompt/index.ts +583 -0
- package/src/core/resolve/args.ts +144 -0
- package/src/core/resolve/coerce.ts +432 -0
- package/src/core/resolve/config.ts +26 -0
- package/src/core/resolve/contracts.ts +135 -0
- package/src/core/resolve/errors.ts +227 -0
- package/src/core/resolve/flags.ts +205 -0
- package/src/core/resolve/index.ts +108 -0
- package/src/core/resolve/property.ts +99 -0
- package/src/core/schema/activity.ts +240 -0
- package/src/core/schema/arg.ts +719 -0
- package/src/core/schema/command.ts +1490 -0
- package/src/core/schema/flag.ts +756 -0
- package/src/core/schema/index.ts +91 -0
- package/src/core/schema/middleware.ts +171 -0
- package/src/core/schema/prompt.ts +156 -0
- package/src/core/schema/run.ts +195 -0
- package/src/core/schema-dsl/index.ts +109 -0
- package/src/core/schema-dsl/parse.ts +262 -0
- package/src/core/schema-dsl/runtime.ts +609 -0
- package/src/core/schema-dsl/to-json-schema.ts +102 -0
- package/src/core/testkit/index.ts +123 -0
- package/src/index.ts +170 -0
- package/src/runtime/adapter.ts +303 -0
- package/src/runtime/auto.ts +110 -0
- package/src/runtime/bun.ts +55 -0
- package/src/runtime/deno.ts +369 -0
- package/src/runtime/detect.ts +105 -0
- package/src/runtime/index.ts +21 -0
- package/src/runtime/node-builtins.d.ts +23 -0
- package/src/runtime/node.ts +300 -0
- package/src/runtime/paths.ts +62 -0
- package/src/runtime/support.ts +135 -0
- package/src/runtime.ts +31 -0
- package/src/testkit.ts +25 -0
- package/src/version.ts +20 -0
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { FlagSchema } from "../schema/flag.mjs";
|
|
2
|
+
import { CommandSchema } from "../schema/command.mjs";
|
|
3
|
+
|
|
4
|
+
//#region src/core/cli/propagate.d.ts
|
|
5
|
+
/**
|
|
6
|
+
* Collect propagated flags from a command path.
|
|
7
|
+
*
|
|
8
|
+
* The command path is an ordered array of {@linkcode CommandSchema} from the root
|
|
9
|
+
* ancestor to the target command that will actually execute. Each ancestor's
|
|
10
|
+
* flags marked `propagate: true` are accumulated. If a descendant (including
|
|
11
|
+
* the target) defines a flag with the same name — regardless of whether the
|
|
12
|
+
* descendant's flag has `propagate: true` — it shadows the ancestor's flag.
|
|
13
|
+
*
|
|
14
|
+
* The target command's own flags are **not** included in the result. This
|
|
15
|
+
* function returns only the *inherited* propagated flags that should be merged
|
|
16
|
+
* into the target command's flag set before resolution.
|
|
17
|
+
*
|
|
18
|
+
* @param commandPath - Ordered schemas from root ancestor to target (inclusive).
|
|
19
|
+
* Must contain at least one element (the target itself). When the path has
|
|
20
|
+
* only one element, no ancestors exist and the result is empty.
|
|
21
|
+
*
|
|
22
|
+
* @returns A record of propagated flag schemas keyed by flag name. Empty when
|
|
23
|
+
* the path has no ancestors or no ancestor flags have `propagate: true`.
|
|
24
|
+
*
|
|
25
|
+
* @example
|
|
26
|
+
* ```ts
|
|
27
|
+
* // Given: root (--verbose [propagate]) → db → migrate
|
|
28
|
+
* // Where migrate does NOT define --verbose
|
|
29
|
+
* const inherited = collectPropagatedFlags([rootSchema, dbSchema, migrateSchema]);
|
|
30
|
+
* // inherited = { verbose: <FlagSchema from root> }
|
|
31
|
+
*
|
|
32
|
+
* // If db also defines --verbose (shadowing root):
|
|
33
|
+
* const inherited2 = collectPropagatedFlags([rootSchema, dbSchemaWithVerbose, migrateSchema]);
|
|
34
|
+
* // inherited2 = { verbose: <FlagSchema from db> }
|
|
35
|
+
* ```
|
|
36
|
+
*/
|
|
37
|
+
declare function collectPropagatedFlags(commandPath: readonly CommandSchema[]): Readonly<Record<string, FlagSchema>>;
|
|
38
|
+
//#endregion
|
|
39
|
+
export { collectPropagatedFlags };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function e(e){if(e.length<=1)return{};let t={};for(let n=0;n<e.length-1;n++){let r=e[n];if(r!==void 0){for(let[i,a]of Object.entries(r.flags))if(a.propagate){let r=!1;for(let t=n+1;t<e.length-1;t++){let n=e[t];if(n!==void 0&&i in n.flags){r=!0;break}}r||(t[i]=a)}}}let n=e[e.length-1];if(n!==void 0)for(let e of Object.keys(n.flags))delete t[e];return t}export{e as collectPropagatedFlags};
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { HelpOptions } from "../help/index.mjs";
|
|
2
|
+
import { CommandSchema } from "../schema/command.mjs";
|
|
3
|
+
|
|
4
|
+
//#region src/core/cli/root-help.d.ts
|
|
5
|
+
/** Structural subset of `CLISchema` — avoids circular imports through the barrel. */
|
|
6
|
+
interface CLISchemaLike {
|
|
7
|
+
readonly name: string;
|
|
8
|
+
readonly version: string | undefined;
|
|
9
|
+
readonly description: string | undefined;
|
|
10
|
+
readonly commands: ReadonlyArray<{
|
|
11
|
+
readonly schema: CommandSchema;
|
|
12
|
+
}>;
|
|
13
|
+
readonly defaultCommand: {
|
|
14
|
+
readonly schema: CommandSchema;
|
|
15
|
+
} | undefined;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Generate root-level help text for the CLI program.
|
|
19
|
+
*
|
|
20
|
+
* Shows program name, version, description, usage line, and available
|
|
21
|
+
* commands. When the default command is the only visible top-level
|
|
22
|
+
* command, merges the root summary with that command's detailed help.
|
|
23
|
+
*
|
|
24
|
+
* @internal
|
|
25
|
+
*/
|
|
26
|
+
declare function formatRootHelp(schema: CLISchemaLike, options?: HelpOptions): string;
|
|
27
|
+
//#endregion
|
|
28
|
+
export { formatRootHelp };
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import{resolveRootSurface as e}from"./root-surface.mjs";import{formatHelpSections as t}from"../help/index.mjs";function n(n,a){let s=a?.width??80,c=e(n);if(c.hasSingleVisibleDefault){let e=c.visibleDefaultCommand;if(e!==void 0){let i=r(n,c.visibleCommands,c.visibleDefaultCommand,s),l=i.findIndex(e=>e.startsWith(`Usage: `)),u=[...t(e,{...a,binName:n.name,isDefaultHelp:!0})],d=u.shift();return l!==-1&&d!==void 0&&(i[l]=o(i[l]??``,d)),e.description!==void 0&&n.description!==void 0&&e.description===n.description&&u.shift(),i.push(...u),`${i.join(`
|
|
2
|
+
|
|
3
|
+
`)}\n`}}let l=r(n,c.visibleCommands,c.visibleDefaultCommand,s),u=i(c.visibleCommands,c.visibleDefaultCommand);return l.push(u.length>0?`Run '${n.name} ${u} --help' for more information.`:`Run '${n.name} --help' for more information.`),`${l.join(`
|
|
4
|
+
|
|
5
|
+
`)}\n`}function r(e,t,n,r){let o=[],s=e.version===void 0?e.name:`${e.name} v${e.version}`;o.push(s),e.description!==void 0&&o.push(e.description);let c=i(t,n);return o.push(c.length>0?`Usage: ${e.name} ${c} [options]`:`Usage: ${e.name} [options]`),t.length>0&&o.push(a(t,n?.name,r)),o}function i(e,t){return e.length===0&&t===void 0?``:t===void 0?`<command>`:`[command]`}function a(e,t,n){let r=[`Commands:`],i=0;for(let n of e){let e=n.name===t?10:0,r=n.name.length+e;r>i&&(i=r)}let a=2+i+2;for(let i of e){let e=s(` ${i.name===t?`${i.name} (default)`:i.name}`,a),o=i.description??``;o.length===0?r.push(e.trimEnd()):r.push(`${e}${c(o,n,a)}`)}return r.join(`
|
|
6
|
+
`)}function o(e,t){let n=t.startsWith(`Usage: `)?t.slice(7):t;return`${e}\n${` `.repeat(7)}${n}`}function s(e,t){return e.length>=t?e:e+` `.repeat(t-e.length)}function c(e,t,n){if(e.length+n<=t)return e;let r=t-n;if(r<=0)return e;let i=e.split(` `),a=[],o=``;for(let e of i)o.length===0?o=e:o.length+1+e.length<=r?o+=` ${e}`:(a.push(o),o=e);o.length>0&&a.push(o);let s=` `.repeat(n);return a.map((e,t)=>t===0?e:`${s}${e}`).join(`
|
|
7
|
+
`)}export{n as formatRootHelp};
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { CommandSchema } from "../schema/command.mjs";
|
|
2
|
+
|
|
3
|
+
//#region src/core/cli/root-surface.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* Structural CLI shape needed for root-surface analysis.
|
|
6
|
+
*
|
|
7
|
+
* Uses structural typing to avoid importing the full `CLISchema` and
|
|
8
|
+
* creating unnecessary cross-module coupling.
|
|
9
|
+
*
|
|
10
|
+
* @internal
|
|
11
|
+
*/
|
|
12
|
+
interface RootSurfaceSchemaLike {
|
|
13
|
+
readonly commands: ReadonlyArray<{
|
|
14
|
+
readonly schema: CommandSchema;
|
|
15
|
+
}>;
|
|
16
|
+
readonly defaultCommand: {
|
|
17
|
+
readonly schema: CommandSchema;
|
|
18
|
+
} | undefined;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Normalized root shape shared by help and completion logic.
|
|
22
|
+
*
|
|
23
|
+
* @internal
|
|
24
|
+
*/
|
|
25
|
+
interface RootSurface {
|
|
26
|
+
readonly visibleCommands: readonly CommandSchema[];
|
|
27
|
+
readonly visibleDefaultCommand: CommandSchema | undefined;
|
|
28
|
+
readonly hasSingleVisibleDefault: boolean;
|
|
29
|
+
readonly hasVisibleSiblingCommands: boolean;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Resolve the visible shape of the CLI root.
|
|
33
|
+
*
|
|
34
|
+
* Hidden commands are excluded from the visible command list. Hidden
|
|
35
|
+
* default commands remain executable, but are not surfaced through
|
|
36
|
+
* help or completions.
|
|
37
|
+
*
|
|
38
|
+
* @internal
|
|
39
|
+
*/
|
|
40
|
+
declare function resolveRootSurface(schema: RootSurfaceSchemaLike): RootSurface;
|
|
41
|
+
//#endregion
|
|
42
|
+
export { type RootSurface, type RootSurfaceSchemaLike, resolveRootSurface };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function e(e){let t=e.commands.map(e=>e.schema).filter(e=>!e.hidden),n=e.defaultCommand?.schema,r=n!==void 0&&!n.hidden?n:void 0;return{visibleCommands:t,visibleDefaultCommand:r,hasSingleVisibleDefault:r!==void 0&&t.length===1&&t[0]?.name===r.name,hasVisibleSiblingCommands:r!==void 0&&t.some(e=>e.name!==r.name)}}export{e as resolveRootSurface};
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
import { Verbosity } from "../output/contracts.mjs";
|
|
2
|
+
import { PromptEngine } from "../prompt/index.mjs";
|
|
3
|
+
import { CLIPlugin } from "./plugin.mjs";
|
|
4
|
+
import { CLIError } from "../errors/index.mjs";
|
|
5
|
+
import { CommandSchema, ErasedCommand } from "../schema/command.mjs";
|
|
6
|
+
import { RuntimeAdapter } from "../../runtime/adapter.mjs";
|
|
7
|
+
import { FormatLoader } from "../config/index.mjs";
|
|
8
|
+
|
|
9
|
+
//#region src/core/cli/runtime-preflight.d.ts
|
|
10
|
+
/** Config discovery settings extracted from CLISchema for preflight use. @internal */
|
|
11
|
+
interface RuntimeConfigSettings {
|
|
12
|
+
/** Application name used to locate config files (e.g. `~/.config/<appName>/`). */
|
|
13
|
+
readonly appName: string;
|
|
14
|
+
/** Optional format loaders (JSON/YAML/TOML); `undefined` uses built-in JSON. */
|
|
15
|
+
readonly loaders: readonly FormatLoader[] | undefined;
|
|
16
|
+
}
|
|
17
|
+
/** Package.json discovery settings extracted from CLISchema. @internal */
|
|
18
|
+
interface RuntimePackageJsonSettings {
|
|
19
|
+
/** Whether to infer the CLI binary name from `package.json` `bin` field. */
|
|
20
|
+
readonly inferName: boolean;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Structural subset of CLISchema used by runtime preflight.
|
|
24
|
+
*
|
|
25
|
+
* Decouples adapter-driven sourcing (config, package.json, stdin) from the
|
|
26
|
+
* full CLIBuilder surface so preflight can be tested independently.
|
|
27
|
+
* @internal
|
|
28
|
+
*/
|
|
29
|
+
interface RuntimePreflightSchemaLike {
|
|
30
|
+
/** CLI program name; may be overridden by package.json discovery or inheritance. */
|
|
31
|
+
readonly name: string;
|
|
32
|
+
/** Whether this CLI inherits its name from a parent (nested CLI embedding). */
|
|
33
|
+
readonly inheritName: boolean;
|
|
34
|
+
/** Declared version; `undefined` means version will be inferred from package.json if available. */
|
|
35
|
+
readonly version: string | undefined;
|
|
36
|
+
/** Declared description; `undefined` allows package.json inference. */
|
|
37
|
+
readonly description: string | undefined;
|
|
38
|
+
/** Registered top-level commands for dispatch planning during stdin detection. */
|
|
39
|
+
readonly commands: readonly ErasedCommand[];
|
|
40
|
+
/** Fallback command when no subcommand token matches. */
|
|
41
|
+
readonly defaultCommand: ErasedCommand | undefined;
|
|
42
|
+
/** Config file discovery settings; `undefined` disables config loading. */
|
|
43
|
+
readonly configSettings: RuntimeConfigSettings | undefined;
|
|
44
|
+
/** Package.json discovery settings; `undefined` disables package.json inference. */
|
|
45
|
+
readonly packageJsonSettings: RuntimePackageJsonSettings | undefined;
|
|
46
|
+
/** Whether `.completions()` registered the built-in completions command. */
|
|
47
|
+
readonly hasBuiltInCompletions: boolean;
|
|
48
|
+
/** Plugins forwarded into the execution pipeline. */
|
|
49
|
+
readonly plugins: readonly CLIPlugin[];
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Caller-supplied overrides for runtime preflight.
|
|
53
|
+
*
|
|
54
|
+
* When provided, these bypass adapter auto-detection (useful for testing
|
|
55
|
+
* and the `CLIRunOptions` public surface).
|
|
56
|
+
* @internal
|
|
57
|
+
*/
|
|
58
|
+
interface RuntimePreflightOptions {
|
|
59
|
+
/** Environment variables override; bypasses adapter env when set. */
|
|
60
|
+
readonly env?: Readonly<Record<string, string | undefined>>;
|
|
61
|
+
/** Pre-loaded config object; skips config file discovery when set. */
|
|
62
|
+
readonly config?: Readonly<Record<string, unknown>>;
|
|
63
|
+
/** Pre-read stdin data; `null` means stdin was explicitly empty. */
|
|
64
|
+
readonly stdinData?: string | null;
|
|
65
|
+
/** Custom prompt engine; bypasses terminal prompter auto-creation. */
|
|
66
|
+
readonly prompter?: PromptEngine;
|
|
67
|
+
/** Output verbosity level override. */
|
|
68
|
+
readonly verbosity?: Verbosity;
|
|
69
|
+
/** Force JSON output mode regardless of `--json` flag presence. */
|
|
70
|
+
readonly jsonMode?: boolean;
|
|
71
|
+
/** TTY detection override; bypasses adapter TTY check. */
|
|
72
|
+
readonly isTTY?: boolean;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Fully resolved runtime inputs ready for the execution pipeline.
|
|
76
|
+
*
|
|
77
|
+
* All adapter vs. caller-override decisions are settled by the time this
|
|
78
|
+
* is constructed; the executor treats these as final truth.
|
|
79
|
+
* @internal
|
|
80
|
+
*/
|
|
81
|
+
interface RuntimeExecutionInputs {
|
|
82
|
+
/** Resolved environment variables (from adapter or caller override). */
|
|
83
|
+
readonly env: Readonly<Record<string, string | undefined>>;
|
|
84
|
+
/** Whether stdout is a TTY (controls color, spinners, interactive prompts). */
|
|
85
|
+
readonly isTTY: boolean;
|
|
86
|
+
/** Whether structured JSON output mode is active. */
|
|
87
|
+
readonly jsonMode: boolean;
|
|
88
|
+
/** Output verbosity level. */
|
|
89
|
+
readonly verbosity: Verbosity;
|
|
90
|
+
/** Pre-read stdin data if the invocation declared stdin-mode args. */
|
|
91
|
+
readonly stdinData?: string | null;
|
|
92
|
+
/** Prompt engine for interactive flag resolution; absent in non-TTY. */
|
|
93
|
+
readonly prompter?: PromptEngine;
|
|
94
|
+
/** Loaded config data for the config resolution step. */
|
|
95
|
+
readonly config?: Readonly<Record<string, unknown>>;
|
|
96
|
+
}
|
|
97
|
+
/** Preflight succeeded — all runtime inputs are resolved and ready for execution. @internal */
|
|
98
|
+
interface ReadyRuntimePreflight {
|
|
99
|
+
/** Discriminant — preflight completed without errors. */
|
|
100
|
+
readonly kind: 'ready';
|
|
101
|
+
/** Schema after package.json discovery and name inheritance applied. */
|
|
102
|
+
readonly schema: RuntimePreflightSchemaLike;
|
|
103
|
+
/** Argv with valid runtime `--config` tokens stripped out. */
|
|
104
|
+
readonly filteredArgv: readonly string[];
|
|
105
|
+
/** Fully resolved runtime inputs for the execution pipeline. */
|
|
106
|
+
readonly inputs: RuntimeExecutionInputs;
|
|
107
|
+
}
|
|
108
|
+
/** Preflight failed during config file discovery/loading. @internal */
|
|
109
|
+
interface RuntimeConfigErrorPreflight {
|
|
110
|
+
/** Discriminant — config loading produced a structured error. */
|
|
111
|
+
readonly kind: 'config-error';
|
|
112
|
+
/** The config discovery/parse error to render. */
|
|
113
|
+
readonly error: CLIError;
|
|
114
|
+
/** Whether JSON output was requested (needed to choose error rendering). */
|
|
115
|
+
readonly jsonMode: boolean;
|
|
116
|
+
}
|
|
117
|
+
/** Discriminated union of preflight outcomes — either ready or config-error. @internal */
|
|
118
|
+
type RuntimePreflightResult = ReadyRuntimePreflight | RuntimeConfigErrorPreflight;
|
|
119
|
+
/** Options bag for {@linkcode prepareRuntimePreflight}. @internal */
|
|
120
|
+
interface PrepareRuntimePreflightOptions {
|
|
121
|
+
/** CLI schema subset driving preflight decisions. */
|
|
122
|
+
readonly schema: RuntimePreflightSchemaLike;
|
|
123
|
+
/** Runtime adapter providing argv, env, stdin, and filesystem access. */
|
|
124
|
+
readonly adapter: RuntimeAdapter;
|
|
125
|
+
/** Caller-supplied overrides; `undefined` means auto-detect everything. */
|
|
126
|
+
readonly options: RuntimePreflightOptions | undefined;
|
|
127
|
+
/** Name inherited from a parent CLI (nested embedding); `undefined` for standalone. */
|
|
128
|
+
readonly inheritedName: string | undefined;
|
|
129
|
+
}
|
|
130
|
+
/** Extract and strip valid runtime `--config` forms from argv, returning path + filtered tokens. @internal */
|
|
131
|
+
declare function extractConfigFlag(argv: readonly string[]): {
|
|
132
|
+
readonly configPath: string | undefined;
|
|
133
|
+
readonly filteredArgv: readonly string[];
|
|
134
|
+
};
|
|
135
|
+
/** Check whether a single command's args declare stdin-mode and argv leaves them unresolved. @internal */
|
|
136
|
+
declare function commandInvocationNeedsStdin(schema: CommandSchema, argv: readonly string[]): boolean;
|
|
137
|
+
/** Plan the invocation and check whether the matched command needs stdin data. @internal */
|
|
138
|
+
declare function invocationNeedsStdin(schema: RuntimePreflightSchemaLike, argv: readonly string[]): boolean;
|
|
139
|
+
/**
|
|
140
|
+
* Run all adapter-driven sourcing work before command execution.
|
|
141
|
+
*
|
|
142
|
+
* Discovers config files, reads package.json metadata, detects stdin needs,
|
|
143
|
+
* wires up the prompt engine, and resolves output policy overrides into a
|
|
144
|
+
* single {@linkcode RuntimePreflightResult}.
|
|
145
|
+
* @internal
|
|
146
|
+
*/
|
|
147
|
+
declare function prepareRuntimePreflight(options: PrepareRuntimePreflightOptions): Promise<RuntimePreflightResult>;
|
|
148
|
+
//#endregion
|
|
149
|
+
export { type PrepareRuntimePreflightOptions, type ReadyRuntimePreflight, type RuntimeExecutionInputs, type RuntimePreflightOptions, type RuntimePreflightResult, type RuntimePreflightSchemaLike, commandInvocationNeedsStdin, extractConfigFlag, invocationNeedsStdin, prepareRuntimePreflight };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{CLIError as e,ParseError as t}from"../errors/index.mjs";import{parse as n}from"../parse/index.mjs";import{createTerminalPrompter as r}from"../prompt/index.mjs";import{planInvocation as i}from"./planner.mjs";import{discoverPackageJson as a,inferCliName as o}from"../config/package-json.mjs";import{discoverConfig as s}from"../config/index.mjs";const c={jsonMode:!1,isTTY:!1,verbosity:`normal`};function l(e){let t=[],n;for(let r=0;r<e.length;r+=1){let i=e[r];if(i!==void 0){if(i===`--`){t.push(...e.slice(r));break}if(n===void 0&&i.startsWith(`--config=`)){let e=i.slice(9);if(e.length>0){n=e;continue}t.push(i);continue}if(n===void 0&&i===`--config`){let a=e[r+1];if(a!==void 0&&!a.startsWith(`-`)&&a!==`--`){n=a,r+=1;continue}t.push(i);continue}t.push(i)}}return{configPath:n,filteredArgv:t}}function u(e,r){if(r.includes(`--help`)||r.includes(`-h`))return!1;try{let t=n(e,r);return e.args.some(({name:e,schema:n})=>{let r=t.args[e];return n.stdinMode&&(r===void 0||r===`-`)})}catch(e){if(e instanceof t)return!1;throw e}}function d(e,t){let n=i({schema:e,argv:t,help:{binName:e.name},output:c});switch(n.kind){case`match`:return u(n.plan.mergedSchema,n.plan.argv);case`dispatch-error`:case`needs-subcommand`:case`root-help`:case`root-version`:return!1}}function f(e,t){if(!e.hasBuiltInCompletions)return!1;let n=i({schema:e,argv:t,help:{binName:e.name},output:c});return n.kind===`match`&&n.plan.command.schema.name===`completions`}async function p(e,t,n,r){let i=e.packageJsonSettings,s=i!==void 0&&!r?await(async()=>{let n=await a(t);if(n===null)return e;let r=i.inferName?o(n):void 0;return{...e,...e.version===void 0&&n.version!==void 0?{version:n.version}:{},...e.description===void 0&&n.description!==void 0?{description:n.description}:{},...r===void 0?{}:{name:r}}})():e;return n===void 0?s:{...s,name:n}}async function m(t,n,r,i,a){if(t.configSettings===void 0||i||a!==void 0)return a;try{let e=await s(t.configSettings.appName,n,{...r===void 0?{}:{configPath:r},...t.configSettings.loaders===void 0?{}:{loaders:t.configSettings.loaders}});return e.found?e.data:void 0}catch(t){if(t instanceof e)return t;throw t}}async function h(t){let n=t.adapter.argv.slice(2),{configPath:i,filteredArgv:a}=t.schema.configSettings===void 0?{configPath:void 0,filteredArgv:n}:l(n),o=a.includes(`--json`)||t.options?.jsonMode===!0,s=f(t.schema,a),c=await p(t.schema,t.adapter,t.inheritedName,s),u=await m(c,t.adapter,i,s,t.options?.config);if(u instanceof e)return{kind:`config-error`,error:u,jsonMode:o};let h=t.options?.prompter===void 0&&t.adapter.stdinIsTTY?r(t.adapter.stdin,t.adapter.stderr):void 0,g=t.options?.stdinData===void 0&&d(c,a)?await t.adapter.readStdin():t.options?.stdinData;return{kind:`ready`,schema:c,filteredArgv:a,inputs:{env:t.options?.env??t.adapter.env,isTTY:t.options?.isTTY??t.adapter.isTTY,jsonMode:o,verbosity:t.options?.verbosity??`normal`,...g===void 0?{}:{stdinData:g},...t.options?.prompter===void 0?h===void 0?{}:{prompter:h}:{prompter:t.options.prompter},...u===void 0?{}:{config:u}}}}export{h as prepareRuntimePreflight};
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { CompletionOptions } from "./shells/shared.mjs";
|
|
2
|
+
import { generateBashCompletion } from "./shells/bash.mjs";
|
|
3
|
+
import { generateFishCompletion } from "./shells/fish.mjs";
|
|
4
|
+
import { generatePowerShellCompletion } from "./shells/powershell.mjs";
|
|
5
|
+
import { generateZshCompletion } from "./shells/zsh.mjs";
|
|
6
|
+
import { CLISchema } from "../cli/index.mjs";
|
|
7
|
+
|
|
8
|
+
//#region src/core/completion/index.d.ts
|
|
9
|
+
/**
|
|
10
|
+
* Supported shell targets for completion script generation.
|
|
11
|
+
*
|
|
12
|
+
* `bash`, `zsh`, `fish`, and `powershell` are implemented today.
|
|
13
|
+
*/
|
|
14
|
+
type Shell = 'bash' | 'zsh' | 'fish' | 'powershell';
|
|
15
|
+
/**
|
|
16
|
+
* Implemented shell values as a frozen readonly non-empty tuple.
|
|
17
|
+
*
|
|
18
|
+
* Use this tuple for user-facing validation and shell selection UIs.
|
|
19
|
+
* It intentionally matches the shipped {@link Shell} union exactly so docs,
|
|
20
|
+
* help output, and completion generation advertise the same support surface.
|
|
21
|
+
*
|
|
22
|
+
* @see {@link Shell} for the union type matching these entries.
|
|
23
|
+
*/
|
|
24
|
+
declare const SHELLS: Readonly<readonly ['bash', 'zsh', 'fish', 'powershell']>;
|
|
25
|
+
/**
|
|
26
|
+
* Generate a completion script for the given shell.
|
|
27
|
+
*
|
|
28
|
+
* This is the primary completion entrypoint for most consumers. Pass a CLI
|
|
29
|
+
* schema and target shell, then write the returned script to a file or source
|
|
30
|
+
* it directly from the command line.
|
|
31
|
+
*
|
|
32
|
+
* @param schema - The CLI schema describing commands, flags, and args.
|
|
33
|
+
* @param shell - Target shell.
|
|
34
|
+
* @param options - Optional generator configuration such as function naming
|
|
35
|
+
* and root default-command completion behavior.
|
|
36
|
+
* @returns A complete shell completion script as a string.
|
|
37
|
+
*
|
|
38
|
+
* @example
|
|
39
|
+
* ```ts
|
|
40
|
+
* const script = generateCompletion(app.schema, 'bash');
|
|
41
|
+
* // e.g. source <(mycli completions bash)
|
|
42
|
+
* ```
|
|
43
|
+
*/
|
|
44
|
+
declare function generateCompletion(schema: CLISchema, shell: Shell, options?: CompletionOptions): string;
|
|
45
|
+
//#endregion
|
|
46
|
+
export { type CompletionOptions, SHELLS, type Shell, generateBashCompletion, generateCompletion, generateFishCompletion, generatePowerShellCompletion, generateZshCompletion };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{generateBashCompletion as e}from"./shells/bash.mjs";import{generateFishCompletion as t}from"./shells/fish.mjs";import{generatePowerShellCompletion as n}from"./shells/powershell.mjs";import{generateZshCompletion as r}from"./shells/zsh.mjs";const i=Object.freeze([`bash`,`zsh`,`fish`,`powershell`]);function a(i,a,o){switch(a){case`bash`:return e(i,o);case`zsh`:return r(i,o);case`fish`:return t(i,o);case`powershell`:return n(i,o)}}export{i as SHELLS,a as generateCompletion};
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { CompletionOptions } from "./shared.mjs";
|
|
2
|
+
import { CLISchema } from "../../cli/index.mjs";
|
|
3
|
+
|
|
4
|
+
//#region src/core/completion/shells/bash.d.ts
|
|
5
|
+
/**
|
|
6
|
+
* Generate a bash completion script for the CLI.
|
|
7
|
+
*
|
|
8
|
+
* Use this when you want a bash-specific script directly rather than routing
|
|
9
|
+
* through {@link generateCompletion}. The generated script expects the
|
|
10
|
+
* `bash-completion` package because it relies on `_init_completion`.
|
|
11
|
+
*
|
|
12
|
+
* @param schema - The CLI schema.
|
|
13
|
+
* @param options - Optional generator configuration.
|
|
14
|
+
* @returns A complete bash completion script.
|
|
15
|
+
*
|
|
16
|
+
* @example
|
|
17
|
+
* ```ts
|
|
18
|
+
* const script = generateBashCompletion(app.schema);
|
|
19
|
+
* // install with: mycli completions bash > /etc/bash_completion.d/mycli
|
|
20
|
+
* ```
|
|
21
|
+
*/
|
|
22
|
+
declare function generateBashCompletion(schema: CLISchema, options?: CompletionOptions): string;
|
|
23
|
+
//#endregion
|
|
24
|
+
export { generateBashCompletion };
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{getFlagAliasNames as e}from"../../schema/flag.mjs";import{quoteShellArg as t,resolveRootCompletionSurface as n,sanitizeShellIdentifier as r,versionTag as i,walkCommandTree as a}from"./shared.mjs";function o(e,o){let l=`_${r(o?.functionPrefix??e.name)}_completions`,u=n(e,o?.rootMode),p=u.visibleCommands,v=a(p),y=v.reduce((e,t)=>Math.max(e,t.path.length),0),b=[];if(b.push(`#!/usr/bin/env bash`),b.push(`# Bash completion for ${e.name}`),b.push(`# Generated by ${i()}`),b.push(`#`),b.push(`# Usage: source <(${e.name} completions bash)`),b.push(`#`),b.push(`# Install permanently:`),b.push(`# ${e.name} completions bash > /etc/bash_completion.d/${e.name} # Linux`),b.push(`# ${e.name} completions bash > $(brew --prefix)/etc/bash_completion.d/${e.name} # macOS`),b.push(`#`),b.push(`# Requires: bash-completion (provides _init_completion)`),b.push(``),b.push(`${l}() {`),b.push(` local cur prev words cword`),b.push(` _init_completion || return`),b.push(``),p.length>0){let e=v.filter(e=>e.children.length>0),t=h(v,u);b.push(` # Build subcommand path by scanning COMP_WORDS`),b.push(` local subcmd_path=""`),b.push(` local i`),b.push(` for ((i = 1; i < cword; i++)); do`),b.push(' case "${words[i]}" in'),b.push(` --) break ;;`),t.length>0&&b.push(`\t\t\t${t}) ((i++)); continue ;;`),b.push(` -*) continue ;;`),b.push(` esac`),s(b,p,e,y),b.push(` done`),b.push(``),b.push(` # Complete flags and subcommands for the active path`),b.push(` case "$subcmd_path" in`);for(let e of v){let t=e.path.join(` `),n=e.mergedFlags,r=_(n),i=m(n),a=g(e.children.flatMap(e=>[e.name,...e.aliases])).map(d).join(` `),o=i.split(` `).filter(Boolean).map(d).join(` `),s=a.length>0?`${a} ${o}`:o;if(b.push(`\t\t${c(t)})`),r.length>0){b.push(` local enum_flag=""`),b.push(` local enum_cur="$cur"`),b.push(` local enum_prefix=""`),b.push(` if [[ "$cur" == --*=* ]]; then`),b.push(' enum_flag="${cur%%=*}"'),b.push(' enum_cur="${cur#*=}"'),b.push(' enum_prefix="${cur%%=*}="'),b.push(` fi`),b.push(' case "${enum_flag:-$prev}" in');for(let e of r)b.push(`\t\t\t\t${e.flags})`),b.push(f(e.values,` `,`enum_cur`,`enum_prefix`)),b.push(` return`),b.push(` ;;`);b.push(` *)`),b.push(` ;;`),b.push(` esac`)}b.push(`\t\t\tCOMPREPLY=($(compgen -W '${s.trim()}' -- "$cur"))`),b.push(` return`),b.push(` ;;`)}b.push(` *)`),b.push(` ;;`),b.push(` esac`),b.push(``);let n=m(u.rootFlags).split(` `).filter(Boolean),r=u.includeDefaultFlags?m(u.defaultFlags).split(` `).filter(Boolean):[],i=g([...p.flatMap(e=>[e.name,...e.aliases]),...n,...r]).map(d).join(` `);b.push(` # Root-level completions: visible root surface`),b.push(`\tCOMPREPLY=($(compgen -W '${i}' -- "$cur"))`)}else{let e=m(u.rootFlags);b.push(`\tCOMPREPLY=($(compgen -W '${e}' -- "$cur"))`)}return b.push(`}`),b.push(``),b.push(`complete -F ${l} ${t(e.name)}`),b.push(``),b.join(`
|
|
2
|
+
`)}function s(e,t,n,r){e.push(` case "$subcmd_path" in`),e.push(` '')`),e.push(' case "${words[i]}" in');for(let n of t){let t=[n.name,...n.aliases].map(l);e.push(`\t\t\t\t\t${t.join(`|`)})`),e.push(`\t\t\t\t\t\tsubcmd_path="${u(n.name)}"`),e.push(` ;;`)}if(e.push(` esac`),e.push(` ;;`),r>1)for(let t of n){let n=t.path.join(` `);e.push(`\t\t\t${c(n)})`),e.push(' case "${words[i]}" in');for(let n of t.children){let t=[n.name,...n.aliases].map(l);e.push(`\t\t\t\t\t${t.join(`|`)})`),e.push(`\t\t\t\t\t\tsubcmd_path="$subcmd_path ${u(n.name)}"`),e.push(` ;;`)}e.push(` esac`),e.push(` ;;`)}e.push(` esac`)}function c(e){return e.includes(` `)?`"${u(e)}"`:l(e)}function l(e){return/^[a-zA-Z0-9_\-.]+$/.test(e)?e:e.replace(/\\/g,`\\\\`).replace(/'/g,`\\'`).replace(/"/g,`\\"`).replace(/\|/g,`\\|`).replace(/\*/g,`\\*`).replace(/\?/g,`\\?`).replace(/\[/g,`\\[`).replace(/\]/g,`\\]`).replace(/\(/g,`\\(`).replace(/\)/g,`\\)`).replace(/\{/g,`\\{`).replace(/\}/g,`\\}`).replace(/\+/g,`\\+`).replace(/!/g,`\\!`).replace(/@/g,`\\@`).replace(/#/g,`\\#`).replace(/~/g,`\\~`).replace(/\s/g,e=>e===` `?`\\ `:`\\${e}`)}function u(e){return e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`).replace(/\$/g,`\\$`).replace(/`/g,"\\`")}function d(e){return/^[a-zA-Z0-9_\-.]+$/.test(e)?e:e.replace(/'/g,`'\\''`)}function f(e,t,n=`cur`,r){let i=[];if(e.some(e=>!/^[a-zA-Z0-9_\-.]+$/.test(e))){let r=e.map(p).join(`\\n`);i.push(`${t}local IFS=$'\\n'`),i.push(`${t}COMPREPLY=($(compgen -W $'${r}' -- "$${n}"))`)}else i.push(`${t}COMPREPLY=($(compgen -W '${e.join(` `)}' -- "$${n}"))`);return r!==void 0&&(i.push(`${t}if [[ -n "$${r}" && "\${#COMPREPLY[@]}" -gt 0 ]]; then`),i.push(`${t}\tlocal i`),i.push(`${t}\tfor ((i = 0; i < \${#COMPREPLY[@]}; i++)); do`),i.push(`${t}\t\tCOMPREPLY[i]="$${r}\${COMPREPLY[i]}"`),i.push(`${t}\tdone`),i.push(`${t}fi`)),i.join(`
|
|
3
|
+
`)}function p(e){return e.replace(/\\/g,`\\\\`).replace(/'/g,`\\'`).replace(/\n/g,`\\n`)}function m(t){let n=[];for(let[r,i]of Object.entries(t)){n.push(`--${r}`);for(let t of e(i))n.push(t.length===1?`-${t}`:`--${t}`)}return n.join(` `)}function h(t,n){let r=new Set,i=t=>{for(let[n,i]of Object.entries(t))if(i.kind!==`boolean`){r.add(`--${n}`);for(let t of e(i,{includeHidden:!0}))r.add(t.length===1?`-${t}`:`--${t}`)}};for(let e of t)i(e.mergedFlags);return i(n.rootFlags),n.includeDefaultFlags&&i(n.defaultFlags),[...r].map(l).join(`|`)}function g(e){return[...new Set(e)]}function _(t){let n=[];for(let[r,i]of Object.entries(t)){if(i.kind!==`enum`||i.enumValues===void 0)continue;let t=[`--${r}`,...e(i,{includeHidden:!0}).map(e=>e.length===1?`-${e}`:`--${e}`)].map(l);n.push({flags:t.join(`|`),values:i.enumValues})}return n}export{o as generateBashCompletion};
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { CompletionOptions } from "./shared.mjs";
|
|
2
|
+
import { CLISchema } from "../../cli/index.mjs";
|
|
3
|
+
|
|
4
|
+
//#region src/core/completion/shells/fish.d.ts
|
|
5
|
+
/**
|
|
6
|
+
* Generate a fish completion script for the CLI.
|
|
7
|
+
*
|
|
8
|
+
* @param schema - The CLI schema.
|
|
9
|
+
* @param options - Optional generator configuration.
|
|
10
|
+
* @returns A complete fish completion script.
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* ```ts
|
|
14
|
+
* const script = generateFishCompletion(app.schema);
|
|
15
|
+
* // install with: mycli completions fish > ~/.config/fish/completions/mycli.fish
|
|
16
|
+
* ```
|
|
17
|
+
*/
|
|
18
|
+
declare function generateFishCompletion(schema: CLISchema, options?: CompletionOptions): string;
|
|
19
|
+
//#endregion
|
|
20
|
+
export { generateFishCompletion };
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{getFlagAliasNames as e}from"../../schema/flag.mjs";import{quoteShellArg as t,resolveRootCompletionSurface as n,sanitizeShellIdentifier as r,versionTag as i,walkCommandTree as a}from"./shared.mjs";function o(e,o){let u=`__${r(o?.functionPrefix??e.name)}_completions`,d=`${u}_path`,f=`${u}_path_is`,p=n(e,o?.rootMode),m=p.visibleCommands,h=a(m),g=t(e.name),_=[];_.push(`# Fish completion for ${e.name}`),_.push(`# Generated by ${i()}`),_.push(`#`),_.push(`# Usage: source (${e.name} completions fish | psub)`),_.push(`#`),_.push(`# Install permanently:`),_.push(`# ${e.name} completions fish > ~/.config/fish/completions/${e.name}.fish`),_.push(``),_.push(`complete -c ${g} -f`),_.push(``),s(_,d,f,m,h,p),c(_,g,f,``,m),l(_,g,f,``,p.rootFlags),p.includeDefaultFlags&&l(_,g,f,``,p.defaultFlags);for(let e of h){let t=e.path.join(` `);c(_,g,f,t,e.children),l(_,g,f,t,e.mergedFlags)}return _.join(`
|
|
2
|
+
`)}function s(e,n,r,i,a,o){let s=u(a,o);e.push(`function ${n}`),e.push(` set -l words (commandline -opc)`),e.push(` if test (count $words) -gt 0`),e.push(` set -e words[1]`),e.push(` end`),e.push(` set -l subcmd_path ''`),e.push(` set -l expect_value 0`),e.push(` for word in $words`),e.push(` if test $expect_value -eq 1`),e.push(` set expect_value 0`),e.push(` continue`),e.push(` end`),e.push(` switch $word`),e.push(` case '--'`),e.push(` break`),s.exact.length>0&&(e.push(`\t\t\tcase ${s.exact.map(t).join(` `)}`),e.push(` set expect_value 1`),e.push(` continue`)),s.prefix.length>0&&(e.push(`\t\t\tcase ${s.prefix.map(t).join(` `)}`),e.push(` continue`)),e.push(` case '-*'`),e.push(` continue`),e.push(` end`),e.push(` switch "$subcmd_path|$word"`);for(let n of i)for(let r of[n.name,...n.aliases])e.push(`\t\t\tcase ${t(`|${r}`)}`),e.push(`\t\t\t\tset subcmd_path ${t(n.name)}`);for(let n of a)for(let r of n.children)for(let i of[r.name,...r.aliases])e.push(`\t\t\tcase ${t(`${n.path.join(` `)}|${i}`)}`),e.push(`\t\t\t\tset subcmd_path ${t(`${n.path.join(` `)} ${r.name}`)}`);e.push(` case '*'`),e.push(` break`),e.push(` end`),e.push(` end`),e.push(` printf '%s\\n' "$subcmd_path"`),e.push(`end`),e.push(``),e.push(`function ${r}`),e.push(` set -l expected "$argv[1]"`),e.push(`\ttest (${n}) = "$expected"`),e.push(`end`),e.push(``)}function c(e,n,r,i,a){let o=d(r,i);for(let r of a){let i=t(r.description??r.name);for(let a of[r.name,...r.aliases])e.push(`complete -c ${n} -n "${o}" -a ${t(a)} -d ${i}`)}a.length>0&&e.push(``)}function l(n,r,i,a,o){let s=d(i,a);for(let[i,a]of Object.entries(o)){let o=[`complete -c ${r}`,`-n "${s}"`];for(let n of e(a,{kind:`short`}))o.push(`-s ${t(n)}`);o.push(`-l ${t(i)}`);for(let n of e(a,{kind:`long`}))o.push(`-l ${t(n)}`);if(o.push(`-d ${t(a.description??i)}`),a.kind!==`boolean`&&o.push(`-r`,`-f`),a.kind===`enum`&&a.enumValues!==void 0){for(let e of a.enumValues)n.push([...o,`-a ${t(e)}`].join(` `));continue}n.push(o.join(` `))}Object.keys(o).length>0&&n.push(``)}function u(t,n){let r=new Set,i=new Set,a=[n.rootFlags,...n.includeDefaultFlags?[n.defaultFlags]:[],...t.map(e=>e.mergedFlags)];for(let t of a)for(let[n,a]of Object.entries(t))if(a.kind!==`boolean`){r.add(`--${n}`),i.add(`--${n}=*`);for(let t of e(a,{kind:`short`,includeHidden:!0}))r.add(`-${t}`),i.add(`-${t}*`);for(let t of e(a,{kind:`long`,includeHidden:!0}))r.add(`--${t}`),i.add(`--${t}=*`)}return{exact:[...r],prefix:[...i]}}function d(e,n){return`${e} ${t(n)}`}export{o as generateFishCompletion};
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { CompletionOptions } from "./shared.mjs";
|
|
2
|
+
import { CLISchema } from "../../cli/index.mjs";
|
|
3
|
+
|
|
4
|
+
//#region src/core/completion/shells/powershell.d.ts
|
|
5
|
+
/**
|
|
6
|
+
* Generate a PowerShell completion script for the CLI.
|
|
7
|
+
*
|
|
8
|
+
* @param schema - The CLI schema.
|
|
9
|
+
* @param options - Optional generator configuration.
|
|
10
|
+
* @returns A complete PowerShell completion script.
|
|
11
|
+
*/
|
|
12
|
+
declare function generatePowerShellCompletion(schema: CLISchema, options?: CompletionOptions): string;
|
|
13
|
+
//#endregion
|
|
14
|
+
export { generatePowerShellCompletion };
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{getFlagAliasNames as e}from"../../schema/flag.mjs";import{resolveRootCompletionSurface as t,sanitizeShellIdentifier as n,versionTag as r,walkCommandTree as i}from"./shared.mjs";function a(e,a){let s=`__${n(a?.functionPrefix??e.name)}_completions`,u=`${s}_paths`,d=t(e,a?.rootMode),f=d.visibleCommands,p=i(f),m=[];return m.push(`# PowerShell completion for ${e.name}`),m.push(`# Generated by ${r()}`),m.push(`#`),m.push(`# Install for the current session:`),m.push(`# ${e.name} completions powershell | Invoke-Expression`),m.push(`#`),m.push(`# Install permanently:`),m.push(`# ${e.name} completions powershell > $PROFILE.CurrentUserCurrentHost`),m.push(``),m.push(`using namespace System.Management.Automation`),m.push(`using namespace System.Management.Automation.Language`),m.push(``),o(m,u,d,p),m.push(``),c(m,s,u),m.push(``),m.push(`Register-ArgumentCompleter -Native -CommandName ${l(e.name)} -ScriptBlock {`),m.push(` param($wordToComplete, $commandAst, $cursorPosition)`),m.push(`\t$state = ${s}_GetState -CommandAst $commandAst -CursorPosition $cursorPosition`),m.push(` if ($null -eq $state.PathData) {`),m.push(` return`),m.push(` }`),m.push(``),m.push(` $results = [System.Collections.Generic.List[CompletionResult]]::new()`),m.push(` $wordPrefix = if ([string]::IsNullOrEmpty($wordToComplete)) { '' } else { $wordToComplete }`),m.push(``),m.push(` if ($state.ExpectingValue) {`),m.push(`\t\t${s}_AddEnumResults -Results $results -Flag $state.ValueFlag -WordToComplete $wordPrefix`),m.push(` return $results`),m.push(` }`),m.push(``),m.push(`\t$inlineValue = ${s}_ResolveInlineValueCompletion -PathData $state.PathData -WordToComplete $wordPrefix`),m.push(` if ($null -ne $inlineValue) {`),m.push(`\t\t${s}_AddInlineEnumResults -Results $results -InlineValue $inlineValue -WordToComplete $wordPrefix`),m.push(` return $results`),m.push(` }`),m.push(``),m.push(` if ($wordPrefix.StartsWith('-')) {`),m.push(`\t\t${s}_AddFlagResults -Results $results -PathData $state.PathData -WordToComplete $wordPrefix`),m.push(` return $results`),m.push(` }`),m.push(``),m.push(`\t${s}_AddCommandResults -Results $results -PathData $state.PathData -WordToComplete $wordPrefix`),m.push(`\t${s}_AddFlagResults -Results $results -PathData $state.PathData -WordToComplete $wordPrefix`),m.push(` return $results`),m.push(`}`),m.join(`
|
|
2
|
+
`)}function o(e,t,n,r){e.push(`$script:${t} = @{`),s(e,``,n.visibleCommands,{...n.rootFlags,...n.includeDefaultFlags?n.defaultFlags:{}});for(let t of r)s(e,t.path.join(` `),t.children,t.mergedFlags);e.push(`}`)}function s(t,n,r,i){t.push(`\t${l(n)} = @{`),t.push(` Commands = @(`);for(let e of r)t.push(` @{`),t.push(`\t\t\t\tCanonicalName = ${l(e.name)}`),t.push(`\t\t\t\tNames = ${u([e.name,...e.aliases])}`),t.push(`\t\t\t\tDescription = ${l(e.description??e.name)}`),t.push(` }`);t.push(` )`),t.push(` Flags = @(`);for(let[n,r]of Object.entries(i)){let i=d([`--${n}`,...e(r,{kind:`short`}).map(e=>`-${e}`),...e(r,{kind:`long`}).map(e=>`--${e}`)]),a=d([`--${n}`,...e(r,{kind:`short`,includeHidden:!0}).map(e=>`-${e}`),...e(r,{kind:`long`,includeHidden:!0}).map(e=>`--${e}`)]);t.push(` @{`),t.push(`\t\t\t\tCanonicalName = ${l(n)}`),t.push(`\t\t\t\tForms = ${u(i)}`),t.push(`\t\t\t\tParseForms = ${u(a)}`),t.push(`\t\t\t\tRequiresValue = ${r.kind===`boolean`?`$false`:`$true`}`),t.push(`\t\t\t\tDescription = ${l(r.description??n)}`),t.push(`\t\t\t\tEnumValues = ${u(r.enumValues??[])}`),t.push(` }`)}t.push(` )`),t.push(` }`)}function c(e,t,n){e.push(`function ${t}_UnquoteToken {`),e.push(` param([string]$TokenText)`),e.push(` if ($TokenText.Length -lt 2) {`),e.push(` return $TokenText`),e.push(` }`),e.push(``),e.push(` if (($TokenText.StartsWith("'") -and $TokenText.EndsWith("'")) -or`),e.push(` ($TokenText.StartsWith('"') -and $TokenText.EndsWith('"'))) {`),e.push(` return $TokenText.Substring(1, $TokenText.Length - 2)`),e.push(` }`),e.push(``),e.push(` return $TokenText`),e.push(`}`),e.push(``),e.push(`function ${t}_FindCommand {`),e.push(` param($PathData, [string]$Token)`),e.push(` foreach ($command in $PathData.Commands) {`),e.push(` foreach ($name in $command.Names) {`),e.push(` if ($name -eq $Token) {`),e.push(` return $command`),e.push(` }`),e.push(` }`),e.push(` }`),e.push(` return $null`),e.push(`}`),e.push(``),e.push(`function ${t}_ResolveFlagToken {`),e.push(` param($PathData, [string]$Token)`),e.push(` foreach ($flag in $PathData.Flags) {`),e.push(` foreach ($form in $flag.ParseForms) {`),e.push(` if ($Token -eq $form) {`),e.push(` return @{ Flag = $flag; InlinePrefix = $null }`),e.push(` }`),e.push(``),e.push(` if (-not $flag.RequiresValue) {`),e.push(` continue`),e.push(` }`),e.push(``),e.push(` if ($form.StartsWith('--') -and $Token.StartsWith("$form=")) {`),e.push(` return @{ Flag = $flag; InlinePrefix = "$form=" }`),e.push(` }`),e.push(``),e.push(` if ($form.StartsWith('-') -and -not $form.StartsWith('--') -and $Token.StartsWith($form) -and $Token.Length -gt $form.Length) {`),e.push(` return @{ Flag = $flag; InlinePrefix = $form }`),e.push(` }`),e.push(` }`),e.push(` }`),e.push(` return $null`),e.push(`}`),e.push(``),e.push(`function ${t}_GetState {`),e.push(` param([CommandAst]$CommandAst, [int]$CursorPosition)`),e.push(`\t$pathData = $script:${n}[${l(``)}]`),e.push(` $path = ""`),e.push(` $expectingValue = $false`),e.push(` $valueFlag = $null`),e.push(` $tokens = [System.Collections.Generic.List[string]]::new()`),e.push(``),e.push(` foreach ($element in $CommandAst.CommandElements | Select-Object -Skip 1) {`),e.push(` if ($element.Extent.EndOffset -gt $CursorPosition) {`),e.push(` break`),e.push(` }`),e.push(`\t\t$tokenText = ${t}_UnquoteToken $element.Extent.Text`),e.push(` [void]$tokens.Add($tokenText)`),e.push(` }`),e.push(``),e.push(` foreach ($token in $tokens) {`),e.push(` if ($expectingValue) {`),e.push(` $expectingValue = $false`),e.push(` $valueFlag = $null`),e.push(` continue`),e.push(` }`),e.push(``),e.push(` if ($token -eq '--') {`),e.push(` break`),e.push(` }`),e.push(``),e.push(`\t\t$flagMatch = ${t}_ResolveFlagToken -PathData $pathData -Token $token`),e.push(` if ($null -ne $flagMatch) {`),e.push(` if ($flagMatch.InlinePrefix -eq $null -and $flagMatch.Flag.RequiresValue) {`),e.push(` $expectingValue = $true`),e.push(` $valueFlag = $flagMatch.Flag`),e.push(` }`),e.push(` continue`),e.push(` }`),e.push(``),e.push(` if ($token.StartsWith('-')) {`),e.push(` continue`),e.push(` }`),e.push(``),e.push(`\t\t$command = ${t}_FindCommand -PathData $pathData -Token $token`),e.push(` if ($null -eq $command) {`),e.push(` break`),e.push(` }`),e.push(``),e.push(` $path = if ([string]::IsNullOrEmpty($path)) {`),e.push(` $command.CanonicalName`),e.push(` } else {`),e.push(` "$path $($command.CanonicalName)"`),e.push(` }`),e.push(`\t\t$nextPathData = $script:${n}[$path]`),e.push(` if ($null -eq $nextPathData) {`),e.push(` break`),e.push(` }`),e.push(` $pathData = $nextPathData`),e.push(` }`),e.push(``),e.push(` return @{`),e.push(` Path = $path`),e.push(` PathData = $pathData`),e.push(` ExpectingValue = $expectingValue`),e.push(` ValueFlag = $valueFlag`),e.push(` }`),e.push(`}`),e.push(``),e.push(`function ${t}_ResolveInlineValueCompletion {`),e.push(` param($PathData, [string]$WordToComplete)`),e.push(`\t$flagMatch = ${t}_ResolveFlagToken -PathData $PathData -Token $WordToComplete`),e.push(` if ($null -eq $flagMatch -or $flagMatch.InlinePrefix -eq $null) {`),e.push(` return $null`),e.push(` }`),e.push(` return $flagMatch`),e.push(`}`),e.push(``),e.push(`function ${t}_AddCommandResults {`),e.push(` param($Results, $PathData, [string]$WordToComplete)`),e.push(` foreach ($command in $PathData.Commands) {`),e.push(` foreach ($name in $command.Names) {`),e.push(` if (-not [string]::IsNullOrEmpty($WordToComplete) -and -not $name.StartsWith($WordToComplete, [System.StringComparison]::OrdinalIgnoreCase)) {`),e.push(` continue`),e.push(` }`),e.push(``),e.push(` $Results.Add([CompletionResult]::new(`),e.push(` $name,`),e.push(` $name,`),e.push(` [CompletionResultType]::Command,`),e.push(` $command.Description`),e.push(` ))`),e.push(` }`),e.push(` }`),e.push(`}`),e.push(``),e.push(`function ${t}_AddFlagResults {`),e.push(` param($Results, $PathData, [string]$WordToComplete)`),e.push(` foreach ($flag in $PathData.Flags) {`),e.push(` foreach ($form in $flag.Forms) {`),e.push(` if (-not [string]::IsNullOrEmpty($WordToComplete) -and -not $form.StartsWith($WordToComplete, [System.StringComparison]::OrdinalIgnoreCase)) {`),e.push(` continue`),e.push(` }`),e.push(``),e.push(` $Results.Add([CompletionResult]::new(`),e.push(` $form,`),e.push(` $form,`),e.push(` [CompletionResultType]::ParameterName,`),e.push(` $flag.Description`),e.push(` ))`),e.push(` }`),e.push(` }`),e.push(`}`),e.push(``),e.push(`function ${t}_AddEnumResults {`),e.push(` param($Results, $Flag, [string]$WordToComplete)`),e.push(` foreach ($value in $Flag.EnumValues) {`),e.push(` if (-not [string]::IsNullOrEmpty($WordToComplete) -and -not $value.StartsWith($WordToComplete, [System.StringComparison]::OrdinalIgnoreCase)) {`),e.push(` continue`),e.push(` }`),e.push(``),e.push(` $Results.Add([CompletionResult]::new(`),e.push(` $value,`),e.push(` $value,`),e.push(` [CompletionResultType]::ParameterValue,`),e.push(` $Flag.Description`),e.push(` ))`),e.push(` }`),e.push(`}`),e.push(``),e.push(`function ${t}_AddInlineEnumResults {`),e.push(` param($Results, $InlineValue, [string]$WordToComplete)`),e.push(` foreach ($value in $InlineValue.Flag.EnumValues) {`),e.push(` $completion = "$($InlineValue.InlinePrefix)$value"`),e.push(` if (-not [string]::IsNullOrEmpty($WordToComplete) -and -not $completion.StartsWith($WordToComplete, [System.StringComparison]::OrdinalIgnoreCase)) {`),e.push(` continue`),e.push(` }`),e.push(``),e.push(` $Results.Add([CompletionResult]::new(`),e.push(` $completion,`),e.push(` $value,`),e.push(` [CompletionResultType]::ParameterValue,`),e.push(` $InlineValue.Flag.Description`),e.push(` ))`),e.push(` }`),e.push(`}`)}function l(e){return`'${e.replace(/'/g,`''`)}'`}function u(e){return e.length===0?`@()`:`@(${e.map(l).join(`, `)})`}function d(e){return[...new Set(e)]}export{a as generatePowerShellCompletion};
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import { FlagSchema } from "../../schema/flag.mjs";
|
|
2
|
+
import { CommandSchema } from "../../schema/command.mjs";
|
|
3
|
+
|
|
4
|
+
//#region src/core/completion/shells/shared.d.ts
|
|
5
|
+
/**
|
|
6
|
+
* Format a version tag for generated completion script headers.
|
|
7
|
+
*
|
|
8
|
+
* Produces e.g. `"@kjanat/dreamcli v0.9.1 (f9b5f1a)"` when built, or
|
|
9
|
+
* `"@kjanat/dreamcli"` when running unbundled in development.
|
|
10
|
+
*
|
|
11
|
+
* @internal
|
|
12
|
+
*/
|
|
13
|
+
declare function versionTag(): string;
|
|
14
|
+
/**
|
|
15
|
+
* Options for completion script generation.
|
|
16
|
+
*
|
|
17
|
+
* Passed to individual shell generators alongside the CLI schema.
|
|
18
|
+
*
|
|
19
|
+
* These options affect the generated script text, not runtime completion
|
|
20
|
+
* behavior after installation.
|
|
21
|
+
*/
|
|
22
|
+
interface CompletionOptions {
|
|
23
|
+
/**
|
|
24
|
+
* Override the generated shell function name prefix.
|
|
25
|
+
*
|
|
26
|
+
* Defaults to the CLI name from the schema. This is mainly useful when
|
|
27
|
+
* embedding multiple generated scripts in the same environment and you want
|
|
28
|
+
* deterministic, collision-free helper names.
|
|
29
|
+
*
|
|
30
|
+
* @example
|
|
31
|
+
* ```ts
|
|
32
|
+
* generateCompletion(schema, 'bash', { functionPrefix: 'acme' });
|
|
33
|
+
* ```
|
|
34
|
+
*/
|
|
35
|
+
readonly functionPrefix?: string;
|
|
36
|
+
/**
|
|
37
|
+
* Controls which root-level surface shell completion exposes when a
|
|
38
|
+
* default command exists.
|
|
39
|
+
*
|
|
40
|
+
* - `'subcommands'` keeps hybrid CLIs command-centric at the root while
|
|
41
|
+
* still exposing default-command flags for a single visible default
|
|
42
|
+
* command.
|
|
43
|
+
* - `'surface'` exposes the default command's root-usable flags at the
|
|
44
|
+
* root whenever a visible default command exists.
|
|
45
|
+
*
|
|
46
|
+
* @defaultValue `'subcommands'`
|
|
47
|
+
*/
|
|
48
|
+
readonly rootMode?: 'subcommands' | 'surface';
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Normalized root completion surface consumed by shell generators.
|
|
52
|
+
*
|
|
53
|
+
* @internal
|
|
54
|
+
*/
|
|
55
|
+
interface RootCompletionSurface {
|
|
56
|
+
readonly visibleCommands: readonly CommandSchema[];
|
|
57
|
+
readonly visibleDefaultCommand: CommandSchema | undefined;
|
|
58
|
+
readonly rootFlags: Readonly<Record<string, FlagSchema>>;
|
|
59
|
+
readonly defaultFlags: Readonly<Record<string, FlagSchema>>;
|
|
60
|
+
readonly includeDefaultFlags: boolean;
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Schema shape needed to compute the root completion surface.
|
|
64
|
+
*
|
|
65
|
+
* @internal
|
|
66
|
+
*/
|
|
67
|
+
interface RootCompletionSchemaLike {
|
|
68
|
+
readonly commands: ReadonlyArray<{
|
|
69
|
+
readonly schema: CommandSchema;
|
|
70
|
+
}>;
|
|
71
|
+
readonly defaultCommand: {
|
|
72
|
+
readonly schema: CommandSchema;
|
|
73
|
+
} | undefined;
|
|
74
|
+
readonly version: string | undefined;
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Resolve the root-level completion surface from the CLI schema and policy.
|
|
78
|
+
*
|
|
79
|
+
* @internal
|
|
80
|
+
*/
|
|
81
|
+
declare function resolveRootCompletionSurface(schema: RootCompletionSchemaLike, rootMode?: CompletionOptions['rootMode']): RootCompletionSurface;
|
|
82
|
+
/**
|
|
83
|
+
* A flattened node from the command tree, carrying its ancestry context.
|
|
84
|
+
*
|
|
85
|
+
* Used by both bash and zsh generators to produce completions at every
|
|
86
|
+
* nesting level with correct propagated flag inheritance.
|
|
87
|
+
*
|
|
88
|
+
* @internal
|
|
89
|
+
*/
|
|
90
|
+
interface CommandNode {
|
|
91
|
+
/** Name path from root: `['db', 'migrate']` */
|
|
92
|
+
readonly path: readonly string[];
|
|
93
|
+
/** The command schema at this node */
|
|
94
|
+
readonly schema: CommandSchema;
|
|
95
|
+
/** Propagated flags inherited from ancestors (excludes own flags) */
|
|
96
|
+
readonly propagatedFlags: Readonly<Record<string, FlagSchema>>;
|
|
97
|
+
/** Merged flags: propagated + own (own shadows propagated) */
|
|
98
|
+
readonly mergedFlags: Readonly<Record<string, FlagSchema>>;
|
|
99
|
+
/** Visible child command schemas (for subcommand completion) */
|
|
100
|
+
readonly children: readonly CommandSchema[];
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Walk the command tree depth-first, producing a flat list of
|
|
104
|
+
* {@link CommandNode}s with propagated flag context.
|
|
105
|
+
*
|
|
106
|
+
* @param topLevel - Top-level visible command schemas.
|
|
107
|
+
* @param ancestorSchemas - Schema path from root (for propagation calculation).
|
|
108
|
+
* @returns Flat list of all visible nodes in the tree.
|
|
109
|
+
*
|
|
110
|
+
* @internal
|
|
111
|
+
*/
|
|
112
|
+
declare function walkCommandTree(topLevel: readonly CommandSchema[], ancestorSchemas?: readonly CommandSchema[]): readonly CommandNode[];
|
|
113
|
+
/**
|
|
114
|
+
* Sanitize a string for use as a shell function identifier.
|
|
115
|
+
* Replaces non-alphanumeric/underscore characters with underscores.
|
|
116
|
+
* When sanitization changes the name, appends a short stable hash suffix so
|
|
117
|
+
* distinct originals cannot collide on the same helper identifier.
|
|
118
|
+
* Used by both bash and zsh generators.
|
|
119
|
+
*
|
|
120
|
+
* @internal
|
|
121
|
+
*/
|
|
122
|
+
declare function sanitizeShellIdentifier(name: string): string;
|
|
123
|
+
/**
|
|
124
|
+
* Quote a string for safe interpolation into a shell script.
|
|
125
|
+
*
|
|
126
|
+
* Uses single-quote wrapping with the standard `'\''` idiom for
|
|
127
|
+
* embedded single quotes. This prevents shell injection from CLI
|
|
128
|
+
* names containing spaces, semicolons, backticks, or other
|
|
129
|
+
* special characters.
|
|
130
|
+
*
|
|
131
|
+
* Returns the input unquoted if it consists only of shell-safe
|
|
132
|
+
* characters (`[a-zA-Z0-9_\-.]`), avoiding unnecessary noise
|
|
133
|
+
* in generated scripts for common CLI names like `my-cli` or `app.v2`.
|
|
134
|
+
*
|
|
135
|
+
* @internal
|
|
136
|
+
*/
|
|
137
|
+
declare function quoteShellArg(value: string): string;
|
|
138
|
+
//#endregion
|
|
139
|
+
export { type CommandNode, type CompletionOptions, type RootCompletionSurface, quoteShellArg, resolveRootCompletionSurface, sanitizeShellIdentifier, versionTag, walkCommandTree };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{collectPropagatedFlags as e}from"../../cli/propagate.mjs";import{resolveRootSurface as t}from"../../cli/root-surface.mjs";import{DREAMCLI_REVISION as n,DREAMCLI_VERSION as r}from"../../../version.mjs";function i(){return`@kjanat/dreamcli v${r}${` (${n})`}`}function a(e,n=`subcommands`){let r=t(e),i=o(e.version!==void 0),a=r.visibleDefaultCommand?.flags??{},s=n===`surface`?r.visibleDefaultCommand!==void 0:r.hasSingleVisibleDefault;return{visibleCommands:r.visibleCommands,visibleDefaultCommand:r.visibleDefaultCommand,rootFlags:i,defaultFlags:a,includeDefaultFlags:s}}function o(e){return{help:s(`Show help text`),...e?{version:s(`Show version`)}:{}}}function s(e){return{kind:`boolean`,presence:`optional`,defaultValue:void 0,aliases:[],envVar:void 0,configPath:void 0,description:e,enumValues:void 0,elementSchema:void 0,prompt:void 0,parseFn:void 0,deprecated:void 0,propagate:!1}}function c(t,n=[]){let r=[];for(let i of t){if(i.hidden)continue;let t=[...n,i],a=e(t),o={...a,...i.flags},s=i.commands.filter(e=>!e.hidden);r.push({path:t.map(e=>e.name),schema:i,propagatedFlags:a,mergedFlags:o,children:s}),s.length>0&&r.push(...c(s,t))}return r}function l(e){let t=e.replace(/[^a-zA-Z0-9_]/g,`_`);if(t===e)return t;let n=2166136261;for(let t=0;t<e.length;t+=1)n^=e.charCodeAt(t),n=Math.imul(n,16777619);return`${t}_${(n>>>0).toString(16).padStart(8,`0`)}`}function u(e){return/^[a-zA-Z0-9_\-.]+$/.test(e)?e:`'${e.replace(/'/g,`'\\''`)}'`}export{u as quoteShellArg,a as resolveRootCompletionSurface,l as sanitizeShellIdentifier,i as versionTag,c as walkCommandTree};
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { CompletionOptions } from "./shared.mjs";
|
|
2
|
+
import { CLISchema } from "../../cli/index.mjs";
|
|
3
|
+
|
|
4
|
+
//#region src/core/completion/shells/zsh.d.ts
|
|
5
|
+
/**
|
|
6
|
+
* Generate a zsh completion script for the CLI.
|
|
7
|
+
*
|
|
8
|
+
* Use this when you want a zsh-specific script directly rather than routing
|
|
9
|
+
* through {@link generateCompletion}. The generated script is compatible with
|
|
10
|
+
* zsh's normal `#compdef` / `fpath` loading flow.
|
|
11
|
+
*
|
|
12
|
+
* @param schema - The CLI schema.
|
|
13
|
+
* @param options - Optional generator configuration.
|
|
14
|
+
* @returns A complete zsh completion script.
|
|
15
|
+
*
|
|
16
|
+
* @example
|
|
17
|
+
* ```ts
|
|
18
|
+
* const script = generateZshCompletion(app.schema);
|
|
19
|
+
* // install with: mycli completions zsh > "${fpath[1]}/_mycli"
|
|
20
|
+
* ```
|
|
21
|
+
*/
|
|
22
|
+
declare function generateZshCompletion(schema: CLISchema, options?: CompletionOptions): string;
|
|
23
|
+
//#endregion
|
|
24
|
+
export { generateZshCompletion };
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{getFlagAliasNames as e}from"../../schema/flag.mjs";import{quoteShellArg as t,resolveRootCompletionSurface as n,sanitizeShellIdentifier as r,versionTag as i,walkCommandTree as a}from"./shared.mjs";import{CLIError as o}from"../../errors/index.mjs";function s(e,s){let f=`_${r(s?.functionPrefix??e.name)}`,m=n(e,s?.rootMode),h=m.visibleCommands,g=a(h),_=[];_.push(`#compdef ${t(e.name)}`),_.push(`# Zsh completion for ${e.name}`),_.push(`# Generated by ${i()}`),_.push(`#`),_.push(`# Usage: source <(${e.name} completions zsh)`),_.push(`#`),_.push(`# Install permanently:`),_.push(`# ${e.name} completions zsh > "\${fpath[1]}/_${e.name}"`),_.push(`# # Then restart your shell`),_.push(``);let v=g.filter(e=>e.children.length>0),y=g.filter(e=>e.children.length===0);for(let e of y)e.path.length<2||l(_,`${f}_${e.path.map(r).join(`_`)}`,e);let b=[...v].sort((e,t)=>t.path.length-e.path.length);for(let e of b)c(_,`${f}_${e.path.map(r).join(`_`)}`,f,e);if(_.push(`${f}() {`),h.length>0){_.push(` local -a subcmds`),_.push(` local line state`),_.push(``);let e=p({...m.rootFlags,...m.includeDefaultFlags?m.defaultFlags:{}});_.push(` _arguments -C \\`);for(let t of e)_.push(`\t\t${t} \\`);_.push(` '1: :->subcmd' \\`),_.push(` '*::arg:->args'`),_.push(``),_.push(` case "$state" in`),_.push(` subcmd)`),_.push(` subcmds=(`),u(_,h,` `),_.push(` )`),_.push(` _describe 'command' subcmds`),_.push(` ;;`),_.push(` args)`),_.push(` case "$line[1]" in`);for(let e of h){let t=[e.name,...e.aliases].map(d),n=e.commands.filter(e=>!e.hidden);if(_.push(`\t\t\t\t${t.join(`|`)})`),n.length>0){let t=`${f}_${r(e.name)}`;_.push(`\t\t\t\t\t${t}`)}else{let t=g.find(t=>t.path.length===1&&t.schema.name===e.name);if(t===void 0)throw new o(`Missing completion node for command '${e.name}'`,{code:`UNEXPECTED_ERROR`});let n=p(t.mergedFlags);if(n.length>0){_.push(` _arguments \\`);for(let e=0;e<n.length;e++){let t=e<n.length-1?` \\`:``;_.push(`\t\t\t\t\t\t${n[e]}${t}`)}}}_.push(` ;;`)}_.push(` esac`),_.push(` ;;`),_.push(` esac`)}else{let e=p(m.rootFlags);_.push(` _arguments \\`);for(let t=0;t<e.length;t++){let n=t<e.length-1?` \\`:``;_.push(`\t\t${e[t]}${n}`)}}return _.push(`}`),_.push(``),_.push(`compdef ${f} ${t(e.name)}`),_.push(``),_.join(`
|
|
2
|
+
`)}function c(e,t,n,i){e.push(`${t}() {`),e.push(` local -a subcmds`),e.push(` local line state`),e.push(``);let a=p(i.mergedFlags);e.push(` _arguments -C \\`);for(let t of a)e.push(`\t\t${t} \\`);e.push(` '1: :->subcmd' \\`),e.push(` '*::arg:->args'`),e.push(``),e.push(` case "$state" in`),e.push(` subcmd)`),e.push(` subcmds=(`),u(e,i.children,` `),e.push(` )`),e.push(` _describe 'command' subcmds`),e.push(` ;;`),e.push(` args)`),e.push(` case "$line[1]" in`);for(let t of i.children){let a=[t.name,...t.aliases].map(d),o=`${n}_${[...i.path,t.name].map(r).join(`_`)}`;e.push(`\t\t\t\t${a.join(`|`)})`),e.push(`\t\t\t\t\t${o}`),e.push(` ;;`)}e.push(` esac`),e.push(` ;;`),e.push(` esac`),e.push(`}`),e.push(``)}function l(e,t,n){let r=p(n.mergedFlags);if(e.push(`${t}() {`),r.length>0){e.push(` _arguments \\`);for(let t=0;t<r.length;t++){let n=t<r.length-1?` \\`:``;e.push(`\t\t${r[t]}${n}`)}}e.push(`}`),e.push(``)}function u(e,n,r){for(let i of n){let n=i.description??i.name;for(let a of[i.name,...i.aliases])e.push(`${r}${t(`${a}:${n}`)}`)}}function d(e){return/^[a-zA-Z0-9_\-.]+$/.test(e)?e:e.replace(/\\/g,`\\\\`).replace(/'/g,`\\'`).replace(/"/g,`\\"`).replace(/`/g,"\\`").replace(/\|/g,`\\|`).replace(/\*/g,`\\*`).replace(/\?/g,`\\?`).replace(/\[/g,`\\[`).replace(/\]/g,`\\]`).replace(/\(/g,`\\(`).replace(/\)/g,`\\)`).replace(/\{/g,`\\{`).replace(/\}/g,`\\}`).replace(/\+/g,`\\+`).replace(/!/g,`\\!`).replace(/@/g,`\\@`).replace(/#/g,`\\#`).replace(/~/g,`\\~`).replace(/\s/g,e=>e===` `?`\\ `:`\\${e}`)}function f(e){return e.replace(/\\/g,`\\\\`).replace(/\]/g,`\\]`)}function p(n){let r=[];for(let[i,a]of Object.entries(n)){let n=f(a.description??i),o=`--${i}`,s=e(a,{kind:`short`}).map(e=>`-${e}`),c=e(a,{kind:`long`}).map(e=>`--${e}`),l=[...s,o,...c],u=``;if(a.kind===`boolean`||(u=a.kind===`enum`&&a.enumValues!==void 0?`:value:(${a.enumValues.map(m).join(` `)})`:`:value:`),l.length>1){let e=l.map(d).join(`,`);r.push(`${t(`(${l.join(` `)})`)}{${e}}${t(`[${n}]${u}`)}`)}else r.push(t(`${o}[${n}]${u}`))}return r}function m(e){return/^[a-zA-Z0-9_\-.]+$/.test(e)?e:e.replace(/\\/g,`\\\\`).replace(/ /g,`\\ `).replace(/\(/g,`\\(`).replace(/\)/g,`\\)`)}export{s as generateZshCompletion};
|