@hop-top/kit 0.5.0-alpha.1 → 0.5.0-alpha.11

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 (293) hide show
  1. package/CHANGELOG.md +275 -0
  2. package/LICENSE +1 -1
  3. package/LICENSE-cobra.txt +174 -0
  4. package/NOTICE +15 -0
  5. package/README.md +55 -259
  6. package/dist/aim-DZHwwiIc.d.ts +139 -0
  7. package/dist/aim.d.ts +1 -116
  8. package/dist/aim.js +13 -414
  9. package/dist/alias-D9_qFlyP.d.ts +174 -0
  10. package/dist/alias.d.ts +2 -73
  11. package/dist/alias.js +27 -207
  12. package/dist/api-DAexsu2H.d.ts +77 -0
  13. package/dist/api.d.ts +1 -62
  14. package/dist/api.js +10 -164
  15. package/dist/auth-2-jfgiHn.d.ts +34 -0
  16. package/dist/auth.d.ts +1 -26
  17. package/dist/auth.js +6 -40
  18. package/dist/chunk-3FIKGFKI.js +54 -0
  19. package/dist/chunk-4FMALWYB.js +669 -0
  20. package/dist/chunk-4GPCWBBA.js +143 -0
  21. package/dist/chunk-4UE5TCMQ.js +104 -0
  22. package/dist/chunk-65VPWMPV.js +1134 -0
  23. package/dist/chunk-6HFAEZ52.js +29 -0
  24. package/dist/chunk-6SVOHNIC.js +17 -0
  25. package/dist/chunk-BDNNPRX6.js +41 -0
  26. package/dist/chunk-BRNEKPWX.js +37 -0
  27. package/dist/chunk-BXJ2J27B.js +219 -0
  28. package/dist/chunk-CSJWB6D3.js +151 -0
  29. package/dist/chunk-CXBZTONY.js +65 -0
  30. package/dist/chunk-EE4M2UOF.js +818 -0
  31. package/dist/chunk-GFRAYYRD.js +817 -0
  32. package/dist/chunk-IVQHLI56.js +1890 -0
  33. package/dist/chunk-IZ6Q4SE3.js +178 -0
  34. package/dist/chunk-JKMQSAJP.js +174 -0
  35. package/dist/chunk-K7E34Q3A.js +1445 -0
  36. package/dist/chunk-KVG7YCTS.js +115 -0
  37. package/dist/chunk-L23O2FFE.js +51 -0
  38. package/dist/chunk-MFVUENZR.js +1549 -0
  39. package/dist/chunk-ML7D5DWY.js +263 -0
  40. package/dist/chunk-MQXYDYRD.js +968 -0
  41. package/dist/chunk-POR5L2DG.js +247 -0
  42. package/dist/chunk-QJVSKKRQ.js +369 -0
  43. package/dist/chunk-QQQYCWSC.js +240 -0
  44. package/dist/chunk-R5U7XKVJ.js +16 -0
  45. package/dist/chunk-RYKLVOVK.js +309 -0
  46. package/dist/chunk-SNVGDYX7.js +187 -0
  47. package/dist/chunk-T6OZMPPV.js +68 -0
  48. package/dist/chunk-UKZIAQA7.js +26 -0
  49. package/dist/chunk-VGOA5Y7S.js +251 -0
  50. package/dist/chunk-VWGP4NVJ.js +513 -0
  51. package/dist/chunk-WBVO43HU.js +355 -0
  52. package/dist/chunk-WUOAQVOA.js +86 -0
  53. package/dist/chunk-XJTRY453.js +868 -0
  54. package/dist/chunk-YOBAUCVN.js +583 -0
  55. package/dist/cli-RSRk1M36.d.ts +707 -0
  56. package/dist/cli.d.ts +7 -309
  57. package/dist/cli.js +125 -945
  58. package/dist/completion-csVun6SP.d.ts +112 -0
  59. package/dist/completion-values-By-mnjNt.d.ts +142 -0
  60. package/dist/completion-values.d.ts +1 -0
  61. package/dist/completion-values.js +29 -0
  62. package/dist/completion.d.ts +3 -0
  63. package/dist/completion.js +34 -0
  64. package/dist/compliance-AxFf-uMy.d.ts +60 -0
  65. package/dist/compliance.d.ts +1 -0
  66. package/dist/compliance.js +17 -0
  67. package/dist/config-CaK60ByQ.d.ts +241 -0
  68. package/dist/config.d.ts +1 -97
  69. package/dist/config.js +8 -78
  70. package/dist/errcorrect-BcX1Ft0K.d.ts +44 -0
  71. package/dist/errcorrect.d.ts +1 -37
  72. package/dist/errcorrect.js +8 -68
  73. package/dist/error-Do8Qji43.d.ts +231 -0
  74. package/dist/id/index.d.ts +2 -83
  75. package/dist/id/index.js +14 -65
  76. package/dist/index-BKJZClJx.d.ts +1486 -0
  77. package/dist/index-C3Zw4wDJ.d.ts +359 -0
  78. package/dist/index-CGE5yLBj.d.ts +328 -0
  79. package/dist/index-VLDcI5NF.d.ts +95 -0
  80. package/dist/index.d.ts +37 -0
  81. package/dist/index.js +132 -0
  82. package/dist/llm-DYuR7_uX.d.ts +1069 -0
  83. package/dist/llm-anthropic-Cd_I2xXB.d.ts +67 -0
  84. package/dist/llm-anthropic.d.ts +2 -0
  85. package/dist/llm-anthropic.js +13 -0
  86. package/dist/llm-openai-DyFrucmV.d.ts +87 -0
  87. package/dist/llm-openai.d.ts +2 -0
  88. package/dist/llm-openai.js +19 -0
  89. package/dist/llm.d.ts +1 -188
  90. package/dist/llm.js +101 -356
  91. package/dist/log-CkaxMX3U.d.ts +115 -0
  92. package/dist/log.d.ts +2 -0
  93. package/dist/log.js +14 -0
  94. package/dist/mcp/index.d.ts +4 -0
  95. package/dist/mcp/index.js +185 -0
  96. package/dist/netpolicy-Brx5XZUB.d.ts +151 -0
  97. package/dist/netpolicy.d.ts +1 -0
  98. package/dist/netpolicy.js +25 -0
  99. package/dist/output-CjZWmL8s.d.ts +420 -0
  100. package/dist/output.d.ts +3 -213
  101. package/dist/output.js +135 -447
  102. package/dist/parity-CvMuYcVI.d.ts +61 -0
  103. package/dist/progress-CAzyxeWl.d.ts +38 -0
  104. package/dist/progress.d.ts +1 -30
  105. package/dist/progress.js +6 -55
  106. package/dist/provenance-SMFHm5gx.d.ts +30 -0
  107. package/dist/provenance.d.ts +1 -24
  108. package/dist/provenance.js +6 -31
  109. package/dist/routellm-B0nv59mH.d.ts +111 -0
  110. package/dist/routellm.d.ts +2 -64
  111. package/dist/routellm.js +13 -255
  112. package/dist/rpc-D31Lg0Kc.d.ts +32 -0
  113. package/dist/rpc.d.ts +2 -25
  114. package/dist/rpc.js +4 -98
  115. package/dist/safety-CUaYEjZc.d.ts +30 -0
  116. package/dist/safety.d.ts +1 -24
  117. package/dist/safety.js +6 -43
  118. package/dist/scope-BrhYB4ij.d.ts +141 -0
  119. package/dist/scope.d.ts +1 -121
  120. package/dist/scope.js +20 -377
  121. package/dist/serve-D8yWMrTc.d.ts +646 -0
  122. package/dist/serve.d.ts +3 -0
  123. package/dist/serve.js +75 -0
  124. package/dist/sqlstore.js +6 -39
  125. package/dist/stream-CrjeCp0M.d.ts +44 -0
  126. package/dist/stream.d.ts +1 -35
  127. package/dist/stream.js +8 -51
  128. package/dist/telemetry/index.d.ts +1 -315
  129. package/dist/telemetry/index.js +26 -599
  130. package/dist/toolspec-DcPwwoAZ.d.ts +368 -0
  131. package/dist/toolspec.d.ts +2 -0
  132. package/dist/toolspec.js +37 -0
  133. package/dist/tui/index.d.ts +6 -298
  134. package/dist/tui/index.js +17 -381
  135. package/dist/upgrade-C3RWGwRi.d.ts +125 -0
  136. package/dist/upgrade.d.ts +1 -95
  137. package/dist/upgrade.js +6 -114
  138. package/dist/xdg-DB7Shoib.d.ts +179 -0
  139. package/dist/xdg.d.ts +1 -169
  140. package/dist/xdg.js +14 -128
  141. package/package.json +192 -24
  142. package/src/README.md +15 -0
  143. package/src/alias.conformance.test.ts +250 -0
  144. package/src/alias.test.ts +206 -2
  145. package/src/alias.ts +196 -21
  146. package/src/cli.help-command.test.ts +105 -0
  147. package/src/cli.offline.test.ts +93 -0
  148. package/src/cli.parity.test.ts +192 -0
  149. package/src/cli.root.conformance.test.ts +166 -0
  150. package/src/cli.test.ts +95 -1
  151. package/src/cli.ts +234 -25
  152. package/src/completion-scripts.ts +16 -0
  153. package/src/completion-values.test.ts +76 -16
  154. package/src/completion-values.ts +170 -66
  155. package/src/completion.conformance.test.ts +298 -0
  156. package/src/completion.test.ts +268 -145
  157. package/src/completion.ts +772 -121
  158. package/src/compliance.test.ts +196 -2
  159. package/src/compliance.ts +440 -20
  160. package/src/config-merge.test.ts +425 -0
  161. package/src/config.test.ts +228 -1
  162. package/src/config.ts +429 -16
  163. package/src/delegation.test.ts +299 -0
  164. package/src/delegation.ts +807 -0
  165. package/src/gen/crud_pb.ts +7 -7
  166. package/src/id/README.md +38 -0
  167. package/src/id/contract.test.ts +1 -1
  168. package/src/id/index.test.ts +1 -1
  169. package/src/id/index.ts +3 -2
  170. package/src/index.test.ts +71 -0
  171. package/src/index.ts +46 -0
  172. package/src/llm-anthropic.conformance.test.ts +1135 -0
  173. package/src/llm-anthropic.test.ts +152 -0
  174. package/src/llm-anthropic.ts +940 -0
  175. package/src/llm-choice-hermetic.test.ts +335 -0
  176. package/src/llm-config.test.ts +232 -0
  177. package/src/llm-config.ts +106 -0
  178. package/src/llm-endpoint.ts +254 -0
  179. package/src/llm-error.ts +17 -0
  180. package/src/llm-errors.ts +152 -0
  181. package/src/llm-file.ts +126 -0
  182. package/src/llm-http.ts +317 -0
  183. package/src/llm-keys.ts +167 -0
  184. package/src/llm-media.conformance.test.ts +87 -0
  185. package/src/llm-media.test.ts +279 -0
  186. package/src/llm-media.ts +322 -0
  187. package/src/llm-openai.conformance.test.ts +407 -0
  188. package/src/llm-openai.test.ts +510 -0
  189. package/src/llm-openai.ts +708 -0
  190. package/src/llm-payload.ts +155 -0
  191. package/src/llm-quote.ts +46 -0
  192. package/src/llm-routellm.conformance.test.ts +44 -0
  193. package/src/llm-toolnames.conformance.test.ts +112 -0
  194. package/src/llm-toolnames.test.ts +132 -0
  195. package/src/llm-toolnames.ts +298 -0
  196. package/src/llm-uri.ts +99 -0
  197. package/src/llm.test.ts +43 -15
  198. package/src/llm.toolcall.test.ts +175 -0
  199. package/src/llm.ts +602 -190
  200. package/src/log.parity.test.ts +105 -0
  201. package/src/log.test.ts +270 -1
  202. package/src/log.ts +228 -49
  203. package/src/mcp/README.md +63 -0
  204. package/src/mcp/args-separator.test.ts +164 -0
  205. package/src/mcp/args.test.ts +223 -0
  206. package/src/mcp/args.ts +160 -0
  207. package/src/mcp/audit.test.ts +520 -0
  208. package/src/mcp/audit.ts +70 -0
  209. package/src/mcp/bridge.test.ts +250 -0
  210. package/src/mcp/bridge.ts +286 -0
  211. package/src/mcp/conformance.test.ts +357 -0
  212. package/src/mcp/dispatch.ts +359 -0
  213. package/src/mcp/identity.test.ts +166 -0
  214. package/src/mcp/identity.ts +72 -0
  215. package/src/mcp/index.ts +176 -0
  216. package/src/mcp/legacy-notify.test.ts +59 -0
  217. package/src/mcp/legacy.ts +367 -0
  218. package/src/mcp/mcp.test.ts +707 -0
  219. package/src/mcp/modern-confirm.test.ts +520 -0
  220. package/src/mcp/modern-confirm.ts +484 -0
  221. package/src/mcp/modern.ts +788 -0
  222. package/src/mcp/stdio.test.ts +313 -0
  223. package/src/mcp/stdio.ts +254 -0
  224. package/src/mcp/tasks.ts +82 -0
  225. package/src/mcp/testtree.ts +250 -0
  226. package/src/mcp/toolname.test.ts +147 -0
  227. package/src/mcp/types.ts +689 -0
  228. package/src/netpolicy.test.ts +280 -0
  229. package/src/netpolicy.ts +256 -0
  230. package/src/output/README.md +46 -0
  231. package/src/output/builtins.ts +5 -5
  232. package/src/output/dispatch.ts +10 -2
  233. package/src/output/error.ts +459 -0
  234. package/src/output/formatter.ts +29 -5
  235. package/src/output/formatters/README.md +50 -0
  236. package/src/output/formatters/csv.ts +48 -12
  237. package/src/output/formatters/json.ts +4 -25
  238. package/src/output/formatters/project.ts +34 -0
  239. package/src/output/formatters/table.ts +8 -6
  240. package/src/output/formatters/text.ts +7 -3
  241. package/src/output/formatters/yaml.ts +5 -22
  242. package/src/output/projection.test.ts +298 -0
  243. package/src/output/projection.ts +33 -59
  244. package/src/output/template.ts +11 -21
  245. package/src/output.surface.test.ts +41 -0
  246. package/src/output.ts +64 -3
  247. package/src/plan.ts +89 -0
  248. package/src/policy.ts +472 -0
  249. package/src/published-types.test.ts +133 -0
  250. package/src/routellm.test.ts +209 -28
  251. package/src/routellm.toolcall.test.ts +521 -0
  252. package/src/routellm.ts +213 -177
  253. package/src/router/README.md +44 -0
  254. package/src/router/server.test.ts +41 -0
  255. package/src/router/server.ts +11 -0
  256. package/src/safety.test.ts +19 -9
  257. package/src/scope-defaults.json +29 -29
  258. package/src/serve.test.ts +1257 -0
  259. package/src/serve.ts +1665 -0
  260. package/src/sideeffect.ts +105 -0
  261. package/src/telemetry/README.md +48 -0
  262. package/src/telemetry/client.test.ts +31 -0
  263. package/src/telemetry/client.ts +12 -6
  264. package/src/telemetry/offline.test.ts +64 -0
  265. package/src/toolspec-internal.ts +279 -0
  266. package/src/toolspec-manifest.test.ts +167 -0
  267. package/src/toolspec-manifest.ts +415 -0
  268. package/src/toolspec-spec-schemas.ts +12 -0
  269. package/src/toolspec-spec.test.ts +273 -0
  270. package/src/toolspec-spec.ts +458 -0
  271. package/src/toolspec.from-command.test.ts +350 -0
  272. package/src/toolspec.test.ts +2 -2
  273. package/src/toolspec.ts +222 -0
  274. package/src/triton/README.md +34 -0
  275. package/src/tui/README.md +42 -0
  276. package/src/tui/parity.test.ts +120 -31
  277. package/src/tui/parity.ts +58 -7
  278. package/src/upgrade.test.ts +291 -0
  279. package/src/upgrade.ts +116 -7
  280. package/src/wizard.test.ts +7 -7
  281. package/test/llm/conformance-helpers.ts +100 -0
  282. package/test/output/csv.test.ts +164 -0
  283. package/test/output/dispatch.test.ts +1 -2
  284. package/test/output/error.test.ts +277 -0
  285. package/test/output/smoke-capture.ts +2 -2
  286. package/test/output/smoke.test.ts +2 -2
  287. package/test/output/taxonomy-contract.test.ts +148 -0
  288. package/test/setup-env.ts +16 -0
  289. package/test/toolspec/fixture.ts +79 -0
  290. package/tsconfig.json +3 -1
  291. package/tsconfig.test.json +10 -0
  292. package/vitest.config.ts +9 -0
  293. package/src/tui/parity.json +0 -74
package/src/cli.ts CHANGED
@@ -26,18 +26,62 @@
26
26
  */
27
27
 
28
28
  import { Command, Help } from 'commander';
29
- import { parity } from './tui/parity.js';
29
+ import { parity, type ParityData } from './tui/parity.js';
30
30
  import { registerOutputFlags } from './output/flags.js';
31
+ import { EXIT_USAGE } from './output/error.js';
32
+ import { install as installNetPolicy, setProcessOffline } from './netpolicy.js';
33
+ import { installCompletionRequest } from './completion.js';
31
34
  import './output/builtins.js';
35
+ import { installDelegation, type PromptSource } from './delegation.js';
36
+ import type { PolicyLoader } from './policy.js';
37
+ export { controllingTTY, destructiveToken, dryRunApplied, installConfirmTokenFlag,
38
+ isDryRun, noPrompt, resolveConfirmMode, resolveDryRunPolicy,
39
+ scriptedPrompt } from './delegation.js';
40
+ export type { ConfirmMode, DryRunPolicy, PromptSource, Prompter } from './delegation.js';
41
+ export { Engine, KIT_DEFAULT_NAME, MaxOpsExceededError, defaultPolicyLoader,
42
+ kitDefault, loadNamedPolicy, loadPolicy, resolvePolicyPath } from './policy.js';
43
+ export type { Policy, PolicyLoader, Verdict } from './policy.js';
44
+ export { INFERRED_TIER, SIDE_EFFECT_TIERS, destructiveNames, gateSideEffect,
45
+ inferredDestructive, isDestructiveLike, isDestructiveName,
46
+ isWriteLike } from './sideeffect.js';
47
+ export type { SideEffect } from './sideeffect.js';
48
+ export { renderPlan } from './plan.js';
49
+ export type { Effect, Plan } from './plan.js';
50
+ export { ErrOffline, OfflineError, guardFetch, isOffline, isOfflineError,
51
+ withOffline } from './netpolicy.js';
32
52
  export { HintSet, hintsEnabled, renderHints, active,
33
53
  registerUpgradeHints, registerVersionHints } from './hint.js';
34
54
  export type { Hint, HintOptions } from './hint.js';
35
55
 
36
56
  // ---------------------------------------------------------------------------
37
- // Verbose count — stacking -V flags
57
+ // Verbose count — stacking -V flags; quiet
38
58
  // ---------------------------------------------------------------------------
39
59
 
40
60
  const verboseCountMap = new WeakMap<Command, number>();
61
+ const quietMap = new WeakMap<Command, boolean>();
62
+
63
+ /**
64
+ * Return the single-character shorthand declared by the parity contract's
65
+ * `verbosity.flag`, with leading dashes stripped. A contract value that is
66
+ * not a single character after stripping falls back to `V`.
67
+ *
68
+ * Taking the contract as a parameter (rather than reading the module-level
69
+ * `parity`) keeps the mapping testable against a constructed `ParityData`
70
+ * without mutating the shared `parity.json`.
71
+ */
72
+ export function verbosityShorthand(d: ParityData): string {
73
+ const s = (d.verbosity?.flag ?? '').replace(/^-+/, '');
74
+ return s.length === 1 ? s : 'V';
75
+ }
76
+
77
+ /**
78
+ * Render the `-V` option spec commander registers, e.g. `-V, --verbose`.
79
+ * The shorthand comes from the parity contract; the long name is
80
+ * kit-local (the contract declares only the shorthand).
81
+ */
82
+ export function verbosityFlagSpec(d: ParityData): string {
83
+ return `-${verbosityShorthand(d)}, --verbose`;
84
+ }
41
85
 
42
86
  /** Read the accumulated -V count for a parsed command tree. */
43
87
  export function verboseCount(cmd: Command): number {
@@ -51,6 +95,24 @@ export function verboseCount(cmd: Command): number {
51
95
  return 0;
52
96
  }
53
97
 
98
+ /**
99
+ * Report whether `--quiet` is in effect for a parsed command tree.
100
+ *
101
+ * `--quiet` wins over `-V`: when set, `verboseCount` reads 0 and the
102
+ * logger level is the contract's `verbosity.quiet_override`. False before
103
+ * parsing and when `disable.quiet` drops the flag.
104
+ */
105
+ export function isQuiet(cmd: Command): boolean {
106
+ // Walk up to root to find the stored flag.
107
+ let c: Command | null = cmd;
108
+ while (c) {
109
+ const q = quietMap.get(c);
110
+ if (q !== undefined) return q;
111
+ c = c.parent ?? null;
112
+ }
113
+ return false;
114
+ }
115
+
54
116
  // ---------------------------------------------------------------------------
55
117
  // Named streams — registerStream / channel
56
118
  // ---------------------------------------------------------------------------
@@ -62,9 +124,43 @@ interface StreamDef {
62
124
 
63
125
  const streamDefsMap = new WeakMap<Command, StreamDef[]>();
64
126
 
127
+ /**
128
+ * Return the long flag name declared by the parity contract's
129
+ * `streams.flag`, with leading dashes stripped (commander's parsed option
130
+ * key is the undashed camelCase name). Falls back to `stream`.
131
+ *
132
+ * Taking the contract as a parameter (rather than reading the module-level
133
+ * `parity`) keeps the mapping testable against a constructed `ParityData`
134
+ * without mutating the shared `parity.json`.
135
+ */
136
+ export function streamFlagName(d: ParityData): string {
137
+ const name = (d.streams?.flag ?? '').replace(/^-+/, '');
138
+ return name === '' ? 'stream' : name;
139
+ }
140
+
141
+ /**
142
+ * Render a stream's prefix from the parity contract's
143
+ * `streams.label_format` template. The template's `{name}` placeholder is
144
+ * substituted with the stream name; a trailing space separates the label
145
+ * from the payload.
146
+ */
147
+ export function streamLabel(d: ParityData, name: string): string {
148
+ const format = d.streams?.label_format || '[{name}]';
149
+ return format.split('{name}').join(name) + ' ';
150
+ }
151
+
152
+ /**
153
+ * Resolve the parity contract's `streams.output` destination to a stream.
154
+ * Anything other than `stdout` resolves to stderr, which is the contract's
155
+ * declared destination.
156
+ */
157
+ export function streamOutput(d: ParityData): NodeJS.WritableStream {
158
+ return d.streams?.output === 'stdout' ? process.stdout : process.stderr;
159
+ }
160
+
65
161
  /**
66
162
  * Register a named diagnostic stream on a command.
67
- * Adds a `--stream <names>` option (comma-separated) on first call.
163
+ * Adds the parity contract's stream option (comma-separated) on first call.
68
164
  *
69
165
  * Parity note: Go uses StringSlice (repeatable --stream); TS and Python
70
166
  * use a single comma-separated string value.
@@ -76,9 +172,9 @@ export function registerStream(
76
172
  if (!defs) {
77
173
  defs = [];
78
174
  streamDefsMap.set(cmd, defs);
79
- // Add --stream option on first registration.
175
+ // Add the contract's stream option on first registration.
80
176
  cmd.option(
81
- '--stream <names>',
177
+ `--${streamFlagName(parity)} <names>`,
82
178
  'Enable diagnostic streams (comma-separated)',
83
179
  );
84
180
  }
@@ -93,24 +189,37 @@ export function getStreamDefs(cmd: Command): StreamDef[] {
93
189
  const noopWriter = { write(_s: string): boolean { return true; } };
94
190
 
95
191
  /**
96
- * Return a writer for a named stream. When the stream is enabled via
97
- * `--stream`, writes go to stderr with a `[name] ` prefix. Otherwise
98
- * writes are discarded.
192
+ * Commander stores a parsed option under the camelCased form of its long
193
+ * name (`--log-level` → `opts.logLevel`), so the contract's flag name must
194
+ * be camelCased before it is read back off `cmd.opts()`.
195
+ */
196
+ function optionKey(flagName: string): string {
197
+ return flagName.replace(/-([a-z])/g, (_, c: string) => c.toUpperCase());
198
+ }
199
+
200
+ /**
201
+ * Return a writer for a named stream. When the stream is enabled via the
202
+ * parity contract's stream flag, writes go to the contract's
203
+ * `streams.output` destination, prefixed with its `streams.label_format`
204
+ * label. Otherwise writes are discarded.
99
205
  */
100
206
  export function channel(
101
207
  cmd: Command, name: string,
102
208
  ): { write(s: string): boolean } {
103
209
  const opts = cmd.opts();
104
- const enabled = typeof opts.stream === 'string'
105
- ? opts.stream.split(',').map((s: string) => s.trim()).includes(name)
210
+ const raw = opts[optionKey(streamFlagName(parity))];
211
+ const enabled = typeof raw === 'string'
212
+ ? raw.split(',').map((s: string) => s.trim()).includes(name)
106
213
  : false;
107
214
  if (!enabled) return noopWriter;
215
+ const prefix = streamLabel(parity, name);
216
+ const w = streamOutput(parity);
108
217
  return {
109
218
  write(s: string): boolean {
110
219
  // Split on newlines and prefix each line (parity with Go/Python).
111
220
  const lines = s.split('\n');
112
221
  for (const line of lines) {
113
- if (line) process.stderr.write(`[${name}] ${line}\n`);
222
+ if (line) w.write(`${prefix}${line}\n`);
114
223
  }
115
224
  return true;
116
225
  },
@@ -238,8 +347,25 @@ export interface CLIConfig {
238
347
  quiet?: boolean;
239
348
  noColor?: boolean;
240
349
  hints?: boolean;
350
+ offline?: boolean;
351
+ /** Drop the root `--dry-run` flag; it is then never applied. */
352
+ dryRun?: boolean;
241
353
  };
242
354
 
355
+ /**
356
+ * Resolves a named root `--policy <name>`; see {@link defaultPolicyLoader}
357
+ * for the `$XDG_CONFIG_HOME/<name>/policies/<policy>.yaml` loader. Unset
358
+ * wires none: only the reserved `kit-default` policy resolves.
359
+ */
360
+ policy?: PolicyLoader;
361
+
362
+ /**
363
+ * The terminal the `--confirm` prompt asks on. Defaults to the
364
+ * controlling terminal (`/dev/tty`); with none, an unset `--confirm`
365
+ * resolves to `no`.
366
+ */
367
+ promptSource?: PromptSource;
368
+
243
369
  /** Command groups for partitioned help (e.g. COMMANDS vs MANAGEMENT). */
244
370
  groups?: Array<{
245
371
  id: string; // e.g. "management"
@@ -463,6 +589,21 @@ export function applyHelpTheme(
463
589
  output.push('');
464
590
  }
465
591
 
592
+ // Arguments — only listed when at least one carries a description
593
+ // (Commander's visibleArguments rule); title from parity.json.
594
+ const argList = helper.visibleArguments(cmd);
595
+ if (argList.length > 0) {
596
+ const title = parity.help.sections?.['arguments']?.title ?? 'ARGUMENTS';
597
+ output.push(helper.styleTitle(`${title}:`));
598
+ for (const a of argList) {
599
+ output.push(callFormatItem(
600
+ helper.styleArgumentTerm(helper.argumentTerm(a)),
601
+ helper.styleArgumentDescription(helper.argumentDescription(a)),
602
+ ));
603
+ }
604
+ output.push('');
605
+ }
606
+
466
607
  // Collect sections in parity order.
467
608
  const helpSections: { name: string; items: string[] }[] = [];
468
609
 
@@ -598,6 +739,22 @@ export function applyHelpTheme(
598
739
  });
599
740
  }
600
741
 
742
+ /**
743
+ * Resolves operands as a command path below root, matching names and
744
+ * aliases. Only a fully-resolved path counts: "remote nosuch" names no
745
+ * command rather than falling back to "remote".
746
+ */
747
+ function findHelpTarget(root: Command, operands: string[]): Command | undefined {
748
+ let cmd: Command | undefined;
749
+ let scope = root;
750
+ for (const word of operands) {
751
+ cmd = scope.commands.find(c => c.name() === word || c.aliases().includes(word));
752
+ if (!cmd) return undefined;
753
+ scope = cmd;
754
+ }
755
+ return cmd;
756
+ }
757
+
601
758
  // ---------------------------------------------------------------------------
602
759
  // Factory
603
760
  // ---------------------------------------------------------------------------
@@ -663,16 +820,51 @@ export function createCLI(cfg: CLIConfig): CLIResult {
663
820
  program.option('--no-hints', 'Suppress next-step hints after command output', false);
664
821
  }
665
822
 
666
- // -V / --verbose: accumulator pattern for stacking (-VV = 2).
823
+ // --offline (cli-parity-guide, "Global Flags") disables all network
824
+ // access. It is the highest-precedence override: per-command network
825
+ // opt-ins (peer discovery, sync replication, repo creation, initial
826
+ // push, upgrade checks) must behave as if their corresponding opt-out
827
+ // flag had been passed. The override only forces opt-outs ON — it never
828
+ // un-sets an explicitly passed --no-* flag, which is why it stamps a
829
+ // marker rather than rewriting parsed options.
830
+ //
831
+ // Registering the flag alone would be advisory: a leaf that never
832
+ // consults the marker would still reach the wire. installNetPolicy
833
+ // guards globalThis.fetch so the refusal happens beneath naive callers.
834
+ if (!cfg.disable?.offline) {
835
+ program.option('--offline', 'Disable network access', false);
836
+ installNetPolicy();
837
+ // preSubcommand fires before a subcommand's action handler, and the
838
+ // root's own action for a leaf-less program; hook both so the marker
839
+ // is set whichever shape the adopter uses.
840
+ const stamp = (thisCmd: Command) => {
841
+ setProcessOffline(thisCmd.opts()['offline'] === true);
842
+ };
843
+ program.hook('preSubcommand', (thisCmd) => stamp(thisCmd));
844
+ program.hook('preAction', (thisCmd) => stamp(thisCmd));
845
+ }
846
+
847
+ // Delegation gates: --dry-run, --confirm, --max-ops, --policy and the
848
+ // hooks enforcing them on every runnable leaf.
849
+ installDelegation(program, {
850
+ policy: cfg.policy,
851
+ promptSource: cfg.promptSource,
852
+ disableDryRun: cfg.disable?.dryRun === true,
853
+ });
854
+
855
+ // Stackable verbosity count flag (-VV = 2). The shorthand comes from the
856
+ // parity contract's verbosity block; commander takes the option spec as a
857
+ // runtime string, so it need not be a literal.
667
858
  program.option(
668
- '-V, --verbose', 'Increase verbosity',
859
+ verbosityFlagSpec(parity), 'Increase verbosity',
669
860
  (_: string, prev: number) => prev + 1, 0,
670
861
  );
671
- // Store count after parse; quiet overrides verbose.
862
+ // Store count + quiet after parse; quiet overrides verbose.
672
863
  program.hook('preAction', (thisCmd) => {
673
864
  const opts = thisCmd.opts();
674
- const count = opts.quiet ? 0 : (opts.verbose ?? 0);
675
- verboseCountMap.set(thisCmd, count);
865
+ const quiet = opts.quiet === true;
866
+ quietMap.set(thisCmd, quiet);
867
+ verboseCountMap.set(thisCmd, quiet ? 0 : (opts.verbose ?? 0));
676
868
  });
677
869
 
678
870
  if (cfg.groups?.some(g => g.hidden)) {
@@ -690,21 +882,34 @@ export function createCLI(cfg: CLIConfig): CLIResult {
690
882
  });
691
883
  }
692
884
 
693
- // help <group> subcommand (hidden from default help).
885
+ // help [command | group] subcommand (hidden from default help).
886
+ // Operands resolve in order: "all", a fully-resolved command path
887
+ // (a command wins over a group of the same name), a group ID; else a
888
+ // usage error (exit 2).
694
889
  if (cfg.groups && cfg.groups.length > 0) {
695
890
  const groupIds = cfg.groups.map(g => g.id);
696
- const helpCmd = program.command('help [group]')
697
- .description('Show help for a command group')
698
- .action((group?: string) => {
699
- if (group === 'all') {
700
- process.argv.push('--help-all');
891
+ const helpCmd = program.command('help [operands...]')
892
+ .description('Show help for a command or command group')
893
+ .action((operands: string[]) => {
894
+ if (operands.length === 0) {
701
895
  program.help();
702
- } else if (group && groupIds.includes(group)) {
703
- process.argv.push(`--help-${group}`);
896
+ }
897
+ if (operands.length === 1 && operands[0] === 'all') {
898
+ process.argv.push('--help-all');
704
899
  program.help();
705
- } else {
900
+ }
901
+ const target = findHelpTarget(program, operands);
902
+ if (target) {
903
+ target.help();
904
+ }
905
+ if (operands.length === 1 && groupIds.includes(operands[0]!)) {
906
+ process.argv.push(`--help-${operands[0]}`);
706
907
  program.help();
707
908
  }
909
+ program.error(
910
+ `error: unknown help topic '${operands.join(' ')}' for '${program.name()}'`,
911
+ { exitCode: EXIT_USAGE, code: 'commander.unknownCommand' },
912
+ );
708
913
  });
709
914
  // Hide from default help output.
710
915
  (helpCmd as any).hideHelp = true;
@@ -716,6 +921,10 @@ export function createCLI(cfg: CLIConfig): CLIResult {
716
921
  program.option(flag, g.usage, g.default ?? '');
717
922
  }
718
923
 
924
+ // Shell completion scripts call back into `<name> __complete`; answer
925
+ // it ahead of commander's parse so no hook or action runs on tab.
926
+ installCompletionRequest(program);
927
+
719
928
  // Apply brand color scheme + section order to --help output.
720
929
  // noColor is read lazily at render time inside applyHelpTheme.
721
930
  applyHelpTheme(program, theme, false, cfg.help?.sectionOrder,
@@ -0,0 +1,16 @@
1
+ // Code generated by make completion-regen; DO NOT EDIT.
2
+ //
3
+ // cobra's bash (V2), zsh, fish and powershell completion scripts, as the
4
+ // cobra version in go.mod writes them, with the program-dependent parts
5
+ // replaced by @@...@@ tokens (go/console/cli/completion/
6
+ // completion_templates_test.go). Derived from Cobra
7
+ // (https://github.com/spf13/cobra), Copyright 2013-2023 The Cobra
8
+ // Authors, licensed under the Apache License, Version 2.0; the full text
9
+ // is in sdk/ts/LICENSE-cobra.txt.
10
+
11
+ export const SCRIPT_TEMPLATES = {
12
+ bash: "# bash completion V2 for @@NAME_PAD36@@ -*- shell-script -*-\n\n__@@NAME@@_debug()\n{\n if [[ -n ${BASH_COMP_DEBUG_FILE-} ]]; then\n echo \"$*\" >> \"${BASH_COMP_DEBUG_FILE}\"\n fi\n}\n\n# Macs have bash3 for which the bash-completion package doesn't include\n# _init_completion. This is a minimal version of that function.\n__@@NAME@@_init_completion()\n{\n COMPREPLY=()\n _get_comp_words_by_ref \"$@\" cur prev words cword\n}\n\n# This function calls the @@NAME@@ program to obtain the completion\n# results and the directive. It fills the 'out' and 'directive' vars.\n__@@NAME@@_get_completion_results() {\n local requestComp lastParam lastChar args\n\n # Prepare the command to request completions for the program.\n # Calling ${words[0]} instead of directly @@NAME@@ allows handling aliases\n args=(\"${words[@]:1}\")\n requestComp=\"${words[0]} @@COMP_CMD@@ ${args[*]}\"\n\n lastParam=${words[$((${#words[@]}-1))]}\n lastChar=${lastParam:$((${#lastParam}-1)):1}\n __@@NAME@@_debug \"lastParam ${lastParam}, lastChar ${lastChar}\"\n\n if [[ -z ${cur} && ${lastChar} != = ]]; then\n # If the last parameter is complete (there is a space following it)\n # We add an extra empty parameter so we can indicate this to the go method.\n __@@NAME@@_debug \"Adding extra empty parameter\"\n requestComp=\"${requestComp} ''\"\n fi\n\n # When completing a flag with an = (e.g., @@NAME@@ -n=<TAB>)\n # bash focuses on the part after the =, so we need to remove\n # the flag part from $cur\n if [[ ${cur} == -*=* ]]; then\n cur=\"${cur#*=}\"\n fi\n\n __@@NAME@@_debug \"Calling ${requestComp}\"\n # Use eval to handle any environment variables and such\n out=$(eval \"${requestComp}\" 2>/dev/null)\n\n # Extract the directive integer at the very end of the output following a colon (:)\n directive=${out##*:}\n # Remove the directive\n out=${out%:*}\n if [[ ${directive} == \"${out}\" ]]; then\n # There is not directive specified\n directive=0\n fi\n __@@NAME@@_debug \"The completion directive is: ${directive}\"\n __@@NAME@@_debug \"The completions are: ${out}\"\n}\n\n__@@NAME@@_process_completion_results() {\n local shellCompDirectiveError=1\n local shellCompDirectiveNoSpace=2\n local shellCompDirectiveNoFileComp=4\n local shellCompDirectiveFilterFileExt=8\n local shellCompDirectiveFilterDirs=16\n local shellCompDirectiveKeepOrder=32\n\n if (((directive & shellCompDirectiveError) != 0)); then\n # Error code. No completion.\n __@@NAME@@_debug \"Received error from custom completion go code\"\n return\n else\n if (((directive & shellCompDirectiveNoSpace) != 0)); then\n if [[ $(type -t compopt) == builtin ]]; then\n __@@NAME@@_debug \"Activating no space\"\n compopt -o nospace\n else\n __@@NAME@@_debug \"No space directive not supported in this version of bash\"\n fi\n fi\n if (((directive & shellCompDirectiveKeepOrder) != 0)); then\n if [[ $(type -t compopt) == builtin ]]; then\n # no sort isn't supported for bash less than < 4.4\n if [[ ${BASH_VERSINFO[0]} -lt 4 || ( ${BASH_VERSINFO[0]} -eq 4 && ${BASH_VERSINFO[1]} -lt 4 ) ]]; then\n __@@NAME@@_debug \"No sort directive not supported in this version of bash\"\n else\n __@@NAME@@_debug \"Activating keep order\"\n compopt -o nosort\n fi\n else\n __@@NAME@@_debug \"No sort directive not supported in this version of bash\"\n fi\n fi\n if (((directive & shellCompDirectiveNoFileComp) != 0)); then\n if [[ $(type -t compopt) == builtin ]]; then\n __@@NAME@@_debug \"Activating no file completion\"\n compopt +o default\n else\n __@@NAME@@_debug \"No file completion directive not supported in this version of bash\"\n fi\n fi\n fi\n\n # Separate activeHelp from normal completions\n local completions=()\n local activeHelp=()\n __@@NAME@@_extract_activeHelp\n\n if (((directive & shellCompDirectiveFilterFileExt) != 0)); then\n # File extension filtering\n local fullFilter=\"\" filter filteringCmd\n\n # Do not use quotes around the $completions variable or else newline\n # characters will be kept.\n for filter in ${completions[*]}; do\n fullFilter+=\"$filter|\"\n done\n\n filteringCmd=\"_filedir $fullFilter\"\n __@@NAME@@_debug \"File filtering command: $filteringCmd\"\n $filteringCmd\n elif (((directive & shellCompDirectiveFilterDirs) != 0)); then\n # File completion for directories only\n\n local subdir\n subdir=${completions[0]}\n if [[ -n $subdir ]]; then\n __@@NAME@@_debug \"Listing directories in $subdir\"\n pushd \"$subdir\" >/dev/null 2>&1 && _filedir -d && popd >/dev/null 2>&1 || return\n else\n __@@NAME@@_debug \"Listing directories in .\"\n _filedir -d\n fi\n else\n __@@NAME@@_handle_completion_types\n fi\n\n __@@NAME@@_handle_special_char \"$cur\" :\n __@@NAME@@_handle_special_char \"$cur\" =\n\n # Print the activeHelp statements before we finish\n __@@NAME@@_handle_activeHelp\n}\n\n__@@NAME@@_handle_activeHelp() {\n # Print the activeHelp statements\n if ((${#activeHelp[*]} != 0)); then\n if [ -z $COMP_TYPE ]; then\n # Bash v3 does not set the COMP_TYPE variable.\n printf \"\\n\";\n printf \"%s\\n\" \"${activeHelp[@]}\"\n printf \"\\n\"\n __@@NAME@@_reprint_commandLine\n return\n fi\n\n # Only print ActiveHelp on the second TAB press\n if [ $COMP_TYPE -eq 63 ]; then\n printf \"\\n\"\n printf \"%s\\n\" \"${activeHelp[@]}\"\n\n if ((${#COMPREPLY[*]} == 0)); then\n # When there are no completion choices from the program, file completion\n # may kick in if the program has not disabled it; in such a case, we want\n # to know if any files will match what the user typed, so that we know if\n # there will be completions presented, so that we know how to handle ActiveHelp.\n # To find out, we actually trigger the file completion ourselves;\n # the call to _filedir will fill COMPREPLY if files match.\n if (((directive & shellCompDirectiveNoFileComp) == 0)); then\n __@@NAME@@_debug \"Listing files\"\n _filedir\n fi\n fi\n\n if ((${#COMPREPLY[*]} != 0)); then\n # If there are completion choices to be shown, print a delimiter.\n # Re-printing the command-line will automatically be done\n # by the shell when it prints the completion choices.\n printf -- \"--\"\n else\n # When there are no completion choices at all, we need\n # to re-print the command-line since the shell will\n # not be doing it itself.\n __@@NAME@@_reprint_commandLine\n fi\n elif [ $COMP_TYPE -eq 37 ] || [ $COMP_TYPE -eq 42 ]; then\n # For completion type: menu-complete/menu-complete-backward and insert-completions\n # the completions are immediately inserted into the command-line, so we first\n # print the activeHelp message and reprint the command-line since the shell won't.\n printf \"\\n\"\n printf \"%s\\n\" \"${activeHelp[@]}\"\n\n __@@NAME@@_reprint_commandLine\n fi\n fi\n}\n\n__@@NAME@@_reprint_commandLine() {\n # The prompt format is only available from bash 4.4.\n # We test if it is available before using it.\n if (x=${PS1@P}) 2> /dev/null; then\n printf \"%s\" \"${PS1@P}${COMP_LINE[@]}\"\n else\n # Can't print the prompt. Just print the\n # text the user had typed, it is workable enough.\n printf \"%s\" \"${COMP_LINE[@]}\"\n fi\n}\n\n# Separate activeHelp lines from real completions.\n# Fills the $activeHelp and $completions arrays.\n__@@NAME@@_extract_activeHelp() {\n local activeHelpMarker=\"_activeHelp_ \"\n local endIndex=${#activeHelpMarker}\n\n while IFS='' read -r comp; do\n [[ -z $comp ]] && continue\n\n if [[ ${comp:0:endIndex} == $activeHelpMarker ]]; then\n comp=${comp:endIndex}\n __@@NAME@@_debug \"ActiveHelp found: $comp\"\n if [[ -n $comp ]]; then\n activeHelp+=(\"$comp\")\n fi\n else\n # Not an activeHelp line but a normal completion\n completions+=(\"$comp\")\n fi\n done <<<\"${out}\"\n}\n\n__@@NAME@@_handle_completion_types() {\n __@@NAME@@_debug \"__@@NAME@@_handle_completion_types: COMP_TYPE is $COMP_TYPE\"\n\n case $COMP_TYPE in\n 37|42)\n # Type: menu-complete/menu-complete-backward and insert-completions\n # If the user requested inserting one completion at a time, or all\n # completions at once on the command-line we must remove the descriptions.\n # https://github.com/spf13/cobra/issues/1508\n\n # If there are no completions, we don't need to do anything\n (( ${#completions[@]} == 0 )) && return 0\n\n local tab=$'\\t'\n\n # Strip any description and escape the completion to handled special characters\n IFS=$'\\n' read -ra completions -d '' < <(printf \"%q\\n\" \"${completions[@]%%$tab*}\")\n\n # Only consider the completions that match\n IFS=$'\\n' read -ra COMPREPLY -d '' < <(IFS=$'\\n'; compgen -W \"${completions[*]}\" -- \"${cur}\")\n\n # compgen looses the escaping so we need to escape all completions again since they will\n # all be inserted on the command-line.\n IFS=$'\\n' read -ra COMPREPLY -d '' < <(printf \"%q\\n\" \"${COMPREPLY[@]}\")\n ;;\n\n *)\n # Type: complete (normal completion)\n __@@NAME@@_handle_standard_completion_case\n ;;\n esac\n}\n\n__@@NAME@@_handle_standard_completion_case() {\n local tab=$'\\t'\n\n # If there are no completions, we don't need to do anything\n (( ${#completions[@]} == 0 )) && return 0\n\n # Short circuit to optimize if we don't have descriptions\n if [[ \"${completions[*]}\" != *$tab* ]]; then\n # First, escape the completions to handle special characters\n IFS=$'\\n' read -ra completions -d '' < <(printf \"%q\\n\" \"${completions[@]}\")\n # Only consider the completions that match what the user typed\n IFS=$'\\n' read -ra COMPREPLY -d '' < <(IFS=$'\\n'; compgen -W \"${completions[*]}\" -- \"${cur}\")\n\n # compgen looses the escaping so, if there is only a single completion, we need to\n # escape it again because it will be inserted on the command-line. If there are multiple\n # completions, we don't want to escape them because they will be printed in a list\n # and we don't want to show escape characters in that list.\n if (( ${#COMPREPLY[@]} == 1 )); then\n COMPREPLY[0]=$(printf \"%q\" \"${COMPREPLY[0]}\")\n fi\n return 0\n fi\n\n local longest=0\n local compline\n # Look for the longest completion so that we can format things nicely\n while IFS='' read -r compline; do\n [[ -z $compline ]] && continue\n\n # Before checking if the completion matches what the user typed,\n # we need to strip any description and escape the completion to handle special\n # characters because those escape characters are part of what the user typed.\n # Don't call \"printf\" in a sub-shell because it will be much slower\n # since we are in a loop.\n printf -v comp \"%q\" \"${compline%%$tab*}\" &>/dev/null || comp=$(printf \"%q\" \"${compline%%$tab*}\")\n\n # Only consider the completions that match\n [[ $comp == \"$cur\"* ]] || continue\n\n # The completions matches. Add it to the list of full completions including\n # its description. We don't escape the completion because it may get printed\n # in a list if there are more than one and we don't want show escape characters\n # in that list.\n COMPREPLY+=(\"$compline\")\n\n # Strip any description before checking the length, and again, don't escape\n # the completion because this length is only used when printing the completions\n # in a list and we don't want show escape characters in that list.\n comp=${compline%%$tab*}\n if ((${#comp}>longest)); then\n longest=${#comp}\n fi\n done < <(printf \"%s\\n\" \"${completions[@]}\")\n\n # If there is a single completion left, remove the description text and escape any special characters\n if ((${#COMPREPLY[*]} == 1)); then\n __@@NAME@@_debug \"COMPREPLY[0]: ${COMPREPLY[0]}\"\n COMPREPLY[0]=$(printf \"%q\" \"${COMPREPLY[0]%%$tab*}\")\n __@@NAME@@_debug \"Removed description from single completion, which is now: ${COMPREPLY[0]}\"\n else\n # Format the descriptions\n __@@NAME@@_format_comp_descriptions $longest\n fi\n}\n\n__@@NAME@@_handle_special_char()\n{\n local comp=\"$1\"\n local char=$2\n if [[ \"$comp\" == *${char}* && \"$COMP_WORDBREAKS\" == *${char}* ]]; then\n local word=${comp%\"${comp##*${char}}\"}\n local idx=${#COMPREPLY[*]}\n while ((--idx >= 0)); do\n COMPREPLY[idx]=${COMPREPLY[idx]#\"$word\"}\n done\n fi\n}\n\n__@@NAME@@_format_comp_descriptions()\n{\n local tab=$'\\t'\n local comp desc maxdesclength\n local longest=$1\n\n local i ci\n for ci in ${!COMPREPLY[*]}; do\n comp=${COMPREPLY[ci]}\n # Properly format the description string which follows a tab character if there is one\n if [[ \"$comp\" == *$tab* ]]; then\n __@@NAME@@_debug \"Original comp: $comp\"\n desc=${comp#*$tab}\n comp=${comp%%$tab*}\n\n # $COLUMNS stores the current shell width.\n # Remove an extra 4 because we add 2 spaces and 2 parentheses.\n maxdesclength=$(( COLUMNS - longest - 4 ))\n\n # Make sure we can fit a description of at least 8 characters\n # if we are to align the descriptions.\n if ((maxdesclength > 8)); then\n # Add the proper number of spaces to align the descriptions\n for ((i = ${#comp} ; i < longest ; i++)); do\n comp+=\" \"\n done\n else\n # Don't pad the descriptions so we can fit more text after the completion\n maxdesclength=$(( COLUMNS - ${#comp} - 4 ))\n fi\n\n # If there is enough space for any description text,\n # truncate the descriptions that are too long for the shell width\n if ((maxdesclength > 0)); then\n if ((${#desc} > maxdesclength)); then\n desc=${desc:0:$(( maxdesclength - 1 ))}\n desc+=\"…\"\n fi\n comp+=\" ($desc)\"\n fi\n COMPREPLY[ci]=$comp\n __@@NAME@@_debug \"Final comp: $comp\"\n fi\n done\n}\n\n__start_@@NAME@@()\n{\n local cur prev words cword split\n\n COMPREPLY=()\n\n # Call _init_completion from the bash-completion package\n # to prepare the arguments properly\n if declare -F _init_completion >/dev/null 2>&1; then\n _init_completion -n =: || return\n else\n __@@NAME@@_init_completion -n =: || return\n fi\n\n __@@NAME@@_debug\n __@@NAME@@_debug \"========= starting completion logic ==========\"\n __@@NAME@@_debug \"cur is ${cur}, words[*] is ${words[*]}, #words[@] is ${#words[@]}, cword is $cword\"\n\n # The user could have moved the cursor backwards on the command-line.\n # We need to trigger completion from the $cword location, so we need\n # to truncate the command-line ($words) up to the $cword location.\n words=(\"${words[@]:0:$cword+1}\")\n __@@NAME@@_debug \"Truncated words[*]: ${words[*]},\"\n\n local out directive\n __@@NAME@@_get_completion_results\n __@@NAME@@_process_completion_results\n}\n\nif [[ $(type -t compopt) = \"builtin\" ]]; then\n complete -o default -F __start_@@NAME@@ @@NAME@@\nelse\n complete -o default -o nospace -F __start_@@NAME@@ @@NAME@@\nfi\n\n# ex: ts=4 sw=4 et filetype=sh\n",
13
+ zsh: "#compdef @@NAME@@\ncompdef _@@NAME@@ @@NAME@@\n\n# zsh completion for @@NAME_PAD36@@ -*- shell-script -*-\n\n__@@NAME@@_debug()\n{\n local file=\"$BASH_COMP_DEBUG_FILE\"\n if [[ -n ${file} ]]; then\n echo \"$*\" >> \"${file}\"\n fi\n}\n\n_@@NAME@@()\n{\n local shellCompDirectiveError=1\n local shellCompDirectiveNoSpace=2\n local shellCompDirectiveNoFileComp=4\n local shellCompDirectiveFilterFileExt=8\n local shellCompDirectiveFilterDirs=16\n local shellCompDirectiveKeepOrder=32\n\n local lastParam lastChar flagPrefix requestComp out directive comp lastComp noSpace keepOrder\n local -a completions\n\n __@@NAME@@_debug \"\\n========= starting completion logic ==========\"\n __@@NAME@@_debug \"CURRENT: ${CURRENT}, words[*]: ${words[*]}\"\n\n # The user could have moved the cursor backwards on the command-line.\n # We need to trigger completion from the $CURRENT location, so we need\n # to truncate the command-line ($words) up to the $CURRENT location.\n # (We cannot use $CURSOR as its value does not work when a command is an alias.)\n words=(\"${=words[1,CURRENT]}\")\n __@@NAME@@_debug \"Truncated words[*]: ${words[*]},\"\n\n lastParam=${words[-1]}\n lastChar=${lastParam[-1]}\n __@@NAME@@_debug \"lastParam: ${lastParam}, lastChar: ${lastChar}\"\n\n # For zsh, when completing a flag with an = (e.g., @@NAME@@ -n=<TAB>)\n # completions must be prefixed with the flag\n setopt local_options BASH_REMATCH\n if [[ \"${lastParam}\" =~ '-.*=' ]]; then\n # We are dealing with a flag with an =\n flagPrefix=\"-P ${BASH_REMATCH}\"\n fi\n\n # Prepare the command to obtain completions\n requestComp=\"${words[1]} @@COMP_CMD@@ ${words[2,-1]}\"\n if [ \"${lastChar}\" = \"\" ]; then\n # If the last parameter is complete (there is a space following it)\n # We add an extra empty parameter so we can indicate this to the go completion code.\n __@@NAME@@_debug \"Adding extra empty parameter\"\n requestComp=\"${requestComp} \\\"\\\"\"\n fi\n\n __@@NAME@@_debug \"About to call: eval ${requestComp}\"\n\n # Use eval to handle any environment variables and such\n out=$(eval ${requestComp} 2>/dev/null)\n __@@NAME@@_debug \"completion output: ${out}\"\n\n # Extract the directive integer following a : from the last line\n local lastLine\n while IFS='\\n' read -r line; do\n lastLine=${line}\n done < <(printf \"%s\\n\" \"${out[@]}\")\n __@@NAME@@_debug \"last line: ${lastLine}\"\n\n if [ \"${lastLine[1]}\" = : ]; then\n directive=${lastLine[2,-1]}\n # Remove the directive including the : and the newline\n local suffix\n (( suffix=${#lastLine}+2))\n out=${out[1,-$suffix]}\n else\n # There is no directive specified. Leave $out as is.\n __@@NAME@@_debug \"No directive found. Setting do default\"\n directive=0\n fi\n\n __@@NAME@@_debug \"directive: ${directive}\"\n __@@NAME@@_debug \"completions: ${out}\"\n __@@NAME@@_debug \"flagPrefix: ${flagPrefix}\"\n\n if [ $((directive & shellCompDirectiveError)) -ne 0 ]; then\n __@@NAME@@_debug \"Completion received error. Ignoring completions.\"\n return\n fi\n\n local activeHelpMarker=\"_activeHelp_ \"\n local endIndex=${#activeHelpMarker}\n local startIndex=$((${#activeHelpMarker}+1))\n local hasActiveHelp=0\n while IFS='\\n' read -r comp; do\n # Check if this is an activeHelp statement (i.e., prefixed with $activeHelpMarker)\n if [ \"${comp[1,$endIndex]}\" = \"$activeHelpMarker\" ];then\n __@@NAME@@_debug \"ActiveHelp found: $comp\"\n comp=\"${comp[$startIndex,-1]}\"\n if [ -n \"$comp\" ]; then\n compadd -x \"${comp}\"\n __@@NAME@@_debug \"ActiveHelp will need delimiter\"\n hasActiveHelp=1\n fi\n\n continue\n fi\n\n if [ -n \"$comp\" ]; then\n # If requested, completions are returned with a description.\n # The description is preceded by a TAB character.\n # For zsh's _describe, we need to use a : instead of a TAB.\n # We first need to escape any : as part of the completion itself.\n comp=${comp//:/\\\\:}\n\n local tab=\"$(printf '\\t')\"\n comp=${comp//$tab/:}\n\n __@@NAME@@_debug \"Adding completion: ${comp}\"\n completions+=${comp}\n lastComp=$comp\n fi\n done < <(printf \"%s\\n\" \"${out[@]}\")\n\n # Add a delimiter after the activeHelp statements, but only if:\n # - there are completions following the activeHelp statements, or\n # - file completion will be performed (so there will be choices after the activeHelp)\n if [ $hasActiveHelp -eq 1 ]; then\n if [ ${#completions} -ne 0 ] || [ $((directive & shellCompDirectiveNoFileComp)) -eq 0 ]; then\n __@@NAME@@_debug \"Adding activeHelp delimiter\"\n compadd -x \"--\"\n hasActiveHelp=0\n fi\n fi\n\n if [ $((directive & shellCompDirectiveNoSpace)) -ne 0 ]; then\n __@@NAME@@_debug \"Activating nospace.\"\n noSpace=\"-S ''\"\n fi\n\n if [ $((directive & shellCompDirectiveKeepOrder)) -ne 0 ]; then\n __@@NAME@@_debug \"Activating keep order.\"\n keepOrder=\"-V\"\n fi\n\n if [ $((directive & shellCompDirectiveFilterFileExt)) -ne 0 ]; then\n # File extension filtering\n local filteringCmd\n filteringCmd='_files'\n for filter in ${completions[@]}; do\n if [ ${filter[1]} != '*' ]; then\n # zsh requires a glob pattern to do file filtering\n filter=\"\\*.$filter\"\n fi\n filteringCmd+=\" -g $filter\"\n done\n filteringCmd+=\" ${flagPrefix}\"\n\n __@@NAME@@_debug \"File filtering command: $filteringCmd\"\n _arguments '*:filename:'\"$filteringCmd\"\n elif [ $((directive & shellCompDirectiveFilterDirs)) -ne 0 ]; then\n # File completion for directories only\n local subdir\n subdir=\"${completions[1]}\"\n if [ -n \"$subdir\" ]; then\n __@@NAME@@_debug \"Listing directories in $subdir\"\n pushd \"${subdir}\" >/dev/null 2>&1\n else\n __@@NAME@@_debug \"Listing directories in .\"\n fi\n\n local result\n _arguments '*:dirname:_files -/'\" ${flagPrefix}\"\n result=$?\n if [ -n \"$subdir\" ]; then\n popd >/dev/null 2>&1\n fi\n return $result\n else\n __@@NAME@@_debug \"Calling _describe\"\n if eval _describe $keepOrder \"completions\" completions $flagPrefix $noSpace; then\n __@@NAME@@_debug \"_describe found some completions\"\n\n # Return the success of having called _describe\n return 0\n else\n __@@NAME@@_debug \"_describe did not find completions.\"\n __@@NAME@@_debug \"Checking if we should do file completion.\"\n if [ $((directive & shellCompDirectiveNoFileComp)) -ne 0 ]; then\n __@@NAME@@_debug \"deactivating file completion\"\n\n # We must return an error code here to let zsh know that there were no\n # completions found by _describe; this is what will trigger other\n # matching algorithms to attempt to find completions.\n # For example zsh can match letters in the middle of words.\n return 1\n else\n # Perform file completion\n __@@NAME@@_debug \"Activating file completion\"\n\n # We must return the result of this command, so it must be the\n # last command, or else we must store its result to return it.\n _arguments '*:filename:_files'\" ${flagPrefix}\"\n fi\n fi\n fi\n}\n\n# don't run the completion function when being source-ed or eval-ed\nif [ \"$funcstack[1]\" = \"_@@NAME@@\" ]; then\n _@@NAME@@\nfi\n",
14
+ fish: "# fish completion for @@NAME_PAD36@@ -*- shell-script -*-\n\nfunction __@@NAME_VAR@@_debug\n set -l file \"$BASH_COMP_DEBUG_FILE\"\n if test -n \"$file\"\n echo \"$argv\" >> $file\n end\nend\n\nfunction __@@NAME_VAR@@_perform_completion\n __@@NAME_VAR@@_debug \"Starting __@@NAME_VAR@@_perform_completion\"\n\n # Extract all args except the last one\n set -l args (commandline -opc)\n # Extract the last arg and escape it in case it is a space\n set -l lastArg (string escape -- (commandline -ct))\n\n __@@NAME_VAR@@_debug \"args: $args\"\n __@@NAME_VAR@@_debug \"last arg: $lastArg\"\n\n # Disable ActiveHelp which is not supported for fish shell\n set -l requestComp \"@@ACTIVE_HELP_VAR@@=0 $args[1] @@COMP_CMD@@ $args[2..-1] $lastArg\"\n\n __@@NAME_VAR@@_debug \"Calling $requestComp\"\n set -l results (eval $requestComp 2> /dev/null)\n\n # Some programs may output extra empty lines after the directive.\n # Let's ignore them or else it will break completion.\n # Ref: https://github.com/spf13/cobra/issues/1279\n for line in $results[-1..1]\n if test (string trim -- $line) = \"\"\n # Found an empty line, remove it\n set results $results[1..-2]\n else\n # Found non-empty line, we have our proper output\n break\n end\n end\n\n set -l comps $results[1..-2]\n set -l directiveLine $results[-1]\n\n # For Fish, when completing a flag with an = (e.g., <program> -n=<TAB>)\n # completions must be prefixed with the flag\n set -l flagPrefix (string match -r -- '-.*=' \"$lastArg\")\n\n __@@NAME_VAR@@_debug \"Comps: $comps\"\n __@@NAME_VAR@@_debug \"DirectiveLine: $directiveLine\"\n __@@NAME_VAR@@_debug \"flagPrefix: $flagPrefix\"\n\n for comp in $comps\n printf \"%s%s\\n\" \"$flagPrefix\" \"$comp\"\n end\n\n printf \"%s\\n\" \"$directiveLine\"\nend\n\n# this function limits calls to __@@NAME_VAR@@_perform_completion, by caching the result behind $__@@NAME_VAR@@_perform_completion_once_result\nfunction __@@NAME_VAR@@_perform_completion_once\n __@@NAME_VAR@@_debug \"Starting __@@NAME_VAR@@_perform_completion_once\"\n\n if test -n \"$__@@NAME_VAR@@_perform_completion_once_result\"\n __@@NAME_VAR@@_debug \"Seems like a valid result already exists, skipping __@@NAME_VAR@@_perform_completion\"\n return 0\n end\n\n set --global __@@NAME_VAR@@_perform_completion_once_result (__@@NAME_VAR@@_perform_completion)\n if test -z \"$__@@NAME_VAR@@_perform_completion_once_result\"\n __@@NAME_VAR@@_debug \"No completions, probably due to a failure\"\n return 1\n end\n\n __@@NAME_VAR@@_debug \"Performed completions and set __@@NAME_VAR@@_perform_completion_once_result\"\n return 0\nend\n\n# this function is used to clear the $__@@NAME_VAR@@_perform_completion_once_result variable after completions are run\nfunction __@@NAME_VAR@@_clear_perform_completion_once_result\n __@@NAME_VAR@@_debug \"\"\n __@@NAME_VAR@@_debug \"========= clearing previously set __@@NAME_VAR@@_perform_completion_once_result variable ==========\"\n set --erase __@@NAME_VAR@@_perform_completion_once_result\n __@@NAME_VAR@@_debug \"Successfully erased the variable __@@NAME_VAR@@_perform_completion_once_result\"\nend\n\nfunction __@@NAME_VAR@@_requires_order_preservation\n __@@NAME_VAR@@_debug \"\"\n __@@NAME_VAR@@_debug \"========= checking if order preservation is required ==========\"\n\n __@@NAME_VAR@@_perform_completion_once\n if test -z \"$__@@NAME_VAR@@_perform_completion_once_result\"\n __@@NAME_VAR@@_debug \"Error determining if order preservation is required\"\n return 1\n end\n\n set -l directive (string sub --start 2 $__@@NAME_VAR@@_perform_completion_once_result[-1])\n __@@NAME_VAR@@_debug \"Directive is: $directive\"\n\n set -l shellCompDirectiveKeepOrder 32\n set -l keeporder (math (math --scale 0 $directive / $shellCompDirectiveKeepOrder) % 2)\n __@@NAME_VAR@@_debug \"Keeporder is: $keeporder\"\n\n if test $keeporder -ne 0\n __@@NAME_VAR@@_debug \"This does require order preservation\"\n return 0\n end\n\n __@@NAME_VAR@@_debug \"This doesn't require order preservation\"\n return 1\nend\n\n\n# This function does two things:\n# - Obtain the completions and store them in the global __@@NAME_VAR@@_comp_results\n# - Return false if file completion should be performed\nfunction __@@NAME_VAR@@_prepare_completions\n __@@NAME_VAR@@_debug \"\"\n __@@NAME_VAR@@_debug \"========= starting completion logic ==========\"\n\n # Start fresh\n set --erase __@@NAME_VAR@@_comp_results\n\n __@@NAME_VAR@@_perform_completion_once\n __@@NAME_VAR@@_debug \"Completion results: $__@@NAME_VAR@@_perform_completion_once_result\"\n\n if test -z \"$__@@NAME_VAR@@_perform_completion_once_result\"\n __@@NAME_VAR@@_debug \"No completion, probably due to a failure\"\n # Might as well do file completion, in case it helps\n return 1\n end\n\n set -l directive (string sub --start 2 $__@@NAME_VAR@@_perform_completion_once_result[-1])\n set --global __@@NAME_VAR@@_comp_results $__@@NAME_VAR@@_perform_completion_once_result[1..-2]\n\n __@@NAME_VAR@@_debug \"Completions are: $__@@NAME_VAR@@_comp_results\"\n __@@NAME_VAR@@_debug \"Directive is: $directive\"\n\n set -l shellCompDirectiveError 1\n set -l shellCompDirectiveNoSpace 2\n set -l shellCompDirectiveNoFileComp 4\n set -l shellCompDirectiveFilterFileExt 8\n set -l shellCompDirectiveFilterDirs 16\n\n if test -z \"$directive\"\n set directive 0\n end\n\n set -l compErr (math (math --scale 0 $directive / $shellCompDirectiveError) % 2)\n if test $compErr -eq 1\n __@@NAME_VAR@@_debug \"Received error directive: aborting.\"\n # Might as well do file completion, in case it helps\n return 1\n end\n\n set -l filefilter (math (math --scale 0 $directive / $shellCompDirectiveFilterFileExt) % 2)\n set -l dirfilter (math (math --scale 0 $directive / $shellCompDirectiveFilterDirs) % 2)\n if test $filefilter -eq 1; or test $dirfilter -eq 1\n __@@NAME_VAR@@_debug \"File extension filtering or directory filtering not supported\"\n # Do full file completion instead\n return 1\n end\n\n set -l nospace (math (math --scale 0 $directive / $shellCompDirectiveNoSpace) % 2)\n set -l nofiles (math (math --scale 0 $directive / $shellCompDirectiveNoFileComp) % 2)\n\n __@@NAME_VAR@@_debug \"nospace: $nospace, nofiles: $nofiles\"\n\n # If we want to prevent a space, or if file completion is NOT disabled,\n # we need to count the number of valid completions.\n # To do so, we will filter on prefix as the completions we have received\n # may not already be filtered so as to allow fish to match on different\n # criteria than the prefix.\n if test $nospace -ne 0; or test $nofiles -eq 0\n set -l prefix (commandline -t | string escape --style=regex)\n __@@NAME_VAR@@_debug \"prefix: $prefix\"\n\n set -l completions (string match -r -- \"^$prefix.*\" $__@@NAME_VAR@@_comp_results)\n set --global __@@NAME_VAR@@_comp_results $completions\n __@@NAME_VAR@@_debug \"Filtered completions are: $__@@NAME_VAR@@_comp_results\"\n\n # Important not to quote the variable for count to work\n set -l numComps (count $__@@NAME_VAR@@_comp_results)\n __@@NAME_VAR@@_debug \"numComps: $numComps\"\n\n if test $numComps -eq 1; and test $nospace -ne 0\n # We must first split on \\t to get rid of the descriptions to be\n # able to check what the actual completion will be.\n # We don't need descriptions anyway since there is only a single\n # real completion which the shell will expand immediately.\n set -l split (string split --max 1 \\t $__@@NAME_VAR@@_comp_results[1])\n\n # Fish won't add a space if the completion ends with any\n # of the following characters: @=/:.,\n set -l lastChar (string sub -s -1 -- $split)\n if not string match -r -q \"[@=/:.,]\" -- \"$lastChar\"\n # In other cases, to support the \"nospace\" directive we trick the shell\n # by outputting an extra, longer completion.\n __@@NAME_VAR@@_debug \"Adding second completion to perform nospace directive\"\n set --global __@@NAME_VAR@@_comp_results $split[1] $split[1].\n __@@NAME_VAR@@_debug \"Completions are now: $__@@NAME_VAR@@_comp_results\"\n end\n end\n\n if test $numComps -eq 0; and test $nofiles -eq 0\n # To be consistent with bash and zsh, we only trigger file\n # completion when there are no other completions\n __@@NAME_VAR@@_debug \"Requesting file completion\"\n return 1\n end\n end\n\n return 0\nend\n\n# Since Fish completions are only loaded once the user triggers them, we trigger them ourselves\n# so we can properly delete any completions provided by another script.\n# Only do this if the program can be found, or else fish may print some errors; besides,\n# the existing completions will only be loaded if the program can be found.\nif type -q \"@@NAME@@\"\n # The space after the program name is essential to trigger completion for the program\n # and not completion of the program name itself.\n # Also, we use '> /dev/null 2>&1' since '&>' is not supported in older versions of fish.\n complete --do-complete \"@@NAME@@ \" > /dev/null 2>&1\nend\n\n# Remove any pre-existing completions for the program since we will be handling all of them.\ncomplete -c @@NAME@@ -e\n\n# this will get called after the two calls below and clear the $__@@NAME_VAR@@_perform_completion_once_result global\ncomplete -c @@NAME@@ -n '__@@NAME_VAR@@_clear_perform_completion_once_result'\n# The call to __@@NAME_VAR@@_prepare_completions will setup __@@NAME_VAR@@_comp_results\n# which provides the program's completion choices.\n# If this doesn't require order preservation, we don't use the -k flag\ncomplete -c @@NAME@@ -n 'not __@@NAME_VAR@@_requires_order_preservation && __@@NAME_VAR@@_prepare_completions' -f -a '$__@@NAME_VAR@@_comp_results'\n# otherwise we use the -k flag\ncomplete -k -c @@NAME@@ -n '__@@NAME_VAR@@_requires_order_preservation && __@@NAME_VAR@@_prepare_completions' -f -a '$__@@NAME_VAR@@_comp_results'\n",
15
+ powershell: "# powershell completion for @@NAME_PAD36@@ -*- shell-script -*-\n\nfunction __@@NAME@@_debug {\n if ($env:BASH_COMP_DEBUG_FILE) {\n \"$args\" | Out-File -Append -FilePath \"$env:BASH_COMP_DEBUG_FILE\"\n }\n}\n\nfilter __@@NAME@@_escapeStringWithSpecialChars {\n $_ -replace '\\s|#|@|\\$|;|,|''|\\{|\\}|\\(|\\)|\"|`|\\||<|>|&','`$&'\n}\n\n[scriptblock]${__@@NAME_VAR@@CompleterBlock} = {\n param(\n $WordToComplete,\n $CommandAst,\n $CursorPosition\n )\n\n # Get the current command line and convert into a string\n $Command = $CommandAst.CommandElements\n $Command = \"$Command\"\n\n __@@NAME@@_debug \"\"\n __@@NAME@@_debug \"========= starting completion logic ==========\"\n __@@NAME@@_debug \"WordToComplete: $WordToComplete Command: $Command CursorPosition: $CursorPosition\"\n\n # The user could have moved the cursor backwards on the command-line.\n # We need to trigger completion from the $CursorPosition location, so we need\n # to truncate the command-line ($Command) up to the $CursorPosition location.\n # Make sure the $Command is longer then the $CursorPosition before we truncate.\n # This happens because the $Command does not include the last space.\n if ($Command.Length -gt $CursorPosition) {\n $Command=$Command.Substring(0,$CursorPosition)\n }\n __@@NAME@@_debug \"Truncated command: $Command\"\n\n $ShellCompDirectiveError=1\n $ShellCompDirectiveNoSpace=2\n $ShellCompDirectiveNoFileComp=4\n $ShellCompDirectiveFilterFileExt=8\n $ShellCompDirectiveFilterDirs=16\n $ShellCompDirectiveKeepOrder=32\n\n # Prepare the command to request completions for the program.\n # Split the command at the first space to separate the program and arguments.\n $Program,$Arguments = $Command.Split(\" \",2)\n\n $RequestComp=\"$Program @@COMP_CMD@@ $Arguments\"\n __@@NAME@@_debug \"RequestComp: $RequestComp\"\n\n # we cannot use $WordToComplete because it\n # has the wrong values if the cursor was moved\n # so use the last argument\n if ($WordToComplete -ne \"\" ) {\n $WordToComplete = $Arguments.Split(\" \")[-1]\n }\n __@@NAME@@_debug \"New WordToComplete: $WordToComplete\"\n\n\n # Check for flag with equal sign\n $IsEqualFlag = ($WordToComplete -Like \"--*=*\" )\n if ( $IsEqualFlag ) {\n __@@NAME@@_debug \"Completing equal sign flag\"\n # Remove the flag part\n $Flag,$WordToComplete = $WordToComplete.Split(\"=\",2)\n }\n\n if ( $WordToComplete -eq \"\" -And ( -Not $IsEqualFlag )) {\n # If the last parameter is complete (there is a space following it)\n # We add an extra empty parameter so we can indicate this to the go method.\n __@@NAME@@_debug \"Adding extra empty parameter\"\n # PowerShell 7.2+ changed the way how the arguments are passed to executables,\n # so for pre-7.2 or when Legacy argument passing is enabled we need to use\n # `\"`\" to pass an empty argument, a \"\" or '' does not work!!!\n if ($PSVersionTable.PsVersion -lt [version]'7.2.0' -or\n ($PSVersionTable.PsVersion -lt [version]'7.3.0' -and -not [ExperimentalFeature]::IsEnabled(\"PSNativeCommandArgumentPassing\")) -or\n (($PSVersionTable.PsVersion -ge [version]'7.3.0' -or [ExperimentalFeature]::IsEnabled(\"PSNativeCommandArgumentPassing\")) -and\n $PSNativeCommandArgumentPassing -eq 'Legacy')) {\n $RequestComp=\"$RequestComp\" + ' `\"`\"'\n } else {\n $RequestComp=\"$RequestComp\" + ' \"\"'\n }\n }\n\n __@@NAME@@_debug \"Calling $RequestComp\"\n # First disable ActiveHelp which is not supported for Powershell\n ${env:@@ACTIVE_HELP_VAR@@}=0\n\n #call the command store the output in $out and redirect stderr and stdout to null\n # $Out is an array contains each line per element\n Invoke-Expression -OutVariable out \"$RequestComp\" 2>&1 | Out-Null\n\n # get directive from last line\n [int]$Directive = $Out[-1].TrimStart(':')\n if ($Directive -eq \"\") {\n # There is no directive specified\n $Directive = 0\n }\n __@@NAME@@_debug \"The completion directive is: $Directive\"\n\n # remove directive (last element) from out\n $Out = $Out | Where-Object { $_ -ne $Out[-1] }\n __@@NAME@@_debug \"The completions are: $Out\"\n\n if (($Directive -band $ShellCompDirectiveError) -ne 0 ) {\n # Error code. No completion.\n __@@NAME@@_debug \"Received error from custom completion go code\"\n return\n }\n\n $Longest = 0\n [Array]$Values = $Out | ForEach-Object {\n #Split the output in name and description\n $Name, $Description = $_.Split(\"`t\",2)\n __@@NAME@@_debug \"Name: $Name Description: $Description\"\n\n # Look for the longest completion so that we can format things nicely\n if ($Longest -lt $Name.Length) {\n $Longest = $Name.Length\n }\n\n # Set the description to a one space string if there is none set.\n # This is needed because the CompletionResult does not accept an empty string as argument\n if (-Not $Description) {\n $Description = \" \"\n }\n New-Object -TypeName PSCustomObject -Property @{\n Name = \"$Name\"\n Description = \"$Description\"\n }\n }\n\n\n $Space = \" \"\n if (($Directive -band $ShellCompDirectiveNoSpace) -ne 0 ) {\n # remove the space here\n __@@NAME@@_debug \"ShellCompDirectiveNoSpace is called\"\n $Space = \"\"\n }\n\n if ((($Directive -band $ShellCompDirectiveFilterFileExt) -ne 0 ) -or\n (($Directive -band $ShellCompDirectiveFilterDirs) -ne 0 )) {\n __@@NAME@@_debug \"ShellCompDirectiveFilterFileExt ShellCompDirectiveFilterDirs are not supported\"\n\n # return here to prevent the completion of the extensions\n return\n }\n\n $Values = $Values | Where-Object {\n # filter the result\n $_.Name -like \"$WordToComplete*\"\n\n # Join the flag back if we have an equal sign flag\n if ( $IsEqualFlag ) {\n __@@NAME@@_debug \"Join the equal sign flag back to the completion value\"\n $_.Name = $Flag + \"=\" + $_.Name\n }\n }\n\n # we sort the values in ascending order by name if keep order isn't passed\n if (($Directive -band $ShellCompDirectiveKeepOrder) -eq 0 ) {\n $Values = $Values | Sort-Object -Property Name\n }\n\n if (($Directive -band $ShellCompDirectiveNoFileComp) -ne 0 ) {\n __@@NAME@@_debug \"ShellCompDirectiveNoFileComp is called\"\n\n if ($Values.Length -eq 0) {\n # Just print an empty string here so the\n # shell does not start to complete paths.\n # We cannot use CompletionResult here because\n # it does not accept an empty string as argument.\n \"\"\n return\n }\n }\n\n # Get the current mode\n $Mode = (Get-PSReadLineKeyHandler | Where-Object {$_.Key -eq \"Tab\" }).Function\n __@@NAME@@_debug \"Mode: $Mode\"\n\n $Values | ForEach-Object {\n\n # store temporary because switch will overwrite $_\n $comp = $_\n\n # PowerShell supports three different completion modes\n # - TabCompleteNext (default windows style - on each key press the next option is displayed)\n # - Complete (works like bash)\n # - MenuComplete (works like zsh)\n # You set the mode with Set-PSReadLineKeyHandler -Key Tab -Function <mode>\n\n # CompletionResult Arguments:\n # 1) CompletionText text to be used as the auto completion result\n # 2) ListItemText text to be displayed in the suggestion list\n # 3) ResultType type of completion result\n # 4) ToolTip text for the tooltip with details about the object\n\n switch ($Mode) {\n\n # bash like\n \"Complete\" {\n\n if ($Values.Length -eq 1) {\n __@@NAME@@_debug \"Only one completion left\"\n\n # insert space after value\n $CompletionText = $($comp.Name | __@@NAME@@_escapeStringWithSpecialChars) + $Space\n if ($ExecutionContext.SessionState.LanguageMode -eq \"FullLanguage\"){\n [System.Management.Automation.CompletionResult]::new($CompletionText, \"$($comp.Name)\", 'ParameterValue', \"$($comp.Description)\")\n } else {\n $CompletionText\n }\n\n } else {\n # Add the proper number of spaces to align the descriptions\n while($comp.Name.Length -lt $Longest) {\n $comp.Name = $comp.Name + \" \"\n }\n\n # Check for empty description and only add parentheses if needed\n if ($($comp.Description) -eq \" \" ) {\n $Description = \"\"\n } else {\n $Description = \" ($($comp.Description))\"\n }\n\n $CompletionText = \"$($comp.Name)$Description\"\n if ($ExecutionContext.SessionState.LanguageMode -eq \"FullLanguage\"){\n [System.Management.Automation.CompletionResult]::new($CompletionText, \"$($comp.Name)$Description\", 'ParameterValue', \"$($comp.Description)\")\n } else {\n $CompletionText\n }\n }\n }\n\n # zsh like\n \"MenuComplete\" {\n # insert space after value\n # MenuComplete will automatically show the ToolTip of\n # the highlighted value at the bottom of the suggestions.\n\n $CompletionText = $($comp.Name | __@@NAME@@_escapeStringWithSpecialChars) + $Space\n if ($ExecutionContext.SessionState.LanguageMode -eq \"FullLanguage\"){\n [System.Management.Automation.CompletionResult]::new($CompletionText, \"$($comp.Name)\", 'ParameterValue', \"$($comp.Description)\")\n } else {\n $CompletionText\n }\n }\n\n # TabCompleteNext and in case we get something unknown\n Default {\n # Like MenuComplete but we don't want to add a space here because\n # the user need to press space anyway to get the completion.\n # Description will not be shown because that's not possible with TabCompleteNext\n\n $CompletionText = $($comp.Name | __@@NAME@@_escapeStringWithSpecialChars)\n if ($ExecutionContext.SessionState.LanguageMode -eq \"FullLanguage\"){\n [System.Management.Automation.CompletionResult]::new($CompletionText, \"$($comp.Name)\", 'ParameterValue', \"$($comp.Description)\")\n } else {\n $CompletionText\n }\n }\n }\n\n }\n}\n\nRegister-ArgumentCompleter -CommandName '@@NAME@@' -ScriptBlock ${__@@NAME_VAR@@CompleterBlock}\n",
16
+ } as const;
@@ -8,6 +8,9 @@ import {
8
8
  configKeysCompleter,
9
9
  fileCompleter,
10
10
  dirCompleter,
11
+ resolveCompletions,
12
+ directiveName,
13
+ ShellCompDirective,
11
14
  type CompletionItem,
12
15
  } from './completion-values';
13
16
 
@@ -84,7 +87,7 @@ describe('prefixedCompleter', () => {
84
87
  const inner = staticValues('a', 'b');
85
88
  const c = prefixedCompleter('env', inner);
86
89
  const result = c.complete('');
87
- expect(result).toEqual([{ value: 'env:', description: 'env:...' }]);
90
+ expect(result).toEqual([{ value: 'env:', description: 'env values' }]);
88
91
  });
89
92
 
90
93
  it('completes values after colon', () => {
@@ -112,47 +115,104 @@ describe('prefixedCompleter', () => {
112
115
  });
113
116
 
114
117
  describe('configKeysCompleter', () => {
115
- it('returns top-level keys', () => {
118
+ it('returns top-level keys', async () => {
116
119
  const c = configKeysCompleter({ name: 'x', version: '1', debug: true });
117
- const items = c.complete('');
120
+ const items = await c.complete('');
118
121
  const values = items.map((i: CompletionItem) => i.value);
119
122
  expect(values).toContain('name');
120
123
  expect(values).toContain('version');
121
124
  expect(values).toContain('debug');
122
125
  });
123
126
 
124
- it('returns nested keys with dot notation', () => {
127
+ it('returns nested keys with dot notation', async () => {
125
128
  const c = configKeysCompleter({ db: { host: 'localhost', port: 5432 } });
126
- const items = c.complete('db.');
129
+ const items = await c.complete('db.');
127
130
  const values = items.map((i: CompletionItem) => i.value);
128
131
  expect(values).toContain('db.host');
129
132
  expect(values).toContain('db.port');
130
133
  });
131
134
 
132
- it('filters by prefix', () => {
135
+ it('returns leaf keys only, lowercased', async () => {
136
+ const c = configKeysCompleter({ Server: { Port: 1 }, tags: ['a'] });
137
+ const values = (await c.complete('')).map((i: CompletionItem) => i.value);
138
+ expect(values).toEqual(['server.port', 'tags']);
139
+ expect((await c.complete('SER')).map((i: CompletionItem) => i.value))
140
+ .toEqual(['server.port']);
141
+ });
142
+
143
+ it('filters by prefix', async () => {
133
144
  const c = configKeysCompleter({ name: 'x', namespace: 'y', version: '1' });
134
- const items = c.complete('na');
145
+ const items = await c.complete('na');
135
146
  const values = items.map((i: CompletionItem) => i.value);
136
147
  expect(values).toEqual(['name', 'namespace']);
137
148
  });
138
149
  });
139
150
 
140
151
  describe('fileCompleter', () => {
141
- it('returns items with value field', () => {
152
+ it('returns its extensions and filters by extension', async () => {
142
153
  const c = fileCompleter('.ts', '.js');
143
- const items = c.complete('');
144
- // file completer returns a marker item for shell-level file completion
145
- expect(items.length).toBeGreaterThanOrEqual(1);
146
- expect(items[0]).toHaveProperty('value');
154
+ expect(await c.complete('')).toEqual([{ value: '.ts' }, { value: '.js' }]);
155
+ expect(await resolveCompletions(c, 'x')).toEqual({
156
+ completions: ['.ts', '.js'], directive: ShellCompDirective.FilterFileExt,
157
+ });
158
+ });
159
+
160
+ it('without extensions falls back to default completion', async () => {
161
+ expect(await resolveCompletions(fileCompleter(), '')).toEqual({
162
+ completions: [], directive: ShellCompDirective.Default,
163
+ });
147
164
  });
148
165
  });
149
166
 
150
167
  describe('dirCompleter', () => {
151
- it('returns items with value field', () => {
168
+ it('completes directories only', async () => {
152
169
  const c = dirCompleter();
153
- const items = c.complete('');
154
- expect(items.length).toBeGreaterThanOrEqual(1);
155
- expect(items[0]).toHaveProperty('value');
170
+ expect(await c.complete('')).toEqual([]);
171
+ expect(await resolveCompletions(c, 'src')).toEqual({
172
+ completions: [], directive: ShellCompDirective.FilterDirs,
173
+ });
174
+ });
175
+ });
176
+
177
+ describe('resolveCompletions', () => {
178
+ it('joins descriptions with a tab and completes no files', async () => {
179
+ const c = staticCompleter({ value: 'a', description: 'A' }, { value: 'b' });
180
+ expect(await resolveCompletions(c, '')).toEqual({
181
+ completions: ['a\tA', 'b'], directive: ShellCompDirective.NoFileComp,
182
+ });
183
+ });
184
+
185
+ it('turns a thrown or rejected completer into the error directive', async () => {
186
+ const sync = funcCompleter(() => { throw new Error('down'); });
187
+ const rejected = funcCompleter(async () => { throw new Error('down'); });
188
+ for (const c of [sync, rejected, prefixedCompleter('env', rejected)]) {
189
+ expect(await resolveCompletions(c, 'env:')).toEqual({
190
+ completions: [], directive: ShellCompDirective.Error,
191
+ });
192
+ }
193
+ });
194
+
195
+ it('passes the context through to the completer', async () => {
196
+ let seen;
197
+ const c = funcCompleter((_p, ctx) => { seen = ctx; return []; });
198
+ await resolveCompletions(c, '', { commandPath: 'deploy', args: ['x'] });
199
+ expect(seen).toEqual({ commandPath: 'deploy', args: ['x'] });
200
+ });
201
+
202
+ it('awaits async inner completers of prefixed', async () => {
203
+ const c = prefixedCompleter('env', funcCompleter(async () => [{ value: 'prod' }]));
204
+ expect(await resolveCompletions(c, 'env:')).toEqual({
205
+ completions: ['env:prod'], directive: ShellCompDirective.NoFileComp,
206
+ });
207
+ });
208
+ });
209
+
210
+ describe('directiveName', () => {
211
+ it('names cobra directives', () => {
212
+ expect(directiveName(0)).toBe('ShellCompDirectiveDefault');
213
+ expect(directiveName(4)).toBe('ShellCompDirectiveNoFileComp');
214
+ expect(directiveName(6)).toBe('ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp');
215
+ expect(directiveName(64)).toBe('ERROR: unexpected ShellCompDirective value: 64');
156
216
  });
157
217
  });
158
218