slack-term 1.57.0 → 1.58.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 Ym}from"node:module";var Um=Object.create;var{getPrototypeOf:Jm,defineProperty:El,getOwnPropertyNames:Km}=Object;var $l=Object.prototype.hasOwnProperty;function qm(e){return this[e]}var Hm,zm,Cl=(e,t,n)=>{var s=e!=null&&typeof e==="object";if(s){var r=t?Hm??=new WeakMap:zm??=new WeakMap,o=r.get(e);if(o)return o}n=e!=null?Um(Jm(e)):{};let i=t||!e||!e.__esModule||!$l.call(e,"default")?El(n,"default",{value:e,enumerable:!0}):n;if(e&&typeof e==="object"||typeof e==="function"){for(let l of Km(e))if(!$l.call(i,l))El(i,l,{get:qm.bind(e,l),enumerable:!0})}if(s)r.set(e,i);return i};var Al=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Ds=Ym(import.meta.url);var Hl=Al(function(LS,ql){ql.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 bu=Al(function(__,yu){yu.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(r,o){return o};var s=Error().stack;if(Error.prepareStackTrace=n,s!==null&&typeof s==="object")return s[t]?s[t].getFileName():void 0}});import{createHash as bm}from"crypto";import{existsSync as wm,readFileSync as wl,mkdirSync as KD,realpathSync as qD,writeFileSync as km}from"fs";import{spawnSync as HD}from"child_process";import{homedir as zo}from"os";import{dirname as zD,join as mt,resolve as YD}from"path";import{notStrictEqual as Iy,strictEqual as vy}from"assert";var Gm={right:Zm,center:Qm};class Fl{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
- `).map((s)=>s.split("\t")),n=0;return t.forEach((s)=>{if(s.length>1&&Qe.stringWidth(s[0])>n)n=Math.min(Math.floor(this.width*0.5),Qe.stringWidth(s[0]))}),t.forEach((s)=>{this.div(...s.map((r,o)=>({text:r.trim(),padding:this.measurePadding(r),width:o===0&&s.length>1?n:void 0})))}),this.rows[this.rows.length-1]}colFromString(e){return{text:e,padding:this.measurePadding(e)}}measurePadding(e){let t=Qe.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,s)=>{let r="";n.forEach((o,i)=>{let{width:l}=e[i],u=this.negatePadding(e[i]),f=o;if(u>Qe.stringWidth(o))f+=" ".repeat(u-Qe.stringWidth(o));if(e[i].align&&e[i].align!=="left"&&this.wrap){let c=Gm[e[i].align];if(f=c(f,u),Qe.stringWidth(f)<u)f+=" ".repeat((l||0)-Qe.stringWidth(f)-1)}let a=e[i].padding||[0,0,0,0];if(a[3])r+=" ".repeat(a[3]);if(r+=Tl(e[i],f,"| "),r+=f,r+=Tl(e[i],f," |"),a[1])r+=" ".repeat(a[1]);if(s===0&&t.length>0)r=this.renderInline(r,t[t.length-1])}),t.push({text:r.replace(/ +$/,""),span:e.span})}),t}renderInline(e,t){let n=e.match(/^ */),s=n?n[0].length:0,r=t.text,o=Qe.stringWidth(r.trimRight());if(!t.span)return e;if(!this.wrap)return t.hidden=!0,r+e;if(s<o)return e;return t.hidden=!0,r.trimRight()+" ".repeat(s-o)+e.trimLeft()}rasterize(e){let t=[],n=this.columnWidths(e),s;return e.forEach((r,o)=>{if(r.width=n[o],this.wrap)s=Qe.wrap(r.text,this.negatePadding(r),{hard:!0}).split(`
3
+ import{createRequire as xy}from"node:module";var gy=Object.create;var{getPrototypeOf:my,defineProperty:Ul,getOwnPropertyNames:yy}=Object;var by=Object.prototype.hasOwnProperty;function wy(e){return this[e]}var ky,Dy,Jl=(e,t,n)=>{var s=e!=null&&typeof e==="object";if(s){var r=t?ky??=new WeakMap:Dy??=new WeakMap,o=r.get(e);if(o)return o}n=e!=null?gy(my(e)):{};let i=t||!e||!e.__esModule?Ul(n,"default",{value:e,enumerable:!0}):n;if(e&&typeof e==="object"||typeof e==="function"){for(let a of yy(e))if(!by.call(i,a))Ul(i,a,{get:wy.bind(e,a),enumerable:!0})}if(s)r.set(e,i);return i};var Kl=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var $e=xy(import.meta.url);var lu=Kl(function(x_,cu){cu.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 Pu=Kl(function(uE,vu){vu.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(r,o){return o};var s=Error().stack;if(Error.prepareStackTrace=n,s!==null&&typeof s==="object")return s[t]?s[t].getFileName():void 0}});function ql(e){let t=[],n=!1,s=!1,r=null;for(let o=0;o<e.length;o++){let i=e[o];if(i==="--"){t.push(...e.slice(o));break}if(i==="--async-callback"){if(o+1===e.length||e[o+1]==="--")throw Error("--async-callback needs a command");r=e[++o]}else if(i.startsWith("--async-callback="))r=i.slice(17);else if(i==="--async")n=!0;else{if(i==="--help"||i==="-h")s=!0;t.push(i)}}return{enabled:n&&!s,args:t,callback:r}}import{createHash as Hm}from"crypto";import{existsSync as zm,readFileSync as Ll,mkdirSync as Tx,realpathSync as Fx,writeFileSync as Ym}from"fs";import{spawnSync as Ox}from"child_process";import{homedir as ri}from"os";import{dirname as Ix,join as yt,resolve as Rx}from"path";import{notStrictEqual as ab,strictEqual as cb}from"assert";var Sy={right:$y,center:Cy};class zl{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
+ `).map((s)=>s.split("\t")),n=0;return t.forEach((s)=>{if(s.length>1&&et.stringWidth(s[0])>n)n=Math.min(Math.floor(this.width*0.5),et.stringWidth(s[0]))}),t.forEach((s)=>{this.div(...s.map((r,o)=>({text:r.trim(),padding:this.measurePadding(r),width:o===0&&s.length>1?n:void 0})))}),this.rows[this.rows.length-1]}colFromString(e){return{text:e,padding:this.measurePadding(e)}}measurePadding(e){let t=et.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,s)=>{let r="";n.forEach((o,i)=>{let{width:a}=e[i],c=this.negatePadding(e[i]),d=o;if(c>et.stringWidth(o))d+=" ".repeat(c-et.stringWidth(o));if(e[i].align&&e[i].align!=="left"&&this.wrap){let p=Sy[e[i].align];if(d=p(d,c),et.stringWidth(d)<c)d+=" ".repeat((a||0)-et.stringWidth(d)-1)}let f=e[i].padding||[0,0,0,0];if(f[3])r+=" ".repeat(f[3]);if(r+=Hl(e[i],d,"| "),r+=d,r+=Hl(e[i],d," |"),f[1])r+=" ".repeat(f[1]);if(s===0&&t.length>0)r=this.renderInline(r,t[t.length-1])}),t.push({text:r.replace(/ +$/,""),span:e.span})}),t}renderInline(e,t){let n=e.match(/^ */),s=n?n[0].length:0,r=t.text,o=et.stringWidth(r.trimRight());if(!t.span)return e;if(!this.wrap)return t.hidden=!0,r+e;if(s<o)return e;return t.hidden=!0,r.trimRight()+" ".repeat(s-o)+e.trimLeft()}rasterize(e){let t=[],n=this.columnWidths(e),s;return e.forEach((r,o)=>{if(r.width=n[o],this.wrap)s=et.wrap(r.text,this.negatePadding(r),{hard:!0}).split(`
6
6
  `);else s=r.text.split(`
7
- `);if(r.border)s.unshift("."+"-".repeat(this.negatePadding(r)+2)+"."),s.push("'"+"-".repeat(this.negatePadding(r)+2)+"'");if(r.padding)s.unshift(...Array(r.padding[0]||0).fill("")),s.push(...Array(r.padding[2]||0).fill(""));s.forEach((i,l)=>{if(!t[l])t.push([]);let u=t[l];for(let f=0;f<o;f++)if(u[f]===void 0)u.push("");u.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((o)=>o.width||Qe.stringWidth(o.text));let t=e.length,n=this.width,s=e.map((o)=>{if(o.width)return t--,n-=o.width,o.width;return}),r=t?Math.floor(n/t):0;return s.map((o,i)=>{if(o===void 0)return Math.max(r,Xm(e[i]));return o})}}function Tl(e,t,n){if(e.border){if(/[.']-+[.']/.test(t))return"";if(t.trim().length!==0)return n;return" "}return""}function Xm(e){let t=e.padding||[],n=1+(t[3]||0)+(t[1]||0);if(e.border)return n+4;return n}function Vm(){if(typeof process==="object"&&process.stdout&&process.stdout.columns)return process.stdout.columns;return 80}function Zm(e,t){e=e.trim();let n=Qe.stringWidth(e);if(n<t)return" ".repeat(t-n)+e;return e}function Qm(e,t){e=e.trim();let n=Qe.stringWidth(e);if(n>=t)return e;return" ".repeat(t-n>>1)+e}var Qe;function Ol(e,t){return Qe=t,new Fl({width:(e===null||e===void 0?void 0:e.width)||Vm(),wrap:e===null||e===void 0?void 0:e.wrap})}function ui({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 ey=ui();function bn(e){if(typeof e!=="string")throw TypeError(`Expected a \`string\`, got \`${typeof e}\``);if(!e.includes("\x1B")&&!e.includes("›"))return e;return e.replace(ey,"")}var Rl=161,Il=1114109,vl=[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],Pl=12288,Ll=65510,Nl=[12288,12288,65281,65376,65504,65510];var Ml=4352,Bl=262141,di=[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 mr=(e,t)=>{let n=0,s=Math.floor(e.length/2)-1;while(n<=s){let r=Math.floor((n+s)/2),o=r*2;if(t<e[o])s=r-1;else if(t>e[o+1])n=r+1;else return!0}return!1};var jl=19968,[ty,ny]=sy(di);function sy(e){let t=e[0],n=e[1];for(let s=0;s<e.length;s+=2){let r=e[s],o=e[s+1];if(jl>=r&&jl<=o)return[r,o];if(o-r>n-t)t=r,n=o}return[t,n]}var Wl=(e)=>{if(e<Rl||e>Il)return!1;return mr(vl,e)},Ul=(e)=>{if(e<Pl||e>Ll)return!1;return mr(Nl,e)};var Jl=(e)=>{if(e>=ty&&e<=ny)return!0;if(e<Ml||e>Bl)return!1;return mr(di,e)};function ry(e){if(!Number.isSafeInteger(e))throw TypeError(`Expected a code point, got \`${typeof e}\`.`)}function Kl(e,{ambiguousAsWide:t=!1}={}){if(ry(e),Ul(e)||Jl(e)||t&&Wl(e))return 2;return 1}var zl=Cl(Hl(),1),oy=new Intl.Segmenter,iy=/^\p{Default_Ignorable_Code_Point}$/u;function yt(e,t={}){if(typeof e!=="string"||e.length===0)return 0;let{ambiguousIsNarrow:n=!0,countAnsiEscapeCodes:s=!1}=t;if(!s)e=bn(e);if(e.length===0)return 0;let r=0,o={ambiguousAsWide:!n};for(let{segment:i}of oy.segment(e)){let l=i.codePointAt(0);if(l<=31||l>=127&&l<=159)continue;if(l>=8203&&l<=8207||l===65279)continue;if(l>=768&&l<=879||l>=6832&&l<=6911||l>=7616&&l<=7679||l>=8400&&l<=8447||l>=65056&&l<=65071)continue;if(l>=55296&&l<=57343)continue;if(l>=65024&&l<=65039)continue;if(iy.test(i))continue;if(zl.default().test(i)){r+=2;continue}r+=Kl(l,o)}return r}var Yl=(e=0)=>(t)=>`\x1B[${t+e}m`,Gl=(e=0)=>(t)=>`\x1B[${38+e};5;${t}m`,Xl=(e=0)=>(t,n,s)=>`\x1B[${38+e};2;${t};${n};${s}m`,_e={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]}},jS=Object.keys(_e.modifier),ay=Object.keys(_e.color),cy=Object.keys(_e.bgColor),WS=[...ay,...cy];function ly(){let e=new Map;for(let[t,n]of Object.entries(_e)){for(let[s,r]of Object.entries(n))_e[s]={open:`\x1B[${r[0]}m`,close:`\x1B[${r[1]}m`},n[s]=_e[s],e.set(r[0],r[1]);Object.defineProperty(_e,t,{value:n,enumerable:!1})}return Object.defineProperty(_e,"codes",{value:e,enumerable:!1}),_e.color.close="\x1B[39m",_e.bgColor.close="\x1B[49m",_e.color.ansi=Yl(),_e.color.ansi256=Gl(),_e.color.ansi16m=Xl(),_e.bgColor.ansi=Yl(10),_e.bgColor.ansi256=Gl(10),_e.bgColor.ansi16m=Xl(10),Object.defineProperties(_e,{rgbToAnsi256:{value(t,n,s){if(t===n&&n===s){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(s/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[s]=n;if(s.length===3)s=[...s].map((o)=>o+o).join("");let r=Number.parseInt(s,16);return[r>>16&255,r>>8&255,r&255]},enumerable:!1},hexToAnsi256:{value:(t)=>_e.rgbToAnsi256(..._e.hexToRgb(t)),enumerable:!1},ansi256ToAnsi:{value(t){if(t<8)return 30+t;if(t<16)return 90+(t-8);let n,s,r;if(t>=232)n=((t-232)*10+8)/255,s=n,r=n;else{t-=16;let l=t%36;n=Math.floor(t/36)/5,s=Math.floor(l/6)/5,r=l%6/5}let o=Math.max(n,s,r)*2;if(o===0)return 30;let i=30+(Math.round(r)<<2|Math.round(s)<<1|Math.round(n));if(o===2)i+=60;return i},enumerable:!1},rgbToAnsi:{value:(t,n,s)=>_e.ansi256ToAnsi(_e.rgbToAnsi256(t,n,s)),enumerable:!1},hexToAnsi:{value:(t)=>_e.ansi256ToAnsi(_e.hexToAnsi256(t)),enumerable:!1}}),_e}var uy=ly(),Vl=uy;var br=new Set(["\x1B","›"]),dy=39,pi="\x07",eu="[",fy="]",tu="m",yr=`${fy}8;;`,Zl=(e)=>`${br.values().next().value}${eu}${e}${tu}`,Ql=(e)=>`${br.values().next().value}${yr}${e}${pi}`,py=(e)=>e.split(" ").map((t)=>yt(t)),fi=(e,t,n)=>{let s=[...t],r=!1,o=!1,i=yt(bn(e.at(-1)));for(let[l,u]of s.entries()){let f=yt(u);if(i+f<=n)e[e.length-1]+=u;else e.push(u),i=0;if(br.has(u))r=!0,o=s.slice(l+1,l+1+yr.length).join("")===yr;if(r){if(o){if(u===pi)r=!1,o=!1}else if(u===tu)r=!1;continue}if(i+=f,i===n&&l<s.length-1)e.push(""),i=0}if(!i&&e.at(-1).length>0&&e.length>1)e[e.length-2]+=e.pop()},hy=(e)=>{let t=e.split(" "),n=t.length;while(n>0){if(yt(t[n-1])>0)break;n--}if(n===t.length)return e;return t.slice(0,n).join(" ")+t.slice(n).join("")},gy=(e,t,n={})=>{if(n.trim!==!1&&e.trim()==="")return"";let s="",r,o,i=py(e),l=[""];for(let[c,d]of e.split(" ").entries()){if(n.trim!==!1)l[l.length-1]=l.at(-1).trimStart();let p=yt(l.at(-1));if(c!==0){if(p>=t&&(n.wordWrap===!1||n.trim===!1))l.push(""),p=0;if(p>0||n.trim===!1)l[l.length-1]+=" ",p++}if(n.hard&&i[c]>t){let h=t-p,g=1+Math.floor((i[c]-h-1)/t);if(Math.floor((i[c]-1)/t)<g)l.push("");fi(l,d,t);continue}if(p+i[c]>t&&p>0&&i[c]>0){if(n.wordWrap===!1&&p<t){fi(l,d,t);continue}l.push("")}if(p+i[c]>t&&n.wordWrap===!1){fi(l,d,t);continue}l[l.length-1]+=d}if(n.trim!==!1)l=l.map((c)=>hy(c));let u=l.join(`
8
- `),f=[...u],a=0;for(let[c,d]of f.entries()){if(s+=d,br.has(d)){let{groups:h}=new RegExp(`(?:\\${eu}(?<code>\\d+)m|\\${yr}(?<uri>.*)${pi})`).exec(u.slice(a))||{groups:{}};if(h.code!==void 0){let g=Number.parseFloat(h.code);r=g===dy?void 0:g}else if(h.uri!==void 0)o=h.uri.length===0?void 0:h.uri}let p=Vl.codes.get(Number(r));if(f[c+1]===`
9
- `){if(o)s+=Ql("");if(r&&p)s+=Zl(p)}else if(d===`
10
- `){if(r&&p)s+=Zl(r);if(o)s+=Ql(o)}a+=d.length}return s};function hi(e,t,n){return String(e).normalize().replaceAll(`\r
7
+ `);if(r.border)s.unshift("."+"-".repeat(this.negatePadding(r)+2)+"."),s.push("'"+"-".repeat(this.negatePadding(r)+2)+"'");if(r.padding)s.unshift(...Array(r.padding[0]||0).fill("")),s.push(...Array(r.padding[2]||0).fill(""));s.forEach((i,a)=>{if(!t[a])t.push([]);let c=t[a];for(let d=0;d<o;d++)if(c[d]===void 0)c.push("");c.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((o)=>o.width||et.stringWidth(o.text));let t=e.length,n=this.width,s=e.map((o)=>{if(o.width)return t--,n-=o.width,o.width;return}),r=t?Math.floor(n/t):0;return s.map((o,i)=>{if(o===void 0)return Math.max(r,_y(e[i]));return o})}}function Hl(e,t,n){if(e.border){if(/[.']-+[.']/.test(t))return"";if(t.trim().length!==0)return n;return" "}return""}function _y(e){let t=e.padding||[],n=1+(t[3]||0)+(t[1]||0);if(e.border)return n+4;return n}function Ey(){if(typeof process==="object"&&process.stdout&&process.stdout.columns)return process.stdout.columns;return 80}function $y(e,t){e=e.trim();let n=et.stringWidth(e);if(n<t)return" ".repeat(t-n)+e;return e}function Cy(e,t){e=e.trim();let n=et.stringWidth(e);if(n>=t)return e;return" ".repeat(t-n>>1)+e}var et;function Yl(e,t){return et=t,new zl({width:(e===null||e===void 0?void 0:e.width)||Ey(),wrap:e===null||e===void 0?void 0:e.wrap})}function Di({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 Ay=Di();function kn(e){if(typeof e!=="string")throw TypeError(`Expected a \`string\`, got \`${typeof e}\``);if(!e.includes("\x1B")&&!e.includes("›"))return e;return e.replace(Ay,"")}var Gl=161,Xl=1114109,Vl=[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],Zl=12288,Ql=65510,eu=[12288,12288,65281,65376,65504,65510];var tu=4352,nu=262141,xi=[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 Sr=(e,t)=>{let n=0,s=Math.floor(e.length/2)-1;while(n<=s){let r=Math.floor((n+s)/2),o=r*2;if(t<e[o])s=r-1;else if(t>e[o+1])n=r+1;else return!0}return!1};var su=19968,[Ty,Fy]=Oy(xi);function Oy(e){let t=e[0],n=e[1];for(let s=0;s<e.length;s+=2){let r=e[s],o=e[s+1];if(su>=r&&su<=o)return[r,o];if(o-r>n-t)t=r,n=o}return[t,n]}var ru=(e)=>{if(e<Gl||e>Xl)return!1;return Sr(Vl,e)},ou=(e)=>{if(e<Zl||e>Ql)return!1;return Sr(eu,e)};var iu=(e)=>{if(e>=Ty&&e<=Fy)return!0;if(e<tu||e>nu)return!1;return Sr(xi,e)};function Iy(e){if(!Number.isSafeInteger(e))throw TypeError(`Expected a code point, got \`${typeof e}\`.`)}function au(e,{ambiguousAsWide:t=!1}={}){if(Iy(e),ou(e)||iu(e)||t&&ru(e))return 2;return 1}var uu=Jl(lu(),1),Ry=new Intl.Segmenter,vy=/^\p{Default_Ignorable_Code_Point}$/u;function bt(e,t={}){if(typeof e!=="string"||e.length===0)return 0;let{ambiguousIsNarrow:n=!0,countAnsiEscapeCodes:s=!1}=t;if(!s)e=kn(e);if(e.length===0)return 0;let r=0,o={ambiguousAsWide:!n};for(let{segment:i}of Ry.segment(e)){let a=i.codePointAt(0);if(a<=31||a>=127&&a<=159)continue;if(a>=8203&&a<=8207||a===65279)continue;if(a>=768&&a<=879||a>=6832&&a<=6911||a>=7616&&a<=7679||a>=8400&&a<=8447||a>=65056&&a<=65071)continue;if(a>=55296&&a<=57343)continue;if(a>=65024&&a<=65039)continue;if(vy.test(i))continue;if(uu.default().test(i)){r+=2;continue}r+=au(a,o)}return r}var du=(e=0)=>(t)=>`\x1B[${t+e}m`,fu=(e=0)=>(t)=>`\x1B[${38+e};5;${t}m`,pu=(e=0)=>(t,n,s)=>`\x1B[${38+e};2;${t};${n};${s}m`,_e={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]}},$_=Object.keys(_e.modifier),Py=Object.keys(_e.color),Ly=Object.keys(_e.bgColor),C_=[...Py,...Ly];function Ny(){let e=new Map;for(let[t,n]of Object.entries(_e)){for(let[s,r]of Object.entries(n))_e[s]={open:`\x1B[${r[0]}m`,close:`\x1B[${r[1]}m`},n[s]=_e[s],e.set(r[0],r[1]);Object.defineProperty(_e,t,{value:n,enumerable:!1})}return Object.defineProperty(_e,"codes",{value:e,enumerable:!1}),_e.color.close="\x1B[39m",_e.bgColor.close="\x1B[49m",_e.color.ansi=du(),_e.color.ansi256=fu(),_e.color.ansi16m=pu(),_e.bgColor.ansi=du(10),_e.bgColor.ansi256=fu(10),_e.bgColor.ansi16m=pu(10),Object.defineProperties(_e,{rgbToAnsi256:{value(t,n,s){if(t===n&&n===s){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(s/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[s]=n;if(s.length===3)s=[...s].map((o)=>o+o).join("");let r=Number.parseInt(s,16);return[r>>16&255,r>>8&255,r&255]},enumerable:!1},hexToAnsi256:{value:(t)=>_e.rgbToAnsi256(..._e.hexToRgb(t)),enumerable:!1},ansi256ToAnsi:{value(t){if(t<8)return 30+t;if(t<16)return 90+(t-8);let n,s,r;if(t>=232)n=((t-232)*10+8)/255,s=n,r=n;else{t-=16;let a=t%36;n=Math.floor(t/36)/5,s=Math.floor(a/6)/5,r=a%6/5}let o=Math.max(n,s,r)*2;if(o===0)return 30;let i=30+(Math.round(r)<<2|Math.round(s)<<1|Math.round(n));if(o===2)i+=60;return i},enumerable:!1},rgbToAnsi:{value:(t,n,s)=>_e.ansi256ToAnsi(_e.rgbToAnsi256(t,n,s)),enumerable:!1},hexToAnsi:{value:(t)=>_e.ansi256ToAnsi(_e.hexToAnsi256(t)),enumerable:!1}}),_e}var My=Ny(),hu=My;var Er=new Set(["\x1B","›"]),By=39,_i="\x07",yu="[",jy="]",bu="m",_r=`${jy}8;;`,gu=(e)=>`${Er.values().next().value}${yu}${e}${bu}`,mu=(e)=>`${Er.values().next().value}${_r}${e}${_i}`,Wy=(e)=>e.split(" ").map((t)=>bt(t)),Si=(e,t,n)=>{let s=[...t],r=!1,o=!1,i=bt(kn(e.at(-1)));for(let[a,c]of s.entries()){let d=bt(c);if(i+d<=n)e[e.length-1]+=c;else e.push(c),i=0;if(Er.has(c))r=!0,o=s.slice(a+1,a+1+_r.length).join("")===_r;if(r){if(o){if(c===_i)r=!1,o=!1}else if(c===bu)r=!1;continue}if(i+=d,i===n&&a<s.length-1)e.push(""),i=0}if(!i&&e.at(-1).length>0&&e.length>1)e[e.length-2]+=e.pop()},Uy=(e)=>{let t=e.split(" "),n=t.length;while(n>0){if(bt(t[n-1])>0)break;n--}if(n===t.length)return e;return t.slice(0,n).join(" ")+t.slice(n).join("")},Jy=(e,t,n={})=>{if(n.trim!==!1&&e.trim()==="")return"";let s="",r,o,i=Wy(e),a=[""];for(let[p,g]of e.split(" ").entries()){if(n.trim!==!1)a[a.length-1]=a.at(-1).trimStart();let y=bt(a.at(-1));if(p!==0){if(y>=t&&(n.wordWrap===!1||n.trim===!1))a.push(""),y=0;if(y>0||n.trim===!1)a[a.length-1]+=" ",y++}if(n.hard&&i[p]>t){let k=t-y,w=1+Math.floor((i[p]-k-1)/t);if(Math.floor((i[p]-1)/t)<w)a.push("");Si(a,g,t);continue}if(y+i[p]>t&&y>0&&i[p]>0){if(n.wordWrap===!1&&y<t){Si(a,g,t);continue}a.push("")}if(y+i[p]>t&&n.wordWrap===!1){Si(a,g,t);continue}a[a.length-1]+=g}if(n.trim!==!1)a=a.map((p)=>Uy(p));let c=a.join(`
8
+ `),d=[...c],f=0;for(let[p,g]of d.entries()){if(s+=g,Er.has(g)){let{groups:k}=new RegExp(`(?:\\${yu}(?<code>\\d+)m|\\${_r}(?<uri>.*)${_i})`).exec(c.slice(f))||{groups:{}};if(k.code!==void 0){let w=Number.parseFloat(k.code);r=w===By?void 0:w}else if(k.uri!==void 0)o=k.uri.length===0?void 0:k.uri}let y=hu.codes.get(Number(r));if(d[p+1]===`
9
+ `){if(o)s+=mu("");if(r&&y)s+=gu(y)}else if(g===`
10
+ `){if(r&&y)s+=gu(r);if(o)s+=mu(o)}f+=g.length}return s};function Ei(e,t,n){return String(e).normalize().replaceAll(`\r
11
11
  `,`
12
12
  `).split(`
13
- `).map((s)=>gy(s,t,n)).join(`
14
- `)}function gi(e){return Ol(e,{stringWidth:yt,stripAnsi:bn,wrap:hi})}import{dirname as nu,resolve as su}from"path";import{readdirSync as my,statSync as yy}from"fs";function mi(e,t){let n=su(".",e),s;if(!yy(n).isDirectory())n=nu(n);while(!0){if(s=t(n,my(n)),s)return su(n,s);if(n=nu(s=n),s===n)break}}import{inspect as Py}from"util";import{fileURLToPath as ku}from"url";import{format as ky}from"util";import{normalize as Dy,resolve as xy}from"path";function wn(e){if(!(e!==e.toLowerCase()&&e!==e.toUpperCase()))e=e.toLowerCase();if(e.indexOf("-")===-1&&e.indexOf("_")===-1)return e;else{let n="",s=!1,r=e.match(/^-+/);for(let o=r?r[0].length:0;o<e.length;o++){let i=e.charAt(o);if(s)s=!1,i=i.toUpperCase();if(o!==0&&(i==="-"||i==="_"))s=!0;else if(i!=="-"&&i!=="_")n+=i}return n}}function wr(e,t){let n=e.toLowerCase();t=t||"-";let s="";for(let r=0;r<e.length;r++){let o=n.charAt(r),i=e.charAt(r);if(o!==i&&r>0)s+=`${t}${n.charAt(r)}`;else s+=i}return s}function kr(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 ru(e){if(Array.isArray(e))return e.map((i)=>typeof i!=="string"?i+"":i);e=e.trim();let t=0,n=null,s=null,r=null,o=[];for(let i=0;i<e.length;i++){if(n=s,s=e.charAt(i),s===" "&&!r){if(n!==" ")t++;continue}if(s===r)r=null;else if((s==="'"||s==='"')&&!r)r=s;if(!o[t])o[t]="";o[t]+=s}return o}var at;(function(e){e.BOOLEAN="boolean",e.STRING="string",e.NUMBER="number",e.ARRAY="array"})(at||(at={}));var Lt;class bi{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),s=ru(e),r=typeof e==="string",o=by(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),l=Object.assign(Object.create(null),n.default),u=n.configObjects||[],f=n.envPrefix,a=i["populate--"],c=a?"--":"_",d=Object.create(null),p=Object.create(null),h=n.__||Lt.format,g={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:[]},y=/^-([0-9]+(\.[0-9]+)?|\.[0-9]+)$/,m=new RegExp("^--"+i["negation-prefix"]+"(.+)");if([].concat(n.array||[]).filter(Boolean).forEach(function(C){let T=typeof C==="object"?C.key:C,U=Object.keys(C).map(function(v){return{boolean:"bools",string:"strings",number:"numbers"}[v]}).filter(Boolean).pop();if(U)g[U][T]=!0;g.arrays[T]=!0,g.keys.push(T)}),[].concat(n.boolean||[]).filter(Boolean).forEach(function(C){g.bools[C]=!0,g.keys.push(C)}),[].concat(n.string||[]).filter(Boolean).forEach(function(C){g.strings[C]=!0,g.keys.push(C)}),[].concat(n.number||[]).filter(Boolean).forEach(function(C){g.numbers[C]=!0,g.keys.push(C)}),[].concat(n.count||[]).filter(Boolean).forEach(function(C){g.counts[C]=!0,g.keys.push(C)}),[].concat(n.normalize||[]).filter(Boolean).forEach(function(C){g.normalize[C]=!0,g.keys.push(C)}),typeof n.narg==="object")Object.entries(n.narg).forEach(([C,T])=>{if(typeof T==="number")g.nargs[C]=T,g.keys.push(C)});if(typeof n.coerce==="object")Object.entries(n.coerce).forEach(([C,T])=>{if(typeof T==="function")g.coercions[C]=T,g.keys.push(C)});if(typeof n.config<"u"){if(Array.isArray(n.config)||typeof n.config==="string")[].concat(n.config).filter(Boolean).forEach(function(C){g.configs[C]=!0});else if(typeof n.config==="object")Object.entries(n.config).forEach(([C,T])=>{if(typeof T==="boolean"||typeof T==="function")g.configs[C]=T})}ie(n.key,o,n.default,g.arrays),Object.keys(l).forEach(function(C){(g.aliases[C]||[]).forEach(function(T){l[T]=l[C]})});let w=null;yn();let k=[],_=Object.assign(Object.create(null),{_:[]}),D={};for(let C=0;C<s.length;C++){let T=s[C],U=T.replace(/^-{3,}/,"---"),v,A,ee,V,se,Ie;if(T!=="--"&&/^-/.test(T)&&re(T))E(T);else if(U.match(/^---+(=|$)/)){E(T);continue}else if(T.match(/^--.+=/)||!i["short-option-groups"]&&T.match(/^-.+=/)){if(V=T.match(/^--?([^=]+)=([\s\S]*)$/),V!==null&&Array.isArray(V)&&V.length>=3)if(q(V[1],g.arrays))C=x(C,V[1],s,V[2]);else if(q(V[1],g.nargs)!==!1)C=S(C,V[1],s,V[2]);else F(V[1],V[2],!0)}else if(T.match(m)&&i["boolean-negation"]){if(V=T.match(m),V!==null&&Array.isArray(V)&&V.length>=2)A=V[1],F(A,q(A,g.arrays)?[!1]:!1)}else if(T.match(/^--.+/)||!i["short-option-groups"]&&T.match(/^-[^-]+/)){if(V=T.match(/^--?(.+)/),V!==null&&Array.isArray(V)&&V.length>=2)if(A=V[1],q(A,g.arrays))C=x(C,A,s);else if(q(A,g.nargs)!==!1)C=S(C,A,s);else if(se=s[C+1],se!==void 0&&(!se.match(/^-/)||se.match(y))&&!q(A,g.bools)&&!q(A,g.counts))F(A,se),C++;else if(/^(true|false)$/.test(se))F(A,se),C++;else F(A,X(A))}else if(T.match(/^-.\..+=/)){if(V=T.match(/^-([^=]+)=([\s\S]*)$/),V!==null&&Array.isArray(V)&&V.length>=3)F(V[1],V[2])}else if(T.match(/^-.\..+/)&&!T.match(y)){if(se=s[C+1],V=T.match(/^-(.\..+)/),V!==null&&Array.isArray(V)&&V.length>=2)if(A=V[1],se!==void 0&&!se.match(/^-/)&&!q(A,g.bools)&&!q(A,g.counts))F(A,se),C++;else F(A,X(A))}else if(T.match(/^-[^-]+/)&&!T.match(y)){ee=T.slice(1,-1).split(""),v=!1;for(let Je=0;Je<ee.length;Je++){if(se=T.slice(Je+2),ee[Je+1]&&ee[Je+1]==="="){if(Ie=T.slice(Je+3),A=ee[Je],q(A,g.arrays))C=x(C,A,s,Ie);else if(q(A,g.nargs)!==!1)C=S(C,A,s,Ie);else F(A,Ie);v=!0;break}if(se==="-"){F(ee[Je],se);continue}if(/[A-Za-z]/.test(ee[Je])&&/^-?\d+(\.\d*)?(e-?\d+)?$/.test(se)&&q(se,g.bools)===!1){F(ee[Je],se),v=!0;break}if(ee[Je+1]&&ee[Je+1].match(/\W/)){F(ee[Je],se),v=!0;break}else F(ee[Je],X(ee[Je]))}if(A=T.slice(-1)[0],!v&&A!=="-")if(q(A,g.arrays))C=x(C,A,s);else if(q(A,g.nargs)!==!1)C=S(C,A,s);else if(se=s[C+1],se!==void 0&&(!/^(-|--)[^-]/.test(se)||se.match(y))&&!q(A,g.bools)&&!q(A,g.counts))F(A,se),C++;else if(/^(true|false)$/.test(se))F(A,se),C++;else F(A,X(A))}else if(T.match(/^-[0-9]$/)&&T.match(y)&&q(T.slice(1),g.bools))A=T.slice(1),F(A,X(A));else if(T==="--"){k=s.slice(C+1);break}else if(i["halt-at-non-option"]){k=s.slice(C);break}else E(T)}if(J(_,!0),J(_,!1),L(_),N(),z(_,g.aliases,l,!0),K(_),i["set-placeholder-key"])B(_);if(Object.keys(g.counts).forEach(function(C){if(!Y(_,C.split(".")))F(C,0)}),a&&k.length)_[c]=[];if(k.forEach(function(C){_[c].push(C)}),i["camel-case-expansion"]&&i["strip-dashed"])Object.keys(_).filter((C)=>C!=="--"&&C.includes("-")).forEach((C)=>{delete _[C]});if(i["strip-aliased"])[].concat(...Object.keys(o).map((C)=>o[C])).forEach((C)=>{if(i["camel-case-expansion"]&&C.includes("-"))delete _[C.split(".").map((T)=>wn(T)).join(".")];delete _[C]});function E(C){let T=P("_",C);if(typeof T==="string"||typeof T==="number")_._.push(T)}function S(C,T,U,v){let A,ee=q(T,g.nargs);if(ee=typeof ee!=="number"||isNaN(ee)?1:ee,ee===0){if(!be(v))w=Error(h("Argument unexpected for: %s",T));return F(T,X(T)),C}let V=be(v)?0:1;if(i["nargs-eats-options"]){if(U.length-(C+1)+V<ee)w=Error(h("Not enough arguments following: %s",T));V=ee}else{for(A=C+1;A<U.length;A++)if(!U[A].match(/^-[^0-9]/)||U[A].match(y)||re(U[A]))V++;else break;if(V<ee)w=Error(h("Not enough arguments following: %s",T))}let se=Math.min(V,ee);if(!be(v)&&se>0)F(T,v),se--;for(A=C+1;A<se+C+1;A++)F(T,U[A]);return C+se}function x(C,T,U,v){let A=[],ee=v||U[C+1],V=q(T,g.nargs);if(q(T,g.bools)&&!/^(true|false)$/.test(ee))A.push(!0);else if(be(ee)||be(v)&&/^-/.test(ee)&&!y.test(ee)&&!re(ee)){if(l[T]!==void 0){let se=l[T];A=Array.isArray(se)?se:[se]}}else{if(!be(v))A.push(I(T,v,!0));for(let se=C+1;se<U.length;se++){if(!i["greedy-arrays"]&&A.length>0||V&&typeof V==="number"&&A.length>=V)break;if(ee=U[se],/^-/.test(ee)&&!y.test(ee)&&!re(ee))break;C=se,A.push(I(T,ee,r))}}if(typeof V==="number"&&(V&&A.length<V||isNaN(V)&&A.length===0))w=Error(h("Not enough arguments following: %s",T));return F(T,A),C}function F(C,T,U=r){if(/-/.test(C)&&i["camel-case-expansion"]){let ee=C.split(".").map(function(V){return wn(V)}).join(".");R(C,ee)}let v=I(C,T,U),A=C.split(".");if(j(_,A,v),g.aliases[C])g.aliases[C].forEach(function(ee){let V=ee.split(".");j(_,V,v)});if(A.length>1&&i["dot-notation"])(g.aliases[A[0]]||[]).forEach(function(ee){let V=ee.split("."),se=[].concat(A);if(se.shift(),V=V.concat(se),!(g.aliases[C]||[]).includes(V.join(".")))j(_,V,v)});if(q(C,g.normalize)&&!q(C,g.arrays))[C].concat(g.aliases[C]||[]).forEach(function(V){Object.defineProperty(D,V,{enumerable:!0,get(){return T},set(se){T=typeof se==="string"?Lt.normalize(se):se}})})}function R(C,T){if(!(g.aliases[C]&&g.aliases[C].length))g.aliases[C]=[T],d[T]=!0;if(!(g.aliases[T]&&g.aliases[T].length))R(T,C)}function I(C,T,U){if(U)T=wy(T);if(q(C,g.bools)||q(C,g.counts)){if(typeof T==="string")T=T==="true"}let v=Array.isArray(T)?T.map(function(A){return P(C,A)}):P(C,T);if(q(C,g.counts)&&(be(v)||typeof v==="boolean"))v=yi();if(q(C,g.normalize)&&q(C,g.arrays))if(Array.isArray(T))v=T.map((A)=>Lt.normalize(A));else v=Lt.normalize(T);return v}function P(C,T){if(!i["parse-positional-numbers"]&&C==="_")return T;if(!q(C,g.strings)&&!q(C,g.bools)&&!Array.isArray(T)){if(kr(T)&&i["parse-numbers"]&&Number.isSafeInteger(Math.floor(parseFloat(`${T}`)))||!be(T)&&q(C,g.numbers))T=Number(T)}return T}function L(C){let T=Object.create(null);z(T,g.aliases,l),Object.keys(g.configs).forEach(function(U){let v=C[U]||T[U];if(v)try{let A=null,ee=Lt.resolve(Lt.cwd(),v),V=g.configs[U];if(typeof V==="function"){try{A=V(ee)}catch(se){A=se}if(A instanceof Error){w=A;return}}else A=Lt.require(ee);W(A)}catch(A){if(A.name==="PermissionDenied")w=A;else if(C[U])w=Error(h("Invalid JSON config file: %s",v))}})}function W(C,T){Object.keys(C).forEach(function(U){let v=C[U],A=T?T+"."+U:U;if(typeof v==="object"&&v!==null&&!Array.isArray(v)&&i["dot-notation"])W(v,A);else if(!Y(_,A.split("."))||q(A,g.arrays)&&i["combine-arrays"])F(A,v)})}function N(){if(typeof u<"u")u.forEach(function(C){W(C)})}function J(C,T){if(typeof f>"u")return;let U=typeof f==="string"?f:"",v=Lt.env();Object.keys(v).forEach(function(A){if(U===""||A.lastIndexOf(U,0)===0){let ee=A.split("__").map(function(V,se){if(se===0)V=V.substring(U.length);return wn(V)});if((T&&g.configs[ee.join(".")]||!T)&&!Y(C,ee))F(ee.join("."),v[A])}})}function K(C){let T,U=new Set;Object.keys(C).forEach(function(v){if(!U.has(v)){if(T=q(v,g.coercions),typeof T==="function")try{let A=P(v,T(C[v]));[].concat(g.aliases[v]||[],v).forEach((ee)=>{U.add(ee),C[ee]=A})}catch(A){w=A}}})}function B(C){return g.keys.forEach((T)=>{if(~T.indexOf("."))return;if(typeof C[T]>"u")C[T]=void 0}),C}function z(C,T,U,v=!1){Object.keys(U).forEach(function(A){if(!Y(C,A.split("."))){if(j(C,A.split("."),U[A]),v)p[A]=!0;(T[A]||[]).forEach(function(ee){if(Y(C,ee.split(".")))return;j(C,ee.split("."),U[A])})}})}function Y(C,T){let U=C;if(!i["dot-notation"])T=[T.join(".")];T.slice(0,-1).forEach(function(A){U=U[A]||{}});let v=T[T.length-1];if(typeof U!=="object")return!1;else return v in U}function j(C,T,U){let v=C;if(!i["dot-notation"])T=[T.join(".")];T.slice(0,-1).forEach(function(Ie){if(Ie=ou(Ie),typeof v==="object"&&v[Ie]===void 0)v[Ie]={};if(typeof v[Ie]!=="object"||Array.isArray(v[Ie])){if(Array.isArray(v[Ie]))v[Ie].push({});else v[Ie]=[v[Ie],{}];v=v[Ie][v[Ie].length-1]}else v=v[Ie]});let A=ou(T[T.length-1]),ee=q(T.join("."),g.arrays),V=Array.isArray(U),se=i["duplicate-arguments-array"];if(!se&&q(A,g.nargs)){if(se=!0,!be(v[A])&&g.nargs[A]===1||Array.isArray(v[A])&&v[A].length===g.nargs[A])v[A]=void 0}if(U===yi())v[A]=yi(v[A]);else if(Array.isArray(v[A]))if(se&&ee&&V)v[A]=i["flatten-duplicate-arrays"]?v[A].concat(U):(Array.isArray(v[A][0])?v[A]:[v[A]]).concat([U]);else if(!se&&Boolean(ee)===Boolean(V))v[A]=U;else v[A]=v[A].concat([U]);else if(v[A]===void 0&&ee)v[A]=V?U:[U];else if(se&&!(v[A]===void 0||q(A,g.counts)||q(A,g.bools)))v[A]=[v[A],U];else v[A]=U}function ie(...C){C.forEach(function(T){Object.keys(T||{}).forEach(function(U){if(g.aliases[U])return;g.aliases[U]=[].concat(o[U]||[]),g.aliases[U].concat(U).forEach(function(v){if(/-/.test(v)&&i["camel-case-expansion"]){let A=wn(v);if(A!==U&&g.aliases[U].indexOf(A)===-1)g.aliases[U].push(A),d[A]=!0}}),g.aliases[U].concat(U).forEach(function(v){if(v.length>1&&/[A-Z]/.test(v)&&i["camel-case-expansion"]){let A=wr(v,"-");if(A!==U&&g.aliases[U].indexOf(A)===-1)g.aliases[U].push(A),d[A]=!0}}),g.aliases[U].forEach(function(v){g.aliases[v]=[U].concat(g.aliases[U].filter(function(A){return v!==A}))})})})}function q(C,T){let U=[].concat(g.aliases[C]||[],C),v=Object.keys(T),A=U.find((ee)=>v.includes(ee));return A?T[A]:!1}function ue(C){let T=Object.keys(g);return[].concat(T.map((v)=>g[v])).some(function(v){return Array.isArray(v)?v.includes(C):v[C]})}function le(C,...T){return[].concat(...T).some(function(v){let A=C.match(v);return A&&ue(A[1])})}function H(C){if(C.match(y)||!C.match(/^-[^-]+/))return!1;let T=!0,U,v=C.slice(1).split("");for(let A=0;A<v.length;A++){if(U=C.slice(A+2),!ue(v[A])){T=!1;break}if(v[A+1]&&v[A+1]==="="||U==="-"||/[A-Za-z]/.test(v[A])&&/^-?\d+(\.\d*)?(e-?\d+)?$/.test(U)||v[A+1]&&v[A+1].match(/\W/))break}return T}function re(C){return i["unknown-options-as-args"]&&pe(C)}function pe(C){if(C=C.replace(/^-{3,}/,"--"),C.match(y))return!1;if(H(C))return!1;return!le(C,/^-+([^=]+?)=[\s\S]*$/,m,/^-+([^=]+?)$/,/^-+([^=]+?)-$/,/^-+([^=]+?\d+)$/,/^-+([^=]+?)\W+.*$/)}function X(C){if(!q(C,g.bools)&&!q(C,g.counts)&&`${C}`in l)return l[C];else return te(fe(C))}function te(C){return{[at.BOOLEAN]:!0,[at.STRING]:"",[at.NUMBER]:void 0,[at.ARRAY]:[]}[C]}function fe(C){let T=at.BOOLEAN;if(q(C,g.strings))T=at.STRING;else if(q(C,g.numbers))T=at.NUMBER;else if(q(C,g.bools))T=at.BOOLEAN;else if(q(C,g.arrays))T=at.ARRAY;return T}function be(C){return C===void 0}function yn(){Object.keys(g.counts).find((C)=>{if(q(C,g.arrays))return w=Error(h("Invalid configuration: %s, opts.count excludes opts.array.",C)),!0;else if(q(C,g.nargs))return w=Error(h("Invalid configuration: %s, opts.count excludes opts.narg.",C)),!0;return!1})}return{aliases:Object.assign({},g.aliases),argv:Object.assign(D,_),configuration:i,defaulted:Object.assign({},p),error:w,newAliases:Object.assign({},d)}}}function by(e){let t=[],n=Object.create(null),s=!0;Object.keys(e).forEach(function(r){t.push([].concat(e[r],r))});while(s){s=!1;for(let r=0;r<t.length;r++)for(let o=r+1;o<t.length;o++)if(t[r].filter(function(l){return t[o].indexOf(l)!==-1}).length){t[r]=t[r].concat(t[o]),t.splice(o,1),s=!0;break}}return t.forEach(function(r){r=r.filter(function(i,l,u){return u.indexOf(i)===l});let o=r.pop();if(o!==void 0&&typeof o==="string")n[o]=r}),n}function yi(e){return e!==void 0?e+1:1}function ou(e){if(e==="__proto__")return"___proto___";return e}function wy(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 Sy}from"fs";import{createRequire as iu}from"node:module";var wi,ki,Di,au=process&&process.env&&process.env.YARGS_MIN_NODE_VERSION?Number(process.env.YARGS_MIN_NODE_VERSION):20,cu=(ki=(wi=process===null||process===void 0?void 0:process.versions)===null||wi===void 0?void 0:wi.node)!==null&&ki!==void 0?ki:(Di=process===null||process===void 0?void 0:process.version)===null||Di===void 0?void 0:Di.slice(1);if(cu){if(Number(cu.match(/^([^.]+)/)[1])<au)throw Error(`yargs parser supports a minimum Node.js version of ${au}. Read our version support policy: https://github.com/yargs/yargs-parser#supported-nodejs-versions`)}var _y=process?process.env:{},lu=iu?iu(import.meta.url):void 0,uu=new bi({cwd:process.cwd,env:()=>_y,format:ky,normalize:Dy,resolve:xy,require:(e)=>{if(typeof lu<"u")return lu(e);else if(e.match(/\.json$/))return JSON.parse(Sy(e,"utf8"));else throw Error("only .json config files are supported in ESM")}}),xs=function(t,n){return uu.parse(t.slice(),n).argv};xs.detailed=function(e,t){return uu.parse(e.slice(),t)};xs.camelCase=wn;xs.decamelize=wr;xs.looksLikeNumber=kr;var xi=xs;import{basename as Ly,dirname as Ny,extname as My,relative as By,resolve as wu,join as jy}from"path";function du(){if(Ey())return 0;return 1}function Ey(){return $y()&&!process.defaultApp}function $y(){return!!process.versions.electron}function Si(e){return e.slice(du()+1)}function fu(){return process.argv[du()]}import{readFileSync as Cy,statSync as Ay,writeFile as Ty}from"fs";import{format as Fy}from"util";import{resolve as Oy}from"path";var pu={fs:{readFileSync:Cy,writeFile:Ty},format:Fy,resolve:Oy,exists:(e)=>{try{return Ay(e).isFile()}catch(t){return!1}}};var bt;class hu{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 bt.format.apply(bt.format,[this.cache[this.locale][t]||t].concat(e))}__n(){let e=Array.prototype.slice.call(arguments),t=e.shift(),n=e.shift(),s=e.shift(),r=function(){};if(typeof e[e.length-1]==="function")r=e.pop();if(!this.cache[this.locale])this._readLocaleFile();let o=s===1?t:n;if(this.cache[this.locale][t])o=this.cache[this.locale][t][s===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:r});else r();let i=[o];if(~o.indexOf("%d"))i.push(s);return bt.format.apply(bt.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(s,r){let o=t[r+1];if(n+=s,typeof o<"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:s,cb:r}=t,o=this._resolveLocaleFile(n,s),i=JSON.stringify(this.cache[s],null,2);bt.fs.writeFile(o,i,"utf-8",function(l){if(e.writeQueue.shift(),e.writeQueue.length>0)e._processWriteQueue();r(l)})}_readLocaleFile(){let e={},t=this._resolveLocaleFile(this.directory,this.locale);try{if(bt.fs.readFileSync)e=JSON.parse(bt.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=bt.resolve(e,"./",t+".json");if(this.fallbackToLanguage&&!this._fileExistsSync(n)&&~t.lastIndexOf("_")){let s=bt.resolve(e,"./",t.split("_")[0]+".json");if(this._fileExistsSync(s))n=s}return n}_fileExistsSync(e){return bt.exists(e)}}function gu(e,t){bt=t;let n=new hu(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 Ry=(e)=>gu(e,pu),mu=Ry;var Du=Cl(bu(),1);import{createRequire as Wy}from"node:module";import{readFileSync as Uy,readdirSync as Jy}from"node:fs";var _i=ku(import.meta.url),Ky=_i.substring(0,_i.lastIndexOf("node_modules")),qy=Wy(import.meta.url),Ei={assert:{notStrictEqual:Iy,strictEqual:vy},cliui:gi,findUp:mi,getEnv:(e)=>process.env[e],inspect:Py,getProcessArgvBin:fu,mainFilename:Ky||process.cwd(),Parser:xi,path:{basename:Ly,dirname:Ny,extname:My,relative:By,resolve:wu,join:jy},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:Uy,readdirSync:Jy,require:qy,getCallerFile:()=>{let e=Du.default(3);return e.match(/^file:\/\//)?ku(e):e},stringWidth:yt,y18n:mu({directory:wu(_i,"../../../locales"),updateFiles:!1})};function Ke(e,t,n,s){n.assert.notStrictEqual(e,t,s)}function $i(e,t){t.assert.strictEqual(typeof e,"string")}function zn(e){return Object.keys(e)}function xe(e){return!!e&&!!e.then&&typeof e.then==="function"}class Ce extends Error{constructor(e){super(e||"yargs error");if(this.name="YError",Error.captureStackTrace)Error.captureStackTrace(this,Ce)}}function Xt(e){let n=e.replace(/\s{2,}/g," ").split(/\s+(?![^[]*]|[^<]*>)/),s=/\.*[\][<>]/g,r=n.shift();if(!r)throw Error(`No command found in: ${e}`);let o={cmd:r.replace(s,""),demanded:[],optional:[]};return n.forEach((i,l)=>{let u=!1;if(i=i.replace(/\s/g,""),/\.+[\]>]/.test(i)&&l===n.length-1)u=!0;if(/^\[/.test(i))o.optional.push({cmd:i.replace(s,"").split("|"),variadic:u});else o.demanded.push({cmd:i.replace(s,"").split("|"),variadic:u})}),o}var Hy=["first","second","third","fourth","fifth","sixth"];function Z(e,t,n){function s(){return typeof e==="object"?[{demanded:[],optional:[]},e,t]:[Xt(`cmd ${e}`),t,n]}try{let r=0,[o,i,l]=s(),u=[].slice.call(i);while(u.length&&u[u.length-1]===void 0)u.pop();let f=l||u.length;if(f<o.demanded.length)throw new Ce(`Not enough arguments provided. Expected ${o.demanded.length} but received ${u.length}.`);let a=o.demanded.length+o.optional.length;if(f>a)throw new Ce(`Too many arguments provided. Expected max ${a} but received ${f}.`);o.demanded.forEach((c)=>{let d=u.shift(),p=xu(d);if(c.cmd.filter((g)=>g===p||g==="*").length===0)Su(p,c.cmd,r);r+=1}),o.optional.forEach((c)=>{if(u.length===0)return;let d=u.shift(),p=xu(d);if(c.cmd.filter((g)=>g===p||g==="*").length===0)Su(p,c.cmd,r);r+=1})}catch(r){console.warn(r.stack)}}function xu(e){if(Array.isArray(e))return"array";else if(e===null)return"null";return typeof e}function Su(e,t,n){throw new Ce(`Invalid ${Hy[n]||"manyith"} argument. Expected ${t.join(" or ")} but received ${e}.`)}class Ci{constructor(e){this.globalMiddleware=[],this.frozens=[],this.yargs=e}addMiddleware(e,t,n=!0,s=!1){if(Z("<array|function> [boolean] [boolean] [boolean]",[e,t,n],arguments.length),Array.isArray(e)){for(let r=0;r<e.length;r++){if(typeof e[r]!=="function")throw Error("middleware must be a function");let o=e[r];o.applyBeforeValidation=t,o.global=n}Array.prototype.push.apply(this.globalMiddleware,e)}else if(typeof e==="function"){let r=e;r.applyBeforeValidation=t,r.global=n,r.mutates=s,this.globalMiddleware.push(e)}return this.yargs}addCoerceMiddleware(e,t){let n=this.yargs.getAliases();return this.globalMiddleware=this.globalMiddleware.filter((s)=>{let r=[...n[t]||[],t];if(!s.option)return!0;else return!r.includes(s.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 _u(e){if(!e)return[];return e.map((t)=>(t.applyBeforeValidation=!1,t))}function kn(e,t,n,s){return n.reduce((r,o)=>{if(o.applyBeforeValidation!==s)return r;if(o.mutates){if(o.applied)return r;o.applied=!0}if(xe(r))return r.then((i)=>Promise.all([i,o(i,t)])).then(([i,l])=>Object.assign(i,l));else{let i=o(r,t);return xe(i)?i.then((l)=>Object.assign(r,l)):Object.assign(r,i)}},e)}function Dn(e,t,n=(s)=>{throw s}){try{let s=zy(e)?e():e;return xe(s)?s.then((r)=>t(r)):t(s)}catch(s){return n(s)}}function zy(e){return typeof e==="function"}var Yn=/(^\*)|(^\$0)/;class $u{constructor(e,t,n,s){this.requireCache=new Set,this.handlers={},this.aliasMap={},this.frozens=[],this.shim=s,this.usage=e,this.globalMiddleware=n,this.validation=t}addDirectory(e,t,n,s){s=s||{},this.requireCache.add(n);let r=this.shim.path.resolve(this.shim.path.dirname(n),e),o=this.shim.readdirSync(r,{recursive:s.recurse?!0:!1});if(!Array.isArray(s.extensions))s.extensions=["js"];let i=typeof s.visit==="function"?s.visit:(l)=>l;for(let l of o){let u=l.toString();if(s.exclude){let a=!1;if(typeof s.exclude==="function")a=s.exclude(u);else a=s.exclude.test(u);if(a)continue}if(s.include){let a=!1;if(typeof s.include==="function")a=s.include(u);else a=s.include.test(u);if(!a)continue}let f=!1;for(let a of s.extensions)if(u.endsWith(a))f=!0;if(f){let a=this.shim.path.join(r,u),c=t(a),d=Object.create(null,Object.getOwnPropertyDescriptors({...c}));if(i(d,a,u)){if(this.requireCache.has(a))continue;else this.requireCache.add(a);if(!d.command)d.command=this.shim.path.basename(a,this.shim.path.extname(a));this.addHandler(d)}}}}addHandler(e,t,n,s,r,o){let i=[],l=_u(r);if(s=s||(()=>{}),Array.isArray(e))if(Yy(e))[e,...i]=e;else for(let u of e)this.addHandler(u);else if(Xy(e)){let u=Array.isArray(e.command)||typeof e.command==="string"?e.command:null;if(u===null)throw Error(`No command name given for module: ${this.shim.inspect(e)}`);if(e.aliases)u=[].concat(u).concat(e.aliases);this.addHandler(u,this.extractDesc(e),e.builder,e.handler,e.middlewares,e.deprecated);return}else if(Eu(n)){this.addHandler([e].concat(i),t,n.builder,n.handler,n.middlewares,n.deprecated);return}if(typeof e==="string"){let u=Xt(e);i=i.map((c)=>Xt(c).cmd);let f=!1,a=[u.cmd].concat(i).filter((c)=>{if(Yn.test(c))return f=!0,!1;return!0});if(a.length===0&&f)a.push("$0");if(f)u.cmd=a[0],i=a.slice(1),e=e.replace(Yn,u.cmd);if(i.forEach((c)=>{this.aliasMap[c]=u.cmd}),t!==!1)this.usage.command(e,t,f,i,o);if(this.handlers[u.cmd]={original:e,description:t,handler:s,builder:n||{},middlewares:l,deprecated:o,demanded:u.demanded,optional:u.optional},f)this.defaultCommand=this.handlers[u.cmd]}}getCommandHandlers(){return this.handlers}getCommands(){return Object.keys(this.handlers).concat(Object.keys(this.aliasMap))}hasDefaultCommand(){return!!this.defaultCommand}runCommand(e,t,n,s,r,o){let i=this.handlers[e]||this.handlers[this.aliasMap[e]]||this.defaultCommand,l=t.getInternalMethods().getContext(),u=l.commands.slice(),f=!e;if(e)l.commands.push(e),l.fullCommands.push(i.original);let a=this.applyBuilderUpdateUsageAndParse(f,i,t,n.aliases,u,s,r,o);return xe(a)?a.then((c)=>this.applyMiddlewareAndGetResult(f,i,c.innerArgv,l,r,c.aliases,t)):this.applyMiddlewareAndGetResult(f,i,a.innerArgv,l,r,a.aliases,t)}applyBuilderUpdateUsageAndParse(e,t,n,s,r,o,i,l){let u=t.builder,f=n;if(Dr(u)){n.getInternalMethods().getUsageInstance().freeze();let a=u(n.getInternalMethods().reset(s),l);if(xe(a))return a.then((c)=>(f=Au(c)?c:n,this.parseAndUpdateUsage(e,t,f,r,o,i)))}else if(Gy(u))n.getInternalMethods().getUsageInstance().freeze(),f=n.getInternalMethods().reset(s),Object.keys(t.builder).forEach((a)=>{f.option(a,u[a])});return this.parseAndUpdateUsage(e,t,f,r,o,i)}parseAndUpdateUsage(e,t,n,s,r,o){if(e)n.getInternalMethods().getUsageInstance().unfreeze(!0);if(this.shouldUpdateUsage(n))n.getInternalMethods().getUsageInstance().usage(this.usageFromParentCommandsCommandHandler(s,t),t.description);let i=n.getInternalMethods().runYargsParserAndExecuteCommands(null,void 0,!0,r,o);return xe(i)?i.then((l)=>({aliases:n.parsed.aliases,innerArgv:l})):{aliases:n.parsed.aliases,innerArgv:i}}shouldUpdateUsage(e){return!e.getInternalMethods().getUsageInstance().getUsageDisabled()&&e.getInternalMethods().getUsageInstance().getUsage().length===0}usageFromParentCommandsCommandHandler(e,t){let n=Yn.test(t.original)?t.original.replace(Yn,"").trim():t.original,s=e.filter((r)=>!Yn.test(r));return s.push(n),`$0 ${s.join(" ")}`}handleValidationAndGetResult(e,t,n,s,r,o,i,l){if(!o.getInternalMethods().getHasOutput()){let u=o.getInternalMethods().runValidation(r,l,o.parsed.error,e);n=Dn(n,(f)=>(u(f),f))}if(t.handler&&!o.getInternalMethods().getHasOutput()){o.getInternalMethods().setHasOutput();let u=!!o.getOptions().configuration["populate--"];if(o.getInternalMethods().postProcess(n,u,!1,!1),n=kn(n,o,i,!1),n=Dn(n,(f)=>{let a=t.handler(f);return xe(a)?a.then(()=>f):f}),!e)o.getInternalMethods().getUsageInstance().cacheHelpMessage();if(xe(n)&&!o.getInternalMethods().hasParseCallback())n.catch((f)=>{try{o.getInternalMethods().getUsageInstance().fail(null,f)}catch(a){}})}if(!e)s.commands.pop(),s.fullCommands.pop();return n}applyMiddlewareAndGetResult(e,t,n,s,r,o,i){let l={};if(r)return n;if(!i.getInternalMethods().getHasOutput())l=this.populatePositionals(t,n,s,i);let u=this.globalMiddleware.getMiddleware().slice(0).concat(t.middlewares),f=kn(n,i,u,!0);return xe(f)?f.then((a)=>this.handleValidationAndGetResult(e,t,a,s,o,i,u,l)):this.handleValidationAndGetResult(e,t,f,s,o,i,u,l)}populatePositionals(e,t,n,s){t._=t._.slice(n.commands.length);let r=e.demanded.slice(0),o=e.optional.slice(0),i={};this.validation.positionalCount(r.length,t._.length);while(r.length){let l=r.shift();this.populatePositional(l,t,i)}while(o.length){let l=o.shift();this.populatePositional(l,t,i)}return t._=n.commands.concat(t._.map((l)=>""+l)),this.postProcessPositionals(t,i,this.cmdToParseOptions(e.original),s),i}populatePositional(e,t,n){let s=e.cmd[0];if(e.variadic)n[s]=t._.splice(0).map(String);else if(t._.length)n[s]=[String(t._.shift())]}cmdToParseOptions(e){let t={array:[],default:{},alias:{},demand:{}},n=Xt(e);return n.demanded.forEach((s)=>{let[r,...o]=s.cmd;if(s.variadic)t.array.push(r),t.default[r]=[];t.alias[r]=o,t.demand[r]=!0}),n.optional.forEach((s)=>{let[r,...o]=s.cmd;if(s.variadic)t.array.push(r),t.default[r]=[];t.alias[r]=o}),t}postProcessPositionals(e,t,n,s){let r=Object.assign({},s.getOptions());r.default=Object.assign(n.default,r.default);for(let u of Object.keys(n.alias))r.alias[u]=(r.alias[u]||[]).concat(n.alias[u]);r.array=r.array.concat(n.array),r.config={};let o=[];if(Object.keys(t).forEach((u)=>{t[u].map((f)=>{if(r.configuration["unknown-options-as-args"])r.key[u]=!0;o.push(`--${u}`),o.push(f)})}),!o.length)return;let i=Object.assign({},r.configuration,{"populate--":!1}),l=this.shim.Parser.detailed(o,Object.assign({},r,{configuration:i}));if(l.error)s.getInternalMethods().getUsageInstance().fail(l.error.message,l.error);else{let u=Object.keys(t);Object.keys(t).forEach((f)=>{u.push(...l.aliases[f])}),Object.keys(l.argv).forEach((f)=>{if(u.includes(f)){if(!t[f])t[f]=l.argv[f];if(!this.isInConfigs(s,f)&&!this.isDefaulted(s,f)&&Object.prototype.hasOwnProperty.call(e,f)&&Object.prototype.hasOwnProperty.call(l.argv,f)&&(Array.isArray(e[f])||Array.isArray(l.argv[f])))e[f]=[].concat(e[f],l.argv[f]);else e[f]=l.argv[f]}})}}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((s)=>Object.prototype.hasOwnProperty.call(s,t))||n.some((s)=>Object.prototype.hasOwnProperty.call(s,this.shim.Parser.camelCase(t)))}runDefaultBuilderOn(e){if(!this.defaultCommand)return;if(this.shouldUpdateUsage(e)){let n=Yn.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(Dr(t))return t(e,!0);else if(!Eu(t))Object.keys(t).forEach((n)=>{e.option(n,t[n])});return}extractDesc({describe:e,description:t,desc:n}){for(let s of[e,t,n]){if(typeof s==="string"||s===!1)return s;Ke(s,!0,this.shim)}return!1}freeze(){this.frozens.push({handlers:this.handlers,aliasMap:this.aliasMap,defaultCommand:this.defaultCommand})}unfreeze(){let e=this.frozens.pop();Ke(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 Cu(e,t,n,s){return new $u(e,t,n,s)}function Eu(e){return typeof e==="object"&&!!e.builder&&typeof e.handler==="function"}function Yy(e){return e.every((t)=>typeof t==="string")}function Dr(e){return typeof e==="function"}function Gy(e){return typeof e==="object"}function Xy(e){return typeof e==="object"&&!Array.isArray(e)}function Vt(e={},t=()=>!0){let n={};return zn(e).forEach((s)=>{if(t(s,e[s]))n[s]=e[s]}),n}function Zt(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 Vy(e){return typeof e==="boolean"}function Fu(e,t){let n=t.y18n.__,s={},r=[];s.failFn=function(P){r.push(P)};let o=null,i=null,l=!0;s.showHelpOnFail=function(P=!0,L){let[W,N]=typeof P==="string"?[!0,P]:[P,L];if(e.getInternalMethods().isGlobalContext())i=N;return o=N,l=W,s};let u=!1;s.fail=function(P,L){let W=e.getInternalMethods().getLoggerInstance();if(r.length)for(let N=r.length-1;N>=0;--N){let J=r[N];if(Vy(J)){if(L)throw L;else if(P)throw Error(P)}else J(P,L,s)}else{if(e.getExitProcess())Zt(!0);if(!u){if(u=!0,l)e.showHelp("error"),W.error();if(P||L)W.error(P||L);let N=o||i;if(N){if(P||L)W.error("");W.error(N)}}if(L=L||new Ce(P),e.getExitProcess())return e.exit(1);else if(e.getInternalMethods().hasParseCallback())return e.exit(1,L);else throw L}};let f=[],a=!1;s.usage=(I,P)=>{if(I===null)return a=!0,f=[],s;return a=!1,f.push([I,P||""]),s},s.getUsage=()=>f,s.getUsageDisabled=()=>a,s.getPositionalGroupName=()=>n("Positionals:");let c=[];s.example=(I,P)=>{c.push([I,P||""])};let d=[];s.command=function(P,L,W,N,J=!1){if(W)d=d.map((K)=>(K[2]=!1,K));d.push([P,L||"",W,N,J])},s.getCommands=()=>d;let p={};s.describe=function(P,L){if(Array.isArray(P))P.forEach((W)=>{s.describe(W,L)});else if(typeof P==="object")Object.keys(P).forEach((W)=>{s.describe(W,P[W])});else p[P]=L},s.getDescriptions=()=>p;let h=[];s.epilog=(I)=>{h.push(I)};let g=!1,y;s.wrap=(I)=>{g=!0,y=I},s.getWrap=()=>{if(t.getEnv("YARGS_DISABLE_WRAP"))return null;if(!g)y=x(),g=!0;return y};let m="__yargsString__:";s.deferY18nLookup=(I)=>m+I,s.help=function(){if(_)return _;k();let P=e.customScriptName?e.$0:t.path.basename(e.$0),L=e.getDemandedOptions(),W=e.getDemandedCommands(),N=e.getDeprecatedOptions(),J=e.getGroups(),K=e.getOptions(),B=[];B=B.concat(Object.keys(p)),B=B.concat(Object.keys(L)),B=B.concat(Object.keys(W)),B=B.concat(Object.keys(K.default)),B=B.filter(E),B=Object.keys(B.reduce((H,re)=>{if(re!=="_")H[re]=!0;return H},{}));let z=s.getWrap(),Y=t.cliui({width:z,wrap:!!z});if(!a){if(f.length)f.forEach((H)=>{if(Y.div({text:`${H[0].replace(/\$0/g,P)}`}),H[1])Y.div({text:`${H[1]}`,padding:[1,0,0,0]})}),Y.div();else if(d.length){let H=null;if(W._)H=`${P} <${n("command")}>
15
- `;else H=`${P} [${n("command")}]
16
- `;Y.div(`${H}`)}}if(d.length>1||d.length===1&&!d[0][2]){Y.div(n("Commands:"));let H=e.getInternalMethods().getContext(),re=H.commands.length?`${H.commands.join(" ")} `:"";if(e.getInternalMethods().getParserConfiguration()["sort-commands"]===!0)d=d.sort((X,te)=>X[0].localeCompare(te[0]));let pe=P?`${P} `:"";d.forEach((X)=>{let te=`${pe}${re}${X[0].replace(/^\$0 ?/,"")}`;Y.span({text:te,padding:[0,2,0,2],width:w(d,z,`${P}${re}`)+4},{text:X[1]});let fe=[];if(X[2])fe.push(`[${n("default")}]`);if(X[3]&&X[3].length)fe.push(`[${n("aliases:")} ${X[3].join(", ")}]`);if(X[4])if(typeof X[4]==="string")fe.push(`[${n("deprecated: %s",X[4])}]`);else fe.push(`[${n("deprecated")}]`);if(fe.length)Y.div({text:fe.join(" "),padding:[0,0,0,2],align:"right"});else Y.div()}),Y.div()}let j=(Object.keys(K.alias)||[]).concat(Object.keys(e.parsed.newAliases)||[]);B=B.filter((H)=>!e.parsed.newAliases[H]&&j.every((re)=>(K.alias[re]||[]).indexOf(H)===-1));let ie=n("Options:");if(!J[ie])J[ie]=[];D(B,K.alias,J,ie);let q=(H)=>/^--/.test(xr(H)),ue=Object.keys(J).filter((H)=>J[H].length>0).map((H)=>{let re=J[H].filter(E).map((pe)=>{if(j.includes(pe))return pe;for(let X=0,te;(te=j[X])!==void 0;X++)if((K.alias[te]||[]).includes(pe))return te;return pe});return{groupName:H,normalizedKeys:re}}).filter(({normalizedKeys:H})=>H.length>0).map(({groupName:H,normalizedKeys:re})=>{let pe=re.reduce((X,te)=>(X[te]=[te].concat(K.alias[te]||[]).map((fe)=>{if(H===s.getPositionalGroupName())return fe;else return(/^[0-9]$/.test(fe)?K.boolean.includes(te)?"-":"--":fe.length>1?"--":"-")+fe}).sort((fe,be)=>q(fe)===q(be)?0:q(fe)?1:-1).join(", "),X),{});return{groupName:H,normalizedKeys:re,switches:pe}});if(ue.filter(({groupName:H})=>H!==s.getPositionalGroupName()).some(({normalizedKeys:H,switches:re})=>!H.every((pe)=>q(re[pe]))))ue.filter(({groupName:H})=>H!==s.getPositionalGroupName()).forEach(({normalizedKeys:H,switches:re})=>{H.forEach((pe)=>{if(q(re[pe]))re[pe]=Zy(re[pe],4)})});if(ue.forEach(({groupName:H,normalizedKeys:re,switches:pe})=>{Y.div(H),re.forEach((X)=>{let te=pe[X],fe=p[X]||"",be=null;if(fe.includes(m))fe=n(fe.substring(m.length));if(K.boolean.includes(X))be=`[${n("boolean")}]`;if(K.count.includes(X))be=`[${n("count")}]`;if(K.string.includes(X))be=`[${n("string")}]`;if(K.normalize.includes(X))be=`[${n("string")}]`;if(K.array.includes(X))be=`[${n("array")}]`;if(K.number.includes(X))be=`[${n("number")}]`;let yn=(U)=>typeof U==="string"?`[${n("deprecated: %s",U)}]`:`[${n("deprecated")}]`,C=[X in N?yn(N[X]):null,be,X in L?`[${n("required")}]`:null,K.choices&&K.choices[X]?`[${n("choices:")} ${s.stringifiedValues(K.choices[X])}]`:null,S(K.default[X],K.defaultDescription[X])].filter(Boolean).join(" ");Y.span({text:xr(te),padding:[0,2,0,2+Tu(te)],width:w(pe,z)+4},fe);let T=e.getInternalMethods().getUsageConfiguration()["hide-types"]===!0;if(C&&!T)Y.div({text:C,padding:[0,0,0,2],align:"right"});else Y.div()}),Y.div()}),c.length)Y.div(n("Examples:")),c.forEach((H)=>{H[0]=H[0].replace(/\$0/g,P)}),c.forEach((H)=>{if(H[1]==="")Y.div({text:H[0],padding:[0,2,0,2]});else Y.div({text:H[0],padding:[0,2,0,2],width:w(c,z)+4},{text:H[1]})}),Y.div();if(h.length>0){let H=h.map((re)=>re.replace(/\$0/g,P)).join(`
17
- `);Y.div(`${H}
18
- `)}return Y.toString().replace(/\s*$/,"")};function w(I,P,L){let W=0;if(!Array.isArray(I))I=Object.values(I).map((N)=>[N]);if(I.forEach((N)=>{W=Math.max(t.stringWidth(L?`${L} ${xr(N[0])}`:xr(N[0]))+Tu(N[0]),W)}),P)W=Math.min(W,parseInt((P*0.5).toString(),10));return W}function k(){let I=e.getDemandedOptions(),P=e.getOptions();(Object.keys(P.alias)||[]).forEach((L)=>{P.alias[L].forEach((W)=>{if(p[W])s.describe(L,p[W]);if(W in I)e.demandOption(L,I[W]);if(P.boolean.includes(W))e.boolean(L);if(P.count.includes(W))e.count(L);if(P.string.includes(W))e.string(L);if(P.normalize.includes(W))e.normalize(L);if(P.array.includes(W))e.array(L);if(P.number.includes(W))e.number(L)})})}let _;s.cacheHelpMessage=function(){_=this.help()},s.clearCachedHelpMessage=function(){_=void 0},s.hasCachedHelpMessage=function(){return!!_};function D(I,P,L,W){let N=[],J=null;return Object.keys(L).forEach((K)=>{N=N.concat(L[K])}),I.forEach((K)=>{if(J=[K].concat(P[K]),!J.some((B)=>N.indexOf(B)!==-1))L[W].push(K)}),N}function E(I){return e.getOptions().hiddenOptions.indexOf(I)<0||e.parsed.argv[e.getOptions().showHiddenOpt]}s.showHelp=(I)=>{let P=e.getInternalMethods().getLoggerInstance();if(!I)I="error";(typeof I==="function"?I:P[I])(s.help())},s.functionDescription=(I)=>["(",I.name?t.Parser.decamelize(I.name,"-"):n("generated-value"),")"].join(""),s.stringifiedValues=function(P,L){let W="",N=L||", ",J=[].concat(P);if(!P||!J.length)return W;return J.forEach((K)=>{if(W.length)W+=N;W+=JSON.stringify(K)}),W};function S(I,P){let L=`[${n("default:")} `;if(I===void 0&&!P)return null;if(P)L+=P;else switch(typeof I){case"string":L+=`"${I}"`;break;case"object":L+=JSON.stringify(I);break;default:L+=I}return`${L}]`}function x(){if(t.process.stdColumns)return Math.min(80,t.process.stdColumns);else return 80}let F=null;s.version=(I)=>{F=I},s.showVersion=(I)=>{let P=e.getInternalMethods().getLoggerInstance();if(!I)I="error";(typeof I==="function"?I:P[I])(F)},s.reset=function(P){return o=null,u=!1,f=[],a=!1,h=[],c=[],d=[],p=Vt(p,(L)=>!P[L]),s};let R=[];return s.freeze=function(){R.push({failMessage:o,failureOutput:u,usages:f,usageDisabled:a,epilogs:h,examples:c,commands:d,descriptions:p})},s.unfreeze=function(P=!1){let L=R.pop();if(!L)return;if(P)p={...L.descriptions,...p},d=[...L.commands,...d],f=[...L.usages,...f],c=[...L.examples,...c],h=[...L.epilogs,...h];else({failMessage:o,failureOutput:u,usages:f,usageDisabled:a,epilogs:h,examples:c,commands:d,descriptions:p}=L)},s}function Ai(e){return typeof e==="object"}function Zy(e,t){return Ai(e)?{text:e.text,indentation:e.indentation+t}:{text:e,indentation:t}}function Tu(e){return Ai(e)?e.indentation:0}function xr(e){return Ai(e)?e.text:e}var Ou=`###-begin-{{app_name}}-completions-###
13
+ `).map((s)=>Jy(s,t,n)).join(`
14
+ `)}function $i(e){return Yl(e,{stringWidth:bt,stripAnsi:kn,wrap:Ei})}import{dirname as wu,resolve as ku}from"path";import{readdirSync as Ky,statSync as qy}from"fs";function Ci(e,t){let n=ku(".",e),s;if(!qy(n).isDirectory())n=wu(n);while(!0){if(s=t(n,Ky(n)),s)return ku(n,s);if(n=wu(s=n),s===n)break}}import{inspect as lb}from"util";import{fileURLToPath as Nu}from"url";import{format as Yy}from"util";import{normalize as Gy,resolve as Xy}from"path";function Dn(e){if(!(e!==e.toLowerCase()&&e!==e.toUpperCase()))e=e.toLowerCase();if(e.indexOf("-")===-1&&e.indexOf("_")===-1)return e;else{let n="",s=!1,r=e.match(/^-+/);for(let o=r?r[0].length:0;o<e.length;o++){let i=e.charAt(o);if(s)s=!1,i=i.toUpperCase();if(o!==0&&(i==="-"||i==="_"))s=!0;else if(i!=="-"&&i!=="_")n+=i}return n}}function $r(e,t){let n=e.toLowerCase();t=t||"-";let s="";for(let r=0;r<e.length;r++){let o=n.charAt(r),i=e.charAt(r);if(o!==i&&r>0)s+=`${t}${n.charAt(r)}`;else s+=i}return s}function Cr(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 Du(e){if(Array.isArray(e))return e.map((i)=>typeof i!=="string"?i+"":i);e=e.trim();let t=0,n=null,s=null,r=null,o=[];for(let i=0;i<e.length;i++){if(n=s,s=e.charAt(i),s===" "&&!r){if(n!==" ")t++;continue}if(s===r)r=null;else if((s==="'"||s==='"')&&!r)r=s;if(!o[t])o[t]="";o[t]+=s}return o}var ct;(function(e){e.BOOLEAN="boolean",e.STRING="string",e.NUMBER="number",e.ARRAY="array"})(ct||(ct={}));var jt;class Ti{constructor(e){jt=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),s=Du(e),r=typeof e==="string",o=Hy(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),a=Object.assign(Object.create(null),n.default),c=n.configObjects||[],d=n.envPrefix,f=i["populate--"],p=f?"--":"_",g=Object.create(null),y=Object.create(null),k=n.__||jt.format,w={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:[]},u=/^-([0-9]+(\.[0-9]+)?|\.[0-9]+)$/,l=new RegExp("^--"+i["negation-prefix"]+"(.+)");if([].concat(n.array||[]).filter(Boolean).forEach(function(T){let P=typeof T==="object"?T.key:T,H=Object.keys(T).map(function(B){return{boolean:"bools",string:"strings",number:"numbers"}[B]}).filter(Boolean).pop();if(H)w[H][P]=!0;w.arrays[P]=!0,w.keys.push(P)}),[].concat(n.boolean||[]).filter(Boolean).forEach(function(T){w.bools[T]=!0,w.keys.push(T)}),[].concat(n.string||[]).filter(Boolean).forEach(function(T){w.strings[T]=!0,w.keys.push(T)}),[].concat(n.number||[]).filter(Boolean).forEach(function(T){w.numbers[T]=!0,w.keys.push(T)}),[].concat(n.count||[]).filter(Boolean).forEach(function(T){w.counts[T]=!0,w.keys.push(T)}),[].concat(n.normalize||[]).filter(Boolean).forEach(function(T){w.normalize[T]=!0,w.keys.push(T)}),typeof n.narg==="object")Object.entries(n.narg).forEach(([T,P])=>{if(typeof P==="number")w.nargs[T]=P,w.keys.push(T)});if(typeof n.coerce==="object")Object.entries(n.coerce).forEach(([T,P])=>{if(typeof P==="function")w.coercions[T]=P,w.keys.push(T)});if(typeof n.config<"u"){if(Array.isArray(n.config)||typeof n.config==="string")[].concat(n.config).filter(Boolean).forEach(function(T){w.configs[T]=!0});else if(typeof n.config==="object")Object.entries(n.config).forEach(([T,P])=>{if(typeof P==="boolean"||typeof P==="function")w.configs[T]=P})}ie(n.key,o,n.default,w.arrays),Object.keys(a).forEach(function(T){(w.aliases[T]||[]).forEach(function(P){a[P]=a[T]})});let h=null;wn();let m=[],b=Object.assign(Object.create(null),{_:[]}),_={};for(let T=0;T<s.length;T++){let P=s[T],H=P.replace(/^-{3,}/,"---"),B,R,te,V,oe,Pe;if(P!=="--"&&/^-/.test(P)&&ne(P))x(P);else if(H.match(/^---+(=|$)/)){x(P);continue}else if(P.match(/^--.+=/)||!i["short-option-groups"]&&P.match(/^-.+=/)){if(V=P.match(/^--?([^=]+)=([\s\S]*)$/),V!==null&&Array.isArray(V)&&V.length>=3)if(q(V[1],w.arrays))T=E(T,V[1],s,V[2]);else if(q(V[1],w.nargs)!==!1)T=S(T,V[1],s,V[2]);else I(V[1],V[2],!0)}else if(P.match(l)&&i["boolean-negation"]){if(V=P.match(l),V!==null&&Array.isArray(V)&&V.length>=2)R=V[1],I(R,q(R,w.arrays)?[!1]:!1)}else if(P.match(/^--.+/)||!i["short-option-groups"]&&P.match(/^-[^-]+/)){if(V=P.match(/^--?(.+)/),V!==null&&Array.isArray(V)&&V.length>=2)if(R=V[1],q(R,w.arrays))T=E(T,R,s);else if(q(R,w.nargs)!==!1)T=S(T,R,s);else if(oe=s[T+1],oe!==void 0&&(!oe.match(/^-/)||oe.match(u))&&!q(R,w.bools)&&!q(R,w.counts))I(R,oe),T++;else if(/^(true|false)$/.test(oe))I(R,oe),T++;else I(R,Y(R))}else if(P.match(/^-.\..+=/)){if(V=P.match(/^-([^=]+)=([\s\S]*)$/),V!==null&&Array.isArray(V)&&V.length>=3)I(V[1],V[2])}else if(P.match(/^-.\..+/)&&!P.match(u)){if(oe=s[T+1],V=P.match(/^-(.\..+)/),V!==null&&Array.isArray(V)&&V.length>=2)if(R=V[1],oe!==void 0&&!oe.match(/^-/)&&!q(R,w.bools)&&!q(R,w.counts))I(R,oe),T++;else I(R,Y(R))}else if(P.match(/^-[^-]+/)&&!P.match(u)){te=P.slice(1,-1).split(""),B=!1;for(let Ke=0;Ke<te.length;Ke++){if(oe=P.slice(Ke+2),te[Ke+1]&&te[Ke+1]==="="){if(Pe=P.slice(Ke+3),R=te[Ke],q(R,w.arrays))T=E(T,R,s,Pe);else if(q(R,w.nargs)!==!1)T=S(T,R,s,Pe);else I(R,Pe);B=!0;break}if(oe==="-"){I(te[Ke],oe);continue}if(/[A-Za-z]/.test(te[Ke])&&/^-?\d+(\.\d*)?(e-?\d+)?$/.test(oe)&&q(oe,w.bools)===!1){I(te[Ke],oe),B=!0;break}if(te[Ke+1]&&te[Ke+1].match(/\W/)){I(te[Ke],oe),B=!0;break}else I(te[Ke],Y(te[Ke]))}if(R=P.slice(-1)[0],!B&&R!=="-")if(q(R,w.arrays))T=E(T,R,s);else if(q(R,w.nargs)!==!1)T=S(T,R,s);else if(oe=s[T+1],oe!==void 0&&(!/^(-|--)[^-]/.test(oe)||oe.match(u))&&!q(R,w.bools)&&!q(R,w.counts))I(R,oe),T++;else if(/^(true|false)$/.test(oe))I(R,oe),T++;else I(R,Y(R))}else if(P.match(/^-[0-9]$/)&&P.match(u)&&q(P.slice(1),w.bools))R=P.slice(1),I(R,Y(R));else if(P==="--"){m=s.slice(T+1);break}else if(i["halt-at-non-option"]){m=s.slice(T);break}else x(P)}if(M(b,!0),M(b,!1),F(b),O(),ee(b,w.aliases,a,!0),J(b),i["set-placeholder-key"])j(b);if(Object.keys(w.counts).forEach(function(T){if(!X(b,T.split(".")))I(T,0)}),f&&m.length)b[p]=[];if(m.forEach(function(T){b[p].push(T)}),i["camel-case-expansion"]&&i["strip-dashed"])Object.keys(b).filter((T)=>T!=="--"&&T.includes("-")).forEach((T)=>{delete b[T]});if(i["strip-aliased"])[].concat(...Object.keys(o).map((T)=>o[T])).forEach((T)=>{if(i["camel-case-expansion"]&&T.includes("-"))delete b[T.split(".").map((P)=>Dn(P)).join(".")];delete b[T]});function x(T){let P=A("_",T);if(typeof P==="string"||typeof P==="number")b._.push(P)}function S(T,P,H,B){let R,te=q(P,w.nargs);if(te=typeof te!=="number"||isNaN(te)?1:te,te===0){if(!be(B))h=Error(k("Argument unexpected for: %s",P));return I(P,Y(P)),T}let V=be(B)?0:1;if(i["nargs-eats-options"]){if(H.length-(T+1)+V<te)h=Error(k("Not enough arguments following: %s",P));V=te}else{for(R=T+1;R<H.length;R++)if(!H[R].match(/^-[^0-9]/)||H[R].match(u)||ne(H[R]))V++;else break;if(V<te)h=Error(k("Not enough arguments following: %s",P))}let oe=Math.min(V,te);if(!be(B)&&oe>0)I(P,B),oe--;for(R=T+1;R<oe+T+1;R++)I(P,H[R]);return T+oe}function E(T,P,H,B){let R=[],te=B||H[T+1],V=q(P,w.nargs);if(q(P,w.bools)&&!/^(true|false)$/.test(te))R.push(!0);else if(be(te)||be(B)&&/^-/.test(te)&&!u.test(te)&&!ne(te)){if(a[P]!==void 0){let oe=a[P];R=Array.isArray(oe)?oe:[oe]}}else{if(!be(B))R.push(C(P,B,!0));for(let oe=T+1;oe<H.length;oe++){if(!i["greedy-arrays"]&&R.length>0||V&&typeof V==="number"&&R.length>=V)break;if(te=H[oe],/^-/.test(te)&&!u.test(te)&&!ne(te))break;T=oe,R.push(C(P,te,r))}}if(typeof V==="number"&&(V&&R.length<V||isNaN(V)&&R.length===0))h=Error(k("Not enough arguments following: %s",P));return I(P,R),T}function I(T,P,H=r){if(/-/.test(T)&&i["camel-case-expansion"]){let te=T.split(".").map(function(V){return Dn(V)}).join(".");N(T,te)}let B=C(T,P,H),R=T.split(".");if(U(b,R,B),w.aliases[T])w.aliases[T].forEach(function(te){let V=te.split(".");U(b,V,B)});if(R.length>1&&i["dot-notation"])(w.aliases[R[0]]||[]).forEach(function(te){let V=te.split("."),oe=[].concat(R);if(oe.shift(),V=V.concat(oe),!(w.aliases[T]||[]).includes(V.join(".")))U(b,V,B)});if(q(T,w.normalize)&&!q(T,w.arrays))[T].concat(w.aliases[T]||[]).forEach(function(V){Object.defineProperty(_,V,{enumerable:!0,get(){return P},set(oe){P=typeof oe==="string"?jt.normalize(oe):oe}})})}function N(T,P){if(!(w.aliases[T]&&w.aliases[T].length))w.aliases[T]=[P],g[P]=!0;if(!(w.aliases[P]&&w.aliases[P].length))N(P,T)}function C(T,P,H){if(H)P=zy(P);if(q(T,w.bools)||q(T,w.counts)){if(typeof P==="string")P=P==="true"}let B=Array.isArray(P)?P.map(function(R){return A(T,R)}):A(T,P);if(q(T,w.counts)&&(be(B)||typeof B==="boolean"))B=Ai();if(q(T,w.normalize)&&q(T,w.arrays))if(Array.isArray(P))B=P.map((R)=>jt.normalize(R));else B=jt.normalize(P);return B}function A(T,P){if(!i["parse-positional-numbers"]&&T==="_")return P;if(!q(T,w.strings)&&!q(T,w.bools)&&!Array.isArray(P)){if(Cr(P)&&i["parse-numbers"]&&Number.isSafeInteger(Math.floor(parseFloat(`${P}`)))||!be(P)&&q(T,w.numbers))P=Number(P)}return P}function F(T){let P=Object.create(null);ee(P,w.aliases,a),Object.keys(w.configs).forEach(function(H){let B=T[H]||P[H];if(B)try{let R=null,te=jt.resolve(jt.cwd(),B),V=w.configs[H];if(typeof V==="function"){try{R=V(te)}catch(oe){R=oe}if(R instanceof Error){h=R;return}}else R=jt.require(te);v(R)}catch(R){if(R.name==="PermissionDenied")h=R;else if(T[H])h=Error(k("Invalid JSON config file: %s",B))}})}function v(T,P){Object.keys(T).forEach(function(H){let B=T[H],R=P?P+"."+H:H;if(typeof B==="object"&&B!==null&&!Array.isArray(B)&&i["dot-notation"])v(B,R);else if(!X(b,R.split("."))||q(R,w.arrays)&&i["combine-arrays"])I(R,B)})}function O(){if(typeof c<"u")c.forEach(function(T){v(T)})}function M(T,P){if(typeof d>"u")return;let H=typeof d==="string"?d:"",B=jt.env();Object.keys(B).forEach(function(R){if(H===""||R.lastIndexOf(H,0)===0){let te=R.split("__").map(function(V,oe){if(oe===0)V=V.substring(H.length);return Dn(V)});if((P&&w.configs[te.join(".")]||!P)&&!X(T,te))I(te.join("."),B[R])}})}function J(T){let P,H=new Set;Object.keys(T).forEach(function(B){if(!H.has(B)){if(P=q(B,w.coercions),typeof P==="function")try{let R=A(B,P(T[B]));[].concat(w.aliases[B]||[],B).forEach((te)=>{H.add(te),T[te]=R})}catch(R){h=R}}})}function j(T){return w.keys.forEach((P)=>{if(~P.indexOf("."))return;if(typeof T[P]>"u")T[P]=void 0}),T}function ee(T,P,H,B=!1){Object.keys(H).forEach(function(R){if(!X(T,R.split("."))){if(U(T,R.split("."),H[R]),B)y[R]=!0;(P[R]||[]).forEach(function(te){if(X(T,te.split(".")))return;U(T,te.split("."),H[R])})}})}function X(T,P){let H=T;if(!i["dot-notation"])P=[P.join(".")];P.slice(0,-1).forEach(function(R){H=H[R]||{}});let B=P[P.length-1];if(typeof H!=="object")return!1;else return B in H}function U(T,P,H){let B=T;if(!i["dot-notation"])P=[P.join(".")];P.slice(0,-1).forEach(function(Pe){if(Pe=xu(Pe),typeof B==="object"&&B[Pe]===void 0)B[Pe]={};if(typeof B[Pe]!=="object"||Array.isArray(B[Pe])){if(Array.isArray(B[Pe]))B[Pe].push({});else B[Pe]=[B[Pe],{}];B=B[Pe][B[Pe].length-1]}else B=B[Pe]});let R=xu(P[P.length-1]),te=q(P.join("."),w.arrays),V=Array.isArray(H),oe=i["duplicate-arguments-array"];if(!oe&&q(R,w.nargs)){if(oe=!0,!be(B[R])&&w.nargs[R]===1||Array.isArray(B[R])&&B[R].length===w.nargs[R])B[R]=void 0}if(H===Ai())B[R]=Ai(B[R]);else if(Array.isArray(B[R]))if(oe&&te&&V)B[R]=i["flatten-duplicate-arrays"]?B[R].concat(H):(Array.isArray(B[R][0])?B[R]:[B[R]]).concat([H]);else if(!oe&&Boolean(te)===Boolean(V))B[R]=H;else B[R]=B[R].concat([H]);else if(B[R]===void 0&&te)B[R]=V?H:[H];else if(oe&&!(B[R]===void 0||q(R,w.counts)||q(R,w.bools)))B[R]=[B[R],H];else B[R]=H}function ie(...T){T.forEach(function(P){Object.keys(P||{}).forEach(function(H){if(w.aliases[H])return;w.aliases[H]=[].concat(o[H]||[]),w.aliases[H].concat(H).forEach(function(B){if(/-/.test(B)&&i["camel-case-expansion"]){let R=Dn(B);if(R!==H&&w.aliases[H].indexOf(R)===-1)w.aliases[H].push(R),g[R]=!0}}),w.aliases[H].concat(H).forEach(function(B){if(B.length>1&&/[A-Z]/.test(B)&&i["camel-case-expansion"]){let R=$r(B,"-");if(R!==H&&w.aliases[H].indexOf(R)===-1)w.aliases[H].push(R),g[R]=!0}}),w.aliases[H].forEach(function(B){w.aliases[B]=[H].concat(w.aliases[H].filter(function(R){return B!==R}))})})})}function q(T,P){let H=[].concat(w.aliases[T]||[],T),B=Object.keys(P),R=H.find((te)=>B.includes(te));return R?P[R]:!1}function ce(T){let P=Object.keys(w);return[].concat(P.map((B)=>w[B])).some(function(B){return Array.isArray(B)?B.includes(T):B[T]})}function z(T,...P){return[].concat(...P).some(function(B){let R=T.match(B);return R&&ce(R[1])})}function K(T){if(T.match(u)||!T.match(/^-[^-]+/))return!1;let P=!0,H,B=T.slice(1).split("");for(let R=0;R<B.length;R++){if(H=T.slice(R+2),!ce(B[R])){P=!1;break}if(B[R+1]&&B[R+1]==="="||H==="-"||/[A-Za-z]/.test(B[R])&&/^-?\d+(\.\d*)?(e-?\d+)?$/.test(H)||B[R+1]&&B[R+1].match(/\W/))break}return P}function ne(T){return i["unknown-options-as-args"]&&fe(T)}function fe(T){if(T=T.replace(/^-{3,}/,"--"),T.match(u))return!1;if(K(T))return!1;return!z(T,/^-+([^=]+?)=[\s\S]*$/,l,/^-+([^=]+?)$/,/^-+([^=]+?)-$/,/^-+([^=]+?\d+)$/,/^-+([^=]+?)\W+.*$/)}function Y(T){if(!q(T,w.bools)&&!q(T,w.counts)&&`${T}`in a)return a[T];else return se(pe(T))}function se(T){return{[ct.BOOLEAN]:!0,[ct.STRING]:"",[ct.NUMBER]:void 0,[ct.ARRAY]:[]}[T]}function pe(T){let P=ct.BOOLEAN;if(q(T,w.strings))P=ct.STRING;else if(q(T,w.numbers))P=ct.NUMBER;else if(q(T,w.bools))P=ct.BOOLEAN;else if(q(T,w.arrays))P=ct.ARRAY;return P}function be(T){return T===void 0}function wn(){Object.keys(w.counts).find((T)=>{if(q(T,w.arrays))return h=Error(k("Invalid configuration: %s, opts.count excludes opts.array.",T)),!0;else if(q(T,w.nargs))return h=Error(k("Invalid configuration: %s, opts.count excludes opts.narg.",T)),!0;return!1})}return{aliases:Object.assign({},w.aliases),argv:Object.assign(_,b),configuration:i,defaulted:Object.assign({},y),error:h,newAliases:Object.assign({},g)}}}function Hy(e){let t=[],n=Object.create(null),s=!0;Object.keys(e).forEach(function(r){t.push([].concat(e[r],r))});while(s){s=!1;for(let r=0;r<t.length;r++)for(let o=r+1;o<t.length;o++)if(t[r].filter(function(a){return t[o].indexOf(a)!==-1}).length){t[r]=t[r].concat(t[o]),t.splice(o,1),s=!0;break}}return t.forEach(function(r){r=r.filter(function(i,a,c){return c.indexOf(i)===a});let o=r.pop();if(o!==void 0&&typeof o==="string")n[o]=r}),n}function Ai(e){return e!==void 0?e+1:1}function xu(e){if(e==="__proto__")return"___proto___";return e}function zy(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 Vy}from"fs";import{createRequire as Su}from"node:module";var Fi,Oi,Ii,_u=process&&process.env&&process.env.YARGS_MIN_NODE_VERSION?Number(process.env.YARGS_MIN_NODE_VERSION):20,Eu=(Oi=(Fi=process===null||process===void 0?void 0:process.versions)===null||Fi===void 0?void 0:Fi.node)!==null&&Oi!==void 0?Oi:(Ii=process===null||process===void 0?void 0:process.version)===null||Ii===void 0?void 0:Ii.slice(1);if(Eu){if(Number(Eu.match(/^([^.]+)/)[1])<_u)throw Error(`yargs parser supports a minimum Node.js version of ${_u}. Read our version support policy: https://github.com/yargs/yargs-parser#supported-nodejs-versions`)}var Zy=process?process.env:{},$u=Su?Su(import.meta.url):void 0,Cu=new Ti({cwd:process.cwd,env:()=>Zy,format:Yy,normalize:Gy,resolve:Xy,require:(e)=>{if(typeof $u<"u")return $u(e);else if(e.match(/\.json$/))return JSON.parse(Vy(e,"utf8"));else throw Error("only .json config files are supported in ESM")}}),Cs=function(t,n){return Cu.parse(t.slice(),n).argv};Cs.detailed=function(e,t){return Cu.parse(e.slice(),t)};Cs.camelCase=Dn;Cs.decamelize=$r;Cs.looksLikeNumber=Cr;var Ri=Cs;import{basename as ub,dirname as db,extname as fb,relative as pb,resolve as Lu,join as hb}from"path";function Au(){if(Qy())return 0;return 1}function Qy(){return eb()&&!process.defaultApp}function eb(){return!!process.versions.electron}function vi(e){return e.slice(Au()+1)}function Tu(){return process.argv[Au()]}import{readFileSync as tb,statSync as nb,writeFile as sb}from"fs";import{format as rb}from"util";import{resolve as ob}from"path";var Fu={fs:{readFileSync:tb,writeFile:sb},format:rb,resolve:ob,exists:(e)=>{try{return nb(e).isFile()}catch(t){return!1}}};var wt;class Ou{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 wt.format.apply(wt.format,[this.cache[this.locale][t]||t].concat(e))}__n(){let e=Array.prototype.slice.call(arguments),t=e.shift(),n=e.shift(),s=e.shift(),r=function(){};if(typeof e[e.length-1]==="function")r=e.pop();if(!this.cache[this.locale])this._readLocaleFile();let o=s===1?t:n;if(this.cache[this.locale][t])o=this.cache[this.locale][t][s===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:r});else r();let i=[o];if(~o.indexOf("%d"))i.push(s);return wt.format.apply(wt.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(s,r){let o=t[r+1];if(n+=s,typeof o<"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],n=t.directory,s=t.locale,r=t.cb,o=this._resolveLocaleFile(n,s),i=JSON.stringify(this.cache[s],null,2);wt.fs.writeFile(o,i,"utf-8",function(a){if(e.writeQueue.shift(),e.writeQueue.length>0)e._processWriteQueue();r(a)})}_readLocaleFile(){let e={},t=this._resolveLocaleFile(this.directory,this.locale);try{if(wt.fs.readFileSync)e=JSON.parse(wt.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=wt.resolve(e,"./",t+".json");if(this.fallbackToLanguage&&!this._fileExistsSync(n)&&~t.lastIndexOf("_")){let s=wt.resolve(e,"./",t.split("_")[0]+".json");if(this._fileExistsSync(s))n=s}return n}_fileExistsSync(e){return wt.exists(e)}}function Iu(e,t){wt=t;let n=new Ou(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 ib=(e)=>Iu(e,Fu),Ru=ib;var Mu=Jl(Pu(),1);import{createRequire as gb}from"node:module";import{readFileSync as mb,readdirSync as yb}from"node:fs";var Pi=Nu(import.meta.url),bb=Pi.substring(0,Pi.lastIndexOf("node_modules")),wb=gb(import.meta.url),Li={assert:{notStrictEqual:ab,strictEqual:cb},cliui:$i,findUp:Ci,getEnv:(e)=>process.env[e],inspect:lb,getProcessArgvBin:Tu,mainFilename:bb||process.cwd(),Parser:Ri,path:{basename:ub,dirname:db,extname:fb,relative:pb,resolve:Lu,join:hb},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:mb,readdirSync:yb,require:wb,getCallerFile:()=>{let e=Mu.default(3);return e.match(/^file:\/\//)?Nu(e):e},stringWidth:bt,y18n:Ru({directory:Lu(Pi,"../../../locales"),updateFiles:!1})};function qe(e,t,n,s){n.assert.notStrictEqual(e,t,s)}function Ni(e,t){t.assert.strictEqual(typeof e,"string")}function Zn(e){return Object.keys(e)}function xe(e){return!!e&&!!e.then&&typeof e.then==="function"}class Te extends Error{constructor(e){super(e||"yargs error");if(this.name="YError",Error.captureStackTrace)Error.captureStackTrace(this,Te)}}function Zt(e){let n=e.replace(/\s{2,}/g," ").split(/\s+(?![^[]*]|[^<]*>)/),s=/\.*[\][<>]/g,r=n.shift();if(!r)throw Error(`No command found in: ${e}`);let o={cmd:r.replace(s,""),demanded:[],optional:[]};return n.forEach((i,a)=>{let c=!1;if(i=i.replace(/\s/g,""),/\.+[\]>]/.test(i)&&a===n.length-1)c=!0;if(/^\[/.test(i))o.optional.push({cmd:i.replace(s,"").split("|"),variadic:c});else o.demanded.push({cmd:i.replace(s,"").split("|"),variadic:c})}),o}var kb=["first","second","third","fourth","fifth","sixth"];function Z(e,t,n){function s(){return typeof e==="object"?[{demanded:[],optional:[]},e,t]:[Zt(`cmd ${e}`),t,n]}try{let r=0,[o,i,a]=s(),c=[].slice.call(i);while(c.length&&c[c.length-1]===void 0)c.pop();let d=a||c.length;if(d<o.demanded.length)throw new Te(`Not enough arguments provided. Expected ${o.demanded.length} but received ${c.length}.`);let f=o.demanded.length+o.optional.length;if(d>f)throw new Te(`Too many arguments provided. Expected max ${f} but received ${d}.`);o.demanded.forEach((p)=>{let g=c.shift(),y=Bu(g);if(p.cmd.filter((w)=>w===y||w==="*").length===0)ju(y,p.cmd,r);r+=1}),o.optional.forEach((p)=>{if(c.length===0)return;let g=c.shift(),y=Bu(g);if(p.cmd.filter((w)=>w===y||w==="*").length===0)ju(y,p.cmd,r);r+=1})}catch(r){console.warn(r.stack)}}function Bu(e){if(Array.isArray(e))return"array";else if(e===null)return"null";return typeof e}function ju(e,t,n){throw new Te(`Invalid ${kb[n]||"manyith"} argument. Expected ${t.join(" or ")} but received ${e}.`)}class Mi{constructor(e){this.globalMiddleware=[],this.frozens=[],this.yargs=e}addMiddleware(e,t,n=!0,s=!1){if(Z("<array|function> [boolean] [boolean] [boolean]",[e,t,n],arguments.length),Array.isArray(e)){for(let r=0;r<e.length;r++){if(typeof e[r]!=="function")throw Error("middleware must be a function");let o=e[r];o.applyBeforeValidation=t,o.global=n}Array.prototype.push.apply(this.globalMiddleware,e)}else if(typeof e==="function"){let r=e;r.applyBeforeValidation=t,r.global=n,r.mutates=s,this.globalMiddleware.push(e)}return this.yargs}addCoerceMiddleware(e,t){let n=this.yargs.getAliases();return this.globalMiddleware=this.globalMiddleware.filter((s)=>{let r=[...n[t]||[],t];if(!s.option)return!0;else return!r.includes(s.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 Wu(e){if(!e)return[];return e.map((t)=>(t.applyBeforeValidation=!1,t))}function xn(e,t,n,s){return n.reduce((r,o)=>{if(o.applyBeforeValidation!==s)return r;if(o.mutates){if(o.applied)return r;o.applied=!0}if(xe(r))return r.then((i)=>Promise.all([i,o(i,t)])).then(([i,a])=>Object.assign(i,a));else{let i=o(r,t);return xe(i)?i.then((a)=>Object.assign(r,a)):Object.assign(r,i)}},e)}function Sn(e,t,n=(s)=>{throw s}){try{let s=Db(e)?e():e;return xe(s)?s.then((r)=>t(r)):t(s)}catch(s){return n(s)}}function Db(e){return typeof e==="function"}var Qn=/(^\*)|(^\$0)/;class Ju{constructor(e,t,n,s){this.requireCache=new Set,this.handlers={},this.aliasMap={},this.frozens=[],this.shim=s,this.usage=e,this.globalMiddleware=n,this.validation=t}addDirectory(e,t,n,s){s=s||{},this.requireCache.add(n);let r=this.shim.path.resolve(this.shim.path.dirname(n),e),o=this.shim.readdirSync(r,{recursive:s.recurse?!0:!1});if(!Array.isArray(s.extensions))s.extensions=["js"];let i=typeof s.visit==="function"?s.visit:(a)=>a;for(let a of o){let c=a.toString();if(s.exclude){let f=!1;if(typeof s.exclude==="function")f=s.exclude(c);else f=s.exclude.test(c);if(f)continue}if(s.include){let f=!1;if(typeof s.include==="function")f=s.include(c);else f=s.include.test(c);if(!f)continue}let d=!1;for(let f of s.extensions)if(c.endsWith(f))d=!0;if(d){let f=this.shim.path.join(r,c),p=t(f),g=Object.create(null,Object.getOwnPropertyDescriptors({...p}));if(i(g,f,c)){if(this.requireCache.has(f))continue;else this.requireCache.add(f);if(!g.command)g.command=this.shim.path.basename(f,this.shim.path.extname(f));this.addHandler(g)}}}}addHandler(e,t,n,s,r,o){let i=[],a=Wu(r);if(s=s||(()=>{}),Array.isArray(e))if(xb(e))[e,...i]=e;else for(let c of e)this.addHandler(c);else if(_b(e)){let c=Array.isArray(e.command)||typeof e.command==="string"?e.command:null;if(c===null)throw Error(`No command name given for module: ${this.shim.inspect(e)}`);if(e.aliases)c=[].concat(c).concat(e.aliases);this.addHandler(c,this.extractDesc(e),e.builder,e.handler,e.middlewares,e.deprecated);return}else if(Uu(n)){this.addHandler([e].concat(i),t,n.builder,n.handler,n.middlewares,n.deprecated);return}if(typeof e==="string"){let c=Zt(e);i=i.map((p)=>Zt(p).cmd);let d=!1,f=[c.cmd].concat(i).filter((p)=>{if(Qn.test(p))return d=!0,!1;return!0});if(f.length===0&&d)f.push("$0");if(d)c.cmd=f[0],i=f.slice(1),e=e.replace(Qn,c.cmd);if(i.forEach((p)=>{this.aliasMap[p]=c.cmd}),t!==!1)this.usage.command(e,t,d,i,o);if(this.handlers[c.cmd]={original:e,description:t,handler:s,builder:n||{},middlewares:a,deprecated:o,demanded:c.demanded,optional:c.optional},d)this.defaultCommand=this.handlers[c.cmd]}}getCommandHandlers(){return this.handlers}getCommands(){return Object.keys(this.handlers).concat(Object.keys(this.aliasMap))}hasDefaultCommand(){return!!this.defaultCommand}runCommand(e,t,n,s,r,o){let i=this.handlers[e]||this.handlers[this.aliasMap[e]]||this.defaultCommand,a=t.getInternalMethods().getContext(),c=a.commands.slice(),d=!e;if(e)a.commands.push(e),a.fullCommands.push(i.original);let f=this.applyBuilderUpdateUsageAndParse(d,i,t,n.aliases,c,s,r,o);return xe(f)?f.then((p)=>this.applyMiddlewareAndGetResult(d,i,p.innerArgv,a,r,p.aliases,t)):this.applyMiddlewareAndGetResult(d,i,f.innerArgv,a,r,f.aliases,t)}applyBuilderUpdateUsageAndParse(e,t,n,s,r,o,i,a){let c=t.builder,d=n;if(Ar(c)){n.getInternalMethods().getUsageInstance().freeze();let f=c(n.getInternalMethods().reset(s),a);if(xe(f))return f.then((p)=>(d=qu(p)?p:n,this.parseAndUpdateUsage(e,t,d,r,o,i)))}else if(Sb(c))n.getInternalMethods().getUsageInstance().freeze(),d=n.getInternalMethods().reset(s),Object.keys(t.builder).forEach((f)=>{d.option(f,c[f])});return this.parseAndUpdateUsage(e,t,d,r,o,i)}parseAndUpdateUsage(e,t,n,s,r,o){if(e)n.getInternalMethods().getUsageInstance().unfreeze(!0);if(this.shouldUpdateUsage(n))n.getInternalMethods().getUsageInstance().usage(this.usageFromParentCommandsCommandHandler(s,t),t.description);let i=n.getInternalMethods().runYargsParserAndExecuteCommands(null,void 0,!0,r,o);return xe(i)?i.then((a)=>({aliases:n.parsed.aliases,innerArgv:a})):{aliases:n.parsed.aliases,innerArgv:i}}shouldUpdateUsage(e){return!e.getInternalMethods().getUsageInstance().getUsageDisabled()&&e.getInternalMethods().getUsageInstance().getUsage().length===0}usageFromParentCommandsCommandHandler(e,t){let n=Qn.test(t.original)?t.original.replace(Qn,"").trim():t.original,s=e.filter((r)=>!Qn.test(r));return s.push(n),`$0 ${s.join(" ")}`}handleValidationAndGetResult(e,t,n,s,r,o,i,a){if(!o.getInternalMethods().getHasOutput()){let c=o.getInternalMethods().runValidation(r,a,o.parsed.error,e);n=Sn(n,(d)=>(c(d),d))}if(t.handler&&!o.getInternalMethods().getHasOutput()){o.getInternalMethods().setHasOutput();let c=!!o.getOptions().configuration["populate--"];if(o.getInternalMethods().postProcess(n,c,!1,!1),n=xn(n,o,i,!1),n=Sn(n,(d)=>{let f=t.handler(d);return xe(f)?f.then(()=>d):d}),!e)o.getInternalMethods().getUsageInstance().cacheHelpMessage();if(xe(n)&&!o.getInternalMethods().hasParseCallback())n.catch((d)=>{try{o.getInternalMethods().getUsageInstance().fail(null,d)}catch(f){}})}if(!e)s.commands.pop(),s.fullCommands.pop();return n}applyMiddlewareAndGetResult(e,t,n,s,r,o,i){let a={};if(r)return n;if(!i.getInternalMethods().getHasOutput())a=this.populatePositionals(t,n,s,i);let c=this.globalMiddleware.getMiddleware().slice(0).concat(t.middlewares),d=xn(n,i,c,!0);return xe(d)?d.then((f)=>this.handleValidationAndGetResult(e,t,f,s,o,i,c,a)):this.handleValidationAndGetResult(e,t,d,s,o,i,c,a)}populatePositionals(e,t,n,s){t._=t._.slice(n.commands.length);let r=e.demanded.slice(0),o=e.optional.slice(0),i={};this.validation.positionalCount(r.length,t._.length);while(r.length){let a=r.shift();this.populatePositional(a,t,i)}while(o.length){let a=o.shift();this.populatePositional(a,t,i)}return t._=n.commands.concat(t._.map((a)=>""+a)),this.postProcessPositionals(t,i,this.cmdToParseOptions(e.original),s),i}populatePositional(e,t,n){let s=e.cmd[0];if(e.variadic)n[s]=t._.splice(0).map(String);else if(t._.length)n[s]=[String(t._.shift())]}cmdToParseOptions(e){let t={array:[],default:{},alias:{},demand:{}},n=Zt(e);return n.demanded.forEach((s)=>{let[r,...o]=s.cmd;if(s.variadic)t.array.push(r),t.default[r]=[];t.alias[r]=o,t.demand[r]=!0}),n.optional.forEach((s)=>{let[r,...o]=s.cmd;if(s.variadic)t.array.push(r),t.default[r]=[];t.alias[r]=o}),t}postProcessPositionals(e,t,n,s){let r=Object.assign({},s.getOptions());r.default=Object.assign(n.default,r.default);for(let c of Object.keys(n.alias))r.alias[c]=(r.alias[c]||[]).concat(n.alias[c]);r.array=r.array.concat(n.array),r.config={};let o=[];if(Object.keys(t).forEach((c)=>{t[c].map((d)=>{if(r.configuration["unknown-options-as-args"])r.key[c]=!0;o.push(`--${c}`),o.push(d)})}),!o.length)return;let i=Object.assign({},r.configuration,{"populate--":!1}),a=this.shim.Parser.detailed(o,Object.assign({},r,{configuration:i}));if(a.error)s.getInternalMethods().getUsageInstance().fail(a.error.message,a.error);else{let c=Object.keys(t);Object.keys(t).forEach((d)=>{c.push(...a.aliases[d])}),Object.keys(a.argv).forEach((d)=>{if(c.includes(d)){if(!t[d])t[d]=a.argv[d];if(!this.isInConfigs(s,d)&&!this.isDefaulted(s,d)&&Object.prototype.hasOwnProperty.call(e,d)&&Object.prototype.hasOwnProperty.call(a.argv,d)&&(Array.isArray(e[d])||Array.isArray(a.argv[d])))e[d]=[].concat(e[d],a.argv[d]);else e[d]=a.argv[d]}})}}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((s)=>Object.prototype.hasOwnProperty.call(s,t))||n.some((s)=>Object.prototype.hasOwnProperty.call(s,this.shim.Parser.camelCase(t)))}runDefaultBuilderOn(e){if(!this.defaultCommand)return;if(this.shouldUpdateUsage(e)){let n=Qn.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(Ar(t))return t(e,!0);else if(!Uu(t))Object.keys(t).forEach((n)=>{e.option(n,t[n])});return}extractDesc({describe:e,description:t,desc:n}){for(let s of[e,t,n]){if(typeof s==="string"||s===!1)return s;qe(s,!0,this.shim)}return!1}freeze(){this.frozens.push({handlers:this.handlers,aliasMap:this.aliasMap,defaultCommand:this.defaultCommand})}unfreeze(){let e=this.frozens.pop();qe(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 Ku(e,t,n,s){return new Ju(e,t,n,s)}function Uu(e){return typeof e==="object"&&!!e.builder&&typeof e.handler==="function"}function xb(e){return e.every((t)=>typeof t==="string")}function Ar(e){return typeof e==="function"}function Sb(e){return typeof e==="object"}function _b(e){return typeof e==="object"&&!Array.isArray(e)}function Qt(e={},t=()=>!0){let n={};return Zn(e).forEach((s)=>{if(t(s,e[s]))n[s]=e[s]}),n}function en(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 Eb(e){return typeof e==="boolean"}function zu(e,t){let n=t.y18n.__,s={},r=[];s.failFn=function(A){r.push(A)};let o=null,i=null,a=!0;s.showHelpOnFail=function(A=!0,F){let[v,O]=typeof A==="string"?[!0,A]:[A,F];if(e.getInternalMethods().isGlobalContext())i=O;return o=O,a=v,s};let c=!1;s.fail=function(A,F){let v=e.getInternalMethods().getLoggerInstance();if(r.length)for(let O=r.length-1;O>=0;--O){let M=r[O];if(Eb(M)){if(F)throw F;else if(A)throw Error(A)}else M(A,F,s)}else{if(e.getExitProcess())en(!0);if(!c){if(c=!0,a)e.showHelp("error"),v.error();if(A||F)v.error(A||F);let O=o||i;if(O){if(A||F)v.error("");v.error(O)}}if(F=F||new Te(A),e.getExitProcess())return e.exit(1);else if(e.getInternalMethods().hasParseCallback())return e.exit(1,F);else throw F}};let d=[],f=!1;s.usage=(C,A)=>{if(C===null)return f=!0,d=[],s;return f=!1,d.push([C,A||""]),s},s.getUsage=()=>d,s.getUsageDisabled=()=>f,s.getPositionalGroupName=()=>n("Positionals:");let p=[];s.example=(C,A)=>{p.push([C,A||""])};let g=[];s.command=function(A,F,v,O,M=!1){if(v)g=g.map((J)=>(J[2]=!1,J));g.push([A,F||"",v,O,M])},s.getCommands=()=>g;let y={};s.describe=function(A,F){if(Array.isArray(A))A.forEach((v)=>{s.describe(v,F)});else if(typeof A==="object")Object.keys(A).forEach((v)=>{s.describe(v,A[v])});else y[A]=F},s.getDescriptions=()=>y;let k=[];s.epilog=(C)=>{k.push(C)};let w=!1,u;s.wrap=(C)=>{w=!0,u=C},s.getWrap=()=>{if(t.getEnv("YARGS_DISABLE_WRAP"))return null;if(!w)u=E(),w=!0;return u};let l="__yargsString__:";s.deferY18nLookup=(C)=>l+C,s.help=function(){if(b)return b;m();let A=e.customScriptName?e.$0:t.path.basename(e.$0),F=e.getDemandedOptions(),v=e.getDemandedCommands(),O=e.getDeprecatedOptions(),M=e.getGroups(),J=e.getOptions(),j=[];j=j.concat(Object.keys(y)),j=j.concat(Object.keys(F)),j=j.concat(Object.keys(v)),j=j.concat(Object.keys(J.default)),j=j.filter(x),j=Object.keys(j.reduce((K,ne)=>{if(ne!=="_")K[ne]=!0;return K},{}));let ee=s.getWrap(),X=t.cliui({width:ee,wrap:!!ee});if(!f){if(d.length)d.forEach((K)=>{if(X.div({text:`${K[0].replace(/\$0/g,A)}`}),K[1])X.div({text:`${K[1]}`,padding:[1,0,0,0]})}),X.div();else if(g.length){let K=null;if(v._)K=`${A} <${n("command")}>
15
+ `;else K=`${A} [${n("command")}]
16
+ `;X.div(`${K}`)}}if(g.length>1||g.length===1&&!g[0][2]){X.div(n("Commands:"));let K=e.getInternalMethods().getContext(),ne=K.commands.length?`${K.commands.join(" ")} `:"";if(e.getInternalMethods().getParserConfiguration()["sort-commands"]===!0)g=g.sort((Y,se)=>Y[0].localeCompare(se[0]));let fe=A?`${A} `:"";g.forEach((Y)=>{let se=`${fe}${ne}${Y[0].replace(/^\$0 ?/,"")}`;X.span({text:se,padding:[0,2,0,2],width:h(g,ee,`${A}${ne}`)+4},{text:Y[1]});let pe=[];if(Y[2])pe.push(`[${n("default")}]`);if(Y[3]&&Y[3].length)pe.push(`[${n("aliases:")} ${Y[3].join(", ")}]`);if(Y[4])if(typeof Y[4]==="string")pe.push(`[${n("deprecated: %s",Y[4])}]`);else pe.push(`[${n("deprecated")}]`);if(pe.length)X.div({text:pe.join(" "),padding:[0,0,0,2],align:"right"});else X.div()}),X.div()}let U=(Object.keys(J.alias)||[]).concat(Object.keys(e.parsed.newAliases)||[]);j=j.filter((K)=>!e.parsed.newAliases[K]&&U.every((ne)=>(J.alias[ne]||[]).indexOf(K)===-1));let ie=n("Options:");if(!M[ie])M[ie]=[];_(j,J.alias,M,ie);let q=(K)=>/^--/.test(Tr(K)),ce=Object.keys(M).filter((K)=>M[K].length>0).map((K)=>{let ne=M[K].filter(x).map((fe)=>{if(U.includes(fe))return fe;for(let Y=0,se;(se=U[Y])!==void 0;Y++)if((J.alias[se]||[]).includes(fe))return se;return fe});return{groupName:K,normalizedKeys:ne}}).filter(({normalizedKeys:K})=>K.length>0).map(({groupName:K,normalizedKeys:ne})=>{let fe=ne.reduce((Y,se)=>(Y[se]=[se].concat(J.alias[se]||[]).map((pe)=>{if(K===s.getPositionalGroupName())return pe;else return(/^[0-9]$/.test(pe)?J.boolean.includes(se)?"-":"--":pe.length>1?"--":"-")+pe}).sort((pe,be)=>q(pe)===q(be)?0:q(pe)?1:-1).join(", "),Y),{});return{groupName:K,normalizedKeys:ne,switches:fe}});if(ce.filter(({groupName:K})=>K!==s.getPositionalGroupName()).some(({normalizedKeys:K,switches:ne})=>!K.every((fe)=>q(ne[fe]))))ce.filter(({groupName:K})=>K!==s.getPositionalGroupName()).forEach(({normalizedKeys:K,switches:ne})=>{K.forEach((fe)=>{if(q(ne[fe]))ne[fe]=$b(ne[fe],4)})});if(ce.forEach(({groupName:K,normalizedKeys:ne,switches:fe})=>{X.div(K),ne.forEach((Y)=>{let se=fe[Y],pe=y[Y]||"",be=null;if(pe.includes(l))pe=n(pe.substring(l.length));if(J.boolean.includes(Y))be=`[${n("boolean")}]`;if(J.count.includes(Y))be=`[${n("count")}]`;if(J.string.includes(Y))be=`[${n("string")}]`;if(J.normalize.includes(Y))be=`[${n("string")}]`;if(J.array.includes(Y))be=`[${n("array")}]`;if(J.number.includes(Y))be=`[${n("number")}]`;let wn=(H)=>typeof H==="string"?`[${n("deprecated: %s",H)}]`:`[${n("deprecated")}]`,T=[Y in O?wn(O[Y]):null,be,Y in F?`[${n("required")}]`:null,J.choices&&J.choices[Y]?`[${n("choices:")} ${s.stringifiedValues(J.choices[Y])}]`:null,S(J.default[Y],J.defaultDescription[Y])].filter(Boolean).join(" ");X.span({text:Tr(se),padding:[0,2,0,2+Hu(se)],width:h(fe,ee)+4},pe);let P=e.getInternalMethods().getUsageConfiguration()["hide-types"]===!0;if(T&&!P)X.div({text:T,padding:[0,0,0,2],align:"right"});else X.div()}),X.div()}),p.length)X.div(n("Examples:")),p.forEach((K)=>{K[0]=K[0].replace(/\$0/g,A)}),p.forEach((K)=>{if(K[1]==="")X.div({text:K[0],padding:[0,2,0,2]});else X.div({text:K[0],padding:[0,2,0,2],width:h(p,ee)+4},{text:K[1]})}),X.div();if(k.length>0){let K=k.map((ne)=>ne.replace(/\$0/g,A)).join(`
17
+ `);X.div(`${K}
18
+ `)}return X.toString().replace(/\s*$/,"")};function h(C,A,F){let v=0;if(!Array.isArray(C))C=Object.values(C).map((O)=>[O]);if(C.forEach((O)=>{v=Math.max(t.stringWidth(F?`${F} ${Tr(O[0])}`:Tr(O[0]))+Hu(O[0]),v)}),A)v=Math.min(v,parseInt((A*0.5).toString(),10));return v}function m(){let C=e.getDemandedOptions(),A=e.getOptions();(Object.keys(A.alias)||[]).forEach((F)=>{A.alias[F].forEach((v)=>{if(y[v])s.describe(F,y[v]);if(v in C)e.demandOption(F,C[v]);if(A.boolean.includes(v))e.boolean(F);if(A.count.includes(v))e.count(F);if(A.string.includes(v))e.string(F);if(A.normalize.includes(v))e.normalize(F);if(A.array.includes(v))e.array(F);if(A.number.includes(v))e.number(F)})})}let b;s.cacheHelpMessage=function(){b=this.help()},s.clearCachedHelpMessage=function(){b=void 0},s.hasCachedHelpMessage=function(){return!!b};function _(C,A,F,v){let O=[],M=null;return Object.keys(F).forEach((J)=>{O=O.concat(F[J])}),C.forEach((J)=>{if(M=[J].concat(A[J]),!M.some((j)=>O.indexOf(j)!==-1))F[v].push(J)}),O}function x(C){return e.getOptions().hiddenOptions.indexOf(C)<0||e.parsed.argv[e.getOptions().showHiddenOpt]}s.showHelp=(C)=>{let A=e.getInternalMethods().getLoggerInstance();if(!C)C="error";(typeof C==="function"?C:A[C])(s.help())},s.functionDescription=(C)=>["(",C.name?t.Parser.decamelize(C.name,"-"):n("generated-value"),")"].join(""),s.stringifiedValues=function(A,F){let v="",O=F||", ",M=[].concat(A);if(!A||!M.length)return v;return M.forEach((J)=>{if(v.length)v+=O;v+=JSON.stringify(J)}),v};function S(C,A){let F=`[${n("default:")} `;if(C===void 0&&!A)return null;if(A)F+=A;else switch(typeof C){case"string":F+=`"${C}"`;break;case"object":F+=JSON.stringify(C);break;default:F+=C}return`${F}]`}function E(){if(t.process.stdColumns)return Math.min(80,t.process.stdColumns);else return 80}let I=null;s.version=(C)=>{I=C},s.showVersion=(C)=>{let A=e.getInternalMethods().getLoggerInstance();if(!C)C="error";(typeof C==="function"?C:A[C])(I)},s.reset=function(A){return o=null,c=!1,d=[],f=!1,k=[],p=[],g=[],y=Qt(y,(F)=>!A[F]),s};let N=[];return s.freeze=function(){N.push({failMessage:o,failureOutput:c,usages:d,usageDisabled:f,epilogs:k,examples:p,commands:g,descriptions:y})},s.unfreeze=function(A=!1){let F=N.pop();if(!F)return;if(A)y={...F.descriptions,...y},g=[...F.commands,...g],d=[...F.usages,...d],p=[...F.examples,...p],k=[...F.epilogs,...k];else({failMessage:o,failureOutput:c,usages:d,usageDisabled:f,epilogs:k,examples:p,commands:g,descriptions:y}=F)},s}function Bi(e){return typeof e==="object"}function $b(e,t){return Bi(e)?{text:e.text,indentation:e.indentation+t}:{text:e,indentation:t}}function Hu(e){return Bi(e)?e.indentation:0}function Tr(e){return Bi(e)?e.text:e}var Yu=`###-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
- `,Ru=`#compdef {{app_name}}
47
+ `,Gu=`#compdef {{app_name}}
48
48
  ###-begin-{{app_name}}-completions-###
49
49
  #
50
50
  # yargs command completion script
@@ -71,24 +71,24 @@ else
71
71
  compdef _{{app_name}}_yargs_completions {{app_name}}
72
72
  fi
73
73
  ###-end-{{app_name}}-completions-###
74
- `;class Iu{constructor(e,t,n,s){var r,o,i;this.yargs=e,this.usage=t,this.command=n,this.shim=s,this.completionKey="get-yargs-completions",this.aliases=null,this.customCompletionFunction=null,this.indexAfterLastReset=0,this.zshShell=(i=((r=this.shim.getEnv("SHELL"))===null||r===void 0?void 0:r.includes("zsh"))||((o=this.shim.getEnv("ZSH_NAME"))===null||o===void 0?void 0:o.includes("zsh")))!==null&&i!==void 0?i:!1}defaultCompletion(e,t,n,s){let r=this.command.getCommandHandlers();for(let i=0,l=e.length;i<l;++i)if(r[e[i]]&&r[e[i]].builder){let u=r[e[i]].builder;if(Dr(u)){this.indexAfterLastReset=i+1;let f=this.yargs.getInternalMethods().reset();return u(f,!0),f.argv}}let o=[];this.commandCompletions(o,e,n),this.optionCompletions(o,e,t,n),this.choicesFromOptionsCompletions(o,e,t,n),this.choicesFromPositionalsCompletions(o,e,t,n),s(null,o)}commandCompletions(e,t,n){let s=this.yargs.getInternalMethods().getContext().commands;if(!n.match(/^-/)&&s[s.length-1]!==n&&!this.previousArgHasChoices(t))this.usage.getCommands().forEach((r)=>{let o=Xt(r[0]).cmd;if(t.indexOf(o)===-1)if(!this.zshShell)e.push(o);else{let i=r[1]||"";e.push(o.replace(/:/g,"\\:")+":"+i)}})}optionCompletions(e,t,n,s){if((s.match(/^-/)||s===""&&e.length===0)&&!this.previousArgHasChoices(t)){let r=this.yargs.getOptions(),o=this.yargs.getGroups()[this.usage.getPositionalGroupName()]||[];Object.keys(r.key).forEach((i)=>{let l=!!r.configuration["boolean-negation"]&&r.boolean.includes(i);if(!o.includes(i)&&!r.hiddenOptions.includes(i)&&!this.argsContainKey(t,i,l))this.completeOptionKey(i,e,s,l&&!!r.default[i])})}}choicesFromOptionsCompletions(e,t,n,s){if(this.previousArgHasChoices(t)){let r=this.getPreviousArgChoices(t);if(r&&r.length>0)e.push(...r.map((o)=>o.replace(/:/g,"\\:")))}}choicesFromPositionalsCompletions(e,t,n,s){if(s===""&&e.length>0&&this.previousArgHasChoices(t))return;let r=this.yargs.getGroups()[this.usage.getPositionalGroupName()]||[],o=Math.max(this.indexAfterLastReset,this.yargs.getInternalMethods().getContext().commands.length+1),i=r[n._.length-o-1];if(!i)return;let l=this.yargs.getOptions().choices[i]||[];for(let u of l)if(u.startsWith(s))e.push(u.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 s=t.replace(/^-+/,""),r=this.yargs.getOptions(),o=[s,...this.yargs.getAliases()[s]||[]],i;for(let l of o)if(Object.prototype.hasOwnProperty.call(r.key,l)&&Array.isArray(r.choices[l])){i=r.choices[l];break}if(i)return i.filter((l)=>!n||l.startsWith(n))}previousArgHasChoices(e){let t=this.getPreviousArgChoices(e);return t!==void 0&&t.length>0}argsContainKey(e,t,n){let s=(r)=>e.indexOf((/^[^0-9]$/.test(r)?"-":"--")+r)!==-1;if(s(t))return!0;if(n&&s(`no-${t}`))return!0;if(this.aliases){for(let r of this.aliases[t])if(s(r))return!0}return!1}completeOptionKey(e,t,n,s){var r,o,i,l;let u=e;if(this.zshShell){let d=this.usage.getDescriptions(),p=(o=(r=this===null||this===void 0?void 0:this.aliases)===null||r===void 0?void 0:r[e])===null||o===void 0?void 0:o.find((y)=>{let m=d[y];return typeof m==="string"&&m.length>0}),h=p?d[p]:void 0,g=(l=(i=d[e])!==null&&i!==void 0?i:h)!==null&&l!==void 0?l:"";u=`${e.replace(/:/g,"\\:")}:${g.replace("__yargsString__:","").replace(/(\r\n|\n|\r)/gm," ")}`}let f=(d)=>/^--/.test(d),a=(d)=>/^[^0-9]$/.test(d),c=!f(n)&&a(e)?"-":"--";if(t.push(c+u),s)t.push(c+"no-"+u)}customCompletion(e,t,n,s){if(Ke(this.customCompletionFunction,null,this.shim),eb(this.customCompletionFunction)){let r=this.customCompletionFunction(n,t);if(xe(r))return r.then((o)=>{this.shim.process.nextTick(()=>{s(null,o)})}).catch((o)=>{this.shim.process.nextTick(()=>{s(o,void 0)})});return s(null,r)}else if(tb(this.customCompletionFunction))return this.customCompletionFunction(n,t,(r=s)=>this.defaultCompletion(e,t,n,r),(r)=>{s(null,r)});else return this.customCompletionFunction(n,t,(r)=>{s(null,r)})}getCompletion(e,t){let n=e.length?e[e.length-1]:"",s=this.yargs.parse(e,!0),r=this.customCompletionFunction?(o)=>this.customCompletion(e,o,n,t):(o)=>this.defaultCompletion(e,o,n,t);return xe(s)?s.then(r):r(s)}generateCompletionScript(e,t){let n=this.zshShell?Ru:Ou,s=this.shim.path.basename(e);if(e.match(/\.js$/))e=`./${e}`;return n=n.replace(/{{app_name}}/g,s),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 vu(e,t,n,s){return new Iu(e,t,n,s)}function eb(e){return e.length<3}function tb(e){return e.length>3}function Pu(e,t){if(e.length===0)return t.length;if(t.length===0)return e.length;let n=[],s;for(s=0;s<=t.length;s++)n[s]=[s];let r;for(r=0;r<=e.length;r++)n[0][r]=r;for(s=1;s<=t.length;s++)for(r=1;r<=e.length;r++)if(t.charAt(s-1)===e.charAt(r-1))n[s][r]=n[s-1][r-1];else if(s>1&&r>1&&t.charAt(s-2)===e.charAt(r-1)&&t.charAt(s-1)===e.charAt(r-2))n[s][r]=n[s-2][r-2]+1;else n[s][r]=Math.min(n[s-1][r-1]+1,Math.min(n[s][r-1]+1,n[s-1][r]+1));return n[t.length][e.length]}var Lu=["$0","--","_"];function Nu(e,t,n){let s=n.y18n.__,r=n.y18n.__n,o={};o.nonOptionCount=function(c){let d=e.getDemandedCommands(),h=c._.length+(c["--"]?c["--"].length:0)-e.getInternalMethods().getContext().commands.length;if(d._&&(h<d._.min||h>d._.max)){if(h<d._.min)if(d._.minMsg!==void 0)t.fail(d._.minMsg?d._.minMsg.replace(/\$0/g,h.toString()).replace(/\$1/,d._.min.toString()):null);else t.fail(r("Not enough non-option arguments: got %s, need at least %s","Not enough non-option arguments: got %s, need at least %s",h,h.toString(),d._.min.toString()));else if(h>d._.max)if(d._.maxMsg!==void 0)t.fail(d._.maxMsg?d._.maxMsg.replace(/\$0/g,h.toString()).replace(/\$1/,d._.max.toString()):null);else t.fail(r("Too many non-option arguments: got %s, maximum of %s","Too many non-option arguments: got %s, maximum of %s",h,h.toString(),d._.max.toString()))}},o.positionalCount=function(c,d){if(d<c)t.fail(r("Not enough non-option arguments: got %s, need at least %s","Not enough non-option arguments: got %s, need at least %s",d,d+"",c+""))},o.requiredArguments=function(c,d){let p=null;for(let h of Object.keys(d))if(!Object.prototype.hasOwnProperty.call(c,h)||typeof c[h]>"u")p=p||{},p[h]=d[h];if(p){let h=[];for(let y of Object.keys(p)){let m=p[y];if(m&&h.indexOf(m)<0)h.push(m)}let g=h.length?`
75
- ${h.join(`
76
- `)}`:"";t.fail(r("Missing required argument: %s","Missing required arguments: %s",Object.keys(p).length,Object.keys(p).join(", ")+g))}},o.unknownArguments=function(c,d,p,h,g=!0){var y;let m=e.getInternalMethods().getCommandInstance().getCommands(),w=[],k=e.getInternalMethods().getContext();if(Object.keys(c).forEach((_)=>{if(!Lu.includes(_)&&!Object.prototype.hasOwnProperty.call(p,_)&&!Object.prototype.hasOwnProperty.call(e.getInternalMethods().getParseContext(),_)&&!o.isValidAndSomeAliasIsNotNew(_,d))w.push(_)}),g&&(k.commands.length>0||m.length>0||h))c._.slice(k.commands.length).forEach((_)=>{if(!m.includes(""+_))w.push(""+_)});if(g){let D=((y=e.getDemandedCommands()._)===null||y===void 0?void 0:y.max)||0,E=k.commands.length+D;if(E<c._.length)c._.slice(E).forEach((S)=>{if(S=String(S),!k.commands.includes(S)&&!w.includes(S))w.push(S)})}if(w.length)t.fail(r("Unknown argument: %s","Unknown arguments: %s",w.length,w.map((_)=>_.trim()?_:`"${_}"`).join(", ")))},o.unknownCommands=function(c){let d=e.getInternalMethods().getCommandInstance().getCommands(),p=[],h=e.getInternalMethods().getContext();if(h.commands.length>0||d.length>0)c._.slice(h.commands.length).forEach((g)=>{if(!d.includes(""+g))p.push(""+g)});if(p.length>0)return t.fail(r("Unknown command: %s","Unknown commands: %s",p.length,p.join(", "))),!0;else return!1},o.isValidAndSomeAliasIsNotNew=function(c,d){if(!Object.prototype.hasOwnProperty.call(d,c))return!1;let p=e.parsed.newAliases;return[c,...d[c]].some((h)=>!Object.prototype.hasOwnProperty.call(p,h)||!p[c])},o.limitedChoices=function(c){let d=e.getOptions(),p={};if(!Object.keys(d.choices).length)return;Object.keys(c).forEach((y)=>{if(Lu.indexOf(y)===-1&&Object.prototype.hasOwnProperty.call(d.choices,y))[].concat(c[y]).forEach((m)=>{if(d.choices[y].indexOf(m)===-1&&m!==void 0)p[y]=(p[y]||[]).concat(m)})});let h=Object.keys(p);if(!h.length)return;let g=s("Invalid values:");h.forEach((y)=>{g+=`
77
- ${s("Argument: %s, Given: %s, Choices: %s",y,t.stringifiedValues(p[y]),t.stringifiedValues(d.choices[y]))}`}),t.fail(g)};let i={};o.implies=function(c,d){if(Z("<string|object> [array|number|string]",[c,d],arguments.length),typeof c==="object")Object.keys(c).forEach((p)=>{o.implies(p,c[p])});else{if(e.global(c),!i[c])i[c]=[];if(Array.isArray(d))d.forEach((p)=>o.implies(c,p));else Ke(d,void 0,n),i[c].push(d)}},o.getImplied=function(){return i};function l(a,c){let d=Number(c);if(c=isNaN(d)?c:d,typeof c==="number")c=a._.length>=c;else if(c.match(/^--no-.+/))c=c.match(/^--no-(.+)/)[1],c=!Object.prototype.hasOwnProperty.call(a,c);else c=Object.prototype.hasOwnProperty.call(a,c);return c}o.implications=function(c){let d=[];if(Object.keys(i).forEach((p)=>{let h=p;(i[p]||[]).forEach((g)=>{let y=h,m=g;if(y=l(c,y),g=l(c,g),y&&!g)d.push(` ${h} -> ${m}`)})}),d.length){let p=`${s("Implications failed:")}
78
- `;d.forEach((h)=>{p+=h}),t.fail(p)}};let u={};o.conflicts=function(c,d){if(Z("<string|object> [array|string]",[c,d],arguments.length),typeof c==="object")Object.keys(c).forEach((p)=>{o.conflicts(p,c[p])});else{if(e.global(c),!u[c])u[c]=[];if(Array.isArray(d))d.forEach((p)=>o.conflicts(c,p));else u[c].push(d)}},o.getConflicting=()=>u,o.conflicting=function(c){if(Object.keys(c).forEach((d)=>{if(u[d])u[d].forEach((p)=>{if(p&&c[d]!==void 0&&c[p]!==void 0)t.fail(s("Arguments %s and %s are mutually exclusive",d,p))})}),e.getInternalMethods().getParserConfiguration()["strip-dashed"])Object.keys(u).forEach((d)=>{u[d].forEach((p)=>{if(p&&c[n.Parser.camelCase(d)]!==void 0&&c[n.Parser.camelCase(p)]!==void 0)t.fail(s("Arguments %s and %s are mutually exclusive",d,p))})})},o.recommendCommands=function(c,d){d=d.sort((y,m)=>m.length-y.length);let h=null,g=1/0;for(let y=0,m;(m=d[y])!==void 0;y++){let w=Pu(c,m);if(w<=3&&w<g)g=w,h=m}if(h)t.fail(s("Did you mean %s?",h))},o.reset=function(c){return i=Vt(i,(d)=>!c[d]),u=Vt(u,(d)=>!c[d]),o};let f=[];return o.freeze=function(){f.push({implied:i,conflicting:u})},o.unfreeze=function(){let c=f.pop();Ke(c,void 0,n),{implied:i,conflicting:u}=c},o}var Ti=[],Ss;function _s(e,t,n,s){Ss=s;let r={};if(Object.prototype.hasOwnProperty.call(e,"extends")){if(typeof e.extends!=="string")return r;let o=/\.json|\..*rc$/.test(e.extends),i=null;if(!o)try{i=import.meta.resolve(e.extends)}catch(l){return e}else i=sb(t,e.extends);nb(i),Ti.push(i),r=o?JSON.parse(Ss.readFileSync(i,"utf8")):s.require(e.extends),delete e.extends,r=_s(r,Ss.path.dirname(i),n,Ss)}return Ti=[],n?Mu(r,e):Object.assign({},r,e)}function nb(e){if(Ti.indexOf(e)>-1)throw new Ce(`Circular extended configurations: '${e}'.`)}function sb(e,t){return Ss.path.resolve(e,t)}function Mu(e,t){let n={};function s(r){return r&&typeof r==="object"&&!Array.isArray(r)}Object.assign(n,e);for(let r of Object.keys(t))if(s(t[r])&&s(n[r]))n[r]=Mu(e[r],t[r]);else n[r]=t[r];return n}var Q=function(e,t,n,s,r){if(s==="m")throw TypeError("Private method is not writable");if(s==="a"&&!r)throw TypeError("Private accessor was defined without a setter");if(typeof t==="function"?e!==t||!r:!t.has(e))throw TypeError("Cannot write private member to an object whose class did not declare it");return s==="a"?r.call(e,n):r?r.value=n:t.set(e,n),n},b=function(e,t,n,s){if(n==="a"&&!s)throw TypeError("Private accessor was defined without a getter");if(typeof t==="function"?e!==t||!s:!t.has(e))throw TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?s:n==="a"?s.call(e):s?s.value:t.get(e)},Ae,xn,Es,ze,et,Sr,Qt,Sn,_r,ct,Er,lt,Ct,tt,ut,$r,_n,ve,ne,Cr,Ar,nt,En,Gn,$n,en,Tr,ae,Cn,An,Tn,de,Fr,At,$e;function rd(e){return(t=[],n=e.process.cwd(),s)=>{let r=new od(t,n,s,e);return Object.defineProperty(r,"argv",{get:()=>r.parse(),enumerable:!0}),r.help(),r.version(),r}}var Bu=Symbol("copyDoubleDash"),ju=Symbol("copyDoubleDash"),Fi=Symbol("deleteFromParserHintObject"),Wu=Symbol("emitWarning"),Uu=Symbol("freeze"),Ju=Symbol("getDollarZero"),Fn=Symbol("getParserConfiguration"),Ku=Symbol("getUsageConfiguration"),Oi=Symbol("guessLocale"),qu=Symbol("guessVersion"),Hu=Symbol("parsePositionalNumbers"),Ri=Symbol("pkgUp"),tn=Symbol("populateParserHintArray"),Xn=Symbol("populateParserHintSingleValueDictionary"),Ii=Symbol("populateParserHintArrayDictionary"),vi=Symbol("populateParserHintDictionary"),Pi=Symbol("sanitizeKey"),Li=Symbol("setKey"),Ni=Symbol("unfreeze"),zu=Symbol("validateAsync"),Yu=Symbol("getCommandInstance"),Gu=Symbol("getContext"),Xu=Symbol("getHasOutput"),Vu=Symbol("getLoggerInstance"),Zu=Symbol("getParseContext"),Qu=Symbol("getUsageInstance"),ed=Symbol("getValidationInstance"),Or=Symbol("hasParseCallback"),td=Symbol("isGlobalContext"),On=Symbol("postProcess"),nd=Symbol("rebase"),Mi=Symbol("reset"),$s=Symbol("runYargsParserAndExecuteCommands"),Bi=Symbol("runValidation"),sd=Symbol("setHasOutput"),Rn=Symbol("kTrackManuallySetKeys"),rb="en_US";class od{constructor(e=[],t,n,s){this.customScriptName=!1,this.parsed=!1,Ae.set(this,void 0),xn.set(this,void 0),Es.set(this,{commands:[],fullCommands:[]}),ze.set(this,null),et.set(this,null),Sr.set(this,"show-hidden"),Qt.set(this,null),Sn.set(this,!0),_r.set(this,{}),ct.set(this,!0),Er.set(this,[]),lt.set(this,void 0),Ct.set(this,{}),tt.set(this,!1),ut.set(this,null),$r.set(this,!0),_n.set(this,void 0),ve.set(this,""),ne.set(this,void 0),Cr.set(this,void 0),Ar.set(this,{}),nt.set(this,null),En.set(this,null),Gn.set(this,{}),$n.set(this,{}),en.set(this,void 0),Tr.set(this,!1),ae.set(this,void 0),Cn.set(this,!1),An.set(this,!1),Tn.set(this,!1),de.set(this,void 0),Fr.set(this,{}),At.set(this,null),$e.set(this,void 0),Q(this,ae,s,"f"),Q(this,en,e,"f"),Q(this,xn,t,"f"),Q(this,Cr,n,"f"),Q(this,lt,new Ci(this),"f"),this.$0=this[Ju](),this[Mi](),Q(this,Ae,b(this,Ae,"f"),"f"),Q(this,de,b(this,de,"f"),"f"),Q(this,$e,b(this,$e,"f"),"f"),Q(this,ne,b(this,ne,"f"),"f"),b(this,ne,"f").showHiddenOpt=b(this,Sr,"f"),Q(this,_n,this[ju](),"f"),b(this,ae,"f").y18n.setLocale(rb)}addHelpOpt(e,t){if(Z("[string|boolean] [string]",[e,t],arguments.length),b(this,ut,"f"))this[Fi](b(this,ut,"f")),Q(this,ut,null,"f");if(e===!1&&t===void 0)return this;return Q(this,ut,typeof e==="string"?e:"help","f"),this.boolean(b(this,ut,"f")),this.describe(b(this,ut,"f"),t||b(this,de,"f").deferY18nLookup("Show help")),this}help(e,t){return this.addHelpOpt(e,t)}addShowHiddenOpt(e,t){if(Z("[string|boolean] [string]",[e,t],arguments.length),e===!1&&t===void 0)return this;let n=typeof e==="string"?e:b(this,Sr,"f");return this.boolean(n),this.describe(n,t||b(this,de,"f").deferY18nLookup("Show hidden options")),b(this,ne,"f").showHiddenOpt=n,this}showHidden(e,t){return this.addShowHiddenOpt(e,t)}alias(e,t){return Z("<object|string|array> [string|array]",[e,t],arguments.length),this[Ii](this.alias.bind(this),"alias",e,t),this}array(e){return Z("<array|string>",[e],arguments.length),this[tn]("array",e),this[Rn](e),this}boolean(e){return Z("<array|string>",[e],arguments.length),this[tn]("boolean",e),this[Rn](e),this}check(e,t){return Z("<function> [boolean]",[e,t],arguments.length),this.middleware((n,s)=>Dn(()=>e(n,s.getOptions()),(r)=>{if(!r)b(this,de,"f").fail(b(this,ae,"f").y18n.__("Argument check failed: %s",e.toString()));else if(typeof r==="string"||r instanceof Error)b(this,de,"f").fail(r.toString(),r);return n},(r)=>(b(this,de,"f").fail(r.message?r.message:r.toString(),r),n)),!1,t),this}choices(e,t){return Z("<object|string|array> [string|array]",[e,t],arguments.length),this[Ii](this.choices.bind(this),"choices",e,t),this}coerce(e,t){if(Z("<object|string|array> [function]",[e,t],arguments.length),Array.isArray(e)){if(!t)throw new Ce("coerce callback must be provided");for(let s of e)this.coerce(s,t);return this}else if(typeof e==="object"){for(let s of Object.keys(e))this.coerce(s,e[s]);return this}if(!t)throw new Ce("coerce callback must be provided");let n=e;return b(this,ne,"f").key[n]=!0,b(this,lt,"f").addCoerceMiddleware((s,r)=>{var o;let i=(o=r.getAliases()[n])!==null&&o!==void 0?o:[],l=[n,...i].filter((u)=>Object.prototype.hasOwnProperty.call(s,u));if(l.length===0)return s;return Dn(()=>t(s[l[0]]),(u)=>(l.forEach((f)=>{s[f]=u}),s),(u)=>{throw new Ce(u.message)})},n),this}conflicts(e,t){return Z("<string|object> [string|array]",[e,t],arguments.length),b(this,$e,"f").conflicts(e,t),this}config(e="config",t,n){if(Z("[object|string] [string|function] [function]",[e,t,n],arguments.length),typeof e==="object"&&!Array.isArray(e))return e=_s(e,b(this,xn,"f"),this[Fn]()["deep-merge-config"]||!1,b(this,ae,"f")),b(this,ne,"f").configObjects=(b(this,ne,"f").configObjects||[]).concat(e),this;if(typeof t==="function")n=t,t=void 0;return this.describe(e,t||b(this,de,"f").deferY18nLookup("Path to JSON config file")),(Array.isArray(e)?e:[e]).forEach((s)=>{b(this,ne,"f").config[s]=n||!0}),this}completion(e,t,n){if(Z("[string] [string|boolean|function] [function]",[e,t,n],arguments.length),typeof t==="function")n=t,t=void 0;if(Q(this,et,e||b(this,et,"f")||"completion","f"),!t&&t!==!1)t="generate completion script";if(this.command(b(this,et,"f"),t),n)b(this,ze,"f").registerFunction(n);return this}command(e,t,n,s,r,o){return Z("<string|array|object> [string|boolean] [function|object] [function] [array] [boolean|string]",[e,t,n,s,r,o],arguments.length),b(this,Ae,"f").addHandler(e,t,n,s,r,o),this}commands(e,t,n,s,r,o){return this.command(e,t,n,s,r,o)}commandDir(e,t){Z("<string> [object]",[e,t],arguments.length);let n=b(this,Cr,"f")||b(this,ae,"f").require;return b(this,Ae,"f").addDirectory(e,n,b(this,ae,"f").getCallerFile(),t),this}count(e){return Z("<array|string>",[e],arguments.length),this[tn]("count",e),this[Rn](e),this}default(e,t,n){if(Z("<object|string|array> [*] [string]",[e,t,n],arguments.length),n)$i(e,b(this,ae,"f")),b(this,ne,"f").defaultDescription[e]=n;if(typeof t==="function"){if($i(e,b(this,ae,"f")),!b(this,ne,"f").defaultDescription[e])b(this,ne,"f").defaultDescription[e]=b(this,de,"f").functionDescription(t);t=t.call()}return this[Xn](this.default.bind(this),"default",e,t),this}defaults(e,t,n){return this.default(e,t,n)}demandCommand(e=1,t,n,s){if(Z("[number] [number|string] [string|null|undefined] [string|null|undefined]",[e,t,n,s],arguments.length),typeof t!=="number")n=t,t=1/0;return this.global("_",!1),b(this,ne,"f").demandedCommands._={min:e,max:t,minMsg:n,maxMsg:s},this}demand(e,t,n){if(Array.isArray(t))t.forEach((s)=>{Ke(n,!0,b(this,ae,"f")),this.demandOption(s,n)}),t=1/0;else if(typeof t!=="number")n=t,t=1/0;if(typeof e==="number")Ke(n,!0,b(this,ae,"f")),this.demandCommand(e,t,n,n);else if(Array.isArray(e))e.forEach((s)=>{Ke(n,!0,b(this,ae,"f")),this.demandOption(s,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 Z("<object|string|array> [string]",[e,t],arguments.length),this[Xn](this.demandOption.bind(this),"demandedOptions",e,t),this}deprecateOption(e,t){return Z("<string> [string|boolean]",[e,t],arguments.length),b(this,ne,"f").deprecatedOptions[e]=t,this}describe(e,t){return Z("<object|string|array> [string]",[e,t],arguments.length),this[Li](e,!0),b(this,de,"f").describe(e,t),this}detectLocale(e){return Z("<boolean>",[e],arguments.length),Q(this,Sn,e,"f"),this}env(e){if(Z("[string|boolean]",[e],arguments.length),e===!1)delete b(this,ne,"f").envPrefix;else b(this,ne,"f").envPrefix=e||"";return this}epilogue(e){return Z("<string>",[e],arguments.length),b(this,de,"f").epilog(e),this}epilog(e){return this.epilogue(e)}example(e,t){if(Z("<string|array> [string]",[e,t],arguments.length),Array.isArray(e))e.forEach((n)=>this.example(...n));else b(this,de,"f").example(e,t);return this}exit(e,t){if(Q(this,tt,!0,"f"),Q(this,Qt,t,"f"),b(this,ct,"f"))b(this,ae,"f").process.exit(e)}exitProcess(e=!0){return Z("[boolean]",[e],arguments.length),Q(this,ct,e,"f"),this}fail(e){if(Z("<function|boolean>",[e],arguments.length),typeof e==="boolean"&&e!==!1)throw new Ce("Invalid first argument. Expected function or boolean 'false'");return b(this,de,"f").failFn(e),this}getAliases(){return this.parsed?this.parsed.aliases:{}}async getCompletion(e,t){if(Z("<array> [function]",[e,t],arguments.length),!t)return new Promise((n,s)=>{b(this,ze,"f").getCompletion(e,(r,o)=>{if(r)s(r);else n(o)})});else return b(this,ze,"f").getCompletion(e,t)}getDemandedOptions(){return Z([],0),b(this,ne,"f").demandedOptions}getDemandedCommands(){return Z([],0),b(this,ne,"f").demandedCommands}getDeprecatedOptions(){return Z([],0),b(this,ne,"f").deprecatedOptions}getDetectLocale(){return b(this,Sn,"f")}getExitProcess(){return b(this,ct,"f")}getGroups(){return Object.assign({},b(this,Ct,"f"),b(this,$n,"f"))}getHelp(){if(Q(this,tt,!0,"f"),!b(this,de,"f").hasCachedHelpMessage()){if(!this.parsed){let t=this[$s](b(this,en,"f"),void 0,void 0,0,!0);if(xe(t))return t.then(()=>b(this,de,"f").help())}let e=b(this,Ae,"f").runDefaultBuilderOn(this);if(xe(e))return e.then(()=>b(this,de,"f").help())}return Promise.resolve(b(this,de,"f").help())}getOptions(){return b(this,ne,"f")}getStrict(){return b(this,Cn,"f")}getStrictCommands(){return b(this,An,"f")}getStrictOptions(){return b(this,Tn,"f")}global(e,t){if(Z("<string|array> [boolean]",[e,t],arguments.length),e=[].concat(e),t!==!1)b(this,ne,"f").local=b(this,ne,"f").local.filter((n)=>e.indexOf(n)===-1);else e.forEach((n)=>{if(!b(this,ne,"f").local.includes(n))b(this,ne,"f").local.push(n)});return this}group(e,t){Z("<string|array> <string>",[e,t],arguments.length);let n=b(this,$n,"f")[t]||b(this,Ct,"f")[t];if(b(this,$n,"f")[t])delete b(this,$n,"f")[t];let s={};return b(this,Ct,"f")[t]=(n||[]).concat(e).filter((r)=>{if(s[r])return!1;return s[r]=!0}),this}hide(e){return Z("<string>",[e],arguments.length),b(this,ne,"f").hiddenOptions.push(e),this}implies(e,t){return Z("<string|object> [number|string|array]",[e,t],arguments.length),b(this,$e,"f").implies(e,t),this}locale(e){if(Z("[string]",[e],arguments.length),e===void 0)return this[Oi](),b(this,ae,"f").y18n.getLocale();return Q(this,Sn,!1,"f"),b(this,ae,"f").y18n.setLocale(e),this}middleware(e,t,n){return b(this,lt,"f").addMiddleware(e,!!t,n)}nargs(e,t){return Z("<string|object|array> [number]",[e,t],arguments.length),this[Xn](this.nargs.bind(this),"narg",e,t),this}normalize(e){return Z("<array|string>",[e],arguments.length),this[tn]("normalize",e),this}number(e){return Z("<array|string>",[e],arguments.length),this[tn]("number",e),this[Rn](e),this}option(e,t){if(Z("<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[Rn](e),b(this,At,"f")&&(e==="version"||(t===null||t===void 0?void 0:t.alias)==="version"))this[Wu](['"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(b(this,ne,"f").key[e]=!0,t.alias)this.alias(e,t.alias);let n=t.deprecate||t.deprecated;if(n)this.deprecateOption(e,n);let s=t.demand||t.required||t.require;if(s)this.demand(e,s);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)b(this,ne,"f").defaultDescription[e]=t.defaultDescription;if(t.skipValidation)this.skipValidation(e);let r=t.describe||t.description||t.desc,o=b(this,de,"f").getDescriptions();if(!Object.prototype.hasOwnProperty.call(o,e)||typeof r==="string")this.describe(e,r);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(Z("[string|array] [function|boolean|object] [function]",[e,t,n],arguments.length),this[Uu](),typeof e>"u")e=b(this,en,"f");if(typeof t==="object")Q(this,En,t,"f"),t=n;if(typeof t==="function")Q(this,nt,t,"f"),t=!1;if(!t)Q(this,en,e,"f");if(b(this,nt,"f"))Q(this,ct,!1,"f");let s=this[$s](e,!!t),r=this.parsed;if(b(this,ze,"f").setParsed(this.parsed),xe(s))return s.then((o)=>{if(b(this,nt,"f"))b(this,nt,"f").call(this,b(this,Qt,"f"),o,b(this,ve,"f"));return o}).catch((o)=>{if(b(this,nt,"f"))b(this,nt,"f")(o,this.parsed.argv,b(this,ve,"f"));throw o}).finally(()=>{this[Ni](),this.parsed=r});else{if(b(this,nt,"f"))b(this,nt,"f").call(this,b(this,Qt,"f"),s,b(this,ve,"f"));this[Ni](),this.parsed=r}return s}parseAsync(e,t,n){let s=this.parse(e,t,n);return!xe(s)?Promise.resolve(s):s}parseSync(e,t,n){let s=this.parse(e,t,n);if(xe(s))throw new Ce(".parseSync() must not be used with asynchronous builders, handlers, or middleware");return s}parserConfiguration(e){return Z("<object>",[e],arguments.length),Q(this,Ar,e,"f"),this}pkgConf(e,t){Z("<string> [string]",[e,t],arguments.length);let n=null,s=this[Ri](t||b(this,xn,"f"));if(s[e]&&typeof s[e]==="object")n=_s(s[e],t||b(this,xn,"f"),this[Fn]()["deep-merge-config"]||!1,b(this,ae,"f")),b(this,ne,"f").configObjects=(b(this,ne,"f").configObjects||[]).concat(n);return this}positional(e,t){Z("<string> <object>",[e,t],arguments.length);let n=["default","defaultDescription","implies","normalize","choices","conflicts","coerce","type","describe","desc","description","alias"];t=Vt(t,(o,i)=>{if(o==="type"&&!["string","number","boolean"].includes(i))return!1;return n.includes(o)});let s=b(this,Es,"f").fullCommands[b(this,Es,"f").fullCommands.length-1],r=s?b(this,Ae,"f").cmdToParseOptions(s):{array:[],alias:{},default:{},demand:{}};return zn(r).forEach((o)=>{let i=r[o];if(Array.isArray(i)){if(i.indexOf(e)!==-1)t[o]=!0}else if(i[e]&&!(o in t))t[o]=i[e]}),this.group(e,b(this,de,"f").getPositionalGroupName()),this.option(e,t)}recommendCommands(e=!0){return Z("[boolean]",[e],arguments.length),Q(this,Tr,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(Z("<array|string|object> [number]",[e],arguments.length),typeof e==="string"&&b(this,ne,"f").narg[e])return this;else this[Xn](this.requiresArg.bind(this),"narg",e,NaN);return this}showCompletionScript(e,t){return Z("[string] [string]",[e,t],arguments.length),e=e||this.$0,b(this,_n,"f").log(b(this,ze,"f").generateCompletionScript(e,t||b(this,et,"f")||"completion")),this}showHelp(e){if(Z("[string|function]",[e],arguments.length),Q(this,tt,!0,"f"),!b(this,de,"f").hasCachedHelpMessage()){if(!this.parsed){let n=this[$s](b(this,en,"f"),void 0,void 0,0,!0);if(xe(n))return n.then(()=>{b(this,de,"f").showHelp(e)}),this}let t=b(this,Ae,"f").runDefaultBuilderOn(this);if(xe(t))return t.then(()=>{b(this,de,"f").showHelp(e)}),this}return b(this,de,"f").showHelp(e),this}scriptName(e){return this.customScriptName=!0,this.$0=e,this}showHelpOnFail(e,t){return Z("[boolean|string] [string]",[e,t],arguments.length),b(this,de,"f").showHelpOnFail(e,t),this}showVersion(e){return Z("[string|function]",[e],arguments.length),b(this,de,"f").showVersion(e),this}skipValidation(e){return Z("<array|string>",[e],arguments.length),this[tn]("skipValidation",e),this}strict(e){return Z("[boolean]",[e],arguments.length),Q(this,Cn,e!==!1,"f"),this}strictCommands(e){return Z("[boolean]",[e],arguments.length),Q(this,An,e!==!1,"f"),this}strictOptions(e){return Z("[boolean]",[e],arguments.length),Q(this,Tn,e!==!1,"f"),this}string(e){return Z("<array|string>",[e],arguments.length),this[tn]("string",e),this[Rn](e),this}terminalWidth(){return Z([],0),b(this,ae,"f").process.stdColumns}updateLocale(e){return this.updateStrings(e)}updateStrings(e){return Z("<object>",[e],arguments.length),Q(this,Sn,!1,"f"),b(this,ae,"f").y18n.updateLocale(e),this}usage(e,t,n,s){if(Z("<string|null|undefined> [string|boolean] [function|object] [function]",[e,t,n,s],arguments.length),t!==void 0)if(Ke(e,null,b(this,ae,"f")),(e||"").match(/^\$0( |$)/))return this.command(e,t,n,s);else throw new Ce(".usage() description must start with $0 if being used as alias for .command()");else return b(this,de,"f").usage(e),this}usageConfiguration(e){return Z("<object>",[e],arguments.length),Q(this,Fr,e,"f"),this}version(e,t,n){if(Z("[boolean|string] [string] [string]",[e,t,n],arguments.length),b(this,At,"f"))this[Fi](b(this,At,"f")),b(this,de,"f").version(void 0),Q(this,At,null,"f");if(arguments.length===0)n=this[qu](),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 Q(this,At,typeof e==="string"?e:"version","f"),t=t||b(this,de,"f").deferY18nLookup("Show version number"),b(this,de,"f").version(n||void 0),this.boolean(b(this,At,"f")),this.describe(b(this,At,"f"),t),this}wrap(e){return Z("<number|null|undefined>",[e],arguments.length),b(this,de,"f").wrap(e),this}[(Ae=new WeakMap,xn=new WeakMap,Es=new WeakMap,ze=new WeakMap,et=new WeakMap,Sr=new WeakMap,Qt=new WeakMap,Sn=new WeakMap,_r=new WeakMap,ct=new WeakMap,Er=new WeakMap,lt=new WeakMap,Ct=new WeakMap,tt=new WeakMap,ut=new WeakMap,$r=new WeakMap,_n=new WeakMap,ve=new WeakMap,ne=new WeakMap,Cr=new WeakMap,Ar=new WeakMap,nt=new WeakMap,En=new WeakMap,Gn=new WeakMap,$n=new WeakMap,en=new WeakMap,Tr=new WeakMap,ae=new WeakMap,Cn=new WeakMap,An=new WeakMap,Tn=new WeakMap,de=new WeakMap,Fr=new WeakMap,At=new WeakMap,$e=new WeakMap,Bu)](e){if(!e._||!e["--"])return e;e._.push.apply(e._,e["--"]);try{delete e["--"]}catch(t){}return e}[ju](){return{log:(...e)=>{if(!this[Or]())console.log(...e);if(Q(this,tt,!0,"f"),b(this,ve,"f").length)Q(this,ve,b(this,ve,"f")+`
80
- `,"f");Q(this,ve,b(this,ve,"f")+e.join(" "),"f")},error:(...e)=>{if(!this[Or]())console.error(...e);if(Q(this,tt,!0,"f"),b(this,ve,"f").length)Q(this,ve,b(this,ve,"f")+`
81
- `,"f");Q(this,ve,b(this,ve,"f")+e.join(" "),"f")}}}[Fi](e){zn(b(this,ne,"f")).forEach((t)=>{if(((s)=>s==="configObjects")(t))return;let n=b(this,ne,"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 b(this,de,"f").getDescriptions()[e]}[Wu](e,t,n){if(!b(this,_r,"f")[n])b(this,ae,"f").process.emitWarning(e,t),b(this,_r,"f")[n]=!0}[Uu](){b(this,Er,"f").push({options:b(this,ne,"f"),configObjects:b(this,ne,"f").configObjects.slice(0),exitProcess:b(this,ct,"f"),groups:b(this,Ct,"f"),strict:b(this,Cn,"f"),strictCommands:b(this,An,"f"),strictOptions:b(this,Tn,"f"),completionCommand:b(this,et,"f"),output:b(this,ve,"f"),exitError:b(this,Qt,"f"),hasOutput:b(this,tt,"f"),parsed:this.parsed,parseFn:b(this,nt,"f"),parseContext:b(this,En,"f")}),b(this,de,"f").freeze(),b(this,$e,"f").freeze(),b(this,Ae,"f").freeze(),b(this,lt,"f").freeze()}[Ju](){let e="",t;if(/\b(node|iojs|electron)(\.exe)?$/.test(b(this,ae,"f").process.argv()[0]))t=b(this,ae,"f").process.argv().slice(1,2);else t=b(this,ae,"f").process.argv().slice(0,1);if(e=t.map((n)=>{let s=this[nd](b(this,xn,"f"),n);return n.match(/^(\/|([a-zA-Z]:)?\\)/)&&s.length<n.length?s:n}).join(" ").trim(),b(this,ae,"f").getEnv("_")&&b(this,ae,"f").getProcessArgvBin()===b(this,ae,"f").getEnv("_"))e=b(this,ae,"f").getEnv("_").replace(`${b(this,ae,"f").path.dirname(b(this,ae,"f").process.execPath())}/`,"");return e}[Fn](){return b(this,Ar,"f")}[Ku](){return b(this,Fr,"f")}[Oi](){if(!b(this,Sn,"f"))return;let e=b(this,ae,"f").getEnv("LC_ALL")||b(this,ae,"f").getEnv("LC_MESSAGES")||b(this,ae,"f").getEnv("LANG")||b(this,ae,"f").getEnv("LANGUAGE")||"en_US";this.locale(e.replace(/[.:].*/,""))}[qu](){return this[Ri]().version||"unknown"}[Hu](e){let t=e["--"]?e["--"]:e._;for(let n=0,s;(s=t[n])!==void 0;n++)if(b(this,ae,"f").Parser.looksLikeNumber(s)&&Number.isSafeInteger(Math.floor(parseFloat(`${s}`))))t[n]=Number(s);return e}[Ri](e){let t=e||"*";if(b(this,Gn,"f")[t])return b(this,Gn,"f")[t];let n={};try{let s=e||b(this,ae,"f").mainFilename;if(b(this,ae,"f").path.extname(s))s=b(this,ae,"f").path.dirname(s);let r=b(this,ae,"f").findUp(s,(o,i)=>{if(i.includes("package.json"))return"package.json";else return});Ke(r,void 0,b(this,ae,"f")),n=JSON.parse(b(this,ae,"f").readFileSync(r,"utf8"))}catch(s){}return b(this,Gn,"f")[t]=n||{},b(this,Gn,"f")[t]}[tn](e,t){t=[].concat(t),t.forEach((n)=>{n=this[Pi](n),b(this,ne,"f")[e].push(n)})}[Xn](e,t,n,s){this[vi](e,t,n,s,(r,o,i)=>{b(this,ne,"f")[r][o]=i})}[Ii](e,t,n,s){this[vi](e,t,n,s,(r,o,i)=>{b(this,ne,"f")[r][o]=(b(this,ne,"f")[r][o]||[]).concat(i)})}[vi](e,t,n,s,r){if(Array.isArray(n))n.forEach((o)=>{e(o,s)});else if(((o)=>typeof o==="object")(n))for(let o of zn(n))e(o,n[o]);else r(t,this[Pi](n),s)}[Pi](e){if(e==="__proto__")return"___proto___";return e}[Li](e,t){return this[Xn](this[Li].bind(this),"key",e,t),this}[Ni](){var e,t,n,s,r,o,i,l,u,f,a,c;let d=b(this,Er,"f").pop();Ke(d,void 0,b(this,ae,"f"));let p;e=this,t=this,n=this,s=this,r=this,o=this,i=this,l=this,u=this,f=this,a=this,c=this,{options:{set value(h){Q(e,ne,h,"f")}}.value,configObjects:p,exitProcess:{set value(h){Q(t,ct,h,"f")}}.value,groups:{set value(h){Q(n,Ct,h,"f")}}.value,output:{set value(h){Q(s,ve,h,"f")}}.value,exitError:{set value(h){Q(r,Qt,h,"f")}}.value,hasOutput:{set value(h){Q(o,tt,h,"f")}}.value,parsed:this.parsed,strict:{set value(h){Q(i,Cn,h,"f")}}.value,strictCommands:{set value(h){Q(l,An,h,"f")}}.value,strictOptions:{set value(h){Q(u,Tn,h,"f")}}.value,completionCommand:{set value(h){Q(f,et,h,"f")}}.value,parseFn:{set value(h){Q(a,nt,h,"f")}}.value,parseContext:{set value(h){Q(c,En,h,"f")}}.value}=d,b(this,ne,"f").configObjects=p,b(this,de,"f").unfreeze(),b(this,$e,"f").unfreeze(),b(this,Ae,"f").unfreeze(),b(this,lt,"f").unfreeze()}[zu](e,t){return Dn(t,(n)=>(e(n),n))}getInternalMethods(){return{getCommandInstance:this[Yu].bind(this),getContext:this[Gu].bind(this),getHasOutput:this[Xu].bind(this),getLoggerInstance:this[Vu].bind(this),getParseContext:this[Zu].bind(this),getParserConfiguration:this[Fn].bind(this),getUsageConfiguration:this[Ku].bind(this),getUsageInstance:this[Qu].bind(this),getValidationInstance:this[ed].bind(this),hasParseCallback:this[Or].bind(this),isGlobalContext:this[td].bind(this),postProcess:this[On].bind(this),reset:this[Mi].bind(this),runValidation:this[Bi].bind(this),runYargsParserAndExecuteCommands:this[$s].bind(this),setHasOutput:this[sd].bind(this)}}[Yu](){return b(this,Ae,"f")}[Gu](){return b(this,Es,"f")}[Xu](){return b(this,tt,"f")}[Vu](){return b(this,_n,"f")}[Zu](){return b(this,En,"f")||{}}[Qu](){return b(this,de,"f")}[ed](){return b(this,$e,"f")}[Or](){return!!b(this,nt,"f")}[td](){return b(this,$r,"f")}[On](e,t,n,s){if(n)return e;if(xe(e))return e;if(!t)e=this[Bu](e);if(this[Fn]()["parse-positional-numbers"]||this[Fn]()["parse-positional-numbers"]===void 0)e=this[Hu](e);if(s)e=kn(e,this,b(this,lt,"f").getMiddleware(),!1);return e}[Mi](e={}){Q(this,ne,b(this,ne,"f")||{},"f");let t={};t.local=b(this,ne,"f").local||[],t.configObjects=b(this,ne,"f").configObjects||[];let n={};t.local.forEach((o)=>{n[o]=!0,(e[o]||[]).forEach((i)=>{n[i]=!0})}),Object.assign(b(this,$n,"f"),Object.keys(b(this,Ct,"f")).reduce((o,i)=>{let l=b(this,Ct,"f")[i].filter((u)=>!(u in n));if(l.length>0)o[i]=l;return o},{})),Q(this,Ct,{},"f");let s=["array","boolean","string","skipValidation","count","normalize","number","hiddenOptions"],r=["narg","key","alias","default","defaultDescription","config","choices","demandedOptions","demandedCommands","deprecatedOptions"];if(s.forEach((o)=>{t[o]=(b(this,ne,"f")[o]||[]).filter((i)=>!n[i])}),r.forEach((o)=>{t[o]=Vt(b(this,ne,"f")[o],(i)=>!n[i])}),t.envPrefix=b(this,ne,"f").envPrefix,Q(this,ne,t,"f"),Q(this,de,b(this,de,"f")?b(this,de,"f").reset(n):Fu(this,b(this,ae,"f")),"f"),Q(this,$e,b(this,$e,"f")?b(this,$e,"f").reset(n):Nu(this,b(this,de,"f"),b(this,ae,"f")),"f"),Q(this,Ae,b(this,Ae,"f")?b(this,Ae,"f").reset():Cu(b(this,de,"f"),b(this,$e,"f"),b(this,lt,"f"),b(this,ae,"f")),"f"),!b(this,ze,"f"))Q(this,ze,vu(this,b(this,de,"f"),b(this,Ae,"f"),b(this,ae,"f")),"f");return b(this,lt,"f").reset(),Q(this,et,null,"f"),Q(this,ve,"","f"),Q(this,Qt,null,"f"),Q(this,tt,!1,"f"),this.parsed=!1,this}[nd](e,t){return b(this,ae,"f").path.relative(e,t)}[$s](e,t,n,s=0,r=!1){var o,i,l,u;let f=!!n||r;e=e||b(this,en,"f"),b(this,ne,"f").__=b(this,ae,"f").y18n.__,b(this,ne,"f").configuration=this[Fn]();let a=!!b(this,ne,"f").configuration["populate--"],c=Object.assign({},b(this,ne,"f").configuration,{"populate--":!0}),d=b(this,ae,"f").Parser.detailed(e,Object.assign({},b(this,ne,"f"),{configuration:{"parse-positional-numbers":!1,...c}})),p=Object.assign(d.argv,b(this,En,"f")),h=void 0,g=d.aliases,y=!1,m=!1;if(Object.keys(p).forEach((w)=>{if(w===b(this,ut,"f")&&p[w])y=!0;else if(w===b(this,At,"f")&&p[w])m=!0}),p.$0=this.$0,this.parsed=d,s===0)b(this,de,"f").clearCachedHelpMessage();try{if(this[Oi](),t)return this[On](p,a,!!n,!1);if(b(this,ut,"f")){if([b(this,ut,"f")].concat(g[b(this,ut,"f")]||[]).filter((E)=>E.length>1).includes(""+p._[p._.length-1]))p._.pop(),y=!0}Q(this,$r,!1,"f");let w=b(this,Ae,"f").getCommands(),k=((o=b(this,ze,"f"))===null||o===void 0?void 0:o.completionKey)?[(i=b(this,ze,"f"))===null||i===void 0?void 0:i.completionKey,...(u=this.getAliases()[(l=b(this,ze,"f"))===null||l===void 0?void 0:l.completionKey])!==null&&u!==void 0?u:[]].some((D)=>Object.prototype.hasOwnProperty.call(p,D)):!1,_=y||k||r;if(p._.length){if(w.length){let D;for(let E=s||0,S;p._[E]!==void 0;E++)if(S=String(p._[E]),w.includes(S)&&S!==b(this,et,"f")){let x=b(this,Ae,"f").runCommand(S,this,d,E+1,r,y||m||r);return this[On](x,a,!!n,!1)}else if(!D&&S!==b(this,et,"f")){D=S;break}if(!b(this,Ae,"f").hasDefaultCommand()&&b(this,Tr,"f")&&D&&!_)b(this,$e,"f").recommendCommands(D,w)}if(b(this,et,"f")&&p._.includes(b(this,et,"f"))&&!k){if(b(this,ct,"f"))Zt(!0);this.showCompletionScript(),this.exit(0)}}if(b(this,Ae,"f").hasDefaultCommand()&&!_){let D=b(this,Ae,"f").runCommand(null,this,d,0,r,y||m||r);return this[On](D,a,!!n,!1)}if(k){if(b(this,ct,"f"))Zt(!0);e=[].concat(e);let D=e.slice(e.indexOf(`--${b(this,ze,"f").completionKey}`)+1);return b(this,ze,"f").getCompletion(D,(E,S)=>{if(E)throw new Ce(E.message);(S||[]).forEach((x)=>{b(this,_n,"f").log(x)}),this.exit(0)}),this[On](p,!a,!!n,!1)}if(!b(this,tt,"f")){if(y){if(b(this,ct,"f"))Zt(!0);f=!0,this.showHelp((D)=>{b(this,_n,"f").log(D),this.exit(0)})}else if(m){if(b(this,ct,"f"))Zt(!0);f=!0,b(this,de,"f").showVersion("log"),this.exit(0)}}if(!f&&b(this,ne,"f").skipValidation.length>0)f=Object.keys(p).some((D)=>b(this,ne,"f").skipValidation.indexOf(D)>=0&&p[D]===!0);if(!f){if(d.error)throw new Ce(d.error.message);if(!k){let D=this[Bi](g,{},d.error);if(!n)h=kn(p,this,b(this,lt,"f").getMiddleware(),!0);if(h=this[zu](D,h!==null&&h!==void 0?h:p),xe(h)&&!n)h=h.then(()=>kn(p,this,b(this,lt,"f").getMiddleware(),!1))}}}catch(w){if(w instanceof Ce)b(this,de,"f").fail(w.message,w);else throw w}return this[On](h!==null&&h!==void 0?h:p,a,!!n,!0)}[Bi](e,t,n,s){let r={...this.getDemandedOptions()};return(o)=>{if(n)throw new Ce(n.message);b(this,$e,"f").nonOptionCount(o),b(this,$e,"f").requiredArguments(o,r);let i=!1;if(b(this,An,"f"))i=b(this,$e,"f").unknownCommands(o);if(b(this,Cn,"f")&&!i)b(this,$e,"f").unknownArguments(o,e,t,!!s);else if(b(this,Tn,"f"))b(this,$e,"f").unknownArguments(o,e,{},!1,!1);b(this,$e,"f").limitedChoices(o),b(this,$e,"f").implications(o),b(this,$e,"f").conflicting(o)}}[sd](){Q(this,tt,!0,"f")}[Rn](e){if(typeof e==="string")b(this,ne,"f").key[e]=!0;else for(let t of e)b(this,ne,"f").key[t]=!0}}function Au(e){return!!e&&typeof e.getInternalMethods==="function"}var ob=rd(Ei),id=ob;var cd=/<https?:\/\/[^\s<>|]+(?:\|[^<>\r\n]*)?>|https?:\/\/[^\t\n\v\f\r <\x00]+/gi,ld=/[\t\n\v\f\r (*_~]/,ib=/[.,:;!?]$/;function ud(e){if(ib.test(e))return e.slice(-1);if(e.endsWith(")")&&ad(e,"(")<ad(e,")"))return")";return}function dd(e){let t=e.split(""),n=(r,o)=>{for(let i=r;i<o;i++)if(t[i]!==`
74
+ `;class Xu{constructor(e,t,n,s){var r,o,i;this.yargs=e,this.usage=t,this.command=n,this.shim=s,this.completionKey="get-yargs-completions",this.aliases=null,this.customCompletionFunction=null,this.indexAfterLastReset=0,this.zshShell=(i=((r=this.shim.getEnv("SHELL"))===null||r===void 0?void 0:r.includes("zsh"))||((o=this.shim.getEnv("ZSH_NAME"))===null||o===void 0?void 0:o.includes("zsh")))!==null&&i!==void 0?i:!1}defaultCompletion(e,t,n,s){let r=this.command.getCommandHandlers();for(let i=0,a=e.length;i<a;++i)if(r[e[i]]&&r[e[i]].builder){let c=r[e[i]].builder;if(Ar(c)){this.indexAfterLastReset=i+1;let d=this.yargs.getInternalMethods().reset();return c(d,!0),d.argv}}let o=[];this.commandCompletions(o,e,n),this.optionCompletions(o,e,t,n),this.choicesFromOptionsCompletions(o,e,t,n),this.choicesFromPositionalsCompletions(o,e,t,n),s(null,o)}commandCompletions(e,t,n){let s=this.yargs.getInternalMethods().getContext().commands;if(!n.match(/^-/)&&s[s.length-1]!==n&&!this.previousArgHasChoices(t))this.usage.getCommands().forEach((r)=>{let o=Zt(r[0]).cmd;if(t.indexOf(o)===-1)if(!this.zshShell)e.push(o);else{let i=r[1]||"";e.push(o.replace(/:/g,"\\:")+":"+i)}})}optionCompletions(e,t,n,s){if((s.match(/^-/)||s===""&&e.length===0)&&!this.previousArgHasChoices(t)){let r=this.yargs.getOptions(),o=this.yargs.getGroups()[this.usage.getPositionalGroupName()]||[];Object.keys(r.key).forEach((i)=>{let a=!!r.configuration["boolean-negation"]&&r.boolean.includes(i);if(!o.includes(i)&&!r.hiddenOptions.includes(i)&&!this.argsContainKey(t,i,a))this.completeOptionKey(i,e,s,a&&!!r.default[i])})}}choicesFromOptionsCompletions(e,t,n,s){if(this.previousArgHasChoices(t)){let r=this.getPreviousArgChoices(t);if(r&&r.length>0)e.push(...r.map((o)=>o.replace(/:/g,"\\:")))}}choicesFromPositionalsCompletions(e,t,n,s){if(s===""&&e.length>0&&this.previousArgHasChoices(t))return;let r=this.yargs.getGroups()[this.usage.getPositionalGroupName()]||[],o=Math.max(this.indexAfterLastReset,this.yargs.getInternalMethods().getContext().commands.length+1),i=r[n._.length-o-1];if(!i)return;let a=this.yargs.getOptions().choices[i]||[];for(let c of a)if(c.startsWith(s))e.push(c.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 s=t.replace(/^-+/,""),r=this.yargs.getOptions(),o=[s,...this.yargs.getAliases()[s]||[]],i;for(let a of o)if(Object.prototype.hasOwnProperty.call(r.key,a)&&Array.isArray(r.choices[a])){i=r.choices[a];break}if(i)return i.filter((a)=>!n||a.startsWith(n))}previousArgHasChoices(e){let t=this.getPreviousArgChoices(e);return t!==void 0&&t.length>0}argsContainKey(e,t,n){let s=(r)=>e.indexOf((/^[^0-9]$/.test(r)?"-":"--")+r)!==-1;if(s(t))return!0;if(n&&s(`no-${t}`))return!0;if(this.aliases){for(let r of this.aliases[t])if(s(r))return!0}return!1}completeOptionKey(e,t,n,s){var r,o,i,a;let c=e;if(this.zshShell){let g=this.usage.getDescriptions(),y=(o=(r=this===null||this===void 0?void 0:this.aliases)===null||r===void 0?void 0:r[e])===null||o===void 0?void 0:o.find((u)=>{let l=g[u];return typeof l==="string"&&l.length>0}),k=y?g[y]:void 0,w=(a=(i=g[e])!==null&&i!==void 0?i:k)!==null&&a!==void 0?a:"";c=`${e.replace(/:/g,"\\:")}:${w.replace("__yargsString__:","").replace(/(\r\n|\n|\r)/gm," ")}`}let d=(g)=>/^--/.test(g),f=(g)=>/^[^0-9]$/.test(g),p=!d(n)&&f(e)?"-":"--";if(t.push(p+c),s)t.push(p+"no-"+c)}customCompletion(e,t,n,s){if(qe(this.customCompletionFunction,null,this.shim),Ab(this.customCompletionFunction)){let r=this.customCompletionFunction(n,t);if(xe(r))return r.then((o)=>{this.shim.process.nextTick(()=>{s(null,o)})}).catch((o)=>{this.shim.process.nextTick(()=>{s(o,void 0)})});return s(null,r)}else if(Tb(this.customCompletionFunction))return this.customCompletionFunction(n,t,(r=s)=>this.defaultCompletion(e,t,n,r),(r)=>{s(null,r)});else return this.customCompletionFunction(n,t,(r)=>{s(null,r)})}getCompletion(e,t){let n=e.length?e[e.length-1]:"",s=this.yargs.parse(e,!0),r=this.customCompletionFunction?(o)=>this.customCompletion(e,o,n,t):(o)=>this.defaultCompletion(e,o,n,t);return xe(s)?s.then(r):r(s)}generateCompletionScript(e,t){let n=this.zshShell?Gu:Yu,s=this.shim.path.basename(e);if(e.match(/\.js$/))e=`./${e}`;return n=n.replace(/{{app_name}}/g,s),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 Vu(e,t,n,s){return new Xu(e,t,n,s)}function Ab(e){return e.length<3}function Tb(e){return e.length>3}function Zu(e,t){if(e.length===0)return t.length;if(t.length===0)return e.length;let n=[],s;for(s=0;s<=t.length;s++)n[s]=[s];let r;for(r=0;r<=e.length;r++)n[0][r]=r;for(s=1;s<=t.length;s++)for(r=1;r<=e.length;r++)if(t.charAt(s-1)===e.charAt(r-1))n[s][r]=n[s-1][r-1];else if(s>1&&r>1&&t.charAt(s-2)===e.charAt(r-1)&&t.charAt(s-1)===e.charAt(r-2))n[s][r]=n[s-2][r-2]+1;else n[s][r]=Math.min(n[s-1][r-1]+1,Math.min(n[s][r-1]+1,n[s-1][r]+1));return n[t.length][e.length]}var Qu=["$0","--","_"];function ed(e,t,n){let s=n.y18n.__,r=n.y18n.__n,o={};o.nonOptionCount=function(p){let g=e.getDemandedCommands(),k=p._.length+(p["--"]?p["--"].length:0)-e.getInternalMethods().getContext().commands.length;if(g._&&(k<g._.min||k>g._.max)){if(k<g._.min)if(g._.minMsg!==void 0)t.fail(g._.minMsg?g._.minMsg.replace(/\$0/g,k.toString()).replace(/\$1/,g._.min.toString()):null);else t.fail(r("Not enough non-option arguments: got %s, need at least %s","Not enough non-option arguments: got %s, need at least %s",k,k.toString(),g._.min.toString()));else if(k>g._.max)if(g._.maxMsg!==void 0)t.fail(g._.maxMsg?g._.maxMsg.replace(/\$0/g,k.toString()).replace(/\$1/,g._.max.toString()):null);else t.fail(r("Too many non-option arguments: got %s, maximum of %s","Too many non-option arguments: got %s, maximum of %s",k,k.toString(),g._.max.toString()))}},o.positionalCount=function(p,g){if(g<p)t.fail(r("Not enough non-option arguments: got %s, need at least %s","Not enough non-option arguments: got %s, need at least %s",g,g+"",p+""))},o.requiredArguments=function(p,g){let y=null;for(let k of Object.keys(g))if(!Object.prototype.hasOwnProperty.call(p,k)||typeof p[k]>"u")y=y||{},y[k]=g[k];if(y){let k=[];for(let u of Object.keys(y)){let l=y[u];if(l&&k.indexOf(l)<0)k.push(l)}let w=k.length?`
75
+ ${k.join(`
76
+ `)}`:"";t.fail(r("Missing required argument: %s","Missing required arguments: %s",Object.keys(y).length,Object.keys(y).join(", ")+w))}},o.unknownArguments=function(p,g,y,k,w=!0){var u;let l=e.getInternalMethods().getCommandInstance().getCommands(),h=[],m=e.getInternalMethods().getContext();if(Object.keys(p).forEach((b)=>{if(!Qu.includes(b)&&!Object.prototype.hasOwnProperty.call(y,b)&&!Object.prototype.hasOwnProperty.call(e.getInternalMethods().getParseContext(),b)&&!o.isValidAndSomeAliasIsNotNew(b,g))h.push(b)}),w&&(m.commands.length>0||l.length>0||k))p._.slice(m.commands.length).forEach((b)=>{if(!l.includes(""+b))h.push(""+b)});if(w){let _=((u=e.getDemandedCommands()._)===null||u===void 0?void 0:u.max)||0,x=m.commands.length+_;if(x<p._.length)p._.slice(x).forEach((S)=>{if(S=String(S),!m.commands.includes(S)&&!h.includes(S))h.push(S)})}if(h.length)t.fail(r("Unknown argument: %s","Unknown arguments: %s",h.length,h.map((b)=>b.trim()?b:`"${b}"`).join(", ")))},o.unknownCommands=function(p){let g=e.getInternalMethods().getCommandInstance().getCommands(),y=[],k=e.getInternalMethods().getContext();if(k.commands.length>0||g.length>0)p._.slice(k.commands.length).forEach((w)=>{if(!g.includes(""+w))y.push(""+w)});if(y.length>0)return t.fail(r("Unknown command: %s","Unknown commands: %s",y.length,y.join(", "))),!0;else return!1},o.isValidAndSomeAliasIsNotNew=function(p,g){if(!Object.prototype.hasOwnProperty.call(g,p))return!1;let y=e.parsed.newAliases;return[p,...g[p]].some((k)=>!Object.prototype.hasOwnProperty.call(y,k)||!y[p])},o.limitedChoices=function(p){let g=e.getOptions(),y={};if(!Object.keys(g.choices).length)return;Object.keys(p).forEach((u)=>{if(Qu.indexOf(u)===-1&&Object.prototype.hasOwnProperty.call(g.choices,u))[].concat(p[u]).forEach((l)=>{if(g.choices[u].indexOf(l)===-1&&l!==void 0)y[u]=(y[u]||[]).concat(l)})});let k=Object.keys(y);if(!k.length)return;let w=s("Invalid values:");k.forEach((u)=>{w+=`
77
+ ${s("Argument: %s, Given: %s, Choices: %s",u,t.stringifiedValues(y[u]),t.stringifiedValues(g.choices[u]))}`}),t.fail(w)};let i={};o.implies=function(p,g){if(Z("<string|object> [array|number|string]",[p,g],arguments.length),typeof p==="object")Object.keys(p).forEach((y)=>{o.implies(y,p[y])});else{if(e.global(p),!i[p])i[p]=[];if(Array.isArray(g))g.forEach((y)=>o.implies(p,y));else qe(g,void 0,n),i[p].push(g)}},o.getImplied=function(){return i};function a(f,p){let g=Number(p);if(p=isNaN(g)?p:g,typeof p==="number")p=f._.length>=p;else if(p.match(/^--no-.+/))p=p.match(/^--no-(.+)/)[1],p=!Object.prototype.hasOwnProperty.call(f,p);else p=Object.prototype.hasOwnProperty.call(f,p);return p}o.implications=function(p){let g=[];if(Object.keys(i).forEach((y)=>{let k=y;(i[y]||[]).forEach((w)=>{let u=k,l=w;if(u=a(p,u),w=a(p,w),u&&!w)g.push(` ${k} -> ${l}`)})}),g.length){let y=`${s("Implications failed:")}
78
+ `;g.forEach((k)=>{y+=k}),t.fail(y)}};let c={};o.conflicts=function(p,g){if(Z("<string|object> [array|string]",[p,g],arguments.length),typeof p==="object")Object.keys(p).forEach((y)=>{o.conflicts(y,p[y])});else{if(e.global(p),!c[p])c[p]=[];if(Array.isArray(g))g.forEach((y)=>o.conflicts(p,y));else c[p].push(g)}},o.getConflicting=()=>c,o.conflicting=function(p){if(Object.keys(p).forEach((g)=>{if(c[g])c[g].forEach((y)=>{if(y&&p[g]!==void 0&&p[y]!==void 0)t.fail(s("Arguments %s and %s are mutually exclusive",g,y))})}),e.getInternalMethods().getParserConfiguration()["strip-dashed"])Object.keys(c).forEach((g)=>{c[g].forEach((y)=>{if(y&&p[n.Parser.camelCase(g)]!==void 0&&p[n.Parser.camelCase(y)]!==void 0)t.fail(s("Arguments %s and %s are mutually exclusive",g,y))})})},o.recommendCommands=function(p,g){g=g.sort((u,l)=>l.length-u.length);let k=null,w=1/0;for(let u=0,l;(l=g[u])!==void 0;u++){let h=Zu(p,l);if(h<=3&&h<w)w=h,k=l}if(k)t.fail(s("Did you mean %s?",k))},o.reset=function(p){return i=Qt(i,(g)=>!p[g]),c=Qt(c,(g)=>!p[g]),o};let d=[];return o.freeze=function(){d.push({implied:i,conflicting:c})},o.unfreeze=function(){let p=d.pop();qe(p,void 0,n),{implied:i,conflicting:c}=p},o}var ji=[],As;function Ts(e,t,n,s){As=s;let r={};if(Object.prototype.hasOwnProperty.call(e,"extends")){if(typeof e.extends!=="string")return r;let o=/\.json|\..*rc$/.test(e.extends),i=null;if(!o)try{i=import.meta.resolve(e.extends)}catch(a){return e}else i=Ob(t,e.extends);Fb(i),ji.push(i),r=o?JSON.parse(As.readFileSync(i,"utf8")):s.require(e.extends),delete e.extends,r=Ts(r,As.path.dirname(i),n,As)}return ji=[],n?td(r,e):Object.assign({},r,e)}function Fb(e){if(ji.indexOf(e)>-1)throw new Te(`Circular extended configurations: '${e}'.`)}function Ob(e,t){return As.path.resolve(e,t)}function td(e,t){let n={};function s(r){return r&&typeof r==="object"&&!Array.isArray(r)}Object.assign(n,e);for(let r of Object.keys(t))if(s(t[r])&&s(n[r]))n[r]=td(e[r],t[r]);else n[r]=t[r];return n}var Q=function(e,t,n,s,r){if(s==="m")throw TypeError("Private method is not writable");if(s==="a"&&!r)throw TypeError("Private accessor was defined without a setter");if(typeof t==="function"?e!==t||!r:!t.has(e))throw TypeError("Cannot write private member to an object whose class did not declare it");return s==="a"?r.call(e,n):r?r.value=n:t.set(e,n),n},D=function(e,t,n,s){if(n==="a"&&!s)throw TypeError("Private accessor was defined without a getter");if(typeof t==="function"?e!==t||!s:!t.has(e))throw TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?s:n==="a"?s.call(e):s?s.value:t.get(e)},Fe,_n,Fs,Ye,tt,Fr,tn,En,Or,lt,Ir,ut,Tt,nt,dt,Rr,$n,Le,re,vr,Pr,st,Cn,es,An,nn,Lr,le,Tn,Fn,On,de,Nr,Ft,Ce;function Dd(e){return(t=[],n=e.process.cwd(),s)=>{let r=new xd(t,n,s,e);return Object.defineProperty(r,"argv",{get:()=>r.parse(),enumerable:!0}),r.help(),r.version(),r}}var nd=Symbol("copyDoubleDash"),sd=Symbol("copyDoubleDash"),Wi=Symbol("deleteFromParserHintObject"),rd=Symbol("emitWarning"),od=Symbol("freeze"),id=Symbol("getDollarZero"),In=Symbol("getParserConfiguration"),ad=Symbol("getUsageConfiguration"),Ui=Symbol("guessLocale"),cd=Symbol("guessVersion"),ld=Symbol("parsePositionalNumbers"),Ji=Symbol("pkgUp"),sn=Symbol("populateParserHintArray"),ts=Symbol("populateParserHintSingleValueDictionary"),Ki=Symbol("populateParserHintArrayDictionary"),qi=Symbol("populateParserHintDictionary"),Hi=Symbol("sanitizeKey"),zi=Symbol("setKey"),Yi=Symbol("unfreeze"),ud=Symbol("validateAsync"),dd=Symbol("getCommandInstance"),fd=Symbol("getContext"),pd=Symbol("getHasOutput"),hd=Symbol("getLoggerInstance"),gd=Symbol("getParseContext"),md=Symbol("getUsageInstance"),yd=Symbol("getValidationInstance"),Mr=Symbol("hasParseCallback"),bd=Symbol("isGlobalContext"),Rn=Symbol("postProcess"),wd=Symbol("rebase"),Gi=Symbol("reset"),Os=Symbol("runYargsParserAndExecuteCommands"),Xi=Symbol("runValidation"),kd=Symbol("setHasOutput"),vn=Symbol("kTrackManuallySetKeys"),Ib="en_US";class xd{constructor(e=[],t,n,s){this.customScriptName=!1,this.parsed=!1,Fe.set(this,void 0),_n.set(this,void 0),Fs.set(this,{commands:[],fullCommands:[]}),Ye.set(this,null),tt.set(this,null),Fr.set(this,"show-hidden"),tn.set(this,null),En.set(this,!0),Or.set(this,{}),lt.set(this,!0),Ir.set(this,[]),ut.set(this,void 0),Tt.set(this,{}),nt.set(this,!1),dt.set(this,null),Rr.set(this,!0),$n.set(this,void 0),Le.set(this,""),re.set(this,void 0),vr.set(this,void 0),Pr.set(this,{}),st.set(this,null),Cn.set(this,null),es.set(this,{}),An.set(this,{}),nn.set(this,void 0),Lr.set(this,!1),le.set(this,void 0),Tn.set(this,!1),Fn.set(this,!1),On.set(this,!1),de.set(this,void 0),Nr.set(this,{}),Ft.set(this,null),Ce.set(this,void 0),Q(this,le,s,"f"),Q(this,nn,e,"f"),Q(this,_n,t,"f"),Q(this,vr,n,"f"),Q(this,ut,new Mi(this),"f"),this.$0=this[id](),this[Gi](),Q(this,Fe,D(this,Fe,"f"),"f"),Q(this,de,D(this,de,"f"),"f"),Q(this,Ce,D(this,Ce,"f"),"f"),Q(this,re,D(this,re,"f"),"f"),D(this,re,"f").showHiddenOpt=D(this,Fr,"f"),Q(this,$n,this[sd](),"f"),D(this,le,"f").y18n.setLocale(Ib)}addHelpOpt(e,t){if(Z("[string|boolean] [string]",[e,t],arguments.length),D(this,dt,"f"))this[Wi](D(this,dt,"f")),Q(this,dt,null,"f");if(e===!1&&t===void 0)return this;return Q(this,dt,typeof e==="string"?e:"help","f"),this.boolean(D(this,dt,"f")),this.describe(D(this,dt,"f"),t||D(this,de,"f").deferY18nLookup("Show help")),this}help(e,t){return this.addHelpOpt(e,t)}addShowHiddenOpt(e,t){if(Z("[string|boolean] [string]",[e,t],arguments.length),e===!1&&t===void 0)return this;let n=typeof e==="string"?e:D(this,Fr,"f");return this.boolean(n),this.describe(n,t||D(this,de,"f").deferY18nLookup("Show hidden options")),D(this,re,"f").showHiddenOpt=n,this}showHidden(e,t){return this.addShowHiddenOpt(e,t)}alias(e,t){return Z("<object|string|array> [string|array]",[e,t],arguments.length),this[Ki](this.alias.bind(this),"alias",e,t),this}array(e){return Z("<array|string>",[e],arguments.length),this[sn]("array",e),this[vn](e),this}boolean(e){return Z("<array|string>",[e],arguments.length),this[sn]("boolean",e),this[vn](e),this}check(e,t){return Z("<function> [boolean]",[e,t],arguments.length),this.middleware((n,s)=>Sn(()=>e(n,s.getOptions()),(r)=>{if(!r)D(this,de,"f").fail(D(this,le,"f").y18n.__("Argument check failed: %s",e.toString()));else if(typeof r==="string"||r instanceof Error)D(this,de,"f").fail(r.toString(),r);return n},(r)=>(D(this,de,"f").fail(r.message?r.message:r.toString(),r),n)),!1,t),this}choices(e,t){return Z("<object|string|array> [string|array]",[e,t],arguments.length),this[Ki](this.choices.bind(this),"choices",e,t),this}coerce(e,t){if(Z("<object|string|array> [function]",[e,t],arguments.length),Array.isArray(e)){if(!t)throw new Te("coerce callback must be provided");for(let s of e)this.coerce(s,t);return this}else if(typeof e==="object"){for(let s of Object.keys(e))this.coerce(s,e[s]);return this}if(!t)throw new Te("coerce callback must be provided");let n=e;return D(this,re,"f").key[n]=!0,D(this,ut,"f").addCoerceMiddleware((s,r)=>{var o;let i=(o=r.getAliases()[n])!==null&&o!==void 0?o:[],a=[n,...i].filter((c)=>Object.prototype.hasOwnProperty.call(s,c));if(a.length===0)return s;return Sn(()=>t(s[a[0]]),(c)=>(a.forEach((d)=>{s[d]=c}),s),(c)=>{throw new Te(c.message)})},n),this}conflicts(e,t){return Z("<string|object> [string|array]",[e,t],arguments.length),D(this,Ce,"f").conflicts(e,t),this}config(e="config",t,n){if(Z("[object|string] [string|function] [function]",[e,t,n],arguments.length),typeof e==="object"&&!Array.isArray(e))return e=Ts(e,D(this,_n,"f"),this[In]()["deep-merge-config"]||!1,D(this,le,"f")),D(this,re,"f").configObjects=(D(this,re,"f").configObjects||[]).concat(e),this;if(typeof t==="function")n=t,t=void 0;return this.describe(e,t||D(this,de,"f").deferY18nLookup("Path to JSON config file")),(Array.isArray(e)?e:[e]).forEach((s)=>{D(this,re,"f").config[s]=n||!0}),this}completion(e,t,n){if(Z("[string] [string|boolean|function] [function]",[e,t,n],arguments.length),typeof t==="function")n=t,t=void 0;if(Q(this,tt,e||D(this,tt,"f")||"completion","f"),!t&&t!==!1)t="generate completion script";if(this.command(D(this,tt,"f"),t),n)D(this,Ye,"f").registerFunction(n);return this}command(e,t,n,s,r,o){return Z("<string|array|object> [string|boolean] [function|object] [function] [array] [boolean|string]",[e,t,n,s,r,o],arguments.length),D(this,Fe,"f").addHandler(e,t,n,s,r,o),this}commands(e,t,n,s,r,o){return this.command(e,t,n,s,r,o)}commandDir(e,t){Z("<string> [object]",[e,t],arguments.length);let n=D(this,vr,"f")||D(this,le,"f").require;return D(this,Fe,"f").addDirectory(e,n,D(this,le,"f").getCallerFile(),t),this}count(e){return Z("<array|string>",[e],arguments.length),this[sn]("count",e),this[vn](e),this}default(e,t,n){if(Z("<object|string|array> [*] [string]",[e,t,n],arguments.length),n)Ni(e,D(this,le,"f")),D(this,re,"f").defaultDescription[e]=n;if(typeof t==="function"){if(Ni(e,D(this,le,"f")),!D(this,re,"f").defaultDescription[e])D(this,re,"f").defaultDescription[e]=D(this,de,"f").functionDescription(t);t=t.call()}return this[ts](this.default.bind(this),"default",e,t),this}defaults(e,t,n){return this.default(e,t,n)}demandCommand(e=1,t,n,s){if(Z("[number] [number|string] [string|null|undefined] [string|null|undefined]",[e,t,n,s],arguments.length),typeof t!=="number")n=t,t=1/0;return this.global("_",!1),D(this,re,"f").demandedCommands._={min:e,max:t,minMsg:n,maxMsg:s},this}demand(e,t,n){if(Array.isArray(t))t.forEach((s)=>{qe(n,!0,D(this,le,"f")),this.demandOption(s,n)}),t=1/0;else if(typeof t!=="number")n=t,t=1/0;if(typeof e==="number")qe(n,!0,D(this,le,"f")),this.demandCommand(e,t,n,n);else if(Array.isArray(e))e.forEach((s)=>{qe(n,!0,D(this,le,"f")),this.demandOption(s,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 Z("<object|string|array> [string]",[e,t],arguments.length),this[ts](this.demandOption.bind(this),"demandedOptions",e,t),this}deprecateOption(e,t){return Z("<string> [string|boolean]",[e,t],arguments.length),D(this,re,"f").deprecatedOptions[e]=t,this}describe(e,t){return Z("<object|string|array> [string]",[e,t],arguments.length),this[zi](e,!0),D(this,de,"f").describe(e,t),this}detectLocale(e){return Z("<boolean>",[e],arguments.length),Q(this,En,e,"f"),this}env(e){if(Z("[string|boolean]",[e],arguments.length),e===!1)delete D(this,re,"f").envPrefix;else D(this,re,"f").envPrefix=e||"";return this}epilogue(e){return Z("<string>",[e],arguments.length),D(this,de,"f").epilog(e),this}epilog(e){return this.epilogue(e)}example(e,t){if(Z("<string|array> [string]",[e,t],arguments.length),Array.isArray(e))e.forEach((n)=>this.example(...n));else D(this,de,"f").example(e,t);return this}exit(e,t){if(Q(this,nt,!0,"f"),Q(this,tn,t,"f"),D(this,lt,"f"))D(this,le,"f").process.exit(e)}exitProcess(e=!0){return Z("[boolean]",[e],arguments.length),Q(this,lt,e,"f"),this}fail(e){if(Z("<function|boolean>",[e],arguments.length),typeof e==="boolean"&&e!==!1)throw new Te("Invalid first argument. Expected function or boolean 'false'");return D(this,de,"f").failFn(e),this}getAliases(){return this.parsed?this.parsed.aliases:{}}async getCompletion(e,t){if(Z("<array> [function]",[e,t],arguments.length),!t)return new Promise((n,s)=>{D(this,Ye,"f").getCompletion(e,(r,o)=>{if(r)s(r);else n(o)})});else return D(this,Ye,"f").getCompletion(e,t)}getDemandedOptions(){return Z([],0),D(this,re,"f").demandedOptions}getDemandedCommands(){return Z([],0),D(this,re,"f").demandedCommands}getDeprecatedOptions(){return Z([],0),D(this,re,"f").deprecatedOptions}getDetectLocale(){return D(this,En,"f")}getExitProcess(){return D(this,lt,"f")}getGroups(){return Object.assign({},D(this,Tt,"f"),D(this,An,"f"))}getHelp(){if(Q(this,nt,!0,"f"),!D(this,de,"f").hasCachedHelpMessage()){if(!this.parsed){let t=this[Os](D(this,nn,"f"),void 0,void 0,0,!0);if(xe(t))return t.then(()=>D(this,de,"f").help())}let e=D(this,Fe,"f").runDefaultBuilderOn(this);if(xe(e))return e.then(()=>D(this,de,"f").help())}return Promise.resolve(D(this,de,"f").help())}getOptions(){return D(this,re,"f")}getStrict(){return D(this,Tn,"f")}getStrictCommands(){return D(this,Fn,"f")}getStrictOptions(){return D(this,On,"f")}global(e,t){if(Z("<string|array> [boolean]",[e,t],arguments.length),e=[].concat(e),t!==!1)D(this,re,"f").local=D(this,re,"f").local.filter((n)=>e.indexOf(n)===-1);else e.forEach((n)=>{if(!D(this,re,"f").local.includes(n))D(this,re,"f").local.push(n)});return this}group(e,t){Z("<string|array> <string>",[e,t],arguments.length);let n=D(this,An,"f")[t]||D(this,Tt,"f")[t];if(D(this,An,"f")[t])delete D(this,An,"f")[t];let s={};return D(this,Tt,"f")[t]=(n||[]).concat(e).filter((r)=>{if(s[r])return!1;return s[r]=!0}),this}hide(e){return Z("<string>",[e],arguments.length),D(this,re,"f").hiddenOptions.push(e),this}implies(e,t){return Z("<string|object> [number|string|array]",[e,t],arguments.length),D(this,Ce,"f").implies(e,t),this}locale(e){if(Z("[string]",[e],arguments.length),e===void 0)return this[Ui](),D(this,le,"f").y18n.getLocale();return Q(this,En,!1,"f"),D(this,le,"f").y18n.setLocale(e),this}middleware(e,t,n){return D(this,ut,"f").addMiddleware(e,!!t,n)}nargs(e,t){return Z("<string|object|array> [number]",[e,t],arguments.length),this[ts](this.nargs.bind(this),"narg",e,t),this}normalize(e){return Z("<array|string>",[e],arguments.length),this[sn]("normalize",e),this}number(e){return Z("<array|string>",[e],arguments.length),this[sn]("number",e),this[vn](e),this}option(e,t){if(Z("<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[vn](e),D(this,Ft,"f")&&(e==="version"||(t===null||t===void 0?void 0:t.alias)==="version"))this[rd](['"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(D(this,re,"f").key[e]=!0,t.alias)this.alias(e,t.alias);let n=t.deprecate||t.deprecated;if(n)this.deprecateOption(e,n);let s=t.demand||t.required||t.require;if(s)this.demand(e,s);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)D(this,re,"f").defaultDescription[e]=t.defaultDescription;if(t.skipValidation)this.skipValidation(e);let r=t.describe||t.description||t.desc,o=D(this,de,"f").getDescriptions();if(!Object.prototype.hasOwnProperty.call(o,e)||typeof r==="string")this.describe(e,r);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(Z("[string|array] [function|boolean|object] [function]",[e,t,n],arguments.length),this[od](),typeof e>"u")e=D(this,nn,"f");if(typeof t==="object")Q(this,Cn,t,"f"),t=n;if(typeof t==="function")Q(this,st,t,"f"),t=!1;if(!t)Q(this,nn,e,"f");if(D(this,st,"f"))Q(this,lt,!1,"f");let s=this[Os](e,!!t),r=this.parsed;if(D(this,Ye,"f").setParsed(this.parsed),xe(s))return s.then((o)=>{if(D(this,st,"f"))D(this,st,"f").call(this,D(this,tn,"f"),o,D(this,Le,"f"));return o}).catch((o)=>{if(D(this,st,"f"))D(this,st,"f")(o,this.parsed.argv,D(this,Le,"f"));throw o}).finally(()=>{this[Yi](),this.parsed=r});else{if(D(this,st,"f"))D(this,st,"f").call(this,D(this,tn,"f"),s,D(this,Le,"f"));this[Yi](),this.parsed=r}return s}parseAsync(e,t,n){let s=this.parse(e,t,n);return!xe(s)?Promise.resolve(s):s}parseSync(e,t,n){let s=this.parse(e,t,n);if(xe(s))throw new Te(".parseSync() must not be used with asynchronous builders, handlers, or middleware");return s}parserConfiguration(e){return Z("<object>",[e],arguments.length),Q(this,Pr,e,"f"),this}pkgConf(e,t){Z("<string> [string]",[e,t],arguments.length);let n=null,s=this[Ji](t||D(this,_n,"f"));if(s[e]&&typeof s[e]==="object")n=Ts(s[e],t||D(this,_n,"f"),this[In]()["deep-merge-config"]||!1,D(this,le,"f")),D(this,re,"f").configObjects=(D(this,re,"f").configObjects||[]).concat(n);return this}positional(e,t){Z("<string> <object>",[e,t],arguments.length);let n=["default","defaultDescription","implies","normalize","choices","conflicts","coerce","type","describe","desc","description","alias"];t=Qt(t,(o,i)=>{if(o==="type"&&!["string","number","boolean"].includes(i))return!1;return n.includes(o)});let s=D(this,Fs,"f").fullCommands[D(this,Fs,"f").fullCommands.length-1],r=s?D(this,Fe,"f").cmdToParseOptions(s):{array:[],alias:{},default:{},demand:{}};return Zn(r).forEach((o)=>{let i=r[o];if(Array.isArray(i)){if(i.indexOf(e)!==-1)t[o]=!0}else if(i[e]&&!(o in t))t[o]=i[e]}),this.group(e,D(this,de,"f").getPositionalGroupName()),this.option(e,t)}recommendCommands(e=!0){return Z("[boolean]",[e],arguments.length),Q(this,Lr,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(Z("<array|string|object> [number]",[e],arguments.length),typeof e==="string"&&D(this,re,"f").narg[e])return this;else this[ts](this.requiresArg.bind(this),"narg",e,NaN);return this}showCompletionScript(e,t){return Z("[string] [string]",[e,t],arguments.length),e=e||this.$0,D(this,$n,"f").log(D(this,Ye,"f").generateCompletionScript(e,t||D(this,tt,"f")||"completion")),this}showHelp(e){if(Z("[string|function]",[e],arguments.length),Q(this,nt,!0,"f"),!D(this,de,"f").hasCachedHelpMessage()){if(!this.parsed){let n=this[Os](D(this,nn,"f"),void 0,void 0,0,!0);if(xe(n))return n.then(()=>{D(this,de,"f").showHelp(e)}),this}let t=D(this,Fe,"f").runDefaultBuilderOn(this);if(xe(t))return t.then(()=>{D(this,de,"f").showHelp(e)}),this}return D(this,de,"f").showHelp(e),this}scriptName(e){return this.customScriptName=!0,this.$0=e,this}showHelpOnFail(e,t){return Z("[boolean|string] [string]",[e,t],arguments.length),D(this,de,"f").showHelpOnFail(e,t),this}showVersion(e){return Z("[string|function]",[e],arguments.length),D(this,de,"f").showVersion(e),this}skipValidation(e){return Z("<array|string>",[e],arguments.length),this[sn]("skipValidation",e),this}strict(e){return Z("[boolean]",[e],arguments.length),Q(this,Tn,e!==!1,"f"),this}strictCommands(e){return Z("[boolean]",[e],arguments.length),Q(this,Fn,e!==!1,"f"),this}strictOptions(e){return Z("[boolean]",[e],arguments.length),Q(this,On,e!==!1,"f"),this}string(e){return Z("<array|string>",[e],arguments.length),this[sn]("string",e),this[vn](e),this}terminalWidth(){return Z([],0),D(this,le,"f").process.stdColumns}updateLocale(e){return this.updateStrings(e)}updateStrings(e){return Z("<object>",[e],arguments.length),Q(this,En,!1,"f"),D(this,le,"f").y18n.updateLocale(e),this}usage(e,t,n,s){if(Z("<string|null|undefined> [string|boolean] [function|object] [function]",[e,t,n,s],arguments.length),t!==void 0)if(qe(e,null,D(this,le,"f")),(e||"").match(/^\$0( |$)/))return this.command(e,t,n,s);else throw new Te(".usage() description must start with $0 if being used as alias for .command()");else return D(this,de,"f").usage(e),this}usageConfiguration(e){return Z("<object>",[e],arguments.length),Q(this,Nr,e,"f"),this}version(e,t,n){if(Z("[boolean|string] [string] [string]",[e,t,n],arguments.length),D(this,Ft,"f"))this[Wi](D(this,Ft,"f")),D(this,de,"f").version(void 0),Q(this,Ft,null,"f");if(arguments.length===0)n=this[cd](),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 Q(this,Ft,typeof e==="string"?e:"version","f"),t=t||D(this,de,"f").deferY18nLookup("Show version number"),D(this,de,"f").version(n||void 0),this.boolean(D(this,Ft,"f")),this.describe(D(this,Ft,"f"),t),this}wrap(e){return Z("<number|null|undefined>",[e],arguments.length),D(this,de,"f").wrap(e),this}[(Fe=new WeakMap,_n=new WeakMap,Fs=new WeakMap,Ye=new WeakMap,tt=new WeakMap,Fr=new WeakMap,tn=new WeakMap,En=new WeakMap,Or=new WeakMap,lt=new WeakMap,Ir=new WeakMap,ut=new WeakMap,Tt=new WeakMap,nt=new WeakMap,dt=new WeakMap,Rr=new WeakMap,$n=new WeakMap,Le=new WeakMap,re=new WeakMap,vr=new WeakMap,Pr=new WeakMap,st=new WeakMap,Cn=new WeakMap,es=new WeakMap,An=new WeakMap,nn=new WeakMap,Lr=new WeakMap,le=new WeakMap,Tn=new WeakMap,Fn=new WeakMap,On=new WeakMap,de=new WeakMap,Nr=new WeakMap,Ft=new WeakMap,Ce=new WeakMap,nd)](e){if(!e._||!e["--"])return e;e._.push.apply(e._,e["--"]);try{delete e["--"]}catch(t){}return e}[sd](){return{log:(...e)=>{if(!this[Mr]())console.log(...e);if(Q(this,nt,!0,"f"),D(this,Le,"f").length)Q(this,Le,D(this,Le,"f")+`
80
+ `,"f");Q(this,Le,D(this,Le,"f")+e.join(" "),"f")},error:(...e)=>{if(!this[Mr]())console.error(...e);if(Q(this,nt,!0,"f"),D(this,Le,"f").length)Q(this,Le,D(this,Le,"f")+`
81
+ `,"f");Q(this,Le,D(this,Le,"f")+e.join(" "),"f")}}}[Wi](e){Zn(D(this,re,"f")).forEach((t)=>{if(((s)=>s==="configObjects")(t))return;let n=D(this,re,"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 D(this,de,"f").getDescriptions()[e]}[rd](e,t,n){if(!D(this,Or,"f")[n])D(this,le,"f").process.emitWarning(e,t),D(this,Or,"f")[n]=!0}[od](){D(this,Ir,"f").push({options:D(this,re,"f"),configObjects:D(this,re,"f").configObjects.slice(0),exitProcess:D(this,lt,"f"),groups:D(this,Tt,"f"),strict:D(this,Tn,"f"),strictCommands:D(this,Fn,"f"),strictOptions:D(this,On,"f"),completionCommand:D(this,tt,"f"),output:D(this,Le,"f"),exitError:D(this,tn,"f"),hasOutput:D(this,nt,"f"),parsed:this.parsed,parseFn:D(this,st,"f"),parseContext:D(this,Cn,"f")}),D(this,de,"f").freeze(),D(this,Ce,"f").freeze(),D(this,Fe,"f").freeze(),D(this,ut,"f").freeze()}[id](){let e="",t;if(/\b(node|iojs|electron)(\.exe)?$/.test(D(this,le,"f").process.argv()[0]))t=D(this,le,"f").process.argv().slice(1,2);else t=D(this,le,"f").process.argv().slice(0,1);if(e=t.map((n)=>{let s=this[wd](D(this,_n,"f"),n);return n.match(/^(\/|([a-zA-Z]:)?\\)/)&&s.length<n.length?s:n}).join(" ").trim(),D(this,le,"f").getEnv("_")&&D(this,le,"f").getProcessArgvBin()===D(this,le,"f").getEnv("_"))e=D(this,le,"f").getEnv("_").replace(`${D(this,le,"f").path.dirname(D(this,le,"f").process.execPath())}/`,"");return e}[In](){return D(this,Pr,"f")}[ad](){return D(this,Nr,"f")}[Ui](){if(!D(this,En,"f"))return;let e=D(this,le,"f").getEnv("LC_ALL")||D(this,le,"f").getEnv("LC_MESSAGES")||D(this,le,"f").getEnv("LANG")||D(this,le,"f").getEnv("LANGUAGE")||"en_US";this.locale(e.replace(/[.:].*/,""))}[cd](){return this[Ji]().version||"unknown"}[ld](e){let t=e["--"]?e["--"]:e._;for(let n=0,s;(s=t[n])!==void 0;n++)if(D(this,le,"f").Parser.looksLikeNumber(s)&&Number.isSafeInteger(Math.floor(parseFloat(`${s}`))))t[n]=Number(s);return e}[Ji](e){let t=e||"*";if(D(this,es,"f")[t])return D(this,es,"f")[t];let n={};try{let s=e||D(this,le,"f").mainFilename;if(D(this,le,"f").path.extname(s))s=D(this,le,"f").path.dirname(s);let r=D(this,le,"f").findUp(s,(o,i)=>{if(i.includes("package.json"))return"package.json";else return});qe(r,void 0,D(this,le,"f")),n=JSON.parse(D(this,le,"f").readFileSync(r,"utf8"))}catch(s){}return D(this,es,"f")[t]=n||{},D(this,es,"f")[t]}[sn](e,t){t=[].concat(t),t.forEach((n)=>{n=this[Hi](n),D(this,re,"f")[e].push(n)})}[ts](e,t,n,s){this[qi](e,t,n,s,(r,o,i)=>{D(this,re,"f")[r][o]=i})}[Ki](e,t,n,s){this[qi](e,t,n,s,(r,o,i)=>{D(this,re,"f")[r][o]=(D(this,re,"f")[r][o]||[]).concat(i)})}[qi](e,t,n,s,r){if(Array.isArray(n))n.forEach((o)=>{e(o,s)});else if(((o)=>typeof o==="object")(n))for(let o of Zn(n))e(o,n[o]);else r(t,this[Hi](n),s)}[Hi](e){if(e==="__proto__")return"___proto___";return e}[zi](e,t){return this[ts](this[zi].bind(this),"key",e,t),this}[Yi](){var e,t,n,s,r,o,i,a,c,d,f,p;let g=D(this,Ir,"f").pop();qe(g,void 0,D(this,le,"f"));let y;e=this,t=this,n=this,s=this,r=this,o=this,i=this,a=this,c=this,d=this,f=this,p=this,{options:{set value(k){Q(e,re,k,"f")}}.value,configObjects:y,exitProcess:{set value(k){Q(t,lt,k,"f")}}.value,groups:{set value(k){Q(n,Tt,k,"f")}}.value,output:{set value(k){Q(s,Le,k,"f")}}.value,exitError:{set value(k){Q(r,tn,k,"f")}}.value,hasOutput:{set value(k){Q(o,nt,k,"f")}}.value,parsed:this.parsed,strict:{set value(k){Q(i,Tn,k,"f")}}.value,strictCommands:{set value(k){Q(a,Fn,k,"f")}}.value,strictOptions:{set value(k){Q(c,On,k,"f")}}.value,completionCommand:{set value(k){Q(d,tt,k,"f")}}.value,parseFn:{set value(k){Q(f,st,k,"f")}}.value,parseContext:{set value(k){Q(p,Cn,k,"f")}}.value}=g,D(this,re,"f").configObjects=y,D(this,de,"f").unfreeze(),D(this,Ce,"f").unfreeze(),D(this,Fe,"f").unfreeze(),D(this,ut,"f").unfreeze()}[ud](e,t){return Sn(t,(n)=>(e(n),n))}getInternalMethods(){return{getCommandInstance:this[dd].bind(this),getContext:this[fd].bind(this),getHasOutput:this[pd].bind(this),getLoggerInstance:this[hd].bind(this),getParseContext:this[gd].bind(this),getParserConfiguration:this[In].bind(this),getUsageConfiguration:this[ad].bind(this),getUsageInstance:this[md].bind(this),getValidationInstance:this[yd].bind(this),hasParseCallback:this[Mr].bind(this),isGlobalContext:this[bd].bind(this),postProcess:this[Rn].bind(this),reset:this[Gi].bind(this),runValidation:this[Xi].bind(this),runYargsParserAndExecuteCommands:this[Os].bind(this),setHasOutput:this[kd].bind(this)}}[dd](){return D(this,Fe,"f")}[fd](){return D(this,Fs,"f")}[pd](){return D(this,nt,"f")}[hd](){return D(this,$n,"f")}[gd](){return D(this,Cn,"f")||{}}[md](){return D(this,de,"f")}[yd](){return D(this,Ce,"f")}[Mr](){return!!D(this,st,"f")}[bd](){return D(this,Rr,"f")}[Rn](e,t,n,s){if(n)return e;if(xe(e))return e;if(!t)e=this[nd](e);if(this[In]()["parse-positional-numbers"]||this[In]()["parse-positional-numbers"]===void 0)e=this[ld](e);if(s)e=xn(e,this,D(this,ut,"f").getMiddleware(),!1);return e}[Gi](e={}){Q(this,re,D(this,re,"f")||{},"f");let t={};t.local=D(this,re,"f").local||[],t.configObjects=D(this,re,"f").configObjects||[];let n={};t.local.forEach((o)=>{n[o]=!0,(e[o]||[]).forEach((i)=>{n[i]=!0})}),Object.assign(D(this,An,"f"),Object.keys(D(this,Tt,"f")).reduce((o,i)=>{let a=D(this,Tt,"f")[i].filter((c)=>!(c in n));if(a.length>0)o[i]=a;return o},{})),Q(this,Tt,{},"f");let s=["array","boolean","string","skipValidation","count","normalize","number","hiddenOptions"],r=["narg","key","alias","default","defaultDescription","config","choices","demandedOptions","demandedCommands","deprecatedOptions"];if(s.forEach((o)=>{t[o]=(D(this,re,"f")[o]||[]).filter((i)=>!n[i])}),r.forEach((o)=>{t[o]=Qt(D(this,re,"f")[o],(i)=>!n[i])}),t.envPrefix=D(this,re,"f").envPrefix,Q(this,re,t,"f"),Q(this,de,D(this,de,"f")?D(this,de,"f").reset(n):zu(this,D(this,le,"f")),"f"),Q(this,Ce,D(this,Ce,"f")?D(this,Ce,"f").reset(n):ed(this,D(this,de,"f"),D(this,le,"f")),"f"),Q(this,Fe,D(this,Fe,"f")?D(this,Fe,"f").reset():Ku(D(this,de,"f"),D(this,Ce,"f"),D(this,ut,"f"),D(this,le,"f")),"f"),!D(this,Ye,"f"))Q(this,Ye,Vu(this,D(this,de,"f"),D(this,Fe,"f"),D(this,le,"f")),"f");return D(this,ut,"f").reset(),Q(this,tt,null,"f"),Q(this,Le,"","f"),Q(this,tn,null,"f"),Q(this,nt,!1,"f"),this.parsed=!1,this}[wd](e,t){return D(this,le,"f").path.relative(e,t)}[Os](e,t,n,s=0,r=!1){var o,i,a,c;let d=!!n||r;e=e||D(this,nn,"f"),D(this,re,"f").__=D(this,le,"f").y18n.__,D(this,re,"f").configuration=this[In]();let f=!!D(this,re,"f").configuration["populate--"],p=Object.assign({},D(this,re,"f").configuration,{"populate--":!0}),g=D(this,le,"f").Parser.detailed(e,Object.assign({},D(this,re,"f"),{configuration:{"parse-positional-numbers":!1,...p}})),y=Object.assign(g.argv,D(this,Cn,"f")),k=void 0,w=g.aliases,u=!1,l=!1;if(Object.keys(y).forEach((h)=>{if(h===D(this,dt,"f")&&y[h])u=!0;else if(h===D(this,Ft,"f")&&y[h])l=!0}),y.$0=this.$0,this.parsed=g,s===0)D(this,de,"f").clearCachedHelpMessage();try{if(this[Ui](),t)return this[Rn](y,f,!!n,!1);if(D(this,dt,"f")){if([D(this,dt,"f")].concat(w[D(this,dt,"f")]||[]).filter((x)=>x.length>1).includes(""+y._[y._.length-1]))y._.pop(),u=!0}Q(this,Rr,!1,"f");let h=D(this,Fe,"f").getCommands(),m=((o=D(this,Ye,"f"))===null||o===void 0?void 0:o.completionKey)?[(i=D(this,Ye,"f"))===null||i===void 0?void 0:i.completionKey,...(c=this.getAliases()[(a=D(this,Ye,"f"))===null||a===void 0?void 0:a.completionKey])!==null&&c!==void 0?c:[]].some((_)=>Object.prototype.hasOwnProperty.call(y,_)):!1,b=u||m||r;if(y._.length){if(h.length){let _;for(let x=s||0,S;y._[x]!==void 0;x++)if(S=String(y._[x]),h.includes(S)&&S!==D(this,tt,"f")){let E=D(this,Fe,"f").runCommand(S,this,g,x+1,r,u||l||r);return this[Rn](E,f,!!n,!1)}else if(!_&&S!==D(this,tt,"f")){_=S;break}if(!D(this,Fe,"f").hasDefaultCommand()&&D(this,Lr,"f")&&_&&!b)D(this,Ce,"f").recommendCommands(_,h)}if(D(this,tt,"f")&&y._.includes(D(this,tt,"f"))&&!m){if(D(this,lt,"f"))en(!0);this.showCompletionScript(),this.exit(0)}}if(D(this,Fe,"f").hasDefaultCommand()&&!b){let _=D(this,Fe,"f").runCommand(null,this,g,0,r,u||l||r);return this[Rn](_,f,!!n,!1)}if(m){if(D(this,lt,"f"))en(!0);e=[].concat(e);let _=e.slice(e.indexOf(`--${D(this,Ye,"f").completionKey}`)+1);return D(this,Ye,"f").getCompletion(_,(x,S)=>{if(x)throw new Te(x.message);(S||[]).forEach((E)=>{D(this,$n,"f").log(E)}),this.exit(0)}),this[Rn](y,!f,!!n,!1)}if(!D(this,nt,"f")){if(u){if(D(this,lt,"f"))en(!0);d=!0,this.showHelp((_)=>{D(this,$n,"f").log(_),this.exit(0)})}else if(l){if(D(this,lt,"f"))en(!0);d=!0,D(this,de,"f").showVersion("log"),this.exit(0)}}if(!d&&D(this,re,"f").skipValidation.length>0)d=Object.keys(y).some((_)=>D(this,re,"f").skipValidation.indexOf(_)>=0&&y[_]===!0);if(!d){if(g.error)throw new Te(g.error.message);if(!m){let _=this[Xi](w,{},g.error);if(!n)k=xn(y,this,D(this,ut,"f").getMiddleware(),!0);if(k=this[ud](_,k!==null&&k!==void 0?k:y),xe(k)&&!n)k=k.then(()=>xn(y,this,D(this,ut,"f").getMiddleware(),!1))}}}catch(h){if(h instanceof Te)D(this,de,"f").fail(h.message,h);else throw h}return this[Rn](k!==null&&k!==void 0?k:y,f,!!n,!0)}[Xi](e,t,n,s){let r={...this.getDemandedOptions()};return(o)=>{if(n)throw new Te(n.message);D(this,Ce,"f").nonOptionCount(o),D(this,Ce,"f").requiredArguments(o,r);let i=!1;if(D(this,Fn,"f"))i=D(this,Ce,"f").unknownCommands(o);if(D(this,Tn,"f")&&!i)D(this,Ce,"f").unknownArguments(o,e,t,!!s);else if(D(this,On,"f"))D(this,Ce,"f").unknownArguments(o,e,{},!1,!1);D(this,Ce,"f").limitedChoices(o),D(this,Ce,"f").implications(o),D(this,Ce,"f").conflicting(o)}}[kd](){Q(this,nt,!0,"f")}[vn](e){if(typeof e==="string")D(this,re,"f").key[e]=!0;else for(let t of e)D(this,re,"f").key[t]=!0}}function qu(e){return!!e&&typeof e.getInternalMethods==="function"}var Rb=Dd(Li),Sd=Rb;var Ed=/<https?:\/\/[^\s<>|]+(?:\|[^<>\r\n]*)?>|https?:\/\/[^\t\n\v\f\r <\x00]+/gi,$d=/[\t\n\v\f\r (*_~]/,vb=/[.,:;!?]$/;function Cd(e){if(vb.test(e))return e.slice(-1);if(e.endsWith(")")&&_d(e,"(")<_d(e,")"))return")";return}function Ad(e){let t=e.split(""),n=(r,o)=>{for(let i=r;i<o;i++)if(t[i]!==`
82
82
  `)t[i]="\x00"},s=0;while(s<e.length){let o=s===0||e[s-1]===`
83
- `?/^ {0,3}(?:(`{3,})[^`\n]*|(~{3,})[^\n]*)(?=\n|$)/.exec(e.slice(s)):null;if(o){let l=o[1]??o[2],u=new RegExp(`
84
- {0,3}${l[0]==="`"?"`":"~"}{${l.length},}[ ]*\r?(?=
85
- |$)`,"g");u.lastIndex=s+o[0].length;let f=u.exec(e),a=f?f.index+f[0].length:e.length;n(s,a),s=a;continue}let i=e[s];if(i==="\\"){s+=2;continue}if(i==="`"){let l=0;while(e[s+l]==="`")l++;let u=s+l,f=-1;while(u<e.length){if(e[u]===`
86
- `&&/^\n[ \t\r]*(?:\n|$)/.test(e.slice(u)))break;if(e[u]!=="`"){u++;continue}let a=0;while(e[u+a]==="`")a++;if(a===l){f=u+a;break}u+=a}if(f<0){s+=l;continue}n(s,f),s=f;continue}if(i==="["){let l=/^\[(?:\\.|[^\]\\\n])*\]\([^()\s]*\)/.exec(e.slice(s));if(l){n(s,s+l[0].length),s+=l[0].length;continue}}s++}return t.join("")}function ab(e,{markdown:t=!0}={}){let n=t?dd(e):e,s=[];for(let r of n.matchAll(cd)){let o=r[0];if(o.startsWith("<"))continue;let i=r.index??0,l=i>0?n[i-1]:"";if(l&&!ld.test(l))s.push({url:o,side:"before",char:e[i-1]});let u=o.match(/[^\x00-\x7f]|>/);if(u)s.push({url:o,side:"after",char:u[0]});else{let f=ud(o);if(f&&!(f===")"&&l==="("))s.push({url:o,side:"trailing",char:f})}}return s}function qe(e,t=!1,n=console.error,{sides:s=["before","after","trailing"],markdown:r=!0}={}){let o=ab(e,{markdown:r}),i=o.filter((c)=>c.side==="trailing"&&s.includes("trailing"));if(i.length)n(`⚠ URL ends in punctuation Slack may take into the link: ${i.map((c)=>`${JSON.stringify(c.url)} → ${JSON.stringify(Cs(`x ${c.url}`).slice(2))}`).join(", ")}. If the ${JSON.stringify(i[0].char)} is not part of the URL, send the suggested form (or --fix-urls).`);let l=o.filter((c)=>c.side!=="trailing"&&s.includes(c.side));if(!l.length)return;let u=l.map((c)=>c.side==="before"?`${JSON.stringify(c.url)} (glued to ${JSON.stringify(c.char)} before it — Slack will NOT make it a link)`:`${JSON.stringify(c.url)} (runs into ${JSON.stringify(c.char)} after it; non-ASCII in a URL is OK only if intended, otherwise send ${JSON.stringify(Cs(`x ${c.url}`).slice(2))} or put an ASCII space after the URL)`),f=l.some((c)=>c.side==="before")?"Put an ASCII space (or a newline) before the URL, ":"",a=`Ambiguous URL boundary: ${u.join(", ")}. ${f}Put the URL on its own line, or wrap it as <url> / <url|label>. Use --fix-urls to wrap them, or --allow-url-adjacent to warn only.`;if(!t)throw Error(a);n(`⚠ Warning: ${a}`)}function Cs(e){let t=dd(e),n="",s=0;for(let r of t.matchAll(cd)){let o=r.index??0;if(r[0].startsWith("<"))continue;let i=e.slice(o,o+r[0].length),l=i.search(/[^\x00-\x7f]|>/);if(l>=0)i=i.slice(0,l);while(ud(i))i=i.slice(0,-1);let u=o>0?t[o-1]:"";if(!(i.length<r[0].length||u&&!ld.test(u))||!/^https?:\/\/./i.test(i))continue;n+=e.slice(s,o)+`<${i}>`,s=o+i.length}return n+e.slice(s)}function ad(e,t){return e.split(t).length-1}import{existsSync as Ts,readFileSync as Ji,writeFileSync as Wi,mkdirSync as md,chmodSync as pd}from"node:fs";import{homedir as ub}from"node:os";import{join as Nt,dirname as Ki}from"node:path";import{existsSync as fd}from"node:fs";import{join as Rr}from"node:path";var cb="slack-hub",lb="slack-term",wt=".slack-hub",kt=".slack-term";function Pe(e,t=process.env){return t[`SLACK_HUB_${e}`]??t[`SLACK_TERM_${e}`]}function Vn(e,t){return!fd(e)&&fd(t)?t:e}function Ir(e){return Vn(Rr(e,cb),Rr(e,lb))}function ji(e){return Vn(Rr(e,wt),Rr(e,kt))}function qi(){return process.env.HOME||ub()}function yd(){return Nt(qi(),".config","slack-cli","profiles.json")}function vr(){return Nt(process.cwd(),".slack-cli","workspace")}function Pr(){return Nt(qi(),".slack-cli","workspace")}function Fs(){let e=yd();if(!Ts(e))return{profiles:{}};return JSON.parse(Ji(e,"utf8"))}function db(e){let t=yd();if(md(Ki(t),{recursive:!0}),process.platform!=="win32"&&Ts(t))pd(t,384);if(Wi(t,JSON.stringify(e,null,2)+`
87
- `,{mode:384}),process.platform!=="win32")pd(t,384)}function Zn(e){if(!Ts(e))return;return Ji(e,"utf8").trim()||void 0}function hd(e,t){let n=Ki(e);md(n,{recursive:!0});let s=Nt(n,".gitignore");if(!Ts(s))Wi(s,`*
88
- `);Wi(e,t+`
89
- `)}function fb(e){let t={};for(let n of e.split(`
90
- `)){let s=n.trim();if(!s||s.startsWith("#"))continue;let r=s.indexOf("=");if(r===-1)continue;let o=s.slice(0,r).trim(),i=s.slice(r+1).trim();if(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))i=i.slice(1,-1);t[o]=i}return t}function gd(e){if(!Ts(e))return{};try{return fb(Ji(e,"utf8"))}catch{return{}}}function Ui(e,t){let n=qi(),s=e;while(!0){for(let i of[Nt(s,wt,".env.local"),Nt(s,kt,".env.local"),Nt(s,".env.local")]){let l=gd(i);for(let u of t)if(l[u])return l[u]}if(s===n)break;let o=Ki(s);if(o===s)break;s=o}let r=gd(Vn(Nt(n,wt,".env.local"),Nt(n,kt,".env.local")));for(let o of t)if(r[o])return r[o];return}function Hi(){let e=Fs(),t=Zn(vr()),n=Zn(Pr()),s=t??n;return Object.entries(e.profiles).map(([r,o])=>{let i=As(e,r);return{name:r,profile:{...o,...i?{cookie:i}:{}},current:r===s}})}function As(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 bd(e){let t=Fs();if(!(e in t.profiles))throw Error(`Profile not found: ${e}`);delete t.profiles[e],db(t)}function wd(e,t=!1){let n=Fs();if(!(e in n.profiles))throw Error(`Profile not found: ${e}`);if(t)hd(Pr(),e);else hd(vr(),e)}function Os(e){let n=Fs().profiles,s=Object.keys(n);if(e){let a=n[e];if(!a)throw Error(`Workspace "${e}" not found. Available: ${s.join(", ")||"(none)"}`);return a.token}if(process.env.SLACK_TOKEN)return process.env.SLACK_TOKEN;let r=process.env.SLACK_BOT_TOKEN??process.env.SLACK_MCP_XOXP_TOKEN;if(r&&s.length===0)return r;let o=[process.env.SLACK_BOT_TOKEN,process.env.SLACK_MCP_XOXP_TOKEN].find((a)=>a&&!a.startsWith("xoxb-"));if(o&&s.length>0){let a=Ui(process.cwd(),["SLACK_BOT_TOKEN","SLACK_MCP_XOXP_TOKEN"]);if(o!==a){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=Ui(process.cwd(),["SLACK_TOKEN"]);if(i)return i;let l=process.env.SLACK_WORKSPACE;if(l){let a=n[l];if(!a)throw Error(`Workspace "${l}" not found. Available: ${s.join(", ")||"(none)"}`);return a.token}let u=Zn(vr());if(u){let a=n[u];if(!a)throw Error(`Workspace "${u}" (from .slack-cli/workspace) not found in profiles.`);return a.token}let f=Zn(Pr());if(f){let a=n[f];if(!a)throw Error(`Workspace "${f}" (from ~/.slack-cli/workspace) not found in profiles.`);return a.token}if(s.length>0)throw Error(`Workspace not selected (${s.join(", ")} available).
83
+ `?/^ {0,3}(?:(`{3,})[^`\n]*|(~{3,})[^\n]*)(?=\n|$)/.exec(e.slice(s)):null;if(o){let a=o[1]??o[2],c=new RegExp(`
84
+ {0,3}${a[0]==="`"?"`":"~"}{${a.length},}[ ]*\r?(?=
85
+ |$)`,"g");c.lastIndex=s+o[0].length;let d=c.exec(e),f=d?d.index+d[0].length:e.length;n(s,f),s=f;continue}let i=e[s];if(i==="\\"){s+=2;continue}if(i==="`"){let a=0;while(e[s+a]==="`")a++;let c=s+a,d=-1;while(c<e.length){if(e[c]===`
86
+ `&&/^\n[ \t\r]*(?:\n|$)/.test(e.slice(c)))break;if(e[c]!=="`"){c++;continue}let f=0;while(e[c+f]==="`")f++;if(f===a){d=c+f;break}c+=f}if(d<0){s+=a;continue}n(s,d),s=d;continue}if(i==="["){let a=/^\[(?:\\.|[^\]\\\n])*\]\([^()\s]*\)/.exec(e.slice(s));if(a){n(s,s+a[0].length),s+=a[0].length;continue}}s++}return t.join("")}function Pb(e,{markdown:t=!0}={}){let n=t?Ad(e):e,s=[];for(let r of n.matchAll(Ed)){let o=r[0];if(o.startsWith("<"))continue;let i=r.index??0,a=i>0?n[i-1]:"";if(a&&!$d.test(a))s.push({url:o,side:"before",char:e[i-1]});let c=o.match(/[^\x00-\x7f]|>/);if(c)s.push({url:o,side:"after",char:c[0]});else{let d=Cd(o);if(d&&!(d===")"&&a==="("))s.push({url:o,side:"trailing",char:d})}}return s}function He(e,t=!1,n=console.error,{sides:s=["before","after","trailing"],markdown:r=!0}={}){let o=Pb(e,{markdown:r}),i=o.filter((p)=>p.side==="trailing"&&s.includes("trailing"));if(i.length)n(`⚠ URL ends in punctuation Slack may take into the link: ${i.map((p)=>`${JSON.stringify(p.url)} → ${JSON.stringify(Is(`x ${p.url}`).slice(2))}`).join(", ")}. If the ${JSON.stringify(i[0].char)} is not part of the URL, send the suggested form (or --fix-urls).`);let a=o.filter((p)=>p.side!=="trailing"&&s.includes(p.side));if(!a.length)return;let c=a.map((p)=>p.side==="before"?`${JSON.stringify(p.url)} (glued to ${JSON.stringify(p.char)} before it — Slack will NOT make it a link)`:`${JSON.stringify(p.url)} (runs into ${JSON.stringify(p.char)} after it; non-ASCII in a URL is OK only if intended, otherwise send ${JSON.stringify(Is(`x ${p.url}`).slice(2))} or put an ASCII space after the URL)`),d=a.some((p)=>p.side==="before")?"Put an ASCII space (or a newline) before the URL, ":"",f=`Ambiguous URL boundary: ${c.join(", ")}. ${d}Put the URL on its own line, or wrap it as <url> / <url|label>. Use --fix-urls to wrap them, or --allow-url-adjacent to warn only.`;if(!t)throw Error(f);n(`⚠ Warning: ${f}`)}function Is(e){let t=Ad(e),n="",s=0;for(let r of t.matchAll(Ed)){let o=r.index??0;if(r[0].startsWith("<"))continue;let i=e.slice(o,o+r[0].length),a=i.search(/[^\x00-\x7f]|>/);if(a>=0)i=i.slice(0,a);while(Cd(i))i=i.slice(0,-1);let c=o>0?t[o-1]:"";if(!(i.length<r[0].length||c&&!$d.test(c))||!/^https?:\/\/./i.test(i))continue;n+=e.slice(s,o)+`<${i}>`,s=o+i.length}return n+e.slice(s)}function _d(e,t){return e.split(t).length-1}import{existsSync as vs,readFileSync as ea,writeFileSync as Zi,mkdirSync as Rd,chmodSync as Fd}from"node:fs";import{homedir as Mb}from"node:os";import{join as Wt,dirname as ta}from"node:path";import{existsSync as Td}from"node:fs";import{join as Br}from"node:path";var Lb="slack-hub",Nb="slack-term",kt=".slack-hub",Dt=".slack-term";function Ae(e,t=process.env){return t[`SLACK_HUB_${e}`]??t[`SLACK_TERM_${e}`]}function ns(e,t){return!Td(e)&&Td(t)?t:e}function jr(e){return ns(Br(e,Lb),Br(e,Nb))}function Vi(e){return ns(Br(e,kt),Br(e,Dt))}function na(){return process.env.HOME||Mb()}function vd(){return Wt(na(),".config","slack-cli","profiles.json")}function Wr(){return Wt(process.cwd(),".slack-cli","workspace")}function Ur(){return Wt(na(),".slack-cli","workspace")}function Ps(){let e=vd();if(!vs(e))return{profiles:{}};return JSON.parse(ea(e,"utf8"))}function Bb(e){let t=vd();if(Rd(ta(t),{recursive:!0}),process.platform!=="win32"&&vs(t))Fd(t,384);if(Zi(t,JSON.stringify(e,null,2)+`
87
+ `,{mode:384}),process.platform!=="win32")Fd(t,384)}function ss(e){if(!vs(e))return;return ea(e,"utf8").trim()||void 0}function Od(e,t){let n=ta(e);Rd(n,{recursive:!0});let s=Wt(n,".gitignore");if(!vs(s))Zi(s,`*
88
+ `);Zi(e,t+`
89
+ `)}function jb(e){let t={};for(let n of e.split(`
90
+ `)){let s=n.trim();if(!s||s.startsWith("#"))continue;let r=s.indexOf("=");if(r===-1)continue;let o=s.slice(0,r).trim(),i=s.slice(r+1).trim();if(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))i=i.slice(1,-1);t[o]=i}return t}function Id(e){if(!vs(e))return{};try{return jb(ea(e,"utf8"))}catch{return{}}}function Qi(e,t){let n=na(),s=e;while(!0){for(let i of[Wt(s,kt,".env.local"),Wt(s,Dt,".env.local"),Wt(s,".env.local")]){let a=Id(i);for(let c of t)if(a[c])return a[c]}if(s===n)break;let o=ta(s);if(o===s)break;s=o}let r=Id(ns(Wt(n,kt,".env.local"),Wt(n,Dt,".env.local")));for(let o of t)if(r[o])return r[o];return}function sa(){let e=Ps(),t=ss(Wr()),n=ss(Ur()),s=t??n;return Object.entries(e.profiles).map(([r,o])=>{let i=Rs(e,r);return{name:r,profile:{...o,...i?{cookie:i}:{}},current:r===s}})}function Rs(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 Pd(e){let t=Ps();if(!(e in t.profiles))throw Error(`Profile not found: ${e}`);delete t.profiles[e],Bb(t)}function Ld(e,t=!1){let n=Ps();if(!(e in n.profiles))throw Error(`Profile not found: ${e}`);if(t)Od(Ur(),e);else Od(Wr(),e)}var Nd;function Md(){return Nd}function Pn(e,t,n,s=[]){return Nd={kind:n,name:t,shadowed:s},e}function Ls(e){let n=Ps().profiles,s=Object.keys(n);if(e){let f=n[e];if(!f)throw Error(`Workspace "${e}" not found. Available: ${s.join(", ")||"(none)"}`);return Pn(f.token,`profile "${e}" (--workspace)`,"profile")}if(process.env.SLACK_TOKEN)return Pn(process.env.SLACK_TOKEN,"SLACK_TOKEN","env",s);let r=process.env.SLACK_BOT_TOKEN??process.env.SLACK_MCP_XOXP_TOKEN;if(r&&s.length===0)return Pn(r,process.env.SLACK_BOT_TOKEN?"SLACK_BOT_TOKEN":"SLACK_MCP_XOXP_TOKEN","env");let o=[process.env.SLACK_BOT_TOKEN,process.env.SLACK_MCP_XOXP_TOKEN].find((f)=>f&&!f.startsWith("xoxb-"));if(o&&s.length>0){let f=Qi(process.cwd(),["SLACK_BOT_TOKEN","SLACK_MCP_XOXP_TOKEN"]);if(o!==f){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=Qi(process.cwd(),["SLACK_TOKEN"]);if(i)return Pn(i,"SLACK_TOKEN (from an env file above the current directory)","env",s);let a=process.env.SLACK_WORKSPACE;if(a){let f=n[a];if(!f)throw Error(`Workspace "${a}" not found. Available: ${s.join(", ")||"(none)"}`);return Pn(f.token,`profile "${a}" (SLACK_WORKSPACE)`,"profile")}let c=ss(Wr());if(c){let f=n[c];if(!f)throw Error(`Workspace "${c}" (from .slack-cli/workspace) not found in profiles.`);return Pn(f.token,`profile "${c}" (.slack-cli/workspace)`,"profile")}let d=ss(Ur());if(d){let f=n[d];if(!f)throw Error(`Workspace "${d}" (from ~/.slack-cli/workspace) not found in profiles.`);return Pn(f.token,`profile "${d}" (~/.slack-cli/workspace)`,"profile")}if(s.length>0)throw Error(`Workspace not selected (${s.join(", ")} available).
92
92
  Select locally: slack auth use <name> (writes .slack-cli/workspace)
93
93
  Select globally: slack auth use -g <name> (writes ~/.slack-cli/workspace)`);throw Error(`No Slack token found.
94
94
  Run one of:
@@ -97,13 +97,13 @@ ${h.join(`
97
97
  `+` slack auth cookie — attach the xoxd cookie from Chrome (macOS/Windows)
98
98
  `+` slack auth firefox — attach the xoxd cookie from Firefox (all platforms)
99
99
  `+` slack auth token --token xoxp-... — paste an existing token
100
- `+" Or set SLACK_TOKEN=xoxp-... in .slack-hub/.env.local")}function Ne(){let e=process.env.SLACK_BOT_TOKEN;return e&&e.startsWith("xoxb-")?e:void 0}function zi(e){let t=Fs(),n=t.profiles;if(e)return As(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 r=Ui(process.cwd(),["SLACK_COOKIE"]);if(r)return r;let o=process.env.SLACK_WORKSPACE;if(o)return As(t,o);let i=Zn(vr());if(i)return As(t,i);let l=Zn(Pr());if(l)return As(t,l);return}import{existsSync as Qn,readFileSync as Nr,writeFileSync as Dd,mkdirSync as xd,chmodSync as Lr}from"node:fs";import{homedir as pb}from"node:os";import{join as nn,dirname as Gi}from"node:path";function Xi(){return process.env.HOME||pb()}function Sd(){return nn(Xi(),".config","slack-cli","profiles.json")}function Vi(){return nn(process.cwd(),".slack-cli","workspace")}function Zi(){return nn(Xi(),".slack-cli","workspace")}function ts(){let e=Sd();if(!Qn(e))return{profiles:{}};return JSON.parse(Nr(e,"utf8"))}function Qi(e){let t=Sd();if(xd(Gi(t),{recursive:!0}),process.platform!=="win32"&&Qn(t))Lr(t,384);if(Dd(t,JSON.stringify(e,null,2)+`
101
- `,{mode:384}),process.platform!=="win32")Lr(t,384)}function es(e){if(!Qn(e))return;return Nr(e,"utf8").trim()||void 0}function hb(e){let t={};for(let n of e.split(`
102
- `)){let s=n.trim();if(!s||s.startsWith("#"))continue;let r=s.indexOf("=");if(r===-1)continue;let o=s.slice(0,r).trim(),i=s.slice(r+1).trim();if(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))i=i.slice(1,-1);t[o]=i}return t}function kd(e){if(!Qn(e))return{};try{return hb(Nr(e,"utf8"))}catch{return{}}}function Yi(e,t){let n=Xi(),s=e;while(!0){for(let i of[nn(s,wt,".env.local"),nn(s,kt,".env.local"),nn(s,".env.local")]){let l=kd(i);for(let u of t)if(l[u])return l[u]}if(s===n)break;let o=Gi(s);if(o===s)break;s=o}let r=kd(Vn(nn(n,wt,".env.local"),nn(n,kt,".env.local")));for(let o of t)if(r[o])return r[o];return}function ea(e,t){xd(Gi(e),{recursive:!0});let n=Qn(e)?Nr(e,"utf8"):"",s=n?n.split(`
103
- `):[];for(let[r,o]of Object.entries(t)){let i=s.findIndex((u)=>{let f=u.trim();return f.startsWith(r+"=")||f.startsWith(r+" =")}),l=`${r}=${o}`;if(i!==-1)s[i]=l;else s.push(l)}if(process.platform!=="win32"&&Qn(e))Lr(e,384);if(Dd(e,s.join(`
100
+ `+" Or set SLACK_TOKEN=xoxp-... in .slack-hub/.env.local")}function Me(){let e=process.env.SLACK_BOT_TOKEN;return e&&e.startsWith("xoxb-")?e:void 0}function ra(e){let t=Ps(),n=t.profiles;if(e)return Rs(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 r=Qi(process.cwd(),["SLACK_COOKIE"]);if(r)return r;let o=process.env.SLACK_WORKSPACE;if(o)return Rs(t,o);let i=ss(Wr());if(i)return Rs(t,i);let a=ss(Ur());if(a)return Rs(t,a);return}import{existsSync as rs,readFileSync as Kr,writeFileSync as jd,mkdirSync as Wd,chmodSync as Jr}from"node:fs";import{homedir as Wb}from"node:os";import{join as rn,dirname as ia}from"node:path";function aa(){return process.env.HOME||Wb()}function Ud(){return rn(aa(),".config","slack-cli","profiles.json")}function ca(){return rn(process.cwd(),".slack-cli","workspace")}function la(){return rn(aa(),".slack-cli","workspace")}function is(){let e=Ud();if(!rs(e))return{profiles:{}};return JSON.parse(Kr(e,"utf8"))}function ua(e){let t=Ud();if(Wd(ia(t),{recursive:!0}),process.platform!=="win32"&&rs(t))Jr(t,384);if(jd(t,JSON.stringify(e,null,2)+`
101
+ `,{mode:384}),process.platform!=="win32")Jr(t,384)}function os(e){if(!rs(e))return;return Kr(e,"utf8").trim()||void 0}function Ub(e){let t={};for(let n of e.split(`
102
+ `)){let s=n.trim();if(!s||s.startsWith("#"))continue;let r=s.indexOf("=");if(r===-1)continue;let o=s.slice(0,r).trim(),i=s.slice(r+1).trim();if(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))i=i.slice(1,-1);t[o]=i}return t}function Bd(e){if(!rs(e))return{};try{return Ub(Kr(e,"utf8"))}catch{return{}}}function oa(e,t){let n=aa(),s=e;while(!0){for(let i of[rn(s,kt,".env.local"),rn(s,Dt,".env.local"),rn(s,".env.local")]){let a=Bd(i);for(let c of t)if(a[c])return a[c]}if(s===n)break;let o=ia(s);if(o===s)break;s=o}let r=Bd(ns(rn(n,kt,".env.local"),rn(n,Dt,".env.local")));for(let o of t)if(r[o])return r[o];return}function da(e,t){Wd(ia(e),{recursive:!0});let n=rs(e)?Kr(e,"utf8"):"",s=n?n.split(`
103
+ `):[];for(let[r,o]of Object.entries(t)){let i=s.findIndex((c)=>{let d=c.trim();return d.startsWith(r+"=")||d.startsWith(r+" =")}),a=`${r}=${o}`;if(i!==-1)s[i]=a;else s.push(a)}if(process.platform!=="win32"&&rs(e))Jr(e,384);if(jd(e,s.join(`
104
104
  `).trimEnd()+`
105
- `,{mode:384}),process.platform!=="win32")Lr(e,384)}function Is(){let e=ts(),t=es(Vi()),n=es(Zi()),s=t??n;return Object.entries(e.profiles).map(([r,o])=>{let i=Rs(e,r);return{name:r,profile:{...o,...i?{cookie:i}:{}},current:r===s}})}function Mr(e,t){let n=ts();if(t.identity&&t.cookie){n.users??={};let s=n.users[t.identity]??{};n.users[t.identity]={...s,cookie:t.cookie};let{cookie:r,...o}=t;n.profiles[e]=o}else n.profiles[e]=t;Qi(n)}function ta(e,t){let n=ts(),s=n.profiles[e];if(!s)throw Error(`Profile not found: ${e}`);if(s.identity)n.users??={},n.users[s.identity]={...n.users[s.identity]??{},cookie:t};else s.cookie=t;Qi(n)}function _d(e,t,n){let s=ts();s.users??={},s.users[e]={...s.users[e]??{},cookie:t,...n?{source:n}:{}},Qi(s)}function Rs(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 Ed(e){let n=ts().profiles,s=Object.keys(n);if(e){let a=n[e];if(!a)throw Error(`Workspace "${e}" not found. Available: ${s.join(", ")||"(none)"}`);return a.token}if(process.env.SLACK_TOKEN)return process.env.SLACK_TOKEN;let r=process.env.SLACK_BOT_TOKEN??process.env.SLACK_MCP_XOXP_TOKEN;if(r&&s.length===0)return r;let o=[process.env.SLACK_BOT_TOKEN,process.env.SLACK_MCP_XOXP_TOKEN].find((a)=>a&&!a.startsWith("xoxb-"));if(o&&s.length>0){let a=Yi(process.cwd(),["SLACK_BOT_TOKEN","SLACK_MCP_XOXP_TOKEN"]);if(o!==a){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=Yi(process.cwd(),["SLACK_TOKEN"]);if(i)return i;let l=process.env.SLACK_WORKSPACE;if(l){let a=n[l];if(!a)throw Error(`Workspace "${l}" not found. Available: ${s.join(", ")||"(none)"}`);return a.token}let u=es(Vi());if(u){let a=n[u];if(!a)throw Error(`Workspace "${u}" (from .slack-cli/workspace) not found in profiles.`);return a.token}let f=es(Zi());if(f){let a=n[f];if(!a)throw Error(`Workspace "${f}" (from ~/.slack-cli/workspace) not found in profiles.`);return a.token}if(s.length>0)throw Error(`Workspace not selected (${s.join(", ")} available).
105
+ `,{mode:384}),process.platform!=="win32")Jr(e,384)}function Ms(){let e=is(),t=os(ca()),n=os(la()),s=t??n;return Object.entries(e.profiles).map(([r,o])=>{let i=Ns(e,r);return{name:r,profile:{...o,...i?{cookie:i}:{}},current:r===s}})}function qr(e,t){let n=is();if(t.identity&&t.cookie){n.users??={};let s=n.users[t.identity]??{};n.users[t.identity]={...s,cookie:t.cookie};let{cookie:r,...o}=t;n.profiles[e]=o}else n.profiles[e]=t;ua(n)}function fa(e,t){let n=is(),s=n.profiles[e];if(!s)throw Error(`Profile not found: ${e}`);if(s.identity)n.users??={},n.users[s.identity]={...n.users[s.identity]??{},cookie:t};else s.cookie=t;ua(n)}function Jd(e,t,n){let s=is();s.users??={},s.users[e]={...s.users[e]??{},cookie:t,...n?{source:n}:{}},ua(s)}function Ns(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}var Jb;function Ln(e,t,n,s=[]){return Jb={kind:n,name:t,shadowed:s},e}function Kd(e){let n=is().profiles,s=Object.keys(n);if(e){let f=n[e];if(!f)throw Error(`Workspace "${e}" not found. Available: ${s.join(", ")||"(none)"}`);return Ln(f.token,`profile "${e}" (--workspace)`,"profile")}if(process.env.SLACK_TOKEN)return Ln(process.env.SLACK_TOKEN,"SLACK_TOKEN","env",s);let r=process.env.SLACK_BOT_TOKEN??process.env.SLACK_MCP_XOXP_TOKEN;if(r&&s.length===0)return Ln(r,process.env.SLACK_BOT_TOKEN?"SLACK_BOT_TOKEN":"SLACK_MCP_XOXP_TOKEN","env");let o=[process.env.SLACK_BOT_TOKEN,process.env.SLACK_MCP_XOXP_TOKEN].find((f)=>f&&!f.startsWith("xoxb-"));if(o&&s.length>0){let f=oa(process.cwd(),["SLACK_BOT_TOKEN","SLACK_MCP_XOXP_TOKEN"]);if(o!==f){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=oa(process.cwd(),["SLACK_TOKEN"]);if(i)return Ln(i,"SLACK_TOKEN (from an env file above the current directory)","env",s);let a=process.env.SLACK_WORKSPACE;if(a){let f=n[a];if(!f)throw Error(`Workspace "${a}" not found. Available: ${s.join(", ")||"(none)"}`);return Ln(f.token,`profile "${a}" (SLACK_WORKSPACE)`,"profile")}let c=os(ca());if(c){let f=n[c];if(!f)throw Error(`Workspace "${c}" (from .slack-cli/workspace) not found in profiles.`);return Ln(f.token,`profile "${c}" (.slack-cli/workspace)`,"profile")}let d=os(la());if(d){let f=n[d];if(!f)throw Error(`Workspace "${d}" (from ~/.slack-cli/workspace) not found in profiles.`);return Ln(f.token,`profile "${d}" (~/.slack-cli/workspace)`,"profile")}if(s.length>0)throw Error(`Workspace not selected (${s.join(", ")} available).
107
107
  Select locally: slack auth use <name> (writes .slack-cli/workspace)
108
108
  Select globally: slack auth use -g <name> (writes ~/.slack-cli/workspace)`);throw Error(`No Slack token found.
109
109
  Run one of:
@@ -112,34 +112,35 @@ ${h.join(`
112
112
  `+` slack auth cookie — attach the xoxd cookie from Chrome (macOS/Windows)
113
113
  `+` slack auth firefox — attach the xoxd cookie from Firefox (all platforms)
114
114
  `+` slack auth token --token xoxp-... — paste an existing token
115
- `+" Or set SLACK_TOKEN=xoxp-... in .slack-hub/.env.local")}function Br(){let e=process.env.SLACK_BOT_TOKEN;return e&&e.startsWith("xoxb-")?e:void 0}function sn(e){let t=ts(),n=t.profiles;if(e)return Rs(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 r=Yi(process.cwd(),["SLACK_COOKIE"]);if(r)return r;let o=process.env.SLACK_WORKSPACE;if(o)return Rs(t,o);let i=es(Vi());if(i)return Rs(t,i);let l=es(Zi());if(l)return Rs(t,l);return}function jr(e){let t=[],n=(o)=>{if(!o)return;let i=t[t.length-1];if(i?.type==="text")i.text+=o;else t.push({type:"text",text:o})},s=/<(https?:\/\/[^\s<>|]+)(?:\|([^<>\r\n]*))?>|https?:\/\/[\x21-\x3b\x3d\x3f-\x7e]+/gi,r=0;for(let o of e.matchAll(s)){let i=o.index??0;if(n(e.slice(r,i)),o[1]){t.push(o[2]?{type:"link",url:o[1],text:o[2]}:{type:"link",url:o[1]}),r=i+o[0].length;continue}let l=o[0];while(/[.,:;!?'"*_~]$/.test(l)||l.endsWith(")")&&$d(l,"(")<$d(l,")"))l=l.slice(0,-1);t.push({type:"link",url:l}),r=i+l.length}return n(e.slice(r)),t}function $d(e,t){return e.split(t).length-1}var gb={"&":"&amp;","<":"&lt;",">":"&gt;"};function mb(e){if(typeof e!=="string"||!/^[0-9a-f]+(-[0-9a-f]+)*$/i.test(e))return[];let t=e.split("-").map((r)=>parseInt(r,16)),n=String.fromCodePoint(...t),s=String.fromCodePoint(...t.filter((r)=>r!==65039));return n===s?[n]:[n,s]}function yb(e){let t=[],n=(o)=>{for(let i of o)if(i===`
116
- `)t.push(null);else if(!/\s/u.test(i))t.push(...gb[i]??i)},s=(o)=>{switch(o.type){case"text":n(String(o.text??""));break;case"link":case"message_mention":n(String(o.url??""));break;case"user":n(String(o.user_id??""));break;case"channel":n(String(o.channel_id??""));break;case"usergroup":n(String(o.usergroup_id??""));break;case"broadcast":n(String(o.range??""));break;case"emoji":t.push([`:${String(o.name??"")}:`,...mb(o.unicode)].filter((i)=>i!=="::"));break;default:break}},r=(o)=>{let i=Array.isArray(o.elements)?o.elements:[];if(o.type==="rich_text_list"||o.type==="rich_text")i.forEach((l,u)=>{if(u>0)t.push(null);r(l)});else i.forEach(s)};return e.forEach((o,i)=>{if(i>0)t.push(null);let l=o;if(l.type==="rich_text")r(l)}),t}function bb(e,t,n){if(typeof t==="string"){let r=n;while(r<e.length&&e[r]!==t)r++;return r<e.length?[r,1]:[-1,0]}let s=[-1,0];for(let r of t){let o=[...r];for(let i=n;i+o.length<=e.length&&(s[0]<0||i<s[0]);i++)if(o.every((l,u)=>e[i+u]===l)){s=[i,o.length];break}}return s}function wb(e,t){if(e.includes(`
117
- `)||!Array.isArray(t)||!t.some((h)=>h?.type==="rich_text"))return e;let n=yb(t);if(!n.includes(null))return e;let s=[...e],r=t[0].elements,i=t[t.length-1].elements,l=Array.isArray(r)&&r[0]?.type==="rich_text_preformatted",u=Array.isArray(i)&&i[i.length-1]?.type==="rich_text_preformatted",f=0,a=-1,c=l,d=[];for(let h of n){if(h===null){c=!0;continue}let[g,y]=bb(s,h,f);if(g<0)return e;if(c)d.push([a+1,g]),c=!1;a=g+y-1,f=g+y}if((c||u)&&a>=0)d.push([a+1,s.length]);let p=/^(?:[-*+•]|\d{1,9}[.)]|&gt;|>)$/;for(let[h,g]of d){let y=h;if(s.lastIndexOf("<",h-1)>s.lastIndexOf(">",h-1)){let k=s.indexOf(">",h);if(k!==-1&&k<g)y=k+1}let m="",w=h===0;while(y<g)if(s[y]===" "){let k=y;while(k<g&&s[k]===" ")k++;if(w&&p.test(m))w=!1;else{let _=k-y<=2?k-y:1;for(let D=y;D<y+_;D++)s[D]=`
118
- `;w=!0}m="",y=k}else m+=s[y],y++}return s.join("")}function Wr(e){if(!e||typeof e!=="object"||Array.isArray(e))return;let t=e;if(typeof t.text==="string")t.text=wb(t.text,t.blocks)}class He 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 sa(){return(process.env.SLACK_API_BASE??"https://slack.com/api").replace(/\/$/,"")}var kb=(()=>{let e=Number(process.env.SLACK_RATELIMIT_WAIT_SEC);return Number.isFinite(e)&&e>=0?e:120})();async function Fd(e,t=(n)=>new Promise((s)=>setTimeout(s,n))){let n=0;for(;;)try{return await e()}catch(s){if(!(s instanceof He)||n+s.retryAfter>kb)throw s;n+=s.retryAfter,console.error(`slack: ${s.message} — waiting`),await t(s.retryAfter*1000)}}function ra(e,t,n,s){return Fd(()=>Db(e,t,n,s))}async function Db(e,t,n,s){s=e.startsWith("xoxc-")?s??sn():void 0;let r={};if(s)r.Cookie=`d=${s}`;let o=await fetch(`${sa()}/${t}`,{...n,headers:{...n.headers??{},Authorization:`Bearer ${e}`,...r}});if(o.status===429){let l=parseInt(o.headers.get("retry-after")??"60",10);throw new He(isNaN(l)?60:l,t)}let i=await o.json();if(i.ok!==!0){let l=i.error??"unknown";if(l==="ratelimited")throw new He(60,t);if(l==="invalid_auth"&&e.startsWith("xoxc-")&&!s)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-hub/.env.local")}function Hr(){let e=process.env.SLACK_BOT_TOKEN;return e&&e.startsWith("xoxb-")?e:void 0}function Ot(e){let t=is(),n=t.profiles;if(e)return Ns(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 r=oa(process.cwd(),["SLACK_COOKIE"]);if(r)return r;let o=process.env.SLACK_WORKSPACE;if(o)return Ns(t,o);let i=os(ca());if(i)return Ns(t,i);let a=os(la());if(a)return Ns(t,a);return}function zr(e){let t=[],n=(o)=>{if(!o)return;let i=t[t.length-1];if(i?.type==="text")i.text+=o;else t.push({type:"text",text:o})},s=/<(https?:\/\/[^\s<>|]+)(?:\|([^<>\r\n]*))?>|https?:\/\/[\x21-\x3b\x3d\x3f-\x7e]+/gi,r=0;for(let o of e.matchAll(s)){let i=o.index??0;if(n(e.slice(r,i)),o[1]){t.push(o[2]?{type:"link",url:o[1],text:o[2]}:{type:"link",url:o[1]}),r=i+o[0].length;continue}let a=o[0];while(/[.,:;!?'"*_~]$/.test(a)||a.endsWith(")")&&qd(a,"(")<qd(a,")"))a=a.slice(0,-1);t.push({type:"link",url:a}),r=i+a.length}return n(e.slice(r)),t}function qd(e,t){return e.split(t).length-1}var Kb={"&":"&amp;","<":"&lt;",">":"&gt;"};function qb(e){if(typeof e!=="string"||!/^[0-9a-f]+(-[0-9a-f]+)*$/i.test(e))return[];let t=e.split("-").map((r)=>parseInt(r,16)),n=String.fromCodePoint(...t),s=String.fromCodePoint(...t.filter((r)=>r!==65039));return n===s?[n]:[n,s]}function Hb(e){let t=[],n=(o)=>{for(let i of o)if(i===`
116
+ `)t.push(null);else if(!/\s/u.test(i))t.push(...Kb[i]??i)},s=(o)=>{switch(o.type){case"text":n(String(o.text??""));break;case"link":case"message_mention":n(String(o.url??""));break;case"user":n(String(o.user_id??""));break;case"channel":n(String(o.channel_id??""));break;case"usergroup":n(String(o.usergroup_id??""));break;case"broadcast":n(String(o.range??""));break;case"emoji":t.push([`:${String(o.name??"")}:`,...qb(o.unicode)].filter((i)=>i!=="::"));break;default:break}},r=(o)=>{let i=Array.isArray(o.elements)?o.elements:[];if(o.type==="rich_text_list"||o.type==="rich_text")i.forEach((a,c)=>{if(c>0)t.push(null);r(a)});else i.forEach(s)};return e.forEach((o,i)=>{if(i>0)t.push(null);let a=o;if(a.type==="rich_text")r(a)}),t}function zb(e,t,n){if(typeof t==="string"){let r=n;while(r<e.length&&e[r]!==t)r++;return r<e.length?[r,1]:[-1,0]}let s=[-1,0];for(let r of t){let o=[...r];for(let i=n;i+o.length<=e.length&&(s[0]<0||i<s[0]);i++)if(o.every((a,c)=>e[i+c]===a)){s=[i,o.length];break}}return s}function Yb(e,t){if(e.includes(`
117
+ `)||!Array.isArray(t)||!t.some((k)=>k?.type==="rich_text"))return e;let n=Hb(t);if(!n.includes(null))return e;let s=[...e],r=t[0].elements,i=t[t.length-1].elements,a=Array.isArray(r)&&r[0]?.type==="rich_text_preformatted",c=Array.isArray(i)&&i[i.length-1]?.type==="rich_text_preformatted",d=0,f=-1,p=a,g=[];for(let k of n){if(k===null){p=!0;continue}let[w,u]=zb(s,k,d);if(w<0)return e;if(p)g.push([f+1,w]),p=!1;f=w+u-1,d=w+u}if((p||c)&&f>=0)g.push([f+1,s.length]);let y=/^(?:[-*+•]|\d{1,9}[.)]|&gt;|>)$/;for(let[k,w]of g){let u=k;if(s.lastIndexOf("<",k-1)>s.lastIndexOf(">",k-1)){let m=s.indexOf(">",k);if(m!==-1&&m<w)u=m+1}let l="",h=k===0;while(u<w)if(s[u]===" "){let m=u;while(m<w&&s[m]===" ")m++;if(h&&y.test(l))h=!1;else{let b=m-u<=2?m-u:1;for(let _=u;_<u+b;_++)s[_]=`
118
+ `;h=!0}l="",u=m}else l+=s[u],u++}return s.join("")}function Yr(e){if(!e||typeof e!=="object"||Array.isArray(e))return;let t=e;if(typeof t.text==="string")t.text=Yb(t.text,t.blocks)}class ze 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 Gr(){return(process.env.SLACK_API_BASE??"https://slack.com/api").replace(/\/$/,"")}function Gb(e){return URL.canParse(e)?new URL(e).origin:e}async function ha(e,t,n){try{return await fetch(t,n)}catch{throw Error(`Slack request failed on ${e}: no answer from ${Gb(t)}`)}}async function ga(e,t){let n;try{n=await t.text()}catch{throw Error(`Slack request failed on ${e}: the answer (HTTP ${t.status}) was cut off`)}try{return JSON.parse(n)}catch{throw Error(`Slack error on ${e}: the answer (HTTP ${t.status}) is not JSON`)}}var Xb=(()=>{let e=Number(process.env.SLACK_RATELIMIT_WAIT_SEC);return Number.isFinite(e)&&e>=0?e:120})();async function Xd(e,t=(n)=>new Promise((s)=>setTimeout(s,n))){let n=0;for(;;)try{return await e()}catch(s){if(!(s instanceof ze)||n+s.retryAfter>Xb)throw s;n+=s.retryAfter,console.error(`slack: ${s.message} — waiting`),await t(s.retryAfter*1000)}}function ma(e,t,n,s){return Xd(()=>Vb(e,t,n,s))}async function Vb(e,t,n,s){s=e.startsWith("xoxc-")?s??Ot():void 0;let r={};if(s)r.Cookie=`d=${s}`;let o=performance.now(),i=await ha(t,`${Gr()}/${t}`,{...n,headers:{...n.headers??{},Authorization:`Bearer ${e}`,...r}});if(Xr(t.replace(/\?.*$/,""),i.status,performance.now()-o),i.status===429){let c=parseInt(i.headers.get("retry-after")??"60",10);throw new ze(isNaN(c)?60:c,t)}let a=await ga(t,i);if(a.ok!==!0){let c=a.error??"unknown";if(c==="ratelimited")throw new ze(60,t);if(c==="invalid_auth"&&e.startsWith("xoxc-")&&!s)throw Error(`Desktop app token (xoxc-) needs its session cookie to be accepted by the public Slack API.
119
119
  Attach it: slack auth firefox (Linux/macOS/Windows) or slack auth chrome (macOS/Linux)
120
120
  Or replace the token with an xoxp- user token:
121
- slack auth login`);if((l==="missing_scope"||l==="cannot_dm_bot")&&e.startsWith("xoxb-")){if(t.startsWith("agents.sessions."))throw Error(`Slack error on ${t}: ${l}. Agent sessions need a granular bot token with chat:write and app membership in the channel.`);throw Error(`Slack error on ${t}: ${l} — ${l==="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"}.
121
+ 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"}.
122
122
  Tailing/DMing people and listing users need a user session, not a bot token.
123
123
  Switch workspace: slack auth ls then slack auth use <name>
124
- Or import your Slack desktop session: slack auth login`)}throw Error(`Slack error on ${t}: ${l}`)}return i}function xb(e,t,n,s){return Fd(()=>Sb(e,t,n,s))}async function Sb(e,t,n,s){let r={};if(s)r.Cookie=`d=${s}`;let o=await fetch(`${sa()}/${t}`,{...n,headers:{...n.headers??{},Authorization:`Bearer ${e}`,...r}});if(o.status===429){let l=parseInt(o.headers.get("retry-after")??"60",10);throw new He(isNaN(l)?60:l,t)}let i=await o.json();if(i.ok!==!0){let l=i.error??"unknown";if(l==="ratelimited")throw new He(60,t);if((l==="invalid_auth"||l==="not_authed")&&!e.startsWith("xoxc-"))throw Error(`${t} requires a desktop app session token (xoxc-).
125
- Import from Slack desktop: slack auth login`);if((l==="invalid_auth"||l==="not_authed")&&!s)throw Error(`${t} also requires the xoxd session cookie.
126
- Attach it with: slack auth firefox (Linux/macOS/Windows) or slack auth chrome (macOS/Linux)`);throw Error(`Slack error on ${t}: ${l}`)}return i}function _b(e,t,n={},s){let r=new URLSearchParams({token:e,...n});return xb(e,t,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:r.toString()},s)}function Te(e,t,n,s){let r=new URLSearchParams(n).toString();return ra(e,`${t}?${r}`,{method:"GET"},s)}function oa(e,t,n,s){return ra(e,t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)},s)}async function Od(e,t,n){if(!e.startsWith("xoxb-"))throw Error("Agent sessions require a bot token (xoxb); user tokens are refused.");return ra(e,t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n),signal:AbortSignal.timeout(1e4)})}function Ps(e,t,n){return Od(e,"agents.sessions.setStatus",{...t,status:n})}function ia(e,t,n){return Od(e,"agents.sessions.rename",{...t,title:n})}async function ns(e,t){let n=await Te(e,"auth.test",{},t);return{team:n.team??"",teamId:n.team_id??"",url:n.url??"",user:n.user??"",userId:n.user_id??""}}async function Rd(e,t){t=e.startsWith("xoxc-")?t??sn():void 0;let n={Authorization:`Bearer ${e}`};if(t)n.Cookie=`d=${t}`;let s=await fetch(`${sa()}/auth.test`,{method:"GET",headers:n});if(s.status===429){let i=parseInt(s.headers.get("retry-after")??"60",10);throw new He(isNaN(i)?60:i,"auth.test")}let r=s.headers.get("x-oauth-scopes")??"",o=await s.json();if(o.ok!==!0)throw Error(`Slack error on auth.test: ${o.error??"unknown"}`);return{userId:o.user_id??"",user:o.user??"",botId:o.bot_id??"",team:o.team??"",url:o.url??"",scopes:r.split(",").map((i)=>i.trim()).filter(Boolean)}}async function Id(e,t,n){let s=await Te(e,"bots.info",{bot:t},n);return{appId:s.bot?.app_id??"",userId:s.bot?.user_id??""}}async function In(e,t,n=20,s,r,o,i){let l={channel:t,limit:String(n)};if(s!==void 0)l.oldest=s;if(r!==void 0)l.cursor=r;if(i)l.inclusive="true";return aa(await Te(e,"conversations.history",l,o))}function aa(e){let t=e,n=Array.isArray(t.messages)?t.messages:t.messages&&typeof t.messages==="object"&&Array.isArray(t.messages.matches)?t.messages.matches:[];for(let s of n)Wr(s);return e}async function vd(e,t,n,s=50,r){return aa(await Te(e,"conversations.replies",{channel:t,ts:n,limit:String(s)},r))}async function Pd(e,t,n,s={},r){let o={channel:t,ts:n,limit:String(s.limit??200)};if(s.oldest!==void 0)o.oldest=s.oldest;if(s.cursor!==void 0)o.cursor=s.cursor;return aa(await Te(e,"conversations.replies",o,r))}async function ca(e,t,n){let s=[],r="";do{let o={limit:"200",types:t,exclude_archived:"true"};if(r)o.cursor=r;let i=await Te(e,"users.conversations",o,n);s.push(...i.channels??[]),r=i.response_metadata?.next_cursor??""}while(r);return s}async function Ur(e,t,n,s,r){await oa(e,"reactions.add",{channel:t,timestamp:n,name:s},r)}async function Ld(e,t,n,s){return((await Te(e,"reactions.get",{channel:t,timestamp:n,full:"true"},s)).message?.reactions??[]).map((o)=>({name:String(o.name??""),users:Array.isArray(o.users)?o.users.map(String):[]}))}async function Jr(e,t,n,s,r){await oa(e,"reactions.remove",{channel:t,timestamp:n,name:s},r)}async function Eb(e,t,n){let r=(await oa(e,"conversations.open",{users:t},n)).channel?.id;if(!r)throw Error(`Failed to open DM with user ${t}`);return r}async function Nd(e,t,n){let s="";while(!0){let r={types:"im",limit:"200"};if(s)r.cursor=s;let o=await Te(e,"conversations.list",r,n);for(let i of o.channels??[])if(i.user===t)return String(i.id??"");if(s=o.response_metadata?.next_cursor??"",!s)break}return""}async function na(e,t,n,s){let r=await Nd(e,t,n);if(r)return r;let o=s?`${s} (${t})`:t;throw Error(`No existing DM with ${o}. Open it once in Slack first.`)}function vs(e){return e.toLowerCase().replace(/[-_\s]/g,"")}function Cd(e,t){let n=vs(e.name??""),s=vs(e.real_name??e.profile?.real_name??""),r=vs(e.profile?.display_name??"");return n===t||s===t||!!r&&r===t}var Md=200;async function $b(e,t,n){let s=0,r=new Set,o="";while(!0){let a={limit:"200"};if(o)a.cursor=o;let c=await Te(e,"users.list",a,n);for(let d of c.members??[]){if(s++,d.id)r.add(d.id);if(Cd(d,t))return{id:d.id??"",workspaceCount:s,connectCount:0,skipped:0,capped:!1}}if(o=c.response_metadata?.next_cursor??"",!o)break}let i=0,l=0,u=!1,f="";while(!0){let a={types:"im",limit:"200"};if(f)a.cursor=f;let c=await Te(e,"conversations.list",a,n);for(let d of c.channels??[]){let p=d.user;if(!p||r.has(p))continue;if(i>=Md){u=!0;break}r.add(p),i++;let h;try{h=(await Te(e,"users.info",{user:p},n)).user}catch(g){if(g instanceof He)throw g;l++;continue}if(h&&Cd(h,t))return{id:p,dm:String(d.id??""),workspaceCount:s,connectCount:i,skipped:l,capped:u}}if(u)break;if(f=c.response_metadata?.next_cursor??"",!f)break}return{id:"",workspaceCount:s,connectCount:i,skipped:l,capped:u}}function Cb(e,t){if(t.workspaceCount===0)return Error(`Cannot resolve ${e}: users.list returned no members at all, so nothing could have matched.
124
+ Or import your Slack desktop session: slack auth login`)}throw Error(`Slack error on ${t}: ${c}${Vd(c,e)}`)}return a}var Hd;var Zb=new Set(["invalid_auth","not_authed","token_revoked","token_expired","account_inactive"]);function Vd(e,t=""){if(!Zb.has(e))return"";if(t.startsWith("xoxb-"))return` (bot token from ${process.env.SLACK_HUB_IDENTITY?`identity @${process.env.SLACK_HUB_IDENTITY}`:"SLACK_BOT_TOKEN"})`;return Hd?` (token from ${Hd})`:""}function Qb(e,t,n,s){return Xd(()=>ew(e,t,n,s))}async function ew(e,t,n,s){let r={};if(s)r.Cookie=`d=${s}`;let o=performance.now(),i=await ha(t,`${Gr()}/${t}`,{...n,headers:{...n.headers??{},Authorization:`Bearer ${e}`,...r}});if(Xr(t.replace(/\?.*$/,""),i.status,performance.now()-o),i.status===429){let c=parseInt(i.headers.get("retry-after")??"60",10);throw new ze(isNaN(c)?60:c,t)}let a=await ga(t,i);if(a.ok!==!0){let c=a.error??"unknown";if(c==="ratelimited")throw new ze(60,t);if((c==="invalid_auth"||c==="not_authed")&&!e.startsWith("xoxc-"))throw Error(`${t} requires a desktop app session token (xoxc-).
125
+ Import from Slack desktop: slack auth login`);if((c==="invalid_auth"||c==="not_authed")&&!s)throw Error(`${t} also requires the xoxd session cookie.
126
+ Attach it with: slack auth firefox (Linux/macOS/Windows) or slack auth chrome (macOS/Linux)`);throw Error(`Slack error on ${t}: ${c}${Vd(c,e)}`)}return a}function tw(e,t,n={},s){let r=new URLSearchParams({token:e,...n});return Qb(e,t,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:r.toString()},s)}var nw=new Set(["auth.test","conversations.info","users.info"]),sw=60000,Zd=!1,as=new Map;function Qd(e,t,n,s){let r=e.startsWith("xoxc-")?s??Ot():void 0;return JSON.stringify([Gr(),e,r,t,n])}function rw(e,t,n){if(!Zd||!nw.has(t))return n();let s=as.get(e);if(s&&Date.now()-s.at<sw)return Xr(t,"cached",0),s.value;let r=n();return as.set(e,{at:Date.now(),value:r}),r.catch(()=>{if(as.get(e)?.value===r)as.delete(e)}),r}function Xr(e,t,n){if(Ae("TIMING")!=="1")return;console.error(`slack-hub timing: ${(performance.now()/1000).toFixed(2)}s ${e} ${t} ${Math.round(n)}ms`)}function Ie(e,t,n,s){let r=new URLSearchParams(n).toString();return rw(Qd(e,t,r,s),t,()=>ma(e,`${t}?${r}`,{method:"GET"},s))}function Bs(e,t,n,s){return as.clear(),ma(e,t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)},s)}async function ef(e,t,n){if(!e.startsWith("xoxb-"))throw Error("Agent sessions require a bot token (xoxb); user tokens are refused.");return ma(e,t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n),signal:AbortSignal.timeout(1e4)})}function Ws(e,t,n){return ef(e,"agents.sessions.setStatus",{...t,status:n})}function ya(e,t,n){return ef(e,"agents.sessions.rename",{...t,title:n})}async function cs(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 tf(e,t){t=e.startsWith("xoxc-")?t??Ot():void 0;let n={Authorization:`Bearer ${e}`};if(t)n.Cookie=`d=${t}`;let s=performance.now(),r=await ha("auth.test",`${Gr()}/auth.test`,{method:"GET",headers:n});if(Xr("auth.test",r.status,performance.now()-s),r.status===429){let a=parseInt(r.headers.get("retry-after")??"60",10);throw new ze(isNaN(a)?60:a,"auth.test")}let o=r.headers.get("x-oauth-scopes")??"",i=await ga("auth.test",r);if(i.ok!==!0)throw Error(`Slack error on auth.test: ${i.error??"unknown"}`);if(Zd)as.set(Qd(e,"auth.test","",t),{at:Date.now(),value:Promise.resolve(i)});return{userId:i.user_id??"",user:i.user??"",botId:i.bot_id??"",team:i.team??"",url:i.url??"",scopes:o.split(",").map((a)=>a.trim()).filter(Boolean)}}async function nf(e,t,n){let s=await Ie(e,"bots.info",{bot:t},n);return{appId:s.bot?.app_id??"",userId:s.bot?.user_id??""}}async function Nn(e,t,n=20,s,r,o,i){let a={channel:t,limit:String(n)};if(s!==void 0)a.oldest=s;if(r!==void 0)a.cursor=r;if(i)a.inclusive="true";return ba(await Ie(e,"conversations.history",a,o))}function ba(e){let t=e,n=Array.isArray(t.messages)?t.messages:t.messages&&typeof t.messages==="object"&&Array.isArray(t.messages.matches)?t.messages.matches:[];for(let s of n)Yr(s);return e}async function sf(e,t,n,s=50,r){return ba(await Ie(e,"conversations.replies",{channel:t,ts:n,limit:String(s)},r))}async function rf(e,t,n,s={},r){let o={channel:t,ts:n,limit:String(s.limit??200)};if(s.oldest!==void 0)o.oldest=s.oldest;if(s.cursor!==void 0)o.cursor=s.cursor;return ba(await Ie(e,"conversations.replies",o,r))}async function wa(e,t,n){let s=[],r="";do{let o={limit:"200",types:t,exclude_archived:"true"};if(r)o.cursor=r;let i=await Ie(e,"users.conversations",o,n);s.push(...i.channels??[]),r=i.response_metadata?.next_cursor??""}while(r);return s}async function Vr(e,t,n,s,r){let o={channel:t,timestamp:n,name:s};try{await Bs(e,"reactions.add",o,r)}catch(i){if(!e.startsWith("xoxb-")||!t.startsWith("C")||!(i instanceof Error)||i.message!=="Slack error on reactions.add: not_in_channel")throw i;try{await Bs(e,"conversations.join",{channel:t},r)}catch(a){throw Error(`Could not join channel to add reaction: ${a instanceof Error?a.message:String(a)}
127
+ Invite the bot to the channel, or grant channels:join for public channels.`)}await Bs(e,"reactions.add",o,r)}}async function of(e,t,n,s){return((await Ie(e,"reactions.get",{channel:t,timestamp:n,full:"true"},s)).message?.reactions??[]).map((o)=>({name:String(o.name??""),users:Array.isArray(o.users)?o.users.map(String):[]}))}async function Zr(e,t,n,s,r){await Bs(e,"reactions.remove",{channel:t,timestamp:n,name:s},r)}async function ow(e,t,n){let r=(await Bs(e,"conversations.open",{users:t},n)).channel?.id;if(!r)throw Error(`Failed to open DM with user ${t}`);return r}async function af(e,t,n){let s="";while(!0){let r={types:"im",limit:"200"};if(s)r.cursor=s;let o=await Ie(e,"conversations.list",r,n);for(let i of o.channels??[])if(i.user===t)return String(i.id??"");if(s=o.response_metadata?.next_cursor??"",!s)break}return""}async function pa(e,t,n,s){let r=await af(e,t,n);if(r)return r;let o=s?`${s} (${t})`:t;throw Error(`No existing DM with ${o}. Open it once in Slack first.`)}function js(e){return e.toLowerCase().replace(/[-_\s]/g,"")}function zd(e,t){let n=js(e.name??""),s=js(e.real_name??e.profile?.real_name??""),r=js(e.profile?.display_name??"");return n===t||s===t||!!r&&r===t}var cf=200;async function iw(e,t,n){let s=0,r=new Set,o="";while(!0){let f={limit:"200"};if(o)f.cursor=o;let p=await Ie(e,"users.list",f,n);for(let g of p.members??[]){if(s++,g.id)r.add(g.id);if(zd(g,t))return{id:g.id??"",workspaceCount:s,connectCount:0,skipped:0,capped:!1}}if(o=p.response_metadata?.next_cursor??"",!o)break}let i=0,a=0,c=!1,d="";while(!0){let f={types:"im",limit:"200"};if(d)f.cursor=d;let p=await Ie(e,"conversations.list",f,n);for(let g of p.channels??[]){let y=g.user;if(!y||r.has(y))continue;if(i>=cf){c=!0;break}r.add(y),i++;let k;try{k=(await Ie(e,"users.info",{user:y},n)).user}catch(w){if(w instanceof ze)throw w;a++;continue}if(k&&zd(k,t))return{id:y,dm:String(g.id??""),workspaceCount:s,connectCount:i,skipped:a,capped:c}}if(c)break;if(d=p.response_metadata?.next_cursor??"",!d)break}return{id:"",workspaceCount:s,connectCount:i,skipped:a,capped:c}}function aw(e,t){if(t.workspaceCount===0)return Error(`Cannot resolve ${e}: users.list returned no members at all, so nothing could have matched.
127
128
  `+`That is a token or scope fault, not a wrong handle — this says nothing about whether ${e} exists.
128
- 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)`,s=[];if(t.capped)s.push(`stopped after ${Md} Slack Connect DM partners, so there may be more`);if(t.skipped)s.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.
129
+ 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)`,s=[];if(t.capped)s.push(`stopped after ${cf} Slack Connect DM partners, so there may be more`);if(t.skipped)s.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.
129
130
  `+(s.length?`This search was incomplete: ${s.join("; ")}.
130
131
  `:"")+`Slack Connect people from another workspace are not in users.list, so if they never
131
132
  DMed you they cannot be found by name at all. Look them up and use their ID:
132
- slack user ls --external`)}function la(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],s=t[2]&&t[3]?`${t[2]}.${t[3]}`:void 0,r=e.indexOf("?"),o=r>=0?new URLSearchParams(e.slice(r)):void 0,i=o?.get("thread_ts")??void 0,f={channel:o?.get("cid")??void 0??n};if(s)f.ts=s;if(i)f.threadTs=i;return f}function Ab(e){return la(e)?.channel}function Ad(e){return/^[CDG][A-Z0-9]{8,}$/.test(e)}function Td(e){return/^[UW][A-Z0-9]{6,}$/.test(e)}async function Kr(e,t,n){let s=Ab(t);if(s)return s;if(!t.startsWith("@")&&!t.startsWith("#")){if(Ad(t))return t;if(Td(t))return na(e,t,n);throw Error(`Target must start with # or @ (or be a Slack URL/ID), got: ${t}`)}if(t.startsWith("#")&&Ad(t.slice(1)))return t.slice(1);let r=t.startsWith("@"),o=t.slice(1),i=vs(o);if(r){if(Td(o))return na(e,o,n);let f=await Te(e,"auth.test",{},n);if(i==="you"||i==="me"||vs(f.user??"")===i){let d=f.user_id;if(!d)throw Error("auth.test did not return user_id");return await Nd(e,d,n)||Eb(e,d,n)}let c=await $b(e,i,n);if(!c.id)throw Cb(t,c);if(c.dm)return c.dm;return na(e,c.id,n,t)}let l=o.toLowerCase(),u="";while(!0){let f={limit:"200",types:"public_channel,private_channel",exclude_archived:"true"};if(u)f.cursor=u;let a=await Te(e,"conversations.list",f,n);for(let c of a.channels??[])if(String(c.name??"").toLowerCase()===l)return String(c.id??"");if(u=a.response_metadata?.next_cursor??"",!u)break}throw Error(`channel not found: ${t}`)}async function qr(e,t,n){try{let s=await Te(e,"users.info",{user:t},n),r=s.user?.profile?.display_name,o=r&&r.length>0?r:s.user?.real_name??s.user?.name??t,i=s.user?.name??t;return[o,i]}catch{return[t,t]}}async function ss(e,t,n){try{let s=await Te(e,"users.info",{user:t},n),r=s.user?.profile?.display_name;if(r&&r.length>0)return r;return s.user?.real_name??s.user?.name??t}catch{return t}}async function Hr(e,t){let n=[],s="";while(!0){let r={limit:"200"};if(s)r.cursor=s;let o=await Te(e,"users.list",r,t);if(n.push(...o.members??[]),s=o.response_metadata?.next_cursor??"",!s)break}return{members:n}}async function ua(e,t,n){let s=[],r="";while(!0){let o={channel:t,limit:"200"};if(r)o.cursor=r;let i=await Te(e,"conversations.members",o,n);if(s.push(...i.members??[]),r=i.response_metadata?.next_cursor??"",!r)break}return s}async function da(e,t,n){return Te(e,"users.info",{user:t},n)}async function zr(e,t,n){return Te(e,"conversations.info",{channel:t},n)}async function Bd(e,t){let n=await _b(e,"client.boot",{},t),s=typeof n.url==="string"?n.url:void 0;if(!s){let o=Object.keys(n).join(", ");throw Error(`client.boot did not return a WebSocket URL. Keys: ${o}`)}let r=n.self&&typeof n.self==="object"&&!Array.isArray(n.self)?n.self:{};return{wsUrl:s,selfId:typeof r.id==="string"?r.id:""}}var Tb=["chat:write","im:write"],Fb=["im:history","im:read"];async function Yr(e){let{userId:t,botId:n,team:s,scopes:r}=await Rd(e),o="";if(n)try{o=(await Id(e,n)).appId}catch{o=""}let i=(f)=>r.includes(f),l=Tb.filter((f)=>!i(f)),u=Fb.filter((f)=>!i(f));return{canSend:l.length===0,canReceiveReplies:u.length===0,ok:l.length===0&&u.length===0,botUserId:t,appId:o,team:s,grantedScopes:r,missingSendScopes:l,missingReplyScopes:u}}function jd(e){return["",` Bot user: ${e.botUserId||"(unknown)"}`,` App ID: ${e.appId||"(unknown — bots.info unavailable)"}`,` Granted scopes: ${e.grantedScopes.join(", ")||"(none reported)"}`]}function Gr(e,t=!1){let n=e.appId?`https://api.slack.com/apps/${e.appId}`:"https://api.slack.com/apps";if(e.ok){let r=["✓ 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?r:[...r,...jd(e)]}let s=[];if(!e.canSend)s.push(`⚠ This bot CANNOT send DMs — missing scope(s): ${e.missingSendScopes.join(", ")}.`);else s.push("⚠ This bot can send DMs, but the user's replies will NOT be readable.");return s.push(" Make escalation DMs two-way:"),s.push(` 1. ${n} → App Home → enable "Messages Tab" and check`),s.push(' "Allow users to send Slash commands and messages".'),s.push(` 2. OAuth & Permissions → add Bot Token Scopes: ${[...e.missingSendScopes,...e.missingReplyScopes].join(", ")}`),s.push(" 3. Reinstall the app to apply the new scopes."),t?s:[...s,...jd(e)]}import{createInterface as Ye}from"node:readline/promises";import{join as Da,resolve as nw}from"node:path";import{homedir as sw}from"node:os";import{readdirSync as Ms,readFileSync as Ns,existsSync as st,copyFileSync as ha,mkdtempSync as Kd,rmSync as qd}from"node:fs";import{homedir as Vr,tmpdir as Hd}from"node:os";import{join as ye,dirname as Ib}from"node:path";import{pbkdf2Sync as Xr,createDecipheriv as zd,createHash as vb,timingSafeEqual as Pb}from"node:crypto";import{execSync as Yd,execFileSync as Lb}from"node:child_process";function Ls(e,t){let n=0,s=0,r=t;while(r<e.length){let o=e[r++];if(n+=(o&127)*2**s,(o&128)===0)break;s+=7}return{value:n,pos:r}}function Ob(e){let t=0,n=0,s=0;while(t<e.length){let i=e[t++];if(n+=(i&127)*2**s,(i&128)===0)break;s+=7}let r=Buffer.allocUnsafe(n),o=0;while(t<e.length&&o<n){let i=e[t++],l=i&3;if(l===0){let u=i>>2;if(u>=60){let f=u-59;u=0;for(let a=0;a<f;a++)u+=e[t++]*2**(8*a)}u+=1,e.copy(r,o,t,t+u),t+=u,o+=u}else{let u,f;if(l===1)u=4+(i>>2&7),f=(i>>5&7)*256+e[t++];else if(l===2)u=1+(i>>2),f=e[t]+e[t+1]*256,t+=2;else u=1+(i>>2),f=e[t]+e[t+1]*256+e[t+2]*65536+e[t+3]*16777216,t+=4;let a=o-f;for(let c=0;c<u&&o<n;c++)r[o++]=r[a++]}}return o===n?r:r.subarray(0,o)}function fa(e,t){let n=Ls(e,t),s=Ls(e,n.pos);return{handle:{offset:n.value,size:s.value},pos:s.pos}}function Wd(e,t){let{offset:n,size:s}=t,r=e.subarray(n,n+s);return e[n+s]===1?Ob(r):Buffer.from(r)}function Rb(e){if(e.length<4)return[];let t=e.readUInt32LE(e.length-4),n=e.length-(t+1)*4,s=[],r=0,o=Buffer.alloc(0);while(r<n){let i=Ls(e,r),l=Ls(e,i.pos),u=Ls(e,l.pos);r=u.pos;let f=i.value,a=l.value,c=u.value,d=e.subarray(r,r+a);r+=a;let p=e.subarray(r,r+c);r+=c,o=Buffer.concat([o.subarray(0,f),d]),s.push(p)}return s}function Ud(e){if(e.length<48)return Buffer.alloc(0);try{let t=e.length-48,n=fa(e,t),s=fa(e,n.pos),r=Wd(e,s.handle),o=[];for(let i of Rb(r))try{let{handle:l}=fa(i,0);o.push(Wd(e,l))}catch{}return Buffer.concat(o)}catch{return Buffer.alloc(0)}}function Jd(){let e=process.env.HOME??Vr();if(process.platform==="darwin")return[ye(e,"Library","Application Support","Slack","Local Storage","leveldb")];if(process.platform==="linux")return[ye(e,".config","Slack","Local Storage","leveldb"),ye(e,"snap","slack","current",".config","Slack","Local Storage","leveldb"),ye(e,".var","app","com.slack.Slack","config","Slack","Local Storage","leveldb")];if(process.platform==="win32"){let t=process.env.APPDATA??ye(e,"AppData","Roaming");return[ye(t,"Slack","Local Storage","leveldb")]}throw Error(`Unsupported platform: ${process.platform}`)}function Nb(){let e=process.env.HOME??Vr();if(process.platform==="darwin")return ye(e,"Library","Application Support","Slack","Cookies");return""}function Mb(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),s=e.slice(35),r=zd("aes-128-cbc",t,n);return r.setAutoPadding(!0),Buffer.concat([r.update(s),r.final()]).toString("utf8")}function Bb(){if(process.platform!=="darwin")return;let e=Nb();if(!st(e))return;let t;try{t=Yd('security find-generic-password -w -s "Slack Safe Storage" -a "Slack Key"',{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trimEnd()}catch{return}let n=Xr(t,"saltysalt",1003,16,"sha1");try{let{default:s}=Ds("bun:sqlite"),r=new s(e,{readonly:!0}),o=r.prepare("SELECT encrypted_value FROM cookies WHERE name='d' AND host_key LIKE '%slack%'").get();if(r.close(),!o)return;return Mb(Buffer.from(o.encrypted_value),n)}catch{return}}function Gd(e){if(!st(e))return[];let t=Ms(e).filter((i)=>i.endsWith(".ldb")||i.endsWith(".log"));if(t.length===0)return[];let n=new Map,s=(i)=>{let l=n.get(i);if(l!==void 0)return l;let u="";try{let f=Ns(ye(e,i));u=i.endsWith(".ldb")?Ud(f).toString("latin1")||f.toString("latin1"):f.toString("latin1")}catch{u=""}return n.set(i,u),u},r=new Map;for(let i of t){let l=s(i);for(let u of l.matchAll(/"token":"(xoxc-[^"]+)"/g)){let f=u[1],a=f.split("-")[1]??"";if(!a||f.length<40)continue;let c=Math.max(0,u.index-2000),d=Math.min(l.length,u.index+2000),p=l.slice(c,d),h=p.match(/"url":"(https:\/\/[a-z0-9-]+\.slack\.com\/)"/),g=p.match(/"(?:team_name|name)":"([^"]{2,60})"/),y=r.get(a);if(!y||f.length>y.token.length){let m={token:f,teamId:a},w=h?.[1]??y?.url,k=g?.[1]??y?.teamName;if(w)m.url=w;if(k)m.teamName=k;r.set(a,m)}}}let o=t.map((i)=>s(i).replace(/[^\x20-\x7e]/g," ")).join(" ");for(let i of r.values()){if(i.teamName)continue;let l=o.indexOf(i.teamId);if(l!==-1){let u=Math.max(0,l-500),f=Math.min(o.length,l+500),c=o.slice(u,f).match(/"(?:team_name|name)":"([^"]{2,60})"/);if(c?.[1]){i.teamName=c[1];continue}}if(!i.teamName&&i.url){let u=i.url.match(/https:\/\/([a-z0-9-]+)\.slack\.com\//)?.[1];if(u){let f=o.indexOf(u);if(f!==-1){let a=Math.max(0,f-500),c=Math.min(o.length,f+500),p=o.slice(a,c).match(/"(?:team_name|name)":"([^"]{2,60})"/);if(p?.[1]){i.teamName=p[1];continue}}i.teamName=u.split("-").map((a)=>a.charAt(0).toUpperCase()+a.slice(1)).join(" ")}}}return[...r.values()]}async function ga(e){let t=e??Jd().find(st);if(!t)throw Error(`Slack desktop app LevelDB not found at:
133
- ${Jd().join(`
133
+ slack user ls --external`)}function ka(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],s=t[2]&&t[3]?`${t[2]}.${t[3]}`:void 0,r=e.indexOf("?"),o=r>=0?new URLSearchParams(e.slice(r)):void 0,i=o?.get("thread_ts")??void 0,d={channel:o?.get("cid")??void 0??n};if(s)d.ts=s;if(i)d.threadTs=i;return d}function cw(e){return ka(e)?.channel}function Yd(e){return/^[CDG][A-Z0-9]{8,}$/.test(e)}function Gd(e){return/^[UW][A-Z0-9]{6,}$/.test(e)}async function Qr(e,t,n){let s=cw(t);if(s)return s;if(!t.startsWith("@")&&!t.startsWith("#")){if(Yd(t))return t;if(Gd(t))return pa(e,t,n);throw Error(`Target must start with # or @ (or be a Slack URL/ID), got: ${t}`)}if(t.startsWith("#")&&Yd(t.slice(1)))return t.slice(1);let r=t.startsWith("@"),o=t.slice(1),i=js(o);if(r){if(Gd(o))return pa(e,o,n);let d=await Ie(e,"auth.test",{},n);if(i==="you"||i==="me"||js(d.user??"")===i){let g=d.user_id;if(!g)throw Error("auth.test did not return user_id");return await af(e,g,n)||ow(e,g,n)}let p=await iw(e,i,n);if(!p.id)throw aw(t,p);if(p.dm)return p.dm;return pa(e,p.id,n,t)}let a=o.toLowerCase(),c="";while(!0){let d={limit:"200",types:"public_channel,private_channel",exclude_archived:"true"};if(c)d.cursor=c;let f=await Ie(e,"conversations.list",d,n);for(let p of f.channels??[])if(String(p.name??"").toLowerCase()===a)return String(p.id??"");if(c=f.response_metadata?.next_cursor??"",!c)break}throw Error(`channel not found: ${t}`)}async function eo(e,t,n){try{let s=await Ie(e,"users.info",{user:t},n),r=s.user?.profile?.display_name,o=r&&r.length>0?r:s.user?.real_name??s.user?.name??t,i=s.user?.name??t;return[o,i]}catch{return[t,t]}}async function ls(e,t,n){try{let s=await Ie(e,"users.info",{user:t},n),r=s.user?.profile?.display_name;if(r&&r.length>0)return r;return s.user?.real_name??s.user?.name??t}catch{return t}}async function to(e,t){let n=[],s="";while(!0){let r={limit:"200"};if(s)r.cursor=s;let o=await Ie(e,"users.list",r,t);if(n.push(...o.members??[]),s=o.response_metadata?.next_cursor??"",!s)break}return{members:n}}async function Da(e,t,n){let s=[],r="";while(!0){let o={channel:t,limit:"200"};if(r)o.cursor=r;let i=await Ie(e,"conversations.members",o,n);if(s.push(...i.members??[]),r=i.response_metadata?.next_cursor??"",!r)break}return s}async function xa(e,t,n){return Ie(e,"users.info",{user:t},n)}async function no(e,t,n){return Ie(e,"conversations.info",{channel:t},n)}async function lf(e,t){let n=await tw(e,"client.boot",{},t),s=typeof n.url==="string"?n.url:void 0;if(!s){let o=Object.keys(n).join(", ");throw Error(`client.boot did not return a WebSocket URL. Keys: ${o}`)}let r=n.self&&typeof n.self==="object"&&!Array.isArray(n.self)?n.self:{};return{wsUrl:s,selfId:typeof r.id==="string"?r.id:""}}var lw=["chat:write","im:write"],uw=["im:history","im:read"];async function so(e){let{userId:t,botId:n,team:s,scopes:r}=await tf(e),o="";if(n)try{o=(await nf(e,n)).appId}catch{o=""}let i=(d)=>r.includes(d),a=lw.filter((d)=>!i(d)),c=uw.filter((d)=>!i(d));return{canSend:a.length===0,canReceiveReplies:c.length===0,ok:a.length===0&&c.length===0,botUserId:t,appId:o,team:s,grantedScopes:r,missingSendScopes:a,missingReplyScopes:c}}function uf(e){return["",` Bot user: ${e.botUserId||"(unknown)"}`,` App ID: ${e.appId||"(unknown — bots.info unavailable)"}`,` Granted scopes: ${e.grantedScopes.join(", ")||"(none reported)"}`]}function ro(e,t=!1){let n=e.appId?`https://api.slack.com/apps/${e.appId}`:"https://api.slack.com/apps";if(e.ok){let r=["✓ 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?r:[...r,...uf(e)]}let s=[];if(!e.canSend)s.push(`⚠ This bot CANNOT send DMs — missing scope(s): ${e.missingSendScopes.join(", ")}.`);else s.push("⚠ This bot can send DMs, but the user's replies will NOT be readable.");return s.push(" Make escalation DMs two-way:"),s.push(` 1. ${n} → App Home → enable "Messages Tab" and check`),s.push(' "Allow users to send Slash commands and messages".'),s.push(` 2. OAuth & Permissions → add Bot Token Scopes: ${[...e.missingSendScopes,...e.missingReplyScopes].join(", ")}`),s.push(" 3. Reinstall the app to apply the new scopes."),t?s:[...s,...uf(e)]}import{createInterface as Ge}from"node:readline/promises";import{join as Ia,resolve as Lw}from"node:path";import{homedir as Nw}from"node:os";import{readdirSync as Ks,readFileSync as Js,existsSync as rt,copyFileSync as Ea,mkdtempSync as hf,rmSync as gf}from"node:fs";import{homedir as io,tmpdir as mf}from"node:os";import{join as ye,dirname as pw}from"node:path";import{pbkdf2Sync as oo,createDecipheriv as yf,createHash as hw,timingSafeEqual as gw}from"node:crypto";import{execSync as bf,execFileSync as mw}from"node:child_process";function Us(e,t){let n=0,s=0,r=t;while(r<e.length){let o=e[r++];if(n+=(o&127)*2**s,(o&128)===0)break;s+=7}return{value:n,pos:r}}function dw(e){let t=0,n=0,s=0;while(t<e.length){let i=e[t++];if(n+=(i&127)*2**s,(i&128)===0)break;s+=7}let r=Buffer.allocUnsafe(n),o=0;while(t<e.length&&o<n){let i=e[t++],a=i&3;if(a===0){let c=i>>2;if(c>=60){let d=c-59;c=0;for(let f=0;f<d;f++)c+=e[t++]*2**(8*f)}c+=1,e.copy(r,o,t,t+c),t+=c,o+=c}else{let c,d;if(a===1)c=4+(i>>2&7),d=(i>>5&7)*256+e[t++];else if(a===2)c=1+(i>>2),d=e[t]+e[t+1]*256,t+=2;else c=1+(i>>2),d=e[t]+e[t+1]*256+e[t+2]*65536+e[t+3]*16777216,t+=4;let f=o-d;for(let p=0;p<c&&o<n;p++)r[o++]=r[f++]}}return o===n?r:r.subarray(0,o)}function Sa(e,t){let n=Us(e,t),s=Us(e,n.pos);return{handle:{offset:n.value,size:s.value},pos:s.pos}}function df(e,t){let{offset:n,size:s}=t,r=e.subarray(n,n+s);return e[n+s]===1?dw(r):Buffer.from(r)}function fw(e){if(e.length<4)return[];let t=e.readUInt32LE(e.length-4),n=e.length-(t+1)*4,s=[],r=0,o=Buffer.alloc(0);while(r<n){let i=Us(e,r),a=Us(e,i.pos),c=Us(e,a.pos);r=c.pos;let d=i.value,f=a.value,p=c.value,g=e.subarray(r,r+f);r+=f;let y=e.subarray(r,r+p);r+=p,o=Buffer.concat([o.subarray(0,d),g]),s.push(y)}return s}function ff(e){if(e.length<48)return Buffer.alloc(0);try{let t=e.length-48,n=Sa(e,t),s=Sa(e,n.pos),r=df(e,s.handle),o=[];for(let i of fw(r))try{let{handle:a}=Sa(i,0);o.push(df(e,a))}catch{}return Buffer.concat(o)}catch{return Buffer.alloc(0)}}function pf(){let e=process.env.HOME??io();if(process.platform==="darwin")return[ye(e,"Library","Application Support","Slack","Local Storage","leveldb")];if(process.platform==="linux")return[ye(e,".config","Slack","Local Storage","leveldb"),ye(e,"snap","slack","current",".config","Slack","Local Storage","leveldb"),ye(e,".var","app","com.slack.Slack","config","Slack","Local Storage","leveldb")];if(process.platform==="win32"){let t=process.env.APPDATA??ye(e,"AppData","Roaming");return[ye(t,"Slack","Local Storage","leveldb")]}throw Error(`Unsupported platform: ${process.platform}`)}function yw(){let e=process.env.HOME??io();if(process.platform==="darwin")return ye(e,"Library","Application Support","Slack","Cookies");return""}function bw(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),s=e.slice(35),r=yf("aes-128-cbc",t,n);return r.setAutoPadding(!0),Buffer.concat([r.update(s),r.final()]).toString("utf8")}function ww(){if(process.platform!=="darwin")return;let e=yw();if(!rt(e))return;let t;try{t=bf('security find-generic-password -w -s "Slack Safe Storage" -a "Slack Key"',{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trimEnd()}catch{return}let n=oo(t,"saltysalt",1003,16,"sha1");try{let{default:s}=$e("bun:sqlite"),r=new s(e,{readonly:!0}),o=r.prepare("SELECT encrypted_value FROM cookies WHERE name='d' AND host_key LIKE '%slack%'").get();if(r.close(),!o)return;return bw(Buffer.from(o.encrypted_value),n)}catch{return}}function wf(e){if(!rt(e))return[];let t=Ks(e).filter((i)=>i.endsWith(".ldb")||i.endsWith(".log"));if(t.length===0)return[];let n=new Map,s=(i)=>{let a=n.get(i);if(a!==void 0)return a;let c="";try{let d=Js(ye(e,i));c=i.endsWith(".ldb")?ff(d).toString("latin1")||d.toString("latin1"):d.toString("latin1")}catch{c=""}return n.set(i,c),c},r=new Map;for(let i of t){let a=s(i);for(let c of a.matchAll(/"token":"(xoxc-[^"]+)"/g)){let d=c[1],f=d.split("-")[1]??"";if(!f||d.length<40)continue;let p=Math.max(0,c.index-2000),g=Math.min(a.length,c.index+2000),y=a.slice(p,g),k=y.match(/"url":"(https:\/\/[a-z0-9-]+\.slack\.com\/)"/),w=y.match(/"(?:team_name|name)":"([^"]{2,60})"/),u=r.get(f);if(!u||d.length>u.token.length){let l={token:d,teamId:f},h=k?.[1]??u?.url,m=w?.[1]??u?.teamName;if(h)l.url=h;if(m)l.teamName=m;r.set(f,l)}}}let o=t.map((i)=>s(i).replace(/[^\x20-\x7e]/g," ")).join(" ");for(let i of r.values()){if(i.teamName)continue;let a=o.indexOf(i.teamId);if(a!==-1){let c=Math.max(0,a-500),d=Math.min(o.length,a+500),p=o.slice(c,d).match(/"(?:team_name|name)":"([^"]{2,60})"/);if(p?.[1]){i.teamName=p[1];continue}}if(!i.teamName&&i.url){let c=i.url.match(/https:\/\/([a-z0-9-]+)\.slack\.com\//)?.[1];if(c){let d=o.indexOf(c);if(d!==-1){let f=Math.max(0,d-500),p=Math.min(o.length,d+500),y=o.slice(f,p).match(/"(?:team_name|name)":"([^"]{2,60})"/);if(y?.[1]){i.teamName=y[1];continue}}i.teamName=c.split("-").map((f)=>f.charAt(0).toUpperCase()+f.slice(1)).join(" ")}}}return[...r.values()]}async function $a(e){let t=e??pf().find(rt);if(!t)throw Error(`Slack desktop app LevelDB not found at:
134
+ ${pf().join(`
134
135
  `)}
135
- Is Slack installed and opened at least once?`);let n=Gd(t),s=e?void 0:Bb();if(s)for(let r of n)r.cookie=s;return n}function jb(e,t){try{return JSON.parse(Ns(ye(e,"Local State"),"utf8")).profile?.info_cache?.[t]?.user_name||void 0}catch{return}}function ma(){let e=ya();if(!e||!st(e))return[];let t=["Default",...Ms(e).filter((s)=>s.startsWith("Profile "))],n=[];for(let s of t){let r=ye(e,s,"Local Storage","leveldb"),o=Gd(r);if(o.length===0)continue;let i=jb(e,s);n.push({profileDir:s,...i?{email:i}:{},label:Xd(e,s),sessions:o})}return n}function pa(e,t,n,s=!1){let r=(o,i)=>{try{let l=zd("aes-128-cbc",t,o);l.setAutoPadding(!0);let u=Buffer.concat([l.update(i),l.final()]);if(u.subarray(0,5).toString()==="xoxd-")return u.toString("utf8");if(u.length>=37){let f=vb("sha256").update(n).digest();if(Pb(u.subarray(0,32),f)){let a=u.subarray(32).toString("utf8");if(a.startsWith("xoxd-"))return a}}return}catch{return}};return r(Buffer.alloc(16,32),e.slice(3))??(s&&e.length>=35?r(e.slice(19,35),e.slice(35)):void 0)}function Xd(e,t){let n=(s,r)=>{if(s&&r)return`${s} (${r})`;return s||r||t};try{let r=JSON.parse(Ns(ye(e,"Local State"),"utf8")).profile?.info_cache?.[t];if(r&&(r.name||r.user_name))return n(r.name??"",r.user_name??"")}catch{}try{let r=JSON.parse(Ns(ye(e,t,"Preferences"),"utf8")).profile;return n(r?.name??"",r?.user_name??"")}catch{return t}}function ya(){let e=process.env.HOME??Vr();if(process.platform==="darwin")return ye(e,"Library","Application Support","Google","Chrome");if(process.platform==="linux")return ye(process.env.XDG_CONFIG_HOME??ye(e,".config"),"google-chrome");return""}function Wb(){try{return Lb("secret-tool",["lookup","application","chrome"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trimEnd()||void 0}catch{return}}function Bs(){if(process.platform!=="darwin"&&process.platform!=="linux")return{candidates:[],totalProfiles:0};let e=ya();if(!st(e))return{candidates:[],totalProfiles:0};let t;if(process.platform==="darwin"){let i;try{i=Yd('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=Xr(i,"saltysalt",1003,16,"sha1")}let n=["Default",...Ms(e).filter((i)=>i.startsWith("Profile "))],s=[],r,o=!1;for(let i of n){let l=[ye(e,i,"Network","Cookies"),ye(e,i,"Cookies")].find(st);if(!l)continue;let u=Kd(ye(Hd(),"slack-chrome-cookies-")),f=ye(u,"Cookies");try{if(ha(l,f),st(`${l}-wal`))ha(`${l}-wal`,`${f}-wal`);let{default:a}=Ds("bun:sqlite"),c=new a(f,{readonly:!0}),d;try{d=c.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{c.close()}if(!d)continue;let p=Buffer.from(d.encrypted_value),h=p.subarray(0,3).toString(),g;if(h==="v20")throw Error("Chrome cookie uses unsupported v20 app-bound encryption.");if(process.platform==="linux"){if(!p.length&&d.value?.startsWith("xoxd-"))g=d.value;else if(h==="v10")g=pa(p,Xr("peanuts","saltysalt",1,16,"sha1"),d.host_key);else if(h==="v11"){if(!r){let y=Wb();if(y)r=Xr(y,"saltysalt",1,16,"sha1")}if(r)g=pa(p,r,d.host_key);else o=!0}}else if(h==="v10"&&t)g=pa(p,t,d.host_key,!0);else if(h!=="v10")throw Error("Unknown cookie encryption prefix.");if(g)s.push({profileDir:i,profileName:Xd(e,i),cookie:g})}catch(a){if(a instanceof Error&&(a.message.includes("unsupported v20")||a.message.includes("Unknown cookie")))throw a}finally{qd(u,{recursive:!0,force:!0})}}if(o&&s.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:s,totalProfiles:n.length}}async function ba(){if(process.platform!=="linux")throw Error("Chrome session import is currently supported on Linux only.");let e=ya();if(!st(e))throw Error("Chrome profile directory was not found.");let t=new Map(Bs().candidates.map((r)=>[r.profileDir,r.cookie])),n=new Map,s=["Default",...Ms(e).filter((r)=>r.startsWith("Profile "))];for(let r of s){let o=ye(e,r,"Local Storage","leveldb");if(!st(o))continue;let i;try{i=await ga(o)}catch{continue}for(let l of i){if(n.has(l.teamId))throw Error("More than one Chrome profile has a token for the same workspace. Select one browser profile first.");let u=t.get(r);if(u)l.cookie=u;n.set(l.teamId,l)}}return[...n.values()]}function Ub(){let e=process.env.HOME??Vr();if(process.platform==="darwin")return[ye(e,"Library","Application Support","Firefox","Profiles")];if(process.platform==="linux")return[ye(e,".mozilla","firefox"),ye(e,"snap","firefox","common",".mozilla","firefox"),ye(e,".var","app","org.mozilla.firefox",".mozilla","firefox")];if(process.platform==="win32")return[ye(process.env.APPDATA??ye(e,"AppData","Roaming"),"Mozilla","Firefox","Profiles")];return[]}function Jb(e){let t=ye(e,"profiles.ini"),n=st(t)?t:ye(Ib(e),"profiles.ini"),s={};if(!st(n))return s;try{let r=Ns(n,"utf8"),o="",i="";for(let l of r.split(`
136
- `)){let u=l.trim();if(u.startsWith("[")){o="",i="";continue}let f=u.indexOf("=");if(f===-1)continue;let a=u.slice(0,f).trim().toLowerCase(),c=u.slice(f+1).trim();if(a==="name")o=c;if(a==="path")i=c.split(/[\\/]/).pop()??c;if(o&&i)s[i]=o,o="",i=""}}catch{}return s}function Zr(){let e=[];for(let t of Ub().filter(st)){let n=Jb(t),s;try{s=Ms(t)}catch{continue}for(let r of s){let o=ye(t,r,"cookies.sqlite");if(!st(o))continue;let i=Kd(ye(Hd(),"slack-firefox-cookies-")),l=ye(i,"cookies.sqlite");try{ha(o,l);let{default:u}=Ds("bun:sqlite"),f=new u(l,{readonly:!0}),a=f.prepare("SELECT value FROM moz_cookies WHERE name='d' AND (host='slack.com' OR host LIKE '%.slack.com') LIMIT 1").get();if(f.close(),!a?.value||!a.value.startsWith("xoxd-"))continue;let c=n[r]??r;e.push({profileDir:r,profileName:c,cookie:a.value})}catch{}finally{qd(i,{recursive:!0,force:!0})}}}return e}import{readFileSync as wa,writeFileSync as ka,mkdirSync as Kb,existsSync as js,rmSync as qb}from"node:fs";import{join as dt}from"node:path";import{createDecipheriv as Qr}from"node:crypto";import{spawnSync as Hb}from"node:child_process";var zb=Buffer.from("b31c6e241ac846728da9c1fac4936651cffb944d143ab816276bcc6da0284787","hex"),Yb=Buffer.from("e98f37d7f4e1fa433d19304dc2258042090e2d1d7eea7670d41f738d08729660","hex"),Gb=Buffer.from("ccf8a1cec56605b8517552ba1a2d061c03a29e90274fb2fcf59ba4b75c392390","hex"),Dt="C:\\ProgramData\\slack-hub-abe";function Xb(){let e=process.env.LOCALAPPDATA??dt(process.env.USERPROFILE??"","AppData","Local");return dt(e,"Google","Chrome","User Data")}var Vb=String.raw`try {
136
+ Is Slack installed and opened at least once?`);let n=wf(t),s=e?void 0:ww();if(s)for(let r of n)r.cookie=s;return n}function kw(e,t){try{return JSON.parse(Js(ye(e,"Local State"),"utf8")).profile?.info_cache?.[t]?.user_name||void 0}catch{return}}function Ca(){let e=Aa();if(!e||!rt(e))return[];let t=["Default",...Ks(e).filter((s)=>s.startsWith("Profile "))],n=[];for(let s of t){let r=ye(e,s,"Local Storage","leveldb"),o=wf(r);if(o.length===0)continue;let i=kw(e,s);n.push({profileDir:s,...i?{email:i}:{},label:kf(e,s),sessions:o})}return n}function _a(e,t,n,s=!1){let r=(o,i)=>{try{let a=yf("aes-128-cbc",t,o);a.setAutoPadding(!0);let c=Buffer.concat([a.update(i),a.final()]);if(c.subarray(0,5).toString()==="xoxd-")return c.toString("utf8");if(c.length>=37){let d=hw("sha256").update(n).digest();if(gw(c.subarray(0,32),d)){let f=c.subarray(32).toString("utf8");if(f.startsWith("xoxd-"))return f}}return}catch{return}};return r(Buffer.alloc(16,32),e.slice(3))??(s&&e.length>=35?r(e.slice(19,35),e.slice(35)):void 0)}function kf(e,t){let n=(s,r)=>{if(s&&r)return`${s} (${r})`;return s||r||t};try{let r=JSON.parse(Js(ye(e,"Local State"),"utf8")).profile?.info_cache?.[t];if(r&&(r.name||r.user_name))return n(r.name??"",r.user_name??"")}catch{}try{let r=JSON.parse(Js(ye(e,t,"Preferences"),"utf8")).profile;return n(r?.name??"",r?.user_name??"")}catch{return t}}function Aa(){let e=process.env.HOME??io();if(process.platform==="darwin")return ye(e,"Library","Application Support","Google","Chrome");if(process.platform==="linux")return ye(process.env.XDG_CONFIG_HOME??ye(e,".config"),"google-chrome");return""}function Dw(){try{return mw("secret-tool",["lookup","application","chrome"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trimEnd()||void 0}catch{return}}function qs(){if(process.platform!=="darwin"&&process.platform!=="linux")return{candidates:[],totalProfiles:0};let e=Aa();if(!rt(e))return{candidates:[],totalProfiles:0};let t;if(process.platform==="darwin"){let i;try{i=bf('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=oo(i,"saltysalt",1003,16,"sha1")}let n=["Default",...Ks(e).filter((i)=>i.startsWith("Profile "))],s=[],r,o=!1;for(let i of n){let a=[ye(e,i,"Network","Cookies"),ye(e,i,"Cookies")].find(rt);if(!a)continue;let c=hf(ye(mf(),"slack-chrome-cookies-")),d=ye(c,"Cookies");try{if(Ea(a,d),rt(`${a}-wal`))Ea(`${a}-wal`,`${d}-wal`);let{default:f}=$e("bun:sqlite"),p=new f(d,{readonly:!0}),g;try{g=p.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{p.close()}if(!g)continue;let y=Buffer.from(g.encrypted_value),k=y.subarray(0,3).toString(),w;if(k==="v20")throw Error("Chrome cookie uses unsupported v20 app-bound encryption.");if(process.platform==="linux"){if(!y.length&&g.value?.startsWith("xoxd-"))w=g.value;else if(k==="v10")w=_a(y,oo("peanuts","saltysalt",1,16,"sha1"),g.host_key);else if(k==="v11"){if(!r){let u=Dw();if(u)r=oo(u,"saltysalt",1,16,"sha1")}if(r)w=_a(y,r,g.host_key);else o=!0}}else if(k==="v10"&&t)w=_a(y,t,g.host_key,!0);else if(k!=="v10")throw Error("Unknown cookie encryption prefix.");if(w)s.push({profileDir:i,profileName:kf(e,i),cookie:w})}catch(f){if(f instanceof Error&&(f.message.includes("unsupported v20")||f.message.includes("Unknown cookie")))throw f}finally{gf(c,{recursive:!0,force:!0})}}if(o&&s.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:s,totalProfiles:n.length}}async function Ta(){if(process.platform!=="linux")throw Error("Chrome session import is currently supported on Linux only.");let e=Aa();if(!rt(e))throw Error("Chrome profile directory was not found.");let t=new Map(qs().candidates.map((r)=>[r.profileDir,r.cookie])),n=new Map,s=["Default",...Ks(e).filter((r)=>r.startsWith("Profile "))];for(let r of s){let o=ye(e,r,"Local Storage","leveldb");if(!rt(o))continue;let i;try{i=await $a(o)}catch{continue}for(let a of i){if(n.has(a.teamId))throw Error("More than one Chrome profile has a token for the same workspace. Select one browser profile first.");let c=t.get(r);if(c)a.cookie=c;n.set(a.teamId,a)}}return[...n.values()]}function xw(){let e=process.env.HOME??io();if(process.platform==="darwin")return[ye(e,"Library","Application Support","Firefox","Profiles")];if(process.platform==="linux")return[ye(e,".mozilla","firefox"),ye(e,"snap","firefox","common",".mozilla","firefox"),ye(e,".var","app","org.mozilla.firefox",".mozilla","firefox")];if(process.platform==="win32")return[ye(process.env.APPDATA??ye(e,"AppData","Roaming"),"Mozilla","Firefox","Profiles")];return[]}function Sw(e){let t=ye(e,"profiles.ini"),n=rt(t)?t:ye(pw(e),"profiles.ini"),s={};if(!rt(n))return s;try{let r=Js(n,"utf8"),o="",i="";for(let a of r.split(`
137
+ `)){let c=a.trim();if(c.startsWith("[")){o="",i="";continue}let d=c.indexOf("=");if(d===-1)continue;let f=c.slice(0,d).trim().toLowerCase(),p=c.slice(d+1).trim();if(f==="name")o=p;if(f==="path")i=p.split(/[\\/]/).pop()??p;if(o&&i)s[i]=o,o="",i=""}}catch{}return s}function ao(){let e=[];for(let t of xw().filter(rt)){let n=Sw(t),s;try{s=Ks(t)}catch{continue}for(let r of s){let o=ye(t,r,"cookies.sqlite");if(!rt(o))continue;let i=hf(ye(mf(),"slack-firefox-cookies-")),a=ye(i,"cookies.sqlite");try{Ea(o,a);let{default:c}=$e("bun:sqlite"),d=new c(a,{readonly:!0}),f=d.prepare("SELECT value FROM moz_cookies WHERE name='d' AND (host='slack.com' OR host LIKE '%.slack.com') LIMIT 1").get();if(d.close(),!f?.value||!f.value.startsWith("xoxd-"))continue;let p=n[r]??r;e.push({profileDir:r,profileName:p,cookie:f.value})}catch{}finally{gf(i,{recursive:!0,force:!0})}}}return e}import{readFileSync as Fa,writeFileSync as Oa,mkdirSync as _w,existsSync as Hs,rmSync as Ew}from"node:fs";import{join as ft}from"node:path";import{createDecipheriv as co}from"node:crypto";import{spawnSync as $w}from"node:child_process";var Cw=Buffer.from("b31c6e241ac846728da9c1fac4936651cffb944d143ab816276bcc6da0284787","hex"),Aw=Buffer.from("e98f37d7f4e1fa433d19304dc2258042090e2d1d7eea7670d41f738d08729660","hex"),Tw=Buffer.from("ccf8a1cec56605b8517552ba1a2d061c03a29e90274fb2fcf59ba4b75c392390","hex"),xt="C:\\ProgramData\\slack-hub-abe";function Fw(){let e=process.env.LOCALAPPDATA??ft(process.env.USERPROFILE??"","AppData","Local");return ft(e,"Google","Chrome","User Data")}var Ow=String.raw`try {
137
138
  Add-Type -AssemblyName System.Security
138
139
  $d = [IO.File]::ReadAllBytes('C:\ProgramData\slack-hub-abe\in.bin')
139
140
  $o = [Security.Cryptography.ProtectedData]::Unprotect($d, $null, 'CurrentUser')
140
141
  [IO.File]::WriteAllBytes('C:\ProgramData\slack-hub-abe\sys.bin', $o)
141
142
  } catch { Set-Content 'C:\ProgramData\slack-hub-abe\dpapi.err' ($_.Exception.Message) }
142
- `,Zb=String.raw`try {
143
+ `,Iw=String.raw`try {
143
144
  Add-Type -TypeDefinition @'
144
145
  using System; using System.Runtime.InteropServices;
145
146
  public static class NC {
@@ -155,7 +156,7 @@ public static class NC {
155
156
  '@
156
157
  [IO.File]::WriteAllBytes('C:\ProgramData\slack-hub-abe\cng.bin', [NC]::Dec([IO.File]::ReadAllBytes('C:\ProgramData\slack-hub-abe\eak.bin')))
157
158
  } catch { Set-Content 'C:\ProgramData\slack-hub-abe\cng.err' ($_.Exception.Message) }
158
- `;function Qb(e,t){let n=(s)=>`'${s.replace(/'/g,"''")}'`;return String.raw`
159
+ `;function Rw(e,t){let n=(s)=>`'${s.replace(/'/g,"''")}'`;return String.raw`
159
160
  $ErrorActionPreference = 'Stop'
160
161
  Add-Type -AssemblyName System.Security
161
162
  $work = 'C:\ProgramData\slack-hub-abe'
@@ -221,44 +222,44 @@ icacls "$work\Cookies" /grant "$($u):(R)" | Out-Null
221
222
  if (Test-Path "$work\cng.bin") { icacls "$work\cng.bin" /grant "$($u):(R)" | Out-Null }
222
223
  Write-Host 'OK'
223
224
  try { Stop-Transcript | Out-Null } catch {}
224
- `}function ew(e,t){let s=4+e.readUInt32LE(0)+4,r=e[s];if(r===1||r===2){let o=e.subarray(s+1,s+13),i=e.subarray(s+13,s+45),l=e.subarray(s+45,s+61),u=r===1?Qr("aes-256-gcm",zb,o):Qr("chacha20-poly1305",Yb,o,{authTagLength:16});return u.setAuthTag(l),Buffer.concat([u.update(i),u.final()])}if(r===3){if(!t)throw Error("flag 3 requires the CNG-decrypted key (cng.bin missing)");let o=e.subarray(s+33,s+45),i=e.subarray(s+45,s+77),l=e.subarray(s+77,s+93),u=Buffer.from(t.map((a,c)=>a^Gb[c])),f=Qr("aes-256-gcm",u,o);return f.setAuthTag(l),Buffer.concat([f.update(i),f.final()])}throw Error(`Unsupported app-bound key flag: ${r}`)}function tw(e,t){let n=t.subarray(3,15),s=t.subarray(15,t.length-16),r=t.subarray(t.length-16),o=Qr("aes-256-gcm",e,n);return o.setAuthTag(r),Buffer.concat([o.update(s),o.final()]).subarray(32).toString("utf8")}async function Vd(e){if(process.platform!=="win32")throw Error("Windows-only");let t=Xb();if(!js(dt(t,"Local State")))throw Error(`Chrome Local State not found at ${t}`);Kb(Dt,{recursive:!0});let n=dt(Dt,"extract.ps1");ka(n,Qb(t,e)),ka(dt(Dt,"inner_dpapi.ps1"),Vb),ka(dt(Dt,"inner_cng.ps1"),Zb);let s=`Start-Process powershell -Verb RunAs -Wait -ArgumentList @('-NoProfile','-ExecutionPolicy','Bypass','-WindowStyle','Hidden','-File','${n.replace(/'/g,"''")}')`,r=Hb("powershell",["-NoProfile","-Command",s],{encoding:"utf8",windowsHide:!0});if(r.status!==0&&r.error)throw Error(`Failed to launch elevated helper: ${r.error.message}`);let o=dt(Dt,"out.bin"),i=dt(Dt,"Cookies");if(!js(o)||!js(i)){let l=js(dt(Dt,"log.txt"))?wa(dt(Dt,"log.txt"),"utf8").split(`
225
- `).filter((u)=>u.startsWith("ERROR")).join(" "):"";throw Error(`Elevated extraction did not complete${l?` (${l.trim()})`:" (UAC declined or Chrome build unsupported)"}`)}try{let l=wa(o),u=js(dt(Dt,"cng.bin"))?wa(dt(Dt,"cng.bin")):void 0,f=ew(l,u),{Database:a}=Ds("bun:sqlite"),c=new a(i,{readonly:!0}),d=c.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(c.close(),!d)throw Error("no Slack `d` cookie in that Chrome profile");let p=Buffer.from(d.v);if(p.subarray(0,3).toString()!=="v20")throw Error(`unexpected cookie version ${p.subarray(0,3).toString("latin1")}`);let h=tw(f,p);if(!h.startsWith("xoxd-"))throw Error("decrypted value is not an xoxd- cookie");return h}finally{if(!process.env.SLACK_KEEP_ABE)qb(Dt,{recursive:!0,force:!0})}}var rw=["search:read","channels:history","groups:history","im:history","mpim:history","channels:read","groups:read","im:read","mpim:read","users:read","chat:write","files:write"],ow=["channels:history","groups:history","im:history","mpim:history","channels:read","groups:read","im:read","mpim:read","users:read","chat:write","files:write"];function rs(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function iw(){return JSON.stringify({display_information:{name:"slack-hub"},oauth_config:{scopes:{user:rw}},settings:{org_deploy_enabled:!1,socket_mode_enabled:!1,token_rotation_enabled:!1}},null,2)}function aw(){return JSON.stringify({display_information:{name:"slack-hub"},features:{bot_user:{display_name:"slack-hub",always_online:!1}},oauth_config:{scopes:{bot:ow}},settings:{org_deploy_enabled:!1,socket_mode_enabled:!1,token_rotation_enabled:!1}},null,2)}async function rn(e,t){return(await e.question(t)).trim()}async function Ws(e,t){if(t)return!0;if(!e)return!1;let n=await rn(e,"Read local browser profiles and Slack session cookies? [y/N]: ");return n.toLowerCase()==="y"||n.toLowerCase()==="yes"}async function vn(e,t,n,s){console.error("Verifying token...");let r=await ns(t,s),o=rs(r.team),i;if(n)i=n;else if(e)i=await rn(e,`Workspace name [${o}]: `)||o;else i=o;let l=null;if(e){console.log(""),console.log("Where to save the token?"),console.log(" 1) ./.env.local (current directory) [default]"),console.log(" 2) ./.slack-hub/.env.local (current directory, slack-specific)"),console.log(" 3) ~/.slack-hub/.env.local (global, available everywhere)"),console.log(" 4) profiles.json (multi-workspace: slack auth use)"),console.log("");let u=await rn(e,"Choice [1/2/3/4, Enter=1]: ");if(u==="2")l=Da(process.cwd(),".slack-hub",".env.local");else if(u==="3")l=Da(sw(),".slack-hub",".env.local");else if(u==="4")l=null;else l=Da(process.cwd(),".env.local")}if(l===null)if(Mr(i,{token:t,...r,...s?{cookie:s}:{}}),console.log(`Saved workspace "${i}" to profiles.json: ${r.team} (${r.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 u={SLACK_TOKEN:t};if(s)u.SLACK_COOKIE=s;ea(l,u),console.log(`Saved token to ${l}`),console.log(" SLACK_TOKEN will be picked up automatically in this directory tree.")}return i}async function xa(e,t=!1,n="auto",s=!1){console.error("Scanning Slack desktop app...");let r=await ga();if(r.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"&&r.some((o)=>!o.cookie)&&await Ws(e,t)){let o=[];if(n!=="chrome")for(let i of Zr())o.push({source:"Firefox",profileName:i.profileName,cookie:i.cookie});if(n==="chrome"||n==="all"||n==="auto"&&o.length===0)try{for(let i of Bs().candidates)o.push({source:"Chrome",profileName:i.profileName,cookie:i.cookie})}catch(i){console.error(i instanceof Error?i.message:String(i))}if(o.length===1){for(let i of r)i.cookie??=o[0].cookie;console.log(`Found Slack session cookie in ${o[0].source} profile: ${o[0].profileName}`)}else if(o.length>1)console.log("Multiple browser sessions found. Choose one later with slack auth chrome or slack auth firefox.");if(r.some((i)=>!i.cookie))console.log("Desktop session needs an xoxd cookie on Linux. Run: slack auth chrome or slack auth firefox")}await Sa(r,e,s)}async function Sa(e,t,n=!1){if(e.length===1&&t&&e[0]?.cookie&&!n){let s=e[0],r=s.teamName??s.teamId;console.log(`Found workspace: ${r}${s.cookie?" (+ xoxd cookie)":""}`),await vn(t,s.token,rs(r),s.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 s of e){let r=s.teamName??s.teamId,o=rs(r);Mr(o,{token:s.token,team:r,teamId:s.teamId,url:s.url??"",user:"",...s.cookie?{cookie:s.cookie}:{}}),console.log(`Added workspace "${o}": ${r}${s.cookie?" + xoxd cookie":""}`)}if(console.log(""),e.length===1){let s=rs(e[0].teamName??e[0].teamId);console.log(`Run: slack auth use -g ${s}`)}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 Zd(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 rn(e,"Choice [1/2]: ")==="2"?"bot":"user",s=n==="user"?"xoxp-":"xoxb-",r=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 "${r}" (starts with ${s})`),console.log("");let o=await rn(e,"Paste your token: ");if(!o)console.error("No token provided."),process.exit(1);if(!o.startsWith(s))console.error(`Expected a ${s} token, got: ${o.slice(0,10)}...`),process.exit(1);await vn(e,o)}async function eo(e,t){let n=t==="user"?iw():aw(),s=t==="user"?"User OAuth Token (xoxp-...)":"Bot User OAuth Token (xoxb-...)",r=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 -> ${s}`),console.log("");let o=await rn(e,"Paste your token: ");if(!o)console.error("No token provided."),process.exit(1);if(!o.startsWith(r))console.error(`Expected a ${r} token, got: ${o.slice(0,10)}...`),process.exit(1);await vn(e,o)}async function cw(e,t){let n=ma();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 s=e.profile.token.split("-")[1],r=n.find((o)=>o.sessions.some((i)=>i.teamId===s));if(!r&&t){if(r=n.find((o)=>o.email===t||o.profileDir===t||o.profileDir===`Profile ${t}`),!r)console.error(`Chrome profile "${t}" has no Slack session. Available: ${n.map((o)=>o.email??o.profileDir).join(", ")}`),process.exit(1)}if(!r)if(n.length===1)r=n[0];else if(process.stdin.isTTY){console.log("Multiple Chrome profiles have a Slack session:"),n.forEach((u,f)=>console.log(` ${f+1}) ${u.email??u.label} [${u.profileDir}]`));let o=Ye({input:process.stdin,output:process.stdout}),i=(await o.question(`Choice [1-${n.length}]: `)).trim();o.close();let l=parseInt(i,10)-1;if(isNaN(l)||l<0||l>=n.length)console.error("Invalid choice."),process.exit(1);r=n[l]}else console.error("Multiple Chrome profiles have a Slack session — choose one with --profile:"),n.forEach((o)=>console.error(` slack auth cookie -w ${e.name} --profile "${o.email??o.profileDir}"`)),process.exit(1);console.log(`Using Chrome profile: ${r.email??r.label} [${r.profileDir}]`),console.log("Chrome's cookie is app-bound encrypted; a Windows elevation (UAC) prompt will appear — approve it.");try{return await Vd(r.profileDir)}catch(o){console.error(`
226
- Could not extract the cookie automatically: ${o instanceof Error?o.message:String(o)}`),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-hub/.env.local)"),process.exit(1)}}async function Qd(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=Is();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 o=t.find((i)=>i.current);if(o)n=o.name,console.log(`Using active workspace: ${n}`);else{console.log("Multiple workspaces found. Choose one:"),t.forEach((f,a)=>console.log(` ${a+1}) ${f.name} (${f.profile.team})`));let i=Ye({input:process.stdin,output:process.stdout}),l=(await i.question("Choice: ")).trim();i.close();let u=parseInt(l,10)-1;if(isNaN(u)||u<0||u>=t.length)console.error("Invalid choice."),process.exit(1);n=t[u].name}}let s=t.find((o)=>o.name===n);if(s.profile.token.startsWith("xoxb-")){console.error(`
225
+ `}function vw(e,t){let s=4+e.readUInt32LE(0)+4,r=e[s];if(r===1||r===2){let o=e.subarray(s+1,s+13),i=e.subarray(s+13,s+45),a=e.subarray(s+45,s+61),c=r===1?co("aes-256-gcm",Cw,o):co("chacha20-poly1305",Aw,o,{authTagLength:16});return c.setAuthTag(a),Buffer.concat([c.update(i),c.final()])}if(r===3){if(!t)throw Error("flag 3 requires the CNG-decrypted key (cng.bin missing)");let o=e.subarray(s+33,s+45),i=e.subarray(s+45,s+77),a=e.subarray(s+77,s+93),c=Buffer.from(t.map((f,p)=>f^Tw[p])),d=co("aes-256-gcm",c,o);return d.setAuthTag(a),Buffer.concat([d.update(i),d.final()])}throw Error(`Unsupported app-bound key flag: ${r}`)}function Pw(e,t){let n=t.subarray(3,15),s=t.subarray(15,t.length-16),r=t.subarray(t.length-16),o=co("aes-256-gcm",e,n);return o.setAuthTag(r),Buffer.concat([o.update(s),o.final()]).subarray(32).toString("utf8")}async function Df(e){if(process.platform!=="win32")throw Error("Windows-only");let t=Fw();if(!Hs(ft(t,"Local State")))throw Error(`Chrome Local State not found at ${t}`);_w(xt,{recursive:!0});let n=ft(xt,"extract.ps1");Oa(n,Rw(t,e)),Oa(ft(xt,"inner_dpapi.ps1"),Ow),Oa(ft(xt,"inner_cng.ps1"),Iw);let s=`Start-Process powershell -Verb RunAs -Wait -ArgumentList @('-NoProfile','-ExecutionPolicy','Bypass','-WindowStyle','Hidden','-File','${n.replace(/'/g,"''")}')`,r=$w("powershell",["-NoProfile","-Command",s],{encoding:"utf8",windowsHide:!0});if(r.status!==0&&r.error)throw Error(`Failed to launch elevated helper: ${r.error.message}`);let o=ft(xt,"out.bin"),i=ft(xt,"Cookies");if(!Hs(o)||!Hs(i)){let a=Hs(ft(xt,"log.txt"))?Fa(ft(xt,"log.txt"),"utf8").split(`
226
+ `).filter((c)=>c.startsWith("ERROR")).join(" "):"";throw Error(`Elevated extraction did not complete${a?` (${a.trim()})`:" (UAC declined or Chrome build unsupported)"}`)}try{let a=Fa(o),c=Hs(ft(xt,"cng.bin"))?Fa(ft(xt,"cng.bin")):void 0,d=vw(a,c),{Database:f}=$e("bun:sqlite"),p=new f(i,{readonly:!0}),g=p.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(p.close(),!g)throw Error("no Slack `d` cookie in that Chrome profile");let y=Buffer.from(g.v);if(y.subarray(0,3).toString()!=="v20")throw Error(`unexpected cookie version ${y.subarray(0,3).toString("latin1")}`);let k=Pw(d,y);if(!k.startsWith("xoxd-"))throw Error("decrypted value is not an xoxd- cookie");return k}finally{if(!process.env.SLACK_KEEP_ABE)Ew(xt,{recursive:!0,force:!0})}}var Mw=["search:read","channels:history","groups:history","im:history","mpim:history","channels:read","groups:read","im:read","mpim:read","users:read","chat:write","files:write"],Bw=["channels:history","groups:history","im:history","mpim:history","channels:read","groups:read","im:read","mpim:read","users:read","chat:write","files:write"];function us(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function jw(){return JSON.stringify({display_information:{name:"slack-hub"},oauth_config:{scopes:{user:Mw}},settings:{org_deploy_enabled:!1,socket_mode_enabled:!1,token_rotation_enabled:!1}},null,2)}function Ww(){return JSON.stringify({display_information:{name:"slack-hub"},features:{bot_user:{display_name:"slack-hub",always_online:!1}},oauth_config:{scopes:{bot:Bw}},settings:{org_deploy_enabled:!1,socket_mode_enabled:!1,token_rotation_enabled:!1}},null,2)}async function on(e,t){return(await e.question(t)).trim()}async function zs(e,t){if(t)return!0;if(!e)return!1;let n=await on(e,"Read local browser profiles and Slack session cookies? [y/N]: ");return n.toLowerCase()==="y"||n.toLowerCase()==="yes"}async function Mn(e,t,n,s){console.error("Verifying token...");let r=await cs(t,s),o=us(r.team),i;if(n)i=n;else if(e)i=await on(e,`Workspace name [${o}]: `)||o;else i=o;let a=null;if(e){console.log(""),console.log("Where to save the token?"),console.log(" 1) ./.env.local (current directory) [default]"),console.log(" 2) ./.slack-hub/.env.local (current directory, slack-specific)"),console.log(" 3) ~/.slack-hub/.env.local (global, available everywhere)"),console.log(" 4) profiles.json (multi-workspace: slack auth use)"),console.log("");let c=await on(e,"Choice [1/2/3/4, Enter=1]: ");if(c==="2")a=Ia(process.cwd(),".slack-hub",".env.local");else if(c==="3")a=Ia(Nw(),".slack-hub",".env.local");else if(c==="4")a=null;else a=Ia(process.cwd(),".env.local")}if(a===null)if(qr(i,{token:t,...r,...s?{cookie:s}:{}}),console.log(`Saved workspace "${i}" to profiles.json: ${r.team} (${r.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 c={SLACK_TOKEN:t};if(s)c.SLACK_COOKIE=s;da(a,c),console.log(`Saved token to ${a}`),console.log(" SLACK_TOKEN will be picked up automatically in this directory tree.")}return i}async function Ra(e,t=!1,n="auto",s=!1){console.error("Scanning Slack desktop app...");let r=await $a();if(r.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"&&r.some((o)=>!o.cookie)&&await zs(e,t)){let o=[];if(n!=="chrome")for(let i of ao())o.push({source:"Firefox",profileName:i.profileName,cookie:i.cookie});if(n==="chrome"||n==="all"||n==="auto"&&o.length===0)try{for(let i of qs().candidates)o.push({source:"Chrome",profileName:i.profileName,cookie:i.cookie})}catch(i){console.error(i instanceof Error?i.message:String(i))}if(o.length===1){for(let i of r)i.cookie??=o[0].cookie;console.log(`Found Slack session cookie in ${o[0].source} profile: ${o[0].profileName}`)}else if(o.length>1)console.log("Multiple browser sessions found. Choose one later with slack auth chrome or slack auth firefox.");if(r.some((i)=>!i.cookie))console.log("Desktop session needs an xoxd cookie on Linux. Run: slack auth chrome or slack auth firefox")}await va(r,e,s)}async function va(e,t,n=!1){if(e.length===1&&t&&e[0]?.cookie&&!n){let s=e[0],r=s.teamName??s.teamId;console.log(`Found workspace: ${r}${s.cookie?" (+ xoxd cookie)":""}`),await Mn(t,s.token,us(r),s.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 s of e){let r=s.teamName??s.teamId,o=us(r);qr(o,{token:s.token,team:r,teamId:s.teamId,url:s.url??"",user:"",...s.cookie?{cookie:s.cookie}:{}}),console.log(`Added workspace "${o}": ${r}${s.cookie?" + xoxd cookie":""}`)}if(console.log(""),e.length===1){let s=us(e[0].teamName??e[0].teamId);console.log(`Run: slack auth use -g ${s}`)}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 xf(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 on(e,"Choice [1/2]: ")==="2"?"bot":"user",s=n==="user"?"xoxp-":"xoxb-",r=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 "${r}" (starts with ${s})`),console.log("");let o=await on(e,"Paste your token: ");if(!o)console.error("No token provided."),process.exit(1);if(!o.startsWith(s))console.error(`Expected a ${s} token, got: ${o.slice(0,10)}...`),process.exit(1);await Mn(e,o)}async function lo(e,t){let n=t==="user"?jw():Ww(),s=t==="user"?"User OAuth Token (xoxp-...)":"Bot User OAuth Token (xoxb-...)",r=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 -> ${s}`),console.log("");let o=await on(e,"Paste your token: ");if(!o)console.error("No token provided."),process.exit(1);if(!o.startsWith(r))console.error(`Expected a ${r} token, got: ${o.slice(0,10)}...`),process.exit(1);await Mn(e,o)}async function Uw(e,t){let n=Ca();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 s=e.profile.token.split("-")[1],r=n.find((o)=>o.sessions.some((i)=>i.teamId===s));if(!r&&t){if(r=n.find((o)=>o.email===t||o.profileDir===t||o.profileDir===`Profile ${t}`),!r)console.error(`Chrome profile "${t}" has no Slack session. Available: ${n.map((o)=>o.email??o.profileDir).join(", ")}`),process.exit(1)}if(!r)if(n.length===1)r=n[0];else if(process.stdin.isTTY){console.log("Multiple Chrome profiles have a Slack session:"),n.forEach((c,d)=>console.log(` ${d+1}) ${c.email??c.label} [${c.profileDir}]`));let o=Ge({input:process.stdin,output:process.stdout}),i=(await o.question(`Choice [1-${n.length}]: `)).trim();o.close();let a=parseInt(i,10)-1;if(isNaN(a)||a<0||a>=n.length)console.error("Invalid choice."),process.exit(1);r=n[a]}else console.error("Multiple Chrome profiles have a Slack session — choose one with --profile:"),n.forEach((o)=>console.error(` slack auth cookie -w ${e.name} --profile "${o.email??o.profileDir}"`)),process.exit(1);console.log(`Using Chrome profile: ${r.email??r.label} [${r.profileDir}]`),console.log("Chrome's cookie is app-bound encrypted; a Windows elevation (UAC) prompt will appear — approve it.");try{return await Df(r.profileDir)}catch(o){console.error(`
227
+ Could not extract the cookie automatically: ${o instanceof Error?o.message:String(o)}`),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-hub/.env.local)"),process.exit(1)}}async function Sf(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=Ms();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 o=t.find((i)=>i.current);if(o)n=o.name,console.log(`Using active workspace: ${n}`);else{console.log("Multiple workspaces found. Choose one:"),t.forEach((d,f)=>console.log(` ${f+1}) ${d.name} (${d.profile.team})`));let i=Ge({input:process.stdin,output:process.stdout}),a=(await i.question("Choice: ")).trim();i.close();let c=parseInt(a,10)-1;if(isNaN(c)||c<0||c>=t.length)console.error("Invalid choice."),process.exit(1);n=t[c].name}}let s=t.find((o)=>o.name===n);if(s.profile.token.startsWith("xoxb-")){console.error(`
227
228
  Workspace "${n}" uses a bot token (xoxb-). A Chrome session cookie only
228
229
  `+`augments a user session token (xoxc-) — it has no effect on a bot token, so user-level
229
- `+"actions (tail @user, DMs, listing users) would still fail.");let o=t.filter((i)=>i.profile.token.startsWith("xoxc-")||i.profile.token.startsWith("xoxp-"));if(o.length>0)console.error(` Target a user-token workspace instead: ${o.map((i)=>i.name).join(", ")}`),console.error(` slack auth chrome -w ${o[0].name}`);else console.error(" Import your Slack desktop user session instead: slack auth login");process.exit(1)}let r;if(process.platform==="win32")r=await cw(s,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 o=e.yes?void 0:Ye({input:process.stdin,output:process.stdout});try{if(!await Ws(o,e.yes??!1)){console.log("Browser profile scan cancelled.");return}}finally{o?.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,l;try{({candidates:i,totalProfiles:l}=Bs())}catch(u){console.error(`Failed: ${u instanceof Error?u.message:String(u)}`),process.exit(1)}if(i.length===0)console.error(`No Slack session found in Chrome (scanned ${l} profile${l!==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&&l<=1)r=i[0].cookie,console.log(`Found session in Chrome profile: ${i[0].profileName}`);else{let u=i.length===1?`Found 1 Slack session across ${l} Chrome profiles:`:`Found ${i.length} Slack sessions across ${l} Chrome profiles:`;console.log(u),i.forEach((p,h)=>console.log(` ${h+1}) ${p.profileName} [${p.profileDir}]`)),console.log("");let f=Ye({input:process.stdin,output:process.stdout}),a=i.length===1?" [Enter=1]":"",c=(await f.question(`Choice [1-${i.length}]${a}: `)).trim();f.close();let d=c===""&&i.length===1?0:parseInt(c,10)-1;if(isNaN(d)||d<0||d>=i.length)console.error("Invalid choice."),process.exit(1);r=i[d].cookie}}ta(n,r),console.log(`Saved xoxd cookie to workspace "${n}".`),console.log("RTM WebSocket mode is now available: slack tail @you")}async function _a(e={}){console.error("Scanning Chrome profiles for Slack sessions...");let t=ma();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 o=e.profile,i=t.find((l)=>l.email===o||l.profileDir===o||l.profileDir===`Profile ${o}`);if(!i)console.error(`Chrome profile "${o}" has no Slack session. Available:`),t.forEach((l)=>console.error(` - ${l.email??l.label} [${l.profileDir}] (${l.sessions.length} workspace${l.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((u,f)=>console.log(` ${f+1}) ${u.email??u.label} [${u.profileDir}] (${u.sessions.length} workspace${u.sessions.length!==1?"s":""})`));let o=Ye({input:process.stdin,output:process.stdout}),i=(await o.question(`Choice [1-${t.length}]: `)).trim();o.close();let l=parseInt(i,10)-1;if(isNaN(l)||l<0||l>=t.length)console.error("Invalid choice."),process.exit(1);n=t[l]}else console.error("Multiple Chrome profiles have a Slack session — choose one with --profile:"),t.forEach((o)=>console.error(` slack auth login chrome --profile "${o.email??o.profileDir}"`)),process.exit(1);let s=n.email??n.label??n.profileDir,r;if(process.platform==="darwin")try{let{candidates:o}=Bs();r=o.find((i)=>i.profileDir===n.profileDir)?.cookie??o[0]?.cookie}catch{}if(r)_d(s,r,`chrome:${n.profileDir}`);for(let o of n.sessions){let i=o.teamName??o.teamId,l=rs(i);Mr(l,{token:o.token,team:i,teamId:o.teamId,url:o.url??"",user:"",identity:s}),console.log(`Added workspace "${l}": ${i} (identity: ${s})`)}if(console.log(""),r)console.log(`Captured xoxd cookie for ${s} — 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 ${rs(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 Ea(e={}){let t=Is();if(t.length===0)console.error("No workspaces configured. Run: slack auth login"),process.exit(1);let n;if(e.workspace){if(!t.find((l)=>l.name===e.workspace))console.error(`Workspace "${e.workspace}" not found. Available: ${t.map((l)=>l.name).join(", ")}`),process.exit(1);n=e.workspace}else if(t.length===1)n=t[0].name;else{let i=t.find((l)=>l.current);if(i)n=i.name,console.log(`Using active workspace: ${n}`);else{console.log("Multiple workspaces found. Choose one:"),t.forEach((a,c)=>console.log(` ${c+1}) ${a.name} (${a.profile.team})`));let l=Ye({input:process.stdin,output:process.stdout}),u=(await l.question("Choice: ")).trim();l.close();let f=parseInt(u,10)-1;if(isNaN(f)||f<0||f>=t.length)console.error("Invalid choice."),process.exit(1);n=t[f].name}}if(!e.yes&&!process.stdin.isTTY)console.error("Reading browser profiles requires confirmation. Re-run interactively or pass --yes."),process.exit(1);let s=e.yes?void 0:Ye({input:process.stdin,output:process.stdout});try{if(!await Ws(s,e.yes??!1)){console.log("Browser profile scan cancelled.");return}}finally{s?.close()}console.log("Scanning Firefox profiles for Slack session...");let r=Zr();if(r.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 o;if(r.length===1)o=r[0].cookie,console.log(`Found session in Firefox profile: ${r[0].profileName}`);else{console.log("Multiple Firefox profiles have a Slack session. Choose one:"),r.forEach((f,a)=>console.log(` ${a+1}) ${f.profileName} [${f.profileDir}]`));let i=Ye({input:process.stdin,output:process.stdout}),l=(await i.question("Choice: ")).trim();i.close();let u=parseInt(l,10)-1;if(isNaN(u)||u<0||u>=r.length)console.error("Invalid choice."),process.exit(1);o=r[u].cookie}ta(n,o),console.log(`Saved xoxd cookie to workspace "${n}".`),console.log("RTM WebSocket mode is now available: slack tail @you")}async function ef(e={}){if(e.token){await vn(null,e.token,e.name);return}if(!process.stdin.isTTY){let n=[];for await(let r of process.stdin)n.push(r);let s=Buffer.concat(n).toString("utf8").trim();if(!s)console.error("No token provided on stdin."),process.exit(1);await vn(null,s,e.name);return}let t=Ye({input:process.stdin,output:process.stdout});try{await Zd(t)}finally{t.close()}}async function tf(e={}){let t=Ye({input:process.stdin,output:process.stdout});try{if(e.bot!==void 0){await eo(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 rn(t,"Choice [1/2, Enter=1]: ");await eo(t,n==="2"?"bot":"user")}finally{t.close()}}function nf(e={}){let t=(r,o)=>{if(/[\r\n]/.test(o))throw Error(`Invalid newline in ${r}.`);return`${r}=${/^[A-Za-z0-9._=-]+$/.test(o)?o:JSON.stringify(o)}`},n=[t("SLACK_TOKEN",Ed(e.workspace))],s=sn(e.workspace);if(s)n.push(t("SLACK_COOKIE",s));if(!e.workspace){let r=Br();if(r)n.push(t("SLACK_BOT_TOKEN",r))}console.log(n.join(`
230
- `))}function sf(e){let t=Is(),n=e.workspace?t.find((r)=>r.name===e.workspace):t.find((r)=>r.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 s=nw(e.envfile);ea(s,{SLACK_TOKEN:n.profile.token,SLACK_COOKIE:n.profile.cookie}),console.log(`Saved token and cookie for workspace "${n.name}" to ${s}`)}async function Us(e={}){let t=Is();if(t.length>0){console.log("Currently logged in:");for(let{name:s,profile:r,current:o}of t)console.log(` ${o?"*":" "} ${s} ${r.team} (${r.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 s=process.stdin.isTTY?Ye({input:process.stdin,output:process.stdout}):void 0;try{if(!await Ws(s,e.yes??!1)){console.log("Browser profile scan cancelled.");return}let r=await ba();if(r.length===0)throw Error("No Slack session token found in Chrome profiles.");await Sa(r,s,!0)}finally{s?.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 s=process.stdin.isTTY?Ye({input:process.stdin,output:process.stdout}):void 0;try{try{await xa(s,e.yes??!1,"all",!0)}catch(r){if(!(r instanceof Error)||!r.message.startsWith("Slack desktop app LevelDB not found"))throw r;if(!await Ws(s,e.yes??!1)){console.log("Browser profile scan cancelled.");return}let o=await ba();if(o.length===0)throw Error("No Slack session token found in Chrome profiles.");if(o.every((i)=>!i.cookie)){let i=Zr();if(i.length===1)for(let l of o)l.cookie=i[0].cookie}await Sa(o,s,!0)}}finally{s?.close()}return}if(e.fromDesktop||e.fromChrome||e.fromFirefox||e.fromAll){let s=e.fromChrome?"chrome":e.fromFirefox?"firefox":e.fromAll?"all":"none";if(s!=="none"&&!e.yes&&!process.stdin.isTTY)throw Error("Reading browser profiles requires confirmation. Re-run interactively or pass --yes.");let r=process.stdin.isTTY?Ye({input:process.stdin,output:process.stdout}):void 0;try{await xa(r,e.yes??!1,s,!0)}finally{r?.close()}return}if(e.token){await vn(null,e.token,e.name);return}if(!process.stdin.isTTY){let s=[];for await(let o of process.stdin)s.push(o);let r=Buffer.concat(s).toString("utf8").trim();if(!r)console.error("No token provided on stdin."),process.exit(1);await vn(null,r,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=Ye({input:process.stdin,output:process.stdout});try{let s=await rn(n,"Choice [1/2/3/4/5]: ");if(console.log(""),s==="1")await xa(n,e.yes??!1);else if(s==="2"){n.close(),await _a();return}else if(s==="3")await Zd(n);else if(s==="4")await eo(n,"user");else if(s==="5")await eo(n,"bot");else console.error(`Invalid choice: "${s}". Enter 1, 2, 3, 4, or 5.`),process.exit(1)}finally{n.close()}}async function to(e,t,n,s){let r=t,o=[],i=r,l=0;while(!0){let u=i.indexOf("<@U",l);if(u===-1)break;let f=i.slice(u+2),a=f.search(/[>|]/),c=a===-1?f:f.slice(0,a);if(c.length>=9)o.push(c);l=u+1}for(let u of o){if(!n.has(u))n.set(u,await ss(e,u,s));let f=n.get(u)??u;r=r.replaceAll(`<@${u}>`,`@${f}`),r=r.replace(new RegExp(`<@${u}\\|[^>]*>`,"g"),`@${f}`)}return r}function no(e){return e.replace(/<!date\^(\d+)\^[^|>]*(?:\|([^>]*))?>/g,(t,n,s)=>{let r=Number(n);if(!Number.isFinite(r))return s??"date";let o=new Date(r*1000);if(Number.isNaN(o.getTime()))return s??"date";let i=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],l=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],u=i[o.getUTCDay()]??"",f=l[o.getUTCMonth()]??"";return`${u}, ${f} ${String(o.getUTCDate()).padStart(2,"0")}, ${o.getUTCFullYear()}`})}function of(e){let t=typeof e.ts==="string"?e.ts:"",n=typeof e.thread_ts==="string"?e.thread_ts:"";return n!==""&&n!==t}function lw(e){let[t,n="000000"]=e.split("."),s=new Date(Number(t)*1000),r=s.getUTCFullYear(),o=String(s.getUTCMonth()+1).padStart(2,"0"),i=String(s.getUTCDate()).padStart(2,"0"),l=String(s.getUTCHours()).padStart(2,"0"),u=String(s.getUTCMinutes()).padStart(2,"0"),f=String(s.getUTCSeconds()).padStart(2,"0"),a=n.padEnd(6,"0").slice(0,6);return`${r}-${o}-${i}T${l}:${u}:${f}.${a}`}async function uw(e,t,n){let s=typeof t.ts==="string"?t.ts:"0.000000",r=lw(s),o="?";if(typeof t.user==="string"){let c=t.user,d="@"+c;if(!n.has(d)){let[,p]=await qr(e,c);n.set(d,p)}o=n.get(d)??c}else if(typeof t.username==="string")o=t.username;let i=typeof t.text==="string"?t.text:"",u=no(await to(e,i,n)).split(`
231
- `),f=u[0]+(u.length>1?`
232
- `+u.slice(1).map((c)=>` ${c}`).join(`
233
- `):""),a=of(t)?"↳ ":"";return`${r} ${a}@${o}: ${f}`}async function dw(e,t,n,s,r,o,i,l){if(l?.aborted)return;return new Promise((u)=>{let f=new e(n);l?.addEventListener("abort",()=>{f.close(),u()},{once:!0}),f.addEventListener("open",()=>{process.stderr.write(`Connected via RTM (experimental).
234
- `)}),f.addEventListener("close",()=>u()),f.addEventListener("error",()=>u()),f.addEventListener("message",(a)=>{(async()=>{try{let c;try{c=JSON.parse(String(a.data))}catch{return}let d=typeof c.type==="string"?c.type:"";if(d==="ping"){f.send(JSON.stringify({type:"pong",reply_to:c.id??0}));return}if(d!=="message")return;if((typeof c.channel==="string"?c.channel:"")!==s)return;let h=typeof c.ts==="string"?c.ts:"";if(!h||o.has(h))return;let g=typeof c.subtype==="string"?c.subtype:"";if(g==="message_changed"||g==="message_deleted")return;if(r.thread){if((typeof c.thread_ts==="string"?c.thread_ts:h)!==r.thread&&h!==r.thread)return}if(r.watchThread&&of(c)){if((typeof c.thread_ts==="string"?c.thread_ts:"")!==r.watchThread)return}if(r.me&&r.myUserId){if(!(typeof c.text==="string"?c.text:"").includes(`<@${r.myUserId}>`))return}if(o.add(h),o.size>1000){let m=o.values().next().value;if(m!==void 0)o.delete(m)}let y=await uw(t,c,i);process.stdout.write(y+`
235
- `)}catch(c){process.stderr.write(`RTM message error: ${c instanceof Error?c.message:String(c)}
236
- `)}})()})})}var rf=3,fw=2000,$a={sleep:(e)=>new Promise((t)=>setTimeout(t,e)),clientBoot:Bd,getWebSocket:()=>{let e=globalThis.WebSocket;return typeof e==="function"?e:void 0}};async function af(e,t,n,s,r,o,i){let l=$a.getWebSocket();if(!l)return;for(let u=0;u<rf;u++){if(i?.aborted)return;try{let{wsUrl:f}=await $a.clientBoot(e,t);await dw(l,e,f,n,s,r,o,i)}catch{}if(i?.aborted)return;if(u<rf-1)await $a.sleep(fw)}}function on(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 xt={sleep:(e)=>new Promise((t)=>setTimeout(t,e)),now:()=>Date.now(),tailRTM:af};function Mt(e){return e&&typeof e==="object"&&!Array.isArray(e)?e:{}}function Ca(e){return Array.isArray(e)?e:[]}function cf(e){return Number(e)||0}function lf(e){let t=typeof e.ts==="string"?e.ts:"",n=typeof e.thread_ts==="string"?e.thread_ts:"";return n!==""&&n!==t}function pw(e){let[t,n="000000"]=e.split("."),s=new Date(Number(t)*1000),r=s.getUTCFullYear(),o=String(s.getUTCMonth()+1).padStart(2,"0"),i=String(s.getUTCDate()).padStart(2,"0"),l=String(s.getUTCHours()).padStart(2,"0"),u=String(s.getUTCMinutes()).padStart(2,"0"),f=String(s.getUTCSeconds()).padStart(2,"0"),a=n.padEnd(6,"0").slice(0,6);return`${r}-${o}-${i}T${l}:${u}:${f}.${a}`}async function hw(e,t,n,s,r){let o=typeof t.ts==="string"?t.ts:"0.000000",i=pw(o),l="?";if(typeof t.user==="string"){let h=t.user,g="@"+h;if(!n.has(g)){let[,y]=await qr(e,h,r);n.set(g,y)}l=n.get(g)??h}else if(typeof t.username==="string")l=t.username;let u=typeof t.text==="string"?t.text:"",a=no(await to(e,u,n,r)).split(`
237
- `),c=a[0]+(a.length>1?`
238
- `+a.slice(1).map((h)=>` ${h}`).join(`
239
- `):""),d=lf(t)?"↳ ":"",p=s?`${s} @${l}`:`@${l}`;return`${i} ${d}${p}: ${c}`}async function gw(e,t,n,s,r,o,i){let l=Mt(await In(e,t,20,i?void 0:n||void 0,i,s.cookie)),u=Ca(l.messages).map(Mt).reverse(),f=Mt(l.response_metadata),a=l.has_more===!0&&typeof f.next_cursor==="string"?f.next_cursor:void 0,c=[];if(s.watchThread&&!i){let y=Mt(await vd(e,t,s.watchThread,50,s.cookie));c=Ca(y.messages).map(Mt).filter((m)=>(typeof m.ts==="string"?m.ts:"")!==s.watchThread)}let d=[...u.map((y)=>({m:y,fromHistory:!0})),...c.map((y)=>({m:y,fromHistory:!1}))].sort((y,m)=>cf(typeof y.m.ts==="string"?y.m.ts:"")-cf(typeof m.m.ts==="string"?m.m.ts:"")),p=[],h=n,g=!1;for(let{m:y,fromHistory:m}of d){let w=typeof y.ts==="string"?y.ts:"";if(!w||r.has(w))continue;let k=typeof y.subtype==="string"?y.subtype:"";if(k==="message_changed"||k==="message_deleted")continue;if(s.thread){if((typeof y.thread_ts==="string"?y.thread_ts:w)!==s.thread&&w!==s.thread)continue}if(s.watchThread&&lf(y)){if((typeof y.thread_ts==="string"?y.thread_ts:"")!==s.watchThread)continue}if(s.me&&s.myUserId){if(!(typeof y.text==="string"?y.text:"").includes(`<@${s.myUserId}>`))continue}if(r.add(w),r.size>1000){let D=r.values().next().value;if(D!==void 0)r.delete(D)}if(p.push(await hw(e,y,o,void 0,s.cookie)),m)h=w;let _=typeof y.user==="string"?y.user:"";if(!s.myUserId||_!==s.myUserId)g=!0}return{newCursor:h,lines:p,hasMore:l.has_more===!0,nextPageCursor:a,emittedOther:g}}function mw(e){if(e.includes("slack.com")){let t=la(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 uf(e,t,n={},s){if(n.me&&!t)console.error(`slack tail --me requires a <target> channel.
230
+ `+"actions (tail @user, DMs, listing users) would still fail.");let o=t.filter((i)=>i.profile.token.startsWith("xoxc-")||i.profile.token.startsWith("xoxp-"));if(o.length>0)console.error(` Target a user-token workspace instead: ${o.map((i)=>i.name).join(", ")}`),console.error(` slack auth chrome -w ${o[0].name}`);else console.error(" Import your Slack desktop user session instead: slack auth login");process.exit(1)}let r;if(process.platform==="win32")r=await Uw(s,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 o=e.yes?void 0:Ge({input:process.stdin,output:process.stdout});try{if(!await zs(o,e.yes??!1)){console.log("Browser profile scan cancelled.");return}}finally{o?.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,a;try{({candidates:i,totalProfiles:a}=qs())}catch(c){console.error(`Failed: ${c instanceof Error?c.message:String(c)}`),process.exit(1)}if(i.length===0)console.error(`No Slack session found in Chrome (scanned ${a} profile${a!==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&&a<=1)r=i[0].cookie,console.log(`Found session in Chrome profile: ${i[0].profileName}`);else{let c=i.length===1?`Found 1 Slack session across ${a} Chrome profiles:`:`Found ${i.length} Slack sessions across ${a} Chrome profiles:`;console.log(c),i.forEach((y,k)=>console.log(` ${k+1}) ${y.profileName} [${y.profileDir}]`)),console.log("");let d=Ge({input:process.stdin,output:process.stdout}),f=i.length===1?" [Enter=1]":"",p=(await d.question(`Choice [1-${i.length}]${f}: `)).trim();d.close();let g=p===""&&i.length===1?0:parseInt(p,10)-1;if(isNaN(g)||g<0||g>=i.length)console.error("Invalid choice."),process.exit(1);r=i[g].cookie}}fa(n,r),console.log(`Saved xoxd cookie to workspace "${n}".`),console.log("RTM WebSocket mode is now available: slack tail @you")}async function Pa(e={}){console.error("Scanning Chrome profiles for Slack sessions...");let t=Ca();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 o=e.profile,i=t.find((a)=>a.email===o||a.profileDir===o||a.profileDir===`Profile ${o}`);if(!i)console.error(`Chrome profile "${o}" has no Slack session. Available:`),t.forEach((a)=>console.error(` - ${a.email??a.label} [${a.profileDir}] (${a.sessions.length} workspace${a.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((c,d)=>console.log(` ${d+1}) ${c.email??c.label} [${c.profileDir}] (${c.sessions.length} workspace${c.sessions.length!==1?"s":""})`));let o=Ge({input:process.stdin,output:process.stdout}),i=(await o.question(`Choice [1-${t.length}]: `)).trim();o.close();let a=parseInt(i,10)-1;if(isNaN(a)||a<0||a>=t.length)console.error("Invalid choice."),process.exit(1);n=t[a]}else console.error("Multiple Chrome profiles have a Slack session — choose one with --profile:"),t.forEach((o)=>console.error(` slack auth login chrome --profile "${o.email??o.profileDir}"`)),process.exit(1);let s=n.email??n.label??n.profileDir,r;if(process.platform==="darwin")try{let{candidates:o}=qs();r=o.find((i)=>i.profileDir===n.profileDir)?.cookie??o[0]?.cookie}catch{}if(r)Jd(s,r,`chrome:${n.profileDir}`);for(let o of n.sessions){let i=o.teamName??o.teamId,a=us(i);qr(a,{token:o.token,team:i,teamId:o.teamId,url:o.url??"",user:"",identity:s}),console.log(`Added workspace "${a}": ${i} (identity: ${s})`)}if(console.log(""),r)console.log(`Captured xoxd cookie for ${s} — 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 ${us(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 La(e={}){let t=Ms();if(t.length===0)console.error("No workspaces configured. Run: slack auth login"),process.exit(1);let n;if(e.workspace){if(!t.find((a)=>a.name===e.workspace))console.error(`Workspace "${e.workspace}" not found. Available: ${t.map((a)=>a.name).join(", ")}`),process.exit(1);n=e.workspace}else if(t.length===1)n=t[0].name;else{let i=t.find((a)=>a.current);if(i)n=i.name,console.log(`Using active workspace: ${n}`);else{console.log("Multiple workspaces found. Choose one:"),t.forEach((f,p)=>console.log(` ${p+1}) ${f.name} (${f.profile.team})`));let a=Ge({input:process.stdin,output:process.stdout}),c=(await a.question("Choice: ")).trim();a.close();let d=parseInt(c,10)-1;if(isNaN(d)||d<0||d>=t.length)console.error("Invalid choice."),process.exit(1);n=t[d].name}}if(!e.yes&&!process.stdin.isTTY)console.error("Reading browser profiles requires confirmation. Re-run interactively or pass --yes."),process.exit(1);let s=e.yes?void 0:Ge({input:process.stdin,output:process.stdout});try{if(!await zs(s,e.yes??!1)){console.log("Browser profile scan cancelled.");return}}finally{s?.close()}console.log("Scanning Firefox profiles for Slack session...");let r=ao();if(r.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 o;if(r.length===1)o=r[0].cookie,console.log(`Found session in Firefox profile: ${r[0].profileName}`);else{console.log("Multiple Firefox profiles have a Slack session. Choose one:"),r.forEach((d,f)=>console.log(` ${f+1}) ${d.profileName} [${d.profileDir}]`));let i=Ge({input:process.stdin,output:process.stdout}),a=(await i.question("Choice: ")).trim();i.close();let c=parseInt(a,10)-1;if(isNaN(c)||c<0||c>=r.length)console.error("Invalid choice."),process.exit(1);o=r[c].cookie}fa(n,o),console.log(`Saved xoxd cookie to workspace "${n}".`),console.log("RTM WebSocket mode is now available: slack tail @you")}async function _f(e={}){if(e.token){await Mn(null,e.token,e.name);return}if(!process.stdin.isTTY){let n=[];for await(let r of process.stdin)n.push(r);let s=Buffer.concat(n).toString("utf8").trim();if(!s)console.error("No token provided on stdin."),process.exit(1);await Mn(null,s,e.name);return}let t=Ge({input:process.stdin,output:process.stdout});try{await xf(t)}finally{t.close()}}async function Ef(e={}){let t=Ge({input:process.stdin,output:process.stdout});try{if(e.bot!==void 0){await lo(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 on(t,"Choice [1/2, Enter=1]: ");await lo(t,n==="2"?"bot":"user")}finally{t.close()}}function $f(e={}){let t=(r,o)=>{if(/[\r\n]/.test(o))throw Error(`Invalid newline in ${r}.`);return`${r}=${/^[A-Za-z0-9._=-]+$/.test(o)?o:JSON.stringify(o)}`},n=[t("SLACK_TOKEN",Kd(e.workspace))],s=Ot(e.workspace);if(s)n.push(t("SLACK_COOKIE",s));if(!e.workspace){let r=Hr();if(r)n.push(t("SLACK_BOT_TOKEN",r))}console.log(n.join(`
231
+ `))}function Cf(e){let t=Ms(),n=e.workspace?t.find((r)=>r.name===e.workspace):t.find((r)=>r.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 s=Lw(e.envfile);da(s,{SLACK_TOKEN:n.profile.token,SLACK_COOKIE:n.profile.cookie}),console.log(`Saved token and cookie for workspace "${n.name}" to ${s}`)}async function Ys(e={}){let t=Ms();if(t.length>0){console.log("Currently logged in:");for(let{name:s,profile:r,current:o}of t)console.log(` ${o?"*":" "} ${s} ${r.team} (${r.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 s=process.stdin.isTTY?Ge({input:process.stdin,output:process.stdout}):void 0;try{if(!await zs(s,e.yes??!1)){console.log("Browser profile scan cancelled.");return}let r=await Ta();if(r.length===0)throw Error("No Slack session token found in Chrome profiles.");await va(r,s,!0)}finally{s?.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 s=process.stdin.isTTY?Ge({input:process.stdin,output:process.stdout}):void 0;try{try{await Ra(s,e.yes??!1,"all",!0)}catch(r){if(!(r instanceof Error)||!r.message.startsWith("Slack desktop app LevelDB not found"))throw r;if(!await zs(s,e.yes??!1)){console.log("Browser profile scan cancelled.");return}let o=await Ta();if(o.length===0)throw Error("No Slack session token found in Chrome profiles.");if(o.every((i)=>!i.cookie)){let i=ao();if(i.length===1)for(let a of o)a.cookie=i[0].cookie}await va(o,s,!0)}}finally{s?.close()}return}if(e.fromDesktop||e.fromChrome||e.fromFirefox||e.fromAll){let s=e.fromChrome?"chrome":e.fromFirefox?"firefox":e.fromAll?"all":"none";if(s!=="none"&&!e.yes&&!process.stdin.isTTY)throw Error("Reading browser profiles requires confirmation. Re-run interactively or pass --yes.");let r=process.stdin.isTTY?Ge({input:process.stdin,output:process.stdout}):void 0;try{await Ra(r,e.yes??!1,s,!0)}finally{r?.close()}return}if(e.token){await Mn(null,e.token,e.name);return}if(!process.stdin.isTTY){let s=[];for await(let o of process.stdin)s.push(o);let r=Buffer.concat(s).toString("utf8").trim();if(!r)console.error("No token provided on stdin."),process.exit(1);await Mn(null,r,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=Ge({input:process.stdin,output:process.stdout});try{let s=await on(n,"Choice [1/2/3/4/5]: ");if(console.log(""),s==="1")await Ra(n,e.yes??!1);else if(s==="2"){n.close(),await Pa();return}else if(s==="3")await xf(n);else if(s==="4")await lo(n,"user");else if(s==="5")await lo(n,"bot");else console.error(`Invalid choice: "${s}". Enter 1, 2, 3, 4, or 5.`),process.exit(1)}finally{n.close()}}async function uo(e,t,n,s){let r=t,o=[],i=r,a=0;while(!0){let c=i.indexOf("<@U",a);if(c===-1)break;let d=i.slice(c+2),f=d.search(/[>|]/),p=f===-1?d:d.slice(0,f);if(p.length>=9)o.push(p);a=c+1}for(let c of o){if(!n.has(c))n.set(c,await ls(e,c,s));let d=n.get(c)??c;r=r.replaceAll(`<@${c}>`,`@${d}`),r=r.replace(new RegExp(`<@${c}\\|[^>]*>`,"g"),`@${d}`)}return r}function fo(e){return e.replace(/<!date\^(\d+)\^[^|>]*(?:\|([^>]*))?>/g,(t,n,s)=>{let r=Number(n);if(!Number.isFinite(r))return s??"date";let o=new Date(r*1000);if(Number.isNaN(o.getTime()))return s??"date";let i=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],a=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],c=i[o.getUTCDay()]??"",d=a[o.getUTCMonth()]??"";return`${c}, ${d} ${String(o.getUTCDate()).padStart(2,"0")}, ${o.getUTCFullYear()}`})}function Tf(e){let t=typeof e.ts==="string"?e.ts:"",n=typeof e.thread_ts==="string"?e.thread_ts:"";return n!==""&&n!==t}function Jw(e){let[t,n="000000"]=e.split("."),s=new Date(Number(t)*1000),r=s.getUTCFullYear(),o=String(s.getUTCMonth()+1).padStart(2,"0"),i=String(s.getUTCDate()).padStart(2,"0"),a=String(s.getUTCHours()).padStart(2,"0"),c=String(s.getUTCMinutes()).padStart(2,"0"),d=String(s.getUTCSeconds()).padStart(2,"0"),f=n.padEnd(6,"0").slice(0,6);return`${r}-${o}-${i}T${a}:${c}:${d}.${f}`}async function Kw(e,t,n){let s=typeof t.ts==="string"?t.ts:"0.000000",r=Jw(s),o="?";if(typeof t.user==="string"){let p=t.user,g="@"+p;if(!n.has(g)){let[,y]=await eo(e,p);n.set(g,y)}o=n.get(g)??p}else if(typeof t.username==="string")o=t.username;let i=typeof t.text==="string"?t.text:"",c=fo(await uo(e,i,n)).split(`
232
+ `),d=c[0]+(c.length>1?`
233
+ `+c.slice(1).map((p)=>` ${p}`).join(`
234
+ `):""),f=Tf(t)?"↳ ":"";return`${r} ${f}@${o}: ${d}`}async function qw(e,t,n,s,r,o,i,a){if(a?.aborted)return;return new Promise((c)=>{let d=new e(n);a?.addEventListener("abort",()=>{d.close(),c()},{once:!0}),d.addEventListener("open",()=>{process.stderr.write(`Connected via RTM (experimental).
235
+ `)}),d.addEventListener("close",()=>c()),d.addEventListener("error",()=>c()),d.addEventListener("message",(f)=>{(async()=>{try{let p;try{p=JSON.parse(String(f.data))}catch{return}let g=typeof p.type==="string"?p.type:"";if(g==="ping"){d.send(JSON.stringify({type:"pong",reply_to:p.id??0}));return}if(g!=="message")return;if((typeof p.channel==="string"?p.channel:"")!==s)return;let k=typeof p.ts==="string"?p.ts:"";if(!k||o.has(k))return;let w=typeof p.subtype==="string"?p.subtype:"";if(w==="message_changed"||w==="message_deleted")return;if(r.thread){if((typeof p.thread_ts==="string"?p.thread_ts:k)!==r.thread&&k!==r.thread)return}if(r.watchThread&&Tf(p)){if((typeof p.thread_ts==="string"?p.thread_ts:"")!==r.watchThread)return}if(r.me&&r.myUserId){if(!(typeof p.text==="string"?p.text:"").includes(`<@${r.myUserId}>`))return}if(o.add(k),o.size>1000){let l=o.values().next().value;if(l!==void 0)o.delete(l)}let u=await Kw(t,p,i);process.stdout.write(u+`
236
+ `)}catch(p){process.stderr.write(`RTM message error: ${p instanceof Error?p.message:String(p)}
237
+ `)}})()})})}var Af=3,Hw=2000,Na={sleep:(e)=>new Promise((t)=>setTimeout(t,e)),clientBoot:lf,getWebSocket:()=>{let e=globalThis.WebSocket;return typeof e==="function"?e:void 0}};async function Ff(e,t,n,s,r,o,i){let a=Na.getWebSocket();if(!a)return;for(let c=0;c<Af;c++){if(i?.aborted)return;try{let{wsUrl:d}=await Na.clientBoot(e,t);await qw(a,e,d,n,s,r,o,i)}catch{}if(i?.aborted)return;if(c<Af-1)await Na.sleep(Hw)}}function an(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 St={sleep:(e)=>new Promise((t)=>setTimeout(t,e)),now:()=>Date.now(),tailRTM:Ff};function Ut(e){return e&&typeof e==="object"&&!Array.isArray(e)?e:{}}function Ma(e){return Array.isArray(e)?e:[]}function Of(e){return Number(e)||0}function If(e){let t=typeof e.ts==="string"?e.ts:"",n=typeof e.thread_ts==="string"?e.thread_ts:"";return n!==""&&n!==t}function zw(e){let[t,n="000000"]=e.split("."),s=new Date(Number(t)*1000),r=s.getUTCFullYear(),o=String(s.getUTCMonth()+1).padStart(2,"0"),i=String(s.getUTCDate()).padStart(2,"0"),a=String(s.getUTCHours()).padStart(2,"0"),c=String(s.getUTCMinutes()).padStart(2,"0"),d=String(s.getUTCSeconds()).padStart(2,"0"),f=n.padEnd(6,"0").slice(0,6);return`${r}-${o}-${i}T${a}:${c}:${d}.${f}`}async function Yw(e,t,n,s,r){let o=typeof t.ts==="string"?t.ts:"0.000000",i=zw(o),a="?";if(typeof t.user==="string"){let k=t.user,w="@"+k;if(!n.has(w)){let[,u]=await eo(e,k,r);n.set(w,u)}a=n.get(w)??k}else if(typeof t.username==="string")a=t.username;let c=typeof t.text==="string"?t.text:"",f=fo(await uo(e,c,n,r)).split(`
238
+ `),p=f[0]+(f.length>1?`
239
+ `+f.slice(1).map((k)=>` ${k}`).join(`
240
+ `):""),g=If(t)?"↳ ":"",y=s?`${s} @${a}`:`@${a}`;return`${i} ${g}${y}: ${p}`}async function Gw(e,t,n,s,r,o,i){let a=Ut(await Nn(e,t,20,i?void 0:n||void 0,i,s.cookie)),c=Ma(a.messages).map(Ut).reverse(),d=Ut(a.response_metadata),f=a.has_more===!0&&typeof d.next_cursor==="string"?d.next_cursor:void 0,p=[];if(s.watchThread&&!i){let u=Ut(await sf(e,t,s.watchThread,50,s.cookie));p=Ma(u.messages).map(Ut).filter((l)=>(typeof l.ts==="string"?l.ts:"")!==s.watchThread)}let g=[...c.map((u)=>({m:u,fromHistory:!0})),...p.map((u)=>({m:u,fromHistory:!1}))].sort((u,l)=>Of(typeof u.m.ts==="string"?u.m.ts:"")-Of(typeof l.m.ts==="string"?l.m.ts:"")),y=[],k=n,w=!1;for(let{m:u,fromHistory:l}of g){let h=typeof u.ts==="string"?u.ts:"";if(!h||r.has(h))continue;let m=typeof u.subtype==="string"?u.subtype:"";if(m==="message_changed"||m==="message_deleted")continue;if(s.thread){if((typeof u.thread_ts==="string"?u.thread_ts:h)!==s.thread&&h!==s.thread)continue}if(s.watchThread&&If(u)){if((typeof u.thread_ts==="string"?u.thread_ts:"")!==s.watchThread)continue}if(s.me&&s.myUserId){if(!(typeof u.text==="string"?u.text:"").includes(`<@${s.myUserId}>`))continue}if(r.add(h),r.size>1000){let _=r.values().next().value;if(_!==void 0)r.delete(_)}if(y.push(await Yw(e,u,o,void 0,s.cookie)),l)k=h;let b=typeof u.user==="string"?u.user:"";if(!s.myUserId||b!==s.myUserId)w=!0}return{newCursor:k,lines:y,hasMore:a.has_more===!0,nextPageCursor:f,emittedOther:w}}function Xw(e){if(e.includes("slack.com")){let t=ka(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 Rf(e,t,n={},s){if(n.me&&!t)console.error(`slack tail --me requires a <target> channel.
240
241
  Cross-channel mention streaming is not yet supported.
241
- 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 r=await Kr(e,t,n.cookie),o=n.interval??60000,i=n.timeout?xt.now()+on(n.timeout)*1000:1/0,l=new Map,u=new Set;try{let g=Mt(await zr(e,r,n.cookie));if(Mt(g.channel).is_archived===!0)console.error("Warning: this channel is archived — no new messages will arrive.")}catch(g){let y=g instanceof Error?g.message:String(g);if(y.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(y.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(y.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: ${y}`)}let f="";if(n.since){let g=on(n.since);f=(xt.now()/1000-g).toFixed(6)}else{let g=Mt(await In(e,r,1,void 0,void 0,n.cookie)),y=Ca(g.messages).map(Mt);if(y.length>0&&typeof y[0]?.ts==="string")f=y[0].ts,u.add(f);else f=(xt.now()/1000).toFixed(6)}let a;if(n.me||n.exitOnMessage)a=(await ns(e,n.cookie)).userId||void 0;let c;if(n.watchThread!==void 0)try{c=mw(n.watchThread)}catch(g){console.error(g instanceof Error?g.message:String(g)),process.exit(1)}let d={...n.thread!==void 0?{thread:n.thread}:{},...c!==void 0?{watchThread:c}:{},...n.me!==void 0?{me:n.me}:{},...a!==void 0?{myUserId:a}:{},...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 xt.tailRTM(e,n.cookie,r,d,u,l,s),s?.aborted)return;console.error("RTM unavailable — switching to polling.")}let p=!0,h=xt.now();while(!s?.aborted){if(xt.now()>=i)return;let g=!1;try{let w=xt.now()-h,k=o>0&&w>o*5,_,D=!0;do{let{newCursor:E,lines:S,nextPageCursor:x,emittedOther:F}=await gw(e,r,f,d,u,l,_);if(f=E,p&&D&&n.since&&S.length===0)process.stdout.write(`(no messages in the last ${n.since} — watching for new)
242
- `);D=!1;for(let R of S)process.stdout.write(R+`
243
- `);if(F)g=!0;_=k?x:void 0}while(_);p=!1}catch(m){if(m instanceof He){console.error(`Warning: Slack rate limit hit — backing off for ${m.retryAfter}s`),await xt.sleep(m.retryAfter*1000);continue}throw m}if(n.exitOnMessage&&g)return;h=xt.now();let y=i-xt.now();if(y<=0)return;await xt.sleep(Math.min(o,y))}}import{existsSync as yw,mkdirSync as hf,readFileSync as Fa,renameSync as bw,unlinkSync as df,writeFileSync as Oa}from"node:fs";import{dirname as gf}from"node:path";class Aa extends Error{}function ff(e){let t=e,n=(Array.isArray(t.messages)?t.messages:[]).filter((r)=>!!r&&typeof r==="object"&&!Array.isArray(r)),s=t.has_more===!0?t.response_metadata?.next_cursor:void 0;return typeof s==="string"&&s?{messages:n,nextCursor:s}:{messages:n}}function mf(e,t){return{async listChannels(n){let s;if(n){s=[];for(let r of n){let o=await zr(e,r,t),i=o.channel;if(i&&i.is_member!==!1)s.push(o.channel)}}else try{s=await ca(e,"public_channel,private_channel,im,mpim",t)}catch(r){if(!/missing_scope/.test(r instanceof Error?r.message:String(r)))throw r;s=[];let o=[];for(let i of["public_channel","private_channel","im","mpim"])try{s.push(...await ca(e,i,t))}catch(l){if(!/missing_scope/.test(l instanceof Error?l.message:String(l)))throw l;o.push(i)}he.err(`slack stream: no scope to list ${o.join(", ")} — watching the rest`)}return s.flatMap((r)=>{if(!r||typeof r!=="object"||Array.isArray(r)||typeof r.id!=="string")return[];let o=r.is_im===!0;return[{id:r.id,name:ce(r.name)||r.id,isIm:o,...r.is_mpim===!0?{isMpim:!0}:{},...o&&typeof r.user==="string"?{user:r.user}:{}}]})},history:async(n,s,r)=>ff(await In(e,n,200,s,r,t)),replies:async(n,s,r,o)=>ff(await Pd(e,n,s,{oldest:r,...o?{cursor:o}:{}},t)),userName:(n)=>ss(e,n,t)}}var ww="https://github.com/snomiao/slack-hub/blob/main/worker/README.md",kw=1.618,Dw=25,so=2000,xw=8,he={now:()=>Date.now(),sleep:(e,t)=>new Promise((n)=>{if(t?.aborted)return n();let s=()=>{clearTimeout(r),n()},r=setTimeout(()=>{t?.removeEventListener("abort",s),n()},e);t?.addEventListener("abort",s,{once:!0})}),out:(e)=>{process.stdout.write(e+`
242
+ 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 r=await Qr(e,t,n.cookie),o=n.interval??60000,i=n.timeout?St.now()+an(n.timeout)*1000:1/0,a=new Map,c=new Set;try{let w=Ut(await no(e,r,n.cookie));if(Ut(w.channel).is_archived===!0)console.error("Warning: this channel is archived — no new messages will arrive.")}catch(w){let u=w instanceof Error?w.message:String(w);if(u.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(u.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(u.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: ${u}`)}let d="";if(n.since){let w=an(n.since);d=(St.now()/1000-w).toFixed(6)}else{let w=Ut(await Nn(e,r,1,void 0,void 0,n.cookie)),u=Ma(w.messages).map(Ut);if(u.length>0&&typeof u[0]?.ts==="string")d=u[0].ts,c.add(d);else d=(St.now()/1000).toFixed(6)}let f;if(n.me||n.exitOnMessage)f=(await cs(e,n.cookie)).userId||void 0;let p;if(n.watchThread!==void 0)try{p=Xw(n.watchThread)}catch(w){console.error(w instanceof Error?w.message:String(w)),process.exit(1)}let g={...n.thread!==void 0?{thread:n.thread}:{},...p!==void 0?{watchThread:p}:{},...n.me!==void 0?{me:n.me}:{},...f!==void 0?{myUserId:f}:{},...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 St.tailRTM(e,n.cookie,r,g,c,a,s),s?.aborted)return;console.error("RTM unavailable — switching to polling.")}let y=!0,k=St.now();while(!s?.aborted){if(St.now()>=i)return;let w=!1;try{let h=St.now()-k,m=o>0&&h>o*5,b,_=!0;do{let{newCursor:x,lines:S,nextPageCursor:E,emittedOther:I}=await Gw(e,r,d,g,c,a,b);if(d=x,y&&_&&n.since&&S.length===0)process.stdout.write(`(no messages in the last ${n.since} — watching for new)
243
+ `);_=!1;for(let N of S)process.stdout.write(N+`
244
+ `);if(I)w=!0;b=m?E:void 0}while(b);y=!1}catch(l){if(l instanceof ze){console.error(`Warning: Slack rate limit hit — backing off for ${l.retryAfter}s`),await St.sleep(l.retryAfter*1000);continue}throw l}if(n.exitOnMessage&&w)return;k=St.now();let u=i-St.now();if(u<=0)return;await St.sleep(Math.min(o,u))}}import{existsSync as Vw,mkdirSync as Nf,readFileSync as Wa,renameSync as Zw,unlinkSync as vf,writeFileSync as Ua}from"node:fs";import{dirname as Mf}from"node:path";class Ba extends Error{}function Pf(e){let t=e,n=(Array.isArray(t.messages)?t.messages:[]).filter((r)=>!!r&&typeof r==="object"&&!Array.isArray(r)),s=t.has_more===!0?t.response_metadata?.next_cursor:void 0;return typeof s==="string"&&s?{messages:n,nextCursor:s}:{messages:n}}function Bf(e,t){return{async listChannels(n){let s;if(n){s=[];for(let r of n){let o=await no(e,r,t),i=o.channel;if(i&&i.is_member!==!1)s.push(o.channel)}}else try{s=await wa(e,"public_channel,private_channel,im,mpim",t)}catch(r){if(!/missing_scope/.test(r instanceof Error?r.message:String(r)))throw r;s=[];let o=[];for(let i of["public_channel","private_channel","im","mpim"])try{s.push(...await wa(e,i,t))}catch(a){if(!/missing_scope/.test(a instanceof Error?a.message:String(a)))throw a;o.push(i)}he.err(`slack stream: no scope to list ${o.join(", ")} — watching the rest`)}return s.flatMap((r)=>{if(!r||typeof r!=="object"||Array.isArray(r)||typeof r.id!=="string")return[];let o=r.is_im===!0;return[{id:r.id,name:ue(r.name)||r.id,isIm:o,...r.is_mpim===!0?{isMpim:!0}:{},...o&&typeof r.user==="string"?{user:r.user}:{}}]})},history:async(n,s,r)=>Pf(await Nn(e,n,200,s,r,t)),replies:async(n,s,r,o)=>Pf(await rf(e,n,s,{oldest:r,...o?{cursor:o}:{}},t)),userName:(n)=>ls(e,n,t)}}var Qw="https://github.com/snomiao/slack-hub/blob/main/worker/README.md",ek=1.618,tk=25,po=2000,nk=8,he={now:()=>Date.now(),sleep:(e,t)=>new Promise((n)=>{if(t?.aborted)return n();let s=()=>{clearTimeout(r),n()},r=setTimeout(()=>{t?.removeEventListener("abort",s),n()},e);t?.addEventListener("abort",s,{once:!0})}),out:(e)=>{process.stdout.write(e+`
244
245
  `)},err:(e)=>{process.stderr.write(e+`
245
- `)},pidAlive:(e)=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}};function os(e,t,n){return Math.min(n,Math.round(t*Math.pow(kw,Math.max(0,e-1))))}var Sw=["invalid_auth","not_authed","token_revoked","token_expired","account_inactive","no_permission"],_w=["channel_not_found","not_in_channel","missing_scope","is_archived"];class an extends Error{}function Ge(e){return e instanceof Error?e.message:String(e)}function Ta(e){let t=Ge(e);if(Sw.some((n)=>t.includes(n)))return"fatal";if(_w.some((n)=>t.includes(n)))return"channel";return"transient"}var ce=(e)=>typeof e==="string"?e:"",me=(e)=>Number(e)||0,St=(e)=>e.toFixed(6),Ew=new Set(["message_changed","message_deleted","channel_join","channel_leave","group_join","group_leave"]);function $w(e){let t=[ce(e.text)];if(Array.isArray(e.attachments)){for(let n of e.attachments)if(n&&typeof n==="object"&&!Array.isArray(n))t.push(ce(n.pretext),ce(n.text),ce(n.fallback))}return t.filter(Boolean).join(`
246
- `)}function Cw(e,t,n,s){let o=`${e.endsWith("/")?e:e+"/"}archives/${t}/p${n.replace(".","")}`;return s&&s!==n?`${o}?thread_ts=${s}&cid=${t}`:o}function Aw(e,t){if(!yw(e))return{version:1,identity:t,channels:{}};let n;try{n=JSON.parse(Fa(e,"utf8"))}catch(r){throw new an(`state file ${e} is unreadable (${Ge(r)}); move it aside to start fresh`)}if(!(n&&typeof n==="object"&&n.version===1&&n.channels&&typeof n.channels==="object"&&Object.values(n.channels).every((r)=>r&&typeof r.since==="string"&&typeof r.cursor==="string"&&r.threads&&typeof r.threads==="object")))throw new an(`state file ${e} is not a slack stream state; move it aside to start fresh`);if(n.identity!==t)throw new an(`state file ${e} belongs to identity ${n.identity}, not ${t}; pass a different --state`);return n}function Bt(e,t){hf(gf(e),{recursive:!0});let n=`${e}.tmp-${process.pid}`;Oa(n,JSON.stringify(t)),bw(n,e)}function Tw(e){let t=`${e}.lock`;hf(gf(t),{recursive:!0});let n=()=>{try{if(Fa(t,"utf8").trim()===String(process.pid))df(t)}catch{}};try{Oa(t,String(process.pid),{flag:"wx"})}catch{let s=Number(Fa(t,"utf8").trim());if(s&&he.pidAlive(s))throw new an(`another slack stream (pid ${s}) already uses ${e}`);df(t),Oa(t,String(process.pid),{flag:"wx"})}return n}async function pf(e,t){let n=e.names.get(t);if(n===void 0)n=await e.client.userName(t),e.names.set(t,n);return n}async function Ra(e,t,n,s,r){if(Ew.has(ce(n.subtype)))return!1;let o=ce(n.user),i=ce(n.bot_id),l=e.opts.repliesTo,u=ce(n.thread_ts);if(s&&l&&u&&(l.has(o)||l.has(i))){let m=e.state.joined??={};m[`${t.id}:${u}`]=Math.max(m[`${t.id}:${u}`]??0,me(ce(n.ts)))}if(o&&e.opts.selfUsers.has(o)||i&&e.opts.selfBots.has(i))return!1;e.opts.grep.lastIndex=0;let f=e.opts.grep.test($w(n))?"grep":s&&l&&await Fw(e,t,l,n,r)?"replies-to":void 0;if(!f)return!1;let a=ce(n.ts),c=`${t.id}:${a}`;if(e.state.seen?.[c]!==void 0)return!1;if(e.opts.relay&&!e.opts.once)(e.state.seen??={})[c]=me(a);let d=ce(n.thread_ts)||null,p=o||i,h=o?await pf(e,o):ce(n.username)||ce(n.bot_profile?.name)||i,g=t.isIm?`@${t.user?await pf(e,t.user):t.id}`:t.isMpim?t.name:`#${t.name}`,y={type:s?"reply":"message",channel:{id:t.id,name:g},ts:a,thread_ts:d,user:{id:p,name:h},text:ce(n.text).replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&"),permalink:Cw(e.opts.teamUrl,t.id,a,d??void 0),match:f};return e.opts.json?he.out(JSON.stringify(y)):he.out(Ow(y)),e.opts.onMatch?.(y,Array.isArray(n.files)?n.files.length:0),e.matches++,!0}async function Fw(e,t,n,s,r){if(n.has(ce(s.parent_user_id)))return!0;let o=ce(s.thread_ts),i=yf(e,t,n,o,r);if(i!==void 0)return i;let l=`${t.id}:${o}`,u=e.notJoined?.get(l);if(u!==void 0&&u>=me(ce(s.ts)))return!1;let f=u!==void 0?St(u):"0";return Ia(e,t,n,o,await ro((a)=>e.client.replies(t.id,o,f,a))),e.state.joined?.[l]!==void 0}function yf(e,t,n,s,r){if(e.state.joined?.[`${t.id}:${s}`]!==void 0)return!0;if(!r)return;if(n.has(ce(r.user))||n.has(ce(r.bot_id)))return!0;let o=Array.isArray(r.reply_users)?r.reply_users.map((l)=>ce(l)):void 0;if(o?.some((l)=>n.has(l)))return!0;let i=typeof r.reply_users_count==="number"?r.reply_users_count:void 0;if(o&&(i!==void 0?i<=o.length:o.length<5))return!1;return}function Ia(e,t,n,s,r){let o=`${t.id}:${s}`,i=r.filter((u)=>n.has(ce(u.user))||n.has(ce(u.bot_id))).map((u)=>me(ce(u.ts)));if(i.length){let u=e.state.joined??={};u[o]=Math.max(u[o]??0,...i),e.notJoined?.delete(o);return}let l=Math.max(e.notJoined?.get(o)??0,...r.map((u)=>me(ce(u.ts))));(e.notJoined??=new Map).set(o,l)}function Ow(e){let t=new Date(me(e.ts)*1000).toISOString().replace(/\.\d+Z$/,"Z"),n=e.type==="reply"?"↳ ":"",s=e.text.split(`
246
+ `)},pidAlive:(e)=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}};function ds(e,t,n){return Math.min(n,Math.round(t*Math.pow(ek,Math.max(0,e-1))))}var sk=["invalid_auth","not_authed","token_revoked","token_expired","account_inactive","no_permission"],rk=["channel_not_found","not_in_channel","missing_scope","is_archived"];class cn extends Error{}function Xe(e){return e instanceof Error?e.message:String(e)}function ja(e){let t=Xe(e);if(sk.some((n)=>t.includes(n)))return"fatal";if(rk.some((n)=>t.includes(n)))return"channel";return"transient"}var ue=(e)=>typeof e==="string"?e:"",me=(e)=>Number(e)||0,_t=(e)=>e.toFixed(6),ok=new Set(["message_changed","message_deleted","channel_join","channel_leave","group_join","group_leave"]);function ik(e){let t=[ue(e.text)];if(Array.isArray(e.attachments)){for(let n of e.attachments)if(n&&typeof n==="object"&&!Array.isArray(n))t.push(ue(n.pretext),ue(n.text),ue(n.fallback))}return t.filter(Boolean).join(`
247
+ `)}function ak(e,t,n,s){let o=`${e.endsWith("/")?e:e+"/"}archives/${t}/p${n.replace(".","")}`;return s&&s!==n?`${o}?thread_ts=${s}&cid=${t}`:o}function ck(e,t){if(!Vw(e))return{version:1,identity:t,channels:{}};let n;try{n=JSON.parse(Wa(e,"utf8"))}catch(r){throw new cn(`state file ${e} is unreadable (${Xe(r)}); move it aside to start fresh`)}if(!(n&&typeof n==="object"&&n.version===1&&n.channels&&typeof n.channels==="object"&&Object.values(n.channels).every((r)=>r&&typeof r.since==="string"&&typeof r.cursor==="string"&&r.threads&&typeof r.threads==="object")))throw new cn(`state file ${e} is not a slack stream state; move it aside to start fresh`);if(n.identity!==t)throw new cn(`state file ${e} belongs to identity ${n.identity}, not ${t}; pass a different --state`);return n}function Jt(e,t){Nf(Mf(e),{recursive:!0});let n=`${e}.tmp-${process.pid}`;Ua(n,JSON.stringify(t)),Zw(n,e)}function lk(e){let t=`${e}.lock`;Nf(Mf(t),{recursive:!0});let n=()=>{try{if(Wa(t,"utf8").trim()===String(process.pid))vf(t)}catch{}};try{Ua(t,String(process.pid),{flag:"wx"})}catch{let s=Number(Wa(t,"utf8").trim());if(s&&he.pidAlive(s))throw new cn(`another slack stream (pid ${s}) already uses ${e}`);vf(t),Ua(t,String(process.pid),{flag:"wx"})}return n}async function Lf(e,t){let n=e.names.get(t);if(n===void 0)n=await e.client.userName(t),e.names.set(t,n);return n}async function Ja(e,t,n,s,r){if(ok.has(ue(n.subtype)))return!1;let o=ue(n.user),i=ue(n.bot_id),a=e.opts.repliesTo,c=ue(n.thread_ts);if(s&&a&&c&&(a.has(o)||a.has(i))){let l=e.state.joined??={};l[`${t.id}:${c}`]=Math.max(l[`${t.id}:${c}`]??0,me(ue(n.ts)))}if(o&&e.opts.selfUsers.has(o)||i&&e.opts.selfBots.has(i))return!1;e.opts.grep.lastIndex=0;let d=e.opts.grep.test(ik(n))?"grep":s&&a&&await uk(e,t,a,n,r)?"replies-to":void 0;if(!d)return!1;let f=ue(n.ts),p=`${t.id}:${f}`;if(e.state.seen?.[p]!==void 0)return!1;if(e.opts.relay&&!e.opts.once)(e.state.seen??={})[p]=me(f);let g=ue(n.thread_ts)||null,y=o||i,k=o?await Lf(e,o):ue(n.username)||ue(n.bot_profile?.name)||i,w=t.isIm?`@${t.user?await Lf(e,t.user):t.id}`:t.isMpim?t.name:`#${t.name}`,u={type:s?"reply":"message",channel:{id:t.id,name:w},ts:f,thread_ts:g,user:{id:y,name:k},text:ue(n.text).replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&"),permalink:ak(e.opts.teamUrl,t.id,f,g??void 0),match:d};return e.opts.json?he.out(JSON.stringify(u)):he.out(dk(u)),e.opts.onMatch?.(u,Array.isArray(n.files)?n.files.length:0),e.matches++,!0}async function uk(e,t,n,s,r){if(n.has(ue(s.parent_user_id)))return!0;let o=ue(s.thread_ts),i=jf(e,t,n,o,r);if(i!==void 0)return i;let a=`${t.id}:${o}`,c=e.notJoined?.get(a);if(c!==void 0&&c>=me(ue(s.ts)))return!1;let d=c!==void 0?_t(c):"0";return Ka(e,t,n,o,await ho((f)=>e.client.replies(t.id,o,d,f))),e.state.joined?.[a]!==void 0}function jf(e,t,n,s,r){if(e.state.joined?.[`${t.id}:${s}`]!==void 0)return!0;if(!r)return;if(n.has(ue(r.user))||n.has(ue(r.bot_id)))return!0;let o=Array.isArray(r.reply_users)?r.reply_users.map((a)=>ue(a)):void 0;if(o?.some((a)=>n.has(a)))return!0;let i=typeof r.reply_users_count==="number"?r.reply_users_count:void 0;if(o&&(i!==void 0?i<=o.length:o.length<5))return!1;return}function Ka(e,t,n,s,r){let o=`${t.id}:${s}`,i=r.filter((c)=>n.has(ue(c.user))||n.has(ue(c.bot_id))).map((c)=>me(ue(c.ts)));if(i.length){let c=e.state.joined??={};c[o]=Math.max(c[o]??0,...i),e.notJoined?.delete(o);return}let a=Math.max(e.notJoined?.get(o)??0,...r.map((c)=>me(ue(c.ts))));(e.notJoined??=new Map).set(o,a)}function dk(e){let t=new Date(me(e.ts)*1000).toISOString().replace(/\.\d+Z$/,"Z"),n=e.type==="reply"?"↳ ":"",s=e.text.split(`
247
248
  `).join(`
248
249
  `);return`${t} ${e.channel.name} ${n}@${e.user.name}: ${s}
249
- ${e.permalink}`}async function ro(e){let t=[],n;do{let s=await e(n);t.push(...s.messages),n=s.nextCursor}while(n);return t}async function Rw(e,t,n,s=!0){let r=e.state.channels[t.id],o=n-(e.opts.settleSec??5),i=n-e.opts.threadWindowSec,l=me(r.cursor),u=s?Math.min(l,i):l,f=(await ro((d)=>e.client.history(t.id,St(u),d))).sort((d,p)=>me(ce(d.ts))-me(ce(p.ts))),a=e.opts.repliesTo?new Map(f.map((d)=>[ce(d.ts),d])):void 0,c=f.at(-1);if(c&&me(ce(c.ts))>me(r.latest??"0"))r.latest=ce(c.ts);if(s)r.scanned=St(n);for(let d of f){let p=me(ce(d.ts));if(p<=l||p>o)continue;let h=ce(d.thread_ts),g=await Ra(e,t,d,h!==""&&h!==ce(d.ts),h?a?.get(h):void 0);if(r.cursor=ce(d.ts),g)Bt(e.opts.statePath,e.state)}if(me(r.cursor)<o)r.cursor=St(o);for(let d of f){let p=ce(d.ts),h=me(ce(d.latest_reply));if(!h||ce(d.thread_ts)!==p)continue;let g=me(r.threads[p]??r.since);if(h<=g)continue;let y=e.opts.repliesTo,m=y!==void 0&&yf(e,t,y,p,d)===void 0,w=m?Math.min(g,e.notJoined?.get(`${t.id}:${p}`)??0):g,k=(await ro((_)=>e.client.replies(t.id,p,St(w),_))).sort((_,D)=>me(ce(_.ts))-me(ce(D.ts)));if(m)Ia(e,t,y,p,k);for(let _ of k){let D=me(ce(_.ts));if(ce(_.ts)===p||D<=g||D>o)continue;let E=ce(_.subtype)!=="thread_broadcast"&&await Ra(e,t,_,!0,d);if(r.threads[p]=ce(_.ts),E)Bt(e.opts.statePath,e.state)}r.threads[p]=St(Math.max(me(r.threads[p]??"0"),Math.min(h,o)))}for(let d of Object.keys(r.threads))if(me(d)<i)delete r.threads[d];Bt(e.opts.statePath,e.state)}async function Iw(e,t,n){let s,r,o,i=e.opts.repliesTo,l=`${t.id}:${n.thread_ts??""}`;if(i&&n.thread_ts&&e.state.joined?.[l]===void 0){let h=Math.min(e.notJoined?.get(l)??0,me(n.ts)-1),g=await ro((y)=>e.client.replies(t.id,n.thread_ts,St(h),y));if(s=g.find((y)=>ce(y.ts)===n.ts),r=g.find((y)=>ce(y.ts)===n.thread_ts),s)Ia(e,t,i,n.thread_ts,g)}for(let h=0;h<5&&!s;h++){let g=await e.client.replies(t.id,n.thread_ts??n.ts,St(me(n.ts)-1),o);if(s=g.messages.find((y)=>ce(y.ts)===n.ts),r??=n.thread_ts?g.messages.find((y)=>ce(y.ts)===n.thread_ts):void 0,o=g.nextCursor,!o)break}if(!s)return!1;let u=ce(s.thread_ts),f=e.state.channels[t.id],c=u!==""&&u!==n.ts&&ce(s.subtype)!=="thread_broadcast"?f?.threads[u]:f?.cursor;if(c!==void 0&&me(n.ts)<=me(c))return!0;let d=Object.keys(e.state.joined??{}).length;if(await Ra(e,t,s,u!==""&&u!==n.ts,r)||Object.keys(e.state.joined??{}).length!==d)Bt(e.opts.statePath,e.state);return!0}var vw=2592000;function Pw(e,t){if(!e.joined)return;for(let[n,s]of Object.entries(e.joined))if(s<t)delete e.joined[n];if(!Object.keys(e.joined).length)delete e.joined}function Lw(e,t){if(!e.seen)return;for(let[n,s]of Object.entries(e.seen))if(s<t)delete e.seen[n];if(!Object.keys(e.seen).length)delete e.seen}var Nw=10;function Mw(e,t,n){if(!(t>0))return e;let s=60000/t,r=-1/0,o=async()=>{let i=he.now();r=Math.max(r,i);let l=r-i-(Nw-1)*s;if(r+=s,l>0)await he.sleep(l,n)};return{listChannels:(i)=>e.listChannels(i),userName:(i)=>e.userName(i),history:async(i,l,u)=>(await o(),e.history(i,l,u)),replies:async(i,l,u,f)=>(await o(),e.replies(i,l,u,f))}}function Bw(e,t,n,s){let r=n-s.windowSec,o=(d)=>t.channels[d.id],i=(d)=>o(d)?.scanned!==void 0&&me(o(d).latest??"0")<r,l=(d)=>s.once||o(d)?.scanned===void 0||n-me(o(d).scanned)>=s.periodSec,u=new Map,f=e.filter((d)=>!i(d)),a=s.once||s.periodSec<=s.intervalSec?1/0:Math.max(1,Math.ceil(f.length*s.intervalSec/s.periodSec)),c=f.filter(l).sort((d,p)=>me(o(d)?.scanned??"0")-me(o(p)?.scanned??"0")).slice(0,a);for(let d of c)u.set(d.id,"full");for(let d of e){if(u.has(d.id))continue;u.set(d.id,i(d)&&(d.isIm||d.isMpim)&&!l(d)?"skip":"cursor")}return u}async function bf(e,t){let n=t.maxFailures??(t.once?3:12),s=t.backoffBaseMs??2000,r=t.backoffCapMs??300000,o=t.refreshEvery??10,i=t.once?void 0:t.relay;if(!i&&!t.once)he.err(`slack stream: WARNING: polling mode (${t.pollReason??"no relay configured"}) — this is the fallback, `+`not the intended setup: matches arrive up to ${Math.round(t.intervalMs/1000)}s late (replies under older parents up to ${Math.round(Math.max(t.threadScanSec??180,t.intervalMs/1000))}s) and every cycle spends Slack API calls. For real time, set up the relay (slack relay init) and set SLACK_RELAY_URL + SLACK_RELAY_TOKEN: ${ww}`);e=Mw(e,t.callsPerMin??40,t.signal);let l,u=new AbortController,f=()=>u.abort();t.signal?.addEventListener("abort",f,{once:!0});try{l=Tw(t.statePath);let a=Aw(t.statePath,t.identity),c=t.repliesTo?[...t.repliesTo].sort().join(","):void 0;if(a.joinedBy!==c)delete a.joined;if(c)a.joinedBy=c;else delete a.joinedBy;let d={opts:t,client:e,state:a,names:new Map,matches:0},p=new Set,h=[],g=he.now()/1000,y=g,m="",w=0,k=0,_=-1/0,D=0,E=(j)=>{he.err(`slack stream: rate limited — waiting ${j.retryAfter}s`),D=Math.max(D,he.now()+j.retryAfter*1000)},S=async(j)=>{if(h=(await e.listChannels(t.channels)).filter((ue)=>!t.channels||t.channels.includes(ue.id)),t.channels){for(let ue of t.channels)if(!h.some((le)=>le.id===ue))throw new an(`--channel ${ue}: the identity is not a member of it`)}let q=Object.keys(a.channels).length===0;for(let ue of h){if(a.channels[ue.id])continue;let H=Math.min(q||k===0?j:y,t.sinceSec!==void 0?g-t.sinceSec:1/0);a.channels[ue.id]={since:St(H),cursor:St(H),threads:{}}}y=j,Bt(t.statePath,a)};if(t.sinceSec!==void 0)a.channels={},delete a.seen,delete a.relay;let x={queue:[],retry:[],inflight:void 0,onDrain:void 0,handled:0,live:void 0,full:!1},F=new AbortController,R=()=>F.abort(),I=(j,ie="")=>{if(x.live===j)return;x.live=j,he.err(j?`slack stream: relay connected${ie?` (${ie})`:""} — polling every ${Math.round(Math.max(t.intervalMs,i.reconcileMs)/1000)}s as a safety net`:`slack stream: relay unavailable${ie?` (${ie})`:""} — polling every ${Math.round(t.intervalMs/1000)}s`),R()},P=async(j)=>{let ie=t.sinceSec===void 0&&a.relay?.url===j.url?{seq:a.relay.seq,...a.relay.epoch?{epoch:a.relay.epoch}:{}}:{seq:0},q=0,ue=()=>x.queue.length+x.retry.length+(x.inflight?1:0);while(!u.signal.aborted){while(ue()>=so/2&&!u.signal.aborted)await new Promise((X)=>{let te=()=>X();x.onDrain=()=>{u.signal.removeEventListener("abort",te),X()},u.signal.addEventListener("abort",te,{once:!0})});if(u.signal.aborted)return;let le=new AbortController,H=()=>le.abort();u.signal.addEventListener("abort",H,{once:!0});let re=!1,pe="stream closed";try{await j.subscribe(ie,le.signal,{hello:(X)=>{if(q=0,X.gap)x.full=!0;if(X.gap||a.relay?.url!==j.url||a.relay.epoch!==X.epoch){a.relay={url:j.url,seq:X.seq,...X.epoch?{epoch:X.epoch}:{}},x.handled=Math.min(x.handled,X.seq);for(let te of[...x.queue,...x.retry,...x.inflight?[x.inflight]:[]])te.seq=Math.min(te.seq,X.seq)}ie={seq:X.seq,...X.epoch?{epoch:X.epoch}:{}},I(!0,X.via)},bell:(X,te)=>{if(re)return;if(ue()>=so){he.err(`slack stream: relay backlog over ${so} — pausing the relay until it drains`),re=!0,le.abort(),I(!1,"paused while its backlog drains");return}ie={...ie,seq:X},x.queue.push({seq:X,bell:te,tries:0,dueMs:0}),R()}})}catch(X){if(X instanceof Aa){if(x.live)I(!1,Ge(X));x.live=!1,he.err(`slack stream: relay disabled for this run: ${Ge(X)} — check SLACK_RELAY_TOKEN`);return}pe=Ge(X)}finally{u.signal.removeEventListener("abort",H)}if(u.signal.aborted)return;if(re)continue;I(!1,pe),q++,await he.sleep(os(q,2000,60000),u.signal)}};if(i)P(i);let L=async(j)=>{if(t.channels&&!t.channels.includes(j.channel))return!0;if(j.kind==="reaction"){if(!t.reactions||j.self&&t.selfUsers.has(j.self))return!0;if(j.user&&t.selfUsers.has(j.user))return!0;let ue={type:"reaction",channel:{id:j.channel},ts:j.ts,user:{id:j.user??""}};return he.out(t.json?JSON.stringify(ue):`reaction ${j.channel} ${j.ts} by ${j.user??"?"}`),!0}let ie=h.find((ue)=>ue.id===j.channel);if(!ie){if(he.now()/1000-y<60)return!1;await S(he.now()/1000),ie=h.find((ue)=>ue.id===j.channel)}let q=ie&&a.channels[ie.id];if(!ie||!q||p.has(ie.id))return!0;if(me(j.ts)<me(q.since))return!0;if(j.self&&t.selfUsers.has(j.self)){if(t.repliesTo?.has(j.self)&&j.thread_ts){let ue=a.joined??={},le=`${ie.id}:${j.thread_ts}`;ue[le]=Math.max(ue[le]??0,me(j.ts)),d.notJoined?.delete(le),Bt(t.statePath,a)}return!0}return Iw(d,ie,j)},W=()=>{if(!a.relay||a.relay.url!==i?.url)return;let j=[...x.queue,...x.retry,...x.inflight?[x.inflight]:[]].map((ie)=>ie.seq);a.relay.seq=Math.max(0,j.length?Math.min(...j)-1:Math.max(a.relay.seq,x.handled))},N=async()=>{let j=he.now(),ie=x.retry.filter((le)=>le.dueMs<=j);if(ie.length)x.retry=x.retry.filter((le)=>le.dueMs>j),x.queue=[...ie,...x.queue].sort((le,H)=>le.seq-H.seq);let q=0;while(x.queue.length&&q<Dw&&!t.signal?.aborted&&he.now()>=D){let le=x.queue.shift();x.inflight=le,q++;let H,re;try{H=await L(le.bell)}catch(pe){if(pe instanceof He){E(pe),le.dueMs=D,x.retry.push(le),x.inflight=void 0;break}H=!1,re=pe}if(x.inflight=void 0,re!==void 0&&/thread_not_found|message_not_found/.test(Ge(re)))re=void 0;if(re!==void 0&&Ta(re)==="channel")he.err(`slack stream: relay bell for ${le.bell.channel} dropped: ${Ge(re)}`),H=!0;if(re===void 0&&Y)he.err("slack stream: relay bell reads recovered"),Y=!1;if(H)x.handled=Math.max(x.handled,le.seq);else if(re!==void 0){if(le.fails=(le.fails??0)+1,!Y)he.err(`slack stream: relay bell for ${le.bell.channel} failed (${Ge(re)}) — retrying`);Y=!0,le.dueMs=he.now()+os(le.fails,1500,60000),x.retry.push(le)}else if(++le.tries>=xw)he.err(`slack stream: relay bell for ${le.bell.channel} abandoned after ${le.tries} tries (not visible) — only the poll can find it now`),x.handled=Math.max(x.handled,le.seq);else le.dueMs=he.now()+os(le.tries,1500,60000),x.retry.push(le)}if(x.onDrain&&x.queue.length+x.retry.length<so/2)x.onDrain(),x.onDrain=void 0;let ue=a.relay?.seq;if(W(),q||a.relay?.seq!==ue)Bt(t.statePath,a)},J=()=>x.live===!0&&i?Math.max(t.intervalMs,i.reconcileMs):t.intervalMs,K=()=>{let j=he.now();return(j>=_+J()||x.full)&&j>=D},B=()=>x.queue.length>0||x.retry.some((j)=>j.dueMs<=he.now()),z=!1,Y=!1;while(!t.signal?.aborted){if(K()&&!(z&&B())){x.full=!1;let q=he.now()/1000;try{if(k%o===0)await S(q);let ue=Math.max(0,t.threadScanSec??180),le=Bw(h.filter((H)=>!p.has(H.id)),a,q,{windowSec:t.threadWindowSec,periodSec:ue,intervalSec:J()/1000,once:t.once});for(let H of h){if(t.signal?.aborted)break;if(p.has(H.id))continue;let re=le.get(H.id)??"full";if(re==="skip")continue;for(;;)try{let pe=a.channels[H.id],X=re==="cursor"&&pe.scanned!==void 0&&me(pe.latest??"0")<q-t.threadWindowSec&&q-me(pe.scanned)>=ue;if(await Rw(d,H,q,re==="full"),X)pe.scanned=St(q),Bt(t.statePath,a);break}catch(pe){if(pe instanceof He){if(E(pe),await he.sleep(D-he.now(),t.signal),t.signal?.aborted)break;continue}if(Ta(pe)==="channel"){p.add(H.id),m=Ge(pe),he.err(`slack stream: skipping ${H.isIm?H.id:"#"+H.name} (${H.id}): ${Ge(pe)}`);break}throw pe}}if(h.length>0&&h.every((H)=>p.has(H.id)))throw new an(`every channel failed — nothing left to watch (last: ${m})`);if(w>0)he.err(`slack stream: recovered after ${w} failed attempt(s)`);w=0}catch(ue){if(ue instanceof an||Ta(ue)==="fatal")return he.err(`slack stream: fatal: ${Ge(ue)}`),3;if(w++,w>=n)return he.err(`slack stream: giving up after ${w} consecutive failures: ${Ge(ue)}`),3;let le=os(w,s,r);he.err(`slack stream: ${Ge(ue)} — reconnecting in ${(le/1000).toFixed(1)}s (attempt ${w}/${n})`),await he.sleep(le,t.signal),x.full=!0;continue}if(k++,Lw(a,q-t.threadWindowSec-86400),Pw(a,q-vw),t.once){if(Bt(t.statePath,a),d.matches===0)he.err(`slack stream: no matches in ${h.length-p.size} channel(s)`);return d.matches>0?0:2}_=q*1000,z=!0}if(t.signal?.aborted)break;let j=he.now(),ie=Math.max(D,x.queue.length||x.full?j:Math.min(_+J(),...x.retry.map((q)=>q.dueMs)));if(ie>j){F=new AbortController;let q=F,ue=()=>q.abort();t.signal?.addEventListener("abort",ue,{once:!0}),await he.sleep(ie-j,q.signal),t.signal?.removeEventListener("abort",ue)}if(K()&&!(z&&B()))continue;await N(),z=!1}return 0}catch(a){return he.err(`slack stream: fatal: ${Ge(a)}`),3}finally{u.abort(),t.signal?.removeEventListener("abort",f),l?.()}}class wf extends Error{}function jw(e,t){let n;while((n=e.indexOf(`
250
+ ${e.permalink}`}async function ho(e){let t=[],n;do{let s=await e(n);t.push(...s.messages),n=s.nextCursor}while(n);return t}async function fk(e,t,n,s=!0){let r=e.state.channels[t.id],o=n-(e.opts.settleSec??5),i=n-e.opts.threadWindowSec,a=me(r.cursor),c=s?Math.min(a,i):a,d=(await ho((g)=>e.client.history(t.id,_t(c),g))).sort((g,y)=>me(ue(g.ts))-me(ue(y.ts))),f=e.opts.repliesTo?new Map(d.map((g)=>[ue(g.ts),g])):void 0,p=d.at(-1);if(p&&me(ue(p.ts))>me(r.latest??"0"))r.latest=ue(p.ts);if(s)r.scanned=_t(n);for(let g of d){let y=me(ue(g.ts));if(y<=a||y>o)continue;let k=ue(g.thread_ts),w=await Ja(e,t,g,k!==""&&k!==ue(g.ts),k?f?.get(k):void 0);if(r.cursor=ue(g.ts),w)Jt(e.opts.statePath,e.state)}if(me(r.cursor)<o)r.cursor=_t(o);for(let g of d){let y=ue(g.ts),k=me(ue(g.latest_reply));if(!k||ue(g.thread_ts)!==y)continue;let w=me(r.threads[y]??r.since);if(k<=w)continue;let u=e.opts.repliesTo,l=u!==void 0&&jf(e,t,u,y,g)===void 0,h=l?Math.min(w,e.notJoined?.get(`${t.id}:${y}`)??0):w,m=(await ho((b)=>e.client.replies(t.id,y,_t(h),b))).sort((b,_)=>me(ue(b.ts))-me(ue(_.ts)));if(l)Ka(e,t,u,y,m);for(let b of m){let _=me(ue(b.ts));if(ue(b.ts)===y||_<=w||_>o)continue;let x=ue(b.subtype)!=="thread_broadcast"&&await Ja(e,t,b,!0,g);if(r.threads[y]=ue(b.ts),x)Jt(e.opts.statePath,e.state)}r.threads[y]=_t(Math.max(me(r.threads[y]??"0"),Math.min(k,o)))}for(let g of Object.keys(r.threads))if(me(g)<i)delete r.threads[g];Jt(e.opts.statePath,e.state)}async function pk(e,t,n){let s,r,o,i=e.opts.repliesTo,a=`${t.id}:${n.thread_ts??""}`;if(i&&n.thread_ts&&e.state.joined?.[a]===void 0){let k=Math.min(e.notJoined?.get(a)??0,me(n.ts)-1),w=await ho((u)=>e.client.replies(t.id,n.thread_ts,_t(k),u));if(s=w.find((u)=>ue(u.ts)===n.ts),r=w.find((u)=>ue(u.ts)===n.thread_ts),s)Ka(e,t,i,n.thread_ts,w)}for(let k=0;k<5&&!s;k++){let w=await e.client.replies(t.id,n.thread_ts??n.ts,_t(me(n.ts)-1),o);if(s=w.messages.find((u)=>ue(u.ts)===n.ts),r??=n.thread_ts?w.messages.find((u)=>ue(u.ts)===n.thread_ts):void 0,o=w.nextCursor,!o)break}if(!s)return!1;let c=ue(s.thread_ts),d=e.state.channels[t.id],p=c!==""&&c!==n.ts&&ue(s.subtype)!=="thread_broadcast"?d?.threads[c]:d?.cursor;if(p!==void 0&&me(n.ts)<=me(p))return!0;let g=Object.keys(e.state.joined??{}).length;if(await Ja(e,t,s,c!==""&&c!==n.ts,r)||Object.keys(e.state.joined??{}).length!==g)Jt(e.opts.statePath,e.state);return!0}var hk=2592000;function gk(e,t){if(!e.joined)return;for(let[n,s]of Object.entries(e.joined))if(s<t)delete e.joined[n];if(!Object.keys(e.joined).length)delete e.joined}function mk(e,t){if(!e.seen)return;for(let[n,s]of Object.entries(e.seen))if(s<t)delete e.seen[n];if(!Object.keys(e.seen).length)delete e.seen}var yk=10;function bk(e,t,n){if(!(t>0))return e;let s=60000/t,r=-1/0,o=async()=>{let i=he.now();r=Math.max(r,i);let a=r-i-(yk-1)*s;if(r+=s,a>0)await he.sleep(a,n)};return{listChannels:(i)=>e.listChannels(i),userName:(i)=>e.userName(i),history:async(i,a,c)=>(await o(),e.history(i,a,c)),replies:async(i,a,c,d)=>(await o(),e.replies(i,a,c,d))}}function wk(e,t,n,s){let r=n-s.windowSec,o=(g)=>t.channels[g.id],i=(g)=>o(g)?.scanned!==void 0&&me(o(g).latest??"0")<r,a=(g)=>s.once||o(g)?.scanned===void 0||n-me(o(g).scanned)>=s.periodSec,c=new Map,d=e.filter((g)=>!i(g)),f=s.once||s.periodSec<=s.intervalSec?1/0:Math.max(1,Math.ceil(d.length*s.intervalSec/s.periodSec)),p=d.filter(a).sort((g,y)=>me(o(g)?.scanned??"0")-me(o(y)?.scanned??"0")).slice(0,f);for(let g of p)c.set(g.id,"full");for(let g of e){if(c.has(g.id))continue;c.set(g.id,i(g)&&(g.isIm||g.isMpim)&&!a(g)?"skip":"cursor")}return c}async function Wf(e,t){let n=t.maxFailures??(t.once?3:12),s=t.backoffBaseMs??2000,r=t.backoffCapMs??300000,o=t.refreshEvery??10,i=t.once?void 0:t.relay;if(!i&&!t.once)he.err(`slack stream: WARNING: polling mode (${t.pollReason??"no relay configured"}) — this is the fallback, `+`not the intended setup: matches arrive up to ${Math.round(t.intervalMs/1000)}s late (replies under older parents up to ${Math.round(Math.max(t.threadScanSec??180,t.intervalMs/1000))}s) and every cycle spends Slack API calls. For real time, set up the relay (slack relay init) and set SLACK_RELAY_URL + SLACK_RELAY_TOKEN: ${Qw}`);e=bk(e,t.callsPerMin??40,t.signal);let a,c=new AbortController,d=()=>c.abort();t.signal?.addEventListener("abort",d,{once:!0});try{a=lk(t.statePath);let f=ck(t.statePath,t.identity),p=t.repliesTo?[...t.repliesTo].sort().join(","):void 0;if(f.joinedBy!==p)delete f.joined;if(p)f.joinedBy=p;else delete f.joinedBy;let g={opts:t,client:e,state:f,names:new Map,matches:0},y=new Set,k=[],w=he.now()/1000,u=w,l="",h=0,m=0,b=-1/0,_=0,x=(U)=>{he.err(`slack stream: rate limited — waiting ${U.retryAfter}s`),_=Math.max(_,he.now()+U.retryAfter*1000)},S=async(U)=>{if(k=(await e.listChannels(t.channels)).filter((ce)=>!t.channels||t.channels.includes(ce.id)),t.channels){for(let ce of t.channels)if(!k.some((z)=>z.id===ce))throw new cn(`--channel ${ce}: the identity is not a member of it`)}let q=Object.keys(f.channels).length===0;for(let ce of k){if(f.channels[ce.id])continue;let K=Math.min(q||m===0?U:u,t.sinceSec!==void 0?w-t.sinceSec:1/0);f.channels[ce.id]={since:_t(K),cursor:_t(K),threads:{}}}u=U,Jt(t.statePath,f)};if(t.sinceSec!==void 0)f.channels={},delete f.seen,delete f.relay;let E={queue:[],retry:[],inflight:void 0,onDrain:void 0,handled:0,live:void 0,full:!1},I=new AbortController,N=()=>I.abort(),C=(U,ie="")=>{if(E.live===U)return;E.live=U,he.err(U?`slack stream: relay connected${ie?` (${ie})`:""} — polling every ${Math.round(Math.max(t.intervalMs,i.reconcileMs)/1000)}s as a safety net`:`slack stream: relay unavailable${ie?` (${ie})`:""} — polling every ${Math.round(t.intervalMs/1000)}s`),N()},A=async(U)=>{let ie=t.sinceSec===void 0&&f.relay?.url===U.url?{seq:f.relay.seq,...f.relay.epoch?{epoch:f.relay.epoch}:{}}:{seq:0},q=0,ce=()=>E.queue.length+E.retry.length+(E.inflight?1:0);while(!c.signal.aborted){while(ce()>=po/2&&!c.signal.aborted)await new Promise((Y)=>{let se=()=>Y();E.onDrain=()=>{c.signal.removeEventListener("abort",se),Y()},c.signal.addEventListener("abort",se,{once:!0})});if(c.signal.aborted)return;let z=new AbortController,K=()=>z.abort();c.signal.addEventListener("abort",K,{once:!0});let ne=!1,fe="stream closed";try{await U.subscribe(ie,z.signal,{hello:(Y)=>{if(q=0,Y.gap)E.full=!0;if(Y.gap||f.relay?.url!==U.url||f.relay.epoch!==Y.epoch){f.relay={url:U.url,seq:Y.seq,...Y.epoch?{epoch:Y.epoch}:{}},E.handled=Math.min(E.handled,Y.seq);for(let se of[...E.queue,...E.retry,...E.inflight?[E.inflight]:[]])se.seq=Math.min(se.seq,Y.seq)}ie={seq:Y.seq,...Y.epoch?{epoch:Y.epoch}:{}},C(!0,Y.via)},bell:(Y,se)=>{if(ne)return;if(ce()>=po){he.err(`slack stream: relay backlog over ${po} — pausing the relay until it drains`),ne=!0,z.abort(),C(!1,"paused while its backlog drains");return}ie={...ie,seq:Y},E.queue.push({seq:Y,bell:se,tries:0,dueMs:0}),N()}})}catch(Y){if(Y instanceof Ba){if(E.live)C(!1,Xe(Y));E.live=!1,he.err(`slack stream: relay disabled for this run: ${Xe(Y)} — check SLACK_RELAY_TOKEN`);return}fe=Xe(Y)}finally{c.signal.removeEventListener("abort",K)}if(c.signal.aborted)return;if(ne)continue;C(!1,fe),q++,await he.sleep(ds(q,2000,60000),c.signal)}};if(i)A(i);let F=async(U)=>{if(t.channels&&!t.channels.includes(U.channel))return!0;if(U.kind==="reaction"){if(!t.reactions||U.self&&t.selfUsers.has(U.self))return!0;if(U.user&&t.selfUsers.has(U.user))return!0;let ce={type:"reaction",channel:{id:U.channel},ts:U.ts,user:{id:U.user??""}};return he.out(t.json?JSON.stringify(ce):`reaction ${U.channel} ${U.ts} by ${U.user??"?"}`),!0}let ie=k.find((ce)=>ce.id===U.channel);if(!ie){if(he.now()/1000-u<60)return!1;await S(he.now()/1000),ie=k.find((ce)=>ce.id===U.channel)}let q=ie&&f.channels[ie.id];if(!ie||!q||y.has(ie.id))return!0;if(me(U.ts)<me(q.since))return!0;if(U.self&&t.selfUsers.has(U.self)){if(t.repliesTo?.has(U.self)&&U.thread_ts){let ce=f.joined??={},z=`${ie.id}:${U.thread_ts}`;ce[z]=Math.max(ce[z]??0,me(U.ts)),g.notJoined?.delete(z),Jt(t.statePath,f)}return!0}return pk(g,ie,U)},v=()=>{if(!f.relay||f.relay.url!==i?.url)return;let U=[...E.queue,...E.retry,...E.inflight?[E.inflight]:[]].map((ie)=>ie.seq);f.relay.seq=Math.max(0,U.length?Math.min(...U)-1:Math.max(f.relay.seq,E.handled))},O=async()=>{let U=he.now(),ie=E.retry.filter((z)=>z.dueMs<=U);if(ie.length)E.retry=E.retry.filter((z)=>z.dueMs>U),E.queue=[...ie,...E.queue].sort((z,K)=>z.seq-K.seq);let q=0;while(E.queue.length&&q<tk&&!t.signal?.aborted&&he.now()>=_){let z=E.queue.shift();E.inflight=z,q++;let K,ne;try{K=await F(z.bell)}catch(fe){if(fe instanceof ze){x(fe),z.dueMs=_,E.retry.push(z),E.inflight=void 0;break}K=!1,ne=fe}if(E.inflight=void 0,ne!==void 0&&/thread_not_found|message_not_found/.test(Xe(ne)))ne=void 0;if(ne!==void 0&&ja(ne)==="channel")he.err(`slack stream: relay bell for ${z.bell.channel} dropped: ${Xe(ne)}`),K=!0;if(ne===void 0&&X)he.err("slack stream: relay bell reads recovered"),X=!1;if(K)E.handled=Math.max(E.handled,z.seq);else if(ne!==void 0){if(z.fails=(z.fails??0)+1,!X)he.err(`slack stream: relay bell for ${z.bell.channel} failed (${Xe(ne)}) — retrying`);X=!0,z.dueMs=he.now()+ds(z.fails,1500,60000),E.retry.push(z)}else if(++z.tries>=nk)he.err(`slack stream: relay bell for ${z.bell.channel} abandoned after ${z.tries} tries (not visible) — only the poll can find it now`),E.handled=Math.max(E.handled,z.seq);else z.dueMs=he.now()+ds(z.tries,1500,60000),E.retry.push(z)}if(E.onDrain&&E.queue.length+E.retry.length<po/2)E.onDrain(),E.onDrain=void 0;let ce=f.relay?.seq;if(v(),q||f.relay?.seq!==ce)Jt(t.statePath,f)},M=()=>E.live===!0&&i?Math.max(t.intervalMs,i.reconcileMs):t.intervalMs,J=()=>{let U=he.now();return(U>=b+M()||E.full)&&U>=_},j=()=>E.queue.length>0||E.retry.some((U)=>U.dueMs<=he.now()),ee=!1,X=!1;while(!t.signal?.aborted){if(J()&&!(ee&&j())){E.full=!1;let q=he.now()/1000;try{if(m%o===0)await S(q);let ce=Math.max(0,t.threadScanSec??180),z=wk(k.filter((K)=>!y.has(K.id)),f,q,{windowSec:t.threadWindowSec,periodSec:ce,intervalSec:M()/1000,once:t.once});for(let K of k){if(t.signal?.aborted)break;if(y.has(K.id))continue;let ne=z.get(K.id)??"full";if(ne==="skip")continue;for(;;)try{let fe=f.channels[K.id],Y=ne==="cursor"&&fe.scanned!==void 0&&me(fe.latest??"0")<q-t.threadWindowSec&&q-me(fe.scanned)>=ce;if(await fk(g,K,q,ne==="full"),Y)fe.scanned=_t(q),Jt(t.statePath,f);break}catch(fe){if(fe instanceof ze){if(x(fe),await he.sleep(_-he.now(),t.signal),t.signal?.aborted)break;continue}if(ja(fe)==="channel"){y.add(K.id),l=Xe(fe),he.err(`slack stream: skipping ${K.isIm?K.id:"#"+K.name} (${K.id}): ${Xe(fe)}`);break}throw fe}}if(k.length>0&&k.every((K)=>y.has(K.id)))throw new cn(`every channel failed — nothing left to watch (last: ${l})`);if(h>0)he.err(`slack stream: recovered after ${h} failed attempt(s)`);h=0}catch(ce){if(ce instanceof cn||ja(ce)==="fatal")return he.err(`slack stream: fatal: ${Xe(ce)}`),3;if(h++,h>=n)return he.err(`slack stream: giving up after ${h} consecutive failures: ${Xe(ce)}`),3;let z=ds(h,s,r);he.err(`slack stream: ${Xe(ce)} — reconnecting in ${(z/1000).toFixed(1)}s (attempt ${h}/${n})`),await he.sleep(z,t.signal),E.full=!0;continue}if(m++,mk(f,q-t.threadWindowSec-86400),gk(f,q-hk),t.once){if(Jt(t.statePath,f),g.matches===0)he.err(`slack stream: no matches in ${k.length-y.size} channel(s)`);return g.matches>0?0:2}b=q*1000,ee=!0}if(t.signal?.aborted)break;let U=he.now(),ie=Math.max(_,E.queue.length||E.full?U:Math.min(b+M(),...E.retry.map((q)=>q.dueMs)));if(ie>U){I=new AbortController;let q=I,ce=()=>q.abort();t.signal?.addEventListener("abort",ce,{once:!0}),await he.sleep(ie-U,q.signal),t.signal?.removeEventListener("abort",ce)}if(J()&&!(ee&&j()))continue;await O(),ee=!1}return 0}catch(f){return he.err(`slack stream: fatal: ${Xe(f)}`),3}finally{c.abort(),t.signal?.removeEventListener("abort",d),a?.()}}class Uf extends Error{}function kk(e,t){let n;while((n=e.indexOf(`
250
251
 
251
- `))>=0){let s=e.slice(0,n);e=e.slice(n+2);let r="message",o,i=[];for(let l of s.split(`
252
- `)){if(!l||l.startsWith(":"))continue;let u=l.indexOf(":"),f=u<0?l:l.slice(0,u),a=u<0?"":l.slice(u+1).replace(/^ /,"");if(f==="event")r=a;else if(f==="data")i.push(a);else if(f==="id")o=a}if(i.length)t(r,i.join(`
253
- `),o)}return e}var Ww="slack-hub-relay.v1",Uw="slack-term-relay.v1";function Jw(e){return`bearer.${Buffer.from(e,"utf8").toString("base64url")}`}function va(e){return e==="websocket"||e==="sse"?e:"auto"}var Kw=32;function kf(e){return e===void 0?"":`?after=${e.seq}${e.epoch?`&epoch=${encodeURIComponent(e.epoch)}`:""}`}function Pa(e,t,n=70000,s={}){let r=e.replace(/\/+$/,""),o=s.transport??"auto",i=Hw(r,t,n);return async(l,u,f)=>{let a=s.WebSocket===void 0?globalThis.WebSocket:s.WebSocket;if(o!=="sse")if(!a){if(o==="websocket")throw Error("relay: this runtime has no WebSocket")}else{if(await qw(a,r,t,n,s.pingMs??25000,s.ackDelayMs??100,l,u,f)||u.aborted)return;if(o==="websocket")throw Error("relay: WebSocket connection failed")}return i(l,u,f)}}function qw(e,t,n,s,r,o,i,l,u){return new Promise((f,a)=>{if(l.aborted)return f(!0);let c;try{c=new e(`${t.replace(/^http/i,"ws")}/ws${kf(i)}`,[Ww,Uw,Jw(n)])}catch{return f(!1)}let d=!1,p=!1,h,g,y,m=0,w=0,k=(S)=>{if(p)return;p=!0,clearTimeout(h),clearTimeout(g),clearInterval(y),l.removeEventListener("abort",_),c.onopen=c.onmessage=c.onerror=c.onclose=null;try{c.close(1000)}catch{}if(S)a(S);else f(d||l.aborted)},_=()=>k();l.addEventListener("abort",_,{once:!0});let D=()=>{clearTimeout(h),h=setTimeout(()=>k(d?Error(`relay: no data for ${Math.round(s/1000)}s`):void 0),s)},E=()=>{if(clearTimeout(g),g=void 0,m<=w)return;w=m;try{c.send(JSON.stringify({type:"ack",seq:m}))}catch{}};D(),c.onopen=()=>{d=!0,D(),y=setInterval(()=>{try{c.send("ping")}catch{}},r)},c.onmessage=(S)=>{if(D(),typeof S.data!=="string"||S.data==="pong")return;let x;try{x=JSON.parse(S.data)}catch(F){return k(F)}if(x.type==="hello"){let{type:F,...R}=x;m=w=R.seq,u.hello({...R,via:"websocket"})}else if(x.type==="bell"&&typeof x.seq==="number"){if(u.bell(x.seq,x.bell),p)return;if(m=Math.max(m,x.seq),m-w>=Kw)E();else g??=setTimeout(E,o)}},c.onerror=()=>{},c.onclose=(S)=>{if(!d||S.code===1000)return k();k(Error(`relay: WebSocket closed (${S.code}${S.reason?` ${S.reason}`:""})`))}})}function Hw(e,t,n){return async(s,r,o)=>{let i=new AbortController,l=()=>i.abort();r.addEventListener("abort",l,{once:!0});let u,f=!1,a=()=>{clearTimeout(u),u=setTimeout(()=>{f=!0,i.abort()},n)};try{a();let c=await fetch(`${e}/stream${kf(s)}`,{headers:{authorization:`Bearer ${t}`,accept:"text/event-stream"},signal:i.signal});if(c.status===401)throw new wf("relay rejected the token (401)");if(!c.ok||!c.body)throw Error(`relay: HTTP ${c.status}`);let d=c.body.getReader(),p=new TextDecoder,h="";for(;;){let{done:g,value:y}=await d.read();if(g)return;a(),h=jw((h+p.decode(y,{stream:!0})).replace(/\r\n/g,`
254
- `),(m,w,k)=>{let _=JSON.parse(w);if(m==="hello")o.hello({..._,via:"sse"});else if(m==="bell"&&k!==void 0)o.bell(Number(k),_)})}}catch(c){if(r.aborted)return;if(f)throw Error(`relay: no data for ${Math.round(n/1000)}s`);throw c}finally{clearTimeout(u),r.removeEventListener("abort",l)}}}import{spawnSync as $f}from"node:child_process";import{closeSync as zw,mkdirSync as Yw,openSync as Gw,readFileSync as Cf,unlinkSync as Df,writeFileSync as Xw}from"node:fs";import{homedir as xf,tmpdir as Vw}from"node:os";import{dirname as Zw,resolve as oo}from"node:path";function La(e){if(!e||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}var Sf=1000;function _f(e,t){let n=e.split(/\s+/).filter(Boolean).join(" ");if(t<=1)return"";return n.length<=t?n:`${n.slice(0,t-1)}…`}var Qw=3600000;function Ef(e){return`${new Date(e).toISOString().slice(0,16).replace("T"," ")} UTC`}function Af(e,t,n=Date.now()){if(n-(t??e)<Qw)return"[ask-answer]";return t!==void 0?`[ask-answer, late: answered ${Ef(t)}]`:`[ask-answer, late: asked ${Ef(e)}, pressed since]`}function Tf(e){let t=`${e.tag??"[ask-answer]"} ${e.link} →`,n=_f(e.answer,300),s=e.how?` (${e.how})`:"";if(e.freeText)s+=" — a free-text reply, not a choice: the question stays open";else if(e.collected)s+=" — collected ✅";if(e.goneAsker)s+=` — asked by pid ${e.goneAsker}, now gone: sent to this lane by its directory`;let r=_f(e.question,Sf-t.length-n.length-s.length-8);return`${t} ${n}${s}. Q: ${r}`.slice(0,Sf)}var Ff=(e,t)=>$f(e,t,{encoding:"utf8",timeout:60000});function e0(e){try{let t=Cf(`/proc/${e}/stat`,"utf8");return Number(t.slice(t.lastIndexOf(")")+2).split(" ")[1])||0}catch{let t=$f("ps",["-o","ppid=","-p",String(e)],{encoding:"utf8",timeout:2000});return Number((t.stdout??"").trim())||0}}function Of(e,t,n=Ff,s=e0){for(let r=0;r<4&&e>1;r++,e=s(e)){let o=n(Pe("AY")||"ay",["send",String(e),"--force",t]);if(o.error)return;let i=`${o.stdout??""}${o.stderr??""}`;if(/no agent matched/i.test(i))continue;if(o.status===0||/QUEUED|sent to pid|NOT SUBMITTED/.test(i))return e}return}function Rf(e=Ff){let t=e(Pe("AY")||"ay",["ls","--json"]);try{let n=JSON.parse(t.stdout??"");return Array.isArray(n)?n.flatMap((s)=>typeof s.pid==="number"&&typeof s.cwd==="string"?[{pid:s.pid,cwd:s.cwd,...typeof s.started_at==="number"?{started_at:s.started_at}:{}}]:[]):[]}catch{return[]}}function If(e,t,n=La){let s=oo(e),r=oo(Vw());if(s===oo(xf())||s===r||s.startsWith(`${r}/`))return;return t.filter((i)=>oo(i.cwd.replace(/^~(?=\/|$)/,xf()))===s&&n(i.pid)).sort((i,l)=>(l.started_at??0)-(i.started_at??0))[0]?.pid}function vf(e){Yw(Zw(e),{recursive:!0});for(let t=0;t<2;t++)try{let n=Gw(e,"wx");return Xw(n,String(process.pid)),zw(n),()=>{try{Df(e)}catch{}}}catch{let n=0;try{n=Number(Cf(e,"utf8").trim())}catch{}if(n&&n!==process.pid&&La(n))return;try{Df(e)}catch{}}return}import{existsSync as n0,mkdirSync as s0,writeFileSync as r0}from"node:fs";import{basename as o0,join as Na,resolve as Lf}from"node:path";import{randomBytes as i0}from"node:crypto";var Pf={name:"slack-term",version:"1.57.0",repository:{type:"git",url:"https://github.com/snomiao/slack-hub.git"},bugs:{url:"https://github.com/snomiao/slack-hub/issues"},devDependencies:{"@semantic-release/commit-analyzer":"^13","@semantic-release/github":"^12","@semantic-release/npm":"^13","@semantic-release/release-notes-generator":"^14","@types/bun":"latest","@types/node":"^22","@types/yargs":"^17.0.35","@typescript/native-preview":"^7.0.0-dev.20260707.2","@vitest/coverage-istanbul":"4.1.10","semantic-release":"^24",typescript:"^5.6",vitest:"4.1.10"},bin:{slack:"./ts/cli.ts"},exports:{"./worker":"./worker/src/index.ts","./package.json":"./package.json"},description:"DEPRECATED: renamed to slack-hub — npm i -g slack-hub. Slack CLI — read activity/news/mentions, search, send messages with a confirm-hash safety gate.",engines:{node:">=18"},files:["ts/","locales/","dist/","worker/src/","README.md","SKILL.md","LICENSE"],homepage:"https://github.com/snomiao/slack-hub",keywords:["slack","cli","messaging","agent","terminal"],license:"MIT",overrides:{"@semantic-release/npm":"^13","@semantic-release/github":"^12"},publishConfig:{access:"public",bin:{slack:"./dist/cli.js"}},scripts:{dev:"bun run ts/cli.ts",build:"bun build ts/cli.ts --target=node --outfile dist/cli.js --minify",typecheck:"tsgo --noEmit","typecheck:tsc":"tsc --noEmit","typecheck:worker":"bun install --cwd worker --frozen-lockfile && tsgo --noEmit -p worker",test:"bun test tests/ --timeout 90000 --parallel=2","test:watch":"bun test tests/ --timeout 90000 --isolate --watch","test:parity":"bash tests/parity.sh",record:"bun run tests/record.ts",anonymize:"bun run tests/anonymize.ts","scan-pii":"bash .githooks/pre-commit","scan-pii:all":"bash .githooks/pre-commit --all",prepare:"git config core.hooksPath .githooks 2>/dev/null || true",prepublishOnly:"bun run scan-pii:all && bun run typecheck && bun run build","test:coverage":"vitest run --coverage --exclude tests/parity.test.ts --no-file-parallelism"},type:"module",dependencies:{yargs:"^18.0.0"},peerDependencies:{"@cloudflare/workers-types":"^4"},peerDependenciesMeta:{"@cloudflare/workers-types":{optional:!0}}};var a0="4.105.0",c0="2026-07-01",Ma="slack-hub-relay",l0="https://github.com/snomiao/slack-hub/blob/main/worker/README.md";function u0(e){return/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(e)}function d0(e){return o0(Lf(e)).toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,63).replace(/-+$/,"")||Ma}function f0(e,t={}){let n={name:e,private:!0,type:"module",scripts:{deploy:"wrangler deploy",dev:"wrangler dev --local"},dependencies:{"slack-hub":t.slackHub??`^${Pf.version}`},devDependencies:{wrangler:a0},engines:{node:">=22"}};return{"package.json":`${JSON.stringify(n,null,2)}
252
+ `))>=0){let s=e.slice(0,n);e=e.slice(n+2);let r="message",o,i=[];for(let a of s.split(`
253
+ `)){if(!a||a.startsWith(":"))continue;let c=a.indexOf(":"),d=c<0?a:a.slice(0,c),f=c<0?"":a.slice(c+1).replace(/^ /,"");if(d==="event")r=f;else if(d==="data")i.push(f);else if(d==="id")o=f}if(i.length)t(r,i.join(`
254
+ `),o)}return e}var Dk="slack-hub-relay.v1",xk="slack-term-relay.v1";function Sk(e){return`bearer.${Buffer.from(e,"utf8").toString("base64url")}`}function qa(e){return e==="websocket"||e==="sse"?e:"auto"}var _k=32;function Jf(e){return e===void 0?"":`?after=${e.seq}${e.epoch?`&epoch=${encodeURIComponent(e.epoch)}`:""}`}function Ha(e,t,n=70000,s={}){let r=e.replace(/\/+$/,""),o=s.transport??"auto",i=$k(r,t,n);return async(a,c,d)=>{let f=s.WebSocket===void 0?globalThis.WebSocket:s.WebSocket;if(o!=="sse")if(!f){if(o==="websocket")throw Error("relay: this runtime has no WebSocket")}else{if(await Ek(f,r,t,n,s.pingMs??25000,s.ackDelayMs??100,a,c,d)||c.aborted)return;if(o==="websocket")throw Error("relay: WebSocket connection failed")}return i(a,c,d)}}function Ek(e,t,n,s,r,o,i,a,c){return new Promise((d,f)=>{if(a.aborted)return d(!0);let p;try{p=new e(`${t.replace(/^http/i,"ws")}/ws${Jf(i)}`,[Dk,xk,Sk(n)])}catch{return d(!1)}let g=!1,y=!1,k,w,u,l=0,h=0,m=(S)=>{if(y)return;y=!0,clearTimeout(k),clearTimeout(w),clearInterval(u),a.removeEventListener("abort",b),p.onopen=p.onmessage=p.onerror=p.onclose=null;try{p.close(1000)}catch{}if(S)f(S);else d(g||a.aborted)},b=()=>m();a.addEventListener("abort",b,{once:!0});let _=()=>{clearTimeout(k),k=setTimeout(()=>m(g?Error(`relay: no data for ${Math.round(s/1000)}s`):void 0),s)},x=()=>{if(clearTimeout(w),w=void 0,l<=h)return;h=l;try{p.send(JSON.stringify({type:"ack",seq:l}))}catch{}};_(),p.onopen=()=>{g=!0,_(),u=setInterval(()=>{try{p.send("ping")}catch{}},r)},p.onmessage=(S)=>{if(_(),typeof S.data!=="string"||S.data==="pong")return;let E;try{E=JSON.parse(S.data)}catch(I){return m(I)}if(E.type==="hello"){let{type:I,...N}=E;l=h=N.seq,c.hello({...N,via:"websocket"})}else if(E.type==="bell"&&typeof E.seq==="number"){if(c.bell(E.seq,E.bell),y)return;if(l=Math.max(l,E.seq),l-h>=_k)x();else w??=setTimeout(x,o)}},p.onerror=()=>{},p.onclose=(S)=>{if(!g||S.code===1000)return m();m(Error(`relay: WebSocket closed (${S.code}${S.reason?` ${S.reason}`:""})`))}})}function $k(e,t,n){return async(s,r,o)=>{let i=new AbortController,a=()=>i.abort();r.addEventListener("abort",a,{once:!0});let c,d=!1,f=()=>{clearTimeout(c),c=setTimeout(()=>{d=!0,i.abort()},n)};try{f();let p=await fetch(`${e}/stream${Jf(s)}`,{headers:{authorization:`Bearer ${t}`,accept:"text/event-stream"},signal:i.signal});if(p.status===401)throw new Uf("relay rejected the token (401)");if(!p.ok||!p.body)throw Error(`relay: HTTP ${p.status}`);let g=p.body.getReader(),y=new TextDecoder,k="";for(;;){let{done:w,value:u}=await g.read();if(w)return;f(),k=kk((k+y.decode(u,{stream:!0})).replace(/\r\n/g,`
255
+ `),(l,h,m)=>{let b=JSON.parse(h);if(l==="hello")o.hello({...b,via:"sse"});else if(l==="bell"&&m!==void 0)o.bell(Number(m),b)})}}catch(p){if(r.aborted)return;if(d)throw Error(`relay: no data for ${Math.round(n/1000)}s`);throw p}finally{clearTimeout(c),r.removeEventListener("abort",a)}}}import{spawnSync as zf}from"node:child_process";import{closeSync as Ck,chmodSync as Ak,mkdirSync as Yf,mkdtempSync as Tk,openSync as Fk,readFileSync as Gf,unlinkSync as Kf,writeFileSync as Xf}from"node:fs";import{homedir as Ya,tmpdir as Ok}from"node:os";import{dirname as Ik,join as go,resolve as mo}from"node:path";function za(e){if(!e||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}var qf=850,Rk=3600000;function Hf(e){return`${new Date(e).toISOString().slice(0,16).replace("T"," ")} UTC`}function Vf(e,t,n=Date.now()){if(n-(t??e)<Rk)return"[ask-answer]";return t!==void 0?`[ask-answer, late: answered ${Hf(t)}]`:`[ask-answer, late: asked ${Hf(e)}, pressed since]`}function Zf(e){let t=`${e.tag??"[ask-answer]"} ${e.link} →`,n=e.answer,s=e.how?` (${e.how})`:"";if(e.freeText)s+=" — a free-text reply, not a choice: the question stays open";else if(e.collected)s+=" — collected ✅";if(e.goneAsker)s+=` — asked by pid ${e.goneAsker}, now gone: sent to this lane by its directory`;let r=e.question.split(/\s+/).filter(Boolean).join(" ");return`${t} ${n}${s}. Q: ${r}`}var Qf=(e,t)=>zf(e,t,{encoding:"utf8",timeout:60000});function vk(e){try{let t=Gf(`/proc/${e}/stat`,"utf8");return Number(t.slice(t.lastIndexOf(")")+2).split(" ")[1])||0}catch{let t=zf("ps",["-o","ppid=","-p",String(e)],{encoding:"utf8",timeout:2000});return Number((t.stdout??"").trim())||0}}function ep(e,t,n=Qf,s=vk,r=go(process.env.XDG_STATE_HOME||go(Ya(),".local","state"),"slack-hub","ask-inbox")){let o=t;if(t.length>qf){Yf(r,{recursive:!0,mode:448}),Ak(r,448);let i=Tk(go(r,"answer-")),a=go(i,"message.txt");if(Xf(a,t,{mode:384}),o=`[ask-answer] Full answer and question: ${JSON.stringify(a)}`,o.length>qf)return}for(let i=0;i<4&&e>1;i++,e=s(e)){let a=n(Ae("AY")||"ay",["send",String(e),"--force",o]);if(a.error)return;let c=`${a.stdout??""}${a.stderr??""}`;if(/no agent matched/i.test(c))continue;if(a.status===0||/QUEUED|sent to pid|NOT SUBMITTED/.test(c))return e}return}function tp(e=Qf){let t=e(Ae("AY")||"ay",["ls","--json"]);try{let n=JSON.parse(t.stdout??"");return Array.isArray(n)?n.flatMap((s)=>typeof s.pid==="number"&&typeof s.cwd==="string"?[{pid:s.pid,cwd:s.cwd,...typeof s.started_at==="number"?{started_at:s.started_at}:{}}]:[]):[]}catch{return[]}}function np(e,t,n=za){let s=mo(e),r=mo(Ok());if(s===mo(Ya())||s===r||s.startsWith(`${r}/`))return;let o=t.filter((i)=>mo(i.cwd.replace(/^~(?=\/|$)/,Ya()))===s&&n(i.pid));return o.length===1?o[0].pid:void 0}function sp(e){Yf(Ik(e),{recursive:!0});for(let t=0;t<2;t++)try{let n=Fk(e,"wx");return Xf(n,String(process.pid)),Ck(n),()=>{try{Kf(e)}catch{}}}catch{let n=0;try{n=Number(Gf(e,"utf8").trim())}catch{}if(n&&n!==process.pid&&za(n))return;try{Kf(e)}catch{}}return}import{existsSync as Lk,mkdirSync as Nk,writeFileSync as Mk}from"node:fs";import{basename as Bk,join as Ga,resolve as op}from"node:path";import{randomBytes as jk}from"node:crypto";var rp={name:"slack-term",version:"1.58.0",repository:{type:"git",url:"https://github.com/snomiao/slack-hub.git"},bugs:{url:"https://github.com/snomiao/slack-hub/issues"},devDependencies:{"@semantic-release/commit-analyzer":"^13","@semantic-release/github":"^12","@semantic-release/npm":"^13","@semantic-release/release-notes-generator":"^14","@types/bun":"latest","@types/node":"^22","@types/yargs":"^17.0.35","@vitest/coverage-istanbul":"4.1.11","semantic-release":"^24",tsrs:"0.25.0-ts7.1.0-beta",typescript:"^5.6",vitest:"4.1.11"},bin:{slack:"./ts/cli.ts"},exports:{"./worker":"./worker/src/index.ts","./package.json":"./package.json"},description:"DEPRECATED: renamed to slack-hub — npm i -g slack-hub. Slack CLI — read activity/news/mentions, search, send messages with a confirm-hash safety gate.",engines:{node:">=18"},files:["ts/","locales/","dist/","worker/src/","README.md","SKILL.md","LICENSE"],homepage:"https://github.com/snomiao/slack-hub",keywords:["slack","cli","messaging","agent","terminal"],license:"MIT",overrides:{"@semantic-release/npm":"^13","@semantic-release/github":"^12"},publishConfig:{access:"public",bin:{slack:"./dist/cli.js"}},scripts:{dev:"bun run ts/cli.ts",build:"bun build ts/cli.ts --target=node --outfile dist/cli.js --minify",typecheck:"tsrs --noEmit","typecheck:tsc":"tsc --noEmit","typecheck:worker":"bun install --cwd worker --frozen-lockfile && tsrs --noEmit -p worker && tsrs --noEmit -p worker/test","test:worker":"bun install --cwd worker --frozen-lockfile && cd worker && node node_modules/vitest/vitest.mjs run",test:"bun test tests/ --timeout 90000 --parallel=2","test:watch":"bun test tests/ --timeout 90000 --isolate --watch","test:parity":"bash tests/parity.sh",record:"bun run tests/record.ts",anonymize:"bun run tests/anonymize.ts","scan-pii":"bash .githooks/pre-commit","scan-pii:all":"bash .githooks/pre-commit --all",prepare:"git config core.hooksPath .githooks 2>/dev/null || true",prepublishOnly:"bun run scan-pii:all && bun run typecheck && bun run build","test:coverage":"vitest run --coverage --exclude tests/parity.test.ts --exclude 'tests/parity/**' --no-file-parallelism"},type:"module",dependencies:{yargs:"^18.0.0"},peerDependencies:{"@cloudflare/workers-types":"^4"},peerDependenciesMeta:{"@cloudflare/workers-types":{optional:!0}},rustify:{mode:"hybrid",bins:{slack:"slack"},rootEnv:"SLACK_HUB_PACKAGE_ROOT"}};var Wk="4.105.0",Uk="2026-07-01",Xa="slack-hub-relay",Jk="https://github.com/snomiao/slack-hub/blob/main/worker/README.md";function Kk(e){return/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(e)}function qk(e){return Bk(op(e)).toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,63).replace(/-+$/,"")||Xa}function Hk(e,t={}){let n={name:e,private:!0,type:"module",scripts:{deploy:"wrangler deploy",dev:"wrangler dev --local"},dependencies:{"slack-hub":t.slackHub??`^${rp.version}`},devDependencies:{wrangler:Wk},engines:{node:">=22"}};return{"package.json":`${JSON.stringify(n,null,2)}
255
256
  `,"wrangler.jsonc":`// slack-hub relay: Slack Events API -> doorbells for \`slack stream\`.
256
257
  // Secrets (not in this file): wrangler secret put SLACK_SIGNING_SECRET / RELAY_TOKEN / SLACK_TEAM_ID (optional)
257
258
  {
258
259
  "$schema": "node_modules/wrangler/config-schema.json",
259
260
  "name": ${JSON.stringify(e)},
260
261
  "main": "src/index.ts",
261
- "compatibility_date": "${c0}",
262
+ "compatibility_date": "${Uk}",
262
263
  "durable_objects": {
263
264
  "bindings": [{ "name": "RELAY", "class_name": "Relay" }]
264
265
  },
@@ -274,7 +275,7 @@ export { default, Relay } from "slack-hub/worker";
274
275
  .wrangler/
275
276
  .dev.vars*
276
277
  .env*
277
- `,"README.md":p0(e)}}function Nf(e,t){let n=t??"<RELAY_TOKEN>";return`1. Node >= 22 (wrangler 4 needs it), then install:
278
+ `,"README.md":zk(e)}}function ip(e,t){let n=t??"<RELAY_TOKEN>";return`1. Node >= 22 (wrangler 4 needs it), then install:
278
279
  npm install
279
280
  2. Log in to Cloudflare:
280
281
  npx wrangler login
@@ -295,7 +296,7 @@ export { default, Relay } from "slack-hub/worker";
295
296
  6. Check it:
296
297
  slack relay health # or: curl -H "Authorization: Bearer $SLACK_RELAY_TOKEN" $SLACK_RELAY_URL/health
297
298
  slack stream -e . # stderr says: relay connected (websocket)
298
- `}function p0(e){return`# ${e}
299
+ `}function zk(e){return`# ${e}
299
300
 
300
301
  A [slack-hub](https://github.com/snomiao/slack-hub) relay: a Cloudflare Worker
301
302
  that turns Slack's Events API into a resumable doorbell stream for
@@ -304,7 +305,7 @@ configures and deploys it. Created by \`slack relay init\`.
304
305
 
305
306
  ## Set up
306
307
 
307
- ${Nf(e)}
308
+ ${ip(e)}
308
309
  \`RELAY_TOKEN\` is any long random string (\`openssl rand -hex 32\`); \`slack relay init\`
309
310
  printed one. Keep it out of this folder: anyone holding it can watch when and
310
311
  where messages are posted.
@@ -314,41 +315,41 @@ where messages are posted.
314
315
  Bump \`slack-hub\` in package.json, \`npm install\`, \`npx wrangler deploy\`.
315
316
  Storage survives redeploys; clients reconnect and resume.
316
317
 
317
- Details (endpoints, privacy, protocol): ${l0}
318
- `}function Mf(e,t={},n=i0){let s=t.name??d0(e);if(!u0(s))return{ok:!1,error:`invalid worker name "${s}": use lowercase letters, digits and dashes (1-63 chars, no leading/trailing dash)`};let r=f0(s,t.slackHub!==void 0?{slackHub:t.slackHub}:{}),o=Lf(e),i=Object.keys(r).filter((l)=>n0(Na(o,l)));if(i.length&&!t.force)return{ok:!1,error:`refusing to overwrite existing files in ${o} (pass --force to replace them)`,existing:i};for(let[l,u]of Object.entries(r)){let f=Na(o,l);s0(Na(f,".."),{recursive:!0}),r0(f,u)}return{ok:!0,dir:o,name:s,written:Object.keys(r),token:n(32).toString("hex")}}function Bf(e,t=process.cwd()){let n=e.dir.startsWith(`${t}/`)?e.dir.slice(t.length+1):e.dir;return[`Created ${e.dir} (worker "${e.name}"):`,...e.written.map((s)=>` ${s}`),"","RELAY_TOKEN (generated now, not saved anywhere — copy it):",` ${e.token}`,"","Next steps:",`0. cd ${n}`,Nf(e.name,e.token)].join(`
319
- `)}async function jf(e,t,n=fetch,s=1e4){if(!e||!t)return{code:2,out:"slack relay health: set SLACK_RELAY_URL and SLACK_RELAY_TOKEN (or pass --url / --token)"};let r=`${e.replace(/\/+$/,"")}/health`;try{let o=await n(r,{headers:{authorization:`Bearer ${t}`},signal:AbortSignal.timeout(s)}),i=await o.text();if(o.status===401)return{code:1,out:"slack relay health: 401 unauthorized — SLACK_RELAY_TOKEN does not match the relay's RELAY_TOKEN secret"};if(!o.ok)return{code:1,out:`slack relay health: HTTP ${o.status} from ${r}${i?`: ${i.slice(0,200)}`:""}`};let l;try{l=JSON.parse(i)}catch{return{code:1,out:`slack relay health: not a slack-hub relay (non-JSON reply from ${r})`}}return{code:l.ok===!0?0:1,out:JSON.stringify(l,null,2)}}catch(o){return{code:1,out:`slack relay health: cannot reach ${r}: ${o instanceof Error?o.message:String(o)}`}}}import{spawn as h0}from"node:child_process";import{constants as Wf}from"node:os";var g0=["processing","active","suspended","closed"];function Uf(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?Br():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 Jf(e){if(e!==void 0&&(!e.trim()||[...e].length>200))throw Error("--title must contain 1–200 characters.")}async function Kf(e,t,n){let{ref:s,threadTs:r}=n(t);if(!r||!/^\d{10}\.\d{6}$/.test(r))throw Error("Target must include a thread root: C00000001:1700000000.000100, #channel:ts, or a message permalink.");return{channel_id:await Kr(e,s),thread_ts:r}}function Ba(e,t){console.error(`agent: ${e}: ${t instanceof Error?t.message:"request failed"}`)}async function m0(e,t,n,s){let r,o,i,l,u,f=!1,a=!1,c=1,d=(g)=>{if(o)return;if(o=g,f=!0,r&&r.exitCode===null&&r.signalCode===null)r.kill(g),i=setTimeout(()=>r?.kill("SIGKILL"),5000)},p=()=>d("SIGINT"),h=()=>d("SIGTERM");process.on("SIGINT",p),process.on("SIGTERM",h);try{if(a=!0,await Ps(e,t,"processing"),!f&&s.title!==void 0)await ia(e,t,s.title);if(!f){r=h0(n[0],n.slice(1),{stdio:"inherit"});let g=new Promise((y)=>{r.once("error",()=>{console.error("agent: could not start command"),y(127)}),r.once("exit",(m,w)=>{y(m??(w?128+Wf.signals[w]:1))})});l=setInterval(()=>{if(f||u)return;u=Ps(e,t,"processing").then(()=>{}).catch((y)=>Ba("heartbeat failed; retrying on next tick",y)).finally(()=>{u=void 0})},s.every*1000),c=await g}}catch(g){Ba("could not start agent session",g)}finally{if(f=!0,clearInterval(l),clearTimeout(i),await u,a)try{await Ps(e,t,s.close?"closed":"active")}catch(g){if(Ba("final status clear failed",g),c===0)c=1}process.removeListener("SIGINT",p),process.removeListener("SIGTERM",h)}return o?128+Wf.signals[o]:c}function qf(e,t){let n=(s)=>s.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",(s)=>n(s).positional("status",{type:"string",choices:g0,demandOption:!0}),async(s)=>{Jf(s.title);let r=Uf(s["bot-token-env"]),o=await Kf(r,s.target,t);if(await Ps(r,o,s.status),s.title!==void 0)await ia(r,o,s.title)}).command("run <target>","Keep a thread working while a command runs: run <target> -- <command...>",(s)=>n(s).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(s)=>{if(Jf(s.title),!Number.isFinite(s.every)||s.every<=0||s.every>=3600)throw Error("--every must be greater than 0 and less than 3600 seconds.");let r=process.argv.indexOf("--"),o=r<0?[]:process.argv.slice(r+1);if(!o[0])throw Error("agent run requires -- <command...>");let i=Uf(s["bot-token-env"]),l=await Kf(i,s.target,t);process.exitCode=await m0(i,l,o,{every:s.every,close:s.close,...s.title!==void 0?{title:s.title}:{}})}).demandCommand(1,"Choose agent status or agent run.")}import{existsSync as Hf}from"node:fs";import{join as zf}from"node:path";var y0="slack-hub",Yf="slack-term";function is(e,t=process.env){return t[`SLACK_HUB_${e}`]??t[`SLACK_TERM_${e}`]}function b0(e,t){return!Hf(e)&&Hf(t)?t:e}function ja(e){return b0(zf(e,y0),zf(e,Yf))}function Gf(e,t=Boolean(process.stderr.isTTY)){if(e!==Yf||!t)return;return"slack: the slack-term npm package was renamed to slack-hub — run: npm uninstall -g slack-term && npm install -g slack-hub"}var Xf={name:"slack-term",version:"1.57.0",repository:{type:"git",url:"https://github.com/snomiao/slack-hub.git"},bugs:{url:"https://github.com/snomiao/slack-hub/issues"},devDependencies:{"@semantic-release/commit-analyzer":"^13","@semantic-release/github":"^12","@semantic-release/npm":"^13","@semantic-release/release-notes-generator":"^14","@types/bun":"latest","@types/node":"^22","@types/yargs":"^17.0.35","@typescript/native-preview":"^7.0.0-dev.20260707.2","@vitest/coverage-istanbul":"4.1.10","semantic-release":"^24",typescript:"^5.6",vitest:"4.1.10"},bin:{slack:"./ts/cli.ts"},exports:{"./worker":"./worker/src/index.ts","./package.json":"./package.json"},description:"DEPRECATED: renamed to slack-hub — npm i -g slack-hub. Slack CLI — read activity/news/mentions, search, send messages with a confirm-hash safety gate.",engines:{node:">=18"},files:["ts/","locales/","dist/","worker/src/","README.md","SKILL.md","LICENSE"],homepage:"https://github.com/snomiao/slack-hub",keywords:["slack","cli","messaging","agent","terminal"],license:"MIT",overrides:{"@semantic-release/npm":"^13","@semantic-release/github":"^12"},publishConfig:{access:"public",bin:{slack:"./dist/cli.js"}},scripts:{dev:"bun run ts/cli.ts",build:"bun build ts/cli.ts --target=node --outfile dist/cli.js --minify",typecheck:"tsgo --noEmit","typecheck:tsc":"tsc --noEmit","typecheck:worker":"bun install --cwd worker --frozen-lockfile && tsgo --noEmit -p worker",test:"bun test tests/ --timeout 90000 --parallel=2","test:watch":"bun test tests/ --timeout 90000 --isolate --watch","test:parity":"bash tests/parity.sh",record:"bun run tests/record.ts",anonymize:"bun run tests/anonymize.ts","scan-pii":"bash .githooks/pre-commit","scan-pii:all":"bash .githooks/pre-commit --all",prepare:"git config core.hooksPath .githooks 2>/dev/null || true",prepublishOnly:"bun run scan-pii:all && bun run typecheck && bun run build","test:coverage":"vitest run --coverage --exclude tests/parity.test.ts --no-file-parallelism"},type:"module",dependencies:{yargs:"^18.0.0"},peerDependencies:{"@cloudflare/workers-types":"^4"},peerDependenciesMeta:{"@cloudflare/workers-types":{optional:!0}}};import{readdirSync as v0,readFileSync as P0,statSync as L0}from"node:fs";import{join as Ya}from"node:path";import{fileURLToPath as N0}from"node:url";import{closeSync as k0,existsSync as Vf,mkdirSync as Qf,openSync as D0,readFileSync as io,realpathSync as x0,renameSync as S0,statSync as Ja,unlinkSync as Zf,writeFileSync as _0}from"node:fs";import{homedir as ep}from"node:os";import{dirname as Ka,join as ft,resolve as Wa}from"node:path";function Js(){return Pe("HOME")??Ir(ft(ep(),".config"))}function ao(e=process.cwd()){let t=Wa(e);for(;;){for(let s of[wt,kt]){let r=ft(t,s);try{if(Ja(r).isDirectory())return{dir:r,global:!1}}catch{}}let n=Ka(t);if(n===t)break;t=n}return{dir:Js(),global:!0}}function Pn(e,t){Qf(Ka(e),{recursive:!0});let n=`${e}.tmp-${process.pid}-${Date.now()}`;_0(n,t,{mode:384}),S0(n,e)}function E0(e,t,n=1e4,s=5000){let r=`${e}.lock`;Qf(Ka(r),{recursive:!0});let o=Date.now()+s;for(;;)try{k0(D0(r,"wx"));break}catch(i){if(i.code!=="EEXIST")throw i;try{if(Date.now()-Ja(r).mtimeMs>n){Zf(r);continue}}catch{continue}if(Date.now()>o)throw Error(`${r} is held by another writer`);Bun.sleepSync(25)}try{return t()}finally{try{Zf(r)}catch{}}}function $0(e){if(!e||typeof e!=="object")return;let t=e;if(typeof t.channel!=="string"||!t.channel)return;let n={channel:t.channel};if(typeof t.thread_ts==="string"&&/^\d{10}\.\d{6}$/.test(t.thread_ts))n.thread_ts=t.thread_ts;if(typeof t.added==="string")n.added=t.added;if(typeof t.note==="string")n.note=t.note;return n}function cn(e){let t;try{t=Bun.YAML.parse(io(e,"utf8"))}catch(r){if(r.code==="ENOENT")return{};throw Error(`${e}: ${r instanceof Error?r.message:String(r)}`)}if(!t||typeof t!=="object")return{};let n=t,s={};if(typeof n.prefix==="string"&&n.prefix.trim())s.prefix=n.prefix.trim();else if(Array.isArray(n.prefix)&&n.prefix.length===1&&typeof n.prefix[0]==="string")s.prefix=`[${n.prefix[0]}]`;if(typeof n.channel==="string"&&n.channel)s.channel=n.channel;if(typeof n.as_bot==="boolean")s.as_bot=n.as_bot;if(n.restrict_to_subscriptions===!0)s.restrict_to_subscriptions=!0;if(Array.isArray(n.auto_subscribe))s.auto_subscribe=n.auto_subscribe.filter((r)=>typeof r==="string");if(typeof n.nudge_after_min==="number"&&n.nudge_after_min>0)s.nudge_after_min=n.nudge_after_min;if(typeof n.owner==="string"&&n.owner)s.owner=n.owner;if(n.subscriptions&&typeof n.subscriptions==="object"){let r={};for(let[o,i]of Object.entries(n.subscriptions)){let l=$0(i);if(l&&tp(o))r[o]=l}s.subscriptions=r}return s}function qa(e){let t=cn(ft(e.dir,"settings.yml")),n=cn(ft(e.dir,"settings.local.yml"));if(delete n.restrict_to_subscriptions,delete n.auto_subscribe,delete n.owner,t.restrict_to_subscriptions)delete n.subscriptions,delete n.prefix,delete n.as_bot,delete n.channel;let s={...t.subscriptions,...n.subscriptions},r={...t,...n};if(Object.keys(s).length)r.subscriptions=s;else delete r.subscriptions;return r}var C0=/^[a-z0-9][a-z0-9._-]{0,63}$/;function tp(e){return C0.test(e)&&!/^\d{10}\.\d{6}$/.test(e)}function np(e){let t=cn(ft(e.dir,"settings.yml")),n=t.subscriptions??{},s=t.restrict_to_subscriptions?{}:cn(ft(e.dir,"settings.local.yml")).subscriptions??{},r=[];for(let[o,i]of Object.entries(n))if(!s[o])r.push({...i,name:o,scope:e,file:"settings.yml"});for(let[o,i]of Object.entries(s))r.push({...i,name:o,scope:e,file:"settings.local.yml"});return r.sort((o,i)=>o.name.localeCompare(i.name))}var A0="# Written by `slack alias set/unset`; wins over settings.yml. Safe to edit by hand.\n";function T0(e){try{let t=io(e,"utf8").split(`
318
+ Details (endpoints, privacy, protocol): ${Jk}
319
+ `}function ap(e,t={},n=jk){let s=t.name??qk(e);if(!Kk(s))return{ok:!1,error:`invalid worker name "${s}": use lowercase letters, digits and dashes (1-63 chars, no leading/trailing dash)`};let r=Hk(s,t.slackHub!==void 0?{slackHub:t.slackHub}:{}),o=op(e),i=Object.keys(r).filter((a)=>Lk(Ga(o,a)));if(i.length&&!t.force)return{ok:!1,error:`refusing to overwrite existing files in ${o} (pass --force to replace them)`,existing:i};for(let[a,c]of Object.entries(r)){let d=Ga(o,a);Nk(Ga(d,".."),{recursive:!0}),Mk(d,c)}return{ok:!0,dir:o,name:s,written:Object.keys(r),token:n(32).toString("hex")}}function cp(e,t=process.cwd()){let n=e.dir.startsWith(`${t}/`)?e.dir.slice(t.length+1):e.dir;return[`Created ${e.dir} (worker "${e.name}"):`,...e.written.map((s)=>` ${s}`),"","RELAY_TOKEN (generated now, not saved anywhere — copy it):",` ${e.token}`,"","Next steps:",`0. cd ${n}`,ip(e.name,e.token)].join(`
320
+ `)}async function lp(e,t,n=fetch,s=1e4){if(!e||!t)return{code:2,out:"slack relay health: set SLACK_RELAY_URL and SLACK_RELAY_TOKEN (or pass --url / --token)"};let r=`${e.replace(/\/+$/,"")}/health`;try{let o=await n(r,{headers:{authorization:`Bearer ${t}`},signal:AbortSignal.timeout(s)}),i=await o.text();if(o.status===401)return{code:1,out:"slack relay health: 401 unauthorized — SLACK_RELAY_TOKEN does not match the relay's RELAY_TOKEN secret"};if(!o.ok)return{code:1,out:`slack relay health: HTTP ${o.status} from ${r}${i?`: ${i.slice(0,200)}`:""}`};let a;try{a=JSON.parse(i)}catch{return{code:1,out:`slack relay health: not a slack-hub relay (non-JSON reply from ${r})`}}return{code:a.ok===!0?0:1,out:JSON.stringify(a,null,2)}}catch(o){return{code:1,out:`slack relay health: cannot reach ${r}: ${o instanceof Error?o.message:String(o)}`}}}import{spawn as Yk}from"node:child_process";import{constants as up}from"node:os";var Gk=["processing","active","suspended","closed"];function dp(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?Hr():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 fp(e){if(e!==void 0&&(!e.trim()||[...e].length>200))throw Error("--title must contain 1–200 characters.")}async function pp(e,t,n){let{ref:s,threadTs:r}=n(t);if(!r||!/^\d{10}\.\d{6}$/.test(r))throw Error("Target must include a thread root: C00000001:1700000000.000100, #channel:ts, or a message permalink.");return{channel_id:await Qr(e,s),thread_ts:r}}function Va(e,t){console.error(`agent: ${e}: ${t instanceof Error?t.message:"request failed"}`)}async function Xk(e,t,n,s){let r,o,i,a,c,d=!1,f=!1,p=1,g=(w)=>{if(o)return;if(o=w,d=!0,r&&r.exitCode===null&&r.signalCode===null)r.kill(w),i=setTimeout(()=>r?.kill("SIGKILL"),5000)},y=()=>g("SIGINT"),k=()=>g("SIGTERM");process.on("SIGINT",y),process.on("SIGTERM",k);try{if(f=!0,await Ws(e,t,"processing"),!d&&s.title!==void 0)await ya(e,t,s.title);if(!d){r=Yk(n[0],n.slice(1),{stdio:"inherit"});let w=new Promise((u)=>{r.once("error",()=>{console.error("agent: could not start command"),u(127)}),r.once("exit",(l,h)=>{u(l??(h?128+up.signals[h]:1))})});a=setInterval(()=>{if(d||c)return;c=Ws(e,t,"processing").then(()=>{}).catch((u)=>Va("heartbeat failed; retrying on next tick",u)).finally(()=>{c=void 0})},s.every*1000),p=await w}}catch(w){Va("could not start agent session",w)}finally{if(d=!0,clearInterval(a),clearTimeout(i),await c,f)try{await Ws(e,t,s.close?"closed":"active")}catch(w){if(Va("final status clear failed",w),p===0)p=1}process.removeListener("SIGINT",y),process.removeListener("SIGTERM",k)}return o?128+up.signals[o]:p}function hp(e,t){let n=(s)=>s.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",(s)=>n(s).positional("status",{type:"string",choices:Gk,demandOption:!0}),async(s)=>{fp(s.title);let r=dp(s["bot-token-env"]),o=await pp(r,s.target,t);if(await Ws(r,o,s.status),s.title!==void 0)await ya(r,o,s.title)}).command("run <target>","Keep a thread working while a command runs: run <target> -- <command...>",(s)=>n(s).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(s)=>{if(fp(s.title),!Number.isFinite(s.every)||s.every<=0||s.every>=3600)throw Error("--every must be greater than 0 and less than 3600 seconds.");let r=process.argv.indexOf("--"),o=r<0?[]:process.argv.slice(r+1);if(!o[0])throw Error("agent run requires -- <command...>");let i=dp(s["bot-token-env"]),a=await pp(i,s.target,t);process.exitCode=await Xk(i,a,o,{every:s.every,close:s.close,...s.title!==void 0?{title:s.title}:{}})}).demandCommand(1,"Choose agent status or agent run.")}import{existsSync as gp}from"node:fs";import{join as mp}from"node:path";var Vk="slack-hub",yp="slack-term";function ln(e,t=process.env){return t[`SLACK_HUB_${e}`]??t[`SLACK_TERM_${e}`]}function Zk(e,t){return!gp(e)&&gp(t)?t:e}function Za(e){return Zk(mp(e,Vk),mp(e,yp))}function bp(e,t=process.env){if(e!==yp||/^(1|true|yes|on)$/i.test(ln("NO_RENAME_NOTICE",t)??""))return;return"slack: [deprecated] the slack-term npm package is now slack-hub and will stop being published. Switch: npm uninstall -g slack-term && npm install -g slack-hub (same `slack` command, settings carry over). Silence: SLACK_HUB_NO_RENAME_NOTICE=1"}var Qa={name:"slack-term",version:"1.58.0",repository:{type:"git",url:"https://github.com/snomiao/slack-hub.git"},bugs:{url:"https://github.com/snomiao/slack-hub/issues"},devDependencies:{"@semantic-release/commit-analyzer":"^13","@semantic-release/github":"^12","@semantic-release/npm":"^13","@semantic-release/release-notes-generator":"^14","@types/bun":"latest","@types/node":"^22","@types/yargs":"^17.0.35","@vitest/coverage-istanbul":"4.1.11","semantic-release":"^24",tsrs:"0.25.0-ts7.1.0-beta",typescript:"^5.6",vitest:"4.1.11"},bin:{slack:"./ts/cli.ts"},exports:{"./worker":"./worker/src/index.ts","./package.json":"./package.json"},description:"DEPRECATED: renamed to slack-hub — npm i -g slack-hub. Slack CLI — read activity/news/mentions, search, send messages with a confirm-hash safety gate.",engines:{node:">=18"},files:["ts/","locales/","dist/","worker/src/","README.md","SKILL.md","LICENSE"],homepage:"https://github.com/snomiao/slack-hub",keywords:["slack","cli","messaging","agent","terminal"],license:"MIT",overrides:{"@semantic-release/npm":"^13","@semantic-release/github":"^12"},publishConfig:{access:"public",bin:{slack:"./dist/cli.js"}},scripts:{dev:"bun run ts/cli.ts",build:"bun build ts/cli.ts --target=node --outfile dist/cli.js --minify",typecheck:"tsrs --noEmit","typecheck:tsc":"tsc --noEmit","typecheck:worker":"bun install --cwd worker --frozen-lockfile && tsrs --noEmit -p worker && tsrs --noEmit -p worker/test","test:worker":"bun install --cwd worker --frozen-lockfile && cd worker && node node_modules/vitest/vitest.mjs run",test:"bun test tests/ --timeout 90000 --parallel=2","test:watch":"bun test tests/ --timeout 90000 --isolate --watch","test:parity":"bash tests/parity.sh",record:"bun run tests/record.ts",anonymize:"bun run tests/anonymize.ts","scan-pii":"bash .githooks/pre-commit","scan-pii:all":"bash .githooks/pre-commit --all",prepare:"git config core.hooksPath .githooks 2>/dev/null || true",prepublishOnly:"bun run scan-pii:all && bun run typecheck && bun run build","test:coverage":"vitest run --coverage --exclude tests/parity.test.ts --exclude 'tests/parity/**' --no-file-parallelism"},type:"module",dependencies:{yargs:"^18.0.0"},peerDependencies:{"@cloudflare/workers-types":"^4"},peerDependenciesMeta:{"@cloudflare/workers-types":{optional:!0}},rustify:{mode:"hybrid",bins:{slack:"slack"},rootEnv:"SLACK_HUB_PACKAGE_ROOT"}};import{readdirSync as h0,readFileSync as g0,statSync as m0}from"node:fs";import{join as ac}from"node:path";import{fileURLToPath as y0}from"node:url";import{closeSync as e0,existsSync as wp,mkdirSync as Dp,openSync as t0,readFileSync as yo,realpathSync as n0,renameSync as s0,statSync as nc,unlinkSync as kp,writeFileSync as r0}from"node:fs";import{homedir as xp}from"node:os";import{dirname as sc,join as pt,resolve as ec}from"node:path";function Gs(){return Ae("HOME")??jr(pt(xp(),".config"))}function bo(e=process.cwd()){let t=ec(e);for(;;){for(let s of[kt,Dt]){let r=pt(t,s);try{if(nc(r).isDirectory())return{dir:r,global:!1}}catch{}}let n=sc(t);if(n===t)break;t=n}return{dir:Gs(),global:!0}}function Bn(e,t){Dp(sc(e),{recursive:!0});let n=`${e}.tmp-${process.pid}-${Date.now()}`;r0(n,t,{mode:384}),s0(n,e)}function o0(e,t,n=1e4,s=5000){let r=`${e}.lock`;Dp(sc(r),{recursive:!0});let o=Date.now()+s;for(;;)try{e0(t0(r,"wx"));break}catch(i){if(i.code!=="EEXIST")throw i;try{if(Date.now()-nc(r).mtimeMs>n){kp(r);continue}}catch{continue}if(Date.now()>o)throw Error(`${r} is held by another writer`);Bun.sleepSync(25)}try{return t()}finally{try{kp(r)}catch{}}}function i0(e){if(!e||typeof e!=="object")return;let t=e;if(typeof t.channel!=="string"||!t.channel)return;let n={channel:t.channel};if(typeof t.thread_ts==="string"&&/^\d{10}\.\d{6}$/.test(t.thread_ts))n.thread_ts=t.thread_ts;if(typeof t.added==="string")n.added=t.added;if(typeof t.note==="string")n.note=t.note;return n}function un(e){let t;try{t=Bun.YAML.parse(yo(e,"utf8"))}catch(r){if(r.code==="ENOENT")return{};throw Error(`${e}: ${r instanceof Error?r.message:String(r)}`)}if(!t||typeof t!=="object")return{};let n=t,s={};if(typeof n.prefix==="string"&&n.prefix.trim())s.prefix=n.prefix.trim();else if(Array.isArray(n.prefix)&&n.prefix.length===1&&typeof n.prefix[0]==="string")s.prefix=`[${n.prefix[0]}]`;if(typeof n.channel==="string"&&n.channel)s.channel=n.channel;if(typeof n.as_bot==="boolean")s.as_bot=n.as_bot;if(n.restrict_to_subscriptions===!0)s.restrict_to_subscriptions=!0;if(Array.isArray(n.auto_subscribe))s.auto_subscribe=n.auto_subscribe.filter((r)=>typeof r==="string");if(typeof n.nudge_after_min==="number"&&n.nudge_after_min>0)s.nudge_after_min=n.nudge_after_min;if(typeof n.owner==="string"&&n.owner)s.owner=n.owner;if(n.subscriptions&&typeof n.subscriptions==="object"){let r={};for(let[o,i]of Object.entries(n.subscriptions)){let a=i0(i);if(a&&Sp(o))r[o]=a}s.subscriptions=r}return s}function rc(e){let t=un(pt(e.dir,"settings.yml")),n=un(pt(e.dir,"settings.local.yml"));if(delete n.restrict_to_subscriptions,delete n.auto_subscribe,delete n.owner,t.restrict_to_subscriptions)delete n.subscriptions,delete n.prefix,delete n.as_bot,delete n.channel;let s={...t.subscriptions,...n.subscriptions},r={...t,...n};if(Object.keys(s).length)r.subscriptions=s;else delete r.subscriptions;return r}var a0=/^[a-z0-9][a-z0-9._-]{0,63}$/;function Sp(e){return a0.test(e)&&!/^\d{10}\.\d{6}$/.test(e)}function _p(e){let t=un(pt(e.dir,"settings.yml")),n=t.subscriptions??{},s=t.restrict_to_subscriptions?{}:un(pt(e.dir,"settings.local.yml")).subscriptions??{},r=[];for(let[o,i]of Object.entries(n))if(!s[o])r.push({...i,name:o,scope:e,file:"settings.yml"});for(let[o,i]of Object.entries(s))r.push({...i,name:o,scope:e,file:"settings.local.yml"});return r.sort((o,i)=>o.name.localeCompare(i.name))}var c0="# Written by `slack alias set/unset`; wins over settings.yml. Safe to edit by hand.\n";function l0(e){try{let t=yo(e,"utf8").split(`
320
321
  `),n=[];for(let s of t)if(s.startsWith("#")||!s.trim()&&n.length)n.push(s);else break;return n.length?n.join(`
321
322
  `).replace(/\n*$/,`
322
- `):""}catch{return""}}function F0(e,t,n){let s=ft(e.dir,t?"settings.yml":"settings.local.yml");E0(s,()=>{let r=t?T0(s):A0,o={};try{let i=Bun.YAML.parse(io(s,"utf8"));if(i&&typeof i==="object"&&!Array.isArray(i))o=i}catch(i){if(i.code!=="ENOENT")throw Error(`${s}: ${i instanceof Error?i.message:String(i)}`)}n(o),Pn(s,r+Bun.YAML.stringify(o,null,2)+`
323
- `)})}function sp(e){return cn(ft(e.dir,"settings.yml")).restrict_to_subscriptions===!0}function O0(e,t=process.cwd()){if(!sp(e))return;let n=cn(ft(e.dir,"settings.yml")).owner;if(!n)return`${e.dir} is restricted and names no \`owner\` in settings.yml: nobody may write it with --shared (edit the file)`;let s=(i)=>{try{return x0(Wa(i))}catch{return Wa(i)}},r=s(n.replace(/^~(?=\/|$)/,ep())),o=s(t);if(o===r||o.startsWith(r.endsWith("/")?r:r+"/"))return;return`${e.dir} is owned by ${n}: --shared writes run only from under that directory`}function rp(e,t,n,s={}){let r=typeof s==="boolean"?{shared:s}:s,o=r.shared===!0;if(!tp(t))throw Error(`invalid alias name "${t}" (a-z 0-9 . _ -, at most 64, not a bare ts)`);if(!o&&sp(e))throw new Ua(e);if(o&&!r.asOwner){let l=O0(e,r.cwd);if(l)throw new Ua(e,l)}let i=np(e).find((l)=>l.name===t);return F0(e,o,(l)=>{let u=l.subscriptions&&typeof l.subscriptions==="object"?l.subscriptions:{};u[t]={channel:n.channel,...n.thread_ts?{thread_ts:n.thread_ts}:{},added:n.added??new Date().toISOString(),...n.note?{note:n.note}:{}},l.subscriptions=u}),i}class Ua extends Error{constructor(e,t){super(t??`${e.dir} is restricted (restrict_to_subscriptions in settings.yml): only its owner adds subscriptions, with \`slack alias set --shared\` run from the owner's directory`)}}function R0(){return ft(Js(),"scopes")}function I0(){try{return io(R0(),"utf8").split(`
324
- `).map((e)=>e.trim()).filter((e)=>e&&!e.startsWith("#"))}catch{return[]}}function Ha(){let e=[];for(let s of I0())try{if(Ja(s).isDirectory())e.push({dir:s,global:!1})}catch{}let t=Js();if((Vf(ft(t,"settings.yml"))||Vf(ft(t,"settings.local.yml")))&&!e.some((s)=>s.dir===t))e.push({dir:t,global:!0});return e}function za(e,t,n=Ha()){let s=[];for(let r of n)for(let o of np(r))if(o.channel===e&&(o.thread_ts===void 0||o.thread_ts===t))s.push(o);return s}var ap=N0(new URL("../locales/",import.meta.url)),op=new Map;function ip(e){let t;try{t=L0(e).mtimeMs}catch{return}let n=op.get(e);if(n&&n.mtimeMs===t)return n.pack;let s;try{let r=JSON.parse(P0(e,"utf8"));s=r&&typeof r.lang==="string"?r:void 0}catch{s=void 0}return op.set(e,{mtimeMs:t,pack:s}),s}function cp(){let e=ao();return e.global?void 0:Ya(e.dir,"locales")}function M0(){let e=new Set;for(let t of[ap,cp()]){if(!t)continue;try{for(let n of v0(t))if(n.endsWith(".json"))e.add(n.slice(0,-5))}catch{}}return[...e].sort()}function co(e){let t=ip(Ya(ap,`${e}.json`)),n=cp(),s=n?ip(Ya(n,`${e}.json`)):void 0;if(!s)return t;if(!t)return s;return{...t,...s,ask:{...t.ask,...s.ask},choice_patterns:s.choice_patterns??t.choice_patterns??[]}}function lo(e,t,n={}){let s=co(e)?.ask??{},r=s[t]??s[`${t} (WIRE)`]??co("en")?.ask?.[t]??co("en")?.ask?.[`${t} (WIRE)`];if(r===void 0)throw Error(`language pack ${e}: no ask.${t}`);return r.replace(/\{(\w+)\}/g,(o,i)=>(i in n)?String(n[i]):o)}function lp(){let e=[];for(let t of M0())for(let n of co(t)?.choice_patterns??[])try{e.push({lang:t,re:new RegExp(n,"iu")})}catch{}return e}var Fe=[{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"}],jt=Fe.length,rt="question",ln=`:${rt}: `,Wt="heavy_plus_sign",uo=`:${Wt}: `,pp=[Wt,rt],un="information_source",fo=`:${un}: `,Tt=["ja","en"];function Va(e,t=process.env){for(let[o,i]of[[e.flag,"flag"],[Pe("LANG",t),"env"]]){if(o===void 0||o.trim()==="")continue;let l=o.trim().toLowerCase();return Tt.includes(l)?{lang:l,source:i}:null}let n=(e.readerLocales??[]).map(up);if(n.length&&n[0]&&n.every((o)=>o===n[0]))return{lang:n[0],source:"readers"};let s=Za((e.content??[]).join(`
325
- `));if(s)return{lang:s,source:"content"};let r=up(t.LC_ALL||t.LC_MESSAGES||t.LANG);if(r)return{lang:r,source:"system"};return{lang:"en",source:"default"}}function up(e){let t=(e??"").toLowerCase();return Tt.find((n)=>t===n||/^[_.\-@]/.test(t.slice(n.length))&&t.startsWith(n))??null}function Za(e){let t=e.replace(/<[^>\s]*>/g," ").replace(/https?:\/\/\S+/g," ").replace(/:[a-z0-9_+-]+:/g," ");if(/[\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Han}]/u.test(t))return"ja";if(/\p{Script=Latin}/u.test(t))return"en";return null}var je={get ja(){return dp("ja")},get en(){return dp("en")}};function dp(e){let t=(n,s)=>lo(e,n,s);return{instructionReactionThread:t("instructionReactionThread"),instructionReactionHere:t("instructionReactionHere"),instructionTextThread:t("instructionTextThread"),instructionTextHere:t("instructionTextHere"),overflowNote:t("overflowNote"),otherThread:`${uo}${t("otherThread")}`,otherHere:`${uo}${t("otherHere")}`,explainLine:`${fo}${t("explainLine")}`,explainNote:`${fo}${t("explainNote")}`,invalidPrefix:t("invalidPrefix"),answeredVia:(n,s)=>t("answeredVia",{how:n,who:s?` (${s})`:""}),howReaction:(n)=>t("howReaction",{glyph:n}),howReply:t("howReply"),howReplyN:(n)=>t("howReplyN",{n}),voidStamp:(n)=>t("voidStamp",{reason:n?`: ${n}`:""}),supersededBy:(n)=>t("supersededBy",{link:n})}}var B0=Tt.flatMap((e)=>[je[e].otherThread,je[e].otherHere].map((t)=>ln+t.slice(uo.length)));function hp(e){if(e===void 0)return null;if(e.startsWith(uo)||e.startsWith("➕ "))return Wt;if(e.startsWith(ln)||e.startsWith("❓ "))return rt;return null}function j0(e){return e!==void 0&&(e.startsWith(fo)||e.startsWith("ℹ️ "))}function W0(e,t){if(e===void 0)return!1;return(e.startsWith("ℹ️ ")?fo+e.slice(3):e)===t.explainLine}var po="_";function gp(e){if(e===void 0||!e.endsWith(po))return null;return Tt.find((t)=>e.startsWith(je[t].invalidPrefix))??null}function ho(e){let t=e.split(`
326
- `),n=t[t.length-2];if(!gp(n))return[];return[...n.matchAll(/<@([UW][A-Z0-9]+)>/g)].map((s)=>s[1])}function go(e,t,n="ja"){let s=e.split(`
327
- `);if(s.length<2)return e;if(ho(e).length)s.splice(s.length-2,1);if(t.length)s.splice(s.length-1,0,`${je[n].invalidPrefix}${t.map((o)=>`<@${o}>`).join(", ")}${po}`);let r=s.join(`
328
- `);return r===e?e:r}function mo(e){return typeof e==="string"&&Tt.some((t)=>je[t].explainNote===e.trim())}function fp(e){return gp(e)!==null}var Qa="white_check_mark",qs=`:${Qa}: `,ec="no_entry_sign",Xa=`:${ec}: `,U0=/^【[^】]*(?:作废|作廢|superseded|void)[^】]*】/i;function yo(e){return`:${Fe[e].name}:`}function mp(e,t){let n=Fe[t];for(let s of[yo(t),n.glyph]){if(e.startsWith(`${s} `))return e.slice(s.length+1);if(e===s)return""}return null}function J0(e){return Fe.some((t,n)=>mp(e,n)!==null)}function Me(e){return e.replace(/\s*\n\s*/g," ")}function tc(e,t,n,s,r,o="ja",i=!1){let l=je[o],u=[`${ln}*${e}*`];if(t)u.push("",t);if(n.length){if(u.push(""),u.push(...n.map((f,a)=>`${yo(a)} ${Me(f)}`)),u.push(r?l.otherThread:l.otherHere),i)u.push(l.explainLine);if(s.length)u.push(""),u.push(...s.map((f,a)=>`(${a+11}) ${Me(f)}`)),u.push(l.overflowNote);u.push(""),u.push(r?l.instructionReactionThread:l.instructionReactionHere)}else{if(u.push(""),i)u.push(l.explainLine,"");u.push(r?l.instructionTextThread:l.instructionTextHere)}return u.join(`
329
- `)}function yp(e,t,n,s="ja",r){let o=t.answer.split(`
330
- `).map((l)=>`> ${l}`).join(`
331
- `),i=`${qs}*${e}*
332
- ${je[s].answeredVia(t.how,n)}
323
+ `):""}catch{return""}}function u0(e,t,n){let s=pt(e.dir,t?"settings.yml":"settings.local.yml");o0(s,()=>{let r=t?l0(s):c0,o={};try{let i=Bun.YAML.parse(yo(s,"utf8"));if(i&&typeof i==="object"&&!Array.isArray(i))o=i}catch(i){if(i.code!=="ENOENT")throw Error(`${s}: ${i instanceof Error?i.message:String(i)}`)}n(o),Bn(s,r+Bun.YAML.stringify(o,null,2)+`
324
+ `)})}function Ep(e){return un(pt(e.dir,"settings.yml")).restrict_to_subscriptions===!0}function d0(e,t=process.cwd()){if(!Ep(e))return;let n=un(pt(e.dir,"settings.yml")).owner;if(!n)return`${e.dir} is restricted and names no \`owner\` in settings.yml: nobody may write it with --shared (edit the file)`;let s=(i)=>{try{return n0(ec(i))}catch{return ec(i)}},r=s(n.replace(/^~(?=\/|$)/,xp())),o=s(t);if(o===r||o.startsWith(r.endsWith("/")?r:r+"/"))return;return`${e.dir} is owned by ${n}: --shared writes run only from under that directory`}function $p(e,t,n,s={}){let r=typeof s==="boolean"?{shared:s}:s,o=r.shared===!0;if(!Sp(t))throw Error(`invalid alias name "${t}" (a-z 0-9 . _ -, at most 64, not a bare ts)`);if(!o&&Ep(e))throw new tc(e);if(o&&!r.asOwner){let a=d0(e,r.cwd);if(a)throw new tc(e,a)}let i=_p(e).find((a)=>a.name===t);return u0(e,o,(a)=>{let c=a.subscriptions&&typeof a.subscriptions==="object"?a.subscriptions:{};c[t]={channel:n.channel,...n.thread_ts?{thread_ts:n.thread_ts}:{},added:n.added??new Date().toISOString(),...n.note?{note:n.note}:{}},a.subscriptions=c}),i}class tc extends Error{constructor(e,t){super(t??`${e.dir} is restricted (restrict_to_subscriptions in settings.yml): only its owner adds subscriptions, with \`slack alias set --shared\` run from the owner's directory`)}}function f0(){return pt(Gs(),"scopes")}function p0(){try{return yo(f0(),"utf8").split(`
325
+ `).map((e)=>e.trim()).filter((e)=>e&&!e.startsWith("#"))}catch{return[]}}function oc(){let e=[];for(let s of p0())try{if(nc(s).isDirectory())e.push({dir:s,global:!1})}catch{}let t=Gs();if((wp(pt(t,"settings.yml"))||wp(pt(t,"settings.local.yml")))&&!e.some((s)=>s.dir===t))e.push({dir:t,global:!0});return e}function ic(e,t,n=oc()){let s=[];for(let r of n)for(let o of _p(r))if(o.channel===e&&(o.thread_ts===void 0||o.thread_ts===t))s.push(o);return s}var Tp=y0(new URL("../locales/",import.meta.url)),Cp=new Map;function Ap(e){let t;try{t=m0(e).mtimeMs}catch{return}let n=Cp.get(e);if(n&&n.mtimeMs===t)return n.pack;let s;try{let r=JSON.parse(g0(e,"utf8"));s=r&&typeof r.lang==="string"?r:void 0}catch{s=void 0}return Cp.set(e,{mtimeMs:t,pack:s}),s}function Fp(){let e=bo();return e.global?void 0:ac(e.dir,"locales")}function b0(){let e=new Set;for(let t of[Tp,Fp()]){if(!t)continue;try{for(let n of h0(t))if(n.endsWith(".json"))e.add(n.slice(0,-5))}catch{}}return[...e].sort()}function wo(e){let t=Ap(ac(Tp,`${e}.json`)),n=Fp(),s=n?Ap(ac(n,`${e}.json`)):void 0;if(!s)return t;if(!t)return s;return{...t,...s,ask:{...t.ask,...s.ask},choice_patterns:s.choice_patterns??t.choice_patterns??[]}}function ko(e,t,n={}){let s=wo(e)?.ask??{},r=s[t]??s[`${t} (WIRE)`]??wo("en")?.ask?.[t]??wo("en")?.ask?.[`${t} (WIRE)`];if(r===void 0)throw Error(`language pack ${e}: no ask.${t}`);return r.replace(/\{(\w+)\}/g,(o,i)=>(i in n)?String(n[i]):o)}function Op(){let e=[];for(let t of b0())for(let n of wo(t)?.choice_patterns??[])try{e.push({lang:t,re:new RegExp(n,"iu")})}catch{}return e}var Re=[{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"}],Kt=Re.length,ot="question",dn=`:${ot}: `,qt="heavy_plus_sign",Do=`:${qt}: `,Pp=[qt,ot],fn="information_source",xo=`:${fn}: `,It=["ja","en"];function uc(e,t=process.env){for(let[o,i]of[[e.flag,"flag"],[Ae("LANG",t),"env"]]){if(o===void 0||o.trim()==="")continue;let a=o.trim().toLowerCase();return It.includes(a)?{lang:a,source:i}:null}let n=(e.readerLocales??[]).map(Ip);if(n.length&&n[0]&&n.every((o)=>o===n[0]))return{lang:n[0],source:"readers"};let s=dc((e.content??[]).join(`
326
+ `));if(s)return{lang:s,source:"content"};let r=Ip(t.LC_ALL||t.LC_MESSAGES||t.LANG);if(r)return{lang:r,source:"system"};return{lang:"en",source:"default"}}function Ip(e){let t=(e??"").toLowerCase();return It.find((n)=>t===n||/^[_.\-@]/.test(t.slice(n.length))&&t.startsWith(n))??null}function dc(e){let t=e.replace(/<[^>\s]*>/g," ").replace(/https?:\/\/\S+/g," ").replace(/:[a-z0-9_+-]+:/g," ");if(/[\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Han}]/u.test(t))return"ja";if(/\p{Script=Latin}/u.test(t))return"en";return null}var We={get ja(){return Rp("ja")},get en(){return Rp("en")}};function Rp(e){let t=(n,s)=>ko(e,n,s);return{instructionReactionThread:t("instructionReactionThread"),instructionReactionHere:t("instructionReactionHere"),instructionTextThread:t("instructionTextThread"),instructionTextHere:t("instructionTextHere"),overflowNote:t("overflowNote"),otherThread:`${Do}${t("otherThread")}`,otherHere:`${Do}${t("otherHere")}`,explainLine:`${xo}${t("explainLine")}`,explainNote:`${xo}${t("explainNote")}`,invalidPrefix:t("invalidPrefix"),answeredVia:(n,s)=>t("answeredVia",{how:n,who:s?` (${s})`:""}),howReaction:(n)=>t("howReaction",{glyph:n}),howReply:t("howReply"),howReplyN:(n)=>t("howReplyN",{n}),voidStamp:(n)=>t("voidStamp",{reason:n?`: ${n}`:""}),supersededBy:(n)=>t("supersededBy",{link:n})}}var w0=It.flatMap((e)=>[We[e].otherThread,We[e].otherHere].map((t)=>dn+t.slice(Do.length)));function Lp(e){if(e===void 0)return null;if(e.startsWith(Do)||e.startsWith("➕ "))return qt;if(e.startsWith(dn)||e.startsWith("❓ "))return ot;return null}function k0(e){return e!==void 0&&(e.startsWith(xo)||e.startsWith("ℹ️ "))}function D0(e,t){if(e===void 0)return!1;return(e.startsWith("ℹ️ ")?xo+e.slice(3):e)===t.explainLine}var So="_";function Np(e){if(e===void 0||!e.endsWith(So))return null;return It.find((t)=>e.startsWith(We[t].invalidPrefix))??null}function _o(e){let t=e.split(`
327
+ `),n=t[t.length-2];if(!Np(n))return[];return[...n.matchAll(/<@([UW][A-Z0-9]+)>/g)].map((s)=>s[1])}function Eo(e,t,n="ja"){let s=e.split(`
328
+ `);if(s.length<2)return e;if(_o(e).length)s.splice(s.length-2,1);if(t.length)s.splice(s.length-1,0,`${We[n].invalidPrefix}${t.map((o)=>`<@${o}>`).join(", ")}${So}`);let r=s.join(`
329
+ `);return r===e?e:r}function $o(e){return typeof e==="string"&&It.some((t)=>We[t].explainNote===e.trim())}function vp(e){return Np(e)!==null}var fc="white_check_mark",Vs=`:${fc}: `,pc="no_entry_sign",lc=`:${pc}: `,x0=/^【[^】]*(?:作废|作廢|superseded|void)[^】]*】/i;function Co(e){return`:${Re[e].name}:`}function Mp(e,t){let n=Re[t];for(let s of[Co(t),n.glyph]){if(e.startsWith(`${s} `))return e.slice(s.length+1);if(e===s)return""}return null}function S0(e){return Re.some((t,n)=>Mp(e,n)!==null)}function Be(e){return e.replace(/\s*\n\s*/g," ")}function hc(e,t,n,s,r,o="ja",i=!1){let a=We[o],c=[`${dn}*${e}*`];if(t)c.push("",t);if(n.length){if(c.push(""),c.push(...n.map((d,f)=>`${Co(f)} ${Be(d)}`)),c.push(r?a.otherThread:a.otherHere),i)c.push(a.explainLine);if(s.length)c.push(""),c.push(...s.map((d,f)=>`(${f+11}) ${Be(d)}`)),c.push(a.overflowNote);c.push(""),c.push(r?a.instructionReactionThread:a.instructionReactionHere)}else{if(c.push(""),i)c.push(a.explainLine,"");c.push(r?a.instructionTextThread:a.instructionTextHere)}return c.join(`
330
+ `)}function Bp(e,t,n,s="ja",r){let o=t.answer.split(`
331
+ `).map((a)=>`> ${a}`).join(`
332
+ `),i=`${Vs}*${e}*
333
+ ${We[s].answeredVia(t.how,n)}
333
334
 
334
335
  ${o}`;if(r?.body)i+=`
335
336
 
336
337
  ${r.body}`;if(r?.chosenLine)i+=`
337
338
 
338
- ${r.chosenLine}`;return i}function bp(e,t){let n=Ft(e);if(n.kind!=="open")return;let s={};if(n.body)s.body=n.body;if(t!==void 0&&t>=1){if(t<=n.reactable.length)s.chosenLine=`${yo(t-1)} ${Me(n.reactable[t-1])}`;else if(t-jt<=n.overflow.length&&t>jt)s.chosenLine=`(${t}) ${Me(n.overflow[t-jt-1])}`}return s.body||s.chosenLine?s:void 0}function wp(e,t,n="ja",s,r){let o=je[n],i=`${Xa}*${e}*
339
- ${o.voidStamp(Me(t.trim()))}`;if(r)i+=`
339
+ ${r.chosenLine}`;return i}function jp(e,t){let n=Rt(e);if(n.kind!=="open")return;let s={};if(n.body)s.body=n.body;if(t!==void 0&&t>=1){if(t<=n.reactable.length)s.chosenLine=`${Co(t-1)} ${Be(n.reactable[t-1])}`;else if(t-Kt<=n.overflow.length&&t>Kt)s.chosenLine=`(${t}) ${Be(n.overflow[t-Kt-1])}`}return s.body||s.chosenLine?s:void 0}function Wp(e,t,n="ja",s,r){let o=We[n],i=`${lc}*${e}*
340
+ ${o.voidStamp(Be(t.trim()))}`;if(r)i+=`
340
341
  ${o.supersededBy(r)}`;if(s)i+=`
341
342
 
342
- ${s}`;return i}function kp(e){if(!e.startsWith(ln))return null;let t=e.slice(ln.length),n=t.match(/^\*([\s\S]+?)\*(?=\s|$)/);if(!n)return null;let s=t.slice(n[0].length),r=!1;for(let o of Tt){let i=je[o];for(let u of[i.instructionReactionThread,i.instructionReactionHere,i.instructionTextThread,i.instructionTextHere])if(s.includes(u))r=!0;for(let u of[i.instructionReactionThread,i.instructionReactionHere,i.instructionTextThread,i.instructionTextHere,i.overflowNote,i.otherThread,i.otherHere,...B0,i.explainLine])s=s.split(u).join(" ");let l=s.indexOf(i.invalidPrefix);if(l>=0){let u=s.indexOf(po,l+i.invalidPrefix.length);s=s.slice(0,l)+" "+(u>=0?s.slice(u+po.length):"")}}if(!r)return null;return{question:n[1],body:s.replace(/[ \t]{3,}/g," ").trim()}}function Dp(e){if(!e[0]?.startsWith(qs))return-1;let t=(n)=>!!n&&(n.startsWith("> ")||n.startsWith("&gt; "));for(let n=1;n+2<e.length;n++){let s=e[n];if(s.length>1&&s.startsWith("_")&&s.endsWith("_")&&e[n+1]===""&&t(e[n+2]))return n}return-1}function xp(e){let t=e.split(`
343
- `),n=Dp(t),r=((n>0?t[n]:t[1])??"").match(/^_(?:返信|Answered by reply)(?: \((\d+)\))?/);if(!r)return{byReply:!1};return r[1]?{byReply:!0,n:Number(r[1])}:{byReply:!0}}function Ks(e){return e.replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&")}function Hs(e){if(!e.trim())return"the message body is empty (it may be a bot post or an attachment-only message)";let t=e.split(`
344
- `),n=t[t.length-1]??"";if(e.startsWith(qs))return"it is marked answered, but the quoted answer text is missing";if(!/_$/.test(n))return"it does not end with the `ask` instructions line — this message was not posted by `slack ask`, or its text has been edited";if(!t[0].startsWith(ln)&&!t[0].startsWith("*"))return"it does not start with the (bold) question — its text may have been edited";return"cannot read the list of choices — they are not numbered consecutively from 1, or the text has been edited"}function Ft(e){let t=e.split(`
345
- `),n=(m)=>e.startsWith(`${m}*`)&&t.some((w,k)=>k>0&&w.length>1&&w.startsWith("_")&&w.endsWith("_"));if(n(Xa)){let m=t.findIndex((D,E)=>E>0&&D.startsWith("_")&&D.endsWith("_")),w=Ks(t.slice(0,m>0?m:1).join(`
346
- `).slice(Xa.length).replace(/^\*/,"").replace(/\*$/,"")),k=m>0?t[m].replace(/^_|_$/g,""):"",_=m>0?t[m+1]?.match(/^↪ [^::]*[::] (.+)$/)?.[1]:void 0;return _?{kind:"void",question:w,reason:k,supersededBy:_}:{kind:"void",question:w,reason:k}}let s=t[0].match(U0)?e.match(/:question: \*([^\n]*?)\*/):null;if(s)return{kind:"void",question:Ks(s[1]),reason:Ks(t[0])};if(n(qs)){let m=(E)=>E.startsWith("> ")?E.slice(2):E.startsWith("&gt; ")?E.slice(5):null,w=Dp(t),k;if(w>0){k=[];for(let E=w+2;E<t.length;E++){let S=m(t[E]);if(S===null)break;k.push(S)}}else k=t.map(m).filter((E)=>E!==null);let _=Ks(t.slice(0,w>0?w:1).join(`
347
- `).slice(qs.length).replace(/^\*/,"").replace(/\*$/,"")),D=k.map(Ks).join(`
348
- `);if(!D)return{kind:"other"};return{kind:"resolved",question:_,answer:D}}let r=t[t.length-1]??"",o,i,l=Tt.find((m)=>[je[m].instructionReactionThread,je[m].instructionReactionHere,je[m].instructionTextThread,je[m].instructionTextHere].includes(r));if(!l)return{kind:"other"};let u=je[l];o=r===u.instructionReactionThread||r===u.instructionTextThread,i=r===u.instructionReactionThread||r===u.instructionReactionHere;let f=t[0].startsWith(ln)?t[0].slice(ln.length):t[0];if(t[0]=f,!t[0].startsWith("*"))return{kind:"other"};let a=0;while(a<t.length&&!(t[a].endsWith("*")&&(a>0||t[0].length>1)))a++;if(a>=t.length)return{kind:"other"};let c=t.slice(0,a+1).join(`
349
- `).replace(/^\*/,"").replace(/\*$/,""),d=[],p=[],h=t.length-1;if(fp(t[h-1]))h--;let g=!1;if(i){let m=t.length-2;if(fp(t[m]))m--;if(t[m]!=="")return{kind:"other"};if(m--,t[m]===u.overflowNote){m--;while(m>=0&&/^\(\d+\) /.test(t[m]))p.unshift(t[m].replace(/^\(\d+\) /,"")),m--;if(t[m]!=="")return{kind:"other"};m--}if(j0(t[m]))g=!0,m--;if(hp(t[m]))m--;let w=[];while(m>=0){let k=t[m];if(!J0(k))break;w.unshift(k),m--}if(!w.length||w.length>jt)return{kind:"other"};for(let k=0;k<w.length;k++){let _=mp(w[k],k);if(_===null)return{kind:"other"};d.push(_)}if(t[m]!=="")return{kind:"other"};if(m<a+1)return{kind:"other"};h=m;for(let k=0;k<p.length;k++)if(!t.includes(`(${k+11}) ${p[k]}`))return{kind:"other"}}else if(t[h-1]===""&&W0(t[h-2],u)&&t[h-3]===""&&h-3>=a)g=!0,h-=2;let y=t.slice(a+1,h).join(`
350
- `).replace(/^\n+|\n+$/g,"");return{kind:"open",question:c,body:y,reactable:d,overflow:p,threadOnly:o,lang:l,explain:g}}function zs(e){let t=Ft(e);if(t.kind!=="open")return null;if(!t.reactable.length)return rt;let n=e.split(`
351
- `),s=yo(t.reactable.length-1),r=Fe[t.reactable.length-1].glyph,o=-1;for(let i=n.length-1;i>=0;i--)if(n[i].startsWith(`${s} `)||n[i]===s||n[i].startsWith(`${r} `)||n[i]===r){o=i;break}return(o>=0?hp(n[o+1]):null)??rt}function Ga(e){return e.normalize("NFKC").replace(/[*_`~]/g,"").trim().replace(/^[\s"'`「『((\[]+/,"").replace(/[\s"'`」』))\]。..!!??、,]+$/,"").replace(/\s+/g," ").trim().toLowerCase()}function Sp(e,t,n){let s=Array.from({length:n},(o,i)=>i===n-1?t:""),r=nc(e,s);return r.kind==="chosen"&&r.index===n}function nc(e,t){let n=Ga(e);if(!n)return{kind:"none"};let s=t.map(Ga),r=new Set;s.forEach((f,a)=>{if(f&&f===n)r.add(a+1)}),Fe.forEach((f,a)=>{if(a<t.length&&e.trim()===f.glyph)r.add(a+1)});let o=0,i="",l=n.match(/^(\d{1,2})$/);if(l)o=Number(l[1]);else if(l=n.match(/^(\d{1,2})(?:\s*[.)::、。\-\]]\s*|\s+)(.*)$/)){if(o=Number(l[1]),i=Ga(l[2]),!i)return{kind:"none"};if(/^\d+$/.test(i))return{kind:"none"}}if(o>=1&&o<=t.length&&(i===""||i===s[o-1]))r.add(o);let u=[...r].sort((f,a)=>f-a);if(!u.length)return{kind:"none"};if(u.length>1)return{kind:"ambiguous",indexes:u};return{kind:"chosen",index:u[0]}}var Ln={phi:1.618033988749895,minMs:1000,fastMaxMs:5000,fastWindowMs:120000,slowMaxMs:20000};function _p(e,t){let n=t<Ln.fastWindowMs?Ln.fastMaxMs:Ln.slowMaxMs;return Math.min(Math.max(e,Ln.minMs)*Ln.phi,n)}import{closeSync as K0,existsSync as bo,mkdirSync as wo,openSync as q0,readFileSync as Do,realpathSync as H0,renameSync as z0,statSync as sc,unlinkSync as Ep,writeFileSync as Y0}from"node:fs";import{homedir as $p}from"node:os";import{dirname as rc,join as Xe,resolve as ko}from"node:path";var G0=["inbox","archived","outbox","sent"];function Ys(){return Pe("HOME")??Ir(Xe($p(),".config"))}function Ve(e=process.cwd()){let t=ko(e);for(;;){for(let s of[wt,kt]){let r=Xe(t,s);try{if(sc(r).isDirectory())return{dir:r,global:!1}}catch{}}let n=rc(t);if(n===t)break;t=n}return{dir:Ys(),global:!0}}var X0='# .slack-hub/\n\nState for [slack-hub](https://github.com/snomiao/slack-hub) in this directory.\n`slack` uses the nearest `.slack-hub/` walking up from where it runs (like\n`.git`), so everything below this directory shares it. Without one it uses\n~/.config/slack-hub/.\n\nNothing here is committed: `.gitignore` holds `*`.\n\n| Path | What |\n|---|---|\n| `settings.yml` | yours to edit: `prefix` (put in front of every `slack reply`, e.g. `"[design]"`), `channel` (default), `as_bot`, `subscriptions` |\n| `settings.local.yml` | written by `slack alias set/unset`; same keys, wins over `settings.yml` |\n| `inbox/` → `archived/` | one file per incoming message (`slack stream --inbox`): who, where, the text with secrets redacted, a files count, the permalink. Handled = moved to `archived/`, by `slack done` or by a sent outbox reply with `in_reply_to` |\n| `outbox/` → `sent/` | one file per queued reply (`slack outbox add`, redacted); `slack outbox flush` sends them and moves each to `sent/` with its ts and permalink. A failure stays, with `error` and `attempts` |\n\n`restrict_to_subscriptions`, `auto_subscribe` and `nudge_after_min` count only in\n`settings.yml`. With `restrict_to_subscriptions: true`, only `settings.yml`\'s\nsubscriptions count, `slack alias set` refuses (the owner uses `--shared`), and\n`reply` / `outbox flush` refuse any other thread.\n\n`subscriptions` maps an alias to a place:\n\n subscriptions:\n board:\n channel: C00000001\n thread_ts: "1700000000.000100"\n\n## Commands\n\n slack alias ls # the aliases here\n slack alias set <name> <permalink> # name a thread (a reply\'s permalink names its root)\n slack alias unset <name>\n slack read <name> # read the thread\n slack reply <name> \'<text>\' # reply in it, with the prefix, behind the --code gate\n slack reply --to <permalink> \'<text>\' # reply in the thread where that message is\n slack reply <name> --to <permalink> … # refused when that message is in another thread\n slack inbox ls | listen | nudge # what was routed here\n slack done <file|ts> # handled without a reply\n slack outbox add <name> \'<text>\' --in-reply-to <ts>\n slack outbox flush # send the queue (one --code for the batch)\n slack alias who <channel> <ts> # which dirs subscribe a thread\n',V0=`# slack-hub settings for this directory. settings.local.yml (written by
343
+ ${s}`;return i}function Up(e){if(!e.startsWith(dn))return null;let t=e.slice(dn.length),n=t.match(/^\*([\s\S]+?)\*(?=\s|$)/);if(!n)return null;let s=t.slice(n[0].length),r=!1;for(let o of It){let i=We[o];for(let c of[i.instructionReactionThread,i.instructionReactionHere,i.instructionTextThread,i.instructionTextHere])if(s.includes(c))r=!0;for(let c of[i.instructionReactionThread,i.instructionReactionHere,i.instructionTextThread,i.instructionTextHere,i.overflowNote,i.otherThread,i.otherHere,...w0,i.explainLine])s=s.split(c).join(" ");let a=s.indexOf(i.invalidPrefix);if(a>=0){let c=s.indexOf(So,a+i.invalidPrefix.length);s=s.slice(0,a)+" "+(c>=0?s.slice(c+So.length):"")}}if(!r)return null;return{question:n[1],body:s.replace(/[ \t]{3,}/g," ").trim()}}function Jp(e){if(!e[0]?.startsWith(Vs))return-1;let t=(n)=>!!n&&(n.startsWith("> ")||n.startsWith("&gt; "));for(let n=1;n+2<e.length;n++){let s=e[n];if(s.length>1&&s.startsWith("_")&&s.endsWith("_")&&e[n+1]===""&&t(e[n+2]))return n}return-1}function Kp(e){let t=e.split(`
344
+ `),n=Jp(t),r=((n>0?t[n]:t[1])??"").match(/^_(?:返信|Answered by reply)(?: \((\d+)\))?/);if(!r)return{byReply:!1};return r[1]?{byReply:!0,n:Number(r[1])}:{byReply:!0}}function Xs(e){return e.replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&")}function Zs(e){if(!e.trim())return"the message body is empty (it may be a bot post or an attachment-only message)";let t=e.split(`
345
+ `),n=t[t.length-1]??"";if(e.startsWith(Vs))return"it is marked answered, but the quoted answer text is missing";if(!/_$/.test(n))return"it does not end with the `ask` instructions line — this message was not posted by `slack ask`, or its text has been edited";if(!t[0].startsWith(dn)&&!t[0].startsWith("*"))return"it does not start with the (bold) question — its text may have been edited";return"cannot read the list of choices — they are not numbered consecutively from 1, or the text has been edited"}function Rt(e){let t=e.split(`
346
+ `),n=(l)=>e.startsWith(`${l}*`)&&t.some((h,m)=>m>0&&h.length>1&&h.startsWith("_")&&h.endsWith("_"));if(n(lc)){let l=t.findIndex((_,x)=>x>0&&_.startsWith("_")&&_.endsWith("_")),h=Xs(t.slice(0,l>0?l:1).join(`
347
+ `).slice(lc.length).replace(/^\*/,"").replace(/\*$/,"")),m=l>0?t[l].replace(/^_|_$/g,""):"",b=l>0?t[l+1]?.match(/^↪ [^::]*[::] (.+)$/)?.[1]:void 0;return b?{kind:"void",question:h,reason:m,supersededBy:b}:{kind:"void",question:h,reason:m}}let s=t[0].match(x0)?e.match(/:question: \*([^\n]*?)\*/):null;if(s)return{kind:"void",question:Xs(s[1]),reason:Xs(t[0])};if(n(Vs)){let l=(x)=>x.startsWith("> ")?x.slice(2):x.startsWith("&gt; ")?x.slice(5):null,h=Jp(t),m;if(h>0){m=[];for(let x=h+2;x<t.length;x++){let S=l(t[x]);if(S===null)break;m.push(S)}}else m=t.map(l).filter((x)=>x!==null);let b=Xs(t.slice(0,h>0?h:1).join(`
348
+ `).slice(Vs.length).replace(/^\*/,"").replace(/\*$/,"")),_=m.map(Xs).join(`
349
+ `);if(!_)return{kind:"other"};return{kind:"resolved",question:b,answer:_}}let r=t[t.length-1]??"",o,i,a=It.find((l)=>[We[l].instructionReactionThread,We[l].instructionReactionHere,We[l].instructionTextThread,We[l].instructionTextHere].includes(r));if(!a)return{kind:"other"};let c=We[a];o=r===c.instructionReactionThread||r===c.instructionTextThread,i=r===c.instructionReactionThread||r===c.instructionReactionHere;let d=t[0].startsWith(dn)?t[0].slice(dn.length):t[0];if(t[0]=d,!t[0].startsWith("*"))return{kind:"other"};let f=0;while(f<t.length&&!(t[f].endsWith("*")&&(f>0||t[0].length>1)))f++;if(f>=t.length)return{kind:"other"};let p=t.slice(0,f+1).join(`
350
+ `).replace(/^\*/,"").replace(/\*$/,""),g=[],y=[],k=t.length-1;if(vp(t[k-1]))k--;let w=!1;if(i){let l=t.length-2;if(vp(t[l]))l--;if(t[l]!=="")return{kind:"other"};if(l--,t[l]===c.overflowNote){l--;while(l>=0&&/^\(\d+\) /.test(t[l]))y.unshift(t[l].replace(/^\(\d+\) /,"")),l--;if(t[l]!=="")return{kind:"other"};l--}if(k0(t[l]))w=!0,l--;if(Lp(t[l]))l--;let h=[];while(l>=0){let m=t[l];if(!S0(m))break;h.unshift(m),l--}if(!h.length||h.length>Kt)return{kind:"other"};for(let m=0;m<h.length;m++){let b=Mp(h[m],m);if(b===null)return{kind:"other"};g.push(b)}if(t[l]!=="")return{kind:"other"};if(l<f+1)return{kind:"other"};k=l;for(let m=0;m<y.length;m++)if(!t.includes(`(${m+11}) ${y[m]}`))return{kind:"other"}}else if(t[k-1]===""&&D0(t[k-2],c)&&t[k-3]===""&&k-3>=f)w=!0,k-=2;let u=t.slice(f+1,k).join(`
351
+ `).replace(/^\n+|\n+$/g,"");return{kind:"open",question:p,body:u,reactable:g,overflow:y,threadOnly:o,lang:a,explain:w}}function Qs(e){let t=Rt(e);if(t.kind!=="open")return null;if(!t.reactable.length)return ot;let n=e.split(`
352
+ `),s=Co(t.reactable.length-1),r=Re[t.reactable.length-1].glyph,o=-1;for(let i=n.length-1;i>=0;i--)if(n[i].startsWith(`${s} `)||n[i]===s||n[i].startsWith(`${r} `)||n[i]===r){o=i;break}return(o>=0?Lp(n[o+1]):null)??ot}function cc(e){return e.normalize("NFKC").replace(/[*_`~]/g,"").trim().replace(/^[\s"'`「『((\[]+/,"").replace(/[\s"'`」』))\]。..!!??、,]+$/,"").replace(/\s+/g," ").trim().toLowerCase()}function qp(e,t,n){let s=Array.from({length:n},(o,i)=>i===n-1?t:""),r=gc(e,s);return r.kind==="chosen"&&r.index===n}function gc(e,t){let n=cc(e);if(!n)return{kind:"none"};let s=t.map(cc),r=new Set;s.forEach((d,f)=>{if(d&&d===n)r.add(f+1)}),Re.forEach((d,f)=>{if(f<t.length&&e.trim()===d.glyph)r.add(f+1)});let o=0,i="",a=n.match(/^(\d{1,2})$/);if(a)o=Number(a[1]);else if(a=n.match(/^(\d{1,2})(?:\s*[.)::、。\-\]]\s*|\s+)(.*)$/)){if(o=Number(a[1]),i=cc(a[2]),!i)return{kind:"none"};if(/^\d+$/.test(i))return{kind:"none"}}if(o>=1&&o<=t.length&&(i===""||i===s[o-1]))r.add(o);let c=[...r].sort((d,f)=>d-f);if(!c.length)return{kind:"none"};if(c.length>1)return{kind:"ambiguous",indexes:c};return{kind:"chosen",index:c[0]}}var jn={phi:1.618033988749895,minMs:1000,fastMaxMs:5000,fastWindowMs:120000,slowMaxMs:20000};function Hp(e,t){let n=t<jn.fastWindowMs?jn.fastMaxMs:jn.slowMaxMs;return Math.min(Math.max(e,jn.minMs)*jn.phi,n)}function zp(e){let t=String(e??"").trim().toLowerCase();if(["forever","never","inf","infinity"].includes(t))return 1/0;if(/^\d+(\.\d+)?$/.test(t))return Number(t);let n=t.match(/^(\d+(?:\.\d+)?)(s|m|h|d)$/);return n?Number(n[1])*{s:1,m:60,h:3600,d:86400}[n[2]]:void 0}function Yp(e){let t=[],n=[];for(let s=0;s<e.length;s++){let r=e[s];if(r==="--"){n.push(...e.slice(s));break}let o=r.match(/^--(choices|question|target)(?:=(.*))?$/s);if(!o){n.push(r);continue}if(o[1]!=="choices")return{error:`--${o[1]} is not a flag: the ${o[1]} is positional — slack ask <target> "<question>" [choice…]`};let i=o[2]??e[++s];if(i===void 0||o[2]===void 0&&i.startsWith("--"))return{error:'--choices needs a value, e.g. --choices "Yes|No" (or pass the choices as arguments after the question)'};t.push(i)}return{choices:t.flatMap((s)=>s.split("|")).map((s)=>s.trim()).filter(Boolean),rest:n}}function mc(e){if(!Number.isFinite(e))return"forever";if(e>=3600&&e%3600===0)return`${e/3600}h`;if(e>=60&&e%60===0)return`${e/60}m`;return`${e}s`}import{closeSync as _0,existsSync as Ao,mkdirSync as To,openSync as E0,readFileSync as Oo,realpathSync as $0,renameSync as C0,statSync as yc,unlinkSync as Gp,writeFileSync as A0}from"node:fs";import{homedir as Xp}from"node:os";import{dirname as bc,join as Ve,resolve as Fo}from"node:path";var T0=["inbox","archived","outbox","sent"];function er(){return Ae("HOME")??jr(Ve(Xp(),".config"))}function Ze(e=process.cwd()){let t=Fo(e);for(;;){for(let s of[kt,Dt]){let r=Ve(t,s);try{if(yc(r).isDirectory())return{dir:r,global:!1}}catch{}}let n=bc(t);if(n===t)break;t=n}return{dir:er(),global:!0}}var F0='# .slack-hub/\n\nState for [slack-hub](https://github.com/snomiao/slack-hub) in this directory.\n`slack` uses the nearest `.slack-hub/` walking up from where it runs (like\n`.git`), so everything below this directory shares it. Without one it uses\n~/.config/slack-hub/.\n\nNothing here is committed: `.gitignore` holds `*`.\n\n| Path | What |\n|---|---|\n| `settings.yml` | yours to edit: `prefix` (put in front of every `slack reply`, e.g. `"[design]"`), `channel` (default), `as_bot`, `subscriptions` |\n| `settings.local.yml` | written by `slack alias set/unset`; same keys, wins over `settings.yml` |\n| `inbox/` → `archived/` | one file per incoming message (`slack stream --inbox`): who, where, the text with secrets redacted, a files count, the permalink. Handled = moved to `archived/`, by `slack done` or by a sent outbox reply with `in_reply_to` |\n| `outbox/` → `sent/` | one file per queued reply (`slack outbox add`, redacted); `slack outbox flush` sends them and moves each to `sent/` with its ts and permalink. A failure stays, with `error` and `attempts` |\n\n`restrict_to_subscriptions`, `auto_subscribe` and `nudge_after_min` count only in\n`settings.yml`. With `restrict_to_subscriptions: true`, only `settings.yml`\'s\nsubscriptions count, `slack alias set` refuses (the owner uses `--shared`), and\n`reply` / `outbox flush` refuse any other thread.\n\n`subscriptions` maps an alias to a place:\n\n subscriptions:\n board:\n channel: C00000001\n thread_ts: "1700000000.000100"\n\n## Commands\n\n slack alias ls # the aliases here\n slack alias set <name> <permalink> # name a thread (a reply\'s permalink names its root)\n slack alias unset <name>\n slack read <name> # read the thread\n slack reply <name> \'<text>\' # reply in it, with the prefix, behind the --code gate\n slack reply --to <permalink> \'<text>\' # reply in the thread where that message is\n slack reply <name> --to <permalink> … # refused when that message is in another thread\n slack inbox ls | listen | nudge # what was routed here\n slack done <file|ts> # handled without a reply\n slack outbox add <name> \'<text>\' --in-reply-to <ts>\n slack outbox flush # send the queue (one --code for the batch)\n slack alias who <channel> <ts> # which dirs subscribe a thread\n',O0=`# slack-hub settings for this directory. settings.local.yml (written by
352
353
  # \`slack alias\`) has the same keys and wins over this file.
353
354
  #
354
355
  # prefix: "[lane]" # put in front of every \`slack reply\`; never doubled
@@ -365,33 +366,33 @@ ${s}`;return i}function kp(e){if(!e.startsWith(ln))return null;let t=e.slice(ln.
365
366
  # owner: ~/ws/x/tree/shr # with restrict: --shared writes run only from under it
366
367
  # auto_subscribe: [D00000001] # new top-level messages there are subscribed here
367
368
  # nudge_after_min: 30 # \`slack inbox nudge\` reports what waits longer
368
- `;function oc(e,t={}){let n=ji(ko(e)),s=[];wo(n,{recursive:!0});for(let i of G0){let l=Xe(n,i);if(!bo(l))wo(l,{recursive:!0}),s.push(`${i}/`)}let r=(i,l)=>{let u=Xe(n,i);if(bo(u))return;ic(u,l),s.push(i)};r(".gitignore",`*
369
- `),r("README.md",X0);let o=Object.fromEntries(Object.entries(t).filter(([,i])=>i!==void 0));if(r("settings.yml",V0+(Object.keys(o).length?`
369
+ `;function wc(e,t={}){let n=Vi(Fo(e)),s=[];To(n,{recursive:!0});for(let i of T0){let a=Ve(n,i);if(!Ao(a))To(a,{recursive:!0}),s.push(`${i}/`)}let r=(i,a)=>{let c=Ve(n,i);if(Ao(c))return;kc(c,a),s.push(i)};r(".gitignore",`*
370
+ `),r("README.md",F0);let o=Object.fromEntries(Object.entries(t).filter(([,i])=>i!==void 0));if(r("settings.yml",O0+(Object.keys(o).length?`
370
371
  `+Bun.YAML.stringify(o,null,2)+`
371
- `:"")),n!==Ys())nk(n);return{dir:n,created:s}}function ic(e,t){wo(rc(e),{recursive:!0});let n=`${e}.tmp-${process.pid}-${Date.now()}`;Y0(n,t,{mode:384}),z0(n,e)}function Cp(e,t,n=1e4,s=5000){let r=`${e}.lock`;wo(rc(r),{recursive:!0});let o=Date.now()+s;for(;;)try{K0(q0(r,"wx"));break}catch(i){if(i.code!=="EEXIST")throw i;try{if(Date.now()-sc(r).mtimeMs>n){Ep(r);continue}}catch{continue}if(Date.now()>o)throw Error(`${r} is held by another writer`);Bun.sleepSync(25)}try{return t()}finally{try{Ep(r)}catch{}}}function Z0(e){if(!e||typeof e!=="object")return;let t=e;if(typeof t.channel!=="string"||!t.channel)return;let n={channel:t.channel};if(typeof t.thread_ts==="string"&&/^\d{10}\.\d{6}$/.test(t.thread_ts))n.thread_ts=t.thread_ts;if(typeof t.added==="string")n.added=t.added;if(typeof t.note==="string")n.note=t.note;return n}function as(e){let t;try{t=Bun.YAML.parse(Do(e,"utf8"))}catch(r){if(r.code==="ENOENT")return{};throw Error(`${e}: ${r instanceof Error?r.message:String(r)}`)}if(!t||typeof t!=="object")return{};let n=t,s={};if(typeof n.prefix==="string"&&n.prefix.trim())s.prefix=n.prefix.trim();else if(Array.isArray(n.prefix)&&n.prefix.length===1&&typeof n.prefix[0]==="string")s.prefix=`[${n.prefix[0]}]`;if(typeof n.channel==="string"&&n.channel)s.channel=n.channel;if(typeof n.as_bot==="boolean")s.as_bot=n.as_bot;if(n.restrict_to_subscriptions===!0)s.restrict_to_subscriptions=!0;if(Array.isArray(n.auto_subscribe))s.auto_subscribe=n.auto_subscribe.filter((r)=>typeof r==="string");if(typeof n.nudge_after_min==="number"&&n.nudge_after_min>0)s.nudge_after_min=n.nudge_after_min;if(typeof n.owner==="string"&&n.owner)s.owner=n.owner;if(n.subscriptions&&typeof n.subscriptions==="object"){let r={};for(let[o,i]of Object.entries(n.subscriptions)){let l=Z0(i);if(l&&ac(o))r[o]=l}s.subscriptions=r}return s}function cs(e){let t=as(Xe(e.dir,"settings.yml")),n=as(Xe(e.dir,"settings.local.yml"));if(delete n.restrict_to_subscriptions,delete n.auto_subscribe,delete n.owner,t.restrict_to_subscriptions)delete n.subscriptions,delete n.prefix,delete n.as_bot,delete n.channel;let s={...t.subscriptions,...n.subscriptions},r={...t,...n};if(Object.keys(s).length)r.subscriptions=s;else delete r.subscriptions;return r}var Q0=/^[a-z0-9][a-z0-9._-]{0,63}$/;function ac(e){return Q0.test(e)&&!/^\d{10}\.\d{6}$/.test(e)}function dn(e){let t=as(Xe(e.dir,"settings.yml")),n=t.subscriptions??{},s=t.restrict_to_subscriptions?{}:as(Xe(e.dir,"settings.local.yml")).subscriptions??{},r=[];for(let[o,i]of Object.entries(n))if(!s[o])r.push({...i,name:o,scope:e,file:"settings.yml"});for(let[o,i]of Object.entries(s))r.push({...i,name:o,scope:e,file:"settings.local.yml"});return r.sort((o,i)=>o.name.localeCompare(i.name))}function cc(e,t=process.cwd()){if(!ac(e))return;let n=Ve(t),s=n.global?[n]:[n,{dir:Ys(),global:!0}];for(let r of s){let o=dn(r).find((i)=>i.name===e);if(o)return o}return}var ek="# Written by `slack alias set/unset`; wins over settings.yml. Safe to edit by hand.\n";function tk(e){try{let t=Do(e,"utf8").split(`
372
+ `:"")),n!==er())L0(n);return{dir:n,created:s}}function kc(e,t){To(bc(e),{recursive:!0});let n=`${e}.tmp-${process.pid}-${Date.now()}`;A0(n,t,{mode:384}),C0(n,e)}function Vp(e,t,n=1e4,s=5000){let r=`${e}.lock`;To(bc(r),{recursive:!0});let o=Date.now()+s;for(;;)try{_0(E0(r,"wx"));break}catch(i){if(i.code!=="EEXIST")throw i;try{if(Date.now()-yc(r).mtimeMs>n){Gp(r);continue}}catch{continue}if(Date.now()>o)throw Error(`${r} is held by another writer`);Bun.sleepSync(25)}try{return t()}finally{try{Gp(r)}catch{}}}function I0(e){if(!e||typeof e!=="object")return;let t=e;if(typeof t.channel!=="string"||!t.channel)return;let n={channel:t.channel};if(typeof t.thread_ts==="string"&&/^\d{10}\.\d{6}$/.test(t.thread_ts))n.thread_ts=t.thread_ts;if(typeof t.added==="string")n.added=t.added;if(typeof t.note==="string")n.note=t.note;return n}function fs(e){let t;try{t=Bun.YAML.parse(Oo(e,"utf8"))}catch(r){if(r.code==="ENOENT")return{};throw Error(`${e}: ${r instanceof Error?r.message:String(r)}`)}if(!t||typeof t!=="object")return{};let n=t,s={};if(typeof n.prefix==="string"&&n.prefix.trim())s.prefix=n.prefix.trim();else if(Array.isArray(n.prefix)&&n.prefix.length===1&&typeof n.prefix[0]==="string")s.prefix=`[${n.prefix[0]}]`;if(typeof n.channel==="string"&&n.channel)s.channel=n.channel;if(typeof n.as_bot==="boolean")s.as_bot=n.as_bot;if(n.restrict_to_subscriptions===!0)s.restrict_to_subscriptions=!0;if(Array.isArray(n.auto_subscribe))s.auto_subscribe=n.auto_subscribe.filter((r)=>typeof r==="string");if(typeof n.nudge_after_min==="number"&&n.nudge_after_min>0)s.nudge_after_min=n.nudge_after_min;if(typeof n.owner==="string"&&n.owner)s.owner=n.owner;if(n.subscriptions&&typeof n.subscriptions==="object"){let r={};for(let[o,i]of Object.entries(n.subscriptions)){let a=I0(i);if(a&&Dc(o))r[o]=a}s.subscriptions=r}return s}function ps(e){let t=fs(Ve(e.dir,"settings.yml")),n=fs(Ve(e.dir,"settings.local.yml"));if(delete n.restrict_to_subscriptions,delete n.auto_subscribe,delete n.owner,t.restrict_to_subscriptions)delete n.subscriptions,delete n.prefix,delete n.as_bot,delete n.channel;let s={...t.subscriptions,...n.subscriptions},r={...t,...n};if(Object.keys(s).length)r.subscriptions=s;else delete r.subscriptions;return r}var R0=/^[a-z0-9][a-z0-9._-]{0,63}$/;function Dc(e){return R0.test(e)&&!/^\d{10}\.\d{6}$/.test(e)}function pn(e){let t=fs(Ve(e.dir,"settings.yml")),n=t.subscriptions??{},s=t.restrict_to_subscriptions?{}:fs(Ve(e.dir,"settings.local.yml")).subscriptions??{},r=[];for(let[o,i]of Object.entries(n))if(!s[o])r.push({...i,name:o,scope:e,file:"settings.yml"});for(let[o,i]of Object.entries(s))r.push({...i,name:o,scope:e,file:"settings.local.yml"});return r.sort((o,i)=>o.name.localeCompare(i.name))}function xc(e,t=process.cwd()){if(!Dc(e))return;let n=Ze(t),s=n.global?[n]:[n,{dir:er(),global:!0}];for(let r of s){let o=pn(r).find((i)=>i.name===e);if(o)return o}return}var v0="# Written by `slack alias set/unset`; wins over settings.yml. Safe to edit by hand.\n";function P0(e){try{let t=Oo(e,"utf8").split(`
372
373
  `),n=[];for(let s of t)if(s.startsWith("#")||!s.trim()&&n.length)n.push(s);else break;return n.length?n.join(`
373
374
  `).replace(/\n*$/,`
374
- `):""}catch{return""}}function Ap(e,t,n){let s=Xe(e.dir,t?"settings.yml":"settings.local.yml");Cp(s,()=>{let r=t?tk(s):ek,o={};try{let i=Bun.YAML.parse(Do(s,"utf8"));if(i&&typeof i==="object"&&!Array.isArray(i))o=i}catch(i){if(i.code!=="ENOENT")throw Error(`${s}: ${i instanceof Error?i.message:String(i)}`)}n(o),ic(s,r+Bun.YAML.stringify(o,null,2)+`
375
- `)})}function Mn(e){return as(Xe(e.dir,"settings.yml")).restrict_to_subscriptions===!0}function Tp(e,t=process.cwd()){if(!Mn(e))return;let n=as(Xe(e.dir,"settings.yml")).owner;if(!n)return`${e.dir} is restricted and names no \`owner\` in settings.yml: nobody may write it with --shared (edit the file)`;let s=(i)=>{try{return H0(ko(i))}catch{return ko(i)}},r=s(n.replace(/^~(?=\/|$)/,$p())),o=s(t);if(o===r||o.startsWith(r.endsWith("/")?r:r+"/"))return;return`${e.dir} is owned by ${n}: --shared writes run only from under that directory`}function lc(e,t,n,s={}){let r=typeof s==="boolean"?{shared:s}:s,o=r.shared===!0;if(!ac(t))throw Error(`invalid alias name "${t}" (a-z 0-9 . _ -, at most 64, not a bare ts)`);if(!o&&Mn(e))throw new Nn(e);if(o&&!r.asOwner){let l=Tp(e,r.cwd);if(l)throw new Nn(e,l)}let i=dn(e).find((l)=>l.name===t);return Ap(e,o,(l)=>{let u=l.subscriptions&&typeof l.subscriptions==="object"?l.subscriptions:{};u[t]={channel:n.channel,...n.thread_ts?{thread_ts:n.thread_ts}:{},added:n.added??new Date().toISOString(),...n.note?{note:n.note}:{}},l.subscriptions=u}),i}function Fp(e,t,n=!1,s){let r=dn(e).find((o)=>o.name===t);if(!r)return"absent";if(r.file==="settings.yml"&&!n)return"in-settings.yml";if(r.file==="settings.yml"){let o=Tp(e,s);if(o)throw new Nn(e,o)}return Ap(e,r.file==="settings.yml",(o)=>{let i=o.subscriptions;if(i)delete i[t];if(i&&!Object.keys(i).length)delete o.subscriptions}),"removed"}class Nn extends Error{constructor(e,t){super(t??`${e.dir} is restricted (restrict_to_subscriptions in settings.yml): only its owner adds subscriptions, with \`slack alias set --shared\` run from the owner's directory`)}}function Op(){return Xe(Ys(),"scopes")}function nk(e){let t=Op();Cp(t,()=>{let n=Rp();if(n.includes(e))return;ic(t,[...n,e].join(`
375
+ `):""}catch{return""}}function Zp(e,t,n){let s=Ve(e.dir,t?"settings.yml":"settings.local.yml");Vp(s,()=>{let r=t?P0(s):v0,o={};try{let i=Bun.YAML.parse(Oo(s,"utf8"));if(i&&typeof i==="object"&&!Array.isArray(i))o=i}catch(i){if(i.code!=="ENOENT")throw Error(`${s}: ${i instanceof Error?i.message:String(i)}`)}n(o),kc(s,r+Bun.YAML.stringify(o,null,2)+`
376
+ `)})}function Un(e){return fs(Ve(e.dir,"settings.yml")).restrict_to_subscriptions===!0}function Qp(e,t=process.cwd()){if(!Un(e))return;let n=fs(Ve(e.dir,"settings.yml")).owner;if(!n)return`${e.dir} is restricted and names no \`owner\` in settings.yml: nobody may write it with --shared (edit the file)`;let s=(i)=>{try{return $0(Fo(i))}catch{return Fo(i)}},r=s(n.replace(/^~(?=\/|$)/,Xp())),o=s(t);if(o===r||o.startsWith(r.endsWith("/")?r:r+"/"))return;return`${e.dir} is owned by ${n}: --shared writes run only from under that directory`}function Sc(e,t,n,s={}){let r=typeof s==="boolean"?{shared:s}:s,o=r.shared===!0;if(!Dc(t))throw Error(`invalid alias name "${t}" (a-z 0-9 . _ -, at most 64, not a bare ts)`);if(!o&&Un(e))throw new Wn(e);if(o&&!r.asOwner){let a=Qp(e,r.cwd);if(a)throw new Wn(e,a)}let i=pn(e).find((a)=>a.name===t);return Zp(e,o,(a)=>{let c=a.subscriptions&&typeof a.subscriptions==="object"?a.subscriptions:{};c[t]={channel:n.channel,...n.thread_ts?{thread_ts:n.thread_ts}:{},added:n.added??new Date().toISOString(),...n.note?{note:n.note}:{}},a.subscriptions=c}),i}function eh(e,t,n=!1,s){let r=pn(e).find((o)=>o.name===t);if(!r)return"absent";if(r.file==="settings.yml"&&!n)return"in-settings.yml";if(r.file==="settings.yml"){let o=Qp(e,s);if(o)throw new Wn(e,o)}return Zp(e,r.file==="settings.yml",(o)=>{let i=o.subscriptions;if(i)delete i[t];if(i&&!Object.keys(i).length)delete o.subscriptions}),"removed"}class Wn extends Error{constructor(e,t){super(t??`${e.dir} is restricted (restrict_to_subscriptions in settings.yml): only its owner adds subscriptions, with \`slack alias set --shared\` run from the owner's directory`)}}function th(){return Ve(er(),"scopes")}function L0(e){let t=th();Vp(t,()=>{let n=nh();if(n.includes(e))return;kc(t,[...n,e].join(`
376
377
  `)+`
377
- `)})}function Rp(){try{return Do(Op(),"utf8").split(`
378
- `).map((e)=>e.trim()).filter((e)=>e&&!e.startsWith("#"))}catch{return[]}}function sk(){let e=[];for(let s of Rp())try{if(sc(s).isDirectory())e.push({dir:s,global:!1})}catch{}let t=Ys();if((bo(Xe(t,"settings.yml"))||bo(Xe(t,"settings.local.yml")))&&!e.some((s)=>s.dir===t))e.push({dir:t,global:!0});return e}function Ip(e,t,n=sk()){let s=[];for(let r of n)for(let o of dn(r))if(o.channel===e&&(o.thread_ts===void 0||o.thread_ts===t))s.push(o);return s}function uc(e,t){let n=t?.trim();if(!n)return e;let s=/^\[([^\]@\s]+)\]$/.exec(n),r=e;if(s){let o=s[1].replace(/[.*+?^${}()|[\]\\]/g,"\\$&");r=e.replace(new RegExp(`^\\s*\\[${o}(?:@[a-z0-9-]{1,16})?\\][ \\t]*`),"")}else if(e.trimStart().startsWith(n))r=e.trimStart().slice(n.length).replace(/^[ \t]+/,"");return r.trim()?`${n} ${r}`:""}function dc(e,t){if(e.channel===t.channel&&e.threadTs===t.root)return;let n=(s,r)=>r?`${s} thread ${r}`:`${s} (top level)`;return`the message you are answering (${t.ts}) is in ${n(t.channel,t.root)}, but the destination is ${n(e.channel,e.threadTs)}.
378
+ `)})}function nh(){try{return Oo(th(),"utf8").split(`
379
+ `).map((e)=>e.trim()).filter((e)=>e&&!e.startsWith("#"))}catch{return[]}}function N0(){let e=[];for(let s of nh())try{if(yc(s).isDirectory())e.push({dir:s,global:!1})}catch{}let t=er();if((Ao(Ve(t,"settings.yml"))||Ao(Ve(t,"settings.local.yml")))&&!e.some((s)=>s.dir===t))e.push({dir:t,global:!0});return e}function sh(e,t,n=N0()){let s=[];for(let r of n)for(let o of pn(r))if(o.channel===e&&(o.thread_ts===void 0||o.thread_ts===t))s.push(o);return s}function _c(e,t){let n=t?.trim();if(!n)return e;let s=/^\[([^\]@\s]+)\]$/.exec(n),r=e;if(s){let o=s[1].replace(/[.*+?^${}()|[\]\\]/g,"\\$&");r=e.replace(new RegExp(`^\\s*\\[${o}(?:@[a-z0-9-]{1,16})?\\][ \\t]*`),"")}else if(e.trimStart().startsWith(n))r=e.trimStart().slice(n.length).replace(/^[ \t]+/,"");return r.trim()?`${n} ${r}`:""}function Ec(e,t){if(e.channel===t.channel&&e.threadTs===t.root)return;let n=(s,r)=>r?`${s} thread ${r}`:`${s} (top level)`;return`the message you are answering (${t.ts}) is in ${n(t.channel,t.root)}, but the destination is ${n(e.channel,e.threadTs)}.
379
380
  `+` Drop the destination to reply where the message is: slack reply --to <permalink> '…'
380
- `+" Or pass --any-thread if the other thread is really meant."}var vp=/(⬜️?|:white_large_square:)(\s*)(\d+)\./g,rk=/(✅|:white_check_mark:)\s*(\d+)\./g;function Pp(e,t){let n=[...e.matchAll(vp)].map((i)=>Number(i[3])),s=[...e.matchAll(rk)].map((i)=>Number(i[2]));if(t===void 0){if(n.length===0)return s.length?{kind:"already",n:s[0]}:{kind:"none"};if(n.length>1)return{kind:"ambiguous",open:n};t=n[0]}if(!n.includes(t))return s.includes(t)?{kind:"already",n:t}:{kind:"missing",n:t};let r=!1;return{kind:"ticked",text:e.replace(vp,(i,l,u,f)=>{if(r||Number(f)!==t)return i;return r=!0,`${l.startsWith(":")?":white_check_mark:":"✅"}${u}${f}.`}),n:t}}function Lp(e,t,n){let s=/^\[([^\]@\s]+)\]$/.exec(n?.trim()??"");if(!s)return t;let r=s[1].replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp(`^\\[${r}(?:@[a-z0-9-]{1,16})?\\][ \\t]*`),i=o.exec(e);if(!i)return t;return i[0]+t.replace(o,"")}import{readFileSync as Mp}from"node:fs";import{homedir as ok}from"node:os";import{join as Np}from"node:path";var Bp=/^@([a-z0-9][a-z0-9._-]{0,63})$/;function jp(e){let t=Bp.exec(e[0]??"");return t?{who:t[1],rest:e.slice(1)}:{rest:e}}function ik(e){let t=e;if(!t||typeof t!=="object"||t.kind!=="bot"&&t.kind!=="user")return;let n={kind:t.kind};if(typeof t.env==="string"&&/^[A-Z_][A-Z0-9_]*$/.test(t.env))n.env=t.env;if(typeof t.env_file==="string")n.env_file=t.env_file;if(typeof t.profile==="string")n.profile=t.profile;return n}function xo(e=process.cwd()){let t=ao(e),n=t.global?[t]:[{dir:Js(),global:!0},t],s=new Map;for(let r of n){let i=cn(Np(r.dir,"settings.yml")).restrict_to_subscriptions?["settings.yml"]:["settings.yml","settings.local.yml"];for(let l of i){let u;try{u=Bun.YAML.parse(Mp(Np(r.dir,l),"utf8"))}catch{continue}let f=u?.identities;if(!f||typeof f!=="object")continue;for(let[a,c]of Object.entries(f)){let d=ik(c);if(d&&Bp.test(`@${a}`))s.set(a,d)}}}return s}function ak(e){let t={};for(let n of Mp(e.replace(/^~(?=\/|$)/,ok()),"utf8").split(`
381
- `)){let s=/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*?)\s*$/.exec(n);if(!s)continue;let r=s[2];if(/^(["']).*\1$/.test(r))r=r.slice(1,-1);t[s[1]]=r}return t}function So(e,t=process.env,n=xo()){let s=n.get(e),r=[...n.keys()].sort().map((l)=>`@${l}`).join(", ")||"(none: add `identities:` to .slack-hub/settings.yml)";if(!s)return{error:`unknown identity @${e}. Known: ${r}`};if(s.kind==="user"&&s.profile&&!s.env&&!s.env_file)return t.SLACK_WORKSPACE=s.profile,delete t.SLACK_TOKEN,delete t.SLACK_BOT_TOKEN,t.SLACK_HUB_IDENTITY=e,{kind:"user"};let o=s.env??(s.kind==="bot"?"SLACK_BOT_TOKEN":"SLACK_TOKEN"),i;try{i=s.env_file?ak(s.env_file)[o]:t[o]}catch{return{error:`@${e}: cannot read ${s.env_file}`}}if(!i)return{error:`@${e}: no ${o}${s.env_file?` in ${s.env_file}`:" in the environment"}`};if(s.kind==="bot"&&!i.startsWith("xoxb-"))return{error:`@${e} is a bot, but ${o} is not a bot token (xoxb-)`};if(s.kind==="user"&&i.startsWith("xoxb-"))return{error:`@${e} is a user, but ${o} holds a bot token`};if(s.kind==="bot")t.SLACK_BOT_TOKEN=i,t.SLACK_TOKEN=i;else t.SLACK_TOKEN=i,delete t.SLACK_BOT_TOKEN;return t.SLACK_HUB_IDENTITY=e,{kind:s.kind}}function fc(e=process.env){return["AY_AGENT_ID","AGENT_YES_PID","CLAUDECODE"].find((t)=>e[t])}function Wp(e){if(!e.isWrite||e.who||e.asBot||e.activeIsBot)return null;let t=e.userIdentities??[];if(e.asUser&&!e.agent)return null;let n=e.identities.map((r)=>`@${r}`).join(" | "),s=n?` Name who acts: slack ${e.identities[0]?`@${e.identities[0]}`:"@<who>"} ${e.cmd} … (${n})`:" Add identities to .slack-hub/settings.yml, then: slack @<who> "+e.cmd+" …";if(e.agent){let r=t.length?` As a person, on purpose: slack @${t[0]} ${e.cmd} … (${t.map((o)=>`@${o}`).join(" | ")})`:" As a person, on purpose: add them to `identities:` (kind: user), then slack @<name> "+e.cmd+" …";return[`Error: refusing to post as the user session from inside an agent (${e.agent} is set): \`${e.cmd}\` would go out as a PERSON.`,...e.asUser?[" --as-user is not accepted from an agent: it hides whose name the post goes out under."]:[],s," As the app: add --as-bot",r].join(`
381
+ `+" Or pass --any-thread if the other thread is really meant."}var rh=/(⬜️?|:white_large_square:)(\s*)(\d+)\./g,M0=/(✅|:white_check_mark:)\s*(\d+)\./g;function oh(e,t){let n=[...e.matchAll(rh)].map((i)=>Number(i[3])),s=[...e.matchAll(M0)].map((i)=>Number(i[2]));if(t===void 0){if(n.length===0)return s.length?{kind:"already",n:s[0]}:{kind:"none"};if(n.length>1)return{kind:"ambiguous",open:n};t=n[0]}if(!n.includes(t))return s.includes(t)?{kind:"already",n:t}:{kind:"missing",n:t};let r=!1;return{kind:"ticked",text:e.replace(rh,(i,a,c,d)=>{if(r||Number(d)!==t)return i;return r=!0,`${a.startsWith(":")?":white_check_mark:":"✅"}${c}${d}.`}),n:t}}function ih(e,t,n){let s=/^\[([^\]@\s]+)\]$/.exec(n?.trim()??"");if(!s)return t;let r=s[1].replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp(`^\\[${r}(?:@[a-z0-9-]{1,16})?\\][ \\t]*`),i=o.exec(e);if(!i)return t;return i[0]+t.replace(o,"")}import{readFileSync as ch}from"node:fs";import{homedir as B0}from"node:os";import{join as ah}from"node:path";var lh=/^@([a-z0-9][a-z0-9._-]{0,63})$/;function uh(e){let t=lh.exec(e[0]??"");return t?{who:t[1],rest:e.slice(1)}:{rest:e}}function j0(e){let t=e;if(!t||typeof t!=="object"||t.kind!=="bot"&&t.kind!=="user")return;let n={kind:t.kind};if(typeof t.env==="string"&&/^[A-Z_][A-Z0-9_]*$/.test(t.env))n.env=t.env;if(typeof t.env_file==="string")n.env_file=t.env_file;if(typeof t.profile==="string")n.profile=t.profile;return n}function Io(e=process.cwd()){let t=bo(e),n=t.global?[t]:[{dir:Gs(),global:!0},t],s=new Map;for(let r of n){let i=un(ah(r.dir,"settings.yml")).restrict_to_subscriptions?["settings.yml"]:["settings.yml","settings.local.yml"];for(let a of i){let c;try{c=Bun.YAML.parse(ch(ah(r.dir,a),"utf8"))}catch{continue}let d=c?.identities;if(!d||typeof d!=="object")continue;for(let[f,p]of Object.entries(d)){let g=j0(p);if(g&&lh.test(`@${f}`))s.set(f,g)}}}return s}function W0(e){let t={};for(let n of ch(e.replace(/^~(?=\/|$)/,B0()),"utf8").split(`
382
+ `)){let s=/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*?)\s*$/.exec(n);if(!s)continue;let r=s[2];if(/^(["']).*\1$/.test(r))r=r.slice(1,-1);t[s[1]]=r}return t}function Ro(e,t=process.env,n=Io()){let s=n.get(e),r=[...n.keys()].sort().map((a)=>`@${a}`).join(", ")||"(none: add `identities:` to .slack-hub/settings.yml)";if(!s)return{error:`unknown identity @${e}. Known: ${r}`};if(s.kind==="user"&&s.profile&&!s.env&&!s.env_file)return t.SLACK_WORKSPACE=s.profile,delete t.SLACK_TOKEN,delete t.SLACK_BOT_TOKEN,t.SLACK_HUB_IDENTITY=e,{kind:"user"};let o=s.env??(s.kind==="bot"?"SLACK_BOT_TOKEN":"SLACK_TOKEN"),i;try{i=s.env_file?W0(s.env_file)[o]:t[o]}catch{return{error:`@${e}: cannot read ${s.env_file}`}}if(!i)return{error:`@${e}: no ${o}${s.env_file?` in ${s.env_file}`:" in the environment"}`};if(s.kind==="bot"&&!i.startsWith("xoxb-"))return{error:`@${e} is a bot, but ${o} is not a bot token (xoxb-)`};if(s.kind==="user"&&i.startsWith("xoxb-"))return{error:`@${e} is a user, but ${o} holds a bot token`};if(s.kind==="bot")t.SLACK_BOT_TOKEN=i,t.SLACK_TOKEN=i;else t.SLACK_TOKEN=i,delete t.SLACK_BOT_TOKEN;return t.SLACK_HUB_IDENTITY=e,{kind:s.kind}}function $c(e=process.env){return["AY_AGENT_ID","AGENT_YES_PID","CLAUDECODE"].find((t)=>e[t])}function dh(e){if(!e.isWrite||e.who||e.asBot||e.activeIsBot)return null;let t=e.userIdentities??[];if(e.asUser&&!e.agent)return null;let n=e.identities.map((r)=>`@${r}`).join(" | "),s=n?` Name who acts: slack ${e.identities[0]?`@${e.identities[0]}`:"@<who>"} ${e.cmd} … (${n})`:" Add identities to .slack-hub/settings.yml, then: slack @<who> "+e.cmd+" …";if(e.agent){let r=t.length?` As a person, on purpose: slack @${t[0]} ${e.cmd} … (${t.map((o)=>`@${o}`).join(" | ")})`:" As a person, on purpose: add them to `identities:` (kind: user), then slack @<name> "+e.cmd+" …";return[`Error: refusing to post as the user session from inside an agent (${e.agent} is set): \`${e.cmd}\` would go out as a PERSON.`,...e.asUser?[" --as-user is not accepted from an agent: it hides whose name the post goes out under."]:[],s," As the app: add --as-bot",r].join(`
382
383
  `)}if(e.identities.length>=2)return[`Error: several identities are configured (${n}): name the one \`${e.cmd}\` acts as.`,s," Or: --as-bot / --as-user"].join(`
383
- `);return null}var pc=/:([a-z0-9_+'-]+):((?::skin-tone-[2-6]:)?)/g,ck=/<([A-Za-z][A-Za-z0-9+.-]*:[^|<>\s]*)(?:\|([^<>]*))?>/g,lk=/&(amp|lt|gt);/g,uk=/[︎️]/gu,dk=/[\u{1F3FB}-\u{1F3FF}]/gu,Up=String.raw`:[a-z0-9_+'-]+:(?::skin-tone-[2-6]:)?`,fk=String.raw`©®‼⁉™ℹ←-⇿⌀-⏿Ⓜ■-➿⤀-⥿⬀-⯿〰〽㊗㊙\u{1F000}-\u{1FAFF}`,Jp=String.raw`[${fk}][\u{E0020}-\u{E007F}]*`,pk=new RegExp(String.raw`(?<sc>${Up}(?:‍${Up})*)|(?<emoji>[0-9#*]⃣|[\u{1F1E6}-\u{1F1FF}]{2}|${Jp}(?:‍${Jp})*)|(?<char>[\s\S])`,"gu");function hc(e){let t=new Map,n=[e??null],s=0;while(n.length&&s++<1e5){let r=n.pop();if(Array.isArray(r))n.push(...r);else if(r&&typeof r==="object"){let{name:o,unicode:i}=r;if(r.type==="emoji"&&typeof o==="string"&&typeof i==="string")try{t.set(o.split("::")[0],i.split("-").filter(Boolean).map((l)=>String.fromCodePoint(parseInt(l,16))).join(""))}catch{}n.push(...Object.values(r))}}return t}function hk(e,t,n){if(n===void 0)return t;for(let s of["http://","mailto:"])if(t.slice(0,s.length).toLowerCase()===s&&n===t.slice(s.length))return n;return e}function Gs(e,t){let n=e.normalize("NFC");return n=n.replace(ck,(s,r,o)=>hk(s,r,o)),n=n.replace(lk,(s,r)=>({amp:"&",lt:"<",gt:">"})[r]),n=n.replace(pc,(s,r)=>t.get(r)??s),n=n.replace(uk,"").replace(dk,""),n.split(/\s+/).filter(Boolean).join(" ")}function Kp(e){return[...e.matchAll(pk)].map((t)=>{let n=t.groups;return n.sc!==void 0?["sc",n.sc]:n.emoji!==void 0?["emoji",n.emoji]:["char",n.char]})}function qp(e,t){let n=hc(t.blocks),s=Gs(e,n),r=Gs(typeof t.text==="string"?t.text:"",n);if(s===r)return!0;if(pc.lastIndex=0,!pc.test(r))return!1;let o=Kp(s),i=Kp(r);return o.length===i.length&&o.every(([l,u],f)=>u===i[f][1]||i[f][0]==="sc"&&l==="emoji")}function Hp(e,t){let n=0;while(n<e.length&&n<t.length&&e[n]===t[n])n++;let s=Math.max(0,n-10);return`char ${n}: sent ${JSON.stringify(e.slice(s,n+30))}, stored ${JSON.stringify(t.slice(s,n+30))}`}function gk(e){return e.replace(/```[\s\S]*?```/g," ").replace(/`[^`\n]*`/g," ").replace(/<[^>\s]*>/g," ").replace(/https?:\/\/\S+/g," ")}function zp(e){let t=lp();for(let n of gk(e).split(`
384
- `))for(let s of t)if(s.re.test(n))return s.lang;return}function Yp(e){return`hint: this looks like a choice question — use slack ask '${e}' "<question>" <choice>… so the reader can tap an answer instead of typing it`}import{existsSync as Vp,readdirSync as Sk,readFileSync as _k,renameSync as Ek,statSync as $k,unlinkSync as Ck,utimesSync as Ak}from"node:fs";import{join as Ot}from"node:path";import{readFileSync as mk}from"node:fs";function Gp(e){let t="";for(;;){let o=/^\(\?([is]+)\)/.exec(e);if(!o)break;t+=o[1],e=e.slice(o[0].length)}e=e.replaceAll("(?P<","(?<").replaceAll("\\z","$").replaceAll("[[:alnum:]]","[A-Za-z0-9]").replaceAll("[:alnum:]","A-Za-z0-9").replaceAll("[:alpha:]","A-Za-z").replaceAll("[:digit:]","0-9").replaceAll("[:space:]","\\s");let n="",s=[],r=0;for(let o=0;o<e.length;o++){let i=e[o];if(i==="\\"){n+=i+(e[o+1]??""),o++;continue}if(i==="["){let l=o+1;if(e[l]==="^")l++;if(e[l]==="]")l++;while(l<e.length&&e[l]!=="]"){if(e[l]==="\\")l++;l++}n+=e.slice(o,l+1),o=l;continue}if(e.startsWith("(?i)",o)){n+="(?i:",r++,o+=3;continue}if(i==="("){s.push(r),r=0,n+=i;continue}if(i===")"){n+=")".repeat(r),r=s.pop()??0,n+=i;continue}if(i==="|"&&r){n+=")".repeat(r)+"|"+"(?i:".repeat(r);continue}n+=i}return n+=")".repeat(r),{source:n,flags:[...new Set(t)].join("")}}function yk(e){let t=Bun.TOML.parse(e),n=(i)=>{let l=Gp(i);return new RegExp(l.source,l.flags)},s=(t.allowlist?.regexes??[]).map(n),r=(t.allowlist?.stopwords??[]).map((i)=>i.toLowerCase()),o=[];for(let i of t.rules){if(!i.regex)continue;let l=[...s],u=[],f=[],a=[...r];for(let d of[...i.allowlists??[],...i.allowlist?[i.allowlist]:[]]){let p=d.regexTarget==="match"?u:d.regexTarget==="line"?f:l;for(let h of d.regexes??[])p.push(n(h));for(let h of d.stopwords??[])a.push(String(h).toLowerCase())}let c=Gp(i.regex);o.push({id:i.id,re:new RegExp(c.source,c.flags+"gd"),keywords:(i.keywords??[]).map((d)=>d.toLowerCase()),...i.entropy?{entropy:i.entropy}:{},...i.secretGroup?{group:i.secretGroup}:{},allow:l,...u.length?{allowMatch:u}:{},...f.length?{allowLine:f}:{},stop:a})}return o}var bk=[{id:"url-secret-param",re:/[?&](?:access_token|token|key|api_key|apikey|secret|client_secret|password|passwd|pwd|sig|signature)=([^&\s#<>"'|]{6,})/gid,group:1,keywords:["="],allow:[/^(?:x+|\*+|\.\.\.|your[-_]?\w*|xxx\w*)$/i],stop:[]},{id:"sk-key",re:/\b(sk-(?:proj-|ant-|or-v1-|svcacct-)?[A-Za-z0-9_-]{20,})/gd,group:1,keywords:["sk-"],entropy:3.5,allow:[],stop:[]},{id:"otp-code",re:/(?:code|コード|otp|pin|passcode|認証|確認番号|ワンタイム)[^\d\n]{0,20}(?<![\d.])(\d{6})(?![\d.])/gid,group:1,keywords:[],allow:[],stop:[]}],Xp;function wk(){return Xp??=[...yk(mk(new URL("./vendor/gitleaks.toml",import.meta.url),"utf8")),...bk],Xp}function kk(e){let t=new Map;for(let s of e)t.set(s,(t.get(s)??0)+1);let n=0;for(let s of t.values()){let r=s/e.length;n-=r*Math.log2(r)}return n}function Dk(e,t){let n=new Set;for(let r of t){if(r.length<6)continue;n.add(r),n.add(JSON.stringify(r).slice(1,-1))}let s=[];for(let r of[...n].sort((o,i)=>i.length-o.length))for(let o=e.indexOf(r);o>=0;o=e.indexOf(r,o+r.length))s.push({id:"known-secret",start:o,end:o+r.length});return s}function xk(e,t={}){let n=t.rules??wk(),s=e.toLowerCase(),r=t.known?.length?Dk(e,t.known):[];for(let o of n){if(o.keywords.length&&!o.keywords.some((i)=>s.includes(i)))continue;for(let i of e.matchAll(o.re)){let l=o.group??i.findIndex((c,d)=>d>0&&!!c),u=l>0?i[l]:i[0];if(!u)continue;if(o.entropy&&kk(u)<o.entropy)continue;if(o.allow.some((c)=>c.test(u)))continue;if(o.allowMatch?.some((c)=>c.test(i[0])))continue;if(o.allowLine){let c=e.lastIndexOf(`
385
- `,i.index)+1,d=e.indexOf(`
386
- `,i.index+i[0].length);if(o.allowLine.some((p)=>p.test(e.slice(c,d<0?void 0:d))))continue}let f=u.toLowerCase();if(o.stop.some((c)=>f.includes(c)))continue;let a=o.group?i.indices?.[o.group]:void 0;if(a)r.push({id:o.id,start:a[0],end:a[1]});else{let c=i.index,d=i.index+i[0].length,p=/[\s'"`;=:,]/;while(c<d&&p.test(e[c]))c++;for(;;)if(d>c&&p.test(e[d-1]))d--;else if(d-2>=c&&/\\[nr]/.test(e.slice(d-2,d)))d-=2;else break;r.push({id:o.id,start:c,end:d})}}}return r}function _o(e,t={}){let n=xk(e,t).sort((i,l)=>i.start-l.start||l.end-i.end);if(!n.length)return{text:e,kinds:[]};let s=[];for(let i of n){let l=s[s.length-1];if(l&&i.start<l.end){if(i.end-i.start>l.end-l.start)l.id=i.id;l.end=Math.max(l.end,i.end)}else s.push({...i})}let r="",o=0;for(let i of s)r+=e.slice(o,i.start)+`[redacted:${i.id}]`,o=i.end;return{text:r+e.slice(o),kinds:[...new Set(s.map((i)=>i.id))]}}var Tk=/^\d{10}\.\d{6}$/;function Fk(e,t){return`${e}-${t}.yml`}function Xs(e){return Bun.YAML.stringify(e,null,2)+`
387
- `}function Ok(e,t,n=[]){let s=Fk(t.channel,t.ts);if(Vp(Ot(e.dir,"inbox",s))||Vp(Ot(e.dir,"archived",s)))return!1;let r=_o(t.text,{known:n}),o={...t,text:r.text,...r.kinds.length?{redacted:r.kinds}:{}};return Pn(Ot(e.dir,"inbox",s),Xs(o)),!0}function Zp(e,t=Ha(),n=new Date,s=[]){let r=e.thread_ts??e.ts,o=za(e.channel.id,r,t);if(!o.length&&!e.thread_ts){for(let u of t){if(!qa(u).auto_subscribe?.includes(e.channel.id))continue;rp(u,`t-${e.ts}`,{channel:e.channel.id,thread_ts:e.ts,note:"auto: new top-level message"},{shared:!0,asOwner:!0})}o=za(e.channel.id,r,t)}let i=[],l=new Set;for(let u of o){if(l.has(u.scope.dir))continue;if(l.add(u.scope.dir),Ok(u.scope,{ts:e.ts,channel:e.channel.id,channel_name:e.channel.name,...e.thread_ts?{thread_ts:e.thread_ts}:{},user:e.user.id,user_name:e.user.name,text:e.text,...e.files?{files:e.files}:{},permalink:e.permalink,alias:u.name,received_at:n.toISOString()},s))i.push(u.scope.dir)}return i}function Qp(e,t){let n;try{n=Sk(e).filter((r)=>r.endsWith(".yml"))}catch{return[]}let s=[];for(let r of n.sort()){let o=Ot(e,r);try{let i=t(Bun.YAML.parse(_k(o,"utf8")));if(i)s.push({file:o,entry:i,mtimeMs:$k(o).mtimeMs})}catch{}}return s}function Rk(e){let t=e;return t&&typeof t.ts==="string"&&typeof t.channel==="string"&&typeof t.text==="string"?t:void 0}function ls(e){return Qp(Ot(e.dir,"inbox"),Rk).sort((t,n)=>Number(t.entry.ts)-Number(n.entry.ts))}function gc(e,t){let n=ls(e),s=Tk.test(t)?n.find((o)=>o.entry.ts===t):n.find((o)=>o.file===t||o.file.endsWith(`/${t}`)||o.file.endsWith(`/${t}.yml`));if(!s)return;let r=Ot(e.dir,"archived",s.file.slice(s.file.lastIndexOf("/")+1));return Ek(s.file,r),r}function Ik(e){let t=e;return t&&typeof t.to==="string"&&typeof t.text==="string"?t:void 0}function mc(e){return Qp(Ot(e.dir,"outbox"),Ik)}function eh(e,t,n=new Date){let s=Ot(e.dir,"outbox",`${n.toISOString().replace(/[:.]/g,"-")}-${process.pid}.yml`),r=_o(t.text);return Pn(s,Xs({...t,text:r.text})),{file:s,redacted:r.kinds}}function th(e,t,n,s=new Date){let r=t.file.slice(t.file.lastIndexOf("/")+1),o=_o(t.entry.text),{error:i,...l}=t.entry;if(Pn(Ot(e.dir,"sent",r),Xs({...l,text:o.text,...o.kinds.length?{redacted:o.kinds}:{},...n,sent_at:s.toISOString()})),Ck(t.file),t.entry.in_reply_to)gc(e,t.entry.in_reply_to);return Ot(e.dir,"sent",r)}function nh(e,t){Pn(e.file,Xs({...e.entry,attempts:(e.entry.attempts??0)+1,error:t}))}function sh(e,t=Date.now()){let n=qa(e).nudge_after_min??30;return ls(e).filter((s)=>t-s.mtimeMs>=n*60000)}function rh(e,t=new Date){Pn(e.file,Xs({...e.entry,nudged_at:t.toISOString()}));let n=new Date(e.mtimeMs);Ak(e.file,n,n)}var bc=[{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"}],nA=bc.length,vk="question",Pk=`:${vk}: `,Lk="heavy_plus_sign",yc=`:${Lk}: `;var Nk="information_source",oh=`:${Nk}: `,ah=["ja","en"];var Eo={get ja(){return ih("ja")},get en(){return ih("en")}};function ih(e){let t=(n,s)=>lo(e,n,s);return{instructionReactionThread:t("instructionReactionThread"),instructionReactionHere:t("instructionReactionHere"),instructionTextThread:t("instructionTextThread"),instructionTextHere:t("instructionTextHere"),overflowNote:t("overflowNote"),otherThread:`${yc}${t("otherThread")}`,otherHere:`${yc}${t("otherHere")}`,explainLine:`${oh}${t("explainLine")}`,explainNote:`${oh}${t("explainNote")}`,invalidPrefix:t("invalidPrefix"),answeredVia:(n,s)=>t("answeredVia",{how:n,who:s?` (${s})`:""}),howReaction:(n)=>t("howReaction",{glyph:n}),howReply:t("howReply"),howReplyN:(n)=>t("howReplyN",{n}),voidStamp:(n)=>t("voidStamp",{reason:n?`: ${n}`:""}),supersededBy:(n)=>t("supersededBy",{link:n})}}var sA=ah.flatMap((e)=>[Eo[e].otherThread,Eo[e].otherHere].map((t)=>Pk+t.slice(yc.length)));var ch="_";function lh(e){if(e===void 0||!e.endsWith(ch))return null;return ah.find((t)=>e.startsWith(Eo[t].invalidPrefix))??null}function wc(e){let t=e.split(`
388
- `),n=t[t.length-2];if(!lh(n))return[];return[...n.matchAll(/<@([UW][A-Z0-9]+)>/g)].map((s)=>s[1])}function uh(e,t,n="ja"){let s=e.split(`
389
- `);if(s.length<2)return e;if(wc(e).length)s.splice(s.length-2,1);if(t.length)s.splice(s.length-1,0,`${Eo[n].invalidPrefix}${t.map((o)=>`<@${o}>`).join(", ")}${ch}`);let r=s.join(`
390
- `);return r===e?e:r}function dh(e){return lh(e)!==null}var Mk="white_check_mark",rA=`:${Mk}: `,Bk="no_entry_sign",oA=`:${Bk}: `;var _t=bc,us=_t.length,Zs="ballot_box_with_ballot",kc=`:${Zs}: `,ph="_下のリアクションで投票してください (1 人 1 票、押し直しで変更できます)。_",hh="_下のリアクションで投票してください (当てはまるものを *いくつでも* 押せます)。_",$o="_締切: ",Co="_",xc="bar_chart",Dc=`:${xc}: `;function Ao(e){return`:${_t[e].name}:`}function fh(e,t){for(let n of[Ao(t),_t[t].glyph])if(e.startsWith(`${n} `))return e.slice(n.length+1);return null}function jk(e){return _t.some((t,n)=>e.startsWith(`${Ao(n)} `)||e.startsWith(`${t.glyph} `))}function Vs(e){return e.replace(/\s*\n\s*/g," ")}function gh(e,t,n,s={}){let r=!!s.multi,o=s.deadline??"",i=s.invalid??[];if(!n.length||n.length>us)throw Error(`poll needs 1..${us} choices, got ${n.length}`);let l=[`${kc}*${e}*`];if(t)l.push("",t);if(l.push(""),l.push(...n.map((u,f)=>`${Ao(f)} ${Vs(u)}`)),l.push(""),o)l.push(`${$o}${Vs(o)}${Co}`);return l.push(r?hh:ph),uh(l.join(`
391
- `),r?[]:i)}function mh(e,t){let n=t.reduce((r,o)=>r+o.count,0),s=[`${Dc}*${e}*`,`_投票終了 (計 ${n} 票)_`,""];return s.push(...t.map((r,o)=>`${Ao(o)} ×${r.count} ${Vs(r.choice)}`)),s.join(`
392
- `)}function Qs(e){let t=e.split(`
393
- `);if(e.startsWith(Dc)){let d=t[0].slice(Dc.length).replace(/^\*/,"").replace(/\*$/,""),p=[];for(let h=0;h<_t.length;h++){let g=t.map((m)=>fh(m,h)).find((m)=>m!==null&&m.startsWith("×"));if(g===void 0)break;let y=/^×(\d+) (.*)$/.exec(g);if(!y)return{kind:"other"};p.push({choice:y[2],count:Number(y[1])})}if(!p.length)return{kind:"other"};return{kind:"closed",question:d,tallies:p}}let n=t[t.length-1]??"",s;if(n===ph)s=!1;else if(n===hh)s=!0;else return{kind:"other"};if(t[0].startsWith(kc))t[0]=t[0].slice(kc.length);if(!t[0].startsWith("*"))return{kind:"other"};let r=0;while(r<t.length&&!(t[r].endsWith("*")&&(r>0||t[0].length>1)))r++;if(r>=t.length)return{kind:"other"};let o=t.slice(0,r+1).join(`
394
- `).replace(/^\*/,"").replace(/\*$/,""),i=t.length-2,l=wc(e);if(dh(t[i]))i--;let u="",f=t[i];if(f!==void 0&&f.startsWith($o)&&f.endsWith(Co)&&f.length>$o.length+Co.length)u=f.slice($o.length,-Co.length),i--;if(t[i]!=="")return{kind:"other"};i--;let a=[];while(i>=0){let d=t[i];if(!jk(d))break;a.unshift(d),i--}if(!a.length||a.length>us)return{kind:"other"};let c=[];for(let d=0;d<a.length;d++){let p=fh(a[d],d);if(p===null)return{kind:"other"};c.push(p)}if(t[i]!=="")return{kind:"other"};if(i<r+1)return{kind:"other"};return{kind:"open",question:o,choices:c,multi:s,deadline:u,invalid:l}}function yh(e,t,n,s){let r=new Map(t.map((f)=>[f.name,f.users])),o=e.map((f,a)=>(r.get(_t[a].name)??[]).filter((c)=>!n.has(c))),i=[];if(!s){let f=new Map;for(let a of o)for(let c of a)f.set(c,(f.get(c)??0)+1);for(let[a,c]of f)if(c>1)i.push(a)}let l=new Set(i),u=o.map((f)=>f.filter((a)=>!l.has(a)));return{tallies:e.map((f,a)=>({choice:f,count:u[a].length})),voters:u,ambiguous:i}}function Wk(e=process.env){return!!e.VITEST||e.NODE_ENV==="test"||!!e.BUN_TEST}var bh={isTestEnv:()=>Wk(),sleep:(e)=>bh.isTestEnv()?Promise.resolve():new Promise((t)=>setTimeout(t,e))};function Uk(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 To(e,t,n,s=Uk()){for(let r=0;r<e.length;r++){let o=!0;try{await t(e[r])}catch(i){o=!1,n(e[r],i)}if(o&&s>0&&r<e.length-1)await bh.sleep(s)}}var wh=["text","select","user","link","date","number","checkbox"];function Dh(e){let t=e.split(":"),n=(t[0]??"").trim(),s=(t[1]??"text").trim();if(!n)throw Error(`--col needs a name: ${e}`);if(!wh.includes(s))throw Error(`--col ${e}: unknown type "${s}" (expected one of ${wh.join(", ")})`);if(s==="select"){let r=(t.slice(2).join(":")||"").split(",").map((o)=>o.trim()).filter(Boolean);if(!r.length)throw Error(`--col ${e}: a select column needs choices, e.g. ${n}:select:todo,doing,done`);return{name:n,type:s,choices:r}}if(t.length>2)throw Error(`--col ${e}: only select columns take a third part`);return{name:n,type:s}}var kh=["gray","blue","green","yellow","red","purple","orange","pink","cyan","indigo","brown"];function xh(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 s={key:`col${n+1}`,name:t.name,type:t.type};if(n===0)s.is_primary_column=!0;if(t.type==="select")s.options={format:"single_select",choices:t.choices.map((r,o)=>({value:r,label:r,color:kh[o%kh.length]}))};if(t.type==="user")s.options={format:"single_entity"};return s})}function Sh(e){return((e.list_metadata??e.metadata??{}).schema??e.schema??[]).map((s)=>{let r=s??{},i=((r.options??{}).choices??[]).map((l)=>{let u=l??{};return{value:String(u.value??""),label:String(u.label??u.value??"")}});return{id:String(r.id??""),key:String(r.key??""),name:String(r.name??""),type:String(r.type??""),choices:i}})}function Sc(e,t){let n=e.find((s)=>s.name===t)??e.find((s)=>s.key===t)??e.find((s)=>s.id===t);if(!n)throw Error(`no column "${t}" in this list (columns: ${e.map((s)=>s.name||s.key).join(", ")})`);return n}function _c(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((s)=>s.value===t||s.label===t);if(!n)throw Error(`"${t}" is not an option of ${e.name} (options: ${e.choices.map((s)=>s.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 Ec(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 _h(e){return e.find((t)=>t.key==="todo_completed"||t.type==="todo_completed")}import{spawnSync as Cc}from"node:child_process";import{chmodSync as Jk,existsSync as $h,mkdirSync as Kk}from"node:fs";import{homedir as qk,hostname as Hk}from"node:os";import{basename as Ch,dirname as zk,join as Yk}from"node:path";function Oo(){return!/^(0|off|false|no)$/i.test(Pe("ATTRIBUTION")??"")}var Fo={claude:"claude-code",codex:"codex",gemini:"gemini",opencode:"opencode","cursor-agent":"cursor-agent",aider:"aider",amp:"amp"};function Gk(e){try{let n=(Cc("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:Ch(n[2].trim())}}catch{return}}function Xk(){let e=process.ppid;for(let t=0;t<12&&e>1;t++){let n=Gk(e);if(!n)return;if(Fo[n.comm])return n;e=n.ppid}return}function Eh(e){let t=Number(e);return Number.isInteger(t)&&t>0?t:void 0}function Ah(e=process.env){let t={pid:process.pid,host:Vk(),cwd:process.cwd()},n=Pe("AGENT_CLI",e)||void 0;if(!n&&e.AI_AGENT)n=e.AI_AGENT.split("_")[0]||void 0;if(!n&&e.CLAUDECODE==="1")n="claude-code";let s=Eh(Pe("AGENT_PID",e))??Eh(e.CLAUDE_PID);if(!s||!n){let i=Xk();if(i)s??=i.pid,n??=Fo[i.comm]}if(n)t.cli=n;if(s)t.agentPid=s;let r=Pe("AGENT_SESSION",e)||e.CLAUDE_CODE_SESSION_ID;if(r)t.sessionId=r;let o=Zk(t.cwd);if(o)t.gitBranch=o;return t}function Vk(){try{return Hk()}catch{return""}}function Zk(e){try{let t=Cc("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:e,encoding:"utf8",timeout:2000});return(t.status===0?(t.stdout??"").trim():"")||void 0}catch{return}}var Qk="slack_hub_sent";function Th(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:Qk,event_payload:n}}function Rt(){let e=Pe("SENT_DB");if(e)return e;return Yk(process.env.HOME||qk(),".config","slack-cli","sent.sqlite")}function eD(e){try{if(typeof globalThis.Bun<"u"){let{Database:n}=Ds("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 tD=`
384
+ `);return null}var Cc=/:([a-z0-9_+'-]+):((?::skin-tone-[2-6]:)?)/g,U0=/<([A-Za-z][A-Za-z0-9+.-]*:[^|<>\s]*)(?:\|([^<>]*))?>/g,J0=/&(amp|lt|gt);/g,K0=/[︎️]/gu,q0=/[\u{1F3FB}-\u{1F3FF}]/gu,fh=String.raw`:[a-z0-9_+'-]+:(?::skin-tone-[2-6]:)?`,H0=String.raw`©®‼⁉™ℹ←-⇿⌀-⏿Ⓜ■-➿⤀-⥿⬀-⯿〰〽㊗㊙\u{1F000}-\u{1FAFF}`,ph=String.raw`[${H0}][\u{E0020}-\u{E007F}]*`,z0=new RegExp(String.raw`(?<sc>${fh}(?:‍${fh})*)|(?<emoji>[0-9#*]⃣|[\u{1F1E6}-\u{1F1FF}]{2}|${ph}(?:‍${ph})*)|(?<char>[\s\S])`,"gu");function Ac(e){let t=new Map,n=[e??null],s=0;while(n.length&&s++<1e5){let r=n.pop();if(Array.isArray(r))n.push(...r);else if(r&&typeof r==="object"){let{name:o,unicode:i}=r;if(r.type==="emoji"&&typeof o==="string"&&typeof i==="string")try{t.set(o.split("::")[0],i.split("-").filter(Boolean).map((a)=>String.fromCodePoint(parseInt(a,16))).join(""))}catch{}n.push(...Object.values(r))}}return t}function Y0(e,t,n){if(n===void 0)return t;for(let s of["http://","mailto:"])if(t.slice(0,s.length).toLowerCase()===s&&n===t.slice(s.length))return n;return e}function tr(e,t){let n=e.normalize("NFC");return n=n.replace(U0,(s,r,o)=>Y0(s,r,o)),n=n.replace(J0,(s,r)=>({amp:"&",lt:"<",gt:">"})[r]),n=n.replace(Cc,(s,r)=>t.get(r)??s),n=n.replace(K0,"").replace(q0,""),n.split(/\s+/).filter(Boolean).join(" ")}function hh(e){return[...e.matchAll(z0)].map((t)=>{let n=t.groups;return n.sc!==void 0?["sc",n.sc]:n.emoji!==void 0?["emoji",n.emoji]:["char",n.char]})}function gh(e,t){let n=Ac(t.blocks),s=tr(e,n),r=tr(typeof t.text==="string"?t.text:"",n);if(s===r)return!0;if(Cc.lastIndex=0,!Cc.test(r))return!1;let o=hh(s),i=hh(r);return o.length===i.length&&o.every(([a,c],d)=>c===i[d][1]||i[d][0]==="sc"&&a==="emoji")}function mh(e,t){let n=0;while(n<e.length&&n<t.length&&e[n]===t[n])n++;let s=Math.max(0,n-10);return`char ${n}: sent ${JSON.stringify(e.slice(s,n+30))}, stored ${JSON.stringify(t.slice(s,n+30))}`}function G0(e){return e.replace(/```[\s\S]*?```/g," ").replace(/`[^`\n]*`/g," ").replace(/<[^>\s]*>/g," ").replace(/https?:\/\/\S+/g," ")}function yh(e){let t=Op();for(let n of G0(e).split(`
385
+ `))for(let s of t)if(s.re.test(n))return s.lang;return}function bh(e){return`hint: this looks like a choice question — use slack ask '${e}' "<question>" <choice>… so the reader can tap an answer instead of typing it`}import{existsSync as Dh,readdirSync as sD,readFileSync as rD,renameSync as oD,statSync as iD,unlinkSync as aD,utimesSync as cD}from"node:fs";import{join as vt}from"node:path";import{readFileSync as X0}from"node:fs";function wh(e){let t="";for(;;){let o=/^\(\?([is]+)\)/.exec(e);if(!o)break;t+=o[1],e=e.slice(o[0].length)}e=e.replaceAll("(?P<","(?<").replaceAll("\\z","$").replaceAll("[[:alnum:]]","[A-Za-z0-9]").replaceAll("[:alnum:]","A-Za-z0-9").replaceAll("[:alpha:]","A-Za-z").replaceAll("[:digit:]","0-9").replaceAll("[:space:]","\\s");let n="",s=[],r=0;for(let o=0;o<e.length;o++){let i=e[o];if(i==="\\"){n+=i+(e[o+1]??""),o++;continue}if(i==="["){let a=o+1;if(e[a]==="^")a++;if(e[a]==="]")a++;while(a<e.length&&e[a]!=="]"){if(e[a]==="\\")a++;a++}n+=e.slice(o,a+1),o=a;continue}if(e.startsWith("(?i)",o)){n+="(?i:",r++,o+=3;continue}if(i==="("){s.push(r),r=0,n+=i;continue}if(i===")"){n+=")".repeat(r),r=s.pop()??0,n+=i;continue}if(i==="|"&&r){n+=")".repeat(r)+"|"+"(?i:".repeat(r);continue}n+=i}return n+=")".repeat(r),{source:n,flags:[...new Set(t)].join("")}}function V0(e){let t=Bun.TOML.parse(e),n=(i)=>{let a=wh(i);return new RegExp(a.source,a.flags)},s=(t.allowlist?.regexes??[]).map(n),r=(t.allowlist?.stopwords??[]).map((i)=>i.toLowerCase()),o=[];for(let i of t.rules){if(!i.regex)continue;let a=[...s],c=[],d=[],f=[...r];for(let g of[...i.allowlists??[],...i.allowlist?[i.allowlist]:[]]){let y=g.regexTarget==="match"?c:g.regexTarget==="line"?d:a;for(let k of g.regexes??[])y.push(n(k));for(let k of g.stopwords??[])f.push(String(k).toLowerCase())}let p=wh(i.regex);o.push({id:i.id,re:new RegExp(p.source,p.flags+"gd"),keywords:(i.keywords??[]).map((g)=>g.toLowerCase()),...i.entropy?{entropy:i.entropy}:{},...i.secretGroup?{group:i.secretGroup}:{},allow:a,...c.length?{allowMatch:c}:{},...d.length?{allowLine:d}:{},stop:f})}return o}var Z0=[{id:"url-secret-param",re:/[?&](?:access_token|token|key|api_key|apikey|secret|client_secret|password|passwd|pwd|sig|signature)=([^&\s#<>"'|]{6,})/gid,group:1,keywords:["="],allow:[/^(?:x+|\*+|\.\.\.|your[-_]?\w*|xxx\w*)$/i],stop:[]},{id:"sk-key",re:/\b(sk-(?:proj-|ant-|or-v1-|svcacct-)?[A-Za-z0-9_-]{20,})/gd,group:1,keywords:["sk-"],entropy:3.5,allow:[],stop:[]},{id:"otp-code",re:/(?:code|コード|otp|pin|passcode|認証|確認番号|ワンタイム)[^\d\n]{0,20}(?<![\d.])(\d{6})(?![\d.])/gid,group:1,keywords:[],allow:[],stop:[]}],kh;function Q0(){return kh??=[...V0(X0(new URL("./vendor/gitleaks.toml",import.meta.url),"utf8")),...Z0],kh}function eD(e){let t=new Map;for(let s of e)t.set(s,(t.get(s)??0)+1);let n=0;for(let s of t.values()){let r=s/e.length;n-=r*Math.log2(r)}return n}function tD(e,t){let n=new Set;for(let r of t){if(r.length<6)continue;n.add(r),n.add(JSON.stringify(r).slice(1,-1))}let s=[];for(let r of[...n].sort((o,i)=>i.length-o.length))for(let o=e.indexOf(r);o>=0;o=e.indexOf(r,o+r.length))s.push({id:"known-secret",start:o,end:o+r.length});return s}function nD(e,t={}){let n=t.rules??Q0(),s=e.toLowerCase(),r=t.known?.length?tD(e,t.known):[];for(let o of n){if(o.keywords.length&&!o.keywords.some((i)=>s.includes(i)))continue;for(let i of e.matchAll(o.re)){let a=o.group??i.findIndex((p,g)=>g>0&&!!p),c=a>0?i[a]:i[0];if(!c)continue;if(o.entropy&&eD(c)<o.entropy)continue;if(o.allow.some((p)=>p.test(c)))continue;if(o.allowMatch?.some((p)=>p.test(i[0])))continue;if(o.allowLine){let p=e.lastIndexOf(`
386
+ `,i.index)+1,g=e.indexOf(`
387
+ `,i.index+i[0].length);if(o.allowLine.some((y)=>y.test(e.slice(p,g<0?void 0:g))))continue}let d=c.toLowerCase();if(o.stop.some((p)=>d.includes(p)))continue;let f=o.group?i.indices?.[o.group]:void 0;if(f)r.push({id:o.id,start:f[0],end:f[1]});else{let p=i.index,g=i.index+i[0].length,y=/[\s'"`;=:,]/;while(p<g&&y.test(e[p]))p++;for(;;)if(g>p&&y.test(e[g-1]))g--;else if(g-2>=p&&/\\[nr]/.test(e.slice(g-2,g)))g-=2;else break;r.push({id:o.id,start:p,end:g})}}}return r}function vo(e,t={}){let n=nD(e,t).sort((i,a)=>i.start-a.start||a.end-i.end);if(!n.length)return{text:e,kinds:[]};let s=[];for(let i of n){let a=s[s.length-1];if(a&&i.start<a.end){if(i.end-i.start>a.end-a.start)a.id=i.id;a.end=Math.max(a.end,i.end)}else s.push({...i})}let r="",o=0;for(let i of s)r+=e.slice(o,i.start)+`[redacted:${i.id}]`,o=i.end;return{text:r+e.slice(o),kinds:[...new Set(s.map((i)=>i.id))]}}var lD=/^\d{10}\.\d{6}$/;function uD(e,t){return`${e}-${t}.yml`}function nr(e){return Bun.YAML.stringify(e,null,2)+`
388
+ `}function dD(e,t,n=[]){let s=uD(t.channel,t.ts);if(Dh(vt(e.dir,"inbox",s))||Dh(vt(e.dir,"archived",s)))return!1;let r=vo(t.text,{known:n}),o={...t,text:r.text,...r.kinds.length?{redacted:r.kinds}:{}};return Bn(vt(e.dir,"inbox",s),nr(o)),!0}function xh(e,t=oc(),n=new Date,s=[]){let r=e.thread_ts??e.ts,o=ic(e.channel.id,r,t);if(!o.length&&!e.thread_ts){for(let c of t){if(!rc(c).auto_subscribe?.includes(e.channel.id))continue;$p(c,`t-${e.ts}`,{channel:e.channel.id,thread_ts:e.ts,note:"auto: new top-level message"},{shared:!0,asOwner:!0})}o=ic(e.channel.id,r,t)}let i=[],a=new Set;for(let c of o){if(a.has(c.scope.dir))continue;if(a.add(c.scope.dir),dD(c.scope,{ts:e.ts,channel:e.channel.id,channel_name:e.channel.name,...e.thread_ts?{thread_ts:e.thread_ts}:{},user:e.user.id,user_name:e.user.name,text:e.text,...e.files?{files:e.files}:{},permalink:e.permalink,alias:c.name,received_at:n.toISOString()},s))i.push(c.scope.dir)}return i}function Sh(e,t){let n;try{n=sD(e).filter((r)=>r.endsWith(".yml"))}catch{return[]}let s=[];for(let r of n.sort()){let o=vt(e,r);try{let i=t(Bun.YAML.parse(rD(o,"utf8")));if(i)s.push({file:o,entry:i,mtimeMs:iD(o).mtimeMs})}catch{}}return s}function fD(e){let t=e;return t&&typeof t.ts==="string"&&typeof t.channel==="string"&&typeof t.text==="string"?t:void 0}function hs(e){return Sh(vt(e.dir,"inbox"),fD).sort((t,n)=>Number(t.entry.ts)-Number(n.entry.ts))}function Tc(e,t){let n=hs(e),s=lD.test(t)?n.find((o)=>o.entry.ts===t):n.find((o)=>o.file===t||o.file.endsWith(`/${t}`)||o.file.endsWith(`/${t}.yml`));if(!s)return;let r=vt(e.dir,"archived",s.file.slice(s.file.lastIndexOf("/")+1));return oD(s.file,r),r}function pD(e){let t=e;return t&&typeof t.to==="string"&&typeof t.text==="string"?t:void 0}function Fc(e){return Sh(vt(e.dir,"outbox"),pD)}function _h(e,t,n=new Date){let s=vt(e.dir,"outbox",`${n.toISOString().replace(/[:.]/g,"-")}-${process.pid}.yml`),r=vo(t.text);return Bn(s,nr({...t,text:r.text})),{file:s,redacted:r.kinds}}function Eh(e,t,n,s=new Date){let r=t.file.slice(t.file.lastIndexOf("/")+1),o=vo(t.entry.text),{error:i,...a}=t.entry;if(Bn(vt(e.dir,"sent",r),nr({...a,text:o.text,...o.kinds.length?{redacted:o.kinds}:{},...n,sent_at:s.toISOString()})),aD(t.file),t.entry.in_reply_to)Tc(e,t.entry.in_reply_to);return vt(e.dir,"sent",r)}function $h(e,t){Bn(e.file,nr({...e.entry,attempts:(e.entry.attempts??0)+1,error:t}))}function Ch(e,t=Date.now()){let n=rc(e).nudge_after_min??30;return hs(e).filter((s)=>t-s.mtimeMs>=n*60000)}function Ah(e,t=new Date){Bn(e.file,nr({...e.entry,nudged_at:t.toISOString()}));let n=new Date(e.mtimeMs);cD(e.file,n,n)}var Ic=[{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"}],JA=Ic.length,hD="question",gD=`:${hD}: `,mD="heavy_plus_sign",Oc=`:${mD}: `;var yD="information_source",Th=`:${yD}: `,Oh=["ja","en"];var Po={get ja(){return Fh("ja")},get en(){return Fh("en")}};function Fh(e){let t=(n,s)=>ko(e,n,s);return{instructionReactionThread:t("instructionReactionThread"),instructionReactionHere:t("instructionReactionHere"),instructionTextThread:t("instructionTextThread"),instructionTextHere:t("instructionTextHere"),overflowNote:t("overflowNote"),otherThread:`${Oc}${t("otherThread")}`,otherHere:`${Oc}${t("otherHere")}`,explainLine:`${Th}${t("explainLine")}`,explainNote:`${Th}${t("explainNote")}`,invalidPrefix:t("invalidPrefix"),answeredVia:(n,s)=>t("answeredVia",{how:n,who:s?` (${s})`:""}),howReaction:(n)=>t("howReaction",{glyph:n}),howReply:t("howReply"),howReplyN:(n)=>t("howReplyN",{n}),voidStamp:(n)=>t("voidStamp",{reason:n?`: ${n}`:""}),supersededBy:(n)=>t("supersededBy",{link:n})}}var KA=Oh.flatMap((e)=>[Po[e].otherThread,Po[e].otherHere].map((t)=>gD+t.slice(Oc.length)));var Ih="_";function Rh(e){if(e===void 0||!e.endsWith(Ih))return null;return Oh.find((t)=>e.startsWith(Po[t].invalidPrefix))??null}function Rc(e){let t=e.split(`
389
+ `),n=t[t.length-2];if(!Rh(n))return[];return[...n.matchAll(/<@([UW][A-Z0-9]+)>/g)].map((s)=>s[1])}function vh(e,t,n="ja"){let s=e.split(`
390
+ `);if(s.length<2)return e;if(Rc(e).length)s.splice(s.length-2,1);if(t.length)s.splice(s.length-1,0,`${Po[n].invalidPrefix}${t.map((o)=>`<@${o}>`).join(", ")}${Ih}`);let r=s.join(`
391
+ `);return r===e?e:r}function Ph(e){return Rh(e)!==null}var bD="white_check_mark",qA=`:${bD}: `,wD="no_entry_sign",HA=`:${wD}: `;var Et=Ic,gs=Et.length,rr="ballot_box_with_ballot",vc=`:${rr}: `,Nh="_下のリアクションで投票してください (1 人 1 票、押し直しで変更できます)。_",Mh="_下のリアクションで投票してください (当てはまるものを *いくつでも* 押せます)。_",Lo="_締切: ",No="_",Lc="bar_chart",Pc=`:${Lc}: `;function Mo(e){return`:${Et[e].name}:`}function Lh(e,t){for(let n of[Mo(t),Et[t].glyph])if(e.startsWith(`${n} `))return e.slice(n.length+1);return null}function kD(e){return Et.some((t,n)=>e.startsWith(`${Mo(n)} `)||e.startsWith(`${t.glyph} `))}function sr(e){return e.replace(/\s*\n\s*/g," ")}function Bh(e,t,n,s={}){let r=!!s.multi,o=s.deadline??"",i=s.invalid??[];if(!n.length||n.length>gs)throw Error(`poll needs 1..${gs} choices, got ${n.length}`);let a=[`${vc}*${e}*`];if(t)a.push("",t);if(a.push(""),a.push(...n.map((c,d)=>`${Mo(d)} ${sr(c)}`)),a.push(""),o)a.push(`${Lo}${sr(o)}${No}`);return a.push(r?Mh:Nh),vh(a.join(`
392
+ `),r?[]:i)}function jh(e,t){let n=t.reduce((r,o)=>r+o.count,0),s=[`${Pc}*${e}*`,`_投票終了 (計 ${n} 票)_`,""];return s.push(...t.map((r,o)=>`${Mo(o)} ×${r.count} ${sr(r.choice)}`)),s.join(`
393
+ `)}function or(e){let t=e.split(`
394
+ `);if(e.startsWith(Pc)){let g=t[0].slice(Pc.length).replace(/^\*/,"").replace(/\*$/,""),y=[];for(let k=0;k<Et.length;k++){let w=t.map((l)=>Lh(l,k)).find((l)=>l!==null&&l.startsWith("×"));if(w===void 0)break;let u=/^×(\d+) (.*)$/.exec(w);if(!u)return{kind:"other"};y.push({choice:u[2],count:Number(u[1])})}if(!y.length)return{kind:"other"};return{kind:"closed",question:g,tallies:y}}let n=t[t.length-1]??"",s;if(n===Nh)s=!1;else if(n===Mh)s=!0;else return{kind:"other"};if(t[0].startsWith(vc))t[0]=t[0].slice(vc.length);if(!t[0].startsWith("*"))return{kind:"other"};let r=0;while(r<t.length&&!(t[r].endsWith("*")&&(r>0||t[0].length>1)))r++;if(r>=t.length)return{kind:"other"};let o=t.slice(0,r+1).join(`
395
+ `).replace(/^\*/,"").replace(/\*$/,""),i=t.length-2,a=Rc(e);if(Ph(t[i]))i--;let c="",d=t[i];if(d!==void 0&&d.startsWith(Lo)&&d.endsWith(No)&&d.length>Lo.length+No.length)c=d.slice(Lo.length,-No.length),i--;if(t[i]!=="")return{kind:"other"};i--;let f=[];while(i>=0){let g=t[i];if(!kD(g))break;f.unshift(g),i--}if(!f.length||f.length>gs)return{kind:"other"};let p=[];for(let g=0;g<f.length;g++){let y=Lh(f[g],g);if(y===null)return{kind:"other"};p.push(y)}if(t[i]!=="")return{kind:"other"};if(i<r+1)return{kind:"other"};return{kind:"open",question:o,choices:p,multi:s,deadline:c,invalid:a}}function Wh(e,t,n,s){let r=new Map(t.map((d)=>[d.name,d.users])),o=e.map((d,f)=>(r.get(Et[f].name)??[]).filter((p)=>!n.has(p))),i=[];if(!s){let d=new Map;for(let f of o)for(let p of f)d.set(p,(d.get(p)??0)+1);for(let[f,p]of d)if(p>1)i.push(f)}let a=new Set(i),c=o.map((d)=>d.filter((f)=>!a.has(f)));return{tallies:e.map((d,f)=>({choice:d,count:c[f].length})),voters:c,ambiguous:i}}function DD(e=process.env){return!!e.VITEST||e.NODE_ENV==="test"||!!e.BUN_TEST}var Uh={isTestEnv:()=>DD(),sleep:(e)=>Uh.isTestEnv()?Promise.resolve():new Promise((t)=>setTimeout(t,e))};function xD(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 Bo(e,t,n,s=xD()){for(let r=0;r<e.length;r++){let o=!0;try{await t(e[r])}catch(i){o=!1,n(e[r],i)}if(o&&s>0&&r<e.length-1)await Uh.sleep(s)}}var Jh=["text","select","user","link","date","number","checkbox"];function qh(e){let t=e.split(":"),n=(t[0]??"").trim(),s=(t[1]??"text").trim();if(!n)throw Error(`--col needs a name: ${e}`);if(!Jh.includes(s))throw Error(`--col ${e}: unknown type "${s}" (expected one of ${Jh.join(", ")})`);if(s==="select"){let r=(t.slice(2).join(":")||"").split(",").map((o)=>o.trim()).filter(Boolean);if(!r.length)throw Error(`--col ${e}: a select column needs choices, e.g. ${n}:select:todo,doing,done`);return{name:n,type:s,choices:r}}if(t.length>2)throw Error(`--col ${e}: only select columns take a third part`);return{name:n,type:s}}var Kh=["gray","blue","green","yellow","red","purple","orange","pink","cyan","indigo","brown"];function Hh(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 s={key:`col${n+1}`,name:t.name,type:t.type};if(n===0)s.is_primary_column=!0;if(t.type==="select")s.options={format:"single_select",choices:t.choices.map((r,o)=>({value:r,label:r,color:Kh[o%Kh.length]}))};if(t.type==="user")s.options={format:"single_entity"};return s})}function zh(e){return((e.list_metadata??e.metadata??{}).schema??e.schema??[]).map((s)=>{let r=s??{},i=((r.options??{}).choices??[]).map((a)=>{let c=a??{};return{value:String(c.value??""),label:String(c.label??c.value??"")}});return{id:String(r.id??""),key:String(r.key??""),name:String(r.name??""),type:String(r.type??""),choices:i}})}function Nc(e,t){let n=e.find((s)=>s.name===t)??e.find((s)=>s.key===t)??e.find((s)=>s.id===t);if(!n)throw Error(`no column "${t}" in this list (columns: ${e.map((s)=>s.name||s.key).join(", ")})`);return n}function Mc(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((s)=>s.value===t||s.label===t);if(!n)throw Error(`"${t}" is not an option of ${e.name} (options: ${e.choices.map((s)=>s.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 Bc(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 Yh(e){return e.find((t)=>t.key==="todo_completed"||t.type==="todo_completed")}import{spawnSync as Wc}from"node:child_process";import{chmodSync as SD,existsSync as Xh,mkdirSync as _D}from"node:fs";import{homedir as ED,hostname as $D}from"node:os";import{basename as Vh,dirname as CD,join as AD}from"node:path";function Wo(){return!/^(0|off|false|no)$/i.test(Ae("ATTRIBUTION")??"")}var jo={claude:"claude-code",codex:"codex",gemini:"gemini",opencode:"opencode","cursor-agent":"cursor-agent",aider:"aider",amp:"amp"};function TD(e){try{let n=(Wc("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:Vh(n[2].trim())}}catch{return}}function FD(){let e=process.ppid;for(let t=0;t<12&&e>1;t++){let n=TD(e);if(!n)return;if(jo[n.comm])return n;e=n.ppid}return}function Gh(e){let t=Number(e);return Number.isInteger(t)&&t>0?t:void 0}function Zh(e=process.env){let t={pid:process.pid,host:OD(),cwd:process.cwd()},n=Ae("AGENT_CLI",e)||void 0;if(!n&&e.AI_AGENT)n=e.AI_AGENT.split("_")[0]||void 0;if(!n&&e.CLAUDECODE==="1")n="claude-code";let s=Gh(Ae("AGENT_PID",e))??Gh(e.CLAUDE_PID);if(!s||!n){let i=FD();if(i)s??=i.pid,n??=jo[i.comm]}if(n)t.cli=n;if(s)t.agentPid=s;let r=Ae("AGENT_SESSION",e)||e.CLAUDE_CODE_SESSION_ID;if(r)t.sessionId=r;let o=ID(t.cwd);if(o)t.gitBranch=o;return t}function OD(){try{return $D()}catch{return""}}function ID(e){try{let t=Wc("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:e,encoding:"utf8",timeout:2000});return(t.status===0?(t.stdout??"").trim():"")||void 0}catch{return}}var RD="slack_hub_sent";function Qh(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:RD,event_payload:n}}function Pt(){let e=Ae("SENT_DB");if(e)return e;return AD(process.env.HOME||ED(),".config","slack-cli","sent.sqlite")}function vD(e){try{if(typeof globalThis.Bun<"u"){let{Database:n}=$e("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 PD=`
395
396
  CREATE TABLE IF NOT EXISTS sent (
396
397
  id INTEGER PRIMARY KEY AUTOINCREMENT,
397
398
  kind TEXT NOT NULL,
@@ -423,170 +424,176 @@ CREATE TABLE IF NOT EXISTS sent (
423
424
  );
424
425
  CREATE INDEX IF NOT EXISTS sent_msg ON sent(channel, ts);
425
426
  CREATE INDEX IF NOT EXISTS sent_at ON sent(sent_at);
426
- `;function Ro(){let e=Rt();try{Kk(zk(e),{recursive:!0})}catch{}let t=eD(e);if(!t)return;try{Jk(e,384)}catch{}try{t.exec(tD);for(let n of["delivered_answer TEXT","delivered_cursor TEXT","pushed_at INTEGER","pushed_answer TEXT","identity TEXT"])try{t.exec(`ALTER TABLE sent ADD COLUMN ${n}`)}catch{}return t}catch{try{t.close()}catch{}return}}function Fh(e){if(!Oo())return!1;let t=Ro();if(!t)return console.error(` (could not record to the sent log: ${er} — ${Rt()})`),!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, identity)
427
- 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,Pe("IDENTITY")||null),!0}catch(n){return console.error(` (could not record to the sent log: ${n instanceof Error?n.message:String(n)})`),!1}finally{try{t.close()}catch{}}}var er="cannot open the sent log: this runtime has no SQLite (needs bun, or node >= 22.5 for node:sqlite)";function Ac(e){let t=Ro();if(!t)return;try{let n=[],s=[];if(e.text)n.push("text LIKE ? ESCAPE '\\'"),s.push(`%${$c(e.text)}%`);if(e.channel)n.push("(channel = ? OR target = ?)"),s.push(e.channel,e.channel);if(e.sinceMs!==void 0)n.push("sent_at >= ?"),s.push(e.sinceMs);if(e.session)n.push("session_id LIKE ? ESCAPE '\\'"),s.push(`${$c(e.session)}%`);if(e.cwd)n.push("cwd LIKE ? ESCAPE '\\'"),s.push(`${$c(e.cwd)}%`);if(e.kind)n.push("kind = ?"),s.push(e.kind);let r=`SELECT * FROM sent${n.length?` WHERE ${n.join(" AND ")}`:""} ORDER BY sent_at DESC, id DESC LIMIT ?`;return s.push(e.limit??50),t.prepare(r).all(...s)}finally{try{t.close()}catch{}}}function $c(e){return e.replace(/[\\%_]/g,(t)=>`\\${t}`)}function ds(e,t=Date.now()){let n=e.trim().match(/^(\d+(?:\.\d+)?)\s*(s|m|h|d|w)$/i);if(n){let r={s:1000,m:60000,h:3600000,d:86400000,w:604800000}[n[2].toLowerCase()];return t-Number(n[1])*r}let s=Date.parse(e);return Number.isNaN(s)?void 0:s}function tr(e,...t){if(!Oo()||!$h(Rt()))return;let n=Ro();if(!n)return;try{n.prepare(e).run(...t)}catch{}finally{try{n.close()}catch{}}}function Tc(e,t,n,s){let r=Date.now();tr(`UPDATE sent SET collected_at = COALESCE(collected_at, ?), answer = ?, answer_exit = 0,
427
+ `;function Uo(){let e=Pt();try{_D(CD(e),{recursive:!0})}catch{}let t=vD(e);if(!t)return;try{SD(e,384)}catch{}try{t.exec(PD);for(let n of["delivered_answer TEXT","delivered_cursor TEXT","pushed_at INTEGER","pushed_answer TEXT","identity TEXT"])try{t.exec(`ALTER TABLE sent ADD COLUMN ${n}`)}catch{}return t}catch{try{t.close()}catch{}return}}function eg(e){if(!Wo())return!1;let t=Uo();if(!t)return console.error(` (could not record to the sent log: ${ir} — ${Pt()})`),!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, identity)
428
+ 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,Ae("IDENTITY")||null),!0}catch(n){return console.error(` (could not record to the sent log: ${n instanceof Error?n.message:String(n)})`),!1}finally{try{t.close()}catch{}}}var ir="cannot open the sent log: this runtime has no SQLite (needs bun, or node >= 22.5 for node:sqlite)";function Uc(e){let t=Uo();if(!t)return;try{let n=[],s=[];if(e.text)n.push("text LIKE ? ESCAPE '\\'"),s.push(`%${jc(e.text)}%`);if(e.channel)n.push("(channel = ? OR target = ?)"),s.push(e.channel,e.channel);if(e.sinceMs!==void 0)n.push("sent_at >= ?"),s.push(e.sinceMs);if(e.session)n.push("session_id LIKE ? ESCAPE '\\'"),s.push(`${jc(e.session)}%`);if(e.cwd)n.push("cwd LIKE ? ESCAPE '\\'"),s.push(`${jc(e.cwd)}%`);if(e.kind)n.push("kind = ?"),s.push(e.kind);let r=`SELECT * FROM sent${n.length?` WHERE ${n.join(" AND ")}`:""} ORDER BY sent_at DESC, id DESC LIMIT ?`;return s.push(e.limit??50),t.prepare(r).all(...s)}finally{try{t.close()}catch{}}}function jc(e){return e.replace(/[\\%_]/g,(t)=>`\\${t}`)}function ms(e,t=Date.now()){let n=e.trim().match(/^(\d+(?:\.\d+)?)\s*(s|m|h|d|w)$/i);if(n){let r={s:1000,m:60000,h:3600000,d:86400000,w:604800000}[n[2].toLowerCase()];return t-Number(n[1])*r}let s=Date.parse(e);return Number.isNaN(s)?void 0:s}function ar(e,...t){if(!Wo()||!Xh(Pt()))return;let n=Uo();if(!n)return;try{n.prepare(e).run(...t)}catch{}finally{try{n.close()}catch{}}}function Jc(e,t,n,s){let r=Date.now();ar(`UPDATE sent SET collected_at = COALESCE(collected_at, ?), answer = ?, answer_exit = 0,
428
429
  delivered_at = ?, delivered_answer = ?, delivered_cursor = ?
429
- WHERE kind = 'ask' AND channel = ? AND ts = ?`,r,n,r,n,s,e,t)}function Fc(e,t,n,s){tr(`UPDATE sent SET delivered_at = ?, delivered_answer = ?, delivered_cursor = ?
430
- WHERE kind = 'ask' AND channel = ? AND ts = ? AND collected_at IS NULL`,Date.now(),n,s,e,t)}function Oh(e,t,n){tr("UPDATE sent SET pushed_at = ?, pushed_answer = ? WHERE kind = 'ask' AND channel = ? AND ts = ?",Date.now(),n,e,t)}function Rh(e,t,n){tr("UPDATE sent SET identity = ? WHERE kind = 'ask' AND channel = ? AND ts = ?",n,e,t)}function Io(e,t,n){tr("UPDATE sent SET collected_at = COALESCE(collected_at, ?), answer_exit = ? WHERE kind = 'ask' AND channel = ? AND ts = ?",Date.now(),n,e,t)}function Oc(e){if(!$h(Rt()))return[];let t=Ro();if(!t)return;try{return t.prepare("SELECT * FROM sent WHERE kind = 'ask' AND collected_at IS NULL AND sent_at >= ? ORDER BY sent_at ASC, id ASC").all(e)}finally{try{t.close()}catch{}}}function Ih(e){let t=e.agent_pid??e.pid;if(!nD(t))return!1;try{let s=(Cc("ps",["-o","lstart=,comm=","-p",String(t)],{encoding:"utf8",timeout:2000}).stdout??"").trim(),r=Date.parse(s.slice(0,24));if(!Number.isNaN(r)&&r>e.sent_at+1000)return!1;let o=Ch(s.slice(24).trim()),i=new Set(Object.values(Fo));if(e.cli&&i.has(e.cli)&&o&&Fo[o]!==e.cli)return!1}catch{}return!0}function nD(e){if(!e||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}class ot 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 vc(){return(process.env.SLACK_API_BASE??"https://slack.com/api").replace(/\/$/,"")}var Lh=(()=>{let e=Number(process.env.SLACK_RATELIMIT_WAIT_SEC);return Number.isFinite(e)&&e>=0?e:120})();function Pc(e){Lh=e}async function Nh(e,t=(n)=>new Promise((s)=>setTimeout(s,n))){let n=0;for(;;)try{return await e()}catch(s){if(!(s instanceof ot)||n+s.retryAfter>Lh)throw s;n+=s.retryAfter,console.error(`slack: ${s.message} — waiting`),await t(s.retryAfter*1000)}}function Mh(e,t,n,s){return Nh(()=>sD(e,t,n,s))}async function sD(e,t,n,s){s=e.startsWith("xoxc-")?s??sn():void 0;let r={};if(s)r.Cookie=`d=${s}`;let o=await fetch(`${vc()}/${t}`,{...n,headers:{...n.headers??{},Authorization:`Bearer ${e}`,...r}});if(o.status===429){let l=parseInt(o.headers.get("retry-after")??"60",10);throw new ot(isNaN(l)?60:l,t)}let i=await o.json();if(i.ok!==!0){let l=i.error??"unknown";if(l==="ratelimited")throw new ot(60,t);if(l==="invalid_auth"&&e.startsWith("xoxc-")&&!s)throw Error(`Desktop app token (xoxc-) needs its session cookie to be accepted by the public Slack API.
430
+ WHERE kind = 'ask' AND channel = ? AND ts = ?`,r,n,r,n,s,e,t)}function Kc(e,t,n,s){ar(`UPDATE sent SET delivered_at = ?, delivered_answer = ?, delivered_cursor = ?
431
+ WHERE kind = 'ask' AND channel = ? AND ts = ? AND collected_at IS NULL`,Date.now(),n,s,e,t)}function tg(e,t,n){ar("UPDATE sent SET pushed_at = ?, pushed_answer = ? WHERE kind = 'ask' AND channel = ? AND ts = ?",Date.now(),n,e,t)}function ng(e,t,n){ar("UPDATE sent SET identity = ? WHERE kind = 'ask' AND channel = ? AND ts = ?",n,e,t)}function Jo(e,t,n){ar("UPDATE sent SET collected_at = COALESCE(collected_at, ?), answer_exit = ? WHERE kind = 'ask' AND channel = ? AND ts = ?",Date.now(),n,e,t)}function qc(e){if(!Xh(Pt()))return[];let t=Uo();if(!t)return;try{return t.prepare("SELECT * FROM sent WHERE kind = 'ask' AND collected_at IS NULL AND sent_at >= ? ORDER BY sent_at ASC, id ASC").all(e)}finally{try{t.close()}catch{}}}function sg(e){let t=e.agent_pid??e.pid;if(!LD(t))return!1;try{let s=(Wc("ps",["-o","lstart=,comm=","-p",String(t)],{encoding:"utf8",timeout:2000}).stdout??"").trim(),r=Date.parse(s.slice(0,24));if(!Number.isNaN(r)&&r>e.sent_at+1000)return!1;let o=Vh(s.slice(24).trim()),i=new Set(Object.values(jo));if(e.cli&&i.has(e.cli)&&o&&jo[o]!==e.cli)return!1}catch{}return!0}function LD(e){if(!e||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}class it 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 Ko(){return(process.env.SLACK_API_BASE??"https://slack.com/api").replace(/\/$/,"")}function ND(e){return URL.canParse(e)?new URL(e).origin:e}async function ys(e,t,n){try{return await fetch(t,n)}catch{throw Error(`Slack request failed on ${e}: no answer from ${ND(t)}`)}}async function Gc(e,t){let n;try{n=await t.text()}catch{throw Error(`Slack request failed on ${e}: the answer (HTTP ${t.status}) was cut off`)}try{return JSON.parse(n)}catch{throw Error(`Slack error on ${e}: the answer (HTTP ${t.status}) is not JSON`)}}var ig=(()=>{let e=Number(process.env.SLACK_RATELIMIT_WAIT_SEC);return Number.isFinite(e)&&e>=0?e:120})();function Xc(e){ig=e}async function ag(e,t=(n)=>new Promise((s)=>setTimeout(s,n))){let n=0;for(;;)try{return await e()}catch(s){if(!(s instanceof it)||n+s.retryAfter>ig)throw s;n+=s.retryAfter,console.error(`slack: ${s.message} — waiting`),await t(s.retryAfter*1000)}}function cg(e,t,n,s){return ag(()=>MD(e,t,n,s))}async function MD(e,t,n,s){s=e.startsWith("xoxc-")?s??Ot():void 0;let r={};if(s)r.Cookie=`d=${s}`;let o=performance.now(),i=await ys(t,`${Ko()}/${t}`,{...n,headers:{...n.headers??{},Authorization:`Bearer ${e}`,...r}});if(qo(t.replace(/\?.*$/,""),i.status,performance.now()-o),i.status===429){let c=parseInt(i.headers.get("retry-after")??"60",10);throw new it(isNaN(c)?60:c,t)}let a=await Gc(t,i);if(a.ok!==!0){let c=a.error??"unknown";if(c==="ratelimited")throw new it(60,t);if(c==="invalid_auth"&&e.startsWith("xoxc-")&&!s)throw Error(`Desktop app token (xoxc-) needs its session cookie to be accepted by the public Slack API.
431
432
  Attach it: slack auth firefox (Linux/macOS/Windows) or slack auth chrome (macOS/Linux)
432
433
  Or replace the token with an xoxp- user token:
433
- slack auth login`);if((l==="missing_scope"||l==="cannot_dm_bot")&&e.startsWith("xoxb-")){if(t.startsWith("agents.sessions."))throw Error(`Slack error on ${t}: ${l}. Agent sessions need a granular bot token with chat:write and app membership in the channel.`);throw Error(`Slack error on ${t}: ${l} — ${l==="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"}.
434
+ 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"}.
434
435
  Tailing/DMing people and listing users need a user session, not a bot token.
435
436
  Switch workspace: slack auth ls then slack auth use <name>
436
- Or import your Slack desktop session: slack auth login`)}throw Error(`Slack error on ${t}: ${l}`)}return i}function rD(e,t,n,s){return Nh(()=>oD(e,t,n,s))}async function oD(e,t,n,s){let r={};if(s)r.Cookie=`d=${s}`;let o=await fetch(`${vc()}/${t}`,{...n,headers:{...n.headers??{},Authorization:`Bearer ${e}`,...r}});if(o.status===429){let l=parseInt(o.headers.get("retry-after")??"60",10);throw new ot(isNaN(l)?60:l,t)}let i=await o.json();if(i.ok!==!0){let l=i.error??"unknown";if(l==="ratelimited")throw new ot(60,t);if((l==="invalid_auth"||l==="not_authed")&&!e.startsWith("xoxc-"))throw Error(`${t} requires a desktop app session token (xoxc-).
437
- Import from Slack desktop: slack auth login`);if((l==="invalid_auth"||l==="not_authed")&&!s)throw Error(`${t} also requires the xoxd session cookie.
438
- Attach it with: slack auth firefox (Linux/macOS/Windows) or slack auth chrome (macOS/Linux)`);throw Error(`Slack error on ${t}: ${l}`)}return i}function Et(e,t,n={},s){let r=new URLSearchParams({token:e,...n});return rD(e,t,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:r.toString()},s)}function ke(e,t,n,s){let r=new URLSearchParams(n).toString();return Mh(e,`${t}?${r}`,{method:"GET"},s)}function Oe(e,t,n,s){return Mh(e,t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)},s)}async function Lc(e,t){let n=await ke(e,"auth.test",{},t);return{team:n.team??"",teamId:n.team_id??"",url:n.url??"",user:n.user??"",userId:n.user_id??""}}async function Ut(e,t){t=e.startsWith("xoxc-")?t??sn():void 0;let n={Authorization:`Bearer ${e}`};if(t)n.Cookie=`d=${t}`;let s=await fetch(`${vc()}/auth.test`,{method:"GET",headers:n});if(s.status===429){let i=parseInt(s.headers.get("retry-after")??"60",10);throw new ot(isNaN(i)?60:i,"auth.test")}let r=s.headers.get("x-oauth-scopes")??"",o=await s.json();if(o.ok!==!0)throw Error(`Slack error on auth.test: ${o.error??"unknown"}`);return{userId:o.user_id??"",user:o.user??"",botId:o.bot_id??"",team:o.team??"",url:o.url??"",scopes:r.split(",").map((i)=>i.trim()).filter(Boolean)}}async function Bh(e,t,n){let s=await ke(e,"bots.info",{bot:t},n);return{appId:s.bot?.app_id??"",userId:s.bot?.user_id??""}}async function it(e,t,n=20,s,r,o,i){let l={channel:t,limit:String(n)};if(s!==void 0)l.oldest=s;if(r!==void 0)l.cursor=r;if(i)l.inclusive="true";return vo(await ke(e,"conversations.history",l,o))}function vo(e){let t=e,n=Array.isArray(t.messages)?t.messages:t.messages&&typeof t.messages==="object"&&Array.isArray(t.messages.matches)?t.messages.matches:[];for(let s of n)Wr(s);return e}async function Le(e,t,n,s=50,r){return vo(await ke(e,"conversations.replies",{channel:t,ts:n,limit:String(s)},r))}async function Nc(e,t,n,s={},r){let o={channel:t,ts:n,limit:String(s.limit??200)};if(s.oldest!==void 0)o.oldest=s.oldest;if(s.cursor!==void 0)o.cursor=s.cursor;return vo(await ke(e,"conversations.replies",o,r))}async function jh(e,t,n){return ke(e,"files.info",{file:t},n)}async function Wh(e,t={},n){let s={count:String(Math.min(Math.max(t.count??100,1),200)),page:String(Math.max(t.page??1,1))};if(t.types)s.types=t.types;if(t.channel)s.channel=t.channel;if(t.user)s.user=t.user;return ke(e,"files.list",s,n)}async function Uh(e,t,n,s){let r={name:t,schema:n};if(s)r.todo_mode=!0;return await Oe(e,"slackLists.create",r)}async function Mc(e,t,n={}){let s={list_id:t};if(n.limit)s.limit=n.limit;if(n.cursor)s.cursor=n.cursor;if(n.includeList)s.include_list=!0;return await Oe(e,"slackLists.items.list",s)}async function Jh(e,t,n){return await Oe(e,"slackLists.items.create",{list_id:t,initial_fields:n})}async function Kh(e,t,n,s){let r={list_id:t,access_level:n};if(s.userIds?.length)r.user_ids=s.userIds;if(s.channelIds?.length)r.channel_ids=s.channelIds;return await Oe(e,"slackLists.access.set",r)}async function qh(e,t,n){return await Oe(e,"slackLists.items.update",{list_id:t,cells:n})}async function Hh(e,t,n={},s){let r={list_id:t};if(n.limit)r.limit=String(n.limit);if(n.cursor)r.cursor=n.cursor;return Et(e,"lists.records.list",r,s)}async function zh(e,t,n,s,r){return vo(await ke(e,"search.messages",{query:t,sort:"timestamp",sort_dir:"desc",count:String(Math.min(Math.max(n,1),100)),page:String(Math.max(s,1))},r))}async function Yh(e,t,n){return zh(e,t,100,1,n)}async function Bc(e,t,n,s){let o=1,i=[],l={ok:!0,messages:{}};while(!0){let f=await zh(e,t,100,o,s),a=nr(f,["messages","matches"]),c=Array.isArray(a)?a:[];i.push(...c);let d=Number(nr(f,["messages","paging","pages"])??1);if(l=f,c.length===0||o>=d||i.length>=n)break;o+=1}let u=l;if(!u.messages)u.messages={};return u.messages.matches=i.slice(0,n),u}async function Jt(e,t,n,s,r,o,i,l){let u=i?{channel:t,text:n}:{channel:t,text:n,blocks:[{type:"markdown",text:n}]};if(s!==void 0)u.thread_ts=s;if(r&&s!==void 0)u.reply_broadcast=!0;return(await Gh(e,"chat.postMessage",u,l,o)).ts??""}function iD(e){return e instanceof Error&&/: (invalid_metadata\w*|metadata_\w+)$/.test(e.message)}async function Gh(e,t,n,s,r){if(!s)return Oe(e,t,n,r);try{return await Oe(e,t,{...n,metadata:s},r)}catch(o){if(!iD(o))throw o;return Oe(e,t,n,r)}}async function Xh(e,t,n,s,r,o){let i={channel:t,text:n,post_at:s,blocks:[{type:"markdown",text:n}]};if(r!==void 0)i.thread_ts=r;return(await Oe(e,"chat.scheduleMessage",i,o)).scheduled_message_id??""}async function Vh(e,t,n){let s={};if(t)s.channel=t;return ke(e,"chat.scheduledMessages.list",s,n)}async function Zh(e,t,n,s){await Oe(e,"chat.deleteScheduledMessage",{channel:t,scheduled_message_id:n},s)}async function jn(e,t,n,s){return(await ke(e,"chat.getPermalink",{channel:t,message_ts:n},s)).permalink??""}async function Kt(e,t,n,s,r,o,i){return(await Gh(e,"chat.update",o?{channel:t,ts:n,text:s}:{channel:t,ts:n,text:s,blocks:[{type:"markdown",text:s}]},i,r)).ts??n}async function Qh(e,t,n,s){await Oe(e,"chat.delete",{channel:t,ts:n},s)}async function eg(e,t,n,s,r=200,o){let i={channel:t,ts:n,limit:String(r)};if(s!==void 0)i.cursor=s;return ke(e,"conversations.replies",i,o)}async function jc(e,t,n,s){await Oe(e,"pins.add",{channel:t,timestamp:n},s)}async function It(e,t,n,s,r){await Oe(e,"reactions.add",{channel:t,timestamp:n,name:s},r)}async function tg(e,t,n,s){return((await ke(e,"reactions.get",{channel:t,timestamp:n,full:"true"},s)).message?.reactions??[]).map((o)=>({name:String(o.name??""),users:Array.isArray(o.users)?o.users.map(String):[]}))}async function qt(e,t,n,s,r){await Oe(e,"reactions.remove",{channel:t,timestamp:n,name:s},r)}async function ng(e,t,n=!1,s){let r=await Oe(e,"conversations.create",{name:t,is_private:n},s);return{id:r.channel?.id??"",name:r.channel?.name??t}}async function sg(e,t,n,s){let r=await Oe(e,"conversations.rename",{channel:t,name:n},s);return{id:r.channel?.id??t,name:r.channel?.name??n}}async function Wc(e,t,n,s){await Oe(e,"conversations.invite",{channel:t,users:n.join(",")},s)}async function sr(e,t){let n=[],s="";while(!0){let r={limit:"200",types:"public_channel,private_channel,im,mpim"};if(s)r.cursor=s;let o=await ke(e,"conversations.list",r,t);if(n.push(...o.channels??[]),s=o.response_metadata?.next_cursor??"",!s)break}return{channels:n}}async function Ht(e,t,n){let r=(await Oe(e,"conversations.open",{users:t},n)).channel?.id;if(!r)throw Error(`Failed to open DM with user ${t}`);return r}async function rg(e,t,n){let s="";while(!0){let r={types:"im",limit:"200"};if(s)r.cursor=s;let o=await ke(e,"conversations.list",r,n);for(let i of o.channels??[])if(i.user===t)return String(i.id??"");if(s=o.response_metadata?.next_cursor??"",!s)break}return""}async function Rc(e,t,n,s){let r=await rg(e,t,n);if(r)return r;let o=s?`${s} (${t})`:t;throw Error(`No existing DM with ${o}. Open it once in Slack first.`)}function Bn(e){return e.toLowerCase().replace(/[-_\s]/g,"")}function vh(e,t){let n=Bn(e.name??""),s=Bn(e.real_name??e.profile?.real_name??""),r=Bn(e.profile?.display_name??"");return n===t||s===t||!!r&&r===t}var og=200;async function ig(e,t,n){let s=0,r=new Set,o="";while(!0){let a={limit:"200"};if(o)a.cursor=o;let c=await ke(e,"users.list",a,n);for(let d of c.members??[]){if(s++,d.id)r.add(d.id);if(vh(d,t))return{id:d.id??"",workspaceCount:s,connectCount:0,skipped:0,capped:!1}}if(o=c.response_metadata?.next_cursor??"",!o)break}let i=0,l=0,u=!1,f="";while(!0){let a={types:"im",limit:"200"};if(f)a.cursor=f;let c=await ke(e,"conversations.list",a,n);for(let d of c.channels??[]){let p=d.user;if(!p||r.has(p))continue;if(i>=og){u=!0;break}r.add(p),i++;let h;try{h=(await ke(e,"users.info",{user:p},n)).user}catch(g){if(g instanceof ot)throw g;l++;continue}if(h&&vh(h,t))return{id:p,dm:String(d.id??""),workspaceCount:s,connectCount:i,skipped:l,capped:u}}if(u)break;if(f=c.response_metadata?.next_cursor??"",!f)break}return{id:"",workspaceCount:s,connectCount:i,skipped:l,capped:u}}function ag(e,t){if(t.workspaceCount===0)return Error(`Cannot resolve ${e}: users.list returned no members at all, so nothing could have matched.
437
+ Or import your Slack desktop session: slack auth login`)}throw Error(`Slack error on ${t}: ${c}${ug(c,e)}`)}return a}var zc;function lg(e){zc=e}var BD=new Set(["invalid_auth","not_authed","token_revoked","token_expired","account_inactive"]);function ug(e,t=""){if(!BD.has(e))return"";if(t.startsWith("xoxb-"))return` (bot token from ${process.env.SLACK_HUB_IDENTITY?`identity @${process.env.SLACK_HUB_IDENTITY}`:"SLACK_BOT_TOKEN"})`;return zc?` (token from ${zc})`:""}function jD(e,t,n,s){return ag(()=>WD(e,t,n,s))}async function WD(e,t,n,s){let r={};if(s)r.Cookie=`d=${s}`;let o=performance.now(),i=await ys(t,`${Ko()}/${t}`,{...n,headers:{...n.headers??{},Authorization:`Bearer ${e}`,...r}});if(qo(t.replace(/\?.*$/,""),i.status,performance.now()-o),i.status===429){let c=parseInt(i.headers.get("retry-after")??"60",10);throw new it(isNaN(c)?60:c,t)}let a=await Gc(t,i);if(a.ok!==!0){let c=a.error??"unknown";if(c==="ratelimited")throw new it(60,t);if((c==="invalid_auth"||c==="not_authed")&&!e.startsWith("xoxc-"))throw Error(`${t} requires a desktop app session token (xoxc-).
438
+ Import from Slack desktop: slack auth login`);if((c==="invalid_auth"||c==="not_authed")&&!s)throw Error(`${t} also requires the xoxd session cookie.
439
+ Attach it with: slack auth firefox (Linux/macOS/Windows) or slack auth chrome (macOS/Linux)`);throw Error(`Slack error on ${t}: ${c}${ug(c,e)}`)}return a}function $t(e,t,n={},s){let r=new URLSearchParams({token:e,...n});return jD(e,t,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:r.toString()},s)}var UD=new Set(["auth.test","conversations.info","users.info"]),JD=60000,Vc=!1,Jn=new Map;function dg(e=!0){Vc=e,Jn.clear()}function fg(e,t,n,s){let r=e.startsWith("xoxc-")?s??Ot():void 0;return JSON.stringify([Ko(),e,r,t,n])}function KD(e,t,n){if(!Vc||!UD.has(t))return n();let s=Jn.get(e);if(s&&Date.now()-s.at<JD)return qo(t,"cached",0),s.value;let r=n();return Jn.set(e,{at:Date.now(),value:r}),r.catch(()=>{if(Jn.get(e)?.value===r)Jn.delete(e)}),r}function qo(e,t,n){if(Ae("TIMING")!=="1")return;console.error(`slack-hub timing: ${(performance.now()/1000).toFixed(2)}s ${e} ${t} ${Math.round(n)}ms`)}function ke(e,t,n,s){let r=new URLSearchParams(n).toString();return KD(fg(e,t,r,s),t,()=>cg(e,`${t}?${r}`,{method:"GET"},s))}function Oe(e,t,n,s){return Jn.clear(),cg(e,t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)},s)}async function Zc(e,t){let n=await ke(e,"auth.test",{},t);return{team:n.team??"",teamId:n.team_id??"",url:n.url??"",user:n.user??"",userId:n.user_id??""}}async function Ct(e,t){t=e.startsWith("xoxc-")?t??Ot():void 0;let n={Authorization:`Bearer ${e}`};if(t)n.Cookie=`d=${t}`;let s=performance.now(),r=await ys("auth.test",`${Ko()}/auth.test`,{method:"GET",headers:n});if(qo("auth.test",r.status,performance.now()-s),r.status===429){let a=parseInt(r.headers.get("retry-after")??"60",10);throw new it(isNaN(a)?60:a,"auth.test")}let o=r.headers.get("x-oauth-scopes")??"",i=await Gc("auth.test",r);if(i.ok!==!0)throw Error(`Slack error on auth.test: ${i.error??"unknown"}`);if(Vc)Jn.set(fg(e,"auth.test","",t),{at:Date.now(),value:Promise.resolve(i)});return{userId:i.user_id??"",user:i.user??"",botId:i.bot_id??"",team:i.team??"",url:i.url??"",scopes:o.split(",").map((a)=>a.trim()).filter(Boolean)}}async function pg(e,t,n){let s=await ke(e,"bots.info",{bot:t},n);return{appId:s.bot?.app_id??"",userId:s.bot?.user_id??""}}async function at(e,t,n=20,s,r,o,i){let a={channel:t,limit:String(n)};if(s!==void 0)a.oldest=s;if(r!==void 0)a.cursor=r;if(i)a.inclusive="true";return Ho(await ke(e,"conversations.history",a,o))}function Ho(e){let t=e,n=Array.isArray(t.messages)?t.messages:t.messages&&typeof t.messages==="object"&&Array.isArray(t.messages.matches)?t.messages.matches:[];for(let s of n)Yr(s);return e}async function Ne(e,t,n,s=50,r){return Ho(await ke(e,"conversations.replies",{channel:t,ts:n,limit:String(s)},r))}async function Qc(e,t,n,s={},r){let o={channel:t,ts:n,limit:String(s.limit??200)};if(s.oldest!==void 0)o.oldest=s.oldest;if(s.cursor!==void 0)o.cursor=s.cursor;return Ho(await ke(e,"conversations.replies",o,r))}async function hg(e,t,n){return ke(e,"files.info",{file:t},n)}async function gg(e,t={},n){let s={count:String(Math.min(Math.max(t.count??100,1),200)),page:String(Math.max(t.page??1,1))};if(t.types)s.types=t.types;if(t.channel)s.channel=t.channel;if(t.user)s.user=t.user;return ke(e,"files.list",s,n)}async function mg(e,t,n,s){let r={name:t,schema:n};if(s)r.todo_mode=!0;return await Oe(e,"slackLists.create",r)}async function el(e,t,n={}){let s={list_id:t};if(n.limit)s.limit=n.limit;if(n.cursor)s.cursor=n.cursor;if(n.includeList)s.include_list=!0;return await Oe(e,"slackLists.items.list",s)}async function yg(e,t,n){return await Oe(e,"slackLists.items.create",{list_id:t,initial_fields:n})}async function bg(e,t,n,s){let r={list_id:t,access_level:n};if(s.userIds?.length)r.user_ids=s.userIds;if(s.channelIds?.length)r.channel_ids=s.channelIds;return await Oe(e,"slackLists.access.set",r)}async function wg(e,t,n){return await Oe(e,"slackLists.items.update",{list_id:t,cells:n})}async function kg(e,t,n={},s){let r={list_id:t};if(n.limit)r.limit=String(n.limit);if(n.cursor)r.cursor=n.cursor;return $t(e,"lists.records.list",r,s)}async function Dg(e,t,n,s,r){return Ho(await ke(e,"search.messages",{query:t,sort:"timestamp",sort_dir:"desc",count:String(Math.min(Math.max(n,1),100)),page:String(Math.max(s,1))},r))}async function xg(e,t,n){return Dg(e,t,100,1,n)}async function tl(e,t,n,s){let o=1,i=[],a={ok:!0,messages:{}};while(!0){let d=await Dg(e,t,100,o,s),f=cr(d,["messages","matches"]),p=Array.isArray(f)?f:[];i.push(...p);let g=Number(cr(d,["messages","paging","pages"])??1);if(a=d,p.length===0||o>=g||i.length>=n)break;o+=1}let c=a;if(!c.messages)c.messages={};return c.messages.matches=i.slice(0,n),c}async function Ht(e,t,n,s,r,o,i,a){let c=i?{channel:t,text:n}:{channel:t,text:n,blocks:[{type:"markdown",text:n}]};if(s!==void 0)c.thread_ts=s;if(r&&s!==void 0)c.reply_broadcast=!0;return(await Sg(e,"chat.postMessage",c,a,o)).ts??""}function qD(e){return e instanceof Error&&/: (invalid_metadata\w*|metadata_\w+)$/.test(e.message)}async function Sg(e,t,n,s,r){if(!s)return Oe(e,t,n,r);try{return await Oe(e,t,{...n,metadata:s},r)}catch(o){if(!qD(o))throw o;return Oe(e,t,n,r)}}async function _g(e,t,n,s,r,o){let i={channel:t,text:n,post_at:s,blocks:[{type:"markdown",text:n}]};if(r!==void 0)i.thread_ts=r;return(await Oe(e,"chat.scheduleMessage",i,o)).scheduled_message_id??""}async function Eg(e,t,n){let s={};if(t)s.channel=t;return ke(e,"chat.scheduledMessages.list",s,n)}async function $g(e,t,n,s){await Oe(e,"chat.deleteScheduledMessage",{channel:t,scheduled_message_id:n},s)}async function qn(e,t,n,s){return(await ke(e,"chat.getPermalink",{channel:t,message_ts:n},s)).permalink??""}async function zt(e,t,n,s,r,o,i){return(await Sg(e,"chat.update",o?{channel:t,ts:n,text:s}:{channel:t,ts:n,text:s,blocks:[{type:"markdown",text:s}]},i,r)).ts??n}async function Cg(e,t,n,s){await Oe(e,"chat.delete",{channel:t,ts:n},s)}async function Ag(e,t,n,s,r=200,o){let i={channel:t,ts:n,limit:String(r)};if(s!==void 0)i.cursor=s;return ke(e,"conversations.replies",i,o)}async function nl(e,t,n,s){await Oe(e,"pins.add",{channel:t,timestamp:n},s)}async function Lt(e,t,n,s,r){let o={channel:t,timestamp:n,name:s};try{await Oe(e,"reactions.add",o,r)}catch(i){if(!e.startsWith("xoxb-")||!t.startsWith("C")||!(i instanceof Error)||i.message!=="Slack error on reactions.add: not_in_channel")throw i;try{await Oe(e,"conversations.join",{channel:t},r)}catch(a){throw Error(`Could not join channel to add reaction: ${a instanceof Error?a.message:String(a)}
440
+ Invite the bot to the channel, or grant channels:join for public channels.`)}await Oe(e,"reactions.add",o,r)}}async function Tg(e,t,n,s){return((await ke(e,"reactions.get",{channel:t,timestamp:n,full:"true"},s)).message?.reactions??[]).map((o)=>({name:String(o.name??""),users:Array.isArray(o.users)?o.users.map(String):[]}))}async function Yt(e,t,n,s,r){await Oe(e,"reactions.remove",{channel:t,timestamp:n,name:s},r)}async function Fg(e,t,n=!1,s){let r=await Oe(e,"conversations.create",{name:t,is_private:n},s);return{id:r.channel?.id??"",name:r.channel?.name??t}}async function Og(e,t,n,s){let r=await Oe(e,"conversations.rename",{channel:t,name:n},s);return{id:r.channel?.id??t,name:r.channel?.name??n}}async function sl(e,t,n,s){await Oe(e,"conversations.invite",{channel:t,users:n.join(",")},s)}async function lr(e,t){let n=[],s="";while(!0){let r={limit:"200",types:"public_channel,private_channel,im,mpim"};if(s)r.cursor=s;let o=await ke(e,"conversations.list",r,t);if(n.push(...o.channels??[]),s=o.response_metadata?.next_cursor??"",!s)break}return{channels:n}}async function Gt(e,t,n){let r=(await Oe(e,"conversations.open",{users:t},n)).channel?.id;if(!r)throw Error(`Failed to open DM with user ${t}`);return r}async function Ig(e,t,n){let s="";while(!0){let r={types:"im",limit:"200"};if(s)r.cursor=s;let o=await ke(e,"conversations.list",r,n);for(let i of o.channels??[])if(i.user===t)return String(i.id??"");if(s=o.response_metadata?.next_cursor??"",!s)break}return""}async function Hc(e,t,n,s){let r=await Ig(e,t,n);if(r)return r;let o=s?`${s} (${t})`:t;throw Error(`No existing DM with ${o}. Open it once in Slack first.`)}function Kn(e){return e.toLowerCase().replace(/[-_\s]/g,"")}function rg(e,t){let n=Kn(e.name??""),s=Kn(e.real_name??e.profile?.real_name??""),r=Kn(e.profile?.display_name??"");return n===t||s===t||!!r&&r===t}var Rg=200;async function vg(e,t,n){let s=0,r=new Set,o="";while(!0){let f={limit:"200"};if(o)f.cursor=o;let p=await ke(e,"users.list",f,n);for(let g of p.members??[]){if(s++,g.id)r.add(g.id);if(rg(g,t))return{id:g.id??"",workspaceCount:s,connectCount:0,skipped:0,capped:!1}}if(o=p.response_metadata?.next_cursor??"",!o)break}let i=0,a=0,c=!1,d="";while(!0){let f={types:"im",limit:"200"};if(d)f.cursor=d;let p=await ke(e,"conversations.list",f,n);for(let g of p.channels??[]){let y=g.user;if(!y||r.has(y))continue;if(i>=Rg){c=!0;break}r.add(y),i++;let k;try{k=(await ke(e,"users.info",{user:y},n)).user}catch(w){if(w instanceof it)throw w;a++;continue}if(k&&rg(k,t))return{id:y,dm:String(g.id??""),workspaceCount:s,connectCount:i,skipped:a,capped:c}}if(c)break;if(d=p.response_metadata?.next_cursor??"",!d)break}return{id:"",workspaceCount:s,connectCount:i,skipped:a,capped:c}}function Pg(e,t){if(t.workspaceCount===0)return Error(`Cannot resolve ${e}: users.list returned no members at all, so nothing could have matched.
439
441
  `+`That is a token or scope fault, not a wrong handle — this says nothing about whether ${e} exists.
440
- 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)`,s=[];if(t.capped)s.push(`stopped after ${og} Slack Connect DM partners, so there may be more`);if(t.skipped)s.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.
442
+ 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)`,s=[];if(t.capped)s.push(`stopped after ${Rg} Slack Connect DM partners, so there may be more`);if(t.skipped)s.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.
441
443
  `+(s.length?`This search was incomplete: ${s.join("; ")}.
442
444
  `:"")+`Slack Connect people from another workspace are not in users.list, so if they never
443
445
  DMed you they cannot be found by name at all. Look them up and use their ID:
444
- slack user ls --external`)}async function vt(e,t,n){let s=t.startsWith("@")?t.slice(1):t;if(Ic(s))return s;if(!t.startsWith("@"))throw Error(`Expected @user or a user ID, got: ${t}`);let r=Bn(s),o=await ke(e,"auth.test",{},n);if(r==="you"||r==="me"||Bn(o.user??"")===r){if(!o.user_id)throw Error("auth.test did not return user_id");return o.user_id}let i=await ig(e,r,n);if(i.id)return i.id;throw ag(t,i)}function pt(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],s=t[2]&&t[3]?`${t[2]}.${t[3]}`:void 0,r=e.indexOf("?"),o=r>=0?new URLSearchParams(e.slice(r)):void 0,i=o?.get("thread_ts")??void 0,f={channel:o?.get("cid")??void 0??n};if(s)f.ts=s;if(i)f.threadTs=i;return f}function aD(e){return pt(e)?.channel}function Ph(e){return/^[CDG][A-Z0-9]{8,}$/.test(e)}function Ic(e){return/^[UW][A-Z0-9]{6,}$/.test(e)}async function we(e,t,n){let s=aD(t);if(s)return s;if(!t.startsWith("@")&&!t.startsWith("#")){if(Ph(t))return t;if(Ic(t))return Rc(e,t,n);throw Error(`Target must start with # or @ (or be a Slack URL/ID), got: ${t}`)}if(t.startsWith("#")&&Ph(t.slice(1)))return t.slice(1);let r=t.startsWith("@"),o=t.slice(1),i=Bn(o);if(r){if(Ic(o))return Rc(e,o,n);let f=await ke(e,"auth.test",{},n);if(i==="you"||i==="me"||Bn(f.user??"")===i){let d=f.user_id;if(!d)throw Error("auth.test did not return user_id");return await rg(e,d,n)||Ht(e,d,n)}let c=await ig(e,i,n);if(!c.id)throw ag(t,c);if(c.dm)return c.dm;return Rc(e,c.id,n,t)}let l=o.toLowerCase(),u="";while(!0){let f={limit:"200",types:"public_channel,private_channel",exclude_archived:"true"};if(u)f.cursor=u;let a=await ke(e,"conversations.list",f,n);for(let c of a.channels??[])if(String(c.name??"").toLowerCase()===l)return String(c.id??"");if(u=a.response_metadata?.next_cursor??"",!u)break}throw Error(`channel not found: ${t}`)}async function rr(e,t,n){try{let s=await ke(e,"users.info",{user:t},n),r=s.user?.profile?.display_name,o=r&&r.length>0?r:s.user?.real_name??s.user?.name??t,i=s.user?.name??t;return[o,i]}catch{return[t,t]}}async function Re(e,t,n){try{let s=await ke(e,"users.info",{user:t},n),r=s.user?.profile?.display_name;if(r&&r.length>0)return r;return s.user?.real_name??s.user?.name??t}catch{return t}}async function cg(e,t){let n=[],s="";while(!0){let r={limit:"200"};if(s)r.cursor=s;let o=await ke(e,"users.list",r,t);if(n.push(...o.members??[]),s=o.response_metadata?.next_cursor??"",!s)break}return{members:n}}async function lg(e,t,n){let s=[],r="";while(!0){let o={channel:t,limit:"200"};if(r)o.cursor=r;let i=await ke(e,"conversations.members",o,n);if(s.push(...i.members??[]),r=i.response_metadata?.next_cursor??"",!r)break}return s}async function Uc(e,t={},n){let s={limit:String(t.limit??50)};if(t.filter)s.filter=t.filter;if(t.cursor)s.cursor=t.cursor;return Et(e,"saved.list",s,n)}var Jc=(e)=>({item_type:"message",item_id:e.channel,ts:e.ts});async function ug(e,t,n={},s){let r={...Jc(t),todo_state:n.todo===!1?"saved":"to_do"};if(n.due)r.date_due=String(n.due);return Et(e,"saved.add",r,s)}async function Kc(e,t,n,s){let r=Jc(t);if(n.mark)r.mark=n.mark;if(n.todo!==void 0)r.todo_state=n.todo?"to_do":"saved";if(n.due!==void 0)r.date_due=String(n.due);return Et(e,"saved.update",r,s)}async function dg(e,t,n){return Et(e,"saved.delete",Jc(t),n)}async function or(e,t){return Et(e,"drafts.list",{},t)}async function fg(e,t,n,s){let{randomUUID:r}=await import("node:crypto"),o=JSON.stringify([{type:"rich_text",elements:[{type:"rich_text_section",elements:jr(n)}]}]);return Et(e,"drafts.create",{client_msg_id:r(),destinations:JSON.stringify([{channel_id:t}]),blocks:o,file_ids:JSON.stringify([]),is_from_composer:"true"},s)}async function pg(e,t,n,s,r){let o=JSON.stringify([{type:"rich_text",elements:[{type:"rich_text_section",elements:jr(s)}]}]),i=(Date.now()/1000).toFixed(6);return Et(e,"drafts.update",{draft_id:t,client_last_updated_ts:i,destinations:JSON.stringify([{channel_id:n}]),blocks:o,file_ids:JSON.stringify([])},r)}async function hg(e,t,n){return Et(e,"conversations.info",{channel:t},n)}async function fs(e,t,n){return ke(e,"users.info",{user:t},n)}async function gg(e,t,n){try{let s=await ke(e,"users.info",{user:t,include_locale:"true"},n);return typeof s.user?.locale==="string"?s.user.locale:void 0}catch{return}}async function Wn(e,t,n){return ke(e,"conversations.info",{channel:t},n)}async function mg(e,t,n){let s=(Date.now()/1000).toFixed(6);return Et(e,"drafts.delete",{draft_id:t,client_last_updated_ts:s},n)}async function qc(e,t){let n=await Et(e,"auth.test",{},t);return{userId:String(n.user_id??""),teamId:String(n.team_id??"")}}async function yg(e,t,n,s={},r){let{statSync:o,readFileSync:i}=await import("node:fs"),{basename:l}=await import("node:path"),u=o(n),f=l(n),a=await ke(e,"files.getUploadURLExternal",{filename:f,length:String(u.size)},r),{upload_url:c,file_id:d}=a;if(!c||!d)throw Error("files.getUploadURLExternal returned no upload_url/file_id");let p=i(n),h=await fetch(c,{method:"POST",headers:{"Content-Type":"application/octet-stream"},body:p});if(!h.ok)throw Error(`Upload PUT failed: ${h.status} ${h.statusText}`);let g={files:[{id:d,title:s.title??f}],channel_id:t};if(s.threadTs)g.thread_ts=s.threadTs;if(s.initialComment)g.initial_comment=s.initialComment;let y=await Oe(e,"files.completeUploadExternal",g,r),m={fileId:d},w=y.files?.[0]?.permalink;if(w)m.permalink=w;return m}function nr(e,t){let n=e;for(let s of t){if(n===void 0||n===null)return;if(typeof s==="number"){if(!Array.isArray(n))return;n=n[s]??void 0}else{if(typeof n!=="object"||Array.isArray(n))return;n=n[s]}}return n}var wg=["todo","saved","completed","archived"],ir=(e)=>typeof e==="string"?e:"",bg=(e)=>{let t=typeof e==="number"||typeof e==="string"?Number(e):0;return Number.isFinite(t)?t:0};function Hc(e){let t=e&&typeof e==="object"&&!Array.isArray(e)?e:{};return(Array.isArray(t.saved_items)?t.saved_items:[]).filter((s)=>!!s&&typeof s==="object"&&!Array.isArray(s)).map((s)=>({channel:ir(s.item_id),ts:ir(s.ts),due:bg(s.date_due),completed:bg(s.date_completed),todoState:ir(s.todo_state),state:ir(s.state),archived:s.is_archived===!0,itemType:ir(s.item_type)}))}function kg(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 ar(e){return e.completed>0||e.state==="completed"||e.todoState==="completed"}function zc(e,t,n){let s=ar(e)?"☑":e.todoState==="to_do"?"☐":"·";if(!e.due)return`${s} no due date`;let r=!ar(e)&&e.due<t?" OVERDUE":"";return`${s} due ${n(e.due)}${r}`}function Yc(e,t,n){return`${e.replace(/\/+$/,"")}/archives/${t}/p${n.replace(".","")}`}import{existsSync as yD,readFileSync as bD}from"node:fs";import{homedir as wD}from"node:os";import{join as kD}from"node:path";import{existsSync as cD,mkdirSync as lD,readFileSync as uD,writeFileSync as dD}from"node:fs";import{homedir as fD}from"node:os";import{dirname as pD,join as hD}from"node:path";var gD=3600000,Po={now:()=>Date.now(),path:()=>hD(process.env.HOME||fD(),".config","slack-cli","cache.json")},Lo=!0,fn;function Dg(){return{channels:{},users:{}}}function Gc(){if(fn)return fn;if(fn=Dg(),!Lo)return fn;try{let e=Po.path();if(!cD(e))return fn;let t=JSON.parse(uD(e,"utf8"));for(let n of["channels","users"]){let s=t?.[n];if(!s||typeof s!=="object"||Array.isArray(s))continue;for(let[r,o]of Object.entries(s))if(o&&typeof o==="object"&&typeof o.value==="string"&&typeof o.expires==="number")fn[n][r]={value:o.value,expires:o.expires}}}catch{fn=Dg()}return fn}function mD(e){if(!Lo)return;try{let t=Po.path();lD(pD(t),{recursive:!0}),dD(t,JSON.stringify(e,null,2)+`
445
- `)}catch{}}function xg(e,t){return e?`${e} ${t}`:void 0}function No(e,t,n){if(!Lo)return;let s=xg(t,n);if(!s)return;let r=Gc()[e][s];if(!r)return;if(r.expires<=Po.now()){delete Gc()[e][s];return}return r.value}function Mo(e,t,n,s,r=gD){if(!Lo)return;let o=xg(t,n);if(!o)return;let i=Gc();i[e][o]={value:s,expires:Po.now()+r},mD(i)}var Xc={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"}},ps=["done","dropped","doing","pending"],$g=["alert","needs-discussion","waiting","blocked"];function DD(){return kD(process.env.HOME||wD(),".config","slack-cli","todo.json")}function Bo(e){return e.replace(/^:+|:+$/g,"")}function cr(e=DD()){let t={marker:Xc.marker,progress:{...Xc.progress},flags:{...Xc.flags}};try{if(!yD(e))return t;let n=JSON.parse(bD(e,"utf8"));if(typeof n.marker==="string"&&n.marker.trim())t.marker=Bo(n.marker.trim());for(let s of ps){let r=n.progress?.[s];if(typeof r==="string"&&r.trim())t.progress[s]=Bo(r.trim())}for(let s of $g){let r=n.flags?.[s];if(typeof r==="string"&&r.trim())t.flags[s]=Bo(r.trim())}}catch{}return t}function Sg(e,t,n=!1){return`${n?"-":""}${t?"has":"hasmy"}::${Bo(e)}:`}function Cg(e,t,n={}){let s=n.shared===!0,r=(l)=>Sg(l,s),o=(l)=>Sg(l,s,!0),i=[];if(e==="untriaged")i.push(r(t.marker),...ps.map((l)=>o(t.progress[l])));else if(e==="stuck")i.push(r(t.marker),o(t.progress.done),o(t.progress.dropped),`(${$g.map((l)=>r(t.flags[l])).join(" OR ")})`);else if(e==="open")i.push(r(t.marker),o(t.progress.done),o(t.progress.dropped));else{let l=ps.indexOf(e);i.push(r(t.progress[e]));for(let u of ps.slice(0,l))i.push(o(t.progress[u]))}if(n.in){let l=n.in.startsWith("#")||n.in.startsWith("@")?n.in:`#${n.in}`;i.push(`in:${l}`)}if(n.from){let l=n.from==="me"||n.from.startsWith("@")?n.from:`@${n.from}`;i.push(`from:${l}`)}return i.join(" ")}var xD=3,SD={sleep:(e)=>_D()?Promise.resolve():new Promise((t)=>setTimeout(t,e))};function _D(){return!!process.env.VITEST||!1||!!process.env.BUN_TEST}async function Ze(e,t,n=xD){for(let s=0;;s++)try{return await t()}catch(r){if(!(r instanceof He))throw r;if(s>=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 ${r.retryAfter}s`),await SD.sleep(r.retryAfter*1000)}}var _g=new Map;async function Ag(e,t){let n=_g.get(e);if(n)return n;let s=await Ze("auth.test",()=>ns(e,t)),r={userId:s.userId,teamId:s.teamId};return _g.set(e,r),r}async function Tg(e,t){return(await Ag(e,t)).userId}async function Vc(e,t){try{return(await Ag(e,t)).teamId}catch{return""}}async function Zc(e,t,n,s){if(!t.startsWith("#"))return n(e,t,s);let r=await Vc(e,s),o=No("channels",r,t);if(o)return o;let i=await Ze("resolveChannel",()=>n(e,t,s));return Mo("channels",r,t,i),i}async function Fg(e,t,n,s){let r=await Vc(e,s),o=No("users",r,t);if(o)return o;let i=await Ze("users.info",()=>n(e,t,s));if(i&&i!==t)Mo("users",r,t,i);return i}async function Og(e,t,n,s){let r=await Vc(e,s),o=No("users",r,`tz:${t}`);if(o)return o==="?"?null:o;let i=null;try{let l=await Ze("users.info",()=>n(e,t,s));if(l?.user?.is_bot===!0||t==="USLACKBOT")return Eg(r,t,null);let u=l?.user?.tz;i=typeof u==="string"&&u?u:null}catch{return null}return Eg(r,t,i)}function Eg(e,t,n){return Mo("users",e,`tz:${t}`,n??"?"),n}async function Rg(e,t,n,s,r,o){let i=r.progress[s],l=await Tg(e,o),u=await Ze("reactions.get",()=>Ld(e,t,n,o)),f=new Set(u.filter((p)=>p.users.includes(l)).map((p)=>p.name)),a=ps.map((p)=>r.progress[p]).filter((p)=>f.has(p));if(a.length===1&&a[0]===i)return{noop:!0,removed:[],leftover:[]};if(!f.has(i))await Ze("reactions.add",()=>Ur(e,t,n,i,o));let c=[],d=[];for(let p of a){if(p===i)continue;try{await Ze("reactions.remove",()=>Jr(e,t,n,p,o)),c.push(p)}catch{d.push(p)}}return{noop:!1,added:s,removed:c,leftover:d}}async function Ig(e,t,n,s,r,o,i){let l=r.flags[s];if(o)await Ze("reactions.remove",()=>Jr(e,t,n,l,i));else await Ze("reactions.add",()=>Ur(e,t,n,l,i));return l}var Qc=1000;async function vg(e,t,n,s={}){let r=s.limit??Qc,o=s.cookie,i=await Tg(e,o),l=ps.map((d)=>n.progress[d]),u=[],f=0,a,c=!1;while(f<r){let d=Math.min(200,r-f),p=await Ze("conversations.history",()=>In(e,t,d,void 0,a,o)),h=p.messages??[];f+=h.length;for(let g of h){let y=String(g.ts??"");if(!y)continue;let m=new Set((g.reactions??[]).filter((k)=>(k.users??[]).map(String).includes(i)).map((k)=>String(k.name??""))),w=l.filter((k)=>m.has(k));if(w.length<2)continue;u.push({ts:y,text:String(g.text??"").split(`
446
- `)[0]??"",emoji:w,keep:w[0]})}if(a=p.response_metadata?.next_cursor||void 0,!a||h.length===0)break;if(f>=r){c=!0;break}}if(s.fix)for(let d of u)try{try{await Ze("reactions.add",()=>Ur(e,t,d.ts,d.keep,o))}catch(p){if(!(p instanceof Error)||!/already_reacted/.test(p.message))throw p}for(let p of d.emoji){if(p===d.keep)continue;await Ze("reactions.remove",()=>Jr(e,t,d.ts,p,o))}d.fixed=!0}catch(p){d.fixed=!1,d.error=p instanceof Error?p.message:String(p)}return{scanned:f,findings:u,truncated:c}}var ED=!0,$D;function el(e){if(ED=e,!e)$D=void 0}function We(e){return e.replace(new RegExp(`[${"\\\\¥"}](.)`,"gs"),(t,n)=>{switch(n){case"n":return`
447
- `;case"t":return"\t";case"\\":case"¥":return n==="¥"?"¥":"\\";default:return t}})}function hs(e){return e.replace(new RegExp(`[${"\\\\¥"}]`,"g"),(t)=>`\\${t}`).replace(/\n/g,"\\n").replace(/\t/g,"\\t")}var gs=(e)=>e&&typeof e==="object"&&!Array.isArray(e)?e:{},Ue=(e)=>typeof e==="string"?e:"";function CD(e){return(Array.isArray(e.message_blocks)?e.message_blocks:[]).map((n)=>Ue(gs(gs(n).message).text)).filter(Boolean).join(`
448
- `)}function tl(e){return(Array.isArray(e.attachments)?e.attachments:[]).map(gs).map((n)=>{let s=n.is_share===!0||n.is_msg_unfurl===!0||Array.isArray(n.message_blocks),r=gs(gs((Array.isArray(n.message_blocks)?n.message_blocks:[])[0]));return{shared:s,unfurl:!s&&!!Ue(n.original_url),author_id:Ue(n.author_id)||Ue(gs(r.message).user)||null,author_name:Ue(n.author_name)||null,channel_id:Ue(n.channel_id)||Ue(r.channel)||null,ts:Ue(n.ts)||Ue(r.ts)||null,title:Ue(n.title)||null,text:Ue(n.text)||CD(n)||Ue(n.pretext)||Ue(n.fallback),permalink:Ue(n.from_url)||Ue(n.title_link)||Ue(n.original_url)||null}})}function Pg(e,t){return e.filter((n)=>!n.unfurl&&(n.text||n.title)).map((n)=>{let s=n.author_name??n.author_id,r=n.shared?`↪ shared message${s?` from @${s}`:""}${n.channel_id?` in <#${n.channel_id}>`:""}${n.ts?` · ${t(n.ts)}`:""}`:`▸ ${n.title??"attachment"}`,o=n.text?n.text.replace(/\n+$/,"").split(`
449
- `).map((l)=>`
450
- │ ${l}`).join(""):"",i=n.permalink?`
446
+ slack user ls --external`)}async function Nt(e,t,n){let s=t.startsWith("@")?t.slice(1):t;if(Yc(s))return s;if(!t.startsWith("@"))throw Error(`Expected @user or a user ID, got: ${t}`);let r=Kn(s),o=await ke(e,"auth.test",{},n);if(r==="you"||r==="me"||Kn(o.user??"")===r){if(!o.user_id)throw Error("auth.test did not return user_id");return o.user_id}let i=await vg(e,r,n);if(i.id)return i.id;throw Pg(t,i)}function ht(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],s=t[2]&&t[3]?`${t[2]}.${t[3]}`:void 0,r=e.indexOf("?"),o=r>=0?new URLSearchParams(e.slice(r)):void 0,i=o?.get("thread_ts")??void 0,d={channel:o?.get("cid")??void 0??n};if(s)d.ts=s;if(i)d.threadTs=i;return d}function HD(e){return ht(e)?.channel}function og(e){return/^[CDG][A-Z0-9]{8,}$/.test(e)}function Yc(e){return/^[UW][A-Z0-9]{6,}$/.test(e)}async function we(e,t,n){let s=HD(t);if(s)return s;if(!t.startsWith("@")&&!t.startsWith("#")){if(og(t))return t;if(Yc(t))return Hc(e,t,n);throw Error(`Target must start with # or @ (or be a Slack URL/ID), got: ${t}`)}if(t.startsWith("#")&&og(t.slice(1)))return t.slice(1);let r=t.startsWith("@"),o=t.slice(1),i=Kn(o);if(r){if(Yc(o))return Hc(e,o,n);let d=await ke(e,"auth.test",{},n);if(i==="you"||i==="me"||Kn(d.user??"")===i){let g=d.user_id;if(!g)throw Error("auth.test did not return user_id");return await Ig(e,g,n)||Gt(e,g,n)}let p=await vg(e,i,n);if(!p.id)throw Pg(t,p);if(p.dm)return p.dm;return Hc(e,p.id,n,t)}let a=o.toLowerCase(),c="";while(!0){let d={limit:"200",types:"public_channel,private_channel",exclude_archived:"true"};if(c)d.cursor=c;let f=await ke(e,"conversations.list",d,n);for(let p of f.channels??[])if(String(p.name??"").toLowerCase()===a)return String(p.id??"");if(c=f.response_metadata?.next_cursor??"",!c)break}throw Error(`channel not found: ${t}`)}async function ur(e,t,n){try{let s=await ke(e,"users.info",{user:t},n),r=s.user?.profile?.display_name,o=r&&r.length>0?r:s.user?.real_name??s.user?.name??t,i=s.user?.name??t;return[o,i]}catch{return[t,t]}}async function ve(e,t,n){try{let s=await ke(e,"users.info",{user:t},n),r=s.user?.profile?.display_name;if(r&&r.length>0)return r;return s.user?.real_name??s.user?.name??t}catch{return t}}async function Lg(e,t){let n=[],s="";while(!0){let r={limit:"200"};if(s)r.cursor=s;let o=await ke(e,"users.list",r,t);if(n.push(...o.members??[]),s=o.response_metadata?.next_cursor??"",!s)break}return{members:n}}async function Ng(e,t,n){let s=[],r="";while(!0){let o={channel:t,limit:"200"};if(r)o.cursor=r;let i=await ke(e,"conversations.members",o,n);if(s.push(...i.members??[]),r=i.response_metadata?.next_cursor??"",!r)break}return s}async function rl(e,t={},n){let s={limit:String(t.limit??50)};if(t.filter)s.filter=t.filter;if(t.cursor)s.cursor=t.cursor;return $t(e,"saved.list",s,n)}var ol=(e)=>({item_type:"message",item_id:e.channel,ts:e.ts});async function Mg(e,t,n={},s){let r={...ol(t),todo_state:n.todo===!1?"saved":"to_do"};if(n.due)r.date_due=String(n.due);return $t(e,"saved.add",r,s)}async function il(e,t,n,s){let r=ol(t);if(n.mark)r.mark=n.mark;if(n.todo!==void 0)r.todo_state=n.todo?"to_do":"saved";if(n.due!==void 0)r.date_due=String(n.due);return $t(e,"saved.update",r,s)}async function Bg(e,t,n){return $t(e,"saved.delete",ol(t),n)}async function dr(e,t){return $t(e,"drafts.list",{},t)}async function jg(e,t,n,s){let{randomUUID:r}=await import("node:crypto"),o=JSON.stringify([{type:"rich_text",elements:[{type:"rich_text_section",elements:zr(n)}]}]);return $t(e,"drafts.create",{client_msg_id:r(),destinations:JSON.stringify([{channel_id:t}]),blocks:o,file_ids:JSON.stringify([]),is_from_composer:"true"},s)}async function Wg(e,t,n,s,r){let o=JSON.stringify([{type:"rich_text",elements:[{type:"rich_text_section",elements:zr(s)}]}]),i=(Date.now()/1000).toFixed(6);return $t(e,"drafts.update",{draft_id:t,client_last_updated_ts:i,destinations:JSON.stringify([{channel_id:n}]),blocks:o,file_ids:JSON.stringify([])},r)}async function Ug(e,t,n){return $t(e,"conversations.info",{channel:t},n)}async function bs(e,t,n){return ke(e,"users.info",{user:t},n)}async function Jg(e,t,n){try{let s=await ke(e,"users.info",{user:t,include_locale:"true"},n);return typeof s.user?.locale==="string"?s.user.locale:void 0}catch{return}}async function Hn(e,t,n){return ke(e,"conversations.info",{channel:t},n)}async function Kg(e,t,n){let s=(Date.now()/1000).toFixed(6);return $t(e,"drafts.delete",{draft_id:t,client_last_updated_ts:s},n)}async function al(e,t){let n=await $t(e,"auth.test",{},t);return{userId:String(n.user_id??""),teamId:String(n.team_id??"")}}async function qg(e,t,n,s={},r){let{statSync:o,readFileSync:i}=await import("node:fs"),{basename:a}=await import("node:path"),c=o(n),d=a(n),f=await ke(e,"files.getUploadURLExternal",{filename:d,length:String(c.size)},r),p=f.upload_url,g=f.file_id;if(!p||!g)throw Error("files.getUploadURLExternal returned no upload_url/file_id");let y=i(n),k=await ys("the upload",p,{method:"POST",headers:{"Content-Type":"application/octet-stream"},body:y});if(!k.ok)throw Error(`Upload PUT failed: ${k.status} ${k.statusText}`);let w={files:[{id:g,title:s.title??d}],channel_id:t};if(s.threadTs)w.thread_ts=s.threadTs;if(s.initialComment)w.initial_comment=s.initialComment;let u=await Oe(e,"files.completeUploadExternal",w,r),l={fileId:g},h=u.files?.[0]?.permalink;if(h)l.permalink=h;return l}function cr(e,t){let n=e;for(let s of t){if(n===void 0||n===null)return;if(typeof s==="number"){if(!Array.isArray(n))return;n=n[s]??void 0}else{if(typeof n!=="object"||Array.isArray(n))return;n=n[s]}}return n}var zg=["todo","saved","completed","archived"],fr=(e)=>typeof e==="string"?e:"",Hg=(e)=>{let t=typeof e==="number"||typeof e==="string"?Number(e):0;return Number.isFinite(t)?t:0};function cl(e){let t=e&&typeof e==="object"&&!Array.isArray(e)?e:{};return(Array.isArray(t.saved_items)?t.saved_items:[]).filter((s)=>!!s&&typeof s==="object"&&!Array.isArray(s)).map((s)=>({channel:fr(s.item_id),ts:fr(s.ts),due:Hg(s.date_due),completed:Hg(s.date_completed),todoState:fr(s.todo_state),state:fr(s.state),archived:s.is_archived===!0,itemType:fr(s.item_type)}))}function Yg(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 pr(e){return e.completed>0||e.state==="completed"||e.todoState==="completed"}function ll(e,t,n){let s=pr(e)?"☑":e.todoState==="to_do"?"☐":"·";if(!e.due)return`${s} no due date`;let r=!pr(e)&&e.due<t?" OVERDUE":"";return`${s} due ${n(e.due)}${r}`}function ul(e,t,n){return`${e.replace(/\/+$/,"")}/archives/${t}/p${n.replace(".","")}`}import{existsSync as nx,readFileSync as sx}from"node:fs";import{homedir as rx}from"node:os";import{join as ox}from"node:path";import{existsSync as zD,mkdirSync as YD,readFileSync as GD,writeFileSync as XD}from"node:fs";import{homedir as VD}from"node:os";import{dirname as ZD,join as QD}from"node:path";var ex=3600000,zo={now:()=>Date.now(),path:()=>QD(process.env.HOME||VD(),".config","slack-cli","cache.json")},Yo=!0,hn;function Gg(){return{channels:{},users:{}}}function dl(){if(hn)return hn;if(hn=Gg(),!Yo)return hn;try{let e=zo.path();if(!zD(e))return hn;let t=JSON.parse(GD(e,"utf8"));for(let n of["channels","users"]){let s=t?.[n];if(!s||typeof s!=="object"||Array.isArray(s))continue;for(let[r,o]of Object.entries(s))if(o&&typeof o==="object"&&typeof o.value==="string"&&typeof o.expires==="number")hn[n][r]={value:o.value,expires:o.expires}}}catch{hn=Gg()}return hn}function tx(e){if(!Yo)return;try{let t=zo.path();YD(ZD(t),{recursive:!0}),XD(t,JSON.stringify(e,null,2)+`
447
+ `)}catch{}}function Xg(e,t){return e?`${e} ${t}`:void 0}function Go(e,t,n){if(!Yo)return;let s=Xg(t,n);if(!s)return;let r=dl()[e][s];if(!r)return;if(r.expires<=zo.now()){delete dl()[e][s];return}return r.value}function Xo(e,t,n,s,r=ex){if(!Yo)return;let o=Xg(t,n);if(!o)return;let i=dl();i[e][o]={value:s,expires:zo.now()+r},tx(i)}var fl={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"}},ws=["done","dropped","doing","pending"],em=["alert","needs-discussion","waiting","blocked"];function ix(){return ox(process.env.HOME||rx(),".config","slack-cli","todo.json")}function Vo(e){return e.replace(/^:+|:+$/g,"")}function hr(e=ix()){let t={marker:fl.marker,progress:{...fl.progress},flags:{...fl.flags}};try{if(!nx(e))return t;let n=JSON.parse(sx(e,"utf8"));if(typeof n.marker==="string"&&n.marker.trim())t.marker=Vo(n.marker.trim());for(let s of ws){let r=n.progress?.[s];if(typeof r==="string"&&r.trim())t.progress[s]=Vo(r.trim())}for(let s of em){let r=n.flags?.[s];if(typeof r==="string"&&r.trim())t.flags[s]=Vo(r.trim())}}catch{}return t}function Vg(e,t,n=!1){return`${n?"-":""}${t?"has":"hasmy"}::${Vo(e)}:`}function tm(e,t,n={}){let s=n.shared===!0,r=(a)=>Vg(a,s),o=(a)=>Vg(a,s,!0),i=[];if(e==="untriaged")i.push(r(t.marker),...ws.map((a)=>o(t.progress[a])));else if(e==="stuck")i.push(r(t.marker),o(t.progress.done),o(t.progress.dropped),`(${em.map((a)=>r(t.flags[a])).join(" OR ")})`);else if(e==="open")i.push(r(t.marker),o(t.progress.done),o(t.progress.dropped));else{let a=ws.indexOf(e);i.push(r(t.progress[e]));for(let c of ws.slice(0,a))i.push(o(t.progress[c]))}if(n.in){let a=n.in.startsWith("#")||n.in.startsWith("@")?n.in:`#${n.in}`;i.push(`in:${a}`)}if(n.from){let a=n.from==="me"||n.from.startsWith("@")?n.from:`@${n.from}`;i.push(`from:${a}`)}return i.join(" ")}var ax=3,cx={sleep:(e)=>lx()?Promise.resolve():new Promise((t)=>setTimeout(t,e))};function lx(){return!!process.env.VITEST||!1||!!process.env.BUN_TEST}async function Qe(e,t,n=ax){for(let s=0;;s++)try{return await t()}catch(r){if(!(r instanceof ze))throw r;if(s>=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 ${r.retryAfter}s`),await cx.sleep(r.retryAfter*1000)}}var Zg=new Map;async function nm(e,t){let n=Zg.get(e);if(n)return n;let s=await Qe("auth.test",()=>cs(e,t)),r={userId:s.userId,teamId:s.teamId};return Zg.set(e,r),r}async function sm(e,t){return(await nm(e,t)).userId}async function pl(e,t){try{return(await nm(e,t)).teamId}catch{return""}}async function hl(e,t,n,s){if(!t.startsWith("#"))return n(e,t,s);let r=await pl(e,s),o=Go("channels",r,t);if(o)return o;let i=await Qe("resolveChannel",()=>n(e,t,s));return Xo("channels",r,t,i),i}async function rm(e,t,n,s){let r=await pl(e,s),o=Go("users",r,t);if(o)return o;let i=await Qe("users.info",()=>n(e,t,s));if(i&&i!==t)Xo("users",r,t,i);return i}async function om(e,t,n,s){let r=await pl(e,s),o=Go("users",r,`tz:${t}`);if(o)return o==="?"?null:o;let i=null;try{let a=await Qe("users.info",()=>n(e,t,s));if(a?.user?.is_bot===!0||t==="USLACKBOT")return Qg(r,t,null);let c=a?.user?.tz;i=typeof c==="string"&&c?c:null}catch{return null}return Qg(r,t,i)}function Qg(e,t,n){return Xo("users",e,`tz:${t}`,n??"?"),n}async function im(e,t,n,s,r,o){let i=r.progress[s],a=await sm(e,o),c=await Qe("reactions.get",()=>of(e,t,n,o)),d=new Set(c.filter((y)=>y.users.includes(a)).map((y)=>y.name)),f=ws.map((y)=>r.progress[y]).filter((y)=>d.has(y));if(f.length===1&&f[0]===i)return{noop:!0,removed:[],leftover:[]};if(!d.has(i))await Qe("reactions.add",()=>Vr(e,t,n,i,o));let p=[],g=[];for(let y of f){if(y===i)continue;try{await Qe("reactions.remove",()=>Zr(e,t,n,y,o)),p.push(y)}catch{g.push(y)}}return{noop:!1,added:s,removed:p,leftover:g}}async function am(e,t,n,s,r,o,i){let a=r.flags[s];if(o)await Qe("reactions.remove",()=>Zr(e,t,n,a,i));else await Qe("reactions.add",()=>Vr(e,t,n,a,i));return a}var gl=1000;async function cm(e,t,n,s={}){let r=s.limit??gl,o=s.cookie,i=await sm(e,o),a=ws.map((g)=>n.progress[g]),c=[],d=0,f,p=!1;while(d<r){let g=Math.min(200,r-d),y=await Qe("conversations.history",()=>Nn(e,t,g,void 0,f,o)),k=y.messages??[];d+=k.length;for(let w of k){let u=String(w.ts??"");if(!u)continue;let l=new Set((w.reactions??[]).filter((m)=>(m.users??[]).map(String).includes(i)).map((m)=>String(m.name??""))),h=a.filter((m)=>l.has(m));if(h.length<2)continue;c.push({ts:u,text:String(w.text??"").split(`
448
+ `)[0]??"",emoji:h,keep:h[0]})}if(f=y.response_metadata?.next_cursor||void 0,!f||k.length===0)break;if(d>=r){p=!0;break}}if(s.fix)for(let g of c)try{try{await Qe("reactions.add",()=>Vr(e,t,g.ts,g.keep,o))}catch(y){if(!(y instanceof Error)||!/already_reacted/.test(y.message))throw y}for(let y of g.emoji){if(y===g.keep)continue;await Qe("reactions.remove",()=>Zr(e,t,g.ts,y,o))}g.fixed=!0}catch(y){g.fixed=!1,g.error=y instanceof Error?y.message:String(y)}return{scanned:d,findings:c,truncated:p}}var ux=!0,dx;function ml(e){if(ux=e,!e)dx=void 0}function Ue(e){return e.replace(new RegExp(`[${"\\\\¥"}](.)`,"gs"),(t,n)=>{switch(n){case"n":return`
449
+ `;case"t":return"\t";case"\\":case"¥":return n==="¥"?"¥":"\\";default:return t}})}function ks(e){return e.replace(new RegExp(`[${"\\\\¥"}]`,"g"),(t)=>`\\${t}`).replace(/\n/g,"\\n").replace(/\t/g,"\\t")}var Ds=(e)=>e&&typeof e==="object"&&!Array.isArray(e)?e:{},Je=(e)=>typeof e==="string"?e:"";function fx(e){return(Array.isArray(e.message_blocks)?e.message_blocks:[]).map((n)=>Je(Ds(Ds(n).message).text)).filter(Boolean).join(`
450
+ `)}function yl(e){return(Array.isArray(e.attachments)?e.attachments:[]).map(Ds).map((n)=>{let s=n.is_share===!0||n.is_msg_unfurl===!0||Array.isArray(n.message_blocks),r=Ds(Ds((Array.isArray(n.message_blocks)?n.message_blocks:[])[0]));return{shared:s,unfurl:!s&&!!Je(n.original_url),author_id:Je(n.author_id)||Je(Ds(r.message).user)||null,author_name:Je(n.author_name)||null,channel_id:Je(n.channel_id)||Je(r.channel)||null,ts:Je(n.ts)||Je(r.ts)||null,title:Je(n.title)||null,text:Je(n.text)||fx(n)||Je(n.pretext)||Je(n.fallback),permalink:Je(n.from_url)||Je(n.title_link)||Je(n.original_url)||null}})}function lm(e,t){return e.filter((n)=>!n.unfurl&&(n.text||n.title)).map((n)=>{let s=n.author_name??n.author_id,r=n.shared?`↪ shared message${s?` from @${s}`:""}${n.channel_id?` in <#${n.channel_id}>`:""}${n.ts?` · ${t(n.ts)}`:""}`:`▸ ${n.title??"attachment"}`,o=n.text?n.text.replace(/\n+$/,"").split(`
451
+ `).map((a)=>`
452
+ │ ${a}`).join(""):"",i=n.permalink?`
451
453
  ${n.permalink}`:"";return`
452
- ${r}${o}${i}`}).join("")}var Lg=new Set(["send","reply","outbox flush","channel invite","channels invite","ch invite","inbox nudge","ask","poll","vote","edit","tick","delete","react","upload","schedule send","schedule rm","pinlog new","pinlog set","pinlog note","pinlog pin","todo set","todo flag","todos add","todos done","todos complete","todos edit","todos rm","todos remove","todos delete","lists create","lists add","lists set","lists share","drafts new","drafts save","drafts edit","drafts update","drafts delete","drafts rm","channel create","channel new","channel rename","channel mv"]),AD={channels:"channel",ch:"channel"};function nl(e){let[t="",n=""]=e.map(String),s=AD[t]??t;return Lg.has(s)||Lg.has(`${s} ${n}`)}function sl(e,t){return String(e[0]??"")==="ask"&&(t.ls===!0||t.pending===!0&&t.push!==!0)}function Ng(e,t,n){let s=n.botTokenSource;if(!s||n.globalPaths.includes(s))return null;if(n.slackTokenSet||n.activeTokenIsBot)return null;if(!nl(e)||sl(e,t)||t["as-bot"]===!0)return null;let r=s==="shell"?"exported in the environment":`set in ${s}`,o="as-bot"in t;return[`Error: refusing to act as YOU — SLACK_BOT_TOKEN is ${r}, but \`${e.slice(0,2).join(" ")}\` would use your user session, not the bot.`,o?" As the app: add --as-bot":" This command has no --as-bot: it can only act as a user."," As yourself: set SLACK_TOKEN, or clear the bot token for this run (SLACK_BOT_TOKEN= slack ...)"].join(`
453
- `)}function Un(e){return e.toLowerCase().replace(/[-_\s]/g,"")}function pn(e){return e&&typeof e==="object"&&!Array.isArray(e)?e:{}}function TD(e,t){let n=Un(t),s=pn(e.profile);for(let o of[e.name,e.real_name,s.display_name,s.real_name])if(typeof o==="string"&&o&&Un(o)===n)return!0;let r=typeof s.email==="string"?s.email.toLowerCase():"";return r!==""&&r===t.toLowerCase()}function FD(e){let t=pn(e.profile),n=new Set;for(let s of[t.display_name,e.real_name,e.name,t.real_name])if(typeof s==="string"&&s){let r=Un(s);if(r.length>=2)n.add(r)}return[...n]}function OD(e,t){let n=Un(e),s,r=!1;for(let o of t){let i=typeof o.id==="string"?o.id:"";if(!i)continue;for(let l of FD(o)){let u=-1;if(n===l)u=e.length;else for(let f of Bg)if(e.length>f.length&&e.endsWith(f)&&Un(e.slice(0,e.length-f.length))===l){u=e.length-f.length;break}if(u<0)continue;if(!s||l.length>s.formLen)s={userId:i,matchLen:u,formLen:l.length,display:il(o)},r=!1;else if(l.length===s.formLen&&s.userId!==i)r=!0}}if(!s)return;return r?"ambiguous":{userId:s.userId,matchLen:s.matchLen,display:s.display}}async function hn(e,t,n,s){let r=`[${jg}ー]+`,o=`${r}(?:[._-]+${r})*`,i=new RegExp(`(?<![A-Za-z0-9._@<-])@(${o})`,"gu"),l=new Set;for(let w of t.matchAll(i))l.add(w[1]);if(l.size===0)return{text:t,resolved:[],unresolved:[]};let u=new Map;for(let w of l)u.set(w,{status:"pending"});let f=(w)=>{for(let k of l){if(u.get(k).status!=="pending")continue;if(ol(k)){let _=OD(k,w);if(_==="ambiguous")u.set(k,{status:"ambiguous"});else if(_)u.set(k,{status:"resolved",userId:_.userId,matchLen:_.matchLen,display:_.display})}else{let _=w.filter((E)=>TD(E,k)),D=new Set(_.map((E)=>typeof E.id==="string"?E.id:"").filter(Boolean));if(D.size===1){let E=_.find((S)=>typeof S.id==="string");u.set(k,{status:"resolved",userId:E.id,matchLen:k.length,display:il(E)})}else if(D.size>1)u.set(k,{status:"ambiguous"})}}},a=!1;try{let w=await Hr(e,s);f((w.members??[]).map(pn)),a=!0}catch{a=!1}let c=[...l].some((w)=>u.get(w).status==="pending"),d=!1,p=!0;if(c&&n){d=!0;try{let w=await ua(e,n,s),k=[];for(let _ of w){let D=pn(await da(e,_,s)),E=pn(D.user);if(typeof E.id!=="string")E.id=_;k.push(E)}f(k)}catch{p=!1}}let h=a&&(n?d&&p:!0),g=[],y=[];for(let w of l){let k=u.get(w);if(k.status==="resolved")g.push({surface:`@${w.slice(0,k.matchLen)}`,display:k.display,userId:k.userId});else if(k.status==="ambiguous")y.push({surface:`@${w}`,reason:"ambiguous"});else y.push({surface:`@${w}`,reason:h?"no-match":"unavailable"})}return{text:t.replace(i,(w,k)=>{let _=u.get(k);if(_&&_.status==="resolved")return`<@${_.userId}>${k.slice(_.matchLen)}`;return w}),resolved:g,unresolved:y}}function jo(e){let t=[],n=!1;for(let s of e)if(s.reason==="ambiguous")t.push(`${s.surface} matches multiple people — not tagged, sent as plain text (use <@USERID> to tag)`);else if(s.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(`${s.surface} matched no one — not tagged, sent as plain text`);return t}async function Mg(e,t,n,s={}){let r=s.warn??((i)=>process.stderr.write(`${i}
454
- `)),o=await hn(e,t,n,s.cookie);for(let i of jo(o.unresolved))r(`warn: ${i}`);return o.text}var Bg=["さん","さま","様","君","くん","ちゃん","氏","先生","先輩","殿","老师","老師","兄","姐","哥","姐妹"],jg="\\p{Script=Han}\\p{Script=Hiragana}\\p{Script=Katakana}A-Za-z0-9";function ol(e){return/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]/u.test(e)}function RD(e){let t=[],n=new RegExp(`([${jg}]{1,12})(${Bg.join("|")})`,"gu");for(let s of e.matchAll(n))t.push({ref:s[1],honorific:s[2]});for(let s of e.matchAll(/\b(?:dear|hi|hello|hey)\b[ \t]+([A-Z][A-Za-z'’-]{1,20})/gi))t.push({ref:s[1],honorific:""});for(let s of e.matchAll(/(?:^|\n)[ \t]*([A-Z][A-Za-z'’-]{1,20}),/g))t.push({ref:s[1],honorific:""});return t}function ID(e){let t=pn(e.profile),n=new Set;for(let s of[e.name,e.real_name,t.display_name,t.real_name]){if(typeof s!=="string"||!s)continue;for(let r of[s,...s.split(/\s+/)]){let o=Un(r);if(o.length>=2)n.add(o)}}return[...n]}function vD(e,t){let n=Un(e);if(n.length<2)return;for(let s of t)if(n===s)return s;if(ol(e)){for(let s of t)if(n.includes(s)||s.includes(n))return s}return}function il(e){return[pn(e.profile).display_name,e.real_name,e.name].filter((s)=>typeof s==="string"&&s!=="")[0]??String(e.id??"?")}async function Wg(e,t,n){let s=RD(t);if(s.length===0)return[];let r=new Set;for(let f of t.matchAll(/<@([A-Z0-9]+)(?:\|[^>]*)?>/g))r.add(f[1]);let i=((await Hr(e,n)).members??[]).map(pn).filter((f)=>f.deleted!==!0&&f.is_bot!==!0&&f.id!=="USLACKBOT").map((f)=>({id:typeof f.id==="string"?f.id:"",forms:ID(f),display:il(f)})).filter((f)=>f.id!==""),l=[],u=new Set;for(let{ref:f,honorific:a}of s)for(let c of i){let d=vD(f,c.forms);if(!d)continue;if(r.has(c.id)||u.has(c.id))break;u.add(c.id),l.push({surface:ol(f)?`${d}${a}`:f,display:c.display,userId:c.id});break}return l}async function Jn(e,t,n,s){let r=t,o=[],i=r,l=0;while(!0){let u=i.indexOf("<@U",l);if(u===-1)break;let f=i.slice(u+2),a=f.search(/[>|]/),c=a===-1?f:f.slice(0,a);if(c.length>=9)o.push(c);l=u+1}for(let u of o){if(!n.has(u))n.set(u,await ss(e,u,s));let f=n.get(u)??u;r=r.replaceAll(`<@${u}>`,`@${f}`),r=r.replace(new RegExp(`<@${u}\\|[^>]*>`,"g"),`@${f}`)}return r}function ms(e){return e.replace(/<!date\^(\d+)\^[^|>]*(?:\|([^>]*))?>/g,(t,n,s)=>{let r=Number(n);if(!Number.isFinite(r))return s??"date";let o=new Date(r*1000);if(Number.isNaN(o.getTime()))return s??"date";let i=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],l=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],u=i[o.getUTCDay()]??"",f=l[o.getUTCMonth()]??"";return`${u}, ${f} ${String(o.getUTCDate()).padStart(2,"0")}, ${o.getUTCFullYear()}`})}function Ug(e,t=new Date){let n=new Date(e*1000),s=rl(t),r=rl(new Date(t.getTime()-86400000)),o=rl(n);if(o===s)return"Today";if(o===r)return"Yesterday";let i=n.toLocaleDateString("en-US",{weekday:"long"}),l=n.toLocaleDateString("en-US",{month:"short"});return`${i}, ${l} ${String(n.getDate()).padStart(2,"0")}`}function rl(e){return`${e.getFullYear()}-${e.getMonth()}-${e.getDate()}`}function Kn(e){let t=new Date(e*1000),n=t.getFullYear(),s=String(t.getMonth()+1).padStart(2,"0"),r=String(t.getDate()).padStart(2,"0"),o=String(t.getHours()).padStart(2,"0"),i=String(t.getMinutes()).padStart(2,"0");return`${n}-${s}-${r} ${o}:${i}`}var PD=/[A-Za-z0-9_-]{32,}/g;function ys(e){return e.replace(PD,(t)=>`${t.slice(0,4)}…(${t.length-4} masked)`)}function al(e=new Date,t){let n=process.env.SLACK_QUIET_TZ??"Asia/Tokyo",s=!!t&&LD(t),r=s?t:n,o=Number(process.env.SLACK_QUIET_START??23),i=Number(process.env.SLACK_QUIET_END??8),l,u;try{let p=new Intl.DateTimeFormat("en-GB",{timeZone:r,hour12:!1,weekday:"short",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"});u=p.format(e),l=Number(p.formatToParts(e).find((h)=>h.type==="hour")?.value??"12")}catch{return null}let f=o>i?l>=o||l<i:l>=o&&l<i,a=s?`${r}, recipient`:`${r}, sender — recipient's timezone unknown`,c=`\uD83D\uDD50 ${u} (${a})`;if(!f)return c;return`${c}
455
- ⚠ QUIET HOURS (${o}:00-${i}:00) — this will buzz a phone.${s?"":" Their local time may differ."} Send only for a production incident; otherwise hold it until morning.`}function LD(e){try{return new Intl.DateTimeFormat("en-GB",{timeZone:e}),!0}catch{return!1}}import{writeSync as Jg}from"node:fs";import{isatty as Kg}from"node:tty";import{format as qg}from"node:util";var ND=new Int32Array(new SharedArrayBuffer(4)),MD=141;function Hg(e,t){let n=Buffer.from(t,"utf8"),s=0;while(s<n.length)try{s+=Jg(e,n,s,n.length-s)}catch(r){let o=r.code;if(o==="EAGAIN"||o==="EWOULDBLOCK"){Atomics.wait(ND,0,0,2);continue}if(o==="EPIPE")process.exit(MD);if(e!==2)try{Jg(2,`slack: cannot write output (${o??String(r)}); output is incomplete
456
- `)}catch{}process.exit(1)}}function zg(){if(!Kg(1))console.log=(...e)=>Hg(1,qg(...e)+`
457
- `),console.info=console.log;if(!Kg(2))console.error=(...e)=>Hg(2,qg(...e)+`
458
- `),console.warn=console.error}import{closeSync as Yg,mkdirSync as BD,openSync as Gg,readFileSync as bs,statSync as Xg,unlinkSync as Wo,writeFileSync as Vg}from"node:fs";import{homedir as jD}from"node:os";import{join as Zg}from"node:path";var ur="Pinlog · 最終更新";function cl(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=(r)=>t.find((o)=>o.type===r)?.value??"??",s=n("hour")==="24"?"00":n("hour");return`${n("year")}-${n("month")}-${n("day")} ${s}:${n("minute")} JST`}function WD(e){return`_${ur} ${cl(e)} · 更新はスレッドに_`}var ll=new RegExp(`(^|\\n+)_?${ur} \\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2} JST · 更新はスレッドに_?[ \\t]*\\n*$`);function ws(e){return ll.test(e)}function dr(e){return e.replace(ll,"")}function ul(e,t){return`${dr(e).trimEnd()}
454
+ ${r}${o}${i}`}).join("")}var um=new Set(["send","reply","outbox flush","channel invite","channels invite","ch invite","inbox nudge","ask","poll","vote","edit","tick","delete","react","upload","schedule send","schedule rm","pinlog new","pinlog set","pinlog note","pinlog pin","todo set","todo flag","todos add","todos done","todos complete","todos edit","todos rm","todos remove","todos delete","lists create","lists add","lists set","lists share","drafts new","drafts save","drafts edit","drafts update","drafts delete","drafts rm","channel create","channel new","channel rename","channel mv"]),px={channels:"channel",ch:"channel"};function bl(e){let[t="",n=""]=e.map(String),s=px[t]??t;return um.has(s)||um.has(`${s} ${n}`)}function wl(e,t){return String(e[0]??"")==="ask"&&(t.ls===!0||t.pending===!0&&t.push!==!0)}function dm(e,t,n){let s=n.botTokenSource;if(!s||n.globalPaths.includes(s))return null;if(n.slackTokenSet||n.activeTokenIsBot)return null;if(!bl(e)||wl(e,t)||t["as-bot"]===!0)return null;let r=s==="shell"?"exported in the environment":`set in ${s}`,o="as-bot"in t;return[`Error: refusing to act as YOU — SLACK_BOT_TOKEN is ${r}, but \`${e.slice(0,2).join(" ")}\` would use your user session, not the bot.`,o?" As the app: add --as-bot":" This command has no --as-bot: it can only act as a user."," As yourself: set SLACK_TOKEN, or clear the bot token for this run (SLACK_BOT_TOKEN= slack ...)"].join(`
455
+ `)}function zn(e){return e.toLowerCase().replace(/[-_\s]/g,"")}function gn(e){return e&&typeof e==="object"&&!Array.isArray(e)?e:{}}function hx(e,t){let n=zn(t),s=gn(e.profile);for(let o of[e.name,e.real_name,s.display_name,s.real_name])if(typeof o==="string"&&o&&zn(o)===n)return!0;let r=typeof s.email==="string"?s.email.toLowerCase():"";return r!==""&&r===t.toLowerCase()}function gx(e){let t=gn(e.profile),n=new Set;for(let s of[t.display_name,e.real_name,e.name,t.real_name])if(typeof s==="string"&&s){let r=zn(s);if(r.length>=2)n.add(r)}return[...n]}function mx(e,t){let n=zn(e),s,r=!1;for(let o of t){let i=typeof o.id==="string"?o.id:"";if(!i)continue;for(let a of gx(o)){let c=-1;if(n===a)c=e.length;else for(let d of pm)if(e.length>d.length&&e.endsWith(d)&&zn(e.slice(0,e.length-d.length))===a){c=e.length-d.length;break}if(c<0)continue;if(!s||a.length>s.formLen)s={userId:i,matchLen:c,formLen:a.length,display:xl(o)},r=!1;else if(a.length===s.formLen&&s.userId!==i)r=!0}}if(!s)return;return r?"ambiguous":{userId:s.userId,matchLen:s.matchLen,display:s.display}}async function mn(e,t,n,s){let r=`[${hm}ー]+`,o=`${r}(?:[._-]+${r})*`,i=new RegExp(`(?<![A-Za-z0-9._@<-])@(${o})`,"gu"),a=new Set;for(let h of t.matchAll(i))a.add(h[1]);if(a.size===0)return{text:t,resolved:[],unresolved:[]};let c=new Map;for(let h of a)c.set(h,{status:"pending"});let d=(h)=>{for(let m of a){if(c.get(m).status!=="pending")continue;if(Dl(m)){let b=mx(m,h);if(b==="ambiguous")c.set(m,{status:"ambiguous"});else if(b)c.set(m,{status:"resolved",userId:b.userId,matchLen:b.matchLen,display:b.display})}else{let b=h.filter((x)=>hx(x,m)),_=new Set(b.map((x)=>typeof x.id==="string"?x.id:"").filter(Boolean));if(_.size===1){let x=b.find((S)=>typeof S.id==="string");c.set(m,{status:"resolved",userId:x.id,matchLen:m.length,display:xl(x)})}else if(_.size>1)c.set(m,{status:"ambiguous"})}}},f=!1;try{let h=await to(e,s);d((h.members??[]).map(gn)),f=!0}catch{f=!1}let p=[...a].some((h)=>c.get(h).status==="pending"),g=!1,y=!0;if(p&&n){g=!0;try{let h=await Da(e,n,s),m=[];for(let b of h){let _=gn(await xa(e,b,s)),x=gn(_.user);if(typeof x.id!=="string")x.id=b;m.push(x)}d(m)}catch{y=!1}}let k=f&&(n?g&&y:!0),w=[],u=[];for(let h of a){let m=c.get(h);if(m.status==="resolved")w.push({surface:`@${h.slice(0,m.matchLen)}`,display:m.display,userId:m.userId});else if(m.status==="ambiguous")u.push({surface:`@${h}`,reason:"ambiguous"});else u.push({surface:`@${h}`,reason:k?"no-match":"unavailable"})}return{text:t.replace(i,(h,m)=>{let b=c.get(m);if(b&&b.status==="resolved")return`<@${b.userId}>${m.slice(b.matchLen)}`;return h}),resolved:w,unresolved:u}}function Zo(e){let t=[],n=!1;for(let s of e)if(s.reason==="ambiguous")t.push(`${s.surface} matches multiple people — not tagged, sent as plain text (use <@USERID> to tag)`);else if(s.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(`${s.surface} matched no one — not tagged, sent as plain text`);return t}async function fm(e,t,n,s={}){let r=s.warn??((i)=>process.stderr.write(`${i}
456
+ `)),o=await mn(e,t,n,s.cookie);for(let i of Zo(o.unresolved))r(`warn: ${i}`);return o.text}var pm=["さん","さま","様","君","くん","ちゃん","氏","先生","先輩","殿","老师","老師","兄","姐","哥","姐妹"],hm="\\p{Script=Han}\\p{Script=Hiragana}\\p{Script=Katakana}A-Za-z0-9";function Dl(e){return/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]/u.test(e)}function yx(e){let t=[],n=new RegExp(`([${hm}]{1,12})(${pm.join("|")})`,"gu");for(let s of e.matchAll(n))t.push({ref:s[1],honorific:s[2]});for(let s of e.matchAll(/\b(?:dear|hi|hello|hey)\b[ \t]+([A-Z][A-Za-z'’-]{1,20})/gi))t.push({ref:s[1],honorific:""});for(let s of e.matchAll(/(?:^|\n)[ \t]*([A-Z][A-Za-z'’-]{1,20}),/g))t.push({ref:s[1],honorific:""});return t}function bx(e){let t=gn(e.profile),n=new Set;for(let s of[e.name,e.real_name,t.display_name,t.real_name]){if(typeof s!=="string"||!s)continue;for(let r of[s,...s.split(/\s+/)]){let o=zn(r);if(o.length>=2)n.add(o)}}return[...n]}function wx(e,t){let n=zn(e);if(n.length<2)return;for(let s of t)if(n===s)return s;if(Dl(e)){for(let s of t)if(n.includes(s)||s.includes(n))return s}return}function xl(e){return[gn(e.profile).display_name,e.real_name,e.name].filter((s)=>typeof s==="string"&&s!=="")[0]??String(e.id??"?")}async function gm(e,t,n){let s=yx(t);if(s.length===0)return[];let r=new Set;for(let d of t.matchAll(/<@([A-Z0-9]+)(?:\|[^>]*)?>/g))r.add(d[1]);let i=((await to(e,n)).members??[]).map(gn).filter((d)=>d.deleted!==!0&&d.is_bot!==!0&&d.id!=="USLACKBOT").map((d)=>({id:typeof d.id==="string"?d.id:"",forms:bx(d),display:xl(d)})).filter((d)=>d.id!==""),a=[],c=new Set;for(let{ref:d,honorific:f}of s)for(let p of i){let g=wx(d,p.forms);if(!g)continue;if(r.has(p.id)||c.has(p.id))break;c.add(p.id),a.push({surface:Dl(d)?`${g}${f}`:d,display:p.display,userId:p.id});break}return a}async function Yn(e,t,n,s){let r=t,o=[],i=r,a=0;while(!0){let c=i.indexOf("<@U",a);if(c===-1)break;let d=i.slice(c+2),f=d.search(/[>|]/),p=f===-1?d:d.slice(0,f);if(p.length>=9)o.push(p);a=c+1}for(let c of o){if(!n.has(c))n.set(c,await ls(e,c,s));let d=n.get(c)??c;r=r.replaceAll(`<@${c}>`,`@${d}`),r=r.replace(new RegExp(`<@${c}\\|[^>]*>`,"g"),`@${d}`)}return r}function xs(e){return e.replace(/<!date\^(\d+)\^[^|>]*(?:\|([^>]*))?>/g,(t,n,s)=>{let r=Number(n);if(!Number.isFinite(r))return s??"date";let o=new Date(r*1000);if(Number.isNaN(o.getTime()))return s??"date";let i=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],a=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],c=i[o.getUTCDay()]??"",d=a[o.getUTCMonth()]??"";return`${c}, ${d} ${String(o.getUTCDate()).padStart(2,"0")}, ${o.getUTCFullYear()}`})}function mm(e,t=new Date){let n=new Date(e*1000),s=kl(t),r=kl(new Date(t.getTime()-86400000)),o=kl(n);if(o===s)return"Today";if(o===r)return"Yesterday";let i=n.toLocaleDateString("en-US",{weekday:"long"}),a=n.toLocaleDateString("en-US",{month:"short"});return`${i}, ${a} ${String(n.getDate()).padStart(2,"0")}`}function kl(e){return`${e.getFullYear()}-${e.getMonth()}-${e.getDate()}`}function Gn(e){let t=new Date(e*1000),n=t.getFullYear(),s=String(t.getMonth()+1).padStart(2,"0"),r=String(t.getDate()).padStart(2,"0"),o=String(t.getHours()).padStart(2,"0"),i=String(t.getMinutes()).padStart(2,"0");return`${n}-${s}-${r} ${o}:${i}`}var kx=/[A-Za-z0-9_-]{32,}/g;function Ss(e){return e.replace(kx,(t)=>`${t.slice(0,4)}…(${t.length-4} masked)`)}function Sl(e=new Date,t){let n=process.env.SLACK_QUIET_TZ??"Asia/Tokyo",s=!!t&&Dx(t),r=s?t:n,o=Number(process.env.SLACK_QUIET_START??23),i=Number(process.env.SLACK_QUIET_END??8),a,c;try{let y=new Intl.DateTimeFormat("en-GB",{timeZone:r,hour12:!1,weekday:"short",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"});c=y.format(e),a=Number(y.formatToParts(e).find((k)=>k.type==="hour")?.value??"12")}catch{return null}let d=o>i?a>=o||a<i:a>=o&&a<i,f=s?`${r}, recipient`:`${r}, sender — recipient's timezone unknown`,p=`\uD83D\uDD50 ${c} (${f})`;if(!d)return p;return`${p}
457
+ ⚠ QUIET HOURS (${o}:00-${i}:00) — this will buzz a phone.${s?"":" Their local time may differ."} Send only for a production incident; otherwise hold it until morning.`}function Dx(e){try{return new Intl.DateTimeFormat("en-GB",{timeZone:e}),!0}catch{return!1}}import{writeSync as ym}from"node:fs";import{isatty as bm}from"node:tty";import{format as wm}from"node:util";var xx=new Int32Array(new SharedArrayBuffer(4)),Sx=141;function km(e,t){let n=Buffer.from(t,"utf8"),s=0;while(s<n.length)try{s+=ym(e,n,s,n.length-s)}catch(r){let o=r.code;if(o==="EAGAIN"||o==="EWOULDBLOCK"){Atomics.wait(xx,0,0,2);continue}if(o==="EPIPE")process.exit(Sx);if(e!==2)try{ym(2,`slack: cannot write output (${o??String(r)}); output is incomplete
458
+ `)}catch{}process.exit(1)}}function Dm(){if(!bm(1))console.log=(...e)=>km(1,wm(...e)+`
459
+ `),console.info=console.log;if(!bm(2))console.error=(...e)=>km(2,wm(...e)+`
460
+ `),console.warn=console.error}import{closeSync as xm,mkdirSync as _x,openSync as Sm,readFileSync as _s,statSync as _m,unlinkSync as Qo,writeFileSync as Em}from"node:fs";import{homedir as Ex}from"node:os";import{join as $m}from"node:path";var mr="Pinlog · 最終更新";function _l(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=(r)=>t.find((o)=>o.type===r)?.value??"??",s=n("hour")==="24"?"00":n("hour");return`${n("year")}-${n("month")}-${n("day")} ${s}:${n("minute")} JST`}function $x(e){return`_${mr} ${_l(e)} · 更新はスレッドに_`}var El=new RegExp(`(^|\\n+)_?${mr} \\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2} JST · 更新はスレッドに_?[ \\t]*\\n*$`);function Es(e){return El.test(e)}function yr(e){return e.replace(El,"")}function $l(e,t){return`${yr(e).trimEnd()}
459
461
 
460
- ${WD(t)}`}function dl(e){let n=e.match(ll)?.[0]?.match(/(\d{4}-\d{2}-\d{2} \d{2}:\d{2} JST)/);return n?n[1]:null}class lr extends Error{holder;constructor(e){super(`locked by ${e}`);this.holder=e;this.name="LockBusyError"}}function UD(){return Zg(process.env.HOME||jD(),".config","slack-cli","locks")}function Qg(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 JD(e,t){let n=`${e}.break`,s=`pid=${process.pid} nonce=${Math.random().toString(36).slice(2)}${Date.now()}
461
- `,r;try{r=Gg(n,"wx"),Vg(r,s)}catch(o){if(o.code!=="EEXIST")throw o;try{let i=bs(n,"utf8");if((/^pid=\d+/.test(i)?!Qg(i):Date.now()-Xg(n).mtimeMs>1e4)&&bs(n,"utf8")===i)Wo(n)}catch{}return}try{if(bs(e,"utf8")===t)Wo(e)}catch{}finally{Yg(r);try{if(bs(n,"utf8")===s)Wo(n)}catch{}}}function em(e,t={}){let n=t.dir??UD(),s=t.staleMs??120000;BD(n,{recursive:!0});let r=Zg(n,`${e.replace(/[^A-Za-z0-9._-]/g,"_")}.lock`),o=`pid=${process.pid} since=${new Date().toISOString()} nonce=${Math.random().toString(36).slice(2)}${Date.now()}
462
- `;for(let i=0;i<3;i++)try{let l=Gg(r,"wx");Vg(l,o),Yg(l);let u=!0,f=()=>{if(!u)return;u=!1;try{if(bs(r,"utf8")===o)Wo(r)}catch{}};return process.once("exit",f),f}catch(l){if(l.code!=="EEXIST")throw l;let u,f;try{u=bs(r,"utf8"),f=Date.now()-Xg(r).mtimeMs}catch{continue}if(/^pid=\d+/.test(u)?!Qg(u):f>s){JD(r,u);continue}throw new lr(u.trim().replace(/ nonce=\S+/,"")||"another process")}throw new lr("another process")}function ht(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}var Dm=new Map,gl=new Map,kl=[mt(zo(),".slack-cli",".env.local"),mt(zo(),".config/slack-cli",".env")];function Jo(e){if(!wm(e))return;let t=wl(e,"utf8");for(let n of t.split(`
463
- `)){let s=n.trim();if(!s||s.startsWith("#"))continue;let r=s.indexOf("=");if(r===-1)continue;let o=s.slice(0,r).trim(),i=s.slice(r+1).trim();if(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))i=i.slice(1,-1);if(kl.includes(e))gl.set(o,[...gl.get(o)??[],{path:e,val:i}]);if(!(o in process.env))process.env[o]=i,Dm.set(o,e)}}function GD(e){KD(e,{recursive:!0});let t=mt(e,".gitignore");if(!wm(t))km(t,`*
464
- `)}function XD(){for(let e of kl)Jo(e);Jo(mt(process.cwd(),".slack-cli",".env.local")),Jo(mt(process.cwd(),".env.local")),Jo(mt(process.cwd(),".env"))}function VD(e){return bm("sha256").update(e).digest("hex")}function O(e){return e&&typeof e==="object"&&!Array.isArray(e)?e:{}}function G(e){return Array.isArray(e)?e:[]}function Yo(e){return Number(e.ts??0)}async function xm(e,t,n){let s=t.user;if(typeof s==="string"){if(!n.has(s))n.set(s,await Re(e,s));return n.get(s)??s}return typeof t.username==="string"?t.username:"bot"}function ml(e){let t=new Date(e*1000),n=t.getUTCFullYear(),s=String(t.getUTCMonth()+1).padStart(2,"0"),r=String(t.getUTCDate()).padStart(2,"0"),o=String(t.getUTCHours()).padStart(2,"0"),i=String(t.getUTCMinutes()).padStart(2,"0"),l=String(t.getUTCSeconds()).padStart(2,"0");return`${n}-${s}-${r} ${o}:${i}:${l}`}function Go(e){let[t,n="000000"]=e.split("."),s=Number(t),r=new Date(s*1000),o=r.getUTCFullYear(),i=String(r.getUTCMonth()+1).padStart(2,"0"),l=String(r.getUTCDate()).padStart(2,"0"),u=String(r.getUTCHours()).padStart(2,"0"),f=String(r.getUTCMinutes()).padStart(2,"0"),a=String(r.getUTCSeconds()).padStart(2,"0"),c=n.padEnd(6,"0").slice(0,6);return`${o}-${i}-${l}T${u}:${f}:${a}.${c}`}function Dl(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 fl(e){return/^\d{4}-\d{2}-\d{2}T/.test(e)?Dl(e):e}async function ti(e,t,n,s,r){let o=typeof t.ts==="string"?t.ts:`${Yo(t)}.000000`,i=Go(o),l="?";if(typeof t.user==="string"){let k=t.user,_="@"+k;if(!n.has(_)){let D=await Fg(e,k,async(E,S,x)=>(await rr(E,S,x))[1],r);n.set(_,D)}l=n.get(_)??k}else if(typeof t.username==="string")l=t.username;let u=typeof t.text==="string"?t.text:"",a=ms(await Jn(e,u,n,r)).split(`
465
- `),c=a[0]+(a.length>1?`
466
- `+a.slice(1).map((k)=>` ${k}`).join(`
467
- `):""),d=s?`${s} @${l}`:`@${l}`,p=G(t.reactions).map(O).map((k)=>{let _=typeof k.name==="string"?k.name:"",D=Number(k.count??G(k.users).length??0);return _?`:${_}:\xD7${D}`:""}).filter(Boolean).join(" "),h=G(t.files).map(O).map((k)=>{let _=typeof k.name==="string"?k.name:typeof k.title==="string"?k.title:"(file)",D=typeof k.size==="number"?` (${ni(k.size)})`:"",E=typeof k.id==="string"?` [${k.id}]`:"";return`
468
- \uD83D\uDCCE ${_}${D}${E}`}).join(""),g=Number(t.reply_count??0),y=g>0?` [+${g} ${g===1?"reply":"replies"}]`:"",m=await Promise.all(tl(t).map(async(k)=>({...k,text:k.text?ms(await Jn(e,k.text,n,r)):""}))),w=(p?`
469
- ${p}`:"")+h+Pg(m,Go);return`${i} ${d}: ${c}${y}${w}`}function ni(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function ZD(e){return G(e.files).map(O).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 Sm(e){let t=ZD(e),n=tl(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:G(e.reactions).map(O).map((s)=>({name:s.name??null,count:s.count??null,users:Array.isArray(s.users)?s.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 QD(e,t,n,s,r){let o=[];for(let i of n){let l=i;if(Number(i.reply_count??0)>0&&typeof i.ts==="string"){let u=await Le(e,t,i.ts,200,r),f=G(u.messages).map(O);l=f[f.length-1]??i}if(l.user!==s)o.push(i)}return o}async function tm(e,t,n,s="text",r=!1,o){let i=pt(t),l=await we(e,t,o),u=new Map,a=await(async()=>{if(i?.threadTs){let d=await Le(e,l,i.threadTs,n,o);return G(d.messages).map(O)}let c=await it(e,l,n,void 0,void 0,o);return G(c.messages).map(O).reverse()})();if(r){let{userId:c}=await Lc(e,o);a=await QD(e,l,a,c,o)}if(s==="jsonl"){for(let c of a)console.log(JSON.stringify(Sm(c)));return}for(let c of a)console.log(await ti(e,c,u,void 0,o))}function ex(e){let t=(r)=>r.replace(/\\/g,"\\\\").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t"),n=typeof e.user==="string"?e.user:typeof e.bot_id==="string"?e.bot_id:"",s=Array.isArray(e.files)&&e.files.length?` [files: ${e.files.length}]`:"";return`${String(e.ts)} ${n} ${t(typeof e.text==="string"?e.text:"")}${s}`}async function tx(e,t,n,s){let r=[],o;for(let i=0;i<200;i++){let l=O(await Nc(e,t,n,o?{cursor:o}:{},s));for(let u of G(l.messages).map(O))if(!r.some((f)=>f.ts===u.ts))r.push(u);if(o=String(O(l.response_metadata).next_cursor??"")||void 0,!o)return r}throw Error("thread has more than 200 pages: refusing to return it partially")}async function nm(e,t,n,s,r="text",o,i){let l=await we(e,t,o),f=i!==void 0||r==="tsv"?await tx(e,l,fl(n),o):G((await Le(e,l,fl(n),s,o)).messages).map(O);if(i!==void 0){let c=Number(fl(i));if(!Number.isFinite(c))throw Error(`--since needs a message ts (1700000000.000100) or ISO stamp (got ${M(i)})`);f=f.filter((d)=>Number(d.ts)>c)}if(r==="tsv"){for(let c of f)console.log(ex(c));return}if(r==="jsonl"){for(let c of f)console.log(JSON.stringify(Sm(c)));return}let a=new Map;for(let c of f)console.log(await ti(e,c,a,void 0,o))}async function nx(e){let t=await sr(e),n=G(t.channels).map(O).filter((r)=>r.is_member===!0).sort((r,o)=>Number(o.updated??0)-Number(r.updated??0)).slice(0,10),s=new Map;for(let r of n){let o=String(r.id??""),i=typeof r.name==="string"?r.name:typeof r.user==="string"?r.user:o,l=await it(e,o,5),u=G(l.messages).map(O).filter((f)=>f.subtype===void 0||f.subtype===null).filter((f)=>{let a=typeof f.text==="string"?f.text:"";return a.length>0&&!a.startsWith("<@")}).slice(0,3).reverse();if(u.length===0)continue;console.log(`-- #${i} --------------------------------`);for(let f of u){let a=await xm(e,f,s),c=(typeof f.text==="string"?f.text:"").split(`
470
- `)[0]??"",d=await Jn(e,c,s);console.log(` ${a}: ${d}`)}}}async function sx(e,t){let n=await Yh(e,"to:me"),s=G(nr(n,["messages","matches"])).map(O).slice(0,t),r=new Map,o=[];for(let i of s){let l=Ug(Yo(i)),u=o[o.length-1];if(u?.label===l)u.msgs.push(i);else o.push({label:l,msgs:[i]})}for(let i=0;i<o.length;i++){let{label:l,msgs:u}=o[i];if(i>0)console.log("");console.log(` ${l}`),console.log(" ----------------------------");for(let f of[...u].reverse()){let a=O(f.channel),c=a.is_im===!0,d=typeof a.name==="string"?a.name:"dm",p;if(c&&d.startsWith("U")){let h="@"+d;if(!r.has(h)){let[,g]=await rr(e,d);r.set(h,g)}p=`@${r.get(h)??d}`}else if(c)p=`@${d}`;else p=`#${d}`;console.log(await ti(e,f,r,p))}}}async function rx(e,t,n,s,r="text",o){let i=await sr(e,o),l=G(i.channels).map(O).filter((u)=>s||u.is_member===!0).filter((u)=>{if(!n)return!0;return(typeof u.name==="string"?u.name:"").toLowerCase().includes(n.toLowerCase())}).sort((u,f)=>Number(f.updated??0)-Number(u.updated??0)).slice(0,t);if(r==="jsonl"){for(let u of l)console.log(JSON.stringify(u));return}for(let u of l){let f=String(u.id??""),a=typeof u.name==="string"?u.name:typeof u.user==="string"?u.user:f,c=u.is_im===!0,d=u.is_mpim===!0,p=c||d?"@":"#",h=u.is_member===!0?"":" (not joined)",g=typeof O(u.purpose).value==="string"?String(O(u.purpose).value):"",y=g?` ${g.split(`
471
- `)[0]?.slice(0,60)}`:"";console.log(`${p}${a} ${f}${h}${y}`)}}function ox(e){let t=(r)=>r.startsWith("xoxp-")||r.startsWith("xoxc-"),n=Hi(),s=n.find((r)=>r.profile.token===e);if(!s)return;return n.find((r)=>t(r.profile.token)&&r.profile.teamId===s.profile.teamId)}async function _m(e,t,n,s,r){let o=e,i=r,l;try{l=await Bc(o,t,n,i)}catch(a){let c=a instanceof Error?a.message:String(a);if(e.startsWith("xoxb-")&&c.includes("not_allowed_token_type")){let d=ox(e);if(d)console.error(`Note: search.messages needs a user token \u2014 the active profile is a bot token (xoxb-); falling back to profile "${d.name}".`),o=d.profile.token,i=d.profile.cookie,l=await Bc(o,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.
462
+ ${$x(t)}`}function Cl(e){let n=e.match(El)?.[0]?.match(/(\d{4}-\d{2}-\d{2} \d{2}:\d{2} JST)/);return n?n[1]:null}class gr extends Error{holder;constructor(e){super(`locked by ${e}`);this.holder=e;this.name="LockBusyError"}}function Cx(){return $m(process.env.HOME||Ex(),".config","slack-cli","locks")}function Cm(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 Ax(e,t){let n=`${e}.break`,s=`pid=${process.pid} nonce=${Math.random().toString(36).slice(2)}${Date.now()}
463
+ `,r;try{r=Sm(n,"wx"),Em(r,s)}catch(o){if(o.code!=="EEXIST")throw o;try{let i=_s(n,"utf8");if((/^pid=\d+/.test(i)?!Cm(i):Date.now()-_m(n).mtimeMs>1e4)&&_s(n,"utf8")===i)Qo(n)}catch{}return}try{if(_s(e,"utf8")===t)Qo(e)}catch{}finally{xm(r);try{if(_s(n,"utf8")===s)Qo(n)}catch{}}}function Am(e,t={}){let n=t.dir??Cx(),s=t.staleMs??120000;_x(n,{recursive:!0});let r=$m(n,`${e.replace(/[^A-Za-z0-9._-]/g,"_")}.lock`),o=`pid=${process.pid} since=${new Date().toISOString()} nonce=${Math.random().toString(36).slice(2)}${Date.now()}
464
+ `;for(let i=0;i<3;i++)try{let a=Sm(r,"wx");Em(a,o),xm(a);let c=!0,d=()=>{if(!c)return;c=!1;try{if(_s(r,"utf8")===o)Qo(r)}catch{}};return process.once("exit",d),d}catch(a){if(a.code!=="EEXIST")throw a;let c,d;try{c=_s(r,"utf8"),d=Date.now()-_m(r).mtimeMs}catch{continue}if(/^pid=\d+/.test(c)?!Cm(c):d>s){Ax(r,c);continue}throw new gr(c.trim().replace(/ nonce=\S+/,"")||"another process")}throw new gr("another process")}function gt(e,t){return`${e}:${t}`}function ei(e){let t=e.match(/^([CDG][A-Z0-9]{8,}):(\d{10}\.\d{6})$/);return t?{channel:t[1],ts:t[2]}:null}var Ol=new Map,Il=new Map,Nl=[yt(ri(),".slack-cli",".env.local"),yt(ri(),".config/slack-cli",".env")];function ti(e){if(!zm(e))return;let t=Ll(e,"utf8");for(let n of t.split(`
465
+ `)){let s=n.trim();if(!s||s.startsWith("#"))continue;let r=s.indexOf("=");if(r===-1)continue;let o=s.slice(0,r).trim(),i=s.slice(r+1).trim();if(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))i=i.slice(1,-1);if(Nl.includes(e))Il.set(o,[...Il.get(o)??[],{path:e,val:i}]);if(!(o in process.env))process.env[o]=i,Ol.set(o,e)}}function vx(e){Tx(e,{recursive:!0});let t=yt(e,".gitignore");if(!zm(t))Ym(t,`*
466
+ `)}function Px(){for(let e of Nl)ti(e);ti(yt(process.cwd(),".slack-cli",".env.local")),ti(yt(process.cwd(),".env.local")),ti(yt(process.cwd(),".env"))}function Lx(e){return Hm("sha256").update(e).digest("hex")}function L(e){return e&&typeof e==="object"&&!Array.isArray(e)?e:{}}function G(e){return Array.isArray(e)?e:[]}function oi(e){return Number(e.ts??0)}async function Gm(e,t,n){let s=t.user;if(typeof s==="string"){if(!n.has(s))n.set(s,await ve(e,s));return n.get(s)??s}return typeof t.username==="string"?t.username:"bot"}function Rl(e){let t=new Date(e*1000),n=t.getUTCFullYear(),s=String(t.getUTCMonth()+1).padStart(2,"0"),r=String(t.getUTCDate()).padStart(2,"0"),o=String(t.getUTCHours()).padStart(2,"0"),i=String(t.getUTCMinutes()).padStart(2,"0"),a=String(t.getUTCSeconds()).padStart(2,"0");return`${n}-${s}-${r} ${o}:${i}:${a}`}function ii(e){let[t,n="000000"]=e.split("."),s=Number(t),r=new Date(s*1000),o=r.getUTCFullYear(),i=String(r.getUTCMonth()+1).padStart(2,"0"),a=String(r.getUTCDate()).padStart(2,"0"),c=String(r.getUTCHours()).padStart(2,"0"),d=String(r.getUTCMinutes()).padStart(2,"0"),f=String(r.getUTCSeconds()).padStart(2,"0"),p=n.padEnd(6,"0").slice(0,6);return`${o}-${i}-${a}T${c}:${d}:${f}.${p}`}function Ml(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 Al(e){return/^\d{4}-\d{2}-\d{2}T/.test(e)?Ml(e):e}async function fi(e,t,n,s,r){let o=typeof t.ts==="string"?t.ts:`${oi(t)}.000000`,i=ii(o),a="?";if(typeof t.user==="string"){let m=t.user,b="@"+m;if(!n.has(b)){let _=await rm(e,m,async(x,S,E)=>(await ur(x,S,E))[1],r);n.set(b,_)}a=n.get(b)??m}else if(typeof t.username==="string")a=t.username;let c=typeof t.text==="string"?t.text:"",f=xs(await Yn(e,c,n,r)).split(`
467
+ `),p=f[0]+(f.length>1?`
468
+ `+f.slice(1).map((m)=>` ${m}`).join(`
469
+ `):""),g=s?`${s} @${a}`:`@${a}`,y=G(t.reactions).map(L).map((m)=>{let b=typeof m.name==="string"?m.name:"",_=Number(m.count??G(m.users).length??0);return b?`:${b}:\xD7${_}`:""}).filter(Boolean).join(" "),k=G(t.files).map(L).map((m)=>{let b=typeof m.name==="string"?m.name:typeof m.title==="string"?m.title:"(file)",_=typeof m.size==="number"?` (${pi(m.size)})`:"",x=typeof m.id==="string"?` [${m.id}]`:"";return`
470
+ \uD83D\uDCCE ${b}${_}${x}`}).join(""),w=Number(t.reply_count??0),u=w>0?` [+${w} ${w===1?"reply":"replies"}]`:"",l=await Promise.all(yl(t).map(async(m)=>({...m,text:m.text?xs(await Yn(e,m.text,n,r)):""}))),h=(y?`
471
+ ${y}`:"")+k+lm(l,ii);return`${i} ${g}: ${p}${u}${h}`}function pi(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function Nx(e){return G(e.files).map(L).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 Xm(e){let t=Nx(e),n=yl(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:G(e.reactions).map(L).map((s)=>({name:s.name??null,count:s.count??null,users:Array.isArray(s.users)?s.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 Mx(e,t,n,s,r){let o=[];for(let i of n){let a=i;if(Number(i.reply_count??0)>0&&typeof i.ts==="string"){let c=await Ne(e,t,i.ts,200,r),d=G(c.messages).map(L);a=d[d.length-1]??i}if(a.user!==s)o.push(i)}return o}async function Tm(e,t,n,s="text",r=!1,o){let i=ht(t),a=await we(e,t,o),c=new Map,f=await(async()=>{if(i?.threadTs){let g=await Ne(e,a,i.threadTs,n,o);return G(g.messages).map(L)}let p=await at(e,a,n,void 0,void 0,o);return G(p.messages).map(L).reverse()})();if(r){let{userId:p}=await Zc(e,o);f=await Mx(e,a,f,p,o)}if(s==="jsonl"){for(let p of f)console.log(JSON.stringify(Xm(p)));return}for(let p of f)console.log(await fi(e,p,c,void 0,o))}function Bx(e){let t=(r)=>r.replace(/\\/g,"\\\\").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t"),n=typeof e.user==="string"?e.user:typeof e.bot_id==="string"?e.bot_id:"",s=Array.isArray(e.files)&&e.files.length?` [files: ${e.files.length}]`:"";return`${String(e.ts)} ${n} ${t(typeof e.text==="string"?e.text:"")}${s}`}async function jx(e,t,n,s){let r=[],o;for(let i=0;i<200;i++){let a=L(await Qc(e,t,n,o?{cursor:o}:{},s));for(let c of G(a.messages).map(L))if(!r.some((d)=>d.ts===c.ts))r.push(c);if(o=String(L(a.response_metadata).next_cursor??"")||void 0,!o)return r}throw Error("thread has more than 200 pages: refusing to return it partially")}async function Fm(e,t,n,s,r="text",o,i){let a=await we(e,t,o),d=i!==void 0||r==="tsv"?await jx(e,a,Al(n),o):G((await Ne(e,a,Al(n),s,o)).messages).map(L);if(i!==void 0){let p=Number(Al(i));if(!Number.isFinite(p))throw Error(`--since needs a message ts (1700000000.000100) or ISO stamp (got ${W(i)})`);d=d.filter((g)=>Number(g.ts)>p)}if(r==="tsv"){for(let p of d)console.log(Bx(p));return}if(r==="jsonl"){for(let p of d)console.log(JSON.stringify(Xm(p)));return}let f=new Map;for(let p of d)console.log(await fi(e,p,f,void 0,o))}async function Wx(e){let t=await lr(e),n=G(t.channels).map(L).filter((r)=>r.is_member===!0).sort((r,o)=>Number(o.updated??0)-Number(r.updated??0)).slice(0,10),s=new Map;for(let r of n){let o=String(r.id??""),i=typeof r.name==="string"?r.name:typeof r.user==="string"?r.user:o,a=await at(e,o,5),c=G(a.messages).map(L).filter((d)=>d.subtype===void 0||d.subtype===null).filter((d)=>{let f=typeof d.text==="string"?d.text:"";return f.length>0&&!f.startsWith("<@")}).slice(0,3).reverse();if(c.length===0)continue;console.log(`-- #${i} --------------------------------`);for(let d of c){let f=await Gm(e,d,s),p=(typeof d.text==="string"?d.text:"").split(`
472
+ `)[0]??"",g=await Yn(e,p,s);console.log(` ${f}: ${g}`)}}}async function Ux(e,t){let n=await xg(e,"to:me"),s=G(cr(n,["messages","matches"])).map(L).slice(0,t),r=new Map,o=[];for(let i of s){let a=mm(oi(i)),c=o[o.length-1];if(c?.label===a)c.msgs.push(i);else o.push({label:a,msgs:[i]})}for(let i=0;i<o.length;i++){let{label:a,msgs:c}=o[i];if(i>0)console.log("");console.log(` ${a}`),console.log(" ----------------------------");for(let d of[...c].reverse()){let f=L(d.channel),p=f.is_im===!0,g=typeof f.name==="string"?f.name:"dm",y;if(p&&g.startsWith("U")){let k="@"+g;if(!r.has(k)){let[,w]=await ur(e,g);r.set(k,w)}y=`@${r.get(k)??g}`}else if(p)y=`@${g}`;else y=`#${g}`;console.log(await fi(e,d,r,y))}}}async function Jx(e,t,n,s,r="text",o){let i=await lr(e,o),a=G(i.channels).map(L).filter((c)=>s||c.is_member===!0).filter((c)=>{if(!n)return!0;return(typeof c.name==="string"?c.name:"").toLowerCase().includes(n.toLowerCase())}).sort((c,d)=>Number(d.updated??0)-Number(c.updated??0)).slice(0,t);if(r==="jsonl"){for(let c of a)console.log(JSON.stringify(c));return}for(let c of a){let d=String(c.id??""),f=typeof c.name==="string"?c.name:typeof c.user==="string"?c.user:d,p=c.is_im===!0,g=c.is_mpim===!0,y=p||g?"@":"#",k=c.is_member===!0?"":" (not joined)",w=typeof L(c.purpose).value==="string"?String(L(c.purpose).value):"",u=w?` ${w.split(`
473
+ `)[0]?.slice(0,60)}`:"";console.log(`${y}${f} ${d}${k}${u}`)}}function Kx(e){let t=(r)=>r.startsWith("xoxp-")||r.startsWith("xoxc-"),n=sa(),s=n.find((r)=>r.profile.token===e);if(!s)return;return n.find((r)=>t(r.profile.token)&&r.profile.teamId===s.profile.teamId)}async function Vm(e,t,n,s,r){let o=e,i=r,a;try{a=await tl(o,t,n,i)}catch(f){let p=f instanceof Error?f.message:String(f);if(e.startsWith("xoxb-")&&p.includes("not_allowed_token_type")){let g=Kx(e);if(g)console.error(`Note: search.messages needs a user token \u2014 the active profile is a bot token (xoxb-); falling back to profile "${g.name}".`),o=g.profile.token,i=g.profile.cookie,a=await tl(o,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.
472
474
  `+` Add a user-token profile: slack auth login (or slack auth login --token <token>)
473
- Then select it: slack auth use <name> (or pass --workspace <name>)`),process.exit(1)}else throw a}if(s){console.log(JSON.stringify(l,null,2));return}let u=G(nr(l,["messages","matches"])).map(O),f=new Map;for(let a of u){let c=O(a.channel),d=c.is_im===!0,p=typeof c.name==="string"?c.name:"dm",h;if(d&&p.startsWith("U")){let g="@"+p;if(!f.has(g)){let[,y]=await rr(o,p,i);f.set(g,y)}h=`@${f.get(g)??p}`}else if(d)h=`@${p}`;else h=`#${p}`;console.log(await ti(o,a,f,h,i))}}async function Em(e,t,n,s){let{ref:r,ts:o}=Yt(t);if(!o)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 Zc(e,r,we,s),ts:o}}async function ix(e,t){let n=cr(),s={};if(!t.mine)s.shared=!0;if(t.in)s.in=t.in;if(t.from)s.from=t.from;let r=Cg(t.state,n,s);if(!t.json){let o=await Be(e,t.cookie),i=t.mine?"your reactions only [hasmy:]":"anyone's reactions [has:]";console.error(`(From: ${oi(o)} \xB7 matching ${i})`),console.error(`(query: ${r})`)}await Ze("search.messages",()=>_m(e,r,t.count,t.json,t.cookie))}async function ax(e,t){let n=cr(),{channelId:s,ts:r}=await Em(e,t.target,t.channelId,t.cookie),o=await Rg(e,s,r,t.state,n,t.cookie);if(o.noop){console.log(`= Already ${t.state} (ts: ${r})`);return}let i=o.removed.length?`, removed ${o.removed.map((l)=>`:${l}:`).join(" ")}`:"";if(console.log(`\u2713 ${t.state} :${n.progress[t.state]}: (ts: ${r})${i}`),o.leftover.length)console.error(`\u26A0 ${o.leftover.map((l)=>`:${l}:`).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 cx(e,t){let n=cr(),{channelId:s,ts:r}=await Em(e,t.target,t.channelId,t.cookie),o=await Ig(e,s,r,t.flag,n,t.remove===!0,t.cookie);console.log(`\u2713 ${t.remove?"Cleared":"Flagged"} ${t.flag} :${o}: (ts: ${r})`)}async function lx(e,t){let n=cr(),s=t.channelId??await Zc(e,t.channel,we,t.cookie),r={limit:t.limit};if(t.fix)r.fix=!0;if(t.cookie)r.cookie=t.cookie;let o=await vg(e,s,n,r);if(o.findings.length===0)console.log(`\u2713 No multi-state tasks in ${o.scanned} message(s).`);else{for(let i of o.findings){let l=i.fixed===!0?"fixed":i.fixed===!1?`FAILED: ${i.error??"?"}`:"needs --fix";console.log(`${i.ts} ${i.emoji.map((u)=>`:${u}:`).join(" ")} \u2192 keep :${i.keep}: [${l}] ${M(i.text).slice(0,60)}`)}console.log(`${o.findings.length} multi-state task(s) in ${o.scanned} message(s).`)}if(o.truncated)console.error(`\u26A0 Scan limit reached (${t.limit} messages) \u2014 older history was NOT checked. Raise it with --limit N.`)}async function ux(e,t,n,s){let r=Math.floor(Date.now()/1000)-t*86400,o=await sr(e),i=G(o.channels).map(O).filter((a)=>a.is_member===!0&&a.is_im!==!0&&a.is_mpim!==!0).filter((a)=>{if(!s)return!0;return(typeof a.name==="string"?a.name:"").toLowerCase().includes(s.toLowerCase())}).sort((a,c)=>Number(c.updated??0)-Number(a.updated??0)),l=new Map,u=0,f=0;for(let a of i){let c=String(a.id??""),d=typeof a.name==="string"?a.name:c,p;try{p=await it(e,c,n)}catch(g){console.error(` SKIP #${d}: ${g.message}`);continue}let h=G(p.messages).map(O).filter((g)=>(g.subtype===void 0||g.subtype===null)&&Yo(g)>=r);if(h.length===0)continue;f+=1,u+=h.length,console.log(`## #${d} (${h.length} msgs)
474
- `);for(let g of[...h].reverse()){let y=await xm(e,g,l),m=typeof g.text==="string"?g.text:"",k=ms(await Jn(e,m,l)).split(`
475
- `).join(" \u21B5 ");console.log(`[${Kn(Yo(g))}] ${y}: ${k}`)}console.log("")}console.error(`Dumped ${u} messages across ${f} channels (cutoff: ${t}d)`)}function dx(e){let t=[];function n(s){if(typeof s==="string"){t.push(s);return}if(Array.isArray(s)){for(let r of s)n(r);return}if(s&&typeof s==="object"){let r=s;if(typeof r.text==="string"){t.push(r.text);return}if(r.type==="link"&&typeof r.url==="string"){t.push(r.url);return}if(Array.isArray(r.elements))n(r.elements);else if(Array.isArray(r.content))n(r.content)}}for(let s of e)n(s);return t.join("").trim()}async function si(e,t,n){let s=new Map;return async(r)=>{if(!r)return"(unknown)";if(s.has(r))return s.get(r);try{let o=await hg(e,r,t),i=O(o.channel),l;if(i.is_im===!0){let u=typeof i.user==="string"?i.user:"";if(!u||u===n)l="@self";else{let[f]=await rr(e,u);l=`@${f}`}}else l=`#${typeof i.name==="string"?i.name:r}`;return s.set(r,l),l}catch{return r}}}function xl(e){let t=O(G(e.destinations)[0]);return String(t.channel_id??e.channel_id??e.channel??"")}function Xo(e){return dx(G(e.blocks))||(typeof e.text==="string"?e.text:"(no text)")}async function fx(e,t,n=!1){let s=await or(e,t),r=G(s.drafts??s.messages??[]).map(O).filter((f)=>f.is_deleted!==!0),o=n?r:r.filter((f)=>f.is_sent!==!0);if(o.length===0){console.log(n?"No drafts.":"No pending drafts. Run with --all to include sent.");return}let i="";try{({userId:i}=await qc(e,t))}catch{}let l=await si(e,t,i),u=new Map;for(let f of o){let a=xl(f),c=Xo(f),d=Number(f.date_created??f.date_create??0),p=d?ml(d):"?",h=await l(a),g=typeof f.id==="string"?f.id:"",y=f.is_sent===!0?" [SENT]":"",m=ms(await Jn(e,c,u));console.log(`-- ${g} ${h} [${p}]${y}`);for(let w of m.split(`
476
- `))console.log(` ${w}`)}}var Vo=50,fr=20;async function px(e,t,n){let s=[],r,o=0;do{let c=O(await Uc(e,{filter:n.filter,limit:Vo,cursor:r},t));s.push(...Hc(c));let d=O(c.response_metadata).next_cursor;r=typeof d==="string"&&d?d:void 0}while(r&&++o<fr);if(r)console.error(`Note: read the first ${s.length} items only (${fr} pages); the order covers those.`);let i=kg(s).slice(0,n.limit);if(i.length===0){(n.json?console.error:console.log)(`No ${n.filter==="todo"?"to-dos":`${n.filter} items`}.`);return}let l="",u="";try{({url:l,userId:u}=await Ut(e,t))}catch{}let f=await si(e,t,u),a=Date.now()/1000;for(let c of i){let d;if(c.channel&&c.ts)try{let w=O(await Le(e,c.channel,c.ts,1,t));d=G(w.messages).map(O).find((k)=>k.ts===c.ts)}catch{}let p=c.channel&&c.ts?l?Yc(l,c.channel,c.ts):`${c.channel}:${c.ts}`:"";if(n.json){console.log(JSON.stringify({...c,done:ar(c),permalink:p,user:d?.user??null,text:d?.text??null}));continue}let h=c.channel?await f(c.channel):`(${c.itemType||"item"})`,g=typeof d?.user==="string"?`@${await Re(e,d.user,t)}: `:"",y=typeof d?.text==="string"?d.text.split(`
477
- `)[0]??"":"(message not readable)",m=y.length>100?`${y.slice(0,100)}\u2026`:y;if(console.log(`${zc(c,a,Kn)} ${M(h)}`),console.log(` ${M(g+m)}`),p)console.log(` ${p}`)}}function hx(e){if(e.kind==="done")return e.undo?["completed","todo","saved","archived"]:["todo","saved","completed","archived"];return["todo","saved","completed","archived"]}async function gx(e,t,n,s,r){let o=0;for(let i of r){let l;do{if(o++>=fr)return"unknown";let u=O(await Uc(e,{filter:i,limit:Vo,cursor:l},t)),f=Hc(u).find((c)=>c.channel===n&&c.ts===s);if(f)return f;let a=O(u.response_metadata).next_cursor;l=typeof a==="string"&&a?a:void 0}while(l)}return}function mx(e,t){let n=(s)=>s===void 0?[]:[` Due: ${s?t(s):"(clear the due date)"}`];switch(e.kind){case"add":return[` Action: add as ${e.saved?"a saved item (no checkbox)":"a to-do"}`,...n(e.due)];case"done":return[` Action: mark ${e.undo?"NOT done (reopen)":"done"}`];case"edit":return[" Action: edit",...e.todo===void 0?[]:[` Kind: ${e.todo?"to-do":"saved item (no checkbox)"}`],...n(e.due)];case"rm":return[" Action: REMOVE from your To-dos (the message itself is untouched)"]}}async function Ko(e,t,n,s,r){let{ref:o,ts:i}=Yt(n);if(!i)console.error("Error: a To-do points at a message \u2014 give its permalink or #chan:<ts> (see `slack todos ls`)."),process.exit(2);if(s.kind==="edit"&&s.due===void 0&&s.todo===void 0)console.error("Error: nothing to edit \u2014 pass --due <time|none>, --todo or --saved."),process.exit(2);let l=await we(e,o,t),u=await gx(e,t,l,i,hx(s));if(u==="unknown"&&s.kind!=="add")console.error(`Error: not found in the first ${fr*Vo} saved items \u2014 stopped there to stay under Slack's rate limits. Nothing was changed.`),process.exit(1);let f=u==="unknown"?void 0:u;if(s.kind==="add"&&f)console.error(`Error: that message is already in your To-dos (${ar(f)?"done":f.todoState||"saved"}) \u2014 use \`slack todos edit\` or \`done\`.`),process.exit(1);if(s.kind!=="add"&&!f)console.error("Error: that message is not in your To-dos \u2014 nothing to change. `slack todos ls --filter saved` lists everything saved."),process.exit(1);let a="",c="";try{({url:a,userId:c}=await Ut(e,t))}catch{}let d=await(await si(e,t,c))(l),p;try{let _=O(await Le(e,l,i,1,t));p=G(_.messages).map(O).find((D)=>D.ts===i)}catch{}let h=typeof p?.user==="string"?`@${await Re(e,p.user,t)}: `:"",g=typeof p?.text==="string"?p.text.split(`
478
- `)[0]??"":"(message not readable)",y=ys(g.length>100?`${g.slice(0,100)}\u2026`:g),m=Date.now()/1000,w=De("todos",JSON.stringify(s),l,i,c);if(r!==w)Se(r,w,["--- To-do ------------------------------------",` For: ${c?`@${await Re(e,c,t)} (your own To-dos)`:"(your own To-dos)"}`,` Where: ${M(d)}`,` Msg: ${M(h+y)}`,...a?[` Link: ${Yc(a,l,i)}`]:[],...f?[` Now: ${zc(f,m,Kn)}`]:[],...u==="unknown"?[` Note: not checked beyond the first ${fr*Vo} saved items \u2014 it may already be saved`]:[],...mx(s,jm),"----------------------------------------------"]);let k={channel:l,ts:i};switch(s.kind){case"add":await ug(e,k,{todo:!s.saved,...s.due?{due:s.due}:{}},t),console.log(`\u2713 Added to your To-dos${s.due?` (due ${Kn(s.due)})`:""}`);break;case"done":await Kc(e,k,{mark:s.undo?"uncompleted":"completed"},t),console.log(s.undo?"\u2713 Reopened":"\u2713 Marked done");break;case"edit":await Kc(e,k,{...s.todo===void 0?{}:{todo:s.todo},...s.due===void 0?{}:{due:s.due}},t),console.log("\u2713 Updated");break;case"rm":await dg(e,k,t),console.log("\u2713 Removed from your To-dos");break}}async function yx(e,t,n){let s=await or(e,t),r=G(s.drafts).map(O).find((h)=>String(h.id)===n);if(!r)console.error(`Draft not found: ${n}`),process.exit(1);let o="";try{({userId:o}=await qc(e,t))}catch{}let i=await si(e,t,o),l=xl(r),u=Xo(r),f=Number(r.date_created??0),a=String(r.last_updated_ts??"?"),c=await i(l),p=ms(await Jn(e,u,new Map));console.log(`id: ${r.id}`),console.log(`channel: ${c} (${l})`),console.log(`created: ${f?ml(f):"?"}`),console.log(`updated: ${ml(Number(a.split(".")[0]))}`),console.log(`status: ${r.is_sent===!0?"sent":"pending"}`),console.log("---"),console.log(p)}function De(...e){return VD(e.join(`
479
- `)).slice(0,4)}function M(e){return e.replace(/\x1b\[[0-9;:?]*[ -/]*[@-~]/g,"").replace(/[\x00-\x1f\x7f-\x9f]/g,"").replace(/[\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/g,"")}var bx={"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 ge(e){let t=e instanceof Error?e.message:String(e),n=t.match(/Slack error on (\S+): (\w+)/);if(!n)return t;let[,s,r]=n;switch(r){case"missing_scope":return`Error: token lacks the ${bx[s]??"the required"} scope (needed for ${s}). 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 ri(e,t,n){if(!t.startsWith("D"))return null;try{let s=await ii(e,t,n);if(!s)return null;return await Og(e,s,fs,n)}catch{return null}}function Se(e,t,n,s,r=new Date){for(let i of n)console.log(i);let o=al(r,s);if(o)console.log(o);if(e!==void 0)console.error(`Code mismatch (got ${e}, expected ${t})`);console.error(`Rerun with --code=${t}`),process.exit(1)}function Yt(e){let t=pt(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 s=e.slice(n+1);if(/^\d{10}\.\d{6}$/.test(s))return{ref:e.slice(0,n),ts:s};if(/^\d{4}-\d{2}-\d{2}T/.test(s))return{ref:e.slice(0,n),ts:Dl(s)}}}return{ref:e}}function $t(e,t=!0){let n=pt(e);if(n){if(!t)return{ref:n.channel};let o=n.threadTs??n.ts;return o?{ref:n.channel,threadTs:o}:{ref:n.channel}}let s=e.indexOf(":");if(s>0){let o=e.slice(s+1);if(/^\d{10}\.\d{6}$/.test(o))return{ref:e.slice(0,s),threadTs:o};if(/^\d{4}-\d{2}-\d{2}T/.test(o))return{ref:e.slice(0,s),threadTs:Dl(o)}}let r=cc(e);if(r)return r.thread_ts?{ref:r.channel,threadTs:r.thread_ts}:{ref:r.channel};return{ref:e}}async function sm(e,t,n,s,r,o=!1){let i=cs(n),l,u;if(s)if(pt(s)){let f=await ks(e,s,t);l=f.channel,u=f.root}else{let f=$t(s);if(!f.threadTs&&/^\d{10}\.\d{6}$/.test(s)){if(!i.channel)return{error:`a bare ts needs a channel: set \`channel\` in .slack-hub/settings.yml, or pass #chan:${s}`};f={ref:i.channel,threadTs:s}}if(!f.threadTs)return{error:`"${s}" is not a thread \u2014 reply only posts in threads. For a top-level post use \`slack send\`.`};l=await we(e,f.ref,t),u=f.threadTs}if(r){let f=await ks(e,r,t);if(l===void 0)l=f.channel,u=f.root;else if(!o){let a=dc({channel:l,...u?{threadTs:u}:{}},f);if(a)return{error:a}}}if(!l||!u)return{error:"reply needs a destination (alias, permalink, #chan:<ts>) or --to <permalink>"};if(Mn(n)&&!dn(n).some((f)=>f.channel===l&&(f.thread_ts===void 0||f.thread_ts===u)))return{error:`${l} thread ${u} is not one of ${n.dir}'s subscriptions (restrict_to_subscriptions)`};return{channel:l,threadTs:u}}async function ks(e,t,n){let s=pt(t),r,o,i;if(s)r=s.channel,o=s.ts,i=s.threadTs;else{let u=$t(t);r=u.ref,o=u.threadTs}if(!o)throw Error(`--to needs a message permalink (or #chan:<ts>), got "${t}"`);let l=await we(e,r,n);if(!i)try{let u=O(await Le(e,l,o,1,n)).messages??[],f=u.map(O).find((a)=>a.ts===o)??O(u[0]);i=typeof f.thread_ts==="string"?f.thread_ts:o}catch(u){if(!/thread_not_found/.test(u instanceof Error?u.message:String(u)))throw u;i=o}return{channel:l,ts:o,root:i}}async function zt(e,t,n,s){let r=n;if(/^#?[CDG][A-Z0-9]{8,}$/.test(n)||!n.startsWith("#")&&!n.startsWith("@"))try{let i=O(await Wn(e,t,s)),l=O(i.channel);if(l.is_im===!0){let u=typeof l.user==="string"?l.user:"";r=u?`@${await Re(e,u,s)}`:t}else r=typeof l.name==="string"?`#${l.name}`:t}catch{r=t}return r===t?t:`${r} (${t})`}async function Be(e,t){try{return await Ut(e,t)}catch{return null}}function Gt(e,t){let n;return async()=>{if(n===void 0)n=await Be(e,t);return n}}function Hn(e){if(!Oo())return{record:()=>{}};let t=Ah();return{metadata:Th(e,t),record:(n)=>{Fh({...n,kind:e,attribution:t})}}}function wx(e){let t=M(e.text.split(`
480
- `)[0]??"").slice(0,100),n=e.permalink||`${e.channel}:${e.ts}`,s=[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`${Kn(e.sent_at/1000)} ${e.kind.padEnd(4)} ${M(e.target??e.channel)} ${n}
475
+ Then select it: slack auth use <name> (or pass --workspace <name>)`),process.exit(1)}else throw f}if(s){console.log(JSON.stringify(a,null,2));return}let c=G(cr(a,["messages","matches"])).map(L),d=new Map;for(let f of c){let p=L(f.channel),g=p.is_im===!0,y=typeof p.name==="string"?p.name:"dm",k;if(g&&y.startsWith("U")){let w="@"+y;if(!d.has(w)){let[,u]=await ur(o,y,i);d.set(w,u)}k=`@${d.get(w)??y}`}else if(g)k=`@${y}`;else k=`#${y}`;console.log(await fi(o,f,d,k,i))}}async function Zm(e,t,n,s){let{ref:r,ts:o}=Xt(t);if(!o)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 hl(e,r,we,s),ts:o}}async function qx(e,t){let n=hr(),s={};if(!t.mine)s.shared=!0;if(t.in)s.in=t.in;if(t.from)s.from=t.from;let r=tm(t.state,n,s);if(!t.json){let o=await je(e,t.cookie),i=t.mine?"your reactions only [hasmy:]":"anyone's reactions [has:]";console.error(`(From: ${mi(o)} \xB7 matching ${i})`),console.error(`(query: ${r})`)}await Qe("search.messages",()=>Vm(e,r,t.count,t.json,t.cookie))}async function Hx(e,t){let n=hr(),{channelId:s,ts:r}=await Zm(e,t.target,t.channelId,t.cookie),o=await im(e,s,r,t.state,n,t.cookie);if(o.noop){console.log(`= Already ${t.state} (ts: ${r})`);return}let i=o.removed.length?`, removed ${o.removed.map((a)=>`:${a}:`).join(" ")}`:"";if(console.log(`\u2713 ${t.state} :${n.progress[t.state]}: (ts: ${r})${i}`),o.leftover.length)console.error(`\u26A0 ${o.leftover.map((a)=>`:${a}:`).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 zx(e,t){let n=hr(),{channelId:s,ts:r}=await Zm(e,t.target,t.channelId,t.cookie),o=await am(e,s,r,t.flag,n,t.remove===!0,t.cookie);console.log(`\u2713 ${t.remove?"Cleared":"Flagged"} ${t.flag} :${o}: (ts: ${r})`)}async function Yx(e,t){let n=hr(),s=t.channelId??await hl(e,t.channel,we,t.cookie),r={limit:t.limit};if(t.fix)r.fix=!0;if(t.cookie)r.cookie=t.cookie;let o=await cm(e,s,n,r);if(o.findings.length===0)console.log(`\u2713 No multi-state tasks in ${o.scanned} message(s).`);else{for(let i of o.findings){let a=i.fixed===!0?"fixed":i.fixed===!1?`FAILED: ${i.error??"?"}`:"needs --fix";console.log(`${i.ts} ${i.emoji.map((c)=>`:${c}:`).join(" ")} \u2192 keep :${i.keep}: [${a}] ${W(i.text).slice(0,60)}`)}console.log(`${o.findings.length} multi-state task(s) in ${o.scanned} message(s).`)}if(o.truncated)console.error(`\u26A0 Scan limit reached (${t.limit} messages) \u2014 older history was NOT checked. Raise it with --limit N.`)}async function Gx(e,t,n,s){let r=Math.floor(Date.now()/1000)-t*86400,o=await lr(e),i=G(o.channels).map(L).filter((f)=>f.is_member===!0&&f.is_im!==!0&&f.is_mpim!==!0).filter((f)=>{if(!s)return!0;return(typeof f.name==="string"?f.name:"").toLowerCase().includes(s.toLowerCase())}).sort((f,p)=>Number(p.updated??0)-Number(f.updated??0)),a=new Map,c=0,d=0;for(let f of i){let p=String(f.id??""),g=typeof f.name==="string"?f.name:p,y;try{y=await at(e,p,n)}catch(w){console.error(` SKIP #${g}: ${w.message}`);continue}let k=G(y.messages).map(L).filter((w)=>(w.subtype===void 0||w.subtype===null)&&oi(w)>=r);if(k.length===0)continue;d+=1,c+=k.length,console.log(`## #${g} (${k.length} msgs)
476
+ `);for(let w of[...k].reverse()){let u=await Gm(e,w,a),l=typeof w.text==="string"?w.text:"",m=xs(await Yn(e,l,a)).split(`
477
+ `).join(" \u21B5 ");console.log(`[${Gn(oi(w))}] ${u}: ${m}`)}console.log("")}console.error(`Dumped ${c} messages across ${d} channels (cutoff: ${t}d)`)}function Xx(e){let t=[];function n(s){if(typeof s==="string"){t.push(s);return}if(Array.isArray(s)){for(let r of s)n(r);return}if(s&&typeof s==="object"){let r=s;if(typeof r.text==="string"){t.push(r.text);return}if(r.type==="link"&&typeof r.url==="string"){t.push(r.url);return}if(Array.isArray(r.elements))n(r.elements);else if(Array.isArray(r.content))n(r.content)}}for(let s of e)n(s);return t.join("").trim()}async function hi(e,t,n){let s=new Map;return async(r)=>{if(!r)return"(unknown)";if(s.has(r))return s.get(r);try{let o=await Ug(e,r,t),i=L(o.channel),a;if(i.is_im===!0){let c=typeof i.user==="string"?i.user:"";if(!c||c===n)a="@self";else{let[d]=await ur(e,c);a=`@${d}`}}else a=`#${typeof i.name==="string"?i.name:r}`;return s.set(r,a),a}catch{return r}}}function Bl(e){let t=L(G(e.destinations)[0]);return String(t.channel_id??e.channel_id??e.channel??"")}function ai(e){return Xx(G(e.blocks))||(typeof e.text==="string"?e.text:"(no text)")}async function Vx(e,t,n=!1){let s=await dr(e,t),r=G(s.drafts??s.messages??[]).map(L).filter((d)=>d.is_deleted!==!0),o=n?r:r.filter((d)=>d.is_sent!==!0);if(o.length===0){console.log(n?"No drafts.":"No pending drafts. Run with --all to include sent.");return}let i="";try{({userId:i}=await al(e,t))}catch{}let a=await hi(e,t,i),c=new Map;for(let d of o){let f=Bl(d),p=ai(d),g=Number(d.date_created??d.date_create??0),y=g?Rl(g):"?",k=await a(f),w=typeof d.id==="string"?d.id:"",u=d.is_sent===!0?" [SENT]":"",l=xs(await Yn(e,p,c));console.log(`-- ${w} ${k} [${y}]${u}`);for(let h of l.split(`
478
+ `))console.log(` ${h}`)}}var ci=50,wr=20;async function Zx(e,t,n){let s=[],r,o=0;do{let p=L(await rl(e,{filter:n.filter,limit:ci,cursor:r},t));s.push(...cl(p));let g=L(p.response_metadata).next_cursor;r=typeof g==="string"&&g?g:void 0}while(r&&++o<wr);if(r)console.error(`Note: read the first ${s.length} items only (${wr} pages); the order covers those.`);let i=Yg(s).slice(0,n.limit);if(i.length===0){(n.json?console.error:console.log)(`No ${n.filter==="todo"?"to-dos":`${n.filter} items`}.`);return}let a="",c="";try{({url:a,userId:c}=await Ct(e,t))}catch{}let d=await hi(e,t,c),f=Date.now()/1000;for(let p of i){let g;if(p.channel&&p.ts)try{let h=L(await Ne(e,p.channel,p.ts,1,t));g=G(h.messages).map(L).find((m)=>m.ts===p.ts)}catch{}let y=p.channel&&p.ts?a?ul(a,p.channel,p.ts):`${p.channel}:${p.ts}`:"";if(n.json){console.log(JSON.stringify({...p,done:pr(p),permalink:y,user:g?.user??null,text:g?.text??null}));continue}let k=p.channel?await d(p.channel):`(${p.itemType||"item"})`,w=typeof g?.user==="string"?`@${await ve(e,g.user,t)}: `:"",u=typeof g?.text==="string"?g.text.split(`
479
+ `)[0]??"":"(message not readable)",l=u.length>100?`${u.slice(0,100)}\u2026`:u;if(console.log(`${ll(p,f,Gn)} ${W(k)}`),console.log(` ${W(w+l)}`),y)console.log(` ${y}`)}}function Qx(e){if(e.kind==="done")return e.undo?["completed","todo","saved","archived"]:["todo","saved","completed","archived"];return["todo","saved","completed","archived"]}async function eS(e,t,n,s,r){let o=0;for(let i of r){let a;do{if(o++>=wr)return"unknown";let c=L(await rl(e,{filter:i,limit:ci,cursor:a},t)),d=cl(c).find((p)=>p.channel===n&&p.ts===s);if(d)return d;let f=L(c.response_metadata).next_cursor;a=typeof f==="string"&&f?f:void 0}while(a)}return}function tS(e,t){let n=(s)=>s===void 0?[]:[` Due: ${s?t(s):"(clear the due date)"}`];switch(e.kind){case"add":return[` Action: add as ${e.saved?"a saved item (no checkbox)":"a to-do"}`,...n(e.due)];case"done":return[` Action: mark ${e.undo?"NOT done (reopen)":"done"}`];case"edit":return[" Action: edit",...e.todo===void 0?[]:[` Kind: ${e.todo?"to-do":"saved item (no checkbox)"}`],...n(e.due)];case"rm":return[" Action: REMOVE from your To-dos (the message itself is untouched)"]}}async function ni(e,t,n,s,r){let{ref:o,ts:i}=Xt(n);if(!i)console.error("Error: a To-do points at a message \u2014 give its permalink or #chan:<ts> (see `slack todos ls`)."),process.exit(2);if(s.kind==="edit"&&s.due===void 0&&s.todo===void 0)console.error("Error: nothing to edit \u2014 pass --due <time|none>, --todo or --saved."),process.exit(2);let a=await we(e,o,t),c=await eS(e,t,a,i,Qx(s));if(c==="unknown"&&s.kind!=="add")console.error(`Error: not found in the first ${wr*ci} saved items \u2014 stopped there to stay under Slack's rate limits. Nothing was changed.`),process.exit(1);let d=c==="unknown"?void 0:c;if(s.kind==="add"&&d)console.error(`Error: that message is already in your To-dos (${pr(d)?"done":d.todoState||"saved"}) \u2014 use \`slack todos edit\` or \`done\`.`),process.exit(1);if(s.kind!=="add"&&!d)console.error("Error: that message is not in your To-dos \u2014 nothing to change. `slack todos ls --filter saved` lists everything saved."),process.exit(1);let f="",p="";try{({url:f,userId:p}=await Ct(e,t))}catch{}let g=await(await hi(e,t,p))(a),y;try{let b=L(await Ne(e,a,i,1,t));y=G(b.messages).map(L).find((_)=>_.ts===i)}catch{}let k=typeof y?.user==="string"?`@${await ve(e,y.user,t)}: `:"",w=typeof y?.text==="string"?y.text.split(`
480
+ `)[0]??"":"(message not readable)",u=Ss(w.length>100?`${w.slice(0,100)}\u2026`:w),l=Date.now()/1000,h=De("todos",JSON.stringify(s),a,i,p);if(r!==h)Se(r,h,["--- To-do ------------------------------------",` For: ${p?`@${await ve(e,p,t)} (your own To-dos)`:"(your own To-dos)"}`,` Where: ${W(g)}`,` Msg: ${W(k+u)}`,...f?[` Link: ${ul(f,a,i)}`]:[],...d?[` Now: ${ll(d,l,Gn)}`]:[],...c==="unknown"?[` Note: not checked beyond the first ${wr*ci} saved items \u2014 it may already be saved`]:[],...tS(s,py),"----------------------------------------------"]);let m={channel:a,ts:i};switch(s.kind){case"add":await Mg(e,m,{todo:!s.saved,...s.due?{due:s.due}:{}},t),console.log(`\u2713 Added to your To-dos${s.due?` (due ${Gn(s.due)})`:""}`);break;case"done":await il(e,m,{mark:s.undo?"uncompleted":"completed"},t),console.log(s.undo?"\u2713 Reopened":"\u2713 Marked done");break;case"edit":await il(e,m,{...s.todo===void 0?{}:{todo:s.todo},...s.due===void 0?{}:{due:s.due}},t),console.log("\u2713 Updated");break;case"rm":await Bg(e,m,t),console.log("\u2713 Removed from your To-dos");break}}async function nS(e,t,n){let s=await dr(e,t),r=G(s.drafts).map(L).find((k)=>String(k.id)===n);if(!r)console.error(`Draft not found: ${n}`),process.exit(1);let o="";try{({userId:o}=await al(e,t))}catch{}let i=await hi(e,t,o),a=Bl(r),c=ai(r),d=Number(r.date_created??0),f=String(r.last_updated_ts??"?"),p=await i(a),y=xs(await Yn(e,c,new Map));console.log(`id: ${r.id}`),console.log(`channel: ${p} (${a})`),console.log(`created: ${d?Rl(d):"?"}`),console.log(`updated: ${Rl(Number(f.split(".")[0]))}`),console.log(`status: ${r.is_sent===!0?"sent":"pending"}`),console.log("---"),console.log(y)}function De(...e){return Lx(e.join(`
481
+ `)).slice(0,4)}function W(e){return e.replace(/\x1b\[[0-9;:?]*[ -/]*[@-~]/g,"").replace(/[\x00-\x1f\x7f-\x9f]/g,"").replace(/[\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/g,"")}var sS={"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 ge(e){let t=e instanceof Error?e.message:String(e),n=t.match(/Slack error on (\S+): (\w+)/);if(!n)return t;let[,s,r]=n;switch(r){case"missing_scope":return`Error: token lacks the ${sS[s]??"the required"} scope (needed for ${s}). 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 gi(e,t,n){if(!t.startsWith("D"))return null;try{let s=await yi(e,t,n);if(!s)return null;return await om(e,s,bs,n)}catch{return null}}function Se(e,t,n,s,r=new Date){for(let i of n)console.log(i);let o=Sl(r,s);if(o)console.log(o);if(e!==void 0)console.error(`Code mismatch (got ${e}, expected ${t})`);console.error(`Rerun with --code=${t}`),process.exit(1)}function Xt(e){let t=ht(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 s=e.slice(n+1);if(/^\d{10}\.\d{6}$/.test(s))return{ref:e.slice(0,n),ts:s};if(/^\d{4}-\d{2}-\d{2}T/.test(s))return{ref:e.slice(0,n),ts:Ml(s)}}}return{ref:e}}function At(e,t=!0){let n=ht(e);if(n){if(!t)return{ref:n.channel};let o=n.threadTs??n.ts;return o?{ref:n.channel,threadTs:o}:{ref:n.channel}}let s=e.indexOf(":");if(s>0){let o=e.slice(s+1);if(/^\d{10}\.\d{6}$/.test(o))return{ref:e.slice(0,s),threadTs:o};if(/^\d{4}-\d{2}-\d{2}T/.test(o))return{ref:e.slice(0,s),threadTs:Ml(o)}}let r=xc(e);if(r)return r.thread_ts?{ref:r.channel,threadTs:r.thread_ts}:{ref:r.channel};return{ref:e}}async function Om(e,t,n,s,r,o=!1){let i=ps(n),a,c;if(s)if(ht(s)){let d=await $s(e,s,t);a=d.channel,c=d.root}else{let d=At(s);if(!d.threadTs&&/^\d{10}\.\d{6}$/.test(s)){if(!i.channel)return{error:`a bare ts needs a channel: set \`channel\` in .slack-hub/settings.yml, or pass #chan:${s}`};d={ref:i.channel,threadTs:s}}if(!d.threadTs)return{error:`"${s}" is not a thread \u2014 reply only posts in threads. For a top-level post use \`slack send\`.`};a=await we(e,d.ref,t),c=d.threadTs}if(r){let d=await $s(e,r,t);if(a===void 0)a=d.channel,c=d.root;else if(!o){let f=Ec({channel:a,...c?{threadTs:c}:{}},d);if(f)return{error:f}}}if(!a||!c)return{error:"reply needs a destination (alias, permalink, #chan:<ts>) or --to <permalink>"};if(Un(n)&&!pn(n).some((d)=>d.channel===a&&(d.thread_ts===void 0||d.thread_ts===c)))return{error:`${a} thread ${c} is not one of ${n.dir}'s subscriptions (restrict_to_subscriptions)`};return{channel:a,threadTs:c}}async function $s(e,t,n){let s=ht(t),r,o,i;if(s)r=s.channel,o=s.ts,i=s.threadTs;else{let c=At(t);r=c.ref,o=c.threadTs}if(!o)throw Error(`--to needs a message permalink (or #chan:<ts>), got "${t}"`);let a=await we(e,r,n);if(!i)try{let c=L(await Ne(e,a,o,1,n)).messages??[],d=c.map(L).find((f)=>f.ts===o)??L(c[0]);i=typeof d.thread_ts==="string"?d.thread_ts:o}catch(c){if(!/thread_not_found/.test(c instanceof Error?c.message:String(c)))throw c;i=o}return{channel:a,ts:o,root:i}}async function Bt(e,t,n,s){let r=n;if(/^#?[CDG][A-Z0-9]{8,}$/.test(n)||!n.startsWith("#")&&!n.startsWith("@"))try{let i=L(await Hn(e,t,s)),a=L(i.channel);if(a.is_im===!0){let c=typeof a.user==="string"?a.user:"";r=c?`@${await ve(e,c,s)}`:t}else r=typeof a.name==="string"?`#${a.name}`:t}catch{r=t}return r===t?t:`${r} (${t})`}async function je(e,t){try{return await Ct(e,t)}catch{return null}}function Vt(e,t){let n;return()=>n??=je(e,t)}function Vn(e){if(!Wo())return{record:()=>{}};let t=Zh();return{metadata:Qh(e,t),record:(n)=>{eg({...n,kind:e,attribution:t})}}}function rS(e){let t=W(e.text.split(`
482
+ `)[0]??"").slice(0,100),n=e.permalink||`${e.channel}:${e.ts}`,s=[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`${Gn(e.sent_at/1000)} ${e.kind.padEnd(4)} ${W(e.target??e.channel)} ${n}
481
483
  ${t}
482
- ${M(s)}`}function oi(e,t){let n=t?" [as bot]":"";if(!e)return`(unknown \u2014 auth.test failed)${n}`;let s=M(e.user||e.userId||"?"),r=e.userId?` (${e.userId})`:"",o=e.team?` \u2014 ${M(e.team)}`:"";return`@${s}${r}${o}${n}`}function Ee(e,t={}){return` ${"From:".padEnd(t.pad??6)}${oi(e,t.asBot)}`}async function yl(e,t,n=60,s){let r=typeof t.user==="string"?await Re(e,t.user,s):typeof t.username==="string"?t.username:"?",o=ys((typeof t.text==="string"?t.text:"").split(`
483
- `)[0]??""),i=o.length>n?`${o.slice(0,n)}\u2026`:o,l=typeof t.ts==="string"?t.ts:"";return`${l?Go(l).slice(0,16).replace("T"," "):""} @${r}${i?`: ${i}`:""}`}async function kx(e,t,n,s){let r=n.find((o)=>String(o.ts)===t)??n[0];if(!r)return t;return yl(e,r,40,s)}function rm(e){return e.toLowerCase().replace(/<[@#!][^>]+>/g," ").replace(/[^\p{L}\p{N}\s]/gu," ").replace(/\s+/g," ").trim()}function Dx(e,t){let n=rm(e),s=rm(t);if(!n||!s)return 0;if(n===s)return 1;let r=(f)=>{let a=new Map;for(let c=0;c<f.length-1;c++){let d=f.slice(c,c+2);a.set(d,(a.get(d)??0)+1)}return a},o=r(n),i=r(s);if(o.size===0||i.size===0)return 0;let l=0;for(let[f,a]of o){let c=i.get(f);if(c)l+=Math.min(a,c)}let u=om(o)+om(i);return u===0?0:2*l/u}function om(e){let t=0;for(let n of e.values())t+=n;return t}async function im(e,t,n,s){let r=Ne();if(!r)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
484
- Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(1);if(s)return{botToken:r};let{ref:o}=Yt(e);if(!o.startsWith("@"))return{botToken:r};try{let i=await vt(t,o,n);return{botToken:r,channelId:await Ht(r,i)}}catch(i){console.error(`Error: could not resolve ${M(o)} to the bot's DM.
484
+ ${W(s)}`}function mi(e,t){let n=t?" [as bot]":"";if(!e)return`(unknown \u2014 auth.test failed)${n}`;let s=W(e.user||e.userId||"?"),r=e.userId?` (${e.userId})`:"",o=e.team?` \u2014 ${W(e.team)}`:"";return`@${s}${r}${o}${n}`}function Ee(e,t={}){return` ${"From:".padEnd(t.pad??6)}${mi(e,t.asBot)}`}async function vl(e,t,n=60,s){let r=typeof t.user==="string"?process.stdout.isTTY?await ve(e,t.user,s):t.user:typeof t.username==="string"?t.username:"?",o=Ss((typeof t.text==="string"?t.text:"").split(`
485
+ `)[0]??""),i=o.length>n?`${o.slice(0,n)}\u2026`:o,a=typeof t.ts==="string"?t.ts:"";return`${a?ii(a).slice(0,16).replace("T"," "):""} @${r}${i?`: ${i}`:""}`}async function oS(e,t,n,s){let r=n.find((o)=>String(o.ts)===t)??n[0];if(!r)return t;return vl(e,r,40,s)}function Im(e){return e.toLowerCase().replace(/<[@#!][^>]+>/g," ").replace(/[^\p{L}\p{N}\s]/gu," ").replace(/\s+/g," ").trim()}function iS(e,t){let n=Im(e),s=Im(t);if(!n||!s)return 0;if(n===s)return 1;let r=(d)=>{let f=new Map;for(let p=0;p<d.length-1;p++){let g=d.slice(p,p+2);f.set(g,(f.get(g)??0)+1)}return f},o=r(n),i=r(s);if(o.size===0||i.size===0)return 0;let a=0;for(let[d,f]of o){let p=i.get(d);if(p)a+=Math.min(f,p)}let c=Rm(o)+Rm(i);return c===0?0:2*a/c}function Rm(e){let t=0;for(let n of e.values())t+=n;return t}async function vm(e,t,n,s){let r=Me();if(!r)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
486
+ Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(1);if(s)return{botToken:r};let{ref:o}=Xt(e);if(!o.startsWith("@"))return{botToken:r};try{let i=await Nt(t,o,n);return{botToken:r,channelId:await Gt(r,i)}}catch(i){console.error(`Error: could not resolve ${W(o)} to the bot's DM.
485
487
  ${i instanceof Error?i.message:String(i)}
486
- `+" Tip: pass the message permalink, or --channel-id <D\u2026>, to skip the lookup."),process.exit(1)}}async function xx(e,t){let n=Gt(e,t.cookie),{ref:s,ts:r}=Yt(t.target);if(!r)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 o;if(t.channelId)o=t.channelId;else o=await we(e,s,t.cookie);let i=await Le(e,o,r,1,t.cookie),u=G(i.messages).map(O).find((S)=>String(S.ts)===r);if(!u)console.error(`Message not found at ts=${r} in channel ${o}`),process.exit(1);let f=typeof u.text==="string"?u.text:"",a=t.newText;if(t.tick){let S=Pp(f,t.tick.n);if(S.kind==="already")console.log(`already ticked (${S.n}.)`),process.exit(0);if(S.kind==="none")console.error("Error: the message has no \u2B1C <n>. item"),process.exit(2);if(S.kind==="missing")console.error(`Error: the message has no \u2B1C ${S.n}. item`),process.exit(2);if(S.kind==="ambiguous")console.error(`Error: several open items (${S.open.join(", ")}): name one, e.g. slack tick <target> ${S.open[0]}`),process.exit(2);a=S.text}else a=Lp(f,a,t.lanePrefix);let c=t.mentionCookie??t.cookie,d=t.mentions&&!t.tick?await Mg(t.mentionToken??e,a,o,c?{cookie:c}:{}):a;qe(d,t.allowUrlAdjacent);let p=Ft(f).kind,h=Ft(d).kind,g=Qs(f).kind!=="other",y=g?Qs(d).kind==="other":p!=="other"&&(h==="other"||p!=="open"&&h==="open");if(y&&!t.force)console.error(`Error: this message is ${g?"a `slack poll`":`a \`slack ask\` question (${p==="open"?"open":p==="resolved"?"answered":"void"})`}, and ${g||h==="other"?"the new text would no longer read back as one (collect could not find the question, the pills or the answer)":"the new text would turn it back into an OPEN question"}.
487
- `+(g?" Edit it anyway with --force.":` To retire it: slack ask --void='${t.target}' --reason '\u2026'
488
- Edit it anyway with --force.`)),process.exit(1);let m=y,w=await n(),k=m?De("force-edit-ask-poll",f,d,w?.userId??""):De(f,d,w?.userId??"");if(t.code!==k)Se(t.code,k,[...m?[`\u26A0 --force: rewriting a \`slack ${g?"poll":"ask"}\` message by hand \u2014 collect may no longer read it back`]:[],"--- Editing as -------------------------------",Ee(w,{asBot:t.asBot}),"--- Original message -------------------------",...f.split(`
489
- `).map((S)=>` ${S}`),"--- Replacing with ---------------------------",...d.split(`
490
- `).map((S)=>` ${S}`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);let _=Hn("edit"),D=p!=="other"||h!=="other"||g||Qs(d).kind!=="other",E=await Kt(e,o,r,d,t.cookie,D?!0:void 0,_.metadata);console.log(`\u2713 Edited (ts: ${E})`),_.record({team:w?.team,channel:o,target:t.target,ts:r,text:d,asBot:t.asBot})}async function Sx(e,t){let n=Gt(e,t.cookie),{ref:s,ts:r}=Yt(t.target);if(!r)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 o;if(t.channelId)o=t.channelId;else o=await we(e,s,t.cookie);let i=await Le(e,o,r,1,t.cookie),u=G(i.messages).map(O).find((d)=>String(d.ts)===r);if(!u)console.error(`Message not found at ts=${r} in channel ${o}`),process.exit(1);let f=typeof u.text==="string"?u.text:"",a=await n(),c=De(o,r,f,a?.userId??"");if(t.code!==c){let d=await zt(e,o,s,t.cookie);Se(t.code,c,["--- Deleting message -------------------------",Ee(a,{asBot:t.asBot}),` \u2192 ${d} at ${Go(r)}`,...f.split(`
491
- `).map((p)=>` ${p}`),"---------------------------------------------"])}await Qh(e,o,r,t.cookie),console.log(`\u2713 Deleted (ts: ${r})`)}function mn(e){return`'${e.replace(/'/g,"'\\''")}'`}async function Sl(e,t,n){let s=Uo(t);if(s)return{...s,ref:s.channel};let{ref:r,ts:o}=Yt(t);if(!o)console.error(`Error: ${M(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 ${mn(t)}`),process.exit(2);return{channel:await we(e,r,n),ts:o,ref:r}}async function _x(e,t,n,s){let r=O(await Le(e,t,n,1,s)),o=G(r.messages).map(O).find((i)=>String(i.ts)===n);if(!o)console.error(`Error: no message at ts=${n} in ${t}.`),process.exit(1);return o}function qo(e,t){if(t!==void 0)try{return wl(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:We(e)}var am=40000;function Zo(e,t){if(t.length>am)console.error(`Error: the ${e} is ${t.length} characters; Slack truncates past ${am}. Shorten it \u2014 move detail to a linked page.`),process.exit(2)}function Qo(e){let n=(e instanceof Error?e.message:String(e)).match(/Slack error on \S+: (\w+)/);if(e instanceof ot)return!0;return!!n&&!["internal_error","fatal_error","request_timeout","service_unavailable"].includes(n[1])}function $m(e,t){let n=al(e);return n&&n.includes("QUIET HOURS")?`\u26A0 Quiet hours (JST): ${t}.`:null}async function Ex(e,t){let{ref:n,ts:s}=Yt(t.target);if(s||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 ${mn(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(qe(t.state,t.allowUrlAdjacent),t.log!==void 0)qe(t.log,t.allowUrlAdjacent),Zo("reason",t.log);let r=`${t.workspace?` -w ${mn(t.workspace)}`:""}${t.asBot?" --as-bot":""}`,o=Gt(e,t.cookie),i=await we(e,n,t.cookie),l=await o(),u=De("pinlog-create",i,t.state,t.log??"",l?.userId??""),f=new Date,a=ul(t.state,f);if(Zo("HEAD (state + footer)",a),t.code!==u){let g=await zt(e,i,n,t.cookie),y=(await Cm(e,i,200,t.cookie)).found;Se(t.code,u,["--- New pinlog -------------------------------",Ee(l,{asBot:t.asBot}),` \u2192 ${g} \u2014 NEW top-level message, then pinned`,...y.length?[`\u26A0 ${y.length} board(s) already in this channel \u2014 to change one, use \`slack pinlog set <board> \u2026\` instead:`,...y.slice(0,5).map((m)=>` ${ht(i,String(m.ts))} ${Am(String(m.text))}`)]:[" (no other boards in the last 200 messages of this channel)"],"--- State (the top-level message) ------------",...a.split(`
492
- `).map((m)=>` ${M(m)}`),...t.log?["--- Reason (first thread reply \u2014 notifies) ---",...t.log.split(`
493
- `).map((m)=>` ${M(m)}`)]:[],"---------------------------------------------"])}let c=Hn("send"),d;try{d=await Jt(e,i,a,void 0,!1,t.cookie,!0,c.metadata)}catch(g){if(Qo(g))console.error(`\u2717 HEAD was NOT posted: ${ge(g)}`);else console.error(`\u26A0 UNKNOWN whether the HEAD was posted: ${ge(g)}
494
- Check before retrying, or you will have two boards: slack pinlog ls ${mn(t.target)}${r}`);process.exit(1)}if(!d)console.error("\u2717 Slack accepted the post but returned no ts \u2014 check the channel before retrying, it may have landed."),process.exit(1);c.record({team:l?.team,channel:i,target:t.target,ts:d,text:a,asBot:t.asBot});let p=ht(i,d);console.log(`\u2713 Posted HEAD: ${p}`);let h=$m(f,"this new top-level post notified everyone who follows the channel");if(h)console.error(h);try{await jc(e,i,d,t.cookie),console.log("\u2713 Pinned")}catch(g){let y=g instanceof Error?g.message:String(g),m=/missing_scope/.test(y)?`the ${t.asBot?"bot":"user"} token lacks the pins:write scope`:ge(g);console.error(`\u26A0 NOT pinned: ${m}.`),console.error(` The board works unpinned; pin it later with: slack pinlog pin ${p}${r}`)}if(t.log)try{let g=await Jt(e,i,t.log,d,!1,t.cookie,!0);console.log(`\u2713 Reason posted in the thread (ts: ${g})`)}catch(g){let y=De("pinlog-log",i,d,t.log,l?.userId??"");console.error(`${Qo(g)?"\u2717 The reason was NOT posted":"\u26A0 UNKNOWN whether the reason was posted"}: ${ge(g)}
488
+ `+" Tip: pass the message permalink, or --channel-id <D\u2026>, to skip the lookup."),process.exit(1)}}async function aS(e,t){let n=Vt(e,t.cookie),{ref:s,ts:r}=Xt(t.target);if(!r)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 o;if(t.channelId)o=t.channelId;else o=await we(e,s,t.cookie);let i=await Ne(e,o,r,1,t.cookie),c=G(i.messages).map(L).find((S)=>String(S.ts)===r);if(!c)console.error(`Message not found at ts=${r} in channel ${o}`),process.exit(1);let d=typeof c.text==="string"?c.text:"",f=t.newText;if(t.tick){let S=oh(d,t.tick.n);if(S.kind==="already")console.log(`already ticked (${S.n}.)`),process.exit(0);if(S.kind==="none")console.error("Error: the message has no \u2B1C <n>. item"),process.exit(2);if(S.kind==="missing")console.error(`Error: the message has no \u2B1C ${S.n}. item`),process.exit(2);if(S.kind==="ambiguous")console.error(`Error: several open items (${S.open.join(", ")}): name one, e.g. slack tick <target> ${S.open[0]}`),process.exit(2);f=S.text}else f=ih(d,f,t.lanePrefix);let p=t.mentionCookie??t.cookie,g=t.mentions&&!t.tick?await fm(t.mentionToken??e,f,o,p?{cookie:p}:{}):f;He(g,t.allowUrlAdjacent);let y=Rt(d).kind,k=Rt(g).kind,w=or(d).kind!=="other",u=w?or(g).kind==="other":y!=="other"&&(k==="other"||y!=="open"&&k==="open");if(u&&!t.force)console.error(`Error: this message is ${w?"a `slack poll`":`a \`slack ask\` question (${y==="open"?"open":y==="resolved"?"answered":"void"})`}, and ${w||k==="other"?"the new text would no longer read back as one (collect could not find the question, the pills or the answer)":"the new text would turn it back into an OPEN question"}.
489
+ `+(w?" Edit it anyway with --force.":` To retire it: slack ask --void='${t.target}' --reason '\u2026'
490
+ Edit it anyway with --force.`)),process.exit(1);let l=u,h=await n(),m=l?De("force-edit-ask-poll",d,g,h?.userId??""):De(d,g,h?.userId??"");if(t.code!==m)Se(t.code,m,[...l?[`\u26A0 --force: rewriting a \`slack ${w?"poll":"ask"}\` message by hand \u2014 collect may no longer read it back`]:[],"--- Editing as -------------------------------",Ee(h,{asBot:t.asBot}),"--- Original message -------------------------",...d.split(`
491
+ `).map((S)=>` ${S}`),"--- Replacing with ---------------------------",...g.split(`
492
+ `).map((S)=>` ${S}`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);let b=Vn("edit"),_=y!=="other"||k!=="other"||w||or(g).kind!=="other",x=await zt(e,o,r,g,t.cookie,_?!0:void 0,b.metadata);console.log(`\u2713 Edited (ts: ${x})`),b.record({team:h?.team,channel:o,target:t.target,ts:r,text:g,asBot:t.asBot})}async function cS(e,t){let n=Vt(e,t.cookie),{ref:s,ts:r}=Xt(t.target);if(!r)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 o;if(t.channelId)o=t.channelId;else o=await we(e,s,t.cookie);let i=await Ne(e,o,r,1,t.cookie),c=G(i.messages).map(L).find((g)=>String(g.ts)===r);if(!c)console.error(`Message not found at ts=${r} in channel ${o}`),process.exit(1);let d=typeof c.text==="string"?c.text:"",f=await n(),p=De(o,r,d,f?.userId??"");if(t.code!==p){let g=await Bt(e,o,s,t.cookie);Se(t.code,p,["--- Deleting message -------------------------",Ee(f,{asBot:t.asBot}),` \u2192 ${g} at ${ii(r)}`,...d.split(`
493
+ `).map((y)=>` ${y}`),"---------------------------------------------"])}await Cg(e,o,r,t.cookie),console.log(`\u2713 Deleted (ts: ${r})`)}function bn(e){return`'${e.replace(/'/g,"'\\''")}'`}async function jl(e,t,n){let s=ei(t);if(s)return{...s,ref:s.channel};let{ref:r,ts:o}=Xt(t);if(!o)console.error(`Error: ${W(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 ${bn(t)}`),process.exit(2);return{channel:await we(e,r,n),ts:o,ref:r}}async function lS(e,t,n,s){let r=L(await Ne(e,t,n,1,s)),o=G(r.messages).map(L).find((i)=>String(i.ts)===n);if(!o)console.error(`Error: no message at ts=${n} in ${t}.`),process.exit(1);return o}function si(e,t){if(t!==void 0)try{return Ll(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:Ue(e)}var Pm=40000;function li(e,t){if(t.length>Pm)console.error(`Error: the ${e} is ${t.length} characters; Slack truncates past ${Pm}. Shorten it \u2014 move detail to a linked page.`),process.exit(2)}function ui(e){let n=(e instanceof Error?e.message:String(e)).match(/Slack error on \S+: (\w+)/);if(e instanceof it)return!0;return!!n&&!["internal_error","fatal_error","request_timeout","service_unavailable"].includes(n[1])}function Qm(e,t){let n=Sl(e);return n&&n.includes("QUIET HOURS")?`\u26A0 Quiet hours (JST): ${t}.`:null}async function uS(e,t){let{ref:n,ts:s}=Xt(t.target);if(s||ei(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 ${bn(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(He(t.state,t.allowUrlAdjacent),t.log!==void 0)He(t.log,t.allowUrlAdjacent),li("reason",t.log);let r=`${t.workspace?` -w ${bn(t.workspace)}`:""}${t.asBot?" --as-bot":""}`,o=Vt(e,t.cookie),i=await we(e,n,t.cookie),a=await o(),c=De("pinlog-create",i,t.state,t.log??"",a?.userId??""),d=new Date,f=$l(t.state,d);if(li("HEAD (state + footer)",f),t.code!==c){let w=await Bt(e,i,n,t.cookie),u=(await ey(e,i,200,t.cookie)).found;Se(t.code,c,["--- New pinlog -------------------------------",Ee(a,{asBot:t.asBot}),` \u2192 ${w} \u2014 NEW top-level message, then pinned`,...u.length?[`\u26A0 ${u.length} board(s) already in this channel \u2014 to change one, use \`slack pinlog set <board> \u2026\` instead:`,...u.slice(0,5).map((l)=>` ${gt(i,String(l.ts))} ${ty(String(l.text))}`)]:[" (no other boards in the last 200 messages of this channel)"],"--- State (the top-level message) ------------",...f.split(`
494
+ `).map((l)=>` ${W(l)}`),...t.log?["--- Reason (first thread reply \u2014 notifies) ---",...t.log.split(`
495
+ `).map((l)=>` ${W(l)}`)]:[],"---------------------------------------------"])}let p=Vn("send"),g;try{g=await Ht(e,i,f,void 0,!1,t.cookie,!0,p.metadata)}catch(w){if(ui(w))console.error(`\u2717 HEAD was NOT posted: ${ge(w)}`);else console.error(`\u26A0 UNKNOWN whether the HEAD was posted: ${ge(w)}
496
+ Check before retrying, or you will have two boards: slack pinlog ls ${bn(t.target)}${r}`);process.exit(1)}if(!g)console.error("\u2717 Slack accepted the post but returned no ts \u2014 check the channel before retrying, it may have landed."),process.exit(1);p.record({team:a?.team,channel:i,target:t.target,ts:g,text:f,asBot:t.asBot});let y=gt(i,g);console.log(`\u2713 Posted HEAD: ${y}`);let k=Qm(d,"this new top-level post notified everyone who follows the channel");if(k)console.error(k);try{await nl(e,i,g,t.cookie),console.log("\u2713 Pinned")}catch(w){let u=w instanceof Error?w.message:String(w),l=/missing_scope/.test(u)?`the ${t.asBot?"bot":"user"} token lacks the pins:write scope`:ge(w);console.error(`\u26A0 NOT pinned: ${l}.`),console.error(` The board works unpinned; pin it later with: slack pinlog pin ${y}${r}`)}if(t.log)try{let w=await Ht(e,i,t.log,g,!1,t.cookie,!0);console.log(`\u2713 Reason posted in the thread (ts: ${w})`)}catch(w){let u=De("pinlog-log",i,g,t.log,a?.userId??"");console.error(`${ui(w)?"\u2717 The reason was NOT posted":"\u26A0 UNKNOWN whether the reason was posted"}: ${ge(w)}
495
497
  The board IS posted. Retry just the reason (check the thread first):
496
- slack pinlog note ${p} ${mn(hs(t.log))}${t.allowUrlAdjacent?" --allow-url-adjacent":""}${r} --code=${y}`),process.exit(1)}}async function cm(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(qe(t.log,t.allowUrlAdjacent),t.state!==void 0)qe(t.state,t.allowUrlAdjacent);Zo("log line",t.log);let n=Gt(e,t.cookie),{channel:s,ts:r,ref:o}=await Sl(e,t.target,t.cookie);try{em(`pinlog-${s}-${r}`)}catch(m){if(!(m instanceof lr))throw m;console.error(`Error: another update of ${ht(s,r)} is running (${m.holder}). Re-run when it has finished \u2014 then re-read the board, it has changed.`),process.exit(1)}let i=await _x(e,s,r,t.cookie),l=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(!ws(l)&&!t.adopt)console.error(`Error: the message at ${ht(s,r)} is not a pinlog HEAD (no "${ur}" footer).
497
- `+" Refusing to overwrite it \u2014 check the id. To turn this message into a board on purpose, add --adopt."),process.exit(1);let u=await n(),f=ht(s,r),a=new Date,c=`${t.workspace?` -w ${mn(t.workspace)}`:""}${t.asBot?" --as-bot":""}`,d=De("pinlog-log",s,r,t.log,u?.userId??""),p=`slack pinlog note ${f} ${mn(hs(t.log))}${t.allowUrlAdjacent?" --allow-url-adjacent":""}${c} --code=${d}`,h=$m(a,"the log reply notified everyone following this thread \u2014 hold non-urgent updates until 08:00");if(t.logOnly){if(t.code!==d){let m=await zt(e,s,o,t.cookie);Se(t.code,d,["--- Pinlog log reply (HEAD unchanged) --------",Ee(u,{asBot:t.asBot}),` \u2192 ${m}, thread of ${f}`,...t.log.split(`
498
- `).map((w)=>` ${M(w)}`),"---------------------------------------------"])}}else{let m=ul(t.state,a);Zo("new HEAD (state + footer)",m);let w=!ws(l),k=De("pinlog-update",s,r,l,t.state,t.log,u?.userId??"");if(t.code!==k){let E=await zt(e,s,o,t.cookie),S=dr(l).trim()===dr(t.state).trim();Se(t.code,k,["--- Updating pinlog --------------------------",Ee(u,{asBot:t.asBot}),` \u2192 ${E}, ${f}`,"--- Current HEAD -----------------------------",...l.split(`
499
- `).map((x)=>` ${M(x)}`),"--- New HEAD (edited in place \u2014 silent) ------",...m.split(`
500
- `).map((x)=>` ${M(x)}`),"--- Log reply (in the thread \u2014 notifies) -----",...t.log.split(`
501
- `).map((x)=>` ${M(x)}`),"---------------------------------------------",...S?["\u26A0 The state text is unchanged \u2014 only the footer time moves. Replies are for real changes."]:[],...w?["\u26A0 Adopting: this message has no pinlog footer yet \u2014 it becomes a board now."]:[]])}let _=Hn("edit");try{await Kt(e,s,r,m,t.cookie,!0,_.metadata)}catch(E){let S=E instanceof Error?E.message:String(E),x=/cant_update_message/.test(S)?`
502
- Only the HEAD's author can edit it${t.asBot?"":" \u2014 if the bot created this board, add --as-bot"}.`:"",F=Qo(E)?`\u2717 HEAD was NOT updated: ${ge(E)}${x}`:`\u26A0 UNKNOWN whether the HEAD was updated: ${ge(E)}
503
- Check it first: slack pinlog get ${f}${c}`;console.error(`${F}
504
- The log reply was NOT posted (a log line for a change the board may not show would be a lie).`),process.exit(1)}_.record({team:u?.team,channel:s,target:t.target,ts:r,text:m,asBot:t.asBot});let D;try{if(D=G(O(await Le(e,s,r,1,t.cookie)).messages).map(O).find((S)=>S.ts===r),!D)console.error("\u26A0 HEAD updated, but the read-back did not return it, so it was not checked")}catch(E){console.error(`\u26A0 HEAD updated, but it could not be read back to check: ${ge(E)}`)}if(D&&!qp(m,D)){let E=hc(D.blocks);console.error(`\u2717 HEAD was edited, but Slack does not show what was sent (${Hp(Gs(m,E),Gs(typeof D.text==="string"?D.text:"",E))}).
505
- The log reply was NOT posted. Check it: slack pinlog get ${f}${c}`),process.exit(3)}console.log(`\u2713 HEAD updated${D?" (read back: matches)":""}: ${f}`)}let g=Hn("send"),y;try{y=await Jt(e,s,t.log,r,!1,t.cookie,!0,g.metadata)}catch(m){let w=Qo(m);console.error((w?`\u2717 Log reply was NOT posted: ${ge(m)}
506
- `:`\u26A0 UNKNOWN whether the log reply was posted: ${ge(m)}
507
- `)+(t.logOnly?"":` The HEAD IS updated \u2014 only the log line ${w?"is":"may be"} missing.
508
- `)+(w?"":` Check the thread first (retrying a reply that landed notifies everyone twice): slack pinlog get ${f}${c}
509
- `)+` Retry just the log line${w?"":" (only if it is not there)"}:
510
- ${p}`),process.exit(1)}if(g.record({team:u?.team,channel:s,target:t.target,ts:y,text:t.log,asBot:t.asBot}),console.log(`\u2713 Logged (ts: ${y})`),h)console.error(h)}function lm(e){return e.replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&")}function $x(e){return cl(new Date(Number(e.split(".")[0])*1000))}async function Cx(e,t,n,s){if(typeof t.user==="string"){let o=n.get(t.user);if(o!==void 0)return o;let i;try{i=await Re(e,t.user,s)}catch{i=t.user}return n.set(t.user,i),i}let r=O(t.bot_profile);if(typeof r.name==="string")return r.name;return typeof t.username==="string"?t.username:"bot"}async function Ax(e,t,n,s){let{channel:r,ts:o}=await Sl(e,t,n),i=[],l,u=0;do{let g=O(await eg(e,r,o,l,200,n));for(let m of G(g.messages).map(O)){if(String(m.ts)===o&&i.some((w)=>String(w.ts)===o))continue;i.push(m)}let y=O(g.response_metadata).next_cursor;l=typeof y==="string"&&y?y:void 0,u++}while(l&&u<50);let f=l===void 0,a=i.find((g)=>String(g.ts)===o);if(!a)console.error(`Error: no message at ts=${o} in ${r}.`),process.exit(1);let c=typeof a.text==="string"?a.text:"",d=i.filter((g)=>String(g.ts)!==o);if(s){console.log(JSON.stringify({id:ht(r,o),isPinlog:ws(c),updated:dl(c),complete:f,head:c,log:d.map((g)=>({ts:String(g.ts),user:g.user??null,text:typeof g.text==="string"?g.text:""}))}));return}if(!ws(c))console.error(`\u26A0 ${ht(r,o)} has no "${ur}" footer \u2014 showing it anyway, but it is not a pinlog HEAD.`);console.log(`=== HEAD ${ht(r,o)} ===`);for(let g of lm(c).split(`
511
- `))console.log(M(g));let p=f?"":" \u2014 INCOMPLETE: the newest entries are not shown";console.log(`=== log (${d.length}${p}) ===`);let h=new Map;for(let g of d){let y=typeof g.text==="string"?g.text:"",m=M(await Cx(e,g,h,n)),w=lm(y).split(`
512
- `).map((k)=>M(k));console.log(`${$x(String(g.ts))} @${m}: ${w[0]??""}`);for(let k of w.slice(1))console.log(` ${k}`)}}async function Cm(e,t,n,s){let r=0,o,i=[];do{let l=O(await it(e,t,Math.min(200,n-r),void 0,o,s)),u=G(l.messages).map(O);r+=u.length;for(let a of u)if(typeof a.text==="string"&&ws(a.text))i.push(a);let f=O(l.response_metadata).next_cursor;o=typeof f==="string"&&f?f:void 0}while(o&&r<n);return{found:i,scanned:r}}function Am(e){return M(dr(e).split(`
513
- `).find((t)=>t.trim())??"").slice(0,80)}async function Tx(e,t,n,s){let{ref:r,ts:o}=Yt(t);if(o||Uo(t))console.error(`Error: \`pinlog ls\` takes a channel. For one board: slack pinlog get ${mn(t)}`),process.exit(2);let i=await we(e,r,s),{found:l,scanned:u}=await Cm(e,i,n,s),f=await zt(e,i,r,s);if(l.length===0){console.log(`No pinlogs in the last ${u} messages of ${f}.${u>=n?` (Older ones: --limit ${n*2})`:""}`);return}for(let a of l){let c=String(a.ts),d=ht(i,c),p=String(a.text),h=G(a.pinned_to).some((m)=>m===i)?"\uD83D\uDCCC":" ",g=Am(p),y=typeof a.reply_count==="number"?a.reply_count:0;console.log(`${h} ${d} updated ${dl(p)??"?"} log ${y}`),console.log(` ${g}`)}}async function Fx(e,t,n){let{channel:s,ts:r}=await Sl(e,t,n);try{await jc(e,s,r,n),console.log(`\u2713 Pinned ${ht(s,r)}`)}catch(o){let i=o instanceof Error?o.message:String(o);if(/already_pinned/.test(i)){console.log(`\u2713 Already pinned: ${ht(s,r)}`);return}console.error(`\u2717 NOT pinned: ${ge(o)}`),process.exit(1)}}async function Ox(e,t){let{ref:n,ts:s}=Yt(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=t.emoji.replace(/^:|:$/g,""),o;if(t.channelId)o=t.channelId;else o=await we(e,n,t.cookie);if(t.remove)await qt(e,o,s,r,t.cookie),console.log(`\u2713 Removed :${r}: (ts: ${s})`);else await It(e,o,s,r,t.cookie),console.log(`\u2713 Reacted :${r}: (ts: ${s})`)}async function _l(e,t,n,s){if(!n||!t.startsWith("D"))return!1;try{let r=O(await Wn(e,t,s)),o=O(r.channel);return o.is_im===!0&&o.user===n}catch{return!1}}function Rx(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 s of G(n.reply_users))if(typeof s==="string")t.add(s)}return t}async function Ix(e,t,n){if(!t.startsWith("D"))return;try{let s=O(O(await Wn(e,t,n)).channel);return s.is_im===!0&&typeof s.user==="string"?s.user:void 0}catch{return}}async function vx(e,t){let{ref:n,threadTs:s}=$t(t.target),r=t.cookie;if(!t.code&&zp(t.message))console.error(Yp(t.target));let o=Gt(e,r),i;if(t.channelId)i=t.channelId;else if(t.userId)i=await Ht(e,t.userId,r);else i=await we(e,n,r);if(!t.asBot&&await _l(e,i,(await o())?.userId,r))console.error(`Warning: "${t.target}" is a DM to yourself \u2014 Slack will NOT notify you of your own message.
514
- `+` To reach yourself with a notification, send as the bot: slack send '${t.target}' '...' --as-bot`);let l=We(t.message);qe(l,t.allowUrlAdjacent);let u=l,f=null;if(t.mentions){f=await hn(t.mentionToken??e,l,i,t.mentionCookie),u=f.text;for(let S of jo(f.unresolved))console.error(`\u26A0 ${M(S)}`)}let a=[];if(f&&(f.resolved.length>0||f.unresolved.length>0)){a.push("--- Mentions ---------------------------------");for(let S of f.resolved)a.push(` \u2713 ${M(S.surface)} \u2192 @${M(S.display)} (${S.userId}) \u2014 will notify`);for(let S of f.unresolved){let x=S.reason==="ambiguous"?"ambiguous":S.reason==="unavailable"?"lookup unavailable":"no match";a.push(` \u26A0 ${M(S.surface)} \u2014 plain text, NOT notified (${x})`)}}let c="",d="?",p=[],h,g,y;if(s)try{let S=await Le(e,i,s,100,r);p=G(S.messages).map(O);let x=p[p.length-1];c=typeof x?.text==="string"?x.text:"",h=typeof x?.user==="string"?x.user:void 0,g=typeof x?.bot_id==="string"?x.bot_id:void 0,y=typeof x?.ts==="string"?x.ts:void 0}catch{}else try{let S=await it(e,i,1,void 0,void 0,r),x=G(S.messages).map(O),F=x.filter((I)=>I.subtype===void 0||I.subtype===null)[0];c=typeof F?.text==="string"?F.text:"",d=typeof F?.user==="string"?await Re(e,F.user,r):typeof F?.username==="string"?F.username:"?";let R=x[0];h=typeof R?.user==="string"?R.user:void 0,g=typeof R?.bot_id==="string"?R.bot_id:void 0,y=typeof R?.ts==="string"?R.ts:void 0}catch{}try{let S=s?Rx(p):new Set([await Ix(e,i,r)].filter((x)=>!!x));for(let x of await Wg(t.mentionToken??e,u,t.mentionCookie)){if(S.has(x.userId))continue;console.error(`\u26A0 possible untagged mention: ${M(x.surface)} \u2014 @${M(x.display)} won't be notified (did you mean <@${x.userId}>?)`)}}catch{}if(process.env.SLACK_UNREPLIED_WARN!=="0"&&y&&(h||g))try{let S=await o();if(!!S&&(!!h&&!!S.userId&&S.userId===h||!!g&&!!S.botId&&S.botId===g)){let F=`slack edit "#${i}:${y}" "<new text>" --channel-id ${i}`;try{let R=await jn(e,i,y,r);if(R)F=`slack edit "${R}" "<new text>"`}catch{}console.error("\u26A0 They haven't replied yet (the last message is yours)."),console.error(" To avoid a string of messages, consider editing your last message instead of sending a new one:"),console.error(` ${F}`),console.error(" To send anyway, confirm with --code=XXXX.")}}catch{}if(s&&p.length){let S={sim:0,msg:null};for(let x of p){let F=typeof x.text==="string"?x.text:"";if(!F)continue;let R=Dx(u,F);if(R>S.sim)S={sim:R,msg:x}}if(S.msg&&S.sim>=0.82){let x=Math.round(S.sim*100);console.error(`\u26A0 possible duplicate: ${x}% similar to an existing thread message \u2014 ${await yl(e,S.msg,60,r)}`)}}let m=await o(),w=await ri(e,i,r),k=De(i,s??"",c,u,m?.userId??"");if(t.code!==k){let S=await zt(e,i,n,r),x=Ee(m,{asBot:t.asBot});if(s){let F=await kx(e,s,p,r),R=p.slice(-3),I=R.length?await Promise.all(R.map(async(P)=>` ${await yl(e,P,60,r)}`)):[" (thread context unavailable)"];Se(t.code,k,["--- Recent messages in thread ----------------",...I,...a,"--- Sending ----------------------------------",x,` \u2192 ${S} thread of ${F} \u2014 THREAD REPLY`,` Message: ${u}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"],w)}else Se(t.code,k,["--- Last message in channel ------------------",` ${d}: ${ys(c.split(`
515
- `)[0]??"").slice(0,100)}`,...a,"--- Sending ----------------------------------",x,` \u2192 ${S} \u2014 NEW top-level message`,` Message: ${u}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"],w)}let _=Hn("send"),D=await Jt(e,i,u,s,t.broadcast,r,void 0,_.metadata),E="";try{E=await jn(e,i,D,r)}catch{}if(_.record({team:(await o())?.team,channel:i,target:t.target,ts:D,threadTs:s,permalink:E,text:u,asBot:t.asBot}),t.json)console.log(JSON.stringify({ok:!0,channel:i,ts:D,...s?{thread_ts:s}:{},...E?{permalink:E}:{}}));else if(E)console.log(`\u2713 Sent: ${E}`);else console.log(`\u2713 Sent (ts: ${D})`);if(t.asBot&&i.startsWith("D"))try{let S=await Yr(e);if(!S.ok)for(let x of Gr(S,!0))console.error(x);else{let x=S.appId?`https://api.slack.com/apps/${S.appId}`:"https://api.slack.com/apps";console.error(`Note: if ${t.target} can't reply (app messaging may be off), enable Messages Tab: ${x} \u2192 App Home.`)}}catch{}}var Px=2,oe=3,Lx=4,Nx=5,ei=6,Mx=7,Bx=10;function jx(){return/^(1|true|yes|on)$/i.test(is("ASK_EXPLAIN")??"")}var um=8,Wx=(e)=>new Promise((t)=>setTimeout(t,e));function pl(e){return e==="-"||e===""&&process.argv.slice(2).includes("-")}async function hl(){return(await Bun.stdin.text()).replace(/\s+$/,"")}var Tm=new Set(["thread_broadcast"]),Ux=/(?<![A-Za-z0-9._@<-])@(here|channel|everyone)(?![A-Za-z0-9._-])/giu;function Fm(e){if(!e.length)return;let t=e.map((n)=>{let s=M(n.surface);if(n.reason==="unavailable")return`${s}: could not fetch the user list or channel members (users:read missing or an API/connection error)`;if(n.reason==="ambiguous")return`${s}: matches multiple people \u2014 use an explicit <@USERID> tag`;return`${s}: matched no one`});console.error(`Error: \`ask\` will not post with unresolved answerer tags.
498
+ slack pinlog note ${y} ${bn(ks(t.log))}${t.allowUrlAdjacent?" --allow-url-adjacent":""}${r} --code=${u}`),process.exit(1)}}async function Lm(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(He(t.log,t.allowUrlAdjacent),t.state!==void 0)He(t.state,t.allowUrlAdjacent);li("log line",t.log);let n=Vt(e,t.cookie),{channel:s,ts:r,ref:o}=await jl(e,t.target,t.cookie);try{Am(`pinlog-${s}-${r}`)}catch(l){if(!(l instanceof gr))throw l;console.error(`Error: another update of ${gt(s,r)} is running (${l.holder}). Re-run when it has finished \u2014 then re-read the board, it has changed.`),process.exit(1)}let i=await lS(e,s,r,t.cookie),a=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(!Es(a)&&!t.adopt)console.error(`Error: the message at ${gt(s,r)} is not a pinlog HEAD (no "${mr}" footer).
499
+ `+" Refusing to overwrite it \u2014 check the id. To turn this message into a board on purpose, add --adopt."),process.exit(1);let c=await n(),d=gt(s,r),f=new Date,p=`${t.workspace?` -w ${bn(t.workspace)}`:""}${t.asBot?" --as-bot":""}`,g=De("pinlog-log",s,r,t.log,c?.userId??""),y=`slack pinlog note ${d} ${bn(ks(t.log))}${t.allowUrlAdjacent?" --allow-url-adjacent":""}${p} --code=${g}`,k=Qm(f,"the log reply notified everyone following this thread \u2014 hold non-urgent updates until 08:00");if(t.logOnly){if(t.code!==g){let l=await Bt(e,s,o,t.cookie);Se(t.code,g,["--- Pinlog log reply (HEAD unchanged) --------",Ee(c,{asBot:t.asBot}),` \u2192 ${l}, thread of ${d}`,...t.log.split(`
500
+ `).map((h)=>` ${W(h)}`),"---------------------------------------------"])}}else{let l=$l(t.state,f);li("new HEAD (state + footer)",l);let h=!Es(a),m=De("pinlog-update",s,r,a,t.state,t.log,c?.userId??"");if(t.code!==m){let x=await Bt(e,s,o,t.cookie),S=yr(a).trim()===yr(t.state).trim();Se(t.code,m,["--- Updating pinlog --------------------------",Ee(c,{asBot:t.asBot}),` \u2192 ${x}, ${d}`,"--- Current HEAD -----------------------------",...a.split(`
501
+ `).map((E)=>` ${W(E)}`),"--- New HEAD (edited in place \u2014 silent) ------",...l.split(`
502
+ `).map((E)=>` ${W(E)}`),"--- Log reply (in the thread \u2014 notifies) -----",...t.log.split(`
503
+ `).map((E)=>` ${W(E)}`),"---------------------------------------------",...S?["\u26A0 The state text is unchanged \u2014 only the footer time moves. Replies are for real changes."]:[],...h?["\u26A0 Adopting: this message has no pinlog footer yet \u2014 it becomes a board now."]:[]])}let b=Vn("edit");try{await zt(e,s,r,l,t.cookie,!0,b.metadata)}catch(x){let S=x instanceof Error?x.message:String(x),E=/cant_update_message/.test(S)?`
504
+ Only the HEAD's author can edit it${t.asBot?"":" \u2014 if the bot created this board, add --as-bot"}.`:"",I=ui(x)?`\u2717 HEAD was NOT updated: ${ge(x)}${E}`:`\u26A0 UNKNOWN whether the HEAD was updated: ${ge(x)}
505
+ Check it first: slack pinlog get ${d}${p}`;console.error(`${I}
506
+ The log reply was NOT posted (a log line for a change the board may not show would be a lie).`),process.exit(1)}b.record({team:c?.team,channel:s,target:t.target,ts:r,text:l,asBot:t.asBot});let _;try{if(_=G(L(await Ne(e,s,r,1,t.cookie)).messages).map(L).find((S)=>S.ts===r),!_)console.error("\u26A0 HEAD updated, but the read-back did not return it, so it was not checked")}catch(x){console.error(`\u26A0 HEAD updated, but it could not be read back to check: ${ge(x)}`)}if(_&&!gh(l,_)){let x=Ac(_.blocks);console.error(`\u2717 HEAD was edited, but Slack does not show what was sent (${mh(tr(l,x),tr(typeof _.text==="string"?_.text:"",x))}).
507
+ The log reply was NOT posted. Check it: slack pinlog get ${d}${p}`),process.exit(3)}console.log(`\u2713 HEAD updated${_?" (read back: matches)":""}: ${d}`)}let w=Vn("send"),u;try{u=await Ht(e,s,t.log,r,!1,t.cookie,!0,w.metadata)}catch(l){let h=ui(l);console.error((h?`\u2717 Log reply was NOT posted: ${ge(l)}
508
+ `:`\u26A0 UNKNOWN whether the log reply was posted: ${ge(l)}
509
+ `)+(t.logOnly?"":` The HEAD IS updated \u2014 only the log line ${h?"is":"may be"} missing.
510
+ `)+(h?"":` Check the thread first (retrying a reply that landed notifies everyone twice): slack pinlog get ${d}${p}
511
+ `)+` Retry just the log line${h?"":" (only if it is not there)"}:
512
+ ${y}`),process.exit(1)}if(w.record({team:c?.team,channel:s,target:t.target,ts:u,text:t.log,asBot:t.asBot}),console.log(`\u2713 Logged (ts: ${u})`),k)console.error(k)}function Nm(e){return e.replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&")}function dS(e){return _l(new Date(Number(e.split(".")[0])*1000))}async function fS(e,t,n,s){if(typeof t.user==="string"){let o=n.get(t.user);if(o!==void 0)return o;let i;try{i=await ve(e,t.user,s)}catch{i=t.user}return n.set(t.user,i),i}let r=L(t.bot_profile);if(typeof r.name==="string")return r.name;return typeof t.username==="string"?t.username:"bot"}async function pS(e,t,n,s){let{channel:r,ts:o}=await jl(e,t,n),i=[],a,c=0;do{let w=L(await Ag(e,r,o,a,200,n));for(let l of G(w.messages).map(L)){if(String(l.ts)===o&&i.some((h)=>String(h.ts)===o))continue;i.push(l)}let u=L(w.response_metadata).next_cursor;a=typeof u==="string"&&u?u:void 0,c++}while(a&&c<50);let d=a===void 0,f=i.find((w)=>String(w.ts)===o);if(!f)console.error(`Error: no message at ts=${o} in ${r}.`),process.exit(1);let p=typeof f.text==="string"?f.text:"",g=i.filter((w)=>String(w.ts)!==o);if(s){console.log(JSON.stringify({id:gt(r,o),isPinlog:Es(p),updated:Cl(p),complete:d,head:p,log:g.map((w)=>({ts:String(w.ts),user:w.user??null,text:typeof w.text==="string"?w.text:""}))}));return}if(!Es(p))console.error(`\u26A0 ${gt(r,o)} has no "${mr}" footer \u2014 showing it anyway, but it is not a pinlog HEAD.`);console.log(`=== HEAD ${gt(r,o)} ===`);for(let w of Nm(p).split(`
513
+ `))console.log(W(w));let y=d?"":" \u2014 INCOMPLETE: the newest entries are not shown";console.log(`=== log (${g.length}${y}) ===`);let k=new Map;for(let w of g){let u=typeof w.text==="string"?w.text:"",l=W(await fS(e,w,k,n)),h=Nm(u).split(`
514
+ `).map((m)=>W(m));console.log(`${dS(String(w.ts))} @${l}: ${h[0]??""}`);for(let m of h.slice(1))console.log(` ${m}`)}}async function ey(e,t,n,s){let r=0,o,i=[];do{let a=L(await at(e,t,Math.min(200,n-r),void 0,o,s)),c=G(a.messages).map(L);r+=c.length;for(let f of c)if(typeof f.text==="string"&&Es(f.text))i.push(f);let d=L(a.response_metadata).next_cursor;o=typeof d==="string"&&d?d:void 0}while(o&&r<n);return{found:i,scanned:r}}function ty(e){return W(yr(e).split(`
515
+ `).find((t)=>t.trim())??"").slice(0,80)}async function hS(e,t,n,s){let{ref:r,ts:o}=Xt(t);if(o||ei(t))console.error(`Error: \`pinlog ls\` takes a channel. For one board: slack pinlog get ${bn(t)}`),process.exit(2);let i=await we(e,r,s),{found:a,scanned:c}=await ey(e,i,n,s),d=await Bt(e,i,r,s);if(a.length===0){console.log(`No pinlogs in the last ${c} messages of ${d}.${c>=n?` (Older ones: --limit ${n*2})`:""}`);return}for(let f of a){let p=String(f.ts),g=gt(i,p),y=String(f.text),k=G(f.pinned_to).some((l)=>l===i)?"\uD83D\uDCCC":" ",w=ty(y),u=typeof f.reply_count==="number"?f.reply_count:0;console.log(`${k} ${g} updated ${Cl(y)??"?"} log ${u}`),console.log(` ${w}`)}}async function gS(e,t,n){let{channel:s,ts:r}=await jl(e,t,n);try{await nl(e,s,r,n),console.log(`\u2713 Pinned ${gt(s,r)}`)}catch(o){let i=o instanceof Error?o.message:String(o);if(/already_pinned/.test(i)){console.log(`\u2713 Already pinned: ${gt(s,r)}`);return}console.error(`\u2717 NOT pinned: ${ge(o)}`),process.exit(1)}}async function mS(e,t){let{ref:n,ts:s}=Xt(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=t.emoji.replace(/^:|:$/g,""),o;if(t.channelId)o=t.channelId;else o=await we(e,n,t.cookie);if(t.remove)await Yt(e,o,s,r,t.cookie),console.log(`\u2713 Removed :${r}: (ts: ${s})`);else await Lt(e,o,s,r,t.cookie),console.log(`\u2713 Reacted :${r}: (ts: ${s})`)}async function Wl(e,t,n,s){if(!n||!t.startsWith("D"))return!1;try{let r=L(await Hn(e,t,s)),o=L(r.channel);return o.is_im===!0&&o.user===n}catch{return!1}}function yS(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 s of G(n.reply_users))if(typeof s==="string")t.add(s)}return t}async function bS(e,t,n){if(!t.startsWith("D"))return;try{let s=L(L(await Hn(e,t,n)).channel);return s.is_im===!0&&typeof s.user==="string"?s.user:void 0}catch{return}}async function wS(e,t){let{ref:n,threadTs:s}=At(t.target),r=t.cookie;if(!t.code&&yh(t.message))console.error(bh(t.target));let o=Vt(e,r),i=o(),a;if(t.channelId)a=t.channelId;else if(t.userId)a=await Gt(e,t.userId,r);else a=await we(e,n,r);let c=gi(e,a,r),d=t.code===void 0?Bt(e,a,n,r):void 0,f=(s?Ne(e,a,s,100,r):at(e,a,1,void 0,void 0,r)).catch(()=>null);if(!t.asBot&&await Wl(e,a,(await i)?.userId,r))console.error(`Warning: "${t.target}" is a DM to yourself \u2014 Slack will NOT notify you of your own message.
516
+ `+` To reach yourself with a notification, send as the bot: slack send '${t.target}' '...' --as-bot`);let p=Ue(t.message);He(p,t.allowUrlAdjacent);let g=p,y=null;if(t.mentions){y=await mn(t.mentionToken??e,p,a,t.mentionCookie),g=y.text;for(let C of Zo(y.unresolved))console.error(`\u26A0 ${W(C)}`)}let k=[];if(y&&(y.resolved.length>0||y.unresolved.length>0)){k.push("--- Mentions ---------------------------------");for(let C of y.resolved)k.push(` \u2713 ${W(C.surface)} \u2192 @${W(C.display)} (${C.userId}) \u2014 will notify`);for(let C of y.unresolved){let A=C.reason==="ambiguous"?"ambiguous":C.reason==="unavailable"?"lookup unavailable":"no match";k.push(` \u26A0 ${W(C.surface)} \u2014 plain text, NOT notified (${A})`)}}let w="",u="?",l=[],h,m,b;if(s)try{let C=await f;l=G(C.messages).map(L);let A=l[l.length-1];w=typeof A?.text==="string"?A.text:"",h=typeof A?.user==="string"?A.user:void 0,m=typeof A?.bot_id==="string"?A.bot_id:void 0,b=typeof A?.ts==="string"?A.ts:void 0}catch{}else try{let C=await f,A=G(C.messages).map(L),F=A.filter((O)=>O.subtype===void 0||O.subtype===null)[0];w=typeof F?.text==="string"?F.text:"",u=typeof F?.user==="string"?await ve(e,F.user,r):typeof F?.username==="string"?F.username:"?";let v=A[0];h=typeof v?.user==="string"?v.user:void 0,m=typeof v?.bot_id==="string"?v.bot_id:void 0,b=typeof v?.ts==="string"?v.ts:void 0}catch{}try{let C=s?yS(l):new Set([await bS(e,a,r)].filter((A)=>!!A));for(let A of await gm(t.mentionToken??e,g,t.mentionCookie)){if(C.has(A.userId))continue;console.error(`\u26A0 possible untagged mention: ${W(A.surface)} \u2014 @${W(A.display)} won't be notified (did you mean <@${A.userId}>?)`)}}catch{}if(process.env.SLACK_UNREPLIED_WARN!=="0"&&b&&(h||m))try{let C=await o();if(!!C&&(!!h&&!!C.userId&&C.userId===h||!!m&&!!C.botId&&C.botId===m)){let F=`slack edit "#${a}:${b}" "<new text>" --channel-id ${a}`;try{let v=await qn(e,a,b,r);if(v)F=`slack edit "${v}" "<new text>"`}catch{}console.error("\u26A0 They haven't replied yet (the last message is yours)."),console.error(" To avoid a string of messages, consider editing your last message instead of sending a new one:"),console.error(` ${F}`),console.error(" To send anyway, confirm with --code=XXXX.")}}catch{}if(s&&l.length){let C={sim:0,msg:null};for(let A of l){let F=typeof A.text==="string"?A.text:"";if(!F)continue;let v=iS(g,F);if(v>C.sim)C={sim:v,msg:A}}if(C.msg&&C.sim>=0.82){let A=Math.round(C.sim*100);console.error(`\u26A0 possible duplicate: ${A}% similar to an existing thread message \u2014 ${await vl(e,C.msg,60,r)}`)}}let _=await o(),x=await c,S=De(a,s??"",w,g,_?.userId??"");if(t.code!==S){let C=await(d??Bt(e,a,n,r)),A=Ee(_,{asBot:t.asBot});if(s){let F=l.slice(-3),[v,O]=await Promise.all([oS(e,s,l,r),F.length?Promise.all(F.map(async(M)=>` ${await vl(e,M,60,r)}`)):Promise.resolve([" (thread context unavailable)"])]);Se(t.code,S,["--- Recent messages in thread ----------------",...O,...k,"--- Sending ----------------------------------",A,` \u2192 ${C} thread of ${v} \u2014 THREAD REPLY`,` Message: ${g}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"],x)}else Se(t.code,S,["--- Last message in channel ------------------",` ${u}: ${Ss(w.split(`
517
+ `)[0]??"").slice(0,100)}`,...k,"--- Sending ----------------------------------",A,` \u2192 ${C} \u2014 NEW top-level message`,` Message: ${g}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"],x)}let E=Vn("send"),I=await Ht(e,a,g,s,t.broadcast,r,void 0,E.metadata),N="";try{N=await qn(e,a,I,r)}catch{}if(E.record({team:(await o())?.team,channel:a,target:t.target,ts:I,threadTs:s,permalink:N,text:g,asBot:t.asBot}),t.json)console.log(JSON.stringify({ok:!0,channel:a,ts:I,...s?{thread_ts:s}:{},...N?{permalink:N}:{}}));else if(N)console.log(`\u2713 Sent: ${N}`);else console.log(`\u2713 Sent (ts: ${I})`);if(t.asBot&&a.startsWith("D"))try{let C=await so(e);if(!C.ok)for(let A of ro(C,!0))console.error(A);else{let A=C.appId?`https://api.slack.com/apps/${C.appId}`:"https://api.slack.com/apps";console.error(`Note: if ${t.target} can't reply (app messaging may be off), enable Messages Tab: ${A} \u2192 App Home.`)}}catch{}}var kS=2,ae=3,DS=4,xS=5,di=6,SS=7,_S=10;function ES(){return/^(1|true|yes|on)$/i.test(ln("ASK_EXPLAIN")??"")}var Mm=8,$S=(e)=>new Promise((t)=>setTimeout(t,e));function Tl(e){return e==="-"||e===""&&process.argv.slice(2).includes("-")}async function Fl(){return(await Bun.stdin.text()).replace(/\s+$/,"")}var ny=new Set(["thread_broadcast"]),CS=/(?<![A-Za-z0-9._@<-])@(here|channel|everyone)(?![A-Za-z0-9._-])/giu;function sy(e){if(!e.length)return;let t=e.map((n)=>{let s=W(n.surface);if(n.reason==="unavailable")return`${s}: could not fetch the user list or channel members (users:read missing or an API/connection error)`;if(n.reason==="ambiguous")return`${s}: matches multiple people \u2014 use an explicit <@USERID> tag`;return`${s}: matched no one`});console.error(`Error: \`ask\` will not post with unresolved answerer tags.
516
518
  ${t.join(`
517
- `)}`),process.exit(oe)}function pr(e){let t=new Set;return{text:e.replace(Ux,(s,r)=>{let o=r.toLowerCase();return t.add(o),`<!${o}>`}),kinds:t}}async function ii(e,t,n){if(!t.startsWith("D"))return;try{let s=O(await Wn(e,t,n)),r=O(s.channel);return r.is_im===!0&&typeof r.user==="string"?r.user:void 0}catch{return}}async function Om(e,t,n,s){let r=new Map;if(t.threadParentTs||t.replyCount!==0)try{let l=O(await Le(e,t.channelId,t.threadParentTs??t.ts,100,t.cookie));for(let u of G(l.messages).map(O))r.set(String(u.ts),u)}catch(l){console.error(` (could not read the thread's follow-up notes: ${l instanceof Error?l.message:String(l)})`)}if(!t.threadOnly&&!t.threadParentTs)try{let l=O(await it(e,t.channelId,30,t.ts,void 0,t.cookie,!0)),u=G(l.messages).map(O),f=u.filter((a)=>Number(a.ts)>Number(t.ts)&&(t.askerBotId&&a.bot_id===t.askerBotId||t.askerUserId&&a.user===t.askerUserId)).reduce((a,c)=>Math.min(a,Number(c.ts)),1/0);for(let a of u)if(Number(a.ts)<f&&!r.has(String(a.ts)))r.set(String(a.ts),a)}catch(l){console.error(` (could not read the DM's follow-up notes: ${l instanceof Error?l.message:String(l)})`)}let o=[...r.values()].filter((l)=>Number(l.ts)>Number(t.ts)).filter((l)=>!n||Number(l.ts)>Number(n)).filter((l)=>t.isAnswerer(l.user)&&!l.bot_id).filter((l)=>typeof l.subtype!=="string"||Tm.has(l.subtype)).filter((l)=>typeof l.text==="string"&&l.text.trim()!==""&&!mo(l.text)).sort((l,u)=>Number(l.ts)-Number(u.ts)).filter((l)=>!s(l)),i=[];for(let l of o){let u="";try{u=await jn(e,t.channelId,String(l.ts),t.cookie)}catch{}i.push({ts:String(l.ts),user:String(l.user),text:l.text.trim(),permalink:u})}return i}function Pt(...e){return e.filter((t)=>!!t).reduce((t,n)=>!t||Number(n)>Number(t)?n:t,"")}async function gn(e,t,n){if(t.json){console.log(JSON.stringify({status:n.status,answer:n.answer,how:n.how??null,who:n.who??null,...n.status==="void"?{reason:n.reason??"",supersededBy:n.supersededBy??null}:{},...n.explain?.length?{explain:n.explain}:{},notes:n.notes,cursor:n.cursor,permalink:t.shown}));return}if(n.notes.length){console.error(` ${n.notes.length} thread note(s) (separate from the answer):`);for(let s of n.notes){let r=s.user;try{r=await Re(e,s.user,t.cookie)}catch{}for(let[o,i]of s.text.split(`
518
- `).entries())console.error(` ${o?" ".repeat(M(r).length+2):`${M(r)}: `}${M(i)}`)}}if(n.status==="answered")console.error(` To pick up later notes: ${qn(t.shown,t.asBot,n.cursor)}`);if(n.answer!==null)console.log(n.answer)}function Rm(e,t,n=!1){let{channelId:s,ts:r,reactable:o,threadOnly:i,audience:l,broadcast:u,cookie:f}=t,a=je[t.lang],c={explainNow:[],explainPosted:!1},{askerUserId:d,askerBotId:p}=t,h=(N)=>typeof N==="string"&&!!N&&N!==d&&(u||l.has(N)),g=(N)=>{if(c.replyCount=Number(N.reply_count)||0,typeof N.text==="string")c.ownText=N.text},y=(N)=>{let J=typeof N.text==="string"?Ft(N.text):void 0;if(J?.kind==="void")c.voided=J;return!!c.voided};function m(N){let J=G(N.reactions).map(O),K=[];for(let B=0;B<o.length;B++){let z=J.find((j)=>j.name===Fe[B].name),Y=z?G(z.users).filter(h):[];if(Y.length)K.push({index:B,users:Y})}return K}async function w(N,J){if(n)return;let K=typeof N.text==="string"?N.text:"";if(!K)return;let B=go(K,J,t.lang);if(B===K)return;try{await Kt(e,s,r,B,f,!0)}catch(z){console.error(` (could not add the notice to the question text: ${z instanceof Error?z.message:String(z)})`)}}let k=new Set;function _(N){for(let J of G(N.reactions).map(O)){if(typeof J.name!=="string"||!pp.includes(J.name))continue;let K=J.name===Wt?"\u2795":"\u2753";for(let B of G(J.users).filter(h)){if(k.has(B))continue;if(k.add(B),!n)console.error(` (<@${B}> pressed ${K} other; waiting for their reply)`)}}}let D=new Set,E=new Map,S=!1;async function x(N){if(N==="USLACKBOT")return!0;let J=E.get(N);if(J!==void 0)return J;try{let K=O(O(await fs(e,N,f)).user).is_bot;if(typeof K!=="boolean")return null;return E.set(N,K),K}catch{return null}}async function F(){let N=t.threadParentTs??r;try{let J,K=0;for(;;){let B=O(await Nc(e,s,N,{oldest:r,...J?{cursor:J}:{}},f));if(G(B.messages).map(O).some((z)=>Number(z.ts)>Number(r)&&mo(z.text)))return"exists";if(J=String(O(B.response_metadata).next_cursor??"")||void 0,!J)break;if(++K>=Bx)return"exists"}}catch(J){return console.error(` (could not read the thread, so the explain-request note has not been posted yet: ${J instanceof Error?J.message:String(J)})`),"unread"}try{await Jt(e,s,a.explainNote,N,!1,f,!0)}catch(J){return console.error(` (could not post the explain-request note to the thread: ${J instanceof Error?J.message:String(J)})`),"failed"}return"posted"}async function R(N){let J=G(N.reactions).map(O).find((B)=>B.name===un),K=[];for(let B of J?G(J.users).filter(h):[]){if(await x(B)!==!1)continue;if(K.push(B),D.has(B))continue;if(D.add(B),!n)console.error(` (<@${B}> pressed \u2139\uFE0F explain \u2014 not an answer. Explain in the thread; still waiting for an answer)`)}if(c.explainNow=K,K.length&&!S&&!n){let B=await F();if(B!=="unread")S=!0,c.explainPosted=B==="posted"}}async function I(N){if(t.explain)await R(N);if(o.length)_(N);let J=m(N);if(J.length<=1&&ho(typeof N.text==="string"?N.text:"").length)await w(N,[]);if(!J.length)return null;if(J.length===1){let{index:j,users:ie}=J[0];return{answer:o[j],how:a.howReaction(Fe[j].glyph),who:ie[0],choice:j+1}}let K=J.map((j)=>Fe[j.index].glyph).join(" / "),B=new Map;for(let j of J)for(let ie of j.users)B.set(ie,(B.get(ie)??0)+1);let z=[...B].filter(([,j])=>j>1).map(([j])=>j);if(!n)console.error(z.length?` (${K} are pressed at once; waiting until it is narrowed to one)`:` (answers are split: ${K}; waiting until they agree on one)`);let Y=z.sort();return await w(N,Y),null}let P=[...o,...t.overflow];function L(N,J=1/0){let K=[...N].sort((B,z)=>Number(B.ts)-Number(z.ts));for(let B of K){if(!(Number(B.ts)>Number(r)))continue;if(t.after&&!(Number(B.ts)>Number(t.after)))continue;if(!h(B.user))continue;if(typeof B.subtype==="string"&&!Tm.has(B.subtype))continue;if(Number(B.ts)>=J)break;let z=typeof B.text==="string"?B.text.trim():"";if(!z||t.explain&&mo(z))continue;if(!P.length)return{answer:z,how:a.howReply,who:B.user,ts:String(B.ts)};let Y=nc(z,P);if(Y.kind==="chosen")return{answer:P[Y.index-1],how:a.howReplyN(Y.index),who:B.user,ts:String(B.ts),choice:Y.index};let j=Y.kind==="ambiguous",ie=c.unchosen;if(!ie||ie.ambiguous&&!j||ie.ambiguous===j&&Number(B.ts)<Number(ie.ts))c.unchosen={text:z,who:typeof B.user==="string"?B.user:"",ts:String(B.ts),ambiguous:j}}return null}async function W(){if(delete c.unchosen,t.threadParentTs){let B=O(await Le(e,s,t.threadParentTs,100,f)),z=G(B.messages).map(O),Y=z.find((j)=>j.ts===r);if(Y){if(g(Y),y(Y))return null;let j=await I(Y);if(j)return j}return L(z)}let N=O(await it(e,s,30,r,void 0,f,!0)),J=G(N.messages).map(O),K=J.find((B)=>B.ts===r);if(K){if(g(K),y(K))return null}if(K){let B=await I(K);if(B)return B}if(!i){let B=J.filter((Y)=>Number(Y.ts)>Number(r)&&(p&&Y.bot_id===p||d&&Y.user===d)).reduce((Y,j)=>Math.min(Y,Number(j.ts)),1/0),z=L(J,B);if(z)return z}if(K&&Number(K.reply_count)>0){let B=O(await Le(e,s,r,30,f)),z=L(G(B.messages).map(O));if(z)return z}return null}return{poll:W,state:c,isAnswerer:h,candidates:P}}async function Im(e,t){let{channelId:n,ts:s,question:r,reactable:o,threadOnly:i,cookie:l,timeout:u,shown:f}=t,{askerUserId:a,askerBotId:c}=t,{poll:d,state:p,isAnswerer:h,candidates:g}=Rm(e,t),y="";async function m(x){for(let R=0;R<o.length;R++)try{await qt(e,n,s,Fe[R].name,l)}catch{}let F="";if(x.who)try{F=await Re(e,x.who,l)}catch{F=x.who}if(F)console.error(` Answered by: ${M(F)}`);try{let R=p.ownText?bp(p.ownText,x.choice):void 0;await Kt(e,n,s,yp(r,x,F,t.lang,R),l,!0);try{await It(e,n,s,Qa,l),await qt(e,n,s,t.seedMarker,l)}catch{}try{if(t.explain)await qt(e,n,s,un,l)}catch{}}catch(R){console.error(` (failed to update the original message: ${R instanceof Error?R.message:String(R)})`)}}let w=Date.now()+u*1000,k=Date.now(),_=0,D=Ln.minMs,E=0,S;for(;;){let x=null;try{x=await d(),_=0}catch(R){if(R instanceof ot)E=R.retryAfter*1000;else{if(_++,_>=um)console.error(`Error: Slack requests failed ${_} times in a row: ${R instanceof Error?R.message:String(R)}`),process.exit(oe);console.error(` (Slack error ${_}/${um}, retrying: ${R instanceof Error?R.message:String(R)})`)}}S=p.unchosen;let F=p.voided;if(F){if(vm(F,f),t.json)await gn(e,t,{status:"void",answer:null,reason:F.reason,...F.supersededBy?{supersededBy:F.supersededBy}:{},notes:[],cursor:Pt(s,t.after)});process.exit(ei)}if(x){let R=await Om(e,{channelId:n,ts:s,threadOnly:i,replyCount:p.replyCount,isAnswerer:h,askerUserId:a,askerBotId:c,...t.threadParentTs?{threadParentTs:t.threadParentTs}:{},...l?{cookie:l}:{}},t.after,(P)=>P.ts===x.ts);await m(x);let I={status:"answered",answer:x.answer,how:x.how,notes:R,cursor:Pt(s,t.after,x.ts,...R.map((P)=>P.ts))};if(Tc(n,s,x.answer,I.cursor),x.who)I.who=x.who;await gn(e,t,I),process.exit(0)}if(p.explainPosted&&t.explainExit){if(console.error(` An explanation was requested (the question is still open). Explain in the thread, then collect with: ${qn(f,t.asBot,t.after)}`),t.json)await gn(e,t,{status:"explain",answer:null,notes:[],cursor:Pt(s,t.after),explain:p.explainNow});process.exit(Mx)}if(S&&!S.ambiguous){let R=S.who;try{if(R)R=await Re(e,R,l)}catch{}if(console.error(` (${M(R)} replied with something that is not a choice \u2014 not a decision. Printing the reply on stdout)`),console.error(` Choices: ${g.map((I,P)=>`${P+1}. ${M(Me(I))}`).join(" ")}`),console.error(` ${f}`),console.error(` To wait for what comes after this reply: ${qn(f,t.asBot,S.ts)}`),Fc(n,s,S.text,Pt(s,t.after,S.ts)),t.json)await gn(e,t,{status:"freetext",answer:S.text,who:S.who,notes:[],cursor:Pt(s,t.after,S.ts),explain:p.explainNow});else console.log(S.text);process.exit(Nx)}if(S&&S.ts!==y){y=S.ts;let R=S.who;try{if(R)R=await Re(e,R,l)}catch{}console.error(` (${M(R)}'s reply matches several choices; waiting until it is narrowed to one)`),console.error(` "${M(S.text)}"`)}if(Date.now()>=w)break;await Wx(Math.min(Math.max(D,E),Math.max(0,w-Date.now()))),E=0,D=_p(D,Date.now()-k)}if(S){if(console.error("Error: there was a reply, but it matches several choices so it cannot be settled (the message is left in place)"),console.error(` Reply: "${M(S.text)}"`),console.error(` Choices: ${g.map((x,F)=>`${F+1}. ${M(Me(x))}`).join(" ")}`),console.error(` ${f}`),console.error(` Reply in the thread, then collect with: ${qn(f,t.asBot,t.after)}`),t.json)await gn(e,t,{status:"ambiguous",answer:null,notes:[],cursor:Pt(s,t.after),explain:p.explainNow});process.exit(Lx)}if(u===0)console.error(`No answer yet: ${f}`);else console.error(`Error: no answer within ${u}s (the message is left in place)`),console.error(` ${f}`),console.error(` To collect later: ${qn(f,t.asBot,t.after)}`);if(t.json)await gn(e,t,{status:"timeout",answer:null,notes:[],cursor:Pt(s,t.after),explain:p.explainNow});process.exit(Px)}function qn(e,t,n){return`slack ask --waitFor='${e}'${t?" --as-bot":""}${n?` --after=${n}`:""}`}async function Jx(e,t){let{ref:n,threadTs:s}=$t(t.target,!1),r=t.cookie,o=Gt(e,r),i;if(t.channelId)i=t.channelId;else if(t.userId)i=await Ht(e,t.userId,r);else i=await we(e,n,r);let l=(await o())?.userId??"",u=await ii(e,i,r),f=fc();if(!t.asBot&&!!l&&u===l){if(console.error(`${f?"Error":"Warning"}: "${t.target}" is a DM to yourself \u2014 Slack will NOT notify you of your own message.
519
- `+` To reach yourself with a notification, ask as the bot: slack @<bot> ask '${t.target}' '...' (or --as-bot)`),f)process.exit(oe)}let a=pr(We(t.question)),c=pr(We(t.body??"")),d=new Set([...a.kinds,...c.kinds]);for(let te of`${a.text}
520
- ${c.text}`.matchAll(/<!(here|channel|everyone)(?:\|[^>]*)?>/g))d.add(te[1]);let p=t.mentionToken??e,h=await hn(p,a.text,i,t.mentionCookie),g=c.text?await hn(p,c.text,i,t.mentionCookie):{text:"",resolved:[],unresolved:[]},y=h.text,m=g.text,w=[...h.resolved,...g.resolved],k=[...h.unresolved,...g.unresolved];Fm(k);let _=!!l&&(w.some((te)=>te.userId===l)||new RegExp(`<@${l}(?:\\|[^>]*)?>`).test(`${y}
521
- ${m}`));if(f&&!t.asBot&&_)console.error(`Error: \`ask\` would post as you (${l}) a question addressed to you \u2014 the asker and the one asked are the same person.
519
+ `)}`),process.exit(ae)}function kr(e){let t=new Set;return{text:e.replace(CS,(s,r)=>{let o=r.toLowerCase();return t.add(o),`<!${o}>`}),kinds:t}}async function yi(e,t,n){if(!t.startsWith("D"))return;try{let s=L(await Hn(e,t,n)),r=L(s.channel);return r.is_im===!0&&typeof r.user==="string"?r.user:void 0}catch{return}}async function ry(e,t,n,s){let r=new Map;if(t.threadParentTs||t.replyCount!==0)try{let a=L(await Ne(e,t.channelId,t.threadParentTs??t.ts,100,t.cookie));for(let c of G(a.messages).map(L))r.set(String(c.ts),c)}catch(a){console.error(` (could not read the thread's follow-up notes: ${a instanceof Error?a.message:String(a)})`)}if(!t.threadOnly&&!t.threadParentTs)try{let a=L(await at(e,t.channelId,30,t.ts,void 0,t.cookie,!0)),c=G(a.messages).map(L),d=c.filter((f)=>Number(f.ts)>Number(t.ts)&&(t.askerBotId&&f.bot_id===t.askerBotId||t.askerUserId&&f.user===t.askerUserId)).reduce((f,p)=>Math.min(f,Number(p.ts)),1/0);for(let f of c)if(Number(f.ts)<d&&!r.has(String(f.ts)))r.set(String(f.ts),f)}catch(a){console.error(` (could not read the DM's follow-up notes: ${a instanceof Error?a.message:String(a)})`)}let o=[...r.values()].filter((a)=>Number(a.ts)>Number(t.ts)).filter((a)=>!n||Number(a.ts)>Number(n)).filter((a)=>t.isAnswerer(a.user)&&!a.bot_id).filter((a)=>typeof a.subtype!=="string"||ny.has(a.subtype)).filter((a)=>typeof a.text==="string"&&a.text.trim()!==""&&!$o(a.text)).sort((a,c)=>Number(a.ts)-Number(c.ts)).filter((a)=>!s(a)),i=[];for(let a of o){let c="";try{c=await qn(e,t.channelId,String(a.ts),t.cookie)}catch{}i.push({ts:String(a.ts),user:String(a.user),text:a.text.trim(),permalink:c})}return i}function Mt(...e){return e.filter((t)=>!!t).reduce((t,n)=>!t||Number(n)>Number(t)?n:t,"")}async function yn(e,t,n){if(t.json){console.log(JSON.stringify({status:n.status,answer:n.answer,how:n.how??null,who:n.who??null,...n.status==="void"?{reason:n.reason??"",supersededBy:n.supersededBy??null}:{},...n.explain?.length?{explain:n.explain}:{},notes:n.notes,cursor:n.cursor,permalink:t.shown}));return}if(n.notes.length){console.error(` ${n.notes.length} thread note(s) (separate from the answer):`);for(let s of n.notes){let r=s.user;try{r=await ve(e,s.user,t.cookie)}catch{}for(let[o,i]of s.text.split(`
520
+ `).entries())console.error(` ${o?" ".repeat(W(r).length+2):`${W(r)}: `}${W(i)}`)}}if(n.status==="answered")console.error(` To pick up later notes: ${Xn(t.shown,t.asBot,n.cursor)}`);if(n.answer!==null)console.log(n.answer)}function oy(e,t,n=!1){let{channelId:s,ts:r,reactable:o,threadOnly:i,audience:a,broadcast:c,cookie:d}=t,f=We[t.lang],p={explainNow:[],explainPosted:!1},g=t.askerUserId,y=t.askerBotId,k=(O)=>typeof O==="string"&&!!O&&O!==g&&(c||a.has(O)),w=(O)=>{if(p.replyCount=Number(O.reply_count)||0,typeof O.text==="string")p.ownText=O.text},u=(O)=>{let M=typeof O.text==="string"?Rt(O.text):void 0;if(M?.kind==="void")p.voided=M;return!!p.voided};function l(O){let M=G(O.reactions).map(L),J=[];for(let j=0;j<o.length;j++){let ee=M.find((U)=>U.name===Re[j].name),X=ee?G(ee.users).filter(k):[];if(X.length)J.push({index:j,users:X})}return J}async function h(O,M){if(n)return;let J=typeof O.text==="string"?O.text:"";if(!J)return;let j=Eo(J,M,t.lang);if(j===J)return;try{await zt(e,s,r,j,d,!0)}catch(ee){console.error(` (could not add the notice to the question text: ${ee instanceof Error?ee.message:String(ee)})`)}}let m=new Set;function b(O){for(let M of G(O.reactions).map(L)){if(typeof M.name!=="string"||!Pp.includes(M.name))continue;let J=M.name===qt?"\u2795":"\u2753";for(let j of G(M.users).filter(k)){if(m.has(j))continue;if(m.add(j),!n)console.error(` (<@${j}> pressed ${J} other; waiting for their reply)`)}}}let _=new Set,x=new Map,S=!1;async function E(O){if(O==="USLACKBOT")return!0;let M=x.get(O);if(M!==void 0)return M;try{let J=L(L(await bs(e,O,d)).user).is_bot;if(typeof J!=="boolean")return null;return x.set(O,J),J}catch{return null}}async function I(){let O=t.threadParentTs??r;try{let M,J=0;for(;;){let j=L(await Qc(e,s,O,{oldest:r,...M?{cursor:M}:{}},d));if(G(j.messages).map(L).some((ee)=>Number(ee.ts)>Number(r)&&$o(ee.text)))return"exists";if(M=String(L(j.response_metadata).next_cursor??"")||void 0,!M)break;if(++J>=_S)return"exists"}}catch(M){return console.error(` (could not read the thread, so the explain-request note has not been posted yet: ${M instanceof Error?M.message:String(M)})`),"unread"}try{await Ht(e,s,f.explainNote,O,!1,d,!0)}catch(M){return console.error(` (could not post the explain-request note to the thread: ${M instanceof Error?M.message:String(M)})`),"failed"}return"posted"}async function N(O){let M=G(O.reactions).map(L).find((j)=>j.name===fn),J=[];for(let j of M?G(M.users).filter(k):[]){if(await E(j)!==!1)continue;if(J.push(j),_.has(j))continue;if(_.add(j),!n)console.error(` (<@${j}> pressed \u2139\uFE0F explain \u2014 not an answer. Explain in the thread; still waiting for an answer)`)}if(p.explainNow=J,J.length&&!S&&!n){let j=await I();if(j!=="unread")S=!0,p.explainPosted=j==="posted"}}async function C(O){if(t.explain)await N(O);if(o.length)b(O);let M=l(O);if(M.length<=1&&_o(typeof O.text==="string"?O.text:"").length)await h(O,[]);if(!M.length)return null;if(M.length===1){let{index:U,users:ie}=M[0];return{answer:o[U],how:f.howReaction(Re[U].glyph),who:ie[0],choice:U+1}}let J=M.map((U)=>Re[U.index].glyph).join(" / "),j=new Map;for(let U of M)for(let ie of U.users)j.set(ie,(j.get(ie)??0)+1);let ee=[...j].filter(([,U])=>U>1).map(([U])=>U);if(!n)console.error(ee.length?` (${J} are pressed at once; waiting until it is narrowed to one)`:` (answers are split: ${J}; waiting until they agree on one)`);let X=ee.sort();return await h(O,X),null}let A=[...o,...t.overflow];function F(O,M=1/0){let J=[...O].sort((j,ee)=>Number(j.ts)-Number(ee.ts));for(let j of J){if(!(Number(j.ts)>Number(r)))continue;if(t.after&&!(Number(j.ts)>Number(t.after)))continue;if(!k(j.user))continue;if(typeof j.subtype==="string"&&!ny.has(j.subtype))continue;if(Number(j.ts)>=M)break;let ee=typeof j.text==="string"?j.text.trim():"";if(!ee||t.explain&&$o(ee))continue;if(!A.length)return{answer:ee,how:f.howReply,who:j.user,ts:String(j.ts)};let X=gc(ee,A);if(X.kind==="chosen")return{answer:A[X.index-1],how:f.howReplyN(X.index),who:j.user,ts:String(j.ts),choice:X.index};let U=X.kind==="ambiguous",ie=p.unchosen;if(!ie||ie.ambiguous&&!U||ie.ambiguous===U&&Number(j.ts)<Number(ie.ts))p.unchosen={text:ee,who:typeof j.user==="string"?j.user:"",ts:String(j.ts),ambiguous:U}}return null}async function v(){if(delete p.unchosen,t.threadParentTs){let j=L(await Ne(e,s,t.threadParentTs,100,d)),ee=G(j.messages).map(L),X=ee.find((U)=>U.ts===r);if(X){if(w(X),u(X))return null;let U=await C(X);if(U)return U}return F(ee)}let O=L(await at(e,s,30,r,void 0,d,!0)),M=G(O.messages).map(L),J=M.find((j)=>j.ts===r);if(J){if(w(J),u(J))return null}if(J){let j=await C(J);if(j)return j}if(!i){let j=M.filter((X)=>Number(X.ts)>Number(r)&&(y&&X.bot_id===y||g&&X.user===g)).reduce((X,U)=>Math.min(X,Number(U.ts)),1/0),ee=F(M,j);if(ee)return ee}if(J&&Number(J.reply_count)>0){let j=L(await Ne(e,s,r,30,d)),ee=F(G(j.messages).map(L));if(ee)return ee}return null}return{poll:v,state:p,isAnswerer:k,candidates:A}}async function iy(e,t){let{channelId:n,ts:s,question:r,reactable:o,threadOnly:i,cookie:a,timeout:c,shown:d}=t,f=t.askerUserId,p=t.askerBotId,{poll:g,state:y,isAnswerer:k,candidates:w}=oy(e,t),u="";async function l(E){for(let N=0;N<o.length;N++)try{await Yt(e,n,s,Re[N].name,a)}catch{}let I="";if(E.who)try{I=await ve(e,E.who,a)}catch{I=E.who}if(I)console.error(` Answered by: ${W(I)}`);try{let N=y.ownText?jp(y.ownText,E.choice):void 0;await zt(e,n,s,Bp(r,E,I,t.lang,N),a,!0);try{await Lt(e,n,s,fc,a),await Yt(e,n,s,t.seedMarker,a)}catch{}try{if(t.explain)await Yt(e,n,s,fn,a)}catch{}}catch(N){console.error(` (failed to update the original message: ${N instanceof Error?N.message:String(N)})`)}}let h=Date.now()+c*1000,m=Date.now(),b=0,_=jn.minMs,x=0,S;for(;;){let E=null;try{E=await g(),b=0}catch(N){if(N instanceof it)x=N.retryAfter*1000;else{if(b++,b>=Mm)console.error(`Error: Slack requests failed ${b} times in a row: ${N instanceof Error?N.message:String(N)}`),process.exit(ae);console.error(` (Slack error ${b}/${Mm}, retrying: ${N instanceof Error?N.message:String(N)})`)}}S=y.unchosen;let I=y.voided;if(I){if(ay(I,d),t.json)await yn(e,t,{status:"void",answer:null,reason:I.reason,...I.supersededBy?{supersededBy:I.supersededBy}:{},notes:[],cursor:Mt(s,t.after)});process.exit(di)}if(E){let N=await ry(e,{channelId:n,ts:s,threadOnly:i,replyCount:y.replyCount,isAnswerer:k,askerUserId:f,askerBotId:p,...t.threadParentTs?{threadParentTs:t.threadParentTs}:{},...a?{cookie:a}:{}},t.after,(A)=>A.ts===E.ts);await l(E);let C={status:"answered",answer:E.answer,how:E.how,notes:N,cursor:Mt(s,t.after,E.ts,...N.map((A)=>A.ts))};if(Jc(n,s,E.answer,C.cursor),E.who)C.who=E.who;await yn(e,t,C),process.exit(0)}if(y.explainPosted&&t.explainExit){if(console.error(` An explanation was requested (the question is still open). Explain in the thread, then collect with: ${Xn(d,t.asBot,t.after)}`),t.json)await yn(e,t,{status:"explain",answer:null,notes:[],cursor:Mt(s,t.after),explain:y.explainNow});process.exit(SS)}if(S&&!S.ambiguous){let N=S.who;try{if(N)N=await ve(e,N,a)}catch{}if(console.error(` (${W(N)} replied with something that is not a choice \u2014 not a decision. Printing the reply on stdout)`),console.error(` Choices: ${w.map((C,A)=>`${A+1}. ${W(Be(C))}`).join(" ")}`),console.error(` ${d}`),console.error(` To wait for what comes after this reply: ${Xn(d,t.asBot,S.ts)}`),Kc(n,s,S.text,Mt(s,t.after,S.ts)),t.json)await yn(e,t,{status:"freetext",answer:S.text,who:S.who,notes:[],cursor:Mt(s,t.after,S.ts),explain:y.explainNow});else console.log(S.text);process.exit(xS)}if(S&&S.ts!==u){u=S.ts;let N=S.who;try{if(N)N=await ve(e,N,a)}catch{}console.error(` (${W(N)}'s reply matches several choices; waiting until it is narrowed to one)`),console.error(` "${W(S.text)}"`)}if(Date.now()>=h)break;await $S(Math.min(Math.max(_,x),Math.max(0,h-Date.now()))),x=0,_=Hp(_,Date.now()-m)}if(S){if(console.error("Error: there was a reply, but it matches several choices so it cannot be settled (the message is left in place)"),console.error(` Reply: "${W(S.text)}"`),console.error(` Choices: ${w.map((E,I)=>`${I+1}. ${W(Be(E))}`).join(" ")}`),console.error(` ${d}`),console.error(` Reply in the thread, then collect with: ${Xn(d,t.asBot,t.after)}`),t.json)await yn(e,t,{status:"ambiguous",answer:null,notes:[],cursor:Mt(s,t.after),explain:y.explainNow});process.exit(DS)}if(c===0)console.error(`No answer yet: ${d}`);else console.error(`Error: no answer within ${mc(c)} (the message is left in place)`),console.error(` ${d}`),console.error(` To collect later: ${Xn(d,t.asBot,t.after)}`);if(t.json)await yn(e,t,{status:"timeout",answer:null,notes:[],cursor:Mt(s,t.after),explain:y.explainNow});process.exit(kS)}function Xn(e,t,n){return`slack ask --waitFor='${e}'${t?" --as-bot":""}${n?` --after=${n}`:""}`}async function AS(e,t){let{ref:n,threadTs:s}=At(t.target,!1),r=t.cookie,o=Vt(e,r),i;if(t.channelId)i=t.channelId;else if(t.userId)i=await Gt(e,t.userId,r);else i=await we(e,n,r);let a=(await o())?.userId??"",c=await yi(e,i,r),d=$c();if(!t.asBot&&!!a&&c===a){if(console.error(`${d?"Error":"Warning"}: "${t.target}" is a DM to yourself \u2014 Slack will NOT notify you of your own message.
521
+ `+` To reach yourself with a notification, ask as the bot: slack @<bot> ask '${t.target}' '...' (or --as-bot)`),d)process.exit(ae)}let f=kr(Ue(t.question)),p=kr(Ue(t.body??"")),g=new Set([...f.kinds,...p.kinds]);for(let se of`${f.text}
522
+ ${p.text}`.matchAll(/<!(here|channel|everyone)(?:\|[^>]*)?>/g))g.add(se[1]);let y=t.mentionToken??e,k=await mn(y,f.text,i,t.mentionCookie),w=p.text?await mn(y,p.text,i,t.mentionCookie):{text:"",resolved:[],unresolved:[]},u=k.text,l=w.text,h=[...k.resolved,...w.resolved],m=[...k.unresolved,...w.unresolved];sy(m);let b=!!a&&(h.some((se)=>se.userId===a)||new RegExp(`<@${a}(?:\\|[^>]*)?>`).test(`${u}
523
+ ${l}`));if(d&&!t.asBot&&b)console.error(`Error: \`ask\` would post as you (${a}) a question addressed to you \u2014 the asker and the one asked are the same person.
522
524
  `+` To ask yourself, ask as the bot: slack @<bot> ask '${t.target}' '${t.question}' (or --as-bot)
523
- To ask someone else as yourself, tag them, not you.`),process.exit(oe);let D=d.size>0,E=new Set(w.map((te)=>te.userId).filter((te)=>te!==l)),S=new Map(w.map((te)=>[te.userId,te.display]));for(let te of`${y}
524
- ${m}`.matchAll(/<@([UW][A-Z0-9]+)(?:\|[^>]*)?>/g)){let fe=te[1];if(fe===l||E.has(fe))continue;E.add(fe),S.set(fe,await Re(p,fe,t.mentionCookie))}let x;if(D)x=`anyone in ${n} (${[...d].map((te)=>`@${te}`).join(", ")})`;else{if(!E.size&&u&&u!==l)E.add(u),S.set(u,await Re(e,u,r));if(!E.size)console.error("Error: `ask` will not post a question nobody is addressed to \u2014 no one is tagged.\n"+` Tag the person who should answer: slack ask '${t.target}' '@alice ${t.question}' ...
525
+ To ask someone else as yourself, tag them, not you.`),process.exit(ae);let _=g.size>0,x=new Set(h.map((se)=>se.userId).filter((se)=>se!==a)),S=new Map(h.map((se)=>[se.userId,se.display]));for(let se of`${u}
526
+ ${l}`.matchAll(/<@([UW][A-Z0-9]+)(?:\|[^>]*)?>/g)){let pe=se[1];if(pe===a||x.has(pe))continue;x.add(pe),S.set(pe,await ve(y,pe,t.mentionCookie))}let E;if(_)E=`anyone in ${n} (${[...g].map((se)=>`@${se}`).join(", ")})`;else{if(!x.size&&c&&c!==a)x.add(c),S.set(c,await ve(e,c,r));if(!x.size)console.error("Error: `ask` will not post a question nobody is addressed to \u2014 no one is tagged.\n"+` Tag the person who should answer: slack ask '${t.target}' '@alice ${t.question}' ...
525
527
  Or open it to the whole channel: slack ask '${t.target}' '@here ${t.question}' ...
526
- (In a 1:1 DM the other person counts automatically.)`),process.exit(oe);x=[...E].map((te)=>`@${M(S.get(te)??te)} (${te})`).join(", ")}let F=t.choices.map(We),R=F.slice(0,jt),I=F.slice(jt),P=!i.startsWith("D")||!!s,L=D?[]:await Promise.all([...E].map((te)=>gg(p,te,t.mentionCookie))),W=Va({flag:t.lang,readerLocales:L,content:[y,m,...R,...I]});if(!W)console.error(`Error: unsupported language "${M(t.lang??is("LANG")??"")}" \u2014 use one of: ${Tt.join(", ")}`),process.exit(oe);let N=W.lang,J=t.explain??jx(),K=tc(y,m,R,I,P,N,J);qe(K,t.allowUrlAdjacent);let B="",z="?";try{let te=await it(e,i,1,void 0,void 0,r),fe=G(te.messages).map(O).filter((be)=>be.subtype===void 0||be.subtype===null)[0];B=typeof fe?.text==="string"?fe.text:"",z=typeof fe?.user==="string"?await Re(e,fe.user,r):typeof fe?.username==="string"?fe.username:"?"}catch{}let Y=await o(),j=await ri(e,i,r),ie=De(i,s??"",B,K,Y?.userId??"",...t.voidAfter?["reask",`${t.voidAfter.channelId}:${t.voidAfter.ts}`,t.voidAfter.reason]:[]);if(t.code!==ie){let te=await zt(e,i,n,r),fe=R.length?["--- Choices (seeded as reactions) ------------",...R.map((be,yn)=>` ${Fe[yn].glyph} ${Me(be)}`),...I.map((be,yn)=>` (${yn+11}) ${Me(be)} \u2014 text answer only`)]:["--- Choices ----------------------------------"," (none \u2014 free-text reply)"];Se(t.code,ie,["--- Last message in channel ------------------",` ${z}: ${ys(B.split(`
527
- `)[0]??"").slice(0,100)}`,...fe,"--- Asking -----------------------------------",Ee(Y,{asBot:t.asBot}),` \u2192 ${te}${s?" \u2014 THREAD REPLY":" \u2014 NEW top-level message"}`,` Question: ${y}`,` Answerable by: ${x}`,` Via: ${P?"reactions or thread replies":"reactions or replies in this DM"}`,...J?[" Explain: \u2139\uFE0F pill offered \u2014 pressing it asks you to explain; it is never an answer"]:[],...t.voidAfter?[` Then void: ${M(t.voidAfter.link)} (reason: ${M(t.voidAfter.reason||"none")}) \u2014 replaced by this question`]:[],` Language: ${N} (${{flag:"--lang",env:"SLACK_HUB_LANG",readers:"answerers' Slack locale",content:"the question's text",system:"system locale",default:"default"}[W.source]}; override with --lang)`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"],j)}let q=Hn("ask"),ue=await Jt(e,i,K,s,!1,r,!0,q.metadata),le=R.length?Wt:rt;await To([...R.map((te,fe)=>Fe[fe].name),le,...J?[un]:[]],(te)=>It(e,i,ue,te,r),(te,fe)=>{let be=fe instanceof Error?fe.message:String(fe);if(te===le)console.error(` (could not add marker ${te}: ${be})`);else console.error(` (could not add reaction ${te}: ${be})`)});let H="";try{H=await jn(e,i,ue,r)}catch{}let re=H||`${i}:${ue}`;if(console.error(`\u2713 Asked: ${re}`),q.record({team:Y?.team,channel:i,target:t.target,ts:ue,threadTs:s,permalink:H,text:K,asBot:t.asBot}),t.voidAfter){if(!await Lm(e,t.voidAfter,t.voidAfter.reason,re,r))console.error(` \u26A0 The new question is posted, but the old one could not be voided \u2014 do it by hand: slack ask --void='${M(t.voidAfter.link)}' --superseded-by='${re}'`)}if(!t.wait){console.log(qn(re,!!t.asBot));return}let pe=t.timeout??3600;console.error(` Waiting for an answer (up to ${pe}s)\u2026 Ctrl-C to stop`);let X={channelId:i,ts:ue,question:y,reactable:R,overflow:I,threadOnly:P,seedMarker:le,lang:N,audience:E,broadcast:D,askerUserId:Y?.userId??"",askerBotId:Y?.botId??"",timeout:pe,shown:re,asBot:!!t.asBot,json:!!t.json,explain:J,explainExit:!!t.explainExit};if(s)X.threadParentTs=s;if(r)X.cookie=r;await Im(e,X)}function vm(e,t){if(console.error(`This question is void \u2014 it will never be answered. Stop waiting on it: ${M(t)}`),e.reason)console.error(` ${M(e.reason)}`);if(e.supersededBy)console.error(` New question: ${M(e.supersededBy)}`)}async function bl(e,t,n){let s=pt(t),r,o,i;if(s?.ts)r=s.channel,o=s.ts,i=s.threadTs&&s.threadTs!==s.ts?s.threadTs:void 0;else{let l=t.match(/^([A-Za-z0-9]+):(\d{10}\.\d{6})$/);if(!l)return null;r=l[1],o=l[2]}return hr(e,{channelId:r,ts:o,threadTs:i},n)}async function hr(e,t,n){let{channelId:s,ts:r}=t,o=t.threadTs&&t.threadTs!==t.ts?t.threadTs:void 0,i;if(o){let u=O(await Le(e,s,o,100,n));i=G(u.messages).map(O).find((f)=>f.ts===r)}else{let u=O(await it(e,s,1,r,void 0,n,!0));i=G(u.messages).map(O).find((f)=>f.ts===r)}let l={channelId:s,ts:r};if(o)l.threadTs=o;if(i)l.msg=i;return l}async function Pm(e,t,n,s,r){let o=M(t),i=await bl(e,t,r);if(!i)return console.error(`\u2717 ${o}: not a permalink (or 'C\u2026:1700000000.000100')`),null;if(!i.msg)return console.error(`\u2717 ${o}: message not found`),null;let l=i.msg;if(!(!!n?.userId&&l.user===n.userId||!!n?.botId&&l.bot_id===n.botId))return console.error(`\u2717 ${o}: not a question posted by you (${oi(n,s)})${s?"":" \u2014 if the bot posted it, use --as-bot"}`),null;let f=typeof l.text==="string"?l.text:"",a=Ft(f);if(a.kind==="void")return"void";if(a.kind==="resolved")return console.error(`\u2717 ${o}: already answered (answer: ${M(a.answer.split(`
528
- `)[0]??"")}) \u2014 cannot be changed`),null;if(a.kind!=="open")return console.error(`\u2717 ${o}: cannot be read as a \`slack ask\` question \u2014 ${Hs(f)}`),null;let c={link:t,channelId:i.channelId,ts:i.ts,parsed:a,seedMarker:zs(f)??rt,msg:l};if(i.threadTs)c.threadTs=i.threadTs;return c}async function Kx(e,t,n,s){let r=(i)=>typeof i==="string"&&i!==n?.userId;if(G(t.msg.reactions).map(O).some((i)=>Fe.some((l)=>l.name===i.name)&&G(i.users).some(r)))return!0;if(Number(t.msg.reply_count)>0){let i=O(await Le(e,t.channelId,t.ts,100,s));if(G(i.messages).map(O).some((l)=>Number(l.ts)>Number(t.ts)&&r(l.user)&&!l.bot_id))return!0}if(t.channelId.startsWith("D")){let i=O(await it(e,t.channelId,30,t.ts,void 0,s,!0));if(G(i.messages).map(O).some((l)=>Number(l.ts)>Number(t.ts)&&r(l.user)&&!l.bot_id))return!0}return!1}async function qx(e,t){let n=await Be(e,t.cookie),s=await Pm(e,t.link,n,t.asBot,t.cookie);if(s==="void")console.error(`\u2717 ${M(t.link)}: a voided question cannot be edited`),process.exit(oe);if(!s)process.exit(oe);let r=s.parsed,o=async(E)=>{let S=pr(We(E)),x=await hn(t.mentionToken,S.text,s.channelId,t.mentionCookie);return Fm(x.unresolved),x.text},i=t.question!==void 0?await o(t.question):r.question,l=t.body!==void 0?await o(t.body):r.body,u=[...r.reactable,...r.overflow],f=t.choices?t.choices.map(We):u,a=JSON.stringify(f.map(Me))!==JSON.stringify(u.map(Me));if(a&&await Kx(e,s,n,t.cookie))console.error(`\u2717 This question already has responses (reactions or replies) \u2014 changing the choices would change what the pressed reactions mean.
528
+ (In a 1:1 DM the other person counts automatically.)`),process.exit(ae);E=[...x].map((se)=>`@${W(S.get(se)??se)} (${se})`).join(", ")}let I=t.choices.map(Ue),N=I.slice(0,Kt),C=I.slice(Kt),A=!i.startsWith("D")||!!s,F=_?[]:await Promise.all([...x].map((se)=>Jg(y,se,t.mentionCookie))),v=uc({flag:t.lang,readerLocales:F,content:[u,l,...N,...C]});if(!v)console.error(`Error: unsupported language "${W(t.lang??ln("LANG")??"")}" \u2014 use one of: ${It.join(", ")}`),process.exit(ae);let O=v.lang,M=t.explain??ES(),J=hc(u,l,N,C,A,O,M);He(J,t.allowUrlAdjacent);let j="",ee="?";try{let se=await at(e,i,1,void 0,void 0,r),pe=G(se.messages).map(L).filter((be)=>be.subtype===void 0||be.subtype===null)[0];j=typeof pe?.text==="string"?pe.text:"",ee=typeof pe?.user==="string"?await ve(e,pe.user,r):typeof pe?.username==="string"?pe.username:"?"}catch{}let X=await o(),U=await gi(e,i,r),ie=De(i,s??"",j,J,X?.userId??"",...t.voidAfter?["reask",`${t.voidAfter.channelId}:${t.voidAfter.ts}`,t.voidAfter.reason]:[]);if(t.code!==ie){let se=await Bt(e,i,n,r),pe=N.length?["--- Choices (seeded as reactions) ------------",...N.map((be,wn)=>` ${Re[wn].glyph} ${Be(be)}`),...C.map((be,wn)=>` (${wn+11}) ${Be(be)} \u2014 text answer only`)]:["--- Choices ----------------------------------"," (none \u2014 free-text reply)"];Se(t.code,ie,["--- Last message in channel ------------------",` ${ee}: ${Ss(j.split(`
529
+ `)[0]??"").slice(0,100)}`,...pe,"--- Asking -----------------------------------",Ee(X,{asBot:t.asBot}),` \u2192 ${se}${s?" \u2014 THREAD REPLY":" \u2014 NEW top-level message"}`,` Question: ${u}`,` Answerable by: ${E}`,` Via: ${A?"reactions or thread replies":"reactions or replies in this DM"}`,...M?[" Explain: \u2139\uFE0F pill offered \u2014 pressing it asks you to explain; it is never an answer"]:[],...t.voidAfter?[` Then void: ${W(t.voidAfter.link)} (reason: ${W(t.voidAfter.reason||"none")}) \u2014 replaced by this question`]:[],` Language: ${O} (${{flag:"--lang",env:"SLACK_HUB_LANG",readers:"answerers' Slack locale",content:"the question's text",system:"system locale",default:"default"}[v.source]}; override with --lang)`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"],U)}let q=Vn("ask"),ce=await Ht(e,i,J,s,!1,r,!0,q.metadata),z=N.length?qt:ot;await Bo([...N.map((se,pe)=>Re[pe].name),z,...M?[fn]:[]],(se)=>Lt(e,i,ce,se,r),(se,pe)=>{let be=pe instanceof Error?pe.message:String(pe);if(se===z)console.error(` (could not add marker ${se}: ${be})`);else console.error(` (could not add reaction ${se}: ${be})`)});let K="";try{K=await qn(e,i,ce,r)}catch{}let ne=K||`${i}:${ce}`;if(console.error(`\u2713 Asked: ${ne}`),q.record({team:X?.team,channel:i,target:t.target,ts:ce,threadTs:s,permalink:K,text:J,asBot:t.asBot}),t.voidAfter){if(!await ly(e,t.voidAfter,t.voidAfter.reason,ne,r))console.error(` \u26A0 The new question is posted, but the old one could not be voided \u2014 do it by hand: slack ask --void='${W(t.voidAfter.link)}' --superseded-by='${ne}'`)}if(!t.wait){console.log(Xn(ne,!!t.asBot));return}let fe=t.timeout??3600;console.error(` Waiting for an answer (up to ${mc(fe)})\u2026 Ctrl-C to stop`);let Y={channelId:i,ts:ce,question:u,reactable:N,overflow:C,threadOnly:A,seedMarker:z,lang:O,audience:x,broadcast:_,askerUserId:X?.userId??"",askerBotId:X?.botId??"",timeout:fe,shown:ne,asBot:!!t.asBot,json:!!t.json,explain:M,explainExit:!!t.explainExit};if(s)Y.threadParentTs=s;if(r)Y.cookie=r;await iy(e,Y)}function ay(e,t){if(console.error(`This question is void \u2014 it will never be answered. Stop waiting on it: ${W(t)}`),e.reason)console.error(` ${W(e.reason)}`);if(e.supersededBy)console.error(` New question: ${W(e.supersededBy)}`)}async function Pl(e,t,n){let s=ht(t),r,o,i;if(s?.ts)r=s.channel,o=s.ts,i=s.threadTs&&s.threadTs!==s.ts?s.threadTs:void 0;else{let a=t.match(/^([A-Za-z0-9]+):(\d{10}\.\d{6})$/);if(!a)return null;r=a[1],o=a[2]}return Dr(e,{channelId:r,ts:o,threadTs:i},n)}async function Dr(e,t,n){let{channelId:s,ts:r}=t,o=t.threadTs&&t.threadTs!==t.ts?t.threadTs:void 0,i;if(o){let c=L(await Ne(e,s,o,100,n));i=G(c.messages).map(L).find((d)=>d.ts===r)}else{let c=L(await at(e,s,1,r,void 0,n,!0));i=G(c.messages).map(L).find((d)=>d.ts===r)}let a={channelId:s,ts:r};if(o)a.threadTs=o;if(i)a.msg=i;return a}async function cy(e,t,n,s,r){let o=W(t),i=await Pl(e,t,r);if(!i)return console.error(`\u2717 ${o}: not a permalink (or 'C\u2026:1700000000.000100')`),null;if(!i.msg)return console.error(`\u2717 ${o}: message not found`),null;let a=i.msg;if(!(!!n?.userId&&a.user===n.userId||!!n?.botId&&a.bot_id===n.botId))return console.error(`\u2717 ${o}: not a question posted by you (${mi(n,s)})${s?"":" \u2014 if the bot posted it, use --as-bot"}`),null;let d=typeof a.text==="string"?a.text:"",f=Rt(d);if(f.kind==="void")return"void";if(f.kind==="resolved")return console.error(`\u2717 ${o}: already answered (answer: ${W(f.answer.split(`
530
+ `)[0]??"")}) \u2014 cannot be changed`),null;if(f.kind!=="open")return console.error(`\u2717 ${o}: cannot be read as a \`slack ask\` question \u2014 ${Zs(d)}`),null;let p={link:t,channelId:i.channelId,ts:i.ts,parsed:f,seedMarker:Qs(d)??ot,msg:a};if(i.threadTs)p.threadTs=i.threadTs;return p}async function TS(e,t,n,s){let r=(i)=>typeof i==="string"&&i!==n?.userId;if(G(t.msg.reactions).map(L).some((i)=>Re.some((a)=>a.name===i.name)&&G(i.users).some(r)))return!0;if(Number(t.msg.reply_count)>0){let i=L(await Ne(e,t.channelId,t.ts,100,s));if(G(i.messages).map(L).some((a)=>Number(a.ts)>Number(t.ts)&&r(a.user)&&!a.bot_id))return!0}if(t.channelId.startsWith("D")){let i=L(await at(e,t.channelId,30,t.ts,void 0,s,!0));if(G(i.messages).map(L).some((a)=>Number(a.ts)>Number(t.ts)&&r(a.user)&&!a.bot_id))return!0}return!1}async function FS(e,t){let n=await je(e,t.cookie),s=await cy(e,t.link,n,t.asBot,t.cookie);if(s==="void")console.error(`\u2717 ${W(t.link)}: a voided question cannot be edited`),process.exit(ae);if(!s)process.exit(ae);let r=s.parsed,o=async(x)=>{let S=kr(Ue(x)),E=await mn(t.mentionToken,S.text,s.channelId,t.mentionCookie);return sy(E.unresolved),E.text},i=t.question!==void 0?await o(t.question):r.question,a=t.body!==void 0?await o(t.body):r.body,c=[...r.reactable,...r.overflow],d=t.choices?t.choices.map(Ue):c,f=JSON.stringify(d.map(Be))!==JSON.stringify(c.map(Be));if(f&&await TS(e,s,n,t.cookie))console.error(`\u2717 This question already has responses (reactions or replies) \u2014 changing the choices would change what the pressed reactions mean.
529
531
  `+` The question and body can still be changed. To change the choices, void it and ask again:
530
- slack ask --void='${M(t.link)}' --reask${t.asBot?" --as-bot":""} \u2026`),process.exit(oe);if(!([...`${i}
531
- ${l}`.matchAll(/<@([UW][A-Z0-9]+)(?:\|[^>]*)?>/g)].some((E)=>E[1]!==n?.userId)||/<!(?:here|channel|everyone)/.test(`${i}
532
- ${l}`)||s.channelId.startsWith("D")))console.error("\u2717 The question would be addressed to nobody \u2014 keep an @mention of who can answer"),process.exit(oe);let p=t.lang?Va({flag:t.lang})?.lang??r.lang:r.lang,h=f.slice(0,jt),g=f.slice(jt),y=typeof s.msg.text==="string"?s.msg.text:"",m=tc(i,l,h,g,r.threadOnly,p,r.explain),w=ho(y);if(w.length)m=go(m,w,p);if(qe(m,t.allowUrlAdjacent),m===y){console.error("No changes.");return}let k=De("ask-edit",`${s.channelId}:${s.ts}`,m,n?.userId??"");if(t.code!==k){let E=(S,x,F)=>x===F?[` ${S}: (unchanged)`]:[` ${S}:`,...x.split(`
533
- `).map((R)=>` - ${R}`),...F.split(`
534
- `).map((R)=>` + ${R}`)];Se(t.code,k,["--- Editing question --------------------------",Ee(n,{asBot:t.asBot}),` ${M(t.link)}`,...E("Question",r.question,i),...E("Body",r.body,l),...a?[" Choices (nobody has answered yet \u2014 pills are re-seeded):",...u.map((S,x)=>` - ${x+1}. ${Me(S)}`),...f.map((S,x)=>` + ${x+1}. ${Me(S)}`)]:[" Choices: (unchanged)"],...p!==r.lang?[` Language: ${r.lang} \u2192 ${p} (the instructions are rewritten)`]:[],"----------------------------------------------"])}await Kt(e,s.channelId,s.ts,m,t.cookie,!0);let _=h.length?Wt:rt,D=zs(y)??rt;if(a){let E=(S)=>r.explain?[S,un]:[S];for(let S of[...r.reactable.map((x,F)=>Fe[F].name),...E(D)])try{await qt(e,s.channelId,s.ts,S,t.cookie)}catch{}await To([...h.map((S,x)=>Fe[x].name),...E(_)],(S)=>It(e,s.channelId,s.ts,S,t.cookie),(S,x)=>console.error(` (could not add reaction ${S}: ${x instanceof Error?x.message:String(x)})`))}else if(D!==_)try{await It(e,s.channelId,s.ts,_,t.cookie),await qt(e,s.channelId,s.ts,D,t.cookie)}catch(E){console.error(` (could not swap the marker to ${_}: ${E instanceof Error?E.message:String(E)})`)}console.error(`\u2713 Edited: ${M(t.link)}`)}async function Hx(e,t){let n={kind:"ask",limit:t.limit};if(t.channel)n.channel=t.channel;let s=Ac(n);if(!s)console.error(`Error: ${er}
535
- (${Rt()})`),process.exit(oe);let r;if(t.stale){if(r=ds(t.stale),r===void 0)console.error(`Error: --stale needs a duration like 24h / 3d (got ${M(t.stale)})`),process.exit(oe)}let o=[];for(let l of s){if(r!==void 0&&l.sent_at>r)continue;let u=l.as_bot?e.bot:e.user,f=l.permalink||`${l.channel}:${l.ts}`,a="unknown",c=(l.text.split(`
536
- `)[0]??"").replace(/^:question: /,""),d;if(u)try{let h=await hr(u,{channelId:l.channel,ts:l.ts,threadTs:l.thread_ts??void 0},l.as_bot?void 0:e.cookie);if(!h.msg)a="gone";else{let g=Ft(typeof h.msg.text==="string"?h.msg.text:"");if(a=g.kind==="resolved"?"answered":g.kind==="other"?"edited":g.kind,g.kind!=="other"&&g.question)c=g.question;if(g.kind==="resolved")d=g.answer}}catch{a="unknown"}if(t.state!=="all"&&a!==t.state)continue;let p={state:a,age_h:Math.round((Date.now()-l.sent_at)/3600000),asBot:!!l.as_bot,channel:l.channel,target:l.target??l.channel,link:f,question:Me(c)};if(d!==void 0)p.answer=d;o.push(p)}if(t.json)console.log(JSON.stringify(o));else{for(let l of o)console.log(`${l.state.padEnd(8)} ${String(l.age_h).padStart(4)}h ${l.asBot?"bot ":"user"} ${M(l.target)} ${l.link}
537
- ${M(l.question).slice(0,100)}`);console.error(`${o.length} question(s)${t.state==="all"?"":` in state "${t.state}"`}${t.stale?`, older than ${t.stale}`:""}.`)}let i=o.filter((l)=>l.state==="open");if(t.stale&&i.length)for(let l of[!1,!0]){let u=i.filter((f)=>f.asBot===l);if(!u.length)continue;console.error(`To void them (${u.length}, ${l?"bot":"user"}):
538
- slack ask ${u.map((f)=>`--void='${f.link}'`).join(" ")} --reason 'stale'${l?" --as-bot":""}`)}}async function zx(e,t,n){if(n.has(e.channel))return n.get(e.channel);let s={channelId:e.channel,ts:e.ts,threadTs:e.thread_ts??void 0},r=async(i)=>{if(!i)return!1;try{return await hr(i,s),!0}catch(l){if(l instanceof ot)throw l;return/channel_not_found|not_in_channel/.test(l instanceof Error?l.message:String(l))?!1:void 0}},o;if(await r(t)===!1)for(let[i,l]of xo()){if(l.kind!=="bot"||i===is("IDENTITY"))continue;let u={...process.env};if("error"in So(i,u))continue;if(await r(u.SLACK_BOT_TOKEN)){o=i;break}}return n.set(e.channel,o),o}function Yx(e,t){if(!e.identity||e.identity===is("IDENTITY"))return t;let n={...process.env},s=So(e.identity,n);if("error"in s)return s.error;if(s.kind==="bot")return{bot:n.SLACK_BOT_TOKEN,user:n.SLACK_TOKEN};if(!n.SLACK_TOKEN)return`asked as @${e.identity}, a profile identity: run the pass as that identity`;return{user:n.SLACK_TOKEN}}async function dm(e,t){let n=[];Pc(0);let s=Oc(t.sinceMs);if(!s)console.error(`Error: ${er}
539
- (${Rt()})`),process.exit(oe);let r=Date.now()-86400000,o=s.filter((y)=>(!t.channel||y.channel===t.channel||y.target===t.channel)&&(!t.only||t.only.has(`${y.channel}:${y.ts}`))&&(!t.skip||y.sent_at>=r||!t.skip.has(`${y.channel}:${y.ts}`))),i=[],l={unanswered:0,ambiguous:0,resolved:0,void:0,explain:0,throttled:0},u=[],f=[],a=e.user?(await Be(e.user,e.cookie))?.team??"":e.bot?(await Be(e.bot))?.team??"":"",c=new Map,d=new Map;o.reverse();for(let[y,m]of o.entries()){if(m.team&&a&&m.team!==a){c.set(m.team,(c.get(m.team)??0)+1);continue}let w=m.permalink||`${m.channel}:${m.ts}`,k=!!m.as_bot;n.push(`${m.channel}:${m.ts}`);let _=m.delivered_cursor??void 0;try{if(!m.identity&&k){let B=await zx(m,e.bot,d);if(B){if(m.identity=B,t.push)Rh(m.channel,m.ts,B)}}let D=Yx(m,e);if(typeof D==="string"){f.push(`${w}: ${D}`);continue}let E=k?D.bot:D.user;if(!E){f.push(`${w}: ${k?"asked with --as-bot, but there is no bot token":"no user token"}`);continue}let S=k?void 0:D.cookie,x={channelId:m.channel,ts:m.ts,threadTs:m.thread_ts??void 0},F=await hr(E,x,S);if(!F.msg){f.push(`${w}: message not found (deleted?)`);continue}let R=await Nm(E,{channelId:m.channel,ts:m.ts,msg:F.msg},S),I=R.parsed;if(I.kind==="resolved"){if(l.resolved++,t.push)Io(m.channel,m.ts,0);continue}if(I.kind==="void"){if(l.void++,t.push)Io(m.channel,m.ts,ei);continue}if(I.kind==="other"){f.push(`${w}: cannot be read as a \`slack ask\` question \u2014 ${Hs(R.text)}`);continue}if(!R.audience.size&&!R.broadcast){f.push(`${w}: the question is addressed to nobody`);continue}let P=Mm(R,I,x,{timeout:0,link:w,asBot:k,json:!1,cookie:S,after:_}),L=Rm(E,P,!0),W=await L.poll(),N=L.state.unchosen;if(L.state.voided){if(l.void++,t.push)Io(m.channel,m.ts,ei);continue}let J=qn(w,k,_);if(L.state.explainNow.length)l.explain++,u.push(`${w}: \u2139\uFE0F an explanation was requested (${L.state.explainNow.map((B)=>`<@${B}>`).join(" ")}) \u2014 explain in the thread`);let K={row:m,link:w,question:I.question,collect:J,alive:Ih(m)};if(W)i.push({...K,answer:W.answer,how:W.how,freeText:!1,...W.ts?{answeredTs:W.ts}:{}});else if(N&&!N.ambiguous&&N.text!==m.delivered_answer)i.push({...K,answer:N.text,how:"reply (not a choice)",freeText:!0,cursor:Pt(m.ts,_,N.ts),answeredTs:N.ts});else if(N?.ambiguous)l.ambiguous++;else l.unanswered++}catch(D){if(D instanceof ot){n.pop(),l.throttled=o.length-y,f.push(`rate-limited by Slack (${D.message}): ${l.throttled} question(s) not checked this pass`);break}f.push(`${w}: ${D instanceof Error?D.message:String(D)}`)}}if(t.push)Xx(i,t.selfArgs??[],f);let p=(y)=>!y.pushed&&y.row.pushed_answer!==y.answer,h=t.watch?i.filter((y)=>y.pushed):t.undelivered?i.filter(p):i,g={checked:n,throttled:l.throttled>0};if(t.watch&&!h.length&&!f.length)return g;if(t.json)for(let y of h){let m=y.row;console.log(JSON.stringify({id:m.id,link:y.link,channel:m.channel,ts:m.ts,asked_at:m.sent_at,question:y.question,answer:y.answer,how:y.how,free_text:y.freeText,sender:{session_id:m.session_id??null,cli:m.cli??null,agent_pid:m.agent_pid??null,pid:m.pid,alive:y.alive,cwd:m.cwd,git_branch:m.git_branch??null,host:m.host??null},delivered_at:m.delivered_at??null,collect:y.collect,...t.push?{pushed:y.pushed??null}:{},...y.undelivered?{undelivered:y.undelivered}:{}}))}else{let y=new Map;for(let m of h){let w=m.row.session_id?`session ${m.row.session_id}`:`pid ${m.row.agent_pid??m.row.pid}`;y.set(w,[...y.get(w)??[],m])}for(let[m,w]of y){let k=w[0].row;console.log(`${M(m)} ${M(k.cli??"?")} pid ${k.agent_pid??k.pid} ${w[0].alive?"(alive)":"(gone)"}${k.git_branch?` branch=${M(k.git_branch)}`:""} cwd=${M(k.cwd)}`);for(let _ of w){if(console.log(` ${M(_.link)} (${Kn(_.row.sent_at/1000)})`),console.log(` Q: ${M(Me(_.question))}`),console.log(` A: ${M(Me(_.answer))} \u2014 ${M(_.how)}${_.freeText?" \u2014 not a decision":""}`),console.log(` collect: ${M(_.collect)}`),_.undelivered)console.log(` undelivered: ${M(_.undelivered)}`);if(_.pushed)console.log(` pushed to pid ${_.pushed.pid}${_.pushed.collected?", collected \u2705":""}`)}}}for(let y of f)console.error(` (${M(y)})`);for(let y of u)console.error(` (${M(y)})`);for(let[y,m]of c)console.error(` (${m} question(s) belong to another workspace "${M(y)}" \u2014 check with slack -w <name> ask --pending)`);return console.error(`${i.length} answered but not collected, ${l.unanswered} unanswered`+(l.ambiguous?`, ${l.ambiguous} with a reply matching several choices (unsettled)`:"")+(l.resolved?`, ${l.resolved} \u2705 already collected`:"")+(l.void?`, ${l.void} voided`:"")+(l.explain?`, ${l.explain} with an \u2139\uFE0F explain request`:"")+(l.throttled?`, ${l.throttled} not checked (rate-limited)`:"")+(t.push?`, ${i.filter((y)=>y.pushed).length} pushed to the asker`:"")+(t.undelivered?`, ${i.filter(p).length} undelivered`:"")+` \u2014 checked ${o.length} uncollected question(s) (log: ${Rt()})`),g}async function Gx(e,t,n){let s=!1,r=new Set,o=!0,i=async()=>{if(s)return;s=!0;try{while(o||r.size){let f=o?void 0:new Set(r);o=!1,r.clear();try{await e(f)}catch(a){console.error(`slack ask --watch: pass failed: ${ge(a)}`)}}}finally{s=!1}},l=process.env.SLACK_RELAY_URL,u=process.env.SLACK_RELAY_TOKEN;if(l&&u){let f=Pa(l,u,void 0,{transport:va(process.env.SLACK_RELAY_TRANSPORT)});(async()=>{for(let a=0;;a++){try{await f(void 0,new AbortController().signal,{hello:()=>{a=0},bell:(c,d)=>{let p=`${d.channel}:${d.thread_ts??d.ts}`;if(!(Oc(t())??[]).some((g)=>`${g.channel}:${g.ts}`===p))return;r.add(p),setTimeout(()=>{i()},3000)}})}catch(c){console.error(`slack ask --watch: relay: ${c instanceof Error?c.message:String(c)} \u2014 reconnecting`)}await new Promise((c)=>setTimeout(c,os(a,2000,300000)))}})()}else console.error("slack ask --watch: no SLACK_RELAY_URL / SLACK_RELAY_TOKEN \u2014 checking every interval only");for(;;)o=!0,await i(),await new Promise((f)=>setTimeout(f,typeof n==="number"?n:n()))}function Xx(e,t,n){let s=vf(mt(ja(process.env.XDG_STATE_HOME||mt(zo(),".local","state")),"ask-push.lock"));if(!s){n.push("another `ask --pending --push` pass is running: nothing pushed by this one");return}try{let r;for(let o of e){let i=o.row,l=i.pushed_answer===o.answer,u=i.agent_pid??i.pid;if(!l){let a=u,c=o.alive?a:If(i.cwd,r??=Rf());if(c===void 0){o.undelivered=`the asker (pid ${a}) is gone and no live agent runs in ${i.cwd}`;continue}let d=Tf({link:o.link,answer:o.answer,how:o.how,question:o.question,freeText:o.freeText,collected:!o.freeText,...o.alive?{}:{goneAsker:a},tag:Af(i.sent_at,o.answeredTs?Number(o.answeredTs)*1000:void 0)}),p=Of(c,d);if(p===void 0){o.undelivered=`pid ${c} did not take the push over ay \u2014 tried again next pass`,n.push(`${o.link}: ${o.undelivered}`);continue}u=p,Oh(i.channel,i.ts,o.answer)}else if(o.freeText)continue;let f=!1;if(o.freeText)Fc(i.channel,i.ts,o.answer,o.cursor??"");else{let a=i.delivered_cursor?[`--after=${i.delivered_cursor}`]:[],c=i.identity&&i.identity!==is("IDENTITY")?[`@${i.identity}`]:[],d=HD(process.execPath,[...process.argv.slice(1,2),...c,...t,"ask",`--waitFor=${o.link}`,"--timeout","0",...i.as_bot?["--as-bot"]:[],...a],{encoding:"utf8",timeout:120000,stdio:["ignore","pipe","pipe"]});if(f=d.status===0,!f)n.push(`${o.link}: pushed, but collecting it exited ${d.status??"on a signal"} \u2014 collect by hand: ${o.collect}`)}o.pushed={pid:u,collected:f}}}finally{s()}}async function Lm(e,t,n,s,r){let o=M(t.link);try{let i=wp(t.parsed.question,n,t.parsed.lang,t.parsed.body||void 0,s);await Kt(e,t.channelId,t.ts,i,r,!0)}catch(i){return console.error(`\u2717 ${o}: failed to rewrite: ${i instanceof Error?i.message:String(i)}`),!1}for(let i of[...t.parsed.reactable.map((l,u)=>Fe[u].name),t.seedMarker,...t.parsed.explain?[un]:[]])try{await qt(e,t.channelId,t.ts,i,r)}catch{}try{await It(e,t.channelId,t.ts,ec,r)}catch(i){console.error(` (${o}: could not add the \uD83D\uDEAB reaction: ${i instanceof Error?i.message:String(i)})`)}return console.error(`\u2713 Voided: ${o}`),!0}async function Vx(e,t){let n=await Be(e,t.cookie);if(t.supersededBy){let l=M(t.supersededBy),u=!1;try{let f=await bl(e,t.supersededBy,t.cookie);if(u=!!f?.msg,!f)console.error(`Error: --superseded-by must be a message permalink (or 'C\u2026:1700000000.000100'): ${l}`),process.exit(oe)}catch(f){console.error(`Error: cannot check --superseded-by: ${l} (${f instanceof Error?f.message:String(f)})`),process.exit(oe)}if(!u)console.error(`Error: --superseded-by message not found: ${l}`),process.exit(oe)}let s=[],r=0;for(let l of t.links){let u=M(l),f=await bl(e,l,t.cookie);if(!f){console.error(`\u2717 ${u}: not a permalink (or 'C\u2026:1700000000.000100')`),r++;continue}if(!f.msg){console.error(`\u2717 ${u}: message not found`),r++;continue}let a=f.msg;if(!(!!n?.userId&&a.user===n.userId||!!n?.botId&&a.bot_id===n.botId)){console.error(`\u2717 ${u}: not a question posted by you (${oi(n,t.asBot)}), so it cannot be voided${t.asBot?"":" \u2014 if the bot posted it, use --as-bot"}`),r++;continue}let d=typeof a.text==="string"?a.text:"",p=Ft(d),h=!1;if(p.kind==="void"){console.error(`- ${u}: already voided (nothing to do)`);continue}if(p.kind==="resolved"){console.error(`\u2717 ${u}: an answered question cannot be voided (answer: ${M(p.answer.split(`
540
- `)[0]??"")})`),r++;continue}if(p.kind!=="open"){let m=kp(d);if(!m){console.error(`\u2717 ${u}: cannot be read as a \`slack ask\` question \u2014 ${Hs(d)}`),r++;continue}let w=G(a.reactions).map(O).filter((k)=>G(k.users).includes(n?.userId??"\x00")).map((k)=>Fe.findIndex((_)=>_.name===k.name)).filter((k)=>k>=0);p={kind:"open",question:m.question,body:m.body,reactable:Array.from({length:w.length?Math.max(...w)+1:0},()=>""),overflow:[],threadOnly:!0,lang:Za(d)??"ja",explain:G(a.reactions).map(O).some((k)=>k.name===un&&G(k.users).includes(n?.userId??"\x00"))},h=!0}let g=h?G(a.reactions).map(O).some((m)=>m.name===Wt&&G(m.users).includes(n?.userId??"\x00"))?Wt:rt:zs(d)??rt,y=G(a.reactions).map(O).filter((m)=>typeof m.name==="string"&&Fe.some((w)=>w.name===m.name)).filter((m)=>G(m.users).some((w)=>w!==n?.userId)).map((m)=>`:${String(m.name)}:`);s.push({link:l,channelId:f.channelId,ts:f.ts,text:d,parsed:p,seedMarker:g,pressed:y,...h?{unreadable:h}:{}})}if(!s.length)console.error(r?"No questions can be voided.":"Nothing to do."),process.exit(r?oe:0);let o=De("ask-void",...s.map((l)=>`${l.channelId}:${l.ts}`),t.reason,t.supersededBy??"",n?.userId??"");if(t.code!==o)Se(t.code,o,["--- Void -----------------------------------------",Ee(n,{asBot:t.asBot}),` Reason: ${t.reason?M(t.reason):"(none)"}`,...t.supersededBy?[` Replaced: ${M(t.supersededBy)}`]:[],` ${s.length} question(s):`,...s.map((l)=>` \u2022 ${M(l.link)}
541
- ${M(l.parsed.question.split(`
542
- `)[0]??"").slice(0,100)}`+(l.pressed.length?`
543
- (already pressed: ${l.pressed.join(" ")} \u2014 left in place, never collected)`:"")+(l.unreadable?`
544
- \u26A0 its layout no longer reads as an ask (edited by hand?) \u2014 voided from a best-effort read: question and the rest of the text kept as they are`:""))," Each becomes \uD83D\uDEAB (body kept, options and instructions removed); our pills and marker (\u2795, or \u2753) come off; a \uD83D\uDEAB reaction is added.",...r?[` (${r} link(s) above were refused and will be skipped)`]:[],"----------------------------------------------"]);let i=0;for(let l of s)if(!await Lm(e,l,t.reason,t.supersededBy,t.cookie))i++;process.exit(i||r?oe:0)}async function Zx(e,t){let n=pt(t.link),s,r,o;if(n?.ts)s=n.channel,r=n.ts,o=n.threadTs&&n.threadTs!==n.ts?n.threadTs:void 0;else{let g=t.link.match(/^([A-Za-z0-9]+):(\d{10}\.\d{6})$/);if(!g)console.error(`Error: --waitFor needs the permalink of a question (or 'C\u2026:1700000000.000100').
545
- `+` Got: ${M(t.link)}`),process.exit(oe);s=g[1],r=g[2]}let i=await hr(e,{channelId:s,ts:r,threadTs:o},t.cookie);if(!i.msg)console.error(`Error: message not found: ${M(t.link)}`),process.exit(oe);let l=i.msg,u=await Nm(e,{channelId:s,ts:r,msg:l},t.cookie),{text:f,parsed:a,audience:c,broadcast:d,askerUserId:p,askerBotId:h}=u;if(a.kind==="other")console.error(`Error: this cannot be read as a \`slack ask\` question.
546
- Reason: ${Hs(f)}
547
- ${M(t.link)}
548
- (the pressed reactions are still there: check with slack read '${M(t.link)}')`),process.exit(oe);if(a.kind==="void"){if(vm(a,t.link),t.json)await gn(e,{json:!0,shown:t.link,asBot:t.asBot,cookie:t.cookie},{status:"void",answer:null,reason:a.reason,...a.supersededBy?{supersededBy:a.supersededBy}:{},notes:[],cursor:Pt(r,t.after)});process.exit(ei)}if(a.kind==="resolved"){console.error(`\u2713 Answered: ${M(a.question)}`);let g=typeof O(l.edited).ts==="string"?String(O(l.edited).ts):void 0,y=xp(f),m=!1,w=(E)=>{if(m||!y.byReply)return!1;if(g&&Number(E.ts)>Number(g))return!1;let S=typeof E.text==="string"?E.text.trim():"",x=S===a.answer||y.n!==void 0&&(new RegExp(`^[(\uFF08]?${y.n}(?![0-9])`).test(S)||Sp(S,a.answer,y.n));if(x)m=!0;return x},k=t.after,_=[];if(c.size||d){let E=(S)=>typeof S==="string"&&!!S&&S!==p&&(d||c.has(S));_=await Om(e,{channelId:s,ts:r,threadOnly:!!o||!s.startsWith("D"),replyCount:Number(l.reply_count)||0,isAnswerer:E,askerUserId:p,askerBotId:h,...o?{threadParentTs:o}:{},...t.cookie?{cookie:t.cookie}:{}},k,w)}let D=Pt(r,k,..._.map((E)=>E.ts));await gn(e,{json:t.json,shown:t.link,asBot:t.asBot,cookie:t.cookie},{status:"answered",answer:a.answer,notes:_,cursor:D}),Tc(s,r,a.answer,D);return}if(!c.size&&!d)console.error(`Error: this question is addressed to nobody, so valid answerers cannot be determined: ${M(t.link)}`),process.exit(oe);if(t.timeout>0)console.error(` Waiting for an answer (up to ${t.timeout}s)\u2026 Ctrl-C to stop`);await Im(e,Mm(u,a,{channelId:s,ts:r,threadTs:o},t))}async function Nm(e,t,n){let{msg:s}=t,r=typeof s.text==="string"?s.text:"",o=Ft(r),i=typeof s.user==="string"?s.user:"",l=typeof s.bot_id==="string"?s.bot_id:"",u=/<!(here|channel|everyone)(\^[^>]*)?(\|[^>]*)?>/.test(r),f=new Set;for(let a of r.matchAll(/<@([UW][A-Z0-9]+)>/g))if(a[1]!==i)f.add(a[1]);if(o.kind!=="other"&&!f.size&&!u){let a=await ii(e,t.channelId,n);if(a&&a!==i)f.add(a)}return{text:r,parsed:o,audience:f,broadcast:u,askerUserId:i,askerBotId:l}}function Mm(e,t,n,s){let r={channelId:n.channelId,ts:n.ts,question:t.question,reactable:t.reactable,overflow:t.overflow,threadOnly:t.threadOnly,seedMarker:zs(e.text)??rt,lang:t.lang,audience:e.audience,broadcast:e.broadcast,askerUserId:e.askerUserId,askerBotId:e.askerBotId,timeout:s.timeout,shown:s.link,asBot:s.asBot,json:s.json,explain:t.explain,explainExit:!!s.explainExit};if(n.threadTs)r.threadParentTs=n.threadTs;if(s.cookie)r.cookie=s.cookie;if(s.after)r.after=s.after;return r}var gt=3;function Qx(e){return`slack poll --results='${e}'`}async function eS(e,t){let{ref:n,threadTs:s}=$t(t.target,!1),r=t.cookie,o=Gt(e,r),i;if(t.channelId)i=t.channelId;else if(t.userId)i=await Ht(e,t.userId,r);else i=await we(e,n,r);let l=(await o())?.userId??"",u=await ii(e,i,r);if(!t.asBot&&!!l&&u===l)console.error(`Warning: "${t.target}" is a DM to yourself \u2014 Slack will NOT notify you of your own message.
549
- `+` To reach yourself with a notification, post as the bot: slack poll '${t.target}' '...' --as-bot`);let f=pr(We(t.question)),a=pr(We(t.body??"")),c=t.mentionToken??e,d=await hn(c,f.text,i,t.mentionCookie),p=a.text?await hn(c,a.text,i,t.mentionCookie):{text:"",resolved:[],unresolved:[]},h=d.text,g=p.text;for(let L of jo([...d.unresolved,...p.unresolved]))console.error(`\u26A0 ${M(L)}`);let y=t.choices.map(We),m=!!t.multi,w=t.until??"",k=gh(h,g,y,{multi:m,deadline:w});qe(k,t.allowUrlAdjacent);let _="",D="?";try{let L=await it(e,i,1,void 0,void 0,r),W=G(L.messages).map(O).filter((N)=>N.subtype===void 0||N.subtype===null)[0];_=typeof W?.text==="string"?W.text:"",D=typeof W?.user==="string"?await Re(e,W.user,r):typeof W?.username==="string"?W.username:"?"}catch{}let E=await o(),S=await ri(e,i,r),x=De(i,s??"",_,k,E?.userId??"");if(t.code!==x){let L=await zt(e,i,n,r);Se(t.code,x,["--- Last message in channel ------------------",` ${D}: ${ys(_.split(`
550
- `)[0]??"").slice(0,100)}`,"--- Ballot (seeded as reactions) -------------",...y.map((W,N)=>` ${_t[N].glyph} ${Vs(W)}`),"--- Posting ----------------------------------",Ee(E,{asBot:t.asBot}),` \u2192 ${L}${s?" \u2014 THREAD REPLY":" \u2014 NEW top-level message"}`,` Question: ${h}`,` Rule: ${m?"any number of votes per person (--multi)":"one vote per person"}${w?` \u2014 closes ${w}`:""}`," Note: your own votes are not counted (the pills are seeds you added, so they can't be told apart)","--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"],S)}let F=Hn("poll"),R=await Jt(e,i,k,s,!1,r,!0,F.metadata);await To([Zs,...y.map((L,W)=>_t[W].name)],(L)=>It(e,i,R,L,r),(L,W)=>{let N=W instanceof Error?W.message:String(W);if(L===Zs)console.error(` (could not add marker ${L}: ${N})`);else console.error(` (could not add reaction ${L}: ${N})`)});let I="";try{I=await jn(e,i,R,r)}catch{}let P=I||`${i}:${R}`;console.error(`\u2713 Posted: ${P}`),F.record({team:E?.team,channel:i,target:t.target,ts:R,threadTs:s,permalink:I,text:k,asBot:t.asBot}),console.log(Qx(P)),console.error(` To close: slack poll --close='${P}'${t.asBot?" --as-bot":""}`)}async function tS(e,t,n){let s=pt(t),r,o,i;if(s?.ts)r=s.channel,o=s.ts,i=s.threadTs&&s.threadTs!==s.ts?s.threadTs:void 0;else{let u=t.match(/^([A-Za-z0-9]+):(\d{10}\.\d{6})$/);if(!u)console.error(`Error: --results/--close needs the permalink of a poll (or 'C\u2026:1700000000.000100').
551
- `+` Got: ${M(t)}`),process.exit(gt);r=u[1],o=u[2]}let l;if(i){let u=O(await Le(e,r,i,100,n));l=G(u.messages).map(O).find((f)=>f.ts===o)}else{let u=O(await it(e,r,1,o,void 0,n,!0));l=G(u.messages).map(O).find((f)=>f.ts===o)}if(!l)console.error(`Error: message not found: ${M(t)}`),process.exit(gt);return{channelId:r,ts:o,msg:l}}function fm(e){let t=Math.max(1,...e.map((n)=>n.count));return e.map((n,s)=>`${_t[s].glyph} ${String(n.count).padStart(3)} ${"\u2588".repeat(Math.round(n.count/t*20))}${n.count?" ":""}${n.choice}`)}async function nS(e,t){let{channelId:n,ts:s,msg:r}=await tS(e,t.link,t.cookie),o=typeof r.text==="string"?r.text:"",i=Qs(o);if(i.kind==="other")console.error(`Error: this is not a \`slack poll\` poll (don't know how to count its votes).
552
- ${M(t.link)}`),process.exit(gt);if(i.kind==="closed"){console.error(`\u2713 Poll closed: ${M(i.question)}`);for(let p of fm(i.tallies))console.log(p);return}let l=new Set;if(typeof r.user==="string"&&r.user)l.add(r.user);let u=await tg(e,n,s,t.cookie),f=yh(i.choices,u,l,i.multi);console.error(`${M(i.question)}${i.deadline?` (closes ${i.deadline})`:""}`);for(let p of fm(f.tallies))console.log(p);let a=f.tallies.reduce((p,h)=>p+h.count,0);if(console.error(` ${a} vote(s) total${i.multi?" (multiple choice)":""}`),t.names)for(let p=0;p<f.voters.length;p++){if(!f.voters[p].length)continue;let h=await Promise.all(f.voters[p].map((g)=>Re(e,g,t.cookie)));console.error(` ${_t[p].glyph} ${h.map((g)=>`@${M(g)}`).join(", ")}`)}let c=i.multi?[]:f.ambiguous,d=go(o,c);if(d!==o&&!t.noNotify)try{await Kt(t.writeToken??e,n,s,d,t.writeToken?t.writeCookie:t.cookie,!0)}catch(p){console.error(` (could not add the notice to the poll text: ${p instanceof Error?p.message:String(p)})
553
- `+" Only the poster can rewrite a message \u2014 if the bot posted the poll, add --as-bot.")}if(f.ambiguous.length){let p=await Promise.all(f.ambiguous.map((h)=>Re(e,h,t.cookie)));console.error(`\u26A0 One vote per person, but some people pressed several (invalid votes): ${p.map((h)=>`@${M(h)}`).join(", ")}`)}if(!t.close)return;await Kt(t.writeToken??e,n,s,mh(i.question,f.tallies),t.writeToken?t.writeCookie:t.cookie,!0);try{await It(t.writeToken??e,n,s,xc,t.writeToken?t.writeCookie:t.cookie),await qt(t.writeToken??e,n,s,Zs,t.writeToken?t.writeCookie:t.cookie)}catch{}console.error(`\u2713 Closed the poll: ${M(t.link)}`)}async function sS(e){let t=await Yr(e);for(let n of Gr(t,!1))console.log(n);if(!t.ok)process.exit(1)}function Ho(){let e=Ne();if(!e)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
554
- Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(1);return e}async function pm(e,t,n,s){let r=await vt(n,e,s);return Ht(t,r)}function hm(e){try{return Bm(e)}catch{console.error(`Error: cannot parse --due "${e}" \u2014 use an ISO datetime (2026-11-01T18:00) or a Unix ts.`),process.exit(2)}}function Bm(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 jm(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 rS(e,t){qe(t.message,t.allowUrlAdjacent);let n=Gt(e,t.cookie),{ref:s,threadTs:r}=$t(t.target),o;if(t.channelId)o=t.channelId;else if(t.userId)o=await Ht(e,t.userId,t.cookie);else o=await we(e,s,t.cookie);let i=Bm(t.at),l=new Date(i*1000).toISOString(),u=await n();if(!t.asBot&&await _l(e,o,u?.userId,t.cookie))console.error(`Warning: "${t.target}" is a DM to yourself \u2014 Slack will NOT notify you when this fires.
555
- `+` To be notified, schedule it as the bot: slack schedule send '${t.target}' '...' --at '${t.at}' --as-bot`);let f=De(o,t.message,String(i),u?.userId??""),a=t.targetOverride?` [${t.targetOverride} \u2192 ${o}]`:"";if(t.code!==f){let d=await ri(e,o,t.cookie);Se(t.code,f,["--- Scheduling message -----------------------",Ee(u,{asBot:t.asBot,pad:9}),` To: ${s}${r?` (thread ${r})`:""}${a}`,` At: ${jm(i)}`,` Message: ${t.message}`,"---------------------------------------------"],d,new Date(i*1000))}let c=await Xh(e,o,t.message,i,r,t.cookie);if(console.log(`\u2713 Scheduled (id: ${c}, at: ${l})`),t.asBot){if(console.error(` Scheduled as the bot \u2014 the user token cannot see or cancel it. Use the same flag:
532
+ slack ask --void='${W(t.link)}' --reask${t.asBot?" --as-bot":""} \u2026`),process.exit(ae);if(!([...`${i}
533
+ ${a}`.matchAll(/<@([UW][A-Z0-9]+)(?:\|[^>]*)?>/g)].some((x)=>x[1]!==n?.userId)||/<!(?:here|channel|everyone)/.test(`${i}
534
+ ${a}`)||s.channelId.startsWith("D")))console.error("\u2717 The question would be addressed to nobody \u2014 keep an @mention of who can answer"),process.exit(ae);let y=t.lang?uc({flag:t.lang})?.lang??r.lang:r.lang,k=d.slice(0,Kt),w=d.slice(Kt),u=typeof s.msg.text==="string"?s.msg.text:"",l=hc(i,a,k,w,r.threadOnly,y,r.explain),h=_o(u);if(h.length)l=Eo(l,h,y);if(He(l,t.allowUrlAdjacent),l===u){console.error("No changes.");return}let m=De("ask-edit",`${s.channelId}:${s.ts}`,l,n?.userId??"");if(t.code!==m){let x=(S,E,I)=>E===I?[` ${S}: (unchanged)`]:[` ${S}:`,...E.split(`
535
+ `).map((N)=>` - ${N}`),...I.split(`
536
+ `).map((N)=>` + ${N}`)];Se(t.code,m,["--- Editing question --------------------------",Ee(n,{asBot:t.asBot}),` ${W(t.link)}`,...x("Question",r.question,i),...x("Body",r.body,a),...f?[" Choices (nobody has answered yet \u2014 pills are re-seeded):",...c.map((S,E)=>` - ${E+1}. ${Be(S)}`),...d.map((S,E)=>` + ${E+1}. ${Be(S)}`)]:[" Choices: (unchanged)"],...y!==r.lang?[` Language: ${r.lang} \u2192 ${y} (the instructions are rewritten)`]:[],"----------------------------------------------"])}await zt(e,s.channelId,s.ts,l,t.cookie,!0);let b=k.length?qt:ot,_=Qs(u)??ot;if(f){let x=(S)=>r.explain?[S,fn]:[S];for(let S of[...r.reactable.map((E,I)=>Re[I].name),...x(_)])try{await Yt(e,s.channelId,s.ts,S,t.cookie)}catch{}await Bo([...k.map((S,E)=>Re[E].name),...x(b)],(S)=>Lt(e,s.channelId,s.ts,S,t.cookie),(S,E)=>console.error(` (could not add reaction ${S}: ${E instanceof Error?E.message:String(E)})`))}else if(_!==b)try{await Lt(e,s.channelId,s.ts,b,t.cookie),await Yt(e,s.channelId,s.ts,_,t.cookie)}catch(x){console.error(` (could not swap the marker to ${b}: ${x instanceof Error?x.message:String(x)})`)}console.error(`\u2713 Edited: ${W(t.link)}`)}async function OS(e,t){let n={kind:"ask",limit:t.limit};if(t.channel)n.channel=t.channel;let s=Uc(n);if(!s)console.error(`Error: ${ir}
537
+ (${Pt()})`),process.exit(ae);let r;if(t.stale){if(r=ms(t.stale),r===void 0)console.error(`Error: --stale needs a duration like 24h / 3d (got ${W(t.stale)})`),process.exit(ae)}let o=[];for(let a of s){if(r!==void 0&&a.sent_at>r)continue;let c=a.as_bot?e.bot:e.user,d=a.permalink||`${a.channel}:${a.ts}`,f="unknown",p=(a.text.split(`
538
+ `)[0]??"").replace(/^:question: /,""),g;if(c)try{let k=await Dr(c,{channelId:a.channel,ts:a.ts,threadTs:a.thread_ts??void 0},a.as_bot?void 0:e.cookie);if(!k.msg)f="gone";else{let w=Rt(typeof k.msg.text==="string"?k.msg.text:"");if(f=w.kind==="resolved"?"answered":w.kind==="other"?"edited":w.kind,w.kind!=="other"&&w.question)p=w.question;if(w.kind==="resolved")g=w.answer}}catch{f="unknown"}if(t.state!=="all"&&f!==t.state)continue;let y={state:f,age_h:Math.round((Date.now()-a.sent_at)/3600000),asBot:!!a.as_bot,channel:a.channel,target:a.target??a.channel,link:d,question:Be(p)};if(g!==void 0)y.answer=g;o.push(y)}if(t.json)console.log(JSON.stringify(o));else{for(let a of o)console.log(`${a.state.padEnd(8)} ${String(a.age_h).padStart(4)}h ${a.asBot?"bot ":"user"} ${W(a.target)} ${a.link}
539
+ ${W(a.question).slice(0,100)}`);console.error(`${o.length} question(s)${t.state==="all"?"":` in state "${t.state}"`}${t.stale?`, older than ${t.stale}`:""}.`)}let i=o.filter((a)=>a.state==="open");if(t.stale&&i.length)for(let a of[!1,!0]){let c=i.filter((d)=>d.asBot===a);if(!c.length)continue;console.error(`To void them (${c.length}, ${a?"bot":"user"}):
540
+ slack ask ${c.map((d)=>`--void='${d.link}'`).join(" ")} --reason 'stale'${a?" --as-bot":""}`)}}async function IS(e,t,n){if(n.has(e.channel))return n.get(e.channel);let s={channelId:e.channel,ts:e.ts,threadTs:e.thread_ts??void 0},r=async(i)=>{if(!i)return!1;try{return await Dr(i,s),!0}catch(a){if(a instanceof it)throw a;return/channel_not_found|not_in_channel/.test(a instanceof Error?a.message:String(a))?!1:void 0}},o;if(await r(t)===!1)for(let[i,a]of Io()){if(a.kind!=="bot"||i===ln("IDENTITY"))continue;let c={...process.env};if("error"in Ro(i,c))continue;if(await r(c.SLACK_BOT_TOKEN)){o=i;break}}return n.set(e.channel,o),o}function RS(e,t){if(!e.identity||e.identity===ln("IDENTITY"))return t;let n={...process.env},s=Ro(e.identity,n);if("error"in s)return s.error;if(s.kind==="bot")return{bot:n.SLACK_BOT_TOKEN,user:n.SLACK_TOKEN};if(!n.SLACK_TOKEN)return`asked as @${e.identity}, a profile identity: run the pass as that identity`;return{user:n.SLACK_TOKEN}}async function Bm(e,t){let n=[];Xc(0);let s=qc(t.sinceMs);if(!s)console.error(`Error: ${ir}
541
+ (${Pt()})`),process.exit(ae);let r=Date.now()-86400000,o=s.filter((u)=>(!t.channel||u.channel===t.channel||u.target===t.channel)&&(!t.only||t.only.has(`${u.channel}:${u.ts}`))&&(!t.skip||u.sent_at>=r||!t.skip.has(`${u.channel}:${u.ts}`))),i=[],a={unanswered:0,ambiguous:0,resolved:0,void:0,explain:0,throttled:0},c=[],d=[],f=e.user?(await je(e.user,e.cookie))?.team??"":e.bot?(await je(e.bot))?.team??"":"",p=new Map,g=new Map;o.reverse();for(let[u,l]of o.entries()){if(l.team&&f&&l.team!==f){p.set(l.team,(p.get(l.team)??0)+1);continue}let h=l.permalink||`${l.channel}:${l.ts}`,m=!!l.as_bot;n.push(`${l.channel}:${l.ts}`);let b=l.delivered_cursor??void 0;try{if(!l.identity&&m){let j=await IS(l,e.bot,g);if(j){if(l.identity=j,t.push)ng(l.channel,l.ts,j)}}let _=RS(l,e);if(typeof _==="string"){d.push(`${h}: ${_}`);continue}let x=m?_.bot:_.user;if(!x){d.push(`${h}: ${m?"asked with --as-bot, but there is no bot token":"no user token"}`);continue}let S=m?void 0:_.cookie,E={channelId:l.channel,ts:l.ts,threadTs:l.thread_ts??void 0},I=await Dr(x,E,S);if(!I.msg){d.push(`${h}: message not found (deleted?)`);continue}let N=await uy(x,{channelId:l.channel,ts:l.ts,msg:I.msg},S),C=N.parsed;if(C.kind==="resolved"){if(a.resolved++,t.push)Jo(l.channel,l.ts,0);continue}if(C.kind==="void"){if(a.void++,t.push)Jo(l.channel,l.ts,di);continue}if(C.kind==="other"){d.push(`${h}: cannot be read as a \`slack ask\` question \u2014 ${Zs(N.text)}`);continue}if(!N.audience.size&&!N.broadcast){d.push(`${h}: the question is addressed to nobody`);continue}let A=dy(N,C,E,{timeout:0,link:h,asBot:m,json:!1,cookie:S,after:b}),F=oy(x,A,!0),v=await F.poll(),O=F.state.unchosen;if(F.state.voided){if(a.void++,t.push)Jo(l.channel,l.ts,di);continue}let M=Xn(h,m,b);if(F.state.explainNow.length)a.explain++,c.push(`${h}: \u2139\uFE0F an explanation was requested (${F.state.explainNow.map((j)=>`<@${j}>`).join(" ")}) \u2014 explain in the thread`);let J={row:l,link:h,question:C.question,collect:M,alive:sg(l)};if(v)i.push({...J,answer:v.answer,how:v.how,freeText:!1,...v.ts?{answeredTs:v.ts}:{}});else if(O&&!O.ambiguous&&O.text!==l.delivered_answer)i.push({...J,answer:O.text,how:"reply (not a choice)",freeText:!0,cursor:Mt(l.ts,b,O.ts),answeredTs:O.ts});else if(O?.ambiguous)a.ambiguous++;else a.unanswered++}catch(_){if(_ instanceof it){n.pop(),a.throttled=o.length-u,d.push(`rate-limited by Slack (${_.message}): ${a.throttled} question(s) not checked this pass`);break}d.push(`${h}: ${_ instanceof Error?_.message:String(_)}`)}}if(t.push)PS(i,t.selfArgs??[],d);let y=(u)=>!u.pushed&&u.row.pushed_answer!==u.answer,k=t.watch?i.filter((u)=>u.pushed):t.undelivered?i.filter(y):i,w={checked:n,throttled:a.throttled>0};if(t.watch&&!k.length&&!d.length)return w;if(t.json)for(let u of k){let l=u.row;console.log(JSON.stringify({id:l.id,link:u.link,channel:l.channel,ts:l.ts,asked_at:l.sent_at,question:u.question,answer:u.answer,how:u.how,free_text:u.freeText,sender:{session_id:l.session_id??null,cli:l.cli??null,agent_pid:l.agent_pid??null,pid:l.pid,alive:u.alive,cwd:l.cwd,git_branch:l.git_branch??null,host:l.host??null},delivered_at:l.delivered_at??null,collect:u.collect,...t.push?{pushed:u.pushed??null}:{},...u.undelivered?{undelivered:u.undelivered}:{}}))}else{let u=new Map;for(let l of k){let h=l.row.session_id?`session ${l.row.session_id}`:`pid ${l.row.agent_pid??l.row.pid}`;u.set(h,[...u.get(h)??[],l])}for(let[l,h]of u){let m=h[0].row;console.log(`${W(l)} ${W(m.cli??"?")} pid ${m.agent_pid??m.pid} ${h[0].alive?"(alive)":"(gone)"}${m.git_branch?` branch=${W(m.git_branch)}`:""} cwd=${W(m.cwd)}`);for(let b of h){if(console.log(` ${W(b.link)} (${Gn(b.row.sent_at/1000)})`),console.log(` Q: ${W(Be(b.question))}`),console.log(` A: ${W(Be(b.answer))} \u2014 ${W(b.how)}${b.freeText?" \u2014 not a decision":""}`),console.log(` collect: ${W(b.collect)}`),b.undelivered)console.log(` undelivered: ${W(b.undelivered)}`);if(b.pushed)console.log(` pushed to pid ${b.pushed.pid}${b.pushed.collected?", collected \u2705":""}`)}}}for(let u of d)console.error(` (${W(u)})`);for(let u of c)console.error(` (${W(u)})`);for(let[u,l]of p)console.error(` (${l} question(s) belong to another workspace "${W(u)}" \u2014 check with slack -w <name> ask --pending)`);return console.error(`${i.length} answered but not collected, ${a.unanswered} unanswered`+(a.ambiguous?`, ${a.ambiguous} with a reply matching several choices (unsettled)`:"")+(a.resolved?`, ${a.resolved} \u2705 already collected`:"")+(a.void?`, ${a.void} voided`:"")+(a.explain?`, ${a.explain} with an \u2139\uFE0F explain request`:"")+(a.throttled?`, ${a.throttled} not checked (rate-limited)`:"")+(t.push?`, ${i.filter((u)=>u.pushed).length} pushed to the asker`:"")+(t.undelivered?`, ${i.filter(y).length} undelivered`:"")+` \u2014 checked ${o.length} uncollected question(s) (log: ${Pt()})`),w}async function vS(e,t,n){let s=!1,r=new Set,o=!0,i=async()=>{if(s)return;s=!0;try{while(o||r.size){let d=o?void 0:new Set(r);o=!1,r.clear();try{await e(d)}catch(f){console.error(`slack ask --watch: pass failed: ${ge(f)}`)}}}finally{s=!1}},a=process.env.SLACK_RELAY_URL,c=process.env.SLACK_RELAY_TOKEN;if(a&&c){let d=Ha(a,c,void 0,{transport:qa(process.env.SLACK_RELAY_TRANSPORT)});(async()=>{for(let f=0;;f++){try{await d(void 0,new AbortController().signal,{hello:()=>{f=0},bell:(p,g)=>{let y=`${g.channel}:${g.thread_ts??g.ts}`;if(!(qc(t())??[]).some((w)=>`${w.channel}:${w.ts}`===y))return;r.add(y),setTimeout(()=>{i()},3000)}})}catch(p){console.error(`slack ask --watch: relay: ${p instanceof Error?p.message:String(p)} \u2014 reconnecting`)}await new Promise((p)=>setTimeout(p,ds(f,2000,300000)))}})()}else console.error("slack ask --watch: no SLACK_RELAY_URL / SLACK_RELAY_TOKEN \u2014 checking every interval only");for(;;)o=!0,await i(),await new Promise((d)=>setTimeout(d,typeof n==="number"?n:n()))}function PS(e,t,n){let s=sp(yt(Za(process.env.XDG_STATE_HOME||yt(ri(),".local","state")),"ask-push.lock"));if(!s){n.push("another `ask --pending --push` pass is running: nothing pushed by this one");return}try{let r;for(let o of e){let i=o.row,a=i.pushed_answer===o.answer,c=i.agent_pid??i.pid;if(!a){let f=c,p=o.alive?f:np(i.cwd,r??=tp());if(p===void 0){o.undelivered=`the asker (pid ${f}) is gone and no live agent runs in ${i.cwd}`;continue}let g=Zf({link:o.link,answer:o.answer,how:o.how,question:o.question,freeText:o.freeText,collected:!o.freeText,...o.alive?{}:{goneAsker:f},tag:Vf(i.sent_at,o.answeredTs?Number(o.answeredTs)*1000:void 0)}),y=ep(p,g);if(y===void 0){o.undelivered=`pid ${p} did not take the push over ay \u2014 tried again next pass`,n.push(`${o.link}: ${o.undelivered}`);continue}c=y,tg(i.channel,i.ts,o.answer)}else if(o.freeText)continue;let d=!1;if(o.freeText)Kc(i.channel,i.ts,o.answer,o.cursor??"");else{let f=i.delivered_cursor?[`--after=${i.delivered_cursor}`]:[],p=i.identity&&i.identity!==ln("IDENTITY")?[`@${i.identity}`]:[],g=Ox(process.execPath,[...process.argv.slice(1,2),...p,...t,"ask",`--waitFor=${o.link}`,"--timeout","0",...i.as_bot?["--as-bot"]:[],...f],{encoding:"utf8",timeout:120000,stdio:["ignore","pipe","pipe"]});if(d=g.status===0,!d)n.push(`${o.link}: pushed, but collecting it exited ${g.status??"on a signal"} \u2014 collect by hand: ${o.collect}`)}o.pushed={pid:c,collected:d}}}finally{s()}}async function ly(e,t,n,s,r){let o=W(t.link);try{let i=Wp(t.parsed.question,n,t.parsed.lang,t.parsed.body||void 0,s);await zt(e,t.channelId,t.ts,i,r,!0)}catch(i){return console.error(`\u2717 ${o}: failed to rewrite: ${i instanceof Error?i.message:String(i)}`),!1}for(let i of[...t.parsed.reactable.map((a,c)=>Re[c].name),t.seedMarker,...t.parsed.explain?[fn]:[]])try{await Yt(e,t.channelId,t.ts,i,r)}catch{}try{await Lt(e,t.channelId,t.ts,pc,r)}catch(i){console.error(` (${o}: could not add the \uD83D\uDEAB reaction: ${i instanceof Error?i.message:String(i)})`)}return console.error(`\u2713 Voided: ${o}`),!0}async function LS(e,t){let n=await je(e,t.cookie);if(t.supersededBy){let a=W(t.supersededBy),c=!1;try{let d=await Pl(e,t.supersededBy,t.cookie);if(c=!!d?.msg,!d)console.error(`Error: --superseded-by must be a message permalink (or 'C\u2026:1700000000.000100'): ${a}`),process.exit(ae)}catch(d){console.error(`Error: cannot check --superseded-by: ${a} (${d instanceof Error?d.message:String(d)})`),process.exit(ae)}if(!c)console.error(`Error: --superseded-by message not found: ${a}`),process.exit(ae)}let s=[],r=0;for(let a of t.links){let c=W(a),d=await Pl(e,a,t.cookie);if(!d){console.error(`\u2717 ${c}: not a permalink (or 'C\u2026:1700000000.000100')`),r++;continue}if(!d.msg){console.error(`\u2717 ${c}: message not found`),r++;continue}let f=d.msg;if(!(!!n?.userId&&f.user===n.userId||!!n?.botId&&f.bot_id===n.botId)){console.error(`\u2717 ${c}: not a question posted by you (${mi(n,t.asBot)}), so it cannot be voided${t.asBot?"":" \u2014 if the bot posted it, use --as-bot"}`),r++;continue}let g=typeof f.text==="string"?f.text:"",y=Rt(g),k=!1;if(y.kind==="void"){console.error(`- ${c}: already voided (nothing to do)`);continue}if(y.kind==="resolved"){console.error(`\u2717 ${c}: an answered question cannot be voided (answer: ${W(y.answer.split(`
542
+ `)[0]??"")})`),r++;continue}if(y.kind!=="open"){let l=Up(g);if(!l){console.error(`\u2717 ${c}: cannot be read as a \`slack ask\` question \u2014 ${Zs(g)}`),r++;continue}let h=G(f.reactions).map(L).filter((m)=>G(m.users).includes(n?.userId??"\x00")).map((m)=>Re.findIndex((b)=>b.name===m.name)).filter((m)=>m>=0);y={kind:"open",question:l.question,body:l.body,reactable:Array.from({length:h.length?Math.max(...h)+1:0},()=>""),overflow:[],threadOnly:!0,lang:dc(g)??"ja",explain:G(f.reactions).map(L).some((m)=>m.name===fn&&G(m.users).includes(n?.userId??"\x00"))},k=!0}let w=k?G(f.reactions).map(L).some((l)=>l.name===qt&&G(l.users).includes(n?.userId??"\x00"))?qt:ot:Qs(g)??ot,u=G(f.reactions).map(L).filter((l)=>typeof l.name==="string"&&Re.some((h)=>h.name===l.name)).filter((l)=>G(l.users).some((h)=>h!==n?.userId)).map((l)=>`:${String(l.name)}:`);s.push({link:a,channelId:d.channelId,ts:d.ts,text:g,parsed:y,seedMarker:w,pressed:u,...k?{unreadable:k}:{}})}if(!s.length)console.error(r?"No questions can be voided.":"Nothing to do."),process.exit(r?ae:0);let o=De("ask-void",...s.map((a)=>`${a.channelId}:${a.ts}`),t.reason,t.supersededBy??"",n?.userId??"");if(t.code!==o)Se(t.code,o,["--- Void -----------------------------------------",Ee(n,{asBot:t.asBot}),` Reason: ${t.reason?W(t.reason):"(none)"}`,...t.supersededBy?[` Replaced: ${W(t.supersededBy)}`]:[],` ${s.length} question(s):`,...s.map((a)=>` \u2022 ${W(a.link)}
543
+ ${W(a.parsed.question.split(`
544
+ `)[0]??"").slice(0,100)}`+(a.pressed.length?`
545
+ (already pressed: ${a.pressed.join(" ")} \u2014 left in place, never collected)`:"")+(a.unreadable?`
546
+ \u26A0 its layout no longer reads as an ask (edited by hand?) \u2014 voided from a best-effort read: question and the rest of the text kept as they are`:""))," Each becomes \uD83D\uDEAB (body kept, options and instructions removed); our pills and marker (\u2795, or \u2753) come off; a \uD83D\uDEAB reaction is added.",...r?[` (${r} link(s) above were refused and will be skipped)`]:[],"----------------------------------------------"]);let i=0;for(let a of s)if(!await ly(e,a,t.reason,t.supersededBy,t.cookie))i++;process.exit(i||r?ae:0)}async function NS(e,t){let n=ht(t.link),s,r,o;if(n?.ts)s=n.channel,r=n.ts,o=n.threadTs&&n.threadTs!==n.ts?n.threadTs:void 0;else{let w=t.link.match(/^([A-Za-z0-9]+):(\d{10}\.\d{6})$/);if(!w)console.error(`Error: --waitFor needs the permalink of a question (or 'C\u2026:1700000000.000100').
547
+ `+` Got: ${W(t.link)}`),process.exit(ae);s=w[1],r=w[2]}let i=await Dr(e,{channelId:s,ts:r,threadTs:o},t.cookie);if(!i.msg)console.error(`Error: message not found: ${W(t.link)}`),process.exit(ae);let a=i.msg,c=await uy(e,{channelId:s,ts:r,msg:a},t.cookie),{text:d,parsed:f,audience:p,broadcast:g,askerUserId:y,askerBotId:k}=c;if(f.kind==="other")console.error(`Error: this cannot be read as a \`slack ask\` question.
548
+ Reason: ${Zs(d)}
549
+ ${W(t.link)}
550
+ (the pressed reactions are still there: check with slack read '${W(t.link)}')`),process.exit(ae);if(f.kind==="void"){if(ay(f,t.link),t.json)await yn(e,{json:!0,shown:t.link,asBot:t.asBot,cookie:t.cookie},{status:"void",answer:null,reason:f.reason,...f.supersededBy?{supersededBy:f.supersededBy}:{},notes:[],cursor:Mt(r,t.after)});process.exit(di)}if(f.kind==="resolved"){console.error(`\u2713 Answered: ${W(f.question)}`);let w=typeof L(a.edited).ts==="string"?String(L(a.edited).ts):void 0,u=Kp(d),l=!1,h=(x)=>{if(l||!u.byReply)return!1;if(w&&Number(x.ts)>Number(w))return!1;let S=typeof x.text==="string"?x.text.trim():"",E=S===f.answer||u.n!==void 0&&(new RegExp(`^[(\uFF08]?${u.n}(?![0-9])`).test(S)||qp(S,f.answer,u.n));if(E)l=!0;return E},m=t.after,b=[];if(p.size||g){let x=(S)=>typeof S==="string"&&!!S&&S!==y&&(g||p.has(S));b=await ry(e,{channelId:s,ts:r,threadOnly:!!o||!s.startsWith("D"),replyCount:Number(a.reply_count)||0,isAnswerer:x,askerUserId:y,askerBotId:k,...o?{threadParentTs:o}:{},...t.cookie?{cookie:t.cookie}:{}},m,h)}let _=Mt(r,m,...b.map((x)=>x.ts));await yn(e,{json:t.json,shown:t.link,asBot:t.asBot,cookie:t.cookie},{status:"answered",answer:f.answer,notes:b,cursor:_}),Jc(s,r,f.answer,_);return}if(!p.size&&!g)console.error(`Error: this question is addressed to nobody, so valid answerers cannot be determined: ${W(t.link)}`),process.exit(ae);if(t.timeout>0)console.error(` Waiting for an answer (up to ${t.timeout}s)\u2026 Ctrl-C to stop`);await iy(e,dy(c,f,{channelId:s,ts:r,threadTs:o},t))}async function uy(e,t,n){let{msg:s}=t,r=typeof s.text==="string"?s.text:"",o=Rt(r),i=typeof s.user==="string"?s.user:"",a=typeof s.bot_id==="string"?s.bot_id:"",c=/<!(here|channel|everyone)(\^[^>]*)?(\|[^>]*)?>/.test(r),d=new Set;for(let f of r.matchAll(/<@([UW][A-Z0-9]+)>/g))if(f[1]!==i)d.add(f[1]);if(o.kind!=="other"&&!d.size&&!c){let f=await yi(e,t.channelId,n);if(f&&f!==i)d.add(f)}return{text:r,parsed:o,audience:d,broadcast:c,askerUserId:i,askerBotId:a}}function dy(e,t,n,s){let r={channelId:n.channelId,ts:n.ts,question:t.question,reactable:t.reactable,overflow:t.overflow,threadOnly:t.threadOnly,seedMarker:Qs(e.text)??ot,lang:t.lang,audience:e.audience,broadcast:e.broadcast,askerUserId:e.askerUserId,askerBotId:e.askerBotId,timeout:s.timeout,shown:s.link,asBot:s.asBot,json:s.json,explain:t.explain,explainExit:!!s.explainExit};if(n.threadTs)r.threadParentTs=n.threadTs;if(s.cookie)r.cookie=s.cookie;if(s.after)r.after=s.after;return r}var mt=3;function MS(e){return`slack poll --results='${e}'`}async function BS(e,t){let{ref:n,threadTs:s}=At(t.target,!1),r=t.cookie,o=Vt(e,r),i;if(t.channelId)i=t.channelId;else if(t.userId)i=await Gt(e,t.userId,r);else i=await we(e,n,r);let a=(await o())?.userId??"",c=await yi(e,i,r);if(!t.asBot&&!!a&&c===a)console.error(`Warning: "${t.target}" is a DM to yourself \u2014 Slack will NOT notify you of your own message.
551
+ `+` To reach yourself with a notification, post as the bot: slack poll '${t.target}' '...' --as-bot`);let d=kr(Ue(t.question)),f=kr(Ue(t.body??"")),p=t.mentionToken??e,g=await mn(p,d.text,i,t.mentionCookie),y=f.text?await mn(p,f.text,i,t.mentionCookie):{text:"",resolved:[],unresolved:[]},k=g.text,w=y.text;for(let F of Zo([...g.unresolved,...y.unresolved]))console.error(`\u26A0 ${W(F)}`);let u=t.choices.map(Ue),l=!!t.multi,h=t.until??"",m=Bh(k,w,u,{multi:l,deadline:h});He(m,t.allowUrlAdjacent);let b="",_="?";try{let F=await at(e,i,1,void 0,void 0,r),v=G(F.messages).map(L).filter((O)=>O.subtype===void 0||O.subtype===null)[0];b=typeof v?.text==="string"?v.text:"",_=typeof v?.user==="string"?await ve(e,v.user,r):typeof v?.username==="string"?v.username:"?"}catch{}let x=await o(),S=await gi(e,i,r),E=De(i,s??"",b,m,x?.userId??"");if(t.code!==E){let F=await Bt(e,i,n,r);Se(t.code,E,["--- Last message in channel ------------------",` ${_}: ${Ss(b.split(`
552
+ `)[0]??"").slice(0,100)}`,"--- Ballot (seeded as reactions) -------------",...u.map((v,O)=>` ${Et[O].glyph} ${sr(v)}`),"--- Posting ----------------------------------",Ee(x,{asBot:t.asBot}),` \u2192 ${F}${s?" \u2014 THREAD REPLY":" \u2014 NEW top-level message"}`,` Question: ${k}`,` Rule: ${l?"any number of votes per person (--multi)":"one vote per person"}${h?` \u2014 closes ${h}`:""}`," Note: your own votes are not counted (the pills are seeds you added, so they can't be told apart)","--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"],S)}let I=Vn("poll"),N=await Ht(e,i,m,s,!1,r,!0,I.metadata);await Bo([rr,...u.map((F,v)=>Et[v].name)],(F)=>Lt(e,i,N,F,r),(F,v)=>{let O=v instanceof Error?v.message:String(v);if(F===rr)console.error(` (could not add marker ${F}: ${O})`);else console.error(` (could not add reaction ${F}: ${O})`)});let C="";try{C=await qn(e,i,N,r)}catch{}let A=C||`${i}:${N}`;console.error(`\u2713 Posted: ${A}`),I.record({team:x?.team,channel:i,target:t.target,ts:N,threadTs:s,permalink:C,text:m,asBot:t.asBot}),console.log(MS(A)),console.error(` To close: slack poll --close='${A}'${t.asBot?" --as-bot":""}`)}async function jS(e,t,n){let s=ht(t),r,o,i;if(s?.ts)r=s.channel,o=s.ts,i=s.threadTs&&s.threadTs!==s.ts?s.threadTs:void 0;else{let c=t.match(/^([A-Za-z0-9]+):(\d{10}\.\d{6})$/);if(!c)console.error(`Error: --results/--close needs the permalink of a poll (or 'C\u2026:1700000000.000100').
553
+ `+` Got: ${W(t)}`),process.exit(mt);r=c[1],o=c[2]}let a;if(i){let c=L(await Ne(e,r,i,100,n));a=G(c.messages).map(L).find((d)=>d.ts===o)}else{let c=L(await at(e,r,1,o,void 0,n,!0));a=G(c.messages).map(L).find((d)=>d.ts===o)}if(!a)console.error(`Error: message not found: ${W(t)}`),process.exit(mt);return{channelId:r,ts:o,msg:a}}function jm(e){let t=Math.max(1,...e.map((n)=>n.count));return e.map((n,s)=>`${Et[s].glyph} ${String(n.count).padStart(3)} ${"\u2588".repeat(Math.round(n.count/t*20))}${n.count?" ":""}${n.choice}`)}async function WS(e,t){let{channelId:n,ts:s,msg:r}=await jS(e,t.link,t.cookie),o=typeof r.text==="string"?r.text:"",i=or(o);if(i.kind==="other")console.error(`Error: this is not a \`slack poll\` poll (don't know how to count its votes).
554
+ ${W(t.link)}`),process.exit(mt);if(i.kind==="closed"){console.error(`\u2713 Poll closed: ${W(i.question)}`);for(let y of jm(i.tallies))console.log(y);return}let a=new Set;if(typeof r.user==="string"&&r.user)a.add(r.user);let c=await Tg(e,n,s,t.cookie),d=Wh(i.choices,c,a,i.multi);console.error(`${W(i.question)}${i.deadline?` (closes ${i.deadline})`:""}`);for(let y of jm(d.tallies))console.log(y);let f=d.tallies.reduce((y,k)=>y+k.count,0);if(console.error(` ${f} vote(s) total${i.multi?" (multiple choice)":""}`),t.names)for(let y=0;y<d.voters.length;y++){if(!d.voters[y].length)continue;let k=await Promise.all(d.voters[y].map((w)=>ve(e,w,t.cookie)));console.error(` ${Et[y].glyph} ${k.map((w)=>`@${W(w)}`).join(", ")}`)}let p=i.multi?[]:d.ambiguous,g=Eo(o,p);if(g!==o&&!t.noNotify)try{await zt(t.writeToken??e,n,s,g,t.writeToken?t.writeCookie:t.cookie,!0)}catch(y){console.error(` (could not add the notice to the poll text: ${y instanceof Error?y.message:String(y)})
555
+ `+" Only the poster can rewrite a message \u2014 if the bot posted the poll, add --as-bot.")}if(d.ambiguous.length){let y=await Promise.all(d.ambiguous.map((k)=>ve(e,k,t.cookie)));console.error(`\u26A0 One vote per person, but some people pressed several (invalid votes): ${y.map((k)=>`@${W(k)}`).join(", ")}`)}if(!t.close)return;await zt(t.writeToken??e,n,s,jh(i.question,d.tallies),t.writeToken?t.writeCookie:t.cookie,!0);try{await Lt(t.writeToken??e,n,s,Lc,t.writeToken?t.writeCookie:t.cookie),await Yt(t.writeToken??e,n,s,rr,t.writeToken?t.writeCookie:t.cookie)}catch{}console.error(`\u2713 Closed the poll: ${W(t.link)}`)}async function US(e){let t=await so(e);for(let n of ro(t,!1))console.log(n);if(!t.ok)process.exit(1)}function br(){let e=Me();if(!e)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
556
+ Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(1);return e}async function Wm(e,t,n,s){let r=await Nt(n,e,s);return Gt(t,r)}function Um(e){try{return fy(e)}catch{console.error(`Error: cannot parse --due "${e}" \u2014 use an ISO datetime (2026-11-01T18:00) or a Unix ts.`),process.exit(2)}}function fy(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 py(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 JS(e,t){He(t.message,t.allowUrlAdjacent);let n=Vt(e,t.cookie),{ref:s,threadTs:r}=At(t.target),o;if(t.channelId)o=t.channelId;else if(t.userId)o=await Gt(e,t.userId,t.cookie);else o=await we(e,s,t.cookie);let i=fy(t.at),a=new Date(i*1000).toISOString(),c=await n();if(!t.asBot&&await Wl(e,o,c?.userId,t.cookie))console.error(`Warning: "${t.target}" is a DM to yourself \u2014 Slack will NOT notify you when this fires.
557
+ `+` To be notified, schedule it as the bot: slack schedule send '${t.target}' '...' --at '${t.at}' --as-bot`);let d=De(o,t.message,String(i),c?.userId??""),f=t.targetOverride?` [${t.targetOverride} \u2192 ${o}]`:"";if(t.code!==d){let g=await gi(e,o,t.cookie);Se(t.code,d,["--- Scheduling message -----------------------",Ee(c,{asBot:t.asBot,pad:9}),` To: ${s}${r?` (thread ${r})`:""}${f}`,` At: ${py(i)}`,` Message: ${t.message}`,"---------------------------------------------"],g,new Date(i*1000))}let p=await _g(e,o,t.message,i,r,t.cookie);if(console.log(`\u2713 Scheduled (id: ${p}, at: ${a})`),t.asBot){if(console.error(` Scheduled as the bot \u2014 the user token cannot see or cancel it. Use the same flag:
556
558
  `+` slack schedule ls --as-bot
557
- slack schedule rm '${t.target}' ${c} --as-bot`),o.startsWith("D"))try{let d=await Yr(e);if(!d.ok)for(let p of Gr(d,!0))console.error(p);else{let p=d.appId?`https://api.slack.com/apps/${d.appId}`:"https://api.slack.com/apps";console.error(`Note: if ${t.target} can't reply (app messaging may be off), enable Messages Tab: ${p} \u2192 App Home.`)}}catch{}}}async function gm(e,t,n,s){let r;if(n)r=n;else if(t)r=await we(e,t,s);let i=(await Vh(e,r,s)).scheduled_messages??[];if(i.length===0){console.log("(no scheduled messages)");return}for(let l of i){let u=new Date(l.post_at*1000).toISOString();console.log(`${l.id} ${u} [${l.channel_id}] ${l.text.split(`
558
- `)[0]?.slice(0,80)??""}`)}}async function mm(e,t){let n;if(t.channelId)n=t.channelId;else n=await we(e,t.target,t.cookie);let s=await Be(e,t.cookie),r=De(n,t.id,s?.userId??"");if(t.code!==r)Se(t.code,r,["--- Deleting scheduled message ---------------",Ee(s,{asBot:t.asBot,pad:9}),` Channel: ${t.target}${t.targetOverride?` [${t.targetOverride} \u2192 ${n}]`:""}`,` ID: ${t.id}`,"---------------------------------------------"]);await Zh(e,n,t.id,t.cookie),console.log(`\u2713 Deleted scheduled message ${t.id}`)}async function ym(e,t){if(t.comment!==void 0)qe(t.comment,t.allowUrlAdjacent);let n=Gt(e,t.cookie),{statSync:s,existsSync:r}=await import("fs"),{basename:o}=await import("path");for(let h of t.filePaths)if(!r(h))console.error(`Error: file not found: ${h}`),process.exit(1);let{ref:i,threadTs:l}=$t(t.target),u;if(t.channelId)u=t.channelId;else if(t.userId)u=await Ht(e,t.userId,t.cookie);else u=await we(e,i,t.cookie);if(await _l(e,u,(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 f=t.filePaths.length>1,a=t.filePaths.map((h)=>{let g=o(h),y=f?g:t.title??g;return{fp:h,filename:g,title:y,sizeFmt:ni(s(h).size)}}),c=await n(),d=De(u,...a.flatMap((h)=>[h.fp,h.title]),c?.userId??"");if(t.code!==d){let h=` To: ${i}${l?` (thread ${l})`:""}`,g=f?[`--- Uploading ${a.length} files ------------------------`,Ee(c,{pad:7}),h,...a.map((y)=>` ${y.filename} (${y.sizeFmt})`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]:["--- Uploading file ---------------------------",Ee(c,{pad:7}),h,` File: ${a[0].fp}`,` Title: ${a[0].title}`,` Size: ${a[0].sizeFmt}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"];Se(t.code,d,g)}let p=a.length;for(let h=0;h<p;h++){let g=a[h],y={title:g.title};if(l!==void 0)y.threadTs=l;if(t.comment!==void 0&&h===0)y.initialComment=t.comment;let{fileId:m,permalink:w}=await yg(e,u,g.fp,y,t.cookie),k=p>1?`[${h+1}/${p}] `:"";console.log(`${k}\u2713 Uploaded (file_id: ${m}${w?`, url: ${w}`:""})`)}}async function oS(e,t,n){let s=n.channel?await we(e,n.channel,t):void 0,r=[],o=1,i=1;do{let u={page:o,count:200};if(n.types)u.types=n.types;if(s)u.channel=s;if(n.user)u.user=n.user;let f=O(await Wh(e,u,t));for(let a of G(f.files))r.push(O(a));i=Number(O(f.paging).pages??1),o++}while(r.length<n.limit&&o<=i);let l=r.slice(0,n.limit);if(n.format==="jsonl"){for(let u of l)console.log(JSON.stringify({id:u.id??null,name:u.name??u.title??null,filetype:u.filetype??null,size:u.size??null,user:u.user??null,created:u.created??null,permalink:u.permalink??null}));return}for(let u of l){let f=String(u.id??""),a=typeof u.name==="string"?u.name:typeof u.title==="string"?u.title:f,c=typeof u.filetype==="string"?u.filetype:"?",d=typeof u.size==="number"?ni(u.size):"";console.log(`${f} ${c.padEnd(7)} ${d.padStart(9)} ${a}`)}}function ai(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 iS(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(O(n).text??O(n).name??O(n).value??"")).filter(Boolean).join(", ");for(let n of["rich_text","select","user","date","number","checkbox","email","phone"]){let s=e[n];if(s!=null)return typeof s==="object"?JSON.stringify(s):String(s)}return""}async function aS(e,t,n,s){let r=ai(n);if(!r)throw Error(`Not a list ID or list URL: ${n}
559
- `+"Expected F\u2026 or https://<ws>.slack.com/lists/<TEAM>/<F-id>");let o=[],i;do{let u={limit:200};if(i)u.cursor=i;let f=s.asBot?await Mc(gr(),r,u):O(await Hh(e,r,u,t));for(let c of G(f.items??f.records))o.push(O(c));let a=O(f.response_metadata).next_cursor;i=typeof a==="string"&&a?a:void 0}while(i&&o.length<s.limit);let l=o.slice(0,s.limit);if(s.format==="jsonl"){for(let u of l)console.log(JSON.stringify(u));return}for(let u of l){let f=String(u.id??""),a=G(u.fields).map(O).map((c)=>{let d=String(c.key??c.column_id??"?"),p=iS(c);return p?`${d}=${p}`:""}).filter(Boolean);console.log(`${f} ${a.join(" | ")}`)}}function gr(){let e=Ne();if(!e)console.error(`Error: Slack List writes go through the public slackLists.* API, which needs a bot token (xoxb-) \u2014 none was found.
560
- `+" Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell)."),process.exit(1);return e}async function ci(e){let t=[];try{t=(await Ut(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).
561
- `+" Add it under OAuth & Permissions \u2192 Bot Token Scopes in the Slack app config, then reinstall the app."),process.exit(1)}async function cS(e,t){try{let n=await Lc(e);if(n.url&&n.teamId)return`${n.url.replace(/\/$/,"")}/lists/${n.teamId}/${t}`}catch{}return t}async function Wm(e,t){let n=await Mc(e,t,{limit:1,includeList:!0}),s=Sh(O(n.list));if(!s.length)throw Error(`could not read the column schema of list ${t}`);return s}function li(e){console.error(ge(e)),process.exit(1)}async function lS(e){let t=e.cols.map(Dh),n=xh(t),s=gr();await ci(s);let r=await Be(s),o=De("lists-create",e.name,JSON.stringify(n),String(e.todo),r?.userId??"");if(e.code!==o)Se(e.code,o,["--- Creating Slack List ----------------------",Ee(r,{asBot:!0,pad:9}),` name: ${e.name}`,...t.map((u,f)=>` column: ${u.name} (${u.type}${u.choices?`: ${u.choices.join("/")}`:""})${f===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 Uh(s,e.name,n,e.todo)}catch(u){li(u)}let l=String(i.list_id??O(i.list).id??"");console.log(`\u2713 Created list ${e.name} (${l})`),console.log(await cS(s,l))}async function uS(e){let t=ai(e.list);if(!t)throw Error(`Not a list ID or list URL: ${e.list}`);let n=gr();await ci(n);let s=await Wm(n,t),o=[{col:s.find((a)=>a.type==="text")??s[0],value:e.text},...Ec(e.sets).map((a)=>({col:Sc(s,a.col),value:a.value}))],i=o.map((a)=>({column_id:a.col.id,..._c(a.col,a.value)})),l=await Be(n),u=De("lists-add",t,JSON.stringify(i),l?.userId??"");if(e.code!==u)Se(e.code,u,["--- Adding a row to Slack List ---------------",Ee(l,{asBot:!0,pad:9}),` list: ${t}`,...o.map((a)=>` ${(a.col.name||a.col.key).padEnd(8)} ${a.value}`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);let f;try{f=await Jh(n,t,i)}catch(a){li(a)}console.log(`\u2713 Added row ${String(O(f.item).id??"")} ${e.text}`)}async function dS(e){let t=ai(e.list);if(!t)throw Error(`Not a list ID or list URL: ${e.list}`);let n=gr();await ci(n);let s=await Wm(n,t),r=Ec(e.sets).map((u)=>({col:Sc(s,u.col),value:u.value}));if(e.done!==void 0){let u=_h(s);if(!u)throw Error(`list ${t} has no Completed column \u2014 it was not created with todo mode`);r.push({col:{...u,type:"checkbox"},value:String(e.done)})}if(!r.length)throw Error("nothing to set \u2014 pass --set name=value and/or --done / --no-done");let o=r.map((u)=>({row_id:e.row,column_id:u.col.id,..._c(u.col,u.value)})),i=await Be(n),l=De("lists-set",t,e.row,JSON.stringify(o),i?.userId??"");if(e.code!==l)Se(e.code,l,["--- Updating Slack List row -----------------",Ee(i,{asBot:!0,pad:9}),` list: ${t}`,` row: ${e.row}`,...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"]);try{await qh(n,t,o)}catch(u){li(u)}console.log(`\u2713 Updated row ${e.row}`)}async function fS(e){let t=ai(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=gr();await ci(n);let s=e.users.length?e.users:e.channels,r=await Be(n),o=De("lists-share",t,e.level,s.join(","),r?.userId??"");if(e.code!==o)Se(e.code,o,["--- Sharing Slack List ----------------------",Ee(r,{asBot:!0,pad:9}),` list: ${t}`,` ${e.users.length?"users: ":"channels:"} ${s.join(", ")}`,` access: ${e.level}${e.level==="owner"?" \u26A0 transfers ownership":""}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);try{await Kh(n,t,e.level,e.users.length?{userIds:e.users}:{channelIds:e.channels})}catch(i){li(i)}console.log(`\u2713 Granted ${e.level} on ${t} to ${s.join(", ")}`)}function pS(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 hS(e,t,n,s){let r=pS(n);if(!r)throw Error(`Not a file ID or file permalink: ${n}
562
- `+"Expected F\u2026 or https://<ws>.slack.com/files/<UID>/<FID>/<name>");let o=O(await jh(e,r,t)),i=O(o.file),l=typeof i.name==="string"?i.name:typeof i.title==="string"?i.title:r,u=typeof i.url_private_download==="string"?i.url_private_download:typeof i.url_private==="string"?i.url_private:"";if(!u)throw Error(`files.info returned no download URL for ${r}`);let f={Authorization:`Bearer ${e}`};if(t)f.Cookie=`d=${t}`;let a=await fetch(u,{headers:f});if(!a.ok)throw Error(`Download failed: HTTP ${a.status} ${a.statusText}`);let c=Buffer.from(await a.arrayBuffer()),{statSync:d,existsSync:p}=await import("fs"),{basename:h}=await import("path"),g=s??l;if(s&&p(s)&&d(s).isDirectory())g=mt(s,h(l));km(g,c),console.log(`\u2713 Downloaded ${l} (${ni(c.length)}) \u2192 ${g}`)}async function gS(){zg(),XD();let e=Gf(Xf.name);if(e)console.error(e);let t=(a)=>Os(a.workspace),n=(a)=>zi(a.workspace),s=async(a)=>{let c=Ve(),d=cs(c);if(Mn(c))try{let g=await ks(t(a),a.target,n(a));if(!dn(c).some((y)=>y.channel===g.channel&&(y.thread_ts===void 0||y.thread_ts===g.root)))console.error(`Error: that message is not in one of ${c.dir}'s subscriptions (restrict_to_subscriptions)`),process.exit(2)}catch(g){console.error(ge(g)),process.exit(1)}if(a["fix-urls"]&&a.newText)a={...a,newText:Cs(a.newText)};let p={target:a.target,newText:a.newText??"",allowUrlAdjacent:a["allow-url-adjacent"]===!0};if(a.tick)p.tick=a.tick;if(d.prefix)p.lanePrefix=d.prefix;if(a.force)p.force=!0;if(a.code)p.code=a.code;if(a["channel-id"])p.channelId=a["channel-id"];if(a.mentions!==!1)p.mentions=!0;let h;if(a["as-bot"]){let g=await im(p.target,t(a),n(a),p.channelId);if(h=g.botToken,g.channelId&&!p.channelId)p.channelId=g.channelId;p.asBot=!0,p.mentionToken=t(a);let y=n(a);if(y)p.mentionCookie=y}else{h=t(a);let g=n(a);if(g)p.cookie=g}await xx(h,p)},r=async(a)=>{if(pl(a.message))a={...a,message:await hl()};if(!String(a.message??"").trim())console.error("Error: message is empty"),process.exit(1);if(a["fix-urls"])a={...a,message:Cs(a.message)};let c={target:a.target,message:a.message,allowUrlAdjacent:a["allow-url-adjacent"]===!0};if(a.json)c.json=!0;if(a.code)c.code=a.code;if(a["channel-id"])c.channelId=a["channel-id"];if(a["user-id"])c.userId=a["user-id"];if(a.broadcast)c.broadcast=!0;if(a.mentions!==!1){c.mentions=!0,c.mentionToken=t(a);let p=n(a);if(p)c.mentionCookie=p}let d;if(a["as-bot"]){let p=Ne();if(!p)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
563
- Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(1);if(!c.channelId&&!c.userId&&c.target.startsWith("@"))try{c.userId=await vt(t(a),c.target,n(a))}catch(h){console.error(`Error: could not resolve ${c.target} to a user for the bot DM.
564
- ${h instanceof Error?h.message:String(h)}
565
- Tip: pass --user-id <Uxxxx> to skip the lookup.`),process.exit(1)}d=p,c.asBot=!0}else{d=t(a);let p=n(a);if(p)c.cookie=p}try{await vx(d,c)}catch(p){console.error(ge(p)),process.exit(1)}},o={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}},i=async(a,c)=>{let d={state:a.state??"open",mine:c||a.mine===!0,count:a.n??50,json:a.json===!0};if(a.in)d.in=a.in;if(a.from)d.from=a.from;let p=n(a);if(p)d.cookie=p;await ix(t(a),d)},{who:l,rest:u}=jp(Si(process.argv)),f;if(l){let a=So(l);if("error"in a)console.error(`Error: ${a.error}`),process.exit(2);f=a.kind}await id(u).scriptName("slack").showHelpOnFail(!1).fail((a,c,d)=>{if(c)console.error(c.message),process.exit(1);console.error(a),console.error(""),d.showHelp(),process.exit(1)}).option("workspace",{alias:"w",type:"string",describe:"Workspace name"}).option("as-user",{type:"boolean",describe:"Act as the user session on purpose (not accepted for writes from inside an agent: name the person with slack @<who>)"}).middleware(async(a)=>{let c=String((a._??[])[0]??"");if(f==="bot"&&"as-bot"in a)a["as-bot"]=!0,a.asBot=!0;if(f==="user"&&a["as-bot"]===!0)console.error(`Error: @${l} is a user identity, but --as-bot was given`),process.exit(2);if(!c||c==="auth"||c==="login"||c==="agent"||c==="sent"||c==="relay")return;try{let d=Os(a.workspace),p=Ne(),h=Ng(a._??[],a,{botTokenSource:p?Dm.get("SLACK_BOT_TOKEN")??gl.get("SLACK_BOT_TOKEN")?.find((m)=>m.val===p)?.path??"shell":void 0,globalPaths:kl,slackTokenSet:!!process.env.SLACK_TOKEN,activeTokenIsBot:!!p&&d===p});if(h)console.error(h),process.exit(2);let g=xo(),y=Wp({isWrite:nl(a._??[])&&!sl(a._??[],a),who:l,asBot:a["as-bot"]===!0,asUser:a["as-user"]===!0,activeIsBot:d.startsWith("xoxb-"),agent:fc(),identities:[...g.keys()].sort(),userIdentities:[...g].filter(([,m])=>m.kind==="user").map(([m])=>m).sort(),cmd:(a._??[]).slice(0,2).join(" ")});if(y)console.error(y),process.exit(2)}catch(d){if((d instanceof Error?d.message:String(d)).startsWith("No profiles configured"))console.log(`No workspace configured. Let's set that up:
566
- `),await Us(),process.exit(0);throw d}},!0).command("agent","Bot agent session status and command heartbeat",(a)=>qf(a,$t)).command(["read [target]","msgs [target]"],"Browse messages",(a)=>a.positional("target",{type:"string",describe:"#channel, @user, URL, or an alias (slack alias ls)"}).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(a)=>{let c=t(a),d=a.json?"jsonl":a.format,p=a.target?cc(a.target):void 0;if(p?.thread_ts)await nm(c,p.channel,p.thread_ts,Math.max(a.limit,100),d,n(a));else if(p)await tm(c,p.channel,a.limit,d,a.unreplied,n(a));else if(a.target)await tm(c,a.target,a.limit,d,a.unreplied,n(a));else await nx(c)}).command("thread <target> <ts>","Show thread messages",(a)=>a.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","tsv"],default:"text",describe:"jsonl exposes raw ts/user/text (incl. external-guest user IDs); tsv: <ts> TAB <user|bot id> TAB <text, \\ \\n \\r \\t escaped> [files: N], every page"}).option("json",{type:"boolean",default:!1,describe:"Alias for --format=jsonl"}).option("since",{type:"string",describe:"Only messages after this ts (reads every page)"}),async(a)=>{let c=a.json?"jsonl":a.format;await nm(t(a),a.target,a.ts,a.limit,c,n(a),a.since)}).command(["channel","channels","ch"],"Channel commands",(a)=>a.command(["ls","list"],"List channels",(c)=>c.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(c)=>{await rx(t(c),c.limit,c.filter,c.all,c.json?"jsonl":c.format,n(c))}).command("get <channel>","Show channel details",(c)=>c.positional("channel",{type:"string",demandOption:!0,describe:"#name or channel ID"}),async(c)=>{let d=t(c),p=n(c),h=c.channel,g=h.startsWith("#")||h.startsWith("@")||h.startsWith("C")||h.startsWith("G")||h.startsWith("D")?h:`#${h}`,y=await we(d,g,p),m=O(await Wn(d,y,p)),w=O(m.channel),k=typeof w.name==="string"?w.name:y,D=w.is_im===!0?"@":"#",E=String(O(w.purpose).value??""),S=String(O(w.topic).value??""),x=w.num_members??w.member_count??"";if(console.log(`${D}${k} ${y}`),S)console.log(`topic: ${S}`);if(E)console.log(`purpose: ${E}`);if(x)console.log(`members: ${x}`);console.log(`private: ${w.is_private===!0}`)}).command("invite <channel> <users..>","Invite people to a channel (conversations.invite; confirm-hash gate). Acts as the current identity, e.g. slack @bot channel invite \u2026",(c)=>c.positional("channel",{type:"string",demandOption:!0,describe:"#name, channel id, or permalink"}).positional("users",{type:"string",array:!0,demandOption:!0,describe:"@handle or U\u2026 ids"}).option("code",{type:"string",describe:"Safety hash to confirm"}),async(c)=>{let d=t(c),p=n(c),h,g=[];try{h=await we(d,String(c.channel),p);for(let k of c.users.map(String))g.push(/^[UW][A-Z0-9]{2,}$/.test(k)?k:await vt(d,k,p))}catch(k){console.error(ge(k)),process.exit(1)}let y=await Be(d,p),m=await zt(d,h,String(c.channel),p),w=De("channel-invite",h,g.join(","),y?.userId??"");if(c.code!==w)Se(c.code,w,["--- Inviting to a channel --------------------",Ee(y,{pad:9}),` channel: ${m}`,` users: ${g.join(", ")}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);try{await Wc(d,h,g,p)}catch(k){let _=k instanceof Error?k.message:String(k);if(!/already_in_channel/.test(_))console.error(`\u2717 invite failed: ${ge(k)}${/not_in_channel/.test(_)?`
567
- The inviter must be a member of the channel first.`:""}`),process.exit(1)}console.log(`\u2713 Invited ${g.length} to ${m}`)}).command(["create <name>","new <name>"],"Create a channel (confirm-hash safety gate)",(c)=>c.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(c)=>{let d=t(c),p=n(c),h=c.name.replace(/^#/,"").toLowerCase(),g=c.private===!0,y=c.invite.filter(Boolean),m=await Be(d,p),w=De(h,String(g),y.join(","),m?.userId??"");if(c.code!==w)Se(c.code,w,["--- Creating channel -------------------------",Ee(m,{pad:9}),` name: ${g?"\uD83D\uDD12 ":"#"}${h}`,` private: ${g}`,...y.length?[` invite: ${y.join(", ")}`]:[],"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);let k;try{k=await ng(d,h,g,p)}catch(_){console.error(_ instanceof Error?_.message:String(_)),process.exit(1)}if(console.log(`\u2713 Created ${g?"\uD83D\uDD12 ":"#"}${k.name} (${k.id})`),y.length){let _=[];for(let D of y)try{_.push(D.startsWith("U")||D.startsWith("W")?D:await vt(d,D,p))}catch(E){console.error(` ! could not resolve ${D}: ${E instanceof Error?E.message:String(E)}`)}for(let D of _)try{let E=O(await fs(d,D,p)),S=O(E.user);if(S.is_ultra_restricted===!0)console.error(`\u26A0 ${D} 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(S.is_restricted===!0)console.error(`\u26A0 ${D} is a multi-channel guest \u2014 double-check they were actually added (guest invites can silently no-op depending on workspace restrictions).`)}catch{}if(_.length)try{await Wc(d,k.id,_,p),console.log(`\u2713 Invited ${_.length} member${_.length===1?"":"s"}`)}catch(D){console.error(` ! invite failed: ${D instanceof Error?D.message:String(D)}`)}}}).command(["rename <channel> <new-name>","mv <channel> <new-name>"],"Rename a channel (confirm-hash safety gate)",(c)=>c.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(c)=>{let d=t(c),p=n(c),h=c.channel;if(h.startsWith("@"))console.error(`Error: ${h} is a DM \u2014 only channels can be renamed.`),process.exit(1);let g=h.startsWith("#")||/^[CG][A-Z0-9]{8,}$/.test(h)?h:`#${h}`,y=c.newName.replace(/^#/,"").toLowerCase(),m,w;try{m=await we(d,g,p)}catch(E){console.error(`Error: could not resolve channel ${h}: ${E instanceof Error?E.message:String(E)}`),process.exit(1)}try{let E=O(O(await Wn(d,m,p)).channel);if(E.is_im===!0||E.is_mpim===!0)console.error(`Error: ${m} is a DM \u2014 only channels can be renamed.`),process.exit(1);w=typeof E.name==="string"?E.name:g.replace(/^#/,"")}catch(E){let S=E instanceof Error?E.message:String(E);if(/channel_not_found/.test(S))console.error(`Error: could not resolve channel ${h}: channel not found (or not visible to this token).`),process.exit(1);w=g.replace(/^#/,"")}if(c.dryRun===!0){console.log(`#${w} -> #${y} (${m})`),console.log("(dry run \u2014 conversations.rename not called)");return}let k=await Be(d,p),_=De("rename",m,y,k?.userId??"");if(c.code!==_)Se(c.code,_,["--- Renaming channel -------------------------",Ee(k,{pad:9}),` channel: ${m}`,` from: #${w}`,` to: #${y}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);let D;try{D=await sg(d,m,y,p)}catch(E){let x=(E instanceof Error?E.message:String(E)).match(/Slack error on conversations\.rename: (\w+)/)?.[1],F={name_taken:`Error: a channel named #${y} already exists.`,invalid_name:`Error: "${y}" is not a valid channel name (lowercase letters, numbers, hyphens, underscores; max 80 chars).`,invalid_name_specials:`Error: "${y}" contains characters Slack doesn't allow in channel names.`,invalid_name_maxlength:`Error: "${y}" 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 #${w} (workspace settings may restrict renaming to admins or the channel creator).`,not_in_channel:`Error: this token isn't a member of #${w} \u2014 join it first.`,is_archived:`Error: #${w} is archived \u2014 unarchive it before renaming.`};console.error((x&&F[x])??ge(E)),process.exit(1)}console.log(`\u2713 Renamed #${w} -> #${D.name} (${D.id})`)}).demandCommand(1,"").showHelpOnFail(!0)).command(["user","usr"],"User commands",(a)=>a.command(["ls","list"],"List workspace members",(c)=>c.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(c)=>{let d=c.json?"jsonl":c.format,p=t(c),h=n(c),g=await cg(p,h),y=c.filter?.toLowerCase(),m=G(g.members).map(O);if(c.external){let D=new Set(m.map((F)=>String(F.id))),E=O(await sr(p,h)),S=G(E.channels).map(O).filter((F)=>F.is_ext_shared===!0&&!!F.name),x=new Set;for(let F of S)try{for(let R of await lg(p,String(F.id),h))if(!D.has(R))x.add(R)}catch{}for(let F of x)try{let R=O(await fs(p,F,h)),I=O(R.user);if(I.id)m.push(I)}catch{}}let w=m.filter((D)=>D.deleted!==!0&&D.is_bot!==!0&&String(D.id)!=="USLACKBOT").filter((D)=>{if(!y)return!0;let E=String(D.name??"").toLowerCase(),S=String(O(D.profile).real_name??"").toLowerCase(),x=String(O(D.profile).email??"").toLowerCase();return E.includes(y)||S.includes(y)||x.includes(y)}).slice(0,c.limit);if(d==="jsonl"){for(let D of w)console.log(JSON.stringify(D));return}if(d==="yaml"){for(let D of w){let E=function(S,x=""){if(S===null)return"null";if(typeof S==="string")return S.includes(`
559
+ slack schedule rm '${t.target}' ${p} --as-bot`),o.startsWith("D"))try{let g=await so(e);if(!g.ok)for(let y of ro(g,!0))console.error(y);else{let y=g.appId?`https://api.slack.com/apps/${g.appId}`:"https://api.slack.com/apps";console.error(`Note: if ${t.target} can't reply (app messaging may be off), enable Messages Tab: ${y} \u2192 App Home.`)}}catch{}}}async function Jm(e,t,n,s){let r;if(n)r=n;else if(t)r=await we(e,t,s);let i=(await Eg(e,r,s)).scheduled_messages??[];if(i.length===0){console.log("(no scheduled messages)");return}for(let a of i){let c=new Date(a.post_at*1000).toISOString();console.log(`${a.id} ${c} [${a.channel_id}] ${a.text.split(`
560
+ `)[0]?.slice(0,80)??""}`)}}async function Km(e,t){let n;if(t.channelId)n=t.channelId;else n=await we(e,t.target,t.cookie);let s=await je(e,t.cookie),r=De(n,t.id,s?.userId??"");if(t.code!==r)Se(t.code,r,["--- Deleting scheduled message ---------------",Ee(s,{asBot:t.asBot,pad:9}),` Channel: ${t.target}${t.targetOverride?` [${t.targetOverride} \u2192 ${n}]`:""}`,` ID: ${t.id}`,"---------------------------------------------"]);await $g(e,n,t.id,t.cookie),console.log(`\u2713 Deleted scheduled message ${t.id}`)}async function qm(e,t){if(t.comment!==void 0)He(t.comment,t.allowUrlAdjacent);let n=Vt(e,t.cookie),{statSync:s,existsSync:r}=await import("fs"),{basename:o}=await import("path");for(let k of t.filePaths)if(!r(k))console.error(`Error: file not found: ${k}`),process.exit(1);let{ref:i,threadTs:a}=At(t.target),c;if(t.channelId)c=t.channelId;else if(t.userId)c=await Gt(e,t.userId,t.cookie);else c=await we(e,i,t.cookie);if(await Wl(e,c,(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 d=t.filePaths.length>1,f=t.filePaths.map((k)=>{let w=o(k),u=d?w:t.title??w;return{fp:k,filename:w,title:u,sizeFmt:pi(s(k).size)}}),p=await n(),g=De(c,...f.flatMap((k)=>[k.fp,k.title]),p?.userId??"");if(t.code!==g){let k=` To: ${i}${a?` (thread ${a})`:""}`,w=d?[`--- Uploading ${f.length} files ------------------------`,Ee(p,{pad:7}),k,...f.map((u)=>` ${u.filename} (${u.sizeFmt})`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]:["--- Uploading file ---------------------------",Ee(p,{pad:7}),k,` File: ${f[0].fp}`,` Title: ${f[0].title}`,` Size: ${f[0].sizeFmt}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"];Se(t.code,g,w)}let y=f.length;for(let k=0;k<y;k++){let w=f[k],u={title:w.title};if(a!==void 0)u.threadTs=a;if(t.comment!==void 0&&k===0)u.initialComment=t.comment;let{fileId:l,permalink:h}=await qg(e,c,w.fp,u,t.cookie),m=y>1?`[${k+1}/${y}] `:"";console.log(`${m}\u2713 Uploaded (file_id: ${l}${h?`, url: ${h}`:""})`)}}async function KS(e,t,n){let s=n.channel?await we(e,n.channel,t):void 0,r=[],o=1,i=1;do{let c={page:o,count:200};if(n.types)c.types=n.types;if(s)c.channel=s;if(n.user)c.user=n.user;let d=L(await gg(e,c,t));for(let f of G(d.files))r.push(L(f));i=Number(L(d.paging).pages??1),o++}while(r.length<n.limit&&o<=i);let a=r.slice(0,n.limit);if(n.format==="jsonl"){for(let c of a)console.log(JSON.stringify({id:c.id??null,name:c.name??c.title??null,filetype:c.filetype??null,size:c.size??null,user:c.user??null,created:c.created??null,permalink:c.permalink??null}));return}for(let c of a){let d=String(c.id??""),f=typeof c.name==="string"?c.name:typeof c.title==="string"?c.title:d,p=typeof c.filetype==="string"?c.filetype:"?",g=typeof c.size==="number"?pi(c.size):"";console.log(`${d} ${p.padEnd(7)} ${g.padStart(9)} ${f}`)}}function bi(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 qS(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(L(n).text??L(n).name??L(n).value??"")).filter(Boolean).join(", ");for(let n of["rich_text","select","user","date","number","checkbox","email","phone"]){let s=e[n];if(s!=null)return typeof s==="object"?JSON.stringify(s):String(s)}return""}async function HS(e,t,n,s){let r=bi(n);if(!r)throw Error(`Not a list ID or list URL: ${n}
561
+ `+"Expected F\u2026 or https://<ws>.slack.com/lists/<TEAM>/<F-id>");let o=[],i;do{let c={limit:200};if(i)c.cursor=i;let d=s.asBot?await el(xr(),r,c):L(await kg(e,r,c,t));for(let p of G(d.items??d.records))o.push(L(p));let f=L(d.response_metadata).next_cursor;i=typeof f==="string"&&f?f:void 0}while(i&&o.length<s.limit);let a=o.slice(0,s.limit);if(s.format==="jsonl"){for(let c of a)console.log(JSON.stringify(c));return}for(let c of a){let d=String(c.id??""),f=G(c.fields).map(L).map((p)=>{let g=String(p.key??p.column_id??"?"),y=qS(p);return y?`${g}=${y}`:""}).filter(Boolean);console.log(`${d} ${f.join(" | ")}`)}}function xr(){let e=Me();if(!e)console.error(`Error: Slack List writes go through the public slackLists.* API, which needs a bot token (xoxb-) \u2014 none was found.
562
+ `+" Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell)."),process.exit(1);return e}async function wi(e){let t=[];try{t=(await Ct(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).
563
+ `+" Add it under OAuth & Permissions \u2192 Bot Token Scopes in the Slack app config, then reinstall the app."),process.exit(1)}async function zS(e,t){try{let n=await Zc(e);if(n.url&&n.teamId)return`${n.url.replace(/\/$/,"")}/lists/${n.teamId}/${t}`}catch{}return t}async function hy(e,t){let n=await el(e,t,{limit:1,includeList:!0}),s=zh(L(n.list));if(!s.length)throw Error(`could not read the column schema of list ${t}`);return s}function ki(e){console.error(ge(e)),process.exit(1)}async function YS(e){let t=e.cols.map(qh),n=Hh(t),s=xr();await wi(s);let r=await je(s),o=De("lists-create",e.name,JSON.stringify(n),String(e.todo),r?.userId??"");if(e.code!==o)Se(e.code,o,["--- Creating Slack List ----------------------",Ee(r,{asBot:!0,pad:9}),` name: ${e.name}`,...t.map((c,d)=>` column: ${c.name} (${c.type}${c.choices?`: ${c.choices.join("/")}`:""})${d===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 mg(s,e.name,n,e.todo)}catch(c){ki(c)}let a=String(i.list_id??L(i.list).id??"");console.log(`\u2713 Created list ${e.name} (${a})`),console.log(await zS(s,a))}async function GS(e){let t=bi(e.list);if(!t)throw Error(`Not a list ID or list URL: ${e.list}`);let n=xr();await wi(n);let s=await hy(n,t),o=[{col:s.find((f)=>f.type==="text")??s[0],value:e.text},...Bc(e.sets).map((f)=>({col:Nc(s,f.col),value:f.value}))],i=o.map((f)=>({column_id:f.col.id,...Mc(f.col,f.value)})),a=await je(n),c=De("lists-add",t,JSON.stringify(i),a?.userId??"");if(e.code!==c)Se(e.code,c,["--- Adding a row to Slack List ---------------",Ee(a,{asBot:!0,pad:9}),` list: ${t}`,...o.map((f)=>` ${(f.col.name||f.col.key).padEnd(8)} ${f.value}`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);let d;try{d=await yg(n,t,i)}catch(f){ki(f)}console.log(`\u2713 Added row ${String(L(d.item).id??"")} ${e.text}`)}async function XS(e){let t=bi(e.list);if(!t)throw Error(`Not a list ID or list URL: ${e.list}`);let n=xr();await wi(n);let s=await hy(n,t),r=Bc(e.sets).map((c)=>({col:Nc(s,c.col),value:c.value}));if(e.done!==void 0){let c=Yh(s);if(!c)throw Error(`list ${t} has no Completed column \u2014 it was not created with todo mode`);r.push({col:{...c,type:"checkbox"},value:String(e.done)})}if(!r.length)throw Error("nothing to set \u2014 pass --set name=value and/or --done / --no-done");let o=r.map((c)=>({row_id:e.row,column_id:c.col.id,...Mc(c.col,c.value)})),i=await je(n),a=De("lists-set",t,e.row,JSON.stringify(o),i?.userId??"");if(e.code!==a)Se(e.code,a,["--- Updating Slack List row -----------------",Ee(i,{asBot:!0,pad:9}),` list: ${t}`,` row: ${e.row}`,...r.map((c)=>` ${(c.col.name||c.col.key).padEnd(8)} ${c.value}`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);try{await wg(n,t,o)}catch(c){ki(c)}console.log(`\u2713 Updated row ${e.row}`)}async function VS(e){let t=bi(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=xr();await wi(n);let s=e.users.length?e.users:e.channels,r=await je(n),o=De("lists-share",t,e.level,s.join(","),r?.userId??"");if(e.code!==o)Se(e.code,o,["--- Sharing Slack List ----------------------",Ee(r,{asBot:!0,pad:9}),` list: ${t}`,` ${e.users.length?"users: ":"channels:"} ${s.join(", ")}`,` access: ${e.level}${e.level==="owner"?" \u26A0 transfers ownership":""}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);try{await bg(n,t,e.level,e.users.length?{userIds:e.users}:{channelIds:e.channels})}catch(i){ki(i)}console.log(`\u2713 Granted ${e.level} on ${t} to ${s.join(", ")}`)}function ZS(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 QS(e,t,n,s){let r=ZS(n);if(!r)throw Error(`Not a file ID or file permalink: ${n}
564
+ `+"Expected F\u2026 or https://<ws>.slack.com/files/<UID>/<FID>/<name>");let o=L(await hg(e,r,t)),i=L(o.file),a=typeof i.name==="string"?i.name:typeof i.title==="string"?i.title:r,c=typeof i.url_private_download==="string"?i.url_private_download:typeof i.url_private==="string"?i.url_private:"";if(!c)throw Error(`files.info returned no download URL for ${r}`);let d={Authorization:`Bearer ${e}`};if(t)d.Cookie=`d=${t}`;let f=await ys("the download",c,{headers:d});if(!f.ok)throw Error(`Download failed: HTTP ${f.status} ${f.statusText}`);let p=Buffer.from(await f.arrayBuffer()),{statSync:g,existsSync:y}=await import("fs"),{basename:k}=await import("path"),w=s??a;if(s&&y(s)&&g(s).isDirectory())w=yt(s,k(a));Ym(w,p),console.log(`\u2713 Downloaded ${a} (${pi(p.length)}) \u2192 ${w}`)}async function e_(){Dm(),Px();let e=bp(Qa.name);if(e)console.error(e);let t=!1,n=(u)=>{let l=Ls(u.workspace),h=Md();if(h){let m=process.env.SLACK_HUB_IDENTITY,b=h.kind==="env"?Ol.get("SLACK_TOKEN"):void 0,_=m&&h.kind==="env"?`identity @${m}`:b?`${h.name} in ${b}`:h.name;if(lg(_),!m&&h.kind==="env"&&h.shadowed.length>0&&!t){t=!0;let x=process.env.SLACK_COOKIE?" (and SLACK_COOKIE)":"";console.error(`note: using ${_}${x}, which overrides profiles.json (${h.shadowed.join(", ")}); unset it or pass --workspace <name> to use a profile`)}}return l},s=(u)=>ra(u.workspace),r=async(u)=>{if(u["as-bot"]){let h=br();if(u.workspace){let[m,b]=await Promise.all([Ct(n(u),s(u)),Ct(h)]);if(m.url!==b.url)console.error("Error: --as-bot token belongs to a different workspace than -w; select that workspace's bot token."),process.exit(2)}return{token:h,asBot:!0}}let l=s(u);return{token:n(u),...l?{cookie:l}:{},asBot:!1}},o=async(u)=>{let l=Ze(),h=ps(l);if(Un(l))try{let _=await $s(n(u),u.target,s(u));if(!pn(l).some((x)=>x.channel===_.channel&&(x.thread_ts===void 0||x.thread_ts===_.root)))console.error(`Error: that message is not in one of ${l.dir}'s subscriptions (restrict_to_subscriptions)`),process.exit(2)}catch(_){console.error(ge(_)),process.exit(1)}if(u["fix-urls"]&&u.newText)u={...u,newText:Is(u.newText)};let m={target:u.target,newText:u.newText??"",allowUrlAdjacent:u["allow-url-adjacent"]===!0};if(u.tick)m.tick=u.tick;if(h.prefix)m.lanePrefix=h.prefix;if(u.force)m.force=!0;if(u.code)m.code=u.code;if(u["channel-id"])m.channelId=u["channel-id"];if(u.mentions!==!1)m.mentions=!0;let b;if(u["as-bot"]){let _=await vm(m.target,n(u),s(u),m.channelId);if(b=_.botToken,_.channelId&&!m.channelId)m.channelId=_.channelId;m.asBot=!0,m.mentionToken=n(u);let x=s(u);if(x)m.mentionCookie=x}else{b=n(u);let _=s(u);if(_)m.cookie=_}await aS(b,m)},i=async(u)=>{if(Tl(u.message))u={...u,message:await Fl()};if(!String(u.message??"").trim())console.error("Error: message is empty"),process.exit(1);if(u["fix-urls"])u={...u,message:Is(u.message)};let l={target:u.target,message:u.message,allowUrlAdjacent:u["allow-url-adjacent"]===!0};if(u.json)l.json=!0;if(u.code)l.code=u.code;if(u["channel-id"])l.channelId=u["channel-id"];if(u["user-id"])l.userId=u["user-id"];if(u.broadcast)l.broadcast=!0;if(u.mentions!==!1){l.mentions=!0,l.mentionToken=n(u);let m=s(u);if(m)l.mentionCookie=m}let h;if(u["as-bot"]){let m=Me();if(!m)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
565
+ Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(1);if(!l.channelId&&!l.userId&&l.target.startsWith("@"))try{l.userId=await Nt(n(u),l.target,s(u))}catch(b){console.error(`Error: could not resolve ${l.target} to a user for the bot DM.
566
+ ${b instanceof Error?b.message:String(b)}
567
+ Tip: pass --user-id <Uxxxx> to skip the lookup.`),process.exit(1)}h=m,l.asBot=!0}else{h=n(u);let m=s(u);if(m)l.cookie=m}try{await wS(h,l)}catch(m){console.error(ge(m)),process.exit(1)}},a={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}},c=async(u,l)=>{let h={state:u.state??"open",mine:l||u.mine===!0,count:u.n??50,json:u.json===!0};if(u.in)h.in=u.in;if(u.from)h.from=u.from;let m=s(u);if(m)h.cookie=m;await qx(n(u),h)};if(dg(),ln("TIMING")==="1")process.on("exit",()=>console.error(`slack-hub timing: ${(performance.now()/1000).toFixed(2)}s exit`));let{who:d,rest:f}=uh(vi(process.argv)),p=f,g=[],y=f.findIndex((u)=>!u.startsWith("-"));if(y>=0&&f[y]==="ask"){let u=Yp(f.slice(y+1));if("error"in u)console.error(`Error: ${u.error}`),process.exit(ae);p=[...f.slice(0,y+1),...u.rest],g=u.choices}let k;if(d){let u=Ro(d);if("error"in u)console.error(`Error: ${u.error}`),process.exit(2);k=u.kind}let w=ql(f);if(w.enabled){let u=await import("fs"),l=await import("path"),h=await import("os"),{spawn:m}=await import("child_process"),{callback:b,args:_}=w,x=_.includes("-")&&!process.stdin.isTTY?u.readFileSync(0,"utf8"):void 0,S=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`,E=l.join(h.homedir(),".local","state","slack-post","jobs");u.mkdirSync(E,{recursive:!0,mode:448}),u.chmodSync(E,448),u.chmodSync(l.dirname(E),448);let I=l.join(h.homedir(),".local","state","slack-post","last-failed.json"),N;if(u.existsSync(I))try{N=JSON.parse(u.readFileSync(I,"utf8"))}catch{}let C=[];try{for(let O of u.readdirSync(E)){if(!O.endsWith(".json"))continue;try{let M=JSON.parse(u.readFileSync(l.join(E,O),"utf8"));if(M.status==="queued"||M.status==="running")C.push({jobId:M.jobId,status:M.status,target:M.target})}catch{}}}catch{}let A=l.join(E,`${S}.json`),F={jobId:S,status:"queued",target:_.join(" "),createdAt:new Date().toISOString(),callback:b,forwardArgs:_,...d?{who:d}:{},...x!==void 0?{stdin:x}:{}};if(u.writeFileSync(A,JSON.stringify(F,null,2),{mode:384}),m(process.execPath,[process.argv[1],"_post-worker",A],{detached:!0,stdio:"ignore"}).unref(),_.includes("--json"))console.log(JSON.stringify({ok:!0,queued:!0,jobId:S,statusFile:A,...N?{lastFailed:N}:{},...C.length?{inFlight:C}:{}}));else{if(N)console.error(`\u26A0 Last post failed (job: ${N.jobId}, target: ${N.target}): ${N.error}`);if(C.length)console.error(`\u23F3 In-flight posts (${C.length}): ${C.map((O)=>`${O.jobId}[${O.status}]`).join(", ")}`);console.log(`\u2713 Queued (job: ${S}) \xB7 check: slack jobs ${S}`)}return}await Sd(p).scriptName("slack").version(Qa.version).showHelpOnFail(!1).fail((u,l,h)=>{if(l)console.error(l.message),process.exit(1);console.error(u),console.error(""),h.showHelp(),process.exit(1)}).option("workspace",{alias:"w",type:"string",describe:"Workspace name"}).option("as-user",{type:"boolean",describe:"Act as the user session on purpose (not accepted for writes from inside an agent: name the person with slack @<who>)"}).middleware(async(u)=>{let l=String((u._??[])[0]??"");if(k==="bot"&&"as-bot"in u)u["as-bot"]=!0,u.asBot=!0;if(k==="user"&&u["as-bot"]===!0)console.error(`Error: @${d} is a user identity, but --as-bot was given`),process.exit(2);if(!l||["auth","login","agent","sent","relay","jobs","_post-worker"].includes(l))return;try{let h=Ls(u.workspace),m=Me(),b=dm(u._??[],u,{botTokenSource:m?Ol.get("SLACK_BOT_TOKEN")??Il.get("SLACK_BOT_TOKEN")?.find((S)=>S.val===m)?.path??"shell":void 0,globalPaths:Nl,slackTokenSet:!!process.env.SLACK_TOKEN,activeTokenIsBot:!!m&&h===m});if(b)console.error(b),process.exit(2);let _=Io(),x=dh({isWrite:bl(u._??[])&&!wl(u._??[],u),who:d,asBot:u["as-bot"]===!0,asUser:u["as-user"]===!0,activeIsBot:h.startsWith("xoxb-"),agent:$c(),identities:[..._.keys()].sort(),userIdentities:[..._].filter(([,S])=>S.kind==="user").map(([S])=>S).sort(),cmd:(u._??[]).slice(0,2).join(" ")});if(x)console.error(x),process.exit(2)}catch(h){if((h instanceof Error?h.message:String(h)).startsWith("No profiles configured"))console.log(`No workspace configured. Let's set that up:
568
+ `),await Ys(),process.exit(0);throw h}},!0).command("agent","Bot agent session status and command heartbeat",(u)=>hp(u,At)).command(["read [target]","msgs [target]"],"Browse messages",(u)=>u.positional("target",{type:"string",describe:"#channel, @user, URL, or an alias (slack alias ls)"}).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(u)=>{let l=n(u),h=u.json?"jsonl":u.format,m=u.target?xc(u.target):void 0;if(m?.thread_ts)await Fm(l,m.channel,m.thread_ts,Math.max(u.limit,100),h,s(u));else if(m)await Tm(l,m.channel,u.limit,h,u.unreplied,s(u));else if(u.target)await Tm(l,u.target,u.limit,h,u.unreplied,s(u));else await Wx(l)}).command("thread <target> <ts>","Show thread messages",(u)=>u.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","tsv"],default:"text",describe:"jsonl exposes raw ts/user/text (incl. external-guest user IDs); tsv: <ts> TAB <user|bot id> TAB <text, \\ \\n \\r \\t escaped> [files: N], every page"}).option("json",{type:"boolean",default:!1,describe:"Alias for --format=jsonl"}).option("since",{type:"string",describe:"Only messages after this ts (reads every page)"}),async(u)=>{let l=u.json?"jsonl":u.format;await Fm(n(u),u.target,u.ts,u.limit,l,s(u),u.since)}).command(["channel","channels","ch"],"Channel commands",(u)=>u.command(["ls","list"],"List channels",(l)=>l.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(l)=>{await Jx(n(l),l.limit,l.filter,l.all,l.json?"jsonl":l.format,s(l))}).command("get <channel>","Show channel details",(l)=>l.positional("channel",{type:"string",demandOption:!0,describe:"#name or channel ID"}),async(l)=>{let h=n(l),m=s(l),b=l.channel,_=b.startsWith("#")||b.startsWith("@")||b.startsWith("C")||b.startsWith("G")||b.startsWith("D")?b:`#${b}`,x=await we(h,_,m),S=L(await Hn(h,x,m)),E=L(S.channel),I=typeof E.name==="string"?E.name:x,C=E.is_im===!0?"@":"#",A=String(L(E.purpose).value??""),F=String(L(E.topic).value??""),v=E.num_members??E.member_count??"";if(console.log(`${C}${I} ${x}`),F)console.log(`topic: ${F}`);if(A)console.log(`purpose: ${A}`);if(v)console.log(`members: ${v}`);console.log(`private: ${E.is_private===!0}`)}).command("invite <channel> <users..>","Invite people to a channel (conversations.invite; confirm-hash gate). Acts as the current identity, e.g. slack @bot channel invite \u2026",(l)=>l.positional("channel",{type:"string",demandOption:!0,describe:"#name, channel id, or permalink"}).positional("users",{type:"string",array:!0,demandOption:!0,describe:"@handle or U\u2026 ids"}).option("code",{type:"string",describe:"Safety hash to confirm"}).option("as-bot",{type:"boolean",default:!1,describe:"Invite via the bot token, without a user-session cookie"}),async(l)=>{let{token:h,cookie:m,asBot:b}=await r(l),_,x=[];try{_=await we(h,String(l.channel),m);for(let N of l.users.map(String))x.push(/^[UW][A-Z0-9]{2,}$/.test(N)?N:await Nt(h,N,m))}catch(N){console.error(ge(N)),process.exit(1)}let S=await je(h,m),E=await Bt(h,_,String(l.channel),m),I=De("channel-invite",_,x.join(","),S?.userId??"");if(l.code!==I)Se(l.code,I,["--- Inviting to a channel --------------------",Ee(S,{pad:9,asBot:b}),` channel: ${E}`,` users: ${x.join(", ")}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);try{await sl(h,_,x,m)}catch(N){let C=N instanceof Error?N.message:String(N);if(!/already_in_channel/.test(C))console.error(`\u2717 invite failed: ${ge(N)}${/not_in_channel/.test(C)?`
569
+ The inviter must be a member of the channel first.`:""}`),process.exit(1)}console.log(`\u2713 Invited ${x.length} to ${E}`)}).command(["create <name>","new <name>"],"Create a channel (confirm-hash safety gate)",(l)=>l.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"}).option("as-bot",{type:"boolean",default:!1,describe:"Create and invite via the bot token, without a user-session cookie"}),async(l)=>{let{token:h,cookie:m,asBot:b}=await r(l),_=l.name.replace(/^#/,"").toLowerCase(),x=l.private===!0,S=l.invite.filter(Boolean),E=await je(h,m),I=De(_,String(x),S.join(","),E?.userId??"");if(l.code!==I)Se(l.code,I,["--- Creating channel -------------------------",Ee(E,{pad:9,asBot:b}),` name: ${x?"\uD83D\uDD12 ":"#"}${_}`,` private: ${x}`,...S.length?[` invite: ${S.join(", ")}`]:[],"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);let N;try{N=await Fg(h,_,x,m)}catch(C){console.error(C instanceof Error?C.message:String(C)),process.exit(1)}if(console.log(`\u2713 Created ${x?"\uD83D\uDD12 ":"#"}${N.name} (${N.id})`),S.length){let C=[];for(let A of S)try{C.push(A.startsWith("U")||A.startsWith("W")?A:await Nt(h,A,m))}catch(F){console.error(` ! could not resolve ${A}: ${F instanceof Error?F.message:String(F)}`)}for(let A of C)try{let F=L(await bs(h,A,m)),v=L(F.user);if(v.is_ultra_restricted===!0)console.error(`\u26A0 ${A} 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(v.is_restricted===!0)console.error(`\u26A0 ${A} is a multi-channel guest \u2014 double-check they were actually added (guest invites can silently no-op depending on workspace restrictions).`)}catch{}if(C.length)try{await sl(h,N.id,C,m),console.log(`\u2713 Invited ${C.length} member${C.length===1?"":"s"}`)}catch(A){console.error(` ! invite failed: ${A instanceof Error?A.message:String(A)}`)}}}).command(["rename <channel> <new-name>","mv <channel> <new-name>"],"Rename a channel (confirm-hash safety gate)",(l)=>l.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(l)=>{let h=n(l),m=s(l),b=l.channel;if(b.startsWith("@"))console.error(`Error: ${b} is a DM \u2014 only channels can be renamed.`),process.exit(1);let _=b.startsWith("#")||/^[CG][A-Z0-9]{8,}$/.test(b)?b:`#${b}`,x=l.newName.replace(/^#/,"").toLowerCase(),S,E;try{S=await we(h,_,m)}catch(A){console.error(`Error: could not resolve channel ${b}: ${A instanceof Error?A.message:String(A)}`),process.exit(1)}try{let A=L(L(await Hn(h,S,m)).channel);if(A.is_im===!0||A.is_mpim===!0)console.error(`Error: ${S} is a DM \u2014 only channels can be renamed.`),process.exit(1);E=typeof A.name==="string"?A.name:_.replace(/^#/,"")}catch(A){let F=A instanceof Error?A.message:String(A);if(/channel_not_found/.test(F))console.error(`Error: could not resolve channel ${b}: channel not found (or not visible to this token).`),process.exit(1);E=_.replace(/^#/,"")}if(l.dryRun===!0){console.log(`#${E} -> #${x} (${S})`),console.log("(dry run \u2014 conversations.rename not called)");return}let I=await je(h,m),N=De("rename",S,x,I?.userId??"");if(l.code!==N)Se(l.code,N,["--- Renaming channel -------------------------",Ee(I,{pad:9}),` channel: ${S}`,` from: #${E}`,` to: #${x}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);let C;try{C=await Og(h,S,x,m)}catch(A){let v=(A instanceof Error?A.message:String(A)).match(/Slack error on conversations\.rename: (\w+)/)?.[1],O={name_taken:`Error: a channel named #${x} already exists.`,invalid_name:`Error: "${x}" is not a valid channel name (lowercase letters, numbers, hyphens, underscores; max 80 chars).`,invalid_name_specials:`Error: "${x}" contains characters Slack doesn't allow in channel names.`,invalid_name_maxlength:`Error: "${x}" 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 #${E} (workspace settings may restrict renaming to admins or the channel creator).`,not_in_channel:`Error: this token isn't a member of #${E} \u2014 join it first.`,is_archived:`Error: #${E} is archived \u2014 unarchive it before renaming.`};console.error((v&&O[v])??ge(A)),process.exit(1)}console.log(`\u2713 Renamed #${E} -> #${C.name} (${C.id})`)}).demandCommand(1,"").showHelpOnFail(!0)).command(["user","usr"],"User commands",(u)=>u.command(["ls","list"],"List workspace members",(l)=>l.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(l)=>{let h=l.json?"jsonl":l.format,m=n(l),b=s(l),_=await Lg(m,b),x=l.filter?.toLowerCase(),S=G(_.members).map(L);if(l.external){let C=new Set(S.map((O)=>String(O.id))),A=L(await lr(m,b)),F=G(A.channels).map(L).filter((O)=>O.is_ext_shared===!0&&!!O.name),v=new Set;for(let O of F)try{for(let M of await Ng(m,String(O.id),b))if(!C.has(M))v.add(M)}catch{}for(let O of v)try{let M=L(await bs(m,O,b)),J=L(M.user);if(J.id)S.push(J)}catch{}}let E=S.filter((C)=>C.deleted!==!0&&C.is_bot!==!0&&String(C.id)!=="USLACKBOT").filter((C)=>{if(!x)return!0;let A=String(C.name??"").toLowerCase(),F=String(L(C.profile).real_name??"").toLowerCase(),v=String(L(C.profile).email??"").toLowerCase();return A.includes(x)||F.includes(x)||v.includes(x)}).slice(0,l.limit);if(h==="jsonl"){for(let C of E)console.log(JSON.stringify(C));return}if(h==="yaml"){for(let C of E){let A=function(F,v=""){if(F===null)return"null";if(typeof F==="string")return F.includes(`
568
570
  `)?`|
569
- ${S.split(`
571
+ ${F.split(`
570
572
  `).join(`
571
- `)}`:S;if(typeof S!=="object")return String(S);if(Array.isArray(S))return S.map((F)=>`
572
- ${x} - ${E(F,x+" ")}`).join("");return Object.entries(S).map(([F,R])=>`
573
- ${x} ${F}: ${E(R,x+" ")}`).join("")};console.log("---");for(let[S,x]of Object.entries(D))console.log(`${S}: ${E(x)}`)}return}let k=Intl.DateTimeFormat().resolvedOptions().timeZone,_=w.length?String(O(G(g.members).map(O)[0]??{}).team_id??""):"";for(let D of w){let E=O(D.profile),S=String(D.name??D.id),x=String(D.id??""),F=String(E.display_name||""),R=String(E.real_name||""),I=String(E.email||""),P=String(D.tz??""),W=[...new Set([F,R].filter((z)=>z&&z!==S))].join(" / "),N=P&&P!==k?P:"",J=String(D.team_id??""),K=D.is_stranger===!0||_&&J&&J!==_?`external:${J||"?"}`:D.is_ultra_restricted===!0?"single-channel guest":D.is_restricted===!0?"guest":"",B=[I,N].filter(Boolean).join(" ");console.log(`@${S} ${x} ${W}${B?" "+B:""}${K?` [${K}]`:""}`)}}).command("get <user>","Show user details",(c)=>c.positional("user",{type:"string",demandOption:!0,describe:"@handle or user ID"}),async(c)=>{let d=t(c),p=n(c),h=c.user.startsWith("@")?c.user:`@${c.user}`,g="";try{g=await vt(d,h,p)}catch(L){console.error(L instanceof Error?L.message:String(L)),process.exit(1)}let y=O(await fs(d,g,p)),m=O(y.user),w=O(m.profile),k=Intl.DateTimeFormat().resolvedOptions().timeZone,_=String(m.name??g),D=String(m.id??g),E=String(w.display_name||""),S=String(w.real_name||""),x=String(w.email||""),F=String(m.tz??""),R=String(w.phone||""),I=String(w.title||"");console.log(`@${_} ${D}`);let P=[...new Set([E,S].filter((L)=>L&&L!==_))];if(P.length)console.log(`name: ${P.join(" / ")}`);if(x)console.log(`email: ${x}`);if(R)console.log(`phone: ${R}`);if(I)console.log(`title: ${I}`);if(F&&F!==k)console.log(`tz: ${F}`)}).demandCommand(1,"").showHelpOnFail(!0)).command("news","Activity feed (mentions to you)",(a)=>a.option("limit",{alias:"l",type:"number",default:20}),async(a)=>{await sx(t(a),a.limit)}).command("search <query>","Full-text search",(a)=>a.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(a)=>{await _m(t(a),a.query,a.count,a.json,n(a))}).command("send <target> <message>","Send a message (confirm-hash safety gate); - as the message reads stdin",(a)=>a.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("fix-urls",{type:"boolean",default:!1,describe:"Wrap ambiguous bare URLs as <url> (cut at the first non-ASCII character / trailing punctuation) before sending"}).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."}).option("to",{type:"string",describe:"Permalink of the message you are answering: refuses when it is not in the target's thread (see also `slack reply --to`)"}).option("json",{type:"boolean",default:!1,describe:"On success print one JSON line: {ok, channel, ts, thread_ts?, permalink?}"}).option("any-thread",{type:"boolean",default:!1,describe:"With --to: send even when the message is in another thread"}),async(a)=>{if(a.to&&!a["any-thread"])try{let c=t(a),d=n(a),p=await ks(c,a.to,d),h=pt(a.target)?await ks(c,a.target,d):void 0,g=h?{channel:h.channel,threadTs:h.root}:(()=>{let w=$t(a.target);return{ref:w.ref,...w.threadTs?{threadTs:w.threadTs}:{}}})(),y="channel"in g?g.channel:await we(c,g.ref,d),m=dc({channel:y,...g.threadTs?{threadTs:g.threadTs}:{}},p);if(m)console.error(`Error: ${m}`),process.exit(2)}catch(c){console.error(ge(c)),process.exit(1)}await r(a)}).command("init [dir]","Create .slack-hub/ in a directory: aliases, settings, inbox/outbox (never committed)",(a)=>a.positional("dir",{type:"string",default:".",describe:"Directory to put .slack-hub/ in"}).option("prefix",{type:"string",describe:'Put in front of every `slack reply`, e.g. "[design]"'}).option("channel",{type:"string",describe:"Default channel (id)"}).option("as-bot",{type:"boolean",describe:"Reply as the bot by default"}),(a)=>{let{dir:c,created:d}=oc(a.dir,{...a.prefix?{prefix:a.prefix}:{},...a.channel?{channel:a.channel}:{},...a["as-bot"]!==void 0?{as_bot:a["as-bot"]}:{}});console.log(d.length?`${c}: created ${d.join(", ")}`:`${c}: already set up`)}).command("alias","Name channels and threads for this directory (the nearest .slack-hub/)",(a)=>a.command(["ls","list"],"List aliases: name, channel, thread, file",(c)=>c.option("json",{type:"boolean",default:!1}),(c)=>{let d=Ve(),p=dn(d);if(c.json){console.log(JSON.stringify(p.map(({scope:h,...g})=>g)));return}for(let h of p)console.log(`${h.name} ${h.channel} ${h.thread_ts??"-"} ${h.file}${h.note?` ${h.note}`:""}`);if(!p.length)console.error(`no aliases in ${d.dir}${d.global?" (no .slack-hub/ above here: `slack init` makes one)":""}`)}).command("set <name> <target>","Name a channel or thread: a permalink (a reply's names its thread root), #chan:<ts>, or #chan",(c)=>c.positional("name",{type:"string",demandOption:!0}).positional("target",{type:"string",demandOption:!0}).option("note",{type:"string",describe:"Free text shown by `alias ls`"}).option("shared",{type:"boolean",default:!1,describe:"Write settings.yml (the allowlist owner's file) instead of settings.local.yml"}).option("dir",{type:"string",describe:"Use the .slack-hub/ above this directory instead of the cwd's (with --shared: a lane's dir)"}),async(c)=>{let d=t(c),p=n(c),h=Ve(c.dir),g=pt(c.target)?.ts!==void 0||$t(c.target).threadTs!==void 0,y,m,w="";if(g){let D=await ks(d,c.target,p);if(y=D.channel,m=D.root,D.root!==D.ts)w=` (${D.ts} is a reply: named its thread root)`}else y=await we(d,$t(c.target).ref,p);let k;try{k=lc(h,c.name,{channel:y,...m?{thread_ts:m}:{},...c.note?{note:c.note}:{}},c.shared)}catch(D){if(D instanceof Nn)console.error(`Error: ${D.message}`),process.exit(2);throw D}let _=k&&(k.channel!==y||k.thread_ts!==m)?` (was ${k.channel} ${k.thread_ts??"-"})`:"";console.log(`${c.name} \u2192 ${y} ${m??"-"}${w}${_} [${h.dir}]`)}).command(["unset <name>","rm <name>"],"Remove an alias (from settings.local.yml; --shared: also from settings.yml)",(c)=>c.positional("name",{type:"string",demandOption:!0}).option("shared",{type:"boolean",default:!1,describe:"Allow removing one defined in settings.yml"}).option("dir",{type:"string",describe:"Use the .slack-hub/ above this directory"}),(c)=>{let d=Ve(c.dir),p;try{p=Fp(d,c.name,c.shared)}catch(h){if(h instanceof Nn)console.error(`Error: ${h.message}`),process.exit(2);throw h}if(p==="removed")console.log(`${c.name} removed [${d.dir}]`);else if(p==="absent")console.error(`no alias "${c.name}" in ${d.dir}`),process.exit(2);else console.error(`"${c.name}" is defined in ${d.dir}/settings.yml: edit that file to remove it`),process.exit(2)}).command("who <channel> <ts>","Which registered .slack-hub/ dirs subscribe this thread (or message): dir, alias",(c)=>c.positional("channel",{type:"string",demandOption:!0,describe:"Channel id"}).positional("ts",{type:"string",demandOption:!0,describe:"Thread root ts (a reply's own ts is not its thread)"}).option("json",{type:"boolean",default:!1}),(c)=>{let d=Ip(c.channel,c.ts).map((p)=>({dir:zD(p.scope.dir),scope:p.scope.dir,alias:p.name,file:p.file}));if(c.json)console.log(JSON.stringify(d));else for(let p of d)console.log(`${p.dir} ${p.alias}`);if(!d.length)process.exitCode=2}).command("import <tsv>","One-shot: import a legacy allowlist.tsv (<thread_ts> TAB <lane>) into each lane's settings.yml",(c)=>c.positional("tsv",{type:"string",demandOption:!0}).option("channel",{type:"string",demandOption:!0,describe:"The channel every thread is in (for a DM: the DM id)"}).option("lane-dir",{type:"array",string:!0,demandOption:!0,describe:"<lane>=<dir> (a directory holding .slack-hub/, made if missing); repeatable"}),(c)=>{let d=new Map;for(let g of c["lane-dir"]??[]){let y=String(g).indexOf("=");if(y<=0)console.error(`Error: --lane-dir ${g}: want <lane>=<dir>`),process.exit(2);d.set(String(g).slice(0,y),String(g).slice(y+1))}let p=0,h=new Map;for(let g of wl(c.tsv,"utf8").split(`
574
- `)){let[y,m]=g.trim().split("\t");if(!y||g.startsWith("#")||!m)continue;let w=d.get(m);if(!w||!/^\d{10}\.\d{6}$/.test(y)){h.set(m,(h.get(m)??0)+1);continue}let k={dir:oc(w).dir,global:!1};lc(k,`t-${y}`,{channel:c.channel,thread_ts:y,note:"imported from legacy allowlist"},!0),p++}console.log(`imported ${p} subscription(s)`);for(let[g,y]of h)console.error(`skipped ${y} line(s) for lane "${g}" (no --lane-dir, or not a ts)`)}).demandCommand(1,"alias needs a subcommand: ls, set, unset, who, import")).command("reply [dest] [message]","Reply in a thread \u2014 an alias, a permalink or #chan:<ts> \u2014 with the directory's prefix (confirm-hash gate, like send)",(a)=>a.positional("dest",{type:"string",describe:"alias | permalink | #chan:<ts> | <ts> (in settings' channel). Omit with --to"}).positional("message",{type:"string",describe:"Text, or - for stdin"}).option("json",{type:"boolean",default:!1,describe:"On success print one JSON line: {ok, channel, ts, thread_ts, permalink?}"}).option("to",{type:"string",describe:"Permalink of the message you are answering: replies in ITS thread; with a dest, refuses when they differ"}).option("any-thread",{type:"boolean",default:!1,describe:"With --to and a dest: post to dest even when the message is in another thread"}).option("prefix",{type:"string",describe:`Override settings' prefix ("" for none)`}).option("code",{type:"string",describe:"Safety hash to confirm send"}).option("as-bot",{type:"boolean",describe:"Send via the bot token (default: settings' as_bot)"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing ambiguous bare URL boundaries"}).option("fix-urls",{type:"boolean",default:!1,describe:"Wrap ambiguous bare URLs as <url> (cut at the first non-ASCII character / trailing punctuation) before sending"}).option("broadcast",{type:"boolean",default:!1,describe:"Also send to channel"}).option("mentions",{type:"boolean",default:!0,describe:"Convert @handle tokens to real mentions (--no-mentions for literal text)"}),async(a)=>{let{dest:c,message:d}=a;if(a.to&&d===void 0)d=c,c=void 0;if(pl(d))d=await hl();if(d===void 0||!d.trim())console.error("Error: message is empty"),process.exit(1);if(!c&&!a.to)console.error("Error: reply needs a destination (alias, permalink, #chan:<ts>) or --to <permalink>"),process.exit(2);let p=t(a),h=n(a),g=Ve(),y=cs(g),m;try{let D=await sm(p,h,g,c,a.to,a["any-thread"]);if("error"in D)console.error(`Error: ${D.error}`),process.exit(2);m=D}catch(D){console.error(ge(D)),process.exit(1)}let{channel:w,threadTs:k}=m;if(Mn(g)&&(a.prefix!==void 0||a["as-bot"]!==void 0&&a["as-bot"]!==(y.as_bot??!1)))console.error(`Error: ${g.dir} is restricted: who it posts as (prefix, as_bot) comes from settings.yml; --prefix / --as-bot are refused`),process.exit(2);let _=uc(d,a.prefix??y.prefix);if(!_.trim())console.error("Error: message is empty (only the prefix)"),process.exit(1);await r({workspace:a.workspace,target:`${w}:${k}`,message:_,code:a.code,"allow-url-adjacent":a["allow-url-adjacent"],"fix-urls":a["fix-urls"],"as-bot":a["as-bot"]??y.as_bot??!1,broadcast:a.broadcast,mentions:a.mentions,json:a.json})}).command("inbox","This directory's .slack-hub/inbox/: messages routed here by `slack stream --inbox`",(a)=>a.command(["ls","list"],"Pending messages: ts, from, alias, text (redacted)",(c)=>c.option("json",{type:"boolean",default:!1}),(c)=>{let d=ls(Ve());if(c.json){console.log(JSON.stringify(d.map((p)=>({file:p.file,...p.entry}))));return}for(let p of d)console.log(`${p.entry.ts} ${p.entry.user_name??p.entry.user} ${p.entry.alias} ${p.entry.text.replace(/\\/g,"\\\\").replace(/\n/g,"\\n").replace(/\t/g,"\\t")}${p.entry.files?` [files: ${p.entry.files}]`:""}`)}).command("listen","Print each message as it arrives in inbox/ (one JSON line each); pending ones first. Exits 0 at --timeout",(c)=>c.option("timeout",{type:"number",default:3600,describe:"Seconds"}).option("new-only",{type:"boolean",default:!1,describe:"Skip what is already pending"}).option("thread",{type:"string",describe:"Only messages in this thread (its root ts)"}).option("alias",{type:"string",describe:"Only messages routed by this alias"}).option("from",{type:"array",string:!0,describe:"Only messages from these user ids; repeatable"}),async(c)=>{let d=Ve(),p=c.from?.length?new Set(c.from.map(String)):void 0,h=(m)=>(!c.thread||(m.thread_ts??m.ts)===c.thread)&&(!c.alias||m.alias===c.alias)&&(!p||p.has(m.user)),g=new Set;if(c["new-only"])for(let m of ls(d))g.add(m.file);let y=Date.now()+c.timeout*1000;for(;;){for(let m of ls(d)){if(g.has(m.file))continue;if(g.add(m.file),h(m.entry))console.log(JSON.stringify({file:m.file,...m.entry}))}if(Date.now()>=y)break;await new Promise((m)=>setTimeout(m,Math.min(500,Math.max(0,y-Date.now()))))}}).command("nudge","Pending messages older than settings' nudge_after_min (default 30): exit 1 when there are any; --eyes also puts \uD83D\uDC40 on each, once",(c)=>c.option("json",{type:"boolean",default:!1}).option("eyes",{type:"boolean",default:!1,describe:"React \uD83D\uDC40 on each overdue message (once per message: recorded as nudged_at)"}).option("as-bot",{type:"boolean",describe:"React via the bot token (default: settings' as_bot)"}),async(c)=>{let d=Ve(),p=sh(d);if(c.eyes){let h=c["as-bot"]??cs(d).as_bot??!1,g=h?Ne():t(c);if(!g)console.error("Error: as_bot needs a bot token (SLACK_BOT_TOKEN)"),process.exit(1);let y=h?void 0:n(c);for(let m of p){if(m.entry.nudged_at)continue;try{await It(g,m.entry.channel,m.entry.ts,"eyes",y)}catch(w){if(!/already_reacted/.test(w instanceof Error?w.message:String(w))){console.error(`\u26A0 ${m.entry.channel}:${m.entry.ts}: could not add \uD83D\uDC40: ${ge(w)}`);continue}}rh(m),m.entry.nudged_at=new Date().toISOString()}}if(c.json)console.log(JSON.stringify(p.map((h)=>({file:h.file,ts:h.entry.ts,channel:h.entry.channel,permalink:h.entry.permalink,waiting_min:Math.round((Date.now()-h.mtimeMs)/60000),...h.entry.nudged_at?{nudged_at:h.entry.nudged_at}:{}}))));else for(let h of p)console.log(`${h.entry.ts} ${Math.round((Date.now()-h.mtimeMs)/60000)} min ${h.entry.permalink}${h.entry.nudged_at?"\t\uD83D\uDC40":""}`);if(p.length)process.exitCode=1}).demandCommand(1,"inbox needs a subcommand: ls, listen, nudge")).command("done <ref..>","Mark inbox messages handled (moved to archived/) without replying: a file name, path or message ts",(a)=>a.positional("ref",{type:"string",array:!0,demandOption:!0}),(a)=>{let c=Ve(),d=0;for(let p of a.ref){let h=gc(c,p);if(h)console.log(`archived ${h}`);else console.error(`not in ${c.dir}/inbox: ${p}`),d++}if(d)process.exit(2)}).command("outbox","This directory's .slack-hub/outbox/: replies queued as files, sent by `outbox flush`",(a)=>a.command("add <dest> <message>","Queue a reply (text redacted before it is written; - reads stdin)",(c)=>c.positional("dest",{type:"string",demandOption:!0,describe:"alias | permalink | #chan:<ts>"}).positional("message",{type:"string",demandOption:!0}).option("in-reply-to",{type:"string",describe:"ts of the inbox message this answers: archived once sent"}),async(c)=>{let d=pl(c.message)?await hl():c.message;if(!d.trim())console.error("Error: message is empty"),process.exit(1);let p=eh(Ve(),{to:c.dest,text:d,...c["in-reply-to"]?{in_reply_to:c["in-reply-to"]}:{}});if(p.redacted.length)console.error(`\u26A0 redacted before queueing: ${p.redacted.join(", ")}`);console.log(p.file)}).command(["ls","list"],"Queued replies: file, dest, attempts, error",(c)=>c,()=>{for(let c of mc(Ve()))console.log(`${c.file} ${c.entry.to}${c.entry.attempts?` attempts=${c.entry.attempts} ${c.entry.error??""}`:""}`)}).command("flush","Send every queued reply (prefix, thread and restrict checks as `reply`); a --code covers the whole batch",(c)=>c.option("code",{type:"string",describe:"Safety hash to confirm the batch"}).option("as-bot",{type:"boolean",describe:"Send via the bot token (default: settings' as_bot)"}),async(c)=>{let d=Ve(),p=cs(d),h=mc(d);if(!h.length){console.error(`nothing in ${d.dir}/outbox`);return}if(Mn(d)&&c["as-bot"]!==void 0&&c["as-bot"]!==(p.as_bot??!1))console.error(`Error: ${d.dir} is restricted: as_bot comes from settings.yml; --as-bot is refused`),process.exit(2);let g=c["as-bot"]??p.as_bot??!1,y=t(c),m=n(c),w,k;if(g){let F=Ne();if(!F)console.error("Error: as_bot needs a bot token (SLACK_BOT_TOKEN)"),process.exit(1);w=F}else w=y,k=m;let _=[],D=[];for(let F of h)try{let R=await sm(y,m,d,F.entry.to,void 0);if("error"in R){D.push(`${F.file}: ${R.error}`);continue}let I=uc(F.entry.text,p.prefix);if(!I.trim()){D.push(`${F.file}: empty`);continue}qe(I),_.push({item:F,...R,text:I})}catch(R){D.push(`${F.file}: ${ge(R)}`)}for(let F of D)console.error(`refused (stays queued): ${F}`);if(!_.length)process.exit(2);let E=[`OUTBOX \u2014 ${_.length} repl${_.length===1?"y":"ies"}${g?" as the bot":""}:`];for(let F of _)E.push(` \u2192 ${F.channel} thread ${F.threadTs}: ${M(F.text).replace(/\n/g,"\u23CE").slice(0,120)}${F.text.includes("[redacted:")?" (secrets were masked when queued: this is what posts)":""}`);let S=De("outbox",g?"bot":"user",..._.map((F)=>`${F.channel}:${F.threadTs}:${F.text}`));if(c.code!==S)Se(c.code,S,E);let x=0;for(let F of _)try{let R=await Jt(w,F.channel,F.text,F.threadTs,!1,k),I="";try{I=await jn(w,F.channel,R,k)}catch{}let P=th(d,F.item,{ts:R,permalink:I,channel:F.channel,thread_ts:F.threadTs});console.log(`\u2713 ${I||R} (${P})`)}catch(R){nh(F.item,ge(R)),console.error(`\u2717 ${F.item.file}: ${ge(R)}`),x++}if(x)process.exit(1)}).demandCommand(1,"outbox needs a subcommand: add, ls, flush")).command("ask [target] [question] [choices..]","Ask a question with its choices pre-seeded as 1\uFE0F\u20E3..\uD83D\uDD1F reactions (confirm-hash safety gate). Lifecycle: --waitFor=<link> collect, --void=<link> void (verb aliases: `ask collect <link>`, `ask void <link\u2026>`)",(a)=>a.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("lang",{type:"string",choices:[...Tt],describe:"Language of the instructions in the posted body. Default: $SLACK_HUB_LANG, else the answerers' Slack locale, else the question's own language, else the system locale, else ja"}).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), 6 = the question was voided (`slack ask void`) \u2014 stop waiting. 7 = only with --explain-exit: \u2139\uFE0F pressed, explain and collect again (the question stays open)."}).option("waitFor",{type:"string",describe:"Collect the answer to a question already posted: pass its permalink. Nothing is posted (except, on an --explain question someone pressed \u2139\uFE0F on, one thread note per question). Same stdout/exit contract as --wait; --timeout 0 checks once and exits 2 if still open."}).option("after",{type:"string",describe:"With --waitFor: the cursor \u2014 everything at or before this ts was already delivered. Text replies there are neither answers nor notes again (pass the `cursor` a previous --json result gave you, or the reply ts an exit 5 printed). Reactions still count."}).option("void",{type:"string",array:!0,describe:"Void question(s) you posted that expired or stopped meaning anything \u2014 --void=<permalink>, repeatable. The text becomes \uD83D\uDEAB with --reason (body kept, options removed), our pills come off, and --wait/--waitFor on it exits 6. Same --code gate. Only your own questions (--as-bot for the bot's). Alias: `slack ask void <link\u2026>`."}).option("reask",{type:"boolean",default:!1,describe:"With ONE --void: post the question again (same channel/thread, same text and choices unless you give new ones as positionals / --body) and void the old one as replaced by it \u2014 one gate for both. The way to change the options of a question someone already answered."}).option("edit",{type:"string",describe:'Change an open question you posted: --edit=<permalink> ["new question" [choices\u2026]] [--body \u2026]. Rebuilt with the ask layout so collect still reads it. Options can change only while nobody has answered (then: --void=<link> --reask). Same --code gate.'}).option("ls",{type:"boolean",default:!1,describe:"List the questions you posted (local sent-log) with their LIVE state: --state open|answered|void|all (default open), --stale 24h, --channel, --json. With --stale it prints the --void command that would retire them."}).option("pending",{type:"boolean",default:!1,describe:"List questions THIS machine asked (local sent-log) that somebody answered but nobody collected, grouped by the asking session, with whether that agent is still alive and the --waitFor line that collects each. Read-only unless --push: --since 7d, --channel, --json. Never waits out a rate limit: a throttled pass says how many it skipped."}).option("push",{type:"boolean",default:!1,describe:"With --pending: send each answer to the agent that asked (ay send to the pid in the sent-log, or up to 3 of its parents), then collect a decision (\u2705, off this list); a free-text reply is marked delivered, the question stays open. A gone asker's answer goes to the newest live agent in the same directory (a restarted lane), else it stays listed. Each answer is pushed once."}).option("undelivered",{type:"boolean",default:!1,describe:"With --pending: the sweep \u2014 only answers that have reached nobody yet. With --push, also why (asker gone and no live agent in its directory, or ay refused)."}).option("watch",{type:"boolean",default:!1,describe:"With --pending --push: keep running \u2014 a pass every --interval, and one for a question as soon as the relay rings for it (SLACK_RELAY_URL / SLACK_RELAY_TOKEN). Prints only what it pushed."}).option("interval",{type:"number",default:10,describe:"With --watch: minutes between full passes"}).option("since",{type:"string",default:"7d",describe:"With --pending: how far back to look (30m, 2h, 7d, or an ISO date)"}).option("stale",{type:"string",describe:"With --ls: only open questions older than this (24h, 3d)"}).option("state",{type:"string",default:"open",choices:["open","answered","void","edited","gone","unknown","all"],describe:"With --ls: which state to list"}).option("channel",{type:"string",describe:"With --ls / --pending: only this channel (id, or the target as typed)"}).option("limit",{type:"number",default:50,describe:"With --ls: how many recent asks to check"}).option("reason",{type:"string",describe:"With --void: why it is void (written into the message)"}).option("superseded-by",{type:"string",describe:"With --void: permalink of the question that replaces it"}).option("explain",{type:"boolean",describe:"Also offer an \u2139\uFE0F 'explain' pill (seeded after \u2795): pressing it asks YOU to explain the question in its thread and is never an answer \u2014 the question stays open. --wait/--waitFor report it on stderr (and as `explain` in --json), and post one thread note per question. Default: $SLACK_HUB_ASK_EXPLAIN=1 turns it on; --no-explain turns it off."}).option("explain-exit",{type:"boolean",default:!1,describe:'With --wait / --waitFor: exit 7 (stdout empty; --json status "explain") when someone presses \u2139\uFE0F \u2014 once per question, on the run that posts the thread note. The question stays open: explain, then collect again.'}).option("json",{type:"boolean",default:!1,describe:"With --pending: one JSON object per answered question (sender, answer, collect command). With --wait / --waitFor: print ONE JSON object on stdout \u2014 {status, answer, how, who, notes:[{ts,user,text,permalink}], cursor, permalink} \u2014 instead of the bare answer. `notes` are the audience's replies that are not the answer (thread replies; plain replies too in a 1:1 DM). Exit codes unchanged."}).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. @tags and an @user target then resolve with the bot token too (needs users:read)."}),async(a)=>{if(a.ls||a.pending){if(a.ls&&a.pending)console.error("Error: --ls and --pending are separate lists \u2014 pick one."),process.exit(oe);let D=(()=>{try{return t(a)}catch{return}})(),E={};if(D)E.user=D;let S=Ne();if(S)E.bot=S;let x=n(a);if(x)E.cookie=x;if(a.pending){if(a.target||a.question||a.waitFor||a.wait||a.void||a.edit)console.error("Error: --pending reads the local log \u2014 do not also pass a target/question or another ask action."),process.exit(oe);let R=ds(String(a.since));if(R===void 0)console.error(`Error: --since needs 30m / 2h / 7d / 1w or an ISO date (got ${M(String(a.since))})`),process.exit(oe);if(a.watch&&!a.push)console.error("Error: --watch keeps pushing answers \u2014 use it with --push."),process.exit(oe);let I={sinceMs:R,json:!!a.json,push:!!a.push,undelivered:!!a.undelivered};if(a.channel)I.channel=String(a.channel);if(a.workspace)I.selfArgs=["-w",String(a.workspace)];if(a.watch){let P=Number(a.interval);if(!(P>0))console.error("Error: --interval needs a number of minutes above 0."),process.exit(oe);let L=String(a.since),W=new Set;await Gx(async(N)=>{let J=await dm(E,{...I,sinceMs:ds(L)??R,watch:!0,...N?{only:N}:{skip:W}});if(N)return;if(J.throttled)for(let K of J.checked)W.add(K);else W.clear()},()=>ds(L)??R,()=>(W.size?Math.min(2,P):P)*60000)}try{await dm(E,I)}catch(P){console.error(ge(P)),process.exit(oe)}return}let F={state:String(a.state??"open"),json:!!a.json,limit:Number(a.limit)||50};if(a.stale)F.stale=String(a.stale);if(a.channel)F.channel=String(a.channel);await Hx(E,F);return}let c=(D)=>{if(!D){let S=n(a);return S?{token:t(a),cookie:S}:{token:t(a)}}let E=Ne();if(!E)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
575
- Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(oe);return{token:E}},d=a.target!==void 0&&a.target!=="void"&&a.target!=="collect"?String(a.target):void 0,p=[a.question,...a.choices??[]].filter((D)=>D!==void 0).map(String);if(a.edit){if(a.void||a.wait||a.waitFor)console.error("Error: --edit changes one open question \u2014 do not combine it with --void/--wait/--waitFor."),process.exit(oe);let{token:D,cookie:E}=c(!!a["as-bot"]),S={link:String(a.edit),asBot:!!a["as-bot"],mentionToken:D,allowUrlAdjacent:!!a["allow-url-adjacent"]};if(d!==void 0)S.question=d;if(p.length)S.choices=p.map((x)=>x.trim()).filter(Boolean);if(a.body!==void 0)S.body=String(a.body);if(a.lang)S.lang=String(a.lang);if(a.code)S.code=String(a.code);if(E)S.cookie=E,S.mentionCookie=E;try{await qx(D,S)}catch(x){console.error(ge(x)),process.exit(oe)}return}let h,g=(a.void??[]).map(String).filter(Boolean);if(a.reask){if(g.length!==1||a.target==="void")console.error("Error: --reask goes with exactly one --void=<permalink> (the question to replace)."),process.exit(oe);if(a.waitFor)console.error("Error: --reask posts a new question \u2014 --wait works, --waitFor does not."),process.exit(oe);let{token:D,cookie:E}=c(!!a["as-bot"]),S=await Be(D,E),x=await Pm(D,g[0],S,!!a["as-bot"],E);if(x==="void")console.error(`\u2717 ${M(g[0])}: already voided \u2014 to ask again, just use slack ask`),process.exit(oe);if(!x)process.exit(oe);if(h={...x,reason:We(String(a.reason??"")).trim()},a.target=x.threadTs?`${x.channelId}:${x.threadTs}`:x.channelId,a["channel-id"]=x.channelId,a.question=d??hs(x.parsed.question),a.choices=p.length?p:[...x.parsed.reactable,...x.parsed.overflow].map(hs),a.body===void 0&&x.parsed.body)a.body=hs(x.parsed.body);if(!a.lang)a.lang=x.parsed.lang;if(a.explain===void 0&&x.parsed.explain)a.explain=!0;a.void=void 0}if(!h&&(a.target==="void"||g.length)){let D=a.target==="void"?[a.question,...a.choices??[]]:[];if(a.target!=="void"&&(a.target||a.question||a.choices?.length))console.error("Error: --void voids existing questions \u2014 do not also pass a target/question/choices."),process.exit(oe);let E=[...g,...D.map((R)=>String(R??""))].filter(Boolean);if(!E.length)console.error("Error: --void=<permalink> \u2014 which question(s)?"),process.exit(oe);if(a.wait||a.waitFor)console.error("Error: --void voids existing questions \u2014 do not also pass --wait/--waitFor."),process.exit(oe);let S,x;if(a["as-bot"]){let R=Ne();if(!R)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
576
- Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(oe);S=R}else S=t(a),x=n(a);let F={links:E,reason:We(String(a.reason??"")).trim(),asBot:!!a["as-bot"]};if(a["superseded-by"])F.supersededBy=String(a["superseded-by"]);if(a.code)F.code=String(a.code);if(x)F.cookie=x;try{await Vx(S,F)}catch(R){console.error(ge(R)),process.exit(oe)}return}if(a.target==="collect"){if(!a.question||a.choices?.length)console.error("Error: slack ask collect <permalink> \u2014 exactly one question."),process.exit(oe);a.waitFor=String(a.question),a.target=void 0,a.question=void 0}let y=a.waitFor?String(a.waitFor):"",m=Number(a.timeout);if(!Number.isFinite(m)||m<0||m===0&&!y)console.error("Error: --timeout must be a positive number of seconds"),process.exit(oe);if(y){if(a.target||a.question||a.choices?.length)console.error("Error: --waitFor collects an existing question \u2014 do not also pass a target/question/choices."),process.exit(oe);let D,E;if(a["as-bot"]){let S=Ne();if(!S)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
577
- Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(oe);D=S}else D=t(a),E=n(a);try{let S={link:y,timeout:m,asBot:!!a["as-bot"],json:!!a.json};if(a["explain-exit"])S.explainExit=!0;if(E)S.cookie=E;if(a.after){let x=String(a.after);if(!/^\d{10}\.\d{6}$/.test(x))console.error(`Error: --after needs a message ts like 1700000000.000100 (got ${M(x)})`),process.exit(oe);S.after=x}await Zx(D,S)}catch(S){console.error(ge(S)),process.exit(oe)}return}if(!a.target)console.error("Error: target is required (or use --waitFor <permalink> to collect an answer)"),process.exit(oe);let w=String(a.question??"").trim();if(!w)console.error("Error: question is empty"),process.exit(oe);let k={allowUrlAdjacent:a["allow-url-adjacent"],target:a.target,question:w,choices:(a.choices??[]).map((D)=>String(D).trim()).filter(Boolean),timeout:m};if(a.code)k.code=a.code;if(a.body)k.body=a.body;if(a.lang)k.lang=String(a.lang);if(a.wait)k.wait=!0;if(a.json)k.json=!0;if(typeof a.explain==="boolean")k.explain=a.explain;if(a["explain-exit"])k.explainExit=!0;if(h)k.voidAfter=h;if(a["channel-id"])k.channelId=a["channel-id"];if(a["user-id"])k.userId=a["user-id"];let _;if(a["as-bot"]){let D=Ne();if(!D)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
578
- Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(oe);if(!k.channelId&&!k.userId&&k.target.startsWith("@"))try{k.userId=await vt(D,k.target)}catch(E){console.error(`Error: could not resolve ${k.target} to a user for the bot DM.
573
+ `)}`:F;if(typeof F!=="object")return String(F);if(Array.isArray(F))return F.map((O)=>`
574
+ ${v} - ${A(O,v+" ")}`).join("");return Object.entries(F).map(([O,M])=>`
575
+ ${v} ${O}: ${A(M,v+" ")}`).join("")};console.log("---");for(let[F,v]of Object.entries(C))console.log(`${F}: ${A(v)}`)}return}let I=Intl.DateTimeFormat().resolvedOptions().timeZone,N=E.length?String(L(G(_.members).map(L)[0]??{}).team_id??""):"";for(let C of E){let A=L(C.profile),F=String(C.name??C.id),v=String(C.id??""),O=String(A.display_name||""),M=String(A.real_name||""),J=String(A.email||""),j=String(C.tz??""),X=[...new Set([O,M].filter((z)=>z&&z!==F))].join(" / "),U=j&&j!==I?j:"",ie=String(C.team_id??""),q=C.is_stranger===!0||N&&ie&&ie!==N?`external:${ie||"?"}`:C.is_ultra_restricted===!0?"single-channel guest":C.is_restricted===!0?"guest":"",ce=[J,U].filter(Boolean).join(" ");console.log(`@${F} ${v} ${X}${ce?" "+ce:""}${q?` [${q}]`:""}`)}}).command("get <user>","Show user details",(l)=>l.positional("user",{type:"string",demandOption:!0,describe:"@handle or user ID"}),async(l)=>{let h=n(l),m=s(l),b=l.user.startsWith("@")?l.user:`@${l.user}`,_="";try{_=await Nt(h,b,m)}catch(ee){console.error(ee instanceof Error?ee.message:String(ee)),process.exit(1)}let x=L(await bs(h,_,m)),S=L(x.user),E=L(S.profile),I=Intl.DateTimeFormat().resolvedOptions().timeZone,N=String(S.name??_),C=String(S.id??_),A=String(E.display_name||""),F=String(E.real_name||""),v=String(E.email||""),O=String(S.tz??""),M=String(E.phone||""),J=String(E.title||"");console.log(`@${N} ${C}`);let j=[...new Set([A,F].filter((ee)=>ee&&ee!==N))];if(j.length)console.log(`name: ${j.join(" / ")}`);if(v)console.log(`email: ${v}`);if(M)console.log(`phone: ${M}`);if(J)console.log(`title: ${J}`);if(O&&O!==I)console.log(`tz: ${O}`)}).demandCommand(1,"").showHelpOnFail(!0)).command("news","Activity feed (mentions to you)",(u)=>u.option("limit",{alias:"l",type:"number",default:20}),async(u)=>{await Ux(n(u),u.limit)}).command("search <query>","Full-text search",(u)=>u.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(u)=>{await Vm(n(u),u.query,u.count,u.json,s(u))}).command("send <target> <message>","Send a message (confirm-hash safety gate); - as the message reads stdin",(u)=>u.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("fix-urls",{type:"boolean",default:!1,describe:"Wrap ambiguous bare URLs as <url> (cut at the first non-ASCII character / trailing punctuation) before sending"}).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."}).option("to",{type:"string",describe:"Permalink of the message you are answering: refuses when it is not in the target's thread (see also `slack reply --to`)"}).option("json",{type:"boolean",default:!1,describe:"On success print one JSON line: {ok, channel, ts, thread_ts?, permalink?}"}).option("any-thread",{type:"boolean",default:!1,describe:"With --to: send even when the message is in another thread"}),async(u)=>{if(u.to&&!u["any-thread"])try{let l=n(u),h=s(u),m=await $s(l,u.to,h),b=ht(u.target)?await $s(l,u.target,h):void 0,_=b?{channel:b.channel,threadTs:b.root}:(()=>{let E=At(u.target);return{ref:E.ref,...E.threadTs?{threadTs:E.threadTs}:{}}})(),x="channel"in _?_.channel:await we(l,_.ref,h),S=Ec({channel:x,..._.threadTs?{threadTs:_.threadTs}:{}},m);if(S)console.error(`Error: ${S}`),process.exit(2)}catch(l){console.error(ge(l)),process.exit(1)}await i(u)}).command("jobs [jobId]","Background `--async` sends: list recent jobs, or show one (status, permalink, error output)",(u)=>u.positional("jobId",{type:"string",describe:"A job id from `--async`; omit to list recent jobs"}).option("limit",{type:"number",default:20,describe:"Jobs to list"}).option("json",{type:"boolean",default:!1}),async(u)=>{let l=await import("fs"),h=await import("path"),m=await import("os"),b=h.join(m.homedir(),".local","state","slack-post","jobs");if(u.jobId){let x=h.join(b,`${u.jobId}.json`);if(!/^[0-9a-z-]+$/.test(u.jobId)||!l.existsSync(x))console.error(`Error: job not found: ${u.jobId} (list them: slack jobs)`),process.exit(1);let S=JSON.parse(l.readFileSync(x,"utf8"));if(delete S.stdin,u.json){console.log(JSON.stringify(S));return}console.log(`job ${S.jobId}: ${S.status}${S.who?` as @${S.who}`:""}`),console.log(` command: slack ${W(S.target??"")}`);for(let E of["createdAt","startedAt","finishedAt","permalink"])if(S[E])console.log(` ${E}: ${S[E]}`);if(S.error)console.log(` output:
576
+ ${W(S.error).split(`
577
+ `).map((E)=>` ${E}`).join(`
578
+ `)}`);return}let _=[];try{for(let x of l.readdirSync(b)){if(!x.endsWith(".json"))continue;try{_.push(JSON.parse(l.readFileSync(h.join(b,x),"utf8")))}catch{}}}catch{}if(_=_.sort((x,S)=>(S.createdAt??"").localeCompare(x.createdAt??"")).slice(0,Math.max(1,u.limit)),u.json){for(let x of _)console.log(JSON.stringify({jobId:x.jobId,status:x.status,createdAt:x.createdAt,finishedAt:x.finishedAt,permalink:x.permalink,error:x.error}));return}if(!_.length){console.log("No --async jobs yet.");return}for(let x of _){let S=(x.createdAt??"").replace("T"," ").slice(0,19),E=x.status==="done"?x.permalink??"":x.status==="failed"?(x.error??"").split(`
579
+ `).pop()??"":"";console.log(`${S} ${x.jobId} ${x.status.padEnd(7)} ${W(E).slice(0,120)}`)}}).command("_post-worker <jobFile>",!1,(u)=>u.positional("jobFile",{type:"string",demandOption:!0}),async(u)=>{let l=await import("fs"),h=await import("path"),{spawnSync:m}=await import("child_process"),b=u.jobFile,_=h.join(h.dirname(h.dirname(b)),"last-failed.json"),x=JSON.parse(l.readFileSync(b,"utf8"));x.status="running",x.startedAt=new Date().toISOString(),l.writeFileSync(b,JSON.stringify(x,null,2),{mode:384}),l.chmodSync(b,384);let S=m(process.execPath,[process.argv[1],...x.who?[`@${x.who}`]:[],...x.forwardArgs],{encoding:"utf8",...typeof x.stdin==="string"?{input:x.stdin}:{}});if(delete x.stdin,x.finishedAt=new Date().toISOString(),S.status===0){try{let E=JSON.parse(S.stdout.trim().split(`
580
+ `).pop()||"{}");x.status="done",x.ts=E.ts,x.permalink=E.permalink}catch{x.status="done"}try{l.unlinkSync(_)}catch{}}else x.status="failed",x.error=(S.stderr||S.stdout||`exit ${S.status}`).trim().slice(-500),l.writeFileSync(_,JSON.stringify({jobId:x.jobId,target:x.target,error:x.error,finishedAt:x.finishedAt},null,2),{mode:384}),l.chmodSync(_,384);if(l.writeFileSync(b,JSON.stringify(x,null,2),{mode:384}),l.chmodSync(b,384),x.callback)m("bash",["-lc",x.callback],{env:{...process.env,SLACK_POST_JOB_ID:x.jobId,SLACK_POST_STATUS:x.status,SLACK_POST_TS:x.ts||"",SLACK_POST_PERMALINK:x.permalink||"",SLACK_POST_ERROR:x.error||""}})}).command("init [dir]","Create .slack-hub/ in a directory: aliases, settings, inbox/outbox (never committed)",(u)=>u.positional("dir",{type:"string",default:".",describe:"Directory to put .slack-hub/ in"}).option("prefix",{type:"string",describe:'Put in front of every `slack reply`, e.g. "[design]"'}).option("channel",{type:"string",describe:"Default channel (id)"}).option("as-bot",{type:"boolean",describe:"Reply as the bot by default"}),(u)=>{let{dir:l,created:h}=wc(u.dir,{...u.prefix?{prefix:u.prefix}:{},...u.channel?{channel:u.channel}:{},...u["as-bot"]!==void 0?{as_bot:u["as-bot"]}:{}});console.log(h.length?`${l}: created ${h.join(", ")}`:`${l}: already set up`)}).command("alias","Name channels and threads for this directory (the nearest .slack-hub/)",(u)=>u.command(["ls","list"],"List aliases: name, channel, thread, file",(l)=>l.option("json",{type:"boolean",default:!1}),(l)=>{let h=Ze(),m=pn(h);if(l.json){console.log(JSON.stringify(m.map(({scope:b,..._})=>_)));return}for(let b of m)console.log(`${b.name} ${b.channel} ${b.thread_ts??"-"} ${b.file}${b.note?` ${b.note}`:""}`);if(!m.length)console.error(`no aliases in ${h.dir}${h.global?" (no .slack-hub/ above here: `slack init` makes one)":""}`)}).command("set <name> <target>","Name a channel or thread: a permalink (a reply's names its thread root), #chan:<ts>, or #chan",(l)=>l.positional("name",{type:"string",demandOption:!0}).positional("target",{type:"string",demandOption:!0}).option("note",{type:"string",describe:"Free text shown by `alias ls`"}).option("shared",{type:"boolean",default:!1,describe:"Write settings.yml (the allowlist owner's file) instead of settings.local.yml"}).option("dir",{type:"string",describe:"Use the .slack-hub/ above this directory instead of the cwd's (with --shared: a lane's dir)"}),async(l)=>{let h=n(l),m=s(l),b=Ze(l.dir),_=ht(l.target)?.ts!==void 0||At(l.target).threadTs!==void 0,x,S,E="";if(_){let C=await $s(h,l.target,m);if(x=C.channel,S=C.root,C.root!==C.ts)E=` (${C.ts} is a reply: named its thread root)`}else x=await we(h,At(l.target).ref,m);let I;try{I=Sc(b,l.name,{channel:x,...S?{thread_ts:S}:{},...l.note?{note:l.note}:{}},l.shared)}catch(C){if(C instanceof Wn)console.error(`Error: ${C.message}`),process.exit(2);throw C}let N=I&&(I.channel!==x||I.thread_ts!==S)?` (was ${I.channel} ${I.thread_ts??"-"})`:"";console.log(`${l.name} \u2192 ${x} ${S??"-"}${E}${N} [${b.dir}]`)}).command(["unset <name>","rm <name>"],"Remove an alias (from settings.local.yml; --shared: also from settings.yml)",(l)=>l.positional("name",{type:"string",demandOption:!0}).option("shared",{type:"boolean",default:!1,describe:"Allow removing one defined in settings.yml"}).option("dir",{type:"string",describe:"Use the .slack-hub/ above this directory"}),(l)=>{let h=Ze(l.dir),m;try{m=eh(h,l.name,l.shared)}catch(b){if(b instanceof Wn)console.error(`Error: ${b.message}`),process.exit(2);throw b}if(m==="removed")console.log(`${l.name} removed [${h.dir}]`);else if(m==="absent")console.error(`no alias "${l.name}" in ${h.dir}`),process.exit(2);else console.error(`"${l.name}" is defined in ${h.dir}/settings.yml: edit that file to remove it`),process.exit(2)}).command("who <channel> <ts>","Which registered .slack-hub/ dirs subscribe this thread (or message): dir, alias",(l)=>l.positional("channel",{type:"string",demandOption:!0,describe:"Channel id"}).positional("ts",{type:"string",demandOption:!0,describe:"Thread root ts (a reply's own ts is not its thread)"}).option("json",{type:"boolean",default:!1}),(l)=>{let h=sh(l.channel,l.ts).map((m)=>({dir:Ix(m.scope.dir),scope:m.scope.dir,alias:m.name,file:m.file}));if(l.json)console.log(JSON.stringify(h));else for(let m of h)console.log(`${m.dir} ${m.alias}`);if(!h.length)process.exitCode=2}).command("import <tsv>","One-shot: import a legacy allowlist.tsv (<thread_ts> TAB <lane>) into each lane's settings.yml",(l)=>l.positional("tsv",{type:"string",demandOption:!0}).option("channel",{type:"string",demandOption:!0,describe:"The channel every thread is in (for a DM: the DM id)"}).option("lane-dir",{type:"array",string:!0,demandOption:!0,describe:"<lane>=<dir> (a directory holding .slack-hub/, made if missing); repeatable"}),(l)=>{let h=new Map;for(let _ of l["lane-dir"]??[]){let x=String(_).indexOf("=");if(x<=0)console.error(`Error: --lane-dir ${_}: want <lane>=<dir>`),process.exit(2);h.set(String(_).slice(0,x),String(_).slice(x+1))}let m=0,b=new Map;for(let _ of Ll(l.tsv,"utf8").split(`
581
+ `)){let[x,S]=_.trim().split("\t");if(!x||_.startsWith("#")||!S)continue;let E=h.get(S);if(!E||!/^\d{10}\.\d{6}$/.test(x)){b.set(S,(b.get(S)??0)+1);continue}let I={dir:wc(E).dir,global:!1};Sc(I,`t-${x}`,{channel:l.channel,thread_ts:x,note:"imported from legacy allowlist"},!0),m++}console.log(`imported ${m} subscription(s)`);for(let[_,x]of b)console.error(`skipped ${x} line(s) for lane "${_}" (no --lane-dir, or not a ts)`)}).demandCommand(1,"alias needs a subcommand: ls, set, unset, who, import")).command("reply [dest] [message]","Reply in a thread \u2014 an alias, a permalink or #chan:<ts> \u2014 with the directory's prefix (confirm-hash gate, like send)",(u)=>u.positional("dest",{type:"string",describe:"alias | permalink | #chan:<ts> | <ts> (in settings' channel). Omit with --to"}).positional("message",{type:"string",describe:"Text, or - for stdin"}).option("json",{type:"boolean",default:!1,describe:"On success print one JSON line: {ok, channel, ts, thread_ts, permalink?}"}).option("to",{type:"string",describe:"Permalink of the message you are answering: replies in ITS thread; with a dest, refuses when they differ"}).option("any-thread",{type:"boolean",default:!1,describe:"With --to and a dest: post to dest even when the message is in another thread"}).option("prefix",{type:"string",describe:`Override settings' prefix ("" for none)`}).option("code",{type:"string",describe:"Safety hash to confirm send"}).option("as-bot",{type:"boolean",describe:"Send via the bot token (default: settings' as_bot)"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing ambiguous bare URL boundaries"}).option("fix-urls",{type:"boolean",default:!1,describe:"Wrap ambiguous bare URLs as <url> (cut at the first non-ASCII character / trailing punctuation) before sending"}).option("broadcast",{type:"boolean",default:!1,describe:"Also send to channel"}).option("mentions",{type:"boolean",default:!0,describe:"Convert @handle tokens to real mentions (--no-mentions for literal text)"}),async(u)=>{let{dest:l,message:h}=u;if(u.to&&h===void 0)h=l,l=void 0;if(Tl(h))h=await Fl();if(h===void 0||!h.trim())console.error("Error: message is empty"),process.exit(1);if(!l&&!u.to)console.error("Error: reply needs a destination (alias, permalink, #chan:<ts>) or --to <permalink>"),process.exit(2);let m=n(u),b=s(u),_=Ze(),x=ps(_),S;try{let C=await Om(m,b,_,l,u.to,u["any-thread"]);if("error"in C)console.error(`Error: ${C.error}`),process.exit(2);S=C}catch(C){console.error(ge(C)),process.exit(1)}let{channel:E,threadTs:I}=S;if(Un(_)&&(u.prefix!==void 0||u["as-bot"]!==void 0&&u["as-bot"]!==(x.as_bot??!1)))console.error(`Error: ${_.dir} is restricted: who it posts as (prefix, as_bot) comes from settings.yml; --prefix / --as-bot are refused`),process.exit(2);let N=_c(h,u.prefix??x.prefix);if(!N.trim())console.error("Error: message is empty (only the prefix)"),process.exit(1);await i({workspace:u.workspace,target:`${E}:${I}`,message:N,code:u.code,"allow-url-adjacent":u["allow-url-adjacent"],"fix-urls":u["fix-urls"],"as-bot":u["as-bot"]??x.as_bot??!1,broadcast:u.broadcast,mentions:u.mentions,json:u.json})}).command("inbox","This directory's .slack-hub/inbox/: messages routed here by `slack stream --inbox`",(u)=>u.command(["ls","list"],"Pending messages: ts, from, alias, text (redacted)",(l)=>l.option("json",{type:"boolean",default:!1}),(l)=>{let h=hs(Ze());if(l.json){console.log(JSON.stringify(h.map((m)=>({file:m.file,...m.entry}))));return}for(let m of h)console.log(`${m.entry.ts} ${m.entry.user_name??m.entry.user} ${m.entry.alias} ${m.entry.text.replace(/\\/g,"\\\\").replace(/\n/g,"\\n").replace(/\t/g,"\\t")}${m.entry.files?` [files: ${m.entry.files}]`:""}`)}).command("listen","Print each message as it arrives in inbox/ (one JSON line each); pending ones first. Exits 0 at --timeout",(l)=>l.option("timeout",{type:"number",default:3600,describe:"Seconds"}).option("new-only",{type:"boolean",default:!1,describe:"Skip what is already pending"}).option("thread",{type:"string",describe:"Only messages in this thread (its root ts)"}).option("alias",{type:"string",describe:"Only messages routed by this alias"}).option("from",{type:"array",string:!0,describe:"Only messages from these user ids; repeatable"}),async(l)=>{let h=Ze(),m=l.from?.length?new Set(l.from.map(String)):void 0,b=(S)=>(!l.thread||(S.thread_ts??S.ts)===l.thread)&&(!l.alias||S.alias===l.alias)&&(!m||m.has(S.user)),_=new Set;if(l["new-only"])for(let S of hs(h))_.add(S.file);let x=Date.now()+l.timeout*1000;for(;;){for(let S of hs(h)){if(_.has(S.file))continue;if(_.add(S.file),b(S.entry))console.log(JSON.stringify({file:S.file,...S.entry}))}if(Date.now()>=x)break;await new Promise((S)=>setTimeout(S,Math.min(500,Math.max(0,x-Date.now()))))}}).command("nudge","Pending messages older than settings' nudge_after_min (default 30): exit 1 when there are any; --eyes also puts \uD83D\uDC40 on each, once",(l)=>l.option("json",{type:"boolean",default:!1}).option("eyes",{type:"boolean",default:!1,describe:"React \uD83D\uDC40 on each overdue message (once per message: recorded as nudged_at)"}).option("as-bot",{type:"boolean",describe:"React via the bot token (default: settings' as_bot)"}),async(l)=>{let h=Ze(),m=Ch(h);if(l.eyes){let b=l["as-bot"]??ps(h).as_bot??!1,_=b?Me():n(l);if(!_)console.error("Error: as_bot needs a bot token (SLACK_BOT_TOKEN)"),process.exit(1);let x=b?void 0:s(l);for(let S of m){if(S.entry.nudged_at)continue;try{await Lt(_,S.entry.channel,S.entry.ts,"eyes",x)}catch(E){if(!/already_reacted/.test(E instanceof Error?E.message:String(E))){console.error(`\u26A0 ${S.entry.channel}:${S.entry.ts}: could not add \uD83D\uDC40: ${ge(E)}`);continue}}Ah(S),S.entry.nudged_at=new Date().toISOString()}}if(l.json)console.log(JSON.stringify(m.map((b)=>({file:b.file,ts:b.entry.ts,channel:b.entry.channel,permalink:b.entry.permalink,waiting_min:Math.round((Date.now()-b.mtimeMs)/60000),...b.entry.nudged_at?{nudged_at:b.entry.nudged_at}:{}}))));else for(let b of m)console.log(`${b.entry.ts} ${Math.round((Date.now()-b.mtimeMs)/60000)} min ${b.entry.permalink}${b.entry.nudged_at?"\t\uD83D\uDC40":""}`);if(m.length)process.exitCode=1}).demandCommand(1,"inbox needs a subcommand: ls, listen, nudge")).command("done <ref..>","Mark inbox messages handled (moved to archived/) without replying: a file name, path or message ts",(u)=>u.positional("ref",{type:"string",array:!0,demandOption:!0}),(u)=>{let l=Ze(),h=0;for(let m of u.ref){let b=Tc(l,m);if(b)console.log(`archived ${b}`);else console.error(`not in ${l.dir}/inbox: ${m}`),h++}if(h)process.exit(2)}).command("outbox","This directory's .slack-hub/outbox/: replies queued as files, sent by `outbox flush`",(u)=>u.command("add <dest> <message>","Queue a reply (text redacted before it is written; - reads stdin)",(l)=>l.positional("dest",{type:"string",demandOption:!0,describe:"alias | permalink | #chan:<ts>"}).positional("message",{type:"string",demandOption:!0}).option("in-reply-to",{type:"string",describe:"ts of the inbox message this answers: archived once sent"}),async(l)=>{let h=Tl(l.message)?await Fl():l.message;if(!h.trim())console.error("Error: message is empty"),process.exit(1);let m=_h(Ze(),{to:l.dest,text:h,...l["in-reply-to"]?{in_reply_to:l["in-reply-to"]}:{}});if(m.redacted.length)console.error(`\u26A0 redacted before queueing: ${m.redacted.join(", ")}`);console.log(m.file)}).command(["ls","list"],"Queued replies: file, dest, attempts, error",(l)=>l,()=>{for(let l of Fc(Ze()))console.log(`${l.file} ${l.entry.to}${l.entry.attempts?` attempts=${l.entry.attempts} ${l.entry.error??""}`:""}`)}).command("flush","Send every queued reply (prefix, thread and restrict checks as `reply`); a --code covers the whole batch",(l)=>l.option("code",{type:"string",describe:"Safety hash to confirm the batch"}).option("as-bot",{type:"boolean",describe:"Send via the bot token (default: settings' as_bot)"}),async(l)=>{let h=Ze(),m=ps(h),b=Fc(h);if(!b.length){console.error(`nothing in ${h.dir}/outbox`);return}if(Un(h)&&l["as-bot"]!==void 0&&l["as-bot"]!==(m.as_bot??!1))console.error(`Error: ${h.dir} is restricted: as_bot comes from settings.yml; --as-bot is refused`),process.exit(2);let _=l["as-bot"]??m.as_bot??!1,x=n(l),S=s(l),E,I;if(_){let O=Me();if(!O)console.error("Error: as_bot needs a bot token (SLACK_BOT_TOKEN)"),process.exit(1);E=O}else E=x,I=S;let N=[],C=[];for(let O of b)try{let M=await Om(x,S,h,O.entry.to,void 0);if("error"in M){C.push(`${O.file}: ${M.error}`);continue}let J=_c(O.entry.text,m.prefix);if(!J.trim()){C.push(`${O.file}: empty`);continue}He(J),N.push({item:O,...M,text:J})}catch(M){C.push(`${O.file}: ${ge(M)}`)}for(let O of C)console.error(`refused (stays queued): ${O}`);if(!N.length)process.exit(2);let A=[`OUTBOX \u2014 ${N.length} repl${N.length===1?"y":"ies"}${_?" as the bot":""}:`];for(let O of N)A.push(` \u2192 ${O.channel} thread ${O.threadTs}: ${W(O.text).replace(/\n/g,"\u23CE").slice(0,120)}${O.text.includes("[redacted:")?" (secrets were masked when queued: this is what posts)":""}`);let F=De("outbox",_?"bot":"user",...N.map((O)=>`${O.channel}:${O.threadTs}:${O.text}`));if(l.code!==F)Se(l.code,F,A);let v=0;for(let O of N)try{let M=await Ht(E,O.channel,O.text,O.threadTs,!1,I),J="";try{J=await qn(E,O.channel,M,I)}catch{}let j=Eh(h,O.item,{ts:M,permalink:J,channel:O.channel,thread_ts:O.threadTs});console.log(`\u2713 ${J||M} (${j})`)}catch(M){$h(O.item,ge(M)),console.error(`\u2717 ${O.item.file}: ${ge(M)}`),v++}if(v)process.exit(1)}).demandCommand(1,"outbox needs a subcommand: add, ls, flush")).command("ask [target] [question] [choices..]","Ask a question with its choices pre-seeded as 1\uFE0F\u20E3..\uD83D\uDD1F reactions (confirm-hash safety gate). Lifecycle: --waitFor=<link> collect, --void=<link> void (verb aliases: `ask collect <link>`, `ask void <link\u2026>`)",(u)=>u.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. Also accepted as --choices "A|B|C" (split on |).'}).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("lang",{type:"string",choices:[...It],describe:"Language of the instructions in the posted body. Default: $SLACK_HUB_LANG, else the answerers' Slack locale, else the question's own language, else the system locale, else ja"}).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), 6 = the question was voided (`slack ask void`) \u2014 stop waiting. 7 = only with --explain-exit: \u2139\uFE0F pressed, explain and collect again (the question stays open)."}).option("waitFor",{type:"string",describe:"Collect the answer to a question already posted: pass its permalink. Nothing is posted (except, on an --explain question someone pressed \u2139\uFE0F on, one thread note per question). Same stdout/exit contract as --wait; --timeout 0 checks once and exits 2 if still open."}).option("after",{type:"string",describe:"With --waitFor: the cursor \u2014 everything at or before this ts was already delivered. Text replies there are neither answers nor notes again (pass the `cursor` a previous --json result gave you, or the reply ts an exit 5 printed). Reactions still count."}).option("void",{type:"string",array:!0,describe:"Void question(s) you posted that expired or stopped meaning anything \u2014 --void=<permalink>, repeatable. The text becomes \uD83D\uDEAB with --reason (body kept, options removed), our pills come off, and --wait/--waitFor on it exits 6. Same --code gate. Only your own questions (--as-bot for the bot's). Alias: `slack ask void <link\u2026>`."}).option("reask",{type:"boolean",default:!1,describe:"With ONE --void: post the question again (same channel/thread, same text and choices unless you give new ones as positionals / --body) and void the old one as replaced by it \u2014 one gate for both. The way to change the options of a question someone already answered."}).option("edit",{type:"string",describe:'Change an open question you posted: --edit=<permalink> ["new question" [choices\u2026]] [--body \u2026]. Rebuilt with the ask layout so collect still reads it. Options can change only while nobody has answered (then: --void=<link> --reask). Same --code gate.'}).option("ls",{type:"boolean",default:!1,describe:"List the questions you posted (local sent-log) with their LIVE state: --state open|answered|void|all (default open), --stale 24h, --channel, --json. With --stale it prints the --void command that would retire them."}).option("pending",{type:"boolean",default:!1,describe:"List questions THIS machine asked (local sent-log) that somebody answered but nobody collected, grouped by the asking session, with whether that agent is still alive and the --waitFor line that collects each. Read-only unless --push: --since 7d, --channel, --json. Never waits out a rate limit: a throttled pass says how many it skipped."}).option("push",{type:"boolean",default:!1,describe:"With --pending: send each answer to the agent that asked (ay send to the pid in the sent-log, or up to 3 of its parents), then collect a decision (\u2705, off this list); a free-text reply is marked delivered, the question stays open. A gone asker's answer goes to the unique live agent in the same directory (a restarted lane), else it stays listed. Each answer is pushed once."}).option("undelivered",{type:"boolean",default:!1,describe:"With --pending: the sweep \u2014 only answers that have reached nobody yet. With --push, also why (asker gone and no live agent in its directory, or ay refused)."}).option("watch",{type:"boolean",default:!1,describe:"With --pending --push: keep running \u2014 a pass every --interval, and one for a question as soon as the relay rings for it (SLACK_RELAY_URL / SLACK_RELAY_TOKEN). Prints only what it pushed."}).option("interval",{type:"number",default:10,describe:"With --watch: minutes between full passes"}).option("since",{type:"string",default:"7d",describe:"With --pending: how far back to look (30m, 2h, 7d, or an ISO date)"}).option("stale",{type:"string",describe:"With --ls: only open questions older than this (24h, 3d)"}).option("state",{type:"string",default:"open",choices:["open","answered","void","edited","gone","unknown","all"],describe:"With --ls: which state to list"}).option("channel",{type:"string",describe:"With --ls / --pending: only this channel (id, or the target as typed)"}).option("limit",{type:"number",default:50,describe:"With --ls: how many recent asks to check"}).option("reason",{type:"string",describe:"With --void: why it is void (written into the message)"}).option("superseded-by",{type:"string",describe:"With --void: permalink of the question that replaces it"}).option("explain",{type:"boolean",describe:"Also offer an \u2139\uFE0F 'explain' pill (seeded after \u2795): pressing it asks YOU to explain the question in its thread and is never an answer \u2014 the question stays open. --wait/--waitFor report it on stderr (and as `explain` in --json), and post one thread note per question. Default: $SLACK_HUB_ASK_EXPLAIN=1 turns it on; --no-explain turns it off."}).option("explain-exit",{type:"boolean",default:!1,describe:'With --wait / --waitFor: exit 7 (stdout empty; --json status "explain") when someone presses \u2139\uFE0F \u2014 once per question, on the run that posts the thread note. The question stays open: explain, then collect again.'}).option("json",{type:"boolean",default:!1,describe:"With --pending: one JSON object per answered question (sender, answer, collect command). With --wait / --waitFor: print ONE JSON object on stdout \u2014 {status, answer, how, who, notes:[{ts,user,text,permalink}], cursor, permalink} \u2014 instead of the bare answer. `notes` are the audience's replies that are not the answer (thread replies; plain replies too in a 1:1 DM). Exit codes unchanged."}).option("timeout",{type:"string",default:"3600",describe:"Overall limit for --wait / --waitFor: seconds or a duration (90s, 30m, 2h, 1d), or `forever`. 0 with --waitFor = check once. Running out exits 2 (stdout empty) \u2014 never mistaken for an answer"}).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. @tags and an @user target then resolve with the bot token too (needs users:read)."}),async(u)=>{if(g.length)u.choices=[...u.choices??[],...g];if(u.ls||u.pending){if(u.ls&&u.pending)console.error("Error: --ls and --pending are separate lists \u2014 pick one."),process.exit(ae);let C=(()=>{try{return n(u)}catch{return}})(),A={};if(C)A.user=C;let F=Me();if(F)A.bot=F;let v=s(u);if(v)A.cookie=v;if(u.pending){if(u.target||u.question||u.waitFor||u.wait||u.void||u.edit)console.error("Error: --pending reads the local log \u2014 do not also pass a target/question or another ask action."),process.exit(ae);let M=ms(String(u.since));if(M===void 0)console.error(`Error: --since needs 30m / 2h / 7d / 1w or an ISO date (got ${W(String(u.since))})`),process.exit(ae);if(u.watch&&!u.push)console.error("Error: --watch keeps pushing answers \u2014 use it with --push."),process.exit(ae);let J={sinceMs:M,json:!!u.json,push:!!u.push,undelivered:!!u.undelivered};if(u.channel)J.channel=String(u.channel);if(u.workspace)J.selfArgs=["-w",String(u.workspace)];if(u.watch){let j=Number(u.interval);if(!(j>0))console.error("Error: --interval needs a number of minutes above 0."),process.exit(ae);let ee=String(u.since),X=new Set;await vS(async(U)=>{let ie=await Bm(A,{...J,sinceMs:ms(ee)??M,watch:!0,...U?{only:U}:{skip:X}});if(U)return;if(ie.throttled)for(let q of ie.checked)X.add(q);else X.clear()},()=>ms(ee)??M,()=>(X.size?Math.min(2,j):j)*60000)}try{await Bm(A,J)}catch(j){console.error(ge(j)),process.exit(ae)}return}let O={state:String(u.state??"open"),json:!!u.json,limit:Number(u.limit)||50};if(u.stale)O.stale=String(u.stale);if(u.channel)O.channel=String(u.channel);await OS(A,O);return}let l=(C)=>{if(!C){let F=s(u);return F?{token:n(u),cookie:F}:{token:n(u)}}let A=Me();if(!A)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
582
+ Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(ae);return{token:A}},h=u.target!==void 0&&u.target!=="void"&&u.target!=="collect"?String(u.target):void 0,m=[u.question,...u.choices??[]].filter((C)=>C!==void 0).map(String);if(u.edit){if(u.void||u.wait||u.waitFor)console.error("Error: --edit changes one open question \u2014 do not combine it with --void/--wait/--waitFor."),process.exit(ae);let{token:C,cookie:A}=l(!!u["as-bot"]),F={link:String(u.edit),asBot:!!u["as-bot"],mentionToken:C,allowUrlAdjacent:!!u["allow-url-adjacent"]};if(h!==void 0)F.question=h;if(m.length)F.choices=m.map((v)=>v.trim()).filter(Boolean);if(u.body!==void 0)F.body=String(u.body);if(u.lang)F.lang=String(u.lang);if(u.code)F.code=String(u.code);if(A)F.cookie=A,F.mentionCookie=A;try{await FS(C,F)}catch(v){console.error(ge(v)),process.exit(ae)}return}let b,_=(u.void??[]).map(String).filter(Boolean);if(u.reask){if(_.length!==1||u.target==="void")console.error("Error: --reask goes with exactly one --void=<permalink> (the question to replace)."),process.exit(ae);if(u.waitFor)console.error("Error: --reask posts a new question \u2014 --wait works, --waitFor does not."),process.exit(ae);let{token:C,cookie:A}=l(!!u["as-bot"]),F=await je(C,A),v=await cy(C,_[0],F,!!u["as-bot"],A);if(v==="void")console.error(`\u2717 ${W(_[0])}: already voided \u2014 to ask again, just use slack ask`),process.exit(ae);if(!v)process.exit(ae);if(b={...v,reason:Ue(String(u.reason??"")).trim()},u.target=v.threadTs?`${v.channelId}:${v.threadTs}`:v.channelId,u["channel-id"]=v.channelId,u.question=h??ks(v.parsed.question),u.choices=m.length?m:[...v.parsed.reactable,...v.parsed.overflow].map(ks),u.body===void 0&&v.parsed.body)u.body=ks(v.parsed.body);if(!u.lang)u.lang=v.parsed.lang;if(u.explain===void 0&&v.parsed.explain)u.explain=!0;u.void=void 0}if(!b&&(u.target==="void"||_.length)){let C=u.target==="void"?[u.question,...u.choices??[]]:[];if(u.target!=="void"&&(u.target||u.question||u.choices?.length))console.error("Error: --void voids existing questions \u2014 do not also pass a target/question/choices."),process.exit(ae);let A=[..._,...C.map((M)=>String(M??""))].filter(Boolean);if(!A.length)console.error("Error: --void=<permalink> \u2014 which question(s)?"),process.exit(ae);if(u.wait||u.waitFor)console.error("Error: --void voids existing questions \u2014 do not also pass --wait/--waitFor."),process.exit(ae);let F,v;if(u["as-bot"]){let M=Me();if(!M)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
583
+ Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(ae);F=M}else F=n(u),v=s(u);let O={links:A,reason:Ue(String(u.reason??"")).trim(),asBot:!!u["as-bot"]};if(u["superseded-by"])O.supersededBy=String(u["superseded-by"]);if(u.code)O.code=String(u.code);if(v)O.cookie=v;try{await LS(F,O)}catch(M){console.error(ge(M)),process.exit(ae)}return}if(u.target==="collect"){if(!u.question||u.choices?.length)console.error("Error: slack ask collect <permalink> \u2014 exactly one question."),process.exit(ae);u.waitFor=String(u.question),u.target=void 0,u.question=void 0}let x=u.waitFor?String(u.waitFor):"",S=zp(u.timeout);if(S===void 0||S===0&&!x)console.error(`Error: --timeout must be a positive number of seconds, a duration (90s, 30m, 2h, 1d) or \`forever\` (got ${W(String(u.timeout))})`),process.exit(ae);if(x){if(u.target||u.question||u.choices?.length)console.error("Error: --waitFor collects an existing question \u2014 do not also pass a target/question/choices."),process.exit(ae);let C,A;if(u["as-bot"]){let F=Me();if(!F)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
584
+ Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(ae);C=F}else C=n(u),A=s(u);try{let F={link:x,timeout:S,asBot:!!u["as-bot"],json:!!u.json};if(u["explain-exit"])F.explainExit=!0;if(A)F.cookie=A;if(u.after){let v=String(u.after);if(!/^\d{10}\.\d{6}$/.test(v))console.error(`Error: --after needs a message ts like 1700000000.000100 (got ${W(v)})`),process.exit(ae);F.after=v}await NS(C,F)}catch(F){console.error(ge(F)),process.exit(ae)}return}if(!u.target)console.error("Error: target is required (or use --waitFor <permalink> to collect an answer)"),process.exit(ae);let E=String(u.question??"").trim();if(!E)console.error("Error: question is empty"),process.exit(ae);let I={allowUrlAdjacent:u["allow-url-adjacent"],target:u.target,question:E,choices:(u.choices??[]).map((C)=>String(C).trim()).filter(Boolean),timeout:S};if(u.code)I.code=u.code;if(u.body)I.body=u.body;if(u.lang)I.lang=String(u.lang);if(u.wait)I.wait=!0;if(u.json)I.json=!0;if(typeof u.explain==="boolean")I.explain=u.explain;if(u["explain-exit"])I.explainExit=!0;if(b)I.voidAfter=b;if(u["channel-id"])I.channelId=u["channel-id"];if(u["user-id"])I.userId=u["user-id"];let N;if(u["as-bot"]){let C=Me();if(!C)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
585
+ Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(ae);if(!I.channelId&&!I.userId&&I.target.startsWith("@"))try{I.userId=await Nt(C,I.target)}catch(A){console.error(`Error: could not resolve ${I.target} to a user for the bot DM.
586
+ ${A instanceof Error?A.message:String(A)}
587
+ Tip: pass --user-id <Uxxxx> to skip the lookup.`),process.exit(ae)}N=C,I.mentionToken=C,I.asBot=!0}else{N=n(u),I.mentionToken=N;let C=s(u);if(C)I.cookie=C,I.mentionCookie=C}try{await AS(N,I)}catch(C){console.error(ge(C)),process.exit(ae)}}).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)",(u)=>u.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: one vote per person)"}).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. @tags and an @user target then resolve with the bot token too (needs users:read)."}),async(u)=>{let l=u.close?String(u.close):u.results?String(u.results):"";if(u.results&&u.close)console.error("Error: pass --results or --close, not both (--close counts as well)."),process.exit(mt);let h=()=>{let S=Me();if(!S)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
588
+ Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(mt);return S};if(l){if(u.target||u.question||u.choices?.length)console.error("Error: --results/--close reads an existing poll \u2014 do not also pass a target/question/choices."),process.exit(mt);let S=n(u),E=s(u);try{let I={link:l};if(u.close)I.close=!0;if(u.names)I.names=!0;if(u["no-notify"])I.noNotify=!0;if(E)I.cookie=E;if(u["as-bot"])I.writeToken=h();await WS(S,I)}catch(I){console.error(ge(I)),process.exit(mt)}return}if(!u.target)console.error("Error: target is required (or use --results <permalink> to count a poll)"),process.exit(mt);let m=String(u.question??"").trim();if(!m)console.error("Error: question is empty"),process.exit(mt);let b=(u.choices??[]).map((S)=>String(S).trim()).filter(Boolean);if(b.length<2||b.length>gs)console.error(`Error: poll needs 2..${gs} choices (got ${b.length}). For a free-text question use \`slack ask\`.`),process.exit(mt);let _={target:u.target,question:m,choices:b};if(u.multi)_.multi=!0;if(u.until)_.until=String(u.until);if(u.code)_.code=u.code;if(u.body)_.body=u.body;if(u["allow-url-adjacent"])_.allowUrlAdjacent=!0;if(u["channel-id"])_.channelId=u["channel-id"];if(u["user-id"])_.userId=u["user-id"];let x;if(u["as-bot"]){let S=h();if(!_.channelId&&!_.userId&&_.target.startsWith("@"))try{_.userId=await Nt(S,_.target)}catch(E){console.error(`Error: could not resolve ${_.target} to a user for the bot DM.
579
589
  ${E instanceof Error?E.message:String(E)}
580
- Tip: pass --user-id <Uxxxx> to skip the lookup.`),process.exit(oe)}_=D,k.mentionToken=D,k.asBot=!0}else{_=t(a),k.mentionToken=_;let D=n(a);if(D)k.cookie=D,k.mentionCookie=D}try{await Jx(_,k)}catch(D){console.error(ge(D)),process.exit(oe)}}).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)",(a)=>a.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: one vote per person)"}).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. @tags and an @user target then resolve with the bot token too (needs users:read)."}),async(a)=>{let c=a.close?String(a.close):a.results?String(a.results):"";if(a.results&&a.close)console.error("Error: pass --results or --close, not both (--close counts as well)."),process.exit(gt);let d=()=>{let m=Ne();if(!m)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
581
- Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(gt);return m};if(c){if(a.target||a.question||a.choices?.length)console.error("Error: --results/--close reads an existing poll \u2014 do not also pass a target/question/choices."),process.exit(gt);let m=t(a),w=n(a);try{let k={link:c};if(a.close)k.close=!0;if(a.names)k.names=!0;if(a["no-notify"])k.noNotify=!0;if(w)k.cookie=w;if(a["as-bot"])k.writeToken=d();await nS(m,k)}catch(k){console.error(ge(k)),process.exit(gt)}return}if(!a.target)console.error("Error: target is required (or use --results <permalink> to count a poll)"),process.exit(gt);let p=String(a.question??"").trim();if(!p)console.error("Error: question is empty"),process.exit(gt);let h=(a.choices??[]).map((m)=>String(m).trim()).filter(Boolean);if(h.length<2||h.length>us)console.error(`Error: poll needs 2..${us} choices (got ${h.length}). For a free-text question use \`slack ask\`.`),process.exit(gt);let g={target:a.target,question:p,choices:h};if(a.multi)g.multi=!0;if(a.until)g.until=String(a.until);if(a.code)g.code=a.code;if(a.body)g.body=a.body;if(a["allow-url-adjacent"])g.allowUrlAdjacent=!0;if(a["channel-id"])g.channelId=a["channel-id"];if(a["user-id"])g.userId=a["user-id"];let y;if(a["as-bot"]){let m=d();if(!g.channelId&&!g.userId&&g.target.startsWith("@"))try{g.userId=await vt(m,g.target)}catch(w){console.error(`Error: could not resolve ${g.target} to a user for the bot DM.
582
- ${w instanceof Error?w.message:String(w)}
583
- Tip: pass --user-id <Uxxxx> to skip the lookup.`),process.exit(gt)}y=m,g.mentionToken=m,g.asBot=!0}else{y=t(a),g.mentionToken=y;let m=n(a);if(m)g.cookie=m,g.mentionCookie=m}try{await eS(y,g)}catch(m){console.error(ge(m)),process.exit(gt)}}).command("sent [query]","Search what THIS machine posted/edited (send, ask, poll, edit) and who sent it \u2014 read-only, local log",(a)=>a.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)"}),(a)=>{let c;if(a.since!==void 0){if(c=ds(String(a.since)),c===void 0)console.error(`Error: --since needs 30m / 2h / 7d / 1w or an ISO date (got ${M(String(a.since))})`),process.exit(1)}let d={limit:Number(a.count)||50};if(a.query)d.text=String(a.query);if(a.channel)d.channel=String(a.channel);if(c!==void 0)d.sinceMs=c;if(a.session)d.session=String(a.session);if(a.cwd){let h=YD(String(a.cwd));try{d.cwd=qD(h)}catch{d.cwd=h}}if(a.kind)d.kind=a.kind;let p=Ac(d);if(!p)console.error(`Error: ${er}
584
- (${Rt()})`),process.exit(1);if(a.json){for(let h of p)console.log(JSON.stringify(h));return}if(!p.length){console.error(`No sent messages match (log: ${Rt()}).`);return}for(let h of p)console.log(wx(h))}).command("doctor","Check the bot token (xoxb) can carry a two-way DM (scopes + Messages Tab)",(a)=>a,async()=>{let a=Ne();if(!a)console.error(`Error: slack doctor checks the bot token, but no xoxb- token was found.
585
- Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(1);await sS(a)}).command("schedule","Manage scheduled messages",(a)=>a.command("send <target> <message>","Schedule a message for later delivery",(c)=>c.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(c)=>{if(!String(c.message??"").trim())console.error("Error: message is empty"),process.exit(1);let d={target:c.target,message:c.message,at:c.at};if(c.code)d.code=c.code;if(c["allow-url-adjacent"])d.allowUrlAdjacent=!0;if(c["channel-id"])d.channelId=c["channel-id"],d.targetOverride=`--channel-id ${c["channel-id"]}`;if(c["user-id"])d.userId=c["user-id"],d.targetOverride=`--user-id ${c["user-id"]}`;let p;if(c["as-bot"]){let h=Ho();if(!d.channelId&&!d.userId&&d.target.startsWith("@"))try{d.userId=await vt(t(c),d.target,n(c))}catch(g){console.error(`Error: could not resolve ${d.target} to a user for the bot DM.
586
- ${g instanceof Error?g.message:String(g)}
587
- Tip: pass --user-id <Uxxxx> to skip the lookup.`),process.exit(1)}p=h,d.asBot=!0}else{p=t(c);let h=n(c);if(h)d.cookie=h}await rS(p,d)}).command(["ls","list"],"List pending scheduled messages",(c)=>c.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(c)=>{let d=c.target;if(c["as-bot"]){let p=Ho(),h=c["channel-id"];if(!h&&d?.startsWith("@"))h=await pm(d,p,t(c),n(c));await gm(p,d,h);return}await gm(t(c),d,c["channel-id"],n(c))}).command("rm <target> <id>","Delete a scheduled message",(c)=>c.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(c)=>{let d={target:c.target,id:c.id};if(c.code)d.code=c.code;if(c["channel-id"])d.channelId=c["channel-id"],d.targetOverride=`--channel-id ${c["channel-id"]}`;if(c["as-bot"]){let h=Ho();if(!d.channelId&&d.target.startsWith("@"))d.channelId=await pm(d.target,h,t(c),n(c));d.asBot=!0,await mm(h,d);return}let p=n(c);if(p)d.cookie=p;await mm(t(c),d)}).demandCommand(1,"").showHelpOnFail(!0),()=>{}).command("edit <target> <newText>","Edit a sent message",(a)=>a.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("force",{type:"boolean",default:!1,describe:"Apply an edit that BREAKS a `slack ask` / `slack poll` message (new text no longer reads as one, or an answered/void question made open again). Refused by default because collect reads that body back; edits that keep it readable (e.g. writing the \u2705 form) need no flag. Prefer `slack ask --edit=` / `--void=`."}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing ambiguous bare URL boundaries"}).option("fix-urls",{type:"boolean",default:!1,describe:"Wrap ambiguous bare URLs as <url> (cut at the first non-ASCII character / trailing punctuation) before sending"}).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(a)=>s(a)).command("tick <target> [n]","Tick item n of a posted checklist (\u2B1C n. \u2192 \u2705 n.), nothing else changed; without n, the one open item (confirm-hash gate, like edit)",(a)=>a.positional("target",{type:"string",demandOption:!0,describe:"#chan:ts, @user:ts, or permalink"}).positional("n",{type:"number",describe:"Item number"}).option("code",{type:"string",describe:"Safety hash to confirm the edit"}).option("channel-id",{type:"string",describe:"Raw channel ID"}).option("as-bot",{type:"boolean",default:!1,describe:"Edit as the bot (needed for a message the bot posted)"}),async(a)=>s({...a,tick:a.n!==void 0?{n:a.n}:{},mentions:!1})).command("delete <target>","Delete a sent message (confirm-hash safety gate)",(a)=>a.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(a)=>{let c={target:a.target};if(a.code)c.code=a.code;if(a["channel-id"])c.channelId=a["channel-id"];let d;if(a["as-bot"]){let p=await im(c.target,t(a),n(a),c.channelId);if(d=p.botToken,p.channelId&&!c.channelId)c.channelId=p.channelId;c.asBot=!0}else{d=t(a);let p=n(a);if(p)c.cookie=p}await Sx(d,c)}).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)",(a)=>{let c={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."},d=async(h)=>{if(h["as-bot"]){let y=Ho();if(typeof h.workspace==="string"){let m=n(h),[w,k]=await Promise.all([Ut(t(h),m),Ut(y)]);if(w.url!==k.url)console.error(`Error: --as-bot acts with SLACK_BOT_TOKEN, which belongs to ${k.url}, but -w ${h.workspace} is ${w.url}.
588
- Drop -w, or set SLACK_BOT_TOKEN to that workspace's bot token.`),process.exit(2)}return{token:y,asBot:!0}}let g=n(h);return{token:t(h),...g?{cookie:g}:{},asBot:!1}},p=(h)=>{console.error(ge(h)),process.exit(1)};return a.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)",(h)=>h.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",c).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(h)=>{let g=h.file!==void 0;if(g&&h.state!==void 0&&h.reason!==void 0)console.error("Error: with --file, pass only the reason after <channel> (the state comes from the file)."),process.exit(2);let y=g?qo(void 0,h.file):qo(h.state,void 0),m=g?h.state:h.reason;if(y===void 0)console.error("Error: the state is required (positional or --file)."),process.exit(2);let w=await d(h),k={target:h.channel,state:y,asBot:w.asBot,allowUrlAdjacent:h["allow-url-adjacent"]};if(m!==void 0)k.log=We(m);if(w.cookie)k.cookie=w.cookie;if(typeof h.workspace==="string")k.workspace=h.workspace;if(h.code)k.code=h.code;await Ex(w.token,k).catch(p)}).command("set <board> [state] [reason]","Change a board: replace its state (silent edit) AND post the reason in its thread (notifies)",(h)=>h.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",c).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(h)=>{let g=h.file!==void 0;if(g&&h.state!==void 0&&h.reason!==void 0)console.error("Error: with --file, pass only the reason after <board> (the state comes from the file)."),process.exit(2);let y=g?qo(void 0,h.file):qo(h.state,void 0),m=g?h.state:h.reason;if(y===void 0||m===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 w=await d(h),k={target:h.board,state:y,log:We(m),adopt:h.adopt,asBot:w.asBot,allowUrlAdjacent:h["allow-url-adjacent"]};if(typeof h.workspace==="string")k.workspace=h.workspace;if(w.cookie)k.cookie=w.cookie;if(h.code)k.code=h.code;await cm(w.token,k).catch(p)}).command("note <board> <reason>","Post only a reason in a board's thread (notifies); the state stays as is",(h)=>h.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",c),async(h)=>{let g=await d(h),y={target:h.board,log:We(h.reason),logOnly:!0,asBot:g.asBot,allowUrlAdjacent:h["allow-url-adjacent"]};if(typeof h.workspace==="string")y.workspace=h.workspace;if(g.cookie)y.cookie=g.cookie;if(h.code)y.code=h.code;await cm(g.token,y).catch(p)}).command(["get <board>","show <board>"],"Show a board's state and its log (read-only)",(h)=>h.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",c),async(h)=>{let g=await d(h);await Ax(g.token,h.board,g.cookie,h.json).catch(p)}).command(["ls <channel>","list <channel>"],"List the boards in a channel, found by their footer (read-only)",(h)=>h.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",c),async(h)=>{let g=await d(h);await Tx(g.token,h.channel,h.limit,g.cookie).catch(p)}).command("pin <board>",!1,(h)=>h.positional("board",{type:"string",demandOption:!0}).option("as-bot",c),async(h)=>{let g=await d(h);await Fx(g.token,h.board,g.cookie).catch(p)}).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",(a)=>a.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(a)=>{let c={target:a.target,emoji:a.emoji};if(a.remove)c.remove=!0;if(a["channel-id"])c.channelId=a["channel-id"];let d=n(a);if(d)c.cookie=d;try{await Ox(t(a),c)}catch(p){console.error(ge(p)),process.exit(1)}}).command("todo","Reaction-backed task tracking (:pushpin: marks a task, progress lives in a second reaction)",(a)=>a.option("cache",{type:"boolean",default:!0,describe:"Use ~/.config/slack-cli/cache.json for channel/user lookups (--no-cache to bypass)"}).middleware((c)=>{if(c.cache===!1)el(!1)}).command(["ls","list"],"List everyone's tasks (has: \u2014 read-only, one search per run)",(c)=>c.options(o).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(c)=>{await i(c,!1)}).command("set <target> <state>","Move a task to a progress state (adds the new reaction before removing the old one)",(c)=>c.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(c)=>{let d={target:c.target,state:c.state};if(c["channel-id"])d.channelId=c["channel-id"];let p=n(c);if(p)d.cookie=p;try{await ax(t(c),d)}catch(h){console.error(ge(h)),process.exit(1)}}).command("flag <target> <flag>","Add (or --remove) a reason flag (alert | needs-discussion | waiting | blocked) \u2014 flags stack, independent of progress",(c)=>c.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(c)=>{let d={target:c.target,flag:c.flag};if(c.remove)d.remove=!0;if(c["channel-id"])d.channelId=c["channel-id"];let p=n(c);if(p)d.cookie=p;try{await cx(t(c),d)}catch(h){console.error(ge(h)),process.exit(1)}}).command("doctor","Find messages carrying two or more progress reactions (--fix repairs them)",(c)=>c.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:Qc,describe:"Max messages to scan"}).option("channel-id",{type:"string",describe:"Raw channel ID"}),async(c)=>{let d={channel:c.in,limit:c.limit};if(c.fix)d.fix=!0;if(c["channel-id"])d.channelId=c["channel-id"];let p=n(c);if(p)d.cookie=p;await lx(t(c),d)}).demandCommand(1,"Specify a todo subcommand (ls, set, flag, doctor)"),()=>{}).command("mytodo","Tasks carrying YOUR reactions (hasmy:) \u2014 the my-only half of `todo`",(a)=>a.option("cache",{type:"boolean",default:!0,describe:"Use ~/.config/slack-cli/cache.json for channel/user lookups (--no-cache to bypass)"}).middleware((c)=>{if(c.cache===!1)el(!1)}).command(["ls","list"],"List tasks you have reacted to (hasmy: \u2014 read-only, one search per run)",(c)=>c.options(o),async(c)=>{await i(c,!0)}).demandCommand(1,"Specify a mytodo subcommand (ls)"),()=>{}).command("upload <target> <file..>","Upload one or more files to a channel or DM",(a)=>a.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"}).option("as-bot",{type:"boolean",default:!1,describe:"Upload via the bot token (xoxb / SLACK_BOT_TOKEN); `slack @bot upload \u2026` does this too"}),async(a)=>{let c={target:a.target,filePaths:a.file};if(a.title)c.title=a.title;if(a.comment)c.comment=a.comment;if(a["allow-url-adjacent"])c.allowUrlAdjacent=!0;if(a.code)c.code=a.code;if(a["channel-id"])c.channelId=a["channel-id"];if(a["user-id"])c.userId=a["user-id"];if(a["as-bot"]){let p=Ne();if(!p)console.error("Error: --as-bot needs a bot token (SLACK_BOT_TOKEN)"),process.exit(1);await ym(p,c);return}let d=n(a);if(d)c.cookie=d;await ym(t(a),c)}).command("files","File commands",(a)=>a.command(["ls","list"],"List files visible to you (files.list)",(c)=>c.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(c)=>{let d={limit:c.limit,format:c.json?"jsonl":c.format};if(c.type)d.types=c.type;if(c.channel)d.channel=c.channel;if(c.user)d.user=c.user;await oS(t(c),n(c),d)}).demandCommand(1,"").showHelpOnFail(!0),()=>{}).command("lists","Slack Lists \u2014 read rows (lists <ref>), or create / add / set (gated, as the bot)",(a)=>a.command("create <name>","Create a Slack List (confirm-hash safety gate; bot token, lists:write)",(c)=>c.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(c)=>{try{let d={name:c.name,cols:c.col,todo:c.todo===!0};if(c.code!==void 0)d.code=c.code;await lS(d)}catch(d){console.error(ge(d)),process.exit(1)}}).command("add <list> <text>","Add a row to a Slack List (confirm-hash safety gate; bot token)",(c)=>c.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(c)=>{try{let d={list:c.list,text:c.text,sets:c.set};if(c.code!==void 0)d.code=c.code;await uS(d)}catch(d){console.error(ge(d)),process.exit(1)}}).command("set <list> <row>","Update cells of a Slack List row; --done checks it off (confirm-hash safety gate; bot token)",(c)=>c.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(c)=>{try{let d={list:c.list,row:c.row,sets:c.set};if(c.done!==void 0)d.done=c.done;if(c.code!==void 0)d.code=c.code;await dS(d)}catch(d){console.error(ge(d)),process.exit(1)}}).command("share <list>","Grant users or channels access to a Slack List (confirm-hash safety gate; bot token)",(c)=>c.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(c)=>{try{let d={list:c.list,users:c.user,channels:c.channel,level:c.level};if(c.code!==void 0)d.code=c.code;await fS(d)}catch(d){console.error(ge(d)),process.exit(1)}}).command("$0 <ref>","Read a Slack List's rows (by list URL or F-id) \u2014 read-only",(c)=>c.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(c)=>{let d=c.json?"jsonl":c.format;try{let p=c.asBot===!0;await aS(p?"":t(c),p?void 0:n(c),c.ref,{limit:c.limit,format:d,asBot:p})}catch(p){console.error(ge(p)),process.exit(1)}})).command("download <ref> [dest]","Download a file attachment (by file ID or file permalink) to disk",(a)=>a.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(a)=>{await hS(t(a),n(a),a.ref,a.dest)}).command("dump","Bulk export channel history as markdown",(a)=>a.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(a)=>{await ux(t(a),a.days,a.limit,a.filter)}).command("todos","Slack's To-dos tab \u2014 your personal to-dos (requires xoxc desktop token). Not `slack todo` (reaction tasks)",(a)=>a.command(["$0","ls","list"],"List your To-dos, soonest due first",(c)=>c.option("filter",{type:"string",choices:[...wg],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(c)=>{if(!Number.isInteger(c.limit)||c.limit<1)console.error(`Error: --limit must be a whole number of at least 1 (got ${c.limit}).`),process.exit(2);await px(t(c),n(c),{filter:c.filter,limit:c.limit,json:c.json})}).command("add <target>","Add a message to your To-dos (two-step: preview, then --code)",(c)=>c.positional("target",{type:"string",demandOption:!0,describe:"Message permalink or #chan:<ts>"}).option("due",{type:"string",describe:"Due time (ISO datetime or Unix ts)"}).option("saved",{type:"boolean",default:!1,describe:"Save it without a checkbox instead of as a to-do"}).option("code",{type:"string",describe:"Confirmation code from the preview"}),async(c)=>{let d=c.due===void 0?void 0:hm(c.due);await Ko(t(c),n(c),c.target,{kind:"add",...d?{due:d}:{},saved:c.saved},c.code)}).command(["done <target>","complete <target>"],"Check a to-do off (--undo reopens it)",(c)=>c.positional("target",{type:"string",demandOption:!0,describe:"Message permalink or #chan:<ts>"}).option("undo",{type:"boolean",default:!1,describe:"Mark it not done again"}).option("code",{type:"string",describe:"Confirmation code from the preview"}),async(c)=>{await Ko(t(c),n(c),c.target,{kind:"done",undo:c.undo},c.code)}).command("edit <target>","Change a to-do's due date, or switch it between to-do and saved item",(c)=>c.positional("target",{type:"string",demandOption:!0,describe:"Message permalink or #chan:<ts>"}).option("due",{type:"string",describe:"New due time (ISO datetime or Unix ts), or `none` to clear it"}).option("todo",{type:"boolean",describe:"Make it a to-do (with a checkbox)"}).option("saved",{type:"boolean",describe:"Make it a plain saved item (no checkbox)"}).conflicts("todo","saved").option("code",{type:"string",describe:"Confirmation code from the preview"}),async(c)=>{let d=c.due===void 0?void 0:c.due==="none"?0:hm(c.due),p=c.todo?!0:c.saved?!1:void 0;await Ko(t(c),n(c),c.target,{kind:"edit",...d===void 0?{}:{due:d},...p===void 0?{}:{todo:p}},c.code)}).command(["rm <target>","remove <target>","delete <target>"],"Remove a message from your To-dos (the message stays)",(c)=>c.positional("target",{type:"string",demandOption:!0,describe:"Message permalink or #chan:<ts>"}).option("code",{type:"string",describe:"Confirmation code from the preview"}),async(c)=>{await Ko(t(c),n(c),c.target,{kind:"rm"},c.code)})).command("drafts","Manage message drafts (requires xoxc desktop token)",(a)=>a.command(["$0","ls","list"],"List pending drafts",(c)=>c.option("all",{alias:"a",type:"boolean",default:!1,describe:"Include sent drafts"}),async(c)=>{await fx(t(c),n(c),c.all)}).command(["new <channel> [text..]","save <channel> [text..]"],"Create a draft",(c)=>c.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(c)=>{let d=t(c),p=n(c),h=c.text.join(" ");if(!h)console.error("Usage: slack drafts new <#channel|@user> <text>"),process.exit(2);qe(h,c["allow-url-adjacent"],void 0,{sides:["after"],markdown:!1});let g=await we(d,c.channel,p),y=await fg(d,g,h,p);console.log(`\u2713 Draft created (id: ${O(y.draft).id??"?"})`)}).command("get <id>","Show a draft",(c)=>c.positional("id",{type:"string",demandOption:!0}),async(c)=>{await yx(t(c),n(c),c.id)}).command(["edit <id> [text..]","update <id> [text..]"],"Edit a draft",(c)=>c.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(c)=>{let d=t(c),p=n(c),h=c.text.join(" ");if(!h)console.error("Usage: slack drafts edit <id> <new-text>"),process.exit(2);qe(h,c["allow-url-adjacent"],void 0,{sides:["after"],markdown:!1});let g=await or(d,p),y=G(g.drafts).map(O).find((D)=>String(D.id)===c.id);if(!y)console.error(`Draft not found: ${c.id}`),process.exit(1);let m=Xo(y),w=await Be(d,p),k=De(m,h,w?.userId??"");if(c.code!==k)Se(c.code,k,["--- Editing draft as -------------------------",Ee(w),"--- Current draft ----------------------------",...m.split(`
589
- `).map((D)=>` ${D}`),"--- Replacing with ---------------------------",...h.split(`
590
- `).map((D)=>` ${D}`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);let _=await pg(d,c.id,xl(y),h,p);console.log(`\u2713 Draft updated (id: ${O(_.draft).id??"?"})`)}).command(["delete <id>","rm <id>"],"Delete a draft",(c)=>c.positional("id",{type:"string",demandOption:!0}).option("code",{type:"string"}),async(c)=>{let d=t(c),p=n(c),h=await or(d,p),g=G(h.drafts).map(O).find((k)=>String(k.id)===c.id);if(!g)console.error(`Draft not found: ${c.id}`),process.exit(1);let y=Xo(g),m=await Be(d,p),w=De(c.id,y,m?.userId??"");if(c.code!==w)Se(c.code,w,["\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",Ee(m),` id: ${c.id}`,...y.split(`
591
- `).map((k)=>` ${k}`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);await mg(d,c.id,p),console.log(`\u2713 Draft deleted (id: ${c.id})`)})).command("auth","Authentication and workspace management",(a)=>a.command("token","Print the active token (or save one with --token)",(c)=>c.option("token",{type:"string",describe:"Token to save directly (non-interactive)"}).option("name",{type:"string",describe:"Workspace name (used with --token)"}),async(c)=>{if(c.token===void 0){console.log(Os(c.workspace));return}await ef({...c.token!==void 0?{token:c.token}:{},...c.name!==void 0?{name:c.name}:{}})}).command("env","Print active workspace credentials in dotenv format",()=>{},(c)=>{let d=Os(c.workspace),p=d.startsWith("xoxc-")?zi(c.workspace):void 0,h=[["SLACK_TOKEN",d]];if(p)h.push(["SLACK_COOKIE",p]);let g=h.map(([y,m])=>{if(/[\r\n\0']/.test(m))throw Error(`Cannot export ${y}: unsupported characters in credential`);return`${y}='${m}'`});console.log(g.join(`
592
- `))}).command("app","Create a new Slack app and obtain a token (guided wizard)",(c)=>c.option("bot",{type:"boolean",describe:"Create a bot token (xoxb-) instead of user (xoxp-)"}),async(c)=>{await tf({...c.bot!==void 0?{bot:c.bot}:{}})}).command("login","Log in: interactive wizard, or a source (chrome, firefox)",(c)=>c.command("chrome","Import workspaces from Chrome, grouped by account (all platforms)",(d)=>d.option("profile",{type:"string",alias:"p",describe:'Chrome profile email or dir (e.g. "you@example.com" or "Profile 3")'}),async(d)=>{await _a({...d.profile!==void 0?{profile:d.profile}:{}})}).command("firefox","Import the xoxd cookie from Firefox into a workspace",(d)=>d.option("workspace",{type:"string",alias:"w",describe:"Workspace name to update (default: active)"}),async(d)=>{await Ea({...d.workspace!==void 0?{workspace:d.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(d)=>{await Us({...d.token!==void 0?{token:d.token}:{},...d.name!==void 0?{name:d.name}:{},yes:d.yes,fromDesktop:d.fromDesktop,fromChrome:d.fromChrome,fromFirefox:d.fromFirefox,fromAll:d.fromAll})}),async(c)=>{await Us({...c.token!==void 0?{token:c.token}:{},...c.name!==void 0?{name:c.name}:{},yes:c.yes,fromDesktop:c.fromDesktop,fromChrome:c.fromChrome,fromFirefox:c.fromFirefox,fromAll:c.fromAll})}).command("tokens","Print the selected credentials as dotenv assignments",(c)=>c.option("workspace",{type:"string",alias:"w",describe:"Workspace name (default: active)"}),(c)=>nf({...c.workspace!==void 0?{workspace:c.workspace}:{}})).command("save","Save the active profile token and cookie to an env file",(c)=>c.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)"}),(c)=>sf({envfile:c.envfile,...c.workspace!==void 0?{workspace:c.workspace}:{}})).command(["ls","status"],"Show auth status",()=>{},()=>{let c=Hi();if(c.length===0){console.log("No workspaces configured. Run: slack auth login");return}for(let{name:d,profile:p,current:h}of c)console.log(`${h?"* ":" "}${d} ${p.team} (${p.user}) ${p.url??""}`)}).command("use <name>","Switch active workspace",(c)=>c.positional("name",{type:"string",demandOption:!0}).option("g",{type:"boolean",default:!1,describe:"Write global lockfile (~/.slack-cli/workspace)"}),(c)=>{if(!c.g)GD(mt(process.cwd(),".slack-cli"));wd(c.name,c.g),console.log(`Switched to workspace "${c.name}" ${c.g?"globally":"locally"}`)}).command(["logout <name>","rm <name>","remove <name>"],"Remove a workspace",(c)=>c.positional("name",{type:"string",demandOption:!0}),(c)=>{bd(c.name),console.log(`Removed workspace "${c.name}"`)}).command(["cookie","chrome"],"Attach a Chrome xoxd cookie to a workspace (macOS/Linux/Windows). To import workspaces, use: slack auth login chrome",(c)=>c.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(c)=>{await Qd({...c.workspace!==void 0?{workspace:c.workspace}:{},...c.profile!==void 0?{profile:c.profile}:{},yes:c.yes})}).command("firefox","Attach Firefox browser xoxd cookie to a workspace (all platforms)",(c)=>c.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(c)=>{await Ea({...c.workspace!==void 0?{workspace:c.workspace}:{},yes:c.yes})}).command("$0",!1,()=>{},()=>{a.showHelp(),process.exit(0)})).command("relay","Set up / check the real-time relay for `slack stream` (a Cloudflare Worker)",(a)=>a.command("init [dir]","Scaffold a deployable relay Worker folder (local files only; prints a fresh RELAY_TOKEN and the next steps)",(c)=>c.positional("dir",{type:"string",default:Ma,describe:"Folder to create"}).option("name",{type:"string",describe:"Worker name (default: the folder's name)"}).option("force",{type:"boolean",default:!1,describe:"Overwrite files that already exist"}).option("slack-hub",{type:"string",describe:"slack-hub dependency spec (default: this CLI's version), e.g. latest or file:../slack-hub"}),(c)=>{let d=Mf(c.dir,{force:c.force,...c.name!==void 0?{name:c.name}:{},...c["slack-hub"]!==void 0?{slackHub:c["slack-hub"]}:{}});if(!d.ok){console.error(`slack relay init: ${d.error}`);for(let p of d.existing??[])console.error(` exists: ${p}`);process.exit(2)}console.log(Bf(d))}).command("health","GET /health on the relay (SLACK_RELAY_URL / SLACK_RELAY_TOKEN); exit 0 = ok",(c)=>c.option("url",{type:"string",describe:"Relay URL (default: $SLACK_RELAY_URL)"}).option("token",{type:"string",describe:"Relay token (default: $SLACK_RELAY_TOKEN)"}),async(c)=>{let d=await jf(c.url??process.env.SLACK_RELAY_URL,c.token??process.env.SLACK_RELAY_TOKEN);(d.code===0?console.log:console.error)(d.out),process.exit(d.code)}).demandCommand(1,"Specify a relay subcommand (init, health)")).command("stream","Print every new message matching --grep, across all channels the identity is in (threads included); resumable",(a)=>a.option("grep",{alias:"e",type:"string",demandOption:!0,describe:"Regex matched against each message's text (raw, e.g. <@U00000001>). Non-matching messages are never printed or logged"}).option("ignore-case",{alias:"i",type:"boolean",default:!1,describe:"Case-insensitive --grep"}).option("channel",{type:"array",string:!0,describe:"Only these channels (#name, id or permalink); repeatable"}).option("replies-to",{type:"array",string:!0,describe:"Also print replies in threads this id started or replied in (user U\u2026/bot B\u2026; `self` = the streaming identity), --grep or not; repeatable"}).option("json",{type:"boolean",default:!1,describe:"One JSON object per match: type, channel{id,name}, ts, thread_ts, user{id,name}, text, permalink, match (grep | replies-to)"}).option("once",{type:"boolean",default:!1,describe:"Scan once from the saved cursor (or --since) and exit: 0 = matches printed, 2 = none, 3 = failure"}).option("since",{type:"string",describe:"Replay from this long ago (e.g. 30m, 2h), ignoring the saved cursor"}).option("interval",{type:"string",default:"45s",describe:"Poll interval (e.g. 30s, 2m)"}).option("thread-window",{type:"string",default:"3d",describe:"Watch replies in threads whose parent is at most this old"}).option("thread-scan",{type:"string",default:"3m",describe:"Polling: re-read each channel's whole --thread-window this often (cycles in between read only what is new)"}).option("calls-per-min",{type:"number",default:40,describe:"Polling: pace conversations.history/replies to this many calls per minute (0 = unpaced)"}).option("state",{type:"string",describe:"Cursor file (default: one per identity+grep+channels under $XDG_STATE_HOME/slack-hub/stream/)"}).option("as-user",{type:"boolean",default:!1,describe:"Stream as the user identity (sees the user's DMs) instead of the bot"}).option("relay",{type:"boolean",default:!0,describe:"Use the doorbell relay (`slack relay init`) when SLACK_RELAY_URL and SLACK_RELAY_TOKEN are set; --no-relay polls only"}).option("reconcile",{type:"string",default:"5m",describe:"While the relay is connected, poll this rarely as a safety net"}).option("inbox",{type:"boolean",default:!1,describe:"Also write each match into the inbox/ of every .slack-hub/ that subscribes its thread (redacted, text-only)"}).option("reactions",{type:"boolean",default:!1,describe:'Relay only: also print reaction_added bells as {type: "reaction", channel, ts, user} (the emoji: reactions.get)'}),async(a)=>{let c,d,p,h,g,y;try{c=new RegExp(a.grep,a["ignore-case"]?"i":""),p=on(a.interval)*1000,h=on(a["thread-window"]),g=on(a["thread-scan"]),y=a.since!==void 0?on(a.since):void 0,d=on(a.reconcile)*1000}catch(z){console.error(`slack stream: ${z instanceof Error?z.message:String(z)}`),process.exit(1)}let m=Ne(),w=a["as-user"]===!0||!m,k=w?t(a):m,_=w?n(a):void 0;if(!m&&a["as-user"]!==!0)console.error("slack stream: no bot token (SLACK_BOT_TOKEN) \u2014 streaming as the USER identity, which includes its DMs.");let D;try{D=await Ut(k,_)}catch(z){console.error(`slack stream: fatal: ${z instanceof Error?z.message:String(z)}`),process.exit(3)}let E=new Set([D.userId].filter(Boolean)),S=new Set([D.botId].filter(Boolean));if(w&&m)try{let z=await Ut(m);if(z.userId)E.add(z.userId);if(z.botId)S.add(z.botId)}catch{}let x;if(a["replies-to"]?.length){x=new Set;for(let z of a["replies-to"].map(String)){if(z==="self"){for(let Y of[D.userId,D.botId])if(Y)x.add(Y);continue}if(!/^[UWB][A-Z0-9]{2,}$/.test(z))console.error(`slack stream: --replies-to: "${z}" is not a user or bot id (U\u2026/W\u2026/B\u2026) or "self"`),process.exit(1);if(x.add(z),z.startsWith("B"))try{let{userId:Y}=await Bh(k,z,_);if(Y)x.add(Y)}catch(Y){console.error(`slack stream: --replies-to ${z}: cannot resolve its bot user id (${Y instanceof Error?Y.message:String(Y)}); threads where it shows as a user id are missed`)}}}let F;if(a.channel?.length)try{F=[];for(let z of a.channel)F.push(await we(k,String(z),_))}catch(z){console.error(`slack stream: --channel: ${z instanceof Error?z.message:String(z)}`),process.exit(1)}let R=bm("sha256").update(JSON.stringify([D.url,D.userId,c.source,c.flags,[...F??[]].sort(),...a["replies-to"]?.length?[[...a["replies-to"].map(String)].sort()]:[]])).digest("hex").slice(0,16),I=process.env.XDG_STATE_HOME||mt(zo(),".local","state"),P=a.state??mt(ja(I),"stream",`${R}.json`);console.error(`slack stream: as ${w?"user":"bot"} @${D.user} (${D.userId}); state ${P}`);let L=process.env.SLACK_RELAY_URL,W=process.env.SLACK_RELAY_TOKEN,N=a.relay&&!w&&!a.once&&L&&W?{url:L,subscribe:Pa(L,W,void 0,{transport:va(process.env.SLACK_RELAY_TRANSPORT)}),reconcileMs:d}:void 0;if(a.relay&&w&&L)console.error("slack stream: relay not used with --as-user (it only sees the bot's channels)");let J=!a.relay?"--no-relay":w?L?"--as-user: the relay only rings for the bot's channels":"streaming as the user; the relay serves the bot identity":"SLACK_RELAY_URL / SLACK_RELAY_TOKEN not set",K=new AbortController;process.on("SIGINT",()=>K.abort()),process.on("SIGTERM",()=>K.abort()),Pc(0);let B=await bf(mf(k,_),{grep:c,...x?{repliesTo:x}:{},...F?{channels:F}:{},selfUsers:E,selfBots:S,json:a.json,reactions:a.reactions,...a.inbox?{onMatch:(z,Y)=>{try{let j=[k,_,process.env.SLACK_RELAY_TOKEN].filter((q)=>!!q),ie=Zp({...z,...Y?{files:Y}:{}},void 0,new Date,j);if(ie.length)console.error(`slack stream: delivered ${z.channel.id}:${z.ts} to ${ie.length} inbox(es)`)}catch(j){console.error(`slack stream: inbox delivery failed: ${j instanceof Error?j.message:String(j)}`)}}}:{},once:a.once,...y!==void 0?{sinceSec:y}:{},intervalMs:p,threadWindowSec:h,threadScanSec:g,callsPerMin:a["calls-per-min"],...N?{}:{pollReason:J},statePath:P,teamUrl:D.url,identity:D.userId,signal:K.signal,...N?{relay:N}:{}});process.exit(B)}).command("tail [target]","Stream new messages in real time (like tail -f)",(a)=>a.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(a)=>{let c=t(a),d=n(a),p=new AbortController;process.on("SIGINT",()=>{p.abort(),process.exit(0)}),await uf(c,a.target,{...a.since!==void 0?{since:a.since}:{},...a.thread!==void 0?{thread:a.thread}:{},...a["watch-thread"]!==void 0?{watchThread:a["watch-thread"]}:{},me:a.me,interval:a.interval,...a.timeout!==void 0?{timeout:a.timeout}:{},...a["exit-on-message"]===!0?{exitOnMessage:!0}:{},...d!==void 0?{cookie:d}:{},...a.rtm===!1?{noRtm:!0}:{}},p.signal)}).command("login",!1,(a)=>a.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(a)=>{await Us({...a.token!==void 0?{token:a.token}:{},...a.name!==void 0?{name:a.name}:{},yes:a.yes,fromDesktop:a.fromDesktop,fromChrome:a.fromChrome,fromFirefox:a.fromFirefox,fromAll:a.fromAll})}).demandCommand(1,"Specify a command. Run with --help for usage.").strict().help().alias("help","h").parseAsync()}gS().catch((e)=>{console.error(e instanceof Error?e.message:String(e)),process.exit(1)});
590
+ Tip: pass --user-id <Uxxxx> to skip the lookup.`),process.exit(mt)}x=S,_.mentionToken=S,_.asBot=!0}else{x=n(u),_.mentionToken=x;let S=s(u);if(S)_.cookie=S,_.mentionCookie=S}try{await BS(x,_)}catch(S){console.error(ge(S)),process.exit(mt)}}).command("sent [query]","Search what THIS machine posted/edited (send, ask, poll, edit) and who sent it \u2014 read-only, local log",(u)=>u.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)"}),(u)=>{let l;if(u.since!==void 0){if(l=ms(String(u.since)),l===void 0)console.error(`Error: --since needs 30m / 2h / 7d / 1w or an ISO date (got ${W(String(u.since))})`),process.exit(1)}let h={limit:Number(u.count)||50};if(u.query)h.text=String(u.query);if(u.channel)h.channel=String(u.channel);if(l!==void 0)h.sinceMs=l;if(u.session)h.session=String(u.session);if(u.cwd){let b=Rx(String(u.cwd));try{h.cwd=Fx(b)}catch{h.cwd=b}}if(u.kind)h.kind=u.kind;let m=Uc(h);if(!m)console.error(`Error: ${ir}
591
+ (${Pt()})`),process.exit(1);if(u.json){for(let b of m)console.log(JSON.stringify(b));return}if(!m.length){console.error(`No sent messages match (log: ${Pt()}).`);return}for(let b of m)console.log(rS(b))}).command("doctor","Check the bot token (xoxb) can carry a two-way DM (scopes + Messages Tab)",(u)=>u,async()=>{let u=Me();if(!u)console.error(`Error: slack doctor checks the bot token, but no xoxb- token was found.
592
+ Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(1);await US(u)}).command("schedule","Manage scheduled messages",(u)=>u.command("send <target> <message>","Schedule a message for later delivery",(l)=>l.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(l)=>{if(!String(l.message??"").trim())console.error("Error: message is empty"),process.exit(1);let h={target:l.target,message:l.message,at:l.at};if(l.code)h.code=l.code;if(l["allow-url-adjacent"])h.allowUrlAdjacent=!0;if(l["channel-id"])h.channelId=l["channel-id"],h.targetOverride=`--channel-id ${l["channel-id"]}`;if(l["user-id"])h.userId=l["user-id"],h.targetOverride=`--user-id ${l["user-id"]}`;let m;if(l["as-bot"]){let b=br();if(!h.channelId&&!h.userId&&h.target.startsWith("@"))try{h.userId=await Nt(n(l),h.target,s(l))}catch(_){console.error(`Error: could not resolve ${h.target} to a user for the bot DM.
593
+ ${_ instanceof Error?_.message:String(_)}
594
+ Tip: pass --user-id <Uxxxx> to skip the lookup.`),process.exit(1)}m=b,h.asBot=!0}else{m=n(l);let b=s(l);if(b)h.cookie=b}await JS(m,h)}).command(["ls","list"],"List pending scheduled messages",(l)=>l.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(l)=>{let h=l.target;if(l["as-bot"]){let m=br(),b=l["channel-id"];if(!b&&h?.startsWith("@"))b=await Wm(h,m,n(l),s(l));await Jm(m,h,b);return}await Jm(n(l),h,l["channel-id"],s(l))}).command("rm <target> <id>","Delete a scheduled message",(l)=>l.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(l)=>{let h={target:l.target,id:l.id};if(l.code)h.code=l.code;if(l["channel-id"])h.channelId=l["channel-id"],h.targetOverride=`--channel-id ${l["channel-id"]}`;if(l["as-bot"]){let b=br();if(!h.channelId&&h.target.startsWith("@"))h.channelId=await Wm(h.target,b,n(l),s(l));h.asBot=!0,await Km(b,h);return}let m=s(l);if(m)h.cookie=m;await Km(n(l),h)}).demandCommand(1,"").showHelpOnFail(!0),()=>{}).command("edit <target> <newText>","Edit a sent message",(u)=>u.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("force",{type:"boolean",default:!1,describe:"Apply an edit that BREAKS a `slack ask` / `slack poll` message (new text no longer reads as one, or an answered/void question made open again). Refused by default because collect reads that body back; edits that keep it readable (e.g. writing the \u2705 form) need no flag. Prefer `slack ask --edit=` / `--void=`."}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing ambiguous bare URL boundaries"}).option("fix-urls",{type:"boolean",default:!1,describe:"Wrap ambiguous bare URLs as <url> (cut at the first non-ASCII character / trailing punctuation) before sending"}).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(u)=>o(u)).command("tick <target> [n]","Tick item n of a posted checklist (\u2B1C n. \u2192 \u2705 n.), nothing else changed; without n, the one open item (confirm-hash gate, like edit)",(u)=>u.positional("target",{type:"string",demandOption:!0,describe:"#chan:ts, @user:ts, or permalink"}).positional("n",{type:"number",describe:"Item number"}).option("code",{type:"string",describe:"Safety hash to confirm the edit"}).option("channel-id",{type:"string",describe:"Raw channel ID"}).option("as-bot",{type:"boolean",default:!1,describe:"Edit as the bot (needed for a message the bot posted)"}),async(u)=>o({...u,tick:u.n!==void 0?{n:u.n}:{},mentions:!1})).command("delete <target>","Delete a sent message (confirm-hash safety gate)",(u)=>u.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(u)=>{let l={target:u.target};if(u.code)l.code=u.code;if(u["channel-id"])l.channelId=u["channel-id"];let h;if(u["as-bot"]){let m=await vm(l.target,n(u),s(u),l.channelId);if(h=m.botToken,m.channelId&&!l.channelId)l.channelId=m.channelId;l.asBot=!0}else{h=n(u);let m=s(u);if(m)l.cookie=m}await cS(h,l)}).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)",(u)=>{let l={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."},h=async(b)=>{if(b["as-bot"]){let x=br();if(typeof b.workspace==="string"){let S=s(b),[E,I]=await Promise.all([Ct(n(b),S),Ct(x)]);if(E.url!==I.url)console.error(`Error: --as-bot acts with SLACK_BOT_TOKEN, which belongs to ${I.url}, but -w ${b.workspace} is ${E.url}.
595
+ Drop -w, or set SLACK_BOT_TOKEN to that workspace's bot token.`),process.exit(2)}return{token:x,asBot:!0}}let _=s(b);return{token:n(b),..._?{cookie:_}:{},asBot:!1}},m=(b)=>{console.error(ge(b)),process.exit(1)};return u.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)",(b)=>b.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",l).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(b)=>{let _=b.file!==void 0;if(_&&b.state!==void 0&&b.reason!==void 0)console.error("Error: with --file, pass only the reason after <channel> (the state comes from the file)."),process.exit(2);let x=_?si(void 0,b.file):si(b.state,void 0),S=_?b.state:b.reason;if(x===void 0)console.error("Error: the state is required (positional or --file)."),process.exit(2);let E=await h(b),I={target:b.channel,state:x,asBot:E.asBot,allowUrlAdjacent:b["allow-url-adjacent"]};if(S!==void 0)I.log=Ue(S);if(E.cookie)I.cookie=E.cookie;if(typeof b.workspace==="string")I.workspace=b.workspace;if(b.code)I.code=b.code;await uS(E.token,I).catch(m)}).command("set <board> [state] [reason]","Change a board: replace its state (silent edit) AND post the reason in its thread (notifies)",(b)=>b.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",l).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(b)=>{let _=b.file!==void 0;if(_&&b.state!==void 0&&b.reason!==void 0)console.error("Error: with --file, pass only the reason after <board> (the state comes from the file)."),process.exit(2);let x=_?si(void 0,b.file):si(b.state,void 0),S=_?b.state:b.reason;if(x===void 0||S===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 E=await h(b),I={target:b.board,state:x,log:Ue(S),adopt:b.adopt,asBot:E.asBot,allowUrlAdjacent:b["allow-url-adjacent"]};if(typeof b.workspace==="string")I.workspace=b.workspace;if(E.cookie)I.cookie=E.cookie;if(b.code)I.code=b.code;await Lm(E.token,I).catch(m)}).command("note <board> <reason>","Post only a reason in a board's thread (notifies); the state stays as is",(b)=>b.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",l),async(b)=>{let _=await h(b),x={target:b.board,log:Ue(b.reason),logOnly:!0,asBot:_.asBot,allowUrlAdjacent:b["allow-url-adjacent"]};if(typeof b.workspace==="string")x.workspace=b.workspace;if(_.cookie)x.cookie=_.cookie;if(b.code)x.code=b.code;await Lm(_.token,x).catch(m)}).command(["get <board>","show <board>"],"Show a board's state and its log (read-only)",(b)=>b.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",l),async(b)=>{let _=await h(b);await pS(_.token,b.board,_.cookie,b.json).catch(m)}).command(["ls <channel>","list <channel>"],"List the boards in a channel, found by their footer (read-only)",(b)=>b.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",l),async(b)=>{let _=await h(b);await hS(_.token,b.channel,b.limit,_.cookie).catch(m)}).command("pin <board>",!1,(b)=>b.positional("board",{type:"string",demandOption:!0}).option("as-bot",l),async(b)=>{let _=await h(b);await gS(_.token,b.board,_.cookie).catch(m)}).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",(u)=>u.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(u)=>{let l={target:u.target,emoji:u.emoji};if(u.remove)l.remove=!0;if(u["channel-id"])l.channelId=u["channel-id"];let h=s(u);if(h)l.cookie=h;try{await mS(n(u),l)}catch(m){console.error(ge(m)),process.exit(1)}}).command("todo","Reaction-backed task tracking (:pushpin: marks a task, progress lives in a second reaction)",(u)=>u.option("cache",{type:"boolean",default:!0,describe:"Use ~/.config/slack-cli/cache.json for channel/user lookups (--no-cache to bypass)"}).middleware((l)=>{if(l.cache===!1)ml(!1)}).command(["ls","list"],"List everyone's tasks (has: \u2014 read-only, one search per run)",(l)=>l.options(a).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(l)=>{await c(l,!1)}).command("set <target> <state>","Move a task to a progress state (adds the new reaction before removing the old one)",(l)=>l.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(l)=>{let h={target:l.target,state:l.state};if(l["channel-id"])h.channelId=l["channel-id"];let m=s(l);if(m)h.cookie=m;try{await Hx(n(l),h)}catch(b){console.error(ge(b)),process.exit(1)}}).command("flag <target> <flag>","Add (or --remove) a reason flag (alert | needs-discussion | waiting | blocked) \u2014 flags stack, independent of progress",(l)=>l.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(l)=>{let h={target:l.target,flag:l.flag};if(l.remove)h.remove=!0;if(l["channel-id"])h.channelId=l["channel-id"];let m=s(l);if(m)h.cookie=m;try{await zx(n(l),h)}catch(b){console.error(ge(b)),process.exit(1)}}).command("doctor","Find messages carrying two or more progress reactions (--fix repairs them)",(l)=>l.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:gl,describe:"Max messages to scan"}).option("channel-id",{type:"string",describe:"Raw channel ID"}),async(l)=>{let h={channel:l.in,limit:l.limit};if(l.fix)h.fix=!0;if(l["channel-id"])h.channelId=l["channel-id"];let m=s(l);if(m)h.cookie=m;await Yx(n(l),h)}).demandCommand(1,"Specify a todo subcommand (ls, set, flag, doctor)"),()=>{}).command("mytodo","Tasks carrying YOUR reactions (hasmy:) \u2014 the my-only half of `todo`",(u)=>u.option("cache",{type:"boolean",default:!0,describe:"Use ~/.config/slack-cli/cache.json for channel/user lookups (--no-cache to bypass)"}).middleware((l)=>{if(l.cache===!1)ml(!1)}).command(["ls","list"],"List tasks you have reacted to (hasmy: \u2014 read-only, one search per run)",(l)=>l.options(a),async(l)=>{await c(l,!0)}).demandCommand(1,"Specify a mytodo subcommand (ls)"),()=>{}).command("upload <target> <file..>","Upload one or more files to a channel or DM",(u)=>u.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"}).option("as-bot",{type:"boolean",default:!1,describe:"Upload via the bot token (xoxb / SLACK_BOT_TOKEN); `slack @bot upload \u2026` does this too"}),async(u)=>{let l={target:u.target,filePaths:u.file};if(u.title)l.title=u.title;if(u.comment)l.comment=u.comment;if(u["allow-url-adjacent"])l.allowUrlAdjacent=!0;if(u.code)l.code=u.code;if(u["channel-id"])l.channelId=u["channel-id"];if(u["user-id"])l.userId=u["user-id"];if(u["as-bot"]){let m=Me();if(!m)console.error("Error: --as-bot needs a bot token (SLACK_BOT_TOKEN)"),process.exit(1);await qm(m,l);return}let h=s(u);if(h)l.cookie=h;await qm(n(u),l)}).command("files","File commands",(u)=>u.command(["ls","list"],"List files visible to you (files.list)",(l)=>l.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(l)=>{let h={limit:l.limit,format:l.json?"jsonl":l.format};if(l.type)h.types=l.type;if(l.channel)h.channel=l.channel;if(l.user)h.user=l.user;await KS(n(l),s(l),h)}).demandCommand(1,"").showHelpOnFail(!0),()=>{}).command("lists","Slack Lists \u2014 read rows (lists <ref>), or create / add / set (gated, as the bot)",(u)=>u.command("create <name>","Create a Slack List (confirm-hash safety gate; bot token, lists:write)",(l)=>l.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(l)=>{try{let h={name:l.name,cols:l.col,todo:l.todo===!0};if(l.code!==void 0)h.code=l.code;await YS(h)}catch(h){console.error(ge(h)),process.exit(1)}}).command("add <list> <text>","Add a row to a Slack List (confirm-hash safety gate; bot token)",(l)=>l.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(l)=>{try{let h={list:l.list,text:l.text,sets:l.set};if(l.code!==void 0)h.code=l.code;await GS(h)}catch(h){console.error(ge(h)),process.exit(1)}}).command("set <list> <row>","Update cells of a Slack List row; --done checks it off (confirm-hash safety gate; bot token)",(l)=>l.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(l)=>{try{let h={list:l.list,row:l.row,sets:l.set};if(l.done!==void 0)h.done=l.done;if(l.code!==void 0)h.code=l.code;await XS(h)}catch(h){console.error(ge(h)),process.exit(1)}}).command("share <list>","Grant users or channels access to a Slack List (confirm-hash safety gate; bot token)",(l)=>l.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(l)=>{try{let h={list:l.list,users:l.user,channels:l.channel,level:l.level};if(l.code!==void 0)h.code=l.code;await VS(h)}catch(h){console.error(ge(h)),process.exit(1)}}).command("$0 <ref>","Read a Slack List's rows (by list URL or F-id) \u2014 read-only",(l)=>l.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(l)=>{let h=l.json?"jsonl":l.format;try{let m=l.asBot===!0;await HS(m?"":n(l),m?void 0:s(l),l.ref,{limit:l.limit,format:h,asBot:m})}catch(m){console.error(ge(m)),process.exit(1)}})).command("download <ref> [dest]","Download a file attachment (by file ID or file permalink) to disk",(u)=>u.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(u)=>{await QS(n(u),s(u),u.ref,u.dest)}).command("dump","Bulk export channel history as markdown",(u)=>u.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(u)=>{await Gx(n(u),u.days,u.limit,u.filter)}).command("todos","Slack's To-dos tab \u2014 your personal to-dos (requires xoxc desktop token). Not `slack todo` (reaction tasks)",(u)=>u.command(["$0","ls","list"],"List your To-dos, soonest due first",(l)=>l.option("filter",{type:"string",choices:[...zg],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(l)=>{if(!Number.isInteger(l.limit)||l.limit<1)console.error(`Error: --limit must be a whole number of at least 1 (got ${l.limit}).`),process.exit(2);await Zx(n(l),s(l),{filter:l.filter,limit:l.limit,json:l.json})}).command("add <target>","Add a message to your To-dos (two-step: preview, then --code)",(l)=>l.positional("target",{type:"string",demandOption:!0,describe:"Message permalink or #chan:<ts>"}).option("due",{type:"string",describe:"Due time (ISO datetime or Unix ts)"}).option("saved",{type:"boolean",default:!1,describe:"Save it without a checkbox instead of as a to-do"}).option("code",{type:"string",describe:"Confirmation code from the preview"}),async(l)=>{let h=l.due===void 0?void 0:Um(l.due);await ni(n(l),s(l),l.target,{kind:"add",...h?{due:h}:{},saved:l.saved},l.code)}).command(["done <target>","complete <target>"],"Check a to-do off (--undo reopens it)",(l)=>l.positional("target",{type:"string",demandOption:!0,describe:"Message permalink or #chan:<ts>"}).option("undo",{type:"boolean",default:!1,describe:"Mark it not done again"}).option("code",{type:"string",describe:"Confirmation code from the preview"}),async(l)=>{await ni(n(l),s(l),l.target,{kind:"done",undo:l.undo},l.code)}).command("edit <target>","Change a to-do's due date, or switch it between to-do and saved item",(l)=>l.positional("target",{type:"string",demandOption:!0,describe:"Message permalink or #chan:<ts>"}).option("due",{type:"string",describe:"New due time (ISO datetime or Unix ts), or `none` to clear it"}).option("todo",{type:"boolean",describe:"Make it a to-do (with a checkbox)"}).option("saved",{type:"boolean",describe:"Make it a plain saved item (no checkbox)"}).conflicts("todo","saved").option("code",{type:"string",describe:"Confirmation code from the preview"}),async(l)=>{let h=l.due===void 0?void 0:l.due==="none"?0:Um(l.due),m=l.todo?!0:l.saved?!1:void 0;await ni(n(l),s(l),l.target,{kind:"edit",...h===void 0?{}:{due:h},...m===void 0?{}:{todo:m}},l.code)}).command(["rm <target>","remove <target>","delete <target>"],"Remove a message from your To-dos (the message stays)",(l)=>l.positional("target",{type:"string",demandOption:!0,describe:"Message permalink or #chan:<ts>"}).option("code",{type:"string",describe:"Confirmation code from the preview"}),async(l)=>{await ni(n(l),s(l),l.target,{kind:"rm"},l.code)})).command("drafts","Manage message drafts (requires xoxc desktop token)",(u)=>u.command(["$0","ls","list"],"List pending drafts",(l)=>l.option("all",{alias:"a",type:"boolean",default:!1,describe:"Include sent drafts"}),async(l)=>{await Vx(n(l),s(l),l.all)}).command(["new <channel> [text..]","save <channel> [text..]"],"Create a draft",(l)=>l.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(l)=>{let h=n(l),m=s(l),b=l.text.join(" ");if(!b)console.error("Usage: slack drafts new <#channel|@user> <text>"),process.exit(2);He(b,l["allow-url-adjacent"],void 0,{sides:["after"],markdown:!1});let _=await we(h,l.channel,m),x=await jg(h,_,b,m);console.log(`\u2713 Draft created (id: ${L(x.draft).id??"?"})`)}).command("get <id>","Show a draft",(l)=>l.positional("id",{type:"string",demandOption:!0}),async(l)=>{await nS(n(l),s(l),l.id)}).command(["edit <id> [text..]","update <id> [text..]"],"Edit a draft",(l)=>l.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(l)=>{let h=n(l),m=s(l),b=l.text.join(" ");if(!b)console.error("Usage: slack drafts edit <id> <new-text>"),process.exit(2);He(b,l["allow-url-adjacent"],void 0,{sides:["after"],markdown:!1});let _=await dr(h,m),x=G(_.drafts).map(L).find((C)=>String(C.id)===l.id);if(!x)console.error(`Draft not found: ${l.id}`),process.exit(1);let S=ai(x),E=await je(h,m),I=De(S,b,E?.userId??"");if(l.code!==I)Se(l.code,I,["--- Editing draft as -------------------------",Ee(E),"--- Current draft ----------------------------",...S.split(`
596
+ `).map((C)=>` ${C}`),"--- Replacing with ---------------------------",...b.split(`
597
+ `).map((C)=>` ${C}`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);let N=await Wg(h,l.id,Bl(x),b,m);console.log(`\u2713 Draft updated (id: ${L(N.draft).id??"?"})`)}).command(["delete <id>","rm <id>"],"Delete a draft",(l)=>l.positional("id",{type:"string",demandOption:!0}).option("code",{type:"string"}),async(l)=>{let h=n(l),m=s(l),b=await dr(h,m),_=G(b.drafts).map(L).find((I)=>String(I.id)===l.id);if(!_)console.error(`Draft not found: ${l.id}`),process.exit(1);let x=ai(_),S=await je(h,m),E=De(l.id,x,S?.userId??"");if(l.code!==E)Se(l.code,E,["\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",Ee(S),` id: ${l.id}`,...x.split(`
598
+ `).map((I)=>` ${I}`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);await Kg(h,l.id,m),console.log(`\u2713 Draft deleted (id: ${l.id})`)})).command("auth","Authentication and workspace management",(u)=>u.command("token","Print the active token (or save one with --token)",(l)=>l.option("token",{type:"string",describe:"Token to save directly (non-interactive)"}).option("name",{type:"string",describe:"Workspace name (used with --token)"}),async(l)=>{if(l.token===void 0){console.log(Ls(l.workspace));return}await _f({...l.token!==void 0?{token:l.token}:{},...l.name!==void 0?{name:l.name}:{}})}).command("env","Print active workspace credentials in dotenv format",()=>{},(l)=>{let h=Ls(l.workspace),m=h.startsWith("xoxc-")?ra(l.workspace):void 0,b=[["SLACK_TOKEN",h]];if(m)b.push(["SLACK_COOKIE",m]);let _=b.map(([x,S])=>{if(/[\r\n\0']/.test(S))throw Error(`Cannot export ${x}: unsupported characters in credential`);return`${x}='${S}'`});console.log(_.join(`
599
+ `))}).command("app","Create a new Slack app and obtain a token (guided wizard)",(l)=>l.option("bot",{type:"boolean",describe:"Create a bot token (xoxb-) instead of user (xoxp-)"}),async(l)=>{await Ef({...l.bot!==void 0?{bot:l.bot}:{}})}).command("login","Log in: interactive wizard, or a source (chrome, firefox)",(l)=>l.command("chrome","Import workspaces from Chrome, grouped by account (all platforms)",(h)=>h.option("profile",{type:"string",alias:"p",describe:'Chrome profile email or dir (e.g. "you@example.com" or "Profile 3")'}),async(h)=>{await Pa({...h.profile!==void 0?{profile:h.profile}:{}})}).command("firefox","Import the xoxd cookie from Firefox into a workspace",(h)=>h.option("workspace",{type:"string",alias:"w",describe:"Workspace name to update (default: active)"}),async(h)=>{await La({...h.workspace!==void 0?{workspace:h.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(h)=>{await Ys({...h.token!==void 0?{token:h.token}:{},...h.name!==void 0?{name:h.name}:{},yes:h.yes,fromDesktop:h.fromDesktop,fromChrome:h.fromChrome,fromFirefox:h.fromFirefox,fromAll:h.fromAll})}),async(l)=>{await Ys({...l.token!==void 0?{token:l.token}:{},...l.name!==void 0?{name:l.name}:{},yes:l.yes,fromDesktop:l.fromDesktop,fromChrome:l.fromChrome,fromFirefox:l.fromFirefox,fromAll:l.fromAll})}).command("tokens","Print the selected credentials as dotenv assignments",(l)=>l.option("workspace",{type:"string",alias:"w",describe:"Workspace name (default: active)"}),(l)=>$f({...l.workspace!==void 0?{workspace:l.workspace}:{}})).command("save","Save the active profile token and cookie to an env file",(l)=>l.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)"}),(l)=>Cf({envfile:l.envfile,...l.workspace!==void 0?{workspace:l.workspace}:{}})).command(["ls","status"],"Show auth status",()=>{},()=>{let l=sa();if(l.length===0){console.log("No workspaces configured. Run: slack auth login");return}for(let{name:h,profile:m,current:b}of l)console.log(`${b?"* ":" "}${h} ${m.team} (${m.user}) ${m.url??""}`)}).command("use <name>","Switch active workspace",(l)=>l.positional("name",{type:"string",demandOption:!0}).option("g",{type:"boolean",default:!1,describe:"Write global lockfile (~/.slack-cli/workspace)"}),(l)=>{if(!l.g)vx(yt(process.cwd(),".slack-cli"));Ld(l.name,l.g),console.log(`Switched to workspace "${l.name}" ${l.g?"globally":"locally"}`)}).command(["logout <name>","rm <name>","remove <name>"],"Remove a workspace",(l)=>l.positional("name",{type:"string",demandOption:!0}),(l)=>{Pd(l.name),console.log(`Removed workspace "${l.name}"`)}).command(["cookie","chrome"],"Attach a Chrome xoxd cookie to a workspace (macOS/Linux/Windows). To import workspaces, use: slack auth login chrome",(l)=>l.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(l)=>{await Sf({...l.workspace!==void 0?{workspace:l.workspace}:{},...l.profile!==void 0?{profile:l.profile}:{},yes:l.yes})}).command("firefox","Attach Firefox browser xoxd cookie to a workspace (all platforms)",(l)=>l.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(l)=>{await La({...l.workspace!==void 0?{workspace:l.workspace}:{},yes:l.yes})}).command("$0",!1,()=>{},()=>{u.showHelp(),process.exit(0)})).command("relay","Set up / check the real-time relay for `slack stream` (a Cloudflare Worker)",(u)=>u.command("init [dir]","Scaffold a deployable relay Worker folder (local files only; prints a fresh RELAY_TOKEN and the next steps)",(l)=>l.positional("dir",{type:"string",default:Xa,describe:"Folder to create"}).option("name",{type:"string",describe:"Worker name (default: the folder's name)"}).option("force",{type:"boolean",default:!1,describe:"Overwrite files that already exist"}).option("slack-hub",{type:"string",describe:"slack-hub dependency spec (default: this CLI's version), e.g. latest or file:../slack-hub"}),(l)=>{let h=ap(l.dir,{force:l.force,...l.name!==void 0?{name:l.name}:{},...l["slack-hub"]!==void 0?{slackHub:l["slack-hub"]}:{}});if(!h.ok){console.error(`slack relay init: ${h.error}`);for(let m of h.existing??[])console.error(` exists: ${m}`);process.exit(2)}console.log(cp(h))}).command("health","GET /health on the relay (SLACK_RELAY_URL / SLACK_RELAY_TOKEN); exit 0 = ok",(l)=>l.option("url",{type:"string",describe:"Relay URL (default: $SLACK_RELAY_URL)"}).option("token",{type:"string",describe:"Relay token (default: $SLACK_RELAY_TOKEN)"}),async(l)=>{let h=await lp(l.url??process.env.SLACK_RELAY_URL,l.token??process.env.SLACK_RELAY_TOKEN);(h.code===0?console.log:console.error)(h.out),process.exit(h.code)}).demandCommand(1,"Specify a relay subcommand (init, health)")).command("stream","Print every new message matching --grep, across all channels the identity is in (threads included); resumable",(u)=>u.option("grep",{alias:"e",type:"string",demandOption:!0,describe:"Regex matched against each message's text (raw, e.g. <@U00000001>). Non-matching messages are never printed or logged"}).option("ignore-case",{alias:"i",type:"boolean",default:!1,describe:"Case-insensitive --grep"}).option("channel",{type:"array",string:!0,describe:"Only these channels (#name, id or permalink); repeatable"}).option("replies-to",{type:"array",string:!0,describe:"Also print replies in threads this id started or replied in (user U\u2026/bot B\u2026; `self` = the streaming identity), --grep or not; repeatable"}).option("json",{type:"boolean",default:!1,describe:"One JSON object per match: type, channel{id,name}, ts, thread_ts, user{id,name}, text, permalink, match (grep | replies-to)"}).option("once",{type:"boolean",default:!1,describe:"Scan once from the saved cursor (or --since) and exit: 0 = matches printed, 2 = none, 3 = failure"}).option("since",{type:"string",describe:"Replay from this long ago (e.g. 30m, 2h), ignoring the saved cursor"}).option("interval",{type:"string",default:"45s",describe:"Poll interval (e.g. 30s, 2m)"}).option("thread-window",{type:"string",default:"3d",describe:"Watch replies in threads whose parent is at most this old"}).option("thread-scan",{type:"string",default:"3m",describe:"Polling: re-read each channel's whole --thread-window this often (cycles in between read only what is new)"}).option("calls-per-min",{type:"number",default:40,describe:"Polling: pace conversations.history/replies to this many calls per minute (0 = unpaced)"}).option("state",{type:"string",describe:"Cursor file (default: one per identity+grep+channels under $XDG_STATE_HOME/slack-hub/stream/)"}).option("as-user",{type:"boolean",default:!1,describe:"Stream as the user identity (sees the user's DMs) instead of the bot"}).option("relay",{type:"boolean",default:!0,describe:"Use the doorbell relay (`slack relay init`) when SLACK_RELAY_URL and SLACK_RELAY_TOKEN are set; --no-relay polls only"}).option("reconcile",{type:"string",default:"5m",describe:"While the relay is connected, poll this rarely as a safety net"}).option("inbox",{type:"boolean",default:!1,describe:"Also write each match into the inbox/ of every .slack-hub/ that subscribes its thread (redacted, text-only)"}).option("reactions",{type:"boolean",default:!1,describe:'Relay only: also print reaction_added bells as {type: "reaction", channel, ts, user} (the emoji: reactions.get)'}),async(u)=>{let l,h,m,b,_,x;try{l=new RegExp(u.grep,u["ignore-case"]?"i":""),m=an(u.interval)*1000,b=an(u["thread-window"]),_=an(u["thread-scan"]),x=u.since!==void 0?an(u.since):void 0,h=an(u.reconcile)*1000}catch(z){console.error(`slack stream: ${z instanceof Error?z.message:String(z)}`),process.exit(1)}let S=Me(),E=u["as-user"]===!0||!S,I=E?n(u):S,N=E?s(u):void 0;if(!S&&u["as-user"]!==!0)console.error("slack stream: no bot token (SLACK_BOT_TOKEN) \u2014 streaming as the USER identity, which includes its DMs.");let C;try{C=await Ct(I,N)}catch(z){console.error(`slack stream: fatal: ${z instanceof Error?z.message:String(z)}`),process.exit(3)}let A=new Set([C.userId].filter(Boolean)),F=new Set([C.botId].filter(Boolean));if(E&&S)try{let z=await Ct(S);if(z.userId)A.add(z.userId);if(z.botId)F.add(z.botId)}catch{}let v;if(u["replies-to"]?.length){v=new Set;for(let z of u["replies-to"].map(String)){if(z==="self"){for(let K of[C.userId,C.botId])if(K)v.add(K);continue}if(!/^[UWB][A-Z0-9]{2,}$/.test(z))console.error(`slack stream: --replies-to: "${z}" is not a user or bot id (U\u2026/W\u2026/B\u2026) or "self"`),process.exit(1);if(v.add(z),z.startsWith("B"))try{let{userId:K}=await pg(I,z,N);if(K)v.add(K)}catch(K){console.error(`slack stream: --replies-to ${z}: cannot resolve its bot user id (${K instanceof Error?K.message:String(K)}); threads where it shows as a user id are missed`)}}}let O;if(u.channel?.length)try{O=[];for(let z of u.channel)O.push(await we(I,String(z),N))}catch(z){console.error(`slack stream: --channel: ${z instanceof Error?z.message:String(z)}`),process.exit(1)}let M=Hm("sha256").update(JSON.stringify([C.url,C.userId,l.source,l.flags,[...O??[]].sort(),...u["replies-to"]?.length?[[...u["replies-to"].map(String)].sort()]:[]])).digest("hex").slice(0,16),J=process.env.XDG_STATE_HOME||yt(ri(),".local","state"),j=u.state??yt(Za(J),"stream",`${M}.json`);console.error(`slack stream: as ${E?"user":"bot"} @${C.user} (${C.userId}); state ${j}`);let ee=process.env.SLACK_RELAY_URL,X=process.env.SLACK_RELAY_TOKEN,U=u.relay&&!E&&!u.once&&ee&&X?{url:ee,subscribe:Ha(ee,X,void 0,{transport:qa(process.env.SLACK_RELAY_TRANSPORT)}),reconcileMs:h}:void 0;if(u.relay&&E&&ee)console.error("slack stream: relay not used with --as-user (it only sees the bot's channels)");let ie=!u.relay?"--no-relay":E?ee?"--as-user: the relay only rings for the bot's channels":"streaming as the user; the relay serves the bot identity":"SLACK_RELAY_URL / SLACK_RELAY_TOKEN not set",q=new AbortController;process.on("SIGINT",()=>q.abort()),process.on("SIGTERM",()=>q.abort()),Xc(0);let ce=await Wf(Bf(I,N),{grep:l,...v?{repliesTo:v}:{},...O?{channels:O}:{},selfUsers:A,selfBots:F,json:u.json,reactions:u.reactions,...u.inbox?{onMatch:(z,K)=>{try{let ne=[I,N,process.env.SLACK_RELAY_TOKEN].filter((Y)=>!!Y),fe=xh({...z,...K?{files:K}:{}},void 0,new Date,ne);if(fe.length)console.error(`slack stream: delivered ${z.channel.id}:${z.ts} to ${fe.length} inbox(es)`)}catch(ne){console.error(`slack stream: inbox delivery failed: ${ne instanceof Error?ne.message:String(ne)}`)}}}:{},once:u.once,...x!==void 0?{sinceSec:x}:{},intervalMs:m,threadWindowSec:b,threadScanSec:_,callsPerMin:u["calls-per-min"],...U?{}:{pollReason:ie},statePath:j,teamUrl:C.url,identity:C.userId,signal:q.signal,...U?{relay:U}:{}});process.exit(ce)}).command("tail [target]","Stream new messages in real time (like tail -f)",(u)=>u.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(u)=>{let l=n(u),h=s(u),m=new AbortController;process.on("SIGINT",()=>{m.abort(),process.exit(0)}),await Rf(l,u.target,{...u.since!==void 0?{since:u.since}:{},...u.thread!==void 0?{thread:u.thread}:{},...u["watch-thread"]!==void 0?{watchThread:u["watch-thread"]}:{},me:u.me,interval:u.interval,...u.timeout!==void 0?{timeout:u.timeout}:{},...u["exit-on-message"]===!0?{exitOnMessage:!0}:{},...h!==void 0?{cookie:h}:{},...u.rtm===!1?{noRtm:!0}:{}},m.signal)}).command("login",!1,(u)=>u.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(u)=>{await Ys({...u.token!==void 0?{token:u.token}:{},...u.name!==void 0?{name:u.name}:{},yes:u.yes,fromDesktop:u.fromDesktop,fromChrome:u.fromChrome,fromFirefox:u.fromFirefox,fromAll:u.fromAll})}).demandCommand(1,"Specify a command. Run with --help for usage.").strict().help().alias("help","h").parseAsync()}e_().catch((e)=>{console.error(e instanceof Error?e.message:String(e)),process.exit(1)});