node-karin 1.7.13 → 1.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (302) hide show
  1. package/CHANGELOG.md +819 -751
  2. package/default/config/adapter.json +27 -27
  3. package/default/config/config.json +44 -44
  4. package/default/config/groups.json +66 -66
  5. package/default/config/pm2.json +15 -15
  6. package/default/config/privates.json +25 -25
  7. package/default/config/redis.json +5 -5
  8. package/default/config/render.json +18 -18
  9. package/dist/cli/index.cjs +1 -487
  10. package/dist/cli/index.mjs +4120 -0
  11. package/dist/cli/pm2.js +1 -1
  12. package/dist/global.d.d.ts +68 -0
  13. package/dist/index.d.ts +1962 -508
  14. package/dist/index.mjs +31566 -0
  15. package/dist/logger-DVUGuzNj.d.ts +101 -0
  16. package/dist/module/art-template.d.ts +12 -1
  17. package/dist/module/axios.d.ts +1 -1
  18. package/dist/module/chalk.d.ts +1 -1
  19. package/dist/module/chokidar.d.ts +1 -1
  20. package/dist/module/express.d.ts +2 -1
  21. package/dist/module/express.mjs +2 -0
  22. package/dist/module/lodash.d.ts +2 -1
  23. package/dist/module/{lodash.js → lodash.mjs} +1 -0
  24. package/dist/module/moment.d.ts +1 -1
  25. package/dist/module/node-schedule.d.ts +1 -1
  26. package/dist/module/redis.d.ts +1 -1
  27. package/dist/module/sqlite3.d.ts +1 -1
  28. package/dist/module/ws.d.ts +2 -1
  29. package/dist/module/ws.mjs +2 -0
  30. package/dist/module/yaml.d.ts +1 -1
  31. package/dist/root.d.ts +5 -1
  32. package/dist/{root.js → root.mjs} +3 -1
  33. package/dist/start/app.d.ts +1 -0
  34. package/dist/start/app.mjs +9 -0
  35. package/dist/start/index.d.ts +1 -0
  36. package/dist/start/index.mjs +102 -0
  37. package/dist/web/assets/css/components-ep7vm38G.css +1 -0
  38. package/dist/web/assets/css/index-DxLRZkvi.css.br +0 -0
  39. package/dist/web/assets/js/components-Bp80gYJA.js.br +0 -0
  40. package/dist/web/assets/js/entry-DhKjPdoJ.js.br +0 -0
  41. package/dist/web/assets/js/hooks-CSKAeqvP.js.br +0 -0
  42. package/dist/web/assets/js/page-404.tsx-Dr2zAhTf.js +1 -0
  43. package/dist/web/assets/js/page-dashboard-B6B4ob8B.js.br +0 -0
  44. package/dist/web/assets/js/page-loading.tsx-g_ta_NRr.js.br +0 -0
  45. package/dist/web/assets/js/page-login.tsx-Cm98Ubip.js.br +0 -0
  46. package/dist/web/assets/js/utils-Cj3xTboC.js +2 -0
  47. package/dist/web/assets/js/vendor-editor-B8hjWfkw.js.br +0 -0
  48. package/dist/web/assets/js/vendor-heroui-CMeNhCFh.js.br +0 -0
  49. package/dist/web/assets/js/vendor-others-Bv0hrdEA.js.br +0 -0
  50. package/dist/web/assets/js/vendor-react-ChUmQ3I2.js.br +0 -0
  51. package/dist/web/assets/js/vendor-ui-utils-5rYIvRjL.js.br +0 -0
  52. package/dist/web/assets/js/vendor-visual-CdiJEXnN.js.br +0 -0
  53. package/dist/web/{flUhRq6tzZclQEJ-Vdg-IuiaDsNc.woff2 → flUhRq6tzZclQEJ-Vdg-IuiaDsNc.woff2.br} +0 -0
  54. package/dist/web/grid.svg +5 -5
  55. package/dist/web/icon.css +24 -24
  56. package/dist/web/index.html +37 -24
  57. package/dist/web/karin.png.br +0 -0
  58. package/dist/web/monaco-editor/min/vs/base/browser/ui/codicons/codicon/codicon.ttf.br +0 -0
  59. package/dist/web/sha256.min.js.br +0 -0
  60. package/package.json +192 -201
  61. package/README.md +0 -32
  62. package/dist/cli/index.js +0 -479
  63. package/dist/index.js +0 -19515
  64. package/dist/module/art-template.cjs +0 -11
  65. package/dist/module/axios.cjs +0 -22
  66. package/dist/module/chalk.cjs +0 -22
  67. package/dist/module/chokidar.cjs +0 -22
  68. package/dist/module/dotenv.cjs +0 -22
  69. package/dist/module/dotenv.d.ts +0 -2
  70. package/dist/module/dotenv.js +0 -2
  71. package/dist/module/express.cjs +0 -36
  72. package/dist/module/express.js +0 -1
  73. package/dist/module/lodash.cjs +0 -11
  74. package/dist/module/log4js.cjs +0 -22
  75. package/dist/module/log4js.d.ts +0 -2
  76. package/dist/module/log4js.js +0 -2
  77. package/dist/module/moment.cjs +0 -11
  78. package/dist/module/node-schedule.cjs +0 -22
  79. package/dist/module/redis.cjs +0 -22
  80. package/dist/module/sqlite3.cjs +0 -22
  81. package/dist/module/ws.cjs +0 -28
  82. package/dist/module/ws.js +0 -1
  83. package/dist/module/yaml.cjs +0 -22
  84. package/dist/web/assets/404-C9u_NlJi.js +0 -1
  85. package/dist/web/assets/Item-pd96GKIG.js.br +0 -0
  86. package/dist/web/assets/SelectionManager-BlXTH2VC.js.br +0 -0
  87. package/dist/web/assets/abap-BrgZPUOV.js.br +0 -0
  88. package/dist/web/assets/about-BwlDpX-c.js.br +0 -0
  89. package/dist/web/assets/accordion-Bj06RlD-.js.br +0 -0
  90. package/dist/web/assets/adapter-Du42CYBT.js.br +0 -0
  91. package/dist/web/assets/addon-web-links-Wrx0dCGl.js.br +0 -0
  92. package/dist/web/assets/apex-DyP6w7ZV.js.br +0 -0
  93. package/dist/web/assets/azcli-BaLxmfj-.js.br +0 -0
  94. package/dist/web/assets/bat-CFOPXBzS.js.br +0 -0
  95. package/dist/web/assets/bicep-BfEKNvv3.js.br +0 -0
  96. package/dist/web/assets/bot-DdYIqTVP.js +0 -6
  97. package/dist/web/assets/cameligo-BFG1Mk7z.js.br +0 -0
  98. package/dist/web/assets/chunk-2C6KNKEU-CBJmVWyn.js.br +0 -0
  99. package/dist/web/assets/chunk-2QAN2V2R-BulY1jfw.js.br +0 -0
  100. package/dist/web/assets/chunk-3TCFMHK3-BpJf4Q9f.js.br +0 -0
  101. package/dist/web/assets/chunk-4EXC76WE-DWVJR0TX.js.br +0 -0
  102. package/dist/web/assets/chunk-6JWJ7CFW-BDAlVmIQ.js.br +0 -0
  103. package/dist/web/assets/chunk-6NGXL2PC-DIPEMSmA.js.br +0 -0
  104. package/dist/web/assets/chunk-6VC6TS2O-sjq9IySl.js.br +0 -0
  105. package/dist/web/assets/chunk-736YWA4T-BK_z11TK.js.br +0 -0
  106. package/dist/web/assets/chunk-A6PX3NG3-BsGR2bWZ.js.br +0 -0
  107. package/dist/web/assets/chunk-B75B6XQK-B0VUBvt8.js +0 -1
  108. package/dist/web/assets/chunk-BWXGEJBS-DvCShJym.js.br +0 -0
  109. package/dist/web/assets/chunk-D5XJWRAV-9uH2CwV1.js +0 -1
  110. package/dist/web/assets/chunk-HAJUSXOG-6BFBENy1.js.br +0 -0
  111. package/dist/web/assets/chunk-IHO36JMK-DKnKLDmu.js.br +0 -0
  112. package/dist/web/assets/chunk-J6JGI6RM-DKmnXtnU.js.br +0 -0
  113. package/dist/web/assets/chunk-J7I6W5JF-IqR8CF_Q.js.br +0 -0
  114. package/dist/web/assets/chunk-KCYYJJH4-BdofC4qA.js.br +0 -0
  115. package/dist/web/assets/chunk-KHLLQ6W4-CpyZzH4q.js.br +0 -0
  116. package/dist/web/assets/chunk-KQ5CH2X7-MWuUq5gI.js.br +0 -0
  117. package/dist/web/assets/chunk-LAX3QLKM-B0tE0BjZ.js +0 -1
  118. package/dist/web/assets/chunk-LGSBTEIA--Gvr91gm.js +0 -1
  119. package/dist/web/assets/chunk-M3MASYO7-BVjxibqV.js +0 -1
  120. package/dist/web/assets/chunk-ML27DD5T-BjYAog8d.js.br +0 -0
  121. package/dist/web/assets/chunk-MSDKUXDP-DKkJKxM-.js.br +0 -0
  122. package/dist/web/assets/chunk-MW56SEHC-CTlcS-O4.js.br +0 -0
  123. package/dist/web/assets/chunk-MZRCPRP2-BBG21hp8.js.br +0 -0
  124. package/dist/web/assets/chunk-OH2E76JR-BYurMayl.js +0 -1
  125. package/dist/web/assets/chunk-OTWYT2HS-cQ8QQNDY.js +0 -1
  126. package/dist/web/assets/chunk-RRTOIK23-CSPsT46O.js.br +0 -0
  127. package/dist/web/assets/chunk-SLABUSGS-s9w3Zt5w.js.br +0 -0
  128. package/dist/web/assets/chunk-TE6SZS6W-1UK_YAGg.js +0 -1
  129. package/dist/web/assets/chunk-UX7UMZL5-DHf8C-o1.js +0 -1
  130. package/dist/web/assets/chunk-WQVQ7P2I-C4kbg9VI.js.br +0 -0
  131. package/dist/web/assets/clojure-DTECt2xU.js.br +0 -0
  132. package/dist/web/assets/codicon-DCmgc-ay.ttf +0 -0
  133. package/dist/web/assets/coffee-CDGzqUPQ.js.br +0 -0
  134. package/dist/web/assets/config-CEElyPBT.js.br +0 -0
  135. package/dist/web/assets/config-DVn1FaJ-.js.br +0 -0
  136. package/dist/web/assets/cpp-CLLBncYj.js.br +0 -0
  137. package/dist/web/assets/csharp-dUCx_-0o.js.br +0 -0
  138. package/dist/web/assets/csp-5Rap-vPy.js.br +0 -3
  139. package/dist/web/assets/css-D3h14YRZ.js.br +0 -0
  140. package/dist/web/assets/cssMode-CXyVPoom.js.br +0 -0
  141. package/dist/web/assets/cypher-DrQuvNYM.js.br +0 -0
  142. package/dist/web/assets/dart-CFKIUWau.js.br +0 -0
  143. package/dist/web/assets/default_page-BKgpdS-e.js +0 -1
  144. package/dist/web/assets/detail-C5769b6q.js.br +0 -0
  145. package/dist/web/assets/detail-COuw3J9r.js.br +0 -0
  146. package/dist/web/assets/detail-DqW0R8N9.css.br +0 -0
  147. package/dist/web/assets/dockerfile-Zznr-cwX.js.br +0 -0
  148. package/dist/web/assets/ecl-Ce3n6wWz.js.br +0 -0
  149. package/dist/web/assets/editor.worker-oRlJJsnX.js.br +0 -0
  150. package/dist/web/assets/elixir-deUWdS0T.js.br +0 -0
  151. package/dist/web/assets/env-CSYJHsPf.js.br +0 -0
  152. package/dist/web/assets/eye-DEh2Pgsu.js +0 -6
  153. package/dist/web/assets/features-animation-F-pzovue.js +0 -1
  154. package/dist/web/assets/flow9-i9-g7ZhI.js.br +0 -0
  155. package/dist/web/assets/focusSafely-DOspV_xj.js.br +0 -0
  156. package/dist/web/assets/freemarker2-BV0OzS9F.js.br +0 -0
  157. package/dist/web/assets/friend_request-DfiA7sPM.js.br +0 -0
  158. package/dist/web/assets/fsharp-CzKuDChf.js.br +0 -0
  159. package/dist/web/assets/github-nVmhSG0k.js +0 -11
  160. package/dist/web/assets/go-Cphgjts3.js.br +0 -0
  161. package/dist/web/assets/graphql-Cg7bfA9N.js.br +0 -0
  162. package/dist/web/assets/group-CfWIxZ1S.js.br +0 -0
  163. package/dist/web/assets/group_notice-XufgXVhG.js +0 -1
  164. package/dist/web/assets/handlebars-DSMVNR0n.js.br +0 -0
  165. package/dist/web/assets/hcl-0cvrggvQ.js.br +0 -0
  166. package/dist/web/assets/html-ClQau7kT.js.br +0 -0
  167. package/dist/web/assets/htmlMode-CN2HUcKJ.js.br +0 -0
  168. package/dist/web/assets/iconBase-BbDMq9Lm.js.br +0 -0
  169. package/dist/web/assets/index-B2KKfeyN.js.br +0 -0
  170. package/dist/web/assets/index-B59L0CDQ.js.br +0 -0
  171. package/dist/web/assets/index-BRJPOEf0.js.br +0 -0
  172. package/dist/web/assets/index-BSQ_9cWz.js.br +0 -0
  173. package/dist/web/assets/index-BTn745-y.js.br +0 -0
  174. package/dist/web/assets/index-Bl5YOuTR.js.br +0 -0
  175. package/dist/web/assets/index-Bm-03b92.js +0 -1
  176. package/dist/web/assets/index-CNKcljeW.js +0 -1
  177. package/dist/web/assets/index-CSkzWqtN.js.br +0 -0
  178. package/dist/web/assets/index-CY-NVVkv.js.br +0 -0
  179. package/dist/web/assets/index-CeBvj3ZH.js.br +0 -0
  180. package/dist/web/assets/index-CnkVaH2P.css.br +0 -0
  181. package/dist/web/assets/index-DCzNSkJn.js.br +0 -0
  182. package/dist/web/assets/index-DNKbYZlM.js +0 -1
  183. package/dist/web/assets/index-DVsvetQP.js.br +0 -0
  184. package/dist/web/assets/index-D_816BTl.js.br +0 -0
  185. package/dist/web/assets/index-Db1iHKoe.js.br +0 -0
  186. package/dist/web/assets/index-DjU-NtVQ.js +0 -1
  187. package/dist/web/assets/index-Drqc4ASm.js.br +0 -0
  188. package/dist/web/assets/index-DvwfI5vP.css.br +0 -0
  189. package/dist/web/assets/index-Dwnb7Xtz.js.br +0 -0
  190. package/dist/web/assets/index-EGWrH2j2.js +0 -1
  191. package/dist/web/assets/index-IUy6p99y.js +0 -1
  192. package/dist/web/assets/index-k_Cd4_SW.js.br +0 -0
  193. package/dist/web/assets/index-nZMp9MWB.js.br +0 -0
  194. package/dist/web/assets/index.esm-BSKygSH-.js.br +0 -0
  195. package/dist/web/assets/ini-Drc7WvVn.js.br +0 -0
  196. package/dist/web/assets/inputGroup-CJGuoYUx.js.br +0 -0
  197. package/dist/web/assets/isSymbol-BShv9ove.js.br +0 -0
  198. package/dist/web/assets/java-B_fMsGYe.js.br +0 -0
  199. package/dist/web/assets/javascript-BegoFNre.js.br +0 -0
  200. package/dist/web/assets/jsonMode-Dxf_RJRO.js.br +0 -0
  201. package/dist/web/assets/julia-Bqgm2twL.js.br +0 -0
  202. package/dist/web/assets/kotlin-BSkB5QuD.js.br +0 -0
  203. package/dist/web/assets/layout-al9rnD7b.js.br +0 -0
  204. package/dist/web/assets/less-BsTHnhdd.js.br +0 -0
  205. package/dist/web/assets/lexon-YWi4-JPR.js.br +0 -0
  206. package/dist/web/assets/liquid-bFSovgkX.js.br +0 -0
  207. package/dist/web/assets/loading-Czh_ivNv.js.br +0 -0
  208. package/dist/web/assets/login-DpjAzjKU.js.br +0 -0
  209. package/dist/web/assets/lua-nf6ki56Z.js.br +0 -0
  210. package/dist/web/assets/m3-Cpb6xl2v.js.br +0 -0
  211. package/dist/web/assets/markdown-DSZPf7rp.js.br +0 -0
  212. package/dist/web/assets/mdx-DGviX4hR.js.br +0 -0
  213. package/dist/web/assets/merge-CuVThMNe.js.br +0 -0
  214. package/dist/web/assets/mergeRefs-BpO9bzld.js +0 -1
  215. package/dist/web/assets/message-mTjTgeaM.js +0 -1
  216. package/dist/web/assets/message.model-B1qK1MiE.js.br +0 -0
  217. package/dist/web/assets/mips-B_c3zf-v.js.br +0 -0
  218. package/dist/web/assets/msdax-rUNN04Wq.js.br +0 -0
  219. package/dist/web/assets/mysql-DDwshQtU.js.br +0 -0
  220. package/dist/web/assets/number-7W8NeZVk.js.br +0 -0
  221. package/dist/web/assets/objective-c-B5zXfXm9.js.br +0 -0
  222. package/dist/web/assets/pascal-CXOwvkN_.js.br +0 -0
  223. package/dist/web/assets/pascaligo-Bc-ZgV77.js.br +0 -0
  224. package/dist/web/assets/perl-CwNk8-XU.js.br +0 -0
  225. package/dist/web/assets/pgsql-tGk8EFnU.js.br +0 -0
  226. package/dist/web/assets/php-CpIb_Oan.js.br +0 -0
  227. package/dist/web/assets/pla-B03wrqEc.js.br +0 -0
  228. package/dist/web/assets/pm2-CniXkaeu.js.br +0 -0
  229. package/dist/web/assets/postiats-BKlk5iyT.js.br +0 -0
  230. package/dist/web/assets/powerquery-Bhzvs7bI.js.br +0 -0
  231. package/dist/web/assets/powershell-Dd3NCNK9.js.br +0 -0
  232. package/dist/web/assets/private-CfG8JI8L.js.br +0 -0
  233. package/dist/web/assets/protobuf-COyEY5Pt.js.br +0 -0
  234. package/dist/web/assets/pug-BaJupSGV.js.br +0 -0
  235. package/dist/web/assets/python-D0ZD_k1N.js.br +0 -0
  236. package/dist/web/assets/qsharp-DXyYeYxl.js.br +0 -0
  237. package/dist/web/assets/r-CdQndTaG.js.br +0 -0
  238. package/dist/web/assets/razor-DRYiVyDt.js.br +0 -0
  239. package/dist/web/assets/react-resizable-panels.browser.esm-DubqLJ4h.js.br +0 -0
  240. package/dist/web/assets/redis-BJLUr1tG.js.br +0 -0
  241. package/dist/web/assets/redis-CVwtpugi.js.br +0 -0
  242. package/dist/web/assets/redshift-25W9uPmb.js.br +0 -0
  243. package/dist/web/assets/render-DEylqIUg.js.br +0 -0
  244. package/dist/web/assets/restructuredtext-DfzH4Xui.js.br +0 -0
  245. package/dist/web/assets/router-D_dYaqfK.js +0 -1
  246. package/dist/web/assets/ruby-Cp1zYvxS.js.br +0 -0
  247. package/dist/web/assets/rust-D5C2fndG.js.br +0 -0
  248. package/dist/web/assets/save-D6wQsuGT.js +0 -1
  249. package/dist/web/assets/sb-CDntyWJ8.js.br +0 -0
  250. package/dist/web/assets/scala-BoFRg7Ot.js.br +0 -0
  251. package/dist/web/assets/scheme-Bio4gycK.js.br +0 -0
  252. package/dist/web/assets/scss-4Ik7cdeQ.js.br +0 -0
  253. package/dist/web/assets/server-CRdhk2Wy.js.br +0 -0
  254. package/dist/web/assets/shell-CX-rkNHf.js.br +0 -0
  255. package/dist/web/assets/solidity-Tw7wswEv.js.br +0 -0
  256. package/dist/web/assets/sophia-C5WLch3f.js.br +0 -0
  257. package/dist/web/assets/sparql-DHaeiCBh.js.br +0 -0
  258. package/dist/web/assets/sql-CCSDG5nI.js.br +0 -0
  259. package/dist/web/assets/st-pnP8ivHi.js.br +0 -0
  260. package/dist/web/assets/swift-DwJ7jVG9.js.br +0 -0
  261. package/dist/web/assets/systemverilog-B9Xyijhd.js.br +0 -0
  262. package/dist/web/assets/tcl-DnHyzjbg.js.br +0 -0
  263. package/dist/web/assets/terminal-CfCQe79-.js +0 -6
  264. package/dist/web/assets/terminal-bNIVjrPM.js.br +0 -0
  265. package/dist/web/assets/test-url-CZXnW7jp.js.br +0 -0
  266. package/dist/web/assets/theme-switch-Bz2l2CwF.js.br +0 -0
  267. package/dist/web/assets/ts.worker-Bd4z-OY3.js.br +0 -0
  268. package/dist/web/assets/tsMode-DKGjerkd.js.br +0 -0
  269. package/dist/web/assets/twig-CPajHgWi.js.br +0 -0
  270. package/dist/web/assets/typescript-CsEXAEHs.js.br +0 -0
  271. package/dist/web/assets/typespec-D-MeaMDU.js.br +0 -0
  272. package/dist/web/assets/use-dialog-BrR6Szrb.js +0 -1
  273. package/dist/web/assets/useEvent-DaW3_jZI.js +0 -1
  274. package/dist/web/assets/useFocusable-CtLTcLFV.js.br +0 -0
  275. package/dist/web/assets/useFormReset-CBBc4OFV.js +0 -1
  276. package/dist/web/assets/useHover-NCfDbwX0.js.br +0 -0
  277. package/dist/web/assets/useKeyboard-BZ4YtCxw.js +0 -1
  278. package/dist/web/assets/useLabel-DBycc4Nu.js +0 -1
  279. package/dist/web/assets/useNumberFormatter-DhAgwXM6.js.br +0 -0
  280. package/dist/web/assets/useRequest-BWEdMIz7.js.br +0 -0
  281. package/dist/web/assets/useToggle-Wuq-KqyX.js.br +0 -0
  282. package/dist/web/assets/users-_IqQqJDb.js +0 -11
  283. package/dist/web/assets/vb-DgyLZaXg.js.br +0 -0
  284. package/dist/web/assets/video_insert-Bj2IxuYI.js.br +0 -0
  285. package/dist/web/assets/webui-B6dfxJX4.js.br +0 -0
  286. package/dist/web/assets/wgsl-BIv9DU6q.js.br +0 -0
  287. package/dist/web/assets/xml-BHQFK9Jh.js.br +0 -0
  288. package/dist/web/assets/yaml-2He2eI3V.js.br +0 -0
  289. package/dist/web/karin.png +0 -0
  290. package/dist/web/monaco-editor/min/vs/base/browser/ui/codicons/codicon/codicon.ttf +0 -0
  291. /package/dist/module/{art-template.js → art-template.mjs} +0 -0
  292. /package/dist/module/{axios.js → axios.mjs} +0 -0
  293. /package/dist/module/{chalk.js → chalk.mjs} +0 -0
  294. /package/dist/module/{chokidar.js → chokidar.mjs} +0 -0
  295. /package/dist/module/{moment.js → moment.mjs} +0 -0
  296. /package/dist/module/{node-schedule.js → node-schedule.mjs} +0 -0
  297. /package/dist/module/{redis.js → redis.mjs} +0 -0
  298. /package/dist/module/{sqlite3.js → sqlite3.mjs} +0 -0
  299. /package/dist/module/{yaml.js → yaml.mjs} +0 -0
  300. /package/dist/web/assets/{addon-web-links-CFbL2ovg.css.br → css/vendor-editor-CFbL2ovg.css.br} +0 -0
  301. /package/dist/web/assets/{index-ZgkIHsf0.css → css/vendor-others-ZgkIHsf0.css} +0 -0
  302. /package/dist/web/assets/{favicon-BoqZd694.ico → ico/favicon-BoqZd694.ico} +0 -0
@@ -0,0 +1,4120 @@
1
+ #!/usr/bin/env node
2
+ import fs, { createReadStream, createWriteStream } from "node:fs";
3
+ import { fileURLToPath, URL as URL$1, pathToFileURL } from "node:url";
4
+ import path, { join } from "node:path";
5
+ import require$$1, { execSync as execSync$1, exec as exec$2, spawn } from "node:child_process";
6
+ import { pipeline } from "node:stream/promises";
7
+ import require$$0 from "node:events";
8
+ import require$$4 from "node:process";
9
+ const execSync = (cmd, options = {}) => {
10
+ try {
11
+ const result = execSync$1(cmd, options);
12
+ return { status: true, error: null, stdout: result.toString(), stderr: "" };
13
+ } catch (error2) {
14
+ return { status: false, error: error2, stdout: "", stderr: "" };
15
+ }
16
+ };
17
+ const exec$1 = (cmd, options = {}) => {
18
+ return new Promise((resolve) => {
19
+ exec$2(cmd, options, (error2, stdout, stderr) => {
20
+ const status = !error2;
21
+ resolve({ status, error: error2, stdout, stderr });
22
+ });
23
+ });
24
+ };
25
+ const pm2Dir = path.join(process.cwd(), "@karinjs/config/pm2.json");
26
+ const readPm2Config = () => {
27
+ if (!fs.existsSync(pm2Dir)) {
28
+ console.log(`[pm2] 配置文件不存在 请检查 ${pm2Dir} 是否存在`);
29
+ return null;
30
+ }
31
+ return JSON.parse(fs.readFileSync(pm2Dir, "utf-8"));
32
+ };
33
+ const ensureLogDir = (dirPath) => {
34
+ if (!fs.existsSync(dirPath)) {
35
+ fs.mkdirSync(dirPath, { recursive: true });
36
+ console.log(`[pm2] 创建日志目录: ${dirPath}`);
37
+ return true;
38
+ }
39
+ return false;
40
+ };
41
+ const rotateLogFile = async (logPath, logDirPath, logType, maxSizeMB) => {
42
+ if (!fs.existsSync(logPath)) return false;
43
+ const stats = fs.statSync(logPath);
44
+ const maxSizeBytes = maxSizeMB * 1024 * 1024;
45
+ if (stats.size < maxSizeBytes) return false;
46
+ const fileName = path.basename(logPath);
47
+ const timestamp = Date.now();
48
+ const archivedName = `${fileName}.${timestamp}`;
49
+ const archivedPath = path.join(logDirPath, archivedName);
50
+ const tempPath = path.join(logDirPath, `${fileName}.temp`);
51
+ try {
52
+ const sourceStream = createReadStream(logPath);
53
+ const destStream = createWriteStream(archivedPath);
54
+ await pipeline(sourceStream, destStream);
55
+ const originalMode = fs.statSync(logPath).mode;
56
+ fs.writeFileSync(tempPath, "");
57
+ fs.chmodSync(tempPath, originalMode);
58
+ fs.renameSync(tempPath, logPath);
59
+ console.log(`[pm2] 日志已按大小切割: ${logType} => ${archivedName} (${(stats.size / 1024 / 1024).toFixed(2)}MB)`);
60
+ return true;
61
+ } catch (err) {
62
+ console.error(`[pm2] 切割日志失败: ${logType}`, err);
63
+ if (fs.existsSync(tempPath)) {
64
+ fs.unlinkSync(tempPath);
65
+ }
66
+ return false;
67
+ }
68
+ };
69
+ const cleanupLogFiles = (errorLogBaseName, outLogBaseName, logDirPath, maxLogFiles) => {
70
+ if (maxLogFiles <= 0) return;
71
+ const files = fs.readdirSync(logDirPath);
72
+ const cleanupByLogType = (baseName, logType) => {
73
+ const filePattern = new RegExp(`^${baseName.replace(/\./g, "\\.")}\\.(\\d+)$`);
74
+ const logFiles = files.filter((file) => filePattern.test(file)).map((file) => {
75
+ const match = file.match(filePattern);
76
+ return {
77
+ file,
78
+ timestamp: match ? parseInt(match[1], 10) : 0
79
+ };
80
+ }).sort((a, b) => b.timestamp - a.timestamp);
81
+ if (logFiles.length > maxLogFiles) {
82
+ logFiles.slice(maxLogFiles).forEach((item) => {
83
+ const filePath = path.join(logDirPath, item.file);
84
+ fs.unlinkSync(filePath);
85
+ console.log(`[pm2] 删除过期${logType}日志: ${item.file}`);
86
+ });
87
+ }
88
+ };
89
+ cleanupByLogType(errorLogBaseName, "错误");
90
+ cleanupByLogType(outLogBaseName, "输出");
91
+ };
92
+ const rotateLogs = async () => {
93
+ const config = readPm2Config();
94
+ if (!config) return;
95
+ try {
96
+ const maxLogFiles = Number(config.maxLogFiles) ?? 10;
97
+ const maxErrorLogSize = Number(config.maxErrorLogSize) ?? 50;
98
+ const maxOutLogSize = Number(config.maxOutLogSize) ?? 50;
99
+ if (maxLogFiles === 0) {
100
+ return;
101
+ }
102
+ const errorLogPath = path.resolve(process.cwd(), config.apps[0].error_file);
103
+ const outLogPath = path.resolve(process.cwd(), config.apps[0].out_file);
104
+ const logDirPath = path.dirname(errorLogPath);
105
+ if (ensureLogDir(logDirPath)) return;
106
+ const errorLogBaseName = path.basename(errorLogPath);
107
+ const outLogBaseName = path.basename(outLogPath);
108
+ await rotateLogFile(outLogPath, logDirPath, "输出", maxOutLogSize);
109
+ await rotateLogFile(errorLogPath, logDirPath, "错误", maxErrorLogSize);
110
+ cleanupLogFiles(errorLogBaseName, outLogBaseName, logDirPath, maxLogFiles);
111
+ } catch (error2) {
112
+ console.error("[pm2] 日志切割过程中发生错误:", error2);
113
+ }
114
+ };
115
+ const upgradeScriptPath = (config) => {
116
+ const script = "index.mjs";
117
+ if (config.apps[0].script !== script) {
118
+ config.apps[0].script = script;
119
+ fs.writeFileSync(pm2Dir, JSON.stringify(config, null, 2));
120
+ }
121
+ };
122
+ const checkInitialization = () => {
123
+ const script = "index.mjs";
124
+ if (!fs.existsSync(script)) {
125
+ console.log("正在升级到1.8.0版本...");
126
+ execSync("npx ki init", { cwd: process.cwd() });
127
+ console.log("升级成功 正在启动pm2服务...");
128
+ }
129
+ };
130
+ const start$1 = async () => {
131
+ rotateLogs();
132
+ console.log("[pm2] 启动中...");
133
+ const config = readPm2Config();
134
+ if (!config) {
135
+ process.exit(1);
136
+ }
137
+ upgradeScriptPath(config);
138
+ checkInitialization();
139
+ const { error: error2 } = execSync(`pm2 start ${pm2Dir}`, { cwd: process.cwd() });
140
+ if (error2) {
141
+ console.log("[pm2] 启动失败");
142
+ console.log(error2);
143
+ process.exit(1);
144
+ }
145
+ console.log("[pm2] 启动成功");
146
+ console.log("[pm2] 重启服务: pnpm rs");
147
+ console.log("[pm2] 查看日志: pnpm log");
148
+ console.log("[pm2] 停止服务: pnpm stop");
149
+ console.log("[pm2] 查看监控: pm2 monit");
150
+ console.log("[pm2] 查看列表: pm2 list");
151
+ process.exit(0);
152
+ };
153
+ const log = async () => {
154
+ rotateLogs();
155
+ const config = readPm2Config();
156
+ if (!config) {
157
+ console.log("[pm2] 如果是新项目,请先前台启动生成配置文件: pnpm app");
158
+ process.exit(1);
159
+ }
160
+ try {
161
+ const prefix = process.platform === "win32" ? "pm2.cmd" : "pm2";
162
+ spawn(prefix, ["logs", config.apps[0].name, "--lines", config.lines || 1e3], { stdio: "inherit", shell: true });
163
+ } catch (error2) {
164
+ console.error("[pm2] 发生未知错误: 请检查pm2是否安装 【npm install -g pm2】");
165
+ console.error(error2);
166
+ process.exit(1);
167
+ }
168
+ };
169
+ const stop = async () => {
170
+ rotateLogs();
171
+ const config = readPm2Config();
172
+ if (!config) {
173
+ console.log("[pm2] 如果是新项目,请先前台启动生成配置文件: pnpm app");
174
+ process.exit(1);
175
+ }
176
+ execSync(`pm2 stop ${config.apps[0].name}`, { cwd: process.cwd() });
177
+ console.log("[pm2] 停止成功");
178
+ process.exit(0);
179
+ };
180
+ const restart = async (force) => {
181
+ rotateLogs();
182
+ console.log("[pm2] 重启中...");
183
+ if (!fs.existsSync(pm2Dir) && !force) {
184
+ console.log(`[pm2] 配置文件不存在 请检查 ${pm2Dir} 是否存在`);
185
+ console.log("[pm2] 如果是新项目,请先前台启动生成配置文件: pnpm app");
186
+ process.exit(1);
187
+ }
188
+ const appName = force ? "karin" : readPm2Config()?.apps[0].name;
189
+ if (!appName) {
190
+ process.exit(1);
191
+ }
192
+ execSync(`pm2 delete ${appName}`, { cwd: process.cwd() });
193
+ execSync(`pm2 start ${pm2Dir}`, { cwd: process.cwd() });
194
+ console.log("[pm2] 重启成功");
195
+ process.exit(0);
196
+ };
197
+ const pm2 = {
198
+ start: start$1,
199
+ log,
200
+ stop,
201
+ restart
202
+ };
203
+ const getIsDev = (dir) => {
204
+ if (process.env.NODE_ENV === "development") {
205
+ return true;
206
+ }
207
+ const list = [
208
+ "src",
209
+ "tsconfig.json",
210
+ "eslint.config.mjs",
211
+ "eslint.config.js",
212
+ ".prettierrc",
213
+ "vite.config.ts",
214
+ "tsup.config.ts"
215
+ ];
216
+ return list.some((item) => fs.existsSync(path.join(dir, item)));
217
+ };
218
+ const removeDirectory = (dirPath) => {
219
+ if (fs.existsSync(dirPath)) {
220
+ fs.rmSync(dirPath, { recursive: true, force: true });
221
+ }
222
+ };
223
+ const createDir = (isDev, dir) => {
224
+ const list = [
225
+ "logs",
226
+ "config",
227
+ "data",
228
+ "resource",
229
+ "temp/console",
230
+ "temp/html"
231
+ ];
232
+ list.forEach((item) => {
233
+ const dirPath = path.join(dir, "@karinjs", item);
234
+ if (!fs.existsSync(dirPath)) {
235
+ fs.mkdirSync(dirPath, { recursive: true });
236
+ }
237
+ });
238
+ if (isDev) return;
239
+ const example = path.join(dir, "plugins", "karin-plugin-example");
240
+ if (!fs.existsSync(example)) {
241
+ fs.mkdirSync(example, { recursive: true });
242
+ }
243
+ };
244
+ const npmrc = (dir) => {
245
+ const list = [
246
+ "package-lock=false",
247
+ "public-hoist-pattern[]=*sqlite3*",
248
+ "public-hoist-pattern[]=*express*",
249
+ "sqlite3_binary_host_mirror=https://registry.npmmirror.com/-/binary/sqlite3",
250
+ "node_sqlite3_binary_host_mirror=https://registry.npmmirror.com/-/binary/sqlite3",
251
+ "better_sqlite3_binary_host_mirror=https://registry.npmmirror.com/-/binary/better-sqlite3",
252
+ "sass_binary_site=https://registry.npmmirror.com/-/binary/node-sass",
253
+ "sharp_binary_host=https://registry.npmmirror.com/-/binary/sharp",
254
+ "sharp_libvips_binary_host=https://registry.npmmirror.com/-/binary/sharp-libvips",
255
+ "canvas_binary_host_mirror=https://registry.npmmirror.com/-/binary/canvas",
256
+ "# 19以下版本",
257
+ "puppeteer_download_host=https://registry.npmmirror.com/mirrors",
258
+ "# 20以上版本",
259
+ "PUPPETEER_DOWNLOAD_BASE_URL = https://registry.npmmirror.com/binaries/chrome-for-testing"
260
+ ];
261
+ const npmrc2 = path.join(dir, ".npmrc");
262
+ if (!fs.existsSync(npmrc2)) {
263
+ fs.writeFileSync(npmrc2, list.join("\n"));
264
+ return;
265
+ }
266
+ const data = fs.readFileSync(npmrc2, "utf-8");
267
+ const dataLines = data.split("\n").map((line) => line.trim());
268
+ const newEntries = list.filter((item) => {
269
+ if (item.startsWith("public-hoist-pattern[]=")) {
270
+ return !dataLines.includes(item);
271
+ }
272
+ const key = item.split("=")[0];
273
+ return !data.includes(key);
274
+ });
275
+ if (newEntries.length > 0) {
276
+ fs.appendFileSync(npmrc2, "\n" + newEntries.join("\n"));
277
+ }
278
+ };
279
+ const pnpmfile = (isDev, dir) => {
280
+ if (isDev) return;
281
+ const pnpmfile2 = path.join(dir, ".pnpmfile.cjs");
282
+ if (fs.existsSync(pnpmfile2)) return;
283
+ const content = [
284
+ "// 清空对等依赖中的node-karin",
285
+ "function readPackage (pkg, context) {",
286
+ " if (pkg?.['peerDependencies']?.['node-karin'] && pkg['peerDependencies']['node-karin'] !== 'file:./lib') {",
287
+ " delete pkg['peerDependencies']['node-karin']",
288
+ " }",
289
+ " return pkg",
290
+ "}",
291
+ "module.exports = {",
292
+ " hooks: {",
293
+ " readPackage",
294
+ " },",
295
+ "}"
296
+ ].join("\n");
297
+ fs.writeFileSync(pnpmfile2, content);
298
+ };
299
+ const createOrUpdateEnv = (dir) => {
300
+ const generateRandomKey = (type) => {
301
+ if (type === "http" && process.env.HTTP_AUTH_KEY) {
302
+ return process.env.HTTP_AUTH_KEY;
303
+ }
304
+ if (type === "ws" && process.env.WS_SERVER_AUTH_KEY) {
305
+ return process.env.WS_SERVER_AUTH_KEY;
306
+ }
307
+ const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
308
+ return Array.from({ length: 6 }, () => {
309
+ return chars.charAt(Math.floor(Math.random() * chars.length));
310
+ }).join("");
311
+ };
312
+ const envData = [
313
+ "# 是否启用HTTP",
314
+ "HTTP_ENABLE=true",
315
+ "# HTTP监听端口",
316
+ "HTTP_PORT=7777",
317
+ "# HTTP监听地址",
318
+ "HTTP_HOST=0.0.0.0",
319
+ "# HTTP鉴权秘钥 仅用于karin自身Api",
320
+ `HTTP_AUTH_KEY=${generateRandomKey("http")}`,
321
+ "# ws_server鉴权秘钥",
322
+ `WS_SERVER_AUTH_KEY=${generateRandomKey("ws")}`,
323
+ "\n",
324
+ "# 是否启用Redis 关闭后将使用内部虚拟Redis",
325
+ "REDIS_ENABLE=true",
326
+ "# 重启是否调用pm2 如果不调用则会直接关机 此配置适合有进程守护的程序",
327
+ "PM2_RESTART=true",
328
+ "\n",
329
+ "# 日志等级",
330
+ "LOG_LEVEL=info",
331
+ "# 日志保留天数",
332
+ "LOG_DAYS_TO_KEEP=7",
333
+ "# 日志文件最大大小 如果此项大于0则启用日志分割",
334
+ "LOG_MAX_LOG_SIZE=0",
335
+ "# logger.fnc颜色",
336
+ 'LOG_FNC_COLOR="#E1D919"',
337
+ "# 日志实时Api最多支持同时连接数",
338
+ "LOG_API_MAX_CONNECTIONS=5",
339
+ "\n",
340
+ "# ffmpeg",
341
+ "FFMPEG_PATH=",
342
+ "# ffprobe",
343
+ "FFPROBE_PATH=",
344
+ "# ffplay",
345
+ "FFPLAY_PATH=",
346
+ "RUNTIME=node",
347
+ "NODE_ENV=production",
348
+ "TSX_WATCH=false"
349
+ ];
350
+ const env = path.join(dir, ".env");
351
+ if (!fs.existsSync(env)) {
352
+ fs.writeFileSync(env, envData.join("\n"));
353
+ return;
354
+ }
355
+ const value = fs.readFileSync(env, "utf-8");
356
+ const newEntries = envData.filter((item) => {
357
+ if (item.includes("#")) return false;
358
+ const key = item.split("=")[0];
359
+ return !value.includes(key);
360
+ });
361
+ if (newEntries.length > 0) {
362
+ fs.appendFileSync(env, "\n" + newEntries.join("\n"));
363
+ }
364
+ };
365
+ const createWorkspace = (isDev, dir) => {
366
+ if (isDev) return;
367
+ const workspace = path.join(dir, "pnpm-workspace.yaml");
368
+ if (fs.existsSync(workspace)) return;
369
+ const content = "packages:\n - 'plugins/*'\n";
370
+ fs.writeFileSync(workspace, content);
371
+ };
372
+ const createConfigFile = (dir) => {
373
+ const pkgDir = fileURLToPath(new URL$1("../..", import.meta.url));
374
+ const defCfg = path.join(pkgDir, "default", "config");
375
+ const files = fs.readdirSync(defCfg);
376
+ files.forEach((file) => {
377
+ if (!file.endsWith(".json")) return;
378
+ const filePath = path.join(defCfg, file);
379
+ const targetPath = path.join(dir, "@karinjs", "config");
380
+ const targetFile = path.join(targetPath, file);
381
+ if (!fs.existsSync(targetFile)) {
382
+ fs.copyFileSync(filePath, targetFile);
383
+ return;
384
+ }
385
+ const defData = fs.readFileSync(filePath, "utf-8");
386
+ const targetData = fs.readFileSync(targetFile, "utf-8");
387
+ const mergedData = { ...JSON.parse(defData), ...JSON.parse(targetData) };
388
+ if (file.includes("pm2.json")) {
389
+ mergedData.apps[0].script = "index.mjs";
390
+ }
391
+ fs.writeFileSync(targetFile, JSON.stringify(mergedData, null, 2));
392
+ });
393
+ };
394
+ const modifyPackageJson = (isDev, dir) => {
395
+ const pkgDir = path.join(dir, "package.json");
396
+ const pkg = (() => {
397
+ try {
398
+ return JSON.parse(fs.readFileSync(pkgDir, "utf-8"));
399
+ } catch {
400
+ return {};
401
+ }
402
+ })();
403
+ if (!pkg.scripts) pkg.scripts = {};
404
+ if (!pkg.name) pkg.name = "karin-project";
405
+ if (!pkg.version) pkg.version = "1.0.0";
406
+ pkg.type = "module";
407
+ if (!isDev) {
408
+ if (!pkg.scripts.ki) pkg.scripts.ki = "ki";
409
+ if (!pkg.scripts.karin) pkg.scripts.karin = "ki";
410
+ if (!pkg.scripts.app) pkg.scripts.app = "node index.mjs";
411
+ if (!pkg.scripts.start) pkg.scripts.start = "node index.mjs";
412
+ if (!pkg.scripts.pm2) pkg.scripts.pm2 = "pm2 start @karinjs/config/pm2.json";
413
+ if (!pkg.scripts.stop) pkg.scripts.stop = "ki stop";
414
+ if (!pkg.scripts.rs) pkg.scripts.rs = "ki rs";
415
+ if (!pkg.scripts.log) pkg.scripts.log = "ki log";
416
+ if (!pkg.scripts.up) pkg.scripts.up = "ki up";
417
+ }
418
+ if (!isDev && !pkg?.dependencies?.["node-karin"]) {
419
+ if (!pkg.dependencies) pkg.dependencies = {};
420
+ pkg.dependencies["node-karin"] = "latest";
421
+ }
422
+ if (pkg.pnpm) delete pkg.pnpm;
423
+ fs.writeFileSync(pkgDir, JSON.stringify(pkg, null, 2));
424
+ return pkg;
425
+ };
426
+ const createEntryFile = (isDev, dir) => {
427
+ if (isDev) {
428
+ if (fs.existsSync(`${dir}/src`)) {
429
+ fs.writeFileSync(path.join(dir, "src", "app.ts"), "import('node-karin/start')");
430
+ return;
431
+ }
432
+ }
433
+ const entryFile = path.join(dir, "index.mjs");
434
+ if (fs.existsSync(entryFile)) return;
435
+ fs.writeFileSync(entryFile, `(() => {
436
+ import('node-karin/start')
437
+ })()
438
+ `);
439
+ };
440
+ const removeFilesIfForced = (dir) => {
441
+ removeDirectory(path.join(dir, "@karinjs"));
442
+ const pnpmfilePath = path.join(dir, ".pnpmfile.cjs");
443
+ if (fs.existsSync(pnpmfilePath)) {
444
+ fs.unlinkSync(pnpmfilePath);
445
+ }
446
+ const entryFilePath = path.join(dir, "index.mjs");
447
+ if (fs.existsSync(entryFilePath)) {
448
+ fs.unlinkSync(entryFilePath);
449
+ }
450
+ const envPath = path.join(dir, ".env");
451
+ if (fs.existsSync(envPath)) {
452
+ fs.unlinkSync(envPath);
453
+ }
454
+ };
455
+ const init = async (force) => {
456
+ const dir = process.env.INIT_CWD || process.cwd();
457
+ const isDev = getIsDev(dir);
458
+ if (force) {
459
+ removeFilesIfForced(dir);
460
+ }
461
+ createDir(isDev, dir);
462
+ createWorkspace(isDev, dir);
463
+ createConfigFile(dir);
464
+ modifyPackageJson(isDev, dir);
465
+ npmrc(dir);
466
+ pnpmfile(isDev, dir);
467
+ createEntryFile(isDev, dir);
468
+ createOrUpdateEnv(dir);
469
+ if (process.env.KARIN_CLI) {
470
+ console.log("[cli] 初始化完成 请使用 pnpm app 启动项目");
471
+ process.exit(0);
472
+ }
473
+ };
474
+ const MAIN = "index.mjs";
475
+ const start = async () => {
476
+ const indexPath = path.join(process.cwd(), MAIN);
477
+ await import(pathToFileURL(indexPath).toString());
478
+ };
479
+ const exec = (cmd, options) => {
480
+ return new Promise((resolve) => {
481
+ const timeout = (options?.timeout || 30) * 1e3;
482
+ const timer = setTimeout(() => {
483
+ resolve({
484
+ status: false,
485
+ error: new Error("命令执行超时"),
486
+ stdout: "",
487
+ stderr: "命令执行超时"
488
+ });
489
+ }, timeout);
490
+ const child = exec$2(cmd, options, (error2, stdout, stderr) => {
491
+ clearTimeout(timer);
492
+ stderr = stderr.toString().trim();
493
+ stdout = stdout.toString().trim();
494
+ const status = !error2;
495
+ resolve({ status, error: error2, stdout, stderr });
496
+ });
497
+ child.stdin?.write("\n");
498
+ });
499
+ };
500
+ const handleReturn = (data, callback) => {
501
+ if (data.error || typeof data.stdout !== "string") {
502
+ throw data.error || new Error("stdout 类型错误");
503
+ }
504
+ return data.stdout;
505
+ };
506
+ const getLocalCommitHash = async (cwd, options) => {
507
+ const branch = "HEAD";
508
+ const short = "";
509
+ const cmd = `git rev-parse ${short} ${branch}`;
510
+ const data = await exec(cmd, { cwd });
511
+ return handleReturn(data);
512
+ };
513
+ const getRemoteCommitHash = async (cwd, options) => {
514
+ let branch = "origin/HEAD";
515
+ if (!branch.startsWith("origin/")) {
516
+ branch = `origin/${branch}`;
517
+ }
518
+ const short = "";
519
+ const cmd = `git rev-parse ${short} ${branch}`;
520
+ const data = await exec(cmd, { cwd });
521
+ return handleReturn(data);
522
+ };
523
+ const pullResult = (status, currentHash, remoteHash, data, prefix = "") => {
524
+ return {
525
+ status,
526
+ data: typeof data === "string" ? data : `${prefix}${data.message || data.stack || "未知错误"}`,
527
+ hash: {
528
+ before: currentHash,
529
+ after: remoteHash
530
+ }
531
+ };
532
+ };
533
+ const gitPull = async (cwd, options = {}) => {
534
+ try {
535
+ const currentHash = await getLocalCommitHash(cwd);
536
+ const remoteHash = await getRemoteCommitHash(cwd);
537
+ if (currentHash === remoteHash) {
538
+ return pullResult(false, currentHash, remoteHash, "当前已经是最新版本");
539
+ }
540
+ if (options.force) {
541
+ const remote = options.remote || "origin/HEAD";
542
+ const fetchResult = await exec("git fetch origin", { cwd, ...options });
543
+ if (fetchResult.error) {
544
+ return pullResult(false, currentHash, remoteHash, fetchResult.error, "同步远程分支失败: ");
545
+ }
546
+ const resetResult = await exec(`git reset --hard ${remote}`, { cwd, ...options });
547
+ if (resetResult.error) {
548
+ return pullResult(false, currentHash, remoteHash, resetResult.error, "强制同步远程分支失败: ");
549
+ }
550
+ const hash2 = await getLocalCommitHash(cwd);
551
+ return pullResult(true, currentHash, hash2, "本地分支已强制与远程分支同步");
552
+ }
553
+ const cmd = options.customCmd || "git pull";
554
+ const { error: error2 } = await exec(cmd, { ...options, cwd });
555
+ if (error2) {
556
+ return pullResult(false, currentHash, remoteHash, error2, "更新失败: ");
557
+ }
558
+ const hash = await getLocalCommitHash(cwd);
559
+ return pullResult(true, currentHash, hash, "更新成功");
560
+ } catch (error2) {
561
+ return pullResult(false, "", "", error2.message, "发生错误: ");
562
+ }
563
+ };
564
+ const checkGitInstalled = async () => {
565
+ try {
566
+ const { status } = await exec$1("git --version");
567
+ return status;
568
+ } catch {
569
+ return false;
570
+ }
571
+ };
572
+ const sortUpdateItems = (items) => {
573
+ return [...items].sort((a, b) => {
574
+ if (a.isPlugin !== b.isPlugin) {
575
+ return a.isPlugin ? 1 : -1;
576
+ }
577
+ if (a.needUpdate !== b.needUpdate) {
578
+ return a.needUpdate ? 1 : -1;
579
+ }
580
+ return a.name.localeCompare(b.name);
581
+ });
582
+ };
583
+ const updateAll = async (force, parallel = false) => {
584
+ try {
585
+ console.log("开始执行更新任务\n");
586
+ const allItems = [];
587
+ const packagesToUpdate = [];
588
+ await checkDependencies("./package.json", allItems, packagesToUpdate);
589
+ await checkPlugins("./plugins", allItems, force, parallel);
590
+ const sortedItems = sortUpdateItems(allItems);
591
+ if (sortedItems.length > 0) {
592
+ console.log("检查结果:");
593
+ const tableData = sortedItems.map((item) => {
594
+ return {
595
+ name: item.name,
596
+ type: item.type,
597
+ currentVersion: item.currentVersion,
598
+ latestVersion: item.latestVersion,
599
+ status: item.status
600
+ };
601
+ });
602
+ console.table(tableData);
603
+ } else {
604
+ console.log("没有找到需要检查的项目");
605
+ }
606
+ if (packagesToUpdate.length > 0) {
607
+ console.log("\n开始更新包:");
608
+ try {
609
+ const { status, error: error2 } = await exec$1(`pnpm update ${packagesToUpdate.join(" ")} --save`);
610
+ if (status) {
611
+ console.log("npm包更新完成");
612
+ const updatedItems = sortedItems.filter((item) => item.needUpdate);
613
+ if (updatedItems.length > 0) {
614
+ console.log("\n已更新的项目:");
615
+ const updatedTable = updatedItems.map((item) => ({
616
+ name: item.name,
617
+ type: item.type,
618
+ from: item.currentVersion,
619
+ to: item.latestVersion
620
+ }));
621
+ console.table(updatedTable);
622
+ }
623
+ } else {
624
+ console.error("npm包更新失败:", error2);
625
+ }
626
+ } catch (error2) {
627
+ console.error("npm包更新失败:", error2);
628
+ }
629
+ }
630
+ console.log("\n更新任务执行完成");
631
+ } finally {
632
+ process.exit(0);
633
+ }
634
+ };
635
+ const checkDependencies = async (packagePath, allItems, packagesToUpdate) => {
636
+ try {
637
+ const packageJson = JSON.parse(fs.readFileSync(packagePath, "utf-8"));
638
+ const dependencies = packageJson.dependencies || {};
639
+ const checkVersionTasks = Object.entries(dependencies).map(async ([pkg, version]) => {
640
+ if (pkg.startsWith("@types/")) {
641
+ return;
642
+ }
643
+ try {
644
+ const { stdout: pkgInfoStr } = await exec$1(`pnpm view ${pkg} --json`);
645
+ const pkgInfo = JSON.parse(pkgInfoStr.trim());
646
+ if (!pkgInfo.karin && pkg !== "node-karin") return;
647
+ const currentVersion = version.replace(/[\^~]/g, "");
648
+ const { stdout: distTagsStr } = await exec$1(`pnpm view ${pkg} dist-tags --json`);
649
+ const distTags = JSON.parse(distTagsStr.trim());
650
+ const isPreRelease = /[-+]/.test(currentVersion);
651
+ const latestVersion = distTags.latest;
652
+ const needUpdate = isPreRelease || currentVersion !== latestVersion;
653
+ if (needUpdate) {
654
+ packagesToUpdate.push(`${pkg}@latest`);
655
+ allItems.push({
656
+ name: pkg,
657
+ type: "npm",
658
+ currentVersion: `${currentVersion}${isPreRelease ? " (预发布)" : ""}`,
659
+ latestVersion,
660
+ status: `${currentVersion} -> ${latestVersion}`,
661
+ needUpdate: true,
662
+ isPlugin: true
663
+ });
664
+ } else {
665
+ allItems.push({
666
+ name: pkg,
667
+ type: "npm",
668
+ currentVersion,
669
+ latestVersion,
670
+ status: "已是最新",
671
+ needUpdate: false,
672
+ isPlugin: true
673
+ });
674
+ }
675
+ } catch (error2) {
676
+ console.error(`检查 ${pkg} 版本失败:`, error2);
677
+ }
678
+ });
679
+ await Promise.all(checkVersionTasks);
680
+ } catch (error2) {
681
+ console.error("更新依赖失败:", error2);
682
+ }
683
+ };
684
+ const checkPlugins = async (pluginsPath, allItems, force, parallel = true) => {
685
+ if (!await checkGitInstalled()) {
686
+ console.error("请先安装git");
687
+ return;
688
+ }
689
+ if (!fs.existsSync(pluginsPath)) {
690
+ console.error("plugins目录不存在");
691
+ return;
692
+ }
693
+ const isDirectory = (await fs.promises.stat(pluginsPath)).isDirectory();
694
+ if (!isDirectory) {
695
+ console.error("plugins路径不是一个目录");
696
+ return;
697
+ }
698
+ const dirs = await fs.promises.readdir(pluginsPath);
699
+ if (parallel) {
700
+ const tasks = dirs.map(async (dir) => {
701
+ await processPlugin(dir, pluginsPath, allItems, force);
702
+ });
703
+ await Promise.all(tasks);
704
+ } else {
705
+ for (const dir of dirs) {
706
+ await processPlugin(dir, pluginsPath, allItems, force);
707
+ }
708
+ }
709
+ };
710
+ const processPlugin = async (dir, pluginsPath, allItems, force) => {
711
+ const pluginPath = join(pluginsPath, dir);
712
+ const gitPath = join(pluginPath, ".git");
713
+ const packageJsonPath = join(pluginPath, "package.json");
714
+ if (!dir.startsWith("karin-plugin-") || !(await fs.promises.stat(pluginPath)).isDirectory()) {
715
+ return;
716
+ }
717
+ if (!fs.existsSync(gitPath)) {
718
+ allItems.push({
719
+ name: dir,
720
+ type: "git",
721
+ currentVersion: "-",
722
+ latestVersion: "-",
723
+ status: "不是git仓库,已跳过",
724
+ needUpdate: false,
725
+ isPlugin: false
726
+ });
727
+ try {
728
+ const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf-8"));
729
+ if (!packageJson.karin) {
730
+ allItems.push({
731
+ name: dir,
732
+ type: "git",
733
+ currentVersion: "-",
734
+ latestVersion: "-",
735
+ status: "非Karin插件,已跳过",
736
+ needUpdate: false,
737
+ isPlugin: false
738
+ });
739
+ return;
740
+ }
741
+ const { status, hash, data } = await gitPull(pluginPath, { customCmd: "git pull", force });
742
+ if (!status) {
743
+ allItems.push({
744
+ name: dir,
745
+ type: "git",
746
+ currentVersion: "-",
747
+ latestVersion: "-",
748
+ status: `更新失败: ${data}`,
749
+ needUpdate: false,
750
+ isPlugin: true
751
+ });
752
+ } else {
753
+ allItems.push({
754
+ name: dir,
755
+ type: "git",
756
+ currentVersion: hash.before,
757
+ latestVersion: hash.after,
758
+ status: "更新成功",
759
+ needUpdate: true,
760
+ isPlugin: true
761
+ });
762
+ }
763
+ } catch (error2) {
764
+ allItems.push({
765
+ name: dir,
766
+ type: "git",
767
+ currentVersion: "-",
768
+ latestVersion: "-",
769
+ status: `处理失败: ${error2}`,
770
+ needUpdate: false,
771
+ isPlugin: false
772
+ });
773
+ }
774
+ }
775
+ };
776
+ function getDefaultExportFromCjs(x) {
777
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x;
778
+ }
779
+ var commander$1 = {};
780
+ var argument = {};
781
+ var error = {};
782
+ var hasRequiredError;
783
+ function requireError() {
784
+ if (hasRequiredError) return error;
785
+ hasRequiredError = 1;
786
+ class CommanderError2 extends Error {
787
+ /**
788
+ * Constructs the CommanderError class
789
+ * @param {number} exitCode suggested exit code which could be used with process.exit
790
+ * @param {string} code an id string representing the error
791
+ * @param {string} message human-readable description of the error
792
+ */
793
+ constructor(exitCode, code, message) {
794
+ super(message);
795
+ Error.captureStackTrace(this, this.constructor);
796
+ this.name = this.constructor.name;
797
+ this.code = code;
798
+ this.exitCode = exitCode;
799
+ this.nestedError = void 0;
800
+ }
801
+ }
802
+ class InvalidArgumentError2 extends CommanderError2 {
803
+ /**
804
+ * Constructs the InvalidArgumentError class
805
+ * @param {string} [message] explanation of why argument is invalid
806
+ */
807
+ constructor(message) {
808
+ super(1, "commander.invalidArgument", message);
809
+ Error.captureStackTrace(this, this.constructor);
810
+ this.name = this.constructor.name;
811
+ }
812
+ }
813
+ error.CommanderError = CommanderError2;
814
+ error.InvalidArgumentError = InvalidArgumentError2;
815
+ return error;
816
+ }
817
+ var hasRequiredArgument;
818
+ function requireArgument() {
819
+ if (hasRequiredArgument) return argument;
820
+ hasRequiredArgument = 1;
821
+ const { InvalidArgumentError: InvalidArgumentError2 } = requireError();
822
+ class Argument2 {
823
+ /**
824
+ * Initialize a new command argument with the given name and description.
825
+ * The default is that the argument is required, and you can explicitly
826
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
827
+ *
828
+ * @param {string} name
829
+ * @param {string} [description]
830
+ */
831
+ constructor(name, description) {
832
+ this.description = description || "";
833
+ this.variadic = false;
834
+ this.parseArg = void 0;
835
+ this.defaultValue = void 0;
836
+ this.defaultValueDescription = void 0;
837
+ this.argChoices = void 0;
838
+ switch (name[0]) {
839
+ case "<":
840
+ this.required = true;
841
+ this._name = name.slice(1, -1);
842
+ break;
843
+ case "[":
844
+ this.required = false;
845
+ this._name = name.slice(1, -1);
846
+ break;
847
+ default:
848
+ this.required = true;
849
+ this._name = name;
850
+ break;
851
+ }
852
+ if (this._name.length > 3 && this._name.slice(-3) === "...") {
853
+ this.variadic = true;
854
+ this._name = this._name.slice(0, -3);
855
+ }
856
+ }
857
+ /**
858
+ * Return argument name.
859
+ *
860
+ * @return {string}
861
+ */
862
+ name() {
863
+ return this._name;
864
+ }
865
+ /**
866
+ * @package
867
+ */
868
+ _concatValue(value, previous) {
869
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
870
+ return [value];
871
+ }
872
+ return previous.concat(value);
873
+ }
874
+ /**
875
+ * Set the default value, and optionally supply the description to be displayed in the help.
876
+ *
877
+ * @param {*} value
878
+ * @param {string} [description]
879
+ * @return {Argument}
880
+ */
881
+ default(value, description) {
882
+ this.defaultValue = value;
883
+ this.defaultValueDescription = description;
884
+ return this;
885
+ }
886
+ /**
887
+ * Set the custom handler for processing CLI command arguments into argument values.
888
+ *
889
+ * @param {Function} [fn]
890
+ * @return {Argument}
891
+ */
892
+ argParser(fn) {
893
+ this.parseArg = fn;
894
+ return this;
895
+ }
896
+ /**
897
+ * Only allow argument value to be one of choices.
898
+ *
899
+ * @param {string[]} values
900
+ * @return {Argument}
901
+ */
902
+ choices(values) {
903
+ this.argChoices = values.slice();
904
+ this.parseArg = (arg, previous) => {
905
+ if (!this.argChoices.includes(arg)) {
906
+ throw new InvalidArgumentError2(
907
+ `Allowed choices are ${this.argChoices.join(", ")}.`
908
+ );
909
+ }
910
+ if (this.variadic) {
911
+ return this._concatValue(arg, previous);
912
+ }
913
+ return arg;
914
+ };
915
+ return this;
916
+ }
917
+ /**
918
+ * Make argument required.
919
+ *
920
+ * @returns {Argument}
921
+ */
922
+ argRequired() {
923
+ this.required = true;
924
+ return this;
925
+ }
926
+ /**
927
+ * Make argument optional.
928
+ *
929
+ * @returns {Argument}
930
+ */
931
+ argOptional() {
932
+ this.required = false;
933
+ return this;
934
+ }
935
+ }
936
+ function humanReadableArgName(arg) {
937
+ const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
938
+ return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
939
+ }
940
+ argument.Argument = Argument2;
941
+ argument.humanReadableArgName = humanReadableArgName;
942
+ return argument;
943
+ }
944
+ var command = {};
945
+ var help = {};
946
+ var hasRequiredHelp;
947
+ function requireHelp() {
948
+ if (hasRequiredHelp) return help;
949
+ hasRequiredHelp = 1;
950
+ const { humanReadableArgName } = requireArgument();
951
+ class Help2 {
952
+ constructor() {
953
+ this.helpWidth = void 0;
954
+ this.minWidthToWrap = 40;
955
+ this.sortSubcommands = false;
956
+ this.sortOptions = false;
957
+ this.showGlobalOptions = false;
958
+ }
959
+ /**
960
+ * prepareContext is called by Commander after applying overrides from `Command.configureHelp()`
961
+ * and just before calling `formatHelp()`.
962
+ *
963
+ * Commander just uses the helpWidth and the rest is provided for optional use by more complex subclasses.
964
+ *
965
+ * @param {{ error?: boolean, helpWidth?: number, outputHasColors?: boolean }} contextOptions
966
+ */
967
+ prepareContext(contextOptions) {
968
+ this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;
969
+ }
970
+ /**
971
+ * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
972
+ *
973
+ * @param {Command} cmd
974
+ * @returns {Command[]}
975
+ */
976
+ visibleCommands(cmd) {
977
+ const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
978
+ const helpCommand = cmd._getHelpCommand();
979
+ if (helpCommand && !helpCommand._hidden) {
980
+ visibleCommands.push(helpCommand);
981
+ }
982
+ if (this.sortSubcommands) {
983
+ visibleCommands.sort((a, b) => {
984
+ return a.name().localeCompare(b.name());
985
+ });
986
+ }
987
+ return visibleCommands;
988
+ }
989
+ /**
990
+ * Compare options for sort.
991
+ *
992
+ * @param {Option} a
993
+ * @param {Option} b
994
+ * @returns {number}
995
+ */
996
+ compareOptions(a, b) {
997
+ const getSortKey = (option2) => {
998
+ return option2.short ? option2.short.replace(/^-/, "") : option2.long.replace(/^--/, "");
999
+ };
1000
+ return getSortKey(a).localeCompare(getSortKey(b));
1001
+ }
1002
+ /**
1003
+ * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
1004
+ *
1005
+ * @param {Command} cmd
1006
+ * @returns {Option[]}
1007
+ */
1008
+ visibleOptions(cmd) {
1009
+ const visibleOptions = cmd.options.filter((option2) => !option2.hidden);
1010
+ const helpOption = cmd._getHelpOption();
1011
+ if (helpOption && !helpOption.hidden) {
1012
+ const removeShort = helpOption.short && cmd._findOption(helpOption.short);
1013
+ const removeLong = helpOption.long && cmd._findOption(helpOption.long);
1014
+ if (!removeShort && !removeLong) {
1015
+ visibleOptions.push(helpOption);
1016
+ } else if (helpOption.long && !removeLong) {
1017
+ visibleOptions.push(
1018
+ cmd.createOption(helpOption.long, helpOption.description)
1019
+ );
1020
+ } else if (helpOption.short && !removeShort) {
1021
+ visibleOptions.push(
1022
+ cmd.createOption(helpOption.short, helpOption.description)
1023
+ );
1024
+ }
1025
+ }
1026
+ if (this.sortOptions) {
1027
+ visibleOptions.sort(this.compareOptions);
1028
+ }
1029
+ return visibleOptions;
1030
+ }
1031
+ /**
1032
+ * Get an array of the visible global options. (Not including help.)
1033
+ *
1034
+ * @param {Command} cmd
1035
+ * @returns {Option[]}
1036
+ */
1037
+ visibleGlobalOptions(cmd) {
1038
+ if (!this.showGlobalOptions) return [];
1039
+ const globalOptions = [];
1040
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
1041
+ const visibleOptions = ancestorCmd.options.filter(
1042
+ (option2) => !option2.hidden
1043
+ );
1044
+ globalOptions.push(...visibleOptions);
1045
+ }
1046
+ if (this.sortOptions) {
1047
+ globalOptions.sort(this.compareOptions);
1048
+ }
1049
+ return globalOptions;
1050
+ }
1051
+ /**
1052
+ * Get an array of the arguments if any have a description.
1053
+ *
1054
+ * @param {Command} cmd
1055
+ * @returns {Argument[]}
1056
+ */
1057
+ visibleArguments(cmd) {
1058
+ if (cmd._argsDescription) {
1059
+ cmd.registeredArguments.forEach((argument2) => {
1060
+ argument2.description = argument2.description || cmd._argsDescription[argument2.name()] || "";
1061
+ });
1062
+ }
1063
+ if (cmd.registeredArguments.find((argument2) => argument2.description)) {
1064
+ return cmd.registeredArguments;
1065
+ }
1066
+ return [];
1067
+ }
1068
+ /**
1069
+ * Get the command term to show in the list of subcommands.
1070
+ *
1071
+ * @param {Command} cmd
1072
+ * @returns {string}
1073
+ */
1074
+ subcommandTerm(cmd) {
1075
+ const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
1076
+ return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + // simplistic check for non-help option
1077
+ (args ? " " + args : "");
1078
+ }
1079
+ /**
1080
+ * Get the option term to show in the list of options.
1081
+ *
1082
+ * @param {Option} option
1083
+ * @returns {string}
1084
+ */
1085
+ optionTerm(option2) {
1086
+ return option2.flags;
1087
+ }
1088
+ /**
1089
+ * Get the argument term to show in the list of arguments.
1090
+ *
1091
+ * @param {Argument} argument
1092
+ * @returns {string}
1093
+ */
1094
+ argumentTerm(argument2) {
1095
+ return argument2.name();
1096
+ }
1097
+ /**
1098
+ * Get the longest command term length.
1099
+ *
1100
+ * @param {Command} cmd
1101
+ * @param {Help} helper
1102
+ * @returns {number}
1103
+ */
1104
+ longestSubcommandTermLength(cmd, helper) {
1105
+ return helper.visibleCommands(cmd).reduce((max, command2) => {
1106
+ return Math.max(
1107
+ max,
1108
+ this.displayWidth(
1109
+ helper.styleSubcommandTerm(helper.subcommandTerm(command2))
1110
+ )
1111
+ );
1112
+ }, 0);
1113
+ }
1114
+ /**
1115
+ * Get the longest option term length.
1116
+ *
1117
+ * @param {Command} cmd
1118
+ * @param {Help} helper
1119
+ * @returns {number}
1120
+ */
1121
+ longestOptionTermLength(cmd, helper) {
1122
+ return helper.visibleOptions(cmd).reduce((max, option2) => {
1123
+ return Math.max(
1124
+ max,
1125
+ this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option2)))
1126
+ );
1127
+ }, 0);
1128
+ }
1129
+ /**
1130
+ * Get the longest global option term length.
1131
+ *
1132
+ * @param {Command} cmd
1133
+ * @param {Help} helper
1134
+ * @returns {number}
1135
+ */
1136
+ longestGlobalOptionTermLength(cmd, helper) {
1137
+ return helper.visibleGlobalOptions(cmd).reduce((max, option2) => {
1138
+ return Math.max(
1139
+ max,
1140
+ this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option2)))
1141
+ );
1142
+ }, 0);
1143
+ }
1144
+ /**
1145
+ * Get the longest argument term length.
1146
+ *
1147
+ * @param {Command} cmd
1148
+ * @param {Help} helper
1149
+ * @returns {number}
1150
+ */
1151
+ longestArgumentTermLength(cmd, helper) {
1152
+ return helper.visibleArguments(cmd).reduce((max, argument2) => {
1153
+ return Math.max(
1154
+ max,
1155
+ this.displayWidth(
1156
+ helper.styleArgumentTerm(helper.argumentTerm(argument2))
1157
+ )
1158
+ );
1159
+ }, 0);
1160
+ }
1161
+ /**
1162
+ * Get the command usage to be displayed at the top of the built-in help.
1163
+ *
1164
+ * @param {Command} cmd
1165
+ * @returns {string}
1166
+ */
1167
+ commandUsage(cmd) {
1168
+ let cmdName = cmd._name;
1169
+ if (cmd._aliases[0]) {
1170
+ cmdName = cmdName + "|" + cmd._aliases[0];
1171
+ }
1172
+ let ancestorCmdNames = "";
1173
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
1174
+ ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
1175
+ }
1176
+ return ancestorCmdNames + cmdName + " " + cmd.usage();
1177
+ }
1178
+ /**
1179
+ * Get the description for the command.
1180
+ *
1181
+ * @param {Command} cmd
1182
+ * @returns {string}
1183
+ */
1184
+ commandDescription(cmd) {
1185
+ return cmd.description();
1186
+ }
1187
+ /**
1188
+ * Get the subcommand summary to show in the list of subcommands.
1189
+ * (Fallback to description for backwards compatibility.)
1190
+ *
1191
+ * @param {Command} cmd
1192
+ * @returns {string}
1193
+ */
1194
+ subcommandDescription(cmd) {
1195
+ return cmd.summary() || cmd.description();
1196
+ }
1197
+ /**
1198
+ * Get the option description to show in the list of options.
1199
+ *
1200
+ * @param {Option} option
1201
+ * @return {string}
1202
+ */
1203
+ optionDescription(option2) {
1204
+ const extraInfo = [];
1205
+ if (option2.argChoices) {
1206
+ extraInfo.push(
1207
+ // use stringify to match the display of the default value
1208
+ `choices: ${option2.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
1209
+ );
1210
+ }
1211
+ if (option2.defaultValue !== void 0) {
1212
+ const showDefault = option2.required || option2.optional || option2.isBoolean() && typeof option2.defaultValue === "boolean";
1213
+ if (showDefault) {
1214
+ extraInfo.push(
1215
+ `default: ${option2.defaultValueDescription || JSON.stringify(option2.defaultValue)}`
1216
+ );
1217
+ }
1218
+ }
1219
+ if (option2.presetArg !== void 0 && option2.optional) {
1220
+ extraInfo.push(`preset: ${JSON.stringify(option2.presetArg)}`);
1221
+ }
1222
+ if (option2.envVar !== void 0) {
1223
+ extraInfo.push(`env: ${option2.envVar}`);
1224
+ }
1225
+ if (extraInfo.length > 0) {
1226
+ return `${option2.description} (${extraInfo.join(", ")})`;
1227
+ }
1228
+ return option2.description;
1229
+ }
1230
+ /**
1231
+ * Get the argument description to show in the list of arguments.
1232
+ *
1233
+ * @param {Argument} argument
1234
+ * @return {string}
1235
+ */
1236
+ argumentDescription(argument2) {
1237
+ const extraInfo = [];
1238
+ if (argument2.argChoices) {
1239
+ extraInfo.push(
1240
+ // use stringify to match the display of the default value
1241
+ `choices: ${argument2.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
1242
+ );
1243
+ }
1244
+ if (argument2.defaultValue !== void 0) {
1245
+ extraInfo.push(
1246
+ `default: ${argument2.defaultValueDescription || JSON.stringify(argument2.defaultValue)}`
1247
+ );
1248
+ }
1249
+ if (extraInfo.length > 0) {
1250
+ const extraDescription = `(${extraInfo.join(", ")})`;
1251
+ if (argument2.description) {
1252
+ return `${argument2.description} ${extraDescription}`;
1253
+ }
1254
+ return extraDescription;
1255
+ }
1256
+ return argument2.description;
1257
+ }
1258
+ /**
1259
+ * Generate the built-in help text.
1260
+ *
1261
+ * @param {Command} cmd
1262
+ * @param {Help} helper
1263
+ * @returns {string}
1264
+ */
1265
+ formatHelp(cmd, helper) {
1266
+ const termWidth = helper.padWidth(cmd, helper);
1267
+ const helpWidth = helper.helpWidth ?? 80;
1268
+ function callFormatItem(term, description) {
1269
+ return helper.formatItem(term, termWidth, description, helper);
1270
+ }
1271
+ let output = [
1272
+ `${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`,
1273
+ ""
1274
+ ];
1275
+ const commandDescription = helper.commandDescription(cmd);
1276
+ if (commandDescription.length > 0) {
1277
+ output = output.concat([
1278
+ helper.boxWrap(
1279
+ helper.styleCommandDescription(commandDescription),
1280
+ helpWidth
1281
+ ),
1282
+ ""
1283
+ ]);
1284
+ }
1285
+ const argumentList = helper.visibleArguments(cmd).map((argument2) => {
1286
+ return callFormatItem(
1287
+ helper.styleArgumentTerm(helper.argumentTerm(argument2)),
1288
+ helper.styleArgumentDescription(helper.argumentDescription(argument2))
1289
+ );
1290
+ });
1291
+ if (argumentList.length > 0) {
1292
+ output = output.concat([
1293
+ helper.styleTitle("Arguments:"),
1294
+ ...argumentList,
1295
+ ""
1296
+ ]);
1297
+ }
1298
+ const optionList = helper.visibleOptions(cmd).map((option2) => {
1299
+ return callFormatItem(
1300
+ helper.styleOptionTerm(helper.optionTerm(option2)),
1301
+ helper.styleOptionDescription(helper.optionDescription(option2))
1302
+ );
1303
+ });
1304
+ if (optionList.length > 0) {
1305
+ output = output.concat([
1306
+ helper.styleTitle("Options:"),
1307
+ ...optionList,
1308
+ ""
1309
+ ]);
1310
+ }
1311
+ if (helper.showGlobalOptions) {
1312
+ const globalOptionList = helper.visibleGlobalOptions(cmd).map((option2) => {
1313
+ return callFormatItem(
1314
+ helper.styleOptionTerm(helper.optionTerm(option2)),
1315
+ helper.styleOptionDescription(helper.optionDescription(option2))
1316
+ );
1317
+ });
1318
+ if (globalOptionList.length > 0) {
1319
+ output = output.concat([
1320
+ helper.styleTitle("Global Options:"),
1321
+ ...globalOptionList,
1322
+ ""
1323
+ ]);
1324
+ }
1325
+ }
1326
+ const commandList = helper.visibleCommands(cmd).map((cmd2) => {
1327
+ return callFormatItem(
1328
+ helper.styleSubcommandTerm(helper.subcommandTerm(cmd2)),
1329
+ helper.styleSubcommandDescription(helper.subcommandDescription(cmd2))
1330
+ );
1331
+ });
1332
+ if (commandList.length > 0) {
1333
+ output = output.concat([
1334
+ helper.styleTitle("Commands:"),
1335
+ ...commandList,
1336
+ ""
1337
+ ]);
1338
+ }
1339
+ return output.join("\n");
1340
+ }
1341
+ /**
1342
+ * Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations.
1343
+ *
1344
+ * @param {string} str
1345
+ * @returns {number}
1346
+ */
1347
+ displayWidth(str) {
1348
+ return stripColor(str).length;
1349
+ }
1350
+ /**
1351
+ * Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc.
1352
+ *
1353
+ * @param {string} str
1354
+ * @returns {string}
1355
+ */
1356
+ styleTitle(str) {
1357
+ return str;
1358
+ }
1359
+ styleUsage(str) {
1360
+ return str.split(" ").map((word) => {
1361
+ if (word === "[options]") return this.styleOptionText(word);
1362
+ if (word === "[command]") return this.styleSubcommandText(word);
1363
+ if (word[0] === "[" || word[0] === "<")
1364
+ return this.styleArgumentText(word);
1365
+ return this.styleCommandText(word);
1366
+ }).join(" ");
1367
+ }
1368
+ styleCommandDescription(str) {
1369
+ return this.styleDescriptionText(str);
1370
+ }
1371
+ styleOptionDescription(str) {
1372
+ return this.styleDescriptionText(str);
1373
+ }
1374
+ styleSubcommandDescription(str) {
1375
+ return this.styleDescriptionText(str);
1376
+ }
1377
+ styleArgumentDescription(str) {
1378
+ return this.styleDescriptionText(str);
1379
+ }
1380
+ styleDescriptionText(str) {
1381
+ return str;
1382
+ }
1383
+ styleOptionTerm(str) {
1384
+ return this.styleOptionText(str);
1385
+ }
1386
+ styleSubcommandTerm(str) {
1387
+ return str.split(" ").map((word) => {
1388
+ if (word === "[options]") return this.styleOptionText(word);
1389
+ if (word[0] === "[" || word[0] === "<")
1390
+ return this.styleArgumentText(word);
1391
+ return this.styleSubcommandText(word);
1392
+ }).join(" ");
1393
+ }
1394
+ styleArgumentTerm(str) {
1395
+ return this.styleArgumentText(str);
1396
+ }
1397
+ styleOptionText(str) {
1398
+ return str;
1399
+ }
1400
+ styleArgumentText(str) {
1401
+ return str;
1402
+ }
1403
+ styleSubcommandText(str) {
1404
+ return str;
1405
+ }
1406
+ styleCommandText(str) {
1407
+ return str;
1408
+ }
1409
+ /**
1410
+ * Calculate the pad width from the maximum term length.
1411
+ *
1412
+ * @param {Command} cmd
1413
+ * @param {Help} helper
1414
+ * @returns {number}
1415
+ */
1416
+ padWidth(cmd, helper) {
1417
+ return Math.max(
1418
+ helper.longestOptionTermLength(cmd, helper),
1419
+ helper.longestGlobalOptionTermLength(cmd, helper),
1420
+ helper.longestSubcommandTermLength(cmd, helper),
1421
+ helper.longestArgumentTermLength(cmd, helper)
1422
+ );
1423
+ }
1424
+ /**
1425
+ * Detect manually wrapped and indented strings by checking for line break followed by whitespace.
1426
+ *
1427
+ * @param {string} str
1428
+ * @returns {boolean}
1429
+ */
1430
+ preformatted(str) {
1431
+ return /\n[^\S\r\n]/.test(str);
1432
+ }
1433
+ /**
1434
+ * Format the "item", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.
1435
+ *
1436
+ * So "TTT", 5, "DDD DDDD DD DDD" might be formatted for this.helpWidth=17 like so:
1437
+ * TTT DDD DDDD
1438
+ * DD DDD
1439
+ *
1440
+ * @param {string} term
1441
+ * @param {number} termWidth
1442
+ * @param {string} description
1443
+ * @param {Help} helper
1444
+ * @returns {string}
1445
+ */
1446
+ formatItem(term, termWidth, description, helper) {
1447
+ const itemIndent = 2;
1448
+ const itemIndentStr = " ".repeat(itemIndent);
1449
+ if (!description) return itemIndentStr + term;
1450
+ const paddedTerm = term.padEnd(
1451
+ termWidth + term.length - helper.displayWidth(term)
1452
+ );
1453
+ const spacerWidth = 2;
1454
+ const helpWidth = this.helpWidth ?? 80;
1455
+ const remainingWidth = helpWidth - termWidth - spacerWidth - itemIndent;
1456
+ let formattedDescription;
1457
+ if (remainingWidth < this.minWidthToWrap || helper.preformatted(description)) {
1458
+ formattedDescription = description;
1459
+ } else {
1460
+ const wrappedDescription = helper.boxWrap(description, remainingWidth);
1461
+ formattedDescription = wrappedDescription.replace(
1462
+ /\n/g,
1463
+ "\n" + " ".repeat(termWidth + spacerWidth)
1464
+ );
1465
+ }
1466
+ return itemIndentStr + paddedTerm + " ".repeat(spacerWidth) + formattedDescription.replace(/\n/g, `
1467
+ ${itemIndentStr}`);
1468
+ }
1469
+ /**
1470
+ * Wrap a string at whitespace, preserving existing line breaks.
1471
+ * Wrapping is skipped if the width is less than `minWidthToWrap`.
1472
+ *
1473
+ * @param {string} str
1474
+ * @param {number} width
1475
+ * @returns {string}
1476
+ */
1477
+ boxWrap(str, width) {
1478
+ if (width < this.minWidthToWrap) return str;
1479
+ const rawLines = str.split(/\r\n|\n/);
1480
+ const chunkPattern = /[\s]*[^\s]+/g;
1481
+ const wrappedLines = [];
1482
+ rawLines.forEach((line) => {
1483
+ const chunks = line.match(chunkPattern);
1484
+ if (chunks === null) {
1485
+ wrappedLines.push("");
1486
+ return;
1487
+ }
1488
+ let sumChunks = [chunks.shift()];
1489
+ let sumWidth = this.displayWidth(sumChunks[0]);
1490
+ chunks.forEach((chunk) => {
1491
+ const visibleWidth = this.displayWidth(chunk);
1492
+ if (sumWidth + visibleWidth <= width) {
1493
+ sumChunks.push(chunk);
1494
+ sumWidth += visibleWidth;
1495
+ return;
1496
+ }
1497
+ wrappedLines.push(sumChunks.join(""));
1498
+ const nextChunk = chunk.trimStart();
1499
+ sumChunks = [nextChunk];
1500
+ sumWidth = this.displayWidth(nextChunk);
1501
+ });
1502
+ wrappedLines.push(sumChunks.join(""));
1503
+ });
1504
+ return wrappedLines.join("\n");
1505
+ }
1506
+ }
1507
+ function stripColor(str) {
1508
+ const sgrPattern = /\x1b\[\d*(;\d*)*m/g;
1509
+ return str.replace(sgrPattern, "");
1510
+ }
1511
+ help.Help = Help2;
1512
+ help.stripColor = stripColor;
1513
+ return help;
1514
+ }
1515
+ var option = {};
1516
+ var hasRequiredOption;
1517
+ function requireOption() {
1518
+ if (hasRequiredOption) return option;
1519
+ hasRequiredOption = 1;
1520
+ const { InvalidArgumentError: InvalidArgumentError2 } = requireError();
1521
+ class Option2 {
1522
+ /**
1523
+ * Initialize a new `Option` with the given `flags` and `description`.
1524
+ *
1525
+ * @param {string} flags
1526
+ * @param {string} [description]
1527
+ */
1528
+ constructor(flags, description) {
1529
+ this.flags = flags;
1530
+ this.description = description || "";
1531
+ this.required = flags.includes("<");
1532
+ this.optional = flags.includes("[");
1533
+ this.variadic = /\w\.\.\.[>\]]$/.test(flags);
1534
+ this.mandatory = false;
1535
+ const optionFlags = splitOptionFlags(flags);
1536
+ this.short = optionFlags.shortFlag;
1537
+ this.long = optionFlags.longFlag;
1538
+ this.negate = false;
1539
+ if (this.long) {
1540
+ this.negate = this.long.startsWith("--no-");
1541
+ }
1542
+ this.defaultValue = void 0;
1543
+ this.defaultValueDescription = void 0;
1544
+ this.presetArg = void 0;
1545
+ this.envVar = void 0;
1546
+ this.parseArg = void 0;
1547
+ this.hidden = false;
1548
+ this.argChoices = void 0;
1549
+ this.conflictsWith = [];
1550
+ this.implied = void 0;
1551
+ }
1552
+ /**
1553
+ * Set the default value, and optionally supply the description to be displayed in the help.
1554
+ *
1555
+ * @param {*} value
1556
+ * @param {string} [description]
1557
+ * @return {Option}
1558
+ */
1559
+ default(value, description) {
1560
+ this.defaultValue = value;
1561
+ this.defaultValueDescription = description;
1562
+ return this;
1563
+ }
1564
+ /**
1565
+ * Preset to use when option used without option-argument, especially optional but also boolean and negated.
1566
+ * The custom processing (parseArg) is called.
1567
+ *
1568
+ * @example
1569
+ * new Option('--color').default('GREYSCALE').preset('RGB');
1570
+ * new Option('--donate [amount]').preset('20').argParser(parseFloat);
1571
+ *
1572
+ * @param {*} arg
1573
+ * @return {Option}
1574
+ */
1575
+ preset(arg) {
1576
+ this.presetArg = arg;
1577
+ return this;
1578
+ }
1579
+ /**
1580
+ * Add option name(s) that conflict with this option.
1581
+ * An error will be displayed if conflicting options are found during parsing.
1582
+ *
1583
+ * @example
1584
+ * new Option('--rgb').conflicts('cmyk');
1585
+ * new Option('--js').conflicts(['ts', 'jsx']);
1586
+ *
1587
+ * @param {(string | string[])} names
1588
+ * @return {Option}
1589
+ */
1590
+ conflicts(names) {
1591
+ this.conflictsWith = this.conflictsWith.concat(names);
1592
+ return this;
1593
+ }
1594
+ /**
1595
+ * Specify implied option values for when this option is set and the implied options are not.
1596
+ *
1597
+ * The custom processing (parseArg) is not called on the implied values.
1598
+ *
1599
+ * @example
1600
+ * program
1601
+ * .addOption(new Option('--log', 'write logging information to file'))
1602
+ * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
1603
+ *
1604
+ * @param {object} impliedOptionValues
1605
+ * @return {Option}
1606
+ */
1607
+ implies(impliedOptionValues) {
1608
+ let newImplied = impliedOptionValues;
1609
+ if (typeof impliedOptionValues === "string") {
1610
+ newImplied = { [impliedOptionValues]: true };
1611
+ }
1612
+ this.implied = Object.assign(this.implied || {}, newImplied);
1613
+ return this;
1614
+ }
1615
+ /**
1616
+ * Set environment variable to check for option value.
1617
+ *
1618
+ * An environment variable is only used if when processed the current option value is
1619
+ * undefined, or the source of the current value is 'default' or 'config' or 'env'.
1620
+ *
1621
+ * @param {string} name
1622
+ * @return {Option}
1623
+ */
1624
+ env(name) {
1625
+ this.envVar = name;
1626
+ return this;
1627
+ }
1628
+ /**
1629
+ * Set the custom handler for processing CLI option arguments into option values.
1630
+ *
1631
+ * @param {Function} [fn]
1632
+ * @return {Option}
1633
+ */
1634
+ argParser(fn) {
1635
+ this.parseArg = fn;
1636
+ return this;
1637
+ }
1638
+ /**
1639
+ * Whether the option is mandatory and must have a value after parsing.
1640
+ *
1641
+ * @param {boolean} [mandatory=true]
1642
+ * @return {Option}
1643
+ */
1644
+ makeOptionMandatory(mandatory = true) {
1645
+ this.mandatory = !!mandatory;
1646
+ return this;
1647
+ }
1648
+ /**
1649
+ * Hide option in help.
1650
+ *
1651
+ * @param {boolean} [hide=true]
1652
+ * @return {Option}
1653
+ */
1654
+ hideHelp(hide = true) {
1655
+ this.hidden = !!hide;
1656
+ return this;
1657
+ }
1658
+ /**
1659
+ * @package
1660
+ */
1661
+ _concatValue(value, previous) {
1662
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
1663
+ return [value];
1664
+ }
1665
+ return previous.concat(value);
1666
+ }
1667
+ /**
1668
+ * Only allow option value to be one of choices.
1669
+ *
1670
+ * @param {string[]} values
1671
+ * @return {Option}
1672
+ */
1673
+ choices(values) {
1674
+ this.argChoices = values.slice();
1675
+ this.parseArg = (arg, previous) => {
1676
+ if (!this.argChoices.includes(arg)) {
1677
+ throw new InvalidArgumentError2(
1678
+ `Allowed choices are ${this.argChoices.join(", ")}.`
1679
+ );
1680
+ }
1681
+ if (this.variadic) {
1682
+ return this._concatValue(arg, previous);
1683
+ }
1684
+ return arg;
1685
+ };
1686
+ return this;
1687
+ }
1688
+ /**
1689
+ * Return option name.
1690
+ *
1691
+ * @return {string}
1692
+ */
1693
+ name() {
1694
+ if (this.long) {
1695
+ return this.long.replace(/^--/, "");
1696
+ }
1697
+ return this.short.replace(/^-/, "");
1698
+ }
1699
+ /**
1700
+ * Return option name, in a camelcase format that can be used
1701
+ * as an object attribute key.
1702
+ *
1703
+ * @return {string}
1704
+ */
1705
+ attributeName() {
1706
+ if (this.negate) {
1707
+ return camelcase(this.name().replace(/^no-/, ""));
1708
+ }
1709
+ return camelcase(this.name());
1710
+ }
1711
+ /**
1712
+ * Check if `arg` matches the short or long flag.
1713
+ *
1714
+ * @param {string} arg
1715
+ * @return {boolean}
1716
+ * @package
1717
+ */
1718
+ is(arg) {
1719
+ return this.short === arg || this.long === arg;
1720
+ }
1721
+ /**
1722
+ * Return whether a boolean option.
1723
+ *
1724
+ * Options are one of boolean, negated, required argument, or optional argument.
1725
+ *
1726
+ * @return {boolean}
1727
+ * @package
1728
+ */
1729
+ isBoolean() {
1730
+ return !this.required && !this.optional && !this.negate;
1731
+ }
1732
+ }
1733
+ class DualOptions {
1734
+ /**
1735
+ * @param {Option[]} options
1736
+ */
1737
+ constructor(options) {
1738
+ this.positiveOptions = /* @__PURE__ */ new Map();
1739
+ this.negativeOptions = /* @__PURE__ */ new Map();
1740
+ this.dualOptions = /* @__PURE__ */ new Set();
1741
+ options.forEach((option2) => {
1742
+ if (option2.negate) {
1743
+ this.negativeOptions.set(option2.attributeName(), option2);
1744
+ } else {
1745
+ this.positiveOptions.set(option2.attributeName(), option2);
1746
+ }
1747
+ });
1748
+ this.negativeOptions.forEach((value, key) => {
1749
+ if (this.positiveOptions.has(key)) {
1750
+ this.dualOptions.add(key);
1751
+ }
1752
+ });
1753
+ }
1754
+ /**
1755
+ * Did the value come from the option, and not from possible matching dual option?
1756
+ *
1757
+ * @param {*} value
1758
+ * @param {Option} option
1759
+ * @returns {boolean}
1760
+ */
1761
+ valueFromOption(value, option2) {
1762
+ const optionKey = option2.attributeName();
1763
+ if (!this.dualOptions.has(optionKey)) return true;
1764
+ const preset = this.negativeOptions.get(optionKey).presetArg;
1765
+ const negativeValue = preset !== void 0 ? preset : false;
1766
+ return option2.negate === (negativeValue === value);
1767
+ }
1768
+ }
1769
+ function camelcase(str) {
1770
+ return str.split("-").reduce((str2, word) => {
1771
+ return str2 + word[0].toUpperCase() + word.slice(1);
1772
+ });
1773
+ }
1774
+ function splitOptionFlags(flags) {
1775
+ let shortFlag;
1776
+ let longFlag;
1777
+ const shortFlagExp = /^-[^-]$/;
1778
+ const longFlagExp = /^--[^-]/;
1779
+ const flagParts = flags.split(/[ |,]+/).concat("guard");
1780
+ if (shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();
1781
+ if (longFlagExp.test(flagParts[0])) longFlag = flagParts.shift();
1782
+ if (!shortFlag && shortFlagExp.test(flagParts[0]))
1783
+ shortFlag = flagParts.shift();
1784
+ if (!shortFlag && longFlagExp.test(flagParts[0])) {
1785
+ shortFlag = longFlag;
1786
+ longFlag = flagParts.shift();
1787
+ }
1788
+ if (flagParts[0].startsWith("-")) {
1789
+ const unsupportedFlag = flagParts[0];
1790
+ const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;
1791
+ if (/^-[^-][^-]/.test(unsupportedFlag))
1792
+ throw new Error(
1793
+ `${baseError}
1794
+ - a short flag is a single dash and a single character
1795
+ - either use a single dash and a single character (for a short flag)
1796
+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`
1797
+ );
1798
+ if (shortFlagExp.test(unsupportedFlag))
1799
+ throw new Error(`${baseError}
1800
+ - too many short flags`);
1801
+ if (longFlagExp.test(unsupportedFlag))
1802
+ throw new Error(`${baseError}
1803
+ - too many long flags`);
1804
+ throw new Error(`${baseError}
1805
+ - unrecognised flag format`);
1806
+ }
1807
+ if (shortFlag === void 0 && longFlag === void 0)
1808
+ throw new Error(
1809
+ `option creation failed due to no flags found in '${flags}'.`
1810
+ );
1811
+ return { shortFlag, longFlag };
1812
+ }
1813
+ option.Option = Option2;
1814
+ option.DualOptions = DualOptions;
1815
+ return option;
1816
+ }
1817
+ var suggestSimilar = {};
1818
+ var hasRequiredSuggestSimilar;
1819
+ function requireSuggestSimilar() {
1820
+ if (hasRequiredSuggestSimilar) return suggestSimilar;
1821
+ hasRequiredSuggestSimilar = 1;
1822
+ const maxDistance = 3;
1823
+ function editDistance(a, b) {
1824
+ if (Math.abs(a.length - b.length) > maxDistance)
1825
+ return Math.max(a.length, b.length);
1826
+ const d = [];
1827
+ for (let i = 0; i <= a.length; i++) {
1828
+ d[i] = [i];
1829
+ }
1830
+ for (let j = 0; j <= b.length; j++) {
1831
+ d[0][j] = j;
1832
+ }
1833
+ for (let j = 1; j <= b.length; j++) {
1834
+ for (let i = 1; i <= a.length; i++) {
1835
+ let cost = 1;
1836
+ if (a[i - 1] === b[j - 1]) {
1837
+ cost = 0;
1838
+ } else {
1839
+ cost = 1;
1840
+ }
1841
+ d[i][j] = Math.min(
1842
+ d[i - 1][j] + 1,
1843
+ // deletion
1844
+ d[i][j - 1] + 1,
1845
+ // insertion
1846
+ d[i - 1][j - 1] + cost
1847
+ // substitution
1848
+ );
1849
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
1850
+ d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
1851
+ }
1852
+ }
1853
+ }
1854
+ return d[a.length][b.length];
1855
+ }
1856
+ function suggestSimilar$1(word, candidates) {
1857
+ if (!candidates || candidates.length === 0) return "";
1858
+ candidates = Array.from(new Set(candidates));
1859
+ const searchingOptions = word.startsWith("--");
1860
+ if (searchingOptions) {
1861
+ word = word.slice(2);
1862
+ candidates = candidates.map((candidate) => candidate.slice(2));
1863
+ }
1864
+ let similar = [];
1865
+ let bestDistance = maxDistance;
1866
+ const minSimilarity = 0.4;
1867
+ candidates.forEach((candidate) => {
1868
+ if (candidate.length <= 1) return;
1869
+ const distance = editDistance(word, candidate);
1870
+ const length = Math.max(word.length, candidate.length);
1871
+ const similarity = (length - distance) / length;
1872
+ if (similarity > minSimilarity) {
1873
+ if (distance < bestDistance) {
1874
+ bestDistance = distance;
1875
+ similar = [candidate];
1876
+ } else if (distance === bestDistance) {
1877
+ similar.push(candidate);
1878
+ }
1879
+ }
1880
+ });
1881
+ similar.sort((a, b) => a.localeCompare(b));
1882
+ if (searchingOptions) {
1883
+ similar = similar.map((candidate) => `--${candidate}`);
1884
+ }
1885
+ if (similar.length > 1) {
1886
+ return `
1887
+ (Did you mean one of ${similar.join(", ")}?)`;
1888
+ }
1889
+ if (similar.length === 1) {
1890
+ return `
1891
+ (Did you mean ${similar[0]}?)`;
1892
+ }
1893
+ return "";
1894
+ }
1895
+ suggestSimilar.suggestSimilar = suggestSimilar$1;
1896
+ return suggestSimilar;
1897
+ }
1898
+ var hasRequiredCommand;
1899
+ function requireCommand() {
1900
+ if (hasRequiredCommand) return command;
1901
+ hasRequiredCommand = 1;
1902
+ const EventEmitter = require$$0.EventEmitter;
1903
+ const childProcess = require$$1;
1904
+ const path$1 = path;
1905
+ const fs$1 = fs;
1906
+ const process2 = require$$4;
1907
+ const { Argument: Argument2, humanReadableArgName } = requireArgument();
1908
+ const { CommanderError: CommanderError2 } = requireError();
1909
+ const { Help: Help2, stripColor } = requireHelp();
1910
+ const { Option: Option2, DualOptions } = requireOption();
1911
+ const { suggestSimilar: suggestSimilar2 } = requireSuggestSimilar();
1912
+ class Command2 extends EventEmitter {
1913
+ /**
1914
+ * Initialize a new `Command`.
1915
+ *
1916
+ * @param {string} [name]
1917
+ */
1918
+ constructor(name) {
1919
+ super();
1920
+ this.commands = [];
1921
+ this.options = [];
1922
+ this.parent = null;
1923
+ this._allowUnknownOption = false;
1924
+ this._allowExcessArguments = false;
1925
+ this.registeredArguments = [];
1926
+ this._args = this.registeredArguments;
1927
+ this.args = [];
1928
+ this.rawArgs = [];
1929
+ this.processedArgs = [];
1930
+ this._scriptPath = null;
1931
+ this._name = name || "";
1932
+ this._optionValues = {};
1933
+ this._optionValueSources = {};
1934
+ this._storeOptionsAsProperties = false;
1935
+ this._actionHandler = null;
1936
+ this._executableHandler = false;
1937
+ this._executableFile = null;
1938
+ this._executableDir = null;
1939
+ this._defaultCommandName = null;
1940
+ this._exitCallback = null;
1941
+ this._aliases = [];
1942
+ this._combineFlagAndOptionalValue = true;
1943
+ this._description = "";
1944
+ this._summary = "";
1945
+ this._argsDescription = void 0;
1946
+ this._enablePositionalOptions = false;
1947
+ this._passThroughOptions = false;
1948
+ this._lifeCycleHooks = {};
1949
+ this._showHelpAfterError = false;
1950
+ this._showSuggestionAfterError = true;
1951
+ this._savedState = null;
1952
+ this._outputConfiguration = {
1953
+ writeOut: (str) => process2.stdout.write(str),
1954
+ writeErr: (str) => process2.stderr.write(str),
1955
+ outputError: (str, write) => write(str),
1956
+ getOutHelpWidth: () => process2.stdout.isTTY ? process2.stdout.columns : void 0,
1957
+ getErrHelpWidth: () => process2.stderr.isTTY ? process2.stderr.columns : void 0,
1958
+ getOutHasColors: () => useColor() ?? (process2.stdout.isTTY && process2.stdout.hasColors?.()),
1959
+ getErrHasColors: () => useColor() ?? (process2.stderr.isTTY && process2.stderr.hasColors?.()),
1960
+ stripColor: (str) => stripColor(str)
1961
+ };
1962
+ this._hidden = false;
1963
+ this._helpOption = void 0;
1964
+ this._addImplicitHelpCommand = void 0;
1965
+ this._helpCommand = void 0;
1966
+ this._helpConfiguration = {};
1967
+ }
1968
+ /**
1969
+ * Copy settings that are useful to have in common across root command and subcommands.
1970
+ *
1971
+ * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
1972
+ *
1973
+ * @param {Command} sourceCommand
1974
+ * @return {Command} `this` command for chaining
1975
+ */
1976
+ copyInheritedSettings(sourceCommand) {
1977
+ this._outputConfiguration = sourceCommand._outputConfiguration;
1978
+ this._helpOption = sourceCommand._helpOption;
1979
+ this._helpCommand = sourceCommand._helpCommand;
1980
+ this._helpConfiguration = sourceCommand._helpConfiguration;
1981
+ this._exitCallback = sourceCommand._exitCallback;
1982
+ this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
1983
+ this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
1984
+ this._allowExcessArguments = sourceCommand._allowExcessArguments;
1985
+ this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
1986
+ this._showHelpAfterError = sourceCommand._showHelpAfterError;
1987
+ this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
1988
+ return this;
1989
+ }
1990
+ /**
1991
+ * @returns {Command[]}
1992
+ * @private
1993
+ */
1994
+ _getCommandAndAncestors() {
1995
+ const result = [];
1996
+ for (let command2 = this; command2; command2 = command2.parent) {
1997
+ result.push(command2);
1998
+ }
1999
+ return result;
2000
+ }
2001
+ /**
2002
+ * Define a command.
2003
+ *
2004
+ * There are two styles of command: pay attention to where to put the description.
2005
+ *
2006
+ * @example
2007
+ * // Command implemented using action handler (description is supplied separately to `.command`)
2008
+ * program
2009
+ * .command('clone <source> [destination]')
2010
+ * .description('clone a repository into a newly created directory')
2011
+ * .action((source, destination) => {
2012
+ * console.log('clone command called');
2013
+ * });
2014
+ *
2015
+ * // Command implemented using separate executable file (description is second parameter to `.command`)
2016
+ * program
2017
+ * .command('start <service>', 'start named service')
2018
+ * .command('stop [service]', 'stop named service, or all if no name supplied');
2019
+ *
2020
+ * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
2021
+ * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
2022
+ * @param {object} [execOpts] - configuration options (for executable)
2023
+ * @return {Command} returns new command for action handler, or `this` for executable command
2024
+ */
2025
+ command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
2026
+ let desc = actionOptsOrExecDesc;
2027
+ let opts = execOpts;
2028
+ if (typeof desc === "object" && desc !== null) {
2029
+ opts = desc;
2030
+ desc = null;
2031
+ }
2032
+ opts = opts || {};
2033
+ const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
2034
+ const cmd = this.createCommand(name);
2035
+ if (desc) {
2036
+ cmd.description(desc);
2037
+ cmd._executableHandler = true;
2038
+ }
2039
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
2040
+ cmd._hidden = !!(opts.noHelp || opts.hidden);
2041
+ cmd._executableFile = opts.executableFile || null;
2042
+ if (args) cmd.arguments(args);
2043
+ this._registerCommand(cmd);
2044
+ cmd.parent = this;
2045
+ cmd.copyInheritedSettings(this);
2046
+ if (desc) return this;
2047
+ return cmd;
2048
+ }
2049
+ /**
2050
+ * Factory routine to create a new unattached command.
2051
+ *
2052
+ * See .command() for creating an attached subcommand, which uses this routine to
2053
+ * create the command. You can override createCommand to customise subcommands.
2054
+ *
2055
+ * @param {string} [name]
2056
+ * @return {Command} new command
2057
+ */
2058
+ createCommand(name) {
2059
+ return new Command2(name);
2060
+ }
2061
+ /**
2062
+ * You can customise the help with a subclass of Help by overriding createHelp,
2063
+ * or by overriding Help properties using configureHelp().
2064
+ *
2065
+ * @return {Help}
2066
+ */
2067
+ createHelp() {
2068
+ return Object.assign(new Help2(), this.configureHelp());
2069
+ }
2070
+ /**
2071
+ * You can customise the help by overriding Help properties using configureHelp(),
2072
+ * or with a subclass of Help by overriding createHelp().
2073
+ *
2074
+ * @param {object} [configuration] - configuration options
2075
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
2076
+ */
2077
+ configureHelp(configuration) {
2078
+ if (configuration === void 0) return this._helpConfiguration;
2079
+ this._helpConfiguration = configuration;
2080
+ return this;
2081
+ }
2082
+ /**
2083
+ * The default output goes to stdout and stderr. You can customise this for special
2084
+ * applications. You can also customise the display of errors by overriding outputError.
2085
+ *
2086
+ * The configuration properties are all functions:
2087
+ *
2088
+ * // change how output being written, defaults to stdout and stderr
2089
+ * writeOut(str)
2090
+ * writeErr(str)
2091
+ * // change how output being written for errors, defaults to writeErr
2092
+ * outputError(str, write) // used for displaying errors and not used for displaying help
2093
+ * // specify width for wrapping help
2094
+ * getOutHelpWidth()
2095
+ * getErrHelpWidth()
2096
+ * // color support, currently only used with Help
2097
+ * getOutHasColors()
2098
+ * getErrHasColors()
2099
+ * stripColor() // used to remove ANSI escape codes if output does not have colors
2100
+ *
2101
+ * @param {object} [configuration] - configuration options
2102
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
2103
+ */
2104
+ configureOutput(configuration) {
2105
+ if (configuration === void 0) return this._outputConfiguration;
2106
+ Object.assign(this._outputConfiguration, configuration);
2107
+ return this;
2108
+ }
2109
+ /**
2110
+ * Display the help or a custom message after an error occurs.
2111
+ *
2112
+ * @param {(boolean|string)} [displayHelp]
2113
+ * @return {Command} `this` command for chaining
2114
+ */
2115
+ showHelpAfterError(displayHelp = true) {
2116
+ if (typeof displayHelp !== "string") displayHelp = !!displayHelp;
2117
+ this._showHelpAfterError = displayHelp;
2118
+ return this;
2119
+ }
2120
+ /**
2121
+ * Display suggestion of similar commands for unknown commands, or options for unknown options.
2122
+ *
2123
+ * @param {boolean} [displaySuggestion]
2124
+ * @return {Command} `this` command for chaining
2125
+ */
2126
+ showSuggestionAfterError(displaySuggestion = true) {
2127
+ this._showSuggestionAfterError = !!displaySuggestion;
2128
+ return this;
2129
+ }
2130
+ /**
2131
+ * Add a prepared subcommand.
2132
+ *
2133
+ * See .command() for creating an attached subcommand which inherits settings from its parent.
2134
+ *
2135
+ * @param {Command} cmd - new subcommand
2136
+ * @param {object} [opts] - configuration options
2137
+ * @return {Command} `this` command for chaining
2138
+ */
2139
+ addCommand(cmd, opts) {
2140
+ if (!cmd._name) {
2141
+ throw new Error(`Command passed to .addCommand() must have a name
2142
+ - specify the name in Command constructor or using .name()`);
2143
+ }
2144
+ opts = opts || {};
2145
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
2146
+ if (opts.noHelp || opts.hidden) cmd._hidden = true;
2147
+ this._registerCommand(cmd);
2148
+ cmd.parent = this;
2149
+ cmd._checkForBrokenPassThrough();
2150
+ return this;
2151
+ }
2152
+ /**
2153
+ * Factory routine to create a new unattached argument.
2154
+ *
2155
+ * See .argument() for creating an attached argument, which uses this routine to
2156
+ * create the argument. You can override createArgument to return a custom argument.
2157
+ *
2158
+ * @param {string} name
2159
+ * @param {string} [description]
2160
+ * @return {Argument} new argument
2161
+ */
2162
+ createArgument(name, description) {
2163
+ return new Argument2(name, description);
2164
+ }
2165
+ /**
2166
+ * Define argument syntax for command.
2167
+ *
2168
+ * The default is that the argument is required, and you can explicitly
2169
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
2170
+ *
2171
+ * @example
2172
+ * program.argument('<input-file>');
2173
+ * program.argument('[output-file]');
2174
+ *
2175
+ * @param {string} name
2176
+ * @param {string} [description]
2177
+ * @param {(Function|*)} [fn] - custom argument processing function
2178
+ * @param {*} [defaultValue]
2179
+ * @return {Command} `this` command for chaining
2180
+ */
2181
+ argument(name, description, fn, defaultValue) {
2182
+ const argument2 = this.createArgument(name, description);
2183
+ if (typeof fn === "function") {
2184
+ argument2.default(defaultValue).argParser(fn);
2185
+ } else {
2186
+ argument2.default(fn);
2187
+ }
2188
+ this.addArgument(argument2);
2189
+ return this;
2190
+ }
2191
+ /**
2192
+ * Define argument syntax for command, adding multiple at once (without descriptions).
2193
+ *
2194
+ * See also .argument().
2195
+ *
2196
+ * @example
2197
+ * program.arguments('<cmd> [env]');
2198
+ *
2199
+ * @param {string} names
2200
+ * @return {Command} `this` command for chaining
2201
+ */
2202
+ arguments(names) {
2203
+ names.trim().split(/ +/).forEach((detail) => {
2204
+ this.argument(detail);
2205
+ });
2206
+ return this;
2207
+ }
2208
+ /**
2209
+ * Define argument syntax for command, adding a prepared argument.
2210
+ *
2211
+ * @param {Argument} argument
2212
+ * @return {Command} `this` command for chaining
2213
+ */
2214
+ addArgument(argument2) {
2215
+ const previousArgument = this.registeredArguments.slice(-1)[0];
2216
+ if (previousArgument && previousArgument.variadic) {
2217
+ throw new Error(
2218
+ `only the last argument can be variadic '${previousArgument.name()}'`
2219
+ );
2220
+ }
2221
+ if (argument2.required && argument2.defaultValue !== void 0 && argument2.parseArg === void 0) {
2222
+ throw new Error(
2223
+ `a default value for a required argument is never used: '${argument2.name()}'`
2224
+ );
2225
+ }
2226
+ this.registeredArguments.push(argument2);
2227
+ return this;
2228
+ }
2229
+ /**
2230
+ * Customise or override default help command. By default a help command is automatically added if your command has subcommands.
2231
+ *
2232
+ * @example
2233
+ * program.helpCommand('help [cmd]');
2234
+ * program.helpCommand('help [cmd]', 'show help');
2235
+ * program.helpCommand(false); // suppress default help command
2236
+ * program.helpCommand(true); // add help command even if no subcommands
2237
+ *
2238
+ * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added
2239
+ * @param {string} [description] - custom description
2240
+ * @return {Command} `this` command for chaining
2241
+ */
2242
+ helpCommand(enableOrNameAndArgs, description) {
2243
+ if (typeof enableOrNameAndArgs === "boolean") {
2244
+ this._addImplicitHelpCommand = enableOrNameAndArgs;
2245
+ return this;
2246
+ }
2247
+ enableOrNameAndArgs = enableOrNameAndArgs ?? "help [command]";
2248
+ const [, helpName, helpArgs] = enableOrNameAndArgs.match(/([^ ]+) *(.*)/);
2249
+ const helpDescription = description ?? "display help for command";
2250
+ const helpCommand = this.createCommand(helpName);
2251
+ helpCommand.helpOption(false);
2252
+ if (helpArgs) helpCommand.arguments(helpArgs);
2253
+ if (helpDescription) helpCommand.description(helpDescription);
2254
+ this._addImplicitHelpCommand = true;
2255
+ this._helpCommand = helpCommand;
2256
+ return this;
2257
+ }
2258
+ /**
2259
+ * Add prepared custom help command.
2260
+ *
2261
+ * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`
2262
+ * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only
2263
+ * @return {Command} `this` command for chaining
2264
+ */
2265
+ addHelpCommand(helpCommand, deprecatedDescription) {
2266
+ if (typeof helpCommand !== "object") {
2267
+ this.helpCommand(helpCommand, deprecatedDescription);
2268
+ return this;
2269
+ }
2270
+ this._addImplicitHelpCommand = true;
2271
+ this._helpCommand = helpCommand;
2272
+ return this;
2273
+ }
2274
+ /**
2275
+ * Lazy create help command.
2276
+ *
2277
+ * @return {(Command|null)}
2278
+ * @package
2279
+ */
2280
+ _getHelpCommand() {
2281
+ const hasImplicitHelpCommand = this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"));
2282
+ if (hasImplicitHelpCommand) {
2283
+ if (this._helpCommand === void 0) {
2284
+ this.helpCommand(void 0, void 0);
2285
+ }
2286
+ return this._helpCommand;
2287
+ }
2288
+ return null;
2289
+ }
2290
+ /**
2291
+ * Add hook for life cycle event.
2292
+ *
2293
+ * @param {string} event
2294
+ * @param {Function} listener
2295
+ * @return {Command} `this` command for chaining
2296
+ */
2297
+ hook(event, listener) {
2298
+ const allowedValues = ["preSubcommand", "preAction", "postAction"];
2299
+ if (!allowedValues.includes(event)) {
2300
+ throw new Error(`Unexpected value for event passed to hook : '${event}'.
2301
+ Expecting one of '${allowedValues.join("', '")}'`);
2302
+ }
2303
+ if (this._lifeCycleHooks[event]) {
2304
+ this._lifeCycleHooks[event].push(listener);
2305
+ } else {
2306
+ this._lifeCycleHooks[event] = [listener];
2307
+ }
2308
+ return this;
2309
+ }
2310
+ /**
2311
+ * Register callback to use as replacement for calling process.exit.
2312
+ *
2313
+ * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
2314
+ * @return {Command} `this` command for chaining
2315
+ */
2316
+ exitOverride(fn) {
2317
+ if (fn) {
2318
+ this._exitCallback = fn;
2319
+ } else {
2320
+ this._exitCallback = (err) => {
2321
+ if (err.code !== "commander.executeSubCommandAsync") {
2322
+ throw err;
2323
+ }
2324
+ };
2325
+ }
2326
+ return this;
2327
+ }
2328
+ /**
2329
+ * Call process.exit, and _exitCallback if defined.
2330
+ *
2331
+ * @param {number} exitCode exit code for using with process.exit
2332
+ * @param {string} code an id string representing the error
2333
+ * @param {string} message human-readable description of the error
2334
+ * @return never
2335
+ * @private
2336
+ */
2337
+ _exit(exitCode, code, message) {
2338
+ if (this._exitCallback) {
2339
+ this._exitCallback(new CommanderError2(exitCode, code, message));
2340
+ }
2341
+ process2.exit(exitCode);
2342
+ }
2343
+ /**
2344
+ * Register callback `fn` for the command.
2345
+ *
2346
+ * @example
2347
+ * program
2348
+ * .command('serve')
2349
+ * .description('start service')
2350
+ * .action(function() {
2351
+ * // do work here
2352
+ * });
2353
+ *
2354
+ * @param {Function} fn
2355
+ * @return {Command} `this` command for chaining
2356
+ */
2357
+ action(fn) {
2358
+ const listener = (args) => {
2359
+ const expectedArgsCount = this.registeredArguments.length;
2360
+ const actionArgs = args.slice(0, expectedArgsCount);
2361
+ if (this._storeOptionsAsProperties) {
2362
+ actionArgs[expectedArgsCount] = this;
2363
+ } else {
2364
+ actionArgs[expectedArgsCount] = this.opts();
2365
+ }
2366
+ actionArgs.push(this);
2367
+ return fn.apply(this, actionArgs);
2368
+ };
2369
+ this._actionHandler = listener;
2370
+ return this;
2371
+ }
2372
+ /**
2373
+ * Factory routine to create a new unattached option.
2374
+ *
2375
+ * See .option() for creating an attached option, which uses this routine to
2376
+ * create the option. You can override createOption to return a custom option.
2377
+ *
2378
+ * @param {string} flags
2379
+ * @param {string} [description]
2380
+ * @return {Option} new option
2381
+ */
2382
+ createOption(flags, description) {
2383
+ return new Option2(flags, description);
2384
+ }
2385
+ /**
2386
+ * Wrap parseArgs to catch 'commander.invalidArgument'.
2387
+ *
2388
+ * @param {(Option | Argument)} target
2389
+ * @param {string} value
2390
+ * @param {*} previous
2391
+ * @param {string} invalidArgumentMessage
2392
+ * @private
2393
+ */
2394
+ _callParseArg(target, value, previous, invalidArgumentMessage) {
2395
+ try {
2396
+ return target.parseArg(value, previous);
2397
+ } catch (err) {
2398
+ if (err.code === "commander.invalidArgument") {
2399
+ const message = `${invalidArgumentMessage} ${err.message}`;
2400
+ this.error(message, { exitCode: err.exitCode, code: err.code });
2401
+ }
2402
+ throw err;
2403
+ }
2404
+ }
2405
+ /**
2406
+ * Check for option flag conflicts.
2407
+ * Register option if no conflicts found, or throw on conflict.
2408
+ *
2409
+ * @param {Option} option
2410
+ * @private
2411
+ */
2412
+ _registerOption(option2) {
2413
+ const matchingOption = option2.short && this._findOption(option2.short) || option2.long && this._findOption(option2.long);
2414
+ if (matchingOption) {
2415
+ const matchingFlag = option2.long && this._findOption(option2.long) ? option2.long : option2.short;
2416
+ throw new Error(`Cannot add option '${option2.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
2417
+ - already used by option '${matchingOption.flags}'`);
2418
+ }
2419
+ this.options.push(option2);
2420
+ }
2421
+ /**
2422
+ * Check for command name and alias conflicts with existing commands.
2423
+ * Register command if no conflicts found, or throw on conflict.
2424
+ *
2425
+ * @param {Command} command
2426
+ * @private
2427
+ */
2428
+ _registerCommand(command2) {
2429
+ const knownBy = (cmd) => {
2430
+ return [cmd.name()].concat(cmd.aliases());
2431
+ };
2432
+ const alreadyUsed = knownBy(command2).find(
2433
+ (name) => this._findCommand(name)
2434
+ );
2435
+ if (alreadyUsed) {
2436
+ const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
2437
+ const newCmd = knownBy(command2).join("|");
2438
+ throw new Error(
2439
+ `cannot add command '${newCmd}' as already have command '${existingCmd}'`
2440
+ );
2441
+ }
2442
+ this.commands.push(command2);
2443
+ }
2444
+ /**
2445
+ * Add an option.
2446
+ *
2447
+ * @param {Option} option
2448
+ * @return {Command} `this` command for chaining
2449
+ */
2450
+ addOption(option2) {
2451
+ this._registerOption(option2);
2452
+ const oname = option2.name();
2453
+ const name = option2.attributeName();
2454
+ if (option2.negate) {
2455
+ const positiveLongFlag = option2.long.replace(/^--no-/, "--");
2456
+ if (!this._findOption(positiveLongFlag)) {
2457
+ this.setOptionValueWithSource(
2458
+ name,
2459
+ option2.defaultValue === void 0 ? true : option2.defaultValue,
2460
+ "default"
2461
+ );
2462
+ }
2463
+ } else if (option2.defaultValue !== void 0) {
2464
+ this.setOptionValueWithSource(name, option2.defaultValue, "default");
2465
+ }
2466
+ const handleOptionValue = (val, invalidValueMessage, valueSource) => {
2467
+ if (val == null && option2.presetArg !== void 0) {
2468
+ val = option2.presetArg;
2469
+ }
2470
+ const oldValue = this.getOptionValue(name);
2471
+ if (val !== null && option2.parseArg) {
2472
+ val = this._callParseArg(option2, val, oldValue, invalidValueMessage);
2473
+ } else if (val !== null && option2.variadic) {
2474
+ val = option2._concatValue(val, oldValue);
2475
+ }
2476
+ if (val == null) {
2477
+ if (option2.negate) {
2478
+ val = false;
2479
+ } else if (option2.isBoolean() || option2.optional) {
2480
+ val = true;
2481
+ } else {
2482
+ val = "";
2483
+ }
2484
+ }
2485
+ this.setOptionValueWithSource(name, val, valueSource);
2486
+ };
2487
+ this.on("option:" + oname, (val) => {
2488
+ const invalidValueMessage = `error: option '${option2.flags}' argument '${val}' is invalid.`;
2489
+ handleOptionValue(val, invalidValueMessage, "cli");
2490
+ });
2491
+ if (option2.envVar) {
2492
+ this.on("optionEnv:" + oname, (val) => {
2493
+ const invalidValueMessage = `error: option '${option2.flags}' value '${val}' from env '${option2.envVar}' is invalid.`;
2494
+ handleOptionValue(val, invalidValueMessage, "env");
2495
+ });
2496
+ }
2497
+ return this;
2498
+ }
2499
+ /**
2500
+ * Internal implementation shared by .option() and .requiredOption()
2501
+ *
2502
+ * @return {Command} `this` command for chaining
2503
+ * @private
2504
+ */
2505
+ _optionEx(config, flags, description, fn, defaultValue) {
2506
+ if (typeof flags === "object" && flags instanceof Option2) {
2507
+ throw new Error(
2508
+ "To add an Option object use addOption() instead of option() or requiredOption()"
2509
+ );
2510
+ }
2511
+ const option2 = this.createOption(flags, description);
2512
+ option2.makeOptionMandatory(!!config.mandatory);
2513
+ if (typeof fn === "function") {
2514
+ option2.default(defaultValue).argParser(fn);
2515
+ } else if (fn instanceof RegExp) {
2516
+ const regex = fn;
2517
+ fn = (val, def) => {
2518
+ const m = regex.exec(val);
2519
+ return m ? m[0] : def;
2520
+ };
2521
+ option2.default(defaultValue).argParser(fn);
2522
+ } else {
2523
+ option2.default(fn);
2524
+ }
2525
+ return this.addOption(option2);
2526
+ }
2527
+ /**
2528
+ * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
2529
+ *
2530
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
2531
+ * option-argument is indicated by `<>` and an optional option-argument by `[]`.
2532
+ *
2533
+ * See the README for more details, and see also addOption() and requiredOption().
2534
+ *
2535
+ * @example
2536
+ * program
2537
+ * .option('-p, --pepper', 'add pepper')
2538
+ * .option('--pt, --pizza-type <TYPE>', 'type of pizza') // required option-argument
2539
+ * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
2540
+ * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
2541
+ *
2542
+ * @param {string} flags
2543
+ * @param {string} [description]
2544
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
2545
+ * @param {*} [defaultValue]
2546
+ * @return {Command} `this` command for chaining
2547
+ */
2548
+ option(flags, description, parseArg, defaultValue) {
2549
+ return this._optionEx({}, flags, description, parseArg, defaultValue);
2550
+ }
2551
+ /**
2552
+ * Add a required option which must have a value after parsing. This usually means
2553
+ * the option must be specified on the command line. (Otherwise the same as .option().)
2554
+ *
2555
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
2556
+ *
2557
+ * @param {string} flags
2558
+ * @param {string} [description]
2559
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
2560
+ * @param {*} [defaultValue]
2561
+ * @return {Command} `this` command for chaining
2562
+ */
2563
+ requiredOption(flags, description, parseArg, defaultValue) {
2564
+ return this._optionEx(
2565
+ { mandatory: true },
2566
+ flags,
2567
+ description,
2568
+ parseArg,
2569
+ defaultValue
2570
+ );
2571
+ }
2572
+ /**
2573
+ * Alter parsing of short flags with optional values.
2574
+ *
2575
+ * @example
2576
+ * // for `.option('-f,--flag [value]'):
2577
+ * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
2578
+ * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
2579
+ *
2580
+ * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.
2581
+ * @return {Command} `this` command for chaining
2582
+ */
2583
+ combineFlagAndOptionalValue(combine = true) {
2584
+ this._combineFlagAndOptionalValue = !!combine;
2585
+ return this;
2586
+ }
2587
+ /**
2588
+ * Allow unknown options on the command line.
2589
+ *
2590
+ * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.
2591
+ * @return {Command} `this` command for chaining
2592
+ */
2593
+ allowUnknownOption(allowUnknown = true) {
2594
+ this._allowUnknownOption = !!allowUnknown;
2595
+ return this;
2596
+ }
2597
+ /**
2598
+ * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
2599
+ *
2600
+ * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.
2601
+ * @return {Command} `this` command for chaining
2602
+ */
2603
+ allowExcessArguments(allowExcess = true) {
2604
+ this._allowExcessArguments = !!allowExcess;
2605
+ return this;
2606
+ }
2607
+ /**
2608
+ * Enable positional options. Positional means global options are specified before subcommands which lets
2609
+ * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
2610
+ * The default behaviour is non-positional and global options may appear anywhere on the command line.
2611
+ *
2612
+ * @param {boolean} [positional]
2613
+ * @return {Command} `this` command for chaining
2614
+ */
2615
+ enablePositionalOptions(positional = true) {
2616
+ this._enablePositionalOptions = !!positional;
2617
+ return this;
2618
+ }
2619
+ /**
2620
+ * Pass through options that come after command-arguments rather than treat them as command-options,
2621
+ * so actual command-options come before command-arguments. Turning this on for a subcommand requires
2622
+ * positional options to have been enabled on the program (parent commands).
2623
+ * The default behaviour is non-positional and options may appear before or after command-arguments.
2624
+ *
2625
+ * @param {boolean} [passThrough] for unknown options.
2626
+ * @return {Command} `this` command for chaining
2627
+ */
2628
+ passThroughOptions(passThrough = true) {
2629
+ this._passThroughOptions = !!passThrough;
2630
+ this._checkForBrokenPassThrough();
2631
+ return this;
2632
+ }
2633
+ /**
2634
+ * @private
2635
+ */
2636
+ _checkForBrokenPassThrough() {
2637
+ if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {
2638
+ throw new Error(
2639
+ `passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`
2640
+ );
2641
+ }
2642
+ }
2643
+ /**
2644
+ * Whether to store option values as properties on command object,
2645
+ * or store separately (specify false). In both cases the option values can be accessed using .opts().
2646
+ *
2647
+ * @param {boolean} [storeAsProperties=true]
2648
+ * @return {Command} `this` command for chaining
2649
+ */
2650
+ storeOptionsAsProperties(storeAsProperties = true) {
2651
+ if (this.options.length) {
2652
+ throw new Error("call .storeOptionsAsProperties() before adding options");
2653
+ }
2654
+ if (Object.keys(this._optionValues).length) {
2655
+ throw new Error(
2656
+ "call .storeOptionsAsProperties() before setting option values"
2657
+ );
2658
+ }
2659
+ this._storeOptionsAsProperties = !!storeAsProperties;
2660
+ return this;
2661
+ }
2662
+ /**
2663
+ * Retrieve option value.
2664
+ *
2665
+ * @param {string} key
2666
+ * @return {object} value
2667
+ */
2668
+ getOptionValue(key) {
2669
+ if (this._storeOptionsAsProperties) {
2670
+ return this[key];
2671
+ }
2672
+ return this._optionValues[key];
2673
+ }
2674
+ /**
2675
+ * Store option value.
2676
+ *
2677
+ * @param {string} key
2678
+ * @param {object} value
2679
+ * @return {Command} `this` command for chaining
2680
+ */
2681
+ setOptionValue(key, value) {
2682
+ return this.setOptionValueWithSource(key, value, void 0);
2683
+ }
2684
+ /**
2685
+ * Store option value and where the value came from.
2686
+ *
2687
+ * @param {string} key
2688
+ * @param {object} value
2689
+ * @param {string} source - expected values are default/config/env/cli/implied
2690
+ * @return {Command} `this` command for chaining
2691
+ */
2692
+ setOptionValueWithSource(key, value, source) {
2693
+ if (this._storeOptionsAsProperties) {
2694
+ this[key] = value;
2695
+ } else {
2696
+ this._optionValues[key] = value;
2697
+ }
2698
+ this._optionValueSources[key] = source;
2699
+ return this;
2700
+ }
2701
+ /**
2702
+ * Get source of option value.
2703
+ * Expected values are default | config | env | cli | implied
2704
+ *
2705
+ * @param {string} key
2706
+ * @return {string}
2707
+ */
2708
+ getOptionValueSource(key) {
2709
+ return this._optionValueSources[key];
2710
+ }
2711
+ /**
2712
+ * Get source of option value. See also .optsWithGlobals().
2713
+ * Expected values are default | config | env | cli | implied
2714
+ *
2715
+ * @param {string} key
2716
+ * @return {string}
2717
+ */
2718
+ getOptionValueSourceWithGlobals(key) {
2719
+ let source;
2720
+ this._getCommandAndAncestors().forEach((cmd) => {
2721
+ if (cmd.getOptionValueSource(key) !== void 0) {
2722
+ source = cmd.getOptionValueSource(key);
2723
+ }
2724
+ });
2725
+ return source;
2726
+ }
2727
+ /**
2728
+ * Get user arguments from implied or explicit arguments.
2729
+ * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
2730
+ *
2731
+ * @private
2732
+ */
2733
+ _prepareUserArgs(argv, parseOptions) {
2734
+ if (argv !== void 0 && !Array.isArray(argv)) {
2735
+ throw new Error("first parameter to parse must be array or undefined");
2736
+ }
2737
+ parseOptions = parseOptions || {};
2738
+ if (argv === void 0 && parseOptions.from === void 0) {
2739
+ if (process2.versions?.electron) {
2740
+ parseOptions.from = "electron";
2741
+ }
2742
+ const execArgv = process2.execArgv ?? [];
2743
+ if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) {
2744
+ parseOptions.from = "eval";
2745
+ }
2746
+ }
2747
+ if (argv === void 0) {
2748
+ argv = process2.argv;
2749
+ }
2750
+ this.rawArgs = argv.slice();
2751
+ let userArgs;
2752
+ switch (parseOptions.from) {
2753
+ case void 0:
2754
+ case "node":
2755
+ this._scriptPath = argv[1];
2756
+ userArgs = argv.slice(2);
2757
+ break;
2758
+ case "electron":
2759
+ if (process2.defaultApp) {
2760
+ this._scriptPath = argv[1];
2761
+ userArgs = argv.slice(2);
2762
+ } else {
2763
+ userArgs = argv.slice(1);
2764
+ }
2765
+ break;
2766
+ case "user":
2767
+ userArgs = argv.slice(0);
2768
+ break;
2769
+ case "eval":
2770
+ userArgs = argv.slice(1);
2771
+ break;
2772
+ default:
2773
+ throw new Error(
2774
+ `unexpected parse option { from: '${parseOptions.from}' }`
2775
+ );
2776
+ }
2777
+ if (!this._name && this._scriptPath)
2778
+ this.nameFromFilename(this._scriptPath);
2779
+ this._name = this._name || "program";
2780
+ return userArgs;
2781
+ }
2782
+ /**
2783
+ * Parse `argv`, setting options and invoking commands when defined.
2784
+ *
2785
+ * Use parseAsync instead of parse if any of your action handlers are async.
2786
+ *
2787
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
2788
+ *
2789
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
2790
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
2791
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
2792
+ * - `'user'`: just user arguments
2793
+ *
2794
+ * @example
2795
+ * program.parse(); // parse process.argv and auto-detect electron and special node flags
2796
+ * program.parse(process.argv); // assume argv[0] is app and argv[1] is script
2797
+ * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
2798
+ *
2799
+ * @param {string[]} [argv] - optional, defaults to process.argv
2800
+ * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron
2801
+ * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
2802
+ * @return {Command} `this` command for chaining
2803
+ */
2804
+ parse(argv, parseOptions) {
2805
+ this._prepareForParse();
2806
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
2807
+ this._parseCommand([], userArgs);
2808
+ return this;
2809
+ }
2810
+ /**
2811
+ * Parse `argv`, setting options and invoking commands when defined.
2812
+ *
2813
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
2814
+ *
2815
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
2816
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
2817
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
2818
+ * - `'user'`: just user arguments
2819
+ *
2820
+ * @example
2821
+ * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags
2822
+ * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script
2823
+ * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
2824
+ *
2825
+ * @param {string[]} [argv]
2826
+ * @param {object} [parseOptions]
2827
+ * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
2828
+ * @return {Promise}
2829
+ */
2830
+ async parseAsync(argv, parseOptions) {
2831
+ this._prepareForParse();
2832
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
2833
+ await this._parseCommand([], userArgs);
2834
+ return this;
2835
+ }
2836
+ _prepareForParse() {
2837
+ if (this._savedState === null) {
2838
+ this.saveStateBeforeParse();
2839
+ } else {
2840
+ this.restoreStateBeforeParse();
2841
+ }
2842
+ }
2843
+ /**
2844
+ * Called the first time parse is called to save state and allow a restore before subsequent calls to parse.
2845
+ * Not usually called directly, but available for subclasses to save their custom state.
2846
+ *
2847
+ * This is called in a lazy way. Only commands used in parsing chain will have state saved.
2848
+ */
2849
+ saveStateBeforeParse() {
2850
+ this._savedState = {
2851
+ // name is stable if supplied by author, but may be unspecified for root command and deduced during parsing
2852
+ _name: this._name,
2853
+ // option values before parse have default values (including false for negated options)
2854
+ // shallow clones
2855
+ _optionValues: { ...this._optionValues },
2856
+ _optionValueSources: { ...this._optionValueSources }
2857
+ };
2858
+ }
2859
+ /**
2860
+ * Restore state before parse for calls after the first.
2861
+ * Not usually called directly, but available for subclasses to save their custom state.
2862
+ *
2863
+ * This is called in a lazy way. Only commands used in parsing chain will have state restored.
2864
+ */
2865
+ restoreStateBeforeParse() {
2866
+ if (this._storeOptionsAsProperties)
2867
+ throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
2868
+ - either make a new Command for each call to parse, or stop storing options as properties`);
2869
+ this._name = this._savedState._name;
2870
+ this._scriptPath = null;
2871
+ this.rawArgs = [];
2872
+ this._optionValues = { ...this._savedState._optionValues };
2873
+ this._optionValueSources = { ...this._savedState._optionValueSources };
2874
+ this.args = [];
2875
+ this.processedArgs = [];
2876
+ }
2877
+ /**
2878
+ * Throw if expected executable is missing. Add lots of help for author.
2879
+ *
2880
+ * @param {string} executableFile
2881
+ * @param {string} executableDir
2882
+ * @param {string} subcommandName
2883
+ */
2884
+ _checkForMissingExecutable(executableFile, executableDir, subcommandName) {
2885
+ if (fs$1.existsSync(executableFile)) return;
2886
+ const executableDirMessage = executableDir ? `searched for local subcommand relative to directory '${executableDir}'` : "no directory for search for local subcommand, use .executableDir() to supply a custom directory";
2887
+ const executableMissing = `'${executableFile}' does not exist
2888
+ - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
2889
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
2890
+ - ${executableDirMessage}`;
2891
+ throw new Error(executableMissing);
2892
+ }
2893
+ /**
2894
+ * Execute a sub-command executable.
2895
+ *
2896
+ * @private
2897
+ */
2898
+ _executeSubCommand(subcommand, args) {
2899
+ args = args.slice();
2900
+ let launchWithNode = false;
2901
+ const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
2902
+ function findFile(baseDir, baseName) {
2903
+ const localBin = path$1.resolve(baseDir, baseName);
2904
+ if (fs$1.existsSync(localBin)) return localBin;
2905
+ if (sourceExt.includes(path$1.extname(baseName))) return void 0;
2906
+ const foundExt = sourceExt.find(
2907
+ (ext) => fs$1.existsSync(`${localBin}${ext}`)
2908
+ );
2909
+ if (foundExt) return `${localBin}${foundExt}`;
2910
+ return void 0;
2911
+ }
2912
+ this._checkForMissingMandatoryOptions();
2913
+ this._checkForConflictingOptions();
2914
+ let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
2915
+ let executableDir = this._executableDir || "";
2916
+ if (this._scriptPath) {
2917
+ let resolvedScriptPath;
2918
+ try {
2919
+ resolvedScriptPath = fs$1.realpathSync(this._scriptPath);
2920
+ } catch {
2921
+ resolvedScriptPath = this._scriptPath;
2922
+ }
2923
+ executableDir = path$1.resolve(
2924
+ path$1.dirname(resolvedScriptPath),
2925
+ executableDir
2926
+ );
2927
+ }
2928
+ if (executableDir) {
2929
+ let localFile = findFile(executableDir, executableFile);
2930
+ if (!localFile && !subcommand._executableFile && this._scriptPath) {
2931
+ const legacyName = path$1.basename(
2932
+ this._scriptPath,
2933
+ path$1.extname(this._scriptPath)
2934
+ );
2935
+ if (legacyName !== this._name) {
2936
+ localFile = findFile(
2937
+ executableDir,
2938
+ `${legacyName}-${subcommand._name}`
2939
+ );
2940
+ }
2941
+ }
2942
+ executableFile = localFile || executableFile;
2943
+ }
2944
+ launchWithNode = sourceExt.includes(path$1.extname(executableFile));
2945
+ let proc;
2946
+ if (process2.platform !== "win32") {
2947
+ if (launchWithNode) {
2948
+ args.unshift(executableFile);
2949
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
2950
+ proc = childProcess.spawn(process2.argv[0], args, { stdio: "inherit" });
2951
+ } else {
2952
+ proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
2953
+ }
2954
+ } else {
2955
+ this._checkForMissingExecutable(
2956
+ executableFile,
2957
+ executableDir,
2958
+ subcommand._name
2959
+ );
2960
+ args.unshift(executableFile);
2961
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
2962
+ proc = childProcess.spawn(process2.execPath, args, { stdio: "inherit" });
2963
+ }
2964
+ if (!proc.killed) {
2965
+ const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
2966
+ signals.forEach((signal) => {
2967
+ process2.on(signal, () => {
2968
+ if (proc.killed === false && proc.exitCode === null) {
2969
+ proc.kill(signal);
2970
+ }
2971
+ });
2972
+ });
2973
+ }
2974
+ const exitCallback = this._exitCallback;
2975
+ proc.on("close", (code) => {
2976
+ code = code ?? 1;
2977
+ if (!exitCallback) {
2978
+ process2.exit(code);
2979
+ } else {
2980
+ exitCallback(
2981
+ new CommanderError2(
2982
+ code,
2983
+ "commander.executeSubCommandAsync",
2984
+ "(close)"
2985
+ )
2986
+ );
2987
+ }
2988
+ });
2989
+ proc.on("error", (err) => {
2990
+ if (err.code === "ENOENT") {
2991
+ this._checkForMissingExecutable(
2992
+ executableFile,
2993
+ executableDir,
2994
+ subcommand._name
2995
+ );
2996
+ } else if (err.code === "EACCES") {
2997
+ throw new Error(`'${executableFile}' not executable`);
2998
+ }
2999
+ if (!exitCallback) {
3000
+ process2.exit(1);
3001
+ } else {
3002
+ const wrappedError = new CommanderError2(
3003
+ 1,
3004
+ "commander.executeSubCommandAsync",
3005
+ "(error)"
3006
+ );
3007
+ wrappedError.nestedError = err;
3008
+ exitCallback(wrappedError);
3009
+ }
3010
+ });
3011
+ this.runningCommand = proc;
3012
+ }
3013
+ /**
3014
+ * @private
3015
+ */
3016
+ _dispatchSubcommand(commandName, operands, unknown) {
3017
+ const subCommand = this._findCommand(commandName);
3018
+ if (!subCommand) this.help({ error: true });
3019
+ subCommand._prepareForParse();
3020
+ let promiseChain;
3021
+ promiseChain = this._chainOrCallSubCommandHook(
3022
+ promiseChain,
3023
+ subCommand,
3024
+ "preSubcommand"
3025
+ );
3026
+ promiseChain = this._chainOrCall(promiseChain, () => {
3027
+ if (subCommand._executableHandler) {
3028
+ this._executeSubCommand(subCommand, operands.concat(unknown));
3029
+ } else {
3030
+ return subCommand._parseCommand(operands, unknown);
3031
+ }
3032
+ });
3033
+ return promiseChain;
3034
+ }
3035
+ /**
3036
+ * Invoke help directly if possible, or dispatch if necessary.
3037
+ * e.g. help foo
3038
+ *
3039
+ * @private
3040
+ */
3041
+ _dispatchHelpCommand(subcommandName) {
3042
+ if (!subcommandName) {
3043
+ this.help();
3044
+ }
3045
+ const subCommand = this._findCommand(subcommandName);
3046
+ if (subCommand && !subCommand._executableHandler) {
3047
+ subCommand.help();
3048
+ }
3049
+ return this._dispatchSubcommand(
3050
+ subcommandName,
3051
+ [],
3052
+ [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]
3053
+ );
3054
+ }
3055
+ /**
3056
+ * Check this.args against expected this.registeredArguments.
3057
+ *
3058
+ * @private
3059
+ */
3060
+ _checkNumberOfArguments() {
3061
+ this.registeredArguments.forEach((arg, i) => {
3062
+ if (arg.required && this.args[i] == null) {
3063
+ this.missingArgument(arg.name());
3064
+ }
3065
+ });
3066
+ if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
3067
+ return;
3068
+ }
3069
+ if (this.args.length > this.registeredArguments.length) {
3070
+ this._excessArguments(this.args);
3071
+ }
3072
+ }
3073
+ /**
3074
+ * Process this.args using this.registeredArguments and save as this.processedArgs!
3075
+ *
3076
+ * @private
3077
+ */
3078
+ _processArguments() {
3079
+ const myParseArg = (argument2, value, previous) => {
3080
+ let parsedValue = value;
3081
+ if (value !== null && argument2.parseArg) {
3082
+ const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument2.name()}'.`;
3083
+ parsedValue = this._callParseArg(
3084
+ argument2,
3085
+ value,
3086
+ previous,
3087
+ invalidValueMessage
3088
+ );
3089
+ }
3090
+ return parsedValue;
3091
+ };
3092
+ this._checkNumberOfArguments();
3093
+ const processedArgs = [];
3094
+ this.registeredArguments.forEach((declaredArg, index) => {
3095
+ let value = declaredArg.defaultValue;
3096
+ if (declaredArg.variadic) {
3097
+ if (index < this.args.length) {
3098
+ value = this.args.slice(index);
3099
+ if (declaredArg.parseArg) {
3100
+ value = value.reduce((processed, v) => {
3101
+ return myParseArg(declaredArg, v, processed);
3102
+ }, declaredArg.defaultValue);
3103
+ }
3104
+ } else if (value === void 0) {
3105
+ value = [];
3106
+ }
3107
+ } else if (index < this.args.length) {
3108
+ value = this.args[index];
3109
+ if (declaredArg.parseArg) {
3110
+ value = myParseArg(declaredArg, value, declaredArg.defaultValue);
3111
+ }
3112
+ }
3113
+ processedArgs[index] = value;
3114
+ });
3115
+ this.processedArgs = processedArgs;
3116
+ }
3117
+ /**
3118
+ * Once we have a promise we chain, but call synchronously until then.
3119
+ *
3120
+ * @param {(Promise|undefined)} promise
3121
+ * @param {Function} fn
3122
+ * @return {(Promise|undefined)}
3123
+ * @private
3124
+ */
3125
+ _chainOrCall(promise, fn) {
3126
+ if (promise && promise.then && typeof promise.then === "function") {
3127
+ return promise.then(() => fn());
3128
+ }
3129
+ return fn();
3130
+ }
3131
+ /**
3132
+ *
3133
+ * @param {(Promise|undefined)} promise
3134
+ * @param {string} event
3135
+ * @return {(Promise|undefined)}
3136
+ * @private
3137
+ */
3138
+ _chainOrCallHooks(promise, event) {
3139
+ let result = promise;
3140
+ const hooks = [];
3141
+ this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== void 0).forEach((hookedCommand) => {
3142
+ hookedCommand._lifeCycleHooks[event].forEach((callback) => {
3143
+ hooks.push({ hookedCommand, callback });
3144
+ });
3145
+ });
3146
+ if (event === "postAction") {
3147
+ hooks.reverse();
3148
+ }
3149
+ hooks.forEach((hookDetail) => {
3150
+ result = this._chainOrCall(result, () => {
3151
+ return hookDetail.callback(hookDetail.hookedCommand, this);
3152
+ });
3153
+ });
3154
+ return result;
3155
+ }
3156
+ /**
3157
+ *
3158
+ * @param {(Promise|undefined)} promise
3159
+ * @param {Command} subCommand
3160
+ * @param {string} event
3161
+ * @return {(Promise|undefined)}
3162
+ * @private
3163
+ */
3164
+ _chainOrCallSubCommandHook(promise, subCommand, event) {
3165
+ let result = promise;
3166
+ if (this._lifeCycleHooks[event] !== void 0) {
3167
+ this._lifeCycleHooks[event].forEach((hook) => {
3168
+ result = this._chainOrCall(result, () => {
3169
+ return hook(this, subCommand);
3170
+ });
3171
+ });
3172
+ }
3173
+ return result;
3174
+ }
3175
+ /**
3176
+ * Process arguments in context of this command.
3177
+ * Returns action result, in case it is a promise.
3178
+ *
3179
+ * @private
3180
+ */
3181
+ _parseCommand(operands, unknown) {
3182
+ const parsed = this.parseOptions(unknown);
3183
+ this._parseOptionsEnv();
3184
+ this._parseOptionsImplied();
3185
+ operands = operands.concat(parsed.operands);
3186
+ unknown = parsed.unknown;
3187
+ this.args = operands.concat(unknown);
3188
+ if (operands && this._findCommand(operands[0])) {
3189
+ return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
3190
+ }
3191
+ if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) {
3192
+ return this._dispatchHelpCommand(operands[1]);
3193
+ }
3194
+ if (this._defaultCommandName) {
3195
+ this._outputHelpIfRequested(unknown);
3196
+ return this._dispatchSubcommand(
3197
+ this._defaultCommandName,
3198
+ operands,
3199
+ unknown
3200
+ );
3201
+ }
3202
+ if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
3203
+ this.help({ error: true });
3204
+ }
3205
+ this._outputHelpIfRequested(parsed.unknown);
3206
+ this._checkForMissingMandatoryOptions();
3207
+ this._checkForConflictingOptions();
3208
+ const checkForUnknownOptions = () => {
3209
+ if (parsed.unknown.length > 0) {
3210
+ this.unknownOption(parsed.unknown[0]);
3211
+ }
3212
+ };
3213
+ const commandEvent = `command:${this.name()}`;
3214
+ if (this._actionHandler) {
3215
+ checkForUnknownOptions();
3216
+ this._processArguments();
3217
+ let promiseChain;
3218
+ promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
3219
+ promiseChain = this._chainOrCall(
3220
+ promiseChain,
3221
+ () => this._actionHandler(this.processedArgs)
3222
+ );
3223
+ if (this.parent) {
3224
+ promiseChain = this._chainOrCall(promiseChain, () => {
3225
+ this.parent.emit(commandEvent, operands, unknown);
3226
+ });
3227
+ }
3228
+ promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
3229
+ return promiseChain;
3230
+ }
3231
+ if (this.parent && this.parent.listenerCount(commandEvent)) {
3232
+ checkForUnknownOptions();
3233
+ this._processArguments();
3234
+ this.parent.emit(commandEvent, operands, unknown);
3235
+ } else if (operands.length) {
3236
+ if (this._findCommand("*")) {
3237
+ return this._dispatchSubcommand("*", operands, unknown);
3238
+ }
3239
+ if (this.listenerCount("command:*")) {
3240
+ this.emit("command:*", operands, unknown);
3241
+ } else if (this.commands.length) {
3242
+ this.unknownCommand();
3243
+ } else {
3244
+ checkForUnknownOptions();
3245
+ this._processArguments();
3246
+ }
3247
+ } else if (this.commands.length) {
3248
+ checkForUnknownOptions();
3249
+ this.help({ error: true });
3250
+ } else {
3251
+ checkForUnknownOptions();
3252
+ this._processArguments();
3253
+ }
3254
+ }
3255
+ /**
3256
+ * Find matching command.
3257
+ *
3258
+ * @private
3259
+ * @return {Command | undefined}
3260
+ */
3261
+ _findCommand(name) {
3262
+ if (!name) return void 0;
3263
+ return this.commands.find(
3264
+ (cmd) => cmd._name === name || cmd._aliases.includes(name)
3265
+ );
3266
+ }
3267
+ /**
3268
+ * Return an option matching `arg` if any.
3269
+ *
3270
+ * @param {string} arg
3271
+ * @return {Option}
3272
+ * @package
3273
+ */
3274
+ _findOption(arg) {
3275
+ return this.options.find((option2) => option2.is(arg));
3276
+ }
3277
+ /**
3278
+ * Display an error message if a mandatory option does not have a value.
3279
+ * Called after checking for help flags in leaf subcommand.
3280
+ *
3281
+ * @private
3282
+ */
3283
+ _checkForMissingMandatoryOptions() {
3284
+ this._getCommandAndAncestors().forEach((cmd) => {
3285
+ cmd.options.forEach((anOption) => {
3286
+ if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === void 0) {
3287
+ cmd.missingMandatoryOptionValue(anOption);
3288
+ }
3289
+ });
3290
+ });
3291
+ }
3292
+ /**
3293
+ * Display an error message if conflicting options are used together in this.
3294
+ *
3295
+ * @private
3296
+ */
3297
+ _checkForConflictingLocalOptions() {
3298
+ const definedNonDefaultOptions = this.options.filter((option2) => {
3299
+ const optionKey = option2.attributeName();
3300
+ if (this.getOptionValue(optionKey) === void 0) {
3301
+ return false;
3302
+ }
3303
+ return this.getOptionValueSource(optionKey) !== "default";
3304
+ });
3305
+ const optionsWithConflicting = definedNonDefaultOptions.filter(
3306
+ (option2) => option2.conflictsWith.length > 0
3307
+ );
3308
+ optionsWithConflicting.forEach((option2) => {
3309
+ const conflictingAndDefined = definedNonDefaultOptions.find(
3310
+ (defined) => option2.conflictsWith.includes(defined.attributeName())
3311
+ );
3312
+ if (conflictingAndDefined) {
3313
+ this._conflictingOption(option2, conflictingAndDefined);
3314
+ }
3315
+ });
3316
+ }
3317
+ /**
3318
+ * Display an error message if conflicting options are used together.
3319
+ * Called after checking for help flags in leaf subcommand.
3320
+ *
3321
+ * @private
3322
+ */
3323
+ _checkForConflictingOptions() {
3324
+ this._getCommandAndAncestors().forEach((cmd) => {
3325
+ cmd._checkForConflictingLocalOptions();
3326
+ });
3327
+ }
3328
+ /**
3329
+ * Parse options from `argv` removing known options,
3330
+ * and return argv split into operands and unknown arguments.
3331
+ *
3332
+ * Side effects: modifies command by storing options. Does not reset state if called again.
3333
+ *
3334
+ * Examples:
3335
+ *
3336
+ * argv => operands, unknown
3337
+ * --known kkk op => [op], []
3338
+ * op --known kkk => [op], []
3339
+ * sub --unknown uuu op => [sub], [--unknown uuu op]
3340
+ * sub -- --unknown uuu op => [sub --unknown uuu op], []
3341
+ *
3342
+ * @param {string[]} argv
3343
+ * @return {{operands: string[], unknown: string[]}}
3344
+ */
3345
+ parseOptions(argv) {
3346
+ const operands = [];
3347
+ const unknown = [];
3348
+ let dest = operands;
3349
+ const args = argv.slice();
3350
+ function maybeOption(arg) {
3351
+ return arg.length > 1 && arg[0] === "-";
3352
+ }
3353
+ let activeVariadicOption = null;
3354
+ while (args.length) {
3355
+ const arg = args.shift();
3356
+ if (arg === "--") {
3357
+ if (dest === unknown) dest.push(arg);
3358
+ dest.push(...args);
3359
+ break;
3360
+ }
3361
+ if (activeVariadicOption && !maybeOption(arg)) {
3362
+ this.emit(`option:${activeVariadicOption.name()}`, arg);
3363
+ continue;
3364
+ }
3365
+ activeVariadicOption = null;
3366
+ if (maybeOption(arg)) {
3367
+ const option2 = this._findOption(arg);
3368
+ if (option2) {
3369
+ if (option2.required) {
3370
+ const value = args.shift();
3371
+ if (value === void 0) this.optionMissingArgument(option2);
3372
+ this.emit(`option:${option2.name()}`, value);
3373
+ } else if (option2.optional) {
3374
+ let value = null;
3375
+ if (args.length > 0 && !maybeOption(args[0])) {
3376
+ value = args.shift();
3377
+ }
3378
+ this.emit(`option:${option2.name()}`, value);
3379
+ } else {
3380
+ this.emit(`option:${option2.name()}`);
3381
+ }
3382
+ activeVariadicOption = option2.variadic ? option2 : null;
3383
+ continue;
3384
+ }
3385
+ }
3386
+ if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
3387
+ const option2 = this._findOption(`-${arg[1]}`);
3388
+ if (option2) {
3389
+ if (option2.required || option2.optional && this._combineFlagAndOptionalValue) {
3390
+ this.emit(`option:${option2.name()}`, arg.slice(2));
3391
+ } else {
3392
+ this.emit(`option:${option2.name()}`);
3393
+ args.unshift(`-${arg.slice(2)}`);
3394
+ }
3395
+ continue;
3396
+ }
3397
+ }
3398
+ if (/^--[^=]+=/.test(arg)) {
3399
+ const index = arg.indexOf("=");
3400
+ const option2 = this._findOption(arg.slice(0, index));
3401
+ if (option2 && (option2.required || option2.optional)) {
3402
+ this.emit(`option:${option2.name()}`, arg.slice(index + 1));
3403
+ continue;
3404
+ }
3405
+ }
3406
+ if (maybeOption(arg)) {
3407
+ dest = unknown;
3408
+ }
3409
+ if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
3410
+ if (this._findCommand(arg)) {
3411
+ operands.push(arg);
3412
+ if (args.length > 0) unknown.push(...args);
3413
+ break;
3414
+ } else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
3415
+ operands.push(arg);
3416
+ if (args.length > 0) operands.push(...args);
3417
+ break;
3418
+ } else if (this._defaultCommandName) {
3419
+ unknown.push(arg);
3420
+ if (args.length > 0) unknown.push(...args);
3421
+ break;
3422
+ }
3423
+ }
3424
+ if (this._passThroughOptions) {
3425
+ dest.push(arg);
3426
+ if (args.length > 0) dest.push(...args);
3427
+ break;
3428
+ }
3429
+ dest.push(arg);
3430
+ }
3431
+ return { operands, unknown };
3432
+ }
3433
+ /**
3434
+ * Return an object containing local option values as key-value pairs.
3435
+ *
3436
+ * @return {object}
3437
+ */
3438
+ opts() {
3439
+ if (this._storeOptionsAsProperties) {
3440
+ const result = {};
3441
+ const len = this.options.length;
3442
+ for (let i = 0; i < len; i++) {
3443
+ const key = this.options[i].attributeName();
3444
+ result[key] = key === this._versionOptionName ? this._version : this[key];
3445
+ }
3446
+ return result;
3447
+ }
3448
+ return this._optionValues;
3449
+ }
3450
+ /**
3451
+ * Return an object containing merged local and global option values as key-value pairs.
3452
+ *
3453
+ * @return {object}
3454
+ */
3455
+ optsWithGlobals() {
3456
+ return this._getCommandAndAncestors().reduce(
3457
+ (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),
3458
+ {}
3459
+ );
3460
+ }
3461
+ /**
3462
+ * Display error message and exit (or call exitOverride).
3463
+ *
3464
+ * @param {string} message
3465
+ * @param {object} [errorOptions]
3466
+ * @param {string} [errorOptions.code] - an id string representing the error
3467
+ * @param {number} [errorOptions.exitCode] - used with process.exit
3468
+ */
3469
+ error(message, errorOptions) {
3470
+ this._outputConfiguration.outputError(
3471
+ `${message}
3472
+ `,
3473
+ this._outputConfiguration.writeErr
3474
+ );
3475
+ if (typeof this._showHelpAfterError === "string") {
3476
+ this._outputConfiguration.writeErr(`${this._showHelpAfterError}
3477
+ `);
3478
+ } else if (this._showHelpAfterError) {
3479
+ this._outputConfiguration.writeErr("\n");
3480
+ this.outputHelp({ error: true });
3481
+ }
3482
+ const config = errorOptions || {};
3483
+ const exitCode = config.exitCode || 1;
3484
+ const code = config.code || "commander.error";
3485
+ this._exit(exitCode, code, message);
3486
+ }
3487
+ /**
3488
+ * Apply any option related environment variables, if option does
3489
+ * not have a value from cli or client code.
3490
+ *
3491
+ * @private
3492
+ */
3493
+ _parseOptionsEnv() {
3494
+ this.options.forEach((option2) => {
3495
+ if (option2.envVar && option2.envVar in process2.env) {
3496
+ const optionKey = option2.attributeName();
3497
+ if (this.getOptionValue(optionKey) === void 0 || ["default", "config", "env"].includes(
3498
+ this.getOptionValueSource(optionKey)
3499
+ )) {
3500
+ if (option2.required || option2.optional) {
3501
+ this.emit(`optionEnv:${option2.name()}`, process2.env[option2.envVar]);
3502
+ } else {
3503
+ this.emit(`optionEnv:${option2.name()}`);
3504
+ }
3505
+ }
3506
+ }
3507
+ });
3508
+ }
3509
+ /**
3510
+ * Apply any implied option values, if option is undefined or default value.
3511
+ *
3512
+ * @private
3513
+ */
3514
+ _parseOptionsImplied() {
3515
+ const dualHelper = new DualOptions(this.options);
3516
+ const hasCustomOptionValue = (optionKey) => {
3517
+ return this.getOptionValue(optionKey) !== void 0 && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
3518
+ };
3519
+ this.options.filter(
3520
+ (option2) => option2.implied !== void 0 && hasCustomOptionValue(option2.attributeName()) && dualHelper.valueFromOption(
3521
+ this.getOptionValue(option2.attributeName()),
3522
+ option2
3523
+ )
3524
+ ).forEach((option2) => {
3525
+ Object.keys(option2.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
3526
+ this.setOptionValueWithSource(
3527
+ impliedKey,
3528
+ option2.implied[impliedKey],
3529
+ "implied"
3530
+ );
3531
+ });
3532
+ });
3533
+ }
3534
+ /**
3535
+ * Argument `name` is missing.
3536
+ *
3537
+ * @param {string} name
3538
+ * @private
3539
+ */
3540
+ missingArgument(name) {
3541
+ const message = `error: missing required argument '${name}'`;
3542
+ this.error(message, { code: "commander.missingArgument" });
3543
+ }
3544
+ /**
3545
+ * `Option` is missing an argument.
3546
+ *
3547
+ * @param {Option} option
3548
+ * @private
3549
+ */
3550
+ optionMissingArgument(option2) {
3551
+ const message = `error: option '${option2.flags}' argument missing`;
3552
+ this.error(message, { code: "commander.optionMissingArgument" });
3553
+ }
3554
+ /**
3555
+ * `Option` does not have a value, and is a mandatory option.
3556
+ *
3557
+ * @param {Option} option
3558
+ * @private
3559
+ */
3560
+ missingMandatoryOptionValue(option2) {
3561
+ const message = `error: required option '${option2.flags}' not specified`;
3562
+ this.error(message, { code: "commander.missingMandatoryOptionValue" });
3563
+ }
3564
+ /**
3565
+ * `Option` conflicts with another option.
3566
+ *
3567
+ * @param {Option} option
3568
+ * @param {Option} conflictingOption
3569
+ * @private
3570
+ */
3571
+ _conflictingOption(option2, conflictingOption) {
3572
+ const findBestOptionFromValue = (option3) => {
3573
+ const optionKey = option3.attributeName();
3574
+ const optionValue = this.getOptionValue(optionKey);
3575
+ const negativeOption = this.options.find(
3576
+ (target) => target.negate && optionKey === target.attributeName()
3577
+ );
3578
+ const positiveOption = this.options.find(
3579
+ (target) => !target.negate && optionKey === target.attributeName()
3580
+ );
3581
+ if (negativeOption && (negativeOption.presetArg === void 0 && optionValue === false || negativeOption.presetArg !== void 0 && optionValue === negativeOption.presetArg)) {
3582
+ return negativeOption;
3583
+ }
3584
+ return positiveOption || option3;
3585
+ };
3586
+ const getErrorMessage = (option3) => {
3587
+ const bestOption = findBestOptionFromValue(option3);
3588
+ const optionKey = bestOption.attributeName();
3589
+ const source = this.getOptionValueSource(optionKey);
3590
+ if (source === "env") {
3591
+ return `environment variable '${bestOption.envVar}'`;
3592
+ }
3593
+ return `option '${bestOption.flags}'`;
3594
+ };
3595
+ const message = `error: ${getErrorMessage(option2)} cannot be used with ${getErrorMessage(conflictingOption)}`;
3596
+ this.error(message, { code: "commander.conflictingOption" });
3597
+ }
3598
+ /**
3599
+ * Unknown option `flag`.
3600
+ *
3601
+ * @param {string} flag
3602
+ * @private
3603
+ */
3604
+ unknownOption(flag) {
3605
+ if (this._allowUnknownOption) return;
3606
+ let suggestion = "";
3607
+ if (flag.startsWith("--") && this._showSuggestionAfterError) {
3608
+ let candidateFlags = [];
3609
+ let command2 = this;
3610
+ do {
3611
+ const moreFlags = command2.createHelp().visibleOptions(command2).filter((option2) => option2.long).map((option2) => option2.long);
3612
+ candidateFlags = candidateFlags.concat(moreFlags);
3613
+ command2 = command2.parent;
3614
+ } while (command2 && !command2._enablePositionalOptions);
3615
+ suggestion = suggestSimilar2(flag, candidateFlags);
3616
+ }
3617
+ const message = `error: unknown option '${flag}'${suggestion}`;
3618
+ this.error(message, { code: "commander.unknownOption" });
3619
+ }
3620
+ /**
3621
+ * Excess arguments, more than expected.
3622
+ *
3623
+ * @param {string[]} receivedArgs
3624
+ * @private
3625
+ */
3626
+ _excessArguments(receivedArgs) {
3627
+ if (this._allowExcessArguments) return;
3628
+ const expected = this.registeredArguments.length;
3629
+ const s = expected === 1 ? "" : "s";
3630
+ const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
3631
+ const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
3632
+ this.error(message, { code: "commander.excessArguments" });
3633
+ }
3634
+ /**
3635
+ * Unknown command.
3636
+ *
3637
+ * @private
3638
+ */
3639
+ unknownCommand() {
3640
+ const unknownName = this.args[0];
3641
+ let suggestion = "";
3642
+ if (this._showSuggestionAfterError) {
3643
+ const candidateNames = [];
3644
+ this.createHelp().visibleCommands(this).forEach((command2) => {
3645
+ candidateNames.push(command2.name());
3646
+ if (command2.alias()) candidateNames.push(command2.alias());
3647
+ });
3648
+ suggestion = suggestSimilar2(unknownName, candidateNames);
3649
+ }
3650
+ const message = `error: unknown command '${unknownName}'${suggestion}`;
3651
+ this.error(message, { code: "commander.unknownCommand" });
3652
+ }
3653
+ /**
3654
+ * Get or set the program version.
3655
+ *
3656
+ * This method auto-registers the "-V, --version" option which will print the version number.
3657
+ *
3658
+ * You can optionally supply the flags and description to override the defaults.
3659
+ *
3660
+ * @param {string} [str]
3661
+ * @param {string} [flags]
3662
+ * @param {string} [description]
3663
+ * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments
3664
+ */
3665
+ version(str, flags, description) {
3666
+ if (str === void 0) return this._version;
3667
+ this._version = str;
3668
+ flags = flags || "-V, --version";
3669
+ description = description || "output the version number";
3670
+ const versionOption = this.createOption(flags, description);
3671
+ this._versionOptionName = versionOption.attributeName();
3672
+ this._registerOption(versionOption);
3673
+ this.on("option:" + versionOption.name(), () => {
3674
+ this._outputConfiguration.writeOut(`${str}
3675
+ `);
3676
+ this._exit(0, "commander.version", str);
3677
+ });
3678
+ return this;
3679
+ }
3680
+ /**
3681
+ * Set the description.
3682
+ *
3683
+ * @param {string} [str]
3684
+ * @param {object} [argsDescription]
3685
+ * @return {(string|Command)}
3686
+ */
3687
+ description(str, argsDescription) {
3688
+ if (str === void 0 && argsDescription === void 0)
3689
+ return this._description;
3690
+ this._description = str;
3691
+ if (argsDescription) {
3692
+ this._argsDescription = argsDescription;
3693
+ }
3694
+ return this;
3695
+ }
3696
+ /**
3697
+ * Set the summary. Used when listed as subcommand of parent.
3698
+ *
3699
+ * @param {string} [str]
3700
+ * @return {(string|Command)}
3701
+ */
3702
+ summary(str) {
3703
+ if (str === void 0) return this._summary;
3704
+ this._summary = str;
3705
+ return this;
3706
+ }
3707
+ /**
3708
+ * Set an alias for the command.
3709
+ *
3710
+ * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
3711
+ *
3712
+ * @param {string} [alias]
3713
+ * @return {(string|Command)}
3714
+ */
3715
+ alias(alias) {
3716
+ if (alias === void 0) return this._aliases[0];
3717
+ let command2 = this;
3718
+ if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
3719
+ command2 = this.commands[this.commands.length - 1];
3720
+ }
3721
+ if (alias === command2._name)
3722
+ throw new Error("Command alias can't be the same as its name");
3723
+ const matchingCommand = this.parent?._findCommand(alias);
3724
+ if (matchingCommand) {
3725
+ const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
3726
+ throw new Error(
3727
+ `cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`
3728
+ );
3729
+ }
3730
+ command2._aliases.push(alias);
3731
+ return this;
3732
+ }
3733
+ /**
3734
+ * Set aliases for the command.
3735
+ *
3736
+ * Only the first alias is shown in the auto-generated help.
3737
+ *
3738
+ * @param {string[]} [aliases]
3739
+ * @return {(string[]|Command)}
3740
+ */
3741
+ aliases(aliases) {
3742
+ if (aliases === void 0) return this._aliases;
3743
+ aliases.forEach((alias) => this.alias(alias));
3744
+ return this;
3745
+ }
3746
+ /**
3747
+ * Set / get the command usage `str`.
3748
+ *
3749
+ * @param {string} [str]
3750
+ * @return {(string|Command)}
3751
+ */
3752
+ usage(str) {
3753
+ if (str === void 0) {
3754
+ if (this._usage) return this._usage;
3755
+ const args = this.registeredArguments.map((arg) => {
3756
+ return humanReadableArgName(arg);
3757
+ });
3758
+ return [].concat(
3759
+ this.options.length || this._helpOption !== null ? "[options]" : [],
3760
+ this.commands.length ? "[command]" : [],
3761
+ this.registeredArguments.length ? args : []
3762
+ ).join(" ");
3763
+ }
3764
+ this._usage = str;
3765
+ return this;
3766
+ }
3767
+ /**
3768
+ * Get or set the name of the command.
3769
+ *
3770
+ * @param {string} [str]
3771
+ * @return {(string|Command)}
3772
+ */
3773
+ name(str) {
3774
+ if (str === void 0) return this._name;
3775
+ this._name = str;
3776
+ return this;
3777
+ }
3778
+ /**
3779
+ * Set the name of the command from script filename, such as process.argv[1],
3780
+ * or require.main.filename, or __filename.
3781
+ *
3782
+ * (Used internally and public although not documented in README.)
3783
+ *
3784
+ * @example
3785
+ * program.nameFromFilename(require.main.filename);
3786
+ *
3787
+ * @param {string} filename
3788
+ * @return {Command}
3789
+ */
3790
+ nameFromFilename(filename) {
3791
+ this._name = path$1.basename(filename, path$1.extname(filename));
3792
+ return this;
3793
+ }
3794
+ /**
3795
+ * Get or set the directory for searching for executable subcommands of this command.
3796
+ *
3797
+ * @example
3798
+ * program.executableDir(__dirname);
3799
+ * // or
3800
+ * program.executableDir('subcommands');
3801
+ *
3802
+ * @param {string} [path]
3803
+ * @return {(string|null|Command)}
3804
+ */
3805
+ executableDir(path2) {
3806
+ if (path2 === void 0) return this._executableDir;
3807
+ this._executableDir = path2;
3808
+ return this;
3809
+ }
3810
+ /**
3811
+ * Return program help documentation.
3812
+ *
3813
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
3814
+ * @return {string}
3815
+ */
3816
+ helpInformation(contextOptions) {
3817
+ const helper = this.createHelp();
3818
+ const context = this._getOutputContext(contextOptions);
3819
+ helper.prepareContext({
3820
+ error: context.error,
3821
+ helpWidth: context.helpWidth,
3822
+ outputHasColors: context.hasColors
3823
+ });
3824
+ const text = helper.formatHelp(this, helper);
3825
+ if (context.hasColors) return text;
3826
+ return this._outputConfiguration.stripColor(text);
3827
+ }
3828
+ /**
3829
+ * @typedef HelpContext
3830
+ * @type {object}
3831
+ * @property {boolean} error
3832
+ * @property {number} helpWidth
3833
+ * @property {boolean} hasColors
3834
+ * @property {function} write - includes stripColor if needed
3835
+ *
3836
+ * @returns {HelpContext}
3837
+ * @private
3838
+ */
3839
+ _getOutputContext(contextOptions) {
3840
+ contextOptions = contextOptions || {};
3841
+ const error2 = !!contextOptions.error;
3842
+ let baseWrite;
3843
+ let hasColors;
3844
+ let helpWidth;
3845
+ if (error2) {
3846
+ baseWrite = (str) => this._outputConfiguration.writeErr(str);
3847
+ hasColors = this._outputConfiguration.getErrHasColors();
3848
+ helpWidth = this._outputConfiguration.getErrHelpWidth();
3849
+ } else {
3850
+ baseWrite = (str) => this._outputConfiguration.writeOut(str);
3851
+ hasColors = this._outputConfiguration.getOutHasColors();
3852
+ helpWidth = this._outputConfiguration.getOutHelpWidth();
3853
+ }
3854
+ const write = (str) => {
3855
+ if (!hasColors) str = this._outputConfiguration.stripColor(str);
3856
+ return baseWrite(str);
3857
+ };
3858
+ return { error: error2, write, hasColors, helpWidth };
3859
+ }
3860
+ /**
3861
+ * Output help information for this command.
3862
+ *
3863
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
3864
+ *
3865
+ * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
3866
+ */
3867
+ outputHelp(contextOptions) {
3868
+ let deprecatedCallback;
3869
+ if (typeof contextOptions === "function") {
3870
+ deprecatedCallback = contextOptions;
3871
+ contextOptions = void 0;
3872
+ }
3873
+ const outputContext = this._getOutputContext(contextOptions);
3874
+ const eventContext = {
3875
+ error: outputContext.error,
3876
+ write: outputContext.write,
3877
+ command: this
3878
+ };
3879
+ this._getCommandAndAncestors().reverse().forEach((command2) => command2.emit("beforeAllHelp", eventContext));
3880
+ this.emit("beforeHelp", eventContext);
3881
+ let helpInformation = this.helpInformation({ error: outputContext.error });
3882
+ if (deprecatedCallback) {
3883
+ helpInformation = deprecatedCallback(helpInformation);
3884
+ if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
3885
+ throw new Error("outputHelp callback must return a string or a Buffer");
3886
+ }
3887
+ }
3888
+ outputContext.write(helpInformation);
3889
+ if (this._getHelpOption()?.long) {
3890
+ this.emit(this._getHelpOption().long);
3891
+ }
3892
+ this.emit("afterHelp", eventContext);
3893
+ this._getCommandAndAncestors().forEach(
3894
+ (command2) => command2.emit("afterAllHelp", eventContext)
3895
+ );
3896
+ }
3897
+ /**
3898
+ * You can pass in flags and a description to customise the built-in help option.
3899
+ * Pass in false to disable the built-in help option.
3900
+ *
3901
+ * @example
3902
+ * program.helpOption('-?, --help' 'show help'); // customise
3903
+ * program.helpOption(false); // disable
3904
+ *
3905
+ * @param {(string | boolean)} flags
3906
+ * @param {string} [description]
3907
+ * @return {Command} `this` command for chaining
3908
+ */
3909
+ helpOption(flags, description) {
3910
+ if (typeof flags === "boolean") {
3911
+ if (flags) {
3912
+ this._helpOption = this._helpOption ?? void 0;
3913
+ } else {
3914
+ this._helpOption = null;
3915
+ }
3916
+ return this;
3917
+ }
3918
+ flags = flags ?? "-h, --help";
3919
+ description = description ?? "display help for command";
3920
+ this._helpOption = this.createOption(flags, description);
3921
+ return this;
3922
+ }
3923
+ /**
3924
+ * Lazy create help option.
3925
+ * Returns null if has been disabled with .helpOption(false).
3926
+ *
3927
+ * @returns {(Option | null)} the help option
3928
+ * @package
3929
+ */
3930
+ _getHelpOption() {
3931
+ if (this._helpOption === void 0) {
3932
+ this.helpOption(void 0, void 0);
3933
+ }
3934
+ return this._helpOption;
3935
+ }
3936
+ /**
3937
+ * Supply your own option to use for the built-in help option.
3938
+ * This is an alternative to using helpOption() to customise the flags and description etc.
3939
+ *
3940
+ * @param {Option} option
3941
+ * @return {Command} `this` command for chaining
3942
+ */
3943
+ addHelpOption(option2) {
3944
+ this._helpOption = option2;
3945
+ return this;
3946
+ }
3947
+ /**
3948
+ * Output help information and exit.
3949
+ *
3950
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
3951
+ *
3952
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
3953
+ */
3954
+ help(contextOptions) {
3955
+ this.outputHelp(contextOptions);
3956
+ let exitCode = Number(process2.exitCode ?? 0);
3957
+ if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
3958
+ exitCode = 1;
3959
+ }
3960
+ this._exit(exitCode, "commander.help", "(outputHelp)");
3961
+ }
3962
+ /**
3963
+ * // Do a little typing to coordinate emit and listener for the help text events.
3964
+ * @typedef HelpTextEventContext
3965
+ * @type {object}
3966
+ * @property {boolean} error
3967
+ * @property {Command} command
3968
+ * @property {function} write
3969
+ */
3970
+ /**
3971
+ * Add additional text to be displayed with the built-in help.
3972
+ *
3973
+ * Position is 'before' or 'after' to affect just this command,
3974
+ * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
3975
+ *
3976
+ * @param {string} position - before or after built-in help
3977
+ * @param {(string | Function)} text - string to add, or a function returning a string
3978
+ * @return {Command} `this` command for chaining
3979
+ */
3980
+ addHelpText(position, text) {
3981
+ const allowedValues = ["beforeAll", "before", "after", "afterAll"];
3982
+ if (!allowedValues.includes(position)) {
3983
+ throw new Error(`Unexpected value for position to addHelpText.
3984
+ Expecting one of '${allowedValues.join("', '")}'`);
3985
+ }
3986
+ const helpEvent = `${position}Help`;
3987
+ this.on(helpEvent, (context) => {
3988
+ let helpStr;
3989
+ if (typeof text === "function") {
3990
+ helpStr = text({ error: context.error, command: context.command });
3991
+ } else {
3992
+ helpStr = text;
3993
+ }
3994
+ if (helpStr) {
3995
+ context.write(`${helpStr}
3996
+ `);
3997
+ }
3998
+ });
3999
+ return this;
4000
+ }
4001
+ /**
4002
+ * Output help information if help flags specified
4003
+ *
4004
+ * @param {Array} args - array of options to search for help flags
4005
+ * @private
4006
+ */
4007
+ _outputHelpIfRequested(args) {
4008
+ const helpOption = this._getHelpOption();
4009
+ const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
4010
+ if (helpRequested) {
4011
+ this.outputHelp();
4012
+ this._exit(0, "commander.helpDisplayed", "(outputHelp)");
4013
+ }
4014
+ }
4015
+ }
4016
+ function incrementNodeInspectorPort(args) {
4017
+ return args.map((arg) => {
4018
+ if (!arg.startsWith("--inspect")) {
4019
+ return arg;
4020
+ }
4021
+ let debugOption;
4022
+ let debugHost = "127.0.0.1";
4023
+ let debugPort = "9229";
4024
+ let match;
4025
+ if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
4026
+ debugOption = match[1];
4027
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
4028
+ debugOption = match[1];
4029
+ if (/^\d+$/.test(match[3])) {
4030
+ debugPort = match[3];
4031
+ } else {
4032
+ debugHost = match[3];
4033
+ }
4034
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
4035
+ debugOption = match[1];
4036
+ debugHost = match[3];
4037
+ debugPort = match[4];
4038
+ }
4039
+ if (debugOption && debugPort !== "0") {
4040
+ return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
4041
+ }
4042
+ return arg;
4043
+ });
4044
+ }
4045
+ function useColor() {
4046
+ if (process2.env.NO_COLOR || process2.env.FORCE_COLOR === "0" || process2.env.FORCE_COLOR === "false")
4047
+ return false;
4048
+ if (process2.env.FORCE_COLOR || process2.env.CLICOLOR_FORCE !== void 0)
4049
+ return true;
4050
+ return void 0;
4051
+ }
4052
+ command.Command = Command2;
4053
+ command.useColor = useColor;
4054
+ return command;
4055
+ }
4056
+ var hasRequiredCommander;
4057
+ function requireCommander() {
4058
+ if (hasRequiredCommander) return commander$1;
4059
+ hasRequiredCommander = 1;
4060
+ const { Argument: Argument2 } = requireArgument();
4061
+ const { Command: Command2 } = requireCommand();
4062
+ const { CommanderError: CommanderError2, InvalidArgumentError: InvalidArgumentError2 } = requireError();
4063
+ const { Help: Help2 } = requireHelp();
4064
+ const { Option: Option2 } = requireOption();
4065
+ commander$1.program = new Command2();
4066
+ commander$1.createCommand = (name) => new Command2(name);
4067
+ commander$1.createOption = (flags, description) => new Option2(flags, description);
4068
+ commander$1.createArgument = (name, description) => new Argument2(name, description);
4069
+ commander$1.Command = Command2;
4070
+ commander$1.Option = Option2;
4071
+ commander$1.Argument = Argument2;
4072
+ commander$1.Help = Help2;
4073
+ commander$1.CommanderError = CommanderError2;
4074
+ commander$1.InvalidArgumentError = InvalidArgumentError2;
4075
+ commander$1.InvalidOptionArgumentError = InvalidArgumentError2;
4076
+ return commander$1;
4077
+ }
4078
+ var commanderExports = requireCommander();
4079
+ const commander = /* @__PURE__ */ getDefaultExportFromCjs(commanderExports);
4080
+ const {
4081
+ program,
4082
+ createCommand,
4083
+ createArgument,
4084
+ createOption,
4085
+ CommanderError,
4086
+ InvalidArgumentError,
4087
+ InvalidOptionArgumentError,
4088
+ // deprecated old name
4089
+ Command,
4090
+ Argument,
4091
+ Option,
4092
+ Help
4093
+ } = commander;
4094
+ if (!process.argv?.[2]) process.argv.push("-h");
4095
+ const getVersion = () => {
4096
+ try {
4097
+ const file = fileURLToPath(new URL("../../package.json", import.meta.url));
4098
+ const packageJson = JSON.parse(fs.readFileSync(file, "utf-8"));
4099
+ return packageJson.version;
4100
+ } catch {
4101
+ return "unknown";
4102
+ }
4103
+ };
4104
+ program.version(getVersion(), "-v, --version", "显示版本号");
4105
+ program.command(".").description("前台启动").action(start);
4106
+ program.command("app").description("前台启动").action(start);
4107
+ program.command("start").description("前台启动").action(start);
4108
+ program.command("pm2").description("后台运行").action(pm2.start);
4109
+ program.command("stop").description("停止后台服务").action(pm2.stop);
4110
+ program.command("rs").description("重启后台服务").option("-f, --force", "强制重启").action((options) => pm2.restart(options.force));
4111
+ program.command("log").description("查看日志").action(pm2.log);
4112
+ program.command("up").description("更新插件").option("-f, --force", "强制更新").option("-s, --serial", "并发更新").action((options) => updateAll(options.force, !options.serial));
4113
+ program.command("init").description("初始化项目").option("-f, --force", "强制初始化").option("-d, --dev", "开发模式").action((options) => {
4114
+ process.env.KARIN_CLI = "true";
4115
+ if (options.dev) {
4116
+ process.env.NODE_ENV = "development";
4117
+ }
4118
+ init(options.force);
4119
+ });
4120
+ program.parse(process.argv);