@neta-art/cohub-cli 10.24.0 → 10.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (368) hide show
  1. package/bin/cohub.js +4 -1
  2. package/dist/board-gpu/page.js +1566 -71230
  3. package/dist/bootstrap.js +67 -27
  4. package/dist/build.json +1 -1
  5. package/dist/{board-kernel/FilterPipe.js → chunks/Geometry.js} +10447 -10469
  6. package/dist/chunks/about.js +102 -0
  7. package/dist/chunks/app-realtime.js +2216 -0
  8. package/dist/chunks/app-realtime2.js +2 -0
  9. package/dist/chunks/app-ref.js +88 -0
  10. package/dist/chunks/apps.js +1423 -0
  11. package/dist/chunks/auth.js +175 -0
  12. package/dist/chunks/avatar.js +146 -0
  13. package/dist/chunks/board-export-resources.js +232 -0
  14. package/dist/chunks/board-export.js +874 -0
  15. package/dist/chunks/board-export2.js +2 -0
  16. package/dist/{board-kernel.js → chunks/board-kernel.js} +18032 -28512
  17. package/dist/chunks/board-kernel2.js +4 -0
  18. package/dist/chunks/board-profile.js +69 -0
  19. package/dist/chunks/board-simulate.js +315 -0
  20. package/dist/chunks/board-time.js +34 -0
  21. package/dist/chunks/boards.js +1943 -0
  22. package/dist/{board-kernel → chunks}/browserAll.js +9 -8
  23. package/dist/chunks/channels.js +64 -0
  24. package/dist/chunks/client.js +12606 -0
  25. package/dist/chunks/command-input.js +17 -0
  26. package/dist/chunks/commander.js +2962 -0
  27. package/dist/chunks/cron-jobs.js +163 -0
  28. package/dist/chunks/daemon.js +545 -0
  29. package/dist/chunks/daemon2.js +2 -0
  30. package/dist/chunks/desktop.js +172 -0
  31. package/dist/chunks/endpoint-options.js +26 -0
  32. package/dist/chunks/env-proxy.js +35 -0
  33. package/dist/chunks/environment.js +154 -0
  34. package/dist/chunks/feedback.js +120 -0
  35. package/dist/chunks/generations.js +379 -0
  36. package/dist/chunks/host.js +9 -0
  37. package/dist/chunks/http-put.js +131 -0
  38. package/dist/chunks/id.js +2416 -0
  39. package/dist/{board-kernel → chunks}/init.js +1 -1
  40. package/dist/chunks/install.js +11959 -0
  41. package/dist/chunks/launch.js +374 -0
  42. package/dist/chunks/local-media.js +47 -0
  43. package/dist/chunks/me.js +134 -0
  44. package/dist/chunks/media.js +315 -0
  45. package/dist/chunks/models.js +242 -0
  46. package/dist/chunks/operands.js +46 -0
  47. package/dist/chunks/package-paths.js +13 -0
  48. package/dist/chunks/policy.js +221 -0
  49. package/dist/chunks/preferences.js +29 -0
  50. package/dist/chunks/profile.js +64 -0
  51. package/dist/chunks/prompts.js +41 -0
  52. package/dist/chunks/public.js +2 -0
  53. package/dist/chunks/public2.js +244 -0
  54. package/dist/chunks/references.js +197 -0
  55. package/dist/chunks/referrals.js +90 -0
  56. package/dist/chunks/rolldown-runtime.js +26 -0
  57. package/dist/chunks/rooms-connect.js +2 -0
  58. package/dist/chunks/rooms-connect2.js +151 -0
  59. package/dist/chunks/rooms-rtc.js +309 -0
  60. package/dist/chunks/rooms.js +211 -0
  61. package/dist/chunks/run.js +220 -0
  62. package/dist/chunks/runtime.js +638 -0
  63. package/dist/chunks/runtime2.js +286 -0
  64. package/dist/chunks/runtimes.js +48 -0
  65. package/dist/chunks/safe-remote-image.js +198 -0
  66. package/dist/chunks/schemas.js +6017 -0
  67. package/dist/chunks/search.js +113 -0
  68. package/dist/chunks/self-update.js +238 -0
  69. package/dist/chunks/serve.js +1246 -0
  70. package/dist/chunks/session-status.js +24 -0
  71. package/dist/chunks/skills.js +35 -0
  72. package/dist/chunks/spaces.js +5080 -0
  73. package/dist/chunks/src.js +405 -0
  74. package/dist/chunks/supervisor.js +2511 -0
  75. package/dist/chunks/supervisor2.js +2 -0
  76. package/dist/chunks/tasks.js +82 -0
  77. package/dist/chunks/themes.js +2898 -0
  78. package/dist/chunks/version.js +2 -0
  79. package/dist/chunks/version2.js +22 -0
  80. package/dist/chunks/version3.js +18 -0
  81. package/dist/chunks/web.js +7 -0
  82. package/dist/{board-kernel → chunks}/webworkerAll.js +1 -1
  83. package/dist/runtime/native/pi-extension.js +174 -166
  84. package/dist/runtime/worker.js +27 -16
  85. package/package.json +8 -9
  86. package/dist/about.d.ts +0 -2
  87. package/dist/about.js +0 -71
  88. package/dist/app-download.d.ts +0 -11
  89. package/dist/app-download.js +0 -252
  90. package/dist/app-ref.d.ts +0 -5
  91. package/dist/app-ref.js +0 -8
  92. package/dist/app-target.d.ts +0 -26
  93. package/dist/app-target.js +0 -55
  94. package/dist/auth.d.ts +0 -45
  95. package/dist/auth.js +0 -307
  96. package/dist/avatar.d.ts +0 -55
  97. package/dist/avatar.js +0 -104
  98. package/dist/board-command-support.d.ts +0 -6
  99. package/dist/board-command-support.js +0 -88
  100. package/dist/board-export-resources.d.ts +0 -12
  101. package/dist/board-export-resources.js +0 -51
  102. package/dist/board-export.d.ts +0 -110
  103. package/dist/board-export.js +0 -592
  104. package/dist/board-fonts.d.ts +0 -11
  105. package/dist/board-fonts.js +0 -10
  106. package/dist/board-gpu/daemon.d.ts +0 -11
  107. package/dist/board-gpu/daemon.js +0 -295
  108. package/dist/board-gpu/index.d.ts +0 -33
  109. package/dist/board-gpu/index.js +0 -189
  110. package/dist/board-gpu/protocol.d.ts +0 -77
  111. package/dist/board-gpu/protocol.js +0 -1
  112. package/dist/board-kernel.d.ts +0 -5
  113. package/dist/board-media-export.d.ts +0 -17
  114. package/dist/board-media-export.js +0 -164
  115. package/dist/board-media.d.ts +0 -5
  116. package/dist/board-media.js +0 -66
  117. package/dist/board-profile.d.ts +0 -21
  118. package/dist/board-profile.js +0 -67
  119. package/dist/board-simulate.d.ts +0 -67
  120. package/dist/board-simulate.js +0 -259
  121. package/dist/board-time.d.ts +0 -3
  122. package/dist/board-time.js +0 -34
  123. package/dist/bootstrap.d.ts +0 -2
  124. package/dist/client.d.ts +0 -5
  125. package/dist/client.js +0 -24
  126. package/dist/command-input.d.ts +0 -4
  127. package/dist/command-input.js +0 -16
  128. package/dist/commands/app-commerce.d.ts +0 -2
  129. package/dist/commands/app-commerce.js +0 -228
  130. package/dist/commands/app-domains.d.ts +0 -2
  131. package/dist/commands/app-domains.js +0 -133
  132. package/dist/commands/apps.d.ts +0 -4
  133. package/dist/commands/apps.js +0 -827
  134. package/dist/commands/auth.d.ts +0 -2
  135. package/dist/commands/auth.js +0 -186
  136. package/dist/commands/boards/authoring.d.ts +0 -2
  137. package/dist/commands/boards/authoring.js +0 -166
  138. package/dist/commands/boards/examples.d.ts +0 -10
  139. package/dist/commands/boards/examples.js +0 -118
  140. package/dist/commands/boards.d.ts +0 -13
  141. package/dist/commands/boards.js +0 -836
  142. package/dist/commands/channels.d.ts +0 -2
  143. package/dist/commands/channels.js +0 -74
  144. package/dist/commands/cron-jobs.d.ts +0 -2
  145. package/dist/commands/cron-jobs.js +0 -155
  146. package/dist/commands/decision.d.ts +0 -4
  147. package/dist/commands/decision.js +0 -113
  148. package/dist/commands/desktop.d.ts +0 -10
  149. package/dist/commands/desktop.js +0 -233
  150. package/dist/commands/feedback.d.ts +0 -2
  151. package/dist/commands/feedback.js +0 -131
  152. package/dist/commands/generations.d.ts +0 -2
  153. package/dist/commands/generations.js +0 -427
  154. package/dist/commands/host.d.ts +0 -2
  155. package/dist/commands/host.js +0 -11
  156. package/dist/commands/me.d.ts +0 -2
  157. package/dist/commands/me.js +0 -121
  158. package/dist/commands/models.d.ts +0 -28
  159. package/dist/commands/models.js +0 -271
  160. package/dist/commands/profile.d.ts +0 -2
  161. package/dist/commands/profile.js +0 -81
  162. package/dist/commands/prompts.d.ts +0 -2
  163. package/dist/commands/prompts.js +0 -37
  164. package/dist/commands/public.d.ts +0 -20
  165. package/dist/commands/public.js +0 -291
  166. package/dist/commands/references.d.ts +0 -2
  167. package/dist/commands/references.js +0 -193
  168. package/dist/commands/referrals.d.ts +0 -2
  169. package/dist/commands/referrals.js +0 -88
  170. package/dist/commands/rooms-connect.d.ts +0 -17
  171. package/dist/commands/rooms-connect.js +0 -140
  172. package/dist/commands/rooms-rtc-binary.d.ts +0 -2
  173. package/dist/commands/rooms-rtc-binary.js +0 -107
  174. package/dist/commands/rooms-rtc.d.ts +0 -21
  175. package/dist/commands/rooms-rtc.js +0 -171
  176. package/dist/commands/rooms.d.ts +0 -3
  177. package/dist/commands/rooms.js +0 -277
  178. package/dist/commands/run.d.ts +0 -13
  179. package/dist/commands/run.js +0 -246
  180. package/dist/commands/runtime.d.ts +0 -3
  181. package/dist/commands/runtime.js +0 -320
  182. package/dist/commands/sandboxd-binary.d.ts +0 -11
  183. package/dist/commands/sandboxd-binary.js +0 -238
  184. package/dist/commands/search.d.ts +0 -2
  185. package/dist/commands/search.js +0 -114
  186. package/dist/commands/session-access.d.ts +0 -2
  187. package/dist/commands/session-access.js +0 -70
  188. package/dist/commands/skills.d.ts +0 -2
  189. package/dist/commands/skills.js +0 -34
  190. package/dist/commands/space-activity.d.ts +0 -26
  191. package/dist/commands/space-activity.js +0 -147
  192. package/dist/commands/space-commerce.d.ts +0 -2
  193. package/dist/commands/space-commerce.js +0 -514
  194. package/dist/commands/space-displays.d.ts +0 -2
  195. package/dist/commands/space-displays.js +0 -620
  196. package/dist/commands/space-files.d.ts +0 -5
  197. package/dist/commands/space-files.js +0 -215
  198. package/dist/commands/space-invitations.d.ts +0 -29
  199. package/dist/commands/space-invitations.js +0 -189
  200. package/dist/commands/space-turns.d.ts +0 -49
  201. package/dist/commands/space-turns.js +0 -205
  202. package/dist/commands/space-wallet.d.ts +0 -2
  203. package/dist/commands/space-wallet.js +0 -141
  204. package/dist/commands/space-webhooks.d.ts +0 -7
  205. package/dist/commands/space-webhooks.js +0 -73
  206. package/dist/commands/spaces.d.ts +0 -25
  207. package/dist/commands/spaces.js +0 -2170
  208. package/dist/commands/tasks.d.ts +0 -8
  209. package/dist/commands/tasks.js +0 -80
  210. package/dist/commands/version.d.ts +0 -2
  211. package/dist/commands/version.js +0 -21
  212. package/dist/endpoint-options.d.ts +0 -4
  213. package/dist/endpoint-options.js +0 -26
  214. package/dist/env-proxy.d.ts +0 -5
  215. package/dist/env-proxy.js +0 -20
  216. package/dist/help-path.d.ts +0 -18
  217. package/dist/help-path.js +0 -223
  218. package/dist/host/auth.d.ts +0 -20
  219. package/dist/host/auth.js +0 -119
  220. package/dist/host/login-env.d.ts +0 -1
  221. package/dist/host/login-env.js +0 -31
  222. package/dist/host/runtime.d.ts +0 -35
  223. package/dist/host/runtime.js +0 -395
  224. package/dist/host/runtimes.d.ts +0 -9
  225. package/dist/host/runtimes.js +0 -42
  226. package/dist/host/serve.d.ts +0 -2
  227. package/dist/host/serve.js +0 -117
  228. package/dist/host/workspaces.d.ts +0 -2
  229. package/dist/host/workspaces.js +0 -18
  230. package/dist/http-put.d.ts +0 -25
  231. package/dist/http-put.js +0 -132
  232. package/dist/index.d.ts +0 -2
  233. package/dist/index.js +0 -129
  234. package/dist/launcher.d.ts +0 -4
  235. package/dist/launcher.js +0 -38
  236. package/dist/local-media.d.ts +0 -2
  237. package/dist/local-media.js +0 -30
  238. package/dist/network-error.d.ts +0 -3
  239. package/dist/network-error.js +0 -22
  240. package/dist/output.d.ts +0 -46
  241. package/dist/output.js +0 -244
  242. package/dist/runtime/archive-store.d.ts +0 -54
  243. package/dist/runtime/archive-store.js +0 -379
  244. package/dist/runtime/cli-path.d.ts +0 -5
  245. package/dist/runtime/cli-path.js +0 -27
  246. package/dist/runtime/codex-usage.d.ts +0 -7
  247. package/dist/runtime/codex-usage.js +0 -11
  248. package/dist/runtime/connection.d.ts +0 -42
  249. package/dist/runtime/connection.js +0 -789
  250. package/dist/runtime/diagnostics.d.ts +0 -107
  251. package/dist/runtime/diagnostics.js +0 -392
  252. package/dist/runtime/harnesses/chained-projection.d.ts +0 -40
  253. package/dist/runtime/harnesses/chained-projection.js +0 -95
  254. package/dist/runtime/harnesses/chained-transcript.d.ts +0 -24
  255. package/dist/runtime/harnesses/chained-transcript.js +0 -62
  256. package/dist/runtime/harnesses/claude-approval.d.ts +0 -34
  257. package/dist/runtime/harnesses/claude-approval.js +0 -124
  258. package/dist/runtime/harnesses/claude-transcript.d.ts +0 -8
  259. package/dist/runtime/harnesses/claude-transcript.js +0 -138
  260. package/dist/runtime/harnesses/claude.d.ts +0 -8
  261. package/dist/runtime/harnesses/claude.js +0 -225
  262. package/dist/runtime/harnesses/codex-approval.d.ts +0 -25
  263. package/dist/runtime/harnesses/codex-approval.js +0 -69
  264. package/dist/runtime/harnesses/codex.d.ts +0 -4
  265. package/dist/runtime/harnesses/codex.js +0 -269
  266. package/dist/runtime/harnesses/cursor-transcript.d.ts +0 -37
  267. package/dist/runtime/harnesses/cursor-transcript.js +0 -183
  268. package/dist/runtime/harnesses/cursor.d.ts +0 -24
  269. package/dist/runtime/harnesses/cursor.js +0 -620
  270. package/dist/runtime/harnesses/index.d.ts +0 -16
  271. package/dist/runtime/harnesses/index.js +0 -73
  272. package/dist/runtime/harnesses/pi.d.ts +0 -4
  273. package/dist/runtime/harnesses/pi.js +0 -247
  274. package/dist/runtime/harnesses/process.d.ts +0 -31
  275. package/dist/runtime/harnesses/process.js +0 -75
  276. package/dist/runtime/harnesses/stream-json.d.ts +0 -48
  277. package/dist/runtime/harnesses/stream-json.js +0 -336
  278. package/dist/runtime/harnesses/types.d.ts +0 -117
  279. package/dist/runtime/harnesses/types.js +0 -1
  280. package/dist/runtime/harnesses/workbuddy-transcript.d.ts +0 -8
  281. package/dist/runtime/harnesses/workbuddy-transcript.js +0 -127
  282. package/dist/runtime/harnesses/workbuddy.d.ts +0 -21
  283. package/dist/runtime/harnesses/workbuddy.js +0 -123
  284. package/dist/runtime/instance.d.ts +0 -20
  285. package/dist/runtime/instance.js +0 -247
  286. package/dist/runtime/json-rpc.d.ts +0 -53
  287. package/dist/runtime/json-rpc.js +0 -212
  288. package/dist/runtime/launch.d.ts +0 -25
  289. package/dist/runtime/launch.js +0 -247
  290. package/dist/runtime/local-workspace.d.ts +0 -15
  291. package/dist/runtime/local-workspace.js +0 -52
  292. package/dist/runtime/model-catalog.d.ts +0 -12
  293. package/dist/runtime/model-catalog.js +0 -84
  294. package/dist/runtime/native/adapters.d.ts +0 -15
  295. package/dist/runtime/native/adapters.js +0 -11
  296. package/dist/runtime/native/approvals.d.ts +0 -18
  297. package/dist/runtime/native/approvals.js +0 -54
  298. package/dist/runtime/native/archive.d.ts +0 -19
  299. package/dist/runtime/native/archive.js +0 -142
  300. package/dist/runtime/native/attach.d.ts +0 -36
  301. package/dist/runtime/native/attach.js +0 -128
  302. package/dist/runtime/native/codex-link.d.ts +0 -60
  303. package/dist/runtime/native/codex-link.js +0 -322
  304. package/dist/runtime/native/config.d.ts +0 -16
  305. package/dist/runtime/native/config.js +0 -24
  306. package/dist/runtime/native/daemon.d.ts +0 -92
  307. package/dist/runtime/native/daemon.js +0 -380
  308. package/dist/runtime/native/execution.d.ts +0 -26
  309. package/dist/runtime/native/execution.js +0 -34
  310. package/dist/runtime/native/identity.d.ts +0 -9
  311. package/dist/runtime/native/identity.js +0 -15
  312. package/dist/runtime/native/ingest.d.ts +0 -263
  313. package/dist/runtime/native/ingest.js +0 -884
  314. package/dist/runtime/native/install.d.ts +0 -9
  315. package/dist/runtime/native/install.js +0 -113
  316. package/dist/runtime/native/paths.d.ts +0 -2
  317. package/dist/runtime/native/paths.js +0 -7
  318. package/dist/runtime/native/pi-extension.d.ts +0 -36
  319. package/dist/runtime/native/pi-link.d.ts +0 -69
  320. package/dist/runtime/native/pi-link.js +0 -269
  321. package/dist/runtime/native/results.d.ts +0 -41
  322. package/dist/runtime/native/results.js +0 -128
  323. package/dist/runtime/native/sessions.d.ts +0 -45
  324. package/dist/runtime/native/sessions.js +0 -87
  325. package/dist/runtime/native/transcript.d.ts +0 -89
  326. package/dist/runtime/native/transcript.js +0 -656
  327. package/dist/runtime/native/translate.d.ts +0 -46
  328. package/dist/runtime/native/translate.js +0 -299
  329. package/dist/runtime/native/transport.d.ts +0 -7
  330. package/dist/runtime/native/transport.js +0 -16
  331. package/dist/runtime/native/version.d.ts +0 -5
  332. package/dist/runtime/native/version.js +0 -21
  333. package/dist/runtime/preferences.d.ts +0 -7
  334. package/dist/runtime/preferences.js +0 -22
  335. package/dist/runtime/presentation.d.ts +0 -32
  336. package/dist/runtime/presentation.js +0 -124
  337. package/dist/runtime/process-group.d.ts +0 -5
  338. package/dist/runtime/process-group.js +0 -161
  339. package/dist/runtime/projection-store.d.ts +0 -27
  340. package/dist/runtime/projection-store.js +0 -30
  341. package/dist/runtime/space-binding.d.ts +0 -48
  342. package/dist/runtime/space-binding.js +0 -342
  343. package/dist/runtime/supervisor.d.ts +0 -19
  344. package/dist/runtime/supervisor.js +0 -441
  345. package/dist/runtime/turn-projection.d.ts +0 -41
  346. package/dist/runtime/turn-projection.js +0 -120
  347. package/dist/runtime/worker.d.ts +0 -1
  348. package/dist/safe-remote-image.d.ts +0 -36
  349. package/dist/safe-remote-image.js +0 -191
  350. package/dist/self-update.d.ts +0 -7
  351. package/dist/self-update.js +0 -202
  352. package/dist/session-status.d.ts +0 -10
  353. package/dist/session-status.js +0 -25
  354. package/dist/space-files/limit.d.ts +0 -2
  355. package/dist/space-files/limit.js +0 -16
  356. package/dist/space-files/operands.d.ts +0 -17
  357. package/dist/space-files/operands.js +0 -33
  358. package/dist/space-files/transfer.d.ts +0 -53
  359. package/dist/space-files/transfer.js +0 -297
  360. package/dist/space-files/upload.d.ts +0 -17
  361. package/dist/space-files/upload.js +0 -76
  362. package/dist/space.d.ts +0 -44
  363. package/dist/space.js +0 -192
  364. package/dist/version.d.ts +0 -2
  365. package/dist/version.js +0 -17
  366. package/dist/web.d.ts +0 -1
  367. package/dist/web.js +0 -4
  368. /package/dist/{board-kernel → chunks}/lexer.js +0 -0
@@ -0,0 +1,2962 @@
1
+ import childProcess from "node:child_process";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import process from "node:process";
5
+ import { stripVTControlCharacters } from "node:util";
6
+ import { EventEmitter } from "node:events";
7
+ //#region ../../node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/error.js
8
+ /**
9
+ * CommanderError class
10
+ */
11
+ var CommanderError = class extends Error {
12
+ /**
13
+ * Constructs the CommanderError class
14
+ * @param {number} exitCode suggested exit code which could be used with process.exit
15
+ * @param {string} code an id string representing the error
16
+ * @param {string} message human-readable description of the error
17
+ */
18
+ constructor(exitCode, code, message) {
19
+ super(message);
20
+ Error.captureStackTrace(this, this.constructor);
21
+ this.name = this.constructor.name;
22
+ this.code = code;
23
+ this.exitCode = exitCode;
24
+ this.nestedError = void 0;
25
+ }
26
+ };
27
+ /**
28
+ * InvalidArgumentError class
29
+ */
30
+ var InvalidArgumentError = class extends CommanderError {
31
+ /**
32
+ * Constructs the InvalidArgumentError class
33
+ * @param {string} [message] explanation of why argument is invalid
34
+ */
35
+ constructor(message) {
36
+ super(1, "commander.invalidArgument", message);
37
+ Error.captureStackTrace(this, this.constructor);
38
+ this.name = this.constructor.name;
39
+ }
40
+ };
41
+ //#endregion
42
+ //#region ../../node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/argument.js
43
+ var Argument = class {
44
+ /**
45
+ * Initialize a new command argument with the given name and description.
46
+ * The default is that the argument is required, and you can explicitly
47
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
48
+ *
49
+ * @param {string} name
50
+ * @param {string} [description]
51
+ */
52
+ constructor(name, description) {
53
+ this.description = description || "";
54
+ this.variadic = false;
55
+ this.parseArg = void 0;
56
+ this.defaultValue = void 0;
57
+ this.defaultValueDescription = void 0;
58
+ this.argChoices = void 0;
59
+ switch (name[0]) {
60
+ case "<":
61
+ this.required = true;
62
+ this._name = name.slice(1, -1);
63
+ break;
64
+ case "[":
65
+ this.required = false;
66
+ this._name = name.slice(1, -1);
67
+ break;
68
+ default:
69
+ this.required = true;
70
+ this._name = name;
71
+ }
72
+ if (this._name.endsWith("...")) {
73
+ this.variadic = true;
74
+ this._name = this._name.slice(0, -3);
75
+ }
76
+ }
77
+ /**
78
+ * Return argument name.
79
+ *
80
+ * @return {string}
81
+ */
82
+ name() {
83
+ return this._name;
84
+ }
85
+ /**
86
+ * @package
87
+ */
88
+ _collectValue(value, previous) {
89
+ if (previous === this.defaultValue || !Array.isArray(previous)) return [value];
90
+ previous.push(value);
91
+ return previous;
92
+ }
93
+ /**
94
+ * Set the default value, and optionally supply the description to be displayed in the help.
95
+ *
96
+ * @param {*} value
97
+ * @param {string} [description]
98
+ * @return {Argument}
99
+ */
100
+ default(value, description) {
101
+ this.defaultValue = value;
102
+ this.defaultValueDescription = description;
103
+ return this;
104
+ }
105
+ /**
106
+ * Set the custom handler for processing CLI command arguments into argument values.
107
+ *
108
+ * @param {Function} [fn]
109
+ * @return {Argument}
110
+ */
111
+ argParser(fn) {
112
+ this.parseArg = fn;
113
+ return this;
114
+ }
115
+ /**
116
+ * Only allow argument value to be one of choices.
117
+ *
118
+ * @param {string[]} values
119
+ * @return {Argument}
120
+ */
121
+ choices(values) {
122
+ this.argChoices = values.slice();
123
+ this.parseArg = (arg, previous) => {
124
+ if (!this.argChoices.includes(arg)) throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
125
+ if (this.variadic) return this._collectValue(arg, previous);
126
+ return arg;
127
+ };
128
+ return this;
129
+ }
130
+ /**
131
+ * Make argument required.
132
+ *
133
+ * @returns {Argument}
134
+ */
135
+ argRequired() {
136
+ this.required = true;
137
+ return this;
138
+ }
139
+ /**
140
+ * Make argument optional.
141
+ *
142
+ * @returns {Argument}
143
+ */
144
+ argOptional() {
145
+ this.required = false;
146
+ return this;
147
+ }
148
+ };
149
+ /**
150
+ * Takes an argument and returns its human readable equivalent for help usage.
151
+ *
152
+ * @param {Argument} arg
153
+ * @return {string}
154
+ * @private
155
+ */
156
+ function humanReadableArgName(arg) {
157
+ const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
158
+ return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
159
+ }
160
+ //#endregion
161
+ //#region ../../node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/help.js
162
+ /**
163
+ * TypeScript import types for JSDoc, used by Visual Studio Code IntelliSense and `npm run typescript-checkJS`
164
+ * https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html#import-types
165
+ * @typedef { import("./argument.js").Argument } Argument
166
+ * @typedef { import("./command.js").Command } Command
167
+ * @typedef { import("./option.js").Option } Option
168
+ */
169
+ var Help = class {
170
+ constructor() {
171
+ this.helpWidth = void 0;
172
+ this.minWidthToWrap = 40;
173
+ this.sortSubcommands = false;
174
+ this.sortOptions = false;
175
+ this.showGlobalOptions = false;
176
+ }
177
+ /**
178
+ * prepareContext is called by Commander after applying overrides from `Command.configureHelp()`
179
+ * and just before calling `formatHelp()`.
180
+ *
181
+ * Commander just uses the helpWidth and the rest is provided for optional use by more complex subclasses.
182
+ *
183
+ * @param {{ error?: boolean, helpWidth?: number, outputHasColors?: boolean }} contextOptions
184
+ */
185
+ prepareContext(contextOptions) {
186
+ this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;
187
+ }
188
+ /**
189
+ * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
190
+ *
191
+ * @param {Command} cmd
192
+ * @returns {Command[]}
193
+ */
194
+ visibleCommands(cmd) {
195
+ const visibleCommands = cmd.commands.filter((cmd) => !cmd._hidden);
196
+ const helpCommand = cmd._getHelpCommand();
197
+ if (helpCommand && !helpCommand._hidden) visibleCommands.push(helpCommand);
198
+ if (this.sortSubcommands) visibleCommands.sort((a, b) => {
199
+ return a.name().localeCompare(b.name());
200
+ });
201
+ return visibleCommands;
202
+ }
203
+ /**
204
+ * Compare options for sort.
205
+ *
206
+ * @param {Option} a
207
+ * @param {Option} b
208
+ * @returns {number}
209
+ */
210
+ compareOptions(a, b) {
211
+ const getSortKey = (option) => {
212
+ return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
213
+ };
214
+ return getSortKey(a).localeCompare(getSortKey(b));
215
+ }
216
+ /**
217
+ * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
218
+ *
219
+ * @param {Command} cmd
220
+ * @returns {Option[]}
221
+ */
222
+ visibleOptions(cmd) {
223
+ const visibleOptions = cmd.options.filter((option) => !option.hidden);
224
+ const helpOption = cmd._getHelpOption();
225
+ if (helpOption && !helpOption.hidden) {
226
+ const removeShort = helpOption.short && cmd._findOption(helpOption.short);
227
+ const removeLong = helpOption.long && cmd._findOption(helpOption.long);
228
+ if (!removeShort && !removeLong) visibleOptions.push(helpOption);
229
+ else if (helpOption.long && !removeLong) visibleOptions.push(cmd.createOption(helpOption.long, helpOption.description));
230
+ else if (helpOption.short && !removeShort) visibleOptions.push(cmd.createOption(helpOption.short, helpOption.description));
231
+ }
232
+ if (this.sortOptions) visibleOptions.sort(this.compareOptions);
233
+ return visibleOptions;
234
+ }
235
+ /**
236
+ * Get an array of the visible global options. (Not including help.)
237
+ *
238
+ * @param {Command} cmd
239
+ * @returns {Option[]}
240
+ */
241
+ visibleGlobalOptions(cmd) {
242
+ if (!this.showGlobalOptions) return [];
243
+ const globalOptions = [];
244
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
245
+ const visibleOptions = ancestorCmd.options.filter((option) => !option.hidden);
246
+ globalOptions.push(...visibleOptions);
247
+ }
248
+ if (this.sortOptions) globalOptions.sort(this.compareOptions);
249
+ return globalOptions;
250
+ }
251
+ /**
252
+ * Get an array of the arguments if any have a description.
253
+ *
254
+ * @param {Command} cmd
255
+ * @returns {Argument[]}
256
+ */
257
+ visibleArguments(cmd) {
258
+ if (cmd._argsDescription) cmd.registeredArguments.forEach((argument) => {
259
+ argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
260
+ });
261
+ if (cmd.registeredArguments.find((argument) => argument.description)) return cmd.registeredArguments;
262
+ return [];
263
+ }
264
+ /**
265
+ * Get the command term to show in the list of subcommands.
266
+ *
267
+ * @param {Command} cmd
268
+ * @returns {string}
269
+ */
270
+ subcommandTerm(cmd) {
271
+ const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
272
+ return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + (args ? " " + args : "");
273
+ }
274
+ /**
275
+ * Get the option term to show in the list of options.
276
+ *
277
+ * @param {Option} option
278
+ * @returns {string}
279
+ */
280
+ optionTerm(option) {
281
+ return option.flags;
282
+ }
283
+ /**
284
+ * Get the argument term to show in the list of arguments.
285
+ *
286
+ * @param {Argument} argument
287
+ * @returns {string}
288
+ */
289
+ argumentTerm(argument) {
290
+ return argument.name();
291
+ }
292
+ /**
293
+ * Get the longest command term length.
294
+ *
295
+ * @param {Command} cmd
296
+ * @param {Help} helper
297
+ * @returns {number}
298
+ */
299
+ longestSubcommandTermLength(cmd, helper) {
300
+ return helper.visibleCommands(cmd).reduce((max, command) => {
301
+ return Math.max(max, this.displayWidth(helper.styleSubcommandTerm(helper.subcommandTerm(command))));
302
+ }, 0);
303
+ }
304
+ /**
305
+ * Get the longest option term length.
306
+ *
307
+ * @param {Command} cmd
308
+ * @param {Help} helper
309
+ * @returns {number}
310
+ */
311
+ longestOptionTermLength(cmd, helper) {
312
+ return helper.visibleOptions(cmd).reduce((max, option) => {
313
+ return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
314
+ }, 0);
315
+ }
316
+ /**
317
+ * Get the longest global option term length.
318
+ *
319
+ * @param {Command} cmd
320
+ * @param {Help} helper
321
+ * @returns {number}
322
+ */
323
+ longestGlobalOptionTermLength(cmd, helper) {
324
+ return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
325
+ return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
326
+ }, 0);
327
+ }
328
+ /**
329
+ * Get the longest argument term length.
330
+ *
331
+ * @param {Command} cmd
332
+ * @param {Help} helper
333
+ * @returns {number}
334
+ */
335
+ longestArgumentTermLength(cmd, helper) {
336
+ return helper.visibleArguments(cmd).reduce((max, argument) => {
337
+ return Math.max(max, this.displayWidth(helper.styleArgumentTerm(helper.argumentTerm(argument))));
338
+ }, 0);
339
+ }
340
+ /**
341
+ * Get the command usage to be displayed at the top of the built-in help.
342
+ *
343
+ * @param {Command} cmd
344
+ * @returns {string}
345
+ */
346
+ commandUsage(cmd) {
347
+ let cmdName = cmd._name;
348
+ if (cmd._aliases[0]) cmdName = cmdName + "|" + cmd._aliases[0];
349
+ let ancestorCmdNames = "";
350
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
351
+ return ancestorCmdNames + cmdName + " " + cmd.usage();
352
+ }
353
+ /**
354
+ * Get the description for the command.
355
+ *
356
+ * @param {Command} cmd
357
+ * @returns {string}
358
+ */
359
+ commandDescription(cmd) {
360
+ return cmd.description();
361
+ }
362
+ /**
363
+ * Get the subcommand summary to show in the list of subcommands.
364
+ * (Fallback to description for backwards compatibility.)
365
+ *
366
+ * @param {Command} cmd
367
+ * @returns {string}
368
+ */
369
+ subcommandDescription(cmd) {
370
+ return cmd.summary() || cmd.description();
371
+ }
372
+ /**
373
+ * Get the option description to show in the list of options.
374
+ *
375
+ * @param {Option} option
376
+ * @return {string}
377
+ */
378
+ optionDescription(option) {
379
+ const extraInfo = [];
380
+ if (option.argChoices) extraInfo.push(`choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
381
+ if (option.defaultValue !== void 0) {
382
+ if (option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean") extraInfo.push(`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`);
383
+ }
384
+ if (option.presetArg !== void 0 && option.optional) extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
385
+ if (option.envVar !== void 0) extraInfo.push(`env: ${option.envVar}`);
386
+ if (extraInfo.length > 0) {
387
+ const extraDescription = `(${extraInfo.join(", ")})`;
388
+ if (option.description) return `${option.description} ${extraDescription}`;
389
+ return extraDescription;
390
+ }
391
+ return option.description;
392
+ }
393
+ /**
394
+ * Get the argument description to show in the list of arguments.
395
+ *
396
+ * @param {Argument} argument
397
+ * @return {string}
398
+ */
399
+ argumentDescription(argument) {
400
+ const extraInfo = [];
401
+ if (argument.argChoices) extraInfo.push(`choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
402
+ if (argument.defaultValue !== void 0) extraInfo.push(`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`);
403
+ if (extraInfo.length > 0) {
404
+ const extraDescription = `(${extraInfo.join(", ")})`;
405
+ if (argument.description) return `${argument.description} ${extraDescription}`;
406
+ return extraDescription;
407
+ }
408
+ return argument.description;
409
+ }
410
+ /**
411
+ * Format a list of items, given a heading and an array of formatted items.
412
+ *
413
+ * @param {string} heading
414
+ * @param {string[]} items
415
+ * @param {Help} helper
416
+ * @returns string[]
417
+ */
418
+ formatItemList(heading, items, helper) {
419
+ if (items.length === 0) return [];
420
+ return [
421
+ helper.styleTitle(heading),
422
+ ...items,
423
+ ""
424
+ ];
425
+ }
426
+ /**
427
+ * Group items by their help group heading.
428
+ *
429
+ * @param {Command[] | Option[]} unsortedItems
430
+ * @param {Command[] | Option[]} visibleItems
431
+ * @param {Function} getGroup
432
+ * @returns {Map<string, Command[] | Option[]>}
433
+ */
434
+ groupItems(unsortedItems, visibleItems, getGroup) {
435
+ const result = /* @__PURE__ */ new Map();
436
+ unsortedItems.forEach((item) => {
437
+ const group = getGroup(item);
438
+ if (!result.has(group)) result.set(group, []);
439
+ });
440
+ visibleItems.forEach((item) => {
441
+ const group = getGroup(item);
442
+ if (!result.has(group)) result.set(group, []);
443
+ result.get(group).push(item);
444
+ });
445
+ return result;
446
+ }
447
+ /**
448
+ * Generate the built-in help text.
449
+ *
450
+ * @param {Command} cmd
451
+ * @param {Help} helper
452
+ * @returns {string}
453
+ */
454
+ formatHelp(cmd, helper) {
455
+ const termWidth = helper.padWidth(cmd, helper);
456
+ const helpWidth = helper.helpWidth ?? 80;
457
+ function callFormatItem(term, description) {
458
+ return helper.formatItem(term, termWidth, description, helper);
459
+ }
460
+ let output = [`${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`, ""];
461
+ const commandDescription = helper.commandDescription(cmd);
462
+ if (commandDescription.length > 0) output = output.concat([helper.boxWrap(helper.styleCommandDescription(commandDescription), helpWidth), ""]);
463
+ const argumentList = helper.visibleArguments(cmd).map((argument) => {
464
+ return callFormatItem(helper.styleArgumentTerm(helper.argumentTerm(argument)), helper.styleArgumentDescription(helper.argumentDescription(argument)));
465
+ });
466
+ output = output.concat(this.formatItemList("Arguments:", argumentList, helper));
467
+ this.groupItems(cmd.options, helper.visibleOptions(cmd), (option) => option.helpGroupHeading ?? "Options:").forEach((options, group) => {
468
+ const optionList = options.map((option) => {
469
+ return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
470
+ });
471
+ output = output.concat(this.formatItemList(group, optionList, helper));
472
+ });
473
+ if (helper.showGlobalOptions) {
474
+ const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
475
+ return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
476
+ });
477
+ output = output.concat(this.formatItemList("Global Options:", globalOptionList, helper));
478
+ }
479
+ this.groupItems(cmd.commands, helper.visibleCommands(cmd), (sub) => sub.helpGroup() || "Commands:").forEach((commands, group) => {
480
+ const commandList = commands.map((sub) => {
481
+ return callFormatItem(helper.styleSubcommandTerm(helper.subcommandTerm(sub)), helper.styleSubcommandDescription(helper.subcommandDescription(sub)));
482
+ });
483
+ output = output.concat(this.formatItemList(group, commandList, helper));
484
+ });
485
+ return output.join("\n");
486
+ }
487
+ /**
488
+ * Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations.
489
+ *
490
+ * @param {string} str
491
+ * @returns {number}
492
+ */
493
+ displayWidth(str) {
494
+ return stripVTControlCharacters(str).length;
495
+ }
496
+ /**
497
+ * Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc.
498
+ *
499
+ * @param {string} str
500
+ * @returns {string}
501
+ */
502
+ styleTitle(str) {
503
+ return str;
504
+ }
505
+ styleUsage(str) {
506
+ return str.split(" ").map((word) => {
507
+ if (word === "[options]") return this.styleOptionText(word);
508
+ if (word === "[command]") return this.styleSubcommandText(word);
509
+ if (word[0] === "[" || word[0] === "<") return this.styleArgumentText(word);
510
+ return this.styleCommandText(word);
511
+ }).join(" ");
512
+ }
513
+ styleCommandDescription(str) {
514
+ return this.styleDescriptionText(str);
515
+ }
516
+ styleOptionDescription(str) {
517
+ return this.styleDescriptionText(str);
518
+ }
519
+ styleSubcommandDescription(str) {
520
+ return this.styleDescriptionText(str);
521
+ }
522
+ styleArgumentDescription(str) {
523
+ return this.styleDescriptionText(str);
524
+ }
525
+ styleDescriptionText(str) {
526
+ return str;
527
+ }
528
+ styleOptionTerm(str) {
529
+ return this.styleOptionText(str);
530
+ }
531
+ styleSubcommandTerm(str) {
532
+ return str.split(" ").map((word) => {
533
+ if (word === "[options]") return this.styleOptionText(word);
534
+ if (word[0] === "[" || word[0] === "<") return this.styleArgumentText(word);
535
+ return this.styleSubcommandText(word);
536
+ }).join(" ");
537
+ }
538
+ styleArgumentTerm(str) {
539
+ return this.styleArgumentText(str);
540
+ }
541
+ styleOptionText(str) {
542
+ return str;
543
+ }
544
+ styleArgumentText(str) {
545
+ return str;
546
+ }
547
+ styleSubcommandText(str) {
548
+ return str;
549
+ }
550
+ styleCommandText(str) {
551
+ return str;
552
+ }
553
+ /**
554
+ * Calculate the pad width from the maximum term length.
555
+ *
556
+ * @param {Command} cmd
557
+ * @param {Help} helper
558
+ * @returns {number}
559
+ */
560
+ padWidth(cmd, helper) {
561
+ return Math.max(helper.longestOptionTermLength(cmd, helper), helper.longestGlobalOptionTermLength(cmd, helper), helper.longestSubcommandTermLength(cmd, helper), helper.longestArgumentTermLength(cmd, helper));
562
+ }
563
+ /**
564
+ * Detect manually wrapped and indented strings by checking for line break followed by whitespace.
565
+ *
566
+ * @param {string} str
567
+ * @returns {boolean}
568
+ */
569
+ preformatted(str) {
570
+ return /\n[^\S\r\n]/.test(str);
571
+ }
572
+ /**
573
+ * Format the "item", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.
574
+ *
575
+ * So "TTT", 5, "DDD DDDD DD DDD" might be formatted for this.helpWidth=17 like so:
576
+ * TTT DDD DDDD
577
+ * DD DDD
578
+ *
579
+ * @param {string} term
580
+ * @param {number} termWidth
581
+ * @param {string} description
582
+ * @param {Help} helper
583
+ * @returns {string}
584
+ */
585
+ formatItem(term, termWidth, description, helper) {
586
+ const itemIndent = 2;
587
+ const itemIndentStr = " ".repeat(itemIndent);
588
+ if (!description) return itemIndentStr + term;
589
+ const paddedTerm = term.padEnd(termWidth + term.length - helper.displayWidth(term));
590
+ const spacerWidth = 2;
591
+ const remainingWidth = (this.helpWidth ?? 80) - termWidth - spacerWidth - itemIndent;
592
+ let formattedDescription;
593
+ if (remainingWidth < this.minWidthToWrap || helper.preformatted(description)) formattedDescription = description;
594
+ else formattedDescription = helper.boxWrap(description, remainingWidth).replace(/\n/g, "\n" + " ".repeat(termWidth + spacerWidth));
595
+ return itemIndentStr + paddedTerm + " ".repeat(spacerWidth) + formattedDescription.replace(/\n/g, `\n${itemIndentStr}`);
596
+ }
597
+ /**
598
+ * Wrap a string at whitespace, preserving existing line breaks.
599
+ * Wrapping is skipped if the width is less than `minWidthToWrap`.
600
+ *
601
+ * @param {string} str
602
+ * @param {number} width
603
+ * @returns {string}
604
+ */
605
+ boxWrap(str, width) {
606
+ if (width < this.minWidthToWrap) return str;
607
+ const rawLines = str.split(/\r\n|\n/);
608
+ const chunkPattern = /[\s]*[^\s]+/g;
609
+ const wrappedLines = [];
610
+ rawLines.forEach((line) => {
611
+ const chunks = line.match(chunkPattern);
612
+ if (chunks === null) {
613
+ wrappedLines.push("");
614
+ return;
615
+ }
616
+ let sumChunks = [chunks.shift()];
617
+ let sumWidth = this.displayWidth(sumChunks[0]);
618
+ chunks.forEach((chunk) => {
619
+ const visibleWidth = this.displayWidth(chunk);
620
+ if (sumWidth + visibleWidth <= width) {
621
+ sumChunks.push(chunk);
622
+ sumWidth += visibleWidth;
623
+ return;
624
+ }
625
+ wrappedLines.push(sumChunks.join(""));
626
+ const nextChunk = chunk.trimStart();
627
+ sumChunks = [nextChunk];
628
+ sumWidth = this.displayWidth(nextChunk);
629
+ });
630
+ wrappedLines.push(sumChunks.join(""));
631
+ });
632
+ return wrappedLines.join("\n");
633
+ }
634
+ };
635
+ //#endregion
636
+ //#region ../../node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/option.js
637
+ var Option = class {
638
+ /**
639
+ * Initialize a new `Option` with the given `flags` and `description`.
640
+ *
641
+ * @param {string} flags
642
+ * @param {string} [description]
643
+ */
644
+ constructor(flags, description) {
645
+ this.flags = flags;
646
+ this.description = description || "";
647
+ this.required = flags.includes("<");
648
+ this.optional = flags.includes("[");
649
+ this.variadic = /\w\.\.\.[>\]]$/.test(flags);
650
+ this.mandatory = false;
651
+ const optionFlags = splitOptionFlags(flags);
652
+ this.short = optionFlags.shortFlag;
653
+ this.long = optionFlags.longFlag;
654
+ this.negate = false;
655
+ if (this.long) this.negate = this.long.startsWith("--no-");
656
+ this.defaultValue = void 0;
657
+ this.defaultValueDescription = void 0;
658
+ this.presetArg = void 0;
659
+ this.envVar = void 0;
660
+ this.parseArg = void 0;
661
+ this.hidden = false;
662
+ this.argChoices = void 0;
663
+ this.conflictsWith = [];
664
+ this.implied = void 0;
665
+ this.helpGroupHeading = void 0;
666
+ }
667
+ /**
668
+ * Set the default value, and optionally supply the description to be displayed in the help.
669
+ *
670
+ * @param {*} value
671
+ * @param {string} [description]
672
+ * @return {Option}
673
+ */
674
+ default(value, description) {
675
+ this.defaultValue = value;
676
+ this.defaultValueDescription = description;
677
+ return this;
678
+ }
679
+ /**
680
+ * Preset to use when option used without option-argument, especially optional but also boolean and negated.
681
+ * The custom processing (parseArg) is called.
682
+ *
683
+ * @example
684
+ * new Option('--color').default('GREYSCALE').preset('RGB');
685
+ * new Option('--donate [amount]').preset('20').argParser(parseFloat);
686
+ *
687
+ * @param {*} arg
688
+ * @return {Option}
689
+ */
690
+ preset(arg) {
691
+ this.presetArg = arg;
692
+ return this;
693
+ }
694
+ /**
695
+ * Add option name(s) that conflict with this option.
696
+ * An error will be displayed if conflicting options are found during parsing.
697
+ *
698
+ * @example
699
+ * new Option('--rgb').conflicts('cmyk');
700
+ * new Option('--js').conflicts(['ts', 'jsx']);
701
+ *
702
+ * @param {(string | string[])} names
703
+ * @return {Option}
704
+ */
705
+ conflicts(names) {
706
+ this.conflictsWith = this.conflictsWith.concat(names);
707
+ return this;
708
+ }
709
+ /**
710
+ * Specify implied option values for when this option is set and the implied options are not.
711
+ *
712
+ * The custom processing (parseArg) is not called on the implied values.
713
+ *
714
+ * @example
715
+ * program
716
+ * .addOption(new Option('--log', 'write logging information to file'))
717
+ * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
718
+ *
719
+ * @param {object} impliedOptionValues
720
+ * @return {Option}
721
+ */
722
+ implies(impliedOptionValues) {
723
+ let newImplied = impliedOptionValues;
724
+ if (typeof impliedOptionValues === "string") newImplied = { [impliedOptionValues]: true };
725
+ this.implied = Object.assign(this.implied || {}, newImplied);
726
+ return this;
727
+ }
728
+ /**
729
+ * Set environment variable to check for option value.
730
+ *
731
+ * An environment variable is only used if when processed the current option value is
732
+ * undefined, or the source of the current value is 'default' or 'config' or 'env'.
733
+ *
734
+ * @param {string} name
735
+ * @return {Option}
736
+ */
737
+ env(name) {
738
+ this.envVar = name;
739
+ return this;
740
+ }
741
+ /**
742
+ * Set the custom handler for processing CLI option arguments into option values.
743
+ *
744
+ * @param {Function} [fn]
745
+ * @return {Option}
746
+ */
747
+ argParser(fn) {
748
+ this.parseArg = fn;
749
+ return this;
750
+ }
751
+ /**
752
+ * Whether the option is mandatory and must have a value after parsing.
753
+ *
754
+ * @param {boolean} [mandatory=true]
755
+ * @return {Option}
756
+ */
757
+ makeOptionMandatory(mandatory = true) {
758
+ this.mandatory = !!mandatory;
759
+ return this;
760
+ }
761
+ /**
762
+ * Hide option in help.
763
+ *
764
+ * @param {boolean} [hide=true]
765
+ * @return {Option}
766
+ */
767
+ hideHelp(hide = true) {
768
+ this.hidden = !!hide;
769
+ return this;
770
+ }
771
+ /**
772
+ * @package
773
+ */
774
+ _collectValue(value, previous) {
775
+ if (previous === this.defaultValue || !Array.isArray(previous)) return [value];
776
+ previous.push(value);
777
+ return previous;
778
+ }
779
+ /**
780
+ * Only allow option value to be one of choices.
781
+ *
782
+ * @param {string[]} values
783
+ * @return {Option}
784
+ */
785
+ choices(values) {
786
+ this.argChoices = values.slice();
787
+ this.parseArg = (arg, previous) => {
788
+ if (!this.argChoices.includes(arg)) throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
789
+ if (this.variadic) return this._collectValue(arg, previous);
790
+ return arg;
791
+ };
792
+ return this;
793
+ }
794
+ /**
795
+ * Return option name.
796
+ *
797
+ * @return {string}
798
+ */
799
+ name() {
800
+ if (this.long) return this.long.replace(/^--/, "");
801
+ return this.short.replace(/^-/, "");
802
+ }
803
+ /**
804
+ * Return option name, in a camelcase format that can be used
805
+ * as an object attribute key.
806
+ *
807
+ * @return {string}
808
+ */
809
+ attributeName() {
810
+ if (this.negate) return camelcase(this.name().replace(/^no-/, ""));
811
+ return camelcase(this.name());
812
+ }
813
+ /**
814
+ * Set the help group heading.
815
+ *
816
+ * @param {string} heading
817
+ * @return {Option}
818
+ */
819
+ helpGroup(heading) {
820
+ this.helpGroupHeading = heading;
821
+ return this;
822
+ }
823
+ /**
824
+ * Check if `arg` matches the short or long flag.
825
+ *
826
+ * @param {string} arg
827
+ * @return {boolean}
828
+ * @package
829
+ */
830
+ is(arg) {
831
+ return this.short === arg || this.long === arg;
832
+ }
833
+ /**
834
+ * Return whether a boolean option.
835
+ *
836
+ * Options are one of boolean, negated, required argument, or optional argument.
837
+ *
838
+ * @return {boolean}
839
+ * @package
840
+ */
841
+ isBoolean() {
842
+ return !this.required && !this.optional && !this.negate;
843
+ }
844
+ };
845
+ /**
846
+ * This class is to make it easier to work with dual options, without changing the existing
847
+ * implementation. We support separate dual options for separate positive and negative options,
848
+ * like `--build` and `--no-build`, which share a single option value. This works nicely for some
849
+ * use cases, but is tricky for others where we want separate behaviours despite
850
+ * the single shared option value.
851
+ */
852
+ var DualOptions = class {
853
+ /**
854
+ * @param {Option[]} options
855
+ */
856
+ constructor(options) {
857
+ this.positiveOptions = /* @__PURE__ */ new Map();
858
+ this.negativeOptions = /* @__PURE__ */ new Map();
859
+ this.dualOptions = /* @__PURE__ */ new Set();
860
+ options.forEach((option) => {
861
+ if (option.negate) this.negativeOptions.set(option.attributeName(), option);
862
+ else this.positiveOptions.set(option.attributeName(), option);
863
+ });
864
+ this.negativeOptions.forEach((value, key) => {
865
+ if (this.positiveOptions.has(key)) this.dualOptions.add(key);
866
+ });
867
+ }
868
+ /**
869
+ * Did the value come from the option, and not from possible matching dual option?
870
+ *
871
+ * @param {*} value
872
+ * @param {Option} option
873
+ * @returns {boolean}
874
+ */
875
+ valueFromOption(value, option) {
876
+ const optionKey = option.attributeName();
877
+ if (!this.dualOptions.has(optionKey)) return true;
878
+ const preset = this.negativeOptions.get(optionKey).presetArg;
879
+ const negativeValue = preset !== void 0 ? preset : false;
880
+ return option.negate === (negativeValue === value);
881
+ }
882
+ };
883
+ /**
884
+ * Convert string from kebab-case to camelCase.
885
+ *
886
+ * @param {string} str
887
+ * @return {string}
888
+ * @private
889
+ */
890
+ function camelcase(str) {
891
+ return str.split("-").reduce((str, word) => {
892
+ return str + word[0].toUpperCase() + word.slice(1);
893
+ });
894
+ }
895
+ /**
896
+ * Split the short and long flag out of something like '-m,--mixed <value>'
897
+ *
898
+ * @private
899
+ */
900
+ function splitOptionFlags(flags) {
901
+ let shortFlag;
902
+ let longFlag;
903
+ const shortFlagExp = /^-[^-]$/;
904
+ const longFlagExp = /^--[^-]/;
905
+ const flagParts = flags.split(/[ |,]+/).concat("guard");
906
+ if (shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();
907
+ if (longFlagExp.test(flagParts[0])) longFlag = flagParts.shift();
908
+ if (!shortFlag && shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();
909
+ if (!shortFlag && longFlagExp.test(flagParts[0])) {
910
+ shortFlag = longFlag;
911
+ longFlag = flagParts.shift();
912
+ }
913
+ if (flagParts[0].startsWith("-")) {
914
+ const unsupportedFlag = flagParts[0];
915
+ const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;
916
+ if (/^-[^-][^-]/.test(unsupportedFlag)) throw new Error(`${baseError}
917
+ - a short flag is a single dash and a single character
918
+ - either use a single dash and a single character (for a short flag)
919
+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`);
920
+ if (shortFlagExp.test(unsupportedFlag)) throw new Error(`${baseError}
921
+ - too many short flags`);
922
+ if (longFlagExp.test(unsupportedFlag)) throw new Error(`${baseError}
923
+ - too many long flags`);
924
+ throw new Error(`${baseError}
925
+ - unrecognised flag format`);
926
+ }
927
+ if (shortFlag === void 0 && longFlag === void 0) throw new Error(`option creation failed due to no flags found in '${flags}'.`);
928
+ return {
929
+ shortFlag,
930
+ longFlag
931
+ };
932
+ }
933
+ //#endregion
934
+ //#region ../../node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/suggestSimilar.js
935
+ const maxDistance = 3;
936
+ function editDistance(a, b) {
937
+ if (Math.abs(a.length - b.length) > maxDistance) return Math.max(a.length, b.length);
938
+ const d = [];
939
+ for (let i = 0; i <= a.length; i++) d[i] = [i];
940
+ for (let j = 0; j <= b.length; j++) d[0][j] = j;
941
+ for (let j = 1; j <= b.length; j++) for (let i = 1; i <= a.length; i++) {
942
+ let cost;
943
+ if (a[i - 1] === b[j - 1]) cost = 0;
944
+ else cost = 1;
945
+ d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
946
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
947
+ }
948
+ return d[a.length][b.length];
949
+ }
950
+ /**
951
+ * Find close matches, restricted to same number of edits.
952
+ *
953
+ * @param {string} word
954
+ * @param {string[]} candidates
955
+ * @returns {string}
956
+ */
957
+ function suggestSimilar(word, candidates) {
958
+ if (!candidates || candidates.length === 0) return "";
959
+ candidates = Array.from(new Set(candidates));
960
+ const searchingOptions = word.startsWith("--");
961
+ if (searchingOptions) {
962
+ word = word.slice(2);
963
+ candidates = candidates.map((candidate) => candidate.slice(2));
964
+ }
965
+ let similar = [];
966
+ let bestDistance = maxDistance;
967
+ const minSimilarity = .4;
968
+ candidates.forEach((candidate) => {
969
+ if (candidate.length <= 1) return;
970
+ const distance = editDistance(word, candidate);
971
+ const length = Math.max(word.length, candidate.length);
972
+ if ((length - distance) / length > minSimilarity) {
973
+ if (distance < bestDistance) {
974
+ bestDistance = distance;
975
+ similar = [candidate];
976
+ } else if (distance === bestDistance) similar.push(candidate);
977
+ }
978
+ });
979
+ similar.sort((a, b) => a.localeCompare(b));
980
+ if (searchingOptions) similar = similar.map((candidate) => `--${candidate}`);
981
+ if (similar.length > 1) return `\n(Did you mean one of ${similar.join(", ")}?)`;
982
+ if (similar.length === 1) return `\n(Did you mean ${similar[0]}?)`;
983
+ return "";
984
+ }
985
+ //#endregion
986
+ //#region ../../node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/command.js
987
+ var Command = class Command extends EventEmitter {
988
+ /**
989
+ * Initialize a new `Command`.
990
+ *
991
+ * @param {string} [name]
992
+ */
993
+ constructor(name) {
994
+ super();
995
+ /** @type {Command[]} */
996
+ this.commands = [];
997
+ /** @type {Option[]} */
998
+ this.options = [];
999
+ this.parent = null;
1000
+ this._allowUnknownOption = false;
1001
+ this._allowExcessArguments = false;
1002
+ /** @type {Argument[]} */
1003
+ this.registeredArguments = [];
1004
+ this._args = this.registeredArguments;
1005
+ /** @type {string[]} */
1006
+ this.args = [];
1007
+ this.rawArgs = [];
1008
+ this.processedArgs = [];
1009
+ this._scriptPath = null;
1010
+ this._name = name || "";
1011
+ this._optionValues = {};
1012
+ this._optionValueSources = {};
1013
+ this._storeOptionsAsProperties = false;
1014
+ this._actionHandler = null;
1015
+ this._executableHandler = false;
1016
+ this._executableFile = null;
1017
+ this._executableDir = null;
1018
+ this._defaultCommandName = null;
1019
+ this._exitCallback = null;
1020
+ this._aliases = [];
1021
+ this._combineFlagAndOptionalValue = true;
1022
+ this._description = "";
1023
+ this._summary = "";
1024
+ this._argsDescription = void 0;
1025
+ this._enablePositionalOptions = false;
1026
+ this._passThroughOptions = false;
1027
+ this._lifeCycleHooks = {};
1028
+ /** @type {(boolean | string)} */
1029
+ this._showHelpAfterError = false;
1030
+ this._showSuggestionAfterError = true;
1031
+ this._savedState = null;
1032
+ this._outputConfiguration = {
1033
+ writeOut: (str) => process.stdout.write(str),
1034
+ writeErr: (str) => process.stderr.write(str),
1035
+ outputError: (str, write) => write(str),
1036
+ getOutHelpWidth: () => process.stdout.isTTY ? process.stdout.columns : void 0,
1037
+ getErrHelpWidth: () => process.stderr.isTTY ? process.stderr.columns : void 0,
1038
+ getOutHasColors: () => useColor() ?? (process.stdout.isTTY && process.stdout.hasColors?.()),
1039
+ getErrHasColors: () => useColor() ?? (process.stderr.isTTY && process.stderr.hasColors?.()),
1040
+ stripColor: (str) => stripVTControlCharacters(str)
1041
+ };
1042
+ this._hidden = false;
1043
+ /** @type {(Option | null | undefined)} */
1044
+ this._helpOption = void 0;
1045
+ this._addImplicitHelpCommand = void 0;
1046
+ /** @type {Command} */
1047
+ this._helpCommand = void 0;
1048
+ this._helpConfiguration = {};
1049
+ /** @type {string | undefined} */
1050
+ this._helpGroupHeading = void 0;
1051
+ /** @type {string | undefined} */
1052
+ this._defaultCommandGroup = void 0;
1053
+ /** @type {string | undefined} */
1054
+ this._defaultOptionGroup = void 0;
1055
+ }
1056
+ /**
1057
+ * Copy settings that are useful to have in common across root command and subcommands.
1058
+ *
1059
+ * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
1060
+ *
1061
+ * @param {Command} sourceCommand
1062
+ * @return {Command} `this` command for chaining
1063
+ */
1064
+ copyInheritedSettings(sourceCommand) {
1065
+ this._outputConfiguration = sourceCommand._outputConfiguration;
1066
+ this._helpOption = sourceCommand._helpOption;
1067
+ this._helpCommand = sourceCommand._helpCommand;
1068
+ this._helpConfiguration = sourceCommand._helpConfiguration;
1069
+ this._exitCallback = sourceCommand._exitCallback;
1070
+ this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
1071
+ this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
1072
+ this._allowExcessArguments = sourceCommand._allowExcessArguments;
1073
+ this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
1074
+ this._showHelpAfterError = sourceCommand._showHelpAfterError;
1075
+ this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
1076
+ return this;
1077
+ }
1078
+ /**
1079
+ * @returns {Command[]}
1080
+ * @private
1081
+ */
1082
+ _getCommandAndAncestors() {
1083
+ const result = [];
1084
+ for (let command = this; command; command = command.parent) result.push(command);
1085
+ return result;
1086
+ }
1087
+ /**
1088
+ * Define a command.
1089
+ *
1090
+ * There are two styles of command: pay attention to where to put the description.
1091
+ *
1092
+ * @example
1093
+ * // Command implemented using action handler (description is supplied separately to `.command`)
1094
+ * program
1095
+ * .command('clone <source> [destination]')
1096
+ * .description('clone a repository into a newly created directory')
1097
+ * .action((source, destination) => {
1098
+ * console.log('clone command called');
1099
+ * });
1100
+ *
1101
+ * // Command implemented using separate executable file (description is second parameter to `.command`)
1102
+ * program
1103
+ * .command('start <service>', 'start named service')
1104
+ * .command('stop [service]', 'stop named service, or all if no name supplied');
1105
+ *
1106
+ * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
1107
+ * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
1108
+ * @param {object} [execOpts] - configuration options (for executable)
1109
+ * @return {Command} returns new command for action handler, or `this` for executable command
1110
+ */
1111
+ command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
1112
+ let desc = actionOptsOrExecDesc;
1113
+ let opts = execOpts;
1114
+ if (typeof desc === "object" && desc !== null) {
1115
+ opts = desc;
1116
+ desc = null;
1117
+ }
1118
+ opts = opts || {};
1119
+ const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
1120
+ const cmd = this.createCommand(name);
1121
+ if (desc) {
1122
+ cmd.description(desc);
1123
+ cmd._executableHandler = true;
1124
+ }
1125
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
1126
+ cmd._hidden = !!(opts.noHelp || opts.hidden);
1127
+ cmd._executableFile = opts.executableFile || null;
1128
+ if (args) cmd.arguments(args);
1129
+ this._registerCommand(cmd);
1130
+ cmd.parent = this;
1131
+ cmd.copyInheritedSettings(this);
1132
+ if (desc) return this;
1133
+ return cmd;
1134
+ }
1135
+ /**
1136
+ * Factory routine to create a new unattached command.
1137
+ *
1138
+ * See .command() for creating an attached subcommand, which uses this routine to
1139
+ * create the command. You can override createCommand to customise subcommands.
1140
+ *
1141
+ * @param {string} [name]
1142
+ * @return {Command} new command
1143
+ */
1144
+ createCommand(name) {
1145
+ return new Command(name);
1146
+ }
1147
+ /**
1148
+ * You can customise the help with a subclass of Help by overriding createHelp,
1149
+ * or by overriding Help properties using configureHelp().
1150
+ *
1151
+ * @return {Help}
1152
+ */
1153
+ createHelp() {
1154
+ return Object.assign(new Help(), this.configureHelp());
1155
+ }
1156
+ /**
1157
+ * You can customise the help by overriding Help properties using configureHelp(),
1158
+ * or with a subclass of Help by overriding createHelp().
1159
+ *
1160
+ * @param {object} [configuration] - configuration options
1161
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
1162
+ */
1163
+ configureHelp(configuration) {
1164
+ if (configuration === void 0) return this._helpConfiguration;
1165
+ this._helpConfiguration = configuration;
1166
+ return this;
1167
+ }
1168
+ /**
1169
+ * The default output goes to stdout and stderr. You can customise this for special
1170
+ * applications. You can also customise the display of errors by overriding outputError.
1171
+ *
1172
+ * The configuration properties are all functions:
1173
+ *
1174
+ * // change how output being written, defaults to stdout and stderr
1175
+ * writeOut(str)
1176
+ * writeErr(str)
1177
+ * // change how output being written for errors, defaults to writeErr
1178
+ * outputError(str, write) // used for displaying errors and not used for displaying help
1179
+ * // specify width for wrapping help
1180
+ * getOutHelpWidth()
1181
+ * getErrHelpWidth()
1182
+ * // color support, currently only used with Help
1183
+ * getOutHasColors()
1184
+ * getErrHasColors()
1185
+ * stripColor() // used to remove ANSI escape codes if output does not have colors
1186
+ *
1187
+ * @param {object} [configuration] - configuration options
1188
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
1189
+ */
1190
+ configureOutput(configuration) {
1191
+ if (configuration === void 0) return this._outputConfiguration;
1192
+ this._outputConfiguration = {
1193
+ ...this._outputConfiguration,
1194
+ ...configuration
1195
+ };
1196
+ return this;
1197
+ }
1198
+ /**
1199
+ * Display the help or a custom message after an error occurs.
1200
+ *
1201
+ * @param {(boolean|string)} [displayHelp]
1202
+ * @return {Command} `this` command for chaining
1203
+ */
1204
+ showHelpAfterError(displayHelp = true) {
1205
+ if (typeof displayHelp !== "string") displayHelp = !!displayHelp;
1206
+ this._showHelpAfterError = displayHelp;
1207
+ return this;
1208
+ }
1209
+ /**
1210
+ * Display suggestion of similar commands for unknown commands, or options for unknown options.
1211
+ *
1212
+ * @param {boolean} [displaySuggestion]
1213
+ * @return {Command} `this` command for chaining
1214
+ */
1215
+ showSuggestionAfterError(displaySuggestion = true) {
1216
+ this._showSuggestionAfterError = !!displaySuggestion;
1217
+ return this;
1218
+ }
1219
+ /**
1220
+ * Add a prepared subcommand.
1221
+ *
1222
+ * See .command() for creating an attached subcommand which inherits settings from its parent.
1223
+ *
1224
+ * @param {Command} cmd - new subcommand
1225
+ * @param {object} [opts] - configuration options
1226
+ * @return {Command} `this` command for chaining
1227
+ */
1228
+ addCommand(cmd, opts) {
1229
+ if (!cmd._name) throw new Error(`Command passed to .addCommand() must have a name
1230
+ - specify the name in Command constructor or using .name()`);
1231
+ opts = opts || {};
1232
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
1233
+ if (opts.noHelp || opts.hidden) cmd._hidden = true;
1234
+ this._registerCommand(cmd);
1235
+ cmd.parent = this;
1236
+ cmd._checkForBrokenPassThrough();
1237
+ return this;
1238
+ }
1239
+ /**
1240
+ * Factory routine to create a new unattached argument.
1241
+ *
1242
+ * See .argument() for creating an attached argument, which uses this routine to
1243
+ * create the argument. You can override createArgument to return a custom argument.
1244
+ *
1245
+ * @param {string} name
1246
+ * @param {string} [description]
1247
+ * @return {Argument} new argument
1248
+ */
1249
+ createArgument(name, description) {
1250
+ return new Argument(name, description);
1251
+ }
1252
+ /**
1253
+ * Define argument syntax for command.
1254
+ *
1255
+ * The default is that the argument is required, and you can explicitly
1256
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
1257
+ *
1258
+ * @example
1259
+ * program.argument('<input-file>');
1260
+ * program.argument('[output-file]');
1261
+ *
1262
+ * @param {string} name
1263
+ * @param {string} [description]
1264
+ * @param {(Function|*)} [parseArg] - custom argument processing function or default value
1265
+ * @param {*} [defaultValue]
1266
+ * @return {Command} `this` command for chaining
1267
+ */
1268
+ argument(name, description, parseArg, defaultValue) {
1269
+ const argument = this.createArgument(name, description);
1270
+ if (typeof parseArg === "function") argument.default(defaultValue).argParser(parseArg);
1271
+ else argument.default(parseArg);
1272
+ this.addArgument(argument);
1273
+ return this;
1274
+ }
1275
+ /**
1276
+ * Define argument syntax for command, adding multiple at once (without descriptions).
1277
+ *
1278
+ * See also .argument().
1279
+ *
1280
+ * @example
1281
+ * program.arguments('<cmd> [env]');
1282
+ *
1283
+ * @param {string} names
1284
+ * @return {Command} `this` command for chaining
1285
+ */
1286
+ arguments(names) {
1287
+ names.trim().split(/ +/).forEach((detail) => {
1288
+ this.argument(detail);
1289
+ });
1290
+ return this;
1291
+ }
1292
+ /**
1293
+ * Define argument syntax for command, adding a prepared argument.
1294
+ *
1295
+ * @param {Argument} argument
1296
+ * @return {Command} `this` command for chaining
1297
+ */
1298
+ addArgument(argument) {
1299
+ const previousArgument = this.registeredArguments.slice(-1)[0];
1300
+ if (previousArgument?.variadic) throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);
1301
+ if (argument.required && argument.defaultValue !== void 0 && argument.parseArg === void 0) throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);
1302
+ this.registeredArguments.push(argument);
1303
+ return this;
1304
+ }
1305
+ /**
1306
+ * Customise or override default help command. By default a help command is automatically added if your command has subcommands.
1307
+ *
1308
+ * @example
1309
+ * program.helpCommand('help [cmd]');
1310
+ * program.helpCommand('help [cmd]', 'show help');
1311
+ * program.helpCommand(false); // suppress default help command
1312
+ * program.helpCommand(true); // add help command even if no subcommands
1313
+ *
1314
+ * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added
1315
+ * @param {string} [description] - custom description
1316
+ * @return {Command} `this` command for chaining
1317
+ */
1318
+ helpCommand(enableOrNameAndArgs, description) {
1319
+ if (typeof enableOrNameAndArgs === "boolean") {
1320
+ this._addImplicitHelpCommand = enableOrNameAndArgs;
1321
+ if (enableOrNameAndArgs && this._defaultCommandGroup) this._initCommandGroup(this._getHelpCommand());
1322
+ return this;
1323
+ }
1324
+ const [, helpName, helpArgs] = (enableOrNameAndArgs ?? "help [command]").match(/([^ ]+) *(.*)/);
1325
+ const helpDescription = description ?? "display help for command";
1326
+ const helpCommand = this.createCommand(helpName);
1327
+ helpCommand.helpOption(false);
1328
+ if (helpArgs) helpCommand.arguments(helpArgs);
1329
+ if (helpDescription) helpCommand.description(helpDescription);
1330
+ this._addImplicitHelpCommand = true;
1331
+ this._helpCommand = helpCommand;
1332
+ if (enableOrNameAndArgs || description) this._initCommandGroup(helpCommand);
1333
+ return this;
1334
+ }
1335
+ /**
1336
+ * Add prepared custom help command.
1337
+ *
1338
+ * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`
1339
+ * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only
1340
+ * @return {Command} `this` command for chaining
1341
+ */
1342
+ addHelpCommand(helpCommand, deprecatedDescription) {
1343
+ if (typeof helpCommand !== "object") {
1344
+ this.helpCommand(helpCommand, deprecatedDescription);
1345
+ return this;
1346
+ }
1347
+ this._addImplicitHelpCommand = true;
1348
+ this._helpCommand = helpCommand;
1349
+ this._initCommandGroup(helpCommand);
1350
+ return this;
1351
+ }
1352
+ /**
1353
+ * Lazy create help command.
1354
+ *
1355
+ * @return {(Command|null)}
1356
+ * @package
1357
+ */
1358
+ _getHelpCommand() {
1359
+ if (this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"))) {
1360
+ if (this._helpCommand === void 0) this.helpCommand(void 0, void 0);
1361
+ return this._helpCommand;
1362
+ }
1363
+ return null;
1364
+ }
1365
+ /**
1366
+ * Add hook for life cycle event.
1367
+ *
1368
+ * @param {string} event
1369
+ * @param {Function} listener
1370
+ * @return {Command} `this` command for chaining
1371
+ */
1372
+ hook(event, listener) {
1373
+ const allowedValues = [
1374
+ "preSubcommand",
1375
+ "preAction",
1376
+ "postAction"
1377
+ ];
1378
+ if (!allowedValues.includes(event)) throw new Error(`Unexpected value for event passed to hook : '${event}'.
1379
+ Expecting one of '${allowedValues.join("', '")}'`);
1380
+ if (this._lifeCycleHooks[event]) this._lifeCycleHooks[event].push(listener);
1381
+ else this._lifeCycleHooks[event] = [listener];
1382
+ return this;
1383
+ }
1384
+ /**
1385
+ * Register callback to use as replacement for calling process.exit.
1386
+ *
1387
+ * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
1388
+ * @return {Command} `this` command for chaining
1389
+ */
1390
+ exitOverride(fn) {
1391
+ if (fn) this._exitCallback = fn;
1392
+ else this._exitCallback = (err) => {
1393
+ if (err.code !== "commander.executeSubCommandAsync") throw err;
1394
+ };
1395
+ return this;
1396
+ }
1397
+ /**
1398
+ * Call process.exit, and _exitCallback if defined.
1399
+ *
1400
+ * @param {number} exitCode exit code for using with process.exit
1401
+ * @param {string} code an id string representing the error
1402
+ * @param {string} message human-readable description of the error
1403
+ * @return never
1404
+ * @private
1405
+ */
1406
+ _exit(exitCode, code, message) {
1407
+ if (this._exitCallback) this._exitCallback(new CommanderError(exitCode, code, message));
1408
+ process.exit(exitCode);
1409
+ }
1410
+ /**
1411
+ * Register callback `fn` for the command.
1412
+ *
1413
+ * @example
1414
+ * program
1415
+ * .command('serve')
1416
+ * .description('start service')
1417
+ * .action(function() {
1418
+ * // do work here
1419
+ * });
1420
+ *
1421
+ * @param {Function} fn
1422
+ * @return {Command} `this` command for chaining
1423
+ */
1424
+ action(fn) {
1425
+ const listener = (args) => {
1426
+ const expectedArgsCount = this.registeredArguments.length;
1427
+ const actionArgs = args.slice(0, expectedArgsCount);
1428
+ if (this._storeOptionsAsProperties) actionArgs[expectedArgsCount] = this;
1429
+ else actionArgs[expectedArgsCount] = this.opts();
1430
+ actionArgs.push(this);
1431
+ return fn.apply(this, actionArgs);
1432
+ };
1433
+ this._actionHandler = listener;
1434
+ return this;
1435
+ }
1436
+ /**
1437
+ * Factory routine to create a new unattached option.
1438
+ *
1439
+ * See .option() for creating an attached option, which uses this routine to
1440
+ * create the option. You can override createOption to return a custom option.
1441
+ *
1442
+ * @param {string} flags
1443
+ * @param {string} [description]
1444
+ * @return {Option} new option
1445
+ */
1446
+ createOption(flags, description) {
1447
+ return new Option(flags, description);
1448
+ }
1449
+ /**
1450
+ * Wrap parseArgs to catch 'commander.invalidArgument'.
1451
+ *
1452
+ * @param {(Option | Argument)} target
1453
+ * @param {string} value
1454
+ * @param {*} previous
1455
+ * @param {string} invalidArgumentMessage
1456
+ * @private
1457
+ */
1458
+ _callParseArg(target, value, previous, invalidArgumentMessage) {
1459
+ try {
1460
+ return target.parseArg(value, previous);
1461
+ } catch (err) {
1462
+ if (err.code === "commander.invalidArgument") {
1463
+ const message = `${invalidArgumentMessage} ${err.message}`;
1464
+ this.error(message, {
1465
+ exitCode: err.exitCode,
1466
+ code: err.code
1467
+ });
1468
+ }
1469
+ throw err;
1470
+ }
1471
+ }
1472
+ /**
1473
+ * Check for option flag conflicts.
1474
+ * Register option if no conflicts found, or throw on conflict.
1475
+ *
1476
+ * @param {Option} option
1477
+ * @private
1478
+ */
1479
+ _registerOption(option) {
1480
+ const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
1481
+ if (matchingOption) {
1482
+ const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
1483
+ throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
1484
+ - already used by option '${matchingOption.flags}'`);
1485
+ }
1486
+ this._initOptionGroup(option);
1487
+ this.options.push(option);
1488
+ }
1489
+ /**
1490
+ * Check for command name and alias conflicts with existing commands.
1491
+ * Register command if no conflicts found, or throw on conflict.
1492
+ *
1493
+ * @param {Command} command
1494
+ * @private
1495
+ */
1496
+ _registerCommand(command) {
1497
+ const knownBy = (cmd) => {
1498
+ return [cmd.name()].concat(cmd.aliases());
1499
+ };
1500
+ const alreadyUsed = knownBy(command).find((name) => this._findCommand(name));
1501
+ if (alreadyUsed) {
1502
+ const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
1503
+ const newCmd = knownBy(command).join("|");
1504
+ throw new Error(`cannot add command '${newCmd}' as already have command '${existingCmd}'`);
1505
+ }
1506
+ this._initCommandGroup(command);
1507
+ this.commands.push(command);
1508
+ }
1509
+ /**
1510
+ * Add an option.
1511
+ *
1512
+ * @param {Option} option
1513
+ * @return {Command} `this` command for chaining
1514
+ */
1515
+ addOption(option) {
1516
+ this._registerOption(option);
1517
+ const oname = option.name();
1518
+ const name = option.attributeName();
1519
+ if (option.defaultValue !== void 0) this.setOptionValueWithSource(name, option.defaultValue, "default");
1520
+ const handleOptionValue = (val, invalidValueMessage, valueSource) => {
1521
+ if (val == null && option.presetArg !== void 0) val = option.presetArg;
1522
+ const oldValue = this.getOptionValue(name);
1523
+ if (val !== null && option.parseArg) val = this._callParseArg(option, val, oldValue, invalidValueMessage);
1524
+ else if (val !== null && option.variadic) val = option._collectValue(val, oldValue);
1525
+ if (val == null) {
1526
+ if (option.negate) val = false;
1527
+ else if (option.isBoolean() || option.optional) val = true;
1528
+ else val = "";
1529
+ }
1530
+ this.setOptionValueWithSource(name, val, valueSource);
1531
+ };
1532
+ this.on("option:" + oname, (val) => {
1533
+ const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
1534
+ handleOptionValue(val, invalidValueMessage, "cli");
1535
+ });
1536
+ if (option.envVar) this.on("optionEnv:" + oname, (val) => {
1537
+ const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
1538
+ handleOptionValue(val, invalidValueMessage, "env");
1539
+ });
1540
+ return this;
1541
+ }
1542
+ /**
1543
+ * Internal implementation shared by .option() and .requiredOption()
1544
+ *
1545
+ * @return {Command} `this` command for chaining
1546
+ * @private
1547
+ */
1548
+ _optionEx(config, flags, description, fn, defaultValue) {
1549
+ if (typeof flags === "object" && flags instanceof Option) throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");
1550
+ const option = this.createOption(flags, description);
1551
+ option.makeOptionMandatory(!!config.mandatory);
1552
+ if (typeof fn === "function") option.default(defaultValue).argParser(fn);
1553
+ else if (fn instanceof RegExp) {
1554
+ const regex = fn;
1555
+ fn = (val, def) => {
1556
+ const m = regex.exec(val);
1557
+ return m ? m[0] : def;
1558
+ };
1559
+ option.default(defaultValue).argParser(fn);
1560
+ } else option.default(fn);
1561
+ return this.addOption(option);
1562
+ }
1563
+ /**
1564
+ * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
1565
+ *
1566
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
1567
+ * option-argument is indicated by `<>` and an optional option-argument by `[]`.
1568
+ *
1569
+ * See the README for more details, and see also addOption() and requiredOption().
1570
+ *
1571
+ * @example
1572
+ * program
1573
+ * .option('-p, --pepper', 'add pepper')
1574
+ * .option('--pt, --pizza-type <TYPE>', 'type of pizza') // required option-argument
1575
+ * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
1576
+ * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
1577
+ *
1578
+ * @param {string} flags
1579
+ * @param {string} [description]
1580
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
1581
+ * @param {*} [defaultValue]
1582
+ * @return {Command} `this` command for chaining
1583
+ */
1584
+ option(flags, description, parseArg, defaultValue) {
1585
+ return this._optionEx({}, flags, description, parseArg, defaultValue);
1586
+ }
1587
+ /**
1588
+ * Add a required option which must have a value after parsing. This usually means
1589
+ * the option must be specified on the command line. (Otherwise the same as .option().)
1590
+ *
1591
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
1592
+ *
1593
+ * @param {string} flags
1594
+ * @param {string} [description]
1595
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
1596
+ * @param {*} [defaultValue]
1597
+ * @return {Command} `this` command for chaining
1598
+ */
1599
+ requiredOption(flags, description, parseArg, defaultValue) {
1600
+ return this._optionEx({ mandatory: true }, flags, description, parseArg, defaultValue);
1601
+ }
1602
+ /**
1603
+ * Alter parsing of short flags with optional values.
1604
+ *
1605
+ * @example
1606
+ * // for `.option('-f,--flag [value]'):
1607
+ * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
1608
+ * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
1609
+ *
1610
+ * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.
1611
+ * @return {Command} `this` command for chaining
1612
+ */
1613
+ combineFlagAndOptionalValue(combine = true) {
1614
+ this._combineFlagAndOptionalValue = !!combine;
1615
+ return this;
1616
+ }
1617
+ /**
1618
+ * Allow unknown options on the command line.
1619
+ *
1620
+ * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.
1621
+ * @return {Command} `this` command for chaining
1622
+ */
1623
+ allowUnknownOption(allowUnknown = true) {
1624
+ this._allowUnknownOption = !!allowUnknown;
1625
+ return this;
1626
+ }
1627
+ /**
1628
+ * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
1629
+ *
1630
+ * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.
1631
+ * @return {Command} `this` command for chaining
1632
+ */
1633
+ allowExcessArguments(allowExcess = true) {
1634
+ this._allowExcessArguments = !!allowExcess;
1635
+ return this;
1636
+ }
1637
+ /**
1638
+ * Enable positional options. Positional means global options are specified before subcommands which lets
1639
+ * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
1640
+ * The default behaviour is non-positional and global options may appear anywhere on the command line.
1641
+ *
1642
+ * @param {boolean} [positional]
1643
+ * @return {Command} `this` command for chaining
1644
+ */
1645
+ enablePositionalOptions(positional = true) {
1646
+ this._enablePositionalOptions = !!positional;
1647
+ return this;
1648
+ }
1649
+ /**
1650
+ * Pass through options that come after command-arguments rather than treat them as command-options,
1651
+ * so actual command-options come before command-arguments. Turning this on for a subcommand requires
1652
+ * positional options to have been enabled on the program (parent commands).
1653
+ * The default behaviour is non-positional and options may appear before or after command-arguments.
1654
+ *
1655
+ * @param {boolean} [passThrough] for unknown options.
1656
+ * @return {Command} `this` command for chaining
1657
+ */
1658
+ passThroughOptions(passThrough = true) {
1659
+ this._passThroughOptions = !!passThrough;
1660
+ this._checkForBrokenPassThrough();
1661
+ return this;
1662
+ }
1663
+ /**
1664
+ * @private
1665
+ */
1666
+ _checkForBrokenPassThrough() {
1667
+ if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`);
1668
+ }
1669
+ /**
1670
+ * Whether to store option values as properties on command object,
1671
+ * or store separately (specify false). In both cases the option values can be accessed using .opts().
1672
+ *
1673
+ * @param {boolean} [storeAsProperties=true]
1674
+ * @return {Command} `this` command for chaining
1675
+ */
1676
+ storeOptionsAsProperties(storeAsProperties = true) {
1677
+ if (this.options.length) throw new Error("call .storeOptionsAsProperties() before adding options");
1678
+ if (Object.keys(this._optionValues).length) throw new Error("call .storeOptionsAsProperties() before setting option values");
1679
+ this._storeOptionsAsProperties = !!storeAsProperties;
1680
+ return this;
1681
+ }
1682
+ /**
1683
+ * Retrieve option value.
1684
+ *
1685
+ * @param {string} key
1686
+ * @return {object} value
1687
+ */
1688
+ getOptionValue(key) {
1689
+ if (this._storeOptionsAsProperties) return this[key];
1690
+ return this._optionValues[key];
1691
+ }
1692
+ /**
1693
+ * Store option value.
1694
+ *
1695
+ * @param {string} key
1696
+ * @param {object} value
1697
+ * @return {Command} `this` command for chaining
1698
+ */
1699
+ setOptionValue(key, value) {
1700
+ return this.setOptionValueWithSource(key, value, void 0);
1701
+ }
1702
+ /**
1703
+ * Store option value and where the value came from.
1704
+ *
1705
+ * @param {string} key
1706
+ * @param {object} value
1707
+ * @param {string} source - expected values are default/config/env/cli/implied
1708
+ * @return {Command} `this` command for chaining
1709
+ */
1710
+ setOptionValueWithSource(key, value, source) {
1711
+ if (this._storeOptionsAsProperties) this[key] = value;
1712
+ else this._optionValues[key] = value;
1713
+ this._optionValueSources[key] = source;
1714
+ return this;
1715
+ }
1716
+ /**
1717
+ * Get source of option value.
1718
+ * Expected values are default | config | env | cli | implied
1719
+ *
1720
+ * @param {string} key
1721
+ * @return {string}
1722
+ */
1723
+ getOptionValueSource(key) {
1724
+ return this._optionValueSources[key];
1725
+ }
1726
+ /**
1727
+ * Get source of option value. See also .optsWithGlobals().
1728
+ * Expected values are default | config | env | cli | implied
1729
+ *
1730
+ * @param {string} key
1731
+ * @return {string}
1732
+ */
1733
+ getOptionValueSourceWithGlobals(key) {
1734
+ let source;
1735
+ this._getCommandAndAncestors().forEach((cmd) => {
1736
+ if (cmd.getOptionValueSource(key) !== void 0) source = cmd.getOptionValueSource(key);
1737
+ });
1738
+ return source;
1739
+ }
1740
+ /**
1741
+ * Get user arguments from implied or explicit arguments.
1742
+ * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
1743
+ *
1744
+ * @private
1745
+ */
1746
+ _prepareUserArgs(argv, parseOptions) {
1747
+ if (argv !== void 0 && !Array.isArray(argv)) throw new Error("first parameter to parse must be array or undefined");
1748
+ parseOptions = parseOptions || {};
1749
+ if (argv === void 0 && parseOptions.from === void 0) {
1750
+ if (process.versions?.electron) parseOptions.from = "electron";
1751
+ const execArgv = process.execArgv ?? [];
1752
+ if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) parseOptions.from = "eval";
1753
+ }
1754
+ if (argv === void 0) argv = process.argv;
1755
+ this.rawArgs = argv.slice();
1756
+ let userArgs;
1757
+ switch (parseOptions.from) {
1758
+ case void 0:
1759
+ case "node":
1760
+ this._scriptPath = argv[1];
1761
+ userArgs = argv.slice(2);
1762
+ break;
1763
+ case "electron":
1764
+ if (process.defaultApp) {
1765
+ this._scriptPath = argv[1];
1766
+ userArgs = argv.slice(2);
1767
+ } else userArgs = argv.slice(1);
1768
+ break;
1769
+ case "user":
1770
+ userArgs = argv.slice(0);
1771
+ break;
1772
+ case "eval":
1773
+ userArgs = argv.slice(1);
1774
+ break;
1775
+ default: throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);
1776
+ }
1777
+ if (!this._name && this._scriptPath) this.nameFromFilename(this._scriptPath);
1778
+ this._name = this._name || "program";
1779
+ return userArgs;
1780
+ }
1781
+ /**
1782
+ * Parse `argv`, setting options and invoking commands when defined.
1783
+ *
1784
+ * Use parseAsync instead of parse if any of your action handlers are async.
1785
+ *
1786
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
1787
+ *
1788
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
1789
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
1790
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
1791
+ * - `'user'`: just user arguments
1792
+ *
1793
+ * @example
1794
+ * program.parse(); // parse process.argv and auto-detect electron and special node flags
1795
+ * program.parse(process.argv); // assume argv[0] is app and argv[1] is script
1796
+ * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
1797
+ *
1798
+ * @param {string[]} [argv] - optional, defaults to process.argv
1799
+ * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron
1800
+ * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
1801
+ * @return {Command} `this` command for chaining
1802
+ */
1803
+ parse(argv, parseOptions) {
1804
+ this._prepareForParse();
1805
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1806
+ this._parseCommand([], userArgs);
1807
+ return this;
1808
+ }
1809
+ /**
1810
+ * Parse `argv`, setting options and invoking commands when defined.
1811
+ *
1812
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
1813
+ *
1814
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
1815
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
1816
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
1817
+ * - `'user'`: just user arguments
1818
+ *
1819
+ * @example
1820
+ * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags
1821
+ * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script
1822
+ * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
1823
+ *
1824
+ * @param {string[]} [argv]
1825
+ * @param {object} [parseOptions]
1826
+ * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
1827
+ * @return {Promise}
1828
+ */
1829
+ async parseAsync(argv, parseOptions) {
1830
+ this._prepareForParse();
1831
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1832
+ await this._parseCommand([], userArgs);
1833
+ return this;
1834
+ }
1835
+ _prepareForParse() {
1836
+ if (this._savedState === null) {
1837
+ this.options.filter((option) => option.negate && option.defaultValue === void 0 && this.getOptionValue(option.attributeName()) === void 0).forEach((option) => {
1838
+ const positiveLongFlag = option.long.replace(/^--no-/, "--");
1839
+ if (!this._findOption(positiveLongFlag)) this.setOptionValueWithSource(option.attributeName(), true, "default");
1840
+ });
1841
+ this.saveStateBeforeParse();
1842
+ } else this.restoreStateBeforeParse();
1843
+ }
1844
+ /**
1845
+ * Called the first time parse is called to save state and allow a restore before subsequent calls to parse.
1846
+ * Not usually called directly, but available for subclasses to save their custom state.
1847
+ *
1848
+ * This is called in a lazy way. Only commands used in parsing chain will have state saved.
1849
+ */
1850
+ saveStateBeforeParse() {
1851
+ this._savedState = {
1852
+ _name: this._name,
1853
+ _optionValues: { ...this._optionValues },
1854
+ _optionValueSources: { ...this._optionValueSources }
1855
+ };
1856
+ }
1857
+ /**
1858
+ * Restore state before parse for calls after the first.
1859
+ * Not usually called directly, but available for subclasses to save their custom state.
1860
+ *
1861
+ * This is called in a lazy way. Only commands used in parsing chain will have state restored.
1862
+ */
1863
+ restoreStateBeforeParse() {
1864
+ if (this._storeOptionsAsProperties) throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
1865
+ - either make a new Command for each call to parse, or stop storing options as properties`);
1866
+ this._name = this._savedState._name;
1867
+ this._scriptPath = null;
1868
+ this.rawArgs = [];
1869
+ this._optionValues = { ...this._savedState._optionValues };
1870
+ this._optionValueSources = { ...this._savedState._optionValueSources };
1871
+ this.args = [];
1872
+ this.processedArgs = [];
1873
+ }
1874
+ /**
1875
+ * Throw if expected executable is missing. Add lots of help for author.
1876
+ *
1877
+ * @param {string} executableFile
1878
+ * @param {string} executableDir
1879
+ * @param {string} subcommandName
1880
+ */
1881
+ _checkForMissingExecutable(executableFile, executableDir, subcommandName) {
1882
+ if (fs.existsSync(executableFile)) return;
1883
+ const executableMissing = `'${executableFile}' does not exist
1884
+ - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
1885
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
1886
+ - ${executableDir ? `searched for local subcommand relative to directory '${executableDir}'` : "no directory for search for local subcommand, use .executableDir() to supply a custom directory"}`;
1887
+ throw new Error(executableMissing);
1888
+ }
1889
+ /**
1890
+ * Execute a sub-command executable.
1891
+ *
1892
+ * @private
1893
+ */
1894
+ _executeSubCommand(subcommand, args) {
1895
+ args = args.slice();
1896
+ const sourceExt = [
1897
+ ".js",
1898
+ ".ts",
1899
+ ".tsx",
1900
+ ".mjs",
1901
+ ".cjs"
1902
+ ];
1903
+ function findFile(baseDir, baseName) {
1904
+ const localBin = path.resolve(baseDir, baseName);
1905
+ if (fs.existsSync(localBin)) return localBin;
1906
+ if (sourceExt.includes(path.extname(baseName))) return void 0;
1907
+ const foundExt = sourceExt.find((ext) => fs.existsSync(`${localBin}${ext}`));
1908
+ if (foundExt) return `${localBin}${foundExt}`;
1909
+ }
1910
+ this._checkForMissingMandatoryOptions();
1911
+ this._checkForConflictingOptions();
1912
+ let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
1913
+ let executableDir = this._executableDir || "";
1914
+ if (this._scriptPath) {
1915
+ let resolvedScriptPath;
1916
+ try {
1917
+ resolvedScriptPath = fs.realpathSync(this._scriptPath);
1918
+ } catch {
1919
+ resolvedScriptPath = this._scriptPath;
1920
+ }
1921
+ executableDir = path.resolve(path.dirname(resolvedScriptPath), executableDir);
1922
+ }
1923
+ if (executableDir) {
1924
+ let localFile = findFile(executableDir, executableFile);
1925
+ if (!localFile && !subcommand._executableFile && this._scriptPath) {
1926
+ const legacyName = path.basename(this._scriptPath, path.extname(this._scriptPath));
1927
+ if (legacyName !== this._name) localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);
1928
+ }
1929
+ executableFile = localFile || executableFile;
1930
+ }
1931
+ const launchWithNode = sourceExt.includes(path.extname(executableFile));
1932
+ let proc;
1933
+ if (process.platform !== "win32") {
1934
+ if (launchWithNode) {
1935
+ args.unshift(executableFile);
1936
+ args = incrementNodeInspectorPort(process.execArgv).concat(args);
1937
+ proc = childProcess.spawn(process.argv[0], args, { stdio: "inherit" });
1938
+ } else proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
1939
+ } else {
1940
+ this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
1941
+ args.unshift(executableFile);
1942
+ args = incrementNodeInspectorPort(process.execArgv).concat(args);
1943
+ proc = childProcess.spawn(process.execPath, args, { stdio: "inherit" });
1944
+ }
1945
+ if (!proc.killed) [
1946
+ "SIGUSR1",
1947
+ "SIGUSR2",
1948
+ "SIGTERM",
1949
+ "SIGINT",
1950
+ "SIGHUP"
1951
+ ].forEach((signal) => {
1952
+ process.on(signal, () => {
1953
+ if (proc.killed === false && proc.exitCode === null) proc.kill(signal);
1954
+ });
1955
+ });
1956
+ const exitCallback = this._exitCallback;
1957
+ proc.on("close", (code) => {
1958
+ code = code ?? 1;
1959
+ if (!exitCallback) process.exit(code);
1960
+ else exitCallback(new CommanderError(code, "commander.executeSubCommandAsync", "(close)"));
1961
+ });
1962
+ proc.on("error", (err) => {
1963
+ if (err.code === "ENOENT") this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
1964
+ else if (err.code === "EACCES") throw new Error(`'${executableFile}' not executable`);
1965
+ if (!exitCallback) process.exit(1);
1966
+ else {
1967
+ const wrappedError = new CommanderError(1, "commander.executeSubCommandAsync", "(error)");
1968
+ wrappedError.nestedError = err;
1969
+ exitCallback(wrappedError);
1970
+ }
1971
+ });
1972
+ this.runningCommand = proc;
1973
+ }
1974
+ /**
1975
+ * @private
1976
+ */
1977
+ _dispatchSubcommand(commandName, operands, unknown) {
1978
+ const subCommand = this._findCommand(commandName);
1979
+ if (!subCommand) this.help({ error: true });
1980
+ subCommand._prepareForParse();
1981
+ let promiseChain;
1982
+ promiseChain = this._chainOrCallSubCommandHook(promiseChain, subCommand, "preSubcommand");
1983
+ promiseChain = this._chainOrCall(promiseChain, () => {
1984
+ if (subCommand._executableHandler) this._executeSubCommand(subCommand, operands.concat(unknown));
1985
+ else return subCommand._parseCommand(operands, unknown);
1986
+ });
1987
+ return promiseChain;
1988
+ }
1989
+ /**
1990
+ * Invoke help directly if possible, or dispatch if necessary.
1991
+ * e.g. help foo
1992
+ *
1993
+ * @private
1994
+ */
1995
+ _dispatchHelpCommand(subcommandName) {
1996
+ if (!subcommandName) this.help();
1997
+ const subCommand = this._findCommand(subcommandName);
1998
+ if (subCommand && !subCommand._executableHandler) subCommand.help();
1999
+ return this._dispatchSubcommand(subcommandName, [], [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]);
2000
+ }
2001
+ /**
2002
+ * Check this.args against expected this.registeredArguments.
2003
+ *
2004
+ * @private
2005
+ */
2006
+ _checkNumberOfArguments() {
2007
+ this.registeredArguments.forEach((arg, i) => {
2008
+ if (arg.required && this.args[i] == null) this.missingArgument(arg.name());
2009
+ });
2010
+ if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) return;
2011
+ if (this.args.length > this.registeredArguments.length) this._excessArguments(this.args);
2012
+ }
2013
+ /**
2014
+ * Process this.args using this.registeredArguments and save as this.processedArgs!
2015
+ *
2016
+ * @private
2017
+ */
2018
+ _processArguments() {
2019
+ const myParseArg = (argument, value, previous) => {
2020
+ let parsedValue = value;
2021
+ if (value !== null && argument.parseArg) {
2022
+ const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
2023
+ parsedValue = this._callParseArg(argument, value, previous, invalidValueMessage);
2024
+ }
2025
+ return parsedValue;
2026
+ };
2027
+ this._checkNumberOfArguments();
2028
+ const processedArgs = [];
2029
+ this.registeredArguments.forEach((declaredArg, index) => {
2030
+ let value = declaredArg.defaultValue;
2031
+ if (declaredArg.variadic) {
2032
+ if (index < this.args.length) {
2033
+ value = this.args.slice(index);
2034
+ if (declaredArg.parseArg) value = value.reduce((processed, v) => {
2035
+ return myParseArg(declaredArg, v, processed);
2036
+ }, declaredArg.defaultValue);
2037
+ } else if (value === void 0) value = [];
2038
+ } else if (index < this.args.length) {
2039
+ value = this.args[index];
2040
+ if (declaredArg.parseArg) value = myParseArg(declaredArg, value, declaredArg.defaultValue);
2041
+ }
2042
+ processedArgs[index] = value;
2043
+ });
2044
+ this.processedArgs = processedArgs;
2045
+ }
2046
+ /**
2047
+ * Once we have a promise we chain, but call synchronously until then.
2048
+ *
2049
+ * @param {(Promise|undefined)} promise
2050
+ * @param {Function} fn
2051
+ * @return {(Promise|undefined)}
2052
+ * @private
2053
+ */
2054
+ _chainOrCall(promise, fn) {
2055
+ if (promise?.then && typeof promise.then === "function") return promise.then(() => fn());
2056
+ return fn();
2057
+ }
2058
+ /**
2059
+ *
2060
+ * @param {(Promise|undefined)} promise
2061
+ * @param {string} event
2062
+ * @return {(Promise|undefined)}
2063
+ * @private
2064
+ */
2065
+ _chainOrCallHooks(promise, event) {
2066
+ let result = promise;
2067
+ const hooks = [];
2068
+ this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== void 0).forEach((hookedCommand) => {
2069
+ hookedCommand._lifeCycleHooks[event].forEach((callback) => {
2070
+ hooks.push({
2071
+ hookedCommand,
2072
+ callback
2073
+ });
2074
+ });
2075
+ });
2076
+ if (event === "postAction") hooks.reverse();
2077
+ hooks.forEach((hookDetail) => {
2078
+ result = this._chainOrCall(result, () => {
2079
+ return hookDetail.callback(hookDetail.hookedCommand, this);
2080
+ });
2081
+ });
2082
+ return result;
2083
+ }
2084
+ /**
2085
+ *
2086
+ * @param {(Promise|undefined)} promise
2087
+ * @param {Command} subCommand
2088
+ * @param {string} event
2089
+ * @return {(Promise|undefined)}
2090
+ * @private
2091
+ */
2092
+ _chainOrCallSubCommandHook(promise, subCommand, event) {
2093
+ let result = promise;
2094
+ if (this._lifeCycleHooks[event] !== void 0) this._lifeCycleHooks[event].forEach((hook) => {
2095
+ result = this._chainOrCall(result, () => {
2096
+ return hook(this, subCommand);
2097
+ });
2098
+ });
2099
+ return result;
2100
+ }
2101
+ /**
2102
+ * Process arguments in context of this command.
2103
+ * Returns action result, in case it is a promise.
2104
+ *
2105
+ * @private
2106
+ */
2107
+ _parseCommand(operands, unknown) {
2108
+ const parsed = this.parseOptions(unknown);
2109
+ this._parseOptionsEnv();
2110
+ this._parseOptionsImplied();
2111
+ operands = operands.concat(parsed.operands);
2112
+ unknown = parsed.unknown;
2113
+ this.args = operands.concat(unknown);
2114
+ if (operands && this._findCommand(operands[0])) return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
2115
+ if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) return this._dispatchHelpCommand(operands[1]);
2116
+ if (this._defaultCommandName) {
2117
+ this._outputHelpIfRequested(unknown);
2118
+ return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);
2119
+ }
2120
+ if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) this.help({ error: true });
2121
+ this._outputHelpIfRequested(parsed.unknown);
2122
+ this._checkForMissingMandatoryOptions();
2123
+ this._checkForConflictingOptions();
2124
+ const checkForUnknownOptions = () => {
2125
+ if (parsed.unknown.length > 0) this.unknownOption(parsed.unknown[0]);
2126
+ };
2127
+ const commandEvent = `command:${this.name()}`;
2128
+ if (this._actionHandler) {
2129
+ checkForUnknownOptions();
2130
+ this._processArguments();
2131
+ let promiseChain;
2132
+ promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
2133
+ promiseChain = this._chainOrCall(promiseChain, () => this._actionHandler(this.processedArgs));
2134
+ if (this.parent) promiseChain = this._chainOrCall(promiseChain, () => {
2135
+ this.parent.emit(commandEvent, operands, unknown);
2136
+ });
2137
+ promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
2138
+ return promiseChain;
2139
+ }
2140
+ if (this.parent?.listenerCount(commandEvent)) {
2141
+ checkForUnknownOptions();
2142
+ this._processArguments();
2143
+ this.parent.emit(commandEvent, operands, unknown);
2144
+ } else if (operands.length) {
2145
+ if (this._findCommand("*")) return this._dispatchSubcommand("*", operands, unknown);
2146
+ if (this.listenerCount("command:*")) this.emit("command:*", operands, unknown);
2147
+ else if (this.commands.length) this.unknownCommand();
2148
+ else {
2149
+ checkForUnknownOptions();
2150
+ this._processArguments();
2151
+ }
2152
+ } else if (this.commands.length) {
2153
+ checkForUnknownOptions();
2154
+ this.help({ error: true });
2155
+ } else {
2156
+ checkForUnknownOptions();
2157
+ this._processArguments();
2158
+ }
2159
+ }
2160
+ /**
2161
+ * Find matching command.
2162
+ *
2163
+ * @private
2164
+ * @return {Command | undefined}
2165
+ */
2166
+ _findCommand(name) {
2167
+ if (!name) return void 0;
2168
+ return this.commands.find((cmd) => cmd._name === name || cmd._aliases.includes(name));
2169
+ }
2170
+ /**
2171
+ * Return an option matching `arg` if any.
2172
+ *
2173
+ * @param {string} arg
2174
+ * @return {Option}
2175
+ * @package
2176
+ */
2177
+ _findOption(arg) {
2178
+ return this.options.find((option) => option.is(arg));
2179
+ }
2180
+ /**
2181
+ * Display an error message if a mandatory option does not have a value.
2182
+ * Called after checking for help flags in leaf subcommand.
2183
+ *
2184
+ * @private
2185
+ */
2186
+ _checkForMissingMandatoryOptions() {
2187
+ this._getCommandAndAncestors().forEach((cmd) => {
2188
+ cmd.options.forEach((anOption) => {
2189
+ if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === void 0) cmd.missingMandatoryOptionValue(anOption);
2190
+ });
2191
+ });
2192
+ }
2193
+ /**
2194
+ * Display an error message if conflicting options are used together in this.
2195
+ *
2196
+ * @private
2197
+ */
2198
+ _checkForConflictingLocalOptions() {
2199
+ const definedNonDefaultOptions = this.options.filter((option) => {
2200
+ const optionKey = option.attributeName();
2201
+ if (this.getOptionValue(optionKey) === void 0) return false;
2202
+ return this.getOptionValueSource(optionKey) !== "default";
2203
+ });
2204
+ definedNonDefaultOptions.filter((option) => option.conflictsWith.length > 0).forEach((option) => {
2205
+ const conflictingAndDefined = definedNonDefaultOptions.find((defined) => option.conflictsWith.includes(defined.attributeName()));
2206
+ if (conflictingAndDefined) this._conflictingOption(option, conflictingAndDefined);
2207
+ });
2208
+ }
2209
+ /**
2210
+ * Display an error message if conflicting options are used together.
2211
+ * Called after checking for help flags in leaf subcommand.
2212
+ *
2213
+ * @private
2214
+ */
2215
+ _checkForConflictingOptions() {
2216
+ this._getCommandAndAncestors().forEach((cmd) => {
2217
+ cmd._checkForConflictingLocalOptions();
2218
+ });
2219
+ }
2220
+ /**
2221
+ * Parse options from `argv` removing known options,
2222
+ * and return argv split into operands and unknown arguments.
2223
+ *
2224
+ * Side effects: modifies command by storing options. Does not reset state if called again.
2225
+ *
2226
+ * Examples:
2227
+ *
2228
+ * argv => operands, unknown
2229
+ * --known kkk op => [op], []
2230
+ * op --known kkk => [op], []
2231
+ * sub --unknown uuu op => [sub], [--unknown uuu op]
2232
+ * sub -- --unknown uuu op => [sub --unknown uuu op], []
2233
+ *
2234
+ * @param {string[]} args
2235
+ * @return {{operands: string[], unknown: string[]}}
2236
+ */
2237
+ parseOptions(args) {
2238
+ const operands = [];
2239
+ const unknown = [];
2240
+ let dest = operands;
2241
+ function maybeOption(arg) {
2242
+ return arg.length > 1 && arg[0] === "-";
2243
+ }
2244
+ const negativeNumberArg = (arg) => {
2245
+ if (!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(arg)) return false;
2246
+ return !this._getCommandAndAncestors().some((cmd) => cmd.options.map((opt) => opt.short).some((short) => /^-\d$/.test(short)));
2247
+ };
2248
+ let activeVariadicOption = null;
2249
+ let activeGroup = null;
2250
+ let i = 0;
2251
+ while (i < args.length || activeGroup) {
2252
+ const arg = activeGroup ?? args[i++];
2253
+ activeGroup = null;
2254
+ if (arg === "--") {
2255
+ if (dest === unknown) dest.push(arg);
2256
+ dest.push(...args.slice(i));
2257
+ break;
2258
+ }
2259
+ if (activeVariadicOption && (!maybeOption(arg) || negativeNumberArg(arg))) {
2260
+ this.emit(`option:${activeVariadicOption.name()}`, arg);
2261
+ continue;
2262
+ }
2263
+ activeVariadicOption = null;
2264
+ if (maybeOption(arg)) {
2265
+ const option = this._findOption(arg);
2266
+ if (option) {
2267
+ if (option.required) {
2268
+ const value = args[i++];
2269
+ if (value === void 0) this.optionMissingArgument(option);
2270
+ this.emit(`option:${option.name()}`, value);
2271
+ } else if (option.optional) {
2272
+ let value = null;
2273
+ if (i < args.length && (!maybeOption(args[i]) || negativeNumberArg(args[i]))) value = args[i++];
2274
+ this.emit(`option:${option.name()}`, value);
2275
+ } else this.emit(`option:${option.name()}`);
2276
+ activeVariadicOption = option.variadic ? option : null;
2277
+ continue;
2278
+ }
2279
+ }
2280
+ if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
2281
+ const option = this._findOption(`-${arg[1]}`);
2282
+ if (option) {
2283
+ if (option.required || option.optional && this._combineFlagAndOptionalValue) this.emit(`option:${option.name()}`, arg.slice(2));
2284
+ else {
2285
+ this.emit(`option:${option.name()}`);
2286
+ activeGroup = `-${arg.slice(2)}`;
2287
+ }
2288
+ continue;
2289
+ }
2290
+ }
2291
+ if (/^--[^=]+=/.test(arg)) {
2292
+ const index = arg.indexOf("=");
2293
+ const option = this._findOption(arg.slice(0, index));
2294
+ if (option && (option.required || option.optional)) {
2295
+ this.emit(`option:${option.name()}`, arg.slice(index + 1));
2296
+ continue;
2297
+ }
2298
+ }
2299
+ if (dest === operands && maybeOption(arg) && !(this.commands.length === 0 && negativeNumberArg(arg))) dest = unknown;
2300
+ if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
2301
+ if (this._findCommand(arg)) {
2302
+ operands.push(arg);
2303
+ unknown.push(...args.slice(i));
2304
+ break;
2305
+ } else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
2306
+ operands.push(arg, ...args.slice(i));
2307
+ break;
2308
+ } else if (this._defaultCommandName) {
2309
+ unknown.push(arg, ...args.slice(i));
2310
+ break;
2311
+ }
2312
+ }
2313
+ if (this._passThroughOptions) {
2314
+ dest.push(arg, ...args.slice(i));
2315
+ break;
2316
+ }
2317
+ dest.push(arg);
2318
+ }
2319
+ return {
2320
+ operands,
2321
+ unknown
2322
+ };
2323
+ }
2324
+ /**
2325
+ * Return an object containing local option values as key-value pairs.
2326
+ *
2327
+ * @return {object}
2328
+ */
2329
+ opts() {
2330
+ if (this._storeOptionsAsProperties) {
2331
+ const result = {};
2332
+ const len = this.options.length;
2333
+ for (let i = 0; i < len; i++) {
2334
+ const key = this.options[i].attributeName();
2335
+ result[key] = key === this._versionOptionName ? this._version : this[key];
2336
+ }
2337
+ return result;
2338
+ }
2339
+ return this._optionValues;
2340
+ }
2341
+ /**
2342
+ * Return an object containing merged local and global option values as key-value pairs.
2343
+ *
2344
+ * @return {object}
2345
+ */
2346
+ optsWithGlobals() {
2347
+ return this._getCommandAndAncestors().reduce((combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()), {});
2348
+ }
2349
+ /**
2350
+ * Display error message and exit (or call exitOverride).
2351
+ *
2352
+ * @param {string} message
2353
+ * @param {object} [errorOptions]
2354
+ * @param {string} [errorOptions.code] - an id string representing the error
2355
+ * @param {number} [errorOptions.exitCode] - used with process.exit
2356
+ */
2357
+ error(message, errorOptions) {
2358
+ this._outputConfiguration.outputError(`${message}\n`, this._outputConfiguration.writeErr);
2359
+ if (typeof this._showHelpAfterError === "string") this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`);
2360
+ else if (this._showHelpAfterError) {
2361
+ this._outputConfiguration.writeErr("\n");
2362
+ this.outputHelp({ error: true });
2363
+ }
2364
+ const config = errorOptions || {};
2365
+ const exitCode = config.exitCode || 1;
2366
+ const code = config.code || "commander.error";
2367
+ this._exit(exitCode, code, message);
2368
+ }
2369
+ /**
2370
+ * Apply any option related environment variables, if option does
2371
+ * not have a value from cli or client code.
2372
+ *
2373
+ * @private
2374
+ */
2375
+ _parseOptionsEnv() {
2376
+ this.options.forEach((option) => {
2377
+ if (option.envVar && option.envVar in process.env) {
2378
+ const optionKey = option.attributeName();
2379
+ if (this.getOptionValue(optionKey) === void 0 || [
2380
+ "default",
2381
+ "config",
2382
+ "env"
2383
+ ].includes(this.getOptionValueSource(optionKey))) {
2384
+ if (option.required || option.optional) this.emit(`optionEnv:${option.name()}`, process.env[option.envVar]);
2385
+ else this.emit(`optionEnv:${option.name()}`);
2386
+ }
2387
+ }
2388
+ });
2389
+ }
2390
+ /**
2391
+ * Apply any implied option values, if option is undefined or default value.
2392
+ *
2393
+ * @private
2394
+ */
2395
+ _parseOptionsImplied() {
2396
+ const dualHelper = new DualOptions(this.options);
2397
+ const hasCustomOptionValue = (optionKey) => {
2398
+ return this.getOptionValue(optionKey) !== void 0 && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
2399
+ };
2400
+ this.options.filter((option) => option.implied !== void 0 && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(this.getOptionValue(option.attributeName()), option)).forEach((option) => {
2401
+ Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
2402
+ this.setOptionValueWithSource(impliedKey, option.implied[impliedKey], "implied");
2403
+ });
2404
+ });
2405
+ }
2406
+ /**
2407
+ * Argument `name` is missing.
2408
+ *
2409
+ * @param {string} name
2410
+ * @private
2411
+ */
2412
+ missingArgument(name) {
2413
+ const message = `error: missing required argument '${name}'`;
2414
+ this.error(message, { code: "commander.missingArgument" });
2415
+ }
2416
+ /**
2417
+ * `Option` is missing an argument.
2418
+ *
2419
+ * @param {Option} option
2420
+ * @private
2421
+ */
2422
+ optionMissingArgument(option) {
2423
+ const message = `error: option '${option.flags}' argument missing`;
2424
+ this.error(message, { code: "commander.optionMissingArgument" });
2425
+ }
2426
+ /**
2427
+ * `Option` does not have a value, and is a mandatory option.
2428
+ *
2429
+ * @param {Option} option
2430
+ * @private
2431
+ */
2432
+ missingMandatoryOptionValue(option) {
2433
+ const message = `error: required option '${option.flags}' not specified`;
2434
+ this.error(message, { code: "commander.missingMandatoryOptionValue" });
2435
+ }
2436
+ /**
2437
+ * `Option` conflicts with another option.
2438
+ *
2439
+ * @param {Option} option
2440
+ * @param {Option} conflictingOption
2441
+ * @private
2442
+ */
2443
+ _conflictingOption(option, conflictingOption) {
2444
+ const findBestOptionFromValue = (option) => {
2445
+ const optionKey = option.attributeName();
2446
+ const optionValue = this.getOptionValue(optionKey);
2447
+ const negativeOption = this.options.find((target) => target.negate && optionKey === target.attributeName());
2448
+ const positiveOption = this.options.find((target) => !target.negate && optionKey === target.attributeName());
2449
+ if (negativeOption && (negativeOption.presetArg === void 0 && optionValue === false || negativeOption.presetArg !== void 0 && optionValue === negativeOption.presetArg)) return negativeOption;
2450
+ return positiveOption || option;
2451
+ };
2452
+ const getErrorMessage = (option) => {
2453
+ const bestOption = findBestOptionFromValue(option);
2454
+ const optionKey = bestOption.attributeName();
2455
+ if (this.getOptionValueSource(optionKey) === "env") return `environment variable '${bestOption.envVar}'`;
2456
+ return `option '${bestOption.flags}'`;
2457
+ };
2458
+ const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
2459
+ this.error(message, { code: "commander.conflictingOption" });
2460
+ }
2461
+ /**
2462
+ * Unknown option `flag`.
2463
+ *
2464
+ * @param {string} flag
2465
+ * @private
2466
+ */
2467
+ unknownOption(flag) {
2468
+ if (this._allowUnknownOption) return;
2469
+ let suggestion = "";
2470
+ if (flag.startsWith("--") && this._showSuggestionAfterError) {
2471
+ let candidateFlags = [];
2472
+ let command = this;
2473
+ do {
2474
+ const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
2475
+ candidateFlags = candidateFlags.concat(moreFlags);
2476
+ command = command.parent;
2477
+ } while (command && !command._enablePositionalOptions);
2478
+ suggestion = suggestSimilar(flag, candidateFlags);
2479
+ }
2480
+ const message = `error: unknown option '${flag}'${suggestion}`;
2481
+ this.error(message, { code: "commander.unknownOption" });
2482
+ }
2483
+ /**
2484
+ * Excess arguments, more than expected.
2485
+ *
2486
+ * @param {string[]} receivedArgs
2487
+ * @private
2488
+ */
2489
+ _excessArguments(receivedArgs) {
2490
+ if (this._allowExcessArguments) return;
2491
+ const expected = this.registeredArguments.length;
2492
+ const s = expected === 1 ? "" : "s";
2493
+ const received = receivedArgs.length;
2494
+ const message = `error: too many arguments${this.parent ? ` for '${this.name()}'` : ""}. Expected ${expected} argument${s} but got ${received}: ${receivedArgs.join(", ")}.`;
2495
+ this.error(message, { code: "commander.excessArguments" });
2496
+ }
2497
+ /**
2498
+ * Unknown command.
2499
+ *
2500
+ * @private
2501
+ */
2502
+ unknownCommand() {
2503
+ const unknownName = this.args[0];
2504
+ let suggestion = "";
2505
+ if (this._showSuggestionAfterError) {
2506
+ const candidateNames = [];
2507
+ this.createHelp().visibleCommands(this).forEach((command) => {
2508
+ candidateNames.push(command.name());
2509
+ if (command.alias()) candidateNames.push(command.alias());
2510
+ });
2511
+ suggestion = suggestSimilar(unknownName, candidateNames);
2512
+ }
2513
+ const message = `error: unknown command '${unknownName}'${suggestion}`;
2514
+ this.error(message, { code: "commander.unknownCommand" });
2515
+ }
2516
+ /**
2517
+ * Get or set the program version.
2518
+ *
2519
+ * This method auto-registers the "-V, --version" option which will print the version number.
2520
+ *
2521
+ * You can optionally supply the flags and description to override the defaults.
2522
+ *
2523
+ * @param {string} [str]
2524
+ * @param {string} [flags]
2525
+ * @param {string} [description]
2526
+ * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments
2527
+ */
2528
+ version(str, flags, description) {
2529
+ if (str === void 0) return this._version;
2530
+ this._version = str;
2531
+ flags = flags || "-V, --version";
2532
+ description = description || "output the version number";
2533
+ const versionOption = this.createOption(flags, description);
2534
+ this._versionOptionName = versionOption.attributeName();
2535
+ this._registerOption(versionOption);
2536
+ this.on("option:" + versionOption.name(), () => {
2537
+ this._outputConfiguration.writeOut(`${str}\n`);
2538
+ this._exit(0, "commander.version", str);
2539
+ });
2540
+ return this;
2541
+ }
2542
+ /**
2543
+ * Set the description.
2544
+ *
2545
+ * @param {string} [str]
2546
+ * @param {object} [argsDescription]
2547
+ * @return {(string|Command)}
2548
+ */
2549
+ description(str, argsDescription) {
2550
+ if (str === void 0 && argsDescription === void 0) return this._description;
2551
+ this._description = str;
2552
+ if (argsDescription) this._argsDescription = argsDescription;
2553
+ return this;
2554
+ }
2555
+ /**
2556
+ * Set the summary. Used when listed as subcommand of parent.
2557
+ *
2558
+ * @param {string} [str]
2559
+ * @return {(string|Command)}
2560
+ */
2561
+ summary(str) {
2562
+ if (str === void 0) return this._summary;
2563
+ this._summary = str;
2564
+ return this;
2565
+ }
2566
+ /**
2567
+ * Set an alias for the command.
2568
+ *
2569
+ * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
2570
+ *
2571
+ * @param {string} [alias]
2572
+ * @return {(string|Command)}
2573
+ */
2574
+ alias(alias) {
2575
+ if (alias === void 0) return this._aliases[0];
2576
+ /** @type {Command} */
2577
+ let command = this;
2578
+ if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) command = this.commands[this.commands.length - 1];
2579
+ if (alias === command._name) throw new Error("Command alias can't be the same as its name");
2580
+ const matchingCommand = this.parent?._findCommand(alias);
2581
+ if (matchingCommand) {
2582
+ const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
2583
+ throw new Error(`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`);
2584
+ }
2585
+ command._aliases.push(alias);
2586
+ return this;
2587
+ }
2588
+ /**
2589
+ * Set aliases for the command.
2590
+ *
2591
+ * Only the first alias is shown in the auto-generated help.
2592
+ *
2593
+ * @param {string[]} [aliases]
2594
+ * @return {(string[]|Command)}
2595
+ */
2596
+ aliases(aliases) {
2597
+ if (aliases === void 0) return this._aliases;
2598
+ aliases.forEach((alias) => this.alias(alias));
2599
+ return this;
2600
+ }
2601
+ /**
2602
+ * Set / get the command usage `str`.
2603
+ *
2604
+ * @param {string} [str]
2605
+ * @return {(string|Command)}
2606
+ */
2607
+ usage(str) {
2608
+ if (str === void 0) {
2609
+ if (this._usage) return this._usage;
2610
+ const args = this.registeredArguments.map((arg) => {
2611
+ return humanReadableArgName(arg);
2612
+ });
2613
+ return [].concat(this.options.length || this._helpOption !== null ? "[options]" : [], this.commands.length ? "[command]" : [], this.registeredArguments.length ? args : []).join(" ");
2614
+ }
2615
+ this._usage = str;
2616
+ return this;
2617
+ }
2618
+ /**
2619
+ * Get or set the name of the command.
2620
+ *
2621
+ * @param {string} [str]
2622
+ * @return {(string|Command)}
2623
+ */
2624
+ name(str) {
2625
+ if (str === void 0) return this._name;
2626
+ this._name = str;
2627
+ return this;
2628
+ }
2629
+ /**
2630
+ * Set/get the help group heading for this subcommand in parent command's help.
2631
+ *
2632
+ * @param {string} [heading]
2633
+ * @return {Command | string}
2634
+ */
2635
+ helpGroup(heading) {
2636
+ if (heading === void 0) return this._helpGroupHeading ?? "";
2637
+ this._helpGroupHeading = heading;
2638
+ return this;
2639
+ }
2640
+ /**
2641
+ * Set/get the default help group heading for subcommands added to this command.
2642
+ * (This does not override a group set directly on the subcommand using .helpGroup().)
2643
+ *
2644
+ * @example
2645
+ * program.commandsGroup('Development Commands:);
2646
+ * program.command('watch')...
2647
+ * program.command('lint')...
2648
+ * ...
2649
+ *
2650
+ * @param {string} [heading]
2651
+ * @returns {Command | string}
2652
+ */
2653
+ commandsGroup(heading) {
2654
+ if (heading === void 0) return this._defaultCommandGroup ?? "";
2655
+ this._defaultCommandGroup = heading;
2656
+ return this;
2657
+ }
2658
+ /**
2659
+ * Set/get the default help group heading for options added to this command.
2660
+ * (This does not override a group set directly on the option using .helpGroup().)
2661
+ *
2662
+ * @example
2663
+ * program
2664
+ * .optionsGroup('Development Options:')
2665
+ * .option('-d, --debug', 'output extra debugging')
2666
+ * .option('-p, --profile', 'output profiling information')
2667
+ *
2668
+ * @param {string} [heading]
2669
+ * @returns {Command | string}
2670
+ */
2671
+ optionsGroup(heading) {
2672
+ if (heading === void 0) return this._defaultOptionGroup ?? "";
2673
+ this._defaultOptionGroup = heading;
2674
+ return this;
2675
+ }
2676
+ /**
2677
+ * @param {Option} option
2678
+ * @private
2679
+ */
2680
+ _initOptionGroup(option) {
2681
+ if (this._defaultOptionGroup && !option.helpGroupHeading) option.helpGroup(this._defaultOptionGroup);
2682
+ }
2683
+ /**
2684
+ * @param {Command} cmd
2685
+ * @private
2686
+ */
2687
+ _initCommandGroup(cmd) {
2688
+ if (this._defaultCommandGroup && !cmd.helpGroup()) cmd.helpGroup(this._defaultCommandGroup);
2689
+ }
2690
+ /**
2691
+ * Set the name of the command from script filename, such as process.argv[1],
2692
+ * or import.meta.filename.
2693
+ *
2694
+ * (Used internally and public although not documented in README.)
2695
+ *
2696
+ * @example
2697
+ * program.nameFromFilename(import.meta.filename);
2698
+ *
2699
+ * @param {string} filename
2700
+ * @return {Command}
2701
+ */
2702
+ nameFromFilename(filename) {
2703
+ this._name = path.basename(filename, path.extname(filename));
2704
+ return this;
2705
+ }
2706
+ /**
2707
+ * Get or set the directory for searching for executable subcommands of this command.
2708
+ *
2709
+ * @example
2710
+ * program.executableDir(import.meta.dirname);
2711
+ * // or
2712
+ * program.executableDir('subcommands');
2713
+ *
2714
+ * @param {string} [path]
2715
+ * @return {(string|null|Command)}
2716
+ */
2717
+ executableDir(path) {
2718
+ if (path === void 0) return this._executableDir;
2719
+ this._executableDir = path;
2720
+ return this;
2721
+ }
2722
+ /**
2723
+ * Return program help documentation.
2724
+ *
2725
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
2726
+ * @return {string}
2727
+ */
2728
+ helpInformation(contextOptions) {
2729
+ const helper = this.createHelp();
2730
+ const context = this._getOutputContext(contextOptions);
2731
+ helper.prepareContext({
2732
+ error: context.error,
2733
+ helpWidth: context.helpWidth,
2734
+ outputHasColors: context.hasColors
2735
+ });
2736
+ const text = helper.formatHelp(this, helper);
2737
+ if (context.hasColors) return text;
2738
+ return this._outputConfiguration.stripColor(text);
2739
+ }
2740
+ /**
2741
+ * @typedef HelpContext
2742
+ * @type {object}
2743
+ * @property {boolean} error
2744
+ * @property {number} helpWidth
2745
+ * @property {boolean} hasColors
2746
+ * @property {function} write - includes stripColor if needed
2747
+ *
2748
+ * @returns {HelpContext}
2749
+ * @private
2750
+ */
2751
+ _getOutputContext(contextOptions) {
2752
+ contextOptions = contextOptions || {};
2753
+ const error = !!contextOptions.error;
2754
+ let baseWrite;
2755
+ let hasColors;
2756
+ let helpWidth;
2757
+ if (error) {
2758
+ baseWrite = (str) => this._outputConfiguration.writeErr(str);
2759
+ hasColors = this._outputConfiguration.getErrHasColors();
2760
+ helpWidth = this._outputConfiguration.getErrHelpWidth();
2761
+ } else {
2762
+ baseWrite = (str) => this._outputConfiguration.writeOut(str);
2763
+ hasColors = this._outputConfiguration.getOutHasColors();
2764
+ helpWidth = this._outputConfiguration.getOutHelpWidth();
2765
+ }
2766
+ const write = (str) => {
2767
+ if (!hasColors) str = this._outputConfiguration.stripColor(str);
2768
+ return baseWrite(str);
2769
+ };
2770
+ return {
2771
+ error,
2772
+ write,
2773
+ hasColors,
2774
+ helpWidth
2775
+ };
2776
+ }
2777
+ /**
2778
+ * Output help information for this command.
2779
+ *
2780
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
2781
+ *
2782
+ * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
2783
+ */
2784
+ outputHelp(contextOptions) {
2785
+ let deprecatedCallback;
2786
+ if (typeof contextOptions === "function") {
2787
+ deprecatedCallback = contextOptions;
2788
+ contextOptions = void 0;
2789
+ }
2790
+ const outputContext = this._getOutputContext(contextOptions);
2791
+ /** @type {HelpTextEventContext} */
2792
+ const eventContext = {
2793
+ error: outputContext.error,
2794
+ write: outputContext.write,
2795
+ command: this
2796
+ };
2797
+ this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", eventContext));
2798
+ this.emit("beforeHelp", eventContext);
2799
+ let helpInformation = this.helpInformation({ error: outputContext.error });
2800
+ if (deprecatedCallback) {
2801
+ helpInformation = deprecatedCallback(helpInformation);
2802
+ if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) throw new Error("outputHelp callback must return a string or a Buffer");
2803
+ }
2804
+ outputContext.write(helpInformation);
2805
+ if (this._getHelpOption()?.long) this.emit(this._getHelpOption().long);
2806
+ this.emit("afterHelp", eventContext);
2807
+ this._getCommandAndAncestors().forEach((command) => command.emit("afterAllHelp", eventContext));
2808
+ }
2809
+ /**
2810
+ * You can pass in flags and a description to customise the built-in help option.
2811
+ * Pass in false to disable the built-in help option.
2812
+ *
2813
+ * @example
2814
+ * program.helpOption('-?, --help' 'show help'); // customise
2815
+ * program.helpOption(false); // disable
2816
+ *
2817
+ * @param {(string | boolean)} flags
2818
+ * @param {string} [description]
2819
+ * @return {Command} `this` command for chaining
2820
+ */
2821
+ helpOption(flags, description) {
2822
+ if (typeof flags === "boolean") {
2823
+ if (flags) {
2824
+ if (this._helpOption === null) this._helpOption = void 0;
2825
+ if (this._defaultOptionGroup) this._initOptionGroup(this._getHelpOption());
2826
+ } else this._helpOption = null;
2827
+ return this;
2828
+ }
2829
+ this._helpOption = this.createOption(flags ?? "-h, --help", description ?? "display help for command");
2830
+ if (flags || description) this._initOptionGroup(this._helpOption);
2831
+ return this;
2832
+ }
2833
+ /**
2834
+ * Lazy create help option.
2835
+ * Returns null if has been disabled with .helpOption(false).
2836
+ *
2837
+ * @returns {(Option | null)} the help option
2838
+ * @package
2839
+ */
2840
+ _getHelpOption() {
2841
+ if (this._helpOption === void 0) this.helpOption(void 0, void 0);
2842
+ return this._helpOption;
2843
+ }
2844
+ /**
2845
+ * Supply your own option to use for the built-in help option.
2846
+ * This is an alternative to using helpOption() to customise the flags and description etc.
2847
+ *
2848
+ * @param {Option} option
2849
+ * @return {Command} `this` command for chaining
2850
+ */
2851
+ addHelpOption(option) {
2852
+ this._helpOption = option;
2853
+ this._initOptionGroup(option);
2854
+ return this;
2855
+ }
2856
+ /**
2857
+ * Output help information and exit.
2858
+ *
2859
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
2860
+ *
2861
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
2862
+ */
2863
+ help(contextOptions) {
2864
+ this.outputHelp(contextOptions);
2865
+ let exitCode = Number(process.exitCode ?? 0);
2866
+ if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) exitCode = 1;
2867
+ this._exit(exitCode, "commander.help", "(outputHelp)");
2868
+ }
2869
+ /**
2870
+ * // Do a little typing to coordinate emit and listener for the help text events.
2871
+ * @typedef HelpTextEventContext
2872
+ * @type {object}
2873
+ * @property {boolean} error
2874
+ * @property {Command} command
2875
+ * @property {function} write
2876
+ */
2877
+ /**
2878
+ * Add additional text to be displayed with the built-in help.
2879
+ *
2880
+ * Position is 'before' or 'after' to affect just this command,
2881
+ * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
2882
+ *
2883
+ * @param {string} position - before or after built-in help
2884
+ * @param {(string | Function)} text - string to add, or a function returning a string
2885
+ * @return {Command} `this` command for chaining
2886
+ */
2887
+ addHelpText(position, text) {
2888
+ const allowedValues = [
2889
+ "beforeAll",
2890
+ "before",
2891
+ "after",
2892
+ "afterAll"
2893
+ ];
2894
+ if (!allowedValues.includes(position)) throw new Error(`Unexpected value for position to addHelpText.
2895
+ Expecting one of '${allowedValues.join("', '")}'`);
2896
+ const helpEvent = `${position}Help`;
2897
+ this.on(helpEvent, (context) => {
2898
+ let helpStr;
2899
+ if (typeof text === "function") helpStr = text({
2900
+ error: context.error,
2901
+ command: context.command
2902
+ });
2903
+ else helpStr = text;
2904
+ if (helpStr) context.write(`${helpStr}\n`);
2905
+ });
2906
+ return this;
2907
+ }
2908
+ /**
2909
+ * Output help information if help flags specified
2910
+ *
2911
+ * @param {Array} args - array of options to search for help flags
2912
+ * @private
2913
+ */
2914
+ _outputHelpIfRequested(args) {
2915
+ const helpOption = this._getHelpOption();
2916
+ if (helpOption && args.find((arg) => helpOption.is(arg))) {
2917
+ this.outputHelp();
2918
+ this._exit(0, "commander.helpDisplayed", "(outputHelp)");
2919
+ }
2920
+ }
2921
+ };
2922
+ /**
2923
+ * Scan arguments and increment port number for inspect calls (to avoid conflicts when spawning new command).
2924
+ *
2925
+ * @param {string[]} args - array of arguments from node.execArgv
2926
+ * @returns {string[]}
2927
+ * @private
2928
+ */
2929
+ function incrementNodeInspectorPort(args) {
2930
+ return args.map((arg) => {
2931
+ if (!arg.startsWith("--inspect")) return arg;
2932
+ let debugOption;
2933
+ let debugHost = "127.0.0.1";
2934
+ let debugPort = "9229";
2935
+ let match;
2936
+ if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) debugOption = match[1];
2937
+ else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
2938
+ debugOption = match[1];
2939
+ if (/^\d+$/.test(match[3])) debugPort = match[3];
2940
+ else debugHost = match[3];
2941
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
2942
+ debugOption = match[1];
2943
+ debugHost = match[3];
2944
+ debugPort = match[4];
2945
+ }
2946
+ if (debugOption && debugPort !== "0") return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
2947
+ return arg;
2948
+ });
2949
+ }
2950
+ /**
2951
+ * Exported for using from tests, not otherwise used outside this file.
2952
+ *
2953
+ * @returns {boolean | undefined}
2954
+ * @package
2955
+ */
2956
+ function useColor() {
2957
+ if (process.env.NO_COLOR || process.env.FORCE_COLOR === "0" || process.env.FORCE_COLOR === "false") return false;
2958
+ if (process.env.FORCE_COLOR || process.env.CLICOLOR_FORCE !== void 0) return true;
2959
+ }
2960
+ new Command();
2961
+ //#endregion
2962
+ export { InvalidArgumentError as i, Option as n, Help as r, Command as t };