@kjanat/dreamcli 3.0.0-rc.1 → 3.0.0-rc.10

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.
Files changed (194) hide show
  1. package/CHANGELOG.md +217 -1
  2. package/dist/core/cli/dispatch.d.mts +6 -5
  3. package/dist/core/cli/dispatch.mjs +205 -1
  4. package/dist/core/cli/help-links.d.mts +0 -1
  5. package/dist/core/cli/help-links.mjs +41 -1
  6. package/dist/core/cli/index.d.mts +81 -8
  7. package/dist/core/cli/index.mjs +945 -1
  8. package/dist/core/cli/planner.d.mts +5 -1
  9. package/dist/core/cli/planner.mjs +300 -1
  10. package/dist/core/cli/plugin.d.mts +1 -1
  11. package/dist/core/cli/plugin.mjs +41 -1
  12. package/dist/core/cli/propagate.d.mts +1 -1
  13. package/dist/core/cli/propagate.mjs +57 -1
  14. package/dist/core/cli/root-help.d.mts +2 -1
  15. package/dist/core/cli/root-help.mjs +226 -4
  16. package/dist/core/cli/root-surface.d.mts +12 -1
  17. package/dist/core/cli/root-surface.mjs +28 -1
  18. package/dist/core/cli/runtime-preflight.d.mts +14 -2
  19. package/dist/core/cli/runtime-preflight.mjs +169 -1
  20. package/dist/core/completion/index.d.mts +0 -1
  21. package/dist/core/completion/index.mjs +90 -1
  22. package/dist/core/completion/shells/bash.d.mts +0 -1
  23. package/dist/core/completion/shells/bash.mjs +308 -3
  24. package/dist/core/completion/shells/fish.d.mts +0 -1
  25. package/dist/core/completion/shells/fish.mjs +162 -2
  26. package/dist/core/completion/shells/powershell.d.mts +0 -1
  27. package/dist/core/completion/shells/powershell.mjs +358 -2
  28. package/dist/core/completion/shells/shared.d.mts +13 -2
  29. package/dist/core/completion/shells/shared.mjs +176 -1
  30. package/dist/core/completion/shells/zsh.d.mts +0 -1
  31. package/dist/core/completion/shells/zsh.mjs +251 -2
  32. package/dist/core/config/index.d.mts +2 -3
  33. package/dist/core/config/index.mjs +246 -1
  34. package/dist/core/config/package-json.d.mts +27 -4
  35. package/dist/core/config/package-json.mjs +386 -3
  36. package/dist/core/errors/index.d.mts +3 -3
  37. package/dist/core/errors/index.mjs +87 -1
  38. package/dist/core/execution/index.d.mts +0 -1
  39. package/dist/core/execution/index.mjs +201 -1
  40. package/dist/core/help/ansi.d.mts +11 -5
  41. package/dist/core/help/ansi.mjs +121 -2
  42. package/dist/core/help/index.d.mts +22 -3
  43. package/dist/core/help/index.mjs +341 -7
  44. package/dist/core/help/theme.d.mts +68 -0
  45. package/dist/core/help/theme.mjs +46 -0
  46. package/dist/core/json-schema/index.d.mts +15 -2
  47. package/dist/core/json-schema/index.mjs +536 -12
  48. package/dist/core/json-schema/meta-descriptions.generated.d.mts +55 -38
  49. package/dist/core/json-schema/meta-descriptions.generated.mjs +102 -28
  50. package/dist/core/output/activity.d.mts +0 -1
  51. package/dist/core/output/activity.mjs +452 -1
  52. package/dist/core/output/bind.mjs +56 -1
  53. package/dist/core/output/contracts.d.mts +4 -5
  54. package/dist/core/output/contracts.mjs +57 -1
  55. package/dist/core/output/display-value.mjs +32 -1
  56. package/dist/core/output/index.d.mts +21 -1
  57. package/dist/core/output/index.mjs +442 -2
  58. package/dist/core/output/renderers.d.mts +0 -1
  59. package/dist/core/output/renderers.mjs +46 -1
  60. package/dist/core/output/writer.mjs +12 -1
  61. package/dist/core/parse/index.d.mts +40 -7
  62. package/dist/core/parse/index.mjs +727 -1
  63. package/dist/core/prompt/index.d.mts +1 -1
  64. package/dist/core/prompt/index.mjs +348 -6
  65. package/dist/core/resolve/args.d.mts +1 -1
  66. package/dist/core/resolve/args.mjs +105 -1
  67. package/dist/core/resolve/coerce.d.mts +1 -1
  68. package/dist/core/resolve/coerce.mjs +336 -1
  69. package/dist/core/resolve/config.mjs +19 -1
  70. package/dist/core/resolve/contracts.d.mts +9 -4
  71. package/dist/core/resolve/errors.d.mts +0 -1
  72. package/dist/core/resolve/errors.mjs +140 -2
  73. package/dist/core/resolve/flags.d.mts +7 -2
  74. package/dist/core/resolve/flags.mjs +251 -1
  75. package/dist/core/resolve/index.d.mts +2 -2
  76. package/dist/core/resolve/index.mjs +85 -1
  77. package/dist/core/resolve/property.d.mts +4 -2
  78. package/dist/core/resolve/property.mjs +53 -1
  79. package/dist/core/schema/activity.d.mts +31 -11
  80. package/dist/core/schema/arg.d.mts +3 -4
  81. package/dist/core/schema/arg.mjs +463 -1
  82. package/dist/core/schema/command.d.mts +26 -6
  83. package/dist/core/schema/command.mjs +726 -1
  84. package/dist/core/schema/flag.d.mts +485 -19
  85. package/dist/core/schema/flag.mjs +705 -1
  86. package/dist/core/schema/index.d.mts +4 -2
  87. package/dist/core/schema/middleware.d.mts +4 -3
  88. package/dist/core/schema/middleware.mjs +41 -1
  89. package/dist/core/schema/number-constraints.mjs +60 -1
  90. package/dist/core/schema/prompt.d.mts +6 -3
  91. package/dist/core/schema/run.d.mts +20 -1
  92. package/dist/core/schema/string-constraints.d.mts +97 -0
  93. package/dist/core/schema/string-constraints.mjs +69 -0
  94. package/dist/core/schema/value-parsers.d.mts +78 -0
  95. package/dist/core/schema/value-parsers.mjs +142 -0
  96. package/dist/core/schema-dsl/runtime.mjs +271 -2
  97. package/dist/core/schema-dsl/to-json-schema.d.mts +0 -1
  98. package/dist/core/schema-dsl/to-json-schema.mjs +74 -1
  99. package/dist/core/testkit/index.d.mts +0 -31
  100. package/dist/core/testkit/index.mjs +83 -1
  101. package/dist/index.d.mts +11 -6
  102. package/dist/index.mjs +22 -1
  103. package/dist/runtime/adapter.d.mts +38 -2
  104. package/dist/runtime/adapter.mjs +87 -1
  105. package/dist/runtime/auto.d.mts +2 -3
  106. package/dist/runtime/auto.mjs +45 -1
  107. package/dist/runtime/deno.d.mts +24 -5
  108. package/dist/runtime/deno.mjs +262 -2
  109. package/dist/runtime/detect.mjs +45 -1
  110. package/dist/runtime/index.d.mts +3 -4
  111. package/dist/runtime/node.d.mts +8 -2
  112. package/dist/runtime/node.mjs +220 -2
  113. package/dist/runtime/paths.mjs +48 -1
  114. package/dist/runtime.d.mts +4 -4
  115. package/dist/runtime.mjs +6 -1
  116. package/dist/strings.mjs +22 -1
  117. package/dist/testkit.d.mts +1 -0
  118. package/dist/testkit.mjs +5 -1
  119. package/dist/version.d.mts +7 -3
  120. package/dist/version.mjs +7 -1
  121. package/dreamcli.schema.json +36 -7
  122. package/package.json +45 -42
  123. package/dist/runtime/bun.d.mts +0 -28
  124. package/dist/runtime/bun.mjs +0 -1
  125. package/src/core/cli/dispatch.ts +0 -355
  126. package/src/core/cli/help-links.ts +0 -82
  127. package/src/core/cli/index.ts +0 -1614
  128. package/src/core/cli/planner.ts +0 -656
  129. package/src/core/cli/plugin.ts +0 -117
  130. package/src/core/cli/propagate.ts +0 -97
  131. package/src/core/cli/root-help.ts +0 -342
  132. package/src/core/cli/root-surface.ts +0 -87
  133. package/src/core/cli/runtime-preflight.ts +0 -456
  134. package/src/core/completion/index.ts +0 -138
  135. package/src/core/completion/shells/bash.ts +0 -459
  136. package/src/core/completion/shells/fish.ts +0 -259
  137. package/src/core/completion/shells/powershell.ts +0 -439
  138. package/src/core/completion/shells/shared.ts +0 -310
  139. package/src/core/completion/shells/zsh.ts +0 -381
  140. package/src/core/config/index.ts +0 -417
  141. package/src/core/config/package-json.ts +0 -560
  142. package/src/core/errors/index.ts +0 -193
  143. package/src/core/execution/index.ts +0 -265
  144. package/src/core/help/ansi.ts +0 -144
  145. package/src/core/help/index.ts +0 -563
  146. package/src/core/json-schema/index.ts +0 -910
  147. package/src/core/json-schema/meta-descriptions.generated.ts +0 -202
  148. package/src/core/output/activity.ts +0 -575
  149. package/src/core/output/bind.ts +0 -59
  150. package/src/core/output/contracts.ts +0 -194
  151. package/src/core/output/display-value.ts +0 -48
  152. package/src/core/output/index.ts +0 -704
  153. package/src/core/output/renderers.ts +0 -125
  154. package/src/core/output/writer.ts +0 -46
  155. package/src/core/parse/index.ts +0 -742
  156. package/src/core/prompt/index.ts +0 -623
  157. package/src/core/resolve/args.ts +0 -144
  158. package/src/core/resolve/coerce.ts +0 -500
  159. package/src/core/resolve/config.ts +0 -26
  160. package/src/core/resolve/contracts.ts +0 -135
  161. package/src/core/resolve/errors.ts +0 -227
  162. package/src/core/resolve/flags.ts +0 -269
  163. package/src/core/resolve/index.ts +0 -108
  164. package/src/core/resolve/property.ts +0 -99
  165. package/src/core/schema/activity.ts +0 -240
  166. package/src/core/schema/arg.ts +0 -841
  167. package/src/core/schema/command.ts +0 -1500
  168. package/src/core/schema/flag.ts +0 -917
  169. package/src/core/schema/index.ts +0 -96
  170. package/src/core/schema/middleware.ts +0 -171
  171. package/src/core/schema/number-constraints.ts +0 -153
  172. package/src/core/schema/prompt.ts +0 -171
  173. package/src/core/schema/run.ts +0 -198
  174. package/src/core/schema-dsl/index.ts +0 -109
  175. package/src/core/schema-dsl/parse.ts +0 -262
  176. package/src/core/schema-dsl/runtime.ts +0 -609
  177. package/src/core/schema-dsl/to-json-schema.ts +0 -102
  178. package/src/core/testkit/index.ts +0 -147
  179. package/src/index.ts +0 -181
  180. package/src/runtime/adapter.ts +0 -303
  181. package/src/runtime/auto.ts +0 -86
  182. package/src/runtime/bun.ts +0 -48
  183. package/src/runtime/deno.ts +0 -367
  184. package/src/runtime/detect.ts +0 -105
  185. package/src/runtime/index.ts +0 -21
  186. package/src/runtime/node-builtins.d.ts +0 -27
  187. package/src/runtime/node.ts +0 -289
  188. package/src/runtime/paths.ts +0 -64
  189. package/src/runtime/support.ts +0 -77
  190. package/src/runtime.ts +0 -31
  191. package/src/schema.ts +0 -16
  192. package/src/strings.ts +0 -34
  193. package/src/testkit.ts +0 -25
  194. package/src/version.ts +0 -20
@@ -1,459 +0,0 @@
1
- /**
2
- * Bash completion script generator.
3
- *
4
- * Produces a self-contained bash script with:
5
- * - A main `_<name>_completions` function using `COMP_WORDS`/`COMP_CWORD`
6
- * - Multi-level subcommand path detection via progressive COMP_WORDS scanning
7
- * - Per-command case branches with flag and subcommand completions
8
- * - Propagated flags from ancestor commands at each nesting level
9
- * - Enum value completions for `--flag=<value>` patterns
10
- * - A `complete -F` registration line
11
- *
12
- * **Requires** the `bash-completion` package (`_init_completion`).
13
- *
14
- * @module dreamcli/core/completion/shells/bash
15
- * @internal
16
- */
17
-
18
- import type { CLISchema } from '#internals/core/cli/index.ts';
19
- import { getFlagAliasNames } from '#internals/core/schema/flag.ts';
20
- import type { CommandSchema, FlagSchema } from '#internals/core/schema/index.ts';
21
- import type { CommandNode, CompletionOptions, RootCompletionSurface } from './shared.ts';
22
- import {
23
- quoteShellArg,
24
- resolveRootCompletionSurface,
25
- sanitizeShellIdentifier,
26
- versionTag,
27
- walkCommandTree,
28
- } from './shared.ts';
29
-
30
- // --- Public generator
31
-
32
- /**
33
- * Generate a bash completion script for the CLI.
34
- *
35
- * Use this when you want a bash-specific script directly rather than routing
36
- * through {@link generateCompletion}. The generated script expects the
37
- * `bash-completion` package because it relies on `_init_completion`.
38
- *
39
- * @param schema - The CLI schema.
40
- * @param options - Optional generator configuration.
41
- * @returns A complete bash completion script.
42
- *
43
- * @example
44
- * ```ts
45
- * const script = generateBashCompletion(app.schema);
46
- * // install with: mycli completions bash > /etc/bash_completion.d/mycli
47
- * ```
48
- */
49
- function generateBashCompletion(schema: CLISchema, options?: CompletionOptions): string {
50
- const prefix = options?.functionPrefix ?? schema.name;
51
- const funcName = `_${sanitizeShellIdentifier(prefix)}_completions`;
52
- const rootSurface = resolveRootCompletionSurface(schema, options?.rootMode);
53
- const visibleCommands = rootSurface.visibleCommands;
54
- const nodes = walkCommandTree(visibleCommands);
55
- const maxDepth = nodes.reduce((max, n) => Math.max(max, n.path.length), 0);
56
-
57
- const lines: string[] = [];
58
-
59
- lines.push('#!/usr/bin/env bash');
60
- lines.push(`# Bash completion for ${schema.name}`);
61
- lines.push(`# Generated by ${versionTag()}`);
62
- lines.push('#');
63
- lines.push(`# Usage: source <(${schema.name} completions bash)`);
64
- lines.push('#');
65
- lines.push('# Install permanently:');
66
- lines.push(
67
- `# ${schema.name} completions bash > /etc/bash_completion.d/${schema.name} # Linux`,
68
- );
69
- lines.push(
70
- `# ${schema.name} completions bash > $(brew --prefix)/etc/bash_completion.d/${schema.name} # macOS`,
71
- );
72
- lines.push('#');
73
- lines.push('# Requires: bash-completion (provides _init_completion)');
74
- lines.push('');
75
- lines.push(`${funcName}() {`);
76
- lines.push(`\tlocal cur prev words cword`);
77
- lines.push(`\t_init_completion || return`);
78
- lines.push('');
79
-
80
- // --- Subcommand dispatch ---
81
- if (visibleCommands.length > 0) {
82
- const groupNodes = nodes.filter((n) => n.children.length > 0);
83
-
84
- // Collect all value-taking flag forms across the entire tree so the
85
- // walker can skip their operands instead of treating them as subcommands.
86
- const valueFlagPattern = collectValueFlagPattern(nodes, rootSurface);
87
-
88
- // Build subcommand path by scanning COMP_WORDS at each depth level.
89
- // At depth 0 we look for top-level command names, at depth 1 we look
90
- // for children of the matched depth-0 command, etc.
91
- lines.push('\t# Build subcommand path by scanning COMP_WORDS');
92
- lines.push('\tlocal subcmd_path=""');
93
- lines.push('\tlocal i');
94
- lines.push('\tfor ((i = 1; i < cword; i++)); do');
95
- // biome-ignore lint/suspicious/noTemplateCurlyInString: bash syntax, not JS template
96
- lines.push('\t\tcase "${words[i]}" in');
97
- lines.push('\t\t\t--) break ;;');
98
- if (valueFlagPattern.length > 0) {
99
- lines.push(`\t\t\t${valueFlagPattern}) ((i++)); continue ;;`);
100
- }
101
- lines.push('\t\t\t-*) continue ;;');
102
- lines.push('\t\tesac');
103
-
104
- // Emit progressive path-building cases
105
- emitBashPathDetection(lines, visibleCommands, groupNodes, maxDepth);
106
-
107
- lines.push('\tdone');
108
- lines.push('');
109
-
110
- // Per-path completions: one case branch per node
111
- lines.push('\t# Complete flags and subcommands for the active path');
112
- lines.push('\tcase "$subcmd_path" in');
113
-
114
- for (const node of nodes) {
115
- const pathKey = node.path.join(' ');
116
- const mergedFlags = node.mergedFlags;
117
- const enumCases = collectEnumCasesFromFlags(mergedFlags);
118
- const flagWords = collectFlagWords(mergedFlags);
119
- const childNames = dedupeWords(
120
- node.children.flatMap((child) => [child.name, ...child.aliases]),
121
- )
122
- .map(escapeForSingleQuote)
123
- .join(' ');
124
- const escapedFlagWords = flagWords
125
- .split(' ')
126
- .filter(Boolean)
127
- .map(escapeForSingleQuote)
128
- .join(' ');
129
- const completionWords =
130
- childNames.length > 0 ? `${childNames} ${escapedFlagWords}` : escapedFlagWords;
131
-
132
- lines.push(`\t\t${quoteShellCasePattern(pathKey)})`);
133
-
134
- if (enumCases.length > 0) {
135
- lines.push('\t\t\tlocal enum_flag=""');
136
- lines.push('\t\t\tlocal enum_cur="$cur"');
137
- lines.push('\t\t\tlocal enum_prefix=""');
138
- lines.push('\t\t\tif [[ "$cur" == --*=* ]]; then');
139
- lines.push(`\t\t\t\tenum_flag="\${cur%%=*}"`);
140
- lines.push(`\t\t\t\tenum_cur="\${cur#*=}"`);
141
- lines.push(`\t\t\t\tenum_prefix="\${cur%%=*}="`);
142
- lines.push('\t\t\tfi');
143
- lines.push(`\t\t\tcase "\${enum_flag:-$prev}" in`);
144
- for (const ec of enumCases) {
145
- lines.push(`\t\t\t\t${ec.flags})`);
146
- lines.push(formatBashEnumCompletion(ec.values, '\t\t\t\t\t', 'enum_cur', 'enum_prefix'));
147
- lines.push('\t\t\t\t\treturn');
148
- lines.push('\t\t\t\t\t;;');
149
- }
150
- lines.push('\t\t\t\t*)');
151
- lines.push('\t\t\t\t\t;;');
152
- lines.push('\t\t\tesac');
153
- }
154
-
155
- lines.push(`\t\t\tCOMPREPLY=($(compgen -W '${completionWords.trim()}' -- "$cur"))`);
156
- lines.push('\t\t\treturn');
157
- lines.push('\t\t\t;;');
158
- }
159
-
160
- lines.push('\t\t*)');
161
- lines.push('\t\t\t;;');
162
- lines.push('\tesac');
163
- lines.push('');
164
-
165
- // --- Root-level: visible root surface ---
166
- const rootFlagWords = collectFlagWords(rootSurface.rootFlags).split(' ').filter(Boolean);
167
- const defaultFlagWords = rootSurface.includeDefaultFlags
168
- ? collectFlagWords(rootSurface.defaultFlags).split(' ').filter(Boolean)
169
- : [];
170
- const completionWords = dedupeWords([
171
- ...visibleCommands.flatMap((command) => [command.name, ...command.aliases]),
172
- ...rootFlagWords,
173
- ...defaultFlagWords,
174
- ])
175
- .map(escapeForSingleQuote)
176
- .join(' ');
177
- lines.push(`\t# Root-level completions: visible root surface`);
178
- lines.push(`\tCOMPREPLY=($(compgen -W '${completionWords}' -- "$cur"))`);
179
- } else {
180
- const globalFlags = collectFlagWords(rootSurface.rootFlags);
181
- lines.push(`\tCOMPREPLY=($(compgen -W '${globalFlags}' -- "$cur"))`);
182
- }
183
-
184
- lines.push('}');
185
- lines.push('');
186
- lines.push(`complete -F ${funcName} ${quoteShellArg(schema.name)}`);
187
- lines.push('');
188
-
189
- return lines.join('\n');
190
- }
191
-
192
- // --- Bash helpers — internal
193
-
194
- /**
195
- * Emit bash case branches for progressive subcommand path detection.
196
- *
197
- * For each nesting depth, generates a `case "$subcmd_path"` that matches
198
- * the current accumulated path and extends it when a matching child command
199
- * name is found in COMP_WORDS.
200
- *
201
- * @internal
202
- */
203
- function emitBashPathDetection(
204
- lines: string[],
205
- visibleCommands: readonly CommandSchema[],
206
- groupNodes: readonly CommandNode[],
207
- maxDepth: number,
208
- ): void {
209
- // Depth 0: match top-level command names
210
- lines.push(`\t\tcase "$subcmd_path" in`);
211
- lines.push(`\t\t\t'')`);
212
- lines.push(`\t\t\t\tcase "\${words[i]}" in`);
213
- for (const command of visibleCommands) {
214
- const patterns = [command.name, ...command.aliases].map(escapeBashCasePatternValue);
215
- lines.push(`\t\t\t\t\t${patterns.join('|')})`);
216
- lines.push(`\t\t\t\t\t\tsubcmd_path="${escapeBashDoubleQuotedValue(command.name)}"`);
217
- lines.push(`\t\t\t\t\t\t;;`);
218
- }
219
- lines.push(`\t\t\t\tesac`);
220
- lines.push(`\t\t\t\t;;`);
221
-
222
- // Deeper levels: for each group that has children, match its path and extend
223
- if (maxDepth > 1) {
224
- for (const node of groupNodes) {
225
- const pathKey = node.path.join(' ');
226
-
227
- lines.push(`\t\t\t${quoteShellCasePattern(pathKey)})`);
228
- lines.push(`\t\t\t\tcase "\${words[i]}" in`);
229
- for (const child of node.children) {
230
- const childPatterns = [child.name, ...child.aliases].map(escapeBashCasePatternValue);
231
- lines.push(`\t\t\t\t\t${childPatterns.join('|')})`);
232
- lines.push(
233
- `\t\t\t\t\t\tsubcmd_path="$subcmd_path ${escapeBashDoubleQuotedValue(child.name)}"`,
234
- );
235
- lines.push(`\t\t\t\t\t\t;;`);
236
- }
237
- lines.push(`\t\t\t\tesac`);
238
- lines.push(`\t\t\t\t;;`);
239
- }
240
- }
241
-
242
- lines.push(`\t\tesac`);
243
- }
244
-
245
- /**
246
- * Escape a string for use as a bash `case` pattern.
247
- *
248
- * Escapes glob metacharacters so arbitrary command, alias, and flag names are
249
- * matched literally rather than being interpreted as shell patterns.
250
- *
251
- * @internal
252
- */
253
- function quoteShellCasePattern(pattern: string): string {
254
- if (pattern.includes(' ')) return `"${escapeBashDoubleQuotedValue(pattern)}"`;
255
- return escapeBashCasePatternValue(pattern);
256
- }
257
-
258
- /**
259
- * Escape a value for use in a bash `case` pattern.
260
- *
261
- * Escapes glob metacharacters so arbitrary command and flag names are matched
262
- * literally rather than being interpreted as shell patterns.
263
- *
264
- * @internal
265
- */
266
- function escapeBashCasePatternValue(value: string): string {
267
- if (/^[a-zA-Z0-9_\-.]+$/.test(value)) return value;
268
- return value
269
- .replace(/\\/g, '\\\\')
270
- .replace(/'/g, "\\'")
271
- .replace(/"/g, '\\"')
272
- .replace(/\|/g, '\\|')
273
- .replace(/\*/g, '\\*')
274
- .replace(/\?/g, '\\?')
275
- .replace(/\[/g, '\\[')
276
- .replace(/\]/g, '\\]')
277
- .replace(/\(/g, '\\(')
278
- .replace(/\)/g, '\\)')
279
- .replace(/\{/g, '\\{')
280
- .replace(/\}/g, '\\}')
281
- .replace(/\+/g, '\\+')
282
- .replace(/!/g, '\\!')
283
- .replace(/@/g, '\\@')
284
- .replace(/#/g, '\\#')
285
- .replace(/~/g, '\\~')
286
- .replace(/\s/g, (match) => (match === ' ' ? '\\ ' : `\\${match}`));
287
- }
288
-
289
- /**
290
- * Escape a value for interpolation inside a bash double-quoted string.
291
- *
292
- * @internal
293
- */
294
- function escapeBashDoubleQuotedValue(value: string): string {
295
- return value
296
- .replace(/\\/g, '\\\\')
297
- .replace(/"/g, '\\"')
298
- .replace(/\$/g, '\\$')
299
- .replace(/`/g, '\\`');
300
- }
301
-
302
- /**
303
- * Escape a string for safe embedding inside an existing single-quoted
304
- * shell literal (e.g. inside `compgen -W '...'`).
305
- *
306
- * Uses the `'\''` idiom: close quote, escaped literal quote, reopen
307
- * quote. Returns the input unchanged when it consists only of shell-safe
308
- * characters, which covers the vast majority of flag/command names.
309
- *
310
- * @internal
311
- */
312
- function escapeForSingleQuote(value: string): string {
313
- if (/^[a-zA-Z0-9_\-.]+$/.test(value)) return value;
314
- return value.replace(/'/g, "'\\''");
315
- }
316
-
317
- /**
318
- * Format a COMPREPLY line for bash enum value completion.
319
- *
320
- * When all values are simple (no whitespace or special chars), emits a
321
- * standard `compgen -W 'v1 v2' -- "$cur"` line.
322
- *
323
- * When any value contains whitespace, single quotes, or backslashes,
324
- * uses `IFS=$'\n'` with `$'...'` quoting to split on newlines
325
- * instead of spaces, handling all special characters correctly.
326
- *
327
- * @internal
328
- */
329
- function formatBashEnumCompletion(
330
- values: readonly string[],
331
- indent: string,
332
- currentVar = 'cur',
333
- prefixVar?: string,
334
- ): string {
335
- const lines: string[] = [];
336
- const needsDollarQuoting = values.some((v) => !/^[a-zA-Z0-9_\-.]+$/.test(v));
337
- if (needsDollarQuoting) {
338
- const escaped = values.map(escapeBashDollarQuote);
339
- const joined = escaped.join('\\n');
340
- lines.push(`${indent}local IFS=$'\\n'`);
341
- lines.push(`${indent}COMPREPLY=($(compgen -W $'${joined}' -- "$${currentVar}"))`);
342
- } else {
343
- lines.push(`${indent}COMPREPLY=($(compgen -W '${values.join(' ')}' -- "$${currentVar}"))`);
344
- }
345
- if (prefixVar !== undefined) {
346
- lines.push(`${indent}if [[ -n "$${prefixVar}" && "\${#COMPREPLY[@]}" -gt 0 ]]; then`);
347
- lines.push(`${indent}\tlocal i`);
348
- lines.push(`${indent}\tfor ((i = 0; i < \${#COMPREPLY[@]}; i++)); do`);
349
- lines.push(`${indent}\t\tCOMPREPLY[i]="$${prefixVar}\${COMPREPLY[i]}"`);
350
- lines.push(`${indent}\tdone`);
351
- lines.push(`${indent}fi`);
352
- }
353
- return lines.join('\n');
354
- }
355
-
356
- /**
357
- * Escape a single enum value for use inside a bash `$'...'` string.
358
- *
359
- * In `$'...'` context:
360
- * - `\\` → literal backslash
361
- * - `\'` → literal single quote
362
- * - `\n` → newline (used as IFS delimiter, so must be escaped in values)
363
- *
364
- * Values that are simple identifiers pass through unescaped.
365
- *
366
- * @internal
367
- */
368
- function escapeBashDollarQuote(value: string): string {
369
- return value.replace(/\\/g, '\\\\').replace(/'/g, "\\'").replace(/\n/g, '\\n');
370
- }
371
-
372
- /**
373
- * Collect all `--flag` words (long + short aliases) for a flag record.
374
- *
375
- * @internal
376
- */
377
- function collectFlagWords(flags: Readonly<Record<string, FlagSchema>>): string {
378
- const words: string[] = [];
379
- for (const [name, schema] of Object.entries(flags)) {
380
- words.push(`--${name}`);
381
- for (const alias of getFlagAliasNames(schema)) {
382
- words.push(alias.length === 1 ? `-${alias}` : `--${alias}`);
383
- }
384
- }
385
- return words.join(' ');
386
- }
387
-
388
- /**
389
- * Collect all non-boolean flag forms across every node and root surface,
390
- * deduplicated and escaped for use in a bash `case` pattern.
391
- *
392
- * Returns a `|`-joined pattern like `--schema|-s|--output|-o` that the
393
- * subcommand-path walker uses to skip the operand following a value-taking
394
- * flag. Returns an empty string when no value-taking flags exist.
395
- *
396
- * @internal
397
- */
398
- function collectValueFlagPattern(
399
- nodes: readonly CommandNode[],
400
- rootSurface: RootCompletionSurface,
401
- ): string {
402
- const forms = new Set<string>();
403
- const addFlags = (flags: Readonly<Record<string, FlagSchema>>): void => {
404
- for (const [name, schema] of Object.entries(flags)) {
405
- if (schema.kind === 'boolean') continue;
406
- forms.add(`--${name}`);
407
- for (const alias of getFlagAliasNames(schema, { includeHidden: true })) {
408
- forms.add(alias.length === 1 ? `-${alias}` : `--${alias}`);
409
- }
410
- }
411
- };
412
- for (const node of nodes) addFlags(node.mergedFlags);
413
- addFlags(rootSurface.rootFlags);
414
- if (rootSurface.includeDefaultFlags) addFlags(rootSurface.defaultFlags);
415
- return [...forms].map(escapeBashCasePatternValue).join('|');
416
- }
417
-
418
- function dedupeWords(words: readonly string[]): readonly string[] {
419
- return [...new Set(words)];
420
- }
421
-
422
- /**
423
- * A consolidated enum-value case: the flag forms that trigger it and the values.
424
- *
425
- * @internal
426
- */
427
- interface EnumCase {
428
- readonly flags: string;
429
- readonly values: readonly string[];
430
- }
431
-
432
- /**
433
- * Collect enum flag cases from a merged flag record.
434
- *
435
- * Each enum flag produces one case entry with its long/short flag forms
436
- * as the pattern and enum values as the completions.
437
- *
438
- * @internal
439
- */
440
- function collectEnumCasesFromFlags(
441
- flags: Readonly<Record<string, FlagSchema>>,
442
- ): readonly EnumCase[] {
443
- const cases: EnumCase[] = [];
444
- for (const [name, schema] of Object.entries(flags)) {
445
- if (schema.kind !== 'enum' || schema.enumValues === undefined) continue;
446
- const flagForms = [
447
- `--${name}`,
448
- ...getFlagAliasNames(schema, { includeHidden: true }).map((alias) =>
449
- alias.length === 1 ? `-${alias}` : `--${alias}`,
450
- ),
451
- ].map(escapeBashCasePatternValue);
452
- cases.push({ flags: flagForms.join('|'), values: schema.enumValues });
453
- }
454
- return cases;
455
- }
456
-
457
- // --- Exports
458
-
459
- export { generateBashCompletion };