politty 0.4.15 → 0.5.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 (75) hide show
  1. package/dist/{arg-registry-Dw0f11Zc.d.ts → arg-registry--NRaNFJM.d.cts} +238 -6
  2. package/dist/arg-registry--NRaNFJM.d.cts.map +1 -0
  3. package/dist/{arg-registry-CB5gGtzp.d.cts → arg-registry-6E0WHOh_.d.ts} +238 -6
  4. package/dist/arg-registry-6E0WHOh_.d.ts.map +1 -0
  5. package/dist/augment.d.cts +1 -1
  6. package/dist/augment.d.cts.map +1 -1
  7. package/dist/augment.d.ts +1 -1
  8. package/dist/augment.d.ts.map +1 -1
  9. package/dist/completion/index.cjs +2 -1
  10. package/dist/completion/index.d.cts +3 -2
  11. package/dist/completion/index.d.ts +3 -2
  12. package/dist/completion/index.js +2 -2
  13. package/dist/completion-BA5JMvVG.js +4067 -0
  14. package/dist/completion-BA5JMvVG.js.map +1 -0
  15. package/dist/completion-Cqs1Ja7C.cjs +4169 -0
  16. package/dist/completion-Cqs1Ja7C.cjs.map +1 -0
  17. package/dist/docs/index.cjs +89 -29
  18. package/dist/docs/index.cjs.map +1 -1
  19. package/dist/docs/index.d.cts +1 -1
  20. package/dist/docs/index.d.cts.map +1 -1
  21. package/dist/docs/index.d.ts +1 -1
  22. package/dist/docs/index.d.ts.map +1 -1
  23. package/dist/docs/index.js +92 -31
  24. package/dist/docs/index.js.map +1 -1
  25. package/dist/{index-C1gGgUeB.d.cts → index-DBMfKZ34.d.ts} +189 -17
  26. package/dist/index-DBMfKZ34.d.ts.map +1 -0
  27. package/dist/{index-Dg9Fpz0R.d.ts → index-DJp8k5Bq.d.cts} +189 -17
  28. package/dist/index-DJp8k5Bq.d.cts.map +1 -0
  29. package/dist/index.cjs +12 -10
  30. package/dist/index.d.cts +36 -4
  31. package/dist/index.d.cts.map +1 -1
  32. package/dist/index.d.ts +36 -4
  33. package/dist/index.d.ts.map +1 -1
  34. package/dist/index.js +4 -4
  35. package/dist/log-collector-Cd2_mv87.cjs.map +1 -1
  36. package/dist/log-collector-Cu6MCtAx.js.map +1 -1
  37. package/dist/prompt/clack/index.cjs.map +1 -1
  38. package/dist/prompt/clack/index.d.cts +1 -1
  39. package/dist/prompt/clack/index.d.cts.map +1 -1
  40. package/dist/prompt/clack/index.d.ts +1 -1
  41. package/dist/prompt/clack/index.d.ts.map +1 -1
  42. package/dist/prompt/clack/index.js.map +1 -1
  43. package/dist/prompt/index.d.cts +1 -1
  44. package/dist/prompt/index.d.cts.map +1 -1
  45. package/dist/prompt/index.d.ts +1 -1
  46. package/dist/prompt/index.d.ts.map +1 -1
  47. package/dist/prompt/inquirer/index.cjs.map +1 -1
  48. package/dist/prompt/inquirer/index.d.cts +1 -1
  49. package/dist/prompt/inquirer/index.d.cts.map +1 -1
  50. package/dist/prompt/inquirer/index.d.ts +1 -1
  51. package/dist/prompt/inquirer/index.d.ts.map +1 -1
  52. package/dist/prompt/inquirer/index.js.map +1 -1
  53. package/dist/prompt-BKHqGrFw.js.map +1 -1
  54. package/dist/prompt-aXfSf27y.cjs.map +1 -1
  55. package/dist/{runner-DKAQBNNh.js → runner-BmSEiD9A.js} +319 -52
  56. package/dist/runner-BmSEiD9A.js.map +1 -0
  57. package/dist/{runner-CriXJlm4.cjs → runner-CRZ_7Y9i.cjs} +366 -87
  58. package/dist/runner-CRZ_7Y9i.cjs.map +1 -0
  59. package/dist/{subcommand-router-ENeCymvX.js → schema-extractor-C50R-1re.js} +175 -137
  60. package/dist/schema-extractor-C50R-1re.js.map +1 -0
  61. package/dist/{subcommand-router-CqZX3orq.cjs → schema-extractor-SLPgBNgZ.cjs} +174 -136
  62. package/dist/schema-extractor-SLPgBNgZ.cjs.map +1 -0
  63. package/package.json +16 -16
  64. package/dist/arg-registry-CB5gGtzp.d.cts.map +0 -1
  65. package/dist/arg-registry-Dw0f11Zc.d.ts.map +0 -1
  66. package/dist/completion-B5fgnUGm.cjs +0 -1940
  67. package/dist/completion-B5fgnUGm.cjs.map +0 -1
  68. package/dist/completion-Ca5ESJlG.js +0 -1844
  69. package/dist/completion-Ca5ESJlG.js.map +0 -1
  70. package/dist/index-C1gGgUeB.d.cts.map +0 -1
  71. package/dist/index-Dg9Fpz0R.d.ts.map +0 -1
  72. package/dist/runner-CriXJlm4.cjs.map +0 -1
  73. package/dist/runner-DKAQBNNh.js.map +0 -1
  74. package/dist/subcommand-router-CqZX3orq.cjs.map +0 -1
  75. package/dist/subcommand-router-ENeCymvX.js.map +0 -1
@@ -1,1844 +0,0 @@
1
- import { c as resolveSubCommandMeta, h as arg, i as resolveSubCommandAlias, l as extractFields, p as toCamelCase } from "./subcommand-router-ENeCymvX.js";
2
- import { z } from "zod";
3
- import { execSync } from "node:child_process";
4
-
5
- //#region src/core/command.ts
6
- function defineCommand(config) {
7
- return {
8
- name: config.name,
9
- description: config.description,
10
- aliases: config.aliases,
11
- args: config.args,
12
- subCommands: config.subCommands,
13
- setup: config.setup,
14
- run: config.run,
15
- cleanup: config.cleanup,
16
- notes: config.notes,
17
- examples: config.examples
18
- };
19
- }
20
- /**
21
- * Create a typed defineCommand factory with pre-bound global args type.
22
- * This is the recommended pattern for type-safe global options.
23
- *
24
- * @example
25
- * ```ts
26
- * // global-args.ts
27
- * type GlobalArgsType = { verbose: boolean; config?: string };
28
- * export const defineAppCommand = createDefineCommand<GlobalArgsType>();
29
- *
30
- * // commands/build.ts
31
- * export const buildCommand = defineAppCommand({
32
- * name: "build",
33
- * args: z.object({ output: arg(z.string().default("dist")) }),
34
- * run: (args) => {
35
- * args.verbose; // typed via GlobalArgsType
36
- * args.output; // typed via local args
37
- * },
38
- * });
39
- * ```
40
- */
41
- function createDefineCommand() {
42
- return defineCommand;
43
- }
44
-
45
- //#endregion
46
- //#region src/completion/value-completion-resolver.ts
47
- /**
48
- * Resolve value completion from field metadata
49
- *
50
- * Priority:
51
- * 1. Explicit custom completion (choices or shellCommand)
52
- * 2. Explicit completion type (file, directory, none)
53
- * 3. Auto-detected enum values from schema
54
- */
55
- function resolveValueCompletion(field) {
56
- const meta = field.completion;
57
- if (meta?.custom) {
58
- if (meta.custom.choices && meta.custom.choices.length > 0) return {
59
- type: "choices",
60
- choices: meta.custom.choices
61
- };
62
- if (meta.custom.shellCommand) return {
63
- type: "command",
64
- shellCommand: meta.custom.shellCommand
65
- };
66
- }
67
- if (meta?.type) {
68
- if (meta.type === "file") {
69
- if (meta.matcher) return {
70
- type: "file",
71
- matcher: meta.matcher
72
- };
73
- if (meta.extensions) return {
74
- type: "file",
75
- extensions: meta.extensions
76
- };
77
- return { type: "file" };
78
- }
79
- if (meta.type === "directory") return { type: "directory" };
80
- if (meta.type === "none") return { type: "none" };
81
- }
82
- if (field.enumValues && field.enumValues.length > 0) return {
83
- type: "choices",
84
- choices: field.enumValues
85
- };
86
- }
87
-
88
- //#endregion
89
- //#region src/completion/extractor.ts
90
- /**
91
- * Extract completion data from commands
92
- */
93
- /**
94
- * Sanitize a name for use as a shell function/variable identifier.
95
- * Replaces any character that is not alphanumeric or underscore with underscore.
96
- *
97
- * Note: This is not injective -- distinct names may produce the same output
98
- * (e.g., "foo-bar" and "foo_bar" both become "foo_bar"). When used for nested
99
- * path encoding (`path.map(sanitize).join("_")`), cross-level collisions are
100
- * theoretically possible (e.g., "foo-bar:baz" vs "foo:bar-baz") but extremely
101
- * unlikely in real CLI designs. If collision-safety is needed, sanitize must be
102
- * replaced with an injective encoding.
103
- */
104
- function sanitize(name) {
105
- return name.replace(/[^a-zA-Z0-9_]/g, "_");
106
- }
107
- /**
108
- * Filter subcommands to only visible (non-internal) ones.
109
- * Internal subcommands start with "__" and are hidden from completion/help.
110
- */
111
- function getVisibleSubs(subs) {
112
- return subs.filter((s) => !s.name.startsWith("__"));
113
- }
114
- /**
115
- * Get all completable subcommand names including aliases.
116
- * Returns an array of { name, description } for all visible subcommands
117
- * and their aliases.
118
- */
119
- function getSubNamesWithAliases(subs) {
120
- const result = [];
121
- for (const sub of getVisibleSubs(subs)) {
122
- result.push({
123
- name: sub.name,
124
- description: sub.description
125
- });
126
- if (sub.aliases) for (const alias of sub.aliases) result.push({
127
- name: alias,
128
- description: sub.description
129
- });
130
- }
131
- return result;
132
- }
133
- /**
134
- * Convert a resolved field to a completable option
135
- */
136
- function fieldToOption(field) {
137
- return {
138
- name: field.name,
139
- cliName: field.cliName,
140
- alias: field.alias,
141
- description: field.description,
142
- takesValue: field.type !== "boolean",
143
- valueType: field.type,
144
- required: field.required,
145
- valueCompletion: resolveValueCompletion(field)
146
- };
147
- }
148
- /**
149
- * Extract options from a command's args schema
150
- */
151
- function extractOptions$1(command) {
152
- if (!command.args) return [];
153
- return extractFields(command.args).fields.filter((field) => !field.positional).map(fieldToOption);
154
- }
155
- /**
156
- * Extract positional arguments from a command
157
- */
158
- function extractPositionals(command) {
159
- if (!command.args) return [];
160
- return extractFields(command.args).fields.filter((field) => field.positional);
161
- }
162
- /**
163
- * Extract completable positional arguments from a command
164
- */
165
- function extractCompletablePositionals(command) {
166
- if (!command.args) return [];
167
- return extractFields(command.args).fields.filter((field) => field.positional).map((field, index) => ({
168
- name: field.name,
169
- cliName: field.cliName,
170
- position: index,
171
- description: field.description,
172
- required: field.required,
173
- variadic: field.type === "array",
174
- valueCompletion: resolveValueCompletion(field)
175
- }));
176
- }
177
- /**
178
- * Extract a completable subcommand from a command
179
- */
180
- function extractSubcommand(name, command) {
181
- const subcommands = [];
182
- if (command.subCommands) for (const [subName, subCommand] of Object.entries(command.subCommands)) {
183
- const resolved = resolveSubCommandMeta(subCommand);
184
- if (resolved) subcommands.push(extractSubcommand(subName, resolved));
185
- else subcommands.push({
186
- name: subName,
187
- description: "(lazy loaded)",
188
- subcommands: [],
189
- options: [],
190
- positionals: []
191
- });
192
- }
193
- return {
194
- name,
195
- description: command.description,
196
- aliases: command.aliases,
197
- subcommands,
198
- options: extractOptions$1(command),
199
- positionals: extractCompletablePositionals(command)
200
- };
201
- }
202
- /** Join parent and child with a separator, omitting separator when parent is empty. */
203
- function joinPrefix(parent, child, sep) {
204
- return parent ? `${parent}${sep}${child}` : child;
205
- }
206
- /**
207
- * Collect opt-takes-value case entries for a subcommand tree.
208
- * Used by bash and zsh generators (identical case syntax: `path:--opt) return 0 ;;`).
209
- * parentPath is a colon-delimited path (e.g., "" for root, "workspace:user" for nested).
210
- */
211
- function optTakesValueEntries(sub, parentPath) {
212
- const lines = [];
213
- for (const opt of sub.options) if (opt.takesValue) {
214
- const patterns = [`${parentPath}:--${opt.cliName}`];
215
- if (opt.alias) for (const a of opt.alias) patterns.push(`${parentPath}:${a.length === 1 ? `-${a}` : `--${a}`}`);
216
- lines.push(` ${patterns.join("|")}) return 0 ;;`);
217
- }
218
- for (const child of getVisibleSubs(sub.subcommands)) {
219
- lines.push(...optTakesValueEntries(child, joinPrefix(parentPath, child.name, ":")));
220
- if (child.aliases) for (const alias of child.aliases) lines.push(...optTakesValueEntries(child, joinPrefix(parentPath, alias, ":")));
221
- }
222
- return lines;
223
- }
224
- /**
225
- * Recursively collect all subcommand route entries.
226
- * Returns entries used by all shell generators for both dispatch routing
227
- * and subcommand lookup (is_subcmd) tables.
228
- * Aliases are mapped to the same handler as the canonical name.
229
- */
230
- function collectRouteEntries(sub, parentPath = "", parentFunc = "") {
231
- const entries = [];
232
- for (const child of getVisibleSubs(sub.subcommands)) {
233
- const pathStr = joinPrefix(parentPath, child.name, ":");
234
- const funcSuffix = joinPrefix(parentFunc, sanitize(child.name), "_");
235
- entries.push(...collectRouteEntries(child, pathStr, funcSuffix));
236
- entries.push({
237
- pathStr,
238
- funcSuffix,
239
- lookupPattern: `${parentPath}:${child.name}`
240
- });
241
- if (child.aliases) for (const alias of child.aliases) {
242
- const aliasPathStr = joinPrefix(parentPath, alias, ":");
243
- entries.push(...collectRouteEntries(child, aliasPathStr, funcSuffix));
244
- entries.push({
245
- pathStr: aliasPathStr,
246
- funcSuffix,
247
- lookupPattern: `${parentPath}:${alias}`
248
- });
249
- }
250
- }
251
- return entries;
252
- }
253
- /**
254
- * Generate is_subcmd case/switch body lines (bash/zsh case syntax).
255
- * Returns lines for the case statement body only (caller wraps in function).
256
- */
257
- function isSubcmdCaseLines(routeEntries) {
258
- return routeEntries.map((r) => ` ${r.lookupPattern}) return 0 ;;`);
259
- }
260
- /**
261
- * Recursively merge global options into a subcommand and all its descendants.
262
- * Avoids duplicates by checking existing option names.
263
- */
264
- function propagateGlobalOptions(sub, globalOptions) {
265
- const existingNames = new Set(sub.options.map((o) => o.name));
266
- const newOpts = globalOptions.filter((o) => !existingNames.has(o.name));
267
- sub.options = [...sub.options, ...newOpts];
268
- for (const child of sub.subcommands) propagateGlobalOptions(child, globalOptions);
269
- }
270
- /**
271
- * Extract completion data from a command tree
272
- *
273
- * @param command - The root command
274
- * @param programName - Program name for completion scripts
275
- * @param globalArgsSchema - Optional global args schema. When provided, global options
276
- * are derived from this schema instead of the root command's options.
277
- */
278
- function extractCompletionData(command, programName, globalArgsSchema) {
279
- const rootSubcommand = extractSubcommand(programName, command);
280
- let globalOptions;
281
- if (globalArgsSchema) {
282
- globalOptions = extractFields(globalArgsSchema).fields.filter((field) => !field.positional).map(fieldToOption);
283
- propagateGlobalOptions(rootSubcommand, globalOptions);
284
- } else globalOptions = rootSubcommand.options;
285
- return {
286
- command: rootSubcommand,
287
- programName,
288
- globalOptions
289
- };
290
- }
291
-
292
- //#endregion
293
- //#region src/completion/bash.ts
294
- /** Escape a string for use inside bash double-quotes */
295
- function escapeBashDQ(s) {
296
- return s.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\$/g, "\\$").replace(/`/g, "\\`");
297
- }
298
- /**
299
- * Generate bash value completion code for a ValueCompletion spec.
300
- * Returns an array of bash lines.
301
- */
302
- function bashValueLines(vc, inline) {
303
- if (!vc) return [];
304
- switch (vc.type) {
305
- case "choices": {
306
- const items = vc.choices.map((c) => `"${escapeBashDQ(c)}"`).join(" ");
307
- if (inline) return [
308
- `local -a _choices=(${items})`,
309
- `COMPREPLY=()`,
310
- `local _c; for _c in "\${_choices[@]}"; do [[ "$_c" == "$_cur"* ]] && COMPREPLY+=("\${_inline_prefix}\${_c}"); done`,
311
- `compopt -o nospace`,
312
- `compopt +o default 2>/dev/null`
313
- ];
314
- return [
315
- `local -a _choices=(${items})`,
316
- `COMPREPLY=()`,
317
- `local _c; for _c in "\${_choices[@]}"; do [[ "$_c" == "$_cur"* ]] && COMPREPLY+=("$_c"); done`,
318
- `compopt +o default 2>/dev/null`
319
- ];
320
- }
321
- case "file":
322
- if (vc.matcher?.length) return bashFileFilter(vc.matcher.map((p) => `[[ "\${_f##*/}" == ${p} ]]`).join(" || "), inline);
323
- if (vc.extensions?.length) return bashFileFilter(vc.extensions.map((ext) => `[[ "$_f" == *".${ext}" ]]`).join(" || "), inline);
324
- if (inline) return [
325
- `local -a _entries=($(compgen -f -- "$_cur"))`,
326
- `COMPREPLY=("\${_entries[@]/#/$_inline_prefix}")`,
327
- `compopt -o filenames`
328
- ];
329
- return [`COMPREPLY=($(compgen -f -- "$_cur"))`, `compopt -o filenames`];
330
- case "directory":
331
- if (inline) return [
332
- `local -a _dirs=($(compgen -d -- "$_cur"))`,
333
- `COMPREPLY=("\${_dirs[@]/#/$_inline_prefix}")`,
334
- `compopt -o filenames`
335
- ];
336
- return [`COMPREPLY=($(compgen -d -- "$_cur"))`, `compopt -o filenames`];
337
- case "command": {
338
- const cmd = vc.shellCommand;
339
- if (inline) return [`COMPREPLY=($(compgen -P "$_inline_prefix" -W "$(${cmd})" -- "$_cur"))`];
340
- return [`COMPREPLY=($(compgen -W "$(${cmd})" -- "$_cur"))`];
341
- }
342
- case "none": return [`compopt +o default 2>/dev/null`];
343
- }
344
- }
345
- function bashFileFilter(checks, inline) {
346
- const prefix = inline ? `"\${_inline_prefix}$_f"` : `"$_f"`;
347
- return [
348
- `local -a _all_entries=($(compgen -f -- "$_cur"))`,
349
- `for _f in "\${_all_entries[@]}"; do`,
350
- ` if [[ -d "$_f" ]]; then`,
351
- ` COMPREPLY+=(${prefix})`,
352
- ` elif ${checks}; then`,
353
- ` COMPREPLY+=(${prefix})`,
354
- ` fi`,
355
- `done`,
356
- `compopt -o filenames`,
357
- `compopt +o default 2>/dev/null`
358
- ];
359
- }
360
- /** Collect value-taking option patterns for case matching */
361
- function optionValueCases$2(options, inline) {
362
- const lines = [];
363
- for (const opt of options) {
364
- if (!opt.takesValue || !opt.valueCompletion) continue;
365
- const valLines = bashValueLines(opt.valueCompletion, inline);
366
- if (valLines.length === 0) continue;
367
- const patterns = [`--${opt.cliName}`];
368
- if (opt.alias) for (const a of opt.alias) patterns.push(a.length === 1 ? `-${a}` : `--${a}`);
369
- const patternStr = patterns.join("|");
370
- lines.push(` ${patternStr})`);
371
- for (const vl of valLines) lines.push(` ${vl}`);
372
- lines.push(` return ;;`);
373
- }
374
- return lines;
375
- }
376
- /** Generate positional completion block */
377
- function positionalBlock$2(positionals) {
378
- if (positionals.length === 0) return [];
379
- const lines = [];
380
- lines.push(` case "$_pos_count" in`);
381
- for (const pos of positionals) {
382
- if (pos.variadic) lines.push(` ${pos.position}|*)`);
383
- else lines.push(` ${pos.position})`);
384
- for (const vl of bashValueLines(pos.valueCompletion, false)) lines.push(` ${vl}`);
385
- lines.push(` ;;`);
386
- }
387
- lines.push(` esac`);
388
- return lines;
389
- }
390
- /** Generate prev/inline value completion blocks for options */
391
- function valueCompletionBlocks(options) {
392
- if (!options.some((o) => o.takesValue && o.valueCompletion)) return [];
393
- const lines = [];
394
- const prevCases = optionValueCases$2(options, false);
395
- if (prevCases.length > 0) {
396
- lines.push(` if [[ -z "$_inline_prefix" ]]; then`);
397
- lines.push(` case "$_prev" in`);
398
- lines.push(...prevCases);
399
- lines.push(` esac`);
400
- lines.push(` fi`);
401
- }
402
- const inlineCases = optionValueCases$2(options, true);
403
- if (inlineCases.length > 0) {
404
- lines.push(` if [[ -n "$_inline_prefix" ]]; then`);
405
- lines.push(` case "\${_inline_prefix%=}" in`);
406
- lines.push(...inlineCases);
407
- lines.push(` esac`);
408
- lines.push(` fi`);
409
- }
410
- return lines;
411
- }
412
- /** Generate available-options list lines */
413
- function availableOptionLines$2(options, fn) {
414
- const lines = [];
415
- for (const opt of options) if (opt.valueType === "array") lines.push(` _avail+=(--${opt.cliName})`);
416
- else {
417
- const patterns = [`"--${opt.cliName}"`];
418
- if (opt.alias) for (const a of opt.alias) patterns.push(a.length === 1 ? `"-${a}"` : `"--${a}"`);
419
- lines.push(` __${fn}_not_used ${patterns.join(" ")} && _avail+=(--${opt.cliName})`);
420
- }
421
- lines.push(` __${fn}_not_used "--help" && _avail+=(--help)`);
422
- return lines;
423
- }
424
- /**
425
- * Generate a per-subcommand completion function.
426
- * Recursively generates functions for nested subcommands.
427
- */
428
- function generateSubHandler$2(sub, fn, path) {
429
- const fullPath = [...path, sub.name];
430
- const funcName = `__${fn}_complete_${fullPath.map(sanitize).join("_")}`;
431
- const visibleSubs = getVisibleSubs(sub.subcommands);
432
- const lines = [];
433
- for (const child of visibleSubs) lines.push(...generateSubHandler$2(child, fn, fullPath));
434
- lines.push(`${funcName}() {`);
435
- lines.push(...valueCompletionBlocks(sub.options));
436
- const fullPathStr = fullPath.join(":");
437
- lines.push(` if [[ -z "$_inline_prefix" ]] && __${fn}_opt_takes_value "${fullPathStr}" "$_prev"; then return; fi`);
438
- lines.push(` if [[ -n "$_inline_prefix" ]] && __${fn}_opt_takes_value "${fullPathStr}" "\${_inline_prefix%=}"; then return; fi`);
439
- if (sub.positionals.length > 0) {
440
- lines.push(` if (( _after_dd )); then`);
441
- lines.push(...positionalBlock$2(sub.positionals).map((l) => ` ${l}`));
442
- lines.push(` return`);
443
- lines.push(` fi`);
444
- } else lines.push(` if (( _after_dd )); then return; fi`);
445
- lines.push(` if [[ "$_cur" == -* ]]; then`);
446
- lines.push(` local -a _avail=()`);
447
- lines.push(...availableOptionLines$2(sub.options, fn));
448
- lines.push(` COMPREPLY=($(compgen -W "\${_avail[*]}" -- "$_cur"))`);
449
- lines.push(` compopt +o default 2>/dev/null`);
450
- lines.push(` return`);
451
- lines.push(` fi`);
452
- if (visibleSubs.length > 0) {
453
- const subNames = getSubNamesWithAliases(sub.subcommands).map((s) => s.name).join(" ");
454
- lines.push(` COMPREPLY=($(compgen -W "${subNames}" -- "$_cur"))`);
455
- lines.push(` compopt +o default 2>/dev/null`);
456
- } else if (sub.positionals.length > 0) lines.push(...positionalBlock$2(sub.positionals));
457
- lines.push(`}`);
458
- lines.push(``);
459
- return lines;
460
- }
461
- function generateBashCompletion(command, options) {
462
- const { programName } = options;
463
- const data = extractCompletionData(command, programName, options.globalArgsSchema);
464
- const fn = sanitize(programName);
465
- const root = data.command;
466
- const visibleSubs = getVisibleSubs(root.subcommands);
467
- const lines = [];
468
- lines.push(`# Bash completion for ${programName}`);
469
- lines.push(`# Generated by politty`);
470
- lines.push(``);
471
- lines.push(`__${fn}_not_used() {`);
472
- lines.push(` for _u in "\${_used_opts[@]}"; do`);
473
- lines.push(` for _chk in "$@"; do`);
474
- lines.push(` [[ "$_u" == "$_chk" ]] && return 1`);
475
- lines.push(` done`);
476
- lines.push(` done`);
477
- lines.push(` return 0`);
478
- lines.push(`}`);
479
- lines.push(``);
480
- lines.push(`__${fn}_opt_takes_value() {`);
481
- lines.push(` case "$1:$2" in`);
482
- lines.push(...optTakesValueEntries(root, ""));
483
- lines.push(` esac`);
484
- lines.push(` return 1`);
485
- lines.push(`}`);
486
- lines.push(``);
487
- const routeEntries = collectRouteEntries(root);
488
- if (routeEntries.length > 0) {
489
- lines.push(`__${fn}_is_subcmd() {`);
490
- lines.push(` case "$1:$2" in`);
491
- lines.push(...isSubcmdCaseLines(routeEntries));
492
- lines.push(` esac`);
493
- lines.push(` return 1`);
494
- lines.push(`}`);
495
- lines.push(``);
496
- }
497
- for (const sub of visibleSubs) lines.push(...generateSubHandler$2(sub, fn, []));
498
- lines.push(`__${fn}_complete_root() {`);
499
- lines.push(...valueCompletionBlocks(root.options));
500
- lines.push(` if [[ -z "$_inline_prefix" ]] && __${fn}_opt_takes_value "" "$_prev"; then return; fi`);
501
- lines.push(` if [[ -n "$_inline_prefix" ]] && __${fn}_opt_takes_value "" "\${_inline_prefix%=}"; then return; fi`);
502
- if (root.positionals.length > 0) {
503
- lines.push(` if (( _after_dd )); then`);
504
- lines.push(...positionalBlock$2(root.positionals).map((l) => ` ${l}`));
505
- lines.push(` return`);
506
- lines.push(` fi`);
507
- } else lines.push(` if (( _after_dd )); then return; fi`);
508
- lines.push(` if [[ "$_cur" == -* ]]; then`);
509
- lines.push(` local -a _avail=()`);
510
- lines.push(...availableOptionLines$2(root.options, fn));
511
- lines.push(` COMPREPLY=($(compgen -W "\${_avail[*]}" -- "$_cur"))`);
512
- lines.push(` compopt +o default 2>/dev/null`);
513
- if (visibleSubs.length > 0) {
514
- lines.push(` else`);
515
- const subNames = getSubNamesWithAliases(root.subcommands).map((s) => s.name).join(" ");
516
- lines.push(` COMPREPLY=($(compgen -W "${subNames}" -- "$_cur"))`);
517
- lines.push(` compopt +o default 2>/dev/null`);
518
- } else if (root.positionals.length > 0) {
519
- lines.push(` else`);
520
- lines.push(...positionalBlock$2(root.positionals).map((l) => ` ${l}`));
521
- }
522
- lines.push(` fi`);
523
- lines.push(`}`);
524
- lines.push(``);
525
- const subRouting = routeEntries.map((r) => ` ${r.pathStr}) __${fn}_complete_${r.funcSuffix} ;;`).join("\n");
526
- lines.push(`_${fn}_completions() {`);
527
- lines.push(` COMPREPLY=()`);
528
- lines.push(``);
529
- lines.push(` # Rejoin words split by '=' in COMP_WORDBREAKS`);
530
- lines.push(` local -a _words=()`);
531
- lines.push(` local _i=1`);
532
- lines.push(` while (( _i <= COMP_CWORD )); do`);
533
- lines.push(` if [[ "\${COMP_WORDS[_i]}" == "=" && \${#_words[@]} -gt 0 ]]; then`);
534
- lines.push(` _words[\${#_words[@]}-1]+="=\${COMP_WORDS[_i+1]:-}"`);
535
- lines.push(` (( _i += 2 ))`);
536
- lines.push(` else`);
537
- lines.push(` _words+=("\${COMP_WORDS[_i]}")`);
538
- lines.push(` (( _i++ ))`);
539
- lines.push(` fi`);
540
- lines.push(` done`);
541
- lines.push(``);
542
- lines.push(` local _cur=""`);
543
- lines.push(` (( \${#_words[@]} > 0 )) && _cur="\${_words[\${#_words[@]}-1]}"`);
544
- lines.push(``);
545
- lines.push(` local _inline_prefix=""`);
546
- lines.push(` if [[ "$_cur" == --*=* ]]; then`);
547
- lines.push(` _inline_prefix="\${_cur%%=*}="`);
548
- lines.push(` _cur="\${_cur#*=}"`);
549
- lines.push(` fi`);
550
- lines.push(``);
551
- lines.push(` local _prev=""`);
552
- lines.push(` (( \${#_words[@]} > 1 )) && _prev="\${_words[\${#_words[@]}-2]}"`);
553
- lines.push(``);
554
- lines.push(` local _subcmd="" _after_dd=0 _pos_count=0 _skip_next=0`);
555
- lines.push(` local -a _used_opts=()`);
556
- lines.push(``);
557
- lines.push(` local _j=0`);
558
- lines.push(` while (( _j < \${#_words[@]} - 1 )); do`);
559
- lines.push(` local _w="\${_words[_j]}"`);
560
- lines.push(` if (( _skip_next )); then _skip_next=0; (( _j++ )); continue; fi`);
561
- lines.push(` if [[ "$_w" == "--" ]]; then _after_dd=1; (( _j++ )); continue; fi`);
562
- lines.push(` if (( _after_dd )); then (( _pos_count++ )); (( _j++ )); continue; fi`);
563
- lines.push(` if [[ "$_w" == --*=* ]]; then _used_opts+=("\${_w%%=*}"); (( _j++ )); continue; fi`);
564
- lines.push(` if [[ "$_w" == -* ]]; then`);
565
- lines.push(` _used_opts+=("$_w")`);
566
- lines.push(` __${fn}_opt_takes_value "$_subcmd" "$_w" && _skip_next=1`);
567
- lines.push(` (( _j++ )); continue`);
568
- lines.push(` fi`);
569
- if (routeEntries.length > 0) lines.push(` if __${fn}_is_subcmd "$_subcmd" "$_w"; then _subcmd="\${_subcmd:+\${_subcmd}:}$_w"; _used_opts=(); _pos_count=0; else (( _pos_count++ )); fi`);
570
- else lines.push(` (( _pos_count++ ))`);
571
- lines.push(` (( _j++ ))`);
572
- lines.push(` done`);
573
- lines.push(``);
574
- lines.push(` case "$_subcmd" in`);
575
- lines.push(subRouting);
576
- lines.push(` *) __${fn}_complete_root ;;`);
577
- lines.push(` esac`);
578
- lines.push(`}`);
579
- lines.push(``);
580
- lines.push(`complete -o default -F _${fn}_completions ${programName}`);
581
- lines.push(``);
582
- return {
583
- script: lines.join("\n"),
584
- shell: "bash",
585
- installInstructions: `# To enable completions, add the following to your ~/.bashrc:
586
-
587
- # Option 1: Source directly
588
- eval "$(${programName} completion bash)"
589
-
590
- # Option 2: Save to a file
591
- ${programName} completion bash > ~/.local/share/bash-completion/completions/${programName}
592
-
593
- # Then reload your shell or run:
594
- source ~/.bashrc`
595
- };
596
- }
597
-
598
- //#endregion
599
- //#region src/completion/dynamic/candidate-generator.ts
600
- /**
601
- * Generate completion candidates based on context
602
- */
603
- /**
604
- * Completion directive flags (bitwise)
605
- */
606
- const CompletionDirective = {
607
- Default: 0,
608
- NoSpace: 1,
609
- NoFileCompletion: 2,
610
- FilterPrefix: 4,
611
- KeepOrder: 8,
612
- FileCompletion: 16,
613
- DirectoryCompletion: 32,
614
- Error: 64
615
- };
616
- /**
617
- * Generate completion candidates based on context
618
- */
619
- function generateCandidates(context) {
620
- const candidates = [];
621
- let directive = CompletionDirective.Default;
622
- switch (context.completionType) {
623
- case "subcommand": return generateSubcommandCandidates(context);
624
- case "option-name": return generateOptionNameCandidates(context);
625
- case "option-value": return generateOptionValueCandidates(context);
626
- case "positional": return generatePositionalCandidates(context);
627
- default: return {
628
- candidates,
629
- directive
630
- };
631
- }
632
- }
633
- /**
634
- * Execute a shell command and return results as candidates
635
- */
636
- function executeShellCommand(command) {
637
- try {
638
- return execSync(command, {
639
- encoding: "utf-8",
640
- timeout: 5e3
641
- }).split("\n").map((line) => line.trim()).filter((line) => line.length > 0).map((line) => ({
642
- value: line,
643
- type: "value"
644
- }));
645
- } catch {
646
- return [];
647
- }
648
- }
649
- /**
650
- * Resolve value completion, executing shell commands and file lookups in JS
651
- */
652
- function resolveValueCandidates(vc, candidates, _currentWord, description) {
653
- let directive = CompletionDirective.FilterPrefix;
654
- let fileExtensions;
655
- let fileMatchers;
656
- switch (vc.type) {
657
- case "choices":
658
- if (vc.choices) for (const choice of vc.choices) candidates.push({
659
- value: choice,
660
- description,
661
- type: "value"
662
- });
663
- directive |= CompletionDirective.NoFileCompletion;
664
- break;
665
- case "file":
666
- if (vc.matcher && vc.matcher.length > 0) {
667
- fileMatchers = vc.matcher.filter((m) => m.trim().length > 0);
668
- if (fileMatchers.length === 0) {
669
- fileMatchers = void 0;
670
- directive |= CompletionDirective.FileCompletion;
671
- }
672
- } else if (vc.extensions && vc.extensions.length > 0) {
673
- fileExtensions = Array.from(new Set(vc.extensions.map((ext) => ext.trim().replace(/^\./, "")).filter((ext) => ext.length > 0)));
674
- if (fileExtensions.length === 0) {
675
- fileExtensions = void 0;
676
- directive |= CompletionDirective.FileCompletion;
677
- }
678
- } else directive |= CompletionDirective.FileCompletion;
679
- break;
680
- case "directory":
681
- directive |= CompletionDirective.DirectoryCompletion;
682
- break;
683
- case "command":
684
- if (vc.shellCommand) candidates.push(...executeShellCommand(vc.shellCommand));
685
- directive |= CompletionDirective.NoFileCompletion;
686
- break;
687
- case "none":
688
- directive |= CompletionDirective.NoFileCompletion;
689
- break;
690
- }
691
- return {
692
- directive,
693
- fileExtensions,
694
- fileMatchers
695
- };
696
- }
697
- /**
698
- * Generate subcommand candidates
699
- */
700
- function generateSubcommandCandidates(context) {
701
- const candidates = [];
702
- let directive = CompletionDirective.FilterPrefix;
703
- for (const name of context.subcommands) {
704
- let description;
705
- const sub = context.currentCommand.subCommands?.[name];
706
- if (sub) description = resolveSubCommandMeta(sub)?.description;
707
- else {
708
- const canonical = resolveSubCommandAlias(context.currentCommand, name);
709
- if (canonical) {
710
- const resolved = context.currentCommand.subCommands?.[canonical];
711
- if (resolved) description = resolveSubCommandMeta(resolved)?.description;
712
- }
713
- }
714
- candidates.push({
715
- value: name,
716
- description,
717
- type: "subcommand"
718
- });
719
- }
720
- if (candidates.length === 0 || context.currentWord.startsWith("-")) {
721
- const optionResult = generateOptionNameCandidates(context);
722
- candidates.push(...optionResult.candidates);
723
- }
724
- return {
725
- candidates,
726
- directive
727
- };
728
- }
729
- /**
730
- * Generate option name candidates
731
- */
732
- function generateOptionNameCandidates(context) {
733
- const candidates = [];
734
- const directive = CompletionDirective.FilterPrefix;
735
- const availableOptions = context.options.filter((opt) => {
736
- if (opt.valueType === "array") return true;
737
- if (context.usedOptions.has(opt.cliName)) return false;
738
- if (opt.alias && opt.alias.some((a) => context.usedOptions.has(a))) return false;
739
- return true;
740
- });
741
- for (const opt of availableOptions) candidates.push({
742
- value: `--${opt.cliName}`,
743
- description: opt.description,
744
- type: "option"
745
- });
746
- if (!context.usedOptions.has("help")) candidates.push({
747
- value: "--help",
748
- description: "Show help information",
749
- type: "option"
750
- });
751
- return {
752
- candidates,
753
- directive
754
- };
755
- }
756
- /**
757
- * Generate option value candidates
758
- */
759
- function generateOptionValueCandidates(context) {
760
- const candidates = [];
761
- if (!context.targetOption) return {
762
- candidates,
763
- directive: CompletionDirective.FilterPrefix
764
- };
765
- const vc = context.targetOption.valueCompletion;
766
- if (!vc) return {
767
- candidates,
768
- directive: CompletionDirective.FilterPrefix
769
- };
770
- return {
771
- candidates,
772
- ...resolveValueCandidates(vc, candidates, context.currentWord)
773
- };
774
- }
775
- /**
776
- * Generate positional argument candidates
777
- */
778
- function generatePositionalCandidates(context) {
779
- const candidates = [];
780
- const positionalIndex = context.positionalIndex ?? 0;
781
- const positional = context.positionals[positionalIndex] ?? (context.positionals.at(-1)?.variadic ? context.positionals.at(-1) : void 0);
782
- if (!positional) return {
783
- candidates,
784
- directive: CompletionDirective.FilterPrefix
785
- };
786
- const vc = positional.valueCompletion;
787
- if (!vc) return {
788
- candidates,
789
- directive: CompletionDirective.FilterPrefix
790
- };
791
- return {
792
- candidates,
793
- ...resolveValueCandidates(vc, candidates, context.currentWord, positional.description)
794
- };
795
- }
796
-
797
- //#endregion
798
- //#region src/completion/dynamic/context-parser.ts
799
- /**
800
- * Parse completion context from partial command line
801
- */
802
- /**
803
- * Extract options from a command
804
- */
805
- function extractOptions(command) {
806
- if (!command.args) return [];
807
- return extractFields(command.args).fields.filter((field) => !field.positional).map((field) => ({
808
- name: field.name,
809
- cliName: field.cliName,
810
- alias: field.alias,
811
- description: field.description,
812
- takesValue: field.type !== "boolean",
813
- valueType: field.type,
814
- required: field.required,
815
- valueCompletion: resolveValueCompletion(field)
816
- }));
817
- }
818
- /**
819
- * Extract positionals from a command
820
- */
821
- function extractPositionalsForContext(command) {
822
- if (!command.args) return [];
823
- return extractFields(command.args).fields.filter((field) => field.positional).map((field, index) => ({
824
- name: field.name,
825
- cliName: field.cliName,
826
- position: index,
827
- description: field.description,
828
- required: field.required,
829
- variadic: field.type === "array",
830
- valueCompletion: resolveValueCompletion(field)
831
- }));
832
- }
833
- /**
834
- * Get subcommand names from a command (including aliases)
835
- */
836
- function getSubcommandNames(command) {
837
- if (!command.subCommands) return [];
838
- const names = [];
839
- for (const [name, subCmd] of Object.entries(command.subCommands)) {
840
- if (name.startsWith("__")) continue;
841
- names.push(name);
842
- const meta = resolveSubCommandMeta(subCmd);
843
- if (meta?.aliases) names.push(...meta.aliases);
844
- }
845
- return names;
846
- }
847
- /**
848
- * Resolve subcommand by name (including alias lookup)
849
- */
850
- function resolveSubcommand(command, name) {
851
- if (!command.subCommands) return null;
852
- const sub = command.subCommands[name];
853
- if (sub) return resolveSubCommandMeta(sub);
854
- const canonical = resolveSubCommandAlias(command, name);
855
- if (canonical) return resolveSubCommandMeta(command.subCommands[canonical]);
856
- return null;
857
- }
858
- /**
859
- * Check if a word is an option (starts with - or --)
860
- */
861
- function isOption(word) {
862
- return word.startsWith("-");
863
- }
864
- /**
865
- * Parse option name from word (e.g., "--foo=bar" -> "foo", "-v" -> "v")
866
- */
867
- function parseOptionName(word) {
868
- if (word.startsWith("--")) {
869
- const withoutPrefix = word.slice(2);
870
- const eqIndex = withoutPrefix.indexOf("=");
871
- return eqIndex >= 0 ? withoutPrefix.slice(0, eqIndex) : withoutPrefix;
872
- }
873
- if (word.startsWith("-")) return word.slice(1, 2);
874
- return word;
875
- }
876
- /**
877
- * Check if option has inline value (e.g., "--foo=bar")
878
- */
879
- function hasInlineValue(word) {
880
- return word.includes("=");
881
- }
882
- /**
883
- * Find option by name or alias
884
- */
885
- function findOption(options, nameOrAlias) {
886
- return options.find((opt) => {
887
- if (opt.cliName === nameOrAlias) return true;
888
- if (opt.alias?.includes(nameOrAlias)) return true;
889
- if (nameOrAlias.length > 1) {
890
- if (opt.cliName.includes("-") && toCamelCase(opt.cliName) === nameOrAlias) return true;
891
- if (opt.alias?.some((a) => a.includes("-") && toCamelCase(a) === nameOrAlias)) return true;
892
- }
893
- return false;
894
- });
895
- }
896
- /**
897
- * Parse completion context from command line arguments
898
- *
899
- * @param argv - Arguments after the program name (e.g., ["build", "--fo"])
900
- * @param rootCommand - The root command
901
- * @returns Completion context
902
- */
903
- function parseCompletionContext(argv, rootCommand) {
904
- let currentCommand = rootCommand;
905
- const subcommandPath = [];
906
- const usedOptions = /* @__PURE__ */ new Set();
907
- let positionalCount = 0;
908
- let i = 0;
909
- let options = extractOptions(currentCommand);
910
- let afterDoubleDash = false;
911
- while (i < argv.length - 1) {
912
- const word = argv[i];
913
- if (!afterDoubleDash && word === "--") {
914
- afterDoubleDash = true;
915
- i++;
916
- continue;
917
- }
918
- if (!afterDoubleDash && isOption(word)) {
919
- const optName = parseOptionName(word);
920
- const opt = findOption(options, optName);
921
- if (opt) {
922
- usedOptions.add(opt.cliName);
923
- if (opt.alias) for (const a of opt.alias) usedOptions.add(a);
924
- if (opt.takesValue && !hasInlineValue(word)) i++;
925
- }
926
- i++;
927
- continue;
928
- }
929
- const subcommand = afterDoubleDash ? null : resolveSubcommand(currentCommand, word);
930
- if (subcommand) {
931
- subcommandPath.push(word);
932
- currentCommand = subcommand;
933
- options = extractOptions(currentCommand);
934
- usedOptions.clear();
935
- positionalCount = 0;
936
- i++;
937
- continue;
938
- }
939
- positionalCount++;
940
- i++;
941
- }
942
- const currentWord = argv[argv.length - 1] ?? "";
943
- const previousWord = argv[argv.length - 2] ?? "";
944
- const positionals = extractPositionalsForContext(currentCommand);
945
- const subcommands = getSubcommandNames(currentCommand);
946
- let completionType;
947
- let targetOption;
948
- let positionalIndex;
949
- if (!afterDoubleDash && previousWord && isOption(previousWord) && !hasInlineValue(previousWord)) {
950
- const optName = parseOptionName(previousWord);
951
- const opt = findOption(options, optName);
952
- if (opt && opt.takesValue) {
953
- completionType = "option-value";
954
- targetOption = opt;
955
- } else if (currentWord.startsWith("-")) completionType = "option-name";
956
- else {
957
- completionType = determineDefaultCompletionType(currentWord, subcommands, positionals, positionalCount);
958
- if (completionType === "positional") positionalIndex = positionalCount;
959
- }
960
- } else if (!afterDoubleDash && currentWord.startsWith("--") && hasInlineValue(currentWord)) {
961
- const optName = parseOptionName(currentWord);
962
- const opt = findOption(options, optName);
963
- if (opt && opt.takesValue) {
964
- completionType = "option-value";
965
- targetOption = opt;
966
- } else completionType = "option-name";
967
- } else if (!afterDoubleDash && currentWord.startsWith("-")) completionType = "option-name";
968
- else {
969
- completionType = determineDefaultCompletionType(currentWord, subcommands, positionals, positionalCount, afterDoubleDash);
970
- if (completionType === "positional") positionalIndex = positionalCount;
971
- }
972
- return {
973
- subcommandPath,
974
- currentCommand,
975
- currentWord,
976
- previousWord,
977
- completionType,
978
- targetOption,
979
- positionalIndex,
980
- options,
981
- subcommands,
982
- positionals,
983
- usedOptions,
984
- providedPositionalCount: positionalCount
985
- };
986
- }
987
- /**
988
- * Determine default completion type when not completing an option
989
- */
990
- function determineDefaultCompletionType(currentWord, subcommands, positionals, positionalCount, afterDoubleDash) {
991
- if (afterDoubleDash) return "positional";
992
- if (subcommands.length > 0) {
993
- if (subcommands.filter((s) => s.startsWith(currentWord)).length > 0 || currentWord === "") return "subcommand";
994
- }
995
- if (positionalCount < positionals.length) return "positional";
996
- if (positionals.length > 0 && positionals[positionals.length - 1].variadic) return "positional";
997
- return "subcommand";
998
- }
999
-
1000
- //#endregion
1001
- //#region src/completion/dynamic/shell-formatter.ts
1002
- /**
1003
- * Format completion candidates for the specified shell
1004
- *
1005
- * @returns Shell-ready output string (lines separated by newline, last line is :directive)
1006
- */
1007
- function formatForShell(result, options) {
1008
- switch (options.shell) {
1009
- case "bash": return formatForBash(result, options);
1010
- case "zsh": return formatForZsh(result, options);
1011
- case "fish": return formatForFish(result, options);
1012
- }
1013
- }
1014
- /**
1015
- * Check if the FilterPrefix directive is set
1016
- */
1017
- function shouldFilterPrefix(directive) {
1018
- return (directive & CompletionDirective.FilterPrefix) !== 0;
1019
- }
1020
- /**
1021
- * Filter candidates by prefix
1022
- */
1023
- function filterByPrefix(candidates, prefix) {
1024
- if (!prefix) return candidates;
1025
- return candidates.filter((c) => c.value.startsWith(prefix));
1026
- }
1027
- /**
1028
- * Append extension metadata and directive to output lines
1029
- */
1030
- function appendMetadata(lines, result) {
1031
- if (result.fileExtensions && result.fileExtensions.length > 0) lines.push(`@ext:${result.fileExtensions.join(",")}`);
1032
- if (result.fileMatchers && result.fileMatchers.length > 0) lines.push(`@matcher:${result.fileMatchers.join(",")}`);
1033
- lines.push(`:${result.directive}`);
1034
- }
1035
- /**
1036
- * Format for bash
1037
- *
1038
- * - Pre-filters candidates by currentWord prefix (replaces compgen -W)
1039
- * - Handles --opt=value inline values by prepending prefix
1040
- * - Outputs plain values only (no descriptions - bash COMPREPLY doesn't support them)
1041
- * - Last line: :directive
1042
- */
1043
- function formatForBash(result, options) {
1044
- let { candidates } = result;
1045
- if (shouldFilterPrefix(result.directive)) candidates = filterByPrefix(candidates, options.currentWord);
1046
- const lines = candidates.map((c) => {
1047
- if (options.inlinePrefix) return `${options.inlinePrefix}${c.value}`;
1048
- return c.value;
1049
- });
1050
- appendMetadata(lines, result);
1051
- return lines.join("\n");
1052
- }
1053
- /**
1054
- * Format for zsh
1055
- *
1056
- * - Outputs value:description pairs for _describe
1057
- * - Colons in values/descriptions are escaped with backslash
1058
- * - Last line: :directive
1059
- */
1060
- function formatForZsh(result, _options) {
1061
- const lines = result.candidates.map((c) => {
1062
- const escapedValue = c.value.replace(/:/g, "\\:");
1063
- if (c.description) return `${escapedValue}:${c.description.replace(/:/g, "\\:")}`;
1064
- return escapedValue;
1065
- });
1066
- appendMetadata(lines, result);
1067
- return lines.join("\n");
1068
- }
1069
- /**
1070
- * Format for fish
1071
- *
1072
- * - Outputs value\tdescription pairs
1073
- * - Last line: :directive
1074
- */
1075
- function formatForFish(result, _options) {
1076
- const lines = result.candidates.map((c) => {
1077
- if (c.description) return `${c.value}\t${c.description}`;
1078
- return c.value;
1079
- });
1080
- appendMetadata(lines, result);
1081
- return lines.join("\n");
1082
- }
1083
-
1084
- //#endregion
1085
- //#region src/completion/dynamic/complete-command.ts
1086
- /**
1087
- * Dynamic completion command implementation
1088
- *
1089
- * This creates a hidden `__complete` command that outputs completion candidates
1090
- * for shell scripts to consume. Usage:
1091
- *
1092
- * mycli __complete --shell bash -- build --fo
1093
- * mycli __complete --shell zsh -- plugin add
1094
- *
1095
- * Output format depends on the target shell:
1096
- * bash: plain values (pre-filtered by prefix), last line :directive
1097
- * zsh: value:description pairs, last line :directive
1098
- * fish: value\tdescription pairs, last line :directive
1099
- */
1100
- /**
1101
- * Detect inline option-value prefix (e.g., "--format=" from "--format=json")
1102
- */
1103
- function detectInlinePrefix(currentWord) {
1104
- if (currentWord.startsWith("--") && currentWord.includes("=")) return currentWord.slice(0, currentWord.indexOf("=") + 1);
1105
- }
1106
- /**
1107
- * Schema for the __complete command
1108
- */
1109
- const completeArgsSchema = z.object({
1110
- shell: arg(z.enum([
1111
- "bash",
1112
- "zsh",
1113
- "fish"
1114
- ]), { description: "Target shell for output formatting" }),
1115
- args: arg(z.array(z.string()).default([]), {
1116
- positional: true,
1117
- description: "Arguments to complete",
1118
- variadic: true
1119
- })
1120
- });
1121
- /**
1122
- * Create the dynamic completion command
1123
- *
1124
- * @param rootCommand - The root command to generate completions for
1125
- * @param programName - The program name (optional, defaults to rootCommand.name)
1126
- * @returns A command that outputs completion candidates
1127
- */
1128
- function createDynamicCompleteCommand(rootCommand, _programName) {
1129
- return defineCommand({
1130
- name: "__complete",
1131
- args: completeArgsSchema,
1132
- run(args) {
1133
- const context = parseCompletionContext(args.args, rootCommand);
1134
- const result = generateCandidates(context);
1135
- const inlinePrefix = detectInlinePrefix(context.currentWord);
1136
- const output = formatForShell(result, {
1137
- shell: args.shell,
1138
- currentWord: inlinePrefix ? context.currentWord.slice(inlinePrefix.length) : context.currentWord,
1139
- inlinePrefix
1140
- });
1141
- console.log(output);
1142
- }
1143
- });
1144
- }
1145
- /**
1146
- * Check if a command tree contains the __complete command
1147
- */
1148
- function hasCompleteCommand(command) {
1149
- return Boolean(command.subCommands?.["__complete"]);
1150
- }
1151
-
1152
- //#endregion
1153
- //#region src/completion/fish.ts
1154
- /** Escape shell-special characters for fish double-quoted strings */
1155
- function escapeDesc$1(s) {
1156
- return s.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\$/g, "\\$");
1157
- }
1158
- /**
1159
- * Generate fish value completion lines for a ValueCompletion spec.
1160
- * Each line outputs candidates via echo (tab-separated value\tdescription).
1161
- */
1162
- function fishValueLines(vc) {
1163
- if (!vc) return [];
1164
- switch (vc.type) {
1165
- case "choices": return vc.choices.map((c) => `echo "${escapeDesc$1(c)}"`);
1166
- case "file":
1167
- if (vc.matcher?.length) return fishMatcherLines(vc.matcher);
1168
- if (vc.extensions?.length) return fishExtensionLines(vc.extensions);
1169
- return [`__fish_complete_path "$_cur"`];
1170
- case "directory": return [`__fish_complete_directories "$_cur"`];
1171
- case "command": return [
1172
- `for _v in (${vc.shellCommand})`,
1173
- ` echo "$_v"`,
1174
- `end`
1175
- ];
1176
- case "none": return [];
1177
- }
1178
- }
1179
- /** Generate fish matcher-filtered file completion */
1180
- function fishMatcherLines(patterns) {
1181
- return [
1182
- `__fish_complete_directories "$_cur"`,
1183
- `set -l _dir ""`,
1184
- `if string match -q '*/*' "$_cur"`,
1185
- ` set _dir (string replace -r '[^/]*$' '' "$_cur")`,
1186
- `end`,
1187
- ...patterns.flatMap((p) => [
1188
- `for _f in "$_dir"${p}`,
1189
- ` test -f "$_f"; and string match -q "$_cur*" "$_f"; and echo "$_f"`,
1190
- `end`
1191
- ])
1192
- ];
1193
- }
1194
- /** Generate fish extension-filtered file completion */
1195
- function fishExtensionLines(extensions) {
1196
- const lines = [];
1197
- lines.push(`__fish_complete_directories "$_cur"`);
1198
- for (const ext of extensions) {
1199
- lines.push(`for _f in "$_cur"*.${ext}`);
1200
- lines.push(` test -f "$_f"; and echo "$_f"`);
1201
- lines.push(`end`);
1202
- }
1203
- return lines;
1204
- }
1205
- /** Generate option-value switch cases for fish */
1206
- function optionValueCases$1(options) {
1207
- const lines = [];
1208
- for (const opt of options) {
1209
- if (!opt.takesValue || !opt.valueCompletion) continue;
1210
- const valLines = fishValueLines(opt.valueCompletion);
1211
- if (valLines.length === 0) continue;
1212
- const conditions = [`test "$_prev" = "--${opt.cliName}"`];
1213
- if (opt.alias) for (const a of opt.alias) conditions.push(`test "$_prev" = "${a.length === 1 ? `-${a}` : `--${a}`}"`);
1214
- const cond = conditions.join("; or ");
1215
- lines.push(` if ${cond}`);
1216
- for (const vl of valLines) lines.push(` ${vl}`);
1217
- lines.push(` return`);
1218
- lines.push(` end`);
1219
- }
1220
- return lines;
1221
- }
1222
- /** Generate positional completion block for fish */
1223
- function positionalBlock$1(positionals) {
1224
- if (positionals.length === 0) return [];
1225
- const lines = [];
1226
- for (const pos of positionals) {
1227
- const valLines = fishValueLines(pos.valueCompletion);
1228
- if (valLines.length === 0) continue;
1229
- if (pos.variadic) lines.push(` if test $_pos_count -ge ${pos.position}`);
1230
- else lines.push(` if test $_pos_count -eq ${pos.position}`);
1231
- for (const vl of valLines) lines.push(` ${vl}`);
1232
- lines.push(` return`);
1233
- lines.push(` end`);
1234
- }
1235
- return lines;
1236
- }
1237
- /** Generate available-option echo lines for fish */
1238
- function availableOptionLines$1(options, fn) {
1239
- const lines = [];
1240
- for (const opt of options) {
1241
- const desc = escapeDesc$1(opt.description ?? "");
1242
- if (opt.valueType === "array") lines.push(` echo "--${opt.cliName}\t${desc}"`);
1243
- else {
1244
- const checks = [`"--${opt.cliName}"`];
1245
- if (opt.alias) for (const a of opt.alias) checks.push(a.length === 1 ? `"-${a}"` : `"--${a}"`);
1246
- lines.push(` __${fn}_not_used ${checks.join(" ")}; and echo "--${opt.cliName}\t${desc}"`);
1247
- }
1248
- }
1249
- lines.push(` __${fn}_not_used "--help"; and echo "--help\tShow help"`);
1250
- return lines;
1251
- }
1252
- /** Generate value-option completion block if any value-taking options exist */
1253
- function valueCompletionBlock$1(options) {
1254
- if (!options.some((o) => o.takesValue && o.valueCompletion)) return [];
1255
- return optionValueCases$1(options);
1256
- }
1257
- /**
1258
- * Generate a per-subcommand completion function for fish.
1259
- * Recursively generates functions for nested subcommands.
1260
- */
1261
- function generateSubHandler$1(sub, fn, path) {
1262
- const fullPath = [...path, sub.name];
1263
- const funcName = `__${fn}_complete_${fullPath.map(sanitize).join("_")}`;
1264
- const visibleSubs = getVisibleSubs(sub.subcommands);
1265
- const lines = [];
1266
- for (const child of visibleSubs) lines.push(...generateSubHandler$1(child, fn, fullPath));
1267
- lines.push(`function ${funcName} --no-scope-shadowing`);
1268
- lines.push(...valueCompletionBlock$1(sub.options));
1269
- const fullPathStr = fullPath.join(":");
1270
- lines.push(` if __${fn}_opt_takes_value "${fullPathStr}" "$_prev"; return; end`);
1271
- if (sub.positionals.length > 0) {
1272
- lines.push(` if test $_after_dd -eq 1`);
1273
- lines.push(...positionalBlock$1(sub.positionals).map((l) => ` ${l}`));
1274
- lines.push(` return`);
1275
- lines.push(` end`);
1276
- } else lines.push(` if test $_after_dd -eq 1; return; end`);
1277
- lines.push(` if string match -q -- '-*' "$_cur"`);
1278
- lines.push(...availableOptionLines$1(sub.options, fn));
1279
- lines.push(` return`);
1280
- lines.push(` end`);
1281
- if (visibleSubs.length > 0) for (const s of getSubNamesWithAliases(sub.subcommands)) {
1282
- const desc = escapeDesc$1(s.description ?? "");
1283
- lines.push(` echo "${s.name}\t${desc}"`);
1284
- }
1285
- else if (sub.positionals.length > 0) lines.push(...positionalBlock$1(sub.positionals));
1286
- lines.push(`end`);
1287
- lines.push(``);
1288
- return lines;
1289
- }
1290
- /** Generate opt-takes-value entries for fish switch cases */
1291
- function optTakesValueCases(sub, parentPath) {
1292
- const lines = [];
1293
- for (const opt of sub.options) if (opt.takesValue) {
1294
- const patterns = [`"${parentPath}:--${opt.cliName}"`];
1295
- if (opt.alias) for (const a of opt.alias) patterns.push(`"${parentPath}:${a.length === 1 ? `-${a}` : `--${a}`}"`);
1296
- lines.push(` case ${patterns.join(" ")}`);
1297
- lines.push(` return 0`);
1298
- }
1299
- for (const child of getVisibleSubs(sub.subcommands)) {
1300
- const childPath = parentPath ? `${parentPath}:${child.name}` : child.name;
1301
- lines.push(...optTakesValueCases(child, childPath));
1302
- if (child.aliases) for (const alias of child.aliases) {
1303
- const aliasPath = parentPath ? `${parentPath}:${alias}` : alias;
1304
- lines.push(...optTakesValueCases(child, aliasPath));
1305
- }
1306
- }
1307
- return lines;
1308
- }
1309
- function generateFishCompletion(command, options) {
1310
- const { programName } = options;
1311
- const data = extractCompletionData(command, programName, options.globalArgsSchema);
1312
- const fn = sanitize(programName);
1313
- const root = data.command;
1314
- const visibleSubs = getVisibleSubs(root.subcommands);
1315
- const lines = [];
1316
- lines.push(`# Fish completion for ${programName}`);
1317
- lines.push(`# Generated by politty`);
1318
- lines.push(``);
1319
- lines.push(`function __${fn}_not_used --no-scope-shadowing`);
1320
- lines.push(` for _chk in $argv`);
1321
- lines.push(` if contains -- "$_chk" $_used_opts`);
1322
- lines.push(` return 1`);
1323
- lines.push(` end`);
1324
- lines.push(` end`);
1325
- lines.push(` return 0`);
1326
- lines.push(`end`);
1327
- lines.push(``);
1328
- lines.push(`function __${fn}_opt_takes_value`);
1329
- lines.push(` switch "$argv[1]:$argv[2]"`);
1330
- lines.push(...optTakesValueCases(root, ""));
1331
- lines.push(` end`);
1332
- lines.push(` return 1`);
1333
- lines.push(`end`);
1334
- lines.push(``);
1335
- const routeEntries = collectRouteEntries(root);
1336
- if (routeEntries.length > 0) {
1337
- lines.push(`function __${fn}_is_subcmd`);
1338
- lines.push(` switch "$argv[1]:$argv[2]"`);
1339
- for (const r of routeEntries) {
1340
- lines.push(` case "${r.lookupPattern}"`);
1341
- lines.push(` return 0`);
1342
- }
1343
- lines.push(` end`);
1344
- lines.push(` return 1`);
1345
- lines.push(`end`);
1346
- lines.push(``);
1347
- }
1348
- for (const sub of visibleSubs) lines.push(...generateSubHandler$1(sub, fn, []));
1349
- lines.push(`function __${fn}_complete_root --no-scope-shadowing`);
1350
- lines.push(...valueCompletionBlock$1(root.options));
1351
- lines.push(` if __${fn}_opt_takes_value "" "$_prev"; return; end`);
1352
- if (root.positionals.length > 0) {
1353
- lines.push(` if test $_after_dd -eq 1`);
1354
- lines.push(...positionalBlock$1(root.positionals).map((l) => ` ${l}`));
1355
- lines.push(` return`);
1356
- lines.push(` end`);
1357
- } else lines.push(` if test $_after_dd -eq 1; return; end`);
1358
- lines.push(` if string match -q -- '-*' "$_cur"`);
1359
- lines.push(...availableOptionLines$1(root.options, fn));
1360
- if (visibleSubs.length > 0) {
1361
- lines.push(` else`);
1362
- for (const s of getSubNamesWithAliases(root.subcommands)) {
1363
- const desc = escapeDesc$1(s.description ?? "");
1364
- lines.push(` echo "${s.name}\t${desc}"`);
1365
- }
1366
- } else if (root.positionals.length > 0) {
1367
- lines.push(` else`);
1368
- lines.push(...positionalBlock$1(root.positionals));
1369
- }
1370
- lines.push(` end`);
1371
- lines.push(`end`);
1372
- lines.push(``);
1373
- lines.push(`function __fish_${fn}_complete`);
1374
- lines.push(` set -l _args (commandline -opc)`);
1375
- lines.push(` set -e _args[1]`);
1376
- lines.push(``);
1377
- lines.push(` set -l _ct (commandline -ct)`);
1378
- lines.push(` if test (count $_ct) -eq 0`);
1379
- lines.push(` set -a _args ""`);
1380
- lines.push(` else`);
1381
- lines.push(` set -a _args $_ct`);
1382
- lines.push(` end`);
1383
- lines.push(``);
1384
- lines.push(` set -l _cur ""`);
1385
- lines.push(` if test (count $_args) -gt 0`);
1386
- lines.push(` set _cur "$_args[-1]"`);
1387
- lines.push(` end`);
1388
- lines.push(``);
1389
- lines.push(` set -l _prev ""`);
1390
- lines.push(` if test (count $_args) -gt 1`);
1391
- lines.push(` set _prev "$_args[-2]"`);
1392
- lines.push(` end`);
1393
- lines.push(``);
1394
- lines.push(` set -l _subcmd "" ; set -l _after_dd 0 ; set -l _pos_count 0 ; set -l _skip_next 0`);
1395
- lines.push(` set -l _used_opts`);
1396
- lines.push(``);
1397
- lines.push(` set -l _j 1`);
1398
- lines.push(` set -l _limit (math (count $_args) - 1)`);
1399
- lines.push(` while test $_j -le $_limit`);
1400
- lines.push(` set -l _w "$_args[$_j]"`);
1401
- lines.push(` if test $_skip_next -eq 1; set _skip_next 0; set _j (math $_j + 1); continue; end`);
1402
- lines.push(` if test "$_w" = "--"; set _after_dd 1; set _j (math $_j + 1); continue; end`);
1403
- lines.push(` if test $_after_dd -eq 1; set _pos_count (math $_pos_count + 1); set _j (math $_j + 1); continue; end`);
1404
- lines.push(` if string match -q -- '--*=*' "$_w"; set -a _used_opts (string replace -r '=.*' '' -- "$_w"); set _j (math $_j + 1); continue; end`);
1405
- lines.push(` if string match -q -- '-*' "$_w"`);
1406
- lines.push(` set -a _used_opts "$_w"`);
1407
- lines.push(` __${fn}_opt_takes_value "$_subcmd" "$_w"; and set _skip_next 1`);
1408
- lines.push(` set _j (math $_j + 1); continue`);
1409
- lines.push(` end`);
1410
- if (routeEntries.length > 0) lines.push(` if __${fn}_is_subcmd "$_subcmd" "$_w"; test -n "$_subcmd"; and set _subcmd "$_subcmd:$_w"; or set _subcmd "$_w"; set _used_opts; set _pos_count 0; else; set _pos_count (math $_pos_count + 1); end`);
1411
- else lines.push(` set _pos_count (math $_pos_count + 1)`);
1412
- lines.push(` set _j (math $_j + 1)`);
1413
- lines.push(` end`);
1414
- lines.push(``);
1415
- lines.push(` switch "$_subcmd"`);
1416
- for (const r of routeEntries) lines.push(` case "${r.pathStr}"; __${fn}_complete_${r.funcSuffix}`);
1417
- lines.push(` case '*'; __${fn}_complete_root`);
1418
- lines.push(` end`);
1419
- lines.push(`end`);
1420
- lines.push(``);
1421
- lines.push(`# Clear existing completions`);
1422
- lines.push(`complete -e -c ${programName}`);
1423
- lines.push(``);
1424
- lines.push(`# Register completion`);
1425
- lines.push(`complete -c ${programName} -f -a '(__fish_${fn}_complete)'`);
1426
- lines.push(``);
1427
- return {
1428
- script: lines.join("\n"),
1429
- shell: "fish",
1430
- installInstructions: `# To enable completions, run one of the following:
1431
-
1432
- # Option 1: Source directly
1433
- ${programName} completion fish | source
1434
-
1435
- # Option 2: Save to the fish completions directory
1436
- ${programName} completion fish > ~/.config/fish/completions/${programName}.fish
1437
-
1438
- # The completion will be available immediately in new shell sessions.
1439
- # To use in the current session, run:
1440
- source ~/.config/fish/completions/${programName}.fish`
1441
- };
1442
- }
1443
-
1444
- //#endregion
1445
- //#region src/completion/zsh.ts
1446
- function escapeDesc(s) {
1447
- return s.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\$/g, "\\$").replace(/`/g, "\\`").replace(/:/g, "\\:");
1448
- }
1449
- /**
1450
- * Generate zsh value completion lines for a ValueCompletion spec.
1451
- * Uses `_vals` array (must be declared in the calling function scope).
1452
- */
1453
- function zshValueLines(vc, fn) {
1454
- if (!vc) return [];
1455
- switch (vc.type) {
1456
- case "choices": return [`_vals=(${vc.choices.map((c) => `"${escapeDesc(c)}"`).join(" ")})`, `__${fn}_cdescribe 'completions' _vals`];
1457
- case "file":
1458
- if (vc.matcher?.length) return vc.matcher.map((p) => `_files -g "${p}"`);
1459
- if (vc.extensions?.length) return vc.extensions.map((ext) => `_files -g "*.${ext}"`);
1460
- return [`_files`];
1461
- case "directory": return [`_files -/`];
1462
- case "command": return [`_vals=("\${(@f)$(${vc.shellCommand})}")`, `__${fn}_cdescribe 'completions' _vals`];
1463
- case "none": return [];
1464
- }
1465
- }
1466
- /** Generate option-value case branches */
1467
- function optionValueCases(options, fn) {
1468
- const lines = [];
1469
- for (const opt of options) {
1470
- if (!opt.takesValue || !opt.valueCompletion) continue;
1471
- const valLines = zshValueLines(opt.valueCompletion, fn);
1472
- if (valLines.length === 0) continue;
1473
- const patterns = [`--${opt.cliName}`];
1474
- if (opt.alias) for (const a of opt.alias) patterns.push(a.length === 1 ? `-${a}` : `--${a}`);
1475
- lines.push(` ${patterns.join("|")})`);
1476
- for (const vl of valLines) lines.push(` ${vl}`);
1477
- lines.push(` return 0 ;;`);
1478
- }
1479
- return lines;
1480
- }
1481
- /** Generate positional completion block */
1482
- function positionalBlock(positionals, fn) {
1483
- if (positionals.length === 0) return [];
1484
- const lines = [];
1485
- lines.push(` case "$_pos_count" in`);
1486
- for (const pos of positionals) {
1487
- if (pos.variadic) lines.push(` ${pos.position}|*)`);
1488
- else lines.push(` ${pos.position})`);
1489
- const valLines = zshValueLines(pos.valueCompletion, fn);
1490
- for (const vl of valLines) lines.push(` ${vl}`);
1491
- lines.push(` ;;`);
1492
- }
1493
- lines.push(` esac`);
1494
- return lines;
1495
- }
1496
- /** Generate prev-word value completion case block */
1497
- function valueCompletionBlock(options, fn) {
1498
- if (!options.some((o) => o.takesValue && o.valueCompletion)) return [];
1499
- const prevCases = optionValueCases(options, fn);
1500
- if (prevCases.length === 0) return [];
1501
- return [
1502
- ` case "\${words[CURRENT-1]}" in`,
1503
- ...prevCases,
1504
- ` esac`
1505
- ];
1506
- }
1507
- /** Generate available-options list lines */
1508
- function availableOptionLines(options, fn) {
1509
- const lines = [];
1510
- for (const opt of options) {
1511
- const desc = opt.description ? `:${escapeDesc(opt.description)}` : "";
1512
- if (opt.valueType === "array") lines.push(` _opts+=("--${opt.cliName}${desc}")`);
1513
- else {
1514
- const patterns = [`"--${opt.cliName}"`];
1515
- if (opt.alias) for (const a of opt.alias) patterns.push(a.length === 1 ? `"-${a}"` : `"--${a}"`);
1516
- lines.push(` __${fn}_not_used ${patterns.join(" ")} && _opts+=("--${opt.cliName}${desc}")`);
1517
- }
1518
- }
1519
- lines.push(` __${fn}_not_used "--help" && _opts+=("--help:Show help")`);
1520
- return lines;
1521
- }
1522
- /**
1523
- * Generate a per-subcommand completion function.
1524
- * Recursively generates functions for nested subcommands.
1525
- */
1526
- function generateSubHandler(sub, fn, path) {
1527
- const fullPath = [...path, sub.name];
1528
- const funcName = `__${fn}_complete_${fullPath.map(sanitize).join("_")}`;
1529
- const visibleSubs = getVisibleSubs(sub.subcommands);
1530
- const lines = [];
1531
- for (const child of visibleSubs) lines.push(...generateSubHandler(child, fn, fullPath));
1532
- lines.push(`${funcName}() {`);
1533
- lines.push(` local -a _vals=()`);
1534
- lines.push(...valueCompletionBlock(sub.options, fn));
1535
- const fullPathStr = fullPath.join(":");
1536
- lines.push(` if __${fn}_opt_takes_value "${fullPathStr}" "\${words[CURRENT-1]}"; then return 0; fi`);
1537
- if (sub.positionals.length > 0) {
1538
- lines.push(` if (( _after_dd )); then`);
1539
- lines.push(...positionalBlock(sub.positionals, fn).map((l) => ` ${l}`));
1540
- lines.push(` return 0`);
1541
- lines.push(` fi`);
1542
- } else lines.push(` if (( _after_dd )); then return 0; fi`);
1543
- lines.push(` if [[ "\${words[CURRENT]}" == -* ]]; then`);
1544
- lines.push(` local -a _opts=()`);
1545
- lines.push(...availableOptionLines(sub.options, fn));
1546
- lines.push(` __${fn}_cdescribe 'options' _opts`);
1547
- lines.push(` return 0`);
1548
- lines.push(` fi`);
1549
- if (visibleSubs.length > 0) {
1550
- const subItems = getSubNamesWithAliases(sub.subcommands).map((s) => {
1551
- const desc = s.description ? `:${escapeDesc(s.description)}` : "";
1552
- return `"${s.name}${desc}"`;
1553
- }).join(" ");
1554
- lines.push(` local -a _subs=(${subItems})`);
1555
- lines.push(` __${fn}_cdescribe 'subcommands' _subs`);
1556
- } else if (sub.positionals.length > 0) lines.push(...positionalBlock(sub.positionals, fn));
1557
- lines.push(`}`);
1558
- lines.push(``);
1559
- return lines;
1560
- }
1561
- function generateZshCompletion(command, options) {
1562
- const { programName } = options;
1563
- const data = extractCompletionData(command, programName, options.globalArgsSchema);
1564
- const fn = sanitize(programName);
1565
- const root = data.command;
1566
- const visibleSubs = getVisibleSubs(root.subcommands);
1567
- const lines = [];
1568
- lines.push(`#compdef ${programName}`);
1569
- lines.push(``);
1570
- lines.push(`# Zsh completion for ${programName}`);
1571
- lines.push(`# Generated by politty`);
1572
- lines.push(``);
1573
- lines.push(`__${fn}_not_used() {`);
1574
- lines.push(` local _u _chk`);
1575
- lines.push(` for _u in "\${_used_opts[@]}"; do`);
1576
- lines.push(` for _chk in "$@"; do`);
1577
- lines.push(` [[ "$_u" == "$_chk" ]] && return 1`);
1578
- lines.push(` done`);
1579
- lines.push(` done`);
1580
- lines.push(` return 0`);
1581
- lines.push(`}`);
1582
- lines.push(``);
1583
- lines.push(`__${fn}_cdescribe() {`);
1584
- lines.push(` _describe "$@" 2>/dev/null && return 0`);
1585
- lines.push(` shift`);
1586
- lines.push(` local -a _cd_vals=("\${(@)\${(P)1}%%:*}")`);
1587
- lines.push(` compadd -a _cd_vals 2>/dev/null`);
1588
- lines.push(` return 0`);
1589
- lines.push(`}`);
1590
- lines.push(``);
1591
- lines.push(`__${fn}_opt_takes_value() {`);
1592
- lines.push(` case "$1:$2" in`);
1593
- lines.push(...optTakesValueEntries(root, ""));
1594
- lines.push(` esac`);
1595
- lines.push(` return 1`);
1596
- lines.push(`}`);
1597
- lines.push(``);
1598
- const routeEntries = collectRouteEntries(root);
1599
- if (routeEntries.length > 0) {
1600
- lines.push(`__${fn}_is_subcmd() {`);
1601
- lines.push(` case "$1:$2" in`);
1602
- lines.push(...isSubcmdCaseLines(routeEntries));
1603
- lines.push(` esac`);
1604
- lines.push(` return 1`);
1605
- lines.push(`}`);
1606
- lines.push(``);
1607
- }
1608
- for (const sub of visibleSubs) lines.push(...generateSubHandler(sub, fn, []));
1609
- lines.push(`__${fn}_complete_root() {`);
1610
- lines.push(` local -a _vals=()`);
1611
- lines.push(...valueCompletionBlock(root.options, fn));
1612
- lines.push(` if __${fn}_opt_takes_value "" "\${words[CURRENT-1]}"; then return 0; fi`);
1613
- if (root.positionals.length > 0) {
1614
- lines.push(` if (( _after_dd )); then`);
1615
- lines.push(...positionalBlock(root.positionals, fn).map((l) => ` ${l}`));
1616
- lines.push(` return 0`);
1617
- lines.push(` fi`);
1618
- } else lines.push(` if (( _after_dd )); then return 0; fi`);
1619
- lines.push(` if [[ "\${words[CURRENT]}" == -* ]]; then`);
1620
- lines.push(` local -a _opts=()`);
1621
- lines.push(...availableOptionLines(root.options, fn));
1622
- lines.push(` __${fn}_cdescribe 'options' _opts`);
1623
- if (visibleSubs.length > 0) {
1624
- lines.push(` else`);
1625
- const subItems = getSubNamesWithAliases(root.subcommands).map((s) => {
1626
- const desc = s.description ? `:${escapeDesc(s.description)}` : "";
1627
- return `"${s.name}${desc}"`;
1628
- }).join(" ");
1629
- lines.push(` local -a _subs=(${subItems})`);
1630
- lines.push(` __${fn}_cdescribe 'subcommands' _subs`);
1631
- } else if (root.positionals.length > 0) {
1632
- lines.push(` else`);
1633
- lines.push(...positionalBlock(root.positionals, fn).map((l) => ` ${l}`));
1634
- }
1635
- lines.push(` fi`);
1636
- lines.push(`}`);
1637
- lines.push(``);
1638
- const subRouting = routeEntries.map((r) => ` ${r.pathStr}) __${fn}_complete_${r.funcSuffix} ;;`).join("\n");
1639
- lines.push(`_${fn}() {`);
1640
- lines.push(` (( CURRENT )) || CURRENT=\${#words}`);
1641
- lines.push(``);
1642
- lines.push(` local _subcmd="" _after_dd=0 _pos_count=0 _skip_next=0`);
1643
- lines.push(` local -a _used_opts=()`);
1644
- lines.push(``);
1645
- lines.push(` local _j=2`);
1646
- lines.push(` while (( _j < CURRENT )); do`);
1647
- lines.push(` local _w="\${words[_j]}"`);
1648
- lines.push(` if (( _skip_next )); then _skip_next=0; (( _j++ )); continue; fi`);
1649
- lines.push(` if [[ "$_w" == "--" ]]; then _after_dd=1; (( _j++ )); continue; fi`);
1650
- lines.push(` if (( _after_dd )); then (( _pos_count++ )); (( _j++ )); continue; fi`);
1651
- lines.push(` if [[ "$_w" == --*=* ]]; then _used_opts+=("\${_w%%=*}"); (( _j++ )); continue; fi`);
1652
- lines.push(` if [[ "$_w" == -* ]]; then`);
1653
- lines.push(` _used_opts+=("$_w")`);
1654
- lines.push(` __${fn}_opt_takes_value "$_subcmd" "$_w" && _skip_next=1`);
1655
- lines.push(` (( _j++ )); continue`);
1656
- lines.push(` fi`);
1657
- if (routeEntries.length > 0) lines.push(` if __${fn}_is_subcmd "$_subcmd" "$_w"; then _subcmd="\${_subcmd:+\${_subcmd}:}$_w"; _used_opts=(); _pos_count=0; else (( _pos_count++ )); fi`);
1658
- else lines.push(` (( _pos_count++ ))`);
1659
- lines.push(` (( _j++ ))`);
1660
- lines.push(` done`);
1661
- lines.push(``);
1662
- lines.push(` case "$_subcmd" in`);
1663
- lines.push(subRouting);
1664
- lines.push(` *) __${fn}_complete_root ;;`);
1665
- lines.push(` esac`);
1666
- lines.push(`}`);
1667
- lines.push(``);
1668
- lines.push(`zstyle ':completion:*:*:${programName}:*' file-patterns '%p:globbed-files *(-/):directories'`);
1669
- lines.push(``);
1670
- lines.push(`compdef _${fn} ${programName}`);
1671
- lines.push(``);
1672
- return {
1673
- script: lines.join("\n"),
1674
- shell: "zsh",
1675
- installInstructions: `# To enable completions, add the following to your ~/.zshrc:
1676
-
1677
- # Option 1: Source directly (add before compinit)
1678
- eval "$(${programName} completion zsh)"
1679
-
1680
- # Option 2: Save to a file in your fpath
1681
- ${programName} completion zsh > ~/.zsh/completions/_${programName}
1682
-
1683
- # Make sure your fpath includes the completions directory:
1684
- # fpath=(~/.zsh/completions $fpath)
1685
- # autoload -Uz compinit && compinit
1686
-
1687
- # Then reload your shell or run:
1688
- source ~/.zshrc`
1689
- };
1690
- }
1691
-
1692
- //#endregion
1693
- //#region src/completion/index.ts
1694
- /**
1695
- * Shell completion generation module
1696
- *
1697
- * Provides utilities to generate shell completion scripts for bash, zsh, and fish.
1698
- *
1699
- * @example
1700
- * ```typescript
1701
- * import { generateCompletion, createCompletionCommand } from "politty/completion";
1702
- *
1703
- * // Generate completion script directly
1704
- * const result = generateCompletion(myCommand, {
1705
- * shell: "bash",
1706
- * programName: "mycli"
1707
- * });
1708
- * console.log(result.script);
1709
- *
1710
- * // Or add a completion subcommand to your CLI
1711
- * const mainCommand = withCompletionCommand(
1712
- * defineCommand({
1713
- * name: "mycli",
1714
- * subCommands: { ... },
1715
- * }),
1716
- * );
1717
- * ```
1718
- */
1719
- /**
1720
- * Generate completion script for the specified shell
1721
- */
1722
- function generateCompletion(command, options) {
1723
- switch (options.shell) {
1724
- case "bash": return generateBashCompletion(command, options);
1725
- case "zsh": return generateZshCompletion(command, options);
1726
- case "fish": return generateFishCompletion(command, options);
1727
- default: throw new Error(`Unsupported shell: ${options.shell}`);
1728
- }
1729
- }
1730
- /**
1731
- * Get the list of supported shells
1732
- */
1733
- function getSupportedShells() {
1734
- return [
1735
- "bash",
1736
- "zsh",
1737
- "fish"
1738
- ];
1739
- }
1740
- /**
1741
- * Detect the current shell from environment
1742
- */
1743
- function detectShell() {
1744
- const shellName = (process.env.SHELL || "").split("/").pop()?.toLowerCase() || "";
1745
- if (shellName.includes("bash")) return "bash";
1746
- if (shellName.includes("zsh")) return "zsh";
1747
- if (shellName.includes("fish")) return "fish";
1748
- return null;
1749
- }
1750
- /**
1751
- * Schema for the completion command arguments
1752
- */
1753
- const completionArgsSchema = z.object({
1754
- shell: arg(z.enum([
1755
- "bash",
1756
- "zsh",
1757
- "fish"
1758
- ]).optional().describe("Shell type (auto-detected if not specified)"), {
1759
- positional: true,
1760
- description: "Shell type (bash, zsh, or fish)",
1761
- placeholder: "SHELL"
1762
- }),
1763
- instructions: arg(z.boolean().default(false), {
1764
- alias: "i",
1765
- description: "Show installation instructions"
1766
- })
1767
- });
1768
- /**
1769
- * Create a completion subcommand for your CLI
1770
- *
1771
- * This creates a ready-to-use subcommand that generates completion scripts.
1772
- *
1773
- * @example
1774
- * ```typescript
1775
- * const mainCommand = defineCommand({
1776
- * name: "mycli",
1777
- * subCommands: {
1778
- * completion: createCompletionCommand(mainCommand)
1779
- * }
1780
- * });
1781
- * ```
1782
- */
1783
- function createCompletionCommand(rootCommand, programName, globalArgsSchema) {
1784
- const resolvedProgramName = programName ?? rootCommand.name;
1785
- if (!rootCommand.subCommands?.__complete) rootCommand.subCommands = {
1786
- ...rootCommand.subCommands,
1787
- __complete: createDynamicCompleteCommand(rootCommand, resolvedProgramName)
1788
- };
1789
- return defineCommand({
1790
- name: "completion",
1791
- description: "Generate shell completion script",
1792
- args: completionArgsSchema,
1793
- run(args) {
1794
- const shellType = args.shell || detectShell();
1795
- if (!shellType) {
1796
- console.error("Could not detect shell type. Please specify one of: bash, zsh, fish");
1797
- process.exitCode = 1;
1798
- return;
1799
- }
1800
- const result = generateCompletion(rootCommand, {
1801
- shell: shellType,
1802
- programName: resolvedProgramName,
1803
- includeDescriptions: true,
1804
- ...globalArgsSchema !== void 0 && { globalArgsSchema }
1805
- });
1806
- if (args.instructions) console.log(result.installInstructions);
1807
- else console.log(result.script);
1808
- }
1809
- });
1810
- }
1811
- /**
1812
- * Wrap a command with a completion subcommand
1813
- *
1814
- * This avoids circular references that occur when a command references itself
1815
- * in its subCommands (e.g., for completion generation).
1816
- *
1817
- * @param command - The command to wrap
1818
- * @param options - Options including programName
1819
- * @returns A new command with the completion subcommand added
1820
- *
1821
- * @example
1822
- * ```typescript
1823
- * const mainCommand = withCompletionCommand(
1824
- * defineCommand({
1825
- * name: "mycli",
1826
- * subCommands: { ... },
1827
- * }),
1828
- * );
1829
- * ```
1830
- */
1831
- function withCompletionCommand(command, options) {
1832
- const { programName, globalArgsSchema } = typeof options === "string" ? { programName: options } : options ?? {};
1833
- const wrappedCommand = { ...command };
1834
- wrappedCommand.subCommands = {
1835
- ...command.subCommands,
1836
- completion: createCompletionCommand(wrappedCommand, programName, globalArgsSchema),
1837
- __complete: createDynamicCompleteCommand(wrappedCommand, programName)
1838
- };
1839
- return wrappedCommand;
1840
- }
1841
-
1842
- //#endregion
1843
- export { withCompletionCommand as a, formatForShell as c, generateCandidates as d, extractCompletionData as f, defineCommand as g, createDefineCommand as h, getSupportedShells as i, parseCompletionContext as l, resolveValueCompletion as m, detectShell as n, createDynamicCompleteCommand as o, extractPositionals as p, generateCompletion as r, hasCompleteCommand as s, createCompletionCommand as t, CompletionDirective as u };
1844
- //# sourceMappingURL=completion-Ca5ESJlG.js.map