slack-term 1.39.2 → 1.40.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.
package/dist/cli.js CHANGED
@@ -1,21 +1,21 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- import{createRequire as vd}from"node:module";var Od=Object.create;var{getPrototypeOf:Pd,defineProperty:Ri,getOwnPropertyNames:Rd}=Object;var Ni=Object.prototype.hasOwnProperty;function Nd(e){return this[e]}var Bd,Md,Bi=(e,t,n)=>{var o=e!=null&&typeof e==="object";if(o){var s=t?Bd??=new WeakMap:Md??=new WeakMap,r=s.get(e);if(r)return r}n=e!=null?Od(Pd(e)):{};let i=t||!e||!e.__esModule||!Ni.call(e,"default")?Ri(n,"default",{value:e,enumerable:!0}):n;if(e&&typeof e==="object"||typeof e==="function"){for(let c of Rd(e))if(!Ni.call(i,c))Ri(i,c,{get:Nd.bind(e,c),enumerable:!0})}if(o)s.set(e,i);return i};var Mi=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var En=vd(import.meta.url);var ta=Mi(function(Um,ea){ea.exports=()=>/[#*0-9]\uFE0F?\u20E3|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26AA\u26B0\u26B1\u26BD\u26BE\u26C4\u26C8\u26CF\u26D1\u26E9\u26F0-\u26F5\u26F7\u26F8\u26FA\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2757\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B55\u3030\u303D\u3297\u3299]\uFE0F?|[\u261D\u270C\u270D](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\u270A\u270B](?:\uD83C[\uDFFB-\uDFFF])?|[\u23E9-\u23EC\u23F0\u23F3\u25FD\u2693\u26A1\u26AB\u26C5\u26CE\u26D4\u26EA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2795-\u2797\u27B0\u27BF\u2B50]|\u26D3\uFE0F?(?:\u200D\uD83D\uDCA5)?|\u26F9(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\u2764\uFE0F?(?:\u200D(?:\uD83D\uDD25|\uD83E\uDE79))?|\uD83C(?:[\uDC04\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]\uFE0F?|[\uDF85\uDFC2\uDFC7](?:\uD83C[\uDFFB-\uDFFF])?|[\uDFC4\uDFCA](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDFCB\uDFCC](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF43\uDF45-\uDF4A\uDF4C-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uDDE6\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF]|\uDDE7\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF]|\uDDE8\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF7\uDDFA-\uDDFF]|\uDDE9\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF]|\uDDEA\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA]|\uDDEB\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7]|\uDDEC\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE]|\uDDED\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA]|\uDDEE\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9]|\uDDEF\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5]|\uDDF0\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF]|\uDDF1\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE]|\uDDF2\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF]|\uDDF3\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF]|\uDDF4\uD83C\uDDF2|\uDDF5\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE]|\uDDF6\uD83C\uDDE6|\uDDF7\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC]|\uDDF8\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF]|\uDDF9\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF]|\uDDFA\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF]|\uDDFB\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA]|\uDDFC\uD83C[\uDDEB\uDDF8]|\uDDFD\uD83C\uDDF0|\uDDFE\uD83C[\uDDEA\uDDF9]|\uDDFF\uD83C[\uDDE6\uDDF2\uDDFC]|\uDF44(?:\u200D\uD83D\uDFEB)?|\uDF4B(?:\u200D\uD83D\uDFE9)?|\uDFC3(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDFF3\uFE0F?(?:\u200D(?:\u26A7\uFE0F?|\uD83C\uDF08))?|\uDFF4(?:\u200D\u2620\uFE0F?|\uDB40\uDC67\uDB40\uDC62\uDB40(?:\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDC73\uDB40\uDC63\uDB40\uDC74|\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F)?)|\uD83D(?:[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3]\uFE0F?|[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC](?:\uD83C[\uDFFB-\uDFFF])?|[\uDC6E-\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4\uDEB5](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD74\uDD90](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC25\uDC27-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE41\uDE43\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED8\uDEDC-\uDEDF\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB\uDFF0]|\uDC08(?:\u200D\u2B1B)?|\uDC15(?:\u200D\uD83E\uDDBA)?|\uDC26(?:\u200D(?:\u2B1B|\uD83D\uDD25))?|\uDC3B(?:\u200D\u2744\uFE0F?)?|\uDC41\uFE0F?(?:\u200D\uD83D\uDDE8\uFE0F?)?|\uDC68(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDC68\uDC69]\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?))?|\uDC69(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?[\uDC68\uDC69]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?|\uDC69\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?))|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFC-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFC-\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFD-\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFD\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFE])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFE]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFE])))?))?|\uDD75(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDE2E(?:\u200D\uD83D\uDCA8)?|\uDE35(?:\u200D\uD83D\uDCAB)?|\uDE36(?:\u200D\uD83C\uDF2B\uFE0F?)?|\uDE42(?:\u200D[\u2194\u2195]\uFE0F?)?|\uDEB6(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?)|\uD83E(?:[\uDD0C\uDD0F\uDD18-\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5\uDEC3-\uDEC5\uDEF0\uDEF2-\uDEF8](?:\uD83C[\uDFFB-\uDFFF])?|[\uDD26\uDD35\uDD37-\uDD39\uDD3C-\uDD3E\uDDB8\uDDB9\uDDCD\uDDCF\uDDD4\uDDD6-\uDDDD](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDDDE\uDDDF](?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD0D\uDD0E\uDD10-\uDD17\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCC\uDDD0\uDDE0-\uDDFF\uDE70-\uDE7C\uDE80-\uDE8A\uDE8E-\uDEC2\uDEC6\uDEC8\uDECD-\uDEDC\uDEDF-\uDEEA\uDEEF]|\uDDCE(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDDD1(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1|\uDDD1\u200D\uD83E\uDDD2(?:\u200D\uD83E\uDDD2)?|\uDDD2(?:\u200D\uD83E\uDDD2)?))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE])))?))?|\uDEF1(?:\uD83C(?:\uDFFB(?:\u200D\uD83E\uDEF2\uD83C[\uDFFC-\uDFFF])?|\uDFFC(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFD-\uDFFF])?|\uDFFD(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])?|\uDFFE(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFD\uDFFF])?|\uDFFF(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFE])?))?)/g});var Fa=Mi(function(TD,_a){_a.exports=function(t){if(t===void 0)t=2;if(t>=Error.stackTraceLimit)throw TypeError("getCallerFile(position) requires position be less then Error.stackTraceLimit but position was: `"+t+"` and Error.stackTraceLimit was: `"+Error.stackTraceLimit+"`");var n=Error.prepareStackTrace;Error.prepareStackTrace=function(s,r){return r};var o=Error().stack;if(Error.prepareStackTrace=n,o!==null&&typeof o==="object")return o[t]?o[t].getFileName():void 0}});import{createHash as og}from"crypto";import{existsSync as yd,readFileSync as wd,mkdirSync as rg,realpathSync as ig,writeFileSync as bd}from"fs";import{homedir as id}from"os";import{join as _t,resolve as ag}from"path";import{notStrictEqual as Ef,strictEqual as Sf}from"assert";var Ld={right:Ud,center:Jd};class Li{constructor(e){var t;this.width=e.width,this.wrap=(t=e.wrap)!==null&&t!==void 0?t:!0,this.rows=[]}span(...e){let t=this.div(...e);t.span=!0}resetOutput(){this.rows=[]}div(...e){if(e.length===0)this.div("");if(this.wrap&&this.shouldApplyLayoutDSL(...e)&&typeof e[0]==="string")return this.applyLayoutDSL(e[0]);let t=e.map((n)=>{if(typeof n==="string")return this.colFromString(n);return n});return this.rows.push(t),t}shouldApplyLayoutDSL(...e){return e.length===1&&typeof e[0]==="string"&&/[\t\n]/.test(e[0])}applyLayoutDSL(e){let t=e.split(`
3
+ import{createRequire as Yd}from"node:module";var Kd=Object.create;var{getPrototypeOf:Hd,defineProperty:Li,getOwnPropertyNames:zd}=Object;var Mi=Object.prototype.hasOwnProperty;function qd(e){return this[e]}var Gd,Xd,ji=(e,t,n)=>{var o=e!=null&&typeof e==="object";if(o){var s=t?Gd??=new WeakMap:Xd??=new WeakMap,r=s.get(e);if(r)return r}n=e!=null?Kd(Hd(e)):{};let i=t||!e||!e.__esModule||!Mi.call(e,"default")?Li(n,"default",{value:e,enumerable:!0}):n;if(e&&typeof e==="object"||typeof e==="function"){for(let c of zd(e))if(!Mi.call(i,c))Li(i,c,{get:qd.bind(e,c),enumerable:!0})}if(o)s.set(e,i);return i};var Wi=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Sn=Yd(import.meta.url);var ra=Wi(function(oD,oa){oa.exports=()=>/[#*0-9]\uFE0F?\u20E3|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26AA\u26B0\u26B1\u26BD\u26BE\u26C4\u26C8\u26CF\u26D1\u26E9\u26F0-\u26F5\u26F7\u26F8\u26FA\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2757\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B55\u3030\u303D\u3297\u3299]\uFE0F?|[\u261D\u270C\u270D](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\u270A\u270B](?:\uD83C[\uDFFB-\uDFFF])?|[\u23E9-\u23EC\u23F0\u23F3\u25FD\u2693\u26A1\u26AB\u26C5\u26CE\u26D4\u26EA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2795-\u2797\u27B0\u27BF\u2B50]|\u26D3\uFE0F?(?:\u200D\uD83D\uDCA5)?|\u26F9(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\u2764\uFE0F?(?:\u200D(?:\uD83D\uDD25|\uD83E\uDE79))?|\uD83C(?:[\uDC04\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]\uFE0F?|[\uDF85\uDFC2\uDFC7](?:\uD83C[\uDFFB-\uDFFF])?|[\uDFC4\uDFCA](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDFCB\uDFCC](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF43\uDF45-\uDF4A\uDF4C-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uDDE6\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF]|\uDDE7\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF]|\uDDE8\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF7\uDDFA-\uDDFF]|\uDDE9\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF]|\uDDEA\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA]|\uDDEB\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7]|\uDDEC\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE]|\uDDED\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA]|\uDDEE\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9]|\uDDEF\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5]|\uDDF0\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF]|\uDDF1\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE]|\uDDF2\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF]|\uDDF3\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF]|\uDDF4\uD83C\uDDF2|\uDDF5\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE]|\uDDF6\uD83C\uDDE6|\uDDF7\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC]|\uDDF8\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF]|\uDDF9\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF]|\uDDFA\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF]|\uDDFB\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA]|\uDDFC\uD83C[\uDDEB\uDDF8]|\uDDFD\uD83C\uDDF0|\uDDFE\uD83C[\uDDEA\uDDF9]|\uDDFF\uD83C[\uDDE6\uDDF2\uDDFC]|\uDF44(?:\u200D\uD83D\uDFEB)?|\uDF4B(?:\u200D\uD83D\uDFE9)?|\uDFC3(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDFF3\uFE0F?(?:\u200D(?:\u26A7\uFE0F?|\uD83C\uDF08))?|\uDFF4(?:\u200D\u2620\uFE0F?|\uDB40\uDC67\uDB40\uDC62\uDB40(?:\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDC73\uDB40\uDC63\uDB40\uDC74|\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F)?)|\uD83D(?:[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3]\uFE0F?|[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC](?:\uD83C[\uDFFB-\uDFFF])?|[\uDC6E-\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4\uDEB5](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD74\uDD90](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC25\uDC27-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE41\uDE43\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED8\uDEDC-\uDEDF\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB\uDFF0]|\uDC08(?:\u200D\u2B1B)?|\uDC15(?:\u200D\uD83E\uDDBA)?|\uDC26(?:\u200D(?:\u2B1B|\uD83D\uDD25))?|\uDC3B(?:\u200D\u2744\uFE0F?)?|\uDC41\uFE0F?(?:\u200D\uD83D\uDDE8\uFE0F?)?|\uDC68(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDC68\uDC69]\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?))?|\uDC69(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?[\uDC68\uDC69]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?|\uDC69\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?))|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFC-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFC-\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFD-\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFD\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFE])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFE]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFE])))?))?|\uDD75(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDE2E(?:\u200D\uD83D\uDCA8)?|\uDE35(?:\u200D\uD83D\uDCAB)?|\uDE36(?:\u200D\uD83C\uDF2B\uFE0F?)?|\uDE42(?:\u200D[\u2194\u2195]\uFE0F?)?|\uDEB6(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?)|\uD83E(?:[\uDD0C\uDD0F\uDD18-\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5\uDEC3-\uDEC5\uDEF0\uDEF2-\uDEF8](?:\uD83C[\uDFFB-\uDFFF])?|[\uDD26\uDD35\uDD37-\uDD39\uDD3C-\uDD3E\uDDB8\uDDB9\uDDCD\uDDCF\uDDD4\uDDD6-\uDDDD](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDDDE\uDDDF](?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD0D\uDD0E\uDD10-\uDD17\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCC\uDDD0\uDDE0-\uDDFF\uDE70-\uDE7C\uDE80-\uDE8A\uDE8E-\uDEC2\uDEC6\uDEC8\uDECD-\uDEDC\uDEDF-\uDEEA\uDEEF]|\uDDCE(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDDD1(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1|\uDDD1\u200D\uD83E\uDDD2(?:\u200D\uD83E\uDDD2)?|\uDDD2(?:\u200D\uD83E\uDDD2)?))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE])))?))?|\uDEF1(?:\uD83C(?:\uDFFB(?:\u200D\uD83E\uDEF2\uD83C[\uDFFC-\uDFFF])?|\uDFFC(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFD-\uDFFF])?|\uDFFD(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])?|\uDFFE(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFD\uDFFF])?|\uDFFF(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFE])?))?)/g});var Ia=Wi(function(zD,Ta){Ta.exports=function(t){if(t===void 0)t=2;if(t>=Error.stackTraceLimit)throw TypeError("getCallerFile(position) requires position be less then Error.stackTraceLimit but position was: `"+t+"` and Error.stackTraceLimit was: `"+Error.stackTraceLimit+"`");var n=Error.prepareStackTrace;Error.prepareStackTrace=function(s,r){return r};var o=Error().stack;if(Error.prepareStackTrace=n,o!==null&&typeof o==="object")return o[t]?o[t].getFileName():void 0}});import{createHash as wg}from"crypto";import{existsSync as Id,readFileSync as Od,mkdirSync as bg,realpathSync as kg,writeFileSync as Pd}from"fs";import{homedir as wd}from"os";import{join as Ft,resolve as xg}from"path";import{notStrictEqual as Bf,strictEqual as vf}from"assert";var Vd={right:ef,center:tf};class Ji{constructor(e){var t;this.width=e.width,this.wrap=(t=e.wrap)!==null&&t!==void 0?t:!0,this.rows=[]}span(...e){let t=this.div(...e);t.span=!0}resetOutput(){this.rows=[]}div(...e){if(e.length===0)this.div("");if(this.wrap&&this.shouldApplyLayoutDSL(...e)&&typeof e[0]==="string")return this.applyLayoutDSL(e[0]);let t=e.map((n)=>{if(typeof n==="string")return this.colFromString(n);return n});return this.rows.push(t),t}shouldApplyLayoutDSL(...e){return e.length===1&&typeof e[0]==="string"&&/[\t\n]/.test(e[0])}applyLayoutDSL(e){let t=e.split(`
4
4
  `).map((o)=>o.split("\t")),n=0;return t.forEach((o)=>{if(o.length>1&&Pe.stringWidth(o[0])>n)n=Math.min(Math.floor(this.width*0.5),Pe.stringWidth(o[0]))}),t.forEach((o)=>{this.div(...o.map((s,r)=>({text:s.trim(),padding:this.measurePadding(s),width:r===0&&o.length>1?n:void 0})))}),this.rows[this.rows.length-1]}colFromString(e){return{text:e,padding:this.measurePadding(e)}}measurePadding(e){let t=Pe.stripAnsi(e);return[0,t.match(/\s*$/)[0].length,0,t.match(/^\s*/)[0].length]}toString(){let e=[];return this.rows.forEach((t)=>{this.rowToString(t,e)}),e.filter((t)=>!t.hidden).map((t)=>t.text).join(`
5
- `)}rowToString(e,t){return this.rasterize(e).forEach((n,o)=>{let s="";n.forEach((r,i)=>{let{width:c}=e[i],a=this.negatePadding(e[i]),l=r;if(a>Pe.stringWidth(r))l+=" ".repeat(a-Pe.stringWidth(r));if(e[i].align&&e[i].align!=="left"&&this.wrap){let d=Ld[e[i].align];if(l=d(l,a),Pe.stringWidth(l)<a)l+=" ".repeat((c||0)-Pe.stringWidth(l)-1)}let u=e[i].padding||[0,0,0,0];if(u[3])s+=" ".repeat(u[3]);if(s+=vi(e[i],l,"| "),s+=l,s+=vi(e[i],l," |"),u[1])s+=" ".repeat(u[1]);if(o===0&&t.length>0)s=this.renderInline(s,t[t.length-1])}),t.push({text:s.replace(/ +$/,""),span:e.span})}),t}renderInline(e,t){let n=e.match(/^ */),o=n?n[0].length:0,s=t.text,r=Pe.stringWidth(s.trimRight());if(!t.span)return e;if(!this.wrap)return t.hidden=!0,s+e;if(o<r)return e;return t.hidden=!0,s.trimRight()+" ".repeat(o-r)+e.trimLeft()}rasterize(e){let t=[],n=this.columnWidths(e),o;return e.forEach((s,r)=>{if(s.width=n[r],this.wrap)o=Pe.wrap(s.text,this.negatePadding(s),{hard:!0}).split(`
5
+ `)}rowToString(e,t){return this.rasterize(e).forEach((n,o)=>{let s="";n.forEach((r,i)=>{let{width:c}=e[i],a=this.negatePadding(e[i]),l=r;if(a>Pe.stringWidth(r))l+=" ".repeat(a-Pe.stringWidth(r));if(e[i].align&&e[i].align!=="left"&&this.wrap){let d=Vd[e[i].align];if(l=d(l,a),Pe.stringWidth(l)<a)l+=" ".repeat((c||0)-Pe.stringWidth(l)-1)}let u=e[i].padding||[0,0,0,0];if(u[3])s+=" ".repeat(u[3]);if(s+=Ui(e[i],l,"| "),s+=l,s+=Ui(e[i],l," |"),u[1])s+=" ".repeat(u[1]);if(o===0&&t.length>0)s=this.renderInline(s,t[t.length-1])}),t.push({text:s.replace(/ +$/,""),span:e.span})}),t}renderInline(e,t){let n=e.match(/^ */),o=n?n[0].length:0,s=t.text,r=Pe.stringWidth(s.trimRight());if(!t.span)return e;if(!this.wrap)return t.hidden=!0,s+e;if(o<r)return e;return t.hidden=!0,s.trimRight()+" ".repeat(o-r)+e.trimLeft()}rasterize(e){let t=[],n=this.columnWidths(e),o;return e.forEach((s,r)=>{if(s.width=n[r],this.wrap)o=Pe.wrap(s.text,this.negatePadding(s),{hard:!0}).split(`
6
6
  `);else o=s.text.split(`
7
- `);if(s.border)o.unshift("."+"-".repeat(this.negatePadding(s)+2)+"."),o.push("'"+"-".repeat(this.negatePadding(s)+2)+"'");if(s.padding)o.unshift(...Array(s.padding[0]||0).fill("")),o.push(...Array(s.padding[2]||0).fill(""));o.forEach((i,c)=>{if(!t[c])t.push([]);let a=t[c];for(let l=0;l<r;l++)if(a[l]===void 0)a.push("");a.push(i)})}),t}negatePadding(e){let t=e.width||0;if(e.padding)t-=(e.padding[3]||0)+(e.padding[1]||0);if(e.border)t-=4;return t}columnWidths(e){if(!this.wrap)return e.map((r)=>r.width||Pe.stringWidth(r.text));let t=e.length,n=this.width,o=e.map((r)=>{if(r.width)return t--,n-=r.width,r.width;return}),s=t?Math.floor(n/t):0;return o.map((r,i)=>{if(r===void 0)return Math.max(s,jd(e[i]));return r})}}function vi(e,t,n){if(e.border){if(/[.']-+[.']/.test(t))return"";if(t.trim().length!==0)return n;return" "}return""}function jd(e){let t=e.padding||[],n=1+(t[3]||0)+(t[1]||0);if(e.border)return n+4;return n}function Wd(){if(typeof process==="object"&&process.stdout&&process.stdout.columns)return process.stdout.columns;return 80}function Ud(e,t){e=e.trim();let n=Pe.stringWidth(e);if(n<t)return" ".repeat(t-n)+e;return e}function Jd(e,t){e=e.trim();let n=Pe.stringWidth(e);if(n>=t)return e;return" ".repeat(t-n>>1)+e}var Pe;function ji(e,t){return Pe=t,new Li({width:(e===null||e===void 0?void 0:e.width)||Wd(),wrap:e===null||e===void 0?void 0:e.wrap})}function So({onlyFirst:e=!1}={}){return new RegExp("(?:\\u001B\\][\\s\\S]*?(?:\\u0007|\\u001B\\u005C|\\u009C))|[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]",e?void 0:"g")}var Kd=So();function Tt(e){if(typeof e!=="string")throw TypeError(`Expected a \`string\`, got \`${typeof e}\``);if(!e.includes("\x1B")&&!e.includes("›"))return e;return e.replace(Kd,"")}var Wi=161,Ui=1114109,Ji=[161,161,164,164,167,168,170,170,173,174,176,180,182,186,188,191,198,198,208,208,215,216,222,225,230,230,232,234,236,237,240,240,242,243,247,250,252,252,254,254,257,257,273,273,275,275,283,283,294,295,299,299,305,307,312,312,319,322,324,324,328,331,333,333,338,339,358,359,363,363,462,462,464,464,466,466,468,468,470,470,472,472,474,474,476,476,593,593,609,609,708,708,711,711,713,715,717,717,720,720,728,731,733,733,735,735,768,879,913,929,931,937,945,961,963,969,1025,1025,1040,1103,1105,1105,8208,8208,8211,8214,8216,8217,8220,8221,8224,8226,8228,8231,8240,8240,8242,8243,8245,8245,8251,8251,8254,8254,8308,8308,8319,8319,8321,8324,8364,8364,8451,8451,8453,8453,8457,8457,8467,8467,8470,8470,8481,8482,8486,8486,8491,8491,8531,8532,8539,8542,8544,8555,8560,8569,8585,8585,8592,8601,8632,8633,8658,8658,8660,8660,8679,8679,8704,8704,8706,8707,8711,8712,8715,8715,8719,8719,8721,8721,8725,8725,8730,8730,8733,8736,8739,8739,8741,8741,8743,8748,8750,8750,8756,8759,8764,8765,8776,8776,8780,8780,8786,8786,8800,8801,8804,8807,8810,8811,8814,8815,8834,8835,8838,8839,8853,8853,8857,8857,8869,8869,8895,8895,8978,8978,9312,9449,9451,9547,9552,9587,9600,9615,9618,9621,9632,9633,9635,9641,9650,9651,9654,9655,9660,9661,9664,9665,9670,9672,9675,9675,9678,9681,9698,9701,9711,9711,9733,9734,9737,9737,9742,9743,9756,9756,9758,9758,9792,9792,9794,9794,9824,9825,9827,9829,9831,9834,9836,9837,9839,9839,9886,9887,9919,9919,9926,9933,9935,9939,9941,9953,9955,9955,9960,9961,9963,9969,9972,9972,9974,9977,9979,9980,9982,9983,10045,10045,10102,10111,11094,11097,12872,12879,57344,63743,65024,65039,65533,65533,127232,127242,127248,127277,127280,127337,127344,127373,127375,127376,127387,127404,917760,917999,983040,1048573,1048576,1114109],Ki=12288,Hi=65510,zi=[12288,12288,65281,65376,65504,65510];var qi=4352,Gi=262141,_o=[4352,4447,8986,8987,9001,9002,9193,9196,9200,9200,9203,9203,9725,9726,9748,9749,9776,9783,9800,9811,9855,9855,9866,9871,9875,9875,9889,9889,9898,9899,9917,9918,9924,9925,9934,9934,9940,9940,9962,9962,9970,9971,9973,9973,9978,9978,9981,9981,9989,9989,9994,9995,10024,10024,10060,10060,10062,10062,10067,10069,10071,10071,10133,10135,10160,10160,10175,10175,11035,11036,11088,11088,11093,11093,11904,11929,11931,12019,12032,12245,12272,12287,12289,12350,12353,12438,12441,12543,12549,12591,12593,12686,12688,12773,12783,12830,12832,12871,12880,42124,42128,42182,43360,43388,44032,55203,63744,64255,65040,65049,65072,65106,65108,65126,65128,65131,94176,94180,94192,94198,94208,101589,101631,101662,101760,101874,110576,110579,110581,110587,110589,110590,110592,110882,110898,110898,110928,110930,110933,110933,110948,110951,110960,111355,119552,119638,119648,119670,126980,126980,127183,127183,127374,127374,127377,127386,127488,127490,127504,127547,127552,127560,127568,127569,127584,127589,127744,127776,127789,127797,127799,127868,127870,127891,127904,127946,127951,127955,127968,127984,127988,127988,127992,128062,128064,128064,128066,128252,128255,128317,128331,128334,128336,128359,128378,128378,128405,128406,128420,128420,128507,128591,128640,128709,128716,128716,128720,128722,128725,128728,128732,128735,128747,128748,128756,128764,128992,129003,129008,129008,129292,129338,129340,129349,129351,129535,129648,129660,129664,129674,129678,129734,129736,129736,129741,129756,129759,129770,129775,129784,131072,196605,196608,262141];var ds=(e,t)=>{let n=0,o=Math.floor(e.length/2)-1;while(n<=o){let s=Math.floor((n+o)/2),r=s*2;if(t<e[r])o=s-1;else if(t>e[r+1])n=s+1;else return!0}return!1};var Xi=19968,[Hd,zd]=qd(_o);function qd(e){let t=e[0],n=e[1];for(let o=0;o<e.length;o+=2){let s=e[o],r=e[o+1];if(Xi>=s&&Xi<=r)return[s,r];if(r-s>n-t)t=s,n=r}return[t,n]}var Yi=(e)=>{if(e<Wi||e>Ui)return!1;return ds(Ji,e)},Vi=(e)=>{if(e<Ki||e>Hi)return!1;return ds(zi,e)};var Zi=(e)=>{if(e>=Hd&&e<=zd)return!0;if(e<qi||e>Gi)return!1;return ds(_o,e)};function Gd(e){if(!Number.isSafeInteger(e))throw TypeError(`Expected a code point, got \`${typeof e}\`.`)}function Qi(e,{ambiguousAsWide:t=!1}={}){if(Gd(e),Vi(e)||Zi(e)||t&&Yi(e))return 2;return 1}var na=Bi(ta(),1),Xd=new Intl.Segmenter,Yd=/^\p{Default_Ignorable_Code_Point}$/u;function Ve(e,t={}){if(typeof e!=="string"||e.length===0)return 0;let{ambiguousIsNarrow:n=!0,countAnsiEscapeCodes:o=!1}=t;if(!o)e=Tt(e);if(e.length===0)return 0;let s=0,r={ambiguousAsWide:!n};for(let{segment:i}of Xd.segment(e)){let c=i.codePointAt(0);if(c<=31||c>=127&&c<=159)continue;if(c>=8203&&c<=8207||c===65279)continue;if(c>=768&&c<=879||c>=6832&&c<=6911||c>=7616&&c<=7679||c>=8400&&c<=8447||c>=65056&&c<=65071)continue;if(c>=55296&&c<=57343)continue;if(c>=65024&&c<=65039)continue;if(Yd.test(i))continue;if(na.default().test(i)){s+=2;continue}s+=Qi(c,r)}return s}var sa=(e=0)=>(t)=>`\x1B[${t+e}m`,oa=(e=0)=>(t)=>`\x1B[${38+e};5;${t}m`,ra=(e=0)=>(t,n,o)=>`\x1B[${38+e};2;${t};${n};${o}m`,ae={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}},zm=Object.keys(ae.modifier),Vd=Object.keys(ae.color),Zd=Object.keys(ae.bgColor),qm=[...Vd,...Zd];function Qd(){let e=new Map;for(let[t,n]of Object.entries(ae)){for(let[o,s]of Object.entries(n))ae[o]={open:`\x1B[${s[0]}m`,close:`\x1B[${s[1]}m`},n[o]=ae[o],e.set(s[0],s[1]);Object.defineProperty(ae,t,{value:n,enumerable:!1})}return Object.defineProperty(ae,"codes",{value:e,enumerable:!1}),ae.color.close="\x1B[39m",ae.bgColor.close="\x1B[49m",ae.color.ansi=sa(),ae.color.ansi256=oa(),ae.color.ansi16m=ra(),ae.bgColor.ansi=sa(10),ae.bgColor.ansi256=oa(10),ae.bgColor.ansi16m=ra(10),Object.defineProperties(ae,{rgbToAnsi256:{value(t,n,o){if(t===n&&n===o){if(t<8)return 16;if(t>248)return 231;return Math.round((t-8)/247*24)+232}return 16+36*Math.round(t/255*5)+6*Math.round(n/255*5)+Math.round(o/255*5)},enumerable:!1},hexToRgb:{value(t){let n=/[a-f\d]{6}|[a-f\d]{3}/i.exec(t.toString(16));if(!n)return[0,0,0];let[o]=n;if(o.length===3)o=[...o].map((r)=>r+r).join("");let s=Number.parseInt(o,16);return[s>>16&255,s>>8&255,s&255]},enumerable:!1},hexToAnsi256:{value:(t)=>ae.rgbToAnsi256(...ae.hexToRgb(t)),enumerable:!1},ansi256ToAnsi:{value(t){if(t<8)return 30+t;if(t<16)return 90+(t-8);let n,o,s;if(t>=232)n=((t-232)*10+8)/255,o=n,s=n;else{t-=16;let c=t%36;n=Math.floor(t/36)/5,o=Math.floor(c/6)/5,s=c%6/5}let r=Math.max(n,o,s)*2;if(r===0)return 30;let i=30+(Math.round(s)<<2|Math.round(o)<<1|Math.round(n));if(r===2)i+=60;return i},enumerable:!1},rgbToAnsi:{value:(t,n,o)=>ae.ansi256ToAnsi(ae.rgbToAnsi256(t,n,o)),enumerable:!1},hexToAnsi:{value:(t)=>ae.ansi256ToAnsi(ae.hexToAnsi256(t)),enumerable:!1}}),ae}var ef=Qd(),ia=ef;var ps=new Set(["\x1B","›"]),tf=39,$o="\x07",la="[",nf="]",ua="m",fs=`${nf}8;;`,aa=(e)=>`${ps.values().next().value}${la}${e}${ua}`,ca=(e)=>`${ps.values().next().value}${fs}${e}${$o}`,sf=(e)=>e.split(" ").map((t)=>Ve(t)),Fo=(e,t,n)=>{let o=[...t],s=!1,r=!1,i=Ve(Tt(e.at(-1)));for(let[c,a]of o.entries()){let l=Ve(a);if(i+l<=n)e[e.length-1]+=a;else e.push(a),i=0;if(ps.has(a))s=!0,r=o.slice(c+1,c+1+fs.length).join("")===fs;if(s){if(r){if(a===$o)s=!1,r=!1}else if(a===ua)s=!1;continue}if(i+=l,i===n&&c<o.length-1)e.push(""),i=0}if(!i&&e.at(-1).length>0&&e.length>1)e[e.length-2]+=e.pop()},of=(e)=>{let t=e.split(" "),n=t.length;while(n>0){if(Ve(t[n-1])>0)break;n--}if(n===t.length)return e;return t.slice(0,n).join(" ")+t.slice(n).join("")},rf=(e,t,n={})=>{if(n.trim!==!1&&e.trim()==="")return"";let o="",s,r,i=sf(e),c=[""];for(let[d,f]of e.split(" ").entries()){if(n.trim!==!1)c[c.length-1]=c.at(-1).trimStart();let h=Ve(c.at(-1));if(d!==0){if(h>=t&&(n.wordWrap===!1||n.trim===!1))c.push(""),h=0;if(h>0||n.trim===!1)c[c.length-1]+=" ",h++}if(n.hard&&i[d]>t){let m=t-h,p=1+Math.floor((i[d]-m-1)/t);if(Math.floor((i[d]-1)/t)<p)c.push("");Fo(c,f,t);continue}if(h+i[d]>t&&h>0&&i[d]>0){if(n.wordWrap===!1&&h<t){Fo(c,f,t);continue}c.push("")}if(h+i[d]>t&&n.wordWrap===!1){Fo(c,f,t);continue}c[c.length-1]+=f}if(n.trim!==!1)c=c.map((d)=>of(d));let a=c.join(`
8
- `),l=[...a],u=0;for(let[d,f]of l.entries()){if(o+=f,ps.has(f)){let{groups:m}=new RegExp(`(?:\\${la}(?<code>\\d+)m|\\${fs}(?<uri>.*)${$o})`).exec(a.slice(u))||{groups:{}};if(m.code!==void 0){let p=Number.parseFloat(m.code);s=p===tf?void 0:p}else if(m.uri!==void 0)r=m.uri.length===0?void 0:m.uri}let h=ia.codes.get(Number(s));if(l[d+1]===`
9
- `){if(r)o+=ca("");if(s&&h)o+=aa(h)}else if(f===`
10
- `){if(s&&h)o+=aa(s);if(r)o+=ca(r)}u+=f.length}return o};function Ao(e,t,n){return String(e).normalize().replaceAll(`\r
7
+ `);if(s.border)o.unshift("."+"-".repeat(this.negatePadding(s)+2)+"."),o.push("'"+"-".repeat(this.negatePadding(s)+2)+"'");if(s.padding)o.unshift(...Array(s.padding[0]||0).fill("")),o.push(...Array(s.padding[2]||0).fill(""));o.forEach((i,c)=>{if(!t[c])t.push([]);let a=t[c];for(let l=0;l<r;l++)if(a[l]===void 0)a.push("");a.push(i)})}),t}negatePadding(e){let t=e.width||0;if(e.padding)t-=(e.padding[3]||0)+(e.padding[1]||0);if(e.border)t-=4;return t}columnWidths(e){if(!this.wrap)return e.map((r)=>r.width||Pe.stringWidth(r.text));let t=e.length,n=this.width,o=e.map((r)=>{if(r.width)return t--,n-=r.width,r.width;return}),s=t?Math.floor(n/t):0;return o.map((r,i)=>{if(r===void 0)return Math.max(s,Zd(e[i]));return r})}}function Ui(e,t,n){if(e.border){if(/[.']-+[.']/.test(t))return"";if(t.trim().length!==0)return n;return" "}return""}function Zd(e){let t=e.padding||[],n=1+(t[3]||0)+(t[1]||0);if(e.border)return n+4;return n}function Qd(){if(typeof process==="object"&&process.stdout&&process.stdout.columns)return process.stdout.columns;return 80}function ef(e,t){e=e.trim();let n=Pe.stringWidth(e);if(n<t)return" ".repeat(t-n)+e;return e}function tf(e,t){e=e.trim();let n=Pe.stringWidth(e);if(n>=t)return e;return" ".repeat(t-n>>1)+e}var Pe;function Ki(e,t){return Pe=t,new Ji({width:(e===null||e===void 0?void 0:e.width)||Qd(),wrap:e===null||e===void 0?void 0:e.wrap})}function Ao({onlyFirst:e=!1}={}){return new RegExp("(?:\\u001B\\][\\s\\S]*?(?:\\u0007|\\u001B\\u005C|\\u009C))|[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]",e?void 0:"g")}var nf=Ao();function It(e){if(typeof e!=="string")throw TypeError(`Expected a \`string\`, got \`${typeof e}\``);if(!e.includes("\x1B")&&!e.includes("›"))return e;return e.replace(nf,"")}var Hi=161,zi=1114109,qi=[161,161,164,164,167,168,170,170,173,174,176,180,182,186,188,191,198,198,208,208,215,216,222,225,230,230,232,234,236,237,240,240,242,243,247,250,252,252,254,254,257,257,273,273,275,275,283,283,294,295,299,299,305,307,312,312,319,322,324,324,328,331,333,333,338,339,358,359,363,363,462,462,464,464,466,466,468,468,470,470,472,472,474,474,476,476,593,593,609,609,708,708,711,711,713,715,717,717,720,720,728,731,733,733,735,735,768,879,913,929,931,937,945,961,963,969,1025,1025,1040,1103,1105,1105,8208,8208,8211,8214,8216,8217,8220,8221,8224,8226,8228,8231,8240,8240,8242,8243,8245,8245,8251,8251,8254,8254,8308,8308,8319,8319,8321,8324,8364,8364,8451,8451,8453,8453,8457,8457,8467,8467,8470,8470,8481,8482,8486,8486,8491,8491,8531,8532,8539,8542,8544,8555,8560,8569,8585,8585,8592,8601,8632,8633,8658,8658,8660,8660,8679,8679,8704,8704,8706,8707,8711,8712,8715,8715,8719,8719,8721,8721,8725,8725,8730,8730,8733,8736,8739,8739,8741,8741,8743,8748,8750,8750,8756,8759,8764,8765,8776,8776,8780,8780,8786,8786,8800,8801,8804,8807,8810,8811,8814,8815,8834,8835,8838,8839,8853,8853,8857,8857,8869,8869,8895,8895,8978,8978,9312,9449,9451,9547,9552,9587,9600,9615,9618,9621,9632,9633,9635,9641,9650,9651,9654,9655,9660,9661,9664,9665,9670,9672,9675,9675,9678,9681,9698,9701,9711,9711,9733,9734,9737,9737,9742,9743,9756,9756,9758,9758,9792,9792,9794,9794,9824,9825,9827,9829,9831,9834,9836,9837,9839,9839,9886,9887,9919,9919,9926,9933,9935,9939,9941,9953,9955,9955,9960,9961,9963,9969,9972,9972,9974,9977,9979,9980,9982,9983,10045,10045,10102,10111,11094,11097,12872,12879,57344,63743,65024,65039,65533,65533,127232,127242,127248,127277,127280,127337,127344,127373,127375,127376,127387,127404,917760,917999,983040,1048573,1048576,1114109],Gi=12288,Xi=65510,Yi=[12288,12288,65281,65376,65504,65510];var Vi=4352,Zi=262141,To=[4352,4447,8986,8987,9001,9002,9193,9196,9200,9200,9203,9203,9725,9726,9748,9749,9776,9783,9800,9811,9855,9855,9866,9871,9875,9875,9889,9889,9898,9899,9917,9918,9924,9925,9934,9934,9940,9940,9962,9962,9970,9971,9973,9973,9978,9978,9981,9981,9989,9989,9994,9995,10024,10024,10060,10060,10062,10062,10067,10069,10071,10071,10133,10135,10160,10160,10175,10175,11035,11036,11088,11088,11093,11093,11904,11929,11931,12019,12032,12245,12272,12287,12289,12350,12353,12438,12441,12543,12549,12591,12593,12686,12688,12773,12783,12830,12832,12871,12880,42124,42128,42182,43360,43388,44032,55203,63744,64255,65040,65049,65072,65106,65108,65126,65128,65131,94176,94180,94192,94198,94208,101589,101631,101662,101760,101874,110576,110579,110581,110587,110589,110590,110592,110882,110898,110898,110928,110930,110933,110933,110948,110951,110960,111355,119552,119638,119648,119670,126980,126980,127183,127183,127374,127374,127377,127386,127488,127490,127504,127547,127552,127560,127568,127569,127584,127589,127744,127776,127789,127797,127799,127868,127870,127891,127904,127946,127951,127955,127968,127984,127988,127988,127992,128062,128064,128064,128066,128252,128255,128317,128331,128334,128336,128359,128378,128378,128405,128406,128420,128420,128507,128591,128640,128709,128716,128716,128720,128722,128725,128728,128732,128735,128747,128748,128756,128764,128992,129003,129008,129008,129292,129338,129340,129349,129351,129535,129648,129660,129664,129674,129678,129734,129736,129736,129741,129756,129759,129770,129775,129784,131072,196605,196608,262141];var fs=(e,t)=>{let n=0,o=Math.floor(e.length/2)-1;while(n<=o){let s=Math.floor((n+o)/2),r=s*2;if(t<e[r])o=s-1;else if(t>e[r+1])n=s+1;else return!0}return!1};var Qi=19968,[sf,of]=rf(To);function rf(e){let t=e[0],n=e[1];for(let o=0;o<e.length;o+=2){let s=e[o],r=e[o+1];if(Qi>=s&&Qi<=r)return[s,r];if(r-s>n-t)t=s,n=r}return[t,n]}var ea=(e)=>{if(e<Hi||e>zi)return!1;return fs(qi,e)},ta=(e)=>{if(e<Gi||e>Xi)return!1;return fs(Yi,e)};var na=(e)=>{if(e>=sf&&e<=of)return!0;if(e<Vi||e>Zi)return!1;return fs(To,e)};function af(e){if(!Number.isSafeInteger(e))throw TypeError(`Expected a code point, got \`${typeof e}\`.`)}function sa(e,{ambiguousAsWide:t=!1}={}){if(af(e),ta(e)||na(e)||t&&ea(e))return 2;return 1}var ia=ji(ra(),1),cf=new Intl.Segmenter,lf=/^\p{Default_Ignorable_Code_Point}$/u;function Ze(e,t={}){if(typeof e!=="string"||e.length===0)return 0;let{ambiguousIsNarrow:n=!0,countAnsiEscapeCodes:o=!1}=t;if(!o)e=It(e);if(e.length===0)return 0;let s=0,r={ambiguousAsWide:!n};for(let{segment:i}of cf.segment(e)){let c=i.codePointAt(0);if(c<=31||c>=127&&c<=159)continue;if(c>=8203&&c<=8207||c===65279)continue;if(c>=768&&c<=879||c>=6832&&c<=6911||c>=7616&&c<=7679||c>=8400&&c<=8447||c>=65056&&c<=65071)continue;if(c>=55296&&c<=57343)continue;if(c>=65024&&c<=65039)continue;if(lf.test(i))continue;if(ia.default().test(i)){s+=2;continue}s+=sa(c,r)}return s}var aa=(e=0)=>(t)=>`\x1B[${t+e}m`,ca=(e=0)=>(t)=>`\x1B[${38+e};5;${t}m`,la=(e=0)=>(t,n,o)=>`\x1B[${38+e};2;${t};${n};${o}m`,ce={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}},cD=Object.keys(ce.modifier),uf=Object.keys(ce.color),df=Object.keys(ce.bgColor),lD=[...uf,...df];function ff(){let e=new Map;for(let[t,n]of Object.entries(ce)){for(let[o,s]of Object.entries(n))ce[o]={open:`\x1B[${s[0]}m`,close:`\x1B[${s[1]}m`},n[o]=ce[o],e.set(s[0],s[1]);Object.defineProperty(ce,t,{value:n,enumerable:!1})}return Object.defineProperty(ce,"codes",{value:e,enumerable:!1}),ce.color.close="\x1B[39m",ce.bgColor.close="\x1B[49m",ce.color.ansi=aa(),ce.color.ansi256=ca(),ce.color.ansi16m=la(),ce.bgColor.ansi=aa(10),ce.bgColor.ansi256=ca(10),ce.bgColor.ansi16m=la(10),Object.defineProperties(ce,{rgbToAnsi256:{value(t,n,o){if(t===n&&n===o){if(t<8)return 16;if(t>248)return 231;return Math.round((t-8)/247*24)+232}return 16+36*Math.round(t/255*5)+6*Math.round(n/255*5)+Math.round(o/255*5)},enumerable:!1},hexToRgb:{value(t){let n=/[a-f\d]{6}|[a-f\d]{3}/i.exec(t.toString(16));if(!n)return[0,0,0];let[o]=n;if(o.length===3)o=[...o].map((r)=>r+r).join("");let s=Number.parseInt(o,16);return[s>>16&255,s>>8&255,s&255]},enumerable:!1},hexToAnsi256:{value:(t)=>ce.rgbToAnsi256(...ce.hexToRgb(t)),enumerable:!1},ansi256ToAnsi:{value(t){if(t<8)return 30+t;if(t<16)return 90+(t-8);let n,o,s;if(t>=232)n=((t-232)*10+8)/255,o=n,s=n;else{t-=16;let c=t%36;n=Math.floor(t/36)/5,o=Math.floor(c/6)/5,s=c%6/5}let r=Math.max(n,o,s)*2;if(r===0)return 30;let i=30+(Math.round(s)<<2|Math.round(o)<<1|Math.round(n));if(r===2)i+=60;return i},enumerable:!1},rgbToAnsi:{value:(t,n,o)=>ce.ansi256ToAnsi(ce.rgbToAnsi256(t,n,o)),enumerable:!1},hexToAnsi:{value:(t)=>ce.ansi256ToAnsi(ce.hexToAnsi256(t)),enumerable:!1}}),ce}var pf=ff(),ua=pf;var hs=new Set(["\x1B","›"]),hf=39,Oo="\x07",pa="[",gf="]",ha="m",ps=`${gf}8;;`,da=(e)=>`${hs.values().next().value}${pa}${e}${ha}`,fa=(e)=>`${hs.values().next().value}${ps}${e}${Oo}`,mf=(e)=>e.split(" ").map((t)=>Ze(t)),Io=(e,t,n)=>{let o=[...t],s=!1,r=!1,i=Ze(It(e.at(-1)));for(let[c,a]of o.entries()){let l=Ze(a);if(i+l<=n)e[e.length-1]+=a;else e.push(a),i=0;if(hs.has(a))s=!0,r=o.slice(c+1,c+1+ps.length).join("")===ps;if(s){if(r){if(a===Oo)s=!1,r=!1}else if(a===ha)s=!1;continue}if(i+=l,i===n&&c<o.length-1)e.push(""),i=0}if(!i&&e.at(-1).length>0&&e.length>1)e[e.length-2]+=e.pop()},Df=(e)=>{let t=e.split(" "),n=t.length;while(n>0){if(Ze(t[n-1])>0)break;n--}if(n===t.length)return e;return t.slice(0,n).join(" ")+t.slice(n).join("")},yf=(e,t,n={})=>{if(n.trim!==!1&&e.trim()==="")return"";let o="",s,r,i=mf(e),c=[""];for(let[d,f]of e.split(" ").entries()){if(n.trim!==!1)c[c.length-1]=c.at(-1).trimStart();let h=Ze(c.at(-1));if(d!==0){if(h>=t&&(n.wordWrap===!1||n.trim===!1))c.push(""),h=0;if(h>0||n.trim===!1)c[c.length-1]+=" ",h++}if(n.hard&&i[d]>t){let m=t-h,p=1+Math.floor((i[d]-m-1)/t);if(Math.floor((i[d]-1)/t)<p)c.push("");Io(c,f,t);continue}if(h+i[d]>t&&h>0&&i[d]>0){if(n.wordWrap===!1&&h<t){Io(c,f,t);continue}c.push("")}if(h+i[d]>t&&n.wordWrap===!1){Io(c,f,t);continue}c[c.length-1]+=f}if(n.trim!==!1)c=c.map((d)=>Df(d));let a=c.join(`
8
+ `),l=[...a],u=0;for(let[d,f]of l.entries()){if(o+=f,hs.has(f)){let{groups:m}=new RegExp(`(?:\\${pa}(?<code>\\d+)m|\\${ps}(?<uri>.*)${Oo})`).exec(a.slice(u))||{groups:{}};if(m.code!==void 0){let p=Number.parseFloat(m.code);s=p===hf?void 0:p}else if(m.uri!==void 0)r=m.uri.length===0?void 0:m.uri}let h=ua.codes.get(Number(s));if(l[d+1]===`
9
+ `){if(r)o+=fa("");if(s&&h)o+=da(h)}else if(f===`
10
+ `){if(s&&h)o+=da(s);if(r)o+=fa(r)}u+=f.length}return o};function Po(e,t,n){return String(e).normalize().replaceAll(`\r
11
11
  `,`
12
12
  `).split(`
13
- `).map((o)=>rf(o,t,n)).join(`
14
- `)}function To(e){return ji(e,{stringWidth:Ve,stripAnsi:Tt,wrap:Ao})}import{dirname as da,resolve as fa}from"path";import{readdirSync as af,statSync as cf}from"fs";function Io(e,t){let n=fa(".",e),o;if(!cf(n).isDirectory())n=da(n);while(!0){if(o=t(n,af(n)),o)return fa(n,o);if(n=da(o=n),o===n)break}}import{inspect as _f}from"util";import{fileURLToPath as Aa}from"url";import{format as df}from"util";import{normalize as ff,resolve as pf}from"path";function It(e){if(!(e!==e.toLowerCase()&&e!==e.toUpperCase()))e=e.toLowerCase();if(e.indexOf("-")===-1&&e.indexOf("_")===-1)return e;else{let n="",o=!1,s=e.match(/^-+/);for(let r=s?s[0].length:0;r<e.length;r++){let i=e.charAt(r);if(o)o=!1,i=i.toUpperCase();if(r!==0&&(i==="-"||i==="_"))o=!0;else if(i!=="-"&&i!=="_")n+=i}return n}}function hs(e,t){let n=e.toLowerCase();t=t||"-";let o="";for(let s=0;s<e.length;s++){let r=n.charAt(s),i=e.charAt(s);if(r!==i&&s>0)o+=`${t}${n.charAt(s)}`;else o+=i}return o}function gs(e){if(e===null||e===void 0)return!1;if(typeof e==="number")return!0;if(/^0x[0-9a-f]+$/i.test(e))return!0;if(/^0[^.]/.test(e))return!1;return/^[-]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(e)}function pa(e){if(Array.isArray(e))return e.map((i)=>typeof i!=="string"?i+"":i);e=e.trim();let t=0,n=null,o=null,s=null,r=[];for(let i=0;i<e.length;i++){if(n=o,o=e.charAt(i),o===" "&&!s){if(n!==" ")t++;continue}if(o===s)s=null;else if((o==="'"||o==='"')&&!s)s=o;if(!r[t])r[t]="";r[t]+=o}return r}var We;(function(e){e.BOOLEAN="boolean",e.STRING="string",e.NUMBER="number",e.ARRAY="array"})(We||(We={}));var ct;class Po{constructor(e){ct=e}parse(e,t){let n=Object.assign({alias:void 0,array:void 0,boolean:void 0,config:void 0,configObjects:void 0,configuration:void 0,coerce:void 0,count:void 0,default:void 0,envPrefix:void 0,narg:void 0,normalize:void 0,string:void 0,number:void 0,__:void 0,key:void 0},t),o=pa(e),s=typeof e==="string",r=lf(Object.assign(Object.create(null),n.alias)),i=Object.assign({"boolean-negation":!0,"camel-case-expansion":!0,"combine-arrays":!1,"dot-notation":!0,"duplicate-arguments-array":!0,"flatten-duplicate-arrays":!0,"greedy-arrays":!0,"halt-at-non-option":!1,"nargs-eats-options":!1,"negation-prefix":"no-","parse-numbers":!0,"parse-positional-numbers":!0,"populate--":!1,"set-placeholder-key":!1,"short-option-groups":!0,"strip-aliased":!1,"strip-dashed":!1,"unknown-options-as-args":!1},n.configuration),c=Object.assign(Object.create(null),n.default),a=n.configObjects||[],l=n.envPrefix,u=i["populate--"],d=u?"--":"_",f=Object.create(null),h=Object.create(null),m=n.__||ct.format,p={aliases:Object.create(null),arrays:Object.create(null),bools:Object.create(null),strings:Object.create(null),numbers:Object.create(null),counts:Object.create(null),normalize:Object.create(null),configs:Object.create(null),nargs:Object.create(null),coercions:Object.create(null),keys:[]},D=/^-([0-9]+(\.[0-9]+)?|\.[0-9]+)$/,k=new RegExp("^--"+i["negation-prefix"]+"(.+)");if([].concat(n.array||[]).filter(Boolean).forEach(function(y){let b=typeof y==="object"?y.key:y,P=Object.keys(y).map(function(S){return{boolean:"bools",string:"strings",number:"numbers"}[S]}).filter(Boolean).pop();if(P)p[P][b]=!0;p.arrays[b]=!0,p.keys.push(b)}),[].concat(n.boolean||[]).filter(Boolean).forEach(function(y){p.bools[y]=!0,p.keys.push(y)}),[].concat(n.string||[]).filter(Boolean).forEach(function(y){p.strings[y]=!0,p.keys.push(y)}),[].concat(n.number||[]).filter(Boolean).forEach(function(y){p.numbers[y]=!0,p.keys.push(y)}),[].concat(n.count||[]).filter(Boolean).forEach(function(y){p.counts[y]=!0,p.keys.push(y)}),[].concat(n.normalize||[]).filter(Boolean).forEach(function(y){p.normalize[y]=!0,p.keys.push(y)}),typeof n.narg==="object")Object.entries(n.narg).forEach(([y,b])=>{if(typeof b==="number")p.nargs[y]=b,p.keys.push(y)});if(typeof n.coerce==="object")Object.entries(n.coerce).forEach(([y,b])=>{if(typeof b==="function")p.coercions[y]=b,p.keys.push(y)});if(typeof n.config<"u"){if(Array.isArray(n.config)||typeof n.config==="string")[].concat(n.config).filter(Boolean).forEach(function(y){p.configs[y]=!0});else if(typeof n.config==="object")Object.entries(n.config).forEach(([y,b])=>{if(typeof b==="boolean"||typeof b==="function")p.configs[y]=b})}at(n.key,r,n.default,p.arrays),Object.keys(c).forEach(function(y){(p.aliases[y]||[]).forEach(function(b){c[b]=c[y]})});let x=null;Eo();let E=[],F=Object.assign(Object.create(null),{_:[]}),N={};for(let y=0;y<o.length;y++){let b=o[y],P=b.replace(/^-{3,}/,"---"),S,w,U,M,H,be;if(b!=="--"&&/^-/.test(b)&&se(b))W(b);else if(P.match(/^---+(=|$)/)){W(b);continue}else if(b.match(/^--.+=/)||!i["short-option-groups"]&&b.match(/^-.+=/)){if(M=b.match(/^--?([^=]+)=([\s\S]*)$/),M!==null&&Array.isArray(M)&&M.length>=3)if(R(M[1],p.arrays))y=v(y,M[1],o,M[2]);else if(R(M[1],p.nargs)!==!1)y=O(y,M[1],o,M[2]);else J(M[1],M[2],!0)}else if(b.match(k)&&i["boolean-negation"]){if(M=b.match(k),M!==null&&Array.isArray(M)&&M.length>=2)w=M[1],J(w,R(w,p.arrays)?[!1]:!1)}else if(b.match(/^--.+/)||!i["short-option-groups"]&&b.match(/^-[^-]+/)){if(M=b.match(/^--?(.+)/),M!==null&&Array.isArray(M)&&M.length>=2)if(w=M[1],R(w,p.arrays))y=v(y,w,o);else if(R(w,p.nargs)!==!1)y=O(y,w,o);else if(H=o[y+1],H!==void 0&&(!H.match(/^-/)||H.match(D))&&!R(w,p.bools)&&!R(w,p.counts))J(w,H),y++;else if(/^(true|false)$/.test(H))J(w,H),y++;else J(w,ee(w))}else if(b.match(/^-.\..+=/)){if(M=b.match(/^-([^=]+)=([\s\S]*)$/),M!==null&&Array.isArray(M)&&M.length>=3)J(M[1],M[2])}else if(b.match(/^-.\..+/)&&!b.match(D)){if(H=o[y+1],M=b.match(/^-(.\..+)/),M!==null&&Array.isArray(M)&&M.length>=2)if(w=M[1],H!==void 0&&!H.match(/^-/)&&!R(w,p.bools)&&!R(w,p.counts))J(w,H),y++;else J(w,ee(w))}else if(b.match(/^-[^-]+/)&&!b.match(D)){U=b.slice(1,-1).split(""),S=!1;for(let Fe=0;Fe<U.length;Fe++){if(H=b.slice(Fe+2),U[Fe+1]&&U[Fe+1]==="="){if(be=b.slice(Fe+3),w=U[Fe],R(w,p.arrays))y=v(y,w,o,be);else if(R(w,p.nargs)!==!1)y=O(y,w,o,be);else J(w,be);S=!0;break}if(H==="-"){J(U[Fe],H);continue}if(/[A-Za-z]/.test(U[Fe])&&/^-?\d+(\.\d*)?(e-?\d+)?$/.test(H)&&R(H,p.bools)===!1){J(U[Fe],H),S=!0;break}if(U[Fe+1]&&U[Fe+1].match(/\W/)){J(U[Fe],H),S=!0;break}else J(U[Fe],ee(U[Fe]))}if(w=b.slice(-1)[0],!S&&w!=="-")if(R(w,p.arrays))y=v(y,w,o);else if(R(w,p.nargs)!==!1)y=O(y,w,o);else if(H=o[y+1],H!==void 0&&(!/^(-|--)[^-]/.test(H)||H.match(D))&&!R(w,p.bools)&&!R(w,p.counts))J(w,H),y++;else if(/^(true|false)$/.test(H))J(w,H),y++;else J(w,ee(w))}else if(b.match(/^-[0-9]$/)&&b.match(D)&&R(b.slice(1),p.bools))w=b.slice(1),J(w,ee(w));else if(b==="--"){E=o.slice(y+1);break}else if(i["halt-at-non-option"]){E=o.slice(y);break}else W(b)}if(Z(F,!0),Z(F,!1),T(F),B(),ve(F,p.aliases,c,!0),Y(F),i["set-placeholder-key"])oe(F);if(Object.keys(p.counts).forEach(function(y){if(!ne(F,y.split(".")))J(y,0)}),u&&E.length)F[d]=[];if(E.forEach(function(y){F[d].push(y)}),i["camel-case-expansion"]&&i["strip-dashed"])Object.keys(F).filter((y)=>y!=="--"&&y.includes("-")).forEach((y)=>{delete F[y]});if(i["strip-aliased"])[].concat(...Object.keys(r).map((y)=>r[y])).forEach((y)=>{if(i["camel-case-expansion"]&&y.includes("-"))delete F[y.split(".").map((b)=>It(b)).join(".")];delete F[y]});function W(y){let b=C("_",y);if(typeof b==="string"||typeof b==="number")F._.push(b)}function O(y,b,P,S){let w,U=R(b,p.nargs);if(U=typeof U!=="number"||isNaN(U)?1:U,U===0){if(!me(S))x=Error(m("Argument unexpected for: %s",b));return J(b,ee(b)),y}let M=me(S)?0:1;if(i["nargs-eats-options"]){if(P.length-(y+1)+M<U)x=Error(m("Not enough arguments following: %s",b));M=U}else{for(w=y+1;w<P.length;w++)if(!P[w].match(/^-[^0-9]/)||P[w].match(D)||se(P[w]))M++;else break;if(M<U)x=Error(m("Not enough arguments following: %s",b))}let H=Math.min(M,U);if(!me(S)&&H>0)J(b,S),H--;for(w=y+1;w<H+y+1;w++)J(b,P[w]);return y+H}function v(y,b,P,S){let w=[],U=S||P[y+1],M=R(b,p.nargs);if(R(b,p.bools)&&!/^(true|false)$/.test(U))w.push(!0);else if(me(U)||me(S)&&/^-/.test(U)&&!D.test(U)&&!se(U)){if(c[b]!==void 0){let H=c[b];w=Array.isArray(H)?H:[H]}}else{if(!me(S))w.push(_(b,S,!0));for(let H=y+1;H<P.length;H++){if(!i["greedy-arrays"]&&w.length>0||M&&typeof M==="number"&&w.length>=M)break;if(U=P[H],/^-/.test(U)&&!D.test(U)&&!se(U))break;y=H,w.push(_(b,U,s))}}if(typeof M==="number"&&(M&&w.length<M||isNaN(M)&&w.length===0))x=Error(m("Not enough arguments following: %s",b));return J(b,w),y}function J(y,b,P=s){if(/-/.test(y)&&i["camel-case-expansion"]){let U=y.split(".").map(function(M){return It(M)}).join(".");Q(y,U)}let S=_(y,b,P),w=y.split(".");if(Le(F,w,S),p.aliases[y])p.aliases[y].forEach(function(U){let M=U.split(".");Le(F,M,S)});if(w.length>1&&i["dot-notation"])(p.aliases[w[0]]||[]).forEach(function(U){let M=U.split("."),H=[].concat(w);if(H.shift(),M=M.concat(H),!(p.aliases[y]||[]).includes(M.join(".")))Le(F,M,S)});if(R(y,p.normalize)&&!R(y,p.arrays))[y].concat(p.aliases[y]||[]).forEach(function(M){Object.defineProperty(N,M,{enumerable:!0,get(){return b},set(H){b=typeof H==="string"?ct.normalize(H):H}})})}function Q(y,b){if(!(p.aliases[y]&&p.aliases[y].length))p.aliases[y]=[b],f[b]=!0;if(!(p.aliases[b]&&p.aliases[b].length))Q(b,y)}function _(y,b,P){if(P)b=uf(b);if(R(y,p.bools)||R(y,p.counts)){if(typeof b==="string")b=b==="true"}let S=Array.isArray(b)?b.map(function(w){return C(y,w)}):C(y,b);if(R(y,p.counts)&&(me(S)||typeof S==="boolean"))S=Oo();if(R(y,p.normalize)&&R(y,p.arrays))if(Array.isArray(b))S=b.map((w)=>ct.normalize(w));else S=ct.normalize(b);return S}function C(y,b){if(!i["parse-positional-numbers"]&&y==="_")return b;if(!R(y,p.strings)&&!R(y,p.bools)&&!Array.isArray(b)){if(gs(b)&&i["parse-numbers"]&&Number.isSafeInteger(Math.floor(parseFloat(`${b}`)))||!me(b)&&R(y,p.numbers))b=Number(b)}return b}function T(y){let b=Object.create(null);ve(b,p.aliases,c),Object.keys(p.configs).forEach(function(P){let S=y[P]||b[P];if(S)try{let w=null,U=ct.resolve(ct.cwd(),S),M=p.configs[P];if(typeof M==="function"){try{w=M(U)}catch(H){w=H}if(w instanceof Error){x=w;return}}else w=ct.require(U);A(w)}catch(w){if(w.name==="PermissionDenied")x=w;else if(y[P])x=Error(m("Invalid JSON config file: %s",S))}})}function A(y,b){Object.keys(y).forEach(function(P){let S=y[P],w=b?b+"."+P:P;if(typeof S==="object"&&S!==null&&!Array.isArray(S)&&i["dot-notation"])A(S,w);else if(!ne(F,w.split("."))||R(w,p.arrays)&&i["combine-arrays"])J(w,S)})}function B(){if(typeof a<"u")a.forEach(function(y){A(y)})}function Z(y,b){if(typeof l>"u")return;let P=typeof l==="string"?l:"",S=ct.env();Object.keys(S).forEach(function(w){if(P===""||w.lastIndexOf(P,0)===0){let U=w.split("__").map(function(M,H){if(H===0)M=M.substring(P.length);return It(M)});if((b&&p.configs[U.join(".")]||!b)&&!ne(y,U))J(U.join("."),S[w])}})}function Y(y){let b,P=new Set;Object.keys(y).forEach(function(S){if(!P.has(S)){if(b=R(S,p.coercions),typeof b==="function")try{let w=C(S,b(y[S]));[].concat(p.aliases[S]||[],S).forEach((U)=>{P.add(U),y[U]=w})}catch(w){x=w}}})}function oe(y){return p.keys.forEach((b)=>{if(~b.indexOf("."))return;if(typeof y[b]>"u")y[b]=void 0}),y}function ve(y,b,P,S=!1){Object.keys(P).forEach(function(w){if(!ne(y,w.split("."))){if(Le(y,w.split("."),P[w]),S)h[w]=!0;(b[w]||[]).forEach(function(U){if(ne(y,U.split(".")))return;Le(y,U.split("."),P[w])})}})}function ne(y,b){let P=y;if(!i["dot-notation"])b=[b.join(".")];b.slice(0,-1).forEach(function(w){P=P[w]||{}});let S=b[b.length-1];if(typeof P!=="object")return!1;else return S in P}function Le(y,b,P){let S=y;if(!i["dot-notation"])b=[b.join(".")];b.slice(0,-1).forEach(function(be){if(be=ha(be),typeof S==="object"&&S[be]===void 0)S[be]={};if(typeof S[be]!=="object"||Array.isArray(S[be])){if(Array.isArray(S[be]))S[be].push({});else S[be]=[S[be],{}];S=S[be][S[be].length-1]}else S=S[be]});let w=ha(b[b.length-1]),U=R(b.join("."),p.arrays),M=Array.isArray(P),H=i["duplicate-arguments-array"];if(!H&&R(w,p.nargs)){if(H=!0,!me(S[w])&&p.nargs[w]===1||Array.isArray(S[w])&&S[w].length===p.nargs[w])S[w]=void 0}if(P===Oo())S[w]=Oo(S[w]);else if(Array.isArray(S[w]))if(H&&U&&M)S[w]=i["flatten-duplicate-arrays"]?S[w].concat(P):(Array.isArray(S[w][0])?S[w]:[S[w]]).concat([P]);else if(!H&&Boolean(U)===Boolean(M))S[w]=P;else S[w]=S[w].concat([P]);else if(S[w]===void 0&&U)S[w]=M?P:[P];else if(H&&!(S[w]===void 0||R(w,p.counts)||R(w,p.bools)))S[w]=[S[w],P];else S[w]=P}function at(...y){y.forEach(function(b){Object.keys(b||{}).forEach(function(P){if(p.aliases[P])return;p.aliases[P]=[].concat(r[P]||[]),p.aliases[P].concat(P).forEach(function(S){if(/-/.test(S)&&i["camel-case-expansion"]){let w=It(S);if(w!==P&&p.aliases[P].indexOf(w)===-1)p.aliases[P].push(w),f[w]=!0}}),p.aliases[P].concat(P).forEach(function(S){if(S.length>1&&/[A-Z]/.test(S)&&i["camel-case-expansion"]){let w=hs(S,"-");if(w!==P&&p.aliases[P].indexOf(w)===-1)p.aliases[P].push(w),f[w]=!0}}),p.aliases[P].forEach(function(S){p.aliases[S]=[P].concat(p.aliases[P].filter(function(w){return S!==w}))})})})}function R(y,b){let P=[].concat(p.aliases[y]||[],y),S=Object.keys(b),w=P.find((U)=>S.includes(U));return w?b[w]:!1}function ue(y){let b=Object.keys(p);return[].concat(b.map((S)=>p[S])).some(function(S){return Array.isArray(S)?S.includes(y):S[y]})}function je(y,...b){return[].concat(...b).some(function(S){let w=y.match(S);return w&&ue(w[1])})}function z(y){if(y.match(D)||!y.match(/^-[^-]+/))return!1;let b=!0,P,S=y.slice(1).split("");for(let w=0;w<S.length;w++){if(P=y.slice(w+2),!ue(S[w])){b=!1;break}if(S[w+1]&&S[w+1]==="="||P==="-"||/[A-Za-z]/.test(S[w])&&/^-?\d+(\.\d*)?(e-?\d+)?$/.test(P)||S[w+1]&&S[w+1].match(/\W/))break}return b}function se(y){return i["unknown-options-as-args"]&&ge(y)}function ge(y){if(y=y.replace(/^-{3,}/,"--"),y.match(D))return!1;if(z(y))return!1;return!je(y,/^-+([^=]+?)=[\s\S]*$/,k,/^-+([^=]+?)$/,/^-+([^=]+?)-$/,/^-+([^=]+?\d+)$/,/^-+([^=]+?)\W+.*$/)}function ee(y){if(!R(y,p.bools)&&!R(y,p.counts)&&`${y}`in c)return c[y];else return Ce(de(y))}function Ce(y){return{[We.BOOLEAN]:!0,[We.STRING]:"",[We.NUMBER]:void 0,[We.ARRAY]:[]}[y]}function de(y){let b=We.BOOLEAN;if(R(y,p.strings))b=We.STRING;else if(R(y,p.numbers))b=We.NUMBER;else if(R(y,p.bools))b=We.BOOLEAN;else if(R(y,p.arrays))b=We.ARRAY;return b}function me(y){return y===void 0}function Eo(){Object.keys(p.counts).find((y)=>{if(R(y,p.arrays))return x=Error(m("Invalid configuration: %s, opts.count excludes opts.array.",y)),!0;else if(R(y,p.nargs))return x=Error(m("Invalid configuration: %s, opts.count excludes opts.narg.",y)),!0;return!1})}return{aliases:Object.assign({},p.aliases),argv:Object.assign(N,F),configuration:i,defaulted:Object.assign({},h),error:x,newAliases:Object.assign({},f)}}}function lf(e){let t=[],n=Object.create(null),o=!0;Object.keys(e).forEach(function(s){t.push([].concat(e[s],s))});while(o){o=!1;for(let s=0;s<t.length;s++)for(let r=s+1;r<t.length;r++)if(t[s].filter(function(c){return t[r].indexOf(c)!==-1}).length){t[s]=t[s].concat(t[r]),t.splice(r,1),o=!0;break}}return t.forEach(function(s){s=s.filter(function(i,c,a){return a.indexOf(i)===c});let r=s.pop();if(r!==void 0&&typeof r==="string")n[r]=s}),n}function Oo(e){return e!==void 0?e+1:1}function ha(e){if(e==="__proto__")return"___proto___";return e}function uf(e){return typeof e==="string"&&(e[0]==="'"||e[0]==='"')&&e[e.length-1]===e[0]?e.substring(1,e.length-1):e}import{readFileSync as hf}from"fs";import{createRequire as ga}from"node:module";var Ro,No,Bo,ma=process&&process.env&&process.env.YARGS_MIN_NODE_VERSION?Number(process.env.YARGS_MIN_NODE_VERSION):20,Da=(No=(Ro=process===null||process===void 0?void 0:process.versions)===null||Ro===void 0?void 0:Ro.node)!==null&&No!==void 0?No:(Bo=process===null||process===void 0?void 0:process.version)===null||Bo===void 0?void 0:Bo.slice(1);if(Da){if(Number(Da.match(/^([^.]+)/)[1])<ma)throw Error(`yargs parser supports a minimum Node.js version of ${ma}. Read our version support policy: https://github.com/yargs/yargs-parser#supported-nodejs-versions`)}var gf=process?process.env:{},ya=ga?ga(import.meta.url):void 0,wa=new Po({cwd:process.cwd,env:()=>gf,format:df,normalize:ff,resolve:pf,require:(e)=>{if(typeof ya<"u")return ya(e);else if(e.match(/\.json$/))return JSON.parse(hf(e,"utf8"));else throw Error("only .json config files are supported in ESM")}}),Sn=function(t,n){return wa.parse(t.slice(),n).argv};Sn.detailed=function(e,t){return wa.parse(e.slice(),t)};Sn.camelCase=It;Sn.decamelize=hs;Sn.looksLikeNumber=gs;var Mo=Sn;import{basename as Ff,dirname as $f,extname as Af,relative as Tf,resolve as $a,join as If}from"path";function ba(){if(mf())return 0;return 1}function mf(){return Df()&&!process.defaultApp}function Df(){return!!process.versions.electron}function vo(e){return e.slice(ba()+1)}function ka(){return process.argv[ba()]}import{readFileSync as yf,statSync as wf,writeFile as bf}from"fs";import{format as kf}from"util";import{resolve as xf}from"path";var xa={fs:{readFileSync:yf,writeFile:bf},format:kf,resolve:xf,exists:(e)=>{try{return wf(e).isFile()}catch(t){return!1}}};var Ze;class Ca{constructor(e){e=e||{},this.directory=e.directory||"./locales",this.updateFiles=typeof e.updateFiles==="boolean"?e.updateFiles:!0,this.locale=e.locale||"en",this.fallbackToLanguage=typeof e.fallbackToLanguage==="boolean"?e.fallbackToLanguage:!0,this.cache=Object.create(null),this.writeQueue=[]}__(...e){if(typeof arguments[0]!=="string")return this._taggedLiteral(arguments[0],...arguments);let t=e.shift(),n=function(){};if(typeof e[e.length-1]==="function")n=e.pop();if(n=n||function(){},!this.cache[this.locale])this._readLocaleFile();if(!this.cache[this.locale][t]&&this.updateFiles)this.cache[this.locale][t]=t,this._enqueueWrite({directory:this.directory,locale:this.locale,cb:n});else n();return Ze.format.apply(Ze.format,[this.cache[this.locale][t]||t].concat(e))}__n(){let e=Array.prototype.slice.call(arguments),t=e.shift(),n=e.shift(),o=e.shift(),s=function(){};if(typeof e[e.length-1]==="function")s=e.pop();if(!this.cache[this.locale])this._readLocaleFile();let r=o===1?t:n;if(this.cache[this.locale][t])r=this.cache[this.locale][t][o===1?"one":"other"];if(!this.cache[this.locale][t]&&this.updateFiles)this.cache[this.locale][t]={one:t,other:n},this._enqueueWrite({directory:this.directory,locale:this.locale,cb:s});else s();let i=[r];if(~r.indexOf("%d"))i.push(o);return Ze.format.apply(Ze.format,i.concat(e))}setLocale(e){this.locale=e}getLocale(){return this.locale}updateLocale(e){if(!this.cache[this.locale])this._readLocaleFile();for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t))this.cache[this.locale][t]=e[t]}_taggedLiteral(e,...t){let n="";return e.forEach(function(o,s){let r=t[s+1];if(n+=o,typeof r<"u")n+="%s"}),this.__.apply(this,[n].concat([].slice.call(t,1)))}_enqueueWrite(e){if(this.writeQueue.push(e),this.writeQueue.length===1)this._processWriteQueue()}_processWriteQueue(){let e=this,t=this.writeQueue[0],{directory:n,locale:o,cb:s}=t,r=this._resolveLocaleFile(n,o),i=JSON.stringify(this.cache[o],null,2);Ze.fs.writeFile(r,i,"utf-8",function(c){if(e.writeQueue.shift(),e.writeQueue.length>0)e._processWriteQueue();s(c)})}_readLocaleFile(){let e={},t=this._resolveLocaleFile(this.directory,this.locale);try{if(Ze.fs.readFileSync)e=JSON.parse(Ze.fs.readFileSync(t,"utf-8"))}catch(n){if(n instanceof SyntaxError)n.message="syntax error in "+t;if(n.code==="ENOENT")e={};else throw n}this.cache[this.locale]=e}_resolveLocaleFile(e,t){let n=Ze.resolve(e,"./",t+".json");if(this.fallbackToLanguage&&!this._fileExistsSync(n)&&~t.lastIndexOf("_")){let o=Ze.resolve(e,"./",t.split("_")[0]+".json");if(this._fileExistsSync(o))n=o}return n}_fileExistsSync(e){return Ze.exists(e)}}function Ea(e,t){Ze=t;let n=new Ca(e);return{__:n.__.bind(n),__n:n.__n.bind(n),setLocale:n.setLocale.bind(n),getLocale:n.getLocale.bind(n),updateLocale:n.updateLocale.bind(n),locale:n.locale}}var Cf=(e)=>Ea(e,xa),Sa=Cf;var Ta=Bi(Fa(),1);import{createRequire as Of}from"node:module";import{readFileSync as Pf,readdirSync as Rf}from"node:fs";var Lo=Aa(import.meta.url),Nf=Lo.substring(0,Lo.lastIndexOf("node_modules")),Bf=Of(import.meta.url),jo={assert:{notStrictEqual:Ef,strictEqual:Sf},cliui:To,findUp:Io,getEnv:(e)=>process.env[e],inspect:_f,getProcessArgvBin:ka,mainFilename:Nf||process.cwd(),Parser:Mo,path:{basename:Ff,dirname:$f,extname:Af,relative:Tf,resolve:$a,join:If},process:{argv:()=>process.argv,cwd:process.cwd,emitWarning:(e,t)=>process.emitWarning(e,t),execPath:()=>process.execPath,exit:(e)=>{process.exit(e)},nextTick:process.nextTick,stdColumns:typeof process.stdout.columns<"u"?process.stdout.columns:null},readFileSync:Pf,readdirSync:Rf,require:Bf,getCallerFile:()=>{let e=Ta.default(3);return e.match(/^file:\/\//)?Aa(e):e},stringWidth:Ve,y18n:Sa({directory:$a(Lo,"../../../locales"),updateFiles:!1})};function $e(e,t,n,o){n.assert.notStrictEqual(e,t,o)}function Wo(e,t){t.assert.strictEqual(typeof e,"string")}function sn(e){return Object.keys(e)}function re(e){return!!e&&!!e.then&&typeof e.then==="function"}class fe extends Error{constructor(e){super(e||"yargs error");if(this.name="YError",Error.captureStackTrace)Error.captureStackTrace(this,fe)}}function gt(e){let n=e.replace(/\s{2,}/g," ").split(/\s+(?![^[]*]|[^<]*>)/),o=/\.*[\][<>]/g,s=n.shift();if(!s)throw Error(`No command found in: ${e}`);let r={cmd:s.replace(o,""),demanded:[],optional:[]};return n.forEach((i,c)=>{let a=!1;if(i=i.replace(/\s/g,""),/\.+[\]>]/.test(i)&&c===n.length-1)a=!0;if(/^\[/.test(i))r.optional.push({cmd:i.replace(o,"").split("|"),variadic:a});else r.demanded.push({cmd:i.replace(o,"").split("|"),variadic:a})}),r}var Mf=["first","second","third","fourth","fifth","sixth"];function L(e,t,n){function o(){return typeof e==="object"?[{demanded:[],optional:[]},e,t]:[gt(`cmd ${e}`),t,n]}try{let s=0,[r,i,c]=o(),a=[].slice.call(i);while(a.length&&a[a.length-1]===void 0)a.pop();let l=c||a.length;if(l<r.demanded.length)throw new fe(`Not enough arguments provided. Expected ${r.demanded.length} but received ${a.length}.`);let u=r.demanded.length+r.optional.length;if(l>u)throw new fe(`Too many arguments provided. Expected max ${u} but received ${l}.`);r.demanded.forEach((d)=>{let f=a.shift(),h=Ia(f);if(d.cmd.filter((p)=>p===h||p==="*").length===0)Oa(h,d.cmd,s);s+=1}),r.optional.forEach((d)=>{if(a.length===0)return;let f=a.shift(),h=Ia(f);if(d.cmd.filter((p)=>p===h||p==="*").length===0)Oa(h,d.cmd,s);s+=1})}catch(s){console.warn(s.stack)}}function Ia(e){if(Array.isArray(e))return"array";else if(e===null)return"null";return typeof e}function Oa(e,t,n){throw new fe(`Invalid ${Mf[n]||"manyith"} argument. Expected ${t.join(" or ")} but received ${e}.`)}class Uo{constructor(e){this.globalMiddleware=[],this.frozens=[],this.yargs=e}addMiddleware(e,t,n=!0,o=!1){if(L("<array|function> [boolean] [boolean] [boolean]",[e,t,n],arguments.length),Array.isArray(e)){for(let s=0;s<e.length;s++){if(typeof e[s]!=="function")throw Error("middleware must be a function");let r=e[s];r.applyBeforeValidation=t,r.global=n}Array.prototype.push.apply(this.globalMiddleware,e)}else if(typeof e==="function"){let s=e;s.applyBeforeValidation=t,s.global=n,s.mutates=o,this.globalMiddleware.push(e)}return this.yargs}addCoerceMiddleware(e,t){let n=this.yargs.getAliases();return this.globalMiddleware=this.globalMiddleware.filter((o)=>{let s=[...n[t]||[],t];if(!o.option)return!0;else return!s.includes(o.option)}),e.option=t,this.addMiddleware(e,!0,!0,!0)}getMiddleware(){return this.globalMiddleware}freeze(){this.frozens.push([...this.globalMiddleware])}unfreeze(){let e=this.frozens.pop();if(e!==void 0)this.globalMiddleware=e}reset(){this.globalMiddleware=this.globalMiddleware.filter((e)=>e.global)}}function Pa(e){if(!e)return[];return e.map((t)=>(t.applyBeforeValidation=!1,t))}function Ot(e,t,n,o){return n.reduce((s,r)=>{if(r.applyBeforeValidation!==o)return s;if(r.mutates){if(r.applied)return s;r.applied=!0}if(re(s))return s.then((i)=>Promise.all([i,r(i,t)])).then(([i,c])=>Object.assign(i,c));else{let i=r(s,t);return re(i)?i.then((c)=>Object.assign(s,c)):Object.assign(s,i)}},e)}function Pt(e,t,n=(o)=>{throw o}){try{let o=vf(e)?e():e;return re(o)?o.then((s)=>t(s)):t(o)}catch(o){return n(o)}}function vf(e){return typeof e==="function"}var on=/(^\*)|(^\$0)/;class Na{constructor(e,t,n,o){this.requireCache=new Set,this.handlers={},this.aliasMap={},this.frozens=[],this.shim=o,this.usage=e,this.globalMiddleware=n,this.validation=t}addDirectory(e,t,n,o){o=o||{},this.requireCache.add(n);let s=this.shim.path.resolve(this.shim.path.dirname(n),e),r=this.shim.readdirSync(s,{recursive:o.recurse?!0:!1});if(!Array.isArray(o.extensions))o.extensions=["js"];let i=typeof o.visit==="function"?o.visit:(c)=>c;for(let c of r){let a=c.toString();if(o.exclude){let u=!1;if(typeof o.exclude==="function")u=o.exclude(a);else u=o.exclude.test(a);if(u)continue}if(o.include){let u=!1;if(typeof o.include==="function")u=o.include(a);else u=o.include.test(a);if(!u)continue}let l=!1;for(let u of o.extensions)if(a.endsWith(u))l=!0;if(l){let u=this.shim.path.join(s,a),d=t(u),f=Object.create(null,Object.getOwnPropertyDescriptors({...d}));if(i(f,u,a)){if(this.requireCache.has(u))continue;else this.requireCache.add(u);if(!f.command)f.command=this.shim.path.basename(u,this.shim.path.extname(u));this.addHandler(f)}}}}addHandler(e,t,n,o,s,r){let i=[],c=Pa(s);if(o=o||(()=>{}),Array.isArray(e))if(Lf(e))[e,...i]=e;else for(let a of e)this.addHandler(a);else if(Wf(e)){let a=Array.isArray(e.command)||typeof e.command==="string"?e.command:null;if(a===null)throw Error(`No command name given for module: ${this.shim.inspect(e)}`);if(e.aliases)a=[].concat(a).concat(e.aliases);this.addHandler(a,this.extractDesc(e),e.builder,e.handler,e.middlewares,e.deprecated);return}else if(Ra(n)){this.addHandler([e].concat(i),t,n.builder,n.handler,n.middlewares,n.deprecated);return}if(typeof e==="string"){let a=gt(e);i=i.map((d)=>gt(d).cmd);let l=!1,u=[a.cmd].concat(i).filter((d)=>{if(on.test(d))return l=!0,!1;return!0});if(u.length===0&&l)u.push("$0");if(l)a.cmd=u[0],i=u.slice(1),e=e.replace(on,a.cmd);if(i.forEach((d)=>{this.aliasMap[d]=a.cmd}),t!==!1)this.usage.command(e,t,l,i,r);if(this.handlers[a.cmd]={original:e,description:t,handler:o,builder:n||{},middlewares:c,deprecated:r,demanded:a.demanded,optional:a.optional},l)this.defaultCommand=this.handlers[a.cmd]}}getCommandHandlers(){return this.handlers}getCommands(){return Object.keys(this.handlers).concat(Object.keys(this.aliasMap))}hasDefaultCommand(){return!!this.defaultCommand}runCommand(e,t,n,o,s,r){let i=this.handlers[e]||this.handlers[this.aliasMap[e]]||this.defaultCommand,c=t.getInternalMethods().getContext(),a=c.commands.slice(),l=!e;if(e)c.commands.push(e),c.fullCommands.push(i.original);let u=this.applyBuilderUpdateUsageAndParse(l,i,t,n.aliases,a,o,s,r);return re(u)?u.then((d)=>this.applyMiddlewareAndGetResult(l,i,d.innerArgv,c,s,d.aliases,t)):this.applyMiddlewareAndGetResult(l,i,u.innerArgv,c,s,u.aliases,t)}applyBuilderUpdateUsageAndParse(e,t,n,o,s,r,i,c){let a=t.builder,l=n;if(ms(a)){n.getInternalMethods().getUsageInstance().freeze();let u=a(n.getInternalMethods().reset(o),c);if(re(u))return u.then((d)=>(l=Ma(d)?d:n,this.parseAndUpdateUsage(e,t,l,s,r,i)))}else if(jf(a))n.getInternalMethods().getUsageInstance().freeze(),l=n.getInternalMethods().reset(o),Object.keys(t.builder).forEach((u)=>{l.option(u,a[u])});return this.parseAndUpdateUsage(e,t,l,s,r,i)}parseAndUpdateUsage(e,t,n,o,s,r){if(e)n.getInternalMethods().getUsageInstance().unfreeze(!0);if(this.shouldUpdateUsage(n))n.getInternalMethods().getUsageInstance().usage(this.usageFromParentCommandsCommandHandler(o,t),t.description);let i=n.getInternalMethods().runYargsParserAndExecuteCommands(null,void 0,!0,s,r);return re(i)?i.then((c)=>({aliases:n.parsed.aliases,innerArgv:c})):{aliases:n.parsed.aliases,innerArgv:i}}shouldUpdateUsage(e){return!e.getInternalMethods().getUsageInstance().getUsageDisabled()&&e.getInternalMethods().getUsageInstance().getUsage().length===0}usageFromParentCommandsCommandHandler(e,t){let n=on.test(t.original)?t.original.replace(on,"").trim():t.original,o=e.filter((s)=>!on.test(s));return o.push(n),`$0 ${o.join(" ")}`}handleValidationAndGetResult(e,t,n,o,s,r,i,c){if(!r.getInternalMethods().getHasOutput()){let a=r.getInternalMethods().runValidation(s,c,r.parsed.error,e);n=Pt(n,(l)=>(a(l),l))}if(t.handler&&!r.getInternalMethods().getHasOutput()){r.getInternalMethods().setHasOutput();let a=!!r.getOptions().configuration["populate--"];if(r.getInternalMethods().postProcess(n,a,!1,!1),n=Ot(n,r,i,!1),n=Pt(n,(l)=>{let u=t.handler(l);return re(u)?u.then(()=>l):l}),!e)r.getInternalMethods().getUsageInstance().cacheHelpMessage();if(re(n)&&!r.getInternalMethods().hasParseCallback())n.catch((l)=>{try{r.getInternalMethods().getUsageInstance().fail(null,l)}catch(u){}})}if(!e)o.commands.pop(),o.fullCommands.pop();return n}applyMiddlewareAndGetResult(e,t,n,o,s,r,i){let c={};if(s)return n;if(!i.getInternalMethods().getHasOutput())c=this.populatePositionals(t,n,o,i);let a=this.globalMiddleware.getMiddleware().slice(0).concat(t.middlewares),l=Ot(n,i,a,!0);return re(l)?l.then((u)=>this.handleValidationAndGetResult(e,t,u,o,r,i,a,c)):this.handleValidationAndGetResult(e,t,l,o,r,i,a,c)}populatePositionals(e,t,n,o){t._=t._.slice(n.commands.length);let s=e.demanded.slice(0),r=e.optional.slice(0),i={};this.validation.positionalCount(s.length,t._.length);while(s.length){let c=s.shift();this.populatePositional(c,t,i)}while(r.length){let c=r.shift();this.populatePositional(c,t,i)}return t._=n.commands.concat(t._.map((c)=>""+c)),this.postProcessPositionals(t,i,this.cmdToParseOptions(e.original),o),i}populatePositional(e,t,n){let o=e.cmd[0];if(e.variadic)n[o]=t._.splice(0).map(String);else if(t._.length)n[o]=[String(t._.shift())]}cmdToParseOptions(e){let t={array:[],default:{},alias:{},demand:{}},n=gt(e);return n.demanded.forEach((o)=>{let[s,...r]=o.cmd;if(o.variadic)t.array.push(s),t.default[s]=[];t.alias[s]=r,t.demand[s]=!0}),n.optional.forEach((o)=>{let[s,...r]=o.cmd;if(o.variadic)t.array.push(s),t.default[s]=[];t.alias[s]=r}),t}postProcessPositionals(e,t,n,o){let s=Object.assign({},o.getOptions());s.default=Object.assign(n.default,s.default);for(let a of Object.keys(n.alias))s.alias[a]=(s.alias[a]||[]).concat(n.alias[a]);s.array=s.array.concat(n.array),s.config={};let r=[];if(Object.keys(t).forEach((a)=>{t[a].map((l)=>{if(s.configuration["unknown-options-as-args"])s.key[a]=!0;r.push(`--${a}`),r.push(l)})}),!r.length)return;let i=Object.assign({},s.configuration,{"populate--":!1}),c=this.shim.Parser.detailed(r,Object.assign({},s,{configuration:i}));if(c.error)o.getInternalMethods().getUsageInstance().fail(c.error.message,c.error);else{let a=Object.keys(t);Object.keys(t).forEach((l)=>{a.push(...c.aliases[l])}),Object.keys(c.argv).forEach((l)=>{if(a.includes(l)){if(!t[l])t[l]=c.argv[l];if(!this.isInConfigs(o,l)&&!this.isDefaulted(o,l)&&Object.prototype.hasOwnProperty.call(e,l)&&Object.prototype.hasOwnProperty.call(c.argv,l)&&(Array.isArray(e[l])||Array.isArray(c.argv[l])))e[l]=[].concat(e[l],c.argv[l]);else e[l]=c.argv[l]}})}}isDefaulted(e,t){let{default:n}=e.getOptions();return Object.prototype.hasOwnProperty.call(n,t)||Object.prototype.hasOwnProperty.call(n,this.shim.Parser.camelCase(t))}isInConfigs(e,t){let{configObjects:n}=e.getOptions();return n.some((o)=>Object.prototype.hasOwnProperty.call(o,t))||n.some((o)=>Object.prototype.hasOwnProperty.call(o,this.shim.Parser.camelCase(t)))}runDefaultBuilderOn(e){if(!this.defaultCommand)return;if(this.shouldUpdateUsage(e)){let n=on.test(this.defaultCommand.original)?this.defaultCommand.original:this.defaultCommand.original.replace(/^[^[\]<>]*/,"$0 ");e.getInternalMethods().getUsageInstance().usage(n,this.defaultCommand.description)}let t=this.defaultCommand.builder;if(ms(t))return t(e,!0);else if(!Ra(t))Object.keys(t).forEach((n)=>{e.option(n,t[n])});return}extractDesc({describe:e,description:t,desc:n}){for(let o of[e,t,n]){if(typeof o==="string"||o===!1)return o;$e(o,!0,this.shim)}return!1}freeze(){this.frozens.push({handlers:this.handlers,aliasMap:this.aliasMap,defaultCommand:this.defaultCommand})}unfreeze(){let e=this.frozens.pop();$e(e,void 0,this.shim),{handlers:this.handlers,aliasMap:this.aliasMap,defaultCommand:this.defaultCommand}=e}reset(){return this.handlers={},this.aliasMap={},this.defaultCommand=void 0,this.requireCache=new Set,this}}function Ba(e,t,n,o){return new Na(e,t,n,o)}function Ra(e){return typeof e==="object"&&!!e.builder&&typeof e.handler==="function"}function Lf(e){return e.every((t)=>typeof t==="string")}function ms(e){return typeof e==="function"}function jf(e){return typeof e==="object"}function Wf(e){return typeof e==="object"&&!Array.isArray(e)}function mt(e={},t=()=>!0){let n={};return sn(e).forEach((o)=>{if(t(o,e[o]))n[o]=e[o]}),n}function Dt(e){if(typeof process>"u")return;[process.stdout,process.stderr].forEach((t)=>{let n=t;if(n._handle&&n.isTTY&&typeof n._handle.setBlocking==="function")n._handle.setBlocking(e)})}function Uf(e){return typeof e==="boolean"}function La(e,t){let n=t.y18n.__,o={},s=[];o.failFn=function(C){s.push(C)};let r=null,i=null,c=!0;o.showHelpOnFail=function(C=!0,T){let[A,B]=typeof C==="string"?[!0,C]:[C,T];if(e.getInternalMethods().isGlobalContext())i=B;return r=B,c=A,o};let a=!1;o.fail=function(C,T){let A=e.getInternalMethods().getLoggerInstance();if(s.length)for(let B=s.length-1;B>=0;--B){let Z=s[B];if(Uf(Z)){if(T)throw T;else if(C)throw Error(C)}else Z(C,T,o)}else{if(e.getExitProcess())Dt(!0);if(!a){if(a=!0,c)e.showHelp("error"),A.error();if(C||T)A.error(C||T);let B=r||i;if(B){if(C||T)A.error("");A.error(B)}}if(T=T||new fe(C),e.getExitProcess())return e.exit(1);else if(e.getInternalMethods().hasParseCallback())return e.exit(1,T);else throw T}};let l=[],u=!1;o.usage=(_,C)=>{if(_===null)return u=!0,l=[],o;return u=!1,l.push([_,C||""]),o},o.getUsage=()=>l,o.getUsageDisabled=()=>u,o.getPositionalGroupName=()=>n("Positionals:");let d=[];o.example=(_,C)=>{d.push([_,C||""])};let f=[];o.command=function(C,T,A,B,Z=!1){if(A)f=f.map((Y)=>(Y[2]=!1,Y));f.push([C,T||"",A,B,Z])},o.getCommands=()=>f;let h={};o.describe=function(C,T){if(Array.isArray(C))C.forEach((A)=>{o.describe(A,T)});else if(typeof C==="object")Object.keys(C).forEach((A)=>{o.describe(A,C[A])});else h[C]=T},o.getDescriptions=()=>h;let m=[];o.epilog=(_)=>{m.push(_)};let p=!1,D;o.wrap=(_)=>{p=!0,D=_},o.getWrap=()=>{if(t.getEnv("YARGS_DISABLE_WRAP"))return null;if(!p)D=v(),p=!0;return D};let k="__yargsString__:";o.deferY18nLookup=(_)=>k+_,o.help=function(){if(F)return F;E();let C=e.customScriptName?e.$0:t.path.basename(e.$0),T=e.getDemandedOptions(),A=e.getDemandedCommands(),B=e.getDeprecatedOptions(),Z=e.getGroups(),Y=e.getOptions(),oe=[];oe=oe.concat(Object.keys(h)),oe=oe.concat(Object.keys(T)),oe=oe.concat(Object.keys(A)),oe=oe.concat(Object.keys(Y.default)),oe=oe.filter(W),oe=Object.keys(oe.reduce((z,se)=>{if(se!=="_")z[se]=!0;return z},{}));let ve=o.getWrap(),ne=t.cliui({width:ve,wrap:!!ve});if(!u){if(l.length)l.forEach((z)=>{if(ne.div({text:`${z[0].replace(/\$0/g,C)}`}),z[1])ne.div({text:`${z[1]}`,padding:[1,0,0,0]})}),ne.div();else if(f.length){let z=null;if(A._)z=`${C} <${n("command")}>
15
- `;else z=`${C} [${n("command")}]
16
- `;ne.div(`${z}`)}}if(f.length>1||f.length===1&&!f[0][2]){ne.div(n("Commands:"));let z=e.getInternalMethods().getContext(),se=z.commands.length?`${z.commands.join(" ")} `:"";if(e.getInternalMethods().getParserConfiguration()["sort-commands"]===!0)f=f.sort((ee,Ce)=>ee[0].localeCompare(Ce[0]));let ge=C?`${C} `:"";f.forEach((ee)=>{let Ce=`${ge}${se}${ee[0].replace(/^\$0 ?/,"")}`;ne.span({text:Ce,padding:[0,2,0,2],width:x(f,ve,`${C}${se}`)+4},{text:ee[1]});let de=[];if(ee[2])de.push(`[${n("default")}]`);if(ee[3]&&ee[3].length)de.push(`[${n("aliases:")} ${ee[3].join(", ")}]`);if(ee[4])if(typeof ee[4]==="string")de.push(`[${n("deprecated: %s",ee[4])}]`);else de.push(`[${n("deprecated")}]`);if(de.length)ne.div({text:de.join(" "),padding:[0,0,0,2],align:"right"});else ne.div()}),ne.div()}let Le=(Object.keys(Y.alias)||[]).concat(Object.keys(e.parsed.newAliases)||[]);oe=oe.filter((z)=>!e.parsed.newAliases[z]&&Le.every((se)=>(Y.alias[se]||[]).indexOf(z)===-1));let at=n("Options:");if(!Z[at])Z[at]=[];N(oe,Y.alias,Z,at);let R=(z)=>/^--/.test(Ds(z)),ue=Object.keys(Z).filter((z)=>Z[z].length>0).map((z)=>{let se=Z[z].filter(W).map((ge)=>{if(Le.includes(ge))return ge;for(let ee=0,Ce;(Ce=Le[ee])!==void 0;ee++)if((Y.alias[Ce]||[]).includes(ge))return Ce;return ge});return{groupName:z,normalizedKeys:se}}).filter(({normalizedKeys:z})=>z.length>0).map(({groupName:z,normalizedKeys:se})=>{let ge=se.reduce((ee,Ce)=>(ee[Ce]=[Ce].concat(Y.alias[Ce]||[]).map((de)=>{if(z===o.getPositionalGroupName())return de;else return(/^[0-9]$/.test(de)?Y.boolean.includes(Ce)?"-":"--":de.length>1?"--":"-")+de}).sort((de,me)=>R(de)===R(me)?0:R(de)?1:-1).join(", "),ee),{});return{groupName:z,normalizedKeys:se,switches:ge}});if(ue.filter(({groupName:z})=>z!==o.getPositionalGroupName()).some(({normalizedKeys:z,switches:se})=>!z.every((ge)=>R(se[ge]))))ue.filter(({groupName:z})=>z!==o.getPositionalGroupName()).forEach(({normalizedKeys:z,switches:se})=>{z.forEach((ge)=>{if(R(se[ge]))se[ge]=Jf(se[ge],4)})});if(ue.forEach(({groupName:z,normalizedKeys:se,switches:ge})=>{ne.div(z),se.forEach((ee)=>{let Ce=ge[ee],de=h[ee]||"",me=null;if(de.includes(k))de=n(de.substring(k.length));if(Y.boolean.includes(ee))me=`[${n("boolean")}]`;if(Y.count.includes(ee))me=`[${n("count")}]`;if(Y.string.includes(ee))me=`[${n("string")}]`;if(Y.normalize.includes(ee))me=`[${n("string")}]`;if(Y.array.includes(ee))me=`[${n("array")}]`;if(Y.number.includes(ee))me=`[${n("number")}]`;let Eo=(P)=>typeof P==="string"?`[${n("deprecated: %s",P)}]`:`[${n("deprecated")}]`,y=[ee in B?Eo(B[ee]):null,me,ee in T?`[${n("required")}]`:null,Y.choices&&Y.choices[ee]?`[${n("choices:")} ${o.stringifiedValues(Y.choices[ee])}]`:null,O(Y.default[ee],Y.defaultDescription[ee])].filter(Boolean).join(" ");ne.span({text:Ds(Ce),padding:[0,2,0,2+va(Ce)],width:x(ge,ve)+4},de);let b=e.getInternalMethods().getUsageConfiguration()["hide-types"]===!0;if(y&&!b)ne.div({text:y,padding:[0,0,0,2],align:"right"});else ne.div()}),ne.div()}),d.length)ne.div(n("Examples:")),d.forEach((z)=>{z[0]=z[0].replace(/\$0/g,C)}),d.forEach((z)=>{if(z[1]==="")ne.div({text:z[0],padding:[0,2,0,2]});else ne.div({text:z[0],padding:[0,2,0,2],width:x(d,ve)+4},{text:z[1]})}),ne.div();if(m.length>0){let z=m.map((se)=>se.replace(/\$0/g,C)).join(`
13
+ `).map((o)=>yf(o,t,n)).join(`
14
+ `)}function Ro(e){return Ki(e,{stringWidth:Ze,stripAnsi:It,wrap:Po})}import{dirname as ga,resolve as ma}from"path";import{readdirSync as wf,statSync as bf}from"fs";function No(e,t){let n=ma(".",e),o;if(!bf(n).isDirectory())n=ga(n);while(!0){if(o=t(n,wf(n)),o)return ma(n,o);if(n=ga(o=n),o===n)break}}import{inspect as Lf}from"util";import{fileURLToPath as Pa}from"url";import{format as Ef}from"util";import{normalize as Cf,resolve as Sf}from"path";function Ot(e){if(!(e!==e.toLowerCase()&&e!==e.toUpperCase()))e=e.toLowerCase();if(e.indexOf("-")===-1&&e.indexOf("_")===-1)return e;else{let n="",o=!1,s=e.match(/^-+/);for(let r=s?s[0].length:0;r<e.length;r++){let i=e.charAt(r);if(o)o=!1,i=i.toUpperCase();if(r!==0&&(i==="-"||i==="_"))o=!0;else if(i!=="-"&&i!=="_")n+=i}return n}}function gs(e,t){let n=e.toLowerCase();t=t||"-";let o="";for(let s=0;s<e.length;s++){let r=n.charAt(s),i=e.charAt(s);if(r!==i&&s>0)o+=`${t}${n.charAt(s)}`;else o+=i}return o}function ms(e){if(e===null||e===void 0)return!1;if(typeof e==="number")return!0;if(/^0x[0-9a-f]+$/i.test(e))return!0;if(/^0[^.]/.test(e))return!1;return/^[-]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(e)}function Da(e){if(Array.isArray(e))return e.map((i)=>typeof i!=="string"?i+"":i);e=e.trim();let t=0,n=null,o=null,s=null,r=[];for(let i=0;i<e.length;i++){if(n=o,o=e.charAt(i),o===" "&&!s){if(n!==" ")t++;continue}if(o===s)s=null;else if((o==="'"||o==='"')&&!s)s=o;if(!r[t])r[t]="";r[t]+=o}return r}var Je;(function(e){e.BOOLEAN="boolean",e.STRING="string",e.NUMBER="number",e.ARRAY="array"})(Je||(Je={}));var lt;class vo{constructor(e){lt=e}parse(e,t){let n=Object.assign({alias:void 0,array:void 0,boolean:void 0,config:void 0,configObjects:void 0,configuration:void 0,coerce:void 0,count:void 0,default:void 0,envPrefix:void 0,narg:void 0,normalize:void 0,string:void 0,number:void 0,__:void 0,key:void 0},t),o=Da(e),s=typeof e==="string",r=kf(Object.assign(Object.create(null),n.alias)),i=Object.assign({"boolean-negation":!0,"camel-case-expansion":!0,"combine-arrays":!1,"dot-notation":!0,"duplicate-arguments-array":!0,"flatten-duplicate-arrays":!0,"greedy-arrays":!0,"halt-at-non-option":!1,"nargs-eats-options":!1,"negation-prefix":"no-","parse-numbers":!0,"parse-positional-numbers":!0,"populate--":!1,"set-placeholder-key":!1,"short-option-groups":!0,"strip-aliased":!1,"strip-dashed":!1,"unknown-options-as-args":!1},n.configuration),c=Object.assign(Object.create(null),n.default),a=n.configObjects||[],l=n.envPrefix,u=i["populate--"],d=u?"--":"_",f=Object.create(null),h=Object.create(null),m=n.__||lt.format,p={aliases:Object.create(null),arrays:Object.create(null),bools:Object.create(null),strings:Object.create(null),numbers:Object.create(null),counts:Object.create(null),normalize:Object.create(null),configs:Object.create(null),nargs:Object.create(null),coercions:Object.create(null),keys:[]},D=/^-([0-9]+(\.[0-9]+)?|\.[0-9]+)$/,k=new RegExp("^--"+i["negation-prefix"]+"(.+)");if([].concat(n.array||[]).filter(Boolean).forEach(function(y){let b=typeof y==="object"?y.key:y,P=Object.keys(y).map(function(S){return{boolean:"bools",string:"strings",number:"numbers"}[S]}).filter(Boolean).pop();if(P)p[P][b]=!0;p.arrays[b]=!0,p.keys.push(b)}),[].concat(n.boolean||[]).filter(Boolean).forEach(function(y){p.bools[y]=!0,p.keys.push(y)}),[].concat(n.string||[]).filter(Boolean).forEach(function(y){p.strings[y]=!0,p.keys.push(y)}),[].concat(n.number||[]).filter(Boolean).forEach(function(y){p.numbers[y]=!0,p.keys.push(y)}),[].concat(n.count||[]).filter(Boolean).forEach(function(y){p.counts[y]=!0,p.keys.push(y)}),[].concat(n.normalize||[]).filter(Boolean).forEach(function(y){p.normalize[y]=!0,p.keys.push(y)}),typeof n.narg==="object")Object.entries(n.narg).forEach(([y,b])=>{if(typeof b==="number")p.nargs[y]=b,p.keys.push(y)});if(typeof n.coerce==="object")Object.entries(n.coerce).forEach(([y,b])=>{if(typeof b==="function")p.coercions[y]=b,p.keys.push(y)});if(typeof n.config<"u"){if(Array.isArray(n.config)||typeof n.config==="string")[].concat(n.config).filter(Boolean).forEach(function(y){p.configs[y]=!0});else if(typeof n.config==="object")Object.entries(n.config).forEach(([y,b])=>{if(typeof b==="boolean"||typeof b==="function")p.configs[y]=b})}ct(n.key,r,n.default,p.arrays),Object.keys(c).forEach(function(y){(p.aliases[y]||[]).forEach(function(b){c[b]=c[y]})});let x=null;$o();let C=[],F=Object.assign(Object.create(null),{_:[]}),N={};for(let y=0;y<o.length;y++){let b=o[y],P=b.replace(/^-{3,}/,"---"),S,w,U,v,H,ke;if(b!=="--"&&/^-/.test(b)&&se(b))W(b);else if(P.match(/^---+(=|$)/)){W(b);continue}else if(b.match(/^--.+=/)||!i["short-option-groups"]&&b.match(/^-.+=/)){if(v=b.match(/^--?([^=]+)=([\s\S]*)$/),v!==null&&Array.isArray(v)&&v.length>=3)if(R(v[1],p.arrays))y=L(y,v[1],o,v[2]);else if(R(v[1],p.nargs)!==!1)y=O(y,v[1],o,v[2]);else J(v[1],v[2],!0)}else if(b.match(k)&&i["boolean-negation"]){if(v=b.match(k),v!==null&&Array.isArray(v)&&v.length>=2)w=v[1],J(w,R(w,p.arrays)?[!1]:!1)}else if(b.match(/^--.+/)||!i["short-option-groups"]&&b.match(/^-[^-]+/)){if(v=b.match(/^--?(.+)/),v!==null&&Array.isArray(v)&&v.length>=2)if(w=v[1],R(w,p.arrays))y=L(y,w,o);else if(R(w,p.nargs)!==!1)y=O(y,w,o);else if(H=o[y+1],H!==void 0&&(!H.match(/^-/)||H.match(D))&&!R(w,p.bools)&&!R(w,p.counts))J(w,H),y++;else if(/^(true|false)$/.test(H))J(w,H),y++;else J(w,ee(w))}else if(b.match(/^-.\..+=/)){if(v=b.match(/^-([^=]+)=([\s\S]*)$/),v!==null&&Array.isArray(v)&&v.length>=3)J(v[1],v[2])}else if(b.match(/^-.\..+/)&&!b.match(D)){if(H=o[y+1],v=b.match(/^-(.\..+)/),v!==null&&Array.isArray(v)&&v.length>=2)if(w=v[1],H!==void 0&&!H.match(/^-/)&&!R(w,p.bools)&&!R(w,p.counts))J(w,H),y++;else J(w,ee(w))}else if(b.match(/^-[^-]+/)&&!b.match(D)){U=b.slice(1,-1).split(""),S=!1;for(let Fe=0;Fe<U.length;Fe++){if(H=b.slice(Fe+2),U[Fe+1]&&U[Fe+1]==="="){if(ke=b.slice(Fe+3),w=U[Fe],R(w,p.arrays))y=L(y,w,o,ke);else if(R(w,p.nargs)!==!1)y=O(y,w,o,ke);else J(w,ke);S=!0;break}if(H==="-"){J(U[Fe],H);continue}if(/[A-Za-z]/.test(U[Fe])&&/^-?\d+(\.\d*)?(e-?\d+)?$/.test(H)&&R(H,p.bools)===!1){J(U[Fe],H),S=!0;break}if(U[Fe+1]&&U[Fe+1].match(/\W/)){J(U[Fe],H),S=!0;break}else J(U[Fe],ee(U[Fe]))}if(w=b.slice(-1)[0],!S&&w!=="-")if(R(w,p.arrays))y=L(y,w,o);else if(R(w,p.nargs)!==!1)y=O(y,w,o);else if(H=o[y+1],H!==void 0&&(!/^(-|--)[^-]/.test(H)||H.match(D))&&!R(w,p.bools)&&!R(w,p.counts))J(w,H),y++;else if(/^(true|false)$/.test(H))J(w,H),y++;else J(w,ee(w))}else if(b.match(/^-[0-9]$/)&&b.match(D)&&R(b.slice(1),p.bools))w=b.slice(1),J(w,ee(w));else if(b==="--"){C=o.slice(y+1);break}else if(i["halt-at-non-option"]){C=o.slice(y);break}else W(b)}if(Z(F,!0),Z(F,!1),I(F),B(),je(F,p.aliases,c,!0),Y(F),i["set-placeholder-key"])oe(F);if(Object.keys(p.counts).forEach(function(y){if(!ne(F,y.split(".")))J(y,0)}),u&&C.length)F[d]=[];if(C.forEach(function(y){F[d].push(y)}),i["camel-case-expansion"]&&i["strip-dashed"])Object.keys(F).filter((y)=>y!=="--"&&y.includes("-")).forEach((y)=>{delete F[y]});if(i["strip-aliased"])[].concat(...Object.keys(r).map((y)=>r[y])).forEach((y)=>{if(i["camel-case-expansion"]&&y.includes("-"))delete F[y.split(".").map((b)=>Ot(b)).join(".")];delete F[y]});function W(y){let b=E("_",y);if(typeof b==="string"||typeof b==="number")F._.push(b)}function O(y,b,P,S){let w,U=R(b,p.nargs);if(U=typeof U!=="number"||isNaN(U)?1:U,U===0){if(!we(S))x=Error(m("Argument unexpected for: %s",b));return J(b,ee(b)),y}let v=we(S)?0:1;if(i["nargs-eats-options"]){if(P.length-(y+1)+v<U)x=Error(m("Not enough arguments following: %s",b));v=U}else{for(w=y+1;w<P.length;w++)if(!P[w].match(/^-[^0-9]/)||P[w].match(D)||se(P[w]))v++;else break;if(v<U)x=Error(m("Not enough arguments following: %s",b))}let H=Math.min(v,U);if(!we(S)&&H>0)J(b,S),H--;for(w=y+1;w<H+y+1;w++)J(b,P[w]);return y+H}function L(y,b,P,S){let w=[],U=S||P[y+1],v=R(b,p.nargs);if(R(b,p.bools)&&!/^(true|false)$/.test(U))w.push(!0);else if(we(U)||we(S)&&/^-/.test(U)&&!D.test(U)&&!se(U)){if(c[b]!==void 0){let H=c[b];w=Array.isArray(H)?H:[H]}}else{if(!we(S))w.push(_(b,S,!0));for(let H=y+1;H<P.length;H++){if(!i["greedy-arrays"]&&w.length>0||v&&typeof v==="number"&&w.length>=v)break;if(U=P[H],/^-/.test(U)&&!D.test(U)&&!se(U))break;y=H,w.push(_(b,U,s))}}if(typeof v==="number"&&(v&&w.length<v||isNaN(v)&&w.length===0))x=Error(m("Not enough arguments following: %s",b));return J(b,w),y}function J(y,b,P=s){if(/-/.test(y)&&i["camel-case-expansion"]){let U=y.split(".").map(function(v){return Ot(v)}).join(".");Q(y,U)}let S=_(y,b,P),w=y.split(".");if(We(F,w,S),p.aliases[y])p.aliases[y].forEach(function(U){let v=U.split(".");We(F,v,S)});if(w.length>1&&i["dot-notation"])(p.aliases[w[0]]||[]).forEach(function(U){let v=U.split("."),H=[].concat(w);if(H.shift(),v=v.concat(H),!(p.aliases[y]||[]).includes(v.join(".")))We(F,v,S)});if(R(y,p.normalize)&&!R(y,p.arrays))[y].concat(p.aliases[y]||[]).forEach(function(v){Object.defineProperty(N,v,{enumerable:!0,get(){return b},set(H){b=typeof H==="string"?lt.normalize(H):H}})})}function Q(y,b){if(!(p.aliases[y]&&p.aliases[y].length))p.aliases[y]=[b],f[b]=!0;if(!(p.aliases[b]&&p.aliases[b].length))Q(b,y)}function _(y,b,P){if(P)b=xf(b);if(R(y,p.bools)||R(y,p.counts)){if(typeof b==="string")b=b==="true"}let S=Array.isArray(b)?b.map(function(w){return E(y,w)}):E(y,b);if(R(y,p.counts)&&(we(S)||typeof S==="boolean"))S=Bo();if(R(y,p.normalize)&&R(y,p.arrays))if(Array.isArray(b))S=b.map((w)=>lt.normalize(w));else S=lt.normalize(b);return S}function E(y,b){if(!i["parse-positional-numbers"]&&y==="_")return b;if(!R(y,p.strings)&&!R(y,p.bools)&&!Array.isArray(b)){if(ms(b)&&i["parse-numbers"]&&Number.isSafeInteger(Math.floor(parseFloat(`${b}`)))||!we(b)&&R(y,p.numbers))b=Number(b)}return b}function I(y){let b=Object.create(null);je(b,p.aliases,c),Object.keys(p.configs).forEach(function(P){let S=y[P]||b[P];if(S)try{let w=null,U=lt.resolve(lt.cwd(),S),v=p.configs[P];if(typeof v==="function"){try{w=v(U)}catch(H){w=H}if(w instanceof Error){x=w;return}}else w=lt.require(U);A(w)}catch(w){if(w.name==="PermissionDenied")x=w;else if(y[P])x=Error(m("Invalid JSON config file: %s",S))}})}function A(y,b){Object.keys(y).forEach(function(P){let S=y[P],w=b?b+"."+P:P;if(typeof S==="object"&&S!==null&&!Array.isArray(S)&&i["dot-notation"])A(S,w);else if(!ne(F,w.split("."))||R(w,p.arrays)&&i["combine-arrays"])J(w,S)})}function B(){if(typeof a<"u")a.forEach(function(y){A(y)})}function Z(y,b){if(typeof l>"u")return;let P=typeof l==="string"?l:"",S=lt.env();Object.keys(S).forEach(function(w){if(P===""||w.lastIndexOf(P,0)===0){let U=w.split("__").map(function(v,H){if(H===0)v=v.substring(P.length);return Ot(v)});if((b&&p.configs[U.join(".")]||!b)&&!ne(y,U))J(U.join("."),S[w])}})}function Y(y){let b,P=new Set;Object.keys(y).forEach(function(S){if(!P.has(S)){if(b=R(S,p.coercions),typeof b==="function")try{let w=E(S,b(y[S]));[].concat(p.aliases[S]||[],S).forEach((U)=>{P.add(U),y[U]=w})}catch(w){x=w}}})}function oe(y){return p.keys.forEach((b)=>{if(~b.indexOf("."))return;if(typeof y[b]>"u")y[b]=void 0}),y}function je(y,b,P,S=!1){Object.keys(P).forEach(function(w){if(!ne(y,w.split("."))){if(We(y,w.split("."),P[w]),S)h[w]=!0;(b[w]||[]).forEach(function(U){if(ne(y,U.split(".")))return;We(y,U.split("."),P[w])})}})}function ne(y,b){let P=y;if(!i["dot-notation"])b=[b.join(".")];b.slice(0,-1).forEach(function(w){P=P[w]||{}});let S=b[b.length-1];if(typeof P!=="object")return!1;else return S in P}function We(y,b,P){let S=y;if(!i["dot-notation"])b=[b.join(".")];b.slice(0,-1).forEach(function(ke){if(ke=ya(ke),typeof S==="object"&&S[ke]===void 0)S[ke]={};if(typeof S[ke]!=="object"||Array.isArray(S[ke])){if(Array.isArray(S[ke]))S[ke].push({});else S[ke]=[S[ke],{}];S=S[ke][S[ke].length-1]}else S=S[ke]});let w=ya(b[b.length-1]),U=R(b.join("."),p.arrays),v=Array.isArray(P),H=i["duplicate-arguments-array"];if(!H&&R(w,p.nargs)){if(H=!0,!we(S[w])&&p.nargs[w]===1||Array.isArray(S[w])&&S[w].length===p.nargs[w])S[w]=void 0}if(P===Bo())S[w]=Bo(S[w]);else if(Array.isArray(S[w]))if(H&&U&&v)S[w]=i["flatten-duplicate-arrays"]?S[w].concat(P):(Array.isArray(S[w][0])?S[w]:[S[w]]).concat([P]);else if(!H&&Boolean(U)===Boolean(v))S[w]=P;else S[w]=S[w].concat([P]);else if(S[w]===void 0&&U)S[w]=v?P:[P];else if(H&&!(S[w]===void 0||R(w,p.counts)||R(w,p.bools)))S[w]=[S[w],P];else S[w]=P}function ct(...y){y.forEach(function(b){Object.keys(b||{}).forEach(function(P){if(p.aliases[P])return;p.aliases[P]=[].concat(r[P]||[]),p.aliases[P].concat(P).forEach(function(S){if(/-/.test(S)&&i["camel-case-expansion"]){let w=Ot(S);if(w!==P&&p.aliases[P].indexOf(w)===-1)p.aliases[P].push(w),f[w]=!0}}),p.aliases[P].concat(P).forEach(function(S){if(S.length>1&&/[A-Z]/.test(S)&&i["camel-case-expansion"]){let w=gs(S,"-");if(w!==P&&p.aliases[P].indexOf(w)===-1)p.aliases[P].push(w),f[w]=!0}}),p.aliases[P].forEach(function(S){p.aliases[S]=[P].concat(p.aliases[P].filter(function(w){return S!==w}))})})})}function R(y,b){let P=[].concat(p.aliases[y]||[],y),S=Object.keys(b),w=P.find((U)=>S.includes(U));return w?b[w]:!1}function de(y){let b=Object.keys(p);return[].concat(b.map((S)=>p[S])).some(function(S){return Array.isArray(S)?S.includes(y):S[y]})}function Ue(y,...b){return[].concat(...b).some(function(S){let w=y.match(S);return w&&de(w[1])})}function z(y){if(y.match(D)||!y.match(/^-[^-]+/))return!1;let b=!0,P,S=y.slice(1).split("");for(let w=0;w<S.length;w++){if(P=y.slice(w+2),!de(S[w])){b=!1;break}if(S[w+1]&&S[w+1]==="="||P==="-"||/[A-Za-z]/.test(S[w])&&/^-?\d+(\.\d*)?(e-?\d+)?$/.test(P)||S[w+1]&&S[w+1].match(/\W/))break}return b}function se(y){return i["unknown-options-as-args"]&&ye(y)}function ye(y){if(y=y.replace(/^-{3,}/,"--"),y.match(D))return!1;if(z(y))return!1;return!Ue(y,/^-+([^=]+?)=[\s\S]*$/,k,/^-+([^=]+?)$/,/^-+([^=]+?)-$/,/^-+([^=]+?\d+)$/,/^-+([^=]+?)\W+.*$/)}function ee(y){if(!R(y,p.bools)&&!R(y,p.counts)&&`${y}`in c)return c[y];else return Ee(fe(y))}function Ee(y){return{[Je.BOOLEAN]:!0,[Je.STRING]:"",[Je.NUMBER]:void 0,[Je.ARRAY]:[]}[y]}function fe(y){let b=Je.BOOLEAN;if(R(y,p.strings))b=Je.STRING;else if(R(y,p.numbers))b=Je.NUMBER;else if(R(y,p.bools))b=Je.BOOLEAN;else if(R(y,p.arrays))b=Je.ARRAY;return b}function we(y){return y===void 0}function $o(){Object.keys(p.counts).find((y)=>{if(R(y,p.arrays))return x=Error(m("Invalid configuration: %s, opts.count excludes opts.array.",y)),!0;else if(R(y,p.nargs))return x=Error(m("Invalid configuration: %s, opts.count excludes opts.narg.",y)),!0;return!1})}return{aliases:Object.assign({},p.aliases),argv:Object.assign(N,F),configuration:i,defaulted:Object.assign({},h),error:x,newAliases:Object.assign({},f)}}}function kf(e){let t=[],n=Object.create(null),o=!0;Object.keys(e).forEach(function(s){t.push([].concat(e[s],s))});while(o){o=!1;for(let s=0;s<t.length;s++)for(let r=s+1;r<t.length;r++)if(t[s].filter(function(c){return t[r].indexOf(c)!==-1}).length){t[s]=t[s].concat(t[r]),t.splice(r,1),o=!0;break}}return t.forEach(function(s){s=s.filter(function(i,c,a){return a.indexOf(i)===c});let r=s.pop();if(r!==void 0&&typeof r==="string")n[r]=s}),n}function Bo(e){return e!==void 0?e+1:1}function ya(e){if(e==="__proto__")return"___proto___";return e}function xf(e){return typeof e==="string"&&(e[0]==="'"||e[0]==='"')&&e[e.length-1]===e[0]?e.substring(1,e.length-1):e}import{readFileSync as _f}from"fs";import{createRequire as wa}from"node:module";var Lo,Mo,jo,ba=process&&process.env&&process.env.YARGS_MIN_NODE_VERSION?Number(process.env.YARGS_MIN_NODE_VERSION):20,ka=(Mo=(Lo=process===null||process===void 0?void 0:process.versions)===null||Lo===void 0?void 0:Lo.node)!==null&&Mo!==void 0?Mo:(jo=process===null||process===void 0?void 0:process.version)===null||jo===void 0?void 0:jo.slice(1);if(ka){if(Number(ka.match(/^([^.]+)/)[1])<ba)throw Error(`yargs parser supports a minimum Node.js version of ${ba}. Read our version support policy: https://github.com/yargs/yargs-parser#supported-nodejs-versions`)}var Ff=process?process.env:{},xa=wa?wa(import.meta.url):void 0,Ea=new vo({cwd:process.cwd,env:()=>Ff,format:Ef,normalize:Cf,resolve:Sf,require:(e)=>{if(typeof xa<"u")return xa(e);else if(e.match(/\.json$/))return JSON.parse(_f(e,"utf8"));else throw Error("only .json config files are supported in ESM")}}),_n=function(t,n){return Ea.parse(t.slice(),n).argv};_n.detailed=function(e,t){return Ea.parse(e.slice(),t)};_n.camelCase=Ot;_n.decamelize=gs;_n.looksLikeNumber=ms;var Wo=_n;import{basename as Mf,dirname as jf,extname as Wf,relative as Uf,resolve as Oa,join as Jf}from"path";function Ca(){if($f())return 0;return 1}function $f(){return Af()&&!process.defaultApp}function Af(){return!!process.versions.electron}function Uo(e){return e.slice(Ca()+1)}function Sa(){return process.argv[Ca()]}import{readFileSync as Tf,statSync as If,writeFile as Of}from"fs";import{format as Pf}from"util";import{resolve as Rf}from"path";var _a={fs:{readFileSync:Tf,writeFile:Of},format:Pf,resolve:Rf,exists:(e)=>{try{return If(e).isFile()}catch(t){return!1}}};var Qe;class Fa{constructor(e){e=e||{},this.directory=e.directory||"./locales",this.updateFiles=typeof e.updateFiles==="boolean"?e.updateFiles:!0,this.locale=e.locale||"en",this.fallbackToLanguage=typeof e.fallbackToLanguage==="boolean"?e.fallbackToLanguage:!0,this.cache=Object.create(null),this.writeQueue=[]}__(...e){if(typeof arguments[0]!=="string")return this._taggedLiteral(arguments[0],...arguments);let t=e.shift(),n=function(){};if(typeof e[e.length-1]==="function")n=e.pop();if(n=n||function(){},!this.cache[this.locale])this._readLocaleFile();if(!this.cache[this.locale][t]&&this.updateFiles)this.cache[this.locale][t]=t,this._enqueueWrite({directory:this.directory,locale:this.locale,cb:n});else n();return Qe.format.apply(Qe.format,[this.cache[this.locale][t]||t].concat(e))}__n(){let e=Array.prototype.slice.call(arguments),t=e.shift(),n=e.shift(),o=e.shift(),s=function(){};if(typeof e[e.length-1]==="function")s=e.pop();if(!this.cache[this.locale])this._readLocaleFile();let r=o===1?t:n;if(this.cache[this.locale][t])r=this.cache[this.locale][t][o===1?"one":"other"];if(!this.cache[this.locale][t]&&this.updateFiles)this.cache[this.locale][t]={one:t,other:n},this._enqueueWrite({directory:this.directory,locale:this.locale,cb:s});else s();let i=[r];if(~r.indexOf("%d"))i.push(o);return Qe.format.apply(Qe.format,i.concat(e))}setLocale(e){this.locale=e}getLocale(){return this.locale}updateLocale(e){if(!this.cache[this.locale])this._readLocaleFile();for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t))this.cache[this.locale][t]=e[t]}_taggedLiteral(e,...t){let n="";return e.forEach(function(o,s){let r=t[s+1];if(n+=o,typeof r<"u")n+="%s"}),this.__.apply(this,[n].concat([].slice.call(t,1)))}_enqueueWrite(e){if(this.writeQueue.push(e),this.writeQueue.length===1)this._processWriteQueue()}_processWriteQueue(){let e=this,t=this.writeQueue[0],{directory:n,locale:o,cb:s}=t,r=this._resolveLocaleFile(n,o),i=JSON.stringify(this.cache[o],null,2);Qe.fs.writeFile(r,i,"utf-8",function(c){if(e.writeQueue.shift(),e.writeQueue.length>0)e._processWriteQueue();s(c)})}_readLocaleFile(){let e={},t=this._resolveLocaleFile(this.directory,this.locale);try{if(Qe.fs.readFileSync)e=JSON.parse(Qe.fs.readFileSync(t,"utf-8"))}catch(n){if(n instanceof SyntaxError)n.message="syntax error in "+t;if(n.code==="ENOENT")e={};else throw n}this.cache[this.locale]=e}_resolveLocaleFile(e,t){let n=Qe.resolve(e,"./",t+".json");if(this.fallbackToLanguage&&!this._fileExistsSync(n)&&~t.lastIndexOf("_")){let o=Qe.resolve(e,"./",t.split("_")[0]+".json");if(this._fileExistsSync(o))n=o}return n}_fileExistsSync(e){return Qe.exists(e)}}function $a(e,t){Qe=t;let n=new Fa(e);return{__:n.__.bind(n),__n:n.__n.bind(n),setLocale:n.setLocale.bind(n),getLocale:n.getLocale.bind(n),updateLocale:n.updateLocale.bind(n),locale:n.locale}}var Nf=(e)=>$a(e,_a),Aa=Nf;var Ra=ji(Ia(),1);import{createRequire as Kf}from"node:module";import{readFileSync as Hf,readdirSync as zf}from"node:fs";var Jo=Pa(import.meta.url),qf=Jo.substring(0,Jo.lastIndexOf("node_modules")),Gf=Kf(import.meta.url),Ko={assert:{notStrictEqual:Bf,strictEqual:vf},cliui:Ro,findUp:No,getEnv:(e)=>process.env[e],inspect:Lf,getProcessArgvBin:Sa,mainFilename:qf||process.cwd(),Parser:Wo,path:{basename:Mf,dirname:jf,extname:Wf,relative:Uf,resolve:Oa,join:Jf},process:{argv:()=>process.argv,cwd:process.cwd,emitWarning:(e,t)=>process.emitWarning(e,t),execPath:()=>process.execPath,exit:(e)=>{process.exit(e)},nextTick:process.nextTick,stdColumns:typeof process.stdout.columns<"u"?process.stdout.columns:null},readFileSync:Hf,readdirSync:zf,require:Gf,getCallerFile:()=>{let e=Ra.default(3);return e.match(/^file:\/\//)?Pa(e):e},stringWidth:Ze,y18n:Aa({directory:Oa(Jo,"../../../locales"),updateFiles:!1})};function $e(e,t,n,o){n.assert.notStrictEqual(e,t,o)}function Ho(e,t){t.assert.strictEqual(typeof e,"string")}function on(e){return Object.keys(e)}function re(e){return!!e&&!!e.then&&typeof e.then==="function"}class pe extends Error{constructor(e){super(e||"yargs error");if(this.name="YError",Error.captureStackTrace)Error.captureStackTrace(this,pe)}}function mt(e){let n=e.replace(/\s{2,}/g," ").split(/\s+(?![^[]*]|[^<]*>)/),o=/\.*[\][<>]/g,s=n.shift();if(!s)throw Error(`No command found in: ${e}`);let r={cmd:s.replace(o,""),demanded:[],optional:[]};return n.forEach((i,c)=>{let a=!1;if(i=i.replace(/\s/g,""),/\.+[\]>]/.test(i)&&c===n.length-1)a=!0;if(/^\[/.test(i))r.optional.push({cmd:i.replace(o,"").split("|"),variadic:a});else r.demanded.push({cmd:i.replace(o,"").split("|"),variadic:a})}),r}var Xf=["first","second","third","fourth","fifth","sixth"];function M(e,t,n){function o(){return typeof e==="object"?[{demanded:[],optional:[]},e,t]:[mt(`cmd ${e}`),t,n]}try{let s=0,[r,i,c]=o(),a=[].slice.call(i);while(a.length&&a[a.length-1]===void 0)a.pop();let l=c||a.length;if(l<r.demanded.length)throw new pe(`Not enough arguments provided. Expected ${r.demanded.length} but received ${a.length}.`);let u=r.demanded.length+r.optional.length;if(l>u)throw new pe(`Too many arguments provided. Expected max ${u} but received ${l}.`);r.demanded.forEach((d)=>{let f=a.shift(),h=Na(f);if(d.cmd.filter((p)=>p===h||p==="*").length===0)Ba(h,d.cmd,s);s+=1}),r.optional.forEach((d)=>{if(a.length===0)return;let f=a.shift(),h=Na(f);if(d.cmd.filter((p)=>p===h||p==="*").length===0)Ba(h,d.cmd,s);s+=1})}catch(s){console.warn(s.stack)}}function Na(e){if(Array.isArray(e))return"array";else if(e===null)return"null";return typeof e}function Ba(e,t,n){throw new pe(`Invalid ${Xf[n]||"manyith"} argument. Expected ${t.join(" or ")} but received ${e}.`)}class zo{constructor(e){this.globalMiddleware=[],this.frozens=[],this.yargs=e}addMiddleware(e,t,n=!0,o=!1){if(M("<array|function> [boolean] [boolean] [boolean]",[e,t,n],arguments.length),Array.isArray(e)){for(let s=0;s<e.length;s++){if(typeof e[s]!=="function")throw Error("middleware must be a function");let r=e[s];r.applyBeforeValidation=t,r.global=n}Array.prototype.push.apply(this.globalMiddleware,e)}else if(typeof e==="function"){let s=e;s.applyBeforeValidation=t,s.global=n,s.mutates=o,this.globalMiddleware.push(e)}return this.yargs}addCoerceMiddleware(e,t){let n=this.yargs.getAliases();return this.globalMiddleware=this.globalMiddleware.filter((o)=>{let s=[...n[t]||[],t];if(!o.option)return!0;else return!s.includes(o.option)}),e.option=t,this.addMiddleware(e,!0,!0,!0)}getMiddleware(){return this.globalMiddleware}freeze(){this.frozens.push([...this.globalMiddleware])}unfreeze(){let e=this.frozens.pop();if(e!==void 0)this.globalMiddleware=e}reset(){this.globalMiddleware=this.globalMiddleware.filter((e)=>e.global)}}function va(e){if(!e)return[];return e.map((t)=>(t.applyBeforeValidation=!1,t))}function Pt(e,t,n,o){return n.reduce((s,r)=>{if(r.applyBeforeValidation!==o)return s;if(r.mutates){if(r.applied)return s;r.applied=!0}if(re(s))return s.then((i)=>Promise.all([i,r(i,t)])).then(([i,c])=>Object.assign(i,c));else{let i=r(s,t);return re(i)?i.then((c)=>Object.assign(s,c)):Object.assign(s,i)}},e)}function Rt(e,t,n=(o)=>{throw o}){try{let o=Yf(e)?e():e;return re(o)?o.then((s)=>t(s)):t(o)}catch(o){return n(o)}}function Yf(e){return typeof e==="function"}var rn=/(^\*)|(^\$0)/;class Ma{constructor(e,t,n,o){this.requireCache=new Set,this.handlers={},this.aliasMap={},this.frozens=[],this.shim=o,this.usage=e,this.globalMiddleware=n,this.validation=t}addDirectory(e,t,n,o){o=o||{},this.requireCache.add(n);let s=this.shim.path.resolve(this.shim.path.dirname(n),e),r=this.shim.readdirSync(s,{recursive:o.recurse?!0:!1});if(!Array.isArray(o.extensions))o.extensions=["js"];let i=typeof o.visit==="function"?o.visit:(c)=>c;for(let c of r){let a=c.toString();if(o.exclude){let u=!1;if(typeof o.exclude==="function")u=o.exclude(a);else u=o.exclude.test(a);if(u)continue}if(o.include){let u=!1;if(typeof o.include==="function")u=o.include(a);else u=o.include.test(a);if(!u)continue}let l=!1;for(let u of o.extensions)if(a.endsWith(u))l=!0;if(l){let u=this.shim.path.join(s,a),d=t(u),f=Object.create(null,Object.getOwnPropertyDescriptors({...d}));if(i(f,u,a)){if(this.requireCache.has(u))continue;else this.requireCache.add(u);if(!f.command)f.command=this.shim.path.basename(u,this.shim.path.extname(u));this.addHandler(f)}}}}addHandler(e,t,n,o,s,r){let i=[],c=va(s);if(o=o||(()=>{}),Array.isArray(e))if(Vf(e))[e,...i]=e;else for(let a of e)this.addHandler(a);else if(Qf(e)){let a=Array.isArray(e.command)||typeof e.command==="string"?e.command:null;if(a===null)throw Error(`No command name given for module: ${this.shim.inspect(e)}`);if(e.aliases)a=[].concat(a).concat(e.aliases);this.addHandler(a,this.extractDesc(e),e.builder,e.handler,e.middlewares,e.deprecated);return}else if(La(n)){this.addHandler([e].concat(i),t,n.builder,n.handler,n.middlewares,n.deprecated);return}if(typeof e==="string"){let a=mt(e);i=i.map((d)=>mt(d).cmd);let l=!1,u=[a.cmd].concat(i).filter((d)=>{if(rn.test(d))return l=!0,!1;return!0});if(u.length===0&&l)u.push("$0");if(l)a.cmd=u[0],i=u.slice(1),e=e.replace(rn,a.cmd);if(i.forEach((d)=>{this.aliasMap[d]=a.cmd}),t!==!1)this.usage.command(e,t,l,i,r);if(this.handlers[a.cmd]={original:e,description:t,handler:o,builder:n||{},middlewares:c,deprecated:r,demanded:a.demanded,optional:a.optional},l)this.defaultCommand=this.handlers[a.cmd]}}getCommandHandlers(){return this.handlers}getCommands(){return Object.keys(this.handlers).concat(Object.keys(this.aliasMap))}hasDefaultCommand(){return!!this.defaultCommand}runCommand(e,t,n,o,s,r){let i=this.handlers[e]||this.handlers[this.aliasMap[e]]||this.defaultCommand,c=t.getInternalMethods().getContext(),a=c.commands.slice(),l=!e;if(e)c.commands.push(e),c.fullCommands.push(i.original);let u=this.applyBuilderUpdateUsageAndParse(l,i,t,n.aliases,a,o,s,r);return re(u)?u.then((d)=>this.applyMiddlewareAndGetResult(l,i,d.innerArgv,c,s,d.aliases,t)):this.applyMiddlewareAndGetResult(l,i,u.innerArgv,c,s,u.aliases,t)}applyBuilderUpdateUsageAndParse(e,t,n,o,s,r,i,c){let a=t.builder,l=n;if(Ds(a)){n.getInternalMethods().getUsageInstance().freeze();let u=a(n.getInternalMethods().reset(o),c);if(re(u))return u.then((d)=>(l=Wa(d)?d:n,this.parseAndUpdateUsage(e,t,l,s,r,i)))}else if(Zf(a))n.getInternalMethods().getUsageInstance().freeze(),l=n.getInternalMethods().reset(o),Object.keys(t.builder).forEach((u)=>{l.option(u,a[u])});return this.parseAndUpdateUsage(e,t,l,s,r,i)}parseAndUpdateUsage(e,t,n,o,s,r){if(e)n.getInternalMethods().getUsageInstance().unfreeze(!0);if(this.shouldUpdateUsage(n))n.getInternalMethods().getUsageInstance().usage(this.usageFromParentCommandsCommandHandler(o,t),t.description);let i=n.getInternalMethods().runYargsParserAndExecuteCommands(null,void 0,!0,s,r);return re(i)?i.then((c)=>({aliases:n.parsed.aliases,innerArgv:c})):{aliases:n.parsed.aliases,innerArgv:i}}shouldUpdateUsage(e){return!e.getInternalMethods().getUsageInstance().getUsageDisabled()&&e.getInternalMethods().getUsageInstance().getUsage().length===0}usageFromParentCommandsCommandHandler(e,t){let n=rn.test(t.original)?t.original.replace(rn,"").trim():t.original,o=e.filter((s)=>!rn.test(s));return o.push(n),`$0 ${o.join(" ")}`}handleValidationAndGetResult(e,t,n,o,s,r,i,c){if(!r.getInternalMethods().getHasOutput()){let a=r.getInternalMethods().runValidation(s,c,r.parsed.error,e);n=Rt(n,(l)=>(a(l),l))}if(t.handler&&!r.getInternalMethods().getHasOutput()){r.getInternalMethods().setHasOutput();let a=!!r.getOptions().configuration["populate--"];if(r.getInternalMethods().postProcess(n,a,!1,!1),n=Pt(n,r,i,!1),n=Rt(n,(l)=>{let u=t.handler(l);return re(u)?u.then(()=>l):l}),!e)r.getInternalMethods().getUsageInstance().cacheHelpMessage();if(re(n)&&!r.getInternalMethods().hasParseCallback())n.catch((l)=>{try{r.getInternalMethods().getUsageInstance().fail(null,l)}catch(u){}})}if(!e)o.commands.pop(),o.fullCommands.pop();return n}applyMiddlewareAndGetResult(e,t,n,o,s,r,i){let c={};if(s)return n;if(!i.getInternalMethods().getHasOutput())c=this.populatePositionals(t,n,o,i);let a=this.globalMiddleware.getMiddleware().slice(0).concat(t.middlewares),l=Pt(n,i,a,!0);return re(l)?l.then((u)=>this.handleValidationAndGetResult(e,t,u,o,r,i,a,c)):this.handleValidationAndGetResult(e,t,l,o,r,i,a,c)}populatePositionals(e,t,n,o){t._=t._.slice(n.commands.length);let s=e.demanded.slice(0),r=e.optional.slice(0),i={};this.validation.positionalCount(s.length,t._.length);while(s.length){let c=s.shift();this.populatePositional(c,t,i)}while(r.length){let c=r.shift();this.populatePositional(c,t,i)}return t._=n.commands.concat(t._.map((c)=>""+c)),this.postProcessPositionals(t,i,this.cmdToParseOptions(e.original),o),i}populatePositional(e,t,n){let o=e.cmd[0];if(e.variadic)n[o]=t._.splice(0).map(String);else if(t._.length)n[o]=[String(t._.shift())]}cmdToParseOptions(e){let t={array:[],default:{},alias:{},demand:{}},n=mt(e);return n.demanded.forEach((o)=>{let[s,...r]=o.cmd;if(o.variadic)t.array.push(s),t.default[s]=[];t.alias[s]=r,t.demand[s]=!0}),n.optional.forEach((o)=>{let[s,...r]=o.cmd;if(o.variadic)t.array.push(s),t.default[s]=[];t.alias[s]=r}),t}postProcessPositionals(e,t,n,o){let s=Object.assign({},o.getOptions());s.default=Object.assign(n.default,s.default);for(let a of Object.keys(n.alias))s.alias[a]=(s.alias[a]||[]).concat(n.alias[a]);s.array=s.array.concat(n.array),s.config={};let r=[];if(Object.keys(t).forEach((a)=>{t[a].map((l)=>{if(s.configuration["unknown-options-as-args"])s.key[a]=!0;r.push(`--${a}`),r.push(l)})}),!r.length)return;let i=Object.assign({},s.configuration,{"populate--":!1}),c=this.shim.Parser.detailed(r,Object.assign({},s,{configuration:i}));if(c.error)o.getInternalMethods().getUsageInstance().fail(c.error.message,c.error);else{let a=Object.keys(t);Object.keys(t).forEach((l)=>{a.push(...c.aliases[l])}),Object.keys(c.argv).forEach((l)=>{if(a.includes(l)){if(!t[l])t[l]=c.argv[l];if(!this.isInConfigs(o,l)&&!this.isDefaulted(o,l)&&Object.prototype.hasOwnProperty.call(e,l)&&Object.prototype.hasOwnProperty.call(c.argv,l)&&(Array.isArray(e[l])||Array.isArray(c.argv[l])))e[l]=[].concat(e[l],c.argv[l]);else e[l]=c.argv[l]}})}}isDefaulted(e,t){let{default:n}=e.getOptions();return Object.prototype.hasOwnProperty.call(n,t)||Object.prototype.hasOwnProperty.call(n,this.shim.Parser.camelCase(t))}isInConfigs(e,t){let{configObjects:n}=e.getOptions();return n.some((o)=>Object.prototype.hasOwnProperty.call(o,t))||n.some((o)=>Object.prototype.hasOwnProperty.call(o,this.shim.Parser.camelCase(t)))}runDefaultBuilderOn(e){if(!this.defaultCommand)return;if(this.shouldUpdateUsage(e)){let n=rn.test(this.defaultCommand.original)?this.defaultCommand.original:this.defaultCommand.original.replace(/^[^[\]<>]*/,"$0 ");e.getInternalMethods().getUsageInstance().usage(n,this.defaultCommand.description)}let t=this.defaultCommand.builder;if(Ds(t))return t(e,!0);else if(!La(t))Object.keys(t).forEach((n)=>{e.option(n,t[n])});return}extractDesc({describe:e,description:t,desc:n}){for(let o of[e,t,n]){if(typeof o==="string"||o===!1)return o;$e(o,!0,this.shim)}return!1}freeze(){this.frozens.push({handlers:this.handlers,aliasMap:this.aliasMap,defaultCommand:this.defaultCommand})}unfreeze(){let e=this.frozens.pop();$e(e,void 0,this.shim),{handlers:this.handlers,aliasMap:this.aliasMap,defaultCommand:this.defaultCommand}=e}reset(){return this.handlers={},this.aliasMap={},this.defaultCommand=void 0,this.requireCache=new Set,this}}function ja(e,t,n,o){return new Ma(e,t,n,o)}function La(e){return typeof e==="object"&&!!e.builder&&typeof e.handler==="function"}function Vf(e){return e.every((t)=>typeof t==="string")}function Ds(e){return typeof e==="function"}function Zf(e){return typeof e==="object"}function Qf(e){return typeof e==="object"&&!Array.isArray(e)}function Dt(e={},t=()=>!0){let n={};return on(e).forEach((o)=>{if(t(o,e[o]))n[o]=e[o]}),n}function yt(e){if(typeof process>"u")return;[process.stdout,process.stderr].forEach((t)=>{let n=t;if(n._handle&&n.isTTY&&typeof n._handle.setBlocking==="function")n._handle.setBlocking(e)})}function ep(e){return typeof e==="boolean"}function Ja(e,t){let n=t.y18n.__,o={},s=[];o.failFn=function(E){s.push(E)};let r=null,i=null,c=!0;o.showHelpOnFail=function(E=!0,I){let[A,B]=typeof E==="string"?[!0,E]:[E,I];if(e.getInternalMethods().isGlobalContext())i=B;return r=B,c=A,o};let a=!1;o.fail=function(E,I){let A=e.getInternalMethods().getLoggerInstance();if(s.length)for(let B=s.length-1;B>=0;--B){let Z=s[B];if(ep(Z)){if(I)throw I;else if(E)throw Error(E)}else Z(E,I,o)}else{if(e.getExitProcess())yt(!0);if(!a){if(a=!0,c)e.showHelp("error"),A.error();if(E||I)A.error(E||I);let B=r||i;if(B){if(E||I)A.error("");A.error(B)}}if(I=I||new pe(E),e.getExitProcess())return e.exit(1);else if(e.getInternalMethods().hasParseCallback())return e.exit(1,I);else throw I}};let l=[],u=!1;o.usage=(_,E)=>{if(_===null)return u=!0,l=[],o;return u=!1,l.push([_,E||""]),o},o.getUsage=()=>l,o.getUsageDisabled=()=>u,o.getPositionalGroupName=()=>n("Positionals:");let d=[];o.example=(_,E)=>{d.push([_,E||""])};let f=[];o.command=function(E,I,A,B,Z=!1){if(A)f=f.map((Y)=>(Y[2]=!1,Y));f.push([E,I||"",A,B,Z])},o.getCommands=()=>f;let h={};o.describe=function(E,I){if(Array.isArray(E))E.forEach((A)=>{o.describe(A,I)});else if(typeof E==="object")Object.keys(E).forEach((A)=>{o.describe(A,E[A])});else h[E]=I},o.getDescriptions=()=>h;let m=[];o.epilog=(_)=>{m.push(_)};let p=!1,D;o.wrap=(_)=>{p=!0,D=_},o.getWrap=()=>{if(t.getEnv("YARGS_DISABLE_WRAP"))return null;if(!p)D=L(),p=!0;return D};let k="__yargsString__:";o.deferY18nLookup=(_)=>k+_,o.help=function(){if(F)return F;C();let E=e.customScriptName?e.$0:t.path.basename(e.$0),I=e.getDemandedOptions(),A=e.getDemandedCommands(),B=e.getDeprecatedOptions(),Z=e.getGroups(),Y=e.getOptions(),oe=[];oe=oe.concat(Object.keys(h)),oe=oe.concat(Object.keys(I)),oe=oe.concat(Object.keys(A)),oe=oe.concat(Object.keys(Y.default)),oe=oe.filter(W),oe=Object.keys(oe.reduce((z,se)=>{if(se!=="_")z[se]=!0;return z},{}));let je=o.getWrap(),ne=t.cliui({width:je,wrap:!!je});if(!u){if(l.length)l.forEach((z)=>{if(ne.div({text:`${z[0].replace(/\$0/g,E)}`}),z[1])ne.div({text:`${z[1]}`,padding:[1,0,0,0]})}),ne.div();else if(f.length){let z=null;if(A._)z=`${E} <${n("command")}>
15
+ `;else z=`${E} [${n("command")}]
16
+ `;ne.div(`${z}`)}}if(f.length>1||f.length===1&&!f[0][2]){ne.div(n("Commands:"));let z=e.getInternalMethods().getContext(),se=z.commands.length?`${z.commands.join(" ")} `:"";if(e.getInternalMethods().getParserConfiguration()["sort-commands"]===!0)f=f.sort((ee,Ee)=>ee[0].localeCompare(Ee[0]));let ye=E?`${E} `:"";f.forEach((ee)=>{let Ee=`${ye}${se}${ee[0].replace(/^\$0 ?/,"")}`;ne.span({text:Ee,padding:[0,2,0,2],width:x(f,je,`${E}${se}`)+4},{text:ee[1]});let fe=[];if(ee[2])fe.push(`[${n("default")}]`);if(ee[3]&&ee[3].length)fe.push(`[${n("aliases:")} ${ee[3].join(", ")}]`);if(ee[4])if(typeof ee[4]==="string")fe.push(`[${n("deprecated: %s",ee[4])}]`);else fe.push(`[${n("deprecated")}]`);if(fe.length)ne.div({text:fe.join(" "),padding:[0,0,0,2],align:"right"});else ne.div()}),ne.div()}let We=(Object.keys(Y.alias)||[]).concat(Object.keys(e.parsed.newAliases)||[]);oe=oe.filter((z)=>!e.parsed.newAliases[z]&&We.every((se)=>(Y.alias[se]||[]).indexOf(z)===-1));let ct=n("Options:");if(!Z[ct])Z[ct]=[];N(oe,Y.alias,Z,ct);let R=(z)=>/^--/.test(ys(z)),de=Object.keys(Z).filter((z)=>Z[z].length>0).map((z)=>{let se=Z[z].filter(W).map((ye)=>{if(We.includes(ye))return ye;for(let ee=0,Ee;(Ee=We[ee])!==void 0;ee++)if((Y.alias[Ee]||[]).includes(ye))return Ee;return ye});return{groupName:z,normalizedKeys:se}}).filter(({normalizedKeys:z})=>z.length>0).map(({groupName:z,normalizedKeys:se})=>{let ye=se.reduce((ee,Ee)=>(ee[Ee]=[Ee].concat(Y.alias[Ee]||[]).map((fe)=>{if(z===o.getPositionalGroupName())return fe;else return(/^[0-9]$/.test(fe)?Y.boolean.includes(Ee)?"-":"--":fe.length>1?"--":"-")+fe}).sort((fe,we)=>R(fe)===R(we)?0:R(fe)?1:-1).join(", "),ee),{});return{groupName:z,normalizedKeys:se,switches:ye}});if(de.filter(({groupName:z})=>z!==o.getPositionalGroupName()).some(({normalizedKeys:z,switches:se})=>!z.every((ye)=>R(se[ye]))))de.filter(({groupName:z})=>z!==o.getPositionalGroupName()).forEach(({normalizedKeys:z,switches:se})=>{z.forEach((ye)=>{if(R(se[ye]))se[ye]=tp(se[ye],4)})});if(de.forEach(({groupName:z,normalizedKeys:se,switches:ye})=>{ne.div(z),se.forEach((ee)=>{let Ee=ye[ee],fe=h[ee]||"",we=null;if(fe.includes(k))fe=n(fe.substring(k.length));if(Y.boolean.includes(ee))we=`[${n("boolean")}]`;if(Y.count.includes(ee))we=`[${n("count")}]`;if(Y.string.includes(ee))we=`[${n("string")}]`;if(Y.normalize.includes(ee))we=`[${n("string")}]`;if(Y.array.includes(ee))we=`[${n("array")}]`;if(Y.number.includes(ee))we=`[${n("number")}]`;let $o=(P)=>typeof P==="string"?`[${n("deprecated: %s",P)}]`:`[${n("deprecated")}]`,y=[ee in B?$o(B[ee]):null,we,ee in I?`[${n("required")}]`:null,Y.choices&&Y.choices[ee]?`[${n("choices:")} ${o.stringifiedValues(Y.choices[ee])}]`:null,O(Y.default[ee],Y.defaultDescription[ee])].filter(Boolean).join(" ");ne.span({text:ys(Ee),padding:[0,2,0,2+Ua(Ee)],width:x(ye,je)+4},fe);let b=e.getInternalMethods().getUsageConfiguration()["hide-types"]===!0;if(y&&!b)ne.div({text:y,padding:[0,0,0,2],align:"right"});else ne.div()}),ne.div()}),d.length)ne.div(n("Examples:")),d.forEach((z)=>{z[0]=z[0].replace(/\$0/g,E)}),d.forEach((z)=>{if(z[1]==="")ne.div({text:z[0],padding:[0,2,0,2]});else ne.div({text:z[0],padding:[0,2,0,2],width:x(d,je)+4},{text:z[1]})}),ne.div();if(m.length>0){let z=m.map((se)=>se.replace(/\$0/g,E)).join(`
17
17
  `);ne.div(`${z}
18
- `)}return ne.toString().replace(/\s*$/,"")};function x(_,C,T){let A=0;if(!Array.isArray(_))_=Object.values(_).map((B)=>[B]);if(_.forEach((B)=>{A=Math.max(t.stringWidth(T?`${T} ${Ds(B[0])}`:Ds(B[0]))+va(B[0]),A)}),C)A=Math.min(A,parseInt((C*0.5).toString(),10));return A}function E(){let _=e.getDemandedOptions(),C=e.getOptions();(Object.keys(C.alias)||[]).forEach((T)=>{C.alias[T].forEach((A)=>{if(h[A])o.describe(T,h[A]);if(A in _)e.demandOption(T,_[A]);if(C.boolean.includes(A))e.boolean(T);if(C.count.includes(A))e.count(T);if(C.string.includes(A))e.string(T);if(C.normalize.includes(A))e.normalize(T);if(C.array.includes(A))e.array(T);if(C.number.includes(A))e.number(T)})})}let F;o.cacheHelpMessage=function(){F=this.help()},o.clearCachedHelpMessage=function(){F=void 0},o.hasCachedHelpMessage=function(){return!!F};function N(_,C,T,A){let B=[],Z=null;return Object.keys(T).forEach((Y)=>{B=B.concat(T[Y])}),_.forEach((Y)=>{if(Z=[Y].concat(C[Y]),!Z.some((oe)=>B.indexOf(oe)!==-1))T[A].push(Y)}),B}function W(_){return e.getOptions().hiddenOptions.indexOf(_)<0||e.parsed.argv[e.getOptions().showHiddenOpt]}o.showHelp=(_)=>{let C=e.getInternalMethods().getLoggerInstance();if(!_)_="error";(typeof _==="function"?_:C[_])(o.help())},o.functionDescription=(_)=>["(",_.name?t.Parser.decamelize(_.name,"-"):n("generated-value"),")"].join(""),o.stringifiedValues=function(C,T){let A="",B=T||", ",Z=[].concat(C);if(!C||!Z.length)return A;return Z.forEach((Y)=>{if(A.length)A+=B;A+=JSON.stringify(Y)}),A};function O(_,C){let T=`[${n("default:")} `;if(_===void 0&&!C)return null;if(C)T+=C;else switch(typeof _){case"string":T+=`"${_}"`;break;case"object":T+=JSON.stringify(_);break;default:T+=_}return`${T}]`}function v(){if(t.process.stdColumns)return Math.min(80,t.process.stdColumns);else return 80}let J=null;o.version=(_)=>{J=_},o.showVersion=(_)=>{let C=e.getInternalMethods().getLoggerInstance();if(!_)_="error";(typeof _==="function"?_:C[_])(J)},o.reset=function(C){return r=null,a=!1,l=[],u=!1,m=[],d=[],f=[],h=mt(h,(T)=>!C[T]),o};let Q=[];return o.freeze=function(){Q.push({failMessage:r,failureOutput:a,usages:l,usageDisabled:u,epilogs:m,examples:d,commands:f,descriptions:h})},o.unfreeze=function(C=!1){let T=Q.pop();if(!T)return;if(C)h={...T.descriptions,...h},f=[...T.commands,...f],l=[...T.usages,...l],d=[...T.examples,...d],m=[...T.epilogs,...m];else({failMessage:r,failureOutput:a,usages:l,usageDisabled:u,epilogs:m,examples:d,commands:f,descriptions:h}=T)},o}function Jo(e){return typeof e==="object"}function Jf(e,t){return Jo(e)?{text:e.text,indentation:e.indentation+t}:{text:e,indentation:t}}function va(e){return Jo(e)?e.indentation:0}function Ds(e){return Jo(e)?e.text:e}var ja=`###-begin-{{app_name}}-completions-###
18
+ `)}return ne.toString().replace(/\s*$/,"")};function x(_,E,I){let A=0;if(!Array.isArray(_))_=Object.values(_).map((B)=>[B]);if(_.forEach((B)=>{A=Math.max(t.stringWidth(I?`${I} ${ys(B[0])}`:ys(B[0]))+Ua(B[0]),A)}),E)A=Math.min(A,parseInt((E*0.5).toString(),10));return A}function C(){let _=e.getDemandedOptions(),E=e.getOptions();(Object.keys(E.alias)||[]).forEach((I)=>{E.alias[I].forEach((A)=>{if(h[A])o.describe(I,h[A]);if(A in _)e.demandOption(I,_[A]);if(E.boolean.includes(A))e.boolean(I);if(E.count.includes(A))e.count(I);if(E.string.includes(A))e.string(I);if(E.normalize.includes(A))e.normalize(I);if(E.array.includes(A))e.array(I);if(E.number.includes(A))e.number(I)})})}let F;o.cacheHelpMessage=function(){F=this.help()},o.clearCachedHelpMessage=function(){F=void 0},o.hasCachedHelpMessage=function(){return!!F};function N(_,E,I,A){let B=[],Z=null;return Object.keys(I).forEach((Y)=>{B=B.concat(I[Y])}),_.forEach((Y)=>{if(Z=[Y].concat(E[Y]),!Z.some((oe)=>B.indexOf(oe)!==-1))I[A].push(Y)}),B}function W(_){return e.getOptions().hiddenOptions.indexOf(_)<0||e.parsed.argv[e.getOptions().showHiddenOpt]}o.showHelp=(_)=>{let E=e.getInternalMethods().getLoggerInstance();if(!_)_="error";(typeof _==="function"?_:E[_])(o.help())},o.functionDescription=(_)=>["(",_.name?t.Parser.decamelize(_.name,"-"):n("generated-value"),")"].join(""),o.stringifiedValues=function(E,I){let A="",B=I||", ",Z=[].concat(E);if(!E||!Z.length)return A;return Z.forEach((Y)=>{if(A.length)A+=B;A+=JSON.stringify(Y)}),A};function O(_,E){let I=`[${n("default:")} `;if(_===void 0&&!E)return null;if(E)I+=E;else switch(typeof _){case"string":I+=`"${_}"`;break;case"object":I+=JSON.stringify(_);break;default:I+=_}return`${I}]`}function L(){if(t.process.stdColumns)return Math.min(80,t.process.stdColumns);else return 80}let J=null;o.version=(_)=>{J=_},o.showVersion=(_)=>{let E=e.getInternalMethods().getLoggerInstance();if(!_)_="error";(typeof _==="function"?_:E[_])(J)},o.reset=function(E){return r=null,a=!1,l=[],u=!1,m=[],d=[],f=[],h=Dt(h,(I)=>!E[I]),o};let Q=[];return o.freeze=function(){Q.push({failMessage:r,failureOutput:a,usages:l,usageDisabled:u,epilogs:m,examples:d,commands:f,descriptions:h})},o.unfreeze=function(E=!1){let I=Q.pop();if(!I)return;if(E)h={...I.descriptions,...h},f=[...I.commands,...f],l=[...I.usages,...l],d=[...I.examples,...d],m=[...I.epilogs,...m];else({failMessage:r,failureOutput:a,usages:l,usageDisabled:u,epilogs:m,examples:d,commands:f,descriptions:h}=I)},o}function qo(e){return typeof e==="object"}function tp(e,t){return qo(e)?{text:e.text,indentation:e.indentation+t}:{text:e,indentation:t}}function Ua(e){return qo(e)?e.indentation:0}function ys(e){return qo(e)?e.text:e}var Ka=`###-begin-{{app_name}}-completions-###
19
19
  #
20
20
  # yargs command completion script
21
21
  #
@@ -44,7 +44,7 @@ _{{app_name}}_yargs_completions()
44
44
  }
45
45
  complete -o bashdefault -o default -F _{{app_name}}_yargs_completions {{app_name}}
46
46
  ###-end-{{app_name}}-completions-###
47
- `,Wa=`#compdef {{app_name}}
47
+ `,Ha=`#compdef {{app_name}}
48
48
  ###-begin-{{app_name}}-completions-###
49
49
  #
50
50
  # yargs command completion script
@@ -71,19 +71,24 @@ else
71
71
  compdef _{{app_name}}_yargs_completions {{app_name}}
72
72
  fi
73
73
  ###-end-{{app_name}}-completions-###
74
- `;class Ua{constructor(e,t,n,o){var s,r,i;this.yargs=e,this.usage=t,this.command=n,this.shim=o,this.completionKey="get-yargs-completions",this.aliases=null,this.customCompletionFunction=null,this.indexAfterLastReset=0,this.zshShell=(i=((s=this.shim.getEnv("SHELL"))===null||s===void 0?void 0:s.includes("zsh"))||((r=this.shim.getEnv("ZSH_NAME"))===null||r===void 0?void 0:r.includes("zsh")))!==null&&i!==void 0?i:!1}defaultCompletion(e,t,n,o){let s=this.command.getCommandHandlers();for(let i=0,c=e.length;i<c;++i)if(s[e[i]]&&s[e[i]].builder){let a=s[e[i]].builder;if(ms(a)){this.indexAfterLastReset=i+1;let l=this.yargs.getInternalMethods().reset();return a(l,!0),l.argv}}let r=[];this.commandCompletions(r,e,n),this.optionCompletions(r,e,t,n),this.choicesFromOptionsCompletions(r,e,t,n),this.choicesFromPositionalsCompletions(r,e,t,n),o(null,r)}commandCompletions(e,t,n){let o=this.yargs.getInternalMethods().getContext().commands;if(!n.match(/^-/)&&o[o.length-1]!==n&&!this.previousArgHasChoices(t))this.usage.getCommands().forEach((s)=>{let r=gt(s[0]).cmd;if(t.indexOf(r)===-1)if(!this.zshShell)e.push(r);else{let i=s[1]||"";e.push(r.replace(/:/g,"\\:")+":"+i)}})}optionCompletions(e,t,n,o){if((o.match(/^-/)||o===""&&e.length===0)&&!this.previousArgHasChoices(t)){let s=this.yargs.getOptions(),r=this.yargs.getGroups()[this.usage.getPositionalGroupName()]||[];Object.keys(s.key).forEach((i)=>{let c=!!s.configuration["boolean-negation"]&&s.boolean.includes(i);if(!r.includes(i)&&!s.hiddenOptions.includes(i)&&!this.argsContainKey(t,i,c))this.completeOptionKey(i,e,o,c&&!!s.default[i])})}}choicesFromOptionsCompletions(e,t,n,o){if(this.previousArgHasChoices(t)){let s=this.getPreviousArgChoices(t);if(s&&s.length>0)e.push(...s.map((r)=>r.replace(/:/g,"\\:")))}}choicesFromPositionalsCompletions(e,t,n,o){if(o===""&&e.length>0&&this.previousArgHasChoices(t))return;let s=this.yargs.getGroups()[this.usage.getPositionalGroupName()]||[],r=Math.max(this.indexAfterLastReset,this.yargs.getInternalMethods().getContext().commands.length+1),i=s[n._.length-r-1];if(!i)return;let c=this.yargs.getOptions().choices[i]||[];for(let a of c)if(a.startsWith(o))e.push(a.replace(/:/g,"\\:"))}getPreviousArgChoices(e){if(e.length<1)return;let t=e[e.length-1],n="";if(!t.startsWith("-")&&e.length>1)n=t,t=e[e.length-2];if(!t.startsWith("-"))return;let o=t.replace(/^-+/,""),s=this.yargs.getOptions(),r=[o,...this.yargs.getAliases()[o]||[]],i;for(let c of r)if(Object.prototype.hasOwnProperty.call(s.key,c)&&Array.isArray(s.choices[c])){i=s.choices[c];break}if(i)return i.filter((c)=>!n||c.startsWith(n))}previousArgHasChoices(e){let t=this.getPreviousArgChoices(e);return t!==void 0&&t.length>0}argsContainKey(e,t,n){let o=(s)=>e.indexOf((/^[^0-9]$/.test(s)?"-":"--")+s)!==-1;if(o(t))return!0;if(n&&o(`no-${t}`))return!0;if(this.aliases){for(let s of this.aliases[t])if(o(s))return!0}return!1}completeOptionKey(e,t,n,o){var s,r,i,c;let a=e;if(this.zshShell){let f=this.usage.getDescriptions(),h=(r=(s=this===null||this===void 0?void 0:this.aliases)===null||s===void 0?void 0:s[e])===null||r===void 0?void 0:r.find((D)=>{let k=f[D];return typeof k==="string"&&k.length>0}),m=h?f[h]:void 0,p=(c=(i=f[e])!==null&&i!==void 0?i:m)!==null&&c!==void 0?c:"";a=`${e.replace(/:/g,"\\:")}:${p.replace("__yargsString__:","").replace(/(\r\n|\n|\r)/gm," ")}`}let l=(f)=>/^--/.test(f),u=(f)=>/^[^0-9]$/.test(f),d=!l(n)&&u(e)?"-":"--";if(t.push(d+a),o)t.push(d+"no-"+a)}customCompletion(e,t,n,o){if($e(this.customCompletionFunction,null,this.shim),Hf(this.customCompletionFunction)){let s=this.customCompletionFunction(n,t);if(re(s))return s.then((r)=>{this.shim.process.nextTick(()=>{o(null,r)})}).catch((r)=>{this.shim.process.nextTick(()=>{o(r,void 0)})});return o(null,s)}else if(zf(this.customCompletionFunction))return this.customCompletionFunction(n,t,(s=o)=>this.defaultCompletion(e,t,n,s),(s)=>{o(null,s)});else return this.customCompletionFunction(n,t,(s)=>{o(null,s)})}getCompletion(e,t){let n=e.length?e[e.length-1]:"",o=this.yargs.parse(e,!0),s=this.customCompletionFunction?(r)=>this.customCompletion(e,r,n,t):(r)=>this.defaultCompletion(e,r,n,t);return re(o)?o.then(s):s(o)}generateCompletionScript(e,t){let n=this.zshShell?Wa:ja,o=this.shim.path.basename(e);if(e.match(/\.js$/))e=`./${e}`;return n=n.replace(/{{app_name}}/g,o),n=n.replace(/{{completion_command}}/g,t),n.replace(/{{app_path}}/g,e)}registerFunction(e){this.customCompletionFunction=e}setParsed(e){this.aliases=e.aliases}}function Ja(e,t,n,o){return new Ua(e,t,n,o)}function Hf(e){return e.length<3}function zf(e){return e.length>3}function Ka(e,t){if(e.length===0)return t.length;if(t.length===0)return e.length;let n=[],o;for(o=0;o<=t.length;o++)n[o]=[o];let s;for(s=0;s<=e.length;s++)n[0][s]=s;for(o=1;o<=t.length;o++)for(s=1;s<=e.length;s++)if(t.charAt(o-1)===e.charAt(s-1))n[o][s]=n[o-1][s-1];else if(o>1&&s>1&&t.charAt(o-2)===e.charAt(s-1)&&t.charAt(o-1)===e.charAt(s-2))n[o][s]=n[o-2][s-2]+1;else n[o][s]=Math.min(n[o-1][s-1]+1,Math.min(n[o][s-1]+1,n[o-1][s]+1));return n[t.length][e.length]}var Ha=["$0","--","_"];function za(e,t,n){let o=n.y18n.__,s=n.y18n.__n,r={};r.nonOptionCount=function(d){let f=e.getDemandedCommands(),m=d._.length+(d["--"]?d["--"].length:0)-e.getInternalMethods().getContext().commands.length;if(f._&&(m<f._.min||m>f._.max)){if(m<f._.min)if(f._.minMsg!==void 0)t.fail(f._.minMsg?f._.minMsg.replace(/\$0/g,m.toString()).replace(/\$1/,f._.min.toString()):null);else t.fail(s("Not enough non-option arguments: got %s, need at least %s","Not enough non-option arguments: got %s, need at least %s",m,m.toString(),f._.min.toString()));else if(m>f._.max)if(f._.maxMsg!==void 0)t.fail(f._.maxMsg?f._.maxMsg.replace(/\$0/g,m.toString()).replace(/\$1/,f._.max.toString()):null);else t.fail(s("Too many non-option arguments: got %s, maximum of %s","Too many non-option arguments: got %s, maximum of %s",m,m.toString(),f._.max.toString()))}},r.positionalCount=function(d,f){if(f<d)t.fail(s("Not enough non-option arguments: got %s, need at least %s","Not enough non-option arguments: got %s, need at least %s",f,f+"",d+""))},r.requiredArguments=function(d,f){let h=null;for(let m of Object.keys(f))if(!Object.prototype.hasOwnProperty.call(d,m)||typeof d[m]>"u")h=h||{},h[m]=f[m];if(h){let m=[];for(let D of Object.keys(h)){let k=h[D];if(k&&m.indexOf(k)<0)m.push(k)}let p=m.length?`
74
+ `;class za{constructor(e,t,n,o){var s,r,i;this.yargs=e,this.usage=t,this.command=n,this.shim=o,this.completionKey="get-yargs-completions",this.aliases=null,this.customCompletionFunction=null,this.indexAfterLastReset=0,this.zshShell=(i=((s=this.shim.getEnv("SHELL"))===null||s===void 0?void 0:s.includes("zsh"))||((r=this.shim.getEnv("ZSH_NAME"))===null||r===void 0?void 0:r.includes("zsh")))!==null&&i!==void 0?i:!1}defaultCompletion(e,t,n,o){let s=this.command.getCommandHandlers();for(let i=0,c=e.length;i<c;++i)if(s[e[i]]&&s[e[i]].builder){let a=s[e[i]].builder;if(Ds(a)){this.indexAfterLastReset=i+1;let l=this.yargs.getInternalMethods().reset();return a(l,!0),l.argv}}let r=[];this.commandCompletions(r,e,n),this.optionCompletions(r,e,t,n),this.choicesFromOptionsCompletions(r,e,t,n),this.choicesFromPositionalsCompletions(r,e,t,n),o(null,r)}commandCompletions(e,t,n){let o=this.yargs.getInternalMethods().getContext().commands;if(!n.match(/^-/)&&o[o.length-1]!==n&&!this.previousArgHasChoices(t))this.usage.getCommands().forEach((s)=>{let r=mt(s[0]).cmd;if(t.indexOf(r)===-1)if(!this.zshShell)e.push(r);else{let i=s[1]||"";e.push(r.replace(/:/g,"\\:")+":"+i)}})}optionCompletions(e,t,n,o){if((o.match(/^-/)||o===""&&e.length===0)&&!this.previousArgHasChoices(t)){let s=this.yargs.getOptions(),r=this.yargs.getGroups()[this.usage.getPositionalGroupName()]||[];Object.keys(s.key).forEach((i)=>{let c=!!s.configuration["boolean-negation"]&&s.boolean.includes(i);if(!r.includes(i)&&!s.hiddenOptions.includes(i)&&!this.argsContainKey(t,i,c))this.completeOptionKey(i,e,o,c&&!!s.default[i])})}}choicesFromOptionsCompletions(e,t,n,o){if(this.previousArgHasChoices(t)){let s=this.getPreviousArgChoices(t);if(s&&s.length>0)e.push(...s.map((r)=>r.replace(/:/g,"\\:")))}}choicesFromPositionalsCompletions(e,t,n,o){if(o===""&&e.length>0&&this.previousArgHasChoices(t))return;let s=this.yargs.getGroups()[this.usage.getPositionalGroupName()]||[],r=Math.max(this.indexAfterLastReset,this.yargs.getInternalMethods().getContext().commands.length+1),i=s[n._.length-r-1];if(!i)return;let c=this.yargs.getOptions().choices[i]||[];for(let a of c)if(a.startsWith(o))e.push(a.replace(/:/g,"\\:"))}getPreviousArgChoices(e){if(e.length<1)return;let t=e[e.length-1],n="";if(!t.startsWith("-")&&e.length>1)n=t,t=e[e.length-2];if(!t.startsWith("-"))return;let o=t.replace(/^-+/,""),s=this.yargs.getOptions(),r=[o,...this.yargs.getAliases()[o]||[]],i;for(let c of r)if(Object.prototype.hasOwnProperty.call(s.key,c)&&Array.isArray(s.choices[c])){i=s.choices[c];break}if(i)return i.filter((c)=>!n||c.startsWith(n))}previousArgHasChoices(e){let t=this.getPreviousArgChoices(e);return t!==void 0&&t.length>0}argsContainKey(e,t,n){let o=(s)=>e.indexOf((/^[^0-9]$/.test(s)?"-":"--")+s)!==-1;if(o(t))return!0;if(n&&o(`no-${t}`))return!0;if(this.aliases){for(let s of this.aliases[t])if(o(s))return!0}return!1}completeOptionKey(e,t,n,o){var s,r,i,c;let a=e;if(this.zshShell){let f=this.usage.getDescriptions(),h=(r=(s=this===null||this===void 0?void 0:this.aliases)===null||s===void 0?void 0:s[e])===null||r===void 0?void 0:r.find((D)=>{let k=f[D];return typeof k==="string"&&k.length>0}),m=h?f[h]:void 0,p=(c=(i=f[e])!==null&&i!==void 0?i:m)!==null&&c!==void 0?c:"";a=`${e.replace(/:/g,"\\:")}:${p.replace("__yargsString__:","").replace(/(\r\n|\n|\r)/gm," ")}`}let l=(f)=>/^--/.test(f),u=(f)=>/^[^0-9]$/.test(f),d=!l(n)&&u(e)?"-":"--";if(t.push(d+a),o)t.push(d+"no-"+a)}customCompletion(e,t,n,o){if($e(this.customCompletionFunction,null,this.shim),sp(this.customCompletionFunction)){let s=this.customCompletionFunction(n,t);if(re(s))return s.then((r)=>{this.shim.process.nextTick(()=>{o(null,r)})}).catch((r)=>{this.shim.process.nextTick(()=>{o(r,void 0)})});return o(null,s)}else if(op(this.customCompletionFunction))return this.customCompletionFunction(n,t,(s=o)=>this.defaultCompletion(e,t,n,s),(s)=>{o(null,s)});else return this.customCompletionFunction(n,t,(s)=>{o(null,s)})}getCompletion(e,t){let n=e.length?e[e.length-1]:"",o=this.yargs.parse(e,!0),s=this.customCompletionFunction?(r)=>this.customCompletion(e,r,n,t):(r)=>this.defaultCompletion(e,r,n,t);return re(o)?o.then(s):s(o)}generateCompletionScript(e,t){let n=this.zshShell?Ha:Ka,o=this.shim.path.basename(e);if(e.match(/\.js$/))e=`./${e}`;return n=n.replace(/{{app_name}}/g,o),n=n.replace(/{{completion_command}}/g,t),n.replace(/{{app_path}}/g,e)}registerFunction(e){this.customCompletionFunction=e}setParsed(e){this.aliases=e.aliases}}function qa(e,t,n,o){return new za(e,t,n,o)}function sp(e){return e.length<3}function op(e){return e.length>3}function Ga(e,t){if(e.length===0)return t.length;if(t.length===0)return e.length;let n=[],o;for(o=0;o<=t.length;o++)n[o]=[o];let s;for(s=0;s<=e.length;s++)n[0][s]=s;for(o=1;o<=t.length;o++)for(s=1;s<=e.length;s++)if(t.charAt(o-1)===e.charAt(s-1))n[o][s]=n[o-1][s-1];else if(o>1&&s>1&&t.charAt(o-2)===e.charAt(s-1)&&t.charAt(o-1)===e.charAt(s-2))n[o][s]=n[o-2][s-2]+1;else n[o][s]=Math.min(n[o-1][s-1]+1,Math.min(n[o][s-1]+1,n[o-1][s]+1));return n[t.length][e.length]}var Xa=["$0","--","_"];function Ya(e,t,n){let o=n.y18n.__,s=n.y18n.__n,r={};r.nonOptionCount=function(d){let f=e.getDemandedCommands(),m=d._.length+(d["--"]?d["--"].length:0)-e.getInternalMethods().getContext().commands.length;if(f._&&(m<f._.min||m>f._.max)){if(m<f._.min)if(f._.minMsg!==void 0)t.fail(f._.minMsg?f._.minMsg.replace(/\$0/g,m.toString()).replace(/\$1/,f._.min.toString()):null);else t.fail(s("Not enough non-option arguments: got %s, need at least %s","Not enough non-option arguments: got %s, need at least %s",m,m.toString(),f._.min.toString()));else if(m>f._.max)if(f._.maxMsg!==void 0)t.fail(f._.maxMsg?f._.maxMsg.replace(/\$0/g,m.toString()).replace(/\$1/,f._.max.toString()):null);else t.fail(s("Too many non-option arguments: got %s, maximum of %s","Too many non-option arguments: got %s, maximum of %s",m,m.toString(),f._.max.toString()))}},r.positionalCount=function(d,f){if(f<d)t.fail(s("Not enough non-option arguments: got %s, need at least %s","Not enough non-option arguments: got %s, need at least %s",f,f+"",d+""))},r.requiredArguments=function(d,f){let h=null;for(let m of Object.keys(f))if(!Object.prototype.hasOwnProperty.call(d,m)||typeof d[m]>"u")h=h||{},h[m]=f[m];if(h){let m=[];for(let D of Object.keys(h)){let k=h[D];if(k&&m.indexOf(k)<0)m.push(k)}let p=m.length?`
75
75
  ${m.join(`
76
- `)}`:"";t.fail(s("Missing required argument: %s","Missing required arguments: %s",Object.keys(h).length,Object.keys(h).join(", ")+p))}},r.unknownArguments=function(d,f,h,m,p=!0){var D;let k=e.getInternalMethods().getCommandInstance().getCommands(),x=[],E=e.getInternalMethods().getContext();if(Object.keys(d).forEach((F)=>{if(!Ha.includes(F)&&!Object.prototype.hasOwnProperty.call(h,F)&&!Object.prototype.hasOwnProperty.call(e.getInternalMethods().getParseContext(),F)&&!r.isValidAndSomeAliasIsNotNew(F,f))x.push(F)}),p&&(E.commands.length>0||k.length>0||m))d._.slice(E.commands.length).forEach((F)=>{if(!k.includes(""+F))x.push(""+F)});if(p){let N=((D=e.getDemandedCommands()._)===null||D===void 0?void 0:D.max)||0,W=E.commands.length+N;if(W<d._.length)d._.slice(W).forEach((O)=>{if(O=String(O),!E.commands.includes(O)&&!x.includes(O))x.push(O)})}if(x.length)t.fail(s("Unknown argument: %s","Unknown arguments: %s",x.length,x.map((F)=>F.trim()?F:`"${F}"`).join(", ")))},r.unknownCommands=function(d){let f=e.getInternalMethods().getCommandInstance().getCommands(),h=[],m=e.getInternalMethods().getContext();if(m.commands.length>0||f.length>0)d._.slice(m.commands.length).forEach((p)=>{if(!f.includes(""+p))h.push(""+p)});if(h.length>0)return t.fail(s("Unknown command: %s","Unknown commands: %s",h.length,h.join(", "))),!0;else return!1},r.isValidAndSomeAliasIsNotNew=function(d,f){if(!Object.prototype.hasOwnProperty.call(f,d))return!1;let h=e.parsed.newAliases;return[d,...f[d]].some((m)=>!Object.prototype.hasOwnProperty.call(h,m)||!h[d])},r.limitedChoices=function(d){let f=e.getOptions(),h={};if(!Object.keys(f.choices).length)return;Object.keys(d).forEach((D)=>{if(Ha.indexOf(D)===-1&&Object.prototype.hasOwnProperty.call(f.choices,D))[].concat(d[D]).forEach((k)=>{if(f.choices[D].indexOf(k)===-1&&k!==void 0)h[D]=(h[D]||[]).concat(k)})});let m=Object.keys(h);if(!m.length)return;let p=o("Invalid values:");m.forEach((D)=>{p+=`
77
- ${o("Argument: %s, Given: %s, Choices: %s",D,t.stringifiedValues(h[D]),t.stringifiedValues(f.choices[D]))}`}),t.fail(p)};let i={};r.implies=function(d,f){if(L("<string|object> [array|number|string]",[d,f],arguments.length),typeof d==="object")Object.keys(d).forEach((h)=>{r.implies(h,d[h])});else{if(e.global(d),!i[d])i[d]=[];if(Array.isArray(f))f.forEach((h)=>r.implies(d,h));else $e(f,void 0,n),i[d].push(f)}},r.getImplied=function(){return i};function c(u,d){let f=Number(d);if(d=isNaN(f)?d:f,typeof d==="number")d=u._.length>=d;else if(d.match(/^--no-.+/))d=d.match(/^--no-(.+)/)[1],d=!Object.prototype.hasOwnProperty.call(u,d);else d=Object.prototype.hasOwnProperty.call(u,d);return d}r.implications=function(d){let f=[];if(Object.keys(i).forEach((h)=>{let m=h;(i[h]||[]).forEach((p)=>{let D=m,k=p;if(D=c(d,D),p=c(d,p),D&&!p)f.push(` ${m} -> ${k}`)})}),f.length){let h=`${o("Implications failed:")}
78
- `;f.forEach((m)=>{h+=m}),t.fail(h)}};let a={};r.conflicts=function(d,f){if(L("<string|object> [array|string]",[d,f],arguments.length),typeof d==="object")Object.keys(d).forEach((h)=>{r.conflicts(h,d[h])});else{if(e.global(d),!a[d])a[d]=[];if(Array.isArray(f))f.forEach((h)=>r.conflicts(d,h));else a[d].push(f)}},r.getConflicting=()=>a,r.conflicting=function(d){if(Object.keys(d).forEach((f)=>{if(a[f])a[f].forEach((h)=>{if(h&&d[f]!==void 0&&d[h]!==void 0)t.fail(o("Arguments %s and %s are mutually exclusive",f,h))})}),e.getInternalMethods().getParserConfiguration()["strip-dashed"])Object.keys(a).forEach((f)=>{a[f].forEach((h)=>{if(h&&d[n.Parser.camelCase(f)]!==void 0&&d[n.Parser.camelCase(h)]!==void 0)t.fail(o("Arguments %s and %s are mutually exclusive",f,h))})})},r.recommendCommands=function(d,f){f=f.sort((D,k)=>k.length-D.length);let m=null,p=1/0;for(let D=0,k;(k=f[D])!==void 0;D++){let x=Ka(d,k);if(x<=3&&x<p)p=x,m=k}if(m)t.fail(o("Did you mean %s?",m))},r.reset=function(d){return i=mt(i,(f)=>!d[f]),a=mt(a,(f)=>!d[f]),r};let l=[];return r.freeze=function(){l.push({implied:i,conflicting:a})},r.unfreeze=function(){let d=l.pop();$e(d,void 0,n),{implied:i,conflicting:a}=d},r}var Ko=[],_n;function Fn(e,t,n,o){_n=o;let s={};if(Object.prototype.hasOwnProperty.call(e,"extends")){if(typeof e.extends!=="string")return s;let r=/\.json|\..*rc$/.test(e.extends),i=null;if(!r)try{i=import.meta.resolve(e.extends)}catch(c){return e}else i=Gf(t,e.extends);qf(i),Ko.push(i),s=r?JSON.parse(_n.readFileSync(i,"utf8")):o.require(e.extends),delete e.extends,s=Fn(s,_n.path.dirname(i),n,_n)}return Ko=[],n?qa(s,e):Object.assign({},s,e)}function qf(e){if(Ko.indexOf(e)>-1)throw new fe(`Circular extended configurations: '${e}'.`)}function Gf(e,t){return _n.path.resolve(e,t)}function qa(e,t){let n={};function o(s){return s&&typeof s==="object"&&!Array.isArray(s)}Object.assign(n,e);for(let s of Object.keys(t))if(o(t[s])&&o(n[s]))n[s]=qa(e[s],t[s]);else n[s]=t[s];return n}var j=function(e,t,n,o,s){if(o==="m")throw TypeError("Private method is not writable");if(o==="a"&&!s)throw TypeError("Private accessor was defined without a setter");if(typeof t==="function"?e!==t||!s:!t.has(e))throw TypeError("Cannot write private member to an object whose class did not declare it");return o==="a"?s.call(e,n):s?s.value=n:t.set(e,n),n},g=function(e,t,n,o){if(n==="a"&&!o)throw TypeError("Private accessor was defined without a getter");if(typeof t==="function"?e!==t||!o:!t.has(e))throw TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?o:n==="a"?o.call(e):o?o.value:t.get(e)},pe,Rt,$n,Ae,Re,ys,yt,Nt,ws,Ue,bs,Je,ot,Ne,Ke,ks,Bt,ke,K,xs,Cs,Be,Mt,rn,vt,wt,Es,G,Lt,jt,Wt,V,Ss,rt,le;function pc(e){return(t=[],n=e.process.cwd(),o)=>{let s=new hc(t,n,o,e);return Object.defineProperty(s,"argv",{get:()=>s.parse(),enumerable:!0}),s.help(),s.version(),s}}var Ga=Symbol("copyDoubleDash"),Xa=Symbol("copyDoubleDash"),Ho=Symbol("deleteFromParserHintObject"),Ya=Symbol("emitWarning"),Va=Symbol("freeze"),Za=Symbol("getDollarZero"),Ut=Symbol("getParserConfiguration"),Qa=Symbol("getUsageConfiguration"),zo=Symbol("guessLocale"),ec=Symbol("guessVersion"),tc=Symbol("parsePositionalNumbers"),qo=Symbol("pkgUp"),bt=Symbol("populateParserHintArray"),an=Symbol("populateParserHintSingleValueDictionary"),Go=Symbol("populateParserHintArrayDictionary"),Xo=Symbol("populateParserHintDictionary"),Yo=Symbol("sanitizeKey"),Vo=Symbol("setKey"),Zo=Symbol("unfreeze"),nc=Symbol("validateAsync"),sc=Symbol("getCommandInstance"),oc=Symbol("getContext"),rc=Symbol("getHasOutput"),ic=Symbol("getLoggerInstance"),ac=Symbol("getParseContext"),cc=Symbol("getUsageInstance"),lc=Symbol("getValidationInstance"),_s=Symbol("hasParseCallback"),uc=Symbol("isGlobalContext"),Jt=Symbol("postProcess"),dc=Symbol("rebase"),Qo=Symbol("reset"),An=Symbol("runYargsParserAndExecuteCommands"),er=Symbol("runValidation"),fc=Symbol("setHasOutput"),Kt=Symbol("kTrackManuallySetKeys"),Xf="en_US";class hc{constructor(e=[],t,n,o){this.customScriptName=!1,this.parsed=!1,pe.set(this,void 0),Rt.set(this,void 0),$n.set(this,{commands:[],fullCommands:[]}),Ae.set(this,null),Re.set(this,null),ys.set(this,"show-hidden"),yt.set(this,null),Nt.set(this,!0),ws.set(this,{}),Ue.set(this,!0),bs.set(this,[]),Je.set(this,void 0),ot.set(this,{}),Ne.set(this,!1),Ke.set(this,null),ks.set(this,!0),Bt.set(this,void 0),ke.set(this,""),K.set(this,void 0),xs.set(this,void 0),Cs.set(this,{}),Be.set(this,null),Mt.set(this,null),rn.set(this,{}),vt.set(this,{}),wt.set(this,void 0),Es.set(this,!1),G.set(this,void 0),Lt.set(this,!1),jt.set(this,!1),Wt.set(this,!1),V.set(this,void 0),Ss.set(this,{}),rt.set(this,null),le.set(this,void 0),j(this,G,o,"f"),j(this,wt,e,"f"),j(this,Rt,t,"f"),j(this,xs,n,"f"),j(this,Je,new Uo(this),"f"),this.$0=this[Za](),this[Qo](),j(this,pe,g(this,pe,"f"),"f"),j(this,V,g(this,V,"f"),"f"),j(this,le,g(this,le,"f"),"f"),j(this,K,g(this,K,"f"),"f"),g(this,K,"f").showHiddenOpt=g(this,ys,"f"),j(this,Bt,this[Xa](),"f"),g(this,G,"f").y18n.setLocale(Xf)}addHelpOpt(e,t){if(L("[string|boolean] [string]",[e,t],arguments.length),g(this,Ke,"f"))this[Ho](g(this,Ke,"f")),j(this,Ke,null,"f");if(e===!1&&t===void 0)return this;return j(this,Ke,typeof e==="string"?e:"help","f"),this.boolean(g(this,Ke,"f")),this.describe(g(this,Ke,"f"),t||g(this,V,"f").deferY18nLookup("Show help")),this}help(e,t){return this.addHelpOpt(e,t)}addShowHiddenOpt(e,t){if(L("[string|boolean] [string]",[e,t],arguments.length),e===!1&&t===void 0)return this;let n=typeof e==="string"?e:g(this,ys,"f");return this.boolean(n),this.describe(n,t||g(this,V,"f").deferY18nLookup("Show hidden options")),g(this,K,"f").showHiddenOpt=n,this}showHidden(e,t){return this.addShowHiddenOpt(e,t)}alias(e,t){return L("<object|string|array> [string|array]",[e,t],arguments.length),this[Go](this.alias.bind(this),"alias",e,t),this}array(e){return L("<array|string>",[e],arguments.length),this[bt]("array",e),this[Kt](e),this}boolean(e){return L("<array|string>",[e],arguments.length),this[bt]("boolean",e),this[Kt](e),this}check(e,t){return L("<function> [boolean]",[e,t],arguments.length),this.middleware((n,o)=>Pt(()=>e(n,o.getOptions()),(s)=>{if(!s)g(this,V,"f").fail(g(this,G,"f").y18n.__("Argument check failed: %s",e.toString()));else if(typeof s==="string"||s instanceof Error)g(this,V,"f").fail(s.toString(),s);return n},(s)=>(g(this,V,"f").fail(s.message?s.message:s.toString(),s),n)),!1,t),this}choices(e,t){return L("<object|string|array> [string|array]",[e,t],arguments.length),this[Go](this.choices.bind(this),"choices",e,t),this}coerce(e,t){if(L("<object|string|array> [function]",[e,t],arguments.length),Array.isArray(e)){if(!t)throw new fe("coerce callback must be provided");for(let o of e)this.coerce(o,t);return this}else if(typeof e==="object"){for(let o of Object.keys(e))this.coerce(o,e[o]);return this}if(!t)throw new fe("coerce callback must be provided");let n=e;return g(this,K,"f").key[n]=!0,g(this,Je,"f").addCoerceMiddleware((o,s)=>{var r;let i=(r=s.getAliases()[n])!==null&&r!==void 0?r:[],c=[n,...i].filter((a)=>Object.prototype.hasOwnProperty.call(o,a));if(c.length===0)return o;return Pt(()=>t(o[c[0]]),(a)=>(c.forEach((l)=>{o[l]=a}),o),(a)=>{throw new fe(a.message)})},n),this}conflicts(e,t){return L("<string|object> [string|array]",[e,t],arguments.length),g(this,le,"f").conflicts(e,t),this}config(e="config",t,n){if(L("[object|string] [string|function] [function]",[e,t,n],arguments.length),typeof e==="object"&&!Array.isArray(e))return e=Fn(e,g(this,Rt,"f"),this[Ut]()["deep-merge-config"]||!1,g(this,G,"f")),g(this,K,"f").configObjects=(g(this,K,"f").configObjects||[]).concat(e),this;if(typeof t==="function")n=t,t=void 0;return this.describe(e,t||g(this,V,"f").deferY18nLookup("Path to JSON config file")),(Array.isArray(e)?e:[e]).forEach((o)=>{g(this,K,"f").config[o]=n||!0}),this}completion(e,t,n){if(L("[string] [string|boolean|function] [function]",[e,t,n],arguments.length),typeof t==="function")n=t,t=void 0;if(j(this,Re,e||g(this,Re,"f")||"completion","f"),!t&&t!==!1)t="generate completion script";if(this.command(g(this,Re,"f"),t),n)g(this,Ae,"f").registerFunction(n);return this}command(e,t,n,o,s,r){return L("<string|array|object> [string|boolean] [function|object] [function] [array] [boolean|string]",[e,t,n,o,s,r],arguments.length),g(this,pe,"f").addHandler(e,t,n,o,s,r),this}commands(e,t,n,o,s,r){return this.command(e,t,n,o,s,r)}commandDir(e,t){L("<string> [object]",[e,t],arguments.length);let n=g(this,xs,"f")||g(this,G,"f").require;return g(this,pe,"f").addDirectory(e,n,g(this,G,"f").getCallerFile(),t),this}count(e){return L("<array|string>",[e],arguments.length),this[bt]("count",e),this[Kt](e),this}default(e,t,n){if(L("<object|string|array> [*] [string]",[e,t,n],arguments.length),n)Wo(e,g(this,G,"f")),g(this,K,"f").defaultDescription[e]=n;if(typeof t==="function"){if(Wo(e,g(this,G,"f")),!g(this,K,"f").defaultDescription[e])g(this,K,"f").defaultDescription[e]=g(this,V,"f").functionDescription(t);t=t.call()}return this[an](this.default.bind(this),"default",e,t),this}defaults(e,t,n){return this.default(e,t,n)}demandCommand(e=1,t,n,o){if(L("[number] [number|string] [string|null|undefined] [string|null|undefined]",[e,t,n,o],arguments.length),typeof t!=="number")n=t,t=1/0;return this.global("_",!1),g(this,K,"f").demandedCommands._={min:e,max:t,minMsg:n,maxMsg:o},this}demand(e,t,n){if(Array.isArray(t))t.forEach((o)=>{$e(n,!0,g(this,G,"f")),this.demandOption(o,n)}),t=1/0;else if(typeof t!=="number")n=t,t=1/0;if(typeof e==="number")$e(n,!0,g(this,G,"f")),this.demandCommand(e,t,n,n);else if(Array.isArray(e))e.forEach((o)=>{$e(n,!0,g(this,G,"f")),this.demandOption(o,n)});else if(typeof n==="string")this.demandOption(e,n);else if(n===!0||typeof n>"u")this.demandOption(e);return this}demandOption(e,t){return L("<object|string|array> [string]",[e,t],arguments.length),this[an](this.demandOption.bind(this),"demandedOptions",e,t),this}deprecateOption(e,t){return L("<string> [string|boolean]",[e,t],arguments.length),g(this,K,"f").deprecatedOptions[e]=t,this}describe(e,t){return L("<object|string|array> [string]",[e,t],arguments.length),this[Vo](e,!0),g(this,V,"f").describe(e,t),this}detectLocale(e){return L("<boolean>",[e],arguments.length),j(this,Nt,e,"f"),this}env(e){if(L("[string|boolean]",[e],arguments.length),e===!1)delete g(this,K,"f").envPrefix;else g(this,K,"f").envPrefix=e||"";return this}epilogue(e){return L("<string>",[e],arguments.length),g(this,V,"f").epilog(e),this}epilog(e){return this.epilogue(e)}example(e,t){if(L("<string|array> [string]",[e,t],arguments.length),Array.isArray(e))e.forEach((n)=>this.example(...n));else g(this,V,"f").example(e,t);return this}exit(e,t){if(j(this,Ne,!0,"f"),j(this,yt,t,"f"),g(this,Ue,"f"))g(this,G,"f").process.exit(e)}exitProcess(e=!0){return L("[boolean]",[e],arguments.length),j(this,Ue,e,"f"),this}fail(e){if(L("<function|boolean>",[e],arguments.length),typeof e==="boolean"&&e!==!1)throw new fe("Invalid first argument. Expected function or boolean 'false'");return g(this,V,"f").failFn(e),this}getAliases(){return this.parsed?this.parsed.aliases:{}}async getCompletion(e,t){if(L("<array> [function]",[e,t],arguments.length),!t)return new Promise((n,o)=>{g(this,Ae,"f").getCompletion(e,(s,r)=>{if(s)o(s);else n(r)})});else return g(this,Ae,"f").getCompletion(e,t)}getDemandedOptions(){return L([],0),g(this,K,"f").demandedOptions}getDemandedCommands(){return L([],0),g(this,K,"f").demandedCommands}getDeprecatedOptions(){return L([],0),g(this,K,"f").deprecatedOptions}getDetectLocale(){return g(this,Nt,"f")}getExitProcess(){return g(this,Ue,"f")}getGroups(){return Object.assign({},g(this,ot,"f"),g(this,vt,"f"))}getHelp(){if(j(this,Ne,!0,"f"),!g(this,V,"f").hasCachedHelpMessage()){if(!this.parsed){let t=this[An](g(this,wt,"f"),void 0,void 0,0,!0);if(re(t))return t.then(()=>g(this,V,"f").help())}let e=g(this,pe,"f").runDefaultBuilderOn(this);if(re(e))return e.then(()=>g(this,V,"f").help())}return Promise.resolve(g(this,V,"f").help())}getOptions(){return g(this,K,"f")}getStrict(){return g(this,Lt,"f")}getStrictCommands(){return g(this,jt,"f")}getStrictOptions(){return g(this,Wt,"f")}global(e,t){if(L("<string|array> [boolean]",[e,t],arguments.length),e=[].concat(e),t!==!1)g(this,K,"f").local=g(this,K,"f").local.filter((n)=>e.indexOf(n)===-1);else e.forEach((n)=>{if(!g(this,K,"f").local.includes(n))g(this,K,"f").local.push(n)});return this}group(e,t){L("<string|array> <string>",[e,t],arguments.length);let n=g(this,vt,"f")[t]||g(this,ot,"f")[t];if(g(this,vt,"f")[t])delete g(this,vt,"f")[t];let o={};return g(this,ot,"f")[t]=(n||[]).concat(e).filter((s)=>{if(o[s])return!1;return o[s]=!0}),this}hide(e){return L("<string>",[e],arguments.length),g(this,K,"f").hiddenOptions.push(e),this}implies(e,t){return L("<string|object> [number|string|array]",[e,t],arguments.length),g(this,le,"f").implies(e,t),this}locale(e){if(L("[string]",[e],arguments.length),e===void 0)return this[zo](),g(this,G,"f").y18n.getLocale();return j(this,Nt,!1,"f"),g(this,G,"f").y18n.setLocale(e),this}middleware(e,t,n){return g(this,Je,"f").addMiddleware(e,!!t,n)}nargs(e,t){return L("<string|object|array> [number]",[e,t],arguments.length),this[an](this.nargs.bind(this),"narg",e,t),this}normalize(e){return L("<array|string>",[e],arguments.length),this[bt]("normalize",e),this}number(e){return L("<array|string>",[e],arguments.length),this[bt]("number",e),this[Kt](e),this}option(e,t){if(L("<string|object> [object]",[e,t],arguments.length),typeof e==="object")Object.keys(e).forEach((n)=>{this.options(n,e[n])});else{if(typeof t!=="object")t={};if(this[Kt](e),g(this,rt,"f")&&(e==="version"||(t===null||t===void 0?void 0:t.alias)==="version"))this[Ya](['"version" is a reserved word.',"Please do one of the following:",'- Disable version with `yargs.version(false)` if using "version" as an option',"- Use the built-in `yargs.version` method instead (if applicable)","- Use a different option key","https://yargs.js.org/docs/#api-reference-version"].join(`
79
- `),void 0,"versionWarning");if(g(this,K,"f").key[e]=!0,t.alias)this.alias(e,t.alias);let n=t.deprecate||t.deprecated;if(n)this.deprecateOption(e,n);let o=t.demand||t.required||t.require;if(o)this.demand(e,o);if(t.demandOption)this.demandOption(e,typeof t.demandOption==="string"?t.demandOption:void 0);if(t.conflicts)this.conflicts(e,t.conflicts);if("default"in t)this.default(e,t.default);if(t.implies!==void 0)this.implies(e,t.implies);if(t.nargs!==void 0)this.nargs(e,t.nargs);if(t.config)this.config(e,t.configParser);if(t.normalize)this.normalize(e);if(t.choices)this.choices(e,t.choices);if(t.coerce)this.coerce(e,t.coerce);if(t.group)this.group(e,t.group);if(t.boolean||t.type==="boolean"){if(this.boolean(e),t.alias)this.boolean(t.alias)}if(t.array||t.type==="array"){if(this.array(e),t.alias)this.array(t.alias)}if(t.number||t.type==="number"){if(this.number(e),t.alias)this.number(t.alias)}if(t.string||t.type==="string"){if(this.string(e),t.alias)this.string(t.alias)}if(t.count||t.type==="count")this.count(e);if(typeof t.global==="boolean")this.global(e,t.global);if(t.defaultDescription)g(this,K,"f").defaultDescription[e]=t.defaultDescription;if(t.skipValidation)this.skipValidation(e);let s=t.describe||t.description||t.desc,r=g(this,V,"f").getDescriptions();if(!Object.prototype.hasOwnProperty.call(r,e)||typeof s==="string")this.describe(e,s);if(t.hidden)this.hide(e);if(t.requiresArg)this.requiresArg(e)}return this}options(e,t){return this.option(e,t)}parse(e,t,n){if(L("[string|array] [function|boolean|object] [function]",[e,t,n],arguments.length),this[Va](),typeof e>"u")e=g(this,wt,"f");if(typeof t==="object")j(this,Mt,t,"f"),t=n;if(typeof t==="function")j(this,Be,t,"f"),t=!1;if(!t)j(this,wt,e,"f");if(g(this,Be,"f"))j(this,Ue,!1,"f");let o=this[An](e,!!t),s=this.parsed;if(g(this,Ae,"f").setParsed(this.parsed),re(o))return o.then((r)=>{if(g(this,Be,"f"))g(this,Be,"f").call(this,g(this,yt,"f"),r,g(this,ke,"f"));return r}).catch((r)=>{if(g(this,Be,"f"))g(this,Be,"f")(r,this.parsed.argv,g(this,ke,"f"));throw r}).finally(()=>{this[Zo](),this.parsed=s});else{if(g(this,Be,"f"))g(this,Be,"f").call(this,g(this,yt,"f"),o,g(this,ke,"f"));this[Zo](),this.parsed=s}return o}parseAsync(e,t,n){let o=this.parse(e,t,n);return!re(o)?Promise.resolve(o):o}parseSync(e,t,n){let o=this.parse(e,t,n);if(re(o))throw new fe(".parseSync() must not be used with asynchronous builders, handlers, or middleware");return o}parserConfiguration(e){return L("<object>",[e],arguments.length),j(this,Cs,e,"f"),this}pkgConf(e,t){L("<string> [string]",[e,t],arguments.length);let n=null,o=this[qo](t||g(this,Rt,"f"));if(o[e]&&typeof o[e]==="object")n=Fn(o[e],t||g(this,Rt,"f"),this[Ut]()["deep-merge-config"]||!1,g(this,G,"f")),g(this,K,"f").configObjects=(g(this,K,"f").configObjects||[]).concat(n);return this}positional(e,t){L("<string> <object>",[e,t],arguments.length);let n=["default","defaultDescription","implies","normalize","choices","conflicts","coerce","type","describe","desc","description","alias"];t=mt(t,(r,i)=>{if(r==="type"&&!["string","number","boolean"].includes(i))return!1;return n.includes(r)});let o=g(this,$n,"f").fullCommands[g(this,$n,"f").fullCommands.length-1],s=o?g(this,pe,"f").cmdToParseOptions(o):{array:[],alias:{},default:{},demand:{}};return sn(s).forEach((r)=>{let i=s[r];if(Array.isArray(i)){if(i.indexOf(e)!==-1)t[r]=!0}else if(i[e]&&!(r in t))t[r]=i[e]}),this.group(e,g(this,V,"f").getPositionalGroupName()),this.option(e,t)}recommendCommands(e=!0){return L("[boolean]",[e],arguments.length),j(this,Es,e,"f"),this}required(e,t,n){return this.demand(e,t,n)}require(e,t,n){return this.demand(e,t,n)}requiresArg(e){if(L("<array|string|object> [number]",[e],arguments.length),typeof e==="string"&&g(this,K,"f").narg[e])return this;else this[an](this.requiresArg.bind(this),"narg",e,NaN);return this}showCompletionScript(e,t){return L("[string] [string]",[e,t],arguments.length),e=e||this.$0,g(this,Bt,"f").log(g(this,Ae,"f").generateCompletionScript(e,t||g(this,Re,"f")||"completion")),this}showHelp(e){if(L("[string|function]",[e],arguments.length),j(this,Ne,!0,"f"),!g(this,V,"f").hasCachedHelpMessage()){if(!this.parsed){let n=this[An](g(this,wt,"f"),void 0,void 0,0,!0);if(re(n))return n.then(()=>{g(this,V,"f").showHelp(e)}),this}let t=g(this,pe,"f").runDefaultBuilderOn(this);if(re(t))return t.then(()=>{g(this,V,"f").showHelp(e)}),this}return g(this,V,"f").showHelp(e),this}scriptName(e){return this.customScriptName=!0,this.$0=e,this}showHelpOnFail(e,t){return L("[boolean|string] [string]",[e,t],arguments.length),g(this,V,"f").showHelpOnFail(e,t),this}showVersion(e){return L("[string|function]",[e],arguments.length),g(this,V,"f").showVersion(e),this}skipValidation(e){return L("<array|string>",[e],arguments.length),this[bt]("skipValidation",e),this}strict(e){return L("[boolean]",[e],arguments.length),j(this,Lt,e!==!1,"f"),this}strictCommands(e){return L("[boolean]",[e],arguments.length),j(this,jt,e!==!1,"f"),this}strictOptions(e){return L("[boolean]",[e],arguments.length),j(this,Wt,e!==!1,"f"),this}string(e){return L("<array|string>",[e],arguments.length),this[bt]("string",e),this[Kt](e),this}terminalWidth(){return L([],0),g(this,G,"f").process.stdColumns}updateLocale(e){return this.updateStrings(e)}updateStrings(e){return L("<object>",[e],arguments.length),j(this,Nt,!1,"f"),g(this,G,"f").y18n.updateLocale(e),this}usage(e,t,n,o){if(L("<string|null|undefined> [string|boolean] [function|object] [function]",[e,t,n,o],arguments.length),t!==void 0)if($e(e,null,g(this,G,"f")),(e||"").match(/^\$0( |$)/))return this.command(e,t,n,o);else throw new fe(".usage() description must start with $0 if being used as alias for .command()");else return g(this,V,"f").usage(e),this}usageConfiguration(e){return L("<object>",[e],arguments.length),j(this,Ss,e,"f"),this}version(e,t,n){if(L("[boolean|string] [string] [string]",[e,t,n],arguments.length),g(this,rt,"f"))this[Ho](g(this,rt,"f")),g(this,V,"f").version(void 0),j(this,rt,null,"f");if(arguments.length===0)n=this[ec](),e="version";else if(arguments.length===1){if(e===!1)return this;n=e,e="version"}else if(arguments.length===2)n=t,t=void 0;return j(this,rt,typeof e==="string"?e:"version","f"),t=t||g(this,V,"f").deferY18nLookup("Show version number"),g(this,V,"f").version(n||void 0),this.boolean(g(this,rt,"f")),this.describe(g(this,rt,"f"),t),this}wrap(e){return L("<number|null|undefined>",[e],arguments.length),g(this,V,"f").wrap(e),this}[(pe=new WeakMap,Rt=new WeakMap,$n=new WeakMap,Ae=new WeakMap,Re=new WeakMap,ys=new WeakMap,yt=new WeakMap,Nt=new WeakMap,ws=new WeakMap,Ue=new WeakMap,bs=new WeakMap,Je=new WeakMap,ot=new WeakMap,Ne=new WeakMap,Ke=new WeakMap,ks=new WeakMap,Bt=new WeakMap,ke=new WeakMap,K=new WeakMap,xs=new WeakMap,Cs=new WeakMap,Be=new WeakMap,Mt=new WeakMap,rn=new WeakMap,vt=new WeakMap,wt=new WeakMap,Es=new WeakMap,G=new WeakMap,Lt=new WeakMap,jt=new WeakMap,Wt=new WeakMap,V=new WeakMap,Ss=new WeakMap,rt=new WeakMap,le=new WeakMap,Ga)](e){if(!e._||!e["--"])return e;e._.push.apply(e._,e["--"]);try{delete e["--"]}catch(t){}return e}[Xa](){return{log:(...e)=>{if(!this[_s]())console.log(...e);if(j(this,Ne,!0,"f"),g(this,ke,"f").length)j(this,ke,g(this,ke,"f")+`
80
- `,"f");j(this,ke,g(this,ke,"f")+e.join(" "),"f")},error:(...e)=>{if(!this[_s]())console.error(...e);if(j(this,Ne,!0,"f"),g(this,ke,"f").length)j(this,ke,g(this,ke,"f")+`
81
- `,"f");j(this,ke,g(this,ke,"f")+e.join(" "),"f")}}}[Ho](e){sn(g(this,K,"f")).forEach((t)=>{if(((o)=>o==="configObjects")(t))return;let n=g(this,K,"f")[t];if(Array.isArray(n)){if(n.includes(e))n.splice(n.indexOf(e),1)}else if(typeof n==="object")delete n[e]}),delete g(this,V,"f").getDescriptions()[e]}[Ya](e,t,n){if(!g(this,ws,"f")[n])g(this,G,"f").process.emitWarning(e,t),g(this,ws,"f")[n]=!0}[Va](){g(this,bs,"f").push({options:g(this,K,"f"),configObjects:g(this,K,"f").configObjects.slice(0),exitProcess:g(this,Ue,"f"),groups:g(this,ot,"f"),strict:g(this,Lt,"f"),strictCommands:g(this,jt,"f"),strictOptions:g(this,Wt,"f"),completionCommand:g(this,Re,"f"),output:g(this,ke,"f"),exitError:g(this,yt,"f"),hasOutput:g(this,Ne,"f"),parsed:this.parsed,parseFn:g(this,Be,"f"),parseContext:g(this,Mt,"f")}),g(this,V,"f").freeze(),g(this,le,"f").freeze(),g(this,pe,"f").freeze(),g(this,Je,"f").freeze()}[Za](){let e="",t;if(/\b(node|iojs|electron)(\.exe)?$/.test(g(this,G,"f").process.argv()[0]))t=g(this,G,"f").process.argv().slice(1,2);else t=g(this,G,"f").process.argv().slice(0,1);if(e=t.map((n)=>{let o=this[dc](g(this,Rt,"f"),n);return n.match(/^(\/|([a-zA-Z]:)?\\)/)&&o.length<n.length?o:n}).join(" ").trim(),g(this,G,"f").getEnv("_")&&g(this,G,"f").getProcessArgvBin()===g(this,G,"f").getEnv("_"))e=g(this,G,"f").getEnv("_").replace(`${g(this,G,"f").path.dirname(g(this,G,"f").process.execPath())}/`,"");return e}[Ut](){return g(this,Cs,"f")}[Qa](){return g(this,Ss,"f")}[zo](){if(!g(this,Nt,"f"))return;let e=g(this,G,"f").getEnv("LC_ALL")||g(this,G,"f").getEnv("LC_MESSAGES")||g(this,G,"f").getEnv("LANG")||g(this,G,"f").getEnv("LANGUAGE")||"en_US";this.locale(e.replace(/[.:].*/,""))}[ec](){return this[qo]().version||"unknown"}[tc](e){let t=e["--"]?e["--"]:e._;for(let n=0,o;(o=t[n])!==void 0;n++)if(g(this,G,"f").Parser.looksLikeNumber(o)&&Number.isSafeInteger(Math.floor(parseFloat(`${o}`))))t[n]=Number(o);return e}[qo](e){let t=e||"*";if(g(this,rn,"f")[t])return g(this,rn,"f")[t];let n={};try{let o=e||g(this,G,"f").mainFilename;if(g(this,G,"f").path.extname(o))o=g(this,G,"f").path.dirname(o);let s=g(this,G,"f").findUp(o,(r,i)=>{if(i.includes("package.json"))return"package.json";else return});$e(s,void 0,g(this,G,"f")),n=JSON.parse(g(this,G,"f").readFileSync(s,"utf8"))}catch(o){}return g(this,rn,"f")[t]=n||{},g(this,rn,"f")[t]}[bt](e,t){t=[].concat(t),t.forEach((n)=>{n=this[Yo](n),g(this,K,"f")[e].push(n)})}[an](e,t,n,o){this[Xo](e,t,n,o,(s,r,i)=>{g(this,K,"f")[s][r]=i})}[Go](e,t,n,o){this[Xo](e,t,n,o,(s,r,i)=>{g(this,K,"f")[s][r]=(g(this,K,"f")[s][r]||[]).concat(i)})}[Xo](e,t,n,o,s){if(Array.isArray(n))n.forEach((r)=>{e(r,o)});else if(((r)=>typeof r==="object")(n))for(let r of sn(n))e(r,n[r]);else s(t,this[Yo](n),o)}[Yo](e){if(e==="__proto__")return"___proto___";return e}[Vo](e,t){return this[an](this[Vo].bind(this),"key",e,t),this}[Zo](){var e,t,n,o,s,r,i,c,a,l,u,d;let f=g(this,bs,"f").pop();$e(f,void 0,g(this,G,"f"));let h;e=this,t=this,n=this,o=this,s=this,r=this,i=this,c=this,a=this,l=this,u=this,d=this,{options:{set value(m){j(e,K,m,"f")}}.value,configObjects:h,exitProcess:{set value(m){j(t,Ue,m,"f")}}.value,groups:{set value(m){j(n,ot,m,"f")}}.value,output:{set value(m){j(o,ke,m,"f")}}.value,exitError:{set value(m){j(s,yt,m,"f")}}.value,hasOutput:{set value(m){j(r,Ne,m,"f")}}.value,parsed:this.parsed,strict:{set value(m){j(i,Lt,m,"f")}}.value,strictCommands:{set value(m){j(c,jt,m,"f")}}.value,strictOptions:{set value(m){j(a,Wt,m,"f")}}.value,completionCommand:{set value(m){j(l,Re,m,"f")}}.value,parseFn:{set value(m){j(u,Be,m,"f")}}.value,parseContext:{set value(m){j(d,Mt,m,"f")}}.value}=f,g(this,K,"f").configObjects=h,g(this,V,"f").unfreeze(),g(this,le,"f").unfreeze(),g(this,pe,"f").unfreeze(),g(this,Je,"f").unfreeze()}[nc](e,t){return Pt(t,(n)=>(e(n),n))}getInternalMethods(){return{getCommandInstance:this[sc].bind(this),getContext:this[oc].bind(this),getHasOutput:this[rc].bind(this),getLoggerInstance:this[ic].bind(this),getParseContext:this[ac].bind(this),getParserConfiguration:this[Ut].bind(this),getUsageConfiguration:this[Qa].bind(this),getUsageInstance:this[cc].bind(this),getValidationInstance:this[lc].bind(this),hasParseCallback:this[_s].bind(this),isGlobalContext:this[uc].bind(this),postProcess:this[Jt].bind(this),reset:this[Qo].bind(this),runValidation:this[er].bind(this),runYargsParserAndExecuteCommands:this[An].bind(this),setHasOutput:this[fc].bind(this)}}[sc](){return g(this,pe,"f")}[oc](){return g(this,$n,"f")}[rc](){return g(this,Ne,"f")}[ic](){return g(this,Bt,"f")}[ac](){return g(this,Mt,"f")||{}}[cc](){return g(this,V,"f")}[lc](){return g(this,le,"f")}[_s](){return!!g(this,Be,"f")}[uc](){return g(this,ks,"f")}[Jt](e,t,n,o){if(n)return e;if(re(e))return e;if(!t)e=this[Ga](e);if(this[Ut]()["parse-positional-numbers"]||this[Ut]()["parse-positional-numbers"]===void 0)e=this[tc](e);if(o)e=Ot(e,this,g(this,Je,"f").getMiddleware(),!1);return e}[Qo](e={}){j(this,K,g(this,K,"f")||{},"f");let t={};t.local=g(this,K,"f").local||[],t.configObjects=g(this,K,"f").configObjects||[];let n={};t.local.forEach((r)=>{n[r]=!0,(e[r]||[]).forEach((i)=>{n[i]=!0})}),Object.assign(g(this,vt,"f"),Object.keys(g(this,ot,"f")).reduce((r,i)=>{let c=g(this,ot,"f")[i].filter((a)=>!(a in n));if(c.length>0)r[i]=c;return r},{})),j(this,ot,{},"f");let o=["array","boolean","string","skipValidation","count","normalize","number","hiddenOptions"],s=["narg","key","alias","default","defaultDescription","config","choices","demandedOptions","demandedCommands","deprecatedOptions"];if(o.forEach((r)=>{t[r]=(g(this,K,"f")[r]||[]).filter((i)=>!n[i])}),s.forEach((r)=>{t[r]=mt(g(this,K,"f")[r],(i)=>!n[i])}),t.envPrefix=g(this,K,"f").envPrefix,j(this,K,t,"f"),j(this,V,g(this,V,"f")?g(this,V,"f").reset(n):La(this,g(this,G,"f")),"f"),j(this,le,g(this,le,"f")?g(this,le,"f").reset(n):za(this,g(this,V,"f"),g(this,G,"f")),"f"),j(this,pe,g(this,pe,"f")?g(this,pe,"f").reset():Ba(g(this,V,"f"),g(this,le,"f"),g(this,Je,"f"),g(this,G,"f")),"f"),!g(this,Ae,"f"))j(this,Ae,Ja(this,g(this,V,"f"),g(this,pe,"f"),g(this,G,"f")),"f");return g(this,Je,"f").reset(),j(this,Re,null,"f"),j(this,ke,"","f"),j(this,yt,null,"f"),j(this,Ne,!1,"f"),this.parsed=!1,this}[dc](e,t){return g(this,G,"f").path.relative(e,t)}[An](e,t,n,o=0,s=!1){var r,i,c,a;let l=!!n||s;e=e||g(this,wt,"f"),g(this,K,"f").__=g(this,G,"f").y18n.__,g(this,K,"f").configuration=this[Ut]();let u=!!g(this,K,"f").configuration["populate--"],d=Object.assign({},g(this,K,"f").configuration,{"populate--":!0}),f=g(this,G,"f").Parser.detailed(e,Object.assign({},g(this,K,"f"),{configuration:{"parse-positional-numbers":!1,...d}})),h=Object.assign(f.argv,g(this,Mt,"f")),m=void 0,p=f.aliases,D=!1,k=!1;if(Object.keys(h).forEach((x)=>{if(x===g(this,Ke,"f")&&h[x])D=!0;else if(x===g(this,rt,"f")&&h[x])k=!0}),h.$0=this.$0,this.parsed=f,o===0)g(this,V,"f").clearCachedHelpMessage();try{if(this[zo](),t)return this[Jt](h,u,!!n,!1);if(g(this,Ke,"f")){if([g(this,Ke,"f")].concat(p[g(this,Ke,"f")]||[]).filter((W)=>W.length>1).includes(""+h._[h._.length-1]))h._.pop(),D=!0}j(this,ks,!1,"f");let x=g(this,pe,"f").getCommands(),E=((r=g(this,Ae,"f"))===null||r===void 0?void 0:r.completionKey)?[(i=g(this,Ae,"f"))===null||i===void 0?void 0:i.completionKey,...(a=this.getAliases()[(c=g(this,Ae,"f"))===null||c===void 0?void 0:c.completionKey])!==null&&a!==void 0?a:[]].some((N)=>Object.prototype.hasOwnProperty.call(h,N)):!1,F=D||E||s;if(h._.length){if(x.length){let N;for(let W=o||0,O;h._[W]!==void 0;W++)if(O=String(h._[W]),x.includes(O)&&O!==g(this,Re,"f")){let v=g(this,pe,"f").runCommand(O,this,f,W+1,s,D||k||s);return this[Jt](v,u,!!n,!1)}else if(!N&&O!==g(this,Re,"f")){N=O;break}if(!g(this,pe,"f").hasDefaultCommand()&&g(this,Es,"f")&&N&&!F)g(this,le,"f").recommendCommands(N,x)}if(g(this,Re,"f")&&h._.includes(g(this,Re,"f"))&&!E){if(g(this,Ue,"f"))Dt(!0);this.showCompletionScript(),this.exit(0)}}if(g(this,pe,"f").hasDefaultCommand()&&!F){let N=g(this,pe,"f").runCommand(null,this,f,0,s,D||k||s);return this[Jt](N,u,!!n,!1)}if(E){if(g(this,Ue,"f"))Dt(!0);e=[].concat(e);let N=e.slice(e.indexOf(`--${g(this,Ae,"f").completionKey}`)+1);return g(this,Ae,"f").getCompletion(N,(W,O)=>{if(W)throw new fe(W.message);(O||[]).forEach((v)=>{g(this,Bt,"f").log(v)}),this.exit(0)}),this[Jt](h,!u,!!n,!1)}if(!g(this,Ne,"f")){if(D){if(g(this,Ue,"f"))Dt(!0);l=!0,this.showHelp((N)=>{g(this,Bt,"f").log(N),this.exit(0)})}else if(k){if(g(this,Ue,"f"))Dt(!0);l=!0,g(this,V,"f").showVersion("log"),this.exit(0)}}if(!l&&g(this,K,"f").skipValidation.length>0)l=Object.keys(h).some((N)=>g(this,K,"f").skipValidation.indexOf(N)>=0&&h[N]===!0);if(!l){if(f.error)throw new fe(f.error.message);if(!E){let N=this[er](p,{},f.error);if(!n)m=Ot(h,this,g(this,Je,"f").getMiddleware(),!0);if(m=this[nc](N,m!==null&&m!==void 0?m:h),re(m)&&!n)m=m.then(()=>Ot(h,this,g(this,Je,"f").getMiddleware(),!1))}}}catch(x){if(x instanceof fe)g(this,V,"f").fail(x.message,x);else throw x}return this[Jt](m!==null&&m!==void 0?m:h,u,!!n,!0)}[er](e,t,n,o){let s={...this.getDemandedOptions()};return(r)=>{if(n)throw new fe(n.message);g(this,le,"f").nonOptionCount(r),g(this,le,"f").requiredArguments(r,s);let i=!1;if(g(this,jt,"f"))i=g(this,le,"f").unknownCommands(r);if(g(this,Lt,"f")&&!i)g(this,le,"f").unknownArguments(r,e,t,!!o);else if(g(this,Wt,"f"))g(this,le,"f").unknownArguments(r,e,{},!1,!1);g(this,le,"f").limitedChoices(r),g(this,le,"f").implications(r),g(this,le,"f").conflicting(r)}}[fc](){j(this,Ne,!0,"f")}[Kt](e){if(typeof e==="string")g(this,K,"f").key[e]=!0;else for(let t of e)g(this,K,"f").key[t]=!0}}function Ma(e){return!!e&&typeof e.getInternalMethods==="function"}var Yf=pc(jo),gc=Yf;function Vf(e){return[...e.matchAll(/<https?:\/\/[^\s<>|]+(?:\|[^<>\r\n]*)?>|https?:\/\/[^\t\n\v\f\r <]+/gi)].map(([n])=>n).filter((n)=>!n.startsWith("<")&&(/[^\x00-\x7f]/.test(n)||n.includes(">")))}function kt(e,t=!1,n=console.error){let o=Vf(e);if(!o.length)return;let s=`Ambiguous URL boundary: ${o.map((r)=>JSON.stringify(r)).join(", ")}. Put the URL on its own line, or wrap it as <url> / <url|label>. Use --allow-url-adjacent to warn only.`;if(!t)throw Error(s);n(`Warning: ${s}`)}import{existsSync as In,readFileSync as sr,writeFileSync as tr,mkdirSync as wc,chmodSync as mc}from"node:fs";import{homedir as Zf}from"node:os";import{join as Ht,dirname as or}from"node:path";function rr(){return process.env.HOME||Zf()}function bc(){return Ht(rr(),".config","slack-cli","profiles.json")}function Fs(){return Ht(process.cwd(),".slack-cli","workspace")}function $s(){return Ht(rr(),".slack-cli","workspace")}function On(){let e=bc();if(!In(e))return{profiles:{}};return JSON.parse(sr(e,"utf8"))}function Qf(e){let t=bc();if(wc(or(t),{recursive:!0}),process.platform!=="win32"&&In(t))mc(t,384);if(tr(t,JSON.stringify(e,null,2)+`
82
- `,{mode:384}),process.platform!=="win32")mc(t,384)}function cn(e){if(!In(e))return;return sr(e,"utf8").trim()||void 0}function Dc(e,t){let n=or(e);wc(n,{recursive:!0});let o=Ht(n,".gitignore");if(!In(o))tr(o,`*
83
- `);tr(e,t+`
84
- `)}function ep(e){let t={};for(let n of e.split(`
85
- `)){let o=n.trim();if(!o||o.startsWith("#"))continue;let s=o.indexOf("=");if(s===-1)continue;let r=o.slice(0,s).trim(),i=o.slice(s+1).trim();if(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))i=i.slice(1,-1);t[r]=i}return t}function yc(e){if(!In(e))return{};try{return ep(sr(e,"utf8"))}catch{return{}}}function nr(e,t){let n=rr(),o=e;while(!0){for(let i of[Ht(o,".slack-term",".env.local"),Ht(o,".env.local")]){let c=yc(i);for(let a of t)if(c[a])return c[a]}if(o===n)break;let r=or(o);if(r===o)break;o=r}let s=yc(Ht(n,".slack-term",".env.local"));for(let r of t)if(s[r])return s[r];return}function ir(){let e=On(),t=cn(Fs()),n=cn($s()),o=t??n;return Object.entries(e.profiles).map(([s,r])=>{let i=Tn(e,s);return{name:s,profile:{...r,...i?{cookie:i}:{}},current:s===o}})}function Tn(e,t){if(!t)return;let n=e.profiles[t];if(!n)return;if(n.cookie)return n.cookie;if(n.identity)return e.users?.[n.identity]?.cookie;return}function kc(e){let t=On();if(!(e in t.profiles))throw Error(`Profile not found: ${e}`);delete t.profiles[e],Qf(t)}function xc(e,t=!1){let n=On();if(!(e in n.profiles))throw Error(`Profile not found: ${e}`);if(t)Dc($s(),e);else Dc(Fs(),e)}function Pn(e){let n=On().profiles,o=Object.keys(n);if(e){let u=n[e];if(!u)throw Error(`Workspace "${e}" not found. Available: ${o.join(", ")||"(none)"}`);return u.token}if(process.env.SLACK_TOKEN)return process.env.SLACK_TOKEN;let s=process.env.SLACK_BOT_TOKEN??process.env.SLACK_MCP_XOXP_TOKEN;if(s&&o.length===0)return s;let r=[process.env.SLACK_BOT_TOKEN,process.env.SLACK_MCP_XOXP_TOKEN].find((u)=>u&&!u.startsWith("xoxb-"));if(r&&o.length>0){let u=nr(process.cwd(),["SLACK_BOT_TOKEN","SLACK_MCP_XOXP_TOKEN"]);if(r!==u){if(!globalThis.__slackEnvWarnShown)globalThis.__slackEnvWarnShown=!0,console.error(`Warning: SLACK_MCP_XOXP_TOKEN / SLACK_BOT_TOKEN is set but workspace profiles exist — using profiles.
86
- `+" Migrate to SLACK_TOKEN=... or remove from your shell config.")}}let i=nr(process.cwd(),["SLACK_TOKEN"]);if(i)return i;let c=process.env.SLACK_WORKSPACE;if(c){let u=n[c];if(!u)throw Error(`Workspace "${c}" not found. Available: ${o.join(", ")||"(none)"}`);return u.token}let a=cn(Fs());if(a){let u=n[a];if(!u)throw Error(`Workspace "${a}" (from .slack-cli/workspace) not found in profiles.`);return u.token}let l=cn($s());if(l){let u=n[l];if(!u)throw Error(`Workspace "${l}" (from ~/.slack-cli/workspace) not found in profiles.`);return u.token}if(o.length>0)throw Error(`Workspace not selected (${o.join(", ")} available).
76
+ `)}`:"";t.fail(s("Missing required argument: %s","Missing required arguments: %s",Object.keys(h).length,Object.keys(h).join(", ")+p))}},r.unknownArguments=function(d,f,h,m,p=!0){var D;let k=e.getInternalMethods().getCommandInstance().getCommands(),x=[],C=e.getInternalMethods().getContext();if(Object.keys(d).forEach((F)=>{if(!Xa.includes(F)&&!Object.prototype.hasOwnProperty.call(h,F)&&!Object.prototype.hasOwnProperty.call(e.getInternalMethods().getParseContext(),F)&&!r.isValidAndSomeAliasIsNotNew(F,f))x.push(F)}),p&&(C.commands.length>0||k.length>0||m))d._.slice(C.commands.length).forEach((F)=>{if(!k.includes(""+F))x.push(""+F)});if(p){let N=((D=e.getDemandedCommands()._)===null||D===void 0?void 0:D.max)||0,W=C.commands.length+N;if(W<d._.length)d._.slice(W).forEach((O)=>{if(O=String(O),!C.commands.includes(O)&&!x.includes(O))x.push(O)})}if(x.length)t.fail(s("Unknown argument: %s","Unknown arguments: %s",x.length,x.map((F)=>F.trim()?F:`"${F}"`).join(", ")))},r.unknownCommands=function(d){let f=e.getInternalMethods().getCommandInstance().getCommands(),h=[],m=e.getInternalMethods().getContext();if(m.commands.length>0||f.length>0)d._.slice(m.commands.length).forEach((p)=>{if(!f.includes(""+p))h.push(""+p)});if(h.length>0)return t.fail(s("Unknown command: %s","Unknown commands: %s",h.length,h.join(", "))),!0;else return!1},r.isValidAndSomeAliasIsNotNew=function(d,f){if(!Object.prototype.hasOwnProperty.call(f,d))return!1;let h=e.parsed.newAliases;return[d,...f[d]].some((m)=>!Object.prototype.hasOwnProperty.call(h,m)||!h[d])},r.limitedChoices=function(d){let f=e.getOptions(),h={};if(!Object.keys(f.choices).length)return;Object.keys(d).forEach((D)=>{if(Xa.indexOf(D)===-1&&Object.prototype.hasOwnProperty.call(f.choices,D))[].concat(d[D]).forEach((k)=>{if(f.choices[D].indexOf(k)===-1&&k!==void 0)h[D]=(h[D]||[]).concat(k)})});let m=Object.keys(h);if(!m.length)return;let p=o("Invalid values:");m.forEach((D)=>{p+=`
77
+ ${o("Argument: %s, Given: %s, Choices: %s",D,t.stringifiedValues(h[D]),t.stringifiedValues(f.choices[D]))}`}),t.fail(p)};let i={};r.implies=function(d,f){if(M("<string|object> [array|number|string]",[d,f],arguments.length),typeof d==="object")Object.keys(d).forEach((h)=>{r.implies(h,d[h])});else{if(e.global(d),!i[d])i[d]=[];if(Array.isArray(f))f.forEach((h)=>r.implies(d,h));else $e(f,void 0,n),i[d].push(f)}},r.getImplied=function(){return i};function c(u,d){let f=Number(d);if(d=isNaN(f)?d:f,typeof d==="number")d=u._.length>=d;else if(d.match(/^--no-.+/))d=d.match(/^--no-(.+)/)[1],d=!Object.prototype.hasOwnProperty.call(u,d);else d=Object.prototype.hasOwnProperty.call(u,d);return d}r.implications=function(d){let f=[];if(Object.keys(i).forEach((h)=>{let m=h;(i[h]||[]).forEach((p)=>{let D=m,k=p;if(D=c(d,D),p=c(d,p),D&&!p)f.push(` ${m} -> ${k}`)})}),f.length){let h=`${o("Implications failed:")}
78
+ `;f.forEach((m)=>{h+=m}),t.fail(h)}};let a={};r.conflicts=function(d,f){if(M("<string|object> [array|string]",[d,f],arguments.length),typeof d==="object")Object.keys(d).forEach((h)=>{r.conflicts(h,d[h])});else{if(e.global(d),!a[d])a[d]=[];if(Array.isArray(f))f.forEach((h)=>r.conflicts(d,h));else a[d].push(f)}},r.getConflicting=()=>a,r.conflicting=function(d){if(Object.keys(d).forEach((f)=>{if(a[f])a[f].forEach((h)=>{if(h&&d[f]!==void 0&&d[h]!==void 0)t.fail(o("Arguments %s and %s are mutually exclusive",f,h))})}),e.getInternalMethods().getParserConfiguration()["strip-dashed"])Object.keys(a).forEach((f)=>{a[f].forEach((h)=>{if(h&&d[n.Parser.camelCase(f)]!==void 0&&d[n.Parser.camelCase(h)]!==void 0)t.fail(o("Arguments %s and %s are mutually exclusive",f,h))})})},r.recommendCommands=function(d,f){f=f.sort((D,k)=>k.length-D.length);let m=null,p=1/0;for(let D=0,k;(k=f[D])!==void 0;D++){let x=Ga(d,k);if(x<=3&&x<p)p=x,m=k}if(m)t.fail(o("Did you mean %s?",m))},r.reset=function(d){return i=Dt(i,(f)=>!d[f]),a=Dt(a,(f)=>!d[f]),r};let l=[];return r.freeze=function(){l.push({implied:i,conflicting:a})},r.unfreeze=function(){let d=l.pop();$e(d,void 0,n),{implied:i,conflicting:a}=d},r}var Go=[],Fn;function $n(e,t,n,o){Fn=o;let s={};if(Object.prototype.hasOwnProperty.call(e,"extends")){if(typeof e.extends!=="string")return s;let r=/\.json|\..*rc$/.test(e.extends),i=null;if(!r)try{i=import.meta.resolve(e.extends)}catch(c){return e}else i=ip(t,e.extends);rp(i),Go.push(i),s=r?JSON.parse(Fn.readFileSync(i,"utf8")):o.require(e.extends),delete e.extends,s=$n(s,Fn.path.dirname(i),n,Fn)}return Go=[],n?Va(s,e):Object.assign({},s,e)}function rp(e){if(Go.indexOf(e)>-1)throw new pe(`Circular extended configurations: '${e}'.`)}function ip(e,t){return Fn.path.resolve(e,t)}function Va(e,t){let n={};function o(s){return s&&typeof s==="object"&&!Array.isArray(s)}Object.assign(n,e);for(let s of Object.keys(t))if(o(t[s])&&o(n[s]))n[s]=Va(e[s],t[s]);else n[s]=t[s];return n}var j=function(e,t,n,o,s){if(o==="m")throw TypeError("Private method is not writable");if(o==="a"&&!s)throw TypeError("Private accessor was defined without a setter");if(typeof t==="function"?e!==t||!s:!t.has(e))throw TypeError("Cannot write private member to an object whose class did not declare it");return o==="a"?s.call(e,n):s?s.value=n:t.set(e,n),n},g=function(e,t,n,o){if(n==="a"&&!o)throw TypeError("Private accessor was defined without a getter");if(typeof t==="function"?e!==t||!o:!t.has(e))throw TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?o:n==="a"?o.call(e):o?o.value:t.get(e)},he,Nt,An,Te,Re,ws,wt,Bt,bs,Ke,ks,He,it,Ne,ze,xs,vt,xe,K,Es,Cs,Be,Lt,an,Mt,bt,Ss,G,jt,Wt,Ut,V,_s,at,le;function Dc(e){return(t=[],n=e.process.cwd(),o)=>{let s=new yc(t,n,o,e);return Object.defineProperty(s,"argv",{get:()=>s.parse(),enumerable:!0}),s.help(),s.version(),s}}var Za=Symbol("copyDoubleDash"),Qa=Symbol("copyDoubleDash"),Xo=Symbol("deleteFromParserHintObject"),ec=Symbol("emitWarning"),tc=Symbol("freeze"),nc=Symbol("getDollarZero"),Jt=Symbol("getParserConfiguration"),sc=Symbol("getUsageConfiguration"),Yo=Symbol("guessLocale"),oc=Symbol("guessVersion"),rc=Symbol("parsePositionalNumbers"),Vo=Symbol("pkgUp"),kt=Symbol("populateParserHintArray"),cn=Symbol("populateParserHintSingleValueDictionary"),Zo=Symbol("populateParserHintArrayDictionary"),Qo=Symbol("populateParserHintDictionary"),er=Symbol("sanitizeKey"),tr=Symbol("setKey"),nr=Symbol("unfreeze"),ic=Symbol("validateAsync"),ac=Symbol("getCommandInstance"),cc=Symbol("getContext"),lc=Symbol("getHasOutput"),uc=Symbol("getLoggerInstance"),dc=Symbol("getParseContext"),fc=Symbol("getUsageInstance"),pc=Symbol("getValidationInstance"),Fs=Symbol("hasParseCallback"),hc=Symbol("isGlobalContext"),Kt=Symbol("postProcess"),gc=Symbol("rebase"),sr=Symbol("reset"),Tn=Symbol("runYargsParserAndExecuteCommands"),or=Symbol("runValidation"),mc=Symbol("setHasOutput"),Ht=Symbol("kTrackManuallySetKeys"),ap="en_US";class yc{constructor(e=[],t,n,o){this.customScriptName=!1,this.parsed=!1,he.set(this,void 0),Nt.set(this,void 0),An.set(this,{commands:[],fullCommands:[]}),Te.set(this,null),Re.set(this,null),ws.set(this,"show-hidden"),wt.set(this,null),Bt.set(this,!0),bs.set(this,{}),Ke.set(this,!0),ks.set(this,[]),He.set(this,void 0),it.set(this,{}),Ne.set(this,!1),ze.set(this,null),xs.set(this,!0),vt.set(this,void 0),xe.set(this,""),K.set(this,void 0),Es.set(this,void 0),Cs.set(this,{}),Be.set(this,null),Lt.set(this,null),an.set(this,{}),Mt.set(this,{}),bt.set(this,void 0),Ss.set(this,!1),G.set(this,void 0),jt.set(this,!1),Wt.set(this,!1),Ut.set(this,!1),V.set(this,void 0),_s.set(this,{}),at.set(this,null),le.set(this,void 0),j(this,G,o,"f"),j(this,bt,e,"f"),j(this,Nt,t,"f"),j(this,Es,n,"f"),j(this,He,new zo(this),"f"),this.$0=this[nc](),this[sr](),j(this,he,g(this,he,"f"),"f"),j(this,V,g(this,V,"f"),"f"),j(this,le,g(this,le,"f"),"f"),j(this,K,g(this,K,"f"),"f"),g(this,K,"f").showHiddenOpt=g(this,ws,"f"),j(this,vt,this[Qa](),"f"),g(this,G,"f").y18n.setLocale(ap)}addHelpOpt(e,t){if(M("[string|boolean] [string]",[e,t],arguments.length),g(this,ze,"f"))this[Xo](g(this,ze,"f")),j(this,ze,null,"f");if(e===!1&&t===void 0)return this;return j(this,ze,typeof e==="string"?e:"help","f"),this.boolean(g(this,ze,"f")),this.describe(g(this,ze,"f"),t||g(this,V,"f").deferY18nLookup("Show help")),this}help(e,t){return this.addHelpOpt(e,t)}addShowHiddenOpt(e,t){if(M("[string|boolean] [string]",[e,t],arguments.length),e===!1&&t===void 0)return this;let n=typeof e==="string"?e:g(this,ws,"f");return this.boolean(n),this.describe(n,t||g(this,V,"f").deferY18nLookup("Show hidden options")),g(this,K,"f").showHiddenOpt=n,this}showHidden(e,t){return this.addShowHiddenOpt(e,t)}alias(e,t){return M("<object|string|array> [string|array]",[e,t],arguments.length),this[Zo](this.alias.bind(this),"alias",e,t),this}array(e){return M("<array|string>",[e],arguments.length),this[kt]("array",e),this[Ht](e),this}boolean(e){return M("<array|string>",[e],arguments.length),this[kt]("boolean",e),this[Ht](e),this}check(e,t){return M("<function> [boolean]",[e,t],arguments.length),this.middleware((n,o)=>Rt(()=>e(n,o.getOptions()),(s)=>{if(!s)g(this,V,"f").fail(g(this,G,"f").y18n.__("Argument check failed: %s",e.toString()));else if(typeof s==="string"||s instanceof Error)g(this,V,"f").fail(s.toString(),s);return n},(s)=>(g(this,V,"f").fail(s.message?s.message:s.toString(),s),n)),!1,t),this}choices(e,t){return M("<object|string|array> [string|array]",[e,t],arguments.length),this[Zo](this.choices.bind(this),"choices",e,t),this}coerce(e,t){if(M("<object|string|array> [function]",[e,t],arguments.length),Array.isArray(e)){if(!t)throw new pe("coerce callback must be provided");for(let o of e)this.coerce(o,t);return this}else if(typeof e==="object"){for(let o of Object.keys(e))this.coerce(o,e[o]);return this}if(!t)throw new pe("coerce callback must be provided");let n=e;return g(this,K,"f").key[n]=!0,g(this,He,"f").addCoerceMiddleware((o,s)=>{var r;let i=(r=s.getAliases()[n])!==null&&r!==void 0?r:[],c=[n,...i].filter((a)=>Object.prototype.hasOwnProperty.call(o,a));if(c.length===0)return o;return Rt(()=>t(o[c[0]]),(a)=>(c.forEach((l)=>{o[l]=a}),o),(a)=>{throw new pe(a.message)})},n),this}conflicts(e,t){return M("<string|object> [string|array]",[e,t],arguments.length),g(this,le,"f").conflicts(e,t),this}config(e="config",t,n){if(M("[object|string] [string|function] [function]",[e,t,n],arguments.length),typeof e==="object"&&!Array.isArray(e))return e=$n(e,g(this,Nt,"f"),this[Jt]()["deep-merge-config"]||!1,g(this,G,"f")),g(this,K,"f").configObjects=(g(this,K,"f").configObjects||[]).concat(e),this;if(typeof t==="function")n=t,t=void 0;return this.describe(e,t||g(this,V,"f").deferY18nLookup("Path to JSON config file")),(Array.isArray(e)?e:[e]).forEach((o)=>{g(this,K,"f").config[o]=n||!0}),this}completion(e,t,n){if(M("[string] [string|boolean|function] [function]",[e,t,n],arguments.length),typeof t==="function")n=t,t=void 0;if(j(this,Re,e||g(this,Re,"f")||"completion","f"),!t&&t!==!1)t="generate completion script";if(this.command(g(this,Re,"f"),t),n)g(this,Te,"f").registerFunction(n);return this}command(e,t,n,o,s,r){return M("<string|array|object> [string|boolean] [function|object] [function] [array] [boolean|string]",[e,t,n,o,s,r],arguments.length),g(this,he,"f").addHandler(e,t,n,o,s,r),this}commands(e,t,n,o,s,r){return this.command(e,t,n,o,s,r)}commandDir(e,t){M("<string> [object]",[e,t],arguments.length);let n=g(this,Es,"f")||g(this,G,"f").require;return g(this,he,"f").addDirectory(e,n,g(this,G,"f").getCallerFile(),t),this}count(e){return M("<array|string>",[e],arguments.length),this[kt]("count",e),this[Ht](e),this}default(e,t,n){if(M("<object|string|array> [*] [string]",[e,t,n],arguments.length),n)Ho(e,g(this,G,"f")),g(this,K,"f").defaultDescription[e]=n;if(typeof t==="function"){if(Ho(e,g(this,G,"f")),!g(this,K,"f").defaultDescription[e])g(this,K,"f").defaultDescription[e]=g(this,V,"f").functionDescription(t);t=t.call()}return this[cn](this.default.bind(this),"default",e,t),this}defaults(e,t,n){return this.default(e,t,n)}demandCommand(e=1,t,n,o){if(M("[number] [number|string] [string|null|undefined] [string|null|undefined]",[e,t,n,o],arguments.length),typeof t!=="number")n=t,t=1/0;return this.global("_",!1),g(this,K,"f").demandedCommands._={min:e,max:t,minMsg:n,maxMsg:o},this}demand(e,t,n){if(Array.isArray(t))t.forEach((o)=>{$e(n,!0,g(this,G,"f")),this.demandOption(o,n)}),t=1/0;else if(typeof t!=="number")n=t,t=1/0;if(typeof e==="number")$e(n,!0,g(this,G,"f")),this.demandCommand(e,t,n,n);else if(Array.isArray(e))e.forEach((o)=>{$e(n,!0,g(this,G,"f")),this.demandOption(o,n)});else if(typeof n==="string")this.demandOption(e,n);else if(n===!0||typeof n>"u")this.demandOption(e);return this}demandOption(e,t){return M("<object|string|array> [string]",[e,t],arguments.length),this[cn](this.demandOption.bind(this),"demandedOptions",e,t),this}deprecateOption(e,t){return M("<string> [string|boolean]",[e,t],arguments.length),g(this,K,"f").deprecatedOptions[e]=t,this}describe(e,t){return M("<object|string|array> [string]",[e,t],arguments.length),this[tr](e,!0),g(this,V,"f").describe(e,t),this}detectLocale(e){return M("<boolean>",[e],arguments.length),j(this,Bt,e,"f"),this}env(e){if(M("[string|boolean]",[e],arguments.length),e===!1)delete g(this,K,"f").envPrefix;else g(this,K,"f").envPrefix=e||"";return this}epilogue(e){return M("<string>",[e],arguments.length),g(this,V,"f").epilog(e),this}epilog(e){return this.epilogue(e)}example(e,t){if(M("<string|array> [string]",[e,t],arguments.length),Array.isArray(e))e.forEach((n)=>this.example(...n));else g(this,V,"f").example(e,t);return this}exit(e,t){if(j(this,Ne,!0,"f"),j(this,wt,t,"f"),g(this,Ke,"f"))g(this,G,"f").process.exit(e)}exitProcess(e=!0){return M("[boolean]",[e],arguments.length),j(this,Ke,e,"f"),this}fail(e){if(M("<function|boolean>",[e],arguments.length),typeof e==="boolean"&&e!==!1)throw new pe("Invalid first argument. Expected function or boolean 'false'");return g(this,V,"f").failFn(e),this}getAliases(){return this.parsed?this.parsed.aliases:{}}async getCompletion(e,t){if(M("<array> [function]",[e,t],arguments.length),!t)return new Promise((n,o)=>{g(this,Te,"f").getCompletion(e,(s,r)=>{if(s)o(s);else n(r)})});else return g(this,Te,"f").getCompletion(e,t)}getDemandedOptions(){return M([],0),g(this,K,"f").demandedOptions}getDemandedCommands(){return M([],0),g(this,K,"f").demandedCommands}getDeprecatedOptions(){return M([],0),g(this,K,"f").deprecatedOptions}getDetectLocale(){return g(this,Bt,"f")}getExitProcess(){return g(this,Ke,"f")}getGroups(){return Object.assign({},g(this,it,"f"),g(this,Mt,"f"))}getHelp(){if(j(this,Ne,!0,"f"),!g(this,V,"f").hasCachedHelpMessage()){if(!this.parsed){let t=this[Tn](g(this,bt,"f"),void 0,void 0,0,!0);if(re(t))return t.then(()=>g(this,V,"f").help())}let e=g(this,he,"f").runDefaultBuilderOn(this);if(re(e))return e.then(()=>g(this,V,"f").help())}return Promise.resolve(g(this,V,"f").help())}getOptions(){return g(this,K,"f")}getStrict(){return g(this,jt,"f")}getStrictCommands(){return g(this,Wt,"f")}getStrictOptions(){return g(this,Ut,"f")}global(e,t){if(M("<string|array> [boolean]",[e,t],arguments.length),e=[].concat(e),t!==!1)g(this,K,"f").local=g(this,K,"f").local.filter((n)=>e.indexOf(n)===-1);else e.forEach((n)=>{if(!g(this,K,"f").local.includes(n))g(this,K,"f").local.push(n)});return this}group(e,t){M("<string|array> <string>",[e,t],arguments.length);let n=g(this,Mt,"f")[t]||g(this,it,"f")[t];if(g(this,Mt,"f")[t])delete g(this,Mt,"f")[t];let o={};return g(this,it,"f")[t]=(n||[]).concat(e).filter((s)=>{if(o[s])return!1;return o[s]=!0}),this}hide(e){return M("<string>",[e],arguments.length),g(this,K,"f").hiddenOptions.push(e),this}implies(e,t){return M("<string|object> [number|string|array]",[e,t],arguments.length),g(this,le,"f").implies(e,t),this}locale(e){if(M("[string]",[e],arguments.length),e===void 0)return this[Yo](),g(this,G,"f").y18n.getLocale();return j(this,Bt,!1,"f"),g(this,G,"f").y18n.setLocale(e),this}middleware(e,t,n){return g(this,He,"f").addMiddleware(e,!!t,n)}nargs(e,t){return M("<string|object|array> [number]",[e,t],arguments.length),this[cn](this.nargs.bind(this),"narg",e,t),this}normalize(e){return M("<array|string>",[e],arguments.length),this[kt]("normalize",e),this}number(e){return M("<array|string>",[e],arguments.length),this[kt]("number",e),this[Ht](e),this}option(e,t){if(M("<string|object> [object]",[e,t],arguments.length),typeof e==="object")Object.keys(e).forEach((n)=>{this.options(n,e[n])});else{if(typeof t!=="object")t={};if(this[Ht](e),g(this,at,"f")&&(e==="version"||(t===null||t===void 0?void 0:t.alias)==="version"))this[ec](['"version" is a reserved word.',"Please do one of the following:",'- Disable version with `yargs.version(false)` if using "version" as an option',"- Use the built-in `yargs.version` method instead (if applicable)","- Use a different option key","https://yargs.js.org/docs/#api-reference-version"].join(`
79
+ `),void 0,"versionWarning");if(g(this,K,"f").key[e]=!0,t.alias)this.alias(e,t.alias);let n=t.deprecate||t.deprecated;if(n)this.deprecateOption(e,n);let o=t.demand||t.required||t.require;if(o)this.demand(e,o);if(t.demandOption)this.demandOption(e,typeof t.demandOption==="string"?t.demandOption:void 0);if(t.conflicts)this.conflicts(e,t.conflicts);if("default"in t)this.default(e,t.default);if(t.implies!==void 0)this.implies(e,t.implies);if(t.nargs!==void 0)this.nargs(e,t.nargs);if(t.config)this.config(e,t.configParser);if(t.normalize)this.normalize(e);if(t.choices)this.choices(e,t.choices);if(t.coerce)this.coerce(e,t.coerce);if(t.group)this.group(e,t.group);if(t.boolean||t.type==="boolean"){if(this.boolean(e),t.alias)this.boolean(t.alias)}if(t.array||t.type==="array"){if(this.array(e),t.alias)this.array(t.alias)}if(t.number||t.type==="number"){if(this.number(e),t.alias)this.number(t.alias)}if(t.string||t.type==="string"){if(this.string(e),t.alias)this.string(t.alias)}if(t.count||t.type==="count")this.count(e);if(typeof t.global==="boolean")this.global(e,t.global);if(t.defaultDescription)g(this,K,"f").defaultDescription[e]=t.defaultDescription;if(t.skipValidation)this.skipValidation(e);let s=t.describe||t.description||t.desc,r=g(this,V,"f").getDescriptions();if(!Object.prototype.hasOwnProperty.call(r,e)||typeof s==="string")this.describe(e,s);if(t.hidden)this.hide(e);if(t.requiresArg)this.requiresArg(e)}return this}options(e,t){return this.option(e,t)}parse(e,t,n){if(M("[string|array] [function|boolean|object] [function]",[e,t,n],arguments.length),this[tc](),typeof e>"u")e=g(this,bt,"f");if(typeof t==="object")j(this,Lt,t,"f"),t=n;if(typeof t==="function")j(this,Be,t,"f"),t=!1;if(!t)j(this,bt,e,"f");if(g(this,Be,"f"))j(this,Ke,!1,"f");let o=this[Tn](e,!!t),s=this.parsed;if(g(this,Te,"f").setParsed(this.parsed),re(o))return o.then((r)=>{if(g(this,Be,"f"))g(this,Be,"f").call(this,g(this,wt,"f"),r,g(this,xe,"f"));return r}).catch((r)=>{if(g(this,Be,"f"))g(this,Be,"f")(r,this.parsed.argv,g(this,xe,"f"));throw r}).finally(()=>{this[nr](),this.parsed=s});else{if(g(this,Be,"f"))g(this,Be,"f").call(this,g(this,wt,"f"),o,g(this,xe,"f"));this[nr](),this.parsed=s}return o}parseAsync(e,t,n){let o=this.parse(e,t,n);return!re(o)?Promise.resolve(o):o}parseSync(e,t,n){let o=this.parse(e,t,n);if(re(o))throw new pe(".parseSync() must not be used with asynchronous builders, handlers, or middleware");return o}parserConfiguration(e){return M("<object>",[e],arguments.length),j(this,Cs,e,"f"),this}pkgConf(e,t){M("<string> [string]",[e,t],arguments.length);let n=null,o=this[Vo](t||g(this,Nt,"f"));if(o[e]&&typeof o[e]==="object")n=$n(o[e],t||g(this,Nt,"f"),this[Jt]()["deep-merge-config"]||!1,g(this,G,"f")),g(this,K,"f").configObjects=(g(this,K,"f").configObjects||[]).concat(n);return this}positional(e,t){M("<string> <object>",[e,t],arguments.length);let n=["default","defaultDescription","implies","normalize","choices","conflicts","coerce","type","describe","desc","description","alias"];t=Dt(t,(r,i)=>{if(r==="type"&&!["string","number","boolean"].includes(i))return!1;return n.includes(r)});let o=g(this,An,"f").fullCommands[g(this,An,"f").fullCommands.length-1],s=o?g(this,he,"f").cmdToParseOptions(o):{array:[],alias:{},default:{},demand:{}};return on(s).forEach((r)=>{let i=s[r];if(Array.isArray(i)){if(i.indexOf(e)!==-1)t[r]=!0}else if(i[e]&&!(r in t))t[r]=i[e]}),this.group(e,g(this,V,"f").getPositionalGroupName()),this.option(e,t)}recommendCommands(e=!0){return M("[boolean]",[e],arguments.length),j(this,Ss,e,"f"),this}required(e,t,n){return this.demand(e,t,n)}require(e,t,n){return this.demand(e,t,n)}requiresArg(e){if(M("<array|string|object> [number]",[e],arguments.length),typeof e==="string"&&g(this,K,"f").narg[e])return this;else this[cn](this.requiresArg.bind(this),"narg",e,NaN);return this}showCompletionScript(e,t){return M("[string] [string]",[e,t],arguments.length),e=e||this.$0,g(this,vt,"f").log(g(this,Te,"f").generateCompletionScript(e,t||g(this,Re,"f")||"completion")),this}showHelp(e){if(M("[string|function]",[e],arguments.length),j(this,Ne,!0,"f"),!g(this,V,"f").hasCachedHelpMessage()){if(!this.parsed){let n=this[Tn](g(this,bt,"f"),void 0,void 0,0,!0);if(re(n))return n.then(()=>{g(this,V,"f").showHelp(e)}),this}let t=g(this,he,"f").runDefaultBuilderOn(this);if(re(t))return t.then(()=>{g(this,V,"f").showHelp(e)}),this}return g(this,V,"f").showHelp(e),this}scriptName(e){return this.customScriptName=!0,this.$0=e,this}showHelpOnFail(e,t){return M("[boolean|string] [string]",[e,t],arguments.length),g(this,V,"f").showHelpOnFail(e,t),this}showVersion(e){return M("[string|function]",[e],arguments.length),g(this,V,"f").showVersion(e),this}skipValidation(e){return M("<array|string>",[e],arguments.length),this[kt]("skipValidation",e),this}strict(e){return M("[boolean]",[e],arguments.length),j(this,jt,e!==!1,"f"),this}strictCommands(e){return M("[boolean]",[e],arguments.length),j(this,Wt,e!==!1,"f"),this}strictOptions(e){return M("[boolean]",[e],arguments.length),j(this,Ut,e!==!1,"f"),this}string(e){return M("<array|string>",[e],arguments.length),this[kt]("string",e),this[Ht](e),this}terminalWidth(){return M([],0),g(this,G,"f").process.stdColumns}updateLocale(e){return this.updateStrings(e)}updateStrings(e){return M("<object>",[e],arguments.length),j(this,Bt,!1,"f"),g(this,G,"f").y18n.updateLocale(e),this}usage(e,t,n,o){if(M("<string|null|undefined> [string|boolean] [function|object] [function]",[e,t,n,o],arguments.length),t!==void 0)if($e(e,null,g(this,G,"f")),(e||"").match(/^\$0( |$)/))return this.command(e,t,n,o);else throw new pe(".usage() description must start with $0 if being used as alias for .command()");else return g(this,V,"f").usage(e),this}usageConfiguration(e){return M("<object>",[e],arguments.length),j(this,_s,e,"f"),this}version(e,t,n){if(M("[boolean|string] [string] [string]",[e,t,n],arguments.length),g(this,at,"f"))this[Xo](g(this,at,"f")),g(this,V,"f").version(void 0),j(this,at,null,"f");if(arguments.length===0)n=this[oc](),e="version";else if(arguments.length===1){if(e===!1)return this;n=e,e="version"}else if(arguments.length===2)n=t,t=void 0;return j(this,at,typeof e==="string"?e:"version","f"),t=t||g(this,V,"f").deferY18nLookup("Show version number"),g(this,V,"f").version(n||void 0),this.boolean(g(this,at,"f")),this.describe(g(this,at,"f"),t),this}wrap(e){return M("<number|null|undefined>",[e],arguments.length),g(this,V,"f").wrap(e),this}[(he=new WeakMap,Nt=new WeakMap,An=new WeakMap,Te=new WeakMap,Re=new WeakMap,ws=new WeakMap,wt=new WeakMap,Bt=new WeakMap,bs=new WeakMap,Ke=new WeakMap,ks=new WeakMap,He=new WeakMap,it=new WeakMap,Ne=new WeakMap,ze=new WeakMap,xs=new WeakMap,vt=new WeakMap,xe=new WeakMap,K=new WeakMap,Es=new WeakMap,Cs=new WeakMap,Be=new WeakMap,Lt=new WeakMap,an=new WeakMap,Mt=new WeakMap,bt=new WeakMap,Ss=new WeakMap,G=new WeakMap,jt=new WeakMap,Wt=new WeakMap,Ut=new WeakMap,V=new WeakMap,_s=new WeakMap,at=new WeakMap,le=new WeakMap,Za)](e){if(!e._||!e["--"])return e;e._.push.apply(e._,e["--"]);try{delete e["--"]}catch(t){}return e}[Qa](){return{log:(...e)=>{if(!this[Fs]())console.log(...e);if(j(this,Ne,!0,"f"),g(this,xe,"f").length)j(this,xe,g(this,xe,"f")+`
80
+ `,"f");j(this,xe,g(this,xe,"f")+e.join(" "),"f")},error:(...e)=>{if(!this[Fs]())console.error(...e);if(j(this,Ne,!0,"f"),g(this,xe,"f").length)j(this,xe,g(this,xe,"f")+`
81
+ `,"f");j(this,xe,g(this,xe,"f")+e.join(" "),"f")}}}[Xo](e){on(g(this,K,"f")).forEach((t)=>{if(((o)=>o==="configObjects")(t))return;let n=g(this,K,"f")[t];if(Array.isArray(n)){if(n.includes(e))n.splice(n.indexOf(e),1)}else if(typeof n==="object")delete n[e]}),delete g(this,V,"f").getDescriptions()[e]}[ec](e,t,n){if(!g(this,bs,"f")[n])g(this,G,"f").process.emitWarning(e,t),g(this,bs,"f")[n]=!0}[tc](){g(this,ks,"f").push({options:g(this,K,"f"),configObjects:g(this,K,"f").configObjects.slice(0),exitProcess:g(this,Ke,"f"),groups:g(this,it,"f"),strict:g(this,jt,"f"),strictCommands:g(this,Wt,"f"),strictOptions:g(this,Ut,"f"),completionCommand:g(this,Re,"f"),output:g(this,xe,"f"),exitError:g(this,wt,"f"),hasOutput:g(this,Ne,"f"),parsed:this.parsed,parseFn:g(this,Be,"f"),parseContext:g(this,Lt,"f")}),g(this,V,"f").freeze(),g(this,le,"f").freeze(),g(this,he,"f").freeze(),g(this,He,"f").freeze()}[nc](){let e="",t;if(/\b(node|iojs|electron)(\.exe)?$/.test(g(this,G,"f").process.argv()[0]))t=g(this,G,"f").process.argv().slice(1,2);else t=g(this,G,"f").process.argv().slice(0,1);if(e=t.map((n)=>{let o=this[gc](g(this,Nt,"f"),n);return n.match(/^(\/|([a-zA-Z]:)?\\)/)&&o.length<n.length?o:n}).join(" ").trim(),g(this,G,"f").getEnv("_")&&g(this,G,"f").getProcessArgvBin()===g(this,G,"f").getEnv("_"))e=g(this,G,"f").getEnv("_").replace(`${g(this,G,"f").path.dirname(g(this,G,"f").process.execPath())}/`,"");return e}[Jt](){return g(this,Cs,"f")}[sc](){return g(this,_s,"f")}[Yo](){if(!g(this,Bt,"f"))return;let e=g(this,G,"f").getEnv("LC_ALL")||g(this,G,"f").getEnv("LC_MESSAGES")||g(this,G,"f").getEnv("LANG")||g(this,G,"f").getEnv("LANGUAGE")||"en_US";this.locale(e.replace(/[.:].*/,""))}[oc](){return this[Vo]().version||"unknown"}[rc](e){let t=e["--"]?e["--"]:e._;for(let n=0,o;(o=t[n])!==void 0;n++)if(g(this,G,"f").Parser.looksLikeNumber(o)&&Number.isSafeInteger(Math.floor(parseFloat(`${o}`))))t[n]=Number(o);return e}[Vo](e){let t=e||"*";if(g(this,an,"f")[t])return g(this,an,"f")[t];let n={};try{let o=e||g(this,G,"f").mainFilename;if(g(this,G,"f").path.extname(o))o=g(this,G,"f").path.dirname(o);let s=g(this,G,"f").findUp(o,(r,i)=>{if(i.includes("package.json"))return"package.json";else return});$e(s,void 0,g(this,G,"f")),n=JSON.parse(g(this,G,"f").readFileSync(s,"utf8"))}catch(o){}return g(this,an,"f")[t]=n||{},g(this,an,"f")[t]}[kt](e,t){t=[].concat(t),t.forEach((n)=>{n=this[er](n),g(this,K,"f")[e].push(n)})}[cn](e,t,n,o){this[Qo](e,t,n,o,(s,r,i)=>{g(this,K,"f")[s][r]=i})}[Zo](e,t,n,o){this[Qo](e,t,n,o,(s,r,i)=>{g(this,K,"f")[s][r]=(g(this,K,"f")[s][r]||[]).concat(i)})}[Qo](e,t,n,o,s){if(Array.isArray(n))n.forEach((r)=>{e(r,o)});else if(((r)=>typeof r==="object")(n))for(let r of on(n))e(r,n[r]);else s(t,this[er](n),o)}[er](e){if(e==="__proto__")return"___proto___";return e}[tr](e,t){return this[cn](this[tr].bind(this),"key",e,t),this}[nr](){var e,t,n,o,s,r,i,c,a,l,u,d;let f=g(this,ks,"f").pop();$e(f,void 0,g(this,G,"f"));let h;e=this,t=this,n=this,o=this,s=this,r=this,i=this,c=this,a=this,l=this,u=this,d=this,{options:{set value(m){j(e,K,m,"f")}}.value,configObjects:h,exitProcess:{set value(m){j(t,Ke,m,"f")}}.value,groups:{set value(m){j(n,it,m,"f")}}.value,output:{set value(m){j(o,xe,m,"f")}}.value,exitError:{set value(m){j(s,wt,m,"f")}}.value,hasOutput:{set value(m){j(r,Ne,m,"f")}}.value,parsed:this.parsed,strict:{set value(m){j(i,jt,m,"f")}}.value,strictCommands:{set value(m){j(c,Wt,m,"f")}}.value,strictOptions:{set value(m){j(a,Ut,m,"f")}}.value,completionCommand:{set value(m){j(l,Re,m,"f")}}.value,parseFn:{set value(m){j(u,Be,m,"f")}}.value,parseContext:{set value(m){j(d,Lt,m,"f")}}.value}=f,g(this,K,"f").configObjects=h,g(this,V,"f").unfreeze(),g(this,le,"f").unfreeze(),g(this,he,"f").unfreeze(),g(this,He,"f").unfreeze()}[ic](e,t){return Rt(t,(n)=>(e(n),n))}getInternalMethods(){return{getCommandInstance:this[ac].bind(this),getContext:this[cc].bind(this),getHasOutput:this[lc].bind(this),getLoggerInstance:this[uc].bind(this),getParseContext:this[dc].bind(this),getParserConfiguration:this[Jt].bind(this),getUsageConfiguration:this[sc].bind(this),getUsageInstance:this[fc].bind(this),getValidationInstance:this[pc].bind(this),hasParseCallback:this[Fs].bind(this),isGlobalContext:this[hc].bind(this),postProcess:this[Kt].bind(this),reset:this[sr].bind(this),runValidation:this[or].bind(this),runYargsParserAndExecuteCommands:this[Tn].bind(this),setHasOutput:this[mc].bind(this)}}[ac](){return g(this,he,"f")}[cc](){return g(this,An,"f")}[lc](){return g(this,Ne,"f")}[uc](){return g(this,vt,"f")}[dc](){return g(this,Lt,"f")||{}}[fc](){return g(this,V,"f")}[pc](){return g(this,le,"f")}[Fs](){return!!g(this,Be,"f")}[hc](){return g(this,xs,"f")}[Kt](e,t,n,o){if(n)return e;if(re(e))return e;if(!t)e=this[Za](e);if(this[Jt]()["parse-positional-numbers"]||this[Jt]()["parse-positional-numbers"]===void 0)e=this[rc](e);if(o)e=Pt(e,this,g(this,He,"f").getMiddleware(),!1);return e}[sr](e={}){j(this,K,g(this,K,"f")||{},"f");let t={};t.local=g(this,K,"f").local||[],t.configObjects=g(this,K,"f").configObjects||[];let n={};t.local.forEach((r)=>{n[r]=!0,(e[r]||[]).forEach((i)=>{n[i]=!0})}),Object.assign(g(this,Mt,"f"),Object.keys(g(this,it,"f")).reduce((r,i)=>{let c=g(this,it,"f")[i].filter((a)=>!(a in n));if(c.length>0)r[i]=c;return r},{})),j(this,it,{},"f");let o=["array","boolean","string","skipValidation","count","normalize","number","hiddenOptions"],s=["narg","key","alias","default","defaultDescription","config","choices","demandedOptions","demandedCommands","deprecatedOptions"];if(o.forEach((r)=>{t[r]=(g(this,K,"f")[r]||[]).filter((i)=>!n[i])}),s.forEach((r)=>{t[r]=Dt(g(this,K,"f")[r],(i)=>!n[i])}),t.envPrefix=g(this,K,"f").envPrefix,j(this,K,t,"f"),j(this,V,g(this,V,"f")?g(this,V,"f").reset(n):Ja(this,g(this,G,"f")),"f"),j(this,le,g(this,le,"f")?g(this,le,"f").reset(n):Ya(this,g(this,V,"f"),g(this,G,"f")),"f"),j(this,he,g(this,he,"f")?g(this,he,"f").reset():ja(g(this,V,"f"),g(this,le,"f"),g(this,He,"f"),g(this,G,"f")),"f"),!g(this,Te,"f"))j(this,Te,qa(this,g(this,V,"f"),g(this,he,"f"),g(this,G,"f")),"f");return g(this,He,"f").reset(),j(this,Re,null,"f"),j(this,xe,"","f"),j(this,wt,null,"f"),j(this,Ne,!1,"f"),this.parsed=!1,this}[gc](e,t){return g(this,G,"f").path.relative(e,t)}[Tn](e,t,n,o=0,s=!1){var r,i,c,a;let l=!!n||s;e=e||g(this,bt,"f"),g(this,K,"f").__=g(this,G,"f").y18n.__,g(this,K,"f").configuration=this[Jt]();let u=!!g(this,K,"f").configuration["populate--"],d=Object.assign({},g(this,K,"f").configuration,{"populate--":!0}),f=g(this,G,"f").Parser.detailed(e,Object.assign({},g(this,K,"f"),{configuration:{"parse-positional-numbers":!1,...d}})),h=Object.assign(f.argv,g(this,Lt,"f")),m=void 0,p=f.aliases,D=!1,k=!1;if(Object.keys(h).forEach((x)=>{if(x===g(this,ze,"f")&&h[x])D=!0;else if(x===g(this,at,"f")&&h[x])k=!0}),h.$0=this.$0,this.parsed=f,o===0)g(this,V,"f").clearCachedHelpMessage();try{if(this[Yo](),t)return this[Kt](h,u,!!n,!1);if(g(this,ze,"f")){if([g(this,ze,"f")].concat(p[g(this,ze,"f")]||[]).filter((W)=>W.length>1).includes(""+h._[h._.length-1]))h._.pop(),D=!0}j(this,xs,!1,"f");let x=g(this,he,"f").getCommands(),C=((r=g(this,Te,"f"))===null||r===void 0?void 0:r.completionKey)?[(i=g(this,Te,"f"))===null||i===void 0?void 0:i.completionKey,...(a=this.getAliases()[(c=g(this,Te,"f"))===null||c===void 0?void 0:c.completionKey])!==null&&a!==void 0?a:[]].some((N)=>Object.prototype.hasOwnProperty.call(h,N)):!1,F=D||C||s;if(h._.length){if(x.length){let N;for(let W=o||0,O;h._[W]!==void 0;W++)if(O=String(h._[W]),x.includes(O)&&O!==g(this,Re,"f")){let L=g(this,he,"f").runCommand(O,this,f,W+1,s,D||k||s);return this[Kt](L,u,!!n,!1)}else if(!N&&O!==g(this,Re,"f")){N=O;break}if(!g(this,he,"f").hasDefaultCommand()&&g(this,Ss,"f")&&N&&!F)g(this,le,"f").recommendCommands(N,x)}if(g(this,Re,"f")&&h._.includes(g(this,Re,"f"))&&!C){if(g(this,Ke,"f"))yt(!0);this.showCompletionScript(),this.exit(0)}}if(g(this,he,"f").hasDefaultCommand()&&!F){let N=g(this,he,"f").runCommand(null,this,f,0,s,D||k||s);return this[Kt](N,u,!!n,!1)}if(C){if(g(this,Ke,"f"))yt(!0);e=[].concat(e);let N=e.slice(e.indexOf(`--${g(this,Te,"f").completionKey}`)+1);return g(this,Te,"f").getCompletion(N,(W,O)=>{if(W)throw new pe(W.message);(O||[]).forEach((L)=>{g(this,vt,"f").log(L)}),this.exit(0)}),this[Kt](h,!u,!!n,!1)}if(!g(this,Ne,"f")){if(D){if(g(this,Ke,"f"))yt(!0);l=!0,this.showHelp((N)=>{g(this,vt,"f").log(N),this.exit(0)})}else if(k){if(g(this,Ke,"f"))yt(!0);l=!0,g(this,V,"f").showVersion("log"),this.exit(0)}}if(!l&&g(this,K,"f").skipValidation.length>0)l=Object.keys(h).some((N)=>g(this,K,"f").skipValidation.indexOf(N)>=0&&h[N]===!0);if(!l){if(f.error)throw new pe(f.error.message);if(!C){let N=this[or](p,{},f.error);if(!n)m=Pt(h,this,g(this,He,"f").getMiddleware(),!0);if(m=this[ic](N,m!==null&&m!==void 0?m:h),re(m)&&!n)m=m.then(()=>Pt(h,this,g(this,He,"f").getMiddleware(),!1))}}}catch(x){if(x instanceof pe)g(this,V,"f").fail(x.message,x);else throw x}return this[Kt](m!==null&&m!==void 0?m:h,u,!!n,!0)}[or](e,t,n,o){let s={...this.getDemandedOptions()};return(r)=>{if(n)throw new pe(n.message);g(this,le,"f").nonOptionCount(r),g(this,le,"f").requiredArguments(r,s);let i=!1;if(g(this,Wt,"f"))i=g(this,le,"f").unknownCommands(r);if(g(this,jt,"f")&&!i)g(this,le,"f").unknownArguments(r,e,t,!!o);else if(g(this,Ut,"f"))g(this,le,"f").unknownArguments(r,e,{},!1,!1);g(this,le,"f").limitedChoices(r),g(this,le,"f").implications(r),g(this,le,"f").conflicting(r)}}[mc](){j(this,Ne,!0,"f")}[Ht](e){if(typeof e==="string")g(this,K,"f").key[e]=!0;else for(let t of e)g(this,K,"f").key[t]=!0}}function Wa(e){return!!e&&typeof e.getInternalMethods==="function"}var cp=Dc(Ko),wc=cp;var lp=/<https?:\/\/[^\s<>|]+(?:\|[^<>\r\n]*)?>|https?:\/\/[^\t\n\v\f\r <\x00]+/gi,up=/[\t\n\v\f\r (*_~]/;function dp(e){let t=e.split(""),n=(s,r)=>{for(let i=s;i<r;i++)if(t[i]!==`
82
+ `)t[i]="\x00"},o=0;while(o<e.length){let r=o===0||e[o-1]===`
83
+ `?/^ {0,3}(?:(`{3,})[^`\n]*|(~{3,})[^\n]*)(?=\n|$)/.exec(e.slice(o)):null;if(r){let c=r[1]??r[2],a=new RegExp(`
84
+ {0,3}${c[0]==="`"?"`":"~"}{${c.length},}[ ]*\r?(?=
85
+ |$)`,"g");a.lastIndex=o+r[0].length;let l=a.exec(e),u=l?l.index+l[0].length:e.length;n(o,u),o=u;continue}let i=e[o];if(i==="\\"){o+=2;continue}if(i==="`"){let c=0;while(e[o+c]==="`")c++;let a=o+c,l=-1;while(a<e.length){if(e[a]===`
86
+ `&&/^\n[ \t\r]*(?:\n|$)/.test(e.slice(a)))break;if(e[a]!=="`"){a++;continue}let u=0;while(e[a+u]==="`")u++;if(u===c){l=a+u;break}a+=u}if(l<0){o+=c;continue}n(o,l),o=l;continue}if(i==="["){let c=/^\[(?:\\.|[^\]\\\n])*\]\([^()\s]*\)/.exec(e.slice(o));if(c){n(o,o+c[0].length),o+=c[0].length;continue}}o++}return t.join("")}function fp(e,{markdown:t=!0}={}){let n=t?dp(e):e,o=[];for(let s of n.matchAll(lp)){let r=s[0];if(r.startsWith("<"))continue;let i=s.index??0,c=i>0?n[i-1]:"";if(c&&!up.test(c))o.push({url:r,side:"before",char:e[i-1]});let a=r.match(/[^\x00-\x7f]|>/);if(a)o.push({url:r,side:"after",char:a[0]})}return o}function ve(e,t=!1,n=console.error,{sides:o=["before","after"],markdown:s=!0}={}){let r=fp(e,{markdown:s}).filter((l)=>o.includes(l.side));if(!r.length)return;let i=r.map((l)=>l.side==="before"?`${JSON.stringify(l.url)} (glued to ${JSON.stringify(l.char)} before it — Slack will NOT make it a link)`:`${JSON.stringify(l.url)} (runs into ${JSON.stringify(l.char)} after it)`),c=r.some((l)=>l.side==="before")?"Put an ASCII space (or a newline) before the URL, ":"",a=`Ambiguous URL boundary: ${i.join(", ")}. ${c}Put the URL on its own line, or wrap it as <url> / <url|label>. Use --allow-url-adjacent to warn only.`;if(!t)throw Error(a);n(`Warning: ${a}`)}import{existsSync as On,readFileSync as ar,writeFileSync as rr,mkdirSync as Ec,chmodSync as bc}from"node:fs";import{homedir as pp}from"node:os";import{join as zt,dirname as cr}from"node:path";function lr(){return process.env.HOME||pp()}function Cc(){return zt(lr(),".config","slack-cli","profiles.json")}function $s(){return zt(process.cwd(),".slack-cli","workspace")}function As(){return zt(lr(),".slack-cli","workspace")}function Pn(){let e=Cc();if(!On(e))return{profiles:{}};return JSON.parse(ar(e,"utf8"))}function hp(e){let t=Cc();if(Ec(cr(t),{recursive:!0}),process.platform!=="win32"&&On(t))bc(t,384);if(rr(t,JSON.stringify(e,null,2)+`
87
+ `,{mode:384}),process.platform!=="win32")bc(t,384)}function ln(e){if(!On(e))return;return ar(e,"utf8").trim()||void 0}function kc(e,t){let n=cr(e);Ec(n,{recursive:!0});let o=zt(n,".gitignore");if(!On(o))rr(o,`*
88
+ `);rr(e,t+`
89
+ `)}function gp(e){let t={};for(let n of e.split(`
90
+ `)){let o=n.trim();if(!o||o.startsWith("#"))continue;let s=o.indexOf("=");if(s===-1)continue;let r=o.slice(0,s).trim(),i=o.slice(s+1).trim();if(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))i=i.slice(1,-1);t[r]=i}return t}function xc(e){if(!On(e))return{};try{return gp(ar(e,"utf8"))}catch{return{}}}function ir(e,t){let n=lr(),o=e;while(!0){for(let i of[zt(o,".slack-term",".env.local"),zt(o,".env.local")]){let c=xc(i);for(let a of t)if(c[a])return c[a]}if(o===n)break;let r=cr(o);if(r===o)break;o=r}let s=xc(zt(n,".slack-term",".env.local"));for(let r of t)if(s[r])return s[r];return}function ur(){let e=Pn(),t=ln($s()),n=ln(As()),o=t??n;return Object.entries(e.profiles).map(([s,r])=>{let i=In(e,s);return{name:s,profile:{...r,...i?{cookie:i}:{}},current:s===o}})}function In(e,t){if(!t)return;let n=e.profiles[t];if(!n)return;if(n.cookie)return n.cookie;if(n.identity)return e.users?.[n.identity]?.cookie;return}function Sc(e){let t=Pn();if(!(e in t.profiles))throw Error(`Profile not found: ${e}`);delete t.profiles[e],hp(t)}function _c(e,t=!1){let n=Pn();if(!(e in n.profiles))throw Error(`Profile not found: ${e}`);if(t)kc(As(),e);else kc($s(),e)}function Rn(e){let n=Pn().profiles,o=Object.keys(n);if(e){let u=n[e];if(!u)throw Error(`Workspace "${e}" not found. Available: ${o.join(", ")||"(none)"}`);return u.token}if(process.env.SLACK_TOKEN)return process.env.SLACK_TOKEN;let s=process.env.SLACK_BOT_TOKEN??process.env.SLACK_MCP_XOXP_TOKEN;if(s&&o.length===0)return s;let r=[process.env.SLACK_BOT_TOKEN,process.env.SLACK_MCP_XOXP_TOKEN].find((u)=>u&&!u.startsWith("xoxb-"));if(r&&o.length>0){let u=ir(process.cwd(),["SLACK_BOT_TOKEN","SLACK_MCP_XOXP_TOKEN"]);if(r!==u){if(!globalThis.__slackEnvWarnShown)globalThis.__slackEnvWarnShown=!0,console.error(`Warning: SLACK_MCP_XOXP_TOKEN / SLACK_BOT_TOKEN is set but workspace profiles exist — using profiles.
91
+ `+" Migrate to SLACK_TOKEN=... or remove from your shell config.")}}let i=ir(process.cwd(),["SLACK_TOKEN"]);if(i)return i;let c=process.env.SLACK_WORKSPACE;if(c){let u=n[c];if(!u)throw Error(`Workspace "${c}" not found. Available: ${o.join(", ")||"(none)"}`);return u.token}let a=ln($s());if(a){let u=n[a];if(!u)throw Error(`Workspace "${a}" (from .slack-cli/workspace) not found in profiles.`);return u.token}let l=ln(As());if(l){let u=n[l];if(!u)throw Error(`Workspace "${l}" (from ~/.slack-cli/workspace) not found in profiles.`);return u.token}if(o.length>0)throw Error(`Workspace not selected (${o.join(", ")} available).
87
92
  Select locally: slack auth use <name> (writes .slack-cli/workspace)
88
93
  Select globally: slack auth use -g <name> (writes ~/.slack-cli/workspace)`);throw Error(`No Slack token found.
89
94
  Run one of:
@@ -92,13 +97,13 @@ ${m.join(`
92
97
  `+` slack auth cookie — attach the xoxd cookie from Chrome (macOS/Windows)
93
98
  `+` slack auth firefox — attach the xoxd cookie from Firefox (all platforms)
94
99
  `+` slack auth token --token xoxp-... — paste an existing token
95
- `+" Or set SLACK_TOKEN=xoxp-... in .slack-term/.env.local")}function lt(){let e=process.env.SLACK_BOT_TOKEN;return e&&e.startsWith("xoxb-")?e:void 0}function ar(e){let t=On(),n=t.profiles;if(e)return Tn(t,e);if(process.env.SLACK_COOKIE)return process.env.SLACK_COOKIE;if(process.env.SLACK_MCP_XOXD_COOKIE)return process.env.SLACK_MCP_XOXD_COOKIE;if(process.env.SLACK_MCP_XOXP_TOKEN&&Object.keys(n).length===0)return process.env.SLACK_MCP_XOXD_COOKIE;let s=nr(process.cwd(),["SLACK_COOKIE"]);if(s)return s;let r=process.env.SLACK_WORKSPACE;if(r)return Tn(t,r);let i=cn(Fs());if(i)return Tn(t,i);let c=cn($s());if(c)return Tn(t,c);return}import{existsSync as un,readFileSync as Ts,writeFileSync as Ec,mkdirSync as Sc,chmodSync as As}from"node:fs";import{homedir as tp}from"node:os";import{join as ln,dirname as lr}from"node:path";function ur(){return process.env.HOME||tp()}function _c(){return ln(ur(),".config","slack-cli","profiles.json")}function dr(){return ln(process.cwd(),".slack-cli","workspace")}function fr(){return ln(ur(),".slack-cli","workspace")}function fn(){let e=_c();if(!un(e))return{profiles:{}};return JSON.parse(Ts(e,"utf8"))}function pr(e){let t=_c();if(Sc(lr(t),{recursive:!0}),process.platform!=="win32"&&un(t))As(t,384);if(Ec(t,JSON.stringify(e,null,2)+`
96
- `,{mode:384}),process.platform!=="win32")As(t,384)}function dn(e){if(!un(e))return;return Ts(e,"utf8").trim()||void 0}function np(e){let t={};for(let n of e.split(`
97
- `)){let o=n.trim();if(!o||o.startsWith("#"))continue;let s=o.indexOf("=");if(s===-1)continue;let r=o.slice(0,s).trim(),i=o.slice(s+1).trim();if(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))i=i.slice(1,-1);t[r]=i}return t}function Cc(e){if(!un(e))return{};try{return np(Ts(e,"utf8"))}catch{return{}}}function cr(e,t){let n=ur(),o=e;while(!0){for(let i of[ln(o,".slack-term",".env.local"),ln(o,".env.local")]){let c=Cc(i);for(let a of t)if(c[a])return c[a]}if(o===n)break;let r=lr(o);if(r===o)break;o=r}let s=Cc(ln(n,".slack-term",".env.local"));for(let r of t)if(s[r])return s[r];return}function hr(e,t){Sc(lr(e),{recursive:!0});let n=un(e)?Ts(e,"utf8"):"",o=n?n.split(`
98
- `):[];for(let[s,r]of Object.entries(t)){let i=o.findIndex((a)=>{let l=a.trim();return l.startsWith(s+"=")||l.startsWith(s+" =")}),c=`${s}=${r}`;if(i!==-1)o[i]=c;else o.push(c)}if(process.platform!=="win32"&&un(e))As(e,384);if(Ec(e,o.join(`
100
+ `+" Or set SLACK_TOKEN=xoxp-... in .slack-term/.env.local")}function ut(){let e=process.env.SLACK_BOT_TOKEN;return e&&e.startsWith("xoxb-")?e:void 0}function dr(e){let t=Pn(),n=t.profiles;if(e)return In(t,e);if(process.env.SLACK_COOKIE)return process.env.SLACK_COOKIE;if(process.env.SLACK_MCP_XOXD_COOKIE)return process.env.SLACK_MCP_XOXD_COOKIE;if(process.env.SLACK_MCP_XOXP_TOKEN&&Object.keys(n).length===0)return process.env.SLACK_MCP_XOXD_COOKIE;let s=ir(process.cwd(),["SLACK_COOKIE"]);if(s)return s;let r=process.env.SLACK_WORKSPACE;if(r)return In(t,r);let i=ln($s());if(i)return In(t,i);let c=ln(As());if(c)return In(t,c);return}import{existsSync as dn,readFileSync as Is,writeFileSync as $c,mkdirSync as Ac,chmodSync as Ts}from"node:fs";import{homedir as mp}from"node:os";import{join as un,dirname as pr}from"node:path";function hr(){return process.env.HOME||mp()}function Tc(){return un(hr(),".config","slack-cli","profiles.json")}function gr(){return un(process.cwd(),".slack-cli","workspace")}function mr(){return un(hr(),".slack-cli","workspace")}function pn(){let e=Tc();if(!dn(e))return{profiles:{}};return JSON.parse(Is(e,"utf8"))}function Dr(e){let t=Tc();if(Ac(pr(t),{recursive:!0}),process.platform!=="win32"&&dn(t))Ts(t,384);if($c(t,JSON.stringify(e,null,2)+`
101
+ `,{mode:384}),process.platform!=="win32")Ts(t,384)}function fn(e){if(!dn(e))return;return Is(e,"utf8").trim()||void 0}function Dp(e){let t={};for(let n of e.split(`
102
+ `)){let o=n.trim();if(!o||o.startsWith("#"))continue;let s=o.indexOf("=");if(s===-1)continue;let r=o.slice(0,s).trim(),i=o.slice(s+1).trim();if(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))i=i.slice(1,-1);t[r]=i}return t}function Fc(e){if(!dn(e))return{};try{return Dp(Is(e,"utf8"))}catch{return{}}}function fr(e,t){let n=hr(),o=e;while(!0){for(let i of[un(o,".slack-term",".env.local"),un(o,".env.local")]){let c=Fc(i);for(let a of t)if(c[a])return c[a]}if(o===n)break;let r=pr(o);if(r===o)break;o=r}let s=Fc(un(n,".slack-term",".env.local"));for(let r of t)if(s[r])return s[r];return}function yr(e,t){Ac(pr(e),{recursive:!0});let n=dn(e)?Is(e,"utf8"):"",o=n?n.split(`
103
+ `):[];for(let[s,r]of Object.entries(t)){let i=o.findIndex((a)=>{let l=a.trim();return l.startsWith(s+"=")||l.startsWith(s+" =")}),c=`${s}=${r}`;if(i!==-1)o[i]=c;else o.push(c)}if(process.platform!=="win32"&&dn(e))Ts(e,384);if($c(e,o.join(`
99
104
  `).trimEnd()+`
100
- `,{mode:384}),process.platform!=="win32")As(e,384)}function Nn(){let e=fn(),t=dn(dr()),n=dn(fr()),o=t??n;return Object.entries(e.profiles).map(([s,r])=>{let i=Rn(e,s);return{name:s,profile:{...r,...i?{cookie:i}:{}},current:s===o}})}function Is(e,t){let n=fn();if(t.identity&&t.cookie){n.users??={};let o=n.users[t.identity]??{};n.users[t.identity]={...o,cookie:t.cookie};let{cookie:s,...r}=t;n.profiles[e]=r}else n.profiles[e]=t;pr(n)}function gr(e,t){let n=fn(),o=n.profiles[e];if(!o)throw Error(`Profile not found: ${e}`);if(o.identity)n.users??={},n.users[o.identity]={...n.users[o.identity]??{},cookie:t};else o.cookie=t;pr(n)}function Fc(e,t,n){let o=fn();o.users??={},o.users[e]={...o.users[e]??{},cookie:t,...n?{source:n}:{}},pr(o)}function Rn(e,t){if(!t)return;let n=e.profiles[t];if(!n)return;if(n.cookie)return n.cookie;if(n.identity)return e.users?.[n.identity]?.cookie;return}function $c(e){let n=fn().profiles,o=Object.keys(n);if(e){let u=n[e];if(!u)throw Error(`Workspace "${e}" not found. Available: ${o.join(", ")||"(none)"}`);return u.token}if(process.env.SLACK_TOKEN)return process.env.SLACK_TOKEN;let s=process.env.SLACK_BOT_TOKEN??process.env.SLACK_MCP_XOXP_TOKEN;if(s&&o.length===0)return s;let r=[process.env.SLACK_BOT_TOKEN,process.env.SLACK_MCP_XOXP_TOKEN].find((u)=>u&&!u.startsWith("xoxb-"));if(r&&o.length>0){let u=cr(process.cwd(),["SLACK_BOT_TOKEN","SLACK_MCP_XOXP_TOKEN"]);if(r!==u){if(!globalThis.__slackEnvWarnShown)globalThis.__slackEnvWarnShown=!0,console.error(`Warning: SLACK_MCP_XOXP_TOKEN / SLACK_BOT_TOKEN is set but workspace profiles exist — using profiles.
101
- `+" Migrate to SLACK_TOKEN=... or remove from your shell config.")}}let i=cr(process.cwd(),["SLACK_TOKEN"]);if(i)return i;let c=process.env.SLACK_WORKSPACE;if(c){let u=n[c];if(!u)throw Error(`Workspace "${c}" not found. Available: ${o.join(", ")||"(none)"}`);return u.token}let a=dn(dr());if(a){let u=n[a];if(!u)throw Error(`Workspace "${a}" (from .slack-cli/workspace) not found in profiles.`);return u.token}let l=dn(fr());if(l){let u=n[l];if(!u)throw Error(`Workspace "${l}" (from ~/.slack-cli/workspace) not found in profiles.`);return u.token}if(o.length>0)throw Error(`Workspace not selected (${o.join(", ")} available).
105
+ `,{mode:384}),process.platform!=="win32")Ts(e,384)}function Bn(){let e=pn(),t=fn(gr()),n=fn(mr()),o=t??n;return Object.entries(e.profiles).map(([s,r])=>{let i=Nn(e,s);return{name:s,profile:{...r,...i?{cookie:i}:{}},current:s===o}})}function Os(e,t){let n=pn();if(t.identity&&t.cookie){n.users??={};let o=n.users[t.identity]??{};n.users[t.identity]={...o,cookie:t.cookie};let{cookie:s,...r}=t;n.profiles[e]=r}else n.profiles[e]=t;Dr(n)}function wr(e,t){let n=pn(),o=n.profiles[e];if(!o)throw Error(`Profile not found: ${e}`);if(o.identity)n.users??={},n.users[o.identity]={...n.users[o.identity]??{},cookie:t};else o.cookie=t;Dr(n)}function Ic(e,t,n){let o=pn();o.users??={},o.users[e]={...o.users[e]??{},cookie:t,...n?{source:n}:{}},Dr(o)}function Nn(e,t){if(!t)return;let n=e.profiles[t];if(!n)return;if(n.cookie)return n.cookie;if(n.identity)return e.users?.[n.identity]?.cookie;return}function Oc(e){let n=pn().profiles,o=Object.keys(n);if(e){let u=n[e];if(!u)throw Error(`Workspace "${e}" not found. Available: ${o.join(", ")||"(none)"}`);return u.token}if(process.env.SLACK_TOKEN)return process.env.SLACK_TOKEN;let s=process.env.SLACK_BOT_TOKEN??process.env.SLACK_MCP_XOXP_TOKEN;if(s&&o.length===0)return s;let r=[process.env.SLACK_BOT_TOKEN,process.env.SLACK_MCP_XOXP_TOKEN].find((u)=>u&&!u.startsWith("xoxb-"));if(r&&o.length>0){let u=fr(process.cwd(),["SLACK_BOT_TOKEN","SLACK_MCP_XOXP_TOKEN"]);if(r!==u){if(!globalThis.__slackEnvWarnShown)globalThis.__slackEnvWarnShown=!0,console.error(`Warning: SLACK_MCP_XOXP_TOKEN / SLACK_BOT_TOKEN is set but workspace profiles exist — using profiles.
106
+ `+" Migrate to SLACK_TOKEN=... or remove from your shell config.")}}let i=fr(process.cwd(),["SLACK_TOKEN"]);if(i)return i;let c=process.env.SLACK_WORKSPACE;if(c){let u=n[c];if(!u)throw Error(`Workspace "${c}" not found. Available: ${o.join(", ")||"(none)"}`);return u.token}let a=fn(gr());if(a){let u=n[a];if(!u)throw Error(`Workspace "${a}" (from .slack-cli/workspace) not found in profiles.`);return u.token}let l=fn(mr());if(l){let u=n[l];if(!u)throw Error(`Workspace "${l}" (from ~/.slack-cli/workspace) not found in profiles.`);return u.token}if(o.length>0)throw Error(`Workspace not selected (${o.join(", ")} available).
102
107
  Select locally: slack auth use <name> (writes .slack-cli/workspace)
103
108
  Select globally: slack auth use -g <name> (writes ~/.slack-cli/workspace)`);throw Error(`No Slack token found.
104
109
  Run one of:
@@ -107,31 +112,31 @@ ${m.join(`
107
112
  `+` slack auth cookie — attach the xoxd cookie from Chrome (macOS/Windows)
108
113
  `+` slack auth firefox — attach the xoxd cookie from Firefox (all platforms)
109
114
  `+` slack auth token --token xoxp-... — paste an existing token
110
- `+" Or set SLACK_TOKEN=xoxp-... in .slack-term/.env.local")}function Os(){let e=process.env.SLACK_BOT_TOKEN;return e&&e.startsWith("xoxb-")?e:void 0}function xt(e){let t=fn(),n=t.profiles;if(e)return Rn(t,e);if(process.env.SLACK_COOKIE)return process.env.SLACK_COOKIE;if(process.env.SLACK_MCP_XOXD_COOKIE)return process.env.SLACK_MCP_XOXD_COOKIE;if(process.env.SLACK_MCP_XOXP_TOKEN&&Object.keys(n).length===0)return process.env.SLACK_MCP_XOXD_COOKIE;let s=cr(process.cwd(),["SLACK_COOKIE"]);if(s)return s;let r=process.env.SLACK_WORKSPACE;if(r)return Rn(t,r);let i=dn(dr());if(i)return Rn(t,i);let c=dn(fr());if(c)return Rn(t,c);return}class Qe extends Error{retryAfter;constructor(e){super(`Slack rate limited — retry after ${e}s`);this.name="RateLimitError",this.retryAfter=e}}function Dr(){return(process.env.SLACK_API_BASE??"https://slack.com/api").replace(/\/$/,"")}async function yr(e,t,n,o){o=e.startsWith("xoxc-")?o??xt():void 0;let s={};if(o)s.Cookie=`d=${o}`;let r=await fetch(`${Dr()}/${t}`,{...n,headers:{...n.headers??{},Authorization:`Bearer ${e}`,...s}});if(r.status===429){let c=parseInt(r.headers.get("retry-after")??"60",10);throw new Qe(isNaN(c)?60:c)}let i=await r.json();if(i.ok!==!0){let c=i.error??"unknown";if(c==="ratelimited")throw new Qe(60);if(c==="invalid_auth"&&e.startsWith("xoxc-")&&!o)throw Error(`Desktop app token (xoxc-) needs its session cookie to be accepted by the public Slack API.
115
+ `+" Or set SLACK_TOKEN=xoxp-... in .slack-term/.env.local")}function Ps(){let e=process.env.SLACK_BOT_TOKEN;return e&&e.startsWith("xoxb-")?e:void 0}function xt(e){let t=pn(),n=t.profiles;if(e)return Nn(t,e);if(process.env.SLACK_COOKIE)return process.env.SLACK_COOKIE;if(process.env.SLACK_MCP_XOXD_COOKIE)return process.env.SLACK_MCP_XOXD_COOKIE;if(process.env.SLACK_MCP_XOXP_TOKEN&&Object.keys(n).length===0)return process.env.SLACK_MCP_XOXD_COOKIE;let s=fr(process.cwd(),["SLACK_COOKIE"]);if(s)return s;let r=process.env.SLACK_WORKSPACE;if(r)return Nn(t,r);let i=fn(gr());if(i)return Nn(t,i);let c=fn(mr());if(c)return Nn(t,c);return}function Rs(e){let t=[],n=(r)=>{if(!r)return;let i=t[t.length-1];if(i?.type==="text")i.text+=r;else t.push({type:"text",text:r})},o=/<(https?:\/\/[^\s<>|]+)(?:\|([^<>\r\n]*))?>|https?:\/\/[\x21-\x3b\x3d\x3f-\x7e]+/gi,s=0;for(let r of e.matchAll(o)){let i=r.index??0;if(n(e.slice(s,i)),r[1]){t.push(r[2]?{type:"link",url:r[1],text:r[2]}:{type:"link",url:r[1]}),s=i+r[0].length;continue}let c=r[0];while(/[.,:;!?'"*_~]$/.test(c)||c.endsWith(")")&&Pc(c,"(")<Pc(c,")"))c=c.slice(0,-1);t.push({type:"link",url:c}),s=i+c.length}return n(e.slice(s)),t}function Pc(e,t){return e.split(t).length-1}class et extends Error{retryAfter;method;constructor(e,t){super(t?`Slack rate limited on ${t} — retry after ${e}s`:`Slack rate limited — retry after ${e}s`);if(this.name="RateLimitError",this.retryAfter=e,t)this.method=t}}function kr(){return(process.env.SLACK_API_BASE??"https://slack.com/api").replace(/\/$/,"")}async function xr(e,t,n,o){o=e.startsWith("xoxc-")?o??xt():void 0;let s={};if(o)s.Cookie=`d=${o}`;let r=await fetch(`${kr()}/${t}`,{...n,headers:{...n.headers??{},Authorization:`Bearer ${e}`,...s}});if(r.status===429){let c=parseInt(r.headers.get("retry-after")??"60",10);throw new et(isNaN(c)?60:c,t)}let i=await r.json();if(i.ok!==!0){let c=i.error??"unknown";if(c==="ratelimited")throw new et(60,t);if(c==="invalid_auth"&&e.startsWith("xoxc-")&&!o)throw Error(`Desktop app token (xoxc-) needs its session cookie to be accepted by the public Slack API.
111
116
  Attach it: slack auth firefox (Linux/macOS/Windows) or slack auth chrome (macOS/Linux)
112
117
  Or replace the token with an xoxp- user token:
113
118
  slack auth login`);if((c==="missing_scope"||c==="cannot_dm_bot")&&e.startsWith("xoxb-")){if(t.startsWith("agents.sessions."))throw Error(`Slack error on ${t}: ${c}. Agent sessions need a granular bot token with chat:write and app membership in the channel.`);throw Error(`Slack error on ${t}: ${c} — ${c==="cannot_dm_bot"?`you're authenticated as a bot, so "@you" is the bot itself and it can't DM itself`:"this bot token lacks the user scope this action needs"}.
114
119
  Tailing/DMing people and listing users need a user session, not a bot token.
115
120
  Switch workspace: slack auth ls then slack auth use <name>
116
- Or import your Slack desktop session: slack auth login`)}throw Error(`Slack error on ${t}: ${c}`)}return i}async function sp(e,t,n,o){let s={};if(o)s.Cookie=`d=${o}`;let r=await fetch(`${Dr()}/${t}`,{...n,headers:{...n.headers??{},Authorization:`Bearer ${e}`,...s}});if(r.status===429){let c=parseInt(r.headers.get("retry-after")??"60",10);throw new Qe(isNaN(c)?60:c)}let i=await r.json();if(i.ok!==!0){let c=i.error??"unknown";if(c==="ratelimited")throw new Qe(60);if((c==="invalid_auth"||c==="not_authed")&&!e.startsWith("xoxc-"))throw Error(`The draft API requires a desktop app session token (xoxc-).
117
- Import from Slack desktop: slack auth login`);if((c==="invalid_auth"||c==="not_authed")&&!o)throw Error(`drafts.list also requires the xoxd session cookie.
118
- Attach it with: slack auth firefox (Linux/macOS/Windows) or slack auth chrome (macOS/Linux)`);throw Error(`Slack error on ${t}: ${c}`)}return i}function op(e,t,n={},o){let s=new URLSearchParams({token:e,...n});return sp(e,t,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s.toString()},o)}function Ee(e,t,n,o){let s=new URLSearchParams(n).toString();return yr(e,`${t}?${s}`,{method:"GET"},o)}function wr(e,t,n,o){return yr(e,t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)},o)}async function Oc(e,t,n){if(!e.startsWith("xoxb-"))throw Error("Agent sessions require a bot token (xoxb); user tokens are refused.");return yr(e,t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n),signal:AbortSignal.timeout(1e4)})}function Mn(e,t,n){return Oc(e,"agents.sessions.setStatus",{...t,status:n})}function br(e,t,n){return Oc(e,"agents.sessions.rename",{...t,title:n})}async function pn(e,t){let n=await Ee(e,"auth.test",{},t);return{team:n.team??"",teamId:n.team_id??"",url:n.url??"",user:n.user??"",userId:n.user_id??""}}async function Pc(e,t){t=e.startsWith("xoxc-")?t??xt():void 0;let n={Authorization:`Bearer ${e}`};if(t)n.Cookie=`d=${t}`;let o=await fetch(`${Dr()}/auth.test`,{method:"GET",headers:n});if(o.status===429){let i=parseInt(o.headers.get("retry-after")??"60",10);throw new Qe(isNaN(i)?60:i)}let s=o.headers.get("x-oauth-scopes")??"",r=await o.json();if(r.ok!==!0)throw Error(`Slack error on auth.test: ${r.error??"unknown"}`);return{userId:r.user_id??"",user:r.user??"",botId:r.bot_id??"",team:r.team??"",url:r.url??"",scopes:s.split(",").map((i)=>i.trim()).filter(Boolean)}}async function Rc(e,t,n){let o=await Ee(e,"bots.info",{bot:t},n);return{appId:o.bot?.app_id??"",userId:o.bot?.user_id??""}}async function vn(e,t,n=20,o,s,r,i){let c={channel:t,limit:String(n)};if(o!==void 0)c.oldest=o;if(s!==void 0)c.cursor=s;if(i)c.inclusive="true";return Ee(e,"conversations.history",c,r)}async function Nc(e,t,n,o=50,s){return Ee(e,"conversations.replies",{channel:t,ts:n,limit:String(o)},s)}async function Ps(e,t,n,o,s){await wr(e,"reactions.add",{channel:t,timestamp:n,name:o},s)}async function Bc(e,t,n,o){return((await Ee(e,"reactions.get",{channel:t,timestamp:n,full:"true"},o)).message?.reactions??[]).map((r)=>({name:String(r.name??""),users:Array.isArray(r.users)?r.users.map(String):[]}))}async function Rs(e,t,n,o,s){await wr(e,"reactions.remove",{channel:t,timestamp:n,name:o},s)}async function rp(e,t,n){let s=(await wr(e,"conversations.open",{users:t},n)).channel?.id;if(!s)throw Error(`Failed to open DM with user ${t}`);return s}async function Mc(e,t,n){let o="";while(!0){let s={types:"im",limit:"200"};if(o)s.cursor=o;let r=await Ee(e,"conversations.list",s,n);for(let i of r.channels??[])if(i.user===t)return String(i.id??"");if(o=r.response_metadata?.next_cursor??"",!o)break}return""}async function mr(e,t,n,o){let s=await Mc(e,t,n);if(s)return s;let r=o?`${o} (${t})`:t;throw Error(`No existing DM with ${r}. Open it once in Slack first.`)}function Bn(e){return e.toLowerCase().replace(/[-_\s]/g,"")}function Ac(e,t){let n=Bn(e.name??""),o=Bn(e.real_name??e.profile?.real_name??""),s=Bn(e.profile?.display_name??"");return n===t||o===t||!!s&&s===t}var vc=200;async function ip(e,t,n){let o=0,s=new Set,r="";while(!0){let u={limit:"200"};if(r)u.cursor=r;let d=await Ee(e,"users.list",u,n);for(let f of d.members??[]){if(o++,f.id)s.add(f.id);if(Ac(f,t))return{id:f.id??"",workspaceCount:o,connectCount:0,skipped:0,capped:!1}}if(r=d.response_metadata?.next_cursor??"",!r)break}let i=0,c=0,a=!1,l="";while(!0){let u={types:"im",limit:"200"};if(l)u.cursor=l;let d=await Ee(e,"conversations.list",u,n);for(let f of d.channels??[]){let h=f.user;if(!h||s.has(h))continue;if(i>=vc){a=!0;break}s.add(h),i++;let m;try{m=(await Ee(e,"users.info",{user:h},n)).user}catch(p){if(p instanceof Qe)throw p;c++;continue}if(m&&Ac(m,t))return{id:h,dm:String(f.id??""),workspaceCount:o,connectCount:i,skipped:c,capped:a}}if(a)break;if(l=d.response_metadata?.next_cursor??"",!l)break}return{id:"",workspaceCount:o,connectCount:i,skipped:c,capped:a}}function ap(e,t){if(t.workspaceCount===0)return Error(`Cannot resolve ${e}: users.list returned no members at all, so nothing could have matched.
121
+ Or import your Slack desktop session: slack auth login`)}throw Error(`Slack error on ${t}: ${c}`)}return i}async function yp(e,t,n,o){let s={};if(o)s.Cookie=`d=${o}`;let r=await fetch(`${kr()}/${t}`,{...n,headers:{...n.headers??{},Authorization:`Bearer ${e}`,...s}});if(r.status===429){let c=parseInt(r.headers.get("retry-after")??"60",10);throw new et(isNaN(c)?60:c,t)}let i=await r.json();if(i.ok!==!0){let c=i.error??"unknown";if(c==="ratelimited")throw new et(60,t);if((c==="invalid_auth"||c==="not_authed")&&!e.startsWith("xoxc-"))throw Error(`${t} requires a desktop app session token (xoxc-).
122
+ Import from Slack desktop: slack auth login`);if((c==="invalid_auth"||c==="not_authed")&&!o)throw Error(`${t} also requires the xoxd session cookie.
123
+ Attach it with: slack auth firefox (Linux/macOS/Windows) or slack auth chrome (macOS/Linux)`);throw Error(`Slack error on ${t}: ${c}`)}return i}function wp(e,t,n={},o){let s=new URLSearchParams({token:e,...n});return yp(e,t,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s.toString()},o)}function Ce(e,t,n,o){let s=new URLSearchParams(n).toString();return xr(e,`${t}?${s}`,{method:"GET"},o)}function Er(e,t,n,o){return xr(e,t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)},o)}async function vc(e,t,n){if(!e.startsWith("xoxb-"))throw Error("Agent sessions require a bot token (xoxb); user tokens are refused.");return xr(e,t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n),signal:AbortSignal.timeout(1e4)})}function Ln(e,t,n){return vc(e,"agents.sessions.setStatus",{...t,status:n})}function Cr(e,t,n){return vc(e,"agents.sessions.rename",{...t,title:n})}async function hn(e,t){let n=await Ce(e,"auth.test",{},t);return{team:n.team??"",teamId:n.team_id??"",url:n.url??"",user:n.user??"",userId:n.user_id??""}}async function Lc(e,t){t=e.startsWith("xoxc-")?t??xt():void 0;let n={Authorization:`Bearer ${e}`};if(t)n.Cookie=`d=${t}`;let o=await fetch(`${kr()}/auth.test`,{method:"GET",headers:n});if(o.status===429){let i=parseInt(o.headers.get("retry-after")??"60",10);throw new et(isNaN(i)?60:i,"auth.test")}let s=o.headers.get("x-oauth-scopes")??"",r=await o.json();if(r.ok!==!0)throw Error(`Slack error on auth.test: ${r.error??"unknown"}`);return{userId:r.user_id??"",user:r.user??"",botId:r.bot_id??"",team:r.team??"",url:r.url??"",scopes:s.split(",").map((i)=>i.trim()).filter(Boolean)}}async function Mc(e,t,n){let o=await Ce(e,"bots.info",{bot:t},n);return{appId:o.bot?.app_id??"",userId:o.bot?.user_id??""}}async function Mn(e,t,n=20,o,s,r,i){let c={channel:t,limit:String(n)};if(o!==void 0)c.oldest=o;if(s!==void 0)c.cursor=s;if(i)c.inclusive="true";return Ce(e,"conversations.history",c,r)}async function jc(e,t,n,o=50,s){return Ce(e,"conversations.replies",{channel:t,ts:n,limit:String(o)},s)}async function Ns(e,t,n,o,s){await Er(e,"reactions.add",{channel:t,timestamp:n,name:o},s)}async function Wc(e,t,n,o){return((await Ce(e,"reactions.get",{channel:t,timestamp:n,full:"true"},o)).message?.reactions??[]).map((r)=>({name:String(r.name??""),users:Array.isArray(r.users)?r.users.map(String):[]}))}async function Bs(e,t,n,o,s){await Er(e,"reactions.remove",{channel:t,timestamp:n,name:o},s)}async function bp(e,t,n){let s=(await Er(e,"conversations.open",{users:t},n)).channel?.id;if(!s)throw Error(`Failed to open DM with user ${t}`);return s}async function Uc(e,t,n){let o="";while(!0){let s={types:"im",limit:"200"};if(o)s.cursor=o;let r=await Ce(e,"conversations.list",s,n);for(let i of r.channels??[])if(i.user===t)return String(i.id??"");if(o=r.response_metadata?.next_cursor??"",!o)break}return""}async function br(e,t,n,o){let s=await Uc(e,t,n);if(s)return s;let r=o?`${o} (${t})`:t;throw Error(`No existing DM with ${r}. Open it once in Slack first.`)}function vn(e){return e.toLowerCase().replace(/[-_\s]/g,"")}function Rc(e,t){let n=vn(e.name??""),o=vn(e.real_name??e.profile?.real_name??""),s=vn(e.profile?.display_name??"");return n===t||o===t||!!s&&s===t}var Jc=200;async function kp(e,t,n){let o=0,s=new Set,r="";while(!0){let u={limit:"200"};if(r)u.cursor=r;let d=await Ce(e,"users.list",u,n);for(let f of d.members??[]){if(o++,f.id)s.add(f.id);if(Rc(f,t))return{id:f.id??"",workspaceCount:o,connectCount:0,skipped:0,capped:!1}}if(r=d.response_metadata?.next_cursor??"",!r)break}let i=0,c=0,a=!1,l="";while(!0){let u={types:"im",limit:"200"};if(l)u.cursor=l;let d=await Ce(e,"conversations.list",u,n);for(let f of d.channels??[]){let h=f.user;if(!h||s.has(h))continue;if(i>=Jc){a=!0;break}s.add(h),i++;let m;try{m=(await Ce(e,"users.info",{user:h},n)).user}catch(p){if(p instanceof et)throw p;c++;continue}if(m&&Rc(m,t))return{id:h,dm:String(f.id??""),workspaceCount:o,connectCount:i,skipped:c,capped:a}}if(a)break;if(l=d.response_metadata?.next_cursor??"",!l)break}return{id:"",workspaceCount:o,connectCount:i,skipped:c,capped:a}}function xp(e,t){if(t.workspaceCount===0)return Error(`Cannot resolve ${e}: users.list returned no members at all, so nothing could have matched.
119
124
  `+`That is a token or scope fault, not a wrong handle — this says nothing about whether ${e} exists.
120
- Check who you are: slack auth ls`);let n=t.connectCount?`${t.workspaceCount} workspace account(s) and ${t.connectCount} Slack Connect DM partner(s)`:`${t.workspaceCount} workspace account(s)`,o=[];if(t.capped)o.push(`stopped after ${vc} Slack Connect DM partners, so there may be more`);if(t.skipped)o.push(`${t.skipped} DM partner profile(s) could not be read and were never compared`);return Error(`User not found: ${e} — searched ${n}, none matched.
125
+ Check who you are: slack auth ls`);let n=t.connectCount?`${t.workspaceCount} workspace account(s) and ${t.connectCount} Slack Connect DM partner(s)`:`${t.workspaceCount} workspace account(s)`,o=[];if(t.capped)o.push(`stopped after ${Jc} Slack Connect DM partners, so there may be more`);if(t.skipped)o.push(`${t.skipped} DM partner profile(s) could not be read and were never compared`);return Error(`User not found: ${e} — searched ${n}, none matched.
121
126
  `+(o.length?`This search was incomplete: ${o.join("; ")}.
122
127
  `:"")+`Slack Connect people from another workspace are not in users.list, so if they never
123
128
  DMed you they cannot be found by name at all. Look them up and use their ID:
124
- slack user ls --external`)}function kr(e){let t=e.match(/(?:app\.slack\.com\/client\/T[A-Za-z0-9]+|[A-Za-z0-9-]+\.slack\.com\/archives)\/([A-Za-z0-9]+)(?:\/p(\d{10})(\d{6}))?/);if(!t)return;let n=t[1],o=t[2]&&t[3]?`${t[2]}.${t[3]}`:void 0,s=e.indexOf("?"),r=s>=0?new URLSearchParams(e.slice(s)):void 0,i=r?.get("thread_ts")??void 0,l={channel:r?.get("cid")??void 0??n};if(o)l.ts=o;if(i)l.threadTs=i;return l}function cp(e){return kr(e)?.channel}function Tc(e){return/^[CDG][A-Z0-9]{8,}$/.test(e)}function Ic(e){return/^[UW][A-Z0-9]{6,}$/.test(e)}async function Ns(e,t,n){let o=cp(t);if(o)return o;if(!t.startsWith("@")&&!t.startsWith("#")){if(Tc(t))return t;if(Ic(t))return mr(e,t,n);throw Error(`Target must start with # or @ (or be a Slack URL/ID), got: ${t}`)}if(t.startsWith("#")&&Tc(t.slice(1)))return t.slice(1);let s=t.startsWith("@"),r=t.slice(1),i=Bn(r);if(s){if(Ic(r))return mr(e,r,n);let l=await Ee(e,"auth.test",{},n);if(i==="you"||i==="me"||Bn(l.user??"")===i){let f=l.user_id;if(!f)throw Error("auth.test did not return user_id");return await Mc(e,f,n)||rp(e,f,n)}let d=await ip(e,i,n);if(!d.id)throw ap(t,d);if(d.dm)return d.dm;return mr(e,d.id,n,t)}let c=r.toLowerCase(),a="";while(!0){let l={limit:"200",types:"public_channel,private_channel",exclude_archived:"true"};if(a)l.cursor=a;let u=await Ee(e,"conversations.list",l,n);for(let d of u.channels??[])if(String(d.name??"").toLowerCase()===c)return String(d.id??"");if(a=u.response_metadata?.next_cursor??"",!a)break}throw Error(`channel not found: ${t}`)}async function Bs(e,t,n){try{let o=await Ee(e,"users.info",{user:t},n),s=o.user?.profile?.display_name,r=s&&s.length>0?s:o.user?.real_name??o.user?.name??t,i=o.user?.name??t;return[r,i]}catch{return[t,t]}}async function Ms(e,t,n){try{let o=await Ee(e,"users.info",{user:t},n),s=o.user?.profile?.display_name;if(s&&s.length>0)return s;return o.user?.real_name??o.user?.name??t}catch{return t}}async function vs(e,t){let n=[],o="";while(!0){let s={limit:"200"};if(o)s.cursor=o;let r=await Ee(e,"users.list",s,t);if(n.push(...r.members??[]),o=r.response_metadata?.next_cursor??"",!o)break}return{members:n}}async function xr(e,t,n){let o=[],s="";while(!0){let r={channel:t,limit:"200"};if(s)r.cursor=s;let i=await Ee(e,"conversations.members",r,n);if(o.push(...i.members??[]),s=i.response_metadata?.next_cursor??"",!s)break}return o}async function Cr(e,t,n){return Ee(e,"users.info",{user:t},n)}async function Lc(e,t,n){return Ee(e,"conversations.info",{channel:t},n)}async function jc(e,t){let n=await op(e,"client.boot",{},t),o=typeof n.url==="string"?n.url:void 0;if(!o){let r=Object.keys(n).join(", ");throw Error(`client.boot did not return a WebSocket URL. Keys: ${r}`)}let s=n.self&&typeof n.self==="object"&&!Array.isArray(n.self)?n.self:{};return{wsUrl:o,selfId:typeof s.id==="string"?s.id:""}}var lp=["chat:write","im:write"],up=["im:history","im:read"];async function Ls(e){let{userId:t,botId:n,team:o,scopes:s}=await Pc(e),r="";if(n)try{r=(await Rc(e,n)).appId}catch{r=""}let i=(l)=>s.includes(l),c=lp.filter((l)=>!i(l)),a=up.filter((l)=>!i(l));return{canSend:c.length===0,canReceiveReplies:a.length===0,ok:c.length===0&&a.length===0,botUserId:t,appId:r,team:o,grantedScopes:s,missingSendScopes:c,missingReplyScopes:a}}function Wc(e){return["",` Bot user: ${e.botUserId||"(unknown)"}`,` App ID: ${e.appId||"(unknown — bots.info unavailable)"}`,` Granted scopes: ${e.grantedScopes.join(", ")||"(none reported)"}`]}function js(e,t=!1){let n=e.appId?`https://api.slack.com/apps/${e.appId}`:"https://api.slack.com/apps";if(e.ok){let s=["✓ Bot DM scopes are complete (send + read replies)."," Two-way replies also require the Messages Tab, which is not API-detectable.",' If recipients see "Sending messages to this app is turned off", enable it:',` ${n} → App Home → "Messages Tab" ON + "Allow users to send messages".`];return t?s:[...s,...Wc(e)]}let o=[];if(!e.canSend)o.push(`⚠ This bot CANNOT send DMs — missing scope(s): ${e.missingSendScopes.join(", ")}.`);else o.push("⚠ This bot can send DMs, but the user's replies will NOT be readable.");return o.push(" Make escalation DMs two-way:"),o.push(` 1. ${n} → App Home → enable "Messages Tab" and check`),o.push(' "Allow users to send Slash commands and messages".'),o.push(` 2. OAuth & Permissions → add Bot Token Scopes: ${[...e.missingSendScopes,...e.missingReplyScopes].join(", ")}`),o.push(" 3. Reinstall the app to apply the new scopes."),t?o:[...o,...Wc(e)]}import{createInterface as Te}from"node:readline/promises";import{join as Pr,resolve as Bp}from"node:path";import{homedir as Mp}from"node:os";import{readdirSync as Wn,readFileSync as jn,existsSync as Me,copyFileSync as _r,mkdtempSync as Hc,rmSync as zc}from"node:fs";import{homedir as Us,tmpdir as qc}from"node:os";import{join as te,dirname as pp}from"node:path";import{pbkdf2Sync as Ws,createDecipheriv as Gc,createHash as hp,timingSafeEqual as gp}from"node:crypto";import{execSync as Xc,execFileSync as mp}from"node:child_process";function Ln(e,t){let n=0,o=0,s=t;while(s<e.length){let r=e[s++];if(n+=(r&127)*2**o,(r&128)===0)break;o+=7}return{value:n,pos:s}}function dp(e){let t=0,n=0,o=0;while(t<e.length){let i=e[t++];if(n+=(i&127)*2**o,(i&128)===0)break;o+=7}let s=Buffer.allocUnsafe(n),r=0;while(t<e.length&&r<n){let i=e[t++],c=i&3;if(c===0){let a=i>>2;if(a>=60){let l=a-59;a=0;for(let u=0;u<l;u++)a+=e[t++]*2**(8*u)}a+=1,e.copy(s,r,t,t+a),t+=a,r+=a}else{let a,l;if(c===1)a=4+(i>>2&7),l=(i>>5&7)*256+e[t++];else if(c===2)a=1+(i>>2),l=e[t]+e[t+1]*256,t+=2;else a=1+(i>>2),l=e[t]+e[t+1]*256+e[t+2]*65536+e[t+3]*16777216,t+=4;let u=r-l;for(let d=0;d<a&&r<n;d++)s[r++]=s[u++]}}return r===n?s:s.subarray(0,r)}function Er(e,t){let n=Ln(e,t),o=Ln(e,n.pos);return{handle:{offset:n.value,size:o.value},pos:o.pos}}function Uc(e,t){let{offset:n,size:o}=t,s=e.subarray(n,n+o);return e[n+o]===1?dp(s):Buffer.from(s)}function fp(e){if(e.length<4)return[];let t=e.readUInt32LE(e.length-4),n=e.length-(t+1)*4,o=[],s=0,r=Buffer.alloc(0);while(s<n){let i=Ln(e,s),c=Ln(e,i.pos),a=Ln(e,c.pos);s=a.pos;let l=i.value,u=c.value,d=a.value,f=e.subarray(s,s+u);s+=u;let h=e.subarray(s,s+d);s+=d,r=Buffer.concat([r.subarray(0,l),f]),o.push(h)}return o}function Jc(e){if(e.length<48)return Buffer.alloc(0);try{let t=e.length-48,n=Er(e,t),o=Er(e,n.pos),s=Uc(e,o.handle),r=[];for(let i of fp(s))try{let{handle:c}=Er(i,0);r.push(Uc(e,c))}catch{}return Buffer.concat(r)}catch{return Buffer.alloc(0)}}function Kc(){let e=process.env.HOME??Us();if(process.platform==="darwin")return[te(e,"Library","Application Support","Slack","Local Storage","leveldb")];if(process.platform==="linux")return[te(e,".config","Slack","Local Storage","leveldb"),te(e,"snap","slack","current",".config","Slack","Local Storage","leveldb"),te(e,".var","app","com.slack.Slack","config","Slack","Local Storage","leveldb")];if(process.platform==="win32"){let t=process.env.APPDATA??te(e,"AppData","Roaming");return[te(t,"Slack","Local Storage","leveldb")]}throw Error(`Unsupported platform: ${process.platform}`)}function Dp(){let e=process.env.HOME??Us();if(process.platform==="darwin")return te(e,"Library","Application Support","Slack","Cookies");return""}function yp(e,t){if(e.length<35||e.slice(0,3).toString()!=="v10")throw Error("Not a v10 encrypted cookie");let n=e.slice(19,35),o=e.slice(35),s=Gc("aes-128-cbc",t,n);return s.setAutoPadding(!0),Buffer.concat([s.update(o),s.final()]).toString("utf8")}function wp(){if(process.platform!=="darwin")return;let e=Dp();if(!Me(e))return;let t;try{t=Xc('security find-generic-password -w -s "Slack Safe Storage" -a "Slack Key"',{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trimEnd()}catch{return}let n=Ws(t,"saltysalt",1003,16,"sha1");try{let{default:o}=En("bun:sqlite"),s=new o(e,{readonly:!0}),r=s.prepare("SELECT encrypted_value FROM cookies WHERE name='d' AND host_key LIKE '%slack%'").get();if(s.close(),!r)return;return yp(Buffer.from(r.encrypted_value),n)}catch{return}}function Yc(e){if(!Me(e))return[];let t=Wn(e).filter((i)=>i.endsWith(".ldb")||i.endsWith(".log"));if(t.length===0)return[];let n=new Map,o=(i)=>{let c=n.get(i);if(c!==void 0)return c;let a="";try{let l=jn(te(e,i));a=i.endsWith(".ldb")?Jc(l).toString("latin1")||l.toString("latin1"):l.toString("latin1")}catch{a=""}return n.set(i,a),a},s=new Map;for(let i of t){let c=o(i);for(let a of c.matchAll(/"token":"(xoxc-[^"]+)"/g)){let l=a[1],u=l.split("-")[1]??"";if(!u||l.length<40)continue;let d=Math.max(0,a.index-2000),f=Math.min(c.length,a.index+2000),h=c.slice(d,f),m=h.match(/"url":"(https:\/\/[a-z0-9-]+\.slack\.com\/)"/),p=h.match(/"(?:team_name|name)":"([^"]{2,60})"/),D=s.get(u);if(!D||l.length>D.token.length){let k={token:l,teamId:u},x=m?.[1]??D?.url,E=p?.[1]??D?.teamName;if(x)k.url=x;if(E)k.teamName=E;s.set(u,k)}}}let r=t.map((i)=>o(i).replace(/[^\x20-\x7e]/g," ")).join(" ");for(let i of s.values()){if(i.teamName)continue;let c=r.indexOf(i.teamId);if(c!==-1){let a=Math.max(0,c-500),l=Math.min(r.length,c+500),d=r.slice(a,l).match(/"(?:team_name|name)":"([^"]{2,60})"/);if(d?.[1]){i.teamName=d[1];continue}}if(!i.teamName&&i.url){let a=i.url.match(/https:\/\/([a-z0-9-]+)\.slack\.com\//)?.[1];if(a){let l=r.indexOf(a);if(l!==-1){let u=Math.max(0,l-500),d=Math.min(r.length,l+500),h=r.slice(u,d).match(/"(?:team_name|name)":"([^"]{2,60})"/);if(h?.[1]){i.teamName=h[1];continue}}i.teamName=a.split("-").map((u)=>u.charAt(0).toUpperCase()+u.slice(1)).join(" ")}}}return[...s.values()]}async function Fr(e){let t=e??Kc().find(Me);if(!t)throw Error(`Slack desktop app LevelDB not found at:
125
- ${Kc().join(`
129
+ slack user ls --external`)}function Sr(e){let t=e.match(/(?:app\.slack\.com\/client\/T[A-Za-z0-9]+|[A-Za-z0-9-]+\.slack\.com\/archives)\/([A-Za-z0-9]+)(?:\/p(\d{10})(\d{6}))?/);if(!t)return;let n=t[1],o=t[2]&&t[3]?`${t[2]}.${t[3]}`:void 0,s=e.indexOf("?"),r=s>=0?new URLSearchParams(e.slice(s)):void 0,i=r?.get("thread_ts")??void 0,l={channel:r?.get("cid")??void 0??n};if(o)l.ts=o;if(i)l.threadTs=i;return l}function Ep(e){return Sr(e)?.channel}function Nc(e){return/^[CDG][A-Z0-9]{8,}$/.test(e)}function Bc(e){return/^[UW][A-Z0-9]{6,}$/.test(e)}async function vs(e,t,n){let o=Ep(t);if(o)return o;if(!t.startsWith("@")&&!t.startsWith("#")){if(Nc(t))return t;if(Bc(t))return br(e,t,n);throw Error(`Target must start with # or @ (or be a Slack URL/ID), got: ${t}`)}if(t.startsWith("#")&&Nc(t.slice(1)))return t.slice(1);let s=t.startsWith("@"),r=t.slice(1),i=vn(r);if(s){if(Bc(r))return br(e,r,n);let l=await Ce(e,"auth.test",{},n);if(i==="you"||i==="me"||vn(l.user??"")===i){let f=l.user_id;if(!f)throw Error("auth.test did not return user_id");return await Uc(e,f,n)||bp(e,f,n)}let d=await kp(e,i,n);if(!d.id)throw xp(t,d);if(d.dm)return d.dm;return br(e,d.id,n,t)}let c=r.toLowerCase(),a="";while(!0){let l={limit:"200",types:"public_channel,private_channel",exclude_archived:"true"};if(a)l.cursor=a;let u=await Ce(e,"conversations.list",l,n);for(let d of u.channels??[])if(String(d.name??"").toLowerCase()===c)return String(d.id??"");if(a=u.response_metadata?.next_cursor??"",!a)break}throw Error(`channel not found: ${t}`)}async function Ls(e,t,n){try{let o=await Ce(e,"users.info",{user:t},n),s=o.user?.profile?.display_name,r=s&&s.length>0?s:o.user?.real_name??o.user?.name??t,i=o.user?.name??t;return[r,i]}catch{return[t,t]}}async function Ms(e,t,n){try{let o=await Ce(e,"users.info",{user:t},n),s=o.user?.profile?.display_name;if(s&&s.length>0)return s;return o.user?.real_name??o.user?.name??t}catch{return t}}async function js(e,t){let n=[],o="";while(!0){let s={limit:"200"};if(o)s.cursor=o;let r=await Ce(e,"users.list",s,t);if(n.push(...r.members??[]),o=r.response_metadata?.next_cursor??"",!o)break}return{members:n}}async function _r(e,t,n){let o=[],s="";while(!0){let r={channel:t,limit:"200"};if(s)r.cursor=s;let i=await Ce(e,"conversations.members",r,n);if(o.push(...i.members??[]),s=i.response_metadata?.next_cursor??"",!s)break}return o}async function Fr(e,t,n){return Ce(e,"users.info",{user:t},n)}async function Kc(e,t,n){return Ce(e,"conversations.info",{channel:t},n)}async function Hc(e,t){let n=await wp(e,"client.boot",{},t),o=typeof n.url==="string"?n.url:void 0;if(!o){let r=Object.keys(n).join(", ");throw Error(`client.boot did not return a WebSocket URL. Keys: ${r}`)}let s=n.self&&typeof n.self==="object"&&!Array.isArray(n.self)?n.self:{};return{wsUrl:o,selfId:typeof s.id==="string"?s.id:""}}var Cp=["chat:write","im:write"],Sp=["im:history","im:read"];async function Ws(e){let{userId:t,botId:n,team:o,scopes:s}=await Lc(e),r="";if(n)try{r=(await Mc(e,n)).appId}catch{r=""}let i=(l)=>s.includes(l),c=Cp.filter((l)=>!i(l)),a=Sp.filter((l)=>!i(l));return{canSend:c.length===0,canReceiveReplies:a.length===0,ok:c.length===0&&a.length===0,botUserId:t,appId:r,team:o,grantedScopes:s,missingSendScopes:c,missingReplyScopes:a}}function zc(e){return["",` Bot user: ${e.botUserId||"(unknown)"}`,` App ID: ${e.appId||"(unknown — bots.info unavailable)"}`,` Granted scopes: ${e.grantedScopes.join(", ")||"(none reported)"}`]}function Us(e,t=!1){let n=e.appId?`https://api.slack.com/apps/${e.appId}`:"https://api.slack.com/apps";if(e.ok){let s=["✓ Bot DM scopes are complete (send + read replies)."," Two-way replies also require the Messages Tab, which is not API-detectable.",' If recipients see "Sending messages to this app is turned off", enable it:',` ${n} → App Home → "Messages Tab" ON + "Allow users to send messages".`];return t?s:[...s,...zc(e)]}let o=[];if(!e.canSend)o.push(`⚠ This bot CANNOT send DMs — missing scope(s): ${e.missingSendScopes.join(", ")}.`);else o.push("⚠ This bot can send DMs, but the user's replies will NOT be readable.");return o.push(" Make escalation DMs two-way:"),o.push(` 1. ${n} → App Home → enable "Messages Tab" and check`),o.push(' "Allow users to send Slash commands and messages".'),o.push(` 2. OAuth & Permissions → add Bot Token Scopes: ${[...e.missingSendScopes,...e.missingReplyScopes].join(", ")}`),o.push(" 3. Reinstall the app to apply the new scopes."),t?o:[...o,...zc(e)]}import{createInterface as Ie}from"node:readline/promises";import{join as vr,resolve as Vp}from"node:path";import{homedir as Zp}from"node:os";import{readdirSync as Un,readFileSync as Wn,existsSync as Le,copyFileSync as Tr,mkdtempSync as Yc,rmSync as Vc}from"node:fs";import{homedir as Ks,tmpdir as Zc}from"node:os";import{join as te,dirname as $p}from"node:path";import{pbkdf2Sync as Js,createDecipheriv as Qc,createHash as Ap,timingSafeEqual as Tp}from"node:crypto";import{execSync as el,execFileSync as Ip}from"node:child_process";function jn(e,t){let n=0,o=0,s=t;while(s<e.length){let r=e[s++];if(n+=(r&127)*2**o,(r&128)===0)break;o+=7}return{value:n,pos:s}}function _p(e){let t=0,n=0,o=0;while(t<e.length){let i=e[t++];if(n+=(i&127)*2**o,(i&128)===0)break;o+=7}let s=Buffer.allocUnsafe(n),r=0;while(t<e.length&&r<n){let i=e[t++],c=i&3;if(c===0){let a=i>>2;if(a>=60){let l=a-59;a=0;for(let u=0;u<l;u++)a+=e[t++]*2**(8*u)}a+=1,e.copy(s,r,t,t+a),t+=a,r+=a}else{let a,l;if(c===1)a=4+(i>>2&7),l=(i>>5&7)*256+e[t++];else if(c===2)a=1+(i>>2),l=e[t]+e[t+1]*256,t+=2;else a=1+(i>>2),l=e[t]+e[t+1]*256+e[t+2]*65536+e[t+3]*16777216,t+=4;let u=r-l;for(let d=0;d<a&&r<n;d++)s[r++]=s[u++]}}return r===n?s:s.subarray(0,r)}function $r(e,t){let n=jn(e,t),o=jn(e,n.pos);return{handle:{offset:n.value,size:o.value},pos:o.pos}}function qc(e,t){let{offset:n,size:o}=t,s=e.subarray(n,n+o);return e[n+o]===1?_p(s):Buffer.from(s)}function Fp(e){if(e.length<4)return[];let t=e.readUInt32LE(e.length-4),n=e.length-(t+1)*4,o=[],s=0,r=Buffer.alloc(0);while(s<n){let i=jn(e,s),c=jn(e,i.pos),a=jn(e,c.pos);s=a.pos;let l=i.value,u=c.value,d=a.value,f=e.subarray(s,s+u);s+=u;let h=e.subarray(s,s+d);s+=d,r=Buffer.concat([r.subarray(0,l),f]),o.push(h)}return o}function Gc(e){if(e.length<48)return Buffer.alloc(0);try{let t=e.length-48,n=$r(e,t),o=$r(e,n.pos),s=qc(e,o.handle),r=[];for(let i of Fp(s))try{let{handle:c}=$r(i,0);r.push(qc(e,c))}catch{}return Buffer.concat(r)}catch{return Buffer.alloc(0)}}function Xc(){let e=process.env.HOME??Ks();if(process.platform==="darwin")return[te(e,"Library","Application Support","Slack","Local Storage","leveldb")];if(process.platform==="linux")return[te(e,".config","Slack","Local Storage","leveldb"),te(e,"snap","slack","current",".config","Slack","Local Storage","leveldb"),te(e,".var","app","com.slack.Slack","config","Slack","Local Storage","leveldb")];if(process.platform==="win32"){let t=process.env.APPDATA??te(e,"AppData","Roaming");return[te(t,"Slack","Local Storage","leveldb")]}throw Error(`Unsupported platform: ${process.platform}`)}function Op(){let e=process.env.HOME??Ks();if(process.platform==="darwin")return te(e,"Library","Application Support","Slack","Cookies");return""}function Pp(e,t){if(e.length<35||e.slice(0,3).toString()!=="v10")throw Error("Not a v10 encrypted cookie");let n=e.slice(19,35),o=e.slice(35),s=Qc("aes-128-cbc",t,n);return s.setAutoPadding(!0),Buffer.concat([s.update(o),s.final()]).toString("utf8")}function Rp(){if(process.platform!=="darwin")return;let e=Op();if(!Le(e))return;let t;try{t=el('security find-generic-password -w -s "Slack Safe Storage" -a "Slack Key"',{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trimEnd()}catch{return}let n=Js(t,"saltysalt",1003,16,"sha1");try{let{default:o}=Sn("bun:sqlite"),s=new o(e,{readonly:!0}),r=s.prepare("SELECT encrypted_value FROM cookies WHERE name='d' AND host_key LIKE '%slack%'").get();if(s.close(),!r)return;return Pp(Buffer.from(r.encrypted_value),n)}catch{return}}function tl(e){if(!Le(e))return[];let t=Un(e).filter((i)=>i.endsWith(".ldb")||i.endsWith(".log"));if(t.length===0)return[];let n=new Map,o=(i)=>{let c=n.get(i);if(c!==void 0)return c;let a="";try{let l=Wn(te(e,i));a=i.endsWith(".ldb")?Gc(l).toString("latin1")||l.toString("latin1"):l.toString("latin1")}catch{a=""}return n.set(i,a),a},s=new Map;for(let i of t){let c=o(i);for(let a of c.matchAll(/"token":"(xoxc-[^"]+)"/g)){let l=a[1],u=l.split("-")[1]??"";if(!u||l.length<40)continue;let d=Math.max(0,a.index-2000),f=Math.min(c.length,a.index+2000),h=c.slice(d,f),m=h.match(/"url":"(https:\/\/[a-z0-9-]+\.slack\.com\/)"/),p=h.match(/"(?:team_name|name)":"([^"]{2,60})"/),D=s.get(u);if(!D||l.length>D.token.length){let k={token:l,teamId:u},x=m?.[1]??D?.url,C=p?.[1]??D?.teamName;if(x)k.url=x;if(C)k.teamName=C;s.set(u,k)}}}let r=t.map((i)=>o(i).replace(/[^\x20-\x7e]/g," ")).join(" ");for(let i of s.values()){if(i.teamName)continue;let c=r.indexOf(i.teamId);if(c!==-1){let a=Math.max(0,c-500),l=Math.min(r.length,c+500),d=r.slice(a,l).match(/"(?:team_name|name)":"([^"]{2,60})"/);if(d?.[1]){i.teamName=d[1];continue}}if(!i.teamName&&i.url){let a=i.url.match(/https:\/\/([a-z0-9-]+)\.slack\.com\//)?.[1];if(a){let l=r.indexOf(a);if(l!==-1){let u=Math.max(0,l-500),d=Math.min(r.length,l+500),h=r.slice(u,d).match(/"(?:team_name|name)":"([^"]{2,60})"/);if(h?.[1]){i.teamName=h[1];continue}}i.teamName=a.split("-").map((u)=>u.charAt(0).toUpperCase()+u.slice(1)).join(" ")}}}return[...s.values()]}async function Ir(e){let t=e??Xc().find(Le);if(!t)throw Error(`Slack desktop app LevelDB not found at:
130
+ ${Xc().join(`
126
131
  `)}
127
- Is Slack installed and opened at least once?`);let n=Yc(t),o=e?void 0:wp();if(o)for(let s of n)s.cookie=o;return n}function bp(e,t){try{return JSON.parse(jn(te(e,"Local State"),"utf8")).profile?.info_cache?.[t]?.user_name||void 0}catch{return}}function $r(){let e=Ar();if(!e||!Me(e))return[];let t=["Default",...Wn(e).filter((o)=>o.startsWith("Profile "))],n=[];for(let o of t){let s=te(e,o,"Local Storage","leveldb"),r=Yc(s);if(r.length===0)continue;let i=bp(e,o);n.push({profileDir:o,...i?{email:i}:{},label:Vc(e,o),sessions:r})}return n}function Sr(e,t,n,o=!1){let s=(r,i)=>{try{let c=Gc("aes-128-cbc",t,r);c.setAutoPadding(!0);let a=Buffer.concat([c.update(i),c.final()]);if(a.subarray(0,5).toString()==="xoxd-")return a.toString("utf8");if(a.length>=37){let l=hp("sha256").update(n).digest();if(gp(a.subarray(0,32),l)){let u=a.subarray(32).toString("utf8");if(u.startsWith("xoxd-"))return u}}return}catch{return}};return s(Buffer.alloc(16,32),e.slice(3))??(o&&e.length>=35?s(e.slice(19,35),e.slice(35)):void 0)}function Vc(e,t){let n=(o,s)=>{if(o&&s)return`${o} (${s})`;return o||s||t};try{let s=JSON.parse(jn(te(e,"Local State"),"utf8")).profile?.info_cache?.[t];if(s&&(s.name||s.user_name))return n(s.name??"",s.user_name??"")}catch{}try{let s=JSON.parse(jn(te(e,t,"Preferences"),"utf8")).profile;return n(s?.name??"",s?.user_name??"")}catch{return t}}function Ar(){let e=process.env.HOME??Us();if(process.platform==="darwin")return te(e,"Library","Application Support","Google","Chrome");if(process.platform==="linux")return te(process.env.XDG_CONFIG_HOME??te(e,".config"),"google-chrome");return""}function kp(){try{return mp("secret-tool",["lookup","application","chrome"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trimEnd()||void 0}catch{return}}function Un(){if(process.platform!=="darwin"&&process.platform!=="linux")return{candidates:[],totalProfiles:0};let e=Ar();if(!Me(e))return{candidates:[],totalProfiles:0};let t;if(process.platform==="darwin"){let i;try{i=Xc('security find-generic-password -a Chrome -s "Chrome Safe Storage" -w',{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trimEnd()}catch{return{candidates:[],totalProfiles:0}}if(!i)return{candidates:[],totalProfiles:0};t=Ws(i,"saltysalt",1003,16,"sha1")}let n=["Default",...Wn(e).filter((i)=>i.startsWith("Profile "))],o=[],s,r=!1;for(let i of n){let c=[te(e,i,"Network","Cookies"),te(e,i,"Cookies")].find(Me);if(!c)continue;let a=Hc(te(qc(),"slack-chrome-cookies-")),l=te(a,"Cookies");try{if(_r(c,l),Me(`${c}-wal`))_r(`${c}-wal`,`${l}-wal`);let{default:u}=En("bun:sqlite"),d=new u(l,{readonly:!0}),f;try{f=d.prepare("SELECT encrypted_value, value, host_key FROM cookies WHERE name='d' AND (host_key='slack.com' OR host_key LIKE '%.slack.com') LIMIT 1").get()}finally{d.close()}if(!f)continue;let h=Buffer.from(f.encrypted_value),m=h.subarray(0,3).toString(),p;if(m==="v20")throw Error("Chrome cookie uses unsupported v20 app-bound encryption.");if(process.platform==="linux"){if(!h.length&&f.value?.startsWith("xoxd-"))p=f.value;else if(m==="v10")p=Sr(h,Ws("peanuts","saltysalt",1,16,"sha1"),f.host_key);else if(m==="v11"){if(!s){let D=kp();if(D)s=Ws(D,"saltysalt",1,16,"sha1")}if(s)p=Sr(h,s,f.host_key);else r=!0}}else if(m==="v10"&&t)p=Sr(h,t,f.host_key,!0);else if(m!=="v10")throw Error("Unknown cookie encryption prefix.");if(p)o.push({profileDir:i,profileName:Vc(e,i),cookie:p})}catch(u){if(u instanceof Error&&(u.message.includes("unsupported v20")||u.message.includes("Unknown cookie")))throw u}finally{zc(a,{recursive:!0,force:!0})}}if(r&&o.length===0)throw Error("Chrome v11 cookie key is unavailable. Install secret-tool and unlock the GNOME keyring, or use slack auth firefox.");return{candidates:o,totalProfiles:n.length}}async function Tr(){if(process.platform!=="linux")throw Error("Chrome session import is currently supported on Linux only.");let e=Ar();if(!Me(e))throw Error("Chrome profile directory was not found.");let t=new Map(Un().candidates.map((s)=>[s.profileDir,s.cookie])),n=new Map,o=["Default",...Wn(e).filter((s)=>s.startsWith("Profile "))];for(let s of o){let r=te(e,s,"Local Storage","leveldb");if(!Me(r))continue;let i;try{i=await Fr(r)}catch{continue}for(let c of i){if(n.has(c.teamId))throw Error("More than one Chrome profile has a token for the same workspace. Select one browser profile first.");let a=t.get(s);if(a)c.cookie=a;n.set(c.teamId,c)}}return[...n.values()]}function xp(){let e=process.env.HOME??Us();if(process.platform==="darwin")return[te(e,"Library","Application Support","Firefox","Profiles")];if(process.platform==="linux")return[te(e,".mozilla","firefox"),te(e,"snap","firefox","common",".mozilla","firefox"),te(e,".var","app","org.mozilla.firefox",".mozilla","firefox")];if(process.platform==="win32")return[te(process.env.APPDATA??te(e,"AppData","Roaming"),"Mozilla","Firefox","Profiles")];return[]}function Cp(e){let t=te(e,"profiles.ini"),n=Me(t)?t:te(pp(e),"profiles.ini"),o={};if(!Me(n))return o;try{let s=jn(n,"utf8"),r="",i="";for(let c of s.split(`
128
- `)){let a=c.trim();if(a.startsWith("[")){r="",i="";continue}let l=a.indexOf("=");if(l===-1)continue;let u=a.slice(0,l).trim().toLowerCase(),d=a.slice(l+1).trim();if(u==="name")r=d;if(u==="path")i=d.split(/[\\/]/).pop()??d;if(r&&i)o[i]=r,r="",i=""}}catch{}return o}function Js(){let e=[];for(let t of xp().filter(Me)){let n=Cp(t),o;try{o=Wn(t)}catch{continue}for(let s of o){let r=te(t,s,"cookies.sqlite");if(!Me(r))continue;let i=Hc(te(qc(),"slack-firefox-cookies-")),c=te(i,"cookies.sqlite");try{_r(r,c);let{default:a}=En("bun:sqlite"),l=new a(c,{readonly:!0}),u=l.prepare("SELECT value FROM moz_cookies WHERE name='d' AND (host='slack.com' OR host LIKE '%.slack.com') LIMIT 1").get();if(l.close(),!u?.value||!u.value.startsWith("xoxd-"))continue;let d=n[s]??s;e.push({profileDir:s,profileName:d,cookie:u.value})}catch{}finally{zc(i,{recursive:!0,force:!0})}}}return e}import{readFileSync as Ir,writeFileSync as Or,mkdirSync as Ep,existsSync as Jn,rmSync as Sp}from"node:fs";import{join as He}from"node:path";import{createDecipheriv as Ks}from"node:crypto";import{spawnSync as _p}from"node:child_process";var Fp=Buffer.from("b31c6e241ac846728da9c1fac4936651cffb944d143ab816276bcc6da0284787","hex"),$p=Buffer.from("e98f37d7f4e1fa433d19304dc2258042090e2d1d7eea7670d41f738d08729660","hex"),Ap=Buffer.from("ccf8a1cec56605b8517552ba1a2d061c03a29e90274fb2fcf59ba4b75c392390","hex"),et="C:\\ProgramData\\slack-term-abe";function Tp(){let e=process.env.LOCALAPPDATA??He(process.env.USERPROFILE??"","AppData","Local");return He(e,"Google","Chrome","User Data")}var Ip=String.raw`try {
132
+ Is Slack installed and opened at least once?`);let n=tl(t),o=e?void 0:Rp();if(o)for(let s of n)s.cookie=o;return n}function Np(e,t){try{return JSON.parse(Wn(te(e,"Local State"),"utf8")).profile?.info_cache?.[t]?.user_name||void 0}catch{return}}function Or(){let e=Pr();if(!e||!Le(e))return[];let t=["Default",...Un(e).filter((o)=>o.startsWith("Profile "))],n=[];for(let o of t){let s=te(e,o,"Local Storage","leveldb"),r=tl(s);if(r.length===0)continue;let i=Np(e,o);n.push({profileDir:o,...i?{email:i}:{},label:nl(e,o),sessions:r})}return n}function Ar(e,t,n,o=!1){let s=(r,i)=>{try{let c=Qc("aes-128-cbc",t,r);c.setAutoPadding(!0);let a=Buffer.concat([c.update(i),c.final()]);if(a.subarray(0,5).toString()==="xoxd-")return a.toString("utf8");if(a.length>=37){let l=Ap("sha256").update(n).digest();if(Tp(a.subarray(0,32),l)){let u=a.subarray(32).toString("utf8");if(u.startsWith("xoxd-"))return u}}return}catch{return}};return s(Buffer.alloc(16,32),e.slice(3))??(o&&e.length>=35?s(e.slice(19,35),e.slice(35)):void 0)}function nl(e,t){let n=(o,s)=>{if(o&&s)return`${o} (${s})`;return o||s||t};try{let s=JSON.parse(Wn(te(e,"Local State"),"utf8")).profile?.info_cache?.[t];if(s&&(s.name||s.user_name))return n(s.name??"",s.user_name??"")}catch{}try{let s=JSON.parse(Wn(te(e,t,"Preferences"),"utf8")).profile;return n(s?.name??"",s?.user_name??"")}catch{return t}}function Pr(){let e=process.env.HOME??Ks();if(process.platform==="darwin")return te(e,"Library","Application Support","Google","Chrome");if(process.platform==="linux")return te(process.env.XDG_CONFIG_HOME??te(e,".config"),"google-chrome");return""}function Bp(){try{return Ip("secret-tool",["lookup","application","chrome"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trimEnd()||void 0}catch{return}}function Jn(){if(process.platform!=="darwin"&&process.platform!=="linux")return{candidates:[],totalProfiles:0};let e=Pr();if(!Le(e))return{candidates:[],totalProfiles:0};let t;if(process.platform==="darwin"){let i;try{i=el('security find-generic-password -a Chrome -s "Chrome Safe Storage" -w',{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trimEnd()}catch{return{candidates:[],totalProfiles:0}}if(!i)return{candidates:[],totalProfiles:0};t=Js(i,"saltysalt",1003,16,"sha1")}let n=["Default",...Un(e).filter((i)=>i.startsWith("Profile "))],o=[],s,r=!1;for(let i of n){let c=[te(e,i,"Network","Cookies"),te(e,i,"Cookies")].find(Le);if(!c)continue;let a=Yc(te(Zc(),"slack-chrome-cookies-")),l=te(a,"Cookies");try{if(Tr(c,l),Le(`${c}-wal`))Tr(`${c}-wal`,`${l}-wal`);let{default:u}=Sn("bun:sqlite"),d=new u(l,{readonly:!0}),f;try{f=d.prepare("SELECT encrypted_value, value, host_key FROM cookies WHERE name='d' AND (host_key='slack.com' OR host_key LIKE '%.slack.com') LIMIT 1").get()}finally{d.close()}if(!f)continue;let h=Buffer.from(f.encrypted_value),m=h.subarray(0,3).toString(),p;if(m==="v20")throw Error("Chrome cookie uses unsupported v20 app-bound encryption.");if(process.platform==="linux"){if(!h.length&&f.value?.startsWith("xoxd-"))p=f.value;else if(m==="v10")p=Ar(h,Js("peanuts","saltysalt",1,16,"sha1"),f.host_key);else if(m==="v11"){if(!s){let D=Bp();if(D)s=Js(D,"saltysalt",1,16,"sha1")}if(s)p=Ar(h,s,f.host_key);else r=!0}}else if(m==="v10"&&t)p=Ar(h,t,f.host_key,!0);else if(m!=="v10")throw Error("Unknown cookie encryption prefix.");if(p)o.push({profileDir:i,profileName:nl(e,i),cookie:p})}catch(u){if(u instanceof Error&&(u.message.includes("unsupported v20")||u.message.includes("Unknown cookie")))throw u}finally{Vc(a,{recursive:!0,force:!0})}}if(r&&o.length===0)throw Error("Chrome v11 cookie key is unavailable. Install secret-tool and unlock the GNOME keyring, or use slack auth firefox.");return{candidates:o,totalProfiles:n.length}}async function Rr(){if(process.platform!=="linux")throw Error("Chrome session import is currently supported on Linux only.");let e=Pr();if(!Le(e))throw Error("Chrome profile directory was not found.");let t=new Map(Jn().candidates.map((s)=>[s.profileDir,s.cookie])),n=new Map,o=["Default",...Un(e).filter((s)=>s.startsWith("Profile "))];for(let s of o){let r=te(e,s,"Local Storage","leveldb");if(!Le(r))continue;let i;try{i=await Ir(r)}catch{continue}for(let c of i){if(n.has(c.teamId))throw Error("More than one Chrome profile has a token for the same workspace. Select one browser profile first.");let a=t.get(s);if(a)c.cookie=a;n.set(c.teamId,c)}}return[...n.values()]}function vp(){let e=process.env.HOME??Ks();if(process.platform==="darwin")return[te(e,"Library","Application Support","Firefox","Profiles")];if(process.platform==="linux")return[te(e,".mozilla","firefox"),te(e,"snap","firefox","common",".mozilla","firefox"),te(e,".var","app","org.mozilla.firefox",".mozilla","firefox")];if(process.platform==="win32")return[te(process.env.APPDATA??te(e,"AppData","Roaming"),"Mozilla","Firefox","Profiles")];return[]}function Lp(e){let t=te(e,"profiles.ini"),n=Le(t)?t:te($p(e),"profiles.ini"),o={};if(!Le(n))return o;try{let s=Wn(n,"utf8"),r="",i="";for(let c of s.split(`
133
+ `)){let a=c.trim();if(a.startsWith("[")){r="",i="";continue}let l=a.indexOf("=");if(l===-1)continue;let u=a.slice(0,l).trim().toLowerCase(),d=a.slice(l+1).trim();if(u==="name")r=d;if(u==="path")i=d.split(/[\\/]/).pop()??d;if(r&&i)o[i]=r,r="",i=""}}catch{}return o}function Hs(){let e=[];for(let t of vp().filter(Le)){let n=Lp(t),o;try{o=Un(t)}catch{continue}for(let s of o){let r=te(t,s,"cookies.sqlite");if(!Le(r))continue;let i=Yc(te(Zc(),"slack-firefox-cookies-")),c=te(i,"cookies.sqlite");try{Tr(r,c);let{default:a}=Sn("bun:sqlite"),l=new a(c,{readonly:!0}),u=l.prepare("SELECT value FROM moz_cookies WHERE name='d' AND (host='slack.com' OR host LIKE '%.slack.com') LIMIT 1").get();if(l.close(),!u?.value||!u.value.startsWith("xoxd-"))continue;let d=n[s]??s;e.push({profileDir:s,profileName:d,cookie:u.value})}catch{}finally{Vc(i,{recursive:!0,force:!0})}}}return e}import{readFileSync as Nr,writeFileSync as Br,mkdirSync as Mp,existsSync as Kn,rmSync as jp}from"node:fs";import{join as qe}from"node:path";import{createDecipheriv as zs}from"node:crypto";import{spawnSync as Wp}from"node:child_process";var Up=Buffer.from("b31c6e241ac846728da9c1fac4936651cffb944d143ab816276bcc6da0284787","hex"),Jp=Buffer.from("e98f37d7f4e1fa433d19304dc2258042090e2d1d7eea7670d41f738d08729660","hex"),Kp=Buffer.from("ccf8a1cec56605b8517552ba1a2d061c03a29e90274fb2fcf59ba4b75c392390","hex"),tt="C:\\ProgramData\\slack-term-abe";function Hp(){let e=process.env.LOCALAPPDATA??qe(process.env.USERPROFILE??"","AppData","Local");return qe(e,"Google","Chrome","User Data")}var zp=String.raw`try {
129
134
  Add-Type -AssemblyName System.Security
130
135
  $d = [IO.File]::ReadAllBytes('C:\ProgramData\slack-term-abe\in.bin')
131
136
  $o = [Security.Cryptography.ProtectedData]::Unprotect($d, $null, 'CurrentUser')
132
137
  [IO.File]::WriteAllBytes('C:\ProgramData\slack-term-abe\sys.bin', $o)
133
138
  } catch { Set-Content 'C:\ProgramData\slack-term-abe\dpapi.err' ($_.Exception.Message) }
134
- `,Op=String.raw`try {
139
+ `,qp=String.raw`try {
135
140
  Add-Type -TypeDefinition @'
136
141
  using System; using System.Runtime.InteropServices;
137
142
  public static class NC {
@@ -147,7 +152,7 @@ public static class NC {
147
152
  '@
148
153
  [IO.File]::WriteAllBytes('C:\ProgramData\slack-term-abe\cng.bin', [NC]::Dec([IO.File]::ReadAllBytes('C:\ProgramData\slack-term-abe\eak.bin')))
149
154
  } catch { Set-Content 'C:\ProgramData\slack-term-abe\cng.err' ($_.Exception.Message) }
150
- `;function Pp(e,t){let n=(o)=>`'${o.replace(/'/g,"''")}'`;return String.raw`
155
+ `;function Gp(e,t){let n=(o)=>`'${o.replace(/'/g,"''")}'`;return String.raw`
151
156
  $ErrorActionPreference = 'Stop'
152
157
  Add-Type -AssemblyName System.Security
153
158
  $work = 'C:\ProgramData\slack-term-abe'
@@ -213,46 +218,46 @@ icacls "$work\Cookies" /grant "$($u):(R)" | Out-Null
213
218
  if (Test-Path "$work\cng.bin") { icacls "$work\cng.bin" /grant "$($u):(R)" | Out-Null }
214
219
  Write-Host 'OK'
215
220
  try { Stop-Transcript | Out-Null } catch {}
216
- `}function Rp(e,t){let o=4+e.readUInt32LE(0)+4,s=e[o];if(s===1||s===2){let r=e.subarray(o+1,o+13),i=e.subarray(o+13,o+45),c=e.subarray(o+45,o+61),a=s===1?Ks("aes-256-gcm",Fp,r):Ks("chacha20-poly1305",$p,r,{authTagLength:16});return a.setAuthTag(c),Buffer.concat([a.update(i),a.final()])}if(s===3){if(!t)throw Error("flag 3 requires the CNG-decrypted key (cng.bin missing)");let r=e.subarray(o+33,o+45),i=e.subarray(o+45,o+77),c=e.subarray(o+77,o+93),a=Buffer.from(t.map((u,d)=>u^Ap[d])),l=Ks("aes-256-gcm",a,r);return l.setAuthTag(c),Buffer.concat([l.update(i),l.final()])}throw Error(`Unsupported app-bound key flag: ${s}`)}function Np(e,t){let n=t.subarray(3,15),o=t.subarray(15,t.length-16),s=t.subarray(t.length-16),r=Ks("aes-256-gcm",e,n);return r.setAuthTag(s),Buffer.concat([r.update(o),r.final()]).subarray(32).toString("utf8")}async function Zc(e){if(process.platform!=="win32")throw Error("Windows-only");let t=Tp();if(!Jn(He(t,"Local State")))throw Error(`Chrome Local State not found at ${t}`);Ep(et,{recursive:!0});let n=He(et,"extract.ps1");Or(n,Pp(t,e)),Or(He(et,"inner_dpapi.ps1"),Ip),Or(He(et,"inner_cng.ps1"),Op);let o=`Start-Process powershell -Verb RunAs -Wait -ArgumentList @('-NoProfile','-ExecutionPolicy','Bypass','-WindowStyle','Hidden','-File','${n.replace(/'/g,"''")}')`,s=_p("powershell",["-NoProfile","-Command",o],{encoding:"utf8",windowsHide:!0});if(s.status!==0&&s.error)throw Error(`Failed to launch elevated helper: ${s.error.message}`);let r=He(et,"out.bin"),i=He(et,"Cookies");if(!Jn(r)||!Jn(i)){let c=Jn(He(et,"log.txt"))?Ir(He(et,"log.txt"),"utf8").split(`
217
- `).filter((a)=>a.startsWith("ERROR")).join(" "):"";throw Error(`Elevated extraction did not complete${c?` (${c.trim()})`:" (UAC declined or Chrome build unsupported)"}`)}try{let c=Ir(r),a=Jn(He(et,"cng.bin"))?Ir(He(et,"cng.bin")):void 0,l=Rp(c,a),{Database:u}=En("bun:sqlite"),d=new u(i,{readonly:!0}),f=d.query("SELECT encrypted_value v FROM cookies WHERE name = char(100) AND host_key LIKE char(37,115,108,97,99,107,37) LIMIT 1").get();if(d.close(),!f)throw Error("no Slack `d` cookie in that Chrome profile");let h=Buffer.from(f.v);if(h.subarray(0,3).toString()!=="v20")throw Error(`unexpected cookie version ${h.subarray(0,3).toString("latin1")}`);let m=Np(l,h);if(!m.startsWith("xoxd-"))throw Error("decrypted value is not an xoxd- cookie");return m}finally{if(!process.env.SLACK_KEEP_ABE)Sp(et,{recursive:!0,force:!0})}}var vp=["search:read","channels:history","groups:history","im:history","mpim:history","channels:read","groups:read","im:read","mpim:read","users:read","chat:write","files:write"],Lp=["channels:history","groups:history","im:history","mpim:history","channels:read","groups:read","im:read","mpim:read","users:read","chat:write","files:write"];function hn(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function jp(){return JSON.stringify({display_information:{name:"slack-term"},oauth_config:{scopes:{user:vp}},settings:{org_deploy_enabled:!1,socket_mode_enabled:!1,token_rotation_enabled:!1}},null,2)}function Wp(){return JSON.stringify({display_information:{name:"slack-term"},features:{bot_user:{display_name:"slack-term",always_online:!1}},oauth_config:{scopes:{bot:Lp}},settings:{org_deploy_enabled:!1,socket_mode_enabled:!1,token_rotation_enabled:!1}},null,2)}async function Ct(e,t){return(await e.question(t)).trim()}async function Kn(e,t){if(t)return!0;if(!e)return!1;let n=await Ct(e,"Read local browser profiles and Slack session cookies? [y/N]: ");return n.toLowerCase()==="y"||n.toLowerCase()==="yes"}async function zt(e,t,n,o){console.error("Verifying token...");let s=await pn(t,o),r=hn(s.team),i;if(n)i=n;else if(e)i=await Ct(e,`Workspace name [${r}]: `)||r;else i=r;let c=null;if(e){console.log(""),console.log("Where to save the token?"),console.log(" 1) ./.env.local (current directory) [default]"),console.log(" 2) ./.slack-term/.env.local (current directory, slack-specific)"),console.log(" 3) ~/.slack-term/.env.local (global, available everywhere)"),console.log(" 4) profiles.json (multi-workspace: slack auth use)"),console.log("");let a=await Ct(e,"Choice [1/2/3/4, Enter=1]: ");if(a==="2")c=Pr(process.cwd(),".slack-term",".env.local");else if(a==="3")c=Pr(Mp(),".slack-term",".env.local");else if(a==="4")c=null;else c=Pr(process.cwd(),".env.local")}if(c===null)if(Is(i,{token:t,...s,...o?{cookie:o}:{}}),console.log(`Saved workspace "${i}" to profiles.json: ${s.team} (${s.user})`),process.env.SLACK_MCP_XOXP_TOKEN)console.log(""),console.log("Warning: SLACK_MCP_XOXP_TOKEN is set — it conflicts with profiles."),console.log(" Unset it: unset SLACK_MCP_XOXP_TOKEN (and remove from ~/.zshrc / ~/.bashrc)");else console.log(` Run: slack auth use -g ${i}`);else{let a={SLACK_TOKEN:t};if(o)a.SLACK_COOKIE=o;hr(c,a),console.log(`Saved token to ${c}`),console.log(" SLACK_TOKEN will be picked up automatically in this directory tree.")}return i}async function Rr(e,t=!1,n="auto",o=!1){console.error("Scanning Slack desktop app...");let s=await Fr();if(s.length===0)console.error("No sessions found. Make sure Slack is installed and you have signed in at least once."),process.exit(1);if(process.platform==="linux"&&n!=="none"&&s.some((r)=>!r.cookie)&&await Kn(e,t)){let r=[];if(n!=="chrome")for(let i of Js())r.push({source:"Firefox",profileName:i.profileName,cookie:i.cookie});if(n==="chrome"||n==="all"||n==="auto"&&r.length===0)try{for(let i of Un().candidates)r.push({source:"Chrome",profileName:i.profileName,cookie:i.cookie})}catch(i){console.error(i instanceof Error?i.message:String(i))}if(r.length===1){for(let i of s)i.cookie??=r[0].cookie;console.log(`Found Slack session cookie in ${r[0].source} profile: ${r[0].profileName}`)}else if(r.length>1)console.log("Multiple browser sessions found. Choose one later with slack auth chrome or slack auth firefox.");if(s.some((i)=>!i.cookie))console.log("Desktop session needs an xoxd cookie on Linux. Run: slack auth chrome or slack auth firefox")}await Nr(s,e,o)}async function Nr(e,t,n=!1){if(e.length===1&&t&&e[0]?.cookie&&!n){let o=e[0],s=o.teamName??o.teamId;console.log(`Found workspace: ${s}${o.cookie?" (+ xoxd cookie)":""}`),await zt(t,o.token,hn(s),o.cookie),console.log(""),console.log("Note: desktop app tokens (xoxc-) are internal Slack tokens."),console.log("If API calls fail, replace with an xoxp- token: slack auth login");return}for(let o of e){let s=o.teamName??o.teamId,r=hn(s);Is(r,{token:o.token,team:s,teamId:o.teamId,url:o.url??"",user:"",...o.cookie?{cookie:o.cookie}:{}}),console.log(`Added workspace "${r}": ${s}${o.cookie?" + xoxd cookie":""}`)}if(console.log(""),e.length===1){let o=hn(e[0].teamName??e[0].teamId);console.log(`Run: slack auth use -g ${o}`)}else console.log("Run: slack auth ls then: slack auth use -g <name>");console.log(""),console.log("Note: desktop app tokens (xoxc-) are internal Slack tokens."),console.log("If API calls fail, replace with an xoxp- user token by re-running: slack auth login")}async function Qc(e){console.log("Which token type does your app use?"),console.log(""),console.log(" 1) User token (xoxp-) -full access including search [recommended]"),console.log(" 2) Bot token (xoxb-) -search and news unavailable"),console.log("");let n=await Ct(e,"Choice [1/2]: ")==="2"?"bot":"user",o=n==="user"?"xoxp-":"xoxb-",s=n==="user"?"User OAuth Token":"Bot User OAuth Token";console.log(""),console.log("Find your token here:"),console.log(" https://api.slack.com/apps"),console.log(" -> Select your app -> OAuth & Permissions"),console.log(` -> Copy the "${s}" (starts with ${o})`),console.log("");let r=await Ct(e,"Paste your token: ");if(!r)console.error("No token provided."),process.exit(1);if(!r.startsWith(o))console.error(`Expected a ${o} token, got: ${r.slice(0,10)}...`),process.exit(1);await zt(e,r)}async function Hs(e,t){let n=t==="user"?jp():Wp(),o=t==="user"?"User OAuth Token (xoxp-...)":"Bot User OAuth Token (xoxb-...)",s=t==="user"?"xoxp-":"xoxb-";if(t==="bot")console.log("Note: bot tokens cannot use search:read (user-only scope)."),console.log(" The news and search commands will not work with a bot token."),console.log("");console.log("Step 1 -Create your Slack app:"),console.log(" Open: https://api.slack.com/apps"),console.log(' Click "Create New App" -> "From a manifest" -> select your workspace'),console.log(" Paste this manifest (JSON tab):"),console.log(""),console.log("-------------------------------------------------------------"),console.log(n),console.log("-------------------------------------------------------------"),console.log(""),console.log('Step 2 -Install: "Install App" -> "Install to Workspace" -> Authorize'),console.log(""),console.log("Step 3 -Copy your token:"),console.log(` OAuth & Permissions -> ${o}`),console.log("");let r=await Ct(e,"Paste your token: ");if(!r)console.error("No token provided."),process.exit(1);if(!r.startsWith(s))console.error(`Expected a ${s} token, got: ${r.slice(0,10)}...`),process.exit(1);await zt(e,r)}async function Up(e,t){let n=$r();if(n.length===0)console.error("No Slack session found in Chrome. Sign in to Slack in Chrome (app.slack.com) and retry."),process.exit(1);let o=e.profile.token.split("-")[1],s=n.find((r)=>r.sessions.some((i)=>i.teamId===o));if(!s&&t){if(s=n.find((r)=>r.email===t||r.profileDir===t||r.profileDir===`Profile ${t}`),!s)console.error(`Chrome profile "${t}" has no Slack session. Available: ${n.map((r)=>r.email??r.profileDir).join(", ")}`),process.exit(1)}if(!s)if(n.length===1)s=n[0];else if(process.stdin.isTTY){console.log("Multiple Chrome profiles have a Slack session:"),n.forEach((a,l)=>console.log(` ${l+1}) ${a.email??a.label} [${a.profileDir}]`));let r=Te({input:process.stdin,output:process.stdout}),i=(await r.question(`Choice [1-${n.length}]: `)).trim();r.close();let c=parseInt(i,10)-1;if(isNaN(c)||c<0||c>=n.length)console.error("Invalid choice."),process.exit(1);s=n[c]}else console.error("Multiple Chrome profiles have a Slack session — choose one with --profile:"),n.forEach((r)=>console.error(` slack auth cookie -w ${e.name} --profile "${r.email??r.profileDir}"`)),process.exit(1);console.log(`Using Chrome profile: ${s.email??s.label} [${s.profileDir}]`),console.log("Chrome's cookie is app-bound encrypted; a Windows elevation (UAC) prompt will appear — approve it.");try{return await Zc(s.profileDir)}catch(r){console.error(`
218
- Could not extract the cookie automatically: ${r instanceof Error?r.message:String(r)}`),console.error("Fallback (manual): Chrome > DevTools (F12) > Application > Cookies > https://app.slack.com > copy the `d` value,"),console.error("then set it via an env file: SLACK_COOKIE=xoxd-... (in .slack-term/.env.local)"),process.exit(1)}}async function el(e={}){if(process.platform!=="darwin"&&process.platform!=="linux"&&process.platform!=="win32")console.error("Chrome cookie extraction is supported on macOS, Linux, and Windows."),process.exit(1);let t=Nn();if(t.length===0)console.error("No workspaces configured. Run: slack auth login"),process.exit(1);let n;if(e.workspace){if(!t.find((i)=>i.name===e.workspace))console.error(`Workspace "${e.workspace}" not found. Available: ${t.map((i)=>i.name).join(", ")}`),process.exit(1);n=e.workspace}else if(t.length===1)n=t[0].name;else{let r=t.find((i)=>i.current);if(r)n=r.name,console.log(`Using active workspace: ${n}`);else{console.log("Multiple workspaces found. Choose one:"),t.forEach((l,u)=>console.log(` ${u+1}) ${l.name} (${l.profile.team})`));let i=Te({input:process.stdin,output:process.stdout}),c=(await i.question("Choice: ")).trim();i.close();let a=parseInt(c,10)-1;if(isNaN(a)||a<0||a>=t.length)console.error("Invalid choice."),process.exit(1);n=t[a].name}}let o=t.find((r)=>r.name===n);if(o.profile.token.startsWith("xoxb-")){console.error(`
221
+ `}function Xp(e,t){let o=4+e.readUInt32LE(0)+4,s=e[o];if(s===1||s===2){let r=e.subarray(o+1,o+13),i=e.subarray(o+13,o+45),c=e.subarray(o+45,o+61),a=s===1?zs("aes-256-gcm",Up,r):zs("chacha20-poly1305",Jp,r,{authTagLength:16});return a.setAuthTag(c),Buffer.concat([a.update(i),a.final()])}if(s===3){if(!t)throw Error("flag 3 requires the CNG-decrypted key (cng.bin missing)");let r=e.subarray(o+33,o+45),i=e.subarray(o+45,o+77),c=e.subarray(o+77,o+93),a=Buffer.from(t.map((u,d)=>u^Kp[d])),l=zs("aes-256-gcm",a,r);return l.setAuthTag(c),Buffer.concat([l.update(i),l.final()])}throw Error(`Unsupported app-bound key flag: ${s}`)}function Yp(e,t){let n=t.subarray(3,15),o=t.subarray(15,t.length-16),s=t.subarray(t.length-16),r=zs("aes-256-gcm",e,n);return r.setAuthTag(s),Buffer.concat([r.update(o),r.final()]).subarray(32).toString("utf8")}async function sl(e){if(process.platform!=="win32")throw Error("Windows-only");let t=Hp();if(!Kn(qe(t,"Local State")))throw Error(`Chrome Local State not found at ${t}`);Mp(tt,{recursive:!0});let n=qe(tt,"extract.ps1");Br(n,Gp(t,e)),Br(qe(tt,"inner_dpapi.ps1"),zp),Br(qe(tt,"inner_cng.ps1"),qp);let o=`Start-Process powershell -Verb RunAs -Wait -ArgumentList @('-NoProfile','-ExecutionPolicy','Bypass','-WindowStyle','Hidden','-File','${n.replace(/'/g,"''")}')`,s=Wp("powershell",["-NoProfile","-Command",o],{encoding:"utf8",windowsHide:!0});if(s.status!==0&&s.error)throw Error(`Failed to launch elevated helper: ${s.error.message}`);let r=qe(tt,"out.bin"),i=qe(tt,"Cookies");if(!Kn(r)||!Kn(i)){let c=Kn(qe(tt,"log.txt"))?Nr(qe(tt,"log.txt"),"utf8").split(`
222
+ `).filter((a)=>a.startsWith("ERROR")).join(" "):"";throw Error(`Elevated extraction did not complete${c?` (${c.trim()})`:" (UAC declined or Chrome build unsupported)"}`)}try{let c=Nr(r),a=Kn(qe(tt,"cng.bin"))?Nr(qe(tt,"cng.bin")):void 0,l=Xp(c,a),{Database:u}=Sn("bun:sqlite"),d=new u(i,{readonly:!0}),f=d.query("SELECT encrypted_value v FROM cookies WHERE name = char(100) AND host_key LIKE char(37,115,108,97,99,107,37) LIMIT 1").get();if(d.close(),!f)throw Error("no Slack `d` cookie in that Chrome profile");let h=Buffer.from(f.v);if(h.subarray(0,3).toString()!=="v20")throw Error(`unexpected cookie version ${h.subarray(0,3).toString("latin1")}`);let m=Yp(l,h);if(!m.startsWith("xoxd-"))throw Error("decrypted value is not an xoxd- cookie");return m}finally{if(!process.env.SLACK_KEEP_ABE)jp(tt,{recursive:!0,force:!0})}}var Qp=["search:read","channels:history","groups:history","im:history","mpim:history","channels:read","groups:read","im:read","mpim:read","users:read","chat:write","files:write"],eh=["channels:history","groups:history","im:history","mpim:history","channels:read","groups:read","im:read","mpim:read","users:read","chat:write","files:write"];function gn(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function th(){return JSON.stringify({display_information:{name:"slack-term"},oauth_config:{scopes:{user:Qp}},settings:{org_deploy_enabled:!1,socket_mode_enabled:!1,token_rotation_enabled:!1}},null,2)}function nh(){return JSON.stringify({display_information:{name:"slack-term"},features:{bot_user:{display_name:"slack-term",always_online:!1}},oauth_config:{scopes:{bot:eh}},settings:{org_deploy_enabled:!1,socket_mode_enabled:!1,token_rotation_enabled:!1}},null,2)}async function Et(e,t){return(await e.question(t)).trim()}async function Hn(e,t){if(t)return!0;if(!e)return!1;let n=await Et(e,"Read local browser profiles and Slack session cookies? [y/N]: ");return n.toLowerCase()==="y"||n.toLowerCase()==="yes"}async function qt(e,t,n,o){console.error("Verifying token...");let s=await hn(t,o),r=gn(s.team),i;if(n)i=n;else if(e)i=await Et(e,`Workspace name [${r}]: `)||r;else i=r;let c=null;if(e){console.log(""),console.log("Where to save the token?"),console.log(" 1) ./.env.local (current directory) [default]"),console.log(" 2) ./.slack-term/.env.local (current directory, slack-specific)"),console.log(" 3) ~/.slack-term/.env.local (global, available everywhere)"),console.log(" 4) profiles.json (multi-workspace: slack auth use)"),console.log("");let a=await Et(e,"Choice [1/2/3/4, Enter=1]: ");if(a==="2")c=vr(process.cwd(),".slack-term",".env.local");else if(a==="3")c=vr(Zp(),".slack-term",".env.local");else if(a==="4")c=null;else c=vr(process.cwd(),".env.local")}if(c===null)if(Os(i,{token:t,...s,...o?{cookie:o}:{}}),console.log(`Saved workspace "${i}" to profiles.json: ${s.team} (${s.user})`),process.env.SLACK_MCP_XOXP_TOKEN)console.log(""),console.log("Warning: SLACK_MCP_XOXP_TOKEN is set — it conflicts with profiles."),console.log(" Unset it: unset SLACK_MCP_XOXP_TOKEN (and remove from ~/.zshrc / ~/.bashrc)");else console.log(` Run: slack auth use -g ${i}`);else{let a={SLACK_TOKEN:t};if(o)a.SLACK_COOKIE=o;yr(c,a),console.log(`Saved token to ${c}`),console.log(" SLACK_TOKEN will be picked up automatically in this directory tree.")}return i}async function Lr(e,t=!1,n="auto",o=!1){console.error("Scanning Slack desktop app...");let s=await Ir();if(s.length===0)console.error("No sessions found. Make sure Slack is installed and you have signed in at least once."),process.exit(1);if(process.platform==="linux"&&n!=="none"&&s.some((r)=>!r.cookie)&&await Hn(e,t)){let r=[];if(n!=="chrome")for(let i of Hs())r.push({source:"Firefox",profileName:i.profileName,cookie:i.cookie});if(n==="chrome"||n==="all"||n==="auto"&&r.length===0)try{for(let i of Jn().candidates)r.push({source:"Chrome",profileName:i.profileName,cookie:i.cookie})}catch(i){console.error(i instanceof Error?i.message:String(i))}if(r.length===1){for(let i of s)i.cookie??=r[0].cookie;console.log(`Found Slack session cookie in ${r[0].source} profile: ${r[0].profileName}`)}else if(r.length>1)console.log("Multiple browser sessions found. Choose one later with slack auth chrome or slack auth firefox.");if(s.some((i)=>!i.cookie))console.log("Desktop session needs an xoxd cookie on Linux. Run: slack auth chrome or slack auth firefox")}await Mr(s,e,o)}async function Mr(e,t,n=!1){if(e.length===1&&t&&e[0]?.cookie&&!n){let o=e[0],s=o.teamName??o.teamId;console.log(`Found workspace: ${s}${o.cookie?" (+ xoxd cookie)":""}`),await qt(t,o.token,gn(s),o.cookie),console.log(""),console.log("Note: desktop app tokens (xoxc-) are internal Slack tokens."),console.log("If API calls fail, replace with an xoxp- token: slack auth login");return}for(let o of e){let s=o.teamName??o.teamId,r=gn(s);Os(r,{token:o.token,team:s,teamId:o.teamId,url:o.url??"",user:"",...o.cookie?{cookie:o.cookie}:{}}),console.log(`Added workspace "${r}": ${s}${o.cookie?" + xoxd cookie":""}`)}if(console.log(""),e.length===1){let o=gn(e[0].teamName??e[0].teamId);console.log(`Run: slack auth use -g ${o}`)}else console.log("Run: slack auth ls then: slack auth use -g <name>");console.log(""),console.log("Note: desktop app tokens (xoxc-) are internal Slack tokens."),console.log("If API calls fail, replace with an xoxp- user token by re-running: slack auth login")}async function ol(e){console.log("Which token type does your app use?"),console.log(""),console.log(" 1) User token (xoxp-) -full access including search [recommended]"),console.log(" 2) Bot token (xoxb-) -search and news unavailable"),console.log("");let n=await Et(e,"Choice [1/2]: ")==="2"?"bot":"user",o=n==="user"?"xoxp-":"xoxb-",s=n==="user"?"User OAuth Token":"Bot User OAuth Token";console.log(""),console.log("Find your token here:"),console.log(" https://api.slack.com/apps"),console.log(" -> Select your app -> OAuth & Permissions"),console.log(` -> Copy the "${s}" (starts with ${o})`),console.log("");let r=await Et(e,"Paste your token: ");if(!r)console.error("No token provided."),process.exit(1);if(!r.startsWith(o))console.error(`Expected a ${o} token, got: ${r.slice(0,10)}...`),process.exit(1);await qt(e,r)}async function qs(e,t){let n=t==="user"?th():nh(),o=t==="user"?"User OAuth Token (xoxp-...)":"Bot User OAuth Token (xoxb-...)",s=t==="user"?"xoxp-":"xoxb-";if(t==="bot")console.log("Note: bot tokens cannot use search:read (user-only scope)."),console.log(" The news and search commands will not work with a bot token."),console.log("");console.log("Step 1 -Create your Slack app:"),console.log(" Open: https://api.slack.com/apps"),console.log(' Click "Create New App" -> "From a manifest" -> select your workspace'),console.log(" Paste this manifest (JSON tab):"),console.log(""),console.log("-------------------------------------------------------------"),console.log(n),console.log("-------------------------------------------------------------"),console.log(""),console.log('Step 2 -Install: "Install App" -> "Install to Workspace" -> Authorize'),console.log(""),console.log("Step 3 -Copy your token:"),console.log(` OAuth & Permissions -> ${o}`),console.log("");let r=await Et(e,"Paste your token: ");if(!r)console.error("No token provided."),process.exit(1);if(!r.startsWith(s))console.error(`Expected a ${s} token, got: ${r.slice(0,10)}...`),process.exit(1);await qt(e,r)}async function sh(e,t){let n=Or();if(n.length===0)console.error("No Slack session found in Chrome. Sign in to Slack in Chrome (app.slack.com) and retry."),process.exit(1);let o=e.profile.token.split("-")[1],s=n.find((r)=>r.sessions.some((i)=>i.teamId===o));if(!s&&t){if(s=n.find((r)=>r.email===t||r.profileDir===t||r.profileDir===`Profile ${t}`),!s)console.error(`Chrome profile "${t}" has no Slack session. Available: ${n.map((r)=>r.email??r.profileDir).join(", ")}`),process.exit(1)}if(!s)if(n.length===1)s=n[0];else if(process.stdin.isTTY){console.log("Multiple Chrome profiles have a Slack session:"),n.forEach((a,l)=>console.log(` ${l+1}) ${a.email??a.label} [${a.profileDir}]`));let r=Ie({input:process.stdin,output:process.stdout}),i=(await r.question(`Choice [1-${n.length}]: `)).trim();r.close();let c=parseInt(i,10)-1;if(isNaN(c)||c<0||c>=n.length)console.error("Invalid choice."),process.exit(1);s=n[c]}else console.error("Multiple Chrome profiles have a Slack session — choose one with --profile:"),n.forEach((r)=>console.error(` slack auth cookie -w ${e.name} --profile "${r.email??r.profileDir}"`)),process.exit(1);console.log(`Using Chrome profile: ${s.email??s.label} [${s.profileDir}]`),console.log("Chrome's cookie is app-bound encrypted; a Windows elevation (UAC) prompt will appear — approve it.");try{return await sl(s.profileDir)}catch(r){console.error(`
223
+ Could not extract the cookie automatically: ${r instanceof Error?r.message:String(r)}`),console.error("Fallback (manual): Chrome > DevTools (F12) > Application > Cookies > https://app.slack.com > copy the `d` value,"),console.error("then set it via an env file: SLACK_COOKIE=xoxd-... (in .slack-term/.env.local)"),process.exit(1)}}async function rl(e={}){if(process.platform!=="darwin"&&process.platform!=="linux"&&process.platform!=="win32")console.error("Chrome cookie extraction is supported on macOS, Linux, and Windows."),process.exit(1);let t=Bn();if(t.length===0)console.error("No workspaces configured. Run: slack auth login"),process.exit(1);let n;if(e.workspace){if(!t.find((i)=>i.name===e.workspace))console.error(`Workspace "${e.workspace}" not found. Available: ${t.map((i)=>i.name).join(", ")}`),process.exit(1);n=e.workspace}else if(t.length===1)n=t[0].name;else{let r=t.find((i)=>i.current);if(r)n=r.name,console.log(`Using active workspace: ${n}`);else{console.log("Multiple workspaces found. Choose one:"),t.forEach((l,u)=>console.log(` ${u+1}) ${l.name} (${l.profile.team})`));let i=Ie({input:process.stdin,output:process.stdout}),c=(await i.question("Choice: ")).trim();i.close();let a=parseInt(c,10)-1;if(isNaN(a)||a<0||a>=t.length)console.error("Invalid choice."),process.exit(1);n=t[a].name}}let o=t.find((r)=>r.name===n);if(o.profile.token.startsWith("xoxb-")){console.error(`
219
224
  Workspace "${n}" uses a bot token (xoxb-). A Chrome session cookie only
220
225
  `+`augments a user session token (xoxc-) — it has no effect on a bot token, so user-level
221
- `+"actions (tail @user, DMs, listing users) would still fail.");let r=t.filter((i)=>i.profile.token.startsWith("xoxc-")||i.profile.token.startsWith("xoxp-"));if(r.length>0)console.error(` Target a user-token workspace instead: ${r.map((i)=>i.name).join(", ")}`),console.error(` slack auth chrome -w ${r[0].name}`);else console.error(" Import your Slack desktop user session instead: slack auth login");process.exit(1)}let s;if(process.platform==="win32")s=await Up(o,e.profile);else{if(!e.yes&&!process.stdin.isTTY)console.error("Reading browser profiles requires confirmation. Re-run interactively or pass --yes."),process.exit(1);let r=e.yes?void 0:Te({input:process.stdin,output:process.stdout});try{if(!await Kn(r,e.yes??!1)){console.log("Browser profile scan cancelled.");return}}finally{r?.close()}if(console.log("Scanning Chrome profiles for Slack session..."),process.platform==="darwin")console.log("macOS may show a dialog asking for your login password — click Allow.");let i,c;try{({candidates:i,totalProfiles:c}=Un())}catch(a){console.error(`Failed: ${a instanceof Error?a.message:String(a)}`),process.exit(1)}if(i.length===0)console.error(`No Slack session found in Chrome (scanned ${c} profile${c!==1?"s":""}). Possible reasons:`),console.error(" - You denied the keychain dialog (try running again and click Allow)"),console.error(" - Chrome is not installed or has no Slack session"),console.error(" - You're not logged in to Slack in Chrome"),process.exit(1);if(i.length===1&&c<=1)s=i[0].cookie,console.log(`Found session in Chrome profile: ${i[0].profileName}`);else{let a=i.length===1?`Found 1 Slack session across ${c} Chrome profiles:`:`Found ${i.length} Slack sessions across ${c} Chrome profiles:`;console.log(a),i.forEach((h,m)=>console.log(` ${m+1}) ${h.profileName} [${h.profileDir}]`)),console.log("");let l=Te({input:process.stdin,output:process.stdout}),u=i.length===1?" [Enter=1]":"",d=(await l.question(`Choice [1-${i.length}]${u}: `)).trim();l.close();let f=d===""&&i.length===1?0:parseInt(d,10)-1;if(isNaN(f)||f<0||f>=i.length)console.error("Invalid choice."),process.exit(1);s=i[f].cookie}}gr(n,s),console.log(`Saved xoxd cookie to workspace "${n}".`),console.log("RTM WebSocket mode is now available: slack tail @you")}async function Br(e={}){console.error("Scanning Chrome profiles for Slack sessions...");let t=$r();if(t.length===0)console.error("No Slack session found in Chrome."),console.error(" Open Slack in Chrome (https://app.slack.com) and sign in, then retry."),process.exit(1);let n;if(e.profile){let r=e.profile,i=t.find((c)=>c.email===r||c.profileDir===r||c.profileDir===`Profile ${r}`);if(!i)console.error(`Chrome profile "${r}" has no Slack session. Available:`),t.forEach((c)=>console.error(` - ${c.email??c.label} [${c.profileDir}] (${c.sessions.length} workspace${c.sessions.length!==1?"s":""})`)),process.exit(1);n=i}else if(t.length===1)n=t[0];else if(process.stdin.isTTY){console.log("Found Slack sessions in multiple Chrome profiles:"),t.forEach((a,l)=>console.log(` ${l+1}) ${a.email??a.label} [${a.profileDir}] (${a.sessions.length} workspace${a.sessions.length!==1?"s":""})`));let r=Te({input:process.stdin,output:process.stdout}),i=(await r.question(`Choice [1-${t.length}]: `)).trim();r.close();let c=parseInt(i,10)-1;if(isNaN(c)||c<0||c>=t.length)console.error("Invalid choice."),process.exit(1);n=t[c]}else console.error("Multiple Chrome profiles have a Slack session — choose one with --profile:"),t.forEach((r)=>console.error(` slack auth login chrome --profile "${r.email??r.profileDir}"`)),process.exit(1);let o=n.email??n.label??n.profileDir,s;if(process.platform==="darwin")try{let{candidates:r}=Un();s=r.find((i)=>i.profileDir===n.profileDir)?.cookie??r[0]?.cookie}catch{}if(s)Fc(o,s,`chrome:${n.profileDir}`);for(let r of n.sessions){let i=r.teamName??r.teamId,c=hn(i);Is(c,{token:r.token,team:i,teamId:r.teamId,url:r.url??"",user:"",identity:o}),console.log(`Added workspace "${c}": ${i} (identity: ${o})`)}if(console.log(""),s)console.log(`Captured xoxd cookie for ${o} — shared across its ${n.sessions.length} workspace(s).`),console.log("RTM WebSocket mode is now available: slack tail @you");else console.log("Note: no xoxd cookie captured (LocalStorage yields the token only; the cookie is"),console.log("encrypted at rest on this platform). Some features (RTM, drafts, search fallback) need it."),console.log(" Attach it from your live browser — e.g. a CDP read via rech — or paste it:"),console.log(` slack auth cookie --workspace ${hn(n.sessions[0].teamName??n.sessions[0].teamId)}`);console.log(""),console.log("Select a workspace: slack auth use <name> (see: slack auth ls)")}async function Mr(e={}){let t=Nn();if(t.length===0)console.error("No workspaces configured. Run: slack auth login"),process.exit(1);let n;if(e.workspace){if(!t.find((c)=>c.name===e.workspace))console.error(`Workspace "${e.workspace}" not found. Available: ${t.map((c)=>c.name).join(", ")}`),process.exit(1);n=e.workspace}else if(t.length===1)n=t[0].name;else{let i=t.find((c)=>c.current);if(i)n=i.name,console.log(`Using active workspace: ${n}`);else{console.log("Multiple workspaces found. Choose one:"),t.forEach((u,d)=>console.log(` ${d+1}) ${u.name} (${u.profile.team})`));let c=Te({input:process.stdin,output:process.stdout}),a=(await c.question("Choice: ")).trim();c.close();let l=parseInt(a,10)-1;if(isNaN(l)||l<0||l>=t.length)console.error("Invalid choice."),process.exit(1);n=t[l].name}}if(!e.yes&&!process.stdin.isTTY)console.error("Reading browser profiles requires confirmation. Re-run interactively or pass --yes."),process.exit(1);let o=e.yes?void 0:Te({input:process.stdin,output:process.stdout});try{if(!await Kn(o,e.yes??!1)){console.log("Browser profile scan cancelled.");return}}finally{o?.close()}console.log("Scanning Firefox profiles for Slack session...");let s=Js();if(s.length===0)console.error("No Slack session found in Firefox. Possible reasons:"),console.error(" - Firefox is not installed"),console.error(" - You are not logged in to Slack in Firefox"),process.exit(1);let r;if(s.length===1)r=s[0].cookie,console.log(`Found session in Firefox profile: ${s[0].profileName}`);else{console.log("Multiple Firefox profiles have a Slack session. Choose one:"),s.forEach((l,u)=>console.log(` ${u+1}) ${l.profileName} [${l.profileDir}]`));let i=Te({input:process.stdin,output:process.stdout}),c=(await i.question("Choice: ")).trim();i.close();let a=parseInt(c,10)-1;if(isNaN(a)||a<0||a>=s.length)console.error("Invalid choice."),process.exit(1);r=s[a].cookie}gr(n,r),console.log(`Saved xoxd cookie to workspace "${n}".`),console.log("RTM WebSocket mode is now available: slack tail @you")}async function tl(e={}){if(e.token){await zt(null,e.token,e.name);return}if(!process.stdin.isTTY){let n=[];for await(let s of process.stdin)n.push(s);let o=Buffer.concat(n).toString("utf8").trim();if(!o)console.error("No token provided on stdin."),process.exit(1);await zt(null,o,e.name);return}let t=Te({input:process.stdin,output:process.stdout});try{await Qc(t)}finally{t.close()}}async function nl(e={}){let t=Te({input:process.stdin,output:process.stdout});try{if(e.bot!==void 0){await Hs(t,e.bot?"bot":"user");return}console.log("Which token type?"),console.log(" 1) User token (xoxp-) -full access including search [default]"),console.log(" 2) Bot token (xoxb-) -search and news unavailable"),console.log("");let n=await Ct(t,"Choice [1/2, Enter=1]: ");await Hs(t,n==="2"?"bot":"user")}finally{t.close()}}function sl(e={}){let t=(s,r)=>{if(/[\r\n]/.test(r))throw Error(`Invalid newline in ${s}.`);return`${s}=${/^[A-Za-z0-9._=-]+$/.test(r)?r:JSON.stringify(r)}`},n=[t("SLACK_TOKEN",$c(e.workspace))],o=xt(e.workspace);if(o)n.push(t("SLACK_COOKIE",o));if(!e.workspace){let s=Os();if(s)n.push(t("SLACK_BOT_TOKEN",s))}console.log(n.join(`
222
- `))}function ol(e){let t=Nn(),n=e.workspace?t.find((s)=>s.name===e.workspace):t.find((s)=>s.current)??(t.length===1?t[0]:void 0);if(!n)throw Error(e.workspace?`Workspace "${e.workspace}" not found. Run: slack auth ls`:"Select a workspace with slack auth use <name>, or pass --workspace <name>.");if(!n.profile.cookie)throw Error(`Workspace "${n.name}" has no session cookie. Run: slack auth chrome -w ${n.name} or slack auth firefox -w ${n.name}`);let o=Bp(e.envfile);hr(o,{SLACK_TOKEN:n.profile.token,SLACK_COOKIE:n.profile.cookie}),console.log(`Saved token and cookie for workspace "${n.name}" to ${o}`)}async function Hn(e={}){let t=Nn();if(t.length>0){console.log("Currently logged in:");for(let{name:o,profile:s,current:r}of t)console.log(` ${r?"*":" "} ${o} ${s.team} (${s.user||"unknown"})`);console.log(""),console.log("Adding another workspace:"),console.log("")}if([e.fromChrome,e.fromFirefox,e.fromAll].filter(Boolean).length>1)throw Error("Choose only one browser source: --from-chrome, --from-firefox, or --from-all.");if(e.fromChrome&&!e.fromDesktop){if(!e.yes&&!process.stdin.isTTY)throw Error("Reading browser profiles requires confirmation. Re-run interactively or pass --yes.");let o=process.stdin.isTTY?Te({input:process.stdin,output:process.stdout}):void 0;try{if(!await Kn(o,e.yes??!1)){console.log("Browser profile scan cancelled.");return}let s=await Tr();if(s.length===0)throw Error("No Slack session token found in Chrome profiles.");await Nr(s,o,!0)}finally{o?.close()}return}if(e.fromAll&&!e.fromDesktop){if(!e.yes&&!process.stdin.isTTY)throw Error("Reading browser profiles requires confirmation. Re-run interactively or pass --yes.");let o=process.stdin.isTTY?Te({input:process.stdin,output:process.stdout}):void 0;try{try{await Rr(o,e.yes??!1,"all",!0)}catch(s){if(!(s instanceof Error)||!s.message.startsWith("Slack desktop app LevelDB not found"))throw s;if(!await Kn(o,e.yes??!1)){console.log("Browser profile scan cancelled.");return}let r=await Tr();if(r.length===0)throw Error("No Slack session token found in Chrome profiles.");if(r.every((i)=>!i.cookie)){let i=Js();if(i.length===1)for(let c of r)c.cookie=i[0].cookie}await Nr(r,o,!0)}}finally{o?.close()}return}if(e.fromDesktop||e.fromChrome||e.fromFirefox||e.fromAll){let o=e.fromChrome?"chrome":e.fromFirefox?"firefox":e.fromAll?"all":"none";if(o!=="none"&&!e.yes&&!process.stdin.isTTY)throw Error("Reading browser profiles requires confirmation. Re-run interactively or pass --yes.");let s=process.stdin.isTTY?Te({input:process.stdin,output:process.stdout}):void 0;try{await Rr(s,e.yes??!1,o,!0)}finally{s?.close()}return}if(e.token){await zt(null,e.token,e.name);return}if(!process.stdin.isTTY){let o=[];for await(let r of process.stdin)o.push(r);let s=Buffer.concat(o).toString("utf8").trim();if(!s)console.error("No token provided on stdin."),process.exit(1);await zt(null,s,e.name);return}console.log("How would you like to authenticate with Slack?"),console.log(""),console.log(" 1) Slack desktop app - import session token"),console.log(" Reads the xoxc- token directly from the installed app."),console.log(" Token: all platforms | xoxd cookie: macOS, or Chrome/Firefox on Linux"),console.log(""),console.log(" 2) Chrome browser - import workspaces"),console.log(" Reads xoxc- tokens from Chrome, grouped by account."),console.log(" Token: all platforms | xoxd cookie: macOS only"),console.log(""),console.log(" 3) Connect existing Slack app [recommended if you have one]"),console.log(" Paste a token from an app you already created."),console.log(""),console.log(" 4) Create new Slack app - user token (xoxp-)"),console.log(" Guided setup with manifest. Full access including search."),console.log(""),console.log(" 5) Create new Slack app - bot token (xoxb-)"),console.log(" Bot is invited to channels. Search and news unavailable."),console.log("");let n=Te({input:process.stdin,output:process.stdout});try{let o=await Ct(n,"Choice [1/2/3/4/5]: ");if(console.log(""),o==="1")await Rr(n,e.yes??!1);else if(o==="2"){n.close(),await Br();return}else if(o==="3")await Qc(n);else if(o==="4")await Hs(n,"user");else if(o==="5")await Hs(n,"bot");else console.error(`Invalid choice: "${o}". Enter 1, 2, 3, 4, or 5.`),process.exit(1)}finally{n.close()}}async function zs(e,t,n,o){let s=t,r=[],i=s,c=0;while(!0){let a=i.indexOf("<@U",c);if(a===-1)break;let l=i.slice(a+2),u=l.search(/[>|]/),d=u===-1?l:l.slice(0,u);if(d.length>=9)r.push(d);c=a+1}for(let a of r){if(!n.has(a))n.set(a,await Ms(e,a,o));let l=n.get(a)??a;s=s.replaceAll(`<@${a}>`,`@${l}`),s=s.replace(new RegExp(`<@${a}\\|[^>]*>`,"g"),`@${l}`)}return s}function qs(e){return e.replace(/<!date\^(\d+)\^[^|>]*(?:\|([^>]*))?>/g,(t,n,o)=>{let s=Number(n);if(!Number.isFinite(s))return o??"date";let r=new Date(s*1000);if(Number.isNaN(r.getTime()))return o??"date";let i=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],c=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],a=i[r.getUTCDay()]??"",l=c[r.getUTCMonth()]??"";return`${a}, ${l} ${String(r.getUTCDate()).padStart(2,"0")}, ${r.getUTCFullYear()}`})}function il(e){let t=typeof e.ts==="string"?e.ts:"",n=typeof e.thread_ts==="string"?e.thread_ts:"";return n!==""&&n!==t}function Jp(e){let[t,n="000000"]=e.split("."),o=new Date(Number(t)*1000),s=o.getUTCFullYear(),r=String(o.getUTCMonth()+1).padStart(2,"0"),i=String(o.getUTCDate()).padStart(2,"0"),c=String(o.getUTCHours()).padStart(2,"0"),a=String(o.getUTCMinutes()).padStart(2,"0"),l=String(o.getUTCSeconds()).padStart(2,"0"),u=n.padEnd(6,"0").slice(0,6);return`${s}-${r}-${i}T${c}:${a}:${l}.${u}`}async function Kp(e,t,n){let o=typeof t.ts==="string"?t.ts:"0.000000",s=Jp(o),r="?";if(typeof t.user==="string"){let d=t.user,f="@"+d;if(!n.has(f)){let[,h]=await Bs(e,d);n.set(f,h)}r=n.get(f)??d}else if(typeof t.username==="string")r=t.username;let i=typeof t.text==="string"?t.text:"",a=qs(await zs(e,i,n)).split(`
226
+ `+"actions (tail @user, DMs, listing users) would still fail.");let r=t.filter((i)=>i.profile.token.startsWith("xoxc-")||i.profile.token.startsWith("xoxp-"));if(r.length>0)console.error(` Target a user-token workspace instead: ${r.map((i)=>i.name).join(", ")}`),console.error(` slack auth chrome -w ${r[0].name}`);else console.error(" Import your Slack desktop user session instead: slack auth login");process.exit(1)}let s;if(process.platform==="win32")s=await sh(o,e.profile);else{if(!e.yes&&!process.stdin.isTTY)console.error("Reading browser profiles requires confirmation. Re-run interactively or pass --yes."),process.exit(1);let r=e.yes?void 0:Ie({input:process.stdin,output:process.stdout});try{if(!await Hn(r,e.yes??!1)){console.log("Browser profile scan cancelled.");return}}finally{r?.close()}if(console.log("Scanning Chrome profiles for Slack session..."),process.platform==="darwin")console.log("macOS may show a dialog asking for your login password — click Allow.");let i,c;try{({candidates:i,totalProfiles:c}=Jn())}catch(a){console.error(`Failed: ${a instanceof Error?a.message:String(a)}`),process.exit(1)}if(i.length===0)console.error(`No Slack session found in Chrome (scanned ${c} profile${c!==1?"s":""}). Possible reasons:`),console.error(" - You denied the keychain dialog (try running again and click Allow)"),console.error(" - Chrome is not installed or has no Slack session"),console.error(" - You're not logged in to Slack in Chrome"),process.exit(1);if(i.length===1&&c<=1)s=i[0].cookie,console.log(`Found session in Chrome profile: ${i[0].profileName}`);else{let a=i.length===1?`Found 1 Slack session across ${c} Chrome profiles:`:`Found ${i.length} Slack sessions across ${c} Chrome profiles:`;console.log(a),i.forEach((h,m)=>console.log(` ${m+1}) ${h.profileName} [${h.profileDir}]`)),console.log("");let l=Ie({input:process.stdin,output:process.stdout}),u=i.length===1?" [Enter=1]":"",d=(await l.question(`Choice [1-${i.length}]${u}: `)).trim();l.close();let f=d===""&&i.length===1?0:parseInt(d,10)-1;if(isNaN(f)||f<0||f>=i.length)console.error("Invalid choice."),process.exit(1);s=i[f].cookie}}wr(n,s),console.log(`Saved xoxd cookie to workspace "${n}".`),console.log("RTM WebSocket mode is now available: slack tail @you")}async function jr(e={}){console.error("Scanning Chrome profiles for Slack sessions...");let t=Or();if(t.length===0)console.error("No Slack session found in Chrome."),console.error(" Open Slack in Chrome (https://app.slack.com) and sign in, then retry."),process.exit(1);let n;if(e.profile){let r=e.profile,i=t.find((c)=>c.email===r||c.profileDir===r||c.profileDir===`Profile ${r}`);if(!i)console.error(`Chrome profile "${r}" has no Slack session. Available:`),t.forEach((c)=>console.error(` - ${c.email??c.label} [${c.profileDir}] (${c.sessions.length} workspace${c.sessions.length!==1?"s":""})`)),process.exit(1);n=i}else if(t.length===1)n=t[0];else if(process.stdin.isTTY){console.log("Found Slack sessions in multiple Chrome profiles:"),t.forEach((a,l)=>console.log(` ${l+1}) ${a.email??a.label} [${a.profileDir}] (${a.sessions.length} workspace${a.sessions.length!==1?"s":""})`));let r=Ie({input:process.stdin,output:process.stdout}),i=(await r.question(`Choice [1-${t.length}]: `)).trim();r.close();let c=parseInt(i,10)-1;if(isNaN(c)||c<0||c>=t.length)console.error("Invalid choice."),process.exit(1);n=t[c]}else console.error("Multiple Chrome profiles have a Slack session — choose one with --profile:"),t.forEach((r)=>console.error(` slack auth login chrome --profile "${r.email??r.profileDir}"`)),process.exit(1);let o=n.email??n.label??n.profileDir,s;if(process.platform==="darwin")try{let{candidates:r}=Jn();s=r.find((i)=>i.profileDir===n.profileDir)?.cookie??r[0]?.cookie}catch{}if(s)Ic(o,s,`chrome:${n.profileDir}`);for(let r of n.sessions){let i=r.teamName??r.teamId,c=gn(i);Os(c,{token:r.token,team:i,teamId:r.teamId,url:r.url??"",user:"",identity:o}),console.log(`Added workspace "${c}": ${i} (identity: ${o})`)}if(console.log(""),s)console.log(`Captured xoxd cookie for ${o} — shared across its ${n.sessions.length} workspace(s).`),console.log("RTM WebSocket mode is now available: slack tail @you");else console.log("Note: no xoxd cookie captured (LocalStorage yields the token only; the cookie is"),console.log("encrypted at rest on this platform). Some features (RTM, drafts, search fallback) need it."),console.log(" Attach it from your live browser — e.g. a CDP read via rech — or paste it:"),console.log(` slack auth cookie --workspace ${gn(n.sessions[0].teamName??n.sessions[0].teamId)}`);console.log(""),console.log("Select a workspace: slack auth use <name> (see: slack auth ls)")}async function Wr(e={}){let t=Bn();if(t.length===0)console.error("No workspaces configured. Run: slack auth login"),process.exit(1);let n;if(e.workspace){if(!t.find((c)=>c.name===e.workspace))console.error(`Workspace "${e.workspace}" not found. Available: ${t.map((c)=>c.name).join(", ")}`),process.exit(1);n=e.workspace}else if(t.length===1)n=t[0].name;else{let i=t.find((c)=>c.current);if(i)n=i.name,console.log(`Using active workspace: ${n}`);else{console.log("Multiple workspaces found. Choose one:"),t.forEach((u,d)=>console.log(` ${d+1}) ${u.name} (${u.profile.team})`));let c=Ie({input:process.stdin,output:process.stdout}),a=(await c.question("Choice: ")).trim();c.close();let l=parseInt(a,10)-1;if(isNaN(l)||l<0||l>=t.length)console.error("Invalid choice."),process.exit(1);n=t[l].name}}if(!e.yes&&!process.stdin.isTTY)console.error("Reading browser profiles requires confirmation. Re-run interactively or pass --yes."),process.exit(1);let o=e.yes?void 0:Ie({input:process.stdin,output:process.stdout});try{if(!await Hn(o,e.yes??!1)){console.log("Browser profile scan cancelled.");return}}finally{o?.close()}console.log("Scanning Firefox profiles for Slack session...");let s=Hs();if(s.length===0)console.error("No Slack session found in Firefox. Possible reasons:"),console.error(" - Firefox is not installed"),console.error(" - You are not logged in to Slack in Firefox"),process.exit(1);let r;if(s.length===1)r=s[0].cookie,console.log(`Found session in Firefox profile: ${s[0].profileName}`);else{console.log("Multiple Firefox profiles have a Slack session. Choose one:"),s.forEach((l,u)=>console.log(` ${u+1}) ${l.profileName} [${l.profileDir}]`));let i=Ie({input:process.stdin,output:process.stdout}),c=(await i.question("Choice: ")).trim();i.close();let a=parseInt(c,10)-1;if(isNaN(a)||a<0||a>=s.length)console.error("Invalid choice."),process.exit(1);r=s[a].cookie}wr(n,r),console.log(`Saved xoxd cookie to workspace "${n}".`),console.log("RTM WebSocket mode is now available: slack tail @you")}async function il(e={}){if(e.token){await qt(null,e.token,e.name);return}if(!process.stdin.isTTY){let n=[];for await(let s of process.stdin)n.push(s);let o=Buffer.concat(n).toString("utf8").trim();if(!o)console.error("No token provided on stdin."),process.exit(1);await qt(null,o,e.name);return}let t=Ie({input:process.stdin,output:process.stdout});try{await ol(t)}finally{t.close()}}async function al(e={}){let t=Ie({input:process.stdin,output:process.stdout});try{if(e.bot!==void 0){await qs(t,e.bot?"bot":"user");return}console.log("Which token type?"),console.log(" 1) User token (xoxp-) -full access including search [default]"),console.log(" 2) Bot token (xoxb-) -search and news unavailable"),console.log("");let n=await Et(t,"Choice [1/2, Enter=1]: ");await qs(t,n==="2"?"bot":"user")}finally{t.close()}}function cl(e={}){let t=(s,r)=>{if(/[\r\n]/.test(r))throw Error(`Invalid newline in ${s}.`);return`${s}=${/^[A-Za-z0-9._=-]+$/.test(r)?r:JSON.stringify(r)}`},n=[t("SLACK_TOKEN",Oc(e.workspace))],o=xt(e.workspace);if(o)n.push(t("SLACK_COOKIE",o));if(!e.workspace){let s=Ps();if(s)n.push(t("SLACK_BOT_TOKEN",s))}console.log(n.join(`
227
+ `))}function ll(e){let t=Bn(),n=e.workspace?t.find((s)=>s.name===e.workspace):t.find((s)=>s.current)??(t.length===1?t[0]:void 0);if(!n)throw Error(e.workspace?`Workspace "${e.workspace}" not found. Run: slack auth ls`:"Select a workspace with slack auth use <name>, or pass --workspace <name>.");if(!n.profile.cookie)throw Error(`Workspace "${n.name}" has no session cookie. Run: slack auth chrome -w ${n.name} or slack auth firefox -w ${n.name}`);let o=Vp(e.envfile);yr(o,{SLACK_TOKEN:n.profile.token,SLACK_COOKIE:n.profile.cookie}),console.log(`Saved token and cookie for workspace "${n.name}" to ${o}`)}async function zn(e={}){let t=Bn();if(t.length>0){console.log("Currently logged in:");for(let{name:o,profile:s,current:r}of t)console.log(` ${r?"*":" "} ${o} ${s.team} (${s.user||"unknown"})`);console.log(""),console.log("Adding another workspace:"),console.log("")}if([e.fromChrome,e.fromFirefox,e.fromAll].filter(Boolean).length>1)throw Error("Choose only one browser source: --from-chrome, --from-firefox, or --from-all.");if(e.fromChrome&&!e.fromDesktop){if(!e.yes&&!process.stdin.isTTY)throw Error("Reading browser profiles requires confirmation. Re-run interactively or pass --yes.");let o=process.stdin.isTTY?Ie({input:process.stdin,output:process.stdout}):void 0;try{if(!await Hn(o,e.yes??!1)){console.log("Browser profile scan cancelled.");return}let s=await Rr();if(s.length===0)throw Error("No Slack session token found in Chrome profiles.");await Mr(s,o,!0)}finally{o?.close()}return}if(e.fromAll&&!e.fromDesktop){if(!e.yes&&!process.stdin.isTTY)throw Error("Reading browser profiles requires confirmation. Re-run interactively or pass --yes.");let o=process.stdin.isTTY?Ie({input:process.stdin,output:process.stdout}):void 0;try{try{await Lr(o,e.yes??!1,"all",!0)}catch(s){if(!(s instanceof Error)||!s.message.startsWith("Slack desktop app LevelDB not found"))throw s;if(!await Hn(o,e.yes??!1)){console.log("Browser profile scan cancelled.");return}let r=await Rr();if(r.length===0)throw Error("No Slack session token found in Chrome profiles.");if(r.every((i)=>!i.cookie)){let i=Hs();if(i.length===1)for(let c of r)c.cookie=i[0].cookie}await Mr(r,o,!0)}}finally{o?.close()}return}if(e.fromDesktop||e.fromChrome||e.fromFirefox||e.fromAll){let o=e.fromChrome?"chrome":e.fromFirefox?"firefox":e.fromAll?"all":"none";if(o!=="none"&&!e.yes&&!process.stdin.isTTY)throw Error("Reading browser profiles requires confirmation. Re-run interactively or pass --yes.");let s=process.stdin.isTTY?Ie({input:process.stdin,output:process.stdout}):void 0;try{await Lr(s,e.yes??!1,o,!0)}finally{s?.close()}return}if(e.token){await qt(null,e.token,e.name);return}if(!process.stdin.isTTY){let o=[];for await(let r of process.stdin)o.push(r);let s=Buffer.concat(o).toString("utf8").trim();if(!s)console.error("No token provided on stdin."),process.exit(1);await qt(null,s,e.name);return}console.log("How would you like to authenticate with Slack?"),console.log(""),console.log(" 1) Slack desktop app - import session token"),console.log(" Reads the xoxc- token directly from the installed app."),console.log(" Token: all platforms | xoxd cookie: macOS, or Chrome/Firefox on Linux"),console.log(""),console.log(" 2) Chrome browser - import workspaces"),console.log(" Reads xoxc- tokens from Chrome, grouped by account."),console.log(" Token: all platforms | xoxd cookie: macOS only"),console.log(""),console.log(" 3) Connect existing Slack app [recommended if you have one]"),console.log(" Paste a token from an app you already created."),console.log(""),console.log(" 4) Create new Slack app - user token (xoxp-)"),console.log(" Guided setup with manifest. Full access including search."),console.log(""),console.log(" 5) Create new Slack app - bot token (xoxb-)"),console.log(" Bot is invited to channels. Search and news unavailable."),console.log("");let n=Ie({input:process.stdin,output:process.stdout});try{let o=await Et(n,"Choice [1/2/3/4/5]: ");if(console.log(""),o==="1")await Lr(n,e.yes??!1);else if(o==="2"){n.close(),await jr();return}else if(o==="3")await ol(n);else if(o==="4")await qs(n,"user");else if(o==="5")await qs(n,"bot");else console.error(`Invalid choice: "${o}". Enter 1, 2, 3, 4, or 5.`),process.exit(1)}finally{n.close()}}async function Gs(e,t,n,o){let s=t,r=[],i=s,c=0;while(!0){let a=i.indexOf("<@U",c);if(a===-1)break;let l=i.slice(a+2),u=l.search(/[>|]/),d=u===-1?l:l.slice(0,u);if(d.length>=9)r.push(d);c=a+1}for(let a of r){if(!n.has(a))n.set(a,await Ms(e,a,o));let l=n.get(a)??a;s=s.replaceAll(`<@${a}>`,`@${l}`),s=s.replace(new RegExp(`<@${a}\\|[^>]*>`,"g"),`@${l}`)}return s}function Xs(e){return e.replace(/<!date\^(\d+)\^[^|>]*(?:\|([^>]*))?>/g,(t,n,o)=>{let s=Number(n);if(!Number.isFinite(s))return o??"date";let r=new Date(s*1000);if(Number.isNaN(r.getTime()))return o??"date";let i=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],c=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],a=i[r.getUTCDay()]??"",l=c[r.getUTCMonth()]??"";return`${a}, ${l} ${String(r.getUTCDate()).padStart(2,"0")}, ${r.getUTCFullYear()}`})}function dl(e){let t=typeof e.ts==="string"?e.ts:"",n=typeof e.thread_ts==="string"?e.thread_ts:"";return n!==""&&n!==t}function oh(e){let[t,n="000000"]=e.split("."),o=new Date(Number(t)*1000),s=o.getUTCFullYear(),r=String(o.getUTCMonth()+1).padStart(2,"0"),i=String(o.getUTCDate()).padStart(2,"0"),c=String(o.getUTCHours()).padStart(2,"0"),a=String(o.getUTCMinutes()).padStart(2,"0"),l=String(o.getUTCSeconds()).padStart(2,"0"),u=n.padEnd(6,"0").slice(0,6);return`${s}-${r}-${i}T${c}:${a}:${l}.${u}`}async function rh(e,t,n){let o=typeof t.ts==="string"?t.ts:"0.000000",s=oh(o),r="?";if(typeof t.user==="string"){let d=t.user,f="@"+d;if(!n.has(f)){let[,h]=await Ls(e,d);n.set(f,h)}r=n.get(f)??d}else if(typeof t.username==="string")r=t.username;let i=typeof t.text==="string"?t.text:"",a=Xs(await Gs(e,i,n)).split(`
223
228
  `),l=a[0]+(a.length>1?`
224
229
  `+a.slice(1).map((d)=>` ${d}`).join(`
225
- `):""),u=il(t)?"↳ ":"";return`${s} ${u}@${r}: ${l}`}async function Hp(e,t,n,o,s,r,i,c){if(c?.aborted)return;return new Promise((a)=>{let l=new e(n);c?.addEventListener("abort",()=>{l.close(),a()},{once:!0}),l.addEventListener("open",()=>{process.stderr.write(`Connected via RTM (experimental).
226
- `)}),l.addEventListener("close",()=>a()),l.addEventListener("error",()=>a()),l.addEventListener("message",(u)=>{(async()=>{try{let d;try{d=JSON.parse(String(u.data))}catch{return}let f=typeof d.type==="string"?d.type:"";if(f==="ping"){l.send(JSON.stringify({type:"pong",reply_to:d.id??0}));return}if(f!=="message")return;if((typeof d.channel==="string"?d.channel:"")!==o)return;let m=typeof d.ts==="string"?d.ts:"";if(!m||r.has(m))return;let p=typeof d.subtype==="string"?d.subtype:"";if(p==="message_changed"||p==="message_deleted")return;if(s.thread){if((typeof d.thread_ts==="string"?d.thread_ts:m)!==s.thread&&m!==s.thread)return}if(s.watchThread&&il(d)){if((typeof d.thread_ts==="string"?d.thread_ts:"")!==s.watchThread)return}if(s.me&&s.myUserId){if(!(typeof d.text==="string"?d.text:"").includes(`<@${s.myUserId}>`))return}if(r.add(m),r.size>1000){let k=r.values().next().value;if(k!==void 0)r.delete(k)}let D=await Kp(t,d,i);process.stdout.write(D+`
230
+ `):""),u=dl(t)?"↳ ":"";return`${s} ${u}@${r}: ${l}`}async function ih(e,t,n,o,s,r,i,c){if(c?.aborted)return;return new Promise((a)=>{let l=new e(n);c?.addEventListener("abort",()=>{l.close(),a()},{once:!0}),l.addEventListener("open",()=>{process.stderr.write(`Connected via RTM (experimental).
231
+ `)}),l.addEventListener("close",()=>a()),l.addEventListener("error",()=>a()),l.addEventListener("message",(u)=>{(async()=>{try{let d;try{d=JSON.parse(String(u.data))}catch{return}let f=typeof d.type==="string"?d.type:"";if(f==="ping"){l.send(JSON.stringify({type:"pong",reply_to:d.id??0}));return}if(f!=="message")return;if((typeof d.channel==="string"?d.channel:"")!==o)return;let m=typeof d.ts==="string"?d.ts:"";if(!m||r.has(m))return;let p=typeof d.subtype==="string"?d.subtype:"";if(p==="message_changed"||p==="message_deleted")return;if(s.thread){if((typeof d.thread_ts==="string"?d.thread_ts:m)!==s.thread&&m!==s.thread)return}if(s.watchThread&&dl(d)){if((typeof d.thread_ts==="string"?d.thread_ts:"")!==s.watchThread)return}if(s.me&&s.myUserId){if(!(typeof d.text==="string"?d.text:"").includes(`<@${s.myUserId}>`))return}if(r.add(m),r.size>1000){let k=r.values().next().value;if(k!==void 0)r.delete(k)}let D=await rh(t,d,i);process.stdout.write(D+`
227
232
  `)}catch(d){process.stderr.write(`RTM message error: ${d instanceof Error?d.message:String(d)}
228
- `)}})()})})}var rl=3,zp=2000,vr={sleep:(e)=>new Promise((t)=>setTimeout(t,e)),clientBoot:jc,getWebSocket:()=>{let e=globalThis.WebSocket;return typeof e==="function"?e:void 0}};async function al(e,t,n,o,s,r,i){let c=vr.getWebSocket();if(!c)return;for(let a=0;a<rl;a++){if(i?.aborted)return;try{let{wsUrl:l}=await vr.clientBoot(e,t);await Hp(c,e,l,n,o,s,r,i)}catch{}if(i?.aborted)return;if(a<rl-1)await vr.sleep(zp)}}function cl(e){let t=e.match(/^(\d+(?:\.\d+)?)(s|m|h|d)$/);if(!t)throw Error(`Invalid --since format: "${e}" (expected e.g. 10m, 2h, 1d)`);let n=parseFloat(t[1]);switch(t[2]){case"s":return n;case"m":return n*60;case"h":return n*3600;case"d":return n*86400}}var tt={sleep:(e)=>new Promise((t)=>setTimeout(t,e)),now:()=>Date.now(),tailRTM:al};function ut(e){return e&&typeof e==="object"&&!Array.isArray(e)?e:{}}function Lr(e){return Array.isArray(e)?e:[]}function ll(e){return Number(e)||0}function ul(e){let t=typeof e.ts==="string"?e.ts:"",n=typeof e.thread_ts==="string"?e.thread_ts:"";return n!==""&&n!==t}function qp(e){let[t,n="000000"]=e.split("."),o=new Date(Number(t)*1000),s=o.getUTCFullYear(),r=String(o.getUTCMonth()+1).padStart(2,"0"),i=String(o.getUTCDate()).padStart(2,"0"),c=String(o.getUTCHours()).padStart(2,"0"),a=String(o.getUTCMinutes()).padStart(2,"0"),l=String(o.getUTCSeconds()).padStart(2,"0"),u=n.padEnd(6,"0").slice(0,6);return`${s}-${r}-${i}T${c}:${a}:${l}.${u}`}async function Gp(e,t,n,o,s){let r=typeof t.ts==="string"?t.ts:"0.000000",i=qp(r),c="?";if(typeof t.user==="string"){let m=t.user,p="@"+m;if(!n.has(p)){let[,D]=await Bs(e,m,s);n.set(p,D)}c=n.get(p)??m}else if(typeof t.username==="string")c=t.username;let a=typeof t.text==="string"?t.text:"",u=qs(await zs(e,a,n,s)).split(`
233
+ `)}})()})})}var ul=3,ah=2000,Ur={sleep:(e)=>new Promise((t)=>setTimeout(t,e)),clientBoot:Hc,getWebSocket:()=>{let e=globalThis.WebSocket;return typeof e==="function"?e:void 0}};async function fl(e,t,n,o,s,r,i){let c=Ur.getWebSocket();if(!c)return;for(let a=0;a<ul;a++){if(i?.aborted)return;try{let{wsUrl:l}=await Ur.clientBoot(e,t);await ih(c,e,l,n,o,s,r,i)}catch{}if(i?.aborted)return;if(a<ul-1)await Ur.sleep(ah)}}function pl(e){let t=e.match(/^(\d+(?:\.\d+)?)(s|m|h|d)$/);if(!t)throw Error(`Invalid --since format: "${e}" (expected e.g. 10m, 2h, 1d)`);let n=parseFloat(t[1]);switch(t[2]){case"s":return n;case"m":return n*60;case"h":return n*3600;case"d":return n*86400}}var nt={sleep:(e)=>new Promise((t)=>setTimeout(t,e)),now:()=>Date.now(),tailRTM:fl};function dt(e){return e&&typeof e==="object"&&!Array.isArray(e)?e:{}}function Jr(e){return Array.isArray(e)?e:[]}function hl(e){return Number(e)||0}function gl(e){let t=typeof e.ts==="string"?e.ts:"",n=typeof e.thread_ts==="string"?e.thread_ts:"";return n!==""&&n!==t}function ch(e){let[t,n="000000"]=e.split("."),o=new Date(Number(t)*1000),s=o.getUTCFullYear(),r=String(o.getUTCMonth()+1).padStart(2,"0"),i=String(o.getUTCDate()).padStart(2,"0"),c=String(o.getUTCHours()).padStart(2,"0"),a=String(o.getUTCMinutes()).padStart(2,"0"),l=String(o.getUTCSeconds()).padStart(2,"0"),u=n.padEnd(6,"0").slice(0,6);return`${s}-${r}-${i}T${c}:${a}:${l}.${u}`}async function lh(e,t,n,o,s){let r=typeof t.ts==="string"?t.ts:"0.000000",i=ch(r),c="?";if(typeof t.user==="string"){let m=t.user,p="@"+m;if(!n.has(p)){let[,D]=await Ls(e,m,s);n.set(p,D)}c=n.get(p)??m}else if(typeof t.username==="string")c=t.username;let a=typeof t.text==="string"?t.text:"",u=Xs(await Gs(e,a,n,s)).split(`
229
234
  `),d=u[0]+(u.length>1?`
230
235
  `+u.slice(1).map((m)=>` ${m}`).join(`
231
- `):""),f=ul(t)?"↳ ":"",h=o?`${o} @${c}`:`@${c}`;return`${i} ${f}${h}: ${d}`}async function Xp(e,t,n,o,s,r,i){let c=ut(await vn(e,t,20,i?void 0:n||void 0,i,o.cookie)),a=Lr(c.messages).map(ut).reverse(),l=ut(c.response_metadata),u=c.has_more===!0&&typeof l.next_cursor==="string"?l.next_cursor:void 0,d=[];if(o.watchThread&&!i){let D=ut(await Nc(e,t,o.watchThread,50,o.cookie));d=Lr(D.messages).map(ut).filter((k)=>(typeof k.ts==="string"?k.ts:"")!==o.watchThread)}let f=[...a.map((D)=>({m:D,fromHistory:!0})),...d.map((D)=>({m:D,fromHistory:!1}))].sort((D,k)=>ll(typeof D.m.ts==="string"?D.m.ts:"")-ll(typeof k.m.ts==="string"?k.m.ts:"")),h=[],m=n,p=!1;for(let{m:D,fromHistory:k}of f){let x=typeof D.ts==="string"?D.ts:"";if(!x||s.has(x))continue;let E=typeof D.subtype==="string"?D.subtype:"";if(E==="message_changed"||E==="message_deleted")continue;if(o.thread){if((typeof D.thread_ts==="string"?D.thread_ts:x)!==o.thread&&x!==o.thread)continue}if(o.watchThread&&ul(D)){if((typeof D.thread_ts==="string"?D.thread_ts:"")!==o.watchThread)continue}if(o.me&&o.myUserId){if(!(typeof D.text==="string"?D.text:"").includes(`<@${o.myUserId}>`))continue}if(s.add(x),s.size>1000){let N=s.values().next().value;if(N!==void 0)s.delete(N)}if(h.push(await Gp(e,D,r,void 0,o.cookie)),k)m=x;let F=typeof D.user==="string"?D.user:"";if(!o.myUserId||F!==o.myUserId)p=!0}return{newCursor:m,lines:h,hasMore:c.has_more===!0,nextPageCursor:u,emittedOther:p}}function Yp(e){if(e.includes("slack.com")){let t=kr(e),n=t?.threadTs??t?.ts;if(n)return n;throw Error(`--watch-thread: could not extract a timestamp from "${e}"`)}if(/^\d{10}\.\d{6}$/.test(e))return e;if(/^\d{16}$/.test(e))return`${e.slice(0,10)}.${e.slice(10)}`;throw Error(`--watch-thread: "${e}" is not a valid ts or permalink`)}async function dl(e,t,n={},o){if(n.me&&!t)console.error(`slack tail --me requires a <target> channel.
236
+ `):""),f=gl(t)?"↳ ":"",h=o?`${o} @${c}`:`@${c}`;return`${i} ${f}${h}: ${d}`}async function uh(e,t,n,o,s,r,i){let c=dt(await Mn(e,t,20,i?void 0:n||void 0,i,o.cookie)),a=Jr(c.messages).map(dt).reverse(),l=dt(c.response_metadata),u=c.has_more===!0&&typeof l.next_cursor==="string"?l.next_cursor:void 0,d=[];if(o.watchThread&&!i){let D=dt(await jc(e,t,o.watchThread,50,o.cookie));d=Jr(D.messages).map(dt).filter((k)=>(typeof k.ts==="string"?k.ts:"")!==o.watchThread)}let f=[...a.map((D)=>({m:D,fromHistory:!0})),...d.map((D)=>({m:D,fromHistory:!1}))].sort((D,k)=>hl(typeof D.m.ts==="string"?D.m.ts:"")-hl(typeof k.m.ts==="string"?k.m.ts:"")),h=[],m=n,p=!1;for(let{m:D,fromHistory:k}of f){let x=typeof D.ts==="string"?D.ts:"";if(!x||s.has(x))continue;let C=typeof D.subtype==="string"?D.subtype:"";if(C==="message_changed"||C==="message_deleted")continue;if(o.thread){if((typeof D.thread_ts==="string"?D.thread_ts:x)!==o.thread&&x!==o.thread)continue}if(o.watchThread&&gl(D)){if((typeof D.thread_ts==="string"?D.thread_ts:"")!==o.watchThread)continue}if(o.me&&o.myUserId){if(!(typeof D.text==="string"?D.text:"").includes(`<@${o.myUserId}>`))continue}if(s.add(x),s.size>1000){let N=s.values().next().value;if(N!==void 0)s.delete(N)}if(h.push(await lh(e,D,r,void 0,o.cookie)),k)m=x;let F=typeof D.user==="string"?D.user:"";if(!o.myUserId||F!==o.myUserId)p=!0}return{newCursor:m,lines:h,hasMore:c.has_more===!0,nextPageCursor:u,emittedOther:p}}function dh(e){if(e.includes("slack.com")){let t=Sr(e),n=t?.threadTs??t?.ts;if(n)return n;throw Error(`--watch-thread: could not extract a timestamp from "${e}"`)}if(/^\d{10}\.\d{6}$/.test(e))return e;if(/^\d{16}$/.test(e))return`${e.slice(0,10)}.${e.slice(10)}`;throw Error(`--watch-thread: "${e}" is not a valid ts or permalink`)}async function ml(e,t,n={},o){if(n.me&&!t)console.error(`slack tail --me requires a <target> channel.
232
237
  Cross-channel mention streaming is not yet supported.
233
- Use: slack tail "#channel" --me`),process.exit(1);if(!t)console.error("Usage: slack tail <#channel|@user>\n Run `slack tail --help` for details."),process.exit(1);let s=await Ns(e,t,n.cookie),r=n.interval??60000,i=n.timeout?tt.now()+cl(n.timeout)*1000:1/0,c=new Map,a=new Set;try{let p=ut(await Lc(e,s,n.cookie));if(ut(p.channel).is_archived===!0)console.error("Warning: this channel is archived — no new messages will arrive.")}catch(p){let D=p instanceof Error?p.message:String(p);if(D.includes("not_in_channel"))console.error("Error: you are not a member of that channel. Join it in Slack first, then retry."),process.exit(1);if(D.includes("missing_scope"))console.error("Error: token lacks the required history scope. Check your token's channels:history (or groups:history) permission."),process.exit(1);if(D.includes("channel_not_found"))console.error("Error: channel not found — it may be a private channel inaccessible with your token."),process.exit(1);console.error(`Warning: preflight check failed: ${D}`)}let l="";if(n.since){let p=cl(n.since);l=(tt.now()/1000-p).toFixed(6)}else{let p=ut(await vn(e,s,1,void 0,void 0,n.cookie)),D=Lr(p.messages).map(ut);if(D.length>0&&typeof D[0]?.ts==="string")l=D[0].ts,a.add(l);else l=(tt.now()/1000).toFixed(6)}let u;if(n.me||n.exitOnMessage)u=(await pn(e,n.cookie)).userId||void 0;let d;if(n.watchThread!==void 0)try{d=Yp(n.watchThread)}catch(p){console.error(p instanceof Error?p.message:String(p)),process.exit(1)}let f={...n.thread!==void 0?{thread:n.thread}:{},...d!==void 0?{watchThread:d}:{},...n.me!==void 0?{me:n.me}:{},...u!==void 0?{myUserId:u}:{},...n.cookie!==void 0?{cookie:n.cookie}:{}};if(e.startsWith("xoxc-")&&n.cookie!==void 0&&n.noRtm!==!0&&n.since===void 0&&n.timeout===void 0&&n.exitOnMessage!==!0){if(await tt.tailRTM(e,n.cookie,s,f,a,c,o),o?.aborted)return;console.error("RTM unavailable — switching to polling.")}let h=!0,m=tt.now();while(!o?.aborted){if(tt.now()>=i)return;let p=!1;try{let x=tt.now()-m,E=r>0&&x>r*5,F,N=!0;do{let{newCursor:W,lines:O,nextPageCursor:v,emittedOther:J}=await Xp(e,s,l,f,a,c,F);if(l=W,h&&N&&n.since&&O.length===0)process.stdout.write(`(no messages in the last ${n.since} — watching for new)
238
+ Use: slack tail "#channel" --me`),process.exit(1);if(!t)console.error("Usage: slack tail <#channel|@user>\n Run `slack tail --help` for details."),process.exit(1);let s=await vs(e,t,n.cookie),r=n.interval??60000,i=n.timeout?nt.now()+pl(n.timeout)*1000:1/0,c=new Map,a=new Set;try{let p=dt(await Kc(e,s,n.cookie));if(dt(p.channel).is_archived===!0)console.error("Warning: this channel is archived — no new messages will arrive.")}catch(p){let D=p instanceof Error?p.message:String(p);if(D.includes("not_in_channel"))console.error("Error: you are not a member of that channel. Join it in Slack first, then retry."),process.exit(1);if(D.includes("missing_scope"))console.error("Error: token lacks the required history scope. Check your token's channels:history (or groups:history) permission."),process.exit(1);if(D.includes("channel_not_found"))console.error("Error: channel not found — it may be a private channel inaccessible with your token."),process.exit(1);console.error(`Warning: preflight check failed: ${D}`)}let l="";if(n.since){let p=pl(n.since);l=(nt.now()/1000-p).toFixed(6)}else{let p=dt(await Mn(e,s,1,void 0,void 0,n.cookie)),D=Jr(p.messages).map(dt);if(D.length>0&&typeof D[0]?.ts==="string")l=D[0].ts,a.add(l);else l=(nt.now()/1000).toFixed(6)}let u;if(n.me||n.exitOnMessage)u=(await hn(e,n.cookie)).userId||void 0;let d;if(n.watchThread!==void 0)try{d=dh(n.watchThread)}catch(p){console.error(p instanceof Error?p.message:String(p)),process.exit(1)}let f={...n.thread!==void 0?{thread:n.thread}:{},...d!==void 0?{watchThread:d}:{},...n.me!==void 0?{me:n.me}:{},...u!==void 0?{myUserId:u}:{},...n.cookie!==void 0?{cookie:n.cookie}:{}};if(e.startsWith("xoxc-")&&n.cookie!==void 0&&n.noRtm!==!0&&n.since===void 0&&n.timeout===void 0&&n.exitOnMessage!==!0){if(await nt.tailRTM(e,n.cookie,s,f,a,c,o),o?.aborted)return;console.error("RTM unavailable — switching to polling.")}let h=!0,m=nt.now();while(!o?.aborted){if(nt.now()>=i)return;let p=!1;try{let x=nt.now()-m,C=r>0&&x>r*5,F,N=!0;do{let{newCursor:W,lines:O,nextPageCursor:L,emittedOther:J}=await uh(e,s,l,f,a,c,F);if(l=W,h&&N&&n.since&&O.length===0)process.stdout.write(`(no messages in the last ${n.since} — watching for new)
234
239
  `);N=!1;for(let Q of O)process.stdout.write(Q+`
235
- `);if(J)p=!0;F=E?v:void 0}while(F);h=!1}catch(k){if(k instanceof Qe){console.error(`Warning: Slack rate limit hit — backing off for ${k.retryAfter}s`),await tt.sleep(k.retryAfter*1000);continue}throw k}if(n.exitOnMessage&&p)return;m=tt.now();let D=i-tt.now();if(D<=0)return;await tt.sleep(Math.min(r,D))}}import{spawn as Vp}from"node:child_process";import{constants as fl}from"node:os";var Zp=["processing","active","suspended","closed"];function pl(e){if(e!==void 0&&!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e))throw Error("--bot-token-env must name an environment variable, not contain a token.");let t=e===void 0?Os():process.env[e];if(!t?.startsWith("xoxb-"))throw Error("Agent commands require a bot token (xoxb). Set SLACK_BOT_TOKEN or --bot-token-env NAME; user tokens are refused.");return t}function hl(e){if(e!==void 0&&(!e.trim()||[...e].length>200))throw Error("--title must contain 1–200 characters.")}async function gl(e,t,n){let{ref:o,threadTs:s}=n(t);if(!s||!/^\d{10}\.\d{6}$/.test(s))throw Error("Target must include a thread root: C00000001:1700000000.000100, #channel:ts, or a message permalink.");return{channel_id:await Ns(e,o),thread_ts:s}}function jr(e,t){console.error(`agent: ${e}: ${t instanceof Error?t.message:"request failed"}`)}async function Qp(e,t,n,o){let s,r,i,c,a,l=!1,u=!1,d=1,f=(p)=>{if(r)return;if(r=p,l=!0,s&&s.exitCode===null&&s.signalCode===null)s.kill(p),i=setTimeout(()=>s?.kill("SIGKILL"),5000)},h=()=>f("SIGINT"),m=()=>f("SIGTERM");process.on("SIGINT",h),process.on("SIGTERM",m);try{if(u=!0,await Mn(e,t,"processing"),!l&&o.title!==void 0)await br(e,t,o.title);if(!l){s=Vp(n[0],n.slice(1),{stdio:"inherit"});let p=new Promise((D)=>{s.once("error",()=>{console.error("agent: could not start command"),D(127)}),s.once("exit",(k,x)=>{D(k??(x?128+fl.signals[x]:1))})});c=setInterval(()=>{if(l||a)return;a=Mn(e,t,"processing").then(()=>{}).catch((D)=>jr("heartbeat failed; retrying on next tick",D)).finally(()=>{a=void 0})},o.every*1000),d=await p}}catch(p){jr("could not start agent session",p)}finally{if(l=!0,clearInterval(c),clearTimeout(i),await a,u)try{await Mn(e,t,o.close?"closed":"active")}catch(p){if(jr("final status clear failed",p),d===0)d=1}process.removeListener("SIGINT",h),process.removeListener("SIGTERM",m)}return r?128+fl.signals[r]:d}function ml(e,t){let n=(o)=>o.positional("target",{type:"string",demandOption:!0,describe:"Thread root: raw channel ID:ts (avoids listing), #channel:ts, or permalink"}).option("title",{type:"string",describe:"Rename the session (1–200 characters)"}).option("bot-token-env",{type:"string",describe:"Environment variable holding an agent-enabled app's xoxb token (default SLACK_BOT_TOKEN); requires chat:write and channel membership"});return e.command("status <target> <status>","Set a bot agent session's status",(o)=>n(o).positional("status",{type:"string",choices:Zp,demandOption:!0}),async(o)=>{hl(o.title);let s=pl(o["bot-token-env"]),r=await gl(s,o.target,t);if(await Mn(s,r,o.status),o.title!==void 0)await br(s,r,o.title)}).command("run <target>","Keep a thread working while a command runs: run <target> -- <command...>",(o)=>n(o).parserConfiguration({"populate--":!0}).option("every",{type:"number",default:300,describe:"Heartbeat seconds (>0 and <3600); processing expires after one hour"}).option("close",{type:"boolean",default:!1,describe:"Finish with closed instead of active (also on failure or interrupt)"}),async(o)=>{if(hl(o.title),!Number.isFinite(o.every)||o.every<=0||o.every>=3600)throw Error("--every must be greater than 0 and less than 3600 seconds.");let s=process.argv.indexOf("--"),r=s<0?[]:process.argv.slice(s+1);if(!r[0])throw Error("agent run requires -- <command...>");let i=pl(o["bot-token-env"]),c=await gl(i,o.target,t);process.exitCode=await Qp(i,c,r,{every:o.every,close:o.close,...o.title!==void 0?{title:o.title}:{}})}).demandCommand(1,"Choose agent status or agent run.")}var ze=[{name:"one",glyph:"1️⃣"},{name:"two",glyph:"2️⃣"},{name:"three",glyph:"3️⃣"},{name:"four",glyph:"4️⃣"},{name:"five",glyph:"5️⃣"},{name:"six",glyph:"6️⃣"},{name:"seven",glyph:"7️⃣"},{name:"eight",glyph:"8️⃣"},{name:"nine",glyph:"9️⃣"},{name:"keycap_ten",glyph:"\uD83D\uDD1F"}],Xs=ze.length,Ys="question";function Ur(e){let t=e.split(`
236
- `),n=t[t.length-2];if(n===void 0||!n.startsWith("_:warning: 同時に複数選ばれているため回答として数えていません — どれか 1 つだけ残してください: ")||!n.endsWith("_"))return[];return[...n.matchAll(/<@([UW][A-Z0-9]+)>/g)].map((o)=>o[1])}function Jr(e,t){let n=e.split(`
237
- `);if(n.length<2)return e;if(Ur(e).length)n.splice(n.length-2,1);if(t.length)n.splice(n.length-1,0,`${"_:warning: 同時に複数選ばれているため回答として数えていません — どれか 1 つだけ残してください: "}${t.map((s)=>`<@${s}>`).join(", ")}_`);let o=n.join(`
238
- `);return o===e?e:o}function eh(e){return e!==void 0&&e.startsWith("_:warning: 同時に複数選ばれているため回答として数えていません — どれか 1 つだけ残してください: ")&&e.endsWith("_")}var Kr="white_check_mark",Gs=`:${Kr}: `;function yl(e){return`:${ze[e].name}:`}function wl(e,t){let n=ze[t];for(let o of[yl(t),n.glyph]){if(e.startsWith(`${o} `))return e.slice(o.length+1);if(e===o)return""}return null}function th(e){return ze.some((t,n)=>wl(e,n)!==null)}function qt(e){return e.replace(/\s*\n\s*/g," ")}function bl(e,t,n,o,s){let r=[`:question: *${e}*`];if(t)r.push("",t);if(n.length){if(r.push(""),r.push(...n.map((i,c)=>`${yl(c)} ${qt(i)}`)),o.length)r.push(""),r.push(...o.map((i,c)=>`(${c+11}) ${qt(i)}`)),r.push("_11 番目以降はリアクションがないので、返信で答えてください。_");r.push(""),r.push(s?"_下のリアクションを 1 つ押すと回答になります。当てはまるものがなければ、このメッセージの *スレッド* で返信してください (チャンネルへの通常投稿は回答として拾いません)。_":"_下のリアクションを 1 つ押すと回答になります。当てはまるものがなければ、このメッセージに返信してください。_")}else r.push(""),r.push(s?"_このメッセージの *スレッド* で返信してください。本文がそのまま回答になります (チャンネルへの通常投稿は回答として拾いません)。_":"_このメッセージに返信してください。本文がそのまま回答になります。_");return r.join(`
239
- `)}function kl(e,t,n){let o=t.answer.split(`
240
+ `);if(J)p=!0;F=C?L:void 0}while(F);h=!1}catch(k){if(k instanceof et){console.error(`Warning: Slack rate limit hit — backing off for ${k.retryAfter}s`),await nt.sleep(k.retryAfter*1000);continue}throw k}if(n.exitOnMessage&&p)return;m=nt.now();let D=i-nt.now();if(D<=0)return;await nt.sleep(Math.min(r,D))}}import{spawn as fh}from"node:child_process";import{constants as Dl}from"node:os";var ph=["processing","active","suspended","closed"];function yl(e){if(e!==void 0&&!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e))throw Error("--bot-token-env must name an environment variable, not contain a token.");let t=e===void 0?Ps():process.env[e];if(!t?.startsWith("xoxb-"))throw Error("Agent commands require a bot token (xoxb). Set SLACK_BOT_TOKEN or --bot-token-env NAME; user tokens are refused.");return t}function wl(e){if(e!==void 0&&(!e.trim()||[...e].length>200))throw Error("--title must contain 1–200 characters.")}async function bl(e,t,n){let{ref:o,threadTs:s}=n(t);if(!s||!/^\d{10}\.\d{6}$/.test(s))throw Error("Target must include a thread root: C00000001:1700000000.000100, #channel:ts, or a message permalink.");return{channel_id:await vs(e,o),thread_ts:s}}function Kr(e,t){console.error(`agent: ${e}: ${t instanceof Error?t.message:"request failed"}`)}async function hh(e,t,n,o){let s,r,i,c,a,l=!1,u=!1,d=1,f=(p)=>{if(r)return;if(r=p,l=!0,s&&s.exitCode===null&&s.signalCode===null)s.kill(p),i=setTimeout(()=>s?.kill("SIGKILL"),5000)},h=()=>f("SIGINT"),m=()=>f("SIGTERM");process.on("SIGINT",h),process.on("SIGTERM",m);try{if(u=!0,await Ln(e,t,"processing"),!l&&o.title!==void 0)await Cr(e,t,o.title);if(!l){s=fh(n[0],n.slice(1),{stdio:"inherit"});let p=new Promise((D)=>{s.once("error",()=>{console.error("agent: could not start command"),D(127)}),s.once("exit",(k,x)=>{D(k??(x?128+Dl.signals[x]:1))})});c=setInterval(()=>{if(l||a)return;a=Ln(e,t,"processing").then(()=>{}).catch((D)=>Kr("heartbeat failed; retrying on next tick",D)).finally(()=>{a=void 0})},o.every*1000),d=await p}}catch(p){Kr("could not start agent session",p)}finally{if(l=!0,clearInterval(c),clearTimeout(i),await a,u)try{await Ln(e,t,o.close?"closed":"active")}catch(p){if(Kr("final status clear failed",p),d===0)d=1}process.removeListener("SIGINT",h),process.removeListener("SIGTERM",m)}return r?128+Dl.signals[r]:d}function kl(e,t){let n=(o)=>o.positional("target",{type:"string",demandOption:!0,describe:"Thread root: raw channel ID:ts (avoids listing), #channel:ts, or permalink"}).option("title",{type:"string",describe:"Rename the session (1–200 characters)"}).option("bot-token-env",{type:"string",describe:"Environment variable holding an agent-enabled app's xoxb token (default SLACK_BOT_TOKEN); requires chat:write and channel membership"});return e.command("status <target> <status>","Set a bot agent session's status",(o)=>n(o).positional("status",{type:"string",choices:ph,demandOption:!0}),async(o)=>{wl(o.title);let s=yl(o["bot-token-env"]),r=await bl(s,o.target,t);if(await Ln(s,r,o.status),o.title!==void 0)await Cr(s,r,o.title)}).command("run <target>","Keep a thread working while a command runs: run <target> -- <command...>",(o)=>n(o).parserConfiguration({"populate--":!0}).option("every",{type:"number",default:300,describe:"Heartbeat seconds (>0 and <3600); processing expires after one hour"}).option("close",{type:"boolean",default:!1,describe:"Finish with closed instead of active (also on failure or interrupt)"}),async(o)=>{if(wl(o.title),!Number.isFinite(o.every)||o.every<=0||o.every>=3600)throw Error("--every must be greater than 0 and less than 3600 seconds.");let s=process.argv.indexOf("--"),r=s<0?[]:process.argv.slice(s+1);if(!r[0])throw Error("agent run requires -- <command...>");let i=yl(o["bot-token-env"]),c=await bl(i,o.target,t);process.exitCode=await hh(i,c,r,{every:o.every,close:o.close,...o.title!==void 0?{title:o.title}:{}})}).demandCommand(1,"Choose agent status or agent run.")}var Ge=[{name:"one",glyph:"1️⃣"},{name:"two",glyph:"2️⃣"},{name:"three",glyph:"3️⃣"},{name:"four",glyph:"4️⃣"},{name:"five",glyph:"5️⃣"},{name:"six",glyph:"6️⃣"},{name:"seven",glyph:"7️⃣"},{name:"eight",glyph:"8️⃣"},{name:"nine",glyph:"9️⃣"},{name:"keycap_ten",glyph:"\uD83D\uDD1F"}],Vs=Ge.length,Zs="question";function zr(e){let t=e.split(`
241
+ `),n=t[t.length-2];if(n===void 0||!n.startsWith("_:warning: 同時に複数選ばれているため回答として数えていません — どれか 1 つだけ残してください: ")||!n.endsWith("_"))return[];return[...n.matchAll(/<@([UW][A-Z0-9]+)>/g)].map((o)=>o[1])}function qr(e,t){let n=e.split(`
242
+ `);if(n.length<2)return e;if(zr(e).length)n.splice(n.length-2,1);if(t.length)n.splice(n.length-1,0,`${"_:warning: 同時に複数選ばれているため回答として数えていません — どれか 1 つだけ残してください: "}${t.map((s)=>`<@${s}>`).join(", ")}_`);let o=n.join(`
243
+ `);return o===e?e:o}function gh(e){return e!==void 0&&e.startsWith("_:warning: 同時に複数選ばれているため回答として数えていません — どれか 1 つだけ残してください: ")&&e.endsWith("_")}var Gr="white_check_mark",Ys=`:${Gr}: `;function El(e){return`:${Ge[e].name}:`}function Cl(e,t){let n=Ge[t];for(let o of[El(t),n.glyph]){if(e.startsWith(`${o} `))return e.slice(o.length+1);if(e===o)return""}return null}function mh(e){return Ge.some((t,n)=>Cl(e,n)!==null)}function Gt(e){return e.replace(/\s*\n\s*/g," ")}function Sl(e,t,n,o,s){let r=[`:question: *${e}*`];if(t)r.push("",t);if(n.length){if(r.push(""),r.push(...n.map((i,c)=>`${El(c)} ${Gt(i)}`)),o.length)r.push(""),r.push(...o.map((i,c)=>`(${c+11}) ${Gt(i)}`)),r.push("_11 番目以降はリアクションがないので、返信で答えてください。_");r.push(""),r.push(s?"_下のリアクションを 1 つ押すと回答になります。当てはまるものがなければ、このメッセージの *スレッド* で返信してください (チャンネルへの通常投稿は回答として拾いません)。_":"_下のリアクションを 1 つ押すと回答になります。当てはまるものがなければ、このメッセージに返信してください。_")}else r.push(""),r.push(s?"_このメッセージの *スレッド* で返信してください。本文がそのまま回答になります (チャンネルへの通常投稿は回答として拾いません)。_":"_このメッセージに返信してください。本文がそのまま回答になります。_");return r.join(`
244
+ `)}function _l(e,t,n){let o=t.answer.split(`
240
245
  `).map((s)=>`> ${s}`).join(`
241
- `);return`${Gs}*${e}*
246
+ `);return`${Ys}*${e}*
242
247
  _${t.how}で回答済み${n?` (${n})`:""}_
243
248
 
244
- ${o}`}function Dl(e){return e.replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&")}function xl(e){if(!e.trim())return"本文が空です (bot 投稿や添付のみのメッセージかもしれません)";let t=e.split(`
245
- `),n=t[t.length-1]??"";if(e.startsWith(Gs))return"回答済みマーク付きですが、引用された回答本文が見つかりません";if(!/_$/.test(n))return"末尾が `ask` の案内文ではありません — このメッセージは `slack ask` で投稿されたものではないか、本文が編集されています";if(!t[0].startsWith(":question: ")&&!t[0].startsWith("*"))return"先頭が質問文 (太字) ではありません — 本文が編集されている可能性があります";return"選択肢の並びを読み取れません — 番号が 1 から連番になっていないか、本文が編集されています"}function Cl(e){let t=e.split(`
246
- `);if(e.startsWith(Gs)){let u=t[0].slice(Gs.length),d=Dl(u.replace(/^\*/,"").replace(/\*$/,"")),f=t.map((h)=>h.startsWith("> ")?h.slice(2):h.startsWith("&gt; ")?h.slice(5):null).filter((h)=>h!==null).map(Dl).join(`
249
+ ${o}`}function xl(e){return e.replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&")}function Fl(e){if(!e.trim())return"本文が空です (bot 投稿や添付のみのメッセージかもしれません)";let t=e.split(`
250
+ `),n=t[t.length-1]??"";if(e.startsWith(Ys))return"回答済みマーク付きですが、引用された回答本文が見つかりません";if(!/_$/.test(n))return"末尾が `ask` の案内文ではありません — このメッセージは `slack ask` で投稿されたものではないか、本文が編集されています";if(!t[0].startsWith(":question: ")&&!t[0].startsWith("*"))return"先頭が質問文 (太字) ではありません — 本文が編集されている可能性があります";return"選択肢の並びを読み取れません — 番号が 1 から連番になっていないか、本文が編集されています"}function $l(e){let t=e.split(`
251
+ `);if(e.startsWith(Ys)){let u=t[0].slice(Ys.length),d=xl(u.replace(/^\*/,"").replace(/\*$/,"")),f=t.map((h)=>h.startsWith("> ")?h.slice(2):h.startsWith("&gt; ")?h.slice(5):null).filter((h)=>h!==null).map(xl).join(`
247
252
  `);if(!f)return{kind:"other"};return{kind:"resolved",question:d,answer:f}}let n=t[t.length-1]??"",o,s;switch(n){case"_下のリアクションを 1 つ押すと回答になります。当てはまるものがなければ、このメッセージの *スレッド* で返信してください (チャンネルへの通常投稿は回答として拾いません)。_":o=!0,s=!0;break;case"_下のリアクションを 1 つ押すと回答になります。当てはまるものがなければ、このメッセージに返信してください。_":o=!1,s=!0;break;case"_このメッセージの *スレッド* で返信してください。本文がそのまま回答になります (チャンネルへの通常投稿は回答として拾いません)。_":o=!0,s=!1;break;case"_このメッセージに返信してください。本文がそのまま回答になります。_":o=!1,s=!1;break;default:return{kind:"other"}}let r=t[0].startsWith(":question: ")?t[0].slice(11):t[0];if(t[0]=r,!t[0].startsWith("*"))return{kind:"other"};let i=0;while(i<t.length&&!(t[i].endsWith("*")&&(i>0||t[0].length>1)))i++;if(i>=t.length)return{kind:"other"};let c=t.slice(0,i+1).join(`
248
- `).replace(/^\*/,"").replace(/\*$/,""),a=[],l=[];if(s){let u=t.length-2;if(eh(t[u]))u--;if(t[u]!=="")return{kind:"other"};if(u--,t[u]==="_11 番目以降はリアクションがないので、返信で答えてください。_"){u--;while(u>=0&&/^\(\d+\) /.test(t[u]))l.unshift(t[u].replace(/^\(\d+\) /,"")),u--;if(t[u]!=="")return{kind:"other"};u--}let d=[];while(u>=0){let f=t[u];if(!th(f))break;d.unshift(f),u--}if(!d.length||d.length>Xs)return{kind:"other"};for(let f=0;f<d.length;f++){let h=wl(d[f],f);if(h===null)return{kind:"other"};a.push(h)}if(t[u]!=="")return{kind:"other"};if(u<i+1)return{kind:"other"};for(let f=0;f<l.length;f++)if(!t.includes(`(${f+11}) ${l[f]}`))return{kind:"other"}}return{kind:"open",question:c,reactable:a,overflow:l,threadOnly:o}}function Wr(e){return e.normalize("NFKC").replace(/[*_`~]/g,"").trim().replace(/^[\s"'`「『((\[]+/,"").replace(/[\s"'`」』))\]。..!!??、,]+$/,"").replace(/\s+/g," ").trim().toLowerCase()}function El(e,t){let n=Wr(e);if(!n)return{kind:"none"};let o=t.map(Wr),s=new Set;o.forEach((l,u)=>{if(l&&l===n)s.add(u+1)}),ze.forEach((l,u)=>{if(u<t.length&&e.trim()===l.glyph)s.add(u+1)});let r=0,i="",c=n.match(/^(\d{1,2})$/);if(c)r=Number(c[1]);else if(c=n.match(/^(\d{1,2})(?:\s*[.)::、。\-\]]\s*|\s+)(.*)$/)){if(r=Number(c[1]),i=Wr(c[2]),!i)return{kind:"none"};if(/^\d+$/.test(i))return{kind:"none"}}if(r>=1&&r<=t.length&&(i===""||i===o[r-1]))s.add(r);let a=[...s].sort((l,u)=>l-u);if(!a.length)return{kind:"none"};if(a.length>1)return{kind:"ambiguous",indexes:a};return{kind:"chosen",index:a[0]}}var Hr=[{name:"one",glyph:"1️⃣"},{name:"two",glyph:"2️⃣"},{name:"three",glyph:"3️⃣"},{name:"four",glyph:"4️⃣"},{name:"five",glyph:"5️⃣"},{name:"six",glyph:"6️⃣"},{name:"seven",glyph:"7️⃣"},{name:"eight",glyph:"8️⃣"},{name:"nine",glyph:"9️⃣"},{name:"keycap_ten",glyph:"\uD83D\uDD1F"}],zw=Hr.length;function zr(e){let t=e.split(`
249
- `),n=t[t.length-2];if(n===void 0||!n.startsWith("_:warning: 同時に複数選ばれているため回答として数えていません — どれか 1 つだけ残してください: ")||!n.endsWith("_"))return[];return[...n.matchAll(/<@([UW][A-Z0-9]+)>/g)].map((o)=>o[1])}function Sl(e,t){let n=e.split(`
250
- `);if(n.length<2)return e;if(zr(e).length)n.splice(n.length-2,1);if(t.length)n.splice(n.length-1,0,`${"_:warning: 同時に複数選ばれているため回答として数えていません — どれか 1 つだけ残してください: "}${t.map((s)=>`<@${s}>`).join(", ")}_`);let o=n.join(`
251
- `);return o===e?e:o}function _l(e){return e!==void 0&&e.startsWith("_:warning: 同時に複数選ばれているため回答として数えていません — どれか 1 つだけ残してください: ")&&e.endsWith("_")}var nh="white_check_mark",qw=`:${nh}: `;var nt=Hr,gn=nt.length,qn="ballot_box_with_ballot",qr=`:${qn}: `,$l="_下のリアクションで投票してください (1 人 1 票、押し直しで変更できます)。_",Al="_下のリアクションで投票してください (当てはまるものを *いくつでも* 押せます)。_",Vs="_締切: ",Zs="_",Xr="bar_chart",Gr=`:${Xr}: `;function Qs(e){return`:${nt[e].name}:`}function Fl(e,t){for(let n of[Qs(t),nt[t].glyph])if(e.startsWith(`${n} `))return e.slice(n.length+1);return null}function sh(e){return nt.some((t,n)=>e.startsWith(`${Qs(n)} `)||e.startsWith(`${t.glyph} `))}function zn(e){return e.replace(/\s*\n\s*/g," ")}function Tl(e,t,n,o={}){let s=!!o.multi,r=o.deadline??"",i=o.invalid??[];if(!n.length||n.length>gn)throw Error(`poll needs 1..${gn} choices, got ${n.length}`);let c=[`${qr}*${e}*`];if(t)c.push("",t);if(c.push(""),c.push(...n.map((a,l)=>`${Qs(l)} ${zn(a)}`)),c.push(""),r)c.push(`${Vs}${zn(r)}${Zs}`);return c.push(s?Al:$l),Sl(c.join(`
252
- `),s?[]:i)}function Il(e,t){let n=t.reduce((s,r)=>s+r.count,0),o=[`${Gr}*${e}*`,`_投票終了 (計 ${n} 票)_`,""];return o.push(...t.map((s,r)=>`${Qs(r)} ×${s.count} ${zn(s.choice)}`)),o.join(`
253
- `)}function Ol(e){let t=e.split(`
254
- `);if(e.startsWith(Gr)){let f=t[0].slice(Gr.length).replace(/^\*/,"").replace(/\*$/,""),h=[];for(let m=0;m<nt.length;m++){let p=t.map((k)=>Fl(k,m)).find((k)=>k!==null&&k.startsWith("×"));if(p===void 0)break;let D=/^×(\d+) (.*)$/.exec(p);if(!D)return{kind:"other"};h.push({choice:D[2],count:Number(D[1])})}if(!h.length)return{kind:"other"};return{kind:"closed",question:f,tallies:h}}let n=t[t.length-1]??"",o;if(n===$l)o=!1;else if(n===Al)o=!0;else return{kind:"other"};if(t[0].startsWith(qr))t[0]=t[0].slice(qr.length);if(!t[0].startsWith("*"))return{kind:"other"};let s=0;while(s<t.length&&!(t[s].endsWith("*")&&(s>0||t[0].length>1)))s++;if(s>=t.length)return{kind:"other"};let r=t.slice(0,s+1).join(`
255
- `).replace(/^\*/,"").replace(/\*$/,""),i=t.length-2,c=zr(e);if(_l(t[i]))i--;let a="",l=t[i];if(l!==void 0&&l.startsWith(Vs)&&l.endsWith(Zs)&&l.length>Vs.length+Zs.length)a=l.slice(Vs.length,-Zs.length),i--;if(t[i]!=="")return{kind:"other"};i--;let u=[];while(i>=0){let f=t[i];if(!sh(f))break;u.unshift(f),i--}if(!u.length||u.length>gn)return{kind:"other"};let d=[];for(let f=0;f<u.length;f++){let h=Fl(u[f],f);if(h===null)return{kind:"other"};d.push(h)}if(t[i]!=="")return{kind:"other"};if(i<s+1)return{kind:"other"};return{kind:"open",question:r,choices:d,multi:o,deadline:a,invalid:c}}function Pl(e,t,n,o){let s=new Map(t.map((l)=>[l.name,l.users])),r=e.map((l,u)=>(s.get(nt[u].name)??[]).filter((d)=>!n.has(d))),i=[];if(!o){let l=new Map;for(let u of r)for(let d of u)l.set(d,(l.get(d)??0)+1);for(let[u,d]of l)if(d>1)i.push(u)}let c=new Set(i),a=r.map((l)=>l.filter((u)=>!c.has(u)));return{tallies:e.map((l,u)=>({choice:l,count:a[u].length})),voters:a,ambiguous:i}}function oh(e=process.env){return!!e.VITEST||e.NODE_ENV==="test"||!!e.BUN_TEST}var Rl={isTestEnv:()=>oh(),sleep:(e)=>Rl.isTestEnv()?Promise.resolve():new Promise((t)=>setTimeout(t,e))};function rh(e=process.env){let t=e.SLACK_REACTION_SEED_GAP_MS;if(t===void 0||t==="")return 1100;let n=Number(t);if(!Number.isFinite(n)||n<0)return 1100;return n}async function Yr(e,t,n,o=rh()){for(let s=0;s<e.length;s++){let r=!0;try{await t(e[s])}catch(i){r=!1,n(e[s],i)}if(r&&o>0&&s<e.length-1)await Rl.sleep(o)}}var Nl=["text","select","user","link","date","number","checkbox"];function Ml(e){let t=e.split(":"),n=(t[0]??"").trim(),o=(t[1]??"text").trim();if(!n)throw Error(`--col needs a name: ${e}`);if(!Nl.includes(o))throw Error(`--col ${e}: unknown type "${o}" (expected one of ${Nl.join(", ")})`);if(o==="select"){let s=(t.slice(2).join(":")||"").split(",").map((r)=>r.trim()).filter(Boolean);if(!s.length)throw Error(`--col ${e}: a select column needs choices, e.g. ${n}:select:todo,doing,done`);return{name:n,type:o,choices:s}}if(t.length>2)throw Error(`--col ${e}: only select columns take a third part`);return{name:n,type:o}}var Bl=["gray","blue","green","yellow","red","purple","orange","pink","cyan","indigo","brown"];function vl(e){if(!e.length)throw Error("at least one --col is required (the first one is the primary text column)");if(e[0].type!=="text")throw Error(`the first --col is the primary column and must be text, got ${e[0].type}`);return e.map((t,n)=>{let o={key:`col${n+1}`,name:t.name,type:t.type};if(n===0)o.is_primary_column=!0;if(t.type==="select")o.options={format:"single_select",choices:t.choices.map((s,r)=>({value:s,label:s,color:Bl[r%Bl.length]}))};if(t.type==="user")o.options={format:"single_entity"};return o})}function Ll(e){return((e.list_metadata??e.metadata??{}).schema??e.schema??[]).map((o)=>{let s=o??{},i=((s.options??{}).choices??[]).map((c)=>{let a=c??{};return{value:String(a.value??""),label:String(a.label??a.value??"")}});return{id:String(s.id??""),key:String(s.key??""),name:String(s.name??""),type:String(s.type??""),choices:i}})}function Vr(e,t){let n=e.find((o)=>o.name===t)??e.find((o)=>o.key===t)??e.find((o)=>o.id===t);if(!n)throw Error(`no column "${t}" in this list (columns: ${e.map((o)=>o.name||o.key).join(", ")})`);return n}function Zr(e,t){switch(e.type){case"text":return{rich_text:[{type:"rich_text",elements:[{type:"rich_text_section",elements:[{type:"text",text:t}]}]}]};case"select":{let n=e.choices.find((o)=>o.value===t||o.label===t);if(!n)throw Error(`"${t}" is not an option of ${e.name} (options: ${e.choices.map((o)=>o.label).join(", ")})`);return{select:[n.value]}}case"user":return{user:[t]};case"link":return{link:[{original_url:t,display_as_url:!0}]};case"date":return{date:[t]};case"number":{let n=Number(t);if(!Number.isFinite(n))throw Error(`${e.name}: "${t}" is not a number`);return{number:[n]}}case"checkbox":case"todo_completed":if(!["true","false"].includes(t))throw Error(`${e.name}: expected true or false, got "${t}"`);return{checkbox:t==="true"};default:throw Error(`writing a ${e.type} column (${e.name}) from the CLI is not supported`)}}function Qr(e){return e.map((t)=>{let n=t.indexOf("=");if(n<=0)throw Error(`--set expects name=value, got: ${t}`);return{col:t.slice(0,n),value:t.slice(n+1)}})}function jl(e){return e.find((t)=>t.key==="todo_completed"||t.type==="todo_completed")}import{spawnSync as Ul}from"node:child_process";import{chmodSync as ih,mkdirSync as ah}from"node:fs";import{homedir as ch,hostname as lh}from"node:os";import{basename as uh,dirname as dh,join as fh}from"node:path";function ti(){return!/^(0|off|false|no)$/i.test(process.env.SLACK_TERM_ATTRIBUTION??"")}var Jl={claude:"claude-code",codex:"codex",gemini:"gemini",opencode:"opencode","cursor-agent":"cursor-agent",aider:"aider",amp:"amp"};function ph(e){try{let n=(Ul("ps",["-o","ppid=,comm=","-p",String(e)],{encoding:"utf8",timeout:2000}).stdout??"").trim().match(/^(\d+)\s+(.+)$/);if(!n)return;return{pid:e,ppid:Number(n[1]),comm:uh(n[2].trim())}}catch{return}}function hh(){let e=process.ppid;for(let t=0;t<12&&e>1;t++){let n=ph(e);if(!n)return;if(Jl[n.comm])return n;e=n.ppid}return}function Wl(e){let t=Number(e);return Number.isInteger(t)&&t>0?t:void 0}function Kl(e=process.env){let t={pid:process.pid,host:gh(),cwd:process.cwd()},n=e.SLACK_TERM_AGENT_CLI||void 0;if(!n&&e.AI_AGENT)n=e.AI_AGENT.split("_")[0]||void 0;if(!n&&e.CLAUDECODE==="1")n="claude-code";let o=Wl(e.SLACK_TERM_AGENT_PID)??Wl(e.CLAUDE_PID);if(!o||!n){let i=hh();if(i)o??=i.pid,n??=Jl[i.comm]}if(n)t.cli=n;if(o)t.agentPid=o;let s=e.SLACK_TERM_AGENT_SESSION||e.CLAUDE_CODE_SESSION_ID;if(s)t.sessionId=s;let r=mh(t.cwd);if(r)t.gitBranch=r;return t}function gh(){try{return lh()}catch{return""}}function mh(e){try{let t=Ul("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:e,encoding:"utf8",timeout:2000});return(t.status===0?(t.stdout??"").trim():"")||void 0}catch{return}}var Dh="slack_term_sent";function Hl(e,t){let n={kind:e,pid:t.pid,host:t.host,cwd:t.cwd};if(t.agentPid)n.agent_pid=t.agentPid;if(t.gitBranch)n.git_branch=t.gitBranch;if(t.cli)n.cli=t.cli;if(t.sessionId)n.session_id=t.sessionId;return{event_type:Dh,event_payload:n}}function Gn(){if(process.env.SLACK_TERM_SENT_DB)return process.env.SLACK_TERM_SENT_DB;return fh(process.env.HOME||ch(),".config","slack-cli","sent.sqlite")}function yh(e){try{if(typeof globalThis.Bun<"u"){let{Database:n}=En("bun:sqlite");return new n(e,{create:!0})}let t=process.getBuiltinModule?.("node:sqlite");if(t?.DatabaseSync)return new t.DatabaseSync(e)}catch{}return}var wh=`
253
+ `).replace(/^\*/,"").replace(/\*$/,""),a=[],l=[];if(s){let u=t.length-2;if(gh(t[u]))u--;if(t[u]!=="")return{kind:"other"};if(u--,t[u]==="_11 番目以降はリアクションがないので、返信で答えてください。_"){u--;while(u>=0&&/^\(\d+\) /.test(t[u]))l.unshift(t[u].replace(/^\(\d+\) /,"")),u--;if(t[u]!=="")return{kind:"other"};u--}let d=[];while(u>=0){let f=t[u];if(!mh(f))break;d.unshift(f),u--}if(!d.length||d.length>Vs)return{kind:"other"};for(let f=0;f<d.length;f++){let h=Cl(d[f],f);if(h===null)return{kind:"other"};a.push(h)}if(t[u]!=="")return{kind:"other"};if(u<i+1)return{kind:"other"};for(let f=0;f<l.length;f++)if(!t.includes(`(${f+11}) ${l[f]}`))return{kind:"other"}}return{kind:"open",question:c,reactable:a,overflow:l,threadOnly:o}}function Hr(e){return e.normalize("NFKC").replace(/[*_`~]/g,"").trim().replace(/^[\s"'`「『((\[]+/,"").replace(/[\s"'`」』))\]。..!!??、,]+$/,"").replace(/\s+/g," ").trim().toLowerCase()}function Al(e,t){let n=Hr(e);if(!n)return{kind:"none"};let o=t.map(Hr),s=new Set;o.forEach((l,u)=>{if(l&&l===n)s.add(u+1)}),Ge.forEach((l,u)=>{if(u<t.length&&e.trim()===l.glyph)s.add(u+1)});let r=0,i="",c=n.match(/^(\d{1,2})$/);if(c)r=Number(c[1]);else if(c=n.match(/^(\d{1,2})(?:\s*[.)::、。\-\]]\s*|\s+)(.*)$/)){if(r=Number(c[1]),i=Hr(c[2]),!i)return{kind:"none"};if(/^\d+$/.test(i))return{kind:"none"}}if(r>=1&&r<=t.length&&(i===""||i===o[r-1]))s.add(r);let a=[...s].sort((l,u)=>l-u);if(!a.length)return{kind:"none"};if(a.length>1)return{kind:"ambiguous",indexes:a};return{kind:"chosen",index:a[0]}}var Xr=[{name:"one",glyph:"1️⃣"},{name:"two",glyph:"2️⃣"},{name:"three",glyph:"3️⃣"},{name:"four",glyph:"4️⃣"},{name:"five",glyph:"5️⃣"},{name:"six",glyph:"6️⃣"},{name:"seven",glyph:"7️⃣"},{name:"eight",glyph:"8️⃣"},{name:"nine",glyph:"9️⃣"},{name:"keycap_ten",glyph:"\uD83D\uDD1F"}],ub=Xr.length;function Yr(e){let t=e.split(`
254
+ `),n=t[t.length-2];if(n===void 0||!n.startsWith("_:warning: 同時に複数選ばれているため回答として数えていません — どれか 1 つだけ残してください: ")||!n.endsWith("_"))return[];return[...n.matchAll(/<@([UW][A-Z0-9]+)>/g)].map((o)=>o[1])}function Tl(e,t){let n=e.split(`
255
+ `);if(n.length<2)return e;if(Yr(e).length)n.splice(n.length-2,1);if(t.length)n.splice(n.length-1,0,`${"_:warning: 同時に複数選ばれているため回答として数えていません — どれか 1 つだけ残してください: "}${t.map((s)=>`<@${s}>`).join(", ")}_`);let o=n.join(`
256
+ `);return o===e?e:o}function Il(e){return e!==void 0&&e.startsWith("_:warning: 同時に複数選ばれているため回答として数えていません — どれか 1 つだけ残してください: ")&&e.endsWith("_")}var Dh="white_check_mark",db=`:${Dh}: `;var st=Xr,mn=st.length,Gn="ballot_box_with_ballot",Vr=`:${Gn}: `,Pl="_下のリアクションで投票してください (1 人 1 票、押し直しで変更できます)。_",Rl="_下のリアクションで投票してください (当てはまるものを *いくつでも* 押せます)。_",Qs="_締切: ",eo="_",Qr="bar_chart",Zr=`:${Qr}: `;function to(e){return`:${st[e].name}:`}function Ol(e,t){for(let n of[to(t),st[t].glyph])if(e.startsWith(`${n} `))return e.slice(n.length+1);return null}function yh(e){return st.some((t,n)=>e.startsWith(`${to(n)} `)||e.startsWith(`${t.glyph} `))}function qn(e){return e.replace(/\s*\n\s*/g," ")}function Nl(e,t,n,o={}){let s=!!o.multi,r=o.deadline??"",i=o.invalid??[];if(!n.length||n.length>mn)throw Error(`poll needs 1..${mn} choices, got ${n.length}`);let c=[`${Vr}*${e}*`];if(t)c.push("",t);if(c.push(""),c.push(...n.map((a,l)=>`${to(l)} ${qn(a)}`)),c.push(""),r)c.push(`${Qs}${qn(r)}${eo}`);return c.push(s?Rl:Pl),Tl(c.join(`
257
+ `),s?[]:i)}function Bl(e,t){let n=t.reduce((s,r)=>s+r.count,0),o=[`${Zr}*${e}*`,`_投票終了 (計 ${n} 票)_`,""];return o.push(...t.map((s,r)=>`${to(r)} ×${s.count} ${qn(s.choice)}`)),o.join(`
258
+ `)}function vl(e){let t=e.split(`
259
+ `);if(e.startsWith(Zr)){let f=t[0].slice(Zr.length).replace(/^\*/,"").replace(/\*$/,""),h=[];for(let m=0;m<st.length;m++){let p=t.map((k)=>Ol(k,m)).find((k)=>k!==null&&k.startsWith("×"));if(p===void 0)break;let D=/^×(\d+) (.*)$/.exec(p);if(!D)return{kind:"other"};h.push({choice:D[2],count:Number(D[1])})}if(!h.length)return{kind:"other"};return{kind:"closed",question:f,tallies:h}}let n=t[t.length-1]??"",o;if(n===Pl)o=!1;else if(n===Rl)o=!0;else return{kind:"other"};if(t[0].startsWith(Vr))t[0]=t[0].slice(Vr.length);if(!t[0].startsWith("*"))return{kind:"other"};let s=0;while(s<t.length&&!(t[s].endsWith("*")&&(s>0||t[0].length>1)))s++;if(s>=t.length)return{kind:"other"};let r=t.slice(0,s+1).join(`
260
+ `).replace(/^\*/,"").replace(/\*$/,""),i=t.length-2,c=Yr(e);if(Il(t[i]))i--;let a="",l=t[i];if(l!==void 0&&l.startsWith(Qs)&&l.endsWith(eo)&&l.length>Qs.length+eo.length)a=l.slice(Qs.length,-eo.length),i--;if(t[i]!=="")return{kind:"other"};i--;let u=[];while(i>=0){let f=t[i];if(!yh(f))break;u.unshift(f),i--}if(!u.length||u.length>mn)return{kind:"other"};let d=[];for(let f=0;f<u.length;f++){let h=Ol(u[f],f);if(h===null)return{kind:"other"};d.push(h)}if(t[i]!=="")return{kind:"other"};if(i<s+1)return{kind:"other"};return{kind:"open",question:r,choices:d,multi:o,deadline:a,invalid:c}}function Ll(e,t,n,o){let s=new Map(t.map((l)=>[l.name,l.users])),r=e.map((l,u)=>(s.get(st[u].name)??[]).filter((d)=>!n.has(d))),i=[];if(!o){let l=new Map;for(let u of r)for(let d of u)l.set(d,(l.get(d)??0)+1);for(let[u,d]of l)if(d>1)i.push(u)}let c=new Set(i),a=r.map((l)=>l.filter((u)=>!c.has(u)));return{tallies:e.map((l,u)=>({choice:l,count:a[u].length})),voters:a,ambiguous:i}}function wh(e=process.env){return!!e.VITEST||e.NODE_ENV==="test"||!!e.BUN_TEST}var Ml={isTestEnv:()=>wh(),sleep:(e)=>Ml.isTestEnv()?Promise.resolve():new Promise((t)=>setTimeout(t,e))};function bh(e=process.env){let t=e.SLACK_REACTION_SEED_GAP_MS;if(t===void 0||t==="")return 1100;let n=Number(t);if(!Number.isFinite(n)||n<0)return 1100;return n}async function ei(e,t,n,o=bh()){for(let s=0;s<e.length;s++){let r=!0;try{await t(e[s])}catch(i){r=!1,n(e[s],i)}if(r&&o>0&&s<e.length-1)await Ml.sleep(o)}}var jl=["text","select","user","link","date","number","checkbox"];function Ul(e){let t=e.split(":"),n=(t[0]??"").trim(),o=(t[1]??"text").trim();if(!n)throw Error(`--col needs a name: ${e}`);if(!jl.includes(o))throw Error(`--col ${e}: unknown type "${o}" (expected one of ${jl.join(", ")})`);if(o==="select"){let s=(t.slice(2).join(":")||"").split(",").map((r)=>r.trim()).filter(Boolean);if(!s.length)throw Error(`--col ${e}: a select column needs choices, e.g. ${n}:select:todo,doing,done`);return{name:n,type:o,choices:s}}if(t.length>2)throw Error(`--col ${e}: only select columns take a third part`);return{name:n,type:o}}var Wl=["gray","blue","green","yellow","red","purple","orange","pink","cyan","indigo","brown"];function Jl(e){if(!e.length)throw Error("at least one --col is required (the first one is the primary text column)");if(e[0].type!=="text")throw Error(`the first --col is the primary column and must be text, got ${e[0].type}`);return e.map((t,n)=>{let o={key:`col${n+1}`,name:t.name,type:t.type};if(n===0)o.is_primary_column=!0;if(t.type==="select")o.options={format:"single_select",choices:t.choices.map((s,r)=>({value:s,label:s,color:Wl[r%Wl.length]}))};if(t.type==="user")o.options={format:"single_entity"};return o})}function Kl(e){return((e.list_metadata??e.metadata??{}).schema??e.schema??[]).map((o)=>{let s=o??{},i=((s.options??{}).choices??[]).map((c)=>{let a=c??{};return{value:String(a.value??""),label:String(a.label??a.value??"")}});return{id:String(s.id??""),key:String(s.key??""),name:String(s.name??""),type:String(s.type??""),choices:i}})}function ti(e,t){let n=e.find((o)=>o.name===t)??e.find((o)=>o.key===t)??e.find((o)=>o.id===t);if(!n)throw Error(`no column "${t}" in this list (columns: ${e.map((o)=>o.name||o.key).join(", ")})`);return n}function ni(e,t){switch(e.type){case"text":return{rich_text:[{type:"rich_text",elements:[{type:"rich_text_section",elements:[{type:"text",text:t}]}]}]};case"select":{let n=e.choices.find((o)=>o.value===t||o.label===t);if(!n)throw Error(`"${t}" is not an option of ${e.name} (options: ${e.choices.map((o)=>o.label).join(", ")})`);return{select:[n.value]}}case"user":return{user:[t]};case"link":return{link:[{original_url:t,display_as_url:!0}]};case"date":return{date:[t]};case"number":{let n=Number(t);if(!Number.isFinite(n))throw Error(`${e.name}: "${t}" is not a number`);return{number:[n]}}case"checkbox":case"todo_completed":if(!["true","false"].includes(t))throw Error(`${e.name}: expected true or false, got "${t}"`);return{checkbox:t==="true"};default:throw Error(`writing a ${e.type} column (${e.name}) from the CLI is not supported`)}}function si(e){return e.map((t)=>{let n=t.indexOf("=");if(n<=0)throw Error(`--set expects name=value, got: ${t}`);return{col:t.slice(0,n),value:t.slice(n+1)}})}function Hl(e){return e.find((t)=>t.key==="todo_completed"||t.type==="todo_completed")}import{spawnSync as ql}from"node:child_process";import{chmodSync as kh,mkdirSync as xh}from"node:fs";import{homedir as Eh,hostname as Ch}from"node:os";import{basename as Sh,dirname as _h,join as Fh}from"node:path";function ri(){return!/^(0|off|false|no)$/i.test(process.env.SLACK_TERM_ATTRIBUTION??"")}var Gl={claude:"claude-code",codex:"codex",gemini:"gemini",opencode:"opencode","cursor-agent":"cursor-agent",aider:"aider",amp:"amp"};function $h(e){try{let n=(ql("ps",["-o","ppid=,comm=","-p",String(e)],{encoding:"utf8",timeout:2000}).stdout??"").trim().match(/^(\d+)\s+(.+)$/);if(!n)return;return{pid:e,ppid:Number(n[1]),comm:Sh(n[2].trim())}}catch{return}}function Ah(){let e=process.ppid;for(let t=0;t<12&&e>1;t++){let n=$h(e);if(!n)return;if(Gl[n.comm])return n;e=n.ppid}return}function zl(e){let t=Number(e);return Number.isInteger(t)&&t>0?t:void 0}function Xl(e=process.env){let t={pid:process.pid,host:Th(),cwd:process.cwd()},n=e.SLACK_TERM_AGENT_CLI||void 0;if(!n&&e.AI_AGENT)n=e.AI_AGENT.split("_")[0]||void 0;if(!n&&e.CLAUDECODE==="1")n="claude-code";let o=zl(e.SLACK_TERM_AGENT_PID)??zl(e.CLAUDE_PID);if(!o||!n){let i=Ah();if(i)o??=i.pid,n??=Gl[i.comm]}if(n)t.cli=n;if(o)t.agentPid=o;let s=e.SLACK_TERM_AGENT_SESSION||e.CLAUDE_CODE_SESSION_ID;if(s)t.sessionId=s;let r=Ih(t.cwd);if(r)t.gitBranch=r;return t}function Th(){try{return Ch()}catch{return""}}function Ih(e){try{let t=ql("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:e,encoding:"utf8",timeout:2000});return(t.status===0?(t.stdout??"").trim():"")||void 0}catch{return}}var Oh="slack_term_sent";function Yl(e,t){let n={kind:e,pid:t.pid,host:t.host,cwd:t.cwd};if(t.agentPid)n.agent_pid=t.agentPid;if(t.gitBranch)n.git_branch=t.gitBranch;if(t.cli)n.cli=t.cli;if(t.sessionId)n.session_id=t.sessionId;return{event_type:Oh,event_payload:n}}function Xn(){if(process.env.SLACK_TERM_SENT_DB)return process.env.SLACK_TERM_SENT_DB;return Fh(process.env.HOME||Eh(),".config","slack-cli","sent.sqlite")}function Ph(e){try{if(typeof globalThis.Bun<"u"){let{Database:n}=Sn("bun:sqlite");return new n(e,{create:!0})}let t=process.getBuiltinModule?.("node:sqlite");if(t?.DatabaseSync)return new t.DatabaseSync(e)}catch{}return}var Rh=`
256
261
  CREATE TABLE IF NOT EXISTS sent (
257
262
  id INTEGER PRIMARY KEY AUTOINCREMENT,
258
263
  kind TEXT NOT NULL,
@@ -279,131 +284,132 @@ CREATE TABLE IF NOT EXISTS sent (
279
284
  );
280
285
  CREATE INDEX IF NOT EXISTS sent_msg ON sent(channel, ts);
281
286
  CREATE INDEX IF NOT EXISTS sent_at ON sent(sent_at);
282
- `;function zl(){let e=Gn();try{ah(dh(e),{recursive:!0})}catch{}let t=yh(e);if(!t)return;try{ih(e,384)}catch{}try{return t.exec(wh),t}catch{try{t.close()}catch{}return}}function ql(e){if(!ti())return!1;let t=zl();if(!t)return console.error(` (送信ログに記録できませんでした: ${ni} — ${Gn()})`),!1;try{let n=e.attribution;return t.prepare(`INSERT INTO sent (kind, team, channel, target, ts, thread_ts, permalink, text, sent_at, pid, agent_pid, host, cwd, git_branch, cli, session_id, as_bot)
283
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(e.kind,e.team??null,e.channel,e.target??null,e.ts,e.threadTs??null,e.permalink??null,e.text,Date.now(),n.pid,n.agentPid??null,n.host||null,n.cwd,n.gitBranch??null,n.cli??null,n.sessionId??null,e.asBot?1:0),!0}catch(n){return console.error(` (送信ログに記録できませんでした: ${n instanceof Error?n.message:String(n)})`),!1}finally{try{t.close()}catch{}}}var ni="送信ログを開けません: SQLite が使えないランタイムです (bun、または node >= 22.5 の node:sqlite が必要)";function Gl(e){let t=zl();if(!t)return;try{let n=[],o=[];if(e.text)n.push("text LIKE ? ESCAPE '\\'"),o.push(`%${ei(e.text)}%`);if(e.channel)n.push("(channel = ? OR target = ?)"),o.push(e.channel,e.channel);if(e.sinceMs!==void 0)n.push("sent_at >= ?"),o.push(e.sinceMs);if(e.session)n.push("session_id LIKE ? ESCAPE '\\'"),o.push(`${ei(e.session)}%`);if(e.cwd)n.push("cwd LIKE ? ESCAPE '\\'"),o.push(`${ei(e.cwd)}%`);if(e.kind)n.push("kind = ?"),o.push(e.kind);let s=`SELECT * FROM sent${n.length?` WHERE ${n.join(" AND ")}`:""} ORDER BY sent_at DESC, id DESC LIMIT ?`;return o.push(e.limit??50),t.prepare(s).all(...o)}finally{try{t.close()}catch{}}}function ei(e){return e.replace(/[\\%_]/g,(t)=>`\\${t}`)}function Xl(e,t=Date.now()){let n=e.trim().match(/^(\d+(?:\.\d+)?)\s*(s|m|h|d|w)$/i);if(n){let s={s:1000,m:60000,h:3600000,d:86400000,w:604800000}[n[2].toLowerCase()];return t-Number(n[1])*s}let o=Date.parse(e);return Number.isNaN(o)?void 0:o}class dt extends Error{retryAfter;constructor(e){super(`Slack rate limited — retry after ${e}s`);this.name="RateLimitError",this.retryAfter=e}}function ri(){return(process.env.SLACK_API_BASE??"https://slack.com/api").replace(/\/$/,"")}async function Zl(e,t,n,o){o=e.startsWith("xoxc-")?o??xt():void 0;let s={};if(o)s.Cookie=`d=${o}`;let r=await fetch(`${ri()}/${t}`,{...n,headers:{...n.headers??{},Authorization:`Bearer ${e}`,...s}});if(r.status===429){let c=parseInt(r.headers.get("retry-after")??"60",10);throw new dt(isNaN(c)?60:c)}let i=await r.json();if(i.ok!==!0){let c=i.error??"unknown";if(c==="ratelimited")throw new dt(60);if(c==="invalid_auth"&&e.startsWith("xoxc-")&&!o)throw Error(`Desktop app token (xoxc-) needs its session cookie to be accepted by the public Slack API.
287
+ `;function Vl(){let e=Xn();try{xh(_h(e),{recursive:!0})}catch{}let t=Ph(e);if(!t)return;try{kh(e,384)}catch{}try{return t.exec(Rh),t}catch{try{t.close()}catch{}return}}function Zl(e){if(!ri())return!1;let t=Vl();if(!t)return console.error(` (送信ログに記録できませんでした: ${ii} — ${Xn()})`),!1;try{let n=e.attribution;return t.prepare(`INSERT INTO sent (kind, team, channel, target, ts, thread_ts, permalink, text, sent_at, pid, agent_pid, host, cwd, git_branch, cli, session_id, as_bot)
288
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(e.kind,e.team??null,e.channel,e.target??null,e.ts,e.threadTs??null,e.permalink??null,e.text,Date.now(),n.pid,n.agentPid??null,n.host||null,n.cwd,n.gitBranch??null,n.cli??null,n.sessionId??null,e.asBot?1:0),!0}catch(n){return console.error(` (送信ログに記録できませんでした: ${n instanceof Error?n.message:String(n)})`),!1}finally{try{t.close()}catch{}}}var ii="送信ログを開けません: SQLite が使えないランタイムです (bun、または node >= 22.5 の node:sqlite が必要)";function Ql(e){let t=Vl();if(!t)return;try{let n=[],o=[];if(e.text)n.push("text LIKE ? ESCAPE '\\'"),o.push(`%${oi(e.text)}%`);if(e.channel)n.push("(channel = ? OR target = ?)"),o.push(e.channel,e.channel);if(e.sinceMs!==void 0)n.push("sent_at >= ?"),o.push(e.sinceMs);if(e.session)n.push("session_id LIKE ? ESCAPE '\\'"),o.push(`${oi(e.session)}%`);if(e.cwd)n.push("cwd LIKE ? ESCAPE '\\'"),o.push(`${oi(e.cwd)}%`);if(e.kind)n.push("kind = ?"),o.push(e.kind);let s=`SELECT * FROM sent${n.length?` WHERE ${n.join(" AND ")}`:""} ORDER BY sent_at DESC, id DESC LIMIT ?`;return o.push(e.limit??50),t.prepare(s).all(...o)}finally{try{t.close()}catch{}}}function oi(e){return e.replace(/[\\%_]/g,(t)=>`\\${t}`)}function eu(e,t=Date.now()){let n=e.trim().match(/^(\d+(?:\.\d+)?)\s*(s|m|h|d|w)$/i);if(n){let s={s:1000,m:60000,h:3600000,d:86400000,w:604800000}[n[2].toLowerCase()];return t-Number(n[1])*s}let o=Date.parse(e);return Number.isNaN(o)?void 0:o}class ft extends Error{retryAfter;method;constructor(e,t){super(t?`Slack rate limited on ${t} — retry after ${e}s`:`Slack rate limited — retry after ${e}s`);if(this.name="RateLimitError",this.retryAfter=e,t)this.method=t}}function li(){return(process.env.SLACK_API_BASE??"https://slack.com/api").replace(/\/$/,"")}async function su(e,t,n,o){o=e.startsWith("xoxc-")?o??xt():void 0;let s={};if(o)s.Cookie=`d=${o}`;let r=await fetch(`${li()}/${t}`,{...n,headers:{...n.headers??{},Authorization:`Bearer ${e}`,...s}});if(r.status===429){let c=parseInt(r.headers.get("retry-after")??"60",10);throw new ft(isNaN(c)?60:c,t)}let i=await r.json();if(i.ok!==!0){let c=i.error??"unknown";if(c==="ratelimited")throw new ft(60,t);if(c==="invalid_auth"&&e.startsWith("xoxc-")&&!o)throw Error(`Desktop app token (xoxc-) needs its session cookie to be accepted by the public Slack API.
284
289
  Attach it: slack auth firefox (Linux/macOS/Windows) or slack auth chrome (macOS/Linux)
285
290
  Or replace the token with an xoxp- user token:
286
291
  slack auth login`);if((c==="missing_scope"||c==="cannot_dm_bot")&&e.startsWith("xoxb-")){if(t.startsWith("agents.sessions."))throw Error(`Slack error on ${t}: ${c}. Agent sessions need a granular bot token with chat:write and app membership in the channel.`);throw Error(`Slack error on ${t}: ${c} — ${c==="cannot_dm_bot"?`you're authenticated as a bot, so "@you" is the bot itself and it can't DM itself`:"this bot token lacks the user scope this action needs"}.
287
292
  Tailing/DMing people and listing users need a user session, not a bot token.
288
293
  Switch workspace: slack auth ls then slack auth use <name>
289
- Or import your Slack desktop session: slack auth login`)}throw Error(`Slack error on ${t}: ${c}`)}return i}async function bh(e,t,n,o){let s={};if(o)s.Cookie=`d=${o}`;let r=await fetch(`${ri()}/${t}`,{...n,headers:{...n.headers??{},Authorization:`Bearer ${e}`,...s}});if(r.status===429){let c=parseInt(r.headers.get("retry-after")??"60",10);throw new dt(isNaN(c)?60:c)}let i=await r.json();if(i.ok!==!0){let c=i.error??"unknown";if(c==="ratelimited")throw new dt(60);if((c==="invalid_auth"||c==="not_authed")&&!e.startsWith("xoxc-"))throw Error(`The draft API requires a desktop app session token (xoxc-).
290
- Import from Slack desktop: slack auth login`);if((c==="invalid_auth"||c==="not_authed")&&!o)throw Error(`drafts.list also requires the xoxd session cookie.
291
- Attach it with: slack auth firefox (Linux/macOS/Windows) or slack auth chrome (macOS/Linux)`);throw Error(`Slack error on ${t}: ${c}`)}return i}function Xt(e,t,n={},o){let s=new URLSearchParams({token:e,...n});return bh(e,t,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s.toString()},o)}function ie(e,t,n,o){let s=new URLSearchParams(n).toString();return Zl(e,`${t}?${s}`,{method:"GET"},o)}function xe(e,t,n,o){return Zl(e,t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)},o)}async function ii(e,t){let n=await ie(e,"auth.test",{},t);return{team:n.team??"",teamId:n.team_id??"",url:n.url??"",user:n.user??"",userId:n.user_id??""}}async function Yn(e,t){t=e.startsWith("xoxc-")?t??xt():void 0;let n={Authorization:`Bearer ${e}`};if(t)n.Cookie=`d=${t}`;let o=await fetch(`${ri()}/auth.test`,{method:"GET",headers:n});if(o.status===429){let i=parseInt(o.headers.get("retry-after")??"60",10);throw new dt(isNaN(i)?60:i)}let s=o.headers.get("x-oauth-scopes")??"",r=await o.json();if(r.ok!==!0)throw Error(`Slack error on auth.test: ${r.error??"unknown"}`);return{userId:r.user_id??"",user:r.user??"",botId:r.bot_id??"",team:r.team??"",url:r.url??"",scopes:s.split(",").map((i)=>i.trim()).filter(Boolean)}}async function st(e,t,n=20,o,s,r,i){let c={channel:t,limit:String(n)};if(o!==void 0)c.oldest=o;if(s!==void 0)c.cursor=s;if(i)c.inclusive="true";return ie(e,"conversations.history",c,r)}async function qe(e,t,n,o=50,s){return ie(e,"conversations.replies",{channel:t,ts:n,limit:String(o)},s)}async function Ql(e,t,n){return ie(e,"files.info",{file:t},n)}async function eu(e,t={},n){let o={count:String(Math.min(Math.max(t.count??100,1),200)),page:String(Math.max(t.page??1,1))};if(t.types)o.types=t.types;if(t.channel)o.channel=t.channel;if(t.user)o.user=t.user;return ie(e,"files.list",o,n)}async function tu(e,t,n,o){let s={name:t,schema:n};if(o)s.todo_mode=!0;return await xe(e,"slackLists.create",s)}async function ai(e,t,n={}){let o={list_id:t};if(n.limit)o.limit=n.limit;if(n.cursor)o.cursor=n.cursor;if(n.includeList)o.include_list=!0;return await xe(e,"slackLists.items.list",o)}async function nu(e,t,n){return await xe(e,"slackLists.items.create",{list_id:t,initial_fields:n})}async function su(e,t,n,o){let s={list_id:t,access_level:n};if(o.userIds?.length)s.user_ids=o.userIds;if(o.channelIds?.length)s.channel_ids=o.channelIds;return await xe(e,"slackLists.access.set",s)}async function ou(e,t,n){return await xe(e,"slackLists.items.update",{list_id:t,cells:n})}async function ru(e,t,n={},o){let s={list_id:t};if(n.limit)s.limit=String(n.limit);if(n.cursor)s.cursor=n.cursor;return Xt(e,"lists.records.list",s,o)}async function iu(e,t,n,o,s){return ie(e,"search.messages",{query:t,sort:"timestamp",sort_dir:"desc",count:String(Math.min(Math.max(n,1),100)),page:String(Math.max(o,1))},s)}async function au(e,t,n){return iu(e,t,100,1,n)}async function ci(e,t,n,o){let r=1,i=[],c={ok:!0,messages:{}};while(!0){let l=await iu(e,t,100,r,o),u=Xn(l,["messages","matches"]),d=Array.isArray(u)?u:[];i.push(...d);let f=Number(Xn(l,["messages","paging","pages"])??1);if(c=l,d.length===0||r>=f||i.length>=n)break;r+=1}let a=c;if(!a.messages)a.messages={};return a.messages.matches=i.slice(0,n),a}async function Yt(e,t,n,o,s,r,i,c){let a=i?{channel:t,text:n}:{channel:t,text:n,blocks:[{type:"markdown",text:n}]};if(o!==void 0)a.thread_ts=o;if(s&&o!==void 0)a.reply_broadcast=!0;return(await cu(e,"chat.postMessage",a,c,r)).ts??""}function kh(e){return e instanceof Error&&/: (invalid_metadata\w*|metadata_\w+)$/.test(e.message)}async function cu(e,t,n,o,s){if(!o)return xe(e,t,n,s);try{return await xe(e,t,{...n,metadata:o},s)}catch(r){if(!kh(r))throw r;return xe(e,t,n,s)}}async function lu(e,t,n,o,s,r){let i={channel:t,text:n,post_at:o,blocks:[{type:"markdown",text:n}]};if(s!==void 0)i.thread_ts=s;return(await xe(e,"chat.scheduleMessage",i,r)).scheduled_message_id??""}async function uu(e,t,n){let o={};if(t)o.channel=t;return ie(e,"chat.scheduledMessages.list",o,n)}async function du(e,t,n,o){await xe(e,"chat.deleteScheduledMessage",{channel:t,scheduled_message_id:n},o)}async function Vn(e,t,n,o){return(await ie(e,"chat.getPermalink",{channel:t,message_ts:n},o)).permalink??""}async function Vt(e,t,n,o,s,r,i){return(await cu(e,"chat.update",r?{channel:t,ts:n,text:o}:{channel:t,ts:n,text:o,blocks:[{type:"markdown",text:o}]},i,s)).ts??n}async function fu(e,t,n,o){await xe(e,"chat.delete",{channel:t,ts:n},o)}async function pu(e,t,n,o,s=200,r){let i={channel:t,ts:n,limit:String(s)};if(o!==void 0)i.cursor=o;return ie(e,"conversations.replies",i,r)}async function li(e,t,n,o){await xe(e,"pins.add",{channel:t,timestamp:n},o)}async function mn(e,t,n,o,s){await xe(e,"reactions.add",{channel:t,timestamp:n,name:o},s)}async function hu(e,t,n,o){return((await ie(e,"reactions.get",{channel:t,timestamp:n,full:"true"},o)).message?.reactions??[]).map((r)=>({name:String(r.name??""),users:Array.isArray(r.users)?r.users.map(String):[]}))}async function Zn(e,t,n,o,s){await xe(e,"reactions.remove",{channel:t,timestamp:n,name:o},s)}async function gu(e,t,n=!1,o){let s=await xe(e,"conversations.create",{name:t,is_private:n},o);return{id:s.channel?.id??"",name:s.channel?.name??t}}async function mu(e,t,n,o){await xe(e,"conversations.invite",{channel:t,users:n.join(",")},o)}async function Qn(e,t){let n=[],o="";while(!0){let s={limit:"200",types:"public_channel,private_channel,im,mpim"};if(o)s.cursor=o;let r=await ie(e,"conversations.list",s,t);if(n.push(...r.channels??[]),o=r.response_metadata?.next_cursor??"",!o)break}return{channels:n}}async function ft(e,t,n){let s=(await xe(e,"conversations.open",{users:t},n)).channel?.id;if(!s)throw Error(`Failed to open DM with user ${t}`);return s}async function Du(e,t,n){let o="";while(!0){let s={types:"im",limit:"200"};if(o)s.cursor=o;let r=await ie(e,"conversations.list",s,n);for(let i of r.channels??[])if(i.user===t)return String(i.id??"");if(o=r.response_metadata?.next_cursor??"",!o)break}return""}async function si(e,t,n,o){let s=await Du(e,t,n);if(s)return s;let r=o?`${o} (${t})`:t;throw Error(`No existing DM with ${r}. Open it once in Slack first.`)}function Gt(e){return e.toLowerCase().replace(/[-_\s]/g,"")}function Yl(e,t){let n=Gt(e.name??""),o=Gt(e.real_name??e.profile?.real_name??""),s=Gt(e.profile?.display_name??"");return n===t||o===t||!!s&&s===t}var yu=200;async function wu(e,t,n){let o=0,s=new Set,r="";while(!0){let u={limit:"200"};if(r)u.cursor=r;let d=await ie(e,"users.list",u,n);for(let f of d.members??[]){if(o++,f.id)s.add(f.id);if(Yl(f,t))return{id:f.id??"",workspaceCount:o,connectCount:0,skipped:0,capped:!1}}if(r=d.response_metadata?.next_cursor??"",!r)break}let i=0,c=0,a=!1,l="";while(!0){let u={types:"im",limit:"200"};if(l)u.cursor=l;let d=await ie(e,"conversations.list",u,n);for(let f of d.channels??[]){let h=f.user;if(!h||s.has(h))continue;if(i>=yu){a=!0;break}s.add(h),i++;let m;try{m=(await ie(e,"users.info",{user:h},n)).user}catch(p){if(p instanceof dt)throw p;c++;continue}if(m&&Yl(m,t))return{id:h,dm:String(f.id??""),workspaceCount:o,connectCount:i,skipped:c,capped:a}}if(a)break;if(l=d.response_metadata?.next_cursor??"",!l)break}return{id:"",workspaceCount:o,connectCount:i,skipped:c,capped:a}}function bu(e,t){if(t.workspaceCount===0)return Error(`Cannot resolve ${e}: users.list returned no members at all, so nothing could have matched.
294
+ Or import your Slack desktop session: slack auth login`)}throw Error(`Slack error on ${t}: ${c}`)}return i}async function Nh(e,t,n,o){let s={};if(o)s.Cookie=`d=${o}`;let r=await fetch(`${li()}/${t}`,{...n,headers:{...n.headers??{},Authorization:`Bearer ${e}`,...s}});if(r.status===429){let c=parseInt(r.headers.get("retry-after")??"60",10);throw new ft(isNaN(c)?60:c,t)}let i=await r.json();if(i.ok!==!0){let c=i.error??"unknown";if(c==="ratelimited")throw new ft(60,t);if((c==="invalid_auth"||c==="not_authed")&&!e.startsWith("xoxc-"))throw Error(`${t} requires a desktop app session token (xoxc-).
295
+ Import from Slack desktop: slack auth login`);if((c==="invalid_auth"||c==="not_authed")&&!o)throw Error(`${t} also requires the xoxd session cookie.
296
+ Attach it with: slack auth firefox (Linux/macOS/Windows) or slack auth chrome (macOS/Linux)`);throw Error(`Slack error on ${t}: ${c}`)}return i}function Ct(e,t,n={},o){let s=new URLSearchParams({token:e,...n});return Nh(e,t,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s.toString()},o)}function ie(e,t,n,o){let s=new URLSearchParams(n).toString();return su(e,`${t}?${s}`,{method:"GET"},o)}function be(e,t,n,o){return su(e,t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)},o)}async function ui(e,t){let n=await ie(e,"auth.test",{},t);return{team:n.team??"",teamId:n.team_id??"",url:n.url??"",user:n.user??"",userId:n.user_id??""}}async function Dn(e,t){t=e.startsWith("xoxc-")?t??xt():void 0;let n={Authorization:`Bearer ${e}`};if(t)n.Cookie=`d=${t}`;let o=await fetch(`${li()}/auth.test`,{method:"GET",headers:n});if(o.status===429){let i=parseInt(o.headers.get("retry-after")??"60",10);throw new ft(isNaN(i)?60:i,"auth.test")}let s=o.headers.get("x-oauth-scopes")??"",r=await o.json();if(r.ok!==!0)throw Error(`Slack error on auth.test: ${r.error??"unknown"}`);return{userId:r.user_id??"",user:r.user??"",botId:r.bot_id??"",team:r.team??"",url:r.url??"",scopes:s.split(",").map((i)=>i.trim()).filter(Boolean)}}async function ot(e,t,n=20,o,s,r,i){let c={channel:t,limit:String(n)};if(o!==void 0)c.oldest=o;if(s!==void 0)c.cursor=s;if(i)c.inclusive="true";return ie(e,"conversations.history",c,r)}async function Me(e,t,n,o=50,s){return ie(e,"conversations.replies",{channel:t,ts:n,limit:String(o)},s)}async function ou(e,t,n){return ie(e,"files.info",{file:t},n)}async function ru(e,t={},n){let o={count:String(Math.min(Math.max(t.count??100,1),200)),page:String(Math.max(t.page??1,1))};if(t.types)o.types=t.types;if(t.channel)o.channel=t.channel;if(t.user)o.user=t.user;return ie(e,"files.list",o,n)}async function iu(e,t,n,o){let s={name:t,schema:n};if(o)s.todo_mode=!0;return await be(e,"slackLists.create",s)}async function di(e,t,n={}){let o={list_id:t};if(n.limit)o.limit=n.limit;if(n.cursor)o.cursor=n.cursor;if(n.includeList)o.include_list=!0;return await be(e,"slackLists.items.list",o)}async function au(e,t,n){return await be(e,"slackLists.items.create",{list_id:t,initial_fields:n})}async function cu(e,t,n,o){let s={list_id:t,access_level:n};if(o.userIds?.length)s.user_ids=o.userIds;if(o.channelIds?.length)s.channel_ids=o.channelIds;return await be(e,"slackLists.access.set",s)}async function lu(e,t,n){return await be(e,"slackLists.items.update",{list_id:t,cells:n})}async function uu(e,t,n={},o){let s={list_id:t};if(n.limit)s.limit=String(n.limit);if(n.cursor)s.cursor=n.cursor;return Ct(e,"lists.records.list",s,o)}async function du(e,t,n,o,s){return ie(e,"search.messages",{query:t,sort:"timestamp",sort_dir:"desc",count:String(Math.min(Math.max(n,1),100)),page:String(Math.max(o,1))},s)}async function fu(e,t,n){return du(e,t,100,1,n)}async function fi(e,t,n,o){let r=1,i=[],c={ok:!0,messages:{}};while(!0){let l=await du(e,t,100,r,o),u=Yn(l,["messages","matches"]),d=Array.isArray(u)?u:[];i.push(...d);let f=Number(Yn(l,["messages","paging","pages"])??1);if(c=l,d.length===0||r>=f||i.length>=n)break;r+=1}let a=c;if(!a.messages)a.messages={};return a.messages.matches=i.slice(0,n),a}async function Yt(e,t,n,o,s,r,i,c){let a=i?{channel:t,text:n}:{channel:t,text:n,blocks:[{type:"markdown",text:n}]};if(o!==void 0)a.thread_ts=o;if(s&&o!==void 0)a.reply_broadcast=!0;return(await pu(e,"chat.postMessage",a,c,r)).ts??""}function Bh(e){return e instanceof Error&&/: (invalid_metadata\w*|metadata_\w+)$/.test(e.message)}async function pu(e,t,n,o,s){if(!o)return be(e,t,n,s);try{return await be(e,t,{...n,metadata:o},s)}catch(r){if(!Bh(r))throw r;return be(e,t,n,s)}}async function hu(e,t,n,o,s,r){let i={channel:t,text:n,post_at:o,blocks:[{type:"markdown",text:n}]};if(s!==void 0)i.thread_ts=s;return(await be(e,"chat.scheduleMessage",i,r)).scheduled_message_id??""}async function gu(e,t,n){let o={};if(t)o.channel=t;return ie(e,"chat.scheduledMessages.list",o,n)}async function mu(e,t,n,o){await be(e,"chat.deleteScheduledMessage",{channel:t,scheduled_message_id:n},o)}async function Vn(e,t,n,o){return(await ie(e,"chat.getPermalink",{channel:t,message_ts:n},o)).permalink??""}async function Vt(e,t,n,o,s,r,i){return(await pu(e,"chat.update",r?{channel:t,ts:n,text:o}:{channel:t,ts:n,text:o,blocks:[{type:"markdown",text:o}]},i,s)).ts??n}async function Du(e,t,n,o){await be(e,"chat.delete",{channel:t,ts:n},o)}async function yu(e,t,n,o,s=200,r){let i={channel:t,ts:n,limit:String(s)};if(o!==void 0)i.cursor=o;return ie(e,"conversations.replies",i,r)}async function pi(e,t,n,o){await be(e,"pins.add",{channel:t,timestamp:n},o)}async function yn(e,t,n,o,s){await be(e,"reactions.add",{channel:t,timestamp:n,name:o},s)}async function wu(e,t,n,o){return((await ie(e,"reactions.get",{channel:t,timestamp:n,full:"true"},o)).message?.reactions??[]).map((r)=>({name:String(r.name??""),users:Array.isArray(r.users)?r.users.map(String):[]}))}async function Zn(e,t,n,o,s){await be(e,"reactions.remove",{channel:t,timestamp:n,name:o},s)}async function bu(e,t,n=!1,o){let s=await be(e,"conversations.create",{name:t,is_private:n},o);return{id:s.channel?.id??"",name:s.channel?.name??t}}async function ku(e,t,n,o){let s=await be(e,"conversations.rename",{channel:t,name:n},o);return{id:s.channel?.id??t,name:s.channel?.name??n}}async function xu(e,t,n,o){await be(e,"conversations.invite",{channel:t,users:n.join(",")},o)}async function Qn(e,t){let n=[],o="";while(!0){let s={limit:"200",types:"public_channel,private_channel,im,mpim"};if(o)s.cursor=o;let r=await ie(e,"conversations.list",s,t);if(n.push(...r.channels??[]),o=r.response_metadata?.next_cursor??"",!o)break}return{channels:n}}async function pt(e,t,n){let s=(await be(e,"conversations.open",{users:t},n)).channel?.id;if(!s)throw Error(`Failed to open DM with user ${t}`);return s}async function Eu(e,t,n){let o="";while(!0){let s={types:"im",limit:"200"};if(o)s.cursor=o;let r=await ie(e,"conversations.list",s,n);for(let i of r.channels??[])if(i.user===t)return String(i.id??"");if(o=r.response_metadata?.next_cursor??"",!o)break}return""}async function ai(e,t,n,o){let s=await Eu(e,t,n);if(s)return s;let r=o?`${o} (${t})`:t;throw Error(`No existing DM with ${r}. Open it once in Slack first.`)}function Xt(e){return e.toLowerCase().replace(/[-_\s]/g,"")}function tu(e,t){let n=Xt(e.name??""),o=Xt(e.real_name??e.profile?.real_name??""),s=Xt(e.profile?.display_name??"");return n===t||o===t||!!s&&s===t}var Cu=200;async function Su(e,t,n){let o=0,s=new Set,r="";while(!0){let u={limit:"200"};if(r)u.cursor=r;let d=await ie(e,"users.list",u,n);for(let f of d.members??[]){if(o++,f.id)s.add(f.id);if(tu(f,t))return{id:f.id??"",workspaceCount:o,connectCount:0,skipped:0,capped:!1}}if(r=d.response_metadata?.next_cursor??"",!r)break}let i=0,c=0,a=!1,l="";while(!0){let u={types:"im",limit:"200"};if(l)u.cursor=l;let d=await ie(e,"conversations.list",u,n);for(let f of d.channels??[]){let h=f.user;if(!h||s.has(h))continue;if(i>=Cu){a=!0;break}s.add(h),i++;let m;try{m=(await ie(e,"users.info",{user:h},n)).user}catch(p){if(p instanceof ft)throw p;c++;continue}if(m&&tu(m,t))return{id:h,dm:String(f.id??""),workspaceCount:o,connectCount:i,skipped:c,capped:a}}if(a)break;if(l=d.response_metadata?.next_cursor??"",!l)break}return{id:"",workspaceCount:o,connectCount:i,skipped:c,capped:a}}function _u(e,t){if(t.workspaceCount===0)return Error(`Cannot resolve ${e}: users.list returned no members at all, so nothing could have matched.
292
297
  `+`That is a token or scope fault, not a wrong handle — this says nothing about whether ${e} exists.
293
- Check who you are: slack auth ls`);let n=t.connectCount?`${t.workspaceCount} workspace account(s) and ${t.connectCount} Slack Connect DM partner(s)`:`${t.workspaceCount} workspace account(s)`,o=[];if(t.capped)o.push(`stopped after ${yu} Slack Connect DM partners, so there may be more`);if(t.skipped)o.push(`${t.skipped} DM partner profile(s) could not be read and were never compared`);return Error(`User not found: ${e} — searched ${n}, none matched.
298
+ Check who you are: slack auth ls`);let n=t.connectCount?`${t.workspaceCount} workspace account(s) and ${t.connectCount} Slack Connect DM partner(s)`:`${t.workspaceCount} workspace account(s)`,o=[];if(t.capped)o.push(`stopped after ${Cu} Slack Connect DM partners, so there may be more`);if(t.skipped)o.push(`${t.skipped} DM partner profile(s) could not be read and were never compared`);return Error(`User not found: ${e} — searched ${n}, none matched.
294
299
  `+(o.length?`This search was incomplete: ${o.join("; ")}.
295
300
  `:"")+`Slack Connect people from another workspace are not in users.list, so if they never
296
301
  DMed you they cannot be found by name at all. Look them up and use their ID:
297
- slack user ls --external`)}async function pt(e,t,n){let o=t.startsWith("@")?t.slice(1):t;if(oi(o))return o;if(!t.startsWith("@"))throw Error(`Expected @user or a user ID, got: ${t}`);let s=Gt(o),r=await ie(e,"auth.test",{},n);if(s==="you"||s==="me"||Gt(r.user??"")===s){if(!r.user_id)throw Error("auth.test did not return user_id");return r.user_id}let i=await wu(e,s,n);if(i.id)return i.id;throw bu(t,i)}function Zt(e){let t=e.match(/(?:app\.slack\.com\/client\/T[A-Za-z0-9]+|[A-Za-z0-9-]+\.slack\.com\/archives)\/([A-Za-z0-9]+)(?:\/p(\d{10})(\d{6}))?/);if(!t)return;let n=t[1],o=t[2]&&t[3]?`${t[2]}.${t[3]}`:void 0,s=e.indexOf("?"),r=s>=0?new URLSearchParams(e.slice(s)):void 0,i=r?.get("thread_ts")??void 0,l={channel:r?.get("cid")??void 0??n};if(o)l.ts=o;if(i)l.threadTs=i;return l}function xh(e){return Zt(e)?.channel}function Vl(e){return/^[CDG][A-Z0-9]{8,}$/.test(e)}function oi(e){return/^[UW][A-Z0-9]{6,}$/.test(e)}async function he(e,t,n){let o=xh(t);if(o)return o;if(!t.startsWith("@")&&!t.startsWith("#")){if(Vl(t))return t;if(oi(t))return si(e,t,n);throw Error(`Target must start with # or @ (or be a Slack URL/ID), got: ${t}`)}if(t.startsWith("#")&&Vl(t.slice(1)))return t.slice(1);let s=t.startsWith("@"),r=t.slice(1),i=Gt(r);if(s){if(oi(r))return si(e,r,n);let l=await ie(e,"auth.test",{},n);if(i==="you"||i==="me"||Gt(l.user??"")===i){let f=l.user_id;if(!f)throw Error("auth.test did not return user_id");return await Du(e,f,n)||ft(e,f,n)}let d=await wu(e,i,n);if(!d.id)throw bu(t,d);if(d.dm)return d.dm;return si(e,d.id,n,t)}let c=r.toLowerCase(),a="";while(!0){let l={limit:"200",types:"public_channel,private_channel",exclude_archived:"true"};if(a)l.cursor=a;let u=await ie(e,"conversations.list",l,n);for(let d of u.channels??[])if(String(d.name??"").toLowerCase()===c)return String(d.id??"");if(a=u.response_metadata?.next_cursor??"",!a)break}throw Error(`channel not found: ${t}`)}async function es(e,t,n){try{let o=await ie(e,"users.info",{user:t},n),s=o.user?.profile?.display_name,r=s&&s.length>0?s:o.user?.real_name??o.user?.name??t,i=o.user?.name??t;return[r,i]}catch{return[t,t]}}async function Ie(e,t,n){try{let o=await ie(e,"users.info",{user:t},n),s=o.user?.profile?.display_name;if(s&&s.length>0)return s;return o.user?.real_name??o.user?.name??t}catch{return t}}async function ku(e,t){let n=[],o="";while(!0){let s={limit:"200"};if(o)s.cursor=o;let r=await ie(e,"users.list",s,t);if(n.push(...r.members??[]),o=r.response_metadata?.next_cursor??"",!o)break}return{members:n}}async function xu(e,t,n){let o=[],s="";while(!0){let r={channel:t,limit:"200"};if(s)r.cursor=s;let i=await ie(e,"conversations.members",r,n);if(o.push(...i.members??[]),s=i.response_metadata?.next_cursor??"",!s)break}return o}async function ts(e,t){return Xt(e,"drafts.list",{},t)}async function Cu(e,t,n,o){let{randomUUID:s}=await import("node:crypto"),r=JSON.stringify([{type:"rich_text",elements:[{type:"rich_text_section",elements:[{type:"text",text:n}]}]}]);return Xt(e,"drafts.create",{client_msg_id:s(),destinations:JSON.stringify([{channel_id:t}]),blocks:r,file_ids:JSON.stringify([]),is_from_composer:"true"},o)}async function Eu(e,t,n,o,s){let r=JSON.stringify([{type:"rich_text",elements:[{type:"rich_text_section",elements:[{type:"text",text:o}]}]}]),i=(Date.now()/1000).toFixed(6);return Xt(e,"drafts.update",{draft_id:t,client_last_updated_ts:i,destinations:JSON.stringify([{channel_id:n}]),blocks:r,file_ids:JSON.stringify([])},s)}async function Su(e,t,n){return Xt(e,"conversations.info",{channel:t},n)}async function ns(e,t,n){return ie(e,"users.info",{user:t},n)}async function Dn(e,t,n){return ie(e,"conversations.info",{channel:t},n)}async function _u(e,t,n){let o=(Date.now()/1000).toFixed(6);return Xt(e,"drafts.delete",{draft_id:t,client_last_updated_ts:o},n)}async function ui(e,t){let n=await Xt(e,"auth.test",{},t);return{userId:String(n.user_id??""),teamId:String(n.team_id??"")}}async function Fu(e,t,n,o={},s){let{statSync:r,readFileSync:i}=await import("node:fs"),{basename:c}=await import("node:path"),a=r(n),l=c(n),u=await ie(e,"files.getUploadURLExternal",{filename:l,length:String(a.size)},s),{upload_url:d,file_id:f}=u;if(!d||!f)throw Error("files.getUploadURLExternal returned no upload_url/file_id");let h=i(n),m=await fetch(d,{method:"POST",headers:{"Content-Type":"application/octet-stream"},body:h});if(!m.ok)throw Error(`Upload PUT failed: ${m.status} ${m.statusText}`);let p={files:[{id:f,title:o.title??l}],channel_id:t};if(o.threadTs)p.thread_ts=o.threadTs;if(o.initialComment)p.initial_comment=o.initialComment;let D=await xe(e,"files.completeUploadExternal",p,s),k={fileId:f},x=D.files?.[0]?.permalink;if(x)k.permalink=x;return k}function Xn(e,t){let n=e;for(let o of t){if(n===void 0||n===null)return;if(typeof o==="number"){if(!Array.isArray(n))return;n=n[o]??void 0}else{if(typeof n!=="object"||Array.isArray(n))return;n=n[o]}}return n}import{existsSync as Oh,readFileSync as Ph}from"node:fs";import{homedir as Rh}from"node:os";import{join as Nh}from"node:path";import{existsSync as Ch,mkdirSync as Eh,readFileSync as Sh,writeFileSync as _h}from"node:fs";import{homedir as Fh}from"node:os";import{dirname as $h,join as Ah}from"node:path";var Th=3600000,eo={now:()=>Date.now(),path:()=>Ah(process.env.HOME||Fh(),".config","slack-cli","cache.json")},to=!0,Et;function $u(){return{channels:{},users:{}}}function di(){if(Et)return Et;if(Et=$u(),!to)return Et;try{let e=eo.path();if(!Ch(e))return Et;let t=JSON.parse(Sh(e,"utf8"));for(let n of["channels","users"]){let o=t?.[n];if(!o||typeof o!=="object"||Array.isArray(o))continue;for(let[s,r]of Object.entries(o))if(r&&typeof r==="object"&&typeof r.value==="string"&&typeof r.expires==="number")Et[n][s]={value:r.value,expires:r.expires}}}catch{Et=$u()}return Et}function Ih(e){if(!to)return;try{let t=eo.path();Eh($h(t),{recursive:!0}),_h(t,JSON.stringify(e,null,2)+`
298
- `)}catch{}}function Au(e,t){return e?`${e} ${t}`:void 0}function no(e,t,n){if(!to)return;let o=Au(t,n);if(!o)return;let s=di()[e][o];if(!s)return;if(s.expires<=eo.now()){delete di()[e][o];return}return s.value}function so(e,t,n,o,s=Th){if(!to)return;let r=Au(t,n);if(!r)return;let i=di();i[e][r]={value:o,expires:eo.now()+s},Ih(i)}var fi={marker:"pushpin",progress:{done:"white_check_mark",dropped:"no_entry_sign",doing:"eyes",pending:"hourglass_flowing_sand"},flags:{alert:"exclamation","needs-discussion":"thinking_face",waiting:"speech_balloon",blocked:"lock"}},yn=["done","dropped","doing","pending"],Pu=["alert","needs-discussion","waiting","blocked"];function Bh(){return Nh(process.env.HOME||Rh(),".config","slack-cli","todo.json")}function oo(e){return e.replace(/^:+|:+$/g,"")}function ss(e=Bh()){let t={marker:fi.marker,progress:{...fi.progress},flags:{...fi.flags}};try{if(!Oh(e))return t;let n=JSON.parse(Ph(e,"utf8"));if(typeof n.marker==="string"&&n.marker.trim())t.marker=oo(n.marker.trim());for(let o of yn){let s=n.progress?.[o];if(typeof s==="string"&&s.trim())t.progress[o]=oo(s.trim())}for(let o of Pu){let s=n.flags?.[o];if(typeof s==="string"&&s.trim())t.flags[o]=oo(s.trim())}}catch{}return t}function Tu(e,t,n=!1){return`${n?"-":""}${t?"has":"hasmy"}::${oo(e)}:`}function Ru(e,t,n={}){let o=n.shared===!0,s=(c)=>Tu(c,o),r=(c)=>Tu(c,o,!0),i=[];if(e==="untriaged")i.push(s(t.marker),...yn.map((c)=>r(t.progress[c])));else if(e==="stuck")i.push(s(t.marker),r(t.progress.done),r(t.progress.dropped),`(${Pu.map((c)=>s(t.flags[c])).join(" OR ")})`);else if(e==="open")i.push(s(t.marker),r(t.progress.done),r(t.progress.dropped));else{let c=yn.indexOf(e);i.push(s(t.progress[e]));for(let a of yn.slice(0,c))i.push(r(t.progress[a]))}if(n.in){let c=n.in.startsWith("#")||n.in.startsWith("@")?n.in:`#${n.in}`;i.push(`in:${c}`)}if(n.from){let c=n.from==="me"||n.from.startsWith("@")?n.from:`@${n.from}`;i.push(`from:${c}`)}return i.join(" ")}var Mh=3,vh={sleep:(e)=>Lh()?Promise.resolve():new Promise((t)=>setTimeout(t,e))};function Lh(){return!!process.env.VITEST||!1||!!process.env.BUN_TEST}async function Oe(e,t,n=Mh){for(let o=0;;o++)try{return await t()}catch(s){if(!(s instanceof Qe))throw s;if(o>=n)throw Error(`Slack rate limit hit on ${e} — gave up after ${n} retries. Try again in a minute.`);console.error(`Warning: Slack rate limit hit on ${e} — backing off for ${s.retryAfter}s`),await vh.sleep(s.retryAfter*1000)}}var Iu=new Map;async function Nu(e,t){let n=Iu.get(e);if(n)return n;let o=await Oe("auth.test",()=>pn(e,t)),s={userId:o.userId,teamId:o.teamId};return Iu.set(e,s),s}async function Bu(e,t){return(await Nu(e,t)).userId}async function pi(e,t){try{return(await Nu(e,t)).teamId}catch{return""}}async function hi(e,t,n,o){if(!t.startsWith("#"))return n(e,t,o);let s=await pi(e,o),r=no("channels",s,t);if(r)return r;let i=await Oe("resolveChannel",()=>n(e,t,o));return so("channels",s,t,i),i}async function Mu(e,t,n,o){let s=await pi(e,o),r=no("users",s,t);if(r)return r;let i=await Oe("users.info",()=>n(e,t,o));if(i&&i!==t)so("users",s,t,i);return i}async function vu(e,t,n,o){let s=await pi(e,o),r=no("users",s,`tz:${t}`);if(r)return r==="?"?null:r;let i=null;try{let c=await Oe("users.info",()=>n(e,t,o));if(c?.user?.is_bot===!0||t==="USLACKBOT")return Ou(s,t,null);let a=c?.user?.tz;i=typeof a==="string"&&a?a:null}catch{return null}return Ou(s,t,i)}function Ou(e,t,n){return so("users",e,`tz:${t}`,n??"?"),n}async function Lu(e,t,n,o,s,r){let i=s.progress[o],c=await Bu(e,r),a=await Oe("reactions.get",()=>Bc(e,t,n,r)),l=new Set(a.filter((h)=>h.users.includes(c)).map((h)=>h.name)),u=yn.map((h)=>s.progress[h]).filter((h)=>l.has(h));if(u.length===1&&u[0]===i)return{noop:!0,removed:[],leftover:[]};if(!l.has(i))await Oe("reactions.add",()=>Ps(e,t,n,i,r));let d=[],f=[];for(let h of u){if(h===i)continue;try{await Oe("reactions.remove",()=>Rs(e,t,n,h,r)),d.push(h)}catch{f.push(h)}}return{noop:!1,added:o,removed:d,leftover:f}}async function ju(e,t,n,o,s,r,i){let c=s.flags[o];if(r)await Oe("reactions.remove",()=>Rs(e,t,n,c,i));else await Oe("reactions.add",()=>Ps(e,t,n,c,i));return c}var gi=1000;async function Wu(e,t,n,o={}){let s=o.limit??gi,r=o.cookie,i=await Bu(e,r),c=yn.map((f)=>n.progress[f]),a=[],l=0,u,d=!1;while(l<s){let f=Math.min(200,s-l),h=await Oe("conversations.history",()=>vn(e,t,f,void 0,u,r)),m=h.messages??[];l+=m.length;for(let p of m){let D=String(p.ts??"");if(!D)continue;let k=new Set((p.reactions??[]).filter((E)=>(E.users??[]).map(String).includes(i)).map((E)=>String(E.name??""))),x=c.filter((E)=>k.has(E));if(x.length<2)continue;a.push({ts:D,text:String(p.text??"").split(`
299
- `)[0]??"",emoji:x,keep:x[0]})}if(u=h.response_metadata?.next_cursor||void 0,!u||m.length===0)break;if(l>=s){d=!0;break}}if(o.fix)for(let f of a)try{try{await Oe("reactions.add",()=>Ps(e,t,f.ts,f.keep,r))}catch(h){if(!(h instanceof Error)||!/already_reacted/.test(h.message))throw h}for(let h of f.emoji){if(h===f.keep)continue;await Oe("reactions.remove",()=>Rs(e,t,f.ts,h,r))}f.fixed=!0}catch(h){f.fixed=!1,f.error=h instanceof Error?h.message:String(h)}return{scanned:l,findings:a,truncated:d}}var jh=!0,Wh;function mi(e){if(jh=e,!e)Wh=void 0}function Ge(e){return e.replace(new RegExp(`[${"\\\\¥"}](.)`,"gs"),(t,n)=>{switch(n){case"n":return`
300
- `;case"t":return"\t";case"\\":case"¥":return n==="¥"?"¥":"\\";default:return t}})}function Di(e){return e.replace(new RegExp(`[${"\\\\¥"}]`,"g"),(t)=>`\\${t}`).replace(/\n/g,"\\n").replace(/\t/g,"\\t")}var wn=(e)=>e&&typeof e==="object"&&!Array.isArray(e)?e:{},Se=(e)=>typeof e==="string"?e:"";function Uh(e){return(Array.isArray(e.message_blocks)?e.message_blocks:[]).map((n)=>Se(wn(wn(n).message).text)).filter(Boolean).join(`
301
- `)}function yi(e){return(Array.isArray(e.attachments)?e.attachments:[]).map(wn).map((n)=>{let o=n.is_share===!0||n.is_msg_unfurl===!0||Array.isArray(n.message_blocks),s=wn(wn((Array.isArray(n.message_blocks)?n.message_blocks:[])[0]));return{shared:o,unfurl:!o&&!!Se(n.original_url),author_id:Se(n.author_id)||Se(wn(s.message).user)||null,author_name:Se(n.author_name)||null,channel_id:Se(n.channel_id)||Se(s.channel)||null,ts:Se(n.ts)||Se(s.ts)||null,title:Se(n.title)||null,text:Se(n.text)||Uh(n)||Se(n.pretext)||Se(n.fallback),permalink:Se(n.from_url)||Se(n.title_link)||Se(n.original_url)||null}})}function Uu(e,t){return e.filter((n)=>!n.unfurl&&(n.text||n.title)).map((n)=>{let o=n.author_name??n.author_id,s=n.shared?`↪ shared message${o?` from @${o}`:""}${n.channel_id?` in <#${n.channel_id}>`:""}${n.ts?` · ${t(n.ts)}`:""}`:`▸ ${n.title??"attachment"}`,r=n.text?n.text.replace(/\n+$/,"").split(`
302
+ slack user ls --external`)}async function ht(e,t,n){let o=t.startsWith("@")?t.slice(1):t;if(ci(o))return o;if(!t.startsWith("@"))throw Error(`Expected @user or a user ID, got: ${t}`);let s=Xt(o),r=await ie(e,"auth.test",{},n);if(s==="you"||s==="me"||Xt(r.user??"")===s){if(!r.user_id)throw Error("auth.test did not return user_id");return r.user_id}let i=await Su(e,s,n);if(i.id)return i.id;throw _u(t,i)}function Zt(e){let t=e.match(/(?:app\.slack\.com\/client\/T[A-Za-z0-9]+|[A-Za-z0-9-]+\.slack\.com\/archives)\/([A-Za-z0-9]+)(?:\/p(\d{10})(\d{6}))?/);if(!t)return;let n=t[1],o=t[2]&&t[3]?`${t[2]}.${t[3]}`:void 0,s=e.indexOf("?"),r=s>=0?new URLSearchParams(e.slice(s)):void 0,i=r?.get("thread_ts")??void 0,l={channel:r?.get("cid")??void 0??n};if(o)l.ts=o;if(i)l.threadTs=i;return l}function vh(e){return Zt(e)?.channel}function nu(e){return/^[CDG][A-Z0-9]{8,}$/.test(e)}function ci(e){return/^[UW][A-Z0-9]{6,}$/.test(e)}async function ue(e,t,n){let o=vh(t);if(o)return o;if(!t.startsWith("@")&&!t.startsWith("#")){if(nu(t))return t;if(ci(t))return ai(e,t,n);throw Error(`Target must start with # or @ (or be a Slack URL/ID), got: ${t}`)}if(t.startsWith("#")&&nu(t.slice(1)))return t.slice(1);let s=t.startsWith("@"),r=t.slice(1),i=Xt(r);if(s){if(ci(r))return ai(e,r,n);let l=await ie(e,"auth.test",{},n);if(i==="you"||i==="me"||Xt(l.user??"")===i){let f=l.user_id;if(!f)throw Error("auth.test did not return user_id");return await Eu(e,f,n)||pt(e,f,n)}let d=await Su(e,i,n);if(!d.id)throw _u(t,d);if(d.dm)return d.dm;return ai(e,d.id,n,t)}let c=r.toLowerCase(),a="";while(!0){let l={limit:"200",types:"public_channel,private_channel",exclude_archived:"true"};if(a)l.cursor=a;let u=await ie(e,"conversations.list",l,n);for(let d of u.channels??[])if(String(d.name??"").toLowerCase()===c)return String(d.id??"");if(a=u.response_metadata?.next_cursor??"",!a)break}throw Error(`channel not found: ${t}`)}async function es(e,t,n){try{let o=await ie(e,"users.info",{user:t},n),s=o.user?.profile?.display_name,r=s&&s.length>0?s:o.user?.real_name??o.user?.name??t,i=o.user?.name??t;return[r,i]}catch{return[t,t]}}async function Ae(e,t,n){try{let o=await ie(e,"users.info",{user:t},n),s=o.user?.profile?.display_name;if(s&&s.length>0)return s;return o.user?.real_name??o.user?.name??t}catch{return t}}async function Fu(e,t){let n=[],o="";while(!0){let s={limit:"200"};if(o)s.cursor=o;let r=await ie(e,"users.list",s,t);if(n.push(...r.members??[]),o=r.response_metadata?.next_cursor??"",!o)break}return{members:n}}async function $u(e,t,n){let o=[],s="";while(!0){let r={channel:t,limit:"200"};if(s)r.cursor=s;let i=await ie(e,"conversations.members",r,n);if(o.push(...i.members??[]),s=i.response_metadata?.next_cursor??"",!s)break}return o}async function Au(e,t={},n){let o={limit:String(t.limit??50)};if(t.filter)o.filter=t.filter;if(t.cursor)o.cursor=t.cursor;return Ct(e,"saved.list",o,n)}async function ts(e,t){return Ct(e,"drafts.list",{},t)}async function Tu(e,t,n,o){let{randomUUID:s}=await import("node:crypto"),r=JSON.stringify([{type:"rich_text",elements:[{type:"rich_text_section",elements:Rs(n)}]}]);return Ct(e,"drafts.create",{client_msg_id:s(),destinations:JSON.stringify([{channel_id:t}]),blocks:r,file_ids:JSON.stringify([]),is_from_composer:"true"},o)}async function Iu(e,t,n,o,s){let r=JSON.stringify([{type:"rich_text",elements:[{type:"rich_text_section",elements:Rs(o)}]}]),i=(Date.now()/1000).toFixed(6);return Ct(e,"drafts.update",{draft_id:t,client_last_updated_ts:i,destinations:JSON.stringify([{channel_id:n}]),blocks:r,file_ids:JSON.stringify([])},s)}async function Ou(e,t,n){return Ct(e,"conversations.info",{channel:t},n)}async function ns(e,t,n){return ie(e,"users.info",{user:t},n)}async function Qt(e,t,n){return ie(e,"conversations.info",{channel:t},n)}async function Pu(e,t,n){let o=(Date.now()/1000).toFixed(6);return Ct(e,"drafts.delete",{draft_id:t,client_last_updated_ts:o},n)}async function hi(e,t){let n=await Ct(e,"auth.test",{},t);return{userId:String(n.user_id??""),teamId:String(n.team_id??"")}}async function Ru(e,t,n,o={},s){let{statSync:r,readFileSync:i}=await import("node:fs"),{basename:c}=await import("node:path"),a=r(n),l=c(n),u=await ie(e,"files.getUploadURLExternal",{filename:l,length:String(a.size)},s),{upload_url:d,file_id:f}=u;if(!d||!f)throw Error("files.getUploadURLExternal returned no upload_url/file_id");let h=i(n),m=await fetch(d,{method:"POST",headers:{"Content-Type":"application/octet-stream"},body:h});if(!m.ok)throw Error(`Upload PUT failed: ${m.status} ${m.statusText}`);let p={files:[{id:f,title:o.title??l}],channel_id:t};if(o.threadTs)p.thread_ts=o.threadTs;if(o.initialComment)p.initial_comment=o.initialComment;let D=await be(e,"files.completeUploadExternal",p,s),k={fileId:f},x=D.files?.[0]?.permalink;if(x)k.permalink=x;return k}function Yn(e,t){let n=e;for(let o of t){if(n===void 0||n===null)return;if(typeof o==="number"){if(!Array.isArray(n))return;n=n[o]??void 0}else{if(typeof n!=="object"||Array.isArray(n))return;n=n[o]}}return n}var Bu=["todo","saved","completed","archived"],ss=(e)=>typeof e==="string"?e:"",Nu=(e)=>{let t=typeof e==="number"||typeof e==="string"?Number(e):0;return Number.isFinite(t)?t:0};function vu(e){let t=e&&typeof e==="object"&&!Array.isArray(e)?e:{};return(Array.isArray(t.saved_items)?t.saved_items:[]).filter((o)=>!!o&&typeof o==="object"&&!Array.isArray(o)).map((o)=>({channel:ss(o.item_id),ts:ss(o.ts),due:Nu(o.date_due),completed:Nu(o.date_completed),todoState:ss(o.todo_state),state:ss(o.state),archived:o.is_archived===!0,itemType:ss(o.item_type)}))}function Lu(e){return[...e].sort((t,n)=>{if(t.due&&n.due)return t.due-n.due;if(t.due!==n.due)return t.due?-1:1;return Number(n.ts)-Number(t.ts)})}function no(e){return e.completed>0||e.state==="completed"}function Mu(e,t,n){let o=no(e)?"☑":e.todoState==="to_do"?"☐":"·";if(!e.due)return`${o} no due date`;let s=!no(e)&&e.due<t?" OVERDUE":"";return`${o} due ${n(e.due)}${s}`}function ju(e,t,n){return`${e.replace(/\/+$/,"")}/archives/${t}/p${n.replace(".","")}`}import{existsSync as qh,readFileSync as Gh}from"node:fs";import{homedir as Xh}from"node:os";import{join as Yh}from"node:path";import{existsSync as Lh,mkdirSync as Mh,readFileSync as jh,writeFileSync as Wh}from"node:fs";import{homedir as Uh}from"node:os";import{dirname as Jh,join as Kh}from"node:path";var Hh=3600000,so={now:()=>Date.now(),path:()=>Kh(process.env.HOME||Uh(),".config","slack-cli","cache.json")},oo=!0,St;function Wu(){return{channels:{},users:{}}}function gi(){if(St)return St;if(St=Wu(),!oo)return St;try{let e=so.path();if(!Lh(e))return St;let t=JSON.parse(jh(e,"utf8"));for(let n of["channels","users"]){let o=t?.[n];if(!o||typeof o!=="object"||Array.isArray(o))continue;for(let[s,r]of Object.entries(o))if(r&&typeof r==="object"&&typeof r.value==="string"&&typeof r.expires==="number")St[n][s]={value:r.value,expires:r.expires}}}catch{St=Wu()}return St}function zh(e){if(!oo)return;try{let t=so.path();Mh(Jh(t),{recursive:!0}),Wh(t,JSON.stringify(e,null,2)+`
303
+ `)}catch{}}function Uu(e,t){return e?`${e} ${t}`:void 0}function ro(e,t,n){if(!oo)return;let o=Uu(t,n);if(!o)return;let s=gi()[e][o];if(!s)return;if(s.expires<=so.now()){delete gi()[e][o];return}return s.value}function io(e,t,n,o,s=Hh){if(!oo)return;let r=Uu(t,n);if(!r)return;let i=gi();i[e][r]={value:o,expires:so.now()+s},zh(i)}var mi={marker:"pushpin",progress:{done:"white_check_mark",dropped:"no_entry_sign",doing:"eyes",pending:"hourglass_flowing_sand"},flags:{alert:"exclamation","needs-discussion":"thinking_face",waiting:"speech_balloon",blocked:"lock"}},wn=["done","dropped","doing","pending"],zu=["alert","needs-discussion","waiting","blocked"];function Vh(){return Yh(process.env.HOME||Xh(),".config","slack-cli","todo.json")}function ao(e){return e.replace(/^:+|:+$/g,"")}function os(e=Vh()){let t={marker:mi.marker,progress:{...mi.progress},flags:{...mi.flags}};try{if(!qh(e))return t;let n=JSON.parse(Gh(e,"utf8"));if(typeof n.marker==="string"&&n.marker.trim())t.marker=ao(n.marker.trim());for(let o of wn){let s=n.progress?.[o];if(typeof s==="string"&&s.trim())t.progress[o]=ao(s.trim())}for(let o of zu){let s=n.flags?.[o];if(typeof s==="string"&&s.trim())t.flags[o]=ao(s.trim())}}catch{}return t}function Ju(e,t,n=!1){return`${n?"-":""}${t?"has":"hasmy"}::${ao(e)}:`}function qu(e,t,n={}){let o=n.shared===!0,s=(c)=>Ju(c,o),r=(c)=>Ju(c,o,!0),i=[];if(e==="untriaged")i.push(s(t.marker),...wn.map((c)=>r(t.progress[c])));else if(e==="stuck")i.push(s(t.marker),r(t.progress.done),r(t.progress.dropped),`(${zu.map((c)=>s(t.flags[c])).join(" OR ")})`);else if(e==="open")i.push(s(t.marker),r(t.progress.done),r(t.progress.dropped));else{let c=wn.indexOf(e);i.push(s(t.progress[e]));for(let a of wn.slice(0,c))i.push(r(t.progress[a]))}if(n.in){let c=n.in.startsWith("#")||n.in.startsWith("@")?n.in:`#${n.in}`;i.push(`in:${c}`)}if(n.from){let c=n.from==="me"||n.from.startsWith("@")?n.from:`@${n.from}`;i.push(`from:${c}`)}return i.join(" ")}var Zh=3,Qh={sleep:(e)=>eg()?Promise.resolve():new Promise((t)=>setTimeout(t,e))};function eg(){return!!process.env.VITEST||!1||!!process.env.BUN_TEST}async function Oe(e,t,n=Zh){for(let o=0;;o++)try{return await t()}catch(s){if(!(s instanceof et))throw s;if(o>=n)throw Error(`Slack rate limit hit on ${e} — gave up after ${n} retries. Try again in a minute.`);console.error(`Warning: Slack rate limit hit on ${e} — backing off for ${s.retryAfter}s`),await Qh.sleep(s.retryAfter*1000)}}var Ku=new Map;async function Gu(e,t){let n=Ku.get(e);if(n)return n;let o=await Oe("auth.test",()=>hn(e,t)),s={userId:o.userId,teamId:o.teamId};return Ku.set(e,s),s}async function Xu(e,t){return(await Gu(e,t)).userId}async function Di(e,t){try{return(await Gu(e,t)).teamId}catch{return""}}async function yi(e,t,n,o){if(!t.startsWith("#"))return n(e,t,o);let s=await Di(e,o),r=ro("channels",s,t);if(r)return r;let i=await Oe("resolveChannel",()=>n(e,t,o));return io("channels",s,t,i),i}async function Yu(e,t,n,o){let s=await Di(e,o),r=ro("users",s,t);if(r)return r;let i=await Oe("users.info",()=>n(e,t,o));if(i&&i!==t)io("users",s,t,i);return i}async function Vu(e,t,n,o){let s=await Di(e,o),r=ro("users",s,`tz:${t}`);if(r)return r==="?"?null:r;let i=null;try{let c=await Oe("users.info",()=>n(e,t,o));if(c?.user?.is_bot===!0||t==="USLACKBOT")return Hu(s,t,null);let a=c?.user?.tz;i=typeof a==="string"&&a?a:null}catch{return null}return Hu(s,t,i)}function Hu(e,t,n){return io("users",e,`tz:${t}`,n??"?"),n}async function Zu(e,t,n,o,s,r){let i=s.progress[o],c=await Xu(e,r),a=await Oe("reactions.get",()=>Wc(e,t,n,r)),l=new Set(a.filter((h)=>h.users.includes(c)).map((h)=>h.name)),u=wn.map((h)=>s.progress[h]).filter((h)=>l.has(h));if(u.length===1&&u[0]===i)return{noop:!0,removed:[],leftover:[]};if(!l.has(i))await Oe("reactions.add",()=>Ns(e,t,n,i,r));let d=[],f=[];for(let h of u){if(h===i)continue;try{await Oe("reactions.remove",()=>Bs(e,t,n,h,r)),d.push(h)}catch{f.push(h)}}return{noop:!1,added:o,removed:d,leftover:f}}async function Qu(e,t,n,o,s,r,i){let c=s.flags[o];if(r)await Oe("reactions.remove",()=>Bs(e,t,n,c,i));else await Oe("reactions.add",()=>Ns(e,t,n,c,i));return c}var wi=1000;async function ed(e,t,n,o={}){let s=o.limit??wi,r=o.cookie,i=await Xu(e,r),c=wn.map((f)=>n.progress[f]),a=[],l=0,u,d=!1;while(l<s){let f=Math.min(200,s-l),h=await Oe("conversations.history",()=>Mn(e,t,f,void 0,u,r)),m=h.messages??[];l+=m.length;for(let p of m){let D=String(p.ts??"");if(!D)continue;let k=new Set((p.reactions??[]).filter((C)=>(C.users??[]).map(String).includes(i)).map((C)=>String(C.name??""))),x=c.filter((C)=>k.has(C));if(x.length<2)continue;a.push({ts:D,text:String(p.text??"").split(`
304
+ `)[0]??"",emoji:x,keep:x[0]})}if(u=h.response_metadata?.next_cursor||void 0,!u||m.length===0)break;if(l>=s){d=!0;break}}if(o.fix)for(let f of a)try{try{await Oe("reactions.add",()=>Ns(e,t,f.ts,f.keep,r))}catch(h){if(!(h instanceof Error)||!/already_reacted/.test(h.message))throw h}for(let h of f.emoji){if(h===f.keep)continue;await Oe("reactions.remove",()=>Bs(e,t,f.ts,h,r))}f.fixed=!0}catch(h){f.fixed=!1,f.error=h instanceof Error?h.message:String(h)}return{scanned:l,findings:a,truncated:d}}var tg=!0,ng;function bi(e){if(tg=e,!e)ng=void 0}function Xe(e){return e.replace(new RegExp(`[${"\\\\¥"}](.)`,"gs"),(t,n)=>{switch(n){case"n":return`
305
+ `;case"t":return"\t";case"\\":case"¥":return n==="¥"?"¥":"\\";default:return t}})}function ki(e){return e.replace(new RegExp(`[${"\\\\¥"}]`,"g"),(t)=>`\\${t}`).replace(/\n/g,"\\n").replace(/\t/g,"\\t")}var bn=(e)=>e&&typeof e==="object"&&!Array.isArray(e)?e:{},Se=(e)=>typeof e==="string"?e:"";function sg(e){return(Array.isArray(e.message_blocks)?e.message_blocks:[]).map((n)=>Se(bn(bn(n).message).text)).filter(Boolean).join(`
306
+ `)}function xi(e){return(Array.isArray(e.attachments)?e.attachments:[]).map(bn).map((n)=>{let o=n.is_share===!0||n.is_msg_unfurl===!0||Array.isArray(n.message_blocks),s=bn(bn((Array.isArray(n.message_blocks)?n.message_blocks:[])[0]));return{shared:o,unfurl:!o&&!!Se(n.original_url),author_id:Se(n.author_id)||Se(bn(s.message).user)||null,author_name:Se(n.author_name)||null,channel_id:Se(n.channel_id)||Se(s.channel)||null,ts:Se(n.ts)||Se(s.ts)||null,title:Se(n.title)||null,text:Se(n.text)||sg(n)||Se(n.pretext)||Se(n.fallback),permalink:Se(n.from_url)||Se(n.title_link)||Se(n.original_url)||null}})}function td(e,t){return e.filter((n)=>!n.unfurl&&(n.text||n.title)).map((n)=>{let o=n.author_name??n.author_id,s=n.shared?`↪ shared message${o?` from @${o}`:""}${n.channel_id?` in <#${n.channel_id}>`:""}${n.ts?` · ${t(n.ts)}`:""}`:`▸ ${n.title??"attachment"}`,r=n.text?n.text.replace(/\n+$/,"").split(`
302
307
  `).map((c)=>`
303
308
  │ ${c}`).join(""):"",i=n.permalink?`
304
309
  ${n.permalink}`:"";return`
305
- ${s}${r}${i}`}).join("")}function Qt(e){return e.toLowerCase().replace(/[-_\s]/g,"")}function St(e){return e&&typeof e==="object"&&!Array.isArray(e)?e:{}}function Jh(e,t){let n=Qt(t),o=St(e.profile);for(let r of[e.name,e.real_name,o.display_name,o.real_name])if(typeof r==="string"&&r&&Qt(r)===n)return!0;let s=typeof o.email==="string"?o.email.toLowerCase():"";return s!==""&&s===t.toLowerCase()}function Kh(e){let t=St(e.profile),n=new Set;for(let o of[t.display_name,e.real_name,e.name,t.real_name])if(typeof o==="string"&&o){let s=Qt(o);if(s.length>=2)n.add(s)}return[...n]}function Hh(e,t){let n=Qt(e),o,s=!1;for(let r of t){let i=typeof r.id==="string"?r.id:"";if(!i)continue;for(let c of Kh(r)){let a=-1;if(n===c)a=e.length;else for(let l of Ku)if(e.length>l.length&&e.endsWith(l)&&Qt(e.slice(0,e.length-l.length))===c){a=e.length-l.length;break}if(a<0)continue;if(!o||c.length>o.formLen)o={userId:i,matchLen:a,formLen:c.length,display:ki(r)},s=!1;else if(c.length===o.formLen&&o.userId!==i)s=!0}}if(!o)return;return s?"ambiguous":{userId:o.userId,matchLen:o.matchLen,display:o.display}}async function en(e,t,n,o){let s=`[${Hu}ー]+`,r=`${s}(?:[._-]+${s})*`,i=new RegExp(`(?<![A-Za-z0-9._@<-])@(${r})`,"gu"),c=new Set;for(let x of t.matchAll(i))c.add(x[1]);if(c.size===0)return{text:t,resolved:[],unresolved:[]};let a=new Map;for(let x of c)a.set(x,{status:"pending"});let l=(x)=>{for(let E of c){if(a.get(E).status!=="pending")continue;if(bi(E)){let F=Hh(E,x);if(F==="ambiguous")a.set(E,{status:"ambiguous"});else if(F)a.set(E,{status:"resolved",userId:F.userId,matchLen:F.matchLen,display:F.display})}else{let F=x.filter((W)=>Jh(W,E)),N=new Set(F.map((W)=>typeof W.id==="string"?W.id:"").filter(Boolean));if(N.size===1){let W=F.find((O)=>typeof O.id==="string");a.set(E,{status:"resolved",userId:W.id,matchLen:E.length,display:ki(W)})}else if(N.size>1)a.set(E,{status:"ambiguous"})}}},u=!1;try{let x=await vs(e,o);l((x.members??[]).map(St)),u=!0}catch{u=!1}let d=[...c].some((x)=>a.get(x).status==="pending"),f=!1,h=!0;if(d&&n){f=!0;try{let x=await xr(e,n,o),E=[];for(let F of x){let N=St(await Cr(e,F,o)),W=St(N.user);if(typeof W.id!=="string")W.id=F;E.push(W)}l(E)}catch{h=!1}}let m=u&&(n?f&&h:!0),p=[],D=[];for(let x of c){let E=a.get(x);if(E.status==="resolved")p.push({surface:`@${x.slice(0,E.matchLen)}`,display:E.display,userId:E.userId});else if(E.status==="ambiguous")D.push({surface:`@${x}`,reason:"ambiguous"});else D.push({surface:`@${x}`,reason:m?"no-match":"unavailable"})}return{text:t.replace(i,(x,E)=>{let F=a.get(E);if(F&&F.status==="resolved")return`<@${F.userId}>${E.slice(F.matchLen)}`;return x}),resolved:p,unresolved:D}}function os(e){let t=[],n=!1;for(let o of e)if(o.reason==="ambiguous")t.push(`${o.surface} matches multiple people — not tagged, sent as plain text (use <@USERID> to tag)`);else if(o.reason==="unavailable"){if(n)continue;t.push("could not fetch the user list (users:read missing or an API/connection error) — @mentions not tagged, sent as plain text"),n=!0}else t.push(`${o.surface} matched no one — not tagged, sent as plain text`);return t}async function Ju(e,t,n,o={}){let s=o.warn??((i)=>process.stderr.write(`${i}
306
- `)),r=await en(e,t,n,o.cookie);for(let i of os(r.unresolved))s(`warn: ${i}`);return r.text}var Ku=["さん","さま","様","君","くん","ちゃん","氏","先生","先輩","殿","老师","老師","兄","姐","哥","姐妹"],Hu="\\p{Script=Han}\\p{Script=Hiragana}\\p{Script=Katakana}A-Za-z0-9";function bi(e){return/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]/u.test(e)}function zh(e){let t=[],n=new RegExp(`([${Hu}]{1,12})(${Ku.join("|")})`,"gu");for(let o of e.matchAll(n))t.push({ref:o[1],honorific:o[2]});for(let o of e.matchAll(/\b(?:dear|hi|hello|hey)\b[ \t]+([A-Z][A-Za-z'’-]{1,20})/gi))t.push({ref:o[1],honorific:""});for(let o of e.matchAll(/(?:^|\n)[ \t]*([A-Z][A-Za-z'’-]{1,20}),/g))t.push({ref:o[1],honorific:""});return t}function qh(e){let t=St(e.profile),n=new Set;for(let o of[e.name,e.real_name,t.display_name,t.real_name]){if(typeof o!=="string"||!o)continue;for(let s of[o,...o.split(/\s+/)]){let r=Qt(s);if(r.length>=2)n.add(r)}}return[...n]}function Gh(e,t){let n=Qt(e);if(n.length<2)return;for(let o of t)if(n===o)return o;if(bi(e)){for(let o of t)if(n.includes(o)||o.includes(n))return o}return}function ki(e){return[St(e.profile).display_name,e.real_name,e.name].filter((o)=>typeof o==="string"&&o!=="")[0]??String(e.id??"?")}async function zu(e,t,n){let o=zh(t);if(o.length===0)return[];let s=new Set;for(let l of t.matchAll(/<@([A-Z0-9]+)(?:\|[^>]*)?>/g))s.add(l[1]);let i=((await vs(e,n)).members??[]).map(St).filter((l)=>l.deleted!==!0&&l.is_bot!==!0&&l.id!=="USLACKBOT").map((l)=>({id:typeof l.id==="string"?l.id:"",forms:qh(l),display:ki(l)})).filter((l)=>l.id!==""),c=[],a=new Set;for(let{ref:l,honorific:u}of o)for(let d of i){let f=Gh(l,d.forms);if(!f)continue;if(s.has(d.id)||a.has(d.id))break;a.add(d.id),c.push({surface:bi(l)?`${f}${u}`:l,display:d.display,userId:d.id});break}return c}async function tn(e,t,n,o){let s=t,r=[],i=s,c=0;while(!0){let a=i.indexOf("<@U",c);if(a===-1)break;let l=i.slice(a+2),u=l.search(/[>|]/),d=u===-1?l:l.slice(0,u);if(d.length>=9)r.push(d);c=a+1}for(let a of r){if(!n.has(a))n.set(a,await Ms(e,a,o));let l=n.get(a)??a;s=s.replaceAll(`<@${a}>`,`@${l}`),s=s.replace(new RegExp(`<@${a}\\|[^>]*>`,"g"),`@${l}`)}return s}function bn(e){return e.replace(/<!date\^(\d+)\^[^|>]*(?:\|([^>]*))?>/g,(t,n,o)=>{let s=Number(n);if(!Number.isFinite(s))return o??"date";let r=new Date(s*1000);if(Number.isNaN(r.getTime()))return o??"date";let i=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],c=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],a=i[r.getUTCDay()]??"",l=c[r.getUTCMonth()]??"";return`${a}, ${l} ${String(r.getUTCDate()).padStart(2,"0")}, ${r.getUTCFullYear()}`})}function qu(e,t=new Date){let n=new Date(e*1000),o=wi(t),s=wi(new Date(t.getTime()-86400000)),r=wi(n);if(r===o)return"Today";if(r===s)return"Yesterday";let i=n.toLocaleDateString("en-US",{weekday:"long"}),c=n.toLocaleDateString("en-US",{month:"short"});return`${i}, ${c} ${String(n.getDate()).padStart(2,"0")}`}function wi(e){return`${e.getFullYear()}-${e.getMonth()}-${e.getDate()}`}function xi(e){let t=new Date(e*1000),n=t.getFullYear(),o=String(t.getMonth()+1).padStart(2,"0"),s=String(t.getDate()).padStart(2,"0"),r=String(t.getHours()).padStart(2,"0"),i=String(t.getMinutes()).padStart(2,"0");return`${n}-${o}-${s} ${r}:${i}`}var Xh=/[A-Za-z0-9_-]{32,}/g;function rs(e){return e.replace(Xh,(t)=>`${t.slice(0,4)}…(${t.length-4} masked)`)}function Ci(e=new Date,t){let n=process.env.SLACK_QUIET_TZ??"Asia/Tokyo",o=!!t&&Yh(t),s=o?t:n,r=Number(process.env.SLACK_QUIET_START??23),i=Number(process.env.SLACK_QUIET_END??8),c,a;try{let h=new Intl.DateTimeFormat("en-GB",{timeZone:s,hour12:!1,weekday:"short",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"});a=h.format(e),c=Number(h.formatToParts(e).find((m)=>m.type==="hour")?.value??"12")}catch{return null}let l=r>i?c>=r||c<i:c>=r&&c<i,u=o?`${s}, recipient`:`${s}, sender — recipient's timezone unknown`,d=`\uD83D\uDD50 ${a} (${u})`;if(!l)return d;return`${d}
307
- ⚠ QUIET HOURS (${r}:00-${i}:00) — this will buzz a phone.${o?"":" Their local time may differ."} Send only for a production incident; otherwise hold it until morning.`}function Yh(e){try{return new Intl.DateTimeFormat("en-GB",{timeZone:e}),!0}catch{return!1}}import{writeSync as Gu}from"node:fs";import{isatty as Xu}from"node:tty";import{format as Yu}from"node:util";var Vh=new Int32Array(new SharedArrayBuffer(4)),Zh=141;function Vu(e,t){let n=Buffer.from(t,"utf8"),o=0;while(o<n.length)try{o+=Gu(e,n,o,n.length-o)}catch(s){let r=s.code;if(r==="EAGAIN"||r==="EWOULDBLOCK"){Atomics.wait(Vh,0,0,2);continue}if(r==="EPIPE")process.exit(Zh);if(e!==2)try{Gu(2,`slack: cannot write output (${r??String(s)}); output is incomplete
308
- `)}catch{}process.exit(1)}}function Zu(){if(!Xu(1))console.log=(...e)=>Vu(1,Yu(...e)+`
309
- `),console.info=console.log;if(!Xu(2))console.error=(...e)=>Vu(2,Yu(...e)+`
310
- `),console.warn=console.error}import{closeSync as Qu,mkdirSync as Qh,openSync as ed,readFileSync as kn,statSync as td,unlinkSync as ro,writeFileSync as nd}from"node:fs";import{homedir as eg}from"node:os";import{join as sd}from"node:path";var as="Pinlog · 最終更新";function Ei(e){let t=new Intl.DateTimeFormat("en-GB",{timeZone:"Asia/Tokyo",hour12:!1,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"}).formatToParts(e),n=(s)=>t.find((r)=>r.type===s)?.value??"??",o=n("hour")==="24"?"00":n("hour");return`${n("year")}-${n("month")}-${n("day")} ${o}:${n("minute")} JST`}function tg(e){return`_${as} ${Ei(e)} · 更新はスレッドに_`}var Si=new RegExp(`(^|\\n+)_?${as} \\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2} JST · 更新はスレッドに_?[ \\t]*\\n*$`);function xn(e){return Si.test(e)}function cs(e){return e.replace(Si,"")}function _i(e,t){return`${cs(e).trimEnd()}
310
+ ${s}${r}${i}`}).join("")}function en(e){return e.toLowerCase().replace(/[-_\s]/g,"")}function _t(e){return e&&typeof e==="object"&&!Array.isArray(e)?e:{}}function og(e,t){let n=en(t),o=_t(e.profile);for(let r of[e.name,e.real_name,o.display_name,o.real_name])if(typeof r==="string"&&r&&en(r)===n)return!0;let s=typeof o.email==="string"?o.email.toLowerCase():"";return s!==""&&s===t.toLowerCase()}function rg(e){let t=_t(e.profile),n=new Set;for(let o of[t.display_name,e.real_name,e.name,t.real_name])if(typeof o==="string"&&o){let s=en(o);if(s.length>=2)n.add(s)}return[...n]}function ig(e,t){let n=en(e),o,s=!1;for(let r of t){let i=typeof r.id==="string"?r.id:"";if(!i)continue;for(let c of rg(r)){let a=-1;if(n===c)a=e.length;else for(let l of sd)if(e.length>l.length&&e.endsWith(l)&&en(e.slice(0,e.length-l.length))===c){a=e.length-l.length;break}if(a<0)continue;if(!o||c.length>o.formLen)o={userId:i,matchLen:a,formLen:c.length,display:Si(r)},s=!1;else if(c.length===o.formLen&&o.userId!==i)s=!0}}if(!o)return;return s?"ambiguous":{userId:o.userId,matchLen:o.matchLen,display:o.display}}async function tn(e,t,n,o){let s=`[${od}ー]+`,r=`${s}(?:[._-]+${s})*`,i=new RegExp(`(?<![A-Za-z0-9._@<-])@(${r})`,"gu"),c=new Set;for(let x of t.matchAll(i))c.add(x[1]);if(c.size===0)return{text:t,resolved:[],unresolved:[]};let a=new Map;for(let x of c)a.set(x,{status:"pending"});let l=(x)=>{for(let C of c){if(a.get(C).status!=="pending")continue;if(Ci(C)){let F=ig(C,x);if(F==="ambiguous")a.set(C,{status:"ambiguous"});else if(F)a.set(C,{status:"resolved",userId:F.userId,matchLen:F.matchLen,display:F.display})}else{let F=x.filter((W)=>og(W,C)),N=new Set(F.map((W)=>typeof W.id==="string"?W.id:"").filter(Boolean));if(N.size===1){let W=F.find((O)=>typeof O.id==="string");a.set(C,{status:"resolved",userId:W.id,matchLen:C.length,display:Si(W)})}else if(N.size>1)a.set(C,{status:"ambiguous"})}}},u=!1;try{let x=await js(e,o);l((x.members??[]).map(_t)),u=!0}catch{u=!1}let d=[...c].some((x)=>a.get(x).status==="pending"),f=!1,h=!0;if(d&&n){f=!0;try{let x=await _r(e,n,o),C=[];for(let F of x){let N=_t(await Fr(e,F,o)),W=_t(N.user);if(typeof W.id!=="string")W.id=F;C.push(W)}l(C)}catch{h=!1}}let m=u&&(n?f&&h:!0),p=[],D=[];for(let x of c){let C=a.get(x);if(C.status==="resolved")p.push({surface:`@${x.slice(0,C.matchLen)}`,display:C.display,userId:C.userId});else if(C.status==="ambiguous")D.push({surface:`@${x}`,reason:"ambiguous"});else D.push({surface:`@${x}`,reason:m?"no-match":"unavailable"})}return{text:t.replace(i,(x,C)=>{let F=a.get(C);if(F&&F.status==="resolved")return`<@${F.userId}>${C.slice(F.matchLen)}`;return x}),resolved:p,unresolved:D}}function rs(e){let t=[],n=!1;for(let o of e)if(o.reason==="ambiguous")t.push(`${o.surface} matches multiple people — not tagged, sent as plain text (use <@USERID> to tag)`);else if(o.reason==="unavailable"){if(n)continue;t.push("could not fetch the user list (users:read missing or an API/connection error) — @mentions not tagged, sent as plain text"),n=!0}else t.push(`${o.surface} matched no one — not tagged, sent as plain text`);return t}async function nd(e,t,n,o={}){let s=o.warn??((i)=>process.stderr.write(`${i}
311
+ `)),r=await tn(e,t,n,o.cookie);for(let i of rs(r.unresolved))s(`warn: ${i}`);return r.text}var sd=["さん","さま","様","君","くん","ちゃん","氏","先生","先輩","殿","老师","老師","兄","姐","哥","姐妹"],od="\\p{Script=Han}\\p{Script=Hiragana}\\p{Script=Katakana}A-Za-z0-9";function Ci(e){return/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]/u.test(e)}function ag(e){let t=[],n=new RegExp(`([${od}]{1,12})(${sd.join("|")})`,"gu");for(let o of e.matchAll(n))t.push({ref:o[1],honorific:o[2]});for(let o of e.matchAll(/\b(?:dear|hi|hello|hey)\b[ \t]+([A-Z][A-Za-z'’-]{1,20})/gi))t.push({ref:o[1],honorific:""});for(let o of e.matchAll(/(?:^|\n)[ \t]*([A-Z][A-Za-z'’-]{1,20}),/g))t.push({ref:o[1],honorific:""});return t}function cg(e){let t=_t(e.profile),n=new Set;for(let o of[e.name,e.real_name,t.display_name,t.real_name]){if(typeof o!=="string"||!o)continue;for(let s of[o,...o.split(/\s+/)]){let r=en(s);if(r.length>=2)n.add(r)}}return[...n]}function lg(e,t){let n=en(e);if(n.length<2)return;for(let o of t)if(n===o)return o;if(Ci(e)){for(let o of t)if(n.includes(o)||o.includes(n))return o}return}function Si(e){return[_t(e.profile).display_name,e.real_name,e.name].filter((o)=>typeof o==="string"&&o!=="")[0]??String(e.id??"?")}async function rd(e,t,n){let o=ag(t);if(o.length===0)return[];let s=new Set;for(let l of t.matchAll(/<@([A-Z0-9]+)(?:\|[^>]*)?>/g))s.add(l[1]);let i=((await js(e,n)).members??[]).map(_t).filter((l)=>l.deleted!==!0&&l.is_bot!==!0&&l.id!=="USLACKBOT").map((l)=>({id:typeof l.id==="string"?l.id:"",forms:cg(l),display:Si(l)})).filter((l)=>l.id!==""),c=[],a=new Set;for(let{ref:l,honorific:u}of o)for(let d of i){let f=lg(l,d.forms);if(!f)continue;if(s.has(d.id)||a.has(d.id))break;a.add(d.id),c.push({surface:Ci(l)?`${f}${u}`:l,display:d.display,userId:d.id});break}return c}async function nn(e,t,n,o){let s=t,r=[],i=s,c=0;while(!0){let a=i.indexOf("<@U",c);if(a===-1)break;let l=i.slice(a+2),u=l.search(/[>|]/),d=u===-1?l:l.slice(0,u);if(d.length>=9)r.push(d);c=a+1}for(let a of r){if(!n.has(a))n.set(a,await Ms(e,a,o));let l=n.get(a)??a;s=s.replaceAll(`<@${a}>`,`@${l}`),s=s.replace(new RegExp(`<@${a}\\|[^>]*>`,"g"),`@${l}`)}return s}function kn(e){return e.replace(/<!date\^(\d+)\^[^|>]*(?:\|([^>]*))?>/g,(t,n,o)=>{let s=Number(n);if(!Number.isFinite(s))return o??"date";let r=new Date(s*1000);if(Number.isNaN(r.getTime()))return o??"date";let i=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],c=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],a=i[r.getUTCDay()]??"",l=c[r.getUTCMonth()]??"";return`${a}, ${l} ${String(r.getUTCDate()).padStart(2,"0")}, ${r.getUTCFullYear()}`})}function id(e,t=new Date){let n=new Date(e*1000),o=Ei(t),s=Ei(new Date(t.getTime()-86400000)),r=Ei(n);if(r===o)return"Today";if(r===s)return"Yesterday";let i=n.toLocaleDateString("en-US",{weekday:"long"}),c=n.toLocaleDateString("en-US",{month:"short"});return`${i}, ${c} ${String(n.getDate()).padStart(2,"0")}`}function Ei(e){return`${e.getFullYear()}-${e.getMonth()}-${e.getDate()}`}function co(e){let t=new Date(e*1000),n=t.getFullYear(),o=String(t.getMonth()+1).padStart(2,"0"),s=String(t.getDate()).padStart(2,"0"),r=String(t.getHours()).padStart(2,"0"),i=String(t.getMinutes()).padStart(2,"0");return`${n}-${o}-${s} ${r}:${i}`}var ug=/[A-Za-z0-9_-]{32,}/g;function is(e){return e.replace(ug,(t)=>`${t.slice(0,4)}…(${t.length-4} masked)`)}function _i(e=new Date,t){let n=process.env.SLACK_QUIET_TZ??"Asia/Tokyo",o=!!t&&dg(t),s=o?t:n,r=Number(process.env.SLACK_QUIET_START??23),i=Number(process.env.SLACK_QUIET_END??8),c,a;try{let h=new Intl.DateTimeFormat("en-GB",{timeZone:s,hour12:!1,weekday:"short",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"});a=h.format(e),c=Number(h.formatToParts(e).find((m)=>m.type==="hour")?.value??"12")}catch{return null}let l=r>i?c>=r||c<i:c>=r&&c<i,u=o?`${s}, recipient`:`${s}, sender — recipient's timezone unknown`,d=`\uD83D\uDD50 ${a} (${u})`;if(!l)return d;return`${d}
312
+ ⚠ QUIET HOURS (${r}:00-${i}:00) — this will buzz a phone.${o?"":" Their local time may differ."} Send only for a production incident; otherwise hold it until morning.`}function dg(e){try{return new Intl.DateTimeFormat("en-GB",{timeZone:e}),!0}catch{return!1}}import{writeSync as ad}from"node:fs";import{isatty as cd}from"node:tty";import{format as ld}from"node:util";var fg=new Int32Array(new SharedArrayBuffer(4)),pg=141;function ud(e,t){let n=Buffer.from(t,"utf8"),o=0;while(o<n.length)try{o+=ad(e,n,o,n.length-o)}catch(s){let r=s.code;if(r==="EAGAIN"||r==="EWOULDBLOCK"){Atomics.wait(fg,0,0,2);continue}if(r==="EPIPE")process.exit(pg);if(e!==2)try{ad(2,`slack: cannot write output (${r??String(s)}); output is incomplete
313
+ `)}catch{}process.exit(1)}}function dd(){if(!cd(1))console.log=(...e)=>ud(1,ld(...e)+`
314
+ `),console.info=console.log;if(!cd(2))console.error=(...e)=>ud(2,ld(...e)+`
315
+ `),console.warn=console.error}import{closeSync as fd,mkdirSync as hg,openSync as pd,readFileSync as xn,statSync as hd,unlinkSync as lo,writeFileSync as gd}from"node:fs";import{homedir as gg}from"node:os";import{join as md}from"node:path";var cs="Pinlog · 最終更新";function Fi(e){let t=new Intl.DateTimeFormat("en-GB",{timeZone:"Asia/Tokyo",hour12:!1,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"}).formatToParts(e),n=(s)=>t.find((r)=>r.type===s)?.value??"??",o=n("hour")==="24"?"00":n("hour");return`${n("year")}-${n("month")}-${n("day")} ${o}:${n("minute")} JST`}function mg(e){return`_${cs} ${Fi(e)} · 更新はスレッドに_`}var $i=new RegExp(`(^|\\n+)_?${cs} \\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2} JST · 更新はスレッドに_?[ \\t]*\\n*$`);function En(e){return $i.test(e)}function ls(e){return e.replace($i,"")}function Ai(e,t){return`${ls(e).trimEnd()}
311
316
 
312
- ${tg(t)}`}function Fi(e){let n=e.match(Si)?.[0]?.match(/(\d{4}-\d{2}-\d{2} \d{2}:\d{2} JST)/);return n?n[1]:null}class is extends Error{holder;constructor(e){super(`locked by ${e}`);this.holder=e;this.name="LockBusyError"}}function ng(){return sd(process.env.HOME||eg(),".config","slack-cli","locks")}function od(e){let t=e.match(/^pid=(\d+)/);if(!t)return!0;try{return process.kill(Number(t[1]),0),!0}catch(n){return n.code==="EPERM"}}function sg(e,t){let n=`${e}.break`,o=`pid=${process.pid} nonce=${Math.random().toString(36).slice(2)}${Date.now()}
313
- `,s;try{s=ed(n,"wx"),nd(s,o)}catch(r){if(r.code!=="EEXIST")throw r;try{let i=kn(n,"utf8");if((/^pid=\d+/.test(i)?!od(i):Date.now()-td(n).mtimeMs>1e4)&&kn(n,"utf8")===i)ro(n)}catch{}return}try{if(kn(e,"utf8")===t)ro(e)}catch{}finally{Qu(s);try{if(kn(n,"utf8")===o)ro(n)}catch{}}}function rd(e,t={}){let n=t.dir??ng(),o=t.staleMs??120000;Qh(n,{recursive:!0});let s=sd(n,`${e.replace(/[^A-Za-z0-9._-]/g,"_")}.lock`),r=`pid=${process.pid} since=${new Date().toISOString()} nonce=${Math.random().toString(36).slice(2)}${Date.now()}
314
- `;for(let i=0;i<3;i++)try{let c=ed(s,"wx");nd(c,r),Qu(c);let a=!0,l=()=>{if(!a)return;a=!1;try{if(kn(s,"utf8")===r)ro(s)}catch{}};return process.once("exit",l),l}catch(c){if(c.code!=="EEXIST")throw c;let a,l;try{a=kn(s,"utf8"),l=Date.now()-td(s).mtimeMs}catch{continue}if(/^pid=\d+/.test(a)?!od(a):l>o){sg(s,a);continue}throw new is(a.trim().replace(/ nonce=\S+/,"")||"another process")}throw new is("another process")}function Xe(e,t){return`${e}:${t}`}function io(e){let t=e.match(/^([CDG][A-Z0-9]{8,}):(\d{10}\.\d{6})$/);return t?{channel:t[1],ts:t[2]}:null}function ls(e){if(!yd(e))return;let t=wd(e,"utf8");for(let n of t.split(`
315
- `)){let o=n.trim();if(!o||o.startsWith("#"))continue;let s=o.indexOf("=");if(s===-1)continue;let r=o.slice(0,s).trim(),i=o.slice(s+1).trim();if(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))i=i.slice(1,-1);if(!(r in process.env))process.env[r]=i}}function cg(e){rg(e,{recursive:!0});let t=_t(e,".gitignore");if(!yd(t))bd(t,`*
316
- `)}function lg(){ls(_t(id(),".slack-cli",".env.local")),ls(_t(id(),".config/slack-cli",".env")),ls(_t(process.cwd(),".slack-cli",".env.local")),ls(_t(process.cwd(),".env.local")),ls(_t(process.cwd(),".env"))}function ug(e){return og("sha256").update(e).digest("hex")}function I(e){return e&&typeof e==="object"&&!Array.isArray(e)?e:{}}function X(e){return Array.isArray(e)?e:[]}function uo(e){return Number(e.ts??0)}async function kd(e,t,n){let o=t.user;if(typeof o==="string"){if(!n.has(o))n.set(o,await Ie(e,o));return n.get(o)??o}return typeof t.username==="string"?t.username:"bot"}function $i(e){let t=new Date(e*1000),n=t.getUTCFullYear(),o=String(t.getUTCMonth()+1).padStart(2,"0"),s=String(t.getUTCDate()).padStart(2,"0"),r=String(t.getUTCHours()).padStart(2,"0"),i=String(t.getUTCMinutes()).padStart(2,"0"),c=String(t.getUTCSeconds()).padStart(2,"0");return`${n}-${o}-${s} ${r}:${i}:${c}`}function fo(e){let[t,n="000000"]=e.split("."),o=Number(t),s=new Date(o*1000),r=s.getUTCFullYear(),i=String(s.getUTCMonth()+1).padStart(2,"0"),c=String(s.getUTCDate()).padStart(2,"0"),a=String(s.getUTCHours()).padStart(2,"0"),l=String(s.getUTCMinutes()).padStart(2,"0"),u=String(s.getUTCSeconds()).padStart(2,"0"),d=n.padEnd(6,"0").slice(0,6);return`${r}-${i}-${c}T${a}:${l}:${u}.${d}`}function Ti(e){let t=e.match(/^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})\.(\d{6})$/);if(!t)throw Error(`Invalid message timestamp "${e}" \u2014 expected 2026-05-11T06:01:04.000100`);let n=Date.parse(t[1]+"Z");if(isNaN(n))throw Error(`Cannot parse date in "${e}"`);return`${Math.floor(n/1000)}.${t[2]}`}function dg(e){return/^\d{4}-\d{2}-\d{2}T/.test(e)?Ti(e):e}async function Do(e,t,n,o,s){let r=typeof t.ts==="string"?t.ts:`${uo(t)}.000000`,i=fo(r),c="?";if(typeof t.user==="string"){let E=t.user,F="@"+E;if(!n.has(F)){let N=await Mu(e,E,async(W,O,v)=>(await es(W,O,v))[1],s);n.set(F,N)}c=n.get(F)??E}else if(typeof t.username==="string")c=t.username;let a=typeof t.text==="string"?t.text:"",u=bn(await tn(e,a,n,s)).split(`
317
+ ${mg(t)}`}function Ti(e){let n=e.match($i)?.[0]?.match(/(\d{4}-\d{2}-\d{2} \d{2}:\d{2} JST)/);return n?n[1]:null}class as extends Error{holder;constructor(e){super(`locked by ${e}`);this.holder=e;this.name="LockBusyError"}}function Dg(){return md(process.env.HOME||gg(),".config","slack-cli","locks")}function Dd(e){let t=e.match(/^pid=(\d+)/);if(!t)return!0;try{return process.kill(Number(t[1]),0),!0}catch(n){return n.code==="EPERM"}}function yg(e,t){let n=`${e}.break`,o=`pid=${process.pid} nonce=${Math.random().toString(36).slice(2)}${Date.now()}
318
+ `,s;try{s=pd(n,"wx"),gd(s,o)}catch(r){if(r.code!=="EEXIST")throw r;try{let i=xn(n,"utf8");if((/^pid=\d+/.test(i)?!Dd(i):Date.now()-hd(n).mtimeMs>1e4)&&xn(n,"utf8")===i)lo(n)}catch{}return}try{if(xn(e,"utf8")===t)lo(e)}catch{}finally{fd(s);try{if(xn(n,"utf8")===o)lo(n)}catch{}}}function yd(e,t={}){let n=t.dir??Dg(),o=t.staleMs??120000;hg(n,{recursive:!0});let s=md(n,`${e.replace(/[^A-Za-z0-9._-]/g,"_")}.lock`),r=`pid=${process.pid} since=${new Date().toISOString()} nonce=${Math.random().toString(36).slice(2)}${Date.now()}
319
+ `;for(let i=0;i<3;i++)try{let c=pd(s,"wx");gd(c,r),fd(c);let a=!0,l=()=>{if(!a)return;a=!1;try{if(xn(s,"utf8")===r)lo(s)}catch{}};return process.once("exit",l),l}catch(c){if(c.code!=="EEXIST")throw c;let a,l;try{a=xn(s,"utf8"),l=Date.now()-hd(s).mtimeMs}catch{continue}if(/^pid=\d+/.test(a)?!Dd(a):l>o){yg(s,a);continue}throw new as(a.trim().replace(/ nonce=\S+/,"")||"another process")}throw new as("another process")}function Ye(e,t){return`${e}:${t}`}function uo(e){let t=e.match(/^([CDG][A-Z0-9]{8,}):(\d{10}\.\d{6})$/);return t?{channel:t[1],ts:t[2]}:null}function us(e){if(!Id(e))return;let t=Od(e,"utf8");for(let n of t.split(`
320
+ `)){let o=n.trim();if(!o||o.startsWith("#"))continue;let s=o.indexOf("=");if(s===-1)continue;let r=o.slice(0,s).trim(),i=o.slice(s+1).trim();if(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))i=i.slice(1,-1);if(!(r in process.env))process.env[r]=i}}function Eg(e){bg(e,{recursive:!0});let t=Ft(e,".gitignore");if(!Id(t))Pd(t,`*
321
+ `)}function Cg(){us(Ft(wd(),".slack-cli",".env.local")),us(Ft(wd(),".config/slack-cli",".env")),us(Ft(process.cwd(),".slack-cli",".env.local")),us(Ft(process.cwd(),".env.local")),us(Ft(process.cwd(),".env"))}function Sg(e){return wg("sha256").update(e).digest("hex")}function T(e){return e&&typeof e==="object"&&!Array.isArray(e)?e:{}}function X(e){return Array.isArray(e)?e:[]}function go(e){return Number(e.ts??0)}async function Rd(e,t,n){let o=t.user;if(typeof o==="string"){if(!n.has(o))n.set(o,await Ae(e,o));return n.get(o)??o}return typeof t.username==="string"?t.username:"bot"}function Ii(e){let t=new Date(e*1000),n=t.getUTCFullYear(),o=String(t.getUTCMonth()+1).padStart(2,"0"),s=String(t.getUTCDate()).padStart(2,"0"),r=String(t.getUTCHours()).padStart(2,"0"),i=String(t.getUTCMinutes()).padStart(2,"0"),c=String(t.getUTCSeconds()).padStart(2,"0");return`${n}-${o}-${s} ${r}:${i}:${c}`}function mo(e){let[t,n="000000"]=e.split("."),o=Number(t),s=new Date(o*1000),r=s.getUTCFullYear(),i=String(s.getUTCMonth()+1).padStart(2,"0"),c=String(s.getUTCDate()).padStart(2,"0"),a=String(s.getUTCHours()).padStart(2,"0"),l=String(s.getUTCMinutes()).padStart(2,"0"),u=String(s.getUTCSeconds()).padStart(2,"0"),d=n.padEnd(6,"0").slice(0,6);return`${r}-${i}-${c}T${a}:${l}:${u}.${d}`}function Pi(e){let t=e.match(/^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})\.(\d{6})$/);if(!t)throw Error(`Invalid message timestamp "${e}" \u2014 expected 2026-05-11T06:01:04.000100`);let n=Date.parse(t[1]+"Z");if(isNaN(n))throw Error(`Cannot parse date in "${e}"`);return`${Math.floor(n/1000)}.${t[2]}`}function _g(e){return/^\d{4}-\d{2}-\d{2}T/.test(e)?Pi(e):e}async function ko(e,t,n,o,s){let r=typeof t.ts==="string"?t.ts:`${go(t)}.000000`,i=mo(r),c="?";if(typeof t.user==="string"){let C=t.user,F="@"+C;if(!n.has(F)){let N=await Yu(e,C,async(W,O,L)=>(await es(W,O,L))[1],s);n.set(F,N)}c=n.get(F)??C}else if(typeof t.username==="string")c=t.username;let a=typeof t.text==="string"?t.text:"",u=kn(await nn(e,a,n,s)).split(`
317
322
  `),d=u[0]+(u.length>1?`
318
- `+u.slice(1).map((E)=>` ${E}`).join(`
319
- `):""),f=o?`${o} @${c}`:`@${c}`,h=X(t.reactions).map(I).map((E)=>{let F=typeof E.name==="string"?E.name:"",N=Number(E.count??X(E.users).length??0);return F?`:${F}:\xD7${N}`:""}).filter(Boolean).join(" "),m=X(t.files).map(I).map((E)=>{let F=typeof E.name==="string"?E.name:typeof E.title==="string"?E.title:"(file)",N=typeof E.size==="number"?` (${yo(E.size)})`:"",W=typeof E.id==="string"?` [${E.id}]`:"";return`
320
- \uD83D\uDCCE ${F}${N}${W}`}).join(""),p=Number(t.reply_count??0),D=p>0?` [+${p} ${p===1?"reply":"replies"}]`:"",k=await Promise.all(yi(t).map(async(E)=>({...E,text:E.text?bn(await tn(e,E.text,n,s)):""}))),x=(h?`
321
- ${h}`:"")+m+Uu(k,fo);return`${i} ${f}: ${d}${D}${x}`}function yo(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function fg(e){return X(e.files).map(I).map((t)=>({id:t.id??null,name:t.name??t.title??null,mimetype:t.mimetype??null,size:t.size??null,url_private_download:t.url_private_download??t.url_private??null,permalink:t.permalink??null}))}function xd(e){let t=fg(e),n=yi(e);return{ts:e.ts??null,user:e.user??null,username:e.username??null,bot_id:e.bot_id??null,thread_ts:e.thread_ts??null,text:typeof e.text==="string"?e.text:"",...Array.isArray(e.reactions)&&e.reactions.length?{reactions:X(e.reactions).map(I).map((o)=>({name:o.name??null,count:o.count??null,users:Array.isArray(o.users)?o.users:[]}))}:{},...e.reply_count!==void 0?{reply_count:e.reply_count}:{},...e.reply_users_count!==void 0?{reply_users_count:e.reply_users_count}:{},...e.latest_reply!==void 0?{latest_reply:e.latest_reply}:{},...t.length>0?{files:t}:{},...n.length>0?{attachments:n}:{}}}async function pg(e,t,n,o,s){let r=[];for(let i of n){let c=i;if(Number(i.reply_count??0)>0&&typeof i.ts==="string"){let a=await qe(e,t,i.ts,200,s),l=X(a.messages).map(I);c=l[l.length-1]??i}if(c.user!==o)r.push(i)}return r}async function hg(e,t,n,o="text",s=!1,r){let i=Zt(t),c=await he(e,t,r),a=new Map,u=await(async()=>{if(i?.threadTs){let f=await qe(e,c,i.threadTs,n,r);return X(f.messages).map(I)}let d=await st(e,c,n,void 0,void 0,r);return X(d.messages).map(I).reverse()})();if(s){let{userId:d}=await ii(e,r);u=await pg(e,c,u,d,r)}if(o==="jsonl"){for(let d of u)console.log(JSON.stringify(xd(d)));return}for(let d of u)console.log(await Do(e,d,a,void 0,r))}async function gg(e,t,n,o,s="text",r){let i=await he(e,t,r),c=await qe(e,i,dg(n),o,r),a=X(c.messages).map(I);if(s==="jsonl"){for(let u of a)console.log(JSON.stringify(xd(u)));return}let l=new Map;for(let u of a)console.log(await Do(e,u,l,void 0,r))}async function mg(e){let t=await Qn(e),n=X(t.channels).map(I).filter((s)=>s.is_member===!0).sort((s,r)=>Number(r.updated??0)-Number(s.updated??0)).slice(0,10),o=new Map;for(let s of n){let r=String(s.id??""),i=typeof s.name==="string"?s.name:typeof s.user==="string"?s.user:r,c=await st(e,r,5),a=X(c.messages).map(I).filter((l)=>l.subtype===void 0||l.subtype===null).filter((l)=>{let u=typeof l.text==="string"?l.text:"";return u.length>0&&!u.startsWith("<@")}).slice(0,3).reverse();if(a.length===0)continue;console.log(`-- #${i} --------------------------------`);for(let l of a){let u=await kd(e,l,o),d=(typeof l.text==="string"?l.text:"").split(`
322
- `)[0]??"",f=await tn(e,d,o);console.log(` ${u}: ${f}`)}}}async function Dg(e,t){let n=await au(e,"to:me"),o=X(Xn(n,["messages","matches"])).map(I).slice(0,t),s=new Map,r=[];for(let i of o){let c=qu(uo(i)),a=r[r.length-1];if(a?.label===c)a.msgs.push(i);else r.push({label:c,msgs:[i]})}for(let i=0;i<r.length;i++){let{label:c,msgs:a}=r[i];if(i>0)console.log("");console.log(` ${c}`),console.log(" ----------------------------");for(let l of[...a].reverse()){let u=I(l.channel),d=u.is_im===!0,f=typeof u.name==="string"?u.name:"dm",h;if(d&&f.startsWith("U")){let m="@"+f;if(!s.has(m)){let[,p]=await es(e,f);s.set(m,p)}h=`@${s.get(m)??f}`}else if(d)h=`@${f}`;else h=`#${f}`;console.log(await Do(e,l,s,h))}}}async function yg(e,t,n,o,s="text",r){let i=await Qn(e,r),c=X(i.channels).map(I).filter((a)=>o||a.is_member===!0).filter((a)=>{if(!n)return!0;return(typeof a.name==="string"?a.name:"").toLowerCase().includes(n.toLowerCase())}).sort((a,l)=>Number(l.updated??0)-Number(a.updated??0)).slice(0,t);if(s==="jsonl"){for(let a of c)console.log(JSON.stringify(a));return}for(let a of c){let l=String(a.id??""),u=typeof a.name==="string"?a.name:typeof a.user==="string"?a.user:l,d=a.is_im===!0,f=a.is_mpim===!0,h=d||f?"@":"#",m=a.is_member===!0?"":" (not joined)",p=typeof I(a.purpose).value==="string"?String(I(a.purpose).value):"",D=p?` ${p.split(`
323
- `)[0]?.slice(0,60)}`:"";console.log(`${h}${u} ${l}${m}${D}`)}}function wg(e){let t=(s)=>s.startsWith("xoxp-")||s.startsWith("xoxc-"),n=ir(),o=n.find((s)=>s.profile.token===e);if(!o)return;return n.find((s)=>t(s.profile.token)&&s.profile.teamId===o.profile.teamId)}async function Cd(e,t,n,o,s){let r=e,i=s,c;try{c=await ci(r,t,n,i)}catch(u){let d=u instanceof Error?u.message:String(u);if(e.startsWith("xoxb-")&&d.includes("not_allowed_token_type")){let f=wg(e);if(f)console.error(`Note: search.messages needs a user token \u2014 the active profile is a bot token (xoxb-); falling back to profile "${f.name}".`),r=f.profile.token,i=f.profile.cookie,c=await ci(r,t,n,i);else console.error(`Error: search requires a user token (xoxp-/xoxc-) \u2014 the active profile is a bot token (xoxb-), which Slack rejects for search.messages.
323
+ `+u.slice(1).map((C)=>` ${C}`).join(`
324
+ `):""),f=o?`${o} @${c}`:`@${c}`,h=X(t.reactions).map(T).map((C)=>{let F=typeof C.name==="string"?C.name:"",N=Number(C.count??X(C.users).length??0);return F?`:${F}:\xD7${N}`:""}).filter(Boolean).join(" "),m=X(t.files).map(T).map((C)=>{let F=typeof C.name==="string"?C.name:typeof C.title==="string"?C.title:"(file)",N=typeof C.size==="number"?` (${xo(C.size)})`:"",W=typeof C.id==="string"?` [${C.id}]`:"";return`
325
+ \uD83D\uDCCE ${F}${N}${W}`}).join(""),p=Number(t.reply_count??0),D=p>0?` [+${p} ${p===1?"reply":"replies"}]`:"",k=await Promise.all(xi(t).map(async(C)=>({...C,text:C.text?kn(await nn(e,C.text,n,s)):""}))),x=(h?`
326
+ ${h}`:"")+m+td(k,mo);return`${i} ${f}: ${d}${D}${x}`}function xo(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function Fg(e){return X(e.files).map(T).map((t)=>({id:t.id??null,name:t.name??t.title??null,mimetype:t.mimetype??null,size:t.size??null,url_private_download:t.url_private_download??t.url_private??null,permalink:t.permalink??null}))}function Nd(e){let t=Fg(e),n=xi(e);return{ts:e.ts??null,user:e.user??null,username:e.username??null,bot_id:e.bot_id??null,thread_ts:e.thread_ts??null,text:typeof e.text==="string"?e.text:"",...Array.isArray(e.reactions)&&e.reactions.length?{reactions:X(e.reactions).map(T).map((o)=>({name:o.name??null,count:o.count??null,users:Array.isArray(o.users)?o.users:[]}))}:{},...e.reply_count!==void 0?{reply_count:e.reply_count}:{},...e.reply_users_count!==void 0?{reply_users_count:e.reply_users_count}:{},...e.latest_reply!==void 0?{latest_reply:e.latest_reply}:{},...t.length>0?{files:t}:{},...n.length>0?{attachments:n}:{}}}async function $g(e,t,n,o,s){let r=[];for(let i of n){let c=i;if(Number(i.reply_count??0)>0&&typeof i.ts==="string"){let a=await Me(e,t,i.ts,200,s),l=X(a.messages).map(T);c=l[l.length-1]??i}if(c.user!==o)r.push(i)}return r}async function Ag(e,t,n,o="text",s=!1,r){let i=Zt(t),c=await ue(e,t,r),a=new Map,u=await(async()=>{if(i?.threadTs){let f=await Me(e,c,i.threadTs,n,r);return X(f.messages).map(T)}let d=await ot(e,c,n,void 0,void 0,r);return X(d.messages).map(T).reverse()})();if(s){let{userId:d}=await ui(e,r);u=await $g(e,c,u,d,r)}if(o==="jsonl"){for(let d of u)console.log(JSON.stringify(Nd(d)));return}for(let d of u)console.log(await ko(e,d,a,void 0,r))}async function Tg(e,t,n,o,s="text",r){let i=await ue(e,t,r),c=await Me(e,i,_g(n),o,r),a=X(c.messages).map(T);if(s==="jsonl"){for(let u of a)console.log(JSON.stringify(Nd(u)));return}let l=new Map;for(let u of a)console.log(await ko(e,u,l,void 0,r))}async function Ig(e){let t=await Qn(e),n=X(t.channels).map(T).filter((s)=>s.is_member===!0).sort((s,r)=>Number(r.updated??0)-Number(s.updated??0)).slice(0,10),o=new Map;for(let s of n){let r=String(s.id??""),i=typeof s.name==="string"?s.name:typeof s.user==="string"?s.user:r,c=await ot(e,r,5),a=X(c.messages).map(T).filter((l)=>l.subtype===void 0||l.subtype===null).filter((l)=>{let u=typeof l.text==="string"?l.text:"";return u.length>0&&!u.startsWith("<@")}).slice(0,3).reverse();if(a.length===0)continue;console.log(`-- #${i} --------------------------------`);for(let l of a){let u=await Rd(e,l,o),d=(typeof l.text==="string"?l.text:"").split(`
327
+ `)[0]??"",f=await nn(e,d,o);console.log(` ${u}: ${f}`)}}}async function Og(e,t){let n=await fu(e,"to:me"),o=X(Yn(n,["messages","matches"])).map(T).slice(0,t),s=new Map,r=[];for(let i of o){let c=id(go(i)),a=r[r.length-1];if(a?.label===c)a.msgs.push(i);else r.push({label:c,msgs:[i]})}for(let i=0;i<r.length;i++){let{label:c,msgs:a}=r[i];if(i>0)console.log("");console.log(` ${c}`),console.log(" ----------------------------");for(let l of[...a].reverse()){let u=T(l.channel),d=u.is_im===!0,f=typeof u.name==="string"?u.name:"dm",h;if(d&&f.startsWith("U")){let m="@"+f;if(!s.has(m)){let[,p]=await es(e,f);s.set(m,p)}h=`@${s.get(m)??f}`}else if(d)h=`@${f}`;else h=`#${f}`;console.log(await ko(e,l,s,h))}}}async function Pg(e,t,n,o,s="text",r){let i=await Qn(e,r),c=X(i.channels).map(T).filter((a)=>o||a.is_member===!0).filter((a)=>{if(!n)return!0;return(typeof a.name==="string"?a.name:"").toLowerCase().includes(n.toLowerCase())}).sort((a,l)=>Number(l.updated??0)-Number(a.updated??0)).slice(0,t);if(s==="jsonl"){for(let a of c)console.log(JSON.stringify(a));return}for(let a of c){let l=String(a.id??""),u=typeof a.name==="string"?a.name:typeof a.user==="string"?a.user:l,d=a.is_im===!0,f=a.is_mpim===!0,h=d||f?"@":"#",m=a.is_member===!0?"":" (not joined)",p=typeof T(a.purpose).value==="string"?String(T(a.purpose).value):"",D=p?` ${p.split(`
328
+ `)[0]?.slice(0,60)}`:"";console.log(`${h}${u} ${l}${m}${D}`)}}function Rg(e){let t=(s)=>s.startsWith("xoxp-")||s.startsWith("xoxc-"),n=ur(),o=n.find((s)=>s.profile.token===e);if(!o)return;return n.find((s)=>t(s.profile.token)&&s.profile.teamId===o.profile.teamId)}async function Bd(e,t,n,o,s){let r=e,i=s,c;try{c=await fi(r,t,n,i)}catch(u){let d=u instanceof Error?u.message:String(u);if(e.startsWith("xoxb-")&&d.includes("not_allowed_token_type")){let f=Rg(e);if(f)console.error(`Note: search.messages needs a user token \u2014 the active profile is a bot token (xoxb-); falling back to profile "${f.name}".`),r=f.profile.token,i=f.profile.cookie,c=await fi(r,t,n,i);else console.error(`Error: search requires a user token (xoxp-/xoxc-) \u2014 the active profile is a bot token (xoxb-), which Slack rejects for search.messages.
324
329
  `+` Add a user-token profile: slack auth login (or slack auth login --token <token>)
325
- Then select it: slack auth use <name> (or pass --workspace <name>)`),process.exit(1)}else throw u}if(o){console.log(JSON.stringify(c,null,2));return}let a=X(Xn(c,["messages","matches"])).map(I),l=new Map;for(let u of a){let d=I(u.channel),f=d.is_im===!0,h=typeof d.name==="string"?d.name:"dm",m;if(f&&h.startsWith("U")){let p="@"+h;if(!l.has(p)){let[,D]=await es(r,h,i);l.set(p,D)}m=`@${l.get(p)??h}`}else if(f)m=`@${h}`;else m=`#${h}`;console.log(await Do(r,u,l,m,i))}}async function Ed(e,t,n,o){let{ref:s,ts:r}=At(t);if(!r)console.error("Error: target must embed a message ts (e.g. #chan:1700000000.000100 or a Slack permalink URL)"),process.exit(2);return{channelId:n??await hi(e,s,he,o),ts:r}}async function bg(e,t){let n=ss(),o={};if(!t.mine)o.shared=!0;if(t.in)o.in=t.in;if(t.from)o.from=t.from;let s=Ru(t.state,n,o);if(!t.json){let r=await it(e,t.cookie),i=t.mine?"your reactions only [hasmy:]":"anyone's reactions [has:]";console.error(`(From: ${_d(r)} \xB7 matching ${i})`),console.error(`(query: ${s})`)}await Oe("search.messages",()=>Cd(e,s,t.count,t.json,t.cookie))}async function kg(e,t){let n=ss(),{channelId:o,ts:s}=await Ed(e,t.target,t.channelId,t.cookie),r=await Lu(e,o,s,t.state,n,t.cookie);if(r.noop){console.log(`= Already ${t.state} (ts: ${s})`);return}let i=r.removed.length?`, removed ${r.removed.map((c)=>`:${c}:`).join(" ")}`:"";if(console.log(`\u2713 ${t.state} :${n.progress[t.state]}: (ts: ${s})${i}`),r.leftover.length)console.error(`\u26A0 ${r.leftover.map((c)=>`:${c}:`).join(" ")} could not be removed \u2014 this message now carries more than one `+"progress reaction. Readers collapse by priority so nothing is lost; repair with: slack todo doctor --in <#chan> --fix")}async function xg(e,t){let n=ss(),{channelId:o,ts:s}=await Ed(e,t.target,t.channelId,t.cookie),r=await ju(e,o,s,t.flag,n,t.remove===!0,t.cookie);console.log(`\u2713 ${t.remove?"Cleared":"Flagged"} ${t.flag} :${r}: (ts: ${s})`)}async function Cg(e,t){let n=ss(),o=t.channelId??await hi(e,t.channel,he,t.cookie),s={limit:t.limit};if(t.fix)s.fix=!0;if(t.cookie)s.cookie=t.cookie;let r=await Wu(e,o,n,s);if(r.findings.length===0)console.log(`\u2713 No multi-state tasks in ${r.scanned} message(s).`);else{for(let i of r.findings){let c=i.fixed===!0?"fixed":i.fixed===!1?`FAILED: ${i.error??"?"}`:"needs --fix";console.log(`${i.ts} ${i.emoji.map((a)=>`:${a}:`).join(" ")} \u2192 keep :${i.keep}: [${c}] ${q(i.text).slice(0,60)}`)}console.log(`${r.findings.length} multi-state task(s) in ${r.scanned} message(s).`)}if(r.truncated)console.error(`\u26A0 Scan limit reached (${t.limit} messages) \u2014 older history was NOT checked. Raise it with --limit N.`)}async function Eg(e,t,n,o){let s=Math.floor(Date.now()/1000)-t*86400,r=await Qn(e),i=X(r.channels).map(I).filter((u)=>u.is_member===!0&&u.is_im!==!0&&u.is_mpim!==!0).filter((u)=>{if(!o)return!0;return(typeof u.name==="string"?u.name:"").toLowerCase().includes(o.toLowerCase())}).sort((u,d)=>Number(d.updated??0)-Number(u.updated??0)),c=new Map,a=0,l=0;for(let u of i){let d=String(u.id??""),f=typeof u.name==="string"?u.name:d,h;try{h=await st(e,d,n)}catch(p){console.error(` SKIP #${f}: ${p.message}`);continue}let m=X(h.messages).map(I).filter((p)=>(p.subtype===void 0||p.subtype===null)&&uo(p)>=s);if(m.length===0)continue;l+=1,a+=m.length,console.log(`## #${f} (${m.length} msgs)
326
- `);for(let p of[...m].reverse()){let D=await kd(e,p,c),k=typeof p.text==="string"?p.text:"",E=bn(await tn(e,k,c)).split(`
327
- `).join(" \u21B5 ");console.log(`[${xi(uo(p))}] ${D}: ${E}`)}console.log("")}console.error(`Dumped ${a} messages across ${l} channels (cutoff: ${t}d)`)}function Sg(e){let t=[];function n(o){if(typeof o==="string"){t.push(o);return}if(Array.isArray(o)){for(let s of o)n(s);return}if(o&&typeof o==="object"){let s=o;if(typeof s.text==="string"){t.push(s.text);return}if(Array.isArray(s.elements))n(s.elements);else if(Array.isArray(s.content))n(s.content)}}for(let o of e)n(o);return t.join("").trim()}async function Sd(e,t,n){let o=new Map;return async(s)=>{if(!s)return"(unknown)";if(o.has(s))return o.get(s);try{let r=await Su(e,s,t),i=I(r.channel),c;if(i.is_im===!0){let a=typeof i.user==="string"?i.user:"";if(!a||a===n)c="@self";else{let[l]=await es(e,a);c=`@${l}`}}else c=`#${typeof i.name==="string"?i.name:s}`;return o.set(s,c),c}catch{return s}}}function Ii(e){let t=I(X(e.destinations)[0]);return String(t.channel_id??e.channel_id??e.channel??"")}function po(e){return Sg(X(e.blocks))||(typeof e.text==="string"?e.text:"(no text)")}async function _g(e,t,n=!1){let o=await ts(e,t),s=X(o.drafts??o.messages??[]).map(I).filter((l)=>l.is_deleted!==!0),r=n?s:s.filter((l)=>l.is_sent!==!0);if(r.length===0){console.log(n?"No drafts.":"No pending drafts. Run with --all to include sent.");return}let i="";try{({userId:i}=await ui(e,t))}catch{}let c=await Sd(e,t,i),a=new Map;for(let l of r){let u=Ii(l),d=po(l),f=Number(l.date_created??l.date_create??0),h=f?$i(f):"?",m=await c(u),p=typeof l.id==="string"?l.id:"",D=l.is_sent===!0?" [SENT]":"",k=bn(await tn(e,d,a));console.log(`-- ${p} ${m} [${h}]${D}`);for(let x of k.split(`
328
- `))console.log(` ${x}`)}}async function Fg(e,t,n){let o=await ts(e,t),s=X(o.drafts).map(I).find((m)=>String(m.id)===n);if(!s)console.error(`Draft not found: ${n}`),process.exit(1);let r="";try{({userId:r}=await ui(e,t))}catch{}let i=await Sd(e,t,r),c=Ii(s),a=po(s),l=Number(s.date_created??0),u=String(s.last_updated_ts??"?"),d=await i(c),h=bn(await tn(e,a,new Map));console.log(`id: ${s.id}`),console.log(`channel: ${d} (${c})`),console.log(`created: ${l?$i(l):"?"}`),console.log(`updated: ${$i(Number(u.split(".")[0]))}`),console.log(`status: ${s.is_sent===!0?"sent":"pending"}`),console.log("---"),console.log(h)}function De(...e){return ug(e.join(`
329
- `)).slice(0,4)}function q(e){return e.replace(/\x1b\[[0-9;:?]*[ -/]*[@-~]/g,"").replace(/[\x00-\x1f\x7f-\x9f]/g,"").replace(/[\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/g,"")}var $g={"reactions.add":"reactions:write","reactions.remove":"reactions:write","chat.postMessage":"chat:write","chat.update":"chat:write","chat.delete":"chat:write","pins.add":"pins:write","slackLists.create":"lists:write","slackLists.items.create":"lists:write","slackLists.items.update":"lists:write","slackLists.items.list":"lists:read","slackLists.access.set":"lists:write","conversations.replies":"channels:history (or groups:history)","conversations.history":"channels:history (or groups:history)"};function ce(e){let t=e instanceof Error?e.message:String(e),n=t.match(/Slack error on (\S+): (\w+)/);if(!n)return t;let[,o,s]=n;switch(s){case"missing_scope":return`Error: token lacks the ${$g[o]??"the required"} scope (needed for ${o}). Add it to your Slack App's User Token Scopes (or Bot Token Scopes if you use a bot token / --as-bot) \u2014 it must be on the token type the CLI actually uses \u2014 then reinstall to the workspace.`;case"invalid_name":return"Error: not a valid emoji shortcode \u2014 use the name without colons (e.g. white_check_mark), and make sure it exists in the workspace.";case"already_reacted":return"Error: you've already added that reaction to the message.";case"no_reaction":return"Error: that reaction isn't on the message \u2014 nothing to remove.";case"message_not_found":return"Error: no message found at that timestamp in the channel \u2014 check the target ts/permalink.";case"channel_not_found":return"Error: channel not found \u2014 check the target.";default:return t}}async function wo(e,t,n){if(!t.startsWith("D"))return null;try{let o=await bo(e,t,n);if(!o)return null;return await vu(e,o,ns,n)}catch{return null}}function ye(e,t,n,o,s=new Date){for(let i of n)console.log(i);let r=Ci(s,o);if(r)console.log(r);if(e!==void 0)console.error(`Code mismatch (got ${e}, expected ${t})`);console.error(`Rerun with --code=${t}`),process.exit(1)}function At(e){let t=Zt(e);if(t)return t.ts?{ref:t.channel,ts:t.ts}:{ref:t.channel};if(e.startsWith("#")||e.startsWith("@")){let n=e.indexOf(":");if(n>0){let o=e.slice(n+1);if(/^\d{10}\.\d{6}$/.test(o))return{ref:e.slice(0,n),ts:o};if(/^\d{4}-\d{2}-\d{2}T/.test(o))return{ref:e.slice(0,n),ts:Ti(o)}}}return{ref:e}}function Cn(e,t=!0){let n=Zt(e);if(n){if(!t)return{ref:n.channel};let s=n.threadTs??n.ts;return s?{ref:n.channel,threadTs:s}:{ref:n.channel}}let o=e.indexOf(":");if(o>0){let s=e.slice(o+1);if(/^\d{10}\.\d{6}$/.test(s))return{ref:e.slice(0,o),threadTs:s};if(/^\d{4}-\d{2}-\d{2}T/.test(s))return{ref:e.slice(0,o),threadTs:Ti(s)}}return{ref:e}}async function $t(e,t,n,o){let s=n;if(/^#?[CDG][A-Z0-9]{8,}$/.test(n)||!n.startsWith("#")&&!n.startsWith("@"))try{let i=I(await Dn(e,t,o)),c=I(i.channel);if(c.is_im===!0){let a=typeof c.user==="string"?c.user:"";s=a?`@${await Ie(e,a,o)}`:t}else s=typeof c.name==="string"?`#${c.name}`:t}catch{s=t}return s===t?t:`${s} (${t})`}async function it(e,t){try{return await Yn(e,t)}catch{return null}}function ht(e,t){let n;return async()=>{if(n===void 0)n=await it(e,t);return n}}function nn(e){if(!ti())return{record:()=>{}};let t=Kl();return{metadata:Hl(e,t),record:(n)=>{ql({...n,kind:e,attribution:t})}}}function Ag(e){let t=q(e.text.split(`
330
- `)[0]??"").slice(0,100),n=e.permalink||`${e.channel}:${e.ts}`,o=[e.cli??"?",e.session_id?`session=${e.session_id}`:"",e.agent_pid?`pid=${e.agent_pid}`:`pid=${e.pid}`,e.git_branch?`branch=${e.git_branch}`:"",`cwd=${e.cwd}`].filter(Boolean).join(" ");return`${xi(e.sent_at/1000)} ${e.kind.padEnd(4)} ${q(e.target??e.channel)} ${n}
330
+ Then select it: slack auth use <name> (or pass --workspace <name>)`),process.exit(1)}else throw u}if(o){console.log(JSON.stringify(c,null,2));return}let a=X(Yn(c,["messages","matches"])).map(T),l=new Map;for(let u of a){let d=T(u.channel),f=d.is_im===!0,h=typeof d.name==="string"?d.name:"dm",m;if(f&&h.startsWith("U")){let p="@"+h;if(!l.has(p)){let[,D]=await es(r,h,i);l.set(p,D)}m=`@${l.get(p)??h}`}else if(f)m=`@${h}`;else m=`#${h}`;console.log(await ko(r,u,l,m,i))}}async function vd(e,t,n,o){let{ref:s,ts:r}=Tt(t);if(!r)console.error("Error: target must embed a message ts (e.g. #chan:1700000000.000100 or a Slack permalink URL)"),process.exit(2);return{channelId:n??await yi(e,s,ue,o),ts:r}}async function Ng(e,t){let n=os(),o={};if(!t.mine)o.shared=!0;if(t.in)o.in=t.in;if(t.from)o.from=t.from;let s=qu(t.state,n,o);if(!t.json){let r=await rt(e,t.cookie),i=t.mine?"your reactions only [hasmy:]":"anyone's reactions [has:]";console.error(`(From: ${Ld(r)} \xB7 matching ${i})`),console.error(`(query: ${s})`)}await Oe("search.messages",()=>Bd(e,s,t.count,t.json,t.cookie))}async function Bg(e,t){let n=os(),{channelId:o,ts:s}=await vd(e,t.target,t.channelId,t.cookie),r=await Zu(e,o,s,t.state,n,t.cookie);if(r.noop){console.log(`= Already ${t.state} (ts: ${s})`);return}let i=r.removed.length?`, removed ${r.removed.map((c)=>`:${c}:`).join(" ")}`:"";if(console.log(`\u2713 ${t.state} :${n.progress[t.state]}: (ts: ${s})${i}`),r.leftover.length)console.error(`\u26A0 ${r.leftover.map((c)=>`:${c}:`).join(" ")} could not be removed \u2014 this message now carries more than one `+"progress reaction. Readers collapse by priority so nothing is lost; repair with: slack todo doctor --in <#chan> --fix")}async function vg(e,t){let n=os(),{channelId:o,ts:s}=await vd(e,t.target,t.channelId,t.cookie),r=await Qu(e,o,s,t.flag,n,t.remove===!0,t.cookie);console.log(`\u2713 ${t.remove?"Cleared":"Flagged"} ${t.flag} :${r}: (ts: ${s})`)}async function Lg(e,t){let n=os(),o=t.channelId??await yi(e,t.channel,ue,t.cookie),s={limit:t.limit};if(t.fix)s.fix=!0;if(t.cookie)s.cookie=t.cookie;let r=await ed(e,o,n,s);if(r.findings.length===0)console.log(`\u2713 No multi-state tasks in ${r.scanned} message(s).`);else{for(let i of r.findings){let c=i.fixed===!0?"fixed":i.fixed===!1?`FAILED: ${i.error??"?"}`:"needs --fix";console.log(`${i.ts} ${i.emoji.map((a)=>`:${a}:`).join(" ")} \u2192 keep :${i.keep}: [${c}] ${q(i.text).slice(0,60)}`)}console.log(`${r.findings.length} multi-state task(s) in ${r.scanned} message(s).`)}if(r.truncated)console.error(`\u26A0 Scan limit reached (${t.limit} messages) \u2014 older history was NOT checked. Raise it with --limit N.`)}async function Mg(e,t,n,o){let s=Math.floor(Date.now()/1000)-t*86400,r=await Qn(e),i=X(r.channels).map(T).filter((u)=>u.is_member===!0&&u.is_im!==!0&&u.is_mpim!==!0).filter((u)=>{if(!o)return!0;return(typeof u.name==="string"?u.name:"").toLowerCase().includes(o.toLowerCase())}).sort((u,d)=>Number(d.updated??0)-Number(u.updated??0)),c=new Map,a=0,l=0;for(let u of i){let d=String(u.id??""),f=typeof u.name==="string"?u.name:d,h;try{h=await ot(e,d,n)}catch(p){console.error(` SKIP #${f}: ${p.message}`);continue}let m=X(h.messages).map(T).filter((p)=>(p.subtype===void 0||p.subtype===null)&&go(p)>=s);if(m.length===0)continue;l+=1,a+=m.length,console.log(`## #${f} (${m.length} msgs)
331
+ `);for(let p of[...m].reverse()){let D=await Rd(e,p,c),k=typeof p.text==="string"?p.text:"",C=kn(await nn(e,k,c)).split(`
332
+ `).join(" \u21B5 ");console.log(`[${co(go(p))}] ${D}: ${C}`)}console.log("")}console.error(`Dumped ${a} messages across ${l} channels (cutoff: ${t}d)`)}function jg(e){let t=[];function n(o){if(typeof o==="string"){t.push(o);return}if(Array.isArray(o)){for(let s of o)n(s);return}if(o&&typeof o==="object"){let s=o;if(typeof s.text==="string"){t.push(s.text);return}if(s.type==="link"&&typeof s.url==="string"){t.push(s.url);return}if(Array.isArray(s.elements))n(s.elements);else if(Array.isArray(s.content))n(s.content)}}for(let o of e)n(o);return t.join("").trim()}async function Ri(e,t,n){let o=new Map;return async(s)=>{if(!s)return"(unknown)";if(o.has(s))return o.get(s);try{let r=await Ou(e,s,t),i=T(r.channel),c;if(i.is_im===!0){let a=typeof i.user==="string"?i.user:"";if(!a||a===n)c="@self";else{let[l]=await es(e,a);c=`@${l}`}}else c=`#${typeof i.name==="string"?i.name:s}`;return o.set(s,c),c}catch{return s}}}function Ni(e){let t=T(X(e.destinations)[0]);return String(t.channel_id??e.channel_id??e.channel??"")}function Do(e){return jg(X(e.blocks))||(typeof e.text==="string"?e.text:"(no text)")}async function Wg(e,t,n=!1){let o=await ts(e,t),s=X(o.drafts??o.messages??[]).map(T).filter((l)=>l.is_deleted!==!0),r=n?s:s.filter((l)=>l.is_sent!==!0);if(r.length===0){console.log(n?"No drafts.":"No pending drafts. Run with --all to include sent.");return}let i="";try{({userId:i}=await hi(e,t))}catch{}let c=await Ri(e,t,i),a=new Map;for(let l of r){let u=Ni(l),d=Do(l),f=Number(l.date_created??l.date_create??0),h=f?Ii(f):"?",m=await c(u),p=typeof l.id==="string"?l.id:"",D=l.is_sent===!0?" [SENT]":"",k=kn(await nn(e,d,a));console.log(`-- ${p} ${m} [${h}]${D}`);for(let x of k.split(`
333
+ `))console.log(` ${x}`)}}async function Ug(e,t,n){let o=[],s;do{let u=T(await Au(e,{filter:n.filter,limit:Math.min(n.limit,100),cursor:s},t));o.push(...vu(u));let d=T(u.response_metadata).next_cursor;s=typeof d==="string"&&d?d:void 0}while(s&&o.length<n.limit);let r=Lu(o).slice(0,n.limit);if(r.length===0){(n.json?console.error:console.log)(`No ${n.filter==="todo"?"to-dos":`${n.filter} items`}.`);return}let i="",c="";try{({url:i,userId:c}=await Dn(e,t))}catch{}let a=await Ri(e,t,c),l=Date.now()/1000;for(let u of r){let d;if(u.channel&&u.ts)try{let k=T(await Me(e,u.channel,u.ts,1,t));d=X(k.messages).map(T).find((x)=>x.ts===u.ts)}catch{}let f=u.channel&&u.ts?i?ju(i,u.channel,u.ts):`${u.channel}:${u.ts}`:"";if(n.json){console.log(JSON.stringify({...u,done:no(u),permalink:f,user:d?.user??null,text:d?.text??null}));continue}let h=u.channel?await a(u.channel):`(${u.itemType||"item"})`,m=typeof d?.user==="string"?`@${await Ae(e,d.user,t)}: `:"",p=typeof d?.text==="string"?d.text.split(`
334
+ `)[0]??"":"(message not readable)",D=p.length>100?`${p.slice(0,100)}\u2026`:p;if(console.log(`${Mu(u,l,co)} ${q(h)}`),console.log(` ${q(m+D)}`),f)console.log(` ${f}`)}}async function Jg(e,t,n){let o=await ts(e,t),s=X(o.drafts).map(T).find((m)=>String(m.id)===n);if(!s)console.error(`Draft not found: ${n}`),process.exit(1);let r="";try{({userId:r}=await hi(e,t))}catch{}let i=await Ri(e,t,r),c=Ni(s),a=Do(s),l=Number(s.date_created??0),u=String(s.last_updated_ts??"?"),d=await i(c),h=kn(await nn(e,a,new Map));console.log(`id: ${s.id}`),console.log(`channel: ${d} (${c})`),console.log(`created: ${l?Ii(l):"?"}`),console.log(`updated: ${Ii(Number(u.split(".")[0]))}`),console.log(`status: ${s.is_sent===!0?"sent":"pending"}`),console.log("---"),console.log(h)}function ge(...e){return Sg(e.join(`
335
+ `)).slice(0,4)}function q(e){return e.replace(/\x1b\[[0-9;:?]*[ -/]*[@-~]/g,"").replace(/[\x00-\x1f\x7f-\x9f]/g,"").replace(/[\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/g,"")}var Kg={"reactions.add":"reactions:write","reactions.remove":"reactions:write","chat.postMessage":"chat:write","chat.update":"chat:write","chat.delete":"chat:write","pins.add":"pins:write","slackLists.create":"lists:write","slackLists.items.create":"lists:write","slackLists.items.update":"lists:write","slackLists.items.list":"lists:read","slackLists.access.set":"lists:write","conversations.rename":"channels:manage (or groups:write for a private channel)","conversations.replies":"channels:history (or groups:history)","conversations.history":"channels:history (or groups:history)"};function ae(e){let t=e instanceof Error?e.message:String(e),n=t.match(/Slack error on (\S+): (\w+)/);if(!n)return t;let[,o,s]=n;switch(s){case"missing_scope":return`Error: token lacks the ${Kg[o]??"the required"} scope (needed for ${o}). Add it to your Slack App's User Token Scopes (or Bot Token Scopes if you use a bot token / --as-bot) \u2014 it must be on the token type the CLI actually uses \u2014 then reinstall to the workspace.`;case"invalid_name":return"Error: not a valid emoji shortcode \u2014 use the name without colons (e.g. white_check_mark), and make sure it exists in the workspace.";case"already_reacted":return"Error: you've already added that reaction to the message.";case"no_reaction":return"Error: that reaction isn't on the message \u2014 nothing to remove.";case"message_not_found":return"Error: no message found at that timestamp in the channel \u2014 check the target ts/permalink.";case"channel_not_found":return"Error: channel not found \u2014 check the target.";default:return t}}async function Eo(e,t,n){if(!t.startsWith("D"))return null;try{let o=await Co(e,t,n);if(!o)return null;return await Vu(e,o,ns,n)}catch{return null}}function me(e,t,n,o,s=new Date){for(let i of n)console.log(i);let r=_i(s,o);if(r)console.log(r);if(e!==void 0)console.error(`Code mismatch (got ${e}, expected ${t})`);console.error(`Rerun with --code=${t}`),process.exit(1)}function Tt(e){let t=Zt(e);if(t)return t.ts?{ref:t.channel,ts:t.ts}:{ref:t.channel};if(e.startsWith("#")||e.startsWith("@")){let n=e.indexOf(":");if(n>0){let o=e.slice(n+1);if(/^\d{10}\.\d{6}$/.test(o))return{ref:e.slice(0,n),ts:o};if(/^\d{4}-\d{2}-\d{2}T/.test(o))return{ref:e.slice(0,n),ts:Pi(o)}}}return{ref:e}}function Cn(e,t=!0){let n=Zt(e);if(n){if(!t)return{ref:n.channel};let s=n.threadTs??n.ts;return s?{ref:n.channel,threadTs:s}:{ref:n.channel}}let o=e.indexOf(":");if(o>0){let s=e.slice(o+1);if(/^\d{10}\.\d{6}$/.test(s))return{ref:e.slice(0,o),threadTs:s};if(/^\d{4}-\d{2}-\d{2}T/.test(s))return{ref:e.slice(0,o),threadTs:Pi(s)}}return{ref:e}}async function At(e,t,n,o){let s=n;if(/^#?[CDG][A-Z0-9]{8,}$/.test(n)||!n.startsWith("#")&&!n.startsWith("@"))try{let i=T(await Qt(e,t,o)),c=T(i.channel);if(c.is_im===!0){let a=typeof c.user==="string"?c.user:"";s=a?`@${await Ae(e,a,o)}`:t}else s=typeof c.name==="string"?`#${c.name}`:t}catch{s=t}return s===t?t:`${s} (${t})`}async function rt(e,t){try{return await Dn(e,t)}catch{return null}}function gt(e,t){let n;return async()=>{if(n===void 0)n=await rt(e,t);return n}}function sn(e){if(!ri())return{record:()=>{}};let t=Xl();return{metadata:Yl(e,t),record:(n)=>{Zl({...n,kind:e,attribution:t})}}}function Hg(e){let t=q(e.text.split(`
336
+ `)[0]??"").slice(0,100),n=e.permalink||`${e.channel}:${e.ts}`,o=[e.cli??"?",e.session_id?`session=${e.session_id}`:"",e.agent_pid?`pid=${e.agent_pid}`:`pid=${e.pid}`,e.git_branch?`branch=${e.git_branch}`:"",`cwd=${e.cwd}`].filter(Boolean).join(" ");return`${co(e.sent_at/1000)} ${e.kind.padEnd(4)} ${q(e.target??e.channel)} ${n}
331
337
  ${t}
332
- ${q(o)}`}function _d(e,t){let n=t?" [as bot]":"";if(!e)return`(unknown \u2014 auth.test failed)${n}`;let o=q(e.user||e.userId||"?"),s=e.userId?` (${e.userId})`:"",r=e.team?` \u2014 ${q(e.team)}`:"";return`@${o}${s}${r}${n}`}function we(e,t={}){return` ${"From:".padEnd(t.pad??6)}${_d(e,t.asBot)}`}async function Ai(e,t,n=60,o){let s=typeof t.user==="string"?await Ie(e,t.user,o):typeof t.username==="string"?t.username:"?",r=rs((typeof t.text==="string"?t.text:"").split(`
333
- `)[0]??""),i=r.length>n?`${r.slice(0,n)}\u2026`:r,c=typeof t.ts==="string"?t.ts:"";return`${c?fo(c).slice(0,16).replace("T"," "):""} @${s}${i?`: ${i}`:""}`}async function Tg(e,t,n,o){let s=n.find((r)=>String(r.ts)===t)??n[0];if(!s)return t;return Ai(e,s,40,o)}function ad(e){return e.toLowerCase().replace(/<[@#!][^>]+>/g," ").replace(/[^\p{L}\p{N}\s]/gu," ").replace(/\s+/g," ").trim()}function Ig(e,t){let n=ad(e),o=ad(t);if(!n||!o)return 0;if(n===o)return 1;let s=(l)=>{let u=new Map;for(let d=0;d<l.length-1;d++){let f=l.slice(d,d+2);u.set(f,(u.get(f)??0)+1)}return u},r=s(n),i=s(o);if(r.size===0||i.size===0)return 0;let c=0;for(let[l,u]of r){let d=i.get(l);if(d)c+=Math.min(u,d)}let a=cd(r)+cd(i);return a===0?0:2*c/a}function cd(e){let t=0;for(let n of e.values())t+=n;return t}async function ld(e,t,n,o){let s=lt();if(!s)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
334
- Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(1);if(o)return{botToken:s};let{ref:r}=At(e);if(!r.startsWith("@"))return{botToken:s};try{let i=await pt(t,r,n);return{botToken:s,channelId:await ft(s,i)}}catch(i){console.error(`Error: could not resolve ${q(r)} to the bot's DM.
338
+ ${q(o)}`}function Ld(e,t){let n=t?" [as bot]":"";if(!e)return`(unknown \u2014 auth.test failed)${n}`;let o=q(e.user||e.userId||"?"),s=e.userId?` (${e.userId})`:"",r=e.team?` \u2014 ${q(e.team)}`:"";return`@${o}${s}${r}${n}`}function De(e,t={}){return` ${"From:".padEnd(t.pad??6)}${Ld(e,t.asBot)}`}async function Oi(e,t,n=60,o){let s=typeof t.user==="string"?await Ae(e,t.user,o):typeof t.username==="string"?t.username:"?",r=is((typeof t.text==="string"?t.text:"").split(`
339
+ `)[0]??""),i=r.length>n?`${r.slice(0,n)}\u2026`:r,c=typeof t.ts==="string"?t.ts:"";return`${c?mo(c).slice(0,16).replace("T"," "):""} @${s}${i?`: ${i}`:""}`}async function zg(e,t,n,o){let s=n.find((r)=>String(r.ts)===t)??n[0];if(!s)return t;return Oi(e,s,40,o)}function bd(e){return e.toLowerCase().replace(/<[@#!][^>]+>/g," ").replace(/[^\p{L}\p{N}\s]/gu," ").replace(/\s+/g," ").trim()}function qg(e,t){let n=bd(e),o=bd(t);if(!n||!o)return 0;if(n===o)return 1;let s=(l)=>{let u=new Map;for(let d=0;d<l.length-1;d++){let f=l.slice(d,d+2);u.set(f,(u.get(f)??0)+1)}return u},r=s(n),i=s(o);if(r.size===0||i.size===0)return 0;let c=0;for(let[l,u]of r){let d=i.get(l);if(d)c+=Math.min(u,d)}let a=kd(r)+kd(i);return a===0?0:2*c/a}function kd(e){let t=0;for(let n of e.values())t+=n;return t}async function xd(e,t,n,o){let s=ut();if(!s)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
340
+ Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(1);if(o)return{botToken:s};let{ref:r}=Tt(e);if(!r.startsWith("@"))return{botToken:s};try{let i=await ht(t,r,n);return{botToken:s,channelId:await pt(s,i)}}catch(i){console.error(`Error: could not resolve ${q(r)} to the bot's DM.
335
341
  ${i instanceof Error?i.message:String(i)}
336
- `+" Tip: pass the message permalink, or --channel-id <D\u2026>, to skip the lookup."),process.exit(1)}}async function Og(e,t){let n=ht(e,t.cookie),{ref:o,ts:s}=At(t.target);if(!s)console.error("Error: target must embed a message ts (e.g. #chan:2026-05-11T06:01:04.000100 or a Slack permalink URL)"),process.exit(2);let r;if(t.channelId)r=t.channelId;else r=await he(e,o,t.cookie);let i=await qe(e,r,s,1,t.cookie),a=X(i.messages).map(I).find((D)=>String(D.ts)===s);if(!a)console.error(`Message not found at ts=${s} in channel ${r}`),process.exit(1);let l=typeof a.text==="string"?a.text:"",u=t.mentionCookie??t.cookie,d=t.mentions?await Ju(t.mentionToken??e,t.newText,r,u?{cookie:u}:{}):t.newText;kt(d,t.allowUrlAdjacent);let f=await n(),h=De(l,d,f?.userId??"");if(t.code!==h)ye(t.code,h,["--- Editing as -------------------------------",we(f,{asBot:t.asBot}),"--- Original message -------------------------",...l.split(`
342
+ `+" Tip: pass the message permalink, or --channel-id <D\u2026>, to skip the lookup."),process.exit(1)}}async function Gg(e,t){let n=gt(e,t.cookie),{ref:o,ts:s}=Tt(t.target);if(!s)console.error("Error: target must embed a message ts (e.g. #chan:2026-05-11T06:01:04.000100 or a Slack permalink URL)"),process.exit(2);let r;if(t.channelId)r=t.channelId;else r=await ue(e,o,t.cookie);let i=await Me(e,r,s,1,t.cookie),a=X(i.messages).map(T).find((D)=>String(D.ts)===s);if(!a)console.error(`Message not found at ts=${s} in channel ${r}`),process.exit(1);let l=typeof a.text==="string"?a.text:"",u=t.mentionCookie??t.cookie,d=t.mentions?await nd(t.mentionToken??e,t.newText,r,u?{cookie:u}:{}):t.newText;ve(d,t.allowUrlAdjacent);let f=await n(),h=ge(l,d,f?.userId??"");if(t.code!==h)me(t.code,h,["--- Editing as -------------------------------",De(f,{asBot:t.asBot}),"--- Original message -------------------------",...l.split(`
337
343
  `).map((D)=>` ${D}`),"--- Replacing with ---------------------------",...d.split(`
338
- `).map((D)=>` ${D}`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);let m=nn("edit"),p=await Vt(e,r,s,d,t.cookie,void 0,m.metadata);console.log(`\u2713 Edited (ts: ${p})`),m.record({team:f?.team,channel:r,target:t.target,ts:s,text:d,asBot:t.asBot})}async function Pg(e,t){let n=ht(e,t.cookie),{ref:o,ts:s}=At(t.target);if(!s)console.error("Error: target must embed a message ts (e.g. #chan:2026-05-11T06:01:04.000100 or a Slack permalink URL)"),process.exit(2);let r;if(t.channelId)r=t.channelId;else r=await he(e,o,t.cookie);let i=await qe(e,r,s,1,t.cookie),a=X(i.messages).map(I).find((f)=>String(f.ts)===s);if(!a)console.error(`Message not found at ts=${s} in channel ${r}`),process.exit(1);let l=typeof a.text==="string"?a.text:"",u=await n(),d=De(r,s,l,u?.userId??"");if(t.code!==d){let f=await $t(e,r,o,t.cookie);ye(t.code,d,["--- Deleting message -------------------------",we(u,{asBot:t.asBot}),` \u2192 ${f} at ${fo(s)}`,...l.split(`
339
- `).map((h)=>` ${h}`),"---------------------------------------------"])}await fu(e,r,s,t.cookie),console.log(`\u2713 Deleted (ts: ${s})`)}function Ft(e){return`'${e.replace(/'/g,"'\\''")}'`}async function Oi(e,t,n){let o=io(t);if(o)return{...o,ref:o.channel};let{ref:s,ts:r}=At(t);if(!r)console.error(`Error: ${q(t)} is a channel, not a board \u2014 pass the board's permalink, `+`#chan:ts, or the id \`new\` printed (C\u2026:ts). Boards in a channel: slack pinlog ls ${Ft(t)}`),process.exit(2);return{channel:await he(e,s,n),ts:r,ref:s}}async function Rg(e,t,n,o){let s=I(await qe(e,t,n,1,o)),r=X(s.messages).map(I).find((i)=>String(i.ts)===n);if(!r)console.error(`Error: no message at ts=${n} in ${t}.`),process.exit(1);return r}function ao(e,t){if(t!==void 0)try{return wd(t==="-"?0:t,"utf8").replace(/\n+$/,"")}catch(n){console.error(`Error: cannot read --file ${t}: ${n instanceof Error?n.message:String(n)}`),process.exit(2)}return e===void 0?void 0:Ge(e)}var ud=40000;function ho(e,t){if(t.length>ud)console.error(`Error: the ${e} is ${t.length} characters; Slack truncates past ${ud}. Shorten it \u2014 move detail to a linked page.`),process.exit(2)}function go(e){let n=(e instanceof Error?e.message:String(e)).match(/Slack error on \S+: (\w+)/);if(e instanceof dt)return!0;return!!n&&!["internal_error","fatal_error","request_timeout","service_unavailable"].includes(n[1])}function Fd(e,t){let n=Ci(e);return n&&n.includes("QUIET HOURS")?`\u26A0 Quiet hours (JST): ${t}.`:null}async function Ng(e,t){let{ref:n,ts:o}=At(t.target);if(o||io(t.target))console.error("Error: `pinlog new` posts a NEW board \u2014 pass a channel (#chan or C\u2026), not a message.\n"+` To change an existing board: slack pinlog set ${Ft(t.target)} '<new state>' '<reason>'`),process.exit(2);if(!t.state.trim())console.error("Error: the initial state is empty \u2014 a board has to say something."),process.exit(2);if(kt(t.state,t.allowUrlAdjacent),t.log!==void 0)kt(t.log,t.allowUrlAdjacent),ho("reason",t.log);let s=`${t.workspace?` -w ${Ft(t.workspace)}`:""}${t.asBot?" --as-bot":""}`,r=ht(e,t.cookie),i=await he(e,n,t.cookie),c=await r(),a=De("pinlog-create",i,t.state,t.log??"",c?.userId??""),l=new Date,u=_i(t.state,l);if(ho("HEAD (state + footer)",u),t.code!==a){let p=await $t(e,i,n,t.cookie),D=(await $d(e,i,200,t.cookie)).found;ye(t.code,a,["--- New pinlog -------------------------------",we(c,{asBot:t.asBot}),` \u2192 ${p} \u2014 NEW top-level message, then pinned`,...D.length?[`\u26A0 ${D.length} board(s) already in this channel \u2014 to change one, use \`slack pinlog set <board> \u2026\` instead:`,...D.slice(0,5).map((k)=>` ${Xe(i,String(k.ts))} ${Ad(String(k.text))}`)]:[" (no other boards in the last 200 messages of this channel)"],"--- State (the top-level message) ------------",...u.split(`
344
+ `).map((D)=>` ${D}`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);let m=sn("edit"),p=await Vt(e,r,s,d,t.cookie,void 0,m.metadata);console.log(`\u2713 Edited (ts: ${p})`),m.record({team:f?.team,channel:r,target:t.target,ts:s,text:d,asBot:t.asBot})}async function Xg(e,t){let n=gt(e,t.cookie),{ref:o,ts:s}=Tt(t.target);if(!s)console.error("Error: target must embed a message ts (e.g. #chan:2026-05-11T06:01:04.000100 or a Slack permalink URL)"),process.exit(2);let r;if(t.channelId)r=t.channelId;else r=await ue(e,o,t.cookie);let i=await Me(e,r,s,1,t.cookie),a=X(i.messages).map(T).find((f)=>String(f.ts)===s);if(!a)console.error(`Message not found at ts=${s} in channel ${r}`),process.exit(1);let l=typeof a.text==="string"?a.text:"",u=await n(),d=ge(r,s,l,u?.userId??"");if(t.code!==d){let f=await At(e,r,o,t.cookie);me(t.code,d,["--- Deleting message -------------------------",De(u,{asBot:t.asBot}),` \u2192 ${f} at ${mo(s)}`,...l.split(`
345
+ `).map((h)=>` ${h}`),"---------------------------------------------"])}await Du(e,r,s,t.cookie),console.log(`\u2713 Deleted (ts: ${s})`)}function $t(e){return`'${e.replace(/'/g,"'\\''")}'`}async function Bi(e,t,n){let o=uo(t);if(o)return{...o,ref:o.channel};let{ref:s,ts:r}=Tt(t);if(!r)console.error(`Error: ${q(t)} is a channel, not a board \u2014 pass the board's permalink, `+`#chan:ts, or the id \`new\` printed (C\u2026:ts). Boards in a channel: slack pinlog ls ${$t(t)}`),process.exit(2);return{channel:await ue(e,s,n),ts:r,ref:s}}async function Yg(e,t,n,o){let s=T(await Me(e,t,n,1,o)),r=X(s.messages).map(T).find((i)=>String(i.ts)===n);if(!r)console.error(`Error: no message at ts=${n} in ${t}.`),process.exit(1);return r}function fo(e,t){if(t!==void 0)try{return Od(t==="-"?0:t,"utf8").replace(/\n+$/,"")}catch(n){console.error(`Error: cannot read --file ${t}: ${n instanceof Error?n.message:String(n)}`),process.exit(2)}return e===void 0?void 0:Xe(e)}var Ed=40000;function yo(e,t){if(t.length>Ed)console.error(`Error: the ${e} is ${t.length} characters; Slack truncates past ${Ed}. Shorten it \u2014 move detail to a linked page.`),process.exit(2)}function wo(e){let n=(e instanceof Error?e.message:String(e)).match(/Slack error on \S+: (\w+)/);if(e instanceof ft)return!0;return!!n&&!["internal_error","fatal_error","request_timeout","service_unavailable"].includes(n[1])}function Md(e,t){let n=_i(e);return n&&n.includes("QUIET HOURS")?`\u26A0 Quiet hours (JST): ${t}.`:null}async function Vg(e,t){let{ref:n,ts:o}=Tt(t.target);if(o||uo(t.target))console.error("Error: `pinlog new` posts a NEW board \u2014 pass a channel (#chan or C\u2026), not a message.\n"+` To change an existing board: slack pinlog set ${$t(t.target)} '<new state>' '<reason>'`),process.exit(2);if(!t.state.trim())console.error("Error: the initial state is empty \u2014 a board has to say something."),process.exit(2);if(ve(t.state,t.allowUrlAdjacent),t.log!==void 0)ve(t.log,t.allowUrlAdjacent),yo("reason",t.log);let s=`${t.workspace?` -w ${$t(t.workspace)}`:""}${t.asBot?" --as-bot":""}`,r=gt(e,t.cookie),i=await ue(e,n,t.cookie),c=await r(),a=ge("pinlog-create",i,t.state,t.log??"",c?.userId??""),l=new Date,u=Ai(t.state,l);if(yo("HEAD (state + footer)",u),t.code!==a){let p=await At(e,i,n,t.cookie),D=(await jd(e,i,200,t.cookie)).found;me(t.code,a,["--- New pinlog -------------------------------",De(c,{asBot:t.asBot}),` \u2192 ${p} \u2014 NEW top-level message, then pinned`,...D.length?[`\u26A0 ${D.length} board(s) already in this channel \u2014 to change one, use \`slack pinlog set <board> \u2026\` instead:`,...D.slice(0,5).map((k)=>` ${Ye(i,String(k.ts))} ${Wd(String(k.text))}`)]:[" (no other boards in the last 200 messages of this channel)"],"--- State (the top-level message) ------------",...u.split(`
340
346
  `).map((k)=>` ${q(k)}`),...t.log?["--- Reason (first thread reply \u2014 notifies) ---",...t.log.split(`
341
- `).map((k)=>` ${q(k)}`)]:[],"---------------------------------------------"])}let d=nn("send"),f;try{f=await Yt(e,i,u,void 0,!1,t.cookie,!0,d.metadata)}catch(p){if(go(p))console.error(`\u2717 HEAD was NOT posted: ${ce(p)}`);else console.error(`\u26A0 UNKNOWN whether the HEAD was posted: ${ce(p)}
342
- Check before retrying, or you will have two boards: slack pinlog ls ${Ft(t.target)}${s}`);process.exit(1)}if(!f)console.error("\u2717 Slack accepted the post but returned no ts \u2014 check the channel before retrying, it may have landed."),process.exit(1);d.record({team:c?.team,channel:i,target:t.target,ts:f,text:u,asBot:t.asBot});let h=Xe(i,f);console.log(`\u2713 Posted HEAD: ${h}`);let m=Fd(l,"this new top-level post notified everyone who follows the channel");if(m)console.error(m);try{await li(e,i,f,t.cookie),console.log("\u2713 Pinned")}catch(p){let D=p instanceof Error?p.message:String(p),k=/missing_scope/.test(D)?`the ${t.asBot?"bot":"user"} token lacks the pins:write scope`:ce(p);console.error(`\u26A0 NOT pinned: ${k}.`),console.error(` The board works unpinned; pin it later with: slack pinlog pin ${h}${s}`)}if(t.log)try{let p=await Yt(e,i,t.log,f,!1,t.cookie,!0);console.log(`\u2713 Reason posted in the thread (ts: ${p})`)}catch(p){let D=De("pinlog-log",i,f,t.log,c?.userId??"");console.error(`${go(p)?"\u2717 The reason was NOT posted":"\u26A0 UNKNOWN whether the reason was posted"}: ${ce(p)}
347
+ `).map((k)=>` ${q(k)}`)]:[],"---------------------------------------------"])}let d=sn("send"),f;try{f=await Yt(e,i,u,void 0,!1,t.cookie,!0,d.metadata)}catch(p){if(wo(p))console.error(`\u2717 HEAD was NOT posted: ${ae(p)}`);else console.error(`\u26A0 UNKNOWN whether the HEAD was posted: ${ae(p)}
348
+ Check before retrying, or you will have two boards: slack pinlog ls ${$t(t.target)}${s}`);process.exit(1)}if(!f)console.error("\u2717 Slack accepted the post but returned no ts \u2014 check the channel before retrying, it may have landed."),process.exit(1);d.record({team:c?.team,channel:i,target:t.target,ts:f,text:u,asBot:t.asBot});let h=Ye(i,f);console.log(`\u2713 Posted HEAD: ${h}`);let m=Md(l,"this new top-level post notified everyone who follows the channel");if(m)console.error(m);try{await pi(e,i,f,t.cookie),console.log("\u2713 Pinned")}catch(p){let D=p instanceof Error?p.message:String(p),k=/missing_scope/.test(D)?`the ${t.asBot?"bot":"user"} token lacks the pins:write scope`:ae(p);console.error(`\u26A0 NOT pinned: ${k}.`),console.error(` The board works unpinned; pin it later with: slack pinlog pin ${h}${s}`)}if(t.log)try{let p=await Yt(e,i,t.log,f,!1,t.cookie,!0);console.log(`\u2713 Reason posted in the thread (ts: ${p})`)}catch(p){let D=ge("pinlog-log",i,f,t.log,c?.userId??"");console.error(`${wo(p)?"\u2717 The reason was NOT posted":"\u26A0 UNKNOWN whether the reason was posted"}: ${ae(p)}
343
349
  The board IS posted. Retry just the reason (check the thread first):
344
- slack pinlog note ${h} ${Ft(Di(t.log))}${t.allowUrlAdjacent?" --allow-url-adjacent":""}${s} --code=${D}`),process.exit(1)}}async function dd(e,t){if(!t.log.trim())console.error("Error: the reason is required \u2014 one short line saying what changed. The thread log is the point of a pinlog."),process.exit(2);if(!t.logOnly&&(t.state===void 0||!t.state.trim()))console.error("Error: the new state is required (positional or --file). To post only a reason: slack pinlog note <board> <reason>"),process.exit(2);if(kt(t.log,t.allowUrlAdjacent),t.state!==void 0)kt(t.state,t.allowUrlAdjacent);ho("log line",t.log);let n=ht(e,t.cookie),{channel:o,ts:s,ref:r}=await Oi(e,t.target,t.cookie);try{rd(`pinlog-${o}-${s}`)}catch(k){if(!(k instanceof is))throw k;console.error(`Error: another update of ${Xe(o,s)} is running (${k.holder}). Re-run when it has finished \u2014 then re-read the board, it has changed.`),process.exit(1)}let i=await Rg(e,o,s,t.cookie),c=typeof i.text==="string"?i.text:"";if(t.adopt&&t.logOnly)console.error("Error: --adopt rewrites the state with a footer \u2014 it does not apply to note."),process.exit(2);if(!xn(c)&&!t.adopt)console.error(`Error: the message at ${Xe(o,s)} is not a pinlog HEAD (no "${as}" footer).
345
- `+" Refusing to overwrite it \u2014 check the id. To turn this message into a board on purpose, add --adopt."),process.exit(1);let a=await n(),l=Xe(o,s),u=new Date,d=`${t.workspace?` -w ${Ft(t.workspace)}`:""}${t.asBot?" --as-bot":""}`,f=De("pinlog-log",o,s,t.log,a?.userId??""),h=`slack pinlog note ${l} ${Ft(Di(t.log))}${t.allowUrlAdjacent?" --allow-url-adjacent":""}${d} --code=${f}`,m=Fd(u,"the log reply notified everyone following this thread \u2014 hold non-urgent updates until 08:00");if(t.logOnly){if(t.code!==f){let k=await $t(e,o,r,t.cookie);ye(t.code,f,["--- Pinlog log reply (HEAD unchanged) --------",we(a,{asBot:t.asBot}),` \u2192 ${k}, thread of ${l}`,...t.log.split(`
346
- `).map((x)=>` ${q(x)}`),"---------------------------------------------"])}}else{let k=_i(t.state,u);ho("new HEAD (state + footer)",k);let x=!xn(c),E=De("pinlog-update",o,s,c,t.state,t.log,a?.userId??"");if(t.code!==E){let N=await $t(e,o,r,t.cookie),W=cs(c).trim()===cs(t.state).trim();ye(t.code,E,["--- Updating pinlog --------------------------",we(a,{asBot:t.asBot}),` \u2192 ${N}, ${l}`,"--- Current HEAD -----------------------------",...c.split(`
350
+ slack pinlog note ${h} ${$t(ki(t.log))}${t.allowUrlAdjacent?" --allow-url-adjacent":""}${s} --code=${D}`),process.exit(1)}}async function Cd(e,t){if(!t.log.trim())console.error("Error: the reason is required \u2014 one short line saying what changed. The thread log is the point of a pinlog."),process.exit(2);if(!t.logOnly&&(t.state===void 0||!t.state.trim()))console.error("Error: the new state is required (positional or --file). To post only a reason: slack pinlog note <board> <reason>"),process.exit(2);if(ve(t.log,t.allowUrlAdjacent),t.state!==void 0)ve(t.state,t.allowUrlAdjacent);yo("log line",t.log);let n=gt(e,t.cookie),{channel:o,ts:s,ref:r}=await Bi(e,t.target,t.cookie);try{yd(`pinlog-${o}-${s}`)}catch(k){if(!(k instanceof as))throw k;console.error(`Error: another update of ${Ye(o,s)} is running (${k.holder}). Re-run when it has finished \u2014 then re-read the board, it has changed.`),process.exit(1)}let i=await Yg(e,o,s,t.cookie),c=typeof i.text==="string"?i.text:"";if(t.adopt&&t.logOnly)console.error("Error: --adopt rewrites the state with a footer \u2014 it does not apply to note."),process.exit(2);if(!En(c)&&!t.adopt)console.error(`Error: the message at ${Ye(o,s)} is not a pinlog HEAD (no "${cs}" footer).
351
+ `+" Refusing to overwrite it \u2014 check the id. To turn this message into a board on purpose, add --adopt."),process.exit(1);let a=await n(),l=Ye(o,s),u=new Date,d=`${t.workspace?` -w ${$t(t.workspace)}`:""}${t.asBot?" --as-bot":""}`,f=ge("pinlog-log",o,s,t.log,a?.userId??""),h=`slack pinlog note ${l} ${$t(ki(t.log))}${t.allowUrlAdjacent?" --allow-url-adjacent":""}${d} --code=${f}`,m=Md(u,"the log reply notified everyone following this thread \u2014 hold non-urgent updates until 08:00");if(t.logOnly){if(t.code!==f){let k=await At(e,o,r,t.cookie);me(t.code,f,["--- Pinlog log reply (HEAD unchanged) --------",De(a,{asBot:t.asBot}),` \u2192 ${k}, thread of ${l}`,...t.log.split(`
352
+ `).map((x)=>` ${q(x)}`),"---------------------------------------------"])}}else{let k=Ai(t.state,u);yo("new HEAD (state + footer)",k);let x=!En(c),C=ge("pinlog-update",o,s,c,t.state,t.log,a?.userId??"");if(t.code!==C){let N=await At(e,o,r,t.cookie),W=ls(c).trim()===ls(t.state).trim();me(t.code,C,["--- Updating pinlog --------------------------",De(a,{asBot:t.asBot}),` \u2192 ${N}, ${l}`,"--- Current HEAD -----------------------------",...c.split(`
347
353
  `).map((O)=>` ${q(O)}`),"--- New HEAD (edited in place \u2014 silent) ------",...k.split(`
348
354
  `).map((O)=>` ${q(O)}`),"--- Log reply (in the thread \u2014 notifies) -----",...t.log.split(`
349
- `).map((O)=>` ${q(O)}`),"---------------------------------------------",...W?["\u26A0 The state text is unchanged \u2014 only the footer time moves. Replies are for real changes."]:[],...x?["\u26A0 Adopting: this message has no pinlog footer yet \u2014 it becomes a board now."]:[]])}let F=nn("edit");try{await Vt(e,o,s,k,t.cookie,!0,F.metadata)}catch(N){let W=N instanceof Error?N.message:String(N),O=/cant_update_message/.test(W)?`
350
- Only the HEAD's author can edit it${t.asBot?"":" \u2014 if the bot created this board, add --as-bot"}.`:"",v=go(N)?`\u2717 HEAD was NOT updated: ${ce(N)}${O}`:`\u26A0 UNKNOWN whether the HEAD was updated: ${ce(N)}
351
- Check it first: slack pinlog get ${l}${d}`;console.error(`${v}
352
- The log reply was NOT posted (a log line for a change the board may not show would be a lie).`),process.exit(1)}F.record({team:a?.team,channel:o,target:t.target,ts:s,text:k,asBot:t.asBot}),console.log(`\u2713 HEAD updated: ${l}`)}let p=nn("send"),D;try{D=await Yt(e,o,t.log,s,!1,t.cookie,!0,p.metadata)}catch(k){let x=go(k);console.error((x?`\u2717 Log reply was NOT posted: ${ce(k)}
353
- `:`\u26A0 UNKNOWN whether the log reply was posted: ${ce(k)}
355
+ `).map((O)=>` ${q(O)}`),"---------------------------------------------",...W?["\u26A0 The state text is unchanged \u2014 only the footer time moves. Replies are for real changes."]:[],...x?["\u26A0 Adopting: this message has no pinlog footer yet \u2014 it becomes a board now."]:[]])}let F=sn("edit");try{await Vt(e,o,s,k,t.cookie,!0,F.metadata)}catch(N){let W=N instanceof Error?N.message:String(N),O=/cant_update_message/.test(W)?`
356
+ Only the HEAD's author can edit it${t.asBot?"":" \u2014 if the bot created this board, add --as-bot"}.`:"",L=wo(N)?`\u2717 HEAD was NOT updated: ${ae(N)}${O}`:`\u26A0 UNKNOWN whether the HEAD was updated: ${ae(N)}
357
+ Check it first: slack pinlog get ${l}${d}`;console.error(`${L}
358
+ The log reply was NOT posted (a log line for a change the board may not show would be a lie).`),process.exit(1)}F.record({team:a?.team,channel:o,target:t.target,ts:s,text:k,asBot:t.asBot}),console.log(`\u2713 HEAD updated: ${l}`)}let p=sn("send"),D;try{D=await Yt(e,o,t.log,s,!1,t.cookie,!0,p.metadata)}catch(k){let x=wo(k);console.error((x?`\u2717 Log reply was NOT posted: ${ae(k)}
359
+ `:`\u26A0 UNKNOWN whether the log reply was posted: ${ae(k)}
354
360
  `)+(t.logOnly?"":` The HEAD IS updated \u2014 only the log line ${x?"is":"may be"} missing.
355
361
  `)+(x?"":` Check the thread first (retrying a reply that landed notifies everyone twice): slack pinlog get ${l}${d}
356
362
  `)+` Retry just the log line${x?"":" (only if it is not there)"}:
357
- ${h}`),process.exit(1)}if(p.record({team:a?.team,channel:o,target:t.target,ts:D,text:t.log,asBot:t.asBot}),console.log(`\u2713 Logged (ts: ${D})`),m)console.error(m)}function fd(e){return e.replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&")}function Bg(e){return Ei(new Date(Number(e.split(".")[0])*1000))}async function Mg(e,t,n,o){if(typeof t.user==="string"){let r=n.get(t.user);if(r!==void 0)return r;let i;try{i=await Ie(e,t.user,o)}catch{i=t.user}return n.set(t.user,i),i}let s=I(t.bot_profile);if(typeof s.name==="string")return s.name;return typeof t.username==="string"?t.username:"bot"}async function vg(e,t,n,o){let{channel:s,ts:r}=await Oi(e,t,n),i=[],c,a=0;do{let p=I(await pu(e,s,r,c,200,n));for(let k of X(p.messages).map(I)){if(String(k.ts)===r&&i.some((x)=>String(x.ts)===r))continue;i.push(k)}let D=I(p.response_metadata).next_cursor;c=typeof D==="string"&&D?D:void 0,a++}while(c&&a<50);let l=c===void 0,u=i.find((p)=>String(p.ts)===r);if(!u)console.error(`Error: no message at ts=${r} in ${s}.`),process.exit(1);let d=typeof u.text==="string"?u.text:"",f=i.filter((p)=>String(p.ts)!==r);if(o){console.log(JSON.stringify({id:Xe(s,r),isPinlog:xn(d),updated:Fi(d),complete:l,head:d,log:f.map((p)=>({ts:String(p.ts),user:p.user??null,text:typeof p.text==="string"?p.text:""}))}));return}if(!xn(d))console.error(`\u26A0 ${Xe(s,r)} has no "${as}" footer \u2014 showing it anyway, but it is not a pinlog HEAD.`);console.log(`=== HEAD ${Xe(s,r)} ===`);for(let p of fd(d).split(`
358
- `))console.log(q(p));let h=l?"":" \u2014 INCOMPLETE: the newest entries are not shown";console.log(`=== log (${f.length}${h}) ===`);let m=new Map;for(let p of f){let D=typeof p.text==="string"?p.text:"",k=q(await Mg(e,p,m,n)),x=fd(D).split(`
359
- `).map((E)=>q(E));console.log(`${Bg(String(p.ts))} @${k}: ${x[0]??""}`);for(let E of x.slice(1))console.log(` ${E}`)}}async function $d(e,t,n,o){let s=0,r,i=[];do{let c=I(await st(e,t,Math.min(200,n-s),void 0,r,o)),a=X(c.messages).map(I);s+=a.length;for(let u of a)if(typeof u.text==="string"&&xn(u.text))i.push(u);let l=I(c.response_metadata).next_cursor;r=typeof l==="string"&&l?l:void 0}while(r&&s<n);return{found:i,scanned:s}}function Ad(e){return q(cs(e).split(`
360
- `).find((t)=>t.trim())??"").slice(0,80)}async function Lg(e,t,n,o){let{ref:s,ts:r}=At(t);if(r||io(t))console.error(`Error: \`pinlog ls\` takes a channel. For one board: slack pinlog get ${Ft(t)}`),process.exit(2);let i=await he(e,s,o),{found:c,scanned:a}=await $d(e,i,n,o),l=await $t(e,i,s,o);if(c.length===0){console.log(`No pinlogs in the last ${a} messages of ${l}.${a>=n?` (Older ones: --limit ${n*2})`:""}`);return}for(let u of c){let d=String(u.ts),f=Xe(i,d),h=String(u.text),m=X(u.pinned_to).some((k)=>k===i)?"\uD83D\uDCCC":" ",p=Ad(h),D=typeof u.reply_count==="number"?u.reply_count:0;console.log(`${m} ${f} updated ${Fi(h)??"?"} log ${D}`),console.log(` ${p}`)}}async function jg(e,t,n){let{channel:o,ts:s}=await Oi(e,t,n);try{await li(e,o,s,n),console.log(`\u2713 Pinned ${Xe(o,s)}`)}catch(r){let i=r instanceof Error?r.message:String(r);if(/already_pinned/.test(i)){console.log(`\u2713 Already pinned: ${Xe(o,s)}`);return}console.error(`\u2717 NOT pinned: ${ce(r)}`),process.exit(1)}}async function Wg(e,t){let{ref:n,ts:o}=At(t.target);if(!o)console.error("Error: target must embed a message ts (e.g. #chan:2026-05-11T06:01:04.000100 or a Slack permalink URL)"),process.exit(2);let s=t.emoji.replace(/^:|:$/g,""),r;if(t.channelId)r=t.channelId;else r=await he(e,n,t.cookie);if(t.remove)await Zn(e,r,o,s,t.cookie),console.log(`\u2713 Removed :${s}: (ts: ${o})`);else await mn(e,r,o,s,t.cookie),console.log(`\u2713 Reacted :${s}: (ts: ${o})`)}async function Pi(e,t,n,o){if(!n||!t.startsWith("D"))return!1;try{let s=I(await Dn(e,t,o)),r=I(s.channel);return r.is_im===!0&&r.user===n}catch{return!1}}function Ug(e){let t=new Set;for(let n of e){if(typeof n.user==="string")t.add(n.user);if(typeof n.parent_user_id==="string")t.add(n.parent_user_id);for(let o of X(n.reply_users))if(typeof o==="string")t.add(o)}return t}async function Jg(e,t,n){if(!t.startsWith("D"))return;try{let o=I(I(await Dn(e,t,n)).channel);return o.is_im===!0&&typeof o.user==="string"?o.user:void 0}catch{return}}async function Kg(e,t){let{ref:n,threadTs:o}=Cn(t.target),s=t.cookie,r=ht(e,s),i;if(t.channelId)i=t.channelId;else if(t.userId)i=await ft(e,t.userId,s);else i=await he(e,n,s);if(!t.asBot&&await Pi(e,i,(await r())?.userId,s))console.error(`Warning: "${t.target}" is a DM to yourself \u2014 Slack will NOT notify you of your own message.
361
- `+` To reach yourself with a notification, send as the bot: slack send '${t.target}' '...' --as-bot`);let c=Ge(t.message);kt(c,t.allowUrlAdjacent);let a=c,l=null;if(t.mentions){l=await en(t.mentionToken??e,c,i,t.mentionCookie),a=l.text;for(let O of os(l.unresolved))console.error(`\u26A0 ${q(O)}`)}let u=[];if(l&&(l.resolved.length>0||l.unresolved.length>0)){u.push("--- Mentions ---------------------------------");for(let O of l.resolved)u.push(` \u2713 ${q(O.surface)} \u2192 @${q(O.display)} (${O.userId}) \u2014 will notify`);for(let O of l.unresolved){let v=O.reason==="ambiguous"?"ambiguous":O.reason==="unavailable"?"lookup unavailable":"no match";u.push(` \u26A0 ${q(O.surface)} \u2014 plain text, NOT notified (${v})`)}}let d="",f="?",h=[],m,p,D;if(o)try{let O=await qe(e,i,o,100,s);h=X(O.messages).map(I);let v=h[h.length-1];d=typeof v?.text==="string"?v.text:"",m=typeof v?.user==="string"?v.user:void 0,p=typeof v?.bot_id==="string"?v.bot_id:void 0,D=typeof v?.ts==="string"?v.ts:void 0}catch{}else try{let O=await st(e,i,1,void 0,void 0,s),v=X(O.messages).map(I),J=v.filter((_)=>_.subtype===void 0||_.subtype===null)[0];d=typeof J?.text==="string"?J.text:"",f=typeof J?.user==="string"?await Ie(e,J.user,s):typeof J?.username==="string"?J.username:"?";let Q=v[0];m=typeof Q?.user==="string"?Q.user:void 0,p=typeof Q?.bot_id==="string"?Q.bot_id:void 0,D=typeof Q?.ts==="string"?Q.ts:void 0}catch{}try{let O=o?Ug(h):new Set([await Jg(e,i,s)].filter((v)=>!!v));for(let v of await zu(t.mentionToken??e,a,t.mentionCookie)){if(O.has(v.userId))continue;console.error(`\u26A0 possible untagged mention: ${q(v.surface)} \u2014 @${q(v.display)} won't be notified (did you mean <@${v.userId}>?)`)}}catch{}if(process.env.SLACK_UNREPLIED_WARN!=="0"&&D&&(m||p))try{let O=await r();if(!!O&&(!!m&&!!O.userId&&O.userId===m||!!p&&!!O.botId&&O.botId===p)){let J=`slack edit "#${i}:${D}" "<\u65B0\u3057\u3044\u672C\u6587>" --channel-id ${i}`;try{let Q=await Vn(e,i,D,s);if(Q)J=`slack edit "${Q}" "<\u65B0\u3057\u3044\u672C\u6587>"`}catch{}console.error("\u26A0 \u76F8\u624B\u306F\u307E\u3060\u8FD4\u4FE1\u3057\u3066\u3044\u307E\u305B\u3093(\u6700\u5F8C\u306E\u30E1\u30C3\u30BB\u30FC\u30B8\u306F\u3042\u306A\u305F\u306E\u3082\u306E\u3067\u3059)\u3002"),console.error(" \u9023\u6295\u3092\u907F\u3051\u308B\u305F\u3081\u3001\u65B0\u898F\u9001\u4FE1\u3067\u306A\u304F\u76F4\u524D\u306E\u30E1\u30C3\u30BB\u30FC\u30B8\u306E edit \u3092\u691C\u8A0E\u3057\u3066\u304F\u3060\u3055\u3044:"),console.error(` ${J}`),console.error(" \u3053\u306E\u307E\u307E\u9001\u4FE1\u3059\u308B\u5834\u5408\u306F --code=XXXX \u3067\u78BA\u5B9A\u3002")}}catch{}if(o&&h.length){let O={sim:0,msg:null};for(let v of h){let J=typeof v.text==="string"?v.text:"";if(!J)continue;let Q=Ig(a,J);if(Q>O.sim)O={sim:Q,msg:v}}if(O.msg&&O.sim>=0.82){let v=Math.round(O.sim*100);console.error(`\u26A0 possible duplicate: ${v}% similar to an existing thread message \u2014 ${await Ai(e,O.msg,60,s)}`)}}let k=await r(),x=await wo(e,i,s),E=De(i,o??"",d,a,k?.userId??"");if(t.code!==E){let O=await $t(e,i,n,s),v=we(k,{asBot:t.asBot});if(o){let J=await Tg(e,o,h,s),Q=h.slice(-3),_=Q.length?await Promise.all(Q.map(async(C)=>` ${await Ai(e,C,60,s)}`)):[" (thread context unavailable)"];ye(t.code,E,["--- Recent messages in thread ----------------",..._,...u,"--- Sending ----------------------------------",v,` \u2192 ${O} thread of ${J} \u2014 THREAD REPLY`,` Message: ${a}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"],x)}else ye(t.code,E,["--- Last message in channel ------------------",` ${f}: ${rs(d.split(`
362
- `)[0]??"").slice(0,100)}`,...u,"--- Sending ----------------------------------",v,` \u2192 ${O} \u2014 NEW top-level message`,` Message: ${a}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"],x)}let F=nn("send"),N=await Yt(e,i,a,o,t.broadcast,s,void 0,F.metadata),W="";try{W=await Vn(e,i,N,s)}catch{}if(F.record({team:(await r())?.team,channel:i,target:t.target,ts:N,threadTs:o,permalink:W,text:a,asBot:t.asBot}),W)console.log(`\u2713 Sent: ${W}`);else console.log(`\u2713 Sent (ts: ${N})`);if(t.asBot&&i.startsWith("D"))try{let O=await Ls(e);if(!O.ok)for(let v of js(O,!0))console.error(v);else{let v=O.appId?`https://api.slack.com/apps/${O.appId}`:"https://api.slack.com/apps";console.error(`Note: if ${t.target} can't reply (app messaging may be off), enable Messages Tab: ${v} \u2192 App Home.`)}}catch{}}var Hg=2,_e=3,zg=4,qg=5,Gg=1.618033988749895,Xg=1000,Yg=5000,pd=8,Vg=(e)=>new Promise((t)=>setTimeout(t,e)),Zg=new Set(["thread_broadcast"]),Qg=/(?<![A-Za-z0-9._@<-])@(here|channel|everyone)(?![A-Za-z0-9._-])/giu;function mo(e){let t=new Set;return{text:e.replace(Qg,(o,s)=>{let r=s.toLowerCase();return t.add(r),`<!${r}>`}),kinds:t}}async function bo(e,t,n){if(!t.startsWith("D"))return;try{let o=I(await Dn(e,t,n)),s=I(o.channel);return s.is_im===!0&&typeof s.user==="string"?s.user:void 0}catch{return}}async function Td(e,t){let{channelId:n,ts:o,question:s,reactable:r,threadOnly:i,audience:c,broadcast:a,cookie:l,timeout:u,shown:d}=t,{askerUserId:f,askerBotId:h}=t,m=(_)=>typeof _==="string"&&!!_&&_!==f&&(a||c.has(_)),p,D="";function k(_){let C=X(_.reactions).map(I),T=[];for(let A=0;A<r.length;A++){let B=C.find((Y)=>Y.name===ze[A].name),Z=B?X(B.users).filter(m):[];if(Z.length)T.push({index:A,users:Z})}return T}async function x(_,C){let T=typeof _.text==="string"?_.text:"";if(!T)return;let A=Jr(T,C);if(A===T)return;try{await Vt(e,n,o,A,l,!0)}catch(B){console.error(` (\u8CEA\u554F\u6587\u306B\u6CE8\u610F\u66F8\u304D\u3092\u5165\u308C\u3089\u308C\u307E\u305B\u3093\u3067\u3057\u305F: ${B instanceof Error?B.message:String(B)})`)}}async function E(_){let C=k(_);if(C.length<=1&&Ur(typeof _.text==="string"?_.text:"").length)await x(_,[]);if(!C.length)return null;if(C.length===1){let{index:B,users:Z}=C[0];return{answer:r[B],how:`\u30EA\u30A2\u30AF\u30B7\u30E7\u30F3 ${ze[B].glyph}`,who:Z[0]}}let T=C.map((B)=>ze[B.index].glyph).join(" / ");console.error(` (${T} \u304C\u540C\u6642\u306B\u9078\u3070\u308C\u3066\u3044\u307E\u3059\u30021 \u3064\u306B\u7D5E\u3063\u3066\u3082\u3089\u3046\u307E\u3067\u5F85\u3061\u307E\u3059)`);let A=[...new Set(C.flatMap((B)=>B.users))].sort();return await x(_,A),null}let F=[...r,...t.overflow];function N(_,C=1/0){let T=[..._].sort((A,B)=>Number(A.ts)-Number(B.ts));for(let A of T){if(!(Number(A.ts)>Number(o)))continue;if(t.after&&!(Number(A.ts)>Number(t.after)))continue;if(!m(A.user))continue;if(typeof A.subtype==="string"&&!Zg.has(A.subtype))continue;if(Number(A.ts)>=C)break;let B=typeof A.text==="string"?A.text.trim():"";if(!B)continue;if(!F.length)return{answer:B,how:"\u8FD4\u4FE1",who:A.user};let Z=El(B,F);if(Z.kind==="chosen")return{answer:F[Z.index-1],how:`\u8FD4\u4FE1 (${Z.index})`,who:A.user};let Y=Z.kind==="ambiguous";if(!p||p.ambiguous&&!Y||p.ambiguous===Y&&Number(A.ts)<Number(p.ts))p={text:B,who:typeof A.user==="string"?A.user:"",ts:String(A.ts),ambiguous:Y}}return null}async function W(){if(p=void 0,t.threadParentTs){let A=I(await qe(e,n,t.threadParentTs,100,l)),B=X(A.messages).map(I),Z=B.find((Y)=>Y.ts===o);if(Z){let Y=await E(Z);if(Y)return Y}return N(B)}let _=I(await st(e,n,30,o,void 0,l,!0)),C=X(_.messages).map(I),T=C.find((A)=>A.ts===o);if(T){let A=await E(T);if(A)return A}if(!i){let A=C.filter((Z)=>Number(Z.ts)>Number(o)&&(h&&Z.bot_id===h||f&&Z.user===f)).reduce((Z,Y)=>Math.min(Z,Number(Y.ts)),1/0),B=N(C,A);if(B)return B}if(T&&Number(T.reply_count)>0){let A=I(await qe(e,n,o,30,l)),B=N(X(A.messages).map(I));if(B)return B}return null}async function O(_){for(let T=0;T<r.length;T++)try{await Zn(e,n,o,ze[T].name,l)}catch{}let C="";if(_.who)try{C=await Ie(e,_.who,l)}catch{C=_.who}if(C)console.error(` \u56DE\u7B54\u8005: ${q(C)}`);try{await Vt(e,n,o,kl(s,_,C),l,!0);try{await mn(e,n,o,Kr,l),await Zn(e,n,o,Ys,l)}catch{}}catch(T){console.error(` (\u5143\u30E1\u30C3\u30BB\u30FC\u30B8\u306E\u66F4\u65B0\u306B\u5931\u6557: ${T instanceof Error?T.message:String(T)})`)}}let v=Date.now()+u*1000,J=0,Q=Xg;for(;;){let _=null;try{_=await W(),J=0}catch(C){if(J++,J>=pd)console.error(`Error: Slack \u3078\u306E\u554F\u3044\u5408\u308F\u305B\u306B ${J} \u56DE\u9023\u7D9A\u3067\u5931\u6557\u3057\u307E\u3057\u305F: ${C instanceof Error?C.message:String(C)}`),process.exit(_e);console.error(` (Slack \u30A8\u30E9\u30FC ${J}/${pd}, \u518D\u8A66\u884C\u3057\u307E\u3059: ${C instanceof Error?C.message:String(C)})`)}if(_)await O(_),console.log(_.answer),process.exit(0);if(p&&!p.ambiguous){let C=p.who;try{if(C)C=await Ie(e,C,l)}catch{}console.error(` (${q(C)} \u304C\u9078\u629E\u80A2\u5916\u306E\u8FD4\u4FE1\u3092\u3057\u307E\u3057\u305F \u2014 \u6C7A\u5B9A\u3067\u306F\u3042\u308A\u307E\u305B\u3093\u3002\u672C\u6587\u3092 stdout \u306B\u51FA\u3057\u307E\u3059)`),console.error(` \u9078\u629E\u80A2: ${F.map((T,A)=>`${A+1}. ${q(qt(T))}`).join(" ")}`),console.error(` ${d}`),console.error(` \u3053\u306E\u8FD4\u4FE1\u306E\u5F8C\u3092\u5F85\u3064: ${lo(d,t.asBot,p.ts)}`),console.log(p.text),process.exit(qg)}if(p&&p.ts!==D){D=p.ts;let C=p.who;try{if(C)C=await Ie(e,C,l)}catch{}console.error(` (${q(C)} \u306E\u8FD4\u4FE1\u306F\u8907\u6570\u306E\u9078\u629E\u80A2\u306B\u4E00\u81F4\u3057\u307E\u3059\u30021 \u3064\u306B\u7D5E\u3063\u3066\u3082\u3089\u3046\u307E\u3067\u5F85\u3061\u307E\u3059)`),console.error(` \u300C${q(p.text)}\u300D`)}if(Date.now()>=v)break;await Vg(Math.min(Q,Math.max(0,v-Date.now()))),Q=Math.min(Q*Gg,Yg)}if(p)console.error("Error: \u8FD4\u4FE1\u306F\u3042\u308A\u307E\u3057\u305F\u304C\u3001\u8907\u6570\u306E\u9078\u629E\u80A2\u306B\u4E00\u81F4\u3059\u308B\u305F\u3081\u78BA\u5B9A\u3067\u304D\u307E\u305B\u3093 (\u30E1\u30C3\u30BB\u30FC\u30B8\u306F\u305D\u306E\u307E\u307E\u6B8B\u3063\u3066\u3044\u307E\u3059)"),console.error(` \u8FD4\u4FE1: \u300C${q(p.text)}\u300D`),console.error(` \u9078\u629E\u80A2: ${F.map((_,C)=>`${C+1}. ${q(qt(_))}`).join(" ")}`),console.error(` ${d}`),console.error(` \u8FD4\u7B54\u3057\u3066\u304B\u3089\u56DE\u53CE\u3059\u308B: ${lo(d,t.asBot,t.after)}`),process.exit(zg);if(u===0)console.error(`\u307E\u3060\u56DE\u7B54\u304C\u3042\u308A\u307E\u305B\u3093: ${d}`);else console.error(`Error: ${u}s \u4EE5\u5185\u306B\u56DE\u7B54\u304C\u3042\u308A\u307E\u305B\u3093\u3067\u3057\u305F (\u30E1\u30C3\u30BB\u30FC\u30B8\u306F\u305D\u306E\u307E\u307E\u6B8B\u3063\u3066\u3044\u307E\u3059)`),console.error(` ${d}`),console.error(` \u3042\u3068\u3067\u56DE\u53CE\u3059\u308B: ${lo(d,t.asBot,t.after)}`);process.exit(Hg)}function lo(e,t,n){return`slack ask --waitFor='${e}'${t?" --as-bot":""}${n?` --after=${n}`:""}`}async function em(e,t){let{ref:n,threadTs:o}=Cn(t.target,!1),s=t.cookie,r=ht(e,s),i;if(t.channelId)i=t.channelId;else if(t.userId)i=await ft(e,t.userId,s);else i=await he(e,n,s);let c=(await r())?.userId??"",a=await bo(e,i,s);if(!t.asBot&&!!c&&a===c)console.error(`Warning: "${t.target}" is a DM to yourself \u2014 Slack will NOT notify you of your own message.
363
- `+` To reach yourself with a notification, ask as the bot: slack ask '${t.target}' '...' --as-bot`);let l=mo(Ge(t.question)),u=mo(Ge(t.body??"")),d=new Set([...l.kinds,...u.kinds]),f=t.mentionToken??e,h=await en(f,l.text,i,t.mentionCookie),m=u.text?await en(f,u.text,i,t.mentionCookie):{text:"",resolved:[],unresolved:[]},p=h.text,D=m.text,k=[...h.resolved,...m.resolved],x=[...h.unresolved,...m.unresolved];for(let R of os(x))console.error(`\u26A0 ${q(R)}`);let E=d.size>0,F=new Set(k.map((R)=>R.userId).filter((R)=>R!==c)),N=new Map(k.map((R)=>[R.userId,R.display])),W;if(E)W=`anyone in ${n} (${[...d].map((R)=>`@${R}`).join(", ")})`;else{if(!F.size&&a&&a!==c)F.add(a),N.set(a,await Ie(e,a,s));if(!F.size)console.error("Error: `ask` will not post a question nobody is addressed to \u2014 no one is tagged.\n"+(x.length?` (${x.map((R)=>q(R.surface)).join(", ")} matched no one, so it names nobody.)
363
+ ${h}`),process.exit(1)}if(p.record({team:a?.team,channel:o,target:t.target,ts:D,text:t.log,asBot:t.asBot}),console.log(`\u2713 Logged (ts: ${D})`),m)console.error(m)}function Sd(e){return e.replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&")}function Zg(e){return Fi(new Date(Number(e.split(".")[0])*1000))}async function Qg(e,t,n,o){if(typeof t.user==="string"){let r=n.get(t.user);if(r!==void 0)return r;let i;try{i=await Ae(e,t.user,o)}catch{i=t.user}return n.set(t.user,i),i}let s=T(t.bot_profile);if(typeof s.name==="string")return s.name;return typeof t.username==="string"?t.username:"bot"}async function em(e,t,n,o){let{channel:s,ts:r}=await Bi(e,t,n),i=[],c,a=0;do{let p=T(await yu(e,s,r,c,200,n));for(let k of X(p.messages).map(T)){if(String(k.ts)===r&&i.some((x)=>String(x.ts)===r))continue;i.push(k)}let D=T(p.response_metadata).next_cursor;c=typeof D==="string"&&D?D:void 0,a++}while(c&&a<50);let l=c===void 0,u=i.find((p)=>String(p.ts)===r);if(!u)console.error(`Error: no message at ts=${r} in ${s}.`),process.exit(1);let d=typeof u.text==="string"?u.text:"",f=i.filter((p)=>String(p.ts)!==r);if(o){console.log(JSON.stringify({id:Ye(s,r),isPinlog:En(d),updated:Ti(d),complete:l,head:d,log:f.map((p)=>({ts:String(p.ts),user:p.user??null,text:typeof p.text==="string"?p.text:""}))}));return}if(!En(d))console.error(`\u26A0 ${Ye(s,r)} has no "${cs}" footer \u2014 showing it anyway, but it is not a pinlog HEAD.`);console.log(`=== HEAD ${Ye(s,r)} ===`);for(let p of Sd(d).split(`
364
+ `))console.log(q(p));let h=l?"":" \u2014 INCOMPLETE: the newest entries are not shown";console.log(`=== log (${f.length}${h}) ===`);let m=new Map;for(let p of f){let D=typeof p.text==="string"?p.text:"",k=q(await Qg(e,p,m,n)),x=Sd(D).split(`
365
+ `).map((C)=>q(C));console.log(`${Zg(String(p.ts))} @${k}: ${x[0]??""}`);for(let C of x.slice(1))console.log(` ${C}`)}}async function jd(e,t,n,o){let s=0,r,i=[];do{let c=T(await ot(e,t,Math.min(200,n-s),void 0,r,o)),a=X(c.messages).map(T);s+=a.length;for(let u of a)if(typeof u.text==="string"&&En(u.text))i.push(u);let l=T(c.response_metadata).next_cursor;r=typeof l==="string"&&l?l:void 0}while(r&&s<n);return{found:i,scanned:s}}function Wd(e){return q(ls(e).split(`
366
+ `).find((t)=>t.trim())??"").slice(0,80)}async function tm(e,t,n,o){let{ref:s,ts:r}=Tt(t);if(r||uo(t))console.error(`Error: \`pinlog ls\` takes a channel. For one board: slack pinlog get ${$t(t)}`),process.exit(2);let i=await ue(e,s,o),{found:c,scanned:a}=await jd(e,i,n,o),l=await At(e,i,s,o);if(c.length===0){console.log(`No pinlogs in the last ${a} messages of ${l}.${a>=n?` (Older ones: --limit ${n*2})`:""}`);return}for(let u of c){let d=String(u.ts),f=Ye(i,d),h=String(u.text),m=X(u.pinned_to).some((k)=>k===i)?"\uD83D\uDCCC":" ",p=Wd(h),D=typeof u.reply_count==="number"?u.reply_count:0;console.log(`${m} ${f} updated ${Ti(h)??"?"} log ${D}`),console.log(` ${p}`)}}async function nm(e,t,n){let{channel:o,ts:s}=await Bi(e,t,n);try{await pi(e,o,s,n),console.log(`\u2713 Pinned ${Ye(o,s)}`)}catch(r){let i=r instanceof Error?r.message:String(r);if(/already_pinned/.test(i)){console.log(`\u2713 Already pinned: ${Ye(o,s)}`);return}console.error(`\u2717 NOT pinned: ${ae(r)}`),process.exit(1)}}async function sm(e,t){let{ref:n,ts:o}=Tt(t.target);if(!o)console.error("Error: target must embed a message ts (e.g. #chan:2026-05-11T06:01:04.000100 or a Slack permalink URL)"),process.exit(2);let s=t.emoji.replace(/^:|:$/g,""),r;if(t.channelId)r=t.channelId;else r=await ue(e,n,t.cookie);if(t.remove)await Zn(e,r,o,s,t.cookie),console.log(`\u2713 Removed :${s}: (ts: ${o})`);else await yn(e,r,o,s,t.cookie),console.log(`\u2713 Reacted :${s}: (ts: ${o})`)}async function vi(e,t,n,o){if(!n||!t.startsWith("D"))return!1;try{let s=T(await Qt(e,t,o)),r=T(s.channel);return r.is_im===!0&&r.user===n}catch{return!1}}function om(e){let t=new Set;for(let n of e){if(typeof n.user==="string")t.add(n.user);if(typeof n.parent_user_id==="string")t.add(n.parent_user_id);for(let o of X(n.reply_users))if(typeof o==="string")t.add(o)}return t}async function rm(e,t,n){if(!t.startsWith("D"))return;try{let o=T(T(await Qt(e,t,n)).channel);return o.is_im===!0&&typeof o.user==="string"?o.user:void 0}catch{return}}async function im(e,t){let{ref:n,threadTs:o}=Cn(t.target),s=t.cookie,r=gt(e,s),i;if(t.channelId)i=t.channelId;else if(t.userId)i=await pt(e,t.userId,s);else i=await ue(e,n,s);if(!t.asBot&&await vi(e,i,(await r())?.userId,s))console.error(`Warning: "${t.target}" is a DM to yourself \u2014 Slack will NOT notify you of your own message.
367
+ `+` To reach yourself with a notification, send as the bot: slack send '${t.target}' '...' --as-bot`);let c=Xe(t.message);ve(c,t.allowUrlAdjacent);let a=c,l=null;if(t.mentions){l=await tn(t.mentionToken??e,c,i,t.mentionCookie),a=l.text;for(let O of rs(l.unresolved))console.error(`\u26A0 ${q(O)}`)}let u=[];if(l&&(l.resolved.length>0||l.unresolved.length>0)){u.push("--- Mentions ---------------------------------");for(let O of l.resolved)u.push(` \u2713 ${q(O.surface)} \u2192 @${q(O.display)} (${O.userId}) \u2014 will notify`);for(let O of l.unresolved){let L=O.reason==="ambiguous"?"ambiguous":O.reason==="unavailable"?"lookup unavailable":"no match";u.push(` \u26A0 ${q(O.surface)} \u2014 plain text, NOT notified (${L})`)}}let d="",f="?",h=[],m,p,D;if(o)try{let O=await Me(e,i,o,100,s);h=X(O.messages).map(T);let L=h[h.length-1];d=typeof L?.text==="string"?L.text:"",m=typeof L?.user==="string"?L.user:void 0,p=typeof L?.bot_id==="string"?L.bot_id:void 0,D=typeof L?.ts==="string"?L.ts:void 0}catch{}else try{let O=await ot(e,i,1,void 0,void 0,s),L=X(O.messages).map(T),J=L.filter((_)=>_.subtype===void 0||_.subtype===null)[0];d=typeof J?.text==="string"?J.text:"",f=typeof J?.user==="string"?await Ae(e,J.user,s):typeof J?.username==="string"?J.username:"?";let Q=L[0];m=typeof Q?.user==="string"?Q.user:void 0,p=typeof Q?.bot_id==="string"?Q.bot_id:void 0,D=typeof Q?.ts==="string"?Q.ts:void 0}catch{}try{let O=o?om(h):new Set([await rm(e,i,s)].filter((L)=>!!L));for(let L of await rd(t.mentionToken??e,a,t.mentionCookie)){if(O.has(L.userId))continue;console.error(`\u26A0 possible untagged mention: ${q(L.surface)} \u2014 @${q(L.display)} won't be notified (did you mean <@${L.userId}>?)`)}}catch{}if(process.env.SLACK_UNREPLIED_WARN!=="0"&&D&&(m||p))try{let O=await r();if(!!O&&(!!m&&!!O.userId&&O.userId===m||!!p&&!!O.botId&&O.botId===p)){let J=`slack edit "#${i}:${D}" "<\u65B0\u3057\u3044\u672C\u6587>" --channel-id ${i}`;try{let Q=await Vn(e,i,D,s);if(Q)J=`slack edit "${Q}" "<\u65B0\u3057\u3044\u672C\u6587>"`}catch{}console.error("\u26A0 \u76F8\u624B\u306F\u307E\u3060\u8FD4\u4FE1\u3057\u3066\u3044\u307E\u305B\u3093(\u6700\u5F8C\u306E\u30E1\u30C3\u30BB\u30FC\u30B8\u306F\u3042\u306A\u305F\u306E\u3082\u306E\u3067\u3059)\u3002"),console.error(" \u9023\u6295\u3092\u907F\u3051\u308B\u305F\u3081\u3001\u65B0\u898F\u9001\u4FE1\u3067\u306A\u304F\u76F4\u524D\u306E\u30E1\u30C3\u30BB\u30FC\u30B8\u306E edit \u3092\u691C\u8A0E\u3057\u3066\u304F\u3060\u3055\u3044:"),console.error(` ${J}`),console.error(" \u3053\u306E\u307E\u307E\u9001\u4FE1\u3059\u308B\u5834\u5408\u306F --code=XXXX \u3067\u78BA\u5B9A\u3002")}}catch{}if(o&&h.length){let O={sim:0,msg:null};for(let L of h){let J=typeof L.text==="string"?L.text:"";if(!J)continue;let Q=qg(a,J);if(Q>O.sim)O={sim:Q,msg:L}}if(O.msg&&O.sim>=0.82){let L=Math.round(O.sim*100);console.error(`\u26A0 possible duplicate: ${L}% similar to an existing thread message \u2014 ${await Oi(e,O.msg,60,s)}`)}}let k=await r(),x=await Eo(e,i,s),C=ge(i,o??"",d,a,k?.userId??"");if(t.code!==C){let O=await At(e,i,n,s),L=De(k,{asBot:t.asBot});if(o){let J=await zg(e,o,h,s),Q=h.slice(-3),_=Q.length?await Promise.all(Q.map(async(E)=>` ${await Oi(e,E,60,s)}`)):[" (thread context unavailable)"];me(t.code,C,["--- Recent messages in thread ----------------",..._,...u,"--- Sending ----------------------------------",L,` \u2192 ${O} thread of ${J} \u2014 THREAD REPLY`,` Message: ${a}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"],x)}else me(t.code,C,["--- Last message in channel ------------------",` ${f}: ${is(d.split(`
368
+ `)[0]??"").slice(0,100)}`,...u,"--- Sending ----------------------------------",L,` \u2192 ${O} \u2014 NEW top-level message`,` Message: ${a}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"],x)}let F=sn("send"),N=await Yt(e,i,a,o,t.broadcast,s,void 0,F.metadata),W="";try{W=await Vn(e,i,N,s)}catch{}if(F.record({team:(await r())?.team,channel:i,target:t.target,ts:N,threadTs:o,permalink:W,text:a,asBot:t.asBot}),W)console.log(`\u2713 Sent: ${W}`);else console.log(`\u2713 Sent (ts: ${N})`);if(t.asBot&&i.startsWith("D"))try{let O=await Ws(e);if(!O.ok)for(let L of Us(O,!0))console.error(L);else{let L=O.appId?`https://api.slack.com/apps/${O.appId}`:"https://api.slack.com/apps";console.error(`Note: if ${t.target} can't reply (app messaging may be off), enable Messages Tab: ${L} \u2192 App Home.`)}}catch{}}var am=2,_e=3,cm=4,lm=5,um=1.618033988749895,dm=1000,fm=5000,_d=8,pm=(e)=>new Promise((t)=>setTimeout(t,e)),hm=new Set(["thread_broadcast"]),gm=/(?<![A-Za-z0-9._@<-])@(here|channel|everyone)(?![A-Za-z0-9._-])/giu;function bo(e){let t=new Set;return{text:e.replace(gm,(o,s)=>{let r=s.toLowerCase();return t.add(r),`<!${r}>`}),kinds:t}}async function Co(e,t,n){if(!t.startsWith("D"))return;try{let o=T(await Qt(e,t,n)),s=T(o.channel);return s.is_im===!0&&typeof s.user==="string"?s.user:void 0}catch{return}}async function Ud(e,t){let{channelId:n,ts:o,question:s,reactable:r,threadOnly:i,audience:c,broadcast:a,cookie:l,timeout:u,shown:d}=t,{askerUserId:f,askerBotId:h}=t,m=(_)=>typeof _==="string"&&!!_&&_!==f&&(a||c.has(_)),p,D="";function k(_){let E=X(_.reactions).map(T),I=[];for(let A=0;A<r.length;A++){let B=E.find((Y)=>Y.name===Ge[A].name),Z=B?X(B.users).filter(m):[];if(Z.length)I.push({index:A,users:Z})}return I}async function x(_,E){let I=typeof _.text==="string"?_.text:"";if(!I)return;let A=qr(I,E);if(A===I)return;try{await Vt(e,n,o,A,l,!0)}catch(B){console.error(` (\u8CEA\u554F\u6587\u306B\u6CE8\u610F\u66F8\u304D\u3092\u5165\u308C\u3089\u308C\u307E\u305B\u3093\u3067\u3057\u305F: ${B instanceof Error?B.message:String(B)})`)}}async function C(_){let E=k(_);if(E.length<=1&&zr(typeof _.text==="string"?_.text:"").length)await x(_,[]);if(!E.length)return null;if(E.length===1){let{index:B,users:Z}=E[0];return{answer:r[B],how:`\u30EA\u30A2\u30AF\u30B7\u30E7\u30F3 ${Ge[B].glyph}`,who:Z[0]}}let I=E.map((B)=>Ge[B.index].glyph).join(" / ");console.error(` (${I} \u304C\u540C\u6642\u306B\u9078\u3070\u308C\u3066\u3044\u307E\u3059\u30021 \u3064\u306B\u7D5E\u3063\u3066\u3082\u3089\u3046\u307E\u3067\u5F85\u3061\u307E\u3059)`);let A=[...new Set(E.flatMap((B)=>B.users))].sort();return await x(_,A),null}let F=[...r,...t.overflow];function N(_,E=1/0){let I=[..._].sort((A,B)=>Number(A.ts)-Number(B.ts));for(let A of I){if(!(Number(A.ts)>Number(o)))continue;if(t.after&&!(Number(A.ts)>Number(t.after)))continue;if(!m(A.user))continue;if(typeof A.subtype==="string"&&!hm.has(A.subtype))continue;if(Number(A.ts)>=E)break;let B=typeof A.text==="string"?A.text.trim():"";if(!B)continue;if(!F.length)return{answer:B,how:"\u8FD4\u4FE1",who:A.user};let Z=Al(B,F);if(Z.kind==="chosen")return{answer:F[Z.index-1],how:`\u8FD4\u4FE1 (${Z.index})`,who:A.user};let Y=Z.kind==="ambiguous";if(!p||p.ambiguous&&!Y||p.ambiguous===Y&&Number(A.ts)<Number(p.ts))p={text:B,who:typeof A.user==="string"?A.user:"",ts:String(A.ts),ambiguous:Y}}return null}async function W(){if(p=void 0,t.threadParentTs){let A=T(await Me(e,n,t.threadParentTs,100,l)),B=X(A.messages).map(T),Z=B.find((Y)=>Y.ts===o);if(Z){let Y=await C(Z);if(Y)return Y}return N(B)}let _=T(await ot(e,n,30,o,void 0,l,!0)),E=X(_.messages).map(T),I=E.find((A)=>A.ts===o);if(I){let A=await C(I);if(A)return A}if(!i){let A=E.filter((Z)=>Number(Z.ts)>Number(o)&&(h&&Z.bot_id===h||f&&Z.user===f)).reduce((Z,Y)=>Math.min(Z,Number(Y.ts)),1/0),B=N(E,A);if(B)return B}if(I&&Number(I.reply_count)>0){let A=T(await Me(e,n,o,30,l)),B=N(X(A.messages).map(T));if(B)return B}return null}async function O(_){for(let I=0;I<r.length;I++)try{await Zn(e,n,o,Ge[I].name,l)}catch{}let E="";if(_.who)try{E=await Ae(e,_.who,l)}catch{E=_.who}if(E)console.error(` \u56DE\u7B54\u8005: ${q(E)}`);try{await Vt(e,n,o,_l(s,_,E),l,!0);try{await yn(e,n,o,Gr,l),await Zn(e,n,o,Zs,l)}catch{}}catch(I){console.error(` (\u5143\u30E1\u30C3\u30BB\u30FC\u30B8\u306E\u66F4\u65B0\u306B\u5931\u6557: ${I instanceof Error?I.message:String(I)})`)}}let L=Date.now()+u*1000,J=0,Q=dm;for(;;){let _=null;try{_=await W(),J=0}catch(E){if(J++,J>=_d)console.error(`Error: Slack \u3078\u306E\u554F\u3044\u5408\u308F\u305B\u306B ${J} \u56DE\u9023\u7D9A\u3067\u5931\u6557\u3057\u307E\u3057\u305F: ${E instanceof Error?E.message:String(E)}`),process.exit(_e);console.error(` (Slack \u30A8\u30E9\u30FC ${J}/${_d}, \u518D\u8A66\u884C\u3057\u307E\u3059: ${E instanceof Error?E.message:String(E)})`)}if(_)await O(_),console.log(_.answer),process.exit(0);if(p&&!p.ambiguous){let E=p.who;try{if(E)E=await Ae(e,E,l)}catch{}console.error(` (${q(E)} \u304C\u9078\u629E\u80A2\u5916\u306E\u8FD4\u4FE1\u3092\u3057\u307E\u3057\u305F \u2014 \u6C7A\u5B9A\u3067\u306F\u3042\u308A\u307E\u305B\u3093\u3002\u672C\u6587\u3092 stdout \u306B\u51FA\u3057\u307E\u3059)`),console.error(` \u9078\u629E\u80A2: ${F.map((I,A)=>`${A+1}. ${q(Gt(I))}`).join(" ")}`),console.error(` ${d}`),console.error(` \u3053\u306E\u8FD4\u4FE1\u306E\u5F8C\u3092\u5F85\u3064: ${ho(d,t.asBot,p.ts)}`),console.log(p.text),process.exit(lm)}if(p&&p.ts!==D){D=p.ts;let E=p.who;try{if(E)E=await Ae(e,E,l)}catch{}console.error(` (${q(E)} \u306E\u8FD4\u4FE1\u306F\u8907\u6570\u306E\u9078\u629E\u80A2\u306B\u4E00\u81F4\u3057\u307E\u3059\u30021 \u3064\u306B\u7D5E\u3063\u3066\u3082\u3089\u3046\u307E\u3067\u5F85\u3061\u307E\u3059)`),console.error(` \u300C${q(p.text)}\u300D`)}if(Date.now()>=L)break;await pm(Math.min(Q,Math.max(0,L-Date.now()))),Q=Math.min(Q*um,fm)}if(p)console.error("Error: \u8FD4\u4FE1\u306F\u3042\u308A\u307E\u3057\u305F\u304C\u3001\u8907\u6570\u306E\u9078\u629E\u80A2\u306B\u4E00\u81F4\u3059\u308B\u305F\u3081\u78BA\u5B9A\u3067\u304D\u307E\u305B\u3093 (\u30E1\u30C3\u30BB\u30FC\u30B8\u306F\u305D\u306E\u307E\u307E\u6B8B\u3063\u3066\u3044\u307E\u3059)"),console.error(` \u8FD4\u4FE1: \u300C${q(p.text)}\u300D`),console.error(` \u9078\u629E\u80A2: ${F.map((_,E)=>`${E+1}. ${q(Gt(_))}`).join(" ")}`),console.error(` ${d}`),console.error(` \u8FD4\u7B54\u3057\u3066\u304B\u3089\u56DE\u53CE\u3059\u308B: ${ho(d,t.asBot,t.after)}`),process.exit(cm);if(u===0)console.error(`\u307E\u3060\u56DE\u7B54\u304C\u3042\u308A\u307E\u305B\u3093: ${d}`);else console.error(`Error: ${u}s \u4EE5\u5185\u306B\u56DE\u7B54\u304C\u3042\u308A\u307E\u305B\u3093\u3067\u3057\u305F (\u30E1\u30C3\u30BB\u30FC\u30B8\u306F\u305D\u306E\u307E\u307E\u6B8B\u3063\u3066\u3044\u307E\u3059)`),console.error(` ${d}`),console.error(` \u3042\u3068\u3067\u56DE\u53CE\u3059\u308B: ${ho(d,t.asBot,t.after)}`);process.exit(am)}function ho(e,t,n){return`slack ask --waitFor='${e}'${t?" --as-bot":""}${n?` --after=${n}`:""}`}async function mm(e,t){let{ref:n,threadTs:o}=Cn(t.target,!1),s=t.cookie,r=gt(e,s),i;if(t.channelId)i=t.channelId;else if(t.userId)i=await pt(e,t.userId,s);else i=await ue(e,n,s);let c=(await r())?.userId??"",a=await Co(e,i,s);if(!t.asBot&&!!c&&a===c)console.error(`Warning: "${t.target}" is a DM to yourself \u2014 Slack will NOT notify you of your own message.
369
+ `+` To reach yourself with a notification, ask as the bot: slack ask '${t.target}' '...' --as-bot`);let l=bo(Xe(t.question)),u=bo(Xe(t.body??"")),d=new Set([...l.kinds,...u.kinds]),f=t.mentionToken??e,h=await tn(f,l.text,i,t.mentionCookie),m=u.text?await tn(f,u.text,i,t.mentionCookie):{text:"",resolved:[],unresolved:[]},p=h.text,D=m.text,k=[...h.resolved,...m.resolved],x=[...h.unresolved,...m.unresolved];for(let R of rs(x))console.error(`\u26A0 ${q(R)}`);let C=d.size>0,F=new Set(k.map((R)=>R.userId).filter((R)=>R!==c)),N=new Map(k.map((R)=>[R.userId,R.display])),W;if(C)W=`anyone in ${n} (${[...d].map((R)=>`@${R}`).join(", ")})`;else{if(!F.size&&a&&a!==c)F.add(a),N.set(a,await Ae(e,a,s));if(!F.size)console.error("Error: `ask` will not post a question nobody is addressed to \u2014 no one is tagged.\n"+(x.length?` (${x.map((R)=>q(R.surface)).join(", ")} matched no one, so it names nobody.)
364
370
  `:"")+` Tag the person who should answer: slack ask '${t.target}' '@alice ${t.question}' ...
365
371
  Or open it to the whole channel: slack ask '${t.target}' '@here ${t.question}' ...
366
- (In a 1:1 DM the other person counts automatically.)`),process.exit(_e);W=[...F].map((R)=>`@${q(N.get(R)??R)} (${R})`).join(", ")}let O=t.choices.map(Ge),v=O.slice(0,Xs),J=O.slice(Xs),Q=!i.startsWith("D")||!!o,_=bl(p,D,v,J,Q);kt(_,t.allowUrlAdjacent);let C="",T="?";try{let R=await st(e,i,1,void 0,void 0,s),ue=X(R.messages).map(I).filter((je)=>je.subtype===void 0||je.subtype===null)[0];C=typeof ue?.text==="string"?ue.text:"",T=typeof ue?.user==="string"?await Ie(e,ue.user,s):typeof ue?.username==="string"?ue.username:"?"}catch{}let A=await r(),B=await wo(e,i,s),Z=De(i,o??"",C,_,A?.userId??"");if(t.code!==Z){let R=await $t(e,i,n,s),ue=v.length?["--- Choices (seeded as reactions) ------------",...v.map((je,z)=>` ${ze[z].glyph} ${qt(je)}`),...J.map((je,z)=>` (${z+11}) ${qt(je)} \u2014 text answer only`)]:["--- Choices ----------------------------------"," (none \u2014 free-text reply)"];ye(t.code,Z,["--- Last message in channel ------------------",` ${T}: ${rs(C.split(`
367
- `)[0]??"").slice(0,100)}`,...ue,"--- Asking -----------------------------------",we(A,{asBot:t.asBot}),` \u2192 ${R}${o?" \u2014 THREAD REPLY":" \u2014 NEW top-level message"}`,` Question: ${p}`,` Answerable by: ${W}`,` Via: ${Q?"reactions or thread replies":"reactions or replies in this DM"}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"],B)}let Y=nn("ask"),oe=await Yt(e,i,_,o,!1,s,!0,Y.metadata);await Yr([Ys,...v.map((R,ue)=>ze[ue].name)],(R)=>mn(e,i,oe,R,s),(R,ue)=>{let je=ue instanceof Error?ue.message:String(ue);if(R===Ys)console.error(` (marker ${R} \u3092\u4ED8\u3051\u3089\u308C\u307E\u305B\u3093\u3067\u3057\u305F: ${je})`);else console.error(` (\u30EA\u30A2\u30AF\u30B7\u30E7\u30F3 ${R} \u3092\u4ED8\u3051\u3089\u308C\u307E\u305B\u3093\u3067\u3057\u305F: ${je})`)});let ve="";try{ve=await Vn(e,i,oe,s)}catch{}let ne=ve||`${i}:${oe}`;if(console.error(`\u2713 Asked: ${ne}`),Y.record({team:A?.team,channel:i,target:t.target,ts:oe,threadTs:o,permalink:ve,text:_,asBot:t.asBot}),!t.wait){console.log(lo(ne,!!t.asBot));return}let Le=t.timeout??3600;console.error(` \u56DE\u7B54\u3092\u5F85\u3063\u3066\u3044\u307E\u3059 (\u6700\u5927 ${Le}s)\u2026 Ctrl-C \u3067\u4E2D\u65AD`);let at={channelId:i,ts:oe,question:p,reactable:v,overflow:J,threadOnly:Q,audience:F,broadcast:E,askerUserId:A?.userId??"",askerBotId:A?.botId??"",timeout:Le,shown:ne,asBot:!!t.asBot};if(o)at.threadParentTs=o;if(s)at.cookie=s;await Td(e,at)}async function tm(e,t){let n=Zt(t.link),o,s,r;if(n?.ts)o=n.channel,s=n.ts,r=n.threadTs&&n.threadTs!==n.ts?n.threadTs:void 0;else{let m=t.link.match(/^([A-Za-z0-9]+):(\d{10}\.\d{6})$/);if(!m)console.error(`Error: --waitFor needs the permalink of a question (or 'C\u2026:1700000000.000100').
368
- `+` Got: ${q(t.link)}`),process.exit(_e);o=m[1],s=m[2]}let i;if(r){let m=I(await qe(e,o,r,100,t.cookie));i=X(m.messages).map(I).find((p)=>p.ts===s)}else{let m=I(await st(e,o,1,s,void 0,t.cookie,!0));i=X(m.messages).map(I).find((p)=>p.ts===s)}if(!i)console.error(`Error: \u305D\u306E\u30E1\u30C3\u30BB\u30FC\u30B8\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093: ${q(t.link)}`),process.exit(_e);let c=typeof i.text==="string"?i.text:"",a=Cl(c);if(a.kind==="other")console.error("Error: \u3053\u308C\u306F `slack ask` \u306E\u8CEA\u554F\u3068\u3057\u3066\u8AAD\u307F\u53D6\u308C\u307E\u305B\u3093\u3002\n"+` \u7406\u7531: ${xl(c)}
372
+ (In a 1:1 DM the other person counts automatically.)`),process.exit(_e);W=[...F].map((R)=>`@${q(N.get(R)??R)} (${R})`).join(", ")}let O=t.choices.map(Xe),L=O.slice(0,Vs),J=O.slice(Vs),Q=!i.startsWith("D")||!!o,_=Sl(p,D,L,J,Q);ve(_,t.allowUrlAdjacent);let E="",I="?";try{let R=await ot(e,i,1,void 0,void 0,s),de=X(R.messages).map(T).filter((Ue)=>Ue.subtype===void 0||Ue.subtype===null)[0];E=typeof de?.text==="string"?de.text:"",I=typeof de?.user==="string"?await Ae(e,de.user,s):typeof de?.username==="string"?de.username:"?"}catch{}let A=await r(),B=await Eo(e,i,s),Z=ge(i,o??"",E,_,A?.userId??"");if(t.code!==Z){let R=await At(e,i,n,s),de=L.length?["--- Choices (seeded as reactions) ------------",...L.map((Ue,z)=>` ${Ge[z].glyph} ${Gt(Ue)}`),...J.map((Ue,z)=>` (${z+11}) ${Gt(Ue)} \u2014 text answer only`)]:["--- Choices ----------------------------------"," (none \u2014 free-text reply)"];me(t.code,Z,["--- Last message in channel ------------------",` ${I}: ${is(E.split(`
373
+ `)[0]??"").slice(0,100)}`,...de,"--- Asking -----------------------------------",De(A,{asBot:t.asBot}),` \u2192 ${R}${o?" \u2014 THREAD REPLY":" \u2014 NEW top-level message"}`,` Question: ${p}`,` Answerable by: ${W}`,` Via: ${Q?"reactions or thread replies":"reactions or replies in this DM"}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"],B)}let Y=sn("ask"),oe=await Yt(e,i,_,o,!1,s,!0,Y.metadata);await ei([Zs,...L.map((R,de)=>Ge[de].name)],(R)=>yn(e,i,oe,R,s),(R,de)=>{let Ue=de instanceof Error?de.message:String(de);if(R===Zs)console.error(` (marker ${R} \u3092\u4ED8\u3051\u3089\u308C\u307E\u305B\u3093\u3067\u3057\u305F: ${Ue})`);else console.error(` (\u30EA\u30A2\u30AF\u30B7\u30E7\u30F3 ${R} \u3092\u4ED8\u3051\u3089\u308C\u307E\u305B\u3093\u3067\u3057\u305F: ${Ue})`)});let je="";try{je=await Vn(e,i,oe,s)}catch{}let ne=je||`${i}:${oe}`;if(console.error(`\u2713 Asked: ${ne}`),Y.record({team:A?.team,channel:i,target:t.target,ts:oe,threadTs:o,permalink:je,text:_,asBot:t.asBot}),!t.wait){console.log(ho(ne,!!t.asBot));return}let We=t.timeout??3600;console.error(` \u56DE\u7B54\u3092\u5F85\u3063\u3066\u3044\u307E\u3059 (\u6700\u5927 ${We}s)\u2026 Ctrl-C \u3067\u4E2D\u65AD`);let ct={channelId:i,ts:oe,question:p,reactable:L,overflow:J,threadOnly:Q,audience:F,broadcast:C,askerUserId:A?.userId??"",askerBotId:A?.botId??"",timeout:We,shown:ne,asBot:!!t.asBot};if(o)ct.threadParentTs=o;if(s)ct.cookie=s;await Ud(e,ct)}async function Dm(e,t){let n=Zt(t.link),o,s,r;if(n?.ts)o=n.channel,s=n.ts,r=n.threadTs&&n.threadTs!==n.ts?n.threadTs:void 0;else{let m=t.link.match(/^([A-Za-z0-9]+):(\d{10}\.\d{6})$/);if(!m)console.error(`Error: --waitFor needs the permalink of a question (or 'C\u2026:1700000000.000100').
374
+ `+` Got: ${q(t.link)}`),process.exit(_e);o=m[1],s=m[2]}let i;if(r){let m=T(await Me(e,o,r,100,t.cookie));i=X(m.messages).map(T).find((p)=>p.ts===s)}else{let m=T(await ot(e,o,1,s,void 0,t.cookie,!0));i=X(m.messages).map(T).find((p)=>p.ts===s)}if(!i)console.error(`Error: \u305D\u306E\u30E1\u30C3\u30BB\u30FC\u30B8\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093: ${q(t.link)}`),process.exit(_e);let c=typeof i.text==="string"?i.text:"",a=$l(c);if(a.kind==="other")console.error("Error: \u3053\u308C\u306F `slack ask` \u306E\u8CEA\u554F\u3068\u3057\u3066\u8AAD\u307F\u53D6\u308C\u307E\u305B\u3093\u3002\n"+` \u7406\u7531: ${Fl(c)}
369
375
  ${q(t.link)}
370
- `+` (\u62BC\u3055\u308C\u305F\u30EA\u30A2\u30AF\u30B7\u30E7\u30F3\u306F\u6B8B\u3063\u3066\u3044\u307E\u3059: slack read '${q(t.link)}' \u3067\u78BA\u8A8D\u3067\u304D\u307E\u3059)`),process.exit(_e);if(a.kind==="resolved"){console.error(`\u2713 \u56DE\u7B54\u6E08\u307F: ${q(a.question)}`),console.log(a.answer);return}let l=typeof i.user==="string"?i.user:"",u=typeof i.bot_id==="string"?i.bot_id:"",d=/<!(here|channel|everyone)(\^[^>]*)?(\|[^>]*)?>/.test(c),f=new Set;for(let m of c.matchAll(/<@([UW][A-Z0-9]+)>/g))if(m[1]!==l)f.add(m[1]);if(!f.size&&!d){let m=await bo(e,o,t.cookie);if(m&&m!==l)f.add(m)}if(!f.size&&!d)console.error(`Error: \u3053\u306E\u8CEA\u554F\u306F\u8AB0\u306B\u3082\u5B9B\u3066\u3089\u308C\u3066\u3044\u306A\u3044\u305F\u3081\u3001\u6709\u52B9\u306A\u56DE\u7B54\u8005\u3092\u5224\u5B9A\u3067\u304D\u307E\u305B\u3093: ${q(t.link)}`),process.exit(_e);if(t.timeout>0)console.error(` \u56DE\u7B54\u3092\u5F85\u3063\u3066\u3044\u307E\u3059 (\u6700\u5927 ${t.timeout}s)\u2026 Ctrl-C \u3067\u4E2D\u65AD`);let h={channelId:o,ts:s,question:a.question,reactable:a.reactable,overflow:a.overflow,threadOnly:a.threadOnly,audience:f,broadcast:d,askerUserId:l,askerBotId:u,timeout:t.timeout,shown:t.link,asBot:t.asBot};if(r)h.threadParentTs=r;if(t.cookie)h.cookie=t.cookie;if(t.after)h.after=t.after;await Td(e,h)}var Ye=3;function nm(e){return`slack poll --results='${e}'`}async function sm(e,t){let{ref:n,threadTs:o}=Cn(t.target,!1),s=t.cookie,r=ht(e,s),i;if(t.channelId)i=t.channelId;else if(t.userId)i=await ft(e,t.userId,s);else i=await he(e,n,s);let c=(await r())?.userId??"",a=await bo(e,i,s);if(!t.asBot&&!!c&&a===c)console.error(`Warning: "${t.target}" is a DM to yourself \u2014 Slack will NOT notify you of your own message.
371
- `+` To reach yourself with a notification, post as the bot: slack poll '${t.target}' '...' --as-bot`);let l=mo(Ge(t.question)),u=mo(Ge(t.body??"")),d=t.mentionToken??e,f=await en(d,l.text,i,t.mentionCookie),h=u.text?await en(d,u.text,i,t.mentionCookie):{text:"",resolved:[],unresolved:[]},m=f.text,p=h.text;for(let T of os([...f.unresolved,...h.unresolved]))console.error(`\u26A0 ${q(T)}`);let D=t.choices.map(Ge),k=!!t.multi,x=t.until??"",E=Tl(m,p,D,{multi:k,deadline:x}),F="",N="?";try{let T=await st(e,i,1,void 0,void 0,s),A=X(T.messages).map(I).filter((B)=>B.subtype===void 0||B.subtype===null)[0];F=typeof A?.text==="string"?A.text:"",N=typeof A?.user==="string"?await Ie(e,A.user,s):typeof A?.username==="string"?A.username:"?"}catch{}let W=await r(),O=await wo(e,i,s),v=De(i,o??"",F,E,W?.userId??"");if(t.code!==v){let T=await $t(e,i,n,s);ye(t.code,v,["--- Last message in channel ------------------",` ${N}: ${rs(F.split(`
372
- `)[0]??"").slice(0,100)}`,"--- Ballot (seeded as reactions) -------------",...D.map((A,B)=>` ${nt[B].glyph} ${zn(A)}`),"--- Posting ----------------------------------",we(W,{asBot:t.asBot}),` \u2192 ${T}${o?" \u2014 THREAD REPLY":" \u2014 NEW top-level message"}`,` Question: ${m}`,` Rule: ${k?"1 \u4EBA \u4F55\u7968\u3067\u3082 (--multi)":"1 \u4EBA 1 \u7968"}${x?` \u2014 \u7DE0\u5207 ${x}`:""}`," Note: \u3042\u306A\u305F\u81EA\u8EAB\u306E\u7968\u306F\u6570\u3048\u307E\u305B\u3093 (\u30D4\u30EB\u306F\u3042\u306A\u305F\u304C\u4ED8\u3051\u305F\u7A2E\u306A\u306E\u3067\u533A\u5225\u3067\u304D\u307E\u305B\u3093)","--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"],O)}let J=nn("poll"),Q=await Yt(e,i,E,o,!1,s,!0,J.metadata);await Yr([qn,...D.map((T,A)=>nt[A].name)],(T)=>mn(e,i,Q,T,s),(T,A)=>{let B=A instanceof Error?A.message:String(A);if(T===qn)console.error(` (marker ${T} \u3092\u4ED8\u3051\u3089\u308C\u307E\u305B\u3093\u3067\u3057\u305F: ${B})`);else console.error(` (\u30EA\u30A2\u30AF\u30B7\u30E7\u30F3 ${T} \u3092\u4ED8\u3051\u3089\u308C\u307E\u305B\u3093\u3067\u3057\u305F: ${B})`)});let _="";try{_=await Vn(e,i,Q,s)}catch{}let C=_||`${i}:${Q}`;console.error(`\u2713 Posted: ${C}`),J.record({team:W?.team,channel:i,target:t.target,ts:Q,threadTs:o,permalink:_,text:E,asBot:t.asBot}),console.log(nm(C)),console.error(` \u7DE0\u3081\u5207\u308B: slack poll --close='${C}'${t.asBot?" --as-bot":""}`)}async function om(e,t,n){let o=Zt(t),s,r,i;if(o?.ts)s=o.channel,r=o.ts,i=o.threadTs&&o.threadTs!==o.ts?o.threadTs:void 0;else{let a=t.match(/^([A-Za-z0-9]+):(\d{10}\.\d{6})$/);if(!a)console.error(`Error: --results/--close needs the permalink of a poll (or 'C\u2026:1700000000.000100').
373
- `+` Got: ${q(t)}`),process.exit(Ye);s=a[1],r=a[2]}let c;if(i){let a=I(await qe(e,s,i,100,n));c=X(a.messages).map(I).find((l)=>l.ts===r)}else{let a=I(await st(e,s,1,r,void 0,n,!0));c=X(a.messages).map(I).find((l)=>l.ts===r)}if(!c)console.error(`Error: \u305D\u306E\u30E1\u30C3\u30BB\u30FC\u30B8\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093: ${q(t)}`),process.exit(Ye);return{channelId:s,ts:r,msg:c}}function hd(e){let t=Math.max(1,...e.map((n)=>n.count));return e.map((n,o)=>`${nt[o].glyph} ${String(n.count).padStart(3)} ${"\u2588".repeat(Math.round(n.count/t*20))}${n.count?" ":""}${n.choice}`)}async function rm(e,t){let{channelId:n,ts:o,msg:s}=await om(e,t.link,t.cookie),r=typeof s.text==="string"?s.text:"",i=Ol(r);if(i.kind==="other")console.error("Error: \u3053\u308C\u306F `slack poll` \u306E\u6295\u7968\u3067\u306F\u3042\u308A\u307E\u305B\u3093 (\u7968\u306E\u6570\u3048\u65B9\u304C\u5206\u304B\u308A\u307E\u305B\u3093)\u3002\n"+` ${q(t.link)}`),process.exit(Ye);if(i.kind==="closed"){console.error(`\u2713 \u6295\u7968\u7D42\u4E86: ${q(i.question)}`);for(let h of hd(i.tallies))console.log(h);return}let c=new Set;if(typeof s.user==="string"&&s.user)c.add(s.user);let a=await hu(e,n,o,t.cookie),l=Pl(i.choices,a,c,i.multi);console.error(`${q(i.question)}${i.deadline?` (\u7DE0\u5207 ${i.deadline})`:""}`);for(let h of hd(l.tallies))console.log(h);let u=l.tallies.reduce((h,m)=>h+m.count,0);if(console.error(` \u8A08 ${u} \u7968${i.multi?" (\u8907\u6570\u9078\u629E\u53EF)":""}`),t.names)for(let h=0;h<l.voters.length;h++){if(!l.voters[h].length)continue;let m=await Promise.all(l.voters[h].map((p)=>Ie(e,p,t.cookie)));console.error(` ${nt[h].glyph} ${m.map((p)=>`@${q(p)}`).join(", ")}`)}let d=i.multi?[]:l.ambiguous,f=Jr(r,d);if(f!==r&&!t.noNotify)try{await Vt(t.writeToken??e,n,o,f,t.writeToken?t.writeCookie:t.cookie,!0)}catch(h){console.error(` (\u6295\u7968\u6587\u306B\u6CE8\u610F\u66F8\u304D\u3092\u5165\u308C\u3089\u308C\u307E\u305B\u3093\u3067\u3057\u305F: ${h instanceof Error?h.message:String(h)})
374
- `+" \u30E1\u30C3\u30BB\u30FC\u30B8\u3092\u66F8\u304D\u63DB\u3048\u3089\u308C\u308B\u306E\u306F\u6295\u7A3F\u8005\u3060\u3051\u3067\u3059 \u2014 bot \u304C\u6295\u7A3F\u3057\u305F\u6295\u7968\u306A\u3089 --as-bot \u3092\u4ED8\u3051\u3066\u304F\u3060\u3055\u3044\u3002")}if(l.ambiguous.length){let h=await Promise.all(l.ambiguous.map((m)=>Ie(e,m,t.cookie)));console.error(`\u26A0 1 \u4EBA 1 \u7968\u306A\u306E\u306B\u8907\u6570\u62BC\u3057\u3066\u3044\u308B\u4EBA\u304C\u3044\u307E\u3059 (\u7121\u52B9\u7968): ${h.map((m)=>`@${q(m)}`).join(", ")}`)}if(!t.close)return;await Vt(t.writeToken??e,n,o,Il(i.question,l.tallies),t.writeToken?t.writeCookie:t.cookie,!0);try{await mn(t.writeToken??e,n,o,Xr,t.writeToken?t.writeCookie:t.cookie),await Zn(t.writeToken??e,n,o,qn,t.writeToken?t.writeCookie:t.cookie)}catch{}console.error(`\u2713 \u6295\u7968\u3092\u7DE0\u3081\u5207\u308A\u307E\u3057\u305F: ${q(t.link)}`)}async function im(e){let t=await Ls(e);for(let n of js(t,!1))console.log(n);if(!t.ok)process.exit(1)}function co(){let e=lt();if(!e)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
375
- Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(1);return e}async function gd(e,t,n,o){let s=await pt(n,e,o);return ft(t,s)}function am(e){if(/^\d{10,}$/.test(e))return parseInt(e,10);let t=new Date(e.replace(" ","T"));if(isNaN(t.getTime()))throw Error(`Cannot parse time: ${e}`);return Math.floor(t.getTime()/1000)}function cm(e){let t=new Date(e*1000);return`${new Intl.DateTimeFormat("sv-SE",{year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1,timeZoneName:"short"}).format(t).replace(/\u2212/g,"-")} (local) / ${t.toISOString()} (Unix: ${e})`}async function lm(e,t){let n=ht(e,t.cookie),{ref:o,threadTs:s}=Cn(t.target),r;if(t.channelId)r=t.channelId;else if(t.userId)r=await ft(e,t.userId,t.cookie);else r=await he(e,o,t.cookie);let i=am(t.at),c=new Date(i*1000).toISOString(),a=await n();if(!t.asBot&&await Pi(e,r,a?.userId,t.cookie))console.error(`Warning: "${t.target}" is a DM to yourself \u2014 Slack will NOT notify you when this fires.
376
- `+` To be notified, schedule it as the bot: slack schedule send '${t.target}' '...' --at '${t.at}' --as-bot`);let l=De(r,t.message,String(i),a?.userId??""),u=t.targetOverride?` [${t.targetOverride} \u2192 ${r}]`:"";if(t.code!==l){let f=await wo(e,r,t.cookie);ye(t.code,l,["--- Scheduling message -----------------------",we(a,{asBot:t.asBot,pad:9}),` To: ${o}${s?` (thread ${s})`:""}${u}`,` At: ${cm(i)}`,` Message: ${t.message}`,"---------------------------------------------"],f,new Date(i*1000))}let d=await lu(e,r,t.message,i,s,t.cookie);if(console.log(`\u2713 Scheduled (id: ${d}, at: ${c})`),t.asBot){if(console.error(` Scheduled as the bot \u2014 the user token cannot see or cancel it. Use the same flag:
376
+ `+` (\u62BC\u3055\u308C\u305F\u30EA\u30A2\u30AF\u30B7\u30E7\u30F3\u306F\u6B8B\u3063\u3066\u3044\u307E\u3059: slack read '${q(t.link)}' \u3067\u78BA\u8A8D\u3067\u304D\u307E\u3059)`),process.exit(_e);if(a.kind==="resolved"){console.error(`\u2713 \u56DE\u7B54\u6E08\u307F: ${q(a.question)}`),console.log(a.answer);return}let l=typeof i.user==="string"?i.user:"",u=typeof i.bot_id==="string"?i.bot_id:"",d=/<!(here|channel|everyone)(\^[^>]*)?(\|[^>]*)?>/.test(c),f=new Set;for(let m of c.matchAll(/<@([UW][A-Z0-9]+)>/g))if(m[1]!==l)f.add(m[1]);if(!f.size&&!d){let m=await Co(e,o,t.cookie);if(m&&m!==l)f.add(m)}if(!f.size&&!d)console.error(`Error: \u3053\u306E\u8CEA\u554F\u306F\u8AB0\u306B\u3082\u5B9B\u3066\u3089\u308C\u3066\u3044\u306A\u3044\u305F\u3081\u3001\u6709\u52B9\u306A\u56DE\u7B54\u8005\u3092\u5224\u5B9A\u3067\u304D\u307E\u305B\u3093: ${q(t.link)}`),process.exit(_e);if(t.timeout>0)console.error(` \u56DE\u7B54\u3092\u5F85\u3063\u3066\u3044\u307E\u3059 (\u6700\u5927 ${t.timeout}s)\u2026 Ctrl-C \u3067\u4E2D\u65AD`);let h={channelId:o,ts:s,question:a.question,reactable:a.reactable,overflow:a.overflow,threadOnly:a.threadOnly,audience:f,broadcast:d,askerUserId:l,askerBotId:u,timeout:t.timeout,shown:t.link,asBot:t.asBot};if(r)h.threadParentTs=r;if(t.cookie)h.cookie=t.cookie;if(t.after)h.after=t.after;await Ud(e,h)}var Ve=3;function ym(e){return`slack poll --results='${e}'`}async function wm(e,t){let{ref:n,threadTs:o}=Cn(t.target,!1),s=t.cookie,r=gt(e,s),i;if(t.channelId)i=t.channelId;else if(t.userId)i=await pt(e,t.userId,s);else i=await ue(e,n,s);let c=(await r())?.userId??"",a=await Co(e,i,s);if(!t.asBot&&!!c&&a===c)console.error(`Warning: "${t.target}" is a DM to yourself \u2014 Slack will NOT notify you of your own message.
377
+ `+` To reach yourself with a notification, post as the bot: slack poll '${t.target}' '...' --as-bot`);let l=bo(Xe(t.question)),u=bo(Xe(t.body??"")),d=t.mentionToken??e,f=await tn(d,l.text,i,t.mentionCookie),h=u.text?await tn(d,u.text,i,t.mentionCookie):{text:"",resolved:[],unresolved:[]},m=f.text,p=h.text;for(let I of rs([...f.unresolved,...h.unresolved]))console.error(`\u26A0 ${q(I)}`);let D=t.choices.map(Xe),k=!!t.multi,x=t.until??"",C=Nl(m,p,D,{multi:k,deadline:x});ve(C,t.allowUrlAdjacent);let F="",N="?";try{let I=await ot(e,i,1,void 0,void 0,s),A=X(I.messages).map(T).filter((B)=>B.subtype===void 0||B.subtype===null)[0];F=typeof A?.text==="string"?A.text:"",N=typeof A?.user==="string"?await Ae(e,A.user,s):typeof A?.username==="string"?A.username:"?"}catch{}let W=await r(),O=await Eo(e,i,s),L=ge(i,o??"",F,C,W?.userId??"");if(t.code!==L){let I=await At(e,i,n,s);me(t.code,L,["--- Last message in channel ------------------",` ${N}: ${is(F.split(`
378
+ `)[0]??"").slice(0,100)}`,"--- Ballot (seeded as reactions) -------------",...D.map((A,B)=>` ${st[B].glyph} ${qn(A)}`),"--- Posting ----------------------------------",De(W,{asBot:t.asBot}),` \u2192 ${I}${o?" \u2014 THREAD REPLY":" \u2014 NEW top-level message"}`,` Question: ${m}`,` Rule: ${k?"1 \u4EBA \u4F55\u7968\u3067\u3082 (--multi)":"1 \u4EBA 1 \u7968"}${x?` \u2014 \u7DE0\u5207 ${x}`:""}`," Note: \u3042\u306A\u305F\u81EA\u8EAB\u306E\u7968\u306F\u6570\u3048\u307E\u305B\u3093 (\u30D4\u30EB\u306F\u3042\u306A\u305F\u304C\u4ED8\u3051\u305F\u7A2E\u306A\u306E\u3067\u533A\u5225\u3067\u304D\u307E\u305B\u3093)","--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"],O)}let J=sn("poll"),Q=await Yt(e,i,C,o,!1,s,!0,J.metadata);await ei([Gn,...D.map((I,A)=>st[A].name)],(I)=>yn(e,i,Q,I,s),(I,A)=>{let B=A instanceof Error?A.message:String(A);if(I===Gn)console.error(` (marker ${I} \u3092\u4ED8\u3051\u3089\u308C\u307E\u305B\u3093\u3067\u3057\u305F: ${B})`);else console.error(` (\u30EA\u30A2\u30AF\u30B7\u30E7\u30F3 ${I} \u3092\u4ED8\u3051\u3089\u308C\u307E\u305B\u3093\u3067\u3057\u305F: ${B})`)});let _="";try{_=await Vn(e,i,Q,s)}catch{}let E=_||`${i}:${Q}`;console.error(`\u2713 Posted: ${E}`),J.record({team:W?.team,channel:i,target:t.target,ts:Q,threadTs:o,permalink:_,text:C,asBot:t.asBot}),console.log(ym(E)),console.error(` \u7DE0\u3081\u5207\u308B: slack poll --close='${E}'${t.asBot?" --as-bot":""}`)}async function bm(e,t,n){let o=Zt(t),s,r,i;if(o?.ts)s=o.channel,r=o.ts,i=o.threadTs&&o.threadTs!==o.ts?o.threadTs:void 0;else{let a=t.match(/^([A-Za-z0-9]+):(\d{10}\.\d{6})$/);if(!a)console.error(`Error: --results/--close needs the permalink of a poll (or 'C\u2026:1700000000.000100').
379
+ `+` Got: ${q(t)}`),process.exit(Ve);s=a[1],r=a[2]}let c;if(i){let a=T(await Me(e,s,i,100,n));c=X(a.messages).map(T).find((l)=>l.ts===r)}else{let a=T(await ot(e,s,1,r,void 0,n,!0));c=X(a.messages).map(T).find((l)=>l.ts===r)}if(!c)console.error(`Error: \u305D\u306E\u30E1\u30C3\u30BB\u30FC\u30B8\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093: ${q(t)}`),process.exit(Ve);return{channelId:s,ts:r,msg:c}}function Fd(e){let t=Math.max(1,...e.map((n)=>n.count));return e.map((n,o)=>`${st[o].glyph} ${String(n.count).padStart(3)} ${"\u2588".repeat(Math.round(n.count/t*20))}${n.count?" ":""}${n.choice}`)}async function km(e,t){let{channelId:n,ts:o,msg:s}=await bm(e,t.link,t.cookie),r=typeof s.text==="string"?s.text:"",i=vl(r);if(i.kind==="other")console.error("Error: \u3053\u308C\u306F `slack poll` \u306E\u6295\u7968\u3067\u306F\u3042\u308A\u307E\u305B\u3093 (\u7968\u306E\u6570\u3048\u65B9\u304C\u5206\u304B\u308A\u307E\u305B\u3093)\u3002\n"+` ${q(t.link)}`),process.exit(Ve);if(i.kind==="closed"){console.error(`\u2713 \u6295\u7968\u7D42\u4E86: ${q(i.question)}`);for(let h of Fd(i.tallies))console.log(h);return}let c=new Set;if(typeof s.user==="string"&&s.user)c.add(s.user);let a=await wu(e,n,o,t.cookie),l=Ll(i.choices,a,c,i.multi);console.error(`${q(i.question)}${i.deadline?` (\u7DE0\u5207 ${i.deadline})`:""}`);for(let h of Fd(l.tallies))console.log(h);let u=l.tallies.reduce((h,m)=>h+m.count,0);if(console.error(` \u8A08 ${u} \u7968${i.multi?" (\u8907\u6570\u9078\u629E\u53EF)":""}`),t.names)for(let h=0;h<l.voters.length;h++){if(!l.voters[h].length)continue;let m=await Promise.all(l.voters[h].map((p)=>Ae(e,p,t.cookie)));console.error(` ${st[h].glyph} ${m.map((p)=>`@${q(p)}`).join(", ")}`)}let d=i.multi?[]:l.ambiguous,f=qr(r,d);if(f!==r&&!t.noNotify)try{await Vt(t.writeToken??e,n,o,f,t.writeToken?t.writeCookie:t.cookie,!0)}catch(h){console.error(` (\u6295\u7968\u6587\u306B\u6CE8\u610F\u66F8\u304D\u3092\u5165\u308C\u3089\u308C\u307E\u305B\u3093\u3067\u3057\u305F: ${h instanceof Error?h.message:String(h)})
380
+ `+" \u30E1\u30C3\u30BB\u30FC\u30B8\u3092\u66F8\u304D\u63DB\u3048\u3089\u308C\u308B\u306E\u306F\u6295\u7A3F\u8005\u3060\u3051\u3067\u3059 \u2014 bot \u304C\u6295\u7A3F\u3057\u305F\u6295\u7968\u306A\u3089 --as-bot \u3092\u4ED8\u3051\u3066\u304F\u3060\u3055\u3044\u3002")}if(l.ambiguous.length){let h=await Promise.all(l.ambiguous.map((m)=>Ae(e,m,t.cookie)));console.error(`\u26A0 1 \u4EBA 1 \u7968\u306A\u306E\u306B\u8907\u6570\u62BC\u3057\u3066\u3044\u308B\u4EBA\u304C\u3044\u307E\u3059 (\u7121\u52B9\u7968): ${h.map((m)=>`@${q(m)}`).join(", ")}`)}if(!t.close)return;await Vt(t.writeToken??e,n,o,Bl(i.question,l.tallies),t.writeToken?t.writeCookie:t.cookie,!0);try{await yn(t.writeToken??e,n,o,Qr,t.writeToken?t.writeCookie:t.cookie),await Zn(t.writeToken??e,n,o,Gn,t.writeToken?t.writeCookie:t.cookie)}catch{}console.error(`\u2713 \u6295\u7968\u3092\u7DE0\u3081\u5207\u308A\u307E\u3057\u305F: ${q(t.link)}`)}async function xm(e){let t=await Ws(e);for(let n of Us(t,!1))console.log(n);if(!t.ok)process.exit(1)}function po(){let e=ut();if(!e)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
381
+ Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(1);return e}async function $d(e,t,n,o){let s=await ht(n,e,o);return pt(t,s)}function Em(e){if(/^\d{10,}$/.test(e))return parseInt(e,10);let t=new Date(e.replace(" ","T"));if(isNaN(t.getTime()))throw Error(`Cannot parse time: ${e}`);return Math.floor(t.getTime()/1000)}function Cm(e){let t=new Date(e*1000);return`${new Intl.DateTimeFormat("sv-SE",{year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1,timeZoneName:"short"}).format(t).replace(/\u2212/g,"-")} (local) / ${t.toISOString()} (Unix: ${e})`}async function Sm(e,t){ve(t.message,t.allowUrlAdjacent);let n=gt(e,t.cookie),{ref:o,threadTs:s}=Cn(t.target),r;if(t.channelId)r=t.channelId;else if(t.userId)r=await pt(e,t.userId,t.cookie);else r=await ue(e,o,t.cookie);let i=Em(t.at),c=new Date(i*1000).toISOString(),a=await n();if(!t.asBot&&await vi(e,r,a?.userId,t.cookie))console.error(`Warning: "${t.target}" is a DM to yourself \u2014 Slack will NOT notify you when this fires.
382
+ `+` To be notified, schedule it as the bot: slack schedule send '${t.target}' '...' --at '${t.at}' --as-bot`);let l=ge(r,t.message,String(i),a?.userId??""),u=t.targetOverride?` [${t.targetOverride} \u2192 ${r}]`:"";if(t.code!==l){let f=await Eo(e,r,t.cookie);me(t.code,l,["--- Scheduling message -----------------------",De(a,{asBot:t.asBot,pad:9}),` To: ${o}${s?` (thread ${s})`:""}${u}`,` At: ${Cm(i)}`,` Message: ${t.message}`,"---------------------------------------------"],f,new Date(i*1000))}let d=await hu(e,r,t.message,i,s,t.cookie);if(console.log(`\u2713 Scheduled (id: ${d}, at: ${c})`),t.asBot){if(console.error(` Scheduled as the bot \u2014 the user token cannot see or cancel it. Use the same flag:
377
383
  `+` slack schedule ls --as-bot
378
- slack schedule rm '${t.target}' ${d} --as-bot`),r.startsWith("D"))try{let f=await Ls(e);if(!f.ok)for(let h of js(f,!0))console.error(h);else{let h=f.appId?`https://api.slack.com/apps/${f.appId}`:"https://api.slack.com/apps";console.error(`Note: if ${t.target} can't reply (app messaging may be off), enable Messages Tab: ${h} \u2192 App Home.`)}}catch{}}}async function md(e,t,n,o){let s;if(n)s=n;else if(t)s=await he(e,t,o);let i=(await uu(e,s,o)).scheduled_messages??[];if(i.length===0){console.log("(no scheduled messages)");return}for(let c of i){let a=new Date(c.post_at*1000).toISOString();console.log(`${c.id} ${a} [${c.channel_id}] ${c.text.split(`
379
- `)[0]?.slice(0,80)??""}`)}}async function Dd(e,t){let n;if(t.channelId)n=t.channelId;else n=await he(e,t.target,t.cookie);let o=await it(e,t.cookie),s=De(n,t.id,o?.userId??"");if(t.code!==s)ye(t.code,s,["--- Deleting scheduled message ---------------",we(o,{asBot:t.asBot,pad:9}),` Channel: ${t.target}${t.targetOverride?` [${t.targetOverride} \u2192 ${n}]`:""}`,` ID: ${t.id}`,"---------------------------------------------"]);await du(e,n,t.id,t.cookie),console.log(`\u2713 Deleted scheduled message ${t.id}`)}async function um(e,t){let n=ht(e,t.cookie),{statSync:o,existsSync:s}=await import("fs"),{basename:r}=await import("path");for(let m of t.filePaths)if(!s(m))console.error(`Error: file not found: ${m}`),process.exit(1);let{ref:i,threadTs:c}=Cn(t.target),a;if(t.channelId)a=t.channelId;else if(t.userId)a=await ft(e,t.userId,t.cookie);else a=await he(e,i,t.cookie);if(await Pi(e,a,(await n())?.userId,t.cookie))console.error(`Warning: "${t.target}" is a DM to yourself \u2014 Slack will NOT notify you of your own upload.`);let l=t.filePaths.length>1,u=t.filePaths.map((m)=>{let p=r(m),D=l?p:t.title??p;return{fp:m,filename:p,title:D,sizeFmt:yo(o(m).size)}}),d=await n(),f=De(a,...u.flatMap((m)=>[m.fp,m.title]),d?.userId??"");if(t.code!==f){let m=` To: ${i}${c?` (thread ${c})`:""}`,p=l?[`--- Uploading ${u.length} files ------------------------`,we(d,{pad:7}),m,...u.map((D)=>` ${D.filename} (${D.sizeFmt})`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]:["--- Uploading file ---------------------------",we(d,{pad:7}),m,` File: ${u[0].fp}`,` Title: ${u[0].title}`,` Size: ${u[0].sizeFmt}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"];ye(t.code,f,p)}let h=u.length;for(let m=0;m<h;m++){let p=u[m],D={title:p.title};if(c!==void 0)D.threadTs=c;if(t.comment!==void 0&&m===0)D.initialComment=t.comment;let{fileId:k,permalink:x}=await Fu(e,a,p.fp,D,t.cookie),E=h>1?`[${m+1}/${h}] `:"";console.log(`${E}\u2713 Uploaded (file_id: ${k}${x?`, url: ${x}`:""})`)}}async function dm(e,t,n){let o=n.channel?await he(e,n.channel,t):void 0,s=[],r=1,i=1;do{let a={page:r,count:200};if(n.types)a.types=n.types;if(o)a.channel=o;if(n.user)a.user=n.user;let l=I(await eu(e,a,t));for(let u of X(l.files))s.push(I(u));i=Number(I(l.paging).pages??1),r++}while(s.length<n.limit&&r<=i);let c=s.slice(0,n.limit);if(n.format==="jsonl"){for(let a of c)console.log(JSON.stringify({id:a.id??null,name:a.name??a.title??null,filetype:a.filetype??null,size:a.size??null,user:a.user??null,created:a.created??null,permalink:a.permalink??null}));return}for(let a of c){let l=String(a.id??""),u=typeof a.name==="string"?a.name:typeof a.title==="string"?a.title:l,d=typeof a.filetype==="string"?a.filetype:"?",f=typeof a.size==="number"?yo(a.size):"";console.log(`${l} ${d.padEnd(7)} ${f.padStart(9)} ${u}`)}}function ko(e){if(/^F[A-Z0-9]+$/i.test(e))return e;return e.match(/\/lists\/[A-Za-z0-9]+\/(F[A-Za-z0-9]+)/i)?.[1]??e.match(/\/lists\/(F[A-Za-z0-9]+)/i)?.[1]}function fm(e){if(typeof e.text==="string"&&e.text)return e.text;let t=e.value;if(typeof t==="string"||typeof t==="number"||typeof t==="boolean")return String(t);if(Array.isArray(t))return t.map((n)=>typeof n==="string"?n:String(I(n).text??I(n).name??I(n).value??"")).filter(Boolean).join(", ");for(let n of["rich_text","select","user","date","number","checkbox","email","phone"]){let o=e[n];if(o!=null)return typeof o==="object"?JSON.stringify(o):String(o)}return""}async function pm(e,t,n,o){let s=ko(n);if(!s)throw Error(`Not a list ID or list URL: ${n}
380
- `+"Expected F\u2026 or https://<ws>.slack.com/lists/<TEAM>/<F-id>");let r=[],i;do{let a={limit:200};if(i)a.cursor=i;let l=o.asBot?await ai(us(),s,a):I(await ru(e,s,a,t));for(let d of X(l.items??l.records))r.push(I(d));let u=I(l.response_metadata).next_cursor;i=typeof u==="string"&&u?u:void 0}while(i&&r.length<o.limit);let c=r.slice(0,o.limit);if(o.format==="jsonl"){for(let a of c)console.log(JSON.stringify(a));return}for(let a of c){let l=String(a.id??""),u=X(a.fields).map(I).map((d)=>{let f=String(d.key??d.column_id??"?"),h=fm(d);return h?`${f}=${h}`:""}).filter(Boolean);console.log(`${l} ${u.join(" | ")}`)}}function us(){let e=lt();if(!e)console.error(`Error: Slack List writes go through the public slackLists.* API, which needs a bot token (xoxb-) \u2014 none was found.
381
- `+" Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell)."),process.exit(1);return e}async function xo(e){let t=[];try{t=(await Yn(e)).scopes}catch{return}if(t.length&&!t.includes("lists:write"))console.error(`Error: the bot token lacks the lists:write scope (needed for slackLists.* writes).
382
- `+" Add it under OAuth & Permissions \u2192 Bot Token Scopes in the Slack app config, then reinstall the app."),process.exit(1)}async function hm(e,t){try{let n=await ii(e);if(n.url&&n.teamId)return`${n.url.replace(/\/$/,"")}/lists/${n.teamId}/${t}`}catch{}return t}async function Id(e,t){let n=await ai(e,t,{limit:1,includeList:!0}),o=Ll(I(n.list));if(!o.length)throw Error(`could not read the column schema of list ${t}`);return o}function Co(e){console.error(ce(e)),process.exit(1)}async function gm(e){let t=e.cols.map(Ml),n=vl(t),o=us();await xo(o);let s=await it(o),r=De("lists-create",e.name,JSON.stringify(n),String(e.todo),s?.userId??"");if(e.code!==r)ye(e.code,r,["--- Creating Slack List ----------------------",we(s,{asBot:!0,pad:9}),` name: ${e.name}`,...t.map((a,l)=>` column: ${a.name} (${a.type}${a.choices?`: ${a.choices.join("/")}`:""})${l===0?" [primary]":""}`),` todo: ${e.todo?"on (adds Completed / Assignee / Due date)":"off"}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);let i;try{i=await tu(o,e.name,n,e.todo)}catch(a){Co(a)}let c=String(i.list_id??I(i.list).id??"");console.log(`\u2713 Created list ${e.name} (${c})`),console.log(await hm(o,c))}async function mm(e){let t=ko(e.list);if(!t)throw Error(`Not a list ID or list URL: ${e.list}`);let n=us();await xo(n);let o=await Id(n,t),r=[{col:o.find((u)=>u.type==="text")??o[0],value:e.text},...Qr(e.sets).map((u)=>({col:Vr(o,u.col),value:u.value}))],i=r.map((u)=>({column_id:u.col.id,...Zr(u.col,u.value)})),c=await it(n),a=De("lists-add",t,JSON.stringify(i),c?.userId??"");if(e.code!==a)ye(e.code,a,["--- Adding a row to Slack List ---------------",we(c,{asBot:!0,pad:9}),` list: ${t}`,...r.map((u)=>` ${(u.col.name||u.col.key).padEnd(8)} ${u.value}`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);let l;try{l=await nu(n,t,i)}catch(u){Co(u)}console.log(`\u2713 Added row ${String(I(l.item).id??"")} ${e.text}`)}async function Dm(e){let t=ko(e.list);if(!t)throw Error(`Not a list ID or list URL: ${e.list}`);let n=us();await xo(n);let o=await Id(n,t),s=Qr(e.sets).map((a)=>({col:Vr(o,a.col),value:a.value}));if(e.done!==void 0){let a=jl(o);if(!a)throw Error(`list ${t} has no Completed column \u2014 it was not created with todo mode`);s.push({col:{...a,type:"checkbox"},value:String(e.done)})}if(!s.length)throw Error("nothing to set \u2014 pass --set name=value and/or --done / --no-done");let r=s.map((a)=>({row_id:e.row,column_id:a.col.id,...Zr(a.col,a.value)})),i=await it(n),c=De("lists-set",t,e.row,JSON.stringify(r),i?.userId??"");if(e.code!==c)ye(e.code,c,["--- Updating Slack List row -----------------",we(i,{asBot:!0,pad:9}),` list: ${t}`,` row: ${e.row}`,...s.map((a)=>` ${(a.col.name||a.col.key).padEnd(8)} ${a.value}`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);try{await ou(n,t,r)}catch(a){Co(a)}console.log(`\u2713 Updated row ${e.row}`)}async function ym(e){let t=ko(e.list);if(!t)throw Error(`Not a list ID or list URL: ${e.list}`);if(!e.users.length===!e.channels.length)throw Error("pass --user or --channel (Slack takes one kind per call, not both)");if(e.level==="owner"&&e.channels.length)throw Error("only a user can be made owner");let n=us();await xo(n);let o=e.users.length?e.users:e.channels,s=await it(n),r=De("lists-share",t,e.level,o.join(","),s?.userId??"");if(e.code!==r)ye(e.code,r,["--- Sharing Slack List ----------------------",we(s,{asBot:!0,pad:9}),` list: ${t}`,` ${e.users.length?"users: ":"channels:"} ${o.join(", ")}`,` access: ${e.level}${e.level==="owner"?" \u26A0 transfers ownership":""}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);try{await su(n,t,e.level,e.users.length?{userIds:e.users}:{channelIds:e.channels})}catch(i){Co(i)}console.log(`\u2713 Granted ${e.level} on ${t} to ${o.join(", ")}`)}function wm(e){if(/^F[A-Z0-9]+$/i.test(e))return e;return e.match(/\/files\/[A-Za-z0-9]+\/(F[A-Za-z0-9]+)/)?.[1]}async function bm(e,t,n,o){let s=wm(n);if(!s)throw Error(`Not a file ID or file permalink: ${n}
383
- `+"Expected F\u2026 or https://<ws>.slack.com/files/<UID>/<FID>/<name>");let r=I(await Ql(e,s,t)),i=I(r.file),c=typeof i.name==="string"?i.name:typeof i.title==="string"?i.title:s,a=typeof i.url_private_download==="string"?i.url_private_download:typeof i.url_private==="string"?i.url_private:"";if(!a)throw Error(`files.info returned no download URL for ${s}`);let l={Authorization:`Bearer ${e}`};if(t)l.Cookie=`d=${t}`;let u=await fetch(a,{headers:l});if(!u.ok)throw Error(`Download failed: HTTP ${u.status} ${u.statusText}`);let d=Buffer.from(await u.arrayBuffer()),{statSync:f,existsSync:h}=await import("fs"),{basename:m}=await import("path"),p=o??c;if(o&&h(o)&&f(o).isDirectory())p=_t(o,m(c));bd(p,d),console.log(`\u2713 Downloaded ${c} (${yo(d.length)}) \u2192 ${p}`)}async function km(){Zu(),lg();let e=(s)=>Pn(s.workspace),t=(s)=>ar(s.workspace),n={state:{type:"string",choices:["open","untriaged","pending","doing","done","dropped","stuck"],default:"open",describe:"open (default) = marked and not done/dropped; untriaged = marked with no progress; stuck = unfinished with a reason flag"},in:{type:"string",describe:"Limit to a channel (#chan)"},from:{type:"string",describe:"Limit to a sender (@user, or 'me') \u2014 usually the person a task is waiting on"},n:{alias:"count",type:"number",default:50,describe:"Max results"},json:{type:"boolean",default:!1}},o=async(s,r)=>{let i={state:s.state??"open",mine:r||s.mine===!0,count:s.n??50,json:s.json===!0};if(s.in)i.in=s.in;if(s.from)i.from=s.from;let c=t(s);if(c)i.cookie=c;await bg(e(s),i)};await gc(vo(process.argv)).scriptName("slack").showHelpOnFail(!1).fail((s,r,i)=>{if(r)console.error(r.message),process.exit(1);console.error(s),console.error(""),i.showHelp(),process.exit(1)}).option("workspace",{alias:"w",type:"string",describe:"Workspace name"}).middleware(async(s)=>{let r=String((s._??[])[0]??"");if(!r||r==="auth"||r==="login"||r==="agent"||r==="sent")return;try{Pn(s.workspace)}catch(i){if((i instanceof Error?i.message:String(i)).startsWith("No profiles configured"))console.log(`No workspace configured. Let's set that up:
384
- `),await Hn(),process.exit(0);throw i}},!0).command("agent","Bot agent session status and command heartbeat",(s)=>ml(s,Cn)).command(["read [target]","msgs [target]"],"Browse messages",(s)=>s.positional("target",{type:"string",describe:"#channel, @user, or URL"}).option("limit",{alias:"n",type:"number",default:20,describe:"Number of messages"}).option("format",{type:"string",choices:["text","jsonl"],default:"text",describe:"jsonl exposes raw ts/user/text (incl. external-guest user IDs)"}).option("json",{type:"boolean",default:!1,describe:"Alias for --format=jsonl"}).option("unreplied",{type:"boolean",default:!1,describe:"Only messages whose last word (incl. thread replies) is not yours \u2014 i.e. awaiting your answer"}),async(s)=>{let r=e(s),i=s.json?"jsonl":s.format;if(s.target)await hg(r,s.target,s.limit,i,s.unreplied,t(s));else await mg(r)}).command("thread <target> <ts>","Show thread messages",(s)=>s.positional("target",{type:"string",demandOption:!0}).positional("ts",{type:"string",demandOption:!0}).option("limit",{alias:"n",type:"number",default:100}).option("format",{type:"string",choices:["text","jsonl"],default:"text",describe:"jsonl exposes raw ts/user/text (incl. external-guest user IDs)"}).option("json",{type:"boolean",default:!1,describe:"Alias for --format=jsonl"}),async(s)=>{let r=s.json?"jsonl":s.format;await gg(e(s),s.target,s.ts,s.limit,r,t(s))}).command(["channel","channels","ch"],"Channel commands",(s)=>s.command(["ls","list"],"List channels",(r)=>r.option("limit",{alias:"n",type:"number",default:200}).option("filter",{alias:"f",type:"string"}).option("all",{type:"boolean",default:!1}).option("format",{type:"string",choices:["text","jsonl"],default:"text"}).option("json",{type:"boolean",default:!1,describe:"Alias for --format=jsonl"}),async(r)=>{await yg(e(r),r.limit,r.filter,r.all,r.json?"jsonl":r.format,t(r))}).command("get <channel>","Show channel details",(r)=>r.positional("channel",{type:"string",demandOption:!0,describe:"#name or channel ID"}),async(r)=>{let i=e(r),c=t(r),a=r.channel,l=a.startsWith("#")||a.startsWith("@")||a.startsWith("C")||a.startsWith("G")||a.startsWith("D")?a:`#${a}`,u=await he(i,l,c),d=I(await Dn(i,u,c)),f=I(d.channel),h=typeof f.name==="string"?f.name:u,p=f.is_im===!0?"@":"#",D=String(I(f.purpose).value??""),k=String(I(f.topic).value??""),x=f.num_members??f.member_count??"";if(console.log(`${p}${h} ${u}`),k)console.log(`topic: ${k}`);if(D)console.log(`purpose: ${D}`);if(x)console.log(`members: ${x}`);console.log(`private: ${f.is_private===!0}`)}).command(["create <name>","new <name>"],"Create a channel (confirm-hash safety gate)",(r)=>r.positional("name",{type:"string",demandOption:!0,describe:"Channel name (Slack lowercases it; no spaces)"}).option("private",{type:"boolean",default:!1,describe:"Create a private channel"}).option("invite",{type:"string",array:!0,default:[],describe:"Users to invite after creating (@handle or Uxxxx, repeatable)"}).option("code",{type:"string",describe:"Safety hash to confirm create"}),async(r)=>{let i=e(r),c=t(r),a=r.name.replace(/^#/,"").toLowerCase(),l=r.private===!0,u=r.invite.filter(Boolean),d=await it(i,c),f=De(a,String(l),u.join(","),d?.userId??"");if(r.code!==f)ye(r.code,f,["--- Creating channel -------------------------",we(d,{pad:9}),` name: ${l?"\uD83D\uDD12 ":"#"}${a}`,` private: ${l}`,...u.length?[` invite: ${u.join(", ")}`]:[],"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);let h;try{h=await gu(i,a,l,c)}catch(m){console.error(m instanceof Error?m.message:String(m)),process.exit(1)}if(console.log(`\u2713 Created ${l?"\uD83D\uDD12 ":"#"}${h.name} (${h.id})`),u.length){let m=[];for(let p of u)try{m.push(p.startsWith("U")||p.startsWith("W")?p:await pt(i,p,c))}catch(D){console.error(` ! could not resolve ${p}: ${D instanceof Error?D.message:String(D)}`)}for(let p of m)try{let D=I(await ns(i,p,c)),k=I(D.user);if(k.is_ultra_restricted===!0)console.error(`\u26A0 ${p} is a single-channel guest \u2014 Slack restricts them to their one existing channel; this invite will likely report success but not actually add them.`);else if(k.is_restricted===!0)console.error(`\u26A0 ${p} is a multi-channel guest \u2014 double-check they were actually added (guest invites can silently no-op depending on workspace restrictions).`)}catch{}if(m.length)try{await mu(i,h.id,m,c),console.log(`\u2713 Invited ${m.length} member${m.length===1?"":"s"}`)}catch(p){console.error(` ! invite failed: ${p instanceof Error?p.message:String(p)}`)}}}).demandCommand(1,"").showHelpOnFail(!0)).command(["user","usr"],"User commands",(s)=>s.command(["ls","list"],"List workspace members",(r)=>r.option("limit",{alias:"n",type:"number",default:200}).option("filter",{alias:"f",type:"string"}).option("format",{type:"string",choices:["text","jsonl","yaml"],default:"text"}).option("json",{type:"boolean",default:!1,describe:"Alias for --format=jsonl"}).option("external",{type:"boolean",default:!1,describe:"Also include people reachable only through Slack Connect shared channels \u2014 they are in ANOTHER workspace, so users.list never returns them (costs one API call per shared channel)"}),async(r)=>{let i=r.json?"jsonl":r.format,c=e(r),a=t(r),l=await ku(c,a),u=r.filter?.toLowerCase(),d=X(l.members).map(I);if(r.external){let p=new Set(d.map((E)=>String(E.id))),D=I(await Qn(c,a)),k=X(D.channels).map(I).filter((E)=>E.is_ext_shared===!0&&!!E.name),x=new Set;for(let E of k)try{for(let F of await xu(c,String(E.id),a))if(!p.has(F))x.add(F)}catch{}for(let E of x)try{let F=I(await ns(c,E,a)),N=I(F.user);if(N.id)d.push(N)}catch{}}let f=d.filter((p)=>p.deleted!==!0&&p.is_bot!==!0&&String(p.id)!=="USLACKBOT").filter((p)=>{if(!u)return!0;let D=String(p.name??"").toLowerCase(),k=String(I(p.profile).real_name??"").toLowerCase(),x=String(I(p.profile).email??"").toLowerCase();return D.includes(u)||k.includes(u)||x.includes(u)}).slice(0,r.limit);if(i==="jsonl"){for(let p of f)console.log(JSON.stringify(p));return}if(i==="yaml"){for(let p of f){let D=function(k,x=""){if(k===null)return"null";if(typeof k==="string")return k.includes(`
384
+ slack schedule rm '${t.target}' ${d} --as-bot`),r.startsWith("D"))try{let f=await Ws(e);if(!f.ok)for(let h of Us(f,!0))console.error(h);else{let h=f.appId?`https://api.slack.com/apps/${f.appId}`:"https://api.slack.com/apps";console.error(`Note: if ${t.target} can't reply (app messaging may be off), enable Messages Tab: ${h} \u2192 App Home.`)}}catch{}}}async function Ad(e,t,n,o){let s;if(n)s=n;else if(t)s=await ue(e,t,o);let i=(await gu(e,s,o)).scheduled_messages??[];if(i.length===0){console.log("(no scheduled messages)");return}for(let c of i){let a=new Date(c.post_at*1000).toISOString();console.log(`${c.id} ${a} [${c.channel_id}] ${c.text.split(`
385
+ `)[0]?.slice(0,80)??""}`)}}async function Td(e,t){let n;if(t.channelId)n=t.channelId;else n=await ue(e,t.target,t.cookie);let o=await rt(e,t.cookie),s=ge(n,t.id,o?.userId??"");if(t.code!==s)me(t.code,s,["--- Deleting scheduled message ---------------",De(o,{asBot:t.asBot,pad:9}),` Channel: ${t.target}${t.targetOverride?` [${t.targetOverride} \u2192 ${n}]`:""}`,` ID: ${t.id}`,"---------------------------------------------"]);await mu(e,n,t.id,t.cookie),console.log(`\u2713 Deleted scheduled message ${t.id}`)}async function _m(e,t){if(t.comment!==void 0)ve(t.comment,t.allowUrlAdjacent);let n=gt(e,t.cookie),{statSync:o,existsSync:s}=await import("fs"),{basename:r}=await import("path");for(let m of t.filePaths)if(!s(m))console.error(`Error: file not found: ${m}`),process.exit(1);let{ref:i,threadTs:c}=Cn(t.target),a;if(t.channelId)a=t.channelId;else if(t.userId)a=await pt(e,t.userId,t.cookie);else a=await ue(e,i,t.cookie);if(await vi(e,a,(await n())?.userId,t.cookie))console.error(`Warning: "${t.target}" is a DM to yourself \u2014 Slack will NOT notify you of your own upload.`);let l=t.filePaths.length>1,u=t.filePaths.map((m)=>{let p=r(m),D=l?p:t.title??p;return{fp:m,filename:p,title:D,sizeFmt:xo(o(m).size)}}),d=await n(),f=ge(a,...u.flatMap((m)=>[m.fp,m.title]),d?.userId??"");if(t.code!==f){let m=` To: ${i}${c?` (thread ${c})`:""}`,p=l?[`--- Uploading ${u.length} files ------------------------`,De(d,{pad:7}),m,...u.map((D)=>` ${D.filename} (${D.sizeFmt})`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]:["--- Uploading file ---------------------------",De(d,{pad:7}),m,` File: ${u[0].fp}`,` Title: ${u[0].title}`,` Size: ${u[0].sizeFmt}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"];me(t.code,f,p)}let h=u.length;for(let m=0;m<h;m++){let p=u[m],D={title:p.title};if(c!==void 0)D.threadTs=c;if(t.comment!==void 0&&m===0)D.initialComment=t.comment;let{fileId:k,permalink:x}=await Ru(e,a,p.fp,D,t.cookie),C=h>1?`[${m+1}/${h}] `:"";console.log(`${C}\u2713 Uploaded (file_id: ${k}${x?`, url: ${x}`:""})`)}}async function Fm(e,t,n){let o=n.channel?await ue(e,n.channel,t):void 0,s=[],r=1,i=1;do{let a={page:r,count:200};if(n.types)a.types=n.types;if(o)a.channel=o;if(n.user)a.user=n.user;let l=T(await ru(e,a,t));for(let u of X(l.files))s.push(T(u));i=Number(T(l.paging).pages??1),r++}while(s.length<n.limit&&r<=i);let c=s.slice(0,n.limit);if(n.format==="jsonl"){for(let a of c)console.log(JSON.stringify({id:a.id??null,name:a.name??a.title??null,filetype:a.filetype??null,size:a.size??null,user:a.user??null,created:a.created??null,permalink:a.permalink??null}));return}for(let a of c){let l=String(a.id??""),u=typeof a.name==="string"?a.name:typeof a.title==="string"?a.title:l,d=typeof a.filetype==="string"?a.filetype:"?",f=typeof a.size==="number"?xo(a.size):"";console.log(`${l} ${d.padEnd(7)} ${f.padStart(9)} ${u}`)}}function So(e){if(/^F[A-Z0-9]+$/i.test(e))return e;return e.match(/\/lists\/[A-Za-z0-9]+\/(F[A-Za-z0-9]+)/i)?.[1]??e.match(/\/lists\/(F[A-Za-z0-9]+)/i)?.[1]}function $m(e){if(typeof e.text==="string"&&e.text)return e.text;let t=e.value;if(typeof t==="string"||typeof t==="number"||typeof t==="boolean")return String(t);if(Array.isArray(t))return t.map((n)=>typeof n==="string"?n:String(T(n).text??T(n).name??T(n).value??"")).filter(Boolean).join(", ");for(let n of["rich_text","select","user","date","number","checkbox","email","phone"]){let o=e[n];if(o!=null)return typeof o==="object"?JSON.stringify(o):String(o)}return""}async function Am(e,t,n,o){let s=So(n);if(!s)throw Error(`Not a list ID or list URL: ${n}
386
+ `+"Expected F\u2026 or https://<ws>.slack.com/lists/<TEAM>/<F-id>");let r=[],i;do{let a={limit:200};if(i)a.cursor=i;let l=o.asBot?await di(ds(),s,a):T(await uu(e,s,a,t));for(let d of X(l.items??l.records))r.push(T(d));let u=T(l.response_metadata).next_cursor;i=typeof u==="string"&&u?u:void 0}while(i&&r.length<o.limit);let c=r.slice(0,o.limit);if(o.format==="jsonl"){for(let a of c)console.log(JSON.stringify(a));return}for(let a of c){let l=String(a.id??""),u=X(a.fields).map(T).map((d)=>{let f=String(d.key??d.column_id??"?"),h=$m(d);return h?`${f}=${h}`:""}).filter(Boolean);console.log(`${l} ${u.join(" | ")}`)}}function ds(){let e=ut();if(!e)console.error(`Error: Slack List writes go through the public slackLists.* API, which needs a bot token (xoxb-) \u2014 none was found.
387
+ `+" Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell)."),process.exit(1);return e}async function _o(e){let t=[];try{t=(await Dn(e)).scopes}catch{return}if(t.length&&!t.includes("lists:write"))console.error(`Error: the bot token lacks the lists:write scope (needed for slackLists.* writes).
388
+ `+" Add it under OAuth & Permissions \u2192 Bot Token Scopes in the Slack app config, then reinstall the app."),process.exit(1)}async function Tm(e,t){try{let n=await ui(e);if(n.url&&n.teamId)return`${n.url.replace(/\/$/,"")}/lists/${n.teamId}/${t}`}catch{}return t}async function Jd(e,t){let n=await di(e,t,{limit:1,includeList:!0}),o=Kl(T(n.list));if(!o.length)throw Error(`could not read the column schema of list ${t}`);return o}function Fo(e){console.error(ae(e)),process.exit(1)}async function Im(e){let t=e.cols.map(Ul),n=Jl(t),o=ds();await _o(o);let s=await rt(o),r=ge("lists-create",e.name,JSON.stringify(n),String(e.todo),s?.userId??"");if(e.code!==r)me(e.code,r,["--- Creating Slack List ----------------------",De(s,{asBot:!0,pad:9}),` name: ${e.name}`,...t.map((a,l)=>` column: ${a.name} (${a.type}${a.choices?`: ${a.choices.join("/")}`:""})${l===0?" [primary]":""}`),` todo: ${e.todo?"on (adds Completed / Assignee / Due date)":"off"}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);let i;try{i=await iu(o,e.name,n,e.todo)}catch(a){Fo(a)}let c=String(i.list_id??T(i.list).id??"");console.log(`\u2713 Created list ${e.name} (${c})`),console.log(await Tm(o,c))}async function Om(e){let t=So(e.list);if(!t)throw Error(`Not a list ID or list URL: ${e.list}`);let n=ds();await _o(n);let o=await Jd(n,t),r=[{col:o.find((u)=>u.type==="text")??o[0],value:e.text},...si(e.sets).map((u)=>({col:ti(o,u.col),value:u.value}))],i=r.map((u)=>({column_id:u.col.id,...ni(u.col,u.value)})),c=await rt(n),a=ge("lists-add",t,JSON.stringify(i),c?.userId??"");if(e.code!==a)me(e.code,a,["--- Adding a row to Slack List ---------------",De(c,{asBot:!0,pad:9}),` list: ${t}`,...r.map((u)=>` ${(u.col.name||u.col.key).padEnd(8)} ${u.value}`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);let l;try{l=await au(n,t,i)}catch(u){Fo(u)}console.log(`\u2713 Added row ${String(T(l.item).id??"")} ${e.text}`)}async function Pm(e){let t=So(e.list);if(!t)throw Error(`Not a list ID or list URL: ${e.list}`);let n=ds();await _o(n);let o=await Jd(n,t),s=si(e.sets).map((a)=>({col:ti(o,a.col),value:a.value}));if(e.done!==void 0){let a=Hl(o);if(!a)throw Error(`list ${t} has no Completed column \u2014 it was not created with todo mode`);s.push({col:{...a,type:"checkbox"},value:String(e.done)})}if(!s.length)throw Error("nothing to set \u2014 pass --set name=value and/or --done / --no-done");let r=s.map((a)=>({row_id:e.row,column_id:a.col.id,...ni(a.col,a.value)})),i=await rt(n),c=ge("lists-set",t,e.row,JSON.stringify(r),i?.userId??"");if(e.code!==c)me(e.code,c,["--- Updating Slack List row -----------------",De(i,{asBot:!0,pad:9}),` list: ${t}`,` row: ${e.row}`,...s.map((a)=>` ${(a.col.name||a.col.key).padEnd(8)} ${a.value}`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);try{await lu(n,t,r)}catch(a){Fo(a)}console.log(`\u2713 Updated row ${e.row}`)}async function Rm(e){let t=So(e.list);if(!t)throw Error(`Not a list ID or list URL: ${e.list}`);if(!e.users.length===!e.channels.length)throw Error("pass --user or --channel (Slack takes one kind per call, not both)");if(e.level==="owner"&&e.channels.length)throw Error("only a user can be made owner");let n=ds();await _o(n);let o=e.users.length?e.users:e.channels,s=await rt(n),r=ge("lists-share",t,e.level,o.join(","),s?.userId??"");if(e.code!==r)me(e.code,r,["--- Sharing Slack List ----------------------",De(s,{asBot:!0,pad:9}),` list: ${t}`,` ${e.users.length?"users: ":"channels:"} ${o.join(", ")}`,` access: ${e.level}${e.level==="owner"?" \u26A0 transfers ownership":""}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);try{await cu(n,t,e.level,e.users.length?{userIds:e.users}:{channelIds:e.channels})}catch(i){Fo(i)}console.log(`\u2713 Granted ${e.level} on ${t} to ${o.join(", ")}`)}function Nm(e){if(/^F[A-Z0-9]+$/i.test(e))return e;return e.match(/\/files\/[A-Za-z0-9]+\/(F[A-Za-z0-9]+)/)?.[1]}async function Bm(e,t,n,o){let s=Nm(n);if(!s)throw Error(`Not a file ID or file permalink: ${n}
389
+ `+"Expected F\u2026 or https://<ws>.slack.com/files/<UID>/<FID>/<name>");let r=T(await ou(e,s,t)),i=T(r.file),c=typeof i.name==="string"?i.name:typeof i.title==="string"?i.title:s,a=typeof i.url_private_download==="string"?i.url_private_download:typeof i.url_private==="string"?i.url_private:"";if(!a)throw Error(`files.info returned no download URL for ${s}`);let l={Authorization:`Bearer ${e}`};if(t)l.Cookie=`d=${t}`;let u=await fetch(a,{headers:l});if(!u.ok)throw Error(`Download failed: HTTP ${u.status} ${u.statusText}`);let d=Buffer.from(await u.arrayBuffer()),{statSync:f,existsSync:h}=await import("fs"),{basename:m}=await import("path"),p=o??c;if(o&&h(o)&&f(o).isDirectory())p=Ft(o,m(c));Pd(p,d),console.log(`\u2713 Downloaded ${c} (${xo(d.length)}) \u2192 ${p}`)}async function vm(){dd(),Cg();let e=(s)=>Rn(s.workspace),t=(s)=>dr(s.workspace),n={state:{type:"string",choices:["open","untriaged","pending","doing","done","dropped","stuck"],default:"open",describe:"open (default) = marked and not done/dropped; untriaged = marked with no progress; stuck = unfinished with a reason flag"},in:{type:"string",describe:"Limit to a channel (#chan)"},from:{type:"string",describe:"Limit to a sender (@user, or 'me') \u2014 usually the person a task is waiting on"},n:{alias:"count",type:"number",default:50,describe:"Max results"},json:{type:"boolean",default:!1}},o=async(s,r)=>{let i={state:s.state??"open",mine:r||s.mine===!0,count:s.n??50,json:s.json===!0};if(s.in)i.in=s.in;if(s.from)i.from=s.from;let c=t(s);if(c)i.cookie=c;await Ng(e(s),i)};await wc(Uo(process.argv)).scriptName("slack").showHelpOnFail(!1).fail((s,r,i)=>{if(r)console.error(r.message),process.exit(1);console.error(s),console.error(""),i.showHelp(),process.exit(1)}).option("workspace",{alias:"w",type:"string",describe:"Workspace name"}).middleware(async(s)=>{let r=String((s._??[])[0]??"");if(!r||r==="auth"||r==="login"||r==="agent"||r==="sent")return;try{Rn(s.workspace)}catch(i){if((i instanceof Error?i.message:String(i)).startsWith("No profiles configured"))console.log(`No workspace configured. Let's set that up:
390
+ `),await zn(),process.exit(0);throw i}},!0).command("agent","Bot agent session status and command heartbeat",(s)=>kl(s,Cn)).command(["read [target]","msgs [target]"],"Browse messages",(s)=>s.positional("target",{type:"string",describe:"#channel, @user, or URL"}).option("limit",{alias:"n",type:"number",default:20,describe:"Number of messages"}).option("format",{type:"string",choices:["text","jsonl"],default:"text",describe:"jsonl exposes raw ts/user/text (incl. external-guest user IDs)"}).option("json",{type:"boolean",default:!1,describe:"Alias for --format=jsonl"}).option("unreplied",{type:"boolean",default:!1,describe:"Only messages whose last word (incl. thread replies) is not yours \u2014 i.e. awaiting your answer"}),async(s)=>{let r=e(s),i=s.json?"jsonl":s.format;if(s.target)await Ag(r,s.target,s.limit,i,s.unreplied,t(s));else await Ig(r)}).command("thread <target> <ts>","Show thread messages",(s)=>s.positional("target",{type:"string",demandOption:!0}).positional("ts",{type:"string",demandOption:!0}).option("limit",{alias:"n",type:"number",default:100}).option("format",{type:"string",choices:["text","jsonl"],default:"text",describe:"jsonl exposes raw ts/user/text (incl. external-guest user IDs)"}).option("json",{type:"boolean",default:!1,describe:"Alias for --format=jsonl"}),async(s)=>{let r=s.json?"jsonl":s.format;await Tg(e(s),s.target,s.ts,s.limit,r,t(s))}).command(["channel","channels","ch"],"Channel commands",(s)=>s.command(["ls","list"],"List channels",(r)=>r.option("limit",{alias:"n",type:"number",default:200}).option("filter",{alias:"f",type:"string"}).option("all",{type:"boolean",default:!1}).option("format",{type:"string",choices:["text","jsonl"],default:"text"}).option("json",{type:"boolean",default:!1,describe:"Alias for --format=jsonl"}),async(r)=>{await Pg(e(r),r.limit,r.filter,r.all,r.json?"jsonl":r.format,t(r))}).command("get <channel>","Show channel details",(r)=>r.positional("channel",{type:"string",demandOption:!0,describe:"#name or channel ID"}),async(r)=>{let i=e(r),c=t(r),a=r.channel,l=a.startsWith("#")||a.startsWith("@")||a.startsWith("C")||a.startsWith("G")||a.startsWith("D")?a:`#${a}`,u=await ue(i,l,c),d=T(await Qt(i,u,c)),f=T(d.channel),h=typeof f.name==="string"?f.name:u,p=f.is_im===!0?"@":"#",D=String(T(f.purpose).value??""),k=String(T(f.topic).value??""),x=f.num_members??f.member_count??"";if(console.log(`${p}${h} ${u}`),k)console.log(`topic: ${k}`);if(D)console.log(`purpose: ${D}`);if(x)console.log(`members: ${x}`);console.log(`private: ${f.is_private===!0}`)}).command(["create <name>","new <name>"],"Create a channel (confirm-hash safety gate)",(r)=>r.positional("name",{type:"string",demandOption:!0,describe:"Channel name (Slack lowercases it; no spaces)"}).option("private",{type:"boolean",default:!1,describe:"Create a private channel"}).option("invite",{type:"string",array:!0,default:[],describe:"Users to invite after creating (@handle or Uxxxx, repeatable)"}).option("code",{type:"string",describe:"Safety hash to confirm create"}),async(r)=>{let i=e(r),c=t(r),a=r.name.replace(/^#/,"").toLowerCase(),l=r.private===!0,u=r.invite.filter(Boolean),d=await rt(i,c),f=ge(a,String(l),u.join(","),d?.userId??"");if(r.code!==f)me(r.code,f,["--- Creating channel -------------------------",De(d,{pad:9}),` name: ${l?"\uD83D\uDD12 ":"#"}${a}`,` private: ${l}`,...u.length?[` invite: ${u.join(", ")}`]:[],"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);let h;try{h=await bu(i,a,l,c)}catch(m){console.error(m instanceof Error?m.message:String(m)),process.exit(1)}if(console.log(`\u2713 Created ${l?"\uD83D\uDD12 ":"#"}${h.name} (${h.id})`),u.length){let m=[];for(let p of u)try{m.push(p.startsWith("U")||p.startsWith("W")?p:await ht(i,p,c))}catch(D){console.error(` ! could not resolve ${p}: ${D instanceof Error?D.message:String(D)}`)}for(let p of m)try{let D=T(await ns(i,p,c)),k=T(D.user);if(k.is_ultra_restricted===!0)console.error(`\u26A0 ${p} is a single-channel guest \u2014 Slack restricts them to their one existing channel; this invite will likely report success but not actually add them.`);else if(k.is_restricted===!0)console.error(`\u26A0 ${p} is a multi-channel guest \u2014 double-check they were actually added (guest invites can silently no-op depending on workspace restrictions).`)}catch{}if(m.length)try{await xu(i,h.id,m,c),console.log(`\u2713 Invited ${m.length} member${m.length===1?"":"s"}`)}catch(p){console.error(` ! invite failed: ${p instanceof Error?p.message:String(p)}`)}}}).command(["rename <channel> <new-name>","mv <channel> <new-name>"],"Rename a channel (confirm-hash safety gate)",(r)=>r.positional("channel",{type:"string",demandOption:!0,describe:"#name, name, or channel ID (C\u2026/G\u2026)"}).positional("new-name",{type:"string",demandOption:!0,describe:"New channel name (Slack lowercases it; no spaces)"}).option("dry-run",{type:"boolean",default:!1,describe:"Resolve the channel and print old -> new without renaming"}).option("code",{type:"string",describe:"Safety hash to confirm rename"}),async(r)=>{let i=e(r),c=t(r),a=r.channel;if(a.startsWith("@"))console.error(`Error: ${a} is a DM \u2014 only channels can be renamed.`),process.exit(1);let l=a.startsWith("#")||/^[CG][A-Z0-9]{8,}$/.test(a)?a:`#${a}`,u=r.newName.replace(/^#/,"").toLowerCase(),d,f;try{d=await ue(i,l,c)}catch(D){console.error(`Error: could not resolve channel ${a}: ${D instanceof Error?D.message:String(D)}`),process.exit(1)}try{let D=T(T(await Qt(i,d,c)).channel);if(D.is_im===!0||D.is_mpim===!0)console.error(`Error: ${d} is a DM \u2014 only channels can be renamed.`),process.exit(1);f=typeof D.name==="string"?D.name:l.replace(/^#/,"")}catch(D){let k=D instanceof Error?D.message:String(D);if(/channel_not_found/.test(k))console.error(`Error: could not resolve channel ${a}: channel not found (or not visible to this token).`),process.exit(1);f=l.replace(/^#/,"")}if(r.dryRun===!0){console.log(`#${f} -> #${u} (${d})`),console.log("(dry run \u2014 conversations.rename not called)");return}let h=await rt(i,c),m=ge("rename",d,u,h?.userId??"");if(r.code!==m)me(r.code,m,["--- Renaming channel -------------------------",De(h,{pad:9}),` channel: ${d}`,` from: #${f}`,` to: #${u}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);let p;try{p=await ku(i,d,u,c)}catch(D){let x=(D instanceof Error?D.message:String(D)).match(/Slack error on conversations\.rename: (\w+)/)?.[1],C={name_taken:`Error: a channel named #${u} already exists.`,invalid_name:`Error: "${u}" is not a valid channel name (lowercase letters, numbers, hyphens, underscores; max 80 chars).`,invalid_name_specials:`Error: "${u}" contains characters Slack doesn't allow in channel names.`,invalid_name_maxlength:`Error: "${u}" is too long (max 80 chars).`,invalid_name_required:"Error: the new channel name can't be empty.",not_authorized:`Error: this token isn't allowed to rename #${f} (workspace settings may restrict renaming to admins or the channel creator).`,not_in_channel:`Error: this token isn't a member of #${f} \u2014 join it first.`,is_archived:`Error: #${f} is archived \u2014 unarchive it before renaming.`};console.error((x&&C[x])??ae(D)),process.exit(1)}console.log(`\u2713 Renamed #${f} -> #${p.name} (${p.id})`)}).demandCommand(1,"").showHelpOnFail(!0)).command(["user","usr"],"User commands",(s)=>s.command(["ls","list"],"List workspace members",(r)=>r.option("limit",{alias:"n",type:"number",default:200}).option("filter",{alias:"f",type:"string"}).option("format",{type:"string",choices:["text","jsonl","yaml"],default:"text"}).option("json",{type:"boolean",default:!1,describe:"Alias for --format=jsonl"}).option("external",{type:"boolean",default:!1,describe:"Also include people reachable only through Slack Connect shared channels \u2014 they are in ANOTHER workspace, so users.list never returns them (costs one API call per shared channel)"}),async(r)=>{let i=r.json?"jsonl":r.format,c=e(r),a=t(r),l=await Fu(c,a),u=r.filter?.toLowerCase(),d=X(l.members).map(T);if(r.external){let p=new Set(d.map((C)=>String(C.id))),D=T(await Qn(c,a)),k=X(D.channels).map(T).filter((C)=>C.is_ext_shared===!0&&!!C.name),x=new Set;for(let C of k)try{for(let F of await $u(c,String(C.id),a))if(!p.has(F))x.add(F)}catch{}for(let C of x)try{let F=T(await ns(c,C,a)),N=T(F.user);if(N.id)d.push(N)}catch{}}let f=d.filter((p)=>p.deleted!==!0&&p.is_bot!==!0&&String(p.id)!=="USLACKBOT").filter((p)=>{if(!u)return!0;let D=String(p.name??"").toLowerCase(),k=String(T(p.profile).real_name??"").toLowerCase(),x=String(T(p.profile).email??"").toLowerCase();return D.includes(u)||k.includes(u)||x.includes(u)}).slice(0,r.limit);if(i==="jsonl"){for(let p of f)console.log(JSON.stringify(p));return}if(i==="yaml"){for(let p of f){let D=function(k,x=""){if(k===null)return"null";if(typeof k==="string")return k.includes(`
385
391
  `)?`|
386
392
  ${k.split(`
387
393
  `).join(`
388
- `)}`:k;if(typeof k!=="object")return String(k);if(Array.isArray(k))return k.map((E)=>`
389
- ${x} - ${D(E,x+" ")}`).join("");return Object.entries(k).map(([E,F])=>`
390
- ${x} ${E}: ${D(F,x+" ")}`).join("")};console.log("---");for(let[k,x]of Object.entries(p))console.log(`${k}: ${D(x)}`)}return}let h=Intl.DateTimeFormat().resolvedOptions().timeZone,m=f.length?String(I(X(l.members).map(I)[0]??{}).team_id??""):"";for(let p of f){let D=I(p.profile),k=String(p.name??p.id),x=String(p.id??""),E=String(D.display_name||""),F=String(D.real_name||""),N=String(D.email||""),W=String(p.tz??""),v=[...new Set([E,F].filter((T)=>T&&T!==k))].join(" / "),J=W&&W!==h?W:"",Q=String(p.team_id??""),_=p.is_stranger===!0||m&&Q&&Q!==m?`external:${Q||"?"}`:p.is_ultra_restricted===!0?"single-channel guest":p.is_restricted===!0?"guest":"",C=[N,J].filter(Boolean).join(" ");console.log(`@${k} ${x} ${v}${C?" "+C:""}${_?` [${_}]`:""}`)}}).command("get <user>","Show user details",(r)=>r.positional("user",{type:"string",demandOption:!0,describe:"@handle or user ID"}),async(r)=>{let i=e(r),c=t(r),a=r.user.startsWith("@")?r.user:`@${r.user}`,l="";try{l=await pt(i,a,c)}catch(O){console.error(O instanceof Error?O.message:String(O)),process.exit(1)}let u=I(await ns(i,l,c)),d=I(u.user),f=I(d.profile),h=Intl.DateTimeFormat().resolvedOptions().timeZone,m=String(d.name??l),p=String(d.id??l),D=String(f.display_name||""),k=String(f.real_name||""),x=String(f.email||""),E=String(d.tz??""),F=String(f.phone||""),N=String(f.title||"");console.log(`@${m} ${p}`);let W=[...new Set([D,k].filter((O)=>O&&O!==m))];if(W.length)console.log(`name: ${W.join(" / ")}`);if(x)console.log(`email: ${x}`);if(F)console.log(`phone: ${F}`);if(N)console.log(`title: ${N}`);if(E&&E!==h)console.log(`tz: ${E}`)}).demandCommand(1,"").showHelpOnFail(!0)).command("news","Activity feed (mentions to you)",(s)=>s.option("limit",{alias:"l",type:"number",default:20}),async(s)=>{await Dg(e(s),s.limit)}).command("search <query>","Full-text search",(s)=>s.positional("query",{type:"string",demandOption:!0}).option("count",{alias:"n",type:"number",default:100}).option("json",{type:"boolean",default:!1,describe:"Output raw JSON"}),async(s)=>{await Cd(e(s),s.query,s.count,s.json,t(s))}).command("send <target> <message>","Send a message (confirm-hash safety gate)",(s)=>s.positional("target",{type:"string",demandOption:!0,describe:"#chan, @user, #chan:thread_ts, or permalink (a message permalink replies in its thread)"}).positional("message",{type:"string",demandOption:!0}).option("code",{type:"string",describe:"Safety hash to confirm send"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing ambiguous bare URL boundaries"}).option("channel-id",{type:"string",describe:"Raw channel ID"}).option("user-id",{type:"string",describe:"Raw user ID (opens DM)"}).option("as-bot",{type:"boolean",default:!1,describe:"Send via the bot token (xoxb / SLACK_BOT_TOKEN) so a DM notifies the recipient and can be two-way"}).option("broadcast",{type:"boolean",default:!1,describe:`Also send to channel: broadcast a threaded reply back to the channel (Slack's "Also send to #channel" checkbox). Only effective with a thread target.`}).option("mentions",{type:"boolean",default:!0,describe:"Convert @handle tokens to real <@USERID> mentions (on by default; resolves via users.list, then channel members for Slack Connect guests). Unresolved handles stay as plain text. The confirm preview shows the converted message before sending. Disable with --no-mentions for literal @text."}),async(s)=>{let r={target:s.target,message:s.message,allowUrlAdjacent:s["allow-url-adjacent"]};if(s.code)r.code=s.code;if(s["channel-id"])r.channelId=s["channel-id"];if(s["user-id"])r.userId=s["user-id"];if(s.broadcast)r.broadcast=!0;if(s.mentions!==!1){r.mentions=!0,r.mentionToken=e(s);let c=t(s);if(c)r.mentionCookie=c}let i;if(s["as-bot"]){let c=lt();if(!c)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
391
- Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(1);if(!r.channelId&&!r.userId&&r.target.startsWith("@"))try{r.userId=await pt(e(s),r.target,t(s))}catch(a){console.error(`Error: could not resolve ${r.target} to a user for the bot DM.
394
+ `)}`:k;if(typeof k!=="object")return String(k);if(Array.isArray(k))return k.map((C)=>`
395
+ ${x} - ${D(C,x+" ")}`).join("");return Object.entries(k).map(([C,F])=>`
396
+ ${x} ${C}: ${D(F,x+" ")}`).join("")};console.log("---");for(let[k,x]of Object.entries(p))console.log(`${k}: ${D(x)}`)}return}let h=Intl.DateTimeFormat().resolvedOptions().timeZone,m=f.length?String(T(X(l.members).map(T)[0]??{}).team_id??""):"";for(let p of f){let D=T(p.profile),k=String(p.name??p.id),x=String(p.id??""),C=String(D.display_name||""),F=String(D.real_name||""),N=String(D.email||""),W=String(p.tz??""),L=[...new Set([C,F].filter((I)=>I&&I!==k))].join(" / "),J=W&&W!==h?W:"",Q=String(p.team_id??""),_=p.is_stranger===!0||m&&Q&&Q!==m?`external:${Q||"?"}`:p.is_ultra_restricted===!0?"single-channel guest":p.is_restricted===!0?"guest":"",E=[N,J].filter(Boolean).join(" ");console.log(`@${k} ${x} ${L}${E?" "+E:""}${_?` [${_}]`:""}`)}}).command("get <user>","Show user details",(r)=>r.positional("user",{type:"string",demandOption:!0,describe:"@handle or user ID"}),async(r)=>{let i=e(r),c=t(r),a=r.user.startsWith("@")?r.user:`@${r.user}`,l="";try{l=await ht(i,a,c)}catch(O){console.error(O instanceof Error?O.message:String(O)),process.exit(1)}let u=T(await ns(i,l,c)),d=T(u.user),f=T(d.profile),h=Intl.DateTimeFormat().resolvedOptions().timeZone,m=String(d.name??l),p=String(d.id??l),D=String(f.display_name||""),k=String(f.real_name||""),x=String(f.email||""),C=String(d.tz??""),F=String(f.phone||""),N=String(f.title||"");console.log(`@${m} ${p}`);let W=[...new Set([D,k].filter((O)=>O&&O!==m))];if(W.length)console.log(`name: ${W.join(" / ")}`);if(x)console.log(`email: ${x}`);if(F)console.log(`phone: ${F}`);if(N)console.log(`title: ${N}`);if(C&&C!==h)console.log(`tz: ${C}`)}).demandCommand(1,"").showHelpOnFail(!0)).command("news","Activity feed (mentions to you)",(s)=>s.option("limit",{alias:"l",type:"number",default:20}),async(s)=>{await Og(e(s),s.limit)}).command("search <query>","Full-text search",(s)=>s.positional("query",{type:"string",demandOption:!0}).option("count",{alias:"n",type:"number",default:100}).option("json",{type:"boolean",default:!1,describe:"Output raw JSON"}),async(s)=>{await Bd(e(s),s.query,s.count,s.json,t(s))}).command("send <target> <message>","Send a message (confirm-hash safety gate)",(s)=>s.positional("target",{type:"string",demandOption:!0,describe:"#chan, @user, #chan:thread_ts, or permalink (a message permalink replies in its thread)"}).positional("message",{type:"string",demandOption:!0}).option("code",{type:"string",describe:"Safety hash to confirm send"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing ambiguous bare URL boundaries"}).option("channel-id",{type:"string",describe:"Raw channel ID"}).option("user-id",{type:"string",describe:"Raw user ID (opens DM)"}).option("as-bot",{type:"boolean",default:!1,describe:"Send via the bot token (xoxb / SLACK_BOT_TOKEN) so a DM notifies the recipient and can be two-way"}).option("broadcast",{type:"boolean",default:!1,describe:`Also send to channel: broadcast a threaded reply back to the channel (Slack's "Also send to #channel" checkbox). Only effective with a thread target.`}).option("mentions",{type:"boolean",default:!0,describe:"Convert @handle tokens to real <@USERID> mentions (on by default; resolves via users.list, then channel members for Slack Connect guests). Unresolved handles stay as plain text. The confirm preview shows the converted message before sending. Disable with --no-mentions for literal @text."}),async(s)=>{if(!String(s.message??"").trim())console.error("Error: message is empty"),process.exit(1);let r={target:s.target,message:s.message,allowUrlAdjacent:s["allow-url-adjacent"]};if(s.code)r.code=s.code;if(s["channel-id"])r.channelId=s["channel-id"];if(s["user-id"])r.userId=s["user-id"];if(s.broadcast)r.broadcast=!0;if(s.mentions!==!1){r.mentions=!0,r.mentionToken=e(s);let c=t(s);if(c)r.mentionCookie=c}let i;if(s["as-bot"]){let c=ut();if(!c)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
397
+ Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(1);if(!r.channelId&&!r.userId&&r.target.startsWith("@"))try{r.userId=await ht(e(s),r.target,t(s))}catch(a){console.error(`Error: could not resolve ${r.target} to a user for the bot DM.
392
398
  ${a instanceof Error?a.message:String(a)}
393
- Tip: pass --user-id <Uxxxx> to skip the lookup.`),process.exit(1)}i=c,r.asBot=!0}else{i=e(s);let c=t(s);if(c)r.cookie=c}try{await Kg(i,r)}catch(c){console.error(ce(c)),process.exit(1)}}).command("ask [target] [question] [choices..]","Ask a question with its choices pre-seeded as 1\uFE0F\u20E3..\uD83D\uDD1F reactions (confirm-hash safety gate)",(s)=>s.positional("target",{type:"string",describe:"#chan, @user, #chan:thread_ts, or permalink (omit with --waitFor)"}).positional("question",{type:"string",describe:"The question. Must @tag whoever may answer (@alice), or the whole channel (@here / @channel / @everyone) \u2014 only their answer counts. In a 1:1 DM the other party counts automatically."}).positional("choices",{type:"string",array:!0,describe:"Up to 10 choices, seeded as 1\uFE0F\u20E3..\uD83D\uDD1F reactions. Beyond 10 they are listed but answerable only by text. With none, the question asks for a free-text reply."}).option("code",{type:"string",describe:"Safety hash to confirm the ask"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing ambiguous bare URL boundaries"}).option("body",{type:"string",describe:"Extra context shown under the question"}).option("wait",{type:"boolean",default:!1,describe:"Block until answered; print ONLY the answer on stdout. Exit 0 = answered, 2 = nobody replied, 3 = transport failure, 4 = a reply matched several choices (stdout empty), 5 = a free-text reply that picked none of the choices (the reply is on stdout; NOT a decision \u2014 the question stays open)."}).option("waitFor",{type:"string",describe:"Collect the answer to a question already posted: pass its permalink. Nothing is posted. Same stdout/exit contract as --wait; --timeout 0 checks once and exits 2 if still open."}).option("after",{type:"string",describe:"With --waitFor: ignore text replies at or before this ts (the reply an exit 5 already delivered). Reactions still count."}).option("timeout",{type:"number",default:3600,describe:"Overall limit for --wait / --waitFor, in seconds (0 with --waitFor = check once)"}).option("channel-id",{type:"string",describe:"Raw channel ID"}).option("user-id",{type:"string",describe:"Raw user ID (opens DM)"}).option("as-bot",{type:"boolean",default:!1,describe:"Ask via the bot token (xoxb / SLACK_BOT_TOKEN) so a DM notifies the recipient"}),async(s)=>{let r=s.waitFor?String(s.waitFor):"",i=Number(s.timeout);if(!Number.isFinite(i)||i<0||i===0&&!r)console.error("Error: --timeout must be a positive number of seconds"),process.exit(_e);if(r){if(s.target||s.question||s.choices?.length)console.error("Error: --waitFor collects an existing question \u2014 do not also pass a target/question/choices."),process.exit(_e);let d,f;if(s["as-bot"]){let h=lt();if(!h)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
394
- Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(_e);d=h}else d=e(s),f=t(s);try{let h={link:r,timeout:i,asBot:!!s["as-bot"]};if(f)h.cookie=f;if(s.after){let m=String(s.after);if(!/^\d{10}\.\d{6}$/.test(m))console.error(`Error: --after needs a message ts like 1700000000.000100 (got ${q(m)})`),process.exit(_e);h.after=m}await tm(d,h)}catch(h){console.error(ce(h)),process.exit(_e)}return}if(!s.target)console.error("Error: target is required (or use --waitFor <permalink> to collect an answer)"),process.exit(_e);let c=String(s.question??"").trim();if(!c)console.error("Error: question is empty"),process.exit(_e);let a={allowUrlAdjacent:s["allow-url-adjacent"],target:s.target,question:c,choices:(s.choices??[]).map((d)=>String(d).trim()).filter(Boolean),timeout:i};if(s.code)a.code=s.code;if(s.body)a.body=s.body;if(s.wait)a.wait=!0;if(s["channel-id"])a.channelId=s["channel-id"];if(s["user-id"])a.userId=s["user-id"];a.mentionToken=e(s);let l=t(s);if(l)a.mentionCookie=l;let u;if(s["as-bot"]){let d=lt();if(!d)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
395
- Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(_e);if(!a.channelId&&!a.userId&&a.target.startsWith("@"))try{a.userId=await pt(e(s),a.target,t(s))}catch(f){console.error(`Error: could not resolve ${a.target} to a user for the bot DM.
399
+ Tip: pass --user-id <Uxxxx> to skip the lookup.`),process.exit(1)}i=c,r.asBot=!0}else{i=e(s);let c=t(s);if(c)r.cookie=c}try{await im(i,r)}catch(c){console.error(ae(c)),process.exit(1)}}).command("ask [target] [question] [choices..]","Ask a question with its choices pre-seeded as 1\uFE0F\u20E3..\uD83D\uDD1F reactions (confirm-hash safety gate)",(s)=>s.positional("target",{type:"string",describe:"#chan, @user, #chan:thread_ts, or permalink (omit with --waitFor)"}).positional("question",{type:"string",describe:"The question. Must @tag whoever may answer (@alice), or the whole channel (@here / @channel / @everyone) \u2014 only their answer counts. In a 1:1 DM the other party counts automatically."}).positional("choices",{type:"string",array:!0,describe:"Up to 10 choices, seeded as 1\uFE0F\u20E3..\uD83D\uDD1F reactions. Beyond 10 they are listed but answerable only by text. With none, the question asks for a free-text reply."}).option("code",{type:"string",describe:"Safety hash to confirm the ask"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing ambiguous bare URL boundaries"}).option("body",{type:"string",describe:"Extra context shown under the question"}).option("wait",{type:"boolean",default:!1,describe:"Block until answered; print ONLY the answer on stdout. Exit 0 = answered, 2 = nobody replied, 3 = transport failure, 4 = a reply matched several choices (stdout empty), 5 = a free-text reply that picked none of the choices (the reply is on stdout; NOT a decision \u2014 the question stays open)."}).option("waitFor",{type:"string",describe:"Collect the answer to a question already posted: pass its permalink. Nothing is posted. Same stdout/exit contract as --wait; --timeout 0 checks once and exits 2 if still open."}).option("after",{type:"string",describe:"With --waitFor: ignore text replies at or before this ts (the reply an exit 5 already delivered). Reactions still count."}).option("timeout",{type:"number",default:3600,describe:"Overall limit for --wait / --waitFor, in seconds (0 with --waitFor = check once)"}).option("channel-id",{type:"string",describe:"Raw channel ID"}).option("user-id",{type:"string",describe:"Raw user ID (opens DM)"}).option("as-bot",{type:"boolean",default:!1,describe:"Ask via the bot token (xoxb / SLACK_BOT_TOKEN) so a DM notifies the recipient"}),async(s)=>{let r=s.waitFor?String(s.waitFor):"",i=Number(s.timeout);if(!Number.isFinite(i)||i<0||i===0&&!r)console.error("Error: --timeout must be a positive number of seconds"),process.exit(_e);if(r){if(s.target||s.question||s.choices?.length)console.error("Error: --waitFor collects an existing question \u2014 do not also pass a target/question/choices."),process.exit(_e);let d,f;if(s["as-bot"]){let h=ut();if(!h)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
400
+ Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(_e);d=h}else d=e(s),f=t(s);try{let h={link:r,timeout:i,asBot:!!s["as-bot"]};if(f)h.cookie=f;if(s.after){let m=String(s.after);if(!/^\d{10}\.\d{6}$/.test(m))console.error(`Error: --after needs a message ts like 1700000000.000100 (got ${q(m)})`),process.exit(_e);h.after=m}await Dm(d,h)}catch(h){console.error(ae(h)),process.exit(_e)}return}if(!s.target)console.error("Error: target is required (or use --waitFor <permalink> to collect an answer)"),process.exit(_e);let c=String(s.question??"").trim();if(!c)console.error("Error: question is empty"),process.exit(_e);let a={allowUrlAdjacent:s["allow-url-adjacent"],target:s.target,question:c,choices:(s.choices??[]).map((d)=>String(d).trim()).filter(Boolean),timeout:i};if(s.code)a.code=s.code;if(s.body)a.body=s.body;if(s.wait)a.wait=!0;if(s["channel-id"])a.channelId=s["channel-id"];if(s["user-id"])a.userId=s["user-id"];a.mentionToken=e(s);let l=t(s);if(l)a.mentionCookie=l;let u;if(s["as-bot"]){let d=ut();if(!d)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
401
+ Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(_e);if(!a.channelId&&!a.userId&&a.target.startsWith("@"))try{a.userId=await ht(e(s),a.target,t(s))}catch(f){console.error(`Error: could not resolve ${a.target} to a user for the bot DM.
396
402
  ${f instanceof Error?f.message:String(f)}
397
- Tip: pass --user-id <Uxxxx> to skip the lookup.`),process.exit(_e)}u=d,a.asBot=!0}else{u=e(s);let d=t(s);if(d)a.cookie=d}try{await em(u,a)}catch(d){console.error(ce(d)),process.exit(_e)}}).command(["poll [target] [question] [choices..]","vote [target] [question] [choices..]"],"Post a poll with its choices pre-seeded as 1\uFE0F\u20E3..\uD83D\uDD1F reactions, then count them (confirm-hash safety gate)",(s)=>s.positional("target",{type:"string",describe:"#chan, @user, #chan:thread_ts, or permalink (omit with --results/--close)"}).positional("question",{type:"string",describe:"The question. @tags are optional here \u2014 unlike `ask`, a poll needs no addressee: anyone who can see it may vote."}).positional("choices",{type:"string",array:!0,describe:"2..10 choices, seeded as 1\uFE0F\u20E3..\uD83D\uDD1F reactions for voters to click"}).option("multi",{type:"boolean",default:!1,describe:"Let one person pick several choices (default: 1 \u4EBA 1 \u7968)"}).option("until",{type:"string",describe:"Deadline shown in the message (display only \u2014 closing is still `--close`)"}).option("results",{type:"string",describe:"Count an existing poll: pass its permalink. Posts nothing; only edit is the invalid-ballot notice in the poll itself (--no-notify to suppress)."}).option("close",{type:"string",describe:"Count an existing poll AND freeze the tally into the message. Only the poster can do this."}).option("names",{type:"boolean",default:!1,describe:"Also list who voted for what (stderr)"}).option("no-notify",{type:"boolean",default:!1,describe:"With --results: do not write the invalid-ballot notice back into the message (keeps it strictly read-only)"}).option("code",{type:"string",describe:"Safety hash to confirm the post"}).option("body",{type:"string",describe:"Extra context shown under the question"}).option("channel-id",{type:"string",describe:"Raw channel ID"}).option("user-id",{type:"string",describe:"Raw user ID (opens DM)"}).option("as-bot",{type:"boolean",default:!1,describe:"Post via the bot token (xoxb / SLACK_BOT_TOKEN) so a DM notifies the recipient \u2014 and so YOUR OWN vote counts, since the seeds are then the bot's"}),async(s)=>{let r=s.close?String(s.close):s.results?String(s.results):"";if(s.results&&s.close)console.error("Error: pass --results or --close, not both (--close counts as well)."),process.exit(Ye);let i=()=>{let f=lt();if(!f)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
398
- Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(Ye);return f};if(r){if(s.target||s.question||s.choices?.length)console.error("Error: --results/--close reads an existing poll \u2014 do not also pass a target/question/choices."),process.exit(Ye);let f=e(s),h=t(s);try{let m={link:r};if(s.close)m.close=!0;if(s.names)m.names=!0;if(s["no-notify"])m.noNotify=!0;if(h)m.cookie=h;if(s["as-bot"])m.writeToken=i();await rm(f,m)}catch(m){console.error(ce(m)),process.exit(Ye)}return}if(!s.target)console.error("Error: target is required (or use --results <permalink> to count a poll)"),process.exit(Ye);let c=String(s.question??"").trim();if(!c)console.error("Error: question is empty"),process.exit(Ye);let a=(s.choices??[]).map((f)=>String(f).trim()).filter(Boolean);if(a.length<2||a.length>gn)console.error(`Error: poll needs 2..${gn} choices (got ${a.length}). For a free-text question use \`slack ask\`.`),process.exit(Ye);let l={target:s.target,question:c,choices:a};if(s.multi)l.multi=!0;if(s.until)l.until=String(s.until);if(s.code)l.code=s.code;if(s.body)l.body=s.body;if(s["channel-id"])l.channelId=s["channel-id"];if(s["user-id"])l.userId=s["user-id"];l.mentionToken=e(s);let u=t(s);if(u)l.mentionCookie=u;let d;if(s["as-bot"]){let f=i();if(!l.channelId&&!l.userId&&l.target.startsWith("@"))try{l.userId=await pt(e(s),l.target,t(s))}catch(h){console.error(`Error: could not resolve ${l.target} to a user for the bot DM.
403
+ Tip: pass --user-id <Uxxxx> to skip the lookup.`),process.exit(_e)}u=d,a.asBot=!0}else{u=e(s);let d=t(s);if(d)a.cookie=d}try{await mm(u,a)}catch(d){console.error(ae(d)),process.exit(_e)}}).command(["poll [target] [question] [choices..]","vote [target] [question] [choices..]"],"Post a poll with its choices pre-seeded as 1\uFE0F\u20E3..\uD83D\uDD1F reactions, then count them (confirm-hash safety gate)",(s)=>s.positional("target",{type:"string",describe:"#chan, @user, #chan:thread_ts, or permalink (omit with --results/--close)"}).positional("question",{type:"string",describe:"The question. @tags are optional here \u2014 unlike `ask`, a poll needs no addressee: anyone who can see it may vote."}).positional("choices",{type:"string",array:!0,describe:"2..10 choices, seeded as 1\uFE0F\u20E3..\uD83D\uDD1F reactions for voters to click"}).option("multi",{type:"boolean",default:!1,describe:"Let one person pick several choices (default: 1 \u4EBA 1 \u7968)"}).option("until",{type:"string",describe:"Deadline shown in the message (display only \u2014 closing is still `--close`)"}).option("results",{type:"string",describe:"Count an existing poll: pass its permalink. Posts nothing; only edit is the invalid-ballot notice in the poll itself (--no-notify to suppress)."}).option("close",{type:"string",describe:"Count an existing poll AND freeze the tally into the message. Only the poster can do this."}).option("names",{type:"boolean",default:!1,describe:"Also list who voted for what (stderr)"}).option("no-notify",{type:"boolean",default:!1,describe:"With --results: do not write the invalid-ballot notice back into the message (keeps it strictly read-only)"}).option("code",{type:"string",describe:"Safety hash to confirm the post"}).option("body",{type:"string",describe:"Extra context shown under the question"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing ambiguous bare URL boundaries"}).option("channel-id",{type:"string",describe:"Raw channel ID"}).option("user-id",{type:"string",describe:"Raw user ID (opens DM)"}).option("as-bot",{type:"boolean",default:!1,describe:"Post via the bot token (xoxb / SLACK_BOT_TOKEN) so a DM notifies the recipient \u2014 and so YOUR OWN vote counts, since the seeds are then the bot's"}),async(s)=>{let r=s.close?String(s.close):s.results?String(s.results):"";if(s.results&&s.close)console.error("Error: pass --results or --close, not both (--close counts as well)."),process.exit(Ve);let i=()=>{let f=ut();if(!f)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
404
+ Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(Ve);return f};if(r){if(s.target||s.question||s.choices?.length)console.error("Error: --results/--close reads an existing poll \u2014 do not also pass a target/question/choices."),process.exit(Ve);let f=e(s),h=t(s);try{let m={link:r};if(s.close)m.close=!0;if(s.names)m.names=!0;if(s["no-notify"])m.noNotify=!0;if(h)m.cookie=h;if(s["as-bot"])m.writeToken=i();await km(f,m)}catch(m){console.error(ae(m)),process.exit(Ve)}return}if(!s.target)console.error("Error: target is required (or use --results <permalink> to count a poll)"),process.exit(Ve);let c=String(s.question??"").trim();if(!c)console.error("Error: question is empty"),process.exit(Ve);let a=(s.choices??[]).map((f)=>String(f).trim()).filter(Boolean);if(a.length<2||a.length>mn)console.error(`Error: poll needs 2..${mn} choices (got ${a.length}). For a free-text question use \`slack ask\`.`),process.exit(Ve);let l={target:s.target,question:c,choices:a};if(s.multi)l.multi=!0;if(s.until)l.until=String(s.until);if(s.code)l.code=s.code;if(s.body)l.body=s.body;if(s["allow-url-adjacent"])l.allowUrlAdjacent=!0;if(s["channel-id"])l.channelId=s["channel-id"];if(s["user-id"])l.userId=s["user-id"];l.mentionToken=e(s);let u=t(s);if(u)l.mentionCookie=u;let d;if(s["as-bot"]){let f=i();if(!l.channelId&&!l.userId&&l.target.startsWith("@"))try{l.userId=await ht(e(s),l.target,t(s))}catch(h){console.error(`Error: could not resolve ${l.target} to a user for the bot DM.
399
405
  ${h instanceof Error?h.message:String(h)}
400
- Tip: pass --user-id <Uxxxx> to skip the lookup.`),process.exit(Ye)}d=f,l.asBot=!0}else{d=e(s);let f=t(s);if(f)l.cookie=f}try{await sm(d,l)}catch(f){console.error(ce(f)),process.exit(Ye)}}).command("sent [query]","Search what THIS machine posted/edited (send, ask, poll, edit) and who sent it \u2014 read-only, local log",(s)=>s.positional("query",{type:"string",describe:"Substring of the message text (case-insensitive)"}).option("channel",{type:"string",describe:"Channel/DM id (C\u2026/D\u2026) or the target as typed (#eng, @bob)"}).option("since",{type:"string",describe:"Only newer than this: 30m, 2h, 7d, 1w, or an ISO date"}).option("session",{type:"string",describe:"Agent session id (prefix match)"}).option("cwd",{type:"string",describe:"Working directory the sender ran in (prefix match)"}).option("kind",{type:"string",choices:["send","ask","poll","edit"],describe:"Only this kind of write"}).option("json",{type:"boolean",default:!1,describe:"One JSON object per line (every recorded field)"}).option("count",{alias:"n",type:"number",default:50,describe:"Max rows (newest first)"}),(s)=>{let r;if(s.since!==void 0){if(r=Xl(String(s.since)),r===void 0)console.error(`Error: --since needs 30m / 2h / 7d / 1w or an ISO date (got ${q(String(s.since))})`),process.exit(1)}let i={limit:Number(s.count)||50};if(s.query)i.text=String(s.query);if(s.channel)i.channel=String(s.channel);if(r!==void 0)i.sinceMs=r;if(s.session)i.session=String(s.session);if(s.cwd){let a=ag(String(s.cwd));try{i.cwd=ig(a)}catch{i.cwd=a}}if(s.kind)i.kind=s.kind;let c=Gl(i);if(!c)console.error(`Error: ${ni}
401
- (${Gn()})`),process.exit(1);if(s.json){for(let a of c)console.log(JSON.stringify(a));return}if(!c.length){console.error(`No sent messages match (log: ${Gn()}).`);return}for(let a of c)console.log(Ag(a))}).command("doctor","Check the bot token (xoxb) can carry a two-way DM (scopes + Messages Tab)",(s)=>s,async()=>{let s=lt();if(!s)console.error(`Error: slack doctor checks the bot token, but no xoxb- token was found.
402
- Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(1);await im(s)}).command("schedule","Manage scheduled messages",(s)=>s.command("send <target> <message>","Schedule a message for later delivery",(r)=>r.positional("target",{type:"string",demandOption:!0,describe:"#chan, @user, #chan:thread_ts, or permalink (a message permalink replies in its thread)"}).positional("message",{type:"string",demandOption:!0}).option("at",{type:"string",demandOption:!0,describe:"Delivery time (ISO datetime or Unix ts)"}).option("code",{type:"string",describe:"Safety hash to confirm"}).option("channel-id",{type:"string",describe:"Raw channel ID"}).option("user-id",{type:"string",describe:"Raw user ID (opens DM)"}).option("as-bot",{type:"boolean",default:!1,describe:"Schedule via the bot token (xoxb / SLACK_BOT_TOKEN) so a DM notifies the recipient. Without it a scheduled DM to yourself is posted by you, and Slack never notifies you of your own message \u2014 it fires into silence."}),async(r)=>{let i={target:r.target,message:r.message,at:r.at};if(r.code)i.code=r.code;if(r["channel-id"])i.channelId=r["channel-id"],i.targetOverride=`--channel-id ${r["channel-id"]}`;if(r["user-id"])i.userId=r["user-id"],i.targetOverride=`--user-id ${r["user-id"]}`;let c;if(r["as-bot"]){let a=co();if(!i.channelId&&!i.userId&&i.target.startsWith("@"))try{i.userId=await pt(e(r),i.target,t(r))}catch(l){console.error(`Error: could not resolve ${i.target} to a user for the bot DM.
406
+ Tip: pass --user-id <Uxxxx> to skip the lookup.`),process.exit(Ve)}d=f,l.asBot=!0}else{d=e(s);let f=t(s);if(f)l.cookie=f}try{await wm(d,l)}catch(f){console.error(ae(f)),process.exit(Ve)}}).command("sent [query]","Search what THIS machine posted/edited (send, ask, poll, edit) and who sent it \u2014 read-only, local log",(s)=>s.positional("query",{type:"string",describe:"Substring of the message text (case-insensitive)"}).option("channel",{type:"string",describe:"Channel/DM id (C\u2026/D\u2026) or the target as typed (#eng, @bob)"}).option("since",{type:"string",describe:"Only newer than this: 30m, 2h, 7d, 1w, or an ISO date"}).option("session",{type:"string",describe:"Agent session id (prefix match)"}).option("cwd",{type:"string",describe:"Working directory the sender ran in (prefix match)"}).option("kind",{type:"string",choices:["send","ask","poll","edit"],describe:"Only this kind of write"}).option("json",{type:"boolean",default:!1,describe:"One JSON object per line (every recorded field)"}).option("count",{alias:"n",type:"number",default:50,describe:"Max rows (newest first)"}),(s)=>{let r;if(s.since!==void 0){if(r=eu(String(s.since)),r===void 0)console.error(`Error: --since needs 30m / 2h / 7d / 1w or an ISO date (got ${q(String(s.since))})`),process.exit(1)}let i={limit:Number(s.count)||50};if(s.query)i.text=String(s.query);if(s.channel)i.channel=String(s.channel);if(r!==void 0)i.sinceMs=r;if(s.session)i.session=String(s.session);if(s.cwd){let a=xg(String(s.cwd));try{i.cwd=kg(a)}catch{i.cwd=a}}if(s.kind)i.kind=s.kind;let c=Ql(i);if(!c)console.error(`Error: ${ii}
407
+ (${Xn()})`),process.exit(1);if(s.json){for(let a of c)console.log(JSON.stringify(a));return}if(!c.length){console.error(`No sent messages match (log: ${Xn()}).`);return}for(let a of c)console.log(Hg(a))}).command("doctor","Check the bot token (xoxb) can carry a two-way DM (scopes + Messages Tab)",(s)=>s,async()=>{let s=ut();if(!s)console.error(`Error: slack doctor checks the bot token, but no xoxb- token was found.
408
+ Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(1);await xm(s)}).command("schedule","Manage scheduled messages",(s)=>s.command("send <target> <message>","Schedule a message for later delivery",(r)=>r.positional("target",{type:"string",demandOption:!0,describe:"#chan, @user, #chan:thread_ts, or permalink (a message permalink replies in its thread)"}).positional("message",{type:"string",demandOption:!0}).option("at",{type:"string",demandOption:!0,describe:"Delivery time (ISO datetime or Unix ts)"}).option("code",{type:"string",describe:"Safety hash to confirm"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing ambiguous bare URL boundaries"}).option("channel-id",{type:"string",describe:"Raw channel ID"}).option("user-id",{type:"string",describe:"Raw user ID (opens DM)"}).option("as-bot",{type:"boolean",default:!1,describe:"Schedule via the bot token (xoxb / SLACK_BOT_TOKEN) so a DM notifies the recipient. Without it a scheduled DM to yourself is posted by you, and Slack never notifies you of your own message \u2014 it fires into silence."}),async(r)=>{if(!String(r.message??"").trim())console.error("Error: message is empty"),process.exit(1);let i={target:r.target,message:r.message,at:r.at};if(r.code)i.code=r.code;if(r["allow-url-adjacent"])i.allowUrlAdjacent=!0;if(r["channel-id"])i.channelId=r["channel-id"],i.targetOverride=`--channel-id ${r["channel-id"]}`;if(r["user-id"])i.userId=r["user-id"],i.targetOverride=`--user-id ${r["user-id"]}`;let c;if(r["as-bot"]){let a=po();if(!i.channelId&&!i.userId&&i.target.startsWith("@"))try{i.userId=await ht(e(r),i.target,t(r))}catch(l){console.error(`Error: could not resolve ${i.target} to a user for the bot DM.
403
409
  ${l instanceof Error?l.message:String(l)}
404
- Tip: pass --user-id <Uxxxx> to skip the lookup.`),process.exit(1)}c=a,i.asBot=!0}else{c=e(r);let a=t(r);if(a)i.cookie=a}await lm(c,i)}).command(["ls","list"],"List pending scheduled messages",(r)=>r.positional("target",{type:"string",describe:"#channel to filter by"}).option("channel-id",{type:"string",describe:"Raw channel ID"}).option("as-bot",{type:"boolean",default:!1,describe:"List what the BOT token scheduled. A message from `schedule send --as-bot` belongs to the app, so the user token's listing does not contain it \u2014 and an invisible pending message cannot be cancelled."}),async(r)=>{let i=r.target;if(r["as-bot"]){let c=co(),a=r["channel-id"];if(!a&&i?.startsWith("@"))a=await gd(i,c,e(r),t(r));await md(c,i,a);return}await md(e(r),i,r["channel-id"],t(r))}).command("rm <target> <id>","Delete a scheduled message",(r)=>r.positional("target",{type:"string",demandOption:!0,describe:"#channel or @user"}).positional("id",{type:"string",demandOption:!0,describe:"Scheduled message ID"}).option("code",{type:"string",describe:"Safety hash to confirm"}).option("channel-id",{type:"string",describe:"Raw channel ID"}).option("as-bot",{type:"boolean",default:!1,describe:"Cancel a message scheduled with `schedule send --as-bot`. It belongs to the bot token, so the user token cannot delete it."}),async(r)=>{let i={target:r.target,id:r.id};if(r.code)i.code=r.code;if(r["channel-id"])i.channelId=r["channel-id"],i.targetOverride=`--channel-id ${r["channel-id"]}`;if(r["as-bot"]){let a=co();if(!i.channelId&&i.target.startsWith("@"))i.channelId=await gd(i.target,a,e(r),t(r));i.asBot=!0,await Dd(a,i);return}let c=t(r);if(c)i.cookie=c;await Dd(e(r),i)}).demandCommand(1,"").showHelpOnFail(!0),()=>{}).command("edit <target> <newText>","Edit a sent message",(s)=>s.positional("target",{type:"string",demandOption:!0,describe:"#chan:ts, @user:ts, or permalink"}).positional("newText",{type:"string",demandOption:!0}).option("code",{type:"string",describe:"Safety hash to confirm edit"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing ambiguous bare URL boundaries"}).option("channel-id",{type:"string",describe:"Raw channel ID"}).option("mentions",{type:"boolean",default:!0,describe:"Convert @handle tokens in the new text to real <@USERID> mentions (on by default). Unresolved handles stay as plain text. Disable with --no-mentions for literal @text."}).option("as-bot",{type:"boolean",default:!1,describe:"Edit as the bot (xoxb / SLACK_BOT_TOKEN). REQUIRED to correct a message the bot posted: Slack only lets a token edit its OWN messages, so a bot-authored message is uneditable by the user token and chat.update returns cant_update_message. Address it by permalink or --channel-id; an @user target resolves against the BOT's DM list, which is where a bot-authored DM actually lives."}),async(s)=>{let r={target:s.target,newText:s.newText,allowUrlAdjacent:s["allow-url-adjacent"]};if(s.code)r.code=s.code;if(s["channel-id"])r.channelId=s["channel-id"];if(s.mentions!==!1)r.mentions=!0;let i;if(s["as-bot"]){let c=await ld(r.target,e(s),t(s),r.channelId);if(i=c.botToken,c.channelId&&!r.channelId)r.channelId=c.channelId;r.asBot=!0,r.mentionToken=e(s);let a=t(s);if(a)r.mentionCookie=a}else{i=e(s);let c=t(s);if(c)r.cookie=c}await Og(i,r)}).command("delete <target>","Delete a sent message (confirm-hash safety gate)",(s)=>s.positional("target",{type:"string",demandOption:!0,describe:"#chan:ts, @user:ts, or permalink"}).option("code",{type:"string",describe:"Safety hash to confirm delete"}).option("channel-id",{type:"string",describe:"Raw channel ID"}).option("as-bot",{type:"boolean",default:!1,describe:"Delete as the bot (xoxb / SLACK_BOT_TOKEN). REQUIRED for a message the bot posted: chat.delete refuses another token's message exactly as chat.update does."}),async(s)=>{let r={target:s.target};if(s.code)r.code=s.code;if(s["channel-id"])r.channelId=s["channel-id"];let i;if(s["as-bot"]){let c=await ld(r.target,e(s),t(s),r.channelId);if(i=c.botToken,c.channelId&&!r.channelId)r.channelId=c.channelId;r.asBot=!0}else{i=e(s);let c=t(s);if(c)r.cookie=c}await Pg(i,r)}).command("pinlog","Pinned status board: the pinned top-level message is the current state (edited in place, silent); each change is one thread reply (the log, notifies)",(s)=>{let r={type:"boolean",default:!1,describe:"Act via the bot token (xoxb / SLACK_BOT_TOKEN). A board the bot created can only be updated --as-bot: Slack lets a token edit only its own messages."},i=async(a)=>{if(a["as-bot"]){let u=co();if(typeof a.workspace==="string"){let d=t(a),[f,h]=await Promise.all([Yn(e(a),d),Yn(u)]);if(f.url!==h.url)console.error(`Error: --as-bot acts with SLACK_BOT_TOKEN, which belongs to ${h.url}, but -w ${a.workspace} is ${f.url}.
405
- Drop -w, or set SLACK_BOT_TOKEN to that workspace's bot token.`),process.exit(2)}return{token:u,asBot:!0}}let l=t(a);return{token:e(a),...l?{cookie:l}:{},asBot:!1}},c=(a)=>{console.error(ce(a)),process.exit(1)};return s.command("new <channel> [state] [reason]","Post a NEW board in a channel and pin it \u2014 the state is the top-level message; prints the board's id (C\u2026:ts)",(a)=>a.positional("channel",{type:"string",demandOption:!0,describe:"#chan or channel ID"}).positional("state",{type:"string",describe:"The whole state (\\n for newlines), or use --file"}).positional("reason",{type:"string",describe:"Optional: why the board exists \u2014 its first thread reply"}).option("file",{type:"string",describe:"Read the state from a file (- = stdin); then the only positional after <channel> is the reason"}).option("code",{type:"string",describe:"Safety hash to confirm (printed by the preview)"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing ambiguous bare URL boundaries"}).option("as-bot",r).example('slack pinlog new "#gtm" "\u8CA9\u58F2\u30D6\u30ED\u30C3\u30AB\u30FC\\n1. \u898B\u7A4D\u30C6\u30F3\u30D7\u30EC \u2014 \u672A"',"preview, then rerun with --code"),async(a)=>{let l=a.file!==void 0;if(l&&a.state!==void 0&&a.reason!==void 0)console.error("Error: with --file, pass only the reason after <channel> (the state comes from the file)."),process.exit(2);let u=l?ao(void 0,a.file):ao(a.state,void 0),d=l?a.state:a.reason;if(u===void 0)console.error("Error: the state is required (positional or --file)."),process.exit(2);let f=await i(a),h={target:a.channel,state:u,asBot:f.asBot,allowUrlAdjacent:a["allow-url-adjacent"]};if(d!==void 0)h.log=Ge(d);if(f.cookie)h.cookie=f.cookie;if(typeof a.workspace==="string")h.workspace=a.workspace;if(a.code)h.code=a.code;await Ng(f.token,h).catch(c)}).command("set <board> [state] [reason]","Change a board: replace its state (silent edit) AND post the reason in its thread (notifies)",(a)=>a.positional("board",{type:"string",demandOption:!0,describe:"The board: permalink, #chan:ts, or the id `new` printed"}).positional("state",{type:"string",describe:"The WHOLE new state, not a diff (or --file)"}).positional("reason",{type:"string",describe:"One short line: what changed and why (required)"}).option("file",{type:"string",describe:"Read the state from a file (- = stdin); then the only positional after <board> is the reason"}).option("adopt",{type:"boolean",default:!1,describe:"Allow a message WITHOUT the pinlog footer: turn a hand-run board into one"}).option("code",{type:"string",describe:"Safety hash to confirm (printed by the preview)"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing ambiguous bare URL boundaries"}).option("as-bot",r).example('slack pinlog set <board-link> "\u8CA9\u58F2\u30D6\u30ED\u30C3\u30AB\u30FC\\n1. \u898B\u7A4D\u30C6\u30F3\u30D7\u30EC \u2014 \u6E08" "\u898B\u7A4D\u30C6\u30F3\u30D7\u30EC: \u672A \u2192 \u6E08"',"").example('slack pinlog set <board-link> --file board.md "\u898B\u7A4D\u30C6\u30F3\u30D7\u30EC: \u672A \u2192 \u6E08"',"state from a file"),async(a)=>{let l=a.file!==void 0;if(l&&a.state!==void 0&&a.reason!==void 0)console.error("Error: with --file, pass only the reason after <board> (the state comes from the file)."),process.exit(2);let u=l?ao(void 0,a.file):ao(a.state,void 0),d=l?a.state:a.reason;if(u===void 0||d===void 0)console.error("Error: `pinlog set` needs the whole new state AND the reason: slack pinlog set <board> '<state>' '<reason>'\n Only a reason, state unchanged: slack pinlog note <board> '<reason>'"),process.exit(2);let f=await i(a),h={target:a.board,state:u,log:Ge(d),adopt:a.adopt,asBot:f.asBot,allowUrlAdjacent:a["allow-url-adjacent"]};if(typeof a.workspace==="string")h.workspace=a.workspace;if(f.cookie)h.cookie=f.cookie;if(a.code)h.code=a.code;await dd(f.token,h).catch(c)}).command("note <board> <reason>","Post only a reason in a board's thread (notifies); the state stays as is",(a)=>a.positional("board",{type:"string",demandOption:!0,describe:"The board: permalink, #chan:ts, or the id `new` printed"}).positional("reason",{type:"string",demandOption:!0,describe:"One short line, e.g. still blocked \u2014 chased X"}).option("code",{type:"string",describe:"Safety hash to confirm (printed by the preview)"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing ambiguous bare URL boundaries"}).option("as-bot",r),async(a)=>{let l=await i(a),u={target:a.board,log:Ge(a.reason),logOnly:!0,asBot:l.asBot,allowUrlAdjacent:a["allow-url-adjacent"]};if(typeof a.workspace==="string")u.workspace=a.workspace;if(l.cookie)u.cookie=l.cookie;if(a.code)u.code=a.code;await dd(l.token,u).catch(c)}).command(["get <board>","show <board>"],"Show a board's state and its log (read-only)",(a)=>a.positional("board",{type:"string",demandOption:!0,describe:"The board: permalink, #chan:ts, or C\u2026:ts"}).option("json",{type:"boolean",default:!1,describe:"One JSON object: {id, isPinlog, updated, head, log[]}"}).option("as-bot",r),async(a)=>{let l=await i(a);await vg(l.token,a.board,l.cookie,a.json).catch(c)}).command(["ls <channel>","list <channel>"],"List the boards in a channel, found by their footer (read-only)",(a)=>a.positional("channel",{type:"string",demandOption:!0}).option("limit",{alias:"n",type:"number",default:500,describe:"How many recent channel messages to scan"}).option("as-bot",r),async(a)=>{let l=await i(a);await Lg(l.token,a.channel,a.limit,l.cookie).catch(c)}).command("pin <board>",!1,(a)=>a.positional("board",{type:"string",demandOption:!0}).option("as-bot",r),async(a)=>{let l=await i(a);await jg(l.token,a.board,l.cookie).catch(c)}).demandCommand(1,"Pick one: ls | get | new | set | note")},()=>{}).command("react <target> <emoji>","Add (or --remove) an emoji reaction \u2014 a lightweight ack that doesn't grow the thread",(s)=>s.positional("target",{type:"string",demandOption:!0,describe:"#chan:ts, @user:ts, or permalink"}).positional("emoji",{type:"string",demandOption:!0,describe:"Emoji shortcode without colons (e.g. eyes, white_check_mark, hourglass)"}).option("remove",{type:"boolean",default:!1,describe:"Remove the reaction instead of adding it"}).option("channel-id",{type:"string",describe:"Raw channel ID"}),async(s)=>{let r={target:s.target,emoji:s.emoji};if(s.remove)r.remove=!0;if(s["channel-id"])r.channelId=s["channel-id"];let i=t(s);if(i)r.cookie=i;try{await Wg(e(s),r)}catch(c){console.error(ce(c)),process.exit(1)}}).command("todo","Reaction-backed task tracking (:pushpin: marks a task, progress lives in a second reaction)",(s)=>s.option("cache",{type:"boolean",default:!0,describe:"Use ~/.config/slack-cli/cache.json for channel/user lookups (--no-cache to bypass)"}).middleware((r)=>{if(r.cache===!1)mi(!1)}).command(["ls","list"],"List everyone's tasks (has: \u2014 read-only, one search per run)",(r)=>r.options(n).option("mine",{type:"boolean",default:!1,describe:"Only your own reactions (hasmy:) \u2014 same as `slack mytodo ls`"}).option("shared",{type:"boolean",default:!1,hidden:!0,describe:"Deprecated \u2014 anyone's reactions is the default for `todo ls`"}),async(r)=>{await o(r,!1)}).command("set <target> <state>","Move a task to a progress state (adds the new reaction before removing the old one)",(r)=>r.positional("target",{type:"string",demandOption:!0,describe:"#chan:ts or permalink"}).positional("state",{type:"string",demandOption:!0,choices:["pending","doing","done","dropped"]}).option("channel-id",{type:"string",describe:"Raw channel ID"}),async(r)=>{let i={target:r.target,state:r.state};if(r["channel-id"])i.channelId=r["channel-id"];let c=t(r);if(c)i.cookie=c;try{await kg(e(r),i)}catch(a){console.error(ce(a)),process.exit(1)}}).command("flag <target> <flag>","Add (or --remove) a reason flag (alert | needs-discussion | waiting | blocked) \u2014 flags stack, independent of progress",(r)=>r.positional("target",{type:"string",demandOption:!0,describe:"#chan:ts or permalink"}).positional("flag",{type:"string",demandOption:!0,choices:["alert","needs-discussion","waiting","blocked"],describe:"waiting = the other party in this conversation owes a reply; blocked = stuck on something outside it"}).option("remove",{type:"boolean",default:!1,describe:"Remove the flag instead of adding it"}).option("channel-id",{type:"string",describe:"Raw channel ID"}),async(r)=>{let i={target:r.target,flag:r.flag};if(r.remove)i.remove=!0;if(r["channel-id"])i.channelId=r["channel-id"];let c=t(r);if(c)i.cookie=c;try{await xg(e(r),i)}catch(a){console.error(ce(a)),process.exit(1)}}).command("doctor","Find messages carrying two or more progress reactions (--fix repairs them)",(r)=>r.option("in",{type:"string",demandOption:!0,describe:"Channel to scan (#chan)"}).option("fix",{type:"boolean",default:!1,describe:"Repair findings (keeps the highest-priority state)"}).option("limit",{type:"number",default:gi,describe:"Max messages to scan"}).option("channel-id",{type:"string",describe:"Raw channel ID"}),async(r)=>{let i={channel:r.in,limit:r.limit};if(r.fix)i.fix=!0;if(r["channel-id"])i.channelId=r["channel-id"];let c=t(r);if(c)i.cookie=c;await Cg(e(r),i)}).demandCommand(1,"Specify a todo subcommand (ls, set, flag, doctor)"),()=>{}).command("mytodo","Tasks carrying YOUR reactions (hasmy:) \u2014 the my-only half of `todo`",(s)=>s.option("cache",{type:"boolean",default:!0,describe:"Use ~/.config/slack-cli/cache.json for channel/user lookups (--no-cache to bypass)"}).middleware((r)=>{if(r.cache===!1)mi(!1)}).command(["ls","list"],"List tasks you have reacted to (hasmy: \u2014 read-only, one search per run)",(r)=>r.options(n),async(r)=>{await o(r,!0)}).demandCommand(1,"Specify a mytodo subcommand (ls)"),()=>{}).command("upload <target> <file..>","Upload one or more files to a channel or DM",(s)=>s.positional("target",{type:"string",demandOption:!0,describe:"#chan, @user, #chan:thread_ts, or permalink (a message permalink replies in its thread)"}).positional("file",{type:"string",array:!0,demandOption:!0,describe:"Path(s) to file(s)"}).option("title",{type:"string",describe:"Title (single file only)"}).option("comment",{type:"string",describe:"Initial comment (first file)"}).option("code",{type:"string",describe:"4-hex safety code to confirm upload"}).option("channel-id",{type:"string"}).option("user-id",{type:"string"}),async(s)=>{let r={target:s.target,filePaths:s.file};if(s.title)r.title=s.title;if(s.comment)r.comment=s.comment;if(s.code)r.code=s.code;if(s["channel-id"])r.channelId=s["channel-id"];if(s["user-id"])r.userId=s["user-id"];let i=t(s);if(i)r.cookie=i;await um(e(s),r)}).command("files","File commands",(s)=>s.command(["ls","list"],"List files visible to you (files.list)",(r)=>r.option("limit",{alias:"l",type:"number",default:100,describe:"Max files to list"}).option("type",{alias:"t",type:"string",describe:"Slack type filter: images, pdfs, gdocs, snippets, zips, spaces, all"}).option("channel",{alias:"c",type:"string",describe:"Only files in this channel (#name, @user, ID, or permalink)"}).option("user",{alias:"u",type:"string",describe:"Only files from this raw user ID"}).option("format",{type:"string",choices:["text","jsonl"],default:"text"}).option("json",{type:"boolean",default:!1,describe:"Alias for --format=jsonl"}),async(r)=>{let i={limit:r.limit,format:r.json?"jsonl":r.format};if(r.type)i.types=r.type;if(r.channel)i.channel=r.channel;if(r.user)i.user=r.user;await dm(e(r),t(r),i)}).demandCommand(1,"").showHelpOnFail(!0),()=>{}).command("lists","Slack Lists \u2014 read rows (lists <ref>), or create / add / set (gated, as the bot)",(s)=>s.command("create <name>","Create a Slack List (confirm-hash safety gate; bot token, lists:write)",(r)=>r.positional("name",{type:"string",demandOption:!0,describe:"List name"}).option("col",{type:"string",array:!0,default:[],describe:"Column name:type (text|select|user|link|date|number|checkbox); select takes name:select:a,b,c. First is the primary text column. Repeatable"}).option("todo",{type:"boolean",default:!1,describe:"Todo mode: adds Completed / Assignee / Due date columns"}).option("code",{type:"string",describe:"Safety hash to confirm create"}),async(r)=>{try{let i={name:r.name,cols:r.col,todo:r.todo===!0};if(r.code!==void 0)i.code=r.code;await gm(i)}catch(i){console.error(ce(i)),process.exit(1)}}).command("add <list> <text>","Add a row to a Slack List (confirm-hash safety gate; bot token)",(r)=>r.positional("list",{type:"string",demandOption:!0,describe:"List URL or F-id"}).positional("text",{type:"string",demandOption:!0,describe:"Primary (first text) column value"}).option("set",{type:"string",array:!0,default:[],describe:"Other cells: column=value (repeatable)"}).option("code",{type:"string",describe:"Safety hash to confirm add"}),async(r)=>{try{let i={list:r.list,text:r.text,sets:r.set};if(r.code!==void 0)i.code=r.code;await mm(i)}catch(i){console.error(ce(i)),process.exit(1)}}).command("set <list> <row>","Update cells of a Slack List row; --done checks it off (confirm-hash safety gate; bot token)",(r)=>r.positional("list",{type:"string",demandOption:!0,describe:"List URL or F-id"}).positional("row",{type:"string",demandOption:!0,describe:"Row id (Rec\u2026), as printed by lists add / lists <ref>"}).option("set",{type:"string",array:!0,default:[],describe:"column=value (repeatable)"}).option("done",{type:"boolean",describe:"Check the row off (--no-done to uncheck); needs a todo-mode list"}).option("code",{type:"string",describe:"Safety hash to confirm update"}),async(r)=>{try{let i={list:r.list,row:r.row,sets:r.set};if(r.done!==void 0)i.done=r.done;if(r.code!==void 0)i.code=r.code;await Dm(i)}catch(i){console.error(ce(i)),process.exit(1)}}).command("share <list>","Grant users or channels access to a Slack List (confirm-hash safety gate; bot token)",(r)=>r.positional("list",{type:"string",demandOption:!0,describe:"List URL or F-id"}).option("user",{type:"string",array:!0,default:[],describe:"User ID (U\u2026), repeatable"}).option("channel",{type:"string",array:!0,default:[],describe:"Channel ID (C\u2026), repeatable"}).option("level",{type:"string",choices:["read","write","owner"],default:"write"}).option("code",{type:"string",describe:"Safety hash to confirm share"}),async(r)=>{try{let i={list:r.list,users:r.user,channels:r.channel,level:r.level};if(r.code!==void 0)i.code=r.code;await ym(i)}catch(i){console.error(ce(i)),process.exit(1)}}).command("$0 <ref>","Read a Slack List's rows (by list URL or F-id) \u2014 read-only",(r)=>r.positional("ref",{type:"string",demandOption:!0,describe:"List URL (\u2026/lists/<TEAM>/<F-id>) or bare F-id"}).option("limit",{alias:"l",type:"number",default:100,describe:"Max rows to show"}).option("format",{type:"string",choices:["text","jsonl"],default:"text"}).option("json",{type:"boolean",default:!1,describe:"Alias for --format=jsonl (raw records)"}).option("as-bot",{type:"boolean",default:!1,describe:"Read with the bot token (SLACK_BOT_TOKEN, lists:read) via the public API instead of the user session"}),async(r)=>{let i=r.json?"jsonl":r.format;try{let c=r.asBot===!0;await pm(c?"":e(r),c?void 0:t(r),r.ref,{limit:r.limit,format:i,asBot:c})}catch(c){console.error(ce(c)),process.exit(1)}})).command("download <ref> [dest]","Download a file attachment (by file ID or file permalink) to disk",(s)=>s.positional("ref",{type:"string",demandOption:!0,describe:"File ID (F\u2026) or Slack file permalink"}).positional("dest",{type:"string",describe:"Output path or directory (default: ./<filename>)"}),async(s)=>{await bm(e(s),t(s),s.ref,s.dest)}).command("dump","Bulk export channel history as markdown",(s)=>s.option("days",{alias:"d",type:"number",default:7,describe:"Days of history"}).option("limit",{alias:"l",type:"number",default:200}).option("filter",{alias:"f",type:"string",describe:"Filter channel names"}),async(s)=>{await Eg(e(s),s.days,s.limit,s.filter)}).command("drafts","Manage message drafts (requires xoxc desktop token)",(s)=>s.command(["$0","ls","list"],"List pending drafts",(r)=>r.option("all",{alias:"a",type:"boolean",default:!1,describe:"Include sent drafts"}),async(r)=>{await _g(e(r),t(r),r.all)}).command(["new <channel> [text..]","save <channel> [text..]"],"Create a draft",(r)=>r.positional("channel",{type:"string",demandOption:!0}).positional("text",{type:"string",array:!0,default:[]}),async(r)=>{let i=e(r),c=t(r),a=r.text.join(" ");if(!a)console.error("Usage: slack drafts new <#channel|@user> <text>"),process.exit(2);let l=await he(i,r.channel,c),u=await Cu(i,l,a,c);console.log(`\u2713 Draft created (id: ${I(u.draft).id??"?"})`)}).command("get <id>","Show a draft",(r)=>r.positional("id",{type:"string",demandOption:!0}),async(r)=>{await Fg(e(r),t(r),r.id)}).command(["edit <id> [text..]","update <id> [text..]"],"Edit a draft",(r)=>r.positional("id",{type:"string",demandOption:!0}).positional("text",{type:"string",array:!0,default:[]}).option("code",{type:"string"}),async(r)=>{let i=e(r),c=t(r),a=r.text.join(" ");if(!a)console.error("Usage: slack drafts edit <id> <new-text>"),process.exit(2);let l=await ts(i,c),u=X(l.drafts).map(I).find((p)=>String(p.id)===r.id);if(!u)console.error(`Draft not found: ${r.id}`),process.exit(1);let d=po(u),f=await it(i,c),h=De(d,a,f?.userId??"");if(r.code!==h)ye(r.code,h,["--- Editing draft as -------------------------",we(f),"--- Current draft ----------------------------",...d.split(`
410
+ Tip: pass --user-id <Uxxxx> to skip the lookup.`),process.exit(1)}c=a,i.asBot=!0}else{c=e(r);let a=t(r);if(a)i.cookie=a}await Sm(c,i)}).command(["ls","list"],"List pending scheduled messages",(r)=>r.positional("target",{type:"string",describe:"#channel to filter by"}).option("channel-id",{type:"string",describe:"Raw channel ID"}).option("as-bot",{type:"boolean",default:!1,describe:"List what the BOT token scheduled. A message from `schedule send --as-bot` belongs to the app, so the user token's listing does not contain it \u2014 and an invisible pending message cannot be cancelled."}),async(r)=>{let i=r.target;if(r["as-bot"]){let c=po(),a=r["channel-id"];if(!a&&i?.startsWith("@"))a=await $d(i,c,e(r),t(r));await Ad(c,i,a);return}await Ad(e(r),i,r["channel-id"],t(r))}).command("rm <target> <id>","Delete a scheduled message",(r)=>r.positional("target",{type:"string",demandOption:!0,describe:"#channel or @user"}).positional("id",{type:"string",demandOption:!0,describe:"Scheduled message ID"}).option("code",{type:"string",describe:"Safety hash to confirm"}).option("channel-id",{type:"string",describe:"Raw channel ID"}).option("as-bot",{type:"boolean",default:!1,describe:"Cancel a message scheduled with `schedule send --as-bot`. It belongs to the bot token, so the user token cannot delete it."}),async(r)=>{let i={target:r.target,id:r.id};if(r.code)i.code=r.code;if(r["channel-id"])i.channelId=r["channel-id"],i.targetOverride=`--channel-id ${r["channel-id"]}`;if(r["as-bot"]){let a=po();if(!i.channelId&&i.target.startsWith("@"))i.channelId=await $d(i.target,a,e(r),t(r));i.asBot=!0,await Td(a,i);return}let c=t(r);if(c)i.cookie=c;await Td(e(r),i)}).demandCommand(1,"").showHelpOnFail(!0),()=>{}).command("edit <target> <newText>","Edit a sent message",(s)=>s.positional("target",{type:"string",demandOption:!0,describe:"#chan:ts, @user:ts, or permalink"}).positional("newText",{type:"string",demandOption:!0}).option("code",{type:"string",describe:"Safety hash to confirm edit"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing ambiguous bare URL boundaries"}).option("channel-id",{type:"string",describe:"Raw channel ID"}).option("mentions",{type:"boolean",default:!0,describe:"Convert @handle tokens in the new text to real <@USERID> mentions (on by default). Unresolved handles stay as plain text. Disable with --no-mentions for literal @text."}).option("as-bot",{type:"boolean",default:!1,describe:"Edit as the bot (xoxb / SLACK_BOT_TOKEN). REQUIRED to correct a message the bot posted: Slack only lets a token edit its OWN messages, so a bot-authored message is uneditable by the user token and chat.update returns cant_update_message. Address it by permalink or --channel-id; an @user target resolves against the BOT's DM list, which is where a bot-authored DM actually lives."}),async(s)=>{let r={target:s.target,newText:s.newText,allowUrlAdjacent:s["allow-url-adjacent"]};if(s.code)r.code=s.code;if(s["channel-id"])r.channelId=s["channel-id"];if(s.mentions!==!1)r.mentions=!0;let i;if(s["as-bot"]){let c=await xd(r.target,e(s),t(s),r.channelId);if(i=c.botToken,c.channelId&&!r.channelId)r.channelId=c.channelId;r.asBot=!0,r.mentionToken=e(s);let a=t(s);if(a)r.mentionCookie=a}else{i=e(s);let c=t(s);if(c)r.cookie=c}await Gg(i,r)}).command("delete <target>","Delete a sent message (confirm-hash safety gate)",(s)=>s.positional("target",{type:"string",demandOption:!0,describe:"#chan:ts, @user:ts, or permalink"}).option("code",{type:"string",describe:"Safety hash to confirm delete"}).option("channel-id",{type:"string",describe:"Raw channel ID"}).option("as-bot",{type:"boolean",default:!1,describe:"Delete as the bot (xoxb / SLACK_BOT_TOKEN). REQUIRED for a message the bot posted: chat.delete refuses another token's message exactly as chat.update does."}),async(s)=>{let r={target:s.target};if(s.code)r.code=s.code;if(s["channel-id"])r.channelId=s["channel-id"];let i;if(s["as-bot"]){let c=await xd(r.target,e(s),t(s),r.channelId);if(i=c.botToken,c.channelId&&!r.channelId)r.channelId=c.channelId;r.asBot=!0}else{i=e(s);let c=t(s);if(c)r.cookie=c}await Xg(i,r)}).command("pinlog","Pinned status board: the pinned top-level message is the current state (edited in place, silent); each change is one thread reply (the log, notifies)",(s)=>{let r={type:"boolean",default:!1,describe:"Act via the bot token (xoxb / SLACK_BOT_TOKEN). A board the bot created can only be updated --as-bot: Slack lets a token edit only its own messages."},i=async(a)=>{if(a["as-bot"]){let u=po();if(typeof a.workspace==="string"){let d=t(a),[f,h]=await Promise.all([Dn(e(a),d),Dn(u)]);if(f.url!==h.url)console.error(`Error: --as-bot acts with SLACK_BOT_TOKEN, which belongs to ${h.url}, but -w ${a.workspace} is ${f.url}.
411
+ Drop -w, or set SLACK_BOT_TOKEN to that workspace's bot token.`),process.exit(2)}return{token:u,asBot:!0}}let l=t(a);return{token:e(a),...l?{cookie:l}:{},asBot:!1}},c=(a)=>{console.error(ae(a)),process.exit(1)};return s.command("new <channel> [state] [reason]","Post a NEW board in a channel and pin it \u2014 the state is the top-level message; prints the board's id (C\u2026:ts)",(a)=>a.positional("channel",{type:"string",demandOption:!0,describe:"#chan or channel ID"}).positional("state",{type:"string",describe:"The whole state (\\n for newlines), or use --file"}).positional("reason",{type:"string",describe:"Optional: why the board exists \u2014 its first thread reply"}).option("file",{type:"string",describe:"Read the state from a file (- = stdin); then the only positional after <channel> is the reason"}).option("code",{type:"string",describe:"Safety hash to confirm (printed by the preview)"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing ambiguous bare URL boundaries"}).option("as-bot",r).example('slack pinlog new "#gtm" "\u8CA9\u58F2\u30D6\u30ED\u30C3\u30AB\u30FC\\n1. \u898B\u7A4D\u30C6\u30F3\u30D7\u30EC \u2014 \u672A"',"preview, then rerun with --code"),async(a)=>{let l=a.file!==void 0;if(l&&a.state!==void 0&&a.reason!==void 0)console.error("Error: with --file, pass only the reason after <channel> (the state comes from the file)."),process.exit(2);let u=l?fo(void 0,a.file):fo(a.state,void 0),d=l?a.state:a.reason;if(u===void 0)console.error("Error: the state is required (positional or --file)."),process.exit(2);let f=await i(a),h={target:a.channel,state:u,asBot:f.asBot,allowUrlAdjacent:a["allow-url-adjacent"]};if(d!==void 0)h.log=Xe(d);if(f.cookie)h.cookie=f.cookie;if(typeof a.workspace==="string")h.workspace=a.workspace;if(a.code)h.code=a.code;await Vg(f.token,h).catch(c)}).command("set <board> [state] [reason]","Change a board: replace its state (silent edit) AND post the reason in its thread (notifies)",(a)=>a.positional("board",{type:"string",demandOption:!0,describe:"The board: permalink, #chan:ts, or the id `new` printed"}).positional("state",{type:"string",describe:"The WHOLE new state, not a diff (or --file)"}).positional("reason",{type:"string",describe:"One short line: what changed and why (required)"}).option("file",{type:"string",describe:"Read the state from a file (- = stdin); then the only positional after <board> is the reason"}).option("adopt",{type:"boolean",default:!1,describe:"Allow a message WITHOUT the pinlog footer: turn a hand-run board into one"}).option("code",{type:"string",describe:"Safety hash to confirm (printed by the preview)"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing ambiguous bare URL boundaries"}).option("as-bot",r).example('slack pinlog set <board-link> "\u8CA9\u58F2\u30D6\u30ED\u30C3\u30AB\u30FC\\n1. \u898B\u7A4D\u30C6\u30F3\u30D7\u30EC \u2014 \u6E08" "\u898B\u7A4D\u30C6\u30F3\u30D7\u30EC: \u672A \u2192 \u6E08"',"").example('slack pinlog set <board-link> --file board.md "\u898B\u7A4D\u30C6\u30F3\u30D7\u30EC: \u672A \u2192 \u6E08"',"state from a file"),async(a)=>{let l=a.file!==void 0;if(l&&a.state!==void 0&&a.reason!==void 0)console.error("Error: with --file, pass only the reason after <board> (the state comes from the file)."),process.exit(2);let u=l?fo(void 0,a.file):fo(a.state,void 0),d=l?a.state:a.reason;if(u===void 0||d===void 0)console.error("Error: `pinlog set` needs the whole new state AND the reason: slack pinlog set <board> '<state>' '<reason>'\n Only a reason, state unchanged: slack pinlog note <board> '<reason>'"),process.exit(2);let f=await i(a),h={target:a.board,state:u,log:Xe(d),adopt:a.adopt,asBot:f.asBot,allowUrlAdjacent:a["allow-url-adjacent"]};if(typeof a.workspace==="string")h.workspace=a.workspace;if(f.cookie)h.cookie=f.cookie;if(a.code)h.code=a.code;await Cd(f.token,h).catch(c)}).command("note <board> <reason>","Post only a reason in a board's thread (notifies); the state stays as is",(a)=>a.positional("board",{type:"string",demandOption:!0,describe:"The board: permalink, #chan:ts, or the id `new` printed"}).positional("reason",{type:"string",demandOption:!0,describe:"One short line, e.g. still blocked \u2014 chased X"}).option("code",{type:"string",describe:"Safety hash to confirm (printed by the preview)"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing ambiguous bare URL boundaries"}).option("as-bot",r),async(a)=>{let l=await i(a),u={target:a.board,log:Xe(a.reason),logOnly:!0,asBot:l.asBot,allowUrlAdjacent:a["allow-url-adjacent"]};if(typeof a.workspace==="string")u.workspace=a.workspace;if(l.cookie)u.cookie=l.cookie;if(a.code)u.code=a.code;await Cd(l.token,u).catch(c)}).command(["get <board>","show <board>"],"Show a board's state and its log (read-only)",(a)=>a.positional("board",{type:"string",demandOption:!0,describe:"The board: permalink, #chan:ts, or C\u2026:ts"}).option("json",{type:"boolean",default:!1,describe:"One JSON object: {id, isPinlog, updated, head, log[]}"}).option("as-bot",r),async(a)=>{let l=await i(a);await em(l.token,a.board,l.cookie,a.json).catch(c)}).command(["ls <channel>","list <channel>"],"List the boards in a channel, found by their footer (read-only)",(a)=>a.positional("channel",{type:"string",demandOption:!0}).option("limit",{alias:"n",type:"number",default:500,describe:"How many recent channel messages to scan"}).option("as-bot",r),async(a)=>{let l=await i(a);await tm(l.token,a.channel,a.limit,l.cookie).catch(c)}).command("pin <board>",!1,(a)=>a.positional("board",{type:"string",demandOption:!0}).option("as-bot",r),async(a)=>{let l=await i(a);await nm(l.token,a.board,l.cookie).catch(c)}).demandCommand(1,"Pick one: ls | get | new | set | note")},()=>{}).command("react <target> <emoji>","Add (or --remove) an emoji reaction \u2014 a lightweight ack that doesn't grow the thread",(s)=>s.positional("target",{type:"string",demandOption:!0,describe:"#chan:ts, @user:ts, or permalink"}).positional("emoji",{type:"string",demandOption:!0,describe:"Emoji shortcode without colons (e.g. eyes, white_check_mark, hourglass)"}).option("remove",{type:"boolean",default:!1,describe:"Remove the reaction instead of adding it"}).option("channel-id",{type:"string",describe:"Raw channel ID"}),async(s)=>{let r={target:s.target,emoji:s.emoji};if(s.remove)r.remove=!0;if(s["channel-id"])r.channelId=s["channel-id"];let i=t(s);if(i)r.cookie=i;try{await sm(e(s),r)}catch(c){console.error(ae(c)),process.exit(1)}}).command("todo","Reaction-backed task tracking (:pushpin: marks a task, progress lives in a second reaction)",(s)=>s.option("cache",{type:"boolean",default:!0,describe:"Use ~/.config/slack-cli/cache.json for channel/user lookups (--no-cache to bypass)"}).middleware((r)=>{if(r.cache===!1)bi(!1)}).command(["ls","list"],"List everyone's tasks (has: \u2014 read-only, one search per run)",(r)=>r.options(n).option("mine",{type:"boolean",default:!1,describe:"Only your own reactions (hasmy:) \u2014 same as `slack mytodo ls`"}).option("shared",{type:"boolean",default:!1,hidden:!0,describe:"Deprecated \u2014 anyone's reactions is the default for `todo ls`"}),async(r)=>{await o(r,!1)}).command("set <target> <state>","Move a task to a progress state (adds the new reaction before removing the old one)",(r)=>r.positional("target",{type:"string",demandOption:!0,describe:"#chan:ts or permalink"}).positional("state",{type:"string",demandOption:!0,choices:["pending","doing","done","dropped"]}).option("channel-id",{type:"string",describe:"Raw channel ID"}),async(r)=>{let i={target:r.target,state:r.state};if(r["channel-id"])i.channelId=r["channel-id"];let c=t(r);if(c)i.cookie=c;try{await Bg(e(r),i)}catch(a){console.error(ae(a)),process.exit(1)}}).command("flag <target> <flag>","Add (or --remove) a reason flag (alert | needs-discussion | waiting | blocked) \u2014 flags stack, independent of progress",(r)=>r.positional("target",{type:"string",demandOption:!0,describe:"#chan:ts or permalink"}).positional("flag",{type:"string",demandOption:!0,choices:["alert","needs-discussion","waiting","blocked"],describe:"waiting = the other party in this conversation owes a reply; blocked = stuck on something outside it"}).option("remove",{type:"boolean",default:!1,describe:"Remove the flag instead of adding it"}).option("channel-id",{type:"string",describe:"Raw channel ID"}),async(r)=>{let i={target:r.target,flag:r.flag};if(r.remove)i.remove=!0;if(r["channel-id"])i.channelId=r["channel-id"];let c=t(r);if(c)i.cookie=c;try{await vg(e(r),i)}catch(a){console.error(ae(a)),process.exit(1)}}).command("doctor","Find messages carrying two or more progress reactions (--fix repairs them)",(r)=>r.option("in",{type:"string",demandOption:!0,describe:"Channel to scan (#chan)"}).option("fix",{type:"boolean",default:!1,describe:"Repair findings (keeps the highest-priority state)"}).option("limit",{type:"number",default:wi,describe:"Max messages to scan"}).option("channel-id",{type:"string",describe:"Raw channel ID"}),async(r)=>{let i={channel:r.in,limit:r.limit};if(r.fix)i.fix=!0;if(r["channel-id"])i.channelId=r["channel-id"];let c=t(r);if(c)i.cookie=c;await Lg(e(r),i)}).demandCommand(1,"Specify a todo subcommand (ls, set, flag, doctor)"),()=>{}).command("mytodo","Tasks carrying YOUR reactions (hasmy:) \u2014 the my-only half of `todo`",(s)=>s.option("cache",{type:"boolean",default:!0,describe:"Use ~/.config/slack-cli/cache.json for channel/user lookups (--no-cache to bypass)"}).middleware((r)=>{if(r.cache===!1)bi(!1)}).command(["ls","list"],"List tasks you have reacted to (hasmy: \u2014 read-only, one search per run)",(r)=>r.options(n),async(r)=>{await o(r,!0)}).demandCommand(1,"Specify a mytodo subcommand (ls)"),()=>{}).command("upload <target> <file..>","Upload one or more files to a channel or DM",(s)=>s.positional("target",{type:"string",demandOption:!0,describe:"#chan, @user, #chan:thread_ts, or permalink (a message permalink replies in its thread)"}).positional("file",{type:"string",array:!0,demandOption:!0,describe:"Path(s) to file(s)"}).option("title",{type:"string",describe:"Title (single file only)"}).option("comment",{type:"string",describe:"Initial comment (first file)"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing ambiguous bare URL boundaries"}).option("code",{type:"string",describe:"4-hex safety code to confirm upload"}).option("channel-id",{type:"string"}).option("user-id",{type:"string"}),async(s)=>{let r={target:s.target,filePaths:s.file};if(s.title)r.title=s.title;if(s.comment)r.comment=s.comment;if(s["allow-url-adjacent"])r.allowUrlAdjacent=!0;if(s.code)r.code=s.code;if(s["channel-id"])r.channelId=s["channel-id"];if(s["user-id"])r.userId=s["user-id"];let i=t(s);if(i)r.cookie=i;await _m(e(s),r)}).command("files","File commands",(s)=>s.command(["ls","list"],"List files visible to you (files.list)",(r)=>r.option("limit",{alias:"l",type:"number",default:100,describe:"Max files to list"}).option("type",{alias:"t",type:"string",describe:"Slack type filter: images, pdfs, gdocs, snippets, zips, spaces, all"}).option("channel",{alias:"c",type:"string",describe:"Only files in this channel (#name, @user, ID, or permalink)"}).option("user",{alias:"u",type:"string",describe:"Only files from this raw user ID"}).option("format",{type:"string",choices:["text","jsonl"],default:"text"}).option("json",{type:"boolean",default:!1,describe:"Alias for --format=jsonl"}),async(r)=>{let i={limit:r.limit,format:r.json?"jsonl":r.format};if(r.type)i.types=r.type;if(r.channel)i.channel=r.channel;if(r.user)i.user=r.user;await Fm(e(r),t(r),i)}).demandCommand(1,"").showHelpOnFail(!0),()=>{}).command("lists","Slack Lists \u2014 read rows (lists <ref>), or create / add / set (gated, as the bot)",(s)=>s.command("create <name>","Create a Slack List (confirm-hash safety gate; bot token, lists:write)",(r)=>r.positional("name",{type:"string",demandOption:!0,describe:"List name"}).option("col",{type:"string",array:!0,default:[],describe:"Column name:type (text|select|user|link|date|number|checkbox); select takes name:select:a,b,c. First is the primary text column. Repeatable"}).option("todo",{type:"boolean",default:!1,describe:"Todo mode: adds Completed / Assignee / Due date columns"}).option("code",{type:"string",describe:"Safety hash to confirm create"}),async(r)=>{try{let i={name:r.name,cols:r.col,todo:r.todo===!0};if(r.code!==void 0)i.code=r.code;await Im(i)}catch(i){console.error(ae(i)),process.exit(1)}}).command("add <list> <text>","Add a row to a Slack List (confirm-hash safety gate; bot token)",(r)=>r.positional("list",{type:"string",demandOption:!0,describe:"List URL or F-id"}).positional("text",{type:"string",demandOption:!0,describe:"Primary (first text) column value"}).option("set",{type:"string",array:!0,default:[],describe:"Other cells: column=value (repeatable)"}).option("code",{type:"string",describe:"Safety hash to confirm add"}),async(r)=>{try{let i={list:r.list,text:r.text,sets:r.set};if(r.code!==void 0)i.code=r.code;await Om(i)}catch(i){console.error(ae(i)),process.exit(1)}}).command("set <list> <row>","Update cells of a Slack List row; --done checks it off (confirm-hash safety gate; bot token)",(r)=>r.positional("list",{type:"string",demandOption:!0,describe:"List URL or F-id"}).positional("row",{type:"string",demandOption:!0,describe:"Row id (Rec\u2026), as printed by lists add / lists <ref>"}).option("set",{type:"string",array:!0,default:[],describe:"column=value (repeatable)"}).option("done",{type:"boolean",describe:"Check the row off (--no-done to uncheck); needs a todo-mode list"}).option("code",{type:"string",describe:"Safety hash to confirm update"}),async(r)=>{try{let i={list:r.list,row:r.row,sets:r.set};if(r.done!==void 0)i.done=r.done;if(r.code!==void 0)i.code=r.code;await Pm(i)}catch(i){console.error(ae(i)),process.exit(1)}}).command("share <list>","Grant users or channels access to a Slack List (confirm-hash safety gate; bot token)",(r)=>r.positional("list",{type:"string",demandOption:!0,describe:"List URL or F-id"}).option("user",{type:"string",array:!0,default:[],describe:"User ID (U\u2026), repeatable"}).option("channel",{type:"string",array:!0,default:[],describe:"Channel ID (C\u2026), repeatable"}).option("level",{type:"string",choices:["read","write","owner"],default:"write"}).option("code",{type:"string",describe:"Safety hash to confirm share"}),async(r)=>{try{let i={list:r.list,users:r.user,channels:r.channel,level:r.level};if(r.code!==void 0)i.code=r.code;await Rm(i)}catch(i){console.error(ae(i)),process.exit(1)}}).command("$0 <ref>","Read a Slack List's rows (by list URL or F-id) \u2014 read-only",(r)=>r.positional("ref",{type:"string",demandOption:!0,describe:"List URL (\u2026/lists/<TEAM>/<F-id>) or bare F-id"}).option("limit",{alias:"l",type:"number",default:100,describe:"Max rows to show"}).option("format",{type:"string",choices:["text","jsonl"],default:"text"}).option("json",{type:"boolean",default:!1,describe:"Alias for --format=jsonl (raw records)"}).option("as-bot",{type:"boolean",default:!1,describe:"Read with the bot token (SLACK_BOT_TOKEN, lists:read) via the public API instead of the user session"}),async(r)=>{let i=r.json?"jsonl":r.format;try{let c=r.asBot===!0;await Am(c?"":e(r),c?void 0:t(r),r.ref,{limit:r.limit,format:i,asBot:c})}catch(c){console.error(ae(c)),process.exit(1)}})).command("download <ref> [dest]","Download a file attachment (by file ID or file permalink) to disk",(s)=>s.positional("ref",{type:"string",demandOption:!0,describe:"File ID (F\u2026) or Slack file permalink"}).positional("dest",{type:"string",describe:"Output path or directory (default: ./<filename>)"}),async(s)=>{await Bm(e(s),t(s),s.ref,s.dest)}).command("dump","Bulk export channel history as markdown",(s)=>s.option("days",{alias:"d",type:"number",default:7,describe:"Days of history"}).option("limit",{alias:"l",type:"number",default:200}).option("filter",{alias:"f",type:"string",describe:"Filter channel names"}),async(s)=>{await Mg(e(s),s.days,s.limit,s.filter)}).command("todos","Slack's To-dos tab \u2014 your personal to-dos (read-only; requires xoxc desktop token). Not `slack todo` (reaction tasks)",(s)=>s.command(["$0","ls","list"],"List your To-dos, soonest due first",(r)=>r.option("filter",{type:"string",choices:[...Bu],default:"todo",describe:"todo = open to-dos; saved = everything saved; completed; archived"}).option("limit",{alias:"n",type:"number",default:50,describe:"At most this many items"}).option("json",{type:"boolean",default:!1,describe:"One JSON object per item (raw fields + permalink + message text)"}),async(r)=>{if(!Number.isInteger(r.limit)||r.limit<1)console.error(`Error: --limit must be a whole number of at least 1 (got ${r.limit}).`),process.exit(2);await Ug(e(r),t(r),{filter:r.filter,limit:r.limit,json:r.json})})).command("drafts","Manage message drafts (requires xoxc desktop token)",(s)=>s.command(["$0","ls","list"],"List pending drafts",(r)=>r.option("all",{alias:"a",type:"boolean",default:!1,describe:"Include sent drafts"}),async(r)=>{await Wg(e(r),t(r),r.all)}).command(["new <channel> [text..]","save <channel> [text..]"],"Create a draft",(r)=>r.positional("channel",{type:"string",demandOption:!0}).positional("text",{type:"string",array:!0,default:[]}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing a bare URL that runs into non-ASCII text (it would link only up to that point)"}),async(r)=>{let i=e(r),c=t(r),a=r.text.join(" ");if(!a)console.error("Usage: slack drafts new <#channel|@user> <text>"),process.exit(2);ve(a,r["allow-url-adjacent"],void 0,{sides:["after"],markdown:!1});let l=await ue(i,r.channel,c),u=await Tu(i,l,a,c);console.log(`\u2713 Draft created (id: ${T(u.draft).id??"?"})`)}).command("get <id>","Show a draft",(r)=>r.positional("id",{type:"string",demandOption:!0}),async(r)=>{await Jg(e(r),t(r),r.id)}).command(["edit <id> [text..]","update <id> [text..]"],"Edit a draft",(r)=>r.positional("id",{type:"string",demandOption:!0}).positional("text",{type:"string",array:!0,default:[]}).option("code",{type:"string"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing a bare URL that runs into non-ASCII text (it would link only up to that point)"}),async(r)=>{let i=e(r),c=t(r),a=r.text.join(" ");if(!a)console.error("Usage: slack drafts edit <id> <new-text>"),process.exit(2);ve(a,r["allow-url-adjacent"],void 0,{sides:["after"],markdown:!1});let l=await ts(i,c),u=X(l.drafts).map(T).find((p)=>String(p.id)===r.id);if(!u)console.error(`Draft not found: ${r.id}`),process.exit(1);let d=Do(u),f=await rt(i,c),h=ge(d,a,f?.userId??"");if(r.code!==h)me(r.code,h,["--- Editing draft as -------------------------",De(f),"--- Current draft ----------------------------",...d.split(`
406
412
  `).map((p)=>` ${p}`),"--- Replacing with ---------------------------",...a.split(`
407
- `).map((p)=>` ${p}`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);let m=await Eu(i,r.id,Ii(u),a,c);console.log(`\u2713 Draft updated (id: ${I(m.draft).id??"?"})`)}).command(["delete <id>","rm <id>"],"Delete a draft",(r)=>r.positional("id",{type:"string",demandOption:!0}).option("code",{type:"string"}),async(r)=>{let i=e(r),c=t(r),a=await ts(i,c),l=X(a.drafts).map(I).find((h)=>String(h.id)===r.id);if(!l)console.error(`Draft not found: ${r.id}`),process.exit(1);let u=po(l),d=await it(i,c),f=De(r.id,u,d?.userId??"");if(r.code!==f)ye(r.code,f,["\u2500-- Deleting draft \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500",we(d),` id: ${r.id}`,...u.split(`
408
- `).map((h)=>` ${h}`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);await _u(i,r.id,c),console.log(`\u2713 Draft deleted (id: ${r.id})`)})).command("auth","Authentication and workspace management",(s)=>s.command("token","Print the active token (or save one with --token)",(r)=>r.option("token",{type:"string",describe:"Token to save directly (non-interactive)"}).option("name",{type:"string",describe:"Workspace name (used with --token)"}),async(r)=>{if(r.token===void 0){console.log(Pn(r.workspace));return}await tl({...r.token!==void 0?{token:r.token}:{},...r.name!==void 0?{name:r.name}:{}})}).command("env","Print active workspace credentials in dotenv format",()=>{},(r)=>{let i=Pn(r.workspace),c=i.startsWith("xoxc-")?ar(r.workspace):void 0,a=[["SLACK_TOKEN",i]];if(c)a.push(["SLACK_COOKIE",c]);let l=a.map(([u,d])=>{if(/[\r\n\0']/.test(d))throw Error(`Cannot export ${u}: unsupported characters in credential`);return`${u}='${d}'`});console.log(l.join(`
409
- `))}).command("app","Create a new Slack app and obtain a token (guided wizard)",(r)=>r.option("bot",{type:"boolean",describe:"Create a bot token (xoxb-) instead of user (xoxp-)"}),async(r)=>{await nl({...r.bot!==void 0?{bot:r.bot}:{}})}).command("login","Log in: interactive wizard, or a source (chrome, firefox)",(r)=>r.command("chrome","Import workspaces from Chrome, grouped by account (all platforms)",(i)=>i.option("profile",{type:"string",alias:"p",describe:'Chrome profile email or dir (e.g. "you@example.com" or "Profile 3")'}),async(i)=>{await Br({...i.profile!==void 0?{profile:i.profile}:{}})}).command("firefox","Import the xoxd cookie from Firefox into a workspace",(i)=>i.option("workspace",{type:"string",alias:"w",describe:"Workspace name to update (default: active)"}),async(i)=>{await Mr({...i.workspace!==void 0?{workspace:i.workspace}:{}})}).option("token",{type:"string",describe:"Token to save directly (non-interactive)"}).option("name",{type:"string",describe:"Workspace name (used with --token)"}).option("yes",{type:"boolean",default:!1,describe:"Allow reading browser profiles without a confirmation prompt"}).option("from-desktop",{type:"boolean",default:!1,describe:"Import the Slack Desktop token without scanning a browser"}).option("from-chrome",{type:"boolean",default:!1,describe:"Import the desktop token and Chrome cookie"}).option("from-firefox",{type:"boolean",default:!1,describe:"Import the desktop token and Firefox cookie"}).option("from-all",{type:"boolean",default:!1,describe:"Import the desktop token and scan Chrome and Firefox"}).command("$0",!1,()=>{},async(i)=>{await Hn({...i.token!==void 0?{token:i.token}:{},...i.name!==void 0?{name:i.name}:{},yes:i.yes,fromDesktop:i.fromDesktop,fromChrome:i.fromChrome,fromFirefox:i.fromFirefox,fromAll:i.fromAll})}),async(r)=>{await Hn({...r.token!==void 0?{token:r.token}:{},...r.name!==void 0?{name:r.name}:{},yes:r.yes,fromDesktop:r.fromDesktop,fromChrome:r.fromChrome,fromFirefox:r.fromFirefox,fromAll:r.fromAll})}).command("tokens","Print the selected credentials as dotenv assignments",(r)=>r.option("workspace",{type:"string",alias:"w",describe:"Workspace name (default: active)"}),(r)=>sl({...r.workspace!==void 0?{workspace:r.workspace}:{}})).command("save","Save the active profile token and cookie to an env file",(r)=>r.option("envfile",{type:"string",demandOption:!0,describe:"Destination env file (e.g. ./.env.local)"}).option("workspace",{type:"string",alias:"w",describe:"Workspace name (default: active)"}),(r)=>ol({envfile:r.envfile,...r.workspace!==void 0?{workspace:r.workspace}:{}})).command(["ls","status"],"Show auth status",()=>{},()=>{let r=ir();if(r.length===0){console.log("No workspaces configured. Run: slack auth login");return}for(let{name:i,profile:c,current:a}of r)console.log(`${a?"* ":" "}${i} ${c.team} (${c.user}) ${c.url??""}`)}).command("use <name>","Switch active workspace",(r)=>r.positional("name",{type:"string",demandOption:!0}).option("g",{type:"boolean",default:!1,describe:"Write global lockfile (~/.slack-cli/workspace)"}),(r)=>{if(!r.g)cg(_t(process.cwd(),".slack-cli"));xc(r.name,r.g),console.log(`Switched to workspace "${r.name}" ${r.g?"globally":"locally"}`)}).command(["logout <name>","rm <name>","remove <name>"],"Remove a workspace",(r)=>r.positional("name",{type:"string",demandOption:!0}),(r)=>{kc(r.name),console.log(`Removed workspace "${r.name}"`)}).command(["cookie","chrome"],"Attach a Chrome xoxd cookie to a workspace (macOS/Linux/Windows). To import workspaces, use: slack auth login chrome",(r)=>r.option("workspace",{type:"string",alias:"w",describe:"Workspace name to update (default: active)"}).option("profile",{type:"string",alias:"p",describe:"Chrome profile email or dir (Windows, when several have a session)"}).option("yes",{type:"boolean",default:!1,describe:"Allow reading browser profiles without a confirmation prompt"}),async(r)=>{await el({...r.workspace!==void 0?{workspace:r.workspace}:{},...r.profile!==void 0?{profile:r.profile}:{},yes:r.yes})}).command("firefox","Attach Firefox browser xoxd cookie to a workspace (all platforms)",(r)=>r.option("workspace",{type:"string",alias:"w",describe:"Workspace name to update (default: active)"}).option("yes",{type:"boolean",default:!1,describe:"Allow reading browser profiles without a confirmation prompt"}),async(r)=>{await Mr({...r.workspace!==void 0?{workspace:r.workspace}:{},yes:r.yes})}).command("$0",!1,()=>{},()=>{s.showHelp(),process.exit(0)})).command("tail [target]","Stream new messages in real time (like tail -f)",(s)=>s.positional("target",{type:"string",describe:"#channel or @user to follow"}).option("since",{type:"string",describe:"Backfill from N ago (e.g. 10m, 2h, 1d)"}).option("thread",{type:"string",describe:"Follow a single thread by timestamp"}).option("watch-thread",{type:"string",describe:"Watch the channel's top-level timeline AND one thread's replies together (ts or permalink)"}).option("me",{type:"boolean",default:!1,describe:"Filter to messages that mention you"}).option("interval",{type:"number",default:60000,describe:"Poll interval in ms (default 60s; use --interval=3000 for near-real-time)"}).option("timeout",{type:"string",describe:"Auto-stop after this long (e.g. 30m, 2h). Exit code 0 even if nothing arrived."}).option("exit-on-message",{type:"boolean",default:!1,describe:"Stop as soon as the first new message from someone else arrives (wait-for-reply)"}).option("rtm",{type:"boolean",default:!0,describe:"Use RTM WebSocket when available (xoxc + cookie); pass --no-rtm to force polling"}),async(s)=>{let r=e(s),i=t(s),c=new AbortController;process.on("SIGINT",()=>{c.abort(),process.exit(0)}),await dl(r,s.target,{...s.since!==void 0?{since:s.since}:{},...s.thread!==void 0?{thread:s.thread}:{},...s["watch-thread"]!==void 0?{watchThread:s["watch-thread"]}:{},me:s.me,interval:s.interval,...s.timeout!==void 0?{timeout:s.timeout}:{},...s["exit-on-message"]===!0?{exitOnMessage:!0}:{},...i!==void 0?{cookie:i}:{},...s.rtm===!1?{noRtm:!0}:{}},c.signal)}).command("login",!1,(s)=>s.option("token",{type:"string"}).option("name",{type:"string"}).option("yes",{type:"boolean",default:!1}).option("from-desktop",{type:"boolean",default:!1}).option("from-chrome",{type:"boolean",default:!1}).option("from-firefox",{type:"boolean",default:!1}).option("from-all",{type:"boolean",default:!1}),async(s)=>{await Hn({...s.token!==void 0?{token:s.token}:{},...s.name!==void 0?{name:s.name}:{},yes:s.yes,fromDesktop:s.fromDesktop,fromChrome:s.fromChrome,fromFirefox:s.fromFirefox,fromAll:s.fromAll})}).demandCommand(1,"Specify a command. Run with --help for usage.").strict().help().alias("help","h").parseAsync()}km().catch((e)=>{console.error(e instanceof Error?e.message:String(e)),process.exit(1)});
413
+ `).map((p)=>` ${p}`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);let m=await Iu(i,r.id,Ni(u),a,c);console.log(`\u2713 Draft updated (id: ${T(m.draft).id??"?"})`)}).command(["delete <id>","rm <id>"],"Delete a draft",(r)=>r.positional("id",{type:"string",demandOption:!0}).option("code",{type:"string"}),async(r)=>{let i=e(r),c=t(r),a=await ts(i,c),l=X(a.drafts).map(T).find((h)=>String(h.id)===r.id);if(!l)console.error(`Draft not found: ${r.id}`),process.exit(1);let u=Do(l),d=await rt(i,c),f=ge(r.id,u,d?.userId??"");if(r.code!==f)me(r.code,f,["\u2500-- Deleting draft \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500",De(d),` id: ${r.id}`,...u.split(`
414
+ `).map((h)=>` ${h}`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);await Pu(i,r.id,c),console.log(`\u2713 Draft deleted (id: ${r.id})`)})).command("auth","Authentication and workspace management",(s)=>s.command("token","Print the active token (or save one with --token)",(r)=>r.option("token",{type:"string",describe:"Token to save directly (non-interactive)"}).option("name",{type:"string",describe:"Workspace name (used with --token)"}),async(r)=>{if(r.token===void 0){console.log(Rn(r.workspace));return}await il({...r.token!==void 0?{token:r.token}:{},...r.name!==void 0?{name:r.name}:{}})}).command("env","Print active workspace credentials in dotenv format",()=>{},(r)=>{let i=Rn(r.workspace),c=i.startsWith("xoxc-")?dr(r.workspace):void 0,a=[["SLACK_TOKEN",i]];if(c)a.push(["SLACK_COOKIE",c]);let l=a.map(([u,d])=>{if(/[\r\n\0']/.test(d))throw Error(`Cannot export ${u}: unsupported characters in credential`);return`${u}='${d}'`});console.log(l.join(`
415
+ `))}).command("app","Create a new Slack app and obtain a token (guided wizard)",(r)=>r.option("bot",{type:"boolean",describe:"Create a bot token (xoxb-) instead of user (xoxp-)"}),async(r)=>{await al({...r.bot!==void 0?{bot:r.bot}:{}})}).command("login","Log in: interactive wizard, or a source (chrome, firefox)",(r)=>r.command("chrome","Import workspaces from Chrome, grouped by account (all platforms)",(i)=>i.option("profile",{type:"string",alias:"p",describe:'Chrome profile email or dir (e.g. "you@example.com" or "Profile 3")'}),async(i)=>{await jr({...i.profile!==void 0?{profile:i.profile}:{}})}).command("firefox","Import the xoxd cookie from Firefox into a workspace",(i)=>i.option("workspace",{type:"string",alias:"w",describe:"Workspace name to update (default: active)"}),async(i)=>{await Wr({...i.workspace!==void 0?{workspace:i.workspace}:{}})}).option("token",{type:"string",describe:"Token to save directly (non-interactive)"}).option("name",{type:"string",describe:"Workspace name (used with --token)"}).option("yes",{type:"boolean",default:!1,describe:"Allow reading browser profiles without a confirmation prompt"}).option("from-desktop",{type:"boolean",default:!1,describe:"Import the Slack Desktop token without scanning a browser"}).option("from-chrome",{type:"boolean",default:!1,describe:"Import the desktop token and Chrome cookie"}).option("from-firefox",{type:"boolean",default:!1,describe:"Import the desktop token and Firefox cookie"}).option("from-all",{type:"boolean",default:!1,describe:"Import the desktop token and scan Chrome and Firefox"}).command("$0",!1,()=>{},async(i)=>{await zn({...i.token!==void 0?{token:i.token}:{},...i.name!==void 0?{name:i.name}:{},yes:i.yes,fromDesktop:i.fromDesktop,fromChrome:i.fromChrome,fromFirefox:i.fromFirefox,fromAll:i.fromAll})}),async(r)=>{await zn({...r.token!==void 0?{token:r.token}:{},...r.name!==void 0?{name:r.name}:{},yes:r.yes,fromDesktop:r.fromDesktop,fromChrome:r.fromChrome,fromFirefox:r.fromFirefox,fromAll:r.fromAll})}).command("tokens","Print the selected credentials as dotenv assignments",(r)=>r.option("workspace",{type:"string",alias:"w",describe:"Workspace name (default: active)"}),(r)=>cl({...r.workspace!==void 0?{workspace:r.workspace}:{}})).command("save","Save the active profile token and cookie to an env file",(r)=>r.option("envfile",{type:"string",demandOption:!0,describe:"Destination env file (e.g. ./.env.local)"}).option("workspace",{type:"string",alias:"w",describe:"Workspace name (default: active)"}),(r)=>ll({envfile:r.envfile,...r.workspace!==void 0?{workspace:r.workspace}:{}})).command(["ls","status"],"Show auth status",()=>{},()=>{let r=ur();if(r.length===0){console.log("No workspaces configured. Run: slack auth login");return}for(let{name:i,profile:c,current:a}of r)console.log(`${a?"* ":" "}${i} ${c.team} (${c.user}) ${c.url??""}`)}).command("use <name>","Switch active workspace",(r)=>r.positional("name",{type:"string",demandOption:!0}).option("g",{type:"boolean",default:!1,describe:"Write global lockfile (~/.slack-cli/workspace)"}),(r)=>{if(!r.g)Eg(Ft(process.cwd(),".slack-cli"));_c(r.name,r.g),console.log(`Switched to workspace "${r.name}" ${r.g?"globally":"locally"}`)}).command(["logout <name>","rm <name>","remove <name>"],"Remove a workspace",(r)=>r.positional("name",{type:"string",demandOption:!0}),(r)=>{Sc(r.name),console.log(`Removed workspace "${r.name}"`)}).command(["cookie","chrome"],"Attach a Chrome xoxd cookie to a workspace (macOS/Linux/Windows). To import workspaces, use: slack auth login chrome",(r)=>r.option("workspace",{type:"string",alias:"w",describe:"Workspace name to update (default: active)"}).option("profile",{type:"string",alias:"p",describe:"Chrome profile email or dir (Windows, when several have a session)"}).option("yes",{type:"boolean",default:!1,describe:"Allow reading browser profiles without a confirmation prompt"}),async(r)=>{await rl({...r.workspace!==void 0?{workspace:r.workspace}:{},...r.profile!==void 0?{profile:r.profile}:{},yes:r.yes})}).command("firefox","Attach Firefox browser xoxd cookie to a workspace (all platforms)",(r)=>r.option("workspace",{type:"string",alias:"w",describe:"Workspace name to update (default: active)"}).option("yes",{type:"boolean",default:!1,describe:"Allow reading browser profiles without a confirmation prompt"}),async(r)=>{await Wr({...r.workspace!==void 0?{workspace:r.workspace}:{},yes:r.yes})}).command("$0",!1,()=>{},()=>{s.showHelp(),process.exit(0)})).command("tail [target]","Stream new messages in real time (like tail -f)",(s)=>s.positional("target",{type:"string",describe:"#channel or @user to follow"}).option("since",{type:"string",describe:"Backfill from N ago (e.g. 10m, 2h, 1d)"}).option("thread",{type:"string",describe:"Follow a single thread by timestamp"}).option("watch-thread",{type:"string",describe:"Watch the channel's top-level timeline AND one thread's replies together (ts or permalink)"}).option("me",{type:"boolean",default:!1,describe:"Filter to messages that mention you"}).option("interval",{type:"number",default:60000,describe:"Poll interval in ms (default 60s; use --interval=3000 for near-real-time)"}).option("timeout",{type:"string",describe:"Auto-stop after this long (e.g. 30m, 2h). Exit code 0 even if nothing arrived."}).option("exit-on-message",{type:"boolean",default:!1,describe:"Stop as soon as the first new message from someone else arrives (wait-for-reply)"}).option("rtm",{type:"boolean",default:!0,describe:"Use RTM WebSocket when available (xoxc + cookie); pass --no-rtm to force polling"}),async(s)=>{let r=e(s),i=t(s),c=new AbortController;process.on("SIGINT",()=>{c.abort(),process.exit(0)}),await ml(r,s.target,{...s.since!==void 0?{since:s.since}:{},...s.thread!==void 0?{thread:s.thread}:{},...s["watch-thread"]!==void 0?{watchThread:s["watch-thread"]}:{},me:s.me,interval:s.interval,...s.timeout!==void 0?{timeout:s.timeout}:{},...s["exit-on-message"]===!0?{exitOnMessage:!0}:{},...i!==void 0?{cookie:i}:{},...s.rtm===!1?{noRtm:!0}:{}},c.signal)}).command("login",!1,(s)=>s.option("token",{type:"string"}).option("name",{type:"string"}).option("yes",{type:"boolean",default:!1}).option("from-desktop",{type:"boolean",default:!1}).option("from-chrome",{type:"boolean",default:!1}).option("from-firefox",{type:"boolean",default:!1}).option("from-all",{type:"boolean",default:!1}),async(s)=>{await zn({...s.token!==void 0?{token:s.token}:{},...s.name!==void 0?{name:s.name}:{},yes:s.yes,fromDesktop:s.fromDesktop,fromChrome:s.fromChrome,fromFirefox:s.fromFirefox,fromAll:s.fromAll})}).demandCommand(1,"Specify a command. Run with --help for usage.").strict().help().alias("help","h").parseAsync()}vm().catch((e)=>{console.error(e instanceof Error?e.message:String(e)),process.exit(1)});