@kjanat/dreamcli 0.0.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. package/CHANGELOG.md +667 -0
  2. package/LICENSE +22 -0
  3. package/README.md +370 -0
  4. package/dist/adapter-B37d9oia.mjs +1 -0
  5. package/dist/adapter-CCSh5juX.cjs +1 -0
  6. package/dist/adapter-DIwO-q7K.d.mts +3447 -0
  7. package/dist/adapter-DQnxxLiE.d.cts +3447 -0
  8. package/dist/auto-5cjZaF9V.mjs +3 -0
  9. package/dist/auto-B0eSgoDw.cjs +3 -0
  10. package/dist/index.cjs +10 -0
  11. package/dist/index.d.cts +920 -0
  12. package/dist/index.d.mts +920 -0
  13. package/dist/index.mjs +10 -0
  14. package/dist/runtime.cjs +1 -0
  15. package/dist/runtime.d.cts +253 -0
  16. package/dist/runtime.d.mts +253 -0
  17. package/dist/runtime.mjs +1 -0
  18. package/dist/testkit-CEDYPvhF.mjs +14 -0
  19. package/dist/testkit-ClIKijxC.cjs +14 -0
  20. package/dist/testkit.cjs +1 -0
  21. package/dist/testkit.d.cts +25 -0
  22. package/dist/testkit.d.mts +25 -0
  23. package/dist/testkit.mjs +1 -0
  24. package/examples/basic.ts +33 -0
  25. package/examples/gh/package.json +48 -0
  26. package/examples/gh/src/commands/auth.ts +66 -0
  27. package/examples/gh/src/commands/issue.ts +120 -0
  28. package/examples/gh/src/commands/pr.ts +125 -0
  29. package/examples/gh/src/data/issues.yaml +5 -0
  30. package/examples/gh/src/data/issues.yaml.d.ts +17 -0
  31. package/examples/gh/src/data/pull-requests.yaml +7 -0
  32. package/examples/gh/src/data/pull-requests.yaml.d.ts +18 -0
  33. package/examples/gh/src/lib/auth.ts +37 -0
  34. package/examples/gh/src/lib/utils.ts +17 -0
  35. package/examples/gh/src/main.test.ts +306 -0
  36. package/examples/gh/src/main.ts +38 -0
  37. package/examples/gh/tsconfig.json +37 -0
  38. package/examples/interactive.ts +66 -0
  39. package/examples/json-mode.ts +93 -0
  40. package/examples/middleware.ts +71 -0
  41. package/examples/multi-command.ts +66 -0
  42. package/examples/spinner-progress.ts +49 -0
  43. package/examples/testing.ts +145 -0
  44. package/examples/tsconfig.json +17 -0
  45. package/package.json +123 -2
  46. package/src/core/cli/AGENTS.md +72 -0
  47. package/src/core/cli/dispatch.ts +282 -0
  48. package/src/core/cli/index.ts +1425 -0
  49. package/src/core/cli/plugin.ts +111 -0
  50. package/src/core/cli/propagate.ts +97 -0
  51. package/src/core/cli/root-help.ts +269 -0
  52. package/src/core/cli/root-surface.ts +74 -0
  53. package/src/core/completion/AGENTS.md +72 -0
  54. package/src/core/completion/completion-test-helpers.ts +48 -0
  55. package/src/core/completion/index.ts +82 -0
  56. package/src/core/completion/shells/bash.ts +456 -0
  57. package/src/core/completion/shells/fish.ts +24 -0
  58. package/src/core/completion/shells/powershell.ts +24 -0
  59. package/src/core/completion/shells/shared.ts +283 -0
  60. package/src/core/completion/shells/zsh.ts +376 -0
  61. package/src/core/config/index.ts +404 -0
  62. package/src/core/config/package-json.ts +216 -0
  63. package/src/core/errors/index.ts +178 -0
  64. package/src/core/help/index.ts +559 -0
  65. package/src/core/json-schema/index.ts +705 -0
  66. package/src/core/output/AGENTS.md +69 -0
  67. package/src/core/output/activity.ts +568 -0
  68. package/src/core/output/display-value.ts +48 -0
  69. package/src/core/output/index.ts +704 -0
  70. package/src/core/output/writer.ts +46 -0
  71. package/src/core/parse/index.ts +643 -0
  72. package/src/core/prompt/index.ts +566 -0
  73. package/src/core/resolve/AGENTS.md +69 -0
  74. package/src/core/resolve/index.ts +1331 -0
  75. package/src/core/schema/AGENTS.md +61 -0
  76. package/src/core/schema/activity.ts +237 -0
  77. package/src/core/schema/arg.ts +707 -0
  78. package/src/core/schema/command.ts +1263 -0
  79. package/src/core/schema/flag.ts +651 -0
  80. package/src/core/schema/index.ts +82 -0
  81. package/src/core/schema/middleware.ts +171 -0
  82. package/src/core/schema/prompt.ts +148 -0
  83. package/src/core/schema/run.ts +187 -0
  84. package/src/core/testkit/AGENTS.md +55 -0
  85. package/src/core/testkit/index.ts +365 -0
  86. package/src/index.ts +164 -0
  87. package/src/runtime/AGENTS.md +74 -0
  88. package/src/runtime/adapter.ts +300 -0
  89. package/src/runtime/auto.ts +110 -0
  90. package/src/runtime/bun.ts +55 -0
  91. package/src/runtime/deno.ts +355 -0
  92. package/src/runtime/detect.ts +102 -0
  93. package/src/runtime/index.ts +21 -0
  94. package/src/runtime/node-builtins.d.ts +23 -0
  95. package/src/runtime/node.ts +278 -0
  96. package/src/runtime/paths.ts +56 -0
  97. package/src/runtime/support.ts +119 -0
  98. package/src/runtime/test-helpers.ts +40 -0
  99. package/src/runtime.ts +31 -0
  100. package/src/testkit.ts +23 -0
  101. package/src/version.ts +20 -0
@@ -0,0 +1,283 @@
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. `"dreamcli v0.9.1 (f9b5f1a)"` when built, or
23
+ * `"dreamcli"` when running unbundled in development.
24
+ *
25
+ * @internal
26
+ */
27
+ function versionTag(): string {
28
+ if (DREAMCLI_VERSION === 'dev') return 'dreamcli';
29
+ const rev = DREAMCLI_REVISION !== 'dev' ? ` (${DREAMCLI_REVISION})` : '';
30
+ return `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
+ };
@@ -0,0 +1,376 @@
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 type { FlagSchema } from '#internals/core/schema/index.ts';
19
+ import type { CommandNode, CompletionOptions } from './shared.ts';
20
+ import {
21
+ quoteShellArg,
22
+ resolveRootCompletionSurface,
23
+ sanitizeShellIdentifier,
24
+ versionTag,
25
+ walkCommandTree,
26
+ } from './shared.ts';
27
+
28
+ // --- Public generator
29
+
30
+ /**
31
+ * Generate a zsh completion script for the CLI.
32
+ *
33
+ * Use this when you want a zsh-specific script directly rather than routing
34
+ * through {@link generateCompletion}. The generated script is compatible with
35
+ * zsh's normal `#compdef` / `fpath` loading flow.
36
+ *
37
+ * @param schema - The CLI schema.
38
+ * @param options - Optional generator configuration.
39
+ * @returns A complete zsh completion script.
40
+ *
41
+ * @example
42
+ * ```ts
43
+ * const script = generateZshCompletion(app.schema);
44
+ * // install with: mycli completions zsh > "${fpath[1]}/_mycli"
45
+ * ```
46
+ */
47
+ function generateZshCompletion(schema: CLISchema, options?: CompletionOptions): string {
48
+ const prefix = options?.functionPrefix ?? schema.name;
49
+ const funcName = `_${sanitizeShellIdentifier(prefix)}`;
50
+ const rootSurface = resolveRootCompletionSurface(schema, options?.rootMode);
51
+ const visibleCommands = rootSurface.visibleCommands;
52
+ const nodes = walkCommandTree(visibleCommands);
53
+
54
+ const lines: string[] = [];
55
+
56
+ lines.push(`#compdef ${quoteShellArg(schema.name)}`);
57
+ lines.push(`# Zsh completion for ${schema.name}`);
58
+ lines.push(`# Generated by ${versionTag()}`);
59
+ lines.push('#');
60
+ lines.push(`# Usage: source <(${schema.name} completions zsh)`);
61
+ lines.push('#');
62
+ lines.push('# Install permanently:');
63
+ lines.push(`# ${schema.name} completions zsh > "\${fpath[1]}/_${schema.name}"`);
64
+ lines.push('# # Then restart your shell');
65
+ lines.push('');
66
+
67
+ // --- Generate helper functions for group commands (bottom-up) ---
68
+ // Process deepest nodes first so all helpers exist before they're called.
69
+ const groupNodes = nodes.filter((n) => n.children.length > 0);
70
+ const leafNodes = nodes.filter((n) => n.children.length === 0);
71
+
72
+ // Emit leaf helper functions
73
+ for (const node of leafNodes) {
74
+ if (node.path.length < 2) continue; // Top-level leaves handled inline
75
+ const helperName = `${funcName}_${node.path.map(sanitizeShellIdentifier).join('_')}`;
76
+ emitZshLeafFunction(lines, helperName, node);
77
+ }
78
+
79
+ // Emit group helper functions (deepest first)
80
+ const sortedGroups = [...groupNodes].sort((a, b) => b.path.length - a.path.length);
81
+ for (const node of sortedGroups) {
82
+ const helperName = `${funcName}_${node.path.map(sanitizeShellIdentifier).join('_')}`;
83
+ emitZshGroupFunction(lines, helperName, funcName, node);
84
+ }
85
+
86
+ // --- Main function ---
87
+ lines.push(`${funcName}() {`);
88
+
89
+ if (visibleCommands.length > 0) {
90
+ lines.push('\tlocal -a subcmds');
91
+ lines.push('\tlocal line state');
92
+ lines.push('');
93
+
94
+ // --- Root-level: visible root surface ---
95
+ const rootFlags = {
96
+ ...rootSurface.rootFlags,
97
+ ...(rootSurface.includeDefaultFlags ? rootSurface.defaultFlags : {}),
98
+ };
99
+ const rootFlagSpecs = buildZshFlagSpecsFromFlags(rootFlags);
100
+
101
+ lines.push('\t_arguments -C \\');
102
+ for (const spec of rootFlagSpecs) {
103
+ lines.push(`\t\t${spec} \\`);
104
+ }
105
+ lines.push("\t\t'1: :->subcmd' \\");
106
+ lines.push("\t\t'*::arg:->args'");
107
+ lines.push('');
108
+
109
+ // --- Subcommand list ---
110
+ lines.push('\tcase "$state" in');
111
+ lines.push('\t\tsubcmd)');
112
+ lines.push('\t\t\tsubcmds=(');
113
+ appendZshCommandCandidates(lines, visibleCommands, '\t\t\t\t');
114
+ lines.push('\t\t\t)');
115
+ lines.push("\t\t\t_describe 'command' subcmds");
116
+ lines.push('\t\t\t;;');
117
+
118
+ // --- Per-command arguments ---
119
+ lines.push('\t\targs)');
120
+ lines.push('\t\t\tcase "$line[1]" in');
121
+ for (const cmd of visibleCommands) {
122
+ const allNames = [cmd.name, ...cmd.aliases].map(escapeZshCasePatternValue);
123
+ const childCommands = cmd.commands.filter((c) => !c.hidden);
124
+ lines.push(`\t\t\t\t${allNames.join('|')})`);
125
+
126
+ if (childCommands.length > 0) {
127
+ // Group command — delegate to helper function
128
+ const helperName = `${funcName}_${sanitizeShellIdentifier(cmd.name)}`;
129
+ lines.push(`\t\t\t\t\t${helperName}`);
130
+ } else {
131
+ // Leaf command — emit flags inline
132
+ const node = nodes.find((n) => n.path.length === 1 && n.schema.name === cmd.name);
133
+ if (node === undefined) {
134
+ throw new CLIError(`Missing completion node for command '${cmd.name}'`, {
135
+ code: 'UNEXPECTED_ERROR',
136
+ });
137
+ }
138
+ const flagSpecs = buildZshFlagSpecsFromFlags(node.mergedFlags);
139
+
140
+ if (flagSpecs.length > 0) {
141
+ lines.push('\t\t\t\t\t_arguments \\');
142
+ for (let i = 0; i < flagSpecs.length; i++) {
143
+ const trailing = i < flagSpecs.length - 1 ? ' \\' : '';
144
+ lines.push(`\t\t\t\t\t\t${flagSpecs[i]}${trailing}`);
145
+ }
146
+ }
147
+ }
148
+ lines.push('\t\t\t\t\t;;');
149
+ }
150
+ lines.push('\t\t\tesac');
151
+ lines.push('\t\t\t;;');
152
+ lines.push('\tesac');
153
+ } else {
154
+ // --- No subcommands: just global flags ---
155
+ const globalFlags = buildZshFlagSpecsFromFlags(rootSurface.rootFlags);
156
+ lines.push('\t_arguments \\');
157
+ for (let i = 0; i < globalFlags.length; i++) {
158
+ const trailing = i < globalFlags.length - 1 ? ' \\' : '';
159
+ lines.push(`\t\t${globalFlags[i]}${trailing}`);
160
+ }
161
+ }
162
+
163
+ lines.push('}');
164
+ lines.push('');
165
+ lines.push(`${funcName} "$@"`);
166
+ lines.push('');
167
+
168
+ return lines.join('\n');
169
+ }
170
+
171
+ // --- Zsh helpers — internal
172
+
173
+ /**
174
+ * Emit a zsh helper function for a group command (has subcommands).
175
+ *
176
+ * Uses `_arguments -C` for its own flags plus subcommand dispatch.
177
+ *
178
+ * @internal
179
+ */
180
+ function emitZshGroupFunction(
181
+ lines: string[],
182
+ helperName: string,
183
+ rootFuncName: string,
184
+ node: CommandNode,
185
+ ): void {
186
+ lines.push(`${helperName}() {`);
187
+ lines.push('\tlocal -a subcmds');
188
+ lines.push('\tlocal line state');
189
+ lines.push('');
190
+
191
+ // Flags for this group (including propagated)
192
+ const flagSpecs = buildZshFlagSpecsFromFlags(node.mergedFlags);
193
+
194
+ lines.push('\t_arguments -C \\');
195
+ for (const spec of flagSpecs) {
196
+ lines.push(`\t\t${spec} \\`);
197
+ }
198
+ lines.push("\t\t'1: :->subcmd' \\");
199
+ lines.push("\t\t'*::arg:->args'");
200
+ lines.push('');
201
+
202
+ lines.push('\tcase "$state" in');
203
+ lines.push('\t\tsubcmd)');
204
+ lines.push('\t\t\tsubcmds=(');
205
+ appendZshCommandCandidates(lines, node.children, '\t\t\t\t');
206
+ lines.push('\t\t\t)');
207
+ lines.push("\t\t\t_describe 'command' subcmds");
208
+ lines.push('\t\t\t;;');
209
+
210
+ lines.push('\t\targs)');
211
+ lines.push('\t\t\tcase "$line[1]" in');
212
+ for (const child of node.children) {
213
+ const allNames = [child.name, ...child.aliases].map(escapeZshCasePatternValue);
214
+ const childPath = [...node.path, child.name];
215
+ const childFuncName = `${rootFuncName}_${childPath.map(sanitizeShellIdentifier).join('_')}`;
216
+ lines.push(`\t\t\t\t${allNames.join('|')})`);
217
+ lines.push(`\t\t\t\t\t${childFuncName}`);
218
+ lines.push('\t\t\t\t\t;;');
219
+ }
220
+ lines.push('\t\t\tesac');
221
+ lines.push('\t\t\t;;');
222
+ lines.push('\tesac');
223
+
224
+ lines.push('}');
225
+ lines.push('');
226
+ }
227
+
228
+ /**
229
+ * Emit a zsh helper function for a leaf command (no subcommands).
230
+ *
231
+ * Uses plain `_arguments` with the command's own flags plus propagated flags.
232
+ *
233
+ * @internal
234
+ */
235
+ function emitZshLeafFunction(lines: string[], helperName: string, node: CommandNode): void {
236
+ const flagSpecs = buildZshFlagSpecsFromFlags(node.mergedFlags);
237
+
238
+ lines.push(`${helperName}() {`);
239
+ if (flagSpecs.length > 0) {
240
+ lines.push('\t_arguments \\');
241
+ for (let i = 0; i < flagSpecs.length; i++) {
242
+ const trailing = i < flagSpecs.length - 1 ? ' \\' : '';
243
+ lines.push(`\t\t${flagSpecs[i]}${trailing}`);
244
+ }
245
+ }
246
+ lines.push('}');
247
+ lines.push('');
248
+ }
249
+
250
+ function appendZshCommandCandidates(
251
+ lines: string[],
252
+ commands: ReadonlyArray<{
253
+ readonly name: string;
254
+ readonly aliases: readonly string[];
255
+ readonly description: string | undefined;
256
+ }>,
257
+ indent: string,
258
+ ): void {
259
+ for (const command of commands) {
260
+ const description = command.description ?? command.name;
261
+ for (const alias of [command.name, ...command.aliases]) {
262
+ lines.push(`${indent}${quoteShellArg(`${alias}:${description}`)}`);
263
+ }
264
+ }
265
+ }
266
+
267
+ /**
268
+ * Escape a value for use in a zsh `case` pattern.
269
+ *
270
+ * Escapes glob metacharacters so arbitrary command and alias names match
271
+ * literally rather than being interpreted as shell patterns.
272
+ *
273
+ * @internal
274
+ */
275
+ function escapeZshCasePatternValue(value: string): string {
276
+ if (/^[a-zA-Z0-9_\-.]+$/.test(value)) return value;
277
+ return value
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(/\]/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(/\s/g, (match) => (match === ' ' ? '\\ ' : `\\${match}`));
297
+ }
298
+
299
+ /**
300
+ * Escape a description for use inside a zsh `_arguments` flag spec.
301
+ *
302
+ * `]` closes the description segment, so it must be escaped. Backslashes are
303
+ * escaped as well so descriptions with literal escapes remain stable.
304
+ *
305
+ * @internal
306
+ */
307
+ function escapeZshDescription(value: string): string {
308
+ return value.replace(/\\/g, '\\\\').replace(/\]/g, '\\]');
309
+ }
310
+
311
+ /**
312
+ * Build `_arguments` flag spec strings from a merged flag record.
313
+ *
314
+ * Each flag produces one or more spec strings in zsh `_arguments` format:
315
+ * - `'--name[description]'` for simple flags
316
+ * - `'--name[description]:value:(v1 v2 v3)'` for enum flags
317
+ * - `'(-s --name)'{-s,--name}'[description]'` for flags with short aliases
318
+ *
319
+ * @internal
320
+ */
321
+ function buildZshFlagSpecsFromFlags(
322
+ flags: Readonly<Record<string, FlagSchema>>,
323
+ ): readonly string[] {
324
+ const specs: string[] = [];
325
+ for (const [name, schema] of Object.entries(flags)) {
326
+ const desc = escapeZshDescription(schema.description ?? name);
327
+ const longFlag = `--${name}`;
328
+ const shortFlags = schema.aliases.filter((a) => a.length === 1).map((a) => `-${a}`);
329
+
330
+ let valuePart = '';
331
+ if (schema.kind === 'boolean') {
332
+ // Boolean flags take no argument value
333
+ } else if (schema.kind === 'enum' && schema.enumValues !== undefined) {
334
+ const escapedValues = schema.enumValues.map(escapeZshEnumValue);
335
+ valuePart = `:value:(${escapedValues.join(' ')})`;
336
+ } else {
337
+ valuePart = ':value:';
338
+ }
339
+
340
+ if (shortFlags.length > 0) {
341
+ // Mutual exclusion group with ALL short aliases + long flag
342
+ // Format: '(-v -V --verbose)'{-v,-V,--verbose}'[desc]:value'
343
+ const allForms = [...shortFlags, longFlag];
344
+ const escapedForms = allForms.map(escapeZshCasePatternValue).join(',');
345
+ specs.push(
346
+ `${quoteShellArg(`(${allForms.join(' ')})`)}{${escapedForms}}${quoteShellArg(
347
+ `[${desc}]${valuePart}`,
348
+ )}`,
349
+ );
350
+ } else {
351
+ specs.push(quoteShellArg(`${longFlag}[${desc}]${valuePart}`));
352
+ }
353
+ }
354
+ return specs;
355
+ }
356
+
357
+ /**
358
+ * Escape a single enum value for use inside a zsh `(v1 v2)` value list.
359
+ *
360
+ * Simple identifier-like values (matching `[a-zA-Z0-9_\-.]`) pass through
361
+ * unescaped. Values containing spaces, quotes, backslashes, or parentheses
362
+ * are escaped with backslash prefixes for each special character, which
363
+ * is the standard mechanism within zsh parenthesized completion lists.
364
+ *
365
+ * @internal
366
+ */
367
+ function escapeZshEnumValue(value: string): string {
368
+ if (/^[a-zA-Z0-9_\-.]+$/.test(value)) return value;
369
+ return value
370
+ .replace(/\\/g, '\\\\')
371
+ .replace(/ /g, '\\ ')
372
+ .replace(/\(/g, '\\(')
373
+ .replace(/\)/g, '\\)');
374
+ }
375
+
376
+ export { generateZshCompletion };