politty 0.4.16 → 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 (52) hide show
  1. package/dist/{arg-registry-MVWOAcvw.d.cts → arg-registry--NRaNFJM.d.cts} +123 -3
  2. package/dist/arg-registry--NRaNFJM.d.cts.map +1 -0
  3. package/dist/{arg-registry-Cd6xnjHa.d.ts → arg-registry-6E0WHOh_.d.ts} +123 -3
  4. package/dist/arg-registry-6E0WHOh_.d.ts.map +1 -0
  5. package/dist/augment.d.cts +1 -1
  6. package/dist/augment.d.ts +1 -1
  7. package/dist/completion/index.cjs +1 -1
  8. package/dist/completion/index.d.cts +3 -2
  9. package/dist/completion/index.d.ts +3 -2
  10. package/dist/completion/index.js +1 -1
  11. package/dist/completion-BA5JMvVG.js +4067 -0
  12. package/dist/completion-BA5JMvVG.js.map +1 -0
  13. package/dist/completion-Cqs1Ja7C.cjs +4169 -0
  14. package/dist/completion-Cqs1Ja7C.cjs.map +1 -0
  15. package/dist/docs/index.cjs +9 -9
  16. package/dist/docs/index.cjs.map +1 -1
  17. package/dist/docs/index.d.cts +1 -1
  18. package/dist/docs/index.d.ts +1 -1
  19. package/dist/docs/index.js +2 -2
  20. package/dist/{index-CPebddth.d.cts → index-DBMfKZ34.d.ts} +135 -15
  21. package/dist/index-DBMfKZ34.d.ts.map +1 -0
  22. package/dist/{index-DR9HLxIP.d.ts → index-DJp8k5Bq.d.cts} +135 -15
  23. package/dist/index-DJp8k5Bq.d.cts.map +1 -0
  24. package/dist/index.cjs +10 -10
  25. package/dist/index.d.cts +3 -3
  26. package/dist/index.d.ts +3 -3
  27. package/dist/index.js +3 -3
  28. package/dist/prompt/clack/index.d.cts +1 -1
  29. package/dist/prompt/clack/index.d.ts +1 -1
  30. package/dist/prompt/index.d.cts +1 -1
  31. package/dist/prompt/index.d.ts +1 -1
  32. package/dist/prompt/inquirer/index.d.cts +1 -1
  33. package/dist/prompt/inquirer/index.d.ts +1 -1
  34. package/dist/{runner-BHeCMEa5.js → runner-BmSEiD9A.js} +12 -9
  35. package/dist/{runner-BHeCMEa5.js.map → runner-BmSEiD9A.js.map} +1 -1
  36. package/dist/{runner-BcyR6Z8r.cjs → runner-CRZ_7Y9i.cjs} +56 -53
  37. package/dist/{runner-BcyR6Z8r.cjs.map → runner-CRZ_7Y9i.cjs.map} +1 -1
  38. package/dist/{subcommand-router-XZBWe8HN.js → schema-extractor-C50R-1re.js} +135 -135
  39. package/dist/schema-extractor-C50R-1re.js.map +1 -0
  40. package/dist/{subcommand-router-DQy0KZU-.cjs → schema-extractor-SLPgBNgZ.cjs} +134 -134
  41. package/dist/schema-extractor-SLPgBNgZ.cjs.map +1 -0
  42. package/package.json +5 -5
  43. package/dist/arg-registry-Cd6xnjHa.d.ts.map +0 -1
  44. package/dist/arg-registry-MVWOAcvw.d.cts.map +0 -1
  45. package/dist/completion-B04iiki9.js +0 -2338
  46. package/dist/completion-B04iiki9.js.map +0 -1
  47. package/dist/completion-BlZxMSeU.cjs +0 -2440
  48. package/dist/completion-BlZxMSeU.cjs.map +0 -1
  49. package/dist/index-CPebddth.d.cts.map +0 -1
  50. package/dist/index-DR9HLxIP.d.ts.map +0 -1
  51. package/dist/subcommand-router-DQy0KZU-.cjs.map +0 -1
  52. package/dist/subcommand-router-XZBWe8HN.js.map +0 -1
@@ -1,2338 +0,0 @@
1
- import { c as resolveSubCommandMeta, h as arg, i as resolveSubCommandAlias, l as extractFields, p as toCamelCase } from "./subcommand-router-XZBWe8HN.js";
2
- import { z } from "zod";
3
- import { existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
4
- import { dirname, join } from "node:path";
5
- import { execSync, spawn } from "node:child_process";
6
-
7
- //#region src/core/command.ts
8
- function defineCommand(config) {
9
- return {
10
- name: config.name,
11
- description: config.description,
12
- aliases: config.aliases,
13
- args: config.args,
14
- subCommands: config.subCommands,
15
- setup: config.setup,
16
- run: config.run,
17
- cleanup: config.cleanup,
18
- notes: config.notes,
19
- examples: config.examples
20
- };
21
- }
22
- /**
23
- * Create a typed defineCommand factory with pre-bound global args type.
24
- * This is the recommended pattern for type-safe global options.
25
- *
26
- * @example
27
- * ```ts
28
- * // global-args.ts
29
- * type GlobalArgsType = { verbose: boolean; config?: string };
30
- * export const defineAppCommand = createDefineCommand<GlobalArgsType>();
31
- *
32
- * // commands/build.ts
33
- * export const buildCommand = defineAppCommand({
34
- * name: "build",
35
- * args: z.object({ output: arg(z.string().default("dist")) }),
36
- * run: (args) => {
37
- * args.verbose; // typed via GlobalArgsType
38
- * args.output; // typed via local args
39
- * },
40
- * });
41
- * ```
42
- */
43
- function createDefineCommand() {
44
- return defineCommand;
45
- }
46
-
47
- //#endregion
48
- //#region src/completion/value-completion-resolver.ts
49
- /**
50
- * Resolve value completion from field metadata
51
- *
52
- * Priority:
53
- * 1. Explicit custom completion (choices or shellCommand)
54
- * 2. Explicit completion type (file, directory, none)
55
- * 3. Auto-detected enum values from schema
56
- */
57
- function resolveValueCompletion(field) {
58
- const meta = field.completion;
59
- if (meta?.custom) {
60
- if (meta.custom.choices && meta.custom.choices.length > 0) return {
61
- type: "choices",
62
- choices: meta.custom.choices
63
- };
64
- if (meta.custom.shellCommand) return {
65
- type: "command",
66
- shellCommand: meta.custom.shellCommand
67
- };
68
- }
69
- if (meta?.type) {
70
- if (meta.type === "file") {
71
- if (meta.matcher) return {
72
- type: "file",
73
- matcher: meta.matcher
74
- };
75
- if (meta.extensions) return {
76
- type: "file",
77
- extensions: meta.extensions
78
- };
79
- return { type: "file" };
80
- }
81
- if (meta.type === "directory") return { type: "directory" };
82
- if (meta.type === "none") return { type: "none" };
83
- }
84
- if (field.enumValues && field.enumValues.length > 0) return {
85
- type: "choices",
86
- choices: field.enumValues
87
- };
88
- }
89
-
90
- //#endregion
91
- //#region src/completion/extractor.ts
92
- /**
93
- * Extract completion data from commands
94
- */
95
- /**
96
- * Sanitize a name for use as a shell function/variable identifier.
97
- * Replaces any character that is not alphanumeric or underscore with underscore.
98
- *
99
- * Note: This is not injective -- distinct names may produce the same output
100
- * (e.g., "foo-bar" and "foo_bar" both become "foo_bar"). When used for nested
101
- * path encoding (`path.map(sanitize).join("_")`), cross-level collisions are
102
- * theoretically possible (e.g., "foo-bar:baz" vs "foo:bar-baz") but extremely
103
- * unlikely in real CLI designs. If collision-safety is needed, sanitize must be
104
- * replaced with an injective encoding.
105
- */
106
- function sanitize(name) {
107
- return name.replace(/[^a-zA-Z0-9_]/g, "_");
108
- }
109
- /**
110
- * Filter subcommands to only visible (non-internal) ones.
111
- * Internal subcommands start with "__" and are hidden from completion/help.
112
- */
113
- function getVisibleSubs(subs) {
114
- return subs.filter((s) => !s.name.startsWith("__"));
115
- }
116
- /**
117
- * Get all completable subcommand names including aliases.
118
- * Returns an array of { name, description } for all visible subcommands
119
- * and their aliases.
120
- */
121
- function getSubNamesWithAliases(subs) {
122
- const result = [];
123
- for (const sub of getVisibleSubs(subs)) {
124
- result.push({
125
- name: sub.name,
126
- description: sub.description
127
- });
128
- if (sub.aliases) for (const alias of sub.aliases) result.push({
129
- name: alias,
130
- description: sub.description
131
- });
132
- }
133
- return result;
134
- }
135
- /**
136
- * Convert a resolved field to a completable option
137
- */
138
- function fieldToOption(field) {
139
- return {
140
- name: field.name,
141
- cliName: field.cliName,
142
- alias: field.alias,
143
- negation: field.negationDisplay,
144
- negationDescription: field.negationDescription,
145
- description: field.description,
146
- takesValue: field.type !== "boolean",
147
- valueType: field.type,
148
- required: field.required,
149
- valueCompletion: resolveValueCompletion(field)
150
- };
151
- }
152
- /**
153
- * Extract options from a command's args schema
154
- */
155
- function extractOptions$1(command) {
156
- if (!command.args) return [];
157
- return extractFields(command.args).fields.filter((field) => !field.positional).map(fieldToOption);
158
- }
159
- /**
160
- * Extract positional arguments from a command
161
- */
162
- function extractPositionals(command) {
163
- if (!command.args) return [];
164
- return extractFields(command.args).fields.filter((field) => field.positional);
165
- }
166
- /**
167
- * Extract completable positional arguments from a command
168
- */
169
- function extractCompletablePositionals(command) {
170
- if (!command.args) return [];
171
- return extractFields(command.args).fields.filter((field) => field.positional).map((field, index) => ({
172
- name: field.name,
173
- cliName: field.cliName,
174
- position: index,
175
- description: field.description,
176
- required: field.required,
177
- variadic: field.type === "array",
178
- valueCompletion: resolveValueCompletion(field)
179
- }));
180
- }
181
- /**
182
- * Extract a completable subcommand from a command
183
- */
184
- function extractSubcommand(name, command) {
185
- const subcommands = [];
186
- if (command.subCommands) for (const [subName, subCommand] of Object.entries(command.subCommands)) {
187
- const resolved = resolveSubCommandMeta(subCommand);
188
- if (resolved) subcommands.push(extractSubcommand(subName, resolved));
189
- else subcommands.push({
190
- name: subName,
191
- description: "(lazy loaded)",
192
- subcommands: [],
193
- options: [],
194
- positionals: []
195
- });
196
- }
197
- return {
198
- name,
199
- description: command.description,
200
- aliases: command.aliases,
201
- subcommands,
202
- options: extractOptions$1(command),
203
- positionals: extractCompletablePositionals(command)
204
- };
205
- }
206
- /** Join parent and child with a separator, omitting separator when parent is empty. */
207
- function joinPrefix(parent, child, sep) {
208
- return parent ? `${parent}${sep}${child}` : child;
209
- }
210
- /**
211
- * Collect opt-takes-value case entries for a subcommand tree.
212
- * Used by bash and zsh generators (identical case syntax: `path:--opt) return 0 ;;`).
213
- * parentPath is a colon-delimited path (e.g., "" for root, "workspace:user" for nested).
214
- */
215
- function optTakesValueEntries(sub, parentPath) {
216
- const lines = [];
217
- for (const opt of sub.options) if (opt.takesValue) {
218
- const patterns = [`${parentPath}:--${opt.cliName}`];
219
- if (opt.alias) for (const a of opt.alias) patterns.push(`${parentPath}:${a.length === 1 ? `-${a}` : `--${a}`}`);
220
- lines.push(` ${patterns.join("|")}) return 0 ;;`);
221
- }
222
- for (const child of getVisibleSubs(sub.subcommands)) {
223
- lines.push(...optTakesValueEntries(child, joinPrefix(parentPath, child.name, ":")));
224
- if (child.aliases) for (const alias of child.aliases) lines.push(...optTakesValueEntries(child, joinPrefix(parentPath, alias, ":")));
225
- }
226
- return lines;
227
- }
228
- /**
229
- * Recursively collect all subcommand route entries.
230
- * Returns entries used by all shell generators for both dispatch routing
231
- * and subcommand lookup (is_subcmd) tables.
232
- * Aliases are mapped to the same handler as the canonical name.
233
- */
234
- function collectRouteEntries(sub, parentPath = "", parentFunc = "") {
235
- const entries = [];
236
- for (const child of getVisibleSubs(sub.subcommands)) {
237
- const pathStr = joinPrefix(parentPath, child.name, ":");
238
- const funcSuffix = joinPrefix(parentFunc, sanitize(child.name), "_");
239
- entries.push(...collectRouteEntries(child, pathStr, funcSuffix));
240
- entries.push({
241
- pathStr,
242
- funcSuffix,
243
- lookupPattern: `${parentPath}:${child.name}`
244
- });
245
- if (child.aliases) for (const alias of child.aliases) {
246
- const aliasPathStr = joinPrefix(parentPath, alias, ":");
247
- entries.push(...collectRouteEntries(child, aliasPathStr, funcSuffix));
248
- entries.push({
249
- pathStr: aliasPathStr,
250
- funcSuffix,
251
- lookupPattern: `${parentPath}:${alias}`
252
- });
253
- }
254
- }
255
- return entries;
256
- }
257
- /**
258
- * Generate is_subcmd case/switch body lines (bash/zsh case syntax).
259
- * Returns lines for the case statement body only (caller wraps in function).
260
- */
261
- function isSubcmdCaseLines(routeEntries) {
262
- return routeEntries.map((r) => ` ${r.lookupPattern}) return 0 ;;`);
263
- }
264
- /**
265
- * Recursively merge global options into a subcommand and all its descendants.
266
- * Avoids duplicates by checking existing option names.
267
- */
268
- function propagateGlobalOptions(sub, globalOptions) {
269
- const existingNames = new Set(sub.options.map((o) => o.name));
270
- const newOpts = globalOptions.filter((o) => !existingNames.has(o.name));
271
- sub.options = [...sub.options, ...newOpts];
272
- for (const child of sub.subcommands) propagateGlobalOptions(child, globalOptions);
273
- }
274
- /**
275
- * Extract completion data from a command tree
276
- *
277
- * @param command - The root command
278
- * @param programName - Program name for completion scripts
279
- * @param globalArgsSchema - Optional global args schema. When provided, global options
280
- * are derived from this schema instead of the root command's options.
281
- */
282
- function extractCompletionData(command, programName, globalArgsSchema) {
283
- const rootSubcommand = extractSubcommand(programName, command);
284
- let globalOptions;
285
- if (globalArgsSchema) {
286
- globalOptions = extractFields(globalArgsSchema).fields.filter((field) => !field.positional).map(fieldToOption);
287
- propagateGlobalOptions(rootSubcommand, globalOptions);
288
- } else globalOptions = rootSubcommand.options;
289
- return {
290
- command: rootSubcommand,
291
- programName,
292
- globalOptions
293
- };
294
- }
295
-
296
- //#endregion
297
- //#region src/completion/header.ts
298
- /**
299
- * Static-script header utilities.
300
- *
301
- * Every completion script generated by politty starts with a small
302
- * machine-readable header. The rc loader and the runMain background
303
- * refresh path use the `# politty-bin-sig:` line to detect when the
304
- * cached script is stale relative to the binary on disk.
305
- */
306
- /** Schema version of the header itself. Bump when the header layout changes. */
307
- const COMPLETION_VERSION = 1;
308
- /**
309
- * Read the binary's mtime in whole seconds (matches POSIX `stat -c %Y` /
310
- * BSD `stat -f %m`). Returns `"0"` on failure so the header is always
311
- * well-formed.
312
- */
313
- function computeBinSig(binPath) {
314
- try {
315
- return Math.floor(statSync(binPath).mtimeMs / 1e3).toString();
316
- } catch {
317
- return "0";
318
- }
319
- }
320
- /**
321
- * Walk `$PATH` looking for an executable named `programName`. Returns
322
- * the first match's full path, or `null` when not found. We mirror the
323
- * shell's `command -v <prog>` here so the sig embedded in the header
324
- * (computed by Node) lines up with what the rc loader stat-checks at
325
- * runtime — including pnpm/npm bin shims that wrap the real entrypoint.
326
- * Without this alignment, shimmed installs would never match the
327
- * embedded sig and the cache would regenerate on every shell startup.
328
- */
329
- function findOnPath(programName) {
330
- if (!programName || /[/\\\0]/.test(programName)) return null;
331
- const path = process.env.PATH ?? "";
332
- for (const dir of path.split(":")) {
333
- if (!dir) continue;
334
- const candidate = join(dir, programName);
335
- try {
336
- if (statSync(candidate).isFile()) return candidate;
337
- } catch {}
338
- }
339
- return null;
340
- }
341
- /**
342
- * Resolve the binary path used for sig computation and stat checks.
343
- *
344
- * Order: explicit override → `$PATH` lookup of `programName` → `process.argv[1]`.
345
- * The `$PATH` lookup keeps Node-side and shell-side stats pointed at the
346
- * same shim file when the CLI is invoked through a package-manager bin shim.
347
- */
348
- function resolveBinPath(programName, override) {
349
- if (override) return override;
350
- return findOnPath(programName) ?? process.argv[1] ?? "";
351
- }
352
- /**
353
- * Build the header lines (no trailing blank line). Returned without a
354
- * leading `#!` so each generator can prepend its own shebang/compdef
355
- * marker.
356
- */
357
- function buildHeaderLines(opts) {
358
- const sig = computeBinSig(resolveBinPath(opts.programName, opts.binPath));
359
- const lines = [
360
- `# politty-completion-version: ${1}`,
361
- `# politty-bin-sig: ${sig}`,
362
- `# program: ${opts.programName}`
363
- ];
364
- if (opts.programVersion) lines.push(`# program-version: ${opts.programVersion}`);
365
- lines.push(`# shell: ${opts.shell}`);
366
- return lines;
367
- }
368
-
369
- //#endregion
370
- //#region src/completion/bash.ts
371
- /** Escape a string for use inside bash double-quotes */
372
- function escapeBashDQ(s) {
373
- return s.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\$/g, "\\$").replace(/`/g, "\\`");
374
- }
375
- /**
376
- * Generate bash value completion code for a ValueCompletion spec.
377
- * Returns an array of bash lines.
378
- */
379
- function bashValueLines(vc, inline) {
380
- if (!vc) return [];
381
- switch (vc.type) {
382
- case "choices": {
383
- const items = vc.choices.map((c) => `"${escapeBashDQ(c)}"`).join(" ");
384
- if (inline) return [
385
- `local -a _choices=(${items})`,
386
- `COMPREPLY=()`,
387
- `local _c; for _c in "\${_choices[@]}"; do [[ "$_c" == "$_cur"* ]] && COMPREPLY+=("\${_inline_prefix}\${_c}"); done`,
388
- `compopt -o nospace`,
389
- `compopt +o default 2>/dev/null`
390
- ];
391
- return [
392
- `local -a _choices=(${items})`,
393
- `COMPREPLY=()`,
394
- `local _c; for _c in "\${_choices[@]}"; do [[ "$_c" == "$_cur"* ]] && COMPREPLY+=("$_c"); done`,
395
- `compopt +o default 2>/dev/null`
396
- ];
397
- }
398
- case "file":
399
- if (vc.matcher?.length) return bashFileFilter(vc.matcher.map((p) => `[[ "\${_f##*/}" == ${p} ]]`).join(" || "), inline);
400
- if (vc.extensions?.length) return bashFileFilter(vc.extensions.map((ext) => `[[ "$_f" == *".${ext}" ]]`).join(" || "), inline);
401
- if (inline) return [
402
- `local -a _entries=($(compgen -f -- "$_cur"))`,
403
- `COMPREPLY=("\${_entries[@]/#/$_inline_prefix}")`,
404
- `compopt -o filenames`
405
- ];
406
- return [`COMPREPLY=($(compgen -f -- "$_cur"))`, `compopt -o filenames`];
407
- case "directory":
408
- if (inline) return [
409
- `local -a _dirs=($(compgen -d -- "$_cur"))`,
410
- `COMPREPLY=("\${_dirs[@]/#/$_inline_prefix}")`,
411
- `compopt -o filenames`
412
- ];
413
- return [`COMPREPLY=($(compgen -d -- "$_cur"))`, `compopt -o filenames`];
414
- case "command": {
415
- const cmd = vc.shellCommand;
416
- if (inline) return [`COMPREPLY=($(compgen -P "$_inline_prefix" -W "$(${cmd})" -- "$_cur"))`];
417
- return [`COMPREPLY=($(compgen -W "$(${cmd})" -- "$_cur"))`];
418
- }
419
- case "none": return [`compopt +o default 2>/dev/null`];
420
- }
421
- }
422
- function bashFileFilter(checks, inline) {
423
- const prefix = inline ? `"\${_inline_prefix}$_f"` : `"$_f"`;
424
- return [
425
- `local -a _all_entries=($(compgen -f -- "$_cur"))`,
426
- `for _f in "\${_all_entries[@]}"; do`,
427
- ` if [[ -d "$_f" ]]; then`,
428
- ` COMPREPLY+=(${prefix})`,
429
- ` elif ${checks}; then`,
430
- ` COMPREPLY+=(${prefix})`,
431
- ` fi`,
432
- `done`,
433
- `compopt -o filenames`,
434
- `compopt +o default 2>/dev/null`
435
- ];
436
- }
437
- /** Collect value-taking option patterns for case matching */
438
- function optionValueCases$2(options, inline) {
439
- const lines = [];
440
- for (const opt of options) {
441
- if (!opt.takesValue || !opt.valueCompletion) continue;
442
- const valLines = bashValueLines(opt.valueCompletion, inline);
443
- if (valLines.length === 0) continue;
444
- const patterns = [`--${opt.cliName}`];
445
- if (opt.alias) for (const a of opt.alias) patterns.push(a.length === 1 ? `-${a}` : `--${a}`);
446
- const patternStr = patterns.join("|");
447
- lines.push(` ${patternStr})`);
448
- for (const vl of valLines) lines.push(` ${vl}`);
449
- lines.push(` return ;;`);
450
- }
451
- return lines;
452
- }
453
- /** Generate positional completion block */
454
- function positionalBlock$2(positionals) {
455
- if (positionals.length === 0) return [];
456
- const lines = [];
457
- lines.push(` case "$_pos_count" in`);
458
- for (const pos of positionals) {
459
- if (pos.variadic) lines.push(` ${pos.position}|*)`);
460
- else lines.push(` ${pos.position})`);
461
- for (const vl of bashValueLines(pos.valueCompletion, false)) lines.push(` ${vl}`);
462
- lines.push(` ;;`);
463
- }
464
- lines.push(` esac`);
465
- return lines;
466
- }
467
- /** Generate prev/inline value completion blocks for options */
468
- function valueCompletionBlocks(options) {
469
- if (!options.some((o) => o.takesValue && o.valueCompletion)) return [];
470
- const lines = [];
471
- const prevCases = optionValueCases$2(options, false);
472
- if (prevCases.length > 0) {
473
- lines.push(` if [[ -z "$_inline_prefix" ]]; then`);
474
- lines.push(` case "$_prev" in`);
475
- lines.push(...prevCases);
476
- lines.push(` esac`);
477
- lines.push(` fi`);
478
- }
479
- const inlineCases = optionValueCases$2(options, true);
480
- if (inlineCases.length > 0) {
481
- lines.push(` if [[ -n "$_inline_prefix" ]]; then`);
482
- lines.push(` case "\${_inline_prefix%=}" in`);
483
- lines.push(...inlineCases);
484
- lines.push(` esac`);
485
- lines.push(` fi`);
486
- }
487
- return lines;
488
- }
489
- /** Generate available-options list lines */
490
- function availableOptionLines$2(options, fn) {
491
- const lines = [];
492
- for (const opt of options) if (opt.valueType === "array") lines.push(` _avail+=(--${opt.cliName})`);
493
- else {
494
- const patterns = [`"--${opt.cliName}"`];
495
- if (opt.alias) for (const a of opt.alias) patterns.push(a.length === 1 ? `"-${a}"` : `"--${a}"`);
496
- if (opt.negation) patterns.push(`"--${opt.negation}"`);
497
- lines.push(` __${fn}_not_used ${patterns.join(" ")} && _avail+=(--${opt.cliName})`);
498
- if (opt.negation) lines.push(` __${fn}_not_used ${patterns.join(" ")} && _avail+=(--${opt.negation})`);
499
- }
500
- lines.push(` __${fn}_not_used "--help" && _avail+=(--help)`);
501
- return lines;
502
- }
503
- /**
504
- * Generate a per-subcommand completion function.
505
- * Recursively generates functions for nested subcommands.
506
- */
507
- function generateSubHandler$2(sub, fn, path) {
508
- const fullPath = [...path, sub.name];
509
- const funcName = `__${fn}_complete_${fullPath.map(sanitize).join("_")}`;
510
- const visibleSubs = getVisibleSubs(sub.subcommands);
511
- const lines = [];
512
- for (const child of visibleSubs) lines.push(...generateSubHandler$2(child, fn, fullPath));
513
- lines.push(`${funcName}() {`);
514
- lines.push(...valueCompletionBlocks(sub.options));
515
- const fullPathStr = fullPath.join(":");
516
- lines.push(` if [[ -z "$_inline_prefix" ]] && __${fn}_opt_takes_value "${fullPathStr}" "$_prev"; then return; fi`);
517
- lines.push(` if [[ -n "$_inline_prefix" ]] && __${fn}_opt_takes_value "${fullPathStr}" "\${_inline_prefix%=}"; then return; fi`);
518
- if (sub.positionals.length > 0) {
519
- lines.push(` if (( _after_dd )); then`);
520
- lines.push(...positionalBlock$2(sub.positionals).map((l) => ` ${l}`));
521
- lines.push(` return`);
522
- lines.push(` fi`);
523
- } else lines.push(` if (( _after_dd )); then return; fi`);
524
- lines.push(` if [[ "$_cur" == -* ]]; then`);
525
- lines.push(` local -a _avail=()`);
526
- lines.push(...availableOptionLines$2(sub.options, fn));
527
- lines.push(` COMPREPLY=($(compgen -W "\${_avail[*]}" -- "$_cur"))`);
528
- lines.push(` compopt +o default 2>/dev/null`);
529
- lines.push(` return`);
530
- lines.push(` fi`);
531
- if (visibleSubs.length > 0) {
532
- const subNames = getSubNamesWithAliases(sub.subcommands).map((s) => s.name).join(" ");
533
- lines.push(` COMPREPLY=($(compgen -W "${subNames}" -- "$_cur"))`);
534
- lines.push(` compopt +o default 2>/dev/null`);
535
- } else if (sub.positionals.length > 0) lines.push(...positionalBlock$2(sub.positionals));
536
- lines.push(`}`);
537
- lines.push(``);
538
- return lines;
539
- }
540
- function generateBashCompletion(command, options) {
541
- const { programName } = options;
542
- const data = extractCompletionData(command, programName, options.globalArgsSchema);
543
- const fn = sanitize(programName);
544
- const root = data.command;
545
- const visibleSubs = getVisibleSubs(root.subcommands);
546
- const lines = [];
547
- lines.push(...buildHeaderLines({
548
- programName,
549
- shell: "bash",
550
- binPath: options.binPath,
551
- programVersion: options.programVersion
552
- }));
553
- lines.push(`# Generated by politty`);
554
- lines.push(``);
555
- lines.push(`__${fn}_not_used() {`);
556
- lines.push(` for _u in "\${_used_opts[@]}"; do`);
557
- lines.push(` for _chk in "$@"; do`);
558
- lines.push(` [[ "$_u" == "$_chk" ]] && return 1`);
559
- lines.push(` done`);
560
- lines.push(` done`);
561
- lines.push(` return 0`);
562
- lines.push(`}`);
563
- lines.push(``);
564
- lines.push(`__${fn}_opt_takes_value() {`);
565
- lines.push(` case "$1:$2" in`);
566
- lines.push(...optTakesValueEntries(root, ""));
567
- lines.push(` esac`);
568
- lines.push(` return 1`);
569
- lines.push(`}`);
570
- lines.push(``);
571
- const routeEntries = collectRouteEntries(root);
572
- if (routeEntries.length > 0) {
573
- lines.push(`__${fn}_is_subcmd() {`);
574
- lines.push(` case "$1:$2" in`);
575
- lines.push(...isSubcmdCaseLines(routeEntries));
576
- lines.push(` esac`);
577
- lines.push(` return 1`);
578
- lines.push(`}`);
579
- lines.push(``);
580
- }
581
- for (const sub of visibleSubs) lines.push(...generateSubHandler$2(sub, fn, []));
582
- lines.push(`__${fn}_complete_root() {`);
583
- lines.push(...valueCompletionBlocks(root.options));
584
- lines.push(` if [[ -z "$_inline_prefix" ]] && __${fn}_opt_takes_value "" "$_prev"; then return; fi`);
585
- lines.push(` if [[ -n "$_inline_prefix" ]] && __${fn}_opt_takes_value "" "\${_inline_prefix%=}"; then return; fi`);
586
- if (root.positionals.length > 0) {
587
- lines.push(` if (( _after_dd )); then`);
588
- lines.push(...positionalBlock$2(root.positionals).map((l) => ` ${l}`));
589
- lines.push(` return`);
590
- lines.push(` fi`);
591
- } else lines.push(` if (( _after_dd )); then return; fi`);
592
- lines.push(` if [[ "$_cur" == -* ]]; then`);
593
- lines.push(` local -a _avail=()`);
594
- lines.push(...availableOptionLines$2(root.options, fn));
595
- lines.push(` COMPREPLY=($(compgen -W "\${_avail[*]}" -- "$_cur"))`);
596
- lines.push(` compopt +o default 2>/dev/null`);
597
- if (visibleSubs.length > 0) {
598
- lines.push(` else`);
599
- const subNames = getSubNamesWithAliases(root.subcommands).map((s) => s.name).join(" ");
600
- lines.push(` COMPREPLY=($(compgen -W "${subNames}" -- "$_cur"))`);
601
- lines.push(` compopt +o default 2>/dev/null`);
602
- } else if (root.positionals.length > 0) {
603
- lines.push(` else`);
604
- lines.push(...positionalBlock$2(root.positionals).map((l) => ` ${l}`));
605
- }
606
- lines.push(` fi`);
607
- lines.push(`}`);
608
- lines.push(``);
609
- const subRouting = routeEntries.map((r) => ` ${r.pathStr}) __${fn}_complete_${r.funcSuffix} ;;`).join("\n");
610
- lines.push(`_${fn}_completions() {`);
611
- lines.push(` COMPREPLY=()`);
612
- lines.push(``);
613
- lines.push(` # Rejoin words split by '=' in COMP_WORDBREAKS`);
614
- lines.push(` local -a _words=()`);
615
- lines.push(` local _i=1`);
616
- lines.push(` while (( _i <= COMP_CWORD )); do`);
617
- lines.push(` if [[ "\${COMP_WORDS[_i]}" == "=" && \${#_words[@]} -gt 0 ]]; then`);
618
- lines.push(` _words[\${#_words[@]}-1]+="=\${COMP_WORDS[_i+1]:-}"`);
619
- lines.push(` (( _i += 2 ))`);
620
- lines.push(` else`);
621
- lines.push(` _words+=("\${COMP_WORDS[_i]}")`);
622
- lines.push(` (( _i++ ))`);
623
- lines.push(` fi`);
624
- lines.push(` done`);
625
- lines.push(``);
626
- lines.push(` local _cur=""`);
627
- lines.push(` (( \${#_words[@]} > 0 )) && _cur="\${_words[\${#_words[@]}-1]}"`);
628
- lines.push(``);
629
- lines.push(` local _inline_prefix=""`);
630
- lines.push(` if [[ "$_cur" == --*=* ]]; then`);
631
- lines.push(` _inline_prefix="\${_cur%%=*}="`);
632
- lines.push(` _cur="\${_cur#*=}"`);
633
- lines.push(` fi`);
634
- lines.push(``);
635
- lines.push(` local _prev=""`);
636
- lines.push(` (( \${#_words[@]} > 1 )) && _prev="\${_words[\${#_words[@]}-2]}"`);
637
- lines.push(``);
638
- lines.push(` local _subcmd="" _after_dd=0 _pos_count=0 _skip_next=0`);
639
- lines.push(` local -a _used_opts=()`);
640
- lines.push(``);
641
- lines.push(` local _j=0`);
642
- lines.push(` while (( _j < \${#_words[@]} - 1 )); do`);
643
- lines.push(` local _w="\${_words[_j]}"`);
644
- lines.push(` if (( _skip_next )); then _skip_next=0; (( _j++ )); continue; fi`);
645
- lines.push(` if [[ "$_w" == "--" ]]; then _after_dd=1; (( _j++ )); continue; fi`);
646
- lines.push(` if (( _after_dd )); then (( _pos_count++ )); (( _j++ )); continue; fi`);
647
- lines.push(` if [[ "$_w" == --*=* ]]; then _used_opts+=("\${_w%%=*}"); (( _j++ )); continue; fi`);
648
- lines.push(` if [[ "$_w" == -* ]]; then`);
649
- lines.push(` _used_opts+=("$_w")`);
650
- lines.push(` __${fn}_opt_takes_value "$_subcmd" "$_w" && _skip_next=1`);
651
- lines.push(` (( _j++ )); continue`);
652
- lines.push(` fi`);
653
- 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`);
654
- else lines.push(` (( _pos_count++ ))`);
655
- lines.push(` (( _j++ ))`);
656
- lines.push(` done`);
657
- lines.push(``);
658
- lines.push(` case "$_subcmd" in`);
659
- lines.push(subRouting);
660
- lines.push(` *) __${fn}_complete_root ;;`);
661
- lines.push(` esac`);
662
- lines.push(`}`);
663
- lines.push(``);
664
- lines.push(`complete -o default -F _${fn}_completions ${programName}`);
665
- lines.push(``);
666
- return {
667
- script: lines.join("\n"),
668
- shell: "bash",
669
- installInstructions: `# To enable completions, add the following to your ~/.bashrc:
670
-
671
- # Option 1: Source directly
672
- eval "$(${programName} completion bash)"
673
-
674
- # Option 2: Save to a file
675
- ${programName} completion bash > ~/.local/share/bash-completion/completions/${programName}
676
-
677
- # Then reload your shell or run:
678
- source ~/.bashrc`
679
- };
680
- }
681
-
682
- //#endregion
683
- //#region src/completion/dynamic/candidate-generator.ts
684
- /**
685
- * Generate completion candidates based on context
686
- */
687
- /**
688
- * Completion directive flags (bitwise)
689
- */
690
- const CompletionDirective = {
691
- /** Default completion behavior */
692
- Default: 0,
693
- /** Don't add space after completion */
694
- NoSpace: 1,
695
- /** Don't offer file completion (even if no other completions) */
696
- NoFileCompletion: 2,
697
- /** Filter completions using current word as prefix */
698
- FilterPrefix: 4,
699
- /** Keep the order of completions */
700
- KeepOrder: 8,
701
- /** Trigger file completion */
702
- FileCompletion: 16,
703
- /** Trigger directory completion */
704
- DirectoryCompletion: 32,
705
- /** Error occurred during completion */
706
- Error: 64
707
- };
708
- /**
709
- * Generate completion candidates based on context
710
- */
711
- function generateCandidates(context) {
712
- const candidates = [];
713
- let directive = CompletionDirective.Default;
714
- switch (context.completionType) {
715
- case "subcommand": return generateSubcommandCandidates(context);
716
- case "option-name": return generateOptionNameCandidates(context);
717
- case "option-value": return generateOptionValueCandidates(context);
718
- case "positional": return generatePositionalCandidates(context);
719
- default: return {
720
- candidates,
721
- directive
722
- };
723
- }
724
- }
725
- /**
726
- * Execute a shell command and return results as candidates
727
- */
728
- function executeShellCommand(command) {
729
- try {
730
- return execSync(command, {
731
- encoding: "utf-8",
732
- timeout: 5e3
733
- }).split("\n").map((line) => line.trim()).filter((line) => line.length > 0).map((line) => ({
734
- value: line,
735
- type: "value"
736
- }));
737
- } catch {
738
- return [];
739
- }
740
- }
741
- /**
742
- * Resolve value completion, executing shell commands and file lookups in JS
743
- */
744
- function resolveValueCandidates(vc, candidates, _currentWord, description) {
745
- let directive = CompletionDirective.FilterPrefix;
746
- let fileExtensions;
747
- let fileMatchers;
748
- switch (vc.type) {
749
- case "choices":
750
- if (vc.choices) for (const choice of vc.choices) candidates.push({
751
- value: choice,
752
- description,
753
- type: "value"
754
- });
755
- directive |= CompletionDirective.NoFileCompletion;
756
- break;
757
- case "file":
758
- if (vc.matcher && vc.matcher.length > 0) {
759
- fileMatchers = vc.matcher.filter((m) => m.trim().length > 0);
760
- if (fileMatchers.length === 0) {
761
- fileMatchers = void 0;
762
- directive |= CompletionDirective.FileCompletion;
763
- }
764
- } else if (vc.extensions && vc.extensions.length > 0) {
765
- fileExtensions = Array.from(new Set(vc.extensions.map((ext) => ext.trim().replace(/^\./, "")).filter((ext) => ext.length > 0)));
766
- if (fileExtensions.length === 0) {
767
- fileExtensions = void 0;
768
- directive |= CompletionDirective.FileCompletion;
769
- }
770
- } else directive |= CompletionDirective.FileCompletion;
771
- break;
772
- case "directory":
773
- directive |= CompletionDirective.DirectoryCompletion;
774
- break;
775
- case "command":
776
- if (vc.shellCommand) candidates.push(...executeShellCommand(vc.shellCommand));
777
- directive |= CompletionDirective.NoFileCompletion;
778
- break;
779
- case "none":
780
- directive |= CompletionDirective.NoFileCompletion;
781
- break;
782
- }
783
- return {
784
- directive,
785
- fileExtensions,
786
- fileMatchers
787
- };
788
- }
789
- /**
790
- * Generate subcommand candidates
791
- */
792
- function generateSubcommandCandidates(context) {
793
- const candidates = [];
794
- let directive = CompletionDirective.FilterPrefix;
795
- for (const name of context.subcommands) {
796
- let description;
797
- const sub = context.currentCommand.subCommands?.[name];
798
- if (sub) description = resolveSubCommandMeta(sub)?.description;
799
- else {
800
- const canonical = resolveSubCommandAlias(context.currentCommand, name);
801
- if (canonical) {
802
- const resolved = context.currentCommand.subCommands?.[canonical];
803
- if (resolved) description = resolveSubCommandMeta(resolved)?.description;
804
- }
805
- }
806
- candidates.push({
807
- value: name,
808
- description,
809
- type: "subcommand"
810
- });
811
- }
812
- if (candidates.length === 0 || context.currentWord.startsWith("-")) {
813
- const optionResult = generateOptionNameCandidates(context);
814
- candidates.push(...optionResult.candidates);
815
- }
816
- return {
817
- candidates,
818
- directive
819
- };
820
- }
821
- /**
822
- * Generate option name candidates
823
- */
824
- function generateOptionNameCandidates(context) {
825
- const candidates = [];
826
- const directive = CompletionDirective.FilterPrefix;
827
- const availableOptions = context.options.filter((opt) => {
828
- if (opt.valueType === "array") return true;
829
- if (context.usedOptions.has(opt.cliName)) return false;
830
- if (opt.alias && opt.alias.some((a) => context.usedOptions.has(a))) return false;
831
- if (opt.negation && context.usedOptions.has(opt.negation)) return false;
832
- return true;
833
- });
834
- for (const opt of availableOptions) {
835
- candidates.push({
836
- value: `--${opt.cliName}`,
837
- description: opt.description,
838
- type: "option"
839
- });
840
- if (opt.negation) candidates.push({
841
- value: `--${opt.negation}`,
842
- description: opt.negationDescription ?? opt.description,
843
- type: "option"
844
- });
845
- }
846
- if (!context.usedOptions.has("help")) candidates.push({
847
- value: "--help",
848
- description: "Show help information",
849
- type: "option"
850
- });
851
- return {
852
- candidates,
853
- directive
854
- };
855
- }
856
- /**
857
- * Generate option value candidates
858
- */
859
- function generateOptionValueCandidates(context) {
860
- const candidates = [];
861
- if (!context.targetOption) return {
862
- candidates,
863
- directive: CompletionDirective.FilterPrefix
864
- };
865
- const vc = context.targetOption.valueCompletion;
866
- if (!vc) return {
867
- candidates,
868
- directive: CompletionDirective.FilterPrefix
869
- };
870
- return {
871
- candidates,
872
- ...resolveValueCandidates(vc, candidates, context.currentWord)
873
- };
874
- }
875
- /**
876
- * Generate positional argument candidates
877
- */
878
- function generatePositionalCandidates(context) {
879
- const candidates = [];
880
- const positionalIndex = context.positionalIndex ?? 0;
881
- const positional = context.positionals[positionalIndex] ?? (context.positionals.at(-1)?.variadic ? context.positionals.at(-1) : void 0);
882
- if (!positional) return {
883
- candidates,
884
- directive: CompletionDirective.FilterPrefix
885
- };
886
- const vc = positional.valueCompletion;
887
- if (!vc) return {
888
- candidates,
889
- directive: CompletionDirective.FilterPrefix
890
- };
891
- return {
892
- candidates,
893
- ...resolveValueCandidates(vc, candidates, context.currentWord, positional.description)
894
- };
895
- }
896
-
897
- //#endregion
898
- //#region src/completion/dynamic/context-parser.ts
899
- /**
900
- * Parse completion context from partial command line
901
- */
902
- /**
903
- * Extract options from a command
904
- */
905
- function extractOptions(command) {
906
- if (!command.args) return [];
907
- return extractFields(command.args).fields.filter((field) => !field.positional).map((field) => ({
908
- name: field.name,
909
- cliName: field.cliName,
910
- alias: field.alias,
911
- negation: field.negationDisplay,
912
- negationDescription: field.negationDescription,
913
- description: field.description,
914
- takesValue: field.type !== "boolean",
915
- valueType: field.type,
916
- required: field.required,
917
- valueCompletion: resolveValueCompletion(field)
918
- }));
919
- }
920
- /**
921
- * Extract positionals from a command
922
- */
923
- function extractPositionalsForContext(command) {
924
- if (!command.args) return [];
925
- return extractFields(command.args).fields.filter((field) => field.positional).map((field, index) => ({
926
- name: field.name,
927
- cliName: field.cliName,
928
- position: index,
929
- description: field.description,
930
- required: field.required,
931
- variadic: field.type === "array",
932
- valueCompletion: resolveValueCompletion(field)
933
- }));
934
- }
935
- /**
936
- * Get subcommand names from a command (including aliases)
937
- */
938
- function getSubcommandNames(command) {
939
- if (!command.subCommands) return [];
940
- const names = [];
941
- for (const [name, subCmd] of Object.entries(command.subCommands)) {
942
- if (name.startsWith("__")) continue;
943
- names.push(name);
944
- const meta = resolveSubCommandMeta(subCmd);
945
- if (meta?.aliases) names.push(...meta.aliases);
946
- }
947
- return names;
948
- }
949
- /**
950
- * Resolve subcommand by name (including alias lookup)
951
- */
952
- function resolveSubcommand(command, name) {
953
- if (!command.subCommands) return null;
954
- const sub = command.subCommands[name];
955
- if (sub) return resolveSubCommandMeta(sub);
956
- const canonical = resolveSubCommandAlias(command, name);
957
- if (canonical) return resolveSubCommandMeta(command.subCommands[canonical]);
958
- return null;
959
- }
960
- /**
961
- * Check if a word is an option (starts with - or --)
962
- */
963
- function isOption(word) {
964
- return word.startsWith("-");
965
- }
966
- /**
967
- * Parse option name from word (e.g., "--foo=bar" -> "foo", "-v" -> "v")
968
- */
969
- function parseOptionName(word) {
970
- if (word.startsWith("--")) {
971
- const withoutPrefix = word.slice(2);
972
- const eqIndex = withoutPrefix.indexOf("=");
973
- return eqIndex >= 0 ? withoutPrefix.slice(0, eqIndex) : withoutPrefix;
974
- }
975
- if (word.startsWith("-")) return word.slice(1, 2);
976
- return word;
977
- }
978
- /**
979
- * Check if option has inline value (e.g., "--foo=bar")
980
- */
981
- function hasInlineValue(word) {
982
- return word.includes("=");
983
- }
984
- /**
985
- * Find option by name or alias
986
- */
987
- function findOption(options, nameOrAlias) {
988
- return options.find((opt) => {
989
- if (opt.cliName === nameOrAlias) return true;
990
- if (opt.alias?.includes(nameOrAlias)) return true;
991
- if (nameOrAlias.length > 1) {
992
- if (opt.cliName.includes("-") && toCamelCase(opt.cliName) === nameOrAlias) return true;
993
- if (opt.alias?.some((a) => a.includes("-") && toCamelCase(a) === nameOrAlias)) return true;
994
- if (opt.negation) {
995
- if (opt.negation === nameOrAlias) return true;
996
- if (opt.negation.includes("-") && toCamelCase(opt.negation) === nameOrAlias) return true;
997
- }
998
- }
999
- return false;
1000
- });
1001
- }
1002
- /**
1003
- * Parse completion context from command line arguments
1004
- *
1005
- * @param argv - Arguments after the program name (e.g., ["build", "--fo"])
1006
- * @param rootCommand - The root command
1007
- * @returns Completion context
1008
- */
1009
- function parseCompletionContext(argv, rootCommand) {
1010
- let currentCommand = rootCommand;
1011
- const subcommandPath = [];
1012
- const usedOptions = /* @__PURE__ */ new Set();
1013
- let positionalCount = 0;
1014
- let i = 0;
1015
- let options = extractOptions(currentCommand);
1016
- let afterDoubleDash = false;
1017
- while (i < argv.length - 1) {
1018
- const word = argv[i];
1019
- if (!afterDoubleDash && word === "--") {
1020
- afterDoubleDash = true;
1021
- i++;
1022
- continue;
1023
- }
1024
- if (!afterDoubleDash && isOption(word)) {
1025
- const optName = parseOptionName(word);
1026
- const opt = findOption(options, optName);
1027
- if (opt) {
1028
- usedOptions.add(opt.cliName);
1029
- if (opt.alias) for (const a of opt.alias) usedOptions.add(a);
1030
- if (opt.negation) usedOptions.add(opt.negation);
1031
- if (opt.takesValue && !hasInlineValue(word)) i++;
1032
- }
1033
- i++;
1034
- continue;
1035
- }
1036
- const subcommand = afterDoubleDash ? null : resolveSubcommand(currentCommand, word);
1037
- if (subcommand) {
1038
- subcommandPath.push(word);
1039
- currentCommand = subcommand;
1040
- options = extractOptions(currentCommand);
1041
- usedOptions.clear();
1042
- positionalCount = 0;
1043
- i++;
1044
- continue;
1045
- }
1046
- positionalCount++;
1047
- i++;
1048
- }
1049
- const currentWord = argv[argv.length - 1] ?? "";
1050
- const previousWord = argv[argv.length - 2] ?? "";
1051
- const positionals = extractPositionalsForContext(currentCommand);
1052
- const subcommands = getSubcommandNames(currentCommand);
1053
- let completionType;
1054
- let targetOption;
1055
- let positionalIndex;
1056
- if (!afterDoubleDash && previousWord && isOption(previousWord) && !hasInlineValue(previousWord)) {
1057
- const optName = parseOptionName(previousWord);
1058
- const opt = findOption(options, optName);
1059
- if (opt && opt.takesValue) {
1060
- completionType = "option-value";
1061
- targetOption = opt;
1062
- } else if (currentWord.startsWith("-")) completionType = "option-name";
1063
- else {
1064
- completionType = determineDefaultCompletionType(currentWord, subcommands, positionals, positionalCount);
1065
- if (completionType === "positional") positionalIndex = positionalCount;
1066
- }
1067
- } else if (!afterDoubleDash && currentWord.startsWith("--") && hasInlineValue(currentWord)) {
1068
- const optName = parseOptionName(currentWord);
1069
- const opt = findOption(options, optName);
1070
- if (opt && opt.takesValue) {
1071
- completionType = "option-value";
1072
- targetOption = opt;
1073
- } else completionType = "option-name";
1074
- } else if (!afterDoubleDash && currentWord.startsWith("-")) completionType = "option-name";
1075
- else {
1076
- completionType = determineDefaultCompletionType(currentWord, subcommands, positionals, positionalCount, afterDoubleDash);
1077
- if (completionType === "positional") positionalIndex = positionalCount;
1078
- }
1079
- return {
1080
- subcommandPath,
1081
- currentCommand,
1082
- currentWord,
1083
- previousWord,
1084
- completionType,
1085
- targetOption,
1086
- positionalIndex,
1087
- options,
1088
- subcommands,
1089
- positionals,
1090
- usedOptions,
1091
- providedPositionalCount: positionalCount
1092
- };
1093
- }
1094
- /**
1095
- * Determine default completion type when not completing an option
1096
- */
1097
- function determineDefaultCompletionType(currentWord, subcommands, positionals, positionalCount, afterDoubleDash) {
1098
- if (afterDoubleDash) return "positional";
1099
- if (subcommands.length > 0) {
1100
- if (subcommands.filter((s) => s.startsWith(currentWord)).length > 0 || currentWord === "") return "subcommand";
1101
- }
1102
- if (positionalCount < positionals.length) return "positional";
1103
- if (positionals.length > 0 && positionals[positionals.length - 1].variadic) return "positional";
1104
- return "subcommand";
1105
- }
1106
-
1107
- //#endregion
1108
- //#region src/completion/dynamic/shell-formatter.ts
1109
- /**
1110
- * Format completion candidates for the specified shell
1111
- *
1112
- * @returns Shell-ready output string (lines separated by newline, last line is :directive)
1113
- */
1114
- function formatForShell(result, options) {
1115
- switch (options.shell) {
1116
- case "bash": return formatForBash(result, options);
1117
- case "zsh": return formatForZsh(result, options);
1118
- case "fish": return formatForFish(result, options);
1119
- }
1120
- }
1121
- /**
1122
- * Check if the FilterPrefix directive is set
1123
- */
1124
- function shouldFilterPrefix(directive) {
1125
- return (directive & CompletionDirective.FilterPrefix) !== 0;
1126
- }
1127
- /**
1128
- * Filter candidates by prefix
1129
- */
1130
- function filterByPrefix(candidates, prefix) {
1131
- if (!prefix) return candidates;
1132
- return candidates.filter((c) => c.value.startsWith(prefix));
1133
- }
1134
- /**
1135
- * Append extension metadata and directive to output lines
1136
- */
1137
- function appendMetadata(lines, result) {
1138
- if (result.fileExtensions && result.fileExtensions.length > 0) lines.push(`@ext:${result.fileExtensions.join(",")}`);
1139
- if (result.fileMatchers && result.fileMatchers.length > 0) lines.push(`@matcher:${result.fileMatchers.join(",")}`);
1140
- lines.push(`:${result.directive}`);
1141
- }
1142
- /**
1143
- * Format for bash
1144
- *
1145
- * - Pre-filters candidates by currentWord prefix (replaces compgen -W)
1146
- * - Handles --opt=value inline values by prepending prefix
1147
- * - Outputs plain values only (no descriptions - bash COMPREPLY doesn't support them)
1148
- * - Last line: :directive
1149
- */
1150
- function formatForBash(result, options) {
1151
- let { candidates } = result;
1152
- if (shouldFilterPrefix(result.directive)) candidates = filterByPrefix(candidates, options.currentWord);
1153
- const lines = candidates.map((c) => {
1154
- if (options.inlinePrefix) return `${options.inlinePrefix}${c.value}`;
1155
- return c.value;
1156
- });
1157
- appendMetadata(lines, result);
1158
- return lines.join("\n");
1159
- }
1160
- /**
1161
- * Format for zsh
1162
- *
1163
- * - Outputs value:description pairs for _describe
1164
- * - Colons in values/descriptions are escaped with backslash
1165
- * - Last line: :directive
1166
- */
1167
- function formatForZsh(result, _options) {
1168
- const lines = result.candidates.map((c) => {
1169
- const escapedValue = c.value.replace(/:/g, "\\:");
1170
- if (c.description) return `${escapedValue}:${c.description.replace(/:/g, "\\:")}`;
1171
- return escapedValue;
1172
- });
1173
- appendMetadata(lines, result);
1174
- return lines.join("\n");
1175
- }
1176
- /**
1177
- * Format for fish
1178
- *
1179
- * - Outputs value\tdescription pairs
1180
- * - Last line: :directive
1181
- */
1182
- function formatForFish(result, _options) {
1183
- const lines = result.candidates.map((c) => {
1184
- if (c.description) return `${c.value}\t${c.description}`;
1185
- return c.value;
1186
- });
1187
- appendMetadata(lines, result);
1188
- return lines.join("\n");
1189
- }
1190
-
1191
- //#endregion
1192
- //#region src/completion/dynamic/complete-command.ts
1193
- /**
1194
- * Dynamic completion command implementation
1195
- *
1196
- * This creates a hidden `__complete` command that outputs completion candidates
1197
- * for shell scripts to consume. Usage:
1198
- *
1199
- * mycli __complete --shell bash -- build --fo
1200
- * mycli __complete --shell zsh -- plugin add
1201
- *
1202
- * Output format depends on the target shell:
1203
- * bash: plain values (pre-filtered by prefix), last line :directive
1204
- * zsh: value:description pairs, last line :directive
1205
- * fish: value\tdescription pairs, last line :directive
1206
- */
1207
- /**
1208
- * Detect inline option-value prefix (e.g., "--format=" from "--format=json")
1209
- */
1210
- function detectInlinePrefix(currentWord) {
1211
- if (currentWord.startsWith("--") && currentWord.includes("=")) return currentWord.slice(0, currentWord.indexOf("=") + 1);
1212
- }
1213
- /**
1214
- * Schema for the __complete command
1215
- */
1216
- const completeArgsSchema = z.object({
1217
- shell: arg(z.enum([
1218
- "bash",
1219
- "zsh",
1220
- "fish"
1221
- ]), { description: "Target shell for output formatting" }),
1222
- args: arg(z.array(z.string()).default([]), {
1223
- positional: true,
1224
- description: "Arguments to complete",
1225
- variadic: true
1226
- })
1227
- });
1228
- /**
1229
- * Create the dynamic completion command
1230
- *
1231
- * @param rootCommand - The root command to generate completions for
1232
- * @param programName - The program name (optional, defaults to rootCommand.name)
1233
- * @returns A command that outputs completion candidates
1234
- */
1235
- function createDynamicCompleteCommand(rootCommand, _programName) {
1236
- return defineCommand({
1237
- name: "__complete",
1238
- args: completeArgsSchema,
1239
- run(args) {
1240
- const context = parseCompletionContext(args.args, rootCommand);
1241
- const result = generateCandidates(context);
1242
- const inlinePrefix = detectInlinePrefix(context.currentWord);
1243
- const output = formatForShell(result, {
1244
- shell: args.shell,
1245
- currentWord: inlinePrefix ? context.currentWord.slice(inlinePrefix.length) : context.currentWord,
1246
- inlinePrefix
1247
- });
1248
- console.log(output);
1249
- }
1250
- });
1251
- }
1252
- /**
1253
- * Check if a command tree contains the __complete command
1254
- */
1255
- function hasCompleteCommand(command) {
1256
- return Boolean(command.subCommands?.["__complete"]);
1257
- }
1258
-
1259
- //#endregion
1260
- //#region src/completion/fish.ts
1261
- /** Escape shell-special characters for fish double-quoted strings */
1262
- function escapeDesc$1(s) {
1263
- return s.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\$/g, "\\$");
1264
- }
1265
- /**
1266
- * Generate fish value completion lines for a ValueCompletion spec.
1267
- * Each line outputs candidates via echo (tab-separated value\tdescription).
1268
- */
1269
- function fishValueLines(vc) {
1270
- if (!vc) return [];
1271
- switch (vc.type) {
1272
- case "choices": return vc.choices.map((c) => `echo "${escapeDesc$1(c)}"`);
1273
- case "file":
1274
- if (vc.matcher?.length) return fishMatcherLines(vc.matcher);
1275
- if (vc.extensions?.length) return fishExtensionLines(vc.extensions);
1276
- return [`__fish_complete_path "$_cur"`];
1277
- case "directory": return [`__fish_complete_directories "$_cur"`];
1278
- case "command": return [
1279
- `for _v in (${vc.shellCommand})`,
1280
- ` echo "$_v"`,
1281
- `end`
1282
- ];
1283
- case "none": return [];
1284
- }
1285
- }
1286
- /** Generate fish matcher-filtered file completion */
1287
- function fishMatcherLines(patterns) {
1288
- return [
1289
- `__fish_complete_directories "$_cur"`,
1290
- `set -l _dir ""`,
1291
- `if string match -q '*/*' "$_cur"`,
1292
- ` set _dir (string replace -r '[^/]*$' '' "$_cur")`,
1293
- `end`,
1294
- ...patterns.flatMap((p) => [
1295
- `for _f in "$_dir"${p}`,
1296
- ` test -f "$_f"; and string match -q "$_cur*" "$_f"; and echo "$_f"`,
1297
- `end`
1298
- ])
1299
- ];
1300
- }
1301
- /** Generate fish extension-filtered file completion */
1302
- function fishExtensionLines(extensions) {
1303
- const lines = [];
1304
- lines.push(`__fish_complete_directories "$_cur"`);
1305
- for (const ext of extensions) {
1306
- lines.push(`for _f in "$_cur"*.${ext}`);
1307
- lines.push(` test -f "$_f"; and echo "$_f"`);
1308
- lines.push(`end`);
1309
- }
1310
- return lines;
1311
- }
1312
- /** Generate option-value switch cases for fish */
1313
- function optionValueCases$1(options) {
1314
- const lines = [];
1315
- for (const opt of options) {
1316
- if (!opt.takesValue || !opt.valueCompletion) continue;
1317
- const valLines = fishValueLines(opt.valueCompletion);
1318
- if (valLines.length === 0) continue;
1319
- const conditions = [`test "$_prev" = "--${opt.cliName}"`];
1320
- if (opt.alias) for (const a of opt.alias) conditions.push(`test "$_prev" = "${a.length === 1 ? `-${a}` : `--${a}`}"`);
1321
- const cond = conditions.join("; or ");
1322
- lines.push(` if ${cond}`);
1323
- for (const vl of valLines) lines.push(` ${vl}`);
1324
- lines.push(` return`);
1325
- lines.push(` end`);
1326
- }
1327
- return lines;
1328
- }
1329
- /** Generate positional completion block for fish */
1330
- function positionalBlock$1(positionals) {
1331
- if (positionals.length === 0) return [];
1332
- const lines = [];
1333
- for (const pos of positionals) {
1334
- const valLines = fishValueLines(pos.valueCompletion);
1335
- if (valLines.length === 0) continue;
1336
- if (pos.variadic) lines.push(` if test $_pos_count -ge ${pos.position}`);
1337
- else lines.push(` if test $_pos_count -eq ${pos.position}`);
1338
- for (const vl of valLines) lines.push(` ${vl}`);
1339
- lines.push(` return`);
1340
- lines.push(` end`);
1341
- }
1342
- return lines;
1343
- }
1344
- /** Generate available-option echo lines for fish */
1345
- function availableOptionLines$1(options, fn) {
1346
- const lines = [];
1347
- for (const opt of options) {
1348
- const desc = escapeDesc$1(opt.description ?? "");
1349
- const negDesc = opt.negationDescription ? escapeDesc$1(opt.negationDescription) : desc;
1350
- if (opt.valueType === "array") lines.push(` echo "--${opt.cliName}\t${desc}"`);
1351
- else {
1352
- const checks = [`"--${opt.cliName}"`];
1353
- if (opt.alias) for (const a of opt.alias) checks.push(a.length === 1 ? `"-${a}"` : `"--${a}"`);
1354
- if (opt.negation) checks.push(`"--${opt.negation}"`);
1355
- lines.push(` __${fn}_not_used ${checks.join(" ")}; and echo "--${opt.cliName}\t${desc}"`);
1356
- if (opt.negation) lines.push(` __${fn}_not_used ${checks.join(" ")}; and echo "--${opt.negation}\t${negDesc}"`);
1357
- }
1358
- }
1359
- lines.push(` __${fn}_not_used "--help"; and echo "--help\tShow help"`);
1360
- return lines;
1361
- }
1362
- /** Generate value-option completion block if any value-taking options exist */
1363
- function valueCompletionBlock$1(options) {
1364
- if (!options.some((o) => o.takesValue && o.valueCompletion)) return [];
1365
- return optionValueCases$1(options);
1366
- }
1367
- /**
1368
- * Generate a per-subcommand completion function for fish.
1369
- * Recursively generates functions for nested subcommands.
1370
- */
1371
- function generateSubHandler$1(sub, fn, path) {
1372
- const fullPath = [...path, sub.name];
1373
- const funcName = `__${fn}_complete_${fullPath.map(sanitize).join("_")}`;
1374
- const visibleSubs = getVisibleSubs(sub.subcommands);
1375
- const lines = [];
1376
- for (const child of visibleSubs) lines.push(...generateSubHandler$1(child, fn, fullPath));
1377
- lines.push(`function ${funcName} --no-scope-shadowing`);
1378
- lines.push(...valueCompletionBlock$1(sub.options));
1379
- const fullPathStr = fullPath.join(":");
1380
- lines.push(` if __${fn}_opt_takes_value "${fullPathStr}" "$_prev"; return; end`);
1381
- if (sub.positionals.length > 0) {
1382
- lines.push(` if test $_after_dd -eq 1`);
1383
- lines.push(...positionalBlock$1(sub.positionals).map((l) => ` ${l}`));
1384
- lines.push(` return`);
1385
- lines.push(` end`);
1386
- } else lines.push(` if test $_after_dd -eq 1; return; end`);
1387
- lines.push(` if string match -q -- '-*' "$_cur"`);
1388
- lines.push(...availableOptionLines$1(sub.options, fn));
1389
- lines.push(` return`);
1390
- lines.push(` end`);
1391
- if (visibleSubs.length > 0) for (const s of getSubNamesWithAliases(sub.subcommands)) {
1392
- const desc = escapeDesc$1(s.description ?? "");
1393
- lines.push(` echo "${s.name}\t${desc}"`);
1394
- }
1395
- else if (sub.positionals.length > 0) lines.push(...positionalBlock$1(sub.positionals));
1396
- lines.push(`end`);
1397
- lines.push(``);
1398
- return lines;
1399
- }
1400
- /** Generate opt-takes-value entries for fish switch cases */
1401
- function optTakesValueCases(sub, parentPath) {
1402
- const lines = [];
1403
- for (const opt of sub.options) if (opt.takesValue) {
1404
- const patterns = [`"${parentPath}:--${opt.cliName}"`];
1405
- if (opt.alias) for (const a of opt.alias) patterns.push(`"${parentPath}:${a.length === 1 ? `-${a}` : `--${a}`}"`);
1406
- lines.push(` case ${patterns.join(" ")}`);
1407
- lines.push(` return 0`);
1408
- }
1409
- for (const child of getVisibleSubs(sub.subcommands)) {
1410
- const childPath = parentPath ? `${parentPath}:${child.name}` : child.name;
1411
- lines.push(...optTakesValueCases(child, childPath));
1412
- if (child.aliases) for (const alias of child.aliases) {
1413
- const aliasPath = parentPath ? `${parentPath}:${alias}` : alias;
1414
- lines.push(...optTakesValueCases(child, aliasPath));
1415
- }
1416
- }
1417
- return lines;
1418
- }
1419
- function generateFishCompletion(command, options) {
1420
- const { programName } = options;
1421
- const data = extractCompletionData(command, programName, options.globalArgsSchema);
1422
- const fn = sanitize(programName);
1423
- const root = data.command;
1424
- const visibleSubs = getVisibleSubs(root.subcommands);
1425
- const lines = [];
1426
- lines.push(...buildHeaderLines({
1427
- programName,
1428
- shell: "fish",
1429
- binPath: options.binPath,
1430
- programVersion: options.programVersion
1431
- }));
1432
- lines.push(`# Generated by politty`);
1433
- lines.push(``);
1434
- const sig = computeBinSig(resolveBinPath(programName, options.binPath));
1435
- const refreshFn = `__${fn}_refresh_completion`;
1436
- lines.push(`function ${refreshFn} --no-scope-shadowing`);
1437
- lines.push(` set -l _bin (command -v ${programName})`);
1438
- lines.push(` test -z "$_bin"; and return 1`);
1439
- lines.push(` set -l _sig (stat -L -c '%Y' "$_bin" 2>/dev/null; or stat -L -f '%m' "$_bin" 2>/dev/null)`);
1440
- lines.push(` test "$_sig" = "${sig}"; and return 1`);
1441
- lines.push(` set -l _target "$__fish_config_dir/completions/${programName}.fish"`);
1442
- lines.push(` "$_bin" __refresh-completion fish 2>/dev/null`);
1443
- lines.push(` and source "$_target" 2>/dev/null`);
1444
- lines.push(` and return 0`);
1445
- lines.push(` return 1`);
1446
- lines.push(`end`);
1447
- lines.push(`${refreshFn}`);
1448
- lines.push(`set -l _politty_refreshed $status`);
1449
- lines.push(`functions -e ${refreshFn}`);
1450
- lines.push(`test $_politty_refreshed -eq 0; and return`);
1451
- lines.push(``);
1452
- lines.push(`function __${fn}_not_used --no-scope-shadowing`);
1453
- lines.push(` for _chk in $argv`);
1454
- lines.push(` if contains -- "$_chk" $_used_opts`);
1455
- lines.push(` return 1`);
1456
- lines.push(` end`);
1457
- lines.push(` end`);
1458
- lines.push(` return 0`);
1459
- lines.push(`end`);
1460
- lines.push(``);
1461
- lines.push(`function __${fn}_opt_takes_value`);
1462
- lines.push(` switch "$argv[1]:$argv[2]"`);
1463
- lines.push(...optTakesValueCases(root, ""));
1464
- lines.push(` end`);
1465
- lines.push(` return 1`);
1466
- lines.push(`end`);
1467
- lines.push(``);
1468
- const routeEntries = collectRouteEntries(root);
1469
- if (routeEntries.length > 0) {
1470
- lines.push(`function __${fn}_is_subcmd`);
1471
- lines.push(` switch "$argv[1]:$argv[2]"`);
1472
- for (const r of routeEntries) {
1473
- lines.push(` case "${r.lookupPattern}"`);
1474
- lines.push(` return 0`);
1475
- }
1476
- lines.push(` end`);
1477
- lines.push(` return 1`);
1478
- lines.push(`end`);
1479
- lines.push(``);
1480
- }
1481
- for (const sub of visibleSubs) lines.push(...generateSubHandler$1(sub, fn, []));
1482
- lines.push(`function __${fn}_complete_root --no-scope-shadowing`);
1483
- lines.push(...valueCompletionBlock$1(root.options));
1484
- lines.push(` if __${fn}_opt_takes_value "" "$_prev"; return; end`);
1485
- if (root.positionals.length > 0) {
1486
- lines.push(` if test $_after_dd -eq 1`);
1487
- lines.push(...positionalBlock$1(root.positionals).map((l) => ` ${l}`));
1488
- lines.push(` return`);
1489
- lines.push(` end`);
1490
- } else lines.push(` if test $_after_dd -eq 1; return; end`);
1491
- lines.push(` if string match -q -- '-*' "$_cur"`);
1492
- lines.push(...availableOptionLines$1(root.options, fn));
1493
- if (visibleSubs.length > 0) {
1494
- lines.push(` else`);
1495
- for (const s of getSubNamesWithAliases(root.subcommands)) {
1496
- const desc = escapeDesc$1(s.description ?? "");
1497
- lines.push(` echo "${s.name}\t${desc}"`);
1498
- }
1499
- } else if (root.positionals.length > 0) {
1500
- lines.push(` else`);
1501
- lines.push(...positionalBlock$1(root.positionals));
1502
- }
1503
- lines.push(` end`);
1504
- lines.push(`end`);
1505
- lines.push(``);
1506
- lines.push(`function __fish_${fn}_complete`);
1507
- lines.push(` set -l _args (commandline -opc)`);
1508
- lines.push(` set -e _args[1]`);
1509
- lines.push(``);
1510
- lines.push(` set -l _ct (commandline -ct)`);
1511
- lines.push(` if test (count $_ct) -eq 0`);
1512
- lines.push(` set -a _args ""`);
1513
- lines.push(` else`);
1514
- lines.push(` set -a _args $_ct`);
1515
- lines.push(` end`);
1516
- lines.push(``);
1517
- lines.push(` set -l _cur ""`);
1518
- lines.push(` if test (count $_args) -gt 0`);
1519
- lines.push(` set _cur "$_args[-1]"`);
1520
- lines.push(` end`);
1521
- lines.push(``);
1522
- lines.push(` set -l _prev ""`);
1523
- lines.push(` if test (count $_args) -gt 1`);
1524
- lines.push(` set _prev "$_args[-2]"`);
1525
- lines.push(` end`);
1526
- lines.push(``);
1527
- lines.push(` set -l _subcmd "" ; set -l _after_dd 0 ; set -l _pos_count 0 ; set -l _skip_next 0`);
1528
- lines.push(` set -l _used_opts`);
1529
- lines.push(``);
1530
- lines.push(` set -l _j 1`);
1531
- lines.push(` set -l _limit (math (count $_args) - 1)`);
1532
- lines.push(` while test $_j -le $_limit`);
1533
- lines.push(` set -l _w "$_args[$_j]"`);
1534
- lines.push(` if test $_skip_next -eq 1; set _skip_next 0; set _j (math $_j + 1); continue; end`);
1535
- lines.push(` if test "$_w" = "--"; set _after_dd 1; set _j (math $_j + 1); continue; end`);
1536
- lines.push(` if test $_after_dd -eq 1; set _pos_count (math $_pos_count + 1); set _j (math $_j + 1); continue; end`);
1537
- lines.push(` if string match -q -- '--*=*' "$_w"; set -a _used_opts (string replace -r '=.*' '' -- "$_w"); set _j (math $_j + 1); continue; end`);
1538
- lines.push(` if string match -q -- '-*' "$_w"`);
1539
- lines.push(` set -a _used_opts "$_w"`);
1540
- lines.push(` __${fn}_opt_takes_value "$_subcmd" "$_w"; and set _skip_next 1`);
1541
- lines.push(` set _j (math $_j + 1); continue`);
1542
- lines.push(` end`);
1543
- 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`);
1544
- else lines.push(` set _pos_count (math $_pos_count + 1)`);
1545
- lines.push(` set _j (math $_j + 1)`);
1546
- lines.push(` end`);
1547
- lines.push(``);
1548
- lines.push(` switch "$_subcmd"`);
1549
- for (const r of routeEntries) lines.push(` case "${r.pathStr}"; __${fn}_complete_${r.funcSuffix}`);
1550
- lines.push(` case '*'; __${fn}_complete_root`);
1551
- lines.push(` end`);
1552
- lines.push(`end`);
1553
- lines.push(``);
1554
- lines.push(`# Clear existing completions`);
1555
- lines.push(`complete -e -c ${programName}`);
1556
- lines.push(``);
1557
- lines.push(`# Register completion`);
1558
- lines.push(`complete -c ${programName} -f -a '(__fish_${fn}_complete)'`);
1559
- lines.push(``);
1560
- return {
1561
- script: lines.join("\n"),
1562
- shell: "fish",
1563
- installInstructions: `# To enable completions, run one of the following:
1564
-
1565
- # Option 1: Source directly
1566
- ${programName} completion fish | source
1567
-
1568
- # Option 2: Save to the fish completions directory
1569
- ${programName} completion fish > ~/.config/fish/completions/${programName}.fish
1570
-
1571
- # The completion will be available immediately in new shell sessions.
1572
- # To use in the current session, run:
1573
- source ~/.config/fish/completions/${programName}.fish`
1574
- };
1575
- }
1576
-
1577
- //#endregion
1578
- //#region src/completion/loader.ts
1579
- /**
1580
- * Rc-loader generators (bash / zsh).
1581
- *
1582
- * These produce the small snippet a user adds once to `~/.bashrc` or
1583
- * `~/.zshrc`. The snippet:
1584
- *
1585
- * 1. Looks up the binary on $PATH.
1586
- * 2. Reads its mtime.
1587
- * 3. If the on-disk completion cache is missing or its
1588
- * `# politty-bin-sig:` header differs, regenerates the cache by
1589
- * spawning the binary once.
1590
- * 4. Sources the cache.
1591
- *
1592
- * All failure modes are silent no-ops so a broken / missing CLI never
1593
- * blocks shell startup.
1594
- */
1595
- /**
1596
- * Single-quote escape: `'` -> `'\''`. Inside single quotes the shell
1597
- * performs no expansion at all, so `$`, backticks, and `$(...)` are
1598
- * inert. Used for hardcoded paths because callers may sources them
1599
- * from env / config — we must not let metachars in the path execute as
1600
- * commands when the rc snippet is sourced.
1601
- */
1602
- function shSingleQuote(s) {
1603
- return `'${s.replace(/'/g, "'\\''")}'`;
1604
- }
1605
- function bashCachePathExpr(programName, cacheDir, shell) {
1606
- if (cacheDir) return shSingleQuote(`${cacheDir}/completion.${shell}`);
1607
- return `"\${XDG_CACHE_HOME:-$HOME/.cache}/${programName}/completion.${shell}"`;
1608
- }
1609
- function generateBashLoader(opts) {
1610
- const fn = sanitize(opts.programName);
1611
- const cache = bashCachePathExpr(opts.programName, opts.cacheDir, "bash");
1612
- return `__${fn}_load_completion() {
1613
- local _bin _cache _sig _hdr
1614
- _bin=$(type -P ${opts.programName} 2>/dev/null)
1615
- [[ -n "$_bin" ]] || return 0
1616
- _cache=${cache}
1617
- _sig=$(stat -L -c '%Y' "$_bin" 2>/dev/null || stat -L -f '%m' "$_bin" 2>/dev/null) || return 0
1618
- _hdr="# politty-bin-sig: $_sig"
1619
- if [[ ! -f "$_cache" ]] || ! head -5 "$_cache" 2>/dev/null | grep -qF "$_hdr"; then
1620
- # Use the hidden __refresh-completion subcommand instead of
1621
- # \`$_bin completion bash\`: the foreground completion command
1622
- # is subject to user setup/cleanup/prompt and required
1623
- # globalArgs validation, which can silently fail or block when
1624
- # invoked from rc; runMain bypasses those for __-prefixed
1625
- # internal subcommands.
1626
- "$_bin" __refresh-completion bash 2>/dev/null
1627
- fi
1628
- # If regen failed but a stale cache survived from a previous run,
1629
- # source it anyway — a stale completion is preferable to no
1630
- # completion at all.
1631
- [[ -f "$_cache" ]] || return 0
1632
- # shellcheck disable=SC1090
1633
- source "$_cache"
1634
- }
1635
- __${fn}_load_completion
1636
- unset -f __${fn}_load_completion
1637
- `;
1638
- }
1639
- function generateZshLoader(opts) {
1640
- const fn = sanitize(opts.programName);
1641
- const cache = bashCachePathExpr(opts.programName, opts.cacheDir, "zsh");
1642
- return `__${fn}_load_completion() {
1643
- emulate -L zsh
1644
- setopt local_options no_aliases
1645
- local _bin _cache _sig _hdr
1646
- _bin=$(whence -p ${opts.programName} 2>/dev/null)
1647
- [[ -n "$_bin" ]] || return 0
1648
- _cache=${cache}
1649
- _sig=$(stat -L -c '%Y' "$_bin" 2>/dev/null || stat -L -f '%m' "$_bin" 2>/dev/null) || return 0
1650
- _hdr="# politty-bin-sig: $_sig"
1651
- if [[ ! -f "$_cache" ]] || ! head -5 "$_cache" 2>/dev/null | grep -qF "$_hdr"; then
1652
- # See bash loader for why we use __refresh-completion instead
1653
- # of \`$_bin completion zsh\`.
1654
- "$_bin" __refresh-completion zsh 2>/dev/null
1655
- fi
1656
- # See bash loader: keep stale completion over no completion.
1657
- [[ -f "$_cache" ]] || return 0
1658
- source "$_cache"
1659
- }
1660
- __${fn}_load_completion
1661
- unfunction __${fn}_load_completion
1662
- `;
1663
- }
1664
- /**
1665
- * Build the rc-loader snippet for bash or zsh. Fish doesn't have an
1666
- * rc-loader; instead, `<program> completion fish --install` writes a
1667
- * self-rewriting autoload file.
1668
- */
1669
- function generateLoader(opts) {
1670
- switch (opts.shell) {
1671
- case "bash": return generateBashLoader(opts);
1672
- case "zsh": return generateZshLoader(opts);
1673
- case "fish": throw new Error("fish does not use an rc loader. Run `<program> completion fish --install` to write the self-refreshing autoload file instead.");
1674
- }
1675
- }
1676
- /**
1677
- * Default cache file path (used by `completion <bash|zsh> --install`
1678
- * and the `__refresh-completion` subcommand). For fish, the install
1679
- * path is `$__fish_config_dir/completions/<program>.fish` and is
1680
- * computed inside `installPath()` instead.
1681
- */
1682
- function defaultCacheDir(programName) {
1683
- return `${process.env.XDG_CACHE_HOME ?? `${process.env.HOME ?? ""}/.cache`}/${programName}`;
1684
- }
1685
-
1686
- //#endregion
1687
- //#region src/completion/install.ts
1688
- /**
1689
- * On-disk install + refresh helpers.
1690
- *
1691
- * `install` writes the generated script to its canonical cache /
1692
- * autoload path. `refresh` is the body of the `__refresh-completion`
1693
- * hidden subcommand and the runMain background hook — it regenerates
1694
- * the cache only when the binary's mtime no longer matches the
1695
- * embedded `# politty-bin-sig:` header.
1696
- *
1697
- * All file I/O is best-effort: failures fall through silently. A stale
1698
- * (or missing) cache is preferable to crashing the user's shell.
1699
- */
1700
- /**
1701
- * Resolve where a script for the given shell should live on disk.
1702
- *
1703
- * - bash/zsh: `<cacheDir>/completion.<shell>` — sourced by the rc loader.
1704
- * - fish: `$__fish_config_dir/completions/<program>.fish` — autoloaded
1705
- * by fish on TAB. We approximate `$__fish_config_dir` from
1706
- * `$XDG_CONFIG_HOME` / `$HOME`.
1707
- */
1708
- function installPath(programName, shell, cacheDir) {
1709
- if (shell === "fish") return join(process.env.XDG_CONFIG_HOME ?? `${process.env.HOME ?? ""}/.config`, "fish", "completions", `${programName}.fish`);
1710
- return join(cacheDir ?? defaultCacheDir(programName), `completion.${shell}`);
1711
- }
1712
- /** Atomic write: tmp file in the same dir, then rename. */
1713
- function writeAtomic(path, content) {
1714
- mkdirSync(dirname(path), { recursive: true });
1715
- const tmp = `${path}.tmp.${process.pid}`;
1716
- writeFileSync(tmp, content);
1717
- renameSync(tmp, path);
1718
- }
1719
- function generateScript(ctx, shell) {
1720
- return generateCompletion(ctx.rootCommand, {
1721
- shell,
1722
- programName: ctx.programName,
1723
- includeDescriptions: true,
1724
- ...ctx.programVersion !== void 0 && { programVersion: ctx.programVersion },
1725
- ...ctx.binPath !== void 0 && { binPath: ctx.binPath },
1726
- ...ctx.cacheDir !== void 0 && { cacheDir: ctx.cacheDir },
1727
- ...ctx.globalArgsSchema !== void 0 && { globalArgsSchema: ctx.globalArgsSchema }
1728
- }).script;
1729
- }
1730
- /** Write the script for `shell` to its install path. Returns the path. */
1731
- function install(ctx, shell) {
1732
- const target = installPath(ctx.programName, shell, ctx.cacheDir);
1733
- writeAtomic(target, generateScript(ctx, shell));
1734
- return target;
1735
- }
1736
- /**
1737
- * Read the first ~5 lines of an existing cache file and return its
1738
- * embedded bin-sig. Returns `null` when the file is missing, unreadable,
1739
- * or doesn't have a sig header.
1740
- */
1741
- function readCachedSig(path) {
1742
- try {
1743
- if (!existsSync(path)) return null;
1744
- const m = readFileSync(path, "utf8").split("\n", 6).join("\n").match(/^# politty-bin-sig: (\S+)/m);
1745
- return m ? m[1] : null;
1746
- } catch {
1747
- return null;
1748
- }
1749
- }
1750
- /**
1751
- * Rewrite the cache only when stale. Used by:
1752
- * - `<program> __refresh-completion <shell>` (the hidden subcommand
1753
- * spawned both by the rc loader and by the runMain background hook)
1754
- *
1755
- * Caller is responsible for gating: the runMain hook (`maybeSpawnRefresh`)
1756
- * checks `hasManagedCache` before spawning so we don't silently create
1757
- * a fish autoload the user never opted into. The rc loader / fish
1758
- * autoload only run after the user has installed completion in the
1759
- * first place, so they're allowed to refresh unconditionally.
1760
- *
1761
- * Must never throw — a stale completion is fine, a crash isn't.
1762
- */
1763
- function refreshIfStale(ctx, shell) {
1764
- try {
1765
- const target = installPath(ctx.programName, shell, ctx.cacheDir);
1766
- const binPath = resolveBinPath(ctx.programName, ctx.binPath);
1767
- if (!binPath) return;
1768
- let currentSig;
1769
- try {
1770
- currentSig = Math.floor(statSync(binPath).mtimeMs / 1e3).toString();
1771
- } catch {
1772
- return;
1773
- }
1774
- if (readCachedSig(target) === currentSig) return;
1775
- writeAtomic(target, generateScript(ctx, shell));
1776
- } catch {}
1777
- }
1778
- /**
1779
- * Returns true when a politty-managed cache file already exists on disk
1780
- * for the given shell — i.e. the user has installed completion via
1781
- * `<program> completion <shell> --install` or the rc loader has already
1782
- * sourced one. Used by the runMain background hook to avoid spawning
1783
- * the refresher (and thereby silently creating files) on plain CLI runs
1784
- * the user never opted into.
1785
- */
1786
- function hasManagedCache(ctx, shell) {
1787
- return readCachedSig(installPath(ctx.programName, shell, ctx.cacheDir)) !== null;
1788
- }
1789
- /**
1790
- * Spawn a detached child process that runs `<program> __refresh-completion <shell>`.
1791
- * The child is fully decoupled (`stdio: "ignore"` + `unref()`), so it
1792
- * outlives the parent without holding any handles.
1793
- *
1794
- * Caller is expected to gate this on the right conditions (interactive
1795
- * shell, not running inside `__complete` itself, etc.).
1796
- *
1797
- * Returns `void` and never throws — even spawn failures are absorbed.
1798
- */
1799
- function spawnBackgroundRefresh(programArgv0, shell) {
1800
- try {
1801
- spawn(process.execPath, [
1802
- programArgv0,
1803
- "__refresh-completion",
1804
- shell
1805
- ], {
1806
- detached: true,
1807
- stdio: "ignore"
1808
- }).unref();
1809
- } catch {}
1810
- }
1811
-
1812
- //#endregion
1813
- //#region src/completion/zsh.ts
1814
- function escapeDesc(s) {
1815
- return s.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\$/g, "\\$").replace(/`/g, "\\`").replace(/:/g, "\\:");
1816
- }
1817
- /**
1818
- * Generate zsh value completion lines for a ValueCompletion spec.
1819
- * Uses `_vals` array (must be declared in the calling function scope).
1820
- */
1821
- function zshValueLines(vc, fn) {
1822
- if (!vc) return [];
1823
- switch (vc.type) {
1824
- case "choices": return [`_vals=(${vc.choices.map((c) => `"${escapeDesc(c)}"`).join(" ")})`, `__${fn}_cdescribe 'completions' _vals`];
1825
- case "file":
1826
- if (vc.matcher?.length) return vc.matcher.map((p) => `_files -g "${p}"`);
1827
- if (vc.extensions?.length) return vc.extensions.map((ext) => `_files -g "*.${ext}"`);
1828
- return [`_files`];
1829
- case "directory": return [`_files -/`];
1830
- case "command": return [`_vals=("\${(@f)$(${vc.shellCommand})}")`, `__${fn}_cdescribe 'completions' _vals`];
1831
- case "none": return [];
1832
- }
1833
- }
1834
- /** Generate option-value case branches */
1835
- function optionValueCases(options, fn) {
1836
- const lines = [];
1837
- for (const opt of options) {
1838
- if (!opt.takesValue || !opt.valueCompletion) continue;
1839
- const valLines = zshValueLines(opt.valueCompletion, fn);
1840
- if (valLines.length === 0) continue;
1841
- const patterns = [`--${opt.cliName}`];
1842
- if (opt.alias) for (const a of opt.alias) patterns.push(a.length === 1 ? `-${a}` : `--${a}`);
1843
- lines.push(` ${patterns.join("|")})`);
1844
- for (const vl of valLines) lines.push(` ${vl}`);
1845
- lines.push(` return 0 ;;`);
1846
- }
1847
- return lines;
1848
- }
1849
- /** Generate positional completion block */
1850
- function positionalBlock(positionals, fn) {
1851
- if (positionals.length === 0) return [];
1852
- const lines = [];
1853
- lines.push(` case "$_pos_count" in`);
1854
- for (const pos of positionals) {
1855
- if (pos.variadic) lines.push(` ${pos.position}|*)`);
1856
- else lines.push(` ${pos.position})`);
1857
- const valLines = zshValueLines(pos.valueCompletion, fn);
1858
- for (const vl of valLines) lines.push(` ${vl}`);
1859
- lines.push(` ;;`);
1860
- }
1861
- lines.push(` esac`);
1862
- return lines;
1863
- }
1864
- /** Generate prev-word value completion case block */
1865
- function valueCompletionBlock(options, fn) {
1866
- if (!options.some((o) => o.takesValue && o.valueCompletion)) return [];
1867
- const prevCases = optionValueCases(options, fn);
1868
- if (prevCases.length === 0) return [];
1869
- return [
1870
- ` case "\${words[CURRENT-1]}" in`,
1871
- ...prevCases,
1872
- ` esac`
1873
- ];
1874
- }
1875
- /** Generate available-options list lines */
1876
- function availableOptionLines(options, fn) {
1877
- const lines = [];
1878
- for (const opt of options) {
1879
- const desc = opt.description ? `:${escapeDesc(opt.description)}` : "";
1880
- const negDesc = opt.negationDescription ? `:${escapeDesc(opt.negationDescription)}` : desc;
1881
- if (opt.valueType === "array") lines.push(` _opts+=("--${opt.cliName}${desc}")`);
1882
- else {
1883
- const patterns = [`"--${opt.cliName}"`];
1884
- if (opt.alias) for (const a of opt.alias) patterns.push(a.length === 1 ? `"-${a}"` : `"--${a}"`);
1885
- if (opt.negation) patterns.push(`"--${opt.negation}"`);
1886
- lines.push(` __${fn}_not_used ${patterns.join(" ")} && _opts+=("--${opt.cliName}${desc}")`);
1887
- if (opt.negation) lines.push(` __${fn}_not_used ${patterns.join(" ")} && _opts+=("--${opt.negation}${negDesc}")`);
1888
- }
1889
- }
1890
- lines.push(` __${fn}_not_used "--help" && _opts+=("--help:Show help")`);
1891
- return lines;
1892
- }
1893
- /**
1894
- * Generate a per-subcommand completion function.
1895
- * Recursively generates functions for nested subcommands.
1896
- */
1897
- function generateSubHandler(sub, fn, path) {
1898
- const fullPath = [...path, sub.name];
1899
- const funcName = `__${fn}_complete_${fullPath.map(sanitize).join("_")}`;
1900
- const visibleSubs = getVisibleSubs(sub.subcommands);
1901
- const lines = [];
1902
- for (const child of visibleSubs) lines.push(...generateSubHandler(child, fn, fullPath));
1903
- lines.push(`${funcName}() {`);
1904
- lines.push(` local -a _vals=()`);
1905
- lines.push(...valueCompletionBlock(sub.options, fn));
1906
- const fullPathStr = fullPath.join(":");
1907
- lines.push(` if __${fn}_opt_takes_value "${fullPathStr}" "\${words[CURRENT-1]}"; then return 0; fi`);
1908
- if (sub.positionals.length > 0) {
1909
- lines.push(` if (( _after_dd )); then`);
1910
- lines.push(...positionalBlock(sub.positionals, fn).map((l) => ` ${l}`));
1911
- lines.push(` return 0`);
1912
- lines.push(` fi`);
1913
- } else lines.push(` if (( _after_dd )); then return 0; fi`);
1914
- lines.push(` if [[ "\${words[CURRENT]}" == -* ]]; then`);
1915
- lines.push(` local -a _opts=()`);
1916
- lines.push(...availableOptionLines(sub.options, fn));
1917
- lines.push(` __${fn}_cdescribe 'options' _opts`);
1918
- lines.push(` return 0`);
1919
- lines.push(` fi`);
1920
- if (visibleSubs.length > 0) {
1921
- const subItems = getSubNamesWithAliases(sub.subcommands).map((s) => {
1922
- const desc = s.description ? `:${escapeDesc(s.description)}` : "";
1923
- return `"${s.name}${desc}"`;
1924
- }).join(" ");
1925
- lines.push(` local -a _subs=(${subItems})`);
1926
- lines.push(` __${fn}_cdescribe 'subcommands' _subs`);
1927
- } else if (sub.positionals.length > 0) lines.push(...positionalBlock(sub.positionals, fn));
1928
- lines.push(`}`);
1929
- lines.push(``);
1930
- return lines;
1931
- }
1932
- function generateZshCompletion(command, options) {
1933
- const { programName } = options;
1934
- const data = extractCompletionData(command, programName, options.globalArgsSchema);
1935
- const fn = sanitize(programName);
1936
- const root = data.command;
1937
- const visibleSubs = getVisibleSubs(root.subcommands);
1938
- const lines = [];
1939
- lines.push(`#compdef ${programName}`);
1940
- lines.push(``);
1941
- lines.push(...buildHeaderLines({
1942
- programName,
1943
- shell: "zsh",
1944
- binPath: options.binPath,
1945
- programVersion: options.programVersion
1946
- }));
1947
- lines.push(`# Generated by politty`);
1948
- lines.push(``);
1949
- lines.push(`__${fn}_not_used() {`);
1950
- lines.push(` local _u _chk`);
1951
- lines.push(` for _u in "\${_used_opts[@]}"; do`);
1952
- lines.push(` for _chk in "$@"; do`);
1953
- lines.push(` [[ "$_u" == "$_chk" ]] && return 1`);
1954
- lines.push(` done`);
1955
- lines.push(` done`);
1956
- lines.push(` return 0`);
1957
- lines.push(`}`);
1958
- lines.push(``);
1959
- lines.push(`__${fn}_cdescribe() {`);
1960
- lines.push(` _describe "$@" 2>/dev/null && return 0`);
1961
- lines.push(` shift`);
1962
- lines.push(` local -a _cd_vals=("\${(@)\${(P)1}%%:*}")`);
1963
- lines.push(` compadd -a _cd_vals 2>/dev/null`);
1964
- lines.push(` return 0`);
1965
- lines.push(`}`);
1966
- lines.push(``);
1967
- lines.push(`__${fn}_opt_takes_value() {`);
1968
- lines.push(` case "$1:$2" in`);
1969
- lines.push(...optTakesValueEntries(root, ""));
1970
- lines.push(` esac`);
1971
- lines.push(` return 1`);
1972
- lines.push(`}`);
1973
- lines.push(``);
1974
- const routeEntries = collectRouteEntries(root);
1975
- if (routeEntries.length > 0) {
1976
- lines.push(`__${fn}_is_subcmd() {`);
1977
- lines.push(` case "$1:$2" in`);
1978
- lines.push(...isSubcmdCaseLines(routeEntries));
1979
- lines.push(` esac`);
1980
- lines.push(` return 1`);
1981
- lines.push(`}`);
1982
- lines.push(``);
1983
- }
1984
- for (const sub of visibleSubs) lines.push(...generateSubHandler(sub, fn, []));
1985
- lines.push(`__${fn}_complete_root() {`);
1986
- lines.push(` local -a _vals=()`);
1987
- lines.push(...valueCompletionBlock(root.options, fn));
1988
- lines.push(` if __${fn}_opt_takes_value "" "\${words[CURRENT-1]}"; then return 0; fi`);
1989
- if (root.positionals.length > 0) {
1990
- lines.push(` if (( _after_dd )); then`);
1991
- lines.push(...positionalBlock(root.positionals, fn).map((l) => ` ${l}`));
1992
- lines.push(` return 0`);
1993
- lines.push(` fi`);
1994
- } else lines.push(` if (( _after_dd )); then return 0; fi`);
1995
- lines.push(` if [[ "\${words[CURRENT]}" == -* ]]; then`);
1996
- lines.push(` local -a _opts=()`);
1997
- lines.push(...availableOptionLines(root.options, fn));
1998
- lines.push(` __${fn}_cdescribe 'options' _opts`);
1999
- if (visibleSubs.length > 0) {
2000
- lines.push(` else`);
2001
- const subItems = getSubNamesWithAliases(root.subcommands).map((s) => {
2002
- const desc = s.description ? `:${escapeDesc(s.description)}` : "";
2003
- return `"${s.name}${desc}"`;
2004
- }).join(" ");
2005
- lines.push(` local -a _subs=(${subItems})`);
2006
- lines.push(` __${fn}_cdescribe 'subcommands' _subs`);
2007
- } else if (root.positionals.length > 0) {
2008
- lines.push(` else`);
2009
- lines.push(...positionalBlock(root.positionals, fn).map((l) => ` ${l}`));
2010
- }
2011
- lines.push(` fi`);
2012
- lines.push(`}`);
2013
- lines.push(``);
2014
- const subRouting = routeEntries.map((r) => ` ${r.pathStr}) __${fn}_complete_${r.funcSuffix} ;;`).join("\n");
2015
- lines.push(`_${fn}() {`);
2016
- lines.push(` (( CURRENT )) || CURRENT=\${#words}`);
2017
- lines.push(``);
2018
- lines.push(` local _subcmd="" _after_dd=0 _pos_count=0 _skip_next=0`);
2019
- lines.push(` local -a _used_opts=()`);
2020
- lines.push(``);
2021
- lines.push(` local _j=2`);
2022
- lines.push(` while (( _j < CURRENT )); do`);
2023
- lines.push(` local _w="\${words[_j]}"`);
2024
- lines.push(` if (( _skip_next )); then _skip_next=0; (( _j++ )); continue; fi`);
2025
- lines.push(` if [[ "$_w" == "--" ]]; then _after_dd=1; (( _j++ )); continue; fi`);
2026
- lines.push(` if (( _after_dd )); then (( _pos_count++ )); (( _j++ )); continue; fi`);
2027
- lines.push(` if [[ "$_w" == --*=* ]]; then _used_opts+=("\${_w%%=*}"); (( _j++ )); continue; fi`);
2028
- lines.push(` if [[ "$_w" == -* ]]; then`);
2029
- lines.push(` _used_opts+=("$_w")`);
2030
- lines.push(` __${fn}_opt_takes_value "$_subcmd" "$_w" && _skip_next=1`);
2031
- lines.push(` (( _j++ )); continue`);
2032
- lines.push(` fi`);
2033
- 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`);
2034
- else lines.push(` (( _pos_count++ ))`);
2035
- lines.push(` (( _j++ ))`);
2036
- lines.push(` done`);
2037
- lines.push(``);
2038
- lines.push(` case "$_subcmd" in`);
2039
- lines.push(subRouting);
2040
- lines.push(` *) __${fn}_complete_root ;;`);
2041
- lines.push(` esac`);
2042
- lines.push(`}`);
2043
- lines.push(``);
2044
- lines.push(`zstyle ':completion:*:*:${programName}:*' file-patterns '%p:globbed-files *(-/):directories'`);
2045
- lines.push(``);
2046
- lines.push(`compdef _${fn} ${programName}`);
2047
- lines.push(``);
2048
- return {
2049
- script: lines.join("\n"),
2050
- shell: "zsh",
2051
- installInstructions: `# To enable completions, add the following to your ~/.zshrc:
2052
-
2053
- # Option 1: Source directly (add before compinit)
2054
- eval "$(${programName} completion zsh)"
2055
-
2056
- # Option 2: Save to a file in your fpath
2057
- ${programName} completion zsh > ~/.zsh/completions/_${programName}
2058
-
2059
- # Make sure your fpath includes the completions directory:
2060
- # fpath=(~/.zsh/completions $fpath)
2061
- # autoload -Uz compinit && compinit
2062
-
2063
- # Then reload your shell or run:
2064
- source ~/.zshrc`
2065
- };
2066
- }
2067
-
2068
- //#endregion
2069
- //#region src/completion/index.ts
2070
- /**
2071
- * Shell completion generation module
2072
- *
2073
- * Provides utilities to generate shell completion scripts for bash, zsh, and fish.
2074
- *
2075
- * @example
2076
- * ```typescript
2077
- * import { generateCompletion, createCompletionCommand } from "politty/completion";
2078
- *
2079
- * // Generate completion script directly
2080
- * const result = generateCompletion(myCommand, {
2081
- * shell: "bash",
2082
- * programName: "mycli"
2083
- * });
2084
- * console.log(result.script);
2085
- *
2086
- * // Or add a completion subcommand to your CLI
2087
- * const mainCommand = withCompletionCommand(
2088
- * defineCommand({
2089
- * name: "mycli",
2090
- * subCommands: { ... },
2091
- * }),
2092
- * );
2093
- * ```
2094
- */
2095
- /**
2096
- * Generate completion script for the specified shell
2097
- */
2098
- function generateCompletion(command, options) {
2099
- switch (options.shell) {
2100
- case "bash": return generateBashCompletion(command, options);
2101
- case "zsh": return generateZshCompletion(command, options);
2102
- case "fish": return generateFishCompletion(command, options);
2103
- default: throw new Error(`Unsupported shell: ${options.shell}`);
2104
- }
2105
- }
2106
- /**
2107
- * Get the list of supported shells
2108
- */
2109
- function getSupportedShells() {
2110
- return [
2111
- "bash",
2112
- "zsh",
2113
- "fish"
2114
- ];
2115
- }
2116
- /**
2117
- * Detect the current shell from environment
2118
- */
2119
- function detectShell() {
2120
- const shellName = (process.env.SHELL || "").split("/").pop()?.toLowerCase() || "";
2121
- if (shellName.includes("bash")) return "bash";
2122
- if (shellName.includes("zsh")) return "zsh";
2123
- if (shellName.includes("fish")) return "fish";
2124
- return null;
2125
- }
2126
- /**
2127
- * Schema for the completion command arguments
2128
- */
2129
- const completionArgsSchema = z.object({
2130
- shell: arg(z.enum([
2131
- "bash",
2132
- "zsh",
2133
- "fish"
2134
- ]).optional().describe("Shell type (auto-detected if not specified)"), {
2135
- positional: true,
2136
- description: "Shell type (bash, zsh, or fish)",
2137
- placeholder: "SHELL"
2138
- }),
2139
- instructions: arg(z.boolean().default(false), {
2140
- alias: "i",
2141
- description: "Show installation instructions"
2142
- }),
2143
- loader: arg(z.boolean().default(false), { description: "Print just the rc loader snippet (bash/zsh). Add it to ~/.bashrc or ~/.zshrc; it auto-regenerates the cache when the binary changes." }),
2144
- install: arg(z.boolean().default(false), { description: "Write the completion script to its on-disk cache (bash/zsh) or autoload location (fish) instead of printing it." })
2145
- });
2146
- const refreshArgsSchema = z.object({ shell: arg(z.enum([
2147
- "bash",
2148
- "zsh",
2149
- "fish"
2150
- ]), {
2151
- positional: true,
2152
- description: "Shell to refresh",
2153
- placeholder: "SHELL"
2154
- }) });
2155
- /**
2156
- * Create a completion subcommand for your CLI
2157
- *
2158
- * This creates a ready-to-use subcommand that generates completion scripts.
2159
- *
2160
- * @example
2161
- * ```typescript
2162
- * const mainCommand = defineCommand({
2163
- * name: "mycli",
2164
- * subCommands: {
2165
- * completion: createCompletionCommand(mainCommand)
2166
- * }
2167
- * });
2168
- * ```
2169
- */
2170
- function createCompletionCommand(rootCommand, programName, globalArgsSchema, extra = {}) {
2171
- const resolvedProgramName = programName ?? rootCommand.name;
2172
- const { cacheDir, programVersion } = extra;
2173
- const refreshExtra = {
2174
- ...cacheDir !== void 0 && { cacheDir },
2175
- ...programVersion !== void 0 && { programVersion },
2176
- ...globalArgsSchema !== void 0 && { globalArgsSchema }
2177
- };
2178
- const installCtxBase = {
2179
- programName: resolvedProgramName,
2180
- ...refreshExtra
2181
- };
2182
- const loaderOptsBase = {
2183
- programName: resolvedProgramName,
2184
- ...cacheDir !== void 0 && { cacheDir }
2185
- };
2186
- if (!rootCommand.subCommands?.__complete) rootCommand.subCommands = {
2187
- ...rootCommand.subCommands,
2188
- __complete: createDynamicCompleteCommand(rootCommand, resolvedProgramName)
2189
- };
2190
- if (!rootCommand.subCommands?.["__refresh-completion"]) rootCommand.subCommands = {
2191
- ...rootCommand.subCommands,
2192
- "__refresh-completion": createRefreshCompletionCommand(rootCommand, resolvedProgramName, refreshExtra)
2193
- };
2194
- return defineCommand({
2195
- name: "completion",
2196
- description: "Generate shell completion script",
2197
- args: completionArgsSchema,
2198
- run(args) {
2199
- const shellType = args.shell || detectShell();
2200
- if (!shellType) {
2201
- console.error("Could not detect shell type. Please specify one of: bash, zsh, fish");
2202
- process.exitCode = 1;
2203
- return;
2204
- }
2205
- if (args.install) {
2206
- let target;
2207
- try {
2208
- target = install({
2209
- rootCommand,
2210
- ...installCtxBase
2211
- }, shellType);
2212
- } catch (e) {
2213
- throw new Error(`install failed: ${e instanceof Error ? e.message : String(e)}`);
2214
- }
2215
- console.error(`installed: ${target}`);
2216
- if (shellType !== "fish") {
2217
- console.error("");
2218
- console.error(`Add to your ~/.${shellType}rc:`);
2219
- console.error("");
2220
- console.error(generateLoader({
2221
- ...loaderOptsBase,
2222
- shell: shellType
2223
- }).trim().replace(/^/gm, " "));
2224
- }
2225
- return;
2226
- }
2227
- if (args.loader) {
2228
- if (shellType === "fish") throw new Error("fish does not use an rc loader. Run `<program> completion fish --install` to write the self-refreshing autoload file instead.");
2229
- process.stdout.write(generateLoader({
2230
- ...loaderOptsBase,
2231
- shell: shellType
2232
- }));
2233
- return;
2234
- }
2235
- const result = generateCompletion(rootCommand, {
2236
- shell: shellType,
2237
- programName: resolvedProgramName,
2238
- includeDescriptions: true,
2239
- ...globalArgsSchema !== void 0 && { globalArgsSchema },
2240
- ...programVersion !== void 0 && { programVersion },
2241
- ...cacheDir !== void 0 && { cacheDir }
2242
- });
2243
- if (args.instructions) console.log(result.installInstructions);
2244
- else console.log(result.script);
2245
- }
2246
- });
2247
- }
2248
- /**
2249
- * Hidden subcommand that the runMain background hook spawns. It does
2250
- * the same stat-compare + atomic rewrite as the rc loader, but in a
2251
- * detached child process so it's invisible to the user.
2252
- */
2253
- function createRefreshCompletionCommand(rootCommand, programName, extra = {}) {
2254
- return defineCommand({
2255
- name: "__refresh-completion",
2256
- description: "(internal) Refresh the on-disk completion cache if stale.",
2257
- args: refreshArgsSchema,
2258
- run(args) {
2259
- refreshIfStale({
2260
- rootCommand,
2261
- programName,
2262
- ...extra
2263
- }, args.shell);
2264
- }
2265
- });
2266
- }
2267
- /**
2268
- * Wrap a command with a completion subcommand
2269
- *
2270
- * This avoids circular references that occur when a command references itself
2271
- * in its subCommands (e.g., for completion generation).
2272
- *
2273
- * @param command - The command to wrap
2274
- * @param options - Options including programName
2275
- * @returns A new command with the completion subcommand added
2276
- *
2277
- * @example
2278
- * ```typescript
2279
- * const mainCommand = withCompletionCommand(
2280
- * defineCommand({
2281
- * name: "mycli",
2282
- * subCommands: { ... },
2283
- * }),
2284
- * );
2285
- * ```
2286
- */
2287
- function withCompletionCommand(command, options) {
2288
- const { programName, globalArgsSchema, cacheDir, programVersion } = typeof options === "string" ? { programName: options } : options ?? {};
2289
- const resolvedProgramName = programName ?? command.name;
2290
- const extra = {
2291
- ...cacheDir !== void 0 && { cacheDir },
2292
- ...programVersion !== void 0 && { programVersion },
2293
- ...globalArgsSchema !== void 0 && { globalArgsSchema }
2294
- };
2295
- const wrappedCommand = { ...command };
2296
- wrappedCommand.subCommands = {
2297
- ...command.subCommands,
2298
- completion: createCompletionCommand(wrappedCommand, programName, globalArgsSchema, extra),
2299
- __complete: createDynamicCompleteCommand(wrappedCommand, programName),
2300
- "__refresh-completion": createRefreshCompletionCommand(wrappedCommand, resolvedProgramName, extra)
2301
- };
2302
- wrappedCommand.runMainHook = (argv) => {
2303
- maybeSpawnRefresh(argv, {
2304
- programName: resolvedProgramName,
2305
- ...cacheDir !== void 0 && { cacheDir }
2306
- });
2307
- };
2308
- return wrappedCommand;
2309
- }
2310
- /**
2311
- * Background-refresh trigger fired from `runMain` via `runMainHook`.
2312
- *
2313
- * Skipped when:
2314
- * - the user is invoking `__complete` / `__refresh-completion` /
2315
- * `completion` themselves (avoids loops and double work)
2316
- * - $SHELL doesn't resolve to a known shell
2317
- * - the user opted out via $POLITTY_NO_COMPLETION_REFRESH
2318
- * - process.argv[1] is missing (shouldn't happen for normal CLIs)
2319
- * - no politty-managed cache exists yet — i.e. the user hasn't
2320
- * installed completion. Without this gate the detached child would
2321
- * create a fish autoload (or any cache file) on every CLI run,
2322
- * even though the user never opted in via `--install` or the rc loader.
2323
- */
2324
- function maybeSpawnRefresh(argv, ctx) {
2325
- if (process.env.POLITTY_NO_COMPLETION_REFRESH) return;
2326
- const firstPositional = argv.find((a) => !a.startsWith("-"));
2327
- if (firstPositional === "__complete" || firstPositional === "__refresh-completion" || firstPositional === "completion") return;
2328
- const shell = detectShell();
2329
- if (!shell) return;
2330
- const argv0 = process.argv[1];
2331
- if (!argv0) return;
2332
- if (!hasManagedCache(ctx, shell)) return;
2333
- spawnBackgroundRefresh(argv0, shell);
2334
- }
2335
-
2336
- //#endregion
2337
- export { defineCommand as _, getSupportedShells as a, hasCompleteCommand as c, CompletionDirective as d, generateCandidates as f, createDefineCommand as g, resolveValueCompletion as h, generateCompletion as i, formatForShell as l, extractPositionals as m, createRefreshCompletionCommand as n, withCompletionCommand as o, extractCompletionData as p, detectShell as r, createDynamicCompleteCommand as s, createCompletionCommand as t, parseCompletionContext as u };
2338
- //# sourceMappingURL=completion-B04iiki9.js.map