@kjanat/dreamcli 2.5.0 → 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 (202) hide show
  1. package/CHANGELOG.md +344 -1
  2. package/README.md +9 -2
  3. package/dist/core/cli/dispatch.d.mts +6 -5
  4. package/dist/core/cli/dispatch.mjs +205 -1
  5. package/dist/core/cli/help-links.d.mts +0 -1
  6. package/dist/core/cli/help-links.mjs +41 -1
  7. package/dist/core/cli/index.d.mts +185 -19
  8. package/dist/core/cli/index.mjs +945 -1
  9. package/dist/core/cli/planner.d.mts +32 -6
  10. package/dist/core/cli/planner.mjs +300 -1
  11. package/dist/core/cli/plugin.d.mts +1 -1
  12. package/dist/core/cli/plugin.mjs +41 -1
  13. package/dist/core/cli/propagate.d.mts +1 -1
  14. package/dist/core/cli/propagate.mjs +57 -1
  15. package/dist/core/cli/root-help.d.mts +18 -3
  16. package/dist/core/cli/root-help.mjs +226 -6
  17. package/dist/core/cli/root-surface.d.mts +30 -4
  18. package/dist/core/cli/root-surface.mjs +28 -1
  19. package/dist/core/cli/runtime-preflight.d.mts +30 -3
  20. package/dist/core/cli/runtime-preflight.mjs +169 -1
  21. package/dist/core/completion/index.d.mts +32 -2
  22. package/dist/core/completion/index.mjs +90 -1
  23. package/dist/core/completion/shells/bash.d.mts +0 -1
  24. package/dist/core/completion/shells/bash.mjs +308 -3
  25. package/dist/core/completion/shells/fish.d.mts +0 -1
  26. package/dist/core/completion/shells/fish.mjs +162 -2
  27. package/dist/core/completion/shells/powershell.d.mts +0 -1
  28. package/dist/core/completion/shells/powershell.mjs +358 -2
  29. package/dist/core/completion/shells/shared.d.mts +23 -2
  30. package/dist/core/completion/shells/shared.mjs +176 -1
  31. package/dist/core/completion/shells/zsh.d.mts +0 -1
  32. package/dist/core/completion/shells/zsh.mjs +251 -2
  33. package/dist/core/config/index.d.mts +2 -3
  34. package/dist/core/config/index.mjs +246 -1
  35. package/dist/core/config/package-json.d.mts +27 -4
  36. package/dist/core/config/package-json.mjs +386 -3
  37. package/dist/core/errors/index.d.mts +3 -3
  38. package/dist/core/errors/index.mjs +87 -1
  39. package/dist/core/execution/index.d.mts +0 -1
  40. package/dist/core/execution/index.mjs +201 -1
  41. package/dist/core/help/ansi.d.mts +11 -5
  42. package/dist/core/help/ansi.mjs +121 -2
  43. package/dist/core/help/index.d.mts +65 -2
  44. package/dist/core/help/index.mjs +341 -7
  45. package/dist/core/help/theme.d.mts +68 -0
  46. package/dist/core/help/theme.mjs +46 -0
  47. package/dist/core/json-schema/index.d.mts +15 -2
  48. package/dist/core/json-schema/index.mjs +536 -12
  49. package/dist/core/json-schema/meta-descriptions.generated.d.mts +22 -5
  50. package/dist/core/json-schema/meta-descriptions.generated.mjs +102 -28
  51. package/dist/core/output/activity.d.mts +0 -1
  52. package/dist/core/output/activity.mjs +452 -1
  53. package/dist/core/output/bind.mjs +56 -1
  54. package/dist/core/output/contracts.d.mts +4 -5
  55. package/dist/core/output/contracts.mjs +57 -1
  56. package/dist/core/output/display-value.mjs +32 -1
  57. package/dist/core/output/index.d.mts +21 -1
  58. package/dist/core/output/index.mjs +442 -2
  59. package/dist/core/output/renderers.d.mts +0 -1
  60. package/dist/core/output/renderers.mjs +46 -1
  61. package/dist/core/output/writer.mjs +12 -1
  62. package/dist/core/parse/index.d.mts +54 -7
  63. package/dist/core/parse/index.mjs +727 -1
  64. package/dist/core/prompt/index.d.mts +12 -4
  65. package/dist/core/prompt/index.mjs +348 -6
  66. package/dist/core/resolve/args.d.mts +1 -1
  67. package/dist/core/resolve/args.mjs +105 -1
  68. package/dist/core/resolve/coerce.d.mts +1 -1
  69. package/dist/core/resolve/coerce.mjs +336 -1
  70. package/dist/core/resolve/config.mjs +19 -1
  71. package/dist/core/resolve/contracts.d.mts +9 -4
  72. package/dist/core/resolve/errors.d.mts +0 -1
  73. package/dist/core/resolve/errors.mjs +140 -2
  74. package/dist/core/resolve/flags.d.mts +7 -2
  75. package/dist/core/resolve/flags.mjs +251 -1
  76. package/dist/core/resolve/index.d.mts +2 -2
  77. package/dist/core/resolve/index.mjs +85 -1
  78. package/dist/core/resolve/property.d.mts +6 -2
  79. package/dist/core/resolve/property.mjs +53 -1
  80. package/dist/core/schema/activity.d.mts +31 -11
  81. package/dist/core/schema/arg.d.mts +92 -13
  82. package/dist/core/schema/arg.mjs +463 -1
  83. package/dist/core/schema/command.d.mts +29 -7
  84. package/dist/core/schema/command.mjs +726 -1
  85. package/dist/core/schema/flag.d.mts +577 -21
  86. package/dist/core/schema/flag.mjs +705 -1
  87. package/dist/core/schema/index.d.mts +5 -2
  88. package/dist/core/schema/middleware.d.mts +4 -3
  89. package/dist/core/schema/middleware.mjs +41 -1
  90. package/dist/core/schema/number-constraints.d.mts +96 -0
  91. package/dist/core/schema/number-constraints.mjs +60 -0
  92. package/dist/core/schema/prompt.d.mts +21 -3
  93. package/dist/core/schema/run.d.mts +24 -5
  94. package/dist/core/schema/string-constraints.d.mts +97 -0
  95. package/dist/core/schema/string-constraints.mjs +69 -0
  96. package/dist/core/schema/value-parsers.d.mts +78 -0
  97. package/dist/core/schema/value-parsers.mjs +142 -0
  98. package/dist/core/schema-dsl/runtime.mjs +271 -2
  99. package/dist/core/schema-dsl/to-json-schema.d.mts +0 -1
  100. package/dist/core/schema-dsl/to-json-schema.mjs +74 -1
  101. package/dist/core/testkit/index.d.mts +9 -36
  102. package/dist/core/testkit/index.mjs +83 -1
  103. package/dist/index.d.mts +12 -6
  104. package/dist/index.mjs +22 -1
  105. package/dist/runtime/adapter.d.mts +38 -2
  106. package/dist/runtime/adapter.mjs +87 -1
  107. package/dist/runtime/auto.d.mts +2 -3
  108. package/dist/runtime/auto.mjs +45 -1
  109. package/dist/runtime/deno.d.mts +24 -5
  110. package/dist/runtime/deno.mjs +262 -2
  111. package/dist/runtime/detect.mjs +45 -1
  112. package/dist/runtime/index.d.mts +3 -4
  113. package/dist/runtime/node.d.mts +8 -2
  114. package/dist/runtime/node.mjs +220 -2
  115. package/dist/runtime/paths.mjs +48 -1
  116. package/dist/runtime.d.mts +4 -4
  117. package/dist/runtime.mjs +6 -1
  118. package/dist/strings.mjs +22 -1
  119. package/dist/testkit.d.mts +1 -0
  120. package/dist/testkit.mjs +5 -1
  121. package/dist/version.d.mts +7 -3
  122. package/dist/version.mjs +7 -1
  123. package/dreamcli.schema.json +36 -7
  124. package/examples/basic.ts +5 -1
  125. package/examples/gh/package.json +2 -7
  126. package/examples/pwsh-demo/package.json +1 -7
  127. package/examples/pwsh-demo/src/main.test.ts +1 -4
  128. package/examples/pwsh-demo/src/main.ts +14 -4
  129. package/examples/transport-launcher.ts +85 -0
  130. package/package.json +43 -49
  131. package/dist/runtime/bun.d.mts +0 -28
  132. package/dist/runtime/bun.mjs +0 -1
  133. package/dist/runtime/support.d.mts +0 -42
  134. package/dist/runtime/support.mjs +0 -1
  135. package/src/core/cli/dispatch.ts +0 -349
  136. package/src/core/cli/help-links.ts +0 -82
  137. package/src/core/cli/index.ts +0 -1413
  138. package/src/core/cli/planner.ts +0 -487
  139. package/src/core/cli/plugin.ts +0 -117
  140. package/src/core/cli/propagate.ts +0 -97
  141. package/src/core/cli/root-help.ts +0 -252
  142. package/src/core/cli/root-surface.ts +0 -74
  143. package/src/core/cli/runtime-preflight.ts +0 -438
  144. package/src/core/completion/index.ts +0 -88
  145. package/src/core/completion/shells/bash.ts +0 -459
  146. package/src/core/completion/shells/fish.ts +0 -259
  147. package/src/core/completion/shells/powershell.ts +0 -439
  148. package/src/core/completion/shells/shared.ts +0 -283
  149. package/src/core/completion/shells/zsh.ts +0 -381
  150. package/src/core/config/index.ts +0 -417
  151. package/src/core/config/package-json.ts +0 -560
  152. package/src/core/errors/index.ts +0 -193
  153. package/src/core/execution/index.ts +0 -268
  154. package/src/core/help/ansi.ts +0 -144
  155. package/src/core/help/index.ts +0 -516
  156. package/src/core/json-schema/index.ts +0 -891
  157. package/src/core/json-schema/meta-descriptions.generated.ts +0 -185
  158. package/src/core/output/activity.ts +0 -575
  159. package/src/core/output/bind.ts +0 -59
  160. package/src/core/output/contracts.ts +0 -194
  161. package/src/core/output/display-value.ts +0 -48
  162. package/src/core/output/index.ts +0 -704
  163. package/src/core/output/renderers.ts +0 -125
  164. package/src/core/output/writer.ts +0 -46
  165. package/src/core/parse/index.ts +0 -681
  166. package/src/core/prompt/index.ts +0 -583
  167. package/src/core/resolve/args.ts +0 -144
  168. package/src/core/resolve/coerce.ts +0 -432
  169. package/src/core/resolve/config.ts +0 -26
  170. package/src/core/resolve/contracts.ts +0 -135
  171. package/src/core/resolve/errors.ts +0 -227
  172. package/src/core/resolve/flags.ts +0 -255
  173. package/src/core/resolve/index.ts +0 -108
  174. package/src/core/resolve/property.ts +0 -99
  175. package/src/core/schema/activity.ts +0 -240
  176. package/src/core/schema/arg.ts +0 -719
  177. package/src/core/schema/command.ts +0 -1498
  178. package/src/core/schema/flag.ts +0 -801
  179. package/src/core/schema/index.ts +0 -91
  180. package/src/core/schema/middleware.ts +0 -171
  181. package/src/core/schema/prompt.ts +0 -156
  182. package/src/core/schema/run.ts +0 -198
  183. package/src/core/schema-dsl/index.ts +0 -109
  184. package/src/core/schema-dsl/parse.ts +0 -262
  185. package/src/core/schema-dsl/runtime.ts +0 -609
  186. package/src/core/schema-dsl/to-json-schema.ts +0 -102
  187. package/src/core/testkit/index.ts +0 -123
  188. package/src/index.ts +0 -179
  189. package/src/runtime/adapter.ts +0 -303
  190. package/src/runtime/auto.ts +0 -110
  191. package/src/runtime/bun.ts +0 -55
  192. package/src/runtime/deno.ts +0 -369
  193. package/src/runtime/detect.ts +0 -105
  194. package/src/runtime/index.ts +0 -21
  195. package/src/runtime/node-builtins.d.ts +0 -27
  196. package/src/runtime/node.ts +0 -300
  197. package/src/runtime/paths.ts +0 -64
  198. package/src/runtime/support.ts +0 -135
  199. package/src/runtime.ts +0 -31
  200. package/src/strings.ts +0 -34
  201. package/src/testkit.ts +0 -25
  202. package/src/version.ts +0 -20
@@ -1,283 +0,0 @@
1
- /**
2
- * Shared infrastructure for shell completion generators.
3
- *
4
- * Provides the command tree walker, shell escaping utilities, and
5
- * the version tag used in generated script headers. Consumed by
6
- * the per-shell generators in sibling files.
7
- *
8
- * @module dreamcli/core/completion/shells/shared
9
- * @internal
10
- */
11
-
12
- import { collectPropagatedFlags } from '#internals/core/cli/propagate.ts';
13
- import { resolveRootSurface } from '#internals/core/cli/root-surface.ts';
14
- import type { CommandSchema, FlagSchema } from '#internals/core/schema/index.ts';
15
- import { DREAMCLI_REVISION, DREAMCLI_VERSION } from '#internals/version.ts';
16
-
17
- // --- Version tag for generated script headers
18
-
19
- /**
20
- * Format a version tag for generated completion script headers.
21
- *
22
- * Produces e.g. `"@kjanat/dreamcli v0.9.1 (f9b5f1a)"` when built, or
23
- * `"@kjanat/dreamcli"` when running unbundled in development.
24
- *
25
- * @internal
26
- */
27
- function versionTag(): string {
28
- if (DREAMCLI_VERSION === 'dev') return '@kjanat/dreamcli';
29
- const rev = DREAMCLI_REVISION !== 'dev' ? ` (${DREAMCLI_REVISION})` : '';
30
- return `@kjanat/dreamcli v${DREAMCLI_VERSION}${rev}`;
31
- }
32
-
33
- // --- CompletionOptions — generator configuration
34
-
35
- /**
36
- * Options for completion script generation.
37
- *
38
- * Passed to individual shell generators alongside the CLI schema.
39
- *
40
- * These options affect the generated script text, not runtime completion
41
- * behavior after installation.
42
- */
43
- interface CompletionOptions {
44
- /**
45
- * Override the generated shell function name prefix.
46
- *
47
- * Defaults to the CLI name from the schema. This is mainly useful when
48
- * embedding multiple generated scripts in the same environment and you want
49
- * deterministic, collision-free helper names.
50
- *
51
- * @example
52
- * ```ts
53
- * generateCompletion(schema, 'bash', { functionPrefix: 'acme' });
54
- * ```
55
- */
56
- readonly functionPrefix?: string;
57
- /**
58
- * Controls which root-level surface shell completion exposes when a
59
- * default command exists.
60
- *
61
- * - `'subcommands'` keeps hybrid CLIs command-centric at the root while
62
- * still exposing default-command flags for a single visible default
63
- * command.
64
- * - `'surface'` exposes the default command's root-usable flags at the
65
- * root whenever a visible default command exists.
66
- *
67
- * @defaultValue `'subcommands'`
68
- */
69
- readonly rootMode?: 'subcommands' | 'surface';
70
- }
71
-
72
- // --- Root completion surface — shared policy resolver
73
-
74
- /**
75
- * Normalized root completion surface consumed by shell generators.
76
- *
77
- * @internal
78
- */
79
- interface RootCompletionSurface {
80
- readonly visibleCommands: readonly CommandSchema[];
81
- readonly visibleDefaultCommand: CommandSchema | undefined;
82
- readonly rootFlags: Readonly<Record<string, FlagSchema>>;
83
- readonly defaultFlags: Readonly<Record<string, FlagSchema>>;
84
- readonly includeDefaultFlags: boolean;
85
- }
86
-
87
- /**
88
- * Schema shape needed to compute the root completion surface.
89
- *
90
- * @internal
91
- */
92
- interface RootCompletionSchemaLike {
93
- readonly commands: ReadonlyArray<{
94
- readonly schema: CommandSchema;
95
- }>;
96
- readonly defaultCommand: { readonly schema: CommandSchema } | undefined;
97
- readonly version: string | undefined;
98
- }
99
-
100
- /**
101
- * Resolve the root-level completion surface from the CLI schema and policy.
102
- *
103
- * @internal
104
- */
105
- function resolveRootCompletionSurface(
106
- schema: RootCompletionSchemaLike,
107
- rootMode: CompletionOptions['rootMode'] = 'subcommands',
108
- ): RootCompletionSurface {
109
- const rootSurface = resolveRootSurface(schema);
110
- const rootFlags = createRootFlags(schema.version !== undefined);
111
- const defaultFlags = rootSurface.visibleDefaultCommand?.flags ?? {};
112
- const includeDefaultFlags =
113
- rootMode === 'surface'
114
- ? rootSurface.visibleDefaultCommand !== undefined
115
- : rootSurface.hasSingleVisibleDefault;
116
-
117
- return {
118
- visibleCommands: rootSurface.visibleCommands,
119
- visibleDefaultCommand: rootSurface.visibleDefaultCommand,
120
- rootFlags,
121
- defaultFlags,
122
- includeDefaultFlags,
123
- };
124
- }
125
-
126
- /**
127
- * Build the synthetic root-level flags (`--help`, optionally `--version`).
128
- *
129
- * @param hasVersion - Whether to include a `--version` flag.
130
- * @returns A record of root flag schemas.
131
- * @internal
132
- */
133
- function createRootFlags(hasVersion: boolean): Readonly<Record<string, FlagSchema>> {
134
- return {
135
- help: createSyntheticRootFlag('Show help text'),
136
- ...(hasVersion ? { version: createSyntheticRootFlag('Show version') } : {}),
137
- };
138
- }
139
-
140
- /**
141
- * Create a minimal boolean {@link FlagSchema} for a synthetic root flag.
142
- *
143
- * @param description - Help text for the flag.
144
- * @returns A complete flag schema with all optional fields defaulted.
145
- * @internal
146
- */
147
- function createSyntheticRootFlag(description: string): FlagSchema {
148
- return {
149
- kind: 'boolean',
150
- presence: 'optional',
151
- defaultValue: undefined,
152
- aliases: [],
153
- envVar: undefined,
154
- configPath: undefined,
155
- description,
156
- enumValues: undefined,
157
- elementSchema: undefined,
158
- prompt: undefined,
159
- parseFn: undefined,
160
- deprecated: undefined,
161
- propagate: false,
162
- };
163
- }
164
-
165
- // --- Command tree walking — shared infrastructure
166
-
167
- /**
168
- * A flattened node from the command tree, carrying its ancestry context.
169
- *
170
- * Used by both bash and zsh generators to produce completions at every
171
- * nesting level with correct propagated flag inheritance.
172
- *
173
- * @internal
174
- */
175
- interface CommandNode {
176
- /** Name path from root: `['db', 'migrate']` */
177
- readonly path: readonly string[];
178
- /** The command schema at this node */
179
- readonly schema: CommandSchema;
180
- /** Propagated flags inherited from ancestors (excludes own flags) */
181
- readonly propagatedFlags: Readonly<Record<string, FlagSchema>>;
182
- /** Merged flags: propagated + own (own shadows propagated) */
183
- readonly mergedFlags: Readonly<Record<string, FlagSchema>>;
184
- /** Visible child command schemas (for subcommand completion) */
185
- readonly children: readonly CommandSchema[];
186
- }
187
-
188
- /**
189
- * Walk the command tree depth-first, producing a flat list of
190
- * {@link CommandNode}s with propagated flag context.
191
- *
192
- * @param topLevel - Top-level visible command schemas.
193
- * @param ancestorSchemas - Schema path from root (for propagation calculation).
194
- * @returns Flat list of all visible nodes in the tree.
195
- *
196
- * @internal
197
- */
198
- function walkCommandTree(
199
- topLevel: readonly CommandSchema[],
200
- ancestorSchemas: readonly CommandSchema[] = [],
201
- ): readonly CommandNode[] {
202
- const nodes: CommandNode[] = [];
203
-
204
- for (const schema of topLevel) {
205
- if (schema.hidden) continue;
206
-
207
- const fullPath = [...ancestorSchemas, schema];
208
- const propagatedFlags = collectPropagatedFlags(fullPath);
209
- const mergedFlags: Record<string, FlagSchema> = { ...propagatedFlags, ...schema.flags };
210
- const children = schema.commands.filter((c) => !c.hidden);
211
-
212
- nodes.push({
213
- path: fullPath.map((s) => s.name),
214
- schema,
215
- propagatedFlags,
216
- mergedFlags,
217
- children,
218
- });
219
-
220
- // Recurse into visible children only (hidden subtrees skipped entirely)
221
- if (children.length > 0) {
222
- nodes.push(...walkCommandTree(children, fullPath));
223
- }
224
- }
225
-
226
- return nodes;
227
- }
228
-
229
- // --- Shell escaping utilities
230
-
231
- /**
232
- * Sanitize a string for use as a shell function identifier.
233
- * Replaces non-alphanumeric/underscore characters with underscores.
234
- * When sanitization changes the name, appends a short stable hash suffix so
235
- * distinct originals cannot collide on the same helper identifier.
236
- * Used by both bash and zsh generators.
237
- *
238
- * @internal
239
- */
240
- function sanitizeShellIdentifier(name: string): string {
241
- const sanitized = name.replace(/[^a-zA-Z0-9_]/g, '_');
242
- if (sanitized === name) {
243
- return sanitized;
244
- }
245
-
246
- let hash = 2166136261;
247
- for (let i = 0; i < name.length; i += 1) {
248
- hash ^= name.charCodeAt(i);
249
- hash = Math.imul(hash, 16777619);
250
- }
251
-
252
- return `${sanitized}_${(hash >>> 0).toString(16).padStart(8, '0')}`;
253
- }
254
-
255
- /**
256
- * Quote a string for safe interpolation into a shell script.
257
- *
258
- * Uses single-quote wrapping with the standard `'\''` idiom for
259
- * embedded single quotes. This prevents shell injection from CLI
260
- * names containing spaces, semicolons, backticks, or other
261
- * special characters.
262
- *
263
- * Returns the input unquoted if it consists only of shell-safe
264
- * characters (`[a-zA-Z0-9_\-.]`), avoiding unnecessary noise
265
- * in generated scripts for common CLI names like `my-cli` or `app.v2`.
266
- *
267
- * @internal
268
- */
269
- function quoteShellArg(value: string): string {
270
- if (/^[a-zA-Z0-9_\-.]+$/.test(value)) return value;
271
- return `'${value.replace(/'/g, "'\\''")}'`;
272
- }
273
-
274
- // --- Exports
275
-
276
- export type { CommandNode, CompletionOptions, RootCompletionSurface };
277
- export {
278
- quoteShellArg,
279
- resolveRootCompletionSurface,
280
- sanitizeShellIdentifier,
281
- versionTag,
282
- walkCommandTree,
283
- };
@@ -1,381 +0,0 @@
1
- /**
2
- * Zsh completion script generator.
3
- *
4
- * Produces a self-contained zsh script with:
5
- * - A `#compdef` directive for auto-loading
6
- * - A main `_<name>` function with subcommand dispatch
7
- * - Per-group helper functions (`_<name>_<cmd>`) with recursive dispatch
8
- * - `_arguments` calls for flags with descriptions (including propagated flags)
9
- * - `_describe` for subcommand lists at each nesting level
10
- * - Enum value completions via `->state` dispatch
11
- *
12
- * @module dreamcli/core/completion/shells/zsh
13
- * @internal
14
- */
15
-
16
- import type { CLISchema } from '#internals/core/cli/index.ts';
17
- import { CLIError } from '#internals/core/errors/index.ts';
18
- import { getFlagAliasNames } from '#internals/core/schema/flag.ts';
19
- import type { FlagSchema } from '#internals/core/schema/index.ts';
20
- import type { CommandNode, CompletionOptions } from './shared.ts';
21
- import {
22
- quoteShellArg,
23
- resolveRootCompletionSurface,
24
- sanitizeShellIdentifier,
25
- versionTag,
26
- walkCommandTree,
27
- } from './shared.ts';
28
-
29
- // --- Public generator
30
-
31
- /**
32
- * Generate a zsh completion script for the CLI.
33
- *
34
- * Use this when you want a zsh-specific script directly rather than routing
35
- * through {@link generateCompletion}. The generated script is compatible with
36
- * zsh's normal `#compdef` / `fpath` loading flow.
37
- *
38
- * @param schema - The CLI schema.
39
- * @param options - Optional generator configuration.
40
- * @returns A complete zsh completion script.
41
- *
42
- * @example
43
- * ```ts
44
- * const script = generateZshCompletion(app.schema);
45
- * // install with: mycli completions zsh > "${fpath[1]}/_mycli"
46
- * ```
47
- */
48
- function generateZshCompletion(schema: CLISchema, options?: CompletionOptions): string {
49
- const prefix = options?.functionPrefix ?? schema.name;
50
- const funcName = `_${sanitizeShellIdentifier(prefix)}`;
51
- const rootSurface = resolveRootCompletionSurface(schema, options?.rootMode);
52
- const visibleCommands = rootSurface.visibleCommands;
53
- const nodes = walkCommandTree(visibleCommands);
54
-
55
- const lines: string[] = [];
56
-
57
- lines.push(`#compdef ${quoteShellArg(schema.name)}`);
58
- lines.push(`# Zsh completion for ${schema.name}`);
59
- lines.push(`# Generated by ${versionTag()}`);
60
- lines.push('#');
61
- lines.push(`# Usage: source <(${schema.name} completions zsh)`);
62
- lines.push('#');
63
- lines.push('# Install permanently:');
64
- lines.push(`# ${schema.name} completions zsh > "\${fpath[1]}/_${schema.name}"`);
65
- lines.push('# # Then restart your shell');
66
- lines.push('');
67
-
68
- // --- Generate helper functions for group commands (bottom-up) ---
69
- // Process deepest nodes first so all helpers exist before they're called.
70
- const groupNodes = nodes.filter((n) => n.children.length > 0);
71
- const leafNodes = nodes.filter((n) => n.children.length === 0);
72
-
73
- // Emit leaf helper functions
74
- for (const node of leafNodes) {
75
- if (node.path.length < 2) continue; // Top-level leaves handled inline
76
- const helperName = `${funcName}_${node.path.map(sanitizeShellIdentifier).join('_')}`;
77
- emitZshLeafFunction(lines, helperName, node);
78
- }
79
-
80
- // Emit group helper functions (deepest first)
81
- const sortedGroups = [...groupNodes].sort((a, b) => b.path.length - a.path.length);
82
- for (const node of sortedGroups) {
83
- const helperName = `${funcName}_${node.path.map(sanitizeShellIdentifier).join('_')}`;
84
- emitZshGroupFunction(lines, helperName, funcName, node);
85
- }
86
-
87
- // --- Main function ---
88
- lines.push(`${funcName}() {`);
89
-
90
- if (visibleCommands.length > 0) {
91
- lines.push('\tlocal -a subcmds');
92
- lines.push('\tlocal line state');
93
- lines.push('');
94
-
95
- // --- Root-level: visible root surface ---
96
- const rootFlags = {
97
- ...rootSurface.rootFlags,
98
- ...(rootSurface.includeDefaultFlags ? rootSurface.defaultFlags : {}),
99
- };
100
- const rootFlagSpecs = buildZshFlagSpecsFromFlags(rootFlags);
101
-
102
- lines.push('\t_arguments -C \\');
103
- for (const spec of rootFlagSpecs) {
104
- lines.push(`\t\t${spec} \\`);
105
- }
106
- lines.push("\t\t'1: :->subcmd' \\");
107
- lines.push("\t\t'*::arg:->args'");
108
- lines.push('');
109
-
110
- // --- Subcommand list ---
111
- lines.push('\tcase "$state" in');
112
- lines.push('\t\tsubcmd)');
113
- lines.push('\t\t\tsubcmds=(');
114
- appendZshCommandCandidates(lines, visibleCommands, '\t\t\t\t');
115
- lines.push('\t\t\t)');
116
- lines.push("\t\t\t_describe 'command' subcmds");
117
- lines.push('\t\t\t;;');
118
-
119
- // --- Per-command arguments ---
120
- lines.push('\t\targs)');
121
- lines.push('\t\t\tcase "$line[1]" in');
122
- for (const cmd of visibleCommands) {
123
- const allNames = [cmd.name, ...cmd.aliases].map(escapeZshCasePatternValue);
124
- const childCommands = cmd.commands.filter((c) => !c.hidden);
125
- lines.push(`\t\t\t\t${allNames.join('|')})`);
126
-
127
- if (childCommands.length > 0) {
128
- // Group command — delegate to helper function
129
- const helperName = `${funcName}_${sanitizeShellIdentifier(cmd.name)}`;
130
- lines.push(`\t\t\t\t\t${helperName}`);
131
- } else {
132
- // Leaf command — emit flags inline
133
- const node = nodes.find((n) => n.path.length === 1 && n.schema.name === cmd.name);
134
- if (node === undefined) {
135
- throw new CLIError(`Missing completion node for command '${cmd.name}'`, {
136
- code: 'UNEXPECTED_ERROR',
137
- });
138
- }
139
- const flagSpecs = buildZshFlagSpecsFromFlags(node.mergedFlags);
140
-
141
- if (flagSpecs.length > 0) {
142
- lines.push('\t\t\t\t\t_arguments \\');
143
- for (let i = 0; i < flagSpecs.length; i++) {
144
- const trailing = i < flagSpecs.length - 1 ? ' \\' : '';
145
- lines.push(`\t\t\t\t\t\t${flagSpecs[i]}${trailing}`);
146
- }
147
- }
148
- }
149
- lines.push('\t\t\t\t\t;;');
150
- }
151
- lines.push('\t\t\tesac');
152
- lines.push('\t\t\t;;');
153
- lines.push('\tesac');
154
- } else {
155
- // --- No subcommands: just global flags ---
156
- const globalFlags = buildZshFlagSpecsFromFlags(rootSurface.rootFlags);
157
- lines.push('\t_arguments \\');
158
- for (let i = 0; i < globalFlags.length; i++) {
159
- const trailing = i < globalFlags.length - 1 ? ' \\' : '';
160
- lines.push(`\t\t${globalFlags[i]}${trailing}`);
161
- }
162
- }
163
-
164
- lines.push('}');
165
- lines.push('');
166
- // Register with compdef for `source <(cmd completions zsh)` usage.
167
- // fpath-based autoloading is handled by the `#compdef` directive above.
168
- lines.push(`compdef ${funcName} ${quoteShellArg(schema.name)}`);
169
- lines.push('');
170
-
171
- return lines.join('\n');
172
- }
173
-
174
- // --- Zsh helpers — internal
175
-
176
- /**
177
- * Emit a zsh helper function for a group command (has subcommands).
178
- *
179
- * Uses `_arguments -C` for its own flags plus subcommand dispatch.
180
- *
181
- * @internal
182
- */
183
- function emitZshGroupFunction(
184
- lines: string[],
185
- helperName: string,
186
- rootFuncName: string,
187
- node: CommandNode,
188
- ): void {
189
- lines.push(`${helperName}() {`);
190
- lines.push('\tlocal -a subcmds');
191
- lines.push('\tlocal line state');
192
- lines.push('');
193
-
194
- // Flags for this group (including propagated)
195
- const flagSpecs = buildZshFlagSpecsFromFlags(node.mergedFlags);
196
-
197
- lines.push('\t_arguments -C \\');
198
- for (const spec of flagSpecs) {
199
- lines.push(`\t\t${spec} \\`);
200
- }
201
- lines.push("\t\t'1: :->subcmd' \\");
202
- lines.push("\t\t'*::arg:->args'");
203
- lines.push('');
204
-
205
- lines.push('\tcase "$state" in');
206
- lines.push('\t\tsubcmd)');
207
- lines.push('\t\t\tsubcmds=(');
208
- appendZshCommandCandidates(lines, node.children, '\t\t\t\t');
209
- lines.push('\t\t\t)');
210
- lines.push("\t\t\t_describe 'command' subcmds");
211
- lines.push('\t\t\t;;');
212
-
213
- lines.push('\t\targs)');
214
- lines.push('\t\t\tcase "$line[1]" in');
215
- for (const child of node.children) {
216
- const allNames = [child.name, ...child.aliases].map(escapeZshCasePatternValue);
217
- const childPath = [...node.path, child.name];
218
- const childFuncName = `${rootFuncName}_${childPath.map(sanitizeShellIdentifier).join('_')}`;
219
- lines.push(`\t\t\t\t${allNames.join('|')})`);
220
- lines.push(`\t\t\t\t\t${childFuncName}`);
221
- lines.push('\t\t\t\t\t;;');
222
- }
223
- lines.push('\t\t\tesac');
224
- lines.push('\t\t\t;;');
225
- lines.push('\tesac');
226
-
227
- lines.push('}');
228
- lines.push('');
229
- }
230
-
231
- /**
232
- * Emit a zsh helper function for a leaf command (no subcommands).
233
- *
234
- * Uses plain `_arguments` with the command's own flags plus propagated flags.
235
- *
236
- * @internal
237
- */
238
- function emitZshLeafFunction(lines: string[], helperName: string, node: CommandNode): void {
239
- const flagSpecs = buildZshFlagSpecsFromFlags(node.mergedFlags);
240
-
241
- lines.push(`${helperName}() {`);
242
- if (flagSpecs.length > 0) {
243
- lines.push('\t_arguments \\');
244
- for (let i = 0; i < flagSpecs.length; i++) {
245
- const trailing = i < flagSpecs.length - 1 ? ' \\' : '';
246
- lines.push(`\t\t${flagSpecs[i]}${trailing}`);
247
- }
248
- }
249
- lines.push('}');
250
- lines.push('');
251
- }
252
-
253
- function appendZshCommandCandidates(
254
- lines: string[],
255
- commands: ReadonlyArray<{
256
- readonly name: string;
257
- readonly aliases: readonly string[];
258
- readonly description: string | undefined;
259
- }>,
260
- indent: string,
261
- ): void {
262
- for (const command of commands) {
263
- const description = command.description ?? command.name;
264
- for (const alias of [command.name, ...command.aliases]) {
265
- lines.push(`${indent}${quoteShellArg(`${alias}:${description}`)}`);
266
- }
267
- }
268
- }
269
-
270
- /**
271
- * Escape a value for use in a zsh `case` pattern.
272
- *
273
- * Escapes glob metacharacters so arbitrary command and alias names match
274
- * literally rather than being interpreted as shell patterns.
275
- *
276
- * @internal
277
- */
278
- function escapeZshCasePatternValue(value: string): string {
279
- if (/^[a-zA-Z0-9_\-.]+$/.test(value)) return value;
280
- return value
281
- .replace(/\\/g, '\\\\')
282
- .replace(/'/g, "\\'")
283
- .replace(/"/g, '\\"')
284
- .replace(/`/g, '\\`')
285
- .replace(/\|/g, '\\|')
286
- .replace(/\*/g, '\\*')
287
- .replace(/\?/g, '\\?')
288
- .replace(/\[/g, '\\[')
289
- .replace(/\]/g, '\\]')
290
- .replace(/\(/g, '\\(')
291
- .replace(/\)/g, '\\)')
292
- .replace(/\{/g, '\\{')
293
- .replace(/\}/g, '\\}')
294
- .replace(/\+/g, '\\+')
295
- .replace(/!/g, '\\!')
296
- .replace(/@/g, '\\@')
297
- .replace(/#/g, '\\#')
298
- .replace(/~/g, '\\~')
299
- .replace(/\s/g, (match) => (match === ' ' ? '\\ ' : `\\${match}`));
300
- }
301
-
302
- /**
303
- * Escape a description for use inside a zsh `_arguments` flag spec.
304
- *
305
- * `]` closes the description segment, so it must be escaped. Backslashes are
306
- * escaped as well so descriptions with literal escapes remain stable.
307
- *
308
- * @internal
309
- */
310
- function escapeZshDescription(value: string): string {
311
- return value.replace(/\\/g, '\\\\').replace(/\]/g, '\\]');
312
- }
313
-
314
- /**
315
- * Build `_arguments` flag spec strings from a merged flag record.
316
- *
317
- * Each flag produces one or more spec strings in zsh `_arguments` format:
318
- * - `'--name[description]'` for simple flags
319
- * - `'--name[description]:value:(v1 v2 v3)'` for enum flags
320
- * - `'(-s --name --alias)'{-s,--name,--alias}'[description]'` for flags with
321
- * visible aliases
322
- *
323
- * @internal
324
- */
325
- function buildZshFlagSpecsFromFlags(
326
- flags: Readonly<Record<string, FlagSchema>>,
327
- ): readonly string[] {
328
- const specs: string[] = [];
329
- for (const [name, schema] of Object.entries(flags)) {
330
- const desc = escapeZshDescription(schema.description ?? name);
331
- const longFlag = `--${name}`;
332
- const shortFlags = getFlagAliasNames(schema, { kind: 'short' }).map((alias) => `-${alias}`);
333
- const longAliases = getFlagAliasNames(schema, { kind: 'long' }).map((alias) => `--${alias}`);
334
- const allForms = [...shortFlags, longFlag, ...longAliases];
335
-
336
- let valuePart = '';
337
- if (schema.kind === 'boolean') {
338
- // Boolean flags take no argument value
339
- } else if (schema.kind === 'enum' && schema.enumValues !== undefined) {
340
- const escapedValues = schema.enumValues.map(escapeZshEnumValue);
341
- valuePart = `:value:(${escapedValues.join(' ')})`;
342
- } else {
343
- valuePart = ':value:';
344
- }
345
-
346
- if (allForms.length > 1) {
347
- // Mutual exclusion group with all visible forms for the same flag.
348
- // Format: '(-v --verbose --verb)'{-v,--verbose,--verb}'[desc]:value'
349
- const escapedForms = allForms.map(escapeZshCasePatternValue).join(',');
350
- specs.push(
351
- `${quoteShellArg(`(${allForms.join(' ')})`)}{${escapedForms}}${quoteShellArg(
352
- `[${desc}]${valuePart}`,
353
- )}`,
354
- );
355
- } else {
356
- specs.push(quoteShellArg(`${longFlag}[${desc}]${valuePart}`));
357
- }
358
- }
359
- return specs;
360
- }
361
-
362
- /**
363
- * Escape a single enum value for use inside a zsh `(v1 v2)` value list.
364
- *
365
- * Simple identifier-like values (matching `[a-zA-Z0-9_\-.]`) pass through
366
- * unescaped. Values containing spaces, quotes, backslashes, or parentheses
367
- * are escaped with backslash prefixes for each special character, which
368
- * is the standard mechanism within zsh parenthesized completion lists.
369
- *
370
- * @internal
371
- */
372
- function escapeZshEnumValue(value: string): string {
373
- if (/^[a-zA-Z0-9_\-.]+$/.test(value)) return value;
374
- return value
375
- .replace(/\\/g, '\\\\')
376
- .replace(/ /g, '\\ ')
377
- .replace(/\(/g, '\\(')
378
- .replace(/\)/g, '\\)');
379
- }
380
-
381
- export { generateZshCompletion };