@kjanat/dreamcli 3.0.0-rc.1 → 3.0.0-rc.3
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 +37 -1
- package/dist/core/cli/dispatch.mjs +214 -1
- package/dist/core/cli/help-links.mjs +41 -1
- package/dist/core/cli/index.mjs +901 -1
- package/dist/core/cli/planner.mjs +300 -1
- package/dist/core/cli/plugin.mjs +41 -1
- package/dist/core/cli/propagate.mjs +57 -1
- package/dist/core/cli/root-help.mjs +208 -4
- package/dist/core/cli/root-surface.mjs +27 -1
- package/dist/core/cli/runtime-preflight.mjs +168 -1
- package/dist/core/completion/index.mjs +90 -1
- package/dist/core/completion/shells/bash.mjs +304 -3
- package/dist/core/completion/shells/fish.mjs +159 -2
- package/dist/core/completion/shells/powershell.mjs +353 -2
- package/dist/core/completion/shells/shared.mjs +154 -1
- package/dist/core/completion/shells/zsh.mjs +244 -2
- package/dist/core/config/index.mjs +246 -1
- package/dist/core/config/package-json.mjs +385 -3
- package/dist/core/errors/index.mjs +87 -1
- package/dist/core/execution/index.mjs +189 -1
- package/dist/core/help/ansi.mjs +122 -2
- package/dist/core/help/index.mjs +329 -7
- package/dist/core/json-schema/index.mjs +487 -9
- package/dist/core/json-schema/meta-descriptions.generated.mjs +93 -28
- package/dist/core/output/activity.mjs +452 -1
- package/dist/core/output/bind.mjs +56 -1
- package/dist/core/output/contracts.mjs +57 -1
- package/dist/core/output/display-value.mjs +32 -1
- package/dist/core/output/index.d.mts +21 -0
- package/dist/core/output/index.mjs +442 -2
- package/dist/core/output/renderers.mjs +46 -1
- package/dist/core/output/writer.mjs +12 -1
- package/dist/core/parse/index.mjs +555 -1
- package/dist/core/prompt/index.d.mts +0 -1
- package/dist/core/prompt/index.mjs +348 -6
- package/dist/core/resolve/args.mjs +105 -1
- package/dist/core/resolve/coerce.mjs +279 -1
- package/dist/core/resolve/config.mjs +19 -1
- package/dist/core/resolve/errors.mjs +140 -2
- package/dist/core/resolve/flags.mjs +196 -1
- package/dist/core/resolve/index.mjs +85 -1
- package/dist/core/resolve/property.d.mts +0 -1
- package/dist/core/resolve/property.mjs +45 -1
- package/dist/core/schema/arg.mjs +463 -1
- package/dist/core/schema/command.d.mts +18 -0
- package/dist/core/schema/command.mjs +712 -1
- package/dist/core/schema/flag.mjs +453 -1
- package/dist/core/schema/middleware.mjs +41 -1
- package/dist/core/schema/number-constraints.mjs +60 -1
- package/dist/core/schema-dsl/runtime.mjs +271 -2
- package/dist/core/schema-dsl/to-json-schema.mjs +74 -1
- package/dist/core/testkit/index.mjs +83 -1
- package/dist/index.d.mts +2 -1
- package/dist/index.mjs +22 -1
- package/dist/runtime/adapter.mjs +82 -1
- package/dist/runtime/auto.mjs +46 -1
- package/dist/runtime/bun.mjs +28 -1
- package/dist/runtime/deno.mjs +217 -2
- package/dist/runtime/detect.mjs +45 -1
- package/dist/runtime/node.mjs +169 -2
- package/dist/runtime/paths.mjs +48 -1
- package/dist/runtime.mjs +7 -1
- package/dist/strings.mjs +22 -1
- package/dist/testkit.mjs +5 -1
- package/dist/version.d.mts +7 -3
- package/dist/version.mjs +7 -1
- package/package.json +21 -26
- package/src/core/cli/dispatch.ts +0 -355
- package/src/core/cli/help-links.ts +0 -82
- package/src/core/cli/index.ts +0 -1614
- package/src/core/cli/planner.ts +0 -656
- package/src/core/cli/plugin.ts +0 -117
- package/src/core/cli/propagate.ts +0 -97
- package/src/core/cli/root-help.ts +0 -342
- package/src/core/cli/root-surface.ts +0 -87
- package/src/core/cli/runtime-preflight.ts +0 -456
- package/src/core/completion/index.ts +0 -138
- package/src/core/completion/shells/bash.ts +0 -459
- package/src/core/completion/shells/fish.ts +0 -259
- package/src/core/completion/shells/powershell.ts +0 -439
- package/src/core/completion/shells/shared.ts +0 -310
- package/src/core/completion/shells/zsh.ts +0 -381
- package/src/core/config/index.ts +0 -417
- package/src/core/config/package-json.ts +0 -560
- package/src/core/errors/index.ts +0 -193
- package/src/core/execution/index.ts +0 -265
- package/src/core/help/ansi.ts +0 -144
- package/src/core/help/index.ts +0 -563
- package/src/core/json-schema/index.ts +0 -910
- package/src/core/json-schema/meta-descriptions.generated.ts +0 -202
- package/src/core/output/activity.ts +0 -575
- package/src/core/output/bind.ts +0 -59
- package/src/core/output/contracts.ts +0 -194
- package/src/core/output/display-value.ts +0 -48
- package/src/core/output/index.ts +0 -704
- package/src/core/output/renderers.ts +0 -125
- package/src/core/output/writer.ts +0 -46
- package/src/core/parse/index.ts +0 -742
- package/src/core/prompt/index.ts +0 -623
- package/src/core/resolve/args.ts +0 -144
- package/src/core/resolve/coerce.ts +0 -500
- package/src/core/resolve/config.ts +0 -26
- package/src/core/resolve/contracts.ts +0 -135
- package/src/core/resolve/errors.ts +0 -227
- package/src/core/resolve/flags.ts +0 -269
- package/src/core/resolve/index.ts +0 -108
- package/src/core/resolve/property.ts +0 -99
- package/src/core/schema/activity.ts +0 -240
- package/src/core/schema/arg.ts +0 -841
- package/src/core/schema/command.ts +0 -1500
- package/src/core/schema/flag.ts +0 -917
- package/src/core/schema/index.ts +0 -96
- package/src/core/schema/middleware.ts +0 -171
- package/src/core/schema/number-constraints.ts +0 -153
- package/src/core/schema/prompt.ts +0 -171
- package/src/core/schema/run.ts +0 -198
- package/src/core/schema-dsl/index.ts +0 -109
- package/src/core/schema-dsl/parse.ts +0 -262
- package/src/core/schema-dsl/runtime.ts +0 -609
- package/src/core/schema-dsl/to-json-schema.ts +0 -102
- package/src/core/testkit/index.ts +0 -147
- package/src/index.ts +0 -181
- package/src/runtime/adapter.ts +0 -303
- package/src/runtime/auto.ts +0 -86
- package/src/runtime/bun.ts +0 -48
- package/src/runtime/deno.ts +0 -367
- package/src/runtime/detect.ts +0 -105
- package/src/runtime/index.ts +0 -21
- package/src/runtime/node-builtins.d.ts +0 -27
- package/src/runtime/node.ts +0 -289
- package/src/runtime/paths.ts +0 -64
- package/src/runtime/support.ts +0 -77
- package/src/runtime.ts +0 -31
- package/src/schema.ts +0 -16
- package/src/strings.ts +0 -34
- package/src/testkit.ts +0 -25
- package/src/version.ts +0 -20
|
@@ -1 +1,168 @@
|
|
|
1
|
-
import
|
|
1
|
+
import { CLIError, ParseError } from "../errors/index.mjs";
|
|
2
|
+
import { parse } from "../parse/index.mjs";
|
|
3
|
+
import { createTerminalPrompter } from "../prompt/index.mjs";
|
|
4
|
+
import { discoverManifest, inferCliName } from "../config/package-json.mjs";
|
|
5
|
+
import { deriveHelpLinks } from "./help-links.mjs";
|
|
6
|
+
import { planInvocation } from "./planner.mjs";
|
|
7
|
+
import { discoverConfig } from "../config/index.mjs";
|
|
8
|
+
//#region src/core/cli/runtime-preflight.ts
|
|
9
|
+
const PRECHECK_OUTPUT = {
|
|
10
|
+
jsonMode: false,
|
|
11
|
+
isTTY: false,
|
|
12
|
+
verbosity: "normal"
|
|
13
|
+
};
|
|
14
|
+
/** Extract and strip valid runtime `--config` forms from argv, returning path + filtered tokens. @internal */
|
|
15
|
+
function extractConfigFlag(argv) {
|
|
16
|
+
const filteredArgv = [];
|
|
17
|
+
let configPath;
|
|
18
|
+
for (let i = 0; i < argv.length; i += 1) {
|
|
19
|
+
const arg = argv[i];
|
|
20
|
+
if (arg === void 0) continue;
|
|
21
|
+
if (arg === "--") {
|
|
22
|
+
filteredArgv.push(...argv.slice(i));
|
|
23
|
+
break;
|
|
24
|
+
}
|
|
25
|
+
if (configPath === void 0 && arg.startsWith("--config=")) {
|
|
26
|
+
const value = arg.slice(9);
|
|
27
|
+
if (value.length > 0) {
|
|
28
|
+
configPath = value;
|
|
29
|
+
continue;
|
|
30
|
+
}
|
|
31
|
+
filteredArgv.push(arg);
|
|
32
|
+
continue;
|
|
33
|
+
}
|
|
34
|
+
if (configPath === void 0 && arg === "--config") {
|
|
35
|
+
const nextArg = argv[i + 1];
|
|
36
|
+
if (nextArg !== void 0 && !nextArg.startsWith("-") && nextArg !== "--") {
|
|
37
|
+
configPath = nextArg;
|
|
38
|
+
i += 1;
|
|
39
|
+
continue;
|
|
40
|
+
}
|
|
41
|
+
filteredArgv.push(arg);
|
|
42
|
+
continue;
|
|
43
|
+
}
|
|
44
|
+
filteredArgv.push(arg);
|
|
45
|
+
}
|
|
46
|
+
return {
|
|
47
|
+
configPath,
|
|
48
|
+
filteredArgv
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
/** Check whether a single command's args declare stdin-mode and argv leaves them unresolved. @internal */
|
|
52
|
+
function commandInvocationNeedsStdin(schema, argv) {
|
|
53
|
+
if (argv.includes("--help") || argv.includes("-h")) return false;
|
|
54
|
+
try {
|
|
55
|
+
const parsed = parse(schema, argv);
|
|
56
|
+
return schema.args.some(({ name, schema: argSchema }) => {
|
|
57
|
+
const parsedValue = parsed.args[name];
|
|
58
|
+
return argSchema.stdinMode && (parsedValue === void 0 || parsedValue === "-");
|
|
59
|
+
});
|
|
60
|
+
} catch (error) {
|
|
61
|
+
if (error instanceof ParseError) return false;
|
|
62
|
+
throw error;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
/** Plan the invocation and check whether the matched command needs stdin data. @internal */
|
|
66
|
+
function invocationNeedsStdin(schema, argv) {
|
|
67
|
+
const plan = planInvocation({
|
|
68
|
+
schema,
|
|
69
|
+
argv,
|
|
70
|
+
help: { binName: schema.name },
|
|
71
|
+
output: PRECHECK_OUTPUT
|
|
72
|
+
});
|
|
73
|
+
switch (plan.kind) {
|
|
74
|
+
case "match": return commandInvocationNeedsStdin(plan.plan.mergedSchema, plan.plan.argv);
|
|
75
|
+
case "dispatch-error":
|
|
76
|
+
case "needs-subcommand":
|
|
77
|
+
case "root-help":
|
|
78
|
+
case "root-version":
|
|
79
|
+
case "root-completions": return false;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
function isCompletionsInvocation(schema, argv) {
|
|
83
|
+
if (!schema.hasBuiltInCompletions) return false;
|
|
84
|
+
const plan = planInvocation({
|
|
85
|
+
schema,
|
|
86
|
+
argv,
|
|
87
|
+
help: { binName: schema.name },
|
|
88
|
+
output: PRECHECK_OUTPUT
|
|
89
|
+
});
|
|
90
|
+
return plan.kind === "match" && plan.plan.command.schema.name === "completions";
|
|
91
|
+
}
|
|
92
|
+
async function applyPackageJsonDiscovery(schema, adapter, inheritedName, isCompletions) {
|
|
93
|
+
const packageJsonSettings = schema.packageJsonSettings;
|
|
94
|
+
const packageSchema = packageJsonSettings !== void 0 && !isCompletions ? await (async () => {
|
|
95
|
+
const pkg = packageJsonSettings.data ?? await discoverManifest(adapter, {
|
|
96
|
+
...packageJsonSettings.from !== void 0 ? { startDir: packageJsonSettings.from } : {},
|
|
97
|
+
files: packageJsonSettings.files
|
|
98
|
+
});
|
|
99
|
+
if (pkg === null) return schema;
|
|
100
|
+
const inferredName = packageJsonSettings.inferName ? inferCliName(pkg, { stripScope: packageJsonSettings.stripScope }) : void 0;
|
|
101
|
+
return {
|
|
102
|
+
...schema,
|
|
103
|
+
...schema.version === void 0 && pkg.version !== void 0 ? { version: pkg.version } : {},
|
|
104
|
+
...schema.description === void 0 && pkg.description !== void 0 ? { description: pkg.description } : {},
|
|
105
|
+
...inferredName !== void 0 ? { name: inferredName } : {},
|
|
106
|
+
helpLinks: deriveHelpLinks(schema.helpLinks, pkg, schema.version ?? pkg.version)
|
|
107
|
+
};
|
|
108
|
+
})() : schema;
|
|
109
|
+
return inheritedName !== void 0 ? {
|
|
110
|
+
...packageSchema,
|
|
111
|
+
name: inheritedName
|
|
112
|
+
} : packageSchema;
|
|
113
|
+
}
|
|
114
|
+
async function loadRuntimeConfig(schema, adapter, configPath, isCompletions, existingConfig) {
|
|
115
|
+
if (schema.configSettings === void 0 || isCompletions || existingConfig !== void 0) return existingConfig;
|
|
116
|
+
try {
|
|
117
|
+
const result = await discoverConfig(schema.configSettings.appName, adapter, {
|
|
118
|
+
...configPath !== void 0 ? { configPath } : {},
|
|
119
|
+
...schema.configSettings.loaders !== void 0 ? { loaders: schema.configSettings.loaders } : {}
|
|
120
|
+
});
|
|
121
|
+
return result.found ? result.data : void 0;
|
|
122
|
+
} catch (error) {
|
|
123
|
+
if (error instanceof CLIError) return error;
|
|
124
|
+
throw error;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* Run all adapter-driven sourcing work before command execution.
|
|
129
|
+
*
|
|
130
|
+
* Discovers config files, reads package.json metadata, detects stdin needs,
|
|
131
|
+
* wires up the prompt engine, and resolves output policy overrides into a
|
|
132
|
+
* single {@linkcode RuntimePreflightResult}.
|
|
133
|
+
* @internal
|
|
134
|
+
*/
|
|
135
|
+
async function prepareRuntimePreflight(options) {
|
|
136
|
+
const rawArgv = options.adapter.argv.slice(2);
|
|
137
|
+
const { configPath, filteredArgv } = options.schema.configSettings !== void 0 ? extractConfigFlag(rawArgv) : {
|
|
138
|
+
configPath: void 0,
|
|
139
|
+
filteredArgv: rawArgv
|
|
140
|
+
};
|
|
141
|
+
const jsonMode = filteredArgv.includes("--json") || options.options?.jsonMode === true;
|
|
142
|
+
const isCompletions = isCompletionsInvocation(options.schema, filteredArgv);
|
|
143
|
+
const schema = await applyPackageJsonDiscovery(options.schema, options.adapter, options.inheritedName, isCompletions);
|
|
144
|
+
const loadedConfig = await loadRuntimeConfig(schema, options.adapter, configPath, isCompletions, options.options?.config);
|
|
145
|
+
if (loadedConfig instanceof CLIError) return {
|
|
146
|
+
kind: "config-error",
|
|
147
|
+
error: loadedConfig,
|
|
148
|
+
jsonMode
|
|
149
|
+
};
|
|
150
|
+
const autoPrompter = options.options?.prompter === void 0 && options.adapter.stdinIsTTY ? createTerminalPrompter(options.adapter.stdin, options.adapter.stderr) : void 0;
|
|
151
|
+
const stdinData = options.options?.stdinData === void 0 && invocationNeedsStdin(schema, filteredArgv) ? await options.adapter.readStdin() : options.options?.stdinData;
|
|
152
|
+
return {
|
|
153
|
+
kind: "ready",
|
|
154
|
+
schema,
|
|
155
|
+
filteredArgv,
|
|
156
|
+
inputs: {
|
|
157
|
+
env: options.options?.env ?? options.adapter.env,
|
|
158
|
+
isTTY: options.options?.isTTY ?? options.adapter.isTTY,
|
|
159
|
+
jsonMode,
|
|
160
|
+
verbosity: options.options?.verbosity ?? "normal",
|
|
161
|
+
...stdinData !== void 0 ? { stdinData } : {},
|
|
162
|
+
...options.options?.prompter !== void 0 ? { prompter: options.options.prompter } : autoPrompter !== void 0 ? { prompter: autoPrompter } : {},
|
|
163
|
+
...loadedConfig !== void 0 ? { config: loadedConfig } : {}
|
|
164
|
+
}
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
//#endregion
|
|
168
|
+
export { prepareRuntimePreflight };
|
|
@@ -1 +1,90 @@
|
|
|
1
|
-
import
|
|
1
|
+
import { generateBashCompletion } from "./shells/bash.mjs";
|
|
2
|
+
import { generateFishCompletion } from "./shells/fish.mjs";
|
|
3
|
+
import { generatePowerShellCompletion } from "./shells/powershell.mjs";
|
|
4
|
+
import { generateZshCompletion } from "./shells/zsh.mjs";
|
|
5
|
+
//#region src/core/completion/index.ts
|
|
6
|
+
/**
|
|
7
|
+
* Implemented shell values as a frozen readonly non-empty tuple.
|
|
8
|
+
*
|
|
9
|
+
* Use this tuple for user-facing validation and shell selection UIs.
|
|
10
|
+
* It intentionally matches the shipped {@link Shell} union exactly so docs,
|
|
11
|
+
* help output, and completion generation advertise the same support surface.
|
|
12
|
+
*
|
|
13
|
+
* @see {@link Shell} for the union type matching these entries.
|
|
14
|
+
*/
|
|
15
|
+
const SHELLS = Object.freeze([
|
|
16
|
+
"bash",
|
|
17
|
+
"zsh",
|
|
18
|
+
"fish",
|
|
19
|
+
"powershell"
|
|
20
|
+
]);
|
|
21
|
+
/**
|
|
22
|
+
* Normalize a raw shell token — a bare name (`zsh`), a `$SHELL` path
|
|
23
|
+
* (`/bin/zsh`), or a Windows executable (`…\pwsh.exe`) — to a supported
|
|
24
|
+
* {@link Shell}, or `undefined` when it does not map to one.
|
|
25
|
+
*
|
|
26
|
+
* Mirrors the matching used by the `completions` subcommand so the subcommand
|
|
27
|
+
* and the eager `--completions <shell>` flag accept exactly the same inputs.
|
|
28
|
+
*
|
|
29
|
+
* @param raw - User-supplied shell token or interpreter path.
|
|
30
|
+
* @returns The resolved {@link Shell}, or `undefined` if unrecognized.
|
|
31
|
+
*/
|
|
32
|
+
function normalizeShell(raw) {
|
|
33
|
+
const segments = raw.split(/[\\/]/);
|
|
34
|
+
const name = (segments[segments.length - 1] ?? raw).replace(/\.(?:exe|cmd|bat)$/i, "");
|
|
35
|
+
if (name === "pwsh") return "powershell";
|
|
36
|
+
return SHELLS.includes(name) ? name : void 0;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Auto-detect the current shell from environment variables.
|
|
40
|
+
*
|
|
41
|
+
* Resolution order:
|
|
42
|
+
* 1. `$SHELL` parsed as an interpreter path (`/bin/zsh` → `zsh`). It wins when
|
|
43
|
+
* it names a shell we support — a pwsh session launched from bash inherits
|
|
44
|
+
* `SHELL=/bin/bash`, and the login shell the user opted into should be
|
|
45
|
+
* honored over the fallback.
|
|
46
|
+
* 2. Otherwise, the presence of `$PSModulePath` signals PowerShell. PowerShell
|
|
47
|
+
* never sets `$SHELL` on any platform but always exports `PSModulePath` for
|
|
48
|
+
* module discovery, so it is the reliable pwsh signal.
|
|
49
|
+
*
|
|
50
|
+
* Returns `undefined` when no signal resolves, leaving the caller to ask the
|
|
51
|
+
* user for an explicit shell.
|
|
52
|
+
*
|
|
53
|
+
* @param env - Environment record (e.g. `process.env` or an adapter's env).
|
|
54
|
+
* @returns The detected {@link Shell}, or `undefined`.
|
|
55
|
+
*/
|
|
56
|
+
function detectShell(env) {
|
|
57
|
+
const shellVar = env.SHELL;
|
|
58
|
+
const fromShell = shellVar !== void 0 && shellVar !== "" ? normalizeShell(shellVar) : void 0;
|
|
59
|
+
if (fromShell !== void 0) return fromShell;
|
|
60
|
+
if (env.PSModulePath !== void 0) return "powershell";
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Generate a completion script for the given shell.
|
|
64
|
+
*
|
|
65
|
+
* This is the primary completion entrypoint for most consumers. Pass a CLI
|
|
66
|
+
* schema and target shell, then write the returned script to a file or source
|
|
67
|
+
* it directly from the command line.
|
|
68
|
+
*
|
|
69
|
+
* @param schema - The CLI schema describing commands, flags, and args.
|
|
70
|
+
* @param shell - Target shell.
|
|
71
|
+
* @param options - Optional generator configuration such as function naming
|
|
72
|
+
* and root default-command completion behavior.
|
|
73
|
+
* @returns A complete shell completion script as a string.
|
|
74
|
+
*
|
|
75
|
+
* @example
|
|
76
|
+
* ```ts
|
|
77
|
+
* const script = generateCompletion(app.schema, 'bash');
|
|
78
|
+
* // e.g. source <(mycli completions bash)
|
|
79
|
+
* ```
|
|
80
|
+
*/
|
|
81
|
+
function generateCompletion(schema, shell, options) {
|
|
82
|
+
switch (shell) {
|
|
83
|
+
case "bash": return generateBashCompletion(schema, options);
|
|
84
|
+
case "zsh": return generateZshCompletion(schema, options);
|
|
85
|
+
case "fish": return generateFishCompletion(schema, options);
|
|
86
|
+
case "powershell": return generatePowerShellCompletion(schema, options);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
//#endregion
|
|
90
|
+
export { SHELLS, detectShell, generateCompletion, normalizeShell };
|
|
@@ -1,3 +1,304 @@
|
|
|
1
|
-
import{getFlagAliasNames
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
import { getFlagAliasNames } from "../../schema/flag.mjs";
|
|
2
|
+
import { quoteShellArg, resolveRootCompletionSurface, sanitizeShellIdentifier, versionTag, walkCommandTree } from "./shared.mjs";
|
|
3
|
+
//#region src/core/completion/shells/bash.ts
|
|
4
|
+
/**
|
|
5
|
+
* Generate a bash completion script for the CLI.
|
|
6
|
+
*
|
|
7
|
+
* Use this when you want a bash-specific script directly rather than routing
|
|
8
|
+
* through {@link generateCompletion}. The generated script expects the
|
|
9
|
+
* `bash-completion` package because it relies on `_init_completion`.
|
|
10
|
+
*
|
|
11
|
+
* @param schema - The CLI schema.
|
|
12
|
+
* @param options - Optional generator configuration.
|
|
13
|
+
* @returns A complete bash completion script.
|
|
14
|
+
*
|
|
15
|
+
* @example
|
|
16
|
+
* ```ts
|
|
17
|
+
* const script = generateBashCompletion(app.schema);
|
|
18
|
+
* // install with: mycli completions bash > /etc/bash_completion.d/mycli
|
|
19
|
+
* ```
|
|
20
|
+
*/
|
|
21
|
+
function generateBashCompletion(schema, options) {
|
|
22
|
+
const funcName = `_${sanitizeShellIdentifier(options?.functionPrefix ?? schema.name)}_completions`;
|
|
23
|
+
const rootSurface = resolveRootCompletionSurface(schema, options?.rootMode);
|
|
24
|
+
const visibleCommands = rootSurface.visibleCommands;
|
|
25
|
+
const nodes = walkCommandTree(visibleCommands);
|
|
26
|
+
const maxDepth = nodes.reduce((max, n) => Math.max(max, n.path.length), 0);
|
|
27
|
+
const lines = [];
|
|
28
|
+
lines.push("#!/usr/bin/env bash");
|
|
29
|
+
lines.push(`# Bash completion for ${schema.name}`);
|
|
30
|
+
lines.push(`# Generated by ${versionTag()}`);
|
|
31
|
+
lines.push("#");
|
|
32
|
+
lines.push(`# Usage: source <(${schema.name} completions bash)`);
|
|
33
|
+
lines.push("#");
|
|
34
|
+
lines.push("# Install permanently:");
|
|
35
|
+
lines.push(`# ${schema.name} completions bash > /etc/bash_completion.d/${schema.name} # Linux`);
|
|
36
|
+
lines.push(`# ${schema.name} completions bash > $(brew --prefix)/etc/bash_completion.d/${schema.name} # macOS`);
|
|
37
|
+
lines.push("#");
|
|
38
|
+
lines.push("# Requires: bash-completion (provides _init_completion)");
|
|
39
|
+
lines.push("");
|
|
40
|
+
lines.push(`${funcName}() {`);
|
|
41
|
+
lines.push(`\tlocal cur prev words cword`);
|
|
42
|
+
lines.push(`\t_init_completion || return`);
|
|
43
|
+
lines.push("");
|
|
44
|
+
if (visibleCommands.length > 0) {
|
|
45
|
+
const groupNodes = nodes.filter((n) => n.children.length > 0);
|
|
46
|
+
const valueFlagPattern = collectValueFlagPattern(nodes, rootSurface);
|
|
47
|
+
lines.push(" # Build subcommand path by scanning COMP_WORDS");
|
|
48
|
+
lines.push(" local subcmd_path=\"\"");
|
|
49
|
+
lines.push(" local i");
|
|
50
|
+
lines.push(" for ((i = 1; i < cword; i++)); do");
|
|
51
|
+
lines.push(" case \"${words[i]}\" in");
|
|
52
|
+
lines.push(" --) break ;;");
|
|
53
|
+
if (valueFlagPattern.length > 0) lines.push(`\t\t\t${valueFlagPattern}) ((i++)); continue ;;`);
|
|
54
|
+
lines.push(" -*) continue ;;");
|
|
55
|
+
lines.push(" esac");
|
|
56
|
+
emitBashPathDetection(lines, visibleCommands, groupNodes, maxDepth);
|
|
57
|
+
lines.push(" done");
|
|
58
|
+
lines.push("");
|
|
59
|
+
lines.push(" # Complete flags and subcommands for the active path");
|
|
60
|
+
lines.push(" case \"$subcmd_path\" in");
|
|
61
|
+
for (const node of nodes) {
|
|
62
|
+
const pathKey = node.path.join(" ");
|
|
63
|
+
const mergedFlags = node.mergedFlags;
|
|
64
|
+
const enumCases = collectEnumCasesFromFlags(mergedFlags);
|
|
65
|
+
const flagWords = collectFlagWords(mergedFlags);
|
|
66
|
+
const childNames = dedupeWords(node.children.flatMap((child) => [child.name, ...child.aliases])).map(escapeForSingleQuote).join(" ");
|
|
67
|
+
const escapedFlagWords = flagWords.split(" ").filter(Boolean).map(escapeForSingleQuote).join(" ");
|
|
68
|
+
const completionWords = childNames.length > 0 ? `${childNames} ${escapedFlagWords}` : escapedFlagWords;
|
|
69
|
+
lines.push(`\t\t${quoteShellCasePattern(pathKey)})`);
|
|
70
|
+
if (enumCases.length > 0) {
|
|
71
|
+
lines.push(" local enum_flag=\"\"");
|
|
72
|
+
lines.push(" local enum_cur=\"$cur\"");
|
|
73
|
+
lines.push(" local enum_prefix=\"\"");
|
|
74
|
+
lines.push(" if [[ \"$cur\" == --*=* ]]; then");
|
|
75
|
+
lines.push(`\t\t\t\tenum_flag="\${cur%%=*}"`);
|
|
76
|
+
lines.push(`\t\t\t\tenum_cur="\${cur#*=}"`);
|
|
77
|
+
lines.push(`\t\t\t\tenum_prefix="\${cur%%=*}="`);
|
|
78
|
+
lines.push(" fi");
|
|
79
|
+
lines.push(`\t\t\tcase "\${enum_flag:-$prev}" in`);
|
|
80
|
+
for (const ec of enumCases) {
|
|
81
|
+
lines.push(`\t\t\t\t${ec.flags})`);
|
|
82
|
+
lines.push(formatBashEnumCompletion(ec.values, " ", "enum_cur", "enum_prefix"));
|
|
83
|
+
lines.push(" return");
|
|
84
|
+
lines.push(" ;;");
|
|
85
|
+
}
|
|
86
|
+
lines.push(" *)");
|
|
87
|
+
lines.push(" ;;");
|
|
88
|
+
lines.push(" esac");
|
|
89
|
+
}
|
|
90
|
+
lines.push(`\t\t\tCOMPREPLY=($(compgen -W '${completionWords.trim()}' -- "$cur"))`);
|
|
91
|
+
lines.push(" return");
|
|
92
|
+
lines.push(" ;;");
|
|
93
|
+
}
|
|
94
|
+
lines.push(" *)");
|
|
95
|
+
lines.push(" ;;");
|
|
96
|
+
lines.push(" esac");
|
|
97
|
+
lines.push("");
|
|
98
|
+
const rootFlagWords = collectFlagWords(rootSurface.rootFlags).split(" ").filter(Boolean);
|
|
99
|
+
const defaultFlagWords = rootSurface.includeDefaultFlags ? collectFlagWords(rootSurface.defaultFlags).split(" ").filter(Boolean) : [];
|
|
100
|
+
const completionWords = dedupeWords([
|
|
101
|
+
...visibleCommands.flatMap((command) => [command.name, ...command.aliases]),
|
|
102
|
+
...rootFlagWords,
|
|
103
|
+
...defaultFlagWords
|
|
104
|
+
]).map(escapeForSingleQuote).join(" ");
|
|
105
|
+
lines.push(`\t# Root-level completions: visible root surface`);
|
|
106
|
+
lines.push(`\tCOMPREPLY=($(compgen -W '${completionWords}' -- "$cur"))`);
|
|
107
|
+
} else {
|
|
108
|
+
const globalFlags = collectFlagWords(rootSurface.rootFlags);
|
|
109
|
+
lines.push(`\tCOMPREPLY=($(compgen -W '${globalFlags}' -- "$cur"))`);
|
|
110
|
+
}
|
|
111
|
+
lines.push("}");
|
|
112
|
+
lines.push("");
|
|
113
|
+
lines.push(`complete -F ${funcName} ${quoteShellArg(schema.name)}`);
|
|
114
|
+
lines.push("");
|
|
115
|
+
return lines.join("\n");
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Emit bash case branches for progressive subcommand path detection.
|
|
119
|
+
*
|
|
120
|
+
* For each nesting depth, generates a `case "$subcmd_path"` that matches
|
|
121
|
+
* the current accumulated path and extends it when a matching child command
|
|
122
|
+
* name is found in COMP_WORDS.
|
|
123
|
+
*
|
|
124
|
+
* @internal
|
|
125
|
+
*/
|
|
126
|
+
function emitBashPathDetection(lines, visibleCommands, groupNodes, maxDepth) {
|
|
127
|
+
lines.push(`\t\tcase "$subcmd_path" in`);
|
|
128
|
+
lines.push(`\t\t\t'')`);
|
|
129
|
+
lines.push(`\t\t\t\tcase "\${words[i]}" in`);
|
|
130
|
+
for (const command of visibleCommands) {
|
|
131
|
+
const patterns = [command.name, ...command.aliases].map(escapeBashCasePatternValue);
|
|
132
|
+
lines.push(`\t\t\t\t\t${patterns.join("|")})`);
|
|
133
|
+
lines.push(`\t\t\t\t\t\tsubcmd_path="${escapeBashDoubleQuotedValue(command.name)}"`);
|
|
134
|
+
lines.push(`\t\t\t\t\t\t;;`);
|
|
135
|
+
}
|
|
136
|
+
lines.push(`\t\t\t\tesac`);
|
|
137
|
+
lines.push(`\t\t\t\t;;`);
|
|
138
|
+
if (maxDepth > 1) for (const node of groupNodes) {
|
|
139
|
+
const pathKey = node.path.join(" ");
|
|
140
|
+
lines.push(`\t\t\t${quoteShellCasePattern(pathKey)})`);
|
|
141
|
+
lines.push(`\t\t\t\tcase "\${words[i]}" in`);
|
|
142
|
+
for (const child of node.children) {
|
|
143
|
+
const childPatterns = [child.name, ...child.aliases].map(escapeBashCasePatternValue);
|
|
144
|
+
lines.push(`\t\t\t\t\t${childPatterns.join("|")})`);
|
|
145
|
+
lines.push(`\t\t\t\t\t\tsubcmd_path="$subcmd_path ${escapeBashDoubleQuotedValue(child.name)}"`);
|
|
146
|
+
lines.push(`\t\t\t\t\t\t;;`);
|
|
147
|
+
}
|
|
148
|
+
lines.push(`\t\t\t\tesac`);
|
|
149
|
+
lines.push(`\t\t\t\t;;`);
|
|
150
|
+
}
|
|
151
|
+
lines.push(`\t\tesac`);
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* Escape a string for use as a bash `case` pattern.
|
|
155
|
+
*
|
|
156
|
+
* Escapes glob metacharacters so arbitrary command, alias, and flag names are
|
|
157
|
+
* matched literally rather than being interpreted as shell patterns.
|
|
158
|
+
*
|
|
159
|
+
* @internal
|
|
160
|
+
*/
|
|
161
|
+
function quoteShellCasePattern(pattern) {
|
|
162
|
+
if (pattern.includes(" ")) return `"${escapeBashDoubleQuotedValue(pattern)}"`;
|
|
163
|
+
return escapeBashCasePatternValue(pattern);
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* Escape a value for use in a bash `case` pattern.
|
|
167
|
+
*
|
|
168
|
+
* Escapes glob metacharacters so arbitrary command and flag names are matched
|
|
169
|
+
* literally rather than being interpreted as shell patterns.
|
|
170
|
+
*
|
|
171
|
+
* @internal
|
|
172
|
+
*/
|
|
173
|
+
function escapeBashCasePatternValue(value) {
|
|
174
|
+
if (/^[a-zA-Z0-9_\-.]+$/.test(value)) return value;
|
|
175
|
+
return value.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, (match) => match === " " ? "\\ " : `\\${match}`);
|
|
176
|
+
}
|
|
177
|
+
/**
|
|
178
|
+
* Escape a value for interpolation inside a bash double-quoted string.
|
|
179
|
+
*
|
|
180
|
+
* @internal
|
|
181
|
+
*/
|
|
182
|
+
function escapeBashDoubleQuotedValue(value) {
|
|
183
|
+
return value.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\$/g, "\\$").replace(/`/g, "\\`");
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* Escape a string for safe embedding inside an existing single-quoted
|
|
187
|
+
* shell literal (e.g. inside `compgen -W '...'`).
|
|
188
|
+
*
|
|
189
|
+
* Uses the `'\''` idiom: close quote, escaped literal quote, reopen
|
|
190
|
+
* quote. Returns the input unchanged when it consists only of shell-safe
|
|
191
|
+
* characters, which covers the vast majority of flag/command names.
|
|
192
|
+
*
|
|
193
|
+
* @internal
|
|
194
|
+
*/
|
|
195
|
+
function escapeForSingleQuote(value) {
|
|
196
|
+
if (/^[a-zA-Z0-9_\-.]+$/.test(value)) return value;
|
|
197
|
+
return value.replace(/'/g, "'\\''");
|
|
198
|
+
}
|
|
199
|
+
/**
|
|
200
|
+
* Format a COMPREPLY line for bash enum value completion.
|
|
201
|
+
*
|
|
202
|
+
* When all values are simple (no whitespace or special chars), emits a
|
|
203
|
+
* standard `compgen -W 'v1 v2' -- "$cur"` line.
|
|
204
|
+
*
|
|
205
|
+
* When any value contains whitespace, single quotes, or backslashes,
|
|
206
|
+
* uses `IFS=$'\n'` with `$'...'` quoting to split on newlines
|
|
207
|
+
* instead of spaces, handling all special characters correctly.
|
|
208
|
+
*
|
|
209
|
+
* @internal
|
|
210
|
+
*/
|
|
211
|
+
function formatBashEnumCompletion(values, indent, currentVar = "cur", prefixVar) {
|
|
212
|
+
const lines = [];
|
|
213
|
+
if (values.some((v) => !/^[a-zA-Z0-9_\-.]+$/.test(v))) {
|
|
214
|
+
const joined = values.map(escapeBashDollarQuote).join("\\n");
|
|
215
|
+
lines.push(`${indent}local IFS=$'\\n'`);
|
|
216
|
+
lines.push(`${indent}COMPREPLY=($(compgen -W $'${joined}' -- "$${currentVar}"))`);
|
|
217
|
+
} else lines.push(`${indent}COMPREPLY=($(compgen -W '${values.join(" ")}' -- "$${currentVar}"))`);
|
|
218
|
+
if (prefixVar !== void 0) {
|
|
219
|
+
lines.push(`${indent}if [[ -n "$${prefixVar}" && "\${#COMPREPLY[@]}" -gt 0 ]]; then`);
|
|
220
|
+
lines.push(`${indent}\tlocal i`);
|
|
221
|
+
lines.push(`${indent}\tfor ((i = 0; i < \${#COMPREPLY[@]}; i++)); do`);
|
|
222
|
+
lines.push(`${indent}\t\tCOMPREPLY[i]="$${prefixVar}\${COMPREPLY[i]}"`);
|
|
223
|
+
lines.push(`${indent}\tdone`);
|
|
224
|
+
lines.push(`${indent}fi`);
|
|
225
|
+
}
|
|
226
|
+
return lines.join("\n");
|
|
227
|
+
}
|
|
228
|
+
/**
|
|
229
|
+
* Escape a single enum value for use inside a bash `$'...'` string.
|
|
230
|
+
*
|
|
231
|
+
* In `$'...'` context:
|
|
232
|
+
* - `\\` → literal backslash
|
|
233
|
+
* - `\'` → literal single quote
|
|
234
|
+
* - `\n` → newline (used as IFS delimiter, so must be escaped in values)
|
|
235
|
+
*
|
|
236
|
+
* Values that are simple identifiers pass through unescaped.
|
|
237
|
+
*
|
|
238
|
+
* @internal
|
|
239
|
+
*/
|
|
240
|
+
function escapeBashDollarQuote(value) {
|
|
241
|
+
return value.replace(/\\/g, "\\\\").replace(/'/g, "\\'").replace(/\n/g, "\\n");
|
|
242
|
+
}
|
|
243
|
+
/**
|
|
244
|
+
* Collect all `--flag` words (long + short aliases) for a flag record.
|
|
245
|
+
*
|
|
246
|
+
* @internal
|
|
247
|
+
*/
|
|
248
|
+
function collectFlagWords(flags) {
|
|
249
|
+
const words = [];
|
|
250
|
+
for (const [name, schema] of Object.entries(flags)) {
|
|
251
|
+
words.push(`--${name}`);
|
|
252
|
+
for (const alias of getFlagAliasNames(schema)) words.push(alias.length === 1 ? `-${alias}` : `--${alias}`);
|
|
253
|
+
}
|
|
254
|
+
return words.join(" ");
|
|
255
|
+
}
|
|
256
|
+
/**
|
|
257
|
+
* Collect all non-boolean flag forms across every node and root surface,
|
|
258
|
+
* deduplicated and escaped for use in a bash `case` pattern.
|
|
259
|
+
*
|
|
260
|
+
* Returns a `|`-joined pattern like `--schema|-s|--output|-o` that the
|
|
261
|
+
* subcommand-path walker uses to skip the operand following a value-taking
|
|
262
|
+
* flag. Returns an empty string when no value-taking flags exist.
|
|
263
|
+
*
|
|
264
|
+
* @internal
|
|
265
|
+
*/
|
|
266
|
+
function collectValueFlagPattern(nodes, rootSurface) {
|
|
267
|
+
const forms = /* @__PURE__ */ new Set();
|
|
268
|
+
const addFlags = (flags) => {
|
|
269
|
+
for (const [name, schema] of Object.entries(flags)) {
|
|
270
|
+
if (schema.kind === "boolean") continue;
|
|
271
|
+
forms.add(`--${name}`);
|
|
272
|
+
for (const alias of getFlagAliasNames(schema, { includeHidden: true })) forms.add(alias.length === 1 ? `-${alias}` : `--${alias}`);
|
|
273
|
+
}
|
|
274
|
+
};
|
|
275
|
+
for (const node of nodes) addFlags(node.mergedFlags);
|
|
276
|
+
addFlags(rootSurface.rootFlags);
|
|
277
|
+
if (rootSurface.includeDefaultFlags) addFlags(rootSurface.defaultFlags);
|
|
278
|
+
return [...forms].map(escapeBashCasePatternValue).join("|");
|
|
279
|
+
}
|
|
280
|
+
function dedupeWords(words) {
|
|
281
|
+
return [...new Set(words)];
|
|
282
|
+
}
|
|
283
|
+
/**
|
|
284
|
+
* Collect enum flag cases from a merged flag record.
|
|
285
|
+
*
|
|
286
|
+
* Each enum flag produces one case entry with its long/short flag forms
|
|
287
|
+
* as the pattern and enum values as the completions.
|
|
288
|
+
*
|
|
289
|
+
* @internal
|
|
290
|
+
*/
|
|
291
|
+
function collectEnumCasesFromFlags(flags) {
|
|
292
|
+
const cases = [];
|
|
293
|
+
for (const [name, schema] of Object.entries(flags)) {
|
|
294
|
+
if (schema.kind !== "enum" || schema.enumValues === void 0) continue;
|
|
295
|
+
const flagForms = [`--${name}`, ...getFlagAliasNames(schema, { includeHidden: true }).map((alias) => alias.length === 1 ? `-${alias}` : `--${alias}`)].map(escapeBashCasePatternValue);
|
|
296
|
+
cases.push({
|
|
297
|
+
flags: flagForms.join("|"),
|
|
298
|
+
values: schema.enumValues
|
|
299
|
+
});
|
|
300
|
+
}
|
|
301
|
+
return cases;
|
|
302
|
+
}
|
|
303
|
+
//#endregion
|
|
304
|
+
export { generateBashCompletion };
|