politty 0.0.1 → 0.1.1

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 (56) hide show
  1. package/README.md +297 -28
  2. package/dist/arg-registry-ClI2WGgH.d.cts +89 -0
  3. package/dist/arg-registry-ClI2WGgH.d.cts.map +1 -0
  4. package/dist/arg-registry-D4NsqcNZ.d.ts +89 -0
  5. package/dist/arg-registry-D4NsqcNZ.d.ts.map +1 -0
  6. package/dist/augment.cjs +0 -0
  7. package/dist/augment.d.cts +17 -0
  8. package/dist/augment.d.cts.map +1 -0
  9. package/dist/augment.d.ts +17 -0
  10. package/dist/augment.d.ts.map +1 -0
  11. package/dist/augment.js +1 -0
  12. package/dist/command-Bgd-yIwv.cjs +25 -0
  13. package/dist/command-Bgd-yIwv.cjs.map +1 -0
  14. package/dist/command-CvKyk4ag.js +20 -0
  15. package/dist/command-CvKyk4ag.js.map +1 -0
  16. package/dist/completion/index.cjs +595 -0
  17. package/dist/completion/index.cjs.map +1 -0
  18. package/dist/completion/index.d.cts +153 -0
  19. package/dist/completion/index.d.cts.map +1 -0
  20. package/dist/completion/index.d.ts +153 -0
  21. package/dist/completion/index.d.ts.map +1 -0
  22. package/dist/completion/index.js +588 -0
  23. package/dist/completion/index.js.map +1 -0
  24. package/dist/docs/index.cjs +1239 -0
  25. package/dist/docs/index.cjs.map +1 -0
  26. package/dist/docs/index.d.cts +500 -0
  27. package/dist/docs/index.d.cts.map +1 -0
  28. package/dist/docs/index.d.ts +500 -0
  29. package/dist/docs/index.d.ts.map +1 -0
  30. package/dist/docs/index.js +1182 -0
  31. package/dist/docs/index.js.map +1 -0
  32. package/dist/index.cjs +29 -0
  33. package/dist/index.d.cts +478 -0
  34. package/dist/index.d.cts.map +1 -0
  35. package/dist/index.d.ts +478 -0
  36. package/dist/index.d.ts.map +1 -0
  37. package/dist/index.js +5 -0
  38. package/dist/runner-BZuYiRhi.cjs +1492 -0
  39. package/dist/runner-BZuYiRhi.cjs.map +1 -0
  40. package/dist/runner-D2BXiWtg.cjs +4 -0
  41. package/dist/runner-DceWXOwD.js +1372 -0
  42. package/dist/runner-DceWXOwD.js.map +1 -0
  43. package/dist/runner-KCql2UKz.js +4 -0
  44. package/dist/schema-extractor-B9D3Rf22.cjs +354 -0
  45. package/dist/schema-extractor-B9D3Rf22.cjs.map +1 -0
  46. package/dist/schema-extractor-D-Eo7I77.d.cts +303 -0
  47. package/dist/schema-extractor-D-Eo7I77.d.cts.map +1 -0
  48. package/dist/schema-extractor-Dk5Z0Iei.js +324 -0
  49. package/dist/schema-extractor-Dk5Z0Iei.js.map +1 -0
  50. package/dist/schema-extractor-kkajLb9E.d.ts +303 -0
  51. package/dist/schema-extractor-kkajLb9E.d.ts.map +1 -0
  52. package/dist/subcommand-router-BiSvDXHg.js +153 -0
  53. package/dist/subcommand-router-BiSvDXHg.js.map +1 -0
  54. package/dist/subcommand-router-Vf-0w9P4.cjs +189 -0
  55. package/dist/subcommand-router-Vf-0w9P4.cjs.map +1 -0
  56. package/package.json +108 -6
@@ -0,0 +1,588 @@
1
+ import { a as arg, t as extractFields } from "../schema-extractor-Dk5Z0Iei.js";
2
+ import { t as defineCommand } from "../command-CvKyk4ag.js";
3
+ import { z } from "zod";
4
+
5
+ //#region src/completion/extractor.ts
6
+ /**
7
+ * Extract completion data from commands
8
+ */
9
+ /**
10
+ * Convert a resolved field to a completable option
11
+ */
12
+ function fieldToOption(field) {
13
+ return {
14
+ name: field.name,
15
+ cliName: field.cliName,
16
+ alias: field.alias,
17
+ description: field.description,
18
+ takesValue: field.type !== "boolean",
19
+ valueType: field.type,
20
+ required: field.required
21
+ };
22
+ }
23
+ /**
24
+ * Extract options from a command's args schema
25
+ */
26
+ function extractOptions(command) {
27
+ if (!command.args) return [];
28
+ return extractFields(command.args).fields.filter((field) => !field.positional).map(fieldToOption);
29
+ }
30
+ /**
31
+ * Extract positional arguments from a command
32
+ */
33
+ function extractPositionals(command) {
34
+ if (!command.args) return [];
35
+ return extractFields(command.args).fields.filter((field) => field.positional);
36
+ }
37
+ /**
38
+ * Extract a completable subcommand from a command
39
+ */
40
+ function extractSubcommand(name, command) {
41
+ const subcommands = [];
42
+ if (command.subCommands) for (const [subName, subCommand] of Object.entries(command.subCommands)) if (typeof subCommand === "function") subcommands.push({
43
+ name: subName,
44
+ description: "(lazy loaded)",
45
+ subcommands: [],
46
+ options: []
47
+ });
48
+ else subcommands.push(extractSubcommand(subName, subCommand));
49
+ return {
50
+ name,
51
+ description: command.description,
52
+ subcommands,
53
+ options: extractOptions(command)
54
+ };
55
+ }
56
+ /**
57
+ * Extract completion data from a command tree
58
+ */
59
+ function extractCompletionData(command, programName) {
60
+ const rootSubcommand = extractSubcommand(programName, command);
61
+ return {
62
+ command: rootSubcommand,
63
+ programName,
64
+ globalOptions: rootSubcommand.options
65
+ };
66
+ }
67
+
68
+ //#endregion
69
+ //#region src/completion/bash.ts
70
+ /**
71
+ * Generate option completions for bash
72
+ */
73
+ function generateOptionCompletions$1(options) {
74
+ const completions = [];
75
+ for (const opt of options) {
76
+ completions.push(`--${opt.cliName}`);
77
+ if (opt.alias) completions.push(`-${opt.alias}`);
78
+ }
79
+ return completions;
80
+ }
81
+ /**
82
+ * Generate subcommand completions for bash
83
+ */
84
+ function generateSubcommandCompletions$1(subcommands) {
85
+ return subcommands.map((sub) => sub.name);
86
+ }
87
+ /**
88
+ * Generate the bash completion script
89
+ */
90
+ function generateBashScript(command, programName, includeDescriptions) {
91
+ const allOptions = collectAllOptions(command);
92
+ const optionList = generateOptionCompletions$1(allOptions).join(" ");
93
+ const subcommandList = generateSubcommandCompletions$1(command.subcommands).join(" ");
94
+ const subcommandCases = buildSubcommandCases(command.subcommands, includeDescriptions);
95
+ return `# Bash completion for ${programName}
96
+ # Generated by politty
97
+
98
+ _${programName}_completions() {
99
+ local cur prev words cword
100
+ _init_completion || return
101
+
102
+ local commands="${subcommandList}"
103
+ local global_opts="${optionList}"
104
+
105
+ # Handle subcommand-specific completions
106
+ local cmd_index=1
107
+ local cmd=""
108
+
109
+ # Find the subcommand
110
+ for ((i=1; i < cword; i++)); do
111
+ case "\${words[i]}" in
112
+ -*)
113
+ # Skip options and their values
114
+ if [[ "\${words[i]}" == *=* ]]; then
115
+ continue
116
+ fi
117
+ # Check if next word is the option's value
118
+ local opt="\${words[i]}"
119
+ case "$opt" in
120
+ ${allOptions.filter((o) => o.takesValue).map((o) => `--${o.cliName}|-${o.alias || ""}`).join("|") || "--*"}
121
+ ((i++))
122
+ ;;
123
+ esac
124
+ ;;
125
+ *)
126
+ # Found a subcommand
127
+ cmd="\${words[i]}"
128
+ cmd_index=$i
129
+ break
130
+ ;;
131
+ esac
132
+ done
133
+
134
+ # Subcommand-specific completions
135
+ case "$cmd" in
136
+ ${subcommandCases}
137
+ *)
138
+ # Root level completions
139
+ if [[ "$cur" == -* ]]; then
140
+ COMPREPLY=($(compgen -W "$global_opts" -- "$cur"))
141
+ else
142
+ COMPREPLY=($(compgen -W "$commands" -- "$cur"))
143
+ fi
144
+ ;;
145
+ esac
146
+
147
+ return 0
148
+ }
149
+
150
+ # Register the completion function
151
+ complete -F _${programName}_completions ${programName}
152
+ `;
153
+ }
154
+ /**
155
+ * Build case statements for subcommand-specific completions
156
+ */
157
+ function buildSubcommandCases(subcommands, includeDescriptions) {
158
+ if (subcommands.length === 0) return "";
159
+ let cases = "";
160
+ for (const sub of subcommands) {
161
+ const completions = [generateOptionCompletions$1(sub.options).join(" "), generateSubcommandCompletions$1(sub.subcommands).join(" ")].filter(Boolean).join(" ");
162
+ cases += ` ${sub.name})\n`;
163
+ cases += ` COMPREPLY=($(compgen -W "${completions}" -- "$cur"))\n`;
164
+ cases += ` ;;\n`;
165
+ if (sub.subcommands.length > 0) {
166
+ const nestedCases = buildSubcommandCases(sub.subcommands, includeDescriptions);
167
+ if (nestedCases) cases += nestedCases;
168
+ }
169
+ }
170
+ return cases;
171
+ }
172
+ /**
173
+ * Collect all options from a command tree
174
+ */
175
+ function collectAllOptions(command) {
176
+ const options = [...command.options];
177
+ for (const sub of command.subcommands) options.push(...collectAllOptions(sub));
178
+ const seen = /* @__PURE__ */ new Set();
179
+ return options.filter((opt) => {
180
+ if (seen.has(opt.name)) return false;
181
+ seen.add(opt.name);
182
+ return true;
183
+ });
184
+ }
185
+ /**
186
+ * Generate bash completion script for a command
187
+ */
188
+ function generateBashCompletion(command, options) {
189
+ const data = extractCompletionData(command, options.programName);
190
+ const includeDescriptions = options.includeDescriptions ?? true;
191
+ return {
192
+ script: generateBashScript(data.command, options.programName, includeDescriptions),
193
+ shell: "bash",
194
+ installInstructions: `# To enable completions, add the following to your ~/.bashrc:
195
+
196
+ # Option 1: Source directly
197
+ eval "$(${options.programName} completion bash)"
198
+
199
+ # Option 2: Save to a file
200
+ ${options.programName} completion bash > ~/.local/share/bash-completion/completions/${options.programName}
201
+
202
+ # Then reload your shell or run:
203
+ source ~/.bashrc`
204
+ };
205
+ }
206
+
207
+ //#endregion
208
+ //#region src/completion/fish.ts
209
+ /**
210
+ * Escape a string for use in fish completion descriptions
211
+ */
212
+ function escapeForFish(str) {
213
+ return str.replace(/'/g, "\\'").replace(/"/g, "\\\"");
214
+ }
215
+ /**
216
+ * Generate completion entries for options
217
+ */
218
+ function generateOptionCompletions(options, programName, condition, includeDescriptions) {
219
+ const completions = [];
220
+ for (const opt of options) {
221
+ let cmd = `complete -c ${programName}`;
222
+ if (condition) cmd += ` -n '${condition}'`;
223
+ cmd += ` -l ${opt.cliName}`;
224
+ if (opt.alias) cmd += ` -s ${opt.alias}`;
225
+ if (opt.takesValue) cmd += " -r";
226
+ else cmd += " -f";
227
+ if (includeDescriptions && opt.description) cmd += ` -d '${escapeForFish(opt.description)}'`;
228
+ completions.push(cmd);
229
+ }
230
+ return completions;
231
+ }
232
+ /**
233
+ * Generate completion entries for subcommands
234
+ */
235
+ function generateSubcommandCompletions(subcommands, programName, condition, includeDescriptions) {
236
+ const completions = [];
237
+ for (const sub of subcommands) {
238
+ let cmd = `complete -c ${programName}`;
239
+ if (condition) cmd += ` -n '${condition}'`;
240
+ cmd += ` -f -a ${sub.name}`;
241
+ if (includeDescriptions && sub.description) cmd += ` -d '${escapeForFish(sub.description)}'`;
242
+ completions.push(cmd);
243
+ }
244
+ return completions;
245
+ }
246
+ /**
247
+ * Generate helper functions for fish
248
+ */
249
+ function generateHelperFunctions(programName) {
250
+ return `# Helper function to check if using subcommand
251
+ function __fish_use_subcommand_${programName}
252
+ set -l cmd (commandline -opc)
253
+ if test (count $cmd) -eq 1
254
+ return 0
255
+ end
256
+ return 1
257
+ end
258
+
259
+ # Helper function to check current subcommand
260
+ function __fish_${programName}_using_command
261
+ set -l cmd (commandline -opc)
262
+ if contains -- $argv[1] $cmd
263
+ return 0
264
+ end
265
+ return 1
266
+ end
267
+ `;
268
+ }
269
+ /**
270
+ * Recursively generate completions for a command and its subcommands
271
+ */
272
+ function generateCommandCompletions(command, programName, includeDescriptions, parentCommands = []) {
273
+ const completions = [];
274
+ const optionCondition = parentCommands.length === 0 ? "" : `__fish_${programName}_using_command ${parentCommands[parentCommands.length - 1]}`;
275
+ const subcommandCondition = parentCommands.length === 0 ? `__fish_use_subcommand_${programName}` : `__fish_${programName}_using_command ${parentCommands[parentCommands.length - 1]}`;
276
+ completions.push(...generateOptionCompletions(command.options, programName, optionCondition, includeDescriptions));
277
+ if (command.subcommands.length > 0) {
278
+ completions.push(...generateSubcommandCompletions(command.subcommands, programName, subcommandCondition, includeDescriptions));
279
+ for (const sub of command.subcommands) completions.push(...generateCommandCompletions(sub, programName, includeDescriptions, [...parentCommands, sub.name]));
280
+ }
281
+ return completions;
282
+ }
283
+ /**
284
+ * Generate the fish completion script
285
+ */
286
+ function generateFishScript(command, programName, includeDescriptions) {
287
+ const helpers = generateHelperFunctions(programName);
288
+ const completions = generateCommandCompletions(command, programName, includeDescriptions);
289
+ return `# Fish completion for ${programName}
290
+ # Generated by politty
291
+
292
+ ${helpers}
293
+
294
+ # Clear existing completions
295
+ complete -e -c ${programName}
296
+
297
+ # Built-in options
298
+ ${[`complete -c ${programName} -l help -s h -d 'Show help information'`, `complete -c ${programName} -l version -d 'Show version information'`].join("\n")}
299
+
300
+ # Command-specific completions
301
+ ${completions.join("\n")}
302
+ `;
303
+ }
304
+ /**
305
+ * Generate fish completion script for a command
306
+ */
307
+ function generateFishCompletion(command, options) {
308
+ const data = extractCompletionData(command, options.programName);
309
+ const includeDescriptions = options.includeDescriptions ?? true;
310
+ return {
311
+ script: generateFishScript(data.command, options.programName, includeDescriptions),
312
+ shell: "fish",
313
+ installInstructions: `# To enable completions, run one of the following:
314
+
315
+ # Option 1: Source directly
316
+ ${options.programName} completion fish | source
317
+
318
+ # Option 2: Save to the fish completions directory
319
+ ${options.programName} completion fish > ~/.config/fish/completions/${options.programName}.fish
320
+
321
+ # The completion will be available immediately in new shell sessions.
322
+ # To use in the current session, run:
323
+ source ~/.config/fish/completions/${options.programName}.fish`
324
+ };
325
+ }
326
+
327
+ //#endregion
328
+ //#region src/completion/zsh.ts
329
+ /**
330
+ * Escape a string for use in zsh completion descriptions
331
+ */
332
+ function escapeForZsh(str) {
333
+ return str.replace(/'/g, "''").replace(/\[/g, "\\[").replace(/\]/g, "\\]");
334
+ }
335
+ /**
336
+ * Generate option specs for zsh _arguments
337
+ */
338
+ function generateOptionSpecs(options, includeDescriptions) {
339
+ const specs = [];
340
+ for (const opt of options) {
341
+ const desc = includeDescriptions && opt.description ? escapeForZsh(opt.description) : "";
342
+ const valueSpec = opt.takesValue ? ":" : "";
343
+ if (desc) specs.push(`'--${opt.cliName}[${desc}]${valueSpec}'`);
344
+ else specs.push(`'--${opt.cliName}${valueSpec}'`);
345
+ if (opt.alias) if (desc) specs.push(`'-${opt.alias}[${desc}]${valueSpec}'`);
346
+ else specs.push(`'-${opt.alias}${valueSpec}'`);
347
+ }
348
+ return specs;
349
+ }
350
+ /**
351
+ * Generate subcommand descriptions for zsh
352
+ */
353
+ function generateSubcommandDescriptions(subcommands, includeDescriptions) {
354
+ if (subcommands.length === 0) return "";
355
+ return subcommands.map((sub) => {
356
+ const desc = includeDescriptions && sub.description ? escapeForZsh(sub.description) : sub.name;
357
+ return `'${sub.name}:${desc}'`;
358
+ }).join("\n ");
359
+ }
360
+ /**
361
+ * Generate a zsh function for a subcommand
362
+ */
363
+ function generateSubcommandFunction(command, programName, includeDescriptions, parentPath = []) {
364
+ const currentPath = [...parentPath, command.name];
365
+ const funcName = parentPath.length === 0 ? `_${programName}` : `_${programName}_${currentPath.slice(1).join("_")}`;
366
+ const optionSpecs = generateOptionSpecs(command.options, includeDescriptions);
367
+ const hasSubcommands = command.subcommands.length > 0;
368
+ let func = `${funcName}() {\n`;
369
+ func += ` local -a args\n`;
370
+ if (hasSubcommands) {
371
+ const subcommandDesc = generateSubcommandDescriptions(command.subcommands, includeDescriptions);
372
+ func += ` local -a subcommands\n`;
373
+ func += ` subcommands=(\n`;
374
+ func += ` ${subcommandDesc}\n`;
375
+ func += ` )\n\n`;
376
+ }
377
+ func += ` args=(\n`;
378
+ if (hasSubcommands) {
379
+ func += ` '1:command:->command'\n`;
380
+ func += ` '*::arg:->args'\n`;
381
+ }
382
+ for (const spec of optionSpecs) func += ` ${spec}\n`;
383
+ func += ` )\n\n`;
384
+ func += ` _arguments -s -S $args\n\n`;
385
+ if (hasSubcommands) {
386
+ func += ` case "$state" in\n`;
387
+ func += ` command)\n`;
388
+ func += ` _describe -t commands 'command' subcommands\n`;
389
+ func += ` ;;\n`;
390
+ func += ` args)\n`;
391
+ func += ` case $words[1] in\n`;
392
+ for (const sub of command.subcommands) {
393
+ const subFuncName = `_${programName}_${[...currentPath.slice(1), sub.name].join("_")}`;
394
+ func += ` ${sub.name})\n`;
395
+ func += ` ${subFuncName}\n`;
396
+ func += ` ;;\n`;
397
+ }
398
+ func += ` esac\n`;
399
+ func += ` ;;\n`;
400
+ func += ` esac\n`;
401
+ }
402
+ func += `}\n`;
403
+ return func;
404
+ }
405
+ /**
406
+ * Collect all subcommand functions recursively
407
+ */
408
+ function collectSubcommandFunctions(command, programName, includeDescriptions, parentPath = []) {
409
+ const functions = [];
410
+ functions.push(generateSubcommandFunction(command, programName, includeDescriptions, parentPath));
411
+ const currentPath = parentPath.length === 0 ? [command.name] : [...parentPath, command.name];
412
+ for (const sub of command.subcommands) functions.push(...collectSubcommandFunctions(sub, programName, includeDescriptions, currentPath));
413
+ return functions;
414
+ }
415
+ /**
416
+ * Generate the zsh completion script
417
+ */
418
+ function generateZshScript(command, programName, includeDescriptions) {
419
+ return `#compdef ${programName}
420
+
421
+ # Zsh completion for ${programName}
422
+ # Generated by politty
423
+
424
+ ${collectSubcommandFunctions(command, programName, includeDescriptions).join("\n")}
425
+
426
+ _${programName} "$@"
427
+ `;
428
+ }
429
+ /**
430
+ * Generate zsh completion script for a command
431
+ */
432
+ function generateZshCompletion(command, options) {
433
+ const data = extractCompletionData(command, options.programName);
434
+ const includeDescriptions = options.includeDescriptions ?? true;
435
+ return {
436
+ script: generateZshScript(data.command, options.programName, includeDescriptions),
437
+ shell: "zsh",
438
+ installInstructions: `# To enable completions, add the following to your ~/.zshrc:
439
+
440
+ # Option 1: Source directly (add before compinit)
441
+ eval "$(${options.programName} completion zsh)"
442
+
443
+ # Option 2: Save to a file in your fpath
444
+ ${options.programName} completion zsh > ~/.zsh/completions/_${options.programName}
445
+
446
+ # Make sure your fpath includes the completions directory:
447
+ # fpath=(~/.zsh/completions $fpath)
448
+ # autoload -Uz compinit && compinit
449
+
450
+ # Then reload your shell or run:
451
+ source ~/.zshrc`
452
+ };
453
+ }
454
+
455
+ //#endregion
456
+ //#region src/completion/index.ts
457
+ /**
458
+ * Shell completion generation module
459
+ *
460
+ * Provides utilities to generate shell completion scripts for bash, zsh, and fish.
461
+ *
462
+ * @example
463
+ * ```typescript
464
+ * import { generateCompletion, createCompletionCommand } from "politty/completion";
465
+ *
466
+ * // Generate completion script directly
467
+ * const result = generateCompletion(myCommand, {
468
+ * shell: "bash",
469
+ * programName: "mycli"
470
+ * });
471
+ * console.log(result.script);
472
+ *
473
+ * // Or add a completion subcommand to your CLI
474
+ * const mainCommand = defineCommand({
475
+ * name: "mycli",
476
+ * subCommands: {
477
+ * completion: createCompletionCommand(myCommand, "mycli")
478
+ * }
479
+ * });
480
+ * ```
481
+ */
482
+ /**
483
+ * Generate completion script for the specified shell
484
+ */
485
+ function generateCompletion(command, options) {
486
+ switch (options.shell) {
487
+ case "bash": return generateBashCompletion(command, options);
488
+ case "zsh": return generateZshCompletion(command, options);
489
+ case "fish": return generateFishCompletion(command, options);
490
+ default: throw new Error(`Unsupported shell: ${options.shell}`);
491
+ }
492
+ }
493
+ /**
494
+ * Get the list of supported shells
495
+ */
496
+ function getSupportedShells() {
497
+ return [
498
+ "bash",
499
+ "zsh",
500
+ "fish"
501
+ ];
502
+ }
503
+ /**
504
+ * Detect the current shell from environment
505
+ */
506
+ function detectShell() {
507
+ const shellName = (process.env.SHELL || "").split("/").pop()?.toLowerCase() || "";
508
+ if (shellName.includes("bash")) return "bash";
509
+ if (shellName.includes("zsh")) return "zsh";
510
+ if (shellName.includes("fish")) return "fish";
511
+ return null;
512
+ }
513
+ /**
514
+ * Schema for the completion command arguments
515
+ */
516
+ const completionArgsSchema = z.object({
517
+ shell: arg(z.enum([
518
+ "bash",
519
+ "zsh",
520
+ "fish"
521
+ ]).optional().describe("Shell type (auto-detected if not specified)"), {
522
+ positional: true,
523
+ description: "Shell type (bash, zsh, or fish)",
524
+ placeholder: "SHELL"
525
+ }),
526
+ instructions: arg(z.boolean().default(false), {
527
+ alias: "i",
528
+ description: "Show installation instructions"
529
+ })
530
+ });
531
+ /**
532
+ * Create a completion subcommand for your CLI
533
+ *
534
+ * This creates a ready-to-use subcommand that generates completion scripts.
535
+ *
536
+ * @example
537
+ * ```typescript
538
+ * const mainCommand = defineCommand({
539
+ * name: "mycli",
540
+ * subCommands: {
541
+ * completion: createCompletionCommand(mainCommand, "mycli")
542
+ * }
543
+ * });
544
+ * ```
545
+ */
546
+ function createCompletionCommand(rootCommand, programName) {
547
+ return defineCommand({
548
+ name: "completion",
549
+ description: "Generate shell completion script",
550
+ args: completionArgsSchema,
551
+ run(args) {
552
+ const shellType = args.shell || detectShell();
553
+ if (!shellType) {
554
+ console.error("Could not detect shell type. Please specify one of: bash, zsh, fish");
555
+ process.exitCode = 1;
556
+ return;
557
+ }
558
+ const result = generateCompletion(rootCommand, {
559
+ shell: shellType,
560
+ programName,
561
+ includeDescriptions: true
562
+ });
563
+ if (args.instructions) console.log(result.installInstructions);
564
+ else console.log(result.script);
565
+ }
566
+ });
567
+ }
568
+ /**
569
+ * Helper to add completion command to an existing command's subCommands
570
+ *
571
+ * @example
572
+ * ```typescript
573
+ * const command = defineCommand({
574
+ * name: "mycli",
575
+ * subCommands: {
576
+ * ...withCompletionCommand(command, "mycli"),
577
+ * // other subcommands
578
+ * }
579
+ * });
580
+ * ```
581
+ */
582
+ function withCompletionCommand(rootCommand, programName) {
583
+ return { completion: createCompletionCommand(rootCommand, programName) };
584
+ }
585
+
586
+ //#endregion
587
+ export { createCompletionCommand, detectShell, extractCompletionData, extractPositionals, generateCompletion, getSupportedShells, withCompletionCommand };
588
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["subcommands: CompletableSubcommand[]","generateOptionCompletions","completions: string[]","generateSubcommandCompletions","completions: string[]","specs: string[]","functions: string[]"],"sources":["../../src/completion/extractor.ts","../../src/completion/bash.ts","../../src/completion/fish.ts","../../src/completion/zsh.ts","../../src/completion/index.ts"],"sourcesContent":["/**\n * Extract completion data from commands\n */\n\nimport { extractFields, type ResolvedFieldMeta } from \"../core/schema-extractor.js\";\nimport type { AnyCommand } from \"../types.js\";\nimport type { CompletableOption, CompletableSubcommand, CompletionData } from \"./types.js\";\n\n/**\n * Convert a resolved field to a completable option\n */\nfunction fieldToOption(field: ResolvedFieldMeta): CompletableOption {\n return {\n name: field.name,\n cliName: field.cliName,\n alias: field.alias,\n description: field.description,\n // Booleans are flags that don't require a value\n takesValue: field.type !== \"boolean\",\n valueType: field.type,\n required: field.required,\n };\n}\n\n/**\n * Extract options from a command's args schema\n */\nfunction extractOptions(command: AnyCommand): CompletableOption[] {\n if (!command.args) {\n return [];\n }\n\n const extracted = extractFields(command.args);\n return extracted.fields\n .filter((field) => !field.positional) // Only include flags/options, not positionals\n .map(fieldToOption);\n}\n\n/**\n * Extract positional arguments from a command\n */\nexport function extractPositionals(command: AnyCommand): ResolvedFieldMeta[] {\n if (!command.args) {\n return [];\n }\n\n const extracted = extractFields(command.args);\n return extracted.fields.filter((field) => field.positional);\n}\n\n/**\n * Extract a completable subcommand from a command\n */\nfunction extractSubcommand(name: string, command: AnyCommand): CompletableSubcommand {\n const subcommands: CompletableSubcommand[] = [];\n\n // Extract subcommands recursively (only sync subcommands for now)\n if (command.subCommands) {\n for (const [subName, subCommand] of Object.entries(command.subCommands)) {\n // Skip async subcommands as we can't inspect them statically\n if (typeof subCommand === \"function\") {\n // For async subcommands, add a placeholder\n subcommands.push({\n name: subName,\n description: \"(lazy loaded)\",\n subcommands: [],\n options: [],\n });\n } else {\n subcommands.push(extractSubcommand(subName, subCommand));\n }\n }\n }\n\n return {\n name,\n description: command.description,\n subcommands,\n options: extractOptions(command),\n };\n}\n\n/**\n * Extract completion data from a command tree\n */\nexport function extractCompletionData(command: AnyCommand, programName: string): CompletionData {\n const rootSubcommand = extractSubcommand(programName, command);\n\n return {\n command: rootSubcommand,\n programName,\n // Global options are the options defined on the root command\n globalOptions: rootSubcommand.options,\n };\n}\n","/**\n * Bash completion script generator\n */\n\nimport type { AnyCommand } from \"../types.js\";\nimport { extractCompletionData } from \"./extractor.js\";\nimport type {\n CompletableOption,\n CompletableSubcommand,\n CompletionOptions,\n CompletionResult,\n} from \"./types.js\";\n\n/**\n * Generate option completions for bash\n */\nfunction generateOptionCompletions(options: CompletableOption[]): string[] {\n const completions: string[] = [];\n\n for (const opt of options) {\n completions.push(`--${opt.cliName}`);\n if (opt.alias) {\n completions.push(`-${opt.alias}`);\n }\n }\n\n return completions;\n}\n\n/**\n * Generate subcommand completions for bash\n */\nfunction generateSubcommandCompletions(subcommands: CompletableSubcommand[]): string[] {\n return subcommands.map((sub) => sub.name);\n}\n\n/**\n * Generate the bash completion script\n */\nfunction generateBashScript(\n command: CompletableSubcommand,\n programName: string,\n includeDescriptions: boolean,\n): string {\n const allOptions = collectAllOptions(command);\n\n const optionList = generateOptionCompletions(allOptions).join(\" \");\n const subcommandList = generateSubcommandCompletions(command.subcommands).join(\" \");\n\n // Build subcommand-specific completions\n const subcommandCases = buildSubcommandCases(command.subcommands, includeDescriptions);\n\n return `# Bash completion for ${programName}\n# Generated by politty\n\n_${programName}_completions() {\n local cur prev words cword\n _init_completion || return\n\n local commands=\"${subcommandList}\"\n local global_opts=\"${optionList}\"\n\n # Handle subcommand-specific completions\n local cmd_index=1\n local cmd=\"\"\n\n # Find the subcommand\n for ((i=1; i < cword; i++)); do\n case \"\\${words[i]}\" in\n -*)\n # Skip options and their values\n if [[ \"\\${words[i]}\" == *=* ]]; then\n continue\n fi\n # Check if next word is the option's value\n local opt=\"\\${words[i]}\"\n case \"$opt\" in\n ${\n allOptions\n .filter((o) => o.takesValue)\n .map((o) => `--${o.cliName}|-${o.alias || \"\"}`)\n .join(\"|\") || \"--*\"\n }\n ((i++))\n ;;\n esac\n ;;\n *)\n # Found a subcommand\n cmd=\"\\${words[i]}\"\n cmd_index=$i\n break\n ;;\n esac\n done\n\n # Subcommand-specific completions\n case \"$cmd\" in\n${subcommandCases}\n *)\n # Root level completions\n if [[ \"$cur\" == -* ]]; then\n COMPREPLY=($(compgen -W \"$global_opts\" -- \"$cur\"))\n else\n COMPREPLY=($(compgen -W \"$commands\" -- \"$cur\"))\n fi\n ;;\n esac\n\n return 0\n}\n\n# Register the completion function\ncomplete -F _${programName}_completions ${programName}\n`;\n}\n\n/**\n * Build case statements for subcommand-specific completions\n */\nfunction buildSubcommandCases(\n subcommands: CompletableSubcommand[],\n includeDescriptions: boolean,\n): string {\n if (subcommands.length === 0) {\n return \"\";\n }\n\n let cases = \"\";\n\n for (const sub of subcommands) {\n const options = generateOptionCompletions(sub.options).join(\" \");\n const nestedSubcommands = generateSubcommandCompletions(sub.subcommands).join(\" \");\n const completions = [options, nestedSubcommands].filter(Boolean).join(\" \");\n\n cases += ` ${sub.name})\\n`;\n cases += ` COMPREPLY=($(compgen -W \"${completions}\" -- \"$cur\"))\\n`;\n cases += ` ;;\\n`;\n\n // Add nested subcommand cases if any\n if (sub.subcommands.length > 0) {\n const nestedCases = buildSubcommandCases(sub.subcommands, includeDescriptions);\n if (nestedCases) {\n cases += nestedCases;\n }\n }\n }\n\n return cases;\n}\n\n/**\n * Collect all options from a command tree\n */\nfunction collectAllOptions(command: CompletableSubcommand): CompletableOption[] {\n const options = [...command.options];\n\n for (const sub of command.subcommands) {\n options.push(...collectAllOptions(sub));\n }\n\n // Deduplicate by name\n const seen = new Set<string>();\n return options.filter((opt) => {\n if (seen.has(opt.name)) {\n return false;\n }\n seen.add(opt.name);\n return true;\n });\n}\n\n/**\n * Generate bash completion script for a command\n */\nexport function generateBashCompletion(\n command: AnyCommand,\n options: CompletionOptions,\n): CompletionResult {\n const data = extractCompletionData(command, options.programName);\n const includeDescriptions = options.includeDescriptions ?? true;\n\n const script = generateBashScript(data.command, options.programName, includeDescriptions);\n\n return {\n script,\n shell: \"bash\",\n installInstructions: `# To enable completions, add the following to your ~/.bashrc:\n\n# Option 1: Source directly\neval \"$(${options.programName} completion bash)\"\n\n# Option 2: Save to a file\n${options.programName} completion bash > ~/.local/share/bash-completion/completions/${options.programName}\n\n# Then reload your shell or run:\nsource ~/.bashrc`,\n };\n}\n","/**\n * Fish completion script generator\n */\n\nimport type { AnyCommand } from \"../types.js\";\nimport { extractCompletionData } from \"./extractor.js\";\nimport type {\n CompletableOption,\n CompletableSubcommand,\n CompletionOptions,\n CompletionResult,\n} from \"./types.js\";\n\n/**\n * Escape a string for use in fish completion descriptions\n */\nfunction escapeForFish(str: string): string {\n return str.replace(/'/g, \"\\\\'\").replace(/\"/g, '\\\\\"');\n}\n\n/**\n * Generate completion entries for options\n */\nfunction generateOptionCompletions(\n options: CompletableOption[],\n programName: string,\n condition: string,\n includeDescriptions: boolean,\n): string[] {\n const completions: string[] = [];\n\n for (const opt of options) {\n let cmd = `complete -c ${programName}`;\n\n // Add condition if specified\n if (condition) {\n cmd += ` -n '${condition}'`;\n }\n\n // Add long option\n cmd += ` -l ${opt.cliName}`;\n\n // Add short option if exists\n if (opt.alias) {\n cmd += ` -s ${opt.alias}`;\n }\n\n // Add flag for options that take values\n if (opt.takesValue) {\n cmd += \" -r\"; // Require argument\n } else {\n cmd += \" -f\"; // No argument (flag)\n }\n\n // Add description\n if (includeDescriptions && opt.description) {\n cmd += ` -d '${escapeForFish(opt.description)}'`;\n }\n\n completions.push(cmd);\n }\n\n return completions;\n}\n\n/**\n * Generate completion entries for subcommands\n */\nfunction generateSubcommandCompletions(\n subcommands: CompletableSubcommand[],\n programName: string,\n condition: string,\n includeDescriptions: boolean,\n): string[] {\n const completions: string[] = [];\n\n for (const sub of subcommands) {\n let cmd = `complete -c ${programName}`;\n\n // Add condition\n if (condition) {\n cmd += ` -n '${condition}'`;\n }\n\n // Subcommands are exclusive (no prefix)\n cmd += ` -f -a ${sub.name}`;\n\n // Add description\n if (includeDescriptions && sub.description) {\n cmd += ` -d '${escapeForFish(sub.description)}'`;\n }\n\n completions.push(cmd);\n }\n\n return completions;\n}\n\n/**\n * Generate helper functions for fish\n */\nfunction generateHelperFunctions(programName: string): string {\n return `# Helper function to check if using subcommand\nfunction __fish_use_subcommand_${programName}\n set -l cmd (commandline -opc)\n if test (count $cmd) -eq 1\n return 0\n end\n return 1\nend\n\n# Helper function to check current subcommand\nfunction __fish_${programName}_using_command\n set -l cmd (commandline -opc)\n if contains -- $argv[1] $cmd\n return 0\n end\n return 1\nend\n`;\n}\n\n/**\n * Recursively generate completions for a command and its subcommands\n */\nfunction generateCommandCompletions(\n command: CompletableSubcommand,\n programName: string,\n includeDescriptions: boolean,\n parentCommands: string[] = [],\n): string[] {\n const completions: string[] = [];\n\n // Build condition for this level\n const optionCondition =\n parentCommands.length === 0\n ? \"\"\n : `__fish_${programName}_using_command ${parentCommands[parentCommands.length - 1]}`;\n\n const subcommandCondition =\n parentCommands.length === 0\n ? `__fish_use_subcommand_${programName}`\n : `__fish_${programName}_using_command ${parentCommands[parentCommands.length - 1]}`;\n\n // Add option completions\n completions.push(\n ...generateOptionCompletions(\n command.options,\n programName,\n optionCondition,\n includeDescriptions,\n ),\n );\n\n // Add subcommand completions\n if (command.subcommands.length > 0) {\n completions.push(\n ...generateSubcommandCompletions(\n command.subcommands,\n programName,\n subcommandCondition,\n includeDescriptions,\n ),\n );\n\n // Recursively add completions for subcommands\n for (const sub of command.subcommands) {\n completions.push(\n ...generateCommandCompletions(sub, programName, includeDescriptions, [\n ...parentCommands,\n sub.name,\n ]),\n );\n }\n }\n\n return completions;\n}\n\n/**\n * Generate the fish completion script\n */\nfunction generateFishScript(\n command: CompletableSubcommand,\n programName: string,\n includeDescriptions: boolean,\n): string {\n const helpers = generateHelperFunctions(programName);\n const completions = generateCommandCompletions(command, programName, includeDescriptions);\n\n // Add built-in options (help and version)\n const builtinCompletions = [\n `complete -c ${programName} -l help -s h -d 'Show help information'`,\n `complete -c ${programName} -l version -d 'Show version information'`,\n ];\n\n return `# Fish completion for ${programName}\n# Generated by politty\n\n${helpers}\n\n# Clear existing completions\ncomplete -e -c ${programName}\n\n# Built-in options\n${builtinCompletions.join(\"\\n\")}\n\n# Command-specific completions\n${completions.join(\"\\n\")}\n`;\n}\n\n/**\n * Generate fish completion script for a command\n */\nexport function generateFishCompletion(\n command: AnyCommand,\n options: CompletionOptions,\n): CompletionResult {\n const data = extractCompletionData(command, options.programName);\n const includeDescriptions = options.includeDescriptions ?? true;\n\n const script = generateFishScript(data.command, options.programName, includeDescriptions);\n\n return {\n script,\n shell: \"fish\",\n installInstructions: `# To enable completions, run one of the following:\n\n# Option 1: Source directly\n${options.programName} completion fish | source\n\n# Option 2: Save to the fish completions directory\n${options.programName} completion fish > ~/.config/fish/completions/${options.programName}.fish\n\n# The completion will be available immediately in new shell sessions.\n# To use in the current session, run:\nsource ~/.config/fish/completions/${options.programName}.fish`,\n };\n}\n","/**\n * Zsh completion script generator\n */\n\nimport type { AnyCommand } from \"../types.js\";\nimport { extractCompletionData } from \"./extractor.js\";\nimport type {\n CompletableOption,\n CompletableSubcommand,\n CompletionOptions,\n CompletionResult,\n} from \"./types.js\";\n\n/**\n * Escape a string for use in zsh completion descriptions\n */\nfunction escapeForZsh(str: string): string {\n return str.replace(/'/g, \"''\").replace(/\\[/g, \"\\\\[\").replace(/\\]/g, \"\\\\]\");\n}\n\n/**\n * Generate option specs for zsh _arguments\n */\nfunction generateOptionSpecs(options: CompletableOption[], includeDescriptions: boolean): string[] {\n const specs: string[] = [];\n\n for (const opt of options) {\n const desc = includeDescriptions && opt.description ? escapeForZsh(opt.description) : \"\";\n const valueSpec = opt.takesValue ? \":\" : \"\";\n\n // Long option\n if (desc) {\n specs.push(`'--${opt.cliName}[${desc}]${valueSpec}'`);\n } else {\n specs.push(`'--${opt.cliName}${valueSpec}'`);\n }\n\n // Short option (alias)\n if (opt.alias) {\n if (desc) {\n specs.push(`'-${opt.alias}[${desc}]${valueSpec}'`);\n } else {\n specs.push(`'-${opt.alias}${valueSpec}'`);\n }\n }\n }\n\n return specs;\n}\n\n/**\n * Generate subcommand descriptions for zsh\n */\nfunction generateSubcommandDescriptions(\n subcommands: CompletableSubcommand[],\n includeDescriptions: boolean,\n): string {\n if (subcommands.length === 0) {\n return \"\";\n }\n\n const lines = subcommands.map((sub) => {\n const desc = includeDescriptions && sub.description ? escapeForZsh(sub.description) : sub.name;\n return `'${sub.name}:${desc}'`;\n });\n\n return lines.join(\"\\n \");\n}\n\n/**\n * Generate a zsh function for a subcommand\n */\nfunction generateSubcommandFunction(\n command: CompletableSubcommand,\n programName: string,\n includeDescriptions: boolean,\n parentPath: string[] = [],\n): string {\n const currentPath = [...parentPath, command.name];\n const funcName =\n parentPath.length === 0\n ? `_${programName}`\n : `_${programName}_${currentPath.slice(1).join(\"_\")}`;\n\n const optionSpecs = generateOptionSpecs(command.options, includeDescriptions);\n const hasSubcommands = command.subcommands.length > 0;\n\n let func = `${funcName}() {\\n`;\n func += ` local -a args\\n`;\n\n if (hasSubcommands) {\n const subcommandDesc = generateSubcommandDescriptions(command.subcommands, includeDescriptions);\n func += ` local -a subcommands\\n`;\n func += ` subcommands=(\\n`;\n func += ` ${subcommandDesc}\\n`;\n func += ` )\\n\\n`;\n }\n\n func += ` args=(\\n`;\n\n if (hasSubcommands) {\n func += ` '1:command:->command'\\n`;\n func += ` '*::arg:->args'\\n`;\n }\n\n for (const spec of optionSpecs) {\n func += ` ${spec}\\n`;\n }\n\n func += ` )\\n\\n`;\n\n func += ` _arguments -s -S $args\\n\\n`;\n\n if (hasSubcommands) {\n func += ` case \"$state\" in\\n`;\n func += ` command)\\n`;\n func += ` _describe -t commands 'command' subcommands\\n`;\n func += ` ;;\\n`;\n func += ` args)\\n`;\n func += ` case $words[1] in\\n`;\n\n for (const sub of command.subcommands) {\n const subFuncName = `_${programName}_${[...currentPath.slice(1), sub.name].join(\"_\")}`;\n func += ` ${sub.name})\\n`;\n func += ` ${subFuncName}\\n`;\n func += ` ;;\\n`;\n }\n\n func += ` esac\\n`;\n func += ` ;;\\n`;\n func += ` esac\\n`;\n }\n\n func += `}\\n`;\n\n return func;\n}\n\n/**\n * Collect all subcommand functions recursively\n */\nfunction collectSubcommandFunctions(\n command: CompletableSubcommand,\n programName: string,\n includeDescriptions: boolean,\n parentPath: string[] = [],\n): string[] {\n const functions: string[] = [];\n\n // Generate function for this command\n functions.push(generateSubcommandFunction(command, programName, includeDescriptions, parentPath));\n\n // Generate functions for subcommands\n const currentPath = parentPath.length === 0 ? [command.name] : [...parentPath, command.name];\n\n for (const sub of command.subcommands) {\n functions.push(\n ...collectSubcommandFunctions(sub, programName, includeDescriptions, currentPath),\n );\n }\n\n return functions;\n}\n\n/**\n * Generate the zsh completion script\n */\nfunction generateZshScript(\n command: CompletableSubcommand,\n programName: string,\n includeDescriptions: boolean,\n): string {\n const functions = collectSubcommandFunctions(command, programName, includeDescriptions);\n\n return `#compdef ${programName}\n\n# Zsh completion for ${programName}\n# Generated by politty\n\n${functions.join(\"\\n\")}\n\n_${programName} \"$@\"\n`;\n}\n\n/**\n * Generate zsh completion script for a command\n */\nexport function generateZshCompletion(\n command: AnyCommand,\n options: CompletionOptions,\n): CompletionResult {\n const data = extractCompletionData(command, options.programName);\n const includeDescriptions = options.includeDescriptions ?? true;\n\n const script = generateZshScript(data.command, options.programName, includeDescriptions);\n\n return {\n script,\n shell: \"zsh\",\n installInstructions: `# To enable completions, add the following to your ~/.zshrc:\n\n# Option 1: Source directly (add before compinit)\neval \"$(${options.programName} completion zsh)\"\n\n# Option 2: Save to a file in your fpath\n${options.programName} completion zsh > ~/.zsh/completions/_${options.programName}\n\n# Make sure your fpath includes the completions directory:\n# fpath=(~/.zsh/completions $fpath)\n# autoload -Uz compinit && compinit\n\n# Then reload your shell or run:\nsource ~/.zshrc`,\n };\n}\n","/**\n * Shell completion generation module\n *\n * Provides utilities to generate shell completion scripts for bash, zsh, and fish.\n *\n * @example\n * ```typescript\n * import { generateCompletion, createCompletionCommand } from \"politty/completion\";\n *\n * // Generate completion script directly\n * const result = generateCompletion(myCommand, {\n * shell: \"bash\",\n * programName: \"mycli\"\n * });\n * console.log(result.script);\n *\n * // Or add a completion subcommand to your CLI\n * const mainCommand = defineCommand({\n * name: \"mycli\",\n * subCommands: {\n * completion: createCompletionCommand(myCommand, \"mycli\")\n * }\n * });\n * ```\n */\n\nimport { z } from \"zod\";\nimport { arg } from \"../core/arg-registry.js\";\nimport { defineCommand } from \"../core/command.js\";\nimport type { AnyCommand, Command } from \"../types.js\";\nimport { generateBashCompletion } from \"./bash.js\";\nimport { generateFishCompletion } from \"./fish.js\";\nimport type { CompletionOptions, CompletionResult, ShellType } from \"./types.js\";\nimport { generateZshCompletion } from \"./zsh.js\";\n\n// Re-export types\n// Re-export extractor\nexport { extractCompletionData, extractPositionals } from \"./extractor.js\";\nexport type {\n CompletableOption,\n CompletableSubcommand,\n CompletionData,\n CompletionGenerator,\n CompletionOptions,\n CompletionResult,\n ShellType,\n} from \"./types.js\";\n\n/**\n * Generate completion script for the specified shell\n */\nexport function generateCompletion(\n command: AnyCommand,\n options: CompletionOptions,\n): CompletionResult {\n switch (options.shell) {\n case \"bash\":\n return generateBashCompletion(command, options);\n case \"zsh\":\n return generateZshCompletion(command, options);\n case \"fish\":\n return generateFishCompletion(command, options);\n default:\n throw new Error(`Unsupported shell: ${options.shell}`);\n }\n}\n\n/**\n * Get the list of supported shells\n */\nexport function getSupportedShells(): ShellType[] {\n return [\"bash\", \"zsh\", \"fish\"];\n}\n\n/**\n * Detect the current shell from environment\n */\nexport function detectShell(): ShellType | null {\n const shell = process.env.SHELL || \"\";\n const shellName = shell.split(\"/\").pop()?.toLowerCase() || \"\";\n\n if (shellName.includes(\"bash\")) {\n return \"bash\";\n }\n if (shellName.includes(\"zsh\")) {\n return \"zsh\";\n }\n if (shellName.includes(\"fish\")) {\n return \"fish\";\n }\n\n return null;\n}\n\n/**\n * Schema for the completion command arguments\n */\nconst completionArgsSchema = z.object({\n shell: arg(\n z\n .enum([\"bash\", \"zsh\", \"fish\"])\n .optional()\n .describe(\"Shell type (auto-detected if not specified)\"),\n {\n positional: true,\n description: \"Shell type (bash, zsh, or fish)\",\n placeholder: \"SHELL\",\n },\n ),\n instructions: arg(z.boolean().default(false), {\n alias: \"i\",\n description: \"Show installation instructions\",\n }),\n});\n\ntype CompletionArgs = z.infer<typeof completionArgsSchema>;\n\n/**\n * Create a completion subcommand for your CLI\n *\n * This creates a ready-to-use subcommand that generates completion scripts.\n *\n * @example\n * ```typescript\n * const mainCommand = defineCommand({\n * name: \"mycli\",\n * subCommands: {\n * completion: createCompletionCommand(mainCommand, \"mycli\")\n * }\n * });\n * ```\n */\nexport function createCompletionCommand(\n rootCommand: AnyCommand,\n programName: string,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n): Command<typeof completionArgsSchema, CompletionArgs, any> {\n return defineCommand({\n name: \"completion\",\n description: \"Generate shell completion script\",\n args: completionArgsSchema,\n run(args) {\n // Detect shell if not specified\n const shellType = args.shell || detectShell();\n\n if (!shellType) {\n console.error(\"Could not detect shell type. Please specify one of: bash, zsh, fish\");\n process.exitCode = 1;\n return;\n }\n\n const result = generateCompletion(rootCommand, {\n shell: shellType,\n programName,\n includeDescriptions: true,\n });\n\n if (args.instructions) {\n console.log(result.installInstructions);\n } else {\n console.log(result.script);\n }\n },\n });\n}\n\n/**\n * Helper to add completion command to an existing command's subCommands\n *\n * @example\n * ```typescript\n * const command = defineCommand({\n * name: \"mycli\",\n * subCommands: {\n * ...withCompletionCommand(command, \"mycli\"),\n * // other subcommands\n * }\n * });\n * ```\n */\nexport function withCompletionCommand(\n rootCommand: AnyCommand,\n programName: string,\n): { completion: ReturnType<typeof createCompletionCommand> } {\n return {\n completion: createCompletionCommand(rootCommand, programName),\n };\n}\n"],"mappings":";;;;;;;;;;;AAWA,SAAS,cAAc,OAA6C;AAClE,QAAO;EACL,MAAM,MAAM;EACZ,SAAS,MAAM;EACf,OAAO,MAAM;EACb,aAAa,MAAM;EAEnB,YAAY,MAAM,SAAS;EAC3B,WAAW,MAAM;EACjB,UAAU,MAAM;EACjB;;;;;AAMH,SAAS,eAAe,SAA0C;AAChE,KAAI,CAAC,QAAQ,KACX,QAAO,EAAE;AAIX,QADkB,cAAc,QAAQ,KAAK,CAC5B,OACd,QAAQ,UAAU,CAAC,MAAM,WAAW,CACpC,IAAI,cAAc;;;;;AAMvB,SAAgB,mBAAmB,SAA0C;AAC3E,KAAI,CAAC,QAAQ,KACX,QAAO,EAAE;AAIX,QADkB,cAAc,QAAQ,KAAK,CAC5B,OAAO,QAAQ,UAAU,MAAM,WAAW;;;;;AAM7D,SAAS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