politty 0.4.16 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (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-BFOAOg95.cjs +4294 -0
  12. package/dist/completion-BFOAOg95.cjs.map +1 -0
  13. package/dist/completion-K5LGh1hO.js +4192 -0
  14. package/dist/completion-K5LGh1hO.js.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-DR9HLxIP.d.ts → index-Cg8qstsT.d.cts} +136 -15
  21. package/dist/index-Cg8qstsT.d.cts.map +1 -0
  22. package/dist/{index-CPebddth.d.cts → index-O3yn97Ed.d.ts} +136 -15
  23. package/dist/index-O3yn97Ed.d.ts.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 +8 -8
  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
@@ -0,0 +1,4294 @@
1
+ const require_log_collector = require('./log-collector-Cd2_mv87.cjs');
2
+ const require_schema_extractor = require('./schema-extractor-SLPgBNgZ.cjs');
3
+ let zod = require("zod");
4
+ let node_child_process = require("node:child_process");
5
+ let node_fs = require("node:fs");
6
+ let node_path = require("node:path");
7
+
8
+ //#region src/core/command.ts
9
+ function defineCommand(config) {
10
+ return {
11
+ name: config.name,
12
+ description: config.description,
13
+ aliases: config.aliases,
14
+ args: config.args,
15
+ subCommands: config.subCommands,
16
+ setup: config.setup,
17
+ run: config.run,
18
+ cleanup: config.cleanup,
19
+ notes: config.notes,
20
+ examples: config.examples
21
+ };
22
+ }
23
+ /**
24
+ * Create a typed defineCommand factory with pre-bound global args type.
25
+ * This is the recommended pattern for type-safe global options.
26
+ *
27
+ * @example
28
+ * ```ts
29
+ * // global-args.ts
30
+ * type GlobalArgsType = { verbose: boolean; config?: string };
31
+ * export const defineAppCommand = createDefineCommand<GlobalArgsType>();
32
+ *
33
+ * // commands/build.ts
34
+ * export const buildCommand = defineAppCommand({
35
+ * name: "build",
36
+ * args: z.object({ output: arg(z.string().default("dist")) }),
37
+ * run: (args) => {
38
+ * args.verbose; // typed via GlobalArgsType
39
+ * args.output; // typed via local args
40
+ * },
41
+ * });
42
+ * ```
43
+ */
44
+ function createDefineCommand() {
45
+ return defineCommand;
46
+ }
47
+
48
+ //#endregion
49
+ //#region src/completion/shell-shared.ts
50
+ /**
51
+ * Helpers shared across the bash/zsh/fish completion generators.
52
+ *
53
+ * The three generators are necessarily distinct (each shell has its own
54
+ * syntax) but they share a handful of building blocks: ANSI-C literal
55
+ * encoding, the `--alias`/`-a` token shape, and the resolved-dep records
56
+ * that drive expand lookups. Keeping these in one place avoids drift
57
+ * when one generator gets a fix that the others should mirror.
58
+ */
59
+ /**
60
+ * Build the shell-agnostic part of an expand location for an option. Wraps
61
+ * `resolveExpandDepGlobality` so the three generators don't each repeat the
62
+ * `(opt.valueCompletion, opt.isGlobal === true, options, positionals)`
63
+ * incantation.
64
+ */
65
+ function optionExpandLocation(opt, frameOptions, framePositionals) {
66
+ return {
67
+ fieldName: opt.name,
68
+ isArrayOption: opt.valueType === "array",
69
+ isGlobal: opt.isGlobal === true,
70
+ resolvedDeps: resolveExpandDepGlobality(opt.valueCompletion, opt.isGlobal === true, frameOptions, framePositionals)
71
+ };
72
+ }
73
+ /**
74
+ * Shell-agnostic expand location for a positional. Positionals are never
75
+ * global (the runtime parser does not propagate positionals across frames)
76
+ * and never array-dedup hosts (`key=value` semantics don't apply), so those
77
+ * bits are hard-coded.
78
+ */
79
+ function positionalExpandLocation(pos, frameOptions, framePositionals) {
80
+ return {
81
+ fieldName: pos.name,
82
+ isArrayOption: false,
83
+ isGlobal: false,
84
+ resolvedDeps: resolveExpandDepGlobality(pos.valueCompletion, false, frameOptions, framePositionals)
85
+ };
86
+ }
87
+ /**
88
+ * Resolve each `dependsOn` entry to its globality at codegen time. A
89
+ * global host's deps all live in the global namespace. A local host
90
+ * may declare deps against a propagated global (its sibling index
91
+ * includes globals); those individual deps must read from the global
92
+ * bucket even when the host itself is local — the tracker only ever
93
+ * writes the global value into \`_global_arg_values_<name>\`, so a
94
+ * lookup against the local bucket would see the empty key.
95
+ *
96
+ * Local-precedence matches `buildSiblingIndex` in `expand-resolver.ts`:
97
+ * a dep name that exists on a local field (option OR positional) at the
98
+ * frame resolves to the local, even if a same-named global also exists.
99
+ * Marking such a dep as global would route the lookup at the wrong
100
+ * bucket and produce no candidates.
101
+ */
102
+ function resolveExpandDepGlobality(vc, hostIsGlobal, frameOptions, framePositionals = []) {
103
+ if (vc?.type !== "expand") return [];
104
+ const globalOptionNames = /* @__PURE__ */ new Set();
105
+ const localFieldNames = /* @__PURE__ */ new Set();
106
+ for (const o of frameOptions) if (o.isGlobal === true) globalOptionNames.add(o.name);
107
+ else localFieldNames.add(o.name);
108
+ for (const p of framePositionals) localFieldNames.add(p.name);
109
+ return vc.dependsOn.map((name) => ({
110
+ name,
111
+ isGlobal: hostIsGlobal || globalOptionNames.has(name) && !localFieldNames.has(name)
112
+ }));
113
+ }
114
+ /**
115
+ * Encode a string as an ANSI-C shell literal (`$'…'`) with backslash
116
+ * escapes. Used by bash and zsh to embed expand-table values so newlines,
117
+ * the unit-separator key delimiter, and other control characters survive
118
+ * verbatim.
119
+ */
120
+ function ansiC(s) {
121
+ let out = "$'";
122
+ for (const ch of s) {
123
+ const code = ch.codePointAt(0);
124
+ if (ch === "\\") out += "\\\\";
125
+ else if (ch === "'") out += "\\'";
126
+ else if (ch === "\n") out += "\\n";
127
+ else if (ch === "\r") out += "\\r";
128
+ else if (ch === " ") out += "\\t";
129
+ else if (code < 32 || code === 127) out += `\\x${code.toString(16).padStart(2, "0")}`;
130
+ else out += ch;
131
+ }
132
+ out += "'";
133
+ return out;
134
+ }
135
+ /**
136
+ * Render an alias as its CLI token form: single-char aliases become `-x`,
137
+ * multi-char aliases become `--long`. Mirrors the parser's accepted shapes
138
+ * and is the bare-token form (no quoting) used inside generated case
139
+ * patterns.
140
+ */
141
+ function aliasToken(alias) {
142
+ return alias.length === 1 ? `-${alias}` : `--${alias}`;
143
+ }
144
+ /**
145
+ * Append every alternate spelling runtime's aliasMap accepts for an alias:
146
+ * `-a` / `--a` for single-char, `--to-be` / `--toBe` for hyphenated.
147
+ * Shared between {@link collectOptionTokens} and {@link localShadowingTokens}.
148
+ */
149
+ function pushAliasTokens(tokens, a) {
150
+ pushUnique(tokens, aliasToken(a));
151
+ if (a.length === 1) pushUnique(tokens, `--${a}`);
152
+ else if (a.includes("-")) pushUnique(tokens, `--${require_schema_extractor.toCamelCase(a)}`);
153
+ }
154
+ function pushUnique(tokens, t) {
155
+ if (!tokens.includes(t)) tokens.push(t);
156
+ }
157
+ /**
158
+ * Every CLI spelling the runtime's aliasMap routes to this option:
159
+ * - `--cliName` (always),
160
+ * - `-x` when `cliName` is one character,
161
+ * - `--toCamelCase(cliName)` when `cliName` is hyphenated,
162
+ * - and the analogous forms for each alias.
163
+ *
164
+ * The order is stable so shell-side case patterns stay diff-friendly.
165
+ */
166
+ function collectOptionTokens(cliName, aliases) {
167
+ const tokens = [`--${cliName}`];
168
+ if (cliName.length === 1) tokens.push(`-${cliName}`);
169
+ if (cliName.includes("-")) tokens.push(`--${require_schema_extractor.toCamelCase(cliName)}`);
170
+ for (const a of aliases ?? []) pushAliasTokens(tokens, a);
171
+ return tokens;
172
+ }
173
+ /**
174
+ * Single-character tokens (`-x`) that global options at this frame own.
175
+ * Shared between availability-guard and value-completion token filtering:
176
+ * both paths must agree on which short forms `separateGlobalArgs` routes
177
+ * to a global rather than a same-letter local.
178
+ */
179
+ function globalShortTokens(frameOptions) {
180
+ const out = /* @__PURE__ */ new Set();
181
+ for (const o of frameOptions) {
182
+ if (o.isGlobal !== true) continue;
183
+ if (o.cliName.length === 1) out.add(`-${o.cliName}`);
184
+ for (const a of o.alias ?? []) if (a.length === 1) out.add(`-${a}`);
185
+ }
186
+ return out;
187
+ }
188
+ /**
189
+ * Build the quoted-token list bash/zsh/fish pass to `__<fn>_not_used` to
190
+ * decide whether an option (and its negation form, if any) is still
191
+ * available. Quoting style (`"…"`) is identical across all three shells,
192
+ * so the helper lives here instead of being re-derived per generator.
193
+ */
194
+ function quotedAvailabilityTokens(cliName, aliases, negation, options) {
195
+ const tokens = new Set(collectOptionTokens(cliName, aliases));
196
+ if (negation) {
197
+ tokens.add(`--${negation}`);
198
+ if (negation.includes("-")) tokens.add(`--${require_schema_extractor.toCamelCase(negation)}`);
199
+ }
200
+ if (options?.frameOptions) if (options.isGlobal === true) for (const o of options.frameOptions) {
201
+ if (o.isGlobal === true) continue;
202
+ for (const t of localShadowingTokens(o.cliName, o.alias)) tokens.delete(t);
203
+ }
204
+ else {
205
+ const globalShort = globalShortTokens(options.frameOptions);
206
+ if (globalShort.size > 0) {
207
+ const localExplicitShort = new Set((aliases ?? []).filter((a) => a.length === 1).map((a) => `-${a}`));
208
+ for (const g of globalShort) if (!localExplicitShort.has(g)) tokens.delete(g);
209
+ }
210
+ }
211
+ return [...tokens].map((t) => `"${t}"`);
212
+ }
213
+ /**
214
+ * Tokens the runtime's `separateGlobalArgs` would consider locally
215
+ * owned at the leaf: long-form cliName plus every EXPLICIT alias
216
+ * spelling (in all forms the aliasMap accepts — `-a`/`--a` for short,
217
+ * `--to-be`/`--toBe` for hyphenated). Excludes the auto-derived `-x`
218
+ * for a 1-char cliName because that short form lives in the local
219
+ * aliasMap only when an explicit alias declares it.
220
+ */
221
+ function localShadowingTokens(cliName, aliases) {
222
+ const tokens = [`--${cliName}`];
223
+ if (cliName.includes("-")) tokens.push(`--${require_schema_extractor.toCamelCase(cliName)}`);
224
+ for (const a of aliases ?? []) pushAliasTokens(tokens, a);
225
+ return tokens;
226
+ }
227
+
228
+ //#endregion
229
+ //#region src/completion/value-completion-resolver.ts
230
+ /**
231
+ * Resolve value completion from field metadata.
232
+ *
233
+ * Priority (within `custom`): `expand` > `resolve` > `choices` > `shellCommand`.
234
+ * Specifying more than one of these on the same field throws so the
235
+ * misconfiguration surfaces at command-definition time rather than at
236
+ * completion time. The `expand` variant returns a sentinel — the extractor
237
+ * resolves it against sibling fields and replaces the sentinel with a
238
+ * `{ type: "expand", table, dependsOn }` entry.
239
+ *
240
+ * Outside `custom`: explicit `type` (file/directory/none) > auto-detected
241
+ * enum values from the schema.
242
+ */
243
+ function resolveValueCompletion(field) {
244
+ const meta = field.completion;
245
+ if (meta?.custom) {
246
+ const c = meta.custom;
247
+ const definedKeys = [];
248
+ if (c.expand) definedKeys.push("expand");
249
+ if (c.resolve) definedKeys.push("resolve");
250
+ if (c.choices && c.choices.length > 0) definedKeys.push("choices");
251
+ if (c.shellCommand) definedKeys.push("shellCommand");
252
+ if (definedKeys.length > 1) throw new Error(`Field "${field.name ?? "<unknown>"}": completion.custom may only specify one of choices, shellCommand, resolve, expand (got ${definedKeys.join(", ")}).`);
253
+ if (c.expand) return {
254
+ type: "pending-expand",
255
+ spec: c.expand
256
+ };
257
+ if (c.resolve) return {
258
+ type: "dynamic",
259
+ resolve: c.resolve
260
+ };
261
+ if (c.choices && c.choices.length > 0) return {
262
+ type: "choices",
263
+ choices: c.choices
264
+ };
265
+ if (c.shellCommand) return {
266
+ type: "command",
267
+ shellCommand: c.shellCommand
268
+ };
269
+ }
270
+ if (meta?.type) {
271
+ if (meta.type === "file") {
272
+ if (meta.matcher) return {
273
+ type: "file",
274
+ matcher: meta.matcher
275
+ };
276
+ if (meta.extensions) return {
277
+ type: "file",
278
+ extensions: meta.extensions
279
+ };
280
+ return { type: "file" };
281
+ }
282
+ if (meta.type === "directory") return { type: "directory" };
283
+ if (meta.type === "none") return { type: "none" };
284
+ }
285
+ if (field.enumValues && field.enumValues.length > 0) return {
286
+ type: "choices",
287
+ choices: field.enumValues
288
+ };
289
+ }
290
+
291
+ //#endregion
292
+ //#region src/completion/dynamic/context-parser.ts
293
+ /**
294
+ * Parse completion context from partial command line
295
+ */
296
+ /**
297
+ * The dynamic completion path runs `__complete` at TAB time and never sees
298
+ * "expand" fields (those are handled inline by the static shell script).
299
+ * Strip the transient pending sentinel here so the rest of the runtime path
300
+ * can stay strict about handling only resolved `ValueCompletion` values.
301
+ */
302
+ function stripPendingExpand(vc) {
303
+ return vc?.type === "pending-expand" ? void 0 : vc;
304
+ }
305
+ /**
306
+ * Extract options from a command
307
+ */
308
+ function extractOptions(command) {
309
+ if (!command.args) return [];
310
+ return extractOptionsFromSchema(command.args);
311
+ }
312
+ function extractOptionsFromSchema(schema) {
313
+ return require_schema_extractor.extractFields(schema).fields.filter((field) => !field.positional).map((field) => {
314
+ const aliases = require_schema_extractor.getAllAliases(field);
315
+ return {
316
+ name: field.name,
317
+ cliName: field.cliName,
318
+ alias: aliases.length > 0 ? aliases : void 0,
319
+ negation: field.negationDisplay,
320
+ negationDescription: field.negationDescription,
321
+ description: field.description,
322
+ takesValue: field.type !== "boolean",
323
+ valueType: field.type,
324
+ required: field.required,
325
+ defaultNegationAccepted: field.type === "boolean" && (field.negation === void 0 || field.negation === true),
326
+ valueCompletion: stripPendingExpand(resolveValueCompletion(field))
327
+ };
328
+ });
329
+ }
330
+ /**
331
+ * Build the CLI tokens an option is recognised by (`--cliName`,
332
+ * `--long-alias`, `-x`). Wraps `collectOptionTokens` so collision
333
+ * detection sees every spelling the runtime aliasMap accepts — including
334
+ * the camelCase form of hyphenated names, without which a parent-frame
335
+ * local that intercepts `--toBe` for a global `to-be` would silently
336
+ * skip the migration loop.
337
+ */
338
+ function optionTokenSet(opt) {
339
+ return new Set(collectOptionTokens(opt.cliName, opt.alias));
340
+ }
341
+ /**
342
+ * Find a global option whose CLI tokens overlap with `local`'s tokens.
343
+ * Used at subcommand descent to migrate values the runtime's
344
+ * `scanForSubcommand` would have routed to a global field even though
345
+ * the completion parser stored them under a different-named local.
346
+ */
347
+ function findGlobalByTokenCollision(globals, local) {
348
+ const localTokens = optionTokenSet(local);
349
+ for (const g of globals) for (const t of optionTokenSet(g)) if (localTokens.has(t)) return g;
350
+ }
351
+ /**
352
+ * Mirror runtime `scanForSubcommand`: walk a pre-subcommand token slice
353
+ * with the global schema only, populating `globalParsedArgs` with the
354
+ * values the runtime would have routed there before the next subcommand
355
+ * boundary. Runs at every subcommand descent — the runtime invokes
356
+ * `scanForSubcommand` recursively at each frame in `parseArgs`, so the
357
+ * pre-sub global pass applies per descent, not just from root.
358
+ *
359
+ * Returns the set of global option names captured during this pre-scan.
360
+ * Used at descent to skip the local→global token migration for entries
361
+ * whose true value is already known here — a value-taking global
362
+ * aliased the same as a parent-local boolean (e.g. global `--profile`
363
+ * /`-p` and local boolean `alias: "p"`) would otherwise have `true`
364
+ * written over the genuine `"prod"`.
365
+ */
366
+ function parsePreSubGlobals(tokens, globalOptions, globalParsedArgs) {
367
+ const captured = /* @__PURE__ */ new Set();
368
+ if (globalOptions.length === 0) return captured;
369
+ const arrayWrittenInThisSlice = /* @__PURE__ */ new Set();
370
+ const writeGlobal = (opt, value) => {
371
+ writeOptionValue(globalParsedArgs, opt, value, arrayWrittenInThisSlice);
372
+ captured.add(opt.name);
373
+ };
374
+ let i = 0;
375
+ while (i < tokens.length) {
376
+ const word = tokens[i];
377
+ if (word === "--") break;
378
+ if (!word.startsWith("-")) break;
379
+ if (!word.startsWith("--") && word.length > 2) {
380
+ const eqIdx = word.indexOf("=");
381
+ if ((eqIdx >= 0 ? word.slice(1, eqIdx) : word.slice(1)).length > 1) break;
382
+ }
383
+ const parsed = parseOption(word);
384
+ const opt = findOption(globalOptions, parsed);
385
+ if (!opt) break;
386
+ if (opt.takesValue) if (hasInlineValue(word)) {
387
+ const eqIdx = word.indexOf("=");
388
+ writeGlobal(opt, word.slice(eqIdx + 1));
389
+ i++;
390
+ } else if (i + 1 < tokens.length) {
391
+ const next = tokens[i + 1];
392
+ if (next.startsWith("-")) {
393
+ i++;
394
+ continue;
395
+ }
396
+ writeGlobal(opt, next);
397
+ i += 2;
398
+ } else break;
399
+ else {
400
+ globalParsedArgs[opt.name] = !isNegationOf(opt, parsed);
401
+ captured.add(opt.name);
402
+ i++;
403
+ }
404
+ }
405
+ return captured;
406
+ }
407
+ /**
408
+ * Reshape a value pulled from local storage so it matches the global's
409
+ * declared shape before landing in `globalParsedArgs`. Without this,
410
+ * migrating a local scalar into an array global would expose the
411
+ * resolver to `parsedArgs.tags === "foo"` instead of `["foo"]` — a
412
+ * state the runtime parser never produces.
413
+ */
414
+ function adaptValueForGlobal(value, global) {
415
+ if (global.valueType === "array") {
416
+ if (Array.isArray(value)) return value;
417
+ return [value];
418
+ }
419
+ if (Array.isArray(value)) return value.at(-1);
420
+ return value;
421
+ }
422
+ /**
423
+ * Append globals to local, preserving local-shadowing by list ORDER rather
424
+ * than by exclusion. Keeping a global in the merged list — even when a
425
+ * local declares the same `cliName` — lets a global's non-colliding tokens
426
+ * (e.g. a `-e` alias the local does not redeclare) still resolve to the
427
+ * global. `findOption` walks the list and returns the first match, so a
428
+ * token the local actually owns still wins.
429
+ */
430
+ function mergeGlobalOptions(local, globals) {
431
+ if (globals.length === 0) return local;
432
+ return [...local, ...globals];
433
+ }
434
+ /**
435
+ * Clamp a positional index against `positionals` so a value past the last
436
+ * declared positional resolves to the trailing variadic slot (if any).
437
+ * Returns `undefined` only when `positionals` is empty — callers can then
438
+ * skip the variadic/previousValues path entirely.
439
+ */
440
+ function clampToVariadic(positionalIndex, positionals) {
441
+ const lastIdx = positionals.length - 1;
442
+ if (lastIdx < 0) return void 0;
443
+ return positionalIndex > lastIdx ? lastIdx : positionalIndex;
444
+ }
445
+ /**
446
+ * Extract positionals from a command
447
+ */
448
+ function extractPositionalsForContext(command) {
449
+ if (!command.args) return [];
450
+ return require_schema_extractor.extractFields(command.args).fields.filter((field) => field.positional).map((field, index) => ({
451
+ name: field.name,
452
+ cliName: field.cliName,
453
+ position: index,
454
+ description: field.description,
455
+ required: field.required,
456
+ variadic: field.type === "array",
457
+ valueCompletion: stripPendingExpand(resolveValueCompletion(field))
458
+ }));
459
+ }
460
+ /**
461
+ * Get subcommand names from a command (including aliases)
462
+ */
463
+ function getSubcommandNames(command) {
464
+ if (!command.subCommands) return [];
465
+ const names = [];
466
+ for (const [name, subCmd] of Object.entries(command.subCommands)) {
467
+ if (name.startsWith("__")) continue;
468
+ names.push(name);
469
+ const meta = require_schema_extractor.resolveSubCommandMeta(subCmd);
470
+ if (meta?.aliases) names.push(...meta.aliases);
471
+ }
472
+ return names;
473
+ }
474
+ /**
475
+ * Resolve subcommand by name (including alias lookup)
476
+ */
477
+ function resolveSubcommand(command, name) {
478
+ if (!command.subCommands) return null;
479
+ const sub = command.subCommands[name];
480
+ if (sub) return require_schema_extractor.resolveSubCommandMeta(sub);
481
+ const canonical = require_schema_extractor.resolveSubCommandAlias(command, name);
482
+ if (canonical) return require_schema_extractor.resolveSubCommandMeta(command.subCommands[canonical]);
483
+ return null;
484
+ }
485
+ /**
486
+ * Check if a word is an option (starts with - or --)
487
+ */
488
+ function isOption(word) {
489
+ return word.startsWith("-");
490
+ }
491
+ /**
492
+ * Parse option name from word, retaining the form the user typed so the
493
+ * lookup can keep short-form (`-x`) and long-form (`--x`) matches in
494
+ * separate token spaces — runtime negation, cliName, and multi-char
495
+ * aliases only ever appear as long form.
496
+ */
497
+ function parseOption(word) {
498
+ if (word.startsWith("--")) {
499
+ const withoutPrefix = word.slice(2);
500
+ const eqIndex = withoutPrefix.indexOf("=");
501
+ return {
502
+ name: eqIndex >= 0 ? withoutPrefix.slice(0, eqIndex) : withoutPrefix,
503
+ isLong: true
504
+ };
505
+ }
506
+ if (word.startsWith("-")) return {
507
+ name: word.slice(1, 2),
508
+ isLong: false
509
+ };
510
+ return {
511
+ name: word,
512
+ isLong: true
513
+ };
514
+ }
515
+ /**
516
+ * Check if option has inline value (e.g., "--foo=bar")
517
+ */
518
+ function hasInlineValue(word) {
519
+ return word.includes("=");
520
+ }
521
+ /**
522
+ * For boolean options, the runtime parser accepts the implicit
523
+ * `--no-<cliName>` (and camelCase `--noCliName`) form unless the user
524
+ * opted out via `negation: false` or supplied a custom-string negation
525
+ * (which suppresses the default form). Aliases participate too: a
526
+ * boolean with `alias: "c"` accepts `--no-c` / `--noC` because the
527
+ * runtime resolves the post-`no-` segment through `aliasMap`. Implicit
528
+ * negation is LONG-FORM only — `-no-c` is never an accepted negation —
529
+ * so callers must say so via `isLong` to prevent a short option from
530
+ * being read as a negation.
531
+ */
532
+ function isImplicitBooleanNegation(opt, name, isLong) {
533
+ if (!isLong) return false;
534
+ if (opt.valueType !== "boolean") return false;
535
+ if (opt.defaultNegationAccepted === false) return false;
536
+ const candidates = [opt.cliName, ...opt.alias ?? []];
537
+ for (const c of candidates) {
538
+ const hyphenated = `no-${c}`;
539
+ if (name === hyphenated) return true;
540
+ if (name === require_schema_extractor.toCamelCase(hyphenated)) return true;
541
+ }
542
+ return false;
543
+ }
544
+ /** True when `source` is hyphenated and its camelCase form equals `name`. */
545
+ function matchesCamelCase(source, name) {
546
+ return source !== void 0 && source.includes("-") && require_schema_extractor.toCamelCase(source) === name;
547
+ }
548
+ /**
549
+ * Write `value` into `target[opt.name]` following the runtime's per-frame
550
+ * array semantics: the first write in a frame REPLACES any inherited value
551
+ * (mirroring the runtime's shallow merge of inherited globals), subsequent
552
+ * writes in the same frame APPEND. Scalars overwrite unconditionally.
553
+ * `arraysSeenInFrame` is the frame-scoped seen-set the caller maintains.
554
+ */
555
+ function writeOptionValue(target, opt, value, arraysSeenInFrame) {
556
+ if (opt.valueType !== "array") {
557
+ target[opt.name] = value;
558
+ return;
559
+ }
560
+ if (arraysSeenInFrame.has(opt.name)) {
561
+ const existing = target[opt.name];
562
+ target[opt.name] = Array.isArray(existing) ? [...existing, value] : [value];
563
+ } else {
564
+ target[opt.name] = [value];
565
+ arraysSeenInFrame.add(opt.name);
566
+ }
567
+ }
568
+ /**
569
+ * True when the typed token is the boolean option's negation form — either
570
+ * the explicit `negation` name (or its camelCase variant) or the implicit
571
+ * `--no-<name>` form. Long-form only; short tokens are never negations.
572
+ */
573
+ function isNegationOf(opt, parsed) {
574
+ if (!parsed.isLong) return false;
575
+ if (opt.negation !== void 0 && (opt.negation === parsed.name || matchesCamelCase(opt.negation, parsed.name))) return true;
576
+ return isImplicitBooleanNegation(opt, parsed.name, parsed.isLong);
577
+ }
578
+ /**
579
+ * Match by cliName, alias, camelCase variants, or an explicit negation
580
+ * name. `isLong` separates the short (`-x`) and long (`--xxx`) token
581
+ * spaces: cliNames and explicit negations are only valid as long form,
582
+ * and aliases match their own length class (a 1-char alias only matches
583
+ * short form because its token is `-x`).
584
+ */
585
+ function matchesExplicit(opt, name, isLong) {
586
+ if (opt.cliName === name && (isLong || opt.cliName.length === 1)) return true;
587
+ if (opt.alias) {
588
+ for (const a of opt.alias) if (a === name && (isLong || a.length === 1)) return true;
589
+ }
590
+ if (isLong && opt.negation === name) return true;
591
+ if (!isLong || name.length <= 1) return false;
592
+ if (matchesCamelCase(opt.cliName, name)) return true;
593
+ if (opt.alias?.some((a) => matchesCamelCase(a, name))) return true;
594
+ return matchesCamelCase(opt.negation, name);
595
+ }
596
+ /**
597
+ * Find option by name or alias. Tried in two passes so that a real field
598
+ * literally named `noFoo` always wins over `--no-foo` being interpreted as
599
+ * the implicit negation of a sibling `foo` field — the runtime parser
600
+ * resolves the explicit field first as well.
601
+ *
602
+ * Short-form precedence mirrors runtime's `separateGlobalArgs`: when a
603
+ * global owns the `-x` alias and the local does NOT explicitly declare
604
+ * `alias: "x"`, the global wins (a bare local `cliName: "x"` does not
605
+ * register `x` in the local aliasMap). Long form keeps the local-first
606
+ * order via the unshadowed merged list.
607
+ */
608
+ function findOption(options, parsed) {
609
+ if (!parsed.isLong) {
610
+ const localWithExplicitAlias = options.find((opt) => opt.isGlobal !== true && opt.alias?.includes(parsed.name) === true);
611
+ if (localWithExplicitAlias) return localWithExplicitAlias;
612
+ const global = options.find((opt) => opt.isGlobal === true && matchesExplicit(opt, parsed.name, parsed.isLong));
613
+ if (global) return global;
614
+ }
615
+ const explicit = options.find((opt) => matchesExplicit(opt, parsed.name, parsed.isLong));
616
+ if (explicit) return explicit;
617
+ return options.find((opt) => isImplicitBooleanNegation(opt, parsed.name, parsed.isLong));
618
+ }
619
+ /**
620
+ * Parse completion context from command line arguments
621
+ *
622
+ * @param argv - Arguments after the program name (e.g., ["build", "--fo"])
623
+ * @param rootCommand - The root command
624
+ * @param globalArgsSchema - Optional global args. When provided, options
625
+ * derived from this schema are merged into every command level so dynamic
626
+ * resolvers attached to global options can be reached from any subcommand.
627
+ * @returns Completion context
628
+ */
629
+ function parseCompletionContext(argv, rootCommand, globalArgsSchema) {
630
+ let currentCommand = rootCommand;
631
+ const subcommandPath = [];
632
+ const globalOptions = globalArgsSchema ? extractOptionsFromSchema(globalArgsSchema).map((o) => ({
633
+ ...o,
634
+ isGlobal: true
635
+ })) : [];
636
+ const usedOptions = /* @__PURE__ */ new Set();
637
+ let positionalCount = 0;
638
+ let parsedArgs = {};
639
+ let positionalValues = [];
640
+ const globalParsedArgs = {};
641
+ const globalsCapturedByPreSubScan = /* @__PURE__ */ new Set();
642
+ let frameStartIdx = 0;
643
+ let arraysSetInCurrentFrame = /* @__PURE__ */ new Set();
644
+ /**
645
+ * Mark the option's cliName plus every alias and (if present) negation
646
+ * form as consumed. The negation shares the field's "used" slot so
647
+ * typing either form filters both from subsequent suggestions.
648
+ */
649
+ const markUsed = (opt) => {
650
+ usedOptions.add(opt.cliName);
651
+ for (const a of opt.alias ?? []) usedOptions.add(a);
652
+ if (opt.negation) usedOptions.add(opt.negation);
653
+ };
654
+ const recordOptionValue = (opt, value) => {
655
+ writeOptionValue(opt.isGlobal === true ? globalParsedArgs : parsedArgs, opt, value, arraysSetInCurrentFrame);
656
+ };
657
+ /**
658
+ * Record a boolean flag the user typed. The positive form sets `true`;
659
+ * the negation form (`--no-foo` or a custom `negationDisplay`) sets
660
+ * `false`. Dynamic resolvers depend on these values to switch candidates
661
+ * based on flag state, so the absence of a writer here used to hide
662
+ * boolean siblings entirely.
663
+ */
664
+ const recordBooleanFlag = (opt, parsed) => {
665
+ const target = opt.isGlobal === true ? globalParsedArgs : parsedArgs;
666
+ target[opt.name] = !isNegationOf(opt, parsed);
667
+ };
668
+ let i = 0;
669
+ let options = mergeGlobalOptions(extractOptions(currentCommand), globalOptions);
670
+ let afterDoubleDash = false;
671
+ while (i < argv.length - 1) {
672
+ const word = argv[i];
673
+ if (!afterDoubleDash && word === "--") {
674
+ afterDoubleDash = true;
675
+ i++;
676
+ continue;
677
+ }
678
+ if (!afterDoubleDash && word.startsWith("-") && !word.startsWith("--") && word.length > 2 && !word.includes("=")) {
679
+ const chars = Array.from(word.slice(1));
680
+ const localOptions = options.filter((o) => o.isGlobal !== true);
681
+ for (const c of chars) {
682
+ const o = findOption(localOptions, {
683
+ name: c,
684
+ isLong: false
685
+ });
686
+ if (!o || o.takesValue) continue;
687
+ markUsed(o);
688
+ recordBooleanFlag(o, {
689
+ name: c,
690
+ isLong: false
691
+ });
692
+ }
693
+ i++;
694
+ continue;
695
+ }
696
+ if (!afterDoubleDash && isOption(word)) {
697
+ const parsed = parseOption(word);
698
+ const opt = findOption(options, parsed);
699
+ if (opt) {
700
+ markUsed(opt);
701
+ if (opt.takesValue) {
702
+ if (hasInlineValue(word)) {
703
+ const eqIdx = word.indexOf("=");
704
+ recordOptionValue(opt, word.slice(eqIdx + 1));
705
+ } else if (i + 1 < argv.length - 1) {
706
+ const next = argv[i + 1];
707
+ if (!isOption(next)) {
708
+ recordOptionValue(opt, next);
709
+ i++;
710
+ }
711
+ }
712
+ } else recordBooleanFlag(opt, parsed);
713
+ }
714
+ i++;
715
+ continue;
716
+ }
717
+ const subcommand = afterDoubleDash ? null : resolveSubcommand(currentCommand, word);
718
+ if (subcommand) {
719
+ subcommandPath.push(word);
720
+ const parentLocalOptions = extractOptions(currentCommand);
721
+ const preSubSlice = argv.slice(frameStartIdx, i);
722
+ for (const name of parsePreSubGlobals(preSubSlice, globalOptions, globalParsedArgs)) globalsCapturedByPreSubScan.add(name);
723
+ currentCommand = subcommand;
724
+ options = mergeGlobalOptions(extractOptions(currentCommand), globalOptions);
725
+ for (const key of Object.keys(parsedArgs)) {
726
+ const localOpt = parentLocalOptions.find((o) => o.name === key);
727
+ const tokenCollidingGlobal = globalOptions.find((g) => g.name === key) ?? (localOpt ? findGlobalByTokenCollision(globalOptions, localOpt) : void 0);
728
+ if (!tokenCollidingGlobal) continue;
729
+ if (globalsCapturedByPreSubScan.has(tokenCollidingGlobal.name)) continue;
730
+ globalParsedArgs[tokenCollidingGlobal.name] = adaptValueForGlobal(parsedArgs[key], tokenCollidingGlobal);
731
+ }
732
+ usedOptions.clear();
733
+ positionalCount = 0;
734
+ parsedArgs = {};
735
+ positionalValues = [];
736
+ arraysSetInCurrentFrame = /* @__PURE__ */ new Set();
737
+ frameStartIdx = i + 1;
738
+ i++;
739
+ continue;
740
+ }
741
+ positionalValues.push(word);
742
+ positionalCount++;
743
+ i++;
744
+ }
745
+ const currentWord = argv[argv.length - 1] ?? "";
746
+ const previousWord = argv[argv.length - 2] ?? "";
747
+ const positionals = extractPositionalsForContext(currentCommand);
748
+ const subcommands = getSubcommandNames(currentCommand);
749
+ for (let p = 0; p < positionals.length; p++) {
750
+ const pos = positionals[p];
751
+ if (pos.variadic) {
752
+ parsedArgs[pos.name] = positionalValues.slice(p);
753
+ break;
754
+ }
755
+ if (p < positionalValues.length) parsedArgs[pos.name] = positionalValues[p];
756
+ }
757
+ let completionType;
758
+ let targetOption;
759
+ let positionalIndex;
760
+ if (!afterDoubleDash && previousWord && isOption(previousWord) && !hasInlineValue(previousWord)) {
761
+ const opt = findOption(options, parseOption(previousWord));
762
+ if (opt && opt.takesValue) {
763
+ completionType = "option-value";
764
+ targetOption = opt;
765
+ } else if (currentWord.startsWith("-")) completionType = "option-name";
766
+ else {
767
+ completionType = determineDefaultCompletionType(currentWord, subcommands, positionals, positionalCount);
768
+ if (completionType === "positional") positionalIndex = positionalCount;
769
+ }
770
+ } else if (!afterDoubleDash && currentWord.startsWith("-") && hasInlineValue(currentWord)) {
771
+ const opt = findOption(options, parseOption(currentWord));
772
+ if (opt && opt.takesValue) {
773
+ completionType = "option-value";
774
+ targetOption = opt;
775
+ } else completionType = "option-name";
776
+ } else if (!afterDoubleDash && currentWord.startsWith("-")) completionType = "option-name";
777
+ else {
778
+ completionType = determineDefaultCompletionType(currentWord, subcommands, positionals, positionalCount, afterDoubleDash);
779
+ if (completionType === "positional") positionalIndex = positionalCount;
780
+ }
781
+ let previousValues = [];
782
+ if (targetOption) {
783
+ if (targetOption.valueType === "array") {
784
+ const stored = (targetOption.isGlobal === true ? globalParsedArgs : parsedArgs)[targetOption.name];
785
+ previousValues = Array.isArray(stored) ? stored.filter((v) => typeof v === "string") : [];
786
+ }
787
+ } else if (completionType === "positional" && positionalIndex !== void 0) {
788
+ const clampedIdx = clampToVariadic(positionalIndex, positionals);
789
+ if (clampedIdx !== void 0 && positionals[clampedIdx]?.variadic) previousValues = positionalValues.slice(clampedIdx);
790
+ }
791
+ const mergedParsedArgs = {
792
+ ...globalParsedArgs,
793
+ ...parsedArgs
794
+ };
795
+ return {
796
+ subcommandPath,
797
+ currentCommand,
798
+ currentWord,
799
+ previousWord,
800
+ completionType,
801
+ targetOption,
802
+ positionalIndex,
803
+ options,
804
+ subcommands,
805
+ positionals,
806
+ usedOptions,
807
+ providedPositionalCount: positionalCount,
808
+ parsedArgs: mergedParsedArgs,
809
+ previousValues
810
+ };
811
+ }
812
+ /**
813
+ * Determine default completion type when not completing an option
814
+ */
815
+ function determineDefaultCompletionType(currentWord, subcommands, positionals, positionalCount, afterDoubleDash) {
816
+ if (afterDoubleDash) return "positional";
817
+ if (subcommands.length > 0) {
818
+ if (subcommands.filter((s) => s.startsWith(currentWord)).length > 0 || currentWord === "") return "subcommand";
819
+ }
820
+ if (positionalCount < positionals.length) return "positional";
821
+ if (positionals.length > 0 && positionals[positionals.length - 1].variadic) return "positional";
822
+ return "subcommand";
823
+ }
824
+
825
+ //#endregion
826
+ //#region src/completion/dynamic/candidate-generator.ts
827
+ /**
828
+ * Generate completion candidates based on context
829
+ */
830
+ /**
831
+ * Completion directive flags (bitwise)
832
+ */
833
+ const CompletionDirective = {
834
+ /** Default completion behavior */
835
+ Default: 0,
836
+ /** Don't add space after completion */
837
+ NoSpace: 1,
838
+ /** Don't offer file completion (even if no other completions) */
839
+ NoFileCompletion: 2,
840
+ /** Filter completions using current word as prefix */
841
+ FilterPrefix: 4,
842
+ /** Keep the order of completions */
843
+ KeepOrder: 8,
844
+ /** Trigger file completion */
845
+ FileCompletion: 16,
846
+ /** Trigger directory completion */
847
+ DirectoryCompletion: 32,
848
+ /** Error occurred during completion */
849
+ Error: 64
850
+ };
851
+ /**
852
+ * Detect an inline `--opt=` prefix on an option-value `currentWord`.
853
+ * Mirrors what the shell scripts already strip via `_inline_prefix`, so
854
+ * resolvers see only the value portion (e.g. `foo` for `--field=foo`).
855
+ * Positional words are excluded: `cli -- --foo=bar` is a legitimate
856
+ * positional value, not an inline option assignment.
857
+ */
858
+ function detectInlineOptionPrefix(currentWord) {
859
+ if (!currentWord.startsWith("-")) return void 0;
860
+ const eqIdx = currentWord.indexOf("=");
861
+ if (eqIdx <= 0) return void 0;
862
+ return currentWord.slice(0, eqIdx + 1);
863
+ }
864
+ /**
865
+ * Generate completion candidates based on context.
866
+ *
867
+ * Async because dynamic resolvers may return promises. Sync completion
868
+ * sources (choices/file/directory/command/none, subcommand, option name)
869
+ * still resolve synchronously and the await is a no-op for them.
870
+ *
871
+ * Inline option-value prefixes (`--field=foo`) on the option-value path
872
+ * are stripped here so resolvers and post-processing always see the
873
+ * value portion regardless of whether the caller pre-normalized.
874
+ */
875
+ async function generateCandidates(context, options) {
876
+ switch (context.completionType) {
877
+ case "subcommand": return generateSubcommandCandidates(context);
878
+ case "option-name": return generateOptionNameCandidates(context);
879
+ case "option-value": {
880
+ const opt = context.targetOption;
881
+ const inlinePrefix = opt ? detectInlineOptionPrefix(context.currentWord) : void 0;
882
+ return generateValueCandidates(inlinePrefix ? {
883
+ ...context,
884
+ currentWord: context.currentWord.slice(inlinePrefix.length)
885
+ } : context, options, opt?.name, opt?.valueCompletion);
886
+ }
887
+ case "positional": {
888
+ const positional = resolvePositionalTarget(context);
889
+ return generateValueCandidates(context, options, positional?.name, positional?.valueCompletion, positional?.description);
890
+ }
891
+ }
892
+ }
893
+ /**
894
+ * Pick the positional whose `valueCompletion` should drive the current
895
+ * cursor. Clamps to the trailing variadic positional so a value beyond
896
+ * the schema's positional count still resolves to the variadic slot —
897
+ * but only when that slot IS variadic; otherwise a non-variadic last
898
+ * positional must not greedily absorb the extra value.
899
+ */
900
+ function resolvePositionalTarget(context) {
901
+ const requestedIdx = context.positionalIndex ?? 0;
902
+ const clampedIdx = clampToVariadic(requestedIdx, context.positionals);
903
+ if (clampedIdx === void 0) return void 0;
904
+ const candidate = context.positionals[clampedIdx];
905
+ if (!candidate) return void 0;
906
+ return clampedIdx === requestedIdx || candidate.variadic ? candidate : void 0;
907
+ }
908
+ /**
909
+ * Execute a shell command and return results as candidates
910
+ */
911
+ function executeShellCommand(command) {
912
+ try {
913
+ return (0, node_child_process.execSync)(command, {
914
+ encoding: "utf-8",
915
+ timeout: 5e3
916
+ }).split("\n").map((line) => line.trim()).filter((line) => line.length > 0).map((line) => ({
917
+ value: line,
918
+ type: "value"
919
+ }));
920
+ } catch {
921
+ return [];
922
+ }
923
+ }
924
+ /**
925
+ * Two-stage `key=value` post-processing. Returns the transformed candidate
926
+ * list plus whether it contains a bare `key=` entry so the caller can flip
927
+ * NoSpace and let the user keep typing past the first TAB.
928
+ *
929
+ * Key stage (`=` not yet typed): collapse every `key=value` candidate to a
930
+ * unique `key=` entry so the first TAB picks the key.
931
+ *
932
+ * Value stage (`=` typed): drop only the bare `<key>=` candidate that
933
+ * echoes the prefix the user already typed. A blanket `endsWith("=")`
934
+ * filter would also remove legitimate values such as base64 `key=YWJj=` or
935
+ * value-only `YWJj=` (padding), so match the candidate string exactly
936
+ * against the typed key prefix.
937
+ */
938
+ function applyKeyValuePostProcessing(candidates, currentWord) {
939
+ const keyStage = !currentWord.includes("=");
940
+ const processed = keyStage ? collapseToKeys(candidates) : dropBareKeyEcho(candidates, currentWord);
941
+ return {
942
+ candidates: processed,
943
+ hasEqSuffix: keyStage && processed.some((c) => c.value.endsWith("="))
944
+ };
945
+ }
946
+ function collapseToKeys(candidates) {
947
+ const seen = /* @__PURE__ */ new Set();
948
+ const out = [];
949
+ for (const c of candidates) {
950
+ const eqIdx = c.value.indexOf("=");
951
+ if (eqIdx <= 0) {
952
+ out.push(c);
953
+ continue;
954
+ }
955
+ const keyPart = c.value.slice(0, eqIdx + 1);
956
+ if (seen.has(keyPart)) continue;
957
+ seen.add(keyPart);
958
+ out.push({
959
+ ...c,
960
+ value: keyPart
961
+ });
962
+ }
963
+ return out;
964
+ }
965
+ function dropBareKeyEcho(candidates, currentWord) {
966
+ const keyPrefix = currentWord.slice(0, currentWord.indexOf("=") + 1);
967
+ return candidates.filter((c) => c.value !== keyPrefix);
968
+ }
969
+ /**
970
+ * Resolve value completion, executing shell commands and file lookups in JS
971
+ */
972
+ async function resolveValueCandidates(vc, ctx, description) {
973
+ const candidates = [];
974
+ let directive = CompletionDirective.FilterPrefix;
975
+ let fileExtensions;
976
+ let fileMatchers;
977
+ switch (vc.type) {
978
+ case "choices":
979
+ if (vc.choices) for (const choice of vc.choices) candidates.push({
980
+ value: choice,
981
+ description,
982
+ type: "value"
983
+ });
984
+ directive |= CompletionDirective.NoFileCompletion;
985
+ break;
986
+ case "file":
987
+ if (vc.matcher && vc.matcher.length > 0) {
988
+ fileMatchers = vc.matcher.filter((m) => m.trim().length > 0);
989
+ if (fileMatchers.length === 0) {
990
+ fileMatchers = void 0;
991
+ directive |= CompletionDirective.FileCompletion;
992
+ }
993
+ } else if (vc.extensions && vc.extensions.length > 0) {
994
+ fileExtensions = Array.from(new Set(vc.extensions.map((ext) => ext.trim().replace(/^\./, "")).filter((ext) => ext.length > 0)));
995
+ if (fileExtensions.length === 0) {
996
+ fileExtensions = void 0;
997
+ directive |= CompletionDirective.FileCompletion;
998
+ }
999
+ } else directive |= CompletionDirective.FileCompletion;
1000
+ break;
1001
+ case "directory":
1002
+ directive |= CompletionDirective.DirectoryCompletion;
1003
+ break;
1004
+ case "command":
1005
+ if (vc.shellCommand) candidates.push(...executeShellCommand(vc.shellCommand));
1006
+ directive |= CompletionDirective.NoFileCompletion;
1007
+ break;
1008
+ case "none":
1009
+ directive |= CompletionDirective.NoFileCompletion;
1010
+ break;
1011
+ case "dynamic":
1012
+ try {
1013
+ const result = await vc.resolve(ctx);
1014
+ for (const c of result.candidates) {
1015
+ const normalized = typeof c === "string" ? { value: c } : c;
1016
+ candidates.push({
1017
+ ...normalized,
1018
+ type: "value"
1019
+ });
1020
+ }
1021
+ directive = result.directive ?? CompletionDirective.FilterPrefix | CompletionDirective.NoFileCompletion;
1022
+ } catch {
1023
+ directive = CompletionDirective.NoFileCompletion | CompletionDirective.Error;
1024
+ }
1025
+ break;
1026
+ case "expand":
1027
+ directive |= CompletionDirective.NoFileCompletion;
1028
+ break;
1029
+ }
1030
+ if (vc.type === "dynamic" || vc.type === "expand") {
1031
+ const processed = applyKeyValuePostProcessing(candidates, ctx.currentWord);
1032
+ if (processed.hasEqSuffix) directive |= CompletionDirective.NoSpace;
1033
+ return {
1034
+ candidates: processed.candidates,
1035
+ directive,
1036
+ fileExtensions,
1037
+ fileMatchers
1038
+ };
1039
+ }
1040
+ return {
1041
+ candidates,
1042
+ directive,
1043
+ fileExtensions,
1044
+ fileMatchers
1045
+ };
1046
+ }
1047
+ /**
1048
+ * Generate subcommand candidates
1049
+ */
1050
+ function generateSubcommandCandidates(context) {
1051
+ const candidates = [];
1052
+ for (const name of context.subcommands) {
1053
+ const subs = context.currentCommand.subCommands;
1054
+ const direct = subs?.[name];
1055
+ const aliasCanonical = direct ? void 0 : require_schema_extractor.resolveSubCommandAlias(context.currentCommand, name);
1056
+ const resolved = direct ?? (aliasCanonical ? subs?.[aliasCanonical] : void 0);
1057
+ const description = resolved ? require_schema_extractor.resolveSubCommandMeta(resolved)?.description : void 0;
1058
+ candidates.push({
1059
+ value: name,
1060
+ description,
1061
+ type: "subcommand"
1062
+ });
1063
+ }
1064
+ if (candidates.length === 0 || context.currentWord.startsWith("-")) {
1065
+ const optionResult = generateOptionNameCandidates(context);
1066
+ candidates.push(...optionResult.candidates);
1067
+ }
1068
+ return {
1069
+ candidates,
1070
+ directive: CompletionDirective.FilterPrefix
1071
+ };
1072
+ }
1073
+ /**
1074
+ * Generate option name candidates
1075
+ */
1076
+ function generateOptionNameCandidates(context) {
1077
+ const candidates = [];
1078
+ const availableOptions = context.options.filter((opt) => {
1079
+ if (opt.valueType === "array") return true;
1080
+ if (context.usedOptions.has(opt.cliName)) return false;
1081
+ if (opt.alias && opt.alias.some((a) => context.usedOptions.has(a))) return false;
1082
+ if (opt.negation && context.usedOptions.has(opt.negation)) return false;
1083
+ return true;
1084
+ });
1085
+ for (const opt of availableOptions) {
1086
+ candidates.push({
1087
+ value: `--${opt.cliName}`,
1088
+ description: opt.description,
1089
+ type: "option"
1090
+ });
1091
+ if (opt.negation) candidates.push({
1092
+ value: `--${opt.negation}`,
1093
+ description: opt.negationDescription ?? opt.description,
1094
+ type: "option"
1095
+ });
1096
+ }
1097
+ if (!context.usedOptions.has("help")) candidates.push({
1098
+ value: "--help",
1099
+ description: "Show help information",
1100
+ type: "option"
1101
+ });
1102
+ return {
1103
+ candidates,
1104
+ directive: CompletionDirective.FilterPrefix
1105
+ };
1106
+ }
1107
+ /**
1108
+ * Build the resolver-invocation slice of CompletionContext.
1109
+ * `currentWord` reaches resolvers normalized by `generateCandidates` —
1110
+ * the option-value path strips any inline `--field=` prefix first, so
1111
+ * resolvers and the key=value post-processing only ever see the value
1112
+ * portion. The target field is dropped from `parsedArgs` so resolvers
1113
+ * can treat it as "other args": for repeatable options and variadic
1114
+ * positionals the parser already stages already-typed values under the
1115
+ * same key, and exposing them under both `parsedArgs` and `previousValues`
1116
+ * would let a resolver mistake the in-flight field for a fully-supplied
1117
+ * sibling.
1118
+ */
1119
+ function resolverContext(context, options, targetFieldName) {
1120
+ return {
1121
+ currentWord: context.currentWord,
1122
+ shell: options.shell,
1123
+ parsedArgs: parsedArgsWithoutTarget(context.parsedArgs, targetFieldName),
1124
+ previousValues: context.previousValues,
1125
+ subcommandPath: context.subcommandPath
1126
+ };
1127
+ }
1128
+ function parsedArgsWithoutTarget(parsedArgs, key) {
1129
+ if (key === void 0 || !(key in parsedArgs)) return parsedArgs;
1130
+ const next = { ...parsedArgs };
1131
+ delete next[key];
1132
+ return next;
1133
+ }
1134
+ /**
1135
+ * Generate value candidates for either an option or a positional. Both paths
1136
+ * resolve the same way once their target field is identified. `description`
1137
+ * is propagated to choices candidates (positional path supplies it; option
1138
+ * path does not, mirroring the prior split implementations).
1139
+ */
1140
+ async function generateValueCandidates(context, options, targetFieldName, vc, description) {
1141
+ if (!vc) return {
1142
+ candidates: [],
1143
+ directive: CompletionDirective.FilterPrefix
1144
+ };
1145
+ return resolveValueCandidates(vc, resolverContext(context, options, targetFieldName), description);
1146
+ }
1147
+
1148
+ //#endregion
1149
+ //#region src/completion/expand-resolver.ts
1150
+ /**
1151
+ * Resolve every pending `expand` spec on a subcommand. The static extractor
1152
+ * collects pending targets while building options/positionals (it sees the
1153
+ * sentinel via `resolveValueCompletion`) and passes them here once siblings
1154
+ * are known.
1155
+ */
1156
+ function resolveExpandTargets(sub, targets, globalOptions = []) {
1157
+ if (targets.length === 0) return;
1158
+ const siblingIndex = buildSiblingIndex(sub, globalOptions);
1159
+ for (const target of targets) target.set(resolveOne(target, siblingIndex));
1160
+ }
1161
+ /**
1162
+ * Build a name → static-values map for siblings, using each field's already
1163
+ * resolved `valueCompletion`. Only `choices`-typed completions count;
1164
+ * referencing anything else from `dependsOn` is reported as a clean error
1165
+ * in {@link resolveOne}. Global options with static choices are merged in
1166
+ * so a local expand can declare `dependsOn: ["env"]` against a global
1167
+ * \`env\` field — runtime propagates the global value to every frame, so
1168
+ * the resolved table must cover those combinations too.
1169
+ */
1170
+ function buildSiblingIndex(sub, globalOptions) {
1171
+ const index = /* @__PURE__ */ new Map();
1172
+ const claimedByLocal = /* @__PURE__ */ new Set();
1173
+ for (const field of [...sub.options, ...sub.positionals]) claimedByLocal.add(field.name);
1174
+ const visit = (fields, fromGlobal) => {
1175
+ for (const field of fields) {
1176
+ if (index.has(field.name)) continue;
1177
+ if (fromGlobal && claimedByLocal.has(field.name)) continue;
1178
+ const vc = field.valueCompletion;
1179
+ if (vc?.type === "choices" && vc.choices && vc.choices.length > 0) index.set(field.name, vc.choices);
1180
+ }
1181
+ };
1182
+ visit([...sub.options, ...sub.positionals], false);
1183
+ visit(globalOptions, true);
1184
+ return index;
1185
+ }
1186
+ function resolveOne(target, siblings) {
1187
+ const { spec } = target;
1188
+ const deps = spec.dependsOn;
1189
+ if (deps.length === 0) throw new Error(`Field "${target.describe}": completion.custom.expand.dependsOn must list at least one sibling arg.`);
1190
+ const valueLists = [];
1191
+ for (const dep of deps) {
1192
+ if (dep === target.name) throw new Error(`Field "${target.describe}": completion.custom.expand.dependsOn cannot reference the field itself ("${dep}").`);
1193
+ const values = siblings.get(dep);
1194
+ if (!values) throw new Error(`Field "${target.describe}": completion.custom.expand.dependsOn references "${dep}", which is not a sibling arg with a static \`choices\`/enum schema on the same command. Chaining expand specs is not supported.`);
1195
+ valueLists.push([...values]);
1196
+ }
1197
+ const table = [];
1198
+ for (const combo of cartesian(valueLists)) {
1199
+ const depsRecord = {};
1200
+ deps.forEach((name, idx) => {
1201
+ depsRecord[name] = combo[idx];
1202
+ });
1203
+ let raw;
1204
+ try {
1205
+ raw = spec.enumerate(depsRecord);
1206
+ } catch (err) {
1207
+ const cause = err instanceof Error ? err.message : String(err);
1208
+ throw new Error(`Field "${target.describe}": completion.custom.expand.enumerate threw for deps=${JSON.stringify(depsRecord)}: ${cause}`);
1209
+ }
1210
+ const candidates = normaliseCandidates(raw);
1211
+ if (candidates.length === 0) continue;
1212
+ table.push({
1213
+ key: combo,
1214
+ candidates
1215
+ });
1216
+ }
1217
+ return {
1218
+ type: "expand",
1219
+ dependsOn: deps,
1220
+ table
1221
+ };
1222
+ }
1223
+ function normaliseCandidates(raw) {
1224
+ const out = [];
1225
+ const seen = /* @__PURE__ */ new Set();
1226
+ for (const item of raw) {
1227
+ const value = typeof item === "string" ? item : item.value;
1228
+ if (seen.has(value)) continue;
1229
+ seen.add(value);
1230
+ const entry = { value };
1231
+ if (typeof item !== "string" && item.description !== void 0) entry.description = item.description;
1232
+ out.push(entry);
1233
+ }
1234
+ return out;
1235
+ }
1236
+ function* cartesian(lists) {
1237
+ if (lists.length === 0) {
1238
+ yield [];
1239
+ return;
1240
+ }
1241
+ const indices = Array.from({ length: lists.length }).fill(0);
1242
+ while (true) {
1243
+ yield indices.map((i, dim) => lists[dim][i]);
1244
+ let dim = lists.length - 1;
1245
+ while (dim >= 0) {
1246
+ indices[dim]++;
1247
+ if (indices[dim] < lists[dim].length) break;
1248
+ indices[dim] = 0;
1249
+ dim--;
1250
+ }
1251
+ if (dim < 0) return;
1252
+ }
1253
+ }
1254
+
1255
+ //#endregion
1256
+ //#region src/completion/extractor.ts
1257
+ /**
1258
+ * Extract completion data from commands
1259
+ */
1260
+ /**
1261
+ * Resolve and assign value completion to a field. Pending expand sentinels
1262
+ * are stashed in `pending`; the eventual `resolveExpandTargets` pass replaces
1263
+ * the sentinel with a fully-resolved `{ type: "expand", ... }` via `set`.
1264
+ */
1265
+ function assignValueCompletion(field, pending, describe, set) {
1266
+ const raw = resolveValueCompletion(field);
1267
+ if (raw?.type === "pending-expand") {
1268
+ pending.push({
1269
+ name: field.name,
1270
+ describe,
1271
+ set,
1272
+ spec: raw.spec
1273
+ });
1274
+ return;
1275
+ }
1276
+ if (raw !== void 0) set(raw);
1277
+ }
1278
+ /**
1279
+ * Sanitize a name for use as a shell function/variable identifier.
1280
+ * Replaces any character that is not alphanumeric or underscore with underscore.
1281
+ *
1282
+ * Note: This is not injective -- distinct names may produce the same output
1283
+ * (e.g., "foo-bar" and "foo_bar" both become "foo_bar"). When used for nested
1284
+ * path encoding (`path.map(sanitize).join("_")`), cross-level collisions are
1285
+ * theoretically possible (e.g., "foo-bar:baz" vs "foo:bar-baz") but extremely
1286
+ * unlikely in real CLI designs. If collision-safety is needed, sanitize must be
1287
+ * replaced with an injective encoding.
1288
+ */
1289
+ function sanitize(name) {
1290
+ return name.replace(/[^a-zA-Z0-9_]/g, "_");
1291
+ }
1292
+ /**
1293
+ * Build the override env-var name shells inspect to pick a different
1294
+ * binary (`<NAME>_BIN`). Shell parameter names cannot begin with a
1295
+ * digit, so prepend an underscore when the upper-cased function name
1296
+ * starts with one — e.g. `2fa` ⇒ `_2FA_BIN`.
1297
+ */
1298
+ function binEnvVarName(fn) {
1299
+ const upper = fn.toUpperCase();
1300
+ return /^[A-Z_]/.test(upper) ? `${upper}_BIN` : `_${upper}_BIN`;
1301
+ }
1302
+ /**
1303
+ * Hoisted expand-table variable name for a (funcSuffix, fieldName) at frame
1304
+ * scope. Bash uses indirect expansion `${!var}` on per-entry scalars, zsh
1305
+ * uses associative-array subscripts on this same base — the identifier
1306
+ * shape is identical, so both generators share this helper.
1307
+ */
1308
+ function expandTableVarName(fn, funcSuffix, fieldName) {
1309
+ return `__${fn}_expand_${funcSuffix}__${sanitize(fieldName)}`;
1310
+ }
1311
+ /**
1312
+ * Body of the `__<fn>_invoke_complete` wrapper that bash and zsh emit when
1313
+ * any field uses an in-process JS resolver. Bytes are identical between the
1314
+ * two shells — both use `local`, `shift`, and the `<NAME>_BIN`-override
1315
+ * lookup — so the helper lives here. Fish has a different `function`
1316
+ * syntax (no `local`, `set -l` instead) and emits its own version inline.
1317
+ */
1318
+ function dynamicInvokeCompleteLines(fn, programName) {
1319
+ return [
1320
+ `__${fn}_invoke_complete() {`,
1321
+ ` local _shell="$1"; shift`,
1322
+ ` "\${${binEnvVarName(fn)}:-${programName}}" __complete --shell "$_shell" -- "$@" 2>/dev/null`,
1323
+ `}`
1324
+ ];
1325
+ }
1326
+ /**
1327
+ * Filter subcommands to only visible (non-internal) ones.
1328
+ * Internal subcommands start with "__" and are hidden from completion/help.
1329
+ */
1330
+ function getVisibleSubs(subs) {
1331
+ return subs.filter((s) => !s.name.startsWith("__"));
1332
+ }
1333
+ /**
1334
+ * Get all completable subcommand names including aliases.
1335
+ * Returns an array of { name, description } for all visible subcommands
1336
+ * and their aliases.
1337
+ */
1338
+ function getSubNamesWithAliases(subs) {
1339
+ const result = [];
1340
+ for (const sub of getVisibleSubs(subs)) {
1341
+ result.push({
1342
+ name: sub.name,
1343
+ description: sub.description
1344
+ });
1345
+ if (sub.aliases) for (const alias of sub.aliases) result.push({
1346
+ name: alias,
1347
+ description: sub.description
1348
+ });
1349
+ }
1350
+ return result;
1351
+ }
1352
+ /**
1353
+ * Convert a resolved field to a completable option. Pending expand specs
1354
+ * are stashed in `pending` and patched onto the returned object after
1355
+ * sibling choices are known.
1356
+ */
1357
+ function fieldToOption(field, pending) {
1358
+ const defaultNegationAccepted = field.type === "boolean" && (field.negation === void 0 || field.negation === true);
1359
+ const opt = {
1360
+ name: field.name,
1361
+ cliName: field.cliName,
1362
+ alias: field.alias,
1363
+ negation: field.negationDisplay,
1364
+ negationDescription: field.negationDescription,
1365
+ description: field.description,
1366
+ takesValue: field.type !== "boolean",
1367
+ valueType: field.type,
1368
+ required: field.required,
1369
+ defaultNegationAccepted
1370
+ };
1371
+ assignValueCompletion(field, pending, `--${field.cliName}`, (next) => {
1372
+ opt.valueCompletion = next;
1373
+ });
1374
+ return opt;
1375
+ }
1376
+ /**
1377
+ * Extract positional arguments from a command
1378
+ */
1379
+ function extractPositionals(command) {
1380
+ if (!command.args) return [];
1381
+ return require_schema_extractor.extractFields(command.args).fields.filter((field) => field.positional);
1382
+ }
1383
+ /** Convert pre-extracted fields to options. */
1384
+ function fieldsToOptions(fields, pending) {
1385
+ return fields.filter((field) => !field.positional).map((field) => fieldToOption(field, pending));
1386
+ }
1387
+ /** Convert pre-extracted fields to positionals. */
1388
+ function fieldsToPositionals(fields, pending) {
1389
+ return fields.filter((field) => field.positional).map((field, index) => {
1390
+ const pos = {
1391
+ name: field.name,
1392
+ cliName: field.cliName,
1393
+ position: index,
1394
+ description: field.description,
1395
+ required: field.required,
1396
+ variadic: field.type === "array"
1397
+ };
1398
+ assignValueCompletion(field, pending, `<${field.cliName}>`, (next) => {
1399
+ pos.valueCompletion = next;
1400
+ });
1401
+ return pos;
1402
+ });
1403
+ }
1404
+ /**
1405
+ * Extract a completable subcommand from a command
1406
+ */
1407
+ function extractSubcommand(name, command, globalOptions = []) {
1408
+ const subcommands = [];
1409
+ if (command.subCommands) for (const [subName, subCommand] of Object.entries(command.subCommands)) {
1410
+ const resolved = require_schema_extractor.resolveSubCommandMeta(subCommand);
1411
+ if (resolved) subcommands.push(extractSubcommand(subName, resolved, globalOptions));
1412
+ else subcommands.push({
1413
+ name: subName,
1414
+ description: "(lazy loaded)",
1415
+ subcommands: [],
1416
+ options: [],
1417
+ positionals: []
1418
+ });
1419
+ }
1420
+ const pending = [];
1421
+ const fields = command.args ? require_schema_extractor.extractFields(command.args).fields : [];
1422
+ const node = {
1423
+ name,
1424
+ description: command.description,
1425
+ aliases: command.aliases,
1426
+ subcommands,
1427
+ options: fieldsToOptions(fields, pending),
1428
+ positionals: fieldsToPositionals(fields, pending)
1429
+ };
1430
+ resolveExpandTargets(node, pending, globalOptions);
1431
+ return node;
1432
+ }
1433
+ /** Join parent and child with a separator, omitting separator when parent is empty. */
1434
+ function joinPrefix(parent, child, sep) {
1435
+ return parent ? `${parent}${sep}${child}` : child;
1436
+ }
1437
+ /**
1438
+ * Expand each parent pathStr by joining every child name (canonical plus
1439
+ * aliases) with `:`. Used to keep alias-expanded path variants in lockstep
1440
+ * across walkers that need to reach the same node from any path the
1441
+ * runtime scanner can produce.
1442
+ */
1443
+ function expandChildPathStrs(pathStrs, child) {
1444
+ const childNames = [child.name, ...child.aliases ?? []];
1445
+ return pathStrs.flatMap((p) => childNames.map((n) => joinPrefix(p, n, ":")));
1446
+ }
1447
+ /**
1448
+ * Walk the subcommand tree and yield a row per value-taking option, with
1449
+ * the path-aware token set the runtime would actually route here. Used by
1450
+ * all three shell generators — bash/zsh format these as `|`-joined case
1451
+ * patterns, fish wraps each pattern in a quoted glob.
1452
+ *
1453
+ * At ANCESTOR frames (those with further subcommand children) the runtime's
1454
+ * `scanForSubcommand` consults globals only — local-precedence does NOT
1455
+ * apply, so a global value option keeps every alias even when a local at
1456
+ * the frame claims the same short token. At LEAF frames, the leaf parser's
1457
+ * `separateGlobalArgs` applies local-precedence so `effectiveOptionTokens`
1458
+ * is the correct filter.
1459
+ */
1460
+ function walkOptTakesValueRows(sub, parentPath) {
1461
+ const rows = [];
1462
+ const isAncestor = getVisibleSubs(sub.subcommands).length > 0;
1463
+ for (const opt of sub.options) {
1464
+ if (!opt.takesValue) continue;
1465
+ const tokens = isAncestor && opt.isGlobal === true ? collectOptionTokens(opt.cliName, opt.alias) : effectiveOptionTokens(opt, sub.options);
1466
+ if (tokens.length === 0) continue;
1467
+ rows.push({
1468
+ parentPath,
1469
+ tokens
1470
+ });
1471
+ }
1472
+ for (const child of getVisibleSubs(sub.subcommands)) for (const name of [child.name, ...child.aliases ?? []]) rows.push(...walkOptTakesValueRows(child, joinPrefix(parentPath, name, ":")));
1473
+ return rows;
1474
+ }
1475
+ /**
1476
+ * Collect opt-takes-value case entries for a subcommand tree.
1477
+ * Used by bash and zsh generators (identical case syntax: `path:--opt) return 0 ;;`).
1478
+ * parentPath is a colon-delimited path (e.g., "" for root, "workspace:user" for nested).
1479
+ */
1480
+ function optTakesValueEntries(sub, parentPath) {
1481
+ return walkOptTakesValueRows(sub, parentPath).map((row) => {
1482
+ return ` ${row.tokens.map((t) => `${row.parentPath}:${t}`).join("|")}) return 0 ;;`;
1483
+ });
1484
+ }
1485
+ /**
1486
+ * Recursively collect all subcommand route entries.
1487
+ * Returns entries used by all shell generators for both dispatch routing
1488
+ * and subcommand lookup (is_subcmd) tables.
1489
+ * Aliases are mapped to the same handler as the canonical name.
1490
+ */
1491
+ function collectRouteEntries(sub, parentPath = "", parentFunc = "") {
1492
+ const entries = [];
1493
+ for (const child of getVisibleSubs(sub.subcommands)) {
1494
+ const funcSuffix = joinPrefix(parentFunc, sanitize(child.name), "_");
1495
+ for (const name of [child.name, ...child.aliases ?? []]) {
1496
+ const pathStr = joinPrefix(parentPath, name, ":");
1497
+ entries.push(...collectRouteEntries(child, pathStr, funcSuffix));
1498
+ entries.push({
1499
+ pathStr,
1500
+ funcSuffix,
1501
+ lookupPattern: `${parentPath}:${name}`
1502
+ });
1503
+ }
1504
+ }
1505
+ return entries;
1506
+ }
1507
+ /**
1508
+ * Generate is_subcmd case/switch body lines (bash/zsh case syntax).
1509
+ * Returns lines for the case statement body only (caller wraps in function).
1510
+ */
1511
+ function isSubcmdCaseLines(routeEntries) {
1512
+ return routeEntries.map((r) => ` ${r.lookupPattern}) return 0 ;;`);
1513
+ }
1514
+ /**
1515
+ * Subcommand-dispatch case body lines for bash/zsh: each route forwards
1516
+ * `$_subcmd` to its handler function. Identical emission between shells.
1517
+ */
1518
+ function subDispatchCaseLines(routeEntries, fn) {
1519
+ return routeEntries.map((r) => ` ${r.pathStr}) __${fn}_complete_${r.funcSuffix} ;;`);
1520
+ }
1521
+ /**
1522
+ * Per-shell `_arg_values` write expression. zsh uses an associative-array
1523
+ * subscript; bash uses prefix-scalar variables so the generated script
1524
+ * runs on bash 3.2 (macOS default `/bin/bash`), which lacks associative
1525
+ * arrays. The `isGlobal` flag picks the bucket (`_global_arg_values_*`
1526
+ * survives subcommand descent; `_arg_values_*` does not).
1527
+ */
1528
+ function trackedFieldAssign(t, shell) {
1529
+ const prefix = t.isGlobal ? `_global_arg_values` : `_arg_values`;
1530
+ return shell === "bash" ? `${prefix}_${sanitize(t.fieldName)}="$3"` : `${prefix}[${t.fieldName}]="$3"`;
1531
+ }
1532
+ /**
1533
+ * Case-statement body lines for `__track_opt` — capture option values into
1534
+ * the per-frame state. See {@link trackedFieldAssign} for the per-shell
1535
+ * assignment shape.
1536
+ */
1537
+ function trackOptCaseLines(trackedFields, shell) {
1538
+ const lines = [];
1539
+ for (const t of trackedFields) {
1540
+ if (t.isPositional || !t.optionTokens || t.optionTokens.length === 0) continue;
1541
+ const joined = t.pathStrs.flatMap((p) => t.optionTokens.map((n) => `${p}:${n}`)).join("|");
1542
+ lines.push(` ${joined}) ${trackedFieldAssign(t, shell)} ;;`);
1543
+ }
1544
+ return lines;
1545
+ }
1546
+ /**
1547
+ * Case-statement body lines for `__track_pos` — capture positional values
1548
+ * by `(subcmd, positional-index)`. See {@link trackedFieldAssign} for the
1549
+ * per-shell assignment shape.
1550
+ */
1551
+ function trackPosCaseLines(trackedFields, shell) {
1552
+ const lines = [];
1553
+ for (const t of trackedFields) {
1554
+ if (!t.isPositional) continue;
1555
+ const joined = t.pathStrs.map((p) => `${p}:${t.position}`).join("|");
1556
+ lines.push(` ${joined}) ${trackedFieldAssign(t, shell)} ;;`);
1557
+ }
1558
+ return lines;
1559
+ }
1560
+ /**
1561
+ * Case-statement body lines for `__track_array_expand` — record each `key=`
1562
+ * slot the user has typed so the candidate loop can skip already-consumed
1563
+ * entries. The first write to a global array in a frame replaces the
1564
+ * inherited bucket (mirroring the runtime's per-frame array merge);
1565
+ * subsequent writes append. zsh uses associative arrays; bash uses
1566
+ * prefix-scalar variables (see {@link trackOptCaseLines}).
1567
+ */
1568
+ function trackArrayExpandCaseLines(arrayExpandSpecs, shell) {
1569
+ const lines = [];
1570
+ for (const spec of arrayExpandSpecs) {
1571
+ if (spec.optionTokens.length === 0) continue;
1572
+ const joined = spec.pathStrs.flatMap((p) => spec.optionTokens.map((tok) => `${p}:${tok}`)).join("|");
1573
+ const bucket = sanitize(spec.fieldName);
1574
+ const bucketPrefix = spec.isGlobal ? `_global_used_field_keys` : `_used_field_keys`;
1575
+ const bucketRef = shell === "bash" ? `${bucketPrefix}_${bucket}` : `${bucketPrefix}[${bucket}]`;
1576
+ const seenRef = shell === "bash" ? `_global_arr_seen_${bucket}` : `_global_arr_seen[${bucket}]`;
1577
+ const assignFirst = `${bucketRef}=" $_k "`;
1578
+ const assignAppend = `${bucketRef}+=" $_k "`;
1579
+ const seenSet = `${seenRef}=1`;
1580
+ lines.push(` ${joined})`);
1581
+ lines.push(` if [[ "$3" == *=* ]]; then`);
1582
+ lines.push(` local _k="\${3%%=*}"`);
1583
+ if (spec.isGlobal) {
1584
+ lines.push(` if [[ -n "$_k" ]]; then`);
1585
+ lines.push(` if [[ -z "\${${seenRef}:-}" ]]; then`);
1586
+ lines.push(` ${assignFirst}`);
1587
+ lines.push(` ${seenSet}`);
1588
+ lines.push(` else`);
1589
+ lines.push(` ${assignAppend}`);
1590
+ lines.push(` fi`);
1591
+ lines.push(` fi`);
1592
+ } else lines.push(` [[ -n "$_k" ]] && ${assignAppend}`);
1593
+ lines.push(` fi`);
1594
+ lines.push(` ;;`);
1595
+ }
1596
+ return lines;
1597
+ }
1598
+ /**
1599
+ * Compute the option token set the runtime would actually route to
1600
+ * `opt` at the given frame. Globals shadow LOCAL short tokens of the
1601
+ * same letter (runtime's `separateGlobalArgs` harvests `-x` for the
1602
+ * global unless the local explicitly declares `alias: "x"`), so a
1603
+ * local cliName `x` with no alias must NOT emit `-x` in its
1604
+ * tracker / value-completion / takes-value cases when a global at the
1605
+ * frame owns that token. Long forms are unaffected — precedence is
1606
+ * scoped to short aliases.
1607
+ */
1608
+ function effectiveOptionTokens(opt, frameOptions) {
1609
+ const all = collectOptionTokens(opt.cliName, opt.alias);
1610
+ if (opt.isGlobal === true) {
1611
+ const localClaimed = /* @__PURE__ */ new Set();
1612
+ for (const o of frameOptions) {
1613
+ if (o.isGlobal === true) continue;
1614
+ for (const t of localShadowingTokens(o.cliName, o.alias)) localClaimed.add(t);
1615
+ }
1616
+ return all.filter((t) => !localClaimed.has(t));
1617
+ }
1618
+ const globalShort = globalShortTokens(frameOptions);
1619
+ if (globalShort.size === 0) return all;
1620
+ return all.filter((t) => {
1621
+ if (!t.startsWith("-") || t.startsWith("--")) return true;
1622
+ if (!globalShort.has(t)) return true;
1623
+ return opt.alias?.includes(t.slice(1)) === true;
1624
+ });
1625
+ }
1626
+ /**
1627
+ * Walk the subcommand tree and return every resolved expand spec along
1628
+ * with where it lives. The order is deterministic (DFS, root → leaves;
1629
+ * options before positionals within a node).
1630
+ */
1631
+ function collectExpandSpecs(root) {
1632
+ const out = [];
1633
+ walk(root, [], [""], [], "root", out);
1634
+ return out;
1635
+ }
1636
+ function walk(node, path, pathStrs, intermediatePathStrs, funcSuffix, out) {
1637
+ const pathStr = pathStrs[0];
1638
+ for (const opt of node.options) {
1639
+ const vc = opt.valueCompletion;
1640
+ if (vc?.type === "expand") {
1641
+ const isArrayOption = opt.valueType === "array";
1642
+ out.push({
1643
+ path,
1644
+ pathStr,
1645
+ pathStrs,
1646
+ intermediatePathStrs,
1647
+ funcSuffix,
1648
+ fieldName: opt.name,
1649
+ isGlobal: opt.isGlobal === true,
1650
+ isPositional: false,
1651
+ isArrayOption,
1652
+ optionTokens: isArrayOption ? effectiveOptionTokens(opt, node.options) : [],
1653
+ vc
1654
+ });
1655
+ }
1656
+ }
1657
+ for (const pos of node.positionals) {
1658
+ const vc = pos.valueCompletion;
1659
+ if (vc?.type === "expand") out.push({
1660
+ path,
1661
+ pathStr,
1662
+ pathStrs,
1663
+ intermediatePathStrs,
1664
+ funcSuffix,
1665
+ fieldName: pos.name,
1666
+ isGlobal: false,
1667
+ isPositional: true,
1668
+ isArrayOption: false,
1669
+ optionTokens: [],
1670
+ vc
1671
+ });
1672
+ }
1673
+ for (const child of getVisibleSubs(node.subcommands)) walk(child, [...path, child.name], expandChildPathStrs(pathStrs, child), [...intermediatePathStrs, ...pathStrs], funcSuffix === "root" ? sanitize(child.name) : `${funcSuffix}_${sanitize(child.name)}`, out);
1674
+ }
1675
+ /**
1676
+ * For every expand spec, find each `dependsOn` sibling field at the same
1677
+ * path and return enough metadata for the shell generator to emit tracker
1678
+ * cases. Fields that cannot be resolved are silently skipped — the static
1679
+ * extractor already validated `dependsOn` upstream in
1680
+ * `resolveExpandTargets`, so unresolved siblings here would indicate a
1681
+ * programming error and would simply yield no tracker entries.
1682
+ */
1683
+ function collectTrackedFields(root, specs, globalOptions = []) {
1684
+ const nodeByPath = indexNodesByPath(root);
1685
+ const buckets = /* @__PURE__ */ new Map();
1686
+ const addPath = (key, ref, paths) => {
1687
+ let bucket = buckets.get(key);
1688
+ if (!bucket) {
1689
+ bucket = {
1690
+ ref,
1691
+ pathStrs: [],
1692
+ seen: /* @__PURE__ */ new Set()
1693
+ };
1694
+ buckets.set(key, bucket);
1695
+ }
1696
+ for (const p of paths) {
1697
+ if (bucket.seen.has(p)) continue;
1698
+ bucket.seen.add(p);
1699
+ bucket.pathStrs.push(p);
1700
+ }
1701
+ };
1702
+ /**
1703
+ * Group spec frames by the per-leaf surviving-token set for a global option.
1704
+ * The runtime scanner at a LEAF frame drops global tokens that a local
1705
+ * option already claims (via `localShadowingTokens`); at ANCESTOR frames it
1706
+ * sees only globals so every token survives. Grouping by token-set keeps the
1707
+ * generated tracker case body minimal — one branch per unique frame group.
1708
+ */
1709
+ const groupGlobalFramesByTokenSet = (optTokens, leafPaths, ancestorPaths) => {
1710
+ const groups = /* @__PURE__ */ new Map();
1711
+ const recordLeaf = (path, tokens) => {
1712
+ if (tokens.length === 0) return;
1713
+ const tokenKey = tokens.join(" ");
1714
+ let group = groups.get(tokenKey);
1715
+ if (!group) {
1716
+ group = {
1717
+ tokens,
1718
+ paths: []
1719
+ };
1720
+ groups.set(tokenKey, group);
1721
+ }
1722
+ group.paths.push(path);
1723
+ };
1724
+ for (const p of leafPaths) {
1725
+ const n = nodeByPath.get(p);
1726
+ if (!n) continue;
1727
+ const claimed = /* @__PURE__ */ new Set();
1728
+ for (const o of n.options) {
1729
+ if (o.isGlobal === true) continue;
1730
+ for (const t of localShadowingTokens(o.cliName, o.alias)) claimed.add(t);
1731
+ }
1732
+ recordLeaf(p, optTokens.filter((t) => !claimed.has(t)));
1733
+ }
1734
+ for (const p of ancestorPaths) recordLeaf(p, optTokens);
1735
+ return groups;
1736
+ };
1737
+ const addGlobalDepTracker = (dep, opt, spec) => {
1738
+ const groups = groupGlobalFramesByTokenSet(collectOptionTokens(opt.cliName, opt.alias), spec.pathStrs, spec.intermediatePathStrs);
1739
+ for (const [tokenKey, group] of groups) addPath(`g::${dep}::${tokenKey}`, {
1740
+ fieldName: dep,
1741
+ isGlobal: true,
1742
+ isPositional: false,
1743
+ optionTokens: group.tokens
1744
+ }, group.paths);
1745
+ };
1746
+ for (const spec of specs) {
1747
+ const node = nodeByPath.get(spec.pathStr);
1748
+ if (!node) continue;
1749
+ for (const dep of spec.vc.dependsOn) {
1750
+ if (spec.isGlobal) {
1751
+ const globalOpt = globalOptions.find((o) => o.name === dep);
1752
+ if (!globalOpt) continue;
1753
+ addGlobalDepTracker(dep, globalOpt, spec);
1754
+ continue;
1755
+ }
1756
+ const posIndex = node.positionals.findIndex((p) => p.name === dep);
1757
+ if (posIndex >= 0) {
1758
+ addPath(`lp::${spec.pathStr}::${dep}`, {
1759
+ fieldName: dep,
1760
+ isGlobal: false,
1761
+ isPositional: true,
1762
+ position: posIndex
1763
+ }, spec.pathStrs);
1764
+ continue;
1765
+ }
1766
+ const opt = node.options.find((o) => o.name === dep);
1767
+ if (!opt) continue;
1768
+ if (opt.isGlobal === true) {
1769
+ addGlobalDepTracker(dep, opt, spec);
1770
+ continue;
1771
+ }
1772
+ addPath(`lo::${spec.pathStr}::${dep}`, {
1773
+ fieldName: dep,
1774
+ isGlobal: false,
1775
+ isPositional: false,
1776
+ optionTokens: effectiveOptionTokens(opt, node.options)
1777
+ }, spec.pathStrs);
1778
+ }
1779
+ }
1780
+ const out = [];
1781
+ for (const bucket of buckets.values()) {
1782
+ if (bucket.pathStrs.length === 0) continue;
1783
+ out.push({
1784
+ ...bucket.ref,
1785
+ pathStr: bucket.pathStrs[0],
1786
+ pathStrs: bucket.pathStrs
1787
+ });
1788
+ }
1789
+ return out;
1790
+ }
1791
+ function indexNodesByPath(root) {
1792
+ const map = /* @__PURE__ */ new Map();
1793
+ const recurse = (node, pathStrs) => {
1794
+ for (const p of pathStrs) map.set(p, node);
1795
+ for (const child of getVisibleSubs(node.subcommands)) recurse(child, expandChildPathStrs(pathStrs, child));
1796
+ };
1797
+ recurse(root, [""]);
1798
+ return map;
1799
+ }
1800
+ /**
1801
+ * Walk a CompletableSubcommand tree and return true when any option or
1802
+ * positional uses an in-process dynamic resolver. Used by shell generators
1803
+ * to decide whether to emit `__<fn>_invoke_complete` delegate helpers.
1804
+ */
1805
+ function hasDynamicCompletion(sub) {
1806
+ for (const opt of sub.options) if (opt.valueCompletion?.type === "dynamic") return true;
1807
+ for (const pos of sub.positionals) if (pos.valueCompletion?.type === "dynamic") return true;
1808
+ for (const child of sub.subcommands) if (hasDynamicCompletion(child)) return true;
1809
+ return false;
1810
+ }
1811
+ /**
1812
+ * Recursively merge global options into a subcommand and all its descendants.
1813
+ * Avoids duplicates by checking existing option names.
1814
+ */
1815
+ function propagateGlobalOptions(sub, globalOptions) {
1816
+ const existingNames = new Set(sub.options.map((o) => o.name));
1817
+ const newOpts = globalOptions.filter((o) => !existingNames.has(o.name));
1818
+ sub.options = [...sub.options, ...newOpts];
1819
+ for (const child of sub.subcommands) propagateGlobalOptions(child, globalOptions);
1820
+ }
1821
+ /**
1822
+ * Extract completion data from a command tree
1823
+ *
1824
+ * @param command - The root command
1825
+ * @param programName - Program name for completion scripts
1826
+ * @param globalArgsSchema - Optional global args schema. When provided, global options
1827
+ * are derived from this schema instead of the root command's options.
1828
+ */
1829
+ function extractCompletionData(command, programName, globalArgsSchema) {
1830
+ let globalOptions = [];
1831
+ if (globalArgsSchema) {
1832
+ const globalPending = [];
1833
+ globalOptions = fieldsToOptions(require_schema_extractor.extractFields(globalArgsSchema).fields, globalPending).map((opt) => {
1834
+ opt.isGlobal = true;
1835
+ return opt;
1836
+ });
1837
+ resolveExpandTargets({
1838
+ name: programName,
1839
+ subcommands: [],
1840
+ options: globalOptions,
1841
+ positionals: []
1842
+ }, globalPending);
1843
+ }
1844
+ const rootSubcommand = extractSubcommand(programName, command, globalOptions);
1845
+ if (globalArgsSchema) propagateGlobalOptions(rootSubcommand, globalOptions);
1846
+ else globalOptions = rootSubcommand.options;
1847
+ return {
1848
+ command: rootSubcommand,
1849
+ programName,
1850
+ globalOptions
1851
+ };
1852
+ }
1853
+
1854
+ //#endregion
1855
+ //#region src/completion/header.ts
1856
+ /**
1857
+ * Static-script header utilities.
1858
+ *
1859
+ * Every completion script generated by politty starts with a small
1860
+ * machine-readable header. The rc loader and the runMain background
1861
+ * refresh path use the `# politty-bin-sig:` line to detect when the
1862
+ * cached script is stale relative to the binary on disk.
1863
+ */
1864
+ /** Schema version of the header itself. Bump when the header layout changes. */
1865
+ const COMPLETION_VERSION = 1;
1866
+ /**
1867
+ * Read the binary's mtime in whole seconds (matches POSIX `stat -c %Y` /
1868
+ * BSD `stat -f %m`). Returns `"0"` on failure so the header is always
1869
+ * well-formed.
1870
+ */
1871
+ function computeBinSig(binPath) {
1872
+ try {
1873
+ return Math.floor((0, node_fs.statSync)(binPath).mtimeMs / 1e3).toString();
1874
+ } catch {
1875
+ return "0";
1876
+ }
1877
+ }
1878
+ /**
1879
+ * Walk `$PATH` looking for an executable named `programName`. Returns
1880
+ * the first match's full path, or `null` when not found. We mirror the
1881
+ * shell's `command -v <prog>` here so the sig embedded in the header
1882
+ * (computed by Node) lines up with what the rc loader stat-checks at
1883
+ * runtime — including pnpm/npm bin shims that wrap the real entrypoint.
1884
+ * Without this alignment, shimmed installs would never match the
1885
+ * embedded sig and the cache would regenerate on every shell startup.
1886
+ */
1887
+ function findOnPath(programName) {
1888
+ if (!programName || /[/\\\0]/.test(programName)) return null;
1889
+ const path = process.env.PATH ?? "";
1890
+ for (const dir of path.split(":")) {
1891
+ if (!dir) continue;
1892
+ const candidate = (0, node_path.join)(dir, programName);
1893
+ try {
1894
+ if ((0, node_fs.statSync)(candidate).isFile()) return candidate;
1895
+ } catch {}
1896
+ }
1897
+ return null;
1898
+ }
1899
+ /**
1900
+ * Resolve the binary path used for sig computation and stat checks.
1901
+ *
1902
+ * Order: explicit override → `$PATH` lookup of `programName` → `process.argv[1]`.
1903
+ * The `$PATH` lookup keeps Node-side and shell-side stats pointed at the
1904
+ * same shim file when the CLI is invoked through a package-manager bin shim.
1905
+ */
1906
+ function resolveBinPath(programName, override) {
1907
+ if (override) return override;
1908
+ return findOnPath(programName) ?? process.argv[1] ?? "";
1909
+ }
1910
+ /**
1911
+ * Build the header lines (no trailing blank line). Returned without a
1912
+ * leading `#!` so each generator can prepend its own shebang/compdef
1913
+ * marker.
1914
+ */
1915
+ function buildHeaderLines(opts) {
1916
+ const sig = computeBinSig(resolveBinPath(opts.programName, opts.binPath));
1917
+ const lines = [
1918
+ `# politty-completion-version: ${1}`,
1919
+ `# politty-bin-sig: ${sig}`,
1920
+ `# program: ${opts.programName}`
1921
+ ];
1922
+ if (opts.programVersion) lines.push(`# program-version: ${opts.programVersion}`);
1923
+ lines.push(`# shell: ${opts.shell}`);
1924
+ return lines;
1925
+ }
1926
+
1927
+ //#endregion
1928
+ //#region src/completion/self-refresh.ts
1929
+ /**
1930
+ * Self-refresh guards embedded in generated bash/zsh scripts.
1931
+ *
1932
+ * These guards make the default `completion <shell>` output safe to
1933
+ * save as a static completion file: when the CLI binary changes, the
1934
+ * script asks the hidden refresh subcommand to rewrite the sourced
1935
+ * file in place, then sources the fresh file and stops executing the
1936
+ * stale body.
1937
+ */
1938
+ function statSigExpr() {
1939
+ return `$(stat -L -c '%Y' "$_bin" 2>/dev/null || stat -L -f '%m' "$_bin" 2>/dev/null)`;
1940
+ }
1941
+ function generateBashSelfRefresh(opts) {
1942
+ const { programName, binPath } = opts;
1943
+ const fn = sanitize(programName);
1944
+ const sig = computeBinSig(resolveBinPath(programName, binPath));
1945
+ const refreshFn = `__${fn}_self_refresh`;
1946
+ return [
1947
+ `${refreshFn}() {`,
1948
+ ` local _self _bin _sig`,
1949
+ ` _self=\${BASH_SOURCE[0]:-}`,
1950
+ ` [[ -n "$_self" && -f "$_self" ]] || return 1`,
1951
+ ` head -n 8 "$_self" 2>/dev/null | grep -qF "# politty-completion-version:" || return 1`,
1952
+ ` head -n 8 "$_self" 2>/dev/null | grep -qF "# program: ${programName}" || return 1`,
1953
+ ` head -n 8 "$_self" 2>/dev/null | grep -qF "# shell: bash" || return 1`,
1954
+ ` _bin=$(type -P ${programName} 2>/dev/null)`,
1955
+ ` [[ -n "$_bin" ]] || return 1`,
1956
+ ` _sig=${statSigExpr()} || return 1`,
1957
+ ` [[ "$_sig" != "${sig}" ]] || return 1`,
1958
+ ` "$_bin" __refresh-completion bash "$_self" 2>/dev/null || return 1`,
1959
+ ` head -n 8 "$_self" 2>/dev/null | grep -qF "# politty-bin-sig: $_sig" || return 1`,
1960
+ ` source "$_self" 2>/dev/null || return 1`,
1961
+ ` return 0`,
1962
+ `}`,
1963
+ `if ${refreshFn}; then`,
1964
+ ` unset -f ${refreshFn}`,
1965
+ ` return 0 2>/dev/null || true`,
1966
+ `else`,
1967
+ ` unset -f ${refreshFn}`,
1968
+ `fi`,
1969
+ ``
1970
+ ];
1971
+ }
1972
+ function generateZshSelfRefresh(opts) {
1973
+ const { programName, binPath } = opts;
1974
+ const fn = sanitize(programName);
1975
+ const completionFn = `_${programName}`;
1976
+ const sig = computeBinSig(resolveBinPath(programName, binPath));
1977
+ const refreshFn = `__${fn}_self_refresh`;
1978
+ return [
1979
+ `${refreshFn}() {`,
1980
+ ` emulate -L zsh`,
1981
+ ` setopt local_options no_aliases`,
1982
+ ` local _self _bin _sig`,
1983
+ ` _self="\${(%):-%x}"`,
1984
+ ` [[ -n "$_self" && -f "$_self" ]] || return 1`,
1985
+ ` head -n 8 "$_self" 2>/dev/null | grep -qF "# politty-completion-version:" || return 1`,
1986
+ ` head -n 8 "$_self" 2>/dev/null | grep -qF "# program: ${programName}" || return 1`,
1987
+ ` head -n 8 "$_self" 2>/dev/null | grep -qF "# shell: zsh" || return 1`,
1988
+ ` _bin=$(whence -p ${programName} 2>/dev/null)`,
1989
+ ` [[ -n "$_bin" ]] || return 1`,
1990
+ ` _sig=${statSigExpr()} || return 1`,
1991
+ ` [[ "$_sig" != "${sig}" ]] || return 1`,
1992
+ ` "$_bin" __refresh-completion zsh "$_self" 2>/dev/null || return 1`,
1993
+ ` head -n 8 "$_self" 2>/dev/null | grep -qF "# politty-bin-sig: $_sig" || return 1`,
1994
+ ` source "$_self" 2>/dev/null || return 1`,
1995
+ ` ${completionFn} "$@"`,
1996
+ ` return 0`,
1997
+ `}`,
1998
+ `if ${refreshFn} "$@"; then`,
1999
+ ` unfunction ${refreshFn} 2>/dev/null`,
2000
+ ` return 0 2>/dev/null || true`,
2001
+ `else`,
2002
+ ` unfunction ${refreshFn} 2>/dev/null`,
2003
+ `fi`,
2004
+ ``
2005
+ ];
2006
+ }
2007
+
2008
+ //#endregion
2009
+ //#region src/completion/bash.ts
2010
+ /** Escape a string for use inside bash double-quotes */
2011
+ function escapeBashDQ(s) {
2012
+ return s.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\$/g, "\\$").replace(/`/g, "\\`");
2013
+ }
2014
+ /**
2015
+ * Hex-encode the UTF-8 byte representation of `s` so the resulting
2016
+ * string is safe as a suffix of a bash identifier. Each non-alnum byte
2017
+ * becomes `_HH` (exactly 2 hex digits, always upper-case). `_` is also
2018
+ * encoded (as `_5F`) to keep the join separator between encoded dep
2019
+ * values unambiguous — without that, `(v1="-", v2="")` and
2020
+ * `(v1="_2D", v2="")` would both render `_2D_`.
2021
+ *
2022
+ * Per-byte fixed-width encoding avoids the variable-length codepoint
2023
+ * collision where `-A` (codepoint 0x2D + literal `A`) and `˚` (codepoint
2024
+ * 0x02DA) would both produce `_2DA` under the previous scheme. Mirrors
2025
+ * the runtime `__<fn>_enc` helper emitted alongside expand tables; the
2026
+ * helper forces `LC_ALL=C` so its `${var:i:1}` iterates over the same
2027
+ * UTF-8 bytes this encoder emits.
2028
+ */
2029
+ function bashEncodeKey(s) {
2030
+ let out = "";
2031
+ const bytes = new TextEncoder().encode(s);
2032
+ for (const byte of bytes) if (byte >= 48 && byte <= 57 || byte >= 65 && byte <= 90 || byte >= 97 && byte <= 122) out += String.fromCharCode(byte);
2033
+ else out += `_${byte.toString(16).toUpperCase().padStart(2, "0")}`;
2034
+ return out;
2035
+ }
2036
+ /**
2037
+ * Generate bash value completion code for a ValueCompletion spec.
2038
+ * `location` is required when `vc.type === "expand"` (otherwise unused).
2039
+ */
2040
+ function bashValueLines(vc, inline, fn, location) {
2041
+ if (!vc) return [];
2042
+ switch (vc.type) {
2043
+ case "expand": {
2044
+ if (!location) throw new Error("bashValueLines: expand variant requires a location");
2045
+ const varName = expandTableVarName(fn, location.funcSuffix, location.fieldName);
2046
+ const encLines = [`local _enc_key='' _enc_v`];
2047
+ location.resolvedDeps.forEach((d, i) => {
2048
+ const safe = sanitize(d.name);
2049
+ const varRef = d.isGlobal ? `_global_arg_values_${safe}` : `_arg_values_${safe}`;
2050
+ encLines.push(`_enc_v="\${${varRef}:-}"`);
2051
+ encLines.push(i === 0 ? `_enc_key="$(__${fn}_enc "$_enc_v")"` : `_enc_key+="_$(__${fn}_enc "$_enc_v")"`);
2052
+ });
2053
+ const inlineExpr = inline ? `"\${_inline_prefix}\${_c}"` : `"$_c"`;
2054
+ const bucketRef = location.isGlobal ? `\${_global_used_field_keys_${sanitize(location.fieldName)}:-}` : `\${_used_field_keys_${sanitize(location.fieldName)}:-}`;
2055
+ const arrayDedupLines = location.isArrayOption ? [` if [[ -n "$_ck" && " ${bucketRef} " == *" $_ck "* ]]; then continue; fi`] : [];
2056
+ return [
2057
+ `compopt +o default 2>/dev/null`,
2058
+ ...encLines,
2059
+ `local _varname=${varName}__\${_enc_key}`,
2060
+ `local _raw="\${!_varname:-}"`,
2061
+ `if [[ -n "$_raw" ]]; then`,
2062
+ ` local -a _vals=()`,
2063
+ ` local _line`,
2064
+ ` while IFS= read -r _line; do _vals+=("$_line"); done <<< "$_raw"`,
2065
+ ` local _c _ck _seen_keys=" " _had_key=0`,
2066
+ ` for _c in "\${_vals[@]}"; do`,
2067
+ ` [[ -z "$_c" ]] && continue`,
2068
+ ` if [[ "$_c" == *=* ]]; then`,
2069
+ ` _ck="\${_c%%=*}"`,
2070
+ ...arrayDedupLines,
2071
+ ` if [[ "$_cur" != *=* ]]; then`,
2072
+ ` [[ "$_seen_keys" == *" $_ck "* ]] && continue`,
2073
+ ` _seen_keys+="$_ck "`,
2074
+ ` _c="\${_ck}="`,
2075
+ ` _had_key=1`,
2076
+ ` elif [[ "$_c" != *=?* ]]; then`,
2077
+ ` continue`,
2078
+ ` fi`,
2079
+ ` fi`,
2080
+ ` [[ "$_c" == "$_cur"* ]] && COMPREPLY+=(${inlineExpr})`,
2081
+ ` done`,
2082
+ ` if (( _had_key )); then compopt -o nospace 2>/dev/null; fi`,
2083
+ `fi`,
2084
+ `if (( \${#COMPREPLY[@]} == 0 )); then COMPREPLY=( "" ); fi`
2085
+ ];
2086
+ }
2087
+ case "dynamic": return [
2088
+ `local _dyn_out`,
2089
+ `_dyn_out=$(__${fn}_invoke_complete bash "\${_words[@]}")`,
2090
+ `__${fn}_apply_dynamic_output "$_dyn_out"`
2091
+ ];
2092
+ case "choices": {
2093
+ const lines = [
2094
+ `local -a _choices=(${vc.choices.map((c) => `"${escapeBashDQ(c)}"`).join(" ")})`,
2095
+ `COMPREPLY=()`,
2096
+ `local _c; for _c in "\${_choices[@]}"; do [[ "$_c" == "$_cur"* ]] && COMPREPLY+=("\${_inline_prefix}\${_c}"); done`
2097
+ ];
2098
+ if (inline) lines.push(`compopt -o nospace`);
2099
+ lines.push(`compopt +o default 2>/dev/null`);
2100
+ return lines;
2101
+ }
2102
+ case "file":
2103
+ if (vc.matcher?.length) return bashFileFilter(vc.matcher.map((p) => `[[ "\${_f##*/}" == ${p} ]]`).join(" || "));
2104
+ if (vc.extensions?.length) return bashFileFilter(vc.extensions.map((ext) => `[[ "$_f" == *".${ext}" ]]`).join(" || "));
2105
+ return [`COMPREPLY=($(compgen -P "$_inline_prefix" -f -- "$_cur"))`, `compopt -o filenames`];
2106
+ case "directory": return [`COMPREPLY=($(compgen -P "$_inline_prefix" -d -- "$_cur"))`, `compopt -o filenames`];
2107
+ case "command": return [`COMPREPLY=($(compgen -P "$_inline_prefix" -W "$(${vc.shellCommand})" -- "$_cur"))`];
2108
+ case "none": return [`compopt +o default 2>/dev/null`];
2109
+ }
2110
+ }
2111
+ /**
2112
+ * Snippet that unsets every shell variable matching `<prefix>*`. Bash 3.2
2113
+ * has no associative arrays, so the trackers use one variable per field;
2114
+ * the per-invocation reset clears them by enumerating with `compgen -v
2115
+ * <prefix>` and feeding the names to `unset`. `2>/dev/null` is paired both
2116
+ * sides so an empty enumeration result (no variables yet) doesn't print
2117
+ * the `unset:` usage line.
2118
+ */
2119
+ function unsetPrefixed(prefix) {
2120
+ return `unset $(compgen -v ${prefix} 2>/dev/null) 2>/dev/null`;
2121
+ }
2122
+ function bashFileFilter(checks) {
2123
+ return [
2124
+ `local -a _all_entries=($(compgen -f -- "$_cur"))`,
2125
+ `for _f in "\${_all_entries[@]}"; do`,
2126
+ ` if [[ -d "$_f" ]]; then`,
2127
+ ` COMPREPLY+=("\${_inline_prefix}$_f")`,
2128
+ ` elif ${checks}; then`,
2129
+ ` COMPREPLY+=("\${_inline_prefix}$_f")`,
2130
+ ` fi`,
2131
+ `done`,
2132
+ `compopt -o filenames`,
2133
+ `compopt +o default 2>/dev/null`
2134
+ ];
2135
+ }
2136
+ /** Collect value-taking option patterns for case matching */
2137
+ function optionValueCases$2(options, positionals, inline, fn, funcSuffix) {
2138
+ const lines = [];
2139
+ for (const opt of options) {
2140
+ if (!opt.takesValue || !opt.valueCompletion) continue;
2141
+ const valLines = bashValueLines(opt.valueCompletion, inline, fn, {
2142
+ funcSuffix,
2143
+ ...optionExpandLocation(opt, options, positionals)
2144
+ });
2145
+ if (valLines.length === 0) continue;
2146
+ const patterns = effectiveOptionTokens(opt, options);
2147
+ if (patterns.length === 0) continue;
2148
+ lines.push(` ${patterns.join("|")})`);
2149
+ for (const vl of valLines) lines.push(` ${vl}`);
2150
+ lines.push(` return ;;`);
2151
+ }
2152
+ return lines;
2153
+ }
2154
+ /** Generate positional completion block */
2155
+ function positionalBlock$2(positionals, fn, funcSuffix, options = []) {
2156
+ if (positionals.length === 0) return [];
2157
+ const lines = [];
2158
+ lines.push(` case "$_pos_count" in`);
2159
+ for (const pos of positionals) {
2160
+ if (pos.variadic) lines.push(` ${pos.position}|*)`);
2161
+ else lines.push(` ${pos.position})`);
2162
+ for (const vl of bashValueLines(pos.valueCompletion, false, fn, {
2163
+ funcSuffix,
2164
+ ...positionalExpandLocation(pos, options, positionals)
2165
+ })) lines.push(` ${vl}`);
2166
+ lines.push(` ;;`);
2167
+ }
2168
+ lines.push(` esac`);
2169
+ return lines;
2170
+ }
2171
+ /** Generate prev/inline value completion blocks for options */
2172
+ function valueCompletionBlocks(options, positionals, fn, funcSuffix) {
2173
+ if (!options.some((o) => o.takesValue && o.valueCompletion)) return [];
2174
+ const lines = [];
2175
+ const prevCases = optionValueCases$2(options, positionals, false, fn, funcSuffix);
2176
+ if (prevCases.length > 0) {
2177
+ lines.push(` if [[ -z "$_inline_prefix" ]]; then`);
2178
+ lines.push(` case "$_prev" in`);
2179
+ lines.push(...prevCases);
2180
+ lines.push(` esac`);
2181
+ lines.push(` fi`);
2182
+ }
2183
+ const inlineCases = optionValueCases$2(options, positionals, true, fn, funcSuffix);
2184
+ if (inlineCases.length > 0) {
2185
+ lines.push(` if [[ -n "$_inline_prefix" ]]; then`);
2186
+ lines.push(` case "\${_inline_prefix%=}" in`);
2187
+ lines.push(...inlineCases);
2188
+ lines.push(` esac`);
2189
+ lines.push(` fi`);
2190
+ }
2191
+ return lines;
2192
+ }
2193
+ /** Generate available-options list lines */
2194
+ function availableOptionLines$2(options, fn) {
2195
+ const lines = [];
2196
+ for (const opt of options) {
2197
+ if (opt.valueType === "array") {
2198
+ lines.push(` _avail+=(--${opt.cliName})`);
2199
+ continue;
2200
+ }
2201
+ const patterns = quotedAvailabilityTokens(opt.cliName, opt.alias, opt.negation, {
2202
+ isGlobal: opt.isGlobal === true,
2203
+ frameOptions: options
2204
+ });
2205
+ const guard = `__${fn}_not_used ${patterns.join(" ")}`;
2206
+ const emitNames = opt.negation ? [opt.cliName, opt.negation] : [opt.cliName];
2207
+ for (const name of emitNames) {
2208
+ if (!patterns.includes(`"--${name}"`)) continue;
2209
+ lines.push(` ${guard} && _avail+=(--${name})`);
2210
+ }
2211
+ }
2212
+ lines.push(` __${fn}_not_used "--help" && _avail+=(--help)`);
2213
+ return lines;
2214
+ }
2215
+ /**
2216
+ * Generate a per-subcommand completion function.
2217
+ * Recursively generates functions for nested subcommands.
2218
+ */
2219
+ function generateSubHandler$2(sub, fn, path) {
2220
+ const fullPath = [...path, sub.name];
2221
+ const funcSuffix = fullPath.map(sanitize).join("_");
2222
+ const funcName = `__${fn}_complete_${funcSuffix}`;
2223
+ const visibleSubs = getVisibleSubs(sub.subcommands);
2224
+ const lines = [];
2225
+ for (const child of visibleSubs) lines.push(...generateSubHandler$2(child, fn, fullPath));
2226
+ lines.push(`${funcName}() {`);
2227
+ lines.push(...valueCompletionBlocks(sub.options, sub.positionals, fn, funcSuffix));
2228
+ const fullPathStr = fullPath.join(":");
2229
+ lines.push(` if [[ -z "$_inline_prefix" ]] && __${fn}_opt_takes_value "${fullPathStr}" "$_prev"; then return; fi`);
2230
+ lines.push(` if [[ -n "$_inline_prefix" ]] && __${fn}_opt_takes_value "${fullPathStr}" "\${_inline_prefix%=}"; then return; fi`);
2231
+ if (sub.positionals.length > 0) {
2232
+ lines.push(` if (( _after_dd )); then`);
2233
+ lines.push(...positionalBlock$2(sub.positionals, fn, funcSuffix, sub.options).map((l) => ` ${l}`));
2234
+ lines.push(` return`);
2235
+ lines.push(` fi`);
2236
+ } else lines.push(` if (( _after_dd )); then return; fi`);
2237
+ lines.push(` if [[ "$_cur" == -* ]]; then`);
2238
+ lines.push(` local -a _avail=()`);
2239
+ lines.push(...availableOptionLines$2(sub.options, fn));
2240
+ lines.push(` COMPREPLY=($(compgen -W "\${_avail[*]}" -- "$_cur"))`);
2241
+ lines.push(` compopt +o default 2>/dev/null`);
2242
+ lines.push(` return`);
2243
+ lines.push(` fi`);
2244
+ if (visibleSubs.length > 0) {
2245
+ const subNames = getSubNamesWithAliases(sub.subcommands).map((s) => s.name).join(" ");
2246
+ lines.push(` COMPREPLY=($(compgen -W "${subNames}" -- "$_cur"))`);
2247
+ lines.push(` compopt +o default 2>/dev/null`);
2248
+ } else if (sub.positionals.length > 0) lines.push(...positionalBlock$2(sub.positionals, fn, funcSuffix, sub.options));
2249
+ lines.push(`}`);
2250
+ lines.push(``);
2251
+ return lines;
2252
+ }
2253
+ function generateBashCompletion(command, options) {
2254
+ const { programName } = options;
2255
+ const data = extractCompletionData(command, programName, options.globalArgsSchema);
2256
+ const fn = sanitize(programName);
2257
+ const root = data.command;
2258
+ const visibleSubs = getVisibleSubs(root.subcommands);
2259
+ const expandSpecs = collectExpandSpecs(root);
2260
+ const trackedFields = collectTrackedFields(root, expandSpecs, data.globalOptions);
2261
+ const lines = [];
2262
+ lines.push(...buildHeaderLines({
2263
+ programName,
2264
+ shell: "bash",
2265
+ binPath: options.binPath,
2266
+ programVersion: options.programVersion
2267
+ }));
2268
+ lines.push(`# Generated by politty`);
2269
+ lines.push(``);
2270
+ lines.push(...generateBashSelfRefresh({
2271
+ programName,
2272
+ binPath: options.binPath
2273
+ }));
2274
+ const hasExpand = expandSpecs.length > 0;
2275
+ const arrayExpandSpecs = expandSpecs.filter((s) => s.isArrayOption);
2276
+ const hasArrayExpand = arrayExpandSpecs.length > 0;
2277
+ if (hasExpand) {
2278
+ lines.push(`__${fn}_enc() {`);
2279
+ lines.push(` local LC_ALL=C`);
2280
+ lines.push(` local _s=$1 _r='' _c _i`);
2281
+ lines.push(` for (( _i=0; _i<\${#_s}; _i++ )); do`);
2282
+ lines.push(` _c=\${_s:_i:1}`);
2283
+ lines.push(` case "$_c" in`);
2284
+ lines.push(` [a-zA-Z0-9]) _r+="$_c" ;;`);
2285
+ lines.push(` *) printf -v _r '%s_%02X' "$_r" "'$_c" ;;`);
2286
+ lines.push(` esac`);
2287
+ lines.push(` done`);
2288
+ lines.push(` printf '%s' "$_r"`);
2289
+ lines.push(`}`);
2290
+ lines.push(``);
2291
+ }
2292
+ for (const spec of expandSpecs) {
2293
+ const varName = expandTableVarName(fn, spec.funcSuffix, spec.fieldName);
2294
+ for (const entry of spec.vc.table) {
2295
+ const encKey = entry.key.map(bashEncodeKey).join("_");
2296
+ const value = entry.candidates.map((c) => c.value).join("\n");
2297
+ lines.push(`${varName}__${encKey}=${ansiC(value)}`);
2298
+ }
2299
+ lines.push(``);
2300
+ }
2301
+ if (hasDynamicCompletion(root)) {
2302
+ lines.push(...dynamicInvokeCompleteLines(fn, programName));
2303
+ lines.push(``);
2304
+ lines.push(`__${fn}_apply_dynamic_output() {`);
2305
+ lines.push(` local _raw="$1"`);
2306
+ lines.push(` COMPREPLY=()`);
2307
+ lines.push(` local _directive=0`);
2308
+ lines.push(` local -a _lines=()`);
2309
+ lines.push(` local _line`);
2310
+ lines.push(` while IFS= read -r _line; do _lines+=("$_line"); done <<< "$_raw"`);
2311
+ lines.push(` local _last=$((\${#_lines[@]} - 1))`);
2312
+ lines.push(` if (( _last >= 0 )) && [[ "\${_lines[$_last]}" =~ ^:[0-9]+$ ]]; then`);
2313
+ lines.push(` _directive="\${_lines[$_last]#:}"`);
2314
+ lines.push(` unset '_lines[_last]'`);
2315
+ lines.push(` fi`);
2316
+ lines.push(` for _line in "\${_lines[@]}"; do`);
2317
+ lines.push(` [[ -z "$_line" ]] && continue`);
2318
+ lines.push(` COMPREPLY+=("$_line")`);
2319
+ lines.push(` done`);
2320
+ lines.push(` local _ip="\${_inline_prefix:-}"`);
2321
+ lines.push(` if (( _directive & ${CompletionDirective.DirectoryCompletion} )); then`);
2322
+ lines.push(` compopt +o default 2>/dev/null`);
2323
+ lines.push(` compopt -o filenames 2>/dev/null`);
2324
+ lines.push(` local _d`);
2325
+ lines.push(` while IFS= read -r _d; do COMPREPLY+=("\${_ip}\${_d}"); done < <(compgen -d -- "$_cur")`);
2326
+ lines.push(` if (( \${#COMPREPLY[@]} == 0 )); then COMPREPLY=( "" ); fi`);
2327
+ lines.push(` elif (( _directive & ${CompletionDirective.FileCompletion} )); then`);
2328
+ lines.push(` if (( \${#COMPREPLY[@]} > 0 )) || [[ -n "$_ip" ]]; then`);
2329
+ lines.push(` compopt -o filenames 2>/dev/null`);
2330
+ lines.push(` local _f`);
2331
+ lines.push(` while IFS= read -r _f; do COMPREPLY+=("\${_ip}\${_f}"); done < <(compgen -f -- "$_cur")`);
2332
+ lines.push(` else`);
2333
+ lines.push(` compopt -o default 2>/dev/null`);
2334
+ lines.push(` fi`);
2335
+ lines.push(` else`);
2336
+ lines.push(` if (( _directive & ${CompletionDirective.NoFileCompletion} )); then`);
2337
+ lines.push(` compopt +o default 2>/dev/null`);
2338
+ lines.push(` if (( \${#COMPREPLY[@]} == 0 )); then COMPREPLY=( "" ); fi`);
2339
+ lines.push(` fi`);
2340
+ lines.push(` fi`);
2341
+ lines.push(` if (( _directive & ${CompletionDirective.NoSpace} )); then`);
2342
+ lines.push(` compopt -o nospace 2>/dev/null`);
2343
+ lines.push(` fi`);
2344
+ lines.push(`}`);
2345
+ lines.push(``);
2346
+ }
2347
+ lines.push(`__${fn}_not_used() {`);
2348
+ lines.push(` for _u in "\${_used_opts[@]}"; do`);
2349
+ lines.push(` for _chk in "$@"; do`);
2350
+ lines.push(` [[ "$_u" == "$_chk" ]] && return 1`);
2351
+ lines.push(` done`);
2352
+ lines.push(` done`);
2353
+ lines.push(` return 0`);
2354
+ lines.push(`}`);
2355
+ lines.push(``);
2356
+ lines.push(`__${fn}_opt_takes_value() {`);
2357
+ lines.push(` case "$1:$2" in`);
2358
+ lines.push(...optTakesValueEntries(root, ""));
2359
+ lines.push(` esac`);
2360
+ lines.push(` return 1`);
2361
+ lines.push(`}`);
2362
+ lines.push(``);
2363
+ if (hasExpand) {
2364
+ lines.push(`__${fn}_track_opt() {`);
2365
+ lines.push(` case "$1:$2" in`);
2366
+ lines.push(...trackOptCaseLines(trackedFields, "bash"));
2367
+ lines.push(` esac`);
2368
+ lines.push(`}`);
2369
+ lines.push(``);
2370
+ lines.push(`__${fn}_track_pos() {`);
2371
+ lines.push(` case "$1:$2" in`);
2372
+ lines.push(...trackPosCaseLines(trackedFields, "bash"));
2373
+ lines.push(` esac`);
2374
+ lines.push(`}`);
2375
+ lines.push(``);
2376
+ }
2377
+ if (hasArrayExpand) {
2378
+ lines.push(`__${fn}_track_array_expand() {`);
2379
+ lines.push(` case "$1:$2" in`);
2380
+ lines.push(...trackArrayExpandCaseLines(arrayExpandSpecs, "bash"));
2381
+ lines.push(` esac`);
2382
+ lines.push(`}`);
2383
+ lines.push(``);
2384
+ }
2385
+ const routeEntries = collectRouteEntries(root);
2386
+ if (routeEntries.length > 0) {
2387
+ lines.push(`__${fn}_is_subcmd() {`);
2388
+ lines.push(` case "$1:$2" in`);
2389
+ lines.push(...isSubcmdCaseLines(routeEntries));
2390
+ lines.push(` esac`);
2391
+ lines.push(` return 1`);
2392
+ lines.push(`}`);
2393
+ lines.push(``);
2394
+ }
2395
+ for (const sub of visibleSubs) lines.push(...generateSubHandler$2(sub, fn, []));
2396
+ lines.push(`__${fn}_complete_root() {`);
2397
+ lines.push(...valueCompletionBlocks(root.options, root.positionals, fn, "root"));
2398
+ lines.push(` if [[ -z "$_inline_prefix" ]] && __${fn}_opt_takes_value "" "$_prev"; then return; fi`);
2399
+ lines.push(` if [[ -n "$_inline_prefix" ]] && __${fn}_opt_takes_value "" "\${_inline_prefix%=}"; then return; fi`);
2400
+ if (root.positionals.length > 0) {
2401
+ lines.push(` if (( _after_dd )); then`);
2402
+ lines.push(...positionalBlock$2(root.positionals, fn, "root", root.options).map((l) => ` ${l}`));
2403
+ lines.push(` return`);
2404
+ lines.push(` fi`);
2405
+ } else lines.push(` if (( _after_dd )); then return; fi`);
2406
+ lines.push(` if [[ "$_cur" == -* ]]; then`);
2407
+ lines.push(` local -a _avail=()`);
2408
+ lines.push(...availableOptionLines$2(root.options, fn));
2409
+ lines.push(` COMPREPLY=($(compgen -W "\${_avail[*]}" -- "$_cur"))`);
2410
+ lines.push(` compopt +o default 2>/dev/null`);
2411
+ if (visibleSubs.length > 0) {
2412
+ lines.push(` else`);
2413
+ const subNames = getSubNamesWithAliases(root.subcommands).map((s) => s.name).join(" ");
2414
+ lines.push(` COMPREPLY=($(compgen -W "${subNames}" -- "$_cur"))`);
2415
+ lines.push(` compopt +o default 2>/dev/null`);
2416
+ } else if (root.positionals.length > 0) {
2417
+ lines.push(` else`);
2418
+ lines.push(...positionalBlock$2(root.positionals, fn, "root", root.options).map((l) => ` ${l}`));
2419
+ }
2420
+ lines.push(` fi`);
2421
+ lines.push(`}`);
2422
+ lines.push(``);
2423
+ const subRouting = subDispatchCaseLines(routeEntries, fn).join("\n");
2424
+ lines.push(`_${fn}_completions() {`);
2425
+ lines.push(` COMPREPLY=()`);
2426
+ lines.push(``);
2427
+ lines.push(` # Rejoin words split by '=' in COMP_WORDBREAKS`);
2428
+ lines.push(` local -a _words=()`);
2429
+ lines.push(` local _i=1`);
2430
+ lines.push(` while (( _i <= COMP_CWORD )); do`);
2431
+ lines.push(` if [[ "\${COMP_WORDS[_i]}" == "=" && \${#_words[@]} -gt 0 ]]; then`);
2432
+ lines.push(` _words[\${#_words[@]}-1]+="=\${COMP_WORDS[_i+1]:-}"`);
2433
+ lines.push(` (( _i += 2 ))`);
2434
+ lines.push(` else`);
2435
+ lines.push(` _words+=("\${COMP_WORDS[_i]}")`);
2436
+ lines.push(` (( _i++ ))`);
2437
+ lines.push(` fi`);
2438
+ lines.push(` done`);
2439
+ lines.push(``);
2440
+ lines.push(` local _cur=""`);
2441
+ lines.push(` (( \${#_words[@]} > 0 )) && _cur="\${_words[\${#_words[@]}-1]}"`);
2442
+ lines.push(` local _inline_prefix=""`);
2443
+ lines.push(``);
2444
+ lines.push(` local _prev=""`);
2445
+ lines.push(` (( \${#_words[@]} > 1 )) && _prev="\${_words[\${#_words[@]}-2]}"`);
2446
+ lines.push(``);
2447
+ lines.push(` local _subcmd="" _after_dd=0 _pos_count=0 _skip_next=0`);
2448
+ lines.push(` local -a _used_opts=()`);
2449
+ if (hasExpand) {
2450
+ lines.push(` ${unsetPrefixed("_arg_values_")}`);
2451
+ lines.push(` ${unsetPrefixed("_global_arg_values_")}`);
2452
+ }
2453
+ if (hasArrayExpand) {
2454
+ lines.push(` ${unsetPrefixed("_used_field_keys_")}`);
2455
+ lines.push(` ${unsetPrefixed("_global_used_field_keys_")}`);
2456
+ lines.push(` ${unsetPrefixed("_global_arr_seen_")}`);
2457
+ }
2458
+ lines.push(``);
2459
+ lines.push(` local _j=0`);
2460
+ lines.push(` while (( _j < \${#_words[@]} - 1 )); do`);
2461
+ lines.push(` local _w="\${_words[_j]}"`);
2462
+ lines.push(` if (( _skip_next )); then _skip_next=0; (( _j++ )); continue; fi`);
2463
+ lines.push(` if [[ "$_w" == "--" ]]; then _after_dd=1; (( _j++ )); continue; fi`);
2464
+ const afterDdTrack = hasExpand ? `__${fn}_track_pos "$_subcmd" "$_pos_count" "$_w"; ` : "";
2465
+ lines.push(` if (( _after_dd )); then ${afterDdTrack}(( _pos_count++ )); (( _j++ )); continue; fi`);
2466
+ lines.push(` if [[ "$_w" == -*=* ]]; then`);
2467
+ lines.push(` _used_opts+=("\${_w%%=*}")`);
2468
+ if (hasExpand) {
2469
+ lines.push(` __${fn}_track_opt "$_subcmd" "\${_w%%=*}" "\${_w#*=}"`);
2470
+ if (hasArrayExpand) lines.push(` __${fn}_track_array_expand "$_subcmd" "\${_w%%=*}" "\${_w#*=}"`);
2471
+ }
2472
+ lines.push(` (( _j++ )); continue`);
2473
+ lines.push(` fi`);
2474
+ lines.push(` if [[ "$_w" == -* ]]; then`);
2475
+ lines.push(` _used_opts+=("$_w")`);
2476
+ lines.push(` if __${fn}_opt_takes_value "$_subcmd" "$_w"; then`);
2477
+ lines.push(` local _next="\${_words[_j+1]:-}"`);
2478
+ lines.push(` if [[ -n "$_next" && "$_next" != -* ]]; then _skip_next=1; fi`);
2479
+ if (hasExpand) {
2480
+ lines.push(` if (( _skip_next )); then`);
2481
+ lines.push(` __${fn}_track_opt "$_subcmd" "$_w" "$_next"`);
2482
+ if (hasArrayExpand) {
2483
+ lines.push(` if (( _j + 2 < \${#_words[@]} )); then`);
2484
+ lines.push(` __${fn}_track_array_expand "$_subcmd" "$_w" "$_next"`);
2485
+ lines.push(` fi`);
2486
+ }
2487
+ lines.push(` fi`);
2488
+ }
2489
+ lines.push(` fi`);
2490
+ lines.push(` (( _j++ )); continue`);
2491
+ lines.push(` fi`);
2492
+ const clearState = hasArrayExpand ? `; ${unsetPrefixed("_arg_values_")}; ${unsetPrefixed("_used_field_keys_")}; ${unsetPrefixed("_global_arr_seen_")}` : hasExpand ? `; ${unsetPrefixed("_arg_values_")}` : "";
2493
+ const posTrack = hasExpand ? `__${fn}_track_pos "$_subcmd" "$_pos_count" "$_w"; ` : "";
2494
+ if (routeEntries.length > 0) lines.push(` if __${fn}_is_subcmd "$_subcmd" "$_w"; then _subcmd="\${_subcmd:+\${_subcmd}:}$_w"; _used_opts=(); _pos_count=0${clearState}; else ${posTrack}(( _pos_count++ )); fi`);
2495
+ else {
2496
+ if (hasExpand) lines.push(` __${fn}_track_pos "$_subcmd" "$_pos_count" "$_w"`);
2497
+ lines.push(` (( _pos_count++ ))`);
2498
+ }
2499
+ lines.push(` (( _j++ ))`);
2500
+ lines.push(` done`);
2501
+ lines.push(``);
2502
+ lines.push(` if (( ! _after_dd )) && [[ "$_cur" == -*=* ]]; then`);
2503
+ lines.push(` _inline_prefix="\${_cur%%=*}="`);
2504
+ lines.push(` _cur="\${_cur#*=}"`);
2505
+ lines.push(` fi`);
2506
+ lines.push(``);
2507
+ lines.push(` case "$_subcmd" in`);
2508
+ lines.push(subRouting);
2509
+ lines.push(` *) __${fn}_complete_root ;;`);
2510
+ lines.push(` esac`);
2511
+ lines.push(`}`);
2512
+ lines.push(``);
2513
+ lines.push(`complete -o default -F _${fn}_completions ${programName}`);
2514
+ lines.push(``);
2515
+ return {
2516
+ script: lines.join("\n"),
2517
+ shell: "bash",
2518
+ installInstructions: `# To enable auto-refreshing bash completions, add this to your ~/.bashrc:
2519
+ eval "$(${programName} completion bash)"
2520
+
2521
+ # For faster shell startup, save the script instead:
2522
+ mkdir -p ~/.local/share/bash-completion/completions
2523
+ ${programName} completion bash > ~/.local/share/bash-completion/completions/${programName}
2524
+
2525
+ # Then reload your shell or run:
2526
+ source ~/.bashrc`
2527
+ };
2528
+ }
2529
+
2530
+ //#endregion
2531
+ //#region src/completion/dynamic/shell-formatter.ts
2532
+ /**
2533
+ * Format completion candidates for the specified shell
2534
+ *
2535
+ * @returns Shell-ready output string (lines separated by newline, last line is :directive)
2536
+ */
2537
+ function formatForShell(result, options) {
2538
+ switch (options.shell) {
2539
+ case "bash": return formatForBash(result, options);
2540
+ case "zsh": return formatForZsh(result, options);
2541
+ case "fish": return formatForFish(result, options);
2542
+ }
2543
+ }
2544
+ /**
2545
+ * Append extension metadata and directive to output lines
2546
+ */
2547
+ function appendMetadata(lines, result) {
2548
+ if (result.fileExtensions && result.fileExtensions.length > 0) lines.push(`@ext:${result.fileExtensions.join(",")}`);
2549
+ if (result.fileMatchers && result.fileMatchers.length > 0) lines.push(`@matcher:${result.fileMatchers.join(",")}`);
2550
+ lines.push(`:${result.directive}`);
2551
+ }
2552
+ /**
2553
+ * Format for bash
2554
+ *
2555
+ * - Pre-filters candidates by currentWord prefix (replaces compgen -W)
2556
+ * - Handles --opt=value inline values by prepending prefix
2557
+ * - Outputs plain values only (no descriptions - bash COMPREPLY doesn't support them)
2558
+ * - Last line: :directive
2559
+ */
2560
+ function formatForBash(result, options) {
2561
+ const lines = ((result.directive & CompletionDirective.FilterPrefix) !== 0 && options.currentWord ? result.candidates.filter((c) => c.value.startsWith(options.currentWord)) : result.candidates).map((c) => options.inlinePrefix ? `${options.inlinePrefix}${c.value}` : c.value);
2562
+ appendMetadata(lines, result);
2563
+ return lines.join("\n");
2564
+ }
2565
+ /**
2566
+ * Format for zsh
2567
+ *
2568
+ * - Outputs value:description pairs for _describe
2569
+ * - Colons in values/descriptions are escaped with backslash
2570
+ * - Last line: :directive
2571
+ */
2572
+ function formatForZsh(result, _options) {
2573
+ const lines = result.candidates.map((c) => {
2574
+ const escapedValue = c.value.replace(/:/g, "\\:");
2575
+ if (c.description) return `${escapedValue}:${c.description.replace(/:/g, "\\:")}`;
2576
+ return escapedValue;
2577
+ });
2578
+ appendMetadata(lines, result);
2579
+ return lines.join("\n");
2580
+ }
2581
+ /**
2582
+ * Format for fish
2583
+ *
2584
+ * - Outputs value\tdescription pairs
2585
+ * - Last line: :directive
2586
+ */
2587
+ function formatForFish(result, _options) {
2588
+ const lines = result.candidates.map((c) => {
2589
+ if (c.description) return `${c.value}\t${c.description}`;
2590
+ return c.value;
2591
+ });
2592
+ appendMetadata(lines, result);
2593
+ return lines.join("\n");
2594
+ }
2595
+
2596
+ //#endregion
2597
+ //#region src/completion/dynamic/complete-command.ts
2598
+ /**
2599
+ * Dynamic completion command implementation
2600
+ *
2601
+ * This creates a hidden `__complete` command that outputs completion candidates
2602
+ * for shell scripts to consume. Usage:
2603
+ *
2604
+ * mycli __complete --shell bash -- build --fo
2605
+ * mycli __complete --shell zsh -- plugin add
2606
+ *
2607
+ * Output format depends on the target shell:
2608
+ * bash: plain values (pre-filtered by prefix), last line :directive
2609
+ * zsh: value:description pairs, last line :directive
2610
+ * fish: value\tdescription pairs, last line :directive
2611
+ */
2612
+ /**
2613
+ * Schema for the __complete command
2614
+ */
2615
+ const completeArgsSchema = zod.z.object({
2616
+ shell: require_schema_extractor.arg(zod.z.enum([
2617
+ "bash",
2618
+ "zsh",
2619
+ "fish"
2620
+ ]), { description: "Target shell for output formatting" }),
2621
+ args: require_schema_extractor.arg(zod.z.array(zod.z.string()).default([]), {
2622
+ positional: true,
2623
+ description: "Arguments to complete",
2624
+ variadic: true
2625
+ })
2626
+ });
2627
+ /**
2628
+ * Create the dynamic completion command
2629
+ *
2630
+ * @param rootCommand - The root command to generate completions for
2631
+ * @param programName - The program name (optional, defaults to rootCommand.name)
2632
+ * @param globalArgsSchema - Global args schema. Forwarded to
2633
+ * `parseCompletionContext` so resolvers attached to global options remain
2634
+ * reachable at every subcommand level.
2635
+ * @returns A command that outputs completion candidates
2636
+ */
2637
+ function createDynamicCompleteCommand(rootCommand, _programName, globalArgsSchema) {
2638
+ return defineCommand({
2639
+ name: "__complete",
2640
+ args: completeArgsSchema,
2641
+ async run(args) {
2642
+ const context = parseCompletionContext(args.args, rootCommand, globalArgsSchema);
2643
+ const inlinePrefix = context.completionType === "option-value" && context.targetOption ? detectInlineOptionPrefix(context.currentWord) : void 0;
2644
+ const effectiveWord = inlinePrefix ? context.currentWord.slice(inlinePrefix.length) : context.currentWord;
2645
+ const output = formatForShell(await generateCandidates(context, { shell: args.shell }), {
2646
+ shell: args.shell,
2647
+ currentWord: effectiveWord,
2648
+ inlinePrefix
2649
+ });
2650
+ console.log(output);
2651
+ }
2652
+ });
2653
+ }
2654
+ /**
2655
+ * Check if a command tree contains the __complete command
2656
+ */
2657
+ function hasCompleteCommand(command) {
2658
+ return Boolean(command.subCommands?.["__complete"]);
2659
+ }
2660
+
2661
+ //#endregion
2662
+ //#region src/completion/fish.ts
2663
+ /** Escape shell-special characters for fish double-quoted strings */
2664
+ function escapeDesc$1(s) {
2665
+ return s.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\$/g, "\\$");
2666
+ }
2667
+ /**
2668
+ * Escape a fish `switch` case pattern. Fish's `case` interprets its
2669
+ * arguments as globs even when double-quoted, so glob metacharacters
2670
+ * (`*`, `?`, `[`, `]`) must be backslash-escaped to keep the comparison
2671
+ * literal — otherwise a key like `prod*` would also match a runtime
2672
+ * value of `production`. Quote/dollar/backslash are escaped first so the
2673
+ * resulting string remains valid inside a double-quoted literal.
2674
+ */
2675
+ function fishCaseEscape(s) {
2676
+ return s.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\$/g, "\\$").replace(/\*/g, "\\*").replace(/\?/g, "\\?").replace(/\[/g, "\\[").replace(/]/g, "\\]");
2677
+ }
2678
+ /**
2679
+ * Generate fish value completion lines for a ValueCompletion spec.
2680
+ * Each line outputs candidates via echo (tab-separated value\tdescription).
2681
+ *
2682
+ * `location` is required for the expand variant (carries fieldName +
2683
+ * isArrayOption); other variants ignore it.
2684
+ */
2685
+ function fishValueLines(vc, fn, location) {
2686
+ if (!vc) return [];
2687
+ switch (vc.type) {
2688
+ case "expand": {
2689
+ if (!location) throw new Error("fishValueLines: expand variant requires a location");
2690
+ const depExpr = (d) => {
2691
+ const safe = sanitize(d.name);
2692
+ return d.isGlobal ? `$_global_arg_values_${safe}` : `$_arg_values_${safe}`;
2693
+ };
2694
+ const depKey = location.resolvedDeps.map((d) => `"${depExpr(d)}"`).join(`\\x1f`);
2695
+ const bucket = sanitize(location.fieldName);
2696
+ const bucketList = location.isGlobal ? `$_global_used_field_keys_${bucket}` : `$_used_field_keys_${bucket}`;
2697
+ const out = [`switch ${depKey}`];
2698
+ for (const entry of vc.table) {
2699
+ const casePattern = entry.key.map((k) => `"${fishCaseEscape(k)}"`).join(`\\x1f`);
2700
+ out.push(` case ${casePattern}`);
2701
+ const keyOnlyLines = [];
2702
+ const fullLines = [];
2703
+ const seenKeys = /* @__PURE__ */ new Set();
2704
+ const printfLine = (value, description) => description ? `printf '%s\\t%s\\n' "${escapeDesc$1(value)}" "${escapeDesc$1(description)}"` : `printf '%s\\n' "${escapeDesc$1(value)}"`;
2705
+ const wrapWithDedup = (echoLine, keyPart) => location.isArrayOption && keyPart.length > 0 ? [
2706
+ ` if not contains -- "${escapeDesc$1(keyPart)}" ${bucketList}`,
2707
+ ` ${echoLine}`,
2708
+ ` end`
2709
+ ] : [` ${echoLine}`];
2710
+ for (const c of entry.candidates) {
2711
+ const eqIdx = c.value.indexOf("=");
2712
+ const keyPart = eqIdx > 0 ? c.value.slice(0, eqIdx) : "";
2713
+ const echoLine = printfLine(c.value, c.description);
2714
+ if (!(keyPart.length > 0 && c.value.length === eqIdx + 1)) fullLines.push(...wrapWithDedup(echoLine, keyPart));
2715
+ if (keyPart.length === 0) keyOnlyLines.push(` ${echoLine}`);
2716
+ else if (!seenKeys.has(keyPart)) {
2717
+ seenKeys.add(keyPart);
2718
+ keyOnlyLines.push(...wrapWithDedup(printfLine(`${keyPart}=`, c.description), keyPart));
2719
+ }
2720
+ }
2721
+ if (fullLines.length !== keyOnlyLines.length || fullLines.some((l, i) => l !== keyOnlyLines[i])) {
2722
+ out.push(` if string match -q '*=*' -- "$_cur"`);
2723
+ out.push(...fullLines);
2724
+ out.push(` else`);
2725
+ out.push(...keyOnlyLines);
2726
+ out.push(` end`);
2727
+ } else out.push(...fullLines);
2728
+ }
2729
+ out.push(`end`);
2730
+ return out;
2731
+ }
2732
+ case "dynamic": return [`__${fn}_invoke_complete fish $_args | __${fn}_apply_dynamic_output "$_cur"`];
2733
+ case "choices": return vc.choices.map((c) => `echo "${escapeDesc$1(c)}"`);
2734
+ case "file":
2735
+ if (vc.matcher?.length) return fishMatcherLines(vc.matcher);
2736
+ if (vc.extensions?.length) return fishExtensionLines(vc.extensions);
2737
+ return [`__fish_complete_path "$_cur"`];
2738
+ case "directory": return [`__fish_complete_directories "$_cur"`];
2739
+ case "command": return [
2740
+ `for _v in (${vc.shellCommand})`,
2741
+ ` echo "$_v"`,
2742
+ `end`
2743
+ ];
2744
+ case "none": return [];
2745
+ }
2746
+ }
2747
+ /** Generate fish matcher-filtered file completion */
2748
+ function fishMatcherLines(patterns) {
2749
+ return [
2750
+ `__fish_complete_directories "$_cur"`,
2751
+ `set -l _dir ""`,
2752
+ `if string match -q '*/*' "$_cur"`,
2753
+ ` set _dir (string replace -r '[^/]*$' '' "$_cur")`,
2754
+ `end`,
2755
+ ...patterns.flatMap((p) => [
2756
+ `for _f in "$_dir"${p}`,
2757
+ ` test -f "$_f"; and string match -q "$_cur*" "$_f"; and echo "$_f"`,
2758
+ `end`
2759
+ ])
2760
+ ];
2761
+ }
2762
+ /** Generate fish extension-filtered file completion */
2763
+ function fishExtensionLines(extensions) {
2764
+ const lines = [];
2765
+ lines.push(`__fish_complete_directories "$_cur"`);
2766
+ for (const ext of extensions) {
2767
+ lines.push(`for _f in "$_cur"*.${ext}`);
2768
+ lines.push(` test -f "$_f"; and echo "$_f"`);
2769
+ lines.push(`end`);
2770
+ }
2771
+ return lines;
2772
+ }
2773
+ /** Generate option-value switch cases for fish */
2774
+ function optionValueCases$1(options, positionals, fn) {
2775
+ const lines = [];
2776
+ for (const opt of options) {
2777
+ if (!opt.takesValue || !opt.valueCompletion) continue;
2778
+ const valLines = fishValueLines(opt.valueCompletion, fn, optionExpandLocation(opt, options, positionals));
2779
+ if (valLines.length === 0) continue;
2780
+ const tokens = effectiveOptionTokens(opt, options);
2781
+ if (tokens.length === 0) continue;
2782
+ const cond = tokens.map((t) => `test "$_prev" = "${t}"`).join("; or ");
2783
+ lines.push(` if ${cond}`);
2784
+ for (const vl of valLines) lines.push(` ${vl}`);
2785
+ lines.push(` return`);
2786
+ lines.push(` end`);
2787
+ }
2788
+ return lines;
2789
+ }
2790
+ /** Generate positional completion block for fish */
2791
+ function positionalBlock$1(positionals, fn, options = []) {
2792
+ if (positionals.length === 0) return [];
2793
+ const lines = [];
2794
+ for (const pos of positionals) {
2795
+ const valLines = fishValueLines(pos.valueCompletion, fn, positionalExpandLocation(pos, options, positionals));
2796
+ if (valLines.length === 0) continue;
2797
+ if (pos.variadic) lines.push(` if test $_pos_count -ge ${pos.position}`);
2798
+ else lines.push(` if test $_pos_count -eq ${pos.position}`);
2799
+ for (const vl of valLines) lines.push(` ${vl}`);
2800
+ lines.push(` return`);
2801
+ lines.push(` end`);
2802
+ }
2803
+ return lines;
2804
+ }
2805
+ /** Generate available-option echo lines for fish */
2806
+ function availableOptionLines$1(options, fn) {
2807
+ const lines = [];
2808
+ for (const opt of options) {
2809
+ const desc = escapeDesc$1(opt.description ?? "");
2810
+ if (opt.valueType === "array") {
2811
+ lines.push(` echo "--${opt.cliName}\t${desc}"`);
2812
+ continue;
2813
+ }
2814
+ const checks = quotedAvailabilityTokens(opt.cliName, opt.alias, opt.negation, {
2815
+ isGlobal: opt.isGlobal === true,
2816
+ frameOptions: options
2817
+ });
2818
+ const guard = `__${fn}_not_used ${checks.join(" ")}`;
2819
+ const negDesc = opt.negationDescription ? escapeDesc$1(opt.negationDescription) : desc;
2820
+ const entries = [{
2821
+ name: opt.cliName,
2822
+ desc
2823
+ }];
2824
+ if (opt.negation) entries.push({
2825
+ name: opt.negation,
2826
+ desc: negDesc
2827
+ });
2828
+ for (const e of entries) {
2829
+ if (!checks.includes(`"--${e.name}"`)) continue;
2830
+ lines.push(` ${guard}; and echo "--${e.name}\t${e.desc}"`);
2831
+ }
2832
+ }
2833
+ lines.push(` __${fn}_not_used "--help"; and echo "--help\tShow help"`);
2834
+ return lines;
2835
+ }
2836
+ /**
2837
+ * Generate a per-subcommand completion function for fish.
2838
+ * Recursively generates functions for nested subcommands.
2839
+ */
2840
+ function generateSubHandler$1(sub, fn, path) {
2841
+ const fullPath = [...path, sub.name];
2842
+ const funcName = `__${fn}_complete_${fullPath.map(sanitize).join("_")}`;
2843
+ const visibleSubs = getVisibleSubs(sub.subcommands);
2844
+ const lines = [];
2845
+ for (const child of visibleSubs) lines.push(...generateSubHandler$1(child, fn, fullPath));
2846
+ lines.push(`function ${funcName} --no-scope-shadowing`);
2847
+ lines.push(...optionValueCases$1(sub.options, sub.positionals, fn));
2848
+ const fullPathStr = fullPath.join(":");
2849
+ lines.push(` if __${fn}_opt_takes_value "${fullPathStr}" "$_prev"; return; end`);
2850
+ if (sub.positionals.length > 0) {
2851
+ lines.push(` if test $_after_dd -eq 1`);
2852
+ lines.push(...positionalBlock$1(sub.positionals, fn, sub.options).map((l) => ` ${l}`));
2853
+ lines.push(` return`);
2854
+ lines.push(` end`);
2855
+ } else lines.push(` if test $_after_dd -eq 1; return; end`);
2856
+ lines.push(` if string match -q -- '-*' "$_cur"`);
2857
+ lines.push(...availableOptionLines$1(sub.options, fn));
2858
+ lines.push(` return`);
2859
+ lines.push(` end`);
2860
+ if (visibleSubs.length > 0) for (const s of getSubNamesWithAliases(sub.subcommands)) {
2861
+ const desc = escapeDesc$1(s.description ?? "");
2862
+ lines.push(` echo "${s.name}\t${desc}"`);
2863
+ }
2864
+ else if (sub.positionals.length > 0) lines.push(...positionalBlock$1(sub.positionals, fn, sub.options));
2865
+ lines.push(`end`);
2866
+ lines.push(``);
2867
+ return lines;
2868
+ }
2869
+ /** Generate opt-takes-value entries for fish switch cases */
2870
+ function optTakesValueCases(sub, parentPath) {
2871
+ const lines = [];
2872
+ for (const row of walkOptTakesValueRows(sub, parentPath)) {
2873
+ const patterns = row.tokens.map((t) => `"${row.parentPath}:${t}"`);
2874
+ lines.push(` case ${patterns.join(" ")}`);
2875
+ lines.push(` return 0`);
2876
+ }
2877
+ return lines;
2878
+ }
2879
+ function generateFishCompletion(command, options) {
2880
+ const { programName } = options;
2881
+ const data = extractCompletionData(command, programName, options.globalArgsSchema);
2882
+ const fn = sanitize(programName);
2883
+ const root = data.command;
2884
+ const visibleSubs = getVisibleSubs(root.subcommands);
2885
+ const expandSpecs = collectExpandSpecs(root);
2886
+ const trackedFields = collectTrackedFields(root, expandSpecs, data.globalOptions);
2887
+ const hasExpand = expandSpecs.length > 0;
2888
+ const arrayExpandSpecs = expandSpecs.filter((s) => s.isArrayOption);
2889
+ const hasArrayExpand = arrayExpandSpecs.length > 0;
2890
+ const lines = [];
2891
+ lines.push(...buildHeaderLines({
2892
+ programName,
2893
+ shell: "fish",
2894
+ binPath: options.binPath,
2895
+ programVersion: options.programVersion
2896
+ }));
2897
+ lines.push(`# Generated by politty`);
2898
+ lines.push(``);
2899
+ const sig = computeBinSig(resolveBinPath(programName, options.binPath));
2900
+ const refreshFn = `__${fn}_refresh_completion`;
2901
+ lines.push(`function ${refreshFn} --no-scope-shadowing`);
2902
+ lines.push(` set -l _bin (command -v ${programName})`);
2903
+ lines.push(` test -z "$_bin"; and return 1`);
2904
+ lines.push(` set -l _sig (stat -L -c '%Y' "$_bin" 2>/dev/null; or stat -L -f '%m' "$_bin" 2>/dev/null)`);
2905
+ lines.push(` test "$_sig" = "${sig}"; and return 1`);
2906
+ lines.push(` set -l _target (status current-filename)`);
2907
+ lines.push(` test -n "$_target"; and test -f "$_target"; or return 1`);
2908
+ lines.push(` "$_bin" __refresh-completion fish "$_target" 2>/dev/null`);
2909
+ lines.push(` and source "$_target" 2>/dev/null`);
2910
+ lines.push(` and return 0`);
2911
+ lines.push(` return 1`);
2912
+ lines.push(`end`);
2913
+ lines.push(`${refreshFn}`);
2914
+ lines.push(`set -l _politty_refreshed $status`);
2915
+ lines.push(`functions -e ${refreshFn}`);
2916
+ lines.push(`test $_politty_refreshed -eq 0; and return`);
2917
+ lines.push(``);
2918
+ if (hasDynamicCompletion(root)) {
2919
+ lines.push(`function __${fn}_invoke_complete`);
2920
+ lines.push(` set -l _shell $argv[1]`);
2921
+ lines.push(` set -l _argv $argv[2..]`);
2922
+ lines.push(` set -l _bin ${programName}`);
2923
+ lines.push(` if set -q ${binEnvVarName(fn)}`);
2924
+ lines.push(` set _bin $${binEnvVarName(fn)}`);
2925
+ lines.push(` end`);
2926
+ lines.push(` $_bin __complete --shell $_shell -- $_argv 2>/dev/null`);
2927
+ lines.push(`end`);
2928
+ lines.push(``);
2929
+ lines.push(`function __${fn}_apply_dynamic_output`);
2930
+ lines.push(` set -l _cur $argv[1]`);
2931
+ lines.push(` set -l _directive 0`);
2932
+ lines.push(` set -l _emitted 0`);
2933
+ lines.push(` set -l _prev ""`);
2934
+ lines.push(` set -l _has_prev 0`);
2935
+ lines.push(` while read -l _l`);
2936
+ lines.push(` if test $_has_prev -eq 1`);
2937
+ lines.push(` if test -n "$_prev"`);
2938
+ lines.push(` printf '%s\\n' "$_prev"`);
2939
+ lines.push(` set _emitted 1`);
2940
+ lines.push(` end`);
2941
+ lines.push(` end`);
2942
+ lines.push(` set _prev $_l`);
2943
+ lines.push(` set _has_prev 1`);
2944
+ lines.push(` end`);
2945
+ lines.push(` if test $_has_prev -eq 1`);
2946
+ lines.push(` if string match -qr '^:[0-9]+$' -- $_prev`);
2947
+ lines.push(` set _directive (string sub -s 2 -- $_prev)`);
2948
+ lines.push(` else`);
2949
+ lines.push(` if test -n "$_prev"`);
2950
+ lines.push(` printf '%s\\n' "$_prev"`);
2951
+ lines.push(` set _emitted 1`);
2952
+ lines.push(` end`);
2953
+ lines.push(` end`);
2954
+ lines.push(` end`);
2955
+ lines.push(` if test (math "bitand($_directive, ${CompletionDirective.DirectoryCompletion})") -ne 0`);
2956
+ lines.push(` __fish_complete_directories "$_cur"`);
2957
+ lines.push(` else if test (math "bitand($_directive, ${CompletionDirective.FileCompletion})") -ne 0`);
2958
+ lines.push(` __fish_complete_path "$_cur"`);
2959
+ lines.push(` else if test $_emitted -eq 0; and test (math "bitand($_directive, ${CompletionDirective.NoFileCompletion})") -eq 0`);
2960
+ lines.push(` __fish_complete_path "$_cur"`);
2961
+ lines.push(` end`);
2962
+ lines.push(`end`);
2963
+ lines.push(``);
2964
+ }
2965
+ lines.push(`function __${fn}_not_used --no-scope-shadowing`);
2966
+ lines.push(` for _chk in $argv`);
2967
+ lines.push(` if contains -- "$_chk" $_used_opts`);
2968
+ lines.push(` return 1`);
2969
+ lines.push(` end`);
2970
+ lines.push(` end`);
2971
+ lines.push(` return 0`);
2972
+ lines.push(`end`);
2973
+ lines.push(``);
2974
+ lines.push(`function __${fn}_opt_takes_value`);
2975
+ lines.push(` switch "$argv[1]:$argv[2]"`);
2976
+ lines.push(...optTakesValueCases(root, ""));
2977
+ lines.push(` end`);
2978
+ lines.push(` return 1`);
2979
+ lines.push(`end`);
2980
+ lines.push(``);
2981
+ if (hasExpand) {
2982
+ const trackerVar = (t) => `${t.isGlobal ? "_global_arg_values_" : "_arg_values_"}${sanitize(t.fieldName)}`;
2983
+ lines.push(`function __${fn}_track_opt --no-scope-shadowing`);
2984
+ lines.push(` switch "$argv[1]:$argv[2]"`);
2985
+ for (const t of trackedFields) {
2986
+ if (t.isPositional || !t.optionTokens || t.optionTokens.length === 0) continue;
2987
+ const cases = t.pathStrs.flatMap((p) => t.optionTokens.map((n) => `"${p}:${n}"`)).join(" ");
2988
+ lines.push(` case ${cases}`);
2989
+ lines.push(` set -g ${trackerVar(t)} "$argv[3]"`);
2990
+ }
2991
+ lines.push(` end`);
2992
+ lines.push(`end`);
2993
+ lines.push(``);
2994
+ lines.push(`function __${fn}_track_pos --no-scope-shadowing`);
2995
+ lines.push(` switch "$argv[1]:$argv[2]"`);
2996
+ for (const t of trackedFields) {
2997
+ if (!t.isPositional) continue;
2998
+ const cases = t.pathStrs.map((p) => `"${p}:${t.position}"`).join(" ");
2999
+ lines.push(` case ${cases}`);
3000
+ lines.push(` set -g ${trackerVar(t)} "$argv[3]"`);
3001
+ }
3002
+ lines.push(` end`);
3003
+ lines.push(`end`);
3004
+ lines.push(``);
3005
+ }
3006
+ if (hasArrayExpand) {
3007
+ lines.push(`function __${fn}_track_array_expand --no-scope-shadowing`);
3008
+ lines.push(` switch "$argv[1]:$argv[2]"`);
3009
+ for (const spec of arrayExpandSpecs) {
3010
+ if (spec.optionTokens.length === 0) continue;
3011
+ const cases = spec.pathStrs.flatMap((p) => spec.optionTokens.map((tok) => `"${p}:${tok}"`)).join(" ");
3012
+ const bucket = sanitize(spec.fieldName);
3013
+ const bucketVar = spec.isGlobal ? `_global_used_field_keys_` : `_used_field_keys_`;
3014
+ lines.push(` case ${cases}`);
3015
+ lines.push(` if string match -q '*=*' -- "$argv[3]"`);
3016
+ lines.push(` set -l _k (string replace -r '=.*' '' -- "$argv[3]")`);
3017
+ lines.push(` if test -n "$_k"`);
3018
+ if (spec.isGlobal) {
3019
+ lines.push(` if not set -q _global_arr_seen_${bucket}`);
3020
+ lines.push(` set -g ${bucketVar}${bucket} "$_k"`);
3021
+ lines.push(` set -g _global_arr_seen_${bucket} 1`);
3022
+ lines.push(` else if not contains -- "$_k" $${bucketVar}${bucket}`);
3023
+ lines.push(` set -ga ${bucketVar}${bucket} "$_k"`);
3024
+ lines.push(` end`);
3025
+ } else {
3026
+ lines.push(` if not contains -- "$_k" $${bucketVar}${bucket}`);
3027
+ lines.push(` set -ga ${bucketVar}${bucket} "$_k"`);
3028
+ lines.push(` end`);
3029
+ }
3030
+ lines.push(` end`);
3031
+ lines.push(` end`);
3032
+ }
3033
+ lines.push(` end`);
3034
+ lines.push(`end`);
3035
+ lines.push(``);
3036
+ }
3037
+ const routeEntries = collectRouteEntries(root);
3038
+ if (routeEntries.length > 0) {
3039
+ lines.push(`function __${fn}_is_subcmd`);
3040
+ lines.push(` switch "$argv[1]:$argv[2]"`);
3041
+ for (const r of routeEntries) {
3042
+ lines.push(` case "${r.lookupPattern}"`);
3043
+ lines.push(` return 0`);
3044
+ }
3045
+ lines.push(` end`);
3046
+ lines.push(` return 1`);
3047
+ lines.push(`end`);
3048
+ lines.push(``);
3049
+ }
3050
+ for (const sub of visibleSubs) lines.push(...generateSubHandler$1(sub, fn, []));
3051
+ lines.push(`function __${fn}_complete_root --no-scope-shadowing`);
3052
+ lines.push(...optionValueCases$1(root.options, root.positionals, fn));
3053
+ lines.push(` if __${fn}_opt_takes_value "" "$_prev"; return; end`);
3054
+ if (root.positionals.length > 0) {
3055
+ lines.push(` if test $_after_dd -eq 1`);
3056
+ lines.push(...positionalBlock$1(root.positionals, fn, root.options).map((l) => ` ${l}`));
3057
+ lines.push(` return`);
3058
+ lines.push(` end`);
3059
+ } else lines.push(` if test $_after_dd -eq 1; return; end`);
3060
+ lines.push(` if string match -q -- '-*' "$_cur"`);
3061
+ lines.push(...availableOptionLines$1(root.options, fn));
3062
+ if (visibleSubs.length > 0) {
3063
+ lines.push(` else`);
3064
+ for (const s of getSubNamesWithAliases(root.subcommands)) {
3065
+ const desc = escapeDesc$1(s.description ?? "");
3066
+ lines.push(` echo "${s.name}\t${desc}"`);
3067
+ }
3068
+ } else if (root.positionals.length > 0) {
3069
+ lines.push(` else`);
3070
+ lines.push(...positionalBlock$1(root.positionals, fn, root.options));
3071
+ }
3072
+ lines.push(` end`);
3073
+ lines.push(`end`);
3074
+ lines.push(``);
3075
+ lines.push(`function __fish_${fn}_complete`);
3076
+ lines.push(` set -l _args (commandline -opc)`);
3077
+ lines.push(` set -e _args[1]`);
3078
+ lines.push(``);
3079
+ lines.push(` set -l _ct (commandline -ct)`);
3080
+ lines.push(` if test (count $_ct) -eq 0`);
3081
+ lines.push(` set -a _args ""`);
3082
+ lines.push(` else`);
3083
+ lines.push(` set -a _args $_ct`);
3084
+ lines.push(` end`);
3085
+ lines.push(``);
3086
+ lines.push(` set -l _cur ""`);
3087
+ lines.push(` if test (count $_args) -gt 0`);
3088
+ lines.push(` set _cur "$_args[-1]"`);
3089
+ lines.push(` end`);
3090
+ lines.push(``);
3091
+ lines.push(` set -l _prev ""`);
3092
+ lines.push(` if test (count $_args) -gt 1`);
3093
+ lines.push(` set _prev "$_args[-2]"`);
3094
+ lines.push(` end`);
3095
+ lines.push(``);
3096
+ lines.push(` set -l _subcmd "" ; set -l _after_dd 0 ; set -l _pos_count 0 ; set -l _skip_next 0`);
3097
+ lines.push(` set -l _used_opts`);
3098
+ lines.push(``);
3099
+ if (hasExpand) for (const t of trackedFields) {
3100
+ lines.push(` set -e _arg_values_${sanitize(t.fieldName)}`);
3101
+ lines.push(` set -e _global_arg_values_${sanitize(t.fieldName)}`);
3102
+ }
3103
+ if (hasArrayExpand) for (const spec of arrayExpandSpecs) {
3104
+ lines.push(` set -e _used_field_keys_${sanitize(spec.fieldName)}`);
3105
+ lines.push(` set -e _global_used_field_keys_${sanitize(spec.fieldName)}`);
3106
+ lines.push(` set -e _global_arr_seen_${sanitize(spec.fieldName)}`);
3107
+ }
3108
+ lines.push(` set -l _j 1`);
3109
+ lines.push(` set -l _limit (math (count $_args) - 1)`);
3110
+ lines.push(` while test $_j -le $_limit`);
3111
+ lines.push(` set -l _w "$_args[$_j]"`);
3112
+ lines.push(` if test $_skip_next -eq 1; set _skip_next 0; set _j (math $_j + 1); continue; end`);
3113
+ lines.push(` if test "$_w" = "--"; set _after_dd 1; set _j (math $_j + 1); continue; end`);
3114
+ const afterDdTrack = hasExpand ? `__${fn}_track_pos "$_subcmd" "$_pos_count" "$_w"; ` : "";
3115
+ lines.push(` if test $_after_dd -eq 1; ${afterDdTrack}set _pos_count (math $_pos_count + 1); set _j (math $_j + 1); continue; end`);
3116
+ lines.push(` if string match -q -- '-*=*' "$_w"`);
3117
+ lines.push(` set -l _opt (string replace -r '=.*' '' -- "$_w")`);
3118
+ lines.push(` set -a _used_opts "$_opt"`);
3119
+ if (hasExpand) {
3120
+ lines.push(` set -l _val (string replace -r '^[^=]*=' '' -- "$_w")`);
3121
+ lines.push(` __${fn}_track_opt "$_subcmd" "$_opt" "$_val"`);
3122
+ if (hasArrayExpand) lines.push(` __${fn}_track_array_expand "$_subcmd" "$_opt" "$_val"`);
3123
+ }
3124
+ lines.push(` set _j (math $_j + 1); continue`);
3125
+ lines.push(` end`);
3126
+ lines.push(` if string match -q -- '-*' "$_w"`);
3127
+ lines.push(` set -a _used_opts "$_w"`);
3128
+ lines.push(` if __${fn}_opt_takes_value "$_subcmd" "$_w"`);
3129
+ lines.push(` set -l _next ""`);
3130
+ lines.push(` set -l _next_idx (math $_j + 1)`);
3131
+ lines.push(` if test $_next_idx -le (count $_args)`);
3132
+ lines.push(` set _next "$_args[$_next_idx]"`);
3133
+ lines.push(` end`);
3134
+ lines.push(` if test -n "$_next"; and not string match -q -- '-*' "$_next"`);
3135
+ lines.push(` set _skip_next 1`);
3136
+ if (hasExpand) {
3137
+ lines.push(` __${fn}_track_opt "$_subcmd" "$_w" "$_next"`);
3138
+ if (hasArrayExpand) {
3139
+ lines.push(` if test $_j -lt $_limit`);
3140
+ lines.push(` __${fn}_track_array_expand "$_subcmd" "$_w" "$_next"`);
3141
+ lines.push(` end`);
3142
+ }
3143
+ }
3144
+ lines.push(` end`);
3145
+ lines.push(` end`);
3146
+ lines.push(` set _j (math $_j + 1); continue`);
3147
+ lines.push(` end`);
3148
+ if (routeEntries.length > 0) {
3149
+ lines.push(` if __${fn}_is_subcmd "$_subcmd" "$_w"`);
3150
+ lines.push(` test -n "$_subcmd"; and set _subcmd "$_subcmd:$_w"; or set _subcmd "$_w"`);
3151
+ lines.push(` set _used_opts; set _pos_count 0`);
3152
+ if (hasExpand) {
3153
+ for (const t of trackedFields) lines.push(` set -e _arg_values_${sanitize(t.fieldName)}`);
3154
+ if (hasArrayExpand) for (const spec of arrayExpandSpecs) {
3155
+ lines.push(` set -e _used_field_keys_${sanitize(spec.fieldName)}`);
3156
+ lines.push(` set -e _global_arr_seen_${sanitize(spec.fieldName)}`);
3157
+ }
3158
+ }
3159
+ lines.push(` else`);
3160
+ if (hasExpand) lines.push(` __${fn}_track_pos "$_subcmd" "$_pos_count" "$_w"`);
3161
+ lines.push(` set _pos_count (math $_pos_count + 1)`);
3162
+ lines.push(` end`);
3163
+ } else {
3164
+ if (hasExpand) lines.push(` __${fn}_track_pos "$_subcmd" "$_pos_count" "$_w"`);
3165
+ lines.push(` set _pos_count (math $_pos_count + 1)`);
3166
+ }
3167
+ lines.push(` set _j (math $_j + 1)`);
3168
+ lines.push(` end`);
3169
+ lines.push(``);
3170
+ lines.push(` switch "$_subcmd"`);
3171
+ for (const r of routeEntries) lines.push(` case "${r.pathStr}"; __${fn}_complete_${r.funcSuffix}`);
3172
+ lines.push(` case '*'; __${fn}_complete_root`);
3173
+ lines.push(` end`);
3174
+ lines.push(`end`);
3175
+ lines.push(``);
3176
+ lines.push(`# Clear existing completions`);
3177
+ lines.push(`complete -e -c ${programName}`);
3178
+ lines.push(``);
3179
+ lines.push(`# Register completion`);
3180
+ lines.push(`complete -c ${programName} -f -a '(__fish_${fn}_complete)'`);
3181
+ lines.push(``);
3182
+ return {
3183
+ script: lines.join("\n"),
3184
+ shell: "fish",
3185
+ installInstructions: `# To enable auto-refreshing fish completions, run:
3186
+ ${programName} completion fish --install`
3187
+ };
3188
+ }
3189
+
3190
+ //#endregion
3191
+ //#region src/completion/loader.ts
3192
+ /**
3193
+ * Rc-loader generators (bash / zsh).
3194
+ *
3195
+ * These produce the small snippet a user adds once to `~/.bashrc` or
3196
+ * `~/.zshrc`. The snippet:
3197
+ *
3198
+ * 1. Looks up the binary on $PATH.
3199
+ * 2. Reads its mtime.
3200
+ * 3. If the on-disk completion cache is missing or its
3201
+ * `# politty-bin-sig:` header differs, regenerates the cache by
3202
+ * spawning the binary once.
3203
+ * 4. Sources the cache.
3204
+ *
3205
+ * All failure modes are silent no-ops so a broken / missing CLI never
3206
+ * blocks shell startup.
3207
+ */
3208
+ /**
3209
+ * Single-quote escape: `'` -> `'\''`. Inside single quotes the shell
3210
+ * performs no expansion at all, so `$`, backticks, and `$(...)` are
3211
+ * inert. Used for hardcoded paths because callers may sources them
3212
+ * from env / config — we must not let metachars in the path execute as
3213
+ * commands when the rc snippet is sourced.
3214
+ */
3215
+ function shSingleQuote$1(s) {
3216
+ return `'${s.replace(/'/g, "'\\''")}'`;
3217
+ }
3218
+ function bashCachePathExpr(programName, cacheDir, shell) {
3219
+ if (cacheDir) return shSingleQuote$1(`${cacheDir}/completion.${shell}`);
3220
+ return `"\${XDG_CACHE_HOME:-$HOME/.cache}/${programName}/completion.${shell}"`;
3221
+ }
3222
+ function generateBashLoader(opts) {
3223
+ const fn = sanitize(opts.programName);
3224
+ const cache = bashCachePathExpr(opts.programName, opts.cacheDir, "bash");
3225
+ return `__${fn}_load_completion() {
3226
+ local _bin _cache _sig _hdr
3227
+ _bin=$(type -P ${opts.programName} 2>/dev/null)
3228
+ [[ -n "$_bin" ]] || return 0
3229
+ _cache=${cache}
3230
+ _sig=$(stat -L -c '%Y' "$_bin" 2>/dev/null || stat -L -f '%m' "$_bin" 2>/dev/null) || return 0
3231
+ _hdr="# politty-bin-sig: $_sig"
3232
+ if [[ ! -f "$_cache" ]] || ! head -5 "$_cache" 2>/dev/null | grep -qF "$_hdr"; then
3233
+ # Use the hidden __refresh-completion subcommand instead of
3234
+ # \`$_bin completion bash\`: the foreground completion command
3235
+ # is subject to user setup/cleanup/prompt and required
3236
+ # globalArgs validation, which can silently fail or block when
3237
+ # invoked from rc; runMain bypasses those for __-prefixed
3238
+ # internal subcommands.
3239
+ "$_bin" __refresh-completion bash 2>/dev/null
3240
+ fi
3241
+ # If regen failed but a stale cache survived from a previous run,
3242
+ # source it anyway — a stale completion is preferable to no
3243
+ # completion at all.
3244
+ [[ -f "$_cache" ]] || return 0
3245
+ # shellcheck disable=SC1090
3246
+ source "$_cache"
3247
+ }
3248
+ __${fn}_load_completion
3249
+ unset -f __${fn}_load_completion
3250
+ `;
3251
+ }
3252
+ function generateZshLoader(opts) {
3253
+ const fn = sanitize(opts.programName);
3254
+ const cache = bashCachePathExpr(opts.programName, opts.cacheDir, "zsh");
3255
+ return `__${fn}_load_completion() {
3256
+ emulate -L zsh
3257
+ setopt local_options no_aliases
3258
+ local _bin _cache _sig _hdr
3259
+ _bin=$(whence -p ${opts.programName} 2>/dev/null)
3260
+ [[ -n "$_bin" ]] || return 0
3261
+ _cache=${cache}
3262
+ _sig=$(stat -L -c '%Y' "$_bin" 2>/dev/null || stat -L -f '%m' "$_bin" 2>/dev/null) || return 0
3263
+ _hdr="# politty-bin-sig: $_sig"
3264
+ if [[ ! -f "$_cache" ]] || ! head -5 "$_cache" 2>/dev/null | grep -qF "$_hdr"; then
3265
+ # See bash loader for why we use __refresh-completion instead
3266
+ # of \`$_bin completion zsh\`.
3267
+ "$_bin" __refresh-completion zsh 2>/dev/null
3268
+ fi
3269
+ # See bash loader: keep stale completion over no completion.
3270
+ [[ -f "$_cache" ]] || return 0
3271
+ source "$_cache"
3272
+ }
3273
+ __${fn}_load_completion
3274
+ unfunction __${fn}_load_completion
3275
+ `;
3276
+ }
3277
+ /**
3278
+ * Build the rc-loader snippet for bash or zsh. Fish doesn't have an
3279
+ * rc-loader; instead, `<program> completion fish --install` writes a
3280
+ * self-rewriting autoload file.
3281
+ */
3282
+ function generateLoader(opts) {
3283
+ switch (opts.shell) {
3284
+ case "bash": return generateBashLoader(opts);
3285
+ case "zsh": return generateZshLoader(opts);
3286
+ 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.");
3287
+ }
3288
+ }
3289
+ /**
3290
+ * Default cache file path (used by `completion <bash|zsh> --install`
3291
+ * and the `__refresh-completion` subcommand). For fish, the install
3292
+ * path is `$__fish_config_dir/completions/<program>.fish` and is
3293
+ * computed inside `installPath()` instead.
3294
+ */
3295
+ function defaultCacheDir(programName) {
3296
+ return `${process.env.XDG_CACHE_HOME ?? `${process.env.HOME ?? ""}/.cache`}/${programName}`;
3297
+ }
3298
+
3299
+ //#endregion
3300
+ //#region src/completion/install.ts
3301
+ /**
3302
+ * On-disk install + refresh helpers.
3303
+ *
3304
+ * `install` writes the generated script to its canonical cache /
3305
+ * autoload path. `refresh` is the body of the `__refresh-completion`
3306
+ * hidden subcommand and the runMain background hook — it regenerates
3307
+ * the cache only when the binary's mtime no longer matches the
3308
+ * embedded `# politty-bin-sig:` header.
3309
+ *
3310
+ * All file I/O is best-effort: failures fall through silently. A stale
3311
+ * (or missing) cache is preferable to crashing the user's shell.
3312
+ */
3313
+ /**
3314
+ * Resolve where a script for the given shell should live on disk.
3315
+ *
3316
+ * - bash/zsh: `<cacheDir>/completion.<shell>` — sourced by the rc loader.
3317
+ * - fish: `$__fish_config_dir/completions/<program>.fish` — autoloaded
3318
+ * by fish on TAB. We approximate `$__fish_config_dir` from
3319
+ * `$XDG_CONFIG_HOME` / `$HOME`.
3320
+ */
3321
+ function installPath(programName, shell, cacheDir) {
3322
+ if (shell === "fish") return (0, node_path.join)(process.env.XDG_CONFIG_HOME ?? `${process.env.HOME ?? ""}/.config`, "fish", "completions", `${programName}.fish`);
3323
+ return (0, node_path.join)(cacheDir ?? defaultCacheDir(programName), `completion.${shell}`);
3324
+ }
3325
+ /** Atomic write: tmp file in the same dir, then rename. */
3326
+ function writeAtomic(path, content) {
3327
+ (0, node_fs.mkdirSync)((0, node_path.dirname)(path), { recursive: true });
3328
+ const tmp = `${path}.tmp.${process.pid}`;
3329
+ (0, node_fs.writeFileSync)(tmp, content);
3330
+ (0, node_fs.renameSync)(tmp, path);
3331
+ }
3332
+ function generateScript(ctx, shell) {
3333
+ return generateCompletion(ctx.rootCommand, {
3334
+ shell,
3335
+ programName: ctx.programName,
3336
+ includeDescriptions: true,
3337
+ ...ctx.programVersion !== void 0 && { programVersion: ctx.programVersion },
3338
+ ...ctx.binPath !== void 0 && { binPath: ctx.binPath },
3339
+ ...ctx.cacheDir !== void 0 && { cacheDir: ctx.cacheDir },
3340
+ ...ctx.globalArgsSchema !== void 0 && { globalArgsSchema: ctx.globalArgsSchema }
3341
+ }).script;
3342
+ }
3343
+ /** Write the script for `shell` to its install path. Returns the path. */
3344
+ function install(ctx, shell) {
3345
+ const target = installPath(ctx.programName, shell, ctx.cacheDir);
3346
+ writeAtomic(target, generateScript(ctx, shell));
3347
+ return target;
3348
+ }
3349
+ /**
3350
+ * Read the first ~5 lines of an existing cache file and return its
3351
+ * embedded bin-sig. Returns `null` when the file is missing, unreadable,
3352
+ * or doesn't have a sig header.
3353
+ */
3354
+ function readCachedSig(path) {
3355
+ try {
3356
+ if (!(0, node_fs.existsSync)(path)) return null;
3357
+ const m = (0, node_fs.readFileSync)(path, "utf8").split("\n", 6).join("\n").match(/^# politty-bin-sig: (\S+)/m);
3358
+ return m ? m[1] : null;
3359
+ } catch {
3360
+ return null;
3361
+ }
3362
+ }
3363
+ function isManagedTarget(path, programName, shell) {
3364
+ try {
3365
+ if (!(0, node_fs.existsSync)(path)) return false;
3366
+ const head = (0, node_fs.readFileSync)(path, "utf8").split("\n", 8).join("\n");
3367
+ return /^# politty-completion-version: \S+/m.test(head) && head.includes(`# program: ${programName}`) && head.includes(`# shell: ${shell}`);
3368
+ } catch {
3369
+ return false;
3370
+ }
3371
+ }
3372
+ /**
3373
+ * Rewrite the cache only when stale. Used by:
3374
+ * - `<program> __refresh-completion <shell>` (the hidden subcommand
3375
+ * spawned both by the rc loader and by the runMain background hook)
3376
+ *
3377
+ * Caller is responsible for gating: the runMain hook (`maybeSpawnRefresh`)
3378
+ * checks `hasManagedCache` before spawning so we don't silently create
3379
+ * a fish autoload the user never opted into. The rc loader / fish
3380
+ * autoload only run after the user has installed completion in the
3381
+ * first place, so they're allowed to refresh unconditionally.
3382
+ *
3383
+ * Must never throw — a stale completion is fine, a crash isn't.
3384
+ */
3385
+ function refreshIfStale(ctx, shell) {
3386
+ try {
3387
+ const target = ctx.targetPath ? (0, node_fs.realpathSync)(ctx.targetPath) : installPath(ctx.programName, shell, ctx.cacheDir);
3388
+ if (ctx.targetPath && !isManagedTarget(target, ctx.programName, shell)) return;
3389
+ const binPath = resolveBinPath(ctx.programName, ctx.binPath);
3390
+ if (!binPath) return;
3391
+ let currentSig;
3392
+ try {
3393
+ currentSig = Math.floor((0, node_fs.statSync)(binPath).mtimeMs / 1e3).toString();
3394
+ } catch {
3395
+ return;
3396
+ }
3397
+ if (readCachedSig(target) === currentSig) return;
3398
+ writeAtomic(target, generateScript(ctx, shell));
3399
+ } catch {}
3400
+ }
3401
+ /**
3402
+ * Returns true when a politty-managed cache file already exists on disk
3403
+ * for the given shell — i.e. the user has installed completion via
3404
+ * `<program> completion <shell> --install` or the rc loader has already
3405
+ * sourced one. Used by the runMain background hook to avoid spawning
3406
+ * the refresher (and thereby silently creating files) on plain CLI runs
3407
+ * the user never opted into.
3408
+ */
3409
+ function hasManagedCache(ctx, shell) {
3410
+ return readCachedSig(installPath(ctx.programName, shell, ctx.cacheDir)) !== null;
3411
+ }
3412
+ /**
3413
+ * Spawn a detached child process that runs `<program> __refresh-completion <shell>`.
3414
+ * The child is fully decoupled (`stdio: "ignore"` + `unref()`), so it
3415
+ * outlives the parent without holding any handles.
3416
+ *
3417
+ * Caller is expected to gate this on the right conditions (interactive
3418
+ * shell, not running inside `__complete` itself, etc.).
3419
+ *
3420
+ * Returns `void` and never throws — even spawn failures are absorbed.
3421
+ */
3422
+ function spawnBackgroundRefresh(programArgv0, shell) {
3423
+ try {
3424
+ (0, node_child_process.spawn)(process.execPath, [
3425
+ programArgv0,
3426
+ "__refresh-completion",
3427
+ shell
3428
+ ], {
3429
+ detached: true,
3430
+ stdio: "ignore"
3431
+ }).unref();
3432
+ } catch {}
3433
+ }
3434
+
3435
+ //#endregion
3436
+ //#region src/completion/zsh.ts
3437
+ function escapeDesc(s) {
3438
+ return s.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\$/g, "\\$").replace(/`/g, "\\`").replace(/:/g, "\\:");
3439
+ }
3440
+ /**
3441
+ * Escape a candidate value for use inside a `_describe` spec. `_describe`
3442
+ * splits each spec on the first unescaped `:` to separate value from
3443
+ * description, so any literal `:` in the value (URLs, namespaced ids) must
3444
+ * be backslash-escaped — and the escape itself must double up so the final
3445
+ * string interprets `\:` as a single literal.
3446
+ */
3447
+ function escapeDescribeValue(s) {
3448
+ return s.replace(/\\/g, "\\\\").replace(/:/g, "\\:");
3449
+ }
3450
+ /** Escape a string for use inside zsh double-quotes. */
3451
+ function escapeZshDQ(s) {
3452
+ return s.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\$/g, "\\$").replace(/`/g, "\\`");
3453
+ }
3454
+ /**
3455
+ * Generate zsh value completion lines for a ValueCompletion spec.
3456
+ * Uses `_vals` array (must be declared in the calling function scope).
3457
+ * `location` is required when `vc.type === "expand"`.
3458
+ */
3459
+ function zshValueLines(vc, fn, location) {
3460
+ if (!vc) return [];
3461
+ switch (vc.type) {
3462
+ case "expand": {
3463
+ if (!location) throw new Error("zshValueLines: expand variant requires a location");
3464
+ const varName = expandTableVarName(fn, location.funcSuffix, location.fieldName);
3465
+ const depKey = location.resolvedDeps.map((d) => d.isGlobal ? `"\${_global_arg_values[${d.name}]:-}"` : `"\${_arg_values[${d.name}]:-}"`).join(`$'\\x1f'`);
3466
+ const bucket = sanitize(location.fieldName);
3467
+ const bucketRef = location.isGlobal ? `\${_global_used_field_keys[${bucket}]:-}` : `\${_used_field_keys[${bucket}]:-}`;
3468
+ const arrayDedupLines = location.isArrayOption ? [` if [[ -n "$_ck" && " ${bucketRef} " == *" $_ck "* ]]; then continue; fi`] : [];
3469
+ return [
3470
+ `local _key=${depKey}`,
3471
+ `local _raw="\${${varName}[$_key]:-}"`,
3472
+ `if [[ -n "$_raw" ]]; then`,
3473
+ ` local -a _candidates=("\${(@f)_raw}")`,
3474
+ ` _vals=()`,
3475
+ ` local _c _ck _cke _vp _seen_keys=" " _desc _has_eq=0 _tmp`,
3476
+ ` for _c in "\${_candidates[@]}"; do`,
3477
+ ` _tmp="\${_c//\\\\:/$'\\x01'}"`,
3478
+ ` _vp="\${_tmp%%:*}"`,
3479
+ ` if [[ "$_vp" == *=* ]]; then`,
3480
+ ` _cke="\${_c%%=*}"`,
3481
+ ` _ck="\${_cke//\\\\:/:}"`,
3482
+ ...arrayDedupLines,
3483
+ ` if [[ "\${words[CURRENT]}" != *=* ]]; then`,
3484
+ ` [[ "$_seen_keys" == *" $_ck "* ]] && continue`,
3485
+ ` _seen_keys+="$_ck "`,
3486
+ ` if [[ "$_tmp" == *:* ]]; then`,
3487
+ ` _desc="\${\${_tmp#*:}//$'\\x01'/\\\\:}"`,
3488
+ ` _c="\${_cke}=:$_desc"`,
3489
+ ` else`,
3490
+ ` _c="\${_cke}="`,
3491
+ ` fi`,
3492
+ ` _has_eq=1`,
3493
+ ` else`,
3494
+ ` [[ "$_vp" == *=?* ]] || continue`,
3495
+ ` fi`,
3496
+ ` fi`,
3497
+ ` _vals+=("$_c")`,
3498
+ ` done`,
3499
+ ` if (( _has_eq )); then`,
3500
+ ` __${fn}_cdescribe 'completions' _vals -S ''`,
3501
+ ` else`,
3502
+ ` __${fn}_cdescribe 'completions' _vals`,
3503
+ ` fi`,
3504
+ `fi`
3505
+ ];
3506
+ }
3507
+ case "dynamic": return [`__${fn}_apply_dynamic_output "$(__${fn}_invoke_complete zsh "\${(@)words[2,CURRENT]}")"`];
3508
+ case "choices": return [`_vals=(${vc.choices.map((c) => `"${escapeDesc(c)}"`).join(" ")})`, `__${fn}_cdescribe 'completions' _vals`];
3509
+ case "file":
3510
+ if (vc.matcher?.length) return vc.matcher.map((p) => `_files -g "${p}"`);
3511
+ if (vc.extensions?.length) return vc.extensions.map((ext) => `_files -g "*.${ext}"`);
3512
+ return [`_files`];
3513
+ case "directory": return [`_files -/`];
3514
+ case "command": return [`_vals=("\${(@f)$(${vc.shellCommand})}")`, `__${fn}_cdescribe 'completions' _vals`];
3515
+ case "none": return [];
3516
+ }
3517
+ }
3518
+ /** Generate option-value case branches */
3519
+ function optionValueCases(options, positionals, fn, funcSuffix) {
3520
+ const lines = [];
3521
+ for (const opt of options) {
3522
+ if (!opt.takesValue || !opt.valueCompletion) continue;
3523
+ const valLines = zshValueLines(opt.valueCompletion, fn, {
3524
+ funcSuffix,
3525
+ ...optionExpandLocation(opt, options, positionals)
3526
+ });
3527
+ if (valLines.length === 0) continue;
3528
+ const patterns = effectiveOptionTokens(opt, options);
3529
+ if (patterns.length === 0) continue;
3530
+ lines.push(` ${patterns.join("|")})`);
3531
+ for (const vl of valLines) lines.push(` ${vl}`);
3532
+ lines.push(` return 0 ;;`);
3533
+ }
3534
+ return lines;
3535
+ }
3536
+ /** Generate positional completion block */
3537
+ function positionalBlock(positionals, fn, funcSuffix, options = []) {
3538
+ if (positionals.length === 0) return [];
3539
+ const lines = [];
3540
+ lines.push(` case "$_pos_count" in`);
3541
+ for (const pos of positionals) {
3542
+ if (pos.variadic) lines.push(` ${pos.position}|*)`);
3543
+ else lines.push(` ${pos.position})`);
3544
+ const valLines = zshValueLines(pos.valueCompletion, fn, {
3545
+ funcSuffix,
3546
+ ...positionalExpandLocation(pos, options, positionals)
3547
+ });
3548
+ for (const vl of valLines) lines.push(` ${vl}`);
3549
+ lines.push(` ;;`);
3550
+ }
3551
+ lines.push(` esac`);
3552
+ return lines;
3553
+ }
3554
+ /** Generate prev-word value completion case block */
3555
+ function valueCompletionBlock(options, positionals, fn, funcSuffix) {
3556
+ if (!options.some((o) => o.takesValue && o.valueCompletion)) return [];
3557
+ const prevCases = optionValueCases(options, positionals, fn, funcSuffix);
3558
+ if (prevCases.length === 0) return [];
3559
+ return [
3560
+ ` case "\${words[CURRENT-1]}" in`,
3561
+ ...prevCases,
3562
+ ` esac`
3563
+ ];
3564
+ }
3565
+ /** Generate available-options list lines */
3566
+ function availableOptionLines(options, fn) {
3567
+ const lines = [];
3568
+ for (const opt of options) {
3569
+ const desc = opt.description ? `:${escapeDesc(opt.description)}` : "";
3570
+ if (opt.valueType === "array") {
3571
+ lines.push(` _opts+=("--${opt.cliName}${desc}")`);
3572
+ continue;
3573
+ }
3574
+ const patterns = quotedAvailabilityTokens(opt.cliName, opt.alias, opt.negation, {
3575
+ isGlobal: opt.isGlobal === true,
3576
+ frameOptions: options
3577
+ });
3578
+ const guard = `__${fn}_not_used ${patterns.join(" ")}`;
3579
+ const negDesc = opt.negationDescription ? `:${escapeDesc(opt.negationDescription)}` : desc;
3580
+ const entries = [{
3581
+ name: opt.cliName,
3582
+ desc
3583
+ }];
3584
+ if (opt.negation) entries.push({
3585
+ name: opt.negation,
3586
+ desc: negDesc
3587
+ });
3588
+ for (const e of entries) {
3589
+ if (!patterns.includes(`"--${e.name}"`)) continue;
3590
+ lines.push(` ${guard} && _opts+=("--${e.name}${e.desc}")`);
3591
+ }
3592
+ }
3593
+ lines.push(` __${fn}_not_used "--help" && _opts+=("--help:Show help")`);
3594
+ return lines;
3595
+ }
3596
+ /**
3597
+ * Generate a per-subcommand completion function.
3598
+ * Recursively generates functions for nested subcommands.
3599
+ */
3600
+ function generateSubHandler(sub, fn, path) {
3601
+ const fullPath = [...path, sub.name];
3602
+ const funcSuffix = fullPath.map(sanitize).join("_");
3603
+ const funcName = `__${fn}_complete_${funcSuffix}`;
3604
+ const visibleSubs = getVisibleSubs(sub.subcommands);
3605
+ const lines = [];
3606
+ for (const child of visibleSubs) lines.push(...generateSubHandler(child, fn, fullPath));
3607
+ lines.push(`${funcName}() {`);
3608
+ lines.push(` local -a _vals=()`);
3609
+ lines.push(...valueCompletionBlock(sub.options, sub.positionals, fn, funcSuffix));
3610
+ const fullPathStr = fullPath.join(":");
3611
+ lines.push(` if __${fn}_opt_takes_value "${fullPathStr}" "\${words[CURRENT-1]}"; then return 0; fi`);
3612
+ if (sub.positionals.length > 0) {
3613
+ lines.push(` if (( _after_dd )); then`);
3614
+ lines.push(...positionalBlock(sub.positionals, fn, funcSuffix, sub.options).map((l) => ` ${l}`));
3615
+ lines.push(` return 0`);
3616
+ lines.push(` fi`);
3617
+ } else lines.push(` if (( _after_dd )); then return 0; fi`);
3618
+ lines.push(` if [[ "\${words[CURRENT]}" == -* ]]; then`);
3619
+ lines.push(` local -a _opts=()`);
3620
+ lines.push(...availableOptionLines(sub.options, fn));
3621
+ lines.push(` __${fn}_cdescribe 'options' _opts`);
3622
+ lines.push(` return 0`);
3623
+ lines.push(` fi`);
3624
+ if (visibleSubs.length > 0) {
3625
+ const subItems = getSubNamesWithAliases(sub.subcommands).map((s) => {
3626
+ const desc = s.description ? `:${escapeDesc(s.description)}` : "";
3627
+ return `"${s.name}${desc}"`;
3628
+ }).join(" ");
3629
+ lines.push(` local -a _subs=(${subItems})`);
3630
+ lines.push(` __${fn}_cdescribe 'subcommands' _subs`);
3631
+ } else if (sub.positionals.length > 0) lines.push(...positionalBlock(sub.positionals, fn, funcSuffix, sub.options));
3632
+ lines.push(`}`);
3633
+ lines.push(``);
3634
+ return lines;
3635
+ }
3636
+ function generateZshCompletion(command, options) {
3637
+ const { programName } = options;
3638
+ const data = extractCompletionData(command, programName, options.globalArgsSchema);
3639
+ const fn = sanitize(programName);
3640
+ const completionFn = `_${programName}`;
3641
+ const autoloadCheck = `"\${funcstack[1]:-}" == "${escapeZshDQ(completionFn)}"`;
3642
+ const root = data.command;
3643
+ const visibleSubs = getVisibleSubs(root.subcommands);
3644
+ const expandSpecs = collectExpandSpecs(root);
3645
+ const trackedFields = collectTrackedFields(root, expandSpecs, data.globalOptions);
3646
+ const hasExpand = expandSpecs.length > 0;
3647
+ const arrayExpandSpecs = expandSpecs.filter((s) => s.isArrayOption);
3648
+ const hasArrayExpand = arrayExpandSpecs.length > 0;
3649
+ const lines = [];
3650
+ lines.push(`#compdef ${programName}`);
3651
+ lines.push(``);
3652
+ lines.push(...buildHeaderLines({
3653
+ programName,
3654
+ shell: "zsh",
3655
+ binPath: options.binPath,
3656
+ programVersion: options.programVersion
3657
+ }));
3658
+ lines.push(`# Generated by politty`);
3659
+ lines.push(``);
3660
+ lines.push(...generateZshSelfRefresh({
3661
+ programName,
3662
+ binPath: options.binPath
3663
+ }));
3664
+ for (const spec of expandSpecs) {
3665
+ const varName = expandTableVarName(fn, spec.funcSuffix, spec.fieldName);
3666
+ if (spec.vc.table.length === 0) lines.push(`typeset -gA ${varName}=()`);
3667
+ else {
3668
+ lines.push(`typeset -gA ${varName}=(`);
3669
+ for (const entry of spec.vc.table) {
3670
+ const key = entry.key.join("");
3671
+ const value = entry.candidates.map((c) => {
3672
+ const escapedValue = escapeDescribeValue(c.value);
3673
+ return c.description ? `${escapedValue}:${c.description}` : escapedValue;
3674
+ }).join("\n");
3675
+ lines.push(` ${ansiC(key)} ${ansiC(value)}`);
3676
+ }
3677
+ lines.push(`)`);
3678
+ }
3679
+ lines.push(``);
3680
+ }
3681
+ if (hasDynamicCompletion(root)) {
3682
+ lines.push(...dynamicInvokeCompleteLines(fn, programName));
3683
+ lines.push(``);
3684
+ lines.push(`__${fn}_apply_dynamic_output() {`);
3685
+ lines.push(` local _raw="$1"`);
3686
+ lines.push(` local _directive=0`);
3687
+ lines.push(` local -a _vals _lines`);
3688
+ lines.push(` _lines=("\${(@f)_raw}")`);
3689
+ lines.push(` local _last=$#_lines`);
3690
+ lines.push(` if (( _last >= 1 )) && [[ "\${_lines[$_last]}" == :<-> ]]; then`);
3691
+ lines.push(` _directive="\${_lines[$_last]#:}"`);
3692
+ lines.push(` _lines[$_last]=()`);
3693
+ lines.push(` fi`);
3694
+ lines.push(` local _l`);
3695
+ lines.push(` for _l in "\${_lines[@]}"; do`);
3696
+ lines.push(` [[ -z "$_l" ]] && continue`);
3697
+ lines.push(` _vals+=("$_l")`);
3698
+ lines.push(` done`);
3699
+ lines.push(` if (( \${#_vals[@]} > 0 )); then`);
3700
+ lines.push(` if (( _directive & ${CompletionDirective.NoSpace} )); then`);
3701
+ lines.push(` __${fn}_cdescribe 'completions' _vals -S ''`);
3702
+ lines.push(` else`);
3703
+ lines.push(` __${fn}_cdescribe 'completions' _vals`);
3704
+ lines.push(` fi`);
3705
+ lines.push(` fi`);
3706
+ lines.push(` if (( _directive & ${CompletionDirective.DirectoryCompletion} )); then`);
3707
+ lines.push(` _files -/`);
3708
+ lines.push(` elif (( _directive & ${CompletionDirective.FileCompletion} )); then`);
3709
+ lines.push(` _files`);
3710
+ lines.push(` elif (( \${#_vals[@]} == 0 )) && ! (( _directive & ${CompletionDirective.NoFileCompletion} )); then`);
3711
+ lines.push(` _files`);
3712
+ lines.push(` fi`);
3713
+ lines.push(`}`);
3714
+ lines.push(``);
3715
+ }
3716
+ lines.push(`__${fn}_not_used() {`);
3717
+ lines.push(` local _u _chk`);
3718
+ lines.push(` for _u in "\${_used_opts[@]}"; do`);
3719
+ lines.push(` for _chk in "$@"; do`);
3720
+ lines.push(` [[ "$_u" == "$_chk" ]] && return 1`);
3721
+ lines.push(` done`);
3722
+ lines.push(` done`);
3723
+ lines.push(` return 0`);
3724
+ lines.push(`}`);
3725
+ lines.push(``);
3726
+ lines.push(`__${fn}_cdescribe() {`);
3727
+ lines.push(` _describe "$@" 2>/dev/null && return 0`);
3728
+ lines.push(` shift`);
3729
+ lines.push(` local _cd_arr="$1"`);
3730
+ lines.push(` shift`);
3731
+ lines.push(` local -a _cd_vals=("\${(@)\${(P)_cd_arr}%%:*}")`);
3732
+ lines.push(` compadd "$@" -a _cd_vals 2>/dev/null`);
3733
+ lines.push(` return 0`);
3734
+ lines.push(`}`);
3735
+ lines.push(``);
3736
+ lines.push(`__${fn}_opt_takes_value() {`);
3737
+ lines.push(` case "$1:$2" in`);
3738
+ lines.push(...optTakesValueEntries(root, ""));
3739
+ lines.push(` esac`);
3740
+ lines.push(` return 1`);
3741
+ lines.push(`}`);
3742
+ lines.push(``);
3743
+ if (hasExpand) {
3744
+ lines.push(`__${fn}_track_opt() {`);
3745
+ lines.push(` case "$1:$2" in`);
3746
+ lines.push(...trackOptCaseLines(trackedFields, "zsh"));
3747
+ lines.push(` esac`);
3748
+ lines.push(`}`);
3749
+ lines.push(``);
3750
+ lines.push(`__${fn}_track_pos() {`);
3751
+ lines.push(` case "$1:$2" in`);
3752
+ lines.push(...trackPosCaseLines(trackedFields, "zsh"));
3753
+ lines.push(` esac`);
3754
+ lines.push(`}`);
3755
+ lines.push(``);
3756
+ }
3757
+ if (hasArrayExpand) {
3758
+ lines.push(`__${fn}_track_array_expand() {`);
3759
+ lines.push(` case "$1:$2" in`);
3760
+ lines.push(...trackArrayExpandCaseLines(arrayExpandSpecs, "zsh"));
3761
+ lines.push(` esac`);
3762
+ lines.push(`}`);
3763
+ lines.push(``);
3764
+ }
3765
+ const routeEntries = collectRouteEntries(root);
3766
+ if (routeEntries.length > 0) {
3767
+ lines.push(`__${fn}_is_subcmd() {`);
3768
+ lines.push(` case "$1:$2" in`);
3769
+ lines.push(...isSubcmdCaseLines(routeEntries));
3770
+ lines.push(` esac`);
3771
+ lines.push(` return 1`);
3772
+ lines.push(`}`);
3773
+ lines.push(``);
3774
+ }
3775
+ for (const sub of visibleSubs) lines.push(...generateSubHandler(sub, fn, []));
3776
+ lines.push(`__${fn}_complete_root() {`);
3777
+ lines.push(` local -a _vals=()`);
3778
+ lines.push(...valueCompletionBlock(root.options, root.positionals, fn, "root"));
3779
+ lines.push(` if __${fn}_opt_takes_value "" "\${words[CURRENT-1]}"; then return 0; fi`);
3780
+ if (root.positionals.length > 0) {
3781
+ lines.push(` if (( _after_dd )); then`);
3782
+ lines.push(...positionalBlock(root.positionals, fn, "root", root.options).map((l) => ` ${l}`));
3783
+ lines.push(` return 0`);
3784
+ lines.push(` fi`);
3785
+ } else lines.push(` if (( _after_dd )); then return 0; fi`);
3786
+ lines.push(` if [[ "\${words[CURRENT]}" == -* ]]; then`);
3787
+ lines.push(` local -a _opts=()`);
3788
+ lines.push(...availableOptionLines(root.options, fn));
3789
+ lines.push(` __${fn}_cdescribe 'options' _opts`);
3790
+ if (visibleSubs.length > 0) {
3791
+ lines.push(` else`);
3792
+ const subItems = getSubNamesWithAliases(root.subcommands).map((s) => {
3793
+ const desc = s.description ? `:${escapeDesc(s.description)}` : "";
3794
+ return `"${s.name}${desc}"`;
3795
+ }).join(" ");
3796
+ lines.push(` local -a _subs=(${subItems})`);
3797
+ lines.push(` __${fn}_cdescribe 'subcommands' _subs`);
3798
+ } else if (root.positionals.length > 0) {
3799
+ lines.push(` else`);
3800
+ lines.push(...positionalBlock(root.positionals, fn, "root", root.options).map((l) => ` ${l}`));
3801
+ }
3802
+ lines.push(` fi`);
3803
+ lines.push(`}`);
3804
+ lines.push(``);
3805
+ const subRouting = subDispatchCaseLines(routeEntries, fn).join("\n");
3806
+ lines.push(`${completionFn}() {`);
3807
+ lines.push(` (( CURRENT )) || CURRENT=\${#words}`);
3808
+ lines.push(``);
3809
+ lines.push(` local _subcmd="" _after_dd=0 _pos_count=0 _skip_next=0`);
3810
+ lines.push(` local -a _used_opts=()`);
3811
+ if (hasExpand) {
3812
+ lines.push(` local -A _arg_values=()`);
3813
+ lines.push(` local -A _global_arg_values=()`);
3814
+ }
3815
+ if (hasArrayExpand) {
3816
+ lines.push(` local -A _used_field_keys=()`);
3817
+ lines.push(` local -A _global_used_field_keys=()`);
3818
+ lines.push(` local -A _global_arr_seen=()`);
3819
+ }
3820
+ lines.push(``);
3821
+ lines.push(` local _j=2`);
3822
+ lines.push(` while (( _j < CURRENT )); do`);
3823
+ lines.push(` local _w="\${words[_j]}"`);
3824
+ lines.push(` if (( _skip_next )); then _skip_next=0; (( _j++ )); continue; fi`);
3825
+ lines.push(` if [[ "$_w" == "--" ]]; then _after_dd=1; (( _j++ )); continue; fi`);
3826
+ const afterDdTrack = hasExpand ? `__${fn}_track_pos "$_subcmd" "$_pos_count" "$_w"; ` : "";
3827
+ lines.push(` if (( _after_dd )); then ${afterDdTrack}(( _pos_count++ )); (( _j++ )); continue; fi`);
3828
+ lines.push(` if [[ "$_w" == -*=* ]]; then`);
3829
+ lines.push(` _used_opts+=("\${_w%%=*}")`);
3830
+ if (hasExpand) {
3831
+ lines.push(` __${fn}_track_opt "$_subcmd" "\${_w%%=*}" "\${_w#*=}"`);
3832
+ if (hasArrayExpand) lines.push(` __${fn}_track_array_expand "$_subcmd" "\${_w%%=*}" "\${_w#*=}"`);
3833
+ }
3834
+ lines.push(` (( _j++ )); continue`);
3835
+ lines.push(` fi`);
3836
+ lines.push(` if [[ "$_w" == -* ]]; then`);
3837
+ lines.push(` _used_opts+=("$_w")`);
3838
+ lines.push(` if __${fn}_opt_takes_value "$_subcmd" "$_w"; then`);
3839
+ lines.push(` local _next="\${words[_j+1]:-}"`);
3840
+ lines.push(` if [[ -n "$_next" && "$_next" != -* ]]; then _skip_next=1; fi`);
3841
+ if (hasExpand) {
3842
+ lines.push(` if (( _skip_next )); then`);
3843
+ lines.push(` __${fn}_track_opt "$_subcmd" "$_w" "$_next"`);
3844
+ if (hasArrayExpand) {
3845
+ lines.push(` if (( _j + 1 < CURRENT )); then`);
3846
+ lines.push(` __${fn}_track_array_expand "$_subcmd" "$_w" "$_next"`);
3847
+ lines.push(` fi`);
3848
+ }
3849
+ lines.push(` fi`);
3850
+ }
3851
+ lines.push(` fi`);
3852
+ lines.push(` (( _j++ )); continue`);
3853
+ lines.push(` fi`);
3854
+ const clearState = hasArrayExpand ? `; _arg_values=(); _used_field_keys=(); _global_arr_seen=()` : hasExpand ? `; _arg_values=()` : "";
3855
+ const posTrack = hasExpand ? `__${fn}_track_pos "$_subcmd" "$_pos_count" "$_w"; ` : "";
3856
+ if (routeEntries.length > 0) lines.push(` if __${fn}_is_subcmd "$_subcmd" "$_w"; then _subcmd="\${_subcmd:+\${_subcmd}:}$_w"; _used_opts=(); _pos_count=0${clearState}; else ${posTrack}(( _pos_count++ )); fi`);
3857
+ else {
3858
+ if (hasExpand) lines.push(` __${fn}_track_pos "$_subcmd" "$_pos_count" "$_w"`);
3859
+ lines.push(` (( _pos_count++ ))`);
3860
+ }
3861
+ lines.push(` (( _j++ ))`);
3862
+ lines.push(` done`);
3863
+ lines.push(``);
3864
+ lines.push(` case "$_subcmd" in`);
3865
+ lines.push(subRouting);
3866
+ lines.push(` *) __${fn}_complete_root ;;`);
3867
+ lines.push(` esac`);
3868
+ lines.push(`}`);
3869
+ lines.push(``);
3870
+ lines.push(`zstyle ':completion:*:*:${programName}:*' file-patterns '%p:globbed-files *(-/):directories'`);
3871
+ lines.push(``);
3872
+ lines.push(`if [[ ${autoloadCheck} ]]; then`);
3873
+ lines.push(` ${completionFn} "$@"`);
3874
+ lines.push(`else`);
3875
+ lines.push(` compdef ${completionFn} ${programName}`);
3876
+ lines.push(`fi`);
3877
+ lines.push(``);
3878
+ return {
3879
+ script: lines.join("\n"),
3880
+ shell: "zsh",
3881
+ installInstructions: `# To enable auto-refreshing zsh completions, add this to your ~/.zshrc after compinit:
3882
+ eval "$(${programName} completion zsh)"
3883
+
3884
+ # For faster shell startup, save the script in your fpath:
3885
+ mkdir -p ~/.zsh/completions
3886
+ ${programName} completion zsh > ~/.zsh/completions/_${programName}
3887
+
3888
+ # Make sure your ~/.zshrc includes the fpath line before compinit:
3889
+ fpath=(~/.zsh/completions $fpath)
3890
+ autoload -Uz compinit && compinit
3891
+
3892
+ # If ~/.zshrc already calls compinit, add only the fpath line before
3893
+ # the existing compinit call.
3894
+
3895
+ # Then reload your shell or run:
3896
+ source ~/.zshrc`
3897
+ };
3898
+ }
3899
+
3900
+ //#endregion
3901
+ //#region src/completion/index.ts
3902
+ /**
3903
+ * Shell completion generation module
3904
+ *
3905
+ * Provides utilities to generate shell completion scripts for bash, zsh, and fish.
3906
+ *
3907
+ * @example
3908
+ * ```typescript
3909
+ * import { generateCompletion, createCompletionCommand } from "politty/completion";
3910
+ *
3911
+ * // Generate completion script directly
3912
+ * const result = generateCompletion(myCommand, {
3913
+ * shell: "bash",
3914
+ * programName: "mycli"
3915
+ * });
3916
+ * console.log(result.script);
3917
+ *
3918
+ * // Or add a completion subcommand to your CLI
3919
+ * const mainCommand = withCompletionCommand(
3920
+ * defineCommand({
3921
+ * name: "mycli",
3922
+ * subCommands: { ... },
3923
+ * }),
3924
+ * );
3925
+ * ```
3926
+ */
3927
+ /**
3928
+ * Generate completion script for the specified shell
3929
+ */
3930
+ function generateCompletion(command, options) {
3931
+ switch (options.shell) {
3932
+ case "bash": return generateBashCompletion(command, options);
3933
+ case "zsh": return generateZshCompletion(command, options);
3934
+ case "fish": return generateFishCompletion(command, options);
3935
+ default: throw new Error(`Unsupported shell: ${options.shell}`);
3936
+ }
3937
+ }
3938
+ /**
3939
+ * Get the list of supported shells
3940
+ */
3941
+ function getSupportedShells() {
3942
+ return [
3943
+ "bash",
3944
+ "zsh",
3945
+ "fish"
3946
+ ];
3947
+ }
3948
+ function shSingleQuote(s) {
3949
+ return `'${s.replace(/'/g, "'\\''")}'`;
3950
+ }
3951
+ function printZshFpathSetup(programName, target) {
3952
+ console.error("");
3953
+ console.error("Configure zsh fpath with:");
3954
+ console.error("");
3955
+ console.error(" mkdir -p ~/.zsh/completions");
3956
+ console.error(` ln -sf ${shSingleQuote(target)} ~/.zsh/completions/_${programName}`);
3957
+ console.error("");
3958
+ console.error("Add only this block to your ~/.zshrc before compinit:");
3959
+ console.error("");
3960
+ console.error(" fpath=(~/.zsh/completions $fpath)");
3961
+ console.error(" autoload -Uz compinit && compinit");
3962
+ }
3963
+ /**
3964
+ * Detect the current shell from environment
3965
+ */
3966
+ function detectShell() {
3967
+ const shellName = (process.env.SHELL || "").split("/").pop()?.toLowerCase() || "";
3968
+ if (shellName.includes("bash")) return "bash";
3969
+ if (shellName.includes("zsh")) return "zsh";
3970
+ if (shellName.includes("fish")) return "fish";
3971
+ return null;
3972
+ }
3973
+ /**
3974
+ * Schema for the completion command arguments
3975
+ */
3976
+ const completionArgsSchema = zod.z.object({
3977
+ shell: require_schema_extractor.arg(zod.z.enum([
3978
+ "bash",
3979
+ "zsh",
3980
+ "fish"
3981
+ ]).optional().describe("Shell type (auto-detected if not specified)"), {
3982
+ positional: true,
3983
+ description: "Shell type (bash, zsh, or fish)",
3984
+ placeholder: "SHELL"
3985
+ }),
3986
+ instructions: require_schema_extractor.arg(zod.z.boolean().default(false), {
3987
+ alias: "i",
3988
+ description: "Show installation instructions"
3989
+ }),
3990
+ loader: require_schema_extractor.arg(zod.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." }),
3991
+ install: require_schema_extractor.arg(zod.z.boolean().default(false), { description: "Write the completion script to its on-disk cache (bash/zsh) or autoload location (fish) instead of printing it." })
3992
+ });
3993
+ const refreshArgsSchema = zod.z.object({
3994
+ shell: require_schema_extractor.arg(zod.z.enum([
3995
+ "bash",
3996
+ "zsh",
3997
+ "fish"
3998
+ ]), {
3999
+ positional: true,
4000
+ description: "Shell to refresh",
4001
+ placeholder: "SHELL"
4002
+ }),
4003
+ target: require_schema_extractor.arg(zod.z.string().optional(), {
4004
+ positional: true,
4005
+ description: "Existing politty-generated completion file to refresh",
4006
+ placeholder: "TARGET"
4007
+ })
4008
+ });
4009
+ /**
4010
+ * Create a completion subcommand for your CLI
4011
+ *
4012
+ * This creates a ready-to-use subcommand that generates completion scripts.
4013
+ *
4014
+ * @example
4015
+ * ```typescript
4016
+ * const mainCommand = defineCommand({
4017
+ * name: "mycli",
4018
+ * subCommands: {
4019
+ * completion: createCompletionCommand(mainCommand)
4020
+ * }
4021
+ * });
4022
+ * ```
4023
+ */
4024
+ function createCompletionCommand(rootCommand, programName, globalArgsSchema, extra = {}) {
4025
+ const resolvedProgramName = programName ?? rootCommand.name;
4026
+ const { cacheDir, programVersion } = extra;
4027
+ const refreshExtra = {
4028
+ ...cacheDir !== void 0 && { cacheDir },
4029
+ ...programVersion !== void 0 && { programVersion },
4030
+ ...globalArgsSchema !== void 0 && { globalArgsSchema }
4031
+ };
4032
+ const installCtxBase = {
4033
+ programName: resolvedProgramName,
4034
+ ...refreshExtra
4035
+ };
4036
+ const loaderOptsBase = {
4037
+ programName: resolvedProgramName,
4038
+ ...cacheDir !== void 0 && { cacheDir }
4039
+ };
4040
+ if (!rootCommand.subCommands?.__complete) rootCommand.subCommands = {
4041
+ ...rootCommand.subCommands,
4042
+ __complete: createDynamicCompleteCommand(rootCommand, resolvedProgramName, globalArgsSchema)
4043
+ };
4044
+ if (!rootCommand.subCommands?.["__refresh-completion"]) rootCommand.subCommands = {
4045
+ ...rootCommand.subCommands,
4046
+ "__refresh-completion": createRefreshCompletionCommand(rootCommand, resolvedProgramName, refreshExtra)
4047
+ };
4048
+ return defineCommand({
4049
+ name: "completion",
4050
+ description: "Generate shell completion script",
4051
+ args: completionArgsSchema,
4052
+ run(args) {
4053
+ const shellType = args.shell || detectShell();
4054
+ if (!shellType) {
4055
+ console.error("Could not detect shell type. Please specify one of: bash, zsh, fish");
4056
+ process.exitCode = 1;
4057
+ return;
4058
+ }
4059
+ if (args.install) {
4060
+ let target;
4061
+ try {
4062
+ target = install({
4063
+ rootCommand,
4064
+ ...installCtxBase
4065
+ }, shellType);
4066
+ } catch (e) {
4067
+ throw new Error(`install failed: ${e instanceof Error ? e.message : String(e)}`);
4068
+ }
4069
+ console.error(`installed: ${target}`);
4070
+ if (shellType === "bash") {
4071
+ console.error("");
4072
+ console.error(`Add to your ~/.${shellType}rc:`);
4073
+ console.error("");
4074
+ console.error(generateLoader({
4075
+ ...loaderOptsBase,
4076
+ shell: shellType
4077
+ }).trim().replace(/^/gm, " "));
4078
+ } else if (shellType === "zsh") printZshFpathSetup(resolvedProgramName, target);
4079
+ return;
4080
+ }
4081
+ if (args.loader) {
4082
+ 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.");
4083
+ process.stdout.write(generateLoader({
4084
+ ...loaderOptsBase,
4085
+ shell: shellType
4086
+ }));
4087
+ return;
4088
+ }
4089
+ const result = generateCompletion(rootCommand, {
4090
+ shell: shellType,
4091
+ programName: resolvedProgramName,
4092
+ includeDescriptions: true,
4093
+ ...globalArgsSchema !== void 0 && { globalArgsSchema },
4094
+ ...programVersion !== void 0 && { programVersion },
4095
+ ...cacheDir !== void 0 && { cacheDir }
4096
+ });
4097
+ if (args.instructions) console.log(result.installInstructions);
4098
+ else console.log(result.script);
4099
+ }
4100
+ });
4101
+ }
4102
+ /**
4103
+ * Hidden subcommand that the runMain background hook spawns. It does
4104
+ * the same stat-compare + atomic rewrite as the rc loader, but in a
4105
+ * detached child process so it's invisible to the user.
4106
+ */
4107
+ function createRefreshCompletionCommand(rootCommand, programName, extra = {}) {
4108
+ return defineCommand({
4109
+ name: "__refresh-completion",
4110
+ description: "(internal) Refresh the on-disk completion cache if stale.",
4111
+ args: refreshArgsSchema,
4112
+ run(args) {
4113
+ refreshIfStale({
4114
+ rootCommand,
4115
+ programName,
4116
+ ...extra,
4117
+ ...args.target !== void 0 && { targetPath: args.target }
4118
+ }, args.shell);
4119
+ }
4120
+ });
4121
+ }
4122
+ /**
4123
+ * Wrap a command with a completion subcommand
4124
+ *
4125
+ * This avoids circular references that occur when a command references itself
4126
+ * in its subCommands (e.g., for completion generation).
4127
+ *
4128
+ * @param command - The command to wrap
4129
+ * @param options - Options including programName
4130
+ * @returns A new command with the completion subcommand added
4131
+ *
4132
+ * @example
4133
+ * ```typescript
4134
+ * const mainCommand = withCompletionCommand(
4135
+ * defineCommand({
4136
+ * name: "mycli",
4137
+ * subCommands: { ... },
4138
+ * }),
4139
+ * );
4140
+ * ```
4141
+ */
4142
+ function withCompletionCommand(command, options) {
4143
+ const { programName, globalArgsSchema, cacheDir, programVersion } = typeof options === "string" ? { programName: options } : options ?? {};
4144
+ const resolvedProgramName = programName ?? command.name;
4145
+ const extra = {
4146
+ ...cacheDir !== void 0 && { cacheDir },
4147
+ ...programVersion !== void 0 && { programVersion },
4148
+ ...globalArgsSchema !== void 0 && { globalArgsSchema }
4149
+ };
4150
+ const wrappedCommand = { ...command };
4151
+ wrappedCommand.subCommands = {
4152
+ ...command.subCommands,
4153
+ completion: createCompletionCommand(wrappedCommand, programName, globalArgsSchema, extra),
4154
+ __complete: createDynamicCompleteCommand(wrappedCommand, programName, globalArgsSchema),
4155
+ "__refresh-completion": createRefreshCompletionCommand(wrappedCommand, resolvedProgramName, extra)
4156
+ };
4157
+ wrappedCommand.runMainHook = (argv) => {
4158
+ maybeSpawnRefresh(argv, {
4159
+ programName: resolvedProgramName,
4160
+ ...cacheDir !== void 0 && { cacheDir }
4161
+ });
4162
+ };
4163
+ return wrappedCommand;
4164
+ }
4165
+ /**
4166
+ * Background-refresh trigger fired from `runMain` via `runMainHook`.
4167
+ *
4168
+ * Skipped when:
4169
+ * - the user is invoking `__complete` / `__refresh-completion` /
4170
+ * `completion` themselves (avoids loops and double work)
4171
+ * - $SHELL doesn't resolve to a known shell
4172
+ * - the user opted out via $POLITTY_NO_COMPLETION_REFRESH
4173
+ * - process.argv[1] is missing (shouldn't happen for normal CLIs)
4174
+ * - no politty-managed cache exists yet — i.e. the user hasn't
4175
+ * installed completion. Without this gate the detached child would
4176
+ * create a fish autoload (or any cache file) on every CLI run,
4177
+ * even though the user never opted in via `--install` or the rc loader.
4178
+ */
4179
+ function maybeSpawnRefresh(argv, ctx) {
4180
+ if (process.env.POLITTY_NO_COMPLETION_REFRESH) return;
4181
+ const firstPositional = argv.find((a) => !a.startsWith("-"));
4182
+ if (firstPositional === "__complete" || firstPositional === "__refresh-completion" || firstPositional === "completion") return;
4183
+ const shell = detectShell();
4184
+ if (!shell) return;
4185
+ const argv0 = process.argv[1];
4186
+ if (!argv0) return;
4187
+ if (!hasManagedCache(ctx, shell)) return;
4188
+ spawnBackgroundRefresh(argv0, shell);
4189
+ }
4190
+
4191
+ //#endregion
4192
+ Object.defineProperty(exports, 'CompletionDirective', {
4193
+ enumerable: true,
4194
+ get: function () {
4195
+ return CompletionDirective;
4196
+ }
4197
+ });
4198
+ Object.defineProperty(exports, 'createCompletionCommand', {
4199
+ enumerable: true,
4200
+ get: function () {
4201
+ return createCompletionCommand;
4202
+ }
4203
+ });
4204
+ Object.defineProperty(exports, 'createDefineCommand', {
4205
+ enumerable: true,
4206
+ get: function () {
4207
+ return createDefineCommand;
4208
+ }
4209
+ });
4210
+ Object.defineProperty(exports, 'createDynamicCompleteCommand', {
4211
+ enumerable: true,
4212
+ get: function () {
4213
+ return createDynamicCompleteCommand;
4214
+ }
4215
+ });
4216
+ Object.defineProperty(exports, 'createRefreshCompletionCommand', {
4217
+ enumerable: true,
4218
+ get: function () {
4219
+ return createRefreshCompletionCommand;
4220
+ }
4221
+ });
4222
+ Object.defineProperty(exports, 'defineCommand', {
4223
+ enumerable: true,
4224
+ get: function () {
4225
+ return defineCommand;
4226
+ }
4227
+ });
4228
+ Object.defineProperty(exports, 'detectShell', {
4229
+ enumerable: true,
4230
+ get: function () {
4231
+ return detectShell;
4232
+ }
4233
+ });
4234
+ Object.defineProperty(exports, 'extractCompletionData', {
4235
+ enumerable: true,
4236
+ get: function () {
4237
+ return extractCompletionData;
4238
+ }
4239
+ });
4240
+ Object.defineProperty(exports, 'extractPositionals', {
4241
+ enumerable: true,
4242
+ get: function () {
4243
+ return extractPositionals;
4244
+ }
4245
+ });
4246
+ Object.defineProperty(exports, 'formatForShell', {
4247
+ enumerable: true,
4248
+ get: function () {
4249
+ return formatForShell;
4250
+ }
4251
+ });
4252
+ Object.defineProperty(exports, 'generateCandidates', {
4253
+ enumerable: true,
4254
+ get: function () {
4255
+ return generateCandidates;
4256
+ }
4257
+ });
4258
+ Object.defineProperty(exports, 'generateCompletion', {
4259
+ enumerable: true,
4260
+ get: function () {
4261
+ return generateCompletion;
4262
+ }
4263
+ });
4264
+ Object.defineProperty(exports, 'getSupportedShells', {
4265
+ enumerable: true,
4266
+ get: function () {
4267
+ return getSupportedShells;
4268
+ }
4269
+ });
4270
+ Object.defineProperty(exports, 'hasCompleteCommand', {
4271
+ enumerable: true,
4272
+ get: function () {
4273
+ return hasCompleteCommand;
4274
+ }
4275
+ });
4276
+ Object.defineProperty(exports, 'parseCompletionContext', {
4277
+ enumerable: true,
4278
+ get: function () {
4279
+ return parseCompletionContext;
4280
+ }
4281
+ });
4282
+ Object.defineProperty(exports, 'resolveValueCompletion', {
4283
+ enumerable: true,
4284
+ get: function () {
4285
+ return resolveValueCompletion;
4286
+ }
4287
+ });
4288
+ Object.defineProperty(exports, 'withCompletionCommand', {
4289
+ enumerable: true,
4290
+ get: function () {
4291
+ return withCompletionCommand;
4292
+ }
4293
+ });
4294
+ //# sourceMappingURL=completion-BFOAOg95.cjs.map