@capytale/activity.js 2.9.3

Sign up to get free protection for your applications and to get access to all the features.
Files changed (455) hide show
  1. package/README.md +41 -0
  2. package/activity/activityBunch/all/index.d.ts +21 -0
  3. package/activity/activityBunch/all/index.d.ts.map +1 -0
  4. package/activity/activityBunch/all/index.js +10 -0
  5. package/activity/activityBunch/all/index.js.map +1 -0
  6. package/activity/activityBunch/backend.d.ts +9 -0
  7. package/activity/activityBunch/backend.d.ts.map +1 -0
  8. package/activity/activityBunch/backend.js +59 -0
  9. package/activity/activityBunch/backend.js.map +1 -0
  10. package/activity/activityBunch/base/console.d.ts +20 -0
  11. package/activity/activityBunch/base/console.d.ts.map +1 -0
  12. package/activity/activityBunch/base/console.js +26 -0
  13. package/activity/activityBunch/base/console.js.map +1 -0
  14. package/activity/activityBunch/base/db.d.ts +16 -0
  15. package/activity/activityBunch/base/db.d.ts.map +1 -0
  16. package/activity/activityBunch/base/db.js +26 -0
  17. package/activity/activityBunch/base/db.js.map +1 -0
  18. package/activity/activityBunch/base/fs.d.ts +19 -0
  19. package/activity/activityBunch/base/fs.d.ts.map +1 -0
  20. package/activity/activityBunch/base/fs.js +26 -0
  21. package/activity/activityBunch/base/fs.js.map +1 -0
  22. package/activity/activityBunch/base/index.d.ts +61 -0
  23. package/activity/activityBunch/base/index.d.ts.map +1 -0
  24. package/activity/activityBunch/base/index.js +72 -0
  25. package/activity/activityBunch/base/index.js.map +1 -0
  26. package/activity/activityBunch/base/nodes/activity.d.ts +10 -0
  27. package/activity/activityBunch/base/nodes/activity.d.ts.map +1 -0
  28. package/activity/activityBunch/base/nodes/activity.db.d.ts +17 -0
  29. package/activity/activityBunch/base/nodes/activity.db.d.ts.map +1 -0
  30. package/activity/activityBunch/base/nodes/activity.db.js +12 -0
  31. package/activity/activityBunch/base/nodes/activity.db.js.map +1 -0
  32. package/activity/activityBunch/base/nodes/activity.fs.d.ts +17 -0
  33. package/activity/activityBunch/base/nodes/activity.fs.d.ts.map +1 -0
  34. package/activity/activityBunch/base/nodes/activity.fs.js +12 -0
  35. package/activity/activityBunch/base/nodes/activity.fs.js.map +1 -0
  36. package/activity/activityBunch/base/nodes/activity.js +10 -0
  37. package/activity/activityBunch/base/nodes/activity.js.map +1 -0
  38. package/activity/activityBunch/base/nodes/base.d.ts +50 -0
  39. package/activity/activityBunch/base/nodes/base.d.ts.map +1 -0
  40. package/activity/activityBunch/base/nodes/base.js +71 -0
  41. package/activity/activityBunch/base/nodes/base.js.map +1 -0
  42. package/activity/activityBunch/base/nodes/console.d.ts +19 -0
  43. package/activity/activityBunch/base/nodes/console.d.ts.map +1 -0
  44. package/activity/activityBunch/base/nodes/console.js +18 -0
  45. package/activity/activityBunch/base/nodes/console.js.map +1 -0
  46. package/activity/activityBunch/base/nodes/notebook.d.ts +19 -0
  47. package/activity/activityBunch/base/nodes/notebook.d.ts.map +1 -0
  48. package/activity/activityBunch/base/nodes/notebook.js +18 -0
  49. package/activity/activityBunch/base/nodes/notebook.js.map +1 -0
  50. package/activity/activityBunch/base/notebook.d.ts +23 -0
  51. package/activity/activityBunch/base/notebook.d.ts.map +1 -0
  52. package/activity/activityBunch/base/notebook.js +26 -0
  53. package/activity/activityBunch/base/notebook.js.map +1 -0
  54. package/activity/activityBunch/blockpython/index.d.ts +3 -0
  55. package/activity/activityBunch/blockpython/index.d.ts.map +1 -0
  56. package/activity/activityBunch/blockpython/index.js +3 -0
  57. package/activity/activityBunch/blockpython/index.js.map +1 -0
  58. package/activity/activityBunch/codabloc/index.d.ts +3 -0
  59. package/activity/activityBunch/codabloc/index.d.ts.map +1 -0
  60. package/activity/activityBunch/codabloc/index.js +3 -0
  61. package/activity/activityBunch/codabloc/index.js.map +1 -0
  62. package/activity/activityBunch/codepuzzle/index.d.ts +3 -0
  63. package/activity/activityBunch/codepuzzle/index.d.ts.map +1 -0
  64. package/activity/activityBunch/codepuzzle/index.js +3 -0
  65. package/activity/activityBunch/codepuzzle/index.js.map +1 -0
  66. package/activity/activityBunch/console/index.d.ts +3 -0
  67. package/activity/activityBunch/console/index.d.ts.map +1 -0
  68. package/activity/activityBunch/console/index.js +3 -0
  69. package/activity/activityBunch/console/index.js.map +1 -0
  70. package/activity/activityBunch/geogebra/default.d.ts +6 -0
  71. package/activity/activityBunch/geogebra/default.d.ts.map +1 -0
  72. package/activity/activityBunch/geogebra/default.js +5 -0
  73. package/activity/activityBunch/geogebra/default.js.map +1 -0
  74. package/activity/activityBunch/geogebra/index.d.ts +7 -0
  75. package/activity/activityBunch/geogebra/index.d.ts.map +1 -0
  76. package/activity/activityBunch/geogebra/index.js +15 -0
  77. package/activity/activityBunch/geogebra/index.js.map +1 -0
  78. package/activity/activityBunch/html/default.d.ts +7 -0
  79. package/activity/activityBunch/html/default.d.ts.map +1 -0
  80. package/activity/activityBunch/html/default.js +6 -0
  81. package/activity/activityBunch/html/default.js.map +1 -0
  82. package/activity/activityBunch/html/html.d.ts +17 -0
  83. package/activity/activityBunch/html/html.d.ts.map +1 -0
  84. package/activity/activityBunch/html/html.js +22 -0
  85. package/activity/activityBunch/html/html.js.map +1 -0
  86. package/activity/activityBunch/html/index.d.ts +3 -0
  87. package/activity/activityBunch/html/index.d.ts.map +1 -0
  88. package/activity/activityBunch/html/index.js +3 -0
  89. package/activity/activityBunch/html/index.js.map +1 -0
  90. package/activity/activityBunch/html/nodes.d.ts +23 -0
  91. package/activity/activityBunch/html/nodes.d.ts.map +1 -0
  92. package/activity/activityBunch/html/nodes.js +19 -0
  93. package/activity/activityBunch/html/nodes.js.map +1 -0
  94. package/activity/activityBunch/notebook/index.d.ts +3 -0
  95. package/activity/activityBunch/notebook/index.d.ts.map +1 -0
  96. package/activity/activityBunch/notebook/index.js +3 -0
  97. package/activity/activityBunch/notebook/index.js.map +1 -0
  98. package/activity/activityBunch/ocaml/index.d.ts +3 -0
  99. package/activity/activityBunch/ocaml/index.d.ts.map +1 -0
  100. package/activity/activityBunch/ocaml/index.js +3 -0
  101. package/activity/activityBunch/ocaml/index.js.map +1 -0
  102. package/activity/activityBunch/pixel/default.d.ts +6 -0
  103. package/activity/activityBunch/pixel/default.d.ts.map +1 -0
  104. package/activity/activityBunch/pixel/default.js +5 -0
  105. package/activity/activityBunch/pixel/default.js.map +1 -0
  106. package/activity/activityBunch/pixel/index.d.ts +3 -0
  107. package/activity/activityBunch/pixel/index.d.ts.map +1 -0
  108. package/activity/activityBunch/pixel/index.js +3 -0
  109. package/activity/activityBunch/pixel/index.js.map +1 -0
  110. package/activity/activityBunch/pixel/pixel.d.ts +6 -0
  111. package/activity/activityBunch/pixel/pixel.d.ts.map +1 -0
  112. package/activity/activityBunch/pixel/pixel.js +13 -0
  113. package/activity/activityBunch/pixel/pixel.js.map +1 -0
  114. package/activity/activityBunch/sql/index.d.ts +3 -0
  115. package/activity/activityBunch/sql/index.d.ts.map +1 -0
  116. package/activity/activityBunch/sql/index.js +3 -0
  117. package/activity/activityBunch/sql/index.js.map +1 -0
  118. package/activity/activityBunch/uni/backend.d.ts +12 -0
  119. package/activity/activityBunch/uni/backend.d.ts.map +1 -0
  120. package/activity/activityBunch/uni/backend.js +37 -0
  121. package/activity/activityBunch/uni/backend.js.map +1 -0
  122. package/activity/activityBunch/uni/index.d.ts +3 -0
  123. package/activity/activityBunch/uni/index.d.ts.map +1 -0
  124. package/activity/activityBunch/uni/index.js +3 -0
  125. package/activity/activityBunch/uni/index.js.map +1 -0
  126. package/activity/activityBunch/uni/nodes.d.ts +19 -0
  127. package/activity/activityBunch/uni/nodes.d.ts.map +1 -0
  128. package/activity/activityBunch/uni/nodes.js +17 -0
  129. package/activity/activityBunch/uni/nodes.js.map +1 -0
  130. package/activity/activityBunch/uni/uni.d.ts +23 -0
  131. package/activity/activityBunch/uni/uni.d.ts.map +1 -0
  132. package/activity/activityBunch/uni/uni.js +18 -0
  133. package/activity/activityBunch/uni/uni.js.map +1 -0
  134. package/activity/activitySession/backend.d.ts +9 -0
  135. package/activity/activitySession/backend.d.ts.map +1 -0
  136. package/activity/activitySession/backend.js +47 -0
  137. package/activity/activitySession/backend.js.map +1 -0
  138. package/activity/activitySession/index.d.ts +33 -0
  139. package/activity/activitySession/index.d.ts.map +1 -0
  140. package/activity/activitySession/index.js +63 -0
  141. package/activity/activitySession/index.js.map +1 -0
  142. package/activity/activitySession/uni/backend.d.ts +10 -0
  143. package/activity/activitySession/uni/backend.d.ts.map +1 -0
  144. package/activity/activitySession/uni/backend.js +47 -0
  145. package/activity/activitySession/uni/backend.js.map +1 -0
  146. package/activity/activitySession/uni/index.d.ts +4 -0
  147. package/activity/activitySession/uni/index.d.ts.map +1 -0
  148. package/activity/activitySession/uni/index.js +3 -0
  149. package/activity/activitySession/uni/index.js.map +1 -0
  150. package/activity/activityType/activityType.d.ts +23 -0
  151. package/activity/activityType/activityType.d.ts.map +1 -0
  152. package/activity/activityType/activityType.js +2 -0
  153. package/activity/activityType/activityType.js.map +1 -0
  154. package/activity/activityType/backend.d.ts +8 -0
  155. package/activity/activityType/backend.d.ts.map +1 -0
  156. package/activity/activityType/backend.js +11 -0
  157. package/activity/activityType/backend.js.map +1 -0
  158. package/activity/archiver/all/index.d.ts +25 -0
  159. package/activity/archiver/all/index.d.ts.map +1 -0
  160. package/activity/archiver/all/index.js +37 -0
  161. package/activity/archiver/all/index.js.map +1 -0
  162. package/activity/archiver/base/index.d.ts +92 -0
  163. package/activity/archiver/base/index.d.ts.map +1 -0
  164. package/activity/archiver/base/index.js +140 -0
  165. package/activity/archiver/base/index.js.map +1 -0
  166. package/activity/archiver/codabloc/index.d.ts +2 -0
  167. package/activity/archiver/codabloc/index.d.ts.map +1 -0
  168. package/activity/archiver/codabloc/index.js +32 -0
  169. package/activity/archiver/codabloc/index.js.map +1 -0
  170. package/activity/archiver/codabloc/void.sb3.d.ts +3 -0
  171. package/activity/archiver/codabloc/void.sb3.d.ts.map +1 -0
  172. package/activity/archiver/codabloc/void.sb3.js +2 -0
  173. package/activity/archiver/codabloc/void.sb3.js.map +1 -0
  174. package/activity/archiver/codepuzzle/index.d.ts +2 -0
  175. package/activity/archiver/codepuzzle/index.d.ts.map +1 -0
  176. package/activity/archiver/codepuzzle/index.js +23 -0
  177. package/activity/archiver/codepuzzle/index.js.map +1 -0
  178. package/activity/archiver/console/index.d.ts +2 -0
  179. package/activity/archiver/console/index.d.ts.map +1 -0
  180. package/activity/archiver/console/index.js +34 -0
  181. package/activity/archiver/console/index.js.map +1 -0
  182. package/activity/archiver/geogebra/index.d.ts +2 -0
  183. package/activity/archiver/geogebra/index.d.ts.map +1 -0
  184. package/activity/archiver/geogebra/index.js +35 -0
  185. package/activity/archiver/geogebra/index.js.map +1 -0
  186. package/activity/archiver/geogebra/void.ggb.d.ts +3 -0
  187. package/activity/archiver/geogebra/void.ggb.d.ts.map +1 -0
  188. package/activity/archiver/geogebra/void.ggb.js +2 -0
  189. package/activity/archiver/geogebra/void.ggb.js.map +1 -0
  190. package/activity/archiver/html/index.d.ts +2 -0
  191. package/activity/archiver/html/index.d.ts.map +1 -0
  192. package/activity/archiver/html/index.js +28 -0
  193. package/activity/archiver/html/index.js.map +1 -0
  194. package/activity/archiver/notebook/index.d.ts +2 -0
  195. package/activity/archiver/notebook/index.d.ts.map +1 -0
  196. package/activity/archiver/notebook/index.js +36 -0
  197. package/activity/archiver/notebook/index.js.map +1 -0
  198. package/activity/archiver/notebook/pyRename.d.ts +2 -0
  199. package/activity/archiver/notebook/pyRename.d.ts.map +1 -0
  200. package/activity/archiver/notebook/pyRename.js +5 -0
  201. package/activity/archiver/notebook/pyRename.js.map +1 -0
  202. package/activity/archiver/ocaml/index.d.ts +2 -0
  203. package/activity/archiver/ocaml/index.d.ts.map +1 -0
  204. package/activity/archiver/ocaml/index.js +27 -0
  205. package/activity/archiver/ocaml/index.js.map +1 -0
  206. package/activity/archiver/pixel/index.d.ts +2 -0
  207. package/activity/archiver/pixel/index.d.ts.map +1 -0
  208. package/activity/archiver/pixel/index.js +27 -0
  209. package/activity/archiver/pixel/index.js.map +1 -0
  210. package/activity/archiver/sql/index.d.ts +2 -0
  211. package/activity/archiver/sql/index.d.ts.map +1 -0
  212. package/activity/archiver/sql/index.js +27 -0
  213. package/activity/archiver/sql/index.js.map +1 -0
  214. package/activity/error.d.ts +4 -0
  215. package/activity/error.d.ts.map +1 -0
  216. package/activity/error.js +7 -0
  217. package/activity/error.js.map +1 -0
  218. package/activity/evaluation/backend.d.ts +31 -0
  219. package/activity/evaluation/backend.d.ts.map +1 -0
  220. package/activity/evaluation/backend.js +217 -0
  221. package/activity/evaluation/backend.js.map +1 -0
  222. package/activity/evaluation/evaluation.d.ts +63 -0
  223. package/activity/evaluation/evaluation.d.ts.map +1 -0
  224. package/activity/evaluation/evaluation.js +2 -0
  225. package/activity/evaluation/evaluation.js.map +1 -0
  226. package/activity/evaluation/sendBackend.d.ts +12 -0
  227. package/activity/evaluation/sendBackend.d.ts.map +1 -0
  228. package/activity/evaluation/sendBackend.js +39 -0
  229. package/activity/evaluation/sendBackend.js.map +1 -0
  230. package/activity/field/config.d.ts +26 -0
  231. package/activity/field/config.d.ts.map +1 -0
  232. package/activity/field/config.js +75 -0
  233. package/activity/field/config.js.map +1 -0
  234. package/activity/field/const.d.ts +32 -0
  235. package/activity/field/const.d.ts.map +1 -0
  236. package/activity/field/const.js +75 -0
  237. package/activity/field/const.js.map +1 -0
  238. package/activity/field/merge.d.ts +41 -0
  239. package/activity/field/merge.d.ts.map +1 -0
  240. package/activity/field/merge.js +66 -0
  241. package/activity/field/merge.js.map +1 -0
  242. package/activity/field/multiFormatedText.d.ts +21 -0
  243. package/activity/field/multiFormatedText.d.ts.map +1 -0
  244. package/activity/field/multiFormatedText.js +73 -0
  245. package/activity/field/multiFormatedText.js.map +1 -0
  246. package/activity/field/workflow.d.ts +4 -0
  247. package/activity/field/workflow.d.ts.map +1 -0
  248. package/activity/field/workflow.js +21 -0
  249. package/activity/field/workflow.js.map +1 -0
  250. package/activity/iterator.d.ts +12 -0
  251. package/activity/iterator.d.ts.map +1 -0
  252. package/activity/iterator.js +47 -0
  253. package/activity/iterator.js.map +1 -0
  254. package/api/csrf/csrfBackend.d.ts +8 -0
  255. package/api/csrf/csrfBackend.d.ts.map +1 -0
  256. package/api/csrf/csrfBackend.js +2 -0
  257. package/api/csrf/csrfBackend.js.map +1 -0
  258. package/api/fs/fsBackend.d.ts +15 -0
  259. package/api/fs/fsBackend.d.ts.map +1 -0
  260. package/api/fs/fsBackend.js +2 -0
  261. package/api/fs/fsBackend.js.map +1 -0
  262. package/api/fs/httpFsBackend.d.ts +5 -0
  263. package/api/fs/httpFsBackend.d.ts.map +1 -0
  264. package/api/fs/httpFsBackend.js +25 -0
  265. package/api/fs/httpFsBackend.js.map +1 -0
  266. package/api/http/backend.d.ts +28 -0
  267. package/api/http/backend.d.ts.map +1 -0
  268. package/api/http/backend.js +99 -0
  269. package/api/http/backend.js.map +1 -0
  270. package/api/http/error.d.ts +8 -0
  271. package/api/http/error.d.ts.map +1 -0
  272. package/api/http/error.js +14 -0
  273. package/api/http/error.js.map +1 -0
  274. package/api/http/route.d.ts +6 -0
  275. package/api/http/route.d.ts.map +1 -0
  276. package/api/http/route.js +2 -0
  277. package/api/http/route.js.map +1 -0
  278. package/api/me/backend.d.ts +16 -0
  279. package/api/me/backend.d.ts.map +1 -0
  280. package/api/me/backend.js +16 -0
  281. package/api/me/backend.js.map +1 -0
  282. package/api/rest/error.d.ts +4 -0
  283. package/api/rest/error.d.ts.map +1 -0
  284. package/api/rest/error.js +7 -0
  285. package/api/rest/error.js.map +1 -0
  286. package/api/rest/field.d.ts +45 -0
  287. package/api/rest/field.d.ts.map +1 -0
  288. package/api/rest/field.js +190 -0
  289. package/api/rest/field.js.map +1 -0
  290. package/api/rest/httpRestBackend.d.ts +5 -0
  291. package/api/rest/httpRestBackend.d.ts.map +1 -0
  292. package/api/rest/httpRestBackend.js +35 -0
  293. package/api/rest/httpRestBackend.js.map +1 -0
  294. package/api/rest/restBackend.d.ts +7 -0
  295. package/api/rest/restBackend.d.ts.map +1 -0
  296. package/api/rest/restBackend.js +2 -0
  297. package/api/rest/restBackend.js.map +1 -0
  298. package/api/rest/restObject.d.ts +12 -0
  299. package/api/rest/restObject.d.ts.map +1 -0
  300. package/api/rest/restObject.js +2 -0
  301. package/api/rest/restObject.js.map +1 -0
  302. package/api/time/backend.d.ts +4 -0
  303. package/api/time/backend.d.ts.map +1 -0
  304. package/api/time/backend.js +6 -0
  305. package/api/time/backend.js.map +1 -0
  306. package/api/time/clock.d.ts +7 -0
  307. package/api/time/clock.d.ts.map +1 -0
  308. package/api/time/clock.js +24 -0
  309. package/api/time/clock.js.map +1 -0
  310. package/auth/ent/backend.d.ts +7 -0
  311. package/auth/ent/backend.d.ts.map +1 -0
  312. package/auth/ent/backend.js +8 -0
  313. package/auth/ent/backend.js.map +1 -0
  314. package/auth/ent/entData.d.ts +8 -0
  315. package/auth/ent/entData.d.ts.map +1 -0
  316. package/auth/ent/entData.js +2 -0
  317. package/auth/ent/entData.js.map +1 -0
  318. package/auth/sesame/backend.d.ts +49 -0
  319. package/auth/sesame/backend.d.ts.map +1 -0
  320. package/auth/sesame/backend.js +57 -0
  321. package/auth/sesame/backend.js.map +1 -0
  322. package/auth/sesame/sesameCode.d.ts +18 -0
  323. package/auth/sesame/sesameCode.d.ts.map +1 -0
  324. package/auth/sesame/sesameCode.js +2 -0
  325. package/auth/sesame/sesameCode.js.map +1 -0
  326. package/auth/sesame/sesameUser.d.ts +99 -0
  327. package/auth/sesame/sesameUser.d.ts.map +1 -0
  328. package/auth/sesame/sesameUser.js +2 -0
  329. package/auth/sesame/sesameUser.js.map +1 -0
  330. package/backend/capytale/activityBunch.d.ts +5 -0
  331. package/backend/capytale/activityBunch.d.ts.map +1 -0
  332. package/backend/capytale/activityBunch.js +6 -0
  333. package/backend/capytale/activityBunch.js.map +1 -0
  334. package/backend/capytale/activitySession.d.ts +5 -0
  335. package/backend/capytale/activitySession.d.ts.map +1 -0
  336. package/backend/capytale/activitySession.js +9 -0
  337. package/backend/capytale/activitySession.js.map +1 -0
  338. package/backend/capytale/activityType.d.ts +6 -0
  339. package/backend/capytale/activityType.d.ts.map +1 -0
  340. package/backend/capytale/activityType.js +4 -0
  341. package/backend/capytale/activityType.js.map +1 -0
  342. package/backend/capytale/clock.d.ts +3 -0
  343. package/backend/capytale/clock.d.ts.map +1 -0
  344. package/backend/capytale/clock.js +5 -0
  345. package/backend/capytale/clock.js.map +1 -0
  346. package/backend/capytale/csrf.d.ts +4 -0
  347. package/backend/capytale/csrf.d.ts.map +1 -0
  348. package/backend/capytale/csrf.js +29 -0
  349. package/backend/capytale/csrf.js.map +1 -0
  350. package/backend/capytale/ent.d.ts +3 -0
  351. package/backend/capytale/ent.d.ts.map +1 -0
  352. package/backend/capytale/ent.js +4 -0
  353. package/backend/capytale/ent.js.map +1 -0
  354. package/backend/capytale/evaluation.d.ts +6 -0
  355. package/backend/capytale/evaluation.d.ts.map +1 -0
  356. package/backend/capytale/evaluation.js +5 -0
  357. package/backend/capytale/evaluation.js.map +1 -0
  358. package/backend/capytale/fs.d.ts +4 -0
  359. package/backend/capytale/fs.d.ts.map +1 -0
  360. package/backend/capytale/fs.js +6 -0
  361. package/backend/capytale/fs.js.map +1 -0
  362. package/backend/capytale/http.d.ts +4 -0
  363. package/backend/capytale/http.d.ts.map +1 -0
  364. package/backend/capytale/http.js +5 -0
  365. package/backend/capytale/http.js.map +1 -0
  366. package/backend/capytale/me.d.ts +5 -0
  367. package/backend/capytale/me.d.ts.map +1 -0
  368. package/backend/capytale/me.js +4 -0
  369. package/backend/capytale/me.js.map +1 -0
  370. package/backend/capytale/resolver.d.ts +3 -0
  371. package/backend/capytale/resolver.d.ts.map +1 -0
  372. package/backend/capytale/resolver.js +80 -0
  373. package/backend/capytale/resolver.js.map +1 -0
  374. package/backend/capytale/rest.d.ts +4 -0
  375. package/backend/capytale/rest.d.ts.map +1 -0
  376. package/backend/capytale/rest.js +6 -0
  377. package/backend/capytale/rest.js.map +1 -0
  378. package/backend/capytale/sesame.d.ts +3 -0
  379. package/backend/capytale/sesame.d.ts.map +1 -0
  380. package/backend/capytale/sesame.js +5 -0
  381. package/backend/capytale/sesame.js.map +1 -0
  382. package/backend/capytale/tracker.d.ts +3 -0
  383. package/backend/capytale/tracker.d.ts.map +1 -0
  384. package/backend/capytale/tracker.js +10 -0
  385. package/backend/capytale/tracker.js.map +1 -0
  386. package/backend/capytale/user.d.ts +5 -0
  387. package/backend/capytale/user.d.ts.map +1 -0
  388. package/backend/capytale/user.js +10 -0
  389. package/backend/capytale/user.js.map +1 -0
  390. package/bin/cactjs.js +3577 -0
  391. package/common/action.d.ts +3 -0
  392. package/common/action.d.ts.map +1 -0
  393. package/common/action.js +2 -0
  394. package/common/action.js.map +1 -0
  395. package/common/field.d.ts +31 -0
  396. package/common/field.d.ts.map +1 -0
  397. package/common/field.js +2 -0
  398. package/common/field.js.map +1 -0
  399. package/entity/entity.d.ts +57 -0
  400. package/entity/entity.d.ts.map +1 -0
  401. package/entity/entity.js +188 -0
  402. package/entity/entity.js.map +1 -0
  403. package/entity/error.d.ts +4 -0
  404. package/entity/error.d.ts.map +1 -0
  405. package/entity/error.js +7 -0
  406. package/entity/error.js.map +1 -0
  407. package/entity/fieldDefinition.d.ts +135 -0
  408. package/entity/fieldDefinition.d.ts.map +1 -0
  409. package/entity/fieldDefinition.js +58 -0
  410. package/entity/fieldDefinition.js.map +1 -0
  411. package/entity/fieldImplementation.d.ts +41 -0
  412. package/entity/fieldImplementation.d.ts.map +1 -0
  413. package/entity/fieldImplementation.js +405 -0
  414. package/entity/fieldImplementation.js.map +1 -0
  415. package/entity/fieldType.d.ts +44 -0
  416. package/entity/fieldType.d.ts.map +1 -0
  417. package/entity/fieldType.js +2 -0
  418. package/entity/fieldType.js.map +1 -0
  419. package/entity/node.d.ts +31 -0
  420. package/entity/node.d.ts.map +1 -0
  421. package/entity/node.js +73 -0
  422. package/entity/node.js.map +1 -0
  423. package/entity/restFsBackend.d.ts +7 -0
  424. package/entity/restFsBackend.d.ts.map +1 -0
  425. package/entity/restFsBackend.js +2 -0
  426. package/entity/restFsBackend.js.map +1 -0
  427. package/entity/user.d.ts +20 -0
  428. package/entity/user.d.ts.map +1 -0
  429. package/entity/user.js +23 -0
  430. package/entity/user.js.map +1 -0
  431. package/entity/utility.d.ts +5 -0
  432. package/entity/utility.d.ts.map +1 -0
  433. package/entity/utility.js +5 -0
  434. package/entity/utility.js.map +1 -0
  435. package/index.d.ts +4 -0
  436. package/index.d.ts.map +1 -0
  437. package/index.js +13 -0
  438. package/index.js.map +1 -0
  439. package/package.json +29 -0
  440. package/tracker/index.d.ts +9 -0
  441. package/tracker/index.d.ts.map +1 -0
  442. package/tracker/index.js +129 -0
  443. package/tracker/index.js.map +1 -0
  444. package/util/isoDate.d.ts +2 -0
  445. package/util/isoDate.d.ts.map +1 -0
  446. package/util/isoDate.js +15 -0
  447. package/util/isoDate.js.map +1 -0
  448. package/util/iterator.d.ts +11 -0
  449. package/util/iterator.d.ts.map +1 -0
  450. package/util/iterator.js +44 -0
  451. package/util/iterator.js.map +1 -0
  452. package/util/scriptLoader.d.ts +3 -0
  453. package/util/scriptLoader.d.ts.map +1 -0
  454. package/util/scriptLoader.js +10 -0
  455. package/util/scriptLoader.js.map +1 -0
package/bin/cactjs.js ADDED
@@ -0,0 +1,3577 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ var require$$0 = require('events');
5
+ var require$$1 = require('child_process');
6
+ var require$$2 = require('path');
7
+ var fs$1 = require('fs');
8
+ var require$$4 = require('process');
9
+ var crypto = require('crypto');
10
+
11
+ var commander = {};
12
+
13
+ var argument = {};
14
+
15
+ var error = {};
16
+
17
+ /**
18
+ * CommanderError class
19
+ * @class
20
+ */
21
+
22
+ let CommanderError$3 = class CommanderError extends Error {
23
+ /**
24
+ * Constructs the CommanderError class
25
+ * @param {number} exitCode suggested exit code which could be used with process.exit
26
+ * @param {string} code an id string representing the error
27
+ * @param {string} message human-readable description of the error
28
+ * @constructor
29
+ */
30
+ constructor(exitCode, code, message) {
31
+ super(message);
32
+ // properly capture stack trace in Node.js
33
+ Error.captureStackTrace(this, this.constructor);
34
+ this.name = this.constructor.name;
35
+ this.code = code;
36
+ this.exitCode = exitCode;
37
+ this.nestedError = undefined;
38
+ }
39
+ };
40
+
41
+ /**
42
+ * InvalidArgumentError class
43
+ * @class
44
+ */
45
+ let InvalidArgumentError$4 = class InvalidArgumentError extends CommanderError$3 {
46
+ /**
47
+ * Constructs the InvalidArgumentError class
48
+ * @param {string} [message] explanation of why argument is invalid
49
+ * @constructor
50
+ */
51
+ constructor(message) {
52
+ super(1, 'commander.invalidArgument', message);
53
+ // properly capture stack trace in Node.js
54
+ Error.captureStackTrace(this, this.constructor);
55
+ this.name = this.constructor.name;
56
+ }
57
+ };
58
+
59
+ error.CommanderError = CommanderError$3;
60
+ error.InvalidArgumentError = InvalidArgumentError$4;
61
+
62
+ const { InvalidArgumentError: InvalidArgumentError$3 } = error;
63
+
64
+ let Argument$3 = class Argument {
65
+ /**
66
+ * Initialize a new command argument with the given name and description.
67
+ * The default is that the argument is required, and you can explicitly
68
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
69
+ *
70
+ * @param {string} name
71
+ * @param {string} [description]
72
+ */
73
+
74
+ constructor(name, description) {
75
+ this.description = description || '';
76
+ this.variadic = false;
77
+ this.parseArg = undefined;
78
+ this.defaultValue = undefined;
79
+ this.defaultValueDescription = undefined;
80
+ this.argChoices = undefined;
81
+
82
+ switch (name[0]) {
83
+ case '<': // e.g. <required>
84
+ this.required = true;
85
+ this._name = name.slice(1, -1);
86
+ break;
87
+ case '[': // e.g. [optional]
88
+ this.required = false;
89
+ this._name = name.slice(1, -1);
90
+ break;
91
+ default:
92
+ this.required = true;
93
+ this._name = name;
94
+ break;
95
+ }
96
+
97
+ if (this._name.length > 3 && this._name.slice(-3) === '...') {
98
+ this.variadic = true;
99
+ this._name = this._name.slice(0, -3);
100
+ }
101
+ }
102
+
103
+ /**
104
+ * Return argument name.
105
+ *
106
+ * @return {string}
107
+ */
108
+
109
+ name() {
110
+ return this._name;
111
+ }
112
+
113
+ /**
114
+ * @package internal use only
115
+ */
116
+
117
+ _concatValue(value, previous) {
118
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
119
+ return [value];
120
+ }
121
+
122
+ return previous.concat(value);
123
+ }
124
+
125
+ /**
126
+ * Set the default value, and optionally supply the description to be displayed in the help.
127
+ *
128
+ * @param {*} value
129
+ * @param {string} [description]
130
+ * @return {Argument}
131
+ */
132
+
133
+ default(value, description) {
134
+ this.defaultValue = value;
135
+ this.defaultValueDescription = description;
136
+ return this;
137
+ }
138
+
139
+ /**
140
+ * Set the custom handler for processing CLI command arguments into argument values.
141
+ *
142
+ * @param {Function} [fn]
143
+ * @return {Argument}
144
+ */
145
+
146
+ argParser(fn) {
147
+ this.parseArg = fn;
148
+ return this;
149
+ }
150
+
151
+ /**
152
+ * Only allow argument value to be one of choices.
153
+ *
154
+ * @param {string[]} values
155
+ * @return {Argument}
156
+ */
157
+
158
+ choices(values) {
159
+ this.argChoices = values.slice();
160
+ this.parseArg = (arg, previous) => {
161
+ if (!this.argChoices.includes(arg)) {
162
+ throw new InvalidArgumentError$3(`Allowed choices are ${this.argChoices.join(', ')}.`);
163
+ }
164
+ if (this.variadic) {
165
+ return this._concatValue(arg, previous);
166
+ }
167
+ return arg;
168
+ };
169
+ return this;
170
+ }
171
+
172
+ /**
173
+ * Make argument required.
174
+ */
175
+ argRequired() {
176
+ this.required = true;
177
+ return this;
178
+ }
179
+
180
+ /**
181
+ * Make argument optional.
182
+ */
183
+ argOptional() {
184
+ this.required = false;
185
+ return this;
186
+ }
187
+ };
188
+
189
+ /**
190
+ * Takes an argument and returns its human readable equivalent for help usage.
191
+ *
192
+ * @param {Argument} arg
193
+ * @return {string}
194
+ * @private
195
+ */
196
+
197
+ function humanReadableArgName$2(arg) {
198
+ const nameOutput = arg.name() + (arg.variadic === true ? '...' : '');
199
+
200
+ return arg.required
201
+ ? '<' + nameOutput + '>'
202
+ : '[' + nameOutput + ']';
203
+ }
204
+
205
+ argument.Argument = Argument$3;
206
+ argument.humanReadableArgName = humanReadableArgName$2;
207
+
208
+ var command = {};
209
+
210
+ var help = {};
211
+
212
+ const { humanReadableArgName: humanReadableArgName$1 } = argument;
213
+
214
+ /**
215
+ * TypeScript import types for JSDoc, used by Visual Studio Code IntelliSense and `npm run typescript-checkJS`
216
+ * https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html#import-types
217
+ * @typedef { import("./argument.js").Argument } Argument
218
+ * @typedef { import("./command.js").Command } Command
219
+ * @typedef { import("./option.js").Option } Option
220
+ */
221
+
222
+ // Although this is a class, methods are static in style to allow override using subclass or just functions.
223
+ let Help$3 = class Help {
224
+ constructor() {
225
+ this.helpWidth = undefined;
226
+ this.sortSubcommands = false;
227
+ this.sortOptions = false;
228
+ this.showGlobalOptions = false;
229
+ }
230
+
231
+ /**
232
+ * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
233
+ *
234
+ * @param {Command} cmd
235
+ * @returns {Command[]}
236
+ */
237
+
238
+ visibleCommands(cmd) {
239
+ const visibleCommands = cmd.commands.filter(cmd => !cmd._hidden);
240
+ const helpCommand = cmd._getHelpCommand();
241
+ if (helpCommand && !helpCommand._hidden) {
242
+ visibleCommands.push(helpCommand);
243
+ }
244
+ if (this.sortSubcommands) {
245
+ visibleCommands.sort((a, b) => {
246
+ // @ts-ignore: overloaded return type
247
+ return a.name().localeCompare(b.name());
248
+ });
249
+ }
250
+ return visibleCommands;
251
+ }
252
+
253
+ /**
254
+ * Compare options for sort.
255
+ *
256
+ * @param {Option} a
257
+ * @param {Option} b
258
+ * @returns number
259
+ */
260
+ compareOptions(a, b) {
261
+ const getSortKey = (option) => {
262
+ // WYSIWYG for order displayed in help. Short used for comparison if present. No special handling for negated.
263
+ return option.short ? option.short.replace(/^-/, '') : option.long.replace(/^--/, '');
264
+ };
265
+ return getSortKey(a).localeCompare(getSortKey(b));
266
+ }
267
+
268
+ /**
269
+ * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
270
+ *
271
+ * @param {Command} cmd
272
+ * @returns {Option[]}
273
+ */
274
+
275
+ visibleOptions(cmd) {
276
+ const visibleOptions = cmd.options.filter((option) => !option.hidden);
277
+ // Built-in help option.
278
+ const helpOption = cmd._getHelpOption();
279
+ if (helpOption && !helpOption.hidden) {
280
+ // Automatically hide conflicting flags. Bit dubious but a historical behaviour that is convenient for single-command programs.
281
+ const removeShort = helpOption.short && cmd._findOption(helpOption.short);
282
+ const removeLong = helpOption.long && cmd._findOption(helpOption.long);
283
+ if (!removeShort && !removeLong) {
284
+ visibleOptions.push(helpOption); // no changes needed
285
+ } else if (helpOption.long && !removeLong) {
286
+ visibleOptions.push(cmd.createOption(helpOption.long, helpOption.description));
287
+ } else if (helpOption.short && !removeShort) {
288
+ visibleOptions.push(cmd.createOption(helpOption.short, helpOption.description));
289
+ }
290
+ }
291
+ if (this.sortOptions) {
292
+ visibleOptions.sort(this.compareOptions);
293
+ }
294
+ return visibleOptions;
295
+ }
296
+
297
+ /**
298
+ * Get an array of the visible global options. (Not including help.)
299
+ *
300
+ * @param {Command} cmd
301
+ * @returns {Option[]}
302
+ */
303
+
304
+ visibleGlobalOptions(cmd) {
305
+ if (!this.showGlobalOptions) return [];
306
+
307
+ const globalOptions = [];
308
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
309
+ const visibleOptions = ancestorCmd.options.filter((option) => !option.hidden);
310
+ globalOptions.push(...visibleOptions);
311
+ }
312
+ if (this.sortOptions) {
313
+ globalOptions.sort(this.compareOptions);
314
+ }
315
+ return globalOptions;
316
+ }
317
+
318
+ /**
319
+ * Get an array of the arguments if any have a description.
320
+ *
321
+ * @param {Command} cmd
322
+ * @returns {Argument[]}
323
+ */
324
+
325
+ visibleArguments(cmd) {
326
+ // Side effect! Apply the legacy descriptions before the arguments are displayed.
327
+ if (cmd._argsDescription) {
328
+ cmd.registeredArguments.forEach(argument => {
329
+ argument.description = argument.description || cmd._argsDescription[argument.name()] || '';
330
+ });
331
+ }
332
+
333
+ // If there are any arguments with a description then return all the arguments.
334
+ if (cmd.registeredArguments.find(argument => argument.description)) {
335
+ return cmd.registeredArguments;
336
+ }
337
+ return [];
338
+ }
339
+
340
+ /**
341
+ * Get the command term to show in the list of subcommands.
342
+ *
343
+ * @param {Command} cmd
344
+ * @returns {string}
345
+ */
346
+
347
+ subcommandTerm(cmd) {
348
+ // Legacy. Ignores custom usage string, and nested commands.
349
+ const args = cmd.registeredArguments.map(arg => humanReadableArgName$1(arg)).join(' ');
350
+ return cmd._name +
351
+ (cmd._aliases[0] ? '|' + cmd._aliases[0] : '') +
352
+ (cmd.options.length ? ' [options]' : '') + // simplistic check for non-help option
353
+ (args ? ' ' + args : '');
354
+ }
355
+
356
+ /**
357
+ * Get the option term to show in the list of options.
358
+ *
359
+ * @param {Option} option
360
+ * @returns {string}
361
+ */
362
+
363
+ optionTerm(option) {
364
+ return option.flags;
365
+ }
366
+
367
+ /**
368
+ * Get the argument term to show in the list of arguments.
369
+ *
370
+ * @param {Argument} argument
371
+ * @returns {string}
372
+ */
373
+
374
+ argumentTerm(argument) {
375
+ return argument.name();
376
+ }
377
+
378
+ /**
379
+ * Get the longest command term length.
380
+ *
381
+ * @param {Command} cmd
382
+ * @param {Help} helper
383
+ * @returns {number}
384
+ */
385
+
386
+ longestSubcommandTermLength(cmd, helper) {
387
+ return helper.visibleCommands(cmd).reduce((max, command) => {
388
+ return Math.max(max, helper.subcommandTerm(command).length);
389
+ }, 0);
390
+ }
391
+
392
+ /**
393
+ * Get the longest option term length.
394
+ *
395
+ * @param {Command} cmd
396
+ * @param {Help} helper
397
+ * @returns {number}
398
+ */
399
+
400
+ longestOptionTermLength(cmd, helper) {
401
+ return helper.visibleOptions(cmd).reduce((max, option) => {
402
+ return Math.max(max, helper.optionTerm(option).length);
403
+ }, 0);
404
+ }
405
+
406
+ /**
407
+ * Get the longest global option term length.
408
+ *
409
+ * @param {Command} cmd
410
+ * @param {Help} helper
411
+ * @returns {number}
412
+ */
413
+
414
+ longestGlobalOptionTermLength(cmd, helper) {
415
+ return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
416
+ return Math.max(max, helper.optionTerm(option).length);
417
+ }, 0);
418
+ }
419
+
420
+ /**
421
+ * Get the longest argument term length.
422
+ *
423
+ * @param {Command} cmd
424
+ * @param {Help} helper
425
+ * @returns {number}
426
+ */
427
+
428
+ longestArgumentTermLength(cmd, helper) {
429
+ return helper.visibleArguments(cmd).reduce((max, argument) => {
430
+ return Math.max(max, helper.argumentTerm(argument).length);
431
+ }, 0);
432
+ }
433
+
434
+ /**
435
+ * Get the command usage to be displayed at the top of the built-in help.
436
+ *
437
+ * @param {Command} cmd
438
+ * @returns {string}
439
+ */
440
+
441
+ commandUsage(cmd) {
442
+ // Usage
443
+ let cmdName = cmd._name;
444
+ if (cmd._aliases[0]) {
445
+ cmdName = cmdName + '|' + cmd._aliases[0];
446
+ }
447
+ let ancestorCmdNames = '';
448
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
449
+ ancestorCmdNames = ancestorCmd.name() + ' ' + ancestorCmdNames;
450
+ }
451
+ return ancestorCmdNames + cmdName + ' ' + cmd.usage();
452
+ }
453
+
454
+ /**
455
+ * Get the description for the command.
456
+ *
457
+ * @param {Command} cmd
458
+ * @returns {string}
459
+ */
460
+
461
+ commandDescription(cmd) {
462
+ // @ts-ignore: overloaded return type
463
+ return cmd.description();
464
+ }
465
+
466
+ /**
467
+ * Get the subcommand summary to show in the list of subcommands.
468
+ * (Fallback to description for backwards compatibility.)
469
+ *
470
+ * @param {Command} cmd
471
+ * @returns {string}
472
+ */
473
+
474
+ subcommandDescription(cmd) {
475
+ // @ts-ignore: overloaded return type
476
+ return cmd.summary() || cmd.description();
477
+ }
478
+
479
+ /**
480
+ * Get the option description to show in the list of options.
481
+ *
482
+ * @param {Option} option
483
+ * @return {string}
484
+ */
485
+
486
+ optionDescription(option) {
487
+ const extraInfo = [];
488
+
489
+ if (option.argChoices) {
490
+ extraInfo.push(
491
+ // use stringify to match the display of the default value
492
+ `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`);
493
+ }
494
+ if (option.defaultValue !== undefined) {
495
+ // default for boolean and negated more for programmer than end user,
496
+ // but show true/false for boolean option as may be for hand-rolled env or config processing.
497
+ const showDefault = option.required || option.optional ||
498
+ (option.isBoolean() && typeof option.defaultValue === 'boolean');
499
+ if (showDefault) {
500
+ extraInfo.push(`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`);
501
+ }
502
+ }
503
+ // preset for boolean and negated are more for programmer than end user
504
+ if (option.presetArg !== undefined && option.optional) {
505
+ extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
506
+ }
507
+ if (option.envVar !== undefined) {
508
+ extraInfo.push(`env: ${option.envVar}`);
509
+ }
510
+ if (extraInfo.length > 0) {
511
+ return `${option.description} (${extraInfo.join(', ')})`;
512
+ }
513
+
514
+ return option.description;
515
+ }
516
+
517
+ /**
518
+ * Get the argument description to show in the list of arguments.
519
+ *
520
+ * @param {Argument} argument
521
+ * @return {string}
522
+ */
523
+
524
+ argumentDescription(argument) {
525
+ const extraInfo = [];
526
+ if (argument.argChoices) {
527
+ extraInfo.push(
528
+ // use stringify to match the display of the default value
529
+ `choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`);
530
+ }
531
+ if (argument.defaultValue !== undefined) {
532
+ extraInfo.push(`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`);
533
+ }
534
+ if (extraInfo.length > 0) {
535
+ const extraDescripton = `(${extraInfo.join(', ')})`;
536
+ if (argument.description) {
537
+ return `${argument.description} ${extraDescripton}`;
538
+ }
539
+ return extraDescripton;
540
+ }
541
+ return argument.description;
542
+ }
543
+
544
+ /**
545
+ * Generate the built-in help text.
546
+ *
547
+ * @param {Command} cmd
548
+ * @param {Help} helper
549
+ * @returns {string}
550
+ */
551
+
552
+ formatHelp(cmd, helper) {
553
+ const termWidth = helper.padWidth(cmd, helper);
554
+ const helpWidth = helper.helpWidth || 80;
555
+ const itemIndentWidth = 2;
556
+ const itemSeparatorWidth = 2; // between term and description
557
+ function formatItem(term, description) {
558
+ if (description) {
559
+ const fullText = `${term.padEnd(termWidth + itemSeparatorWidth)}${description}`;
560
+ return helper.wrap(fullText, helpWidth - itemIndentWidth, termWidth + itemSeparatorWidth);
561
+ }
562
+ return term;
563
+ }
564
+ function formatList(textArray) {
565
+ return textArray.join('\n').replace(/^/gm, ' '.repeat(itemIndentWidth));
566
+ }
567
+
568
+ // Usage
569
+ let output = [`Usage: ${helper.commandUsage(cmd)}`, ''];
570
+
571
+ // Description
572
+ const commandDescription = helper.commandDescription(cmd);
573
+ if (commandDescription.length > 0) {
574
+ output = output.concat([helper.wrap(commandDescription, helpWidth, 0), '']);
575
+ }
576
+
577
+ // Arguments
578
+ const argumentList = helper.visibleArguments(cmd).map((argument) => {
579
+ return formatItem(helper.argumentTerm(argument), helper.argumentDescription(argument));
580
+ });
581
+ if (argumentList.length > 0) {
582
+ output = output.concat(['Arguments:', formatList(argumentList), '']);
583
+ }
584
+
585
+ // Options
586
+ const optionList = helper.visibleOptions(cmd).map((option) => {
587
+ return formatItem(helper.optionTerm(option), helper.optionDescription(option));
588
+ });
589
+ if (optionList.length > 0) {
590
+ output = output.concat(['Options:', formatList(optionList), '']);
591
+ }
592
+
593
+ if (this.showGlobalOptions) {
594
+ const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
595
+ return formatItem(helper.optionTerm(option), helper.optionDescription(option));
596
+ });
597
+ if (globalOptionList.length > 0) {
598
+ output = output.concat(['Global Options:', formatList(globalOptionList), '']);
599
+ }
600
+ }
601
+
602
+ // Commands
603
+ const commandList = helper.visibleCommands(cmd).map((cmd) => {
604
+ return formatItem(helper.subcommandTerm(cmd), helper.subcommandDescription(cmd));
605
+ });
606
+ if (commandList.length > 0) {
607
+ output = output.concat(['Commands:', formatList(commandList), '']);
608
+ }
609
+
610
+ return output.join('\n');
611
+ }
612
+
613
+ /**
614
+ * Calculate the pad width from the maximum term length.
615
+ *
616
+ * @param {Command} cmd
617
+ * @param {Help} helper
618
+ * @returns {number}
619
+ */
620
+
621
+ padWidth(cmd, helper) {
622
+ return Math.max(
623
+ helper.longestOptionTermLength(cmd, helper),
624
+ helper.longestGlobalOptionTermLength(cmd, helper),
625
+ helper.longestSubcommandTermLength(cmd, helper),
626
+ helper.longestArgumentTermLength(cmd, helper)
627
+ );
628
+ }
629
+
630
+ /**
631
+ * Wrap the given string to width characters per line, with lines after the first indented.
632
+ * Do not wrap if insufficient room for wrapping (minColumnWidth), or string is manually formatted.
633
+ *
634
+ * @param {string} str
635
+ * @param {number} width
636
+ * @param {number} indent
637
+ * @param {number} [minColumnWidth=40]
638
+ * @return {string}
639
+ *
640
+ */
641
+
642
+ wrap(str, width, indent, minColumnWidth = 40) {
643
+ // Full \s characters, minus the linefeeds.
644
+ const indents = ' \\f\\t\\v\u00a0\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff';
645
+ // Detect manually wrapped and indented strings by searching for line break followed by spaces.
646
+ const manualIndent = new RegExp(`[\\n][${indents}]+`);
647
+ if (str.match(manualIndent)) return str;
648
+ // Do not wrap if not enough room for a wrapped column of text (as could end up with a word per line).
649
+ const columnWidth = width - indent;
650
+ if (columnWidth < minColumnWidth) return str;
651
+
652
+ const leadingStr = str.slice(0, indent);
653
+ const columnText = str.slice(indent).replace('\r\n', '\n');
654
+ const indentString = ' '.repeat(indent);
655
+ const zeroWidthSpace = '\u200B';
656
+ const breaks = `\\s${zeroWidthSpace}`;
657
+ // Match line end (so empty lines don't collapse),
658
+ // or as much text as will fit in column, or excess text up to first break.
659
+ const regex = new RegExp(`\n|.{1,${columnWidth - 1}}([${breaks}]|$)|[^${breaks}]+?([${breaks}]|$)`, 'g');
660
+ const lines = columnText.match(regex) || [];
661
+ return leadingStr + lines.map((line, i) => {
662
+ if (line === '\n') return ''; // preserve empty lines
663
+ return ((i > 0) ? indentString : '') + line.trimEnd();
664
+ }).join('\n');
665
+ }
666
+ };
667
+
668
+ help.Help = Help$3;
669
+
670
+ var option = {};
671
+
672
+ const { InvalidArgumentError: InvalidArgumentError$2 } = error;
673
+
674
+ let Option$3 = class Option {
675
+ /**
676
+ * Initialize a new `Option` with the given `flags` and `description`.
677
+ *
678
+ * @param {string} flags
679
+ * @param {string} [description]
680
+ */
681
+
682
+ constructor(flags, description) {
683
+ this.flags = flags;
684
+ this.description = description || '';
685
+
686
+ this.required = flags.includes('<'); // A value must be supplied when the option is specified.
687
+ this.optional = flags.includes('['); // A value is optional when the option is specified.
688
+ // variadic test ignores <value,...> et al which might be used to describe custom splitting of single argument
689
+ this.variadic = /\w\.\.\.[>\]]$/.test(flags); // The option can take multiple values.
690
+ this.mandatory = false; // The option must have a value after parsing, which usually means it must be specified on command line.
691
+ const optionFlags = splitOptionFlags(flags);
692
+ this.short = optionFlags.shortFlag;
693
+ this.long = optionFlags.longFlag;
694
+ this.negate = false;
695
+ if (this.long) {
696
+ this.negate = this.long.startsWith('--no-');
697
+ }
698
+ this.defaultValue = undefined;
699
+ this.defaultValueDescription = undefined;
700
+ this.presetArg = undefined;
701
+ this.envVar = undefined;
702
+ this.parseArg = undefined;
703
+ this.hidden = false;
704
+ this.argChoices = undefined;
705
+ this.conflictsWith = [];
706
+ this.implied = undefined;
707
+ }
708
+
709
+ /**
710
+ * Set the default value, and optionally supply the description to be displayed in the help.
711
+ *
712
+ * @param {*} value
713
+ * @param {string} [description]
714
+ * @return {Option}
715
+ */
716
+
717
+ default(value, description) {
718
+ this.defaultValue = value;
719
+ this.defaultValueDescription = description;
720
+ return this;
721
+ }
722
+
723
+ /**
724
+ * Preset to use when option used without option-argument, especially optional but also boolean and negated.
725
+ * The custom processing (parseArg) is called.
726
+ *
727
+ * @example
728
+ * new Option('--color').default('GREYSCALE').preset('RGB');
729
+ * new Option('--donate [amount]').preset('20').argParser(parseFloat);
730
+ *
731
+ * @param {*} arg
732
+ * @return {Option}
733
+ */
734
+
735
+ preset(arg) {
736
+ this.presetArg = arg;
737
+ return this;
738
+ }
739
+
740
+ /**
741
+ * Add option name(s) that conflict with this option.
742
+ * An error will be displayed if conflicting options are found during parsing.
743
+ *
744
+ * @example
745
+ * new Option('--rgb').conflicts('cmyk');
746
+ * new Option('--js').conflicts(['ts', 'jsx']);
747
+ *
748
+ * @param {(string | string[])} names
749
+ * @return {Option}
750
+ */
751
+
752
+ conflicts(names) {
753
+ this.conflictsWith = this.conflictsWith.concat(names);
754
+ return this;
755
+ }
756
+
757
+ /**
758
+ * Specify implied option values for when this option is set and the implied options are not.
759
+ *
760
+ * The custom processing (parseArg) is not called on the implied values.
761
+ *
762
+ * @example
763
+ * program
764
+ * .addOption(new Option('--log', 'write logging information to file'))
765
+ * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
766
+ *
767
+ * @param {Object} impliedOptionValues
768
+ * @return {Option}
769
+ */
770
+ implies(impliedOptionValues) {
771
+ let newImplied = impliedOptionValues;
772
+ if (typeof impliedOptionValues === 'string') {
773
+ // string is not documented, but easy mistake and we can do what user probably intended.
774
+ newImplied = { [impliedOptionValues]: true };
775
+ }
776
+ this.implied = Object.assign(this.implied || {}, newImplied);
777
+ return this;
778
+ }
779
+
780
+ /**
781
+ * Set environment variable to check for option value.
782
+ *
783
+ * An environment variable is only used if when processed the current option value is
784
+ * undefined, or the source of the current value is 'default' or 'config' or 'env'.
785
+ *
786
+ * @param {string} name
787
+ * @return {Option}
788
+ */
789
+
790
+ env(name) {
791
+ this.envVar = name;
792
+ return this;
793
+ }
794
+
795
+ /**
796
+ * Set the custom handler for processing CLI option arguments into option values.
797
+ *
798
+ * @param {Function} [fn]
799
+ * @return {Option}
800
+ */
801
+
802
+ argParser(fn) {
803
+ this.parseArg = fn;
804
+ return this;
805
+ }
806
+
807
+ /**
808
+ * Whether the option is mandatory and must have a value after parsing.
809
+ *
810
+ * @param {boolean} [mandatory=true]
811
+ * @return {Option}
812
+ */
813
+
814
+ makeOptionMandatory(mandatory = true) {
815
+ this.mandatory = !!mandatory;
816
+ return this;
817
+ }
818
+
819
+ /**
820
+ * Hide option in help.
821
+ *
822
+ * @param {boolean} [hide=true]
823
+ * @return {Option}
824
+ */
825
+
826
+ hideHelp(hide = true) {
827
+ this.hidden = !!hide;
828
+ return this;
829
+ }
830
+
831
+ /**
832
+ * @package internal use only
833
+ */
834
+
835
+ _concatValue(value, previous) {
836
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
837
+ return [value];
838
+ }
839
+
840
+ return previous.concat(value);
841
+ }
842
+
843
+ /**
844
+ * Only allow option value to be one of choices.
845
+ *
846
+ * @param {string[]} values
847
+ * @return {Option}
848
+ */
849
+
850
+ choices(values) {
851
+ this.argChoices = values.slice();
852
+ this.parseArg = (arg, previous) => {
853
+ if (!this.argChoices.includes(arg)) {
854
+ throw new InvalidArgumentError$2(`Allowed choices are ${this.argChoices.join(', ')}.`);
855
+ }
856
+ if (this.variadic) {
857
+ return this._concatValue(arg, previous);
858
+ }
859
+ return arg;
860
+ };
861
+ return this;
862
+ }
863
+
864
+ /**
865
+ * Return option name.
866
+ *
867
+ * @return {string}
868
+ */
869
+
870
+ name() {
871
+ if (this.long) {
872
+ return this.long.replace(/^--/, '');
873
+ }
874
+ return this.short.replace(/^-/, '');
875
+ }
876
+
877
+ /**
878
+ * Return option name, in a camelcase format that can be used
879
+ * as a object attribute key.
880
+ *
881
+ * @return {string}
882
+ */
883
+
884
+ attributeName() {
885
+ return camelcase(this.name().replace(/^no-/, ''));
886
+ }
887
+
888
+ /**
889
+ * Check if `arg` matches the short or long flag.
890
+ *
891
+ * @param {string} arg
892
+ * @return {boolean}
893
+ * @package internal use only
894
+ */
895
+
896
+ is(arg) {
897
+ return this.short === arg || this.long === arg;
898
+ }
899
+
900
+ /**
901
+ * Return whether a boolean option.
902
+ *
903
+ * Options are one of boolean, negated, required argument, or optional argument.
904
+ *
905
+ * @return {boolean}
906
+ * @package internal use only
907
+ */
908
+
909
+ isBoolean() {
910
+ return !this.required && !this.optional && !this.negate;
911
+ }
912
+ };
913
+
914
+ /**
915
+ * This class is to make it easier to work with dual options, without changing the existing
916
+ * implementation. We support separate dual options for separate positive and negative options,
917
+ * like `--build` and `--no-build`, which share a single option value. This works nicely for some
918
+ * use cases, but is tricky for others where we want separate behaviours despite
919
+ * the single shared option value.
920
+ */
921
+ let DualOptions$1 = class DualOptions {
922
+ /**
923
+ * @param {Option[]} options
924
+ */
925
+ constructor(options) {
926
+ this.positiveOptions = new Map();
927
+ this.negativeOptions = new Map();
928
+ this.dualOptions = new Set();
929
+ options.forEach(option => {
930
+ if (option.negate) {
931
+ this.negativeOptions.set(option.attributeName(), option);
932
+ } else {
933
+ this.positiveOptions.set(option.attributeName(), option);
934
+ }
935
+ });
936
+ this.negativeOptions.forEach((value, key) => {
937
+ if (this.positiveOptions.has(key)) {
938
+ this.dualOptions.add(key);
939
+ }
940
+ });
941
+ }
942
+
943
+ /**
944
+ * Did the value come from the option, and not from possible matching dual option?
945
+ *
946
+ * @param {*} value
947
+ * @param {Option} option
948
+ * @returns {boolean}
949
+ */
950
+ valueFromOption(value, option) {
951
+ const optionKey = option.attributeName();
952
+ if (!this.dualOptions.has(optionKey)) return true;
953
+
954
+ // Use the value to deduce if (probably) came from the option.
955
+ const preset = this.negativeOptions.get(optionKey).presetArg;
956
+ const negativeValue = (preset !== undefined) ? preset : false;
957
+ return option.negate === (negativeValue === value);
958
+ }
959
+ };
960
+
961
+ /**
962
+ * Convert string from kebab-case to camelCase.
963
+ *
964
+ * @param {string} str
965
+ * @return {string}
966
+ * @private
967
+ */
968
+
969
+ function camelcase(str) {
970
+ return str.split('-').reduce((str, word) => {
971
+ return str + word[0].toUpperCase() + word.slice(1);
972
+ });
973
+ }
974
+
975
+ /**
976
+ * Split the short and long flag out of something like '-m,--mixed <value>'
977
+ *
978
+ * @private
979
+ */
980
+
981
+ function splitOptionFlags(flags) {
982
+ let shortFlag;
983
+ let longFlag;
984
+ // Use original very loose parsing to maintain backwards compatibility for now,
985
+ // which allowed for example unintended `-sw, --short-word` [sic].
986
+ const flagParts = flags.split(/[ |,]+/);
987
+ if (flagParts.length > 1 && !/^[[<]/.test(flagParts[1])) shortFlag = flagParts.shift();
988
+ longFlag = flagParts.shift();
989
+ // Add support for lone short flag without significantly changing parsing!
990
+ if (!shortFlag && /^-[^-]$/.test(longFlag)) {
991
+ shortFlag = longFlag;
992
+ longFlag = undefined;
993
+ }
994
+ return { shortFlag, longFlag };
995
+ }
996
+
997
+ option.Option = Option$3;
998
+ option.DualOptions = DualOptions$1;
999
+
1000
+ var suggestSimilar$2 = {};
1001
+
1002
+ const maxDistance = 3;
1003
+
1004
+ function editDistance(a, b) {
1005
+ // https://en.wikipedia.org/wiki/Damerau–Levenshtein_distance
1006
+ // Calculating optimal string alignment distance, no substring is edited more than once.
1007
+ // (Simple implementation.)
1008
+
1009
+ // Quick early exit, return worst case.
1010
+ if (Math.abs(a.length - b.length) > maxDistance) return Math.max(a.length, b.length);
1011
+
1012
+ // distance between prefix substrings of a and b
1013
+ const d = [];
1014
+
1015
+ // pure deletions turn a into empty string
1016
+ for (let i = 0; i <= a.length; i++) {
1017
+ d[i] = [i];
1018
+ }
1019
+ // pure insertions turn empty string into b
1020
+ for (let j = 0; j <= b.length; j++) {
1021
+ d[0][j] = j;
1022
+ }
1023
+
1024
+ // fill matrix
1025
+ for (let j = 1; j <= b.length; j++) {
1026
+ for (let i = 1; i <= a.length; i++) {
1027
+ let cost = 1;
1028
+ if (a[i - 1] === b[j - 1]) {
1029
+ cost = 0;
1030
+ } else {
1031
+ cost = 1;
1032
+ }
1033
+ d[i][j] = Math.min(
1034
+ d[i - 1][j] + 1, // deletion
1035
+ d[i][j - 1] + 1, // insertion
1036
+ d[i - 1][j - 1] + cost // substitution
1037
+ );
1038
+ // transposition
1039
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
1040
+ d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
1041
+ }
1042
+ }
1043
+ }
1044
+
1045
+ return d[a.length][b.length];
1046
+ }
1047
+
1048
+ /**
1049
+ * Find close matches, restricted to same number of edits.
1050
+ *
1051
+ * @param {string} word
1052
+ * @param {string[]} candidates
1053
+ * @returns {string}
1054
+ */
1055
+
1056
+ function suggestSimilar$1(word, candidates) {
1057
+ if (!candidates || candidates.length === 0) return '';
1058
+ // remove possible duplicates
1059
+ candidates = Array.from(new Set(candidates));
1060
+
1061
+ const searchingOptions = word.startsWith('--');
1062
+ if (searchingOptions) {
1063
+ word = word.slice(2);
1064
+ candidates = candidates.map(candidate => candidate.slice(2));
1065
+ }
1066
+
1067
+ let similar = [];
1068
+ let bestDistance = maxDistance;
1069
+ const minSimilarity = 0.4;
1070
+ candidates.forEach((candidate) => {
1071
+ if (candidate.length <= 1) return; // no one character guesses
1072
+
1073
+ const distance = editDistance(word, candidate);
1074
+ const length = Math.max(word.length, candidate.length);
1075
+ const similarity = (length - distance) / length;
1076
+ if (similarity > minSimilarity) {
1077
+ if (distance < bestDistance) {
1078
+ // better edit distance, throw away previous worse matches
1079
+ bestDistance = distance;
1080
+ similar = [candidate];
1081
+ } else if (distance === bestDistance) {
1082
+ similar.push(candidate);
1083
+ }
1084
+ }
1085
+ });
1086
+
1087
+ similar.sort((a, b) => a.localeCompare(b));
1088
+ if (searchingOptions) {
1089
+ similar = similar.map(candidate => `--${candidate}`);
1090
+ }
1091
+
1092
+ if (similar.length > 1) {
1093
+ return `\n(Did you mean one of ${similar.join(', ')}?)`;
1094
+ }
1095
+ if (similar.length === 1) {
1096
+ return `\n(Did you mean ${similar[0]}?)`;
1097
+ }
1098
+ return '';
1099
+ }
1100
+
1101
+ suggestSimilar$2.suggestSimilar = suggestSimilar$1;
1102
+
1103
+ const EventEmitter = require$$0.EventEmitter;
1104
+ const childProcess = require$$1;
1105
+ const path = require$$2;
1106
+ const fs = fs$1;
1107
+ const process$1 = require$$4;
1108
+
1109
+ const { Argument: Argument$2, humanReadableArgName } = argument;
1110
+ const { CommanderError: CommanderError$2 } = error;
1111
+ const { Help: Help$2 } = help;
1112
+ const { Option: Option$2, DualOptions } = option;
1113
+ const { suggestSimilar } = suggestSimilar$2;
1114
+
1115
+ let Command$2 = class Command extends EventEmitter {
1116
+ /**
1117
+ * Initialize a new `Command`.
1118
+ *
1119
+ * @param {string} [name]
1120
+ */
1121
+
1122
+ constructor(name) {
1123
+ super();
1124
+ /** @type {Command[]} */
1125
+ this.commands = [];
1126
+ /** @type {Option[]} */
1127
+ this.options = [];
1128
+ this.parent = null;
1129
+ this._allowUnknownOption = false;
1130
+ this._allowExcessArguments = true;
1131
+ /** @type {Argument[]} */
1132
+ this.registeredArguments = [];
1133
+ this._args = this.registeredArguments; // deprecated old name
1134
+ /** @type {string[]} */
1135
+ this.args = []; // cli args with options removed
1136
+ this.rawArgs = [];
1137
+ this.processedArgs = []; // like .args but after custom processing and collecting variadic
1138
+ this._scriptPath = null;
1139
+ this._name = name || '';
1140
+ this._optionValues = {};
1141
+ this._optionValueSources = {}; // default, env, cli etc
1142
+ this._storeOptionsAsProperties = false;
1143
+ this._actionHandler = null;
1144
+ this._executableHandler = false;
1145
+ this._executableFile = null; // custom name for executable
1146
+ this._executableDir = null; // custom search directory for subcommands
1147
+ this._defaultCommandName = null;
1148
+ this._exitCallback = null;
1149
+ this._aliases = [];
1150
+ this._combineFlagAndOptionalValue = true;
1151
+ this._description = '';
1152
+ this._summary = '';
1153
+ this._argsDescription = undefined; // legacy
1154
+ this._enablePositionalOptions = false;
1155
+ this._passThroughOptions = false;
1156
+ this._lifeCycleHooks = {}; // a hash of arrays
1157
+ /** @type {(boolean | string)} */
1158
+ this._showHelpAfterError = false;
1159
+ this._showSuggestionAfterError = true;
1160
+
1161
+ // see .configureOutput() for docs
1162
+ this._outputConfiguration = {
1163
+ writeOut: (str) => process$1.stdout.write(str),
1164
+ writeErr: (str) => process$1.stderr.write(str),
1165
+ getOutHelpWidth: () => process$1.stdout.isTTY ? process$1.stdout.columns : undefined,
1166
+ getErrHelpWidth: () => process$1.stderr.isTTY ? process$1.stderr.columns : undefined,
1167
+ outputError: (str, write) => write(str)
1168
+ };
1169
+
1170
+ this._hidden = false;
1171
+ /** @type {(Option | null | undefined)} */
1172
+ this._helpOption = undefined; // Lazy created on demand. May be null if help option is disabled.
1173
+ this._addImplicitHelpCommand = undefined; // undecided whether true or false yet, not inherited
1174
+ /** @type {Command} */
1175
+ this._helpCommand = undefined; // lazy initialised, inherited
1176
+ this._helpConfiguration = {};
1177
+ }
1178
+
1179
+ /**
1180
+ * Copy settings that are useful to have in common across root command and subcommands.
1181
+ *
1182
+ * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
1183
+ *
1184
+ * @param {Command} sourceCommand
1185
+ * @return {Command} `this` command for chaining
1186
+ */
1187
+ copyInheritedSettings(sourceCommand) {
1188
+ this._outputConfiguration = sourceCommand._outputConfiguration;
1189
+ this._helpOption = sourceCommand._helpOption;
1190
+ this._helpCommand = sourceCommand._helpCommand;
1191
+ this._helpConfiguration = sourceCommand._helpConfiguration;
1192
+ this._exitCallback = sourceCommand._exitCallback;
1193
+ this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
1194
+ this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
1195
+ this._allowExcessArguments = sourceCommand._allowExcessArguments;
1196
+ this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
1197
+ this._showHelpAfterError = sourceCommand._showHelpAfterError;
1198
+ this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
1199
+
1200
+ return this;
1201
+ }
1202
+
1203
+ /**
1204
+ * @returns {Command[]}
1205
+ * @private
1206
+ */
1207
+
1208
+ _getCommandAndAncestors() {
1209
+ const result = [];
1210
+ for (let command = this; command; command = command.parent) {
1211
+ result.push(command);
1212
+ }
1213
+ return result;
1214
+ }
1215
+
1216
+ /**
1217
+ * Define a command.
1218
+ *
1219
+ * There are two styles of command: pay attention to where to put the description.
1220
+ *
1221
+ * @example
1222
+ * // Command implemented using action handler (description is supplied separately to `.command`)
1223
+ * program
1224
+ * .command('clone <source> [destination]')
1225
+ * .description('clone a repository into a newly created directory')
1226
+ * .action((source, destination) => {
1227
+ * console.log('clone command called');
1228
+ * });
1229
+ *
1230
+ * // Command implemented using separate executable file (description is second parameter to `.command`)
1231
+ * program
1232
+ * .command('start <service>', 'start named service')
1233
+ * .command('stop [service]', 'stop named service, or all if no name supplied');
1234
+ *
1235
+ * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
1236
+ * @param {(Object|string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
1237
+ * @param {Object} [execOpts] - configuration options (for executable)
1238
+ * @return {Command} returns new command for action handler, or `this` for executable command
1239
+ */
1240
+
1241
+ command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
1242
+ let desc = actionOptsOrExecDesc;
1243
+ let opts = execOpts;
1244
+ if (typeof desc === 'object' && desc !== null) {
1245
+ opts = desc;
1246
+ desc = null;
1247
+ }
1248
+ opts = opts || {};
1249
+ const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
1250
+
1251
+ const cmd = this.createCommand(name);
1252
+ if (desc) {
1253
+ cmd.description(desc);
1254
+ cmd._executableHandler = true;
1255
+ }
1256
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
1257
+ cmd._hidden = !!(opts.noHelp || opts.hidden); // noHelp is deprecated old name for hidden
1258
+ cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor
1259
+ if (args) cmd.arguments(args);
1260
+ this._registerCommand(cmd);
1261
+ cmd.parent = this;
1262
+ cmd.copyInheritedSettings(this);
1263
+
1264
+ if (desc) return this;
1265
+ return cmd;
1266
+ }
1267
+
1268
+ /**
1269
+ * Factory routine to create a new unattached command.
1270
+ *
1271
+ * See .command() for creating an attached subcommand, which uses this routine to
1272
+ * create the command. You can override createCommand to customise subcommands.
1273
+ *
1274
+ * @param {string} [name]
1275
+ * @return {Command} new command
1276
+ */
1277
+
1278
+ createCommand(name) {
1279
+ return new Command(name);
1280
+ }
1281
+
1282
+ /**
1283
+ * You can customise the help with a subclass of Help by overriding createHelp,
1284
+ * or by overriding Help properties using configureHelp().
1285
+ *
1286
+ * @return {Help}
1287
+ */
1288
+
1289
+ createHelp() {
1290
+ return Object.assign(new Help$2(), this.configureHelp());
1291
+ }
1292
+
1293
+ /**
1294
+ * You can customise the help by overriding Help properties using configureHelp(),
1295
+ * or with a subclass of Help by overriding createHelp().
1296
+ *
1297
+ * @param {Object} [configuration] - configuration options
1298
+ * @return {(Command|Object)} `this` command for chaining, or stored configuration
1299
+ */
1300
+
1301
+ configureHelp(configuration) {
1302
+ if (configuration === undefined) return this._helpConfiguration;
1303
+
1304
+ this._helpConfiguration = configuration;
1305
+ return this;
1306
+ }
1307
+
1308
+ /**
1309
+ * The default output goes to stdout and stderr. You can customise this for special
1310
+ * applications. You can also customise the display of errors by overriding outputError.
1311
+ *
1312
+ * The configuration properties are all functions:
1313
+ *
1314
+ * // functions to change where being written, stdout and stderr
1315
+ * writeOut(str)
1316
+ * writeErr(str)
1317
+ * // matching functions to specify width for wrapping help
1318
+ * getOutHelpWidth()
1319
+ * getErrHelpWidth()
1320
+ * // functions based on what is being written out
1321
+ * outputError(str, write) // used for displaying errors, and not used for displaying help
1322
+ *
1323
+ * @param {Object} [configuration] - configuration options
1324
+ * @return {(Command|Object)} `this` command for chaining, or stored configuration
1325
+ */
1326
+
1327
+ configureOutput(configuration) {
1328
+ if (configuration === undefined) return this._outputConfiguration;
1329
+
1330
+ Object.assign(this._outputConfiguration, configuration);
1331
+ return this;
1332
+ }
1333
+
1334
+ /**
1335
+ * Display the help or a custom message after an error occurs.
1336
+ *
1337
+ * @param {(boolean|string)} [displayHelp]
1338
+ * @return {Command} `this` command for chaining
1339
+ */
1340
+ showHelpAfterError(displayHelp = true) {
1341
+ if (typeof displayHelp !== 'string') displayHelp = !!displayHelp;
1342
+ this._showHelpAfterError = displayHelp;
1343
+ return this;
1344
+ }
1345
+
1346
+ /**
1347
+ * Display suggestion of similar commands for unknown commands, or options for unknown options.
1348
+ *
1349
+ * @param {boolean} [displaySuggestion]
1350
+ * @return {Command} `this` command for chaining
1351
+ */
1352
+ showSuggestionAfterError(displaySuggestion = true) {
1353
+ this._showSuggestionAfterError = !!displaySuggestion;
1354
+ return this;
1355
+ }
1356
+
1357
+ /**
1358
+ * Add a prepared subcommand.
1359
+ *
1360
+ * See .command() for creating an attached subcommand which inherits settings from its parent.
1361
+ *
1362
+ * @param {Command} cmd - new subcommand
1363
+ * @param {Object} [opts] - configuration options
1364
+ * @return {Command} `this` command for chaining
1365
+ */
1366
+
1367
+ addCommand(cmd, opts) {
1368
+ if (!cmd._name) {
1369
+ throw new Error(`Command passed to .addCommand() must have a name
1370
+ - specify the name in Command constructor or using .name()`);
1371
+ }
1372
+
1373
+ opts = opts || {};
1374
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
1375
+ if (opts.noHelp || opts.hidden) cmd._hidden = true; // modifying passed command due to existing implementation
1376
+
1377
+ this._registerCommand(cmd);
1378
+ cmd.parent = this;
1379
+ cmd._checkForBrokenPassThrough();
1380
+
1381
+ return this;
1382
+ }
1383
+
1384
+ /**
1385
+ * Factory routine to create a new unattached argument.
1386
+ *
1387
+ * See .argument() for creating an attached argument, which uses this routine to
1388
+ * create the argument. You can override createArgument to return a custom argument.
1389
+ *
1390
+ * @param {string} name
1391
+ * @param {string} [description]
1392
+ * @return {Argument} new argument
1393
+ */
1394
+
1395
+ createArgument(name, description) {
1396
+ return new Argument$2(name, description);
1397
+ }
1398
+
1399
+ /**
1400
+ * Define argument syntax for command.
1401
+ *
1402
+ * The default is that the argument is required, and you can explicitly
1403
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
1404
+ *
1405
+ * @example
1406
+ * program.argument('<input-file>');
1407
+ * program.argument('[output-file]');
1408
+ *
1409
+ * @param {string} name
1410
+ * @param {string} [description]
1411
+ * @param {(Function|*)} [fn] - custom argument processing function
1412
+ * @param {*} [defaultValue]
1413
+ * @return {Command} `this` command for chaining
1414
+ */
1415
+ argument(name, description, fn, defaultValue) {
1416
+ const argument = this.createArgument(name, description);
1417
+ if (typeof fn === 'function') {
1418
+ argument.default(defaultValue).argParser(fn);
1419
+ } else {
1420
+ argument.default(fn);
1421
+ }
1422
+ this.addArgument(argument);
1423
+ return this;
1424
+ }
1425
+
1426
+ /**
1427
+ * Define argument syntax for command, adding multiple at once (without descriptions).
1428
+ *
1429
+ * See also .argument().
1430
+ *
1431
+ * @example
1432
+ * program.arguments('<cmd> [env]');
1433
+ *
1434
+ * @param {string} names
1435
+ * @return {Command} `this` command for chaining
1436
+ */
1437
+
1438
+ arguments(names) {
1439
+ names.trim().split(/ +/).forEach((detail) => {
1440
+ this.argument(detail);
1441
+ });
1442
+ return this;
1443
+ }
1444
+
1445
+ /**
1446
+ * Define argument syntax for command, adding a prepared argument.
1447
+ *
1448
+ * @param {Argument} argument
1449
+ * @return {Command} `this` command for chaining
1450
+ */
1451
+ addArgument(argument) {
1452
+ const previousArgument = this.registeredArguments.slice(-1)[0];
1453
+ if (previousArgument && previousArgument.variadic) {
1454
+ throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);
1455
+ }
1456
+ if (argument.required && argument.defaultValue !== undefined && argument.parseArg === undefined) {
1457
+ throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);
1458
+ }
1459
+ this.registeredArguments.push(argument);
1460
+ return this;
1461
+ }
1462
+
1463
+ /**
1464
+ * Customise or override default help command. By default a help command is automatically added if your command has subcommands.
1465
+ *
1466
+ * program.helpCommand('help [cmd]');
1467
+ * program.helpCommand('help [cmd]', 'show help');
1468
+ * program.helpCommand(false); // suppress default help command
1469
+ * program.helpCommand(true); // add help command even if no subcommands
1470
+ *
1471
+ * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added
1472
+ * @param {string} [description] - custom description
1473
+ * @return {Command} `this` command for chaining
1474
+ */
1475
+
1476
+ helpCommand(enableOrNameAndArgs, description) {
1477
+ if (typeof enableOrNameAndArgs === 'boolean') {
1478
+ this._addImplicitHelpCommand = enableOrNameAndArgs;
1479
+ return this;
1480
+ }
1481
+
1482
+ enableOrNameAndArgs = enableOrNameAndArgs ?? 'help [command]';
1483
+ const [, helpName, helpArgs] = enableOrNameAndArgs.match(/([^ ]+) *(.*)/);
1484
+ const helpDescription = description ?? 'display help for command';
1485
+
1486
+ const helpCommand = this.createCommand(helpName);
1487
+ helpCommand.helpOption(false);
1488
+ if (helpArgs) helpCommand.arguments(helpArgs);
1489
+ if (helpDescription) helpCommand.description(helpDescription);
1490
+
1491
+ this._addImplicitHelpCommand = true;
1492
+ this._helpCommand = helpCommand;
1493
+
1494
+ return this;
1495
+ }
1496
+
1497
+ /**
1498
+ * Add prepared custom help command.
1499
+ *
1500
+ * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`
1501
+ * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only
1502
+ * @return {Command} `this` command for chaining
1503
+ */
1504
+ addHelpCommand(helpCommand, deprecatedDescription) {
1505
+ // If not passed an object, call through to helpCommand for backwards compatibility,
1506
+ // as addHelpCommand was originally used like helpCommand is now.
1507
+ if (typeof helpCommand !== 'object') {
1508
+ this.helpCommand(helpCommand, deprecatedDescription);
1509
+ return this;
1510
+ }
1511
+
1512
+ this._addImplicitHelpCommand = true;
1513
+ this._helpCommand = helpCommand;
1514
+ return this;
1515
+ }
1516
+
1517
+ /**
1518
+ * Lazy create help command.
1519
+ *
1520
+ * @return {(Command|null)}
1521
+ * @package
1522
+ */
1523
+ _getHelpCommand() {
1524
+ const hasImplicitHelpCommand = this._addImplicitHelpCommand ??
1525
+ (this.commands.length && !this._actionHandler && !this._findCommand('help'));
1526
+
1527
+ if (hasImplicitHelpCommand) {
1528
+ if (this._helpCommand === undefined) {
1529
+ this.helpCommand(undefined, undefined); // use default name and description
1530
+ }
1531
+ return this._helpCommand;
1532
+ }
1533
+ return null;
1534
+ }
1535
+
1536
+ /**
1537
+ * Add hook for life cycle event.
1538
+ *
1539
+ * @param {string} event
1540
+ * @param {Function} listener
1541
+ * @return {Command} `this` command for chaining
1542
+ */
1543
+
1544
+ hook(event, listener) {
1545
+ const allowedValues = ['preSubcommand', 'preAction', 'postAction'];
1546
+ if (!allowedValues.includes(event)) {
1547
+ throw new Error(`Unexpected value for event passed to hook : '${event}'.
1548
+ Expecting one of '${allowedValues.join("', '")}'`);
1549
+ }
1550
+ if (this._lifeCycleHooks[event]) {
1551
+ this._lifeCycleHooks[event].push(listener);
1552
+ } else {
1553
+ this._lifeCycleHooks[event] = [listener];
1554
+ }
1555
+ return this;
1556
+ }
1557
+
1558
+ /**
1559
+ * Register callback to use as replacement for calling process.exit.
1560
+ *
1561
+ * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
1562
+ * @return {Command} `this` command for chaining
1563
+ */
1564
+
1565
+ exitOverride(fn) {
1566
+ if (fn) {
1567
+ this._exitCallback = fn;
1568
+ } else {
1569
+ this._exitCallback = (err) => {
1570
+ if (err.code !== 'commander.executeSubCommandAsync') {
1571
+ throw err;
1572
+ }
1573
+ };
1574
+ }
1575
+ return this;
1576
+ }
1577
+
1578
+ /**
1579
+ * Call process.exit, and _exitCallback if defined.
1580
+ *
1581
+ * @param {number} exitCode exit code for using with process.exit
1582
+ * @param {string} code an id string representing the error
1583
+ * @param {string} message human-readable description of the error
1584
+ * @return never
1585
+ * @private
1586
+ */
1587
+
1588
+ _exit(exitCode, code, message) {
1589
+ if (this._exitCallback) {
1590
+ this._exitCallback(new CommanderError$2(exitCode, code, message));
1591
+ // Expecting this line is not reached.
1592
+ }
1593
+ process$1.exit(exitCode);
1594
+ }
1595
+
1596
+ /**
1597
+ * Register callback `fn` for the command.
1598
+ *
1599
+ * @example
1600
+ * program
1601
+ * .command('serve')
1602
+ * .description('start service')
1603
+ * .action(function() {
1604
+ * // do work here
1605
+ * });
1606
+ *
1607
+ * @param {Function} fn
1608
+ * @return {Command} `this` command for chaining
1609
+ */
1610
+
1611
+ action(fn) {
1612
+ const listener = (args) => {
1613
+ // The .action callback takes an extra parameter which is the command or options.
1614
+ const expectedArgsCount = this.registeredArguments.length;
1615
+ const actionArgs = args.slice(0, expectedArgsCount);
1616
+ if (this._storeOptionsAsProperties) {
1617
+ actionArgs[expectedArgsCount] = this; // backwards compatible "options"
1618
+ } else {
1619
+ actionArgs[expectedArgsCount] = this.opts();
1620
+ }
1621
+ actionArgs.push(this);
1622
+
1623
+ return fn.apply(this, actionArgs);
1624
+ };
1625
+ this._actionHandler = listener;
1626
+ return this;
1627
+ }
1628
+
1629
+ /**
1630
+ * Factory routine to create a new unattached option.
1631
+ *
1632
+ * See .option() for creating an attached option, which uses this routine to
1633
+ * create the option. You can override createOption to return a custom option.
1634
+ *
1635
+ * @param {string} flags
1636
+ * @param {string} [description]
1637
+ * @return {Option} new option
1638
+ */
1639
+
1640
+ createOption(flags, description) {
1641
+ return new Option$2(flags, description);
1642
+ }
1643
+
1644
+ /**
1645
+ * Wrap parseArgs to catch 'commander.invalidArgument'.
1646
+ *
1647
+ * @param {(Option | Argument)} target
1648
+ * @param {string} value
1649
+ * @param {*} previous
1650
+ * @param {string} invalidArgumentMessage
1651
+ * @private
1652
+ */
1653
+
1654
+ _callParseArg(target, value, previous, invalidArgumentMessage) {
1655
+ try {
1656
+ return target.parseArg(value, previous);
1657
+ } catch (err) {
1658
+ if (err.code === 'commander.invalidArgument') {
1659
+ const message = `${invalidArgumentMessage} ${err.message}`;
1660
+ this.error(message, { exitCode: err.exitCode, code: err.code });
1661
+ }
1662
+ throw err;
1663
+ }
1664
+ }
1665
+
1666
+ /**
1667
+ * Check for option flag conflicts.
1668
+ * Register option if no conflicts found, or throw on conflict.
1669
+ *
1670
+ * @param {Option} option
1671
+ * @api private
1672
+ */
1673
+
1674
+ _registerOption(option) {
1675
+ const matchingOption = (option.short && this._findOption(option.short)) ||
1676
+ (option.long && this._findOption(option.long));
1677
+ if (matchingOption) {
1678
+ const matchingFlag = (option.long && this._findOption(option.long)) ? option.long : option.short;
1679
+ throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
1680
+ - already used by option '${matchingOption.flags}'`);
1681
+ }
1682
+
1683
+ this.options.push(option);
1684
+ }
1685
+
1686
+ /**
1687
+ * Check for command name and alias conflicts with existing commands.
1688
+ * Register command if no conflicts found, or throw on conflict.
1689
+ *
1690
+ * @param {Command} command
1691
+ * @api private
1692
+ */
1693
+
1694
+ _registerCommand(command) {
1695
+ const knownBy = (cmd) => {
1696
+ return [cmd.name()].concat(cmd.aliases());
1697
+ };
1698
+
1699
+ const alreadyUsed = knownBy(command).find((name) => this._findCommand(name));
1700
+ if (alreadyUsed) {
1701
+ const existingCmd = knownBy(this._findCommand(alreadyUsed)).join('|');
1702
+ const newCmd = knownBy(command).join('|');
1703
+ throw new Error(`cannot add command '${newCmd}' as already have command '${existingCmd}'`);
1704
+ }
1705
+
1706
+ this.commands.push(command);
1707
+ }
1708
+
1709
+ /**
1710
+ * Add an option.
1711
+ *
1712
+ * @param {Option} option
1713
+ * @return {Command} `this` command for chaining
1714
+ */
1715
+ addOption(option) {
1716
+ this._registerOption(option);
1717
+
1718
+ const oname = option.name();
1719
+ const name = option.attributeName();
1720
+
1721
+ // store default value
1722
+ if (option.negate) {
1723
+ // --no-foo is special and defaults foo to true, unless a --foo option is already defined
1724
+ const positiveLongFlag = option.long.replace(/^--no-/, '--');
1725
+ if (!this._findOption(positiveLongFlag)) {
1726
+ this.setOptionValueWithSource(name, option.defaultValue === undefined ? true : option.defaultValue, 'default');
1727
+ }
1728
+ } else if (option.defaultValue !== undefined) {
1729
+ this.setOptionValueWithSource(name, option.defaultValue, 'default');
1730
+ }
1731
+
1732
+ // handler for cli and env supplied values
1733
+ const handleOptionValue = (val, invalidValueMessage, valueSource) => {
1734
+ // val is null for optional option used without an optional-argument.
1735
+ // val is undefined for boolean and negated option.
1736
+ if (val == null && option.presetArg !== undefined) {
1737
+ val = option.presetArg;
1738
+ }
1739
+
1740
+ // custom processing
1741
+ const oldValue = this.getOptionValue(name);
1742
+ if (val !== null && option.parseArg) {
1743
+ val = this._callParseArg(option, val, oldValue, invalidValueMessage);
1744
+ } else if (val !== null && option.variadic) {
1745
+ val = option._concatValue(val, oldValue);
1746
+ }
1747
+
1748
+ // Fill-in appropriate missing values. Long winded but easy to follow.
1749
+ if (val == null) {
1750
+ if (option.negate) {
1751
+ val = false;
1752
+ } else if (option.isBoolean() || option.optional) {
1753
+ val = true;
1754
+ } else {
1755
+ val = ''; // not normal, parseArg might have failed or be a mock function for testing
1756
+ }
1757
+ }
1758
+ this.setOptionValueWithSource(name, val, valueSource);
1759
+ };
1760
+
1761
+ this.on('option:' + oname, (val) => {
1762
+ const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
1763
+ handleOptionValue(val, invalidValueMessage, 'cli');
1764
+ });
1765
+
1766
+ if (option.envVar) {
1767
+ this.on('optionEnv:' + oname, (val) => {
1768
+ const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
1769
+ handleOptionValue(val, invalidValueMessage, 'env');
1770
+ });
1771
+ }
1772
+
1773
+ return this;
1774
+ }
1775
+
1776
+ /**
1777
+ * Internal implementation shared by .option() and .requiredOption()
1778
+ *
1779
+ * @private
1780
+ */
1781
+ _optionEx(config, flags, description, fn, defaultValue) {
1782
+ if (typeof flags === 'object' && flags instanceof Option$2) {
1783
+ throw new Error('To add an Option object use addOption() instead of option() or requiredOption()');
1784
+ }
1785
+ const option = this.createOption(flags, description);
1786
+ option.makeOptionMandatory(!!config.mandatory);
1787
+ if (typeof fn === 'function') {
1788
+ option.default(defaultValue).argParser(fn);
1789
+ } else if (fn instanceof RegExp) {
1790
+ // deprecated
1791
+ const regex = fn;
1792
+ fn = (val, def) => {
1793
+ const m = regex.exec(val);
1794
+ return m ? m[0] : def;
1795
+ };
1796
+ option.default(defaultValue).argParser(fn);
1797
+ } else {
1798
+ option.default(fn);
1799
+ }
1800
+
1801
+ return this.addOption(option);
1802
+ }
1803
+
1804
+ /**
1805
+ * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
1806
+ *
1807
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
1808
+ * option-argument is indicated by `<>` and an optional option-argument by `[]`.
1809
+ *
1810
+ * See the README for more details, and see also addOption() and requiredOption().
1811
+ *
1812
+ * @example
1813
+ * program
1814
+ * .option('-p, --pepper', 'add pepper')
1815
+ * .option('-p, --pizza-type <TYPE>', 'type of pizza') // required option-argument
1816
+ * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
1817
+ * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
1818
+ *
1819
+ * @param {string} flags
1820
+ * @param {string} [description]
1821
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
1822
+ * @param {*} [defaultValue]
1823
+ * @return {Command} `this` command for chaining
1824
+ */
1825
+
1826
+ option(flags, description, parseArg, defaultValue) {
1827
+ return this._optionEx({}, flags, description, parseArg, defaultValue);
1828
+ }
1829
+
1830
+ /**
1831
+ * Add a required option which must have a value after parsing. This usually means
1832
+ * the option must be specified on the command line. (Otherwise the same as .option().)
1833
+ *
1834
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
1835
+ *
1836
+ * @param {string} flags
1837
+ * @param {string} [description]
1838
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
1839
+ * @param {*} [defaultValue]
1840
+ * @return {Command} `this` command for chaining
1841
+ */
1842
+
1843
+ requiredOption(flags, description, parseArg, defaultValue) {
1844
+ return this._optionEx({ mandatory: true }, flags, description, parseArg, defaultValue);
1845
+ }
1846
+
1847
+ /**
1848
+ * Alter parsing of short flags with optional values.
1849
+ *
1850
+ * @example
1851
+ * // for `.option('-f,--flag [value]'):
1852
+ * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
1853
+ * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
1854
+ *
1855
+ * @param {boolean} [combine=true] - if `true` or omitted, an optional value can be specified directly after the flag.
1856
+ */
1857
+ combineFlagAndOptionalValue(combine = true) {
1858
+ this._combineFlagAndOptionalValue = !!combine;
1859
+ return this;
1860
+ }
1861
+
1862
+ /**
1863
+ * Allow unknown options on the command line.
1864
+ *
1865
+ * @param {boolean} [allowUnknown=true] - if `true` or omitted, no error will be thrown
1866
+ * for unknown options.
1867
+ */
1868
+ allowUnknownOption(allowUnknown = true) {
1869
+ this._allowUnknownOption = !!allowUnknown;
1870
+ return this;
1871
+ }
1872
+
1873
+ /**
1874
+ * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
1875
+ *
1876
+ * @param {boolean} [allowExcess=true] - if `true` or omitted, no error will be thrown
1877
+ * for excess arguments.
1878
+ */
1879
+ allowExcessArguments(allowExcess = true) {
1880
+ this._allowExcessArguments = !!allowExcess;
1881
+ return this;
1882
+ }
1883
+
1884
+ /**
1885
+ * Enable positional options. Positional means global options are specified before subcommands which lets
1886
+ * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
1887
+ * The default behaviour is non-positional and global options may appear anywhere on the command line.
1888
+ *
1889
+ * @param {boolean} [positional=true]
1890
+ */
1891
+ enablePositionalOptions(positional = true) {
1892
+ this._enablePositionalOptions = !!positional;
1893
+ return this;
1894
+ }
1895
+
1896
+ /**
1897
+ * Pass through options that come after command-arguments rather than treat them as command-options,
1898
+ * so actual command-options come before command-arguments. Turning this on for a subcommand requires
1899
+ * positional options to have been enabled on the program (parent commands).
1900
+ * The default behaviour is non-positional and options may appear before or after command-arguments.
1901
+ *
1902
+ * @param {boolean} [passThrough=true]
1903
+ * for unknown options.
1904
+ */
1905
+ passThroughOptions(passThrough = true) {
1906
+ this._passThroughOptions = !!passThrough;
1907
+ this._checkForBrokenPassThrough();
1908
+ return this;
1909
+ }
1910
+
1911
+ /**
1912
+ * @private
1913
+ */
1914
+
1915
+ _checkForBrokenPassThrough() {
1916
+ if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {
1917
+ throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`);
1918
+ }
1919
+ }
1920
+
1921
+ /**
1922
+ * Whether to store option values as properties on command object,
1923
+ * or store separately (specify false). In both cases the option values can be accessed using .opts().
1924
+ *
1925
+ * @param {boolean} [storeAsProperties=true]
1926
+ * @return {Command} `this` command for chaining
1927
+ */
1928
+
1929
+ storeOptionsAsProperties(storeAsProperties = true) {
1930
+ if (this.options.length) {
1931
+ throw new Error('call .storeOptionsAsProperties() before adding options');
1932
+ }
1933
+ if (Object.keys(this._optionValues).length) {
1934
+ throw new Error('call .storeOptionsAsProperties() before setting option values');
1935
+ }
1936
+ this._storeOptionsAsProperties = !!storeAsProperties;
1937
+ return this;
1938
+ }
1939
+
1940
+ /**
1941
+ * Retrieve option value.
1942
+ *
1943
+ * @param {string} key
1944
+ * @return {Object} value
1945
+ */
1946
+
1947
+ getOptionValue(key) {
1948
+ if (this._storeOptionsAsProperties) {
1949
+ return this[key];
1950
+ }
1951
+ return this._optionValues[key];
1952
+ }
1953
+
1954
+ /**
1955
+ * Store option value.
1956
+ *
1957
+ * @param {string} key
1958
+ * @param {Object} value
1959
+ * @return {Command} `this` command for chaining
1960
+ */
1961
+
1962
+ setOptionValue(key, value) {
1963
+ return this.setOptionValueWithSource(key, value, undefined);
1964
+ }
1965
+
1966
+ /**
1967
+ * Store option value and where the value came from.
1968
+ *
1969
+ * @param {string} key
1970
+ * @param {Object} value
1971
+ * @param {string} source - expected values are default/config/env/cli/implied
1972
+ * @return {Command} `this` command for chaining
1973
+ */
1974
+
1975
+ setOptionValueWithSource(key, value, source) {
1976
+ if (this._storeOptionsAsProperties) {
1977
+ this[key] = value;
1978
+ } else {
1979
+ this._optionValues[key] = value;
1980
+ }
1981
+ this._optionValueSources[key] = source;
1982
+ return this;
1983
+ }
1984
+
1985
+ /**
1986
+ * Get source of option value.
1987
+ * Expected values are default | config | env | cli | implied
1988
+ *
1989
+ * @param {string} key
1990
+ * @return {string}
1991
+ */
1992
+
1993
+ getOptionValueSource(key) {
1994
+ return this._optionValueSources[key];
1995
+ }
1996
+
1997
+ /**
1998
+ * Get source of option value. See also .optsWithGlobals().
1999
+ * Expected values are default | config | env | cli | implied
2000
+ *
2001
+ * @param {string} key
2002
+ * @return {string}
2003
+ */
2004
+
2005
+ getOptionValueSourceWithGlobals(key) {
2006
+ // global overwrites local, like optsWithGlobals
2007
+ let source;
2008
+ this._getCommandAndAncestors().forEach((cmd) => {
2009
+ if (cmd.getOptionValueSource(key) !== undefined) {
2010
+ source = cmd.getOptionValueSource(key);
2011
+ }
2012
+ });
2013
+ return source;
2014
+ }
2015
+
2016
+ /**
2017
+ * Get user arguments from implied or explicit arguments.
2018
+ * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
2019
+ *
2020
+ * @private
2021
+ */
2022
+
2023
+ _prepareUserArgs(argv, parseOptions) {
2024
+ if (argv !== undefined && !Array.isArray(argv)) {
2025
+ throw new Error('first parameter to parse must be array or undefined');
2026
+ }
2027
+ parseOptions = parseOptions || {};
2028
+
2029
+ // Default to using process.argv
2030
+ if (argv === undefined) {
2031
+ argv = process$1.argv;
2032
+ // @ts-ignore: unknown property
2033
+ if (process$1.versions && process$1.versions.electron) {
2034
+ parseOptions.from = 'electron';
2035
+ }
2036
+ }
2037
+ this.rawArgs = argv.slice();
2038
+
2039
+ // make it a little easier for callers by supporting various argv conventions
2040
+ let userArgs;
2041
+ switch (parseOptions.from) {
2042
+ case undefined:
2043
+ case 'node':
2044
+ this._scriptPath = argv[1];
2045
+ userArgs = argv.slice(2);
2046
+ break;
2047
+ case 'electron':
2048
+ // @ts-ignore: unknown property
2049
+ if (process$1.defaultApp) {
2050
+ this._scriptPath = argv[1];
2051
+ userArgs = argv.slice(2);
2052
+ } else {
2053
+ userArgs = argv.slice(1);
2054
+ }
2055
+ break;
2056
+ case 'user':
2057
+ userArgs = argv.slice(0);
2058
+ break;
2059
+ default:
2060
+ throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);
2061
+ }
2062
+
2063
+ // Find default name for program from arguments.
2064
+ if (!this._name && this._scriptPath) this.nameFromFilename(this._scriptPath);
2065
+ this._name = this._name || 'program';
2066
+
2067
+ return userArgs;
2068
+ }
2069
+
2070
+ /**
2071
+ * Parse `argv`, setting options and invoking commands when defined.
2072
+ *
2073
+ * The default expectation is that the arguments are from node and have the application as argv[0]
2074
+ * and the script being run in argv[1], with user parameters after that.
2075
+ *
2076
+ * @example
2077
+ * program.parse(process.argv);
2078
+ * program.parse(); // implicitly use process.argv and auto-detect node vs electron conventions
2079
+ * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
2080
+ *
2081
+ * @param {string[]} [argv] - optional, defaults to process.argv
2082
+ * @param {Object} [parseOptions] - optionally specify style of options with from: node/user/electron
2083
+ * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
2084
+ * @return {Command} `this` command for chaining
2085
+ */
2086
+
2087
+ parse(argv, parseOptions) {
2088
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
2089
+ this._parseCommand([], userArgs);
2090
+
2091
+ return this;
2092
+ }
2093
+
2094
+ /**
2095
+ * Parse `argv`, setting options and invoking commands when defined.
2096
+ *
2097
+ * Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise.
2098
+ *
2099
+ * The default expectation is that the arguments are from node and have the application as argv[0]
2100
+ * and the script being run in argv[1], with user parameters after that.
2101
+ *
2102
+ * @example
2103
+ * await program.parseAsync(process.argv);
2104
+ * await program.parseAsync(); // implicitly use process.argv and auto-detect node vs electron conventions
2105
+ * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
2106
+ *
2107
+ * @param {string[]} [argv]
2108
+ * @param {Object} [parseOptions]
2109
+ * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
2110
+ * @return {Promise}
2111
+ */
2112
+
2113
+ async parseAsync(argv, parseOptions) {
2114
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
2115
+ await this._parseCommand([], userArgs);
2116
+
2117
+ return this;
2118
+ }
2119
+
2120
+ /**
2121
+ * Execute a sub-command executable.
2122
+ *
2123
+ * @private
2124
+ */
2125
+
2126
+ _executeSubCommand(subcommand, args) {
2127
+ args = args.slice();
2128
+ let launchWithNode = false; // Use node for source targets so do not need to get permissions correct, and on Windows.
2129
+ const sourceExt = ['.js', '.ts', '.tsx', '.mjs', '.cjs'];
2130
+
2131
+ function findFile(baseDir, baseName) {
2132
+ // Look for specified file
2133
+ const localBin = path.resolve(baseDir, baseName);
2134
+ if (fs.existsSync(localBin)) return localBin;
2135
+
2136
+ // Stop looking if candidate already has an expected extension.
2137
+ if (sourceExt.includes(path.extname(baseName))) return undefined;
2138
+
2139
+ // Try all the extensions.
2140
+ const foundExt = sourceExt.find(ext => fs.existsSync(`${localBin}${ext}`));
2141
+ if (foundExt) return `${localBin}${foundExt}`;
2142
+
2143
+ return undefined;
2144
+ }
2145
+
2146
+ // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command.
2147
+ this._checkForMissingMandatoryOptions();
2148
+ this._checkForConflictingOptions();
2149
+
2150
+ // executableFile and executableDir might be full path, or just a name
2151
+ let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
2152
+ let executableDir = this._executableDir || '';
2153
+ if (this._scriptPath) {
2154
+ let resolvedScriptPath; // resolve possible symlink for installed npm binary
2155
+ try {
2156
+ resolvedScriptPath = fs.realpathSync(this._scriptPath);
2157
+ } catch (err) {
2158
+ resolvedScriptPath = this._scriptPath;
2159
+ }
2160
+ executableDir = path.resolve(path.dirname(resolvedScriptPath), executableDir);
2161
+ }
2162
+
2163
+ // Look for a local file in preference to a command in PATH.
2164
+ if (executableDir) {
2165
+ let localFile = findFile(executableDir, executableFile);
2166
+
2167
+ // Legacy search using prefix of script name instead of command name
2168
+ if (!localFile && !subcommand._executableFile && this._scriptPath) {
2169
+ const legacyName = path.basename(this._scriptPath, path.extname(this._scriptPath));
2170
+ if (legacyName !== this._name) {
2171
+ localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);
2172
+ }
2173
+ }
2174
+ executableFile = localFile || executableFile;
2175
+ }
2176
+
2177
+ launchWithNode = sourceExt.includes(path.extname(executableFile));
2178
+
2179
+ let proc;
2180
+ if (process$1.platform !== 'win32') {
2181
+ if (launchWithNode) {
2182
+ args.unshift(executableFile);
2183
+ // add executable arguments to spawn
2184
+ args = incrementNodeInspectorPort(process$1.execArgv).concat(args);
2185
+
2186
+ proc = childProcess.spawn(process$1.argv[0], args, { stdio: 'inherit' });
2187
+ } else {
2188
+ proc = childProcess.spawn(executableFile, args, { stdio: 'inherit' });
2189
+ }
2190
+ } else {
2191
+ args.unshift(executableFile);
2192
+ // add executable arguments to spawn
2193
+ args = incrementNodeInspectorPort(process$1.execArgv).concat(args);
2194
+ proc = childProcess.spawn(process$1.execPath, args, { stdio: 'inherit' });
2195
+ }
2196
+
2197
+ if (!proc.killed) { // testing mainly to avoid leak warnings during unit tests with mocked spawn
2198
+ const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];
2199
+ signals.forEach((signal) => {
2200
+ // @ts-ignore
2201
+ process$1.on(signal, () => {
2202
+ if (proc.killed === false && proc.exitCode === null) {
2203
+ proc.kill(signal);
2204
+ }
2205
+ });
2206
+ });
2207
+ }
2208
+
2209
+ // By default terminate process when spawned process terminates.
2210
+ const exitCallback = this._exitCallback;
2211
+ proc.on('close', (code, _signal) => {
2212
+ code = code ?? 1; // code is null if spawned process terminated due to a signal
2213
+ if (!exitCallback) {
2214
+ process$1.exit(code);
2215
+ } else {
2216
+ exitCallback(new CommanderError$2(code, 'commander.executeSubCommandAsync', '(close)'));
2217
+ }
2218
+ });
2219
+ proc.on('error', (err) => {
2220
+ // @ts-ignore
2221
+ if (err.code === 'ENOENT') {
2222
+ const executableDirMessage = executableDir
2223
+ ? `searched for local subcommand relative to directory '${executableDir}'`
2224
+ : 'no directory for search for local subcommand, use .executableDir() to supply a custom directory';
2225
+ const executableMissing = `'${executableFile}' does not exist
2226
+ - if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
2227
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
2228
+ - ${executableDirMessage}`;
2229
+ throw new Error(executableMissing);
2230
+ // @ts-ignore
2231
+ } else if (err.code === 'EACCES') {
2232
+ throw new Error(`'${executableFile}' not executable`);
2233
+ }
2234
+ if (!exitCallback) {
2235
+ process$1.exit(1);
2236
+ } else {
2237
+ const wrappedError = new CommanderError$2(1, 'commander.executeSubCommandAsync', '(error)');
2238
+ wrappedError.nestedError = err;
2239
+ exitCallback(wrappedError);
2240
+ }
2241
+ });
2242
+
2243
+ // Store the reference to the child process
2244
+ this.runningCommand = proc;
2245
+ }
2246
+
2247
+ /**
2248
+ * @private
2249
+ */
2250
+
2251
+ _dispatchSubcommand(commandName, operands, unknown) {
2252
+ const subCommand = this._findCommand(commandName);
2253
+ if (!subCommand) this.help({ error: true });
2254
+
2255
+ let promiseChain;
2256
+ promiseChain = this._chainOrCallSubCommandHook(promiseChain, subCommand, 'preSubcommand');
2257
+ promiseChain = this._chainOrCall(promiseChain, () => {
2258
+ if (subCommand._executableHandler) {
2259
+ this._executeSubCommand(subCommand, operands.concat(unknown));
2260
+ } else {
2261
+ return subCommand._parseCommand(operands, unknown);
2262
+ }
2263
+ });
2264
+ return promiseChain;
2265
+ }
2266
+
2267
+ /**
2268
+ * Invoke help directly if possible, or dispatch if necessary.
2269
+ * e.g. help foo
2270
+ *
2271
+ * @private
2272
+ */
2273
+
2274
+ _dispatchHelpCommand(subcommandName) {
2275
+ if (!subcommandName) {
2276
+ this.help();
2277
+ }
2278
+ const subCommand = this._findCommand(subcommandName);
2279
+ if (subCommand && !subCommand._executableHandler) {
2280
+ subCommand.help();
2281
+ }
2282
+
2283
+ // Fallback to parsing the help flag to invoke the help.
2284
+ return this._dispatchSubcommand(subcommandName, [], [
2285
+ this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? '--help'
2286
+ ]);
2287
+ }
2288
+
2289
+ /**
2290
+ * Check this.args against expected this.registeredArguments.
2291
+ *
2292
+ * @private
2293
+ */
2294
+
2295
+ _checkNumberOfArguments() {
2296
+ // too few
2297
+ this.registeredArguments.forEach((arg, i) => {
2298
+ if (arg.required && this.args[i] == null) {
2299
+ this.missingArgument(arg.name());
2300
+ }
2301
+ });
2302
+ // too many
2303
+ if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
2304
+ return;
2305
+ }
2306
+ if (this.args.length > this.registeredArguments.length) {
2307
+ this._excessArguments(this.args);
2308
+ }
2309
+ }
2310
+
2311
+ /**
2312
+ * Process this.args using this.registeredArguments and save as this.processedArgs!
2313
+ *
2314
+ * @private
2315
+ */
2316
+
2317
+ _processArguments() {
2318
+ const myParseArg = (argument, value, previous) => {
2319
+ // Extra processing for nice error message on parsing failure.
2320
+ let parsedValue = value;
2321
+ if (value !== null && argument.parseArg) {
2322
+ const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
2323
+ parsedValue = this._callParseArg(argument, value, previous, invalidValueMessage);
2324
+ }
2325
+ return parsedValue;
2326
+ };
2327
+
2328
+ this._checkNumberOfArguments();
2329
+
2330
+ const processedArgs = [];
2331
+ this.registeredArguments.forEach((declaredArg, index) => {
2332
+ let value = declaredArg.defaultValue;
2333
+ if (declaredArg.variadic) {
2334
+ // Collect together remaining arguments for passing together as an array.
2335
+ if (index < this.args.length) {
2336
+ value = this.args.slice(index);
2337
+ if (declaredArg.parseArg) {
2338
+ value = value.reduce((processed, v) => {
2339
+ return myParseArg(declaredArg, v, processed);
2340
+ }, declaredArg.defaultValue);
2341
+ }
2342
+ } else if (value === undefined) {
2343
+ value = [];
2344
+ }
2345
+ } else if (index < this.args.length) {
2346
+ value = this.args[index];
2347
+ if (declaredArg.parseArg) {
2348
+ value = myParseArg(declaredArg, value, declaredArg.defaultValue);
2349
+ }
2350
+ }
2351
+ processedArgs[index] = value;
2352
+ });
2353
+ this.processedArgs = processedArgs;
2354
+ }
2355
+
2356
+ /**
2357
+ * Once we have a promise we chain, but call synchronously until then.
2358
+ *
2359
+ * @param {(Promise|undefined)} promise
2360
+ * @param {Function} fn
2361
+ * @return {(Promise|undefined)}
2362
+ * @private
2363
+ */
2364
+
2365
+ _chainOrCall(promise, fn) {
2366
+ // thenable
2367
+ if (promise && promise.then && typeof promise.then === 'function') {
2368
+ // already have a promise, chain callback
2369
+ return promise.then(() => fn());
2370
+ }
2371
+ // callback might return a promise
2372
+ return fn();
2373
+ }
2374
+
2375
+ /**
2376
+ *
2377
+ * @param {(Promise|undefined)} promise
2378
+ * @param {string} event
2379
+ * @return {(Promise|undefined)}
2380
+ * @private
2381
+ */
2382
+
2383
+ _chainOrCallHooks(promise, event) {
2384
+ let result = promise;
2385
+ const hooks = [];
2386
+ this._getCommandAndAncestors()
2387
+ .reverse()
2388
+ .filter(cmd => cmd._lifeCycleHooks[event] !== undefined)
2389
+ .forEach(hookedCommand => {
2390
+ hookedCommand._lifeCycleHooks[event].forEach((callback) => {
2391
+ hooks.push({ hookedCommand, callback });
2392
+ });
2393
+ });
2394
+ if (event === 'postAction') {
2395
+ hooks.reverse();
2396
+ }
2397
+
2398
+ hooks.forEach((hookDetail) => {
2399
+ result = this._chainOrCall(result, () => {
2400
+ return hookDetail.callback(hookDetail.hookedCommand, this);
2401
+ });
2402
+ });
2403
+ return result;
2404
+ }
2405
+
2406
+ /**
2407
+ *
2408
+ * @param {(Promise|undefined)} promise
2409
+ * @param {Command} subCommand
2410
+ * @param {string} event
2411
+ * @return {(Promise|undefined)}
2412
+ * @private
2413
+ */
2414
+
2415
+ _chainOrCallSubCommandHook(promise, subCommand, event) {
2416
+ let result = promise;
2417
+ if (this._lifeCycleHooks[event] !== undefined) {
2418
+ this._lifeCycleHooks[event].forEach((hook) => {
2419
+ result = this._chainOrCall(result, () => {
2420
+ return hook(this, subCommand);
2421
+ });
2422
+ });
2423
+ }
2424
+ return result;
2425
+ }
2426
+
2427
+ /**
2428
+ * Process arguments in context of this command.
2429
+ * Returns action result, in case it is a promise.
2430
+ *
2431
+ * @private
2432
+ */
2433
+
2434
+ _parseCommand(operands, unknown) {
2435
+ const parsed = this.parseOptions(unknown);
2436
+ this._parseOptionsEnv(); // after cli, so parseArg not called on both cli and env
2437
+ this._parseOptionsImplied();
2438
+ operands = operands.concat(parsed.operands);
2439
+ unknown = parsed.unknown;
2440
+ this.args = operands.concat(unknown);
2441
+
2442
+ if (operands && this._findCommand(operands[0])) {
2443
+ return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
2444
+ }
2445
+ if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) {
2446
+ return this._dispatchHelpCommand(operands[1]);
2447
+ }
2448
+ if (this._defaultCommandName) {
2449
+ this._outputHelpIfRequested(unknown); // Run the help for default command from parent rather than passing to default command
2450
+ return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);
2451
+ }
2452
+ if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
2453
+ // probably missing subcommand and no handler, user needs help (and exit)
2454
+ this.help({ error: true });
2455
+ }
2456
+
2457
+ this._outputHelpIfRequested(parsed.unknown);
2458
+ this._checkForMissingMandatoryOptions();
2459
+ this._checkForConflictingOptions();
2460
+
2461
+ // We do not always call this check to avoid masking a "better" error, like unknown command.
2462
+ const checkForUnknownOptions = () => {
2463
+ if (parsed.unknown.length > 0) {
2464
+ this.unknownOption(parsed.unknown[0]);
2465
+ }
2466
+ };
2467
+
2468
+ const commandEvent = `command:${this.name()}`;
2469
+ if (this._actionHandler) {
2470
+ checkForUnknownOptions();
2471
+ this._processArguments();
2472
+
2473
+ let promiseChain;
2474
+ promiseChain = this._chainOrCallHooks(promiseChain, 'preAction');
2475
+ promiseChain = this._chainOrCall(promiseChain, () => this._actionHandler(this.processedArgs));
2476
+ if (this.parent) {
2477
+ promiseChain = this._chainOrCall(promiseChain, () => {
2478
+ this.parent.emit(commandEvent, operands, unknown); // legacy
2479
+ });
2480
+ }
2481
+ promiseChain = this._chainOrCallHooks(promiseChain, 'postAction');
2482
+ return promiseChain;
2483
+ }
2484
+ if (this.parent && this.parent.listenerCount(commandEvent)) {
2485
+ checkForUnknownOptions();
2486
+ this._processArguments();
2487
+ this.parent.emit(commandEvent, operands, unknown); // legacy
2488
+ } else if (operands.length) {
2489
+ if (this._findCommand('*')) { // legacy default command
2490
+ return this._dispatchSubcommand('*', operands, unknown);
2491
+ }
2492
+ if (this.listenerCount('command:*')) {
2493
+ // skip option check, emit event for possible misspelling suggestion
2494
+ this.emit('command:*', operands, unknown);
2495
+ } else if (this.commands.length) {
2496
+ this.unknownCommand();
2497
+ } else {
2498
+ checkForUnknownOptions();
2499
+ this._processArguments();
2500
+ }
2501
+ } else if (this.commands.length) {
2502
+ checkForUnknownOptions();
2503
+ // This command has subcommands and nothing hooked up at this level, so display help (and exit).
2504
+ this.help({ error: true });
2505
+ } else {
2506
+ checkForUnknownOptions();
2507
+ this._processArguments();
2508
+ // fall through for caller to handle after calling .parse()
2509
+ }
2510
+ }
2511
+
2512
+ /**
2513
+ * Find matching command.
2514
+ *
2515
+ * @private
2516
+ */
2517
+ _findCommand(name) {
2518
+ if (!name) return undefined;
2519
+ return this.commands.find(cmd => cmd._name === name || cmd._aliases.includes(name));
2520
+ }
2521
+
2522
+ /**
2523
+ * Return an option matching `arg` if any.
2524
+ *
2525
+ * @param {string} arg
2526
+ * @return {Option}
2527
+ * @package internal use only
2528
+ */
2529
+
2530
+ _findOption(arg) {
2531
+ return this.options.find(option => option.is(arg));
2532
+ }
2533
+
2534
+ /**
2535
+ * Display an error message if a mandatory option does not have a value.
2536
+ * Called after checking for help flags in leaf subcommand.
2537
+ *
2538
+ * @private
2539
+ */
2540
+
2541
+ _checkForMissingMandatoryOptions() {
2542
+ // Walk up hierarchy so can call in subcommand after checking for displaying help.
2543
+ this._getCommandAndAncestors().forEach((cmd) => {
2544
+ cmd.options.forEach((anOption) => {
2545
+ if (anOption.mandatory && (cmd.getOptionValue(anOption.attributeName()) === undefined)) {
2546
+ cmd.missingMandatoryOptionValue(anOption);
2547
+ }
2548
+ });
2549
+ });
2550
+ }
2551
+
2552
+ /**
2553
+ * Display an error message if conflicting options are used together in this.
2554
+ *
2555
+ * @private
2556
+ */
2557
+ _checkForConflictingLocalOptions() {
2558
+ const definedNonDefaultOptions = this.options.filter(
2559
+ (option) => {
2560
+ const optionKey = option.attributeName();
2561
+ if (this.getOptionValue(optionKey) === undefined) {
2562
+ return false;
2563
+ }
2564
+ return this.getOptionValueSource(optionKey) !== 'default';
2565
+ }
2566
+ );
2567
+
2568
+ const optionsWithConflicting = definedNonDefaultOptions.filter(
2569
+ (option) => option.conflictsWith.length > 0
2570
+ );
2571
+
2572
+ optionsWithConflicting.forEach((option) => {
2573
+ const conflictingAndDefined = definedNonDefaultOptions.find((defined) =>
2574
+ option.conflictsWith.includes(defined.attributeName())
2575
+ );
2576
+ if (conflictingAndDefined) {
2577
+ this._conflictingOption(option, conflictingAndDefined);
2578
+ }
2579
+ });
2580
+ }
2581
+
2582
+ /**
2583
+ * Display an error message if conflicting options are used together.
2584
+ * Called after checking for help flags in leaf subcommand.
2585
+ *
2586
+ * @private
2587
+ */
2588
+ _checkForConflictingOptions() {
2589
+ // Walk up hierarchy so can call in subcommand after checking for displaying help.
2590
+ this._getCommandAndAncestors().forEach((cmd) => {
2591
+ cmd._checkForConflictingLocalOptions();
2592
+ });
2593
+ }
2594
+
2595
+ /**
2596
+ * Parse options from `argv` removing known options,
2597
+ * and return argv split into operands and unknown arguments.
2598
+ *
2599
+ * Examples:
2600
+ *
2601
+ * argv => operands, unknown
2602
+ * --known kkk op => [op], []
2603
+ * op --known kkk => [op], []
2604
+ * sub --unknown uuu op => [sub], [--unknown uuu op]
2605
+ * sub -- --unknown uuu op => [sub --unknown uuu op], []
2606
+ *
2607
+ * @param {string[]} argv
2608
+ * @return {{operands: string[], unknown: string[]}}
2609
+ */
2610
+
2611
+ parseOptions(argv) {
2612
+ const operands = []; // operands, not options or values
2613
+ const unknown = []; // first unknown option and remaining unknown args
2614
+ let dest = operands;
2615
+ const args = argv.slice();
2616
+
2617
+ function maybeOption(arg) {
2618
+ return arg.length > 1 && arg[0] === '-';
2619
+ }
2620
+
2621
+ // parse options
2622
+ let activeVariadicOption = null;
2623
+ while (args.length) {
2624
+ const arg = args.shift();
2625
+
2626
+ // literal
2627
+ if (arg === '--') {
2628
+ if (dest === unknown) dest.push(arg);
2629
+ dest.push(...args);
2630
+ break;
2631
+ }
2632
+
2633
+ if (activeVariadicOption && !maybeOption(arg)) {
2634
+ this.emit(`option:${activeVariadicOption.name()}`, arg);
2635
+ continue;
2636
+ }
2637
+ activeVariadicOption = null;
2638
+
2639
+ if (maybeOption(arg)) {
2640
+ const option = this._findOption(arg);
2641
+ // recognised option, call listener to assign value with possible custom processing
2642
+ if (option) {
2643
+ if (option.required) {
2644
+ const value = args.shift();
2645
+ if (value === undefined) this.optionMissingArgument(option);
2646
+ this.emit(`option:${option.name()}`, value);
2647
+ } else if (option.optional) {
2648
+ let value = null;
2649
+ // historical behaviour is optional value is following arg unless an option
2650
+ if (args.length > 0 && !maybeOption(args[0])) {
2651
+ value = args.shift();
2652
+ }
2653
+ this.emit(`option:${option.name()}`, value);
2654
+ } else { // boolean flag
2655
+ this.emit(`option:${option.name()}`);
2656
+ }
2657
+ activeVariadicOption = option.variadic ? option : null;
2658
+ continue;
2659
+ }
2660
+ }
2661
+
2662
+ // Look for combo options following single dash, eat first one if known.
2663
+ if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') {
2664
+ const option = this._findOption(`-${arg[1]}`);
2665
+ if (option) {
2666
+ if (option.required || (option.optional && this._combineFlagAndOptionalValue)) {
2667
+ // option with value following in same argument
2668
+ this.emit(`option:${option.name()}`, arg.slice(2));
2669
+ } else {
2670
+ // boolean option, emit and put back remainder of arg for further processing
2671
+ this.emit(`option:${option.name()}`);
2672
+ args.unshift(`-${arg.slice(2)}`);
2673
+ }
2674
+ continue;
2675
+ }
2676
+ }
2677
+
2678
+ // Look for known long flag with value, like --foo=bar
2679
+ if (/^--[^=]+=/.test(arg)) {
2680
+ const index = arg.indexOf('=');
2681
+ const option = this._findOption(arg.slice(0, index));
2682
+ if (option && (option.required || option.optional)) {
2683
+ this.emit(`option:${option.name()}`, arg.slice(index + 1));
2684
+ continue;
2685
+ }
2686
+ }
2687
+
2688
+ // Not a recognised option by this command.
2689
+ // Might be a command-argument, or subcommand option, or unknown option, or help command or option.
2690
+
2691
+ // An unknown option means further arguments also classified as unknown so can be reprocessed by subcommands.
2692
+ if (maybeOption(arg)) {
2693
+ dest = unknown;
2694
+ }
2695
+
2696
+ // If using positionalOptions, stop processing our options at subcommand.
2697
+ if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
2698
+ if (this._findCommand(arg)) {
2699
+ operands.push(arg);
2700
+ if (args.length > 0) unknown.push(...args);
2701
+ break;
2702
+ } else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
2703
+ operands.push(arg);
2704
+ if (args.length > 0) operands.push(...args);
2705
+ break;
2706
+ } else if (this._defaultCommandName) {
2707
+ unknown.push(arg);
2708
+ if (args.length > 0) unknown.push(...args);
2709
+ break;
2710
+ }
2711
+ }
2712
+
2713
+ // If using passThroughOptions, stop processing options at first command-argument.
2714
+ if (this._passThroughOptions) {
2715
+ dest.push(arg);
2716
+ if (args.length > 0) dest.push(...args);
2717
+ break;
2718
+ }
2719
+
2720
+ // add arg
2721
+ dest.push(arg);
2722
+ }
2723
+
2724
+ return { operands, unknown };
2725
+ }
2726
+
2727
+ /**
2728
+ * Return an object containing local option values as key-value pairs.
2729
+ *
2730
+ * @return {Object}
2731
+ */
2732
+ opts() {
2733
+ if (this._storeOptionsAsProperties) {
2734
+ // Preserve original behaviour so backwards compatible when still using properties
2735
+ const result = {};
2736
+ const len = this.options.length;
2737
+
2738
+ for (let i = 0; i < len; i++) {
2739
+ const key = this.options[i].attributeName();
2740
+ result[key] = key === this._versionOptionName ? this._version : this[key];
2741
+ }
2742
+ return result;
2743
+ }
2744
+
2745
+ return this._optionValues;
2746
+ }
2747
+
2748
+ /**
2749
+ * Return an object containing merged local and global option values as key-value pairs.
2750
+ *
2751
+ * @return {Object}
2752
+ */
2753
+ optsWithGlobals() {
2754
+ // globals overwrite locals
2755
+ return this._getCommandAndAncestors().reduce(
2756
+ (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),
2757
+ {}
2758
+ );
2759
+ }
2760
+
2761
+ /**
2762
+ * Display error message and exit (or call exitOverride).
2763
+ *
2764
+ * @param {string} message
2765
+ * @param {Object} [errorOptions]
2766
+ * @param {string} [errorOptions.code] - an id string representing the error
2767
+ * @param {number} [errorOptions.exitCode] - used with process.exit
2768
+ */
2769
+ error(message, errorOptions) {
2770
+ // output handling
2771
+ this._outputConfiguration.outputError(`${message}\n`, this._outputConfiguration.writeErr);
2772
+ if (typeof this._showHelpAfterError === 'string') {
2773
+ this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`);
2774
+ } else if (this._showHelpAfterError) {
2775
+ this._outputConfiguration.writeErr('\n');
2776
+ this.outputHelp({ error: true });
2777
+ }
2778
+
2779
+ // exit handling
2780
+ const config = errorOptions || {};
2781
+ const exitCode = config.exitCode || 1;
2782
+ const code = config.code || 'commander.error';
2783
+ this._exit(exitCode, code, message);
2784
+ }
2785
+
2786
+ /**
2787
+ * Apply any option related environment variables, if option does
2788
+ * not have a value from cli or client code.
2789
+ *
2790
+ * @private
2791
+ */
2792
+ _parseOptionsEnv() {
2793
+ this.options.forEach((option) => {
2794
+ if (option.envVar && option.envVar in process$1.env) {
2795
+ const optionKey = option.attributeName();
2796
+ // Priority check. Do not overwrite cli or options from unknown source (client-code).
2797
+ if (this.getOptionValue(optionKey) === undefined || ['default', 'config', 'env'].includes(this.getOptionValueSource(optionKey))) {
2798
+ if (option.required || option.optional) { // option can take a value
2799
+ // keep very simple, optional always takes value
2800
+ this.emit(`optionEnv:${option.name()}`, process$1.env[option.envVar]);
2801
+ } else { // boolean
2802
+ // keep very simple, only care that envVar defined and not the value
2803
+ this.emit(`optionEnv:${option.name()}`);
2804
+ }
2805
+ }
2806
+ }
2807
+ });
2808
+ }
2809
+
2810
+ /**
2811
+ * Apply any implied option values, if option is undefined or default value.
2812
+ *
2813
+ * @private
2814
+ */
2815
+ _parseOptionsImplied() {
2816
+ const dualHelper = new DualOptions(this.options);
2817
+ const hasCustomOptionValue = (optionKey) => {
2818
+ return this.getOptionValue(optionKey) !== undefined && !['default', 'implied'].includes(this.getOptionValueSource(optionKey));
2819
+ };
2820
+ this.options
2821
+ .filter(option => (option.implied !== undefined) &&
2822
+ hasCustomOptionValue(option.attributeName()) &&
2823
+ dualHelper.valueFromOption(this.getOptionValue(option.attributeName()), option))
2824
+ .forEach((option) => {
2825
+ Object.keys(option.implied)
2826
+ .filter(impliedKey => !hasCustomOptionValue(impliedKey))
2827
+ .forEach(impliedKey => {
2828
+ this.setOptionValueWithSource(impliedKey, option.implied[impliedKey], 'implied');
2829
+ });
2830
+ });
2831
+ }
2832
+
2833
+ /**
2834
+ * Argument `name` is missing.
2835
+ *
2836
+ * @param {string} name
2837
+ * @private
2838
+ */
2839
+
2840
+ missingArgument(name) {
2841
+ const message = `error: missing required argument '${name}'`;
2842
+ this.error(message, { code: 'commander.missingArgument' });
2843
+ }
2844
+
2845
+ /**
2846
+ * `Option` is missing an argument.
2847
+ *
2848
+ * @param {Option} option
2849
+ * @private
2850
+ */
2851
+
2852
+ optionMissingArgument(option) {
2853
+ const message = `error: option '${option.flags}' argument missing`;
2854
+ this.error(message, { code: 'commander.optionMissingArgument' });
2855
+ }
2856
+
2857
+ /**
2858
+ * `Option` does not have a value, and is a mandatory option.
2859
+ *
2860
+ * @param {Option} option
2861
+ * @private
2862
+ */
2863
+
2864
+ missingMandatoryOptionValue(option) {
2865
+ const message = `error: required option '${option.flags}' not specified`;
2866
+ this.error(message, { code: 'commander.missingMandatoryOptionValue' });
2867
+ }
2868
+
2869
+ /**
2870
+ * `Option` conflicts with another option.
2871
+ *
2872
+ * @param {Option} option
2873
+ * @param {Option} conflictingOption
2874
+ * @private
2875
+ */
2876
+ _conflictingOption(option, conflictingOption) {
2877
+ // The calling code does not know whether a negated option is the source of the
2878
+ // value, so do some work to take an educated guess.
2879
+ const findBestOptionFromValue = (option) => {
2880
+ const optionKey = option.attributeName();
2881
+ const optionValue = this.getOptionValue(optionKey);
2882
+ const negativeOption = this.options.find(target => target.negate && optionKey === target.attributeName());
2883
+ const positiveOption = this.options.find(target => !target.negate && optionKey === target.attributeName());
2884
+ if (negativeOption && (
2885
+ (negativeOption.presetArg === undefined && optionValue === false) ||
2886
+ (negativeOption.presetArg !== undefined && optionValue === negativeOption.presetArg)
2887
+ )) {
2888
+ return negativeOption;
2889
+ }
2890
+ return positiveOption || option;
2891
+ };
2892
+
2893
+ const getErrorMessage = (option) => {
2894
+ const bestOption = findBestOptionFromValue(option);
2895
+ const optionKey = bestOption.attributeName();
2896
+ const source = this.getOptionValueSource(optionKey);
2897
+ if (source === 'env') {
2898
+ return `environment variable '${bestOption.envVar}'`;
2899
+ }
2900
+ return `option '${bestOption.flags}'`;
2901
+ };
2902
+
2903
+ const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
2904
+ this.error(message, { code: 'commander.conflictingOption' });
2905
+ }
2906
+
2907
+ /**
2908
+ * Unknown option `flag`.
2909
+ *
2910
+ * @param {string} flag
2911
+ * @private
2912
+ */
2913
+
2914
+ unknownOption(flag) {
2915
+ if (this._allowUnknownOption) return;
2916
+ let suggestion = '';
2917
+
2918
+ if (flag.startsWith('--') && this._showSuggestionAfterError) {
2919
+ // Looping to pick up the global options too
2920
+ let candidateFlags = [];
2921
+ let command = this;
2922
+ do {
2923
+ const moreFlags = command.createHelp().visibleOptions(command)
2924
+ .filter(option => option.long)
2925
+ .map(option => option.long);
2926
+ candidateFlags = candidateFlags.concat(moreFlags);
2927
+ command = command.parent;
2928
+ } while (command && !command._enablePositionalOptions);
2929
+ suggestion = suggestSimilar(flag, candidateFlags);
2930
+ }
2931
+
2932
+ const message = `error: unknown option '${flag}'${suggestion}`;
2933
+ this.error(message, { code: 'commander.unknownOption' });
2934
+ }
2935
+
2936
+ /**
2937
+ * Excess arguments, more than expected.
2938
+ *
2939
+ * @param {string[]} receivedArgs
2940
+ * @private
2941
+ */
2942
+
2943
+ _excessArguments(receivedArgs) {
2944
+ if (this._allowExcessArguments) return;
2945
+
2946
+ const expected = this.registeredArguments.length;
2947
+ const s = (expected === 1) ? '' : 's';
2948
+ const forSubcommand = this.parent ? ` for '${this.name()}'` : '';
2949
+ const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
2950
+ this.error(message, { code: 'commander.excessArguments' });
2951
+ }
2952
+
2953
+ /**
2954
+ * Unknown command.
2955
+ *
2956
+ * @private
2957
+ */
2958
+
2959
+ unknownCommand() {
2960
+ const unknownName = this.args[0];
2961
+ let suggestion = '';
2962
+
2963
+ if (this._showSuggestionAfterError) {
2964
+ const candidateNames = [];
2965
+ this.createHelp().visibleCommands(this).forEach((command) => {
2966
+ candidateNames.push(command.name());
2967
+ // just visible alias
2968
+ if (command.alias()) candidateNames.push(command.alias());
2969
+ });
2970
+ suggestion = suggestSimilar(unknownName, candidateNames);
2971
+ }
2972
+
2973
+ const message = `error: unknown command '${unknownName}'${suggestion}`;
2974
+ this.error(message, { code: 'commander.unknownCommand' });
2975
+ }
2976
+
2977
+ /**
2978
+ * Get or set the program version.
2979
+ *
2980
+ * This method auto-registers the "-V, --version" option which will print the version number.
2981
+ *
2982
+ * You can optionally supply the flags and description to override the defaults.
2983
+ *
2984
+ * @param {string} [str]
2985
+ * @param {string} [flags]
2986
+ * @param {string} [description]
2987
+ * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments
2988
+ */
2989
+
2990
+ version(str, flags, description) {
2991
+ if (str === undefined) return this._version;
2992
+ this._version = str;
2993
+ flags = flags || '-V, --version';
2994
+ description = description || 'output the version number';
2995
+ const versionOption = this.createOption(flags, description);
2996
+ this._versionOptionName = versionOption.attributeName();
2997
+ this._registerOption(versionOption);
2998
+
2999
+ this.on('option:' + versionOption.name(), () => {
3000
+ this._outputConfiguration.writeOut(`${str}\n`);
3001
+ this._exit(0, 'commander.version', str);
3002
+ });
3003
+ return this;
3004
+ }
3005
+
3006
+ /**
3007
+ * Set the description.
3008
+ *
3009
+ * @param {string} [str]
3010
+ * @param {Object} [argsDescription]
3011
+ * @return {(string|Command)}
3012
+ */
3013
+ description(str, argsDescription) {
3014
+ if (str === undefined && argsDescription === undefined) return this._description;
3015
+ this._description = str;
3016
+ if (argsDescription) {
3017
+ this._argsDescription = argsDescription;
3018
+ }
3019
+ return this;
3020
+ }
3021
+
3022
+ /**
3023
+ * Set the summary. Used when listed as subcommand of parent.
3024
+ *
3025
+ * @param {string} [str]
3026
+ * @return {(string|Command)}
3027
+ */
3028
+ summary(str) {
3029
+ if (str === undefined) return this._summary;
3030
+ this._summary = str;
3031
+ return this;
3032
+ }
3033
+
3034
+ /**
3035
+ * Set an alias for the command.
3036
+ *
3037
+ * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
3038
+ *
3039
+ * @param {string} [alias]
3040
+ * @return {(string|Command)}
3041
+ */
3042
+
3043
+ alias(alias) {
3044
+ if (alias === undefined) return this._aliases[0]; // just return first, for backwards compatibility
3045
+
3046
+ /** @type {Command} */
3047
+ let command = this;
3048
+ if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
3049
+ // assume adding alias for last added executable subcommand, rather than this
3050
+ command = this.commands[this.commands.length - 1];
3051
+ }
3052
+
3053
+ if (alias === command._name) throw new Error('Command alias can\'t be the same as its name');
3054
+ const matchingCommand = this.parent?._findCommand(alias);
3055
+ if (matchingCommand) {
3056
+ // c.f. _registerCommand
3057
+ const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join('|');
3058
+ throw new Error(`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`);
3059
+ }
3060
+
3061
+ command._aliases.push(alias);
3062
+ return this;
3063
+ }
3064
+
3065
+ /**
3066
+ * Set aliases for the command.
3067
+ *
3068
+ * Only the first alias is shown in the auto-generated help.
3069
+ *
3070
+ * @param {string[]} [aliases]
3071
+ * @return {(string[]|Command)}
3072
+ */
3073
+
3074
+ aliases(aliases) {
3075
+ // Getter for the array of aliases is the main reason for having aliases() in addition to alias().
3076
+ if (aliases === undefined) return this._aliases;
3077
+
3078
+ aliases.forEach((alias) => this.alias(alias));
3079
+ return this;
3080
+ }
3081
+
3082
+ /**
3083
+ * Set / get the command usage `str`.
3084
+ *
3085
+ * @param {string} [str]
3086
+ * @return {(string|Command)}
3087
+ */
3088
+
3089
+ usage(str) {
3090
+ if (str === undefined) {
3091
+ if (this._usage) return this._usage;
3092
+
3093
+ const args = this.registeredArguments.map((arg) => {
3094
+ return humanReadableArgName(arg);
3095
+ });
3096
+ return [].concat(
3097
+ (this.options.length || (this._helpOption !== null) ? '[options]' : []),
3098
+ (this.commands.length ? '[command]' : []),
3099
+ (this.registeredArguments.length ? args : [])
3100
+ ).join(' ');
3101
+ }
3102
+
3103
+ this._usage = str;
3104
+ return this;
3105
+ }
3106
+
3107
+ /**
3108
+ * Get or set the name of the command.
3109
+ *
3110
+ * @param {string} [str]
3111
+ * @return {(string|Command)}
3112
+ */
3113
+
3114
+ name(str) {
3115
+ if (str === undefined) return this._name;
3116
+ this._name = str;
3117
+ return this;
3118
+ }
3119
+
3120
+ /**
3121
+ * Set the name of the command from script filename, such as process.argv[1],
3122
+ * or require.main.filename, or __filename.
3123
+ *
3124
+ * (Used internally and public although not documented in README.)
3125
+ *
3126
+ * @example
3127
+ * program.nameFromFilename(require.main.filename);
3128
+ *
3129
+ * @param {string} filename
3130
+ * @return {Command}
3131
+ */
3132
+
3133
+ nameFromFilename(filename) {
3134
+ this._name = path.basename(filename, path.extname(filename));
3135
+
3136
+ return this;
3137
+ }
3138
+
3139
+ /**
3140
+ * Get or set the directory for searching for executable subcommands of this command.
3141
+ *
3142
+ * @example
3143
+ * program.executableDir(__dirname);
3144
+ * // or
3145
+ * program.executableDir('subcommands');
3146
+ *
3147
+ * @param {string} [path]
3148
+ * @return {(string|null|Command)}
3149
+ */
3150
+
3151
+ executableDir(path) {
3152
+ if (path === undefined) return this._executableDir;
3153
+ this._executableDir = path;
3154
+ return this;
3155
+ }
3156
+
3157
+ /**
3158
+ * Return program help documentation.
3159
+ *
3160
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
3161
+ * @return {string}
3162
+ */
3163
+
3164
+ helpInformation(contextOptions) {
3165
+ const helper = this.createHelp();
3166
+ if (helper.helpWidth === undefined) {
3167
+ helper.helpWidth = (contextOptions && contextOptions.error) ? this._outputConfiguration.getErrHelpWidth() : this._outputConfiguration.getOutHelpWidth();
3168
+ }
3169
+ return helper.formatHelp(this, helper);
3170
+ }
3171
+
3172
+ /**
3173
+ * @private
3174
+ */
3175
+
3176
+ _getHelpContext(contextOptions) {
3177
+ contextOptions = contextOptions || {};
3178
+ const context = { error: !!contextOptions.error };
3179
+ let write;
3180
+ if (context.error) {
3181
+ write = (arg) => this._outputConfiguration.writeErr(arg);
3182
+ } else {
3183
+ write = (arg) => this._outputConfiguration.writeOut(arg);
3184
+ }
3185
+ context.write = contextOptions.write || write;
3186
+ context.command = this;
3187
+ return context;
3188
+ }
3189
+
3190
+ /**
3191
+ * Output help information for this command.
3192
+ *
3193
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
3194
+ *
3195
+ * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
3196
+ */
3197
+
3198
+ outputHelp(contextOptions) {
3199
+ let deprecatedCallback;
3200
+ if (typeof contextOptions === 'function') {
3201
+ deprecatedCallback = contextOptions;
3202
+ contextOptions = undefined;
3203
+ }
3204
+ const context = this._getHelpContext(contextOptions);
3205
+
3206
+ this._getCommandAndAncestors().reverse().forEach(command => command.emit('beforeAllHelp', context));
3207
+ this.emit('beforeHelp', context);
3208
+
3209
+ let helpInformation = this.helpInformation(context);
3210
+ if (deprecatedCallback) {
3211
+ helpInformation = deprecatedCallback(helpInformation);
3212
+ if (typeof helpInformation !== 'string' && !Buffer.isBuffer(helpInformation)) {
3213
+ throw new Error('outputHelp callback must return a string or a Buffer');
3214
+ }
3215
+ }
3216
+ context.write(helpInformation);
3217
+
3218
+ if (this._getHelpOption()?.long) {
3219
+ this.emit(this._getHelpOption().long); // deprecated
3220
+ }
3221
+ this.emit('afterHelp', context);
3222
+ this._getCommandAndAncestors().forEach(command => command.emit('afterAllHelp', context));
3223
+ }
3224
+
3225
+ /**
3226
+ * You can pass in flags and a description to customise the built-in help option.
3227
+ * Pass in false to disable the built-in help option.
3228
+ *
3229
+ * @example
3230
+ * program.helpOption('-?, --help' 'show help'); // customise
3231
+ * program.helpOption(false); // disable
3232
+ *
3233
+ * @param {(string | boolean)} flags
3234
+ * @param {string} [description]
3235
+ * @return {Command} `this` command for chaining
3236
+ */
3237
+
3238
+ helpOption(flags, description) {
3239
+ // Support disabling built-in help option.
3240
+ if (typeof flags === 'boolean') {
3241
+ if (flags) {
3242
+ this._helpOption = this._helpOption ?? undefined; // preserve existing option
3243
+ } else {
3244
+ this._helpOption = null; // disable
3245
+ }
3246
+ return this;
3247
+ }
3248
+
3249
+ // Customise flags and description.
3250
+ flags = flags ?? '-h, --help';
3251
+ description = description ?? 'display help for command';
3252
+ this._helpOption = this.createOption(flags, description);
3253
+
3254
+ return this;
3255
+ }
3256
+
3257
+ /**
3258
+ * Lazy create help option.
3259
+ * Returns null if has been disabled with .helpOption(false).
3260
+ *
3261
+ * @returns {(Option | null)} the help option
3262
+ * @package internal use only
3263
+ */
3264
+ _getHelpOption() {
3265
+ // Lazy create help option on demand.
3266
+ if (this._helpOption === undefined) {
3267
+ this.helpOption(undefined, undefined);
3268
+ }
3269
+ return this._helpOption;
3270
+ }
3271
+
3272
+ /**
3273
+ * Supply your own option to use for the built-in help option.
3274
+ * This is an alternative to using helpOption() to customise the flags and description etc.
3275
+ *
3276
+ * @param {Option} option
3277
+ * @return {Command} `this` command for chaining
3278
+ */
3279
+ addHelpOption(option) {
3280
+ this._helpOption = option;
3281
+ return this;
3282
+ }
3283
+
3284
+ /**
3285
+ * Output help information and exit.
3286
+ *
3287
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
3288
+ *
3289
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
3290
+ */
3291
+
3292
+ help(contextOptions) {
3293
+ this.outputHelp(contextOptions);
3294
+ let exitCode = process$1.exitCode || 0;
3295
+ if (exitCode === 0 && contextOptions && typeof contextOptions !== 'function' && contextOptions.error) {
3296
+ exitCode = 1;
3297
+ }
3298
+ // message: do not have all displayed text available so only passing placeholder.
3299
+ this._exit(exitCode, 'commander.help', '(outputHelp)');
3300
+ }
3301
+
3302
+ /**
3303
+ * Add additional text to be displayed with the built-in help.
3304
+ *
3305
+ * Position is 'before' or 'after' to affect just this command,
3306
+ * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
3307
+ *
3308
+ * @param {string} position - before or after built-in help
3309
+ * @param {(string | Function)} text - string to add, or a function returning a string
3310
+ * @return {Command} `this` command for chaining
3311
+ */
3312
+ addHelpText(position, text) {
3313
+ const allowedValues = ['beforeAll', 'before', 'after', 'afterAll'];
3314
+ if (!allowedValues.includes(position)) {
3315
+ throw new Error(`Unexpected value for position to addHelpText.
3316
+ Expecting one of '${allowedValues.join("', '")}'`);
3317
+ }
3318
+ const helpEvent = `${position}Help`;
3319
+ this.on(helpEvent, (context) => {
3320
+ let helpStr;
3321
+ if (typeof text === 'function') {
3322
+ helpStr = text({ error: context.error, command: context.command });
3323
+ } else {
3324
+ helpStr = text;
3325
+ }
3326
+ // Ignore falsy value when nothing to output.
3327
+ if (helpStr) {
3328
+ context.write(`${helpStr}\n`);
3329
+ }
3330
+ });
3331
+ return this;
3332
+ }
3333
+
3334
+ /**
3335
+ * Output help information if help flags specified
3336
+ *
3337
+ * @param {Array} args - array of options to search for help flags
3338
+ * @private
3339
+ */
3340
+
3341
+ _outputHelpIfRequested(args) {
3342
+ const helpOption = this._getHelpOption();
3343
+ const helpRequested = helpOption && args.find(arg => helpOption.is(arg));
3344
+ if (helpRequested) {
3345
+ this.outputHelp();
3346
+ // (Do not have all displayed text available so only passing placeholder.)
3347
+ this._exit(0, 'commander.helpDisplayed', '(outputHelp)');
3348
+ }
3349
+ }
3350
+ };
3351
+
3352
+ /**
3353
+ * Scan arguments and increment port number for inspect calls (to avoid conflicts when spawning new command).
3354
+ *
3355
+ * @param {string[]} args - array of arguments from node.execArgv
3356
+ * @returns {string[]}
3357
+ * @private
3358
+ */
3359
+
3360
+ function incrementNodeInspectorPort(args) {
3361
+ // Testing for these options:
3362
+ // --inspect[=[host:]port]
3363
+ // --inspect-brk[=[host:]port]
3364
+ // --inspect-port=[host:]port
3365
+ return args.map((arg) => {
3366
+ if (!arg.startsWith('--inspect')) {
3367
+ return arg;
3368
+ }
3369
+ let debugOption;
3370
+ let debugHost = '127.0.0.1';
3371
+ let debugPort = '9229';
3372
+ let match;
3373
+ if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
3374
+ // e.g. --inspect
3375
+ debugOption = match[1];
3376
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
3377
+ debugOption = match[1];
3378
+ if (/^\d+$/.test(match[3])) {
3379
+ // e.g. --inspect=1234
3380
+ debugPort = match[3];
3381
+ } else {
3382
+ // e.g. --inspect=localhost
3383
+ debugHost = match[3];
3384
+ }
3385
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
3386
+ // e.g. --inspect=localhost:1234
3387
+ debugOption = match[1];
3388
+ debugHost = match[3];
3389
+ debugPort = match[4];
3390
+ }
3391
+
3392
+ if (debugOption && debugPort !== '0') {
3393
+ return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
3394
+ }
3395
+ return arg;
3396
+ });
3397
+ }
3398
+
3399
+ command.Command = Command$2;
3400
+
3401
+ const { Argument: Argument$1 } = argument;
3402
+ const { Command: Command$1 } = command;
3403
+ const { CommanderError: CommanderError$1, InvalidArgumentError: InvalidArgumentError$1 } = error;
3404
+ const { Help: Help$1 } = help;
3405
+ const { Option: Option$1 } = option;
3406
+
3407
+ commander.program = new Command$1();
3408
+
3409
+ commander.createCommand = (name) => new Command$1(name);
3410
+ commander.createOption = (flags, description) => new Option$1(flags, description);
3411
+ commander.createArgument = (name, description) => new Argument$1(name, description);
3412
+
3413
+ /**
3414
+ * Expose classes
3415
+ */
3416
+
3417
+ commander.Command = Command$1;
3418
+ commander.Option = Option$1;
3419
+ commander.Argument = Argument$1;
3420
+ commander.Help = Help$1;
3421
+
3422
+ commander.CommanderError = CommanderError$1;
3423
+ commander.InvalidArgumentError = InvalidArgumentError$1;
3424
+ commander.InvalidOptionArgumentError = InvalidArgumentError$1; // Deprecated
3425
+
3426
+ // wrapper to provide named exports for ESM.
3427
+ const {
3428
+ program: program$1,
3429
+ createCommand,
3430
+ createArgument,
3431
+ createOption,
3432
+ CommanderError,
3433
+ InvalidArgumentError,
3434
+ InvalidOptionArgumentError, // deprecated old name
3435
+ Command,
3436
+ Argument,
3437
+ Option,
3438
+ Help
3439
+ } = commander;
3440
+
3441
+ function genKey(b) {
3442
+ let _b;
3443
+ if (b != null)
3444
+ _b = b;
3445
+ else
3446
+ _b = crypto.randomBytes(32);
3447
+ return {
3448
+ get buffer() { return _b; },
3449
+ get phpString() {
3450
+ let s = '';
3451
+ for (let i = 0; i < _b.length; i++) {
3452
+ s += '\\0x' + _b[i].toString(16).padStart(2, '0');
3453
+ }
3454
+ return s;
3455
+ },
3456
+ get hex() {
3457
+ return _b.toString('hex');
3458
+ }
3459
+ };
3460
+ }
3461
+
3462
+ /**
3463
+ * Extrait la clé d'un fichier .env
3464
+ *
3465
+ * @param file
3466
+ * @param key
3467
+ */
3468
+ function extractKey(file, key) {
3469
+ if (!fs$1.existsSync(file))
3470
+ return null;
3471
+ const content = fs$1.readFileSync(file, 'utf-8');
3472
+ for (const l of content.split('\n')) {
3473
+ if (l.startsWith(key + '=')) {
3474
+ return Buffer.from(l.slice(key.length + 1), 'hex');
3475
+ }
3476
+ }
3477
+ return null;
3478
+ }
3479
+ /**
3480
+ * Ajoute ou modifie une clé à un fichier .env
3481
+ *
3482
+ * @param file
3483
+ * @param key
3484
+ * @param value
3485
+ */
3486
+ function addKey(file, key, value) {
3487
+ const line = `${key}=${value}`;
3488
+ let content = '';
3489
+ if (fs$1.existsSync(file)) {
3490
+ let existingContent = fs$1.readFileSync(file, 'utf-8');
3491
+ let trailingNewline = false;
3492
+ if (existingContent.endsWith('\n')) {
3493
+ trailingNewline = true;
3494
+ existingContent = existingContent.slice(0, -1);
3495
+ }
3496
+ let found = false;
3497
+ for (const l of existingContent.split('\n')) {
3498
+ if (l.startsWith(key + '=')) {
3499
+ if (!found) {
3500
+ content += line + '\n';
3501
+ found = true;
3502
+ }
3503
+ }
3504
+ else {
3505
+ content += l + '\n';
3506
+ }
3507
+ }
3508
+ if (found) {
3509
+ if (!trailingNewline)
3510
+ content = content.slice(0, -1);
3511
+ }
3512
+ else {
3513
+ content = line + '\n' + existingContent;
3514
+ }
3515
+ }
3516
+ else {
3517
+ content = line + '\n';
3518
+ }
3519
+ if (!fs$1.existsSync(require$$2.dirname(file)))
3520
+ fs$1.mkdirSync(require$$2.dirname(file), { recursive: true });
3521
+ fs$1.writeFileSync(file, content);
3522
+ }
3523
+
3524
+ /**
3525
+ * Crée un fichier .php
3526
+ *
3527
+ * @param file
3528
+ * @param key
3529
+ */
3530
+ function createPhpFile(file, key) {
3531
+ const content = `<?php
3532
+ // clef de signature
3533
+ return "${key}";`;
3534
+ if (!fs$1.existsSync(require$$2.dirname(file)))
3535
+ fs$1.mkdirSync(require$$2.dirname(file), { recursive: true });
3536
+ fs$1.writeFileSync(file, content);
3537
+ }
3538
+
3539
+ const program = new Command();
3540
+ program
3541
+ .version('0.0.1')
3542
+ .name('cactjs')
3543
+ .description('cactjs est l\'outil de ligne de commande pour @capytale/activity.js');
3544
+ program
3545
+ .command('generate-key')
3546
+ .alias('gk')
3547
+ .description('Génère une clé d\'API et l\'inscrit dans un fichier .env')
3548
+ .option('-f, --env-file <file>', 'Fichier dans lequel ajouter la clé', '.env')
3549
+ .option('-v, --var <var>', 'Nom de la variable à ajouter', 'CAPY_SIGN_KEY')
3550
+ .action((options) => {
3551
+ const key = genKey();
3552
+ const file = require$$2.resolve(process.cwd(), options.envFile);
3553
+ console.log('Génération de clé d\'API', key.hex);
3554
+ console.log('Ajout dans le fichier', file);
3555
+ addKey(file, options.var, key.hex);
3556
+ });
3557
+ program
3558
+ .command('generate-php')
3559
+ .alias('php')
3560
+ .description('Lit une clef d\'API dans un fichier .env et génère un fichier php pour l\'exporter')
3561
+ .option('-f, --env-file <file>', 'Fichier dans lequel lire la clé', '.env')
3562
+ .option('-v, --var <var>', 'Nom de la variable à lire', 'CAPY_SIGN_KEY')
3563
+ .option('-o, --output-file <file>', 'Fichier php à écrire', 'dist/key.php')
3564
+ .action((options) => {
3565
+ const file = require$$2.resolve(process.cwd(), options.envFile);
3566
+ const b = extractKey(file, options.var);
3567
+ if (b == null) {
3568
+ console.error('Impossible de lire la clé');
3569
+ process.exit(1);
3570
+ }
3571
+ const key = genKey(b);
3572
+ console.log('Lecture de la clé d\'API', key.hex);
3573
+ const outFile = require$$2.resolve(process.cwd(), options.outputFile);
3574
+ console.log('Ecriture dans le fichier', outFile);
3575
+ createPhpFile(outFile, key.phpString);
3576
+ });
3577
+ program.parse();